text
stringlengths
8
6.88M
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gmock/gmock-generated-matchers.h> #include <gmock/gmock-matchers.h> #include <gtest/gtest.h> #include "CallstackData.h" MATCHER(CallstackEventEq, "") { const orbit_client_protos::CallstackEvent& a = std::get<0>(arg); const orbit_client_protos::CallstackEvent& b = std::get<1>(arg); return a.time() == b.time() && a.callstack_hash() == b.callstack_hash() && a.thread_id() == b.thread_id(); } TEST(CallstackData, FilterCallstackEventsBasedOnMajorityStart) { CallstackData callstack_data; const int32_t tid = 42; const int32_t tid_with_broken_only = 43; const int32_t tid_without_supermajority = 44; const uint64_t cs1_outer = 0x10; const uint64_t cs1_inner = 0x11; const CallStack cs1{{cs1_inner, cs1_outer}}; const uint64_t hash1 = cs1.GetHash(); callstack_data.AddUniqueCallStack(cs1); const uint64_t cs2_outer = 0x10; const uint64_t cs2_inner = 0x21; const CallStack cs2{{cs2_inner, cs2_outer}}; const uint64_t hash2 = cs2.GetHash(); callstack_data.AddUniqueCallStack(cs2); const uint64_t broken_cs_outer = 0x30; const uint64_t broken_cs_inner = 0x31; const CallStack broken_cs{{broken_cs_inner, broken_cs_outer}}; const uint64_t broken_hash = broken_cs.GetHash(); callstack_data.AddUniqueCallStack(broken_cs); const uint64_t time1 = 100; orbit_client_protos::CallstackEvent event1; event1.set_time(time1); event1.set_thread_id(tid); event1.set_callstack_hash(hash1); callstack_data.AddCallstackEvent(event1); const uint64_t time2 = 200; orbit_client_protos::CallstackEvent event2; event2.set_time(time2); event2.set_thread_id(tid); event2.set_callstack_hash(broken_hash); callstack_data.AddCallstackEvent(event2); const uint64_t time3 = 300; orbit_client_protos::CallstackEvent event3; event3.set_time(time3); event3.set_thread_id(tid); event3.set_callstack_hash(hash2); callstack_data.AddCallstackEvent(event3); const uint64_t time4 = 400; orbit_client_protos::CallstackEvent event4; event4.set_time(time4); event4.set_thread_id(tid); event4.set_callstack_hash(hash1); callstack_data.AddCallstackEvent(event4); const uint64_t time5 = 500; orbit_client_protos::CallstackEvent event5; event5.set_time(time5); event5.set_thread_id(tid_with_broken_only); event5.set_callstack_hash(broken_hash); callstack_data.AddCallstackEvent(event5); const uint64_t time6 = 600; orbit_client_protos::CallstackEvent event6; event6.set_time(time6); event6.set_thread_id(tid_without_supermajority); event6.set_callstack_hash(hash1); callstack_data.AddCallstackEvent(event6); const uint64_t time7 = 700; orbit_client_protos::CallstackEvent event7; event7.set_time(time7); event7.set_thread_id(tid_without_supermajority); event7.set_callstack_hash(broken_hash); callstack_data.AddCallstackEvent(event7); callstack_data.FilterCallstackEventsBasedOnMajorityStart(); EXPECT_THAT( callstack_data.GetCallstackEventsOfTidInTimeRange(tid, 0, std::numeric_limits<uint64_t>::max()), testing::Pointwise(CallstackEventEq(), std::vector<orbit_client_protos::CallstackEvent>{event1, event3, event4})); EXPECT_THAT(callstack_data.GetCallstackEventsOfTidInTimeRange( tid_with_broken_only, 0, std::numeric_limits<uint64_t>::max()), testing::Pointwise(CallstackEventEq(), std::vector<orbit_client_protos::CallstackEvent>{event5})); EXPECT_THAT(callstack_data.GetCallstackEventsOfTidInTimeRange( tid_without_supermajority, 0, std::numeric_limits<uint64_t>::max()), testing::Pointwise(CallstackEventEq(), std::vector<orbit_client_protos::CallstackEvent>{event6, event7})); }
/* * License: * License does not expire. * Can be distributed in infinitely projects * Can be distributed and / or packaged as a code or binary product (sublicensed) * Commercial use allowed under the following conditions : * - Crediting the Author * Can modify source-code */ /* * File: IndexBuffer.cpp * Author: Suirad <darius-suirad@gmx.de> * * Created on 14. Januar 2018, 16:38 */ #include <GL/glew.h> #include "IndexBuffer.h" IndexBuffer::IndexBuffer() { } IndexBuffer::IndexBuffer(unsigned int id, int size) : id(id), size(size) { } void IndexBuffer::bind() { //Bind Indice Buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); } void IndexBuffer::unbind() { //Bind Indice Buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } IndexBuffer::~IndexBuffer() { }
////////////////////////////////////////////////////////////////////////// // Bwindows.cpp:编写 Windows 程序常用的一些自定义函数和类的实现 // 类包括: // CBApp 类: 管理应用程序全局信息 // CBHashLK:长整数型 key 的哈希表类 // CBHashStrK:字符串型 key 的哈希表类 // CBRecycledArr:带回收站的数组类 // CBRecycledArrInt:整型版带回收站的数组类 // CHeapMemory: 用全局对象维护所有通过 new 分配的内存指针 // 同时包含 CBHashLKCBHeapMemory 类的全局对象 HM 的定义 // CBApp 类全局 pApp 指针的定义 // ////////////////////////////////////////////////////////////////////////// #include "Bwindows.h" #include <tchar.h> #include <stdio.h> // 使用 _vsntprintf 等 #include <memory.h> // 全局 App 对象的指针所指向的对象用于获得本程序的某些程序信息, // 如 hInstance 等。必须同时包含 BForm 模块才能使用它获得正确信息 // 其所指对象的属性为常量,该指针所指对象的属性不能被改变 // 在全局 App 对象的构造函数中,用成员初始化表给其中的常成员赋值 CBApp *pApp=0; // 全局对象HM的定义 // 管理程序中所有以 new 开辟的内存指针,该对象析构时可自动 delete 这些内存 // Bwindows.h 中有此全局对象的声明,任何模块包含 Bwindows.h 即可使用此全局对象 CBHeapMemory HM; // 共用空间供字符串函数容错使用: //(gEmptyTSTR用于兼容Unicode和Ansi;gEmptySTR仅用于Ansi;gEmptyWSTR 仅用于 Unicode) // 出错时(如指针为0),容错返回空字符串,就返回此空间的内容 // 此空间在 BWindows.h 中未作声明,其他模块不得使用 TCHAR gEmptyTSTR[1]; char gEmptySTR[1]; WCHAR gEmptyWSTR[1]; ////////////////////////////////////////////////////////////////////////// // 常用自定义函数 // ////////////////////////////////////////////////////////////////////////// // 弹出消息框 // 如 title 为 NULL,就自动使用应用程序名作为 title EDlgBoxCmdID MsgBox(LPCTSTR szPrompt, LPCTSTR szTitle, EMsgBoxBtn buttons, EMsgBoxIcon icon, EDlgBoxDefBtn defBtn, bool bSystemModal, bool bHelpButton, bool bRightJustified, bool bRightToLeftReading) { UINT uType; if (szTitle == NULL) { // 如果 title 为 NULL,就获得应用程序名作为 title TCHAR fName[2048] = {0}; TCHAR * slash, * dot; // 获得应用程序名 if (GetModuleFileName(0, fName, sizeof(fName)) == 0) { // 获得应用程序名失败 szTitle=TEXT("Message"); // 标题使用 "Message" } else // if (GetModuleFileName(0, fName, 2048) == 0) { // 获得应用程序名成功 szTitle = fName; // 先设置为完整应用程序名,下面再提取其中文件名部分 // 如果提取文件名部分失败,仍使用完整的应用程序名 // 查找最后一个 '\\' slash=fName; while(*slash) slash++; while(*slash != TCHAR('\\') && slash>=fName) slash--; if (slash>=fName) { // 截取从 slash + 1 开始到最后一个 '.' 之前的部分为文件主名 szTitle = slash + 1; // 先设置截取从 '\\' 后到末尾的部分, // 下面再查找 '.',如果查找 '.' 失败, // 仍使用从 '\\' 后到末尾的部分 // 查找 slash + 1 后的最后一个 '.' dot = slash+1; while(*dot) dot++; while(*dot != TCHAR('.') && dot>slash+1) dot--; if (*dot == TCHAR('.')) * dot = '\0'; // 查找 '.' 成功,将 '.' 的位置 // 改为 '\0' 使截断字符串 } // end if (slash) } // end if (GetModuleFileName(0, fName, 2048) == 0) } // end if (title == NULL) uType = buttons + icon + defBtn; uType += MB_TASKMODAL; // hWnd == 0 时,添加 MB_TASKMODAL // 以使当前线程所属的顶层窗口都被禁用 if (bSystemModal) { // hWnd == 0 时,用 MB_TASKMODAL;否则用 MB_SYSTEMMODAL uType += MB_TOPMOST; } if (bHelpButton) uType += MB_HELP; if (bRightJustified) uType += MB_RIGHT; if (bRightToLeftReading) uType += MB_RTLREADING; return (EDlgBoxCmdID)MessageBox(0, szPrompt, szTitle, uType); } // 将一个整数转换为八进制的字符串,字符串空间自动管理 LPTSTR Oct(long number) { return StrPrintf(TEXT("%o"), number); } // 将一个整数转换为十六进制的字符串,字符串空间自动管理 LPTSTR Hex(long number) { return StrPrintf(TEXT("%X"), number); } LPTSTR CurDir() { LPTSTR curDirBuff = new TCHAR[1024]; HM.AddPtr(curDirBuff); GetCurrentDirectory(1024, curDirBuff); return curDirBuff; } unsigned char * LoadResData( UINT idRes, UINT typeRes, unsigned long * rSize/*=0*/ ) { return LoadResData(MAKEINTRESOURCE(idRes), MAKEINTRESOURCE(typeRes), rSize); } unsigned char * LoadResData( UINT idRes, LPCTSTR typeRes, unsigned long * rSize/*=0*/ ) { return LoadResData(MAKEINTRESOURCE(idRes), typeRes, rSize); } unsigned char * LoadResData( LPCTSTR idRes, UINT typeRes, unsigned long * rSize/*=0*/ ) { return LoadResData(idRes, MAKEINTRESOURCE(typeRes), rSize); } unsigned char * LoadResData( LPCTSTR idRes, LPCTSTR typeRes, unsigned long * rSize/*=0*/ ) { HRSRC hRes = FindResource(0, idRes, typeRes); if (rSize) *rSize = SizeofResource(0, hRes); HGLOBAL hGlob = LoadResource(0, hRes); return (unsigned char *)LockResource(hGlob); } ////////////////////////////////////////////////////////////////////////// // 时间 函数 ////////////////////////////////////////////////////////////////////////// // 返回当前系统日期、时间的一个字符串 // 若 lpDblTime 不为0,还将还将当前系统日期、时间转换为 double // (为1601-1-1以来经历的毫秒数)存入它指向的 double 型变量中 // 若 lpTime 不为0,还将当前系统日期、时间存储到它指向的结构中 LPTSTR Now( double *lpDblTime/*=0*/, SYSTEMTIME *lpTime/*=0*/ ) { SYSTEMTIME st; GetLocalTime(&st); if (lpTime) *lpTime = st; if (lpDblTime) *lpDblTime = DateTimeDbl(st); return StrPrintf(TEXT("%d-%d-%d %02d:%02d:%02d"), // %02d:不足2位的数字前加0而非加空格补足2位 st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); } // 设置当前系统日期、时间 BOOL NowSet( SYSTEMTIME stNow ) { return SetLocalTime (&stNow); } // 将一个日期、时间转换为 double 返回(为1601-1-1以来经历的毫秒数) double DateTimeDbl( SYSTEMTIME stDatetime ) { FILETIME ft; SystemTimeToFileTime(&stDatetime, &ft); return ((double)ft.dwLowDateTime + 4294967296.0 * ft.dwHighDateTime)/1e4; } // 计算两个日期、时间的时间间隔 double DateDiff( eDataTimeDiffStyle style, SYSTEMTIME stDatetime1, SYSTEMTIME stDatetime2 ) { double diff=DateTimeDbl(stDatetime2)-DateTimeDbl(stDatetime1); switch (style) { case edtYearDiff: diff /= 365; // 继续向下执行其他 case 的语句 case edtMonthDiff: diff /= 12; // 继续向下执行其他 case 的语句 case edtDayDiff: diff /= 24; // 继续向下执行其他 case 的语句 case edtHourDiff: diff /= 60; // 继续向下执行其他 case 的语句 case edtMinuteDiff: diff /= 60; // 继续向下执行其他 case 的语句 case edtSecondDiff: diff /= 1000; // 继续向下执行其他 case 的语句 case edtMilliseconds: break; } return diff; } ////////////////////////////////////////////////////////////////////////// // 自定义字符串 函数 ////////////////////////////////////////////////////////////////////////// // 以 printf 方式制作一个字符串(字符串空间由本模块自动开辟、自动管理) LPTSTR cdecl StrPrintf( LPCTSTR szFormat, ... ) { if (szFormat==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 // 开辟保存结果字符串的空间 lpszResult TCHAR * lpszResult = new TCHAR [2048]; HM.AddPtr(lpszResult); // 将该新分配的内存指针保存到 HM 以自动管理 va_list pArgList; va_start(pArgList, szFormat); _vsntprintf(lpszResult, 2047, szFormat, pArgList); va_end(pArgList); return lpszResult; } // 取字符串的前 length 个字符组成新字符串(使用Unicode时1个汉字算1个长度, // 使用ANSI时1个汉字算2个长度) // 本函数动态开辟保存新字符串的空间,并自动维护此空间(由全局 HM 管理) // 函数返回新字符串的首地址 // length超过字符串长度时返回整个字符串,length<=0 时返回 指向 '\0' (空串)的指针 LPTSTR Left(LPCTSTR szStringSrc, int length) // LPCTSTR 就是 const TCHAR * { if (szStringSrc==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 int lenSrc = lstrlen(szStringSrc); // 将要截取的部分长度 length 限定在 0~字符串最大长度 if (length < 1) length = 0; if (length > lenSrc) length = lenSrc; // 开辟保存结果字符串的空间 lpszResult TCHAR * lpszResult = new TCHAR [length+1]; HM.AddPtr(lpszResult); // 将该新分配的内存指针保存到 HM 以自动管理 // 拷贝内容 _tcsncpy(lpszResult, szStringSrc, length); *(lpszResult+length)='\0'; // 结果字符串最后添加 '\0' return lpszResult; } // 取字符串的后 length 个字符组成新字符串(使用Unicode时1个汉字算1个长度, // 使用ANSI时1个汉字算2个长度) // 本函数动态开辟保存新字符串的空间,并自动维护此空间(由全局 HM 管理) // 函数返回新字符串的首地址 // length超过字符串长度时返回整个字符串,length<=0 时返回 指向 '\0' (空串)的指针 LPTSTR Right(LPCTSTR szStringSrc, int length) { if (szStringSrc==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 int lenSrc = lstrlen(szStringSrc); // 将要截取的部分长度 length 限定在 0~字符串最大长度 if (length < 1) length = 0; if (length > lenSrc) length = lenSrc; // 开辟保存结果字符串的空间 lpszResult TCHAR * lpszResult = new TCHAR [length+1]; HM.AddPtr(lpszResult); // 将该新分配的内存指针保存到 HM 以自动管理 // 生成结果字符串内容 lstrcpy(lpszResult, szStringSrc+lenSrc-length); return lpszResult; } // 取字符串的从第 startPos 个字符起,长 length 个字符组成的字符串(第一个字符位置为1, // 使用Unicode时1个汉字算1个长度,使用ANSI时1个汉字算2个长度) // 本函数动态开辟保存新字符串的空间,并自动维护此空间(由全局 HM 管理) // 函数返回新字符串的首地址 // startPos+length-1 超过字符串长度时返回整个字符串,length<=0 时 // 或 startPos<=0 或 startPos>源字符串长度 时返回指向 '\0' (空串)的指针 LPTSTR Mid(LPCTSTR szStringSrc, int startPos, int length) { if (szStringSrc==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 int lenSrc = lstrlen(szStringSrc); // 将要截取的起始位置 startPos 限定在 1~字符串最大长度+1, // 当 startPos 为“字符串最大长度+1”时,截取到的为 "" if (startPos < 1 || startPos>lenSrc) startPos = lenSrc+1; // 将要截取的部分从 startPos 开始、长度为 length 限定在 // 字符串长度范围之内(调整 length) if (length < 1) length = 0; if (startPos+length-1 > lenSrc) length = lenSrc-startPos+1; // 开辟保存结果字符串的空间 lpszResult TCHAR * lpszResult = new TCHAR [length+1]; HM.AddPtr(lpszResult); // 该新分配的内存指针保存在 HM // 拷贝内容 _tcsncpy(lpszResult, szStringSrc+startPos-1, length); *(lpszResult+length)='\0'; // 结果字符串最后添加 '\0' return lpszResult; } LPTSTR LTrim( LPCTSTR szStringSrc, bool bDelOtherSpace/*=false*/ ) { if (szStringSrc==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 // 开辟保存结果字符串的空间 lpszResult,拷贝内容 TCHAR * lpszResult = new TCHAR [lstrlen(szStringSrc)+1]; HM.AddPtr(lpszResult); // 该新分配的内存指针保存在 HM // 在新字符串中执行删除 TCHAR *p=(TCHAR *)szStringSrc; while (*p && (*p == TEXT(' ') || (bDelOtherSpace && _istspace(*p))) ) p++; // 指向源字符串的第一个非空格 _tcscpy(lpszResult, p); // 从 p 的位置拷贝字符串 // 返回新字符串 return lpszResult; } LPTSTR RTrim( LPCTSTR szStringSrc, bool bDelOtherSpace/*=false*/ ) { if (szStringSrc==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 // 开辟保存结果字符串的空间 lpszResult,拷贝内容 TCHAR * lpszResult = new TCHAR [lstrlen(szStringSrc)+1]; HM.AddPtr(lpszResult); // 该新分配的内存指针保存在 HM _tcscpy(lpszResult, szStringSrc); // 在新字符串中执行删除 TCHAR *p=(TCHAR *)lpszResult; while (*p) p++; p--; // 指向最后一个字符 while (*p==TEXT(' ') || (bDelOtherSpace && _istspace(*p))) p--; p++; *p=0; // 返回新字符串 return lpszResult; } LPTSTR Trim( LPCTSTR szStringSrc, bool bDelOtherSpace/*=false*/ ) { if (szStringSrc==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 // 开辟保存结果字符串的空间 lpszResult,拷贝内容 TCHAR * lpszResult = new TCHAR [lstrlen(szStringSrc)+1]; HM.AddPtr(lpszResult); // 该新分配的内存指针保存在 HM // 在新字符串中执行删除前导空格 TCHAR *p=(TCHAR *)szStringSrc; while (*p && (*p==TEXT(' ') || (bDelOtherSpace && _istspace(*p))) ) p++; // 指向源字符串的第一个非空格 _tcscpy(lpszResult, p); // 从 p 的位置拷贝字符串 // 在新字符串中执行删除尾部空格 p=(TCHAR *)lpszResult; while (*p) p++; p--; // 指向最后一个字符 while (*p==TEXT(' ') || (bDelOtherSpace && _istspace(*p))) p--; p++; *p=0; // 返回新字符串 return lpszResult; } // 在 szSrc 中,从第 start 个字符开始(第一个字符位置为1), // 查找字符串 szFind 的第一次出现的位置(第一个字符位置为1), // 找到返回值>0,没找到返回0 // 说明:本函数未调用任何库函数(strlen也未调用),提高了运行效率 int InStr(int start, LPCTSTR szSrc, LPCTSTR szFind, eBStrCompareMethod compare/*=bcmTextCompare*/) { TCHAR * pSrcCompPos = (TCHAR *)(szSrc + start - 1); // 源字符串中开始比较的位置(地址) if ( szSrc==0 || szFind==0 ) return 0; // 要被查找的字符串为空串(szSrc 指向 '\0'),返回 0 if (*szSrc == 0) return 0; // 要查找的内容为空串(szFind 指向 '\0'),返回 start if (*szFind == 0) return start; // 通过移动指针 pSrcComp 到源字符串的末尾,扫描源字符串 while (*pSrcCompPos) { // ------------------------------------------------------------------------ // 比较源字符串从 pSrcCompPos 开始的一段内容,是否与 stringFind 字符串相同 // ------------------------------------------------------------------------ TCHAR *p1, *p2; p1 = pSrcCompPos; // 源字符串从 pSrcCompPos 开始逐字符扫描 p2 = (TCHAR *)szFind; // 查找字符串从 szFind 开始逐字符扫描 // 如果 源字符串 和 查找字符串 都未到末尾,就继续逐个字符比较 while (*p1 && *p2) { // 获得要比较的两个字符,=> c1、c2 TCHAR c1= *p1, c2= *p2; // 通过将 *p1、*p2 内容存入变量,避免以后反复进行 * 运算,提高运行效率 if (compare == bcmTextCompare) { // 若不区分大小写比较,现在将 c1、c2 统一为大写 if (c1>='a' && c1<='z') c1-=32; if (c2>='a' && c2<='z') c2-=32; } // 如果 c1、c2 不相等,就跳出内层 while if (c1 != c2) break; // 比较下一个字符 p1++; p2++; } // end while (*p1 && *p2) // 跳出内层 while 循环分三种情况: // (1) 查找字符串 到达末尾,此时不论 源字符串 是否到达末尾:表示已经找到 // (2) 源字符串 到达末尾,但查找字符串没有到达末尾:表示没有找到 // (3) 源字符串 和 目标字符串 都没有到达末尾,说明是由 break 跳出的:表示没有找到 // 只有在第 (1) 种情况(已经找到)时函数返回,其它两种情况都继续从源字符串的下一个位置开始查找 if (*p2 == 0) { // 第 (1) 种情况:查找字符串 到达末尾 // 函数返回,任务完成 return pSrcCompPos - szSrc + 1; } // ------------------------------------------------------------------------ // 在源字符串中向后移动一个比较位置 // ------------------------------------------------------------------------ pSrcCompPos++; } // end while (*pSrcCompPos) // 没有找到 return 0; } int InStr(LPCTSTR szSrc, // InStr 的重载版 LPCTSTR szFind, eBStrCompareMethod compare/*=bcmBinaryCompare*/) { return InStr(1, szSrc, szFind, compare); } // 在 szSrc 中,从第 start 个字符开始(第一个字符位置为1)到末尾的部分, // 查找字符串 szFind 的倒数第一次出现的位置(第一个字符位置为1), // 找到返回值>0,没找到返回0 // 说明:本函数未调用任何库函数(strlen也未调用),提高了运行效率 int InStrRev(LPCTSTR szSrc, LPCTSTR szFind, int start/*=1*/, eBStrCompareMethod compare/*=bcmTextCompare*/) { TCHAR * pSrcCompStartPos = (TCHAR *)(szSrc + start - 1); // 源字符串中开始比较的位置(地址) TCHAR * pSrcCompPos = pSrcCompStartPos; if ( szSrc==0 || szFind==0 ) return 0; // 要被查找的字符串为空串(szSrc 指向 '\0'),返回 0 if (*szSrc == 0) return 0; // 要查找的内容为空串(szFind 指向 '\0'),返回 start if (*szFind == 0) return start; // 移动指针 pSrcComp 到最后一个字符 while (*pSrcCompPos) pSrcCompPos++; pSrcCompPos--; // 通过向前移动指针 pSrcComp 到源字符串的 pSrcCompStartPos,扫描源字符串 while (pSrcCompPos>=pSrcCompStartPos) { // ------------------------------------------------------------------------ // 比较源字符串从 pSrcCompPos 开始的一段内容,是否与 stringFind 字符串相同 // ------------------------------------------------------------------------ TCHAR *p1, *p2; p1 = pSrcCompPos; // 源字符串从 pSrcCompPos 开始逐字符扫描 p2 = (TCHAR *)szFind; // 查找字符串从 szFind 开始逐字符扫描 // 如果 源字符串 和 查找字符串 都未到末尾,就继续逐个字符比较 while (*p1 && *p2) { // 获得要比较的两个字符,=> c1、c2 TCHAR c1= *p1, c2= *p2; // 通过将 *p1、*p2 内容存入变量,避免以后反复进行 * 运算,提高运行效率 if (compare == bcmTextCompare) { // 若不区分大小写比较,现在将 c1、c2 统一为大写 if (c1>='a' && c1<='z') c1-=32; if (c2>='a' && c2<='z') c2-=32; } // 如果 c1、c2 不相等,就跳出内层 while if (c1 != c2) break; // 比较下一个字符 p1++; p2++; } // end while (*p1 && *p2) // 跳出内层 while 循环分三种情况: // (1) 查找字符串 到达末尾,此时不论 源字符串 是否到达末尾:表示已经找到 // (2) 源字符串 到达末尾,但查找字符串没有到达末尾:表示没有找到 // (3) 源字符串 和 目标字符串 都没有到达末尾,说明是由 break 跳出的:表示没有找到 // 只有在第 (1) 种情况(已经找到)时函数返回,其它两种情况都继续从源字符串的下一个位置开始查找 if (*p2 == 0) { // 第 (1) 种情况:查找字符串 到达末尾 // 函数返回,任务完成 return pSrcCompPos - szSrc + 1; } // ------------------------------------------------------------------------ // 在源字符串中向前移动一个比较位置 // ------------------------------------------------------------------------ pSrcCompPos--; } // end while (*pSrcCompPos) // 没有找到 return 0; } // 按分隔字符串 delimiters ,分割一个字符串,生成若干子字符串 // 各 子字符串 的地址由 ptrStrings[] 数组返回,函数返回子字符串的个数 // ptrStrings[] 数组下标从1开始,最大到函数返回值 // limit 限制返回子字符串的最大个数,为 -1 时不限制,将返回所有字符串 // 子字符串内存及 ptrStrings[] 数组内存都由本模块自动分配、自动管理 int Split(LPCTSTR stringSrc, TCHAR ** &ptrStrings, // 一个字符指针数组,数组每个元素为一个子字符串的首地址,数组将在本函数中被分配空间,下标 [0]~[函数返回值],[0]空间不用 LPCTSTR delimiters/*=0*/, // 分隔字符串 int limit/*=-1*/, // limit, 限制返回的子字符串总数,–1表示返回所有的子字符串 eBStrCompareMethod compare/*=bcmBinaryCompare*/) // 发现“分隔字符串”的字符串比较是否区分大小写 { const int cPtrArrExpandPer = 20; // ptrStrings[] 每次扩大的大小 void **ptrArr=0; int iArrUbound=0, iSubstrCount=0; if (stringSrc == 0) { ptrStrings = 0; return 0; } // 定义指针数组的初始大小 Redim(ptrArr, cPtrArrExpandPer); iArrUbound = cPtrArrExpandPer; // 在 stringSrc 字符串中查找下一个 delimiters int pos=1, pos2=0; pos2 = InStr(pos, stringSrc, delimiters, compare); while (pos2) { // 将从 pos 到 pos2 的子字符串,存入 ptrArr[] iSubstrCount++; if (iSubstrCount > iArrUbound) { // 重定义指针数组 ptrArr 的初始大小 Redim(ptrArr, iArrUbound+cPtrArrExpandPer, iArrUbound, true); iArrUbound = iArrUbound+cPtrArrExpandPer; } ptrArr[iSubstrCount] = (void *)Mid(stringSrc, pos, pos2-pos); if (limit>0 && iSubstrCount >= limit) goto FinishSub; // pos 向后移动,查找下一个 delimiters pos = pos2 + lstrlen(delimiters); pos2 = InStr(pos, stringSrc, delimiters, compare); } // 最后一部分 pos2 = lstrlen(stringSrc) + 1; // 将从 pos 到 pos2 的子字符串,存入 ptrArr[] iSubstrCount++; if (iSubstrCount > iArrUbound) { // 重定义指针数组 ptrArr 的初始大小 Redim(ptrArr, iArrUbound+cPtrArrExpandPer, iArrUbound, true); iArrUbound = iArrUbound+cPtrArrExpandPer; } ptrArr[iSubstrCount] = (void *)Mid(stringSrc, pos, pos2-pos); FinishSub: // 重定义指针数组 ptrArr 到所需大小,设置 ptrStrings 的返回值 if (iSubstrCount) { Redim(ptrArr, iSubstrCount, iArrUbound, true); HM.AddPtr(ptrArr); // 该新分配的内存指针保存在 mHM ptrStrings = (TCHAR **)ptrArr; } else { // 无子字符串 Erase(ptrArr); ptrStrings = 0; } // 返回子字符串的个数 return iSubstrCount; } // 以 delimiter 连接多个字符串,返回连接好的字符串 // 多个字符串的地址由数组 stringSrcArray[] 给出,将连接 // 数组中从下标 arrayIndexStart 到 arrayIndexEnd 的字符串 // delimiter 为 0 时,默认以 "\0" 连接字符串;否则以字符串 delimiter 连接 // bTailDoubleNull 若为 true,则在结果字符串的最后再加一个'\0'(即最后有两个'\0') // 结果字符串的内存由本模块自动分配、自动管理 LPTSTR Join(TCHAR * stringSrcArray[], const int arrayIndexEnd, LPCTSTR delimiter/*=0*/, const int arrayIndexStart/*=1*/, const bool bTailDoubleNull/*=false*/) { if (stringSrcArray==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 // 获得结果字符串的总长度 => lenResult int lenResult = 0; int lenDelimiter; int i; if (delimiter) lenDelimiter = lstrlen(delimiter); else lenDelimiter = 1; // 字符串中间添加 '\0'(一个字符) for(i=arrayIndexStart; i<=arrayIndexEnd; i++) { if (stringSrcArray[i]==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 lenResult += lstrlen(stringSrcArray[i]); lenResult += lenDelimiter; } lenResult -= lenDelimiter; // 最后一个字符串后面不加 delimiter if (bTailDoubleNull) lenResult += 1; // 如果最后要两个'\0',再加一个长度 // 分配结果字符串的内存空间 TCHAR * stringResult = new TCHAR[lenResult + 1]; // +1为最后的 '\0' 空间(双'\0'时指最后一个'\0') HM.AddPtr(stringResult); // 该新分配的内存指针保存在 HM // 连接字符串 TCHAR *p = stringResult; for(i=arrayIndexStart; i<=arrayIndexEnd; i++) { // 连接 stringSrcArray[i] lstrcpy(p, stringSrcArray[i]); p += lstrlen(stringSrcArray[i]); // 连接 连接字符串 if (i<arrayIndexEnd) // 不在最后一个字符串后连接 delimiter { if (delimiter) { // 以字符串 delimiter 作为连接字符 lstrcpy(p, delimiter); p += lstrlen(delimiter); } else { // 以 '\0' 作为连接字符 *p = '\0'; p++; } } } // 添加结尾的 '\0' if (bTailDoubleNull) {*p = '\0'; p++;} *p = '\0'; // 返回结果字符串指针 return stringResult; } // 连接字符串,生成连接后的长字符串 // 返回连接好的字符串的首地址,自动维护动态空间 // 每次调用可最多连接9个字符串 LPTSTR StrAppend( LPCTSTR str1/*=0*/, LPCTSTR str2/*=0*/, LPCTSTR str3/*=0*/, LPCTSTR str4/*=0*/, LPCTSTR str5/*=0*/, LPCTSTR str6/*=0*/, LPCTSTR str7/*=0*/, LPCTSTR str8/*=0*/, LPCTSTR str9/*=0*/ ) { // 求结果字符串的总长度 => resultStrLen int resultStrLen=0; if (str1) resultStrLen+=_tcslen(str1); if (str2) resultStrLen+=_tcslen(str2); if (str3) resultStrLen+=_tcslen(str3); if (str4) resultStrLen+=_tcslen(str4); if (str5) resultStrLen+=_tcslen(str5); if (str6) resultStrLen+=_tcslen(str6); if (str7) resultStrLen+=_tcslen(str7); if (str8) resultStrLen+=_tcslen(str8); if (str9) resultStrLen+=_tcslen(str9); // 开辟结果字符串的空间 TCHAR * resultStr = new TCHAR[resultStrLen+1]; HM.AddPtr(resultStr); memset(resultStr, 0, resultStrLen+1); // 拷贝连接字符串 if (str1) _tcscat(resultStr, str1); if (str2) _tcscat(resultStr, str2); if (str3) _tcscat(resultStr, str3); if (str4) _tcscat(resultStr, str4); if (str5) _tcscat(resultStr, str5); if (str6) _tcscat(resultStr, str6); if (str7) _tcscat(resultStr, str7); if (str8) _tcscat(resultStr, str8); if (str9) _tcscat(resultStr, str9); // 最后赋值 '\0' *(resultStr + resultStrLen)='\0'; // 返回 return resultStr; } // 将 ANSI 或 UTF8 字符串转换为 Unicode,返回结果字符串首地址 // 参数 bToUTF8orANSI 为 false 时转换 ANSI,为 true 时转换 UTF8 // 结果字符串的内存由本模块自动分配、自动管理 LPWSTR StrConvUnicode(const char * szAnsi, bool bFromUTF8orANSI /*=false*/) // LPWSTR 就是 unsigned short int * { if (szAnsi==0) {gEmptyWSTR[0]=0; return gEmptyWSTR;} // 容错 UINT codePage; WCHAR * wszResult=0; int wLen=0; if (bFromUTF8orANSI) codePage=CP_UTF8; else codePage=CP_ACP; // 获得结果字符串所需字符个数,参数 -1 使函数自动计算 szAnsi 的长度 wLen = MultiByteToWideChar(codePage, 0, szAnsi, -1, NULL, 0); // 分配结果字符串的空间 wszResult = new WCHAR [wLen+1]; HM.AddPtr(wszResult); // 转换 MultiByteToWideChar(codePage, 0, szAnsi, -1, wszResult, wLen); wszResult[wLen]='\0'; return wszResult; } // 将 Unicode 字符串转换为 ANSI 或 UTF8,返回结果字符串首地址 // 参数 bToUTF8orANSI 为 false 时转换为 ANSI,为 true 时转换为 UTF8 // 结果字符串的内存由本模块自动分配、自动管理 char * StrConvFromUnicode(LPCWSTR szUnicode, bool bToUTF8orANSI /*=false*/ ) { if (szUnicode==0) {gEmptySTR[0]=0; return gEmptySTR;} // 容错 UINT codePage; char * szResult=0; int aLenBytes=0; if (bToUTF8orANSI) codePage=CP_UTF8; else codePage=CP_ACP; // 获得结果字符串所需字符个数,参数 -1 使函数自动计算 szUnicode 的长度 aLenBytes=WideCharToMultiByte(codePage, 0, szUnicode, -1, NULL, 0, NULL, NULL); // 分配结果字符串的空间 szResult = new char [aLenBytes]; HM.AddPtr(szResult); // 转换:用 aLenBytes 因函数需要的是字节数非字符数 WideCharToMultiByte(codePage, 0, szUnicode, -1, szResult, aLenBytes, NULL, NULL); return szResult; } double Val( LPCWSTR stringVal ) { if (stringVal==0) {return 0;} // 容错 return atof(StrConvFromUnicode(stringVal, false)); } double Val( LPCSTR stringVal ) { if (stringVal==0) {return 0;} // 容错 return atof(stringVal); } LPTSTR Str(char character) { LPTSTR buff=new TCHAR [10]; HM.AddPtr(buff); // 用 HM 管理动态空间 _stprintf(buff, TEXT("%c"), character); return buff; } LPTSTR Str(unsigned short int number) // TCHAR { LPTSTR buff=new TCHAR [20]; HM.AddPtr(buff); // 用 HM 管理动态空间 #ifdef UNICODE *buff=number; // 按字符串的方式输出一个字符 *(buff+1)='\0'; // 须用 TEXT 宏赋值字符,例TCHAR tch=TEXT('汉'); #else _stprintf(buff, TEXT("%u"), number); #endif return buff; } LPTSTR Str(int number) { LPTSTR buff=new TCHAR [20]; HM.AddPtr(buff); // 用 HM 管理动态空间 _stprintf(buff, TEXT("%d"), number); return buff; } LPTSTR Str(unsigned int number) { LPTSTR buff=new TCHAR [20]; HM.AddPtr(buff); // 用 HM 管理动态空间 _stprintf(buff, TEXT("%u"), number); return buff; } LPTSTR Str(unsigned long number) { LPTSTR buff=new TCHAR [20]; HM.AddPtr(buff); // 用 HM 管理动态空间 _stprintf(buff, TEXT("%lu"), number); return buff; } LPTSTR Str(float number) { LPTSTR buff=new TCHAR [40]; HM.AddPtr(buff); // 用 HM 管理动态空间 _stprintf(buff, TEXT("%.7g"), number); return buff; } LPTSTR Str(double number) { LPTSTR buff=new TCHAR [40]; HM.AddPtr(buff); // 用 HM 管理动态空间 _stprintf(buff, TEXT("%.15g"), number); return buff; } LPTSTR Str(long double number) { LPTSTR buff=new TCHAR [40]; HM.AddPtr(buff); // 用 HM 管理动态空间 _stprintf(buff, TEXT("%.15g"), number); return buff; } LPTSTR Str( LPCTSTR str ) // 原样拷贝后返回 { if (str==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 LPTSTR buff =0; buff = new TCHAR [lstrlen(str)+1]; HM.AddPtr(buff); // 用 HM 管理动态空间 _tcscpy(buff, str); return buff; } LPTSTR LCase( LPCTSTR szStringSrc ) { if (szStringSrc==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 // 拷贝一份字符串到 buff LPTSTR buff =0; buff = new TCHAR [lstrlen(szStringSrc)+1]; HM.AddPtr(buff); // 用 HM 管理动态空间 _tcscpy(buff, szStringSrc); // 转换 buff 中的字符串 CharLower(buff); // 返回新字符串(buff) return buff; } LPTSTR UCase( LPCTSTR szStringSrc ) { if (szStringSrc==0) {gEmptyTSTR[0]=0; return gEmptyTSTR;} // 容错 // 拷贝一份字符串到 buff LPTSTR buff =0; buff = new TCHAR [lstrlen(szStringSrc)+1]; HM.AddPtr(buff); // 用 HM 管理动态空间 _tcscpy(buff, szStringSrc); // 转换 buff 中的字符串 CharUpper(buff); // 返回新字符串(buff) return buff; } // 替换字符串 LPTSTR Replace( LPCTSTR szStringSrc, LPCTSTR szFind, LPCTSTR szReplaceWith, int start/*=1*/, int countLimit/*=-1*/, eBStrCompareMethod compare/*=bcmBinaryCompare*/ ) { // ======================== 准备工作 ======================== // 若源字符串指针为0,或源字符串为 "",返回 "" if (szStringSrc == 0) { gEmptyTSTR[0]=0; return gEmptyTSTR; } if (*szStringSrc == 0) { gEmptyTSTR[0]=0; return gEmptyTSTR;} // 若要替换为的子字符串指针为空,设置要替换为的子字符串为空串 if (szReplaceWith == 0) { gEmptyTSTR[0]=0; szReplaceWith=gEmptyTSTR; } // 拷贝一份字符串到 buff // buff 长度至少为 源字符串长度 + 一个 szReplaceWith 的长度 LPTSTR buff = 0; int iFindLen = lstrlen(szFind); int iReplLen = lstrlen(szReplaceWith); int buffLen = lstrlen(szStringSrc) + iReplLen +1; buff = new TCHAR [buffLen]; // 最后再用 HM.AddPtr(buff); 用 HM 管理动态空间,因可能还要扩大空间 _tcscpy(buff, szStringSrc); // 若要查找的子字符串指针为空,或子字符串为 "",返回源字符串 if (szFind == 0) return buff; if (*szFind == 0) return buff; // 设置将来若 buff 空间不足时,扩大空间时的扩大步长 => ibuffLenExpandPer int ibuffLenExpandPer = 200; if (iReplLen > ibuffLenExpandPer) ibuffLenExpandPer=iReplLen; // ======================== 查找和替换 ======================== // 将源字符串中的字符逐一拷贝到 buff; // 但若遇到 szFind,不拷贝 szFind 而拷贝 szReplaceWith TCHAR *p=(TCHAR *)(szStringSrc+start-1), *p1, *p2, *p3; TCHAR *buffWrite=buff; int iReplacedCount=0; while (*p) { // 在源字符串的 p 位置查找是否与 szFind 相等 p1=p; p2=(TCHAR *)szFind; while (*p1 && *p2) { // 获得要比较的两个字符,=> c1、c2 TCHAR c1= *p1, c2= *p2; // 通过将 *p1、*p2 内容存入变量,避免以后反复进行 * 运算,提高运行效率 if (compare == bcmTextCompare) { // 若不区分大小写比较,现在将 c1、c2 统一为大写 if (c1>='a' && c1<='z') c1-=32; if (c2>='a' && c2<='z') c2-=32; } // 如果 c1、c2 不相等,就跳出内层 while if (c1 != c2) break; // 比较下一个字符 p1++; p2++; } // end while (*p1 && *p2) // 跳出内层 while 循环分三种情况: // (1) 查找字符串 到达末尾,此时不论 源字符串 是否到达末尾:表示已经找到 // (2) 源字符串 到达末尾,但查找字符串没有到达末尾:表示没有找到 // (3) 源字符串 和 目标字符串 都没有到达末尾,说明是由 break 跳出的:表示没有找到 // 只有在第 (1) 种情况(已经找到)时需要替换,其它两种情况都直接拷贝源字符串的 *p if (*p2 == 0) { // 第 (1) 种情况:执行替换, // 即拷贝 szReplaceWith 而不拷贝源字符串, // 并调整 p 的位置越过一个 szFind 的长度 p3 = (TCHAR *)szReplaceWith; while (*p3) { *buffWrite = *p3; buffWrite++; p3++; } p += (iFindLen-1); // -1 是因为最外层 while 最后还要执行 p++ // 计数替换次数和判断替换限制条件 iReplacedCount++; if (countLimit>0 && iReplacedCount>=countLimit) break; // 跳出最外层 while } else { // 第 (2)、(3) 种情况:直接拷贝源字符串 *buffWrite = *p; buffWrite++; } // buff 的剩余长度至少要多出一个 szReplaceWith 的长度 if ( buffLen - (buffWrite-buff+1) < iReplLen ) { // 需要扩大 buff // buff 的长度至少要多出一个 szReplaceWith 的长度 int buffSizeLast = buffLen * sizeof(TCHAR); buffLen += ibuffLenExpandPer; // 新空间大小(字符个数) TCHAR *buff2=new TCHAR [buffLen]; // 开辟新空间 HM.CopyMem(buff2, buff, buffSizeLast); // 将老空间内容拷贝到新空间 buffWrite = buff2 + (buffWrite-buff); // 使 buffWrite 指向新空间的相同位置 delete []buff; // 删除老空间 buff = buff2; // 最后会执行 HM.AddPtr(buff); 管理新空间 } // 源字符串指针 p 指向下一字符 p++; } // end while (*p) *buffWrite = '\0'; // ======================== 返回结果 ======================== HM.AddPtr(buff); return buff; } BOOL MsgBeep( EMsgBeep soundStyle/* = mb_SoundSpeaker*/ ) { return MessageBeep(soundStyle); } ////////////////////////////////////////////////////////////////////////// // 自定义 动态数组 函数 ////////////////////////////////////////////////////////////////////////// // template <typename REDIMTYPE> // int Redim( REDIMTYPE * &arr, int uboundCurrent, int toUBound, bool preserve=false ) // template 函数定义要在头文件中 ////////////////////////////////////////////////////////////////////////// // CBApp 类的实现:管理应用程序全局信息 // ////////////////////////////////////////////////////////////////////// CBApp::CBApp( HINSTANCE hInst, HINSTANCE hPrevInst, char * lpCmdLine, int nShowCmd ): hInstance(hInst), CmdShow(nShowCmd) { ; } LPTSTR CBApp::Command() const { return GetCommandLine(); } // 获得应用程序当前运行的路径 LPTSTR CBApp::Path() { if ( GetModuleFileName(0, m_path, sizeof(m_path)) ) { // 找到最后的 \\,下一位置截断 TCHAR *p = m_path; while (*p) p++; while (*p != '\\') p--; p++; *p='\0'; } else { // 获得应用程序名失败,返回 "" m_path[0] = 0; } return m_path; } int CBApp::ScreenWidth() const { return GetSystemMetrics(SM_CXSCREEN); } int CBApp::ScreenHeight() const { return GetSystemMetrics(SM_CYSCREEN); } ////////////////////////////////////////////////////////////////////// // CBHashLK 类的实现: 长整型键值的哈希表 // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Static 常量定值 ////////////////////////////////////////////////////////////////////// const int CBHashLK::mcIniMemSize = 7; // 初始 mem[] 的大小 const int CBHashLK::mcMaxItemCount = 100000000; // 最多元素个数(可扩大此值到 long 表示的范围之内) const float CBHashLK::mcExpandMaxPort = 0.75; // 已有元素个数大于 0.75*memCount 时就扩大 mem[] 的空间 const int CBHashLK::mcExpandCountThres = 10000; // 扩大 mem[] 空间时,若 memCount 小于此值则每次扩大到 memCount*2;若 memCount 大于此值则每次扩大到 Count+Count/2 const int CBHashLK::mcExpandCountThresMax = 10000000; // 扩大 mem[] 空间时,若 memCount 已大于此值,则每次不再扩大到 Count+Count/2,而只扩大到 Count+mcExpandBigPer const int CBHashLK::mcExpandBigPer = 1000000; // 扩大 mem[] 空间时,若 memCount 已大于 mcExpandCountThresMax,则每次不再扩大到到 Count+Count/2,而只扩大到 Count+mcExpandBigPer const int CBHashLK::mcExpandMem2Per = 10; // 每次扩大 mem2[] 的大小 const int CBHashLK::mcSeqMax = 5; // 顺序检索最大值 ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBHashLK::CBHashLK(int memSize/*=0*/) { mArrTable=0; mArrTableCount = -1; // 无缓存数组 memUsedCount = 0; mem2 = 0; memCount2 = 0; memUsedCount2 = 0; if (memSize) { // 初始定义 memSize 个的 mem[] 空间,无 mem2[] 的空间 RedimArrMemType(mem, memSize); memCount = memSize; } else { // 初始定义 mcIniMemSize 个的 mem[] 空间,无 mem2[] 的空间 RedimArrMemType(mem, mcIniMemSize); memCount = mcIniMemSize; } } CBHashLK::~CBHashLK() { Clear(); // Clear() 函数中,重新开辟了初始大小的 mem[] 空间,再将其删除即可 if (mem) delete[] mem; memCount = 0; } ////////////////////////////////////////////////////////////////////// // 公有方法 ////////////////////////////////////////////////////////////////////// void CBHashLK::AlloMem(int memSize ) { /* 程序初始化时只定义了 mcIniMemSize 大小的 l_Mem[],以后随使用随自动扩 \ 大;但若事先知道有多大,可以先用本函数定义足够大以免以后不断 \ 自动扩大费时;注意这时要比预用的元素个数多定义一些,否则分配空间 \ 时若空间冲突本类还会自动扩大 此函数也可用于截断 l_Mem[] 后面没有使用的空间 注:memSize <= memUsedCount 时,拒绝重新定义,以确保数据不会丢失 */ if (memSize <= memUsedCount || memSize > mcMaxItemCount) return; int iPreMemCount; iPreMemCount = memCount; // ReDim Preserve mem(1 To memSize) RedimArrMemType(mem, memSize, memCount, true); memCount = memSize; if (iPreMemCount <= memCount) ReLocaMem(iPreMemCount); else ReLocaMem(memCount); // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; } bool CBHashLK::Add( DataType data, KeyType key/*=0*/, DataLongType dataLong/*=0*/, DataLong2Type dataLong2/*=0*/, LPCTSTR dataStr/*=NULL*/, LPCTSTR dataStr2/*=NULL*/, double dataDouble/*=0.0*/, bool raiseErrorIfNotHas/*=true*/ ) { int idx; // 哈希表中的数据个数最多不能超过 mcMaxItemCount if (memUsedCount + memUsedCount2 >= mcMaxItemCount) { if (raiseErrorIfNotHas) throw (unsigned char)7; // 超出内存 return false; } // 当前哈希表中不能有相同的“键”存在 if (IsKeyExist(key)) { if (raiseErrorIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return false; } // 通过调用 AlloMemIndex 函数获得一个可用空间的下标:idx idx = AlloMemIndex(key); if (idx > 0) { // 获得的下标值为正数时,使用 mem[] 数组的空间 mem[idx].Data = data; mem[idx].DataLong = dataLong; mem[idx].DataLong2 = dataLong2; mem[idx].DataDouble = dataDouble; mem[idx].Key = key; SaveItemString(&(mem[idx].DataStr), dataStr); SaveItemString(&(mem[idx].DataStr2), dataStr2); mem[idx].Used = true; memUsedCount = memUsedCount + 1; } else if (idx < 0) { // 获得的下标值为负数时,使用 mem2[] 数组的空间,_ // 空间下标为 idx 的绝对值 mem2[-idx].Data = data; mem2[-idx].DataLong = dataLong; mem2[-idx].DataLong2 = dataLong2; mem2[-idx].DataDouble = dataDouble; mem2[-idx].Key = key; SaveItemString(&(mem2[-idx].DataStr), dataStr); SaveItemString(&(mem2[-idx].DataStr2), dataStr2); mem2[-idx].Used = true; memUsedCount2 = memUsedCount2 + 1; } else // idx == 0 { if (raiseErrorIfNotHas) throw (unsigned char)9; // 下标越界:无法分配新数据空间 } // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; // 函数返回成功 return true; } CBHashLK::DataType CBHashLK::Item( KeyType key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].Data; else if (idx < 0) return mem2[-idx].Data; else return 0; } CBHashLK::DataLongType CBHashLK::ItemLong( KeyType key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataLong; else if (idx < 0) return mem2[-idx].DataLong; else return 0; } CBHashLK::DataLong2Type CBHashLK::ItemLong2( KeyType key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataLong2; else if (idx < 0) return mem2[-idx].DataLong2; else return 0; } double CBHashLK::ItemDouble( KeyType key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataDouble; else if (idx < 0) return mem2[-idx].DataDouble; else return 0; } LPTSTR CBHashLK::ItemStr( KeyType key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataStr; else if (idx < 0) return mem2[-idx].DataStr; else return 0; } LPTSTR CBHashLK::ItemStr2( KeyType key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataStr2; else if (idx < 0) return mem2[-idx].DataStr2; else return 0; } // 判断一个 Key 是否在当前集合中存在 bool CBHashLK::IsKeyExist( KeyType key ) { int idx; idx = GetMemIndexFromKey(key, false); return (idx != 0); } bool CBHashLK::Remove( KeyType key, bool raiseErrorIfNotHas/*=True*/ ) { int idx; // 调用 GetMemIndexFromKey 函数获得“键”为 Key 的数据所在空间的下标 idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx == 0) return false; else if (idx > 0) { // 哈希表中“键”为 Key 的数据在 mem[] 数组中,下标为 idx mem[idx].Used = false; mem[idx].Key = 0; SaveItemString(&(mem[idx].DataStr), 0); // 第二个参数为0,删除 mem[idx].DataStr 指向的空间,并让 mem[idx].DataStr=0; SaveItemString(&(mem[idx].DataStr2), 0); memUsedCount = memUsedCount - 1; } else { // idx<0 表示:哈希表中“键”为 Key 的数据在 mem2[] 数组中 \ // 下标为 idx 的绝对值 // 删除下标为“-idx”的元素 SaveItemString(&(mem[-idx].DataStr), 0); // 第二个参数为0,删除 mem[-idx].DataStr 指向的空间,并让 mem[-idx].DataStr=0; SaveItemString(&(mem[-idx].DataStr2), 0); for(int i=-idx; i<= - 1; i++) mem2[i] = mem2[i+1]; mem2[memUsedCount2].DataStr=0; // 直接设置为0,因此空间已经传递给上一元素 mem2[memUsedCount2].DataStr2=0; // 直接设置为0,因此空间已经传递给上一元素 memUsedCount2 = memUsedCount2 - 1; } // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; // 函数返回成功 return true; } void CBHashLK::StartTraversal() { // 开始用 NextXXX ... 方法遍历 mTravIdxCurr = 1; } CBHashLK::DataType CBHashLK::NextItem( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 Data // 若 bRetNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].Data; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].Data; } else { bRetNotValid = true; return 0; } } CBHashLK::DataLongType CBHashLK::NextItemLong( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataLong; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataLong; } else { bRetNotValid = true; return 0; } } CBHashLK::DataLong2Type CBHashLK::NextItemLong2( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataLong2; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataLong2; } else { bRetNotValid = true; return 0; } } double CBHashLK::NextItemDouble( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataDouble; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataDouble; } else { bRetNotValid = true; return 0; } } LPTSTR CBHashLK::NextItemStr( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataStr; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataStr; } else { bRetNotValid = true; return 0; } } LPTSTR CBHashLK::NextItemStr2( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataStr2; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataStr2; } else { bRetNotValid = true; return 0; } } CBHashLK::KeyType CBHashLK::NextKey( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 String // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].Key; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].Key; } else { bRetNotValid = true; return 0; } } // 清除所有元素,重定义 mcIniMemSize 个存储空间 void CBHashLK::Clear( void ) { // 清除 按 Index 访问各元素的缓存数组 if (mArrTable) {delete []mArrTable; mArrTable=0;} mArrTableCount=-1; // 删除 mem[] 和 mem2[] 中的每个元素的 字符串数据 指向的空间 int i; for (i=1; i<=memCount; i++) { if (mem[i].DataStr) {delete [] mem[i].DataStr; mem[i].DataStr=0; } if (mem[i].DataStr2) {delete [] mem[i].DataStr2; mem[i].DataStr2=0; } } for (i=1; i<=memCount2; i++) { if (mem2[i].DataStr) {delete [] mem2[i].DataStr; mem2[i].DataStr=0; } if (mem2[i].DataStr2) {delete [] mem2[i].DataStr2; mem2[i].DataStr2=0; } } // 删除 mem[] 和 mem2[] 的空间 delete [] mem; mem=0; delete [] mem2; mem2=0; memCount = 0; memUsedCount = 0; memCount2 = 0; memUsedCount2 = 0; // 重新开辟空间 RedimArrMemType(mem, mcIniMemSize, memCount, false); memCount = mcIniMemSize; mTravIdxCurr = 0; } // 返回共有元素个数 int CBHashLK::Count( void ) { return memUsedCount + memUsedCount2; } ////////////////////////////////////////////////////////////////////// // 私有方法 ////////////////////////////////////////////////////////////////////// void CBHashLK::ReLocaMem( int preMemCountTo ) { /* 重新分配 mem[], mem2[] 的各元素的空间,mem2[] 的某些元素可能被 \ 重新移动到 mem 将修改 memUsedCount,memUsedCount2, memCount2, mem2[] 的值 preMemCountTo 只考虑 mem[1 to preMemCountTo],preMemCountTo 以后的元素被认为 \ 未用,不考虑;但无论如何都考虑 mem2[] 中的所有元素 */ // 将 mem[] 中的已使用元素和 mem2[] 中的所有元素先放入 memUsed[] 中, \ // 把 memUsed[] 定义为足够大,实际 memUsed[] 只使用了 lngUsedCount 个元素 MemType * memUsed; RedimArrMemType(memUsed, preMemCountTo + memUsedCount2); int iUsedCount=0; int i; // 将 mem[] 中已使用的元素存入 memUsed[] for (i=1; i<=preMemCountTo; i++) if (mem[i].Used) { iUsedCount = iUsedCount + 1; memUsed[iUsedCount] = mem[i]; } // 将 mem2[] 中的所有元素存入 memUsed[] for (i=1; i<=memUsedCount2; i++) { iUsedCount = iUsedCount + 1; memUsed[iUsedCount] = mem2[i]; } /* 此时 memUsed[1 To lngUsedCount] 中为所有 mem[] \ 中的已使用元素 和 mem2[] 中的所有元素 */ // 清空 mem,也清空了所有 Used 域 RedimArrMemType(mem, memCount, memCount, false); memUsedCount=0; // memUsedCount 置0,后面随移动随+1 // 清空 mem2,也清空了所有 Used 域 RedimArrMemType(mem2, -1, memCount2, false); memCount2 = 0; memUsedCount2 = 0; // 逐个把 memUsed[1 To lngUsedCount] 中的元素按新数组大小映射下标存入 mem[] int idx; for (i=1; i<=iUsedCount; i++) { idx = AlloMemIndex(memUsed[i].Key, false); if (idx > 0) { mem[idx] = memUsed[i]; mem[idx].Used = 1; memUsedCount = memUsedCount + 1; } else { mem2[-idx] = memUsed[i]; mem2[-idx].Used = 1; memUsedCount2 = memUsedCount2 + 1; } } // 删除临时空间 memUsed delete [] memUsed; memUsed=0; // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; } // 重定义 mem[] 数组大小,扩大 mem[] 的空间 void CBHashLK::ExpandMem( void ) { int iCount, iPreMemCount; // 计算哈希表中共有数据总数 iCount = memUsedCount + memUsedCount2; // 取“共有数据总数”和“当前 mem[] 的空间总数”两者的较大值 if (iCount < memCount) iCount = memCount; // 保存扩增空间之前的、原来的 mem[] 的空间总数 iPreMemCount = memCount; if (iCount<1) iCount=1; // 避免 iCount 为0时,无法扩大空间 if (iCount < mcExpandCountThres) { // 如果数据总数“比较少”,就扩增空间为原来的2倍 iCount = iCount * 2; } else if (iCount < mcExpandCountThresMax) { // 如果数据总数已经“有点多”,就扩增空间为原来的1.5倍 iCount = iCount * 3 / 2; } else { // 如果数据总数“很多”,就扩增 mcExpandBigPer 个空间 iCount = iCount + mcExpandBigPer; } // 重定义数组大小 // ReDim Preserve mem(1 To lngCount) RedimArrMemType(mem, iCount, memCount, true); memCount = iCount; // 按新数组大小,重新安排其中所有数据的新位置,参数中要传递 // 扩增空间之前的、原来的 mem[] 的空间总数 ReLocaMem(iPreMemCount); // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; } int CBHashLK::AlloSeqIdx( int fromIndex, int toIndex ) { /* 找 mem[] 中一个没使用的空间,从 fromIndex 开始, \ 到 toIndex 结束 返回 mem[] 的一个没使用元素的下标,没找到返回 0 */ int i; if (fromIndex <= 0) fromIndex = 1; if (toIndex > memCount) toIndex = memCount; for (i=fromIndex; i<=toIndex; i++) if (! mem[i].Used) return i; return 0; } // 遍历哈希表,将数据存入 mArrTable(),设置 mArrTableCount 为数据个数(返回成功或失败) bool CBHashLK::RefreshArrTable() { int iCount; int i,j; // 计算哈希表中共有数据总数 iCount = memUsedCount + memUsedCount2; mArrTableCount=iCount; if (mArrTableCount<=0) return false; if (mArrTable) {delete []mArrTable; mArrTable=0;} mArrTable=new int [iCount+1]; // 使数组下标从1开始 j=1; for (i=1; i<=memCount; i++) { if (mem[i].Used) { if (j > iCount) return false; mArrTable[j] = i; // 将 哈希表的本数据所在的 mem[] 的下标 i 存入 mArrTable[j] mem[i].Index = j; // 在 哈希表的本数据 的 Index 成员中记录 mArrTable 的下标 j j=j+1; } } for (i=1; i<=memUsedCount2; i++) { if (mem2[i].Used) { if (j > iCount) return false; mArrTable[j] = -i; // 将 哈希表的本数据所在的 mem2[] 的下标 i (取负)存入 mArrTable[j] mem[i].Index = j; // 在 哈希表的本数据 的 Index 成员中记录 mArrTable 的下标 j j=j+1; } } return true; } int CBHashLK::AlloMemIndex( KeyType key, bool CanExpandMem/*=true */ ) { /* 根据 Key 分配一个 mem[] 中的未用存储空间,返回 mem[] 数组下标 如果 Key 是负值,则转换为正数计算它的存储空间 返回负值表不能在 mem[] 中找到空间:返回值的绝对值为 mem2[] 的 \ 下一个可用下标空间(mem2[]自动Redim),以存入 mem2[] 本函数确保返回一个可使用的空间,最差情况返回 mem2[] 中的空间 另:本函数不修改 memUsedCount2 的值,但 redim mem2[] CanExpandMem=true 时,允许本函数自动扩大 mem[],否则不会自动扩大 方法: 1. 先用 Key Mod memCount + 1,此 Index -> idxMod 2. 若上面的元素已经使用,则看Key是否 < cMaxNumForSquare (sqr(2^31)=46340) \ 若 <,则平方 Key,然后 mod memCount + 1; \ 若 >=,则用按位和移位运算,后相加 key 的各个部分,然后 mod memCount + 1 无论哪种情况,此步 Index -> idxSq 3. 用 memCount-idxMod+1 -> idxModRev 4. 用 memCount-idxSq+1 -> idxSqRev 5. 若上面找到的 Index 都被使用了,则看 Count 是否 > \ mcExpandMaxPort*Count,若是,若 CanExpandMem=true, \ 则扩大 mem[] 的存储空间,然后递归本过程,重复 1-4 步 6. 用 idxMod+1,+2,...,+mcSeqMax;用 idxMod-1,-2,...,-mcSeqMax 7. 再没有,返回负值,绝对值为 mem2[] 的下一个可用空间,以存入 mem2[] */ const int cMaxNumForSquare = 46340; int idxMod=0, idxSq=0; int idxModRev=0, idxSqRev=0; int iCount=0; int keyToCalc=key; // 计算用 Key,永远为>0的数 keyToCalc = key; if (keyToCalc < 0) keyToCalc = 0 - keyToCalc; // 如果 Key 是负值,则转换为正数计算它的存储空间 iCount = memUsedCount + memUsedCount2; if (memCount) { // 1: 先用 Key Mod memCount + 1,此 Index -> idxMod idxMod = keyToCalc % memCount + 1; if (! mem[idxMod].Used) return idxMod; // 2: 用 平方Key 后再除法取余,此 Index -> idxSq if (keyToCalc <= cMaxNumForSquare) { idxSq = (keyToCalc * keyToCalc) % memCount + 1; } else { int kBitSum=0; kBitSum = (keyToCalc & 0xFFFF0000)>>16; kBitSum += (keyToCalc & 0xFF00)>>8; kBitSum += (keyToCalc & 0xF0)>>4; kBitSum += (keyToCalc & 0xF); idxSq = kBitSum % memCount + 1; } if (! mem[idxSq].Used) return idxSq; // 3: 尝试倒数第 idxMod 个空间 -> idxModRev idxModRev = memCount - idxMod + 1; if (! mem[idxModRev].Used) return idxModRev; // 4: 尝试倒数第 idxSq 个空间 -> idxSqRev idxSqRev = memCount - idxSq + 1; if (! mem[idxSqRev].Used) return idxSqRev; } // 5: 如果空间使用百分比超过阈值,就扩大 mem[] 的 空间 if (CanExpandMem && iCount > mcExpandMaxPort * memCount) { ExpandMem(); // 扩大 mem[] 的空间 return AlloMemIndex(key, CanExpandMem); // 递归,重复1-4步 } int lngRetIdx; // 6: 从 idxMod 开始向前、向后线性搜索 mcSeqMax 个空间 int idxMdSta, idxMdEnd; idxMdSta = idxMod - mcSeqMax; idxMdEnd = idxMod + mcSeqMax; lngRetIdx = AlloSeqIdx(idxMdSta, idxMod - 1); if (lngRetIdx > 0) return lngRetIdx; lngRetIdx = AlloSeqIdx(idxMod + 1, idxMdEnd); if (lngRetIdx > 0) return lngRetIdx; // 8: 返回负值,绝对值为 mem2[] 的下一个元素,以存入 mem2[] if (memUsedCount2 + 1 > memCount2) { // ReDim Preserve mem2(1 To mcExpandMem2Per) RedimArrMemType(mem2, memCount2 + mcExpandMem2Per, memCount2, true); memCount2 = memCount2 + mcExpandMem2Per; } return -(memUsedCount2 + 1); } int CBHashLK::FindSeqIdx( KeyType key, int fromIndex, int toIndex ) { // 找 mem[] 中键为Key的元素下标,从 fromIndex 开始, \ // 到 toIndex 结束 // 返回 mem[] 的找到键的下标(>0),没找到返回 0 int i; if (fromIndex < 1) fromIndex = 1; if (toIndex > memCount) toIndex = memCount; for (i=fromIndex; i<=toIndex; i++) if ((mem[i].Used) && mem[i].Key == key ) return i; return 0; } int CBHashLK::TraversalGetNextIdx( void ) { // 用 NextXXX 方法遍历时,返回下一个(Next)的 mem[]下标(返回值>0), \ // 或 mem2[] 的下标(返回值<0),或已遍历结束(返回值=0) int iRetIdx; if (mTravIdxCurr > memCount || -mTravIdxCurr > memCount2 || mTravIdxCurr == 0) return 0; if (mTravIdxCurr > 0) { //////////// 在 mem[] 中找 //////////// while (! mem[mTravIdxCurr].Used) { mTravIdxCurr = mTravIdxCurr + 1; if (mTravIdxCurr > memCount) break; } if (mTravIdxCurr > memCount) { //// 已遍历结束,看若 mem2[] 中还有数据继续遍历 mem2[] //// if (memCount2 > 0) { // 设置下次遍历 mem2[] 中数据的下标的负数 mTravIdxCurr = -1; // 执行下面的 if mTravIdxCurr < 0 Then } else { // 返回结束 iRetIdx = 0; return iRetIdx; } } else { //// 返回 mTravIdxCurr //// iRetIdx = mTravIdxCurr; // 调整下次遍历指针 指向下一个位置(或是 mem[] 的下一个, \ // 或是 mem2[] 的起始) mTravIdxCurr = mTravIdxCurr + 1; if (mTravIdxCurr > memCount) if (memCount2 > 0) mTravIdxCurr = -1; return iRetIdx; } } if (mTravIdxCurr < 0) { //////////// 在 mem2[] 中找 //////////// while (! mem2[-mTravIdxCurr].Used) { mTravIdxCurr = mTravIdxCurr - 1; if (-mTravIdxCurr > memCount2) break; } if (-mTravIdxCurr > memCount2) { //// 已遍历结束 //// // 返回结束 iRetIdx = 0; } else { // 返回负值的 mTravIdxCurr iRetIdx = mTravIdxCurr; // 调整 mTravIdxCurr 的指针 mTravIdxCurr = mTravIdxCurr - 1; } return iRetIdx; } return 0; } // 重定义 一个 MemType 类型的数组(如可以是 mem[] 或 mem2[])的大小,新定义空间自动清零 // arr:为数组指针,可传递:mem 或 mem2,本函数将修改此指针的指向 // toUBound:为要重定义后数组的上界,定义为:[0] to [toUBound],为 -1 时不开辟空间,可用于删除原 // 空间,并 arr 会被设为0 // uboundCurrent:为重定义前数组的上界 [0] to [uboundCurrent],为 -1 表示尚未开辟过空间为第一次调用 // preserve:保留数组原始数据否则不保留 // 返回新空间上标,即 toUBound int CBHashLK::RedimArrMemType( MemType * &arr, int toUBound/*=-1*/, int uboundCurrent/*=-1*/, bool preserve/*=false*/ ) { // 开辟新空间:[0] to [toUBound] if (toUBound >= 0) { MemType * ptrNew = new MemType [toUBound + 1]; // +1 为使可用下标最大到 toUBound // 新空间清零 memset(ptrNew, 0, sizeof(MemType)*(toUBound + 1)); // 将原有空间内容拷贝到新空间 if (preserve && arr!=0 && uboundCurrent>=0) { int ctToCpy; // 保留原有数据,需要拷贝内存的 MemType 元素个数 ctToCpy = uboundCurrent; if (uboundCurrent>toUBound) ctToCpy = toUBound; // 取 uboundCurrent 和 toUBound 的最小值 ctToCpy = ctToCpy + 1; // 必须 +1,因为 uboundCurrent 和 toUBound 都是数组上界 memcpy(ptrNew, arr, sizeof(MemType)*ctToCpy); } // 删除原有空间 if (arr!=0 && uboundCurrent>=0) delete [] arr; // 指针指向新空间 arr = ptrNew; return toUBound; } else // if (toUBound < 0),不开辟空间,删除原有空间 { if(arr!=0 && uboundCurrent>=0) delete [] arr; arr = 0; return 0; } } int CBHashLK::GetMemIndexFromKey( KeyType key, bool raiseErrorIfNotHas/*=true*/ ) { const int cMaxNumForSquare = 46340; // sqrt(2^31)=46340 int idxMod=0, idxSq=0; int idxModRev=0, idxSqRev=0; int keyToCalc=key; // 计算用 Key,永远为>=0的数 if (keyToCalc < 0) keyToCalc = 0 - keyToCalc; if (memCount) { // 1: 先用 Key Mod memCount + 1,此 Index -> idxMod idxMod = keyToCalc % memCount + 1; if (mem[idxMod].Used && mem[idxMod].Key == key) return idxMod; // 2: 用 平方Key后再除法取余,此 Index -> idxSq if (keyToCalc <= cMaxNumForSquare) { idxSq = (keyToCalc * keyToCalc) % memCount + 1; } else { int kBitSum=0; kBitSum = (keyToCalc & 0xFFFF0000)>>16; kBitSum += (keyToCalc & 0xFF00)>>8; kBitSum += (keyToCalc & 0xF0)>>4; kBitSum += (keyToCalc & 0xF); idxSq = kBitSum % memCount + 1; } if (mem[idxSq].Used && mem[idxSq].Key == key) return idxSq; // 3: 尝试倒数第 idxMod 个空间 -> idxModRev idxModRev = memCount - idxMod + 1; if (mem[idxModRev].Used && mem[idxModRev].Key == key) return idxModRev; // 4: 尝试倒数第 idxSq 个空间 -> idxSqRev idxSqRev = memCount - idxSq + 1; if (mem[idxSqRev].Used && mem[idxSqRev].Key == key) return idxSqRev; } int lngRetIdx=0; // 6: 从 idxMod 开始向前、向后线性搜索 mcSeqMax 个空间 int idxMdSta, idxMdEnd; idxMdSta = idxMod - mcSeqMax; idxMdEnd = idxMod + mcSeqMax; lngRetIdx = FindSeqIdx(key, idxMdSta, idxMod - 1); if (lngRetIdx > 0) return lngRetIdx; lngRetIdx = FindSeqIdx(key, idxMod + 1, idxMdEnd); if (lngRetIdx > 0) return lngRetIdx; // 7: 再查看 mem2[] 中的元素有没有 for (int i=1; i<=memUsedCount2; i++) if (mem2[i].Used && mem2[i].Key == key) return -i; if (raiseErrorIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } // 从 index 获得数据在 mem[] 中的下标(返回值>0)或在 mem2[] 中的下标(返回值<0),出错返回 0 int CBHashLK::GetMemIndexFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { if (mArrTableCount != memUsedCount + memUsedCount2) RefreshArrTable(); // 刷新数组缓冲 if (index<1 || index>mArrTableCount) { if (raiseErrorIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } int idx=mArrTable[index]; if (idx==0) { if (raiseErrorIfNotHas) throw (unsigned char)7; // 超出内存(mArrTable[index]意外为0) return 0; } else return idx; } // 用 new 开辟新字符串空间,把 ptrNewString 指向的字符串拷贝到新空间; // ptrSaveTo 是一个保存字符串地址的指针变量的地址,其指向的指针变量将保存 // “用 new 开辟的新字符串空间的地址”,即让 “*ptrSaveTo = 新空间地址” // 兼有释放“*ptrSaveTo”所指向的空间的功能 // 如 ptrSaveTo 参数可被传递 &(mem[i].key) 即指针的指针;ptrNewString 可被传递新的 key // 以完成“mem[i].key=key”的操作,本函数修改 mem[i].key 的内容: // 先删除它旧指向的空间,再让它指向新空间 // 如果 key 为空指针,仅释放“*ptrSaveTo”所指向的空间 void CBHashLK::SaveItemString( TCHAR ** ptrSaveTo, LPCTSTR ptrNewString ) { // 注意 ptrSaveTo 是个二级指针 if (ptrSaveTo==0) return; // 没有保存的位置 // 如果 ptrSaveTo 指向的指针变量不为“空指针”,表示要保存之处已正 // 保存着一个以前开辟的空间地址,应先删除以前开辟的空间 if (*ptrSaveTo != 0) {delete [] (*ptrSaveTo); *ptrSaveTo=0; } if (ptrNewString) { // 开辟新空间,保存 ptrNewString 这个字符串到新空间 TCHAR * p = new TCHAR [lstrlen(ptrNewString)+1]; lstrcpy(p, ptrNewString); // 使 *ptrSaveTo 指向新空间 *ptrSaveTo = p; } } // ---------------- 以 Index 返回数据属性(包括Key,但Key为只读) ---------------- // 注:随着数据增删,Index 可能会变化。某数据的 Index 并不与数据一一对应 CBHashLK::DataType CBHashLK::ItemFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].Data; else if (ii < 0) return mem2[-ii].Data; else return 0; } CBHashLK::DataLong2Type CBHashLK::ItemLong2FromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataLong2; else if (ii < 0) return mem2[-ii].DataLong2; else return 0; } CBHashLK::DataLongType CBHashLK::ItemLongFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataLong; else if (ii < 0) return mem2[-ii].DataLong; else return 0; } double CBHashLK::ItemDoubleFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataDouble; else if (ii < 0) return mem2[-ii].DataDouble; else return 0; } LPTSTR CBHashLK::ItemStrFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataStr; else if (ii < 0) return mem2[-ii].DataStr; else return 0; } LPTSTR CBHashLK::ItemStr2FromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataStr2; else if (ii < 0) return mem2[-ii].DataStr2; else return 0; } CBHashLK::KeyType CBHashLK::IndexToKey( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].Key; else if (ii < 0) return mem2[-ii].Key; else return 0; } int CBHashLK::KeyToIndex( KeyType key, bool raiseErrorIfNotHas/*=true*/ ) { int ii; if (mArrTableCount != memUsedCount + memUsedCount2) RefreshArrTable(); // 刷新数组缓冲 ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii > 0) return mem[ii].Index; else if (ii < 0) return mem2[-ii].Index; else return 0; } // ---------------- 以 Key 设置数据属性 ---------------- bool CBHashLK::ItemSet( KeyType key, DataType vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].Data = vNewValue; else if (ii < 0) mem2[-ii].Data = vNewValue; return true; } bool CBHashLK::ItemLongSet( KeyType key, DataLongType vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataLong = vNewValue; else if (ii < 0) mem2[-ii].DataLong = vNewValue; return true; } bool CBHashLK::ItemLong2Set( KeyType key, DataLong2Type vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataLong2 = vNewValue; else if (ii < 0) mem2[-ii].DataLong2 = vNewValue; return true; } bool CBHashLK::ItemDoubleSet( KeyType key, double vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataDouble = vNewValue; else if (ii < 0) mem2[-ii].DataDouble = vNewValue; return true; } bool CBHashLK::ItemStrSet( KeyType key, LPCTSTR vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) SaveItemString(&(mem[ii].DataStr), vNewValue); else if (ii < 0) SaveItemString(&(mem2[-ii].DataStr), vNewValue); return true; } bool CBHashLK::ItemStr2Set( KeyType key, LPCTSTR vNewValue,bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) SaveItemString(&(mem[ii].DataStr2), vNewValue); else if (ii < 0) SaveItemString(&(mem2[-ii].DataStr2), vNewValue); return true; } // ---------------- 以 Index 设置数据属性(Key为只读不能设置Key) ---------------- // 注:随着数据增删,Index 可能会变化。某数据的 Index 并不与数据一一对应 bool CBHashLK::ItemFromIndexSet( int index, DataType vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].Data = vNewValue; else if (ii < 0) mem2[-ii].Data = vNewValue; return true; } bool CBHashLK::ItemLongFromIndexSet( int index, DataLongType vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataLong = vNewValue; else if (ii < 0) mem2[-ii].DataLong = vNewValue; return true; } bool CBHashLK::ItemLong2FromIndexSet( int index, DataLong2Type vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataLong2 = vNewValue; else if (ii < 0) mem2[-ii].DataLong2 = vNewValue; return true; } bool CBHashLK::ItemDoubleFromIndexSet( int index, double vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataDouble = vNewValue; else if (ii < 0) mem2[-ii].DataDouble = vNewValue; return true; } bool CBHashLK::ItemStrFromIndexSet( int index, LPCTSTR vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) SaveItemString(&(mem[ii].DataStr), vNewValue); else if (ii < 0) SaveItemString(&(mem2[-ii].DataStr), vNewValue); return true; } bool CBHashLK::ItemStr2FromIndexSet( int index, LPCTSTR vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) SaveItemString(&(mem[ii].DataStr2), vNewValue); else if (ii < 0) SaveItemString(&(mem2[-ii].DataStr2), vNewValue); return true; } ////////////////////////////////////////////////////////////////////// // CBHashStrK 类的实现: 字符串型键值的哈希表 // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Static 常量定值 ////////////////////////////////////////////////////////////////////// const int CBHashStrK::mcIniMemSize = 7; // 初始 mem[] 的大小 const int CBHashStrK::mcMaxItemCount = 100000000; // 最多元素个数(可扩大此值到 long 表示的范围之内) const float CBHashStrK::mcExpandMaxPort = 0.75; // 已有元素个数大于 0.75*memCount 时就扩大 mem[] 的空间 const int CBHashStrK::mcExpandCountThres = 10000; // 扩大 mem[] 空间时,若 memCount 小于此值则每次扩大到 memCount*2;若 memCount 大于此值则每次扩大到 Count+Count/2 const int CBHashStrK::mcExpandCountThresMax = 10000000; // 扩大 mem[] 空间时,若 memCount 已大于此值,则每次不再扩大到 Count+Count/2,而只扩大到 Count+mcExpandBigPer const int CBHashStrK::mcExpandBigPer = 1000000; // 扩大 mem[] 空间时,若 memCount 已大于 mcExpandCountThresMax,则每次不再扩大到到 Count+Count/2,而只扩大到 Count+mcExpandBigPer const int CBHashStrK::mcExpandMem2Per = 10; // 每次扩大 mem2[] 的大小 const int CBHashStrK::mcSeqMax = 5; // 顺序检索最大值 ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBHashStrK::CBHashStrK(int memSize/*=0*/) { mArrTable=0; mArrTableCount = -1; // 无缓存数组 memUsedCount = 0; mem2 = 0; memCount2 = 0; memUsedCount2 = 0; KeyCaseSensitive=false; // 是否 key 要区分大小写(默认不分大小写) if (memSize) { // 初始定义 memSize 个的 mem[] 空间,无 mem2[] 的空间 RedimArrMemType(mem, memSize); memCount = memSize; } else { // 初始定义 mcIniMemSize 个的 mem[] 空间,无 mem2[] 的空间 RedimArrMemType(mem, mcIniMemSize); memCount = mcIniMemSize; } } CBHashStrK::~CBHashStrK() { Clear(); // Clear() 函数中,重新开辟了初始大小的 mem[] 空间,再将其删除即可 if (mem) delete[] mem; memCount = 0; } ////////////////////////////////////////////////////////////////////// // 公有方法 ////////////////////////////////////////////////////////////////////// void CBHashStrK::AlloMem(int memSize ) { /* 程序初始化时只定义了 mcIniMemSize 大小的 l_Mem[],以后随使用随自动扩 \ 大;但若事先知道有多大,可以先用本函数定义足够大以免以后不断 \ 自动扩大费时;注意这时要比预用的元素个数多定义一些,否则分配空间 \ 时若空间冲突本类还会自动扩大 此函数也可用于截断 l_Mem[] 后面没有使用的空间 注:memSize <= memUsedCount 时,拒绝重新定义,以确保数据不会丢失 */ if (memSize <= memUsedCount || memSize > mcMaxItemCount) return; int iPreMemCount; iPreMemCount = memCount; // ReDim Preserve mem(1 To memSize) RedimArrMemType(mem, memSize, memCount, true); memCount = memSize; if (iPreMemCount <= memCount) ReLocaMem(iPreMemCount); else ReLocaMem(memCount); // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; } bool CBHashStrK::Add( int data, LPCTSTR key/*=0*/, long dataLong/*=0*/, long dataLong2/*=0*/, LPCTSTR dataStr/*=NULL*/, LPCTSTR dataStr2/*=NULL*/, double dataDouble/*=0.0*/, bool raiseErrorIfNotHas/*=true*/ ) { int idx; // 哈希表中的数据个数最多不能超过 mcMaxItemCount if (memUsedCount + memUsedCount2 >= mcMaxItemCount) { if (raiseErrorIfNotHas) throw (unsigned char)7; // 超出内存 return false; } // 当前哈希表中不能有相同的“键”存在 if (IsKeyExist(key)) { if (raiseErrorIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return false; } // 通过调用 AlloMemIndex 函数获得一个可用空间的下标:idx idx = AlloMemIndex(key); if (idx > 0) { // 获得的下标值为正数时,使用 mem[] 数组的空间 mem[idx].Data = data; mem[idx].DataLong = dataLong; mem[idx].DataLong2 = dataLong2; mem[idx].DataDouble = dataDouble; SaveItemString(&(mem[idx].Key), key); // 保存 key 字符串,动态分配一个空间来保存,新空间地址保存到 mem[idx].Key;如果 mem[idx].Key 现在值不为 0,该函数还兼有先 delete mem[idx].Key 现在指向的空间的功能 SaveItemString(&(mem[idx].DataStr), dataStr); SaveItemString(&(mem[idx].DataStr2), dataStr2); mem[idx].Used = true; memUsedCount = memUsedCount + 1; } else if (idx < 0) { // 获得的下标值为负数时,使用 mem2[] 数组的空间,_ // 空间下标为 idx 的绝对值 mem2[-idx].Data = data; mem2[-idx].DataLong = dataLong; mem2[-idx].DataLong2 = dataLong2; mem2[-idx].DataDouble = dataDouble; SaveItemString(&(mem2[-idx].Key), key); // 保存 key 字符串,动态分配一个空间来保存,新空间地址保存到 mem[idx].Key;如果 mem[idx].Key 现在值不为 0,该函数还兼有先 delete mem[idx].Key 现在指向的空间的功能 SaveItemString(&(mem2[-idx].DataStr), dataStr); SaveItemString(&(mem2[-idx].DataStr2), dataStr2); mem2[-idx].Used = true; memUsedCount2 = memUsedCount2 + 1; } else // idx == 0 { if (raiseErrorIfNotHas) throw (unsigned char)9; // 下标越界:无法分配新数据空间 } // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; // 函数返回成功 return true; } int CBHashStrK::Item( LPCTSTR key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].Data; else if (idx < 0) return mem2[-idx].Data; else return 0; } long CBHashStrK::ItemLong( LPCTSTR key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataLong; else if (idx < 0) return mem2[-idx].DataLong; else return 0; } long CBHashStrK::ItemLong2( LPCTSTR key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataLong2; else if (idx < 0) return mem2[-idx].DataLong2; else return 0; } double CBHashStrK::ItemDouble( LPCTSTR key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataDouble; else if (idx < 0) return mem2[-idx].DataDouble; else return 0; } LPTSTR CBHashStrK::ItemStr( LPCTSTR key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataStr; else if (idx < 0) return mem2[-idx].DataStr; else return 0; } LPTSTR CBHashStrK::ItemStr2( LPCTSTR key, bool raiseErrorIfNotHas/*=true*/ ) { int idx; idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx > 0) return mem[idx].DataStr2; else if (idx < 0) return mem2[-idx].DataStr2; else return 0; } // 判断一个 Key 是否在当前集合中存在 bool CBHashStrK::IsKeyExist( LPCTSTR key ) { int idx; idx = GetMemIndexFromKey(key, false); return (idx != 0); } bool CBHashStrK::Remove( LPCTSTR key, bool raiseErrorIfNotHas/*=True*/ ) { int idx; // 调用 GetMemIndexFromKey 函数获得“键”为 Key 的数据所在空间的下标 idx = GetMemIndexFromKey(key, raiseErrorIfNotHas); if (idx == 0) return false; else if (idx > 0) { // 哈希表中“键”为 Key 的数据在 mem[] 数组中,下标为 idx mem[idx].Used = false; SaveItemString(&(mem[idx].Key), 0); // 第二个参数为0,删除 mem[idx].Key 指向的空间,并让 mem[idx].Key=0; SaveItemString(&(mem[idx].DataStr), 0); SaveItemString(&(mem[idx].DataStr2), 0); memUsedCount = memUsedCount - 1; } else { // idx<0 表示:哈希表中“键”为 Key 的数据在 mem2[] 数组中 \ // 下标为 idx 的绝对值 // 删除下标为“-idx”的元素 SaveItemString(&(mem[-idx].Key), 0); // 第二个参数为0,删除 mem[-idx].Key 指向的空间,并让 mem[-idx].Key=0; SaveItemString(&(mem[-idx].DataStr), 0); SaveItemString(&(mem[-idx].DataStr2), 0); for(int i=-idx; i<= memUsedCount2-1; i++) mem2[i] = mem2[i+1]; mem2[memUsedCount2].Key=0; // 直接设置为0,因此空间地址已经传递给上一元素 mem2[memUsedCount2].DataStr=0; // 直接设置为0,因此空间已经传递给上一元素 mem2[memUsedCount2].DataStr2=0; // 直接设置为0,因此空间已经传递给上一元素 memUsedCount2 = memUsedCount2 - 1; } // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; // 函数返回成功 return true; } void CBHashStrK::StartTraversal() { // 开始用 NextXXX ... 方法遍历 mTravIdxCurr = 1; } int CBHashStrK::NextItem( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 Data // 若 bRetNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].Data; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].Data; } else { bRetNotValid = true; return 0; } } long CBHashStrK::NextItemLong( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataLong; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataLong; } else { bRetNotValid = true; return 0; } } long CBHashStrK::NextItemLong2( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataLong2; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataLong2; } else { bRetNotValid = true; return 0; } } double CBHashStrK::NextItemDouble( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataDouble; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataDouble; } else { bRetNotValid = true; return 0; } } LPTSTR CBHashStrK::NextItemStr( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataStr; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataStr; } else { bRetNotValid = true; return 0; } } LPTSTR CBHashStrK::NextItemStr2( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 DataLong // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].DataStr2; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].DataStr2; } else { bRetNotValid = true; return 0; } } // 返回的字符串指针,直接指向类内部的 key 数据;因此注意:如若修改了该指针指向的内容, // 则类内数据的 key 也同时发生变化 LPTSTR CBHashStrK::NextKey( bool &bRetNotValid ) { // 调用 StartTraversal 后,用此函数遍历 String // 若 bRetEndNotValid 返回 True,表此次遍历已结束(此时函数返回值也无效) int idx; idx = TraversalGetNextIdx(); if (idx > 0) { bRetNotValid = false; return mem[idx].Key; } else if (idx < 0) { bRetNotValid = false; return mem2[-idx].Key; } else { bRetNotValid = true; return 0; } } // 清除所有元素,重定义 mcIniMemSize 个存储空间 void CBHashStrK::Clear( void ) { // 清除 按 Index 访问各元素的缓存数组 if (mArrTable) {delete []mArrTable; mArrTable=0;} mArrTableCount=-1; // 删除 mem[] 和 mem2[] 中的每个元素的 key 和 字符串数据 指向的空间 int i; for (i=1; i<=memCount; i++) { if (mem[i].Key) {delete [] mem[i].Key; mem[i].Key=0; } if (mem[i].DataStr) {delete [] mem[i].DataStr; mem[i].DataStr=0; } if (mem[i].DataStr2) {delete [] mem[i].DataStr2; mem[i].DataStr2=0; } } for (i=1; i<=memCount2; i++) { if (mem2[i].Key) {delete [] mem2[i].Key; mem2[i].Key=0; } if (mem2[i].DataStr) {delete [] mem2[i].DataStr; mem2[i].DataStr=0; } if (mem2[i].DataStr2) {delete [] mem2[i].DataStr2; mem2[i].DataStr2=0; } } // 删除 mem[] 和 mem2[] 的空间 delete [] mem; mem=0; delete [] mem2; mem2=0; memCount = 0; memUsedCount = 0; memCount2 = 0; memUsedCount2 = 0; // 重新开辟空间 RedimArrMemType(mem, mcIniMemSize, memCount, false); memCount = mcIniMemSize; mTravIdxCurr = 0; } // 返回共有元素个数 int CBHashStrK::Count( void ) { return memUsedCount + memUsedCount2; } ////////////////////////////////////////////////////////////////////// // 私有方法 ////////////////////////////////////////////////////////////////////// void CBHashStrK::ReLocaMem( int preMemCountTo ) { /* 重新分配 mem[], mem2[] 的各元素的空间,mem2[] 的某些元素可能被 \ 重新移动到 mem 将修改 memUsedCount,memUsedCount2, memCount2, mem2[] 的值 preMemCountTo 只考虑 mem[1 to preMemCountTo],preMemCountTo 以后的元素被认为 \ 未用,不考虑;但无论如何都考虑 mem2[] 中的所有元素 */ // 将 mem[] 中的已使用元素和 mem2[] 中的所有元素先放入 memUsed[] 中, \ // 把 memUsed[] 定义为足够大,实际 memUsed[] 只使用了 lngUsedCount 个元素 MemType * memUsed; RedimArrMemType(memUsed, preMemCountTo + memUsedCount2); int iUsedCount=0; int i; // 将 mem[] 中已使用的元素存入 memUsed[] for (i=1; i<=preMemCountTo; i++) if (mem[i].Used) { iUsedCount = iUsedCount + 1; memUsed[iUsedCount] = mem[i]; } // 将 mem2[] 中的所有元素存入 memUsed[] for (i=1; i<=memUsedCount2; i++) { iUsedCount = iUsedCount + 1; memUsed[iUsedCount] = mem2[i]; } /* 此时 memUsed[1 To lngUsedCount] 中为所有 mem[] \ 中的已使用元素 和 mem2[] 中的所有元素 */ // 清空 mem,也清空了所有 Used 域 RedimArrMemType(mem, memCount, memCount, false); memUsedCount=0; // memUsedCount 置0,后面随移动随+1 // 清空 mem2,也清空了所有 Used 域 RedimArrMemType(mem2, -1, memCount2, false); memCount2 = 0; memUsedCount2 = 0; // 逐个把 memUsed[1 To lngUsedCount] 中的元素按新数组大小映射下标存入 mem[] int idx; for (i=1; i<=iUsedCount; i++) { idx = AlloMemIndex(memUsed[i].Key, false); if (idx > 0) { mem[idx] = memUsed[i]; mem[idx].Used = 1; memUsedCount = memUsedCount + 1; } else { mem2[-idx] = memUsed[i]; mem2[-idx].Used = 1; memUsedCount2 = memUsedCount2 + 1; } } // 删除临时空间 memUsed delete [] memUsed; memUsed=0; // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; } // 重定义 mem[] 数组大小,扩大 mem[] 的空间 void CBHashStrK::ExpandMem( void ) { int iCount, iPreMemCount; // 计算哈希表中共有数据总数 iCount = memUsedCount + memUsedCount2; // 取“共有数据总数”和“当前 mem[] 的空间总数”两者的较大值 if (iCount < memCount) iCount = memCount; // 保存扩增空间之前的、原来的 mem[] 的空间总数 iPreMemCount = memCount; if (iCount<1) iCount=1; // 避免 iCount 为0时,无法扩大空间 if (iCount < mcExpandCountThres) { // 如果数据总数“比较少”,就扩增空间为原来的2倍 iCount = iCount * 2; } else if (iCount < mcExpandCountThresMax) { // 如果数据总数已经“有点多”,就扩增空间为原来的1.5倍 iCount = iCount * 3 / 2; } else { // 如果数据总数“很多”,就扩增 mcExpandBigPer 个空间 iCount = iCount + mcExpandBigPer; } // 重定义数组大小 // ReDim Preserve mem(1 To lngCount) RedimArrMemType(mem, iCount, memCount, true); memCount = iCount; // 按新数组大小,重新安排其中所有数据的新位置,参数中要传递 // 扩增空间之前的、原来的 mem[] 的空间总数 ReLocaMem(iPreMemCount); // 哈希表遍历的指针重置 mTravIdxCurr = 0; // 按 Index 访问各元素的缓存数组重置 mArrTableCount = -1; } // 遍历哈希表,将数据存入 mArrTable(),设置 mArrTableCount 为数据个数(返回成功或失败) bool CBHashStrK::RefreshArrTable() { int iCount; int i,j; // 计算哈希表中共有数据总数 iCount = memUsedCount + memUsedCount2; mArrTableCount=iCount; if (mArrTableCount<=0) return false; if (mArrTable) {delete []mArrTable; mArrTable=0;} mArrTable=new int [iCount+1]; // 使数组下标从1开始 memset(mArrTable, 0, sizeof(int)*(iCount+1)); j=1; for (i=1; i<=memCount; i++) { if (mem[i].Used) { if (j > iCount) return false; mArrTable[j] = i; // 将 哈希表的本数据所在的 mem[] 的下标 i 存入 mArrTable[j] mem[i].Index = j; // 在 哈希表的本数据 的 Index 成员中记录 mArrTable 的下标 j j=j+1; } } for (i=1; i<=memUsedCount2; i++) { if (mem2[i].Used) { if (j > iCount) return false; mArrTable[j] = -i; // 将 哈希表的本数据所在的 mem2[] 的下标 i (取负)存入 mArrTable[j] mem[i].Index = j; // 在 哈希表的本数据 的 Index 成员中记录 mArrTable 的下标 j j=j+1; } } return true; } int CBHashStrK::AlloSeqIdx( int fromIndex, int toIndex ) { /* 找 mem[] 中一个没使用的空间,从 fromIndex 开始, \ 到 toIndex 结束 返回 mem[] 的一个没使用元素的下标,没找到返回 0 */ int i; if (fromIndex <= 0) fromIndex = 1; if (toIndex > memCount) toIndex = memCount; for (i=fromIndex; i<=toIndex; i++) if (! mem[i].Used) return i; return 0; } int CBHashStrK::AlloMemIndex( LPCTSTR key, bool CanExpandMem/*=true */ ) { /* 根据 Key 分配一个 mem[] 中的未用存储空间,返回 mem[] 数组下标 返回负值表不能在 mem[] 中找到空间:返回值的绝对值为 mem2[] 的 \ 下一个可用下标空间(mem2[]自动Redim),以存入 mem2[] 本函数确保返回一个可使用的空间,最差情况返回 mem2[] 中的空间 另:本函数不修改 memUsedCount2 的值,但 redim mem2[] CanExpandMem=true 时,允许本函数自动扩大 mem[],否则不会自动扩大 方法:将字符串的 key 转换为整数,如果为负数先取绝对值,然后: 1. 先用 Key Mod memCount + 1,此 Index -> idxMod 2. 若上面的元素已经使用,则看Key是否 < cMaxNumForSquare (sqr(2^31)=46340) \ 若 <,则平方 Key,然后 mod memCount + 1; \ 若 >=,则用按位和移位运算,后相加 key 的各个部分,然后 mod memCount + 1 无论哪种情况,此步 Index -> idxSq 3. 用 memCount-idxMod+1 -> idxModRev 4. 用 memCount-idxSq+1 -> idxSqRev 5. 若上面找到的 Index 都被使用了,则看 Count 是否 > \ mcExpandMaxPort*Count,若是,若 CanExpandMem=true, \ 则扩大 mem[] 的存储空间,然后递归本过程,重复 1-4 步 6. 用 idxMod+1,+2,...,+mcSeqMax;用 idxMod-1,-2,...,-mcSeqMax 7. 再没有,返回负值,绝对值为 mem2[] 的下一个可用空间,以存入 mem2[] */ const int cMaxNumForSquare = 46340; int idxMod=0, idxSq=0; int idxModRev=0, idxSqRev=0; int iCount=0; long keyToCalc = KeyStringToLong(key); // 计算用 Key,永远为>0的数 if (keyToCalc < 0) keyToCalc = 0 - keyToCalc; // 如果 Key 是负值,则转换为正数计算它的存储空间 iCount = memUsedCount + memUsedCount2; if (memCount) { // 1: 先用 Key Mod memCount + 1,此 Index -> idxMod idxMod = keyToCalc % memCount + 1; if (! mem[idxMod].Used) return idxMod; // 2: 用 平方Key 后再除法取余,此 Index -> idxSq if (keyToCalc <= cMaxNumForSquare) { idxSq = (keyToCalc * keyToCalc) % memCount + 1; } else { int kBitSum=0; kBitSum = (keyToCalc & 0xFFFF0000)>>16; kBitSum += (keyToCalc & 0xFF00)>>8; kBitSum += (keyToCalc & 0xF0)>>4; kBitSum += (keyToCalc & 0xF); idxSq = kBitSum % memCount + 1; } if (! mem[idxSq].Used) return idxSq; // 3: 尝试倒数第 idxMod 个空间 -> idxModRev idxModRev = memCount - idxMod + 1; if (! mem[idxModRev].Used) return idxModRev; // 4: 尝试倒数第 idxSq 个空间 -> idxSqRev idxSqRev = memCount - idxSq + 1; if (! mem[idxSqRev].Used) return idxSqRev; } // 5: 如果空间使用百分比超过阈值,就扩大 mem[] 的 空间 if (CanExpandMem && iCount > mcExpandMaxPort * memCount) { ExpandMem(); // 扩大 mem[] 的空间 return AlloMemIndex(key, CanExpandMem); // 递归,重复1-4步 } int lngRetIdx; // 6: 从 idxMod 开始向前、向后线性搜索 mcSeqMax 个空间 int idxMdSta, idxMdEnd; idxMdSta = idxMod - mcSeqMax; idxMdEnd = idxMod + mcSeqMax; lngRetIdx = AlloSeqIdx(idxMdSta, idxMod - 1); if (lngRetIdx > 0) return lngRetIdx; lngRetIdx = AlloSeqIdx(idxMod + 1, idxMdEnd); if (lngRetIdx > 0) return lngRetIdx; // 7: 返回负值,绝对值为 mem2[] 的下一个元素,以存入 mem2[] if (memUsedCount2 + 1 > memCount2) { // ReDim Preserve mem2(1 To mcExpandMem2Per) RedimArrMemType(mem2, memCount2 + mcExpandMem2Per, memCount2, true); memCount2 = memCount2 + mcExpandMem2Per; } return -(memUsedCount2 + 1); } int CBHashStrK::FindSeqIdx( LPCTSTR key, int fromIndex, int toIndex ) { // 找 mem[] 中键为Key的元素下标,从 fromIndex 开始, \ // 到 toIndex 结束 // 返回 mem[] 的找到键的下标(>0),没找到返回 0 int i; if (fromIndex < 1) fromIndex = 1; if (toIndex > memCount) toIndex = memCount; for (i=fromIndex; i<=toIndex; i++) if ((mem[i].Used) && CompareKey(mem[i].Key, key) ) return i; return 0; } int CBHashStrK::TraversalGetNextIdx( void ) { // 用 NextXXX 方法遍历时,返回下一个(Next)的 mem[]下标(返回值>0), \ // 或 mem2[] 的下标(返回值<0),或已遍历结束(返回值=0) int iRetIdx; if (mTravIdxCurr > memCount || -mTravIdxCurr > memCount2 || mTravIdxCurr == 0) return 0; if (mTravIdxCurr > 0) { //////////// 在 mem[] 中找 //////////// while (! mem[mTravIdxCurr].Used) { mTravIdxCurr = mTravIdxCurr + 1; if (mTravIdxCurr > memCount) break; } if (mTravIdxCurr > memCount) { //// 已遍历结束,看若 mem2[] 中还有数据继续遍历 mem2[] //// if (memCount2 > 0) { // 设置下次遍历 mem2[] 中数据的下标的负数 mTravIdxCurr = -1; // 执行下面的 if mTravIdxCurr < 0 Then } else { // 返回结束 iRetIdx = 0; return iRetIdx; } } else { //// 返回 mTravIdxCurr //// iRetIdx = mTravIdxCurr; // 调整下次遍历指针 指向下一个位置(或是 mem[] 的下一个, \ // 或是 mem2[] 的起始) mTravIdxCurr = mTravIdxCurr + 1; if (mTravIdxCurr > memCount) if (memCount2 > 0) mTravIdxCurr = -1; return iRetIdx; } } if (mTravIdxCurr < 0) { //////////// 在 mem2[] 中找 //////////// while (! mem2[-mTravIdxCurr].Used) { mTravIdxCurr = mTravIdxCurr - 1; if (-mTravIdxCurr > memCount2) break; } if (-mTravIdxCurr > memCount2) { //// 已遍历结束 //// // 返回结束 iRetIdx = 0; } else { // 返回负值的 mTravIdxCurr iRetIdx = mTravIdxCurr; // 调整 mTravIdxCurr 的指针 mTravIdxCurr = mTravIdxCurr - 1; } return iRetIdx; } return 0; } // 重定义 一个 MemType 类型的数组(如可以是 mem[] 或 mem2[])的大小,新定义空间自动清零 // arr:为数组指针,可传递:mem 或 mem2,本函数将修改此指针的指向 // toUBound:为要重定义后数组的上界,定义为:[0] to [toUBound],为 -1 时不开辟空间,可用于删除原 // 空间,并 arr 会被设为0 // uboundCurrent:为重定义前数组的上界 [0] to [uboundCurrent],为 -1 表示尚未开辟过空间为第一次调用 // preserve:保留数组原始数据否则不保留 // 返回新空间上标,即 toUBound int CBHashStrK::RedimArrMemType( MemType * &arr, int toUBound/*=-1*/, int uboundCurrent/*=-1*/, bool preserve/*=false*/ ) { // 开辟新空间:[0] to [toUBound] if (toUBound >= 0) { MemType * ptrNew = new MemType [toUBound + 1]; // +1 为使可用下标最大到 toUBound // 新空间清零 memset(ptrNew, 0, sizeof(MemType)*(toUBound + 1)); // 将原有空间内容拷贝到新空间 if (preserve && arr!=0 && uboundCurrent>=0) { int ctToCpy; // 保留原有数据,需要拷贝内存的 MemType 元素个数 ctToCpy = uboundCurrent; if (uboundCurrent>toUBound) ctToCpy = toUBound; // 取 uboundCurrent 和 toUBound 的最小值 ctToCpy = ctToCpy + 1; // 必须 +1,因为 uboundCurrent 和 toUBound 都是数组上界 memcpy(ptrNew, arr, sizeof(MemType)*ctToCpy); } // 删除原有空间 if (arr!=0 && uboundCurrent>=0) delete [] arr; // 指针指向新空间 arr = ptrNew; return toUBound; } else // if (toUBound < 0),不开辟空间,删除原有空间 { if(arr!=0 && uboundCurrent>=0) delete [] arr; arr = 0; return 0; } } // 用 new 开辟新字符串空间,把 ptrNewString 指向的字符串拷贝到新空间; // ptrSaveTo 是一个保存字符串地址的指针变量的地址,其指向的指针变量将保存 // “用 new 开辟的新字符串空间的地址”,即让 “*ptrSaveTo = 新空间地址” // 兼有释放“*ptrSaveTo”所指向的空间的功能 // 如 ptrSaveTo 参数可被传递 &(mem[i].key) 即指针的指针;ptrNewString 可被传递新的 key // 以完成“mem[i].key=key”的操作,本函数修改 mem[i].key 的内容: // 先删除它旧指向的空间,再让它指向新空间 // 如果 key 为空指针,仅释放“*ptrSaveTo”所指向的空间 void CBHashStrK::SaveItemString( TCHAR ** ptrSaveTo, LPCTSTR ptrNewString ) { // 注意 ptrSaveTo 是个二级指针 if (ptrSaveTo==0) return; // 没有保存的位置 // 如果 ptrSaveTo 指向的指针变量不为“空指针”,表示要保存之处已正 // 保存着一个以前开辟的空间地址,应先删除以前开辟的空间 if (*ptrSaveTo != 0) {delete [] (*ptrSaveTo); *ptrSaveTo=0; } if (ptrNewString) { // 开辟新空间,保存 ptrNewString 这个字符串到新空间 TCHAR * p = new TCHAR [_tcslen(ptrNewString)+1]; _tcscpy(p, ptrNewString); // 使 *ptrSaveTo 指向新空间 *ptrSaveTo = p; } } // 从 Key 获得数据在 mem[] 中的下标(返回值>0)或在 mem2[] 中的下标(返回值<0),出错返回 0 int CBHashStrK::GetMemIndexFromKey( LPCTSTR key, bool raiseErrorIfNotHas/*=true*/ ) { const long cMaxNumForSquare = 46340; // sqrt(2^31)=46340 int idxMod=0, idxSq=0; int idxModRev=0, idxSqRev=0; long keyToCalc = KeyStringToLong(key); // 计算用 Key,永远为>=0的数 if (keyToCalc < 0) keyToCalc = 0 - keyToCalc; if (memCount) { // 1: 先用 Key Mod memCount + 1,此 Index -> idxMod idxMod = keyToCalc % memCount + 1; if (mem[idxMod].Used && CompareKey(mem[idxMod].Key, key)) return idxMod; // 2: 用 平方Key后再除法取余,此 Index -> idxSq if (keyToCalc <= cMaxNumForSquare) { idxSq = (keyToCalc * keyToCalc) % memCount + 1; } else { int kBitSum=0; kBitSum = (keyToCalc & 0xFFFF0000)>>16; kBitSum += (keyToCalc & 0xFF00)>>8; kBitSum += (keyToCalc & 0xF0)>>4; kBitSum += (keyToCalc & 0xF); idxSq = kBitSum % memCount + 1; } if (mem[idxSq].Used && CompareKey(mem[idxSq].Key, key)) return idxSq; // 3: 尝试倒数第 idxMod 个空间 -> idxModRev idxModRev = memCount - idxMod + 1; if (mem[idxModRev].Used && CompareKey(mem[idxModRev].Key, key)) return idxModRev; // 4: 尝试倒数第 idxSq 个空间 -> idxSqRev idxSqRev = memCount - idxSq + 1; if (mem[idxSqRev].Used && CompareKey(mem[idxSqRev].Key, key)) return idxSqRev; } int lngRetIdx; // 6: 从 idxMod 开始向前、向后线性搜索 mcSeqMax 个空间 int idxMdSta, idxMdEnd; idxMdSta = idxMod - mcSeqMax; idxMdEnd = idxMod + mcSeqMax; lngRetIdx = FindSeqIdx(key, idxMdSta, idxMod - 1); if (lngRetIdx > 0) return lngRetIdx; lngRetIdx = FindSeqIdx(key, idxMod + 1, idxMdEnd); if (lngRetIdx > 0) return lngRetIdx; // 7: 再查看 mem2[] 中的元素有没有 for (int i=1; i<=memUsedCount2; i++) if (mem2[i].Used && CompareKey(mem2[i].Key, key)) return -i; if (raiseErrorIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } // 从 index 获得数据在 mem[] 中的下标(返回值>0)或在 mem2[] 中的下标(返回值<0),出错返回 0 int CBHashStrK::GetMemIndexFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { if (mArrTableCount != memUsedCount + memUsedCount2) RefreshArrTable(); // 刷新数组缓冲 if (index<1 || index>mArrTableCount) { if (raiseErrorIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } int idx=mArrTable[index]; if (idx==0) { if (raiseErrorIfNotHas) throw (unsigned char)7; // 超出内存(mArrTable[index]意外为0) return 0; } else return idx; } // 将一个 字符串类型的 key 转换为一个长整数 // 方法是:取前16个字符、后16个字符,将这32个字符的ASCII码相加求和返回 long CBHashStrK::KeyStringToLong( LPCTSTR key ) { // 方法是:取前16个字符、后16个字符,将这32个字符的ASCII码相加求和返回 const int c_CalcCharNumHead = 16; const int c_CalcCharNumTail = 16; long lResult=0; int iHeadToPos=0; // 实际要取前几个字符 int iTailToPos=0; // 实际要取后几个字符 int i; TCHAR * keyLoc = new TCHAR[_tcslen(key)+1]; // 计算用 key _tcscpy(keyLoc, key); // 拷贝 key 字符串到新开辟的空间做副本,因 key 可能要被按照 KeyCaseSensitive 属性转换大小写 if (! KeyCaseSensitive) _tcsupr(keyLoc); // 如果不区分大小写,将 key 转换为 大写 // 初始化累加 ASCII 码的结果 lResult = 0; // 累加前 c_CalcCharNumHead 个字符的 ASCII 码(不足 c_CalcCharNumHead 的做到字符串结束为止) iHeadToPos = c_CalcCharNumHead; if ((int)_tcslen(keyLoc) < iHeadToPos) iHeadToPos = _tcslen(keyLoc); for(i=0; i<iHeadToPos; i++) lResult += *(keyLoc+i); // 累加后 c_CalcCharNumTail 个字符的 ASCII 码(不足 c_CalcCharNumTail 的做到字符串结束为止) iTailToPos = c_CalcCharNumTail; if ((int)_tcslen(keyLoc) - iHeadToPos < iTailToPos) iTailToPos = _tcslen(keyLoc) - iHeadToPos; for(i = (int)_tcslen(keyLoc) - iTailToPos; i<(int)_tcslen(keyLoc); i++) lResult += *(keyLoc+i); // 释放空间 delete []keyLoc; // 返回结果:累加的 ASCII 码 return lResult; } // 根据 lKeyCaseSensitive 属性,比较两 key 的字符串是否相等 // 相等返回True,不等返回False bool CBHashStrK::CompareKey(LPCTSTR key1, LPCTSTR key2 ) { if (key1==0 || key2==0) return false; if (KeyCaseSensitive) return lstrcmp(key1, key2)==0; else { return lstrcmpi(key1, key2)==0; } } // ---------------- 以 Index 返回数据属性(包括Key,但Key为只读) ---------------- // 注:随着数据增删,Index 可能会变化。某数据的 Index 并不与数据一一对应 int CBHashStrK::ItemFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].Data; else if (ii < 0) return mem2[-ii].Data; else return 0; } long CBHashStrK::ItemLongFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataLong; else if (ii < 0) return mem2[-ii].DataLong; else return 0; } long CBHashStrK::ItemLong2FromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataLong2; else if (ii < 0) return mem2[-ii].DataLong2; else return 0; } double CBHashStrK::ItemDoubleFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataDouble; else if (ii < 0) return mem2[-ii].DataDouble; else return 0; } LPTSTR CBHashStrK::ItemStrFromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataStr; else if (ii < 0) return mem2[-ii].DataStr; else return 0; } LPTSTR CBHashStrK::ItemStr2FromIndex( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].DataStr2; else if (ii < 0) return mem2[-ii].DataStr2; else return 0; } LPTSTR CBHashStrK::IndexToKey( int index, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii > 0) return mem[ii].Key; else if (ii < 0) return mem2[-ii].Key; else return 0; } int CBHashStrK::KeyToIndex( LPCTSTR key, bool raiseErrorIfNotHas/*=true*/ ) { int ii; if (mArrTableCount != memUsedCount + memUsedCount2) RefreshArrTable(); // 刷新数组缓冲 ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii > 0) return mem[ii].Index; else if (ii < 0) return mem2[-ii].Index; else return 0; } // ---------------- 以 Key 设置数据属性 ---------------- bool CBHashStrK::ItemSet( LPCTSTR key, int vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].Data = vNewValue; else if (ii < 0) mem2[-ii].Data = vNewValue; return true; } bool CBHashStrK::ItemLong2Set( LPCTSTR key, long vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataLong2 = vNewValue; else if (ii < 0) mem2[-ii].DataLong2 = vNewValue; return true; } bool CBHashStrK::ItemLongSet( LPCTSTR key, long vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataLong = vNewValue; else if (ii < 0) mem2[-ii].DataLong = vNewValue; return true; } bool CBHashStrK::ItemDoubleSet( LPCTSTR key, double vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataDouble = vNewValue; else if (ii < 0) mem2[-ii].DataDouble = vNewValue; return true; } bool CBHashStrK::ItemStrSet( LPCTSTR key, LPCTSTR vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) SaveItemString(&(mem[ii].DataStr), vNewValue); else if (ii < 0) SaveItemString(&(mem2[-ii].DataStr), vNewValue); return true; } bool CBHashStrK::ItemStr2Set( LPCTSTR key, LPCTSTR vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromKey(key, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) SaveItemString(&(mem[ii].DataStr2), vNewValue); else if (ii < 0) SaveItemString(&(mem2[-ii].DataStr2), vNewValue); return true; } // ---------------- 以 Index 设置数据属性(Key为只读不能设置Key) ---------------- // 注:随着数据增删,Index 可能会变化。某数据的 Index 并不与数据一一对应 bool CBHashStrK::ItemFromIndexSet( int index, int vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].Data = vNewValue; else if (ii < 0) mem2[-ii].Data = vNewValue; return true; } bool CBHashStrK::ItemLongFromIndexSet( int index, long vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataLong = vNewValue; else if (ii < 0) mem2[-ii].DataLong = vNewValue; return true; } bool CBHashStrK::ItemLong2FromIndexSet( int index, long vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataLong2 = vNewValue; else if (ii < 0) mem2[-ii].DataLong2 = vNewValue; return true; } bool CBHashStrK::ItemDoubleFromIndexSet( int index, double vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) mem[ii].DataDouble = vNewValue; else if (ii < 0) mem2[-ii].DataDouble = vNewValue; return true; } bool CBHashStrK::ItemStrFromIndexSet( int index, LPCTSTR vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) SaveItemString(&(mem[ii].DataStr), vNewValue); else if (ii < 0) SaveItemString(&(mem2[-ii].DataStr), vNewValue); return true; } bool CBHashStrK::ItemStr2FromIndexSet( int index, LPCTSTR vNewValue, bool raiseErrorIfNotHas/*=true*/ ) { int ii; ii=GetMemIndexFromIndex(index, raiseErrorIfNotHas); if (ii == 0) return false; else if (ii > 0) SaveItemString(&(mem[ii].DataStr2), vNewValue); else if (ii < 0) SaveItemString(&(mem2[-ii].DataStr2), vNewValue); return true; } ////////////////////////////////////////////////////////////////////// // CBRecycledArr 类的实现:带回收站的数组 // ////////////////////////////////////////////////////////////////////// // =================================================================================== // 字符串数据: // 在 Add 时才 new 空间,开辟 mem[] 的空间时,各 mem[] 元素的字符串指针不 = new // 在 Remove 时,delete 空间,然后保存到“回收站”。回收站中的内容字符串指针都为NULL // 在析构时,delete 空间 // =================================================================================== ////////////////////////////////////////////////////////////////////// // Static 常量定值 ////////////////////////////////////////////////////////////////////// const int CBRecycledArr::mcIniMemSize = 7; // 初始 mem[] 的大小 const int CBRecycledArr::mcMaxItemCount = 100000000; // 最多元素个数(由于内存原因,2G内存之内,sizeof(MemType)*此值不得超过2G) const float CBRecycledArr::mcExpandMaxPort = 0.75; // 已有元素个数大于 0.75*memCount 时就扩大 mem[] 的空间 const int CBRecycledArr::mcExpandCountThres = 10000; // 扩大 mem[] 空间时,若 memCount 小于此值则每次扩大到 memCount*2;若 memCount 大于此值则每次扩大到 Count+Count/2 const int CBRecycledArr::mcExpandCountThresMax = 10000000;// 扩大 mem[] 空间时,若 memCount 已大于此值,则每次不再扩大到 Count+Count/2,而只扩大到 Count+mcExpandBigPer const int CBRecycledArr::mcExpandBigPer = 1000000; // 扩大 mem[] 空间时,若 memCount 已大于 mcExpandCountThresMax,则每次不再扩大到到 Count+Count/2,而只扩大到 Count+mcExpandBigPer const int CBRecycledArr::mcRecyExpandPer = 100; // 扩大 recycles[] 空间时,每次扩大的大小 ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBRecycledArr::CBRecycledArr(int initSize/*=0*/) { // 初始化成员变量的值 mem = 0; memCount = 0; memUsedCount = 0; recycles = 0; recyCount = 0; recyUsedCount = 0; mTravIdxCurr = 0; // 开辟初始空间 if (initSize) { // 开辟 initSize 大小的空间 RedimArrMemType(mem, initSize); memCount = initSize; } else { // 开辟 mcIniMemSize 大小的空间 RedimArrMemType(mem, mcIniMemSize); memCount = mcIniMemSize; } } CBRecycledArr::~CBRecycledArr() { Clear(); // Clear() 函数又自动开辟了 mcIniMemSize 大小的空间,现再删除它即可 delete []mem; memCount=0; } ////////////////////////////////////////////////////////////////////// // 公有函数 ////////////////////////////////////////////////////////////////////// // 添加新数据,返回新数据被保存到的 mem[] 中的下标(>0),出错返回0 int CBRecycledArr::Add( LPCTSTR dataString /*= NULL*/, int dataInt /*= 0*/, int dataInt2 /*= 0*/, float dataFloat /*= 0.0*/, double dataDouble /*= 0.0*/ ) { int idx = 0; // 要将新数据存入 mem[idx] // ======== 为新数据分配新空间,获得空间下标 idx ======== if (recycles!=0 && recyUsedCount>0) { // 回收站中有空间,使用回收站中的最后一个空间;回收站剩余部分仍维护着从小到大排序 idx = recycles [recyUsedCount]; recyUsedCount--; } else { // 回收站中没有空间,使用 mem[idx] 中的下一个可用空间 if (memUsedCount+1 <= memCount) { memUsedCount++; idx = memUsedCount; } else { // Redim preserve mem[1 to memCount + 一批] ExpandMem(); // 扩大空间后再次判断 if (memUsedCount+1 <= memCount) { memUsedCount++; idx = memUsedCount; } else { // 扩大空间后还不能 memUsedCount <= memCount,无法分配空间,返回出错 return 0; } } } // ======== 保存新数据 ======== if (dataString) { mem[idx].DataString = new TCHAR [_tcslen(dataString) + 1]; _tcscpy(mem[idx].DataString, dataString); } else { mem[idx].DataString = NULL; } mem[idx].DataInt = dataInt; mem[idx].DataInt2 = dataInt2; mem[idx].DataFloat = dataFloat; mem[idx].DataDouble = dataDouble; mem[idx].Used = true; // 返回新数据被保存到的 mem[] 中的下标 return idx; } bool CBRecycledArr::Remove( int index ) { int idx, i; index=UserIndexToMemIndex(index); if (index<1 || index>memCount) return false; // index 不合法 if (! mem[index].Used) return false; // 数据已被删除 // ======== 设置数据值为空 ======== if (mem[index].DataString) // 删除该数据的字符串所占用的空间(如果有的话) { delete [] mem[index].DataString; mem[index].DataString = NULL; } mem[index].DataInt = 0; mem[index].DataInt2 = 0; mem[index].DataFloat = 0.0; mem[index].DataDouble = 0.0; mem[index].Used = false; // ======== 在回收站中记录该空间已被删除 ======== // 在回收站中保存记录 index(维护回收站 recycles[] 数组从小到大排序) if (recycles==0 || recyUsedCount + 1 > recyCount) { // 扩大回收站中的空间 RedimArrInt(recycles, recyCount+mcRecyExpandPer, recyCount, true); recyCount = recyCount+mcRecyExpandPer; } // 使用二分查找找到 index 应被保存到的 recycles[] 下标的负数 idx=FindPosInSortedRecycle(index); // 总数 + 1 recyUsedCount++; // 保存新数据 if (idx<0) { // 正常情况,index 应被保存到的 recycles[-idx] for(i=recyUsedCount; i>-idx; i++) recycles[i]=recycles[i-1]; recycles[-idx] = index; } else { // 不正常(如回收站中已经有了值为 index 的这个元素,或二分查找出错) // 容错,仍使用 recycles[idx] 保存 index recycles[idx] = index; } // 返回成功 return true; } LPTSTR CBRecycledArr::Item( int index, bool bRaiseErrIfNotHas/*=false*/ ) { index=UserIndexToMemIndex(index); if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } return mem[index].DataString; } int CBRecycledArr::ItemInt( int index, bool bRaiseErrIfNotHas/*=false*/ ) { index=UserIndexToMemIndex(index); if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } return mem[index].DataInt; } int CBRecycledArr::ItemInt2( int index, bool bRaiseErrIfNotHas/*=false*/ ) { index=UserIndexToMemIndex(index); if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } return mem[index].DataInt2; } float CBRecycledArr::ItemFloat( int index, bool bRaiseErrIfNotHas/*=false*/ ) { index=UserIndexToMemIndex(index); if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0.0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0.0; } return mem[index].DataFloat; } double CBRecycledArr::ItemDouble( int index, bool bRaiseErrIfNotHas/*=false*/ ) { index=UserIndexToMemIndex(index); if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0.0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0.0; } return mem[index].DataDouble; } void CBRecycledArr::Clear() { // 先删除所有字符串的空间 int i; for(i=1; i<=memCount; i++) if (mem[i].DataString) { delete [] mem[i].DataString; mem[i].DataString = NULL; } // 删除 mem 本身的空间和 回收站 本身的空间 if (mem) delete []mem; if (recycles) delete []recycles; mem = 0; memCount = 0; memUsedCount = 0; recycles = 0; recyCount = 0; recyUsedCount = 0; mTravIdxCurr = 0; // 开辟 mcIniMemSize 大小的空间 RedimArrMemType(mem, mcIniMemSize); memCount = mcIniMemSize; } void CBRecycledArr::StartTraversal() { mTravIdxCurr = 1; } LPTSTR CBRecycledArr::NextItem( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].DataString;} } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0; } int CBRecycledArr::NextDataInt( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].DataInt;} } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0; } int CBRecycledArr::NextDataInt2( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].DataInt2;} } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0; } float CBRecycledArr::NextDataFloat( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].DataFloat;} } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0.0; } double CBRecycledArr::NextDataDouble( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].DataDouble; } } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0.0; } // 返回当前拥有的数据个数 int CBRecycledArr::Count() { int ct = memUsedCount-recyUsedCount; if (ct<0) ct = 0; return ct; } ////////////////////////////////////////////////////////////////////// // 私有函数 ////////////////////////////////////////////////////////////////////// void CBRecycledArr::ExpandMem( void ) { int toCount = 0; toCount=memCount; if (toCount < 1) toCount = 1; // 避免 toCount 为0无法扩大空间 if (toCount < mcExpandCountThres) { // 如果数据总数“比较少”,就扩增空间为原来的2倍 toCount = toCount * 2; } else if (toCount < mcExpandCountThresMax) { // 如果数据总数已经“有点多”,就扩增空间为原来的1.5倍 toCount = toCount * 3 / 2; } else { // 如果数据总数“很多”,就扩增 mcExpandBigPer 个空间 toCount = toCount + mcExpandBigPer; } // 重定义数组大小 // ReDim Preserve mem(1 To toCount) RedimArrMemType(mem, toCount, memCount, true); memCount = toCount; } // 重定义 一个 MemType 类型的数组(如可以是 recycles)的大小,新定义空间自动清零 // arr:为数组指针,可传递:recycles,本函数将修改此指针的指向 // toUBound:为要重定义后数组的上界,定义为:[0] to [toUBound],为 -1 时不开辟空间,可用于删除原 // 空间,并 arr 会被设为0 // uboundCurrent:为重定义前数组的上界 [0] to [uboundCurrent],为 -1 表示尚未开辟过空间为第一次调用 // preserve:保留数组原始数据否则不保留 // 返回新空间上标,即 toUBound int CBRecycledArr::RedimArrMemType( MemType * &arr, int toUBound/*=-1*/, int uboundCurrent/*=-1*/, bool preserve/*=false*/ ) { // 开辟新空间:[0] to [toUBound] if (toUBound >= 0) { MemType * ptrNew = new MemType [toUBound + 1]; // +1 为使可用下标最大到 toUBound // 新空间清零 memset(ptrNew, 0, sizeof(MemType)*(toUBound + 1)); // 将原有空间内容拷贝到新空间 if (preserve && arr!=0 && uboundCurrent>=0) { int ctToCpy; // 保留原有数据,需要拷贝内存的 MemType 元素个数 ctToCpy = uboundCurrent; if (uboundCurrent>toUBound) ctToCpy = toUBound; // 取 uboundCurrent 和 toUBound 的最小值 ctToCpy = ctToCpy + 1; // 必须 +1,因为 uboundCurrent 和 toUBound 都是数组上界 memcpy(ptrNew, arr, sizeof(MemType)*ctToCpy); } // 删除原有空间 if (arr!=0 && uboundCurrent>=0) delete [] arr; // 指针指向新空间 arr = ptrNew; return toUBound; } else // if (toUBound < 0),不开辟空间,删除原有空间 { if(arr!=0 && uboundCurrent>=0) delete [] arr; arr = 0; return 0; } } // 重定义 一个 int 类型的数组(如可以是 mem[])的大小,新定义空间自动清零 // arr:为数组指针,可传递:mem,本函数将修改此指针的指向 // toUBound:为要重定义后数组的上界,定义为:[0] to [toUBound],为 -1 时不开辟空间,可用于删除原 // 空间,并 arr 会被设为0 // uboundCurrent:为重定义前数组的上界 [0] to [uboundCurrent],为 -1 表示尚未开辟过空间为第一次调用 // preserve:保留数组原始数据否则不保留 // 返回新空间上标,即 toUBound int CBRecycledArr::RedimArrInt( int * &arr, int toUBound/*=-1*/, int uboundCurrent/*=-1*/, bool preserve/*=false*/ ) { // 开辟新空间:[0] to [toUBound] if (toUBound >= 0) { int * ptrNew = new int [toUBound + 1]; // +1 为使可用下标最大到 toUBound // 新空间清零 memset(ptrNew, 0, sizeof(int)*(toUBound + 1)); // 将原有空间内容拷贝到新空间 if (preserve && arr!=0 && uboundCurrent>=0) { int ctToCpy; // 保留原有数据,需要拷贝内存的 int 元素个数 ctToCpy = uboundCurrent; if (uboundCurrent>toUBound) ctToCpy = toUBound; // 取 uboundCurrent 和 toUBound 的最小值 ctToCpy = ctToCpy + 1; // 必须 +1,因为 uboundCurrent 和 toUBound 都是数组上界 memcpy(ptrNew, arr, sizeof(int)*ctToCpy); } // 删除原有空间 if (arr!=0 && uboundCurrent>=0) delete [] arr; // 指针指向新空间 arr = ptrNew; return toUBound; } else // if (toUBound < 0),不开辟空间,删除原有空间 { if(arr!=0 && uboundCurrent>=0) delete [] arr; arr = 0; return 0; } } // 用二分查找法在数组 recycles 中查找元素 itemToFind 的位置 // 数组 recycles 已按从小到大排序;数据下标要从1开始, recyUsedCount 同时为下标上界 // 函数返回值: // 1. 如找到元素在数组中存在,返回存在的下标(>0); // 2. 如不存在要找的元素,函数返回负数(<0),其绝对值为维护排序该数据要被插入的位置 // (若要插入的位置在最后一个元素之后,函数返回的负数的绝对值为原最大下标+1) // 3. 出错返回 0 int CBRecycledArr::FindPosInSortedRecycle( int itemToFind ) { int iStart=1, iEnd=recyUsedCount; int i; if (recyUsedCount<1) return -1; // 数组还没有元素,返回-1,表示第一个数据要被插入到下标为 [1] 的位置(数组下标从1开始) while(iStart<=iEnd) { i = iStart+(iEnd-iStart)/2; if (itemToFind > recycles[i]) iStart = i + 1; else if(itemToFind < recycles[i]) iEnd = i - 1; else return i; // 找到元素,下标为 i } // 没有找到,返回要插入的位置:直接返回 iEnd+1 的负数即可 return -(iEnd+1); } // 根据用户 index,获得在 mem[] 中的下标;删除数据后,后续数据 index 会自动调整;使 index 总为 1~Count // 出错返回 0 int CBRecycledArr::UserIndexToMemIndex( int index ) { // 获得在 回收站 中记录的那些下标中,比 index 小的有几个 => i int i=FindPosInSortedRecycle(index); if (i<0) i=-i-1; // else 直接返回 index+i return index+i; } ////////////////////////////////////////////////////////////////////// // CBRecycledArrInt 类的实现:整型版带回收站的数组 // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Static 常量定值 ////////////////////////////////////////////////////////////////////// const int CBRecycledArrInt::mcIniMemSize = 7; // 初始 mem[] 的大小 const int CBRecycledArrInt::mcMaxItemCount = 100000000; // 最多元素个数(由于内存原因,2G内存之内,sizeof(MemType)*此值不得超过2G) const float CBRecycledArrInt::mcExpandMaxPort = 0.75; // 已有元素个数大于 0.75*memCount 时就扩大 mem[] 的空间 const int CBRecycledArrInt::mcExpandCountThres = 10000; // 扩大 mem[] 空间时,若 memCount 小于此值则每次扩大到 memCount*2;若 memCount 大于此值则每次扩大到 Count+Count/2 const int CBRecycledArrInt::mcExpandCountThresMax = 10000000;// 扩大 mem[] 空间时,若 memCount 已大于此值,则每次不再扩大到 Count+Count/2,而只扩大到 Count+mcExpandBigPer const int CBRecycledArrInt::mcExpandBigPer = 1000000; // 扩大 mem[] 空间时,若 memCount 已大于 mcExpandCountThresMax,则每次不再扩大到到 Count+Count/2,而只扩大到 Count+mcExpandBigPer const int CBRecycledArrInt::mcRecyExpandPer = 100; // 扩大 recycles[] 空间时,每次扩大的大小 ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBRecycledArrInt::CBRecycledArrInt(int initSize/*=0*/) { // 初始化成员变量的值 mem = 0; memCount = 0; memUsedCount = 0; recycles = 0; recyCount = 0; recyUsedCount = 0; mTravIdxCurr = 0; // 开辟初始空间 if (initSize) { // 开辟 initSize 大小的空间 RedimArrMemType(mem, initSize); memCount = initSize; } else { // 开辟 mcIniMemSize 大小的空间 RedimArrMemType(mem, mcIniMemSize); memCount = mcIniMemSize; } } CBRecycledArrInt::~CBRecycledArrInt() { if (mem) delete []mem; mem = 0; memCount = 0; memUsedCount = 0; if (recycles) delete []recycles; recycles = 0; recyCount = 0; recyUsedCount = 0; mTravIdxCurr = 0; } ////////////////////////////////////////////////////////////////////// // 公有函数 ////////////////////////////////////////////////////////////////////// // 添加新数据,返回新数据被保存到的 mem[] 中的下标(>0),出错返回0 int CBRecycledArrInt::Add( DataType data, DataIntType dataInt /*= 0*/, DataFloatType dataFloat /*= 0.0*/, DataDoubleType dataDouble /*= 0.0*/ ) { int idx = 0; // 要将新数据存入 mem[idx] // 为新数据分配新空间,获得空间下标 idx if (recycles!=0 && recyUsedCount>0) { // 回收站中有空间,使用回收站中的最后一个空间 idx = recycles [recyUsedCount]; recyUsedCount--; } else { // 回收站中没有空间,使用 mem[idx] 中的下一个可用空间 if (memUsedCount+1 <= memCount) { memUsedCount++; idx = memUsedCount; } else { // Redim preserve mem[1 to memCount + 一批] ExpandMem(); // 扩大空间后再次判断 if (memUsedCount+1 <= memCount) { memUsedCount++; idx = memUsedCount; } else { // 扩大空间后还不能 memUsedCount <= memCount,无法分配空间,返回出错 return 0; } } } // 保存新数据 mem[idx].Data = data; mem[idx].DataInt = dataInt; mem[idx].DataFloat = dataFloat; mem[idx].DataDouble = dataDouble; mem[idx].Used = true; // 返回新数据被保存到的 mem[] 中的下标 return idx; } bool CBRecycledArrInt::Remove( int index ) { if (index<1 || index>memCount) return false; // index 不合法 if (! mem[index].Used) return false; // 数据已被删除 // 设置数据值为空 mem[index].Data = 0; mem[index].DataInt = 0; mem[index].DataFloat = 0.0; mem[index].DataDouble = 0.0; mem[index].Used = false; // 在回收站中记录该空间已被删除 if (recycles==0 || recyUsedCount + 1 > recyCount) { // 扩大回收站中的空间 RedimArrInt(recycles, recyCount+mcRecyExpandPer, recyCount, true); recyCount = recyCount+mcRecyExpandPer; } recyUsedCount++; recycles[recyUsedCount] = index; // 返回成功 return true; } CBRecycledArrInt::DataType CBRecycledArrInt::Item( int index, bool bRaiseErrIfNotHas/*=false*/ ) { if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } return mem[index].Data; } CBRecycledArrInt::DataIntType CBRecycledArrInt::ItemInt( int index, bool bRaiseErrIfNotHas/*=false*/ ) { if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0; } return mem[index].DataInt; } CBRecycledArrInt::DataFloatType CBRecycledArrInt::ItemFloat( int index, bool bRaiseErrIfNotHas/*=false*/ ) { if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0.0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0.0; } return mem[index].DataFloat; } CBRecycledArrInt::DataDoubleType CBRecycledArrInt::ItemDouble( int index, bool bRaiseErrIfNotHas/*=false*/ ) { if (index<1 || index>memCount) // index 不合法 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0.0; } if (! mem[index].Used) // 数据已被删除 { if (bRaiseErrIfNotHas) throw (unsigned char)5; // 无效的过程调用或参数 return 0.0; } return mem[index].DataDouble; } void CBRecycledArrInt::Clear() { if (mem) delete []mem; if (recycles) delete []recycles; mem = 0; memCount = 0; memUsedCount = 0; recycles = 0; recyCount = 0; recyUsedCount = 0; mTravIdxCurr = 0; // 开辟 mcIniMemSize 大小的空间 RedimArrMemType(mem, mcIniMemSize); memCount = mcIniMemSize; } void CBRecycledArrInt::StartTraversal() { mTravIdxCurr = 1; } CBRecycledArrInt::DataType CBRecycledArrInt::NextItem( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].Data;} } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0; } CBRecycledArrInt::DataIntType CBRecycledArrInt::NextDataInt( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].DataInt;} } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0; } CBRecycledArrInt::DataFloatType CBRecycledArrInt::NextDataFloat( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].DataFloat;} } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0.0; } CBRecycledArrInt::DataDoubleType CBRecycledArrInt::NextDataDouble( bool &bRetNotValid ) { bRetNotValid = true; // 预设返回数据成功 for (; mTravIdxCurr<=memCount; mTravIdxCurr++) { if (mem[mTravIdxCurr].Used) {mTravIdxCurr++; return mem[mTravIdxCurr-1].DataDouble; } } // 返回数据结束,此时函数返回值无效 bRetNotValid = false; return 0.0; } // 返回当前拥有的数据个数 int CBRecycledArrInt::Count() { int ct = memUsedCount-recyUsedCount; if (ct<0) ct = 0; return ct; } ////////////////////////////////////////////////////////////////////// // 私有函数 ////////////////////////////////////////////////////////////////////// void CBRecycledArrInt::ExpandMem( void ) { int toCount = 0; if (memCount < mcExpandCountThres) { // 如果数据总数“比较少”,就扩增空间为原来的2倍 toCount = memCount * 2; } else if (memCount < mcExpandCountThresMax) { // 如果数据总数已经“有点多”,就扩增空间为原来的1.5倍 toCount = memCount * 3 / 2; } else { // 如果数据总数“很多”,就扩增 mcExpandBigPer 个空间 toCount = memCount + mcExpandBigPer; } // 重定义数组大小 // ReDim Preserve mem(1 To toCount) RedimArrMemType(mem, toCount, memCount, true); memCount = toCount; } // 重定义 一个 MemType 类型的数组(如可以是 recycles)的大小,新定义空间自动清零 // arr:为数组指针,可传递:recycles,本函数将修改此指针的指向 // toUBound:为要重定义后数组的上界,定义为:[0] to [toUBound],为 -1 时不开辟空间,可用于删除原 // 空间,并 arr 会被设为0 // uboundCurrent:为重定义前数组的上界 [0] to [uboundCurrent],为 -1 表示尚未开辟过空间为第一次调用 // preserve:保留数组原始数据否则不保留 // 返回新空间上标,即 toUBound int CBRecycledArrInt::RedimArrMemType( MemType * &arr, int toUBound/*=-1*/, int uboundCurrent/*=-1*/, bool preserve/*=false*/ ) { // 开辟新空间:[0] to [toUBound] if (toUBound >= 0) { MemType * ptrNew = new MemType [toUBound + 1]; // +1 为使可用下标最大到 toUBound // 新空间清零 memset(ptrNew, 0, sizeof(MemType)*(toUBound + 1)); // 将原有空间内容拷贝到新空间 if (preserve && arr!=0 && uboundCurrent>=0) { int ctToCpy; // 保留原有数据,需要拷贝内存的 MemType 元素个数 ctToCpy = uboundCurrent; if (uboundCurrent>toUBound) ctToCpy = toUBound; // 取 uboundCurrent 和 toUBound 的最小值 ctToCpy = ctToCpy + 1; // 必须 +1,因为 uboundCurrent 和 toUBound 都是数组上界 memcpy(ptrNew, arr, sizeof(MemType)*ctToCpy); } // 删除原有空间 if (arr!=0 && uboundCurrent>=0) delete [] arr; // 指针指向新空间 arr = ptrNew; return toUBound; } else // if (toUBound < 0),不开辟空间,删除原有空间 { if(arr!=0 && uboundCurrent>=0) delete [] arr; arr = 0; return 0; } } // 重定义 一个 int 类型的数组(如可以是 mem[])的大小,新定义空间自动清零 // arr:为数组指针,可传递:mem,本函数将修改此指针的指向 // toUBound:为要重定义后数组的上界,定义为:[0] to [toUBound],为 -1 时不开辟空间,可用于删除原 // 空间,并 arr 会被设为0 // uboundCurrent:为重定义前数组的上界 [0] to [uboundCurrent],为 -1 表示尚未开辟过空间为第一次调用 // preserve:保留数组原始数据否则不保留 // 返回新空间上标,即 toUBound int CBRecycledArrInt::RedimArrInt( int * &arr, int toUBound/*=-1*/, int uboundCurrent/*=-1*/, bool preserve/*=false*/ ) { // 开辟新空间:[0] to [toUBound] if (toUBound >= 0) { int * ptrNew = new int [toUBound + 1]; // +1 为使可用下标最大到 toUBound // 新空间清零 memset(ptrNew, 0, sizeof(int)*(toUBound + 1)); // 将原有空间内容拷贝到新空间 if (preserve && arr!=0 && uboundCurrent>=0) { int ctToCpy; // 保留原有数据,需要拷贝内存的 int 元素个数 ctToCpy = uboundCurrent; if (uboundCurrent>toUBound) ctToCpy = toUBound; // 取 uboundCurrent 和 toUBound 的最小值 ctToCpy = ctToCpy + 1; // 必须 +1,因为 uboundCurrent 和 toUBound 都是数组上界 memcpy(ptrNew, arr, sizeof(int)*ctToCpy); } // 删除原有空间 if (arr!=0 && uboundCurrent>=0) delete [] arr; // 指针指向新空间 arr = ptrNew; return toUBound; } else // if (toUBound < 0),不开辟空间,删除原有空间 { if(arr!=0 && uboundCurrent>=0) delete [] arr; arr = 0; return 0; } } ////////////////////////////////////////////////////////////////////// // CHeapMemory 类的实现:用全局对象维护所有通过 new 分配的内存指针 // ////////////////////////////////////////////////////////////////////// CBHeapMemory::CBHeapMemory(int initSize/*=0*/) { // 开辟初始空间 if (initSize) initSize=1000; memHash.AlloMem(initSize); } CBHeapMemory::~CBHeapMemory() { Dispose(); } int CBHeapMemory::AddPtr( void *ptrNew, bool bArrayNew/*=true*/ ) { memHash.Add((long)ptrNew, (long)ptrNew, bArrayNew, 0, 0, 0, 0, false); return memHash.Count(); } // 用 new 分配 size 个字节的空间,并自动清0 void * CBHeapMemory::Alloc( int size ) { char * ptr=new char[size]; memset(ptr, 0, size); AddPtr(ptr, true); return (void *)ptr; } // 释放 ptr 所指向的一段内存空间 // ptr 必须是由本对象所管理的空间,否则本函数不会释放 void CBHeapMemory::Free( void *ptr ) { if ( ptr && memHash.IsKeyExist((long)ptr) ) { if ( memHash.Item((long)ptr,false) == (long)ptr ) // 校验,若 !=,不 delete { if (memHash.ItemLong((long)ptr,false) ) delete []ptr; else delete ptr; } memHash.Remove((long)ptr, false); } } bool CBHeapMemory::IsPtrManaged( void *ptr ) { return memHash.IsKeyExist((long)ptr); } int CBHeapMemory::CountPtrs() { return memHash.Count(); } void * CBHeapMemory::PtrEach( int index, bool * ptrbArrayNew/*=0*/ ) { if ( ptrbArrayNew ) { if ( memHash.ItemLongFromIndex(index,false) ) *ptrbArrayNew=true; else *ptrbArrayNew=false; } return (void *)memHash.ItemFromIndex(index, false); } void CBHeapMemory::Dispose() { // 删除对象中记录的所有空间 int i=0; void * ptr; for (i=1; i<=memHash.Count(); i++) { ptr = (void *)memHash.ItemFromIndex(i,false); if ( ptr ) { if ( memHash.ItemLongFromIndex(i,false) ) delete [] ptr; else delete ptr; memHash.ItemFromIndexSet(i, 0, false); } } // 清空 memHash memHash.Clear(); } // 清零一块内存空间(实际是调用 memset (本类已 include <memory.h>) , // 为使主调程序不必再 include <memory.h>,本类也提供了这个功能接口) void CBHeapMemory::ZeroMem( void * ptr, unsigned int length ) { memset(ptr, 0, length); } // 内存拷贝(实际是调用 memcpy (本类已 include <memory.h>) , // 为使主调程序不必再 include <memory.h>,本类也提供了这个功能接口) void CBHeapMemory::CopyMem( void * dest, void * source, unsigned int length ) { memcpy(dest, source, length); }
#include "object\SpellCard.h" #include "Config.h" #include "Resource.h" const int SpellCard::FLAG_FALSE = 0; const int SpellCard::FLAG_TRUE = 1; const int SpellCard::FLAG_ENDURANCE = 2; SpellCard::SpellCard() : SpellCard({ Ref::FLD_W * (Config::GetInstance()->GetResolutionNo() * 0.5F + 1.0F) - 8.0F - Config::GetInstance()->GetResolutionNo() * 4.0F, 8.0F + Config::GetInstance()->GetResolutionNo() * 4.0F }) { } SpellCard::SpellCard(Vector2 pos) : Object(pos) { } void SpellCard::Init() { } void SpellCard::Fin() { } void SpellCard::Update() { } void SpellCard::Draw() const { int handle = Resource::GetFont(); int width = GetDrawStringWidthToHandle(spellCardName, strlen(spellCardName), handle); int res = Config::GetInstance()->GetResolutionNo() * 8; DrawStringFToHandle(16 + res + position.x - width, 16 + res + position.y, spellCardName, GetColor(255, 255, 255), handle); } SpellCard* SpellCard::WithName(const char name[64]) { strcpy_s(spellCardName, name); return this; } SpellCard* SpellCard::WithBonus(int flag, int amount) { bonusFlag = flag; bonusAmount = amount; return this; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Espen Sand */ #ifndef X11_SKIN_ELEMENT_H #define X11_SKIN_ELEMENT_H #include "modules/skin/OpSkinElement.h" class X11SkinElement : public OpSkinElement { public: X11SkinElement(OpSkin* skin, const OpStringC8& name, SkinType type, SkinSize size); virtual ~X11SkinElement(); virtual OP_STATUS Draw(VisualDevice* vd, OpRect rect, INT32 state, DrawArguments args); virtual OP_STATUS GetTextColor(UINT32* color, INT32 state); virtual OP_STATUS GetSize(INT32* width, INT32* height, INT32 state); virtual OP_STATUS GetMargin(INT32* left, INT32* top, INT32* right, INT32* bottom, INT32 state); virtual OP_STATUS GetPadding(INT32* left, INT32* top, INT32* right, INT32* bottom, INT32 state); virtual void OverrideDefaults(OpSkinElement::StateElement* se); virtual OP_STATUS GetSpacing(INT32* spacing, INT32 state); virtual BOOL IsLoaded() {return m_native_type == NATIVE_NOT_SUPPORTED ? OpSkinElement::IsLoaded() : TRUE;} private: enum NativeType { NATIVE_NOT_SUPPORTED, // for everyone else NATIVE_PUSH_BUTTON, NATIVE_PUSH_DEFAULT_BUTTON, NATIVE_TOOLBAR_BUTTON, NATIVE_SELECTOR_BUTTON, NATIVE_MENU, NATIVE_MENU_BUTTON, NATIVE_MENU_RIGHT_ARROW, NATIVE_MENU_SEPARATOR, NATIVE_POPUP_MENU, NATIVE_POPUP_MENU_BUTTON, NATIVE_HEADER_BUTTON, NATIVE_LINK_BUTTON, NATIVE_TAB_BUTTON, NATIVE_PAGEBAR_BUTTON, NATIVE_CAPTION_MINIMIZE_BUTTON, NATIVE_CAPTION_CLOSE_BUTTON, NATIVE_CAPTION_RESTORE_BUTTON, NATIVE_CHECKBOX, NATIVE_RADIO_BUTTON, NATIVE_DROPDOWN, NATIVE_DROPDOWN_BUTTON, NATIVE_DROPDOWN_LEFT_BUTTON, NATIVE_DROPDOWN_EDIT, NATIVE_EDIT, NATIVE_MULTILINE_EDIT, NATIVE_BROWSER, NATIVE_PROGRESSBAR, NATIVE_START, NATIVE_SEARCH, NATIVE_TREEVIEW, NATIVE_LISTBOX, NATIVE_CHECKMARK, NATIVE_BULLET, NATIVE_WINDOW, NATIVE_BROWSER_WINDOW, NATIVE_DIALOG, NATIVE_DIALOG_PAGE, NATIVE_DIALOG_TAB_PAGE, NATIVE_DIALOG_BUTTON_BORDER, NATIVE_TABS, NATIVE_HOTLIST, NATIVE_HOTLIST_SELECTOR, NATIVE_HOTLIST_SPLITTER, NATIVE_HOTLIST_PANEL_HEADER, NATIVE_SCROLLBAR_HORIZONTAL, NATIVE_SCROLLBAR_HORIZONTAL_KNOB, NATIVE_SCROLLBAR_HORIZONTAL_LEFT, NATIVE_SCROLLBAR_HORIZONTAL_RIGHT, NATIVE_SCROLLBAR_VERTICAL, NATIVE_SCROLLBAR_VERTICAL_KNOB, NATIVE_SCROLLBAR_VERTICAL_UP, NATIVE_SCROLLBAR_VERTICAL_DOWN, NATIVE_SLIDER_HORIZONTAL_TRACK, NATIVE_SLIDER_HORIZONTAL_KNOB, NATIVE_SLIDER_VERTICAL_TRACK, NATIVE_SLIDER_VERTICAL_KNOB, NATIVE_STATUS, NATIVE_MAINBAR, NATIVE_MAINBAR_BUTTON, NATIVE_PERSONALBAR, NATIVE_PAGEBAR, NATIVE_ADDRESSBAR, NATIVE_NAVIGATIONBAR, NATIVE_VIEWBAR, NATIVE_MAILBAR, NATIVE_CHATBAR, NATIVE_CYCLER, NATIVE_PROGRESS_DOCUMENT, NATIVE_PROGRESS_IMAGES, NATIVE_PROGRESS_TOTAL, NATIVE_PROGRESS_SPEED, NATIVE_PROGRESS_ELAPSED, NATIVE_PROGRESS_STATUS, NATIVE_PROGRESS_GENERAL, NATIVE_PROGRESS_CLOCK, NATIVE_PROGRESS_EMPTY, NATIVE_PROGRESS_FULL, NATIVE_IDENTIFY_AS, NATIVE_DIALOG_WARNING, NATIVE_DIALOG_ERROR, NATIVE_DIALOG_QUESTION, NATIVE_DIALOG_INFO, NATIVE_SPEEDDIAL, NATIVE_HORIZONTAL_SEPARATOR, NATIVE_VERTICAL_SEPARATOR, NATIVE_DISCLOSURE_TRIANGLE, NATIVE_SORT_ASCENDING, NATIVE_SORT_DESCENDING, NATIVE_PAGEBAR_CLOSE_BUTTON, NATIVE_NOTIFIER_CLOSE_BUTTON, NATIVE_TOOLTIP, NATIVE_NOTIFIER, NATIVE_EXTENDER_BUTTON, NATIVE_LIST_ITEM, }; private: void DrawDirectionButton(VisualDevice* vd, OpRect rect, int dir, INT32 state, UINT32 fgcol, UINT32 gray, UINT32 lgray, UINT32 dgray, UINT32 dgray2); void DrawArrow(VisualDevice* vd, const OpRect& rect, int direction); void Draw3DBorder(VisualDevice* vd, UINT32 lcolor, UINT32 dcolor, OpRect rect, int omissions=0); void DrawCheckMark(VisualDevice* vd, UINT32 color, const OpRect& rect); void DrawIndeterminate(VisualDevice *vd, UINT32 color, const OpRect &rect); void DrawBullet(VisualDevice* vd, UINT32 color, const OpRect& rect); void DrawCloseCross(VisualDevice* vd, UINT32 color, const OpRect& rect); void DrawTab(VisualDevice* vd, UINT32 lcolor, UINT32 dcolor1, UINT32 dcolor2, const OpRect& rect, BOOL is_active); void DrawFrame(VisualDevice* vd, UINT32 lcolor, UINT32 dcolor1, UINT32 dcolor2, const OpRect& rect); void DrawTopFrameLine(VisualDevice* vd, UINT32 lcolor, UINT32 dcolor1, UINT32 dcolor2, const OpRect& rect); private: NativeType m_native_type; }; #endif
/** hihocoder-#1317-ËÑË÷4-ÌøÎèÁ´ 15/06/16 16:22:19 xuchen **/ #include <iostream> #include <cstdio> #include <cmath> #include <vector> #include <string.h> #include <algorithm> #include <stdlib.h> #include <queue> #include <stack> #include <map> using namespace std; const int N = 105; struct Node{ int x, y; Node *right, *left, *up, *down; /* Node(int x, int y, Node* r, Node* l, Node* u, Node* d) {this->x=x; this->y=y; right=r; left=l; up=u; down=d;} */ }; Node head; Node columnHead[N]; Node nodes[N*N]; int matrix[N][N]; int id[N][N]; int ans[N]; int t; int n, m; int cnt; void build() { head.x=0; head.y=0; head.right=&head; head.left=&head; head.up=&head; head.down=&head; Node *pre = &head; for(int i=1; i<=m; ++i) { Node* p = &columnHead[i]; p->up = p; p->down = p; p->left = pre; p->right = &head; pre->right = p; head.left = p; p->x = 0; p->y = i; pre = p; } cnt=0; for(int i=1; i<=n; ++i) { for(int j=1; j<=m; ++j) { if(1 == matrix[i][j]) { ++cnt; id[i][j] = cnt; nodes[cnt].x=i; nodes[cnt].y=j; nodes[cnt].left=&nodes[cnt]; nodes[cnt].right=&nodes[cnt]; nodes[cnt].up=&nodes[cnt]; nodes[cnt].down=&nodes[cnt]; } } } for(int j=1; j<=m; ++j) { Node* pre = &columnHead[j]; for(int i=1; i<=n; ++i) { if(1==matrix[i][j]) { Node* p = &nodes[id[i][j]]; pre->down->up = p; p->down = pre->down; pre->down = p; p->up=pre; pre = p; } } } for(int i=1; i<=n; ++i) { Node *pre = NULL; for(int j=1; j<=m; ++j) { if(1==matrix[i][j]) { Node* p = &nodes[id[i][j]]; if(NULL == pre) { pre = p; } else { pre->right->left = p; p->right = pre->right; pre->right = p; p->left = pre; pre = p; } } } } } void remove(int col) { Node *p = &columnHead[col]; p->left->right = p->right; p->right->left = p->left; Node *p1 = p->down; while(p1!=p) { Node *p2 = p1->right; while(p2!=p1) { p2->up->down = p2->down; p2->down->up = p2->up; p2 = p2->right; } p1 = p1->down; } } void recover(int col) { Node *p = &columnHead[col]; p->left->right = p; p->right->left = p; Node *p1 = p->down; while(p1!=p) { Node *p2 = p1->right; while(p2!=p1) { p2->up->down = p2; p2->down->up = p2; p2 = p2->right; } p1 = p1->down; } } bool dance(int depth) { Node *p = head.right; if(p==&head) return true; int col = p->y; Node *p2 = p->down; if(p2==p) return false; remove(col); while(p2!=p) { ans[depth] = p2->x; Node *p3 = p2->right; while(p3!=p2) { remove(p3->y); p3 = p3->right; } if(dance(depth+1)) return true; p3 = p2->left; while(p3!=p2) { recover(p3->y); p3 = p3->left; } p2 = p2->down; } recover(col); return false; } int main() { scanf("%d", &t); while(t--) { scanf("%d %d", &n, &m); memset(matrix, 0, sizeof(matrix)); memset(ans, 0, sizeof(ans)); for(int i=1; i<=n; ++i) { for(int j=1; j<=m; ++j) scanf("%d", &matrix[i][j]); } build(); if(dance(0)) printf("Yes\n"); else printf("No\n"); } return 0; }
#pragma once #include "log.hpp" #include "exception.hpp" #include "assert.hpp" #include "string_utils.hpp" #include "json2pb.hpp" #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> #include <google/protobuf/dynamic_message.h> #include <string> #include <fstream> #include <algorithm> #include <iostream> #include <map> #include <set> #include <sstream> #include <functional> #include <list> #include <vector> #include <mutex> #include <boost/filesystem.hpp> using namespace std; namespace gp = google::protobuf; namespace bfs = boost::filesystem; #define CONFIG_DLOG __DLOG << setw(20) << "[CONFIG] " #define CONFIG_ILOG __ILOG << setw(20) << "[CONFIG] " #define CONFIG_ELOG __ELOG << setw(20) << "[CONFIG] " namespace nora { extern mutex ptts_lock; extern string config_path; template <typename T> class ptts { public: void cout_csv_template() const; vector<string> find_csv_files(const string& type); template <typename F> void load_json_file(const string& file); void load_csv_file(const string& file); void load_csv_files(const string& type); template <typename F> void cout_json_file(const string& csv_file, F *f); template <typename F> void cout_bin_file(const string& type, F *f); template <typename F> void write_all_file(const string& type, F *f); void check(); void modify(); void verify() const; void print() const; void enrich(); const T& get_ptt(uint32_t key) const; T& get_ptt(uint32_t key); T get_ptt_copy(uint32_t key) const; const map<uint32_t, T>& get_ptt_all() const; map<uint32_t, T> get_ptt_all_copy() const; bool has_ptt(uint32_t key); function<void(const T&)> check_func_; function<void(T&)> modify_func_; function<void(const T&)> verify_func_; function<void(map<uint32_t, T>&)> enrich_func_; private: void write_message(const gp::Descriptor *desc, ostringstream& oss, string prefix) const; list<string> load_header_line(ifstream& ifs); void load_fields(gp::Message& msg, istringstream& iss, string header, list<string>& headers); map<uint32_t, T> ptts_; }; inline string append_header(const string& header, const string& str) { string ret = header; if (!ret.empty()) { ret += "."; } ret += str; return ret; } inline bool invisible_header(const string& header) { return header[0] == '_'; } template <typename T> void ptts<T>::write_message(const gp::Descriptor *desc, ostringstream& oss, string prefix) const { for (int i = 0; i < desc->field_count(); ++i) { auto *field = desc->field(i); if (invisible_header(field->name())) { continue; } int count = field->is_repeated() ? 1 : 1; for (int i = 0; i < count; ++i) { if (field->type() == gp::FieldDescriptor::TYPE_MESSAGE) { write_message(field->message_type(), oss, prefix.empty() ? field->name() : prefix + "." + field->name()); } else { if (!prefix.empty()) { oss << prefix << "."; } oss << field->name(); oss << ","; } } } } template <typename T> void ptts<T>::cout_csv_template() const { auto *desc = T::descriptor(); auto *first_field = desc->field(0); if (first_field->type() != gp::FieldDescriptor::TYPE_UINT32 && first_field->type() != gp::FieldDescriptor::TYPE_ENUM) { CONFIG_ELOG << desc->name() << "'s first member is neither uint32 nor enum"; return; } ostringstream oss; write_message(desc, oss, ""); oss.seekp(-1, std::ios_base::end); oss << "\n"; cout << oss.str(); } template <typename T> void ptts<T>::load_fields(gp::Message& msg, istringstream& iss, string header, list<string>& headers) { auto *desc = msg.GetDescriptor(); auto *refl = msg.GetReflection(); string grid; for (auto i = 0; i < desc->field_count(); ++i) { const auto *field = desc->field(i); if (invisible_header(field->name())) { continue; } auto cur_header = append_header(header, field->name()); if (headers.empty()) { CONFIG_ELOG << desc->name() << " run out of header when processing " << cur_header; return; } if (field->cpp_type() == gp::FieldDescriptor::CPPTYPE_MESSAGE) { if (field->is_repeated()) { // CONFIG_DLOG << "process repeated message: " << field->name(); const auto *msg_desc = field->message_type(); // CONFIG_DLOG << "first left headers: " << headers.front(); auto next_header = append_header(cur_header, msg_desc->field(0)->name()); // CONFIG_DLOG << "next header: " << next_header; while (!headers.empty() && headers.front().find(next_header) == 0) { // CONFIG_DLOG << "found one"; auto *sub_msg = refl->AddMessage(&msg, field); load_fields(*sub_msg, iss, cur_header, headers); if (sub_msg->ByteSize() <= 0) { refl->RemoveLast(&msg, field); } } } else { auto *sub_msg = refl->MutableMessage(&msg, field); load_fields(*sub_msg, iss, cur_header, headers); if (sub_msg->ByteSize() <= 0) { refl->ClearField(&msg, field); } } } else if (field->is_repeated()) { while (!headers.empty() && headers.front() == cur_header) { getline(iss, grid); headers.pop_front(); if (string(grid.data()).empty()) continue; switch (field->cpp_type()) { case gp::FieldDescriptor::CPPTYPE_BOOL: try { auto value = false; string str = grid.data(); transform(str.begin(), str.end(), str.begin(), ::toupper); if (grid.data() == string("TRUE")) { value = true; } refl->AddBool(&msg, field, value); } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_UINT32: try { if (grid.empty()) { refl->AddUInt32(&msg, field, 0u); } else { refl->AddUInt32(&msg, field, stoul(grid.data())); } } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_INT32: try { if (grid.empty()) { refl->AddInt32(&msg, field, 0); } else { refl->AddInt32(&msg, field, stoi(grid.data())); } } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_INT64: try { if (grid.empty()) { refl->AddInt64(&msg, field, 0); } else { refl->AddInt64(&msg, field, stoi(grid.data())); } } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_UINT64: try { if (grid.empty()) { refl->AddUInt64(&msg, field, 0ul); } else { refl->AddUInt64(&msg, field, stoull(grid.data())); } } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_DOUBLE: try { if (grid.empty()) { refl->AddDouble(&msg, field, 0.); } else { refl->AddDouble(&msg, field, stod(grid.data())); } } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_STRING: refl->AddString(&msg, field, grid.data()); break; case gp::FieldDescriptor::CPPTYPE_ENUM: { const auto *ed = field->enum_type(); const auto *evd = ed->FindValueByName(grid.data()); if (!evd) { CONFIG_ELOG << field->name() << " has invalid enum value " << grid.data(); return; } refl->AddEnum(&msg, field, evd); } break; default: CONFIG_ELOG << field->name() << " has invalid type " << field->cpp_type_name(); return; } } } else { getline(iss, grid); headers.pop_front(); if (string(grid.data()).empty()) continue; switch (field->cpp_type()) { case gp::FieldDescriptor::CPPTYPE_BOOL: try { auto value = false; string str = grid.data(); transform(str.begin(), str.end(), str.begin(), ::toupper); if (str == string("TRUE")) { value = true; } refl->SetBool(&msg, field, value); } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_UINT32: try { refl->SetUInt32(&msg, field, stoul(grid.data())); } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_INT32: try { refl->SetInt32(&msg, field, stoi(grid.data())); } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_INT64: try { refl->SetInt64(&msg, field, stol(grid.data())); } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_UINT64: try { refl->SetUInt64(&msg, field, stoull(grid.data())); } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_DOUBLE: try { refl->SetDouble(&msg, field, stod(grid.data())); } catch (const invalid_argument& e) { CONFIG_ELOG << field->name() << " has invalid value " << grid.data(); return; } break; case gp::FieldDescriptor::CPPTYPE_STRING: refl->SetString(&msg, field, grid.data()); break; case gp::FieldDescriptor::CPPTYPE_ENUM: { const auto *ed = field->enum_type(); const auto *evd = ed->FindValueByName(grid.data()); if (!evd) { CONFIG_ELOG << field->name() << " has invalid enum value " << grid.data(); return; } refl->SetEnum(&msg, field, evd); break; } default: CONFIG_ELOG << field->name() << " has invalid type " << field->cpp_type_name(); return; } } } } template <typename T> list<string> ptts<T>::load_header_line(ifstream& ifs) { list<string> ret; string line; getline(ifs, line); replace(line.begin(), line.end(), ',', '\n'); replace(line.begin(), line.end(), '\r', '\n'); istringstream iss(line); string grid; while (getline(iss, grid)) { ret.push_back(grid); } return ret; } template <typename T> template <typename F> void ptts<T>::load_json_file(const string& file) { lock_guard<mutex> lock(ptts_lock); ptts_.clear(); if (!ptts_.empty()) { return; } ifstream ifs(file); std::string str; ifs.seekg(0, std::ios::end); str.reserve(ifs.tellg()); ifs.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); F f; json2pb(f, str.data(), str.size()); auto *desc = T::descriptor(); auto *first_field = desc->field(0); for (const auto& i : f.entry()) { const auto* reflection = i.GetReflection(); ptts_[reflection->GetUInt32(i, first_field)] = i; } } template <typename T> vector<string> ptts<T>::find_csv_files(const string& type) { vector<string> ret; ostringstream oss; oss << config_path << "/" << type << "_table.csv"; if (bfs::exists(bfs::path(oss.str()))) { ret.push_back(oss.str()); } else { int i = 1; do { oss.str(""); oss << config_path << "/" << type << "_table_" << i << ".csv"; if (!bfs::exists(bfs::path(oss.str()))) { break; } ret.push_back(oss.str()); i += 1; } while (true); } return ret; } template <typename T> void ptts<T>::load_csv_files(const string& type) { lock_guard<mutex> lock(ptts_lock); ptts_.clear(); auto files = find_csv_files(type); for (const auto& i : files) { load_csv_file(i); } } template <typename T> void ptts<T>::load_csv_file(const string& file) { ifstream ifs(file); auto *desc = T::descriptor(); auto *first_field = desc->field(0); if (first_field->type() != gp::FieldDescriptor::TYPE_UINT32 && first_field->type() != gp::FieldDescriptor::TYPE_ENUM) { CONFIG_ELOG << desc->name() << "'s first member is not uint32"; return; } auto headers = load_header_line(ifs); // load all data lines string line; while (getline(ifs, line)) { replace(line.begin(), line.end(), ',', '\n'); replace(line.begin(), line.end(), '\r', '\n'); istringstream iss(line.data()); if (iss.str().empty()) continue; T t; auto headers_copy = headers; load_fields(t, iss, "", headers_copy); uint32_t key = 0; auto *refl = t.GetReflection(); if (first_field->type() == gp::FieldDescriptor::TYPE_UINT32) { key = refl->GetUInt32(t, desc->field(0)); } else { ASSERT(first_field->type() == gp::FieldDescriptor::TYPE_ENUM); ASSERT(desc->field(0)->number() >= 0); key = static_cast<uint32_t>(refl->GetEnum(t, desc->field(0))->number()); } if (ptts_.count(key) != 0) { CONFIG_ELOG << desc->name() << " has duplicate " << first_field->name() << ": " << key; return; } ptts_[key] = t; } } template <typename T> template <typename F> void ptts<T>::cout_json_file(const string& csv_file, F *f) { load_csv_file(csv_file); if (ptts_.empty()) { return; } for (auto& i : ptts_) { auto *entry = f->add_entry(); *entry = i.second; } auto json_str = pb2json(*f); cout << json_str; } template <typename T> template <typename F> void ptts<T>::cout_bin_file(const string& csv_file, F *f) { load_csv_file(csv_file); if (ptts_.empty()) { return; } vector<int> keys; for (auto& i : ptts_) { keys.push_back(i.first); } sort(keys.begin(), keys.end(), [] (auto a, auto b) { return a < b; }); for_each(keys.begin(),keys.end(),[=](int key){ auto *entry = f->add_entry(); *entry = ptts_[key]; }); string bin_str; f->SerializeToString(&bin_str); cout << bin_str; } template <typename T> template <typename F> void ptts<T>::write_all_file(const string& type, F *f) { load_csv_files(type); if (enrich_func_) { enrich_func_(ptts_); } auto ptts = ptts_; auto files = find_csv_files(type); for (const auto& i : files) { ptts_.clear(); f->clear_entry(); load_csv_file(i); if (ptts_.empty()) { return; } vector<int> keys; for (auto& j : ptts_) { keys.push_back(j.first); } sort(keys.begin(), keys.end(), [] (auto a, auto b) { return a < b; }); for_each(keys.begin(), keys.end(), [this, f, &ptts] (auto key){ *f->add_entry() = ptts[key]; }); string file = i; ASSERT(replace_string(file, ".csv", ".config")); ASSERT(replace_string(file, "_table", "")); ofstream bin_file(file, ios_base::binary|ios_base::out|ios_base::trunc); f->SerializeToOstream(&bin_file); file = i; ASSERT(replace_string(file, ".csv", ".json")); ASSERT(replace_string(file, "_table", "")); ofstream json_file(file, ios_base::binary|ios_base::out|ios_base::trunc); json_file << pb2json(*f); } } template <typename T> void ptts<T>::check() { if (check_func_) { for (auto& i : ptts_) { if (i.first >= 1000000000) { CONFIG_ELOG << " config id used more than 9 digits " << i.first; } check_func_(i.second); if (!i.second.IsInitialized()) { CONFIG_ELOG << i.first << i.second.InitializationErrorString(); } } } } template <typename T> void ptts<T>::modify() { if (modify_func_) { for (auto& i : ptts_) { modify_func_(i.second); } } } template <typename T> void ptts<T>::verify() const { if (verify_func_) { for (const auto& i : ptts_) { verify_func_(i.second); if (!i.second.IsInitialized()) { CONFIG_ELOG << i.first << " not initialized: " << i.second.InitializationErrorString(); continue; } }; } } template <typename T> void ptts<T>::print() const { for (const auto& i : ptts_) { CONFIG_ILOG << "\n" << i.second.DebugString(); } } template <typename T> void ptts<T>::enrich() { if (enrich_func_) { enrich_func_(ptts_); } } template <typename T> const T& ptts<T>::get_ptt(uint32_t key) const { lock_guard<mutex> lock(ptts_lock); ASSERT(ptts_.count(key) > 0); return ptts_.at(key); } template <typename T> T& ptts<T>::get_ptt(uint32_t key) { lock_guard<mutex> lock(ptts_lock); ASSERT(ptts_.count(key) > 0); return ptts_.at(key); } template <typename T> T ptts<T>::get_ptt_copy(uint32_t key) const { lock_guard<mutex> lock(ptts_lock); ASSERT(ptts_.count(key) > 0); return ptts_.at(key); } template <typename T> const map<uint32_t, T>& ptts<T>::get_ptt_all() const { lock_guard<mutex> lock(ptts_lock); return ptts_; } template <typename T> map<uint32_t, T> ptts<T>::get_ptt_all_copy() const { lock_guard<mutex> lock(ptts_lock); return ptts_; } template <typename T> bool ptts<T>::has_ptt(uint32_t key) { lock_guard<mutex> lock(ptts_lock); return ptts_.count(key) > 0; } }
#include<iostream> using namespace std; int main() { int month[5][7] = { 0 }; int num = 1; //일 Check int start = 0; //각 월의 1일 시작점 int day; //요일 Check int x, y; cin >> x; cin>> y; //2007년 각 월의 날짜 입력 switch (x) { case 1: if (num <= 31) { for (int i = 0; i < 5; i++) { for (int j = 0; j < 7; j++) { month[i][j] = num; num++; } } } break; case 2: start =3; if (num <= 28) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 3: start =3; if (num <= 31) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 4: start = 6; if (num <= 30) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 5: start = 1; if (num <= 31) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 6: start = 4; if (num <= 30) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 7: start = 6; if (num <= 31) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 8: start = 2; if (num <= 31) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 9: start = 5; if (num <= 30) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 10: start = 0; if (num <= 31) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 11: start = 3; if (num <= 30) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; case 12: start = 5; if (num <= 31) { for (int i = 0; i < 5; i++) { for (int j = start; j < 7; j++) { month[i][j] = num; num++; } start = 0; } } break; } for (int i = 0; i < 5; i++) { for (int j = 0; j < 7; j++) { if (month[i][j] == y) day = j; } }//입력된 x월 y일의 요일 찾기 switch (day) { case 0: cout << "MON"; break; case 1: cout << "TUE"; break; case 2: cout << "WED"; break; case 3: cout << "THU"; break; case 4: cout << "FRI"; break; case 5: cout << "SAT"; break; case 6: cout << "SUN"; break; } return 0; }
#include "JvState.h" #include "JvText.h" #include "GameState.h" JvState::JvState() : camera(NULL),defaultGroup(NULL) { _bgColor =0; if (NULL == camera) camera = new JvCamera; if (NULL == defaultGroup) defaultGroup = new JvGroup; m_ccbglayer = CCLayerColor::create(); m_ccbglayer->retain(); } JvState::~JvState() { if (camera) delete camera; if (defaultGroup) delete defaultGroup; m_ccbglayer->release(); } void JvState::create() { camera->init(JvG::width,JvG::height); JvG::camera = camera; m_ccbglayer->setContentSize(CCSizeMake(JvG::width,JvG::height)); } void JvState::update() { if (JvG::pause) { pause(); return; } defaultGroup->update(); camera->update(); } void JvState::render() { if (_bgColor!=0) { m_ccbglayer->visit(); } defaultGroup->render(); camera->renderFlash(); } void JvState::collide() { JvU::collide(defaultGroup,defaultGroup); } void JvState::add(JvObject* ObjectP) { defaultGroup->add(ObjectP); } void JvState::setBgColor(int Color) { _bgColor = Color; int r,g,b,a; GET_RGBA_8888(Color,r,g,b,a); m_ccbglayer->setColor(ccc3(r,g,b)); m_ccbglayer->setOpacity(a); } void JvState::pause() { } void JvState::loading() { JvText* loadtxt = new JvText(25,JvG::height-50,300,50,"Arial","Loading..."); loadtxt->setSize(20); add(loadtxt); }
// // TCPServerConnection.cpp // // $Id: //poco/1.4/Net/src/TCPServerConnection.cpp#1 $ // // Library: Net // Package: TCPServer // Module: TCPServerConnection // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "_Net/TCPServerConnection.h" #include "_/Exception.h" #include "_/ErrorHandler.h" using _::Exception; using _::ErrorHandler; namespace _Net { TCPServerConnection::TCPServerConnection(const StreamSocket& rSocket): _socket(rSocket) { } TCPServerConnection::~TCPServerConnection() { } void TCPServerConnection::start() { try { run(); } catch (Exception& exc) { ErrorHandler::handle(exc); } catch (std::exception& exc) { ErrorHandler::handle(exc); } catch (...) { ErrorHandler::handle(); } } } //< namespace _Net
// Created on: 2002-12-12 // Created by: data exchange team // Copyright (c) 2002-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepElement_SurfaceSectionFieldConstant_HeaderFile #define _StepElement_SurfaceSectionFieldConstant_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepElement_SurfaceSectionField.hxx> class StepElement_SurfaceSection; class StepElement_SurfaceSectionFieldConstant; DEFINE_STANDARD_HANDLE(StepElement_SurfaceSectionFieldConstant, StepElement_SurfaceSectionField) //! Representation of STEP entity SurfaceSectionFieldConstant class StepElement_SurfaceSectionFieldConstant : public StepElement_SurfaceSectionField { public: //! Empty constructor Standard_EXPORT StepElement_SurfaceSectionFieldConstant(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init (const Handle(StepElement_SurfaceSection)& aDefinition); //! Returns field Definition Standard_EXPORT Handle(StepElement_SurfaceSection) Definition() const; //! Set field Definition Standard_EXPORT void SetDefinition (const Handle(StepElement_SurfaceSection)& Definition); DEFINE_STANDARD_RTTIEXT(StepElement_SurfaceSectionFieldConstant,StepElement_SurfaceSectionField) protected: private: Handle(StepElement_SurfaceSection) theDefinition; }; #endif // _StepElement_SurfaceSectionFieldConstant_HeaderFile
#include <iostream> #include <fstream> #include <queue> #include "Passenger.h" #include "Event.h" using namespace std; int check = 0; struct Compare{ public: bool operator()(pair<Passenger, Passenger*> a, pair<Passenger, Passenger*> b) { if(check == 0){ if(a.first.lastTime == b.first.lastTime){ return a.first.arrive > b.first.arrive; }else{ return a.first.lastTime > b.first.lastTime; } } else{ if(a.first.board == b.first.board) { return a.first.arrive > b.first.arrive; } else{ return a.first.board > b.first.board; } } } }; priority_queue<pair<Passenger, Passenger*>, vector<pair<Passenger, Passenger*>>, Compare> tailLug; priority_queue<pair<Passenger, Passenger*>, vector<pair<Passenger, Passenger*>>, Compare> tailSec; priority_queue<Event> events; int main() { for(int l = 0; l <= 1; l++){ for(int v = 0; v <= 1; v++){ for(int f = 0; f <= 1; f++){ check = f; ifstream inp("/home/student/ClionProjects/CmpeAirlines/inputLarge1.txt"); int n; int capLug; int capSec; inp >> n >> capLug >>capSec; int countLug = 0; int countSec = 0; for(int i = 0; i < n; i++){ int arrive; int board; int luggage; int security; string vip; string online; inp >> arrive >> board >> luggage >> security >> vip >> online; Passenger* passenger = new Passenger(arrive, board, luggage, security, vip, online); Event* eee = new Event(arrive, 2, passenger); events.push(*eee); } int sumOfTime = 0; int miss = 0; while(events.size()){ Event check = events.top(); events.pop(); if(check.place == 2){ if(check.passenger->online == "N" && l == 1){ check.place = 1; events.push(check); } else{ if(countLug < capLug){ countLug++; check.time += check.passenger->luggage; check.place = 1; events.push(check); } else{ pair<Passenger, Passenger*> pairLug = make_pair(*check.passenger, check.passenger); tailLug.push(pairLug); } } } else if(check.place == 1){ if(check.passenger->online == "L" || l == 0){ countLug--; if(tailLug.size()){ int t = check.time + tailLug.top().second->luggage; Event event(t, 1, tailLug.top().second); events.push(event); tailLug.pop(); countLug++; } } if(check.passenger->vip == "V" && v == 1){ check.place = 0; events.push(check); } else{ if(countSec < capSec){ countSec++; check.time+= check.passenger->security; check.place = 0; events.push(check); } else{ check.passenger->lastTime = check.time; pair<Passenger, Passenger*> pairSec = make_pair(*check.passenger, check.passenger); tailSec.push(pairSec); } } } else{ if(check.passenger->vip == "N" || v == 0){ countSec--; if(tailSec.size()){ int t = check.time + tailSec.top().second->security; Event event(t, 0, tailSec.top().second); events.push(event); tailSec.pop(); countSec++; } } sumOfTime += check.time - check.passenger->arrive; if(check.time > check.passenger->board){ miss++; } } } float sum = sumOfTime * 1.0; float avgTime; avgTime = sum / n; cout << avgTime << " " << miss << endl; } } } return 0; }
#include "FBullCowGame.h" #include <string> using FString = std::string; using int32 = int; FBullCowGame::FBullCowGame() { Reset(); } int32 FBullCowGame::GetMaxTries() const {return MyMaxTrie;} int32 FBullCowGame::GetCurrentTry() const {return MyCurrentTry;} void FBullCowGame::Reset() { constexpr int32 MAX_TRIES = 3; MyMaxTrie = MAX_TRIES; MyCurrentTry = 1; const FString HIDDEN_WORD = "planet"; MyHiddenWord = HIDDEN_WORD; return; } bool FBullCowGame::IsGameWon() const { return false; } EGuessStatus FBullCowGame::CheckGuessValidity(FString Guess) const { if (false)// if the guess isn't an isogram { return EGuessStatus::No_Isogram; // return not isogram error } else if(false) // if the guess isn't all lowercase { return EGuessStatus::Not_Lowercase; } else if(Guess.length() != GetHiddenWordLenght()) // if the guess length is worng { return EGuessStatus::Wrong_Length; } else { return EGuessStatus::OK; } } int32 FBullCowGame::GetHiddenWordLenght() const { return MyHiddenWord.length(); } FBullCowCount FBullCowGame::SubmitGuess(FString Guess) { // increase the turn number MyCurrentTry++; // Setup a return variable FBullCowCount BullCowCount; // loop through all the letters in the guess int32 HiddenWordLenght = MyHiddenWord.length(); for (int32 i=0; i < HiddenWordLenght; i++){ // comparte letters against the hidden word for (int32 j = 0; j < HiddenWordLenght; j++){ // if they match then if (Guess[i] == MyHiddenWord[i]){ //if they are in the same place if (i==j){ BullCowCount.Bulls++; // incremetn bulls } // else else { BullCowCount.Cows++;// incremente cows } } } } return BullCowCount; }
#include <iostream> #include <algorithm> using namespace std; int t, n, previ[100001], a[100001]; bool flag; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; for (int i = 0; i < t; i++) { cin >> n; flag = false; for (int j = 1; j <= n; j++) cin >> a[j]; for (int j = 1; j <= n; j++) { if (previ[a[a[j]]] != a[j] && previ[a[a[j]]] != 0) { // cout << previ[a[a[j]]] << "|" << a[j] << endl; flag = true; break; } previ[a[a[j]]] = a[j]; } if (flag) cout << "Truly Happy" << endl; else cout << "Poor Chef" << endl; fill(previ, previ + n + 1, 0); } }
// This test verifies that the various staggered Dslash functions are working correctly. // * Compares the \gamma5 D function with applying D then \gamma_5. // * Compares the D^\dagger function with applying \gamma_5 then D then \gamma_5 // * Compares summing applying D_{eo}, D_{oe}, and the mass term to applying D. // * Compares summing applying -D_{eo}D_{oe}, -D_{oe}D_{eo}, and the mass term squared to applying D^\dagger D. // * Compares inverting D directly with even-odd reconstruction. // * Compares creating and applying a D stencil to the D function. // * Compares creating and applying a \gamma5 D stencil to the \gamma5 D function. // * Compares creating and applying a D^\dagger stencil to the D^\dagger function. // * Compares applying a \gamma5 D stencil to applying a D stencil then a (-1)^coord function. // * Compares applying a D^\dagger stencil to applying a (-1)^coord function then D stencil then (-1)^coord function. // * Compares summing applying D_{eo}, D_{oe}, and the mass term via stencil to applying a D stencil. // * Compares summing applying -D_{eo}D_{oe}, -D_{oe}D_{eo} via stencil, and the stencil shift term to applying D^\dagger D via stencils. // * Compares inverting a D stencil directly with even-odd stencil reconstruction. // * Compares applying a D stencil to applying a D stencil with the hypercube rotated into degrees of freedom. // * Compares applying a \gamma5 D stencil to performing a dof rotation, applying D_internal, applying \sigma3, undoing dof rotation. // * Compares applying a D^\dagger stencil to performing a dof rotation, applying \sigma3, D_internal, \sigma3, undoing dof rotation. // * Compares applying a D stencil to performing a dof rotation, summing applying D_{tb}, D_{bt}, and the mass, then undoing dof rotation. // * Compares summing applying an internal -D_{tb}D_{bt}, -D_{bt}D_{tb}, and the stencil shift term to applying D^\dagger D via stencils. // * Compares inverting a D_internal stencil directly with top-bottom stencil reconstruction. #include <iostream> #include <iomanip> // to set output precision. #include <cmath> #include <string> #include <sstream> #include <complex> #include <random> #include <cstring> // should be replaced by using sstream // Things for timing. #include <stdlib.h> #include <unistd.h> #include <time.h> // For Dslash pieces and even/odd preconditioning tests. #include "generic_bicgstab_l.h" #include "generic_cg.h" #include "generic_vector.h" #include "verbosity.h" #include "u1_utils.h" #include "operators.h" // For stencil related tests. #include "lattice.h" #include "lattice_functions.h" #include "operators_stencil.h" // For internal dof related tests. #include "mg.h" #include "mg_complex.h" #include "null_gen.h" using namespace std; // Define pi. #define PI 3.141592653589793 // Custom routine to load gauge field. void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA); // Timing routine. timespec diff(timespec start, timespec end) { timespec tmp; if ((end.tv_nsec-start.tv_nsec) < 0) { tmp.tv_sec = end.tv_sec-start.tv_sec-1; tmp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { tmp.tv_sec = end.tv_sec-start.tv_sec; tmp.tv_nsec = end.tv_nsec-start.tv_nsec; } return tmp; } int main(int argc, char** argv) { // Declare some variables. cout << setiosflags(ios::scientific) << setprecision(6); int i,j,x,y; complex<double> *gfield; // Holds the gauge field. complex<double> *lhs, *lhs2, *rhs, *rhs2, *check; // For some Kinetic terms. complex<double> *rhs_internal, *lhs_internal, *lhs2_internal; complex<double> tmp; complex<double> *tmp2, *tmp3; std::mt19937 generator (1337u); // RNG, 1337u is the seed. inversion_info invif; staggered_u1_op stagif; double bnorm; stringstream sstream; // Timing. timespec time1, time2, timediff; // Set parameters. // L_x = L_y = Dimension for a square lattice. int square_size = 64; // Can be set on command line with --square_size. // What masses should we use? double mass = 1e-1; // Solver precision. double outer_precision = 1e-6; // Restart iterations. int outer_restart = 64; // Gauge field information. double BETA = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta). // For heatbath gauge field, corresponds to non-compact beta. // Can be set on command line with --beta. // Load an external cfg? char* load_cfg = NULL; bool do_load = false; ///////////////////////////////////////////// // Get a few parameters from command line. // ///////////////////////////////////////////// for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0) { cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n"; cout << "--lattice-size [32, 64, 128] (default 64)\n"; cout << "--mass [#] (default 1e-1)\n"; cout << "--load-cfg [path] (default do not load, overrides beta)\n"; return 0; } if (i+1 != argc) { if (strcmp(argv[i], "--beta") == 0) { BETA = atof(argv[i+1]); i++; } else if (strcmp(argv[i], "--lattice-size") == 0) { square_size = atoi(argv[i+1]); i++; } else if (strcmp(argv[i], "--mass") == 0) { mass = atof(argv[i+1]); i++; } else if (strcmp(argv[i], "--load-cfg") == 0) { load_cfg = argv[i+1]; do_load = true; i++; } else { cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n"; cout << "--operator [laplace, staggered, g5_staggered, \n"; cout << " normal_staggered, index] (default staggered)\n"; cout << "--lattice-size [32, 64, 128] (default 32)\n"; cout << "--mass [#] (default 1e-2)\n"; cout << "--load-cfg [path] (default do not load, overrides beta)\n"; return 0; } } } //printf("Mass %.8e Blocksize %d %d Null Vectors %d\n", MASS, X_BLOCKSIZE, Y_BLOCKSIZE, n_null_vector); //return 0; /////////////////////////////////////// // End of human-readable parameters! // /////////////////////////////////////// // Only relevant for free laplace test. int Nc = 1; // Only value that matters for staggered // Describe the fine lattice. int x_fine = square_size; int y_fine = square_size; int fine_size = x_fine*y_fine*Nc; cout << "[VOL]: X " << x_fine << " Y " << y_fine << " Volume " << x_fine*y_fine; cout << "\n"; // Do some allocation. // Initialize the lattice. Indexing: index = y*N + x. gfield = new complex<double>[2*fine_size]; lhs = new complex<double>[fine_size]; rhs = new complex<double>[fine_size]; rhs2 = new complex<double>[fine_size]; lhs2 = new complex<double>[fine_size]; check = new complex<double>[fine_size]; tmp2 = new complex<double>[fine_size]; tmp3 = new complex<double>[fine_size]; lhs_internal = new complex<double>[fine_size]; lhs2_internal = new complex<double>[fine_size]; rhs_internal = new complex<double>[fine_size]; // Zero it out. zero<double>(gfield, 2*fine_size); zero<double>(rhs, fine_size); zero<double>(rhs2, fine_size); zero<double>(lhs, fine_size); zero<double>(lhs2, fine_size); zero<double>(check, fine_size); zero<double>(tmp2, fine_size); zero<double>(tmp3, fine_size); zero<double>(lhs_internal, fine_size); zero<double>(rhs_internal, fine_size); zero<double>(lhs2_internal, fine_size); // // Fill stagif. stagif.lattice = gfield; stagif.mass = mass; stagif.x_fine = x_fine; stagif.y_fine = y_fine; stagif.Nc = Nc; // Only relevant for laplace test only. // Create the verbosity structure. inversion_verbose_struct verb; verb.verbosity = VERB_SUMMARY; //VERB_DETAIL; // Describe the gauge field. cout << "[GAUGE]: Creating a gauge field.\n"; unit_gauge_u1(gfield, x_fine, y_fine); // Load the gauge field. if (do_load) { read_gauge_u1(gfield, x_fine, y_fine, load_cfg); cout << "[GAUGE]: Loaded a U(1) gauge field from " << load_cfg << "\n"; } else // various predefined cfgs. { internal_load_gauge_u1(gfield, x_fine, y_fine, BETA); } cout << "[GAUGE]: The average plaquette is " << get_plaquette_u1(gfield, x_fine, y_fine) << ".\n"; cout << "[GAUGE]: The topological charge is " << get_topo_u1(gfield, x_fine, y_fine) << ".\n"; /************** * BEGIN TESTS * **************/ // Set a random source. Should be the same every time b/c we hard code the seed above. gaussian<double>(rhs, fine_size, generator); //////////////////// // * Compares the \gamma5 D function with applying D then \gamma_5. //////////////////// // Apply \gamma_5 D square_staggered_gamma5_u1(lhs, rhs, (void*)&stagif); // Apply D then \gamma_5 square_staggered_u1(tmp2, rhs, (void*)&stagif); gamma_5(lhs2, tmp2, (void*)&stagif); cout << "[TEST1]: \\gamma_5 D test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares the D^\dagger function with applying \gamma_5 then D then \gamma_5 //////////////////// // Apply D^\dagger square_staggered_dagger_u1(lhs, rhs, (void*)&stagif); // Apply \gamma_5 then D then \gamma_5 gamma_5(lhs2, rhs, (void*)&stagif); square_staggered_u1(tmp2, lhs2, (void*)&stagif); gamma_5(lhs2, tmp2, (void*)&stagif); cout << "[TEST2]: D^\\dagger test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares summing applying D_{eo}, D_{oe}, and the mass term to applying D. //////////////////// // Apply D square_staggered_u1(lhs, rhs, (void*)&stagif); // Apply D_{eo}, D_{oe}, m in pieces. square_staggered_deo_u1(lhs2, rhs, (void*)&stagif); // D_{eo} piece in lhs2. square_staggered_doe_u1(tmp2, rhs, (void*)&stagif); // D_{oe} piece in tmp2. for (i = 0; i < fine_size; i++) { lhs2[i] = lhs2[i] + tmp2[i] + stagif.mass*rhs[i]; // combine, add mass. } cout << "[TEST3]: D_{eo}+D_{oe}+m test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares summing applying -D_{eo}D_{oe}, -D_{oe}D_{eo}, and the mass term squared to applying D^\dagger D. //////////////////// // Apply D^\dagger D square_staggered_normal_u1(lhs, rhs, (void*)&stagif); // Apply D_{eo}D_{oe}. square_staggered_doe_u1(tmp2, rhs, (void*)&stagif); square_staggered_deo_u1(lhs2, tmp2, (void*)&stagif); // Apply D_{oe}D_{eo}. square_staggered_deo_u1(tmp2, rhs, (void*)&stagif); square_staggered_doe_u1(tmp3, tmp2, (void*)&stagif); // Combine into m^2 - D_{eo}D_{oe} - D_{oe}D_{eo}. for (i = 0; i < fine_size; i++) { lhs2[i] = stagif.mass*stagif.mass*rhs[i] - lhs2[i] - tmp3[i]; } cout << "[TEST4]: D^\\dagger D test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares inverting D directly with even-odd reconstruction. //////////////////// // Invert D directly using BiCGstab-L. verb.verb_prefix = "[TEST5-D]: "; invif = minv_vector_bicgstab_l(lhs, rhs, fine_size, 100000, outer_precision, 4, square_staggered_u1, (void*)&stagif, &verb); // Invert D using an even/odd decomposition, solving the even system with CG, reconstructing odd. verb.verb_prefix = "[TEST5-D_EO_PRE]: "; // Prepare rhs: m rhs_e - D_{eo} rhs_o square_staggered_eoprec_prepare(rhs2, rhs, (void*)&stagif); // Perform even/odd inversion invif = minv_vector_cg(tmp2, rhs2, fine_size, 1000000, outer_precision, square_staggered_m2mdeodoe_u1, (void*)&stagif, &verb); // Reconstruct odd: m^{-1}*(rhs_o - D_{oe} lhs2_e) square_staggered_eoprec_reconstruct(lhs2, tmp2, rhs, (void*)&stagif); cout << "[TEST5]: Even/odd precond test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// //* Compares creating and applying a D stencil to the D function. //////////////////// // Apply D square_staggered_u1(lhs, rhs, (void*)&stagif); // Prepare a lattice to hold the staggered stencil. const int nd = 2; // 2 dimensions int lattice_size[2]; lattice_size[0] = x_fine; lattice_size[1] = y_fine; Lattice latt_staggered(nd, lattice_size, 1); // 1 for one internal degree of freedom. // Prepare a stencil. stencil_2d stencil_staggered(&latt_staggered, get_stencil_size(STAGGERED)); // stencil size is 1. // Get the staggered stencil. get_square_staggered_u1_stencil(&stencil_staggered, &stagif); // Apply D via the staggered stencil. apply_stencil_2d(lhs2, rhs, &stencil_staggered); cout << "[TEST6]: D stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// //* Compares creating and applying a \gamma5 D stencil to the \gamma5 D function. //////////////////// // Apply \gamma5 D square_staggered_gamma5_u1(lhs, rhs, (void*)&stagif); // Prepare a lattice to hold the \gamma5 staggered stencil. Lattice latt_staggered_gamma5(nd, lattice_size, 1); // 1 for one internal degree of freedom. // Prepare a stencil. stencil_2d stencil_staggered_gamma5(&latt_staggered_gamma5, get_stencil_size(STAGGERED)); // stencil size is 1. // Get the staggered stencil. get_square_staggered_gamma5_u1_stencil(&stencil_staggered_gamma5, &stagif); // Apply \gamma5 D via the staggered stencil. apply_stencil_2d(lhs2, rhs, &stencil_staggered_gamma5); cout << "[TEST7]: \\gamma5 D stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// //* Compares creating and applying a D^\dagger stencil to the D^\dagger function. //////////////////// // Apply D^\dagger square_staggered_dagger_u1(lhs, rhs, (void*)&stagif); // Prepare a lattice to hold the staggered dagger stencil. Lattice latt_staggered_dagger(nd, lattice_size, 1); // 1 for one internal degree of freedom. // Prepare a stencil. stencil_2d stencil_staggered_dagger(&latt_staggered_dagger, get_stencil_size(STAGGERED)); // stencil size is 1. // Get the staggered stencil. get_square_staggered_dagger_u1_stencil(&stencil_staggered_dagger, &stagif); // Apply D^\dagger via the staggered stencil. apply_stencil_2d(lhs2, rhs, &stencil_staggered_dagger); cout << "[TEST8]: D^\\dagger stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares applying a \gamma5 D stencil to applying a D stencil then a (-1)^coord function. //////////////////// // Apply \gamma5 D stencil. apply_stencil_2d(lhs, rhs, &stencil_staggered_gamma5); // Apply a D stencil. apply_stencil_2d(tmp2, rhs, &stencil_staggered); // Apply a lattice \epsilon function. lattice_epsilon(lhs2, tmp2, stencil_staggered.lat); cout << "[TEST9]: \\gamma5 D stencil vs epsilon D stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares applying a D^\dagger stencil to applying a (-1)^coord function then D stencil then (-1)^coord function. //////////////////// // Apply D^\dagger stencil. apply_stencil_2d(lhs, rhs, &stencil_staggered_dagger); // Apply a lattice \epsilon function. lattice_epsilon(lhs2, rhs, stencil_staggered.lat); // Apply a D stencil. apply_stencil_2d(tmp2, lhs2, &stencil_staggered); // Apply a lattice \epsilon function. lattice_epsilon(lhs2, tmp2, stencil_staggered.lat); cout << "[TEST10]: D^\\dagger stencil vs epsilon D epsilon stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares summing applying D_{eo}, D_{oe}, and the mass term via stencil to applying a D stencil. //////////////////// // Apply D via the staggered stencil. apply_stencil_2d(lhs, rhs, &stencil_staggered); // Apply D_{eo}, D_{oe}, m in pieces via stencil. apply_stencil_2d_eo(lhs2, rhs, &stencil_staggered); // D_{eo} piece in lhs2. apply_stencil_2d_oe(tmp2, rhs, &stencil_staggered); // D_{oe} piece in tmp2. for (i = 0; i < stencil_staggered.lat->get_lattice_size(); i++) { lhs2[i] = lhs2[i] + tmp2[i] + stencil_staggered.shift*rhs[i]; } cout << "[TEST11]: D_{eo}+D_{oe}+m stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares summing applying -D_{eo}D_{oe}, -D_{oe}D_{eo} via stencil, and the stencil shift term to applying D^\dagger D via stencils. //////////////////// // Apply D^\dagger D via stencils. (To do: get D^\dagger D stencil directly.) apply_stencil_2d(tmp2, rhs, &stencil_staggered); apply_stencil_2d(lhs, tmp2, &stencil_staggered_dagger); // Apply D_{eo}D_{oe} via stencils. apply_stencil_2d_eo(tmp2, rhs, &stencil_staggered); apply_stencil_2d_oe(lhs2, tmp2, &stencil_staggered); // Apply D_{oe}D_{eo} via stencils. apply_stencil_2d_oe(tmp2, rhs, &stencil_staggered); apply_stencil_2d_eo(tmp3, tmp2, &stencil_staggered); // Combine into m^2 - D_{eo}D_{oe} - D_{oe}D_{eo}. for (i = 0; i < stencil_staggered.lat->get_lattice_size(); i++) { lhs2[i] = stencil_staggered.shift*stencil_staggered.shift*rhs[i] - lhs2[i] - tmp3[i]; } cout << "[TEST12]: D^\\dagger D stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares inverting a D stencil directly with even-odd stencil reconstruction. //////////////////// // Invert D directly using BiCGstab-L. verb.verb_prefix = "[TEST13-D]: "; invif = minv_vector_bicgstab_l(lhs, rhs, fine_size, 100000, outer_precision, 4, apply_stencil_2d, &stencil_staggered, &verb); // Invert D using an even/odd decomposition, solving the even system with CG, reconstructing odd. verb.verb_prefix = "[TEST13-D_EO_PRE]: "; // Prepare rhs: m rhs_e - D_{eo} rhs_o apply_square_staggered_eoprec_prepare_stencil(rhs2, rhs, &stencil_staggered); // Perform even/odd inversion invif = minv_vector_cg(tmp2, rhs2, fine_size, 1000000, outer_precision, apply_square_staggered_m2mdeodoe_stencil, &stencil_staggered, &verb); // Reconstruct odd: m^{-1}*(rhs_o - D_{oe} lhs2_e) apply_square_staggered_eoprec_reconstruct_stencil(lhs2, tmp2, rhs, &stencil_staggered); cout << "[TEST13]: Even/odd precond stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares applying a D stencil to applying a D stencil with the hypercube rotated into degrees of freedom. //////////////////// // Apply D via the staggered stencil. apply_stencil_2d(lhs, rhs, &stencil_staggered); // We're abusing the multigrid/null vector machinary we have to do this test. // Prepare a null vector structure. The null vector structure contains a lot of fields, many of which // are related to generating null vectors via relaxation. Since we only want to do a unitary transformation, // just rotating the hypercube into internal degrees of freedom, we only need to set a few pieces. null_vector_params nvec_params; nvec_params.opt_null = STAGGERED; // using a STAGGERED op. nvec_params.n_null_vector = 1; // only "one" null vector... nvec_params.null_partitions = 4; // partitioned into 4... nvec_params.bstrat = BLOCK_CORNER; // corners of the hypercube. // Prepare a lattice for the internal d.o.f. staggered operator. lattice_size[0] = x_fine/2; lattice_size[1] = y_fine/2; // We're rotating the 2^2 hypercube in. Lattice latt_staggered_internal(nd, lattice_size, 4); // 4 for the 4 internal degrees of freedom. // Prepare a multigrid operator struct. We're not doing anything related to multigrid explicitly, // but we're going to take advantage of the prolong and restrict functions to do the necessary // unitary rotations to go between hypercubes and internal degrees of freedom. // There's a lot of cleanup that could be done within the mg struct. For ex, there are a lot of state-related // variables that could just be queried on the fly from the current lattice. mg_operator_struct_complex mgstruct; mgstruct.x_fine = x_fine; // top level x dimension. mgstruct.y_fine = y_fine; // top level y dimension. mgstruct.n_refine = 1; // we have two "levels", so there's one "refinement": top level is the original lattice, // bottom is the internal lattice. mgstruct.blocksize_x = new int[1]; mgstruct.blocksize_x[0] = 2; // block by 2. mgstruct.blocksize_y = new int[1]; mgstruct.blocksize_y[0] = 2; mgstruct.Nc = 1; // Nc = 1 on the top level, i.e., there are no internal degrees of freedom. mgstruct.latt = new Lattice*[2]; // array of pointers to the lattices. mgstruct.latt[0] = &latt_staggered; mgstruct.latt[1] = &latt_staggered_internal; mgstruct.stencils = new stencil_2d*[2]; // array of pointers to stencils. mgstruct.stencils[0] = &stencil_staggered; // the top level is the fine stencil. // We'll put the internal dof stencil in momentarily. mgstruct.have_dagger_stencil = false; // we don't need the daggered stencil. (This is used for normal smoother solves.) mgstruct.dagger_stencils = 0; mgstruct.n_vector = 4; // We have 4 null vectors. This is currently hard coded to be constant for every level. mgstruct.null_vectors = new complex<double>**[1]; // This holds the null vectors. We have only one refinement. mgstruct.null_vectors[0] = new complex<double>*[mgstruct.n_vector]; // We'll have 4 "null vectors", one for each corner. for (i = 0; i < mgstruct.n_vector; i++) { mgstruct.null_vectors[0][i] = new complex<double>[latt_staggered.get_lattice_size()]; zero<double>(mgstruct.null_vectors[0][i], mgstruct.latt[0]->get_lattice_size()); } mgstruct.matrix_vector = square_staggered_u1; // What's the original fine function? mgstruct.matrix_vector_dagger = 0; // We don't need the daggered function. mgstruct.matrix_extra_data = &stagif; // This is the structure that goes along with the fine function. mgstruct.curr_level = 0; // state variable, the fine level is currently the top (0th) level. mgstruct.curr_dof_fine = mgstruct.latt[0]->get_nc(); // the fine level dof. mgstruct.curr_x_fine = mgstruct.latt[0]->get_lattice_dimension(0); // fine level x dimension mgstruct.curr_y_fine = mgstruct.latt[0]->get_lattice_dimension(1); // fine level y dimension. mgstruct.curr_fine_size = mgstruct.latt[0]->get_lattice_size(); // total size. mgstruct.curr_dof_coarse = mgstruct.latt[1]->get_nc(); // the coarse level dof. mgstruct.curr_x_coarse = mgstruct.latt[1]->get_lattice_dimension(0); // coarse level x dimension mgstruct.curr_y_coarse = mgstruct.latt[1]->get_lattice_dimension(1); // coarse level y dimension. mgstruct.curr_coarse_size = mgstruct.latt[1]->get_lattice_size(); // total size. // Whew, that was a lot. Now that we've got that all filled out, we have a function that'll automatically generate // the unitary transformation null vectors (which are the free field null vectors when you do a 2^2 block size). null_generate_free(&mgstruct, &nvec_params); // We need to properly block normalize the vectors. This is what makes the transformation unitary. // By construction, the vectors are already orthogonal, so the "ortho" part doesn't do anything. block_orthonormalize(&mgstruct); // Create a stencil for the internal dof operator. stencil_2d stencil_staggered_internal(&latt_staggered_internal, get_stencil_size(STAGGERED)); // stencil size is 1. mgstruct.stencils[1] = &stencil_staggered_internal; // Using the fine stencil and the transformation defined by the free null vectors, we can build the // internal dof stencil. generate_coarse_from_fine_stencil(&stencil_staggered_internal, &stencil_staggered, &mgstruct, true); // true -> don't build the mass explicitly into the stencil. stencil_staggered_internal.shift = stencil_staggered.shift; // the mass is unchanged by the unitary transformation. // Alright, everything's done! We're now ready to actually do a test. // Perform a unitary transformation to take the original staggered layout to the internal dof layout. // This function is why we went through all of the misery to set up a mg struct. restrict(rhs_internal, rhs, &mgstruct); // Apply the internal dof stencil. apply_stencil_2d(lhs_internal, rhs_internal, &stencil_staggered_internal); // Perform a unitary transformation to return to the original staggered layout. prolong(lhs2, lhs_internal, &mgstruct); cout << "[TEST14]: Internal dof stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares applying a \gamma5 D stencil to performing a dof rotation, applying D_internal, applying \sigma3, undoing dof rotation. //////////////////// // Apply \gamma5 D via the staggered stencil. apply_stencil_2d(lhs, rhs, &stencil_staggered_gamma5); // Apply an internal unitary transformation. restrict(rhs_internal, rhs, &mgstruct); // Apply D_internal apply_stencil_2d(lhs_internal, rhs_internal, &stencil_staggered_internal); // Apply \sigma3 lattice_sigma3(tmp2, lhs_internal, &latt_staggered_internal); // Apply a hypercube unitary transformation. prolong(lhs2, tmp2, &mgstruct); cout << "[TEST15]: \\gamma5 D stencil vs internal \\sigma3 D stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares applying a D^\dagger stencil to performing a dof rotation, applying \sigma3, D_internal, \sigma3, undoing dof rotation. //////////////////// // Apply D^\dagger via the staggered stencil. apply_stencil_2d(lhs, rhs, &stencil_staggered_dagger); // Apply an internal unitary transformation. restrict(rhs_internal, rhs, &mgstruct); // Apply \sigma3 lattice_sigma3(lhs_internal, rhs_internal, &latt_staggered_internal); // Apply D_internal apply_stencil_2d(tmp2, lhs_internal, &stencil_staggered_internal); // Apply \sigma3 lattice_sigma3(lhs_internal, tmp2, &latt_staggered_internal); // Apply a hypercube unitary transformation. prolong(lhs2, lhs_internal, &mgstruct); cout << "[TEST16]: D^\\dagger stencil vs internal \\sigma3 D \\sigma3 stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares applying a D stencil to performing a dof rotation, summing applying D_{tb}, D_{bt}, and the mass, then undoing dof rotation. //////////////////// // Apply D via the staggered stencil. apply_stencil_2d(lhs, rhs, &stencil_staggered); // Apply an internal unitary transformation. restrict(rhs_internal, rhs, &mgstruct); // Apply internal D_{tb}, D_{bt}, m in pieces. apply_stencil_2d_tb(lhs_internal, rhs_internal, &stencil_staggered_internal); // D_{tb} piece in lhs_internal. apply_stencil_2d_bt(tmp2, rhs_internal, &stencil_staggered_internal); // D_{bt} piece in tmp2. for (i = 0; i < latt_staggered_internal.get_lattice_size(); i++) { lhs_internal[i] = lhs_internal[i] + tmp2[i] + stencil_staggered_internal.shift*rhs_internal[i]; // combine, add mass. } // Apply a hypercube unitary transformation prolong(lhs2, lhs_internal, &mgstruct); cout << "[TEST17]: D stencil vs internal D_{tb}+D_{bt}+mass test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares summing applying an internal -D_{tb}D_{bt}, -D_{bt}D_{tb}, and the stencil shift term to applying D^\dagger D via stencils. //////////////////// // Apply D^\dagger D via stencils. (To do: get D^\dagger D stencil directly.) apply_stencil_2d(tmp2, rhs, &stencil_staggered); apply_stencil_2d(lhs, tmp2, &stencil_staggered_dagger); // Apply an internal unitary transformation. restrict(rhs_internal, rhs, &mgstruct); // Apply D_{tb}D_{bt} via stencils. apply_stencil_2d_bt(tmp2, rhs_internal, &stencil_staggered_internal); apply_stencil_2d_tb(lhs_internal, tmp2, &stencil_staggered_internal); // Apply D_{bt}D_{tb} via stencils. apply_stencil_2d_tb(tmp2, rhs_internal, &stencil_staggered_internal); apply_stencil_2d_bt(tmp3, tmp2, &stencil_staggered_internal); // Combine into m^2 - D_{tb}D_{bt} - D_{bt}D_{tb}. for (i = 0; i < stencil_staggered_internal.lat->get_lattice_size(); i++) { lhs_internal[i] = stencil_staggered_internal.shift*stencil_staggered_internal.shift*rhs_internal[i] - lhs_internal[i] - tmp3[i]; } // Apply a hypercube unitary transformation prolong(lhs2, lhs_internal, &mgstruct); cout << "[TEST18]: D^\\dagger D internal stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; //////////////////// // * Compares inverting a D_internal stencil directly with top-bottom stencil reconstruction. //////////////////// // Apply an internal unitary transformation. restrict(rhs_internal, rhs, &mgstruct); // Invert D_internal directly using BiCGstab-L. verb.verb_prefix = "[TEST19-D_INTERNAL]: "; invif = minv_vector_bicgstab_l(lhs_internal, rhs_internal, fine_size, 100000, outer_precision, 4, apply_stencil_2d, &stencil_staggered_internal, &verb); // Invert D using an even/odd decomposition, solving the even system with CG, reconstructing odd. verb.verb_prefix = "[TEST19-D_INTERNAL_TB_PRE]: "; // Prepare rhs: m rhs_t - D_{tb} rhs_b apply_square_staggered_tbprec_prepare_stencil(rhs2, rhs_internal, &stencil_staggered_internal); // Perform even/odd inversion invif = minv_vector_cg(tmp2, rhs2, fine_size, 1000000, outer_precision, apply_square_staggered_m2mdtbdbt_stencil, &stencil_staggered_internal, &verb); // Reconstruct odd: m^{-1}*(rhs_o - D_{oe} lhs2_e) apply_square_staggered_tbprec_reconstruct_stencil(lhs2_internal, tmp2, rhs_internal, &stencil_staggered_internal); // Apply a hypercube unitary transformation prolong(lhs, lhs_internal, &mgstruct); prolong(lhs2, lhs2_internal, &mgstruct); cout << "[TEST19]: Internal top/bottom precond stencil test: relative residual " << diffnorm2sq(lhs, lhs2, fine_size) << ".\n"; /************ * END TESTS * ************/ // Free the lattice. delete[] gfield; delete[] lhs; delete[] lhs2; delete[] rhs; delete[] rhs2; delete[] check; delete[] tmp2; delete[] tmp3; delete[] lhs_internal; delete[] rhs_internal; delete[] lhs2_internal; // Free null vector and multigrid related things. delete[] mgstruct.blocksize_x; delete[] mgstruct.blocksize_y; delete[] mgstruct.latt; delete[] mgstruct.stencils; for (i = 0; i < mgstruct.n_vector; i++) { delete[] mgstruct.null_vectors[0][i]; } delete[] mgstruct.null_vectors[0]; delete[] mgstruct.null_vectors; return 0; } // Custom routine to load gauge field. void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA) { if (x_fine == 32 && y_fine == 32) { if (abs(BETA - 3.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l32t32b30_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l32t32b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l32t32b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l32t32bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else if (x_fine == 64 && y_fine == 64) { if (abs(BETA - 3.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l64t64b30_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l64t64b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l64t64b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l64t64bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else if (x_fine == 128 && y_fine == 128) { if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l128t128b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l128t128b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l128t128bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } }
/* vim: set ai noet ts=4 sw=4 tw=115: */ // // Copyright (c) 2014 Nikolay Zapolnov (zapolnov@gmail.com). // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "openal_device.h" #include "openal_output.h" #include <iostream> #ifdef __APPLE__ #include <TargetConditionals.h> #if TARGET_OS_IPHONE #include "ios/audio_interruption_listener.h" #endif #endif OpenALDevice::OpenALDevice() : m_Device(nullptr), m_Context(nullptr), m_Suspended(false) { #if defined(__APPLE__) && TARGET_OS_IPHONE AudioInterruptionListener_setup(); #endif const char * defaultDevice = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER); std::clog << "Sound: using default device: " << (defaultDevice ? defaultDevice : "(null)") << std::endl; m_Device = alcOpenDevice(defaultDevice); if (UNLIKELY(!m_Device)) { std::clog << "Sound: unable to open audio device." << std::endl; return; } m_Context = alcCreateContext(m_Device, nullptr); if (UNLIKELY(!m_Context)) { std::clog << "Sound: unable to create OpenAL context." << std::endl; return; } #if defined(__APPLE__) && TARGET_OS_IPHONE AudioInterruptionListener_setCallback([this](bool activate) { m_Suspended = !activate; }); #endif bindContext(); std::clog << "Sound: OpenAL vendor: " << alGetString(AL_VENDOR) << std::endl; std::clog << "Sound: OpenAL renderer: " << alGetString(AL_RENDERER) << std::endl; std::clog << "Sound: OpenAL version: " << alGetString(AL_VERSION) << std::endl; } OpenALDevice::~OpenALDevice() { #if defined(__APPLE__) && TARGET_OS_IPHONE AudioInterruptionListener_setCallback(std::function<void(bool)>()); #endif if (m_Context) { alcDestroyContext(m_Context); m_Context = nullptr; } if (m_Device) { alcCloseDevice(m_Device); m_Device = nullptr; } } AudioOutputPtr OpenALDevice::newOutput(AudioFormat format, size_t hz) { return std::make_shared<OpenALOutput>(*this, format, hz); } void OpenALDevice::bindContext() { if (UNLIKELY(!alcMakeContextCurrent(m_Context))) std::clog << "Sound: unable to activate OpenAL context." << std::endl; else { while (alGetError() != AL_NO_ERROR) ; } } void OpenALDevice::checkError(const char * file, int line, const char * func) { for (;;) { ALenum error = alGetError(); if (LIKELY(error == AL_NO_ERROR)) return; std::cerr << "Sound: " << func << ": " << alGetString(error) << " (in file " << file << " at line " << line << ")." << std::endl; } } AudioDevice & AudioDevice::instance() { static OpenALDevice device; return device; }
#include "precompiled.h" #include "common/log.h" namespace Log { struct Consumer { Consumer(ConsumerCallback callback, void* user, U32 mask) : callback(callback), user(user), mask(mask) {} ConsumerCallback callback; void* user; U32 mask; }; typedef map<string, Consumer> consumer_map_t; consumer_map_t consumer_map; } void Log::addConsumer(const string& name, unsigned int mask, ConsumerCallback callback, void* userdef /* = NULL */) { consumer_map.insert(consumer_map_t::value_type(name, Consumer(callback, userdef, mask))); } void Log::removeConsumer(const string& name) { consumer_map.erase(name); } void Log::log(const char* file, unsigned int line, const char* function, unsigned int flags, const char* format, ...) { va_list args; char buffer[4096]; va_start(args, format); vsprintf(buffer, format, args); va_end(args); #ifdef _DEBUG char buffer2[4096]; sprintf(buffer2, "%s(%i):[%s] %s\n", file, line, function, buffer); OutputDebugString(buffer2); #endif for (consumer_map_t::const_iterator it = consumer_map.begin(); it != consumer_map.end(); it++) { if (flags & it->second.mask) it->second.callback(file, line, function, flags, buffer, it->second.user); } }
#include "Scope.h" #include <iostream> void Scope::Set (int Pos, std::vector<Statement>* Char) { int ArgL = 0; // Tracks where the current parenthesis is, in relation to other ones int ScopeL = 0; // Tracks where the current brackets is, in relation to other ones bool ArgOpen = false; bool ArgClose = false; bool ScopeOpen = false; bool ScopeClose = false; for (Pos; Pos < Char -> size (); Pos++) { try { // Argument detection if (Char -> at (Pos).Args.at (0).compare ("(") == 0 && !ArgClose) { ArgL++; ArgOpen = true; this -> ArgStart = Pos; } else if (Char -> at (Pos).Args.at (0).compare (")") == 0 && !ArgClose) { ArgL--; if (ArgL == 0 && ArgOpen) { ArgClose = true; this -> ArgStop = Pos; } } // Scope detection if (Char -> at (Pos).Args.at (0).compare ("{") == 0 && !ScopeClose && !ScopeOpen) { ScopeL++; ScopeOpen = true; this -> ScopeStart = Pos; } else if (Char -> at (Pos).Args.at (0).compare ("}") == 0 && !ScopeClose) { ScopeL--; if (ScopeL == 0 && ScopeOpen) { ScopeClose = true; this -> ScopeStop = Pos; } } } catch (...) { // Scope parsing error } } }
#include <iostream> #include <algorithm> #include <iterator> void print( int * first_, int * last_ ) { std::cout << "[ "; while( first_ < last_ ) { std::cout << *first_ << " "; first_++; } std::cout << "]"; } void merge( int *first_a, int *last_a, int *first_b, int *last_b, int *first_c ) { while( first_a != last_a ) { //If B is empty, move all remaining elements from A to C if (first_b == last_b) { std::copy(first_a, last_a, first_c); return; } if(*first_a <= *first_b) { *first_c++ = *first_a++; }else { *first_c = *first_b; first_b++; first_c++; } } //If A is empty, move all remaining elements from B to C std::copy(first_b, last_b, first_c); } void merge_sort( int *first, int *last ) { auto n = std::distance(first, last); if(n == 1) return; auto len_left = n/2; auto len_right = n - n/2; int *L = new int[len_left]; int *R = new int[len_right]; std::copy(first, first+len_left, L); std::copy(first+len_left, last, R); merge_sort( L, L+len_left ); merge_sort( R, R+len_right ); merge(L, L+len_left, R, R+len_right, first); delete [] L; delete [] R; } int main( void ) { int A[] = { 3, 2, 7, 4, 1, 8, 5, 6, 9, 0}; std::cout << ">>> Before Merge Sort -> Array A:\n"; print( std::begin(A), std::end(A) ); std::cout << std::endl; merge_sort( std::begin(A), std::end(A) ); std::cout << ">>> After Merge Sort -> Array A:\n"; print( std::begin(A), std::end(A) ); std::cout << std::endl; return 0; }
/* ** EPITECH PROJECT, 2019 ** tek3 ** File description: ** Message */ #ifndef MESSAGE_HPP_ #define MESSAGE_HPP_ #include <QtWidgets> #include <QApplication> #include <vector> #include <iostream> namespace babel { namespace graphic { class Message : public QWidget { Q_OBJECT public: Message(std::string message, QWidget *parent = 0); public: void setBackgroundColor(QColor color); signals: private: QLabel *_content; QPalette _palette; QVBoxLayout *_messageBox; }; } } #endif /* !CONTACTLIST_HPP_ */
/* * StringTest1.cpp * * Created on: 2014年4月9日 * Author: h3c */ #include "String.h" #include <cstdio> #include <cstring> #include <exception> #include <iostream> using namespace std; String::String() { length = 0; buf = NULL; cout << "String()" << endl; } String::String(const char * s) { if (s == NULL) { length = 0; buf = NULL; } else { this->length = strlen(s); buf = new char[length + 1]; strcpy(buf, s); } cout << "String(char *)" << endl; } String::String(String & s) { this->length = s.length; this->buf = new char[length + 1]; strcpy(this->buf, s.buf); cout << "String(String &)" << endl; } String & String::operator =(String & s) { cout << "String & operator =(String &)" << endl; if (this == &s) { //指针比较 return *this; } else { this->length = s.length; delete buf; this->buf = new char[length + 1]; strcpy(this->buf, s.buf); return *this; } } String & String::operator =(const char * s) { cout << "String & operator =(const char *)" << endl; this->length = strlen(s); delete buf; this->buf = new char[length + 1]; strcpy(this->buf, s); return *this; } ostream& operator <<(ostream& out,const String & s) { out << s.buf; return out; } String::~String() { if (length != 0) { delete buf; } buf = NULL; cout << "~String()" << endl; } String::operator const char *() { return this->buf; } int String::find_first(const String & s) { char * pDes = s.buf; char * pSrc = this->buf; bool isNew = true; bool isMatch = false; int position = 0; int index = 0; try { while (*pSrc != '\0') { pDes = s.buf; //每次外层循环豆浆要查找的字符串的指针定位到开始处 while (*pDes != '\0' && *pSrc != '\0') { if (*pDes == *pSrc) { if (isNew) { isNew = false; position = index; } pSrc++; pDes++; index++; isMatch = true; } else { if (isMatch) { pSrc--; index--; } isMatch = false; isNew = true; break; } } if (isMatch && (this->length - position) >= s.length) { return position; } pSrc++; index++; } } catch (int & e1) { cout << "error code=" << e1 << endl; } catch (...) { cout << "出现异常" << endl; } return -1; } int String::find_first(const String &s, int begin, int length) { int srcLength = strlen(this->buf); int desLength = strlen(s.buf); char *pSrc = this->buf; char *pDes = s.buf; if (begin >= srcLength) { //如果开始位置就在字符串末尾,返回-1 return -1; } if (length < desLength) { //如果在源字符串中查找的长度小于目的字符串的长度,则不可能成功,返回-1 return -1; } int maxIndex = begin + length; int index = 0; for (int i = begin; i < maxIndex; i++) { while (*pDes != *pSrc) { //首字符不相同的就指针向后移 pSrc++; i++; } index = i; if (i + desLength <= maxIndex) { int j = 0; for (; j < desLength && (*pDes == *pSrc); j++, i++, pSrc++, pDes++) ; //逐步位移判断字节是否相等 if (j == desLength) { return index; } else { //如果不相等,则证明相同的字段比要查找的字段的长度小,则需要将pSrc指针向前偏移一位,pDes重新初始化 // pSrc--; i--; pDes = s.buf; } } else { return -1; } } return -1; } void String::info() { cout << "In Info buf=" << buf << endl; printf("*******info buf=%p\n", buf); }
#include "compressEpub.h" compressEpub::compressEpub(QObject *parent) : QObject(parent) { } QStringList compressEpub::getAllEpubFiles(QString dirPath, QStringList list) { QDir dir(dirPath); QFileInfoList info_list = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::AllDirs); foreach(QFileInfo file_info, info_list) { if(file_info.isDir()) list = getAllEpubFiles(file_info.absoluteFilePath(), list); else if(file_info.isFile()) { if(file_info.fileName() == "mimetype") list.prepend(file_info.absoluteFilePath()); else list << file_info.absoluteFilePath(); } } return list; } bool compressEpub::compressDir(QString dirPath, QString epubPath) { QStringList list = getAllEpubFiles(dirPath); QuaZip zip(epubPath); if(!zip.open(QuaZip::mdCreate)){ qCritical() << QString("%1 创建失败!").arg(epubPath); return false; } QuaZipFile zipFile(&zip); for(int i = 0; i < list.size(); i++) { QFileInfo info(list.at(i)); if(info.exists()) { QString filePath = info.filePath(); QString fileName = filePath; fileName = fileName.replace(dirPath + "/", ""); QFile file(filePath); if(!file.open(QIODevice::ReadOnly)) { qCritical() << QString("%1 文件读取失败!").arg(filePath); return false; } if(filePath.endsWith("mimetype")) { if(!zipFile.open(QuaZipFile::WriteOnly, QuaZipNewInfo(fileName, filePath), NULL, 0, 0, 0)) { qCritical() << QString("%1 文件写入失败!").arg(filePath); return false; } } else { if(!zipFile.open(QuaZipFile::WriteOnly, QuaZipNewInfo(fileName, filePath))) { qCritical() << QString("%1 文件写入失败!").arg(filePath); return false; } } zipFile.write(file.readAll()); zipFile.close(); file.close(); } else { qCritical() << QString("%1 文件不存在!").arg(list.at(i)); return false; } } zip.close(); return true; } bool compressEpub::compressWithMaterials(QString dirPath, QString epubPath, QStringList fileList) { QStringList list = getAllEpubFiles(dirPath); QuaZip zip(epubPath); if(!zip.open(QuaZip::mdCreate)){ qCritical() << QString("%1 创建失败!").arg(epubPath); return false; } QuaZipFile zipFile(&zip); for(int i = 0; i < list.size(); i++) { QFileInfo info(list.at(i)); if(info.exists()) { QString filePath = info.filePath(); QString fileName = filePath; fileName = fileName.replace(dirPath + "/", ""); QFile file(filePath); if(!file.open(QIODevice::ReadOnly)) { qCritical() << QString("%1 文件读取失败!").arg(filePath); return false; } if(filePath.endsWith("mimetype")) { if(!zipFile.open(QuaZipFile::WriteOnly, QuaZipNewInfo(fileName, filePath), NULL, 0, 0, 0)) { qCritical() << QString("%1 文件写入失败!").arg(filePath); return false; } } else { if(!zipFile.open(QuaZipFile::WriteOnly, QuaZipNewInfo(fileName, filePath))) { qCritical() << QString("%1 文件写入失败!").arg(filePath); return false; } } zipFile.write(file.readAll()); zipFile.close(); file.close(); } else { qCritical() << QString("%1 文件不存在!").arg(list.at(i)); return false; } } for(int i = 0; i < fileList.size(); i++) { QFileInfo info(fileList.at(i)); if(info.exists()) { QString filePath = info.filePath(); QString fileName = info.fileName(); fileName = QString("OEBPS/Images/%1").arg(fileName); QFile file(filePath); if(!file.open(QIODevice::ReadOnly)) { qCritical() << QString("%1 文件读取失败!").arg(filePath); return false; } if(!zipFile.open(QuaZipFile::WriteOnly, QuaZipNewInfo(fileName, filePath))) { qCritical() << QString("%1 文件写入失败!").arg(filePath); return false; } zipFile.write(file.readAll()); zipFile.close(); file.close(); } else { qCritical() << QString("%1 文件不存在!").arg(fileList.at(i)); return false; } } zip.close(); return true; } bool compressEpub::compressArchive(QString dirPath, QString zipPath, QString parentName) { QStringList list = getAllEpubFiles(dirPath); QuaZip zip(zipPath); if(!zip.open(QuaZip::mdCreate)){ qCritical() << QString("%1 创建失败!").arg(zipPath); return false; } QuaZipFile zipFile(&zip); for(int i = 0; i < list.size(); i++) { QFileInfo info(list.at(i)); if(info.exists()) { QString filePath = info.filePath(); QString fileName = filePath; if(parentName.isEmpty()) fileName = fileName.replace(dirPath + "/", ""); else fileName = fileName.replace(dirPath + "/", parentName + "/"); QFile file(filePath); if(!file.open(QIODevice::ReadOnly)) { qCritical() << QString("%1 文件读取失败!").arg(filePath); return false; } if(!zipFile.open(QuaZipFile::WriteOnly, QuaZipNewInfo(fileName, filePath))) { qCritical() << QString("%1 文件写入失败!").arg(filePath); return false; } zipFile.write(file.readAll()); zipFile.close(); file.close(); } else { qCritical() << QString("%1 文件不存在!").arg(list.at(i)); return false; } } zip.close(); return true; }
// File Name: ass4.cpp // Programmer: Tabitha Roemish // Date: February 23, 2018 // File contains: Movie class declaration // movie class is abstract class for movie types (Comedy[F], Drama[D], Classic[C]) #ifndef MOVIE_H #define MOVIE_H #include <string> class Movie { public: virtual void print() = 0; virtual ~Movie(); static Movie * create(std::string identifier); bool operator>(Movie & mv); bool operator==(Movie & mv); }; #endif
#include <bits/stdc++.h> using namespace std; const int maxn = 101; const int INF = 0x7fffffff; struct Graph{ int vexs[maxn]; int arcs[maxn][maxn]; int vexNum; int arcNum; }; bool visited[maxn]; void initGraph(Graph *G); void DFS(Graph *G); void dfs(Graph *G,int i); void BFS(Graph *G,int start); void initGraph(Graph *G){ printf("输入顶点数和边数:"); scanf("%d%d",&G->vexNum,&G->arcNum); //建立节点 printf("输入节点编号:"); for(int i=0; i<G->vexNum; ++i){ scanf("%d",&G->vexs[i]); } //初始化边 memset(G->arcs,INF,sizeof(G->arcs)); //建立边 printf("输入边的左右两个节点的编号及边的权重:\n"); for(int i=0; i<G->arcNum; ++i){ int from,to,weight; scanf("%d%d%d",&from,&to,&weight); G->arcs[from][to] = weight; G->arcs[to][from] = G->arcs[from][to]; } } void DFS(Graph *G){ memset(visited,false,sizeof(visited)); for(int i=0; i<G->vexNum; ++i){ if(visited[i] == false){ dfs(G,i); } } } void dfs(Graph *G,int i){ visited[i] = true; printf("%d ",G->vexs[i]); for(int j=0; j<G->vexNum; ++j){ if(G->arcs[i][j] != 0 && G->arcs[i][j] != INF && visited[j] == false){ dfs(G,j); } } } void BFS(Graph *G,int start){ memset(visited,false,sizeof(visited)); queue<int> Q; visited[start] = true; Q.push(start); while(Q.empty() == false){ int cur = Q.front(); printf("%d ",cur); Q.pop(); for(int i=0; i<G->vexNum; ++i){ if(G->arcs[cur][i] != INF && G->arcs[cur][i] != 0 && visited[i] == false){ visited[i] = true; Q.push(i); } } } } int main(){ Graph *G = new Graph(); initGraph(G); BFS(G,0); return 0; }
#include <iostream> #include <map> #include <vector> using namespace std; template <typename T> T gcd(T a, T b) { if (a < b) return gcd(b, a); return b == 0 ? a : gcd(b, a % b); } const int MAX = 2e7; bool isprime[MAX]; vector<int> primes; void sieve() { fill(isprime, isprime + MAX, true); for (int p = 2; p * p < MAX; ++p) { if (!isprime[p]) continue; primes.push_back(p); for (int q = p; p * q < MAX; ++q) { isprime[p * q] = false; } } } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); sieve(); int N; cin >> N; int a[N]; for (int i = 0; i < N; ++i) cin >> a[i]; int g = 0; for (int i = 0; i < N; ++i) g = gcd(g, a[i]); for (int i = 0; i < N; ++i) a[i] /= g; map<int, int> cnt; for (int i = 0; i < N; ++i) { for (int p : primes) { if (p * p > a[i]) break; if (a[i] % p > 0) continue; if (!cnt.count(p)) cnt[p] = 0; ++cnt[p]; while (a[i] % p == 0) a[i] /= p; } if (a[i] > 1) { if (!cnt.count(a[i])) cnt[a[i]] = 0; ++cnt[a[i]]; } } int ans = N; for (auto p : cnt) { if (p.second < N) ans = min(ans, N - p.second); } cout << (ans == N ? -1 : ans) << endl; return 0; }
const ld PI=acos(-1.0); ld Area(ld x1,ld y1,ld r1,ld x2,ld y2,ld r2) { ld d=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2); if(d>=(r1+r2)*(r1+r2)) return 0; else if((r1-r2)*(r1-r2)>=d) { if(r1>r2) return PI*r2*r2; else return PI*r1*r1; } else { ld a1=2*acosl((r1*r1+d-r2*r2)/2/r1/sqrt(d)); ld a2=2*acosl((r2*r2+d-r1*r1)/2/r2/sqrt(d)); ld ans=r1*r1*a1/2+r2*r2*a2/2-r1*r1*sinl(a1)/2-r2*r2*sinl(a2)/2; return ans; } }
#ifndef PACKEDPSEUDOGENOMEBASE_H_INCLUDED #define PACKEDPSEUDOGENOMEBASE_H_INCLUDED #include "PseudoGenomeBase.h" using namespace PgSAReadsSet; namespace PgSAIndex { class PackedPseudoGenomeBase: public PseudoGenomeBase { protected: uchar symbolsPerElement; uchar bytesPerElement; PackedPseudoGenomeBase(uint_pg_len_max length, ReadsSetProperties* properties, uchar symbolsPerElement, uchar bytesPerElement) : PseudoGenomeBase(length, properties), symbolsPerElement(symbolsPerElement), bytesPerElement(bytesPerElement) { }; PackedPseudoGenomeBase(uint_pg_len_max length, std::istream& src, uchar bytesPerElement) : PseudoGenomeBase(length, src){ int srchelper; src >> srchelper; this->symbolsPerElement = srchelper; this->bytesPerElement = bytesPerElement; }; virtual ~PackedPseudoGenomeBase() { }; public: const uchar getSymbolsPerElement() { return this->symbolsPerElement; }; const uchar getBytesPerElement() { return this->bytesPerElement; }; bool isPgElementMinimal() { return bytesPerElement == 1; }; bool isPgElementStandard() { return bytesPerElement == 2; }; }; class PackedPseudoGenomeHeaderExtension { private: uchar symbolsPerElement; uchar bytesPerElement; public: PackedPseudoGenomeHeaderExtension(PackedPseudoGenomeBase* ppgb) { this->symbolsPerElement = ppgb->getSymbolsPerElement(); this->bytesPerElement = ppgb->getBytesPerElement(); } PackedPseudoGenomeHeaderExtension(std::istream& src) { int srchelper; src >> srchelper; symbolsPerElement = srchelper; src >> srchelper; bytesPerElement = srchelper; src.get(); } ~PackedPseudoGenomeHeaderExtension() { }; void write(std::ostream& dest) { dest << (int) symbolsPerElement << "\n"; dest << (int) bytesPerElement << "\n"; } bool isPgElementMinimal() { return bytesPerElement == 1; }; bool isPgElementStandard() { return bytesPerElement == 2; }; }; } #endif // PACKEDPSEUDOGENOMEBASE_H_INCLUDED
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "input_util.hpp" #include "joystick-support.hpp" #include "our_key_codes.hpp" #include "util.hpp" #include "paddleboat/paddleboat.h" #define INPUT_ACTION_COUNT 6 struct InputAction { uint32_t buttonMask; int32_t actionCode; }; static const InputAction _INPUT_ACTIONS[INPUT_ACTION_COUNT] = { {PADDLEBOAT_BUTTON_A, OURKEY_ENTER}, {PADDLEBOAT_BUTTON_B, OURKEY_ESCAPE}, {PADDLEBOAT_BUTTON_DPAD_UP, OURKEY_UP}, {PADDLEBOAT_BUTTON_DPAD_LEFT, OURKEY_LEFT}, {PADDLEBOAT_BUTTON_DPAD_DOWN, OURKEY_DOWN}, {PADDLEBOAT_BUTTON_DPAD_RIGHT, OURKEY_RIGHT} }; static bool _key_state[OURKEY_COUNT] = {0}; static uint32_t _prev_buttonsDown = 0; static void _report_key_state(int keyCode, bool state, CookedEventCallback callback) { bool wentDown = !_key_state[keyCode] && state; bool wentUp = _key_state[keyCode] && !state; _key_state[keyCode] = state; struct CookedEvent ev; memset(&ev, 0, sizeof(struct CookedEvent)); ev.keyCode = keyCode; if (wentUp) { ev.type = COOKED_EVENT_TYPE_KEY_UP; callback(&ev); } else if (wentDown) { ev.type = COOKED_EVENT_TYPE_KEY_DOWN; callback(&ev); } } static void _report_key_states_from_axes(float x, float y, CookedEventCallback callback) { _report_key_state(OURKEY_LEFT, x < -0.5f, callback); _report_key_state(OURKEY_RIGHT, x > 0.5f, callback); _report_key_state(OURKEY_UP, y < -0.5f, callback); _report_key_state(OURKEY_DOWN, y > 0.5f, callback); } static int32_t _checkControllerButton(const uint32_t buttonsDown, const InputAction &inputAction, CookedEventCallback callback) { if (buttonsDown & inputAction.buttonMask) { _report_key_state(inputAction.actionCode, true, callback); return 1; } else if (_prev_buttonsDown & inputAction.buttonMask) { _report_key_state(inputAction.actionCode, false, callback); return 1; } return 0; } bool CookGameActivityKeyEvent(GameActivityKeyEvent *keyEvent, CookedEventCallback callback) { if (keyEvent->keyCode == AKEYCODE_BACK && 0 == keyEvent->action) { // back key was pressed struct CookedEvent ev; memset(&ev, 0, sizeof(ev)); ev.type = COOKED_EVENT_TYPE_BACK; return callback(&ev); } return false; } bool CookGameActivityMotionEvent(GameActivityMotionEvent *motionEvent, CookedEventCallback callback) { if (motionEvent->pointerCount > 0) { int action = motionEvent->action; int actionMasked = action & AMOTION_EVENT_ACTION_MASK; int ptrIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; if (ptrIndex < motionEvent->pointerCount) { struct CookedEvent ev; memset(&ev, 0, sizeof(ev)); if (actionMasked == AMOTION_EVENT_ACTION_DOWN || actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { ev.type = COOKED_EVENT_TYPE_POINTER_DOWN; } else if (actionMasked == AMOTION_EVENT_ACTION_UP || actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { ev.type = COOKED_EVENT_TYPE_POINTER_UP; } else { ev.type = COOKED_EVENT_TYPE_POINTER_MOVE; } ev.motionPointerId = motionEvent->pointers[ptrIndex].id; ev.motionIsOnScreen = motionEvent->source == AINPUT_SOURCE_TOUCHSCREEN; ev.motionX = GameActivityPointerAxes_getX(&motionEvent->pointers[ptrIndex]); ev.motionY = GameActivityPointerAxes_getY(&motionEvent->pointers[ptrIndex]); if (ev.motionIsOnScreen) { // use screen size as the motion range ev.motionMinX = 0.0f; ev.motionMaxX = SceneManager::GetInstance()->GetScreenWidth(); ev.motionMinY = 0.0f; ev.motionMaxY = SceneManager::GetInstance()->GetScreenHeight(); } return callback(&ev); } } return false; } bool CookGameControllerEvent(const int32_t gameControllerIndex, CookedEventCallback callback) { int addedControllerEvent = 0; if (gameControllerIndex >= 0) { Paddleboat_Controller_Data controllerData; if (Paddleboat_getControllerData(gameControllerIndex, &controllerData) == PADDLEBOAT_NO_ERROR) { // Generate events from buttons for (int i = 0; i < INPUT_ACTION_COUNT; ++i) { addedControllerEvent |= _checkControllerButton(controllerData.buttonsDown, _INPUT_ACTIONS[i], callback); } // Generate an event for the stick position struct CookedEvent ev; memset(&ev, 0, sizeof(ev)); ev.type = COOKED_EVENT_TYPE_JOY; ev.joyX = controllerData.leftStick.stickX; ev.joyY = controllerData.leftStick.stickY; callback(&ev); // Also generate directional button events from the stick position _report_key_states_from_axes(ev.joyX, ev.joyY, callback); // Update our prev variable so we can detect delta changes from down to up _prev_buttonsDown = controllerData.buttonsDown; } } return (addedControllerEvent != 0); }
#pragma once #include "SIngletonBase.h" #define MAXSTRSIZE 128 class TextData : public SingletonBase<TextData> { private: FILE * fp; public: TextData(); ~TextData(); HRESULT Init(); // Save void TextSave(char* saveFileName, vector<string> vStr); char* VectorArrayCombine(vector<string> vArray); // Load // 한 줄에 넣을 데이터 vector<string> TextLoad(char* loadFileName); // 데이터들의 리스트 vector<string> CharArraySeparation(char charArray[]); // 기존 파일 입출력 방식 void CreateWriteTextDataFilePointer(char * fileName) { fopen_s(&fp, fileName, "w"); } void TextWrite(vector<string> vStr); vector< vector<string> > TextRead(); void CreateReadTextDataFilePointer(char * fileName) { fopen_s(&fp, fileName, "r"); } void CloseTextDataFilePointer() { fclose(fp); } }; #define TEXTDATA TextData::GetSingleton()
#pragma once #include "..\Common\Pch.h" #include "..\RenderResource\Camera.h" #include "..\RenderResource\Frustum.h" #include "..\RenderResource\Light.h" #include "..\RenderResource\Material.h" #include "..\RenderResource\RenderTexture.h" #include "..\RenderResource\RenderManager.h" #include "Cube.h" #include "Sphere.h" #include "SkySphere.h" #include "SkyPlane.h" #include "Terrain.h" #include "Rain.h" #include "Trunk.h" #include "Leaf.h" class Game { public: Game(); ~Game(); void Initialize(); void Update(FLOAT delta); void PreRender(); void Render(); private: bool mWireFrame; bool mRained; RenderManager* mRenderManager; Camera* mCamera; Frustum* mFrustum; Light* mLight; Material* mMaterial0; Material* mMaterial1; Cube* mCube; // Material0 RenderTexture* mCubeReflect; Sphere* mSphere; // Material1 RenderTexture* mSphereReflect; SkySphere* mSkySphere; RenderTexture* mSkySphereReflect; SkyPlane* mSkyPlane; RenderTexture* mSkyPlaneReflect; Terrain* mTerrain; RenderTexture* mTrunkShadow; Rain* mRain; Trunk* mTrunk; RenderTexture* mTrunkShadow; Leaf* mLeaf; RenderTexture* mLeafShadow; void InitializeRenderResource(); void InitializeGameObject(); void UpdateRenderResource(FLOAT delta); void UpdateGameObject(FLOAT delta); };
#include <iostream> using namespace std; bool isSubsequence(string s, string t) { bool flag = false; int count = 0; int count1 = 0; int i = 0; if (s.length() == 0) return true; for (i = count; i < s.length(); i++) { flag = false; for (int j = count1; j < t.length(); j++) { if (s[i] == t[j]) { flag = true; count = i + 1; count1 = j + 1; break; } } if (flag == false) break; } if (flag == true) return true; else return false; } int main() { cout << isSubsequence("", "ahbgdc"); }
#include <string> #include <sstream> #include <fstream> #include <map> #include "../../../HiggsAnalysis/CombinedLimit/interface/RooMultiPdf.h" using namespace RooFit; using namespace RooStats ; Double_t MMIN = 1.62; Double_t MMAX = 2.0; double signalScaler=1;///10.; double analysisLumi = 1.; // 1/fb void AddData(TString, TString, RooWorkspace*, const Int_t NCAT, std::vector<string> branch_names, std::vector<string> cat_names, std::vector<string> bdt_val); void SigModelFit(RooWorkspace*, const Int_t NCAT, std::vector<string>, RooFitResult** signal_fitresults, TString type, TString Run); void BkgModelFit(RooWorkspace*, const Int_t NCAT, std::vector<string>, RooFitResult** bkg_fitresults, bool blind, std::vector<string> cat_names, TString m3m_name, bool dp, TString type, TString Run); void MakeSigWS(RooWorkspace* w, const Int_t NCAT, const char* filename, std::vector<string>); void MakeBkgWS(RooWorkspace* w, const Int_t NCAT, const char* filename, std::vector<string>, bool dp, TString type, TString Run); void MakeDataCard(RooWorkspace* w, const Int_t NCAT, const char* fileBaseName, const char* fileBkgName, string configFile, std::vector<string> cat_names, TString type, TString Run, bool blind, bool dp); void MakePlots(RooWorkspace* w, const Int_t NCAT, std::vector<string> cat_names, bool dp, bool blind, string configs, TString type, TString Run); void MakePlotsSplusB(RooWorkspace* w, const Int_t NCAT, std::vector<string> cat_names, bool dp, bool blind, string configs, TString type, TString Run); void MakePlotsSgn(RooWorkspace* w, const Int_t NCAT, std::vector<string> cat_names, string configs); void SetConstantParams(const RooArgSet* params); void tokenize(std::string const &str, const char delim, std::vector<std::string> &out); void createDataCards(TString inputfile, int signalsample = 0, bool blind = true, string modelCard="model_card.rs", string configFile="config.txt", TString type="threeGlobal", TString Run="2017", bool dp = true, bool doscan = false) { //Set verbosity ROOT::Minuit2::Minuit2Minimizer min (ROOT::Minuit2::kCombined); min.SetPrintLevel(0); gErrorIgnoreLevel = 1001; cout<< "Blind option "<<blind<<endl; vector<string> branch_names; // reserved to handle names for relevant branches vector<string> cat_names; // reserved to handle categories vector<string> bdt_val; // reserved to handle bdt cuts string lines[3]; // //read config file std::ifstream file(configFile); if (file.is_open()) { std::string line; int i=0; while (std::getline(file, line) && i<3) { lines[i]=line; i++; } file.close(); } tokenize(lines[0], ',', branch_names); tokenize(lines[1], ',', cat_names); tokenize(lines[2], ',', bdt_val); if(cat_names.size()!=bdt_val.size() && cat_names.size()>0){ cout<<"Please check content of "<<configFile; return; } //retrieve number of categories const Int_t NCAT = cat_names.size(); cout<<"Number of categories is "<<NCAT<<endl; TString m3m_name = branch_names.at(1); TString signalname("T3MSignal"); TString bkgname("T3MBkg"); string configFile_prefix = configFile.erase(configFile.size() - 4); if(!doscan) configFile_prefix = ""; TString fileBaseName = "CMS_"+signalname + TString(configFile_prefix) + TString("_13TeV"); TString fileBkgName = "CMS_"+bkgname + TString(configFile_prefix) + "_13TeV"; TString card_name(modelCard); HLFactory hlf("HLFactory", card_name, false); RooWorkspace* w = hlf.GetWs(); RooFitResult* bkg_fitresults[NCAT]; RooFitResult* signal_fitresults[NCAT]; w->var("m3m")->setMin(MMIN); w->var("m3m")->setMax(MMAX); //w->Print(); AddData(inputfile, Run, w,NCAT,branch_names,cat_names,bdt_val); SigModelFit(w, NCAT, cat_names, signal_fitresults, type, Run); MakeSigWS(w, NCAT, fileBaseName, cat_names); BkgModelFit(w, NCAT, cat_names, bkg_fitresults, blind, cat_names, m3m_name, dp, type, Run); MakeBkgWS(w, NCAT, fileBkgName, cat_names, dp, type, Run); MakeDataCard(w, NCAT, fileBaseName, fileBkgName, configFile_prefix, cat_names, type, Run, blind, dp); TString filename("temp_workspace.root"); w->writeToFile(filename); MakePlots(w,NCAT,cat_names, dp, blind, configFile_prefix, type, Run); //MakePlotsSplusB(w,NCAT,cat_names, dp, blind,configFile_prefix, type, Run); MakePlotsSgn(w,NCAT,cat_names,configFile_prefix); w->Print(); return; } void SigModelFit(RooWorkspace* w, const Int_t NCAT, std::vector<string> cat_names, RooFitResult** signal_fitresults, TString type, TString Run) { RooAbsPdf* pdfSigCB[NCAT]; RooAbsPdf* pdfSigGS[NCAT]; RooAddPdf* SignalModel[NCAT]; RooRealVar* sig_f[NCAT]; RooRealVar* f_cb[NCAT]; RooRealVar* sig_sigma[NCAT]; RooRealVar* sig_gaus_sigma[NCAT]; RooRealVar* sigma[NCAT]; RooRealVar* sigma_gaus[NCAT]; Float_t minMassFit(MMIN),maxMassFit(MMAX); RooRealVar* m3m = w->var("m3m"); m3m->setUnit("GeV"); m3m->setRange("signal",1.69,1.86); m3m->setRange("fullRange",1.62,2.0); //A,B,C TString cat_reso[] = {"A", "B", "C"}; for(int cr = 0; cr < 3; cr++) { std::cout<<">>> mass resolution category "<< cat_reso[cr] << std::endl; //Define roofit categories for simultaneous fit std::map<std::string, RooDataSet*> samplemap; RooCategory c("c", "c"); for (unsigned int category=0; category < NCAT; category++){ std::string cat_name = cat_names.at(category).c_str(); if(cat_name.rfind(cat_reso[cr], 0) == 0){ //A1,A2,A3 //define category c.defineType(cat_name.c_str()); //map category - dataset samplemap[cat_name] = (RooDataSet*) w->data(TString::Format("Sig_%s",cat_name.c_str())); } } RooDataSet combData("combData", "combined data", *m3m, Index(c), Import(samplemap)); // Construct a simultaneous pdf using category "c" as index RooSimultaneous simPdf("simPdf", "simultaneous pdf", c); //parameters in common RooRealVar* sig_m0 = w->var("sig_m0_"+cat_reso[cr]); RooRealVar* sig_alpha = w->var("sig_alpha_"+cat_reso[cr]); RooRealVar* sig_n = w->var("sig_n_"+cat_reso[cr]); for (unsigned int category=0; category < NCAT; category++){ std::string cat_name = cat_names.at(category).c_str(); TString tcat_name = cat_names.at(category).c_str(); if(cat_name.rfind(cat_reso[cr], 0) == 0){ //A1,A2,A3 //parameters and pdf per subcategory pdfSigCB[category] = (RooAbsPdf*) w->pdf("t3m_sig_CBshape_"+tcat_name+"_"+type); pdfSigGS[category] = (RooAbsPdf*) w->pdf("t3m_sig_GSshape_"+tcat_name+"_"+type); sig_f[category] = w->var("cb_fraction_"+tcat_name); sig_sigma[category] = w->var("sig_sigma_"+tcat_name); sig_gaus_sigma[category] = w->var("sig_gaus_sigma_"+tcat_name); SignalModel[category] = new RooAddPdf(TString::Format("SignalModel_fit_%s", cat_name.c_str()),"g+c",RooArgList(*pdfSigCB[category], *pdfSigGS[category]), *sig_f[category]); } } // Associate model with the categories for (unsigned int category=0; category < NCAT; category++){ std::string cat_name = cat_names.at(category).c_str(); if(cat_name.rfind(cat_reso[cr], 0) == 0){ //A1,A2,A3 //simPdf.addPdf(*SignalModel[cr], cat_name.c_str()); simPdf.addPdf(*SignalModel[category], cat_name.c_str()); } } //SignalModel is fitted to data for each mass resolution category separately // --------------------------------------------------- // P e r f o r m a s i m u l t a n e o u s f i t RooFitResult * r = simPdf.fitTo(combData, Save(true)); cout<<"Fit results"<<endl; r->floatParsFinal().Print("s"); //Save fitted pdf to wp for plotting purposes! for (unsigned int category=0; category < NCAT; category++){ std::string cat_name = cat_names.at(category).c_str(); if(cat_name.rfind(cat_reso[cr], 0) == 0){ //A1,A2,A3 w->import(*SignalModel[category]); } } //retrieving parameters from fitted shape // fix all the parameters except for the normalisation of signal TString name_mean = "m0_"+cat_reso[cr]+"_"+type+"_"+Run; TString name_alpha_cb = "alpha_cb_"+cat_reso[cr]+"_"+type+"_"+Run; TString name_n_cb = "n_cb_"+cat_reso[cr]+"_"+type+"_"+Run; RooRealVar mean (name_mean,"mean", sig_m0->getVal(), sig_m0->getVal(), sig_m0->getVal() ); RooRealVar alpha_cb (name_alpha_cb,"alpha_cb",sig_alpha->getVal(), sig_alpha->getVal(), sig_alpha->getVal()); RooRealVar n_cb (name_n_cb,"n_cb",sig_n->getVal(), sig_n->getVal(), sig_n->getVal()); mean.setError(sig_m0->getError()); alpha_cb.setError(sig_alpha->getError()); n_cb.setError(sig_n->getError()); for (unsigned int category=0; category < NCAT; category++){ std::string cat_name = cat_names.at(category).c_str(); if(cat_name.rfind(cat_reso[cr], 0) == 0){ //A1,A2,A3 //fraction can change depending on subcategory TString name_f_cb = TString::Format("f_cb_%s", cat_name.c_str())+"_"+type+"_"+Run; f_cb[category] = new RooRealVar (name_f_cb,"f_cb",sig_f[category]->getVal(), sig_f[category]->getVal(), sig_f[category]->getVal()); f_cb[category]->setError(sig_f[category]->getError()); //sigmas can change depending on subcategory TString name_sigma = TString::Format("sigma_%s", cat_name.c_str())+"_"+type+"_"+Run; sigma[category] = new RooRealVar(name_sigma,"sigma",sig_sigma[category]->getVal(), sig_sigma[category]->getVal(), sig_sigma[category]->getVal()); sigma[category]->setError(sig_sigma[category]->getError()); TString name_sigma_gaus = TString::Format("sigma_gaus_%s", cat_name.c_str())+"_"+type+"_"+Run; sigma_gaus[category] = new RooRealVar(name_sigma_gaus,"sigma_gaus",sig_gaus_sigma[category]->getVal(), sig_gaus_sigma[category]->getVal(), sig_gaus_sigma[category]->getVal()); sigma_gaus[category]->setError(sig_gaus_sigma[category]->getError()); } } for (unsigned int category=0; category < NCAT; category++){ std::string cat_name = cat_names.at(category).c_str(); TString tcat_name = cat_names.at(category).c_str(); if(cat_name.rfind(cat_reso[cr], 0) == 0){ //A1,A2,A3 //Apply correction to the fixed mass char line[100]; RooRealVar UncMean("UncMean", "", 0., -5, 5); UncMean.setVal(0.0); // According to ANv2 L798, "mean" is 0.09% smaller in data. So we scale MC mean by 0.9991, and assign 0.0009 uncertainty sprintf(line, "(1+0.0009*%s)*%.5f", "UncMean", sig_m0->getVal()*0.9991); // mass mean value RooFormulaVar fmean("fmean_"+tcat_name+"_"+type+"_"+Run,line,RooArgList(UncMean)); //Apply correction to the fixed sigmas char line2[100]; RooRealVar UncSigma("UncSigma", "", 0., -5, 5); UncSigma.setVal(0.0); // According to Fig47, MC has up to 2% worse resolution! We don't scale the MC resolution, but only assign 2% uncertainty sprintf(line2, "(1+0.02*%s)*%.5f", "UncSigma", sigma[category]->getVal()); // mass mean value RooFormulaVar fsigma("fsigma_"+tcat_name+"_"+type+"_"+Run,line2,RooArgList(UncSigma)); //Define pdf for each subcategory //RooCBShape CB_final("CB_final_"+tcat_name+"_"+type+"_"+Run,"CB PDF",*m3m,mean,*sigma[category],alpha_cb,n_cb) ; //RooGaussian GS_final("GS_final_"+tcat_name+"_"+type+"_"+Run,"GS PDF",*m3m,mean,*sigma_gaus[category]) ; //RooAddPdf signal("SignalModel_"+tcat_name,"",RooArgList(CB_final,GS_final), *f_cb[category]); // then recreate the signal shape using the 2 RooFormulaVar and the other 4 parameters RooCBShape CB_final("CB_final_"+tcat_name+"_"+type+"_"+Run,"CB PDF",*m3m,fmean,fsigma,alpha_cb,n_cb) ; RooGaussian GS_final("GS_final_"+tcat_name+"_"+type+"_"+Run,"GS PDF",*m3m,fmean,*sigma_gaus[category]) ; RooAddPdf signal("SignalModel_"+tcat_name,"",RooArgList(CB_final,GS_final), *f_cb[category]); w->defineSet("SigPdfParam_"+tcat_name, RooArgSet( //mean, //*w->var("sig_m0_"+cat_reso[cr]+subc), //*sigma[category], //*w->var("sig_sigma_"+cat_reso[cr]+subc), *sigma_gaus[category], //*w->var("sig_gaus_sigma_"+cat_reso[cr]+subc), alpha_cb, //*w->var("sig_alpha_"+cat_reso[cr]+subc), n_cb, //*w->var("sig_n_"+cat_reso[cr]+subc), *f_cb[category] //*w->var("sig_f_"+cat_reso[cr]+subc) ), true); SetConstantParams(w->set("SigPdfParam_"+tcat_name)); //add mean and sigma to named set w->import(mean); w->import(*sigma[category]); w->extendSet("SigPdfParam_"+tcat_name, "m0_"+cat_reso[cr]); w->extendSet("SigPdfParam_"+tcat_name, "sigma_"+tcat_name); w->import(signal); } } } //for debugging std::cout<<"WP after signal fit"<<std::endl; w->Print(); } void MakePlotsSplusB(RooWorkspace* w, const Int_t NCAT, std::vector<string> cat_names, bool dp, bool blind, string configs, TString type, TString Run){ RooDataSet* signalAll[NCAT]; RooDataSet* dataAll[NCAT]; RooDataSet* dataToPlot[NCAT]; RooAbsPdf* sigpdf[NCAT]; RooAbsPdf* bkgpdf[NCAT]; TCut sidebands; RooRealVar* m3m = w->var("m3m"); m3m->setUnit("GeV"); for(unsigned int category=0; category< NCAT; category++){ if (category%3==0) sidebands = TCut("(m3m < 1.75 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.80)"); else if (category%3==1) sidebands = TCut("(m3m < 1.74 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.82)"); else if (category%3==2) sidebands = TCut("(m3m < 1.73 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.83)"); signalAll[category]= (RooDataSet*) w->data(TString::Format("Sig_%s",cat_names.at(category).c_str())); dataAll[category]= (RooDataSet*) w->data(TString::Format("Bkg_%s",cat_names.at(category).c_str())); //blind data if(blind) dataToPlot[category] = (RooDataSet*)dataAll[category]->reduce(sidebands); else dataToPlot[category] = (RooDataSet*)dataAll[category]->reduce("m3m > 1.62 && m3m < 2.0"); dataToPlot[category]->Print(); sigpdf[category] =(RooAbsPdf*)w->pdf("SignalModel"+TString::Format("_fit_%s",cat_names.at(category).c_str())); if(dp){ RooMultiPdf* multipdf = (RooMultiPdf*) w->pdf(TString::Format("roomultipdf_"+Run+"_"+type+"_%s",cat_names.at(category).c_str())); bkgpdf[category] =(RooAbsPdf*)multipdf->getCurrentPdf(); } else bkgpdf[category] =(RooAbsPdf*)w->pdf(TString::Format("t3m_bkg_expo_"+type+"_"+Run+"_%s",cat_names.at(category).c_str())); } m3m->setRange("SB1_A",1.62,1.75); m3m->setRange("SB2_A",1.80,2.0); m3m->setRange("SB1_B",1.62,1.74); m3m->setRange("SB2_B",1.82,2.0); m3m->setRange("SB1_C",1.62,1.73); m3m->setRange("SB2_C",1.83,2.0); m3m->setRange("fullRange",1.62,2.0); TLatex *text = new TLatex(); text->SetNDC(); text->SetTextSize(0.04); cout<<" bkg fit "<<endl; RooPlot* plot[NCAT]; for(unsigned int category=0; category< NCAT; category++){ plot[category] = m3m->frame(); signalAll[category]->plotOn( plot[category],RooFit::MarkerColor(kCyan+2),RooFit::MarkerStyle(6),RooFit::MarkerSize(0.0), Binning(38, 1.620000, 2.00000)); sigpdf[category]->plotOn(plot[category], RooFit::LineColor(kRed),RooFit::LineWidth(3)); //plot data if (category%3==0) dataToPlot[category]->plotOn(plot[category],RooFit::MarkerColor(kBlack),RooFit::MarkerStyle(8),RooFit::MarkerSize(1),RooFit::LineWidth(3), Binning(38, 1.620000, 2.00000)); if (category%3==1) dataToPlot[category]->plotOn(plot[category],RooFit::MarkerColor(kBlack),RooFit::MarkerStyle(8),RooFit::MarkerSize(1),RooFit::LineWidth(3), Binning(38, 1.620000, 2.00000)); if (category%3==2) dataToPlot[category]->plotOn(plot[category],RooFit::MarkerColor(kBlack),RooFit::MarkerStyle(8),RooFit::MarkerSize(1),RooFit::LineWidth(3), Binning(38, 1.620000, 2.00000)); if(blind){ //plot pdf in sidebands if ( category%3==0 ) bkgpdf[category]->plotOn(plot[category], Range("SB1_A,SB2_A"), RooFit::NormRange("SB1_A,SB2_A"), RooFit::LineColor(kBlue), RooFit::LineWidth(3)); if ( category%3==1 ) bkgpdf[category]->plotOn(plot[category], Range("SB1_B,SB2_B"), RooFit::NormRange("SB1_B,SB2_B"), RooFit::LineColor(kBlue), RooFit::LineWidth(3)); if ( category%3==2 ) bkgpdf[category]->plotOn(plot[category], Range("SB1_C,SB2_C"), RooFit::NormRange("SB1_C,SB2_C"), RooFit::LineColor(kBlue), RooFit::LineWidth(3)); }else{ //plot pdf in full range if ( category%3==0 ) bkgpdf[category]->plotOn(plot[category], RooFit::LineColor(kBlue), RooFit::LineWidth(3)); if ( category%3==1 ) bkgpdf[category]->plotOn(plot[category], RooFit::LineColor(kBlue), RooFit::LineWidth(3)); if ( category%3==2 ) bkgpdf[category]->plotOn(plot[category], RooFit::LineColor(kBlue), RooFit::LineWidth(3)); } //plot signal+bkg RooRealVar bkgfrac("bkgfrac", "fraction of background", 0.9, 0., 1.); RooAddPdf model("model", "s+b", RooArgList(*bkgpdf[category], *sigpdf[category]), bkgfrac); model.fitTo(*dataToPlot[category], RooFit::Extended()); model.plotOn(plot[category], RooFit::LineColor(kGreen), RooFit::LineWidth(3)); //bkgpdf[category]->paramOn( plot[category], Format("NELU", AutoPrecision(2)),ShowConstants(), Layout(0.4,0.99,0.9)); plot[category]->SetTitle(TString::Format("Category %s",cat_names.at(category).c_str())); plot[category]->SetMinimum(0.00); plot[category]->SetMaximum(1.40*plot[category]->GetMaximum()); plot[category]->GetXaxis()->SetTitle("m_{3mu} [GeV]"); cout<<"chi2 bkg category: "<<cat_names.at(category).c_str()<<" "<<plot[category]->chiSquare()<<endl; TCanvas* ctmp_sig = new TCanvas(TString::Format("Category %s",cat_names.at(category).c_str()),"Categories",0,0,660,660); ctmp_sig->SetFrameLineWidth(3); ctmp_sig->SetTickx(); ctmp_sig->SetTicky(); plot[category]->Draw(); plot[category]->Print(); plot[category]->Draw("SAME"); TLegend *legmc = new TLegend(0.50,0.70,0.86,0.86); legmc->AddEntry(plot[category]->getObject(0),"MC Signal (B=10^{-7})","LPE"); legmc->AddEntry(plot[category]->getObject(1),"Signal Model","L"); legmc->AddEntry(plot[category]->getObject(2),"Data","LPE"); legmc->AddEntry(plot[category]->getObject(3),"Bkg Model","L"); legmc->SetBorderSize(0); legmc->SetFillStyle(0); legmc->SetTextSize(0.029); legmc->Draw(); ctmp_sig->SaveAs("plots/"+TString::Format("Category_%s_SplusB",cat_names.at(category).c_str())+".png"); } } void MakePlots(RooWorkspace* w, const Int_t NCAT, std::vector<string> cat_names, bool dp, bool blind, string configs, TString type, TString Run){ RooDataSet* signalAll[NCAT]; RooDataSet* dataAll[NCAT]; RooDataSet* dataToPlot[NCAT]; RooAbsPdf* sigpdf[NCAT]; RooAbsPdf* bkgpdf[NCAT]; TCut sidebands; RooRealVar* m3m = w->var("m3m"); m3m->setUnit("GeV"); for(unsigned int category=0; category< NCAT; category++){ if (category%3==0) sidebands = TCut("(m3m < 1.75 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.80)"); else if (category%3==1) sidebands = TCut("(m3m < 1.74 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.82)"); else if (category%3==2) sidebands = TCut("(m3m < 1.73 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.83)"); signalAll[category]= (RooDataSet*) w->data(TString::Format("Sig_%s",cat_names.at(category).c_str())); dataAll[category]= (RooDataSet*) w->data(TString::Format("Bkg_%s",cat_names.at(category).c_str())); //blind data if(blind) dataToPlot[category] = (RooDataSet*)dataAll[category]->reduce(sidebands); else dataToPlot[category] = (RooDataSet*)dataAll[category]->reduce("m3m > 1.62 && m3m < 2.0"); dataToPlot[category]->Print(); sigpdf[category] =(RooAbsPdf*)w->pdf("SignalModel"+TString::Format("_%s",cat_names.at(category).c_str())); if(dp) { RooMultiPdf* multipdf = (RooMultiPdf*) w->pdf(TString::Format("roomultipdf_"+Run+"_"+type+"_%s",cat_names.at(category).c_str())); bkgpdf[category] =(RooAbsPdf*)multipdf->getCurrentPdf(); } else bkgpdf[category] =(RooAbsPdf*)w->pdf(TString::Format("t3m_bkg_expo_"+type+"_"+Run+"_%s",cat_names.at(category).c_str())); } m3m->setRange("SB1_A",1.62,1.75); m3m->setRange("SB2_A",1.80,2.0); m3m->setRange("SB1_B",1.62,1.74); m3m->setRange("SB2_B",1.82,2.0); m3m->setRange("SB1_C",1.62,1.73); m3m->setRange("SB2_C",1.83,2.0); m3m->setRange("SIG_A",1.75,1.80); //12MeV sigma m3m->setRange("SIG_B",1.74,1.82); //19MeV sigma m3m->setRange("SIG_C",1.73,1.83); //23MeV sigma m3m->setRange("fullRange",1.62,2.0); TLatex *text = new TLatex(); text->SetNDC(); text->SetTextSize(0.04); TString filename(type+"_"+Run+"_yields.txt"); //TString filename("yields.txt"); ofstream outFile(filename); outFile << "cat\tsig\tbkg\n" << endl; RooPlot* plot[NCAT]; for(unsigned int category=0; category< NCAT; category++){ plot[category] = m3m->frame(); //plot signal signalAll[category]->plotOn( plot[category],RooFit::MarkerColor(kWhite),RooFit::MarkerStyle(1),RooFit::MarkerSize(0.0), RooFit::LineColor(kWhite), Binning(38, 1.620000, 2.00000)); sigpdf[category]->plotOn(plot[category], RooFit::LineColor(kRed),RooFit::LineWidth(3)); //signal integral RooAbsReal* i_sig; if ( category%3==0 ) i_sig = sigpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SIG_A"); if ( category%3==1 ) i_sig = sigpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SIG_B"); if ( category%3==2 ) i_sig = sigpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SIG_C"); //plot data if (category%3==0) dataToPlot[category]->plotOn(plot[category],RooFit::MarkerColor(kBlack),RooFit::MarkerStyle(8),RooFit::MarkerSize(1),RooFit::LineWidth(3), Binning(38, 1.620000, 2.00000), RooFit::XErrorSize(0)); if (category%3==1) dataToPlot[category]->plotOn(plot[category],RooFit::MarkerColor(kBlack),RooFit::MarkerStyle(8),RooFit::MarkerSize(1),RooFit::LineWidth(3), Binning(38, 1.620000, 2.00000), RooFit::XErrorSize(0)); if (category%3==2) dataToPlot[category]->plotOn(plot[category],RooFit::MarkerColor(kBlack),RooFit::MarkerStyle(8),RooFit::MarkerSize(1),RooFit::LineWidth(3), Binning(38, 1.620000, 2.00000), RooFit::XErrorSize(0)); if(blind){ //plot pdf in sidebands if ( category%3==0 ) bkgpdf[category]->plotOn(plot[category], Range("SB1_A,SB2_A"), RooFit::NormRange("SB1_A,SB2_A"), RooFit::LineColor(kBlue), RooFit::LineWidth(3)); if ( category%3==1 ) bkgpdf[category]->plotOn(plot[category], Range("SB1_B,SB2_B"), RooFit::NormRange("SB1_B,SB2_B"), RooFit::LineColor(kBlue), RooFit::LineWidth(3)); if ( category%3==2 ) bkgpdf[category]->plotOn(plot[category], Range("SB1_C,SB2_C"), RooFit::NormRange("SB1_C,SB2_C"), RooFit::LineColor(kBlue), RooFit::LineWidth(3)); }else{ //plot pdf in full range if ( category%3==0 ) bkgpdf[category]->plotOn(plot[category], RooFit::LineColor(kBlue), RooFit::LineWidth(3)); if ( category%3==1 ) bkgpdf[category]->plotOn(plot[category], RooFit::LineColor(kBlue), RooFit::LineWidth(3)); if ( category%3==2 ) bkgpdf[category]->plotOn(plot[category], RooFit::LineColor(kBlue), RooFit::LineWidth(3)); } //background integral RooAbsReal* i_bkg; RooAbsReal* i_bkg_sb; if ( category%3==0 ) { i_bkg = bkgpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SIG_A"); i_bkg_sb = bkgpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SB1_A,SB2_A"); } if ( category%3==1 ) { i_bkg = bkgpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SIG_B"); i_bkg_sb = bkgpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SB1_B,SB2_B"); } if ( category%3==2 ) { i_bkg = bkgpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SIG_C"); i_bkg_sb = bkgpdf[category]->createIntegral(RooArgSet(*m3m), RooArgSet(*m3m), "SB1_B,SB2_B"); } cout<<category<<" Expected signal yield "<<i_sig->getVal()*signalAll[category]->sumEntries()<<endl; cout<<category<<" i_bkg->getVal() "<<i_bkg->getVal()<<endl; cout<<category<<" i_bkg_sb->getVal() "<<i_bkg_sb->getVal()<<endl; cout<<category<<" dataAll[category]->sumEntries() "<<dataAll[category]->sumEntries()<<endl; cout<<category<<" Expected bkg yield based on SB"<<i_bkg->getVal()*dataAll[category]->sumEntries() / i_bkg_sb->getVal()<<endl; outFile << TString::Format("%s",cat_names.at(category).c_str())<<"\t"<<i_sig->getVal()*signalAll[category]->sumEntries()<<"\t"<<i_bkg->getVal()*dataAll[category]->sumEntries() / i_bkg_sb->getVal()<<endl; //bkgpdf[category]->paramOn( plot[category], Format("NELU", AutoPrecision(2)),ShowConstants(), Layout(0.4,0.99,0.9)); plot[category]->SetTitle(""); //TString::Format("Category %s",cat_names.at(category).c_str())); plot[category]->SetMinimum(0.00); plot[category]->SetMaximum(1.50*plot[category]->GetMaximum()); plot[category]->GetXaxis()->SetTitle("m(3#mu) [GeV]"); plot[category]->GetYaxis()->SetTitle("Events / 10 MeV"); plot[category]->GetXaxis()->SetTitleOffset(1.16); plot[category]->GetYaxis()->SetTitleOffset(1.16); plot[category]->GetXaxis()->SetTitleSize(0.045); plot[category]->GetYaxis()->SetTitleSize(0.045); cout<<"chi2 bkg category: "<<cat_names.at(category).c_str()<<" "<<plot[category]->chiSquare()<<endl; TCanvas* ctmp_sig = new TCanvas(TString::Format("Category %s",cat_names.at(category).c_str()),"Categories",50,50,800,800); ctmp_sig->SetFrameLineWidth(3); //ctmp_sig->SetTickx(); //ctmp_sig->SetTicky(); plot[category]->Draw(); plot[category]->Print(); plot[category]->Draw("SAME"); TLegend *legmc = new TLegend(0.48,0.60,0.86,0.74); legmc->SetBorderSize(0); legmc->SetFillStyle(0); legmc->SetTextFont(42); //legmc->SetTextSize(0.05); legmc->AddEntry(plot[category]->getObject(2),"Data","PE"); //legmc->AddEntry(plot[category]->getObject(0),"MC Signal (B=10^{-7})","LPE"); legmc->AddEntry(plot[category]->getObject(1),"Signal (B=10^{-7})","L"); legmc->AddEntry(plot[category]->getObject(3),"Background-only fit","L"); legmc->Draw(); //add lumi TDR style TLatex latex; latex.SetNDC(); latex.SetTextAngle(0); latex.SetTextColor(kBlack); float l = ctmp_sig->GetLeftMargin(); float t = ctmp_sig->GetTopMargin(); float ri = ctmp_sig->GetRightMargin(); float bo = ctmp_sig->GetBottomMargin(); float lumiTextSize = 0.50;; float lumiTextOffset = 0.2; TString lumiText = Run; if(Run=="2017") lumiText+=", 38 fb^{-1} (13 TeV)"; if(Run=="2018") lumiText+=", 59.7 fb^{-1} (13 TeV)"; latex.SetTextFont(42); latex.SetTextAlign(31); latex.SetTextSize(lumiTextSize*t); latex.DrawLatex(1-ri,1-t+lumiTextOffset*t,lumiText); //add CMS text float cmsTextFont = 61; float cmsTextSize = 0.65; float extraTextFont = 52; float relPosX = 0.045; float relPosY = 0.035; float posX_ = l + 0.05*(1-l-ri); float posY_ = 0.95 -t - relPosY*(1-t-bo); latex.SetTextFont(cmsTextFont); latex.SetTextSize(cmsTextSize*t); latex.SetTextAlign(12); latex.DrawLatex(posX_, posY_, "CMS"); //add Category text latex.SetTextSize(cmsTextSize*t*0.80); latex.DrawLatex(0.5, posY_, TString::Format("HF Category %s",cat_names.at(category).c_str())); TString addlabel = "three global muons"; if (type!="threeGlobal") addlabel = "two global one tracker"; latex.SetTextSize(cmsTextSize*t*0.60); latex.SetTextFont(extraTextFont); latex.DrawLatex(0.5, posY_- 1.2*cmsTextSize*t*0.65, addlabel); //add Preliminary text latex.SetTextFont(extraTextFont); latex.SetTextSize(cmsTextSize*t); latex.DrawLatex(posX_, posY_ - 1.2*cmsTextSize*t, "Preliminary"); //latex.DrawLatex(posX_, posY_ - 1.2*cmsTextSize*t, " "); ctmp_sig->SaveAs("plots/"+TString::Format("Category_%s",cat_names.at(category).c_str())+".png"); ctmp_sig->SaveAs("plots/"+TString::Format("Category_%s",cat_names.at(category).c_str())+".pdf"); ctmp_sig->SaveAs("plots/"+TString::Format("Category_%s",cat_names.at(category).c_str())+".root"); } outFile.close(); } void MakePlotsSgn(RooWorkspace* w, const Int_t NCAT, std::vector<string> cat_names, string configs){ RooDataSet* signalAll[NCAT]; RooAbsPdf* sigpdf[NCAT]; TFile f("signal_shapes.root","recreate"); for(unsigned int category=0; category< NCAT; category++){ signalAll[category] = (RooDataSet*) w->data(TString::Format("Sig_%s",cat_names.at(category).c_str())); sigpdf[category] = (RooAbsPdf*)w->pdf("SignalModel_fit_"+TString::Format("%s",cat_names.at(category).c_str())); //TO DO: display mass and sigma on canvases } RooRealVar* m3m = w->var("m3m"); m3m->setUnit("GeV"); m3m->setRange("fullRange",1.62,2.0); TLatex *text = new TLatex(); text->SetNDC(); text->SetTextSize(0.04); RooPlot* plot_sgn[NCAT]; for(unsigned int category=0; category< NCAT; category++){ plot_sgn[category] = m3m->frame(); signalAll[category]->plotOn( plot_sgn[category],RooFit::MarkerColor(kBlack),RooFit::MarkerStyle(6),RooFit::MarkerSize(0.75)); //signalAll[category]->statOn( plot_sgn[category],Layout(0.65,0.99,0.9)) ; sigpdf[category]->plotOn( plot_sgn[category], RooFit::LineColor(kRed),RooFit::LineWidth(2)); sigpdf[category]->paramOn( plot_sgn[category], Format("NEU", RooFit::AutoPrecision(2)), ShowConstants(true), Layout(0.50,0.9,0.9)); plot_sgn[category]->getAttText()->SetTextSize(0.025); plot_sgn[category]->SetTitle(TString::Format("Category %s",cat_names.at(category).c_str())); plot_sgn[category]->SetMinimum(0.0); plot_sgn[category]->SetMaximum(1.50*plot_sgn[category]->GetMaximum()); plot_sgn[category]->GetXaxis()->SetTitle("m_{3mu} [GeV]"); TCanvas* ctmp_sig = new TCanvas(TString::Format("Category %s",cat_names.at(category).c_str()),"Categories",0,0,660,660); ctmp_sig->SetFrameLineWidth(3); ctmp_sig->SetTickx(); ctmp_sig->SetTicky(); plot_sgn[category]->Draw(); plot_sgn[category]->Print(); plot_sgn[category]->Draw("SAME"); TLegend *legmc = new TLegend(0.12,0.70,0.43,0.86); legmc->AddEntry(plot_sgn[category]->getObject(0),"MC Signal (B=10^{-7})","LPE"); legmc->AddEntry(plot_sgn[category]->getObject(1),"Signal Model","L"); cout<<"chi2 signal category: "<<cat_names.at(category).c_str()<<" "<<plot_sgn[category]->chiSquare()<<endl; //add Lumi and Chi2 to plot Double_t Chi2 = plot_sgn[category]->chiSquare(); std::stringstream stream_chi2; stream_chi2 << std::fixed << std::setprecision(2) << Chi2; std::string strChi2 = stream_chi2.str(); TString chi2tstring = "\\chi^{2}\\text{/NDOF} = "+strChi2; TLatex* text_chi2 = new TLatex(0.55,0.5, chi2tstring); text_chi2->SetTextSize(0.04); text_chi2->SetNDC(kTRUE); text_chi2->Draw("same"); legmc->SetBorderSize(0); legmc->SetFillStyle(0); legmc->SetTextSize(0.029); legmc->Draw(); //draw contour //need to retrieve fit results! //sigpdf[category]->plotOn( plot_sgn[category], RooFit::LineColor(kRed),RooFit::VisualizeError(results,2), RooFit::FillColor(kYellow),RooFit::FillStyle(3001)) ; //sigpdf[category]->plotOn( plot_sgn[category], RooFit::LineColor(kRed),RooFit::VisualizeError(results,2), RooFit::FillColor(kGreen), RooFit::FillStyle(3001)) ; ctmp_sig->SaveAs("plots/"+TString::Format("Signal_%s",cat_names.at(category).c_str())+".png"); ctmp_sig->Write(); } f.Close(); } void AddData(TString file, TString era, RooWorkspace* w, const Int_t NCAT, std::vector<string> branch_names, std::vector<string> cat_names, std::vector<string> bdt_val){ //outputTree,tripletMass,bdt,category,isMC,weight TString tree_name = branch_names.at(0); TString m3m_name = branch_names.at(1); TString bdt_name = branch_names.at(2); TString categ_name = branch_names.at(3); TString MClable_name = branch_names.at(4); TString weight_name = branch_names.at(5); //additional var pre-app comment TString dimu1_name = branch_names.at(6); TString dimu2_name = branch_names.at(7); TString omega_cut = "abs("+dimu1_name+"-0.782)>0.01 && abs("+dimu2_name+"-0.782)>0.01"; //build strings for bdt cut selection vector<TString> bdt_cuts; // reserved to handle bdt cuts (full selection string) for (unsigned int category=0; category < NCAT; category++){ if(category<3) bdt_cuts.push_back( TString::Format("%s>%s", bdt_name.Data(), bdt_val.at(category).c_str()) ); else bdt_cuts.push_back( TString::Format("%s<=%s && %s>%s", bdt_name.Data(), bdt_val.at(category-3).c_str(), bdt_name.Data(), bdt_val.at(category).c_str()) ); } TFile *f = new TFile(file,"READ"); TTree *tree = (TTree *) f->Get(tree_name); RooRealVar m3m(m3m_name, m3m_name, 1.62, 2.0); RooRealVar bdt(bdt_name, bdt_name, -2, 2); RooRealVar categ(categ_name, categ_name, 0, 2);//mass resolution category 0=A, 1=B, 2=C RooRealVar isMC(MClable_name, MClable_name, 0, 4); //0=data, 1=Ds, 2=B0, 3=Bp, 4=W RooRealVar weight(weight_name, weight_name, 0, 1); //normalisation of MC RooRealVar dimu1(dimu1_name, dimu1_name, 0.2, 1.8); //dimu_OS1 RooRealVar dimu2(dimu2_name, dimu2_name, 0.2, 1.8); //dimu_OS2 RooArgSet variables(m3m); variables.add(bdt); variables.add(categ); variables.add(isMC); variables.add(weight); variables.add(dimu1); variables.add(dimu2); TString name, bdtcut, category_cut; for(unsigned int category=0; category< NCAT; category++){ name = TString::Format("Sig_%s",cat_names.at(category).c_str()); bdtcut = bdt_cuts.at(category); TString mc_cut = MClable_name+">0"; cout<<"Importing signal "<<name<<" bdt selection "<<bdtcut<<endl; for(int i = 0; i < 3; i++) { if(category%3==i) category_cut = categ_name+"=="+TString(std::to_string(i)); } RooDataSet sigds(name, name, variables, Import(*tree), Cut("("+mc_cut+"&&"+category_cut+"&&"+bdtcut+"&&"+omega_cut+")"), WeightVar(weight_name)); sigds.Print(); //reduce to only one variable RooDataSet* sigds_reduced = (RooDataSet*) sigds.reduce(RooArgSet(m3m)); w->import(*sigds_reduced,Rename(name),RooFit::RenameVariable(m3m_name,"m3m")); } for(unsigned int category=0; category< NCAT; category++){ name = TString::Format("Bkg_%s",cat_names.at(category).c_str()); bdtcut = bdt_cuts.at(category); TString mc_cut = MClable_name+"==0"; cout<<"Importing background "<<name<<" bdt selection "<<bdtcut<<endl; for(int i = 0; i < 3; i++) { if(category%3==i) category_cut = categ_name+"=="+TString(std::to_string(i)); } RooDataSet bkgds(name, name, variables, Import(*tree), Cut("("+mc_cut+"&&"+category_cut+"&&"+bdtcut+"&&"+omega_cut+")")); bkgds.Print(); //reduce to only one variable RooDataSet* bkgds_reduced = (RooDataSet*) bkgds.reduce(RooArgSet(m3m)); w->import(*bkgds_reduced,Rename(name),RooFit::RenameVariable(m3m_name,"m3m")); } f->Close(); } void BkgModelFit(RooWorkspace* w, const Int_t NCAT, std::vector<string>, RooFitResult** bkg_fitresults, bool blind, std::vector<string> cat_names, TString m3m_name, bool discpf, TString type, TString Run){ RooDataSet* dataAll[NCAT]; RooDataSet* dataToFit[NCAT]; RooAbsPdf* pdfBkgExp[NCAT]; RooAbsPdf* BkgModel[NCAT]; RooRealVar* bkg_norm[NCAT]; RooRealVar* m3m = w->var("m3m"); TCut sidebands; m3m->setUnit("GeV"); m3m->setRange("SB1_A",1.62,1.75); m3m->setRange("SB2_A",1.80,2.0); m3m->setRange("SB1_B",1.62,1.74); m3m->setRange("SB2_B",1.82,2.0); m3m->setRange("SB1_C",1.62,1.73); m3m->setRange("SB2_C",1.83,2.0); m3m->setRange("fullRange",1.62,2.0); for(unsigned int category=0; category< NCAT; category++) { dataAll[category] = (RooDataSet*) w->data(TString::Format("Bkg_%s",cat_names.at(category).c_str())); if (category%3==0) sidebands = TCut("(m3m < 1.75 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.80)"); else if (category%3==1) sidebands = TCut("(m3m < 1.74 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.82)"); else if (category%3==2) sidebands = TCut("(m3m < 1.73 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.83)"); //blind data if(blind) dataToFit[category] = (RooDataSet*)dataAll[category]->reduce(sidebands); else dataToFit[category] = (RooDataSet*)dataAll[category]->reduce("m3m > 1.62 && m3m < 2.0"); dataToFit[category]->Print(); //define bkg model if(!discpf) { pdfBkgExp[category] = (RooAbsPdf*) w->pdf(TString::Format("t3m_bkg_expo_"+type+"_"+Run+"_%s",cat_names.at(category).c_str())); bkg_norm[category] = w->var(TString::Format("t3m_bkg_expo_"+type+"_"+Run+"_%s_norm",cat_names.at(category).c_str())) ; }else{ //open rootfile created by running discrete_profiling_HF.py TString dp_filepath = "../python/MultiPdfWorkspaces/"+Run+"_"+type+"_"+cat_names.at(category).c_str()+".root"; cout<<"Bkg model from external wp "<<dp_filepath<<endl; TFile *f = new TFile(dp_filepath,"READ"); RooWorkspace* wdf = (RooWorkspace*)f->Get("ospace"); RooMultiPdf* multipdf = (RooMultiPdf*) wdf->pdf("roomultipdf_"+Run+"_"+type+"_"+cat_names.at(category).c_str())->Clone(); bkg_norm[category] = (RooRealVar*) wdf->var("roomultipdf_"+Run+"_"+type+"_"+cat_names.at(category).c_str()+"_norm")->Clone(); w->import(*multipdf, RooFit::RenameVariable(m3m_name, "m3m")); //, Rename( TString::Format("multipdf_%s",cat_names.at(category).c_str()) )); //In this way you take the best fit pdf or the exponential, depending on what was done in discrete_profiling_HF.py pdfBkgExp[category] = (RooAbsPdf*) multipdf->getCurrentPdf(); //->Clone("t3m_bkg_dp_"+TString::Format("%s",cat_names.at(category).c_str())); } BkgModel[category] = new RooAddPdf(TString::Format("BkgModel_fit_%s",cat_names.at(category).c_str()),"bkg model",RooArgList(*pdfBkgExp[category]), RooArgList(*bkg_norm[category])); //fit SB1, SB2, combined if(blind){ if ( category%3==0 ) bkg_fitresults[category] = BkgModel[category]->fitTo(*dataToFit[category], Range("SB1_A,SB2_A"), Save(), Extended(true), SumW2Error(true), Verbose(true)) ; if ( category%3==1 ) bkg_fitresults[category] = BkgModel[category]->fitTo(*dataToFit[category], Range("SB1_B,SB2_B"), Save(), Extended(true), SumW2Error(true), Verbose(true)) ; if ( category%3==2 ) bkg_fitresults[category] = BkgModel[category]->fitTo(*dataToFit[category], Range("SB1_C,SB2_C"), Save(), Extended(true), SumW2Error(true), Verbose(true)) ; } else bkg_fitresults[category]=BkgModel[category]->fitTo(*dataToFit[category], Range("fullRange"), Save(), Extended(true), SumW2Error(true)); //Important! Should switch to "m3m" in discrete_profiling.py w->import(*BkgModel[category], RooFit::RenameVariable(m3m_name, "m3m")); w->import(*bkg_norm[category]); w->Print(); } } void MakeSigWS(RooWorkspace* w, const Int_t NCAT, const char* fileBaseName, std::vector<string> cat_names) { TString wsDir = "workspaces/"; RooWorkspace *wAll = new RooWorkspace("w_all","w_all"); RooAbsPdf* SigPdf[NCAT]; cout << "-----------------------------------Write signal workspace--------------" <<std::endl; for(unsigned int category=0; category < NCAT; category++){ //(1) Retrieve p.d.f.s // SigPdf[category] = (RooAbsPdf*) w->pdf("t3m_sig_shape"+TString::Format("_%s",cat_names.at(category).c_str())); // wAll->import(*w->pdf("t3m_sig_CBshape"+TString::Format("_%s",cat_names.at(category).c_str()))); // wAll->import(*w->pdf("t3m_sig_GSshape"+TString::Format("_%s",cat_names.at(category).c_str()))); wAll->import(*w->pdf("SignalModel"+TString::Format("_%s",cat_names.at(category).c_str()))); wAll->import(*w->data(TString::Format("Sig_%s",cat_names.at(category).c_str()))); //(2) factory of systematics //.... } TString filename(wsDir+TString(fileBaseName)+".root"); wAll->writeToFile(filename); cout << "-----------------------------------Write signal workspace in: " << filename << " file" << endl; return; } void MakeBkgWS(RooWorkspace* w, const Int_t NCAT, const char* fileBaseName, std::vector<string> cat_names, bool discpf, TString type, TString Run) { TString wsDir = "workspaces/"; bool blind_WP = false; TCut sidebands; RooWorkspace *wAll = new RooWorkspace("w_all","w_all"); RooDataSet* dataAll[NCAT]; RooDataSet* dataToWp[NCAT]; RooExtendPdf* bkg_fitPdf[NCAT]; for(unsigned int category=0; category < NCAT; category++){ if (category%3==0) sidebands = TCut("(m3m < 1.75 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.80)"); else if (category%3==1) sidebands = TCut("(m3m < 1.74 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.82)"); else if (category%3==2) sidebands = TCut("(m3m < 1.73 && m3m > 1.62) || (m3m < 2.0 && m3m > 1.83)"); dataAll[category] = (RooDataSet*) w->data(TString::Format("Bkg_%s",cat_names.at(category).c_str())); //blind data if(blind_WP) dataToWp[category] = (RooDataSet*)dataAll[category]->reduce(sidebands); else dataToWp[category] = (RooDataSet*)dataAll[category]->reduce("m3m > 1.62 && m3m < 2.0"); wAll->import(*dataToWp[category],Rename(TString::Format("data_obs_%s",cat_names.at(category).c_str()))); if(!discpf){ wAll->import(*w->pdf(TString::Format("t3m_bkg_expo_"+type+"_"+Run+"_%s",cat_names.at(category).c_str()))); wAll->import(*w->var(TString::Format("t3m_bkg_expo_"+type+"_"+Run+"_%s_norm",cat_names.at(category).c_str()))); }else{ wAll->import(*w->pdf(TString::Format("roomultipdf_"+Run+"_"+type+"_%s",cat_names.at(category).c_str() ))); wAll->import(*w->var(TString::Format("roomultipdf_"+Run+"_"+type+"_%s_norm",cat_names.at(category).c_str() ))); } } TString filename(wsDir+TString(fileBaseName)+".root"); wAll->writeToFile(filename); return; } void MakeDataCard(RooWorkspace* w, const Int_t NCAT, const char* fileBaseName, const char* fileBkgName, string configFile, std::vector<string> cat_names, TString type, TString Run, bool blind, bool dp){ TString cardDir = "datacards/"; TString wsDir = "../workspaces/"; RooDataSet* data[NCAT]; RooDataSet* signal[NCAT]; for (int c = 0; c < NCAT; ++c) { data[c] = (RooDataSet *) w->data(Form("Bkg_%s",cat_names.at(c).c_str())); // meaningless for now signal[c] = (RooDataSet*) w->data(Form("Sig_%s",cat_names.at(c).c_str())); TString filename(cardDir+TString(fileBaseName)+Form("_%s",cat_names.at(c).c_str() ) +".txt"); TString cat_name = cat_names.at(c).c_str(); ofstream outFile(filename); outFile << "# HF Tau to three mu" << endl; outFile << "imax 1" << endl; outFile << "jmax 1" << endl; outFile << "kmax *" << endl; outFile << "---------------" << endl; // outFile << Form("shapes data_obs %s ",cat_names.at(c).c_str())<< wsDir+TString(fileBkgName)+".root " << Form("w_all:bkg_fit_1par_%s",cat_names.at(c).c_str()) << endl; // outFile << Form("shapes bkg %s ", cat_names.at(c).c_str()) << wsDir+TString(fileBkgName)+".root " << Form("w_all:data_obs_%s",cat_names.at(c).c_str()) << endl; outFile << Form("shapes data_obs %s ",cat_names.at(c).c_str()) << wsDir+TString(fileBkgName)+".root " << Form("w_all:data_obs_%s",cat_names.at(c).c_str()) << endl; if(dp) outFile << Form("shapes bkg %s ", cat_names.at(c).c_str()) << wsDir+TString(fileBkgName)+".root " << Form("w_all:roomultipdf_"+Run+"_"+type+"_%s",cat_names.at(c).c_str()) << endl; // if(dp) outFile << Form("shapes bkg %s ", cat_names.at(c).c_str()) << wsDir+TString(fileBkgName)+".root " << Form("w_all:t3m_bkg_dp_%s",cat_names.at(c).c_str()) << endl; else outFile << Form("shapes bkg %s ", cat_names.at(c).c_str()) << wsDir+TString(fileBkgName)+".root " << Form("w_all:t3m_bkg_expo_"+type+"_"+Run+"_%s",cat_names.at(c).c_str()) << endl; outFile << Form("shapes sig %s ", cat_names.at(c).c_str()) << wsDir+TString(fileBaseName)+".root " << Form("w_all:SignalModel_%s",cat_names.at(c).c_str()) << endl; outFile << "---------------" << endl; outFile << Form("bin %s ", cat_names.at(c).c_str()) << endl; if(blind) outFile << "observation -1" << endl; else outFile << "observation " << data[c]->sumEntries() << endl; outFile << "------------------------------" << endl; outFile << Form("bin %s %s ",cat_names.at(c).c_str(),cat_names.at(c).c_str())<< endl; outFile << "process sig bkg " << endl; outFile << "process 0 1 " << endl; outFile << "rate " << " " << signal[c]->sumEntries()*signalScaler << " 1 " << endl; //outFile << "rate " << " " << signal[c]->sumEntries()*signalScaler << " " << data[c]->sumEntries() << endl; outFile << "--------------------------------" << endl; //Correlated uncertanties across categories and years //outFile << "lumi_13TeV lnN 1.027 - " << endl; outFile << "ySig_dstn lnN 1.03 - " << endl; //unc. on BR(Ds->taunu) outFile << "ySig_dsmmp lnN 1.08 - " << endl; //unc. on BR(Ds->phi(mumu)pi) outFile << "ySig_bds lnN 1.05 - " << endl; //unc. on BR(B->D+X) outFile << "ySig_bt lnN 1.03 - " << endl; //unc. on BR(B->tau+X) outFile << "ySig_dscal lnN 1.03 - " << endl; //unc. on scaling Ds to include D+ outFile << "ySig_bscal lnN 1.04 - " << endl; //unc. on scaling B0 and B+ to include Bs //Unc on BDT cut efficiency correlated across categories and years //Value changes depending on BDT subcategory and year (e.g. A1, A2, A3 are different, A1, B1, C1 are the same) if (Run.Contains("2018")){ if (cat_name.Contains("1")) outFile << "UncBDTCut lnN 1.15 - " << endl; //unc. on BDT selection if (cat_name.Contains("2")) outFile << "UncBDTCut lnN 1.07 - " << endl; //unc. on BDT selection if (cat_name.Contains("3")) outFile << "UncBDTCut lnN 1.00 - " << endl; //unc. on BDT selection } if (Run.Contains("2017")){ if (cat_name.Contains("1")) outFile << "UncBDTCut lnN 1.20 - " << endl; //unc. on BDT selection if (cat_name.Contains("2")) outFile << "UncBDTCut lnN 1.05 - " << endl; //unc. on BDT selection if (cat_name.Contains("3")) outFile << "UncBDTCut lnN 1.00 - " << endl; //unc. on BDT selection } //Uncorrelated uncertanties across years if (Run.Contains("2018")){ outFile << "DsNorm_18 lnN 1.04 - " << endl; // normalisation factor computed on control channel outFile << "fUnc_18 lnN 1.02 - " << endl; // B/D ratio outFile << "UncHLT_18 lnN 1.05 - " << endl; // uncertanty on 2018 HLT outFile << "UncL1_18 lnN 1.02 - " << endl; // events triggered by TripleMu outFile << "UncRatioAcc_18 lnN 1.01 - " << endl; //unc. on 3mu/2mu ratio acceptance outFile << "UncPionEff_18 lnN 1.021 - " << endl; //unc. on pion reconstruction efficiency //Uncorrelated uncertanties across categories if(type=="threeGlobal"){ outFile << "WNorm_18_3glb lnN 1.05 - " << endl; // 100% unc. on 5% additional W yield outFile << "UncMuonEff_18_3glb lnN 1.016 - " << endl; //GlobalMu ID tag&probe outFile << "UncMVAshape_18_3glb lnN 1.06 - " <<endl; //MVAglb correction }else{ outFile << "UncMuonEff_18_2glbtk lnN 1.08 - " << endl; //TrackerNotGlobal ID tag&probe outFile << "UncMVAshape_18_2glbtk lnN 1.04 - " <<endl; //MVAtk correction } } if (Run.Contains("2017")){ outFile << "DsNorm_17 lnN 1.062 - " <<endl; //normalisation factor computed on control channel outFile << "fUnc_17 lnN 1.02 - " <<endl; //B/D ratio outFile << "UncL1_17 lnN 1.05 - " <<endl; //events triggered by TripleMu outFile << "UncRatioAcc_17 lnN 1.01 - " <<endl; //unc. on 3mu/2mu ratio acceptance outFile << "UncPionEff_17 lnN 1.022 - " << endl; //unc. on pion reconstruction efficiency //Uncorrelated uncertanties across categories if(type=="threeGlobal"){ outFile << "WNorm_17_3glb lnN 1.03 - " << endl; // 100% unc. on 5% additional W yield outFile << "UncMuonEff_17_3glb lnN 1.015 - " << endl; //GlobalMu ID tag&probe outFile << "UncMVAshape_17_3glb lnN 1.03 - " <<endl; //MVAglb correction }else{ outFile << "UncMuonEff_17_2glbtk lnN 1.04 - " << endl; //TrackerNotGlobal ID tag&probe outFile << "UncMVAshape_17_2glbtk lnN 1.04 - " <<endl; //MVAtk correction } } //outFile << Form("norm_"+type+"_"+Run+"_%s rateParam %s bkg 1.", cat_names.at(c).c_str(), cat_names.at(c).c_str()) << endl; if(dp) { outFile << Form("roomultipdf_cat_"+Run+"_"+type+"_%s discrete", cat_names.at(c).c_str()) << endl; outFile << Form("roomultipdf_cat_"+Run+"_"+type+"_%s_norm rateParam %s bkg 1. [0.99,1.01]", cat_names.at(c).c_str(), cat_names.at(c).c_str()) << endl; outFile << Form("roomultipdf_cat_"+Run+"_"+type+"_%s_norm flatParam", cat_names.at(c).c_str()) << endl; } else { outFile << Form("bkg_exp_slope_"+type+"_"+Run+"_%s flatParam", cat_names.at(c).c_str()) << endl; outFile << Form("t3m_bkg_expo_"+type+"_"+Run+"_%s_norm rateParam %s bkg 1. [0.99,1.01]", cat_names.at(c).c_str(), cat_names.at(c).c_str()) << endl; outFile << Form("t3m_bkg_expo_"+type+"_"+Run+"_%s_norm flatParam", cat_names.at(c).c_str()) << endl; } outFile << "UncMean param 0.0 1.0 " << endl; outFile << "UncSigma param 0.0 1.0 " << endl; outFile.close(); cout << "Write data card in: " << filename << " file" << endl; } return; } void SetConstantParams(const RooArgSet* params) { TIterator* iter(params->createIterator()); for (TObject *a = iter->Next(); a != 0; a = iter->Next()) { RooRealVar *rrv = dynamic_cast<RooRealVar *>(a); if (rrv) { rrv->setConstant(true); std::cout << " " << rrv->GetName(); } } } void tokenize(std::string const &str, const char delim, std::vector<std::string> &out) { size_t start; size_t end = 0; while ((start = str.find_first_not_of(delim, end)) != std::string::npos) { end = str.find(delim, start); out.push_back(str.substr(start, end - start)); } }
class Solution { public: int totalNQueens(int n) { vector<int> colNumber(n,-1); int ans = 0; dfs(0,n,ans,colNumber); return ans; } void dfs(int cur,int n,int &ans,vector<int> &colNumber){ if(cur == n){ ans++; return; } for(int i=0; i<n; ++i){ bool flag = true; colNumber[cur] = i; for(int j=0; j<cur; ++j){ if(colNumber[j] == colNumber[cur] || colNumber[j]+j == colNumber[cur]+cur || colNumber[j]-j == colNumber[cur]-cur){ flag = false; break; } } if(flag == true) dfs(cur+1,n,ans,colNumber); } } };
// Example 2_1 : Built-in types, numeric limits. // Created by Oleksiy Grechnyev 2017 #include <iostream> #include <limits> // <iomanip> has std::setw(), std::setfill() for formatting output #include <iomanip> int main(int argc, char **argv){ using namespace std; // Demonstrate the danger of mixing signed and unsigned numbers // I use the block, so that names a, b do not leak { cout << "Adding int and unsigned :" << endl; int a = -10; unsigned int b = 1; cout << " int a = -10; unsigned int b = 1;" << endl; cout << "a + b = " << a + b << endl << endl; } { // Numeric limits cout << "Numeric limits :" << endl; cout << "long long :" << endl; // Or the old, pre-C++ 11 syntax : // typedef long long MyType; using MyType = long long; // You can try different types here cout << boolalpha; // Write bool as true/false cout << "sizeof(MyType) = " << sizeof(MyType) << endl; cout << "is_signed = " << numeric_limits<MyType>::is_signed << endl; cout << "is_integer = " << numeric_limits<MyType>::is_integer << endl; cout << "is_exact = " << numeric_limits<MyType>::is_exact << endl; cout << "has_infinity = " << numeric_limits<MyType>::has_infinity << endl; cout << "has_quiet_NaN = " << numeric_limits<MyType>::has_quiet_NaN << endl; cout << "digits = " << numeric_limits<MyType>::digits << endl; cout << "digits10 = " << numeric_limits<MyType>::digits10 << endl; cout << "lowest() = " << numeric_limits<MyType>::lowest() << endl; cout << "min() = " << numeric_limits<MyType>::min() << endl; cout << "max() = " << numeric_limits<MyType>::max() << endl; } { // Let's try the same for long double cout << endl << "long double :" << endl; // I can re-use MyTtype because of blocks using MyType = long double; cout << "sizeof(MyType) = " << sizeof(MyType) << endl; cout << "is_signed = " << numeric_limits<MyType>::is_signed << endl; cout << "is_integer = " << numeric_limits<MyType>::is_integer << endl; cout << "is_exact = " << numeric_limits<MyType>::is_exact << endl; cout << "has_infinity = " << numeric_limits<MyType>::has_infinity << endl; cout << "has_quiet_NaN = " << numeric_limits<MyType>::has_quiet_NaN << endl; cout << "digits = " << numeric_limits<MyType>::digits << endl; cout << "digits10 = " << numeric_limits<MyType>::digits10 << endl; cout << "min_exponent = " << numeric_limits<MyType>::min_exponent << endl; cout << "max_exponent = " << numeric_limits<MyType>::max_exponent << endl; cout << "min_exponent10 = " << numeric_limits<MyType>::min_exponent10 << endl; cout << "max_exponent10 = " << numeric_limits<MyType>::max_exponent10 << endl; cout << "lowest() = " << numeric_limits<MyType>::lowest() << endl; cout << "min() = " << numeric_limits<MyType>::min() << endl; cout << "max() = " << numeric_limits<MyType>::max() << endl; cout << "epsilon() = " << numeric_limits<MyType>::epsilon() << endl; cout << "infinity() = " << numeric_limits<MyType>::infinity() << endl; cout << "quiet_NaN() = " << numeric_limits<MyType>::quiet_NaN() << endl; } // Other types, literals cout << endl << "Other types, literals :" << endl; // bool { cout << "bool :" << endl; cout << endl << "sizeof(bool) = " << sizeof(bool) << endl; bool b = 12; // 12 is considered true and changed to 1 cout << boolalpha << "b = " << b << endl; // Prints true cout << noboolalpha << "b = " << b << endl; // Prints 1, not 12 cout << "(int)b = " << (int)b << endl; // Prints 1, not 12 } // A small difference between 2 big doubles { cout << "Small difference between 2 big doubles :" << endl; double a = 1.0e15; double b = 1.0e15 + 0.1234; cout << endl << "b - a = " << b-a << endl; } // Literals { cout << "Literals :" << endl; cout << "1234 = " << 1234 << endl; // int cout << "4000000000u = " << 4000000000u << endl; // unsigned // Note the quotes to separate digits ! cout << "8'000'000'000ll = " << 8'000'000'000ll << endl; // long long cout << "8000000000ull = " << 8000000000ull << endl; // unsigned long long cout << "1.23e-4 = " << 1.23e-4 << endl; // double cout << "1.23e-4f = " << 1.23e-4f << endl; // float cout << "1.23e-4l = " << 1.23e-4l << endl; // long double cout << "'A' = " << 'A' << endl; // char cout << "\"Dina Meyer\" = " << "Dina Meyer" << endl; // const char [11] cout << "0xFF = " << 0xFF << endl; // int (HEX) cout << "0xFF = 0x" << hex << 0xFF << dec << endl; // hex print, dec to switch back to decimal !!! cout << "0xFF = 0x" << hex << setw(4) << setfill('0') << 0xFF << dec << endl; cout << dec; cout << "0100 = " << 0100 << endl; // int (OCTAL) cout << "0100 = 0" << oct << 0100 << dec << endl; // int (OCTAL) cout << "0b100 = " << 0b100 << endl; // int (BIN) } return 0; }
#include <Wire.h> #include "MAX30100_PulseOximeter.h" #include <Ticker.h> #include <MedianFilter.h> #include <IOXhop_FirebaseESP32.h> #include <WiFi.h> #define FIREBASE_HOST "seb01-465f5.firebaseio.com" #define FIREBASE_AUTH "pAAbm0SufQuio0OT0uxxhBXJYtCiggSBw0llqI0o" #define WIFI_SSID "Celular Mila" #define WIFI_PASSWORD "23456789" #define REPORTING_PERIOD_MS 100 #define AMOSTRAS 10 // PulseOximeter is the higher level interface to the sensor // it offers: // * beat detection reporting // * heart rate calculation // * SpO2 (oxidation level) calculation PulseOximeter pox; MedianFilter beatFilter(AMOSTRAS, 0); Ticker ticker; //Controle da aquisição volatile bool flag = false; // ================================================================ // === INTERRUPT DETECTION ROUTINE === // ================================================================ void reading(){ flag = true; //Serial.println(flag); } int vHeartBeat[AMOSTRAS]; int i = 0; void setupWifi(){ WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("connecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("connected: "); Serial.println(WiFi.localIP()); } void setupFirebase(){ Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); } void setup() { Serial.begin(115200); setupWifi(); setupFirebase(); Serial.print("Initializing pulse oximeter.."); // Initialize the PulseOximeter instance // Failures are generally due to an improper I2C wiring, missing power supply // or wrong target chip if (!pox.begin()) { Serial.println("FAILED"); for(;;); } else { Serial.println("SUCCESS"); } // The default current for the IR LED is 50mA and it could be changed // by uncommenting the following line. Check MAX30100_Registers.h for all the // available options. pox.setIRLedCurrent(MAX30100_LED_CURR_11MA); // Registra o ticker para ler de tempos em tempos ticker.attach_ms(REPORTING_PERIOD_MS, reading); } void loop() { // Make sure to call update as fast as possible pox.update(); // Asynchronously dump heart rate and oxidation levels to the serial // For both, a value of 0 means "invalid" if (flag) { beatFilter.in(pox.getHeartRate()); i++; if(i == AMOSTRAS) { i=0; Serial.println(beatFilter.out()); ticker.detach(); Firebase.pushInt("HeartBeat", beatFilter.out()); ticker.attach_ms(REPORTING_PERIOD_MS, reading); } flag = false; } } /* float filtroMedianaHeart(){ int j = 0; float aux; for(int i = 0; i < AMOSTRAS ; i++){ aux = vHeartBeat[i]; while(j < AMOSTRAS){ if(aux >= vHeartBeat[j]){ aux = vHeartBeat[j]; vHeartBeat[j] = aux; } j++; } j = i; vHeartBeat[i] = aux; Serial.println(vHeartBeat[i]); } return vHeartBeat[(AMOSTRAS)/2]; } */
#pragma once #include "stdafx.h" #include "Utils.h" #include "StructSettings.h" class SingleData { public: static SingleData* getInstance() { if (!instance) instance = new SingleData; return instance; } void addLabelToAdaptOnTheme(const QString& key, QLabel* label); void addButtoonToAdaptOnTheme(const QString& key, QPushButton* button); void addActionToAdaptOnTheme(const QString& key, QAction* label); void addLabelToAdaptOnFont(const double& multiplier, QLabel* label); void setColoredIcon(int themeIndex); void setFontOnLabels(QFont newFont); std::pair<QString, QPixmap> getCharacter(); QPixmap getPixmap(QString key); void deleteButtonOnAdress(QPushButton* button); QPixmap getPixMapOnActualTheme(QString key); void setIndexActualTheme(int indexTheme); int getThemeActuel(); private: int themeActuel; SingleData(); void loadPixmap(); void pushCharacter(const QString& addNom, const QString& pixMap); void pushPixmapToSoft(const QString& key, const QString& url, const int& addWidth, const int& addHeight); static SingleData* instance; std::vector<std::pair<QString, QPixmap>> listCharacter; std::map<QString, QPixmap> listSoftPixmap; std::vector<std::pair<QString, QLabel*>> listLabelToAdapt; std::vector<std::pair<QString, QPushButton*>> listButtonToAdapt; std::vector<std::pair<QString, QAction*>> listActionToAdapt; std::vector<std::pair<double, QLabel*>> listLabelToAdaptToFont; };
#pragma once #include <ionir/construct/inst.h> namespace ionir { class Pass; class Function; struct IcmpInstOpts : InstOpts { // TODO }; class IcmpInst : public Inst { public: explicit IcmpInst(const IcmpInstOpts &opts); void accept(Pass &visitor) override; }; }
#include<vector> #include<iostream> #include<cstdio> #include <cstring> #include <algorithm> using namespace std; int main(){ int num[10005]; int n; cin >> n; int temp; memset(num, 0, sizeof num); for (int i = 0; i < n; ++i) { cin >> temp; if (num[temp] == 0) { num[temp]++; } } for (int i = 0; i < 10000; ++i) { if (num[i]) { printf("%d ", i); } } }
#pragma once // CPYDlg 对话框 class CPYDlg : public CDialog { DECLARE_DYNAMIC(CPYDlg) public: CPYDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CPYDlg(); // 对话框数据 enum { IDD = IDD_DIALOG_PY }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: // 喷药指数文本内容 CString py_edit_content; afx_msg void OnBnClickedOk(); };
#define CATCH_CONFIG_MAIN #include "../external/catch2/catch.hpp" #include "../src/math/average.hpp" #include <vector> template <typename T> struct TestStruct { std::vector<T> arr; T actual; TestStruct(std::vector<T> arr, T actual) : arr(arr), actual(actual) { } }; TEST_CASE("Average Test", "<average>") { std::vector<TestStruct<int>> testVec { { {2, 6}, 4 }, { {2, 4, 6, 8}, 5 } }; for (auto&& var : testVec) { REQUIRE(Math::average(var.arr.begin(), var.arr.end()) == var.actual); } }
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); /* Prints what numbers in the cost vector add up to exactly the money input. Utilizes a binary search algorithm and hash table to reduce the time for finding the solution in large problems. The unsorted cost array is put into a C++ map (hash table), where the original order of the ice cream prices is saved as the value and the price as the key. To deal with repeated prices, the values of the map are integer vectors which allow for the containing of multiple integers for each price. Next the cost array is sorted so that we can utilize the binary search algorithm for finding two prices that add up to the 'money' input. Essentially, starting from the cheapest flavour we binary search all the flavours more expensive then that flavour for a matching price that adds up to exactly money. If one is not found, then the next most expensive flavour is chosen and the flavours that are more expensive then that flavour are binary searched. Once the two prices are found, the hash table is used to find the two lowest ID occurences of those prices. */ void whatFlavors(vector<int> cost, int money) { bool found = false; int id1, id2, left, right, mid, val, price1, price2; std::map<int, std::vector<int> > table; // Adding values to a table to save the IDs of their order. for (int i = 0; i < cost.size(); i++) { std::vector<int> a = {}; table.insert(std::pair<int,std::vector<int> >(cost[i], a)); } for (int x = 0; x < cost.size(); x++) { table[cost[x]].push_back(x); } // Now that the IDs are saved we sort the valeus in the cost vector. std::sort (cost.begin(), cost.end()); for (int j = 0; j < cost.size(); j ++) { if (found) { break; } left = j + 1; right = cost.size() - 1; mid = (left + right) / 2; val = money - cost[j]; while (left <= right) { mid = (left + right) / 2; if (cost[mid] == val) { price1 = cost[j]; price2 = cost[mid]; found = true; break; } else if (cost[mid] > val) { right = mid - 1; } else { left = mid + 1; } } } id1 = table[price1][0]; id2 = table[price2][0]; if (id1 == id2) { id2 = table[price2][1]; } if (id2 < id1) { std::swap(id1, id2); } std::cout << (id1 + 1) << " " << (id2 + 1) << "\n"; } int main() { int t; cin >> t; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int t_itr = 0; t_itr < t; t_itr++) { int money; cin >> money; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string cost_temp_temp; getline(cin, cost_temp_temp); vector<string> cost_temp = split_string(cost_temp_temp); vector<int> cost(n); for (int i = 0; i < n; i++) { int cost_item = stoi(cost_temp[i]); cost[i] = cost_item; } whatFlavors(cost, money); } return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
#pragma once #include <iberbar/Utility/Platform.h> namespace iberbar { template< typename T > class TSize2 { public: TSize2() throw(); TSize2( T w, T h ) throw(); TSize2( const T* p ) throw(); T Area() const; operator T* () throw(); operator const T* () const throw(); TSize2 operator*( int a ) const; TSize2 operator*=( int a ); TSize2 operator/( int a ) const; TSize2 operator/=( int a ); bool operator==( const TSize2& other ) const; bool operator!=( const TSize2& other ) const; T w; T h; }; typedef TSize2< int > CSize2i; typedef TSize2< float > CSize2f; template class __iberbarUtilityApi__ TSize2<int>; template class __iberbarUtilityApi__ TSize2<float>; template< typename T > TSize2<T>::TSize2() throw() : w(0), h(0) { } template< typename T > TSize2<T>::TSize2( T w, T h ) throw() : w( w ), h( h ) { } template< typename T > TSize2<T>::TSize2( const T* p ) throw() : w( p[0] ), h( p[1] ) { } template< typename T > TSize2<T>::operator T* () throw() { return &w; } template< typename T > TSize2<T>::operator const T* () const throw() { return &w; } template< typename T > inline T TSize2<T>::Area() const { return w * h; } template< typename T > inline TSize2<T> TSize2<T>::operator*( int a ) const { return TSize2<T>( w * a, h * a ); } template< typename T > inline TSize2<T> TSize2<T>::operator*=( int a ) { return TSize2<T>( w * a, h * a ); } template< typename T > inline TSize2<T> TSize2<T>::operator/( int a ) const { return TSize2<T>( w / a, h / a ); } template< typename T > inline TSize2<T> TSize2<T>::operator/=( int a ) { return TSize2<T>( w / a, h / a ); } template< typename T > inline bool TSize2<T>::operator==( const TSize2<T>& other ) const { return (w == other.w && h == other.h); } template< typename T > inline bool TSize2<T>::operator!=( const TSize2<T>& other ) const { return (w != other.w || h != other.h); } }
#include <specex_unbls.h> #include <specex_mask.h> #include <specex_psf.h> #include <specex_image_data.h> specex::Mask::Mask() { } void specex::Mask::ApplyMaskToImage(specex::image_data& img, const specex::PSF& psf, const double& value) const{ int hsize = 5; for(size_t m=0;m<WaveIntervals.size();m++) { const Interval& inter=WaveIntervals[m]; for(map<int,specex::Trace>::const_iterator it = psf.FiberTraces.begin(); it!=psf.FiberTraces.end(); it++) { int i1 = int(it->second.X_vs_W.Value(inter.min)); int j1 = int(it->second.Y_vs_W.Value(inter.min)); int i2 = int(it->second.X_vs_W.Value(inter.max)); int j2 = int(it->second.Y_vs_W.Value(inter.max)); int imin = max(0,min(i1,i2)-hsize); int imax = min(int(img.Nx())-1,max(i1,i2)+hsize); int jmin = max(0,min(j1,j2)); int jmax = min(int(img.Ny())-1,max(j1,j2)); //if(it==PSF.FiberTraces.begin()) { //cout << "DEBUG specex::PSF_Fitter::FitSeveralSpots mask #" << m << " fiber #" << it->first << " : region [" << imin << ":" << imax << "," << jmin << ":" << jmax << "] for first fiber" << endl; for(int j=jmin;j<=jmax;j++) for(int i=imin;i<=imax;i++) img(i,j)=value; } } }
// Created on: 1995-09-01 // Created by: Yves FRICAUD // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepAlgo_FaceRestrictor_HeaderFile #define _BRepAlgo_FaceRestrictor_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <TopoDS_Face.hxx> #include <TopTools_DataMapOfShapeListOfShape.hxx> class TopoDS_Wire; //! Builds all the faces limited with a set of non //! jointing and planars wires. if //! <ControlOrientation> is false The Wires must have //! correct orientations. Sinon orientation des wires //! de telle sorte que les faces ne soient pas infinies //! et qu'elles soient disjointes. class BRepAlgo_FaceRestrictor { public: DEFINE_STANDARD_ALLOC Standard_EXPORT BRepAlgo_FaceRestrictor(); //! the surface of <F> will be the surface of each new //! faces built. //! <Proj> is used to update pcurves on edges if necessary. //! See Add(). Standard_EXPORT void Init (const TopoDS_Face& F, const Standard_Boolean Proj = Standard_False, const Standard_Boolean ControlOrientation = Standard_False); //! Add the wire <W> to the set of wires. //! //! Warning: //! The Wires must be closed. //! //! The edges of <W> can be modified if they have not pcurves //! on the surface <S> of <F>. In this case //! if <Proj> is false the first pcurve of the edge //! is positionned on <S>. //! if <Proj> is True ,the Pcurve On <S> is the //! projection of the curve 3d on <F>. Standard_EXPORT void Add (TopoDS_Wire& W); //! Removes all the Wires Standard_EXPORT void Clear(); //! Evaluate all the faces limited by the set of Wires. Standard_EXPORT void Perform(); Standard_EXPORT Standard_Boolean IsDone() const; Standard_EXPORT Standard_Boolean More() const; Standard_EXPORT void Next(); Standard_EXPORT TopoDS_Face Current() const; protected: private: //! Evaluate all the faces limited by the set of Wires. Standard_EXPORT void PerformWithCorrection(); Standard_Boolean myDone; Standard_Boolean modeProj; TopoDS_Face myFace; TopTools_ListOfShape wires; TopTools_ListOfShape faces; Standard_Boolean myCorrection; TopTools_DataMapOfShapeListOfShape keyIsIn; TopTools_DataMapOfShapeListOfShape keyContains; }; #endif // _BRepAlgo_FaceRestrictor_HeaderFile
#ifndef STANDARDDEVIATION_H #define STANDARDDEVIATION_H #include "../Filters/Filter.h" class StandardDeviation : public Filter { Q_OBJECT public: StandardDeviation(QObject *parent = 0); static QString GetFilterName() {return "Standard Deviation";} void run(); private: double numStdDevs; void runCloud(); void runGrid(); public slots: void setNumStandardDeviations(double stdDev); }; #endif // STANDARDDEVIATION_H
// // imcases.cpp // AutoCaller // // Created by Micheal Chen on 2017/7/26. // // #include "imcases.hpp" #include "imservice.hpp" #include "YouMeHttpRequest.hpp" #include <sstream> #include "audio/include/SimpleAudioEngine.h" using namespace std; IMTestController::IMTestController() { m_config = new Conifg(); m_config->timeout = 10; m_robotUser = ::getRandUserName(); } IMTestController::~IMTestController() { } void IMTestController::login_and_logout() { srand((unsigned int)time(NULL)); //const XCHAR* room_id = ROOM_ID; //用局部变量 //const XCHAR* target_id = ROBOT_TARHET_ID; t1 = std::thread([ this]() { YIMManager *im = YIMManager::CreateInstance(); while (true) { int r = rand(); if (r % 100 == 1) sleep(1); if (r % 2 == 1) { im->Login(m_robotUser.c_str(), __XT("12345"), __XT("")); } else if (r % 2 == 0) { im->Logout(); } else if (r % 2 == 0) { // im->GetChatRoomManager()->JoinChatRoom("2019889"); } else if (r % 7 == 0) { // im->GetChatRoomManager()->LeaveChatRoom("2019889"); } else if (r % 10 == 7) { //im->GetMessageManager()->SendTextMessage("AutoRoboter", ChatType_RoomChat, __XT("Brown ceshi"), nullptr); } else if (r % 10 == 8) { // im->GetMessageManager()->SendTextMessage("AutoRoboter", ChatType_PrivateChat, __XT("Brown ctest test"), nullptr); } else { // } } }); t1.join(); } void IMTestController::runTests() { //每次开始的时候注册回调函数 YIMManager *im = YIMManager::CreateInstance(); im->SetLoginCallback(this); im->SetMessageCallback(this); im->SetChatRoomCallback(this); im->SetNoticeCallback(this); im->SetContactCallback(this); im->SetLocationCallback(this); im->SetAudioPlayCallback(this); im->SetDownloadCallback(this); IM_SetMode(2); //加入频道 { unique_lock<std::mutex> lk(m_mutex); YIMManager *im = YIMManager::CreateInstance(); YIMErrorcode code1 = im->GetChatRoomManager()->JoinChatRoom(__XT("")); EXPECT_EQ("加入房间:房间名为空", "JoinChatRoom", code1, YIMErrorcode_ParamInvalid); YIMErrorcode code = im->GetChatRoomManager()->JoinChatRoom(ROOM_ID); EXPECT_EQ("加入房间", "JoinChatRoom", code, YIMErrorcode_Success); m_cv.wait_for(lk, std::chrono::seconds(10)); } { YIMManager *im = YIMManager::CreateInstance(); YIMErrorcode code = im->GetChatRoomManager()->JoinChatRoom(ROOM_ID); int i = 0; const XCHAR *roomID = __XT("2019899"); while (i < 50) { XUINT64 reqNo; XString message_text = XString(PROTOCOL_TO_PREFIX) + XString(__XT("向机器人发出一条私聊:你好")); im->GetMessageManager()->SendTextMessage(ROBOT_TARHET_ID, ChatType_PrivateChat, message_text.c_str(), &reqNo); ++i; } i = 0; while ( i < 100) { XUINT64 reqNo; XString message_text = XString(PROTOCOL_TO_PREFIX) + XString(__XT("向机器人发出一条世界频道消息: 你好")); im->GetMessageManager()->SendTextMessage(ROOM_ID, ChatType_RoomChat, message_text.c_str(), &reqNo); ++i; } } login_and_logout(); } void IMTestController::sendemail() { YIMManager *im = YIMManager::CreateInstance(); cocos2d::log("IM Finished! OK"); actionLeaveChatRoom(); actionLogout(); endfile(); //发邮件将本地的 报告递出去 std::string extentsion = cocos2d::StringUtils::format("IM_version_%d", im->GetSDKVersion()); YouMeHttpRequest::sendFile("http://106.75.7.162:8999/sendreport", ::filename(), extentsion.c_str()); } void IMTestController::actionSendVoiceSpeech() { std::this_thread::sleep_for(std::chrono::seconds(10)); //录音,返回下载链接, 不转文字识别 XUINT64 reqNo; YIMManager *im = YIMManager::CreateInstance(); YIMErrorcode code = im->GetMessageManager()->StartAudioSpeech(&reqNo, false); EXPECT_EQ("录音,返回下载链接", "StartAudioSpeech", code, YIMErrorcode_Success); if (code == YIMErrorcode_Success) { CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("nekomimi.mp3"); std::this_thread::sleep_for(std::chrono::seconds(15)); CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic(); YIMErrorcode code1 = im->GetMessageManager()->StopAudioSpeech(); EXPECT_EQ("开始录音", "StartAudioSpeech", code1, YIMErrorcode_Success); //std::cv_status s = m_cv.wait_for(lk, std::chrono::seconds(10)); //EXPECT_NO_TIMEOUT("录音,返回下载链接", s); } } void IMTestController::actionGetNearbyObjects() { YIMManager *im = YIMManager::CreateInstance(); YIMErrorcode code = im->GetLocationManager()->GetNearbyObjects(2, __XT("GD")); EXPECT_EQ("获取附近的人", "GetNearbyObjects", code, YIMErrorcode_Success); } void IMTestController::voicesetting() { YIMManager *im = YIMManager::CreateInstance(); XString path = im->GetAudioCachePath(); cocos2d::log("%s", XStringToUTF8(path).c_str()); std::string s = cocos2d::StringUtils::format("voicesetting is %s", XStringToUTF8(path).c_str()); write_a_message(s); } void IMTestController::actionLeaveChatRoom() { unique_lock<std::mutex> lk(m_mutex); YIMManager *im = YIMManager::CreateInstance(); YIMErrorcode code = im->GetChatRoomManager()->LeaveChatRoom(ROOM_ID); EXPECT_EQ("退出房间成功", "LeaveChatRoom", code, YIMErrorcode_Success); std::cv_status s = m_cv.wait_for(lk, std::chrono::seconds(10)); EXPECT_NO_TIMEOUT("退出房间", s); } void IMTestController::OnLogout(YIMErrorcode errorcode) { EXPECT_EQ("退出登录", "Logout回调", errorcode, YIMErrorcode_Success); m_cv.notify_one(); } void IMTestController::actionLogout() { unique_lock<std::mutex> lk(m_mutex); YIMManager *im = YIMManager::CreateInstance(); YIMErrorcode code = im->Logout(); EXPECT_EQ("登出", "Logout", code, YIMErrorcode_Success); std::cv_status s = m_cv.wait_for(lk, std::chrono::seconds(10)); EXPECT_NO_TIMEOUT("退出登录", s); } //lbs void IMTestController::actionGetCurrentLocation() { //获取位置信息 YIMManager *im = YIMManager::CreateInstance(); YIMErrorcode code = im->GetLocationManager()->GetCurrentLocation(); EXPECT_EQ("获取当前位置", "GetCurrentLocation", code, YIMErrorcode_Success); } //Joinroom void IMTestController::OnJoinChatRoom(YIMErrorcode errorcode, const XString &chatRoomID) { //stringstream ss; EXPECT_EQ("加入房间回调", "OnJoinChatRoom", errorcode, YIMErrorcode_Success); //送礼物 //const char *exparam = "{\"nickname\":\"David\",\"server_area\":\"Hong Kong\",\"location\":\"Shang hai\",\"score\":\"1000\",\"level\":\"20\",\"vip_level\":\"1\",\"extra\":\"nothing\"}"; //YIMErrorcode errcode1 = IMService::getInstance()->getYMInst()->GetMessageManager()->SendGift(ZHUBO_ID, UCHATROOMID, 1000, 1, exparam, &reqNo1); m_cv.notify_one(); } //leave room void IMTestController::OnLeaveChatRoom(YIMErrorcode errorcode, const XString& chatRoomID) { std::string casename1 = cocos2d::StringUtils::format("LeaveChatRoomcb: %s", XStringToUTF8(chatRoomID).c_str()); EXPECT_EQ("离开房间回调", "OnLeaveChatRoom回调", errorcode, YIMErrorcode_Success); m_cv.notify_one(); } void IMTestController::OnLogin(YIMErrorcode errorcode, const XString &userID) { EXPECT_EQ("登录成功", "登录成功回调", errorcode, YIMErrorcode_Success); m_cv.notify_one(); } void IMTestController::OnSendMessageStatus(XUINT64 requestID, YIMErrorcode errorcode , bool isForbidRoom, int reasonType, XUINT64 forbidEndTime) { EXPECT_EQ("发送文本消息状态回调", "OnSendMessageStatus", errorcode, YIMErrorcode_Success); //EXPECT_EQ("", "OnSendMessageStatus", requestID > 0, true, // cocos2d::StringUtils::format("seq %lld", requestID)); cocos2d::log("On send message status %lld", requestID); } void IMTestController::requestEnterRoom() { std::string body1("{\"UserID\": \"Robot001\", \"ChannelID\":\"2011234\"}"); YouMeHttpRequest::request("query_im_enter_channel", body1); std::string body2("{\"UserID\": \"Robot002\", \"ChannelID\":\"2011234\"}"); YouMeHttpRequest::request("query_im_enter_channel", body2); std::string body3("{\"UserID\": \"Robot003\", \"ChannelID\":\"2011234\"}"); YouMeHttpRequest::request("query_im_enter_channel", body3); } void IMTestController::requestLeaveRoom() { std::string body_string_1 = cocos2d::StringUtils::format("{\"UserID\": \"Robot001\", \"ChannelID\":\"%s\"}", ROOM_ID); std::string body_string_2 = cocos2d::StringUtils::format("{\"UserID\": \"Robot002\", \"ChannelID\":\"%s\"}", ROOM_ID); std::string body_string_3 = cocos2d::StringUtils::format("{\"UserID\": \"Robot003\", \"ChannelID\":\"%s\"}", ROOM_ID); YouMeHttpRequest::request("query_im_leave_channel", body_string_1); YouMeHttpRequest::request("query_im_leave_channel", body_string_2); YouMeHttpRequest::request("query_im_leave_channel", body_string_3); } void IMTestController::requestNotice() { std::string body1 = cocos2d::StringUtils::format("{ \ \"Notice\": \ { \ \"ChannelID\": \"%s\", \ \"NoticeType\": 2, \ \"LoopType\": 1, \ \"SendDate\": \"20170729\", \ \"SendStartTime\": \"15:00:00\", \ \"SendTimes\": 3, \ \"SendInterval\": 30, \ \"Title\": \"title12345\", \ \"Content\": \"content12345\", \ \"LinkKeyWords\": \"keywords12345\", \ \"LinkAddr\": \"https://www.youme.im\", \ \"EnableStatus\": 2, \ \"Creator\": \"test\" \ }}", ROOM_ID ); YouMeHttpRequest::request("add_notice", body1); } void IMTestController::requestCancelNotice(XUINT64 id) { char strbuffer[128]; sprintf(strbuffer, "{\"Notice\": [{ \"NoticeID\": %lld }]}", id); std::string body1(strbuffer); YouMeHttpRequest::request("delete_notice", strbuffer); } void IMTestController::OnUserLeaveChatRoom(const XString &chatRoomID, const XString &userID) { EXPECT_EQ("用户离开房间回调", "OnUserLeaveChatRoom", XStringToLocal(chatRoomID).c_str(), XStringToLocal(XString(ROOM_ID)).c_str(), cocos2d::StringUtils::format("User %s leaved", userID.c_str())); } void IMTestController::OnUserJoinChatRoom(const XString &chatRoomID, const XString &userID) { EXPECT_EQ("有新用户加入房间", "OnUserJoinChatRoom", chatRoomID.c_str(), ROOM_ID); m_cv.notify_one(); } void IMTestController::OnTranslateTextComplete(YIMErrorcode errorcode, unsigned int requestID, const XString &text, LanguageCode srcLangCode, LanguageCode destLangCode) { EXPECT_EQ("文本翻译完成", "TranslateText", errorcode, YIMErrorcode_Success); //EXPECT_EQ("TranslateText reqNo:cb", requestID, (unsigned int)reqNo); m_cv.notify_one(); } //Recv Message 收消息 //#include "cocos2d.h" #include "YouMeHttpRequest.hpp" void IMTestController::requestSendMsg1() { //std::this_thread::sleep_for(std::chrono::seconds(1)); //第一条 unique_lock<std::mutex> lk(m_mutex); char buffer1[1024]; long timestamp = getCurrentTime(); sprintf(buffer1, "{\"MsgSeq\": \"%ld\",\"ChatType\": 2, \"SendID\": \"Robot\",\"RecvID\" : \"%s\",\"Content\" : \"\\\"家族成员肩:负家族使命晋升为副族长身体是阿斯顿\\\"\"}", timestamp, XStringToLocal(XString(ROOM_ID)).c_str()); YouMeHttpRequest::request("query_im_send_msg", buffer1); std::cv_status s = m_cv.wait_for(lk, std::chrono::seconds(10)); EXPECT_EQ("回调超时检查", "Timeout check", int(s), int(std::cv_status::timeout)); //std::this_thread::sleep_for(std::chrono::milliseconds(50)); //第二条 私聊 lk.unlock(); unique_lock<std::mutex> lk2(m_mutex); char buffer2[1024]; long t = getCurrentTime(); sprintf(buffer2, "{\"MsgSeq\": \"%ld\",\"ChatType\": 1, \"SendID\": \"Robot\",\"RecvID\" : \"%s\",\"Content\" : \"明天还有明天的事,这里是毛泽东的故乡\"}", t, XStringToLocal(XString(m_robotUser)).c_str()); YouMeHttpRequest::request("query_im_send_msg", std::string(buffer2)); std::cv_status s2 = m_cv.wait_for(lk2, std::chrono::seconds(10)); EXPECT_EQ("回调超时检查", "Timeout check", int(s2), int(std::cv_status::timeout)); } void IMTestController::requestSendMsg2() { YIMManager *im = YIMManager::CreateInstance(); int level; XString text = im->FilterKeyword(__XT("出售灵魂和肉体"), &level); cocos2d::log("%s", XStringToLocal(text).c_str()); char buffer[1024]; long t = getCurrentTime(); sprintf(buffer, "{\"MsgSeq\": \"%ld\",\"ChatType\": 2, \"SendID\": \"Robot\",\"RecvID\" : \"%s\",\"Content\" : \"%s\"}", t, XStringToLocal(XString(m_robotUser)).c_str(), XStringToLocal(text).c_str()); YouMeHttpRequest::request("query_im_send_msg", std::string(buffer)); } void IMTestController::requestSendMsg3() { char buffer[1024]; long t = getCurrentTime(); XString text = __XT("Tr:今日では、ゴミをクリーンアップするために、非常に満足していません"); sprintf(buffer, "{\"MsgSeq\": \"%ld\",\"ChatType\": 2, \"SendID\": \"Robot\",\"RecvID\" : \"%s\",\"Content\" : \"%s\"}", t, XStringToLocal(XString(m_robotUser)).c_str(), XStringToLocal(text).c_str()); YouMeHttpRequest::request("query_im_send_msg", std::string(buffer)); } void IMTestController::actionSendVoiceMsgChat() { //std::this_thread::sleep_for(std::chrono::seconds(10)); YIMManager *im = YIMManager::CreateInstance(); XUINT64 reqNo2; std::this_thread::sleep_for(std::chrono::seconds(2)); YIMErrorcode errcode2 = im->GetMessageManager()->SendOnlyAudioMessage(ROBOT_TARHET_ID, YIMChatType::ChatType_PrivateChat, &reqNo2); EXPECT_EQ("录制带翻译的语音,私聊", "SendOnlyAudioMessage", errcode2, YIMErrorcode_Success); if (errcode2 == YIMErrorcode_Success) { CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("nekomimi.mp3"); std::this_thread::sleep_for(std::chrono::seconds(3)); unique_lock<std::mutex> lk(m_mutex); YIMErrorcode errcode21 = im->GetMessageManager()->StopAudioMessage(__XT("{\"test\": \"thanks very much\"}")); CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic(); EXPECT_EQ("停止录音并发送,带翻译,私聊", "StopAudioMessage", errcode21, YIMErrorcode_Success); //std::cv_status s = m_cv.wait_for(lk, std::chrono::seconds(10)); //EXPECT_NO_TIMEOUT("发送带翻译的语音", s); } cocos2d::log("errocode is Failed: %d", errcode2); } void IMTestController::actionSendVoiceMsgPrivate() { std::this_thread::sleep_for(std::chrono::seconds(10)); YIMManager *im = YIMManager::CreateInstance(); XUINT64 reqNo; YIMErrorcode code2 = im->GetMessageManager()->SendOnlyAudioMessage(ROOM_ID, ChatType_RoomChat, &reqNo); EXPECT_EQ("开始录音,私聊频道", "SendOnlyAudioMessage", code2, YIMErrorcode_Success); std::this_thread::sleep_for(std::chrono::seconds(5)); YIMErrorcode code3 = im->GetMessageManager()->StopAudioMessage(__XT("")); EXPECT_EQ("结束录音并发送", "StopAudioMessage", code3, YIMErrorcode_Success); } void IMTestController::actionPlayAudio() { YIMManager *im = YIMManager::CreateInstance(); XString pathName = im->GetAudioCachePath(); unique_lock<std::mutex> lk(m_mutex); YIMErrorcode errcode1 = im->StartPlayAudio(pathName.c_str()); EXPECT_EQ("播放语音", "[PlayAudio][call]", errcode1, YIMErrorcode_Success); std::this_thread::sleep_for(std::chrono::seconds(1)); EXPECT_EQ("检查是否在播放中", "Check is playing", true, im->IsPlaying()); im->SetVolume(0.5); std::this_thread::sleep_for(std::chrono::seconds(2)); im->SetVolume(0.3); m_cv.wait_for(lk, std::chrono::seconds(10)); YIMErrorcode errcode2 = im->StopPlayAudio(); EXPECT_EQ("停止语音播放", "StopAudio", errcode2, YIMErrorcode_Success); } void IMTestController::OnPlayCompletion(YIMErrorcode errorcode, const XString &path) { EXPECT_EQ("语音播放完成", "Play completion", errorcode, YIMErrorcode_Success); cocos2d::log("Played path : %s", XStringToLocal(path).c_str()); m_cv.notify_one(); } void IMTestController::OnRecvNotice(YIMNotice *notice) { requestCancelNotice(notice->GetNoticeID()); EXPECT_EQ_STR("收到公告消息", "RecvNotice: call", XStringToLocal(XString(notice->GetChannelID())).c_str(), XStringToLocal(XString(ROOM_ID)).c_str(), cocos2d::StringUtils::format("Channel:%s", notice->GetChannelID())); //EXPECT_EQ("", "RecvNotice: reqNo", notice->GetNoticeID() != 0, true); //其他参数校验 requestCancelNotice(notice->GetNoticeID()); m_cv.notify_one(); } void IMTestController::OnCancelNotice(XUINT64 noticeID, const XString &channelID) { EXPECT_EQ_STR("取消公告回调", "OnCancelNotice", XStringToLocal(channelID).c_str(), "2011234", cocos2d::StringUtils::format("Channel:%s", XStringToLocal(channelID).c_str())); //EXPECT_EQ("取消公告回调", "OnCancelNotice", noticeID != 0, true); m_cv.notify_one(); } void IMTestController::OnGetRecentContacts(YIMErrorcode errorcode, std::list<XString> &contactList) { EXPECT_EQ("获取最近联系人成功", "GetRecentContacts", errorcode, YIMErrorcode_Success); for (auto it = contactList.begin(); it != contactList.end(); ++it) { cocos2d::log("%s", (*it).c_str()); EXPECT_EQ("", "GetRecentContacts:contacts", (*it).empty(), false); } m_cv.notify_one(); } void IMTestController::OnGetRoomMemberCount(YIMErrorcode errorcode, const XString &chatRoomID, unsigned int count) { EXPECT_EQ("获取房间成员数量回调", "OnGetRoomMemberCount", errorcode, YIMErrorcode_Success); cocos2d::log("Room number is %d", count); std::string comment = cocos2d::StringUtils::format("Number is %d", count); EXPECT_EQ("房间人数数量至少为1", "OnGetRoomMemberCount", count >= 1, true, comment); m_cv.notify_one(); } void IMTestController::OnQueryHistoryMessage(YIMErrorcode errorcode, const XString &targetID, int remain, std::list<std::shared_ptr<IYIMMessage> > messageList) { EXPECT_EQ("查询历史消息记录成功", "QueryHistoryMessage回调", errorcode, YIMErrorcode_Success); for (auto it = messageList.begin(); it != messageList.end(); ++it) { XUINT64 id = (*it)->GetMessageID(); std::string comment = ""; if ((*it)->GetMessageBody()->GetMessageType() ==MessageBodyType_TXT) { IYIMMessageBodyText* pMsg = static_cast<IYIMMessageBodyText*>((*it)->GetMessageBody()); comment = XStringToUTF8(XString(pMsg->GetMessageContent())); } EXPECT_EQ("历史消息内容", "QueryHistoryMessage", id != 0, true, comment); } m_cv.notify_one(); } void IMTestController::OnQueryRoomHistoryMessage(YIMErrorcode errorcode, std::list<std::shared_ptr<IYIMMessage> > messageList) { EXPECT_EQ("查询房间历史消息记录成功", "QueryRoomHistoryFromserver回调", errorcode, YIMErrorcode_Success); for (auto it = messageList.begin(); it != messageList.end(); ++it) { XUINT64 id = (*it)->GetMessageID(); std::string comment = ""; if ((*it)->GetMessageBody()->GetMessageType() ==MessageBodyType_TXT) { IYIMMessageBodyText* pMsg = static_cast<IYIMMessageBodyText*>((*it)->GetMessageBody()); comment = XStringToUTF8(XString(pMsg->GetMessageContent())); } EXPECT_EQ("房间历史消息内容", "QueryHistoryMessage", id != 0, true, comment); } m_cv.notify_one(); } void IMTestController::OnGetUserInfo(YIMErrorcode errorcode, const XString& userID, const XString& userInfo) { EXPECT_EQ("获取用户信息成功", "OnGetUserInfo回调", errorcode, YIMErrorcode_Success); EXPECT_EQ_STR("用户名校验", "GetUserInfo", XStringToLocal(userID).c_str(), "David", cocos2d::StringUtils::format("UserID:%s", XStringToLocal(userID).c_str())); m_cv.notify_one(); } void IMTestController::OnBlockUser(YIMErrorcode errorcode, const XString &userID, bool block) { std::string comment = ""; if (block) { comment = cocos2d::StringUtils::format("user %s is block", XStringToLocal(userID).c_str()); } else { comment = cocos2d::StringUtils::format("user %s is unblock", XStringToLocal(userID).c_str()); } EXPECT_EQ("屏蔽用户", "OnBlockUser", errorcode, YIMErrorcode_Success, comment); m_cv.notify_one(); } void IMTestController::OnUnBlockAllUser(YIMErrorcode errorcode) { EXPECT_EQ("解除屏蔽所有的用户", "OnUnBlockAllUser", errorcode, YIMErrorcode_Success); m_cv.notify_one(); } void IMTestController::OnGetBlockUsers(YIMErrorcode errorcode, std::list<XString> userList) { EXPECT_EQ("获取被屏蔽的所有的用户", "OnGetBlockUsers", errorcode, YIMErrorcode_Success); std::string comments = ""; auto it = userList.begin(); for (; it != userList.end(); ++it) { XString userName = (*it); comments += XStringToLocal(userName); comments += ";"; } cocos2d::StringUtils::format("Users : %s", comments.c_str()); m_cv.notify_one(); } void IMTestController::actionDeletemessage() { } void IMTestController::actionJubao() { YIMManager *im = YIMManager::CreateInstance(); const XCHAR* exparams = __XT("{\"nickname\":\"Mark\", \"server_area\":\"Dongfangkjds\", \"level\":1,\"vip_level\":1}"); YIMErrorcode code = im->GetMessageManager()->Accusation(__XT("RobotJubao"), ChatType_RoomChat, 1, __XT("涉黄"), exparams); EXPECT_EQ("举报用户", "Accusation", code, YIMErrorcode_Success); const char *fmt = "{ \ \"MsgID\" : 76360433937952770, \ \"SendID\" : \"%s\", \ \"RecvID\" : \"RobotJubao\", \ \"Strategy\": \"ignore\" \ }"; std::string body = cocos2d::StringUtils::format(fmt, "RobotRand"); YouMeHttpRequest::request("audit_tipoff_msg", body.c_str()); } void IMTestController::requestForbid() { const char *body = "{ \ \"ChannelID\":\"channel123\", \ \"ChannelDescription\":\"ios-1\", \ \"ShutUpTime\":200, \ \"UserList\":[ \ { \ \"UserID\":\"RobotJinyan\" \ } \ ] \ }"; YouMeHttpRequest::request("forbid_im_send_msg", body); } void IMTestController::translate(const XCHAR* content) { YIMManager *im = YIMManager::CreateInstance(); unsigned int no; YIMErrorcode code = im->GetMessageManager()->TranslateText(&no, content, LANG_ZH_CN, LANG_JA); EXPECT_EQ("翻译文本", "TranslateText", code, YIMErrorcode_Success); } void IMTestController::OnRecvMessage(std::shared_ptr<IYIMMessage> pMessage) { /*** 1 公聊 2 私聊 3 脏词广告 公聊 4 日语 公聊 5 公聊 自定义 **/ YIMMessageBodyType msgType = pMessage->GetMessageBody()->GetMessageType(); if (msgType == YIMMessageBodyType::MessageBodyType_TXT) { //文本消息 //static int index = 0; IYIMMessageBodyText* pMsg = static_cast<IYIMMessageBodyText*>(pMessage->GetMessageBody()); ; cocos2d::log("Message: %s",XStringToLocal(XString(pMsg->GetMessageContent())).c_str()); //XUINT64 id = pMessage->GetMessageID(); std::string text = XStringToLocal(XString(pMsg->GetMessageContent())); std::string msg = XStringToLocal(XString(PROCOLOL_FROM_PREFIX)); if (isStartWith(msg, text)) { m_cv.notify_one(); } } else if (msgType == YIMMessageBodyType::MessageBodyType_Gift) { IYIMMessageGift *pMsg = static_cast<IYIMMessageGift*>(pMessage->GetMessageBody()); cocos2d::log("[Recv msg:][ Message id : %lld", pMessage->GetMessageID()); cocos2d::log(" Message exp: %s", XStringToLocal(XString(pMsg->GetExtraParam())).c_str()); cocos2d::log(" sender: %s", pMessage->GetSenderID()); cocos2d::log(" recver: %s", pMessage->GetReceiveID()); cocos2d::log(" zhubo: %s", XStringToLocal(XString(pMsg->GetAnchor())).c_str()); cocos2d::log(" gift cnt: %d", pMsg->GetGiftCount()); cocos2d::log(" gift id: %d", pMsg->GetGiftID()); cocos2d::log(" ]"); } else if (msgType == YIMMessageBodyType::MessageBodyType_Voice) { // voice IYIMMessageBodyAudio * pMsgVoice = (IYIMMessageBodyAudio*)pMessage->GetMessageBody(); cocos2d::log("[Recv msg:][ Message id : %lld", pMessage->GetMessageID()); cocos2d::log(" sender: %s", XStringToLocal(XString(pMessage->GetSenderID())).c_str()); cocos2d::log(" recvor: %s", XStringToLocal(XString(pMessage->GetReceiveID())).c_str()); cocos2d::log("[Recv msg:][ %s \n messageid is %llu \n param is %s \n audio time is %d\n]", pMsgVoice->GetText(), pMessage->GetMessageID(), pMsgVoice->GetExtraParam(), pMsgVoice->GetAudioTime()); //下载语音文件示例 //->DownloadFile(pMessage->GetMessageID(), "/sdcard/audiocaches/123.wav"); YIMManager::CreateInstance()->GetMessageManager()->DownloadFile(pMessage->GetMessageID(), wav_save_path.c_str()); // m_cv.notify_one(); } else if (msgType == YIMMessageBodyType::MessageBodyType_CustomMesssage) { //static int index = 0; IYIMMessageBodyCustom *pMsg = static_cast<IYIMMessageBodyCustom*>(pMessage->GetMessageBody()); cocos2d::log("[Custom msg: [%s]", pMsg->GetCustomMessage().c_str()); } } void IMTestController::OnReceiveMessageNotify(YIMChatType chatType, const XString &targetID) { EXPECT_EQ("手动消息拉取,消息到达通知", "OnReceiveMessageNotify", chatType, ChatType_RoomChat); EXPECT_EQ_STR("手动消息拉取,消息到达通知,用户ID", "OnReceiveMessageNotify", XStringToLocal(targetID).c_str(), XStringToLocal(XString(ROOM_ID)).c_str()); YIMManager *im = YIMManager::CreateInstance(); //手动获取消息 vector<XString> rooms{ ROOM_ID }; YIMErrorcode code = im->GetMessageManager()->GetNewMessage(rooms); EXPECT_EQ("手动获取消息", "GetNewMessage", code, YIMErrorcode_Success); YIMErrorcode code2 = im->GetMessageManager()->SetReceiveMessageSwitch(rooms, false); EXPECT_EQ("关闭手动消息拉取的开关", "SetReceiveMessageSwitch", code2, YIMErrorcode_Success); m_cv.notify_one(); } void IMTestController::OnAccusationResultNotify(AccusationDealResult result, const XString &userID, unsigned int accusationTime) { EXPECT_EQ_STR("举报结果通知", "[AccusationResultNotify]:cb", XStringToLocal(userID).c_str(), "Robot", cocos2d::StringUtils::format("AccusationResultNotify:Time is %u", accusationTime)); //EXPECT_EQ("", "[AccusationResultNotify]:time", accusationTime, (unsigned int)200); m_cv.notify_one(); } void IMTestController::OnStartSendAudioMessage(XUINT64 requestID, YIMErrorcode errorcode, const XString &text, const XString &audioPath, unsigned int audioTime) { EXPECT_EQ("停止语音录制回调", "OnStartSendAudioMessage", errorcode, YIMErrorcode_Success); cocos2d::log("OnStartSendAudioMessage cb"); //m_cv.notify_one(); 另一个回调接口已经通知过了 } void IMTestController::OnStopAudioSpeechStatus(YIMErrorcode errorcode, std::shared_ptr<IAudioSpeechInfo> audioSpeechInfo) { EXPECT_EQ("语音消息发送成功回调", "[StopAudioSpeechStatus]:cb", errorcode, YIMErrorcode_Success, XStringToLocal(XString(audioSpeechInfo->GetText()))); // const XCHAR *url = audioSpeechInfo->GetDownloadURL(); // const XCHAR *localath = audioSpeechInfo->GetLocalPath(); // //const XCHAR* text = audioSpeechInfo->GetText(); // XUINT64 rid = audioSpeechInfo->GetRequestID(); cocos2d::log("[cb:success]"); m_cv.notify_one(); } //下载回调 void IMTestController::OnDownload(YIMErrorcode errorcode, std::shared_ptr<IYIMMessage> msg, const XString &savePath) { EXPECT_EQ("下载成功", "OnDownload", errorcode, YIMErrorcode_Success); m_cv.notify_one(); } void IMTestController::OnDownloadByUrl(YIMErrorcode errorcode, const XString &strFromUrl, const XString &savePath) { EXPECT_EQ("根据url下载语音成功", "OnDownloadByUrl", errorcode, YIMErrorcode_Success); YIMManager *im = YIMManager::CreateInstance(); YIMErrorcode code = im->StartPlayAudio(savePath.c_str()); EXPECT_EQ("开始播放语音", "StartPlayAudio", code, YIMErrorcode_Success); if (code == YIMErrorcode_Success) { bool b = im->IsPlaying(); EXPECT_EQ("判断是否正在播放语音", "IsPlaying", b, true); } YIMErrorcode code1 = im->StopPlayAudio(); EXPECT_EQ("停止播放语音", "StopPlayAudio", code1, YIMErrorcode_Success); m_cv.notify_one(); } //stopAudio 停止录音并发送 回调到此 void IMTestController::OnSendAudioMessageStatus(XUINT64 requestID, YIMErrorcode errorcode, const XString &text, const XString &audioPath, unsigned int audioTime, bool isForbidRoom, int reasonType, XUINT64 forbidEndTime) { EXPECT_EQ("停止录音并发送成功", "OnSendAudioMessageStatus", errorcode, YIMErrorcode_Success, XStringToUTF8(text).c_str()); cocos2d::log("[=====][cb:success]"); } //LBS void IMTestController::OnGetNearbyObjects(YIMErrorcode errorcode, std::list<std::shared_ptr<RelativeLocation> > neighbourList, unsigned int startDistance, unsigned int endDistance) { std::string info = cocos2d::StringUtils::format("distans: (%d, %d)", startDistance, endDistance); EXPECT_EQ("获取附近联系人", "OnGetNearbyObjects", errorcode, YIMErrorcode_Success, info); m_cv.notify_one(); } void IMTestController::OnUpdateLocation(YIMErrorcode errorcode, std::shared_ptr<GeographyLocation> location) { EXPECT_EQ("更新地理位置信息成功", "OnUpdateLocation", errorcode, YIMErrorcode_Success); m_cv.notify_one(); } /**/ //VoiceCaseController::VoiceCaseController() //{ // YIMManager *im = YIMManager::CreateInstance(); // std::unique_lock<std::mutex> lk(m_mutex); // YIMErrorcode code = im->Login(USER_ID_A, __XT("12345"), __XT("")); // // if (code == YIMErrorcode_Success) { // m_cv.wait_for(lk, std::chrono::seconds(10)); // } // // lk.unlock(); // // std::unique_lock<std::mutex> lk2(m_mutex); // YIMErrorcode code1 = im->GetChatRoomManager()->JoinChatRoom(ROOM_ID); // if (code1 == YIMErrorcode_Success) { // m_cv.wait_for(lk, std::chrono::seconds(10)); // } //} // //VoiceCaseController::~VoiceCaseController() //{ // //} // //void VoiceCaseController::case_send_voice_chatroom() //{ //} // //void VoiceCaseController::case_send_voice_private() //{ // YIMManager *im = YIMManager::CreateInstance(); // XUINT64 reqNo; // // //std::unique_lock<std::mutex> lk2(m_mutex); // // YIMErrorcode code2 = im->GetMessageManager()->SendOnlyAudioMessage(ROOM_ID, ChatType_RoomChat, &reqNo); // // EXPECT_EQ("开始录音,私聊频道", "SendOnlyAudioMessage", code2, YIMErrorcode_Success); // std::this_thread::sleep_for(std::chrono::seconds(5)); // // YIMErrorcode code3 = im->GetMessageManager()->StopAudioMessage(__XT("")); // EXPECT_EQ("结束录音并发送", "StopAudioMessage", code3, YIMErrorcode_Success); //} // // // //void VoiceCaseController::OnRecvMessage(std::shared_ptr<IYIMMessage> message) //{ // //} // //void VoiceCaseController::OnStartSendAudioMessage(XUINT64 requestID, YIMErrorcode errorcode, const XString &text, const XString &audioPath, unsigned int audioTime) //{ // //} // //void VoiceCaseController::OnSendAudioMessageStatus(XUINT64 requestID, YIMErrorcode errorcode, const XString &text, const XString &audioPath, unsigned int audioTime, bool isForbidRoom, int reasonType, XUINT64 forbidEndTime) //{ // //}
#include <algorithm> #include <iostream> #include <stack> #include <vector> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int n, m; std::cin >> n >> m; std::vector<std::vector<bool>> graph(n, std::vector<bool>(n, false)); std::vector<bool> check(n, false); for (int i = 0; i < m; ++i) { int a, b; std::cin >> a >> b; --a; --b; graph[a][b] = true; graph[b][a] = true; } int result{}; for (int i = 0; i < n; ++i) { if (check[i]) { continue; } std::stack<int> st; st.push(i); check[i] = true; while (!st.empty()) { int now = st.top(); st.pop(); for (int j = 0; j < n; ++j) { if (graph[now][j] == true && !check[j]) { st.push(j); check[j] = true; } } } ++result; } std::cout << result << '\n'; return 0; }
#include "StdAfx.h" #include "SettingFrame.h" CSettingFrame::CSettingFrame(void) { pButton_account = NULL; pButton_generic = NULL; pButton_shortcut = NULL; pButton_backup = NULL; pButton_about = NULL; pTabLayout = NULL; } CSettingFrame::~CSettingFrame(void) { } LPCTSTR CSettingFrame::GetWindowClassName() const { return L"settingFrame"; } DuiLib::CDuiString CSettingFrame::GetSkinFile() { return L"setting.xml"; } DuiLib::CDuiString CSettingFrame::GetSkinFolder() { return L""; } void CSettingFrame::Notify(TNotifyUI& msg) { CDuiString SenderName = msg.pSender->GetName(); if(msg.sType == _T("click")) //按钮点击事件 { if(SenderName == L"account_set") { pButton_account->SetTextColor(0x3dce3d); pButton_generic->SetTextColor(0); pButton_shortcut->SetTextColor(0); pButton_backup->SetTextColor(0); pButton_about->SetTextColor(0); if(pTabLayout) { pTabLayout->SelectItem(0); } } else if(SenderName == L"generic_set") { pButton_account->SetTextColor(0); pButton_generic->SetTextColor(0x3dce3d); pButton_shortcut->SetTextColor(0); pButton_backup->SetTextColor(0); pButton_about->SetTextColor(0); if(pTabLayout) { pTabLayout->SelectItem(1); } } else if(SenderName == L"shortcut_set") { pButton_account->SetTextColor(0); pButton_generic->SetTextColor(0); pButton_shortcut->SetTextColor(0x3dce3d); pButton_backup->SetTextColor(0); pButton_about->SetTextColor(0); if(pTabLayout) { pTabLayout->SelectItem(2); } } else if(SenderName == L"backup_set") { pButton_account->SetTextColor(0); pButton_generic->SetTextColor(0); pButton_shortcut->SetTextColor(0); pButton_backup->SetTextColor(0x3dce3d); pButton_about->SetTextColor(0); if(pTabLayout) { pTabLayout->SelectItem(3); } } else if(SenderName == L"about_set") { pButton_account->SetTextColor(0); pButton_generic->SetTextColor(0); pButton_shortcut->SetTextColor(0); pButton_backup->SetTextColor(0); pButton_about->SetTextColor(0x3dce3d); if(pTabLayout) { pTabLayout->SelectItem(4); } } } else if(msg.sType == _T("windowinit")) { OnPrepare(); } __super::Notify(msg); } void CSettingFrame::OnPrepare() { pButton_account = static_cast<CButtonUI*>(m_PaintManager.FindControl(L"account_set")); pButton_generic = static_cast<CButtonUI*>(m_PaintManager.FindControl(L"generic_set")); pButton_shortcut = static_cast<CButtonUI*>(m_PaintManager.FindControl(L"shortcut_set"));; pButton_backup = static_cast<CButtonUI*>(m_PaintManager.FindControl(L"backup_set"));; pButton_about = static_cast<CButtonUI*>(m_PaintManager.FindControl(L"about_set"));; pTabLayout = static_cast<CTabLayoutUI*>(m_PaintManager.FindControl(L"default_bk")); pButton_account->SetTextColor(0x3dce3d); //默认选中账号设置 }
/* -*- coding: utf-8 -*- !@time: 2019-10-20 18:50 !@author: superMC @email: 18758266469@163.com !@fileName: 0_main.cpp */ #include "bilibili/twisting-machine.cpp" int main() { fun(); }
#include "PucksInHand.h" // Pointer that will need to be set in order to execute helper methods contained in this file // This variable must be declared as an extern and should be initialized prior to calling // Pucks In Hands Supervisory or RealTime Methods //extern BHAND_PUCK2 *bhandPuckTwos; #include <string.h> // Number of default properties #define BHAND_NUM_DEFAULTS 31 #define BHAND_NUM_SPREAD_DEFAULTS 6 struct defaultStruct { int prop; long val; }; // Pointer that will need to be set in order to execute supervisory commands contained in this file // This variable must be declared as an extern and should be initialized prior to calling // Pucks In Hands Supervisory or RealTime Methods //extern BHAND_PUCK2 *bhandPuckTwos; static struct defaultStruct bh8Defs[BHAND_NUM_DEFAULTS] = { {PROP_TIE, 0}, {PROP_ACCEL, 200}, {PROP_P, 0}, {PROP_CT, 195000}, {PROP_OT, 0}, {PROP_CTS, 4096}, {PROP_DP, 45000}, {PROP_MT, 3300}, {PROP_MV, 200}, {PROP_MCV, 200}, {PROP_MOV, 200}, {PROP_HOLD, 0}, {PROP_TSTOP, BHAND_DEFAULT_TSTOP}, {PROP_OTEMP, 60}, {PROP_PTEMP, 0}, {PROP_POLES, 6}, {PROP_IKI, 204}, {PROP_IKP, 500}, {PROP_IKCOR, 102}, {PROP_IOFF, 0}, {PROP_IVEL, -75}, {PROP_DS, 25600}, {PROP_KP, 500}, {PROP_KD, 5000}, {PROP_KI, 0}, {PROP_IPNM, 20000}, {PROP_HSG, 0}, {PROP_LSG, 0}, {PROP_GRPA, 0}, {PROP_GRPB, 7}, {PROP_GRPC, 8} }; static struct defaultStruct bh8DefsForSpread[BHAND_NUM_SPREAD_DEFAULTS] = { {PROP_CT, 35950}, {PROP_DP, 17975}, {PROP_MV, 50}, {PROP_HSG, 0}, {PROP_LSG, 0}, {PROP_HOLD, 1} }; /////////////////////////////////////////////////////////////////////////////// // Accessor methods /////////////////////////////////////////////////////////////////////////////// int pucksInHandPropertyNumDefault() { return BHAND_NUM_DEFAULTS; } int pucksInHandPropertyNumSpreadDefault() { return BHAND_NUM_SPREAD_DEFAULTS; } void pucksInHandPropertyDefault(int index, int *property, int *value) { *property = bh8Defs[index].prop; *value = bh8Defs[index].val; } void pucksInHandPropertySpreadDefault(int index, int *property, int *value) { *property = bh8DefsForSpread[index].prop; *value = bh8DefsForSpread[index].val; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_SHELL_PLATFORM_H_ #define BAJKA_SHELL_PLATFORM_H_ #include <stdint.h> // Time extern uint32_t getCurrentMs (); extern void delayMs (uint32_t); // Logging extern int printlogImpl (const char *format, ...); #ifndef NDEBUG #define printlog(...) printlogImpl(__VA_ARGS__) #else #define printlog(...) #endif namespace Common { class DataSource; } extern Common::DataSource *newDataSource (); extern void deleteDataSource (Common::DataSource *ds); namespace Util { class Config; } namespace View { class GLContext; } extern Util::Config *config (); extern void quit (); #endif /* SHELL_H_ */
#pragma once #include <map> #include "CommandDescriptor.h" #include "Exceptions.h" class CommandTemplateParser { static const int TEXT = 0; static const int VARIABLE_NAME = 1; static const int ESCAPED = 2; std::string input; std::string output; CommandDescriptor* commandDescriptor; std::map<std::string, std::string>* variableMap; ExceptionCode exceptionCode; std::string errorMessage; int mode; int depth; int depthSinceHidden; bool justPrintedWhitespace; std::string variableName; void step(char qc); void textStep(char qc); void variableNameStep(char qc); void escapedStep(char qc); void lastStep(); void print(std::string s); bool isVariableTrueOrNonEmpty(std::string name); public: CommandTemplateParser(CommandDescriptor* commandDescriptor); void parse(); ExceptionCode validate(); void addVariable(const std::string *name, const std::string *value); ExceptionCode getError(); std::string getErrorMessage(); std::string getResult(); };
#include<iostream> using namespace std; int digit_sum(int n) { int d,t; if(n!=0) { d=n%10; return (d+digit_sum(n/10)); } else return 0; } int main() { int sum,num; cout<<"enter number\n"; cin>>num; sum=digit_sum(num); cout<<"Sum of digits of "<<num<<" is "<<sum; return 0; }
#include <Routes.h> Routes::Routes(string raw_model, int width, int height, int depth, int bytes): raw_model(raw_model), width(width), height(height), depth(depth), bytes(bytes){} Routes::~Routes() { this->raw_model.~basic_string(); }
#include <iostream> /* Sisend ja väljund */ #include <cstdlib> /* EXIT_SUCCESS jt konstandid */ #include "tstar_algo_jump.hpp" #include <vector> #include <algorithm> #include <climits> #include <unordered_set> #include <unordered_map> #include <map> #include <list> using namespace std; /* Nimeruumi valik (selgitatakse praktikumis) */ vertex_s* vertex_s::get_parent(){ return parent; } void vertex_s::set_parent(vertex_s* par){ parent = par; } vertex_s::vertex_s(int x_init, int y_init){ x = x_init; y = y_init; } vertex_s::vertex_s(Point2D p1){ x = p1.x; y = p1.y; } vertex_s::vertex_s(){ } Point2D vertex_s::get_point(){ return {x,y}; } void vertex_s::set_point(Point2D p1){ x = p1.x; y = p1.y; } int vertex_s::get_gvalue(){ return gvalue; } void vertex_s::set_gvalue(int gval){ gvalue = gval; } double vertex_s::straight_distance(vertex_s othervertex){ int d1; int d2; double distance; if (othervertex.x >= x) d1 = othervertex.x - x; else d1 = x - othervertex.x; if (othervertex.y >= y) d2 = othervertex.y - y; else d2 = y - othervertex.y; distance= sqrt(d1*d1 + d2*d2); return distance; } /* class grid{ public: bool[][] gridcoordinates; grid(bool[][]); bool isBlocked(int x, int y); }; grid::grid(bool[][] coords){ gridcoordinates = coords; } grid::isBlocked(int x, int y) */ void tstar_UpdateVertex (unordered_map<Point2D,vertex_s>* parentmap,vertex_s s_goal, vertex_s* temp_s, vertex_s* near_s, JumpMesh meshgrid, map<float,vertex_s>* openmap){ int g_old = near_s->get_gvalue(); //printf("%d %d \n", temp_s->get_point().x,temp_s->get_point().y); //printf("%d %d \n", near_s->get_point().x,near_s->get_point().y); tstar_ComputeCost(parentmap,temp_s, near_s, meshgrid); //printf("gvalue test: %d \n ", near_s->get_gvalue()); //printf("gold test: %d \n ", g_old); if (near_s->get_gvalue() < g_old){ std::map<float,vertex_s>::iterator it = openmap->begin(); //it = std::find(openmap.begin(), openmap.end(),*near_s); for (it = openmap->begin(); it != openmap->end(); ++it ){ if (it->second == *near_s){ openmap->erase(it); break; } //printf("smalleropen \n"); } //printf("biggeropen \n"); openmap->insert(pair<float,vertex_s>(near_s->get_gvalue()+meshgrid.getDistance(near_s->get_point(), s_goal.get_point()), *near_s )); } } void astar_UpdateVertex (unordered_map<Point2D,vertex_s>* parentmap,vertex_s s_goal, vertex_s* temp_s, vertex_s* near_s, JumpMesh meshgrid, map<float,vertex_s>* openmap){ int g_old = near_s->get_gvalue(); //printf("%d %d \n", temp_s->get_point().x,temp_s->get_point().y); //printf("%d %d \n", near_s->get_point().x,near_s->get_point().y); astar_ComputeCost(parentmap,temp_s, near_s, meshgrid); //printf("gvalue test: %d \n ", near_s->get_gvalue()); //printf("gold test: %d \n ", g_old); if (near_s->get_gvalue() < g_old){ std::map<float,vertex_s>::iterator it = openmap->begin(); //it = std::find(openmap.begin(), openmap.end(),*near_s); for (it = openmap->begin(); it != openmap->end(); ++it ){ if (it->second == *near_s){ openmap->erase(it); } //printf("smalleropen \n"); } //printf("biggeropen \n"); openmap->insert(pair<float,vertex_s>(near_s->get_gvalue()+meshgrid.getDistance(near_s->get_point(), s_goal.get_point()), *near_s )); } } void tstar_ComputeCost(unordered_map<Point2D,vertex_s>* parentmap, vertex_s* s0, vertex_s* s1, JumpMesh meshgrid ){ std::unordered_map<Point2D,vertex_s>::iterator it; it = parentmap->find(s0->get_point()); vertex_s* aword; if (it != parentmap->end()){ //parentmap->emplace(pair<Point2D,vertex_s>(s0->get_parent()->get_point(), *s1)); vertex_s awordnon = it->second; aword = &awordnon;} else{ parentmap->emplace(pair<Point2D,vertex_s>(s0->get_point(), *s0)); s0->set_parent(s0); aword = s0; } //printf("here is fine right \n"); //printf("X value is test Computecost: %d \n ",s0->x); //printf("computecost test"); //printf("%d %d \n", aword->get_point().x,aword->get_point().y); //printf("%d %d \n", s1->get_point().x,s1->get_point().y); //if (tstar_lineofsight(*aword, *s1, meshgrid)){ if (meshgrid.isVisible(aword->get_point(), s1->get_point())){ if (aword->get_gvalue()+meshgrid.getDistance(aword->get_point(), s1->get_point()) < s1->get_gvalue()){ std::unordered_map<Point2D,vertex_s>::iterator it; s1->set_parent(aword); it = parentmap->find(aword->get_point()); if (it != parentmap->end()){ //parentmap->emplace(pair<Point2D,vertex_s>(s0->get_parent()->get_point(), *s1)); parentmap->emplace(pair<Point2D,vertex_s>(s1->get_point(), *aword)); } else{ printf("am here"); it->second = vertex_s(s1->get_point()); } //std::cerr << "if" << s1->get_point() << std::endl; /*if (!parenttest){ parentmap->erase(it); parentmap->emplace(pair<Point2D,vertex_s>(s0->get_parent()->get_point(), *s1)); }*/ s1->set_gvalue(aword->get_gvalue()+meshgrid.getDistance(aword->get_point(), s1->get_point())); } } else{ if (s0->get_gvalue() + meshgrid.getDistance(s0->get_point(), s1->get_point())< s1->get_gvalue()){ //printf("parent change2\n"); std::unordered_map<Point2D,vertex_s>::iterator it; s1->set_parent(s0); it = parentmap->find(s0->get_point()); if (it != parentmap->end()){ parentmap->emplace(pair<Point2D,vertex_s>(s1->get_point(), *s0)); } else{ it->second = vertex_s(s1->get_point()); } /* if (!parenttest){ parentmap->erase(it); parentmap->emplace(pair<Point2D,vertex_s>(s0->get_parent()->get_point(), *s1)); }*/ //std::cerr << "else" << s1->get_point() << std::endl; s1->set_gvalue(s0->get_gvalue() + meshgrid.getDistance(s0->get_point(), s1->get_point())); } } } void astar_ComputeCost (unordered_map<Point2D,vertex_s>* parentmap, vertex_s* s0, vertex_s* s1, JumpMesh meshgrid ){ std::unordered_map<Point2D,vertex_s>::iterator it; it = parentmap->find(s0->get_point()); vertex_s* aword; if (it != parentmap->end()){ //parentmap->emplace(pair<Point2D,vertex_s>(s0->get_parent()->get_point(), *s1)); vertex_s awordnon = it->second; aword = &awordnon;} else{ aword = s0->get_parent(); } //if (tstar_lineofsight(*aword, *s1, meshgrid)){ if ((s0->get_gvalue() + meshgrid.getDistance(s0->get_point(), s1->get_point()))< s1->get_gvalue()){ //printf("parent change2\n"); std::unordered_map<Point2D,vertex_s>::iterator it; s1->set_parent(s0); it = parentmap->find(s0->get_point()); if (it != parentmap->end()){ parentmap->emplace(pair<Point2D,vertex_s>(s1->get_point(), *s0)); } else{ it->second = vertex_s(s1->get_point()); } /* if (!parenttest){ parentmap->erase(it); parentmap->emplace(pair<Point2D,vertex_s>(s0->get_parent()->get_point(), *s1)); }*/ //std::cerr << "else" << s1->get_point() << std::endl; s1->set_gvalue(s0->get_gvalue() + meshgrid.getDistance(s0->get_point(), s1->get_point())); } } vector<Point2D> tstar_mainLoop (JumpMesh meshgrid, Point2D initpoint, Point2D endpoint){ vector<Point2D> result; vector<vertex_s> open; vector<vertex_s> closed; vector<Point2D> neighbours; vertex_s s_start = vertex_s(initpoint); vertex_s s_goal = vertex_s(endpoint); vertex_s temp_s; vertex_s near_s; bool check; //unordered_set<vertex_s> vertex_collectionf; Point2D point_near_s; vector<vertex_s> vectorvertex; unordered_map<Point2D,vertex_s> parentmap; map<float,vertex_s> openmap; s_start.set_gvalue(0); s_start.set_parent(&s_start); parentmap.emplace(pair<Point2D,vertex_s>(initpoint, s_start)); //std::cerr << "Mainloop_init" << initpoint << std::endl; //parentmap.insert(s_start,s_start); openmap.insert(pair<float,vertex_s>(s_start.get_gvalue()+meshgrid.getDistance(s_start.get_point(), s_goal.get_point()), s_start )); while (!openmap.empty()){ std::map<float,vertex_s>::iterator it = openmap.begin(); temp_s = openmap.begin()->second; openmap.erase(openmap.begin()); //printf("The results: %d , %d \n" ,temp_s.get_point().x,temp_s.get_point().y ); if (temp_s.get_point() == s_goal.get_point()){ printf("Path is:\n"); vertex_s temporary_vertex; Point2D pointholder= temp_s.get_point(); printf("Path is:\n"); temporary_vertex = temp_s; printf("Path is:\n"); //cout << temporary_vertex.get_point().x << " , " << temporary_vertex.get_point().y << endl; cout << temp_s.get_point().x << " , " << temp_s.get_point().y << endl; std::unordered_map<Point2D,vertex_s>::iterator it; //std::cerr << "temp_s: " << temp_s.get_point() << std::endl; it = parentmap.find(temporary_vertex.get_point()); float distance = 0; //it->second.get_point(); while (true){ std::unordered_map<Point2D,vertex_s>::iterator it; //cout << "iterator test " << temporary_vertex.get_point().x << " , " << temporary_vertex.get_point().y << endl; it = parentmap.find(temporary_vertex.get_point()); if (it != parentmap.end()){ //cout << "iterator test " << it->second.get_point().x << " , " << it->second.get_point().y << endl; temporary_vertex.set_point(it->second.get_point()); } if (pointholder.x == temporary_vertex.get_point().x and pointholder.y == temporary_vertex.get_point().y){ break;} distance = distance + meshgrid.getDistance(temporary_vertex.get_point(), pointholder); pointholder = temporary_vertex.get_point(); printf("The results: %d , %d \n", pointholder.x, pointholder.y); } /* printf("%d %d \n", temp_s.get_point().x,temp_s.get_point().y); temp_s = *temp_s.get_parent(); printf("%d %d \n", temp_s.get_point().x,temp_s.get_point().y); temp_s = *temp_s.get_parent(); printf("%d %d \n", temp_s.get_point().x,temp_s.get_point().y); */ cout << "The total distance for t-star is " << distance << endl; return result; } closed.push_back(temp_s); neighbours = meshgrid.getNeighbours(temp_s.get_point()); while (!neighbours.empty()){ point_near_s = neighbours.back(); neighbours.pop_back(); /*printf("neighbours test"); printf("%d %d \n", temp_s.get_point().x,temp_s.get_point().y); printf("%d %d \n", point_near_s.x,point_near_s.y); */ near_s.set_point(point_near_s); vectorvertex.push_back(near_s); //near_s.set_point(point_near_s); near_s.set_gvalue(meshgrid.getDistance(near_s.get_point(),temp_s.get_point())); //near_s.set_gvalue(meshgrid.getDistance(near_s.get_point(),temp_s.get_point())); if ((std::find(closed.begin(), closed.end(),near_s)==closed.end())){ check = true; for (it = openmap.begin(); it != openmap.end(); ++it ){ if (it->second == near_s){ check = false; } } if (check == true){ //printf("changing here"); near_s.set_gvalue(INT_MAX); near_s.set_parent(nullptr); } tstar_UpdateVertex(&parentmap, s_goal, &temp_s,&near_s,meshgrid, &openmap); } } } printf("result not found"); return result; } vector<Point2D> astar_mainLoop (JumpMesh meshgrid, Point2D initpoint, Point2D endpoint){ vector<Point2D> result; vector<vertex_s> open; vector<vertex_s> closed; vector<Point2D> neighbours; vertex_s s_start = vertex_s(initpoint); vertex_s s_goal = vertex_s(endpoint); vertex_s temp_s; vertex_s near_s; bool check; //unordered_set<vertex_s> vertex_collectionf; Point2D point_near_s; vector<vertex_s> vectorvertex; unordered_map<Point2D,vertex_s> parentmap; map<float,vertex_s> openmap; s_start.set_gvalue(0); s_start.set_parent(&s_start); parentmap.emplace(pair<Point2D,vertex_s>(initpoint, s_start)); //std::cerr << "Mainloop_init" << initpoint << std::endl; //parentmap.insert(s_start,s_start); openmap.insert(pair<float,vertex_s>(s_start.get_gvalue()+meshgrid.getDistance(s_start.get_point(), s_goal.get_point()), s_start )); while (!openmap.empty()){ std::map<float,vertex_s>::iterator it = openmap.begin(); temp_s = openmap.begin()->second; openmap.erase(openmap.begin()); //printf("The results: %d , %d \n" ,temp_s.get_point().x,temp_s.get_point().y ); if (temp_s.get_point() == s_goal.get_point()){ printf("Path is:"); vertex_s temporary_vertex; Point2D pointholder= temp_s.get_point(); temporary_vertex = *temp_s.get_parent(); //cout << temporary_vertex.get_point().x << " , " << temporary_vertex.get_point().y << endl; cout << temp_s.get_point().x << " , " << temp_s.get_point().y << endl; std::unordered_map<Point2D,vertex_s>::iterator it; //std::cerr << "temp_s: " << temp_s.get_point() << std::endl; it = parentmap.find(temporary_vertex.get_point()); float distance = 0; //it->second.get_point(); while (true){ std::unordered_map<Point2D,vertex_s>::iterator it; //cout << "iterator test " << temporary_vertex.get_point().x << " , " << temporary_vertex.get_point().y << endl; it = parentmap.find(temporary_vertex.get_point()); if (it != parentmap.end()){ //cout << "iterator test " << it->second.get_point().x << " , " << it->second.get_point().y << endl; temporary_vertex.set_point(it->second.get_point()); } if (pointholder.x == temporary_vertex.get_point().x and pointholder.y == temporary_vertex.get_point().y){ break;} distance = distance + meshgrid.getDistance(temporary_vertex.get_point(), pointholder); //cout << distance << endl; pointholder = temporary_vertex.get_point(); printf("The results: %d , %d \n", pointholder.x, pointholder.y); } /* printf("%d %d \n", temp_s.get_point().x,temp_s.get_point().y); temp_s = *temp_s.get_parent(); printf("%d %d \n", temp_s.get_point().x,temp_s.get_point().y); temp_s = *temp_s.get_parent(); printf("%d %d \n", temp_s.get_point().x,temp_s.get_point().y); */ cout << "The total distance for astar is " << distance << endl; return result; } closed.push_back(temp_s); neighbours = meshgrid.getNeighbours(temp_s.get_point()); while (!neighbours.empty()){ point_near_s = neighbours.back(); neighbours.pop_back(); /*printf("neighbours test"); printf("%d %d \n", temp_s.get_point().x,temp_s.get_point().y); printf("%d %d \n", point_near_s.x,point_near_s.y); */ near_s.set_point(point_near_s); vectorvertex.push_back(near_s); //near_s.set_point(point_near_s); near_s.set_gvalue(meshgrid.getDistance(near_s.get_point(),temp_s.get_point())); //near_s.set_gvalue(meshgrid.getDistance(near_s.get_point(),temp_s.get_point())); if ((std::find(closed.begin(), closed.end(),near_s)==closed.end())){ check = true; for (it = openmap.begin(); it != openmap.end(); ++it ){ if (it->second == near_s){ check = false; } } if (check == true){ //printf("changing here"); near_s.set_gvalue(INT_MAX); //near_s.set_parent(nullptr); } astar_UpdateVertex(&parentmap, s_goal, &temp_s,&near_s,meshgrid, &openmap); } } } printf("result not found"); return result; } bool tstar_lineofsight(vertex_s s0, vertex_s s1, JumpMesh meshgrid){ //printf("X value is test lineofsight: %d \n ",s0.x); int x0; int y0; int x1; int y1; int dx; int dy; int sx; int sy; int f; x0 = s0.x; y0 = s0.y; x1 = s1.x; y1 = s1.y; dy = y1-y0; dx = x1-x0; f = 0; if (dy < 0){ dy = -dy; sy = -1; } else sy = 1; if (dx < 0){ dx = -dx; sx = -1; } else sx = 1; if (dx >= dy){ while (x0 != x1){ f = f+ dy; if (f >= dx){ if (!meshgrid.isAccessible({x0+((sx-1)/2),y0+((sy-1)/2)})){ return false; } y0 = y0+sy; f = f-dx; } if ((f != 0) and (!meshgrid.isAccessible({x0+((sx-1)/2),y0+((sy-1)/2)}))){ return false; } if ((dy == 0) and (!meshgrid.isAccessible({x0+((sx-1)/2),y0})) and (!meshgrid.isAccessible({x0+((sx-1)/2),y0-1}))){ return false; } x0 = x0 + sx; } } else{ while(y0 != y1){ f = f+ dx; if (f >= dy){ if (!meshgrid.isAccessible({x0+((sx-1)/2),y0+((sy-1)/2)})){ return false; } x0 = x0+sx; f = f-dy; } if ((f != 0) and (!meshgrid.isAccessible({x0+((sx-1)/2),y0+((sy-1)/2)}))){ return false; } if ((dx == 0) and (!meshgrid.isAccessible({x0,y0+((sy-1)/2)})) and (!meshgrid.isAccessible({x0-1,y0+((sy-1)/2)}))){ return false; } y0 = y0 + sy; } } return true; }
#ifndef ADAPTIVECANNY_H #define ADAPTIVECANNY_H class adaptivecanny { public: adaptivecanny(); }; #endif // ADAPTIVECANNY_H
#include "MainWindow.hpp" #include "EditorApplication.hpp" using namespace Maint; int main(int argc, char *argv[]) { EditorApplication a(argc, argv); a.GetMainWindow()->show(); return a.exec(); }
// // aff_list.cpp for in /home/roby_t/perso/test // // Made by Tristan Roby // Login <roby_t@epitech.net> // // Started on Thu Jan 22 20:04:59 2015 Tristan Roby // Last update Sun Jan 25 21:47:38 2015 Tristan Roby // #include "aff_list.hh" affList::affList(std::string *PokemonName) { this->PokemonName = PokemonName; this->setAll(); } affList::~affList(){} sf::Text affList::getText() const { return (this->Text); } sf::Sprite affList::getSpriteSelect() const { return (this->selectsprite); } sf::Sprite affList::getStatRightSprite() const { return (this->statrightsprite); } sf::Sprite affList::getStatSprite() const { return (this->statsprite); } sf::Sprite affList::getSpriteRight() const { return (this->rightlistsprite); } sf::Sprite affList::getSpriteFond() const { return (this->fondsprite); } sf::Sprite affList::getSpriteImg() const { return (this->imgPokemon); } void affList::setAll() { if (!this->select.loadFromFile("ressources/images/ceinture.png")) std::cout << "olalala" << std::endl; if (!this->myFont.loadFromFile("ressources/pokemonfont.ttf")) std::cout << "olalala" << std::endl; this->select.setSmooth(true); this->selectsprite.setTexture(this->select); this->selectsprite.setPosition(1280-405, 180); if (!this->fond.loadFromFile("ressources/images/fond.jpg")) std::cout << "olalala" << std::endl; this->fondsprite.setTexture(this->fond); if (!this->rightlist.loadFromFile("ressources/images/Pokedex2.jpg")) std::cout << "olalala" << std::endl; this->rightlist.setSmooth(true); this->rightlistsprite.setTexture(this->rightlist); this->rightlistsprite.setPosition(1280-405, 0); this->Text.setCharacterSize(18); this->Text.setFont(myFont); this->Text.setColor(sf::Color::Black); } void affList::lafonctionquivaaffichertoussa(int i, int pos) { std::stringstream ss; std::string img; if (i + pos > 493) i -= 493; if (i + pos == 0) i = 493; ss << i + pos; std::string str = ss.str(); img = "ressources/sprites/" + str + ".png"; if (!this->texPokemon.loadFromFile(img)) std::cout << "olalala" << std::endl; this->texPokemon.setSmooth(true); this->imgPokemon.setTexture(this->texPokemon); this->imgPokemon.setPosition(1280-350, 200 + 100 * pos); this->Text.setString(this->PokemonName[i + pos - 1]); this->Text.setPosition(1280 - 220, 230 + 100 * pos); } void affList::my_aff_selected(sf::RenderWindow &window, affList &a, int i, int j) { std::stringstream ss; std::stringstream ss2; std::string img; ss << j; ss2 << i; std::string str = ss.str(); img = "ressources/gif/" + ss2.str() + "/" + ss2.str() + ".gif/" + ss2.str() + "-" + str +".png"; if (!this->texPokemon.loadFromFile(img)) std::cout << "olalala" << std::endl; this->texPokemon.setSmooth(true); this->imgPokemon.setTexture(this->texPokemon, true); this->imgPokemon.setScale(1.5, 1.5); sf::Rect<int> r; r = imgPokemon.getTextureRect(); this->imgPokemon.setPosition(350 - r.width/2, 450 - r.height/2); if (!this->stat.loadFromFile("ressources/images/stats.png")) std::cout << "olalala" << std::endl; this->stat.setSmooth(true); this->statsprite.setTexture(this->stat); this->statsprite.setScale(1.5, 1); this->statsprite.setPosition(20, 20); this->statrightsprite.setTexture(this->stat); this->statrightsprite.setScale(1, 2.2); this->statrightsprite.setPosition(1280 - 332 - 420, 20); }
/************************************************************************/ /* X10 Rx/Tx library for the XM10/TW7223/TW523 interface, v1.4. */ /* */ /* This library 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 library is distributed in the hope that it will be useful, but */ /* WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this library. If not, see <http://www.gnu.org/licenses/>. */ /* */ /* Written by Thomas Mittet thomas@mittet.nu October 2010. */ /************************************************************************/ #ifndef X10ex_h #define X10ex_h #include <inttypes.h> // Number of silent power line cycles before command is sent #define X10_PRE_CMD_CYCLES 6 // Sample delay should be set to 500us according to spec #define X10_SAMPLE_DELAY 500 // Signal length should be set to 1000us according to spec #define X10_SIGNAL_LENGTH 1000 // Set buffer size to the number of individual messages you would like to // buffer, plus one. The buffer is useful when triggering a scenario e.g. // Each slot in the buffer uses 5 bytes of memory #define X10_BUFFER_SIZE 17 // Set the min delay, in ms, between buffering of two identical messages // This delay does not affect message repeats (when button is held) #define X10_REBUFFER_DELAY 500 // Chooses how to save module state and info (types and names). // Set to 0: Neither state nor info is stored and state code is ignored // Set to 1: Module state data and module info is stored in EEPROM. // Set to 2: State data is stored in volatile memory and cleared on // reboot. Module types and names are not stored when state is set to 2. #define X10_PERSIST_MOD_DATA 1 // Length of module names stored in EEPROM, do not change if you don't // know what you are doing. 4 and 8 should be valid, but this isn't tested. #define X10_INFO_NAME_LEN 16 // Enable this to use X10 standard message PRE_SET_DIM commands. // PRE_SET_DIM commands do not work with any of the European modules I've // tested. I have no idea if it works at all, but it's part of the X10 // standard. If you're using a PLC interface and modules that support // extended code: use the "sendExtDim" method in stead. #define X10_USE_PRE_SET_DIM 0 // These are message buffer data types used to seperate X10 standard // message format from extended message format, e.g. #define X10_MSG_STD B001 #define X10_MSG_CMD B010 #define X10_MSG_EXT B011 #define DATA_UNKNOWN 0xF0 #define CMD_ALL_UNITS_OFF B0000 #define CMD_ALL_LIGHTS_ON B0001 #define CMD_ON B0010 #define CMD_OFF B0011 #define CMD_DIM B0100 #define CMD_BRIGHT B0101 #define CMD_ALL_LIGHTS_OFF B0110 #define CMD_EXTENDED_CODE B0111 #define CMD_HAIL_REQUEST B1000 #define CMD_HAIL_ACKNOWLEDGE B1001 #define CMD_PRE_SET_DIM_0 B1010 #define CMD_PRE_SET_DIM_1 B1011 #define CMD_EXTENDED_DATA B1100 #define CMD_STATUS_ON B1101 #define CMD_STATUS_OFF B1110 #define CMD_STATUS_REQUEST B1111 #define EXC_PRE_SET_DIM B00110001 //#define EXC_EXTENDED_DATA B00110001 #define EXC_DIM_TIME_4 0 #define EXC_DIM_TIME_30 1 #define EXC_DIM_TIME_60 2 #define EXC_DIM_TIME_300 3 #define MODULE_TYPE_UNKNOWN B00 // 0 #define MODULE_TYPE_APPLIANCE B01 // 1 #define MODULE_TYPE_DIMMER B10 // 2 #define MODULE_TYPE_SENSOR B11 // 3 // Used when buffering messages struct X10msg { uint32_t message; uint8_t repetitions; }; // Used when returning module state struct X10state { bool isSeen; // Is true when message addressed to module has been seen/received on power line bool isKnown; // Is true when module state ON/OFF is known bool isOn; // Is true when appliance/dimmer module is ON uint8_t data; }; // Used when returning module type and name struct X10info { uint8_t type; char name[X10_INFO_NAME_LEN + 1]; }; class X10ex { public: typedef void (*plcReceiveCallback_t)(char, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t); // Phase retransmits not needed on European systems using the XM10 PLC interface, // so the phases and sineWaveHz parameters are optional and defaults to 1 and 50. X10ex( uint8_t zeroCrossInt, uint8_t zeroCrossPin, uint8_t transmitPin, uint8_t receivePin, bool receiveTransmits, plcReceiveCallback_t plcReceiveCallback, uint8_t phases = 1, uint8_t sineWaveHz = 50); // Public methods void begin(); bool sendAddress(uint8_t house, uint8_t unit, uint8_t repetitions); bool sendCmd(uint8_t house, uint8_t command, uint8_t repetitions); bool sendCmd(uint8_t house, uint8_t unit, uint8_t command, uint8_t repetitions); #if X10_USE_PRE_SET_DIM bool sendDim(uint8_t house, uint8_t unit, uint8_t percent, uint8_t repetitions); #endif bool sendExtDim(uint8_t house, uint8_t unit, uint8_t percent, uint8_t time, uint8_t repetitions); bool sendExt(uint8_t house, uint8_t unit, uint8_t command, uint8_t extData, uint8_t extCommand, uint8_t repetitions); X10state getModuleState(uint8_t house, uint8_t unit); void wipeModuleState(uint8_t house = '*', uint8_t unit = 0); #if X10_PERSIST_MOD_DATA == 1 X10info getModuleInfo(uint8_t house, uint8_t unit); void setModuleType(uint8_t house, uint8_t unit, uint8_t type); #if not defined(__AVR_ATmega8__) && not defined(__AVR_ATmega168__) bool setModuleName(uint8_t house, uint8_t unit, char name[X10_INFO_NAME_LEN], uint8_t length = X10_INFO_NAME_LEN); #endif void wipeModuleInfo(uint8_t house = '*', uint8_t unit = 0); #endif uint8_t percentToX10Brightness(uint8_t brightness, uint8_t time = EXC_DIM_TIME_4); uint8_t x10BrightnessToPercent(uint8_t brightness); void zeroCross(); void ioTimer(); private: static const uint8_t HOUSE_CODE[16]; static const uint8_t UNIT_CODE[16]; // Set in constructor uint8_t zeroCrossInt, zeroCrossPin, transmitPin, transmitPort, transmitBitMask, receivePin, receivePort, receiveBitMask, ioStopState; uint16_t inputDelayCycles, outputDelayCycles, outputLengthCycles; bool receiveTransmits; plcReceiveCallback_t plcReceiveCallback; // Transmit and receive fields int8_t ioState; bool volatile zcInput, zcOutput; // Transmit fields X10msg volatile sendBf[X10_BUFFER_SIZE]; uint8_t volatile sendBfStart, sendBfEnd; uint32_t sendBfLastMs; uint8_t zeroCount, sentCount, sendOffset; // Receive fields bool receivedDataBit; uint8_t receivedCount, receivedBits, receiveBuffer; uint8_t rxHouse, rxUnit, rxExtUnit, rxCommand, rxData, rxExtCommand; // State stored in byte (8=On/Off, 7=State Known/Unknown, 6-1 data) #if X10_PERSIST_MOD_DATA >= 2 uint8_t moduleState[256]; #endif // Private methods bool getBitToSend(); void receiveMessage(); void receiveStandardMessage(); void receiveExtendedMessage(); #if X10_PERSIST_MOD_DATA void updateModuleState(uint8_t house, uint8_t unit, uint8_t command); #endif void wipeModuleData(uint8_t house, uint8_t unit, bool info); #if X10_PERSIST_MOD_DATA == 1 uint8_t eepromRead(uint16_t address); uint8_t eepromRead(uint8_t house, uint8_t unit, uint16_t offset = 0); uint8_t eepromWrite(uint16_t address, uint8_t data); uint8_t eepromWrite(uint8_t house, uint8_t unit, uint8_t data, uint16_t offset = 0); #endif void clearReceiveBuffer(); uint8_t parseHouseCode(uint8_t house); int8_t findCodeIndex(const uint8_t codeList[16], uint8_t code); void fastDigitalWrite(uint8_t port, uint8_t bitMask, uint8_t value); }; #endif
#include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<=e;i++) //including end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define sful(a) scanf("%llu",&a); #define sfulul(a,b) scanf("%llu %llu",&a,&b); #define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different #define sfc(a) scanf("%c",&a); #define sfs(a) scanf("%s",a); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define vi vector<int> #define vll vector<ll> #define mii map<int,int> #define mlli map<ll,int> #define mib map<int,bool> #define fs first #define sc second #define CASE(t) printf("Case %d: ",++t) // t initialized 0 #define cCASE(t) cout<<"Case "<<++t<<": "; #define D(v,status) cout<<status<<" "<<v<<endl; #define INF 1000000000 //10e9 #define EPS 1e-9 #define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c ) #define CONTEST 1 using namespace std; struct point3d{ int left_x,rgt_x; int down_y,up_y; int down_z,up_z; }; point3d p3d[109]; point3d inter_p(point3d p1,point3d p2) { point3d intersected_p; int leftx1 = p1.left_x; int leftx2 = p2.left_x; int rightx1 = p1.rgt_x; int rightx2 = p2.rgt_x; int right_most_leftX = max(leftx1,leftx2); int left_most_rightX = min(rightx1,rightx2); int downy1 = p1.down_y; int downy2 = p2.down_y; int upy1 = p1.up_y; int upy2 = p2.up_y; int up_most_downY = max(downy1,downy2); int down_most_upY = min(upy1,upy2); int downz1 = p1.down_z; int downz2 = p2.down_z; int upz1 = p1.up_z; int upz2 = p2.up_z; int up_most_downZ = max(downz1,downz2); int down_most_upZ = min(upz1,upz2); if(right_most_leftX<=left_most_rightX && up_most_downY<=down_most_upY && up_most_downZ<=up_most_downZ) { intersected_p.left_x = right_most_leftX; intersected_p.rgt_x = left_most_rightX; intersected_p.down_y = up_most_downY; intersected_p.up_y = down_most_upY; intersected_p.down_z = up_most_downZ; intersected_p.up_z = down_most_upZ; } else { intersected_p.left_x = INF; } return intersected_p; } int volume(point3d p) { int vol = (p.rgt_x - p.left_x)* (p.up_y - p.down_y)*(p.up_z - p.down_z); return vol; } int main() { int tc,cas = 0; //write(); sfi(tc); while(tc--) { int N; sfi(N); loop(i,1,N) { int x1,x2,y1,y2,z1,z2; sfii(x1,y1); sfii(z1,x2); sfii(y2,z2); point3d temp; temp.left_x = x1; temp.rgt_x = x2; temp.down_y = y1; temp.up_y = y2; temp.down_z = z1; temp.up_z = z2; p3d[i] = temp; } int ans = 1; point3d cur_intersection = p3d[1]; loop(i,2,N) { point3d newp = p3d[i]; point3d intersex = inter_p(cur_intersection,p3d[i]); if(intersex.left_x==INF) { ans = 0; break; } else { cur_intersection = intersex; } } CASE(cas); if(N==1) { pf("%d\n",volume(p3d[1])); } else if(ans==0) { pf("%d\n",0); } else { pf("%d\n",volume(cur_intersection)); } } return 0; }
#pragma once #include <vector> #include <combaseapi.h> #include "WPDUtils.h" template <class T> using ptr = std::unique_ptr<T, void (*)(T *)>; template<class T> ptr<T> mockToPtr(T &m) { return ptr<T>{&m, WPD::Utils::ComDeleter<T>}; } LPWSTR allocString(const std::wstring &src); void copyStrings(const std::vector<std::wstring> &src, LPWSTR *dest);
#ifndef _CGetWinGoldRank_h_ #define _CGetWinGoldRank_h_ #pragma once #include <string> #include "CHttpRequestHandler.h" //活动金币排行 class CGetWinGoldRank : public CHttpRequestHandler { public: CGetWinGoldRank(){} ~CGetWinGoldRank(){} virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out); private: }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2008 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/libcrypto/libcrypto_module.h" #include "modules/libcrypto/include/CryptoExternalApiManager.h" #include "modules/libcrypto/include/CryptoMasterPasswordEncryption.h" #include "modules/libcrypto/include/CryptoMasterPasswordHandler.h" #include "modules/libcrypto/include/OpRandomGenerator.h" #include "modules/libcrypto/include/PEMCertificateLoader.h" #if defined(CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION) && !defined(_SSL_USE_OPENSSL_) #include "modules/formats/base64_decode.h" #include "modules/libopeay/openssl/cryptlib.h" #include "modules/libopeay/openssl/evp.h" #include "modules/libopeay/openssl/x509v3.h" #include "modules/libopeay/openssl/rsa.h" #include "modules/libcrypto/src/openssl_impl/openssl_util.h" #endif // CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION && !_SSL_USE_OPENSSL_ LibcryptoModule::LibcryptoModule() : m_random_generator(NULL) #ifdef CRYPTO_MASTER_PASSWORD_SUPPORT , m_master_password_encryption(NULL) , m_master_password_handler(NULL) #endif // CRYPTO_MASTER_PASSWORD_SUPPORT #ifndef _NATIVE_SSL_SUPPORT_ , m_ssl_random_generator(NULL) #endif // !_NATIVE_SSL_SUPPORT_ , m_random_generators(NULL) #ifdef CRYPTO_CERTIFICATE_VERIFICATION_SUPPORT , m_cert_storage(NULL) #endif // CRYPTO_CERTIFICATE_VERIFICATION_SUPPORT { } void LibcryptoModule::InitL(const OperaInitInfo& info) { m_random_generators = OP_NEW_L(OpVector<OpRandomGenerator>, ()); #ifdef CRYPTO_API_SUPPORT # ifndef _NATIVE_SSL_SUPPORT_ LEAVE_IF_NULL(m_ssl_random_generator = OpRandomGenerator::Create()); # endif // !_NATIVE_SSL_SUPPORT_ LEAVE_IF_NULL(m_random_generator = OpRandomGenerator::Create()); OpRandomGenerator::AddEntropyFromTimeAllGenerators(); # ifdef _EXTERNAL_SSL_SUPPORT_ LEAVE_IF_ERROR(CryptoExternalApiManager::InitCryptoLibrary()); // In case of external ssl, CryptoExternalApiManager::InitCryptoLibrary must be implemented by platform # endif # if defined(CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION) && !defined(_SSL_USE_OPENSSL_) InitOpenSSLLibrary(); # endif // CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION && !_SSL_USE_OPENSSL_ #endif // CRYPTO_API_SUPPORT #ifdef CRYPTO_MASTER_PASSWORD_SUPPORT m_master_password_encryption = OP_NEW_L(CryptoMasterPasswordEncryption, ()); m_master_password_encryption->InitL(); m_master_password_handler = OP_NEW_L(CryptoMasterPasswordHandler, ()); m_master_password_handler->InitL(TRUE); #endif // CRYPTO_MASTER_PASSWORD_SUPPORT #ifdef CRYPTO_CERTIFICATE_VERIFICATION_SUPPORT LoadCertificatesL(); #endif // CRYPTO_CERTIFICATE_VERIFICATION_SUPPORT } void LibcryptoModule::Destroy() { #ifdef CRYPTO_CERTIFICATE_VERIFICATION_SUPPORT OP_DELETE(m_cert_storage); m_cert_storage = NULL; #endif // CRYPTO_CERTIFICATE_VERIFICATION_SUPPORT #ifdef CRYPTO_MASTER_PASSWORD_SUPPORT OP_DELETE(m_master_password_handler); m_master_password_handler = NULL; OP_DELETE(m_master_password_encryption); m_master_password_encryption = NULL; #endif // CRYPTO_MASTER_PASSWORD_SUPPORT #ifdef CRYPTO_API_SUPPORT # if defined(CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION) && !defined(_SSL_USE_OPENSSL_) DestroyOpenSSLLibrary(); # endif // CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION && !_SSL_USE_OPENSSL_ # ifdef _EXTERNAL_SSL_SUPPORT_ CryptoExternalApiManager::DestroyCryptoLibrary(); // In case of external ssl, CryptoExternalApiManager::DestroyCryptoLibrary must be implemented by platform # endif //_EXTERNAL_SSL_SUPPORT_ OP_DELETE(m_random_generator); m_random_generator = NULL; # ifndef _NATIVE_SSL_SUPPORT_ OP_DELETE(m_ssl_random_generator); m_ssl_random_generator = NULL; # endif // !_NATIVE_SSL_SUPPORT_ OP_ASSERT(!m_random_generators || (m_random_generators->GetCount() == 0)); OP_DELETE(m_random_generators); m_random_generators = NULL; #endif // CRYPTO_API_SUPPORT } #if defined(CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION) && !defined(_SSL_USE_OPENSSL_) /* If _SSL_USE_OPENSSL_ is off and we want to use some openssl algorithms, * we need to initiate parts of openssl. */ OP_STATUS LibcryptoModule::InitOpenSSLLibrary() { OpenSSL_add_all_digests(); OPENSSL_RETURN_IF(ERR_peek_error()); return OpStatus::OK; } OP_STATUS LibcryptoModule::DestroyOpenSSLLibrary() { X509_PURPOSE_cleanup(); EVP_cleanup(); return OpStatus::OK; } #endif // CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION && !defined(_SSL_USE_OPENSSL_) LibcryptoModule::~LibcryptoModule() { } #ifdef CRYPTO_CERTIFICATE_VERIFICATION_SUPPORT void LibcryptoModule::LoadCertificatesL() { OP_ASSERT(!m_cert_storage); LEAVE_IF_ERROR(CryptoCertificateStorage::Create(m_cert_storage)); OP_ASSERT(m_cert_storage); OP_ASSERT(g_folder_manager); ANCHORD(OpString, folder_path); LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_TRUSTED_CERTS_FOLDER, folder_path)); TRAPD(status, PEMCertificateLoader loader; loader.SetInputDirectoryL(folder_path); loader.SetCertificateStorageContainer(m_cert_storage); loader.ProcessL(); ); } #endif // CRYPTO_CERTIFICATE_VERIFICATION_SUPPORT
#include <iostream> #include <cstdio> #include <unordered_map> #include <vector> using namespace std; const char OPEN_LOOP = '['; const char CLOSE_LOOP = ']'; unordered_map<size_t, size_t> match_brackets(const char code[], size_t size) { unordered_map<size_t, size_t> brackets; unordered_map<size_t, size_t> counts; for (size_t i = 0; i < size; i++) { if (code[i] == OPEN_LOOP) { for (auto &cnt : counts) { counts[cnt.first] += 1; } counts[i] = 1; } if (code[i] == CLOSE_LOOP) { size_t to_close = -1; for (auto &cnt : counts) { counts[cnt.first] -= 1; if (counts[cnt.first] == 0) { to_close = cnt.first; } } counts.erase(to_close); brackets[to_close] = i; } } // printf("Brackets:\n"); // for (auto &b : brackets) // { // printf("%d:%d", b.first, b.second); // printf("%c %c\n", code[b.first], code[b.second]); // } // printf("\n"); return brackets; } void interpret(const char code[], size_t size) { char memory[30000]; char *ptr = memory; unordered_map<size_t, size_t> matched_brackets = match_brackets(code, size); unordered_map<size_t, size_t> loop_jumpbacks; for (auto key_val : matched_brackets) { loop_jumpbacks[key_val.second] = key_val.first; } for (size_t ip = 0; ip < size; ++ip) { switch (code[ip]) { case '>': ++ptr; break; case '<': --ptr; break; case '+': ++(*ptr); break; case '-': --(*ptr); break; case '.': putchar(*ptr); break; case ',': *ptr = getchar(); break; case '[': if (!*ptr) { // if condition is not met jump after closing bracket. ip = matched_brackets[ip]; } break; case ']': ip = loop_jumpbacks[ip] - 1; break; default: break; } } } vector<char> load_code(const char *filename) { FILE *fp = fopen(filename, "rb"); if (!fp) { string exception = "File not found: "; exception += filename; throw exception; } fseek(fp, 0, SEEK_END); size_t filesize = ftell(fp); fseek(fp, 0, SEEK_SET); vector<char> code(filesize); fread(code.data(), 1, filesize, fp); return code; } int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <filename>" << std::endl; return 1; } const char * filename = argv[1]; vector<char> program_code; try { program_code = load_code(filename); } catch (string s) { cout << "Error: " << s << endl; return -1; } interpret(program_code.data(), program_code.size()); }
//=========================================================================== //! @file asset_model_manager.cpp //! @brief アセットモデル管理クラス //=========================================================================== //--------------------------------------------------------------------------- //! デストラクタ //--------------------------------------------------------------------------- AssetModelManager::~AssetModelManager() { this->cleanup(); } //--------------------------------------------------------------------------- //! 初期化 //--------------------------------------------------------------------------- bool AssetModelManager::initialize() { return true; } //--------------------------------------------------------------------------- //! 解放 //--------------------------------------------------------------------------- void AssetModelManager::cleanup() { for(auto assetModel : assetModels_) { auto model = assetModel.second; if(model) { model->cleanup(); model.reset(); } } assetModels_.clear(); } //--------------------------------------------------------------------------- //! モデル取得 //--------------------------------------------------------------------------- std::shared_ptr<AssetModel> AssetModelManager::getModel(const std::string& fileName) { // ない場合 if(!assetModels_.count(fileName)) { auto model = this->createModel(fileName); if(!model) return nullptr; // 配列追加 this->addModel(fileName, model); } return assetModels_[fileName]; } //--------------------------------------------------------------------------- //! モデル作成 //--------------------------------------------------------------------------- AssetModel* AssetModelManager::createModel(const std::string& fileName) { // FBX if(fileName.find(".fbx") != std::string::npos || fileName.find(".FBX") != std::string::npos) { std::unique_ptr<AssetModelFBX> model(new AssetModelFBX()); if (!model) return false; if(!model->load(fileName.c_str())) return nullptr; return model.release(); } // mqo return nullptr; } //--------------------------------------------------------------------------- //! モデル追加 //--------------------------------------------------------------------------- void AssetModelManager::addModel(const std::string& fileName, AssetModel* const assetModel) { assetModels_.insert(std::make_pair(fileName, assetModel)); }
#ifndef INC_1_LAB_MODULES_H #define INC_1_LAB_MODULES_H #include<iostream> #include<fstream> #include<cstdlib> #include<ctime> #include<cstring> using namespace std; //Класс class Hotel { string city; string name; int star; int freeVip, freeSimple; int busyVip, busySimple; public: //Hotel(const Hotel& temp); void setInfo(string city, string name, int star, int freeVip, int freeSimlple, int busyVip, int busySimple); string setCity() { return city; } //Город string setName() { return name; } //Название int setFreeVip() { return freeVip; } int setFreeSimple() {return freeSimple; } int setStar() { return star; } int setBusyVip() { return busyVip; } int setBusySimple() { return busySimple; } friend bool operator >= (Hotel &num1, Hotel& num2); friend bool operator <= (Hotel& num1, Hotel& num2); }; //Принимает данные о гостиницах void Hotel::setInfo(string city, string name, int star, int freeVip, int freeSimple, int busyVip, int busySimple) { this->city = city; this->name = name; this->star = star; this->freeSimple = freeSimple; this->freeVip = freeVip; this->busySimple = busySimple; this->busyVip = busyVip; } //Перегрузка операторов bool operator <=(Hotel& num1, Hotel& num2) { return num1.star < num2.star; } bool operator >=(Hotel& num1, Hotel& num2) { return num1.star > num2.star; } #endif
#ifndef __LOAM_COMMON_ROS_H__ #define __LOAM_COMMON_ROS_H__ #include <loam_velodyne/common.h> #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <pcl_conversions/pcl_conversions.h> void loadCloudFromMsg(const sensor_msgs::PointCloud2ConstPtr& msg, pcl::PointCloud<PointType>::Ptr out_cloud, double &out_time); template <typename PointT> void publishCloud(const pcl::PointCloud<PointT> &cloud, ros::Publisher &publisher, ros::Time stamp, std::string frame_id) { sensor_msgs::PointCloud2 msg; pcl::toROSMsg(cloud, msg); msg.header.stamp = stamp; msg.header.frame_id = frame_id; publisher.publish(msg); } #endif
#include "control.h" RRG::Control::Control() { RRG::InputManager& _inputManager = RRG::InputManager::Instance(); _inputManager.Register<RRG::InputObserver::MouseMoveEvent>([this](RRG::MouseMoveEventArg arg) { OnMouseMove(arg); }); } RRG::Control::~Control() { } void RRG::Control::OnMouseMove(RRG::MouseMoveEventArg arg) { RRG::Point _point = {arg.x, arg.y}; if (IsInside(&_point)) { Notify<RRG::ControlObserver::MouseOverEvent>(); _mouseover = true; } else if (_mouseover) { Notify<RRG::ControlObserver::MouseOutEvent>(); _mouseover = false; } }
#include "precompiled.h" #include "window/appwindow.h" #include "settings/settings.h" namespace eXistenZ { unique_ptr<AppWindow> g_appWindow; } using namespace eXistenZ; REGISTER_STARTUP_FUNCTION(AppWindow, &AppWindow::InitSettings, 10); void AppWindow::InitSettings() { settings::addsetting("system.window.position.x", settings::TYPE_INT, 0, NULL, NULL, NULL); settings::addsetting("system.window.position.y", settings::TYPE_INT, 0, NULL, NULL, NULL); settings::addsetting("system.window.title", settings::TYPE_STRING, 0, NULL, NULL, NULL); settings::setint("system.window.position.x", 0); settings::setint("system.window.position.y", 0); settings::setstring("system.window.title", "eXistenZ"); } AppWindow::AppWindow() : m_hwnd(0), m_fullscreen(false), m_visible(false), m_inputMode(IM_NORMAL), m_active(false), m_inSizeMove(false) { static bool registered = false; static const char* classname = "AppWindow"; if (!registered) { WNDCLASSEX wc; ZeroMemory(&wc, sizeof(wc)); wc.cbSize = sizeof(wc); wc.style = CS_CLASSDC; wc.hInstance = GetModuleHandle(NULL); wc.lpszClassName = classname; wc.lpfnWndProc = (WNDPROC)wndProcTrampoline; registered = (RegisterClassEx(&wc) != 0); ASSERT(registered); } m_hwnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, classname, "eXistenZ", WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, NULL, NULL, GetModuleHandle(NULL), this); ASSERT(m_hwnd); } AppWindow::~AppWindow() { if (m_hwnd) DestroyWindow(m_hwnd); } void AppWindow::setFullscreen(bool fullscreen) { if (m_fullscreen != fullscreen) { m_fullscreen = fullscreen; if (m_visible) showWindow(true); } } void AppWindow::setInputMode(InputMode mode) { if (mode == m_inputMode) return; if (mode == IM_RAW) { INFO("enabling raw input"); GetCursorPos(&m_oldMousePos); RAWINPUTDEVICE rid[1]; rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC; rid[0].usUsage = HID_USAGE_GENERIC_MOUSE; rid[0].dwFlags = RIDEV_CAPTUREMOUSE | RIDEV_NOHOTKEYS | RIDEV_NOLEGACY; rid[0].hwndTarget = m_hwnd; int ok = RegisterRawInputDevices(rid, 1, sizeof(rid[0])); ASSERT(ok); ShowCursor(FALSE); } else // mode == IM_NORMAL { INFO("disabling raw input"); RAWINPUTDEVICE rid[1]; rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC; rid[0].usUsage = HID_USAGE_GENERIC_MOUSE; rid[0].dwFlags = RIDEV_REMOVE; rid[0].hwndTarget = 0; // must be 0 or the following call fails int ok = RegisterRawInputDevices(rid, 1, sizeof(rid[0])); ASSERT(ok); SetCursorPos(m_oldMousePos.x, m_oldMousePos.y); ShowCursor(TRUE); } m_inputMode = mode; } void AppWindow::showWindow(bool show) { if (show) { if (m_fullscreen) { SetWindowLong(m_hwnd, GWL_EXSTYLE, WS_EX_TOPMOST); SetWindowLong(m_hwnd, GWL_STYLE, WS_POPUP | WS_VISIBLE); } else { SetWindowLong(m_hwnd, GWL_EXSTYLE, WS_EX_OVERLAPPEDWINDOW); SetWindowLong(m_hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE); } RECT r; r.left = settings::getint("system.window.position.x"); r.top = settings::getint("system.window.position.y"); r.right = r.left + settings::getint("system.render.resolution.x"); r.bottom = r.top + settings::getint("system.render.resolution.y"); AdjustWindowRectEx(&r, GetWindowLong(m_hwnd, GWL_STYLE), false, GetWindowLong(m_hwnd, GWL_EXSTYLE)); SetWindowPos(m_hwnd, HWND_NOTOPMOST, r.left, r.top, r.right - r.left, r.bottom - r.top, 0); UpdateWindow(m_hwnd); m_visible = true; } else { SetWindowPos( m_hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_HIDEWINDOW); m_visible = false; } } LRESULT AppWindow::onActivateApp(UINT msg, WPARAM w, LPARAM l) { m_active = w == TRUE; return 0; } LRESULT AppWindow::onKey(UINT msg, WPARAM w, LPARAM l) { if (((msg == WM_KEYDOWN) || (msg == WM_SYSKEYDOWN)) && (l & 1 << 30)) // ignore key repeat return DefWindowProc(m_hwnd, msg, w, l); if ((msg == WM_KEYDOWN) || (msg == WM_SYSKEYDOWN)) { if(KeyDown) KeyDown(KeyEventArgs((int)w, BS_PRESSED, l)); } else { if(KeyUp) KeyUp(KeyEventArgs((int)w, BS_RELEASED, l)); } return DefWindowProc(m_hwnd, msg, w, l); } LRESULT AppWindow::onChar(UINT msg, WPARAM w, LPARAM l) { if(KeyPressed) KeyPressed(KeyEventArgs((int)w, BS_PRESSED, l)); return DefWindowProc(m_hwnd, msg, w, l); } LRESULT AppWindow::onMouseMove(UINT msg, WPARAM w, LPARAM l) { if(MouseMove) MouseMove(MouseMoveEventArgs(GET_X_LPARAM(l), GET_Y_LPARAM(l), w)); return DefWindowProc(m_hwnd, msg, w, l); } LRESULT AppWindow::onMouseButton(UINT msg, WPARAM w, LPARAM l) { int button; ButtonState state; switch (msg) { case WM_LBUTTONDOWN: button = 0; state = BS_PRESSED; break; case WM_LBUTTONUP: button = 0; state = BS_RELEASED; break; case WM_RBUTTONDOWN: button = 1; state = BS_PRESSED; break; case WM_RBUTTONUP: button = 1; state = BS_RELEASED; break; case WM_MBUTTONDOWN: button = 2; state = BS_PRESSED; break; case WM_MBUTTONUP: button = 2; state = BS_RELEASED; break; } if(MouseButton) MouseButton(MouseButtonEventArgs(button, state, GET_X_LPARAM(l), GET_Y_LPARAM(l), w)); return DefWindowProc(m_hwnd, msg, w, l); } LRESULT AppWindow::onDestroy( UINT msg, WPARAM w, LPARAM l ) { if (m_inputMode == IM_RAW) // need to unregister raw input setInputMode(IM_NORMAL); PostQuitMessage(0); m_hwnd = 0; return 0; } LRESULT AppWindow::onRawInput(UINT msg, WPARAM w, LPARAM l) { UINT dwSize = 40; static BYTE lpb[40]; GetRawInputData((HRAWINPUT)l, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)); RAWINPUT* raw = (RAWINPUT*)lpb; if (raw->header.dwType == RIM_TYPEMOUSE) { RawMouseMove(RawMouseMoveEventArgs(raw->data.mouse.lLastX, raw->data.mouse.lLastY, 0)); if (raw->data.mouse.ulButtons & RI_MOUSE_LEFT_BUTTON_DOWN) RawMouseButton(MouseButtonEventArgs(0, BS_PRESSED)); if (raw->data.mouse.ulButtons & RI_MOUSE_LEFT_BUTTON_UP) RawMouseButton(MouseButtonEventArgs(0, BS_RELEASED)); if (raw->data.mouse.ulButtons & RI_MOUSE_RIGHT_BUTTON_DOWN) RawMouseButton(MouseButtonEventArgs(1, BS_PRESSED)); if (raw->data.mouse.ulButtons & RI_MOUSE_RIGHT_BUTTON_UP) RawMouseButton(MouseButtonEventArgs(1, BS_RELEASED)); if (raw->data.mouse.ulButtons & RI_MOUSE_MIDDLE_BUTTON_DOWN) RawMouseButton(MouseButtonEventArgs(2, BS_PRESSED)); if (raw->data.mouse.ulButtons & RI_MOUSE_MIDDLE_BUTTON_UP) RawMouseButton(MouseButtonEventArgs(2, BS_RELEASED)); } return DefWindowProc(m_hwnd, msg, w, l); } LRESULT AppWindow::onEnterSizeMove(UINT msg, WPARAM w, LPARAM l) { m_inSizeMove = true; return DefWindowProc(m_hwnd, msg, w, l); } LRESULT AppWindow::onExitSizeMove(UINT msg, WPARAM w, LPARAM l) { m_inSizeMove = false; if(!m_fullscreen && OnResize) { RECT r; GetClientRect(m_hwnd, &r); int width = r.right - r.left; int height = r.bottom - r.top; OnResize(width, height); } return DefWindowProc(m_hwnd, msg, w, l); } LRESULT AppWindow::onSize(UINT msg, WPARAM w, LPARAM l) { int width = LOWORD(l); int height = HIWORD(l); if(!m_inSizeMove && !m_fullscreen && OnResize) OnResize(width, height); return DefWindowProc(m_hwnd, msg, w, l); } LRESULT AppWindow::wndProc(UINT msg, WPARAM w, LPARAM l) { switch (msg) { case WM_ACTIVATEAPP: return onActivateApp(msg, w, l); case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: return onKey(msg, w, l); case WM_CHAR: return onChar(msg, w, l); case WM_MOUSEMOVE: return onMouseMove(msg, w, l); case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_RBUTTONDBLCLK: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_MBUTTONDBLCLK: return onMouseButton(msg, w, l); case WM_INPUT: return onRawInput(msg, w, l); case WM_DESTROY: return onDestroy(msg, w, l); case WM_ENTERSIZEMOVE: return onEnterSizeMove(msg, w, l); case WM_EXITSIZEMOVE: return onExitSizeMove(msg, w, l); case WM_SIZE: return onSize(msg, w, l); default: return DefWindowProc(m_hwnd, msg, w, l); } } LRESULT AppWindow::wndProcTrampoline( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { AppWindow* window = NULL; if (uMsg == WM_NCCREATE) { window = (AppWindow*)((LPCREATESTRUCT)lParam)->lpCreateParams; SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)window); window->m_hwnd = hWnd; } else { window = (AppWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA); if (!window) return DefWindowProc(hWnd, uMsg, wParam, lParam); } return window->wndProc(uMsg, wParam, lParam); }
#include "stdafx.h" #include "Enemy.h" #include "Tank.h" Enemy::Enemy() { } Enemy::~Enemy() { } HRESULT Enemy::Init() { _direction = TANKDIRECTION_UP; frameX = 0; frameY = 0; _image = IMAGE->AddImage("tank", "images/tank.bmp", 0, 0, 256, 128, 8, 4, true, RGB(255, 0, 255)); _speed = 100.0f; cnt = 0; currentDir = _direction; isLive = true; return S_OK; } void Enemy::Release() { } void Enemy::Update() { // 죽었거나 탱크가 죽으면 Update() 진행안하고 반환 if (!isLive || !tank->GetIsLive()) return; // 그냥 랜덤으로 이동 cnt++; if (cnt % 50 == 0) currentDir = (TANKDIRECTION)RND->GetInt(4); switch (currentDir) { case 0: // Left Move if (_x - (_rc.right - _rc.left) / 2 > 0) { _direction = TANKDIRECTION_LEFT; ray = Ray(_x, _y, -1 * WINSIZEX, 0 + _y); TankMove(); } break; case 1: // Right Move if (_x + (_rc.right - _rc.left) / 2 < WINSIZEX) { _direction = TANKDIRECTION_RIGHT; ray = Ray(_x, _y, 1 * WINSIZEX, 0 + _y); TankMove(); } break; case 2: // Up Move if (_y - (_rc.bottom - _rc.top) / 2 > 0) { _direction = TANKDIRECTION_UP; ray = Ray(_x, _y, 0 + _x, -1 * WINSIZEY); TankMove(); } break; case 3: // Down Move if (_y + (_rc.bottom - _rc.top) / 2 < WINSIZEY) { _direction = TANKDIRECTION_DOWN; ray = Ray(_x, _y, 0 + _x, 1 * WINSIZEY); TankMove(); } break; } _rc = RectMakeCenter(_x, _y, _image->GetFrameWidth(), _image->GetFrameHeight()); vTileIndex.clear(); for (int i = 0; i < TILEX*TILEY; i++) { if (_tankMap->GetTiles()[i].obj == OBJ_NONE) continue; if (_tankMap->GetTiles()[i].obj <= OBJ_BLOCK3) { if (ray.CollisionRect(_tankMap->GetTiles()[i].rc) //&& _tankMap->GetTiles()[i].obj != OBJ_NONE ) { vTileIndex.push_back(i); } } //if (_direction == TANKDIRECTION_LEFT // || _direction == TANKDIRECTION_UP) { // reverse(vTile.begin(), vTile.end()); //} } // 총알 발사 // 레이에 타일들 하나라도 걸리면 총알 발사 // 또는 탱크가 레이에 걸려도 발사 if (vTileIndex.size() != 0 || ray.CollisionRect(tank->GetRect())) { if (cnt % 25 == 0) { SOUND->Play("Fire", 0.5f); TankFire(); } } } void Enemy::Render() { // 죽었거나 탱크가 죽으면 Render() 진행안하고 반환 if (!isLive || !tank->GetIsLive()) return; ray.DrawRay(GetMemDC()); _image->FrameRender(GetMemDC(), _rc.left, _rc.top, frameX, frameY); //_image->Render(GetMemDC()); } void Enemy::TankMove() { RECT rcCollision; // 충돌 렉트 // 0은 내가 밟고있는 타일, 1은 내가 진행하고 있는 방향의 타일 int tileIndex[2]; int tileX, tileY; // 타일 x,y rcCollision = _rc; float elapsedTime = FRAME->GetElapsedTime(); float moveSpeed = elapsedTime * _speed; switch (_direction) { case TANKDIRECTION_LEFT: frameY = 3; _x -= moveSpeed; rcCollision = RectMakeCenter(_x, _y, _image->GetFrameWidth(), _image->GetFrameHeight()); break; case TANKDIRECTION_RIGHT: frameY = 2; _x += moveSpeed; rcCollision = RectMakeCenter(_x, _y, _image->GetFrameWidth(), _image->GetFrameHeight()); break; case TANKDIRECTION_UP: frameY = 0; _y -= moveSpeed; rcCollision = RectMakeCenter(_x, _y, _image->GetFrameWidth(), _image->GetFrameHeight()); break; case TANKDIRECTION_DOWN: frameY = 1; _y += moveSpeed; rcCollision = RectMakeCenter(_x, _y, _image->GetFrameWidth(), _image->GetFrameHeight()); break; } // 잘 통과하기 위해서 충돌판정하는 rc값만 1씩 작게 해주는거 rcCollision.left += 1; rcCollision.top += 1; rcCollision.right -= 1; rcCollision.bottom -= 1; // 현태 탱크가 어느 타일 위치에 있는지 계산 // 탱크 위치가 1, 40 이면 1 / 32 -> 0 , 40 / 32 -> 1이라 (0,1) 타일 위치 // 원래대로 따지면 중앙이 정확한데 left, top으로 설정하신거 tileX = (rcCollision.left + (rcCollision.right - rcCollision.left) / 2) / TILESIZE; tileY = (rcCollision.top + (rcCollision.bottom - rcCollision.top) / 2) / TILESIZE; switch (_direction) { case TANKDIRECTION_LEFT: tileIndex[0] = tileX + tileY * TILEX; tileIndex[1] = (tileX - 1) + tileY * TILEX; break; case TANKDIRECTION_RIGHT: tileIndex[0] = tileX + tileY * TILEX; tileIndex[1] = (tileX + 1) + tileY * TILEX; break; case TANKDIRECTION_UP: tileIndex[0] = tileX + tileY * TILEX; tileIndex[1] = tileX + (tileY - 1) * TILEX; break; case TANKDIRECTION_DOWN: tileIndex[0] = tileX + tileY * TILEX; tileIndex[1] = tileX + (tileY + 1) * TILEX; break; } for (int i = 0; i < 2; i++) { RECT temp; if ((_tankMap->GetAttribute()[tileIndex[i]] & ATTR_UNMOVE == ATTR_UNMOVE) && IntersectRect(&temp, &_tankMap->GetTiles()[tileIndex[i]].rc, &rcCollision)) { switch (_direction) { // 탱크의 위치 원위치로 case TANKDIRECTION_LEFT: _rc.left = _tankMap->GetTiles()[tileIndex[i]].rc.right; _rc.right = _rc.left + 32; _x = _rc.left + (_rc.right - _rc.left) / 2; break; case TANKDIRECTION_RIGHT: _rc.right = _tankMap->GetTiles()[tileIndex[i]].rc.left; _rc.left = _rc.right - 32; _x = _rc.left + (_rc.right - _rc.left) / 2; break; case TANKDIRECTION_UP: _rc.top = _tankMap->GetTiles()[tileIndex[i]].rc.bottom; _rc.bottom = _rc.top + 32; _y = _rc.top + (_rc.bottom - _rc.top) / 2; break; case TANKDIRECTION_DOWN: _rc.bottom = _tankMap->GetTiles()[tileIndex[i]].rc.top; _rc.top = _rc.bottom - 32; _y = _rc.top + (_rc.bottom - _rc.top) / 2; break; } } } // 할 필요는 없음 rcCollision = RectMakeCenter(_x, _y, _image->GetFrameWidth(), _image->GetFrameHeight()); } void Enemy::TankFire() { if (vTileIndex.size() != 0) { // 가장 가까운 타일 찾기 tagTile temp = _tankMap->GetTiles()[vTileIndex[0]]; int distance = GetDistance(_x, _y, temp.rc.left + (temp.rc.right - temp.rc.left) / 2, temp.rc.top + (temp.rc.bottom - temp.rc.top) / 2); int index = vTileIndex[0]; for (int i = 1; i < vTileIndex.size(); i++) { tagTile tempTile = _tankMap->GetTiles()[vTileIndex[i]]; int temp = GetDistance(_x, _y, tempTile.rc.left + (tempTile.rc.right - tempTile.rc.left) / 2, tempTile.rc.top + (tempTile.rc.bottom - tempTile.rc.top) / 2); if (temp < distance) { distance = temp; index = vTileIndex[i]; } } // 탱크와의 거리 계산해서 찾은 타일보다 탱크가 더 가까우면 에너미 제거 if (ray.CollisionRect(tank->GetRect()) && tank->GetIsLive() && distance > GetDistance(_x, _y, tank->GetRect().left + (tank->GetRect().right - tank->GetRect().left) / 2, tank->GetRect().top + (tank->GetRect().bottom - tank->GetRect().top) / 2)) { tank->SetIsLive(false); } // 타일이 가까우면 타일 제거 else { // 타일 처리 POINT pos; if (_tankMap->GetTiles()[index].obj == OBJ_BLOCK1) { _tankMap->GetTiles()[index].obj = OBJ_NONE; _tankMap->GetAttribute()[index] = 0; } else { _tankMap->GetTiles()[index].obj = (OBJECT)(_tankMap->GetTiles()[index].obj - 1); pos = _tankMap-> GetOBJECTFrame(_tankMap->GetTiles()[index].obj); _tankMap->GetTiles()[index].objFrameX = pos.x; _tankMap->GetTiles()[index].objFrameY = pos.y; } } } // 제거할 타일이 없을 때 else { // 탱크 제거 if (ray.CollisionRect(tank->GetRect())) { tank->SetIsLive(false); } } } void Enemy::SetTankPosition() { _rc = _tankMap->GetTiles()[_tankMap->GetPosSecond()].rc; _x = _rc.left + (_rc.right - _rc.left) / 2; _y = _rc.top + (_rc.bottom - _rc.top) / 2; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2004 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include <gtk/gtk.h> #include <stdio.h> #include "../mde.h" #define IMAGE_WIDTH 800 #define IMAGE_HEIGHT 600 void InitTest(); void ShutdownTest(); void PulseTest(); guchar rgbbuf[IMAGE_WIDTH * IMAGE_HEIGHT * 3]; guchar rgbabuf[IMAGE_WIDTH * IMAGE_HEIGHT * 4]; gboolean on_darea_expose (GtkWidget *widget, GdkEventExpose *event, gpointer user_data); void CopyRgbaToRgb() { int x, y; for (y = 0; y < IMAGE_HEIGHT; y++) { for (x = 0; x < IMAGE_WIDTH; x++) { rgbbuf[y * IMAGE_WIDTH * 3 + x * 3 + 2] = rgbabuf[y * IMAGE_WIDTH * 4 + x * 4]; rgbbuf[y * IMAGE_WIDTH * 3 + x * 3 + 1] = rgbabuf[y * IMAGE_WIDTH * 4 + x * 4 + 1]; rgbbuf[y * IMAGE_WIDTH * 3 + x * 3 + 0] = rgbabuf[y * IMAGE_WIDTH * 4 + x * 4 + 2]; } } } class GtkMdeScreen : public MDE_Screen { public: GtkMdeScreen(); ~GtkMdeScreen() {} // == Inherit MDE_View ======================================== virtual void OnPaint(const MDE_RECT &rect, MDE_BUFFER *screen); int GetBitsPerPixel(); void OutOfMemory(); MDE_FORMAT GetFormat(); MDE_BUFFER *LockBuffer(); void UnlockBuffer(MDE_Region *update_region); GtkWidget* m_window; private: MDE_BUFFER screen; }; GtkMdeScreen::GtkMdeScreen() { m_rect.w = IMAGE_WIDTH; m_rect.h = IMAGE_HEIGHT; Invalidate(m_rect); } void GtkMdeScreen::OnPaint(const MDE_RECT &rect, MDE_BUFFER *screen) { MDE_SetColor(MDE_RGB(69, 81, 120), screen); MDE_DrawRectFill(rect, screen); } int GtkMdeScreen::GetBitsPerPixel() { return 32; } void GtkMdeScreen::OutOfMemory() { printf("out of memory.\n"); } MDE_FORMAT GtkMdeScreen::GetFormat() { return MDE_FORMAT_BGRA32; } MDE_BUFFER *GtkMdeScreen::LockBuffer() { MDE_InitializeBuffer(IMAGE_WIDTH, IMAGE_HEIGHT, MDE_FORMAT_BGRA32, rgbabuf, NULL, &screen); return &screen; } void GtkMdeScreen::UnlockBuffer(MDE_Region *update_region) { CopyRgbaToRgb(); #define TRIVIAL_REDRAW #ifdef TRIVIAL_REDRAW GdkRectangle r = {0, 0, IMAGE_WIDTH, IMAGE_HEIGHT}; gdk_window_invalidate_rect(m_window->window, &r, true); #else // GdkRegion* reg = gdk_region_new(); for(int i = 0; i < update_region->num_rects; i++) { GdkRectangle r = {update_region->rects[i].x, update_region->rects[i].y, update_region->rects[i].w, update_region->rects[i].h}; gdk_window_invalidate_rect(m_window->window, &r, true); // gdk_region_union_with_rect(reg, &r); } // gdk_window_invalidate_region(m_window->window, reg, true); // gdk_region_destroy(reg); #endif // TRIVIAL_REDRAW } gboolean timeout(gpointer cdata) { ((GtkMdeScreen*)cdata)->Validate(true); PulseTest(); return true; } static int convert_gtk_mouse_button_to_mde(int gtk_button) { switch (gtk_button) { case 2: // middle button return 3; case 3: // right button return 2; case 1: default: return 1; } } gint mouse_evt_cb(GtkWidget *widget, GdkEvent *event, gpointer cdata) { GtkMdeScreen* win = (GtkMdeScreen*)cdata; switch(event->type) { case GDK_MOTION_NOTIFY: { // printf("GDK_MOTION_NOTIFY\n"); int x, y; gtk_widget_get_pointer(widget, &x, &y); win->TrigMouseMove((int)event->motion.x, (int)event->motion.y); return TRUE; } case GDK_BUTTON_PRESS: printf("GDK_BUTTON_PRESS\n"); win->TrigMouseDown((int)event->button.x, (int)event->button.y, convert_gtk_mouse_button_to_mde(event->button.button), 1); return TRUE; case GDK_BUTTON_RELEASE: printf("GDK_BUTTON_RELEASE\n"); win->TrigMouseUp((int)event->button.x, (int)event->button.y, convert_gtk_mouse_button_to_mde(event->button.button)); return TRUE; default: return FALSE; } } int main (int argc, char *argv[]) { GtkWidget *window, *darea; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); darea = gtk_drawing_area_new (); gtk_widget_set_size_request (darea, IMAGE_WIDTH, IMAGE_HEIGHT); gtk_container_add (GTK_CONTAINER (window), darea); gtk_widget_show_all (window); /* Set up the RGB buffer. */ guchar* pos = rgbabuf; for (int y = 0; y < IMAGE_HEIGHT; y++) { for (int x = 0; x < IMAGE_WIDTH; x++) { *pos++ = 1; *pos++ = 1; *pos++ = 1; *pos++; } } CopyRgbaToRgb(); GtkMdeScreen* screen = new GtkMdeScreen(); screen->m_window = window; gtk_signal_connect (GTK_OBJECT (darea), "expose-event", GTK_SIGNAL_FUNC (on_darea_expose), screen); g_signal_connect (GTK_OBJECT(window), "destroy", G_CALLBACK (gtk_main_quit), NULL); gtk_widget_add_events(darea, GDK_ALL_EVENTS_MASK); g_signal_connect( GTK_OBJECT(darea), "motion-notify-event", G_CALLBACK(mouse_evt_cb), screen); g_signal_connect( GTK_OBJECT(darea), "button-press-event", G_CALLBACK (mouse_evt_cb), screen); g_signal_connect( GTK_OBJECT(darea), "button-release-event", G_CALLBACK (mouse_evt_cb), screen); MDE_Init(screen); InitTest(); #ifdef NAIVE_TESTS MDE_BUFFER* buffer = screen->LockBuffer(); printf("Buffer: %p\n", buffer); MDE_SetColor(0x00ff00, buffer); MDE_RECT rect = MDE_MakeRect(50, 50, 100, 100); MDE_DrawRectFill(rect, buffer); MDE_SetColor(0x0000ff, buffer); MDE_DrawLine(150, 150, 190, 190, buffer); MDE_SetColor(0xff0000, buffer); MDE_DrawEllipseFill(rect, buffer); MDE_DrawRect(rect, buffer); buffer->method = MDE_METHOD_COLOR; screen->UnlockBuffer(NULL); CopyRgbaToRgb(); #endif // NAIVE_TESTS g_timeout_add(10, &timeout, screen); gtk_main (); ShutdownTest(); MDE_Shutdown(); return 0; } gboolean on_darea_expose(GtkWidget *widget, GdkEventExpose *event, gpointer user_data) { GdkGC* gc = widget->style->fg_gc[GTK_STATE_NORMAL]; #ifndef TRIVIAL_REDRAW gdk_gc_set_clip_origin(gc, event->area.x, event->area.y); gdk_gc_set_clip_rectangle(gc, &event->area); #endif // TRIVIAL_REDRAW gdk_draw_rgb_image(widget->window, gc, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, GDK_RGB_DITHER_MAX, rgbbuf, IMAGE_WIDTH * 3); return TRUE; }
#include "GnMeshPCH.h" #include "GnGamePCH.h" #include "GBackgroundLayer.h" GBackgroundLayer::GBackgroundLayer() { setIsTouchEnabled(true); } void GBackgroundLayer::ccTouchesBegan(CCSet* pTouches, CCEvent* event) { CCSetIterator it = pTouches->begin(); CCTouch* touch = (CCTouch*)(*it); CCPoint touchPoint = touch->locationInView( touch->view() ); if( mBackgroundRect.ContainsPoint( (gint)touchPoint.x, (gint)touchPoint.y ) == false ) return; mpCurrentTouch = touch; mIsMoveBackground = true; mLastBackgroundMovePostion = touchPoint; } void GBackgroundLayer::ccTouchesMoved(CCSet* pTouches, CCEvent* event) { CCSetIterator it = pTouches->begin(); CCTouch* touch = (CCTouch*)(*it); CCPoint touchPoint = touch->locationInView( touch->view() ); if( mpCurrentTouch != touch || mBackgroundRect.ContainsPoint( (gint)touchPoint.x, (gint)touchPoint.y ) == false ) { return; } float moveX = touchPoint.x - mLastBackgroundMovePostion.x; mLastBackgroundMovePostion = touchPoint; MoveLayer( moveX * 1.0f, 0.0f ); } void GBackgroundLayer::ccTouchesEnded(CCSet* pTouches, CCEvent* event) { CCSetIterator it = pTouches->begin(); CCTouch* touch = (CCTouch*)(*it); if( mpCurrentTouch == touch ) mpCurrentTouch = NULL; } void GBackgroundLayer::Create(CCSprite* pSprite) { CCSize bgSize = pSprite->getContentSize(); pSprite->setAnchorPoint( CCPointMake(0, 0) ); pSprite->setPosition( CCPointMake(0, GetGameState()->GetGameHeight() - bgSize.height ) ); addChild( pSprite ); setContentSize( pSprite->getContentSize() ); setAnchorPoint( CCPointZero ); mBackgroundRect.left = 0; mBackgroundRect.top = 0; mBackgroundRect.right = (gint32)bgSize.width; mBackgroundRect.bottom = (gint32)bgSize.height - 30; } void GBackgroundLayer::MoveLayer(float fDeltaX, float fDeltaY) { CCSize size = getContentSize(); CCPoint thisPosition = getPosition(); float maxLeftMovePos = GetGameState()->GetGameWidth() - size.width; if( fDeltaX < 0.0f && thisPosition.x <= maxLeftMovePos ) // left check return; if( fDeltaX > 0.0f && thisPosition.x >= 0.0f ) return; thisPosition.x += fDeltaX; if( fDeltaX > 0.0f && thisPosition.x >= 0.0f ) thisPosition.x = 0; if( fDeltaX < 0.0f && thisPosition.x <= maxLeftMovePos ) // left check thisPosition.x = maxLeftMovePos; setPosition( CCPointMake(thisPosition.x, thisPosition.y) ); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; int main() { int n; scanf("%d",&n); if (n%2) printf("%d %d\n",9,n-9); else printf("%d %d\n",4,n-4); return 0; }
#ifndef DIVIDE_H #define DIVID_H #include <iostream> #include "Operation.h" class Divide : public Operation{ public: Divide(); Divide(Base*, Base*); double evaluate(); }; #endif
#include <iostream> #include <string> #include <vector> using namespace std; void test01() { // static_cast用来转换内置的数据类型,和C语言的强制类型转换一样 int a = 1; char b = 2; double c = 3.14; a = static_cast<int>(b); a = static_cast<int>(c); c = static_cast<double>(a); } class A { public: int a; }; class B : public A { public: int b; }; void test02() { A *p1 = new A; B *p2 = new B; // static_cast不能转换没有发生继承关系的类 // p1 = static_cast<A*>(p2) ;//此时没写B继承A // 如果两个类之间发生了继承关系,可以类型转换 p1 = static_cast<A *>(p2); // 子转父 向上转换 是安全的 // p2 = static_cast<A *>(p1);//父转子 向下转换 是不安全的 } void test03() { int *p1 = NULL; char *p2 = NULL; // static_cast不能用来转指针 // p1 = static_cast<int *>(p2); } /****************************dynamic_cast动态转换*********************************/ // dynamic_cast void test04() { // 动态转换不能转内置的基本数据 int a = 1; char b = 2; // a = dynamic_cast<int>(b);//转不了 } void test05() { A *p1 = new A; B *p2 = new B; // dynamic不能用于没有发生继承关系之间的类型转换 // dynamic可以用于发生继承关系之间的类型转换 p1 = dynamic_cast<A *>(p2); // 子转父,安全 // p2 = dynamic_cast<A *>(p1);//父转子,不安全 } /****************************const_cast常量转换*********************************/ void test06() { int *p1 = NULL; const int *p2 = NULL; // int *p1 = static_cast<int *>(p2); p1 = const_cast<int *>(p2); p2 = const_cast<const int *>(p1); } /****************************reinterpret_cast重新解释转换*********************************/ void test07() { int *p1 = NULL; char *p2 = NULL; p1 = reinterpret_cast<int *>(p2); p2 = reinterpret_cast<char *>(p1); int c = 0; c = reinterpret_cast<int>(p2); } int main(int argc, char **argv) { return 0; }
#include <unordered_map> class File {}; class FileSystem { private: std::unordered_map<std::string, File> files; public: File& create(std::string); File& edit(std::string); const File& view(std::string); void destroy(std::string); };
#ifndef __HITTRACKER_H_INCLUDED__ #define __HITTRACKER_H_INCLUDED__ #include <string> #include <vector> class HitTracker { public: //Generators HitTracker(); HitTracker(unsigned long long hitCount, unsigned long long iterValue); HitTracker(std::vector<unsigned long long> hits, std::vector<unsigned long long> iters); ~HitTracker(); //Things to track std::vector<unsigned long long> hitCounts; std::vector<unsigned long long> iterValues; void export2csv(std::string name = "HitTracker.csv"); }; #endif
// Created on: 1992-10-02 // Created by: Christian CAILLET // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IFGraph_AllConnected_HeaderFile #define _IFGraph_AllConnected_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Interface_Graph.hxx> #include <Interface_GraphContent.hxx> class Standard_Transient; //! this class gives content of the CONNECTED COMPONENT(S) //! which include specific Entity(ies) class IFGraph_AllConnected : public Interface_GraphContent { public: DEFINE_STANDARD_ALLOC //! creates an AllConnected from a graph, empty ready to be filled Standard_EXPORT IFGraph_AllConnected(const Interface_Graph& agraph); //! creates an AllConnected which memorizes Entities Connected to //! a given one, at any level : that is, itself, all Entities //! Shared by it and Sharing it, and so on. //! In other terms, this is the content of the CONNECTED COMPONENT //! which include a specific Entity Standard_EXPORT IFGraph_AllConnected(const Interface_Graph& agraph, const Handle(Standard_Transient)& ent); //! adds an entity and its Connected ones to the list (allows to //! cumulate all Entities Connected by some ones) //! Note that if "ent" is in the already computed list,, no entity //! will be added, but if "ent" is not already in the list, a new //! Connected Component will be cumulated Standard_EXPORT void GetFromEntity (const Handle(Standard_Transient)& ent); //! Allows to restart on a new data set Standard_EXPORT void ResetData(); //! does the specific evaluation (Connected entities atall levels) Standard_EXPORT virtual void Evaluate() Standard_OVERRIDE; protected: private: Interface_Graph thegraph; }; #endif // _IFGraph_AllConnected_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef CANVAS_SUPPORT #ifdef CANVAS_TEXT_SUPPORT #include "modules/libvega/src/canvas/canvascontext2d.h" #include "modules/pi/OpScreenInfo.h" #include "modules/pi/ui/OpUiInfo.h" #include "modules/logdoc/htm_ldoc.h" #include "modules/logdoc/htm_elm.h" #include "modules/widgets/optextfragmentlist.h" #include "modules/widgets/optextfragment.h" #include "modules/svg/svg_path.h" #include "modules/doc/frm_doc.h" #include "modules/layout/cssprops.h" #include "modules/layout/cascade.h" #if defined USE_TEXTSHAPER_INTERNALLY && defined TEXTSHAPER_SUPPORT # include "modules/display/textshaper.h" #endif // USE_TEXTSHAPER_INTERNALLY && TEXTSHAPER_SUPPORT class TextFragment { public: void Set(const uni_char* fragtext, unsigned fraglen) { text = fragtext; textlen = fraglen; } OP_STATUS ApplyTransforms(TempBuffer& textbuf, bool reversed); const uni_char* Text() const { return text; } unsigned Length() const { return textlen; } private: const uni_char* text; unsigned textlen; }; OP_STATUS TextFragment::ApplyTransforms(TempBuffer& textbuf, bool reversed) { textbuf.Clear(); RETURN_IF_ERROR(textbuf.Expand(textlen)); size_t st_len = textlen; text = VisualDevice::TransformText(text, textbuf.GetStorage(), st_len, reversed ? TEXT_FORMAT_REVERSE_WORD : 0); textlen = (unsigned)st_len; return OpStatus::OK; } class CanvasCSSLineBoxTraverser { public: CanvasCSSLineBoxTraverser(CanvasContext2D::CanvasTextBaseline bline) : baseline_adjustment(0), baseline(bline) {} virtual OP_STATUS beforeTraverse(OpFont* font) { return OpStatus::OK; } virtual void updateBaseline(OpFont* font); virtual OP_STATUS handleFragment(OpFont* font, TextFragment& frag) = 0; protected: int baseline_adjustment; CanvasContext2D::CanvasTextBaseline baseline; }; void CanvasCSSLineBoxTraverser::updateBaseline(OpFont* font) { switch (baseline) { default: case CanvasContext2D::CANVAS_TEXTBASELINE_TOP: case CanvasContext2D::CANVAS_TEXTBASELINE_HANGING: // Emulated by 'top' baseline_adjustment = -(int)(font->Ascent()); break; case CanvasContext2D::CANVAS_TEXTBASELINE_MIDDLE: baseline_adjustment = -((int)font->Ascent() - (int)font->InternalLeading()) / 2; break; case CanvasContext2D::CANVAS_TEXTBASELINE_ALPHABETIC: baseline_adjustment = 0; break; case CanvasContext2D::CANVAS_TEXTBASELINE_IDEOGRAPHIC: // Slightly below the alphabetic baseline. baseline_adjustment = (int)font->Descent() / 8; break; case CanvasContext2D::CANVAS_TEXTBASELINE_BOTTOM: baseline_adjustment = (int)font->Descent(); break; } } class ExtentCalculator : public CanvasCSSLineBoxTraverser { public: ExtentCalculator() : CanvasCSSLineBoxTraverser(CanvasContext2D::CANVAS_TEXTBASELINE_ALPHABETIC) {} virtual OP_STATUS handleFragment(OpFont* font, TextFragment& frag); void reset() { extent = 0.0; } double getExtent() const { return extent; } private: double extent; }; OP_STATUS ExtentCalculator::handleFragment(OpFont* font, TextFragment& frag) { extent += font->StringWidth(frag.Text(), frag.Length()); return OpStatus::OK; } class GlyphOutlineBuilder : public CanvasCSSLineBoxTraverser { public: GlyphOutlineBuilder(VEGAPath* outl, CanvasContext2D::CanvasTextBaseline bline) : CanvasCSSLineBoxTraverser(bline), voutline(outl) {} virtual OP_STATUS beforeTraverse(OpFont* font); virtual OP_STATUS handleFragment(OpFont* font, TextFragment& frag); private: VEGAPath* voutline; VEGA_FIX gofs_x; }; struct CanvasTextContext { HLDocProfile* hld_profile; LayoutFixed font_size; int font_weight; int font_number; BOOL font_italic; BOOL font_smallcaps; enum Direction { DIR_LTR, DIR_RTL }; Direction direction; bool isRTL() const { return direction == DIR_RTL; } void resolveFont(CSS_property_list* font_props, FontAtt& fontatt) const; }; static CanvasTextContext::Direction CSSDirToCanvasDir(short cssdir) { if (cssdir == CSS_VALUE_rtl) return CanvasTextContext::DIR_RTL; return CanvasTextContext::DIR_LTR; } static OP_STATUS SetupTextContext(FramesDocument* frm_doc, HTML_Element* element, CanvasTextContext& textctx) { int direction, font_weight, font_number; LayoutFixed font_size = IntToLayoutFixed(10); // Default BOOL font_italic, font_smallcaps; HLDocProfile* hld_profile = frm_doc ? frm_doc->GetHLDocProfile() : NULL; if (hld_profile && element && hld_profile->GetRoot() && hld_profile->GetRoot()->IsAncestorOf(element)) { Head prop_list; LayoutProperties* cascade = LayoutProperties::CreateCascade(element, prop_list, hld_profile); if (!cascade) return OpStatus::ERR_NO_MEMORY; const HTMLayoutProperties& props = *cascade->GetProps(); direction = props.direction; if (props.decimal_font_size_constrained >= LayoutFixed(0)) font_size = props.decimal_font_size_constrained; font_weight = props.font_weight; font_italic = props.font_italic == FONT_STYLE_ITALIC; font_smallcaps = props.small_caps == CSS_VALUE_small_caps; font_number = props.font_number; cascade = NULL; prop_list.Clear(); } else { direction = (element && element->HasAttr(ATTR_DIR)) ? element->GetNumAttr(ATTR_DIR) : (int)CSS_VALUE_ltr; font_weight = 4; font_italic = FALSE; font_smallcaps = FALSE; font_number = -1; } textctx.hld_profile = hld_profile; textctx.font_size = font_size; textctx.font_weight = font_weight; textctx.font_italic = font_italic; textctx.font_smallcaps = font_smallcaps; textctx.font_number = font_number; textctx.direction = CSSDirToCanvasDir(direction); return OpStatus::OK; } class CanvasCSSLineBox { public: CanvasCSSLineBox(HLDocProfile* hld_profile) { frames_doc = hld_profile ? hld_profile->GetFramesDocument() : NULL; } OP_STATUS setText(const CanvasTextContext& ctx, CSS_property_list* font_props, const uni_char* text); OP_STATUS traverse(CanvasCSSLineBoxTraverser* trav); void determineMaxWidthFont(double maxwidth, VEGA_FIX& hscale); private: static void replaceSpaces(uni_char* text, unsigned len); FontAtt fontatt; OpTextFragmentList frag_list; TempBuffer buffer; FramesDocument* frames_doc; }; /* static */ void CanvasCSSLineBox::replaceSpaces(uni_char* text, unsigned len) { // U+0009 U+000A U+000C U+000D => U+0020 while (len-- > 0) { if (*text == '\x09' || *text == '\x0a' || *text == '\x0c' || *text == '\x0d') *text = ' '; text++; } } OP_STATUS CanvasCSSLineBox::setText(const CanvasTextContext& ctx, CSS_property_list* font_props, const uni_char* text) { unsigned text_len = uni_strlen(text); RETURN_IF_ERROR(buffer.Expand(text_len + 1)); buffer.Append(text); replaceSpaces(buffer.GetStorage(), text_len); ctx.resolveFont(font_props, fontatt); return frag_list.Update(buffer.GetStorage(), buffer.Length(), ctx.direction == CanvasTextContext::DIR_RTL, FALSE /* bidi override */, TRUE /* preserve spaces */, FALSE /* nbsp as space */, NULL /* frames doc. */, fontatt.GetFontNumber()); } void CanvasCSSLineBox::determineMaxWidthFont(double maxwidth, VEGA_FIX& hscale) { ExtentCalculator calculator; bool force_scale = false; while (true) { calculator.reset(); RETURN_VOID_IF_ERROR(traverse(&calculator)); double extent = calculator.getExtent(); double diff = extent - maxwidth; if (diff <= 0.0) { // The text fits - done. hscale = VEGA_INTTOFIX(1); break; } double f = maxwidth / extent; // Is is reasonable to just apply horizontal scaling? if (force_scale || f >= 0.95) { // Apply scale maxw. / ext. hscale = DOUBLE_TO_VEGA(f); break; } int old_height = fontatt.GetHeight(); // Try to approximate how much to reduce the current size int reduction = MAX((int)(old_height * (1.0 - f)), 1); // Size will reach zero => set to one and force scaling force_scale = (reduction >= old_height); fontatt.SetHeight(MAX(1, old_height - reduction)); if (!fontatt.GetChanged()) force_scale = true; } fontatt.ClearChanged(); } static bool alignmentNeedsExtent(const CanvasTextContext& textctx, CanvasContext2D::CanvasTextAlign align) { switch (align) { default: case CanvasContext2D::CANVAS_TEXTALIGN_START: return textctx.isRTL(); case CanvasContext2D::CANVAS_TEXTALIGN_END: return !textctx.isRTL(); case CanvasContext2D::CANVAS_TEXTALIGN_LEFT: break; case CanvasContext2D::CANVAS_TEXTALIGN_RIGHT: case CanvasContext2D::CANVAS_TEXTALIGN_CENTER: return true; } return false; } OP_STATUS GlyphOutlineBuilder::beforeTraverse(OpFont* font) { gofs_x = 0; SVGNumber advance; UINT32 curr_pos = 0; return font->GetOutline(NULL, 0, curr_pos, curr_pos, TRUE, advance, NULL); } OP_STATUS GlyphOutlineBuilder::handleFragment(OpFont* font, TextFragment& frag) { const uni_char* fragtext = frag.Text(); unsigned fraglen = frag.Length(); UINT32 last_pos = 0, curr_pos = 0; SVGNumber advance; OP_STATUS status = OpStatus::OK; while (curr_pos < fraglen) { SVGPath* outline = NULL; UINT32 prev_pos = curr_pos; // Fetch glyph (uncached, slow, et.c et.c) status = font->GetOutline(fragtext, fraglen, curr_pos, last_pos, TRUE, advance, &outline); if (OpStatus::IsError(status)) { if (OpStatus::IsMemoryError(status) || status == OpStatus::ERR_NOT_SUPPORTED) break; curr_pos++; continue; } last_pos = prev_pos; // Append glyph outline to path status = ConvertSVGPathToVEGAPath(outline, gofs_x, VEGA_INTTOFIX(baseline_adjustment), CANVAS_FLATNESS, voutline); OP_DELETE(outline); if (OpStatus::IsError(status)) break; gofs_x += advance.GetVegaNumber(); } return status; } OP_STATUS CanvasCSSLineBox::traverse(CanvasCSSLineBoxTraverser* trav) { const uni_char* text = buffer.GetStorage(); OpFont* font = g_font_cache->GetFont(fontatt, 100, frames_doc); if (!font) return OpStatus::ERR; OP_STATUS status = trav->beforeTraverse(font); if (OpStatus::IsError(status)) { g_font_cache->ReleaseFont(font); return status; } trav->updateBaseline(font); int starting_fontnumber = fontatt.GetFontNumber(); TextFragment tfrag; TempBuffer buf; for (unsigned int frag = 0; frag < frag_list.GetNumFragments(); ++frag) { OP_TEXT_FRAGMENT* fragment = frag_list.GetByVisualOrder(frag); bool mirrored = !!(fragment->packed.bidi & BIDI_FRAGMENT_ANY_MIRRORED); fontatt.SetFontNumber(fragment->wi.GetFontNumber()); if (fontatt.GetChanged()) { g_font_cache->ReleaseFont(font); font = g_font_cache->GetFont(fontatt, 100, frames_doc); if (!font) { status = OpStatus::ERR; break; } fontatt.ClearChanged(); trav->updateBaseline(font); } // Since we don't collapse whitespace, there is no need to // look at has_trailing_whitespace here, since any trailing // whitespace should be included in the fragment length // according to GetNextTextFragment documentation. if (fragment->wi.GetLength()) { tfrag.Set(text + fragment->wi.GetStart(), fragment->wi.GetLength()); status = tfrag.ApplyTransforms(buf, mirrored); if (OpStatus::IsError(status)) break; if (tfrag.Length() > 0) { status = trav->handleFragment(font, tfrag); if (OpStatus::IsError(status)) break; } } } if (font) g_font_cache->ReleaseFont(font); fontatt.SetFontNumber(starting_fontnumber); return status; } OP_STATUS CanvasContext2D::getTextOutline(const CanvasTextContext& ctx, const uni_char* text, double x, double y, double maxwidth, VEGAPath& voutline, VEGATransform& outline_transform) { CanvasCSSLineBox linebox(ctx.hld_profile); RETURN_IF_ERROR(linebox.setText(ctx, m_current_state.font, text)); VEGA_FIX hori_scale = VEGA_INTTOFIX(1); if (!op_isnan(maxwidth)) linebox.determineMaxWidthFont(maxwidth, hori_scale); GlyphOutlineBuilder builder(&voutline, m_current_state.textBaseline); RETURN_IF_ERROR(linebox.traverse(&builder)); outline_transform.loadTranslate(DOUBLE_TO_VEGA(x), DOUBLE_TO_VEGA(y)); if (alignmentNeedsExtent(ctx, m_current_state.textAlign)) { ExtentCalculator calculator; calculator.reset(); linebox.traverse(&calculator); VEGA_FIX tx = VEGA_INTTOFIX((int)calculator.getExtent()); if (m_current_state.textAlign == CANVAS_TEXTALIGN_CENTER) tx /= 2; outline_transform[2] -= tx; } outline_transform[0] = hori_scale; outline_transform[4] = VEGA_INTTOFIX(-1); return OpStatus::OK; } static short GetGenericFontFamily(short gen_font_value) { const uni_char* family_name = CSS_GetKeywordString(gen_font_value); StyleManager::GenericFont gf = StyleManager::GetGenericFont(family_name); return styleManager->GetGenericFontNumber(gf, WritingSystem::Unknown); } void CanvasTextContext::resolveFont(CSS_property_list* font_props, FontAtt& fontatt) const { fontatt.SetHasGetOutline(TRUE); fontatt.SetHeight(10); short fnum = GetGenericFontFamily(CSS_VALUE_sans_serif); fontatt.SetFontNumber(fnum != -1 ? fnum : 0); if (!font_props) return; FontAtt sys_font_att; BOOL sys_font_att_loaded = FALSE; CSS_decl* decl = font_props->GetFirstDecl(); while (decl) { switch (decl->GetProperty()) { case CSS_PROPERTY_font_size: { #define LOAD_SYSTEM_FONT(kw) (sys_font_att_loaded = sys_font_att_loaded || g_op_ui_info->GetUICSSFont(kw, sys_font_att)) int fsize = fontatt.GetHeight(); if (decl->GetDeclType() == CSS_DECL_NUMBER) { /* We need to get fixed point resolved font size and then round it to integer, so that the rounding rules are the same as when the font size is computed in a cascade. */ CSSLengthResolver length_resolver(hld_profile->GetVisualDevice(), TRUE, LayoutFixedToFloat(font_size), font_size, font_number, hld_profile->GetFramesDocument()->RootFontSize(), FALSE); LayoutFixed fixed_fsize = length_resolver.GetLengthInPixels(decl->GetNumberValue(0), decl->GetValueType(0)); fsize = LayoutFixedToIntNonNegative(fixed_fsize); } else if (decl->GetDeclType() == CSS_DECL_TYPE) { short fsize_type = decl->TypeValue(); if (fsize_type == CSS_VALUE_inherit) fsize = LayoutFixedToIntNonNegative(font_size); else if (fsize_type == CSS_VALUE_smaller) fsize = LayoutFixedToIntNonNegative(LayoutFixed(font_size * 0.8f)); else if (fsize_type == CSS_VALUE_larger) fsize = LayoutFixedToIntNonNegative(LayoutFixed(font_size * 1.2f)); else if (fsize_type == CSS_VALUE_use_lang_def) /* ignore? */; else if (CSS_is_fontsize_val(fsize_type)) { int size = fsize_type - CSS_VALUE_xx_small; const WritingSystem::Script script = #ifdef FONTSWITCHING hld_profile ? hld_profile->GetPreferredScript() : #endif // FONTSWITCHING WritingSystem::Unknown; FontAtt* font = styleManager->GetStyle(HE_DOC_ROOT)->GetPresentationAttr().GetPresentationFont(script).Font; OP_ASSERT(font); fsize = styleManager->GetFontSize(font, size); } else if (CSS_is_font_system_val(fsize_type)) { if (LOAD_SYSTEM_FONT(fsize_type)) fsize = sys_font_att.GetSize(); } } fontatt.SetHeight(fsize); } break; case CSS_PROPERTY_font_weight: { int fweight = 4; if (decl->GetDeclType() == CSS_DECL_NUMBER) { fweight = (int) decl->GetNumberValue(0); } else if (decl->GetDeclType() == CSS_DECL_TYPE) { short wtype = decl->TypeValue(); switch (wtype) { case CSS_VALUE_normal: break; case CSS_VALUE_inherit: fweight = font_weight; break; case CSS_VALUE_bold: fweight = 7; break; case CSS_VALUE_bolder: fweight = font_weight + 1; break; case CSS_VALUE_lighter: fweight = font_weight - 1; break; default: if (CSS_is_font_system_val(wtype)) { if (LOAD_SYSTEM_FONT(wtype)) { if (sys_font_att.GetWeight() >= 1 && sys_font_att.GetWeight() <= 9) fweight = sys_font_att.GetWeight(); } } } } if (fweight < 1) fweight = 1; else if (fweight > 9) fweight = 9; fontatt.SetWeight(fweight); } break; case CSS_PROPERTY_font_variant: if (decl->GetDeclType() == CSS_DECL_TYPE) { short variant = decl->TypeValue(); switch (variant) { case CSS_VALUE_normal: break; case CSS_VALUE_inherit: fontatt.SetSmallCaps(font_smallcaps); break; case CSS_VALUE_small_caps: fontatt.SetSmallCaps(TRUE); break; default: if (CSS_is_font_system_val(variant) && LOAD_SYSTEM_FONT(variant)) if (sys_font_att.GetSmallCaps()) fontatt.SetSmallCaps(TRUE); } } break; case CSS_PROPERTY_font_style: if (decl->GetDeclType() == CSS_DECL_TYPE) { short fstyle = decl->TypeValue(); switch (fstyle) { case CSS_VALUE_normal: break; case CSS_VALUE_inherit: fontatt.SetItalic(font_italic); break; case CSS_VALUE_oblique: case CSS_VALUE_italic: fontatt.SetItalic(TRUE); break; default: if (CSS_is_font_system_val(fstyle) && LOAD_SYSTEM_FONT(fstyle)) if (sys_font_att.GetItalic()) fontatt.SetItalic(TRUE); } } break; case CSS_PROPERTY_font_family: { if (decl->GetDeclType() == CSS_DECL_GEN_ARRAY) { const CSS_generic_value* arr = decl->GenArrayValue(); short arr_len = decl->ArrayValueLen(); for (int i = 0; i < arr_len; i++) { if (arr[i].value_type == CSS_IDENT) { if (arr[i].value.type & CSS_GENERIC_FONT_FAMILY) { short fnum = GetGenericFontFamily(arr[i].value.type & CSS_GENERIC_FONT_FAMILY_mask); if (fnum != -1) { fontatt.SetFontNumber(fnum); break; } } else if (styleManager->HasFont(arr[i].value.type)) { fontatt.SetFontNumber(arr[i].value.type); break; } } else if (arr[i].value_type == CSS_STRING_LITERAL) { short fnum = styleManager->LookupFontNumber(hld_profile, arr[i].value.string, CSS_MEDIA_TYPE_NONE/* FIXME: media_type */); if (fnum != -1) { fontatt.SetFontNumber(fnum); break; } } } } else if (decl->GetDeclType() == CSS_DECL_TYPE) { if (decl->TypeValue() == CSS_VALUE_inherit) if (font_number >= 0) fontatt.SetFontNumber(font_number); else if (decl->TypeValue() == CSS_VALUE_use_lang_def) ; else { if (LOAD_SYSTEM_FONT(decl->TypeValue())) { short fnum = styleManager->GetFontNumber(sys_font_att.GetFaceName()); if (fnum >= 0) fontatt.SetFontNumber(fnum); } } } } break; } #undef LOAD_SYSTEM_FONT decl = decl->Suc(); } } #ifdef VEGA_OPPAINTER_SUPPORT #include "modules/libvega/src/oppainter/vegaopfont.h" #include "modules/mdefont/processedstring.h" class RasterTextPainter : public CanvasCSSLineBoxTraverser { public: RasterTextPainter(VEGARenderer* r, VEGAStencil* c, CanvasContext2D::CanvasTextBaseline bline, int x, int y) : CanvasCSSLineBoxTraverser(bline), renderer(r), clip(c), pos_x(x), pos_y(y) {} virtual void updateBaseline(OpFont* font); virtual OP_STATUS handleFragment(OpFont* font, TextFragment& frag); private: void drawFragmentWithOutlines(OpFont* font, TextFragment& frag); VEGARenderer* renderer; VEGAStencil* clip; int pos_x, pos_y, ascent; }; void RasterTextPainter::updateBaseline(OpFont* font) { CanvasCSSLineBoxTraverser::updateBaseline(font); ascent = (int)font->Ascent(); } void RasterTextPainter::drawFragmentWithOutlines(OpFont* font, TextFragment& frag) { const uni_char* fragtext = frag.Text(); unsigned fraglen = frag.Length(); UINT32 last_pos = 0, curr_pos = 0; SVGNumber advance; VEGA_FIX gofs_y = VEGA_INTTOFIX(pos_y - ascent - baseline_adjustment); OP_STATUS status = OpStatus::OK; while (curr_pos < fraglen) { SVGPath* outline = NULL; UINT32 prev_pos = curr_pos; // Fetch glyph (uncached, slow, et.c et.c) status = font->GetOutline(fragtext, fraglen, curr_pos, last_pos, TRUE, advance, &outline); if (OpStatus::IsError(status)) { if (OpStatus::IsMemoryError(status) || status == OpStatus::ERR_NOT_SUPPORTED) break; curr_pos++; continue; } last_pos = prev_pos; VEGA_FIX gofs_x = VEGA_INTTOFIX(pos_x); VEGAPath voutline; status = ConvertSVGPathToVEGAPath(outline, gofs_x, gofs_y, CANVAS_FLATNESS, &voutline); OP_DELETE(outline); if (OpStatus::IsError(status)) break; renderer->fillPath(&voutline, clip); pos_x += VEGA_FIXTOINT(advance.GetVegaNumber()); } } OP_STATUS RasterTextPainter::handleFragment(OpFont* font, TextFragment& frag) { if (font->Type() == OpFontInfo::SVG_WEBFONT) { // Draw with outlines drawFragmentWithOutlines(font, frag); } else { const uni_char* fragtext = frag.Text(); unsigned fraglen = frag.Length(); VEGAOpFont* vegaopfont = static_cast<VEGAOpFont*>(font); VEGAFont* vegafont = vegaopfont->getVegaFont(); renderer->drawString(vegafont, pos_x, pos_y - ascent - baseline_adjustment, fragtext, fraglen, 0, -1, clip); pos_x += font->StringWidth(fragtext, fraglen); } return OpStatus::OK; } void CanvasContext2D::fillRasterText(const CanvasTextContext& ctx, const uni_char* text, int px, int py) { CanvasCSSLineBox linebox(ctx.hld_profile); RETURN_VOID_IF_ERROR(linebox.setText(ctx, m_current_state.font, text)); UINT32 col = m_current_state.fill.color; if (m_current_state.alpha != 0xff) { unsigned int alpha = col >> 24; alpha *= m_current_state.alpha; alpha >>= 8; col = (col&0xffffff) | (alpha<<24); } m_vrenderer->setColor(col); m_vrenderer->setRenderTarget(m_buffer); px += VEGA_FIXTOINT(m_current_state.transform[2]); py += VEGA_FIXTOINT(m_current_state.transform[5]); if (alignmentNeedsExtent(ctx, m_current_state.textAlign)) { ExtentCalculator calculator; calculator.reset(); linebox.traverse(&calculator); int extent = (int)calculator.getExtent(); if (m_current_state.textAlign == CANVAS_TEXTALIGN_CENTER) extent /= 2; px -= extent; } RasterTextPainter tpainter(m_vrenderer, m_current_state.clip, m_current_state.textBaseline, px, py); RETURN_VOID_IF_ERROR(linebox.traverse(&tpainter)); } #endif // VEGA_OPPAINTER_SUPPORT void CanvasContext2D::setFont(CSS_property_list* font, FramesDocument* frm_doc, HTML_Element* element) { if (m_current_state.font) m_current_state.font->Unref(); m_current_state.font = font; CanvasTextContext ctx; if (OpStatus::IsSuccess(SetupTextContext(frm_doc, element, ctx))) { FontAtt att; ctx.resolveFont(font, att); // Load font. } } void CanvasContext2D::fillText(FramesDocument* frm_doc, HTML_Element* element, const uni_char* text, double x, double y, double maxwidth) { if (!m_canvas) return; CanvasTextContext ctx; RETURN_VOID_IF_ERROR(SetupTextContext(frm_doc, element, ctx)); #ifdef VEGA_OPPAINTER_SUPPORT // Fast-path check: // - color fill // - no maxwidth specified // - src-over composite // - 'simple CTM' // - no shadow // - (x, y) aligned to pixelgrid if (isFillColor() && op_isnan(maxwidth) && m_current_state.compOperation == CANVAS_COMP_SRC_OVER && m_current_state.transform.isIntegralTranslation() && !shouldDrawShadow()) { fillRasterText(ctx, text, (int)x, (int)y); return; } #endif // VEGA_OPPAINTER_SUPPORT VEGAPath outline; VEGATransform outline_transform; RETURN_VOID_IF_ERROR(getTextOutline(ctx, text, x, y, maxwidth, outline, outline_transform)); VEGATransform xfrm; xfrm.copy(m_current_state.transform); xfrm.multiply(outline_transform); outline.transform(&xfrm); FillParams parms; parms.paint = &m_current_state.fill; fillPath(parms, outline); } void CanvasContext2D::strokeText(FramesDocument* frm_doc, HTML_Element* element, const uni_char* text, double x, double y, double maxwidth) { if (!m_canvas) return; CanvasTextContext ctx; RETURN_VOID_IF_ERROR(SetupTextContext(frm_doc, element, ctx)); VEGAPath outline; VEGATransform outline_transform; RETURN_VOID_IF_ERROR(getTextOutline(ctx, text, x, y, maxwidth, outline, outline_transform)); VEGAPath stroked_outline; outline.setLineWidth(m_current_state.lineWidth); outline.setLineCap(m_current_state.lineCap); outline.setLineJoin(m_current_state.lineJoin); outline.setMiterLimit(m_current_state.miterLimit); outline.createOutline(&stroked_outline, CANVAS_FLATNESS, 0); // FIXME:OOM VEGATransform xfrm; xfrm.copy(m_current_state.transform); xfrm.multiply(outline_transform); stroked_outline.transform(&xfrm); FillParams parms; parms.paint = &m_current_state.stroke; fillPath(parms, stroked_outline); } OP_STATUS CanvasContext2D::measureText(FramesDocument* frm_doc, HTML_Element* element, const uni_char* text, double* text_extent) { *text_extent = 0.0; if (!m_canvas) return OpStatus::OK; CanvasTextContext ctx; RETURN_IF_ERROR(SetupTextContext(frm_doc, element, ctx)); CanvasCSSLineBox linebox(ctx.hld_profile); RETURN_IF_ERROR(linebox.setText(ctx, m_current_state.font, text)); ExtentCalculator calculator; calculator.reset(); RETURN_IF_ERROR(linebox.traverse(&calculator)); *text_extent = calculator.getExtent(); return OpStatus::OK; } #endif // CANVAS_TEXT_SUPPORT #endif // CANVAS_SUPPORT
// BSD 3-Clause License // // Copyright (c) 2020-2021, bodand // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once // stdlib #include <optional> #include <type_traits> // project #include "_macros.hpp" #ifndef INFO_USE_UNEXPECTED # ifdef _MSC_VER # define INFO_UNEXPECTED unexpected_ # else # define INFO_UNEXPECTED unexpected # endif #else # define INFO_UNEXPECTED INFO_USE_UNEXPECTED #endif namespace info { template<class T> struct INFO_UNEXPECTED { T value; explicit INFO_UNEXPECTED(const T& value) noexcept : value{value} { } }; /** * \brief A exception handling type which contains the value or the reason * why there is no value. * * A type which stores either the value as expected from a successful computation * or an exception (of some type) which can be inspected as for why the computation * failed. * * Inspired by Andrei Alexandrescu's 'Expect the expected' talk on CppCon 2018: * https://www.youtube.com/watch?v=PH4WBuE1BHI * * \note If the expected value is nothing, for example a function is only called * for its side-effects use `expected<void, E>`. * * \tparam T The expected Type * \tparam E The Exception type. * * \since 1.1 * \author bodand */ template<class T, class E> struct expected { /** * \brief Returns whether the computation was successful. */ INFO_NODISCARD("Success check always returns value") bool success() const noexcept; /** * \brief Returns the value, or throws if computation failed. * * Returns the value as returned by a successful computation, * or, if the computation happed to fail, it throws * the exception returned by it. * * \return The return value of the successful computation * \throws The exception reported by the failed computation */ INFO_NODISCARD("Value accessor returns or throws") T value() const; /** * \brief Returns the stored value if it exists, or the supplied * one otherwise. * * Returns the value returned by a successful computation, or the passed * argument static converted to type T, when the computation has failed. * * \tparam U The type of the parameter. Mut be convertible to T. * * \return The stored value, or the passed argument depending on the * success of the original computation. */ template<class U> INFO_NODISCARD("Value_or accessor always returns") T value_or(U&&) const noexcept( noexcept(static_cast<T>(std::forward<U>(std::declval<U>())))); /** * \copydoc value */ INFO_NODISCARD("Dereference operator returns value or throws") T operator*() const; /** * \brief Allows the returned value to be accessed through a pseudo-pointer * interface. Throws if computation failed. * * \return A pointer to the return value of the successful computation * \throws The exception reported by the failed computation */ INFO_NODISCARD("Pointer access operator returns or throws") const T* operator->() const; /** * \brief Allows the returned value to be accessed through a pseudo-pointer * interface. Throws if computation failed. * * \return A pointer to the return value of the successful computation * \throws The exception reported by the failed computation */ INFO_NODISCARD("Pointer access operator returns or throws") T* operator->(); /** * \brief Returns the error. * * Returns the error returned by a failed computation. * If the computation succeeded the behavior is undefined. */ INFO_NODISCARD("Error accessor returns") E error() const noexcept; /** * \brief Throws the contained exception. * * Throws the exception returned from a failed computation. * If the computation succeeded the behavior is undefined. */ void yeet() const; /** * \brief Calls the provided functor on the value, if it exists. Nop otherwise. * * Applies the functor passed to the successful value if possible. If * not, the current exception is propagated further. * * \tparam F The type of the functor * * \return An expected which may contain the value got from the successful * application of the functor, or the currently contained exception. */ template<class F> INFO_NODISCARD("Apply returns the F of the moved version of the current value") expected<std::invoke_result_t<F, T>, E> apply(F&&) const noexcept(std::is_nothrow_invocable_v<F, T>); /** * \brief Calls the provided functor on the value, if it exists. Nop otherwise. * * Applies the functor passed to the successful value if possible. If * not, the current exception is propagated further. * * \tparam F The type of the functor * * \return An expected which may contain the value got from the successful * application of the functor, or the currently contained exception. */ template<class F> expected<std::invoke_result_t<F, T>, E> operator()(F&&) const noexcept(std::is_nothrow_invocable_v<F, T>); /** * \brief Returns whether the computation was successful. */ explicit operator bool() const noexcept; template<typename = std::enable_if_t<std::is_default_constructible_v<T>>> expected() noexcept(std::is_nothrow_default_constructible_v<T>); expected(const T&) noexcept(std::is_nothrow_copy_constructible_v<T>); expected(T&&) noexcept(std::is_nothrow_move_constructible_v<T>); expected(const INFO_UNEXPECTED<E>&) noexcept(std::is_nothrow_copy_constructible_v<E>); expected(INFO_UNEXPECTED<E>&&) noexcept(std::is_nothrow_move_constructible_v<E>); expected(const expected<T, E>& cp) noexcept( std::is_nothrow_copy_constructible_v<T>&& std::is_nothrow_copy_constructible_v<E>); expected(expected<T, E>&& mv) noexcept( std::is_nothrow_move_constructible_v<T>&& std::is_nothrow_move_constructible_v<E>); template<class U, typename = std::enable_if_t<std::is_constructible_v<T, U>>> explicit expected(U&&) noexcept(std::is_nothrow_constructible_v<T, U>); virtual ~expected(); private: union { T _succ; ///< Stores the successful computation's return value E _fail; ///< Stores the failed computation's return value }; bool _ok{true}; ///< Whether or not the computation succeeded }; template<class T, class E> bool expected<T, E>::success() const noexcept { return _ok; } template<class T, class E> T expected<T, E>::value() const { if (INFO_UNLIKELY_(!_ok)) INFO_UNLIKELY yeet(); return _succ; } template<class T, class E> template<class U> T expected<T, E>::value_or(U&& other) const noexcept( noexcept(static_cast<T>(std::forward<U>(std::declval<U>())))) { if (INFO_LIKELY_(_ok)) INFO_LIKELY { return _succ; } return static_cast<T>(std::forward<T>(other)); } template<class T, class E> T expected<T, E>::operator*() const { return value(); } template<class T, class E> const T* expected<T, E>::operator->() const { if (INFO_LIKELY_(_ok)) INFO_LIKELY { return &_succ; } throw _fail; } template<class T, class E> T* expected<T, E>::operator->() { if (INFO_LIKELY_(_ok)) INFO_LIKELY { return &_succ; } throw _fail; } template<class T, class E> E expected<T, E>::error() const noexcept { return _fail; } template<class T, class E> void expected<T, E>::yeet() const { throw _fail; } template<class T, class E> template<class F> expected<std::invoke_result_t<F, T>, E> expected<T, E>::apply(F&& f) const noexcept(std::is_nothrow_invocable_v<F, T>) { if (INFO_LIKELY_(_ok)) INFO_LIKELY { return std::forward<F>(f)(std::move(_succ)); } return INFO_UNEXPECTED{std::move(_fail)}; } template<class T, class E> template<class F> expected<std::invoke_result_t<F, T>, E> expected<T, E>::operator()(F&& f) const noexcept(std::is_nothrow_invocable_v<F, T>) { return apply(std::forward<F>(f)); } template<class T, class E> expected<T, E>::operator bool() const noexcept { return _ok; } template<class T, class E> template<typename> expected<T, E>::expected() noexcept(std::is_nothrow_default_constructible_v<T>) { new (&_succ) T{}; } template<class T, class E> expected<T, E>::expected(const T& succ) noexcept(std::is_nothrow_copy_constructible_v<T>) { new (&_succ) T{succ}; } template<class T, class E> expected<T, E>::expected(T&& succ) noexcept(std::is_nothrow_move_constructible_v<T>) { new (&_succ) T{std::move(succ)}; } template<class T, class E> expected<T, E>::expected(const INFO_UNEXPECTED<E>& unexp) noexcept( std::is_nothrow_copy_constructible_v<E>) : _ok{false} { new (&_fail) E{unexp.value}; } template<class T, class E> expected<T, E>::expected(INFO_UNEXPECTED<E>&& un) noexcept( std::is_nothrow_move_constructible_v<E>) : _ok(false) { new (&_fail) E{std::move(un.value)}; } template<class T, class E> template<class U, typename> expected<T, E>::expected(U&& other) noexcept(std::is_nothrow_constructible_v<T, U>) { new (&_succ) T{std::forward<U>(other)}; } template<class T, class E> expected<T, E>::expected(const expected<T, E>& cp) noexcept( std::is_nothrow_copy_constructible_v<T>&& std::is_nothrow_copy_constructible_v<E>) : _ok{cp._ok} { // clang-format off if (INFO_LIKELY_(_ok)) INFO_LIKELY { new (&_succ) T{cp._succ}; } else { new (&_fail) E{cp._fail}; } // clang-format on } template<class T, class E> expected<T, E>::expected(expected<T, E>&& mv) noexcept( std::is_nothrow_move_constructible_v<T>&& std::is_nothrow_move_constructible_v<E>) : _ok{mv._ok} { // clang-format off if (INFO_LIKELY_(_ok)) INFO_LIKELY { new (&_succ) T{std::move(mv._succ)}; } else { new (&_fail) E{std::move(mv._fail)}; } // clang-format on } template<class T, class E> expected<T, E>::~expected() { // clang-format off if (INFO_LIKELY_(_ok)) INFO_LIKELY { _succ.~T(); } else { _fail.~E(); } // clang-format on } // void Specialization /////////////////////////////////////////////////////// template<class E> struct expected<void, E> { /** * \brief Returns whether the computation was successful. */ INFO_NODISCARD("Success check always returns value") bool success() const noexcept; /** * \brief Returns the error. * * Returns the error returned by a failed computation. * If the computation succeeded the behavior is undefined. */ INFO_NODISCARD("Error accessor always returns") E error() const noexcept; /** * \brief Throws the contained exception. * * Throws the exception returned from a failed computation. * If the computation succeeded the behavior is undefined. */ void yeet() const; /** * \brief Returns whether the computation was successful. */ explicit operator bool() const noexcept; expected() noexcept; expected(const INFO_UNEXPECTED<E>&) noexcept(std::is_nothrow_copy_constructible_v<E>); expected(const expected& cp) noexcept( std::is_nothrow_copy_constructible_v<E>) = default; expected(expected&& mv) noexcept( std::is_nothrow_move_constructible_v<E>) = default; private: std::optional<E> _err; }; template<class E> bool expected<void, E>::success() const noexcept { return (bool) _err; } template<class E> E expected<void, E>::error() const noexcept { return *_err; } template<class E> void expected<void, E>::yeet() const { throw *_err; } template<class E> expected<void, E>::operator bool() const noexcept { return (bool) _err; } template<class E> expected<void, E>::expected() noexcept : _err{std::nullopt} { } template<class E> expected<void, E>::expected(const INFO_UNEXPECTED<E>& unexp) noexcept( std::is_nothrow_copy_constructible_v<E>) : _err{unexp.value} { } } #ifdef INFO_USE_UNEXPECTED # undef INFO_UNEXPECTED #endif
#pragma once #include "pytorchcpp.h" #include <torch\torch.h> #include <torch\cuda.h> #include <fstream> // debugging dll load by metatrader 5 output to txt file -> located where it started #include <mutex> #define GIGABytes 1073741824.0 namespace th = torch; extern std::ofstream debugfile; // have only used once or twice for debugging extern std::mutex m; // to ensure Metatrader only calls on GPU extern c10::TensorOptions dtype32_option; extern c10::TensorOptions dtype64_option; extern c10::TensorOptions dtypeL_option; extern c10::TensorOptions dtype_option; extern th::Device deviceCPU; extern th::Device deviceifGPU;
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SKLAND_WAYLAND_REGISTRY_HPP_ #define SKLAND_WAYLAND_REGISTRY_HPP_ #include "display.hpp" namespace skland { namespace wayland { /** * @ingroup wayland */ class Registry { Registry(const Registry &) = delete; Registry &operator=(const Registry &) = delete; public: Registry() : wl_registry_(nullptr) { } ~Registry() { if (wl_registry_) wl_registry_destroy(wl_registry_); } void Setup(const Display &display) { Destroy(); wl_registry_ = wl_display_get_registry(display.wl_display_); wl_registry_add_listener(wl_registry_, &kListener, this); } void Destroy() { if (wl_registry_) { wl_registry_destroy(wl_registry_); wl_registry_ = nullptr; } } void *Bind(uint32_t name, const struct wl_interface *interface, uint32_t version) const { return wl_registry_bind(wl_registry_, name, interface, version); } void SetUserData(void *user_data) { wl_registry_set_user_data(wl_registry_, user_data); } void *GetUserData() const { return wl_registry_get_user_data(wl_registry_); } uint32_t GetVersion() const { return wl_registry_get_version(wl_registry_); } bool IsValid() const { return nullptr != wl_registry_; } bool Equal(const void *object) const { return wl_registry_ == object; } DelegateRef<void(uint32_t, const char *, uint32_t)> global() { return global_; } DelegateRef<void(uint32_t)> global_remove() { return global_remove_; } private: static void OnGlobal(void *data, struct wl_registry *registry, uint32_t id, const char *interface, uint32_t version); static void OnGlobalRemove(void *data, struct wl_registry *registry, uint32_t name); static const struct wl_registry_listener kListener; struct wl_registry *wl_registry_; Delegate<void(uint32_t, const char *, uint32_t)> global_; Delegate<void(uint32_t)> global_remove_; }; } } #endif // SKLAND_WAYLAND_REGISTRY_HPP_
DOUBLE PRECISION SCALFA COMMON/SCALF/ SCALFA
#include <bits/stdc++.h> using namespace std; int prob[102]={}; int main() { int carc[4]; int n, m, c, ant, ant2; carc[0] = carc[1] = carc[2] = carc[3] = 1; while(scanf("%d %d", &n, &m) && n && m) { for(int i=0;i<n;i++) { ant = 1; ant2 = 0; for(int j=0;j<m;j++) { scanf("%d", &c); if(c==1) prob[j]++, ant2 = 1; else ant = 0; } if(ant == 1) carc[0] = 0; if(ant2 == 0) carc[3] = 0; } for(int i=0;i<m;i++) { if(prob[i]==0) carc[1] = 0; else if(prob[i]==n) carc[2] = 0; prob[i] = 0; } printf("%d\n", carc[0] + carc[1] + carc[2] + carc[3]); carc[0] = carc[1] = carc[2] = carc[3] = 1; } return 0; }
#include <iostream> #include <math.h> using namespace std; int main(){ int x,y,sumx=0,sumy=0; cout<<"Ingrese X: "; cin>>x; sumx==x; cout<<"Ingrese Y: "; sumy==y; cin>>y; cout<<"\n============================\n"; while (x!=0 && y!=0){ cout<<"Ingrese X: "; cin>>x; sumx+=x; cout<<"Ingrese Y: "; cin>>y; sumy+=y; cout<<"\n============================\n"; } cout<<"\nLa suma de X es: "<<sumx<<" \nLa suma de Y es: "<<sumy; return 0; }
bool isSafe(int x,int y,int n,int m){ return (x>=0&&y>=0&&x<n&&y<m); } int Solution::black(vector<string> &A) { queue<pair<int,int>> q; int n = A.size(); int m = A[0].size(); int count = 0; for(int i =0;i<n;i++){ for(int j =0;j<m;j++){ if(A[i][j]=='X'){ count++; q.push({i,j}); while(!q.empty()){ int x = q.front().first; int y = q.front().second; q.pop(); A[x][y]='O'; if(isSafe(x+1,y,n,m)&&A[x+1][y]=='X') q.push({x+1,y}); if(isSafe(x,y+1,n,m)&&A[x][y+1]=='X') q.push({x,y+1}); if(isSafe(x-1,y,n,m)&&A[x-1][y]=='X') q.push({x-1,y}); if(isSafe(x,y-1,n,m)&&A[x][y-1]=='X') q.push({x,y-1}); } } } } return count; }
#include "reactor/net/http/HttpContext.h" #include "reactor/base/strings/strings.h" using namespace std; using namespace reactor::base; namespace reactor { namespace net { namespace http { void HttpContext::parse(const TcpConnectionPtr &conn) { char *data = conn->buffer()->as_str(); char *line = data; char *crlf = nullptr; while (!finished() && !error() && (crlf=strstr(line, "\r\n")) != nullptr) { *crlf = '\0'; switch (state_) { case kRequestLine: parse_request_line(line); break; case kHeader: parse_header(line); break; case kBody: // TODO break; default: printf("unknown state %d\n", state_); } line = crlf + 2; // move to next line } std::string value = strings::lower(request_.header("Connection")); if (value == "close") { close_connection_ = true; } else if (value == "keep-alive" && request_.version() >= "HTTP/1.1") { close_connection_ = false; } conn->buffer()->retrieve(static_cast<int>(line - data)); } void HttpContext::parse_request_line(const std::string &line) { string command, url, version; assert(state_ == kRequestLine); if (line.size() >= 65535) { set_error(1, "invalid request"); return; } vector<string> words = strings::split(line, ' '); if (words.size() == 3) { command = words[0]; url = words[1]; version = words[2]; if (version.substr(0, 5) != "HTTP/") { set_error(400, "Bad request version " + version); return; } vector<string> version_numbers = strings::split(version.substr(5), '.'); if (version_numbers.size() != 2) { set_error(400, "Bad request version " + version); return; } unsigned v1, v2; bool b1, b2; v1 = strings::to_uint(version_numbers[0], &b1); v2 = strings::to_uint(version_numbers[1], &b2); if (!b1 || !b2) { set_error(400, "Bad request version " + version); return; } if (v1 >= 2) { set_error(505, "Invalid HTTP Version " + version); return; } if (v2 >= 1 && v2 >= 1) { close_connection_ = false; } } else if (words.size() == 2) { command = words[0]; url = words[1]; close_connection_ = true; if (command != "GET") { set_error(400, "Bad HTTP/0.9 request type " + command); return; } } else { set_error(400, "Bad request syntax " + line); return; } request_.set_method(command); request_.set_url(url); request_.set_version(version); size_t question = url.find('?'); if (question != string::npos) { request_.set_path(url.substr(0, question)); request_.set_query(url.substr(question+1)); } else { request_.set_path(url); } state_ = kHeader; } void HttpContext::parse_header(const std::string &line) { if (line.size() >= 65535) { set_error(400, "Bad request header (too long)"); return; } if (line.empty()) { state_ = kFinish; return; } size_t colon = line.find(':'); if ((colon != string::npos) && (colon != (line.size() - 1))) { request_.set_header(line.substr(0, colon), line.substr(colon+1)); } else { set_error(400, "Bad request header " + line); } } void HttpContext::set_error(int err, const std::string &msg) { error_code_ = err; error_msg_ = msg; } } // namespace http } // namespace net } // namespace reactor
/* Exp no : 11 Stop and wait SW simulation S1330-R-Jayadeep 06/10/2016 */ #include<iostream> #include<random> using namespace std; class Socket{ string data; public: int receive(char c,int seq){ if(random()%2){ data+=c; return seq; } else return -1; } string receivedData(){ return data; } }; int main(){ string input; cout<<"Enter input string : "; cin>>input; Socket socket; int ack; for(int i=0;i<input.length();i++){ do{ cout<<"Sending "<<input[i]<<endl; ack = socket.receive(input[i],i); cout<<"Received ack : "<<ack<<endl; }while(ack!=i); } cout<<"Received : "+socket.receivedData()<<endl; return 0; } /************************OUTPUT*************************** Enter input string : helloworld Sending h Received ack : 0 Sending e Received ack : -1 Sending e Received ack : 1 Sending l Received ack : 2 Sending l Received ack : 3 Sending o Received ack : 4 Sending w Received ack : -1 Sending w Received ack : -1 Sending w Received ack : 5 Sending o Received ack : 6 Sending r Received ack : -1 Sending r Received ack : 7 Sending l Received ack : -1 Sending l Received ack : 8 Sending d Received ack : 9 Received : helloworld *************************************************/ Result -------- Program is executed and output is verified
#ifndef LISTOFCONSTANTLENGTHREADS_H_INCLUDED #define LISTOFCONSTANTLENGTHREADS_H_INCLUDED #define ORIGINAL_INDEX_OFFSET (FLAGS_OFFSET+1) #include "ReadsListInterface.h" using namespace PgSAReadsSet; namespace PgSAIndex { template < typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, // size of list element in uchar uchar FLAGS_OFFSET // offset of flags in uchar (flags+1 is original read index offset) > class ListOfConstantLengthReads: public GeneratedReadsListInterface<uint_read_len, uint_reads_cnt, uint_pg_len, ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>> ,public ReadsListIteratorInterface<uint_read_len, uint_reads_cnt, ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>> { private: typedef ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET> ThisReadsListType; typedef ReadsListInterface<uint_read_len, uint_reads_cnt, uint_pg_len, ThisReadsListType> ReadsList; static int elementsCompare (const void * a, const void * b) { if (*(uint_pg_len*)a > *(uint_pg_len*)b) return 1; if (*(uint_pg_len*)a < *(uint_pg_len*)b) return -1; return 0; } uchar* pgReadsList = 0; uchar* pgReadsListEnd = 0; const uint_read_len readLength; uint_reads_cnt readsCount; uint_pg_len pseudoGenomeLength; uint_read_len duplicateFilterK; uint_reads_cnt* readsListIdx = 0; // conversion from original index to reads list index /////////////////////////// // GENERATION VARIABLES uint_max curRawIdx; uint_pg_len maxPos; bool isSortRequired; void generateReverseIndex(); /////////////////////////// // ITERATION VARIABLES uint_pg_len suffixPos; int_max guard; // negative possible uint_read_len guardOffset; bool skipDuplicateFilter; uchar* itAddress; vector<uchar*> occurFlagsReadsList; vector<pair<uchar*, uint_read_len>> occurFlagsOccurrencesList; //////////////////////////// // HELPER ROUTINES inline uchar* idx2Address(uint_reads_cnt idx) { return pgReadsList + ((uint_max) idx) * LIST_ELEMENT_SIZE ; }; inline uchar& flagsVariableByAddress(uchar* address) { return ( *(address + FLAGS_OFFSET)); }; inline uint_pg_len getReadPositionByAddress(uchar* address) { // casting address to larger int (uint_max*) improved caching return (uint_pg_len) *((uint_max*) address); //return *((uint_pg_len*) address); }; inline uint_reads_cnt getReadOriginalIndexByAddress(uchar* address) { return (*((uint_reads_cnt*) (address + ORIGINAL_INDEX_OFFSET))); }; inline uint_reads_cnt address2Idx(uchar* address) { return (uint_reads_cnt) ((address - pgReadsList) / LIST_ELEMENT_SIZE); }; inline bool hasDuplicateFilterFlagByAddress(uchar* address) { return flagsVariableByAddress(address) & DUPINREADS_FLAG; }; inline void setDuplicateFilterFlagByAddress(uchar* address) { flagsVariableByAddress(address) |= DUPINREADS_FLAG; }; inline bool hasOccurFlagByAddress(uchar* address) { return flagsVariableByAddress(address) & OCCUR_FLAG; } inline bool hasOccurOnceFlagByAddress(uchar* address) { return (flagsVariableByAddress(address) & OCCURFLAGS_MASK) == OCCUR_FLAG; } inline void setOccurFlagByAddress(uchar* address) { flagsVariableByAddress(address) |= OCCUR_FLAG; } void clearOccurFlagsByAddress(uchar* address); inline void setOccurOnceFlagByAddress(uchar* address) { flagsVariableByAddress(address) |= (((flagsVariableByAddress(address) & OCCUR_FLAG) << 1) | OCCUR_FLAG); } inline uchar& flagsVariable(uint_reads_cnt idx) { return ( *(idx2Address(idx) + FLAGS_OFFSET)); }; public: ListOfConstantLengthReads(uint_read_len readLength, uint_reads_cnt readsCount, uint_pg_len pseudoGenomeLength); ListOfConstantLengthReads(uint_read_len readLength, std::istream& src); void writeImpl(std::ostream& dest); virtual ~ListOfConstantLengthReads(); inline const uchar getListElementSizeImpl() { return LIST_ELEMENT_SIZE; }; inline uint_pg_len getReadPositionImpl(uint_reads_cnt idx) { return getReadPositionByAddress(idx2Address(idx)); }; inline uint_reads_cnt getReadsCountImpl() { return readsCount; }; inline uint_read_len getMaxReadLengthImpl() { return readLength; }; inline uint_read_len getReadLengthImpl(uint_reads_cnt) { return readLength; }; inline uint_reads_cnt getReadOriginalIndexImpl(uint_reads_cnt idx) { return getReadOriginalIndexByAddress(idx2Address(idx)); }; inline uint_reads_cnt getReadsListIndexOfOriginalIndexImpl(uint_reads_cnt originalIdx) { return readsListIdx[originalIdx]; } vector<uint_reads_cnt> lookup; int lookupStepShift = 0; void buildLUTImpl(); uint_reads_cnt findFurthestReadContainingImpl(uint_pg_len pos); inline uint_read_len getDuplicateFilterKmerLengthImpl() { return duplicateFilterK; }; inline void setDuplicateFilterKmerLengthImpl(uint_read_len kLength) { duplicateFilterK = kLength; }; inline bool hasDuplicateFilterFlagImpl(uint_reads_cnt idx) { return hasDuplicateFilterFlagByAddress(idx2Address(idx)); }; inline void setDuplicateFilterFlagImpl(uint_reads_cnt idx) { setDuplicateFilterFlagByAddress(idx2Address(idx)); }; ///////////////////////////////////////// // OCCUR FLAGS MANAGEMENT inline bool hasOccurFlagImpl(uint_reads_cnt idx) { return hasOccurFlagByAddress(idx2Address(idx)); }; inline bool hasOccurOnceFlagImpl(uint_reads_cnt idx) { return hasOccurOnceFlagByAddress(idx2Address(idx)); }; inline void setOccurFlagImpl(uint_reads_cnt idx) { setOccurFlagByAddress(idx2Address(idx)); }; void clearOccurFlagsImpl(uint_reads_cnt idx); inline void setOccurOnceFlagImpl(uint_reads_cnt idx) { setOccurOnceFlagByAddress(idx2Address(idx)); }; /////////////////////////// // ITERATION ROUTINES inline void initIterationImpl(const uint_read_len& kmerLength) { guardOffset = readLength - kmerLength; skipDuplicateFilter = kmerLength < duplicateFilterK; itAddress = pgReadsList; } inline void setIterationPositionImpl(const RPGOffset<uint_read_len, uint_reads_cnt>& saPos) { itAddress = idx2Address(saPos.readListIndex); suffixPos = saPos.offset + this->getReadPositionByAddress(itAddress); guard = (int_max) suffixPos - (int_max) guardOffset; itAddress += LIST_ELEMENT_SIZE; }; inline void setIterationPositionImpl(const RPGOffset<uint_read_len, uint_reads_cnt>& saPos, uchar shift) { itAddress = idx2Address(saPos.readListIndex); suffixPos = saPos.offset + this->getReadPositionByAddress(itAddress) - shift; guard = (int_max) suffixPos - (int_max) guardOffset; while ((itAddress >= pgReadsList) && (suffixPos < getReadPositionByAddress(itAddress))) itAddress -= LIST_ELEMENT_SIZE; itAddress += LIST_ELEMENT_SIZE; }; inline bool moveNextImpl() { return ((itAddress -= LIST_ELEMENT_SIZE) >= pgReadsList) && ((int_max) this->getReadPositionByAddress(itAddress) >= guard); }; inline uint_reads_cnt getReadOriginalIndexImpl() { return getReadOriginalIndexByAddress(itAddress); }; inline uint_read_len getOccurrenceOffsetImpl() { return suffixPos - getReadPositionByAddress(itAddress); }; inline uint_flatten_occurrence_max getFlattenOccurrenceImpl() { return ((uint_flatten_occurrence_max) this->getReadOriginalIndexImpl()) * this->getMaxReadLength() + this->getOccurrenceOffsetImpl(); }; inline uint_reads_cnt getReadIndexImpl() { return address2Idx(itAddress); }; inline bool hasDuplicateFilterFlagImpl() { return (skipDuplicateFilter || hasDuplicateFilterFlagByAddress(itAddress)); }; inline bool hasOccurFlagImpl() { return hasOccurFlagByAddress(itAddress); }; inline bool hasOccurOnceFlagImpl() { return hasOccurOnceFlagByAddress(itAddress); }; inline void setOccurFlagImpl() { setOccurFlagByAddress(itAddress); occurFlagsReadsList.push_back(itAddress); }; uint_reads_cnt clearAllOccurFlagsImpl(); inline void setOccurOnceFlagAndPushReadImpl() { setOccurOnceFlagByAddress(itAddress); occurFlagsReadsList.push_back(itAddress); }; inline void setOccurOnceFlagAndPushOccurrenceImpl() { setOccurOnceFlagByAddress(itAddress); occurFlagsOccurrencesList.push_back( { itAddress, getOccurrenceOffsetImpl()} ); }; template<typename api_uint_reads_cnt> inline void clearAllOccurFlagsAndPushReadsWithSingleOccurrenceImpl(vector<api_uint_reads_cnt>& reads) { for(typename vector<uchar*>::iterator it = occurFlagsReadsList.begin(); it != occurFlagsReadsList.end(); ++it) { if (hasOccurOnceFlagByAddress(*it)) reads.push_back(getReadOriginalIndexByAddress(*it)); clearOccurFlagsByAddress(*it); }; occurFlagsReadsList.clear(); }; uint_reads_cnt clearAllOccurFlagsAndCountSingleOccurrencesImpl(); template<typename api_uint_reads_cnt, typename api_uint_read_len> inline void clearAllOccurFlagsAndPushSingleOccurrencesImpl(vector<pair<api_uint_reads_cnt, api_uint_read_len>>& occurrences) { for(typename vector<pair<uchar*, uint_read_len>>::iterator it = occurFlagsOccurrencesList.begin(); it != occurFlagsOccurrencesList.end(); ++it) { if (this->hasOccurOnceFlagByAddress((*it).first)) occurrences.push_back({ getReadOriginalIndexByAddress((*it).first), (*it).second }); this->clearOccurFlagsByAddress((*it).first); } occurFlagsOccurrencesList.clear(); }; void clearAllOccurFlagsAndPushSingleOccurrencesFlattenImpl(vector<uint_flatten_occurrence_max>& flattenOccurrences); ///////////////////////////////// // GENERATION ROUTINES void addImpl(uint_pg_len pos, uint_read_len len, uint_reads_cnt idx); void validateImpl(); }; template < typename uint_read_len, typename uint_reads_cnt, typename uint_pg_len, unsigned char LIST_ELEMENT_SIZE, // size of list element in uchar uchar FLAGS_OFFSET // offset of flags in uchar (flags+1 is original read index offset) > struct ReadsListIteratorFactoryTemplate<ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET>> { typedef ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET> ReadsListClass; typedef ListOfConstantLengthReads<uint_read_len, uint_reads_cnt, uint_pg_len, LIST_ELEMENT_SIZE, FLAGS_OFFSET> ReadsListIteratorClass; //FIXME: How to handle destruction? ... and get rid of * static ReadsListIteratorClass* getReadsListIterator(ReadsListClass& readsList) { return &readsList; }; }; } #endif // LISTOFCONSTANTLENGTHREADS_H_INCLUDED
#include<bits/stdc++.h> using namespace std; int main() { int x,y; int sum = 0; cin>>x>>y; if(x>y) { swap(x,y); } for(int i =x; i<=y; i++) { if(i%13!=0) { sum = sum + i; } } cout<<sum<<"\n"; return 0; }
#include <iostream> #include <iomanip> using namespace std; int main(){ int i; for ( i = 2;i <= 100; i++) { if(i%2 == 0){ cout << i << endl; } } return 0; }
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <cctype> #include "asar/asardll.h" #include "cfg.h" #include "structs.h" #include "file_io.h" #define ROUTINES 0 #define SPRITES 1 #define GENERATORS 2 #define SHOOTERS 3 #define LIST 4 #define EXTENDED 5 #define CLUSTER 6 #define OVERWORLD 7 #define TEMP_SPR_FILE "spr_temp.asm" #define SPRITE_COUNT 0x80 //count for other sprites like cluster, ow, extended //version 1.xx const char VERSION = 0x01; void double_click_exit() { getc(stdin); //Pause before exit } template <typename T> T* from_table(T* table, int level, int number) { if(level > 0x200 || number > 0xFF) return nullptr; if(level == 0x200) { if(number < 0xB0) return table + (0x2000 + number); else if(number >= 0xB0 && number < 0xC0) return nullptr; else return table + (0x2000 + number - 0x10); } else if(number >= 0xB0 && number < 0xC0){ return table + ((level * 0x10) + (number - 0xB0)); } return nullptr; } bool patch(const char *patch_name, ROM &rom, const char *debug_name) { if(!asar_patch(patch_name, (char *)rom.real_data, MAX_ROM_SIZE, &rom.size)){ int error_count; const errordata *errors = asar_geterrors(&error_count); printf("An error has been detected:\n"); for(int i = 0; i < error_count; i++) printf("%s\n", errors[i].fullerrdata); exit(-1); } return true; } void patch_sprite(sprite* spr, ROM &rom, FILE* output) { FILE* sprite_patch = open(TEMP_SPR_FILE,"w"); fprintf(sprite_patch, "incsrc \"asm/sa1def.asm\"\n"); fprintf(sprite_patch, "incsrc \"shared.asm\"\n"); fprintf(sprite_patch, "incsrc \"%s_header.asm\"\n", spr->directory); fprintf(sprite_patch, "freecode cleaned\n"); fprintf(sprite_patch, "\tincsrc \"%s\"", spr->asm_file); fclose(sprite_patch); patch(TEMP_SPR_FILE, rom, TEMP_SPR_FILE); int print_count = 0; const char * const * prints = asar_getprints(&print_count); int addr = 0xFFFFFF; char buf[5]; if(output) fprintf(output, "%s\n", spr->asm_file); if(print_count > 2 && output) fprintf(output, "Prints:\n"); for(int i = 0; i < print_count; i++) { sscanf(prints[i], "%4s%x", buf, &addr); if(!strcmp(buf,"INIT")) set_pointer(&spr->table.init, addr); else if(!strcmp(buf,"MAIN")) set_pointer(&spr->table.main, addr); else if(!strcmp(buf,"VERG")) { if(VERSION < addr) { printf("Version Guard failed on %s.\n", spr->asm_file); exit(-1); } } else if(output) fprintf(output, "\t%s\n", prints[i]); } if(output) { fprintf(output,"\tINIT: $%06X\n\tMAIN: $%06X" "\n__________________________________\n", spr->table.init.addr(), spr->table.main.addr()); } } void patch_sprites(sprite* sprite_list, int size, ROM &rom, FILE* output) { for(int i = 0; i < size; i++) { sprite* spr = sprite_list + i; if(!spr->asm_file) continue; bool duplicate = false; for(int j = i - 1; j >= 0; j--) { if(sprite_list[j].asm_file) { if(!strcmp(spr->asm_file, sprite_list[j].asm_file)) { spr->table.init = sprite_list[j].table.init; spr->table.main = sprite_list[j].table.main; duplicate = true; break; } } } if(duplicate) continue; patch_sprite(spr, rom, output); } } void clean_hack(ROM &rom){ if(!strncmp((char*)rom.data + rom.snes_to_pc(0x02FFE2), "STSD", 4)){ //already installed load old tables FILE* clean_patch = open("asm/_cleanup.asm", "w"); //remove per level sprites for(int bank = 0; bank < 4; bank++) { fprintf(clean_patch, ";Per Level sprites for levels %03X - %03X\n", (bank * 0x80), ((bank+1)*0x80)-1); int level_table_address = (rom.data[rom.snes_to_pc(0x02FFEA + bank)] << 16) + 0x8000; for(int table_offset = 11; table_offset < 0x8000; table_offset += 0x10) { pointer main_pointer = rom.pointer_snes(level_table_address + table_offset); if(main_pointer.addr() == 0xFFFFFF) { fprintf(clean_patch, ";Encountered pointer to 0xFFFFFF, assuming there to be no sprites to clean!\n"); break; } if(!main_pointer.is_empty()) { fprintf(clean_patch, "autoclean $%06X\n", main_pointer.addr()); } } fprintf(clean_patch, "\n"); } //remove global sprites fprintf(clean_patch, ";Global sprites: \n"); int global_table_address = rom.pointer_snes(0x02FFEE).addr(); for(int table_offset = 11; table_offset < 0xF00; table_offset += 0x10) { pointer main_pointer = rom.pointer_snes(global_table_address + table_offset); if(!main_pointer.is_empty()) { fprintf(clean_patch, "autoclean $%06X\n", main_pointer.addr()); } } //shared routines fprintf(clean_patch, "\n\n;Routines:\n"); for(int i = 0; i < 100; i++){ int routine_pointer = rom.pointer_snes(0x03E05C + i * 3).addr(); if(routine_pointer != 0xFFFFFF){ fprintf(clean_patch, "autoclean $%06X\n", routine_pointer); fprintf(clean_patch, "\torg $%06X\n", 0x03E05C + i * 3); fprintf(clean_patch, "\tdl $FFFFFF\n"); } } int version = rom.data[rom.snes_to_pc(0x02FFE6)]; //Version 1.01 stuff: if(version >= 1) { //remove cluster sprites fprintf(clean_patch, "\n\n;Cluster:\n"); int cluster_table = rom.pointer_snes(0x00A68A).addr(); for(int i = 0; i < SPRITE_COUNT; i++) { pointer cluster_pointer = rom.pointer_snes(cluster_table + 3 * i); if(!cluster_pointer.is_empty()) fprintf(clean_patch, "autoclean $%06X\n", cluster_pointer.addr()); } //remove extended sprites fprintf(clean_patch, "\n\n;Extended:\n"); int extended_table = rom.pointer_snes(0x029B1F).addr(); for(int i = 0; i < SPRITE_COUNT; i++) { pointer extended_pointer = rom.pointer_snes(extended_table + 3 * i); if(!extended_pointer.is_empty()) fprintf(clean_patch, "autoclean $%06X\n", extended_pointer.addr()); } //remove overworld sprites // fprintf(clean_patch, "\n\n;Overworld:\n"); // int ow_table = rom.pointer_snes(0x048633).addr(); // for(int i = 0; i < SPRITE_COUNT; i++) { // pointer ow_pointer = rom.pointer_snes(ow_table + 3 * i); // if(!ow_pointer.is_empty()) // fprintf(clean_patch, "autoclean $%06X\n", ow_pointer.addr()); // } } //everything else is being cleaned by the main patch itself. fclose(clean_patch); patch("asm/_cleanup.asm", rom, "asm/_cleanup.asm"); }else{ //check for old sprite_tool code. (this is annoying) //removes all STAR####MDK tags const char* mdk = "MDK"; //sprite tool added "MDK" after the rats tag to find it's insertions... int number_of_banks = rom.size / 0x8000; for (int i = 0x10; i < number_of_banks; ++i){ char* bank = (char*)(rom.real_data + i * 0x8000); int bank_offset = 8; while(1){ //look for data inserted on previous uses int offset = bank_offset; unsigned int j = 0; for(; offset < 0x8000; offset++) { if(bank[offset] != mdk[j++]) j = 0; if(j == strlen(mdk)) { offset -= strlen(mdk) - 1; //set pointer to start of mdk string break; } } if(offset >= 0x8000) break; bank_offset = offset + strlen(mdk); if(strncmp((bank + offset - 8), "STAR", 4)) //check for "STAR" continue; //delete the amount that the RATS tag is protecting int size = ((unsigned char)bank[offset-3] << 8) + (unsigned char)bank[offset-4] + 8; int inverted = ((unsigned char)bank[offset-1] << 8) + (unsigned char)bank[offset-2]; if ((size - 8 + inverted) == 0x0FFFF) // new tag size++; else if ((size - 8 + inverted) != 0x10000){ // (not old tag either =>) bad tag char answer; int pc = i * 0x8000 + offset - 8 + rom.header_size; printf("size: %04X, inverted: %04X\n", size - 8, inverted); printf("Bad sprite_tool RATS tag detected at $%06X / 0x%05X. Remove anyway (y/n) ", rom.pc_to_snes(pc), pc); scanf("%c",&answer); if(answer != 'Y' && answer != 'y') continue; } //printf("Clear %04X bytes from $%06X / 0x%05X.\n", size, rom.pc_to_snes(pc), pc); memset(bank + offset - 8, 0, size); bank_offset = offset - 8 + size; } } } } void create_shared_patch(const char *routine_path, ROM &rom) { FILE *shared_patch = open("shared.asm", "w"); fprintf(shared_patch, "macro include_once(target, base, offset)\n" " if !<base> != 1\n" " !<base> = 1\n" " pushpc\n" " if read3(<offset>+$03E05C) != $FFFFFF\n" " <base> = read3(<offset>+$03E05C)\n" " else\n" " freecode cleaned\n" " <base>:\n" " print \" Routine: <base> inserted at $\",pc\n" " incsrc <target>\n" " ORG <offset>+$03E05C\n" " dl <base>\n" " endif\n" " pullpc\n" " endif\n" "endmacro\n"); DIR *routine_directory = opendir(routine_path); dirent *routine_file = nullptr; if(!routine_directory){ error("Unable to open the routine directory \"%s\"\n", routine_path); } int routine_count = 0; while((routine_file = readdir(routine_directory)) != NULL){ char *name = routine_file->d_name; if(!strcmp(".asm", name + strlen(name) - 4)){ if(routine_count > 100){ closedir(routine_directory); error("More than 100 routines located. Please remove some.\n", ""); } name[strlen(name) - 4] = 0; fprintf(shared_patch, "!%s = 0\n" "macro %s()\n" "\t%%include_once(\"%s%s.asm\", %s, $%.2X)\n" "\tJSL %s\n" "endmacro\n", name, name, routine_path, name, name, routine_count*3, name); routine_count++; } } closedir(routine_directory); printf("%d Shared routines registered in \"%s\"\n", routine_count, routine_path); fclose(shared_patch); } enum ListType { Sprite = 0, Extended = 1, Cluster = 2, Overworld = 3 }; bool populate_sprite_list(const char** paths, sprite** sprite_lists, const char *list_data, FILE* output) { int line_number = 0, i = 0, bytes_read, sprite_id, level; simple_string current_line; ListType type = Sprite; const char* dir = nullptr; sprite* sprite_list = nullptr; #define ERROR(S) { delete []list_data; error(S, line_number); } #define SETTYPE(T) { type = (T); continue; } do{ level = 0x200; sprite_list = sprite_lists[type]; //read line from list_data current_line = static_cast<simple_string &&>(get_line(list_data, i)); i += current_line.length; if(list_data[i - 1] == '\r') //adjust for windows line end. i++; line_number++; if(!current_line.length || !trim(current_line.data)[0]) continue; //context switching if(!strcmp(current_line.data, "SPRITE:")) SETTYPE(Sprite) if(!strcmp(current_line.data, "EXTENDED:")) SETTYPE(Extended) if(!strcmp(current_line.data, "CLUSTER:")) SETTYPE(Cluster) //if(!strcmp(current_line.data, "OW:")) // SETTYPE(Overworld) //read sprite number if(!sscanf(current_line.data, "%x%n", &sprite_id, &bytes_read)) ERROR("Error on line %d: Invalid line start.\n"); //get sprite pointer sprite* spr = nullptr; if(type == Sprite) { if(current_line.data[bytes_read] == ':') sscanf(current_line.data, "%x%*c%hx%n", &level, &sprite_id, &bytes_read); spr = from_table<sprite>(sprite_list, level, sprite_id); if(!spr) { if(sprite_id >= 0x100) ERROR("Error on line %d: Sprite number must be less than 0x100"); if(level == 0x200 && sprite_id >= 0xB0 && sprite_id < 0xC0) ERROR("Error on line %d: Sprite B0-BF must be assigned a level. Eg. 105:B0"); if(level > 0x200) ERROR("Error on line %d: Level must range from 000-1FF"); if(sprite_id >= 0xB0 && sprite_id < 0xC0) ERROR("Error on line %d: Only sprite B0-BF must be assigned a level."); } } else { if(sprite_id > SPRITE_COUNT) ERROR("Error on line %d: Sprite number must be less than 0x80"); spr = sprite_list + sprite_id; } if(spr->line) ERROR("Error on line %d: Sprite number already used."); spr->line = line_number; spr->level = level; spr->number = sprite_id; //set the directory for the desired type if(type != Sprite) dir = paths[EXTENDED - 1 + type]; else { if(sprite_id < 0xC0) dir = paths[SPRITES]; else if(sprite_id < 0xD0) dir = paths[SHOOTERS]; else dir = paths[GENERATORS]; } spr->directory = dir; //get the filename from the list file char* file_name = nullptr; if(isspace(current_line.data[bytes_read])){ char *trimmed = trim(current_line.data + bytes_read); file_name = new char[strlen(dir) + strlen(trimmed) + 1]; strcpy(file_name, dir); strcat(file_name, trimmed); if(!file_name[0]) { delete[] file_name; ERROR("Error on line %d: Missing filename.\n"); } } else ERROR("Error on line %d: Missing space or level seperator.\n"); char* dot = strrchr(file_name, '.'); //set filename to either cfg or asm file, depending on type. if(type != Sprite) { if(!dot || (strcmp(dot, ".asm") && strcmp(dot, ".ASM"))) ERROR("Error on line %d: Not an asm file."); spr->asm_file = file_name; if(output) fprintf(output, "%s\n\n--------------------------------------\n", file_name); } else { if(!dot || (strcmp(dot, ".cfg") && strcmp(dot, ".CFG"))) ERROR("Error on line %d: Not a cfg file."); spr->cfg_file = file_name; if(!read_cfg_file(spr, (char *)read_all(spr->cfg_file, true), output)) ERROR("Error on line %d: Cannot parse CFG file."); } }while(current_line.length); #undef ERROR #undef SETTYPE delete[] list_data; return true; } // spr = sprite array // filename = duh // size = number of sprites to loop over void write_long_table(sprite* spr, const char* filename, int size = 0x800) { unsigned char dummy[0x10] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF }; unsigned char file[size * 0x10]; if(is_empty_table(spr, size)) write_all(dummy, filename, 0x10); else { for(int i = 0; i < size; i++) memcpy(file + (i * 0x10), &spr[i].table, 0x10); write_all(file, filename, size * 0x10); } } int main(int argc, char* argv[]) { ROM rom; sprite sprite_list[MAX_SPRITE_COUNT]; sprite cluster_list[SPRITE_COUNT]; sprite extended_list[SPRITE_COUNT]; sprite ow_list[SPRITE_COUNT]; sprite* sprites_list_list[4]; sprites_list_list[Sprite] = sprite_list; sprites_list_list[Extended] = extended_list; sprites_list_list[Cluster] = cluster_list; sprites_list_list[Overworld] = ow_list; FILE* output = nullptr; bool keep_temp = false; //first is version 1.xx, others are preserved unsigned char versionflag[4] = { VERSION, 0x00, 0x00, 0x00 }; const char* paths[8]; paths[ROUTINES] = "routines/"; paths[SPRITES] = "sprites/"; paths[SHOOTERS] = "shooters/"; paths[GENERATORS] = "generators/"; paths[LIST] = "list.txt"; paths[EXTENDED] = "extended/"; paths[CLUSTER] = "cluster/"; paths[OVERWORLD] = "overworld/"; if(argc < 2){ atexit(double_click_exit); } if(!asar_init()){ error("Error: Asar library is missing, please redownload the tool or add the dll.\n", ""); } //------------------------------------------------------------------------------------------ // handle arguments passed to tool //------------------------------------------------------------------------------------------ for(int i = 1; i < argc; i++){ if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help") ){ printf("Version 1.%02d\n", VERSION); printf("Usage: pixi <options> <ROM>\nOptions are:\n"); printf("-d\t\tEnable debug output\n"); printf("-k\t\tKeep debug files\n"); printf("-l <listpath>\tSpecify a custom list file (Default: %s)\n", paths[LIST]); printf("\n"); printf("-sp <sprites>\tSpecify a custom sprites directory (Default %s)\n", paths[SPRITES]); printf("-sh <shooters>\tSpecify a custom shooters directory (Default %s)\n", paths[SHOOTERS]); printf("-g <generators>\tSpecify a custom generators directory (Default %s)\n", paths[GENERATORS]); printf("-e <extended>\tSpecify a custom extended sprites directory (Default %s)\n", paths[EXTENDED]); printf("-c <cluster>\tSpecify a custom cluster sprites directory (Default %s)\n", paths[CLUSTER]); //printf("-ow <cluster>\tSpecify a custom overworld sprites directory (Default %s)\n", paths[OVERWORLD]); printf("\n"); printf("-r <sharedpath>\tSpecify a shared routine directory (Default %s)\n", paths[ROUTINES]); exit(0); }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){ output = stdout; }else if(!strcmp(argv[i], "-k")){ keep_temp = true; }else if(!strcmp(argv[i], "-r") && i < argc - 2){ paths[ROUTINES] = argv[i+1]; i++; }else if(!strcmp(argv[i], "-sp") && i < argc - 2){ paths[SPRITES] = argv[i+1]; i++; }else if(!strcmp(argv[i], "-sh") && i < argc - 2){ paths[SHOOTERS] = argv[i+1]; i++; }else if(!strcmp(argv[i], "-g") && i < argc - 2){ paths[GENERATORS] = argv[i+1]; i++; }else if(!strcmp(argv[i], "-l") && i < argc - 2){ paths[LIST] = argv[i+1]; i++; }else if(!strcmp(argv[i], "-e") && i < argc - 2){ paths[EXTENDED] = argv[i+1]; i++; }else if(!strcmp(argv[i], "-c") && i < argc - 2){ paths[CLUSTER] = argv[i+1]; i++; }else{ if(i == argc-1){ break; } error("ERROR: Invalid command line option \"%s\".\n", argv[i]); } } //------------------------------------------------------------------------------------------ // Get ROM name if none has been passed yet. //------------------------------------------------------------------------------------------ if(argc < 2){ printf("Enter a ROM file name, or drag and drop the ROM here: "); char ROM_name[FILENAME_MAX]; if(fgets(ROM_name, FILENAME_MAX, stdin)){ int length = strlen(ROM_name)-1; ROM_name[length] = 0; if((ROM_name[0] == '"' && ROM_name[length - 1] == '"') || (ROM_name[0] == '\'' && ROM_name[length - 1] == '\'')){ ROM_name[length -1] = 0; for(int i = 0; ROM_name[i]; i++){ ROM_name[i] = ROM_name[i+1]; //no buffer overflow there are two null chars. } } } rom.open(ROM_name); }else{ rom.open(argv[argc-1]); } char version = *((char*)rom.data + rom.snes_to_pc(0x02FFE2 + 4)); if(version > VERSION && version != 0xFF) { printf("The ROM has been patched with a newer version of PIXI (1.%02d) already.\n", version); printf("This is version 1.%02d\n", VERSION); printf("Please get a newer version."); exit(-1); } //------------------------------------------------------------------------------------------ // regular stuff //------------------------------------------------------------------------------------------ populate_sprite_list(paths, sprites_list_list, (char *)read_all(paths[LIST], true), output); clean_hack(rom); create_shared_patch(paths[ROUTINES], rom); patch_sprites(sprite_list, MAX_SPRITE_COUNT, rom, output); patch_sprites(cluster_list, SPRITE_COUNT, rom, output); patch_sprites(extended_list, SPRITE_COUNT, rom, output); //patch_sprites(ow_list, SPRITE_COUNT, rom, output); //------------------------------------------------------------------------------------------ // create binary files //------------------------------------------------------------------------------------------ //sprites write_all(versionflag, "asm/_versionflag.bin", 4); write_long_table(sprite_list + 0x0000, "asm/_PerLevelT1.bin"); write_long_table(sprite_list + 0x0800, "asm/_PerLevelT2.bin"); write_long_table(sprite_list + 0x1000, "asm/_PerLevelT3.bin"); write_long_table(sprite_list + 0x1800, "asm/_PerLevelT4.bin"); write_long_table(sprite_list + 0x2000, "asm/_DefaultTables.bin", 0xF0); //cluster unsigned char file[SPRITE_COUNT * 3]; for(int i = 0; i < SPRITE_COUNT; i++) memcpy(file + (i * 3), &cluster_list[i].table.main, 3); write_all(file, "asm/_ClusterPtr.bin", SPRITE_COUNT * 3); //extended for(int i = 0; i < SPRITE_COUNT; i++) memcpy(file + (i * 3), &extended_list[i].table.main, 3); write_all(file, "asm/_ExtendedPtr.bin", SPRITE_COUNT * 3); //overworld // for(int i = 0; i < SPRITE_COUNT; i++) // memcpy(file + (i * 3), &ow_list[i].table.main, 3); // write_all(file, "asm/_OverworldMainPtr.bin", SPRITE_COUNT * 3); // for(int i = 0; i < SPRITE_COUNT; i++) // memcpy(file + (i * 3), &ow_list[i].table.init, 3); // write_all(file, "asm/_OverworldInitPtr.bin", SPRITE_COUNT * 3); //more? //extra byte size file unsigned char extra_bytes[0x200]; for(int i = 0; i < 0x100; i++) { sprite* spr = from_table<sprite>(sprite_list, 0x200, i); if(!spr) { extra_bytes[i] = 7; extra_bytes[i + 0x100] = 7; } else { if(spr->asm_file) { extra_bytes[i] = 3 + spr->byte_count; extra_bytes[i + 0x100] = 3 + spr->extra_byte_count; } else { extra_bytes[i] = 3; extra_bytes[i + 0x100] = 3; } } } write_all(extra_bytes, "asm/_CustomSize.bin", 0x200); //apply the actual patches patch("asm/main.asm", rom, "asm/main.asm"); patch("asm/cluster.asm", rom, "asm/cluster.asm"); patch("asm/extended.asm", rom, "asm/extended.asm"); //patch("asm/overworld.asm", rom, "asm/overworld.asm"); if(!keep_temp){ remove("asm/_versionflag.bin"); remove("asm/_DefaultTables.bin"); remove("asm/_PerLevelT1.bin"); remove("asm/_PerLevelT2.bin"); remove("asm/_PerLevelT3.bin"); remove("asm/_PerLevelT4.bin"); remove("asm/_ClusterPtr.bin"); remove("asm/_ExtendedPtr.bin"); //remove("asm/_OverworldMainPtr.bin"); //remove("asm/_OverworldInitPtr.bin"); remove("asm/_CustomSize.bin"); remove("shared.asm"); remove(TEMP_SPR_FILE); remove("asm/_cleanup.asm"); } rom.close(); asar_close(); printf("\nAll sprites applied successfully!\n"); return 0; }
// BTS, DTS 문제 // // issue : 메모리 초과 // 원인 : BFS 함수 오류 // 해결방법 : BFS 함수에 큐를 사용한다. // // issue : 배열 초과 // 원인 : 배열 인덱스 딱 맞게 설정 // 해결방법 : 배열을 원래 조건보다 여유롭게 설정 #include <iostream> #include <algorithm> #include <vector> #include <queue> using namespace std; vector<int> vertex[1001]; queue<int> vertexQueue; int numberVertex, numberEdge, startVertex; int checkD[1001], checkB[1001]; void BFS(int start); void DFS(int start); int main() { cin >> numberVertex >> numberEdge >> startVertex; for (int i = 0; i < numberEdge; i++) { int top, bottom; cin >> top >> bottom; vertex[top].push_back(bottom); vertex[bottom].push_back(top); // 양쪽에 모두 추가 } for (int i = 0; i < numberVertex; i++) { sort(vertex[i].begin(), vertex[i].end()); } DFS(startVertex); cout << "\n"; BFS(startVertex); return 0; } void BFS(int start) { vertexQueue.push(start); checkB[start] = 1; int i; while (!vertexQueue.empty()) { int frontVertex = vertexQueue.front(); for (i = 0; i < vertex[frontVertex].size(); i++) { if (checkB[vertex[frontVertex][i]] != 1) { checkB[vertex[frontVertex][i]] = 1; vertexQueue.push(vertex[frontVertex][i]); } } cout << vertexQueue.front() << " "; vertexQueue.pop(); } } void DFS(int start) { int i; if (checkD[start] != 1) { checkD[start] = 1; cout << start << " "; for (i = 0; i < vertex[start].size(); i++) { DFS(vertex[start][i]); } } }
#pragma once #include "bricks/core/autopointer.h" namespace Bricks { namespace IO { class StreamReader; class StreamWriter; class Stream; class Console : public Object { protected: Console(Stream* in, Stream* out, Stream* error); public: ~Console(); static Console* GetDefault(); AutoPointer<StreamReader> In; AutoPointer<StreamWriter> Out; AutoPointer<StreamWriter> Error; }; class StandardConsole : public Console { public: StandardConsole(); }; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2008-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef POSIX_OK_NETIF #include "platforms/posix/net/posix_interface.h" #include <net/if.h> #ifdef POSIX_USE_LIFREQ_IOCTL #include <sys/sockio.h> #define USING_SOCKET_IOCTL #endif // POSIX_USE_LIFREQ_IOCTL #ifdef POSIX_USE_IFREQ_IOCTL #include <sys/ioctl.h> #define USING_SOCKET_IOCTL #endif // POSIX_USE_IFREQ_IOCTL #ifdef POSIX_USE_GETIFADDRS #include <ifaddrs.h> #endif #ifdef POSIX_USE_NETLINK #include <netinet/in.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #endif #ifdef POSIX_SUPPORT_IPV6 // convenience query: static bool IsIPv6OK() { return g_opera && g_opera->posix_module.GetIPv6Support(); } #endif /* Control whether Enumerate() might SetIPv6Usable(). * * If we don't have a way of discovering any IPv6 networks locally, Enumerate() * should not presume that the failure to find a usable one means we can't use * IPv6 - we may well have an interface with an IPv6 address we can't see, that * we could be using to access remote IPv6 sites. So each stanza implementing a * portion of Enumerate should define POSIX_NETIF_PROBES_IPv6 precisely if its * way of finding network addresses would in fact discover any IPv6 addresses. * This then enables ProxyStore and Enumerate()'s check for whether we got a * sane IPv6 address. See discussion on ANDMO-264. */ #undef POSIX_NETIF_PROBES_IPv6 /* Tweakify this if struct ifreq ever gets fixed. * * The known struct ifreq implementations use a struct sockaddr member (contrast * getifaddrs, which uses a struct sockaddr*, which may well point to a struct * sockaddr_storage) to hold their address; this is not big enough to hold an * IPv6 address, so we can't possibly get useful results out of the APIs that * return address information in this format (see code testing this define, * below). If its .ifr_addr ever gets upgraded to a struct sockaddr_storage, we * might be able to get IPv6 out of these interfaces; until then, no such luck. * * Of course, if such a change happens, it's entirely possible it'll come with a * change to the ioctl in some way, meaning more code shall need changed to make * the most of it. I've left (Eddy/2011/Sept) assertions in the code that might * have a chance of noticing we have the option, so we'll notice when it's time * to research those details. */ #undef POSIX_IFREQ_CAN_HOLD_IPv6 #if defined(OPSYSTEMINFO_GETSYSTEMIP) && defined(POSIX_OK_SYS) #include "modules/pi/network/OpHostResolver.h" #include "platforms/posix/posix_system_info.h" #include "modules/url/url_socket_wrapper.h" /** Listener for QueryLocalIP. * * Only used if all other ways of discovering local IP address have failed; the * last fall-back is an asynchronous DNS look-up. The listener for that needs * to know where to save the answer and must be able to take responsibility for * deleting both itself and the host-resolver it serviced, if the latter * responds to it asynchronously (i.e. after QueryLocalIP() has returned). */ class FallbackDNSListener : public OpHostResolverListener { OpString8 *const m_sys_ip; const OpString8 *const m_host_name; bool m_async; bool m_done; void Done(OpHostResolver* dns); public: FallbackDNSListener(OpString8 *sys_ip, const OpString8 *host) : m_sys_ip(sys_ip), m_host_name(host), m_async(false), m_done(false) {} bool Detach() { m_async = true; return m_done; } // see comment in QueryLocalIP virtual void OnHostResolved(OpHostResolver* dns); virtual void OnHostResolverError(OpHostResolver* dns, OpHostResolver::Error error); }; void FallbackDNSListener::Done(OpHostResolver* dns) { m_done = true; if (m_async) { delete dns; delete this; } } void FallbackDNSListener::OnHostResolverError(OpHostResolver* dns, OpHostResolver::Error error) { PosixLogger::Log(PosixLogger::DNS, PosixLogger::TERSE, "Failed (%d) synchronous DNS for local %s", (int)error, m_host_name->CStr()); Done(dns); } /** * Address object that remembers the nicest interface it's been asked to Notice(). * * TODO: FIXME: conform to RFC 3484 ! * http://www.rfc-editor.org/rfc/rfc3484.txt */ class NiceAddress : public PosixNetworkAddress { bool m_up; public: NiceAddress() : PosixNetworkAddress(), m_up(false) {} OP_STATUS Notice(const PosixNetworkAddress *what, bool up) { const enum OpSocketAddressNetType type = GetNetType(); if (type == NETTYPE_UNDETERMINED || (m_up == up ? type < what->GetNetType() : up)) { RETURN_IF_ERROR(Import(what)); m_up = up; } return OpStatus::OK; } bool IsUp() { return m_up; } }; void FallbackDNSListener::OnHostResolved(OpHostResolver* dns) { UINT index = dns->GetAddressCount(); if (index > 0) { PosixLogger::Log(PosixLogger::DNS, PosixLogger::CHATTY, "Successfull DNS lookup[%d] for local %s", dns->GetAddressCount(), m_host_name->CStr()); NiceAddress best4; #ifdef POSIX_SUPPORT_IPV6 NiceAddress best6; bool usable = false; #endif while (index-- > 0) { // Extract a result into carrier, get best4 or best6 to Notice it: PosixNetworkAddress carrier; if (OpStatus::IsSuccess(dns->GetAddress(&carrier, index)) && /* karlo/2009/May/25th witnessed DNS returning INADDR_ANY as a * local address (maybe multicast-related ?), so filter that out * if we ever see it again: */ carrier.IsValid()) { /* We don't actually know whether they're up or down, but claim * they're up, anyway: it doesn't matter, as we claim the same * for every one of them. */ #ifdef POSIX_SUPPORT_IPV6 if (carrier.GetDomain() == PF_INET6) { best6.Notice(&carrier, true); if (carrier.IsUsableIPv6()) usable = true; } else #endif best4.Notice(&carrier, true); } } #ifdef POSIX_SUPPORT_IPV6 if (best6.IsValid() && IsIPv6OK()) g_opera->posix_module.SetIPv6Usable(usable); else usable = false; // to save repeating test expressions if (usable && OpStatus::IsSuccess(best6.Notice(&best4, best4.IsUp()))) { best6.ToString8(m_sys_ip); } else #endif if (best4.IsValid()) best4.ToString8(m_sys_ip); else PosixLogger::Log(PosixLogger::DNS, PosixLogger::TERSE, "Seemingly successful DNS lookup found " "%d invalid records for local %s", dns->GetAddressCount(), m_host_name->CStr()); } else PosixLogger::Log(PosixLogger::DNS, PosixLogger::TERSE, "Seemingly successful DNS lookup found no records for local %s", m_host_name->CStr()); Done(dns); } class BestLocalIP : public PosixNetLookup::Store { NiceAddress m_best4; #ifdef POSIX_SUPPORT_IPV6 NiceAddress m_best6; #endif public: virtual OP_STATUS AddPosixNetIF(const PosixNetworkAddress *what, const char *, unsigned int, // ignored bool up) { /* Just remember the best we've seen, for IPv4 and IPv6 respectively, * preferring up over down, public over private over local; and assuming * m_best is indeterminate only if (as it was initially) invalid. * Forget all others: we only want one of each type. */ #ifdef POSIX_SUPPORT_IPV6 if (what->GetDomain() == PF_INET6) return m_best6.Notice(what, up); #endif // POSIX_SUPPORT_IPV6 return m_best4.Notice(what, up); } // OpSocketAddress base-class doesn't const-qualify IsValid, GetNetType or ToString :-( bool Happy() /* const */ { #ifdef POSIX_SUPPORT_IPV6 if (m_best6.IsValid() && g_opera && g_opera->posix_module.GetIPv6Usable()) return true; #endif return m_best4.IsValid(); } OP_STATUS Save(OpString8 *into) /* const */ { #ifdef POSIX_SUPPORT_IPV6 if (g_opera && g_opera->posix_module.GetIPv6Usable() && // Use best v4 address if better than v6 address: OpStatus::IsSuccess(m_best6.Notice(&m_best4, m_best4.IsUp()))) return m_best6.ToString8(into); #endif // POSIX_SUPPORT_IPV6 return m_best4.ToString8(into); } }; OP_STATUS PosixSystemInfo::QueryLocalIP() { // Assumed by assorted socketry code OP_ASSERT(sizeof(struct sockaddr_storage) >= sizeof(sockaddr_in6)); { // Narrow scope of tool: BestLocalIP tool; RETURN_IF_ERROR(PosixNetLookup::Enumerate(&tool, SOCK_STREAM)); if (tool.Happy()) return tool.Save(&m_sys_ip); } /* Fallback. * * First set to 127.0.0.1, then ask DNS if it can help us out - which it * quite likely can't, for example if the available DNS server doesn't * actually know the local machine by the hostname it believes in; this is * probably common among ISP customers (i.e. real users). If DNS gets a * useful result, it'll substitute that in place of 127.0.0.1. * * Note that a DNS look-up on localhost (or its FQDN) is not only slow but * likely to produce poor or unusable results, at least when the * host-resolver in use is getaddrinfo(): see * http://klickverbot.at/blog/2012/01/getaddrinfo-edge-case-behavior-on-windows-linux-and-osx/ * for details. (Short version: "localhost" only gets local loop-back * addresses; Linux does the same for FQDN; Windows and Mac return all * public interfaces for the FQDN; but the local name (FQDN without domain) * doesn't resolve on Mac. We typically only have the local name or * "localhost" from uname or gethostname. See CORE-44333.) So we only do * this as a last resort, when all other methods of discovering the local * address have failed. */ RETURN_IF_ERROR(m_sys_ip.Set("127.0.0.1")); if (m_host_name.HasContent()) { #ifdef POSIX_OK_ASYNC // Ensure PosixAsyncManager is initialized (host resolver needs it): RETURN_IF_ERROR(g_opera->posix_module.InitAsync()); #endif // POSIX_OK_ASYNC FallbackDNSListener *ear = OP_NEW(FallbackDNSListener, (&m_sys_ip, &m_host_name)); if (!ear) return OpStatus::ERR_NO_MEMORY; OpHostResolver *solve = NULL; OpString host; OP_STATUS res = SocketWrapper::CreateHostResolver(&solve, ear); if (OpStatus::IsSuccess(res) && OpStatus::IsSuccess(res = host.Set(m_host_name))) res = solve->Resolve(host.CStr()); /* Resolve *might* already have called OnHostResolved, in which case * we're done with both ear and and solve; more likely, however, it * won't do that for a while; so we have to let ear know it's going to * be responsible for tidying itself and solve away. Fortunately, one * method call can both ask whether it's finished and tell it to tidy up * if not. It is presumed that, if Resolve() returned an error, solve * shall not be calling ear's methods later. */ if (OpStatus::IsError(res) || ear->Detach()) { delete solve; delete ear; } return res; } return OpStatus::OK; } #endif // OPSYSTEMINFO_GETSYSTEMIP && POSIX_OK_SYS #ifdef POSIX_OK_UDP // only depends on this because otherwise it's unused class EqualLocalIP : public PosixNetLookup::Store { const PosixNetworkAddress *const m_sought; unsigned int m_index; public: EqualLocalIP(const PosixNetworkAddress *sought) : m_sought(sought), m_index(0) {} virtual OP_STATUS AddPosixNetIF(const PosixNetworkAddress *what, const char *, // ignored unsigned int index, bool) // ignored { if (m_sought->IsSame(what)) { m_index = index; // Use out-of-range to signal "we're done" return OpStatus::ERR_OUT_OF_RANGE; } return OpStatus::OK; } unsigned int Index() const { return m_index; } }; unsigned int PosixNetworkAddress::IfIndex() const { EqualLocalIP tool(this); /* Enumerate shall return ERR_OUT_OF_RANGE on success, which we ignore; OK * means nothing useful found, ERR means no lookup possible, ERR_NO_MEMORY * has its usual meaning. However, whichever way it fails, we have no * practical use to an error here, so just returning 0 is as good as we can * do. So just ignore the error. */ OpStatus::Ignore(PosixNetLookup::Enumerate(&tool, SOCK_DGRAM)); return tool.Index(); } #endif // POSIX_OK_UDP /** * Tool class used to ensure socket tidy-up in functions below. */ class TransientSocket { const int m_sock; public: TransientSocket(int family, int type, int protocol = 0) : m_sock(socket(family, type, protocol)) {} ~TransientSocket() { close(m_sock); } OP_STATUS check() const { return m_sock + 1 ? OpStatus::OK : OpStatus::ERR; } int get() const { return m_sock; } }; /* Type-safe packaging of some hairy casting. * * We have to reinterpret_cast between the various struct sockaddr* variants; * but we can at least make sure we don't unwittingly convert from some other * type to one of them. Inline functions do the typechecking macros can't. * * Some day, when IPv6 is more widely supported, we may see system types using * struct sockaddr_storage more widely, in which case we're likely to need new * variants on these to accept const pointers to those, too. * * Don't worry about unused-warnings on these. Avoiding them would involve * monstrous and unmaintainable #if-ery; and they're too small to be a footprint * issue ! */ static inline OP_STATUS StoreIPv4(PosixNetworkAddress &dst, const struct sockaddr* src) { return dst.SetFromIPv(reinterpret_cast<const struct sockaddr_in *>(src)->sin_addr); } #ifdef POSIX_SUPPORT_IPV6 static inline OP_STATUS StoreIPv6(PosixNetworkAddress &dst, const struct sockaddr* src) { return dst.SetFromIPv(reinterpret_cast<const struct sockaddr_in6*>(src)->sin6_addr); } #endif // POSIX_SUPPORT_IPV6 #ifdef POSIX_USE_GETIFADDRS static OP_STATUS GetIFAddrs(PosixNetLookup::Store * carrier, struct ifaddrs* run) // <ifaddrs.h> { for (unsigned int index = 1; run; run = run->ifa_next, index++) if (run->ifa_addr) // a struct sockaddr *; NULL if no actual address on interface { PosixNetworkAddress local; switch (run->ifa_addr->sa_family) // see <bits/socket.h> for values { case AF_INET: // 2 RETURN_IF_ERROR(StoreIPv4(local, run->ifa_addr)); break; #ifdef POSIX_SUPPORT_IPV6 #define POSIX_NETIF_PROBES_IPv6 case AF_INET6: // 10 if (IsIPv6OK()) { RETURN_IF_ERROR(StoreIPv6(local, run->ifa_addr)); break; } // else: fall through. #endif default: /* happens ! */ continue; // skip AddPosixNetIF } RETURN_IF_ERROR(carrier->AddPosixNetIF(&local, run->ifa_name, index, // ifa_flags "as for SIOCGIFFLAGS ioctl": (run->ifa_flags & IFF_UP) != 0)); } return OpStatus::OK; } #endif // POSIX_USE_GETIFADDRS #ifdef POSIX_USE_IFREQ_IOCTL static OP_STATUS IfreqIoctl(PosixNetLookup::Store * carrier, int sock) { struct ifreq here; // <net/if.h> /* AlexeyF, in bug 355225, DSK-232744, reports: "here.ifr_ifindex seems to * change after SIOCGIFADDR" - indeed, it turns out all fields other than * .ifr_name are actually different members of a union, which can only know * one of them at a time, so we must record each before asking for the next. * Each member name we access is actually #defined to an actual struct * member name, a dot and a union member name. Joy. */ int index = 0; while ((here.ifr_ifindex = ++index), 1 + ioctl(sock, SIOCGIFNAME, &here)) // http://docsun.cites.uiuc.edu/sun_docs/C/solaris_9/SUNWdev/NETPROTO/p40.html if (1 + ioctl(sock, SIOCGIFFLAGS, &here) && (here.ifr_flags & IFF_LOOPBACK) == 0 && (here.ifr_flags & (IFF_BROADCAST | IFF_POINTOPOINT))) { bool up = (here.ifr_flags & IFF_UP) != 0; if (1 + ioctl(sock, SIOCGIFADDR, &here)) { PosixNetworkAddress addr; switch (here.ifr_addr.sa_family) { case AF_INET: RETURN_IF_ERROR(StoreIPv4(addr, &here.ifr_addr)); break; #ifdef POSIX_SUPPORT_IPV6 case AF_INET6: // To the best of our knowledge, this never happens :-( # ifdef POSIX_IFREQ_CAN_HOLD_IPv6 // See its documentation, above #define POSIX_NETIF_PROBES_IPv6 if (IsIPv6OK()) { RETURN_IF_ERROR(StoreIPv6(addr, &here.ifr_addr)); break; } # else OP_ASSERT(!"Yay ! We *did* get an IPv6 address off SIOCGIFADDR !"); # endif // POSIX_IFREQ_CAN_HOLD_IPv6 continue; #endif // POSIX_SUPPORT_IPV6 default: OP_ASSERT(!"Unrecognized family for local IP address"); continue; } RETURN_IF_ERROR(carrier->AddPosixNetIF(&addr, here.ifr_name, index, up)); } } /* In python's netifaces.c, two more ioctl()s are used with ifreq: * SIOCGIFNETMASK and SIOCGIFBRDADDR, each filling in .ifr_addr; for the * latter, if IFF_POINTTOPOINT is set we get a destination address; * otherwise, a broadcast address. */ return OpStatus::OK; } #endif // POSIX_USE_IFREQ_IOCTL #ifdef POSIX_USE_NETLINK #define NETLINK_MSG_BUFFER_SIZE 4096 static OP_STATUS NetLinkSendRequest(int netLinkSocketFd, int inetFamily) { sockaddr_nl remoteNetLinkAddr; msghdr msgInfo; iovec ioVector; struct { nlmsghdr msgReqHeader; ifaddrmsg msgReqIfAddrInfo; } netlinkReqest; memset(&remoteNetLinkAddr, 0, sizeof(remoteNetLinkAddr)); remoteNetLinkAddr.nl_family = AF_NETLINK; memset(&msgInfo, 0, sizeof(msgInfo)); msgInfo.msg_name = reinterpret_cast<void*>(&remoteNetLinkAddr); msgInfo.msg_namelen = sizeof(remoteNetLinkAddr); memset(&netlinkReqest, 0, sizeof(netlinkReqest)); netlinkReqest.msgReqHeader.nlmsg_len = NLMSG_ALIGN(NLMSG_LENGTH(sizeof(netlinkReqest))); netlinkReqest.msgReqHeader.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; netlinkReqest.msgReqHeader.nlmsg_type = RTM_GETADDR; netlinkReqest.msgReqHeader.nlmsg_pid = getpid(); netlinkReqest.msgReqIfAddrInfo.ifa_family = inetFamily; netlinkReqest.msgReqIfAddrInfo.ifa_index = 0; ioVector.iov_base = reinterpret_cast<void*>(&netlinkReqest.msgReqHeader); ioVector.iov_len = netlinkReqest.msgReqHeader.nlmsg_len; msgInfo.msg_iov = &ioVector; msgInfo.msg_iovlen = 1; return sendmsg(netLinkSocketFd, &msgInfo, 0) > 0 ? OpStatus::OK : OpStatus::ERR; } static OP_STATUS GetNetLink(PosixNetLookup::Store * carrier, int inetFamily) { int msgLength = 0; sockaddr_nl netlinkAddr; TransientSocket netLinkSock(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (netLinkSock.get() == -1) return OpStatus::ERR; memset(&netlinkAddr, 0, sizeof(netlinkAddr)); netlinkAddr.nl_family = AF_NETLINK; netlinkAddr.nl_pid = getpid(); netlinkAddr.nl_groups = RTMGRP_LINK | (inetFamily == AF_INET ? RTMGRP_IPV4_IFADDR : RTMGRP_IPV6_IFADDR); if (bind(netLinkSock.get(), reinterpret_cast<sockaddr*>(&netlinkAddr), sizeof(netlinkAddr)) == -1) return OpStatus::ERR; RETURN_IF_ERROR(NetLinkSendRequest(netLinkSock.get(), inetFamily)); char netlinkMsgBuffer[NETLINK_MSG_BUFFER_SIZE] = {0}; nlmsghdr *netlinkMsgHdr = reinterpret_cast<nlmsghdr*>(netlinkMsgBuffer); iovec ioVector; memset(&ioVector, 0, sizeof(ioVector)); ioVector.iov_base = reinterpret_cast<void*>(netlinkMsgHdr); ioVector.iov_len = NETLINK_MSG_BUFFER_SIZE; msghdr messageHdr; memset(&messageHdr, 0, sizeof(messageHdr)); messageHdr.msg_iov = &ioVector; messageHdr.msg_iovlen = 1; msgLength = recvmsg(netLinkSock.get(), &messageHdr, 0); if (msgLength < 0) return OpStatus::ERR; else if (msgLength == 0) return OpStatus::OK; while (NLMSG_OK(netlinkMsgHdr, msgLength) && netlinkMsgHdr->nlmsg_type != NLMSG_DONE) { if (netlinkMsgHdr->nlmsg_type == RTM_NEWADDR) { ifaddrmsg *netlinkAddrMsg = reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(netlinkMsgHdr)); rtattr *netlinkIfAddrAttr = IFA_RTA(netlinkAddrMsg); int netlinkPayload = IFA_PAYLOAD(netlinkMsgHdr); bool up = (netlinkAddrMsg->ifa_flags & IFF_UP) != 0; while (netlinkPayload && RTA_OK(netlinkIfAddrAttr, netlinkPayload)) { char netlinkIfName[IFNAMSIZ] = {0}; if (netlinkIfAddrAttr->rta_type == IFA_ADDRESS || netlinkIfAddrAttr->rta_type == IFA_LOCAL) { void* netlinkIfAddr = RTA_DATA(netlinkIfAddrAttr); PosixNetworkAddress posixAddr; switch (netlinkAddrMsg->ifa_family) { case AF_INET: RETURN_IF_ERROR(posixAddr.SetFromIPv(*reinterpret_cast<ipv4_addr*>(netlinkIfAddr))); break; #ifdef POSIX_SUPPORT_IPV6 case AF_INET6: # if 0 /* TODO - FIXME: this can't possibly work. * * The netlinkIfAddr is an int, so nowhere big enough to * be an IPv6 address. Likely this means we need to * move some of the code before the switch inside the * AF_INET case and add corresponding code here. */ if (IsIPv6OK()) { RETURN_IF_ERROR(posixAddr.SetFromIPv(*reinterpret_cast<ipv6_addr*>(netlinkIfAddr))); break; } # endif // 0 continue; #endif // POSIX_SUPPORT_IPV6 default: OP_ASSERT(!"Unrecognized family for local IP address"); continue; } RETURN_IF_ERROR(carrier->AddPosixNetIF(&posixAddr, netlinkIfName, netlinkAddrMsg->ifa_index, up)); } netlinkIfAddrAttr = RTA_NEXT(netlinkIfAddrAttr, netlinkPayload); } } netlinkMsgHdr = NLMSG_NEXT(netlinkMsgHdr, msgLength); } return OpStatus::OK; } #endif // POSIX_USE_NETLINK #ifdef POSIX_USE_IFCONF_IOCTL /* Make sure this works on Android, since it can't use the other ioctl()s; see * CORE-32777. May have been made redundant by the netlink code (see above). */ static OP_STATUS DigestIfConf(PosixNetLookup::Store * carrier, int sock, struct ifreq * buffer, size_t space) { struct ifconf ifconf; op_memset(&ifconf, 0, sizeof(ifconf)); ifconf.ifc_buf = (char*) buffer; ifconf.ifc_len = space; if (1 + ioctl(sock, SIOCGIFCONF, (char*)&ifconf)) for (int index = ifconf.ifc_len / sizeof(struct ifreq); index-- > 0;) { struct ifreq *here = buffer + index; PosixNetworkAddress addr; switch (here->ifr_addr.sa_family) { case AF_INET: RETURN_IF_ERROR(StoreIPv4(addr, &here->ifr_addr)); break; #ifdef POSIX_SUPPORT_IPV6 /* Allegedly no IPv6; see * http://comments.gmane.org/gmane.comp.handhelds.android.ndk/4943 */ case AF_INET6: # ifdef POSIX_IFREQ_CAN_HOLD_IPv6 // See its documentation, above #define POSIX_NETIF_PROBES_IPv6 if (IsIPv6OK()) { RETURN_IF_ERROR(StoreIPv6(addr, &here->ifr_addr)); break; } # else OP_ASSERT(!"Yay ! We *did* get an IPv6 address off SIOCGIFCONF !"); # endif // POSIX_IFREQ_CAN_HOLD_IPv6 continue; #endif // POSIX_SUPPORT_IPV6 default: OP_ASSERT(!"Unrecognised family for local IP address"); continue; } if (1 + ioctl(sock, SIOCGIFFLAGS, here)) RETURN_IF_ERROR(carrier->AddPosixNetIF( &addr, here->ifr_name, index+1, (here->ifr_flags & IFF_UP) != 0)); } return OpStatus::OK; } static OP_STATUS IfConfIoctl(PosixNetLookup::Store * carrier, int sock) { #if 0 // Don't know if SIOCGIFCOUNT is available // Is there something else we can use (that works on Android) ? int count; // Not sure what third arg SIOCGIFCOUNT takes; this is just a guess if (ioctl(sock, SIOCGIFCOUNT, &count) + 1) { struct ifreq *buffer = reinterpret_cast<struct ifreq *>( op_calloc(count, sizeof(struct ifreq))); if (!buffer) return OpStatus::ERR_NO_MEMORY; OP_STATUS res = DigestIfConf(carrier, sock, buffer, count * sizeof(struct ifreq)); op_free(buffer); RETURN_IF_ERROR(res); } #else // Hope that 20 >= number of interfaces ! struct ifreq ifreqs[20]; // ARRAY OK 2011-02-23 eddy RETURN_IF_ERROR(DigestIfConf(carrier, sock, ifreqs, sizeof(ifreqs))); #endif return OpStatus::OK; } #endif // POSIX_USE_IFCONF_IOCTL #ifdef POSIX_USE_LIFREQ_IOCTL // See: http://docs.sun.com/app/docs/doc/816-5177/if-tcp-7p?a=view static OP_STATUS DigestLifreq(PosixNetLookup::Store * carrier, int sock4, int type, struct lifreq *data, const struct lifnum &ifn) { struct lifconf ifc; ifc.lifc_len = ifn.lifn_count * sizeof(struct lifreq); ifc.lifc_buf = (caddr_t)data; ifc.lifc_family = ifn.lifn_family; ifc.lifc_flags = 0; if (1 + ioctl(sock4, SIOCGLIFCONF, &ifc) == 0) return OpStatus::ERR; #ifdef POSIX_SUPPORT_IPV6 TransientSocket sock6(PF_INET6, type); #endif for (int i = 0; i < ifn.lifn_count; i++) { struct lifreq &here = data[i]; PosixNetworkAddress local; int sock; switch (here.lifr_addr.ss_family) { case AF_INET: RETURN_IF_ERROR(StoreIPv4(local, &here.lifr_addr)); sock = sock4; break; #ifdef POSIX_SUPPORT_IPV6 #define POSIX_NETIF_PROBES_IPv6 case AF_INET6: if (IsIPv6OK()) { RETURN_IF_ERROR(StoreIPv6(local, &here.lifr_addr)); RETURN_IF_ERROR(sock6.check()); sock = sock6.get(); break; } continue; #endif default: OP_ASSERT(!"Unrecognised family for local IP address"); continue; } // Solaris has SIOCSLIFNAME but no SIOCGLIFNAME ! if (1 + ioctl(sock, SIOCGLIFFLAGS, &here) && (here.lifr_flags & IFF_LOOPBACK) == 0 && (here.lifr_flags & (IFF_BROADCAST | IFF_POINTOPOINT))) { bool up = (here.lifr_flags & IFF_UP) != 0; if (1 + ioctl(sock, SIOCGLIFINDEX, &here)) RETURN_IF_ERROR(carrier->AddPosixNetIF(&local, here.lifr_name, here.lifr_index, up)); } } return OpStatus::OK; } static OP_STATUS LifreqIoctl(PosixNetLookup::Store * carrier, int sock, int type) { struct lifnum ifn; #ifdef POSIX_SUPPORT_IPV6 ifn.lifn_family = AF_UNSPEC; #else ifn.lifn_family = AF_INET; #endif ifn.lifn_flags = 0; ifn.lifn_count = 0; if (1 + ioctl(sock, SIOCGLIFNUM, &ifn) == 0) // ioctl returns -1 on failure return OpStatus::ERR; if (ifn.lifn_count > 0) { struct lifreq * buffer = reinterpret_cast<struct lifreq *>( op_calloc(ifn.lifn_count, sizeof(struct lifreq))); if (!buffer) return OpStatus::ERR_NO_MEMORY; OP_STATUS res = DigestLifreq(carrier, sock, type, buffer, ifn); op_free(buffer); RETURN_IF_ERROR(res); } return OpStatus::OK; } #endif // POSIX_USE_LIFREQ_IOCTL #ifdef POSIX_NETIF_PROBES_IPv6 /** * Wrapper round a Store, that delegates AddPosixNetIF to it, but checks each * interface in passing so as to know if we have any public IPv6. */ class ProxyStore : public PosixNetLookup::Store { PosixNetLookup::Store *const m_wrap; bool m_public; // have we seen a public IPv6 address ? public: ProxyStore(PosixNetLookup::Store *wrap) : m_wrap(wrap), m_public(false) {} virtual OP_STATUS AddPosixNetIF(const PosixNetworkAddress *what, const char *name, unsigned int index, bool up) { if (what->IsUsableIPv6()) m_public = true; return m_wrap->AddPosixNetIF(what, name, index, up); } bool PublicIPv6() { return m_public; } }; #endif // POSIX_NETIF_PROBES_IPv6 // static OP_STATUS PosixNetLookup::Enumerate(Store * carrier, int type) { #ifdef POSIX_NETIF_PROBES_IPv6 ProxyStore wrap(carrier); carrier = &wrap; #endif OP_STATUS err = OpStatus::OK; OpStatus::Ignore(err); #ifdef POSIX_USE_GETIFADDRS struct ifaddrs* interfaces = 0; if (0 == getifaddrs(&interfaces)) { err = GetIFAddrs(carrier, interfaces); freeifaddrs(interfaces); } #endif // POSIX_USE_GETIFADDRS #ifdef POSIX_USE_NETLINK err = GetNetLink(carrier, AF_INET); # ifdef POSIX_SUPPORT_IPV6 if (OpStatus::IsSuccess(err)) err = GetNetLink(carrier, AF_INET6); # endif //POSIX_SUPPORT_IPV6 #endif // POSIX_USE_NETLINK #ifdef USING_SOCKET_IOCTL TransientSocket sock(PF_INET, type); if (OpStatus::IsSuccess(err)) err = sock.check(); #endif #ifdef POSIX_USE_IFCONF_IOCTL if (OpStatus::IsSuccess(err)) err = IfConfIoctl(carrier, sock.get()); #endif #ifdef POSIX_USE_IFREQ_IOCTL if (OpStatus::IsSuccess(err)) err = IfreqIoctl(carrier, sock.get()); #endif #ifdef POSIX_USE_LIFREQ_IOCTL if (OpStatus::IsSuccess(err)) err = LifreqIoctl(carrier, sock.get(), type); #endif #ifdef POSIX_NETIF_PROBES_IPv6 /* If we saw any public IPv6, record that; else, if we succeeded in checking * all interfaces that we could - and should have seen IPv6 addresses, had * there been any - record that we saw none. */ if (IsIPv6OK() && (OpStatus::IsSuccess(err) || wrap.PublicIPv6())) g_opera->posix_module.SetIPv6Usable(wrap.PublicIPv6()); #endif return err; } #endif // POSIX_OK_NETIF
#include<stdio.h> struct student{ char name[21]; int score; }; int main(){ struct student a[10],t; int i,j,k; printf("请输入要排序的个数:"); scanf("%d",&k); for(i=0;i<k;i++) scanf("%s %d", &a[i].name,&a[i].score); for(i=0;i<k-1;i++) for(j=0;j<k-i-1;j++) { if(a[i].score > a[i+1].score) { t=a[i]; a[i]=a[i+1]; a[i+1]=t; } } printf("排序后的顺序为:\n"); for(i=0;i<k;i++) { printf("%s %d\n",a[i].name,a[i].score); } return 0; }
/*First enter RGC irrespective of the order,then enter L,the dependent sources and then dependent sources */ #include<complex> #include<iostream> #include<string> #include<vector> #include<sstream> #include<cctype> #include"stdio.h" #include"stdlib.h" #include<fstream> #include<cmath> using namespace std; void print(vector<vector<double> >&); void printcomplexvector(vector<complex<double> >&); void addzeroes(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &,char, double ,double ,size_t &); void insertvaluesRG(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &,double,double,double); void insertvaluesC(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &,double,double,double); void insertvaluesL(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &,double,double,double); void insertvaluesJ(vector<vector<double> > &,vector<complex<double> >&,double,double,double,double,size_t &); void insertvaluesV(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &,vector<complex<double> >&,double,double,double,double,size_t &); void insertvaluesZ(vector<vector<double> > &,vector<vector<double> > &,double,double,double,double,double); void insertvaluesE(vector<vector<double> > &,double,double,double,double,double); void insertvaluesH(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &,double,double,double,double,double,double,double); #define pi 3.14 #define frequency 1e3 extern "C" void zgesv_( int *n , int *nrhs , complex<double> *a , int *lda , int *ipiv ,complex<double> *b , int *ldb , int *info ); void print_matrix( char* desc, int m, int n, complex<double> *a, int lda ); void print_int_vector( char* desc, int n, int* a ); extern "C" void dgesv_( int* n, int* nrhs, double* a, int* lda, int* ipiv, double* b, int* ldb, int* info ); void AinverseB(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &); void QR_factorization(vector<vector<double> > &,vector<vector<double> > &); void vectormultiplication(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &); void vector_transpose(vector<vector<double> > &,vector<vector<double> > &); void blockArnoldi(vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &,vector<vector<double> > &); extern "C" void dgeev_( char* jobvl, char* jobvr, int* n, double* a,int* lda, double* wr, double* wi, double* vl, int* ldvl, double* vr, int* ldvr, double* work, int* lwork, int* info ); void print_eigenvalues( char* desc, int n, double* wr, double* wi ); int main() { cout<<" DID U CHANGE THE FREQUENCY"<<endl/*<<"REMEMBER ARRAY IS A BITCH"<<endl*/<<"First enter RGC irrespective of the order,then enter L,then independent sources and then dependent sources"<<endl<<"R or r for resistance"<<endl<<"G or g for admittance"<<endl<<"C or c for capacitance"<<endl<<"L or l for inductance"<<endl<<"J or j for current source"<<endl<<"E or e for VCVS"<<endl<<"Z or z for VCCS"<<endl<<"H or h for CCVS"<<endl<<"V or v for independent voltage source"<<endl<<"PRESS ENTER TWICE AFTER DONE ENTERING THE CIRCUIT INFORAMTION IN THE FORM OF SPICE INPUT"<<endl; vector<complex<double> > u_MATRIX; //TAKING OUT EACH STRING AND CONVERTING IT TO RESPECTIVE VALUES string line,s,com1,com2; char new_word,old_word='R'; vector<double>values; vector<string>name; vector<string>read; //WATCH FOR SPACE IN INPUT vector<vector<double> >G_MATRIX; vector<vector<double> >C_MATRIX; vector<vector<double> >B_MATRIX; size_t column=0,previous_section=1,new_section; vector<vector<double> > L_columns; vector<double>L_temp; G_MATRIX.clear(); C_MATRIX.clear(); B_MATRIX.clear(); //reading the input and output node from files created from pul.c code vector<double> input_node,output_node; double temp_node; fstream read1("input_terminal.txt",fstream::in); while(read1>>temp_node) input_node.push_back(temp_node); read1.close(); fstream read2("output_terminal.txt",fstream::in); while(read2>>temp_node) output_node.push_back(temp_node); read2.close(); //printing the nodes for(size_t i=0;i!=input_node.size();++i) cout<<input_node[i]<<" "; cout<<endl; for(size_t i=0;i!=output_node.size();++i) cout<<output_node[i]<<" "; cout<<endl; ifstream myfile("text.txt"); cout<<"Generating the individual Matrices"<<endl; while(getline(myfile,line))/* && !line.empty())*/{ for(size_t i=0;i!=(line.size());++i){ if(isspace(line[i])&& !s.empty()){ read.push_back(s); s.clear(); } else if(!isspace(line[i])){ s+=line[i]; } } read.push_back(s); s.clear();//till here stored the strings from line in vector called read. //now reading that vector and taking out which are numbers and which are string. for(size_t noofelements=0;noofelements!=read.size();++noofelements) { string &element=read[noofelements]; //determining the which is string and which is value size_t count=0; for(size_t i=0;i!=element.size();++i) { if(isdigit(element[i])||ispunct(element[i])||(isdigit(element[i-1])&&element[i]=='e')||(isdigit(element[i-1])&&element[i]=='E')) ++count; } // cout<<"the count is "<<count<<endl; if(count==element.size()) { //taking each values and determining where is comma and word e or E size_t comma_place; size_t comma_counter=0; size_t e_counter=0; vector<size_t>e_place; for(size_t i=0;i!=element.size();++i) { if(element[i]==','){ comma_place=i; ++comma_counter; } else if(element[i]=='e'||element[i]=='E') { ++e_counter; e_place.push_back(i); } } if(comma_counter==0&&e_counter==0) { double f; istringstream(element)>>f; values.push_back(f); values.push_back(0); } else if(comma_counter==1&&e_counter==0) { for(size_t z=0;z<comma_place;++z) s+=element[z]; double f; istringstream(s)>>f; values.push_back(f); s.clear(); for(size_t z=(comma_place+1);z!=element.size();++z) s+=element[z]; double g; istringstream(s)>>g; values.push_back(g); s.clear(); } else if(comma_counter==0&& e_counter==1) { double number,power,scientific; for(size_t z=0;z!=e_place[0];++z) s+=element[z]; istringstream(s)>>number; s.clear(); for(size_t z=(e_place[0]+1);z!=element.size();++z) s+=element[z]; istringstream(s)>>power; s.clear(); scientific=number*pow(10,power); values.push_back(scientific); values.push_back(0); } else if(comma_counter==1&& e_counter==2) { double number1,power1,scientific1,number2,power2,scientific2; for(size_t z=0;z!=e_place[0];++z) s+=element[z]; istringstream(s)>>number1; s.clear(); for(size_t z=(e_place[0]+1);z!=comma_place;++z) s+=element[z]; istringstream(s)>>power1; s.clear(); scientific1=number1*pow(10,power1); values.push_back(scientific1); for(size_t z=comma_place+1;z!=e_place[1];++z) s+=element[z]; istringstream(s)>>number2; s.clear(); for(size_t z=(e_place[1]+1);z!=element.size();++z) s+=element[z]; istringstream(s)>>power2; s.clear(); scientific2=number2*pow(10,power2); values.push_back(scientific2); } else if(comma_counter==1&& e_counter==1) { if(comma_place<e_place[0]) { double f,number,power,scientific; for(size_t z=0;z!=comma_place;++z) s+=element[z]; istringstream(s)>>f; s.clear(); values.push_back(f); for(size_t z=comma_place+1;z!=e_place[0];++z) s+=element[z]; istringstream(s)>>number; s.clear(); for(size_t z=(e_place[0]+1);z!=element.size();++z) s+=element[z]; istringstream(s)>>power; scientific=number*pow(10,power); values.push_back(scientific); } else if(comma_place>e_place[0]) { double f,number,power,scientific; for(size_t z=0;z!=e_place[0];++z) s+=element[z]; istringstream(s)>>number; s.clear(); for(size_t z=(e_place[0]+1);z!=comma_place;++z) s+=element[z]; istringstream(s)>>power; s.clear(); scientific=number*pow(10,power); values.push_back(scientific); for(size_t z=comma_place+1;z!=element.size();++z) s+=element[z]; istringstream(s)>>f; s.clear(); values.push_back(f); } } } else name.push_back(element); } //cout<<name[0][0]<<endl; // cout<<"the numbers in values are"<< endl; // for(size_t i=0;i!= values.size();++i) // cout<<values[i]<<endl; // new_word=name[0][0]; //cout<<"new_word is"<<new_word<<endl; addzeroes(G_MATRIX,C_MATRIX,B_MATRIX,name[0][0],values[0],values[2],column); /* if((new_word=='H'||new_word=='h'||new_word=='v'||new_word=='V'||new_word=='Z'||new_word=='z') && (old_word=='L'||old_word=='l')) { //cout<<"HERE I AM"<<endl; L_columns.push_back(L_temp); if(name[0][0]=='V' || name[0][0]=='v') insertvaluesV(G_MATRIX,C_MATRIX,B_MATRIX,u_MATRIX,values[0],values[2],values[4],values[5],column); else if(name[0][0]=='Z' || name[0][0]=='z') insertvaluesZ(G_MATRIX,C_MATRIX,values[0],values[2],values[4],values[6],values[8]); else if(name[0][0]=='H' || name[0][0]=='h') insertvaluesH(G_MATRIX,C_MATRIX,L_columns,values[0],values[2],values[4],values[6],values[8],values[10],values[12]); }*/ if(name[0][0]=='G'|| name[0][0]=='g') insertvaluesRG(G_MATRIX,C_MATRIX,B_MATRIX,values[0],values[2],values[4]); else if(name[0][0]=='R' || name[0][0]=='r'){ double newvalue=(1/values[4]); insertvaluesRG(G_MATRIX,C_MATRIX,B_MATRIX,values[0],values[2],newvalue); } else if(name[0][0]=='C' || name[0][0]=='c') insertvaluesC(G_MATRIX,C_MATRIX,B_MATRIX,values[0],values[2],values[4]); else if(name[0][0]=='L' || name[0][0]=='l'){ /* new_section=values[6]; if(new_section==previous_section) L_temp.push_back(G_MATRIX.size()); else { previous_section=new_section; L_columns.push_back(L_temp); L_temp.clear(); L_temp.push_back(G_MATRIX.size()); } */ insertvaluesL(G_MATRIX,C_MATRIX,B_MATRIX,values[0],values[2],values[4]); } else if(name[0][0]=='J' || name[0][0]=='j') insertvaluesJ(B_MATRIX,u_MATRIX,values[0],values[2],values[4],values[5],column); else if(name[0][0]=='V' || name[0][0]=='v') {// cout<<"inserting values of V here"<<endl; insertvaluesV(G_MATRIX,C_MATRIX,B_MATRIX,u_MATRIX,values[0],values[2],values[4],values[5],column); } else if(name[0][0]=='Z' || name[0][0]=='z') insertvaluesZ(G_MATRIX,C_MATRIX,values[0],values[2],values[4],values[6],values[8]); else if(name[0][0]=='E' || name[0][0]=='e') insertvaluesE(G_MATRIX,values[0],values[2],values[4],values[6],values[8]); else if(name[0][0]=='H' || name[0][0]=='h') insertvaluesH(G_MATRIX,C_MATRIX,L_columns,values[0],values[2],values[4],values[6],values[8],values[10],values[12]); /*For debugging the complex values are stores in values for(size_t r=0; r!=values.size();++r) cout<<values[r]<<" "; cout<<endl;*/ values.clear(); name.clear(); read.clear(); // to clear the read vector*/ // old_word=new_word; //cout<<"old_word is "<<old_word<<endl; } /* cout<<"columns of L of respective of sections are: "<<endl; cout<<"size of L_columns matrices is :"<<L_columns.size()<<endl; for(size_t i=0;i!=L_columns.size();++i) { cout<<"the section is: "<<i<<endl; for(size_t j=0;j!=(L_columns[0]).size();++j) cout<<L_columns[i][j]<<" "; cout<<endl; }*/ // cout<<"G MATRIX"<<endl; // print(G_MATRIX); // cout<<endl; // cout<<"C MATRIX"<<endl; // print(C_MATRIX); cout<<"Done generating individual matrices"<<endl; // cout<<endl<<"B MATRIX"<<endl; // print(B_MATRIX); // cout<<endl<<"u complex vector"<<endl; // printcomplexvector(u_MATRIX); /*converting ucomplex vectro matrix into ucomplex array matrix*/ complex<double> uarraymatrix[(u_MATRIX).size()][1]; for(size_t i=0;i!=(u_MATRIX).size();++i) uarraymatrix[i][0]=u_MATRIX[i]; /*printing tht ucomplexaray*/ // cout<<endl<<"ucomplexarray"<<endl; // for(size_t i=0;i!=(u_MATRIX).size();++i) // cout<<uarraymatrix[i][0]<<endl; /*converting the B VECTOR MATRIX to B ARRAY MATRIX*/ complex<double> B_COMPLEXARRAYMATRIX[(B_MATRIX).size()][(u_MATRIX).size()]; for(size_t i=0;i!=(B_MATRIX).size();++i) for(size_t j=0;j!=(u_MATRIX).size();++j) B_COMPLEXARRAYMATRIX[i][j]=complex<double>(B_MATRIX[i][j],0); /* print the the B ARRAY MATRIX*/ // cout<<endl<<"B_COMPLEXARRAYMATRIX"<<endl; // for(size_t i=0;i!=(B_MATRIX).size();++i){ // for(size_t j=0;j!=(u_MATRIX).size();++j) // cout<<B_COMPLEXARRAYMATRIX[i][j]<<" "; // cout<<endl;} /*multiplying the B_COMPLEXARRAY AND uarraymatrix*/ complex<double> Bucomplexmultiple[(B_MATRIX).size()][1]; for(size_t i=0;i!=(B_MATRIX).size();++i) for(size_t j=0;j!=(u_MATRIX).size();++j) Bucomplexmultiple[i][0]+=B_COMPLEXARRAYMATRIX[i][j]*uarraymatrix[j][0]; // /*printing the Bucomplexmultiple*/ // cout<<endl<<"Bucomplexmultiple"<<endl; // for(size_t i=0;i!=(B_MATRIX).size();++i) // cout<<Bucomplexmultiple[i][0]<<endl; /*combining G_MATRIX and C_MATRIX into GplussC_MATRIX*/ complex<double> GplussC_MATRIX[(G_MATRIX).size()][(G_MATRIX).size()]; for(size_t i=0;i!=(G_MATRIX).size();++i){ for(size_t j=0;j!=(G_MATRIX).size();++j) { GplussC_MATRIX[i][j]=complex<double>(G_MATRIX[i][j],(2*pi*frequency*C_MATRIX[i][j])); } } /*printing GplussC_MATRIX*/ // cout<<endl<<"GplussC_MATRIX"<<endl; // for(size_t i=0;i!=(G_MATRIX).size();++i){ // // <<cout<<i<<" th line: "; // for(size_t j=0;j!=(G_MATRIX).size();++j) // // {if(i==2&&j==2)cout<<"this is the point"<<endl; // cout<<GplussC_MATRIX[i][j]<<" "; // cout<<";"<<endl; // } // cout<<endl; /*copying elements of GplusC_MATRIX in a one dimension array a*/ complex<double> a[(G_MATRIX.size())*(G_MATRIX.size())]; size_t k=0; for(size_t i=0;i!=(G_MATRIX).size();++i) for(size_t j=0;j!=(G_MATRIX).size();++j) a[k++]=GplussC_MATRIX[j][i]; /*printing the one dimension a matrix*/ // cout<<endl<<" one dimension 'a' matrix"<<endl; // for(size_t i=0;i!=((G_MATRIX.size())*(G_MATRIX.size()));++i) // cout<<a[i]<<" "; // cout<<endl; // /*copying elements of Bucomplexmultiple into b one dimension matrix*/ complex<double> b[B_MATRIX.size()]; for(size_t i=0;i!=(B_MATRIX).size();++i) b[i]=Bucomplexmultiple[i][0]; /* printing the b one dimension matrix*/ // cout<<"one dimension b matrix"<<endl; // for(size_t i=0;i!=(B_MATRIX).size();++i) // cout<<b[i]; // cout<<endl; /*computing ax=b using zgesv routine*/ cout<<"computing Ax=b of orginal solution"<<endl; int n=G_MATRIX.size(); int nrhs=1; int lda=n; int ldb=n; int info; int ipiv[n]; // printf( " ZGESV Program Results\n" ); zgesv_( &n, &nrhs, a, &lda, ipiv, b, &ldb, &info ); /* Check for the exact singularity */ if( info > 0 ) { printf( "The diagonal element of the triangular factor of A,\n" ); printf( "U(%i,%i) is zero, so that A is singular;\n", info, info ); printf( "the solution could not be computed.\n" ); return( 1 ); } /* Print solution */ // print_matrix( " ORIGINAL Solution", n, nrhs, b, ldb ); /* Print details of LU factorization */ // print_matrix( "Details of LU factorization", n, n, a, lda ); /* Print pivot indices */ // print_int_vector( "Pivot indices", n, ipiv ); // converting the b matrices into 2 Dimension orginal_solution matrices in order to compare with MOR result in the end. cout<<"done computing Ax=B of orginal solution"<<endl; complex<double> original_solution[n][1]; for(size_t i=0;i!=n;++i) for(size_t j=0;j!=nrhs;++j) original_solution[i][j]=b[i+j*ldb]; //cout<<"printing the original solution"<<endl; //for(size_t i=0;i!=n;++i) //cout<<original_solution[i][0]<<endl; // //cout<<endl; /* //Computing poles of original equaitons cout<<"computing the poles of original solution"<<endl; vector<vector<double> >A_original_poles; AinverseB(G_MATRIX,C_MATRIX,A_original_poles); // cout<<" A matrix"<<endl; // print(A_original_poles); //mutilpying -1 to A_orignial_poles matrices for(size_t i=0;i!=A_original_poles.size();++i) for(size_t j=0;j!=(A_original_poles[0]).size();++j) A_original_poles[i][j]=-1*A_original_poles[i][j]; //storing in one dimesion to compute eigen value double one_dimension_A_original_poles[A_original_poles.size()*A_original_poles.size()]; size_t count_original_poles=0; for(size_t i=0;i!=A_original_poles.size();++i) for(size_t j=0;j!=(A_original_poles[0]).size();++j) one_dimension_A_original_poles[count_original_poles++]=A_original_poles[j][i]; int N_original_poles=A_original_poles.size(); int info_original_poles,lwork_original_poles; int lda_original_poles=N_original_poles,ldvl_original_poles=N_original_poles,ldvr_original_poles=N_original_poles; double wkopt_original_poles; double* work_original_poles; double wr_original_poles[N_original_poles],wi_original_poles[N_original_poles],vl_original_poles[ldvl_original_poles*N_original_poles],vr_original_poles[ldvr_original_poles*N_original_poles]; cout<<"computing eigenvalues of orginal solution"<<endl; lwork_original_poles=-1; dgeev_("N","N",&N_original_poles,one_dimension_A_original_poles,&lda_original_poles,wr_original_poles,wi_original_poles,vl_original_poles,&ldvl_original_poles,vr_original_poles,&ldvr_original_poles,&wkopt_original_poles,&lwork_original_poles,&info_original_poles); lwork_original_poles=(int)wkopt_original_poles; work_original_poles=(double*)malloc(lwork_original_poles*sizeof(double)); dgeev_("N","N",&N_original_poles,one_dimension_A_original_poles,&lda_original_poles,wr_original_poles,wi_original_poles,vl_original_poles,&ldvl_original_poles,vr_original_poles,&ldvr_original_poles,work_original_poles,&lwork_original_poles,&info_original_poles); if( info > 0 ) { printf( "The algorithm failed to compute eigenvalues.\n" ); return( 1 ); } //print_eigenvalues( "Eigenvalues",N_original_poles , wr_original_poles, wi_original_poles ); cout<<"done generating the eigen values of original solution"<<endl; //computing the poles of orginal solution complex<long double> ai_original_poles[N_original_poles],number1,number2; for(size_t i=0;i!=N_original_poles;++i) ai_original_poles[i]=complex<long double>(wr_original_poles[i],wi_original_poles[i]); cout<<"writing the poles of orginal solution in original_poles.out file"<<endl; fstream result1("original_poles.out",fstream::out); if(result1.is_open()){ for(size_t i=0;i!=N_original_poles;++i) { number1=conj(ai_original_poles[i]); number2=number1/(number1*ai_original_poles[i]); result1<<number2<<endl; } result1.close(); } else cout<<"unable to open file"<<endl; cout<<"done writing the poles of orginal solution in original_poles.out file"<<endl;*/ //function to generate the X matrices containing the genrerated perpendicular columns for MOR cout<<"the number of variable are"<<G_MATRIX.size()<<endl; cout<<endl<<"STARTING THE MOR FROM HERE"<<endl; vector<vector<double> > X_MATRIX; cout<<"computing the orthonormal matrices using block Arnoldi algorithm"<<endl; blockArnoldi(G_MATRIX,C_MATRIX,B_MATRIX,X_MATRIX); cout<<"the rows of X_MATRIX are :"<<X_MATRIX.size()<<" and the columns of X_MATRIX are :"<<(X_MATRIX[0]).size()<<endl; // cout<<"printing the X_MATIRIX"<<endl; // print(X_MATRIX); //checking each coulumvnis orthnormal to each other cout<<"done computing the orthonormal matrices using block Arnoldi algorithm"<<endl; cout<<"checking the mtrices generated is orthonormal or not"<<endl; for(size_t j=0;j!=(((X_MATRIX[0]).size())-1);++j) { double check=0; for(size_t i=0;i!=X_MATRIX.size();++i) { check+=X_MATRIX[i][j]*X_MATRIX[i][j+1]; } int check1=check; // if check not check1 is checked than we find that it is not equal to zeros du to non zero fraction which shows the accuracy of grahm scnmidt method cout<<" value of product of column "<<j<<" and "<<j+1<<" of E = "<<check<<endl; if (check1 ==0) cout<<"ORTHONORMAL matrix"<<endl; else cout<<"NOT ORTHONORMAL matrix"<<endl; } //generating the reduced matrices cout<<"generating the reduced Matrices of orginal matrices"<<endl; vector<vector<double> > X_transpose,multiple,G_cap,C_cap,B_cap; vector_transpose(X_MATRIX,X_transpose); vectormultiplication(X_transpose,X_MATRIX,multiple); // cout<<"printing the multiplication of Z matrices and its transpose"<<endl; // print(multiple); multiple.clear(); vectormultiplication(X_transpose,G_MATRIX,multiple); vectormultiplication(multiple,X_MATRIX,G_cap); multiple.clear(); vectormultiplication(X_transpose,C_MATRIX,multiple); vectormultiplication(multiple,X_MATRIX,C_cap); multiple.clear(); vectormultiplication(X_transpose,B_MATRIX,B_cap); // cout<<"printing the Gcap"<<endl; // print(G_cap); // cout<<"printing the Ccap"<<endl; // print(C_cap); // cout<<"printing the Bcap"<<endl; // print(B_cap); cout<<"done generating the reduced Matrices of orginal matrices"<<endl; X_transpose.clear(); vector_transpose(X_MATRIX,X_transpose); /* //computing poles of MOR method cout<<"computing the poles of MOR method"<<endl; vector<vector<double> >A_MOR_poles; vectormultiplication(X_transpose,A_original_poles,multiple); vectormultiplication(multiple,X_MATRIX,A_MOR_poles); multiple.clear(); double one_dimension_A_MOR_poles[A_MOR_poles.size()*A_MOR_poles.size()]; size_t count_MOR_poles=0; for(size_t i=0;i!=A_MOR_poles.size();++i) for(size_t j=0;j!=(A_MOR_poles[0]).size();++j) one_dimension_A_MOR_poles[count_MOR_poles++]=A_MOR_poles[j][i]; int N_MOR_poles=A_MOR_poles.size(); int info_MOR_poles,lwork_MOR_poles; int lda_MOR_poles=N_MOR_poles,ldvl_MOR_poles=N_MOR_poles,ldvr_MOR_poles=N_MOR_poles; double wkopt_MOR_poles; double* work_MOR_poles; double wr_MOR_poles[N_MOR_poles],wi_MOR_poles[N_MOR_poles],vl_MOR_poles[ldvl_MOR_poles*N_MOR_poles],vr_MOR_poles[ldvr_MOR_poles*N_MOR_poles]; cout<<"computing eigenvalues of MOR method"<<endl; lwork_MOR_poles=-1; dgeev_("N","N",&N_MOR_poles,one_dimension_A_MOR_poles,&lda_MOR_poles,wr_MOR_poles,wi_MOR_poles,vl_MOR_poles,&ldvl_MOR_poles,vr_MOR_poles,&ldvr_MOR_poles,&wkopt_MOR_poles,&lwork_MOR_poles,&info_MOR_poles); lwork_MOR_poles=(int)wkopt_MOR_poles; work_MOR_poles=(double*)malloc(lwork_MOR_poles*sizeof(double)); dgeev_("N","N",&N_MOR_poles,one_dimension_A_MOR_poles,&lda_MOR_poles,wr_MOR_poles,wi_MOR_poles,vl_MOR_poles,&ldvl_MOR_poles,vr_MOR_poles,&ldvr_MOR_poles,work_MOR_poles,&lwork_MOR_poles,&info_MOR_poles); if( info > 0 ) { printf( "The algorithm failed to compute eigenvalues.\n" ); return( 1 ); } //print_eigenvalues( "Eigenvalues",N_MOR_poles , wr_MOR_poles, wi_MOR_poles ); cout<<"done generating the eigen values of MOR solution"<<endl; //computing the poles of MOR solution complex<long double> ai_MOR_poles[N_MOR_poles],number3,number4; for(size_t i=0;i!=N_MOR_poles;++i) ai_MOR_poles[i]=complex<long double>(wr_MOR_poles[i],wi_MOR_poles[i]); cout<<"writing the poles of MOR solution in MOR_poles.out file"<<endl; fstream result2("MOR_poles.out",fstream::out); if(result2.is_open()){ for(size_t i=0;i!=N_MOR_poles;++i) { number3=conj(ai_MOR_poles[i]); number4=number3/(number3*ai_MOR_poles[i]); result2<<number4<<endl; } result2.close(); } else cout<<"unable to open file"<<endl; cout<<"done writing the poles of MOR method in MOR_poles.out file"<<endl;*/ /* Combining G_cap and C_cap into G_capplussC_cap*/ complex<double> G_capplussC_cap[(G_cap).size()][(G_cap).size()]; for(size_t i=0;i!=(G_cap).size();++i){ for(size_t j=0;j!=(G_cap).size();++j) { G_capplussC_cap[i][j]=complex<double>(G_cap[i][j],(2*pi*frequency*C_cap[i][j])); } } /*printing GcapplussCcap*/ // cout<<endl<<"G_capplussC_cap"<<endl; // for(size_t i=0;i!=(G_cap).size();++i){ // for(size_t j=0;j!=(G_cap).size();++j) // { // cout<<G_capplussC_cap[i][j]<<" "; // } // cout<<endl; // } /*copying elements of GcapplusCcap in a one dimension array acap*/ complex<double> a_cap[(G_cap.size())*(G_cap.size())]; size_t k_cap=0; for(size_t i=0;i!=(G_cap).size();++i) for(size_t j=0;j!=(G_cap).size();++j) a_cap[k_cap++]=G_capplussC_cap[j][i]; // cout<<endl; /*printing the one dimension a_cap matrix*/ // cout<<endl<<" one dimension 'a_cap' matrix"<<endl; // for(size_t i=0;i!=((G_cap.size())*(G_cap.size()));++i) // cout<<a_cap[i]<<" "; // cout<<endl; // /*converting the B_cap VECTOR MATRIX to B_cap ARRAY MATRIX*/ complex<double> B_cap_COMPLEXARRAYMATRIX[(B_cap).size()][(u_MATRIX).size()]; for(size_t i=0;i!=(B_cap).size();++i) for(size_t j=0;j!=(u_MATRIX).size();++j) B_cap_COMPLEXARRAYMATRIX[i][j]=complex<double>(B_cap[i][j],0); /* print the the B_cap ARRAY MATRIX*/ // cout<<endl<<"B_capCOMPLEXARRAYMATRIX"<<endl; // for(size_t i=0;i!=(B_cap).size();++i){ // for(size_t j=0;j!=(u_MATRIX).size();++j) // cout<<B_cap_COMPLEXARRAYMATRIX[i][j]<<" "; // cout<<endl;} /*multiplying the B_COMPLEXARRAY AND uarraymatrix*/ complex<double> B_capucomplexmultiple[(B_cap).size()][1]; for(size_t i=0;i!=(B_cap).size();++i) for(size_t j=0;j!=(u_MATRIX).size();++j) B_capucomplexmultiple[i][0]+=B_cap_COMPLEXARRAYMATRIX[i][j]*uarraymatrix[j][0]; /*printing the B_capucomplexmultiple*/ // cout<<endl<<"B_capucomplexmultiple"<<endl; // for(size_t i=0;i!=(B_cap).size();++i) // cout<<B_capucomplexmultiple[i][0]<<endl; /*copying elements of B_capucomplexmultiple into b_cap one dimension matrix*/ complex<double> b_cap[(B_cap).size()]; for(size_t i=0;i!=(B_cap).size();++i) b_cap[i]=B_capucomplexmultiple[i][0]; /* printing the b_cap one dimension matrix*/ // cout<<"one dimension b_cap matrix"<<endl; // for(size_t i=0;i!=(B_cap).size();++i) // cout<<b_cap[i]; // cout<<endl; /*computing a_capx=b_cap using cgesv routine*/ cout<<"computing the Ax=B of the reduced equation of MOR method"<<endl; int n_cap=G_cap.size(); int nrhs_cap=1; int lda_cap=n_cap; int ldb_cap=n_cap; int info_cap; int ipiv_cap[n_cap]; printf( " CGESV Example Program Results\n" ); zgesv_( &n_cap, &nrhs_cap, a_cap, &lda_cap, ipiv_cap, b_cap, &ldb_cap, &info_cap ); /* Check for the exact singularity */ if( info_cap > 0 ) { printf( "The diagonal element of the triangular factor of A,\n" ); printf( "U(%i,%i) is zero, so that A is singular;\n", info_cap, info_cap ); printf( "the solution could not be computed.\n" ); return( 1 ); } /* Print solution */ // print_matrix( "Solution", n_cap, nrhs_cap, b_cap, ldb_cap ); /* Print details of LU factorization */ // print_matrix( "Details of LU factorization", n_cap, n_cap, a_cap, lda_cap ); /* Print pivot indices */ // print_int_vector( "Pivot indices", n_cap, ipiv_cap ); cout<<"done computing the Ax=B of the reduced equation of MOR method"<<endl; /*converting X_matrix into X complex arary matrices*/ complex<double> X_complexarray[X_MATRIX.size()][(X_MATRIX[0]).size()]; for(size_t i=0;i!=X_MATRIX.size();++i) for(size_t j=0;j!=(X_MATRIX[0]).size();++j) X_complexarray[i][j]=complex<double>(X_MATRIX[i][j],0); // cout<<" X MATRIX:-"<<endl; // print(X_MATRIX); /*printing the complex X complex array matrices*/ // cout<<"printing the X complex array"<<endl; // for(size_t i=0;i!=(X_MATRIX).size();++i){ // for(size_t j=0;j!=(X_MATRIX[0]).size();++j) // cout<<X_complexarray[i][j]<<" "; // cout<<endl;} /*converting b_cap from inverse into x_cap 2 dimension array*/ cout<<"the rows of X reduced are :"<<G_cap.size()<<endl; complex<double> x_cap[G_cap.size()][1]; for(size_t i=0;i!=n_cap;++i) for(size_t j=0;j!=nrhs_cap;++j) x_cap[i][j]=b_cap[i+j*ldb_cap]; // /*printing the x_cap array matrices*/ // cout<<endl<<"printing the x_cap array"<<endl; // for(size_t i=0;i!=n_cap;++i) // { // for(size_t j=0;j!=nrhs_cap;++j) // cout<<x_cap[i][j]<<" "; // cout<<endl; // } /*multiplying the X_matrix with x_cap*/ cout<<"computing comparison matirces by mutiplting the MOR solution with orthonormal matrices"<<endl; complex<double>MORsolutioncompare[X_MATRIX.size()][1]; for(size_t i=0;i!=X_MATRIX.size();++i) for(size_t j=0;j!=(X_MATRIX[0]).size();++j) MORsolutioncompare[i][0]+=X_MATRIX[i][j]*x_cap[j][0]; /* writing the orginal and MOR solution in result.out*/ fstream result3("result_at_node.out",fstream::out); fstream result("result.out",fstream::out); cout<<endl<<"********************************************************************************************************************************************************************"<<endl; if(result.is_open()&& result3.is_open()){ cout<<"writing the original and MOR soluition in result.out and result_at_node.out"<<endl; result<<"ORIGINAL SOLUTION"<<'\t' <<"MORsolution"<<endl; // cout<<"ORIGINAL SOLUTION"<<'\t' <<"MORsolution"<<endl; for(size_t i=0;i!=X_MATRIX.size();++i){ // cout<<original_solution[i][0]<<'\t'<<MORsolutioncompare[i][0]<<endl; result<<original_solution[i][0]<<'\t'<<MORsolutioncompare[i][0]<<endl; for(size_t j=0;j!=input_node.size();++j){ if(i==(input_node[j]-1)) result3<<original_solution[i][0]<<'\t'<<MORsolutioncompare[i][0]<<"INPUT NODE : "<<input_node[j]<<endl; } for(size_t k=0;k!=output_node.size();++k){ if(i==(output_node[k]-1)) result3<<original_solution[i][0]<<'\t'<<MORsolutioncompare[i][0]<<"OUTPUT NODE : "<<output_node[k]<<endl; } } result.close(); result3.close(); } else cout<<"unable to open file"<<endl; //cout<<"the size of Original solution is :"<<original_solution.size()<<" and the size of MOR solution compare is :"<<MORsolutioncompare.size()<<endl; cout<<" the original and MOR solution written in result.out"<<endl; cout<<"end of program"<<endl; return 0; } /* Auxiliary routine: printing a matrix */ void print_matrix( char* desc, int m, int n, complex<double> *a, int lda ) { int i, j; printf( "\n %s\n", desc ); for( i = 0; i < m; i++ ) { for( j = 0; j < n; j++ ) printf( " (%f,%f)", a[i+j*lda].real(), a[i+j*lda].imag() ); printf( "\n" ); } } /* Auxiliary routine: printing a vector of integers */ void print_int_vector( char* desc, int n, int* a ) { int j; printf( "\n %s\n", desc ); for( j = 0; j < n; j++ ) printf( " %6i", a[j] ); printf( "\n" ); } /*Function for printing the 2 dimension vector*/ void print( vector<vector<double> > &p) { for(size_t i=0; i!=(p.size());++i){ for(size_t j=0; j!=((p[i]).size());++j) cout<<p[i][j]<<" "; cout<<";"<<endl;} } /* Function for printing one dimension complex vector*/ void printcomplexvector(vector<complex<double> >&p) { for(size_t i=0; i!=(p.size());++i){ // for(size_t j=0; j!=((p[i]).size());++j) cout<<p[i]<<" "; cout<<";"<<endl;} } /* INSERTING ZEROES IN G,C,B MATRIC*/ void addzeroes(vector<vector<double> > &G,vector<vector<double> > &C,vector<vector<double> > &B,char S, double nodeI,double nodeJ,size_t &count) { size_t size=(nodeI>nodeJ)?nodeI:nodeJ; size_t size1=G.size();//or size1=C.size,had to add this syntax because when the vectros were not empty,it was not able to take the size of the vectors. size_t size2=B.size(); if(S=='R'||S=='r'||S=='G'||S=='g'||S=='C'||S=='c'){ if(G.empty() && C.empty() && B.empty() ){ G=vector<vector<double> >(size,vector<double>(size,0)); C=vector<vector<double> >(size,vector<double>(size,0)); B=vector<vector<double> >(size,vector<double>(1,0));} else if(!G.empty() && !C.empty() && !B.empty() && size>G.size() && size>C.size()){ for(size_t i=0; i!=size1;++i){ for(size_t j=0; j!=(size-(G.size())) ;++j){ G[i].push_back(0); C[i].push_back(0); }} for(size_t k=0; k!=(size-size1) ; ++k){ G.push_back(vector<double>(size,0)); C.push_back(vector<double>(size,0)); B.push_back(vector<double>(1,0)); } } } else if(S=='L'||S=='l'){ for(size_t i=0;i!=(G.size());++i){ G[i].push_back(0); C[i].push_back(0);} G.push_back(vector<double>((G.size()+1),0)); C.push_back(vector<double>((C.size()+1),0)); B.push_back(vector<double>(1,0)); } else if(S=='J'||S=='j'){ size_t s=0; for(size_t i=0;i!=B.size();++i){ if(B[i][count]==0) ++s; } if(s<B.size()){ ++count; for(size_t i=0;i!=B.size();++i) B[i].push_back(0); } } else if(S=='V'||S=='v'){ for(size_t i=0;i!=(G.size());++i){ G[i].push_back(0); C[i].push_back(0); } G.push_back(vector<double>((G.size()+1),0)); C.push_back(vector<double>((C.size()+1),0)); B.push_back(vector<double>((count+1),0)); size_t s=0; for(size_t i=0;i!=B.size();++i){ if(B[i][count]==0) ++s; } if(s<B.size()){ ++count; for(size_t i=0;i!=B.size();++i) B[i].push_back(0); } } else if(S=='E'||S=='e'){ for(size_t i=0;i!=(G.size());++i){ G[i].push_back(0); C[i].push_back(0); } G.push_back(vector<double>((G.size()+1),0)); C.push_back(vector<double>((C.size()+1),0)); B.push_back(vector<double>((count+1),0)); } else if(S=='H'||S=='h'){ for(size_t i=0;i!=size1;++i){ // for(size_t j=0;j!=2;++j){ G[i].push_back(0); C[i].push_back(0); // } } G.push_back(vector<double>((size1+1),0)); // G.push_back(vector<double>((size1+2),0)); C.push_back(vector<double>((size1+1),0)); // C.push_back(vector<double>((size1+2),0)); B.push_back(vector<double>((count+1),0)); // B.push_back(vector<double>((count+1),0)); } } void insertvaluesRG(vector<vector<double> > &G,vector<vector<double> > &C,vector<vector<double> > &B,double nodeI,double nodeJ,double value) { double I=nodeI-1; double J=nodeJ-1; for(size_t i=0;i!=(G.size());++i){ for(size_t j=0;j!=((G[i]).size());++j){ if(((i==I)&&(j==J))||((i==J)&&(j==I))&& I>=0 && J>=0) G[i][j]=G[i][j]-value; else if(((i==I)&&(j==I)&& I>=0)||((i==J)&&(j==J)&& J>=0)) G[i][j]=G[i][j]+value; } } } void insertvaluesC(vector<vector<double> > &G,vector<vector<double> > &C,vector<vector<double> > &B,double nodeI,double nodeJ,double value) { double I=nodeI-1; double J=nodeJ-1; for(size_t i=0;i!=(C.size());++i){ for(size_t j=0;j!=((C[i]).size());++j){ if(((i==I)&&(j==J))||((i==J)&&(j==I))&& I>=0 && J>=0) C[i][j]=C[i][j]-value; else if(((i==I)&&(j==I)&& I>=0)||((i==J)&&(j==J)&& J>=0)) C[i][j]=C[i][j]+value; } } } void insertvaluesL(vector<vector<double> > &G,vector<vector<double> > &C,vector<vector<double> > &B,double nodeI,double nodeJ,double value) { C[(C.size())-1][(C.size())-1]=C[(C.size())-1][(C.size())-1]+value; double I=nodeI-1; double J=nodeJ-1; for(size_t i=0;i!=(G.size());++i){ for(size_t j=0;j!=((G[i]).size());++j){ if(i==(G.size()-1) && j==I && I>=0) G[i][j]=G[i][j]-1; else if(i==(G.size()-1) && j==J && J>=0) G[i][j]=G[i][j]+1; else if(j==(G.size()-1) && i==I && I>=0) G[i][j]=G[i][j]+1; else if(j==(G.size()-1) && i==J && J>=0) G[i][j]=G[i][j]-1; } } } void insertvaluesJ(vector<vector<double> > &B,vector<complex<double> > &U,double nodeI,double nodeJ,double value1,double value2,size_t &count) { double I=nodeI-1; double J=nodeJ-1; for(size_t i=0;i!=B.size();++i) { if(i==I && I>=0) B[i][count]=B[i][count]+1; else if(i==J && J>=0) B[i][count]=B[i][count]-1; } complex<double> b= complex<double>(value1,value2); U.push_back(b); } void insertvaluesV(vector<vector<double> > &G,vector<vector<double> > &C,vector<vector<double> > &B,vector<complex<double> >&U,double nodeI,double nodeJ,double value1,double value2,size_t &count) {//cout<<"in the insert function"<<endl; double I=nodeI-1; double J=nodeJ-1; for(size_t i=0;i!=(G.size());++i){ for(size_t j=0;j!=((G[i]).size());++j){ if(i==(G.size()-1) && j==I && I>=0) { // cout<<"inserted at row "<<i<<" and column "<<j<<endl; G[i][j]=G[i][j]-1;} else if(i==(G.size()-1) && j==J && J>=0) {// cout<<"inserted at row "<<i<<" and column "<<j<<endl; G[i][j]=G[i][j]+1; } else if(j==(G.size()-1) && i==I && I>=0) {// cout<<"inserted at row "<<i<<" and column "<<j<<endl; G[i][j]=G[i][j]+1;} else if(j==(G.size()-1) && i==J && J>=0) {G[i][j]=G[i][j]-1; // cout<<"inserted at row "<<i<<" and column "<<j<<endl; } } } //cout<<"done with for loop"<<endl; B[(B.size()-1)][count]=B[(B.size()-1)][count]-1; complex<double> b= complex<double>(value1,value2); U.push_back(b); //cout<<"done with inserting value in B matrices"<<endl; } void insertvaluesZ(vector<vector<double> > &G,vector<vector<double> > &C,double nodeI,double nodeJ,double nodeK,double nodeL,double value) { double Nplus=nodeI-1; double Nminus=nodeJ-1; double NCplus=nodeK-1; double NCminus=nodeL-1; for(size_t i=0;i!=(G.size());++i){ for(size_t j=0;j!=((G[i]).size());++j){ if((i==Nplus && j==NCplus && Nplus>=0 && NCplus>=0)||(i==Nminus && j==NCminus && Nminus>=0 && NCminus>=0)) { C[i][j]=C[i][j]+value; // cout<<"row :"<<i<<" column :"<<j<<endl; } else if((i==Nplus && j==NCminus && Nplus>=0 && NCminus>=0)||(i==Nminus && j==NCplus && Nminus>=0 && NCplus>=0)) { C[i][j]=C[i][j]-value; // cout<<"row :"<<i<<" column :"<<j<<endl; } } } } void insertvaluesE(vector<vector<double> > &G,double nodeI,double nodeJ,double nodeK,double nodeL,double value) { size_t last=(G.size())-1; double Nplus=nodeI-1; double Nminus=nodeJ-1; double NCplus=nodeK-1; double NCminus=nodeL-1; for(size_t i=0;i!=(G.size());++i){ for(size_t j=0;j!=((G[i]).size());++j){ if(i==Nplus && j==last && Nplus>=0) G[i][j]=G[i][j]+1; else if(i==Nminus && j==last && Nminus>=0) G[i][j]=G[i][j]-1; else if(i==last && j==Nplus && Nplus>=0) G[i][j]=G[i][j]+1; else if(i==last && j==Nminus && Nminus>=0) G[i][j]=G[i][j]-1; else if(i==last && j==NCplus && NCplus>=0) G[i][j]=G[i][j]-value; else if(i==last && j==NCminus && NCminus>=0) G[i][j]=G[i][j]+value; } } } void insertvaluesH(vector<vector<double> > &G,vector<vector<double> > &C,vector<vector<double> > & L_current_position,double nodeI,double nodeJ,double nodeK,double nodeL,double value,double row,double column) { size_t last=(G.size())-1; double Nplus=nodeI-1; double Nminus=nodeJ-1; double section=row-1; double dependent_line=column-1; //cout<<"section :"<<section<<" line :"<<dependent_line<<endl; for(size_t i=0;i!=(G.size());++i){ for(size_t j=0;j!=((G[i]).size());++j){ if(i==Nplus && j==last && Nplus>=0) G[i][j]=G[i][j]+1; else if(i==Nminus && j==last && Nminus>=0) G[i][j]=G[i][j]-1; else if(i==last && j==Nplus &&Nplus>=0) G[i][j]=G[i][j]+1; else if(i==last && j==Nminus &&Nminus>=0) G[i][j]=G[i][j]-1; else if(i==last && j==L_current_position[section][dependent_line]) { //cout<<"the current position of H is "<<j<<endl; C[i][j]=C[i][j]-value; } } } } void AinverseB(vector<vector<double> > &Ad,vector<vector<double> > &Bd,vector<vector<double> > &Cd) { size_t sizeA=Ad.size(); int Nd=sizeA; size_t colB=(Bd[0]).size(); int NRHSd=colB; int LDAd =Nd; int LDBd=Nd; int IPIVd[Nd]; int INFOd; double ad[LDAd*Nd],bd[LDBd*NRHSd]; int kd=0; int ld=0; for(size_t i=0;i!=(Ad[0]).size();++i) for(size_t j=0;j!=Ad.size();++j) ad[kd++]=Ad[j][i]; for(size_t i=0;i!=(Bd[0]).size();++i) for(size_t j=0;j!=Bd.size();++j) bd[ld++]=Bd[j][i]; dgesv_( &Nd, &NRHSd, ad, &LDAd, IPIVd, bd, &LDBd, &INFOd ); if( INFOd > 0 ) { cout<<"The diagonal element of the triangular factor of A,\n"; cout<< "U("<<INFOd<<","<<INFOd<<" is zero, so that A is singular;\n"; cout<<( "the solution could not be computed.\n" ); // return(1); } vector<double>tempd; for(size_t i=0;i!=Nd;++i) { for(size_t j=0;j!=NRHSd;++j) tempd.push_back(bd[i+j*LDBd]); Cd.push_back(tempd); tempd.clear(); } } void QR_factorization(vector<vector<double> > &a,vector<vector<double> > &E) { vector<double> u; for(size_t i=0;i!=(a[0]).size();++i){ for(size_t j=0;j!=a.size();++j) u.push_back(a[j][i]); // cout<<"printing"<< i+1 <<"u vector"<<endl; // for(size_t r=0;r!=u.size();++r) // cout<<u[r]<<" "; // cout<<endl; if(i==0) { double sum=0; for(size_t k=0;k!=u.size();++k) sum+=u[k]*u[k]; for(size_t k=0;k!=u.size();++k){ // double root=sqrt(sum); // double value=u[k]/root; E.push_back(vector<double>(1,(u[k]/sqrt(sum)))); } u.clear(); } else{ double sum=0; for(size_t k=0;k!=i;++k) { double prod=0; for(size_t z=0;z!=u.size();++z) prod+=a[z][i]*E[z][k]; for(size_t z=0;z!=u.size();++z) u[z]=u[z]-(prod*E[z][k]); } for(size_t k=0;k!=u.size();++k) sum+=u[k]*u[k]; for(size_t k=0;k!=u.size();++k){ // double root=sqrt(sum); // double value=u[k]/root; E[k].push_back(u[k]/sqrt(sum)); } u.clear(); } } /* for(size_t j=0;j!=((E[0].size())-1);++j) { double check=0; for(size_t i=0;i!=E.size();++i) { check+=E[i][j]*E[i][j+1]; } int check1=check; // if check not check1 is checked than we find that it is not equal to zeros du to non zero fraction which shows the accuracy of grahm scnmidt method cout<<" value of product of column "<<j<<" and "<<j+1<<" of E = "<<check<<endl; if (check1 ==0) cout<<"ORTHONORMAL matrix"<<endl; else cout<<"NOT ORTHONORMAL matrix"<<endl; } cout<<endl;*/ } void vectormultiplication(vector<vector<double> > &a,vector<vector<double> > &b,vector<vector<double> > &c) { if((a[0]).size()!=b.size()) cout<<"columns of 1st matrix and row of 2nd matrix does not match"<<endl; else{ vector<double>temp; size_t row=a.size(); size_t column=(b[1]).size(); size_t inner=b.size(); for(size_t i=0;i!=row;++i){ for(size_t j=0;j!=column;++j){ double sum=0; for(size_t k=0;k!=inner;++k){ sum+=a[i][k]*b[k][j]; } temp.push_back(sum); } c.push_back(temp); temp.clear(); } } } void vector_transpose(vector<vector<double> > &a,vector<vector<double> > &b) { vector<double>temp; for(size_t i=0;i!=(a[0]).size();++i) { for(size_t j=0;j!=a.size();++j) { temp.push_back(a[j][i]); } b.push_back(temp); temp.clear(); } } void blockArnoldi(vector<vector<double> > &G,vector<vector<double> > &C,vector<vector<double> > &B,vector<vector<double> > &X) { vector<double> range,insert; vector<vector<double> > R,Q,V,X_temp,Z,X_transpose,H,XH; AinverseB(G,B,R); //cout<<"the inverse matrix for the first time in block Arnoldi algorithm"<<endl; //print(R); QR_factorization(R,Q); size_t q,n,input1,input2; X=Q; // cout<<"printing the X 0"<<endl; // print(X); Q.clear(); R.clear(); range.push_back((X[0]).size()); cout<<"Enter the value of q"<<endl; cin>>q; if((q%((B[0]).size()))==0){ n=q/((B[0]).size()); cout<<"the value of n is :"<<n<<endl; } else{ n=floor(q/((B[0]).size()))+1; cout<<"the value of n is :"<<n<<endl; } for(size_t kA=1;kA<=n;++kA) { input1=kA-1; if(input1==0){ for(size_t l=0;l!=X.size();++l) { for(size_t m=0;m!=range[input1];++m) insert.push_back(X[l][m]); X_temp.push_back(insert); insert.clear(); } } else{ for(size_t l=0;l!=X.size();++l) { for(size_t m=range[input1-1];m!=range[input1];++m) insert.push_back(X[l][m]); X_temp.push_back(insert); insert.clear(); } } vectormultiplication(C,X_temp,V); X_temp.clear(); AinverseB(G,V,Z); V.clear(); for(size_t jA=1;jA<=kA;++jA) { input2=kA-jA; if(input2==0){ for(size_t l=0;l!=X.size();++l) { for(size_t m=0;m!=range[input2];++m) insert.push_back(X[l][m]); X_temp.push_back(insert); insert.clear(); } } else{ for(size_t l=0;l!=X.size();++l) { for(size_t m=range[input2-1];m!=range[input2];++m) insert.push_back(X[l][m]); X_temp.push_back(insert); insert.clear(); } } vector_transpose(X_temp,X_transpose); vectormultiplication(X_transpose,Z,H); vectormultiplication(X_temp,H,XH); for(size_t iA=0;iA!=Z.size();++iA) for(size_t jA=0;jA!=(Z[0]).size();++jA) Z[iA][jA]=Z[iA][jA]-XH[iA][jA]; X_temp.clear(); X_transpose.clear(); XH.clear(); H.clear(); } //printing the z for arnoldi process for SISO for(size_t iA=0;iA!=Z.size();++iA) for(size_t jA=0;jA!=(Z[0]).size();++jA) cout<<Z[iA][jA]<<" "; cout<<endl; QR_factorization(Z,Q); for(size_t iA=0;iA!=Q.size();++iA) for(size_t jA=0;jA!=(Q[0]).size();++jA) (X[iA]).push_back(Q[iA][jA]); range.push_back((X[0]).size()); cout<<"printing the X"<<kA<<endl; // print(Q); Q.clear(); Z.clear(); } } void print_eigenvalues( char* desc, int n,double* wr,double* wi ) { int j; printf( "\n %s\n", desc ); for( j = 0; j < n; j++ ) { // if( wi[j] == (double)0.0 ) { // printf( " %6.2f", wr[j] ); // } else { printf( " (%f,%f)", wr[j], wi[j] ); // } } printf( "\n" ); }
#include <iostream> using namespace std; long Fibonacci1(unsigned long n){ int a=0; int b=1; int result; for(int i=0; i < n-1; i++){ result = (a+b); a = b; b = result; } return result; } int main() { unsigned long n = 2; cout << Fibonacci1(n) << endl; return 0; }
// Demonstrate file use #include <iostream> #include <fstream> #include <vector> void writeFile(const std::string& filename) { // .c_str() - convert std::string to a C-string (pointer to start and NULL terminator) std::ofstream outputFileStream(filename.c_str()); outputFileStream << "AARDVARK\n" << "ABRIDGE\n" << "ABSENT\n" << "ACCOUNT\n" << "ACUMEN"; // outputFileStream goes out of scope - file stream closed. } void readFile(const std::string& filename, std::vector<std::string>& lines) { lines.clear(); char buffer[1024]; // Read text into this C-string buffer std::ifstream inputFileStream(filename.c_str()); while (inputFileStream) { inputFileStream.getline(buffer, 1024); lines.push_back(buffer); } } int main(int argc, char **argv) { std::string filename = "storage.txt"; writeFile(filename); std::vector<std::string> theLines; readFile(filename, theLines); // Equivalent output loops // Index into vector for (int i = 0; i < theLines.size(); ++i) std::cout << theLines[i] << std::endl; // Iterator for (std::vector<std::string>::const_iterator iter = theLines.begin(); iter != theLines.end(); ++iter) std::cout << *iter << std::endl; // Use auto for shorthand to iterator type for (auto iter = theLines.begin(); iter != theLines.end(); ++iter) std::cout << *iter << std::endl; // C++11 for loop - use reference to avoid copying string from vector into loop variable line for (std::string &line: theLines) std::cout << line << std::endl; return 0; }
// // EnemyBullet.cpp // ClientGame // // Created by liuxun on 15/3/3. // // #include "EnemyBullet.h" #include "Player.h" #include "Enemy2.h" EnemyBullet::EnemyBullet(){ } EnemyBullet::EnemyBullet(Enemy* enemy) { Vector2 enemyVector = MathUtil::VectorFromAngle(enemy->GetRotation() + 90.0f); Vector2 pos = enemy->GetPosition(); pos -= enemyVector * (enemy->GetSize().Y * 0.5f); SetPosition(pos); SetSize(0.5f); SetDensity(1.0f); SetIsSensor(true); SetSprite("./Resources/Images/enemyBullet.png"); SetShapeType(PhysicsActor::SHAPETYPE_CIRCLE); InitPhysics(); GetBody()->SetBullet(true); ApplyLinearImpulse(Vector2(0.0f, -1.0f), Vector2::Zero); Tag("enemyBullet"); theWorld.Add(this); } void EnemyBullet::Update(float dt) { PhysicsActor::Update(dt); if (GetPosition().Y < theCamera.GetWorldMinVertex().Y) { Destroy(); } }