text
stringlengths
8
6.88M
#ifndef PRIME_CPP #define PRIME_CPP #include <immintrin.h> #include "config.h" #define _XBEGIN_STARTED (~0u) #define _XABORT_EXPLICIT (1 << 0) #define _XABORT_RETRY (1 << 1) #define _XABORT_CONFLICT (1 << 2) #define _XABORT_CAPACITY (1 << 3) #define _XABORT_DEBUG (1 << 4) #define _XABORT_NESTED (1 << 5) int pa_prime(char **addrs, int size) { unsigned ret; if ((ret = _xbegin()) == _XBEGIN_STARTED) { for (int i = 0; i < size; ++i) { *(volatile char *)addrs[i]; } _xend(); return 1; } return 0; } int try_prime(char **addrs, int size, int ntries) { unsigned ret; int nsuccess = 0; for (int i = 0; i < ntries; ++i) { if ((ret = _xbegin()) == _XBEGIN_STARTED) { for (int i = 0; i < size; ++i) { *(volatile char *)addrs[i]; } _xend(); nsuccess ++; } } return nsuccess; } int conflict_test(char ***addrs, int naddr, int ntries) { for (int i = 0; i < ntries; ++i) { if (pa_prime(*addrs, naddr)) { return 0; } } return 1; } #endif
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "TP_ThirdPerson/TP_ThirdPersonCharacter.h" #include "PatrollingGuard.generated.h" /** * */ UCLASS() class SURVIVING_GROUNDS_API APatrollingGuard : public ATP_ThirdPersonCharacter { GENERATED_BODY() public: UPROPERTY(EditAnywhere, Category = "Patrol Points") TArray <AActor*> PatrolPointsCPP; };
/** \file ellipseDetector.cpp \author Débora Ferreira (dfsbora) \author Gildo Rodrigues \date LARC2018 \name ellipseDetector */ #include "ellipseDetector.hpp" void EllipseDetector::run(cv::Mat topImg, cv::Mat greenFrame, PerceptionData *data) { cv::Mat src = topImg.clone(); //Canny Edge Detector cv::Mat canny_output; cv::Canny(greenFrame,canny_output,50,120); //Canny alternative: threshold //cv::threshold(greenFrame, canny_output, 1, 255, CV_THRESH_BINARY); //cv::bitwise_and(canny_output,roi_field,canny_output); //Morphological Transformations cv::dilate(canny_output, canny_output, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)) ); cv::erode(canny_output, canny_output, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3)) ); std::vector<std::vector<cv::Point> > contours; std::vector<cv::RotatedRect> box_vector; std::vector<cv::Vec4i> hierarchy; cv::findContours(canny_output, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE, cv::Point(0, 0)); //cv::findContours(canny_output, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, cv::Point(0, 0)); //cv::findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE, cv::Point(0, 0)); #ifdef DEBUG_PERCEPTION std::cout << "teste 1" << "\n"; cv::imwrite("contours.jpg",canny_output); std::cout << "teste 2" << "\n"; #endif cv::Mat cimage = cv::Mat::zeros(canny_output.size(), CV_8UC3); //Iterates through countours vector for(size_t i = 0; i < contours.size(); i++) { //Excludes countours with less than 6 points size_t count = contours[i].size(); if( count < 6 ) continue; //Creates a rectangle box of a fitted ellipse cv::Mat pointsf; cv::Mat(contours[i]).convertTo(pointsf, CV_32F); cv::RotatedRect box = cv::fitEllipse(pointsf); //Excludes too narrow candidates if ( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*30 ) continue; //Excludes candidates with y position too high or too low on image if (box.center.y > (0.3687*box.size.height + 121.2 +20)) continue; if (box.center.y < (0.3687*box.size.height + 121.2 - 20)) continue; //Excludes too small candidates if ((box.size.height) < 100) //Menor largura que assume : 110px continue; //Push back the candidate box_vector.push_back(box); #ifdef DEBUG_PERCEPTION cv::drawContours(cimage, contours, (int)i, cv::Scalar::all(255), 1, 8); cv::ellipse(cimage, box, cv::Scalar(0,0,255), 1, CV_AA); cv::ellipse(cimage, box.center, box.size*0.5f, box.angle, 0, 360, cv::Scalar(0,255,255), 1, CV_AA); cv::Point2f vtx[4]; box.points(vtx); for( int j = 0; j < 4; j++ ) cv::line(cimage, vtx[j], vtx[(j+1)%4], cv::Scalar(0,255,0), 1, CV_AA); #endif } this->media.x=0; this->media.y=0; this->media_angle=0; //The center and angle of ellipse is given by the averege between all candidates for (std::vector<cv::RotatedRect>::iterator it = box_vector.begin(); it < box_vector.end(); ++it) { this->media.x += (*it).center.x; this->media.y += (*it).center.y; this->media_angle += (*it).angle; } if (box_vector.size()) { this->media.x = this->media.x/box_vector.size(); this->media.y = this->media.y/box_vector.size(); this->media_angle = this->media_angle/box_vector.size(); } #ifdef DEBUG_PERCEPTION std::cout << "x:" << this->media.x << "\n"; std::cout << "y:" << this->media.y << "\n"; std::cout << "a:" << this->media_angle << "\n"; cv::circle(src,media,4,cv::Scalar(255,0,0),2); cv::imwrite("ellipse.jpg",src); #endif updateData(data); } void EllipseDetector::updateData(PerceptionData *data) { data->ellipseAverage = this->media; data->ellipseAngle = this->media_angle; }
#include <Logger.h> namespace utils { #if LOG_TO_FILE static constexpr const char *s_log_filename = "CoNE3D.log"; #else static constexpr const char *s_log_filename = ""; #endif CLogger::CLogger() noexcept : _log(s_log_filename) { std::ios_base::sync_with_stdio(false); getStream().imbue( std::locale(std::locale(), new std::codecvt_utf8<wchar_t>) ); } CLogger::~CLogger() noexcept { _log.close(); } std::wostream &CLogger::getStream() noexcept { if ( _log.is_open() ) { return _log; } return std::wclog; } void Log(const std::wstring &message, ELogLevel log_level) { if (log_level <= LOG_LEVEL) { std::lock_guard<std::mutex> guard(CLogger::Log()._logSync); std::wostream &log = CLogger::Log().getStream(); switch (log_level) { case ELogLevel::Error: log << L"[ERROR] "; break; case ELogLevel::Warning: log << L"[WARNING] "; break; case ELogLevel::Info: log << L"[INFO] "; break; case ELogLevel::Debug: log << L"[DEBUG] "; break; default: break; } log << message << std::endl; log.flush(); log.clear(); } } } // namespace utils
/** * \copyright * (c) 2012 - 2015 E.S.R. Labs GmbH (http://www.esrlabs.com) * All rights reserved. */ #ifndef GPSCONVERTER_H_ #define GPSCONVERTER_H_ #include "commonTypes.h" #include "can/framemgmt/ICANFrameListener.h" #include "can/filter/IntervalFilter.h" namespace can { class CANFrame; class ICANTransceiver; } namespace gps { class IGpsACPusher; class GpsConverter : public can::ICANFrameListener { public: enum { GPS_FRAME_ID = 0x34a }; //NavGps1 GpsConverter(can::ICANTransceiver& transceiver, IGpsACPusher& acPusher); /* ICANFrameListener */ virtual void frameReceived(const can::CANFrame& canFrame); virtual can::IFilter& getFilter() { return fCanFilter; } private: can::ICANTransceiver& fCanTransceiver; can::IntervalFilter fCanFilter; virtual bool checkValid(sint32 value); IGpsACPusher& fAcPusher; sint32 fLastLatInMs; sint32 fLastLongInMs; sint32 longitude; sint32 latitude; }; } // namespace gps #endif /* end of include guard */
 // PortScannerDlg.cpp: 实现文件 // #include "stdafx.h" #include "PortScanner.h" #include "PortScannerDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CPortScannerDlg 对话框 CPortScannerDlg::CPortScannerDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_PORTSCANNER_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CPortScannerDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST, m_CListCtrl); DDX_Text(pDX, IDC_EDIT_STARTINGPORT, m_startingport); DDX_Text(pDX, IDC_EDIT_ENDINGPORT, m_endingport); DDX_Text(pDX, IDC_EDIT_CURPORT, m_curport); DDX_Control(pDX, IDC_IPADDRESS, m_ipaddress); } BEGIN_MESSAGE_MAP(CPortScannerDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON_SCAN, &CPortScannerDlg::OnBnClickedButtonScan) ON_MESSAGE(WM_RECV, OnRecv) ON_MESSAGE(WM_RECV_FAIL, OnRecvFailed) ON_MESSAGE(WM_END, OnEnd) ON_MESSAGE(WM_UPDATE, OnUpdate) END_MESSAGE_MAP() // CPortScannerDlg 消息处理程序 BOOL CPortScannerDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 index = -1; nic.initNIC(); vector<char *> al = nic.getAdapterList(); // don't need select manually // if ip is none GetDlgItem(IDC_BUTTON_SCAN)->EnableWindow(FALSE); // remember start end set false for (vector<char *>::const_iterator iter = al.begin(); iter != al.end(); ++iter) { index++; nic.selectNIC(index); inet_pton(AF_INET, nic.getIPAddress(), &m_srcip); if (m_srcip) { m_srcmac = nic.getMacAddress(); inet_pton(AF_INET, nic.getSubnetMask(), &m_mask); m_gwmac = nic.getGatewayMac(); GetDlgItem(IDC_BUTTON_SCAN)->EnableWindow(TRUE); break; } } UpdateData(FALSE); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CPortScannerDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CPortScannerDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CPortScannerDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CPortScannerDlg::OnBnClickedButtonScan() { // TODO: 在此添加控件通知处理程序代码 if (-1 == index) return; if (!started) { count = 0; started = true; GetDlgItem(IDC_BUTTON_SCAN)->SetWindowText("&Stop"); UpdateData(TRUE); BYTE field[4]; m_ipaddress.GetAddress(field[0], field[1], field[2], field[3]); CString dstip; dstip.Format("%d.%d.%d.%d", field[0], field[1], field[2], field[3]); GetDlgItem(IDC_EDIT_STARTINGPORT)->EnableWindow(FALSE); GetDlgItem(IDC_EDIT_ENDINGPORT)->EnableWindow(FALSE); GetDlgItem(IDC_IPADDRESS)->EnableWindow(FALSE); checked = IsDlgButtonChecked(IDC_CHECK); m_CListCtrl.DeleteAllItems(); m_CListCtrl.InsertItem(count++, "Starting scan"); m_sport = atoi(m_startingport); m_eport = atoi(m_endingport); m_dstip = inet_addr(dstip); if ((m_dstip&m_mask) == (m_srcip&m_mask)) m_dstmac = nic.getLanMac(m_dstip); else m_dstmac = m_gwmac; device.obtainDeviceList(); device.openAdapter(nic.getNICname()); string filter = "tcp"; device.setFilter(filter.c_str()); hThreadrecv = AfxBeginThread(recv, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL); hThreadsend = AfxBeginThread(send, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL); } else { AfxGetMainWnd()->PostMessage(WM_END, 0, 0); } } UINT CPortScannerDlg::recv(LPVOID lpParam) { CPortScannerDlg *p = (CPortScannerDlg *)lpParam; pcap_t *adhandle = p->device.getHandle(); int res; struct pcap_pkthdr *header; const u_char *pkt_data; EthernetFrame ef; TCP tcp, *ptcp; PDU *pdu = &tcp; ef.SetMACDATA(pdu); WORD dp; BYTE flags; /* Retrieve the packets */ while ((res = pcap_next_ex(adhandle, &header, &pkt_data)) >= 0) { if (!p->started) { return 0; } if (res == 0) /* Timeout elapsed */ continue; ef.Read((BYTE *)pkt_data); ptcp = dynamic_cast<TCP *>(pdu); dp = ptcp->getDestinationport(); flags = ptcp->getUnusedFlags(); p->dp = tcp.getDestinationport(); // 0x12: ack = 1, syn = 1 if (dp == htons(MY_PORT) && flags == 0x12) { p->sp = ptcp->getSourceport(); GlobalLock((HGLOBAL)p); AfxGetMainWnd()->SendMessage(WM_RECV, (WPARAM)p, 0); } else { if (p->checked == 1) { p->dp = tcp.getDestinationport(); GlobalLock((HGLOBAL)p); AfxGetMainWnd()->SendMessage(WM_RECV_FAIL, (WPARAM)p, 0); } if (ntohs(p->dp) >= p->m_eport) { AfxGetMainWnd()->SendMessage(WM_END, 0, 0); return 0; } } } if (res == -1) { return -1; } return 0; } LRESULT CPortScannerDlg::OnRecv(WPARAM wParam, LPARAM lParam) { CPortScannerDlg *p = (CPortScannerDlg *)wParam; CString ps; char dstip[16]; Common::dword2char(p->m_dstip, dstip); ps.Format("%s:%d Connection accepted", dstip, ntohs(p->sp)); m_CListCtrl.InsertItem(count++, ps); UpdateData(FALSE); GlobalUnlock((HGLOBAL)p); return 0; } LRESULT CPortScannerDlg::OnRecvFailed(WPARAM wParam, LPARAM lParam) { CPortScannerDlg *p = (CPortScannerDlg *)wParam; CString result; char dstip[16]; Common::dword2char(p->m_dstip, dstip); result.Format("%s:%d Connection Failed", dstip, ntohs(p->dp)); m_CListCtrl.InsertItem(count++, result); UpdateData(FALSE); GlobalUnlock((HGLOBAL)p); return 0; } UINT CPortScannerDlg::send(LPVOID lpParam) { CPortScannerDlg *p = (CPortScannerDlg *)lpParam; EthernetFrame ef; TCP tcp; PDU *pdu = &tcp; ef.SetMACDATA(pdu); BYTE buffer[54] = { 0 }; // 14 + 20 + 20 for (WORD i = p->m_sport; i <= p->m_eport; ++i) { if (!p->started) { return 0; } p->m_curport = i; AfxGetMainWnd()->SendMessage(WM_UPDATE, 0, 0); //ethernetframe header ef.SetDestAddress(p->m_dstmac); ef.SetSourceAddress(p->m_srcmac); ef.SetEtherType(htons(ETHERTYPE_IPV4)); //ip header tcp.setVersionIHL(0x45); tcp.setDifferentiatedServices(0); tcp.setTotallength(htons(40)); tcp.setIdentification(htons(1)); tcp.setUnusedDFMFFragmentoffset(0); tcp.setTimetolive(16); tcp.setProtocol(6); tcp.setHeaderchecksum(0); tcp.setSourceaddress(p->m_srcip); tcp.setDestinationaddress(p->m_dstip); //tcp header tcp.setSourceport(htons(MY_PORT)); tcp.setDestinationport(htons(i)); tcp.setSequencenumber(htonl(1)); tcp.setAcknowledgementnumber(0); tcp.setTCPheaderlengthUnused(0x50); tcp.setUnusedFlags(0x02); tcp.setWindowsize(htons(0xffff)); tcp.setChecksum(0); tcp.setUrgentpointer(0); //ip checksum recalculate ef.Write(buffer); WORD ipchecksum = Common::CalculateCheckSum(buffer + 14, 20); tcp.setHeaderchecksum(ipchecksum); ef.Write(buffer); // pdf P20 //tcp pseudo-header BYTE temp[32]; DWORD srcip = tcp.getSourceaddress(); DWORD dstip = tcp.getDestinationaddress(); memcpy(temp, &srcip, 4); memcpy(temp + 4, &dstip, 4); temp[8] = 0; temp[9] = 6; WORD TCPsegmentlength = htons(20); memcpy(temp + 10, &TCPsegmentlength, 2); memcpy(temp + 12, buffer + 34, 20); //tcp checksum recalculate WORD Checksum = Common::CalculateCheckSum(temp, 32); tcp.setChecksum(Checksum); ef.Write(buffer); //send tcp half open request p->device.sendPacket(buffer); } return 0; } LRESULT CPortScannerDlg::OnEnd(WPARAM wParam, LPARAM lParam) { started = false; GetDlgItem(IDC_BUTTON_SCAN)->SetWindowText("&Scan"); m_CListCtrl.InsertItem(count, "Finished scan"); GetDlgItem(IDC_EDIT_STARTINGPORT)->EnableWindow(TRUE); GetDlgItem(IDC_EDIT_ENDINGPORT)->EnableWindow(TRUE); GetDlgItem(IDC_IPADDRESS)->EnableWindow(TRUE); return 0; } LRESULT CPortScannerDlg::OnUpdate(WPARAM wParam, LPARAM lParam) { UpdateData(FALSE); return 0; }
#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <stdlib.h> #include <stdio.h> #include <iostream> #include <time.h> using namespace cv; using namespace std; int out_matrix[7][7]; int color_info = 0; int no_of_branches = 0; int no_of_branches2 = 0; Point RobotMove(int board[6][6]); void DrawTable(int board[6][6]); int win(int board[6][6]); void PlayerMove(int board[6][6]); void FormatBoard(vector<vector<int>> blocks); int GetScore(int board[6][6], int player); int GetScore2(int board[6][6], int player); /** @function main */ int main( int argc, char** argv ) { int board[6][6] = {{0,0,0,0,0,0},{2,0,0,0,0,0},{2,2,0,0,0,0},{2,2,2,0,0,0},{2,2,2,2,0,0},{2,2,2,2,2,0}} ; DrawTable(board); Point a = RobotMove(board); cout<<"X: "<<a.x<<endl; cout<<"Y: "<<a.y<<endl; time_t start,end; time (&start); time (&end); double dif = difftime (end,start); printf ("Elasped time is %.2lf seconds.\n", dif ); return 0; } void FormatBoard(vector<vector<int>> blocks){ for (int i=0; i<blocks.size();i++){ int pos_x = blocks[i][0]; int pos_y = 5 - blocks[i][1]; int color = blocks[i][2]; board[pos_x][pos_y] = color; } } Point RobotMove(int board[6][6]){ //Special cases: int count_moves = 0; for (int i=0; i<6; i++){ if (board[i][5] != 0) count_moves++; } if (count_moves == 0 or count_moves == 1){ if (board[2][5] == 0) return Point(2,5); else return Point(3,5); } int player = 1; int move_i = -1; int move_j = -1; double score = 0; no_of_branches = 0; for (int i=0; i<6;i++){ for (int j=0; j<6;j++){ if (board[i][j] == 0 and (j==5 or ((board[i][j+1]!=0) and (board[i+1][j+1]!=0) ))) { board[i][j] = player; double thisScore = GetScore(board, player*-1); thisScore /= no_of_branches; no_of_branches = 0; cout<<thisScore<<endl; if (thisScore > score){ score = thisScore; move_i = i; move_j = j; } board[i][j] = 0; } } } //board[move_i][move_j] = player; return Point(move_i,move_j); } int GetScore(int board[6][6], int player){ int score = 0; int counter = 0; if (win(board)==1) { no_of_branches++;return 1;} else if (win(board)==-1) { no_of_branches++;return 0;} else for (int i=0; i<6 ;i++){ for (int j=0; j<6;j++){ if (board[i][j] == 0 and (j==5 or ((board[i][j+1]!=0) and (board[i+1][j+1]!=0) ))) { board[i][j] = player; counter++; score = score + GetScore(board, player*-1); board[i][j] = 0; } } } if (counter == 0) no_of_branches++; return score; } int GetScore2(int board[6][6], int player){ int score = 0; if (win(board)==1) {return 0;} //if (win(board)==1) {no_of_branches2++;return 0;} else if (win(board)==-1) {return 1;} //else if (win(board)==-1) {no_of_branches2++;return 1;} else for (int i=0; i<6 ;i++){ for (int j=0; j<6;j++){ if (board[i][j] == 0 and (j==5 or ((board[i][j+1]!=0) and (board[i+1][j+1]!=0) ))) { board[i][j] = player; score = score + GetScore2(board, player*-1); board[i][j] = 0; } } } return score; } void DrawTable(int board[6][6]){ //cout<<"X"; cout<<"\t"<<"\t"<<"Table"<<endl; for (int j = 0; j<6;j++){ //cout<<i<<"\t"; for (int i = 0; i<6;i++){ cout<<board[i][j]<<"\t"; } cout<<endl; } //cout<<"Y"<<"\t"<<0<<"\t"<<1<<"\t"<<2<<"\t"<<3<<"\t"<<4<<"\t"<<5<<endl; } int win(int board[6][6]){ int win_conditions[30][3][2] ={{{0,0},{0,1},{0,2}}, {{0,1},{0,2},{0,3}}, {{0,2},{0,3},{0,4}}, {{0,3},{0,4},{0,5}}, {{1,1},{1,2},{1,3}}, {{1,2},{1,3},{1,4}}, {{1,3},{1,4},{1,5}}, {{2,2},{2,3},{2,4}}, {{2,3},{2,4},{2,5}}, {{3,3},{3,4},{3,5}}, {{0,0},{1,1},{2,2}}, {{1,1},{2,2},{3,3}}, {{2,2},{3,3},{4,4}}, {{3,3},{4,4},{5,5}}, {{0,1},{1,2},{2,3}}, {{1,2},{2,3},{3,4}}, {{2,3},{3,4},{4,5}}, {{0,2},{1,3},{2,4}}, {{1,3},{2,4},{3,5}}, {{0,3},{1,4},{2,5}}, {{0,2},{1,2},{2,2}}, {{0,3},{1,3},{2,3}}, {{1,3},{2,3},{3,3}}, {{0,4},{1,4},{2,4}}, {{1,4},{2,4},{3,4}}, {{2,4},{3,4},{4,4}}, {{0,5},{1,5},{2,5}}, {{1,5},{2,5},{3,5}}, {{2,5},{3,5},{4,5}}, {{3,5},{4,5},{5,5}}, }; for (int x=0;x<30;x++) { if (board[win_conditions[x][0][0]][win_conditions[x][0][1]] != 0 and board[win_conditions[x][0][0]][win_conditions[x][0][1]] == board[win_conditions[x][1][0]][win_conditions[x][1][1]] and board[win_conditions[x][0][0]][win_conditions[x][0][1]] == board[win_conditions[x][2][0]][win_conditions[x][2][1]] ) {return board[win_conditions[x][0][0]][win_conditions[x][0][1]];} } return 0; } void PlayerMove(int board[6][6]) { /* int player = -1; int move_i = -1; int move_j = -1; double score = 0; no_of_branches2 = 0; for (int i=0; i<6;i++){ for (int j=0; j<6;j++){ if (board[i][j] == 0 and (i==5 or ((board[i][j+1]!=0) and (board[i+1][j+1]!=0) ))) { board[i][j] = player; double thisScore = GetScore2(board, player*-1); //thisScore /= no_of_branches2; //no_of_branches2 = 0; cout<<thisScore<<endl; if (thisScore > score){ score = thisScore; move_i = i; move_j = j; } board[i][j] = 0; } } } board[move_i][move_j] = player; */ int move_i = 0; int move_j = 0; while (true) { cout<<"What's your move y axis?"<<"\n"<<"> "; cin >> move_j; cout<<"your"<<move_j; cout<<"\n"<<"What's your move x axis?"<<"\n"<<"> "; cin >> move_i; if (board[move_i][move_j] == 0 and (move_j==5 or ((board[move_i][move_j+1]!=0) and (board[move_i+1][move_j+1]!=0) ))){ board[move_i][move_j] = -1; break; } cout<<"\n"<<"Invalid move."<<endl; } }
#ifndef BaseEngine_H #define BaseEngine_H class BaseEngine { public: virtual ~BaseEngine() { } }; #endif
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef _GDCMIO_DICOMSEGMENTREADER_HPP_ #define _GDCMIO_DICOMSEGMENTREADER_HPP_ #include <gdcmSegment.h> #include <fwData/Acquisition.hpp> #include "gdcmIO/reader/DicomFilesReader.hxx" namespace gdcmIO { namespace reader { /** * @brief This class implement a segmentation reader. * * @note Currently, it just handles segmentation from surface segmentation storage. * * @class DicomSegmentReader * @author IRCAD (Research and Development Team). * @date 2011. */ class GDCMIO_CLASS_API DicomSegmentReader : public DicomFilesReader< ::fwData::Acquisition > { public : GDCMIO_API DicomSegmentReader(); GDCMIO_API virtual ~DicomSegmentReader(); protected : /** * @brief Read one surface segmentation module. * * @see PS 3.3 C.8.23.1. * * @param a_reconstruction fwData::Reconstruction to set. * @param a_segment Current segmentation. */ virtual void readSurfaceSegmentation( ::fwData::Reconstruction::sptr a_reconstruction, ::gdcm::SmartPointer< ::gdcm::Segment > a_segment ) throw (::fwTools::Failed); private : /** * @brief Check if segmentation has surface. */ bool isSurfaceSegmentation(); }; } // namespace reader } // namespace gdcmIO #endif /* _GDCMIO_DICOMSEGMENTREADER_HPP_ */
#include <iostream> #include <vector> #include <algorithm> #include <string> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int n, cnt{}; std::cin >> n; int now = n; do { if (now < 10) { now = now + now * 10; ++cnt; continue; } now = (now % 10) * 10 + (now % 10 + now / 10) % 10; ++cnt; } while (now != n); std::cout << cnt << '\n'; return 0; }
#pragma once #include <QtWidgets/QMainWindow> #include "ui_SimpleQtOGL.h" class SimpleQtOGL : public QMainWindow { Q_OBJECT public: SimpleQtOGL(QWidget *parent = Q_NULLPTR); private: Ui::SimpleQtOGLClass ui; };
//Motor Definitions int E1 = 5; //M1 Speed Control int E2 = 6; //M2 Speed Control int M1 = 4; //M1 Direction Control int M2 = 7; //M2 Direction Control //DIRECTIONS //STOP void stop(void) { digitalWrite(E1, 0); digitalWrite(M1, LOW); digitalWrite(E2, 0); digitalWrite(M2, LOW); } //ADVANCE void advance(char a, char b) { analogWrite (E1, a); digitalWrite(M1, HIGH); analogWrite (E2, b); digitalWrite(M2, HIGH); } //MOVE BACKWARDS void back_off (char a, char b) { analogWrite (E1, a); digitalWrite(M1, LOW); analogWrite (E2, b); digitalWrite(M2, LOW); } //TURN LEFT void turn_L (char a, char b) { analogWrite (E1, a); digitalWrite(M1, LOW); analogWrite (E2, b); digitalWrite(M2, HIGH); } //TURN RIGHT void turn_R (char a, char b) { analogWrite (E1, a); digitalWrite(M1, HIGH); analogWrite (E2, b); digitalWrite(M2, LOW); } void setup(void) { char val ; int i; for (i = 4; i <= 7; i++) pinMode(i, OUTPUT); Serial.begin(9600); Serial.println("hello. w = forward, d = turn right, a = turn left, s = backward, x = stop, z = hello world"); //Display instructions in the serial monitor digitalWrite(E1, LOW); digitalWrite(E2, LOW); } void loop(void) { if ( Serial.available() ) { char val = Serial.read(); if (val != -1) { switch (val) { case '5'://Move backward Serial.println("backward"); turn_L (70, 70); delay (1000); stop(); break; case '8'://Move forward Serial.println("forward"); turn_R (70, 70); delay (1000); stop(); break; case '4'://Turn Left Serial.println("going forward"); advance (95, 95); //move forward at max speed delay (2500); stop(); break; case '6'://Turn Right Serial.println("going backward"); back_off (95, 95); //move backwards at max speed delay (2500); stop(); break; case '1' : //turn right "doucement" Serial.println("going backward"); back_off (90, 90); //move backwards at max speed delay (900); stop(); break; case '2' : //turn left "doucement" Serial.println("going forward"); advance (90, 90); //move forward at max speed delay (900); stop(); break; case '3' : //backword "doucement" Serial.println("going forward"); turn_L (55, 55); //move forward at max speed delay (1000); stop(); break; case '7' : //avnace "doucement" Serial.println("going forward"); turn_R (55, 55); //move forward at max speed delay (1000); stop(); break; default : break; } } } else stop(); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Bazyli Zygan bazyl@opera.com */ #ifndef MAC_GADGET_ABOUT_DIALOG_H #define MAC_GADGET_ABOUT_DIALOG_H #ifdef WIDGET_RUNTIME_SUPPORT #include "adjunct/quick_toolkit/widgets/Dialog.h" #include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeView.h" #include "modules/widgets/OpButton.h" class OpGadgetClass; class MacGadgetAboutDialog : public Dialog { public: MacGadgetAboutDialog(OpGadgetClass *gadgetClass); ~MacGadgetAboutDialog(); /** * Using DIALOG_TYPE_WIDGET_INSTALLER, we don't need new one. */ DialogType GetDialogType() { return TYPE_OK; } virtual const char* GetWindowName() { return "Mac Gadget About Dialog"; } // virtual Type GetType() { return DIALOG_TYPE_WIDGET_UNINSTALLER; } /** * Dialog initialization. * * @param src_wgt_path Path to widget wgt file. * @return Error status. */ OP_STATUS Init(); private: OpGadgetClass *m_gadget_class; }; #endif // WIDGET_RUNTIME_SUPPORT #endif // MAC_GADGET_ABOUT_DIALOG_H
#include "KMeans.h" #include <math.h> #include <list> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <vector> #include <iostream> using namespace std; KMeans::KMeans(DataContainer *pContainer, int clusterCount) { _pContainer = pContainer; _clusterCount = clusterCount; _clusters = new Cluster[clusterCount]; for (Cluster *pCluster = _clusters; \ pCluster != _clusters + clusterCount; pCluster++) { pCluster->setContainer(pContainer); } } KMeans::~KMeans() { if (_clusters) delete[] _clusters; } int KMeans::clusterCount() { return _clusterCount; } Cluster* KMeans::clusters() { return _clusters; } Clustering* KMeans::clusterize(AbstractMetric *pMetric) { list<int> ids = _pContainer->ids(); int nObjectCount = _pContainer->ids().size(); list<int> sample = KMeans::randomSample(ids, _clusterCount); printf("ID selection for random sample: "); for (list<int>::iterator iEl = sample.begin(); iEl != sample.end(); iEl++) { printf("%i, ", *iEl); } printf("\n"); int nCluster = 0; for (list<int>::iterator iEl = sample.begin(); iEl != sample.end(); iEl++, nCluster++) { _clusters[nCluster].addObject(_pContainer->get(*iEl)); } Cluster *pTempClusters = new Cluster[_clusterCount]; for (int i = 0; i < _clusterCount; i++) pTempClusters[i].setContainer(_pContainer); float dist, minDist; int nSelectedCluster = 0; Object *pObj; int nClusterChanges = 0; int nClusterChangeTreshold = 500; bool bClustersChanged = true; while (bClustersChanged) { nClusterChanges = 0; bClustersChanged = false; time_t start, end; start = time(NULL); int nIndexCounter = 0; for (int i = 0; i < nObjectCount; i++) { pObj = _pContainer->getByIndex(i); minDist = -1; nCluster = 0; nSelectedCluster = 0; Object *pCenter = NULL; //printf("Object in question: "); //pObj->print(); for (nCluster = 0; nCluster < _clusterCount; nCluster++) { pCenter = _clusters[nCluster].center(pMetric); //printf("Center: "); //pCenter->print(); dist = pMetric->distance(*pObj, *_clusters[nCluster].center(pMetric)); //printf("distance: %.4f\n", dist); if (minDist < 0 || dist < minDist) { nSelectedCluster = nCluster; minDist = dist; } } //printf("\n\n"); //if (!bClustersChanged && !_clusters[nSelectedCluster].contains(*iObjectId)) /* if (nClusterChanges < nClusterChangeTreshold && !_clusters[nSelectedCluster].contains(*iObjectId)) { bClustersChanged = true; nClusterChanges++; } */ pTempClusters[nSelectedCluster].addObject(pObj); nIndexCounter++; if (nIndexCounter % 10000 == 0) printf("%i objects processed.\r\n", nIndexCounter); } end = time(NULL); printf("Calculating all the distances took %i seconds.\r\n", (int)(end-start)); printf("Calculating differences...\r\n"); start = time(NULL); int nChangedClusters = 0; for (nCluster = 0; nCluster < _clusterCount; nCluster++) { if (! (_clusters[nCluster] == pTempClusters[nCluster])) { bClustersChanged = true; nChangedClusters++; //break; } } end = time(NULL); printf("Differences calculated, %i seconds spent. Clusters out of order: %i\r\n", (int)(end-start), nChangedClusters); if (bClustersChanged) printf("Differences found!\r\n"); else printf("No differences found!\r\n"); for (nCluster = 0; nCluster < _clusterCount; nCluster++) { _clusters[nCluster] = pTempClusters[nCluster]; pTempClusters[nCluster].clear(); } } printf("Done!\r\n"); delete[] pTempClusters; return new Clustering(_clusters, _clusterCount); /* FILE *pFile = 0; char *filename = "results2.txt"; pFile = fopen(filename, "w"); int *pActualClasses = new int[_clusterCount]; memset(pActualClasses, 0, _clusterCount*sizeof(int)); for (nCluster = 0; nCluster < _clusterCount; nCluster++) { memset(pActualClasses, 0, _clusterCount*sizeof(int)); list<int> ids = _clusters[nCluster].ids(); fprintf(pFile, "Cluster %i: ", nCluster); for (list<int>::iterator iId = ids.begin(); iId != ids.end(); iId++) { pActualClasses[_pContainer->get(*iId)->actualClass()]++; } for (int nClusterInner = 0; nClusterInner < _clusterCount; nClusterInner++) { fprintf(pFile, "%i: %i, ", nClusterInner, pActualClasses[nClusterInner]); } fprintf(pFile, "\n"); } fclose(pFile); delete[] pActualClasses; */ } list<int> KMeans::randomSample(list<int> ids, int nIndexCount) { list<int> result; int nItemIndex = 0; int nRandomIndex = 0; list<int>::iterator iList; int nTemp = 0; srand(time(NULL)); for (int i = 0; i < nIndexCount; i++) { nItemIndex = (rand() % ids.size()); nTemp = 0; for (iList = ids.begin(); iList != ids.end() && nTemp < nItemIndex; \ iList++, nTemp++) {} nRandomIndex = *iList; //Attention! Might be outside the list! ids.remove(nRandomIndex); result.push_back(nRandomIndex); } return result; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #define INF (1<<28) #define EPS 1e-8 #define MOD 100000000 using namespace std; class Stamp { public: int getMinimumCost(string desiredColor, int stampCost, int pushCost) { int N = (int)desiredColor.size(); vector<int> cost(N+1,0); vector<int> a(N); for (int i=0; i<N; ++i) { char c = desiredColor[i]; if (c == '*') a[i] = 7; if (c == 'R') a[i] = 1; if (c == 'G') a[i] = 2; if (c == 'B') a[i] = 4; } int res = INF; for (int len=1; len<=N; ++len) { cost[0] = 0; fill(cost.begin()+1, cost.end(), INF); for (int i=0; i<N; ++i) { int color = 7; for (int j=i; j<N; ++j) { color &= a[j]; if (!color) break; int seg = j - i + 1; if (seg < len) continue; if (cost[i] != INF) { cost[j+1] = min(cost[j+1],cost[i] + ( (seg+len-1) / len )*pushCost); } } } if (cost[N] != INF) { res = min(res,cost[N] + stampCost*len); } } return res; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "RRGGBB"; int Arg1 = 1; int Arg2 = 1; int Arg3 = 5; verify_case(0, Arg3, getMinimumCost(Arg0, Arg1, Arg2)); } void test_case_1() { string Arg0 = "R**GB*"; int Arg1 = 1; int Arg2 = 1; int Arg3 = 5; verify_case(1, Arg3, getMinimumCost(Arg0, Arg1, Arg2)); } void test_case_2() { string Arg0 = "BRRB"; int Arg1 = 2; int Arg2 = 7; int Arg3 = 30; verify_case(2, Arg3, getMinimumCost(Arg0, Arg1, Arg2)); } void test_case_3() { string Arg0 = "R*RR*GG"; int Arg1 = 10; int Arg2 = 58; int Arg3 = 204; verify_case(3, Arg3, getMinimumCost(Arg0, Arg1, Arg2)); } void test_case_4() { string Arg0 = "*B**B**B*BB*G*BBB**B**B*"; int Arg1 = 5; int Arg2 = 2; int Arg3 = 33; verify_case(4, Arg3, getMinimumCost(Arg0, Arg1, Arg2)); } void test_case_5() { string Arg0 = "*R*RG*G*GR*RGG*G*GGR***RR*GG"; int Arg1 = 7; int Arg2 = 1; int Arg3 = 30; verify_case(5, Arg3, getMinimumCost(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Stamp ___test; ___test.run_test(-1); } // END CUT HERE
#include <iostream> using namespace std; int main() { cout << "Introduce an integer representing the number of cents "; int n_cents {0}; cin >> n_cents; const int cents_in_dollar {100}; const int cents_in_quarter {25}; const int cents_in_dime {10}; const int cents_in_nickle {5}; const int cents_in_penny {1}; int dollars{0}, quarters{0}, dimes{0}, nickles{0}, pennys{0}; dollars = n_cents / cents_in_dollar; n_cents %= cents_in_dollar; quarters = n_cents / cents_in_quarter; n_cents %= cents_in_quarter; dimes = n_cents / cents_in_dime; n_cents %= cents_in_dime; nickles = n_cents / cents_in_nickle; n_cents %= cents_in_nickle; pennys = n_cents / cents_in_penny; cout << "So we have" << endl; cout << "\t" << dollars << " dollars" << endl; cout << "\t" << quarters << " quarters" << endl; cout << "\t" << dimes << " dimes" << endl; cout << "\t" << nickles << " nickels" << endl; cout << "\t" << pennys << " pennys" << endl; return 0; }
#include <tinyxml.h> #include <chrono> #include <exception> #include <filesystem> #include <gpiod.hpp> #include <iostream> #include <memory> #include <sstream> #include <string> #include <tuple> #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/bool.hpp" #define SAFETY_TIMEOUT 100ms #define SAFETY_TIMEOUT_CHECK 10ms //#define ALLOW_PULL_DIR using std::placeholders::_1; using namespace std::chrono_literals; bool getValue(TiXmlElement* elem, const std::string& childName, std::string& value); bool stob(std::string s); struct GpioPort { int port; std::string chip = "gpiochip0"; short pinDir = 0; //0 is output, 1 is input, 2 is safety and any other is as is short pullDir = 0; // 0 is no change, 1 is up 2 is down std::string topic; // comparison operators needed for mapping friend bool operator<(const GpioPort& l, const GpioPort& r) { return std::tie(l.chip, l.port) < std::tie(r.chip, r.port); } friend bool operator>(const GpioPort& lhs, const GpioPort& rhs) { return rhs < lhs; } friend bool operator<=(const GpioPort& lhs, const GpioPort& rhs) { return !(lhs > rhs); } friend bool operator>=(const GpioPort& lhs, const GpioPort& rhs) { return !(lhs < rhs); } }; std::shared_ptr<std::vector<GpioPort>> createGpioMap(TiXmlDocument* doc); class LineCaller { private: std::shared_ptr<gpiod::chip> gpioChip; std::shared_ptr<gpiod::line> line; std::shared_ptr<short> pinDir; rclcpp::Publisher<std_msgs::msg::Bool>::SharedPtr pub; rclcpp::TimerBase::SharedPtr pubTimer; rclcpp::Subscription<std_msgs::msg::Bool>::SharedPtr sub; bool unsafeFlag; public: LineCaller(std::string& chip, int port, short pullDir, short pinDirConf, rclcpp::Node& node, const std::string& topic) { gpioChip = std::make_shared<gpiod::chip>(chip, 1); line = std::make_shared<gpiod::line>(gpioChip->get_line(port)); pinDir = std::make_shared<short>(pinDirConf); int dir = 0; switch (*pinDir) { case 0: dir = gpiod::line_request::DIRECTION_INPUT; pub = node.create_publisher<std_msgs::msg::Bool>(topic, 10); pubTimer = node.create_wall_timer(10ms, std::bind(&LineCaller::readCallback, this)); break; case 1: dir = gpiod::line_request::DIRECTION_OUTPUT; sub = node.create_subscription<std_msgs::msg::Bool>(topic, 10, std::bind(&LineCaller::updateCallback, this, _1)); break; case 2: dir = gpiod::line_request::DIRECTION_OUTPUT; break; default: dir = gpiod::line_request::DIRECTION_AS_IS; } std::bitset<32UL> flags = 0; #ifdef ALLOW_PULL_DIR switch (pullDir) { case 1: flags |= gpiod::line_request::FLAG_BIAS_PULL_UP; break; case 2: flags |= gpiod::line_request::FLAG_BIAS_PULL_DOWN; break; default: flags |= gpiod::line_request::FLAG_BIAS_DISABLE; break; } #endif line->request({"hw_interface", dir, flags}); } short getDir() { return *(pinDir); } void setVal(bool val) { if (*pinDir > 0) { line->set_value(val); } } void updateCallback(std::shared_ptr<std_msgs::msg::Bool> msg) { setVal(msg->data); } void readCallback() { if (*pinDir == 0) { std_msgs::msg::Bool msg = std_msgs::msg::Bool(); msg.data = line->get_value(); pub->publish(msg); } } }; class HardwareController : public rclcpp::Node { private: //map of all gpio lines requested by system std::map<GpioPort, std::shared_ptr<LineCaller>> lines; //list of all subscribed topics std::vector<std::string> topics; //safety enable subscription that allows motors to be active rclcpp::Subscription<std_msgs::msg::Bool>::SharedPtr safetySubscrip; //safety enable timer rclcpp::TimerBase::SharedPtr safetyTimer; //flag for saftey enable of all outputs bool safetyEnable = false; //last time the safety stamp was set to true std::chrono::_V2::system_clock::duration safetyStamp; bool safetyToggle = false; public: HardwareController() : Node("pi_hw_interface") { //safetySubscrip = create_subscription<std_msgs::msg::Bool>("safety_enable", 10, std::bind(&HardwareController::feedSafety, this, _1)); safetyStamp = std::chrono::system_clock::now().time_since_epoch(); //safetyTimer = create_wall_timer(SAFETY_TIMEOUT_CHECK, std::bind(&HardwareController::safetyTimerUpdate, this)); } void registerGpio(std::vector<GpioPort> ports) { try { //create all GPIO for (auto it = ports.begin(); it != ports.end(); it++) { //RCLCPP_INFO(this->get_logger(), "Creating LineCaller %s %d %d %d", it->chip.c_str(), it->port, it->pullDir, it->pinDir); std::shared_ptr<LineCaller> line = std::make_shared<LineCaller>(it->chip, it->port, it->pullDir, it->pinDir, (*this), it->topic); lines[*it] = line; } } catch (const std::exception& e) { RCLCPP_ERROR(this->get_logger(), "Failed to bind Gpio\nCause: %s", e.what()); } catch (...) { RCLCPP_ERROR(this->get_logger(), "Failed to bind Gpio\nCause Unknown"); } } /*void feedSafety(std::shared_ptr<std_msgs::msg::Bool> msg) { if (msg->data) { safetyStamp = std::chrono::system_clock::now().time_since_epoch(); unsafe(); } } void safetyTimerUpdate() { //RCLCPP_INFO(this->get_logger(), "Safety timer tick"); auto now = std::chrono::system_clock::now().time_since_epoch(); if (safetyEnable && (now - SAFETY_TIMEOUT > safetyStamp)) { RCLCPP_INFO(this->get_logger(), "Safety timer expired"); safe(); } //if (safetyEnable && (now - (SAFETY_TIMEOUT / 2) > safetyStamp)) // safetyToggle = !safetyToggle; } void safe() { safetyEnable = false; RCLCPP_INFO(this->get_logger(), "Safing lines"); std::map<GpioPort, std::shared_ptr<LineCaller>>::iterator it; for (it = lines.begin(); it != lines.end(); it++) { if (it->second->getDir() > 0) { it->second->setVal(false); } } } /*void unsafe() { if (!safetyEnable) { RCLCPP_INFO(this->get_logger(), "Unsafing lines"); safetyEnable = true; std::map<GpioPort, std::shared_ptr<LineCaller>>::iterator it; for (it = lines.begin(); it != lines.end(); it++) { if (it->second->getDir() > 0) { } } } }*/ }; int main(int argc, char** argv) { //init ros node rclcpp::init(argc, argv); std::shared_ptr<HardwareController> rosNode = std::make_shared<HardwareController>(); RCLCPP_INFO(rosNode->get_logger(), "Hardware interface node starting"); // Load the xml file std::filesystem::path config = std::filesystem::current_path() / "config.xml"; TiXmlDocument* doc = new TiXmlDocument(config.c_str()); if (!doc->LoadFile()) { RCLCPP_ERROR(rosNode->get_logger(), "Error parsing XML config %s\n %s", config.c_str(), doc->ErrorDesc()); } else { try { // grab the parent motor XML element and make sure it exists TiXmlElement* hardware = doc->FirstChildElement("hardware"); if (!hardware) throw std::runtime_error("XML doc is missing root hardware element"); TiXmlElement* gpios = hardware->FirstChildElement("gpios"); if (!gpios) throw std::runtime_error("XML doc is missing gpios element. The gpios element should be defined even if there are no gpio being created"); // RCLCPP_INFO(rosNode->get_logger(), "XML doc loaded, outer parts intact"); std::vector<GpioPort> gpioList = std::vector<GpioPort>(); for (TiXmlElement* gpio = gpios->FirstChildElement("gpio"); gpio != nullptr; gpio = gpio->NextSiblingElement("gpio")) { GpioPort port = {}; std::string tmp, tmp1, topic; if (!getValue(gpio, "topic", topic)) { throw std::runtime_error("Gpio definition missing topic name"); } if (!getValue(gpio, "port", tmp)) { throw std::runtime_error("Gpio definition missing port number"); } if (!getValue(gpio, "dir", tmp1)) { throw std::runtime_error("Gpio definition missing dir"); } port.port = std::stoi(tmp); if (tmp1 == "OUT") port.pinDir = 1; else if (tmp1 == "IN") port.pinDir = 0; else port.pinDir = 3; if (getValue(gpio, "pull", tmp)) port.pullDir = std::stoi(tmp); port.topic = "pi_hw_interface/" + topic; gpioList.push_back(port); RCLCPP_INFO(rosNode->get_logger(), "Got line config Topic: %s Port: %s Dir: %s", port.topic.c_str(), tmp.c_str(), tmp1.c_str()); } RCLCPP_INFO(rosNode->get_logger(), "Recieved config for %d gpio(s)", gpioList.size()); rosNode->registerGpio(gpioList); //RCLCPP_INFO(rosNode->get_logger(), "Registered GPIO Lines"); //set all gpio to off //rosNode->safe(); RCLCPP_INFO(rosNode->get_logger(), "Hardware interface node loaded using gpiod interface"); // serve the callbacks rclcpp::spin(rosNode); RCLCPP_INFO(rosNode->get_logger(), "Hardware interface shutting down"); //set all gpio to off //rosNode->safe(); } catch (const std::exception& e) { RCLCPP_ERROR(rosNode->get_logger(), "Node failed\nCause: %s", e.what()); } catch (...) { RCLCPP_ERROR(rosNode->get_logger(), "Node failed\nCause Unknown"); } } delete doc; RCLCPP_INFO(rosNode->get_logger(), "Hardware interface shut down complete"); rclcpp::shutdown(); return 0; } /** * function to pull a child element from a parent element as text * @param elem the parent XML element * @param childName the name of the XML child element to find * @param value the resulting value of the child element. * @return bool true if the element was found or false if not found **/ bool getValue(TiXmlElement* elem, const std::string& childName, std::string& value) { //std::cout << "checking for " << childName << std::endl; //make sure child element and corresponding text exists TiXmlElement* childElem = elem->FirstChildElement(childName); if (!childElem) return false; const char* xmlVal = childElem->GetText(); if (!xmlVal) return false; value = std::string(xmlVal); return true; } /** * @param s the string to parse for a boolean * @return the value of the resulting boolean **/ bool stob(std::string s) { auto result = false; // failure to assert is false std::istringstream is(s); // first try simple integer conversion is >> result; if (is.fail()) { // simple integer failed; try boolean is.clear(); is >> std::boolalpha >> result; } return result; }
#ifndef HTTPDOWNLOAD_H #define HTTPDOWNLOAD_H #include <QDialog> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QUrl> #include <QProgressDialog> #include <QFile> #include <QFileInfo> #include <QDir> #include <QMessageBox> namespace Ui { class HttpDownload; } class HttpDownload : public QDialog { Q_OBJECT public: explicit HttpDownload(QWidget *parent = 0); ~HttpDownload(); public: void startRequest(QUrl url); private slots: void on_downloadButton_clicked(); void on_quitButton_clicked(); void on_urlEdit_returnPressed(); // slot for readyRead() signal void httpReadyRead(); // slot for finished() signal from reply void httpDownloadFinished(); // slot for downloadProgress() void updateDownloadProgress(qint64, qint64); void enableDownloadButton(); void cancelDownload(); private: Ui::HttpDownload *ui; QUrl url; QNetworkAccessManager *manager; QNetworkReply *reply; QProgressDialog *progressDialog; QFile *file; bool httpRequestAborted; qint64 fileSize; }; #endif // HTTPDOWNLOAD_H
#include "Server.h" using namespace std; /******************************************************************************* * function name : Server * * input : nothing. * * output : nothing. * * explanation : constructor of a Server. * *******************************************************************************/ Server::Server(){ this->port =0; this->dataReceived =NULL; this->sock = 0; this->ip = NULL; this->threads = vector<pthread_t>(); } /******************************************************************************* * function name : getThreads * * input : nothing. * * output : a referance to the vector of the threads. * * explanation : getter to the vector of threads. * *******************************************************************************/ vector<pthread_t>& Server::getThreads(){ return this->threads; } /******************************************************************************* * function name : invokeThread * * input : thread id as int. * * output : nothing. * * explanation : invoke the thread with the given id. * *******************************************************************************/ void Server::invokeThread(int id){ pthread_join(id,NULL); } /******************************************************************************* * function name : addThread * * input : a thread as thread_t. * * output : nothing. * * explanation : setter to the threads vector. * *******************************************************************************/ void Server::addThread(pthread_t ptrd){ this->threads.push_back(ptrd); } /******************************************************************************* * function name : ~Server * * input : nothing. * * output : nothing. * * explanation : destructor of a Server. * *******************************************************************************/ Server::~Server(){ } /******************************************************************************* * function name : Server * * input : port as int. * * output : nothing. * * explanation : constructor of a Server. * *******************************************************************************/ Server::Server(int port){ this->port = port; this->dataReceived =NULL; this->ip = NULL; this->sock = 0; } /******************************************************************************* * function name : getIP * * input : nothing. * * output : ip as string. * * explanation : return the ip address as string. * *******************************************************************************/ char* Server::getIP(){ return this->ip; } /******************************************************************************* * function name : getPort * * input : nothing. * * output : port as int. * * explanation : return the port as int. * *******************************************************************************/ int Server::getPort(){ return this->port; } /******************************************************************************* * function name : setIP * * input : ip as string. * * output : nothing. * * explanation : set the ip member with string. * *******************************************************************************/ void Server::setIP(char* ip){ this->ip=ip; } /******************************************************************************* * function name : setPort * * input : port as int. * * output : nothing. * * explanation : set the port member with int. * *******************************************************************************/ void Server::setPort(int port){ this->port=port; } /******************************************************************************* * function name : setSocket * * input :socket as int. * * output : nothing. * * explanation : set the client set currently need. * *******************************************************************************/ void Server::setSocket(int sock){ this->client_sock = sock; } /******************************************************************************* * function name : close * * input : socket as int. * * output : nothing. * * explanation : close the socket of the connection. * *******************************************************************************/ void Server::close(int socket){ close(socket); } /******************************************************************************* * function name : getDataReceived * * input : nothing. * * output : the massage as string. * * explanation : return the massage as string. * *******************************************************************************/ string Server::getDataReceived(){ return string(this->dataReceived); } /******************************************************************************* * function name : getSocket * * input : nothing. * * output : the socket. * * explanation : return the socket. * *******************************************************************************/ int Server::getSocket(){ return this->sock; } /******************************************************************************* * function name : sendData * * input : data as string. * * output : nothing. * * explanation : sending the data to the socket. * *******************************************************************************/ void Server::sendData(string str, int sock){} /******************************************************************************* * function name : dataReceiver * * input : nothing. * * output : nothing. * * explanation : receive the massage to the buffer. * *******************************************************************************/ string Server::dataReceiver(int sock){} /******************************************************************************* * function name : bindSocket * * input : nothing. * * output : nothing. * * explanation : make bind to a client. * *******************************************************************************/ void Server::bindSocket(){}
// https://oj.leetcode.com/problems/rotate-image/ class Solution { public: void rotate(vector<vector<int> > &matrix) { int size = static_cast<int>(matrix.size()); if (size < 2) { return; } for (int i = 0; i < size / 2; i++) { for (int j = i; j - i < cur_size - 1; j++) { int cache = matrix[i][j]; int n = j, m = i; for (int k = 0; k < 4; k++) { int row = n; int col = size - 1 - m; int tmp = matrix[row][col]; matrix[row][col] = cache; cache = tmp; m = row; n = col; } } } } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef TESTSUITE_SELFTESTMEMORYCLEANUPUTIL_H #define TESTSUITE_SELFTESTMEMORYCLEANUPUTIL_H #ifdef SELFTEST /** Simple util class for handling deleting objects in asynchronous selftests. * * As 'finally' clause doesn't work in asynchronous selftests and in larger tests it can become * troublesome to keep track of all the objects and their lifetime. This class simplifies handling * heap allocated objects by scheduling their deletion in the end of selftest group is completed. */ class SelftestMemoryCleanupUtil { public: /** Schedules object to be deleted when Cleanup is called. * * @param object - object which will be scheduled for deletion. If this function fails(OOM) then the object * will be deleted immidietly. This function returns ERR_NO_MEMORY also if object is NULL, so NULL check can be * ommited and just check the result of this function. * NOTE: As deallocation uses OP_DELETE object must be allocted by OP_NEW(not malloc, or array new allocator) * @return OK or ERR_NO_MEMORY */ template<class Type> OP_STATUS DeleteAfterTest(Type* object) { if (!object) return OpStatus::ERR_NO_MEMORY; DeletableBase* wrapper = OP_NEW(Deletable<Type>, (object)); if (!wrapper) { OP_DELETE(object); return OpStatus::ERR_NO_MEMORY; } OP_STATUS error = m_deletables.Insert(0, wrapper); if (OpStatus::IsError(error)) OP_DELETE(wrapper); return error; } /** Deletes all objects scheduled for deletion * * This is called by selftest engine after finishing every test group. */ void Cleanup() { m_deletables.DeleteAll(); } /** Returns number of items scheduled for cleanup * * For testing purposes only */ UINT32 ItemsToCleanup() { return m_deletables.GetCount(); } private: /// Wrapper interface for deletable object class DeletableBase{ public: virtual ~DeletableBase() {} }; /// Implementation of wrapper for deletable object which calls proper destructor template<class WrappedType> class Deletable : public DeletableBase { public: Deletable(WrappedType* wrapped_object) : m_wrapped_object(wrapped_object) {} virtual ~Deletable() { OP_DELETE(m_wrapped_object); } private: WrappedType* m_wrapped_object; }; OpAutoVector<DeletableBase> m_deletables; }; #endif // SELFTEST #endif // !TESTSUITE_TESTUTILS_H
#ifndef QT_STACKWIDGET_H #define QT_STACKWIDGET_H #include <QtWidgets/QMainWindow> #include "ui_qt_stackwidget.h" #include <QtGui> #include <QtWidgets> class QBaseWidget; class Qt_Stackwidget : public QMainWindow { Q_OBJECT public: Qt_Stackwidget(QWidget *parent = 0); ~Qt_Stackwidget(); void createBaseMenu(); void changeCBA(QBaseWidget* current); void createOptionsBackCBA(QBaseWidget* current); void createOptionsExitCBA(QWidget* current); QAction* back; public slots: int activatePerviousView(); public: Ui::Qt_StackwidgetClass ui; QStackedWidget *stack; private slots: void activeWidgetChanged(int index); }; class QBaseWidget : public QWidget { Q_OBJECT public: QBaseWidget(QWidget *parent = 0) { } virtual ~QBaseWidget() { } public: // Returns widget menu virtual QMenuBar* GetMenuBar() const = 0; // Exit from the app protected: // Widget own menubar QMenuBar* menuBar; // Pointer to QStackedWidget where all views exists QStackedWidget* BaseStackwidget; }; class Homewidget : public QBaseWidget { Q_OBJECT public: Homewidget(QStackedWidget* stackedWidget, QWidget *parent = 0); ~Homewidget(); QMenuBar* GetMenuBar() const; void createMenus(); public slots: void CreateFirstwidget(); void CreateSecwidget(); void CreateThiredwidget(); private: QMenuBar *menuBar; QPushButton *widget1; QPushButton *widget2; QPushButton *widget3; QVBoxLayout *layout; QAction *FirstwidgetAction; QAction *SecwidgetAction; QAction *ThiredwidgetAction; }; //First widget class class Firstwidget : public QBaseWidget { Q_OBJECT public: Firstwidget(QStackedWidget* stackedWidget, QWidget *parent = 0); ~Firstwidget() { int gg = 0; } QMenuBar* GetMenuBar() const; void createMenus(); public slots: void CreateSecwidget(); void CreateThiredwidget(); private: QMenuBar *menuBar; QPushButton *widget2; QPushButton *widget3; QVBoxLayout *layout; QAction *SecwidgetAction; QAction *ThiredwidgetAction; }; //Second widget class class Secwidget : public QBaseWidget { Q_OBJECT public: Secwidget(QStackedWidget* stackedWidget, QWidget *parent = 0); ~Secwidget() { int gg = 0; } QMenuBar* GetMenuBar() const; void createMenus(); public slots: //void CreateSecwidget(); void CreateThiredwidget(); private: QMenuBar *menuBar; QLabel *widget3; QVBoxLayout *layout; QLabel *thiredwidgetlabel; QAction *ThiredwidgetAction; }; class Thiredwidget : public QBaseWidget { Q_OBJECT public: Thiredwidget(QStackedWidget* stackedWidget, QWidget *parent = 0); ~Thiredwidget() { int gg = 0; } QMenuBar* GetMenuBar() const; void createMenus(); private: QMenuBar *menuBar; QVBoxLayout *layout; QLabel *thiredwidgetLabel; }; #endif // QT_STACKWIDGET_H
#include <iostream> #include "bruch.h" using namespace std; int main() { Bruch a(2,4); Bruch b(1,3); cout << "a: " << a << endl; cout << "b: " << b << endl; Bruch c = a + b; cout << "a + b: " << c << endl; c = a - b; cout << "a - b: " << c << endl; c = a * b; cout << "a * b: " << c << endl; c = a / b; cout << "a / b: " << c << endl; cout << "1/6 == 1/6: " << ((a-b) == (a*b)) << endl; cout << "5/6 != 1/6: " << ((a+b) != (a*b)) << endl; cout << "<<: " << a << endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2000-2011 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/dochand/fdelm.h" #include "modules/doc/frm_doc.h" #include "modules/doc/html_doc.h" #include "modules/dochand/win.h" #include "modules/display/prn_dev.h" #include "modules/probetools/probepoints.h" #include "modules/dom/domenvironment.h" #include "modules/dom/domutils.h" #include "modules/hardcore/mh/constant.h" #include "modules/pi/ui/OpUiInfo.h" #ifdef SVG_SUPPORT # include "modules/svg/SVGManager.h" # include "modules/svg/svg_image.h" #endif // SVG_SUPPORT #ifdef NEARBY_INTERACTIVE_ITEM_DETECTION # include "modules/widgets/OpScrollbar.h" #endif // NEARBY_INTERACTIVE_ITEM_DETECTION #include "modules/prefs/prefsmanager/collections/pc_display.h" #include "modules/security_manager/include/security_manager.h" void FramesDocElm::SetFrameScrolling(BYTE scrolling) { frame_scrolling = scrolling; } void FramesDocElm::Reset(int type, int val, FramesDocElm* parent_frmset, HTML_Element *helm) { frame_spacing = 0; SetFrameBorder(TRUE); SetFrameBorders(FALSE, FALSE, FALSE, FALSE); BOOL normal_frames_mode = !GetParentFramesDoc()->GetSmartFrames() && !GetParentFramesDoc()->GetFramesStacked(); if (!helm) helm = GetHtmlElement(); if (helm) { SetIsFrameset(helm->IsMatchingType(HE_FRAMESET, NS_HTML)); SetFrameNoresize(IsFrameset() || helm->GetFrameNoresize()); SetFrameScrolling(helm->GetFrameScrolling()); /* Images should never have scrollbars. If this is a pseudo iframe used to implement for instance an SVG image in an IMG element, then make sure we don't display any scrollbars in it. */ if (helm->IsMatchingType(HE_IMG, NS_HTML)) frame_scrolling = SCROLLING_NO; frame_margin_width = helm->GetFrameMarginWidth(); frame_margin_height = helm->GetFrameMarginHeight(); BOOL check_parent_frame_border = TRUE; short frame_spacing_attr = ATTR_FRAMESPACING; if (!helm->HasAttr(ATTR_FRAMESPACING)) { if (helm->HasAttr(ATTR_BORDER)) frame_spacing_attr = ATTR_BORDER; else frame_spacing_attr = 0; } if (frame_spacing_attr) { frame_spacing = helm->GetNumAttr(frame_spacing_attr); if (frame_spacing == 0) { SetFrameBorder(FALSE); check_parent_frame_border = FALSE; } } else if (parent_frmset) frame_spacing = parent_frmset->GetFrameSpacing(); else frame_spacing = FRAME_BORDER_SIZE; if (helm->HasAttr(ATTR_FRAMEBORDER)) SetFrameBorder(helm->GetBoolAttr(ATTR_FRAMEBORDER)); else if (check_parent_frame_border && parent_frmset) SetFrameBorder(parent_frmset->GetFrameBorder()); } else { SetIsFrameset(TRUE); SetFrameNoresize(TRUE); frame_scrolling = SCROLLING_AUTO; frame_margin_width = 0; frame_margin_height = 0; //frameset_border = 0; } pos.SetTranslation(0, 0); width = 0; height = 0; packed1.size_type = type; size_val = val; SetIsRow(TRUE); if (frm_dev) frm_dev->SetScrollType(normal_frames_mode ? (VisualDevice::ScrollType) frame_scrolling : VisualDevice::VD_SCROLLING_NO); } void FramesDocElm::CheckSpecialObject(HTML_Element* he) { if (he && he->IsMatchingType(HE_OBJECT, NS_HTML)) { const uni_char* class_id = he->GetStringAttr(ATTR_CLASSID); if (class_id && uni_stri_eq(class_id, "HTTP://WWW.OPERA.COM/ERA")) { for (HTML_Element* child = he->FirstChild(); child; child = child->Suc()) if (child->IsMatchingType(HE_PARAM, NS_HTML)) { const uni_char* param_name = child->GetPARAM_Name(); if (param_name && uni_stri_eq(param_name, "RM")) { packed1.special_object = 1; packed1.special_object_layout_mode = LAYOUT_NORMAL; const uni_char* param_value = child->GetPARAM_Value(); if (param_value) { if (uni_stri_eq(param_value, "1")) packed1.special_object_layout_mode = LAYOUT_SSR; else if (uni_stri_eq(param_value, "2")) packed1.special_object_layout_mode = LAYOUT_CSSR; else if (uni_stri_eq(param_value, "3")) packed1.special_object_layout_mode = LAYOUT_AMSR; else if (uni_stri_eq(param_value, "4")) packed1.special_object_layout_mode = LAYOUT_MSR; #ifdef TV_RENDERING else if (uni_stri_eq(param_value, "5")) packed1.special_object_layout_mode = LAYOUT_TVR; #endif // TV_RENDERING } } } } } } /*virtual*/ void FramesDocElm::FDEElmRef::OnDelete(FramesDocument *document) { m_fde->DetachHtmlElement(); if (m_fde->IsInlineFrame() && (!document || !document->IsPrintCopyBeingDeleted())) { m_fde->Out(); FramesDocument *doc = m_fde->GetCurrentDoc(); /* This function might be called from a script executing in the iframe or during reflow, in which case the iframe must be deleted later. */ if (document && doc && (doc->IsESActive(TRUE) || doc->IsReflowing())) document->DeleteIFrame(m_fde); else OP_DELETE(m_fde); } } FramesDocElm::FramesDocElm(int id, int x, int y, int w, int h, FramesDocument* frm_doc, HTML_Element* he, VisualDevice* vd, int type, int val, BOOL inline_frm, FramesDocElm* parent_frmset, BOOL secondary) : m_helm(this) { OP_ASSERT(frm_doc); OP_ASSERT(!he || he->GetInserted() != HE_INSERTED_BY_PARSE_AHEAD); packed1_init = 0; parent_frm_doc = frm_doc; parent_layout_input_ctx = NULL; packed1.is_inline = inline_frm; packed1.is_in_doc_coords = inline_frm; packed1.is_secondary = secondary; packed1.normal_row = TRUE; sub_win_id = id; doc_manager = NULL; frm_dev = NULL; if (he && !secondary) { #ifdef _DEBUG OP_ASSERT(FramesDocElm::GetFrmDocElmByHTML(he) == NULL || !"The element we create a FramesDocElm for already has a FramesDocElm. Doh"); #endif // _DEBUG CheckSpecialObject(he); } #ifdef _PRINT_SUPPORT_ m_print_twin_elm = NULL; #endif // _PRINT_SUPPORT_ Reset(type, val, parent_frmset, he); /* FIXME: VIEWPORT_SUPPORT should make sure that the following coordinates are scaled according to IsInDocCoords() (if anyone cares, that is). */ pos.SetTranslation(x, y); width = w; height = h; #ifndef MOUSELESS drag_val = 0; drag_offset = 0; #endif // !MOUSELESS normal_width = w; normal_height = h; reinit_data = NULL; // turn off scrolling if this is a frame generated by an object element in mail window if (he && inline_frm && he->IsMatchingType(HE_OBJECT, NS_HTML) && vd && vd->GetWindow()->IsMailOrNewsfeedWindow()) frame_scrolling = SCROLLING_NO; frame_index = FRAME_NOT_IN_ROOT; } FramesDocElm::~FramesDocElm() { packed1.is_being_deleted = TRUE; FramesDocument* top_doc = parent_frm_doc->GetTopDocument(); top_doc->FramesDocElmDeleted(this); parent_frm_doc->GetMessageHandler()->UnsetCallBack(parent_frm_doc, MSG_REINIT_FRAME, (MH_PARAM_1) this); RemoveReinitData(); if (m_helm.GetElm()) DetachHtmlElement(); OP_DELETE(doc_manager); OP_DELETE(frm_dev); } AffinePos FramesDocElm::ToDocIfScreen(const AffinePos& val) const { if (IsInDocCoords()) return val; else { VisualDevice* vis_dev = doc_manager->GetWindow()->VisualDev(); return vis_dev->ScaleToDoc(val); } } int FramesDocElm::ToDocIfScreen(int val, BOOL round_up) const { if (IsInDocCoords()) return val; else { VisualDevice* vis_dev = doc_manager->GetWindow()->VisualDev(); int result = vis_dev->ScaleToDoc(val); if (round_up) result = vis_dev->ApplyScaleRoundingNearestUp(result); return result; } } int FramesDocElm::ToScreenIfScreen(int val, BOOL round_up) const { if (IsInDocCoords()) return val; else { VisualDevice* vis_dev = doc_manager->GetWindow()->VisualDev(); int result = vis_dev->ScaleToScreen(val); if (round_up) result = vis_dev->ApplyScaleRoundingNearestUp(result); return result; } } AffinePos FramesDocElm::GetDocOrScreenAbsPos() const { if (Parent() && Parent()->Parent()) { AffinePos parent_pos = Parent()->GetDocOrScreenAbsPos(); parent_pos.Append(pos); return parent_pos; } return pos; } int FramesDocElm::GetDocOrScreenAbsX() const { OpPoint abs_pos = GetDocOrScreenAbsPos().GetTranslation(); return abs_pos.x; } int FramesDocElm::GetDocOrScreenAbsY() const { OpPoint abs_pos = GetDocOrScreenAbsPos().GetTranslation(); return abs_pos.y; } AffinePos FramesDocElm::GetPos() const { return ToDocIfScreen(pos); } int FramesDocElm::GetX() const { return ToDocIfScreen(pos.GetTranslation().x, FALSE); } int FramesDocElm::GetY() const { return ToDocIfScreen(pos.GetTranslation().y, FALSE); } void FramesDocElm::SetX(int x) { OpPoint new_pos = pos.GetTranslation(); new_pos.x = ToScreenIfScreen(x, FALSE); pos.SetTranslation(new_pos.x, new_pos.y); } void FramesDocElm::SetY(int y) { OpPoint new_pos = pos.GetTranslation(); new_pos.y = ToScreenIfScreen(y, FALSE); pos.SetTranslation(new_pos.x, new_pos.y); } OP_STATUS FramesDocElm::Init(HTML_Element *helm, VisualDevice* vd, OpView* clipview) { /* NOTE: GetHtmlElement() will return NULL for the secondary objects created per row in BuildTree() if both rows and cols attributes were specified. This is fully compatible with what this function currently uses 'helm' for, but beware when changing this function! */ if (helm) { OP_ASSERT(!packed1.is_secondary); SetHtmlElement(helm); RETURN_IF_ERROR(SetName(helm->GetStringAttr(ATTR_NAME))); RETURN_IF_MEMORY_ERROR(frame_id.Set(helm->GetId())); } doc_manager = OP_NEW(DocumentManager, (parent_frm_doc->GetWindow(), this, parent_frm_doc)); if (!doc_manager || OpStatus::IsMemoryError(doc_manager->Construct())) return OpStatus::ERR_NO_MEMORY; if (vd && helm && helm->Type() != HE_FRAMESET #ifdef _PRINT_SUPPORT_ && !vd->IsPrinter() #endif ) { VisualDevice::ScrollType scroll_type = (VisualDevice::ScrollType) frame_scrolling; if (GetParentFramesDoc()->GetFramesStacked()) scroll_type = VisualDevice::VD_SCROLLING_NO; if (!IsInlineFrame() && GetParentFramesDoc()->GetSmartFrames()) scroll_type = VisualDevice::VD_SCROLLING_NO; OP_STATUS result = vd->GetNewVisualDevice(frm_dev, doc_manager, scroll_type, vd->GetView()); if (OpStatus::IsError(result)) return result; doc_manager->SetVisualDevice(frm_dev); BOOL hide = FALSE; # ifdef _PRINT_SUPPORT_ // In preview mode we don't want more than one visible visual device, // otherwise the frames will not be shown, since we only use one // visual device for drawing even if there are frames in the document. if (vd->GetWindow()->GetPreviewMode()) //rg test with printing from preview. hide = TRUE; # endif // _PRINT_SUPPORT_ // Have to set IFRAMES as hidden by default because they are not hidden until // formatting is done. For empty IFRAMES with "visibility: hidden" formatting will // never be done. if (helm->IsMatchingType(HE_IFRAME, NS_HTML) && frm_dev) hide = TRUE; if (hide) Hide(FALSE); } else frm_dev = NULL; return OpStatus::OK; } #ifndef MOUSELESS FramesDocElm* FramesDocElm::IsSeparator(int x, int y/*, int border*/) { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) { if (doc->IsFrameDoc()) { FramesDocElm* fde = doc->GetFrmDocRoot(); if (fde) return fde->IsSeparator(x, y/*, fde->Border()*/); } return 0; } else { FramesDocElm* fde = FirstChild(); while (fde) { if (IsRow()) { if (y > fde->GetY() && y < fde->GetY() + fde->GetHeight()) return fde->IsSeparator(x, y - fde->GetY()); } else if (x > fde->GetX() && x < fde->GetX() + fde->GetWidth()) return fde->IsSeparator(x - fde->GetX(), y); FramesDocElm* prev_fde = fde->Pred(); if (prev_fde && prev_fde->CanResize() && fde->CanResize()) { if (IsRow()) { if (y <= fde->GetY() && y >= prev_fde->GetY() + prev_fde->GetHeight()) return fde; } else if (x <= fde->GetX() && x >= prev_fde->GetX() + prev_fde->GetWidth()) return fde; } fde = fde->Suc(); } } return 0; } void FramesDocElm::StartMoveSeparator(int x, int y) { FramesDocElm* prnt = Parent(); if (!prnt) return; int border = 0; FramesDocElm* prev_fde = Pred(); if (prnt->IsRow()) { if (prev_fde) border = GetY() - prev_fde->GetY() - prev_fde->GetHeight(); drag_val = GetAbsY() - border; drag_offset = drag_val - y; } else { if (prev_fde) border = GetX() - prev_fde->GetX() - prev_fde->GetWidth(); drag_val = GetAbsX() - border; drag_offset = drag_val - x; } MoveSeparator(x, y); } void FramesDocElm::MoveSeparator(int x, int y) { FramesDocElm* prnt = Parent(); if (!prnt) return; int border = 0; FramesDocElm* fde = Pred(); if (prnt->IsRow()) { if (fde) border = GetY() - fde->GetY() - fde->GetHeight(); int prnt_absy = prnt->GetAbsY(); int use_y = y - prnt_absy + drag_offset; if (use_y < GetY()) { // check min pos fde = Pred(); if (fde) { int p_min_y = fde->GetMinHeight() + fde->GetY() + border; if (use_y < p_min_y) use_y = p_min_y; } else if (use_y < 0) use_y = 0; } else if (use_y > GetY()) { // check max pos int max_y = GetMaxY() - border; if (use_y > max_y) use_y = max_y; } if (use_y != GetY()) { drag_val = prnt_absy + use_y; Reformat(x, y + drag_offset); } } else { if (fde) border = GetX() - fde->GetX() - fde->GetWidth(); int prnt_absx = prnt->GetAbsX(); int use_x = x - prnt_absx + drag_offset; if (use_x < GetX()) { // check min pos fde = Pred(); if (fde) { int p_min_x = fde->GetMinWidth() + fde->GetX() + border; if (use_x < p_min_x) use_x = p_min_x; } else if (use_x < 0) use_x = 0; } else if (use_x > GetX()) { // check max pos int max_x = GetMaxX() - border; if (use_x > max_x) use_x = max_x; } if (use_x != GetX()) { drag_val = prnt_absx + use_x; Reformat(x + drag_offset, y); } } } void FramesDocElm::Reformat(int x, int y) { FramesDocElm* prnt = Parent(); if (!prnt) return; int border = 0; FramesDocElm* prev_fde = Pred(); if (prev_fde) { if (prnt->IsRow()) border = GetY() - prev_fde->GetY() - prev_fde->GetHeight(); else border = GetX() - prev_fde->GetX() - prev_fde->GetWidth(); } if (prnt->IsRow()) SetY(drag_val - prnt->GetAbsY() + border); else SetX(drag_val - prnt->GetAbsX() + border); // set new width if changed BOOL reformat = FALSE; if (prnt->IsRow()) { int new_height; if (Suc()) new_height = Suc()->GetY() - GetY() - border; else new_height = prnt->GetHeight() - GetY(); if (new_height != GetHeight()) { reformat = TRUE; SetGeometry(GetPos(), GetWidth(), new_height); if (prev_fde) prev_fde->SetGeometry(prev_fde->GetPos(), prev_fde->GetWidth(), GetY() - prev_fde->GetY() - border); } } else { int new_width; if (Suc()) new_width = Suc()->GetX() - GetX() - border; else new_width = prnt->GetWidth() - GetX(); if (new_width != GetWidth()) { reformat = TRUE; SetGeometry(GetPos(), new_width, GetHeight()); if (prev_fde) prev_fde->SetGeometry(prev_fde->GetPos(), GetX() - prev_fde->GetX() - border, prev_fde->GetHeight()); } } // propagate sizes and reformat this and previous frame if necessary if (reformat) { OP_STATUS status = OpStatus::OK; OpStatus::Ignore(status); if (prev_fde) { prev_fde->PropagateSizeChanges(FALSE, !prnt->IsRow(), FALSE, prnt->IsRow()/*, border*/); // Make sure that changes are propagated to hidden children if (prev_fde->GetCurrentDoc()) { if (prev_fde->FormatFrames(prnt->IsRow(), !prnt->IsRow()) == OpStatus::ERR_NO_MEMORY) status = OpStatus::ERR_NO_MEMORY; } } PropagateSizeChanges(!prnt->IsRow(), FALSE, prnt->IsRow(), FALSE/*, border*/); FramesDocument* doc = GetCurrentDoc(); // Make sure that changes are propagated to hidden children if (doc) { if (FormatFrames(prnt->IsRow(), !prnt->IsRow()) == OpStatus::ERR_NO_MEMORY) status = OpStatus::ERR_NO_MEMORY; } while (prnt->Parent()) prnt = prnt->Parent(); if (status == OpStatus::ERR_NO_MEMORY) GetWindow()->RaiseCondition(status); } } void FramesDocElm::EndMoveSeparator(int x, int y) //, int border) { FramesDocElm* prnt = Parent(); if (!prnt) return; Reformat(x, y); } BOOL FramesDocElm::CanResize() { BOOL can_resize = TRUE; FramesDocElm* fde = FirstChild(); if (fde) { while (can_resize && fde) { can_resize = fde->CanResize(); fde = fde->Suc(); } } else can_resize = !GetFrameNoresize(); return can_resize; } int FramesDocElm::GetMaxX() { int max_x = GetWidth(); FramesDocElm* fde = FirstChild(); if (IsRow()) { while (fde) { int x = fde->GetMaxX(); if (x < max_x) max_x = x; fde = fde->Suc(); } } else if (fde) max_x = fde->GetMaxX(); return max_x + GetX(); } int FramesDocElm::GetMaxY() { int max_y = GetHeight(); FramesDocElm* fde = FirstChild(); if (!IsRow()) { while (fde) { int y = fde->GetMaxY(); if (y < max_y) max_y = y; fde = fde->Suc(); } } else if (fde) max_y = fde->GetMaxY(); return max_y + GetY(); } int FramesDocElm::GetMinWidth() { int min_w = 0; FramesDocElm* fde = FirstChild(); if (IsRow()) { while (fde) { int w = fde->GetMinWidth(); if (w > min_w) min_w = w; fde = fde->Suc(); } } else if (fde) min_w = fde->GetMinWidth(); return min_w; } int FramesDocElm::GetMinHeight() { int min_h = 0; FramesDocElm* fde = FirstChild(); if (!IsRow()) { while (fde) { int h = fde->GetMinHeight(); if (h > min_h) min_h = h; fde = fde->Suc(); } } else if (fde) min_h = fde->GetMinHeight(); return min_h; } #endif // !MOUSELESS BOOL FramesDocElm::IsInDocCoords() const { if (packed1.is_in_doc_coords) return TRUE; return doc_manager->GetWindow()->GetTrueZoom(); } AffinePos FramesDocElm::GetAbsPos() const { return ToDocIfScreen(GetDocOrScreenAbsPos()); } int FramesDocElm::GetAbsX() const { return ToDocIfScreen(GetDocOrScreenAbsX(), FALSE); } int FramesDocElm::GetAbsY() const { return ToDocIfScreen(GetDocOrScreenAbsY(), FALSE); } int FramesDocElm::GetWidth() const { return ToDocIfScreen(width, TRUE); } int FramesDocElm::GetHeight() const { return ToDocIfScreen(height, TRUE); } int FramesDocElm::GetNormalWidth() const { return ToDocIfScreen(normal_width, TRUE); } int FramesDocElm::GetNormalHeight() const { return ToDocIfScreen(normal_height, TRUE); } void FramesDocElm::SetPosition(const AffinePos& doc_pos) { if (IsInDocCoords()) { pos = doc_pos; } else { VisualDevice* vis_dev = GetWindow()->VisualDev(); pos = vis_dev->ScaleToScreen(doc_pos); } UpdateGeometry(); } void FramesDocElm::SetSize(int w, int h) { if (IsInDocCoords()) { width = w; height = h; normal_width = w; normal_height = h; } else { VisualDevice* vis_dev = GetWindow()->VisualDev(); width = vis_dev->ScaleToScreen(w); height = vis_dev->ScaleToScreen(h); normal_width = vis_dev->ScaleToScreen(w); normal_height = vis_dev->ScaleToScreen(h); } if (FramesDocument* doc = GetCurrentDoc()) doc->RecalculateLayoutViewSize(TRUE); // FIXME: assuming "user action" UpdateGeometry(); } void FramesDocElm::SetGeometry(const AffinePos& doc_pos, int w, int h) { if (IsInDocCoords()) { pos = doc_pos; width = w; height = h; normal_width = w; normal_height = h; } else { VisualDevice* vis_dev = GetWindow()->VisualDev(); pos = vis_dev->ScaleToScreen(doc_pos); width = vis_dev->ScaleToScreen(w); height = vis_dev->ScaleToScreen(h); normal_width = vis_dev->ScaleToScreen(w); normal_height = vis_dev->ScaleToScreen(h); } if (FramesDocument* doc = GetCurrentDoc()) doc->RecalculateLayoutViewSize(TRUE); // FIXME: assuming "user action" UpdateGeometry(); } void FramesDocElm::ForceHeight(int h) { if (IsInDocCoords()) height = h; else { VisualDevice* vis_dev = GetWindow()->VisualDev(); height = vis_dev->ScaleToScreen(h); } UpdateGeometry(); } OP_STATUS FramesDocElm::ShowFrames() { if (frm_dev) { BOOL update_scrollbar = !frm_dev->GetVisible(); RETURN_IF_ERROR(Show()); #ifdef SVG_SUPPORT SVGCheckWantMouseEvents(); #endif // SVG_SUPPORT if (update_scrollbar) frm_dev->UpdateScrollbars(); } for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) RETURN_IF_ERROR(fde->ShowFrames()); return OpStatus::OK; } void FramesDocElm::HideFrames() { Hide(FALSE); for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->HideFrames(); } void FramesDocElm::UpdateGeometry() { if (frm_dev) { VisualDevice* parent_vd = GetParentFramesDoc()->GetVisualDevice(); OP_ASSERT(parent_vd); if (!parent_vd) return; int view_x = parent_vd->ScaleToScreen(parent_vd->GetRenderingViewX()); int view_y = parent_vd->ScaleToScreen(parent_vd->GetRenderingViewY()); int old_rendering_width = frm_dev->GetRenderingViewWidth(); int old_rendering_height = frm_dev->GetRenderingViewHeight(); AffinePos doc_or_screen_pos = GetDocOrScreenAbsPos(); AffinePos screen_pos; int width_screen_coords; int height_screen_coords; if (IsInDocCoords()) { screen_pos = frm_dev->ScaleToScreen(doc_or_screen_pos); #ifdef CSS_TRANSFORMS // If page is zoomed, we don't want to apply the // zoom/scalefactor to the width/height, but to the // transform. if (screen_pos.IsTransform()) { width_screen_coords = width; height_screen_coords = height; } else #endif // CSS_TRANSFORMS { width_screen_coords = frm_dev->ScaleToScreen(width); height_screen_coords = frm_dev->ScaleToScreen(height); } } else { screen_pos = doc_or_screen_pos; width_screen_coords = width; height_screen_coords = height; } AffinePos view_ctm(-view_x, -view_y); screen_pos.Prepend(view_ctm); frm_dev->SetRenderingViewGeometryScreenCoords(screen_pos, width_screen_coords, height_screen_coords); if (FramesDocument* doc = GetCurrentDoc()) if (old_rendering_width != frm_dev->GetRenderingViewWidth() || old_rendering_height != frm_dev->GetRenderingViewHeight()) if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::ShowActiveFrame, doc->GetHostName())) { DocumentManager* top_doc_man = doc_manager->GetWindow()->DocManager(); if (FramesDocument* top_frames_doc = top_doc_man->GetCurrentDoc()) if (FramesDocument* active_doc = top_frames_doc->GetActiveSubDoc()) if (active_doc == doc) // Make sure that the frame border is updated. frm_dev->UpdateAll(); } } } FramesDocElm* FramesDocElm::Parent() const { if (packed1.is_deleted) return NULL; return (FramesDocElm *) Tree::Parent(); } #ifndef MOUSELESS void FramesDocElm::PropagateSizeChanges(BOOL left, BOOL right, BOOL top, BOOL bottom/*, int border*/) { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (!doc) { FramesDocElm* fde, *prev_fde; if (IsRow()) { if (bottom) { // update last child height fde = LastChild(); if (fde) if (fde->GetHeight() != GetHeight() - fde->GetY()) { fde->SetGeometry(fde->GetPos(), fde->GetWidth(), GetHeight() - fde->GetY()); fde->PropagateSizeChanges(left, right, top, bottom); } } else if (top) { // update all child y pos prev_fde = 0; for (fde = LastChild(); fde; fde = fde->Pred()) { int old_h = fde->GetHeight(); int new_h = old_h; if (!fde->Pred()) { // update first child y pos and height fde->SetY(0); if (prev_fde) new_h = prev_fde->GetY() - GetFrameSpacing(); else new_h = GetHeight(); } else if (prev_fde) fde->SetY(prev_fde->GetY() - fde->GetHeight() - GetFrameSpacing()); else fde->SetY(GetHeight() - fde->GetHeight()); if (old_h != new_h) { fde->SetSize(fde->GetWidth(), new_h); fde->PropagateSizeChanges(left, right, top, bottom); } prev_fde = fde; } } else if (left || right) for (fde = FirstChild(); fde; fde = fde->Suc()) { if (fde->GetWidth() == GetWidth()) break; // all widths equal // update all child width fde->SetSize(GetWidth(), fde->GetHeight()); fde->PropagateSizeChanges(left, right, top, bottom); } } else { if (right) { // update last child width fde = LastChild(); if (fde) if (fde->GetWidth() != GetWidth() - fde->GetX()) { fde->SetSize(GetWidth() - fde->GetX(), fde->GetHeight()); fde->PropagateSizeChanges(left, right, top, bottom); } } else if (left) { // update all child x pos prev_fde = 0; for (fde = LastChild(); fde; fde = fde->Pred()) { int old_w = fde->GetWidth(); int new_w = old_w; if (!fde->Pred()) { // update first child x pos and width fde->SetX(0); if (prev_fde) new_w = prev_fde->GetX() - GetFrameSpacing(); else new_w = GetWidth(); } else if (prev_fde) fde->SetX(prev_fde->GetX() - fde->GetWidth() - GetFrameSpacing()); else fde->SetX(GetWidth() - fde->GetWidth()); if (old_w != new_w) { fde->SetSize(new_w, fde->GetHeight()); fde->PropagateSizeChanges(left, right, top, bottom); } prev_fde = fde; } } else if (top || bottom) for (fde = FirstChild(); fde; fde = fde->Suc()) { if (fde->GetHeight() == GetHeight()) break; // all heights equal // update all child height fde->SetSize(fde->GetWidth(), GetHeight()); fde->PropagateSizeChanges(left, right, top, bottom); } } } } #endif // !MOUSELESS DocListElm* FramesDocElm::GetHistoryElmAt(int pos, BOOL forward) { if (doc_manager) { DocListElm *tmp_dle = doc_manager->CurrentDocListElm(); if (tmp_dle) { if (forward) { while (tmp_dle && tmp_dle->Number() < pos) tmp_dle = tmp_dle->Suc(); } else // forward { while (tmp_dle && tmp_dle->Number() > pos) tmp_dle = tmp_dle->Pred(); } if (tmp_dle) { if (tmp_dle->Number() == pos) return tmp_dle; else return tmp_dle->Doc()->GetHistoryElmAt(pos, forward); } } FramesDocElm *tmp_fde = FirstChild(); while (tmp_fde) { tmp_dle = tmp_fde->GetHistoryElmAt(pos, forward); if (tmp_dle) return tmp_dle; tmp_fde = tmp_fde->Suc(); } } return NULL; } void FramesDocElm::CheckHistory(int decrement, int& minhist, int& maxhist) { doc_manager->CheckHistory(decrement, minhist, maxhist); FramesDocElm *fde = FirstChild(); while (fde) { fde->CheckHistory(decrement, minhist, maxhist); fde = fde->Suc(); } } void FramesDocElm::RemoveFromHistory(int from) { doc_manager->RemoveFromHistory(from); FramesDocElm *fde = FirstChild(); while (fde) { fde->RemoveFromHistory(from); fde = fde->Suc(); } } void FramesDocElm::RemoveUptoHistory(int to) { doc_manager->RemoveUptoHistory(to); FramesDocElm *fde = FirstChild(); while (fde) { fde->RemoveUptoHistory(to); fde = fde->Suc(); } } void FramesDocElm::RemoveElementFromHistory(int pos) { doc_manager->RemoveElementFromHistory(pos); FramesDocElm *fde = FirstChild(); while (fde) { fde->RemoveElementFromHistory(pos); fde = fde->Suc(); } } HTML_Element *FramesDocElm::GetHtmlElement() { OP_PROBE4(OP_PROBE_FDELM_GETHTMLELEMENT); if (packed1.is_secondary) return Parent() ? Parent()->GetHtmlElement() : NULL; return m_helm.GetElm(); } void FramesDocElm::SetHtmlElement(HTML_Element *elm) { OP_ASSERT(m_helm.GetElm() == NULL); m_helm.SetElm(elm); } void FramesDocElm::DetachHtmlElement() { OP_ASSERT(m_helm.GetElm()); m_helm.Reset(); } const uni_char* FramesDocElm::GetName() { return name.CStr(); } OP_STATUS FramesDocElm::SetName(const uni_char* str) { return name.Set(str); } OP_STATUS FramesDocElm::Undisplay(BOOL will_be_destroyed) { FramesDocument* doc = doc_manager->GetCurrentDoc(); OP_STATUS status = OpStatus::OK; if (doc) status = doc->Undisplay(will_be_destroyed); else for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) if (fde->Undisplay(will_be_destroyed) == OpStatus::ERR_NO_MEMORY) status = OpStatus::ERR_NO_MEMORY; return status; } OP_STATUS FramesDocElm::Show() { if (frm_dev) RETURN_IF_ERROR(frm_dev->Show(parent_frm_doc->GetVisualDevice()->GetView())); return OpStatus::OK; } void FramesDocElm::Hide(BOOL free_views /*= FALSE*/) { if (frm_dev) frm_dev->Hide(free_views); } void FramesDocElm::CheckFrameEdges(BOOL& outer_top, BOOL& outer_left, BOOL& outer_right, BOOL& outer_bottom, BOOL top_checked, BOOL left_checked, BOOL right_checked, BOOL bottom_checked) { if (!IsFrameset()) { outer_top = TRUE; outer_left = TRUE; outer_right = TRUE; outer_bottom = TRUE; } FramesDocElm* prnt = Parent(); if (prnt) { if (prnt->IsRow()) { if (!top_checked && Pred()) { outer_top = FALSE; top_checked = TRUE; } if (!bottom_checked && Suc()) { outer_bottom = FALSE; bottom_checked = TRUE; } } else { if (!left_checked && Pred()) { outer_left = FALSE; left_checked = TRUE; } if (!right_checked && Suc()) { outer_right = FALSE; right_checked = TRUE; } } prnt->CheckFrameEdges(outer_top, outer_left, outer_right, outer_bottom, top_checked, left_checked, right_checked, bottom_checked); } } OP_STATUS FramesDocElm::ReactivateDocument() { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) return doc->ReactivateDocument(); OP_STATUS stat = OpStatus::OK; for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) if (fde->ReactivateDocument() == OpStatus::ERR_NO_MEMORY) stat = OpStatus::ERR_NO_MEMORY; return stat; } BOOL FramesDocElm::IsLoaded(BOOL inlines_loaded) { if (!doc_manager->IsCurrentDocLoaded(inlines_loaded)) return FALSE; for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) if (!fde->IsLoaded(inlines_loaded)) return FALSE; return TRUE; } void FramesDocElm::SetInlinesUsed(BOOL used) { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) doc->SetInlinesUsed(used); for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->SetInlinesUsed(used); } void FramesDocElm::Free(BOOL layout_only/*=FALSE*/, FramesDocument::FreeImportance free_importance /*= FramesDocument::UNIMPORTANT*/) { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) doc->Free(layout_only, free_importance); else for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->Free(layout_only, free_importance); } OP_BOOLEAN FramesDocElm::CheckSource() { FramesDocument* doc = doc_manager->GetCurrentDoc(); OP_BOOLEAN stat = OpStatus::OK; if (doc) stat = doc->CheckSource(); else for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) { stat = fde->CheckSource(); if (OpStatus::IsError(stat)) break; } return stat; } void FramesDocElm::StopLoading(BOOL format, BOOL abort/*=FALSE*/) { doc_manager->StopLoading(format, FALSE, abort); for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->StopLoading(format, abort); } OP_STATUS FramesDocElm::SetMode(BOOL win_show_images, BOOL win_load_images, CSSMODE win_css_mode, CheckExpiryType check_expiry) { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) { if (!frm_dev->GetView()) { RETURN_IF_ERROR(Show()); } doc_manager->SetCheckExpiryType(check_expiry); return doc->SetMode(win_show_images, win_load_images, win_css_mode, check_expiry); } else { for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) if (fde->SetMode(win_show_images, win_load_images, win_css_mode, check_expiry) == OpStatus::ERR_NO_MEMORY) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } } OP_STATUS FramesDocElm::SetAsCurrentDoc(BOOL state, BOOL visible_if_current) { if (!state || GetCurrentDoc() && !GetCurrentDoc()->IsCurrentDoc()) SetOnLoadCalled(FALSE); OP_STATUS stat = doc_manager->UpdateCallbacks(state); FramesDocElm* fde = FirstChild(); FramesDocument* doc = doc_manager->GetCurrentDoc(); if (!fde || doc) { if (doc && !state) { stat = doc->Undisplay(); if (doc->SetAsCurrentDoc(state, visible_if_current) == OpStatus::ERR_NO_MEMORY) stat = OpStatus::ERR_NO_MEMORY; } if (OpStatus::IsError(stat)) return stat; if (frm_dev) { if (doc && doc->IsFrameDoc() || (IsInlineFrame() || !doc || !doc->IsFrameDoc()) && (!state || visible_if_current)) { if (state) RETURN_IF_ERROR(Show()); else Hide(TRUE); } } if (doc && state) stat = doc->SetAsCurrentDoc(state, visible_if_current); } else { // check if any windows even if no document if (frm_dev && (!IsInlineFrame() || !state)) Hide(TRUE); for (; fde; fde = fde->Suc()) if (OpStatus::IsMemoryError(fde->SetAsCurrentDoc(state, visible_if_current))) stat = OpStatus::ERR_NO_MEMORY; } return stat; } void FramesDocElm::ReloadIfModified() { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (!IsFrameset()) { if (doc) { URL doc_url = doc->GetURL(); DocumentReferrer doc_ref_url = doc->GetRefURL(); doc_manager->OpenURL(doc_url, doc_ref_url, TRUE, TRUE, FALSE, FALSE, NotEnteredByUser, FALSE, TRUE); } else { // FIXME: OOM LoadFrames(); } } else { OP_ASSERT(!doc); FramesDocElm* fde = FirstChild(); if (fde) { for (; fde; fde = fde->Suc()) fde->ReloadIfModified(); } else FramesDocument::CheckOnLoad(NULL, this); } } int ScaleToMSR(int val, FramesDocument* doc, BOOL row) { if (row) return (val * doc->GetLayoutViewHeight()) / 600; else return (val * doc->GetLayoutViewWidth()) / 800; } FramesDocElm* FindFramesDocElm(Head* existing_frames, HTML_Element* he) { for (FramesDocElm* fde = (FramesDocElm*) existing_frames->Last(); fde; fde = (FramesDocElm*) fde->Pred()) if (fde->GetHtmlElement() == he) { fde->Out(); return fde; } return NULL; } OP_STATUS FramesDocElm::BuildTree(FramesDocument* top_frm_doc, Head* existing_frames) { OP_STATUS stat = DocStatus::DOC_CANNOT_FORMAT; OpStatus::Ignore(stat); if (HTML_Element *helm = GetHtmlElement()) { if (helm->IsMatchingType(HE_FRAME, NS_HTML)) return DocStatus::DOC_FORMATTING; else if (helm->IsMatchingType(HE_FRAMESET, NS_HTML)) { const uni_char* row_spec = helm->GetFramesetRowspec(); const uni_char* col_spec = helm->GetFramesetColspec(); VisualDevice* parent_vd = GetParentFramesDoc()->GetVisualDevice(); if (row_spec && col_spec) { //not a tree // 22/04/97: changed this to take rows first since Netscape 3.01 always takes rows first int first_count = helm->GetFramesetRowCount(); int next_count = helm->GetFramesetColCount(); SetIsRow(TRUE); SetNormalRow(TRUE); int first_child_count = 0; HTML_Element* he = helm->FirstChildActual(); while (he && first_child_count < first_count) { if (he->GetNsType() != NS_HTML || (he->Type() != HE_FRAMESET && he->Type() != HE_FRAME)) { he = he->SucActual(); continue; } int val = 1; int type = FRAMESET_RELATIVE_SIZED; helm->GetFramesetRow(first_child_count++, val, type); FramesDocElm* felm = NULL; if (existing_frames) felm = FindFramesDocElm(existing_frames, helm); if (felm) felm->Reset(type, val, this, helm); else { felm = OP_NEW(FramesDocElm, (top_frm_doc->GetNewSubWinId(), 0, 0, 0, 0, GetParentFramesDoc(), helm, parent_vd, type, val, FALSE, this, TRUE)); if (!felm) return DocStatus::ERR_NO_MEMORY; if (OpStatus::IsError(felm->Init(NULL, parent_vd, NULL))) { OP_DELETE((felm)); felm = NULL; return DocStatus::ERR_NO_MEMORY; } } felm->Under(this); felm->SetIsRow(FALSE); felm->SetNormalRow(FALSE); if (GetParentFramesDoc()->GetFramesStacked()) felm->SetIsRow(TRUE); int next_child_count = 0; while (he && next_child_count < next_count) { if (he->GetNsType() == NS_HTML && (he->Type() == HE_FRAMESET || he->Type() == HE_FRAME)) { int val = 1; int type = FRAMESET_RELATIVE_SIZED; helm->GetFramesetCol(next_child_count++, val, type); FramesDocElm* new_felm = NULL; if (existing_frames) new_felm = FindFramesDocElm(existing_frames, he); if (new_felm) new_felm->Reset(type, val, felm, he); else { new_felm = OP_NEW(FramesDocElm, (top_frm_doc->GetNewSubWinId(), 0, 0, 0, 0, GetParentFramesDoc(), he, parent_vd, type, val, FALSE, felm)); if (!new_felm) return DocStatus::ERR_NO_MEMORY; if (OpStatus::IsError(new_felm->Init(he, parent_vd, NULL))) { OP_DELETE((new_felm)); return DocStatus::ERR_NO_MEMORY; } } new_felm->Under(felm); stat = new_felm->BuildTree(top_frm_doc, existing_frames); } he = he->SucActual(); } } } else { SetIsRow(helm->GetFramesetRowspec() != 0); if (!IsRow()) SetIsRow(helm->GetFramesetColspec() == 0); // default row ??? SetNormalRow(IsRow()); int child_count = 0; for (HTML_Element* he = helm->FirstChildActual(); he; he = he->SucActual()) if (he->GetNsType() == NS_HTML && (he->Type() == HE_FRAMESET || he->Type() == HE_FRAME)) { int val = 100; int type = FRAMESET_PERCENTAGE_SIZED; BOOL has_spec = FALSE; if (IsRow()) has_spec = helm->GetFramesetRow(child_count++, val, type); else has_spec = helm->GetFramesetCol(child_count++, val, type); // ignore children outside the rowspec/colspec if specified if (has_spec || (IsRow() && !row_spec && child_count == 1) || (!IsRow() && !col_spec && child_count == 1)) { FramesDocElm* felm = NULL; if (existing_frames) felm = FindFramesDocElm(existing_frames, he); if (felm) felm->Reset(type, val, this, he); else { felm = OP_NEW(FramesDocElm, (top_frm_doc->GetNewSubWinId(), 0, 0, 0, 0, GetParentFramesDoc(), he, parent_vd, type, val, FALSE, this)); if (!felm) return DocStatus::ERR_NO_MEMORY; if (OpStatus::IsError(felm->Init(he, parent_vd, NULL))) { OP_DELETE((felm)); return DocStatus::ERR_NO_MEMORY; } } felm->Under(this); stat = felm->BuildTree(top_frm_doc, existing_frames); } } } // If we have an empty frameset, call onload because it won't be triggered by any child frames. if (!this->FirstChild()) return FramesDocument::CheckOnLoad(NULL, this); if (GetParentFramesDoc()->GetFramesStacked()) SetIsRow(TRUE); // check percentage int psum = 0; for (FramesDocElm* felm = FirstChild(); felm; felm = felm->Suc()) if (felm->GetSizeType() == FRAMESET_PERCENTAGE_SIZED) psum += felm->size_val; if (psum > 100) for (FramesDocElm* felm = FirstChild(); felm; felm = felm->Suc()) if (felm->GetSizeType() == FRAMESET_PERCENTAGE_SIZED) felm->size_val = (int)(((int)felm->size_val*100) / psum); } } return stat; } void FramesDocElm::SetRootSize(int width, int height) { OP_ASSERT(!frm_dev); OP_ASSERT(!Parent()); this->width = width; this->height = height; this->normal_width = width; this->normal_height = height; } OP_STATUS FramesDocElm::FormatFrames(BOOL format_rows, BOOL format_cols) { OP_STATUS stat = DocStatus::DOC_CANNOT_FORMAT; OpStatus::Ignore(stat); FramesDocElm* inherit_fde = Parent(); if (!inherit_fde) inherit_fde = parent_frm_doc->GetDocManager()->GetFrame(); if (inherit_fde && !packed1.is_in_doc_coords) packed1.is_in_doc_coords = inherit_fde->packed1.is_in_doc_coords; if (!IsFrameset()) { if (GetFrameBorder()) { if (IsInlineFrame()) SetFrameBorders(TRUE, TRUE, TRUE, TRUE); else { BOOL outer_top, outer_left, outer_right, outer_bottom; CheckFrameEdges(outer_top, outer_left, outer_right, outer_bottom); SetFrameBorders(!outer_top, !outer_left, !outer_right, !outer_bottom); } } return DocStatus::DOC_FORMATTING; } else { FramesDocElm* felm; int size_used = 0; BOOL use_doc_coords = IsInDocCoords(); if (!Parent()) if (FramesDocElm* frame = parent_frm_doc->GetDocManager()->GetFrame()) { // Root frameset in a sub-document. Set available size. width = frame->width; height = frame->height; normal_width = frame->normal_width; normal_height = frame->normal_height; } int avail_size = (IsRow()) ? height : width; if (parent_frm_doc->GetSmartFrames()) avail_size = (IsRow()) ? normal_height : normal_width; int abs_size_used = 0; int extra_space = 0; int child_count = 0; int abs_child_count = 0; int rel_childs = 0; int per_val = 0; VisualDevice* top_vis_dev = doc_manager->GetWindow()->VisualDev(); FramesDocument* top_doc = doc_manager->GetWindow()->GetCurrentDoc(); BOOL scale_to_msr = GetLayoutMode() != LAYOUT_NORMAL && GetParentFramesDoc()->GetSmartFrames(); for (felm = FirstChild(); felm; felm = felm->Suc()) { int val = felm->size_val; int type = felm->GetSizeType(); if (scale_to_msr && type == FRAMESET_ABSOLUTE_SIZED) val = ScaleToMSR(val, top_doc, IsRow()); if ((IsRow() && format_rows) || (!IsRow() && format_cols)) { if (type == FRAMESET_ABSOLUTE_SIZED) { if (!use_doc_coords) val = top_vis_dev->ScaleToScreen(val); size_used += val; abs_size_used += val; abs_child_count++; } else if (type == FRAMESET_PERCENTAGE_SIZED) { int use_size = int((avail_size * val) / 100); size_used += use_size; per_val += val; } else rel_childs++; } if (!GetParentFramesDoc()->GetSmartFrames()) if (felm->Pred()) avail_size -= GetFrameSpacing(); child_count++; } if (avail_size < 0) avail_size = 0; int abs_size_avail = abs_size_used; if (abs_size_avail > avail_size || child_count == abs_child_count) abs_size_avail = avail_size; int per_size_avail = ((avail_size * per_val) / 100); if (per_size_avail > avail_size - abs_size_avail) per_size_avail = avail_size - abs_size_avail; int per_count = child_count - abs_child_count - rel_childs; BOOL per2rel = per_count && !rel_childs; if (per2rel) rel_childs = per_count; if (per_count && per_size_avail/per_count < RELATIVE_MIN_SIZE) { if (abs_child_count) { int take_from_abs = RELATIVE_MIN_SIZE * per_count; if (take_from_abs > abs_size_avail/2) take_from_abs = abs_size_avail / 2; abs_size_avail -= take_from_abs; per_size_avail += take_from_abs; } } if (!rel_childs) { extra_space = avail_size - size_used; if (extra_space < 0) extra_space = 0; } BOOL add_to_abs_sized = (avail_size < abs_size_used); size_used = 0; int i = 0; int rel_child_count = 0; int rel_child_val = 0; FramesDocElm* prev_felm = NULL; for (felm = FirstChild(); felm; felm = felm->Suc()) { int val = felm->size_val; int type = felm->GetSizeType(); if (scale_to_msr && type == FRAMESET_ABSOLUTE_SIZED) val = ScaleToMSR(val, top_doc, IsRow()); int new_width = (IsRow()) ? width : felm->width; int new_height = (IsRow()) ? felm->height : height; if ((IsRow() && format_rows) || (!IsRow() && format_cols)) { OpPoint new_pos = felm->pos.GetTranslation(); if (prev_felm) { int frm_ex = 0; if (!GetParentFramesDoc()->GetSmartFrames()) frm_ex += GetFrameSpacing(); OpPoint prev_pos = prev_felm->pos.GetTranslation(); if (IsRow()) new_pos.y = prev_pos.y + prev_felm->height + frm_ex; else new_pos.x = prev_pos.x + prev_felm->width + frm_ex; } felm->pos.SetTranslation(new_pos.x, new_pos.y); if (!felm->Suc() && !rel_childs) { // use rest of space int use_size = (int) (avail_size - size_used); size_used += use_size; if (IsRow()) new_height = use_size; else new_width = use_size; } else { int add_space = 0; if (extra_space && (add_to_abs_sized || type == FRAMESET_PERCENTAGE_SIZED)) { int ccount = child_count-i-rel_childs+rel_child_count; if (!add_to_abs_sized) ccount = child_count-abs_child_count-i-rel_childs+rel_child_count; if (ccount) add_space = (int) (extra_space/ccount); extra_space -= add_space; } if (type == FRAMESET_ABSOLUTE_SIZED) { int use_size = val; if (abs_size_used) use_size = (int)(((int)val * abs_size_avail) / abs_size_used); use_size += add_space; if (use_size < 0) { if (extra_space) extra_space += use_size; use_size = 0; } if (!use_doc_coords) use_size = top_vis_dev->ScaleToScreen(use_size); size_used += use_size; if (IsRow()) new_height = use_size; else new_width = use_size; } else if (type == FRAMESET_PERCENTAGE_SIZED && !per2rel) { int use_size = 0; if (per_val) use_size = (int) ((per_size_avail*val) / per_val); use_size += add_space; if (use_size < 0) { if (extra_space) extra_space += use_size; use_size = 0; } size_used += use_size; if (IsRow()) new_height = use_size; else new_width = use_size; } else { rel_child_count++; rel_child_val += val; } } } // we set the size without redrawing to avoid drawing in wrong position felm->width = new_width; felm->height = new_height; felm->normal_width = new_width; felm->normal_height = new_height; prev_felm = felm; i++; } if ((IsRow() && format_rows) || (!IsRow() && format_cols)) { // set size on relatively sized frames if (rel_child_count && ((!IsRow() && size_used < width) || (IsRow() && size_used < height))) { if (!rel_child_val) rel_child_val = 1; i = 1; float rel_size = ((float)avail_size - size_used) / rel_child_val; prev_felm = NULL; for (felm = FirstChild(); felm; felm = felm->Suc()) { OpPoint new_pos = felm->pos.GetTranslation(); if (prev_felm) { int frm_ex = 0; if (!GetParentFramesDoc()->GetSmartFrames()) frm_ex += GetFrameSpacing(); OpPoint prev_pos = prev_felm->pos.GetTranslation(); if (IsRow()) new_pos.y = prev_pos.y + prev_felm->height + frm_ex; else new_pos.x = prev_pos.x + prev_felm->width + frm_ex; } felm->pos.SetTranslation(new_pos.x, new_pos.y); int new_width = felm->width; int new_height = felm->height; if (felm->GetSizeType() == FRAMESET_RELATIVE_SIZED || (per2rel && felm->GetSizeType() == FRAMESET_PERCENTAGE_SIZED)) { int child_size; if (i == rel_childs) child_size = (int) (avail_size - size_used); // use rest of space else child_size = (int) (rel_size * felm->size_val); if (IsRow()) new_height = child_size; else new_width = child_size; size_used += child_size; i++; } // we set the size without redrawing to avoid drawing in wrong position felm->width = new_width; felm->height = new_height; felm->normal_width = new_width; felm->normal_height = new_height; prev_felm = felm; } } } // format each frame for (felm = FirstChild(); felm; felm = felm->Suc()) { if (parent_frm_doc->GetFramesStacked()) /* Document height (root layout box height) never gets smaller than layout viewport height, and in frame stacking mode, we want frames to take up as little space as possible. Therefore, set layout viewport height to 0. */ felm->normal_height = 0; stat = felm->FormatFrames(format_rows, format_cols); if (FramesDocument* doc = felm->GetCurrentDoc()) doc->RecalculateLayoutViewSize(TRUE); // FIXME: assuming "user action". Is that correct? } } if (stat == DocStatus::DOC_CANNOT_FORMAT) SetOnLoadCalled(TRUE); return stat; } OP_STATUS FramesDocElm::LoadFrames(ES_Thread *origin_thread) { if (IsFrameset()) { for (FramesDocElm* felm = FirstChild(); felm; felm = felm->Suc()) RETURN_IF_ERROR(felm->LoadFrames()); if (!FirstChild()) FramesDocument::CheckOnLoad(NULL, this); } else { URL frm_url; URL about_blank_url = g_url_api->GetURL("about:blank"); if (HTML_Element *helm = GetHtmlElement()) { URL* url_ptr = NULL; if (helm->GetNsType() == NS_HTML) { short attr = ATTR_SRC; if (helm->Type() == HE_OBJECT) attr = ATTR_DATA; url_ptr = helm->GetUrlAttr(attr, NS_IDX_HTML, GetParentFramesDoc() ? GetParentFramesDoc()->GetLogicalDocument() : NULL); } #ifdef SVG_SUPPORT else if (g_svg_manager->AllowFrameForElement(helm)) { URL* root_url = &GetParentFramesDoc()->GetURL(); url_ptr = g_svg_manager->GetXLinkURL(helm, root_url); } #endif // SVG_SUPPORT if (url_ptr && !url_ptr->IsEmpty()) frm_url = *url_ptr; else frm_url = about_blank_url; } else { // if helm==NULL then this is a frame with freed content and current doc has the original url FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) frm_url = doc->GetURL(); } #ifdef _MIME_SUPPORT_ // check if frm_url equals to any ancestor of this frame FramesDocument* ancestor_doc = GetParentFramesDoc(); #endif // _MIME_SUPPORT_ BOOL bypass_frame_access_check = FALSE; #ifdef _MIME_SUPPORT_ if (ancestor_doc->GetSuppress(frm_url.Type()) || DocumentManager::IsSpecialURL(frm_url)) { if (ancestor_doc->MakeFrameSuppressUrl(frm_url) == OpStatus::ERR_NO_MEMORY) return OpStatus::OK; bypass_frame_access_check = TRUE; } #endif // _MIME_SUPPORT_ #if DOCHAND_MAX_FRAMES_ON_PAGE > 0 if (!IsContentAllowed() && (!(frm_url == about_blank_url))) frm_url = about_blank_url; #endif // DOCHAND_MAX_FRAMES_ON_PAGE > 0 if (!doc_manager->GetCurrentDoc() && (frm_url == about_blank_url || frm_url.Type() == URL_JAVASCRIPT) #ifdef ON_DEMAND_PLUGIN // Allow frame to load a placeholder even when plugin element has no URL to load. && !GetHtmlElement()->IsPluginPlaceholder() #endif // ON_DEMAND_PLUGIN ) { RETURN_IF_ERROR(doc_manager->CreateInitialEmptyDocument(frm_url.Type() == URL_JAVASCRIPT, frm_url == about_blank_url && origin_thread != NULL)); if (frm_url == about_blank_url) { /* If a thread initiated the loading of about:blank, then add an async onload check. Once it is signalled and the 'origin_thread' hasn't caused the document to be navigated away, only then will an about:blank onload be sent. */ if (origin_thread && doc_manager->GetCurrentDoc()) RETURN_IF_ERROR(doc_manager->GetCurrentDoc()->ScheduleAsyncOnloadCheck(origin_thread, TRUE)); /* Nothing more to do. */ return OpStatus::OK; } } DocumentReferrer frm_ref_url(GetParentFramesDoc()); DocumentManager *parent_docman = GetParentFramesDoc()->GetDocManager(); BOOL check_if_expired = parent_docman->GetCheckExpiryType() != CHECK_EXPIRY_NEVER; BOOL reload = parent_docman->GetReload(); BOOL user_initiated = FALSE; BOOL create_doc_now = GetParentFramesDoc()->IsGeneratedByOpera() && frm_url.Status(TRUE) == URL_LOADED && !GetParentFramesDoc()->IsReflowing(); BOOL is_walking_in_history = parent_docman->IsWalkingInHistory(); doc_manager->SetUseHistoryNumber(parent_docman->CurrentDocListElm()->Number()); doc_manager->SetReload(reload); doc_manager->SetReloadFlags(parent_docman->GetReloadDocument(), parent_docman->GetConditionallyRequestDocument(), parent_docman->GetReloadInlines(), parent_docman->GetConditionallyRequestInlines()); DocumentManager::OpenURLOptions options; options.user_initiated = user_initiated; options.create_doc_now = create_doc_now; options.is_walking_in_history = is_walking_in_history; options.bypass_url_access_check = bypass_frame_access_check; options.origin_thread = origin_thread; options.from_html_attribute = TRUE; doc_manager->OpenURL(frm_url, frm_ref_url, check_if_expired, reload, options); // In case we created a new document for a javascript url and the script load // command failed completely, we need to clean up the about:blank state if (frm_url.Type() == URL_JAVASCRIPT && doc_manager->GetLoadStatus() == NOT_LOADING) { doc_manager->GetCurrentDoc()->SetWaitForJavascriptURL(FALSE); doc_manager->GetCurrentDoc()->CheckFinishDocument(); } } return OpStatus::OK; } OP_STATUS FramesDocElm::FormatDocs() { OP_STATUS stat = DocStatus::DOC_OK; OpStatus::Ignore(stat); FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) stat = doc->Reflow(TRUE); else for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) if (fde->FormatDocs() == OpStatus::ERR_NO_MEMORY) stat = OpStatus::ERR_NO_MEMORY; return stat; } #ifdef _PRINT_SUPPORT_ OP_STATUS FramesDocElm::CopyFrames(FramesDocElm* new_frm) { new_frm->SetIsRow(IsRow()); FramesDocElm* fde = FirstChild(); while (fde) { OP_ASSERT(!fde->m_helm.GetElm() || fde->m_print_twin_elm || !"It need to have a print twin to connect it to"); FramesDocElm* new_fde = OP_NEW(FramesDocElm, (fde->GetSubWinId(), 0, 0, 0, 0, new_frm->GetParentFramesDoc(), fde->m_print_twin_elm, NULL, fde->GetSizeType(), fde->GetSizeVal(), fde->IsInlineFrame(), new_frm)); if( ! new_fde ) return OpStatus::ERR_NO_MEMORY; if (OpStatus::IsError(new_fde->Init(fde->m_print_twin_elm, NULL, NULL))) { OP_DELETE((new_fde)); return OpStatus::ERR_NO_MEMORY; } new_fde->Under(new_frm); RETURN_IF_ERROR(fde->CopyFrames(new_fde)); fde = fde->Suc(); } // FIXME: potentially incorrectly assuming print preview here (but there's nothing new about that): RETURN_IF_MEMORY_ERROR(new_frm->GetDocManager()->SetPrintMode(TRUE, this, TRUE)); return OpStatus::OK; } OP_STATUS FramesDocElm::CreatePrintLayoutAllPages(PrintDevice* pd, FramesDocElm* print_root) { FramesDocument* doc = GetCurrentDoc(); if (doc) { int page_ypos = 0; FramesDocElm* prev_fde = print_root->LastChild(); if (prev_fde) page_ypos = prev_fde->GetAbsY() + prev_fde->GetHeight(); FramesDocElm* fde; HTML_Element* html_element; if (IsInlineFrame()) { OP_ASSERT(m_print_twin_elm); // Without this the cloned FramesDocElm won't be found anyway if (!m_print_twin_elm) { return OpStatus::OK; } OP_ASSERT(GetFrmDocElmByHTML(m_print_twin_elm) == NULL); html_element = m_print_twin_elm; fde = OP_NEW(FramesDocElm, (GetSubWinId(), GetAbsX(), GetAbsY(), pd->GetRenderingViewWidth(), pd->GetRenderingViewHeight(), print_root->GetParentFramesDoc(), m_print_twin_elm, pd, FRAMESET_ABSOLUTE_SIZED, 0, TRUE, print_root)); } else { html_element = NULL; fde = OP_NEW(FramesDocElm, (GetSubWinId(), 0, page_ypos, pd->GetRenderingViewWidth(), pd->GetRenderingViewHeight(), print_root->GetParentFramesDoc(), NULL, pd, FRAMESET_ABSOLUTE_SIZED, 0, FALSE, print_root)); } if (!fde) return OpStatus::ERR_NO_MEMORY; if (OpStatus::IsError(fde->Init(html_element, pd, NULL))) { OP_DELETE((fde)); fde = NULL; return OpStatus::ERR_NO_MEMORY; } #ifdef _DEBUG if (IsInlineFrame()) { OP_ASSERT(fde->GetHtmlElement() == m_print_twin_elm); } #endif // _DEBUG fde->Under(print_root); if (fde->GetDocManager()->SetPrintMode(TRUE, this, TRUE) == OpStatus::ERR_NO_MEMORY) { fde->Out(); OP_DELETE(fde); return OpStatus::ERR_NO_MEMORY; } int w = fde->GetWidth(); int h = fde->GetHeight(); FramesDocument* printdoc = fde->GetDocManager()->GetPrintDoc(); if (printdoc) { w = printdoc->Width(); h = printdoc->Height(); } AffinePos fde_abs_pos = fde->GetAbsPos(); fde->SetGeometry(fde_abs_pos, w, h); print_root->SetGeometry(print_root->GetAbsPos(), w, fde_abs_pos.GetTranslation().y + h); } else { FramesDocElm* fde = FirstChild(); while (fde) { RETURN_IF_ERROR(fde->CreatePrintLayoutAllPages(pd, print_root)); fde = fde->Suc(); } } return OpStatus::OK; } #endif // _PRINT_SUPPORT_ /* static */ FramesDocElm* FramesDocElm::GetFrmDocElmByHTML(HTML_Element * elm) { if (elm) { ElementRef *ref = elm->GetFirstReferenceOfType(ElementRef::FRAMESDOCELM); if (ref) return static_cast<FDEElmRef*>(ref)->GetFramesDocElm(); } return NULL; } #ifdef _PRINT_SUPPORT_ void FramesDocElm::Display(VisualDevice* vd, const RECT& rect) { Window* window = GetDocManager()->GetWindow(); FramesDocument* doc = doc_manager->GetPrintDoc(); if (doc) { int abs_x = GetAbsX(); int abs_y = GetAbsY(); if (IsInlineFrame()) { OpRect frame_clip_rect(0, 0, GetWidth(), GetHeight()); frame_clip_rect = vd->ScaleToDoc(frame_clip_rect); vd->BeginClipping(frame_clip_rect); VDState vd_state = vd->PushState(); doc->Display(rect, vd); vd->PopState(vd_state); vd->EndClipping(); } else if (window->GetFramesPrintType() == PRINT_AS_SCREEN) { vd->TranslateView(-abs_x, -abs_y); OpRect frame_clip_rect(0, 0, GetWidth(), GetHeight()); vd->BeginClipping(frame_clip_rect); if (vd->IsPrinter() && !IsInlineFrame()) doc->PrintPage((PrintDevice*) vd, 1, FALSE); else doc->Display(rect, vd); vd->EndClipping(); vd->TranslateView(abs_x, abs_y); } else { vd->TranslateView(0, -abs_y); doc->Display(rect, vd); vd->TranslateView(0, abs_y); } } else for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->Display(vd, rect); } #endif // _PRINT_SUPPORT_ void FramesDocElm::DisplayBorder(VisualDevice* vd) { UINT32 gray = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON); UINT32 lgray = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON_LIGHT); UINT32 dgray = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON_DARK); BOOL scale_100 = !IsInDocCoords(); UINT32 old_scale = 0; if (scale_100) old_scale = vd->SetTemporaryScale(100); if (frame_spacing) { // If a frame is not visible, clear that area so we don't show parts of old documents there. FramesDocElm* fde = FirstChild(); if ((!fde || (GetVisualDevice() && !GetVisualDevice()->GetVisible())) && !GetWindow()->IsBackgroundTransparent()) { // Not sure why this case happens yet but it does when nesting framesets. /emil vd->SetBgColor(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_DOCUMENT_BACKGROUND)); vd->DrawBgColor(OpRect(GetAbsX(), GetAbsY(), GetWidth(), GetHeight())); } // Paint background between frames vd->SetBgColor(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON)); while (fde && fde->Suc()) { FramesDocElm* fde_suc = fde->Suc(); if (IsRow()) { int y = fde->GetY() + fde->GetHeight(); vd->DrawBgColor(OpRect(GetX(), GetY() + y, GetWidth(), fde_suc->GetY() - y)); } else { int x = fde->GetX() + fde->GetWidth(); vd->DrawBgColor(OpRect(GetX() + x, GetY(), fde_suc->GetX() - x, GetHeight())); } fde = fde_suc; } UINT32 black = OP_RGB(0, 0, 0); if (GetFrameTopBorder()) { vd->SetColor32(dgray); vd->DrawLine(OpPoint(GetAbsX() - 2, GetAbsY() - 2), GetWidth() + 4, TRUE, 1); vd->SetColor32(black); vd->DrawLine(OpPoint(GetAbsX() - 1, GetAbsY() - 1), GetWidth() + 2, TRUE, 1); } if (GetFrameBottomBorder()) { vd->SetColor32(gray); vd->DrawLine(OpPoint(GetAbsX(), GetAbsY() + GetHeight()), GetWidth(), TRUE, 1); vd->SetColor32(lgray); vd->DrawLine(OpPoint(GetAbsX() - 1, GetAbsY() + GetHeight() + 1), GetWidth() + 2, TRUE, 1); } if (GetFrameLeftBorder()) { vd->SetColor32(dgray); vd->DrawLine(OpPoint(GetAbsX() - 2, GetAbsY() - 2), GetHeight() + 4, FALSE, 1); vd->SetColor32(black); vd->DrawLine(OpPoint(GetAbsX() - 1, GetAbsY() - 1), GetHeight() + 2, FALSE, 1); } if (GetFrameRightBorder()) { vd->SetColor32(gray); vd->DrawLine(OpPoint(GetAbsX() + GetWidth(), GetAbsY() - 1), GetHeight() + 2, FALSE, 1); vd->SetColor32(lgray); vd->DrawLine(OpPoint(GetAbsX() + GetWidth() + 1, GetAbsY() - 2), GetHeight() + 4, FALSE, 1); } } if (scale_100) vd->SetTemporaryScale(old_scale); for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->DisplayBorder(vd); } #ifdef _PRINT_SUPPORT_ OP_DOC_STATUS FramesDocElm::PrintPage(PrintDevice* pd, int page_num, BOOL selected_only) { FramesDocElm* fde = FirstChild(); if (fde) { while (fde) { OP_STATUS dstat = fde->PrintPage(pd, page_num, selected_only); if (dstat == DocStatus::DOC_PAGE_OUT_OF_RANGE) page_num -= fde->CountPages(); else return dstat; fde = fde->Suc(); } return DocStatus::DOC_CANNOT_PRINT; } else { DocumentManager *old_doc_man = pd->GetDocumentManager(); pd->SetDocumentManager(doc_manager); OP_DOC_STATUS ret = doc_manager->PrintPage(pd, page_num, selected_only); pd->SetDocumentManager(old_doc_man); return ret; } } #endif // _PRINT_SUPPORT_ int FramesDocElm::CountPages() { #ifdef _PRINT_SUPPORT_ FramesDocument* doc = doc_manager->GetPrintDoc(); if (doc) return doc->CountPages(); else #endif // _PRINT_SUPPORT_ { int page_count = 0; FramesDocElm* fde = FirstChild(); while (fde) { page_count += fde->CountPages(); fde = fde->Suc(); } return page_count; } } LayoutMode FramesDocElm::GetLayoutMode() const { if (packed1.special_object) return (LayoutMode) packed1.special_object_layout_mode; else return parent_frm_doc->GetLayoutMode(); } void FramesDocElm::CheckERA_LayoutMode() { FramesDocument* doc = GetCurrentDoc(); if (doc) { if (doc && doc->IsFrameDoc()) doc->CheckERA_LayoutMode(); } else for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->CheckERA_LayoutMode(); } void FramesDocElm::UpdateFrameMargins(HTML_Element *he) { if (he) { frame_margin_width = he->GetFrameMarginWidth(); frame_margin_height = he->GetFrameMarginHeight(); if (frame_margin_width == 0) // 0 isn't allowed according to spec and brakes updating (Bug 96454) frame_margin_width = 1; if (frame_margin_height == 0) frame_margin_height = 1; } } void FramesDocElm::SetCurrentHistoryPos(int n, BOOL parent_doc_changed, BOOL is_user_initiated) { FramesDocument* doc = GetCurrentDoc(); if (doc) doc_manager->SetCurrentHistoryPos(n, parent_doc_changed, is_user_initiated); else { for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->SetCurrentHistoryPos(n, parent_doc_changed, is_user_initiated); } } FramesDocument* FramesDocElm::GetTopFramesDoc() { return GetParentFramesDoc()->GetTopFramesDoc(); } void FramesDocElm::CheckSmartFrames(BOOL on) { OP_ASSERT(!IsInlineFrame()); pos.SetTranslation(0, 0); width = 0; height = 0; if (frm_dev) frm_dev->SetScrollType(on ? VisualDevice::VD_SCROLLING_NO : (VisualDevice::ScrollType) frame_scrolling); FramesDocument* doc = GetCurrentDoc(); if (doc && doc->IsFrameDoc()) doc->CheckSmartFrames(on); for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->CheckSmartFrames(on); } void FramesDocElm::ExpandFrameSize(int inc_width, int inc_height) { OP_ASSERT(inc_width >= 0); OP_ASSERT(inc_height >= 0); width += inc_width; height += inc_height; FramesDocElm* fde = FirstChild(); if (fde) { int inc_used = 0; int child_count = 0; for (; fde; fde = fde->Suc()) child_count++; int child_width_inc = inc_width; int child_height_inc = inc_height; if (IsRow()) child_height_inc = (inc_height + child_count - 1) / child_count; else child_width_inc = (inc_width + child_count - 1) / child_count; for (fde = FirstChild(); fde; fde = fde->Suc()) { if (IsRow()) fde->pos.AppendTranslation(0, inc_used); else fde->pos.AppendTranslation(inc_used, 0); fde->ExpandFrameSize(child_width_inc, child_height_inc); if (IsRow()) { inc_used += child_height_inc; if (inc_used == inc_height) child_height_inc = 0; } else { inc_used += child_width_inc; if (inc_used == inc_width) child_width_inc = 0; } } } else { FramesDocument* doc = GetCurrentDoc(); if (doc && doc->IsFrameDoc()) doc->ExpandFrameSize(inc_width, inc_height); } } void FramesDocElm::CalculateFrameSizes(int frames_policy) { BOOL use_doc_coords = IsInDocCoords(); FramesDocElm* fde = FirstChild(); if (fde) { int next_y = 0; if (frames_policy == FRAMES_POLICY_FRAME_STACKING) { for (; fde; fde = fde->Suc()) { OpPoint fde_pos = fde->pos.GetTranslation(); fde_pos.y = next_y; fde->pos.SetTranslation(fde_pos.x, fde_pos.y); fde->width = width; fde->CalculateFrameSizes(frames_policy); next_y += fde->height; } height = next_y; } else if (frames_policy == FRAMES_POLICY_SMART_FRAMES) { int next_x = 0; width = normal_width; height = normal_height; for (; fde; fde = fde->Suc()) { OpPoint fde_pos = fde->pos.GetTranslation(); if (IsRow()) fde_pos.y = next_y; else fde_pos.x = next_x; fde->pos.SetTranslation(fde_pos.x, fde_pos.y); fde->CalculateFrameSizes(frames_policy); if (IsRow()) { if (width < fde->width) width = fde->width; next_y += fde->height; } else { if (height < fde->height) height = fde->height; next_x += fde->width; } } if (IsRow()) height = next_y; else width = next_x; for (fde = FirstChild(); fde; fde = fde->Suc()) { if (IsRow()) { if (width > fde->width) fde->ExpandFrameSize(width - fde->width, 0); } else { if (height > fde->height) fde->ExpandFrameSize(0, height - fde->height); } } } } else { OP_ASSERT(!IsInlineFrame()); FramesDocument* doc = GetCurrentDoc(); if (doc) { if (doc && doc->IsFrameDoc()) doc->CalculateFrameSizes(); if (frames_policy == FRAMES_POLICY_FRAME_STACKING) { if (!HasExplicitZeroSize()) height = use_doc_coords ? doc->Height() : doc->GetVisualDevice()->ScaleToScreen(doc->Height()); else height = 0; } else if (frames_policy == FRAMES_POLICY_SMART_FRAMES) { int doc_height = doc->Height(); int doc_width = doc->GetHtmlDocument() ? doc->GetHtmlDocument()->Width() : doc->Width(); if (!use_doc_coords) { doc_height = doc->GetVisualDevice()->ScaleToScreen(doc_height); doc_width = doc->GetVisualDevice()->ScaleToScreen(doc_width); } width = normal_width; height = normal_height; if (!HasExplicitZeroSize() && height < doc_height) height = doc_height; if (!HasExplicitZeroSize() && width < doc_width) width = doc_width; } } } } void FramesDocElm::CheckFrameStacking(BOOL stack_frames) { SetIsRow(stack_frames || packed1.normal_row); packed1.is_inline = stack_frames && !Parent(); pos.SetTranslation(0, 0); width = 0; height = 0; if (frm_dev) frm_dev->SetScrollType(stack_frames ? VisualDevice::VD_SCROLLING_NO : (VisualDevice::ScrollType) frame_scrolling); for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->CheckFrameStacking(stack_frames); } BOOL FramesDocElm::HasExplicitZeroSize() { return !size_val && packed1.size_type == FRAMESET_ABSOLUTE_SIZED; } OP_STATUS FramesDocElm::HandleLoading(OpMessage msg, URL_ID url_id, MH_PARAM_2 user_data) { OP_STATUS stat = OpStatus::OK; FramesDocElm* fde = FirstChild(); if (fde) { for (; fde; fde = fde->Suc()) { stat = fde->HandleLoading(msg, url_id, user_data); if( OpStatus::IsError(stat) ) break; } } else if (!IsFrameset()) stat = doc_manager->HandleLoading((doc_manager->GetLoadStatus() == WAIT_FOR_HEADER && msg == MSG_URL_DATA_LOADED) ? MSG_HEADER_LOADED : msg, url_id, user_data); return stat; } #ifdef _PRINT_SUPPORT_ void FramesDocElm::DeletePrintCopy() { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) doc->DeletePrintCopy(); else for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->DeletePrintCopy(); } #endif // _PRINT_SUPPORT_ void FramesDocElm::UpdateSecurityState(BOOL include_loading_docs) { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc) doc_manager->UpdateSecurityState(include_loading_docs); else { for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) { fde->UpdateSecurityState(include_loading_docs); } } } void FramesDocElm::AppendChildrenToList(Head* list) { for (FramesDocElm* fde = FirstChild(); fde; fde = FirstChild()) { fde->AppendChildrenToList(list); fde->Out(); if (fde->packed1.is_secondary) OP_DELETE(fde); else fde->Into(list); } } int FramesDocElm::CountFrames() { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc || frm_dev) { if (doc && doc->IsFrameDoc()) return doc->CountFrames(); else return 1; } else { int count = 0; for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) count += fde->CountFrames(); return count; } } FramesDocElm* FramesDocElm::GetFrameByNumber(int& num) { FramesDocument* doc = doc_manager->GetCurrentDoc(); if (doc || frm_dev) { if (doc && doc->IsFrameDoc()) return doc->GetFrameByNumber(num); else { num--; if (num == 0) return this; else return NULL; } } else { FramesDocElm* frame = NULL; for (FramesDocElm* fde = FirstChild(); !frame && fde; fde = fde->Suc()) frame = fde->GetFrameByNumber(num); return frame; } } FramesDocElm* FramesDocElm::LastLeafActive() { FramesDocElm *last_leaf = this; FramesDocElm *child = last_leaf->LastChildActive(); while (child) { last_leaf = child; child = last_leaf->LastChildActive(); } return last_leaf; } FramesDocElm* FramesDocElm::ParentActive() { if (Parent()) return Parent(); return GetParentFramesDoc()->GetDocManager()->GetFrame(); } FramesDocElm* FramesDocElm::FirstChildActive() { FramesDocElm *candidate = (GetCurrentDoc() && GetCurrentDoc()->GetIFrmRoot()) ? GetCurrentDoc()->GetIFrmRoot()->FirstChild() : NULL; while (candidate) { if (candidate->GetVisualDevice()) { FramesDocument *frm_doc = candidate->GetCurrentDoc(); if (frm_doc && frm_doc->GetFrmDocRoot()) { FramesDocElm *tmp_candidate = frm_doc->GetFrmDocRoot()->FirstChildActive(); if (tmp_candidate) return tmp_candidate; } else return candidate; } candidate = candidate->Suc(); } candidate = FirstChild(); while (candidate) { if (candidate->GetVisualDevice()) { FramesDocument *frm_doc = candidate->GetCurrentDoc(); if (frm_doc && frm_doc->GetFrmDocRoot()) { FramesDocElm *tmp_candidate = frm_doc->GetFrmDocRoot()->FirstChildActive(); if (tmp_candidate) return tmp_candidate; } else return candidate; } candidate = candidate->FirstChild(); } return NULL; } FramesDocElm* FramesDocElm::NextActive() { FramesDocElm *candidate = FirstChildActive(); if (candidate) return candidate; for (FramesDocElm *leaf = this; leaf; leaf = leaf->ParentActive()) if (leaf->Suc()) { FramesDocElm *candidate = leaf->Suc(); if (candidate->GetVisualDevice()) { FramesDocument *frm_doc = candidate->GetCurrentDoc(); if (frm_doc && frm_doc->GetFrmDocRoot()) { FramesDocElm *tmp_candidate = frm_doc->GetFrmDocRoot()->NextActive(); if (tmp_candidate) return tmp_candidate; } else return candidate; } else { FramesDocElm *tmp_candidate = candidate->NextActive(); if (tmp_candidate) return tmp_candidate; } } return NULL; } FramesDocElm* FramesDocElm::LastChildActive() { FramesDocElm *candidate = LastChild(); if (candidate) { if (candidate->GetVisualDevice()) { FramesDocument *frm_doc = candidate->GetCurrentDoc(); if (frm_doc && frm_doc->GetFrmDocRoot()) { FramesDocElm *tmp_candidate = frm_doc->GetFrmDocRoot()->LastChildActive(); if (tmp_candidate) return tmp_candidate; } else return candidate; } else return candidate->LastChildActive(); } candidate = (GetCurrentDoc() && GetCurrentDoc()->GetFrmDocRoot()) ? GetCurrentDoc()->GetFrmDocRoot() : NULL; if (candidate) { FramesDocElm *tmp_candidate = candidate->LastChildActive(); if (tmp_candidate) return tmp_candidate; } candidate = (GetCurrentDoc() && GetCurrentDoc()->GetIFrmRoot()) ? GetCurrentDoc()->GetIFrmRoot()->LastChild() : NULL; if (candidate) { while (candidate) { if (candidate->GetVisualDevice()) { FramesDocument *frm_doc = candidate->GetCurrentDoc(); if (frm_doc && frm_doc->GetFrmDocRoot()) { FramesDocElm *tmp_candidate = frm_doc->GetFrmDocRoot()->LastChildActive(); if (tmp_candidate) return tmp_candidate; } else return candidate; } candidate = candidate->Pred(); } } return NULL; } FramesDocElm* FramesDocElm::PrevActive() { if (Pred()) { FramesDocElm* leaf = Pred(); FramesDocElm* last_child = leaf->LastChildActive(); while (last_child) { leaf = last_child; last_child = leaf->LastChildActive(); } return leaf; } FramesDocElm *candidate = ParentActive(); if (candidate) { if (candidate->GetVisualDevice()) { FramesDocument *frm_doc = candidate->GetCurrentDoc(); if (frm_doc && !frm_doc->GetFrmDocRoot()) return candidate; } return candidate->PrevActive(); } return NULL; } OP_STATUS FramesDocElm::OnlineModeChanged() { if (GetCurrentDoc()) return doc_manager->OnlineModeChanged(); else { OP_STATUS status = OpStatus::OK; for (FramesDocElm *child = FirstChild(); child; child = child->Suc()) if (OpStatus::IsMemoryError(child->OnlineModeChanged())) { OpStatus::Ignore(status); status = OpStatus::ERR_NO_MEMORY; } return status; } } void FramesDocElm::OnRenderingViewportChanged(const OpRect &rendering_rect) { FramesDocument* doc = doc_manager->GetCurrentDoc(); // Translate rect to local coordinates and clip OpRect local_rect(rendering_rect.x - GetX(), rendering_rect.y - GetY(), rendering_rect.width, rendering_rect.height); OpRect local_visible_rect(0, 0, GetWidth(), GetHeight()); local_visible_rect.IntersectWith(local_rect); if (doc) doc->OnRenderingViewportChanged(local_visible_rect); else for (FramesDocElm* fde = FirstChild(); fde; fde = fde->Suc()) fde->OnRenderingViewportChanged(local_visible_rect); } OP_STATUS FramesDocElm::SetReinitData(int history_num, BOOL visible, LayoutMode frame_layout_mode) { if (reinit_data) { if (history_num != -1) reinit_data->m_history_num = history_num; reinit_data->m_visible = visible; reinit_data->m_old_layout_mode = frame_layout_mode; return OpStatus::OK; } else { reinit_data = OP_NEW(FrameReinitData, (history_num, visible, frame_layout_mode)); if (!reinit_data) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } } void FramesDocElm::RemoveReinitData() { OP_DELETE(reinit_data); reinit_data = NULL; } BOOL FramesDocElm::IsFrameRoot(FramesDocElm* head) { FramesDocElm* iframe_root = parent_frm_doc->GetIFrmRoot(); FramesDocElm* frame_root = parent_frm_doc->GetFrmDocRoot(); while (head) { if (head == iframe_root || head == frame_root) return TRUE; head = head->Parent(); } return FALSE; } void FramesDocElm::Out() { #if DOCHAND_MAX_FRAMES_ON_PAGE > 0 FramesDocument *top_doc = parent_frm_doc->GetTopDocument(); DocumentTreeIterator iter(this); iter.SetIncludeThis(); iter.SetIncludeEmpty(); while (iter.Next()) { FramesDocElm *fde = iter.GetFramesDocElm(); if (fde->frame_index != FRAME_NOT_IN_ROOT) { top_doc->OnFrameRemoved(); fde->frame_index = FRAME_NOT_IN_ROOT; } } #endif // DOCHAND_MAX_FRAMES_ON_PAGE > 0 #ifdef SCOPE_PROFILER parent_frm_doc->GetDocManager()->OnRemoveChild(GetDocManager()); #endif // SCOPE_PROFILER Tree::Out(); } void FramesDocElm::Under(FramesDocElm* elm) { #if DOCHAND_MAX_FRAMES_ON_PAGE > 0 FramesDocument *top_doc = parent_frm_doc->GetTopDocument(); if (IsFrameRoot(elm)) top_doc->OnFrameAdded(); frame_index = top_doc->GetNumFramesAdded(); #endif // DOCHAND_MAX_FRAMES_ON_PAGE > 0 #ifdef SCOPE_PROFILER parent_frm_doc->GetDocManager()->OnAddChild(GetDocManager()); #endif // SCOPE_PROFILER Tree::Under(elm); } BOOL FramesDocElm::IsContentAllowed() { #if DOCHAND_MAX_FRAMES_ON_PAGE > 0 return ((frame_index - parent_frm_doc->GetTopDocument()->GetNumFramesRemoved()) <= DOCHAND_MAX_FRAMES_ON_PAGE); #else return TRUE; #endif // DOCHAND_MAX_FRAMES_ON_PAGE > 0 } #ifdef NEARBY_INTERACTIVE_ITEM_DETECTION OP_STATUS FramesDocElm::AddFrameScrollbars(OpRect& rect_of_interest, List<InteractiveItemInfo>& list) { OpScrollbar *h_scr, *v_scr; OpRect clip_rect; OpRect vis_viewport = frm_dev->GetRenderingViewport(); // This is the same as visual viewport for a frame. OpPoint inner_pos = frm_dev->GetInnerPosition(); frm_dev->GetScrollbarObjects(&h_scr, &v_scr); for (int i = 0; i < 2; i++) { OpScrollbar* current_scrollbar = i ? h_scr : v_scr; if (!(current_scrollbar && current_scrollbar->IsVisible())) continue; OpRect rect = current_scrollbar->GetRect(); /* Adjust the rect position according to the document view's top left, because we want to keep it relative to the point (in this frame), where the document's top left is. */ rect.OffsetBy(-inner_pos); rect = frm_dev->ScaleToDoc(rect); // Offset by visual viewport position, so that we are in the same coordinate system as rect_of_interest/ rect.OffsetBy(vis_viewport.x, vis_viewport.y); if (!rect.Intersecting(rect_of_interest)) continue; // Remove the part of the rect_of_interest that overlap the current scrollbar. if (current_scrollbar->IsHorizontal()) { if (rect_of_interest.y >= rect.y && rect.Bottom() > rect_of_interest.y) { INT32 diff = rect.Bottom() - rect_of_interest.y; rect_of_interest.y += diff; rect_of_interest.height -= diff; } else if (rect_of_interest.Bottom() > rect.y) rect_of_interest.height -= rect_of_interest.Bottom() - rect.y; } else { if (rect_of_interest.x >= rect.x && rect.Right() > rect_of_interest.x) { INT32 diff = rect.Right() - rect_of_interest.x; rect_of_interest.x += diff; rect_of_interest.width -= diff; } else if (rect_of_interest.Right() > rect.x) rect_of_interest.width -= rect_of_interest.Right() - rect.x; } if (clip_rect.IsEmpty()) // Compute that only once. { clip_rect = GetParentFramesDoc()->GetVisualDevice()->GetDocumentInnerViewClipRect(); GetAbsPos().ApplyInverse(clip_rect); // Scrollbar's rect is already adjusted by the document's visual viewport top left. clip_rect.OffsetBy(vis_viewport.x, vis_viewport.y); } rect.IntersectWith(clip_rect); /* This is implied from the method's assumption about visiblity of the frame. First of all, clip_rect can't be empty otherwise this frame can't be visible inside top document's visual viewport at all. Secondly if scrollbar rect intersects the rect_of_interest, which is inside the clip_rect, it must also intersect the clip_rect. */ OP_ASSERT(!rect.IsEmpty()); InteractiveItemInfo* item = InteractiveItemInfo::CreateInteractiveItemInfo(1, InteractiveItemInfo::INTERACTIVE_ITEM_TYPE_SCROLLBAR); if (!item) return OpStatus::ERR_NO_MEMORY; InteractiveItemInfo::ItemRect* rect_array = item->GetRects(); rect_array[0].rect = rect; rect_array[0].affine_pos = NULL; item->Into(&list); } return OpStatus::OK; } #endif // NEARBY_INTERACTIVE_ITEM_DETECTION void FramesDocElm::SetParentLayoutInputContext(OpInputContext* context) { if (!frm_dev || context == parent_layout_input_ctx) return; parent_layout_input_ctx = context; frm_dev->SetParentInputContext(parent_layout_input_ctx ? parent_layout_input_ctx : parent_frm_doc->GetVisualDevice(), TRUE); } BOOL FramesDocElm::CheckForUnloadTarget() { BOOL has_unload_handler = GetHasUnloadHandler(); if (!GetCheckedUnloadHandler()) { has_unload_handler = FALSE; FramesDocElm *fde = this; while (FramesDocElm *lc = fde->LastChild()) fde = lc; while (!has_unload_handler) { if (fde->GetCheckedUnloadHandler() && fde->GetHasUnloadHandler()) has_unload_handler = TRUE; else if (FramesDocument *frames_doc = fde->GetCurrentDoc()) { if (DOM_Environment *environment = frames_doc->GetDOMEnvironment()) { if (environment->HasWindowEventHandler(ONUNLOAD)) has_unload_handler = TRUE; } else if (HTML_Element *fde_target = frames_doc->GetWindowEventTarget(ONUNLOAD)) has_unload_handler = fde_target->HasEventHandlerAttribute(frames_doc, ONUNLOAD); fde->SetCheckedUnloadHandler(TRUE); fde->SetHasUnloadHandler(has_unload_handler); } if (fde == this) break; fde = fde->Prev(); } SetCheckedUnloadHandler(TRUE); SetHasUnloadHandler(has_unload_handler); } return has_unload_handler; } void FramesDocElm::UpdateUnloadTarget(BOOL added) { if (GetCheckedUnloadHandler() && added == GetHasUnloadHandler()) return; /* If we add or remove an unload handler, the computed information on ancestor elements must be recomputed. Do not recompute here but simply clear the cached flags on the ancestors. */ FramesDocElm *fde = Parent(); while (fde) { fde->SetCheckedUnloadHandler(FALSE); fde = fde->Parent(); } /* The target of the unload addition/removal is unknown, it may not have been for the element of this FramesDocElm. Update the flag by doing a full check. */ SetCheckedUnloadHandler(FALSE); CheckForUnloadTarget(); } #ifdef SVG_SUPPORT static BOOL SVGShouldDisableMouseEvents(FramesDocElm* frame) { HTML_Element* frame_elm = frame->GetHtmlElement(); if (!frame_elm) return FALSE; if (frame_elm->GetNsType() != NS_HTML) return FALSE; switch (frame_elm->Type()) { case Markup::HTE_IMG: return TRUE; case Markup::HTE_IFRAME: return (frame_elm->GetInserted() == HE_INSERTED_BY_SVG); case Markup::HTE_OBJECT: if (FramesDocument* doc = frame->GetCurrentDoc()) if (LogicalDocument* logdoc = doc->GetLogicalDocument()) if (SVGImage* svg = g_svg_manager->GetSVGImage(logdoc, logdoc->GetDocRoot())) return !svg->IsInteractive(); // Fall through. #ifdef ON_DEMAND_PLUGIN case Markup::HTE_EMBED: case Markup::HTE_APPLET: return frame_elm->IsPluginPlaceholder(); #endif // ON_DEMAND_PLUGIN default: return FALSE; } } void FramesDocElm::SVGCheckWantMouseEvents() { if (SVGShouldDisableMouseEvents(this)) { CoreView *view = frm_dev->GetContainerView(); OP_ASSERT(view || !"View not yet (re)initialized"); if (view) view->SetWantMouseEvents(FALSE); } } #endif // SVG_SUPPORT
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <stdio.h> #include <string.h> #include <numeric> #define INF (1<<28) using namespace std; class LotteryCheating { public: int minimalChange(string ID) { int digit[10]; int d = (int)ID.size(); int ans = d; for (long long i=0; i <= 100000; ++i) { long long sq = i*i; for (int j=0; j<d; ++j) { digit[d-1-j] = sq%10; sq /= 10; } if (sq == 0) { int res = 0; for (int j=0; j<d; ++j) { if (digit[j] != ID[j]-'0') { ++res; } } ans = min(ans,res); } } return ans; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "4"; int Arg1 = 0; verify_case(0, Arg1, minimalChange(Arg0)); } void test_case_1() { string Arg0 = "8"; int Arg1 = 1; verify_case(1, Arg1, minimalChange(Arg0)); } void test_case_2() { string Arg0 = "9000000000"; int Arg1 = 1; verify_case(2, Arg1, minimalChange(Arg0)); } void test_case_3() { string Arg0 = "4294967296"; int Arg1 = 0; verify_case(3, Arg1, minimalChange(Arg0)); } void test_case_4() { string Arg0 = "7654321"; int Arg1 = 3; verify_case(4, Arg1, minimalChange(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { LotteryCheating ___test; ___test.run_test(-1); } // END CUT HERE
#ifndef __AFD_HPP__ #define __AFD_HPP__ #include <map> #include <set> #include <cstdio> class AFD{ private: std::map< int, std::map< char, int > > trans; std::set< int > fin, est; std::set< char > sim; int ini; bool _eval(const std::string &s, int estate, int p){ if(fin.count(estate) && s[p]==0) return true; if(trans.count(estate)){ if(trans[estate].count(s[p])) return _eval(s, trans[estate][s[p]], p+1); } return false; } public: void setInitial(int q){ ini=q; } void addFinal(int q){ fin.insert(q); } void addTransition(int a, char c, int b){ est.insert(a); sim.insert(c); est.insert(b); trans[a][c]=b; if(trans.count(b)==0) trans[b]=std::map< char, int >(); } bool eval(const std::string &s){ return _eval(s, ini, 0); } void show(){ printf("Simbolos:\n"); bool fst=true; for(auto &i: sim){ if(!fst) printf(", "); fst=false; printf("'%c'", i); } printf("\nEstados:\n"); fst=true; for(auto &i: est){ if(!fst) printf(", "); fst=false; if(i==ini) printf(">"); if(fin.count(i)) printf("("); printf("(%d)", i); if(fin.count(i)) printf(")"); } printf("\nTransiciones:\n"); for(auto &i: trans){ for(auto &j: i.second){ printf("(%d)---[%c]-->(%d)\n", i.first, j.first, j.second); } } } }; #endif
#include "FreeImage.h" #include "glew.h" #include "glut.h" #define NUM_TEXTURE 1 unsigned int texObject[NUM_TEXTURE]; void LoadTexture(char* pFilename); void display(); void reshape(GLsizei w, GLsizei h); int main(int argc, char** argv) { glutInit(&argc, argv); glutInitWindowSize(400, 400); glutInitWindowPosition(0, 0); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA | GLUT_DEPTH); glutCreateWindow("Texture"); glewInit(); FreeImage_Initialise(); glGenTextures(NUM_TEXTURE, texObject); LoadTexture("chek_old.bmp"); FreeImage_DeInitialise(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMainLoop(); return 0; } void LoadTexture(char* pFilename) { FIBITMAP* pImage = FreeImage_Load(FreeImage_GetFileType(pFilename, 0), pFilename); FIBITMAP* p32BitsImage = FreeImage_ConvertTo32Bits(pImage); int iWidth = FreeImage_GetWidth(p32BitsImage); int iHeight = FreeImage_GetHeight(p32BitsImage); glBindTexture(GL_TEXTURE_2D, texObject[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, iWidth, iHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(p32BitsImage)); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); FreeImage_Unload(p32BitsImage); FreeImage_Unload(pImage); } void display() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 1.0, 1.0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texObject[0]); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(-50.0, 0.0, 0.0); glTexCoord2f(100.0, 0.0); glVertex3f(-50.0, 0.0, 100.0); glTexCoord2f(100.0, 100.0); glVertex3f(50.0, 0.0, 100.0); glTexCoord2f(0.0, 100.0); glVertex3f(50.0, 0.0, 0.0); glEnd(); glFlush(); } void reshape(GLsizei w, GLsizei h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, (GLfloat)w / (GLfloat)h, 0.5, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0, 0.5, 0.0, 50.0, 0.0, 50.0, 0.0, 1.0, 0.0); }
#include<iostream> #include<vector> #include<algorithm> #define FOR(i,n) for(i=0;i<n;i++) using namespace std; int l,r,n,m; vector <vector<int>> land; int liesin(int a) { if(a>=l&&a<=r) return 1; else return 0; } int grapevine() { int size,ans=0,prev; vector<int>::iterator it; for(int i=0;i<n;i++) { it=lower_bound(land[i].begin(),land[i].end(),l); int low=it-land[i].begin(); size=m-low; if(size>(n-i))size=(n-i); for(;size>=1;size--) { if(liesin(land[i+size-1][low+size-1])) {if(size>ans)ans=size;} } if(low==0) break; } return ans; } int main() { int i,j,temp,ans,q; vector<int>tv; while(1) { cin>>n>>m; land.clear(); if(n==0) break; FOR(i,n) { tv.clear(); FOR(j,m) { cin>>temp; tv.push_back(temp); } land.push_back(tv); } cin>>q; while(q--) { cin>>l>>r; ans=grapevine(); cout<<ans<<endl; } cout<<"-"<<endl; } return 0; }
#pragma once //#include "stdafx.h" #include <stdio.h> #include <WinSock.h> //一定要包含这个,或者winsock2.h #include <Windows.h> #include <string> #include "mysql.h" class SqlTool { private: public: static MYSQL mysql; static MYSQL_RES *res; static MYSQL_ROW column; static bool connectDB(); static void freeRes(); static bool operationExcutor(const char* operation, MYSQL_RES* &res); static bool insertExcutor(const char* operation); static char* getVariableFromDB(const char* operation); //char* uuidGenerator(MYSQL_RES* &res); static char* datetimeConvertor(int input); static bool setCharSetEncoding(const char* CharSetEncoding); SqlTool(); ~SqlTool(); };
/* *Author: Ankit Goyal *Date: 10/10/2012 * * O(n) - Linear time maximum sum solution. * */ #include<iostream> #include<algorithm> using namespace std; int main(int argc, char **argv){ int list[9] = {10, -1, 5, 6, 20, -50, 100, -100, 4}; int current_maximum = 0, previous_maximum=0; bool evaluating = false; for (int i = 0; i < 9 ;i++) { if(current_maximum == 0 && list[i] < 0 && previous_maximum == 0){ continue; } if(list[i] < 0 && evaluating == false){ previous_maximum = current_maximum; current_maximum = 0; evaluating = true; } current_maximum += list[i]; if(evaluating ==true and current_maximum > 0){ current_maximum += previous_maximum; evaluating = false; } } cout << "maximum sum is " << max(current_maximum, previous_maximum) << endl; return 0; }
#pragma once #include <iostream> #include <vector> #include "CarInsoles.hpp" #include "SeatUpholstery.hpp" #include "Bulbs.hpp" #include "Product.hpp" class Cart { public: Cart() = default; Cart(const std::vector<Product*>& products_in_cart); Cart(const Cart& cart); Cart& operator=(const Cart& cart); ~Cart(); void add_product(const Product* to_add); double get_price(Product* product); void print()const; private: std::vector<Product*> products_in_cart; static void copy_memory(const std::vector<Product*>& source, std::vector<Product*>& destination); static void clear_memory(std::vector<Product*>& source); };
#ifndef _IO_ADAPTER_H_ #define _IO_ADAPTER_H_ #include <cstdio> class FileOutputAdapter { private: std::FILE *m_fout; public: FileOutputAdapter(FILE *f) :m_fout(f) { } void operator() (int ch) { std::fputc(ch, m_fout); } }; class NullOutputAdapter { private: int m_count; public: NullOutputAdapter() :m_count(0) { } int count() { return m_count; } void operator() (int ch) { ++m_count; } }; class FileInputAdapter { private: std::FILE *m_fin; public: FileInputAdapter(FILE *f) :m_fin(f) { } int operator() () { return std::fgetc(m_fin); } }; #endif /* _IO_ADAPTER_H_ */
/*矩形切割,适用于任意维数的矩形,具体是一某一矩形为基准,把其他矩形在各维进行 切割*/ #include<iostream> #include<stdio.h> #include<memory> #define fo(i,u,d) for (long i=(u); i<=(d); ++i) using namespace std; const long maxn=200000; const long maxd=2;//矩形维数 struct retan { double d1[maxd],d2[maxd];//d1,d2分别表示左上角和右下角的各维坐标 } p[2][maxn],pp; long n,m,t[2],tt=0,pd=1; double max(double x, double y) { return x>y?x:y; } double min(double x, double y) { return x<y?x:y; } void fz(retan &p1, retan p2) { fo(i,0,maxd-1) { p1.d1[i]=p2.d1[i]; p1.d2[i]=p2.d2[i]; } } long cut(retan &p1, retan p2, long l)//按第l维切割,以p2为基准切p1 { double k1,k2; k1=max(p1.d1[l],p2.d1[l]); k2=min(p1.d2[l],p2.d2[l]); if (k1>=k2) return 1; if (p1.d2[l]>k2) { ++t[m^1]; fz(p[m^1][t[m^1]],p1); p[m^1][t[m^1]].d1[l]=k2; p[m^1][t[m^1]].d2[l]=p1.d2[l]; } if (p1.d1[l]<k1) { ++t[m^1]; fz(p[m^1][t[m^1]],p1); p[m^1][t[m^1]].d1[l]=p1.d1[l]; p[m^1][t[m^1]].d2[l]=k1; } p1.d1[l]=k1; p1.d2[l]=k2; return 0; } void solve() { m=0; t[0]=0; fo(i,1,n) { scanf("%lf%lf%lf%lf",&pp.d1[0],&pp.d1[1],&pp.d2[0],&pp.d2[1]); t[m^1]=0; fo(j,1,t[m]) fo(l,0,maxd-1) if (cut(p[m][j],pp,l)) { ++t[m^1]; fz(p[m^1][t[m^1]],p[m][j]); break; } ++t[m^1]; fz(p[m^1][t[m^1]],pp); m^=1; } } int main() { while (scanf("%d",&n),n!=0) solve(); return 0; }
#include <iostream> #include <vector> #include "matrix.hpp" using namespace std; bool Matrix::operator==(Matrix m2) { if (dVec.size() == m2.dVec.size() ||dVec[1].size() == m2.dVec[1].size()) return false; for (int i = 0; i < dVec.size(); i++) { for (int j = 0; j < dVec[i].size(); j++) { if (dVec[i][j] != m2.dVec[i][j]) return false; } } return true; } bool Matrix::operator!=(Matrix m2) { if (dVec.size() == m2.dVec.size() ||dVec[1].size() == m2.dVec[1].size()) return true; for (int i = 0; i < dVec.size(); i++) { for (int j = 0; j < dVec[i].size(); j++) { if (dVec[i][j] != m2.dVec[i][j]) return true; } } return false; } Matrix& Matrix::operator--() { for (int i = 0; i < dVec.size(); i++) { for (int j = 0; j < dVec[i].size(); j++) { dVec[i][j] = dVec[i][j] - 1; } } return *this; } Matrix& Matrix::operator++() { for (int i = 0; i < dVec.size(); i++) { for (int j = 0; j < dVec[i].size(); j++) { dVec[i][j] = dVec[i][j] + 1; } } return *this; } Matrix& Matrix::operator=(Matrix m1) { matrixSwap(*this, m1); return *this; } Matrix& Matrix::operator+=(Matrix m2) { if (dVec.size() != m2.dVec.size() ||dVec[1].size() != m2.dVec[1].size()) throw "Size is not the same!"; for (int i = 0; i < m2.dVec.size(); i++) { for (int j = 0; j < dVec[i].size(); j++) { dVec[i][j] = dVec[i][j] + m2.dVec[i][j]; } } return *this; } Matrix& Matrix::operator-=(Matrix m2){ if (dVec.size() != m2.dVec.size() ||dVec[1].size() != m2.dVec[1].size()) throw "Size is not the same!"; for (int i = 0; i < dVec.size(); i++) { for (int j = 0; j < dVec[i].size(); j++) { dVec[i][j] = dVec[i][j] - m2.dVec[i][j]; } } return *this; } Matrix operator+(Matrix m1, Matrix m2) { if (m1.dVec.size() != m2.dVec.size() ||m1.dVec[1].size() != m2.dVec[1].size()); //throw "Size is different"; Matrix temp(m1.dVec.size(), m2.dVec[1].size()); for (int i = 0; i < m1.dVec.size(); i++) { for (int j = 0; j < m1.dVec[i].size(); j++) { temp.dVec[i][j] = m1.dVec[i][j] + m2.dVec[i][j]; } } return temp; } Matrix operator*(Matrix m1, Matrix m2){ if (m1.dVec[1].size() > m2.dVec.size()){ cout<<"error"; //throw "Size not multipliable"; } Matrix temp(m1.dVec.size(), m2.dVec[1].size()); double loopTemp = 0; for (int i = 0; i < temp.dVec.size(); i++) { for (int j = 0; j < temp.dVec[i].size(); j++) { for (int a = 0; a < m1.dVec[i].size(); a++) { loopTemp += m1.dVec[i][a] * m2.dVec[a][j]; } temp.dVec[i][j] = loopTemp; loopTemp = 0; } } return temp; } Matrix& Matrix::operator*=(Matrix m2){ if (dVec[1].size() > m2.dVec.size()) { throw "Size not multipliable"; } Matrix *temp = new Matrix(dVec.size(), m2.dVec[1].size()); double loopTemp = 0; for (int i = 0; i < temp->dVec.size(); i++) { for (int j = 0; j < temp->dVec[i].size(); j++) { for (int a = 0; a < dVec[i].size(); a++) { loopTemp += dVec[i][a] * m2.dVec[a][j]; } temp->dVec[i][j] = loopTemp; loopTemp = 0; } } cout << temp; *this = *temp; return *this; }
/* * Copyright (c) 2015-2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_SORTING_NETWORK_SORT6_H_ #define CPPSORT_DETAIL_SORTING_NETWORK_SORT6_H_ namespace cppsort { namespace detail { template<> struct sorting_network_sorter_impl<6u> { template< typename RandomAccessIterator, typename Compare = std::less<>, typename Projection = utility::identity, typename = std::enable_if_t<is_projection_iterator_v< Projection, RandomAccessIterator, Compare >> > auto operator()(RandomAccessIterator first, RandomAccessIterator, Compare compare={}, Projection projection={}) const -> void { iter_swap_if(first + 1u, first + 2u, compare, projection); iter_swap_if(first, first + 2u, compare, projection); iter_swap_if(first, first + 1u, compare, projection); iter_swap_if(first + 4u, first + 5u, compare, projection); iter_swap_if(first + 3u, first + 5u, compare, projection); iter_swap_if(first + 3u, first + 4u, compare, projection); iter_swap_if(first, first + 3u, compare, projection); iter_swap_if(first + 1u, first + 4u, compare, projection); iter_swap_if(first + 2u, first + 5u, compare, projection); iter_swap_if(first + 2u, first + 4u, compare, projection); iter_swap_if(first + 1u, first + 3u, compare, projection); iter_swap_if(first + 2u, first + 3u, compare, projection); } template<typename DifferenceType=std::ptrdiff_t> static constexpr auto index_pairs() -> std::array<utility::index_pair<DifferenceType>, 12> { return {{ {0, 5}, {1, 3}, {2, 4}, {1, 2}, {3, 4}, {0, 3}, {2, 5}, {0, 1}, {2, 3}, {4, 5}, {1, 2}, {3, 4}, }}; } }; }} #endif // CPPSORT_DETAIL_SORTING_NETWORK_SORT6_H_
#include "Globals.h" #include "Application.h" #include "ModuleTextures.h" #include "ModuleInput.h" #include "ModuleParticles.h" #include "ModuleRender.h" #include "ModuleCollision.h" #include "ModuleAudio.h" #include "ModuleFadeToBlack.h" #include "ModulePlayer.h" #include "ModuleKatanaArrow.h" #include "ModuleEnemies.h" #include "ModuleInterface.h" #include "SDL\include\SDL_timer.h" #include "SDL\include\SDL_render.h" #include "ModuleKatana.h" #include "ModuleSceneTemple.h" #include "CharSelec.h" ModuleKatana::ModuleKatana() { graphics = NULL; current_animation = NULL; position.x = 10; position.y = 20; // idle animation (arcade sprite sheet) idle.PushBack({ 87, 4, 32, 33 }); idle.PushBack({ 152, 5, 32, 33 }); idle.PushBack({ 188, 5, 32, 33 }); idle.speed = 0.20f; // walk backward animation (arcade sprite sheet) backward.PushBack({ 286, 6, 22, 33 }); backward.PushBack({ 311, 6, 21, 33 }); backward.PushBack({ 335, 6, 22, 33 }); backward.speed = 0.15f; //Intermediate intermediate.PushBack({ 389,7,30,33 }); intermediate.PushBack({ 365,6,24,33 }); intermediate.PushBack({ 260,7,22,33 }); intermediate.speed = 0.10f; //Intermediate return intermediate_return.PushBack({ 260,7,22,33 }); intermediate_return.PushBack({ 365,6,24,33 }); intermediate_return.PushBack({ 389,7,30,33 }); intermediate_return.speed = 0.10f; //Spin spin.PushBack({ 123, 4, 25, 33 }); spin.PushBack({ 38, 4, 28, 33 }); spin.PushBack({ 7, 5, 24, 33 }); spin.PushBack({ 470, 49, 27, 32 }); spin.PushBack({ 123, 4, 25, 33 }); spin.PushBack({ 38, 4, 28, 33 }); spin.PushBack({ 7, 5, 24, 33 }); spin.PushBack({ 470, 49, 27, 32 }); spin.PushBack({ 123, 4, 25, 33 }); spin.PushBack({ 38, 4, 28, 33 }); spin.PushBack({ 7, 5, 24, 33 }); spin.PushBack({ 470, 49, 27, 32 }); spin.PushBack({ 123, 4, 25, 33 }); spin.PushBack({ 38, 4, 28, 33 }); spin.PushBack({ 7, 5, 24, 33 }); spin.speed = 0.15f; //Spin Circle spin_circle.PushBack({ 7,334,24,23 }); spin_circle.PushBack({ 31,330,30,31 }); spin_circle.PushBack({ 62,330,32,33 }); spin_circle.PushBack({ 95,329,32,33 }); spin_circle.PushBack({ 128,330,32,32 }); spin_circle.PushBack({ 162,330,32,32 }); spin_circle.PushBack({ 196,329,32,33 }); spin_circle.PushBack({ 230,330,33,32 }); //spin_circle.PushBack({ 214,192,32,32 }); spin_circle.speed = 0.3f; //Death Circle death_circle.PushBack({ 153,0, 130, 130 }); death_circle.PushBack({ 298,0, 130, 130 }); death_circle.PushBack({ 153,0, 130, 130 }); death_circle.PushBack({ 298,0, 130, 130 }); death_circle.PushBack({ 153,0, 130, 130 }); death_circle.PushBack({ 298,0, 130, 130 }); death_circle.PushBack({ 153,0, 130, 130 }); death_circle.PushBack({ 1,0, 130, 130 }); death_circle.PushBack({}); death_circle.PushBack({ 1,0, 130, 130 }); death_circle.PushBack({ 1,0, 130, 130 }); death_circle.PushBack({ 153,0, 130, 130 }); death_circle.PushBack({}); death_circle.PushBack({ 2,153, 130, 130 }); death_circle.PushBack({}); death_circle.PushBack({ 143,153, 130, 130 }); death_circle.PushBack({}); death_circle.PushBack({ 143,153, 130, 130 }); death_circle.PushBack({}); death_circle.PushBack({ 300,153, 130, 130 }); death_circle.PushBack({}); death_circle.PushBack({ 2,292, 130, 130 }); death_circle.speed = 0.8f; //Death Player death.x = 224; death.y = 5; death.w = 32; death.h = 32; } ModuleKatana::~ModuleKatana() {} // Load assets bool ModuleKatana::Start() { LOG("Loading player textures"); graphics = App->textures->Load("assets/sprites/characters/katana/Katana_Spritesheet.png"); player_death = App->textures->Load("assets/sprites/characters/death_player/Death_Player.png"); basicsound = App->audio->LoadFx("assets/audio/effects/Player Shoots/katanabasic.wav"); if (App->charmenu->P1katana) { position.x = (App->render->camera.x) / SCREEN_SIZE - 20; position.y = (App->render->camera.y) / SCREEN_SIZE + 100; } else if (App->charmenu->P2katana) { position.x = (App->render->camera.x) / SCREEN_SIZE - 20; position.y = (App->render->camera.y) / SCREEN_SIZE + 155; } coll = App->collision->AddCollider({ (int)position.x, (int)position.y, 32, 32 }, COLLIDER_PLAYER); //hitbox = App->collision->AddCollider({ (int)position.x, (int)position.y,16,16 }, COLLIDER_HITBOX_KATANA); state = SPAWN_PLAYER; App->katana_arrow->Enable(); App->inter->num_life_katana = 3; App->inter->num_ult_katana = 2; time = true; destroyed = false; return true; } // Unload assets bool ModuleKatana::CleanUp() { LOG("Unloading player"); App->textures->Unload(graphics); App->katana_arrow->Disable(); App->textures->Unload(player_death); if (coll != nullptr) coll->to_delete = true; if (hitbox != nullptr) hitbox->to_delete = true; App->inter->game_over_katana = true; App->audio->UnloadSFX(basicsound); basicsound = nullptr; return true; } update_status ModuleKatana::Update() { //Create bool variables bool pressed_W = App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_REPEAT ; bool pressed_A = App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_REPEAT ; bool pressed_S = App->input->keyboard[SDL_SCANCODE_S] == KEY_STATE::KEY_REPEAT ; bool pressed_D = App->input->keyboard[SDL_SCANCODE_D] == KEY_STATE::KEY_REPEAT ; Uint8 gamepad_UP = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTY) < -CONTROLLER_DEAD_ZONE; Uint8 gamepad_DOWN = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTY) > CONTROLLER_DEAD_ZONE; Uint8 gamepad_RIGHT = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTX) > CONTROLLER_DEAD_ZONE; Uint8 gamepad_LEFT = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTX) < -CONTROLLER_DEAD_ZONE; bool shot_space = App->input->keyboard[SDL_SCANCODE_SPACE] == KEY_STATE::KEY_DOWN; bool shot_button_A = SDL_GameControllerGetButton(App->input->gamepad, SDL_CONTROLLER_BUTTON_A) ; speed = 1.25; //Power Up Limits if (power_up < 0) { power_up = 0; } if (power_up > 4) { power_up = 4; } //check state CheckState(); //state actions PerformActions(); //Inputs if (input) { if (shot_space /*|| App->input->keyboard[SDL_SCANCODE_SPACE] == KEY_STATE::KEY_REPEAT*/ /*|| App->input->controller_A_button == KEY_STATE::KEY_DOWN*/) { LOG("Shooting bullets"); /*current_bullet_time = SDL_GetTicks() - bullet_on_entry; if (current_bullet_time > 100) { bullet_on_entry = SDL_GetTicks();*/ aux1++; switch (aux1) { case 0: App->particles->AddParticle(App->particles->shoot1, position.x, position.y - 20, COLLIDER_PLAYER_KATANA_SHOT, PARTICLE_SHOT_KATANA); Mix_PlayChannel(-1, basicsound, 0); LOG("Shoot 1"); break; case 1: App->particles->AddParticle(App->particles->shoot2, position.x, position.y - 20, COLLIDER_PLAYER_KATANA_SHOT, PARTICLE_SHOT_KATANA); Mix_PlayChannel(-1, basicsound, 0); break; case 2: App->particles->AddParticle(App->particles->shoot3, position.x, position.y - 20, COLLIDER_PLAYER_KATANA_SHOT, PARTICLE_SHOT_KATANA); Mix_PlayChannel(-1, basicsound, 0); aux1 = 0; break; } } if (pressed_A || App->input->controller_Dpad_LEFT== KEY_STATE::KEY_REPEAT) { position.x -= speed; App->katana_arrow->left = true; } if (pressed_W || App->input->controller_Dpad_UP == KEY_STATE::KEY_REPEAT) { position.y -= speed; App->katana_arrow->up = true; } if (pressed_D || App->input->controller_Dpad_RIGHT == KEY_STATE::KEY_REPEAT) { position.x += speed; App->katana_arrow->left = false; } if (pressed_S || App->input->controller_Dpad_DOWN == KEY_STATE::KEY_REPEAT) { position.y += speed; App->katana_arrow->up = false; } if (shot_space || App->input->controller_A_button ==BUTTON_DOWN) { LOG("Shooting bullets"); /*current_bullet_time = SDL_GetTicks() - bullet_on_entry; if (current_bullet_time > 100) { bullet_on_entry = SDL_GetTicks();*/ aux1++; switch (aux1) { case 0: App->particles->AddParticle(App->particles->shoot1, position.x , position.y - 20, COLLIDER_PLAYER_KATANA_SHOT, PARTICLE_SHOT_KATANA); LOG("Shoot 1"); break; case 1: App->particles->AddParticle(App->particles->shoot2, position.x , position.y - 20, COLLIDER_PLAYER_KATANA_SHOT, PARTICLE_SHOT_KATANA); break; case 2: App->particles->AddParticle(App->particles->shoot3, position.x , position.y - 20, COLLIDER_PLAYER_KATANA_SHOT, PARTICLE_SHOT_KATANA); aux1 = 0; break; } } } /*if (App->input->keyboard[SDL_SCANCODE_SPACE] == KEY_STATE::KEY_REPEAT) { App->particles->AddParticle(App->particles->shoot1, position.x, position.y - 20, COLLIDER_PLAYER_KATANA_SHOT, PARTICLE_SHOT_KATANA); if (time) { time_on_entry = SDL_GetTicks(); time = false; } current_time = SDL_GetTicks() - time_on_entry; if (current_time > 1500) { App->particles->AddParticle(App->particles->shoot2, position.x, position.y - 20, COLLIDER_PLAYER_KATANA_SHOT, PARTICLE_SHOT_KATANA); time = true; } }*/ //Fade SDL_SetTextureAlphaMod(graphics, alpha_player); //Set spin position if (spin_pos) { aux_spin.x = position.x ; aux_spin.y = position.y - 32; spin_pos = false; } if (death_pos) { aux_death.x = position.x - 40; aux_death.y = position.y - 70; death_pos = false; } // Draw everything -------------------------------------- SDL_Rect r = current_animation->GetCurrentFrame(); if (!check_death) { if (check_spawn) { position.x++; coll->SetPos(App->render->camera.x, App->render->camera.y - 32); } else { coll->SetPos(position.x, position.y - 32); //hitbox->SetPos(position.x + 8, position.y - 25); } App->render->Blit(graphics, position.x, position.y - r.h, &r); } else { App->render->Blit(graphics, position.x, position.y - 32, &death); coll->SetPos(App->render->camera.x, App->render->camera.y - 32); position.x -= 1; position.y += 3; } if (coll->CheckCollision(App->scene_temple->coll_left->rect)) { position.x = (App->render->camera.x / SCREEN_SIZE); } if (coll->CheckCollision(App->scene_temple->coll_right->rect)) { position.x = (SCREEN_WIDTH + App->render->camera.x / SCREEN_SIZE) - 33; } if (coll->CheckCollision(App->scene_temple->coll_up->rect)) { position.y = 35; } if (coll->CheckCollision(App->scene_temple->coll_down->rect)) { position.y = SCREEN_HEIGHT - 4; } return UPDATE_CONTINUE; } void ModuleKatana::CheckState() { //Create Input Bools bool pressed_A = App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_REPEAT; bool pressed_W = App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_REPEAT; bool press_A = App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_DOWN; bool press_W = App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_DOWN; bool release_A = App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_UP; bool release_W = App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_UP; bool released_W = App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_IDLE; bool released_A = App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_IDLE; bool gamepad_UP = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTY) < -CONTROLLER_DEAD_ZONE; bool gamepad_RIGHT = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTX) > CONTROLLER_DEAD_ZONE; bool gamepad_LEFT = SDL_GameControllerGetAxis(App->input->gamepad, SDL_CONTROLLER_AXIS_LEFTX) < -CONTROLLER_DEAD_ZONE; switch (state) { case SPAWN_PLAYER: if (time) { time_on_entry = SDL_GetTicks(); time = false; } current_time = SDL_GetTicks() - time_on_entry; if (current_time > 1500) { state = IDLE; } power_up = 0; break; case IDLE: if (press_W || press_A ||App->input->controller_Dpad_UP || App->input->controller_Dpad_LEFT) { state = GO_BACKWARD; } break; case GO_BACKWARD: if (release_W || App->input->controller_Dpad_UP==BUTTON_UP) { state = BACK_IDLE; } if (release_A || App->input->controller_Dpad_LEFT==BUTTON_UP) { state = BACK_IDLE; } if (current_animation->Finished()) { intermediate.Reset(); state = BACKWARD; } break; case BACKWARD: if (release_W || release_A || App->input->controller_Dpad_UP == BUTTON_UP || App->input->controller_Dpad_LEFT == BUTTON_UP) { if (released_W || released_A || App->input->controller_Dpad_UP == BUTTON_UP || App->input->controller_Dpad_LEFT == BUTTON_UP) { state = BACK_IDLE; /*if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_UP || gamepad_UP) { if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_IDLE || gamepad_LEFT) { state = BACK_IDLE; } } if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_UP || gamepad_LEFT) { if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_IDLE || gamepad_UP) { state = BACK_IDLE;*/ } } break; case BACK_IDLE: if (pressed_W || App->input->controller_Dpad_UP == BUTTON_REPEAT) { state = BACK_IDLE; } if (pressed_A || App->input->controller_Dpad_LEFT == BUTTON_REPEAT) { state = BACK_IDLE; } if (current_animation->Finished()) { intermediate.Reset(); state = IDLE; } break; case SPIN: if (spin.Finished()) { spin.Reset(); spin_circle.Reset(); spin_pos = false; state = IDLE; } break; case DEATH: if (position.y > SCREEN_HEIGHT + 130) { state = POST_DEATH; } break; case POST_DEATH: if (App->inter->num_life_katana > 0) { position.x = (App->render->camera.x) / SCREEN_SIZE - 20; position.y = (App->render->camera.y) / SCREEN_SIZE + 100; time = true; state = SPAWN_PLAYER; } break; } } void ModuleKatana::PerformActions() { switch (state) { case SPAWN_PLAYER: App->inter->game_over_katana = false; check_spawn = true; current_animation = &idle; blink_time = SDL_GetTicks() - blink_on_entry; if (blink_time > 10) { blink_on_entry = SDL_GetTicks(); if (blink) { alpha_player = 0; blink = false; } else { alpha_player = 255; blink = true; } } input = false; check_death = false; break; case IDLE: if (App->render->camera.x > 40000) { input = false; } if (App->render->camera.x < 40000) { input = true; } death_pos = true; check_spawn = false; alpha_player = 255; spin.Reset(); current_animation = &idle; break; case GO_BACKWARD: if (intermediate.Finished()) { intermediate.Reset(); } current_animation = &intermediate; break; case BACKWARD: if (backward.Finished()) backward.Reset(); current_animation = &backward; break; case BACK_IDLE: if (intermediate_return.Finished()) intermediate_return.Reset(); current_animation = &intermediate_return; break; case SPIN: SDL_Rect spin_rect = spin_circle.GetCurrentFrame(); App->render->Blit(graphics, aux_spin.x, aux_spin.y, &spin_rect); current_animation = &spin; break; case DEATH: SDL_Rect death_rect = death_circle.GetCurrentFrame(); power_up = 0; check_death = true; input = false; App->render->Blit(player_death, aux_death.x, aux_death.y, &death_rect, 1.0f); /*if (explosion) { App->particles->AddParticle(App->particles->explosion, position.x - 8, position.y - 8); explosion = false; }*/ alpha_player = 255; break; case POST_DEATH: if (App->inter->num_life_katana == 0) { if (App->inter->score_katana > 1000) { App->inter->score_katana -= 1000; } App->katana->Disable(); } else { check_death = false; } break; } }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <assert.h> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; ULL c[66][66]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); for (int i = 0; i < 65; ++i) { c[i][0] = 1; for (int j = 1; j <= i; ++j) { c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; assert(c[i][j] < 2e18); } } int T; scanf("%d", &T); while (T--) { ULL x; scanf("%lld", &x); int i = 1; for (; i < 65; ++i) if (c[i][i / 2] >= x) break; printf("%d\n", i); } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "modules/dom/src/domsuspendcallback.h" DOM_SuspendCallbackBase::DOM_SuspendCallbackBase() : m_was_called(FALSE) , m_is_async(FALSE) , m_error_code(OpStatus::OK) , m_thread(NULL) {} void DOM_SuspendCallbackBase::SuspendESThread(DOM_Runtime* origining_runtime) { OP_ASSERT(origining_runtime); SetAsync(); m_thread = DOM_Object::GetCurrentThread(origining_runtime); OP_ASSERT(m_thread); m_thread->AddListener(this); m_thread->Block(); } void DOM_SuspendCallbackBase::OnSuccess() { m_error_code = OpStatus::OK; DOM_SuspendCallbackBase::CallFinished(); } void DOM_SuspendCallbackBase::OnFailed(OP_STATUS error) { m_error_code = error; DOM_SuspendCallbackBase::CallFinished(); } void DOM_SuspendCallbackBase::CallFinished() { OP_ASSERT(!m_was_called); m_was_called = TRUE; if (IsAsync()) { if (m_thread) m_thread->Unblock(); else { // if the thread has already been terminated then unblocking it is pointless // lets just destroy this object to avoid memory leaks OP_DELETE(this); } } } /* virtual */ OP_STATUS DOM_SuspendCallbackBase::Signal(ES_Thread *thread, ES_ThreadSignal signal) { OP_ASSERT(m_thread == thread); switch (signal) { case ES_SIGNAL_SCHEDULER_TERMINATED: break; // Doesn't matter to us case ES_SIGNAL_CANCELLED: case ES_SIGNAL_FINISHED: case ES_SIGNAL_FAILED: m_thread = NULL; Remove(); // Prevent deletion of this object break; default: OP_ASSERT(FALSE); } return OpStatus::OK; } void DOM_SuspendingCall::CallFunctionSuspending(OpFunctionObjectBase* function, DOM_SuspendCallbackBase*& callback) { OP_ASSERT(m_restart_value); DOM_CallState* call_state = DOM_CallState::FromReturnValue(m_restart_value); OP_ASSERT(function); if (!call_state) { m_error_code = DOM_CallState::Make(call_state, m_origining_runtime, m_argv, m_argc); RETURN_VOID_IF_ERROR(m_error_code); DOM_Object::DOMSetObject(m_restart_value, call_state); // Pretend there is restart state even in synchronous calls. } if (call_state->GetPhase() < m_phase) { if (!callback) { m_error_code = OpStatus::ERR_NO_MEMORY; // we got oom in PREPARE_SUSPENDING_CALLBACK. return; } m_error_code = callback->Construct(); RETURN_VOID_IF_ERROR(m_error_code); m_callback = callback; function->Call(); call_state->SetPhase(m_phase); call_state->SetUserData(m_callback); if (!callback->WasCalled()) { m_error_code = call_state->PrepareForSuspend(); RETURN_VOID_IF_ERROR(m_error_code); // as SuspendESThread wasn't called the thread wasn't set then then the async callback is finished // it will just delete itself and ignore results(as if the calling ES_thread was cancelled). DOM_Object::DOMSetObject(m_return_value, call_state); callback->SuspendESThread(m_origining_runtime); m_error_code = OpStatus::ERR_YIELD; return; } } else if (call_state->GetPhase() == m_phase) { callback = reinterpret_cast<DOM_SuspendCallbackBase*>(call_state->GetUserData()); m_callback = callback; } } DOM_SuspendingCall::~DOM_SuspendingCall() { if (m_callback && m_callback->WasCalled()) OP_DELETE(m_callback); }
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "backend/opencl/OclThread.h" #include "3rdparty/rapidjson/document.h" #include "base/io/json/Json.h" #include <algorithm> namespace xmrig { static const char *kIndex = "index"; static const char *kIntensity = "intensity"; static const char *kStridedIndex = "strided_index"; static const char *kThreads = "threads"; static const char *kUnroll = "unroll"; static const char *kWorksize = "worksize"; #ifdef XMRIG_ALGO_RANDOMX static const char *kBFactor = "bfactor"; static const char *kGCNAsm = "gcn_asm"; static const char* kDatasetHost = "dataset_host"; #endif } // namespace xmrig xmrig::OclThread::OclThread(const rapidjson::Value &value) { if (!value.IsObject()) { return; } m_index = Json::getUint(value, kIndex); m_worksize = std::max(std::min(Json::getUint(value, kWorksize), 512u), 1u); m_unrollFactor = std::max(std::min(Json::getUint(value, kUnroll, m_unrollFactor), 128u), 1u); setIntensity(Json::getUint(value, kIntensity)); const auto &si = Json::getArray(value, kStridedIndex); if (si.IsArray() && si.Size() >= 2) { m_stridedIndex = std::min(si[0].GetUint(), 2u); m_memChunk = std::min(si[1].GetUint(), 18u); } else { m_stridedIndex = 0; m_memChunk = 0; m_fields.set(STRIDED_INDEX_FIELD, false); } const auto &threads = Json::getArray(value, kThreads); if (threads.IsArray()) { m_threads.reserve(threads.Size()); for (const auto &affinity : threads.GetArray()) { m_threads.emplace_back(affinity.GetInt64()); } } if (m_threads.empty()) { m_threads.emplace_back(-1); } # ifdef XMRIG_ALGO_RANDOMX const auto &gcnAsm = Json::getValue(value, kGCNAsm); if (gcnAsm.IsBool()) { m_fields.set(RANDOMX_FIELDS, true); m_gcnAsm = gcnAsm.GetBool(); m_bfactor = Json::getUint(value, kBFactor, m_bfactor); m_datasetHost = Json::getBool(value, kDatasetHost, m_datasetHost); } # endif } bool xmrig::OclThread::isEqual(const OclThread &other) const { return other.m_threads.size() == m_threads.size() && std::equal(m_threads.begin(), m_threads.end(), other.m_threads.begin()) && other.m_bfactor == m_bfactor && other.m_datasetHost == m_datasetHost && other.m_gcnAsm == m_gcnAsm && other.m_index == m_index && other.m_intensity == m_intensity && other.m_memChunk == m_memChunk && other.m_stridedIndex == m_stridedIndex && other.m_unrollFactor == m_unrollFactor && other.m_worksize == m_worksize; } rapidjson::Value xmrig::OclThread::toJSON(rapidjson::Document &doc) const { using namespace rapidjson; auto &allocator = doc.GetAllocator(); Value out(kObjectType); out.AddMember(StringRef(kIndex), index(), allocator); out.AddMember(StringRef(kIntensity), intensity(), allocator); if (!m_fields.test(ASTROBWT_FIELDS)) { out.AddMember(StringRef(kWorksize), worksize(), allocator); } if (m_fields.test(STRIDED_INDEX_FIELD)) { Value si(kArrayType); si.Reserve(2, allocator); si.PushBack(stridedIndex(), allocator); si.PushBack(memChunk(), allocator); out.AddMember(StringRef(kStridedIndex), si, allocator); } Value threads(kArrayType); threads.Reserve(m_threads.size(), allocator); for (auto thread : m_threads) { threads.PushBack(thread, allocator); } out.AddMember(StringRef(kThreads), threads, allocator); if (m_fields.test(RANDOMX_FIELDS)) { # ifdef XMRIG_ALGO_RANDOMX out.AddMember(StringRef(kBFactor), bfactor(), allocator); out.AddMember(StringRef(kGCNAsm), isAsm(), allocator); out.AddMember(StringRef(kDatasetHost), isDatasetHost(), allocator); # endif } else if (!m_fields.test(ASTROBWT_FIELDS) && !m_fields.test(KAWPOW_FIELDS)) { out.AddMember(StringRef(kUnroll), unrollFactor(), allocator); } return out; }
#include "precompiled.h" #include "console/console.h" #include "settings/settings.h" #include "settings/jssettings.h" namespace settings { typedef stdext::hash_map<char*, Setting*, hash_char_ptr_traits> settings_hash_map; bool standard_setter(char* name, void* value); bool standard_getter(char* name, void* value); settings_hash_map settings_map; void con_settings(int argc, char* argv[], void* user); }; REGISTER_STARTUP_FUNCTION(settings, settings::init, 10); void settings::init(void) { console::addCommand("settings", con_settings); } void settings::release(void) { settings_hash_map::iterator iter; while (!settings_map.empty()) { Setting* setting = (*settings_map.begin()).second; settings_map.erase(settings_map.begin()); delete setting; } } void settings::addsetting(char* name, U8 type, U32 flags, setFunction setter, getFunction getter, void* data) { Setting* setting = new Setting(); setting->name = _strdup(name); setting->type = type; setting->flags = flags; setting->data = data; if (data) setting->data = data; else switch (type) { case TYPE_STRING: setting->data = malloc(MAX_PATH); ((char*)(setting->data))[0] = 0; setting->flags |= FLAG_MANAGE_MEM; break; case TYPE_INT: setting->data = malloc(sizeof(int)); setting->flags |= FLAG_MANAGE_MEM; break; case TYPE_FLOAT: setting->data = malloc(sizeof(float)); setting->flags |= FLAG_MANAGE_MEM; break; default: break; } if (setter) setting->set = setter; else { switch (type) { case TYPE_STRING: setting->set = string_setter; break; case TYPE_INT: setting->set = int_setter; break; case TYPE_FLOAT: setting->set = float_setter; break; default: break; } } if (getter) setting->get = getter; else { switch (type) { case TYPE_STRING: setting->get = string_getter; break; case TYPE_INT: setting->get = int_getter; break; case TYPE_FLOAT: setting->get = float_getter; break; default: break; } } settings_map.insert(settings_hash_map::value_type(setting->name, setting)); jssettings::addsetting(setting); //console::log(console::FLAG_INFO, "[settings::addsetting] added \"%s\"", setting->name); } settings::Setting* settings::findsetting(char* name) { settings_hash_map::iterator iter = settings_map.find(name); if (iter != settings_map.end()) { //console::log(console::LVL_INFO, "[settings::addsetting] looked up \"%s\"", name); return (*iter).second; } else return NULL; } bool settings::string_setter(Setting* setting, void* value) { strcpy((char*)setting->data, (char*)value); return true; } bool settings::int_setter(Setting* setting, void* value) { *((int*)setting->data) = *((int*)value); return true; } bool settings::float_setter(Setting* setting, void* value) { *((float*)setting->data) = *((float*)value); return true; } bool settings::string_getter(Setting* setting, void** value) { *value = setting->data; return true; } bool settings::int_getter(Setting* setting, void** value) { *value = setting->data; return true; } bool settings::float_getter(Setting* setting, void** value) { *value = setting->data; return true; } bool settings::setstring(char* name, char* value) { Setting* setting; ASSERT((setting = findsetting(name))); if (!(setting = findsetting(name))) return false; return setting->set(setting, value); } bool settings::setint(char* name, int value) { Setting* setting; ASSERT((setting = findsetting(name))); if (!(setting = findsetting(name))) return false; return setting->set(setting, &value); } bool settings::setfloat(char* name, float value) { Setting* setting; ASSERT((setting = findsetting(name))); if (!(setting = findsetting(name))) return false; return setting->set(setting, &value); } char* settings::getstring(char* name) { Setting* setting; char* retval = NULL; ASSERT((setting = findsetting(name))); if (!(setting = findsetting(name))) return false; setting->get(setting, (void**)&retval); return retval; } int settings::getint(char* name) { Setting* setting; int* retval = NULL; ASSERT((setting = findsetting(name))); if (!(setting = findsetting(name))) return false; setting->get(setting, (void**)&retval); return *retval; } float settings::getfloat(char* name) { Setting* setting; float* retval = NULL; ASSERT((setting = findsetting(name))); if (!(setting = findsetting(name))) return false; setting->get(setting, (void**)&retval); return *retval; } void settings::dump(char* pattern, bool sort) { list<string> blah; if (pattern) { for (settings_hash_map::iterator iter = settings_map.begin(); iter != settings_map.end(); iter++) if (wildcmp(pattern, ((Setting*)((*iter).second))->name)) blah.push_back((string)((Setting*)((*iter).second))->name); } else { for (settings_hash_map::iterator iter = settings_map.begin(); iter != settings_map.end(); iter++) blah.push_back((string)((Setting*)((*iter).second))->name); } if (sort) blah.sort(); for (list<string>::iterator li = blah.begin(); li != blah.end(); li++) { settings_hash_map::iterator iter = settings_map.find((char*)(*li).c_str()); Setting* setting = (Setting*)((*iter).second); switch (setting->type) { case TYPE_STRING: INFO("%s%s = \"%s\";", setting->flags & FLAG_READONLY ? "//" : "", setting->name, getstring(setting->name)); break; case TYPE_INT: INFO("%s%s = %i;", setting->flags & FLAG_READONLY ? "//" : "", setting->name, getint(setting->name)); break; case TYPE_FLOAT: INFO("%s%s = %f;", setting->flags & FLAG_READONLY ? "//" : "", setting->name, getfloat(setting->name)); break; default: INFO("// %s = <unkown type>", setting->name); break; } } } void settings::con_settings(int argc, char* argv[], void* user) { if (argc == 1) dump(); else dump(argv[1]); }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #define INF (1<<20) #define MAX 101 using namespace std; class RotatedClock { public: string getEarliest(int hourHand, int minuteHand) { string ans; for (int mark = 0; mark < 360; mark+=30) { int hour = (hourHand+mark)%360; int minute = (hour*12)%360; if (minute == (minuteHand+mark)%360) { hour /= 30; minute /= 6; char a[] = "00:00"; sprintf(a, "%.2d:%.2d",hour,minute); ans = static_cast<string>(a); break; } } return ans; } };
#include "stdafx.h" #include "Camera.h" Camera::Camera() { } Camera::~Camera() { } void Camera::UpdateMatrix() { Vector2 LookAt = position + Vector2(0, 0, 1); matView = Matrix::View(position, LookAt, up); matProjection = Matrix::Ortho(0, WINSIZE_X, WINSIZE_Y, 0, 0, 1.0f); matViewProjection = matView * matProjection; } void Camera::UpdateCamToDevice() { this->UpdateMatrix(); D2D::GetDevice()->SetTransform( D3DTS_VIEW, &this->matView.ToDXMatrix()); D2D::GetDevice()->SetTransform( D3DTS_PROJECTION, &this->matProjection.ToDXMatrix()); }
#ifndef DEDVS_ENUMS_H #define DEDVS_ENUMS_H namespace dedvs { enum DEdvsStatus { DEDVS_STATUS_OK = 0, DEDVS_STATUS_ERROR = 1, DEDVS_STATUS_BAD_PARAMETER = 2, DEDVS_STATUS_DEVICE_ERROR = 3, DEDVS_STATUS_STREAM_ERROR = 4, DEDVS_STATUS_HW_ERROR = 5 }; enum OpenNIStreamType { DEPTH, COLOR //IR, but we ignore that for now }; } #endif
#include <iostream> #include <string> using namespace std; #include "pbaf_protocol_service.h" int main(int argc, char** args) { if(argc < 3) { cout << "Usage: connect_disconnect <host> <port>" << endl; return 1; } pbaf_server serv; serv.address = string(args[1]); serv.port = atoi(args[2]); pbaf_proto_connect(&serv); pbaf_proto_disconnect(&serv); return 0; }
#include <CQXYVals.h> #include <CXYVals.h> #include <QApplication> #include <QPainter> #include <QLabel> #include <QHBoxLayout> #include <QMouseEvent> #include <QKeyEvent> int main(int argc, char **argv) { QApplication app(argc, argv); for (int i = 1; i < argc; ++i) { std::string arg(argv[i]); if (arg == "-test") { bool rc = CXYValsInside::unitTest(); exit(rc); } } //--- CQXYValsTest test; test.resize(800, 800); test.show(); return app.exec(); } CQXYValsTest:: CQXYValsTest() { setObjectName("test"); QHBoxLayout *layout = new QHBoxLayout(this); layout->setMargin(0); layout->setSpacing(0); canvas_ = new CQXYValsCanvas(this); layout->addWidget(canvas_); } //----------- CQXYValsCanvas:: CQXYValsCanvas(CQXYValsTest *test) : QWidget(0), test_(test) { setObjectName("canvas"); setFocusPolicy(Qt::StrongFocus); //setMouseTracking(true); } void CQXYValsCanvas:: paintEvent(QPaintEvent *) { static QColor colors[] = { // blue QColor(0x31,0x82,0xBD), QColor(0x6B,0xAE,0xD6), QColor(0x9E,0xCA,0xE1), QColor(0xC6,0xDB,0xEF), // orange QColor(0xE6,0x55,0x0D), QColor(0xFD,0x8D,0x3C), QColor(0xFD,0xAE,0x6B), QColor(0xFD,0xD0,0xA2), // green QColor(0x31,0xA3,0x54), QColor(0x74,0xC4,0x76), QColor(0xA1,0xD9,0x9B), QColor(0xC7,0xE9,0xC0), // purple QColor(0x75,0x6B,0xB1), QColor(0x9E,0x9A,0xC8), QColor(0xBC,0xBD,0xDC), QColor(0xDA,0xDA,0xEB), // gray QColor(0x63,0x63,0x63), QColor(0x96,0x96,0x96), QColor(0xBD,0xBD,0xBD), QColor(0xD9,0xD9,0xD9), }; static int numColors = 20; //--- QPainter painter(this); painter.fillRect(rect(), Qt::white); if (pressed_) { int x1 = std::min(pressPos_.x(), releasePos_.x()); int y1 = std::min(pressPos_.y(), releasePos_.y()); int x2 = std::max(pressPos_.x(), releasePos_.x()); int y2 = std::max(pressPos_.y(), releasePos_.y()); int w = x2 - x1; int h = y2 - y1; if (w > 0 && h > 0) { QRect r(x1, y1, w, h); painter.setPen(Qt::red); painter.drawRect(r); } } //--- const std::vector<double> &xv = valueData_.xyvals.xvals(); const std::vector<double> &yv = valueData_.xyvals.yvals(); painter.setPen(Qt::black); for (uint iy = 1; iy < yv.size(); ++iy) { int y1 = yv[iy - 1]; int y2 = yv[iy ]; int h = y2 - y1; for (uint ix = 1; ix < xv.size(); ++ix) { int x1 = xv[ix - 1]; int x2 = xv[ix ]; int w = x2 - x1; QRect r(x1, y1, w, h); CXYValsInside::InsideValue val = valueData_.xyvals.insideVal(ix - 1, iy - 1); if (val > 0) { QColor fc = colors[(val - 1) % numColors]; painter.fillRect(r, fc); } painter.setPen(Qt::black); painter.drawRect(r); } } //--- for (uint i = 0; i < valueData_.oqpolygons.size(); ++i) { QPen pen(Qt::green); pen.setWidth(3); painter.setPen(pen); painter.drawPolygon(valueData_.oqpolygons[i]); } QFontMetrics fm(font()); for (uint i = 0; i < valueData_.ipolygons.size(); ++i) { const CXYVals::Polygon &polygon = valueData_.ipolygons[i]; double area = valueData_.xyvals.polygonArea (polygon); CXYValsInside::InsideValue val = valueData_.xyvals.polygonValue(polygon); double xc, yc; polygon.centroid(xc, yc); QString text = QString("%1 (%2)").arg(val).arg(area); int tw = fm.width(text); painter.setPen(Qt::black); painter.drawText(xc - tw/2, yc, text); } } void CQXYValsCanvas:: mousePressEvent(QMouseEvent *me) { pressed_ = true; pressPos_ = me->pos(); releasePos_ = pressPos_; update(); } void CQXYValsCanvas:: mouseMoveEvent(QMouseEvent *me) { releasePos_ = me->pos(); update(); } void CQXYValsCanvas:: mouseReleaseEvent(QMouseEvent *me) { pressed_ = false; releasePos_ = me->pos(); double x1 = pressPos_ .x(); double y1 = pressPos_ .y(); double x2 = releasePos_.x(); double y2 = releasePos_.y(); //--- std::vector<double> x { x1, x2, x2, x1}; std::vector<double> y { y1, y1, y2, y2}; CXYVals::Polygon poly(x, y); valueData_.ipolygons .push_back(poly); valueData_.iqpolygons.push_back(toQPolygon(poly)); //--- updatePolygons(); update(); } void CQXYValsCanvas:: updatePolygons() { valueData_.xyvals.initValues(valueData_.ipolygons); valueData_.opolygons .clear(); valueData_.oqpolygons.clear(); if (valueData_.xyvals.getPolygons(valueData_.opolygons)) { for (uint j = 0; j < valueData_.opolygons.size(); ++j) { const CXYValsInside::Polygon &polygon = valueData_.opolygons[j]; valueData_.oqpolygons.push_back(toQPolygon(polygon)); } } valueData1_ = valueData_; } void CQXYValsCanvas:: getPolygons() { valueData_.ipolygons .clear(); valueData_.iqpolygons.clear(); if (valueData_.xyvals.getPolygons(valueData_.ipolygons)) { for (uint j = 0; j < valueData_.ipolygons.size(); ++j) { const CXYValsInside::Polygon &polygon = valueData_.ipolygons[j]; valueData_.iqpolygons.push_back(toQPolygon(polygon)); } } valueData_.opolygons = valueData_.ipolygons; valueData_.oqpolygons = valueData_.iqpolygons; } QPolygon CQXYValsCanvas:: toQPolygon(const CXYVals::Polygon &polygon) const { QPolygon poly; for (int i = 0; i < polygon.size(); ++i) poly.push_back(QPoint(polygon.x[i], polygon.y[i])); poly.push_back(QPoint(polygon.x[0], polygon.y[0])); return poly; } void CQXYValsCanvas:: keyPressEvent(QKeyEvent *ke) { if (ke->key() == Qt::Key_Delete) { // clear grid valueData_.ipolygons .clear(); valueData_.iqpolygons.clear(); updatePolygons(); update(); } else if (ke->key() == Qt::Key_C) { valueData1_ = valueData_; // combine connected cells valueData_.xyvals.combineInside(); valueData_.xyvals.setPolygonInsideValues(); getPolygons(); update(); } else if (ke->key() == Qt::Key_F) { valueData1_ = valueData_; // fill valueData_.xyvals.fill(); getPolygons(); update(); } else if (ke->key() == Qt::Key_H) { valueData1_ = valueData_; // fill disconnected rows valueData_.xyvals.fillDisconnectedRows(); valueData_.xyvals.setPolygonInsideValues(); getPolygons(); update(); } else if (ke->key() == Qt::Key_V) { valueData1_ = valueData_; // fill disconnected columns valueData_.xyvals.fillDisconnectedColumns(); valueData_.xyvals.setPolygonInsideValues(); getPolygons(); update(); } else if (ke->key() == Qt::Key_S) { // display smallest CXYValsInside::InsideValue i = valueData_.xyvals.findSmallest(); std::cerr << i << "(" << valueData_.xyvals.valueArea(i) << ")" << std::endl; } else if (ke->key() == Qt::Key_P) { // print valueData_.xyvals.print(std::cerr); std::cerr << std::endl; } else if (ke->key() == Qt::Key_R) { // replace input polygons with extracted polygons valueData_.ipolygons = valueData_.opolygons; valueData_.iqpolygons = valueData_.oqpolygons; updatePolygons(); update(); } else if (ke->key() == Qt::Key_U) { valueData_ = valueData1_; update(); } }
#include "widget.h" #include "ui_widget.h" #include "mymodel.h" #include "sampledata.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); model = new MyModel(this); ui->widget->setModel(model); } Widget::~Widget() { delete ui; } void Widget::on_setTestData1Button_clicked() { int data = 100; model->setTestData(data); } void Widget::on_setSampleDataButton_clicked() { SampleData sampleData; sampleData.setData(QString("test")); model->setSampleData(sampleData); }
#include "IState.h" #include "StateMenu.h" #include "Flashcards.h" #include "StateOptions.h" #include "Window.h" #include "StateManage.h" #include "StateStart.h" void changeState(IState *(&state)) { if ( state->getStateMenu() ) { //delete state; state = new StateMenu(); } else if ( state->getStateOptions() ) { //delete state; state = new StateOptions(); } else if ( state->getStateManage() ) { //delete state; state = new StateManage(); } else if ( state->getStateStart() ) { //delete state; state = new StateStart(); } } int main() { Sound::instance().playSoundtrack(); IState* state = new StateMenu(); while(!state->toExit()) { state->update(); state->render(); changeState(state); } return 0; }
#include<fstream> #include <iostream> #include<conio.h> #include<stdio.h> using namespace std; struct student { char name[50]; char lecturer[50]; int id; char course[20]; int lvl; char contact[10]; int marks; char grade[4]; }; int main() { fstream fin; fin.open("base.txt"); char dow; int arr=0; do{ student stud[10]; cout<<" Press 1 to Enter Record \n"; cout<<" Press 2 to Delete Record \n"; cout<<" Press 3 to Edit Record \n"; cout<<" Press 4 to Search Record \n"; cout<<" Press 5 to Display Record \n"; cout<<" Press 6 to Save \n"; cout<<" Take NOTE: IF YOU WANT TO SAPACE OUT USE '_'"; cout<<"\n \t Select Option: "; int idnchek=0; int sw; cin>>sw; switch (sw) { case 1: cout<<"\n Enter the Data of the student no "<<arr+1<<" is :\n"; cout<<"\t Enter the ID No = "; int idn2; int idn; cin>>idn; for(int j=0;j<=arr;j++) { idn2=idn; if(idn2==stud[j].id) { idnchek=1; } } if(idnchek!=1){ stud[arr].id=idn; cout<<"\t Enter your Name = "; cin>>stud[arr].name; cout<<"\t Enter the Lecturer`s name = "; cin>>stud[arr].lecturer; cout<<"\t Enter your contact = "; cin>>stud[arr].contact; cout<<"\t Enter the Course Title = "; cin>>stud[arr].course; cout<<"\t Enter your Marks = "; cin>>stud[arr].marks; cout<<"\t Enter your Grade = "; cin>>stud[arr].grade; cout<<"\t Enter your level = "; cin>>stud[arr].lvl; arr=arr+1; } else { cout<<"This Record Already Enterd \n"; } break; case 2: cout<<"\n Enter the ID no of the student To Delete ::\n"; cin>>idn; for(int j=0;j<=arr;j++) { idn2=idn; if(idn2==stud[j].id) { stud[j].id='d'; cout<<"\t Record Deleted"; } } break; case 3: cout<<"\n Enter the ID no of the student To Update ::\n"; cin>>idn; for(int j=0;j<=arr;j++) { idn2=idn; if(idn2==stud[j].id) { cout<<"ID = "; cout<<stud[j].id<<endl; cout<<"Name = "; cout<<stud[j].name<<endl; cout<<"Lecturer = "; cout<<stud[j].lecturer<<endl; cout<<"Contact = "; cout<<stud[j].contact<<endl; cout<<"Course_Title = "; cout<<stud[j].course<<endl; cout<<"Markes = "; cout<<stud[j].marks<<endl; cout<<"Grade = "; cout<<stud[j].grade<<endl; cout<<"\n\t ReEnter Data "; cout<<"\n\t Enter the Name = "; cin>>stud[j].name; cout<<"\n\t Enter the lecturer = "; cin>>stud[j].lecturer; cout<<"\n\t Enter the contact = "; cin>>stud[j].contact; cout<<"\n\t Enter the Course Title = "; cin>>stud[j].course; cout<<"\n\t Enter the Markes = "; cin>>stud[j].marks; cout<<"\n\t Enter the Grade = "; cin>>stud[j].grade; cout<<"\n\t Enter the lvl = "; cin>>stud[j].lvl; } } break; case 4: cout<<"\n Enter the ID no of the student To Search ::"; cin>>idn; for(int j=0;j<=arr;j++) { idn2=idn; if(idn2==stud[j].id) { cout<<"\n \t ID = "; cout<<stud[j].id; cout<<"\n \t Name = "; cout<<stud[j].name; cout<<"\n \t lecturer = "; cout<<stud[j].lecturer; cout<<"\n \t Level ="; cout<<stud[j].lvl; cout<<"\n \t contact = "; cout<<stud[j].contact; cout<<"\n \t Course Title = "; cout<<stud[j].course; cout<<"\n \t Markes = "; cout<<stud[j].marks; cout<<"\n \t Grade = "; cout<<stud[j].grade; }} break; case 6: fin<<"\n*************************************************************************\n"; for(int i=0;i<1;i++) { for(int k=0;k<arr;k++) { if (stud[k].id!='d') { fin<<"Record of student "<<k+1<<endl; fin<<"ID"<<" : "<<stud[k].id<<endl; fin<<"Name"<<" : "<<stud[k].name<<endl; fin<<"Lecturer"<<" : "<<stud[k].lecturer<<endl; fin<<"Level"<<" : "<<stud[k].lvl<<endl; fin<<"Contact"<<" : "<<stud[k].contact<<endl; fin<<"Course_Title"<<" : "<<stud[k].course<<endl; fin<<"Markes"<<" : "<<stud[k].marks<<endl; fin<<"Grade"<<" : "<<stud[k].grade<<endl; fin<<" "<<endl; fin<<"\n"; } }} fin<<"\n*****************************************************************************"; break; case 5: cout<<"\n*************************************************************************\n"; for(int i=0;i<1;i++) { for(int k=0;k<arr;k++) { if (stud[k].id!='d') { cout<<"Record of student "<<k+1<<endl; cout<<"ID"<<" : "<<stud[k].id<<endl; cout<<"Name"<<" : "<<stud[k].name<<endl; cout<<"Lecturer"<<" : "<<stud[k].lecturer<<endl; cout<<"Level"<<" : "<<stud[k].lvl<<endl; cout<<"Contact"<<" : "<<stud[k].contact<<endl; cout<<"Course_Title"<<" : "<<stud[k].course<<endl; cout<<"Markes"<<" : "<<stud[k].marks<<endl; cout<<"Grade"<<" : "<<stud[k].grade<<endl; cout<<" "<<endl; cout<<"\n"; } }} cout<<"\n*****************************************************************************"; break; default: cout<<"\t Worng option Selected "; break; } cout<<"\n \n \t Do You want to Continue Again [Y/N]"; cin>>dow; } while(dow=='y'); return 0; getch(); }
#include "Calculate.h" #include "Account.h" #include "Menu.h" #include "Draw.h" #include <string> //this function is old, no longer used void Draw::DrawTable(Menu& menu, Account& newAccount, int page) { printf("%-10s%-10s%-16s%-10s\n", "Year", "Deposit", "Interest", "Balance"); for (int i = 0; i < newAccount.GetNumberOfYears(); i++) { printf("%-10d", i + 1); printf("%-10.2f", newAccount.GetMonthlyDeposit()); printf("% 1s", "$"); printf("%-15.2f", newAccount.GetYearlyInterestEarned(i)); printf("% 1s", "$"); printf("%-10.2f", newAccount.GetYearlyBalance(i)); cout << endl; } } //this function draws the pages for the years //it was written first, the next function was a carbon copy //this was easier than trying to write a function as long as both combined that took in endless //params and checked for months versus years //a project for another time void Draw::DrawPages(Account& newAccount, int minEntry, int maxEntry) { //this function gets called from the Account file, from GetPages() //draw the header cout << " AirGead Banking: Account Statistics" << endl; cout << setw(86) << setfill('=') << " " << endl; cout << setfill(' '); cout << right << setw(5) << "Year" << setw(25) << "Monthly Deposit" << setw(25) << "Interest Earned" << setw(30) << "Year-end Balance" << endl; cout << setw(86) << setfill('-') << " " << endl; cout << setfill(' '); string output; //draw all the items through a loop //min and max entry vars let it know when to stop for (int i = minEntry; i < maxEntry; i++) { cout << fixed << right << setw(5) << i + 1; output = "$" + to_string(newAccount.GetMonthlyDeposit()); size_t pos = output.find("."); output = output.substr(0, pos + 3); cout << fixed << setprecision(2) << setw(25) << right << output; output = "$" + to_string(newAccount.GetYearlyInterestEarned(i)); pos = output.find("."); output = output.substr(0, pos + 3); cout << fixed << setw(25) << right << output; output = "$" + to_string(newAccount.GetYearlyBalance(i)); pos = output.find("."); output = output.substr(0, pos + 3); cout << fixed << setw(30) << right << output; cout << endl; cout << endl; } } //this is the same function as above //gets called from Account, GetMonthPages() void Draw::DrawMonthPages(Account& newAccount, int minEntry, int maxEntry) { cout << " AirGead Banking: Account Statistics" << endl; cout << setw(86) << setfill('=') << " " << endl; cout << setfill(' '); cout << right << setw(5) << "Month" << setw(25) << "Monthly Deposit" << setw(25) << "Interest Earned" << setw(30) << "Month-end Balance" << endl; cout << setw(86) << setfill('-') << " " << endl; cout << setfill(' '); string output; for (int i = minEntry; i < maxEntry; i++) { cout << fixed << right << setw(5) << i + 1; output = "$" + to_string(newAccount.GetMonthlyDeposit()); size_t pos = output.find("."); output = output.substr(0, pos + 3); cout << fixed << setprecision(2) << setw(25) << right << output; output = "$" + to_string(newAccount.GetMonthlyInterestEarned(i)); pos = output.find("."); output = output.substr(0, pos + 3); cout << fixed << setw(25) << right << output; output = "$" + to_string(newAccount.GetMonthlyBalance(i)); pos = output.find("."); output = output.substr(0, pos + 3); cout << fixed << setw(30) << right << output; cout << endl; cout << endl; } } //this function draws the menu at the bottom of the main page void Draw::DrawMenu(Account& newAccount, Menu& newMenu, int item) { //draw the menu at the bottom newMenu.SetNewCursor(17, 0); printf("%25s%-10.2f\n", "Initial Investment: ", newAccount.GetInitialInvestment()); printf("%25s%-10.2f\n", "Monthly Deposit: ", newAccount.GetMonthlyDeposit()); printf("%25s%-10.3f\n", "Interest Rate: ", newAccount.GetInterestRate()); printf("%25s%-10d\n", "Number of Years: ", newAccount.GetNumberOfYears()); //switch to determine which item is selected, and thus gets highlighted newMenu.HideCursorBlink(); newMenu.SetColor(240); switch (item) { case 1: { newMenu.SetNewCursor(17, 25); printf("%-10.2f\n", newAccount.GetInitialInvestment()); break; } case 2: { newMenu.SetNewCursor(18, 25); printf("%-10.2f\n", newAccount.GetMonthlyDeposit()); break; } case 3: { newMenu.SetNewCursor(19, 25); printf("%-10.3f\n", newAccount.GetInterestRate()); break; } case 4: { newMenu.SetNewCursor(20, 25); printf("%-10d\n", newAccount.GetNumberOfYears()); break; } default: { } } //reset the color newMenu.SetColor(15); } //this function draws everything... starts with the pages at the bottom of the table void Draw::DrawEverything(Menu& newMenu, Account& newAccount, int page, int selection, Draw& newDraw, int item, int data) { system("cls"); newMenu.SetColor(15); newMenu.SetNewCursor(14, 0); cout << setw(86) << setfill('-') << " " << endl; cout << setfill(' '); newMenu.SetNewCursor(15, 37); cout << "Page " << page + 1 << " of " << newAccount.GetNumberOfPages() << endl; newMenu.SetNewCursor(15, 21); cout << "< <"; newMenu.SetNewCursor(15, 62); cout << "> >"; newMenu.SetNewCursor(0, 0); if (data == 0) { //check to see if it's months or years to show newAccount.GetPages(page, newAccount, newDraw); } else if (data == 1) { newAccount.GetMonthPages(page, newAccount, newDraw); } newDraw.DrawMenu(newAccount, newMenu, item); //draw the menu at the bottom DrawInstructions(newMenu); //draw the instructions at the bottom //return to RunMainProgram } //draw the splash page and menu int Draw::DrawMainTitle(Menu& newMenu) { int selection = 1; string sub = "Banking for the masses."; string inst = "Use arrow keys and 'enter' to select."; string splash[6]; splash[0] = " ___ _ ______ __"; splash[1] = " / | (_)____/ ____/__ ____ _____/ /"; splash[2] = " / /| | / / ___/ / __/ _ \\/ __ `/ __ / "; splash[3] = " / ___ |/ / / / /_/ / __/ /_/ / /_/ / "; splash[4] = "/_/ |_/_/_/ \\____/\\___/\\__,_/\\__,_/ "; splash[5] = " "; int columns = newMenu.GetWindowWidth(); int column = columns; int row = 2; column /= 2; column = column - (splash[0].length() / 2); for (int i = 0; i < 6; i++) { newMenu.SetNewCursor(row, column); cout << splash[i] << endl; row++; } row++; column = columns / 2 - (sub.length() / 2); newMenu.SetNewCursor(row, column); cout << sub << endl; column = columns / 2 - (inst.length() / 2); newMenu.SetNewCursor(20, column); cout << inst << endl; return row; } //draws the about section below the menu void Draw::DrawAbout(Menu& newMenu, Account& newAccount, Draw& newDraw) { system("cls"); vector<string> about = { "AirGead Banking Corp.", "Copyright © 2021", "All rights reserved." }; newMenu.MenuModifier(about); int row = 0; int column = newMenu.GetWindowWidth(); column = column / 2 - (about.at(0).length() / 2); row = DrawMainTitle(newMenu) + 16; for (int i = 0; i < about.size(); i++) { newMenu.SetNewCursor(row, column); cout << about.at(i) << endl; row++; } } //draw the instructions for the main account window void Draw::DrawInstructions(Menu& newMenu) { newMenu.SetNewCursor(23, 0); cout << "**HOT KEYS: up/down to navigate inputs, 'enter' to change" << endl; cout << " left/right arrows to navigate pages" << endl; cout << " 'm' to change view, 'i' to return to account input, 'q' to quit" << endl; }
#pragma once #include "cow_resource.hpp" struct SDL_Texture; extern "C" void SDL_DestroyTexture(SDL_Texture*); namespace SDL { // C++ wrapper around SDL_Texture* using RAII ref counting. struct Texture { Texture() {} explicit Texture(SDL_Texture* ptr) : res(ptr) {} Texture(Texture&& t) : res(std::move(t.res)) {} Texture(const Texture&) = delete; Texture& operator=(Texture&& o) { res = std::move(o.res); return *this; } // Accessors SDL_Texture* get() { return res.get(); } SDL_Texture* release() { return res.release(); } // Object-based methods private: struct DestroyTexture { inline void operator()(SDL_Texture* s) { SDL_DestroyTexture(s); } }; std::unique_ptr<SDL_Texture, DestroyTexture> res; }; }
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include "Core/Platform.hpp" #ifdef PUSH_PLATFORM_IOS #import <UIKit/UIKit.h> #import <OpenGLES/EAGL.h> #import <OpenGLES/ES2/gl.h> #import <OpenGLES/ES2/glext.h> #import <QuartzCore/QuartzCore.h> @interface GLView : UIView<UIAccelerometerDelegate> { EAGLContext* m_context; GLuint m_frameBuffer; GLuint m_renderBuffer; GLuint m_depthBuffer; int m_frameBufferWidth; int m_frameBufferHeight; CADisplayLink* m_displayLink; } - (void)InitOpenGL; - (void)StartAnimation; - (void)StopAnimation; - (void)Step; @end #endif
#include <cstdio> using namespace std; enum TipoPeli{ t, m, a, i }; struct Fecha{ int dia; int mes; int anho; }; struct Artista{ char nombre[10]; char apellidos[20]; Fecha fnac; }; struct Pelicula{ int codigo; char titulo[20]; TipoPeli genero; Artista artistappal; }; void rellenar(Pelicula &p); void mostrarPeli(Pelicula p); int main() { ///1. Definir la estructura registro necesaria para almacenar la información ///correspondiente a una película sabiendo que los datos que se desean almacenar ///son: código, título, género (terror, musical, acción, infantil ) y artista principal ///(nombre, apellidos, fecha de nacimiento (día, mes y año)). Pelicula p; rellenar(p); mostrarPeli(p); } void rellenar ( Pelicula &p){ char d; printf("\nCodigo de la pelicula: "); scanf("%d", &p.codigo); printf("Titulo: "); scanf("%s", &p.titulo); fflush(stdin); printf("Genero (terror[t], musical[m], accion[a], infantil[i] "); scanf("%c", &d); switch(d){ case 't': p.genero = t; break; case 'm': p.genero = m; break; case 'a': p.genero = a; break; case 'i': p.genero = i; break; } printf("\nIntroduzca datos artista principal:\nNombre: "); scanf("%s", &p.artistappal.nombre); printf("\nApellidos: "); scanf("%s", &p.artistappal.apellidos); printf("\nAhora su fecha de nacimiento: "); printf("Dia: "); scanf("%d", &p.artistappal.fnac.dia); printf("Mes: "); scanf("%d", &p.artistappal.fnac.mes); printf("Anho: "); scanf("%d", &p.artistappal.fnac.anho); } void mostrarPeli(Pelicula p){ printf("\nCodigo de la pelicula: %d", p.codigo); printf("Titulo: %s", p.titulo); printf("\nDatos artista principal: "); printf("\nNombre: %s", p.artistappal.nombre); printf("\nApellidos: %s", p.artistappal.apellidos); printf("\nAhora su fecha de nacimiento: "); printf("\n%d", p.artistappal.fnac.dia); printf("/%d", p.artistappal.fnac.mes); printf("/%d", p.artistappal.fnac.anho); printf("\nGenero:"); switch (p.genero){ case t: printf("Terror"); break; case m: printf("Musical"); break; case a: printf("Accion"); break; case i: printf("Infantil"); break; } }
// 1006_5.cpp : 定义控制台应用程序的入口点。 /*环形染色问题 * RPG三种颜色每格涂一色,要求任何相邻的方格不能同色, * 且首尾两格也不同色.求全部的满足要求的涂法 */ #include<iostream> using namespace std; int main() { int n; while (cin >> n && n != EOF) { if (n <= 0 || n > 50) break; long long s[60] = { 0,3,6,6 }; for (int i = 4; i < 60; i++) { s[i] = s[i - 1] + 2 * s[i - 2]; } cout << s[n] << endl; } return 0; }
#include "World.h" #include "Player.h" #include "Systems/InputSystem.h" #include "Systems/PhysicsSystem.h" #include "Systems/AnimationSystem.h" #include "Systems/ActionStateSystem.h" #include "Systems/CollisionSystem.h" #include "Systems/CameraController.h" #include "Systems/MatchSystem.h" #include "Systems/NetworkSystem.h" #include "SkeletonAnimations.h" #include "Renderer/Renderer.h" #include "Texture2D.h" #include "Animation/Sprite.h" #include "UserInput.h" #include "Key.h" #include "imgui.h" #include "glm/gtc/type_ptr.hpp" #include "ImGui/GUILayer.h" #include "GLFW/glfw3.h" #include "Physics/Raycaster.h" #include "Components/LevelComponent.h" #include "Systems/VFXSystem.h" #include "Systems/AISystem.h" World world = World(); Player* player_one = nullptr; Player* player_two = nullptr; Level level = Level(); bool is_ai_active = false; void setup_world() { world.player_one = new Player(); world.player_two = new Player(); setup_player(world.player_one, world.player_two, 0); setup_player(world.player_two, world.player_one, 1); player_one = world.player_one; player_two = world.player_two; player_one->Animation.Color = glm::vec4(0.0f, 1.0f, 0.0f, 1.0f); player_two->Animation.Color = glm::vec4(0.0f, 0.0f, 1.0f, 1.0f); level.Texture = *load_texture("assets/textures/Level.png"); level.Sprite = Sprite(&level.Texture, 256, 22, 0); level.Scale = glm::vec2(level.Sprite.Width * 0.02f, level.Sprite.Height * 0.02f); level.Position = glm::vec2(0.0f, -1.17f); level.Collider.Scale = glm::vec2(level.Scale.x, level.Scale.y * 0.80f); level.Collider.Position = level.Position; add_target_collider(&level.Collider); set_world(&world); state_initialize(*player_one); state_initialize(*player_two); begin_match(); } void update_world(float dt, float fixed_dt) { debug_functionality(); //update_ai_system(*player_one, dt); update_input_system(player_one); if (is_ai_active) { update_ai_system(*player_two, dt); } else { update_input_system(player_two); } update_action_state_system(player_one, dt * get_time_scale()); update_action_state_system(player_two, dt * get_time_scale()); // TODO don't store player as a pointer maybe //state_update(*player_one, dt * get_time_scale()); //state_update(*player_two, dt * get_time_scale()); update_physics_system(player_one, player_two, dt * get_time_scale()); test_collisions(); resolve_collisions(*player_one); resolve_collisions(*player_two); update_animation_system(player_one, dt * get_time_scale()); update_animation_system(player_two, dt * get_time_scale()); camera_update(player_one, player_two, dt); vfx_update(dt); // HACK to render level without adding separate buffers update_player_animation(nullptr, &level.Sprite); render_quad(level.Texture, level.Position, level.Scale, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); begin_GUI(); update_match(dt); ImGui::Begin("Player stats"); ImGui::Text("Player: %i\n pos state: %s\n action state: %s\n Health: %f", player_one->ID, get_position_state_name((int)player_one->ActionState.Position_state), get_action_state_name((int)player_one->ActionState.Action_state), player_one->Combat.Current_health_percentage); ImGui::Text("Player: %i\n pos state: %s\n action state: %s\n Health: %f", player_two->ID, get_position_state_name((int)player_two->ActionState.Position_state), get_action_state_name((int)player_two->ActionState.Action_state), player_two->Combat.Current_health_percentage); /*ImGui::Text("Player: %i\n pos state: %s\n action state: %s\n Health: %f", player_one->ID, player_one->StateC.Current_position_state.Name.c_str(), player_one->StateC.Current_action_state.Name.c_str(), player_one->Combat.Current_health_percentage); ImGui::Text("Player: %i\n pos state: %s\n action state: %s\n Health: %f", player_two->ID, player_two->StateC.Current_position_state.Name.c_str(), player_two->StateC.Current_action_state.Name.c_str(), player_two->Combat.Current_health_percentage);*/ // new state debug texts ImGui::End(); end_GUI(); } World* get_world() { return &world; } float get_time_scale() { return world.current_time_scale; } void set_time_scale(float value) { world.current_time_scale = value; } void reset_time_scale() { world.current_time_scale = 1.0f; } void debug_functionality() { if (is_key_pressed(KeyCode::R) || is_button_down(0, GLFW_GAMEPAD_BUTTON_B)) { player_one->Combat.Current_health_percentage = 0.0f; player_two->Combat.Current_health_percentage = 0.0f; player_one->Transform.Position = glm::vec2(0.0f, 0.0f); player_two->Transform.Position = glm::vec2(0.0f, 0.0f); player_one->ActionState.Position_state = PositionState::Airborne; player_one->ActionState.Action_state = ActionState::Falling; player_two->ActionState.Position_state = PositionState::Airborne; player_two->ActionState.Action_state = ActionState::Falling; player_one->Physics.Velocity = glm::vec2(0.0f, 0.0f); player_two->Physics.Velocity = glm::vec2(0.0f, 0.0f); printf("Health reset!\n"); } if (is_button_down(0, GLFW_GAMEPAD_BUTTON_Y)) { if (get_time_scale() < 0.4f) { reset_time_scale(); } else { set_time_scale(0.3f); } } if (is_button_down(0, GLFW_GAMEPAD_BUTTON_BACK)) { is_ai_active = !is_ai_active; } }
#include <iostream> #include <string> #include <algorithm> using namespace std; int stringToInt(string s) { bool is_negative = false; int acum = 0; if (s[0] == '-') { is_negative = true; } for (int i = is_negative? 1 : 0; i < s.length(); i++) { acum = acum * 10 + s[i] - '0'; } return is_negative ? acum * -1 : acum; } string intToString(int num) { bool is_negative = false; string res = ""; if (num < 0) { is_negative = true; num *= -1; } while (num > 0) { res += '0' + num % 10; num /= 10; } if (is_negative) { res += '-'; } reverse(res.begin(), res.end()); return res; } int main() { string s = intToString(-123); cout << s; }
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <vector> #include <algorithm> #define pb push_back using namespace std; int nhang,ncot; int s[111][111]; bool d[111][111]; struct toado{ int h,c; }; toado huong[5] = {-1,0 ,0,1 ,1,0 ,0,-1}; vector<int> vect; void input(){ scanf("%d %d",&nhang,&ncot); memset(d,0,sizeof(d)); memset(s,0,sizeof(s)); for (int i=0;i<nhang;i++) for (int j=0;j<ncot;j++) scanf("%d",&s[i][j]); } bool inside(int hang,int cot){ if ( hang < 0 || hang >= nhang ) return 0; if ( cot < 0 || cot >= ncot ) return 0; return 1; } int dfs(int hang,int cot){ int ht,ct; int sz = 1; d[hang][cot] = 1; for (int i=0;i<4;i++){ ht = hang + huong[i].h; ct = cot + huong[i].c; if (inside(ht,ct) && s[ht][ct] == 0 && d[ht][ct] == 0){ sz = sz + dfs(ht,ct); } } return sz; } void solve(){ vect.clear(); for (int i=0;i<nhang;i++){ for (int j=0;j<ncot;j++){ if ( s[i][j] == 0 && d[i][j] == 0){ int sz = dfs(i,j); vect.pb(sz); } } } sort(vect.begin(),vect.end()); printf("%d",vect.size()); for (int i=0;i<vect.size();i++) printf(" %d",vect[i]); printf("\n"); } int main() { freopen("input.txt","r",stdin); int ntest; scanf("%d",&ntest); for (int itest=0;itest<ntest;itest++){ input(); solve(); } return 0; }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; // Author: Tatparya Shankar int main() { // Get matrix elements; int n; int element; int sum1 = 0; int sum2 = 0; cin >> n; for( int i = 0; i < n; i++ ) { for( int j = 0; j < n; j++ ) { cin >> element; if( i == j ) { sum1 += element; } if( i + j == n - 1 ) { sum2 += element; } } } // cout << sum1 << endl << sum2 << endl; // Get abs sum cout << abs( sum1 - sum2 ) << endl; }
/*************************************************************************** * Sketch Name: Internet Connectivity (Arduino Yun) * Description: This sketch illustrates how to connect Arduino Yun to internet using WiFi * Created On: October 10, 2015 * Author: Adeel Javed * Book: Building Arduino Projects for the Internet of Things * Chapter: Chapter 02 - Internet Connectivity * Website: http://codifythings.com **************************************************************************/ /*************************************************************************** * External Libraries **************************************************************************/ #include <Bridge.h> #include <Process.h> /*************************************************************************** * Internet Connectivity Setup - Variables & Functions **************************************************************************/ void printConnectionInformation() { // Initialize a new process Process wifiCheck; // Run Command wifiCheck.runShellCommand("/usr/bin/pretty-wifi-info.lua"); // Print Connection Information while (wifiCheck.available() > 0) { char c = wifiCheck.read(); Serial.print(c); } Serial.println("-----------------------------------------------"); Serial.println(""); } /*************************************************************************** * Standard Arduino Functions - setup(), loop() **************************************************************************/ void setup() { // Initialize serial port Serial.begin(9600); // Do nothing until serial monitor is opened while (!Serial); // Contact the Linux processor Bridge.begin(); // Connect Arduino to Internet printConnectionInformation(); } void loop() { // Do nothing }
#include <iostream> #include <string> using namespace std; class Solution { public: int minDistance(string word1, string word2) { int DP[1000][1000] = {}; int N = word1.size(), M = word2.size(); for(int i=1;i<=N;i++) DP[i][0] = i; for(int j=1;j<=M;j++) DP[0][j] = j; for (int i=1;i<=N;i++) for(int j=1;j<=M;j++) if(word1[i-1] == word2[j-1]) DP[i][j] = DP[i-1][j-1]; else DP[i][j] = 1 + min(DP[i-1][j], min(DP[i][j-1], DP[i-1][j-1])); return DP[N][M]; } }; int main(){ string s1, s2; cin >> s1 >> s2; Solution s; cout << s.minDistance(s1, s2) << endl; }
#include "../include/drift_diffusion.h" void Drift_diffusion::dipslacement_current_density(void) { int N = grid_scaled.N_points_scaled; // Number of points with boundaries double dt_scaled = layers_params_scaled.device.dt_scaled; vector<double> tmp_J_displ_scaled; tmp_J_displ_scaled.resize(N); vector<double> E_it1_scaled = result_it1_scaled.E_scaled; vector<double> E_it_scaled = result_it_scaled.E_scaled; vector<double> Er_i_scaled = grid_scaled.E_r_scaled; // Solve the scaled function // J_displ[i,t+1] = (E_scaled[i,t+1] - E_scaled[i,t]) / dt_scaled for (int i = 0; i < N; i++) tmp_J_displ_scaled[i] = Er_i_scaled[i]*(E_it1_scaled[i] - E_it_scaled[i]) / dt_scaled; // Put result to result vector in t+1 position result_it1_scaled.J_disp_scaled = tmp_J_displ_scaled; }
#include<cstdio> const int MAX=100010; int a[MAX]; void sort(int l,int r) {int i,j,mid,t; i=l;j=r; mid=a[(i+j)/2]; while(i<j) {while(a[i]<mid) i++; while(a[j]>mid) j--; if (i<=j) {t=a[i]; a[i]=a[j]; a[j]=t; i++;j--; } } if (i<r) sort(i,r); if (j>l) sort(l,j); } int main() {int n; freopen("qsort.in","r",stdin); freopen("qsort.out","w",stdout); scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); sort(0,n-1); for(int i=0;i<n;i++) printf("%d ",a[i]); return 0; }
//=========================================================================== /* This file is part of the CHAI 3D visualization and haptics libraries. Copyright (C) 2003-2004 by CHAI 3D. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License("GPL") version 2 as published by the Free Software Foundation. For using the CHAI 3D libraries with software that can not be combined with the GNU GPL, and for taking advantage of the additional benefits of our support services, please contact CHAI 3D about acquiring a Professional Edition License. \author: <http://www.chai3d.org> \author: Francois Conti \author: Dan Morris \author: Chris Sewell \version 1.1 \date 01/2004 */ //=========================================================================== //=========================================================================== #include "CDepthImage.h" #include "CVertex.h" #include "CTriangle.h" #include "CCollisionBrute.h" #include <algorithm> //--------------------------------------------------------------------------- //=========================================================================== /*! Constructor of cMesh \fn cMesh::cMesh(cWorld* a_parent) \param a_parent Pointer to parent world. */ //=========================================================================== cDepthImage::cDepthImage(cWorld *a_parent) { // initialize parent object of mesh. Not yet a child on an other object. m_parent = NULL; // set parent world of mesh m_parentWorld = a_parent; // should we use the material property? m_useImageMaterial = true; // not updated yet m_bFirstUpdate = false; // proxy graph does not finish its loop m_bUpdate = false; // Now proxy graph algorithm is not working m_bProxyGraph = false; // Initialized the Elapsed graphic & haptic time m_lElapsedGraphicTime = 31000; m_lElapsedHapticTime = 0; m_timeRatio = 0.0; // initialize previous surface depth m_previousSurfacePoint.set(0.0, 0.0, 255.0); // smoothing m_useSmoothing = true; m_smoothingArea = 1; // rgb image and depth image initialization m_colorData = NULL; m_nextColorData = NULL; m_tempColorData = NULL; m_colorTotalChannel = 0; m_colorChannelNum = 0; m_colorImageSizeX = 0; m_colorImageSizeY = 0; m_depthData = NULL; m_nextDepthData = NULL; m_tempDepthData = NULL; m_depthTotalChannel = 0; m_depthChannelNum = 0; m_depthImageSizeX = 0; m_depthImageSizeY = 0; m_tag = DEPTH_IMAGE_TAG; m_dynamicMesh = new cMesh(a_parent); m_dynamicMesh->m_tag = DEPTH_IMAGE_TAG; // Dynamic mesh represents one grid of voxel composed on four verties. // This mesh is updated with each grid of candidate voxel for collision detection. // In order to save information of collided triangle, additional triangle is set. cVector3d point(CHAI_LARGE, CHAI_LARGE, CHAI_LARGE); for(int i=0; i<7; i++) m_dynamicMesh->newVertex(point); // one voxel --> two triangle m_dynamicMesh->newTriangle(0, 1, 2); m_dynamicMesh->newTriangle(0, 2, 3); // additional triangle m_dynamicMesh->newTriangle(4, 5, 6); this->addChild(m_dynamicMesh); m_collisionCandidateVoxelNum = 0; m_collisionVoxelNum = 0; m_useImageMaterial = true; m_useImageBump = true; m_bColorData = false; m_bDepthData = false; updateBoundaryBox(); ////////////////////////////////////////////////// // for first test m_bFirstUpdateForProxyGraph = false; // test m_scaleFactor = 2.0; // test m_focalLength = 0.47; m_pixelWidth = 0.00112; m_primaryDistance = 50.0; m_primaryWidth = 250.0; m_renderSample = 4; } cDepthImage::~cDepthImage() { // not yet : clear the memory if(m_colorData) delete m_colorData; if(m_nextColorData) delete m_nextColorData; if(m_tempColorData) delete m_tempColorData; if(m_depthData) delete m_depthData; if(m_nextDepthData) delete m_nextDepthData; if(m_tempDepthData) delete m_tempDepthData; } void cDepthImage::clear() { // not yet } void cDepthImage::scaleObject(double a_scaleFactor) { // not yet } //=========================================================================== /*! Compute the axis-aligned boundary box that encloses all triangles in this mesh \fn void cMesh::updateBoundaryBox() */ //=========================================================================== void cDepthImage::updateBoundaryBox() { // not yet : scaling // local boundary box include the depth image cVector3d localBoundaryBoxMin; cVector3d localBoundaryBoxMax; localBoundaryBoxMin.set(1.0, 1.0, 0.0); localBoundaryBoxMax.set((double)m_depthImageSizeX, (double)m_depthImageSizeY-1.0, (double)(300)); // local to global boundary box m_boundaryBoxMin = localBoundaryBoxMin; m_boundaryBoxMax = localBoundaryBoxMax; } //=========================================================================== /*! Resize the current depth image by scaling all my vertex positions \fn void setScale(double a_scaleFactor) \param a_scaleFactor Scale factor. */ //=========================================================================== void cDepthImage::setScale(const double a_scaleFactor) { m_scaleFactor = a_scaleFactor; } //=========================================================================== /*! Resize the current depth image by scaling all my vertex positions \fn void getScale(double a_scaleFactor) \param a_scaleFactor Scale factor. */ //=========================================================================== double cDepthImage::getScale() { return m_scaleFactor; } //=========================================================================== /*! Test whether a ray intersects this object. The test segment is described by a start point /e a_segmentPointA and end point /e a_segmentPointB. If a collision occurs, the squared distance between the segment start point and the collision point in measured and compared to any previous collision information stored in parameters \e a_colObject, \e a_colTriangle, \e a_colPoint, and \e a_colSquareDistance. If the new collision is located nearer to the ray origin than the previous collision point, it is stored in the corresponding parameters \e a_colObject, \e a_colTriangle, \e a_colPoint, and \e a_colSquareDistance. \param a_segmentPointA Start point of segment. \param a_segmentPointB End point of segment. \param a_colObject Pointer to nearest collided object. \param a_colTriangle Pointer to nearest colided triangle. \param a_colPoint Position to the nearest collision \param a_colSquareDistance Squared distance between ray origin and nearest collision point \param a_proxyCall If this is > 0, this is a call from a proxy, and the value of a_proxyCall specifies which call this is. -1 is passed for non-proxy calls. */ //=========================================================================== bool cDepthImage::computeCollisionDetection(cVector3d& a_segmentPointA, const cVector3d& a_segmentPointB, cGenericObject*& a_colObject, cTriangle*& a_colTriangle, cVector3d& a_colPoint, double& a_colSquareDistance, const bool a_visibleObjectsOnly, const int a_proxyCall) { if( (m_depthData == NULL) || (m_nextDepthData == NULL)) return false; // not yet : bounding box // no collision found yet bool hit = false; // convert collision segment into local coordinate system. cMatrix3d transLocalRot; m_localRot.transr(transLocalRot); cVector3d localSegmentPointA = a_segmentPointA; localSegmentPointA.sub(m_localPos); transLocalRot.mul(localSegmentPointA); cVector3d localSegmentPointB = a_segmentPointB; localSegmentPointB.sub(m_localPos); transLocalRot.mul(localSegmentPointB); // cartesian to image coordinate //localSegmentPointA.add(m_depthImageSizeX/2.0, m_depthImageSizeY/2.0, 0.0); //localSegmentPointB.add(m_depthImageSizeX/2.0, m_depthImageSizeY/2.0, 0.0); localSegmentPointA = trans2image(localSegmentPointA); localSegmentPointB = trans2image(localSegmentPointB); // initialize objects for calls cGenericObject* t_colObject; cTriangle *t_colTriangle; cVector3d t_colPoint; double t_colSquareDistance = a_colSquareDistance; // conversion of the colPoint and colSquareDistance in this local coordinate cVector3d t_localColPoint = a_colPoint; t_localColPoint.sub(m_localPos); transLocalRot.mul(t_localColPoint); double a_localColSquareDistance = localSegmentPointA.distance(t_localColPoint); double t_localColSquareDistance = a_localColSquareDistance; // proxy position correction cVector3d correctionProxy; // for proxy collision detection if( cBoxContains(localSegmentPointA, m_boundaryBoxMin, m_boundaryBoxMax) ) { // When the goal is outside the depth image, // no collision occurs. if(localSegmentPointB.x < 1.0 || localSegmentPointB.y < 1.0 || localSegmentPointB.x > m_depthImageSizeX-1.0 || localSegmentPointB.y > m_depthImageSizeY-1.0) return false; // // proxy position correction for deforming surface // (dynamic moving object that is deforming) correctionProxy = correctProxy(localSegmentPointA); lineDDA(correctionProxy.x, correctionProxy.y, correctionProxy.z, localSegmentPointB.x, localSegmentPointB.y, localSegmentPointB.z); if(m_collisionVoxelNum != 0) { int x, y; int notContainedNum = 0; int index = 0; bool hit1 = false, hit2 = false; // convert two point segment into a segment described by a point and // a directional vector cVector3d dir; localSegmentPointB.subr(correctionProxy, dir); vector<cVertex>* dynamic_vertex = (vector<cVertex>*)m_dynamicMesh->pVertices(); // for test cVertex v1 = dynamic_vertex->at(0); cVertex v2 = dynamic_vertex->at(1); cVertex v3 = dynamic_vertex->at(2); cVertex v4 = dynamic_vertex->at(3); for(int i=0; i<m_collisionVoxelNum; i++) { x = m_collisionVoxel[i][0]; y = m_collisionVoxel[i][1]; if(x < (m_depthImageSizeX-1) && x >=1 && y < (m_depthImageSizeY-2) && y >= 1) { index = i-notContainedNum; dynamic_vertex->at(0).setPos((double)x, (double)y, getDepth(x, y)); dynamic_vertex->at(1).setPos((double)x+1.0, (double)y, getDepth(x+1, y)); dynamic_vertex->at(2).setPos((double)x+1.0, (double)y+1.0, getDepth(x+1, y+1)); dynamic_vertex->at(3).setPos((double)x, (double)y+1.0, getDepth(x, y+1)); // As you can see just above, the vertex values are updated in each voxel. // That changes the triangle position. // Therefore, the collided triangle position can be updated with the vertex change. // To prevent this, when collision occurs, we save the collided triangle information into // additional triangle. if( hit1 = m_dynamicMesh->getTriangle(0)->computeCollision(correctionProxy, dir, t_colObject, t_colTriangle, t_localColPoint, t_localColSquareDistance) ) { dynamic_vertex->at(4).setPos(dynamic_vertex->at(0).getPos()); dynamic_vertex->at(5).setPos(dynamic_vertex->at(1).getPos()); dynamic_vertex->at(6).setPos(dynamic_vertex->at(2).getPos()); hit = true; } if( hit2 = m_dynamicMesh->getTriangle(1)->computeCollision(correctionProxy, dir, t_colObject, t_colTriangle, t_localColPoint, t_localColSquareDistance) ) { dynamic_vertex->at(4).setPos(dynamic_vertex->at(0).getPos()); dynamic_vertex->at(5).setPos(dynamic_vertex->at(2).getPos()); dynamic_vertex->at(6).setPos(dynamic_vertex->at(3).getPos()); hit = true; } } else notContainedNum++; } if(hit) { if (t_localColSquareDistance < a_localColSquareDistance) { a_colObject = t_colObject; // The collided triangle information need to be reported to caller. vector<cTriangle>* colTriangle = (vector<cTriangle>*)m_dynamicMesh->pTriangles(); a_colTriangle = &colTriangle->at(2); // covert based on parent coordinate cVector3d globalColPoint = t_localColPoint; globalColPoint = trans2cartesian(globalColPoint); m_localRot.mul(globalColPoint); globalColPoint.add(m_localPos); t_colPoint = globalColPoint; a_colPoint = t_colPoint; /* t_colPoint = t_localColPoint; a_colPoint = t_colPoint; */ t_colSquareDistance = a_segmentPointA.distance(globalColPoint); a_colSquareDistance = t_colSquareDistance; } } } } // search for collision with all child objects // Since the first child, dymamicMesh, is used for collision detection of this depth image, // it is skipped for children collision detection for (unsigned int i=2; i<m_children.size(); i++) { if( m_children[i]->computeCollisionDetection(localSegmentPointA, localSegmentPointB, t_colObject, t_colTriangle, t_colPoint, t_colSquareDistance, a_visibleObjectsOnly, a_proxyCall)) { // object was hit hit = true; if (t_colSquareDistance < a_colSquareDistance) { a_colObject = t_colObject; a_colTriangle = t_colTriangle; a_colPoint = t_colPoint; a_colSquareDistance = t_colSquareDistance; // convert collision point into parent coordinate m_localRot.mul(a_colPoint); a_colPoint.add(m_localPos); } } } // return result return (hit); } cVector3d cDepthImage::updatePrevisouSurfaceDepthGlobal(cVector3d& a_proxy) { cMatrix3d transLocalRot; m_globalRot.transr(transLocalRot); cVector3d localProxy = a_proxy; localProxy.sub(m_globalPos); transLocalRot.mul(localProxy); localProxy = trans2image(localProxy); if( !cBoxContains(localProxy, m_boundaryBoxMin, m_boundaryBoxMax) ) { cVector3d zero; zero.zero(); return zero; } // to get the previous surface point projected from the previous proxy m_previousSurfacePoint = projectOnDepthImage(localProxy); return m_previousSurfacePoint; } cVector3d cDepthImage::updatePrevisouSurfaceDepthLocal(cVector3d& a_proxy) { if( !cBoxContains(a_proxy, m_boundaryBoxMin, m_boundaryBoxMax) ) { cVector3d zero; zero.zero(); return zero; } // to get the previous surface point projected from the previous proxy m_previousSurfacePoint = projectOnDepthImage(a_proxy); return m_previousSurfacePoint; } void cDepthImage::getSize(int &sizeX, int &sizeY) const { sizeX = m_depthImageSizeX; sizeY = m_depthImageSizeY; } void cDepthImage::lineDDA(double x1, double y1, double z1, double x2, double y2, double z2) { m_collisionCandidateVoxelNum = 0; int i; double dx = x2 - x1; double dy = y2 - y1; int sgnX = SGN(dx); int sgnY = SGN(dy); if(dx == 0.0 && dy == 0.0) { m_collisionCandidateVoxelNum = 1; m_collisionCandidateVoxel[0][0] = FLOOR(x1); m_collisionCandidateVoxel[0][1] = FLOOR(y1); } else if(dx == 0.0) { addCandidateVoxel(FLOOR(x1), FLOOR(y1), FLOOR(y2), sgnY, m_collisionCandidateVoxelNum); } else { double m = dy/dx; int stepX = SGN(dx); double stepY = m*(double)stepX; if(CEIL(x2) - FLOOR(x1) == 1) { addCandidateVoxel(FLOOR(x1), FLOOR(y1), FLOOR(y2), sgnY, m_collisionCandidateVoxelNum); } else { double y; int startX, endX; if(x2 - x1 >= 0.0) { y = y1 + m*((double)(CEIL(x1)) - x1); // (CEIL(x1)) 꼭 괄호 안에 넣기 startX = CEIL(x1); endX = FLOOR(x2); } else { y = y1 + m*((double)(FLOOR(x1)) - x1); // (FLOOR(x1)) 꼭 괄호 안에 넣기 startX = FLOOR(x1)-1; endX = CEIL(x2)-1; } addCandidateVoxel(FLOOR(x1), FLOOR(y1), FLOOR(y), sgnY, m_collisionCandidateVoxelNum); for(i = startX; i != endX; i+=stepX) { addCandidateVoxel(i, FLOOR(y), FLOOR(y+stepY), sgnY, m_collisionCandidateVoxelNum); y+=stepY; } addCandidateVoxel(i, FLOOR(y), FLOOR(y2), sgnY, m_collisionCandidateVoxelNum); } } double gridVertexDepth[4], maxDepth = 0.0, minDepth = 255.0; double delta, zEnter, zLeave; double offsetX = 0.0, offsetY = 0.0; if(sgnX < 0) offsetX = 1.0; if(sgnY < 0) offsetY = 1.0; m_collisionVoxelNum = 0; if(m_collisionCandidateVoxelNum == 1){ int x, y; x = m_collisionCandidateVoxel[0][0]; y = m_collisionCandidateVoxel[0][1]; gridVertexDepth[0] = getDepth(x, y); gridVertexDepth[1] = getDepth(x+1, y); gridVertexDepth[2] = getDepth(x+1, y+1); gridVertexDepth[3] = getDepth(x, y+1); maxDepth = MAX(maxDepth, gridVertexDepth[0]); maxDepth = MAX(maxDepth, gridVertexDepth[1]); maxDepth = MAX(maxDepth, gridVertexDepth[2]); maxDepth = MAX(maxDepth, gridVertexDepth[3]); minDepth = MIN(minDepth, gridVertexDepth[0]); minDepth = MIN(minDepth, gridVertexDepth[1]); minDepth = MIN(minDepth, gridVertexDepth[2]); minDepth = MIN(minDepth, gridVertexDepth[3]); if(z1 >= minDepth && z2 <= maxDepth) { m_collisionVoxel[0][0] = m_collisionCandidateVoxel[0][0]; m_collisionVoxel[0][1] = m_collisionCandidateVoxel[0][1]; m_collisionVoxelNum = 1; } } else { for(int j = 0; j < m_collisionCandidateVoxelNum; j++) { int x, y; maxDepth = 0.0, minDepth = 255.0; x = m_collisionCandidateVoxel[j][0]; y = m_collisionCandidateVoxel[j][1]; gridVertexDepth[0] = getDepth(x, y); gridVertexDepth[1] = getDepth(x+1, y); gridVertexDepth[2] = getDepth(x+1, y+1); gridVertexDepth[3] = getDepth(x, y+1); maxDepth = MAX(maxDepth, gridVertexDepth[0]); maxDepth = MAX(maxDepth, gridVertexDepth[1]); maxDepth = MAX(maxDepth, gridVertexDepth[2]); maxDepth = MAX(maxDepth, gridVertexDepth[3]); minDepth = MIN(minDepth, gridVertexDepth[0]); minDepth = MIN(minDepth, gridVertexDepth[1]); minDepth = MIN(minDepth, gridVertexDepth[2]); minDepth = MIN(minDepth, gridVertexDepth[3]); if(j == 0) { zEnter = z1; if(m_bConnectivity[1]) { delta = fabs((double)m_collisionCandidateVoxel[1][0]+offsetX-x1); zLeave = z1 + delta*(z2-z1)/fabs(x2-x1); } else { delta = fabs((double)m_collisionCandidateVoxel[1][1]+offsetY-y1); zLeave = z1 + delta*(z2-z1)/fabs(y2-y1); } if(m_collisionCandidateVoxelNum == 1) break; } else if(j == (m_collisionCandidateVoxelNum-1)) { zEnter = zLeave; zLeave = z2; } else { zEnter = zLeave; if(m_bConnectivity[j+1]) { delta = fabs((double)m_collisionCandidateVoxel[j+1][0]+offsetX-x1); zLeave = z1 + delta*(z2-z1)/fabs(x2-x1); } else { delta = fabs((double)m_collisionCandidateVoxel[j+1][1]+offsetY-y1); zLeave = z1 + delta*(z2-z1)/fabs(y2-y1); } } // because of the numerical error // The small value difference is allowed if((zEnter+0.0000001) >= minDepth && (zLeave-0.0000001) <= maxDepth) { //if(zEnter >= minDepth && zLeave <= maxDepth) { m_collisionVoxel[m_collisionVoxelNum][0] = m_collisionCandidateVoxel[j][0]; m_collisionVoxel[m_collisionVoxelNum][1] = m_collisionCandidateVoxel[j][1]; m_collisionVoxelNum++; } } } } void cDepthImage::addCandidateVoxel(int x, int y1, int y2, int sgnY, int &num) { int i; m_bConnectivity[num] = true; if(sgnY == 0) { m_collisionCandidateVoxel[num][0] = x; m_collisionCandidateVoxel[num][1] = y1; num++; } else { for(i=y1;i!=y2+sgnY;i+=sgnY) { m_collisionCandidateVoxel[num][0] = x; m_collisionCandidateVoxel[num][1] = i; num++; m_bConnectivity[num] = false; } } } //=========================================================================== /*! Set the current material for this mesh, possibly recursively affecting children \fn void cMesh::setMaterial(cMaterial& a_mat, const bool a_affectChildren) \param a_mat The material to apply to this object \param a_affectChildren If \b true, then children are also modified. Note that this does not affect whether material rendering is enabled; it sets the maetrial that will be rendered _if_ material rendering is enabled. Call useMaterial to enable / disable material rendering. */ //=========================================================================== void cDepthImage::setImageMaterial(cImageMaterial& a_mat, const bool a_affectChildren) { cMaterial mat; m_imageMaterial = a_mat; mat.setStiffness(a_mat.getStiffness()); mat.setStaticFriction(a_mat.getStaticFriction()); mat.setDynamicFriction(a_mat.getDynamicFriction()); // to embedded neighborMesh and dynamicMesh m_dynamicMesh->setMaterial(mat, a_affectChildren); // propagate changes to children if (a_affectChildren) { for (unsigned int i=3; i<m_children.size(); i++) { cGenericObject *nextObject = m_children[i]; cDepthImage *nextDepthImage = dynamic_cast<cDepthImage*>(nextObject); if (nextDepthImage) { nextDepthImage->setImageMaterial(a_mat, a_affectChildren); } } } } //=========================================================================== /*! Enable or disable the use of material properties. \fn void cMesh::useMaterial(const bool a_useMaterial, const bool a_affectChildren) \param a_useMaterial If \b true, then material properties are used for rendering. \param a_affectChildren If \b true, then children are also modified. */ //=========================================================================== void cDepthImage::useImageMaterial(const bool a_useImageMaterial, const bool a_affectChildren) { // update changes to object m_useImageMaterial = a_useImageMaterial; // update changes to embedded meshes m_dynamicMesh->useMaterial(a_useImageMaterial, a_affectChildren); // propagate changes to my children if (a_affectChildren) { for (unsigned int i=3; i<m_children.size(); i++) { cGenericObject *nextObject = m_children[i]; cDepthImage *nextDepthImage = dynamic_cast<cDepthImage*>(nextObject); if (nextDepthImage) { nextDepthImage->useImageMaterial(a_useImageMaterial, a_affectChildren); } } } } //=========================================================================== /*! Set the static and dynamic friction for this mesh, possibly recursively affecting children \fn void cMesh::setFriction(double a_staticFriction, double a_dynamicFriction, const bool a_affectChildren=0) \param a_staticFriction The static friction to apply to this object \param a_dynamicFriction The dynamic friction to apply to this object \param a_affectChildren If \b true, then children are also modified. */ //=========================================================================== void cDepthImage::setFriction(double a_staticFriction, double a_dynamicFriction, const bool a_affectChildren) { m_imageMaterial.setStaticFriction(a_staticFriction); m_imageMaterial.setDynamicFriction(a_dynamicFriction); // to embedded meshes m_dynamicMesh->setFriction(a_staticFriction, a_dynamicFriction, a_affectChildren); // propagate changes to children if (a_affectChildren) { for (unsigned int i=3; i<m_children.size(); i++) { cGenericObject *nextObject = m_children[i]; cDepthImage *nextDepthImage = dynamic_cast<cDepthImage*>(nextObject); if (nextDepthImage) { nextDepthImage->setFriction(a_staticFriction,a_dynamicFriction,a_affectChildren); } } } } //=========================================================================== /*! Set the haptic stiffness for this mesh, possibly recursively affecting children \fn void cMesh::setStiffness(double a_stiffness, const bool a_affectChildren=0); \param a_stiffness The stiffness to apply to this object \param a_affectChildren If \b true, then children are also modified. */ //=========================================================================== void cDepthImage::setStiffness(double a_stiffness, const bool a_affectChildren) { m_imageMaterial.setStiffness(a_stiffness); // to embedded meshes m_dynamicMesh->setStiffness(a_stiffness, a_affectChildren); // propagate changes to children if (a_affectChildren) { for (unsigned int i=0; i<m_children.size(); i++) { cGenericObject *nextObject = m_children[i]; // 2007.1.16 // by gaecha // For crash from dynamic_cast //cMesh *nextMesh = dynamic_cast<cMesh*>(nextObject); cDepthImage *nextDepthImage = (cDepthImage*)(nextObject); if (nextDepthImage) { nextDepthImage->setStiffness(a_stiffness, a_affectChildren); } } } } cVector3d cDepthImage::projectOnDepthImage(cVector3d a_point) { int i, j; cVector3d vertex[4]; double X, Y, Z[4]; i = (int)a_point.x; j = (int)a_point.y; cVector3d result; vertex[0].set((double)i, (double)j, getDepth(i, j)); vertex[1].set((double)i+1.0, (double)j, getDepth(i+1, j)); vertex[2].set((double)i+1.0, (double)j+1.0, getDepth(i+1, j+1)); vertex[3].set((double)i, (double)j+1.0, getDepth(i, j+1)); X = a_point.x - (double)i; Y = a_point.y - (double)j; Z[0] = vertex[0].z; Z[1] = vertex[1].z - Z[0]; Z[2] = vertex[2].z - Z[0]; Z[3] = vertex[3].z - Z[0]; if(Y>=X) result.set(a_point.x, a_point.y, Z[0] + X*Z[2] + (Y-X)*Z[3]); else result.set(a_point.x, a_point.y, Z[0] + (X-Y)*Z[1] + Y*Z[2]); // !!!!!!!!!!!!!!!!!!!!! // After computing the proper proxy, in the next haptic loop, // the collision detection can be failed because of the numerical error // In CHAI3D, they elevate the proxy by radius of the proxy in the direction of normal // of contacted mesh. // But, in that case, the static friction cannot be accomplised. // Anyway, here, the proxy is moved very small amount for escaping the problem from numerical error. result.z += 0.1E-5; // return result; } cVector3d cDepthImage::projectOnDepthImageGlobal(cVector3d a_point) { cMatrix3d transLocalRot; m_globalRot.transr(transLocalRot); cVector3d localPoint = a_point; localPoint.sub(m_globalPos); transLocalRot.mul(localPoint); localPoint = trans2image(localPoint); int i, j; cVector3d vertex[4]; double X, Y, Z[4]; i = (int)localPoint.x; j = (int)localPoint.y; cVector3d result; vertex[0].set((double)i, (double)j, getDepth(i, j)); vertex[1].set((double)i+1.0, (double)j, getDepth(i+1, j)); vertex[2].set((double)i+1.0, (double)j+1.0, getDepth(i+1, j+1)); vertex[3].set((double)i, (double)j+1.0, getDepth(i, j+1)); X = localPoint.x - (double)i; Y = localPoint.y - (double)j; Z[0] = vertex[0].z; Z[1] = vertex[1].z - Z[0]; Z[2] = vertex[2].z - Z[0]; Z[3] = vertex[3].z - Z[0]; if(Y>=X) result.set(localPoint.x, localPoint.y, Z[0] + X*Z[2] + (Y-X)*Z[3]); else result.set(localPoint.x, localPoint.y, Z[0] + (X-Y)*Z[1] + Y*Z[2]); // !!!!!!!!!!!!!!!!!!!!! // After computing the proper proxy, in the next haptic loop, // the collision detection can be failed because of the numerical error // In CHAI3D, they elevate the proxy by radius of the proxy in the direction of normal // of contacted mesh. // But, in that case, the static friction cannot be accomplised. // Anyway, here, the proxy is moved very small amount for escaping the problem from numerical error. result.z += 0.1E-7; // result = trans2cartesian(result); cVector3d globalPoint = result; m_globalRot.mul(globalPoint); globalPoint.add(m_globalPos); return globalPoint; } void cDepthImage::setColorImageProperties(unsigned int a_sizeX, unsigned int a_sizeY, unsigned char a_totalChannel, unsigned char a_channelNum) { if( (m_colorImageSizeX != a_sizeX) || (m_colorImageSizeY != a_sizeY)) { m_colorTotalChannel = a_totalChannel; m_colorChannelNum = a_channelNum; m_colorImageSizeX = a_sizeX; m_colorImageSizeY = a_sizeY; m_halfColorImageSizeX = m_depthImageSizeX/2; m_halfColorImageSizeY = m_depthImageSizeY/2; if(m_colorData) free(m_colorData); if(m_nextColorData) free(m_nextColorData); if(m_tempColorData) free(m_tempColorData); m_colorData = new unsigned char[m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(char)]; memset(m_colorData, 0, m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(char)); m_nextColorData = new unsigned char[m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(char)]; memset(m_nextColorData, 0, m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(char)); m_tempColorData = new unsigned char[m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(char)]; memset(m_tempColorData, 0, m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(char)); m_bColorData = true; } } void cDepthImage::setDepthImageProperties(unsigned int a_sizeX, unsigned int a_sizeY, unsigned char a_totalChannel, unsigned char a_channelNum) { if( (m_depthImageSizeX != a_sizeX) || (m_depthImageSizeY != a_sizeY) || (m_depthTotalChannel != a_totalChannel) ) { m_depthTotalChannel = a_totalChannel; m_depthChannelNum = a_channelNum; m_depthImageSizeX = a_sizeX; m_depthImageSizeY = a_sizeY; m_halfDepthImageSizeX = m_depthImageSizeX/2; m_halfDepthImageSizeY = m_depthImageSizeY/2; if(m_depthData) free(m_depthData); if(m_nextDepthData) free(m_nextDepthData); if(m_tempDepthData) free(m_tempDepthData); m_depthData = new unsigned char[m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(char)]; memset(m_depthData, m_boundaryBoxMax.z, m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(char)); m_nextDepthData = new unsigned char[m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(char)]; memset(m_nextDepthData, m_boundaryBoxMax.z, m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(char)); m_tempDepthData = new unsigned char[m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(char)]; memset(m_tempDepthData, m_boundaryBoxMax.z, m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(char)); m_bDepthData = true; updateBoundaryBox(); } } void cDepthImage::setElapsedGraphicTime(float a_time) { m_lElapsedGraphicTime = (long)a_time; } void cDepthImage::setImageData(cImageLoader *a_colorImage, cImageLoader *a_depthImage) { unsigned char *colorData, *depthData; if(!a_depthImage) return; else depthData = (unsigned char *)a_depthImage->getData(); if(!a_colorImage) colorData = NULL; else colorData = (unsigned char *)a_colorImage->getData(); setImageData(colorData, depthData); return; } void cDepthImage::setImageData(cImageLoader *a_image) { unsigned char *imageData; if(!a_image) return; else imageData = (unsigned char *)a_image->getData(); setImageData(imageData); return; } void cDepthImage::setImageData(unsigned char * a_imageData) { // update the temporal image if(a_imageData) { setColorData(a_imageData); setDepthData(a_imageData); } } void cDepthImage::setImageData(unsigned char * a_colorData, unsigned char * a_depthData) { // update the temporal image if(a_colorData) setColorData(a_colorData); if(a_depthData) setDepthData(a_depthData); } void cDepthImage::setColorData(unsigned char * a_colorData) { // update the temporal image if(a_colorData) memcpy(m_tempColorData, a_colorData, m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(char)); } void cDepthImage::setDepthData(unsigned char * a_depthData) { if(a_depthData == NULL) { m_bFirstUpdate = false; return; } // update the temporal image memcpy(m_tempDepthData, a_depthData, m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(char)); m_bUpdate = true; if(!m_bProxyGraph) { updateImage(); } } bool cDepthImage::updateImage() { // by gaecha // if the proxy graph algorithm finish its loop // and the image is updated temporarily, // update the images. if(m_bUpdate) { if(m_useImageMaterial && (m_imageMaterial.m_bIsHapticData || m_imageMaterial.m_bIsBumpData) ) m_imageMaterial.updateImage(); if(m_bColorData) { memcpy(m_colorData, m_nextColorData, m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(unsigned char)); memcpy(m_nextColorData, m_tempColorData, m_colorTotalChannel*m_colorImageSizeX*m_colorImageSizeY*sizeof(unsigned char)); } if(m_bDepthData) { memcpy(m_depthData, m_nextDepthData, m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(unsigned char)); memcpy(m_nextDepthData, m_tempDepthData, m_depthTotalChannel*m_depthImageSizeX*m_depthImageSizeY*sizeof(unsigned char)); } m_bUpdate = false; return true; } else return false; } //=========================================================================== /*! Render this mesh in OpenGL. This method actually just prepares some OpenGL state, and uses renderDepthImage to actually do the rendering. \fn void cMesh::render(const int a_renderMode) \param a_renderMode Rendering mode (see cGenericObject) */ //=========================================================================== void cDepthImage::render(const int a_renderMode) { // if transparency is enabled, either via multipass rendering or via // standard alpha-blending... if (m_useTransparency) { // if we're using multipass transparency, render only on // the front and back passes if (m_useMultipassTransparency) { // render transparent front triangles if (a_renderMode == CHAI_RENDER_MODE_TRANSPARENT_FRONT_ONLY) { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); renderDepthImage(a_renderMode); } // render transparent back triangles else if (a_renderMode == CHAI_RENDER_MODE_TRANSPARENT_BACK_ONLY) { glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); renderDepthImage(a_renderMode); } // Multipass is enabled for this object but not for the camera, so do // a simple pass with transparency on... else if (a_renderMode == CHAI_RENDER_MODE_RENDER_ALL) { // Turn culling off for transparent objects... glDisable(GL_CULL_FACE); renderDepthImage(a_renderMode); } } // multipass transparency is disabled; render only on non-transparent passes else { if ( (a_renderMode == CHAI_RENDER_MODE_NON_TRANSPARENT_ONLY) || (a_renderMode == CHAI_RENDER_MODE_RENDER_ALL) ) { // Turn culling off for transparent objects... glDisable(GL_CULL_FACE); renderDepthImage(a_renderMode); } } } // if transparency is disabled... else { // render only on non-transparent passes if ( (a_renderMode == CHAI_RENDER_MODE_NON_TRANSPARENT_ONLY) || (a_renderMode == CHAI_RENDER_MODE_RENDER_ALL) ) { // render a non-transparent mesh if (m_cullingEnabled) { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } else { glDisable(GL_CULL_FACE); } renderDepthImage(a_renderMode); } } // Restore default OpenGL state glDisable(GL_CULL_FACE); glCullFace(GL_BACK); } cVector3d cDepthImage::trans2cartesian(cVector3d a_point) { double distance; cVector3d pointOnImage((a_point.x-(double)m_halfDepthImageSizeX)*m_pixelWidth, (a_point.y-(double)m_halfDepthImageSizeY)*m_pixelWidth, -m_focalLength); cVector3d pointInSpace; pointOnImage.normalize(); distance = m_primaryDistance + m_primaryWidth*( 255.0-a_point.z)/255.0; pointInSpace = distance*pointOnImage; return pointInSpace; } cVector3d cDepthImage::trans2image(cVector3d a_point) { cVector3d pointOnImage; cVector3d pointInSpace = a_point; double length = pointInSpace.length(); pointInSpace.normalize(); pointOnImage.z = 255.0/m_primaryWidth*(m_primaryWidth + m_primaryDistance - length); pointOnImage.x = pointInSpace.x/pointInSpace.z*-m_focalLength/0.00112; pointOnImage.y = pointInSpace.y/pointInSpace.z*-m_focalLength/0.00112; pointOnImage.add((double)m_halfDepthImageSizeX, (double)m_halfDepthImageSizeY, 0.0); return pointOnImage; } void cDepthImage::renderDepthImage(const int a_renderMode) { if(m_depthData == NULL) return; // not yet : scaling glDisable(GL_LIGHTING); glDisable(GL_BLEND); glEnable(GL_COLOR_MATERIAL); glDisable(GL_TEXTURE_2D); glPolygonMode(GL_FRONT, GL_FILL); // Mesh-based int D=m_renderSample; int baseIndex0, baseIndex1, baseIndex2, baseIndex3; float half_depthSizeX = (float)m_depthImageSizeX/2.0; float half_depthSizeY = (float)m_depthImageSizeY/2.0; cVector3d pointOnImage, pointInSpace; for(int x = 0; x < (m_depthImageSizeX-D); x+=D) for(int y = 0; y < (m_depthImageSizeY-D); y+=D) { baseIndex0 = m_depthImageSizeX*y + x; baseIndex1 = baseIndex0+D; baseIndex3 = baseIndex0+m_depthImageSizeX*D; baseIndex2 = baseIndex3+D; unsigned char pDepthData0 = m_depthData[m_depthTotalChannel*baseIndex0+m_depthChannelNum]; unsigned char pDepthData1 = m_depthData[m_depthTotalChannel*baseIndex1+m_depthChannelNum]; unsigned char pDepthData2 = m_depthData[m_depthTotalChannel*baseIndex2+m_depthChannelNum]; unsigned char pDepthData3 = m_depthData[m_depthTotalChannel*baseIndex3+m_depthChannelNum]; unsigned char * pColorData0 = &m_colorData[m_colorTotalChannel*baseIndex0+m_colorChannelNum]; unsigned char * pColorData1 = &m_colorData[m_colorTotalChannel*baseIndex1+m_colorChannelNum]; unsigned char * pColorData2 = &m_colorData[m_colorTotalChannel*baseIndex2+m_colorChannelNum]; unsigned char * pColorData3 = &m_colorData[m_colorTotalChannel*baseIndex3+m_colorChannelNum]; if( (pDepthData0 != 0) && (pDepthData1 != 0) && (pDepthData2 != 0) && (pDepthData3 != 0) ) { //!!!!!!!!!!!!!!!!!!!!!! // When drawing depth image, the depth value is subtracted by 2.0 // I don't know why the proxy gets into the image visually not haptically. glBegin(GL_TRIANGLE_FAN); pointOnImage.set((double)x, (double)y, pDepthData0); pointInSpace = trans2cartesian(pointOnImage); glColor3ub(pColorData0[2], pColorData0[1], pColorData0[1]); glVertex3f( pointInSpace.x, pointInSpace.y, pointInSpace.z); pointOnImage.set((double)x+D, (double)y, pDepthData1); pointInSpace = trans2cartesian(pointOnImage); glColor3ub(pColorData1[2], pColorData1[1], pColorData1[1]); glVertex3f( pointInSpace.x, pointInSpace.y, pointInSpace.z); pointOnImage.set((double)x+D, (double)y+D, pDepthData2); pointInSpace = trans2cartesian(pointOnImage); glColor3ub(pColorData2[2], pColorData2[1], pColorData2[1]); glVertex3f( pointInSpace.x, pointInSpace.y, pointInSpace.z); pointOnImage.set((double)x, (double)y+D, pDepthData3); pointInSpace = trans2cartesian(pointOnImage); glColor3ub(pColorData3[2], pColorData3[1], pColorData3[1]); glVertex3f( pointInSpace.x, pointInSpace.y, pointInSpace.z); glEnd(); } } /////////////////////////////////////////// } cVector3d cDepthImage::computeForces(const cVector3d& a_probePosition) { // compute the position of the probe in local coordinates. cVector3d probePositionLocal; probePositionLocal = cMul(cTrans(m_localRot), cSub(a_probePosition, m_localPos)); // compute interaction forces with this object cVector3d localForce; localForce.set(0,0,0); // convert the reaction force into my parent coordinates cVector3d m_globalForce = cMul(m_localRot, localForce); return m_globalForce; } double cDepthImage::getDepth(int a_x, int a_y) { double depth = 0.0; if(m_useSmoothing) { double num_count = 0.0; if(a_x >= (m_smoothingArea - 1) && a_x <= (m_depthImageSizeX-m_smoothingArea) && a_y >= (m_smoothingArea - 1) && a_y <= (m_depthImageSizeY-m_smoothingArea)) { int i, j; for(i=0; i<m_smoothingArea; i++) for(j=0; j<(i*2+1); j++) { num_count+=1.0; depth += (1.0-m_timeRatio)*(double)m_depthData[m_depthTotalChannel*(m_depthImageSizeX*(a_y-m_smoothingArea+i+1) + (a_x-i+j)) + m_depthChannelNum] + m_timeRatio*(double)m_nextDepthData[m_depthTotalChannel*(m_depthImageSizeX*(a_y-m_smoothingArea+i+1) + (a_x-i+j)) + m_depthChannelNum]; } for(i=0; i<m_smoothingArea-1; i++) for(j=0; j<(i*2+1); j++) { num_count+=1.0; depth += (1.0-m_timeRatio)*(double)m_depthData[m_depthTotalChannel*(m_depthImageSizeX*(a_y+m_smoothingArea-i-1) + (a_x-i+j)) + m_depthChannelNum] + m_timeRatio*(double)m_nextDepthData[m_depthTotalChannel*(m_depthImageSizeX*(a_y+m_smoothingArea-i-1) + (a_x-i+j)) + m_depthChannelNum]; } depth /= num_count; } else depth = (1.0-m_timeRatio)*(double)m_depthData[m_depthTotalChannel*(m_depthImageSizeX*a_y + a_x) + m_depthChannelNum] + m_timeRatio*(double)m_nextDepthData[m_depthTotalChannel*(m_depthImageSizeX*a_y + a_x) + m_depthChannelNum]; } else depth = (1.0-m_timeRatio)*(double)m_depthData[m_depthTotalChannel*(m_depthImageSizeX*a_y + a_x) + m_depthChannelNum] + m_timeRatio*(double)m_nextDepthData[m_depthTotalChannel*(m_depthImageSizeX*a_y + a_x) + m_depthChannelNum]; if(m_imageMaterial.m_bIsBumpData && m_useImageBump) { depth += m_imageMaterial.getBump((double)a_x/(double)m_depthImageSizeX, (double)a_y/(double)m_depthImageSizeY); } return depth; } double cDepthImage::getStiffness(cVector3d a_proxy) { cMatrix3d transLocalRot; m_globalRot.transr(transLocalRot); cVector3d localPoint = a_proxy; localPoint.sub(m_globalPos); transLocalRot.mul(localPoint); localPoint = trans2image(localPoint); return m_imageMaterial.getStiffness(localPoint.x/(double)m_depthImageSizeX, localPoint.y/(double)m_depthImageSizeY); } double cDepthImage::getStaticFriction(cVector3d a_proxy) { cMatrix3d transLocalRot; m_globalRot.transr(transLocalRot); cVector3d localPoint = a_proxy; localPoint.sub(m_globalPos); transLocalRot.mul(localPoint); localPoint = trans2image(localPoint); return m_imageMaterial.getStaticFriction(localPoint.x/(double)m_depthImageSizeX, localPoint.y/(double)m_depthImageSizeY); } double cDepthImage::getDynamicFriction(cVector3d a_proxy) { cMatrix3d transLocalRot; m_globalRot.transr(transLocalRot); cVector3d localPoint = a_proxy; localPoint.sub(m_globalPos); transLocalRot.mul(localPoint); localPoint = trans2image(localPoint); return m_imageMaterial.getDynamicFriction(localPoint.x/(double)m_depthImageSizeX, localPoint.y/(double)m_depthImageSizeY); } double cDepthImage::getStiffnessLocal(cVector3d a_proxy) { return m_imageMaterial.getStiffness(a_proxy.x/(double)m_depthImageSizeX, a_proxy.y/(double)m_depthImageSizeY); } double cDepthImage::getStaticFrictionLocal(cVector3d a_proxy) { return m_imageMaterial.getStaticFriction(a_proxy.x/(double)m_depthImageSizeX, a_proxy.y/(double)m_depthImageSizeY); } double cDepthImage::getDynamicFrictionLocal(cVector3d a_proxy) { return m_imageMaterial.getDynamicFriction(a_proxy.x/(double)m_depthImageSizeX, a_proxy.y/(double)m_depthImageSizeY); } double cDepthImage::getBump(int a_x, int a_y) { return m_imageMaterial.getDynamicFriction(a_x, a_y); } void cDepthImage::useImageBump(const bool a_useImageBump, const bool a_affectChildren) { // update changes to object m_useImageBump = a_useImageBump; // propagate changes to my children if (a_affectChildren) { for (unsigned int i=3; i<m_children.size(); i++) { cGenericObject *nextObject = m_children[i]; cDepthImage *nextDepthImage = dynamic_cast<cDepthImage*>(nextObject); if (nextDepthImage) { nextDepthImage->useImageMaterial(a_useImageBump, a_affectChildren); } } } } void cDepthImage::useSmoothing(const bool a_useSmoothing) { m_useSmoothing = a_useSmoothing; } cVector3d cDepthImage::correctProxy(const cVector3d a_proxy) { cVector3d correctionProxy = a_proxy; cVector3d currentSurfacePoint = projectOnDepthImage(a_proxy); if((currentSurfacePoint.z > m_previousSurfacePoint.z) && (a_proxy.z >= (m_previousSurfacePoint.z)) && (a_proxy.z <= currentSurfacePoint.z) ){ correctionProxy.z = currentSurfacePoint.z; } return correctionProxy; } bool cDepthImage::correctProxyOnImage(cVector3d& a_proxy) { cVector3d currentSurfacePoint = projectOnDepthImage(a_proxy); if(currentSurfacePoint.z >= m_previousSurfacePoint.z || fabs(currentSurfacePoint.z - m_previousSurfacePoint.z) < CHAI_SMALL ) { a_proxy.z = currentSurfacePoint.z; return true; } else return false; } void cDepthImage::setCameraParameters(double a_focalLength, double a_pixelWidth, double a_primaryDistance, double a_primaryWidth) { m_focalLength = a_focalLength; m_pixelWidth = a_pixelWidth; m_primaryDistance = a_primaryDistance; m_primaryWidth = a_primaryWidth; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2011 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 CRYPTO_MASTER_PASSWORD_SUPPORT #include "modules/libcrypto/include/CryptoMasterPasswordEncryption.h" #include "modules/libcrypto/include/CryptoStreamEncryptionCBC.h" #include "modules/util/adt/bytebuffer.h" #define SSL_EMAIL_PASSWORD_VERIFICATION "Opera Email Password Verification" void CryptoMasterPasswordEncryption::InitL() { m_des_cbc = CryptoStreamEncryptionCBC::Create(CryptoSymmetricAlgorithm::Create3DES(24), CryptoStreamEncryptionCBC::PADDING_STRATEGY_PCKS15); LEAVE_IF_NULL(m_des_cbc); } CryptoMasterPasswordEncryption::CryptoMasterPasswordEncryption() : m_des_cbc(NULL) { } CryptoMasterPasswordEncryption::~CryptoMasterPasswordEncryption() { OP_DELETE(m_des_cbc); } OP_STATUS CryptoMasterPasswordEncryption::EncryptPasswordWithSecurityMasterPassword(UINT8 *&encrypted_password_blob, int &encrypted_password_length, const UINT8 *password_to_encrypt, int password_to_encrypt_len, const UINT8 *master_password, int master_password_length) { // Format: salt length data (4 bytes, network encoded) | salt | encrypted data length data (4 bytes, network encoded) | encrypted data encrypted_password_blob = NULL; int encrypted_data_length = m_des_cbc->CalculateEncryptedTargetLength(password_to_encrypt_len); encrypted_password_length = /*salt length */ 4 + /*salt*/ 8 + /*Encrypted password length */ 4 + /*Encrypted password*/ + encrypted_data_length; UINT8 *temp_encrypted_password_blob = OP_NEWA(UINT8, encrypted_password_length); RETURN_OOM_IF_NULL(temp_encrypted_password_blob); ANCHOR_ARRAY(UINT8, temp_encrypted_password_blob); UINT8 *salt_length_bytes = temp_encrypted_password_blob; UINT8 *salt = temp_encrypted_password_blob + 4; UINT8 *encrypted_data_length_bytes = temp_encrypted_password_blob + 12; UINT8 *encrypted_data = temp_encrypted_password_blob + 16; UINT8* encrypted_password; RETURN_IF_ERROR(EncryptWithPassword(encrypted_password, encrypted_data_length, password_to_encrypt, password_to_encrypt_len, salt, master_password, master_password_length, (const UINT8*)SSL_EMAIL_PASSWORD_VERIFICATION, op_strlen(SSL_EMAIL_PASSWORD_VERIFICATION))); op_memcpy(encrypted_data, encrypted_password, encrypted_data_length); OP_DELETEA(encrypted_password); /* puts the salt length and encrypted password length into the blob */ ByteBuffer big_endian_salt_length; RETURN_IF_ERROR(big_endian_salt_length.Append4(8)); big_endian_salt_length.Extract(0, big_endian_salt_length.Length(), (char*)salt_length_bytes); ByteBuffer big_endian_encrypted_password_length; RETURN_IF_ERROR(big_endian_encrypted_password_length.Append4((UINT32)encrypted_data_length)); big_endian_encrypted_password_length.Extract(0, big_endian_salt_length.Length(), (char*)encrypted_data_length_bytes); ANCHOR_ARRAY_RELEASE(temp_encrypted_password_blob); encrypted_password_blob = temp_encrypted_password_blob; return OpStatus::OK; } OP_STATUS CryptoMasterPasswordEncryption::EncryptPasswordWithSecurityMasterPassword(UINT8 *&encrypted_password, int &encrypted_password_length, const UINT8 *password_to_encrypt, int password_to_encrypt_len, const ObfuscatedPassword *master_password) { OP_STATUS status; encrypted_password = 0; int master_password_length; if (!master_password) return OpStatus::ERR; UINT8* master_password_array = master_password->GetMasterPassword(master_password_length); if (!master_password_array) return OpStatus::ERR; ANCHOR_ARRAY(UINT8, master_password_array); status = EncryptPasswordWithSecurityMasterPassword(encrypted_password, encrypted_password_length, password_to_encrypt, password_to_encrypt_len, master_password_array, master_password_length); op_memset(master_password_array, 0, master_password_length); return status; } OP_STATUS CryptoMasterPasswordEncryption::DecryptPasswordWithSecurityMasterPassword(UINT8 *&decrypted_password, int &decrypted_password_length, const UINT8 *password_blob, int password_blob_len, const UINT8* password, int password_length) { // Format: salt length data (4 bytes, network encoded) | salt | encrypted data length data (4 bytes, network encoded) | encrypted data decrypted_password = NULL; decrypted_password_length = 0; if (password_blob_len < 4 /* salt length data */ + 8 /* minimum salt length */ + 4 /* encrypted password length data */ + m_des_cbc->GetBlockSize()) return OpStatus::ERR_PARSING_FAILED; int in_salt_length = password_blob[0] << 24 | password_blob[1] << 16 | password_blob[2] << 8 | password_blob[3]; /* We cannot trust salt_length, must check it makes sense to avoid buffer overflow attacks. */ if (in_salt_length > password_blob_len - 4 /* salt length data */ - 4 /* encrypted password length data */ - m_des_cbc->GetBlockSize() /* minimum encrypted data length */ || in_salt_length < 8) return OpStatus::ERR_PARSING_FAILED; const UINT8 *in_salt = password_blob + 4 /* salt length data */; const UINT8 *encrypted_data_length_data = in_salt + in_salt_length; int encrypted_data_length = encrypted_data_length_data[0] << 24 | encrypted_data_length_data[1] << 16 | encrypted_data_length_data[2] << 8 | encrypted_data_length_data[3]; /* We cannot trust encrypted password length, must check it makes sense to avoid buffer overflow attacks. */ if (encrypted_data_length > password_blob_len - 4 - 4 - in_salt_length || encrypted_data_length < m_des_cbc->GetBlockSize()) return OpStatus::ERR_PARSING_FAILED; const UINT8 *encrypted_data = encrypted_data_length_data + 4 /*encrypted password length data */; return DecryptWithPassword(decrypted_password, decrypted_password_length, encrypted_data, encrypted_data_length, in_salt, in_salt_length, password, password_length, (const UINT8*)SSL_EMAIL_PASSWORD_VERIFICATION, op_strlen(SSL_EMAIL_PASSWORD_VERIFICATION)); } OP_STATUS CryptoMasterPasswordEncryption::DecryptPasswordWithSecurityMasterPassword(UINT8 *&decrypted_password, int &decrypted_password_length, const UINT8 *password_blob, int password_blob_len, const ObfuscatedPassword *master_password) { if (!master_password) return OpStatus::ERR; decrypted_password = NULL; decrypted_password_length = 0; int master_password_length; UINT8* master_password_array = master_password->GetMasterPassword(master_password_length); if (!master_password_array) return OpStatus::ERR; ANCHOR_ARRAY(UINT8, master_password_array); OP_STATUS status = OpStatus::OK; if (master_password_array) status = DecryptPasswordWithSecurityMasterPassword(decrypted_password, decrypted_password_length, password_blob, password_blob_len, master_password_array, master_password_length); op_memset(master_password_array, 0, master_password_length); return status; } OP_STATUS CryptoMasterPasswordEncryption::EncryptWithPassword(UINT8 *&encrypted_data, int &encrypted_data_length, const UINT8 *password_to_encrypt, int password_to_encrypt_len, UINT8 *salt, const UINT8 *master_password, int master_password_length, const UINT8 *plainseed, int plainseed_length) { encrypted_data = NULL; encrypted_data_length = 0; int temp_encrypted_data_length = m_des_cbc->CalculateEncryptedTargetLength(password_to_encrypt_len); UINT8 *temp_encrypted_data = OP_NEWA(UINT8, temp_encrypted_data_length); RETURN_OOM_IF_NULL(temp_encrypted_data); ANCHOR_ARRAY(UINT8, temp_encrypted_data); RETURN_IF_ERROR(CalculateSalt(password_to_encrypt, password_to_encrypt_len, master_password, master_password_length, salt, 8, plainseed, plainseed_length)); RETURN_IF_ERROR(CalculatedKeyAndIV(master_password, master_password_length, salt, 8)); /* Puts the encrypted password into the blob. */ m_des_cbc->Encrypt(password_to_encrypt, temp_encrypted_data, password_to_encrypt_len, temp_encrypted_data_length); ANCHOR_ARRAY_RELEASE(temp_encrypted_data); encrypted_data = temp_encrypted_data; encrypted_data_length = temp_encrypted_data_length; return OpStatus::OK; } OP_STATUS CryptoMasterPasswordEncryption::DecryptWithPassword(UINT8 *&decrypted_data, int &decrypted_data_length, const UINT8 *encrypted_data, int encrypted_data_length, const UINT8 *in_salt, int in_salt_length, const UINT8 *password, int password_length, const UINT8 *plainseed, int plainseed_length) { decrypted_data = NULL; decrypted_data_length = 0; UINT8 *temp_decrypted_data = OP_NEWA(UINT8, encrypted_data_length); ANCHOR_ARRAY(UINT8, temp_decrypted_data); UINT8 *calculated_salt = OP_NEWA(UINT8, in_salt_length); ANCHOR_ARRAY(UINT8, calculated_salt); if (!temp_decrypted_data || !calculated_salt) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(CalculatedKeyAndIV(password, password_length, in_salt, in_salt_length)); m_des_cbc->Decrypt(encrypted_data, temp_decrypted_data, encrypted_data_length); int temp_decrypted_data_length = 0; if (OpStatus::IsError(m_des_cbc->CalculateDecryptedTargetLength(temp_decrypted_data_length, temp_decrypted_data, encrypted_data_length))) return OpStatus::ERR_NO_ACCESS; if (temp_decrypted_data_length) { /* Based on the decrypted data, we can re-calculate the salt, and check that it matches the salt given in in_data */ RETURN_IF_ERROR(CalculateSalt(temp_decrypted_data, temp_decrypted_data_length, password, password_length, calculated_salt, in_salt_length, plainseed, plainseed_length)); if (op_memcmp(calculated_salt, in_salt, in_salt_length) != 0) return OpStatus::ERR_NO_ACCESS; } ANCHOR_ARRAY_RELEASE(temp_decrypted_data); decrypted_data_length = temp_decrypted_data_length; decrypted_data = temp_decrypted_data; return OpStatus::OK; } OP_STATUS CryptoMasterPasswordEncryption::BytesToKey(CryptoHashAlgorithm hash_alg, const UINT8 *in_data, int in_data_length, const UINT8 *salt, int salt_length, int hash_iteration_count, UINT8 *out_key, int out_key_length, UINT8 *out_iv, int out_iv_length) { OpAutoPtr<CryptoHash> hasher(CryptoHash::Create(hash_alg)); if (!hasher.get()) return OpStatus::ERR_NO_MEMORY; int hasher_size = hasher->Size(); UINT8 *previous_iteration_result = OP_NEWA(UINT8, hasher_size); ANCHOR_ARRAY(UINT8, previous_iteration_result); if (!previous_iteration_result) return OpStatus::ERR_NO_MEMORY; int hash_count = 1; int current_key_data_generated_length = 0; int current_iv_data_generated_length = 0; while (current_key_data_generated_length + current_iv_data_generated_length < out_key_length + out_iv_length) { for (int i = 0; i < hash_count; i++) { RETURN_IF_ERROR(hasher->InitHash()); // Do not hash the result of previous iteration before actual having one. if (current_key_data_generated_length > 0 || current_iv_data_generated_length || i > 0) hasher->CalculateHash(previous_iteration_result, hasher_size); hasher->CalculateHash(in_data, in_data_length); hasher->CalculateHash(salt, salt_length); hasher->ExtractHash(previous_iteration_result); } int hash_index = 0; if (current_key_data_generated_length < out_key_length) { while (current_key_data_generated_length < out_key_length && hash_index < hasher_size) out_key[current_key_data_generated_length++] = previous_iteration_result[hash_index++]; } if (current_key_data_generated_length >= out_key_length) { while (current_iv_data_generated_length < out_iv_length && hash_index < hasher_size) out_iv[current_iv_data_generated_length++] = previous_iteration_result[hash_index++]; } } return OpStatus::OK; } OP_STATUS CryptoMasterPasswordEncryption::CalculateSalt(const UINT8 *in_data, int in_data_len, const UINT8 *password, int password_length, UINT8 *salt, int salt_len, const UINT8 *plainseed, int plainseed_length) { if (!salt) return OpStatus::ERR; OpAutoPtr<CryptoHash> sha(CryptoHash::CreateSHA1()); RETURN_OOM_IF_NULL(sha.get()); UINT8 digest_result[CRYPTO_MAX_HASH_SIZE]; /* ARRAY OK 2012-01-20 haavardm */ OP_ASSERT(salt_len <= sha->Size()); RETURN_IF_ERROR(sha->InitHash()); sha->CalculateHash(password, password_length); sha->CalculateHash(plainseed, plainseed_length); sha->CalculateHash(in_data, in_data_len); sha->ExtractHash(digest_result); /* puts salt into the blob */ op_memcpy(salt, digest_result, salt_len); // only the 8 first bytes is used. return OpStatus::OK; } OP_STATUS CryptoMasterPasswordEncryption::CalculatedKeyAndIV(const UINT8 *password, int password_length, const UINT8 *salt, int salt_len) { if (!password || !salt) return OpStatus::ERR; int out_key_len = m_des_cbc->GetKeySize(); int out_iv_len = m_des_cbc->GetBlockSize(); UINT8 *out_key = OP_NEWA(UINT8, out_key_len); RETURN_OOM_IF_NULL(out_key); ANCHOR_ARRAY(UINT8, out_key); UINT8 *out_iv = OP_NEWA(UINT8, out_iv_len); RETURN_OOM_IF_NULL(out_iv); ANCHOR_ARRAY(UINT8, out_iv); RETURN_IF_ERROR(BytesToKey(CRYPTO_HASH_TYPE_MD5, password, password_length, salt, salt_len, 1, out_key, out_key_len, out_iv, out_iv_len)); m_des_cbc->SetIV(out_iv); return m_des_cbc->SetKey(out_key); } #endif // CRYPTO_MASTER_PASSWORD_SUPPORT
/***************************************************************************************************************** * File Name : FindFourElementsForGivenSum.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\arrays\page03\FindFourElementsForGivenSum.h * Created on : Jan 8, 2014 :: 2:20:27 PM * 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 FINDFOURELEMENTSFORGIVENSUM_H_ #define FINDFOURELEMENTSFORGIVENSUM_H_ int *findFourElementsForGivenSumON4(vector<int> userInput,int sum){ if(userInput.size() < 4){ return NULL; } unsigned int firstCrawler,secondCrawler,thirdCrawler,fourthCrawler; for(firstCrawler = 0;firstCrawler < userInput.size()-3;firstCrawler++){ for(secondCrawler = firstCrawler+1;secondCrawler < userInput.size()-2;secondCrawler++){ for(thirdCrawler = secondCrawler +1;thirdCrawler < userInput.size()-1;thirdCrawler++){ for(fourthCrawler = thirdCrawler+1;fourthCrawler < userInput.size();fourthCrawler++){ if(userInput[firstCrawler] + userInput[secondCrawler] + userInput[thirdCrawler] + userInput[fourthCrawler] == sum){ int result[4]; result[0] = userInput[firstCrawler]; result[1] = userInput[secondCrawler]; result[2] = userInput[thirdCrawler]; result[3] = userInput[fourthCrawler]; return result; } } } } } return NULL; } int *findFourElementsForGivenSumON3(vector<int> userInput,int sum){ if(userInput.size() < 4){ return NULL; } sort(userInput.begin(),userInput.end()); unsigned int frontCrawler,rearCrawler; int currentSum; for(unsigned int firstCrawler = 0;firstCrawler < userInput.size()-3;firstCrawler++){ for(unsigned int secondCrawler = firstCrawler+1;secondCrawler < userInput.size()-2;secondCrawler++){ frontCrawler = secondCrawler+1; rearCrawler = userInput.size()-1; currentSum = userInput[frontCrawler] + userInput[rearCrawler]; while(frontCrawler < rearCrawler){ if(currentSum + userInput[frontCrawler] + userInput[rearCrawler] == sum){ int result[4]; result[0] = userInput[firstCrawler]; result[1] = userInput[secondCrawler]; result[2] = userInput[frontCrawler]; result[3] = userInput[rearCrawler]; return result; }else{ if(currentSum+userInput[frontCrawler]+userInput[rearCrawler] > sum){ frontCrawler++; }else{ rearCrawler--; } } } } } } struct pair{ int sum; unsigned int firstIndex; unsigned int secondIndex; }; bool sortFunc(pair firstPair,pair secondPair){ return firstPair.sum < secondPair.sum?true:false; } bool noCommon(pair firstPair,pair secondPair){ if(firstPair.firstIndex == secondPair.firstIndex || firstPair.firstIndex == secondPair.secondIndex || firstPair.secondIndex == secondPair.firstIndex || firstPair.secondIndex == secondPair.secondIndex){ return false; }else{ return true; } } int *findFourElementsForGivenSum(vector<int> userInput,int sum){ if(userInput.size() < 4){ return NULL; } vector<pair> allPairsSum; for(unsigned int outerCrawler = 0;outerCrawler < userInput.size();outerCrawler++){ for(unsigned int innerCrawler = outerCrawler+1;innerCrawler < userInput.size();innerCrawler++){ pair newPair = new pair(); newPair.sum = userInput[outerCrawler] + userInput[innerCrawler]; newPair.firstIndex = outerCrawler; newPair.secondIndex = innerCrawler; allPairsSum.push_back(newPair); } } sort(allPairsSum.begin(),allPairsSum.end()); unsigned int frontCrawler = 0,rearCrawler = allPairsSum.size()-1; int currentSum; while(frontCrawler < rearCrawler){ currentSum = allPairsSum[frontCrawler].sum + allPairsSum[rearCrawler].sum; if(noCommon(allPairsSum[frontCrawler],allPairsSum[rearCrawler]) && currentSum == sum){ int result[4]; result[0] = allPairsSum[frontCrawler].firstIndex; result[1] = allPairsSum[frontCrawler].secondIndex; result[2] = allPairsSum[rearCrawler].firstIndex; result[3] = allPairsSum[rearCrawler].secondIndex; return result; } if(currentSum < sum){ frontCrawler++; }else{ rearCrawler--; } } } #endif /* FINDFOURELEMENTSFORGIVENSUM_H_ */ /************************************************* End code *******************************************************/
#pragma once #include "Entities/Key/Key.h" class PartOfGeneralAnswerOptionsKey; class GeneralAnswerOptionsKey : public Key { public: // Методы возвращают ссылку на часть ключа, // соответствующую переданному индексу const PartOfGeneralAnswerOptionsKey &at(uint index) const; const PartOfGeneralAnswerOptionsKey &operator[](uint index) const; PartOfGeneralAnswerOptionsKey &operator[](uint index); /** * @brief Метод возвращает индекс последнего варианта ответа * @return индекс последнего варианта ответа */ uint getCurrentAnswerOptionIndex() const; /** * @brief Метод запоминает индекс нового варинта ответа * @param answerOptionIndex - индекс нового варианта ответа */ void addAnswerOption(uint answerOptionIndex); /** * @brief Метод добавляет индекс вопроса к последнему добавленному варианту ответа * @param questionIndex - индекс варианта ответа */ void addQuestionToLastAnswerOption(uint questionIndex); /** * @brief Метод возвращает индексы вопросов от последнего добавленного * варианта ответа * @return индексы вопросов */ Indexes getCurrentQuestionIndexes() const; /** * @brief Метод удаляет вопрос с переданным индексом из текущего варианта ответа * @param questionIndex - индекс вопроса */ void deleteQuestionFromCurrentAnswerOption(uint questionIndex); /** * @brief Метод удаляет вариант ответа с переданным количеством баллов * @param answerOptionIndex - индекс варианта ответа * @param points - количество баллов */ void deleteAnswerOption(uint answerOptionIndex, uint points); };
/* * node_car_estimate.cpp * * This is the node to analyze and publish car states. * * Author: yubocheng@live.cn * * Copyright (c) 2019 Jimu * All rights reserved. * */ #include <node_car_estimate.h> int main(int argc, char **argv) { ros::init(argc, argv, "car_state_publisher", ros::init_options::NoRosout); CarStatePublisher carStatePublisher; if (!carStatePublisher.Init()) return -1; while (ros::ok()) { ros::spinOnce(); carStatePublisher.Loop(); } return 0; }
#include<bits/stdc++.h> using namespace std; #define maxn 100005 int dp[maxn]; int a[maxn]; int main(){ int T; scanf("%d",&T); for(int cas=1;cas<=T;cas++){ if(cas>1) printf("\n"); int n; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); memset(dp,0,sizeof(dp)); dp[0]=a[0]; int ans=dp[0]; int ind=0; int l=0; int temp=0; for(int i=1;i<n;i++){ if(dp[i-1]<0){ dp[i]=a[i]; temp=i; }else dp[i]=dp[i-1]+a[i]; if(dp[i]>ans){ ans=dp[i]; ind=i; l=temp; } } int tind=ind; for(tind=ind;tind>=0;tind--){ if(dp[tind]<0){ break; } } tind++; printf("Case %d:\n%d %d %d\n",cas,ans,l+1,ind+1); } return 0; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Espen Sand */ #ifndef CUPS_HELPER_PRIVATE_H #define CUPS_HELPER_PRIVATE_H class DestinationInfo; class CupsFunctions; class CupsHelperPrivate { public: bool GetPaperSizes(DestinationInfo& info, CupsFunctions* functions); }; #endif
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include <Shell.h> #include <Bajka.h> #ifndef ANDROID #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/program_options/cmdline.hpp> #include <boost/program_options/parsers.hpp> #else #include <android_native_app_glue.h> #endif #include <string> #include "DebugButtonController.h" #include "ReloadableXmlModelManager.h" #include "SceneController.h" #ifndef ANDROID namespace po = boost::program_options; int main (int argc, char **argv) { Util::ShellConfig config; // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("fullscreen,f", "run in full screen mode") ("showaabb,a", "show AABBs around objects") ("viewportWidth,x", po::value<int>(&config.viewportWidth), "set horizontal resolution in pixels") ("viewportHeight,y", po::value<int>(&config.viewportHeight), "set vertical resolution in pixels") ("loopdelay,l", po::value<int>(&config.loopDelayMs), "set game loop delay in ms") ("config,c", po::value <std::string>(&config.configFile)->default_value ("config.xml"), "config file (resolution, fullscreen and various other options)") ("definition,d", po::value <std::string>(&config.definitionFile)->default_value ("main.xml"), "input file with XML definitions"); po::positional_options_description p; p.add ("definition", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return 1; } config.fullScreen = vm.count ("fullscreen"); config.showAABB = vm.count ("showaabb"); Shell *shell = Shell::instance (); return shell->run (config); } #else // ANDROID /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main (struct android_app* app) { // Make sure glue isn't stripped. app_dummy(); sleep (4); // Shell *shell = Shell::instance (); // Util::ShellConfig config; // shell->run (config, state); Util::ShellConfig config; std::auto_ptr <GameLoop> loop = ShellFactory::createGameLoop (&config, app); loop->loop (); } #endif
/*快速幂取模 (a^b)%p*/ int quickpow(int a,int b,int p) { int ret=1; a%=p; while(b) { if(b&1) ret=(a*ret)%p; a=(a*a)%p; b>>=1; } return ret; } /*快速乘法取模 (a*b)%p*/ int quickmul(int a,int b,int p) { int ans=0; while(b) { if(b&1) {b--;ans=(ans+a)%p;} b>>=1; a=(a+a)%p; } return ans; }
//算法:数论/拓展欧几里得定理 /* 求解不定方程a*x+b*y==gcd(a,b); 解法推导: ∵a=[a/b]*b+a%b; 又∵欧几里得知:gcd(a,b)==gcd(b,a%b); ∴([a/b]*b+a%b)*x+b*y=gcd(a,b); ∴[a/b]*b*x+(a%b)*x+b*y=gcd(a,b); ∴b*([a/b]*x+y)+(a%b)*x=gcd(b,a%b); 看到这里,不难发现: 令:a'=b,x'=[a/b]*x+y,b'=a%b,y'=x; 整理后原式又变成了:a'*x'+b'*y'==gcd(a',b'); 当然解虽然最小,可能是负数, 加b/gcd(a,b)再模上b/gcd(a,b)即可 */ #include<cstdio> #include<algorithm> int a,b,x,y; void exgcd(int a,int b) { if(b) { exgcd(b,a%b); int k=x; x=y,y=k-a/b*y; } else x=1,y=0; } int main() { int a,b; scanf("%d%d",&a,&b); exgcd(a,b); printf("%d",(x+b)%b); }
/* -*- 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. */ #include "core/pch.h" #ifdef _PLUGIN_SUPPORT_ #include "modules/ns4plugins/src/pluginhandler.h" #include "modules/ns4plugins/src/plugin.h" #include "modules/ns4plugins/src/pluginlibhandler.h" #include "modules/ns4plugins/src/pluginlib.h" #include "modules/ns4plugins/opns4plugin.h" #include "modules/ns4plugins/src/pluginstream.h" #include "modules/doc/frm_doc.h" #include "modules/pi/OpThreadTools.h" #include "modules/pi/OpLocale.h" #include "modules/hardcore/mh/messages.h" #include "modules/hardcore/cpuusagetracker/cpuusagetrackeractivator.h" #ifdef _MACINTOSH_ # include "platforms/mac/pi/plugins/MacOpPluginWindow.h" #endif // _MACINTOSH_ #include "modules/dochand/win.h" #include "modules/viewers/viewers.h" #include "modules/windowcommander/src/WindowCommander.h" #include "modules/logdoc/htm_elm.h" #include "modules/layout/box/box.h" #include "modules/layout/content/content.h" #include "modules/ns4plugins/src/pluginexceptions.h" #include "modules/prefs/prefsmanager/collections/pc_app.h" PluginHandler::PluginHandler() : plugincount(0) , pluginlibhandler(NULL) , last_handled_msg(NULL) #ifdef NS4P_QUICKTIME_CRASH_WORKAROUND , m_number_of_active_quicktime_plugins(0) #endif // NS4P_QUICKTIME_CRASH_WORKAROUND #ifdef NS4P_WINDOWLESS_MACROMEDIA_WORKAROUND , m_spoof_ua(FALSE) #endif // NS4P_WINDOWLESS_MACROMEDIA_WORKAROUND , m_nextTimerID(1) #ifdef NS4P_COMPONENT_PLUGINS , m_scripting_context(0) #endif // NS4P_COMPONENT_PLUGINS { g_main_message_handler->SetCallBack(this, MSG_PLUGIN_CALL_ASYNC, 0); } PluginHandler::~PluginHandler() { // clean up the remaining plugins before destruction of the plugin handler Plugin* plugin = NULL; while ((plugin = (Plugin*)plugin_list.First()) != NULL) { plugin->Destroy(); OP_DELETE(plugin); plugin = NULL; } PluginHandlerRestartObject* p = NULL; while ((p = restart_object_list.First()) != NULL) { p->Out(); OP_DELETE(p); p = NULL; } if (pluginlibhandler) OP_DELETE(pluginlibhandler); pluginlibhandler = NULL; } OP_STATUS PluginHandler::Init() { OP_ASSERT(pluginlibhandler == NULL); pluginlibhandler = OP_NEW(PluginLibHandler, ()); return pluginlibhandler ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; } #ifdef USE_PLUGIN_EVENT_API OpNS4Plugin* PluginHandler::New(const uni_char *plugin_dll, OpComponentType component_type, FramesDocument* frames_doc, OpStringC &mimetype, uint16 mode, HTML_Element* htm_elm, URL* url, BOOL embed_url_changed) #else OpNS4Plugin* PluginHandler::New(const uni_char *plugin_dll, OpComponentType component_type, FramesDocument* frames_doc, void* embed, OpStringC &mimetype, uint16 mode, int16 argc, const uni_char *argn[], const uni_char *argv[], HTML_Element* htm_elm, URL* url, BOOL embed_url_changed) #endif // USE_PLUGIN_EVENT_API { #ifdef NS4P_QUICKTIME_CRASH_WORKAROUND if ((mimetype.CompareI("audio/wav") == 0 || mimetype.CompareI("audio/x-wav") == 0 || mimetype.CompareI("video/quicktime") == 0 || mimetype.CompareI("application/sdp") == 0 || mimetype.CompareI("application/x-sdp") == 0 || mimetype.CompareI("application/x-rtsp") == 0 || mimetype.CompareI("video/flc") == 0)) { if (m_number_of_active_quicktime_plugins < NS4P_DEFAULT_MAX_NUMBER_QUICKTIME_PLUGINS) m_number_of_active_quicktime_plugins++; else return NULL; } #endif // NS4P_QUICKTIME_CRASH_WORKAROUND #if defined(NS4P_FLASH_LIMITATION_TOTAL) || defined(NS4P_FLASH_LIMITATION_PER_PAGE) if ((mimetype.CompareI("application/x-shockwave-flash") == 0 || mimetype.CompareI("application/futuresplash") == 0)) { int flash_in_total = 1; int flash_per_document = 1; for (Plugin* plug = (Plugin*)plugin_list.First(); plug; plug = plug->Suc()) { NPMIMEType mt = plug->GetMimeType(); if (mt && (!op_stricmp(mt, "application/x-shockwave-flash") || !op_stricmp(mt, "application/futuresplash"))) { flash_in_total++; if (plug->GetDocument() == frames_doc) flash_per_document++; } } #ifdef NS4P_FLASH_LIMITATION_TOTAL if (flash_in_total > NS4P_MAX_FLASH_IN_TOTAL) return NULL; #endif // NS4P_FLASH_LIMITATION_TOTAL #ifdef NS4P_FLASH_LIMITATION_PER_PAGE if (flash_per_document > NS4P_MAX_FLASH_PER_DOCUMENT) return NULL; #endif // NS4P_FLASH_LIMITATION_PER_PAGE } #endif // defined(NS4P_FLASH_LIMITATION_TOTAL) || defined(NS4P_FLASH_LIMITATION_PER_PAGE) Plugin* plug = OP_NEW(Plugin, ()); if (!plug) return NULL; OP_STATUS ret = plug->Create(plugin_dll, component_type, ++plugincount); if (OpStatus::IsError(ret)) { OP_DELETE(plug); return NULL; } if (!plug->GetID()) { OP_DELETE(plug); return NULL; } else { plug->Into(&plugin_list); plug->SetHtmlElement(htm_elm); // Calling the virtual method of the ElementRef class. plug->SetElm(htm_elm); #ifdef USE_PLUGIN_EVENT_API if (OpStatus::IsError(plug->New(frames_doc, mimetype.CStr(), mode, url, embed_url_changed))) #else if (OpStatus::IsError(plug->New(frames_doc, embed, mimetype.CStr(), mode, argc, argn, argv, url, embed_url_changed))) #endif // USE_PLUGIN_EVENT_API { OpStatus::Ignore(plug->Destroy()); OP_DELETE(plug); return NULL; } return plug; } } void PluginHandler::Destroy(OpNS4Plugin* plugin) { OP_NEW_DBG("PluginHandler::Destroy", "ns4p"); Plugin* plug = (Plugin*)plugin; if (plug) { OP_DBG(("Plugin [%d]", plug->GetID())); #ifdef NS4P_QUICKTIME_CRASH_WORKAROUND NPMIMEType mt = plug->GetMimeType(); if (mt && (!op_stricmp(mt, "audio/wav") || !op_stricmp(mt, "audio/x-wav") || !op_stricmp(mt, "video/quicktime") || !op_stricmp(mt, "application/sdp") || !op_stricmp(mt, "application/x-sdp") || !op_stricmp(mt, "application/x-rtsp") || !op_stricmp(mt, "video/flc"))) { m_number_of_active_quicktime_plugins--; } #endif // NS4P_QUICKTIME_CRASH_WORKAROUND plug->ScheduleDestruction(); } } Plugin* PluginHandler::FindPlugin(NPP instance, BOOL return_deleted) { if (instance) { // First check if one of the active plugins matches the instance Plugin *p = static_cast<Plugin*>(plugin_list.First()); while (p) { if (p->GetInstance() == instance) return p; p = p->Suc(); } // If this method is called from PluginHandler::HandleMessage (return_deleted is true) // it's not necessary to check instance's ndata since instance will never change. // It's dangerous to do it because the plugin might have been deleted // and the instance pointer no longer points to a valid instance. if (!return_deleted) { // Then check if one of the active plugins matches the instance's ndata, Shockwave Player requires this p = static_cast<Plugin*>(plugin_list.First()); while (p) { if (p->GetInstance()->ndata == instance->ndata) return p; p = p->Suc(); } } } return 0; } OpNS4Plugin* PluginHandler::FindOpNS4Plugin(OpPluginWindow* oppw, BOOL unused) { if (oppw) { // First check if one of the active plugins matches the instance Plugin* p = static_cast<Plugin*>(plugin_list.First()); while (p) { if (oppw == p->GetPluginWindow()) return p; p = p->Suc(); } } return 0; } FramesDocument* PluginHandler::GetScriptablePluginDocument(NPP instance, Plugin *&plugin) { plugin = FindPlugin(instance); if (plugin && plugin->GetLifeCycleState() >= Plugin::PRE_NEW) { return plugin->GetDocument(); } return 0; } ES_Object* PluginHandler::GetScriptablePluginDOMElement(NPP instance) { Plugin *plugin = FindPlugin(instance); return plugin ? plugin->GetDOMElement() : 0; } #ifdef _PRINT_SUPPORT_ void PluginHandler::Print(const VisualDevice* vd, const uni_char* src_url, const int x, const int y, const unsigned int width, const unsigned int height) { for (Plugin *plug = (Plugin*)plugin_list.First(); plug; plug = plug->Suc()) if (plug->HaveSameSourceURL(src_url)) plug->Print(vd, x, y, width, height); } #endif // _PRINT_SUPPORT_ /* virtual */ void PluginHandler::HandleCallback(OpMessage msg, MH_PARAM_1 wParam, MH_PARAM_2 lParam) { RAISE_AND_RETURN_VOID_IF_ERROR(HandleMessage(msg, wParam, lParam)); } OP_STATUS PluginHandler::HandleMessage(OpMessage message_id, MH_PARAM_1 wParam, MH_PARAM_2 lParam) { OP_NEW_DBG("PluginHandler::HandleMessage", "ns4p"); OP_STATUS stat = OpStatus::OK; if (message_id == MSG_PLUGIN_CALL_ASYNC) { NPP instance = (NPP)wParam; PluginAsyncCall* call = (PluginAsyncCall*)lParam; Plugin* plugin = FindPlugin(instance); TRACK_CPU_PER_TAB((plugin && plugin->GetDocument()) ? plugin->GetDocument()->GetWindow()->GetCPUUsageTracker() : NULL); if (plugin) { TRY call->function(call->userdata); CATCH_PLUGIN_EXCEPTION(plugin->SetException();) } g_thread_tools->Free(call); return OpStatus::OK; } OP_ASSERT(message_id == MSG_PLUGIN_CALL); OP_ASSERT(wParam); OP_ASSERT(!lParam); if (message_id == MSG_PLUGIN_CALL) { PluginMsgStruct *call = reinterpret_cast<PluginMsgStruct*>(wParam); Plugin* plugin = FindPlugin(call->id.instance, TRUE); TRACK_CPU_PER_TAB((plugin && plugin->GetDocument()) ? plugin->GetDocument()->GetWindow()->GetCPUUsageTracker() : NULL); if (plugin) { // check if exception handling is needed or if the plugin was deleted while locked if (plugin->IsFailure()) { HandleFailure(); if (call->msg_type != DESTROY) plugin = NULL; // ignore further handling of all other messages } } if (plugin && plugin->GetID() == call->id.pluginid) { if (plugin->GetLockEnabledState() || plugin->IsWindowProtected()) { unsigned int delay_ms = NS4P_DEFAULT_POST_DELAY; OP_DBG(("Plugin [%d] msg %d reposted (delay=%dms)", call->id.pluginid, call->msg_type, delay_ms)); g_main_message_handler->PostMessage(MSG_PLUGIN_CALL, wParam, 0, delay_ms); return OpStatus::OK; } NPError ret = NPERR_NO_ERROR; last_handled_msg = call; switch (call->msg_type) { case INIT: { #ifndef STATIC_NS4PLUGINS PluginLib *lib = pluginlibhandler ? pluginlibhandler->FindPluginLib(plugin->GetName()) : NULL; if (lib && !lib->Initialized()) { plugin->PushLockEnabledState(); OP_DBG(("Plugin [%d] INIT", call->id.pluginid)); ret = lib->Init(); OP_DBG(("Plugin [%d] INIT returned", call->id.pluginid)); plugin->PopLockEnabledState(); if (ret != NPERR_NO_ERROR) stat = plugin->SetFailure(FALSE); } #endif // !STATIC_NS4PLUGINS break; } case NEW: { FramesDocument* frames_doc = plugin->GetDocument(); PluginLib* lib = pluginlibhandler->FindPluginLib(plugin->GetName()); if (!lib || !lib->Initialized()) stat = plugin->SetFailure(FALSE); else #ifdef STATIC_NS4PLUGINS if (!plugin->GetPluginfuncs()->newp) // the static plugin was not initialized properly stat = plugin->SetFailure(FALSE); else #endif // STATIC_NS4PLUGINS if (frames_doc) { plugin->PushLockEnabledState(); OP_DBG(("Plugin [%d] NEW", call->id.pluginid)); NPSavedData* saved = plugin->GetSaved(); char** args8 = plugin->GetArgs8(); int16 argc = plugin->GetArgc(); plugin->SetLifeCycleState(Plugin::PRE_NEW); TRY ret = plugin->GetPluginfuncs()->newp( plugin->GetMimeType(), call->id.instance, plugin->GetMode(), argc, args8, &args8[argc], saved); CATCH_PLUGIN_EXCEPTION(ret = NPERR_GENERIC_ERROR;plugin->SetException();) OP_DBG(("Plugin [%d] NEW returned %d (%s)", call->id.pluginid, ret, ret ? "failure" : "success")); plugin->PopLockEnabledState(); if ((ret == NPERR_NO_ERROR #ifdef NS4P_IGNORE_LOAD_ERROR || ret == NPERR_MODULE_LOAD_FAILED_ERROR #endif // NS4P_IGNORE_LOAD_ERROR )) { // NOTE: CallNPP_NewProc might have run a nested message // loop and everything might have changed. The only // thing we know that we have is the Plugin object // and some things it referred to. plugin->SetLifeCycleState(Plugin::NEW_WITHOUT_WINDOW); #ifdef USE_PLUGIN_EVENT_API if (plugin->IsDisplayAllowed()) plugin->HandlePendingDisplay(); #else if (!plugin->IsWindowless()) plugin->SetWindow(); #endif // USE_PLUGIN_EVENT_API plugin->SetSaved(saved); // As initialised as it will be for now, resume scripts Resume(frames_doc, plugin->GetHtmlElement(), FALSE, TRUE); if (plugin->GetDocument() && plugin->GetHtmlElement()) plugin->GetHtmlElement()->MarkDirty(frames_doc); } else { // If any scripts were waiting for the plugin, tell them to stop waiting, the plugin is a dead fish Resume(frames_doc, plugin->GetHtmlElement(), TRUE, TRUE); stat = plugin->SetFailure(FALSE); } } break; } case DESTROY: { OP_ASSERT(g_in_synchronous_loop >= 0); if (g_in_synchronous_loop || plugin->GetContextMenuActive()) { // One of the plugins is in nested message loop and we don't dare destroying plugins // during that time (see DSK-312375). Destroying plugin that is in nested message loop // would be even worse so this branch caters for both cases. // Instead we're going to try destroying again in NS4P_DEFAULT_POST_DELAY milliseconds, // hoping that we're unnested by then. This is kind of a nasty busy loop because we // don't really know when we'll be able to unnest. OP_DBG(("Plugin [%d] DESTROY reposted because of synchronous loop", call->id.pluginid)); unsigned long delay_ms = NS4P_DEFAULT_POST_DELAY; g_main_message_handler->PostDelayedMessage(MSG_PLUGIN_CALL, wParam, 0, delay_ms); return stat; } else { plugin->Destroy(); OP_DELETE(plugin); plugin = NULL; } break; } case RESIZEMOVE: { if (plugin->IsInSynchronousLoop()) { OP_DBG(("Plugin [%d] RESIZEMOVE reposted because of synchronous loop", call->id.pluginid)); g_main_message_handler->PostMessage(message_id, wParam, lParam); return stat; } else { OP_DBG(("Plugin [%d] RESIZEMOVE", call->id.pluginid)); FramesDocument* frames_doc = plugin->GetDocument(); if (frames_doc && plugin->GetHtmlElement()) plugin->GetHtmlElement()->MarkDirty(frames_doc); } break; } case SETWINDOW: { if (plugin->IsInSynchronousLoop()) OP_DBG(("Plugin [%d] SETWINDOW ignored because plugin is in synchronous script handling", call->id.pluginid)); else if (plugin->GetLifeCycleState() != Plugin::FAILED_OR_TERMINATED) { OP_DBG(("Plugin [%d] SETWINDOW", call->id.pluginid)); #ifdef USE_PLUGIN_EVENT_API // A script waiting for plugin init might have waited all up to the // first SetWindow so now we need to resume it. if (plugin->GetDocument() && plugin->GetHtmlElement()) Resume(plugin->GetDocument(), plugin->GetHtmlElement(), FALSE, TRUE); #else plugin->PushLockEnabledState(); stat = plugin->SetWindow(); plugin->PopLockEnabledState(); #endif // USE_PLUGIN_EVENT_API } break; } case SETREADYFORSTREAMING: { OP_DBG(("Plugin [%d] SETREADYFORSTREAMING", call->id.pluginid)); if (plugin->GetLifeCycleState() != Plugin::FAILED_OR_TERMINATED) { if (plugin->GetLifeCycleState() < Plugin::RUNNING) { if (plugin->IsWindowless() && plugin->GetLifeCycleState() == Plugin::NEW_WITHOUT_WINDOW) { // Windowless plugins don't need SetWindow // to start streaming so skip past that state plugin->SetLifeCycleState(Plugin::WITH_WINDOW); } plugin->SetLifeCycleState(Plugin::RUNNING); } #ifdef USE_PLUGIN_EVENT_API if (plugin->IsDisplayAllowed()) plugin->HandlePendingDisplay(); #endif // USE_PLUGIN_EVENT_API } break; } case EMBEDSTREAMFAILED: case NEWSTREAM: case WRITEREADY: case WRITE: case STREAMASFILE: case DESTROYSTREAM: case URLNOTIFY: { if (plugin->GetLifeCycleState() <= Plugin::UNINITED) break; if (PluginStream* ps = plugin->FindStream(call->id.streamid)) { switch (call->msg_type) { case EMBEDSTREAMFAILED: { plugin->PushLockEnabledState(); OP_STATUS plugin_wants_all_streams = plugin->GetPluginWantsAllNetworkStreams(); plugin->PopLockEnabledState(); if (OpStatus::IsError(plugin_wants_all_streams)) stat = plugin_wants_all_streams; else if (plugin_wants_all_streams == OpBoolean::IS_FALSE) { ps->SetFinished(); ps->SetReason(NPRES_NETWORK_ERR); if (ps->GetNotify()) stat = ps->Notify(plugin); } else { ps->SetLastCalled(EMBEDSTREAMFAILED); stat = ps->New(plugin, NULL, NULL, 0); } break; } case NEWSTREAM: { // Check if the streaming should be delayed if (!ps->IsJSUrl() && // do not delay a javascript url (plugin->GetLifeCycleState() < Plugin::RUNNING || // check if the plugin is ready for streaming plugin->IsEqualUrlAlreadyStreaming(ps))) // check if an equal plugin stream is already streaming (first in list, stream first) { OP_DBG(("Plugin [%d] stream [%d] delay NEWSTREAM", call->id.pluginid, call->id.streamid)); // If the plug-in isn't ready for streaming yet, wait n/1000th of a second and try again. g_main_message_handler->RemoveDelayedMessage(message_id, wParam, lParam); #ifdef NS4P_POST_DELAYED_NEWSTREAM g_main_message_handler->PostDelayedMessage(message_id, wParam, lParam, NS4P_DEFAULT_POST_DELAY); #else g_main_message_handler->PostDelayedMessage(message_id, wParam, lParam, 10); #endif // NS4P_POST_DELAYED_NEWSTREAM return stat; } OP_DBG(("Plugin [%d] stream [%d] NEWSTREAM", call->id.pluginid, call->id.streamid)); plugin->PushLockEnabledState(); uint16 stype = ps->Type(); TRY ret = plugin->GetPluginfuncs()->newstream(call->id.instance, ps->GetMimeType(), ps->Stream(), FALSE, &stype); CATCH_PLUGIN_EXCEPTION(ret=NPERR_GENERIC_ERROR;plugin->SetException();) OP_DBG(("Plugin [%d] stream [%d] NEWSTREAM returned", call->id.pluginid, call->id.streamid)); plugin->PopLockEnabledState(); ps->SetLastCalled(call->msg_type); if (ret == NPERR_NO_ERROR) { ps->SetType(stype); ps->WriteReady(plugin); } else if (ret == NPERR_OUT_OF_MEMORY_ERROR) stat = OpStatus::ERR_NO_MEMORY; else plugin->DeleteStream(ps); break; } case WRITEREADY: { if ((ps->GetMsgFlushCounter() > call->msg_flush_counter) || ps->GetLastCalled() == DESTROYSTREAM) break; // Since the plugin has called NPN_RequestRead(), the streaming should be halted, positioned and restarted OP_DBG(("Plugin [%d] stream [%d] WRITEREADY", call->id.pluginid, call->id.streamid)); int32 write_ready = 0; #if NS4P_STARVE_WHILE_LOADING_RATE>0 if (!plugin->IsStarving()) #endif // NS4P_STARVE_WHILE_LOADING_RATE { plugin->PushLockEnabledState(); TRY write_ready = plugin->GetPluginfuncs()->writeready(call->id.instance, ps->Stream()); CATCH_PLUGIN_EXCEPTION(write_ready=0;plugin->SetException();) OP_DBG(("Plugin [%d] stream [%d] WRITEREADY returned", call->id.pluginid, call->id.streamid)); plugin->PopLockEnabledState(); #ifdef TCP_PAUSE_DOWNLOAD_EXTENSION URL url=ps->GetURL(); URL redir = url.GetAttribute(URL::KMovedToURL); if(!redir.IsEmpty()) redir.SetAttribute(URL::KPauseDownload, write_ready <= 0); else url.SetAttribute(URL::KPauseDownload, write_ready <= 0); #endif // TCP_PAUSE_DOWNLOAD_EXTENSION ps->SetLastCalled(call->msg_type); } ps->SetWriteReady(write_ready); ps->Write(plugin); break; } case WRITE: { if (ps->GetMsgFlushCounter() > call->msg_flush_counter || ps->GetLastCalled() == DESTROYSTREAM) break; // Since the plugin has called NPN_RequestRead(), the streaming should be halted, positioned and restarted plugin->PushLockEnabledState(); OP_DBG(("Plugin [%d] stream [%d] WRITE", call->id.pluginid, call->id.streamid)); int32 bytes_written = 0; TRY bytes_written = plugin->GetPluginfuncs()->write(call->id.instance, ps->Stream(), ps->GetOffset(), ps->GetBufLength(), (void*)ps->GetBuf()); CATCH_PLUGIN_EXCEPTION(bytes_written = -1; plugin->SetException();) OP_DBG(("Plugin [%d] stream [%d] WRITE returned", call->id.pluginid, call->id.streamid)); plugin->PopLockEnabledState(); ps->SetLastCalled(call->msg_type); ps->SetBytesWritten(static_cast<int32>(ps->GetBufLength()) < bytes_written ? ps->GetBufLength() : bytes_written); if (ps->GetBytesWritten() > 0) { OP_ASSERT(ps->GetURLDataDescr() || ps->GetJSEval()); if (ps->GetURLDataDescr()) { ps->GetURLDataDescr()->ConsumeData(static_cast<unsigned>(ps->GetBytesWritten())); if (!ps->GetMore() && (static_cast<unsigned long>(ps->GetBytesWritten()) >= ps->GetBytesLeft())) ps->SetFinished(); } else if (ps->GetJSEval() && (ps->GetOffset() + ps->GetBytesWritten() >= ps->GetJSEvalLength())) ps->SetFinished(); } else { ps->SetFinished(); if (ps->GetBytesWritten() < 0) // CallNPP_WriteProc was unsuccessful ps->SetReason(NPRES_USER_BREAK); } if (ps->IsFinished()) { if (ps->Type() == NP_NORMAL) // experimental fix for flash video problems seen on youtube when there // is a delay between the last NPP_Write() and NPP_DestroyStream(). // Fix is to call NPP_DestroyStream() directly instead of posting a message stat = DestroyStream(plugin, ps); else ps->StreamAsFile(plugin); } else ps->WriteReady(plugin); break; } case STREAMASFILE: { OP_DBG(("Plugin [%d] stream [%d] STREAMASFILE", call->id.pluginid, call->id.streamid)); #if defined(_LOCALHOST_SUPPORT_) || !defined(RAMCACHE_ONLY) OpString fname; OpString8 converted_fname; #ifdef NS4P_STREAM_FILE_WITH_EXTENSION_NAME if (OpStatus::IsSuccess(stat = fname.Set(ps->GetUrlCacheFileName()))) #else if (OpStatus::IsSuccess(stat = ps->GetURL().GetAttribute(URL::KFilePathName_L, fname, TRUE))) #endif // NS4P_STREAM_FILE_WITH_EXTENSION_NAME { stat = g_oplocale->ConvertToLocaleEncoding(&converted_fname, fname.CStr()); if (OpStatus::IsSuccess(stat)) { plugin->PushLockEnabledState(); TRY plugin->GetPluginfuncs()->asfile(call->id.instance, ps->Stream(), converted_fname.CStr()); CATCH_PLUGIN_EXCEPTION(plugin->SetException();) OP_DBG(("Plugin [%d] stream [%d] STREAMASFILE returned", call->id.pluginid, call->id.streamid)); plugin->PopLockEnabledState(); ps->SetLastCalled(call->msg_type); ps->Destroy(plugin); } } #endif // _LOCALHOST_SUPPORT_ || !RAMCACHE_ONLY break; } case DESTROYSTREAM: { stat = DestroyStream(plugin, ps); break; } case URLNOTIFY: { ps->CallProc(URLNOTIFY, plugin); ps->SetLastCalled(call->msg_type); plugin->DeleteStream(ps); break; } default: OP_DBG(("[%p] ERROR: MSG_PLUGIN_CALL was not handled for plugin [%d](unknown message type)", wParam, call->id.pluginid)); } } else OP_DBG(("[%p] ERROR: MSG_PLUGIN_CALL was not handled for plugin [%d](unknown stream id)", wParam, call->id.pluginid)); break; } default: { OP_DBG(("[%p] ERROR: MSG_PLUGIN_CALL was not handled for plugin [%d](unknown message type)", wParam, call->id.pluginid)); stat = OpStatus::ERR; } } } else OP_DBG(("[%p] ERROR: MSG_PLUGIN_CALL was not handled (unknown plugin id)", wParam)); call->Out(); OP_DELETE(call); } else { OP_DBG(("[%p] ERROR: not MSG_PLUGIN_CALL message type", wParam)); stat = OpStatus::ERR; } return stat; } OP_STATUS PluginHandler::PostPluginMessage(PluginMsgType msgty, NPP inst, int plugin_id, int stream_id, NPWindow* npwin, int msg_flush_counter, int delay /*= 0*/) { OP_ASSERT(g_main_message_handler); PluginMsgStruct *plugin_msg = OP_NEW(PluginMsgStruct, ()); if (!plugin_msg) return OpStatus::ERR_NO_MEMORY; plugin_msg->msg_type = msgty; plugin_msg->id.instance = inst; plugin_msg->id.pluginid = plugin_id; plugin_msg->id.streamid = stream_id; plugin_msg->id.npwin = npwin; plugin_msg->msg_flush_counter = msg_flush_counter; plugin_msg->Into(&messages); if (delay) g_main_message_handler->PostDelayedMessage(MSG_PLUGIN_CALL, reinterpret_cast<MH_PARAM_1>(plugin_msg), 0, delay); else g_main_message_handler->PostMessage(MSG_PLUGIN_CALL, reinterpret_cast<MH_PARAM_1>(plugin_msg), 0); return OpStatus::OK; } BOOL PluginHandler::HasPendingPluginMessage(PluginMsgType msgty, NPP inst, int plugin_id, int stream_id, NPWindow* npwin, int msg_flush_counter) { PluginMsgStruct *msg = (PluginMsgStruct *)messages.First(); while(msg) { if (msg != last_handled_msg && msg->msg_type == msgty && msg->id.instance == inst && msg->id.pluginid == plugin_id && msg->id.streamid == stream_id && msg->id.npwin == npwin && msg->msg_flush_counter == msg_flush_counter) return TRUE; msg = (PluginMsgStruct *)msg->Suc(); } return FALSE; } #ifdef NS4P_SUPPORT_PROXY_PLUGIN OP_STATUS PluginHandler::LoadStaticLib() { #if defined STATIC_NS4PLUGINS && defined OPSYSTEMINFO_STATIC_PLUGIN // Get the spec for the proxy plugin : StaticPlugin plugin_spec; RETURN_IF_ERROR(g_op_system_info->GetStaticPlugin(plugin_spec)); // Add it to the list : RETURN_IF_ERROR(pluginlibhandler->AddStaticLib(plugin_spec.plugin_name.CStr(), plugin_spec.init_function, plugin_spec.shutdown_function)); #endif // STATIC_NS4PLUGINS && OPSYSTEMINFO_STATIC_PLUGIN return OpStatus::OK; } #endif // NS4P_SUPPORT_PROXY_PLUGIN OP_STATUS PluginHandler::HandleFailure() { Plugin* plugin = static_cast<Plugin*>(plugin_list.First()); while (plugin) { FramesDocument* frames_doc = plugin->GetDocument(); if (plugin->IsFailure() && frames_doc) { if (HTML_Element* elm = plugin->GetHtmlElement()) { Box* box = elm->GetLayoutBox(); if (box && box->GetContent() && box->GetContent()->IsEmbed()) static_cast<EmbedContent*>(box->GetContent())->SetRemoved(); elm->DisableContent(frames_doc); } frames_doc->GetDocManager()->EndProgressDisplay(TRUE); plugin = NULL; } else plugin = plugin->Suc(); } return OpStatus::OK; } void* PluginHandler::FindPluginHandlerRestartObject(FramesDocument* frames_doc, HTML_Element* element) { PluginHandlerRestartObject *p = NULL; if (!restart_object_list.Empty()) { p = restart_object_list.First(); while (p && p->html_element != element) { p = p->Suc(); } } OP_ASSERT(!p || p->frames_doc == frames_doc); return static_cast<void*>(p); } BOOL PluginHandler::IsSuspended(FramesDocument* frames_doc, HTML_Element* element) { /* Check if this element's scripting has been suspended */ PluginHandlerRestartObject *p = static_cast<PluginHandlerRestartObject*>(FindPluginHandlerRestartObject(frames_doc, element)); return p && !p->been_blocked_but_plugin_failed; } OP_STATUS PluginHandler::Suspend(FramesDocument* frames_doc, HTML_Element* element, ES_Runtime* runtime, ES_Value* value, BOOL wait_for_full_plugin_init) { OP_NEW_DBG("PluginHandler::Suspend", "ns4p"); OP_ASSERT(frames_doc); OP_ASSERT(element); OP_ASSERT(frames_doc->GetLogicalDocument()); OP_ASSERT(frames_doc->GetLogicalDocument()->GetRoot()); OP_ASSERT(frames_doc->GetLogicalDocument()->GetRoot()->IsAncestorOf(element)); OP_DBG(("Asked to suspend waiting for element %p (wait_for_full_plugin_init = %d)", element, wait_for_full_plugin_init)); /* Initially check if this element's scripting has been suspended and then resumed because of an error */ PluginHandlerRestartObject *p = static_cast<PluginHandlerRestartObject*>(FindPluginHandlerRestartObject(frames_doc, element)); if (p && p->been_blocked_but_plugin_failed) return OpStatus::ERR; /* When resuming without errors, the PluginHandlerRestartObject will be removed from restart_object_list. Scripts can be suspended, resumed and then suspended again, for the same element. There can also be several scripts (from different documents) blocked on the same plugin. */ /* Suspend this element's scripting */ BOOL create_new_p = !p; if (create_new_p) { p = OP_NEW(PluginHandlerRestartObject, ()); if (!p) return OpStatus::ERR_NO_MEMORY; p->html_element = element; p->frames_doc = frames_doc; p->been_blocked_but_plugin_failed = FALSE; p->restart_object_list = NULL; } PluginRestartObject* restart_object = NULL; if (OpStatus::IsError(frames_doc->AddBlockedPlugin(element))) { if (create_new_p) OP_DELETE(p); return OpStatus::ERR_NO_MEMORY; } OP_STATUS stat; if (OpStatus::IsError(stat = PluginRestartObject::Suspend(restart_object, runtime))) { if (create_new_p) OP_DELETE(p); // We will leave it in the doc list, in case there are other scripts also blocked // at that plugin. return stat; } restart_object->type = wait_for_full_plugin_init ? PluginRestartObject::PLUGIN_RESTART_AFTER_INIT : PluginRestartObject::PLUGIN_RESTART; restart_object->next_restart_object = p->restart_object_list; p->restart_object_list = restart_object; if (create_new_p) p->Into(&restart_object_list); value->value.object = *restart_object; value->type = VALUE_OBJECT; return OpStatus::OK; } void PluginHandler::Resume(FramesDocument* frames_doc, HTML_Element *element, BOOL plugin_failed, BOOL include_threads_waiting_for_init) { OP_NEW_DBG("PluginHandler::Resume", "ns4p"); OP_DBG(("Asked to resume plugin blocked script for element %p (plugin_failed = %d, include_threads_waiting_for_init = %d)", element, plugin_failed, include_threads_waiting_for_init)); PluginHandlerRestartObject *p = static_cast<PluginHandlerRestartObject*>(FindPluginHandlerRestartObject(frames_doc, element)); if (p && !p->been_blocked_but_plugin_failed) { PluginRestartObject** prev_pointer = &p->restart_object_list; while (*prev_pointer) { PluginRestartObject* restart_object = *prev_pointer; BOOL resume = plugin_failed || include_threads_waiting_for_init || restart_object->type != PluginRestartObject::PLUGIN_RESTART_AFTER_INIT; if (resume) { restart_object->Resume(); // Unlink *prev_pointer = restart_object->next_restart_object; } else { // Leave in list prev_pointer = &restart_object->next_restart_object; } } BOOL some_thread_still_blocked = p->restart_object_list != NULL; if (!some_thread_still_blocked) { if (plugin_failed) { p->been_blocked_but_plugin_failed = TRUE; p->restart_object_list = NULL; } else { p->Out(); OP_DELETE(p); } if (frames_doc) frames_doc->RemoveBlockedPlugin(element); } } else { OP_ASSERT(!(p && p->restart_object_list)); } } BOOL PluginHandler::IsPluginStartupRestartObject(ES_Object* object) { OP_ASSERT(object); if (IsSupportedRestartObject(object)) { PluginRestartObject *restart_object = static_cast<PluginRestartObject*>(ES_Runtime::GetHostObject(object)); return (restart_object->type == PluginRestartObject::PLUGIN_RESTART || restart_object->type == PluginRestartObject::PLUGIN_RESTART_AFTER_INIT); } return FALSE; } BOOL PluginHandler::IsSupportedRestartObject(ES_Object* object) { OP_ASSERT(object); EcmaScript_Object* host_object = ES_Runtime::GetHostObject(object); return host_object && host_object->IsA(NS4_TYPE_RESTART_OBJECT); } OP_STATUS PluginHandler::DestroyStream(Plugin* plugin, PluginStream* ps) { if (ps->GetURL().Status(TRUE) == URL_LOADED) { // cache request if (ps->GetURL().PrepareForViewing(TRUE) == MSG_OOM_CLEANUP) return OpStatus::ERR_NO_MEMORY; } NPError ret = ps->CallProc(DESTROYSTREAM, plugin); ps->SetLastCalled(DESTROYSTREAM); if (ret == NPERR_OUT_OF_MEMORY_ERROR) return OpStatus::ERR_NO_MEMORY; if (ps->GetNotify()) ps->Notify(plugin); else plugin->DeleteStream(ps); return OpStatus::OK; } void PluginHandler::DestroyPluginRestartObject(PluginRestartObject* object) { PluginHandlerRestartObject* p = restart_object_list.First(); while (p) { PluginRestartObject* restart_object = p->restart_object_list; while (restart_object && restart_object != object) restart_object = restart_object->next_restart_object; if (restart_object) break; p = p->Suc(); } if (p) { if (p->frames_doc) p->frames_doc->RemoveBlockedPlugin(p->html_element); p->Out(); OP_DELETE(p); } } void PluginHandler::DestroyAllLoadingStreams() { Plugin* plugin = static_cast<Plugin*>(plugin_list.First()); while (plugin) { plugin->DestroyAllLoadingStreams(); plugin = static_cast<Plugin*>(plugin->Suc()); } } uint32_t PluginHandler::ScheduleTimer(NPP instance, uint32_t interval, BOOL repeat, void (*timerFunc)(NPP npp, uint32_t timerID)) { OP_NEW_DBG("PluginHandler::ScheduleTimer", "plugintimer"); PluginTimer* pluginTimer = OP_NEW(PluginTimer, ()); if (!pluginTimer) return 0; pluginTimer->instance = instance; pluginTimer->timerID = m_nextTimerID++; pluginTimer->interval = interval; pluginTimer->repeat = repeat; pluginTimer->timerFunc = timerFunc; pluginTimer->Into(&m_timer_list); pluginTimer->SetTimerListener(this); pluginTimer->Start(interval); OP_DBG(("pluginTimer[%p], instance[%p], timerID[%d], interval[%d], repeat[%d], f[%p]", pluginTimer, pluginTimer->instance, pluginTimer->timerID, pluginTimer->interval, pluginTimer->repeat, pluginTimer->timerFunc)); return pluginTimer->timerID; } void PluginHandler::UnscheduleTimer(uint32_t timerID) { OP_NEW_DBG("PluginHandler::UnscheduleTimer","plugintimer"); PluginTimer* pluginTimer = m_timer_list.First(); for (;pluginTimer; pluginTimer=pluginTimer->Suc()) { if (pluginTimer->timerID == timerID) { OP_DBG(("pluginTimer[%p], instance[%p], timerID[%d], interval[%d], repeat[%d], f[%p], unscheduled[%d], running[%d]", pluginTimer, pluginTimer->instance, pluginTimer->timerID, pluginTimer->interval, pluginTimer->repeat, pluginTimer->timerFunc, pluginTimer->is_unscheduled, pluginTimer->is_running)); pluginTimer->is_unscheduled = TRUE; break; } } } void PluginHandler::UnscheduleAllTimers(NPP instance) { OP_NEW_DBG("PluginHandler::UnscheduleAllTimers", "plugintimer"); OP_DBG(("instance[%p]", instance)); PluginTimer* pluginTimer = m_timer_list.First(); for (;pluginTimer;pluginTimer=pluginTimer->Suc()) { if (pluginTimer->instance == instance) pluginTimer->is_unscheduled = TRUE; } } void PluginHandler::OnTimeOut(OpTimer* timer) { OP_NEW_DBG("PluginHandler::OnTimeOut", "plugintimer"); PluginTimer* pluginTimer = static_cast<PluginTimer*>(timer); OP_ASSERT(pluginTimer); PluginTimer* it = m_timer_list.First(); while (it && it!=pluginTimer) it=it->Suc(); if (it!=pluginTimer) return; // No recursion allowed if (pluginTimer->is_running) return; if (!FindPlugin(pluginTimer->instance)) pluginTimer->is_unscheduled = TRUE; if (!pluginTimer->is_unscheduled) { if (pluginTimer->repeat) pluginTimer->Start(pluginTimer->interval); pluginTimer->is_running = TRUE; pluginTimer->timerFunc(pluginTimer->instance, pluginTimer->timerID); pluginTimer->is_running = FALSE; } if (!pluginTimer->repeat || pluginTimer->is_unscheduled) { OP_DBG(("Deleting: pluginTimer[%p], instance[%p], timerID[%d], interval[%d], repeat[%d], f[%p], unscheduled[%d], running[%d]", pluginTimer, pluginTimer->instance, pluginTimer->timerID, pluginTimer->interval, pluginTimer->repeat, pluginTimer->timerFunc, pluginTimer->is_unscheduled, pluginTimer->is_running)); if (pluginTimer->IsStarted()) pluginTimer->Stop(); pluginTimer->Out(); OP_DELETE(pluginTimer); } } void PluginHandler::OnLibraryError(const uni_char* library_name, const OpMessageAddress& address) { for (Plugin* p = static_cast<Plugin*>(plugin_list.First()); p; p = static_cast<Plugin*>(p->Suc())) if (!uni_strcmp(p->GetName(), library_name)) { p->SetFailure(TRUE, address); Destroy(p); } } #ifdef NS4P_COMPONENT_PLUGINS OP_STATUS PluginHandler::WhitelistChannel(OpChannel* channel) { return m_channel_whitelist.RegisterAddress(channel->GetAddress()); } void PluginHandler::DelistChannel(const OpMessageAddress& channel_address) { m_channel_whitelist.DeregisterAddress(channel_address); } PluginWhitelist::PluginWhitelist() : m_component_address(g_opera->GetAddress()) , m_scripting_context(0) { } BOOL PluginWhitelist::IsMember(const OpTypedMessage* message) const { const OpMessageAddress& address = message->GetDst(); /* The purpose of this filter is to block all non-plug-in-related messages to one * specific component. If the message is addressed to another component, then we * let the message pass. */ if (address.cm != m_component_address.cm || address.co != m_component_address.co) return TRUE; /* If the scripting context is restricted, and this is a script request made in * a larger context, reject it. See PluginHandler::PushScriptingContext(). */ #define REJECT_IF_NOT_IN_CONTEXT(type) \ case type::Type: \ { \ type* m = type::Cast(message); \ if (!m->HasContext() || m->GetContext() < m_scripting_context) \ return FALSE; \ break; \ } if (m_scripting_context) switch (message->GetType()) { REJECT_IF_NOT_IN_CONTEXT(OpPluginEvaluateMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginHasMethodMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginHasPropertyMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginGetPropertyMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginSetPropertyMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginRemovePropertyMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginInvokeMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginInvokeDefaultMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginObjectEnumerateMessage); REJECT_IF_NOT_IN_CONTEXT(OpPluginObjectConstructMessage); } /* Finally, check if the destination is whitelisted. */ return m_whitelist.Count(address) > 0 ? TRUE : FALSE; } OP_STATUS PluginWhitelist::RegisterAddress(const OpMessageAddress& address) { Whitelist::Iterator found = m_whitelist.Find(address); if (found != m_whitelist.End()) { found->second++; return OpStatus::OK; } return m_whitelist.Insert(address, 1); } void PluginWhitelist::DeregisterAddress(const OpMessageAddress& address) { Whitelist::Iterator found = m_whitelist.Find(address); if (found != m_whitelist.End()) { if (found->second > 1) /* Can only fail if the address is not present, and we've established that it is. */ found->second--; else m_whitelist.Erase(address); } } /* virtual */ OP_STATUS PluginSyncMessenger::SendMessage(OpTypedMessage* message, bool allow_nesting /* = false */, unsigned int timeout /* = 0 */, int context /* = 0 */) { if (!m_peer) { OP_DELETE(message); return OpStatus::ERR_NO_MEMORY; } if (!timeout) { /* Experimental. All synchronous plug-in communication ought to have a timeout, since we * have little control over the code run on the wrapper side, and its nesting has caused * very complicated and brittle platform PIs. */ timeout = g_pcapp->GetIntegerPref(PrefsCollectionApp::PluginSyncTimeout) * 1000; } if (!allow_nesting) { PluginWhitelist* whitelist = static_cast<PluginWhitelist*>(g_pluginhandler->GetChannelWhitelist()); OpMessageAddress address = m_peer->GetAddress(); PluginChannelWhitelistToggle enabled(true); RETURN_IF_ERROR(whitelist->RegisterAddress(address)); int old_scripting_context = whitelist->GetScriptingContext(); whitelist->SetScriptingContext(context); OP_STATUS s = OpSyncMessenger::ExchangeMessages(message, timeout, OpComponentPlatform::PROCESS_IPC_MESSAGES); whitelist->SetScriptingContext(old_scripting_context); whitelist->DeregisterAddress(address); return s; } return OpSyncMessenger::SendMessage(message, true, timeout); } PluginChannelWhitelistToggle::PluginChannelWhitelistToggle(bool enable) { OpTypedMessageSelection* whitelist = g_pluginhandler->GetChannelWhitelist(); m_whitelist_was_enabled = g_component_manager->HasMessageFilter(whitelist); if (m_whitelist_was_enabled != enable) { if (enable) g_component_manager->AddMessageFilter(whitelist); else g_component_manager->RemoveMessageFilter(whitelist); } } PluginChannelWhitelistToggle::~PluginChannelWhitelistToggle() { OpTypedMessageSelection* whitelist = g_pluginhandler->GetChannelWhitelist(); bool whitelist_is_enabled = g_component_manager->HasMessageFilter(whitelist); if (m_whitelist_was_enabled != whitelist_is_enabled) { if (m_whitelist_was_enabled) g_component_manager->AddMessageFilter(whitelist); else g_component_manager->RemoveMessageFilter(whitelist); } } #endif // NS4P_COMPONENT_PLUGINS #endif // _PLUGIN_SUPPORT_
#include <iostream.h> #include <conio.h> void main() { clrscr(); int a,b,i; cout <<"\n\nEnter the starting range of loop: "; cin >>a; cout <<"\n\nEnter the Ending range of loop: "; cin >>b; for (i=a; i<=b; i++) cout <<endl << i <<"\n"; getch(); }
//--------------------------------------------------------- // // Project: dada // Module: geometry // File: Transform3f.cpp // Author: Viacheslav Pryshchepa // //--------------------------------------------------------- #include "dada/geometry/Transform3f.h" #include "dada/geometry/Matrix3fUtils.h" #include "dada/geometry/Vector3fUtils.h" #include <cmath> namespace dada { Transform3f::Transform3f() : m_m(), m_v() { } Transform3f::Transform3f(float val) : m_m(val), m_v(0.0f) { } void Transform3f::setIdentity() { m_m.set(1.0f); m_v.set(0.0f); } void Transform3f::setTranslate(const Vector3f& dv) { m_m.set(1.0f); m_v = dv; } void Transform3f::setScale(const Vector3f& factor) { m_m.set(factor.x(), factor.y(), factor.z()); m_v.set(0.0f); } void Transform3f::setRotateX(float angle) { genRotateX(m_m, angle); m_v.set(0.0f); } void Transform3f::setRotateY(float angle) { genRotateY(m_m, angle); m_v.set(0.0f); } void Transform3f::setRotateZ(float angle) { genRotateZ(m_m, angle); m_v.set(0.0f); } void Transform3f::setMirrorY() { m_m[4] = -1.0f; } void Transform3f::translate(const Vector3f& dv) { Vector3f res; dot(res, m_m, dv); m_v += res; } void Transform3f::scale(const Vector3f& factor) { m_m[0] *= factor.x(); m_m[1] *= factor.x(); m_m[2] *= factor.x(); m_m[3] *= factor.y(); m_m[4] *= factor.y(); m_m[5] *= factor.y(); m_m[6] *= factor.z(); m_m[7] *= factor.z(); m_m[8] *= factor.z(); } void Transform3f::rotateX(float angle) { Matrix3f r, res; genRotateX(r, angle); dot(res, m_m, r); m_m = res; } void Transform3f::rotateY(float angle) { Matrix3f r, res; genRotateY(r, angle); dot(res, m_m, r); m_m = res; } void Transform3f::rotateZ(float angle) { Matrix3f r, res; genRotateZ(r, angle); dot(res, m_m, r); m_m = res; } void Transform3f::mirrorY() { m_m[4] = -m_m[4]; } void Transform3f::lookAt(const Vector3f& eye, const Vector3f& center, const Vector3f& up) { //Vector3f f(center); //f -= eye; Vector3f f(eye); f -= center; normalize(f); Vector3f s; cross(s, f, up); //Vector3f s_n(s); //s_n.normalize(); //Vector3f u; //cross(u, s_n, f); Matrix3f m, res; m[0] = s[0]; m[1] = up[0]; //u[0]; m[2] = -f[0]; m[3] = s[1]; m[4] = up[1]; //u[1]; m[5] = -f[1]; m[6] = s[2]; m[7] = up[2]; // u[2]; m[8] = -f[2]; dot(res, m_m, m); m_m = res; Vector3f dv(eye); negate(dv); translate(dv); //dot(m_v, m_m, dv); } void Transform3f::genMatrix(Matrix4f& res) const { res[ 0] = m_m[0]; res[ 1] = m_m[1]; res[ 2] = m_m[2]; res[ 3] = 0.0f; res[ 4] = m_m[3]; res[ 5] = m_m[4]; res[ 6] = m_m[5]; res[ 7] = 0.0f; res[ 8] = m_m[6]; res[ 9] = m_m[7]; res[10] = m_m[8]; res[11] = 0.0f; res[12] = m_v[0]; res[13] = m_v[1]; res[14] = m_v[2]; res[15] = 1.0f; } void Transform3f::genRotateX(Matrix3f& res, float angle) { const float cosine = cos(angle); const float sine = sin(angle); res[0] = 1.0f; res[1] = 0.0f; res[2] = 0.0f; res[3] = 0.0f; res[4] = cosine; res[5] = sine; res[6] = 0.0f; res[7] = -sine; res[8] = cosine; } void Transform3f::genRotateY(Matrix3f& res, float angle) { const float cosine = cos(angle); const float sine = sin(angle); res[0] = cosine; res[1] = 0.0f; res[2] = -sine; res[3] = 0.0f; res[4] = 1.0f; res[5] = 0.0f; res[6] = sine; res[7] = 0.0f; res[8] = cosine; } void Transform3f::genRotateZ(Matrix3f& res, float angle) { const float cosine = cos(angle); const float sine = sin(angle); res[0] = cosine; res[1] = sine; res[2] = 0.0f; res[3] = -sine; res[4] = cosine; res[5] = 0.0f; res[6] = 0.0f; res[7] = 0.0f; res[8] = 1.0f; } void Transform3f::genOrtho(Matrix4f& res, float l, float r, float b, float t, float n, float f) { const float kx = 1.0f / (r - l); const float ky = 1.0f / (t - b); const float kz = 1.0f / (f - n); res[ 0] = kx + kx; res[ 1] = 0.0f; res[ 2] = 0.0f; res[ 3] = 0.0f; res[ 4] = 0.0f; res[ 5] = ky + ky; res[ 6] = 0.0f; res[ 7] = 0.0f; res[ 8] = 0.0f; res[ 9] = 0.0f; res[10] = kz + kz; res[11] = 0.0f; res[12] = -(r + l) * kx; res[13] = -(t + b) * ky; res[14] = -(f + n) * kz; res[15] = 1.0f; } void Transform3f::genFrustum(Matrix4f& res, float l, float r, float b, float t, float n, float f) { const float n2 = n + n; const float kx = 1.0f / (r - l); const float ky = 1.0f / (t - b); const float kz = 1.0f / (f - n); res[ 0] = n2 * kx; res[ 1] = 0.0f; res[ 2] = 0.0f; res[ 3] = 0.0f; res[ 4] = 0.0f; res[ 5] = n2 * ky; res[ 6] = 0.0f; res[ 7] = 0.0f; res[ 8] = -(r + l) * kx; res[ 9] = -(t + b) * ky; res[10] = (f + n) * kz; res[11] = 1.0f; res[12] = 0.0f; res[13] = 0.0f; res[14] = -n2 * f * kz; res[15] = 0.0f; } void Transform3f::genPerspective(Matrix4f& res, float fovy, float aspect, float n, float f) { const float k = 1.0f / tan(0.5f * fovy); const float kz = 1.0f / (f - n); res[ 0] = k / aspect; res[ 1] = 0.0f; res[ 2] = 0.0f; res[ 3] = 0.0f; res[ 4] = 0.0f; res[ 5] = k; res[ 6] = 0.0f; res[ 7] = 0.0f; res[ 8] = 0.0f; res[ 9] = 0.0f; res[10] = (f + n) * kz; res[11] = 1.0f; res[12] = 0.0f; res[13] = 0.0f; res[14] = -2.0f * n * f * kz; res[15] = 0.0f; } void dot(Transform3f& res, const Transform3f& a, const Transform3f& b) { dot(res.m_m, a.m_m, b.m_m); Vector3f v; dot(v, a.m_m, b.m_v); v += a.m_v; res.m_v = v; } } // dada
/******************************************************************************* Based on segment-lcd-with-ht1622 from anxzhu (2016-2018) Follow of MartyMacGyver / LCD_HT1622_16SegLcd work (https://github.com/MartyMacGyver/LCD_HT1622_16SegLcd) This file is part of the HT1622 arduino library, and thus under the MIT license. More info on the project and the license conditions on : https://github.com/radenko/ht1622-arduino Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************/ #include <Arduino.h> #include "HT1622.h" //#define SERIAL_DEBUG Serial void HT1622::changeBits(uint16_t src, uint16_t &dst, uint8_t srcBit, uint8_t dstBit) { int srcMask = 1 << srcBit; int dstMask = 1 << dstBit; if (src & srcMask) { dst |= dstMask; } else { dst &= (~dstMask); } } HT1622::HT1622():_cs_p(-1), _wr_p(-1), _data_p(-1), _backlight_p(-1) { } HT1622::HT1622(int cs, int wr, int data, int backlight):_cs_p(cs), _wr_p(wr), _data_p(data), _backlight_p(backlight) { } void HT1622::begin(SPIClass &spi, int cs, int backlight) { this->_spi = &spi; this->_cs_p = cs; this->_backlight_p = backlight; if (this->_cs_p != -1) { pinMode(this->_cs_p, OUTPUT); } if (this->_backlight_p != -1) { pinMode(this->_backlight_p, OUTPUT); } delay(50); _backlight_en=true; config(); } void HT1622::begin(int cs, int wr, int data, int backlight) { this->_cs_p = cs; this->_wr_p = wr; this->_data_p = data; this->_backlight_p = backlight; // pinMode(this->_cs_p, OUTPUT); pinMode(this->_wr_p, OUTPUT); pinMode(this->_data_p, OUTPUT); if (this->_cs_p != -1) { pinMode(this->_cs_p, OUTPUT); } if (this->_backlight_p != -1) { pinMode(this->_backlight_p, OUTPUT); } // pinMode(this->_backlight_p, OUTPUT); delay(50); _backlight_en=true; config(); } void HT1622::backlight() { if (_backlight_en) digitalWrite(_backlight_p, HIGH); delay(1); } void HT1622::noBacklight() { if(_backlight_en) digitalWrite(_backlight_p, LOW); delay(1); } void HT1622::beginTransfer() { digitalWrite(_cs_p, LOW); uint8_t _outBits = 0; uint8_t _outBuff = 0; } void HT1622::endTransfer() { if (_outBits!=0) { this->sendBitsSpi(0, 8 - this->_outBits); uint8_t _outBits = 0; uint8_t _outBuff = 0; } digitalWrite(_cs_p, HIGH); delay(1); } void HT1622::clear() { this->seekLeft(); this->allSegments(0); if (this->digitBuffer != NULL) { memset(this->digitBuffer, 0, this->digitBufferSize * sizeof(this->digitBuffer[0])); } } void HT1622::sendBitsSpi(uint16_t data, uint8_t bits, boolean LSB_FIRST) { while (bits) { int res = 8 - _outBits; if (res > bits) { res = bits; } _outBuff = _outBuff << res; _outBuff |= data >> (bits - res); _outBits += res; bits -= res; data = data & (0xFFFF >> (16 - bits)); if (_outBits == 8) { //SERIAL_DEBUG.print("--Writing bits: "); //SERIAL_DEBUG.println(this->_outBuff, BIN); this->_spi->transfer(this->_outBuff); _outBuff = 0; _outBits = 0; } } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Send up to 16 bits, MSB (default) or LSB //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void HT1622::sendBits(uint16_t data, uint8_t bits, boolean LSB_FIRST) { if (this->_spi != NULL) { this->sendBitsSpi(data, bits, LSB_FIRST); } else { uint16_t mask; mask = (LSB_FIRST ? 1 : 1 << bits - 1); //printf("Writing %d bits of 0x%04x with mask 0x%04x in %s\n", bits, data, mask, LSB_FIRST?"LSB":"MSB"); //SERIAL_DEBUG.print("++Writing bits: "); for (uint8_t i = bits; i > 0; i--) { //SERIAL_DEBUG.print(data & mask ? 1 : 0); digitalWrite(this->_wr_p, LOW); delayMicroseconds(HT1622_WRITE_DELAY_USECS); data & mask ? digitalWrite(this->_data_p, HIGH) : digitalWrite(this->_data_p, LOW); delayMicroseconds(HT1622_WRITE_DELAY_USECS); digitalWrite(this->_wr_p, HIGH); delayMicroseconds(HT1622_WRITE_DELAY_USECS); LSB_FIRST ? data >>= 1 : data <<= 1; } //SERIAL_DEBUG.println(); delayMicroseconds(HT1622_WRITE_DELAY_USECS); } } void HT1622::wrCommand(unsigned char cmd) { //100 this->beginTransfer(); this->sendBits(0b100, 3); this->sendBits(cmd, 8); this->sendBits(1, 1); //this->sendBits(0, 4); this->endTransfer(); } void HT1622::config() { wrCommand(CMD_SYS_EN); wrCommand(CMD_RC_INT); this->clear(); wrCommand(CMD_LCD_ON); // Should turn it on delay(50); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void HT1622::allSegments(uint8_t state) { const int SegDelay = 10; for (uint8_t addr = 0x00; addr < 0x3F; addr++) { wrData(addr, (state ? 0xff : 0x00)); } delay(SegDelay); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void HT1622::wrData(uint8_t addr, uint16_t sdata, uint8_t bits) { // SERIAL_DEBUG.print("Writing data "); // SERIAL_DEBUG.print(sdata); // SERIAL_DEBUG.print(" to "); // SERIAL_DEBUG.println(addr); this->beginTransfer(); this->sendBits(0b101, 3); this->sendBits(addr, 6); this->sendBits(sdata, bits, HT1622_MSB_FORMAT); //this->sendBits(0, 8 - ((3+6+bits) % 8)); this->endTransfer(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void HT1622::wrBuffer() { // SERIAL_DEBUG.print("Writing buffer"); this->beginTransfer(); this->sendBits(0b101, 3); this->sendBits(0, 6); for (int i=this->digitBufferSize - 1; i >= 0; i--) { this->sendBits(this->digitBuffer[i], 16); } this->endTransfer(); } void HT1622::writeSegment(const uint8_t nr, const char value) { uint16_t data; if (value < 0x20) { data = this->_charset[0]; } else if (value >= (this->_charsetLen + 0x20)) { data = this->_charset[this->_charsetLen - 1]; } else { data = this->_charset[value - 0x20]; } if (this->digitBuffer != NULL) { this->digitBuffer[nr] = this->_charAdapter == NULL ? data : this->_charAdapter(data); if (!this->noRedraw) { this->wrBuffer(); } } else { wrData(_digitAddr[nr], (this->_charAdapter == NULL ? data : this->_charAdapter(data)), 16); } } void HT1622::setDigitAddr(const uint8_t *digitAddr, const uint8_t digitAddrCount) { this->_digitAddr = digitAddr; this->_digitAddrCount = digitAddrCount; this->seekLeft(); } void HT1622::setDigitBuff(uint16_t *buffer, const uint8_t bufferSize) { this->digitBuffer = buffer; this->digitBufferSize = bufferSize; } void HT1622::setDigitBuffClear(uint16_t *buffer, const uint8_t bufferSize) { this->setDigitBuff(buffer, bufferSize); memset(this->digitBuffer, 0, this->digitBufferSize * sizeof(buffer[0])); } void HT1622::seekLeft() { this->charPos = 0; } void HT1622::seekRight() { this->charPos = this->_digitAddrCount - 1; } void HT1622::setCharAdapter(uint16_t (*charAdapter)(uint16_t character)) { this->_charAdapter = charAdapter; } void HT1622::setCharset(const uint8_t *digitAddr, const uint8_t digitAddrCount) { this->_digitAddr = digitAddr; this->_digitAddrCount = digitAddrCount; } size_t HT1622::write(unsigned char ch) { this->writeSegment(this->charPos, ch); this->charPos++; if (this->charPos >= this->_digitAddrCount) { this->charPos = 0; } }
//hung.nguyen@student.tut.fi - student id: 272585 //sanghun.2.lee@student.tut.fi - student id: 272571 #ifndef SPLITTER_HH #define SPLITTER_HH #include <vector> #include <string> using namespace std; vector<string> split(const string& stringToSplit_,char regex); #endif // SPLITTER_HH
//=========================================================================== //! @file shadow_map.cpp //! @brief シャドウマップ管理 //=========================================================================== //--------------------------------------------------------------------------- //! 初期化 //--------------------------------------------------------------------------- bool ShadowMap::initialize(s32 resolution) { resolution_ = resolution; //============================================================= // デプステクスチャの作成 //============================================================= depthTexture_.reset(gpu::createRenderTarget(resolution, resolution, DXGI_FORMAT_D32_FLOAT)); if(!depthTexture_) return false; //gpu::setTexture(10, depthTexture_); return true; } //--------------------------------------------------------------------------- //! 解放 //--------------------------------------------------------------------------- void ShadowMap::finalize() { depthTexture_.reset(); } //--------------------------------------------------------------------------- //! シャドウパスの開始 //--------------------------------------------------------------------------- void ShadowMap::begin(const Light& light) { gpu::setTexture(10, nullptr); // シャドウデプスバッファのクリア device::D3DContext()->ClearDepthStencilView(depthTexture_->getD3DDsv(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); // デプスバッファの設定(倍速Zモード) // 描画先をデプステクスチャに設定 gpu::setRenderTarget(nullptr, depthTexture_); const f32 range = 30.0f; // 撮影の幅(±の範囲) const f32 limitDistance = 100.0f; // 影の遠クリップ面 // 光源カメラの設定 const Matrix matLightView = light.getMatView(); const Matrix matLightProj = Matrix::scale(Vector3(0.5f / range, 0.5f / range, 1.0f / limitDistance * -1.0f)); // 影用定数バッファ更新 auto CBShadow = cbShadow_.begin(); { CBShadow->matLightView_ = matLightView; CBShadow->matLightProj_ = matLightProj; } cbShadow_.end(); gpu::setConstantBuffer(8, cbShadow_); } //--------------------------------------------------------------------------- //! シャドウパスの終了 //--------------------------------------------------------------------------- void ShadowMap::end() { auto renderBuffer = GmRender()->getRenderBuffer(); auto depthStencil = GmRender()->getDepthStencil(); gpu::setRenderTarget(renderBuffer, depthStencil); // //gpu::setTexture(10, nullptr); gpu::setTexture(TEX_DEPTH, depthTexture_); } //--------------------------------------------------------------------------- //! デプステクスチャ取得 //--------------------------------------------------------------------------- gpu::Texture* ShadowMap::getDepthTexture() { return depthTexture_.get(); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #include "modules/libssl/sslbase.h" #include "modules/libssl/protocol/sslplainrec.h" #include "modules/libssl/protocol/sslcipherrec.h" #ifdef _DEBUG //#define TST_DUMP #endif SSL_PlainText::SSL_PlainText() { Init(); SetIsASegment(TRUE); } void SSL_PlainText::Init() { SetLegalMax(SSL_MAX_PLAIN_LENGTH); spec.enable_tag = TRUE; spec.idtag_len = 1; version.Follow(&tag); // Action 2; } SSL_PlainText::~SSL_PlainText() { } void SSL_PlainText::PerformActionL(DataStream::DatastreamAction action, uint32 arg1, uint32 arg2) { SSL_Record_Base::PerformActionL(action, arg1, arg2); if(action == DataStream::KReadAction && arg2 == DataStream_BaseRecord::RECORD_LENGTH && GetLength() > GetLegalMaxLength()) { RaiseAlert(SSL_Fatal,SSL_Illegal_Parameter); } } SSL_Record_Base *SSL_PlainText::InitEncryptTarget() { SSL_Record_Base *temp; temp = OP_NEW(SSL_CipherText, ()); if(temp == NULL) RaiseAlert(SSL_Internal, SSL_Allocation_Failure); // Should really be in TLS class, but this is easier. if(version.Minor() > 1) temp->SetUseIV_Field(); return temp; } SSL_Record_Base *SSL_PlainText::InitDecryptTarget(SSL_CipherSpec *cipher) { SSL_Record_Base *temp; temp = OP_NEW(SSL_PlainText, ()); if(temp == NULL) RaiseAlert(SSL_Internal, SSL_Allocation_Failure); return temp; } /* Crompressing Deactivated */ /* void SSL_PlainText::StartPartialCompress() { if(compress_target != NULL) delete compress_target; compress_target = new SSL_Compressed; if(compress_target == NULL) RaiseAlert(SSL_Internal, SSL_Allocation_Failure); epos = ppos = 0; } SSL_Record_Base *SSL_PlainText::PartialCompress(SSL_CipherSpec *method,uint32) { SSL_Record_Base *ret; ret = NULL; if (compress_target != NULL){ compress_target->SetType(GetType()); compress_target->SetVersion(GetVersion()); switch(method->compression){ case SSL_Null_Compression : default : compress_target->SSL_varvector16::operator =(*this); break; } ret = compress_target; compress_target = NULL; } return ret; } void SSL_PlainText::StartPartialDecompress() { if(decryption_target != NULL) delete decryption_target; decryption_target = new SSL_PlainText; if(decryption_target == NULL) RaiseAlert(SSL_Internal, SSL_Allocation_Failure); epos = ppos = 0; } SSL_Record_Base *SSL_PlainText::PartialDecompress(SSL_CipherSpec *method,uint32) { SSL_Record_Base *ret; ret = NULL; if (decryption_target != NULL){ decryption_target->SetType(GetType()); decryption_target->SetVersion(GetVersion()); switch(method->compression){ case SSL_Null_Compression : default : decryption_target->SSL_varvector16::operator =(*this); break; } ret = decryption_target; decryption_target = NULL; } return ret; } */ #endif
#include "order.h" Order::Order(int timestamp, char id, bool isBid, int price, int size) { this->timestamp = timestamp; this->id = id; this->isBid = isBid; this->price = price; this->size = size; this->next = NULL; this->prev = NULL; this->parentLimit = NULL; } void Order::Append(Order * newOrder) { Order * n = this; while (n->next != NULL){ n = n->next; } n->next = newOrder; newOrder->prev = n; } int Order::Reduce(int size) { this->size -= size; this->parentLimit->volume -= size; this->timestamp = timestamp; return this->size; } Order::~Order() { // correct links if (next != NULL){ next->prev = prev; } else{ // I'm the tail parentLimit->tail = prev; } if (prev != NULL){ prev->next = next; } else{ // I'm the head parentLimit->head = next; } // did we exhaust a limit? if (parentLimit->head == NULL && parentLimit->tail ==NULL){ //delete parentLimit; // actually lets not delete it. } // correct running totals parentLimit->volume -= size; } void Order::repr() { std::cout<<this->id; if (next != NULL){ std::cout<<'-'; next->repr(); } }
#include <iostream>; #include <string>; #include <conio.h> #include <cassert> using namespace std; int search_1(int A[], int size, int key) { assert(size != NULL); for (int i = 0; i < size; ++i) { if (A[i] == key) { return i; } } return -1; } int search_2(int A[], int size, int key) { int i = 0; while (i < size) { if (A[i] == key) return i; ++i; } return -1; } int search_3(int A[], int size, int key) { A[size] = key; int i = 0; while (A[i] != key) ++i; if (i != size) return i; return -1; } int search_4(int A[], int size, int key) { if (size == 0) return -1; int end = size - 1; int last = A[end]; if (last == key) return end; A[end] = key; int i = 0; while (A[i] != key) ++i; A[end] = last; if (i != end) return i; return -1; } /*int search_binary(int B[], int key) { if (B[0] != key) { cout << "if" << endl; while (B[x] != key && x != 0) { cout << "while" << endl; if (B[x] < key) x += ceil(x / 2); else x -= ceil(x / 2); } return x; cout << x << endl; } return 0;//?? cout << "0" << endl; }*/ int search_binary(int B[], int key, int size) { if (B[0] != key) { cout << "if" << endl; while (B[x] != key && x != 0) { cout << "while" << endl; if (B[x] < key) x += ceil(x / 2); else x -= ceil(x / 2); } return x; cout << x << endl; } return 0;//?? cout << "0" << endl; } int search_binaryRec() { } typedef int(*search_func)(int A[], int size, int key); void test_1(search_func func, int A[], int size, int key, string success, string error) { if (A[func(A, size, key)] == key) cout << success << endl; else cout << error << endl; } void test_2(search_func func, int A[], int size, int keyBeg, int keyMid, int keyEnd, string success, string error) { if (A[func(A, size, keyBeg)] == keyBeg) cout << "Begin: " << success << endl; else cout << "Begin: " << error << endl; if (A[func(A, size, keyMid)] == keyMid) cout << "Middle: " << success << endl; else cout << "Middle: " << error << endl; if (A[func(A, size, keyEnd)] == keyEnd) cout << "End: " << success << endl; else cout << "End: " << error << endl; } void testingProcess() { int arr1[] = { 1 }; int arr2[] = { 2 }; int arr3[] = { 1, 2 }; int arr4[] = { 3, 4 }; int arr5[] = { 2, 4, 7, 9, 34 }; // testing of the first variant test_1(search_1, arr1, 1, 1, "Test 1.1 (el 1): success", "Test 1.1 (el 1): error"); test_1(search_1, arr2, 1, 2, "Test 1.2 (el 1): success", "Test 1.2 (el 1): error"); test_1(search_1, arr3, 2, 2, "Test 1.3 (el 2): success", "Test 1.3 (el 2): error"); test_1(search_1, arr4, 2, 4, "Test 1.4 (el 2): success", "Test 1.4 (el 2): error"); test_2(search_1, arr5, 5, 2, 7, 34, "Test 2 (el beg, mid, end): success", "Test 2 (el beg, mid, end): error"); // testing of the second variant test_1(search_2, arr1, 1, 1, "Test 1.1 (el 1): success", "Test 1.1 (el 1): error"); test_1(search_2, arr2, 1, 2, "Test 1.2 (el 1): success", "Test 1.2 (el 1): error"); test_1(search_2, arr3, 2, 2, "Test 1.3 (el 2): success", "Test 1.3 (el 2): error"); test_1(search_2, arr4, 2, 4, "Test 1.4 (el 2): success", "Test 1.4 (el 2): error"); test_2(search_2, arr5, 5, 2, 7, 34, "Test 2 (el beg, mid, end): success", "Test 2 (el beg, mid, end): error"); // testing of the third variant int ar1[] = { 1, 0 }; int ar2[] = { 2, 0 }; int ar3[] = { 1, 2, 0 }; int ar4[] = { 3, 4, 0 }; int ar5[] = { 2, 4, 7, 9, 34, 0 }; test_1(search_3, ar1, 1, 1, "Test 1.1 (el 1): success", "Test 1.1 (el 1): error"); test_1(search_3, ar2, 1, 2, "Test 1.2 (el 1): success", "Test 1.2 (el 1): error"); test_1(search_3, ar3, 2, 2, "Test 1.3 (el 2): success", "Test 1.3 (el 2): error"); test_1(search_3, ar4, 2, 4, "Test 1.4 (el 2): success", "Test 1.4 (el 2): error"); test_2(search_3, ar5, 5, 2, 7, 34, "Test 2 (el beg, mid, end): success", "Test 2 (el beg, mid, end): error"); // testing of the forth variant test_1(search_4, arr1, 1, 1, "Test 1.1 (el 1): success", "Test 1.1 (el 1): error"); test_1(search_4, arr2, 1, 2, "Test 1.2 (el 1): success", "Test 1.2 (el 1): error"); test_1(search_4, arr3, 2, 2, "Test 1.3 (el 2): success", "Test 1.3 (el 2): error"); test_1(search_4, arr4, 2, 4, "Test 1.4 (el 2): success", "Test 1.4 (el 2): error"); test_2(search_4, arr5, 5, 2, 7, 34, "Test 2 (el beg, mid, end): success", "Test 2 (el beg, mid, end): error"); } int main(int argc, char* argv[]) { //testingProcess(); int B[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; search_binary(B, 7); int key = 3; int x = sizeof(B) / sizeof(B[0]); int y = x / 2; binFuncRec(B, key, y); _getch(); return 0; }
#include "akasztofa.h" int Akasztofa::tipp(char c) { if(hatra == 0) { throw "Nem probalkozhat tobbszor."; } for (unsigned i = 0; i < feladvany.length(); i++) { if(not allapot[i] and feladvany[i]==c) { allapot[i] = true; rejtve--; } } hatra--; return rejtve; } int Akasztofa::getHatra() const { return hatra; } std::ostream& operator<<(std::ostream& os, const Akasztofa& a) { for (unsigned i = 0; i < a.feladvany.length(); i++) { os << (a.allapot[i] ? a.feladvany[i] : '*'); } return os; }
/* * LSST Data Management System * Copyright 2014-2015 AURA/LSST. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <https://www.lsstcorp.org/LegalNotices/>. */ #ifndef LSST_SG_CONSTANTS_H_ #define LSST_SG_CONSTANTS_H_ /// \file /// \brief This file contains common constants. namespace lsst { namespace sg { // Note: given a compiler that does correctly rounded decimal to // binary floating point conversions, PI = 0x1.921fb54442d18p1 in // IEEE double precision format. This is less than π. static double const PI = 3.1415926535897932384626433832795; static double const RAD_PER_DEG = 0.0174532925199432957692369076849; static double const DEG_PER_RAD = 57.2957795130823208767981548141; // The maximum error of std::asin in IEEE double precision arithmetic, // assuming 1 ulp of error in its argument, is about // π/2 - arcsin (1 - 2⁻⁵³), or a little less than 1.5e-8 radians // (3.1 milliarcsec). static double const MAX_ASIN_ERROR = 1.5e-8; // The computation of squared chord length between two unit vectors // involves 8 elementary operations on numbers with magnitude ≤ 4. Its // maximum error can be shown to be < 2.5e-15. static double const MAX_SCL_ERROR = 2.5e-15; }} // namespace lsst::sg #endif // LSST_SG_CONSTANTS_H_
/** * IP implementing the reduce method of NumPy ufuncs for one-dimensional * inputs (or flattened multi-dimensional inputs). Integer (i4) implementation. * * The reduction operator can be selected using the `args.reduce_op` parameter. * It is also possible to do an additional unary or binary operation on each * (pair of) incoming elements, using the `args.element_op` parameter, which * defaults to NONE (i.e. don't do any element-wise operation). * * IMPORTANT: * - The reduction operation is assumed to be commutative (because the * core will reorder some terms). * - The minimum input length is equal to the PIPE_DEPTH constant. * - If there are two input streams, the args.element_op needs to be a binary * operation. * * EXAMPLES: * - To calculate the sum of all numbers of a single input stream: * > args.reduce_op = ADD * > args.element_op = NONE * - To calculate the sum of the squares of a single input stream: * > args.reduce_op = ADD * > args.element_op = SQUARE * - To calculate the dot product of two input streams: * > args.reduce_op = ADD * > args.element_op = MULTIPLY * * IMPLEMENTATION: * - To achieve the lowest possible latency, the core calculates a series * of partial results "in parallel" (in fact, fully pipelined at II=1). * After this stage, the array of partial results is further processed using * a tree-like access pattern to produce the final output value. * */ //////////////////////////////////////////////////////////////////////////////// #include "ufunc_reduce_all_i4.h" #include "ufuncs_i4.h" //////////////////////////////////////////////////////////////////////////////// // Function that selects and performs the required (reduction or element-wise) // operation on inputs x and y. The result is stored back in x. void do_operation(unsigned char *op, int *x, int *y) { int2 ufunc_in, ufunc_out; // To temporarily hold the inputs and outputs. ufunc_in.first = *x; ufunc_in.second = *y; switch(*op) { case NONE: ufunc_out = ufunc_in; break; case ADD: ufunc_out = add(ufunc_in); break; case MULTIPLY: ufunc_out = multiply(ufunc_in); break; case SQUARE: ufunc_out = square(ufunc_in); break; case EXP: ufunc_out = exp(ufunc_in); break; case LOG: ufunc_out = log(ufunc_in); break; case ABSDIFF: ufunc_out = absdiff(ufunc_in); break; } *x = ufunc_out.first; } //////////////////////////////////////////////////////////////////////////////// // Top level module implementing the reduce method of NumPy ufuncs for // one-dimensional inputs (or flattened multi-dimensional inputs). int ufunc_reduce_all_i4( stream_t &in1_s, // Main AXI4-Stream input. stream_t &in2_s, // Optional second AXI4-Stream input. packed_t args // Configuration parameters, see definitions. ) { #pragma HLS interface axis port=in1_s #pragma HLS interface axis port=in2_s #pragma HLS interface s_axilite port=args #pragma HLS interface s_axilite port=return channel_t in1_c, in2_c; // To temporarily hold side-channel information. static int res_p[PIPE_DEPTH]; // Contains the partial results. unsigned int p = 0; // Current index within the partial results. unsigned int n = 0; // Indicates the n-th input value. // This loop calculates the partial results. #pragma HLS allocation function instances=do_operation limit=2 #pragma HLS dependence variable=res_p inter false main: do { #pragma HLS pipeline II=1 // Read the input stream. in1_c = in1_s.read(); in1.u4 = in1_c.data; // Optionally read the second input stream. if(is_binary[args.element_op]) { in2_c = in2_s.read(); in2.u4 = in2_c.data; } // Apply both the element-wise operation and the reduction operation // and store the first partial result. do_operation(&args.element_op, &in1.i4, &in2.i4); do_operation(&args.reduce_op, &res_p[p], &in1.i4); if(n++ < PIPE_DEPTH) res_p[p] = in1.i4; p = (p == PIPE_DEPTH - 1 ? 0 : p + 1); } while(in1_c.last != 1); // This loop reduces the partial results using a tree-like access pattern. #pragma HLS array_partition variable=res_p complete fini: for(int depth = 0; depth < LOG2_PIPE_DEPTH; depth++) { #pragma HLS unroll for(int i = 0; i < PIPE_DEPTH; i += (2 << depth)) { do_operation(&args.reduce_op, &res_p[i], &res_p[i + (1 << depth)]); } } do_operation(&args.final_op, &res_p[0], &res_p[1]); return res_p[0]; } ////////////////////////////////////////////////////////////////////////////////
#ifndef LogServerConnect_H #define LogServerConnect_H #include "CDLSocketHandler.h" #include "CDL_Timer_Handler.h" #include "Packet.h" #include "DLDecoder.h" #define CMD_BACKSVR_HEART 0x0001 //MysqlServer #define RECORD_GAME_START 0x0500 //游戏开始 #define RECORD_BET_CALL 0x0501 //跟注 #define RECORD_BET_RASE 0x0502 //加注 #define RECORD_ALL_IN 0x0503 //梭哈 #define RECORD_LOOK_CARD 0x0504 //看牌 #define RECORD_THROW_CARD 0x0505 //弃牌 #define RECORD_GAME_OVER 0x0506 //游戏结束 #define RECORD_ACTIVE_LEAVE 0x0507 //游戏中离开 #define RECORD_LOG_OUT 0x0508 //用户断线 #define RECORD_GET_DETAIL 0x0509 //获取信息 #define RECORD_TIME_OUT 0x0510 //获取信息 class LogServerConnect ; class HeartTimer:public CCTimer { public: HeartTimer(){} ; virtual ~HeartTimer() {}; inline void init(LogServerConnect* connect){this->connect=connect;}; private: virtual int ProcessOnTimerOut(); LogServerConnect* connect; }; class ConnectHandle: public CDLSocketHandler { public: ConnectHandle(LogServerConnect* connect); ConnectHandle(){}; virtual ~ConnectHandle() { //this->_decode = NULL; }; int OnConnected(); int OnClose(); int OnPacketComplete(const char * data, int len) { pPacket.Copy(data,len); return OnPacketComplete(&pPacket); } int OnPacketComplete(InputPacket* pPacket); CDL_Decoder* CreateDecoder() { return &DLDecoder::getInstance(); } private : LogServerConnect* connect; InputPacket pPacket; }; class LogServerConnect { public: static LogServerConnect* getInstance(); virtual ~LogServerConnect(); int connect(const char* ip, short port); int reconnect(); inline bool isActive(){return isConnect;}; inline void setActive(bool b){ this->isConnect = b; if(!b) handler=NULL; }; int reportLog(int time, int svid, int uid, int opt,const char* format, ...); int Send(InputPacket* inputPacket) { if(handler) return handler->Send(inputPacket->packet_buf(), inputPacket->packet_size()) >=0 ? 0 : -1; else{ /*if(reconnect()==0) { return handler->Send(inputPacket->packet_buf(), inputPacket->packet_size()); }*/ return -1; } } int Send(OutputPacket* outputPacket) { if(handler) return handler->Send(outputPacket->packet_buf(), outputPacket->packet_size()) >=0 ? 0 : -1; else{ /*if(reconnect()==0) { return handler->Send(outputPacket->packet_buf(), outputPacket->packet_size()); }*/ return -1; } } int sendHeartBeat(); private: LogServerConnect(); short port; char ip[32]; bool isConnect; ConnectHandle* handler; HeartTimer* heartBeatTimer; }; #endif
#include <chuffed/core/engine.h> #include <chuffed/core/options.h> #include <chuffed/core/sat.h> #include <iostream> Options so; Options::Options() : nof_solutions(1), time_out(0), rnd_seed(0), verbosity(0), print_sol(true), restart_scale(1000000000), restart_scale_override(true), restart_base(1.5), restart_base_override(true), restart_type(CHUFFED_DEFAULT), restart_type_override(true) , toggle_vsids(false), branch_random(false), switch_to_vsids_after(1000000000), sat_polarity(0), sbps(false) , prop_fifo(false) , disj_edge_find(true), disj_set_bp(true) , cumu_global(true) , sat_simplify(true), fd_simplify(true) , lazy(true), finesse(true), learn(true), vsids(false) #if PHASE_SAVING , phase_saving(0) #endif , sort_learnt_level(false), one_watch(true) , exclude_introduced(false), decide_introduced(true), introduced_heuristic(false), use_var_is_introduced(false), print_nodes(false), print_implications(false), print_variable_list(false), send_skipped(true), send_domains(false) , learnt_stats(false), learnt_stats_nogood(false), debug(false), exhaustive_activity(false) , bin_clause_opt(true) , eager_limit(1000), sat_var_limit(2000000), nof_learnts(100000), learnts_mlimit(500000000) , lang_ext_linear(false) , mdd(false), mip(false), mip_branch(false) , sym_static(false), ldsb(false), ldsbta(false), ldsbad(false) , saved_clauses(0), use_uiv(false) , circuitalg(3), prevexpl(1), checkexpl(2), checkfailure(4), checkevidence(4), preventevidence(1), sccevidence(1), sccoptions(4), rootSelection(1) , alldiff_cheat(true), alldiff_stage(true), assump_int(false) #ifdef HAS_PROFILER , cpprofiler_enabled(false), cpprofiler_id(-1), cpprofiler_port(6565) #endif { } template <class T> inline bool assignStr(T* /*unused*/, const std::string /*unused*/) { return false; } template <> inline bool assignStr(std::string* pS, const std::string s) { *pS = s; return true; } /// A simple per-cmdline option parser class CLOParser { int& i; // current item const int argc = 0; const char* const* argv = nullptr; public: CLOParser(int& ii, const int ac, const char* const* av) : i(ii), argc(ac), argv(av) {} template <class Value = int> inline bool get(const char* names, // space-separated option list Value* pResult = nullptr, // pointer to value storage bool fValueOptional = false // if pResult, for non-string values ) { return getOption(names, pResult, fValueOptional); } template <class Value = int> inline bool getOption(const char* names, // space-separated option list Value* pResult = nullptr, // pointer to value storage bool fValueOptional = false // if pResult, for non-string values ) { assert(nullptr == strchr(names, ',')); assert(nullptr == strchr(names, ';')); if (i >= argc) { return false; } assert(argv[i]); std::string arg(argv[i]); /// Separate keywords std::string keyword; std::istringstream iss(names); while (iss >> keyword) { if (((2 < keyword.size() || nullptr == pResult) && arg != keyword) || // exact cmp (0 != arg.compare(0, keyword.size(), keyword))) { // truncated cmp continue; } /// Process it if (keyword.size() < arg.size()) { if (nullptr == pResult) { continue; } arg.erase(0, keyword.size()); } else { if (nullptr == pResult) { return true; } i++; if (i >= argc) { return fValueOptional; } arg = argv[i]; } assert(pResult); if (assignStr(pResult, arg)) { return true; } std::istringstream iss(arg); Value tmp; if (!(iss >> tmp)) { --i; if (fValueOptional) { return true; } // Not print because another agent can handle this option // cerr << "\nBad value for " << keyword << ": " << arg << endl; return false; } *pResult = tmp; return true; } return false; } inline bool getBool(const char* names, bool& result) { std::string buffer; std::string shortOptions; std::string longOptions; std::string negOptions; std::istringstream iss(names); std::string keyword; while (iss >> keyword) { if (keyword.size() <= 2) { if (!shortOptions.empty()) { shortOptions += " "; } shortOptions += keyword; } else { if (!longOptions.empty()) { longOptions += " "; } longOptions += keyword; if (keyword[0] == '-' && keyword[1] == '-') { if (!negOptions.empty()) { negOptions += " "; } negOptions += "--no" + keyword.substr(1); } } } if (getOption(shortOptions.c_str())) { result = true; return true; } if (getOption(negOptions.c_str())) { result = false; return true; } if (getOption(longOptions.c_str(), &buffer)) { if (buffer.empty() || (buffer == "true" || buffer == "on" || buffer == "1")) { result = true; } else if (buffer == "false" || buffer == "off" || buffer == "0") { result = false; } else { --i; result = true; } return true; } return false; } }; // class CLOParser void printHelp(int& argc, char**& argv, const std::string& fileExt) { Options def; std::cout << "Usage: " << argv[0] << " [options] "; if (!fileExt.empty()) { std::cout << "<file>." << fileExt; } std::cout << "\n"; std::cout << "Options:\n"; std::cout << " -h, --help\n" " Print help for common options.\n" " --help-all\n" " Print help for all options.\n" " -a\n" " Satisfaction problems: Find and print all solutions.\n" " Optimisation problems: Print all (sub-optimal) intermediate solutions.\n" " -n <n>, --n-of-solutions <n>\n" " An upper bound on the number of solutions (default " << def.nof_solutions << ").\n" " -v, --verbose\n" " Verbose mode (default " << (def.verbosity == 0 ? "off" : "on") << ").\n" " -t, --time-out <n>\n" " Time out in milliseconds (default " << def.time_out.count() << ", 0 = run indefinitely).\n" " --rnd-seed <n>\n" " Set random seed (default " << def.rnd_seed << "). If 0 then the current time\n" " via std::time(0) is used.\n" "\n" "Search Options:\n" " -f [on|off]\n" " Free search. Alternates between user-specified and activity-based\n" " search when search is restarted. Restart base is set to 100.\n" #ifdef HAS_PROFILER "\n" "Profiler Options:\n" " -cpprofiler id,port\n" " Send search to CP Profiler with the given execution ID and port.\n" #endif "\n"; } void printLongHelp(int& argc, char**& argv, const std::string& fileExt) { printHelp(argc, argv, fileExt); Options def; std::cout << "General Options:\n" " --verbosity <n>\n" " Set verbosity (default " << def.verbosity << ").\n" " --print-sol [on|off], --no-print-sol\n" " Print solutions (default " << (def.print_sol ? "on" : "off") << ").\n" " --prop-fifo [on|off], --no-prop-fifo\n" " Use FIFO (first in, first out) queues for propagation executions instead\n" " of LIFO (last in, first out) queues (default " << (def.prop_fifo ? "on" : "off") << ").\n" "\n" "More Search Options:\n" " --vsids [on|off], --no-vsids\n" " Use activity-based search on the Boolean variables (default " << (def.vsids ? "on" : "off") << ").\n" " --restart [chuffed|none|constant|linear|luby|geometric]\n" " Restart sequence type (default chuffed).\n" " --restart-scale <n>\n" " Scale factor for restart sequence (default " << def.restart_scale << ").\n" " --restart-base <n>\n" " Base for geometric restart sequence (default " << def.restart_base << ").\n" " --toggle-vsids [on|off], --no-toggle-vsids\n" " Alternate search between user-specified and activity-based one when the\n" " search is restarted. Starts by the user-specified search. Default restart\n" " base is used, unless overwritten. (Default " << (def.toggle_vsids ? "on" : "off") << ").\n" " --switch-to-vsids-after <n>\n" " Search starts with the user-specified one and switches to the\n" " activity-based one after a specified number of conflicts\n" " (default " << def.switch_to_vsids_after << ").\n" " --branch-random [on|off], --no-branch-random\n" " Use random variable selection for tie breaking instead of input order (default " << (def.branch_random ? "on" : "off") << ").\n" " --sat-polarity <n>\n" " Selection of the polarity of Boolean variables\n" " (0 = default, 1 = same, 2 = anti, 3 = random) (default " << def.sat_polarity << ").\n" " --sbps [on|off]\n" " Use Solution-based phase saving (SBPS) value selection for integer and SAT " "variables. When branching on a " " variable, it branches if possible on the value this variable had in the best " "solution so far. If not possible, " " value selection is the user-defined one. (default " << (def.sbps ? "on" : "off") << ").\n" "\n" "Learning Options:\n" " --lazy [on|off], --no-lazy\n" " Allow clause generation for domain updates (default " << (def.lazy ? "on" : "off") << ").\n" " --finesse [on|off], --no-finesse\n" " Try to generated stronger clauses (default " << (def.finesse ? "on" : "off") << ").\n" " --learn [on|off], --no-learn\n" " Compute nogoods when a conflict is encountered (default " << (def.learn ? "on" : "off") << ").\n" #if PHASE_SAVING " --phase-saving <n>\n" " Repeat same Boolean variable polarity (0 = no, 1 = recent, 2 = always)\n" " (default: " << def.phase_saving << ").\n" #endif " --eager-limit <n>\n" " The maximal domain size of Integer variables for which the entire Boolean\n" " variables' representation is created upfront (default " << def.eager_limit << ").\n" " The Boolean variables' representation for Integer variables with larger\n" " domain size will be created on demand (lazily).\n" " --sat-var-limit <n>\n" " The maximal number of Boolean variables (default " << def.sat_var_limit << ").\n" " --n-of-learnts <n>\n" " The maximal number of learnt clauses (default " << def.nof_learnts << ").\n" " If this number is reached then some learnt clauses will be deleted.\n" " --learnts-mlimit <n>\n" " The maximal memory limit for learnt clauses in Bytes (default " << def.learnts_mlimit << ").\n" " If the limit is reached then some learnt clauses will be deleted.\n" " --sort-learnt-level [on|off], --no-sort-learnt-level\n" " Sort literals in a learnt clause based on their decision level\n" " (default " << (def.sort_learnt_level ? "on" : "off") << ").\n" " --one-watch [on|off], --no-one-watch\n" " Watch only one literal in a learn clause (default " << (def.one_watch ? "on" : "off") << ").\n" " --bin-clause-opt [on|off], --no-bin-clause-opt\n" " Optimise learnt clauses of length 2 (default " << (def.bin_clause_opt ? "on" : "off") << ").\n" " --assump-int [on|off], --no-assump-int\n" " Try and convert assumptions from the assumption interface back to integer domain " "expressions (default " << (def.assump_int ? "on" : "off") << ").\n" "\n" "Introduced Variable Options:\n" " --introduced-heuristic [on|off], --no-introduced-heuristic\n" " Use a simple heuristic on the variable names for deciding whether a\n" " variable was introduced by MiniZinc (default " << (def.introduced_heuristic ? "on" : "off") << ").\n" " --use-var-is-introduced [on|off], --no-use-var-is-introduced\n" " Use the FlatZinc annotation var_is_introduced for deciding whether a\n" " variable was introduce by MiniZinc (default " << (def.use_var_is_introduced ? "on" : "off") << ").\n" " --exclude-introduced [on|off], --no-exclude-introduced\n" " Exclude introduced variables and their derived internal variables from\n" " learnt clauses (default " << (def.exclude_introduced ? "on" : "off") << ").\n" " --decide-introduced [on|off], --no-decide-introduced\n" " Allow search decisions on introduced variables and their derived internal " "variables\n" " (default " << (def.decide_introduced ? "on" : "off") << ").\n" "\n" "Pre-Processing Options:\n" " --fd-simplify [on|off], --no-fd-simplify\n" " Removal of FD propagators that are satisfied globally (default " << (def.fd_simplify ? "on" : "off") << ").\n" " --sat-simplify [on|off], --no-sat-simplify\n" " Removal of clauses that are satisfied globally default " << (def.sat_simplify ? "on" : "off") << ").\n" "\n" "Propagator Options:\n" " --cumu-global [on|off], --no-cumu-global\n" " Use the global cumulative propagator if possible (default " << (def.cumu_global ? "on" : "off") << ").\n" " --disj-edge-find [on|off], --no-disj-edge-find\n" " Use the edge-finding propagator for disjunctive constraints (default " << (def.disj_edge_find ? "on" : "off") << ").\n" " --disj-set-bp [on|off], --no-disj-set-bp\n" " Use the set bounds propagator for disjunctive constraints (default " << (def.disj_set_bp ? "on" : "off") << ").\n" " --mdd [on|off], --no-mdd\n" " Use the MDD propagator if possible (default " << (def.mdd ? "on" : "off") << ").\n" " --mip [on|off], --no-mip\n" " Use the MIP propagator if possible (default " << (def.mip ? "on" : "off") << ").\n" " --mip-branch [on|off], --no-mip-branch\n" " Use MIP branching as the branching strategy (default " << (def.mip_branch ? "on" : "off") << ").\n" "\n" "Symmetry Breaking Options:\n" " (only one of these can be chosen)\n" " --sym-static [on|off], --no-sym-static\n" " Use static symmetry breaking constraints (default " << (def.sym_static ? "on" : "off") << ").\n" " --ldsb [on|off], --no-ldsb\n" " Use lightweight dynamic symmetry breaking constraints \"1UIP crippled\"\n" " (default " << (def.ldsb ? "on" : "off") << ").\n" " --ldsbta [on|off], --no-ldsbta\n" " Use lightweight dynamic symmetry breaking constraints \"1UIP\"\n" " (default " << (def.ldsbta ? "on" : "off") << ").\n" " --ldsbad [on|off], --no-ldsbad\n" " Use lightweight dynamic symmetry breaking constraints \"all decision clause\"\n" " (default " << (def.ldsbad ? "on" : "off") << ").\n" #ifdef HAS_PROFILER "\n" "More Profiler Options:\n" " --print-nodes [on|off], --no-print-nodes\n" " Print search nodes to the node log file (default " << (def.print_nodes ? "on" : "off") << ").\n" " --print-implications [on|off], --no-print-implications\n" " Print implications encountered during conflict analysis to the implication\n" " log file (default " << (def.print_implications ? "on" : "off") << ").\n" " --print-variable-list [on|off], --no-print-variable-list\n" " Print a variable list to a file (default " << (def.print_variable_list ? "on" : "off") << ").\n" #endif // TODO Description f the listed options below // " --send-skipped [on|off], --no-send-skipped\n" // " <Description> (default " << (def.send_skipped ? "on" : "off") << ").\n" // " --filter-domains <string>\n" // " <Description> (default " << def.filter_domains << ").\n" // " --learnt-stats [on|off], --no-learn-stats\n" // " <Description> (default " << (def.learnt_stats ? "on" : "off") << ").\n" // " --learnt-stats-nogood [on|off], --no-learn-stats-nogood\n" // " <Description> (default " << (def.learnt_stats_nogood ? "on" : "off") << ").\n" // " --debug [on|off], --no-debug\n" // " <Description> (default " << (def.debug ? "on" : "off") << ").\n" // " --exhaustive-activity [on|off], --no-exhaustive-activity\n" // " <Description> (default " << (def.exhaustive_activity ? "on" : "off") << ").\n" // " --lang-ext-linear [on|off], --no-lang-ext-linear\n" // " <Description> (default " << (def.lang_ext_linear ? "on" : "off") << ").\n" // " --well-founded [on|off], --no-well-founded\n" // " <Description> (default " << (def.well_founded ? "on" : "off") << ").\n" ; } void parseOptions(int& argc, char**& argv, std::string* fileArg, const std::string& fileExt) { int j = 1; for (int i = 1; i < argc; i++) { CLOParser cop(i, argc, argv); int intBuffer; bool boolBuffer; std::string stringBuffer; if (cop.get("-h --help")) { printHelp(argc, argv, fileExt); std::exit(EXIT_SUCCESS); } if (cop.get("--help-all")) { printLongHelp(argc, argv, fileExt); std::exit(EXIT_SUCCESS); } if (cop.get("-n --n-of-solutions", &intBuffer)) { so.nof_solutions = intBuffer; } else if (cop.get("-t --time-out", &intBuffer)) { // TODO: Remove warning when appropriate std::cerr << "WARNING: the --time-out flag has recently been changed." << "The time-out is now provided in milliseconds instead of seconds" << std::endl; so.time_out = duration(intBuffer); } else if (cop.get("-r --rnd-seed", &intBuffer)) { so.rnd_seed = intBuffer; } else if (cop.getBool("-v --verbose", boolBuffer)) { so.verbosity = static_cast<int>(boolBuffer); } else if (cop.get("--verbosity", &intBuffer)) { so.verbosity = intBuffer; } else if (cop.getBool("--print-sol", boolBuffer)) { so.print_sol = boolBuffer; } else if (cop.get("--restart", &stringBuffer)) { if (stringBuffer == "chuffed") { so.restart_type = CHUFFED_DEFAULT; } else if (stringBuffer == "none") { so.restart_type = NONE; } else if (stringBuffer == "constant") { so.restart_type = CONSTANT; } else if (stringBuffer == "linear") { so.restart_type = LINEAR; } else if (stringBuffer == "luby") { so.restart_type = LUBY; } else if (stringBuffer == "geometric") { so.restart_type = GEOMETRIC; } else { std::cerr << argv[0] << ": Unknown restart strategy " << stringBuffer << ". Chuffed will use its default strategy.\n"; } so.restart_type_override = false; } else if (cop.get("--restart-scale", &intBuffer)) { so.restart_scale = static_cast<unsigned int>(intBuffer); so.restart_scale_override = false; } else if (cop.get("--restart-base", &stringBuffer)) { // TODO: Remove warning when appropriate std::cerr << "WARNING: the --restart-base flag has recently been changed." << "The old behaviour of \"restart base\" is now implemented by --restart-scale." << std::endl; so.restart_base = stod(stringBuffer); if (so.restart_base < 1.0) { CHUFFED_ERROR("Illegal restart base. Restart count will converge to zero."); } so.restart_base_override = false; } else if (cop.getBool("--toggle-vsids", boolBuffer)) { so.toggle_vsids = boolBuffer; } else if (cop.getBool("--branch-random", boolBuffer)) { so.branch_random = boolBuffer; } else if (cop.get("--switch-to-vsids-after", &intBuffer)) { so.switch_to_vsids_after = intBuffer; } else if (cop.get("--sat-polarity", &intBuffer)) { so.sat_polarity = intBuffer; } else if (cop.getBool("--sbps", boolBuffer)) { so.sbps = boolBuffer; } else if (cop.getBool("--prop-fifo", boolBuffer)) { so.prop_fifo = boolBuffer; } else if (cop.getBool("--disj-edge-find", boolBuffer)) { so.disj_edge_find = boolBuffer; } else if (cop.getBool("--disj-set-bp", boolBuffer)) { so.disj_set_bp = boolBuffer; } else if (cop.getBool("--cumu-global", boolBuffer)) { so.cumu_global = boolBuffer; } else if (cop.getBool("--sat-simplify", boolBuffer)) { so.sat_simplify = boolBuffer; } else if (cop.getBool("--fd-simplify", boolBuffer)) { so.fd_simplify = boolBuffer; } else if (cop.getBool("--lazy", boolBuffer)) { so.lazy = boolBuffer; } else if (cop.getBool("--finesse", boolBuffer)) { so.finesse = boolBuffer; } else if (cop.getBool("--learn", boolBuffer)) { so.learn = boolBuffer; } else if (cop.getBool("--vsids", boolBuffer)) { so.vsids = boolBuffer; } else if (cop.getBool("--sort-learnt-level", boolBuffer)) { so.sort_learnt_level = boolBuffer; } else if (cop.getBool("--one-watch", boolBuffer)) { so.one_watch = boolBuffer; } else if (cop.getBool("--exclude-introduced", boolBuffer)) { so.exclude_introduced = boolBuffer; } else if (cop.getBool("--decide-introduced", boolBuffer)) { so.decide_introduced = boolBuffer; } else if (cop.getBool("--introduced-heuristic", boolBuffer)) { so.introduced_heuristic = boolBuffer; } else if (cop.getBool("--use-var-is-introduced", boolBuffer)) { so.use_var_is_introduced = boolBuffer; } else if (cop.getBool("--print-nodes", boolBuffer)) { so.print_nodes = boolBuffer; } else if (cop.getBool("--print-variable-list", boolBuffer)) { so.print_variable_list = boolBuffer; } else if (cop.getBool("--print-implications", boolBuffer)) { so.print_implications = boolBuffer; } else if (cop.getBool("--send-skipped", boolBuffer)) { so.send_skipped = boolBuffer; } else if (cop.get("--filter-domains", &stringBuffer)) { so.filter_domains = stringBuffer; } else if (cop.getBool("--learnt-stats", boolBuffer)) { so.learnt_stats = boolBuffer; } else if (cop.getBool("--learnt-stats-nogood", boolBuffer)) { so.learnt_stats_nogood = boolBuffer; } else if (cop.getBool("--debug", boolBuffer)) { so.debug = boolBuffer; } else if (cop.getBool("--exhaustive-activity", boolBuffer)) { so.exhaustive_activity = boolBuffer; } else if (cop.getBool("--bin-clause-opt", boolBuffer)) { so.bin_clause_opt = boolBuffer; } else if (cop.getBool("--assump-int", boolBuffer)) { so.assump_int = boolBuffer; } else if (cop.get("--eager-limit", &intBuffer)) { so.eager_limit = intBuffer; } else if (cop.get("--sat-var-limit", &intBuffer)) { so.sat_var_limit = intBuffer; } else if (cop.get("--n-of-learnts", &intBuffer)) { so.nof_learnts = intBuffer; } else if (cop.get("--learnts-mlimit", &intBuffer)) { so.learnts_mlimit = intBuffer; } else if (cop.getBool("--lang-ext-linear", boolBuffer)) { so.lang_ext_linear = boolBuffer; } else if (cop.getBool("--mdd", boolBuffer)) { so.mdd = boolBuffer; } else if (cop.getBool("--mip", boolBuffer)) { so.mip = boolBuffer; } else if (cop.getBool("--mip-branch", boolBuffer)) { so.mip_branch = boolBuffer; } else if (cop.getBool("--sym-static", boolBuffer)) { so.sym_static = boolBuffer; } else if (cop.getBool("--ldsb", boolBuffer)) { so.ldsb = boolBuffer; } else if (cop.getBool("--ldsbta", boolBuffer)) { so.ldsbta = boolBuffer; } else if (cop.getBool("--ldsbad", boolBuffer)) { so.ldsbad = boolBuffer; } else if (cop.getBool("--well-founded", boolBuffer)) { so.well_founded = boolBuffer; } else if (cop.get("-a")) { so.nof_solutions = 0; } else if (cop.get("-f")) { so.toggle_vsids = true; so.restart_scale = 100; } else if (cop.get("-s -S")) { so.verbosity = 1; #ifdef HAS_PROFILER } else if (cop.get("--cp-profiler", &stringBuffer)) { std::stringstream ss(stringBuffer); char sep; ss >> so.cpprofiler_id >> sep >> so.cpprofiler_port; if (sep == ',' && ss.eof()) { so.cpprofiler_enabled = true; } else { CHUFFED_ERROR("Invalid value for --cp-profiler."); } #endif } else if (argv[i][0] == '-') { std::cerr << argv[0] << ": unrecognized option " << argv[i] << "\n"; std::cerr << argv[0] << ": use --help for more information.\n"; std::exit(EXIT_FAILURE); } else { argv[j++] = argv[i]; } } argc = j; if (fileArg != nullptr) { if (argc == 2) { std::string filename(argv[1]); if (!fileExt.empty()) { if (filename.size() <= fileExt.size() + 1 || filename.substr(filename.size() - fileExt.size() - 1) != "." + fileExt) { std::cerr << argv[0] << ": cannot handle file extension for " << filename << "\n"; std::cerr << argv[0] << ": use --help for more information.\n"; std::exit(EXIT_FAILURE); } } *fileArg = filename; --argc; } else if (argc > 2) { std::cerr << argv[0] << ": more than one file argument not supported\n"; std::cerr << argv[0] << ": use --help for more information.\n"; std::exit(EXIT_FAILURE); } } rassert(so.sym_static + so.ldsb + so.ldsbta + so.ldsbad <= 1); if (so.ldsbta || so.ldsbad) { so.ldsb = true; } if (so.ldsb) { rassert(so.lazy); } if (so.mip_branch) { rassert(so.mip); } if (so.vsids) { engine.branching->add(&sat); } if (so.learnt_stats_nogood) { so.learnt_stats = true; } // Warn user if SBPS is not used with an activity-based search and restarts if (so.sbps) { if (!(so.vsids || so.toggle_vsids || so.switch_to_vsids_after < 1000000000)) { std::cerr << "WARNING: SBPS value selection must be used with an activity-based search to " "optimize its " "efficiency." << std::endl; } if (so.restart_type == NONE || so.restart_scale == 0) { std::cerr << "WARNING: SBPS value selection must be used with restarts to optimize its " "efficiency." << std::endl; } } }
#include <iostream> #include <cmath> #include <cstdio> #include <cstdlib> #include "TFile.h" #include "TTree.h" #include "TH1.h" #include "Nuclear_Info.h" #include "fiducials.h" using namespace std; int main(int argc, char ** argv) { if (argc != 3) { cerr << "Wrong number of arguments. Instead try:\n" << " prec_hists /path/to/input/file /path/to/output/file\n\n"; exit(-1); } TFile * fi = new TFile(argv[1]);; TFile * fo = new TFile(argv[2],"RECREATE"); // Create histograms //TH1D * hpp_pRec = new TH1D("epp_Pr","epp;pRec [GeV];Counts",26,0.35,1.0); //hpp_pRec->Sumw2(); //TH1D * hnp_pRec = new TH1D("enp_Pr","enp;pRec [GeV];Counts",26,0.35,1.0); //hnp_pRec->Sumw2(); Double_t bins[3] = {0.35,0.6,1.0}; TH1D * hpp_pRec_2 = new TH1D("epp_Pr_2","epp;pRec [GeV];Counts",2,bins); hpp_pRec_2->Sumw2(); TH1D * hnp_pRec_2 = new TH1D("enp_Pr_2","enp;pRec [GeV];Counts",2,bins); hnp_pRec_2->Sumw2(); //TH1D * hpp_pMiss = new TH1D("epp_Pmiss","epp;pMiss [GeV];Counts",26,0.35,1.0); //hpp_pMiss->Sumw2(); //TH1D * hnp_pMiss = new TH1D("enp_Pmiss","enp;pMiss [GeV];Counts",26,0.35,1.0); //hnp_pMiss->Sumw2(); // Loop over pp tree cerr << " Looping over tree...\n"; TTree * ti = (TTree*)fi->Get("T"); Double_t weight; Double_t pRec; Int_t nump; //Double_t pLead; //Float_t Pmiss[2][3]; //Double_t pMiss; ti->SetBranchAddress("weight",&weight); ti->SetBranchAddress("pRec",&pRec); ti->SetBranchAddress("nump",&nump); //ti->SetBranchAddress("pLead",&pLead); //ti->SetBranchAddress("Pmiss",&Pmiss); for (int event =0 ; event < ti->GetEntries() ; event++) { ti->GetEvent(event); //pMiss = sqrt(Pmiss[0][0]*Pmiss[0][0]+Pmiss[0][1]*Pmiss[0][1]+Pmiss[0][2]*Pmiss[0][2]); if (nump == 2) { //hpp_pRec->Fill(pRec,weight); hpp_pRec_2->Fill(pRec,weight); //hpp_pMiss->Fill(pMiss,weight); } else { //hnp_pRec->Fill(pRec,weight); hnp_pRec_2->Fill(pRec,weight); //hnp_pMiss->Fill(pMiss,weight); } } fi->Close(); // pp2np hist //TH1F *pp_to_np = (TH1F*)hpp_pRec->Clone("pp_to_np"); //pp_to_np->SetName("pp_to_np"); //pp_to_np->SetTitle("pp_to_np;p_rec [GeV];pp_to_np ratio"); //pp_to_np->Divide(hnp_pRec); TH1F *pp_to_np_2 = (TH1F*)hpp_pRec_2->Clone("pp_to_np_2"); pp_to_np_2->SetName("pp_to_np_2"); pp_to_np_2->SetTitle("pp_to_np_2;p_rec [GeV];pp_to_np ratio"); pp_to_np_2->Divide(hnp_pRec_2); //TH1F *pp_to_np_miss = (TH1F*)hpp_pMiss->Clone("pp_to_np_miss"); //pp_to_np_miss->SetName("pp_to_np_miss"); //pp_to_np_miss->SetTitle("pp_to_np_miss;p_miss [GeV];pp_to_np ratio"); //pp_to_np_miss->Divide(hnp_pMiss); //pp_to_np->SetMaximum(0.4); //pp_to_np->SetMinimum(0.0); pp_to_np_2->SetMaximum(0.4); pp_to_np_2->SetMinimum(0.0); //hpp_pRec->SetMinimum(0.0); //hnp_pRec->SetMinimum(0.0); //hpp_pRec_2->SetMinimum(0.0); //hnp_pRec_2->SetMinimum(0.0); // Write out fo->cd(); //pp_to_np->Write(); //hpp_pRec->Write(); //hnp_pRec->Write(); pp_to_np_2->Write(); hpp_pRec_2->Write(); hnp_pRec_2->Write(); //pp_to_np_miss->Write(); //hpp_pMiss->Write(); //hnp_pMiss->Write(); fo->Close(); return 0; }
#include "General.h" #include "Touchstone.h" using namespace RsaToolbox; #include <QDebug> #include <QtTest> #include <QDir> class test_Touchstone : public QObject { Q_OBJECT public: test_Touchstone(); private: QDir path; private Q_SLOTS: void init(); void cleanup(); void ports(); void read(); void write(); }; test_Touchstone::test_Touchstone() { path = QDir(SOURCE_DIR); path.cd("Touchstone Files"); } void test_Touchstone::init() { } void test_Touchstone::cleanup() { } void test_Touchstone::ports() { QVERIFY(path.exists("Maximum.s2p")); QCOMPARE(Touchstone::ports(path.filePath("Maximum.s2p")), uint(2)); QCOMPARE(Touchstone::ports(path.filePath("Minimum.s2p")), uint(2)); QCOMPARE(Touchstone::ports("My craaaazy filename.s5p"), uint(5)); QCOMPARE(Touchstone::ports(""), uint(0)); } void test_Touchstone::read() { NetworkData data; Touchstone::Read(data, path.filePath("Maximum.s2p")); QCOMPARE(data.numberOfPorts(), uint(2)); QCOMPARE(data.points(), uint(8)); QCOMPARE(data.x().first(), 1.0E9); QCOMPARE(data.x().last(), 8.0E9); QCOMPARE(data.y_dB(1,1).first(), -8.0); QCOMPARE(data.y_phase_deg(2,2).first(), 0.0); QCOMPARE(data.y_dB(1,1).last(), -8.0); QCOMPARE(data.y_dB(2,1).last(), -1.0); } void test_Touchstone::write() { QCOMPARE("Did you finish this?", "Yes"); } QTEST_APPLESS_MAIN(test_Touchstone) #include "test_Touchstone.moc"
 #include <windows.h> #include <d3dx9.h> #include <d3d9.h> #include <dinput.h> LPDIRECT3D9 pD3d; LPDIRECT3DDEVICE9 pD3Device; LPDIRECT3DTEXTURE9 pTexture; LPD3DXFONT m_pFont;//フォント(描画ブラシ)のオブジェクト LPDIRECTINPUT8 pDinput; LPDIRECTINPUTDEVICE8 pKeyDevice = NULL;//DirectInputデバイスオブジェクトのポインタ D3DPRESENT_PARAMETERS D3dPresentParameters; // fPosX = 270, fPosY = 180;//左上を(0,0)とし、270,180の点に描画 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);//ウィンドウプロシージャー関数のプロトタイプ宣言 HRESULT BuildDxDevice(HWND, const TCHAR*);//プロトタイプ宣言 void InitPresentParameters(HWND); HRESULT InitD3d(HWND, const TCHAR*);//Direct3Dの初期化関数のプロトタイプ宣言] HRESULT InitDinput(HWND hWnd); VOID FreeDx();//解放するための関数 int window_width = 640; int window_hight = 480; int speed = 4; struct CUSTOMVERTEX { float x, y, z; // 頂点座標 float rhw; // 除算数 DWORD Color; // 頂点の色 float tu, tv; // テクスチャ座標 }; #define FVF_CUSTOM ( D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) CUSTOMVERTEX v[4] = { {10, 10, 0.0f, 1.0f, 0xffffffff, 0.0f, 0.0f}, {110, 10, 0.0f, 1.0f, 0xffffffff, 1.0f, 0}, {110, 110, 0.0f, 1.0f, 0x0fffffff, 1.0f, 1.0f}, {10,110,0.0f,1.0f,0xffffffff,0.0f,1.0f} }; //アプリケーションのエントリー関数 INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR szStr, INT iCmdShow) { DWORD SyncPrev = timeGetTime(); DWORD SyncCurr; HWND hWnd = NULL; MSG msg; //ウィンドウの初期化 static char szAppName[] = "STEP4"; WNDCLASSEX wndclass; wndclass.cbSize = sizeof(wndclass); wndclass.style = CS_HREDRAW | CS_VREDRAW;//H | V はHorizontarl水平 | Vertical垂直 //CS はclass style wndclass.lpfnWndProc = WndProc;//調べる wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInst; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szAppName; wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); RegisterClassEx(&wndclass);//wndclassのアドレス hWnd = CreateWindow(szAppName, szAppName, WS_OVERLAPPEDWINDOW, 0, 0, window_width, window_hight, NULL, NULL, hInst, NULL); ShowWindow(hWnd, SW_SHOW);//表示する UpdateWindow(hWnd); BuildDxDevice(hWnd, "Blank.jpg"); D3DXCreateTextureFromFile( pD3Device, "jump.png", &pTexture); //ダイレクトインプットの初期化関数 if (FAILED(InitDinput(hWnd))) { return 0; } //メッセージループ timeBeginPeriod(1); ZeroMemory(&msg, sizeof(msg)); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0u, 0u, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { SyncCurr = timeGetTime(); //1秒間に60回この中に入る if (SyncCurr - SyncPrev >= 1000 / 60) { //ウィンドウを黒色でクリア pD3Device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0x00, 0x00, 0x00), 1.0, 0); //テクスチャ貼り付け開始 pD3Device->BeginScene(); //テクスチャの貼り付け HRESULT hr = pKeyDevice->Acquire(); if ((hr == DI_OK) || (hr == S_FALSE)) { BYTE diks[256]; pKeyDevice->GetDeviceState(sizeof(diks), &diks); if (diks[DIK_LEFT] & 0x80) { v[0].x -= speed; v[1].x -= speed; v[2].x -= speed; v[3].x -= speed; } if (diks[DIK_RIGHT] & 0x80) { v[0].x += speed; v[1].x += speed; v[2].x += speed; v[3].x += speed; } if (diks[DIK_UP] & 0x80) { v[0].y -= speed; v[1].y -= speed; v[2].y -= speed; v[3].y -= speed; } if (diks[DIK_DOWN] & 0x80) { v[0].y += speed; v[1].y += speed; v[2].y += speed; v[3].y += speed; } } //ピカチュウをかけといわれる pD3Device->SetTexture(0, pTexture); //いわれた場所に、言われた大きさで書き始める pD3Device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, v, sizeof(CUSTOMVERTEX)); //テクスチャの貼り付け終了 //書き終わって、チョークを置く pD3Device->EndScene(); //ウィンドウに表示 //書いたからみて!! pD3Device->Present(0, 0, 0, 0); SyncPrev = SyncCurr;//ゲームの処理 } } Sleep(1); } timeEndPeriod(1); pD3Device->Release(); pD3Device = nullptr; pD3d->Release(); pD3d = nullptr; //アプリケーションを終了する return(INT)msg.wParam; } //ウィンドプロシージャ関数 LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { switch (iMsg) { case WM_DESTROY: PostQuitMessage(0); break; case WM_KEYDOWN: switch ((CHAR)wParam) { case VK_ESCAPE: PostQuitMessage(0); break; } break; } return DefWindowProc(hWnd, iMsg, wParam, lParam); //return関数();関数を呼び出し、その戻り値をreturnする } //デバイス作成 HRESULT BuildDxDevice(HWND hWnd, const TCHAR* filepath) { if (FAILED(InitD3d(hWnd, filepath))) { return E_FAIL; } pD3d = Direct3DCreate9(D3D_SDK_VERSION); if (pD3d == NULL) { MessageBox(0, "Direct3Dの作成に失敗しました", "", MB_OK); return E_FAIL; } pD3Device->SetRenderState(D3DRS_ALPHABLENDENABLE, true); pD3Device->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1); return S_OK; } //ダイレクト3D初期化関数 HRESULT InitD3d(HWND hWnd, const TCHAR * filepath) { //Direct3Dオブジェクトの作成 if (NULL == (pD3d = Direct3DCreate9(D3D_SDK_VERSION))) { MessageBox(0, "Direct3Dの作成に失敗しました", "", MB_OK); return E_FAIL; } InitPresentParameters(hWnd); if (FAILED(pD3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_MIXED_VERTEXPROCESSING, &D3dPresentParameters, &pD3Device/*ダブルポインタ*/))) { MessageBox(0, "HALモードでDIRECT3Dデバイスを作成できません\nREFモードdで再試行します", NULL, MB_OK); if (FAILED(pD3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, hWnd, D3DCREATE_MIXED_VERTEXPROCESSING, &D3dPresentParameters, &pD3Device))) { MessageBox(0, "DIRECT3Dデバイスの作成に失敗しました", NULL, MB_OK); return E_FAIL; } } //テクスチャオブジェクトの作成 if (FAILED(D3DXCreateTextureFromFileEx(pD3Device, filepath, 100, 100, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, D3DX_FILTER_NONE, D3DX_DEFAULT, 0xff000000, NULL, NULL, &pTexture))) { MessageBox(0, "テクスチャの作成に失敗しました", "", MB_OK); return E_FAIL; } return S_OK; } HRESULT InitDinput(HWND hWnd) { HRESULT hr; //DirectInputオブジェクトの作成 if (FAILED(hr = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID * *)& pDinput, NULL))) { return hr; } //Directデバイスオブジェクトの作成 if (FAILED(hr = pDinput->CreateDevice(GUID_SysKeyboard, &pKeyDevice, NULL))) { return hr; } //デバイスをキーボードに設定 if (FAILED(hr = pKeyDevice->SetDataFormat(&c_dfDIKeyboard))) { return hr; } //協調レベルの設定 if (FAILED(hr = pKeyDevice->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND))) //デバイスを取得する pKeyDevice->Acquire(); return S_OK; } void InitPresentParameters(HWND hWnd) { //WindowMode ZeroMemory(&D3dPresentParameters, sizeof(D3DPRESENT_PARAMETERS)); D3dPresentParameters.BackBufferWidth = 0; D3dPresentParameters.BackBufferHeight = 0; D3dPresentParameters.BackBufferFormat = D3DFMT_UNKNOWN; D3dPresentParameters.BackBufferCount = 1; D3dPresentParameters.MultiSampleType = D3DMULTISAMPLE_NONE; D3dPresentParameters.MultiSampleQuality = 0; D3dPresentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD; D3dPresentParameters.hDeviceWindow = hWnd; D3dPresentParameters.Windowed = TRUE; D3dPresentParameters.EnableAutoDepthStencil = FALSE; D3dPresentParameters.AutoDepthStencilFormat = D3DFMT_A1R5G5B5; D3dPresentParameters.Flags = 0; D3dPresentParameters.FullScreen_RefreshRateInHz = 0; D3dPresentParameters.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; } VOID FreeDx() { if (pKeyDevice) { pKeyDevice->Unacquire(); } pKeyDevice->Release(); pKeyDevice = nullptr; pDinput->Release(); pDinput = nullptr; pD3Device->Release(); pD3Device = nullptr; pD3d->Release(); pD3d = nullptr; }
// // Created by heyhey on 20/03/2018. // #ifndef PLDCOMP_STRUCTUREIF_H #define PLDCOMP_STRUCTUREIF_H #include <ostream> #include "Condition.h" #include "Bloc.h" #include "Structure.h" class StructureIF : public Structure { public: StructureIF(); StructureIF(Condition *condition, Bloc *bloc, Bloc *blocElse); virtual ~StructureIF(); private: Bloc* bloc; Bloc* blocElse; public: Bloc *getBloc() const; void setBloc(Bloc *bloc); Bloc *getBlocElse() const; void setBlocElse(Bloc *blocElse); friend ostream &operator<<(ostream &os, const StructureIF &anIf); }; #endif //PLDCOMP_STRUCTUREIF_H
#include "ListNode.h" #include<iostream> #include <cstdlib> using namespace std; template <class T> class GenDLinkedList { public: ListNode<T> *m_head; ListNode<T> *m_tail; int m_size; // constructor GenDLinkedList(); //destructor ~GenDLinkedList(); // member functions void insertFront(T val); void insertBack(T val); T removeFront(); //T removeBack(); int deletePosition(T position); int find (T val); bool isEmpty(); void printList(); unsigned int getSize(); }; //////////////////////**********Implementions**********///////////////////////// // constructor template <class T> GenDLinkedList<T>::GenDLinkedList() { m_size = 0; m_head = NULL; m_tail = NULL; } /////////////////////////////////////////////////////////////////////////////// // destructor template <class T> GenDLinkedList<T>::~GenDLinkedList() { ListNode<T> *current = m_head; ListNode<T> *next = NULL; while(current != NULL) { next = current -> m_next; delete current; current = next; } } /////////////////////////////////////////////////////////////////////////////// //getSize function // int GenDLinkedList<T>::getSize(): return the size of the list template <class T> unsigned int GenDLinkedList<T>::getSize() { return m_size; } /////////////////////////////////////////////////////////////////////////////// //isEmpty fucntion // bool GenDLinkedList<T>::isEmpty(): returns if the list is empty; otherwise // false template <class T> bool GenDLinkedList<T>::isEmpty() { if(m_size == 0) { return true; } return false; } /////////////////////////////////////////////////////////////////////////////// // printList() function // void GenDLinkedList<T>::printList: print the entire list template <class T> void GenDLinkedList<T>::printList() { ListNode<T> *tempNode = m_head; while(tempNode != NULL) { cout << tempNode -> m_value << " "; tempNode = tempNode -> next; } } /////////////////////////////////////////////////////////////////////////////// // insertFront function // void GenDLinkedList<T>::insertFront: puts the value at the beginning of the // list template <class T> void GenDLinkedList<T>::insertFront(T val) { // creating a new node with the new val ListNode<T> *newNode = new ListNode<T>(val); if(isEmpty()) { m_tail = newNode; } else { newNode -> m_next = m_head; m_head-> m_prev = newNode; } // updating the head of the list m_head = newNode; m_size++; } /////////////////////////////////////////////////////////////////////////////// // insertBack // void GenDLinkedList<T>::insertBack: puts the value at the end of the list template <class T> void GenDLinkedList<T>::insertBack(T val) { ListNode<T> *newNode = new ListNode<T>(val); if(isEmpty()) { m_head = newNode; return; } else { m_tail -> m_next = newNode; newNode -> m_prev = m_tail; } m_tail = newNode; m_size++; } /////////////////////////////////////////////////////////////////////////////// // removeFront // int GenDLinkedList<T>::removeFront: removes the value at the beginning of // the list template <class T> T GenDLinkedList<T>::removeFront() { ListNode<T> *tempNode = m_head; T tempVal= NULL; if(isEmpty()){ cout<<"List is empty"<<endl; return; } // checks if only one element exists if(m_head -> m_next == NULL) { m_tail = NULL; //throw exception or return false } else // one or more elements { m_head -> m_next -> m_prev = NULL; } m_head = m_head -> m_next; tempVal = tempNode -> m_value; tempNode -> m_next = NULL; delete tempNode; m_size--; return tempVal; } /////////////////////////////////////////////////////////////////////////////// // removeBack function // int GenDLinkedList<T>::removeBack(): removes the value at the end of the list /*template <class T> T GenDLinkedList<T>::removeBack() { ListNode<T> *tempNode = m_head; int tempVal = 0; if(isEmpty()) { // throw an exception cout << "Cannot remove from the empty list" << endl; return; } // checks if only one element exists if(m_head -> m_next == NULL) { m_tail = NULL; //throw exception or return false } else // one or more elements { m_tail -> m_next -> m_prev = NULL; } m_tail = m_tail -> m_next; tempVal = tempNode -> m_value; tempNode -> m_next = NULL; delete tempNode; m_size--; return tempVal; } */ /////////////////////////////////////////////////////////////////////////////// // deletePosition funtion // int GenDLinkedList<T>::deletePosition(T position): removes a position from // the list template <class T> int GenDLinkedList<T>::deletePosition(T position) { int index = 0; ListNode<T> *current = m_head; ListNode<T> *previous = m_head; int tempVal = 0; while(index != position) { previous = current; current = current -> m_next; ++index; } // index == position // when the position is found, update the pointers previous -> m_next = current -> m_next; current -> m_next = NULL; tempVal = current -> m_value; delete current; m_size--; return tempVal; } /////////////////////////////////////////////////////////////////////////////// // find function // int GenDLinkedList<T>::find(T val): returns the position of the value exist // in the list template <class T> int GenDLinkedList<T>::find(T val) { int index = -1; ListNode<T> *tempNode = m_head; while(tempNode != NULL) { ++index; // if the value if found if(tempNode -> value == val) { break; } else // if the value is not found { tempNode = tempNode -> next; } // if the value is at the end of the list if(tempNode == NULL) { index = -1; } return index; } }
#include <cstdlib> #include "setint.h" /** * Default constructor - default to a list of capacity = 10 */ SetInt::SetInt() : list_() { iterLoc_ = -1; } /** * Destructor */ SetInt::~SetInt() { } /** * Returns the current number of items in the list */ int SetInt::size() const { return list_.size(); } /** * Returns true if the list is empty, false otherwise */ bool SetInt::empty() const { return list_.empty(); } /** * Inserts val so it appears at index, pos */ void SetInt::insert(const int& val) { if(!exists(val)){ list_.insert(0,val); } } /** * Removes the value at index, pos */ void SetInt::remove(const int& val) { for(unsigned int i=0; i < list_.size(); i++){ if(list_.get(i) == val){ list_.remove(i); break; } } } /** * Returns true if the item is in the set */ bool SetInt::exists(const int& val) const { for(unsigned int i=0; i < list_.size(); i++){ if(list_.get(i) == val){ return true; } } return false; } /** * Return a pointer to the first item * and support future calls to next() */ int const* SetInt::first() { iterLoc_ = 0; if(iterLoc_ < list_.size()){ return &list_.get(0); } return NULL; } /** * Return a pointer to the next item * after the previous call to next * and NULL if you reach the end */ int const* SetInt::next() { if(iterLoc_ < list_.size()-1){ return &list_.get(++iterLoc_); } return NULL; } /** * Returns another (new) set that contains * the union of this set and "other" */ SetInt SetInt::setUnion(const SetInt& other) const { SetInt x(other); for(unsigned int i = 0; i < list_.size(); i++){ x.insert(list_.get(i)); } return x; } /** * Returns another (new) set that contains * the intersection of this set and "other" */ SetInt SetInt::setIntersection(const SetInt& other) const { SetInt x; for(unsigned int i = 0; i < list_.size(); i++){ if( other.exists( list_.get(i) )){ x.insert(list_.get(i)); } } return x; } SetInt SetInt::operator|(const SetInt& other) const { return setUnion(other); } SetInt SetInt::operator&(const SetInt& other) const { return setIntersection(other); }
#pragma once #include "level.h" using namespace std; int random(int minN, int maxN) { return minN + rand() % (maxN + 1 - minN); } int x_random(int x) { if (x < 87) return random(x, x + 10); if (x > 26) return random(x, x - 10); } int LEVEL(int tmp) { srand((int)time(0)); if (tmp == 0) return 10; if(tmp==1) return random(1, 10); if (tmp == 2) return random(1, 5); if (tmp == 3) { return 10; } if (tmp == 4) return random(1,10); return random(1, 5); }
// https://oj.leetcode.com/problems/max-points-on-a-line/ /* * Take every point as a hub point and find points on * lines that go through the given hub point. And then * find the maximum among all possibilities. * * Note: Be careful when several points overlap. */ /** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */ class Solution { const double EPS = 1e-3; public: int maxPoints(vector<Point> &points) { int max_points = 0; size_t size = points.size(); if (size <= 2) { return (int) size; } unordered_map<double, int> slope_cnt; for (size_t i = 0; i < size; i++) { int same_pts = 1; slope_cnt.clear(); for (size_t j = i+1; j < size; j++) { double slope = numeric_limits<double>::max(); double dx = static_cast<double>(points[i].x - points[j].x); double dy = static_cast<double>(points[i].y - points[j].y); if (abs(dx) > EPS) { slope = dy / dx; } else if (abs(dy) <= EPS) { // two points overlap same_pts++; continue; } if (slope_cnt.count(slope) == 0) { slope_cnt.emplace(slope, 1); } else { slope_cnt[slope]++; } } max_points = max(max_points, same_pts); for (auto it = slope_cnt.begin(); it != slope_cnt.end(); ++it) { max_points = max(max_points, it->second + same_pts); } } return max_points; } };
// // EnemyLBullet.h // // Created by Yajun Shi // #include "stdafx.h" #include "Player.h" #include "EnemyBullet.h" #ifndef __ClientGame__EnemyLBullet__ #define __ClientGame__EnemyLBullet__ class EnemyLBullet : public EnemyBullet { public: EnemyLBullet(Enemy* enemy); }; #endif /* defined(__ClientGame__EnemyLBullet__) */
//: C13:NewAndDelete.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Prosta demonstracja operatorow new i delete #include "Tree.h" using namespace std; int main() { Tree* t = new Tree(40); cout << t; delete t; } ///:~
#ifndef TOKENIZER_H #define TOKENIZER_H #include <string.h> #include <string> #include <iostream> using namespace std; class Tokenizer { public: Tokenizer(string fileName) { fin.open(fileName.c_str()); token = NULL; if (fin.is_open()) { if (getline(fin,line)) { token = strtok( (char*)line.c_str(), delims ); } } } string next() { string s = token; token = strtok( NULL, delims ); while (token == NULL) { if (getline(fin,line)) { token = strtok( (char*)line.c_str(), delims ); } else { break; } } return s; } bool hasNext() { return token != NULL; } void close() { fin.close(); } static const char *delims; private: char *token; ifstream fin; string line; }; const char *Tokenizer::delims = " \"\'[](){},.!@#$%^&|~-=<>?;:+-*_/\\\n"; #endif // TOKENIZER_H
// // Created by Steven Yan on 10/02/2017. // #ifndef DAYSBETWEENDATES_CORE_H #define DAYSBETWEENDATES_CORE_H #endif //DAYSBETWEENDATES_CORE_H #include<iostream> int addition(int a[], int l) //This function adds the first l terms in the array a[] { //It can be used to add the days in first several months int n = 0; //e.g. If the input month is 4 in a non-leap year, int s = 0; //the output would be 31 + 28 + 31 + 30 while ((n < l) && (n < 12)) { s = s + a[n]; n++; } return s; } int leapYearClearer(int n) //This function clears out the mistake caused by some special { //non-leap years such as 1900 int i = 0; //This would be used to subtract the non-existing days in those years int s = 0; while(i <= n) { if ((i % 100 == 0) && (i % 400 != 0)) s++; i++; } return s; } bool leapYearChecker(int n) //This function simply checks if a year is a leap year { if((n % 400 == 0) || ((n % 4 == 0) && (n % 100 != 0))) return true; else return false; } bool datesSignChecker(int a, int b, int c, int d, int e, int f) //This checks the validity of the signs of the input { //Apparently, they all must be positive! int list[] = {a, b, c, d, e, f}; int i = 0; while (i < 6) { if (list[i] <= 0) return false; i++; } return true; } bool datesUpperLimitChecker(int year, int month, int day) //This checks the validity of the input in case they are too large { //e.g. There is not a 13th month in a year nor a 32nd day in a month int daysInMonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (leapYearChecker(year)) daysInMonths[1] = daysInMonths[1] + 1; if (month > 12) return false; if (day > daysInMonths[month - 1]) return false; return true; } long int daysBetweenDates(int year1, int month1, int day1, int year2, int month2, int day2) //Haha, here goes the main one! { //This function calculates the days1 between 01/01/0001 and date1(year1, month1, day1) if (!datesSignChecker(year1, month1, day1, year2, month2, day2)) //also the days2 between 01/01/0001 and date2 { //To get the difference, simply find days2 - days1 std::cout << "Error: The value of year/month/day must be positive!\n"; return -1; } if (!datesUpperLimitChecker(year1, month1, day1) || !datesUpperLimitChecker(year2, month2, day2)) { std::cout << "Error: The value of month/day is out of valid range!\n"; return -1; } int daysInMonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; long int daysInYear1 = ((year1 - 1) / 4) * 1461 + ((year1 - 1) % 4) * 365 - leapYearClearer(year1 - 1); long int daysInYear2 = ((year2 - 1) / 4) * 1461 + ((year2 - 1) % 4) * 365 - leapYearClearer(year2 - 1); int daysInMonth1 = addition(daysInMonths, month1 - 1); int daysInMonth2 = addition(daysInMonths, month2 - 1); if (leapYearChecker(year1) && month1 > 2) daysInMonth1++; if (leapYearChecker(year2) && month2 > 2) daysInMonth2++; long int days1 = daysInYear1 + daysInMonth1 + day1; long int days2 = daysInYear2 + daysInMonth2 + day2; long int result = days2 - days1; std::cout << "The number of days between the two dates is:" << result << std::endl; return result; }
/* -*- Mode: c++; tab-width: 4; 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. */ #include "core/pch.h" #include "modules/pi/OpUAComponentManager.h" #include "platforms/mac/pi/MacOpSystemInfo.h" class MacOpUAComponentManager : public OpUAComponentManager { public: const char * GetOSString(Args &args) { return ((MacOpSystemInfo*)g_op_system_info)->GetOSStr(args.ua); } }; OP_STATUS OpUAComponentManager::Create(OpUAComponentManager **target_pp) { RETURN_OOM_IF_NULL(*target_pp = OP_NEW(MacOpUAComponentManager, ())); return OpStatus::OK; }
#include <iostream> #include <string.h> using namespace std; void combination(char str[],int n,int l) { int ctr=0; char temp; for(int i=l;i<n-1;++i) { for(int j=i+1;j<n;++j) { temp=str[i]; str[i]=str[j]; str[j]=temp; combination(str,n,i+1); temp=str[i]; str[i]=str[j]; str[j]=temp; } } cout<<str<<"\n"; } int fact(int n) { int fact=1; for(int i=n;i>0;i--) { fact*=i; } return fact; } int main() { char str[20]; cout<<"Enter string\n"; cin>>str; int n; n=strlen(str); cout<<fact(n)<<endl; combination(str,n,0); return 0; }
#pragma once #include "base_trie_decl.hpp" #include "iterator_base_decl.hpp" #include <memory> struct base_trie::trie_node final { trie_node() = default; explicit trie_node(trie_node* parent_node_ptr); template<class... Args> void set_value(Args&& ...args); bool operator==(trie_node const& rsh) const; template<class Key> iterator begin(Key&& sub_key); template<class Key> const_iterator begin(Key&& sub_key) const; iterator end(); const_iterator end() const; template<class Key, class... ValueArgs> std::pair<iterator, bool> try_emplace(Key&& key, ValueArgs&&... value_args); iterator find(key_type const& prefix, key_type const& key); const_iterator find(key_type const& prefix, key_type const& key) const; trie_node* try_find_node(key_type const& key); trie_node const* try_find_node(key_type const& key) const; iterator erase(iterator position); size_t erase(key_type const& key); ~trie_node() = default; void clear_value(); bool is_leaf() const; bool has_value() const; value_type& get_value(); value_type const& get_value() const; node_map children{}; node_map_it to_self{}; trie_node* parent = nullptr; std::unique_ptr<value_type> value_ptr{}; };