blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3f7941788a603c221768463d0e01cd54926ce65 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/boost/container/pmr/vector.hpp | 0350574ff58c7c4916babef5ec92b045c6042a8f | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,182 | hpp | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2015-2015. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINER_PMR_VECTOR_HPP
#define BOOST_CONTAINER_PMR_VECTOR_HPP
#if defined (_MSC_VER)
# pragma once
#endif
#include <sstd/boost/container/vector.hpp>
#include <sstd/boost/container/pmr/polymorphic_allocator.hpp>
namespace boost {
namespace container {
namespace pmr {
#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)
template <class T>
using vector = boost::container::vector<T, polymorphic_allocator<T>>;
#endif
//! A portable metafunction to obtain a vector
//! that uses a polymorphic allocator
template<class T>
struct vector_of
{
typedef boost::container::vector
< T, polymorphic_allocator<T> > type;
};
} //namespace pmr {
} //namespace container {
} //namespace boost {
#endif //BOOST_CONTAINER_PMR_VECTOR_HPP
| [
"[email protected]"
] | |
5cf0150cece4b4867666e4c5fa350e10db09c024 | 459d41f078a5bf9fdbc6acd519c8c04300970778 | /DeferredRenderingJingz/LightningRenderer.h | 378693d4e35e8147bed8392c06aa2000b106f962 | [] | no_license | wjingzhe/DeferredRenderingJingz | d4c518b59dd7eeeb3a08e522a20c9022c43fe627 | b84169ab4f13c9ac0e1ae2f497e6254359a4be59 | refs/heads/master | 2020-04-18T14:08:12.624130 | 2019-02-18T14:16:14 | 2019-02-18T14:16:45 | 167,581,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | h | #pragma once
#include <d3d11.h>
#include "ConstantBufferStructs.h"
#include "Camera.h"
class LightingRenderer
{
public:
LightingRenderer();
~LightingRenderer();
void Render(ID3D11RenderTargetView* pLightMapRT,
ID3D11ShaderResourceView* pAlbedo,
ID3D11ShaderResourceView* pNormal,
ID3D11ShaderResourceView* pDepth,
Camera* pCamera);
private:
ID3D11PixelShader* m_pLightingPixelShader;
LightingConstantBuffer m_LightConstantBufferStruct;
ID3D11Buffer* m_pConstantBuffer;
};
| [
"[email protected]"
] | |
da7caca18feae857264bc68f537e80d93b1334c4 | b89c63c4416e15039744f21118e22dfc1a53d3af | /Facade/test/WorkerATest.h | 3114afc0f34e12f47a3ed181bf0d774e9a5216a4 | [] | no_license | yfurukawa/DesignPattern_old | d21158c9a774374ab67f50503a132a6ec2ecb784 | 1adc917bc8182678a78caf9ab9f4ba66bd802114 | refs/heads/master | 2022-10-30T02:06:43.988601 | 2016-11-05T23:09:16 | 2016-11-05T23:09:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | h | #ifndef WORKERATEST_H_
#define WORKERATEST_H_
#include <gtest/gtest.h>
#include "WorkerA.h"
class WorkerATest : public ::testing::Test {
protected:
WorkerA* sut;
void SetUp();
void TearDown();
public:
WorkerATest();
virtual ~WorkerATest();
};
#endif
| [
"[email protected]"
] | |
7c56ff9931efc401da391e41a67d62b908a86671 | d542979d70c3ee01c4878490d4cf643769c15a18 | /leetcode_train/Solution_382.cpp | 83a78338d45971f67572a00f19369947b6cb790e | [] | no_license | lijiaxin-dut/leetcode | 1f08f0ecc88ce1069e46a965884b2c4ecd55931f | a707110de92276a3fc9eb42c857d752db64ca113 | refs/heads/master | 2022-12-31T14:23:03.679701 | 2020-10-12T11:49:30 | 2020-10-12T11:49:30 | 295,137,478 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 945 | cpp | #include<random>
#include"ListNode.h"
//水塘抽样
//维持一个大小为1的水塘
//遇到第k个数时,随机产生[0,k]的数
//如果产生的数为0 ,则更新水塘
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode *head;
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) :head(head) {
}
/** Returns a random node's value. */
int getRandom() {
int res = head->val;
int i = 2;
ListNode *cur = head->next;
while (cur) {
int j = rand() % i;
if (j == 0)
res = cur->val;
++i;
cur = cur->next;
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/ | [
"li_jiax@DESKTOP-HPQ1AKC"
] | li_jiax@DESKTOP-HPQ1AKC |
72c7ae7f870e8ece8b555a0207bade8efa3fc6e8 | 47f1b172aa4bf82afed7956742611b35983a24aa | /t3-venus/tpTools/cnsToolDll/include/uiDataMgr.h | da72e366fcc8c109901843d450d411bd5d4cd877 | [] | no_license | github188/TPS | 92e4a822bd51e5d9f0cb8df9c3d85f2ca9bb958f | b45510bc37837feda19733bec9d3d821e9fc787a | refs/heads/master | 2020-06-19T11:27:51.643398 | 2019-07-12T09:51:04 | 2019-07-12T09:51:04 | 196,691,872 | 0 | 1 | null | 2019-07-13T07:24:30 | 2019-07-13T07:24:29 | null | GB18030 | C++ | false | false | 16,456 | h | // uiDataMgr.h: interface for the CUIDataMgr class.
/*****************************************************************************
模块名 : 窗口相关的公共数据管理模块
文件名 : uiDataMgr.h
相关文件 : 所有窗口相关的全局数据应存放在此处
文件实现功能: 管理窗口数据
作者 : 俞锦锦
版本 : V1.0 Copyright(C) 2011-2012 KDC, All rights reserved.
-----------------------------------------------------------------------------
修改记录:
日 期 版本 修改人 修改内容
2012/11/23 1.0 景洋洋 创建
******************************************************************************/
#if !defined(AFX_UIDATAMGR_H__C2E44322_FA60_408C_972F_0701D85D461C__INCLUDED_)
#define AFX_UIDATAMGR_H__C2E44322_FA60_408C_972F_0701D85D461C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "templateClass.h"
//ip的数据结构
typedef struct IP_Struct{
//ip地址划分后各个域的值
struct IpAdress_Struct
{
int first;
int second;
int third;
int forth;
}IpAdress,*pIPAdress;
//ip地址
char szIPAdress[MAX_PATH];
//子网掩码
char szIPMask[MAX_PATH];
IP_Struct()
{
strcpy(szIPAdress,"");
strcpy(szIPMask,"");
}
IP_Struct(char szIPAdress[],char szIPMask[])
{
strcpy(this->szIPAdress,szIPAdress);
strcpy(this->szIPMask,szIPMask);
}
}IP,*pIP;
class CUIDataMgr:public ISingleTon<CUIDataMgr>
{
public:
CUIDataMgr();
virtual ~CUIDataMgr();
/*---------------------------------------------------------------------
* 功 能:向外部窗口发送通知
* 输入参数:
* 输出参数:
* 返 回 值:返回FALSE则发送失败
* 备 注:
* 日期 版本 修改人 修改记录
* 2012.12.13 1.0 俞锦锦 创建
----------------------------------------------------------------------*/
BOOL NotifyOuterWnd( UINT nMsg , WPARAM wparam, LPARAM lparam );
/*=============================================================================
函 数 名:IsFileExist
功 能:检测文件是否存在
参 数:const CString& strFileFullPath [in] 文件全路径名称
注 意:无
返 回 值:TRUE: 成功 FALSE:失败
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2012/12/14 1.0 刘德印 创建
=============================================================================*/
BOOL IsFileExist(const CString& strFileFullPath);
/*=============================================================================
函 数 名:IsFolderExist
功 能:检测目录是否存在
参 数:const CString& strFolderFullPath [in] 目录全路径名称
注 意:无
返 回 值:TRUE: 成功 FALSE:失败
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2012/12/14 1.0 刘德印 创建
=============================================================================*/
BOOL IsFolderExist(const CString& strFolderFullPath);
/*=============================================================================
函 数 名:IsIniFile
功 能:检测是否是ini文件用于会议模板和地址文件检测
参 数:const String& strFileName [in] 文件全路径名称
注 意:无
返 回 值:TRUE: 成功 FALSE:失败
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2012/12/14 1.0 刘德印 创建
=============================================================================*/
BOOL IsIniFile(const String& strFileName);
/*=============================================================================
函 数 名:GetIpStr
功 能:将普通类型转化为IP串
参 数:unsigned int dwIPAddr [in] IP的整型表示形式
注 意:无
返 回 值:类似“127.0.0.1”形式
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2012/12/14 1.0 刘德印 创建
=============================================================================*/
CString GetIpStr(unsigned int dwIPAddr);
/*=============================================================================
函 数 名: GetFileFolderPath
功 能: 得到文件所在文件夹路径名
参 数: const String& strFilePath [in] 文件全路径名
注 意:无
返 回 值:String 文件所在文件夹路径名
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2013/01/28 1.0 刘德印 创建
=============================================================================*/
String GetFileFolderPath(const String& strFilePath);
/*=============================================================================
函 数 名: OpenBrowseForFolder
功 能: 浏览打开文件目录(应用在文件保存、下载、导出等)
参 数: const String& strFileName [in] 文件名
参 数: HWND hWnd [in] 若为模态对话框,hWnd为父窗口句柄 by xhx
参 数: BOOL bIsAddFileName [in] 是否附加文件名 FALSE则直接得到目录名
注 意:无
返 回 值:String 文件全路径
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2013/01/28 1.0 刘德印 创建
=============================================================================*/
String OpenBrowseForFolder(const String& strFileName, HWND hWnd = NULL, BOOL bIsAddFileName = TRUE );
/*=============================================================================
函 数 名: OpenFileDialog
功 能: 打开文件目录(应用在文件另存为、导入、打开等)
参 数: const String& strFilter [in] 过滤文件
参 数: const String& strDefFileName [in] 默认显示文件名
参 数: const String& strFilePathName [out] 文件全路径
参 数: String strFileName [out] 文件名
参 数: BOOL bOpenStyle [in] 标明是浏览还是保存
注 意:无
返 回 值:String 文件全路径
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2013/01/28 1.0 刘德印 创建
=============================================================================*/
BOOL OpenFileDialog( const String& strFilter, const String& strDefFileName, String& strFilePathName,
String& strFileName, BOOL bOpenStyle = TRUE );
/*=============================================================================
函 数 名: OpenMutiFileDlg
功 能: 打开文件目录(应用在文件另存为、导入、打开等), 选择多个文件
参 数: const String& strFilter [in] 过滤文件
参 数: const String& strDefFileName [in] 默认显示文件名
参 数: const String& strFilePathName [out] 文件全路径
参 数: vector<String>& vecStrFileName [out] 全部文件名
参 数: BOOL bOpenStyle [in] 标明是浏览还是保存
注 意:无
返 回 值:String 文件全路径
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2013/01/28 1.0 刘德印 创建
=============================================================================*/
BOOL OpenMutiFileDlg( const String& strFilter, const String& strDefFileName, String& strFilePathName,
vector<String>& vecStrFileName, BOOL bOpenStyle = TRUE );
/*=============================================================================
函 数 名: CheckTransferFile
功 能: 检测传输全路径和文件名的合法性
参 数: const String strFileFullPath [in] 待检测的文件全路径
参 数: const String strCheckFileName [in] 待检测的文件名
注 意:无
返 回 值:BOOL
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2013/01/28 1.0 刘德印 创建
=============================================================================*/
BOOL CheckTransferFile( const String& strFileFullPath, const String& strCheckFileName );
/*=============================================================================
函 数 名: GetFileSize
功 能: 得到文件大小
参 数: const String strFilePath [in] 文件全路径
注 意:无
返 回 值:u64 字节数
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2013/02/01 1.0 刘德印 创建
=============================================================================*/
u64 GetFileSize( const String& strFilePath );
/*=============================================================================
函 数 名: RecusionMkDir
功 能: 递归创建目录, 如果目录已经存在或者创建成功返回TRUE
参 数: CString strFolder [in] 待创建文件夹路径
注 意:无
返 回 值:BOOL
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2013/01/28 1.0 刘德印 创建
=============================================================================*/
BOOL RecusionMkDir(CString strFolder);
/*=============================================================================
函 数 名:SetLstSelItem
功 能: 设置列表控件的选中行(默认去除选中项)
参 数: const String& strLstWnd [in] 列表名
参 数: IWndTree* pWndTree [in] 窗口所在
参 数: s32 nItemNo [in] 选中行号
注 意:无
返 回 值:BOOL
-------------------------------------------------------------------------------
修改纪录:
日 期 版本 修改人 修改内容
2013/01/17 1.0 刘德印 创建
=============================================================================*/
void SetLstSelItem( const String& strLstWnd, IWndTree* pWndTree = NULL, s32 nItemNo = -1 );
//是否是正确的密码格式
bool IsValidPWStr( CString szPWStr ) ;
//是否是正确的会场名称
bool IsValidNameStr( String strText );
//判断ip是否合理及获取ip各个域的值
bool JudgeIp(char *szIP, IP_Struct::IpAdress_Struct *ipAdress);
//判断是否同一网段
int IsSameNetworkSegment(char *szIPAdress, char *szIPAdresss1, char *szMask);
//是否是正确的IPV6
bool IsValidIpV6( CString szPWStr );
private:
};
#define UIDATAMGR_PTR CUIDataMgr::GetSingletonPtr()
//主要界面信息
extern const string g_stcMsgboxDlg; //警示弹出框
extern const string g_strMainFrame; //cnsTool 主界面
extern const string g_strBasicInfoDlg; //基本信息界面
extern const string g_strCfgFrame; //配置框架
extern const string g_strCfgCnsDlg; //配置框架中的cns界面
extern const string g_strCfgAudioPort; //配置框架中的音频配置界面
//extern const String g_strCfgMixDlg; //配置框架中的混音配置界面
extern const String g_strCfgAudioDlg; //配置框架中的音频配置界面
extern const string g_strCfgMainAudioDlg; //配置框架中的主音频配置界面
extern const string g_strCfgDemonStrationDlg; //配置框架中的演示源设置界面
extern const string g_strCfgAdjustImageDlg; //配置框架中的图像参数配置界面
extern const String g_strRenameOptDlg; //重命名窗口
extern const string g_strCnsCfg ; //CNS配置
//extern const string g_strDiagInfoDlg; //诊断测试界面
extern const string g_strCfgDiagnosticFrame; //诊断测试界面
extern const string g_strDiagInterfaceDlg; //接口诊断界面
extern const string g_strNetDiagnosticDlg; //网络诊断界面
extern const string g_strNetPacketDlg; //网口抓包界面
extern const string g_strCentCfgFrame; //中控信息界面
extern const string g_strDiagInTestInfo; //输入测试界面
extern const string g_strDiagOutTestInfo; //输出测试界面
extern const string g_strDiagTestFrame; //诊断测试显示界面
extern const string g_strDiagStatistic; //统计界面
extern const String g_stcStrCfgNetMngDlg; //网管配置界面
extern const String g_stcStrCfgNetSecurityDlg; //网络安全配置界面
extern const String g_stcStrRouteCfgDlg; //路由添加配置界面
extern const String g_stcStrNetMngOptDlg; //网管操作界面
extern const String g_StrCameraDlg; //摄像调节界面
extern const String g_strAddrbookExpDlg; //地址簿界面
extern const String g_strCfgServerDlg; //配置框架中的服务器界面
extern const String g_strCfgEqDlg; //配置框架中的均衡器界面
extern const String g_stcStrImpCommonDlg; //上传(导入)通用弹出界面
extern const String g_stcStrExpCommonDlg; //下载(导出)通用弹出界面
extern const String g_strWarningDlg; //界面左下角警示界面
extern const String g_strCfgCallSer; //呼叫配置界面
extern const String g_strCfgAdvanceDlg; //高级配置界面
extern const String g_strCentAirCondition; //中控空调界面
extern const String g_strCentCameraDlg; //中控摄像机界面
extern const String g_strCentLightDlg; //中控灯光界面
extern const String g_strCentDisplayDlg; //中控电视机界面
extern const String g_strCentStatusMesDlg; //中控状态信息界面
extern const String g_strCentCurtainDlg; //中控窗帘配置界面
extern const String g_strCentDuoVideo; //中控双流屏配置界面
extern const String g_strCentMatrix; //中控双流屏配置界面
extern const String g_strCentSrceen; //中控双流屏配置界面
//主要方案
extern const string g_strShmShow ; //显示方案, 所有调用该方案的窗口需要将xml的方案名设置为 "SchmShow"
extern const string g_strShmHide ; //隐藏方案, 所有调用该方案的窗口需要将xml的方案名设置为 "SchmHide"
#define ADDRBOOK_FILE_PATH "/usr/conf/"
#define ADDRBOOK_FILE_NAME "kdvaddrbook.kdv"
#define CNSLOG_FILE_PATH "/usr/kdvlog/log/"
#define CNSLOG_FILE_NAME "cnlog.ini"
#define CNSCONFIG_FILE_PATH "/usr/conf/"
#define CNSCONFIG_FILE_NAME "cncfg.ini"
#define CNSCONFIG_FILE_EXT_PATH "/usr/"
#define CNSCONFIG_FILE_NAME_ZERO "0cncfg.ini"
#define CNSCONFIG_FILE_NAME_ONE "1cncfg.ini"
#define CNSCONF_FILE_PATH "/usr/bin/"
#define CNSCAPTURE_FILE_PATH "/ramdisk/"
#define REMOTE_FILE_NAME "/ramdisk/kdvcapture.pcap"
#define CNS_T300E_TUMP_NAME "tcpdump.t300e"
#define CAPTURE_FILE_NAME "kdvcapture.pcap"
#define CNSUPGRADE_FILE_NAME "tpcns.bin"
#define CNSCAMERA_FILE_PATH "/usr/conf/"
#define CNSCAMERA_FILE_NAME "cameracfg.ini"
#define CNSSNAPSHOT_FILE_PATH "download"
#define CNSSNAPSHOT_FILE_NAME1 "snapshot0.jpg"
#define CNSSNAPSHOT_FILE_NAME2 "snapshot1.jpg"
#define CNSSNAPSHOT_FILE_NAME3 "snapshot2.jpg"
#define CNSUPGRADE_NAME "T300E.bin"
#define CNSUPGRADE_NAME_Y "T300E-y.bin"
#define CAPTURE_FILE_MAX_SIZE 199*1024*1024
#define SOFTWARE_BOUNDARY_VERSION "V1.1.6" //ftp用户名密码变更临界版本
//#define SOFTWARE_BETA_VERSION 6 //做用户名和密码兼容老版本用
#endif // !defined(AFX_UIDATAMGR_H__C2E44322_FA60_408C_972F_0701D85D461C__INCLUDED_)
| [
"[email protected]"
] | |
ab64fab10a7c1ad1ad8c54dae381bc2ea2c26fa0 | 5989c871781855a835f3c6727c7abf409c6f16db | /Deep_Neural_Networks/Load_Caffe_framework_models/Load_Caffe_framework_models.cpp | 37a8eaac5b8bc43588e74e0d5c869978a1c911d0 | [] | no_license | linmonsv/OpenCV_Tutorials | a8bf63972b4f3dde53e9a0d87f56aa8dacdca497 | 3c18669450014f22e2bcb8048159b9549944ba2b | refs/heads/master | 2023-01-19T22:22:22.741619 | 2020-11-27T09:41:34 | 2020-11-27T09:41:34 | 266,031,866 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,497 | cpp | #include <fstream>
#include <sstream>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include "common.hpp"
std::string keys =
"{ help h | | Print help message. }"
"{ @alias | | An alias name of model to extract preprocessing parameters from models.yml file. }"
"{ zoo | models.yml | An optional path to file with preprocessing parameters }"
"{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera.}"
"{ framework f | | Optional name of an origin framework of the model. Detect it automatically if it does not set. }"
"{ classes | | Optional path to a text file with names of classes. }"
"{ backend | 0 | Choose one of computation backends: "
"0: automatically (by default), "
"1: Halide language (http://halide-lang.org/), "
"2: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
"3: OpenCV implementation }"
"{ target | 0 | Choose one of target computation devices: "
"0: CPU target (by default), "
"1: OpenCL, "
"2: OpenCL fp16 (half-float precision), "
"3: VPU }";
using namespace cv;
using namespace dnn;
std::vector<std::string> classes;
int main(int argc, char** argv)
{
CommandLineParser parser(argc, argv, keys);
const std::string modelName = parser.get<String>("@alias");
const std::string zooFile = parser.get<String>("zoo");
keys += genPreprocArguments(modelName, zooFile);
parser = CommandLineParser(argc, argv, keys);
parser.about("Use this script to run classification deep learning networks using OpenCV.");
if (argc == 1 || parser.has("help"))
{
//parser.printMessage();
//return 0;
}
float scale = parser.get<float>("scale");
Scalar mean = (104, 117, 123);// parser.get<Scalar>("mean");
bool swapRB = parser.get<bool>("rgb");
int inpWidth = 224;// parser.get<int>("width");
int inpHeight = 224;// parser.get<int>("height");
String model = "bvlc_googlenet.caffemodel";// findFile(parser.get<String>("model"));
String config = "bvlc_googlenet.prototxt";// findFile(parser.get<String>("config"));
String framework = parser.get<String>("framework");
int backendId = parser.get<int>("backend");
int targetId = parser.get<int>("target");
// Open file with classes names.
//if (parser.has("classes"))
{
std::string file = "classification_classes_ILSVRC2012.txt";// parser.get<String>("classes");
std::ifstream ifs(file.c_str());
if (!ifs.is_open())
CV_Error(Error::StsError, "File " + file + " not found");
std::string line;
while (std::getline(ifs, line))
{
classes.push_back(line);
}
}
if (!parser.check())
{
//parser.printErrors();
//return 1;
}
CV_Assert(!model.empty());
Net net = readNet(model, config, framework);
net.setPreferableBackend(backendId);
net.setPreferableTarget(targetId);
// Create a window
static const std::string kWinName = "Deep learning image classification in OpenCV";
namedWindow(kWinName, WINDOW_NORMAL);
VideoCapture cap;
if (true) // (parser.has("input"))
cap.open("test.jpg");// cap.open(parser.get<String>("input"));
else
cap.open(0);
// Process frames.
Mat frame, blob;
while (waitKey(1) < 0)
{
cap >> frame;
if (frame.empty())
{
waitKey();
break;
}
blobFromImage(frame, blob, scale, Size(inpWidth, inpHeight), mean, swapRB, false);
net.setInput(blob);
Mat prob = net.forward();
Point classIdPoint;
double confidence;
minMaxLoc(prob.reshape(1, 1), 0, &confidence, 0, &classIdPoint);
int classId = classIdPoint.x;
// Put efficiency information.
std::vector<double> layersTimes;
double freq = getTickFrequency() / 1000;
double t = net.getPerfProfile(layersTimes) / freq;
std::string label = format("Inference time: %.2f ms", t);
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
// Print predicted class.
label = format("%s: %.4f", (classes.empty() ? format("Class #%d", classId).c_str() :
classes[classId].c_str()),
confidence);
putText(frame, label, Point(0, 40), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
imshow(kWinName, frame);
}
return 0;
} | [
"[email protected]"
] | |
e83bb19bcb4fa147870a1ab0dcca77c524a3ee03 | 05118ca931baadc5f95a1da79161de2ad6aeb0bc | /app/src/main/cpp/main.cpp | 0a5db5a6bec9843b4f9f6a7afb0c995c9a21fd39 | [] | no_license | xiaoxiaochu/NdkDemoProject | a459d7720d1254993fc28307876543d2c8f14386 | c639bc45c809feddcba1ac5445e1231923576d77 | refs/heads/master | 2021-09-11T13:50:55.764565 | 2018-04-08T09:09:01 | 2018-04-08T09:09:01 | 125,789,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,805 | cpp | //
// Created by go on 2018/1/29.
//
//BEGIN_INCLUDE(all)
#include <jni.h>
#include <errno.h>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include <android/sensor.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "native-activity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "native-activity", __VA_ARGS__))
/**
* Our saved state data.
*/
struct saved_state {
float angle;
int32_t x;
int32_t y;
};
/**
* Shared state for our app.
*/
struct engine {
struct android_app* app;
ASensorManager* sensorManager;
const ASensor* accelerometerSensor;
ASensorEventQueue* sensorEventQueue;
int animating;
EGLDisplay display;
EGLSurface surface;
EGLContext context;
int32_t width;
int32_t height;
struct saved_state state;
};
/**
* Initialize an EGL context for the current display.
*/
static int engine_init_display(struct engine* engine) {
// initialize OpenGL ES and EGL
/*
* Here specify the attributes of the desired configuration.
* Below, we select an EGLConfig with at least 8 bits per color
* component compatible with on-screen windows
*/
const EGLint attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLint w, h, format;
EGLint numConfigs;
EGLConfig config;
EGLSurface surface;
EGLContext context;
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(display, 0, 0);
/* Here, the application chooses the configuration it desires. In this
* sample, we have a very simplified selection process, where we pick
* the first EGLConfig that matches our criteria */
eglChooseConfig(display, attribs, &config, 1, &numConfigs);
/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
* guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
* As soon as we picked a EGLConfig, we can safely reconfigure the
* ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);
surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
context = eglCreateContext(display, config, NULL, NULL);
if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
LOGW("Unable to eglMakeCurrent");
return -1;
}
eglQuerySurface(display, surface, EGL_WIDTH, &w);
eglQuerySurface(display, surface, EGL_HEIGHT, &h);
engine->display = display;
engine->context = context;
engine->surface = surface;
engine->width = w;
engine->height = h;
engine->state.angle = 0;
// Initialize GL state.
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
glEnable(GL_CULL_FACE);
glShadeModel(GL_SMOOTH);
glDisable(GL_DEPTH_TEST);
return 0;
}
/**
* Just the current frame in the display.
*/
static void engine_draw_frame(struct engine* engine) {
if (engine->display == NULL) {
// No display.
return;
}
// Just fill the screen with a color.
glClearColor(((float)engine->state.x)/engine->width, engine->state.angle,
((float)engine->state.y)/engine->height, 1);
glClear(GL_COLOR_BUFFER_BIT);
eglSwapBuffers(engine->display, engine->surface);
}
/**
* Tear down the EGL context currently associated with the display.
*/
static void engine_term_display(struct engine* engine) {
if (engine->display != EGL_NO_DISPLAY) {
eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (engine->context != EGL_NO_CONTEXT) {
eglDestroyContext(engine->display, engine->context);
}
if (engine->surface != EGL_NO_SURFACE) {
eglDestroySurface(engine->display, engine->surface);
}
eglTerminate(engine->display);
}
engine->animating = 0;
engine->display = EGL_NO_DISPLAY;
engine->context = EGL_NO_CONTEXT;
engine->surface = EGL_NO_SURFACE;
}
/**
* Process the next input event.
*/
static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
struct engine* engine = (struct engine*)app->userData;
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
engine->animating = 1;
engine->state.x = AMotionEvent_getX(event, 0);
engine->state.y = AMotionEvent_getY(event, 0);
return 1;
}
return 0;
}
/**
* Process the next main command.
*/
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
struct engine* engine = (struct engine*)app->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
// The system has asked us to save our current state. Do so.
engine->app->savedState = malloc(sizeof(struct saved_state));
*((struct saved_state*)engine->app->savedState) = engine->state;
engine->app->savedStateSize = sizeof(struct saved_state);
break;
case APP_CMD_INIT_WINDOW:
// The window is being shown, get it ready.
if (engine->app->window != NULL) {
engine_init_display(engine);
engine_draw_frame(engine);
}
break;
case APP_CMD_TERM_WINDOW:
// The window is being hidden or closed, clean it up.
engine_term_display(engine);
break;
case APP_CMD_GAINED_FOCUS:
// When our app gains focus, we start monitoring the accelerometer.
if (engine->accelerometerSensor != NULL) {
ASensorEventQueue_enableSensor(engine->sensorEventQueue,
engine->accelerometerSensor);
// We'd like to get 60 events per second (in us).
ASensorEventQueue_setEventRate(engine->sensorEventQueue,
engine->accelerometerSensor, (1000L/60)*1000);
}
break;
case APP_CMD_LOST_FOCUS:
// When our app loses focus, we stop monitoring the accelerometer.
// This is to avoid consuming battery while not being used.
if (engine->accelerometerSensor != NULL) {
ASensorEventQueue_disableSensor(engine->sensorEventQueue,
engine->accelerometerSensor);
}
// Also stop animating.
engine->animating = 0;
engine_draw_frame(engine);
break;
}
}
/**
* This is the main entry point of a native application that is using
* android_native_app_glue. It runs in its own thread, with its own
* event loop for receiving input events and doing other things.
*/
void android_main(struct android_app* state) {
struct engine engine;
// Make sure glue isn't stripped.
app_dummy();
memset(&engine, 0, sizeof(engine));
state->userData = &engine;
state->onAppCmd = engine_handle_cmd;
state->onInputEvent = engine_handle_input;
engine.app = state;
// Prepare to monitor accelerometer
engine.sensorManager = ASensorManager_getInstance();
engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
ASENSOR_TYPE_ACCELEROMETER);
engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
state->looper, LOOPER_ID_USER, NULL, NULL);
if (state->savedState != NULL) {
// We are starting with a previous saved state; restore from it.
engine.state = *(struct saved_state*)state->savedState;
}
// loop waiting for stuff to do.
while (1) {
// Read all pending events.
int ident;
int events;
struct android_poll_source* source;
// If not animating, we will block forever waiting for events.
// If animating, we loop until all events are read, then continue
// to draw the next frame of animation.
while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
(void**)&source)) >= 0) {
// Process this event.
if (source != NULL) {
source->process(state, source);
}
// If a sensor has data, process it now.
if (ident == LOOPER_ID_USER) {
if (engine.accelerometerSensor != NULL) {
ASensorEvent event;
while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
&event, 1) > 0) {
LOGI("accelerometer: x=%f y=%f z=%f",
event.acceleration.x, event.acceleration.y,
event.acceleration.z);
}
}
}
// Check if we are exiting.
if (state->destroyRequested != 0) {
engine_term_display(&engine);
return;
}
}
if (engine.animating) {
// Done with events; draw next animation frame.
engine.state.angle += .01f;
if (engine.state.angle > 1) {
engine.state.angle = 0;
}
// Drawing is throttled to the screen update rate, so there
// is no need to do timing here.
engine_draw_frame(&engine);
}
}
}
//END_INCLUDE(all) | [
"[email protected]"
] | |
98e9133cc72955647cd90f523e937330d5d9ee48 | 8accb31bb0677b1dd206d3c6a0ff951105f29f0e | /Hmwk/Assignment_3/Gaddis_8thEd_Chap4_Prob6_MassandWeight/main.cpp | 982a141eb27d9b39c324c1092648915d0fcad389 | [] | no_license | ks2205484/SchallKristopher_CIS5_44187 | 155a4d7516d0dda96c2154fa412e0b064e59aaae | 8b7e212f91ab08a7bceb54df696d60499dd0c8f8 | refs/heads/master | 2021-01-21T11:54:30.946212 | 2017-06-02T04:29:16 | 2017-06-02T04:29:16 | 85,154,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | cpp | /*
* File: main.cpp
* Author: Kristopher, Schall
* Created on March 19, 2017, 5:30 PM
* Purpose: Calculate the weight of an object in Newtons
*/
//System Libraries
#include <iostream> //Input - Output Library
using namespace std; //Name-space under which system libraries exist
//User Libraries
//Global Constants
//Function Prototypes
//Execution begins here
int main(int argc, char** argv) {
//Declare variables
double mass, weight;
//Initialize variables
//Input data
cout<<"Enter an object's Mass (in Kilograms): ";
cin>>mass;
//Map inputs to outputs or process the data
weight=mass*9.8;
//Output the transformed data
cout<<"**********************************\n";
if(weight>1000)
{cout<<"The object's Mass is too Heavy \n";}
if(weight<10)
{cout<<"The object's Mass is too Light \n";}
if(weight>=10&&weight<=1000)
{cout<<"The Weight is: "<<weight<<" Newtons \n";}
cout<<"**********************************";
//Exit stage right!
return 0;
}
| [
"[email protected]"
] | |
91fdb9fe4982d5463462e1add602ae2aaefbca3b | fcccaa83e27090cbb62cbc73b5479dc72d1fb017 | /client/informationBox.h | d32914a2988001ab9246895f335a11a0b03d08a6 | [] | no_license | linvon/QQ | 04be904ad32435e3ed50f35eeff149efb5910c4d | a783c32a1e9030181f592e3a965d5bf1ccb3dd3e | refs/heads/master | 2022-04-09T14:54:26.226391 | 2020-02-21T08:06:14 | 2020-02-21T08:06:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,337 | h | #ifndef INFORMATIONBOX_H_
#define INFORMATIONBOX_H_
#include "constant.h"
#include "links.h"
#include "ui_informationBox.h"
//用于显示或修改信息时用的窗口
class InformationBox : public QWidget
{
Q_OBJECT
private:
Ui::informationBoxForm ui;
QString confirmPwd; //验证的密码
int num;
static const int all = 134; //总头像数
public:
InformationBox(QWidget *parent);
virtual ~InformationBox() = 0;
//获取用户输入的信息
UserInformation getUserInformation();
//将所有栏目设置为只读(用于查看信息)
void setAllReadOnly(bool enable);
//将除帐号,密码栏之外的栏目设为只读
void setMostReadOnly(bool enable);
//将帐号,密码栏设置为只读
void setSomeReadOnly(bool enable);
//将好友信息填入栏目中
void setUserInformation(const UserInformation &userInf);
//(输入的)个人信息的格式是否符合要求
//不知为什么,这个函数不能设为const
bool informationIsAllow();
//(输入的)密码的格式是否符合要求
//不知为什么,这个函数不能设为const
bool passwordIsAllow();
public slots:
void clickedQuitButton();
//完成按钮(纯虚函数)
virtual void clickedOKButton() = 0;
void clickedPastButton();
void clickedNextButton();
void clickedHelpButton();
};
#endif | [
"[email protected]"
] | |
c19011972f1469cc151eab73fb43fd13c2633227 | a9351444445ba6bbe519c9c6a7871577f447f145 | /codechef/BSTOPS/sync_studio.cpp | f93e89021af10851385554e3b9e01dd91a2014ba | [] | no_license | krishnausjs/codechef | a9bf32cb23f1c3162cab4702e9928ac35d649e6f | bc1307b38fbe3d539258df023e36689c327ee52a | refs/heads/master | 2020-05-06T20:19:10.250594 | 2019-04-24T05:25:12 | 2019-04-24T05:25:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 163 | cpp | #include <iostream>
#include <cstdio>
int main()
{
std::ios::sync_with_stdio(true);
std::cout << "a\n";
std::printf("b\n");
std::cout << "c\n";
} | [
"[email protected]"
] | |
bc980692df429b091e1807d9d72581129d6c1fd0 | 5e430b2b5e686e45408ed806ed6c3b85d0f17bd8 | /其他/Ctest/SwapString.cpp | 533d90aa55e4a002b1dc3c4f4f297c90796fbaf7 | [] | no_license | Z21459/OtherDemo | 71090ca3b90dce6f996928fee40adca4350ec6fa | 56aae2886e67563d0184d235214274577ba3cc2c | refs/heads/master | 2022-12-21T05:36:13.129717 | 2020-09-21T12:17:13 | 2020-09-21T12:17:13 | 292,588,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | cpp | #include<stdio.h>
#incldue <stdlib.h>
#incldue <string.h>
char *x = "sda";
char *y = "daf";
Swap(x,y)
void Swap(char*&x,char*&y){
char *temp = x;
x=y;
y = temp;
}
| [
"[email protected]"
] | |
045da2897f2d792d967ea6228869b5127f22952f | fca6aeb4064ea493b1b2cce738b0da0139672b33 | /SpaceEconSim/ResourceManager.hpp | 915c93e8ca606a27135969318e163df2f5a12d98 | [] | no_license | mwhiticker/gam302-spacesim | 826f24b1e38ac845f05d0e6db0c2e9a102cdb0a9 | d9c6d3477fed9e55b7a509b4881ff8eac0df74fc | refs/heads/master | 2021-01-16T00:27:56.219878 | 2012-05-02T22:36:47 | 2012-05-02T22:36:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | hpp | #ifndef RESOURCE_MANAGER_HPP
#define RESOURCE_MANAGER_HPP
#include <string>
#include <vector>
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Rect.hpp>
namespace sf
{
class Image;
class Sprite;
class Texture;
};
class Anim;
class ResourceManager
{
public:
ResourceManager();
//
bool LoadSFMLImage(std::string FilePath, _Out_ sf::Image** Out = NULL );
bool CreateSprite(std::string FilePath, _Out_ sf::Sprite** = NULL, _In_ sf::Rect<int>* a_pSubRect = NULL );
bool CreateAnim(std::string FilePath, sf::Vector2f a_FrameSize, float FrameLength, short numFrames, _Out_ Anim** a_ppOut = NULL );
//
private:
//
std::vector< std::pair<std::string, sf::Image*> > Images;
std::vector< std::pair<std::string, sf::Texture*> > Textures;
std::vector< std::pair<std::string, sf::Sprite*> > Sprites;
};
#endif //RESOURCE_MANAGER_HPP | [
"[email protected]"
] | |
144514b9716f3691a8ce4a9697e7bf38025055bb | 9163f9fc0c303bf3ed44efabad48db685011da7a | /fabric/IClassFactory.cpp | c033cc08ea33fba3b946d7b4e902dea571daf5c5 | [] | no_license | Worik42/com_1 | 99602be1b9f5c9d543d58b0694d6ce9f375f3db2 | 3f01250abffb06c87f22278d2798b682fdf94c22 | refs/heads/master | 2022-04-09T03:03:26.489494 | 2020-03-18T04:49:20 | 2020-03-18T04:49:20 | 247,017,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | cpp | #include "IClassFactory.h"
#include "IUnknown_.h"
#include "CFB.h"
#include "CFA.h"
#include <iostream>
HResult_ getClassObject(CLSID_ &clsid, IID_ &iid, void **ppv)
{
HResult_ res;
if (clsid == 1)
{
CFA *cfa = new CFA();
*ppv = (void *)(IClassFactory *)(CFA *)ppv;
}
else if (clsid == 2)
{
CFB *cfb = new CFB();
*ppv = (void *)(IClassFactory *)(CFB *)ppv;
return res;
}
else
{
ppv = NULL;
return 1;
}
} | [
"[email protected]"
] | |
0f61776468fa09171d3fa1543b1fbf1c79d54bd5 | ac22b21732a48010bceae4629172583cc929cff9 | /parseRun.h | cd53723d78e27e79f5868a45b00e7975aafd653b | [] | no_license | Quizno97/CS280-PA4 | 1d5ea3dfb2698fe2ebabc9d592777540223d4a51 | a9eb249bb2842d6dad69a06fea2f0354cb05f737 | refs/heads/master | 2023-02-04T23:22:38.899560 | 2020-12-24T16:24:39 | 2020-12-24T16:24:39 | 324,195,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,515 | h | #ifndef PARSE_H_
#define PARSE_H_
#include <iostream>
#include <map>
using namespace std;
#include "lex.h"
//using std::map;
map<string, bool> defVar;
namespace Parser {
bool pushed_back = false;
LexItem pushed_token;
static LexItem GetNextToken(istream& in, int& line) {
if( pushed_back ) {
pushed_back = false;
//cout<< "returned token: " << pushed_token.GetLexeme() << endl;
return pushed_token;
}
return getNextToken(in, line);
}
static void PushBackToken(LexItem & t) {
if( pushed_back ) {
//cout<< "Pushed token abort: " << t.GetLexeme() << endl;
abort();
}
pushed_back = true;
pushed_token = t;
//cout<< "Pushed token: " << t.GetLexeme() << endl;
}
}
static int error_count = 0;
void ParseError(int line, string msg)
{
++error_count;
cout << line << ": " << msg << endl;
}
extern bool Prog(istream& in, int& line);
extern bool StmtList(istream& in, int& line);
extern bool Stmt(istream& in, int& line);
extern bool PrintStmt(istream& in, int& line);
extern bool IfStmt(istream& in, int& line);
extern bool Var(istream& in, int& line, LexItem & tok);
extern bool AssignStmt(istream& in, int& line);
extern bool ExprList(istream& in, int& line);
extern bool Expr(istream& in, int& line, Value & retVal);
extern bool Term(istream& in, int& line, Value & retVal);
extern bool Factor(istream& in, int& line, Value & retVal);
#endif /* PARSE_H_ */ | [
"[email protected]"
] | |
591a7f6a7a3d0e5003c63ee418f83cc788639001 | 8701729a97243441c7a58c9ce25cb60c71075b3b | /include/component/componentMenuMain.hpp | f102a775400ed0ef8f4fb670473b468fdc0993bd | [] | no_license | Epithach/PawneMe | 42b8fcc915177323c782d34de2490451233c9dd1 | 334dd9987e6789188158a9d15a740ea8f32abfa2 | refs/heads/master | 2020-05-20T19:28:33.134316 | 2016-08-22T03:19:59 | 2016-08-22T03:19:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,097 | hpp | #ifndef COMPONENTMENUMAIN_HPP_
# define COMPONENTMENUMAIN_HPP_
#include "./componentMenu.hpp"
#include "../engine/engine_component.hpp"
#include "../bridge/bridgeToMenuSelection.hpp"
/* Obliger de le faire sois meme ... fucking sfml */
/**
* \class componentMenuMain
* \brief Class component du menu
* \author pixies
*/
class componentMenuMain : public engineComponent, protected componentMenu
{
public :
/* les default surement a modifier */
componentMenuMain();
virtual ~componentMenuMain() {
std::cout << "Destruction de ComponentMenuMain" << std::endl;
printf("%p\n", this);
}
componentMenuMain(componentMenuMain&) = delete;
componentMenuMain& operator=(componentMenuMain&) = delete;
virtual void update();
virtual void init(); /* A reflechir pour la signature */
private :
/**
* \fn virtual function createSprites
* \brief Crée les sprites et les push dans le vector de sprites
* \author pixies
*/
virtual void createSprites();
/**
* \fn virtual function fillRect
* \brief Remplie le vecteur de structure e_RectCoorSprite avec tout les sprites ajouté
* \author pixies
*/
virtual void fillRect();
/**
* \fn virtual function drawSprites
* \brief affiche les sprites du vecteur
* \author pixies
*/
virtual void drawSprites();
/**
* \fn virtual function keyboardMouseMenu
* \brief event clavier ou souris
* \author pixies
*/
virtual void keyboardMouseMenu();
/**
* \fn virtual function isContainMySprites
* \brief Fait une rectangulation des coordonée fournis avec les coordoné situé dans le vector de e_RectCoorSprite (recode de la fonction contain de la sfml)
* \param int x coordonnée X pointé par la souris int y coordonnéé y pointé par la souris
* \return true si un poin a été trouver, false sinon
* \author pixies
*/
virtual bool isContainsMySprites(int x , int y);
/* Get window from componentWindow STATIC */
sf::RenderWindow& _Cwindow;
sf::Texture _textureMenu;
t_InfSprite _spriteMenu;
/* A voir si on garde cette methode pour les texture */
/* Necessaire pour avoir la transparence PUTIN DE SFML*/
sf::Image _imgButtonPlay;
/* http://www.sfml-dev.org/tutorials/2.4/graphics-sprite-fr.php le moin de texture possible A VOIR */
/* http://www.sfml-dev.org/documentation/2.4.0-fr/classsf_1_1Texture.php */
sf::Texture _textureButtonPlay;
t_InfSprite _spriteButtonPlay;
sf::IntRect _buttonArea;
/* Le button prendra 15% de la taille de l'ecran */
static constexpr float _PourcentageButton = 85.0;
/* INFO/SIZE DU MENU */
static constexpr const auto& _fileTextureMenu = "./texture/menuStart/Hacker-silhouette.jpg";
static constexpr float _LwindowsMenu = 1000.0;
static constexpr float _HwindowsMenu = 664.0;
/* INFO/SIZE DES BOUTONS DU MENU */
static constexpr const auto& _fileTextureMenuPlay = "./texture/menuStart/playMenu.png";
static constexpr float _LwindowsMenuPlay = 67.0;
static constexpr float _HwindowsMenuPlay = 43.0;
};
#endif /* !COMPONENTMENUMAIN_HPP */
| [
"[email protected]"
] | |
e2e61c6c8aa1d149d15a1059c02bc8bccfd732d9 | d2eeac30463f23bfdb3f0ff60313faba814de660 | /vol_29/3827.cpp | 43f807446241d511bd624e8932fc5f46e043f834 | [] | no_license | xizhonghua/zoj | beb607b50d11afe76cc0cc1d96fdcd8b5d28ae70 | bbc94c079bfcdf3365755a98aa53c7b46dd903c8 | refs/heads/master | 2020-05-06T20:29:53.881738 | 2017-03-13T02:50:32 | 2017-03-13T02:50:32 | 12,126,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | cpp | // 3829420 2014-11-27 02:28:40 Accepted 3827 C++ 0 272 xxfflower
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
double p, b;
string unit;
double entropy = 0.0;
cin>>n>>unit;
if(unit == "bit") b = 2;
if(unit == "nat") b = exp(1.0);
if(unit == "dit") b = 10.0;
for(int i=0;i<n;i++)
{
cin>>p;
p/=100.0;
if(p != 0) {
entropy += p*log(p)/log(b);
}
}
cout<<std::fixed<<std::setprecision(12)<<-entropy<<endl;
}
return 0;
} | [
"[email protected]"
] | |
8c927f04d21de552c0d671fd43333e2282eb481d | 1827436f7345390bdc09c021722a185fae6edf23 | /SteamApi/SteamApi.cpp | 966c15823959e7cbf444f7e76227ef97a368a4ea | [] | no_license | galenelias/VapoRT | 506202902bc6e6af611ce554173cac323fe30863 | ba3b69d3a85a1f694fe410fb44be87a95ab00921 | refs/heads/master | 2021-01-01T18:29:09.444210 | 2013-02-03T06:50:27 | 2013-02-03T06:50:27 | 6,557,000 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 24,892 | cpp | #include "pch.h"
#include "SteamApi.h"
#include "pch.h"
#include <ctime>
#include <set>
#include "SteamAPI.h"
#include "SteamAPI_private.h"
#include "StandardUtils.h"
#include "SteamApiUtils.h"
using namespace Util;
namespace SteamAPI
{
class SteamConversation : public ISteamConversation
{
public:
SteamConversation(const std::shared_ptr<SteamUser> & user);
virtual SteamConversation_t GetMessages() override;
virtual IEvent<ISteamConversation, int>& GetConversationChangedEvent() override;
virtual int GetCount() override;
virtual SteamMessagePtr GetMessage(int index) override;
void SyncMessage(const wchar_t * pwzMessage, bool fromMe);
private:
void RefreshMessages();
void CreateChangeEvent(int x);
Event<ISteamConversation, int> m_ConversationChangedEvent;
SteamUserPtr m_User;
SteamConversation_t m_ConversationItems;
std::shared_ptr<concurrency::timer<int>> m_MessagePollTimer;
std::shared_ptr<concurrency::call<int>> m_MessagePollCallback;
};
/*static*/ CSQLite_Connection & CSteamDBConnection::GetInstance()
{
static CSQLite_Connection s_db;
return s_db;
}
// Append friend ids into a single semi-colon delimited string
template<class InputIterator>
std::wstring ConcatenateSteamIds(InputIterator first, InputIterator last)
{
std::wstring wstFriendIds;
std::for_each(first, last, [&wstFriendIds] (const SteamID_t & id)
{
if (!wstFriendIds.empty())
wstFriendIds += L";";
wstFriendIds += id;
});
return wstFriendIds;
}
/// SteamuserMessage ///
SteamUserMessage::SteamUserMessage(SteamUserPtr & user, const wchar_t * pwzMessage, time_t sentTime, bool fFromMe)
: m_fFromMe(fFromMe), m_wstMessage(pwzMessage), m_fromUser(user), m_sentTime(sentTime)
{
}
SteamMessagePtr CreateSteamUserMessageX(SteamUserPtr & user, const wchar_t * pwzMessage, time_t sentTime, bool fFromMe)
{
return SteamUserMessage::CreateSteamUserMessage(user, pwzMessage, sentTime, fFromMe);
}
/*static*/ SteamMessagePtr SteamUserMessage::CreateSteamUserMessage(SteamUserPtr & user, const wchar_t * pwzMessage, time_t sentTime, bool fFromMe)
{
return std::make_shared<SteamUserMessage>(user, pwzMessage, sentTime, fFromMe);
}
/// SteamUser ///
SteamUser::SteamUser(PrivateSteamConnectionPtr & steamConnection )
: m_connectionWeakPtr(steamConnection)
{
}
//SteamConversation_t SteamUser::GetConversationHistory()
//{
// SteamConversation_t rgConversationHistory;
// CSQLite_Connection & db = CSteamDBConnection::GetInstance();
// std::string strQuery = FormatStr("SELECT SteamID, FromMe, Message FROM ConversationHistory WHERE SteamID=\"%S\" ORDER BY Sent ASC ", GetSteamID());
// CSQLite_Results results = db.FRunQuery(strQuery.data());
// for (int iRow = 0; iRow != results.NRows(); ++iRow)
// {
// std::wstring stwMessage = StrMultiToWide(results[iRow][2]);
// std::string strFromMe = results[iRow][1];
// SteamUserPtr userPtr = shared_from_this();
// SteamMessagePtr msg = SteamUserMessage::CreateSteamUserMessage(userPtr, stwMessage.data(), time(nullptr), strFromMe == "True");
// rgConversationHistory.push_back(msg);
// }
// return rgConversationHistory;
//}
SteamConversationPtr SteamUser::GetConversation()
{
if (!m_conversation)
m_conversation = std::make_shared<SteamConversation>(shared_from_this());
return m_conversation;
}
concurrency::task<bool> SteamUser::SendMessage(const wchar_t * pwzMessage)
{
PrivateSteamConnectionPtr spConnection = m_connectionWeakPtr.lock();
if (!spConnection)
throw std::exception("Unexpected");
std::wstring wstrSteamID = m_SteamID;
std::wstring wstrMessage = pwzMessage;
time_t timestamp = time(nullptr);
SyncMessageFromNetwork(pwzMessage, true, timestamp);
return spConnection->ChatLogin().then([wstrMessage, wstrSteamID, spConnection](int)
{
return spConnection->SendUserMessage(wstrSteamID.data(), wstrMessage.data());
});
}
void SteamUser::SyncMessageFromNetwork(const wchar_t * pwzMessage, bool fromMe, time_t timestamp)
{
CSQLite_Connection & db = CSteamDBConnection::GetInstance();
std::wstring wstEscapedMessage = EscapeSQLString(pwzMessage);
std::string strQuery = FormatStr("INSERT INTO ConversationHistory VALUES ('%S', '%s', '%S', '%d')", GetSteamID(), fromMe ? "True" : "False", wstEscapedMessage.c_str(), timestamp);
CSQLite_Results results = db.FRunQuery(strQuery.data());
if (m_conversation)
m_conversation->SyncMessage(pwzMessage, fromMe);
}
void SteamUser::UpdateStatus(int newStatusInt)
{
OnlineStatus newStatus = ConvertIntToStatus(newStatusInt);
if (GetOnlineStatus() != newStatus)
{
SetOnlineStatus(newStatus);
m_StatusChangeEvent(this, 1 /*unused, property id?*/);
}
}
/// SteamConnection ///
void SteamConnection::AddPendingUserLookup(const SteamID_t & steamID)
{
m_setPendingUserLookups.insert(steamID);
}
void SteamConnection::AddPendingUserLookup(const FriendsList_t & rgSteamIDs)
{
for (auto& iter : rgSteamIDs)
AddPendingUserLookup(iter);
}
const SteamUserSet_t & SteamConnection::GetPendingUserLookupSet()
{
return m_setPendingUserLookups;
}
concurrency::task<bool> SteamConnection::SendUserMessage(const wchar_t *pwzSteamID, const wchar_t * pwzMessage)
{
//return concurrency::create_task([]()->bool
//{
// WaitForSingleObjectEx(GetCurrentThread(), 2000, TRUE);
// return true;
//});
VerifyLoggedIn();
WaitForSingleObjectEx(GetCurrentThread(), 2000, TRUE);
auto reqTask = m_dataConnection->SendUserMessage(pwzSteamID, pwzMessage);
auto thisPtr = shared_from_this();
concurrency::task_completion_event<bool> taskCompetion;
reqTask.then( [taskCompetion, thisPtr](http::http_response response)
{
if (response.status_code() == http::status_codes::OK)
{
http::json::value & jsonResponse = response.extract_json().get();
bool success = jsonResponse[L"error"].as_string() == L"OK";
taskCompetion.set(success);
}
else
{
taskCompetion.set(false);
}
}).then([taskCompetion](pplx::task<void> task)
{
try
{
task.get();
}
catch (...)
{
taskCompetion.set_exception(std::current_exception());
}
});
return concurrency::create_task(taskCompetion);
}
/// SteamLoginResult ///
class SteamLoginResult : public ILoginResult
{
public:
virtual bool GetLoginSuccessful() override { return m_fSuccessful; }
virtual const std::wstring & GetLoginError() override { assert(!m_fSuccessful); return m_strError; }
virtual const std::wstring & GetLoginErrorCode() override { assert(!m_fSuccessful); return m_strErrorCode; }
virtual const std::wstring & GetLoginErrorDescription() override { assert(!m_fSuccessful); return m_strErrorDescription; }
SteamLoginResult(bool fSuccessful);
SteamLoginResult(bool fSuccessful, const std::wstring & strError, const std::wstring &strErrorCode, const std::wstring & strErrorDescription);
static LoginResultPtr CreateSuccessfulSteamLoginResult();
static LoginResultPtr CreateErrorSteamLoginResult(const std::wstring & strError, const std::wstring & strErrorCode, const std::wstring & strErrorDescription);
private:
bool m_fSuccessful;
std::wstring m_strError;
std::wstring m_strErrorCode;
std::wstring m_strErrorDescription;
};
SteamLoginResult::SteamLoginResult(bool fSuccessful)
: m_fSuccessful(fSuccessful)
{ }
SteamLoginResult::SteamLoginResult(bool fSuccessful, const std::wstring & strError, const std::wstring & strErrorCode, const std::wstring & strErrorDescription)
: m_fSuccessful(fSuccessful)
, m_strError(strError)
, m_strErrorCode(strErrorCode)
, m_strErrorDescription(strErrorDescription)
{ }
/*static*/ LoginResultPtr SteamLoginResult::CreateSuccessfulSteamLoginResult()
{
return std::make_shared<SteamLoginResult>(true);
}
/*static*/ LoginResultPtr SteamLoginResult::CreateErrorSteamLoginResult(const std::wstring & strError, const std::wstring & strErrorCode, const std::wstring & strErrorDescription)
{
return std::make_shared<SteamLoginResult>(false, strError, strErrorCode, strErrorDescription);
}
SteamConnectionPtr CreateSteamConnection(const wchar_t *pwzDatabaseFile, bool fFakeDataSource)
{
SteamDataConnectionPtr dataConnection = MakeSteamDataConnection(fFakeDataSource);
return std::make_shared<SteamConnection>(pwzDatabaseFile, dataConnection);
}
SteamConnection::SteamConnection(const wchar_t *pwzDatabaseFile, const SteamDataConnectionPtr & dataConnection)
: m_wstDatabaseFile(pwzDatabaseFile)
, m_dataConnection(dataConnection)
, m_MessagePollNumber(-1)
{
SetupDatabase();
}
void SteamConnection::PollMessages(int)
{
OutputDebugString(L"Timer\n");
assert(m_MessagePollNumber != -1);
GetMessages(0, false);
}
void SteamConnection::SetupDatabase()
{
CSQLite_Connection & db = CSteamDBConnection::GetInstance();
db.FInitializeDatabase(StrWideToMulti(m_wstDatabaseFile.data()).data());
bool fCreated = db.FCreateTable("ConversationHistory", "SteamID TEXT, FromMe BOOLEAN, Message TEXT, Sent DATETIME");
fCreated = db.FCreateTable("UserTable", "SteamID TEXT, SteamGuard TEXT");
assert(fCreated);
}
bool SteamConnection::IsLoggedInToChat()
{
return true;
}
void SteamConnection::SetupChatPolling()
{
m_MessagePollCallback = std::make_shared<concurrency::call<int>>([this](int v){PollMessages(v); });
m_MessagePollTimer = std::make_shared<concurrency::timer<int>>(1000, 0, m_MessagePollCallback.get(), false);
m_MessagePollTimer->start();
}
concurrency::task<int> SteamConnection::ChatLogin()
{
VerifyLoggedIn();
auto reqTask = m_dataConnection->ChatLogin();
auto thisPtr = shared_from_this();
concurrency::task_completion_event<int> taskCompetion;
reqTask.then( [taskCompetion, thisPtr](http::http_response response)
{
if (response.status_code() == http::status_codes::OK)
{
http::json::value & jsonResponse = response.extract_json().get();
thisPtr->m_MessagePollNumber = jsonResponse[L"message"].as_integer();
thisPtr->SetupChatPolling();
taskCompetion.set(thisPtr->m_MessagePollNumber);
}
else
{
taskCompetion.set(-1);
}
}).then([taskCompetion](pplx::task<void> task)
{
try
{
task.get();
}
catch (...)
{
taskCompetion.set_exception(std::current_exception());
}
});
//TODO: set_exception on task completion event
return concurrency::create_task(taskCompetion);
}
concurrency::task<void> SteamConnection::GetMessages(int message, bool fSecure)
{
VerifyLoggedIn();
if (message == 0)
message = m_MessagePollNumber;
auto reqTask = m_dataConnection->GetMessages(message, m_PlayerSteamID.c_str(), fSecure);
auto thisPtr = shared_from_this();
concurrency::task_completion_event<void> taskCompetion;
reqTask.then( [taskCompetion, thisPtr, fSecure](http::http_response response)
{
if (response.status_code() == http::status_codes::OK)
{
http::json::value jsonResponse = response.extract_json().get();
thisPtr->ProcessMessages(jsonResponse);
if (JsonHasValue(jsonResponse, L"messagelast"))
thisPtr->m_MessagePollNumber = jsonResponse[L"messagelast"].as_integer();
}
thisPtr->m_MessagePollTimer = std::make_shared<concurrency::timer<int>>(1000, 0, thisPtr->m_MessagePollCallback.get(), false);
thisPtr->m_MessagePollTimer->start();
taskCompetion.set();
}).then([taskCompetion](pplx::task<void> task)
{
try
{
task.get();
}
catch (utilities::win32_exception &)
{
taskCompetion.set_exception(std::current_exception());
}
catch (std::exception &)
{
taskCompetion.set_exception(std::current_exception());
}
catch (...)
{
taskCompetion.set_exception(std::current_exception());
}
});
//TODO: set_exception on task completion event
return concurrency::create_task(taskCompetion);
}
void SteamConnection::ProcessMessages(http::json::value & jsonData)
{
if (!JsonHasValue(jsonData, L"messages"))
return;
http::json::value & messages = jsonData[L"messages"];
for (auto message: messages.elements())
{
auto messageType = message[L"type"].as_string();
time_t timeStamp = message[L"timestamp"].as_integer();
std::wstring wstSteamId = message[L"steamid_from"].as_string();
if (messageType == L"personastate")
{
int newPersonaState = message[L"persona_state"].as_integer();
time_t timestamp = time(nullptr);
if (JsonHasValue(message, L"timestamp"))
timestamp = message[L"timestamp"].as_integer();
SteamID_t steamID = message[L"steamid_from"].as_string();
PrivateSteamUserPtr user = this->GetUserPrivate(steamID);
if (!user)
continue;
user->UpdateStatus(message[L"persona_state"].as_integer());
}
else if (messageType == L"typing")
{
}
else if (messageType == L"saytext")
{
SteamID_t steamID = message[L"steamid_from"].as_string();
PrivateSteamUserPtr user = this->GetUserPrivate(steamID);
if (JsonHasValue(message, L"secure_message_id"))
GetMessages(message[L"secure_message_id"].as_integer(), true);
if (JsonHasValue(message, L"text"))
{
time_t timestamp = time(nullptr);
if (JsonHasValue(message, L"timestamp"))
timestamp = message[L"timestamp"].as_integer();
user->SyncMessageFromNetwork(message[L"text"].as_string().c_str(), false, timestamp);
}
}
else if (messageType == L"personarelationship")
{
SteamID_t steamID = message[L"steamid_from"].as_string();
if (JsonHasValue(message, L"persona_state"))
int personaState = message[L"persona_state"].as_integer();
}
}
}
concurrency::task<LoginResultPtr> SteamConnection::Login(const char *pszUserName, const char *pszPassword, const char *pszAuthCode)
{
concurrency::task_completion_event<LoginResultPtr> taskCompetion;
auto reqTask = m_dataConnection->Login(pszUserName, pszPassword, pszAuthCode);
auto thisPtr = shared_from_this();
reqTask.then( [taskCompetion, thisPtr](http::http_response response)
{
WaitForSingleObjectEx(GetCurrentThread(), 2000, TRUE);
if (response.status_code() == http::status_codes::OK)
{
http::json::value jsonResponse = response.extract_json().get();
if (JsonHasValue(jsonResponse, L"x_steamid") && JsonHasValue(jsonResponse, L"access_token"))
{
// TODO: Synchronize
thisPtr->m_PlayerSteamID = jsonResponse[L"x_steamid"].as_string();
thisPtr->m_dataConnection->SetAccessToken(jsonResponse[L"access_token"].as_string().c_str());
thisPtr->AddPendingUserLookup(thisPtr->m_PlayerSteamID);
srand((int)time(NULL));
thisPtr->m_dataConnection->SetUMQID(rand() % 100000);
thisPtr->NotifyConnectionStateChanged(Connected);
thisPtr->ChatLogin();
taskCompetion.set(SteamLoginResult::CreateSuccessfulSteamLoginResult());
}
else if (JsonHasValue(jsonResponse, L"error"))
{
taskCompetion.set(SteamLoginResult::CreateErrorSteamLoginResult(jsonResponse[L"error"].as_string(), jsonResponse[L"x_errorcode"].as_string(), jsonResponse[L"error_description"].as_string()));
}
else
{
assert(false);
taskCompetion.set(SteamLoginResult::CreateErrorSteamLoginResult(L"Unknown Error", L"xyz", L"."));
}
}
}).then([taskCompetion](pplx::task<void> task)
{
try
{
task.get();
}
catch (...)
{
taskCompetion.set_exception(std::current_exception());
}
});
//TODO: set_exception on task completion event
return concurrency::create_task(taskCompetion);
}
void SteamConnection::NotifyConnectionStateChanged(EConnectionStatus status)
{
m_ConnectionChangeEvent(this, status);
}
bool SteamConnection::VerifyLoggedIn()
{
bool fLoginDetails = !m_PlayerSteamID.empty();// && !m_wstAccessToken.empty();
assert(fLoginDetails);
return fLoginDetails;
}
concurrency::task<UserDataList_t> SteamConnection::GetUsersDataAsync(const FriendsList_t & rgSteamIds)
{
AddPendingUserLookup(rgSteamIds);
auto & lookupSet = GetPendingUserLookupSet();
std::wstring wstFriendIds = ConcatenateSteamIds(begin(lookupSet), end(lookupSet));
VerifyLoggedIn();
auto reqTask = m_dataConnection->GetUsersData(wstFriendIds.c_str());
auto thisPtr = shared_from_this();
concurrency::task_completion_event<UserDataList_t> taskCompetion;
reqTask.then( [taskCompetion, thisPtr, rgSteamIds](http::http_response response)
{
if (response.status_code() == http::status_codes::OK)
{
http::json::value jsonResponse = response.extract_json().get();
UserDataList_t rgUserData;
rgUserData.reserve(rgSteamIds.size());
http::json::value & friendsValue = jsonResponse[L"players"];
PrivateSteamConnectionPtr connectionPtr = thisPtr;
auto players = friendsValue.elements();
// Store all results in our user map
for (auto& player : players)
{
PrivateSteamUserPtr steamUser = SteamUser::CreateSteamUser(player, connectionPtr);
thisPtr->m_UserMap[steamUser->GetSteamID()] = std::move(steamUser);
}
// Fulfill the friend data request from values in our user map
for (auto& steamID : rgSteamIds)
{
rgUserData.push_back(thisPtr->m_UserMap[steamID]);
}
taskCompetion.set(rgUserData);
}
}).then([taskCompetion](pplx::task<void> task)
{
try
{
task.get();
}
catch (...)
{
taskCompetion.set_exception(std::current_exception());
}
});
return concurrency::create_task(taskCompetion);
}
PrivateSteamUserPtr SteamConnection::GetUserPrivate(const SteamID_t & steamID)
{
auto iter = m_UserMap.find(steamID);
if (iter != end(m_UserMap))
return iter->second;
else
return nullptr;
}
concurrency::task<FriendsList_t> SteamConnection::GetFriendsListAsync()
{
VerifyLoggedIn();
return GetFriendsListAsync(m_PlayerSteamID);
}
concurrency::task<FriendsList_t> SteamConnection::GetFriendsListAsync(const SteamID_t & pwszSteamId)
{
auto reqTask = m_dataConnection->GetFriendsList(pwszSteamId.c_str());
auto thisPtr = shared_from_this();
concurrency::task_completion_event<FriendsList_t> taskCompetion;
reqTask.then( [taskCompetion, thisPtr](http::http_response response)
{
if (response.status_code() == http::status_codes::OK)
{
http::json::value & jsonResponse = response.extract_json().get();
taskCompetion.set(ParseGetFriendsListJson(jsonResponse));
}
else
{
taskCompetion.set(FriendsList_t());
}
}).then([taskCompetion](pplx::task<void> task)
{
try
{
task.get();
}
catch (...)
{
taskCompetion.set_exception(std::current_exception());
}
});
//TODO: set_exception on task completion event
return concurrency::create_task(taskCompetion);
}
SteamUserPtr SteamConnection::GetLoggedInUser()
{
assert(!m_PlayerSteamID.empty());
auto iter = m_UserMap.find(m_PlayerSteamID);
assert(iter != end(m_UserMap));
if (iter != end(m_UserMap))
return m_UserMap[m_PlayerSteamID];
return nullptr;
}
/*static*/ FriendsList_t SteamConnection::ParseGetFriendsListJson(http::json::value & jsonResponse)
{
FriendsList_t rgFriendIds;
http::json::value& friendsValue = jsonResponse[L"friends"];
auto players = friendsValue.elements();
for (auto player : players)
{
rgFriendIds.push_back(player[L"steamid"].as_string());
}
return std::move(rgFriendIds);
}
void SteamUser::SetCurrentGame(const wchar_t *pwzGameID, const wchar_t *pwzGameName)
{
m_CurrentGameID = pwzGameID;
if (!m_CurrentGameID.empty())
m_CurrentGameName = pwzGameName;
else
m_CurrentGameName.clear();
}
/*static*/ ISteamUser::OnlineStatus SteamUser::ConvertIntToStatus(int nStatus)
{
if (nStatus >= Offline && nStatus <= LookingToPlay)
return (OnlineStatus)nStatus;
else
throw std::invalid_argument("");
}
/*static*/ PrivateSteamUserPtr SteamUser::CreateSteamUser(http::json::value & jsonPlayer, PrivateSteamConnectionPtr & steamConnection)
{
auto steamUser = std::make_shared<SteamUser>(steamConnection);
steamUser->SetSteamID(jsonPlayer[L"steamid"].as_string().data());
steamUser->SetPersonaName(jsonPlayer[L"personaname"].as_string().data());
//steamUser->SetProfileURI(jsonPlayer[L"profileurl"].as_string().data());
steamUser->SetAvatarImageURI(jsonPlayer[L"avatarmedium"].as_string().data());
if (JsonHasValue(jsonPlayer, L"gameid"))
steamUser->SetCurrentGame(jsonPlayer[L"gameid"].as_string().data(), JsonStringGetValueWithDefault(jsonPlayer, L"gameextrainfo", L"").data());
steamUser->SetOnlineStatus(steamUser->ConvertIntToStatus((int)jsonPlayer[L"personastate"].as_integer() ));
steamUser->SetLastLogOffTime((time_t) (int)jsonPlayer[L"lastlogoff"].as_integer() );
return steamUser;
}
SteamConversation::SteamConversation(const std::shared_ptr<SteamUser> & user)
: m_User(user)
{
//m_MessagePollCallback = std::make_shared<concurrency::call<int>>([this](int v){CreateChangeEvent(v); });
//m_MessagePollTimer = std::make_shared<concurrency::timer<int>>(5000, 0, m_MessagePollCallback.get(), true);
//m_MessagePollTimer->start();
RefreshMessages();
}
void SteamConversation::CreateChangeEvent(int x)
{
//std::wstring stwMessage = L"Blah";
//SteamAPI::SteamMessagePtr msg = SteamAPI::CreateSteamUserMessageX(m_User, stwMessage.data(), false);
//int insertIndex = m_ConversationItems.size();
//m_ConversationItems.push_back(msg);
//m_ConversationChangedEvent(this, insertIndex);
}
SteamConversation_t SteamConversation::GetMessages()
{
return SteamConversation_t();
}
IEvent<ISteamConversation, int>& SteamConversation::GetConversationChangedEvent()
{
return m_ConversationChangedEvent;
}
int SteamConversation::GetCount()
{
return m_ConversationItems.size();
}
SteamMessagePtr SteamConversation::GetMessage(int index)
{
return m_ConversationItems[index];
}
void SteamConversation::SyncMessage(const wchar_t * pwzMessage, bool fromMe)
{
SteamAPI::SteamMessagePtr msg = SteamAPI::CreateSteamUserMessageX(m_User, pwzMessage, time(nullptr), fromMe);
int insertIndex = m_ConversationItems.size();
m_ConversationItems.push_back(msg);
m_ConversationChangedEvent(this, insertIndex);
}
void SteamConversation::RefreshMessages()
{
SteamConversation_t rgConversationHistory;
CSQLite_Connection & db = CSteamDBConnection::GetInstance();
std::string strQuery = FormatStr("SELECT SteamID, FromMe, Message, Sent FROM ConversationHistory WHERE SteamID=\"%S\" ORDER BY Sent ASC ", m_User->GetSteamID());
CSQLite_Results results = db.FRunQuery(strQuery.data());
for (int iRow = 0; iRow != results.NRows(); ++iRow)
{
std::wstring stwMessage = StrMultiToWide(results[iRow][2]);
std::string strFromMe = results[iRow][1];
time_t sentTime = ParseLongLongFromString(results[iRow][3]);
SteamUserPtr userPtr = m_User;
SteamMessagePtr msg = SteamUserMessage::CreateSteamUserMessage(userPtr, stwMessage.data(), sentTime, strFromMe == "True");
rgConversationHistory.push_back(msg);
}
std::swap(m_ConversationItems, rgConversationHistory);
}
std::wstring SteamConnection::LookupSteamGuard(const wchar_t *pwzUserName)
{
std::string strQuery = FormatStr("SELECT SteamGuard FROM UserTable WHERE SteamID=\"%S\"", pwzUserName);
CSQLite_Connection & db = CSteamDBConnection::GetInstance();
CSQLite_Results results = db.FRunQuery(strQuery.data());
if (results.NRows() >= 1)
return StrMultiToWide(results[0][0]);
else
return std::wstring();
}
void SteamConnection::SaveSteamGuard(const wchar_t *pwzUserName, const wchar_t *pwzSteamGuard)
{
std::string strQuery;
if (LookupSteamGuard(pwzUserName) != L"")
strQuery = FormatStr("UPDATE UserTable SET SteamGuard='%S' WHERE SteamID='%S'", pwzSteamGuard, pwzUserName);
else
strQuery = FormatStr("INSERT INTO UserTable VALUES ('%S', '%S')", pwzUserName, pwzSteamGuard);
CSQLite_Connection & db = CSteamDBConnection::GetInstance();
CSQLite_Results results = db.FRunQuery(strQuery.data());
}
} // End namespace SteamAPI
| [
"[email protected]"
] | |
788a50381554e2173a55ae24739522df54bb8871 | febf3f7144af58d22c81b3dac67c643256f1b1ad | /SanguoClient/frameworks/runtime-src/Classes/battle/skills/actions/attack/AttackDiamondAreaCenterOnHero.cpp | cf6ff298577a8d52969333c994401c16aeeeafd6 | [] | no_license | wagulu/cocos2dx_sanguo_heroes | ce503f9562e77f5922e80e77758a56386cd2b288 | e4117963825831ba51a5ead8651cd8dd48602768 | refs/heads/master | 2020-07-17T12:56:14.532212 | 2019-09-01T04:57:31 | 2019-09-01T04:57:31 | 206,023,787 | 4 | 2 | null | 2019-09-03T08:09:08 | 2019-09-03T08:09:08 | null | UTF-8 | C++ | false | false | 2,939 | cpp | //
// AttackDiamondAreaCenterOnHero.cpp
// Game
//
// Created by fuchenhao on 3/5/15.
//
//
#include "AttackDiamondAreaCenterOnHero.h"
#include "BattleWorld.h"
#include "EnumParser.h"
void AttackDiamondAreaCenterOnHero::fireAction(entityx::EntityManager &es)
{
SkillAction::fireAction(es);
int radius = m_skillActionData->config["radius"]->d;
float spreadInterval = m_skillActionData->config["spreadInterval"]->d;
TargetFinder::TargetResults targetResults;
vector<int>& targets = targetResults.targets;
if (m_skillActionData->hasMember("SkillTarget"))
{
auto skillTarget = EnumParserSkillTarget().getValue(*m_skillActionData->config["SkillTarget"]->s);
_TARGET_FINDER.findSkillTargets(m_fromId, skillTarget, targetResults);
}
else
{
auto skillTargetResults = es.get(m_entityId).component<BattleComponent::SkillTargetResults>();
if (skillTargetResults.valid())
{
targets = skillTargetResults->targets;
}
}
for (int targetId : targets)
{
auto* pTargetEntity = _BATTLE_ENTITY.getEntity(targetId);
if (pTargetEntity == nullptr) continue;
BattleConfig::TileResults results;
_TARGET_FINDER.findDiamondAreaTilesCenterOnHero(radius, *pTargetEntity, results);
auto position = pTargetEntity->component<BattleComponent::Position>();
int centerZ = MapHelper::getTileZ(position->z);
int centerX = MapHelper::getTileX(position->x);
int deltaX;
int deltaZ;
int distance;
for (auto* pTile : results.tiles)
{
deltaX = abs(pTile->tileX - centerX);
deltaZ = abs(pTile->tileZ - centerZ);
distance = max(deltaX, deltaZ) - 1;
BattleConfig::AttackData attackData(m_fromId, (deltaX + deltaZ) * spreadInterval);
attackData.setTargetPos(pTile->tileZ, pTile->tileX);
attackData.setSkillData(m_skillId, m_skillActionData->damageData, m_entityId);
attackData.damagePosition.x = position->x;
attackData.damagePosition.y = 0;
attackData.damagePosition.z = position->z;
if (distance < 0)
{
attackData.damagePosition.speedH = 0;
attackData.damagePosition.speedV = 0;
}
else
{
attackData.damagePosition.speedH = m_skillActionData->damageData.deadSpeedH - distance * m_skillActionData->damageData.deadSpeedHDecay;
attackData.damagePosition.speedV = m_skillActionData->damageData.deadSpeddV - distance * m_skillActionData->damageData.deadSpeedVDecay;
}
attackData.damagePosition.gravity = m_skillActionData->damageData.gravity;
_ENTITY_EVENT.emit<BattleEvent::AddAttack>(attackData);
}
}
remove();
}
| [
"[email protected]"
] | |
e3b71cc61cb455d0d417a9cb69796ac8a8a7d9cc | eb4449c4154267e86478726609ca579192306fbb | /ouzel/win/WindowWin.h | d860bcd8857026df2765fe7e921cbd1b3dad0415 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | danielytics/ouzel | 81e8d4d2b71f4ff483a1b8d8c8bd2f0d3683fc3b | 4af201092b8a6a1f9f2aaa13bb00bcd3bf5c0b2e | refs/heads/master | 2021-01-17T16:06:33.824953 | 2016-05-30T01:08:13 | 2016-05-30T01:08:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | h | // Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#pragma once
#define NOMINMAX
#include <windows.h>
#include "Window.h"
namespace ouzel
{
class WindowWin : public Window
{
friend Engine;
public:
virtual ~WindowWin();
virtual void close() override;
virtual void setSize(const Size2& newSize) override;
virtual void setTitle(const std::string& newTitle) override;
void handleResize(INT width, INT height);
HWND getNativeWindow() const { return window; }
HMONITOR getMonitor() const;
protected:
WindowWin(const Size2& pSize, bool pResizable, bool pFullscreen, const std::string& pTitle);
virtual bool init() override;
ATOM windowClass = 0;
HWND window = 0;
DWORD windowStyle;
};
}
| [
"[email protected]"
] | |
3021dcdb1998db0adedcb569ca19250db60d91b0 | d9e6fbaec02944a2fec6c8cc451ee6e6997154dc | /main.cpp | fbaf5b003720c7c80db7d1087136a557e5ee1dc0 | [] | no_license | angelarherbst34/BrainPad | 4379fb43509cf04ca1115484cacf068fb01118d7 | 38a432926a6faeeecdb048960e2c57e261a2387b | refs/heads/master | 2021-06-15T18:05:17.530367 | 2017-05-04T04:11:17 | 2017-05-04T04:11:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | #include "mainwindow.h"
#include <QApplication>
/**
* Creates main window
* @param argc the argument count
* @param argv the argument array
* @return the QApplication (qt)
*/
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
| [
"[email protected]"
] | |
735703cfef996509cb2828a4e818af4905d1111a | af824654c2490819039d801b0d2a75859f0f769d | /src/llfind.cpp | 7a750c1cf88751a1f3581059b4b83403c47fc668 | [
"MIT"
] | permissive | landenlabs2/llfile | ad677380860c3ae5cab06b7731f286886f90b140 | 83d071412467742fcf9611ee0b10e41b6ea19728 | refs/heads/master | 2021-01-13T02:50:04.901118 | 2017-04-03T12:52:05 | 2017-04-03T12:52:05 | 77,151,094 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,615 | cpp | //-----------------------------------------------------------------------------
// llfind - Find files along directory scan or env paths
//
// Author: Dennis Lang - 2015
// http://landenlabs.com/
//
// This file is part of LLFile project.
//
// ----- License ----
//
// Copyright (c) 2015 Dennis Lang
//
// 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 <iostream>
#include <string.h>
#include <assert.h>
#include "LLFind.h"
#include "comma.h"
// ---------------------------------------------------------------------------
static const char sHelp[] =
" Find " LLVERSION "\n"
" Find a file along directory path or env paths\n"
"\n"
" !0eSyntax:!0f\n"
" [<switches>] <Pattern>... \n"
"\n"
" !0eWhere switches are:!0f\n"
" -? ; Show this help\n"
" -A=[nrhs] ; Limit files by attribute (n=normal r=readonly, h=hidden, s=system)\n"
" -D ; Only directories in matching, default is all types\n"
" -D=<dirPattern> ; Only directories matching dirPttern \n"
" -p ; Search PATH environment directories for pattern\n"
" -e=<envName>[,...] ; Search env environment directories for pattern\n"
" -F ; Only files in matching, default is all types\n"
" -F=<filePat>,... ; Limit to matching file patterns \n"
" -G=<grepPattern> ; Find only if file contains grepPattern \n"
" -g=<grepRange> ; default is search entire file, +n=first n lines \n"
" -I=<file> ; Read list of files from this file\n"
" -p ; Short cut for -e=PATH, search path \n"
" -P=<srcPathPat> ; Optional regular expression pattern on source files full path\n"
" -q ; Quiet, default is echo command\n"
" -Q=n ; Quit after 'n' matches\n"
" -s ; Show file size size\n"
" -t[acm] ; Show Time a=access, c=creation, m=modified, n=none\n"
" -X=<pathPat>,... ; Exclude patterns -X=*.lib,*.obj,*.exe\n"
" ; No space in patterns. Pattern applied against fullpath\n"
" ; So *\\ma will exclude a directory ma or file ma \n"
" -V ; Verbose\n"
" -E=[cFDdsa] ; Return exit code, c=file+dir count, F=file count, D=dir Count\n"
" ; d=depth, s=size, a=age \n"
" -r ; Don't recurse into subdirectories\n"
" -1=<file> ; Redirect output to file \n"
"\n"
" !0eWhere Pattern is:!0f\n"
" <file|Pattern> \n"
" [<directory|pattern> \\]... <file|Pattern|#n> \n"
"\n"
" !0ePattern:!0f\n"
" * = zero or more characters\n"
" ? = any character\n"
"\n"
" !0eExample:!0f\n"
" ; Assuming lf.exe and where.exe are linked to llfile.exe\n"
" ; Example to find where an executable is in current search PATH\n"
" llfile -xw cmd.exe ; -xw force where command\n"
" lf -p cmd.exe ; -p enables PATH search\n"
" where cmd.exe ; where command auto adds '-p'\n"
" lf -Ar -i=c:\\fileList.txt >nul ; check for non-readonly files from list \n"
"\n"
" lf -e=LIB libfoo.lib ; search env LIB's path for libfoo.lib\n"
" lf -F=*.exe,*.com,*.bat .\\* ; search for executables or batch files\n"
" lf -F -X=*.obj,*.exe build\\* ; search for none object or exe files\n"
"\n"
"\n";
LLFindConfig LLFind::sConfig;
// ---------------------------------------------------------------------------
LLFind::LLFind() :
m_force(false),
m_envStr(),
m_totalSize(0)
{
m_exitOpts = "c";
m_showAttr =
m_showCtime =
m_showMtime =
m_showAtime =
m_showPath =
m_showSize = false;
memset(&m_fileData, 0, sizeof(m_fileData));
m_dirScan.m_recurse = true;
sConfigp = &GetConfig();
}
// ---------------------------------------------------------------------------
LLConfig& LLFind::GetConfig()
{
return sConfig;
}
// ---------------------------------------------------------------------------
int LLFind::StaticRun(const char* cmdOpts, int argc, const char* pDirs[])
{
LLFind llFind;
return llFind.Run(cmdOpts, argc, pDirs);
}
// ---------------------------------------------------------------------------
int LLFind::Run(const char* cmdOpts, int argc, const char* pDirs[])
{
const char missingRetMsg[] = "Missing return value, c=file count, d=depth, s=size, a=age, syntax -0=<code>";
const char missingEnvMsg[] = "Environment variable name, syntax -E=<envName> ";
const std::string endPathStr(";");
LLSup::StringList envList;
std::string str;
// Initialize stuff
size_t nFiles = 0;
bool sortNeedAllData = m_showSize;
bool whereMode = false; // where mode add [.](exe|com|cmd|bat) to search pattern.
EnableCommaCout();
// Setup default as needed.
if (argc == 0 && strstr(cmdOpts, "I=") == 0)
{
const char* sDefDir[] = {"*"};
argc = sizeof(sDefDir)/sizeof(sDefDir[0]);
pDirs = sDefDir;
}
// Parse options
while (*cmdOpts)
{
switch (*cmdOpts)
{
case 'e': // -e=<envName>[,<envName>
cmdOpts = LLSup::ParseList(cmdOpts+1, envList, missingEnvMsg);
for (unsigned envIdx = 0; envIdx != envList.size(); envIdx++)
{
std::string envStr = envList[envIdx];
VerboseMsg() << "-e " << envStr << std::endl;
m_envStr += LLSup::GetEnvStr(envStr.c_str(), ""); // pointer needs to be freed
m_envStr += endPathStr;
m_dirScan.m_recurse = false;
}
break;
case 'p': // Default to path environment
whereMode = true;
m_dirScan.m_recurse = false;
{
std::string pathStr = LLSup::GetEnvStr("PATH", ""); // pointer needs to be freed
VerboseMsg() << "Searching PATH " << pathStr << std::endl;
pathStr.insert(0, ".\\;"); // Force local directory search first
m_envStr += pathStr;
m_envStr += endPathStr;
}
break;
case 's': // Toggle showing size.
sortNeedAllData |= m_showSize = !m_showSize;
// m_dirSort.SetSortData(sortNeedAllData);
break;
case 't': // Display Time selection
{
bool unknownOpt = false;
while (cmdOpts[1] && !unknownOpt)
{
cmdOpts++;
switch (ToLower(*cmdOpts))
{
case 'a':
sortNeedAllData = m_showAtime = true;
break;
case 'c':
sortNeedAllData = m_showCtime = true;
break;
case 'm':
sortNeedAllData = m_showMtime = true;
break;
case 'n': // NoTime
sortNeedAllData = false;
m_showAtime = m_showCtime = m_showMtime = false;
break;
default:
cmdOpts--;
unknownOpt = true;
break;
}
}
// m_dirSort.SetSortData(sortNeedAllData);
}
break;
case ',':
DisableCommaCout();
break;
case '?':
Colorize(std::cout, sHelp);
return sIgnore;
default:
if ( !ParseBaseCmds(cmdOpts))
return sError;
}
// Advance to next parameter
LLSup::AdvCmd(cmdOpts);
}
VerboseMsg() << "LLFind Env:" << m_envStr << std::endl;
// Move arguments and input files into inFileList.
std::vector<std::string> inFileList;
for (int argn=0; argn < argc; argn++)
{
inFileList.push_back(pDirs[argn]);
}
if (m_inFile.length() != 0)
{
FILE* fin = stdin;
if (strcmp(m_inFile.c_str(), "-") == 0 ||
0 == fopen_s(&fin, m_inFile.c_str(), "rt"))
{
char fileName[MAX_PATH];
while (fgets(fileName, ARRAYSIZE(fileName), fin))
{
TrimString(fileName); // remove extra space or control characters.
if (*fileName == '\0')
continue;
inFileList.push_back(fileName);
}
}
}
if ( !m_envStr.empty())
{
VerboseMsg() << " EnvDir:" << m_envStr << std::endl;
// Iterate over env paths
Split envPaths(m_envStr, ";");
for (unsigned argn=0; argn < inFileList.size(); argn++)
{
for (uint envIdx = 0; envIdx != envPaths.size(); envIdx++)
{
lstring dirPat = LLPath::Join(envPaths[envIdx], inFileList[argn].c_str());
bool findExecutable = whereMode && inFileList[argn].find('.', 0) == -1;
size_t foundCnt = 0;
unsigned pos = dirPat.length();
unsigned len = 0;
const char* sExeExtn[] = { "", ".exe", ".bat", ".cmd", ".com", ".ps1" };
for (unsigned idx = 0; idx < ARRAYSIZE(sExeExtn); idx++)
{
VerboseMsg() << " ScanDir:" << dirPat << std::endl;
m_dirScan.Init(dirPat, NULL);
foundCnt = m_dirScan.GetFilesInDirectory();
if (foundCnt != 0 || !findExecutable)
break;
dirPat.replace(pos, len, sExeExtn[idx]);
len = strlen(sExeExtn[idx]);
}
nFiles += foundCnt;
}
}
}
else
{
// Iterate over dir patterns.
for (unsigned argn=0; argn < inFileList.size(); argn++)
{
VerboseMsg() <<" Dir:" << inFileList[argn] << std::endl;
m_dirScan.Init(inFileList[argn].c_str(), NULL);
nFiles += m_dirScan.GetFilesInDirectory();
}
}
// Return status, c=file count, d=depth, s=size, a=age
if (m_exitOpts.length() != 0)
switch ((char)m_exitOpts[0u])
{
case 'a': // age, -0=a
{
FILETIME ltzFT;
SYSTEMTIME sysTime;
FileTimeToLocalFileTime(&m_fileData.ftLastWriteTime, <zFT); // convert UTC to local Timezone
FileTimeToSystemTime(<zFT, &sysTime);
// TODO - compare to local time and return age.
return 0;
}
break;
case 's': // file size, -0=s
VerboseMsg() << ";Size:" << m_totalSize << std::endl;
return (int)m_fileSize;
case 'd': // file depth, -o=d
VerboseMsg() << ";Depth (-E=d depth currently not implemented,use -E=D for #directories):" << 0 << std::endl;
return 0; // TODO - return maximum file depth.
case 'D': // Directory count, -o=D
VerboseMsg() << ";Directory Count:" << m_countOutDir << std::endl;
return m_countOutDir;
case 'F': // File count, -o=F
VerboseMsg() << ";File Count:" << m_countOutFiles << std::endl;
return m_countOutFiles;
case 'c': // File and directory count, -o=c
default:
VerboseMsg() << ";File + Directory Count:" << (m_countOutDir + m_countOutFiles) << std::endl;
return (int)(m_countOutDir + m_countOutFiles);
}
return ExitStatus(0);
}
// ---------------------------------------------------------------------------
int LLFind::ProcessEntry(
const char* pDir,
const WIN32_FIND_DATA* pFileData,
int depth) // 0...n is directory depth, -n end-of nth diretory
{
if (depth < 0)
return sIgnore; // ignore end-of-directory
// Filter on:
// m_onlyAttr File or Directory, -F or -D
// m_onlyRhs Attributes, -A=rhs
// m_includeList File patterns, -F=<filePat>[,<filePat>]...
// m_onlySize File size, -Z op=(Greater|Less|Equal) value=num<units G|M|K>, ex -Zg100M
// m_excludeList Exclude path patterns, -X=<pathPat>[,<pathPat>]...
// m_timeOp Time, -T[acm]<op><value> ; Test Time a=access, c=creation, m=modified\n
//
// If pass, populate m_srcPath
if ( !FilterDir(pDir, pFileData, depth))
return sIgnore;
VerboseMsg() << m_srcPath << "\n";
if (m_isDir)
{
if (PatternMatch(m_dirScan.m_fileFilter, pFileData->cFileName) == false)
return sIgnore;
if (m_onlyAttr == FILE_ATTRIBUTE_DIRECTORY &&
!LLSup::PatternListMatches(m_includeDirList, pFileData->cFileName, true))
return sIgnore;
}
if ( !FilterGrep())
return sIgnore;
if (m_echo && !IsQuit())
{
if (m_showAttr)
{
// ShowAttributes(LLMsg::Out(), pDir, *pFileData, false);
LLMsg::Out() << LLFind::sConfig.m_dirFieldSep;
}
if (m_showCtime)
LLSup::Format(LLMsg::Out(), pFileData->ftCreationTime) << LLFind::sConfig.m_dirFieldSep ;
if (m_showMtime)
LLSup::Format(LLMsg::Out(), pFileData->ftLastWriteTime) << LLFind::sConfig.m_dirFieldSep;
if (m_showAtime)
LLSup::Format(LLMsg::Out(), pFileData->ftLastAccessTime) << LLFind::sConfig.m_dirFieldSep;
if (m_showSize)
LLMsg::Out() << std::setw(LLFind::sConfig.m_fzWidth) << m_fileSize << LLFind::sConfig.m_dirFieldSep;
LLMsg::Out() << m_srcPath << std::endl;
}
m_totalSize += m_fileSize;
m_fileData = *pFileData;
if (m_isDir)
m_countOutDir++;
else
m_countOutFiles++;
return sOkay;
}
| [
"[email protected]"
] | |
1b065c4f586b6ae661e902c2451014ce287d8785 | 8c46efa71edb8413bb46deb36b347627834a0c77 | /Graphic11/manager/textmanager.cpp | da49dbf74255d44605d86070d96260404de52d97 | [
"MIT"
] | permissive | azhugg/Common | 4f5b08d3f8dc66936b7eb243a5db2b3379fba06a | 239caba7912454a239e2162cad479fb1dd4ced7e | refs/heads/master | 2021-08-18T18:58:12.723498 | 2017-11-23T15:41:11 | 2017-11-23T15:41:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,039 | cpp |
#include "stdafx.h"
#include "textmanager.h"
#include <mmsystem.h>
using namespace graphic;
cTextManager::cTextManager()
: m_maxTextCount(128)
, m_textureSizeX(TEXTURE_SIZEX)
, m_textureSizeY(TEXTURE_SIZEY)
, m_generateCount(0)
, m_cacheCount(0)
{
m_renders.reserve(m_maxTextCount);
m_buffer.reserve(m_maxTextCount);
m_cmds.reserve(m_maxTextCount);
}
cTextManager::~cTextManager()
{
Clear();
}
void cTextManager::Create(const u_int maxTextCount //= 100
, const int textureSizeX //= 256
, const int textureSizeY //= 32
)
{
m_maxTextCount = maxTextCount;
m_renders.reserve(maxTextCount);
m_buffer.reserve(maxTextCount);
m_cmds.reserve(maxTextCount);
m_textureSizeX = textureSizeX;
m_textureSizeY = textureSizeY;
m_graphicBmp = std::shared_ptr<Gdiplus::Bitmap>(new Gdiplus::Bitmap(textureSizeX, textureSizeY, PixelFormat32bppARGB));
m_textBmp = std::shared_ptr<Gdiplus::Bitmap>(new Gdiplus::Bitmap(textureSizeX, textureSizeY, PixelFormat32bppARGB));
m_graphic = std::shared_ptr<Gdiplus::Graphics>(new Gdiplus::Graphics(m_graphicBmp.get()));
m_graphicText = std::shared_ptr<Gdiplus::Graphics>(new Gdiplus::Graphics(m_textBmp.get()));
}
void cTextManager::NewFrame()
{
m_generateCount = 0;
m_cacheCount = 0;
m_renderMap.clear();
m_renders.clear();
for (auto &p : m_buffer)
p->used = false;
m_cmds.clear();
}
void cTextManager::AddTextRender(cRenderer &renderer
, const int id
, const wchar_t *str
, const cColor &color //= cColor::WHITE
, const cColor &outlineColor //= cColor::BLACK
, BILLBOARD_TYPE::TYPE type //= BILLBOARD_TYPE::Y_AXIS
, const Transform &tm //= Transform::Identity
, const int width //=8
, const int height//=1
)
{
const cColor c1 = color.GetAbgr();
const cColor c2 = outlineColor.GetAbgr();
sText *text = GetCacheText(id);
if (text)
{
if (text->text.SetTextRect(renderer, tm, str, c1, c2, type))
++m_generateCount;
else
++m_cacheCount;
text->space = renderer.GetCurrentAlphaBlendSpace();
text->used = true;
text->initTime = timeGetTime();
if (m_renderMap.end() == m_renderMap.find(id))
{
m_renderMap[id] = text;
m_renders.push_back(text);
}
}
else
{
sCommand cmd;
cmd.id = id;
cmd.str = str;
cmd.color = c1;
cmd.outlineColor = c2;
cmd.type = type;
cmd.tm = tm;
cmd.width = width;
cmd.height = height;
cmd.space = renderer.GetCurrentAlphaBlendSpace();
m_cmds.push_back(cmd);
}
}
// Process Command
void cTextManager::ProcessTextCmd(cRenderer &renderer)
{
u_int bufferStartIdx = 0;
for (auto &cmd : m_cmds)
{
bool isFindEmptyText = false;
sText *text = GetCacheText(cmd.id);
if (text)
{
SetCommand2Text(renderer, text, cmd);
isFindEmptyText = true;
++m_cacheCount;
}
else
{
for (u_int i = bufferStartIdx; i < m_buffer.size(); ++i)
{
sText *text = m_buffer[i];
if ((text->id >= 0) && (text->used))
continue;
if (m_cacheMap.end() != m_cacheMap.find(text->id))
continue; // if exist cache, next text
SetCommand2Text(renderer, text, cmd);
m_renders.push_back(text);
isFindEmptyText = true;
bufferStartIdx = i + 1; // set search buffer index
break;
}
}
if (!isFindEmptyText) // not found empty buffer, create text
{
if (m_maxTextCount <= m_buffer.size())
break; // buffer full, Finish
sText *text = new sText;
text->text.Create(renderer, cmd.type, cmd.width, cmd.height, m_textureSizeX, m_textureSizeY);
m_buffer.push_back(text);
SetCommand2Text(renderer, text, cmd);
m_renders.push_back(text);
bufferStartIdx = m_buffer.size();
}
}
m_cmds.clear();
// clear cache if not use buffer
const int curT = timeGetTime();
set<int> rmIds;
for (auto kv : m_cacheMap)
{
sText *text = kv.second;
if (text->used)
continue;
if (text->id >= 0)
{
if ((curT - text->initTime) < 3000)
continue;
rmIds.insert(text->id);
text->id = -1;
}
}
for (auto id : rmIds)
m_cacheMap.erase(id);
GarbageCollection();
}
void cTextManager::Render(cRenderer &renderer
, const bool isSort //= false
)
{
ProcessTextCmd(renderer);
if (isSort)
Sorting();
for (auto &p : m_renders)
renderer.AddRenderAlpha(p->space, &p->text, p->text.m_quad.m_normal, p->text.m_transform.GetMatrix());
}
void cTextManager::SetCommand2Text(cRenderer &renderer, sText *text, const sCommand &cmd)
{
if (text->text.SetTextRect(renderer, cmd.tm, cmd.str.c_str(), cmd.color, cmd.outlineColor, cmd.type))
++m_generateCount;
else
++m_cacheCount;
text->id = cmd.id;
text->used = true;
text->space = cmd.space;
text->initTime = timeGetTime();
m_cacheMap[cmd.id] = text;
}
cTextManager::sText* cTextManager::GetCacheText(const int id)
{
auto it = m_cacheMap.find(id);
if (it == m_cacheMap.end())
return NULL;
return it->second;
}
void cTextManager::GarbageCollection()
{
static int oldT = timeGetTime();
if (timeGetTime() - oldT < 1000) // check 1 seconds
return;
oldT = timeGetTime();
set<int> checkIds;
for (auto &p : m_buffer)
checkIds.insert(p->id);
// Error Found
if (checkIds.size() != m_buffer.size())
{
map<int, std::pair<int,sText*>> duplicateCheck;
for (auto &p : m_buffer)
{
++duplicateCheck[p->id].first;
duplicateCheck[p->id].second = p;
}
for (auto &it : duplicateCheck)
{
if ((it.first >=0) && (it.second.first > 1))
{
it.second.second->id = -1;
it.second.second->used = false;
m_cacheMap.erase(it.first);
}
}
}
}
// Text Sorting With Camera Position
// Descent Distance from Camera
void cTextManager::Sorting()
{
cCamera &cam = GetMainCamera();
const Ray ray = cam.GetRay();
std::sort(m_renders.begin(), m_renders.end(),
[&](const sText* a, const sText* b)
{
const float l1 = a->text.m_transform.pos.LengthRoughly(ray.orig);
const float l2 = b->text.m_transform.pos.LengthRoughly(ray.orig);
return l1 > l2;
}
);
}
void cTextManager::Clear()
{
for (auto &p : m_buffer)
delete p;
m_buffer.clear();
m_graphicBmp = NULL;
m_textBmp = NULL;
m_graphic = NULL;
m_graphicText = NULL;
}
| [
"[email protected]"
] | |
e8326264b7da1746f8ba1e2b419e9beb110ea07d | d70a8896fab79eb3ac0f7d340a7cec094f3fbcc5 | /code/Hud/HUDsquadmsg.cpp | 622a89d56a12d215f92296599859929b1d82e836 | [] | no_license | mmastro/freespace2 | ce3699124ada832d6b306dc8910e4d822906bf09 | 60787ca0068156211436f7716a1d1ee27c88048e | refs/heads/master | 2020-05-15T08:38:34.077297 | 2015-06-20T14:02:24 | 2015-06-20T14:02:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90,107 | cpp | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/Hud/HUDsquadmsg.cpp $
* $Revision: 16 $
* $Date: 9/06/99 10:45a $
* $Author: Andsager $
*
* File to control sqaudmate messaging
*
* $Log: /Freespace2/code/Hud/HUDsquadmsg.cpp $
*
* 16 9/06/99 10:45a Andsager
* Add freighter to player override of protected status.
*
* 15 9/06/99 10:32a Andsager
* Allow attack of protected fighter, bomber, freighters, by player's
* orders.
*
* 14 8/26/99 8:51p Dave
* Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
*
* 13 7/30/99 10:31p Dave
* Added comm menu to the configurable hud files.
*
* 12 7/09/99 5:54p Dave
* Seperated cruiser types into individual types. Added tons of new
* briefing icons. Campaign screen.
*
* 11 6/16/99 10:20a Dave
* Added send-message-list sexpression.
*
* 10 6/09/99 9:53a Andsager
* 1st pass at grey menu items when no ships/wings/fighters accepting
* orders.
*
* 9 4/23/99 12:01p Johnson
* Added SIF_HUGE_SHIP
*
* 8 4/16/99 5:54p Dave
* Support for on/off style "stream" weapons. Real early support for
* target-painting lasers.
*
* 7 3/30/99 5:40p Dave
* Fixed reinforcements for TvT in multiplayer.
*
* 6 3/28/99 5:58p Dave
* Added early demo code. Make objects move. Nice and framerate
* independant, but not much else. Don't use yet unless you're me :)
*
* 5 1/07/99 9:07a Jasen
* HUD coords
*
* 4 12/28/98 3:17p Dave
* Support for multiple hud bitmap filenames for hi-res mode.
*
* 3 12/21/98 5:02p Dave
* Modified all hud elements to be multi-resolution friendly.
*
* 2 10/07/98 10:53a Dave
* Initial checkin.
*
* 1 10/07/98 10:49a Dave
*
* 198 9/11/98 2:05p Allender
* make reinforcements work correctly in multiplayer games. There still
* may be a team vs team issue that I haven't thought of yet :-(
*
* 197 8/28/98 3:28p Dave
* EMP effect done. AI effects may need some tweaking as required.
*
* 196 8/25/98 1:48p Dave
* First rev of EMP effect. Player side stuff basically done. Next comes
* AI code.
*
* 195 6/30/98 2:17p Dave
* Revised object update system. Removed updates for all weapons. Put
* button info back into control info packet.
*
* 194 6/09/98 10:31a Hoffoss
* Created index numbers for all xstr() references. Any new xstr() stuff
* added from here on out should be added to the end if the list. The
* current list count can be found in FreeSpace.cpp (search for
* XSTR_SIZE).
*
* 193 5/26/98 11:54a Allender
* fix multiplayer problems and sexpression crash
*
* 192 5/24/98 4:27p Allender
* fix bug when determine who could message in multiplayer
*
* 191 5/23/98 2:34a Lawrance
* Fix problems with HUD squad messaging, don't save/restore bindings
*
* 190 5/22/98 12:41a Allender
* don't save/restore key presses in comm menu
*
* 189 5/21/98 9:38p Allender
* don't save/clear key bindings
*
* 188 5/21/98 3:32p Allender
* don't allow comm menu in observer mode
*
* 187 5/19/98 12:19p Mike
* Cheat codes!
*
* 186 5/18/98 10:08a Lawrance
* increase MSG_KEY_EAT_TIME to 300ms
*
* 185 5/18/98 12:41a Allender
* fixed subsystem problems on clients (i.e. not reporting properly on
* damage indicator). Fixed ingame join problem with respawns. minor
* comm menu stuff
*
* 184 5/13/98 5:08p Allender
* fix code in which sometimes wings wouldn't respond in multiplayer when
* doing a message all fighters
*
* 183 5/08/98 4:38p Allender
* always allow player ships to count when counting fighters for
* messaging. Terran command will now always issue the shooting at
* friendlies message
*
* 182 5/08/98 2:11p Mike
* Add "/Repair Subsys" to "Rearm" option in Comm menu.
*
* 181 5/06/98 2:57p Allender
* always allow rearm ship to be called in
*
* 180 5/05/98 2:04a Mike
* Fix bug in support ship code.
*
* 179 5/05/98 1:41a Mike
* Improve support ship availability.
*
* 178 5/04/98 12:59a Allender
* players who are traitors shouldn't be allowed to rearm or use messaging
* shortcuts
*
* 177 5/04/98 12:39a Allender
* make page up and page down only active when > 10 items on menu
*
* 176 4/29/98 10:56p Allender
* don't allow shortcuts in mutliplayer when player cannot message (except
* for rearm repair)
*
* 175 4/23/98 10:06a Allender
* don't use the word "player" in event log for rearm event. Send
* shipname instead (players only)
*
* 174 4/23/98 9:15a Allender
* make rearm shortcut work for clients
*
* 173 4/23/98 1:49a Allender
* major rearm/repair fixes for multiplayer. Fixed respawning of AI ships
* to not respawn until 5 seconds after they die. Send escort information
* to ingame joiners
*
* 172 4/22/98 4:59p Allender
* new multiplayer dead popup. big changes to the comm menu system for
* team vs. team. Start of debriefing stuff for team vs. team Make form
* on my wing work with individual ships who have high priority orders
*
* 171 4/21/98 12:15a Allender
* don't allow observers to use shortcut messaging keys
*
* 170 4/20/98 12:36a Mike
* Make team vs. team work when player is hostile. Several targeting
* problems.
*
* 169 4/13/98 12:51p Allender
* made countermeasure succeed indicator work in multiplayer. Make rearm
* shortcut work more appropriately.
*
* 168 4/10/98 2:42p Johnson
* (from allender) when sending wing command, don't assert if ship to
* send message not found -- don't send message. Allow rearm message
* shortcut even if comm destroyed
*
* 167 4/10/98 2:39p Johnson
*
* 166 4/10/98 12:47p Allender
* changed working on replay popup. Don't reference repair in comm menu.
* Added Shift-R for repair me
*
* 165 4/09/98 12:35p Allender
* disallow messaging to departing wings and departing/dying ships
*
* 164 4/08/98 4:06p Allender
* make selection of wing Player team based, not TEAM_FRIENDLY.
*
* 163 4/07/98 5:30p Lawrance
* Player can't send/receive messages when comm is destroyed. Garble
* messages when comm is damaged.
*
* 162 4/07/98 1:53p Lawrance
* Fix uninitialized data bug.
*
* 161 4/06/98 12:11a Allender
* prevent the comm menu keys from being held over after menu goes away
*
* 160 4/05/98 3:06p Allender
* don't allow ships/wings to act on orders which they shouldn't receive
*
* 159 4/03/98 12:17a Allender
* new sexpression to detect departed or destroyed. optionally disallow
* support ships. Allow docking with escape pods
*
* 158 4/02/98 5:50p Dave
* Put in support for standard comm messages to get sent to netplayers as
* well as ai ships. Make critical button presses not get evaluated on the
* observer.
*
* $NoKeywords: $
*/
#include "Freespace.h"
#include "2d.h"
#include "Hud.h"
#include "ship.h"
#include "Player.h"
#include "key.h"
#include "HudTarget.h"
#include "timer.h"
#include "HUDsquadmsg.h"
#include "ControlsConfig.h"
#include "Parselo.h"
#include "AIGoals.h"
#include "MissionParse.h"
#include "Sexp.h"
#include "LinkList.h"
#include "MissionLog.h"
#include "MissionMessage.h"
#include "HUDTarget.h"
#include "GameSnd.h"
#include "Sound.h"
#include "MissionParse.h"
#include "Multimsgs.h"
#include "multiutil.h"
#include "bmpman.h"
#include "HudTargetbox.h"
#include "multi_pmsg.h"
#include "SubsysDamage.h"
#include "Emp.h"
// defines for different modes in the squad messaging system
#define SM_MODE_TYPE_SELECT 1 //am I going to message a ship or a wing
#define SM_MODE_SHIP_SELECT 2 //choosing actual ship
#define SM_MODE_WING_SELECT 3 //choosing actual wing
#define SM_MODE_SHIP_COMMAND 4 //which command to send to a ship
#define SM_MODE_WING_COMMAND 5 //which command to send to a wing
#define SM_MODE_REINFORCEMENTS 6 //call for reinforcements
#define SM_MODE_REPAIR_REARM 7 //repair/rearm player ship
#define SM_MODE_REPAIR_REARM_ABORT 8 //abort repair/rearm of player ship
#define SM_MODE_ALL_FIGHTERS 9 //message all fighters/bombers
#define DEFAULT_MSG_TIMEOUT (8 * 1000) // number of seconds * 1000 to get milliseconds
#define MSG_KEY_EAT_TIME (300)
LOCAL int Squad_msg_mode; // current mode that the messaging system is in
LOCAL int Msg_key_used; // local variable which tells if the key being processed
// with the messaging system was actually used
LOCAL int Msg_key; // global which indicates which key was currently pressed
LOCAL int Msg_mode_timestamp;
LOCAL int Msg_instance; // variable which holds ship/wing instance to send the message to
LOCAL int Msg_shortcut_command; // holds command when using a shortcut key
LOCAL int Msg_target_objnum; // id of the current target of the player
LOCAL ship_subsys *Msg_targeted_subsys;// pointer to current subsystem which is targeted
//#ifndef NDEBUG
LOCAL int Msg_enemies; // tells us whether or not to message enemy ships or friendlies
//#endif
LOCAL int Msg_eat_key_timestamp; // used to temporarily "eat" keys
// defined to position the messaging box
int Mbox_item_h[GR_NUM_RESOLUTIONS] = {
10,
10
};
int Mbox_item_xoffset[GR_NUM_RESOLUTIONS] = {
17,
17
};
// top of the message box gauge
int Mbox_top_coords[GR_NUM_RESOLUTIONS][2] = {
{ // GR_640
445, 5
},
{ // GR_1024
827, 5
}
};
int Mbox_bmap_coords[GR_NUM_RESOLUTIONS][2] = {
{ // GR_640
445, 17
},
{ // GR_1024
827, 17
}
};
// squadmsg menu pgup and pgdn
int Menu_pgup_coords[GR_NUM_RESOLUTIONS][2] = {
{ // GR_640
590, 9
},
{ // GR_1024
937, 9
}
};
int Menu_pgdn_coords[GR_NUM_RESOLUTIONS][2] = {
{ // GR_640
590, 120
},
{ // GR_1024
937, 120
}
};
// -----------
// following defines/vars are used to build menus that are used in messaging mode
typedef struct mmode_item {
int instance; // instance in Ships/Wings array of this menu item
int active; // active items are in bold text -- inactive items greyed out
char text[NAME_LENGTH]; // text to display on the menu
} mmode_item;
#define MAX_MENU_ITEMS 50 // max number of items in the menu
#define MAX_MENU_DISPLAY 10 // max number that can be displayed
mmode_item MsgItems[MAX_MENU_ITEMS];
int Num_menu_items = -1; // number of items for a message menu
int First_menu_item= -1; // index of first item in the menu
// -----------
// following set of vars/defines are used to store/restore key bindings for keys that
// are used in messaging mode
// array to temporarily store key bindings that will be in use for the messaging
// system
typedef struct key_store {
int option_num; // which element in the Control_config array is this
int id; // which id (1 or 2) is this key.
int key_value; // which key value to put there.
} key_store;
#define MAX_KEYS_NO_SCROLL 10
#define MAX_KEYS_USED 12 // maximum number of keys used for the messaging system
key_store key_save[MAX_KEYS_USED]; // array to save the key information during messaging mode
int num_keys_saved = 0; // number of keys that are saved.
// next array is the array of MAX_KEYS_USED size which are the keys to use for messaging mode
int keys_used[] = { KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0,
KEY_PAGEUP, KEY_PAGEDOWN };
#define ID1 1
#define ID2 2
// following are defines and character strings that are used as part of messaging mode
#define TYPE_SHIP_ITEM 0
#define TYPE_WING_ITEM 1
#define TYPE_ALL_FIGHTERS_ITEM 2
#define TYPE_REINFORCEMENT_ITEM 3
#define TYPE_REPAIR_REARM_ITEM 4
#define TYPE_REPAIR_REARM_ABORT_ITEM 5
#define NUM_TYPE_SELECT 6
char *type_select_str(int n)
{
#if NUM_TYPE_SELECT != 6
#error type_select_Str is not up to date
#endif
switch(n) {
case TYPE_SHIP_ITEM:
return XSTR( "Ships", 293);
case TYPE_WING_ITEM:
return XSTR( "Wings", 294);
case TYPE_ALL_FIGHTERS_ITEM:
return XSTR( "All Fighters", 295);
case TYPE_REINFORCEMENT_ITEM:
return XSTR( "Reinforcements", 296);
case TYPE_REPAIR_REARM_ITEM:
return XSTR( "Rearm/Repair Subsys", 297);
case TYPE_REPAIR_REARM_ABORT_ITEM:
return XSTR( "Abort Rearm", 298);
}
return NULL;
}
// data structure to hold character string of commands for comm menu
typedef struct comm_order {
int value; // used to match which command to display on the menu
} comm_order;
// note: If you change this table at all, keep it in sync with version in IgnoreOrdersDlg.cpp
// Also make sure you update comm_order_menu_text below this.
// Also make sure you update MAX_SHIP_ORDERS in HUDsquadmsg.h
comm_order Comm_orders[MAX_SHIP_ORDERS] = {
ATTACK_TARGET_ITEM,
DISABLE_TARGET_ITEM,
DISARM_TARGET_ITEM,
DISABLE_SUBSYSTEM_ITEM,
PROTECT_TARGET_ITEM,
IGNORE_TARGET_ITEM,
FORMATION_ITEM,
COVER_ME_ITEM,
ENGAGE_ENEMY_ITEM,
CAPTURE_TARGET_ITEM,
REARM_REPAIR_ME_ITEM,
ABORT_REARM_REPAIR_ITEM,
DEPART_ITEM,
};
// Text to display on the menu
// Given an index into the Comm_orders array, return the text associated with it.
// MUST BE 1:1 with Comm_orders.
char *comm_order_menu_text(int index)
{
switch( index ) {
case 0: return XSTR( "Destroy my target", 299); break;
case 1: return XSTR( "Disable my target", 300); break;
case 2: return XSTR( "Disarm my target", 301); break;
case 3: return XSTR( "Destroy subsystem", 302); break;
case 4: return XSTR( "Protect my target", 303); break;
case 5: return XSTR( "Ignore my target", 304); break;
case 6: return XSTR( "Form on my wing", 305); break;
case 7: return XSTR( "Cover me", 306); break;
case 8: return XSTR( "Engage enemy", 307); break;
case 9: return XSTR( "Capture my target", 308); break;
case 10: return XSTR( "Rearm me", 309); break;
case 11: return XSTR( "Abort rearm", 310); break;
case 12: return XSTR( "Depart", 311); break;
default:
Assert(0);
}
return NULL;
}
// Text to display on the messaging menu when using the shortcut keys
char *comm_order_hotkey_text( int index )
{
int i;
for (i = 0; i < MAX_SHIP_ORDERS; i++ ) {
if ( Comm_orders[i].value == index )
return comm_order_menu_text(i);
}
Int3();
return NULL;
}
// a define of who can receive message
#define CAN_MESSAGE (SIF_FIGHTER | SIF_BOMBER | SIF_CRUISER | SIF_FREIGHTER | SIF_TRANSPORT | SIF_CAPITAL | SIF_SUPPORT | SIF_SUPERCAP | SIF_DRYDOCK | SIF_GAS_MINER | SIF_AWACS | SIF_CORVETTE)
int squadmsg_history_index = 0;
squadmsg_history Squadmsg_history[SQUADMSG_HISTORY_MAX] = { 0 };
// used for Message box gauge
#define NUM_MBOX_FRAMES 3
static hud_frames Mbox_gauge[NUM_MBOX_FRAMES];
static int Mbox_frames_loaded = 0;
static char *Mbox_fnames[GR_NUM_RESOLUTIONS][NUM_MBOX_FRAMES] =
{
//XSTR:OFF
{ // GR_640
"message1", // top part of menu
"message2", // middle part
"message3" // bottom part
},
{ // GR_1024
"message1", // top part of menu
"message2", // middle part
"message3" // bottom part
}
//XSTR:ON
};
static int Mbox_title_coord[GR_NUM_RESOLUTIONS][2] = {
{ // GR_640
447, 6
},
{ // GR_1024
829, 6
}
};
static int Mbox_item_coord[GR_NUM_RESOLUTIONS][2] = {
{ // GR_640
449, 18
},
{ // GR_1024
831, 18
}
};
// define for trapping messages send to "all fighters"
#define MESSAGE_ALL_FIGHTERS -999
// forward declarations
void hud_add_issued_order(char *name, int order, char *target);
int hud_squadmsg_is_target_order_valid(int order, int find_order, ai_info *aip = NULL );
int hud_squadmsg_ship_order_valid( int shipnum, int order );
// function to set up variables needed when messaging mode is started
void hud_squadmsg_start()
{
// int i;
//if ( num_keys_saved < 0 ) // save the keys if they haven't been saved yet
hud_squadmsg_save_keys();
Msg_key = -1;
/*
for (i=0; i<num_keys_saved; i++)
clear_key_binding ( (short) key_save[i].key_value ); // removes all mention of this key from Control_config
*/
Num_menu_items = -1; // reset the menu items
First_menu_item = 0;
Squad_msg_mode = SM_MODE_TYPE_SELECT; // start off at the base state
Msg_mode_timestamp = timestamp(DEFAULT_MSG_TIMEOUT); // initialize our timer to bogus value
Msg_shortcut_command = -1; // assume no shortcut key being used
Msg_target_objnum = Player_ai->target_objnum; // save the players target object number
Msg_targeted_subsys = Player_ai->targeted_subsys; // save the players currently targted subsystem
#ifndef NDEBUG
Msg_enemies = 0; // tells us if we are messaging enemy ships
#endif
snd_play( &Snds[SND_SQUADMSGING_ON] );
}
// functions which will restore all of the key binding stuff when messaging mode is done
void hud_squadmsg_end()
{
/*
int i;
key_store *ksp;
// move through all keys saved and restore their orignal values.
for ( i=0; i<num_keys_saved; i++ ) {
ksp = &key_save[i];
Control_config[ksp->option_num].key_id = (short) ksp->key_value;
}
*/
if ( message_is_playing() == FALSE )
snd_play( &Snds[SND_SQUADMSGING_OFF] );
}
// function which returns true if there are fighters/bombers on the players team
// in the mission
int hud_squadmsg_count_fighters( )
{
int count;
int team;
object *objp;
ship *shipp;
// set up the team to compare for messaging. In debug versions, we will allow messaging to enemies
//team = TEAM_FRIENDLY;
team = Player_ship->team;
#ifndef NDEBUG
if ( Msg_enemies )
team = opposing_team_mask(Player_ship->team);
#endif
count = 0;
for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
if ( objp->type != OBJ_SHIP )
continue;
shipp = &Ships[objp->instance];
// check fighter is accepting orders
if (shipp->orders_accepted != 0) {
// be sure ship is on correct team, not the player, and is a fighter/bomber
if ( (shipp->team == team) && (objp != Player_obj) && (Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) ) {
return 1;
}
}
}
return 0;
}
// function which counts the number of ships available for messaging. Used to determine if
// we should grey out a menu or allow a shortcut command to apply. parameter "flag" is used
// to tell us whether or not we should add the ship to a menu item or not. We include the
// flag so that we don't have to have conditions for messaging ships/wings in two places.
int hud_squadmsg_count_ships( int add_to_menu )
{
int count;
int team;
ship *shipp;
ship_obj *so;
// set up the team to compare for messaging. In debug versions, we will allow messaging to enemies
//team = TEAM_FRIENDLY;
team = Player_ship->team;
#ifndef NDEBUG
if ( Msg_enemies )
team = opposing_team_mask(Player_ship->team);
#endif
count = 0;
for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
shipp = &Ships[Objects[so->objnum].instance];
Assert ( shipp->objnum != -1 );
// ships must be able to receive a message
if ( !(Ship_info[shipp->ship_info_index].flags & CAN_MESSAGE) )
continue;
// must be on the same team
if ( shipp->team != team )
continue;
// departing or dying ships cannot be on list
if ( shipp->flags & (SF_DEPARTING|SF_DYING) )
continue;
// MULTI - changed to allow messaging of netplayers
// cannot be my ship or an instructor
if ( (&Objects[so->objnum] == Player_obj) || is_instructor(&Objects[so->objnum]) )
continue;
// ship must be accepting ship type orders
if ( shipp->orders_accepted == 0)
continue;
// if it is a player ship, we must be in multiplayer
if ( (Objects[so->objnum].flags & OF_PLAYER_SHIP) && !(Game_mode & GM_MULTIPLAYER) )
continue;
// if a messaging shortcut, be sure this ship can process the order
if ( Msg_shortcut_command != -1 ) {
if ( !(shipp->orders_accepted & Msg_shortcut_command) )
continue;
else if ( !hud_squadmsg_ship_order_valid(Objects[so->objnum].instance, Msg_shortcut_command) )
continue;
}
count++;
if ( add_to_menu ) {
Assert ( Num_menu_items < MAX_MENU_ITEMS );
strcpy( MsgItems[Num_menu_items].text, shipp->ship_name );
MsgItems[Num_menu_items].instance = SHIP_INDEX(shipp);
MsgItems[Num_menu_items].active = 1;
Num_menu_items++;
}
}
// if adding to the menu and we have > 10 items, then don't allow page up and page down to be used.
if ( add_to_menu && (Num_menu_items > MAX_MENU_DISPLAY) )
hud_squadmsg_save_keys(1);
return count;
}
// routine to return true if a wing should be put onto the messaging menu
int hud_squadmsg_wing_valid( wing *wingp, int team )
{
// int player_count, j;
// a couple of special cases to account for before adding to count (or to menu). The wing gone
// flags is firm indication to skip this particular wing. Also, skip if enemy wing
if ( (wingp->flags & WF_WING_GONE) || (wingp->current_count == 0) )
return 0;
// departing wings don't get attention either
if ( wingp->flags & WF_WING_DEPARTING )
return 0;
// sanity check on ship_index field -- if check is successful, then check the team.
Assert (wingp->ship_index[0] != -1 );
if ( Ships[wingp->ship_index[0]].team != team )
return 0;
// if this wing is the players wing, and there is only one ship in the wing, then skip past it
if ( (Ships[Player_obj->instance].wingnum == WING_INDEX(wingp)) && (wingp->current_count == 1) )
return 0;
// check if wing commander is accepting orders
if ( Ships[wingp->ship_index[0]].orders_accepted == 0)
return 0;
// if doing a message shortcut is being used, be sure the wing can "accept" the command. Only need
// to look at the first ship in the wing.
if ( Msg_shortcut_command != -1 ) {
if ( !(Ships[wingp->ship_index[0]].orders_accepted & Msg_shortcut_command) )
return 0;
}
// MULTI - changed to allow messaging of netplayers
// don't count wings where all ships are player ships
/*
player_count = 0;
for ( j = 0; j < wingp->current_count; j++ ) {
if ( Objects[Ships[wingp->ship_index[j]].objnum].flags & OF_PLAYER_SHIP )
player_count++;
}
if ( player_count == wingp->current_count )
return 0;
*/
return 1;
}
// function like above, except for wings
int hud_squadmsg_count_wings( int add_to_menu )
{
int count, i, j;
int team;
// set up the team to compare for messaging. In debug versions, we will allow messaging to enemies
//team = TEAM_FRIENDLY;
team = Player_ship->team;
#ifndef NDEBUG
if ( Msg_enemies )
team = opposing_team_mask(Player_ship->team);
#endif
count = 0;
// add the player starting wings first
for ( i = 0; i < MAX_STARTING_WINGS; i++ ) {
int wingnum;
wingnum = Starting_wings[i];
if ( wingnum == -1 )
continue;
if ( hud_squadmsg_wing_valid(&Wings[wingnum], team) ) {
count++;
if ( add_to_menu ) {
Assert ( Num_menu_items < MAX_MENU_ITEMS );
strcpy( MsgItems[Num_menu_items].text, Wings[wingnum].name );
MsgItems[Num_menu_items].instance = wingnum;
MsgItems[Num_menu_items].active = 1;
Num_menu_items++;
}
}
}
for ( i = 0; i < num_wings; i++ ) {
// if this wing is a player starting wing, skip it since we added it above
for ( j = 0; j < MAX_STARTING_WINGS; j++ ) {
if ( i == Starting_wings[j] )
break;
}
if ( j < MAX_STARTING_WINGS )
continue;
if ( hud_squadmsg_wing_valid(&Wings[i], team) ) {
count++;
if ( add_to_menu ) {
Assert ( Num_menu_items < MAX_MENU_ITEMS );
strcpy( MsgItems[Num_menu_items].text, Wings[i].name );
MsgItems[Num_menu_items].instance = i;
MsgItems[Num_menu_items].active = 1;
Num_menu_items++;
}
}
}
return count;
}
// function to set the current submode in message mode -- also resets variables that
// should be reset inbetween submodes
void hud_squadmsg_do_mode( int mode )
{
Squad_msg_mode = mode;
Num_menu_items = -1;
First_menu_item = 0;
}
void hud_squadmsg_page_down()
{
if ( (First_menu_item + MAX_MENU_DISPLAY) < Num_menu_items ) {
First_menu_item += MAX_MENU_DISPLAY;
Assert ( First_menu_item < Num_menu_items );
}
}
void hud_squadmsg_page_up()
{
if ( First_menu_item > 0 ) {
First_menu_item -= MAX_MENU_DISPLAY;
Assert (First_menu_item >= 0 );
}
}
int hud_squadmsg_get_total_keys()
{
int num_keys_used;
num_keys_used = MAX_KEYS_NO_SCROLL;
if ( Num_menu_items > MAX_MENU_DISPLAY )
num_keys_used = MAX_KEYS_USED;
return num_keys_used;
}
// function called from high level keyboard read code to give the squadmsg code a key.
// return 1 is the key was used by the messaging code, 0 otherwise
int hud_squadmsg_read_key( int k )
{
int i, key_found, num_keys_used;
num_keys_used = hud_squadmsg_get_total_keys();
if ( !(Player->flags & PLAYER_FLAGS_MSG_MODE) ) {
// check to see if any messaging keys are still down for some length of time
// after messaging is over. Return true for a while.
if ( !timestamp_elapsed(Msg_eat_key_timestamp) ) {
for (i = 0; i < num_keys_used; i++ ) {
if ( keyd_pressed[keys_used[i]] )
return 1;
}
}
return 0;
}
key_found = 0;
for (i = 0; i < num_keys_used; i++ ) {
if ( k == keys_used[i] ) {
if ( key_down_count(k) ) {
Msg_key = k;
key_found = 1;
}
if ( keyd_pressed[k] ) {
key_found = 1;
}
// key_down_count(k);
break;
}
}
if ( key_found )
return 1;
return 0;
}
// function which reads the keyboard array and determines if a menu key has been hit
int hud_squadmsg_get_key()
{
int k, i, num_keys_used;
if ( Msg_key == -1 )
return -1;
k = Msg_key;
Msg_key = -1;
num_keys_used = hud_squadmsg_get_total_keys();
// if the emp effect is active, never accept keypresses
if(emp_active_local()){
return -1;
}
for ( i = 0; i < num_keys_used; i++ ) {
if ( k == keys_used[i] ) {
Msg_key_used = 1; // this variable will extend the timer
// use a timestamp to prevent top level key code from possibly reprocessing this key
Msg_eat_key_timestamp = timestamp(MSG_KEY_EAT_TIME);
if ( k == KEY_PAGEDOWN ) { // pageup and pagedown scroll the menu -- deal with these seperately!!
hud_squadmsg_page_down();
return -1;
} else if ( k == KEY_PAGEUP ) {
hud_squadmsg_page_up();
return -1;
} else if ( k == KEY_ESC ) {
hud_squadmsg_toggle();
return -1;
} else if ( (i < Num_menu_items) && (Squad_msg_mode == SM_MODE_REINFORCEMENTS) ) // return any key if selecting reinforcement
return i;
// play general fail sound if inactive item hit.
else if ( (i < Num_menu_items) && !(MsgItems[i].active) )
gamesnd_play_iface(SND_GENERAL_FAIL);
else if ( (i < Num_menu_items) && (MsgItems[i].active) ) // only return keys that are associated with menu items
return i;
else {
Msg_key_used = 0; // if no #-key pressed for visible item, break and allow timer to
break; // to continue as if no key was pressed
}
}
}
return -1;
}
// function which will essentially print out the contents of the current state of the messaging
// menu. Parameters will be a title. The menu items and the number of items will be
// in global vars since they don't get recomputed every frame.
void hud_squadmsg_display_menu( char *title )
{
int bx, by, sx, sy, i, nitems, none_valid, messaging_allowed;
// hud_set_bright_color();
hud_set_gauge_color(HUD_MESSAGE_BOX, HUD_C_BRIGHT);
if ( title ) {
gr_string(Mbox_title_coord[gr_screen.res][0], Mbox_title_coord[gr_screen.res][1], title);
}
if ( Num_menu_items < MAX_MENU_DISPLAY )
nitems = Num_menu_items;
else {
if ( First_menu_item == 0 ) // First_menu_item == 0 means first page of items
nitems = MAX_MENU_DISPLAY;
else if ( (Num_menu_items - First_menu_item) <= MAX_MENU_DISPLAY ) // check if remaining items fit on one page
nitems = Num_menu_items - First_menu_item;
else {
nitems = MAX_MENU_DISPLAY;
}
}
sx = Mbox_item_coord[gr_screen.res][0];
sy = Mbox_item_coord[gr_screen.res][1];
bx = Mbox_bmap_coords[gr_screen.res][0]; // global x-offset where bitmap gets drawn
by = Mbox_bmap_coords[gr_screen.res][1]; // global y-offset where bitmap gets drawn
none_valid = 1; // variable to tell us whether all items in the menu are valid or not
// use another variable to tell us whether we can message or not.
messaging_allowed = 1;
if ( (Game_mode & GM_MULTIPLAYER) && !multi_can_message(Net_player) ){
messaging_allowed = 0;
}
for ( i = 0; i < nitems; i++ ) {
int item_num;
char *text = MsgItems[First_menu_item+i].text;
// blit the background
// hud_set_default_color();
hud_set_gauge_color(HUD_MESSAGE_BOX);
if ( Mbox_gauge[1].first_frame >= 0 ) {
GR_AABITMAP(Mbox_gauge[1].first_frame, bx, by);
}
by += Mbox_item_h[gr_screen.res];
// set the text color
if ( MsgItems[First_menu_item+i].active ) {
// hud_set_bright_color();
hud_set_gauge_color(HUD_MESSAGE_BOX, HUD_C_BRIGHT);
} else {
/*
dim_index = min(5, HUD_color_alpha - 2);
if ( dim_index < 0 ) {
dim_index = 0;
}
gr_set_color_fast(&HUD_color_defaults[dim_index]);
*/
hud_set_gauge_color(HUD_MESSAGE_BOX, HUD_C_DIM);
}
// first do the number
item_num = (i+1) % MAX_MENU_DISPLAY;
emp_hud_printf(sx, sy, EG_SQ1 + i, NOX("%1d."), item_num );
// then the text
emp_hud_string(sx+Mbox_item_xoffset[gr_screen.res], sy, EG_SQ1 + i, text);
sy += Mbox_item_h[gr_screen.res];
// if we have at least one item active, then set the variable so we don't display any
// message about no active items
if ( MsgItems[First_menu_item+i].active )
none_valid = 0;
}
// maybe draw an extra line in to make room for [pgdn], or for the 'no active items'
// display
if ( !messaging_allowed || none_valid || ((First_menu_item + nitems) < Num_menu_items) || (Msg_shortcut_command != -1) ) {
// blit the background
// hud_set_default_color();
hud_set_gauge_color(HUD_MESSAGE_BOX);
if ( Mbox_gauge[1].first_frame >= 0 ) {
GR_AABITMAP(Mbox_gauge[1].first_frame, bx, by);
}
by += Mbox_item_h[gr_screen.res];
}
// draw the bottom of the frame
// hud_set_default_color();
hud_set_gauge_color(HUD_MESSAGE_BOX);
if ( Mbox_gauge[2].first_frame >= 0 ) {
GR_AABITMAP(Mbox_gauge[2].first_frame, bx, by);
}
// determine if we should put the text "[more]" at top or bottom to indicate you can page up or down
hud_targetbox_start_flash(TBOX_FLASH_SQUADMSG);
hud_targetbox_maybe_flash(TBOX_FLASH_SQUADMSG);
if ( First_menu_item > 0 ) {
gr_printf( Menu_pgup_coords[gr_screen.res][0], Menu_pgup_coords[gr_screen.res][1], XSTR( "[pgup]", 312) );
}
if ( (First_menu_item + nitems) < Num_menu_items ) {
gr_printf( Menu_pgdn_coords[gr_screen.res][0], Menu_pgdn_coords[gr_screen.res][1], XSTR( "[pgdn]", 313));
}
if ( messaging_allowed ) {
if ( none_valid ){
gr_printf( sx, by - Mbox_item_h[gr_screen.res] + 2, XSTR( "No valid items", 314));
} else if ( !none_valid && (Msg_shortcut_command != -1) ){
gr_printf( sx, by - Mbox_item_h[gr_screen.res] + 2, "%s", comm_order_hotkey_text(Msg_shortcut_command));
}
} else {
// if this player is not allowed to message, then display message saying so
gr_printf( sx, by - Mbox_item_h[gr_screen.res] + 2, XSTR( "Not allowed to message", 315));
}
}
// function to return true or false if the given ship can rearm, or be repaired
int hud_squadmsg_can_rearm( ship *shipp )
{
// player ships which turns traitor cannot rearm
if ( (shipp == Player_ship) && (Player_ship->team == TEAM_TRAITOR) )
return 0;
// 5/6/98 -- MWA Decided to always be able to call in support.
return 1;
}
// calls for repair/rearm of the player ship. Checks for the presense of the support
// ship and does the appropriate action if found
void hud_squadmsg_repair_rearm( int toggle_state, object *objp)
{
int robjnum;
object *robjp;
object *tobj;
int multi_player_num;
// this is essentially a check for multiplayer server/client mode
// in multiplayer mode, the server may have to issue this command when received from a client
if(objp == NULL) {
tobj = Player_obj;
multi_player_num = -1;
} else {
tobj = objp;
multi_player_num = multi_find_player_by_object(objp);
Assert(multi_player_num != -1);
}
// see if player is already scheduled on arriving support ship. If so, issues appripriate
// message and bail
if ( is_support_allowed(tobj) ) {
if ( mission_is_repair_scheduled( tobj ) ) {
message_send_builtin_to_player( MESSAGE_REARM_ON_WAY, NULL, MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_SOON, 0, 0, multi_player_num, -1 );
} else {
robjnum = hud_support_find_closest(OBJ_INDEX(tobj));
if ( robjnum != -1 ) {
message_send_builtin_to_player( MESSAGE_REARM_ON_WAY, &Ships[Objects[robjnum].instance], MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_SOON, 0, 0, multi_player_num, -1 );
} else {
// request a rearm. Next function returns -1 if ship is warping in, objnum of repair ship otherwise
robjnum = ai_issue_rearm_request( tobj );
if ( robjnum != -1) {
robjp = &Objects[robjnum];
message_send_builtin_to_player( MESSAGE_ON_WAY, &Ships[robjp->instance], MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_SOON, 0, 0, multi_player_num, -1 );
} else {
// if we are in this part of the if statment, a support ship has been warped in to
// service us. Issue appropriate message
message_send_builtin_to_player( MESSAGE_REARM_WARP, NULL, MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_SOON, 0, 0, multi_player_num, -1 );
}
mission_log_add_entry(LOG_PLAYER_REARM, Ships[tobj->instance].ship_name, NULL);
}
}
}
//if ( multi_player_num == -1 ) // only do the hud display if it is for me!
// hud_support_view_start();
if ( toggle_state )
hud_squadmsg_toggle(); // take us out of message mode
}
// function which gets called from keyboard code to issues a shortcut command for rearming.
void hud_squadmsg_rearm_shortcut()
{
if ( !hud_squadmsg_can_rearm(Player_ship) )
return;
// multiplayer clients need to send this message to the server
if ( MULTIPLAYER_CLIENT ) {
send_player_order_packet(SQUAD_MSG_SHIP, 0, REARM_REPAIR_ME_ITEM);
return;
}
hud_squadmsg_repair_rearm(0);
}
// code which is called when a player aborts his rearm request
void hud_squadmsg_repair_rearm_abort( int toggle_state, object *obj)
{
// ai_info *aip;
// object *robjp;
object *tobj;
// this is essentially a check for multiplayer server/client mode
// in multiplayer mode, the server may have to issue this command when received from a client
if(obj == NULL)
tobj = Player_obj;
else
tobj = obj;
// try to abort the request. We shoudln't be in this function unless we are actually
// queued for repair. Send a message from support ship if the support ship is in the mission
ai_abort_rearm_request( tobj );
// move the next statements outside of the above if-statement. Seems like this place
// is the right place, since we want to change state of the messaging system regardless
// of what happened above.
if ( toggle_state )
hud_squadmsg_toggle(); // take us out of message mode
}
// returns 1 if an order is valid for a ship. Applies to things like departure when engines are blown, etc.
int hud_squadmsg_ship_order_valid( int shipnum, int order )
{
// disabled ships can't depart.
if ( (order == DEPART_ITEM) && (Ships[shipnum].flags & SF_DISABLED) )
return 0;
return 1;
}
// returns true or false if the Players target is valid for the given order
// find_order is true when we need to search the comm_orders array for the order entry. We have
// to do this action in some cases since all we know is the actual "value" of the order
int hud_squadmsg_is_target_order_valid(int order, int find_order, ai_info *aip )
{
int target_objnum, i;
ship *shipp, *ordering_shipp;
object *objp;
if ( aip == NULL )
aip = Player_ai;
// find the comm_menu item for this command
if ( find_order ) {
for (i = 0; i < MAX_SHIP_ORDERS; i++ ) {
if ( Comm_orders[i].value == order )
break;
}
Assert( i < MAX_SHIP_ORDERS );
order = i;
}
// orders which don't operate on targets are always valid
if ( !(Comm_orders[order].value & TARGET_MESSAGES) )
return 1;
target_objnum = aip->target_objnum;
// order isn't valid if there is no player target
if ( target_objnum == -1 ) {
return 0;
}
objp = &Objects[target_objnum];
ordering_shipp = &Ships[aip->shipnum];
// target isn't a ship, then return 0
if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_WEAPON) )
return 0;
// if it's a weapon, then it needs to be a WIF_BOMB weapon. Only attack order valid, and only
// valid on bombs not on the player's team
if ( objp->type == OBJ_WEAPON ) {
if ( (Comm_orders[order].value == ATTACK_TARGET_ITEM )
&& (Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_BOMB)
&& (Weapons[objp->instance].team != ordering_shipp->team) )
return 1;
return 0;
}
Assert( objp->type == OBJ_SHIP );
shipp = &Ships[objp->instance];
// if target is a navbouy, return 0
if ( Ship_info[shipp->ship_info_index].flags & SIF_NAVBUOY ){
return 0;
}
// if we are messaging a ship, and that ship is our target, no target type orders are ever active
if ( (Squad_msg_mode == SM_MODE_SHIP_COMMAND) && (target_objnum == Msg_instance) ){
return 0;
}
// if the order is a disable order or depart, and the ship is disabled, order isn't active
if ( (Comm_orders[order].value == DISABLE_TARGET_ITEM) && (shipp->flags & SF_DISABLED) ){
return 0;
}
// same as above except for disabled.
if ( (Comm_orders[order].value == DISARM_TARGET_ITEM) && ((shipp->subsys_info[SUBSYSTEM_TURRET].num > 0) && (shipp->subsys_info[SUBSYSTEM_TURRET].current_hits == 0.0f)) ){
return 0;
}
// if order is disable subsystem, and no subsystem targeted or no hits, then order not valid
if ( (Comm_orders[order].value == DISABLE_SUBSYSTEM_ITEM) && ((aip->targeted_subsys == NULL) || (aip->targeted_subsys->current_hits <= 0.0f)) ){
return 0;
}
// check based on target's and player's team
if ( (shipp->team == ordering_shipp->team) && (Comm_orders[order].value & FRIENDLY_TARGET_MESSAGES) ){
return 1;
} else if ( (shipp->team != ordering_shipp->team) && (Comm_orders[order].value & ENEMY_TARGET_MESSAGES) ){
return 1;
} else {
return 0;
}
}
// function to send an order to all fighters/bombers.
void hud_squadmsg_send_to_all_fighters( int command, int player_num )
{
ai_info *aip;
ship *shipp, *ordering_shipp;
int i, send_message, to_everyone, do_ship;
object *objp;
// quick short circuit here because of actually showing comm menu even though you cannot message.
// just a safety net.
if ( (Game_mode & GM_MULTIPLAYER) && (player_num != -1) ) {
if ( !multi_can_message(&Net_players[player_num]) ) {
return;
}
}
// check for multiplayer mode
if((Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER)) {
send_player_order_packet(SQUAD_MSG_ALL, 0, command);
return;
}
// to_everyone tells us whether the command should apply to all ships, or just to fighets/bombers.
// when true, command goes to *all* friendlies.
send_message = 1; // internal flag to dictate who sends message
to_everyone = 0;
do_ship = 0;
aip = Player_ai;
if ( player_num != -1 )
aip = &Ai_info[Ships[Objects[Net_players[player_num].player->objnum].instance].ai_index];
Assert( aip->shipnum != -1 );
ordering_shipp = &Ships[aip->shipnum];
if ( command == IGNORE_TARGET_ITEM ) {
to_everyone = 1;
// if we were messaging a ship directly, set flag to send no messages. We will send one
// specifically from the ship player is ordering
if ( (Msg_instance != MESSAGE_ALL_FIGHTERS) && (Squad_msg_mode == SM_MODE_SHIP_COMMAND) ) {
do_ship = 1;
send_message = 0;
}
}
for ( i = 0; i < num_wings; i++ ) {
int shipnum;
if ( (Wings[i].flags & WF_WING_GONE) || (Wings[i].current_count == 0) )
continue;
if ( Wings[i].flags & WF_WING_DEPARTING )
continue;
// get the first ship on the wing list and look at it's team and then it's type
shipnum = Wings[i].ship_index[0];
Assert( shipnum != -1 );
shipp = &Ships[shipnum];
// can't message if not on players team
if ( shipp->team != ordering_shipp->team )
continue;
// can't message if ship not fighter/bomber if the command isn't to everyone.
if ( !to_everyone && !(Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) )
continue;
// don't send the command if the "wing" won't accept the command. We do this by looking at
// the set of orders accepted for the first ship in the wing.
if ( !(command & shipp->orders_accepted) )
continue;
// send the command to the wing
if ( Wings[i].current_count > 1 ) {
if ( hud_squadmsg_send_wing_command(i, command, send_message, player_num) ) {
send_message = 0;
}
}
}
// now find any friendly fighter/bomber ships not in wings
for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
if ( objp->type != OBJ_SHIP )
continue;
// don't send messge to ships not on player's team, or that are in a wing.
shipp = &Ships[objp->instance];
if ( (shipp->team != ordering_shipp->team) || (shipp->wingnum != -1) )
continue;
// don't send message to non fighter wings
if ( !to_everyone && !(Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) )
continue;
// skip departing/dying ships
if ( shipp->flags & (SF_DEPARTING|SF_DYING) )
continue;
// don't send command if ship won't accept if
if ( !(command & shipp->orders_accepted) )
continue;
if ( hud_squadmsg_send_ship_command(objp->instance, command, send_message, player_num) ) {
send_message = 0;
}
}
// we might send the ship command again if we are ignoring a target, and the guy
// we ordered directly is a ship -- we want the response to come directly from the
// guy we orders
if ( do_ship ) {
Assert( Msg_instance != MESSAGE_ALL_FIGHTERS );
hud_squadmsg_send_ship_command( Msg_instance, command, 1 );
}
}
// Check if any enemy ships are in the mission
int hud_squadmsg_enemies_present()
{
ship *shipp;
ship_obj *so;
for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
shipp = &Ships[Objects[so->objnum].instance];
if ( shipp->team != Player_ship->team )
return 1;
}
return 0;
}
#define OVERRIDE_PROTECT_SHIP_TYPE (SIF_FIGHTER|SIF_BOMBER|SIF_FREIGHTER|SIF_TRANSPORT)
// function which sends a message to a specific ship. This routine can be called from one of two
// places. Either after selecting a ship when using a hotkey, or after selecting a command when
// using the entire messaging menu system
//
// if local and addr are non-null, it means the function is being called by the (multiplayer) server in response to
// a PLAYER_COMMAND_PACKET
int hud_squadmsg_send_ship_command( int shipnum, int command, int send_message, int player_num )
{
ai_info *ainfo;
int ai_mode, ai_submode; // ai mode and submode needed for ship commands
char *target_shipname; // ship number of possible targets
int message;
int target_team, ship_team; // team id's for the ship getting message and any target the player has
ship *ordering_shipp;
// quick short circuit here because of actually showing comm menu even though you cannot message.
// just a safety net.
if ( (Game_mode & GM_MULTIPLAYER) && (player_num != -1) ) {
if ( !multi_can_message(&Net_players[player_num]) ) {
return 0;
}
}
// check for multiplayer mode
if((Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER)){
send_player_order_packet(SQUAD_MSG_SHIP, shipnum, command);
return 0;
}
ai_mode = AI_GOAL_NONE; // needs to be initialized
ai_submode = -1234567;
ainfo = Player_ai;
if ( player_num != -1 ){
ainfo = &Ai_info[Ships[Objects[Net_players[player_num].player->objnum].instance].ai_index];
}
Assert( ainfo->shipnum != -1 );
ordering_shipp = &Ships[ainfo->shipnum];
// a shortcut to save on repetitive coding. If the order is a 'target' order, make the default
// mesage be "no target"
message = MESSAGE_NOSIR;
if ( (command & TARGET_MESSAGES) && (ainfo->target_objnum == -1) )
message = MESSAGE_NO_TARGET;
if ( hud_squadmsg_is_target_order_valid(command, 1, ainfo) ) {
target_shipname = NULL;
target_team = -1;
if ( ainfo->target_objnum != -1) {
if ( Objects[ainfo->target_objnum].type == OBJ_SHIP ) {
if ( ainfo->target_objnum != Ships[shipnum].objnum ) {
target_shipname = Ships[Objects[ainfo->target_objnum].instance].ship_name; // I think this is right
target_team = Ships[Objects[ainfo->target_objnum].instance].team;
}
}
}
Assert ( ainfo->shipnum != -1 );
ship_team = Ships[ainfo->shipnum].team; // team of the ship issuing the message
switch ( command ) { // value of k matches the #defines for ship messages
case ATTACK_TARGET_ITEM:
if ( Objects[ainfo->target_objnum].type == OBJ_SHIP ) {
Assert( target_shipname );
Assert( ship_team != target_team );
// Orders to override protect
if (Ship_info[Ships[Objects[ainfo->target_objnum].instance].ship_info_index].flags & OVERRIDE_PROTECT_SHIP_TYPE) {
Objects[ainfo->target_objnum].flags &= ~OF_PROTECTED;
}
ai_mode = AI_GOAL_CHASE;
ai_submode = SM_ATTACK;
} else if ( Objects[ainfo->target_objnum].type == OBJ_WEAPON ) {
ai_mode = AI_GOAL_CHASE_WEAPON;
ai_submode = Objects[ainfo->target_objnum].instance; // store the instance of the weapon -- ai goals code will deal with it
} else
Int3();
message = MESSAGE_ATTACK_TARGET;
break;
case DISABLE_TARGET_ITEM:
Assert( target_shipname );
Assert( ship_team != target_team );
// Orders to override protect
if (Ship_info[Ships[Objects[ainfo->target_objnum].instance].ship_info_index].flags & OVERRIDE_PROTECT_SHIP_TYPE) {
Objects[ainfo->target_objnum].flags &= ~OF_PROTECTED;
}
ai_mode = AI_GOAL_DISABLE_SHIP;
ai_submode = -SUBSYSTEM_ENGINE;
message = MESSAGE_DISABLE_TARGET;
break;
case DISARM_TARGET_ITEM:
Assert( target_shipname );
Assert( ship_team != target_team );
// Orders to override protect
if (Ship_info[Ships[Objects[ainfo->target_objnum].instance].ship_info_index].flags & OVERRIDE_PROTECT_SHIP_TYPE) {
Objects[ainfo->target_objnum].flags &= ~OF_PROTECTED;
}
ai_mode = AI_GOAL_DISARM_SHIP;
ai_submode = -SUBSYSTEM_TURRET;
message = MESSAGE_DISARM_TARGET;
break;
case DISABLE_SUBSYSTEM_ITEM:
Assert( target_shipname );
Assert( ship_team != target_team );
Assert( ainfo->targeted_subsys != NULL );
Assert( ainfo->targeted_subsys->current_hits > 0.0f);
// Orders to override protect
if (Ship_info[Ships[Objects[ainfo->target_objnum].instance].ship_info_index].flags & OVERRIDE_PROTECT_SHIP_TYPE) {
Objects[ainfo->target_objnum].flags &= ~OF_PROTECTED;
}
ai_mode = AI_GOAL_DESTROY_SUBSYSTEM;
ai_submode = ship_get_subsys_index( &Ships[Objects[ainfo->target_objnum].instance], ainfo->targeted_subsys->system_info->subobj_name );
message = MESSAGE_ATTACK_TARGET;
break;
case CAPTURE_TARGET_ITEM:
Assert( target_shipname );
Assert( ship_team != target_team );
Assert(ainfo->target_objnum > -1);
Objects[ainfo->target_objnum].flags |= OF_PROTECTED;
ai_mode = AI_GOAL_DOCK;
ai_submode = AIS_DOCK_0;
message = MESSAGE_DOCK_YES;
break;
case PROTECT_TARGET_ITEM:
// AL 31-3-98: Can't protect self... this can happen if all fighters
// are told to protect another friendly ship
if ( ainfo->target_objnum == Ships[shipnum].objnum ) {
return 0;
}
Assert( target_shipname );
Assert( ship_team == target_team );
ai_mode = AI_GOAL_GUARD;
ai_submode = AIS_GUARD_PATROL;
message = MESSAGE_YESSIR;
break;
case IGNORE_TARGET_ITEM:
Assert( target_shipname );
Assert( ship_team != target_team );
ai_mode = AI_GOAL_IGNORE;
ai_submode = 0;
message = MESSAGE_YESSIR;
break;
case FORMATION_ITEM:
message = MESSAGE_YESSIR;
target_shipname = ordering_shipp->ship_name;
ai_mode = AI_GOAL_FORM_ON_WING;
ai_submode = 0;
break;
case COVER_ME_ITEM:
ai_mode = AI_GOAL_GUARD;
ai_submode = AIS_GUARD_PATROL;
target_shipname = ordering_shipp->ship_name;
message = MESSAGE_YESSIR;
break;
case ENGAGE_ENEMY_ITEM:
ai_mode = AI_GOAL_CHASE_ANY;
ai_submode = SM_ATTACK;
// if no enemies present, use the affirmative, instead of engaging enemies message
if ( hud_squadmsg_enemies_present() )
message = MESSAGE_YESSIR;
else
message = MESSAGE_ENGAGE;
target_shipname = NULL;
break;
case DEPART_ITEM:
ai_mode = AI_GOAL_WARP;
ai_submode = -1;
message = MESSAGE_WARP_OUT;
break;
// the following are support ship options!!!
case REARM_REPAIR_ME_ITEM:
if((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (player_num != -1) ){
hud_squadmsg_repair_rearm(0,&Objects[Net_players[player_num].player->objnum]);
} else {
hud_squadmsg_repair_rearm(0); // note we return right away. repair/rearm code handles messaging, etc
}
return 0;
case ABORT_REARM_REPAIR_ITEM:
if((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (player_num != -1) ){
hud_squadmsg_repair_rearm_abort(0,&Objects[Net_players[player_num].player->objnum]);
} else {
hud_squadmsg_repair_rearm_abort(0); // note we return right away. repair/rearm code handles messaging, etc
}
return 0;
case STAY_NEAR_ME_ITEM:
case STAY_NEAR_TARGET_ITEM: // can't attack anything on same team
// cannot stay near a hostile ship(?)
if ( (command == STAY_NEAR_TARGET_ITEM) && (ship_team != target_team) )
break;
ai_mode = AI_GOAL_STAY_NEAR_SHIP;
ai_submode = -1;
message = MESSAGE_YESSIR;
if ( command == STAY_NEAR_ME_ITEM )
target_shipname = ordering_shipp->ship_name;
break;
case KEEP_SAFE_DIST_ITEM:
ai_mode = AI_GOAL_KEEP_SAFE_DISTANCE;
ai_submode = -1;
message = MESSAGE_YESSIR;
break;
default:
Int3(); // get Allender -- illegal message
break;
}
// handle case of messaging one ship. Deal with messaging all fighters next.
if ( ai_mode != AI_GOAL_NONE ) {
Assert(ai_submode != -1234567);
ai_add_ship_goal_player( AIG_TYPE_PLAYER_SHIP, ai_mode, ai_submode, target_shipname, &Ai_info[Ships[shipnum].ai_index] );
if( player_num == -1 )
hud_add_issued_order(Ships[shipnum].ship_name, command, target_shipname);
}
}
// if we're in multiplayer mode, and we're the server, determine if this virtual squadmate order should be
// sent to other players in the game as an actual "order"
if((Game_mode & GM_MULTIPLAYER) && (message != MESSAGE_NOSIR)){
// if the multi_msg system processed and sent this order to a player, we should not play a response
if(multi_msg_eval_ship_squadmsg(shipnum,command,ainfo,player_num)){
send_message = 0;
}
}
// this is the _response_
if ( send_message ){
message_send_builtin_to_player( message, &Ships[shipnum], MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_ANYTIME, 0, 0, player_num, -1 );
}
return send_message;
}
// function to send a command to a wing. Like above function, called from one of two places
//
// if local and addr are non-null, it means the function is being called by the (multiplayer) server in response to
// a PLAYER_COMMAND_PACKET
//
// returns whether or not a message was sent
int hud_squadmsg_send_wing_command( int wingnum, int command, int send_message, int player_num )
{
ai_info *ainfo;
int ai_mode, ai_submode; // ai mode and submode needed for ship commands
char *target_shipname; // ship number of possible targets
int message_sent, message;
int target_team, wing_team; // team for the wing and the player's target
ship *ordering_shipp;
// quick short circuit here because of actually showing comm menu even though you cannot message.
// just a safety net.
if ( (Game_mode & GM_MULTIPLAYER) && (player_num != -1) ) {
if ( !multi_can_message(&Net_players[player_num]) ) {
return 0;
}
}
// check for multiplayer mode
if((Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER)){
send_player_order_packet(SQUAD_MSG_WING, wingnum,command);
return 0;
}
ai_mode = AI_GOAL_NONE; // needs to be initialized
ai_submode = -1234567;
ainfo = Player_ai;
if ( player_num != -1 )
ainfo = &Ai_info[Ships[Objects[Net_players[player_num].player->objnum].instance].ai_index];
Assert( ainfo->shipnum != -1 );
ordering_shipp = &Ships[ainfo->shipnum];
// get the shipnum of the ship the player has targeted. Used in enough places to do this just
// once. If the ship targeted is part of the wing that was messages -- bail out!!!
// a shortcut to save on repetative coding
message = MESSAGE_NOSIR;
if ( (command & TARGET_MESSAGES) && (ainfo->target_objnum == -1) )
message = MESSAGE_NO_TARGET;
if ( hud_squadmsg_is_target_order_valid(command, 1, ainfo) ) {
target_shipname = NULL;
target_team = -1;
if ( ainfo->target_objnum != -1) {
if ( Objects[ainfo->target_objnum].type == OBJ_SHIP ) {
target_shipname = Ships[Objects[ainfo->target_objnum].instance].ship_name; // I think this is right
target_team = Ships[Objects[ainfo->target_objnum].instance].team;
}
}
Assert ( ainfo->shipnum != -1 );
Assert ( (wingnum >= 0) && (wingnum < num_wings) );
// get the team for the wing
Assert ( Wings[wingnum].ship_index[0] != -1 );
wing_team = Ships[Wings[wingnum].ship_index[0]].team;
switch ( command ) { // value of k matches the #defines for ship messages
case ATTACK_TARGET_ITEM:
if ( Objects[ainfo->target_objnum].type == OBJ_SHIP ) {
Assert( target_shipname );
Assert( wing_team != target_team );
if ( (Ships[Objects[ainfo->target_objnum].instance].wingnum != -1) && (Ships[Objects[ainfo->target_objnum].instance].wingnum == wingnum) ) {
message = MESSAGE_NOSIR;
ai_mode = AI_GOAL_NONE;
} else {
ai_mode = AI_GOAL_CHASE;
ai_submode = SM_ATTACK;
message = MESSAGE_ATTACK_TARGET;
}
} else if ( Objects[ainfo->target_objnum].type == OBJ_WEAPON ) {
ai_mode = AI_GOAL_CHASE_WEAPON;
ai_submode = Objects[ainfo->target_objnum].instance; // store the instance of the weapon -- ai goals code will deal with it
message = MESSAGE_ATTACK_TARGET;
} else
Int3();
break;
case DISABLE_TARGET_ITEM:
Assert( target_shipname );
Assert( wing_team != target_team );
ai_mode = AI_GOAL_DISABLE_SHIP;
ai_submode = -SUBSYSTEM_ENGINE;
message = MESSAGE_DISABLE_TARGET;
break;
case DISARM_TARGET_ITEM:
Assert( target_shipname );
Assert( wing_team != target_team );
ai_mode = AI_GOAL_DISARM_SHIP;
ai_submode = -SUBSYSTEM_TURRET;
message = MESSAGE_DISARM_TARGET;
break;
case DISABLE_SUBSYSTEM_ITEM:
Assert( target_shipname );
Assert( wing_team != target_team );
Assert( ainfo->targeted_subsys != NULL );
Assert( ainfo->targeted_subsys->current_hits > 0.0f);
ai_mode = AI_GOAL_DESTROY_SUBSYSTEM;
ai_submode = ship_get_subsys_index( &Ships[Objects[ainfo->target_objnum].instance], ainfo->targeted_subsys->system_info->subobj_name );
message = MESSAGE_ATTACK_TARGET;
break;
case PROTECT_TARGET_ITEM:
Assert( target_shipname );
Assert( wing_team == target_team );
ai_mode = AI_GOAL_GUARD;
ai_submode = AIS_GUARD_PATROL;
message = MESSAGE_YESSIR;
break;
case IGNORE_TARGET_ITEM:
Assert( target_shipname );
Assert( wing_team != target_team );
ai_mode = AI_GOAL_IGNORE;
ai_submode = 0; // actually, a don't care.
message = MESSAGE_YESSIR;
break;
case FORMATION_ITEM:
message = MESSAGE_YESSIR;
target_shipname = ordering_shipp->ship_name;
ai_mode = AI_GOAL_FORM_ON_WING;
ai_submode = 0;
break;
case COVER_ME_ITEM:
ai_mode = AI_GOAL_GUARD;
ai_submode = AIS_GUARD_PATROL;
target_shipname = ordering_shipp->ship_name;
message = MESSAGE_YESSIR;
break;
case ENGAGE_ENEMY_ITEM:
ai_mode = AI_GOAL_CHASE_ANY;
ai_submode = SM_ATTACK;
if ( hud_squadmsg_enemies_present() )
message = MESSAGE_YESSIR;
else
message = MESSAGE_ENGAGE;
target_shipname = NULL;
break;
case DEPART_ITEM:
ai_mode = AI_GOAL_WARP;
ai_submode = -1;
message = MESSAGE_WARP_OUT;
Wings[wingnum].flags |= WF_DEPARTURE_ORDERED;
break;
case REARM_REPAIR_ME_ITEM:
case ABORT_REARM_REPAIR_ITEM:
case STAY_NEAR_ME_ITEM:
case STAY_NEAR_TARGET_ITEM:
case KEEP_SAFE_DIST_ITEM:
return 0;
default:
Int3(); // get Allender -- illegal message
break;
}
if ( ai_mode != AI_GOAL_NONE ) {
Assert(ai_submode != -1234567);
ai_add_wing_goal_player( AIG_TYPE_PLAYER_WING, ai_mode, ai_submode, target_shipname, wingnum );
}
}
// if we're in multiplayer mode, and we're the server, determine if this virtual squadmate order should be
// sent to other players in the game as an actual "order"
if((Game_mode & GM_MULTIPLAYER) && (message != MESSAGE_NOSIR)){
// if there's at least one ai ship which got the command, let the response come through
if(multi_msg_eval_wing_squadmsg(wingnum,command,ainfo,player_num)){
send_message = 0;
}
}
// this is the _response_
message_sent = 0;
if ( send_message ) {
int ship_num;
// get a random ship in the wing to send the message to the player
ship_num = ship_get_random_ship_in_wing( wingnum, SHIP_GET_NO_PLAYERS );
// in multiplayer, its possible that all ships in a wing are players. so we'll just send from a random ship
if(ship_num == -1){
ship_num = ship_get_random_ship_in_wing(wingnum);
}
// only send message if ship is found. There appear to be cases where all ships
// in a wing die in the same frame causing the wing to appear valid in the message
// menu, but the get_random_ship* functions won't return dying ships.
if ( ship_num != -1 ) {
message_send_builtin_to_player( message, &Ships[ship_num], MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_ANYTIME, 0, 0, player_num, -1 );
message_sent = 1;
}
}
return message_sent;
}
// return number of available reinforcements, 0 if none available
int hud_squadmsg_reinforcements_available(int team)
{
int i, count = 0;
for (i = 0; i < Num_reinforcements; i++) {
int wingnum;
// no more left
if ( Reinforcements[i].num_uses >= Reinforcements[i].uses ){
continue;
}
// incorrect team
if ( team != ship_get_reinforcement_team(i) ){
continue;
}
// check the arrival cue sexpression of the ship/wing of this reinforcement. If known
// false, it doesn't count either
if ( (wingnum = wing_name_lookup(Reinforcements[i].name, 1)) != -1 ) {
Assert ( Wings[wingnum].arrival_cue >= 0 );
if ( Sexp_nodes[Wings[wingnum].arrival_cue].value == SEXP_KNOWN_FALSE ){
continue;
}
} else {
p_object *p_objp;
p_objp = mission_parse_get_arrival_ship( Reinforcements[i].name );
if ( p_objp != NULL ) {
if ( Sexp_nodes[p_objp->arrival_cue].value == SEXP_KNOWN_FALSE ){
continue;
}
} else {
Int3(); // allender says bogus! reinforcement should be here since it wasn't a wing!
continue;
}
}
count++;
}
return count;
}
// function to put up window in upper right to allow for player to select the type
// of entity to select for a message (i.e. a wing or a ship)
void hud_squadmsg_type_select( )
{
int k, i;
First_menu_item = 0;
// Add the items
for (i=0; i<NUM_TYPE_SELECT; i++ ) {
strcpy( MsgItems[i].text, type_select_str(i) );
MsgItems[i].active = 1; // assume active
}
Num_menu_items = NUM_TYPE_SELECT;
// check to see if the players team is TEAM_TRAITOR. If so, then he is a "traitor", and will not
// be able to do anything from this menu
if ( Player_ship->team == TEAM_TRAITOR ) {
for (i = 0; i < MAX_MENU_ITEMS; i++ )
MsgItems[i].active = 0;
goto do_main_menu;
}
// based on ship counts, wing counts, shortcut active, grey out possible menu choices
if ( !hud_squadmsg_count_ships(0) )
MsgItems[TYPE_SHIP_ITEM].active = 0;
if ( !hud_squadmsg_count_wings(0) )
MsgItems[TYPE_WING_ITEM].active = 0;
// check to be sure that we have some fighters/bombers on the players team that we
// can message
if ( !hud_squadmsg_count_fighters() ){
MsgItems[TYPE_ALL_FIGHTERS_ITEM].active = 0;
}
if ((Player_ship != NULL) && !hud_squadmsg_reinforcements_available(Player_ship->team)) {
MsgItems[TYPE_REINFORCEMENT_ITEM].active = 0;
}
MsgItems[TYPE_REPAIR_REARM_ITEM].active = 1; // this item will always be available (I think)
MsgItems[TYPE_REPAIR_REARM_ABORT_ITEM].active = 0;
// AL: 10/13/97
// If the player ship communications are severely damaged, then the player
// will only be able to call for repair/rearm ships
//
// also, only allow support ship if this player is not allowed to messaage.
if ( (hud_communications_state(Player_ship) != COMM_OK) || ((Game_mode & GM_MULTIPLAYER) && !multi_can_message(Net_player)) ) {
for ( i = 0; i < MAX_MENU_ITEMS; i++ ){
MsgItems[i].active = 0;
}
MsgItems[TYPE_REPAIR_REARM_ITEM].active = 1;
}
// check to see if the player is awaiting repair or being repaired. Active the abort and inactive the repair items
// check to see if the player is scheduled to be repaired by incoming ship
if ( Ai_info[Ships[Player_obj->instance].ai_index].ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
MsgItems[TYPE_REPAIR_REARM_ITEM].active = 0;
MsgItems[TYPE_REPAIR_REARM_ABORT_ITEM].active = 1;
} else if ( mission_is_repair_scheduled(Player_obj) ) {
MsgItems[TYPE_REPAIR_REARM_ITEM].active = 0;
MsgItems[TYPE_REPAIR_REARM_ABORT_ITEM].active = 1;
}
// if no support available, can't call one in
if ( !is_support_allowed(Player_obj) ) {
MsgItems[TYPE_REPAIR_REARM_ITEM].active = 0;
MsgItems[TYPE_REPAIR_REARM_ABORT_ITEM].active = 0;
}
// de-activate the rearm/repair item if the player has a full load of missiles and
// all subsystems at full strength. We will only check if this item hasn't been marked
// inactive because of some other reason
if ( MsgItems[TYPE_REPAIR_REARM_ITEM].active ) {
if ( !hud_squadmsg_can_rearm(Player_ship) ){
MsgItems[TYPE_REPAIR_REARM_ITEM].active = 0;
}
}
// if using keyboard shortcut, these items are always inactive
if ( Msg_shortcut_command != -1 ) {
MsgItems[TYPE_REPAIR_REARM_ITEM].active = 0;
MsgItems[TYPE_REINFORCEMENT_ITEM].active = 0;
MsgItems[TYPE_REPAIR_REARM_ABORT_ITEM].active = 0;
}
do_main_menu:
hud_squadmsg_display_menu( XSTR( "Message What", 316) );
k = hud_squadmsg_get_key();
if ( k != -1 ) { // when k != -1, we have a key that associates with menu item
Assert ( k < Num_menu_items );
if ( k == TYPE_SHIP_ITEM ){
hud_squadmsg_do_mode( SM_MODE_SHIP_SELECT );
} else if ( k == TYPE_WING_ITEM ) {
hud_squadmsg_do_mode( SM_MODE_WING_SELECT );
} else if ( k == TYPE_ALL_FIGHTERS_ITEM ) {
hud_squadmsg_do_mode( SM_MODE_ALL_FIGHTERS );
}
if ( Msg_shortcut_command == -1 ) {
if ( k == TYPE_REINFORCEMENT_ITEM ) {
hud_squadmsg_do_mode( SM_MODE_REINFORCEMENTS );
player_set_next_all_alone_msg_timestamp();
} else if ( k == TYPE_REPAIR_REARM_ITEM ){
hud_squadmsg_do_mode( SM_MODE_REPAIR_REARM );
} else if ( k == TYPE_REPAIR_REARM_ABORT_ITEM ) {
hud_squadmsg_do_mode( SM_MODE_REPAIR_REARM_ABORT );
}
}
}
}
// function to display a list of ships to send a command to
void hud_squadmsg_ship_select()
{
int k;
if ( Num_menu_items == -1 ) {
Num_menu_items = 0;
hud_squadmsg_count_ships( 1 );
}
hud_squadmsg_display_menu( XSTR( "Select Ship", 317) );
k = hud_squadmsg_get_key();
if ( k != -1 ) { // if true, we have selected a ship.
if ( Msg_shortcut_command == -1 ) {
Msg_instance = MsgItems[First_menu_item + k].instance; // store the instance id in a global
hud_squadmsg_do_mode( SM_MODE_SHIP_COMMAND ); // and move to a new mode
} else {
// we must convert the Msg_shortcut_command value to a value that the message
// system normally uses to select a command. Since the menu
Assert( Msg_shortcut_command != IGNORE_TARGET_ITEM );
hud_squadmsg_send_ship_command( MsgItems[First_menu_item+k].instance, Msg_shortcut_command, 1 );
hud_squadmsg_toggle();
}
}
}
// function to display a list of ships to send a command to
void hud_squadmsg_wing_select()
{
int k;
if ( Num_menu_items == -1 ) {
Num_menu_items = 0;
hud_squadmsg_count_wings( 1 );
}
hud_squadmsg_display_menu( XSTR( "Select Wing", 318) );
k = hud_squadmsg_get_key();
if ( k != -1 ) { // if true, we have selected a ship.
if ( Msg_shortcut_command == -1 ) { // do normal menu stuff when no hoykey active
Msg_instance = MsgItems[First_menu_item + k].instance; // store the instance id in a global
hud_squadmsg_do_mode( SM_MODE_WING_COMMAND ); // and move to a new mode
} else {
Assert( Msg_shortcut_command != IGNORE_TARGET_ITEM );
hud_squadmsg_send_wing_command( MsgItems[First_menu_item+k].instance, Msg_shortcut_command, 1 );
hud_squadmsg_toggle();
}
}
}
// code which gives an order to all fighters/bombers. If there is a message shortcut active, then
// make that order apply to all fighters/bombers. Otherwise, move to the ship_command menu
void hud_squadmsg_msg_all_fighters()
{
if ( Msg_shortcut_command == -1 ) {
Msg_instance = MESSAGE_ALL_FIGHTERS;
hud_squadmsg_do_mode( SM_MODE_SHIP_COMMAND );
} else {
hud_squadmsg_send_to_all_fighters( Msg_shortcut_command );
hud_squadmsg_toggle();
}
}
// called to actually bring in a reinforcement. For single player games, always gets called.
// for multiplayer games, always called on the server side. Clients should never get here
void hud_squadmsg_call_reinforcement(int reinforcement_num, int player_num)
{
int i, delay;
reinforcements *rp;
p_object *p_objp;
rp = &Reinforcements[reinforcement_num];
// safety net mainly for multiplayer servers in case some odd data desync occurs between
// server and clients
if ( MULTIPLAYER_MASTER && (rp->num_uses == rp->uses) ) {
return;
}
// check to see if the reinforcement called was a wing.
for (i = 0; i < num_wings; i++ ) {
if ( !stricmp(rp->name, Wings[i].name) ) {
// found a wingname. Call the parse function to create all the ships in this wing
// we must set the arrival cue of the wing to true, otherwise, this won't work!!
Wings[i].flags &= ~WF_REINFORCEMENT;
Wings[i].flags |= WF_RESET_REINFORCEMENT;
// set up the arrival delay. If it is 0, then make is some random number of seconds
delay = rp->arrival_delay;
if ( delay == 0 )
delay = (int)(frand() * 3.0) + 3;
Wings[i].arrival_delay = timestamp(delay * 1000);
break;
}
}
// if we found no wing name that matched the reinforcement name, then look for a ship
// of the same name
if ( i == num_wings ) {
p_objp = mission_parse_get_arrival_ship( rp->name );
if ( p_objp ) {
// by resetting the reinforcement flag, we will allow code which normally handles arrivals
// to make this reinforcement arrive. Doing so keeps the data structures clean.
p_objp->flags &= ~P_SF_REINFORCEMENT;
// set up the arrival delay
delay = rp->arrival_delay;
if ( delay == 0 )
delay = (int)(frand() * 3.0) + 3; // between 3 and 6 seconds to arrive
p_objp->arrival_delay = timestamp(delay * 1000);
} else {
Int3(); // get allender -- I don't think that this can happen!!!!
return;
}
}
// increment the number of times this is used. Incremented here on single player and multiplayer
// server side only. Clients keep track of own count when they actually call something in.
rp->num_uses++;
// commented out on 9/9/98 because these messages simply are not used
/*
// now play a message (if there is one to play) for this reinforcement arrival. The first for loop
// determine how many messages there are to play, since the array is packet. Then, if >= 1 message
// to play, play one
for (i = 0; i < MAX_REINFORCEMENT_MESSAGES; i++ )
if ( !strlen(rp->yes_messages[i]) )
break;
//if ( i > 0 )
// message_send_to_player( rp->yes_messages[myrand() % i], rp->name, MESSAGE_PRIORITY_NORMAL, HUD_SOURCE_FRIENDLY );
*/
mission_log_add_entry(LOG_PLAYER_REINFORCEMENT, rp->name, NULL);
}
// function to display a list of reinforcements available to the player
void hud_squadmsg_reinforcement_select()
{
int i, k;
reinforcements *rp;
if ( Num_menu_items == -1 ) {
Num_menu_items = 0;
for (i = 0; i < Num_reinforcements; i++) {
rp = &Reinforcements[i];
// don't put reinforcements onto the list that have already been used up.
if ( (rp->num_uses == rp->uses) ){
continue;
}
// don't put items which are not on my team
if((Player_ship != NULL) && (ship_get_reinforcement_team(i) != Player_ship->team)){
continue;
}
Assert ( Num_menu_items < MAX_MENU_ITEMS );
strcpy( MsgItems[Num_menu_items].text, rp->name );
MsgItems[Num_menu_items].instance = i;
MsgItems[Num_menu_items].active = 0;
if ( rp->flags & RF_IS_AVAILABLE ) {
MsgItems[Num_menu_items].active = 1;
}
Num_menu_items++;
}
}
// hud_squadmsg_display_menu( "Select Reinforcement" );
hud_squadmsg_display_menu( XSTR( "Select Ship/Wing", 319) ); // AL 11-14-97: Reinforcement didn't fit, so using this for now
k = hud_squadmsg_get_key();
if (k != -1) {
int rnum;
hud_squadmsg_toggle(); // take us out of message mode
rnum = MsgItems[First_menu_item + k].instance;
// check to see if trying to call a reinforcement not yet available. If so, maybe play message, but
// definately bail
if ( MsgItems[First_menu_item + k].active == 0 ) {
return;
}
// in single player, or a multiplayer master, call in the reinforcement. Clients send a packet to the
// server
if ( MULTIPLAYER_CLIENT ) {
Reinforcements[rnum].num_uses++; // increment this variable here since clients need to maintain a valid count
send_player_order_packet(SQUAD_MSG_REINFORCEMENT, rnum, 0);
} else {
hud_squadmsg_call_reinforcement(rnum);
}
}
}
// function to display list of commands for a ship
void hud_squadmsg_ship_command()
{
int k;
int i, orders, default_orders;
// when adding ship commands, we must look at the type of ship, and what messages that
// ship allows. First, place all messages that are possible onto the menu, then
// see if messaging all ships or just one. Messaging all ships will mean all default orders
// show on comm menu.
if ( Msg_instance != MESSAGE_ALL_FIGHTERS ) {
orders = Ships[Msg_instance].orders_accepted;
default_orders = ship_get_default_orders_accepted( &Ship_info[Ships[Msg_instance].ship_info_index] );
} else {
default_orders = FIGHTER_MESSAGES;
orders = default_orders;
}
First_menu_item = 0;
Num_menu_items = 0;
for ( i = 0; i < MAX_SHIP_ORDERS; i++ ) {
// check to see if the comm order should even be added to the menu -- if so, then add it
// the order will be activated if the bit is set for the ship.
if ( default_orders & Comm_orders[i].value ) {
Assert ( Num_menu_items < MAX_MENU_ITEMS );
strcpy( MsgItems[Num_menu_items].text, comm_order_menu_text(i) );
MsgItems[Num_menu_items].instance = Comm_orders[i].value;
MsgItems[Num_menu_items].active = 0;
// check the bit to see if the command is active
if ( orders & Comm_orders[i].value )
MsgItems[Num_menu_items].active = 1;
// if the order cannot be carried out by the ship, then item should be inactive
if ( (Msg_instance != MESSAGE_ALL_FIGHTERS) && !hud_squadmsg_ship_order_valid( Msg_instance, Comm_orders[i].value ) )
MsgItems[Num_menu_items].active = 0;
// do some other checks to possibly gray out other items.
// if no target, remove any items which are associated with the players target
if ( !hud_squadmsg_is_target_order_valid(i, 0) )
MsgItems[Num_menu_items].active = 0;
// if messaging all fighters, see if we should gray out the order if no one will accept it,
// or modify the text if only some of the ships will accept it
if ( Msg_instance == MESSAGE_ALL_FIGHTERS ) {
ship_obj *so;
ship *shipp;
int partial_accept, all_accept; // value which tells us what to do with menu item
all_accept = Comm_orders[i].value;
partial_accept = 0;
for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
// don't send messge to ships not on player's team, or that are in a wing.
shipp = &Ships[Objects[so->objnum].instance];
if ( shipp->team != Player_ship->team )
continue;
// don't send message to non fighter wings
if ( !(Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) )
continue;
all_accept &= shipp->orders_accepted; // 'and'ing will either keep this bit set or zero it properly
partial_accept |= (shipp->orders_accepted & Comm_orders[i].value); // 'or'ing will tell us if at least one accepts
}
if ( !all_accept ) {
// either modify the text if a partial accept, or grey it out if no one accepts
if ( partial_accept ) {
strcat( MsgItems[Num_menu_items].text, XSTR( "(*)", 320) );
} else {
MsgItems[Num_menu_items].active = 0;
}
}
}
Num_menu_items++;
}
}
hud_squadmsg_display_menu( XSTR( "What Command", 321) );
k = hud_squadmsg_get_key();
// when we get a valid goal, we must add the goal to the ai ship's goal list
if ( k != -1 ) {
Assert ( k < Num_menu_items );
// when messaging all fighters or ignoring target, call the send_to_all_fighters routine
if ( (Msg_instance != MESSAGE_ALL_FIGHTERS) && (MsgItems[k].instance != IGNORE_TARGET_ITEM) )
hud_squadmsg_send_ship_command( Msg_instance, MsgItems[k].instance, 1 );
else
hud_squadmsg_send_to_all_fighters( MsgItems[k].instance );
hud_squadmsg_toggle();
}
}
// function to display list of command for a wing
void hud_squadmsg_wing_command()
{
int k;
wing *wingp;
int default_orders, i, orders;
// when adding commands for wings, we will look at all of the ships in the wing, and create
// the order list from that set of ships. In the future, we may want to do something else....
wingp = &Wings[Msg_instance];
// or together all of the orders for all the ships in the wing
default_orders = 0;
for ( i = 0; i < wingp->current_count; i++ ) {
orders = ship_get_default_orders_accepted( &Ship_info[Ships[wingp->ship_index[i]].ship_info_index] );
default_orders |= orders;
}
default_orders &= ~CAPTURE_TARGET_ITEM; // we cannot capture any target with a wing.
Num_menu_items = 0;
orders = Ships[wingp->ship_index[0]].orders_accepted; // get the orders that the first ship in the wing will accept
for ( i = 0; i < MAX_SHIP_ORDERS; i++ ) {
// add the set of default orders to the comm menu. We will currently allow all messages
// to be available in the wing.
if ( default_orders & Comm_orders[i].value ) {
Assert ( Num_menu_items < MAX_MENU_ITEMS );
strcpy( MsgItems[Num_menu_items].text, comm_order_menu_text(i) );
MsgItems[Num_menu_items].instance = Comm_orders[i].value;
MsgItems[Num_menu_items].active = 0;
// possibly grey out the menu item depending on whether or not the "wing" will accept this order
// the "wing" won't accept the order if the first ship in the wing doesn't accept it.
if ( orders & Comm_orders[i].value )
MsgItems[Num_menu_items].active = 1;
// do some other checks to possibly gray out other items.
// if no target, remove any items which are associated with the players target
if ( !hud_squadmsg_is_target_order_valid(i, 0) )
MsgItems[Num_menu_items].active = 0;
Num_menu_items++;
}
}
hud_squadmsg_display_menu( XSTR( "What Command", 321) );
k = hud_squadmsg_get_key();
if ( k != -1 ) {
// ignore target gets sent to everyone.
if ( MsgItems[k].instance != IGNORE_TARGET_ITEM )
hud_squadmsg_send_wing_command( Msg_instance, MsgItems[k].instance, 1 );
else
hud_squadmsg_send_to_all_fighters( MsgItems[k].instance );
hud_squadmsg_toggle();
}
}
//----------------------------------------------------------
// external entry points below!!!!
// when starting messaging mode, we must remove old bindings from the
// keys that are used for messaging mode (which will get restored when
// messaging mode is done).
// this code below will get called only the key config changes (from ControlsConfig.cpp)
// or if the bindings haven't been saved yet. This code doesn't remove the bindings
// but just sets up the array so that the bindings can be removed when messaging
// mode is entered.
//
// do_scroll indicates whether we should save the page up and page down keys
void hud_squadmsg_save_keys( int do_scroll )
{
// int i, j;
num_keys_saved = 0;
/*
for ( j=0; j<MAX_KEYS_USED; j++ ) {
for ( i=0; Control_config[i].text[0]; i++ ) { // the text field in this structure is empty at the end of the config list
if ( Control_config[i].key_id == keys_used[j] ) { // this is true if we have a match
// if we are not saving scrolling keys and we are trying to match page up and page down
// then skip them.
if ( !do_scroll && ((keys_used[j] == KEY_PAGEDOWN) || (keys_used[j] == KEY_PAGEUP)) )
continue;
Assert( num_keys_saved < MAX_KEYS_USED );
key_save[num_keys_saved].option_num = i;
key_save[num_keys_saved].key_value = keys_used[j];
num_keys_saved++;
break; // done with this key -- move to next.
}
}
}
*/
}
// function is called once per mission start. Initializes those values
// which only need to be inited once per mission.
void hud_init_squadmsg( void )
{
int i;
if ( !Mbox_frames_loaded ) {
for ( i = 0; i < NUM_MBOX_FRAMES; i++ ) {
Mbox_gauge[i].first_frame = bm_load_animation(Mbox_fnames[gr_screen.res][i], &Mbox_gauge[i].num_frames);
if ( Mbox_gauge[i].first_frame == -1 ) {
Warning(LOCATION, "Could not load in ani: %s\n", Mbox_fnames[gr_screen.res][i]);
return;
}
}
Mbox_frames_loaded = 1;
}
Msg_eat_key_timestamp = timestamp(0);
}
// external entry point into code which changes the messaging mode based on the
// previous player flag value. I thought it better to isolate all system changes
// in this code.
void hud_squadmsg_toggle()
{
// if the emp effect is active, always ignore this
if(emp_active_local()){
return;
}
// if entering this mode, must setup messaging system. Don't start squadmessging if
// the player is dead.
if ( !(Player->flags & PLAYER_FLAGS_MSG_MODE) ) {
if ( Game_mode & GM_DEAD ){
return;
}
if ( (Game_mode & GM_MULTIPLAYER) && NETPLAYER_IS_OBSERVER(Net_player) ){
return;
}
hud_squadmsg_start();
} else {
hud_squadmsg_end();
}
Player->flags ^= PLAYER_FLAGS_MSG_MODE;
}
//#ifndef NDEBUG
// extern entry point to allow messaging of enemies
void hud_enemymsg_toggle()
{
hud_squadmsg_toggle();
// if we just entered message mode, turn on var that says to message enemies
if ( Player->flags & PLAYER_FLAGS_MSG_MODE )
Msg_enemies = 1;
}
//#endif
// external entry point into code when a keyboard shortcut is used for a command
// we are passed in an ID for the command to set internal variables. This command
// will be used in place of the last menu in the messaging code
void hud_squadmsg_shortcut( int command )
{
// check if the communications system is capable of sending a message
if ( (hud_communications_state(Player_ship, 1) != COMM_OK) && (command != REARM_REPAIR_ME_ITEM) ) {
return;
}
// observers in multiplayer games cannot have this active either
if ( (Game_mode & GM_MULTIPLAYER) && NETPLAYER_IS_OBSERVER(Net_player) )
return;
// in multiplayer and I cannot message, don't allow anything except calling in for rearm
if ( (Game_mode & GM_MULTIPLAYER) && !multi_can_message(Net_player) && (command != REARM_REPAIR_ME_ITEM) )
gamesnd_play_error_beep();
// player ships which turns traitor cannot rearm
if ( Player_ship->team == TEAM_TRAITOR )
return;
if ( Player->flags & PLAYER_FLAGS_MSG_MODE ) // we are already in messaging mode -- maybe do sometime more interesting?
return;
hud_squadmsg_toggle();
Msg_shortcut_command = command; // save the command for later use
if ( Msg_shortcut_command == CAPTURE_TARGET_ITEM ) // some commands only apply to wings or ships
Squad_msg_mode = SM_MODE_SHIP_SELECT; // -- don't offer choice
else if ( Msg_shortcut_command == IGNORE_TARGET_ITEM ) { // ignoring target applied to all ships
hud_squadmsg_toggle(); // turns off mode which was turned on above
hud_squadmsg_send_to_all_fighters( Msg_shortcut_command );
}
}
// external entry point which is called when the player hits a selection key (1-0) while in messaging
// mode. If we are in messaging mode, send the shortcut command to the ships that are part of the
// passed in selection set. If there is no shortcut command, do nothing. Returns 1 if the key
// was used, else 0. This return value is used to tell the key control system that it should
// call the normal targeting selection stuff.
int hud_squadmsg_hotkey_select( int k )
{
htarget_list *hitem, *plist;
int send_message;
object *objp;
Assert ( Player->flags & PLAYER_FLAGS_MSG_MODE );
if ( Msg_shortcut_command == -1 )
return 0;
Assert ( (k >= 0) && (k < MAX_KEYED_TARGETS) );
plist = &(Player->keyed_targets[k]);
if ( EMPTY(plist) ) // be sure that we have at least one ship in the list
return 0;
send_message = 1;
// for each ship in the selection set list, send the shortcut command that the player
// previously entered. Be sure to check that we are not trying to send a command to
// an enemy ship.
for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) {
objp = hitem->objp;
Assert ( objp->type == OBJ_SHIP );
if ( Ships[objp->instance].team != TEAM_FRIENDLY )
continue;
// be sure that this ship can accept this command
if ( !(Msg_shortcut_command, Ships[objp->instance].orders_accepted) )
continue;
hud_squadmsg_send_ship_command( objp->instance, Msg_shortcut_command, send_message );
send_message = 0;
}
hud_squadmsg_toggle(); // turn off messaging mode
return 1;
}
// the next function is called once a frame when the player is messaging someone
// in his squad. After a period of 5 seconds of inactivity (i.e. no keypress to
// select something in the menu), the menu will disappear. This function will only
// get called if the player flag PLAYER_FLAG_MSG_MODE is set. Parameter is the key
// that was hit this frame
int hud_squadmsg_do_frame( )
{
int target_changed;
Assert ( Player->flags & PLAYER_FLAGS_MSG_MODE ); // be sure that messaging mode is set!!!
// if the player is now dead, or the timestamp elapsed, then get out of messaging mode.
if ( (Game_mode & GM_DEAD) || timestamp_elapsed(Msg_mode_timestamp) ) {
hud_squadmsg_toggle();
return 0;
}
Msg_key_used = 0;
// check the player's current target. Change in target resets the timer
target_changed = 0;
if ( Msg_target_objnum != Player_ai->target_objnum ) {
Msg_target_objnum = Player_ai->target_objnum;
target_changed = 1;
}
if ( Msg_targeted_subsys != Player_ai->targeted_subsys ) {
Msg_targeted_subsys = Player_ai->targeted_subsys;
target_changed = 1;
}
// setup color/font info
// hud_set_default_color();
hud_set_gauge_color(HUD_MESSAGE_BOX);
// check for multiplayer mode - this is really a special case checker for support ship requesting and aborting
if((Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER) && (Squad_msg_mode == SM_MODE_REPAIR_REARM || Squad_msg_mode == SM_MODE_REPAIR_REARM_ABORT)){
char *subsys_name;
// int who_to_sig;
ushort net_sig;
// who_to_sig = Objects[Ships[shipnum].objnum].net_signature;
if(Player_ai->target_objnum != -1)
net_sig = Objects[Player_ai->target_objnum].net_signature;
else
net_sig = 0;
if ((Player_ai->targeted_subsys != NULL) && (Player_ai->targeted_subsys->current_hits > 0.0f))
subsys_name = Player_ai->targeted_subsys->system_info->subobj_name;
else
subsys_name = NULL;
// send the correct packet
if(Squad_msg_mode == SM_MODE_REPAIR_REARM)
send_player_order_packet(SQUAD_MSG_SHIP, 0, REARM_REPAIR_ME_ITEM);
else
send_player_order_packet(SQUAD_MSG_SHIP, 0, ABORT_REARM_REPAIR_ITEM);
// make sure to toggle the mode off
hud_squadmsg_toggle();
return 1;
}
// draw top of frame
if ( Mbox_gauge[0].first_frame >= 0 ) {
GR_AABITMAP(Mbox_gauge[0].first_frame, Mbox_top_coords[gr_screen.res][0], Mbox_top_coords[gr_screen.res][1]);
}
switch( Squad_msg_mode ) {
case SM_MODE_TYPE_SELECT:
hud_squadmsg_type_select();
break;
case SM_MODE_SHIP_SELECT:
hud_squadmsg_ship_select();
break;
case SM_MODE_WING_SELECT:
hud_squadmsg_wing_select();
break;
case SM_MODE_SHIP_COMMAND:
hud_squadmsg_ship_command();
break;
case SM_MODE_WING_COMMAND:
hud_squadmsg_wing_command();
break;
case SM_MODE_REINFORCEMENTS:
hud_squadmsg_reinforcement_select();
break;
case SM_MODE_REPAIR_REARM:
//if((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (addr != NULL)){
// hud_squadmsg_repair_rearm(1,&Objects[Net_players[player_num].player->objnum]);
//} else {
hud_squadmsg_repair_rearm(1); // note we return right away. repair/rearm code handles messaging, etc
//}
break;
case SM_MODE_REPAIR_REARM_ABORT:
//if((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (addr != NULL)){
// hud_squadmsg_repair_rearm_abort(1,&Objects[Net_players[player_num].player->objnum]);
//} else {
hud_squadmsg_repair_rearm_abort(1); // note we return right away. repair/rearm code handles messaging, etc
//}
break;
case SM_MODE_ALL_FIGHTERS:
hud_squadmsg_msg_all_fighters();
break;
default:
Int3(); // get allender -- invalid mode in messaging system
break;
}
// be sure to reset the clip region
HUD_reset_clip(); // JAS: Is this needed?
if ( Msg_key_used || target_changed ) {
Msg_mode_timestamp = timestamp(DEFAULT_MSG_TIMEOUT);
return 1;
} else
return 0;
}
void hud_add_issued_order(char *name, int order, char *target)
{
Squadmsg_history[squadmsg_history_index].ship = get_parse_name_index(name);
Squadmsg_history[squadmsg_history_index].order = order;
if (target)
Squadmsg_history[squadmsg_history_index].target = get_parse_name_index(target);
else
Squadmsg_history[squadmsg_history_index].target = -1;
squadmsg_history_index++;
if (squadmsg_history_index >= SQUADMSG_HISTORY_MAX)
squadmsg_history_index = 0;
}
int hud_query_order_issued(char *name, char *order, char *target)
{
int i, o=-1, ship, t;
ship = get_parse_name_index(name);
t = -1;
if (target)
t = get_parse_name_index(target);
for (i=0; i<MAX_SHIP_ORDERS; i++)
if (!stricmp(order, comm_order_menu_text(i)) )
o = Comm_orders[i].value;
Assert(i < MAX_SHIP_ORDERS);
for (i=0; i<SQUADMSG_HISTORY_MAX; i++)
if (Squadmsg_history[i].order == o)
if (ship == Squadmsg_history[i].ship)
if (Squadmsg_history[i].target == t)
return 1;
return 0;
}
void hudsquadmsg_page_in()
{
int i;
for ( i = 0; i < NUM_MBOX_FRAMES; i++ ) {
bm_page_in_aabitmap( Mbox_gauge[i].first_frame, Mbox_gauge[i].num_frames );
}
}
| [
"[email protected]"
] | |
27c0f89cb2759ff4ac0f7edc2406aecfcdeefb80 | 34874bfaa7656dcc74c954ee9cd96570a39d2853 | /tutorials/Classes/SwapDemo4.cpp | 495ca0d31a026d2b81fa8777aa4191d9d3365bb3 | [] | no_license | venkatarajasekhar/c- | 90256c0d8e89f96832fbcbe3a1f61bca79897948 | 9dc946b06cc20b07d8526ef22f55703a3cdd2989 | refs/heads/master | 2021-01-12T10:32:27.298879 | 2016-05-31T17:15:58 | 2016-05-31T17:15:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | #include<iostream>
using namespace std;
class A
{
int x,y;
public:
void init(int _x,int _y)
{
x = _x;
y = _y;
}
void setX(int _x)
{
x = _x;
}
int getX()
{
return x;
}
void setY(int _y)
{
y = _y;
}
int getY()
{
return y;
}
void show()
{
cout<<x<<"\t"<<y<<endl;
}
};
class B
{
int x,y;
public:
void init(int _x,int _y)
{
x = _x;
y = _y;
}
void setX(int _x)
{
x = _x;
}
int getX()
{
return x;
}
void setY(int _y)
{
y = _y;
}
int getY()
{
return y;
}
void show()
{
cout<<x<<"\t"<<y<<endl;
}
};
void swapValues(int& a,int& b)
{
int temp = a;
a = b;
b = temp;
}
void swap(A& a,B& b)
{
int temp;
temp = a.getX();
a.setX(b.getX());
b.setX(temp);
temp = a.getY();
a.setY(b.getY());
b.setY(temp);
// Error
// swapValues(a.getX(),b.getX());
// swapValues(a.getY(),b.getY());
}
int main()
{
A a;
B b;
a.init(10,20);
b.init(30,40);
cout<<"Before swapping"<<endl;
a.show();
b.show();
swap(a,b);
cout<<"After swapping"<<endl;
a.show();
b.show();
}
| [
"[email protected]"
] | |
40e2d6cf5ed4e5df3d628a41ca4f9f615d93983d | 3448a43cf0635866b25e5d513dd60fb003f47e29 | /src/xrGame/Script_SE_Lamp.h | da56cb423da4cf4f073c30c6fd8619729ac659ae | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | xrLil-Batya/cordisproject | 49632acc5e68bea9847d001d82fb049703d223c2 | 24275a382fec62a4e58d11579bf497b894f220ba | refs/heads/master | 2023-03-19T01:17:25.170059 | 2020-11-17T14:22:06 | 2020-11-17T14:22:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | h | #pragma once
namespace Cordis
{
namespace Scripts
{
class Script_SE_Lamp : public CSE_ALifeObjectHangingLamp
{
using inherited = CSE_ALifeObjectHangingLamp;
public:
Script_SE_Lamp(LPCSTR section_name);
virtual ~Script_SE_Lamp(void);
virtual void on_register(void);
virtual void on_unregister(void);
virtual bool can_switch_online(void) const;
private:
bool m_is_secret_item;
};
} // namespace Scripts
} // namespace Cordis
| [
"[email protected]"
] | |
2e5668df9cca1da0972e2cdd2911daede007e91b | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_repos_function_2304_last_repos.cpp | 0362dc2bdf016b485e22dea3ae6b77f0d7c37b2c | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 211 | cpp | static int iindex_of(h2_ififo *fifo, int id)
{
int i;
for (i = 0; i < fifo->count; ++i) {
if (id == fifo->elems[inth_index(fifo, i)]) {
return i;
}
}
return -1;
} | [
"[email protected]"
] | |
42360717be27e29f59a8c332557116cd799aecde | 0d4f1eeb722b0e49b00142fa56a047610dc4f670 | /C++/Reference/성적프로그램_SingleTon/성적프로그램/Main/MainMananger.cpp | 9cd03294f92606c2750485534ee6bd8c7db2e736 | [] | no_license | KimWoongwon/2A_TOTAL | 23059d717442f4df257b3eca762afcf024286a6c | 21f58798c5a08ce648ecb75d1e45ff22ab01afa8 | refs/heads/master | 2022-11-24T10:03:01.411097 | 2020-08-04T07:32:09 | 2020-08-04T07:32:09 | 276,353,062 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,472 | cpp | #include "MainManager.h"
CMainManager* CMainManager::mPthis = nullptr;
void CMainManager::Create()
{
if (!mPthis)
{
mPthis = new CMainManager();
}
CProgrammingManager::Create();
CGraphicManager::Create();
CDesignManager::Create();
CDataBaseManager::Create();
}
CMainManager* CMainManager::GetInstance()
{
return mPthis;
}
void CMainManager::Destroy()
{
CProgrammingManager::Destroy();
CGraphicManager::Destroy();
CDesignManager::Destroy();
CDataBaseManager::Destroy();
if (mPthis)
{
delete mPthis;
mPthis = nullptr;
}
}
CMainManager::CMainManager()
{
}
void CMainManager::Initialize()
{
CProgrammingManager::GetInstance()->Initialize();
CGraphicManager::GetInstance()->Initialize();
CDesignManager::GetInstance()->Initialize();
CDataBaseManager::GetInstance()->Initialize();
}
CMainManager::~CMainManager()
{
}
int CMainManager::SelectMainMenu()
{
int select;
while (1)
{
cout << "<성적프로그램>" << endl;
cout << "1.성적입력" << endl;
cout << "2.삭제" << endl;
cout << "3.성적출력" << endl;
cout << "4.성적조회" << endl;
cout << "5.종료" << endl;
cout << "선택:";
cin >> select;
rewind(stdin);
if (select < INPUT || select > EXIT)
{
cout << "잘못 입력했습니다." << endl;
continue;
}
break;
}
return select;
}
CManager* CMainManager::MajorSelect(const char* _title)
{
int select;
while (1)
{
cout << _title << endl;
cout << "(프로그래밍:1, 그래픽:2, 기획:3)" << endl;
cout << "선택:";
int select;
cin >> select;
switch (select)
{
case PROGRAMMING:
return CProgrammingManager::GetInstance();
break;
case GRAPHIC:
return CGraphicManager::GetInstance();
break;
case DESIGN:
return CDesignManager::GetInstance();
break;
default:
cout << "잘못 입력했습니다." << endl;
continue;
}
break;
}
}
void CMainManager::Run()
{
CManager* manager = nullptr;
while (1)
{
int select=SelectMainMenu();
switch (select)
{
case INPUT:
manager = MajorSelect("<<성적입력>>");
manager->Input();
break;
case DELETE:
manager = MajorSelect("<<성적입력>>");
manager->Delete();
break;
case SHOWDATA:
manager = MajorSelect("<<성적출력>>");
manager->Display();
break;
case SEARCHDATA:
manager->Search();
break;
case EXIT:
return;
break;
default:
cout << "잘못 입력했습니다 다시 입력하세요 " << endl;
}
}
} | [
"[email protected]"
] | |
752e9571f81a96675688047fdc64bb30df386f0f | 6ed60cf2295a3399201c9b675946c035542a3118 | /src/regexp.cc | 143301f39ede87bf2ef8585eaa767a7e88ddf6bf | [] | no_license | scsmithr/Frankenruma | 1ae649f2af58493a11e59d46b9920ce90ea39358 | 884848731ea6b8c0749708fe189ff74378b80fc3 | refs/heads/master | 2021-07-19T17:58:56.005291 | 2017-10-23T19:05:04 | 2017-10-23T19:05:04 | 107,917,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | cc | #include "regexp.h"
#include <emscripten.h>
using std::string;
Regexp::Regexp(const string& str) {
UChar *c_str = (UChar*)str.c_str();
UChar *pattern_end = c_str + onigenc_str_bytelen_null(ONIG_ENCODING_UTF8, c_str);
int status = onig_new(®ex_, (UChar*)c_str, pattern_end, ONIG_OPTION_CAPTURE_GROUP, ONIG_ENCODING_UTF8, ONIG_SYNTAX_DEFAULT, NULL);
if (status != ONIG_NORMAL) {
EM_ASM(throw 'unable to build regexp');
return;
}
}
Regexp::~Regexp() {
if (regex_ != NULL) {
onig_free(regex_);
}
} | [
"[email protected]"
] | |
84c8fee65d931f90880ce0a450b734437cb28db7 | d0e77bdcff50980e659b6f1e54cae0fbf20f69ea | /Lab 7/tree.cpp | 024f4ff10fb5ae57f8a5df9f95473e473d5edf48 | [] | no_license | JoePowers5/CSCI-2270 | 0d88aa386ba34499ca3c04ef57eeba9bca91e7ba | 83ad80d5d0816095dbb18756c92d5d27c914054c | refs/heads/master | 2022-04-08T06:37:43.289723 | 2019-04-15T19:05:43 | 2019-04-15T19:05:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,615 | cpp | #include <iostream>
#include "tree.hpp"
using namespace std;
#define COUNT 10
/*
Constructor for a Tree object
*/
Tree::Tree()
{
this->root = NULL;
}
/*
Prints a binary tree in a 2D fashion.
Note: The image of the tree is left rotated by 90 degrees.
*/
void Tree::print2DUtil(Node *root, int space)
{
// Base case
if (root == NULL)
return;
// Increase distance between levels
space += COUNT;
// Process right child first
print2DUtil(root->right, space);
// Print current node after space
// count
printf("\n");
for (int i = COUNT; i < space; i++)
printf(" ");
printf("%d\n", root->data);
// Process left child
print2DUtil(root->left, space);
}
void Tree::preOrderTraverse(Node *node)
{
if (node == NULL)
return;
/* first print data of node */
cout << node->data << " ";
/* then recur on left sutree */
preOrderTraverse(node->left);
/* now recur on right subtree */
preOrderTraverse(node->right);
}
/*
***************************************************************************
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Implement this function
This function deletes all the nodes in the tree
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
***************************************************************************
*/
void Tree::deleteTree(Node *node)
{
if (node == NULL) return;
deleteTree(node->left);
deleteTree(node->right);
/* TODO then delete the node */
cout<<"\n Deleting node:"<< node->data;
}
/*
***************************************************************************
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Implement this function
This function gives the sum of all the nodes in the tree
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
***************************************************************************
*/
int Tree::sumNodes(Node *node)
{
if (node == nullptr)
{
return 0;
}
else
{
return node->data + sumNodes(node->left) + sumNodes(node->right);
}
return 0;
}
/*
Creates a tree of 7 elements
*/
void Tree::createTree()
{
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
this->root = root;
}
| [
"[email protected]"
] | |
fed4a5b8ab6aa23794962960573bc8a041ef0b8b | 0fe0ffe29ca6f76c6f15c85c8d82b09beaada246 | /net/quic/core/quic_headers_stream_test.cc | 00fd09d91b4769ed2aac599499f8b7215d4b35d7 | [] | no_license | hanpfei/chromium-net | 4dc8fd48cf3b05d89b11dc121f9c3abdd3ba962e | 9df8ce98c2a14fb60c2f581853011e32eb4bed0f | refs/heads/master | 2023-07-08T15:28:01.033104 | 2023-06-14T13:02:39 | 2023-06-14T13:02:39 | 65,541,033 | 297 | 73 | null | 2022-11-02T23:33:48 | 2016-08-12T09:25:34 | C++ | UTF-8 | C++ | false | false | 38,403 | cc | // Copyright 2013 The Chromium 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 "net/quic/core/quic_headers_stream.h"
#include <string>
#include "base/strings/string_number_conversions.h"
#include "net/quic/core/quic_bug_tracker.h"
#include "net/quic/core/quic_utils.h"
#include "net/quic/core/spdy_utils.h"
#include "net/quic/test_tools/quic_connection_peer.h"
#include "net/quic/test_tools/quic_headers_stream_peer.h"
#include "net/quic/test_tools/quic_spdy_session_peer.h"
#include "net/quic/test_tools/quic_test_utils.h"
#include "net/quic/test_tools/reliable_quic_stream_peer.h"
#include "net/spdy/spdy_alt_svc_wire_format.h"
#include "net/spdy/spdy_flags.h"
#include "net/spdy/spdy_protocol.h"
#include "net/spdy/spdy_test_utils.h"
#include "net/test/gtest_util.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::StringPiece;
using std::ostream;
using std::string;
using std::vector;
using testing::ElementsAre;
using testing::_;
using testing::AtLeast;
using testing::HasSubstr;
using testing::InSequence;
using testing::Invoke;
using testing::Return;
using testing::StrictMock;
using testing::WithArgs;
using testing::_;
// TODO(bnc): Merge these correctly.
bool FLAGS_use_http2_frame_decoder_adapter;
bool FLAGS_spdy_use_hpack_decoder2;
bool FLAGS_spdy_framer_use_new_methods2;
namespace net {
namespace test {
class MockHpackDebugVisitor : public QuicHeadersStream::HpackDebugVisitor {
public:
explicit MockHpackDebugVisitor() : HpackDebugVisitor() {}
MOCK_METHOD1(OnUseEntry, void(QuicTime::Delta elapsed));
private:
DISALLOW_COPY_AND_ASSIGN(MockHpackDebugVisitor);
};
namespace {
// TODO(ckrasic): this workaround is due to absence of std::initializer_list
const bool kFins[] = {false, true};
class MockVisitor : public SpdyFramerVisitorInterface {
public:
MOCK_METHOD1(OnError, void(SpdyFramer* framer));
MOCK_METHOD3(OnDataFrameHeader,
void(SpdyStreamId stream_id, size_t length, bool fin));
MOCK_METHOD3(OnStreamFrameData,
void(SpdyStreamId stream_id, const char* data, size_t len));
MOCK_METHOD1(OnStreamEnd, void(SpdyStreamId stream_id));
MOCK_METHOD2(OnStreamPadding, void(SpdyStreamId stream_id, size_t len));
MOCK_METHOD1(OnHeaderFrameStart,
SpdyHeadersHandlerInterface*(SpdyStreamId stream_id));
MOCK_METHOD2(OnHeaderFrameEnd, void(SpdyStreamId stream_id, bool end));
MOCK_METHOD3(OnControlFrameHeaderData,
bool(SpdyStreamId stream_id,
const char* header_data,
size_t len));
MOCK_METHOD5(OnSynStream,
void(SpdyStreamId stream_id,
SpdyStreamId associated_stream_id,
SpdyPriority priority,
bool fin,
bool unidirectional));
MOCK_METHOD2(OnSynReply, void(SpdyStreamId stream_id, bool fin));
MOCK_METHOD2(OnRstStream,
void(SpdyStreamId stream_id, SpdyRstStreamStatus status));
MOCK_METHOD1(OnSettings, void(bool clear_persisted));
MOCK_METHOD3(OnSetting,
void(SpdySettingsIds id, uint8_t flags, uint32_t value));
MOCK_METHOD0(OnSettingsAck, void());
MOCK_METHOD0(OnSettingsEnd, void());
MOCK_METHOD2(OnPing, void(SpdyPingId unique_id, bool is_ack));
MOCK_METHOD2(OnGoAway,
void(SpdyStreamId last_accepted_stream_id,
SpdyGoAwayStatus status));
MOCK_METHOD7(OnHeaders,
void(SpdyStreamId stream_id,
bool has_priority,
int weight,
SpdyStreamId parent_stream_id,
bool exclusive,
bool fin,
bool end));
MOCK_METHOD2(OnWindowUpdate,
void(SpdyStreamId stream_id, int delta_window_size));
MOCK_METHOD1(OnBlocked, void(SpdyStreamId stream_id));
MOCK_METHOD3(OnPushPromise,
void(SpdyStreamId stream_id,
SpdyStreamId promised_stream_id,
bool end));
MOCK_METHOD2(OnContinuation, void(SpdyStreamId stream_id, bool end));
MOCK_METHOD4(OnPriority,
void(SpdyStreamId stream_id,
SpdyStreamId parent_id,
int weight,
bool exclusive));
MOCK_METHOD3(OnAltSvc,
void(SpdyStreamId stream_id,
StringPiece origin,
const SpdyAltSvcWireFormat::AlternativeServiceVector&
altsvc_vector));
MOCK_METHOD2(OnUnknownFrame, bool(SpdyStreamId stream_id, int frame_type));
};
class ForceHolAckListener : public QuicAckListenerInterface {
public:
ForceHolAckListener() : total_acked_bytes_(0) {}
void OnPacketAcked(int acked_bytes, QuicTime::Delta ack_delay_time) override {
total_acked_bytes_ += acked_bytes;
}
void OnPacketRetransmitted(int retransmitted_bytes) override {}
size_t total_acked_bytes() { return total_acked_bytes_; }
private:
~ForceHolAckListener() override {}
size_t total_acked_bytes_;
DISALLOW_COPY_AND_ASSIGN(ForceHolAckListener);
};
enum Http2DecoderChoice {
HTTP2_DECODER_SPDY,
HTTP2_DECODER_NESTED_SPDY,
HTTP2_DECODER_NEW
};
ostream& operator<<(ostream& os, Http2DecoderChoice v) {
switch (v) {
case HTTP2_DECODER_SPDY:
return os << "SPDY";
case HTTP2_DECODER_NESTED_SPDY:
return os << "NESTED_SPDY";
case HTTP2_DECODER_NEW:
return os << "NEW";
}
return os;
}
enum HpackDecoderChoice { HPACK_DECODER_SPDY, HPACK_DECODER_NEW };
ostream& operator<<(ostream& os, HpackDecoderChoice v) {
switch (v) {
case HPACK_DECODER_SPDY:
return os << "SPDY";
case HPACK_DECODER_NEW:
return os << "NEW";
}
return os;
}
typedef std::
tuple<QuicVersion, Perspective, Http2DecoderChoice, HpackDecoderChoice>
TestParamsTuple;
struct TestParams {
explicit TestParams(TestParamsTuple params)
: version(std::get<0>(params)),
perspective(std::get<1>(params)),
http2_decoder(std::get<2>(params)),
hpack_decoder(std::get<3>(params)) {
switch (http2_decoder) {
case HTTP2_DECODER_SPDY:
FLAGS_use_nested_spdy_framer_decoder = false;
FLAGS_use_http2_frame_decoder_adapter = false;
break;
case HTTP2_DECODER_NESTED_SPDY:
FLAGS_use_nested_spdy_framer_decoder = true;
FLAGS_use_http2_frame_decoder_adapter = false;
break;
case HTTP2_DECODER_NEW:
FLAGS_use_nested_spdy_framer_decoder = false;
FLAGS_use_http2_frame_decoder_adapter = true;
// Http2FrameDecoderAdapter needs the new header methods, else
// --use_http2_frame_decoder_adapter=true will be ignored.
FLAGS_spdy_framer_use_new_methods2 = true;
break;
}
switch (hpack_decoder) {
case HPACK_DECODER_SPDY:
FLAGS_spdy_use_hpack_decoder2 = false;
break;
case HPACK_DECODER_NEW:
FLAGS_spdy_use_hpack_decoder2 = true;
// Needs new header methods to be used.
FLAGS_spdy_framer_use_new_methods2 = true;
break;
}
FLAGS_quic_always_log_bugs_for_tests = true;
VLOG(1) << "TestParams: version: " << QuicVersionToString(version)
<< ", perspective: " << perspective
<< ", http2_decoder: " << http2_decoder
<< ", hpack_decoder: " << hpack_decoder;
}
QuicVersion version;
Perspective perspective;
Http2DecoderChoice http2_decoder;
HpackDecoderChoice hpack_decoder;
};
class QuicHeadersStreamTest : public ::testing::TestWithParam<TestParamsTuple> {
public:
// Constructing the test_params_ object will set the necessary flags before
// the MockQuicConnection is constructed, which we need because the latter
// will construct a SpdyFramer that will use those flags to decide whether
// to construct a decoder adapter.
QuicHeadersStreamTest()
: test_params_(GetParam()),
connection_(new StrictMock<MockQuicConnection>(&helper_,
&alarm_factory_,
perspective(),
GetVersion())),
session_(connection_),
headers_stream_(QuicSpdySessionPeer::GetHeadersStream(&session_)),
body_("hello world"),
hpack_encoder_visitor_(new StrictMock<MockHpackDebugVisitor>),
hpack_decoder_visitor_(new StrictMock<MockHpackDebugVisitor>),
stream_frame_(kHeadersStreamId, /*fin=*/false, /*offset=*/0, ""),
next_promised_stream_id_(2) {
headers_[":version"] = "HTTP/1.1";
headers_[":status"] = "200 Ok";
headers_["content-length"] = "11";
framer_ = std::unique_ptr<SpdyFramer>(new SpdyFramer(HTTP2));
framer_->set_visitor(&visitor_);
EXPECT_EQ(version(), session_.connection()->version());
EXPECT_TRUE(headers_stream_ != nullptr);
connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
}
QuicConsumedData SaveIov(const QuicIOVector& data) {
const iovec* iov = data.iov;
int count = data.iov_count;
int consumed = 0;
for (int i = 0; i < count; ++i) {
saved_data_.append(static_cast<char*>(iov[i].iov_base), iov[i].iov_len);
consumed += iov[i].iov_len;
}
return QuicConsumedData(consumed, false);
}
QuicConsumedData SaveIovAndNotifyAckListener(
const QuicIOVector& data,
QuicAckListenerInterface* ack_listener) {
QuicConsumedData result = SaveIov(data);
if (ack_listener) {
ack_listener->OnPacketAcked(result.bytes_consumed,
QuicTime::Delta::Zero());
}
return result;
}
void SavePayload(const char* data, size_t len) {
saved_payloads_.append(data, len);
}
bool SaveHeaderData(const char* data, int len) {
saved_header_data_.append(data, len);
return true;
}
void SaveHeaderDataStringPiece(StringPiece data) {
saved_header_data_.append(data.data(), data.length());
}
void SavePromiseHeaderList(QuicStreamId /* stream_id */,
QuicStreamId /* promised_stream_id */,
size_t size,
const QuicHeaderList& header_list) {
SaveToHandler(size, header_list);
}
void SaveHeaderList(QuicStreamId /* stream_id */,
bool /* fin */,
size_t size,
const QuicHeaderList& header_list) {
SaveToHandler(size, header_list);
}
void SaveToHandler(size_t size, const QuicHeaderList& header_list) {
headers_handler_.reset(new TestHeadersHandler);
headers_handler_->OnHeaderBlockStart();
for (const auto& p : header_list) {
headers_handler_->OnHeader(p.first, p.second);
}
headers_handler_->OnHeaderBlockEnd(size);
}
void WriteHeadersAndExpectSynStream(QuicStreamId stream_id,
bool fin,
SpdyPriority priority) {
WriteHeadersAndCheckData(stream_id, fin, priority, SYN_STREAM);
}
void WriteHeadersAndExpectSynReply(QuicStreamId stream_id, bool fin) {
WriteHeadersAndCheckData(stream_id, fin, 0, SYN_REPLY);
}
void WriteHeadersAndCheckData(QuicStreamId stream_id,
bool fin,
SpdyPriority priority,
SpdyFrameType type) {
// Write the headers and capture the outgoing data
EXPECT_CALL(session_, WritevData(headers_stream_, kHeadersStreamId, _, _,
false, nullptr))
.WillOnce(WithArgs<2>(Invoke(this, &QuicHeadersStreamTest::SaveIov)));
headers_stream_->WriteHeaders(stream_id, headers_.Clone(), fin, priority,
nullptr);
// Parse the outgoing data and check that it matches was was written.
if (type == SYN_STREAM) {
EXPECT_CALL(visitor_,
OnHeaders(stream_id, kHasPriority,
Spdy3PriorityToHttp2Weight(priority),
/*parent_stream_id=*/0,
/*exclusive=*/false, fin, kFrameComplete));
} else {
EXPECT_CALL(visitor_,
OnHeaders(stream_id, !kHasPriority,
/*priority=*/0,
/*parent_stream_id=*/0,
/*exclusive=*/false, fin, kFrameComplete));
}
headers_handler_.reset(new TestHeadersHandler);
EXPECT_CALL(visitor_, OnHeaderFrameStart(stream_id))
.WillOnce(Return(headers_handler_.get()));
EXPECT_CALL(visitor_, OnHeaderFrameEnd(stream_id, true)).Times(1);
if (fin) {
EXPECT_CALL(visitor_, OnStreamEnd(stream_id));
}
framer_->ProcessInput(saved_data_.data(), saved_data_.length());
EXPECT_FALSE(framer_->HasError())
<< SpdyFramer::ErrorCodeToString(framer_->error_code());
CheckHeaders();
saved_data_.clear();
}
void CheckHeaders() {
EXPECT_EQ(headers_, headers_handler_->decoded_block());
headers_handler_.reset();
}
Perspective perspective() const { return test_params_.perspective; }
QuicVersion version() const { return test_params_.version; }
QuicVersionVector GetVersion() {
QuicVersionVector versions;
versions.push_back(version());
return versions;
}
void TearDownLocalConnectionState() {
QuicConnectionPeer::TearDownLocalConnectionState(connection_);
}
QuicStreamId NextPromisedStreamId() { return next_promised_stream_id_ += 2; }
static const bool kFrameComplete = true;
static const bool kHasPriority = true;
const TestParams test_params_;
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
StrictMock<MockQuicConnection>* connection_;
StrictMock<MockQuicSpdySession> session_;
QuicHeadersStream* headers_stream_;
SpdyHeaderBlock headers_;
std::unique_ptr<TestHeadersHandler> headers_handler_;
string body_;
string saved_data_;
string saved_header_data_;
string saved_payloads_;
std::unique_ptr<SpdyFramer> framer_;
StrictMock<MockVisitor> visitor_;
std::unique_ptr<StrictMock<MockHpackDebugVisitor>> hpack_encoder_visitor_;
std::unique_ptr<StrictMock<MockHpackDebugVisitor>> hpack_decoder_visitor_;
QuicStreamFrame stream_frame_;
QuicStreamId next_promised_stream_id_;
};
// Run all tests with each version, perspective (client or server),
// HTTP/2 and HPACK decoder.
INSTANTIATE_TEST_CASE_P(
Tests,
QuicHeadersStreamTest,
::testing::Combine(
::testing::ValuesIn(QuicSupportedVersions()),
::testing::Values(Perspective::IS_CLIENT, Perspective::IS_SERVER),
::testing::Values(HTTP2_DECODER_SPDY,
HTTP2_DECODER_NESTED_SPDY,
HTTP2_DECODER_NEW),
::testing::Values(HPACK_DECODER_SPDY, HPACK_DECODER_NEW)));
TEST_P(QuicHeadersStreamTest, StreamId) {
EXPECT_EQ(3u, headers_stream_->id());
}
TEST_P(QuicHeadersStreamTest, WriteHeaders) {
for (QuicStreamId stream_id = kClientDataStreamId1;
stream_id < kClientDataStreamId3; stream_id += 2) {
for (bool fin : kFins) {
if (perspective() == Perspective::IS_SERVER) {
WriteHeadersAndExpectSynReply(stream_id, fin);
} else {
for (SpdyPriority priority = 0; priority < 7; ++priority) {
// TODO(rch): implement priorities correctly.
WriteHeadersAndExpectSynStream(stream_id, fin, 0);
}
}
}
}
}
TEST_P(QuicHeadersStreamTest, WritePushPromises) {
for (QuicStreamId stream_id = kClientDataStreamId1;
stream_id < kClientDataStreamId3; stream_id += 2) {
QuicStreamId promised_stream_id = NextPromisedStreamId();
if (perspective() == Perspective::IS_SERVER) {
// Write the headers and capture the outgoing data
EXPECT_CALL(session_, WritevData(headers_stream_, kHeadersStreamId, _, _,
false, nullptr))
.WillOnce(WithArgs<2>(Invoke(this, &QuicHeadersStreamTest::SaveIov)));
headers_stream_->WritePushPromise(stream_id, promised_stream_id,
headers_.Clone(), nullptr);
// Parse the outgoing data and check that it matches was was written.
EXPECT_CALL(visitor_,
OnPushPromise(stream_id, promised_stream_id, kFrameComplete));
headers_handler_.reset(new TestHeadersHandler);
EXPECT_CALL(visitor_, OnHeaderFrameStart(stream_id))
.WillOnce(Return(headers_handler_.get()));
EXPECT_CALL(visitor_, OnHeaderFrameEnd(stream_id, true)).Times(1);
framer_->ProcessInput(saved_data_.data(), saved_data_.length());
EXPECT_FALSE(framer_->HasError())
<< SpdyFramer::ErrorCodeToString(framer_->error_code());
CheckHeaders();
saved_data_.clear();
} else {
EXPECT_DFATAL(
headers_stream_->WritePushPromise(stream_id, promised_stream_id,
headers_.Clone(), nullptr),
"Client shouldn't send PUSH_PROMISE");
}
}
}
TEST_P(QuicHeadersStreamTest, ProcessRawData) {
for (QuicStreamId stream_id = kClientDataStreamId1;
stream_id < kClientDataStreamId3; stream_id += 2) {
for (bool fin : {false, true}) {
for (SpdyPriority priority = 0; priority < 7; ++priority) {
// Replace with "WriteHeadersAndSaveData"
SpdySerializedFrame frame;
if (perspective() == Perspective::IS_SERVER) {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
headers_frame.set_has_priority(true);
headers_frame.set_weight(Spdy3PriorityToHttp2Weight(0));
frame = framer_->SerializeFrame(headers_frame);
EXPECT_CALL(session_, OnStreamHeadersPriority(stream_id, 0));
} else {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
frame = framer_->SerializeFrame(headers_frame);
}
EXPECT_CALL(session_,
OnStreamHeaderList(stream_id, fin, frame.size(), _))
.WillOnce(Invoke(this, &QuicHeadersStreamTest::SaveHeaderList));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
stream_frame_.offset += frame.size();
CheckHeaders();
}
}
}
}
TEST_P(QuicHeadersStreamTest, ProcessPushPromise) {
if (perspective() == Perspective::IS_SERVER)
return;
for (QuicStreamId stream_id = kClientDataStreamId1;
stream_id < kClientDataStreamId3; stream_id += 2) {
QuicStreamId promised_stream_id = NextPromisedStreamId();
SpdyPushPromiseIR push_promise(stream_id, promised_stream_id,
headers_.Clone());
SpdySerializedFrame frame(framer_->SerializeFrame(push_promise));
if (perspective() == Perspective::IS_SERVER) {
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"PUSH_PROMISE not supported.", _))
.WillRepeatedly(InvokeWithoutArgs(
this, &QuicHeadersStreamTest::TearDownLocalConnectionState));
} else {
EXPECT_CALL(session_, OnPromiseHeaderList(stream_id, promised_stream_id,
frame.size(), _))
.WillOnce(
Invoke(this, &QuicHeadersStreamTest::SavePromiseHeaderList));
}
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
if (perspective() == Perspective::IS_CLIENT) {
stream_frame_.offset += frame.size();
CheckHeaders();
}
}
}
TEST_P(QuicHeadersStreamTest, EmptyHeaderHOLBlockedTime) {
EXPECT_CALL(session_, OnHeadersHeadOfLineBlocking(_)).Times(0);
testing::InSequence seq;
bool fin = true;
for (int stream_num = 0; stream_num < 10; stream_num++) {
QuicStreamId stream_id = QuicClientDataStreamId(stream_num);
// Replace with "WriteHeadersAndSaveData"
SpdySerializedFrame frame;
if (perspective() == Perspective::IS_SERVER) {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
headers_frame.set_has_priority(true);
headers_frame.set_weight(Spdy3PriorityToHttp2Weight(0));
frame = framer_->SerializeFrame(headers_frame);
EXPECT_CALL(session_, OnStreamHeadersPriority(stream_id, 0));
} else {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
frame = framer_->SerializeFrame(headers_frame);
}
EXPECT_CALL(session_, OnStreamHeaderList(stream_id, fin, frame.size(), _))
.Times(1);
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
stream_frame_.offset += frame.size();
}
}
TEST_P(QuicHeadersStreamTest, NonEmptyHeaderHOLBlockedTime) {
QuicStreamId stream_id;
bool fin = true;
QuicStreamFrame stream_frames[10];
SpdySerializedFrame frames[10];
// First create all the frames in order
{
InSequence seq;
for (int stream_num = 0; stream_num < 10; ++stream_num) {
stream_id = QuicClientDataStreamId(stream_num);
if (perspective() == Perspective::IS_SERVER) {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
headers_frame.set_has_priority(true);
headers_frame.set_weight(Spdy3PriorityToHttp2Weight(0));
frames[stream_num] = framer_->SerializeFrame(headers_frame);
EXPECT_CALL(session_, OnStreamHeadersPriority(stream_id, 0)).Times(1);
} else {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
frames[stream_num] = framer_->SerializeFrame(headers_frame);
}
stream_frames[stream_num].stream_id = stream_frame_.stream_id;
stream_frames[stream_num].offset = stream_frame_.offset;
stream_frames[stream_num].data_buffer = frames[stream_num].data();
stream_frames[stream_num].data_length = frames[stream_num].size();
DVLOG(1) << "make frame for stream " << stream_num << " offset "
<< stream_frames[stream_num].offset;
stream_frame_.offset += frames[stream_num].size();
EXPECT_CALL(session_, OnStreamHeaderList(stream_id, fin, _, _)).Times(1);
}
}
// Actually writing the frames in reverse order will cause HOL blocking.
EXPECT_CALL(session_, OnHeadersHeadOfLineBlocking(_)).Times(9);
for (int stream_num = 9; stream_num >= 0; --stream_num) {
DVLOG(1) << "OnStreamFrame for stream " << stream_num << " offset "
<< stream_frames[stream_num].offset;
headers_stream_->OnStreamFrame(stream_frames[stream_num]);
connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
}
}
TEST_P(QuicHeadersStreamTest, ProcessLargeRawData) {
// We want to create a frame that is more than the SPDY Framer's max control
// frame size, which is 16K, but less than the HPACK decoders max decode
// buffer size, which is 32K.
headers_["key0"] = string(1 << 13, '.');
headers_["key1"] = string(1 << 13, '.');
headers_["key2"] = string(1 << 13, '.');
for (QuicStreamId stream_id = kClientDataStreamId1;
stream_id < kClientDataStreamId3; stream_id += 2) {
for (bool fin : {false, true}) {
for (SpdyPriority priority = 0; priority < 7; ++priority) {
// Replace with "WriteHeadersAndSaveData"
SpdySerializedFrame frame;
if (perspective() == Perspective::IS_SERVER) {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
headers_frame.set_has_priority(true);
headers_frame.set_weight(Spdy3PriorityToHttp2Weight(0));
frame = framer_->SerializeFrame(headers_frame);
EXPECT_CALL(session_, OnStreamHeadersPriority(stream_id, 0));
} else {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
frame = framer_->SerializeFrame(headers_frame);
}
EXPECT_CALL(session_,
OnStreamHeaderList(stream_id, fin, frame.size(), _))
.WillOnce(Invoke(this, &QuicHeadersStreamTest::SaveHeaderList));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
stream_frame_.offset += frame.size();
CheckHeaders();
}
}
}
}
TEST_P(QuicHeadersStreamTest, ProcessBadData) {
const char kBadData[] = "blah blah blah";
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, _, _))
.Times(::testing::AnyNumber());
stream_frame_.data_buffer = kBadData;
stream_frame_.data_length = strlen(kBadData);
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, ProcessSpdyDataFrame) {
SpdyDataIR data(2, "ping");
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"SPDY DATA frame received.", _))
.WillOnce(InvokeWithoutArgs(
this, &QuicHeadersStreamTest::TearDownLocalConnectionState));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, ProcessSpdyDataFrameForceHolBlocking) {
if (version() <= QUIC_VERSION_35) {
return;
}
QuicSpdySessionPeer::SetForceHolBlocking(&session_, true);
SpdyDataIR data(2, "ping");
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(session_, OnStreamFrameData(2, _, 4, false));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, ProcessSpdyDataFrameEmptyWithFin) {
if (version() <= QUIC_VERSION_35) {
return;
}
QuicSpdySessionPeer::SetForceHolBlocking(&session_, true);
SpdyDataIR data(2, "");
data.set_fin(true);
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(session_, OnStreamFrameData(2, _, 0, true));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, ProcessSpdyRstStreamFrame) {
SpdyRstStreamIR data(2, RST_STREAM_PROTOCOL_ERROR);
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"SPDY RST_STREAM frame received.", _))
.WillOnce(InvokeWithoutArgs(
this, &QuicHeadersStreamTest::TearDownLocalConnectionState));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, ProcessSpdySettingsFrame) {
FLAGS_quic_respect_http2_settings_frame = false;
SpdySettingsIR data;
data.AddSetting(SETTINGS_HEADER_TABLE_SIZE, true, true, 0);
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"SPDY SETTINGS frame received.", _))
.WillOnce(InvokeWithoutArgs(
this, &QuicHeadersStreamTest::TearDownLocalConnectionState));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, RespectHttp2SettingsFrameSupportedFields) {
FLAGS_quic_respect_http2_settings_frame = true;
const uint32_t kTestHeaderTableSize = 1000;
SpdySettingsIR data;
// Respect supported settings frames SETTINGS_HEADER_TABLE_SIZE.
data.AddSetting(SETTINGS_HEADER_TABLE_SIZE, true, true, kTestHeaderTableSize);
SpdySerializedFrame frame(framer_->SerializeFrame(data));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
EXPECT_EQ(kTestHeaderTableSize,
QuicHeadersStreamPeer::GetSpdyFramer(headers_stream_)
.header_encoder_table_size());
}
TEST_P(QuicHeadersStreamTest, RespectHttp2SettingsFrameUnsupportedFields) {
FLAGS_quic_respect_http2_settings_frame = true;
SpdySettingsIR data;
// Does not support SETTINGS_MAX_HEADER_LIST_SIZE,
// SETTINGS_MAX_CONCURRENT_STREAMS, SETTINGS_INITIAL_WINDOW_SIZE,
// SETTINGS_ENABLE_PUSH and SETTINGS_MAX_FRAME_SIZE.
data.AddSetting(SETTINGS_MAX_HEADER_LIST_SIZE, true, true, 2000);
data.AddSetting(SETTINGS_MAX_CONCURRENT_STREAMS, true, true, 100);
data.AddSetting(SETTINGS_INITIAL_WINDOW_SIZE, true, true, 100);
data.AddSetting(SETTINGS_ENABLE_PUSH, true, true, 1);
data.AddSetting(SETTINGS_MAX_FRAME_SIZE, true, true, 1250);
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"Unsupported field of HTTP/2 SETTINGS frame: " +
base::IntToString(SETTINGS_MAX_HEADER_LIST_SIZE),
_));
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"Unsupported field of HTTP/2 SETTINGS frame: " +
base::IntToString(SETTINGS_MAX_CONCURRENT_STREAMS),
_));
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"Unsupported field of HTTP/2 SETTINGS frame: " +
base::IntToString(SETTINGS_INITIAL_WINDOW_SIZE),
_));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"Unsupported field of HTTP/2 SETTINGS frame: " +
base::IntToString(SETTINGS_ENABLE_PUSH),
_));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"Unsupported field of HTTP/2 SETTINGS frame: " +
base::IntToString(SETTINGS_MAX_FRAME_SIZE),
_));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, ProcessSpdyPingFrame) {
SpdyPingIR data(1);
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"SPDY PING frame received.", _))
.WillOnce(InvokeWithoutArgs(
this, &QuicHeadersStreamTest::TearDownLocalConnectionState));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, ProcessSpdyGoAwayFrame) {
SpdyGoAwayIR data(1, GOAWAY_PROTOCOL_ERROR, "go away");
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"SPDY GOAWAY frame received.", _))
.WillOnce(InvokeWithoutArgs(
this, &QuicHeadersStreamTest::TearDownLocalConnectionState));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, ProcessSpdyWindowUpdateFrame) {
SpdyWindowUpdateIR data(1, 1);
SpdySerializedFrame frame(framer_->SerializeFrame(data));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"SPDY WINDOW_UPDATE frame received.", _))
.WillOnce(InvokeWithoutArgs(
this, &QuicHeadersStreamTest::TearDownLocalConnectionState));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
headers_stream_->OnStreamFrame(stream_frame_);
}
TEST_P(QuicHeadersStreamTest, NoConnectionLevelFlowControl) {
EXPECT_FALSE(ReliableQuicStreamPeer::StreamContributesToConnectionFlowControl(
headers_stream_));
}
TEST_P(QuicHeadersStreamTest, HpackDecoderDebugVisitor) {
if (FLAGS_use_nested_spdy_framer_decoder)
return;
StrictMock<MockHpackDebugVisitor>* hpack_decoder_visitor =
hpack_decoder_visitor_.get();
headers_stream_->SetHpackDecoderDebugVisitor(
std::move(hpack_decoder_visitor_));
// Create some headers we expect to generate entries in HPACK's
// dynamic table, in addition to content-length.
headers_["key0"] = string(1 << 1, '.');
headers_["key1"] = string(1 << 2, '.');
headers_["key2"] = string(1 << 3, '.');
{
testing::InSequence seq;
// Number of indexed representations generated in headers below.
for (int i = 1; i < 28; i++) {
EXPECT_CALL(*hpack_decoder_visitor,
OnUseEntry(QuicTime::Delta::FromMilliseconds(i)))
.Times(4);
}
}
for (QuicStreamId stream_id = kClientDataStreamId1;
stream_id < kClientDataStreamId3; stream_id += 2) {
for (bool fin : {false, true}) {
for (SpdyPriority priority = 0; priority < 7; ++priority) {
// Replace with "WriteHeadersAndSaveData"
SpdySerializedFrame frame;
if (perspective() == Perspective::IS_SERVER) {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
headers_frame.set_has_priority(true);
headers_frame.set_weight(Spdy3PriorityToHttp2Weight(0));
frame = framer_->SerializeFrame(headers_frame);
EXPECT_CALL(session_, OnStreamHeadersPriority(stream_id, 0));
} else {
SpdyHeadersIR headers_frame(stream_id, headers_.Clone());
headers_frame.set_fin(fin);
frame = framer_->SerializeFrame(headers_frame);
}
EXPECT_CALL(session_,
OnStreamHeaderList(stream_id, fin, frame.size(), _))
.WillOnce(Invoke(this, &QuicHeadersStreamTest::SaveHeaderList));
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
headers_stream_->OnStreamFrame(stream_frame_);
stream_frame_.offset += frame.size();
CheckHeaders();
}
}
}
}
TEST_P(QuicHeadersStreamTest, HpackEncoderDebugVisitor) {
StrictMock<MockHpackDebugVisitor>* hpack_encoder_visitor =
hpack_encoder_visitor_.get();
headers_stream_->SetHpackEncoderDebugVisitor(
std::move(hpack_encoder_visitor_));
if (perspective() == Perspective::IS_SERVER) {
testing::InSequence seq;
for (int i = 1; i < 4; i++) {
EXPECT_CALL(*hpack_encoder_visitor,
OnUseEntry(QuicTime::Delta::FromMilliseconds(i)));
}
} else {
testing::InSequence seq;
for (int i = 1; i < 28; i++) {
EXPECT_CALL(*hpack_encoder_visitor,
OnUseEntry(QuicTime::Delta::FromMilliseconds(i)));
}
}
for (QuicStreamId stream_id = kClientDataStreamId1;
stream_id < kClientDataStreamId3; stream_id += 2) {
for (bool fin : {false, true}) {
if (perspective() == Perspective::IS_SERVER) {
WriteHeadersAndExpectSynReply(stream_id, fin);
connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
} else {
for (SpdyPriority priority = 0; priority < 7; ++priority) {
// TODO(rch): implement priorities correctly.
WriteHeadersAndExpectSynStream(stream_id, fin, 0);
connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
}
}
}
}
}
TEST_P(QuicHeadersStreamTest, WritevStreamData) {
QuicStreamId id = kClientDataStreamId1;
QuicStreamOffset offset = 0;
struct iovec iov;
string data;
// This test will issue a write that will require fragmenting into
// multiple HTTP/2 DATA frames.
const int kMinDataFrames = 4;
const size_t data_len =
kSpdyInitialFrameSizeLimit * kMinDataFrames + 1024;
// Set headers stream send window large enough for data written below.
headers_stream_->flow_controller()->UpdateSendWindowOffset(data_len * 2 * 4);
test::GenerateBody(&data, data_len);
for (bool fin : {true, false}) {
for (bool use_ack_listener : {true, false}) {
scoped_refptr<ForceHolAckListener> ack_listener;
if (use_ack_listener) {
ack_listener = new ForceHolAckListener();
}
EXPECT_CALL(session_,
WritevData(headers_stream_, kHeadersStreamId, _, _, false, _))
.WillRepeatedly(WithArgs<2, 5>(Invoke(
this, &QuicHeadersStreamTest::SaveIovAndNotifyAckListener)));
QuicConsumedData consumed_data = headers_stream_->WritevStreamData(
id, MakeIOVector(data, &iov), offset, fin, ack_listener.get());
EXPECT_EQ(consumed_data.bytes_consumed, data_len);
EXPECT_EQ(consumed_data.fin_consumed, fin);
// Now process the written data with the SPDY framer, and verify
// that the original data is unchanged.
EXPECT_CALL(visitor_, OnDataFrameHeader(id, _, _))
.Times(AtLeast(kMinDataFrames));
EXPECT_CALL(visitor_, OnStreamFrameData(id, _, _))
.WillRepeatedly(WithArgs<1, 2>(
Invoke(this, &QuicHeadersStreamTest::SavePayload)));
if (fin) {
EXPECT_CALL(visitor_, OnStreamEnd(id));
}
framer_->ProcessInput(saved_data_.data(), saved_data_.length());
EXPECT_EQ(saved_payloads_, data);
if (use_ack_listener) {
// Notice, acked bytes doesn't include extra bytes used by
// HTTP/2 DATA frame headers.
EXPECT_EQ(ack_listener->total_acked_bytes(), data_len);
}
saved_data_.clear();
saved_payloads_.clear();
}
}
}
} // namespace
} // namespace test
} // namespace net
| [
"[email protected]"
] | |
927e0f523d8fda5344729e5c874275ee68c4bfbd | a37579f7b836c596fb12ced8d2d21f9b3c694585 | /waitdiag.h | 5ccd6f76767367881311e4b6766258d3857147b5 | [] | no_license | gitrath/tvmeas | 7dbfd7a60a41fd1f6da31d153db39303a0aaf563 | 43df8a288f06037bbe8a9f22aa9fe164fbd6004b | refs/heads/master | 2021-04-29T07:06:12.918670 | 2017-01-04T06:25:39 | 2017-01-04T06:25:39 | 77,988,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 184 | h | #ifndef waitdiag_h
#define waitdiag_h
#define Uses_TDialog
#include <tv.h>
class WaitDialog : public TDialog
{
public:
WaitDialog( const char *title );
};
#endif
| [
"[email protected]"
] | |
cb97222bd35211a43f7ee2575588a3ffc03da940 | 5d4bbc4ba9ab0ddf8a44034ad1a8f3cf0ee274a3 | /gameOfLife.cpp | a98828fc6460ae82b787bbbee0cced877cfe19e2 | [] | no_license | a5batra/LeetCode-Solutions-in-C-plus-plus | eda25d641859d8da193825cf06fd7db845862224 | 2124763fce4b5f7c150c95578bf972fbba3d3b50 | refs/heads/master | 2021-12-08T21:41:11.234971 | 2021-08-11T20:43:13 | 2021-08-11T20:43:13 | 243,896,276 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,662 | cpp | //
// Created by Ankit Batra on 5/30/21.
//
/* According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised
* by the British mathematician John Horton Conway in 1970."
* The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1)
* or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal)
* using the following four rules (taken from the above Wikipedia article):
* Any live cell with fewer than two live neighbors dies as if caused by under-population.
* Any live cell with two or three live neighbors lives on to the next generation.
* Any live cell with more than three live neighbors dies, as if by over-population.
* Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
* The next state is created by applying the above rules simultaneously to every cell in the current state,
* where births and deaths occur simultaneously.
* Given the current state of the m x n grid board, return the next state. */
// die -> live : -1
// live -> die : 2
class Solution {
vector<vector<int>> dirs;
public:
Solution() {
dirs = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}};
}
int getLiveNeighbors(vector<vector<int>>& board, int r, int c) {
int numLive = 0;
for (int k = 0; k < 8; ++k) {
int nr = r + dirs[k][0];
int nc = c + dirs[k][1];
if (nr < 0 || nr >= board.size() || nc < 0 || nc >= board[0].size())
continue;
if (board[nr][nc] == 1 || board[nr][nc] == 2) numLive++;
}
return numLive;
}
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
if (m == 0) return;
int n = board[0].size();
for (int r = 0; r < m; ++r) {
for (int c = 0; c < n; ++c) {
if (board[r][c] == 1) {
int count = getLiveNeighbors(board, r, c);
if (count < 2) board[r][c] = 2;
else if (count == 2 || count == 3) board[r][c] = 1;
else board[r][c] = 2;
}
else {
int count = getLiveNeighbors(board, r, c);
if (count == 3) board[r][c] = -1;
}
}
}
for (int r = 0; r < m; ++r) {
for (int c = 0; c < n; ++c) {
if (board[r][c] == -1) board[r][c] = 1;
else if (board[r][c] == 2) board[r][c] = 0;
}
}
}
};
| [
"[email protected]"
] | |
7efd46531760b6064ab2924d515848fa953e7433 | 625a9db8addb1f47fa1e49c191ec2b365439eba3 | /bc_window.cpp | 9741338a47b811302fa072ffd1ed975533e31faa | [] | no_license | MishkaV/Lab1 | efb75082905f31b9be7d46a80032b0475aacd8a3 | b235436dafa0253e55281b20d4a9e30a550e8d0d | refs/heads/master | 2023-01-07T16:22:29.523720 | 2020-11-09T09:27:07 | 2020-11-09T09:27:07 | 297,893,137 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,119 | cpp | #include "bc_window.h"
#include "ui_bc_window.h"
#include <QMessageBox>
#include <string>
#include <stdlib.h>
#include <second_window.h>
#include <QStandardItem>
#include <QStandardItemModel>
#include "bonus_card.h"
#include "mainwindow.h"
#include <fstream>
bc_window::bc_window(QWidget *parent) :
QDialog(parent),
ui(new Ui::bc_window)
{
ui->setupUi(this);
this->bc_collection.bc_input_from_file("save_bc.txt");
}
void bc_window::on_bc_view_collection_clicked()
{
if(this->bc_collection.get_iterator() && this->bc_collection.size())
{
second_window window;
window.setModal(true);
window.insert_data(&this->bc_collection, this->bc_collection.size());
window.exec();
}
else
QMessageBox::critical(this,"Show", "There is no data to show");
}
void bc_window::on_bc_size_clicked()
{
if(this->bc_collection.get_iterator() && this->bc_collection.size())
{
QMessageBox::information(this, "Size", "The size of the queue is " + QString::number(this->bc_collection.size()));
}
else
QMessageBox::critical(this,"Size", "There is no queue");
}
void bc_window::on_bc_delete_queue_clicked()
{
if(this->bc_collection.get_iterator() && this->bc_collection.size())
{
this->bc_collection.clear();
this->bc_collectiom_dial->clear();
QMessageBox::information(this, "Clean", "You delete all queue");
}
else
QMessageBox::critical(this,"Clear", "There is no data to clean");
}
void bc_window::on_bc_delete_first_clicked()
{
if(this->bc_collection.get_iterator() && this->bc_collection.size())
{
this->bc_collection.pop();
this->bc_collectiom_dial->pop();
QMessageBox::information(this, "Pop", "You pop first purchase");
}
else
QMessageBox::critical(this,"Pop", "There is no data to pop");
}
void bc_window::on_bc_amount_ok_clicked()
{
if(this->bc_collection.get_iterator() && this->bc_collection.size())
{
std:: string time_from = ui->bc_amount_time_from->text().toStdString();
std:: string date_from = ui->bc_amount_date_from->text().toStdString();
std:: string time_to = ui->bc_amount_time_to->text().toStdString();
std:: string date_to = ui->bc_amount_date_to->text().toStdString();
QMessageBox::information(this, "Sum", "The total amount in this period is " + QString::number(this->bc_collection.sum(time_from, date_from,time_to,date_to)));
}
else
QMessageBox::critical(this,"Sum", "There is no queue");
}
void bc_window::on_bc_file_input_ok_clicked()
{
this->bc_collection.bc_input_from_file(ui->bc_file_input_name->text().toStdString());
this->bc_collectiom_dial->bc_input_from_file(ui->bc_file_input_name->text().toStdString());
QMessageBox::information(this, "Input from file", "Success input from file");
}
void bc_window::on_bc_file_output_ok_clicked()
{
if(this->bc_collection.get_iterator() && this->bc_collection.size())
{
this->bc_collection.output_to_file(ui->bc_file_output_name->text().toStdString());
QMessageBox::information(this, "Output to file", "Success output to file");
}
else
QMessageBox::critical(this,"Output to file", "There is no queue");
}
bc_window::~bc_window()
{
delete ui;
}
void bc_save_data(const purchase_collection& col)
{
ofstream fout("save_bc.txt");
for(int i = 0;i < col.get_count();i++)
{
fout << col.get_iterator()[i]->get_time()<< endl;
fout << col.get_iterator()[i]->get_date() << endl;
fout << col.get_iterator()[i]->get_amount() << endl;
fout << col.get_iterator()[i]->get_data("card") << endl;
fout << col.get_iterator()[i]->get_data("tele") << endl <<endl;
}
fout.close();
}
void bc_window::on_pushButton_bc_back_clicked()
{
QMessageBox::StandardButton save = QMessageBox::question(this, "Save", "Save collection?", QMessageBox::Yes | QMessageBox::No);
if(save == QMessageBox::No)
{
this->bc_collection.clear();
}
bc_save_data(bc_collection);
this->close();
}
| [
"[email protected]"
] | |
49941e74e8a518701713314de0a2c4c4bacb0926 | cde9dc97b0fc3df945e2500a4b21deb9caf994cf | /streamconnector/source/modelserializerv1.cpp | f89708f7b8b023b40e973c7ea4836176201b9740 | [] | no_license | MartinSchouwenburg/ilwisobjects | 7bbe06a9c097472dea0496522465f59701782351 | ad59176c1eb79d56089abc009ea1622958d78fe4 | refs/heads/main | 2023-05-10T13:46:05.864706 | 2021-06-14T08:56:55 | 2021-06-14T08:56:55 | 373,075,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,850 | cpp | /*IlwisObjects is a framework for analysis, processing and visualization of remote sensing and gis data
Copyright (C) 2018 52n North
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.*/
#include "kernel.h"
#include "version.h"
#include "geometries.h"
#include "ilwisdata.h"
#include "symboltable.h"
#include "operationmetadata.h"
#include "location.h"
#include "workflownode.h"
#include "workflow.h"
#include "analysispattern.h"
#include "applicationmodel.h"
#include "model.h"
#include "factory.h"
#include "abstractfactory.h"
#include "connectorinterface.h"
#include "versionedserializer.h"
#include "versioneddatastreamfactory.h"
#include "modellerfactory.h"
#include "modelserializerv1.h"
using namespace Ilwis;
using namespace Stream;
VersionedSerializer *ModelSerializerV1::create(QDataStream& stream, const QString &version)
{
return new ModelSerializerV1(stream, version);
}
ModelSerializerV1::ModelSerializerV1(QDataStream& stream, const QString &version) : VersionedSerializer(stream, version)
{
}
bool ModelSerializerV1::store(IlwisObject *obj,const IOOptions& options)
{
if (!VersionedSerializer::store(obj, options))
return false;
Model *model = static_cast<Model *>(obj);
VersionedDataStreamFactory *factory = kernel()->factory<VersionedDataStreamFactory>("ilwis::VersionedDataStreamFactory");
if (!factory)
return false;
std::unique_ptr<DataInterface> wfstreamer(factory->create(Version::interfaceVersion41, itMODEL,_stream));
if ( !wfstreamer)
return false;
_stream << model->workflowCount();
for(int i=0; i < model->workflowCount(); ++i){
if(!wfstreamer->store(model->workflow(i).ptr(), options))
return false;
}
_stream << model->analysisCount();
for(int i=0; i < model->analysisCount(); ++i){
model->analysisPattern(i)->store(_stream);
}
_stream << model->applicationCount();
for(int i=0; i < model->applicationCount(); ++i){
model->application(i)->store(_stream);
}
return true;
}
bool ModelSerializerV1::loadMetaData(IlwisObject *obj, const IOOptions &options)
{
if (!VersionedSerializer::loadMetaData(obj, options))
return false;
Model *model = static_cast<Model *>(obj);
VersionedDataStreamFactory *factory = kernel()->factory<VersionedDataStreamFactory>("ilwis::VersionedDataStreamFactory");
if (!factory)
return false;
std::unique_ptr<DataInterface> wfstreamer(factory->create(_version, itMODEL,_stream));
if ( !wfstreamer)
return false;
qint32 count;
_stream >> count;
for(int i=0; i < count; ++i){
quint64 type;
QString version, url;
_stream >> url;
_stream >> type;
_stream >> version;
IWorkflow systemWf = makeSystemObject<IWorkflow>(url);
IWorkflow wf (type);
if(!wfstreamer->loadMetaData(wf.ptr(), options))
return false;
model->addWorklfow(systemWf.isValid() ? systemWf :wf );
}
_stream >> count;
for(int i=0; i < count; ++i){
QString type;
_stream >> type;
ModellerFactory *factory = kernel()->factory<ModellerFactory>("ModellerFactory","ilwis");
if ( factory){
AnalysisPattern *pattern = factory->createAnalysisPattern(type,sUNDEF,sUNDEF, options);
if ( pattern){
pattern->loadMetadata(_stream);
model->addAnalysisPattern(pattern);
} else
return false;
}
}
_stream >> count;
for(int i=0; i < count; ++i){
QString type;
_stream >> type;
ModellerFactory *factory = kernel()->factory<ModellerFactory>("ModellerFactory","ilwis");
if ( factory){
ApplicationModel *app = factory->createApplication(type);
if ( app){
app->loadMetadata(_stream);
model->addApplication(app);
} else
return false;
}
}
return true;
}
bool Ilwis::Stream::ModelSerializerV1::loadData(IlwisObject *data, const IOOptions &options)
{
//TODO
return false;
}
| [
"[email protected]"
] | |
285d8459df7b1acd33b8e35c68fcd0986ba460fb | dd6fee79066e2dfa74371bd82c87a563dc0c47fd | /contest/2012summer/2012 Multi-University Training Contest 7/Water World I/forcecode_1.cpp | dddda5bfb97b0a4f96ede97bbacc00464162d026 | [] | no_license | mzry1992/workspace | 404c31df66a3b15a60dc0f07fff397bf50bcc1dc | 9a181419f0d7224e37baa729feaf3bb656544420 | refs/heads/master | 2021-01-19T12:39:17.854501 | 2012-12-24T11:13:22 | 2012-12-24T11:13:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,017 | cpp | #include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
#define EPS 1e-10
#define N 2200
struct TPoint{
double x;
double y;
};
struct Segment{
TPoint s;
TPoint e;
void reset(){if(s.y>e.y)swap(s,e);}
double getx(double h){
double dx=e.x-s.x,dy=e.y-s.y;
return (h-s.y)*dx/dy+s.x;
}
double count(Segment &b){
double lh=s.y,hh=e.y,ans;
if(lh<b.s.y)lh=b.s.y;
if(hh>b.e.y)hh=b.e.y;
if(fabs(hh-lh)<EPS)ans=0;
else ans=(hh-lh)*(getx(lh)-b.getx(lh)+getx(hh)-b.getx(hh))/2.0;
s.x=getx(hh);
s.y=hh;
b.s.x=b.getx(hh);
b.s.y=hh;
return fabs(ans);
}
};
Segment s[N],seg;
const double PI=acos(-1.0);
TPoint rotate( TPoint p,double alpha)
{
TPoint tmp;
tmp.x = p.x * cos(alpha) - p.y * sin(alpha);
tmp.y = p.y * cos(alpha) + p.x * sin(alpha);
return tmp;
}
int main(){
// freopen("data.in", "r", stdin);
// freopen("data2.out", "w", stdout);
//freopen("data.in", "r", stdin);
//freopen("forcedata_1.out", "w", stdout);
int n,i,lh,nh,s_end;
double ans,a;
while(scanf("%d%lf",&n,&a)!=EOF){
a=a/180*PI;
s_end=lh=0;
ans=0;
for(i=0;i<n;i++){
scanf("%d",&nh);
seg.e.x=seg.s.x=i;
seg.s.y=lh;
seg.e.y=nh;
seg.s=rotate(seg.s,a);
seg.e=rotate(seg.e,a);
seg.reset();
while(s_end>0 && s[s_end-1].s.y-seg.e.y<-EPS){
if(seg.e.y-s[s_end-1].e.y>-EPS && fabs(seg.e.x-s[s_end-1].e.x)<EPS ){s_end--;continue;}
ans+=seg.count(s[s_end-1]);
if(s[s_end-1].s.y-seg.e.y<-EPS)s_end--;
else break;
}
s[s_end++]=seg;
lh=nh;
seg.e.x=i+1;
seg.s.x=i;
seg.s.y=seg.e.y=nh;
seg.s=rotate(seg.s,a);
seg.e=rotate(seg.e,a);
seg.reset();
while(s_end>0 && s[s_end-1].s.y-seg.e.y<-EPS){
if(seg.e.y-s[s_end-1].e.y>-EPS && fabs(seg.e.x-s[s_end-1].e.x)<EPS ){s_end--;continue;}
ans+=seg.count(s[s_end-1]);
if(s[s_end-1].s.y-seg.e.y<-EPS)s_end--;
else break;
}
s[s_end++]=seg;
}
printf("%0.2lf\n",ans);
}
return 0;
}
| [
"[email protected]"
] | |
dd319b10d53f3109818cdc6e62869acb4667ba61 | 1d17439857639a56270b7f411d2aefd68330e53e | /hook/test_hook_module.cpp | 8faf6850aafcebda7e9f0d1b735d61f7effa842d | [] | no_license | jmlvanre/modules | cfa6eb4363a4ab7675376b9b2fa2db34c99de8f5 | 3aef6d9c7cabdc9bbae07db639b9c606f0dc08eb | refs/heads/master | 2021-01-14T08:26:28.892537 | 2015-05-29T03:49:09 | 2015-05-29T03:49:09 | 36,481,197 | 0 | 0 | null | 2015-05-29T03:47:33 | 2015-05-29T03:47:33 | null | UTF-8 | C++ | false | false | 4,058 | cpp | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
#include <string>
#include <mesos/hook.hpp>
#include <mesos/mesos.hpp>
#include <mesos/module.hpp>
#include <mesos/module/hook.hpp>
#include <stout/foreach.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
using std::string;
using namespace mesos;
// Must be kept in sync with variables of the same name in
// tests/hook_tests.cpp.
const char* testLabelKey = "MESOS_Test_Label";
const char* testLabelValue = "ApacheMesos";
const char* testEnvironmentVariableName = "MESOS_TEST_ENVIRONMENT_VARIABLE";
class TestHook : public Hook
{
public:
virtual Result<Labels> masterLaunchTaskLabelDecorator(
const TaskInfo& taskInfo,
const FrameworkInfo& frameworkInfo,
const SlaveInfo& slaveInfo)
{
LOG(INFO) << "Executing 'masterLaunchTaskLabelDecorator' hook";
Labels labels;
Label *label = labels.add_labels();
label->set_key(testLabelKey);
label->set_value(testLabelValue);
return labels;
}
// In this hook, we create a temporary file and add its path to an
// environment variable. Later on, this environment variable is
// looked up by the removeExecutorHook to locate and delete this
// file.
virtual Result<Environment> slaveLaunchExecutorEnvironmentDecorator(
const ExecutorInfo& executorInfo,
const TaskInfo& taskInfo)
{
LOG(INFO) << "Executing 'slaveLaunchExecutorEnvironmentDecorator' hook";
// Find the label value for the label that was created in the
// label decorator hook above.
Option<string> labelValue;
foreach (const Label& label, taskInfo.labels().labels()) {
if (label.key() == testLabelKey) {
labelValue = label.value();
CHECK_EQ(labelValue.get(), testLabelValue);
}
}
CHECK_SOME(labelValue);
// Create a temporary file.
Try<string> file = os::mktemp();
CHECK_SOME(file);
CHECK_SOME(os::write(file.get(), labelValue.get()));
// Inject file path into command environment.
Environment environment;
Environment::Variable* variable = environment.add_variables();
variable->set_name(testEnvironmentVariableName);
variable->set_value(file.get());
return environment;
}
// This hook locates the file created by environment decorator hook
// and deletes it.
virtual Try<Nothing> slaveRemoveExecutorHook(
const FrameworkInfo& frameworkInfo,
const ExecutorInfo& executorInfo)
{
LOG(INFO) << "Executing 'slaveRemoveExecutorHook'";
foreach (const Environment::Variable& variable,
executorInfo.command().environment().variables()) {
if (variable.name() == testEnvironmentVariableName) {
string path = variable.value();
// The removeExecutor hook may be called multiple times; thus
// we ignore the subsequent calls.
if (os::isfile(path)) {
CHECK_SOME(os::rm(path));
}
break;
}
}
return Nothing();
}
};
static Hook* createHook(const Parameters& parameters)
{
return new TestHook();
}
// Declares a Hook module named 'TestHook'.
mesos::modules::Module<Hook> org_apache_mesos_TestHook(
MESOS_MODULE_API_VERSION,
MESOS_VERSION,
"Apache Mesos",
"[email protected]",
"Test Hook module.",
NULL,
createHook);
| [
"[email protected]"
] | |
036ffb32a6ddda290d74f95b030ebdca2ab8a8d9 | 1ee19cd1e37c431acb3933408d6aa31e127bb177 | /version-program/program-v1/lib/test-usb2.cc | eea16b5380cd246ad5e5e4d5774e8c08eed7749b | [] | no_license | DuongNguyenHai/screw-machine | 6664b5e227b5a1749f41d11736db5908778c2df8 | e267e99e556777159e55253bb472a50d12eaa675 | refs/heads/master | 2021-09-07T11:33:24.027711 | 2018-02-22T10:53:11 | 2018-02-22T10:53:11 | 113,328,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cc | // g++ -std=c++11 -Wall test-usb2.cc usb-port.cc -o test -lpthread
#include <iostream>
#include <unistd.h>
#include "usb-port.h"
int main(int argc, char const *argv[]) {
StreamPortUSB port;
while(true) {
std::vector<std::string> list = port.listPort();
for (size_t i = 0; i < list.size(); i++) {
port.begin(list[i]);
std::cout << "Open port: " << port.port << std::endl;
sleep(2);
port.end();
}
}
sleep(100);
pause();
return 0;
}
| [
"[email protected]"
] | |
abaf37500a1d5d720b4f99814a65cbc50b9c2595 | 6e80257439f5c31e13b733a0dbd32b64c4737d80 | /MySimpleNativeDll/stdafx.cpp | 22cb7f0fcc07c1fe0f45451ecd515613dcc5a091 | [] | no_license | HyundongHwang/MyNativeDllUwpIntegApp | bce8ca0b17ca47d9090287828c532c7bae5323a7 | eaf3c33f4cbacf42729af7d5d3fa77b6a7d61d5d | refs/heads/master | 2021-01-13T03:49:44.385214 | 2016-12-26T05:31:56 | 2016-12-26T05:31:56 | 77,184,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | // stdafx.cpp : source file that includes just the standard includes
// MySimpleNativeDll.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
9a7b4f73faecfa20c5f93db055e5daad89814788 | 1ca921c261a2cd51ab9199a9905cec757d5becb6 | /Morpion/AlphaBeta.h | 34bf5d89e836a45be0322bd8848ae4f557d28073 | [] | no_license | yazIFI/Morpion | f2023f60be5a3f11347edc8dd71be13e06d7eecc | 7e18b397d70277ae11910d4d8b05edc885c5c8c4 | refs/heads/master | 2021-01-21T13:08:15.524320 | 2014-12-09T21:54:26 | 2014-12-09T21:54:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 198 | h | #pragma once
#include "TypePlay.h"
class AlphaBeta{
private:
int choicePlay;
public:
AlphaBeta(int c_) :
choicePlay(c_)
{}
int getChpoice();
void setChoice(int newChoice);
void play();
}; | [
"[email protected]"
] | |
9d8c752f945cf38bbb592d1b208fbad2fd4e61fc | 1600c1745a1277fe28a55b6a8146e9a2cc13e90a | /app/examGen/RandomProfile.h | 894680627d3ce7d6273146bc968d254d78d9bd92 | [
"MIT"
] | permissive | josokw/ExamGenerator | 4424c08ecacac2fe04d7287ac6dfc1a5234ad2e8 | 6c5d7d8e6a000aa50a1b04a3de80e5732d9f6457 | refs/heads/master | 2023-01-21T09:46:12.176361 | 2023-01-12T14:43:28 | 2023-01-12T14:43:28 | 148,987,104 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,266 | h | #ifndef RANDOMPROFILE_H
#define RANDOMPROFILE_H
//#include "Random.h"
#include "GenRandom.h"
#include <list>
#include <tuple>
#include <vector>
/// Responsible for generating a random profile containing a number of integer
/// values based on range information. Maximum range width: 9. Range (closed
/// interval): [N .. max 9+N]. Examples: [3..7] [3..12] [88..90].
/// Uses the class #GenRandom to generate pseudo random values.
class RandomProfile
{
public:
using range_t = std::pair<int, int>;
using profile_t = std::vector<int>;
using fullR_t = std::tuple<RandomProfile::range_t, int, std::list<int>, int>;
RandomProfile();
RandomProfile(unsigned long sd);
virtual ~RandomProfile() = default;
void generate(const std::vector<RandomProfile::range_t> &Ranges);
void generate(std::vector<fullR_t> &fullRs);
const RandomProfile::profile_t &getProfile() const { return profile_; }
private:
GenRandom genrnd_;
/// Random generated profile data
profile_t profile_;
public:
/// generates 1 random value acoording to Range data
int generate(const RandomProfile::range_t &range);
/// generates 1 random value acoording to fullR data
int generate(fullR_t &fullR);
};
#endif
| [
"[email protected]"
] | |
e8e1cf205c6fcbdb00f1c66b8da51834c7072927 | eb5d15764ed4d88512d849461abbd1515b47c24c | /cryptonote/src/Wallet/WalletErrors.h | 347521266477c5256cb3a869dab93772181a024d | [
"LGPL-3.0-only",
"GPL-3.0-only"
] | permissive | theboldtoken/bold | 4e74e2ef43f103ad8795892450918399030b32db | 3015bc90fedebec106ff28f0d49ea72d147a98fe | refs/heads/master | 2020-03-22T00:01:22.499231 | 2019-09-29T05:48:10 | 2019-09-29T05:48:10 | 117,006,837 | 0 | 1 | MIT | 2018-01-10T22:47:39 | 2018-01-10T20:24:35 | null | UTF-8 | C++ | false | false | 4,677 | h | // Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Bytecoin 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <string>
#include <system_error>
namespace CryptoNote {
namespace error {
// custom error conditions enum type:
enum WalletErrorCodes {
NOT_INITIALIZED = 1,
ALREADY_INITIALIZED,
WRONG_STATE,
WRONG_PASSWORD,
INTERNAL_WALLET_ERROR,
MIXIN_COUNT_TOO_BIG,
BAD_ADDRESS,
TRANSACTION_SIZE_TOO_BIG,
WRONG_AMOUNT,
SUM_OVERFLOW,
ZERO_DESTINATION,
TX_CANCEL_IMPOSSIBLE,
TX_CANCELLED,
OPERATION_CANCELLED,
TX_TRANSFER_IMPOSSIBLE,
WRONG_VERSION,
FEE_TOO_SMALL,
KEY_GENERATION_ERROR,
INDEX_OUT_OF_RANGE,
ADDRESS_ALREADY_EXISTS,
TRACKING_MODE,
WRONG_PARAMETERS,
OBJECT_NOT_FOUND,
WALLET_NOT_FOUND,
CHANGE_ADDRESS_REQUIRED,
CHANGE_ADDRESS_NOT_FOUND,
DESTINATION_ADDRESS_REQUIRED,
DESTINATION_ADDRESS_NOT_FOUND,
BAD_PAYMENT_ID,
BAD_TRANSACTION_EXTRA
};
// custom category:
class WalletErrorCategory : public std::error_category {
public:
static WalletErrorCategory INSTANCE;
virtual const char* name() const throw() override {
return "WalletErrorCategory";
}
virtual std::error_condition default_error_condition(int ev) const throw() override {
return std::error_condition(ev, *this);
}
virtual std::string message(int ev) const override {
switch (ev) {
case NOT_INITIALIZED: return "Object was not initialized";
case WRONG_PASSWORD: return "The password is wrong";
case ALREADY_INITIALIZED: return "The object is already initialized";
case INTERNAL_WALLET_ERROR: return "Internal error occurred";
case MIXIN_COUNT_TOO_BIG: return "MixIn count is too big";
case BAD_ADDRESS: return "Bad address";
case TRANSACTION_SIZE_TOO_BIG: return "Transaction size is too big";
case WRONG_AMOUNT: return "Wrong amount";
case SUM_OVERFLOW: return "Sum overflow";
case ZERO_DESTINATION: return "The destination is empty";
case TX_CANCEL_IMPOSSIBLE: return "Impossible to cancel transaction";
case WRONG_STATE: return "The wallet is in wrong state (maybe loading or saving), try again later";
case OPERATION_CANCELLED: return "The operation you've requested has been cancelled";
case TX_TRANSFER_IMPOSSIBLE: return "Transaction transfer impossible";
case WRONG_VERSION: return "Wrong version";
case FEE_TOO_SMALL: return "Transaction fee is too small";
case KEY_GENERATION_ERROR: return "Cannot generate new key";
case INDEX_OUT_OF_RANGE: return "Index is out of range";
case ADDRESS_ALREADY_EXISTS: return "Address already exists";
case TRACKING_MODE: return "The wallet is in tracking mode";
case WRONG_PARAMETERS: return "Wrong parameters passed";
case OBJECT_NOT_FOUND: return "Object not found";
case WALLET_NOT_FOUND: return "Requested wallet not found";
case CHANGE_ADDRESS_REQUIRED: return "Change address required";
case CHANGE_ADDRESS_NOT_FOUND: return "Change address not found";
case DESTINATION_ADDRESS_REQUIRED: return "Destination address required";
case DESTINATION_ADDRESS_NOT_FOUND: return "Destination address not found";
case BAD_PAYMENT_ID: return "Wrong payment id format";
case BAD_TRANSACTION_EXTRA: return "Wrong transaction extra format";
default: return "Unknown error";
}
}
private:
WalletErrorCategory() {
}
};
}
}
inline std::error_code make_error_code(CryptoNote::error::WalletErrorCodes e) {
return std::error_code(static_cast<int>(e), CryptoNote::error::WalletErrorCategory::INSTANCE);
}
namespace std {
template <>
struct is_error_code_enum<CryptoNote::error::WalletErrorCodes>: public true_type {};
}
| [
"[email protected]"
] | |
f003f28b4c5bbbe92bd56fc06907ea94ff2932a5 | c201b2587cae0b3d40a6fe6b8af8db26d9c70fb6 | /Uintah/src/Core/GeometryPiece/SmoothCylGeomPiece.h | eae15ccc472b098a6e54883181520e560897b2ef | [
"MIT"
] | permissive | timondy/PhaseFieldBenchmarking | b97f01637941b789653493f18751e4499aa9ccae | 676382ed149b2441b862bb823738be27814e6b4d | refs/heads/master | 2023-07-13T05:51:13.307900 | 2023-06-29T19:25:47 | 2023-06-29T19:25:47 | 152,245,104 | 10 | 5 | null | 2019-01-10T15:21:34 | 2018-10-09T12:12:46 | C++ | UTF-8 | C++ | false | false | 5,642 | h | /*
* The MIT License
*
* Copyright (c) 1997-2018 The University of Utah
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef __SMOOTH_CYL_PIECE_H__
#define __SMOOTH_CYL_PIECE_H__
#include <Core/GeometryPiece/SmoothGeomPiece.h>
#include <Core/Geometry/Point.h>
#include <cmath>
#ifndef M_PI
# define M_PI 3.14159265358979323846 /* pi */
#endif
namespace Uintah {
/////////////////////////////////////////////////////////////////////////////
/*!
\class SmoothCylGeomPiece
\brief Creates a smooth cylinder with end-caps
\warning Does not allow for correct application of symmetry
boundary conditions. Use symmetry at your own risk.
The end caps are exactly the same diameter as the outer
diameter of the cylinder and are welded perfectly to the
cylinder.
\author Biswajit Banerjee \n
C-SAFE and Department of Mechanical Engineering \n
University of Utah \n
Creates a smooth cylinder with/without end-caps from the
xml input
file description.
The input form for a cylinder looks like this: \n
\verbatim
<smoothcyl>
<bottom>[0.0,0.0,0.0]</bottom>
<top>[0.0,0.0,10.0]</top>
<radius>2.0</radius>
<num_radial>20</num_radial>
<num_axial>100</num_axial>
</smoothcyl>
\endverbatim
The input form for a hollow cylinder with end-caps looks like this: \n
\verbatim
<smoothcyl>
<bottom>[0.0,0.0,0.0]</bottom>
<top>[0.0,0.0,10.0]</top>
<radius>2.0</radius>
<thickness>0.1</thickness>
<endcap_thickness>1.0</endcap_thickness>
<num_radial>20</num_radial>
<num_axial>100</num_axial>
</smoothcyl>
\endverbatim
If the points are to be written to an output file, use the following
\verbatim
<smoothcyl>
<bottom>[0.0,0.0,0.0]</bottom>
<top>[0.0,0.0,10.0]</top>
<radius>2.0</radius>
<thickness>0.1</thickness>
<endcap_thickness>1.0</endcap_thickness>
<num_radial>20</num_radial>
<num_axial>100</num_axial>
<output_file>"fileName"</output_file>
</smoothcyl>
\endverbatim
*/
/////////////////////////////////////////////////////////////////////////////
class SmoothCylGeomPiece : public SmoothGeomPiece {
public:
//////////////////////////////////////////////////////////////////////
/*!
\brief Constructor that takes a ProblemSpecP argument.
It reads the xml input specification and builds a cylinder.
*/
//////////////////////////////////////////////////////////////////////
SmoothCylGeomPiece(ProblemSpecP &);
//////////////////////////////////////////////////////////////////////
/*! Destructor */
//////////////////////////////////////////////////////////////////////
virtual ~SmoothCylGeomPiece();
static const std::string TYPE_NAME;
virtual std::string getType() const { return TYPE_NAME; }
/// Make a clone
virtual GeometryPieceP clone() const;
//////////////////////////////////////////////////////////////////////
/*! Determines whether a point is inside the cylinder. */
//////////////////////////////////////////////////////////////////////
virtual bool inside(const Point &p) const;
//////////////////////////////////////////////////////////////////////
/*! Returns the bounding box surrounding the box. */
//////////////////////////////////////////////////////////////////////
virtual Box getBoundingBox() const;
//////////////////////////////////////////////////////////////////////
/*! Creates the particles */
//////////////////////////////////////////////////////////////////////
virtual unsigned int createPoints();
private:
virtual void outputHelper( ProblemSpecP & ps ) const;
//////////////////////////////////////////////////////////////////////
/*! Creates the particles for the two end caps */
//////////////////////////////////////////////////////////////////////
int createEndCapPoints();
//////////////////////////////////////////////////////////////////////
/*! Creates the particles for the cylinder */
//////////////////////////////////////////////////////////////////////
int createCylPoints();
Point d_top;
Point d_bottom;
double d_outer_radius;
double d_inner_radius;
double d_capThick;
double d_arcStart;
double d_angle;
int d_numRadial;
int d_numAxial;
int d_numAngular;
std::string d_discretization;
std::string d_fileName;
};
} // End namespace Uintah
#endif // __SMOOTH_CYL_PIECE_H__
| [
"jonmatteochurch@lenovo-e580"
] | jonmatteochurch@lenovo-e580 |
96ace658032e3f992cab30097a92f9ceb0f15fb8 | 548d4d5d0413df7ec823a3cc38823a692c52abbd | /scintilla/test/unit/testSparseState.cxx | cbdc1308a81b93128ca18e000a6cfcc7fa141e7f | [
"LicenseRef-scancode-scintilla",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | xuesong/myedit | 04ef39f1435d0e2b9229a16462b8b7934e6052ea | 3adc018e5687752f13f0e983793471e67880f0cf | refs/heads/master | 2020-03-19T01:37:24.917997 | 2018-05-31T08:55:17 | 2018-05-31T08:55:17 | 135,558,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,175 | cxx | // Unit Tests for Scintilla internal data structures
#include <string>
#include <vector>
#include <algorithm>
#include <memory>
#include "Platform.h"
#include "Sci_Position.h"
#include "SparseState.h"
#include "catch.hpp"
using namespace Scintilla;
// Test SparseState.
TEST_CASE("SparseState") {
SparseState<int> ss;
SECTION("IsEmptyInitially") {
REQUIRE(0u == ss.size());
int val = ss.ValueAt(0);
REQUIRE(0 == val);
}
SECTION("SimpleSetAndGet") {
ss.Set(0, 22);
ss.Set(1, 23);
REQUIRE(2u == ss.size());
REQUIRE(0 == ss.ValueAt(-1));
REQUIRE(22 == ss.ValueAt(0));
REQUIRE(23 == ss.ValueAt(1));
REQUIRE(23 == ss.ValueAt(2));
}
SECTION("RetrieveBetween") {
ss.Set(0, 10);
ss.Set(2, 12);
REQUIRE(2u == ss.size());
REQUIRE(0 == ss.ValueAt(-1));
REQUIRE(10 == ss.ValueAt(0));
REQUIRE(10 == ss.ValueAt(1));
REQUIRE(12 == ss.ValueAt(2));
}
SECTION("RetrieveBefore") {
ss.Set(2, 12);
REQUIRE(1u == ss.size());
REQUIRE(0 == ss.ValueAt(-1));
REQUIRE(0 == ss.ValueAt(0));
REQUIRE(0 == ss.ValueAt(1));
REQUIRE(12 == ss.ValueAt(2));
}
SECTION("Delete") {
ss.Set(0, 30);
ss.Set(2, 32);
ss.Delete(2);
REQUIRE(1u == ss.size());
REQUIRE(0 == ss.ValueAt(-1));
REQUIRE(30 == ss.ValueAt(0));
REQUIRE(30 == ss.ValueAt(1));
REQUIRE(30 == ss.ValueAt(2));
}
SECTION("DeleteBetween") {
ss.Set(0, 30);
ss.Set(2, 32);
ss.Delete(1);
REQUIRE(1u == ss.size());
REQUIRE(0 == ss.ValueAt(-1));
REQUIRE(30 == ss.ValueAt(0));
REQUIRE(30 == ss.ValueAt(1));
REQUIRE(30 == ss.ValueAt(2));
}
SECTION("ReplaceLast") {
ss.Set(0, 30);
ss.Set(2, 31);
ss.Set(2, 32);
REQUIRE(2u == ss.size());
REQUIRE(0 == ss.ValueAt(-1));
REQUIRE(30 == ss.ValueAt(0));
REQUIRE(30 == ss.ValueAt(1));
REQUIRE(32 == ss.ValueAt(2));
REQUIRE(32 == ss.ValueAt(3));
}
SECTION("OnlyChangeAppended") {
ss.Set(0, 30);
ss.Set(2, 31);
ss.Set(3, 31);
REQUIRE(2u == ss.size());
}
SECTION("MergeBetween") {
ss.Set(0, 30);
ss.Set(2, 32);
ss.Set(4, 34);
REQUIRE(3u == ss.size());
SparseState<int> ssAdditions(3);
ssAdditions.Set(4, 34);
REQUIRE(1u == ssAdditions.size());
bool mergeChanged = ss.Merge(ssAdditions,5);
REQUIRE(false == mergeChanged);
ssAdditions.Set(4, 44);
REQUIRE(1u == ssAdditions.size());
mergeChanged = ss.Merge(ssAdditions,5);
REQUIRE(true == mergeChanged);
REQUIRE(3u == ss.size());
REQUIRE(44 == ss.ValueAt(4));
}
SECTION("MergeAtExisting") {
ss.Set(0, 30);
ss.Set(2, 32);
ss.Set(4, 34);
REQUIRE(3u == ss.size());
SparseState<int> ssAdditions(4);
ssAdditions.Set(4, 34);
REQUIRE(1u == ssAdditions.size());
bool mergeChanged = ss.Merge(ssAdditions,5);
REQUIRE(false == mergeChanged);
ssAdditions.Set(4, 44);
REQUIRE(1u == ssAdditions.size());
mergeChanged = ss.Merge(ssAdditions,5);
REQUIRE(true == mergeChanged);
REQUIRE(3u == ss.size());
REQUIRE(44 == ss.ValueAt(4));
}
SECTION("MergeWhichRemoves") {
ss.Set(0, 30);
ss.Set(2, 32);
ss.Set(4, 34);
REQUIRE(3u == ss.size());
SparseState<int> ssAdditions(2);
ssAdditions.Set(2, 22);
REQUIRE(1u == ssAdditions.size());
REQUIRE(22 == ssAdditions.ValueAt(2));
bool mergeChanged = ss.Merge(ssAdditions,5);
REQUIRE(true == mergeChanged);
REQUIRE(2u == ss.size());
REQUIRE(22 == ss.ValueAt(2));
}
SECTION("MergeIgnoreSome") {
ss.Set(0, 30);
ss.Set(2, 32);
ss.Set(4, 34);
SparseState<int> ssAdditions(2);
ssAdditions.Set(2, 32);
bool mergeChanged = ss.Merge(ssAdditions,3);
REQUIRE(false == mergeChanged);
REQUIRE(2u == ss.size());
REQUIRE(32 == ss.ValueAt(2));
}
SECTION("MergeIgnoreSomeStart") {
ss.Set(0, 30);
ss.Set(2, 32);
ss.Set(4, 34);
SparseState<int> ssAdditions(2);
ssAdditions.Set(2, 32);
bool mergeChanged = ss.Merge(ssAdditions,2);
REQUIRE(false == mergeChanged);
REQUIRE(2u == ss.size());
REQUIRE(32 == ss.ValueAt(2));
}
SECTION("MergeIgnoreRepeat") {
ss.Set(0, 30);
ss.Set(2, 32);
ss.Set(4, 34);
SparseState<int> ssAdditions(5);
// Appending same value as at end of pss.
ssAdditions.Set(5, 34);
bool mergeChanged = ss.Merge(ssAdditions,6);
REQUIRE(false == mergeChanged);
REQUIRE(3u == ss.size());
REQUIRE(34 == ss.ValueAt(4));
}
}
TEST_CASE("SparseStateString") {
SparseState<std::string> ss;
SECTION("IsEmptyInitially") {
REQUIRE(0u == ss.size());
std::string val = ss.ValueAt(0);
REQUIRE("" == val);
}
SECTION("SimpleSetAndGet") {
REQUIRE(0u == ss.size());
ss.Set(0, "22");
ss.Set(1, "23");
REQUIRE(2u == ss.size());
REQUIRE("" == ss.ValueAt(-1));
REQUIRE("22" == ss.ValueAt(0));
REQUIRE("23" == ss.ValueAt(1));
REQUIRE("23" == ss.ValueAt(2));
}
SECTION("DeleteBetween") {
ss.Set(0, "30");
ss.Set(2, "32");
ss.Delete(1);
REQUIRE(1u == ss.size());
REQUIRE("" == ss.ValueAt(-1));
REQUIRE("30" == ss.ValueAt(0));
REQUIRE("30" == ss.ValueAt(1));
REQUIRE("30" == ss.ValueAt(2));
}
}
| [
"[email protected]"
] | |
00f23451172a2d7761535817b9a6cacce97c89ac | 6ed471f36e5188f77dc61cca24daa41496a6d4a0 | /SDK/C4_FPV_AnimBP_classes.h | ef281476e5a153437c082efd0f39d89cefad4811 | [] | no_license | zH4x-SDK/zARKSotF-SDK | 77bfaf9b4b9b6a41951ee18db88f826dd720c367 | 714730f4bb79c07d065181caf360d168761223f6 | refs/heads/main | 2023-07-16T22:33:15.140456 | 2021-08-27T13:40:06 | 2021-08-27T13:40:06 | 400,521,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | h | #pragma once
// Name: ARKSotF, Version: 178.8.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// AnimBlueprintGeneratedClass C4_FPV_AnimBP.C4_FPV_AnimBP_C
// 0x0000 (0x0914 - 0x0914)
class UC4_FPV_AnimBP_C : public UFPVPlacerWeaponAnimBP_Base_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("AnimBlueprintGeneratedClass C4_FPV_AnimBP.C4_FPV_AnimBP_C");
return ptr;
}
void ExecuteUbergraph_C4_FPV_AnimBP(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
a39dce0fd1ccdd3d2e7a44f831e9bbdd076e15aa | d747f1a0577da9c17512a3ac331c4896e48b4f65 | /src/Tests/binfile/test7.cpp | c782dfcdb88518bb8672679f56c059ec81d08644 | [] | no_license | LenyKholodov/wood | 4cc470bdfe0c0fbc1c6383f91011461ae09d5497 | 3dbb8421acb24546859bbb63884e11173becd1af | refs/heads/master | 2020-04-14T02:13:03.280422 | 2018-12-30T10:20:30 | 2018-12-30T10:20:30 | 163,578,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include <kernel.h>
void main ()
{
K_FastInit ("test7.map");
zipBinFile zip ("test.zip");
SearchFile* s = zip.OpenSearch ("*");
do
cout<<s->name ()<<" "<<s->size ()<<endl;
while (s->next ());
} | [
"[email protected]"
] | |
28a25aa894f59899029cdb65efa5b1d35f6b7730 | 914c61d58282b9e00e8d2426c367eba67512f169 | /labs/lab_10/temperature.h | 9217570ac45d951aab902d472c75ddd239273442 | [] | no_license | Zachary-Rust/Zachary-Rust-CSCI-21 | ab8d6c7b39cf74f826b70055d91408823051a1b9 | 23ea9cf0165f2b3d64656526b861575ac37a1fec | refs/heads/master | 2021-05-09T20:43:40.145431 | 2018-05-20T04:27:35 | 2018-05-20T04:27:35 | 118,703,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,364 | h | /*
* Name : temperature.h
* Author : FILL IN
* Description : Class Header File
*/
#ifndef LAB_H
#define LAB_H
#include <string>
#include <sstream>
using std::string;
using std::stringstream;
/*
* Class Temperature.
* A class that converts temperatures. It will always internally store the value
* in kelvin.
*/
class Temperature {
public:
/*
* Constructor #1.
* Sets kelvin_ to 0
*/
Temperature();
/*
* Constructor #2.
* Sets kelvin_ to the supplied value
* @param double kelvin - The value to set the internal kelvin to
*/
Temperature(double kelvin);
/*
* Constructor #3.
* Converts the supplied temperature to kelvin and internally stores it.
* The temperature's unit will be provided in the second argument.
* If the second argument is not value (i.e. not 'F' or 'C') assume the
* temperature is in kelvin
* @param double temp - The value to set the internal kelvin to once
* - converted.
* @param char unit - The type of unit temp is. Will be either 'F' or 'C',
* case-insensitive
*/
Temperature(double temp, char unit);
/*
* The temperature will come in as kelvin and this function will set the
* internal temp to this value
* @param double kelvin - The value to set the internal kelvin to.
*/
void SetTempFromKelvin(double kelvin);
/*
* The temperature will come in as Celsius and this function will set the
* internal temp to this value, once converted to kelvin
* Formula: k = c + 273.15
* @param double celsius - The value (in celsius) to set the internal kelvin
* - to.
*/
void SetTempFromCelsius(double celsius);
/*
* The temperature will come in as Fahrenheit and this function will set the
* internal temp to this value, once converted to kelvin
* Formula: k = (5.0 * (f - 32) / 9) + 273.15
* @param double fahrenheit - The value (in fahrenheit) to set the internal
* - kelvin to.
*/
void SetTempFromFahrenheit(double fahrenheit);
/*
* Gets the internal temperature in Kelvin.
* @return double - The temperature in Kelvin
*/
double GetTempAsKelvin() const;
/*
* Returns the internal temp converted to Celsius
* Formula: k - 273.15
* @return double - The temperature in Celsius
*/
double GetTempAsCelsius() const;
/*
* Returns the internal temp converted to Fahrenheit
* Formula: ((c * 9.0) / 5) + 32;
* @return double - The temperature in Fahrenheit
*/
double GetTempAsFahrenheit() const;
/*
* Get a string representation of the temperature.
* The string will be formatted as:
* "TEMP UNIT"
* where TEMP is the temperature to 2 decimal places and UNIT is either
* "Kelvin", "Celsius", or "Fahrenheit".
* The conversion to perform is denoted by the parameter.
* If the unit given through the argument is invalid, set the string to:
* "Invalid Unit"
* @uses stringstream
* @param char unit - The conversion to perform, either 'K', 'C' or 'F',
* defaults to 'K' and is case-insensitive
* @return string - A string representation of the temperature or invalid if
* the provided unit is not recognized
*/
string ToString(char unit = 'K') const;
private:
double kelvin_;
};
#endif
| [
"[email protected]"
] | |
236b58d8bd15b0bbc860d3bfaff3c9fae8b5cc15 | 2360d93766dc54f44b540c1053e87fd94a296f3a | /buch/Programme/Kapitel 8/a8_11/3/polygon.h | eb567035bb01e87a01c66ee94df4a44ceb044d53 | [] | no_license | khayrat/3dgrafik | 16a3098355b7395cd71f8bce56b43fafdf91ee20 | dfdf05187f22f77b7eb2e696fc4d6cbfd9b63d97 | refs/heads/master | 2020-07-22T06:29:56.041226 | 2019-09-25T19:20:13 | 2019-09-25T19:20:13 | 207,101,227 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 11,581 | h | #ifndef POLYGON_H
#define POLYGON_H
#include "simple_types.h"
#include "global_definitions.h"
#include "draw_line.h"
#include "bitmap_32.h"
class polygon
{
private:
long point_count, cp_point_count;
point *points;
bitmap_32 surface;
void z_clipping( void );
void project( void );
void xy_clipping( void );
void shape( pixel_32 *sbuffer, pixel_32 color );
void rasterize( pixel_32 *sbuffer );
public:
void load( FILE *input );
void display( vertex *vs, pixel_32 *sbuffer );
polygon( const polygon &p ) { exit_error( "polygon: Aufruf Kopierkonstruktor.\n" ); }
polygon( void ) : point_count( 0 ), cp_point_count( 0 ), points( NULL ) { }
~polygon( void ) { if( points ) delete [] points; }
};
tvertex get_zplane_coords( tvertex a, tvertex b, double plane_z )
{
double m = (plane_z - b.wz) / (a.wz - b.wz);
tvertex c;
c.wx = (a.wx - b.wx) * m + b.wx;
c.wy = (a.wy - b.wy) * m + b.wy;
c.wz = plane_z;
c.tx = m * (a.tx - b.tx) + b.tx;
c.ty = m * (a.ty - b.ty) + b.ty;
return c;
}
void polygon::z_clipping( void )
{
long x, y;
long local_point_count = 0;
for( x=point_count-1, y=0 ; y<point_count ; x=y, y++ )
{
if( wpoint[ x ].wz >= z_min && wpoint[ y ].wz >= z_min ) // inside
c_wpoint[ local_point_count++ ] = wpoint[ y ];
else if( wpoint[ x ].wz >= z_min && wpoint[ y ].wz < z_min ) // leaving
c_wpoint[ local_point_count++ ] = get_zplane_coords( wpoint[ x ], wpoint[ y ], z_min );
else if( wpoint[ x ].wz < z_min && wpoint[ y ].wz >= z_min ) // entering
{
c_wpoint[ local_point_count++ ] = get_zplane_coords( wpoint[ x ], wpoint[ y ], z_min );
c_wpoint[ local_point_count++ ] = wpoint[ y ];
}
}
cp_point_count = 0;
for( x=local_point_count-1, y=0 ; y<local_point_count ; x=y, y++ )
{
if( c_wpoint[ x ].wz <= z_max && c_wpoint[ y ].wz <= z_max ) // inside
wpoint[ cp_point_count++ ] = c_wpoint[ y ];
else if( c_wpoint[ x ].wz <= z_max && c_wpoint[ y ].wz > z_max ) // leaving
wpoint[ cp_point_count++ ] = get_zplane_coords( c_wpoint[ x ], c_wpoint[ y ], z_max );
else if( c_wpoint[ x ].wz > z_max && c_wpoint[ y ].wz <= z_max ) // entering
{
wpoint[ cp_point_count++ ] = get_zplane_coords( c_wpoint[ x ], c_wpoint[ y ], z_max );
wpoint[ cp_point_count++ ] = c_wpoint[ y ];
}
}
}
void polygon::project( void )
{
for( long x=0 ; x<cp_point_count ; x++ )
{
if( wpoint[ x ].wz <= 0.0 ) exit_error( "polygon_project(): Ungültige z-Koordinate.\n" );
double inv_z = 1.0 / wpoint[ x ].wz;
spoint[ x ].sx = long( wpoint[ x ].wx * inv_z * pr_cnst + x_res/2 );
spoint[ x ].sy = long( wpoint[ x ].wy * inv_z * -pr_cnst + y_res/2 );
spoint[ x ].sz = inv_z + clear_translation;
spoint[ x ].tx = (wpoint[ x ].tx * tx_scale + tx_translation) * inv_z;
spoint[ x ].ty = (wpoint[ x ].ty * ty_scale + ty_translation) * inv_z;
}
}
svertex get_xplane_coords( svertex a, svertex b, long plane_x )
{
double m = (plane_x - b.sx) / double( a.sx - b.sx );
svertex c;
c.sx = plane_x;
c.sy = long( (a.sy - b.sy) * m + b.sy );
c.sz = (a.sz - b.sz) * m + b.sz;
c.tx = m * (a.tx - b.tx) + b.tx;
c.ty = m * (a.ty - b.ty) + b.ty;
return c;
}
svertex get_yplane_coords( svertex a, svertex b, long plane_y )
{
double m = (plane_y - b.sy) / double( a.sy - b.sy );
svertex c;
c.sx = long( (a.sx - b.sx) * m + b.sx );
c.sy = plane_y;
c.sz = (a.sz - b.sz) * m + b.sz;
c.tx = m * (a.tx - b.tx) + b.tx;
c.ty = m * (a.ty - b.ty) + b.ty;
return c;
}
void polygon::xy_clipping( void )
{
long x, y;
long local_point_count = 0;
for( x=cp_point_count-1, y=0 ; y<cp_point_count ; x=y, y++ )
{
if( spoint[ x ].sx >= x_min && spoint[ y ].sx >= x_min ) // inside
c_spoint[ local_point_count++ ] = spoint[ y ];
else if( spoint[ x ].sx >= x_min && spoint[ y ].sx < x_min ) // leaving
c_spoint[ local_point_count++ ] = get_xplane_coords( spoint[ x ], spoint[ y ], x_min );
else if( spoint[ x ].sx < x_min && spoint[ y ].sx >= x_min ) // entering
{
c_spoint[ local_point_count++ ] = get_xplane_coords( spoint[ x ], spoint[ y ], x_min );
c_spoint[ local_point_count++ ] = spoint[ y ];
}
}
cp_point_count = 0;
for( x=local_point_count-1, y=0 ; y<local_point_count ; x=y, y++ )
{
if( c_spoint[ x ].sx <= x_max && c_spoint[ y ].sx <= x_max ) // inside
spoint[ cp_point_count++ ] = c_spoint[ y ];
else if( c_spoint[ x ].sx <= x_max && c_spoint[ y ].sx > x_max ) // leaving
spoint[ cp_point_count++ ] = get_xplane_coords( c_spoint[ x ], c_spoint[ y ], x_max );
else if( c_spoint[ x ].sx > x_max && c_spoint[ y ].sx <= x_max ) // entering
{
spoint[ cp_point_count++ ] = get_xplane_coords( c_spoint[ x ], c_spoint[ y ], x_max );
spoint[ cp_point_count++ ] = c_spoint[ y ];
}
}
local_point_count = 0;
for( x=cp_point_count-1, y=0 ; y<cp_point_count ; x=y, y++ )
{
if( spoint[ x ].sy >= y_min && spoint[ y ].sy >= y_min ) // inside
c_spoint[ local_point_count++ ] = spoint[ y ];
else if( spoint[ x ].sy >= y_min && spoint[ y ].sy < y_min ) // leaving
c_spoint[ local_point_count++ ] = get_yplane_coords( spoint[ x ], spoint[ y ], y_min );
else if( spoint[ x ].sy < y_min && spoint[ y ].sy >= y_min ) // entering
{
c_spoint[ local_point_count++ ] = get_yplane_coords( spoint[ x ], spoint[ y ], y_min );
c_spoint[ local_point_count++ ] = spoint[ y ];
}
}
cp_point_count = 0;
for( x=local_point_count-1, y=0 ; y<local_point_count ; x=y, y++ )
{
if( c_spoint[ x ].sy <= y_max && c_spoint[ y ].sy <= y_max ) // inside
spoint[ cp_point_count++ ] = c_spoint[ y ];
else if( c_spoint[ x ].sy <= y_max && c_spoint[ y ].sy > y_max ) // leaving
spoint[ cp_point_count++ ] = get_yplane_coords( c_spoint[ x ], c_spoint[ y ], y_max );
else if( c_spoint[ x ].sy > y_max && c_spoint[ y ].sy <= y_max ) // entering
{
spoint[ cp_point_count++ ] = get_yplane_coords( c_spoint[ x ], c_spoint[ y ], y_max );
spoint[ cp_point_count++ ] = c_spoint[ y ];
}
}
}
void polygon::display( vertex *vs, pixel_32 *sbuffer )
{
for( long x=0 ; x<point_count ; x++ )
{
wpoint[ x ].wx = vs[ points[ x ].vertex_offset ].wx;
wpoint[ x ].wy = vs[ points[ x ].vertex_offset ].wy;
wpoint[ x ].wz = vs[ points[ x ].vertex_offset ].wz;
wpoint[ x ].tx = points[ x ].tx;
wpoint[ x ].ty = points[ x ].ty;
}
z_clipping();
project();
xy_clipping(); if( !cp_point_count ) return;
surface.display( 0, 0, sbuffer );
rasterize( sbuffer );
}
void set_side( svertex begin, svertex end, screen_side *side )
{
long length = end.sy - begin.sy;
if( length <= 0 )
{
side[ begin.sy ].offset = begin.sy * x_res + begin.sx;
return;
}
double a_offset = double( begin.sy * x_res + begin.sx );
double e_offset = double( end.sy * x_res + end.sx );
double offset_step = ( e_offset - a_offset ) / length;
double z_step = (end.sz - begin.sz) / length;
double tx_step = (end.tx - begin.tx) / length;
double ty_step = (end.ty - begin.ty) / length;
double act_z = begin.sz;
double act_tx = begin.tx;
double act_ty = begin.ty;
for( long act_y=begin.sy ; act_y <= end.sy ; act_y++ )
{
side[ act_y ].offset = long( a_offset + 0.5 );
side[ act_y ].sz = act_z;
side[ act_y ].tx = act_tx; side[ act_y ].ty = act_ty;
a_offset += offset_step;
act_z += z_step;
act_tx += tx_step; act_ty += ty_step;
}
}
inline void inc( long *x, long point_count )
{
(*x)++;
if( (*x) >= point_count ) *x = 0;
}
inline void dec( long *x, long point_count )
{
(*x)--;
if( (*x) < 0 ) *x = point_count-1;
}
void polygon::rasterize( pixel_32 *sbuffer )
{
long x, y, top=0, bottom=0;
for( x=1 ; x<cp_point_count ; x++ )
{
if( spoint[ top ].sy > spoint[ x ].sy ) top = x;
if( spoint[ bottom ].sy < spoint[ x ].sy ) bottom = x;
}
x = y = top;
for( dec( &y, cp_point_count ) ; x!=bottom ; x=y, dec( &y, cp_point_count ) )
set_side( spoint[ x ], spoint[ y ], left_side );
x = y = top;
for( inc( &y, cp_point_count ) ; x!=bottom ; x=y, inc( &y, cp_point_count ) )
set_side( spoint[ x ], spoint[ y ], right_side );
long m = (spoint[ bottom ].sy + spoint[ top ].sy) / 2;
if( left_side[ m ].offset > right_side[ m ].offset )
{
screen_side *t = left_side; left_side = right_side; right_side = t;
}
long length, offset;
double act_z, z_step;
double act_tx, act_ty, tx_step, ty_step;
for( y = spoint[ top ].sy ; y <= spoint[ bottom ].sy ; y++ )
{
length = right_side[ y ].offset - left_side[ y ].offset;
if( length <= 0 ) continue;
z_step = (right_side[ y ].sz - left_side[ y ].sz) / length;
tx_step =(right_side[ y ].tx - left_side[ y ].tx) / length;
ty_step =(right_side[ y ].ty - left_side[ y ].ty) / length;
offset = left_side[ y ].offset;
act_z = left_side[ y ].sz;
act_tx = left_side[ y ].tx; act_ty = left_side[ y ].ty;
while( length-- > 0 )
{
if( act_z > zbuffer[ offset ] )
{
double z = 1.0 / (act_z - clear_translation);
long tx = long( act_tx * (surface.xscale-1) * z ) % surface.xscale; if( tx < 0 ) tx += surface.xscale;
long ty = long( act_ty * (surface.yscale-1) * z ) % surface.yscale; if( ty < 0 ) ty += surface.yscale;
sbuffer[ offset ] = surface.picture[ ty * surface.xscale + tx ];
zbuffer[ offset ] = act_z;
}
offset++;
act_z += z_step;
act_tx += tx_step; act_ty += ty_step;
}
}
}
void polygon::shape( pixel_32 *sbuffer, pixel_32 color )
{
long x, y;
for( x=cp_point_count-1, y=0 ; y<cp_point_count ; x=y, y++ )
draw_line( spoint[ x ], spoint[ y ], color, sbuffer );
}
void polygon::load( FILE *input )
{
fscanf( input, "%ld", &point_count );
if( (points = new point[ point_count ]) == NULL )
exit_error( "*points: Fehler bei der Reservierung von Arbeitsspeicher.\n" );
if( point_count != 4 ) exit_error( "polygon::load: Es werden lediglich viereckige Polygone unterstützt.\n" );
long x;
for( x=0 ; x<point_count ; x++ )
fscanf( input, "%ld", &points[ x ].vertex_offset );
char filename[ 100 ];
fscanf( input, "%s", filename );
surface.load( filename );
points[ 0 ].tx = 0; points[ 0 ].ty = 0;
points[ 1 ].tx = 1; points[ 1 ].ty = 0;
points[ 2 ].tx = 1; points[ 2 ].ty = 1;
points[ 3 ].tx = 0; points[ 3 ].ty = 1;
}
#endif | [
"[email protected]"
] | |
ee47d4e261f7cf4e317aa6aca6620ab3c5944c20 | 473fc28d466ddbe9758ca49c7d4fb42e7d82586e | /app/src/main/java/com/syd/source/aosp/external/parameter-framework/upstream/test/test-subsystem/TESTSubsystemBuilder.cpp | 6ec062e03615819a28148efe0b326a4bd384a5e4 | [
"BSD-3-Clause",
"BSL-1.0"
] | permissive | lz-purple/Source | a7788070623f2965a8caa3264778f48d17372bab | e2745b756317aac3c7a27a4c10bdfe0921a82a1c | refs/heads/master | 2020-12-23T17:03:12.412572 | 2020-01-31T01:54:37 | 2020-01-31T01:54:37 | 237,205,127 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,919 | cpp | /*
* Copyright (c) 2011-2015, Intel Corporation
* 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.
*/
#include "Plugin.h"
#include "LoggingElementBuilderTemplate.h"
#include "TESTSubsystem.h"
void PARAMETER_FRAMEWORK_PLUGIN_ENTRYPOINT_V1(CSubsystemLibrary *pSubsystemLibrary,
core::log::Logger &logger)
{
pSubsystemLibrary->addElementBuilder(
"TEST", new TLoggingElementBuilderTemplate<CTESTSubsystem>(logger));
}
| [
"[email protected]"
] | |
0e2ba65fa5889feb33d85451b13e7b48fef69097 | 611d7ddb49a9814677d2126995d3751d0e127d5f | /PTA/PTA/1142.cpp | ba745d2c1fa5647ad5577f0583c3d793c113ba0d | [] | no_license | WYWAshley/PTA | f22df2c8d8a26701b3bb9cf4bb0e4be77759d2dd | 6fa3a107240b162e0b4c3e2bba7c4964d84a6348 | refs/heads/master | 2022-04-03T14:37:54.845040 | 2020-01-17T06:48:42 | 2020-01-17T06:48:42 | 206,225,124 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,075 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
using namespace std;
int Q1142()
{
int nV, nE;
scanf("%d %d", &nV, &nE);
vector<vector<int>> edge(nV + 1);
for (int i = 0; i<nE; i++) {
int a, b;
scanf("%d %d", &a, &b);
edge[a].push_back(b);
edge[b].push_back(a);
}
int qnum;
scanf("%d", &qnum);
for (int i = 0; i<qnum; i++) {
int tnum;
scanf("%d", &tnum);
bool flag = true;
vector<int> temp(nV + 1, 0);
vector<bool> temp2(nV + 1, false);
for (int j = 0; j<tnum; j++) {
int now;
scanf("%d", &now);
temp2[now] = true;
for (int k = 0; k<edge[now].size(); k++) {
temp[edge[now][k]]++;
}
}
for (int j = 1; j<nV + 1; j++) {//检查是不是clique
if (temp2[j] && temp[j] < tnum - 1) {
printf("Not a Clique\n");
flag = false;
break;
}
}
if (!flag) continue;
for (int j = 1; j<nV + 1; j++) {//检查是不是maximal
if (!temp2[j] && temp[j] == tnum) {
printf("Not Maximal\n");
flag = false;
break;
}
}
if (flag)
printf("Yes\n");
}
system("pause");
return 0;
}
| [
"[email protected]"
] | |
41e9cc3a6ad4fea6e2c2d4d3892e3828c39da24f | 148b158ab7c85b3dc8a7b560ed5af0100bdc96fe | /eurobot2015/eurobot2015_petit_nav/src/petit_drive_roboclaw.cpp | c7c345a97f7a8f85bdd2f8158799164d43010c4a | [] | no_license | JBot/smart-robotics-ros-pkg | 54f48d2a95199fa1b63bb9cf8d55bfee5b37ab8f | 8e9571f9af5062c4a0e6ad8336ad737bfa702e23 | refs/heads/master | 2021-01-18T21:11:35.593369 | 2016-05-08T11:23:32 | 2016-05-08T11:23:32 | 1,266,955 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 18,447 | cpp | #include "ros/ros.h"
#include "geometry_msgs/Pose.h"
#include "geometry_msgs/PoseStamped.h"
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <nav_msgs/Odometry.h>
#include <std_msgs/Float32.h>
#include <geometry_msgs/Twist.h>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <sstream>
#include <math.h>
#include <vector>
#ifdef USE_BOOST
#include <boost/asio.hpp>
#include <boost/asio/serial_port.hpp>
#include <boost/array.hpp>
#else
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitionss
#include <time.h> // time calls
#endif
#define theta1 (3.14159265359 - 2.09439510239)
#define theta2 (3.14159265359)
#define theta3 (3.14159265359 + 2.09439510239)
#define R (0.09)
#define RAYON (0.03)
class DriveRoboClaw {
public:
DriveRoboClaw();
void rotate(int32_t speed);
void write_RoboClaw_forward_M1(char addr, int32_t speed);
void write_RoboClaw_backward_M1(char addr, int32_t speed);
void write_RoboClaw_forward_M2(char addr, int32_t speed);
void write_RoboClaw_backward_M2(char addr, int32_t speed);
void write_RoboClaw_PID_M1(char addr, int32_t D, int32_t P, int32_t I, int32_t QQPS);
void write_RoboClaw_PID_M2(char addr, int32_t D, int32_t P, int32_t I, int32_t QQPS);
void write_RoboClaw_drive_M1(char addr, int32_t speed);
void write_RoboClaw_drive_M2(char addr, int32_t speed);
void write_RoboClaw_speed_M1(char addr, int32_t speed);
void write_RoboClaw_speed_M2(char addr, int32_t speed);
void write_RoboClaw_speed_M1M2(char addr, int32_t speedM1, int32_t speedM2);
void write_RoboClaw_speed_dist_M1M2(char addr, int32_t speedM1, int32_t distanceM1, int32_t speedM2, int32_t distanceM2);
double speed_motor1;
double speed_motor2;
double speed_motor3;
double speed_motor4;
private:
void velCallback(const geometry_msgs::Twist::ConstPtr& vel);
void compute_motor_speed(double x, double y, double z);
ros::NodeHandle nh;
ros::Subscriber vel_sub;
#ifdef USE_BOOST
std::string port_; ///< @brief The serial port the driver is attached to
uint32_t baud_rate_; ///< @brief The baud rate for the serial connection
boost::shared_ptr<boost::asio::serial_port> serial_;
boost::asio::io_service io;
boost::array < uint8_t, 16 > raw_bytes_;
boost::array < uint8_t, 2 > speed_;
#else
int fd; // file description for the serial port
struct termios port_settings; // structure to store the port settings in
#endif
};
DriveRoboClaw::DriveRoboClaw()
{
#ifdef USE_BOOST
port_="/dev/ttyUSB0";
baud_rate_=38400;
try {
//boost::asio::serial_port serial_(io, port_);
serial_ = boost::shared_ptr<boost::asio::serial_port>(new boost::asio::serial_port(io, port_));
//serial_.set_option(boost::asio::serial_port_base::baud_rate(baud_rate_));
//boost::asio::write(serial_,boost::asio::buffer(sendThis,1));
serial_->set_option(boost::asio::serial_port_base::character_size(8));
serial_->set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
serial_->set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
serial_->set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));
}
catch(boost::system::system_error ex) {
ROS_ERROR("Error instantiating laser object. Are you sure you have the correct port and baud rate? Error was %s", ex.what());
//return -1;
}
#else
//fd = open("/dev/ttyROBOCLAW", O_RDWR | O_NOCTTY | O_NDELAY);
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1) // if open is unsucessful
{
//perror("open_port: Unable to open /dev/ttyS0 - ");
printf("open_port: Unable to open /dev/ttyROBOCLAW. \n");
}
else
{
fcntl(fd, F_SETFL, 0);
printf("port is open.\n");
}
cfsetispeed(&port_settings, B38400); // set baud rates
cfsetospeed(&port_settings, B38400);
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port
#endif
speed_motor1 = 0;
speed_motor2 = 0;
speed_motor3 = 0;
speed_motor4 = 0;
vel_sub = nh.subscribe<geometry_msgs::Twist>("cmd_vel", 1, &DriveRoboClaw::velCallback, this);
//write_RoboClaw_PID_M1(128, 16384, 65536, 32768, 44000);
//write_RoboClaw_PID_M2(128, 0x00004000, 0x00010000, 0x00008000, 44000);
write_RoboClaw_PID_M1(128, 90384, 170536, 100768, 80000); // 94000 // 120000
write_RoboClaw_PID_M2(128, 90384, 170536, 100768, 80000);
write_RoboClaw_PID_M1(129, 90384, 170536, 100768, 80000);
write_RoboClaw_PID_M2(129, 90384, 170536, 100768, 80000);
}
void DriveRoboClaw::velCallback(const geometry_msgs::Twist::ConstPtr& vel)
{
compute_motor_speed(vel->linear.x, vel->linear.y, vel->angular.z);
write_RoboClaw_speed_M1M2(128, int32_t(speed_motor1 * 3200.0), -int32_t(speed_motor2 * 3200.0));
write_RoboClaw_speed_M1M2(129, -int32_t(speed_motor3 * 3200.0), int32_t(speed_motor4 * 3200.0));
//write_RoboClaw_speed_M1M2(129, -int32_t(speed_motor3 * 3200.0), int32_t(speed_motor4 * 3200.0));
}
void DriveRoboClaw::compute_motor_speed(double x, double y, double z)
{
//speed_motor1 = x * 6 - z * 3;
//speed_motor2 = x * 6 + z * 3;
speed_motor1 = x * 20 - y * 20 + z * 10;
speed_motor2 = x * 20 + y * 20 + z * 10;
speed_motor3 = x * 20 - y * 20 - z * 10;
speed_motor4 = x * 20 + y * 20 - z * 10;
printf("speed_motor1 : %f speed_motor2 : %f speed_motor3 : %f speed_motor4 : %f \n", speed_motor1, speed_motor2, speed_motor3, speed_motor4);
}
/***********************/
/* ROBO CLAW FUNCTIONS */
/***********************/
/* Without ENCODERS */
// Used to change the speed value of motor 1
void DriveRoboClaw::write_RoboClaw_forward_M1(char addr, int32_t speed)
{
char checkSUM;
checkSUM =
(addr + 0 + ((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[4];
commands[0] = addr;
commands[1] = 0;
commands[2] = ((char) (speed & 0xFF));
commands[3] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 4));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 4); //Send data
#endif
}
// Used to change the speed value of motor 1
void DriveRoboClaw::write_RoboClaw_backward_M1(char addr, int32_t speed)
{
char checkSUM;
checkSUM =
(addr + 1 + ((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[4];
commands[0] = addr;
commands[1] = 1;
commands[2] = ((char) (speed & 0xFF));
commands[3] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 4));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 4); //Send data
#endif
}
// Used to change the speed value of motor 2
void DriveRoboClaw::write_RoboClaw_forward_M2(char addr, int32_t speed)
{
char checkSUM;
checkSUM =
(addr + 4 + ((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[4];
commands[0] = addr;
commands[1] = 4;
commands[2] = ((char) (speed & 0xFF));
commands[3] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 4));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 4); //Send data
#endif
}
// Used to change the speed value of motor 2
void DriveRoboClaw::write_RoboClaw_backward_M2(char addr, int32_t speed)
{
char checkSUM;
checkSUM =
(addr + 5 + ((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[4];
commands[0] = addr;
commands[1] = 5;
commands[2] = ((char) (speed & 0xFF));
commands[3] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 4));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 4); //Send data
#endif
}
// Used to change the speed value of motor 2
void DriveRoboClaw::write_RoboClaw_drive_M1(char addr, int32_t speed)
{
char checkSUM;
checkSUM =
(addr + 6 + ((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[4];
commands[0] = addr;
commands[1] = 6;
commands[2] = ((char) (speed & 0xFF));
commands[3] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 4));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 4); //Send data
#endif
}
// Used to change the speed value of motor 2
void DriveRoboClaw::write_RoboClaw_drive_M2(char addr, int32_t speed)
{
char checkSUM;
checkSUM =
(addr + 7 + ((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[4];
commands[0] = addr;
commands[1] = 7;
commands[2] = ((char) (speed & 0xFF));
commands[3] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 4));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 4); //Send data
#endif
}
/* With ENCODERS */
// of motor 1
void DriveRoboClaw::write_RoboClaw_PID_M1(char addr, int32_t D, int32_t P, int32_t I, int32_t QQPS)
{
char checkSUM;
checkSUM =
(addr + 28 + ((char) ((D >> 24) & 0xFF)) +
((char) ((D >> 16) & 0xFF)) + ((char) ((D >> 8) & 0xFF)) +
((char) (D & 0xFF)) + ((char) ((P >> 24) & 0xFF)) +
((char) ((P >> 16) & 0xFF)) + ((char) ((P >> 8) & 0xFF)) +
((char) (P & 0xFF)) + ((char) ((I >> 24) & 0xFF)) +
((char) ((I >> 16) & 0xFF)) + ((char) ((I >> 8) & 0xFF)) +
((char) (I & 0xFF)) + ((char) ((QQPS >> 24) & 0xFF)) +
((char) ((QQPS >> 16) & 0xFF)) + ((char) ((QQPS >> 8) & 0xFF)) +
((char) (QQPS & 0xFF))) & 0x7F;
unsigned char commands[19];
commands[0] = addr;
commands[1] = 28;
commands[2] = ((char) ((D >> 24) & 0xFF));
commands[3] = ((char) ((D >> 16) & 0xFF));
commands[4] = ((char) ((D >> 8) & 0xFF));
commands[5] = ((char) (D & 0xFF));
commands[6] = ((char) ((P >> 24) & 0xFF));
commands[7] = ((char) ((P >> 16) & 0xFF));
commands[8] = ((char) ((P >> 8) & 0xFF));
commands[9] = ((char) (P & 0xFF));
commands[10] = ((char) ((I >> 24) & 0xFF));
commands[11] = ((char) ((I >> 16) & 0xFF));
commands[12] = ((char) ((I >> 8) & 0xFF));
commands[13] = ((char) (I & 0xFF));
commands[14] = ((char) ((QQPS >> 24) & 0xFF));
commands[15] = ((char) ((QQPS >> 16) & 0xFF));
commands[16] = ((char) ((QQPS >> 8) & 0xFF));
commands[17] = ((char) (QQPS & 0xFF));
commands[18] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 19));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 19); //Send data
#endif
}
// of motor 2
void DriveRoboClaw::write_RoboClaw_PID_M2(char addr, int32_t D, int32_t P, int32_t I, int32_t QQPS)
{
char checkSUM;
checkSUM =
(addr + 29 + ((char) ((D >> 24) & 0xFF)) +
((char) ((D >> 16) & 0xFF)) + ((char) ((D >> 8) & 0xFF)) +
((char) (D & 0xFF)) + ((char) ((P >> 24) & 0xFF)) +
((char) ((P >> 16) & 0xFF)) + ((char) ((P >> 8) & 0xFF)) +
((char) (P & 0xFF)) + ((char) ((I >> 24) & 0xFF)) +
((char) ((I >> 16) & 0xFF)) + ((char) ((I >> 8) & 0xFF)) +
((char) (I & 0xFF)) + ((char) ((QQPS >> 24) & 0xFF)) +
((char) ((QQPS >> 16) & 0xFF)) + ((char) ((QQPS >> 8) & 0xFF)) +
((char) (QQPS & 0xFF))) & 0x7F;
unsigned char commands[19];
commands[0] = addr;
commands[1] = 29;
commands[2] = ((char) ((D >> 24) & 0xFF));
commands[3] = ((char) ((D >> 16) & 0xFF));
commands[4] = ((char) ((D >> 8) & 0xFF));
commands[5] = ((char) (D & 0xFF));
commands[6] = ((char) ((P >> 24) & 0xFF));
commands[7] = ((char) ((P >> 16) & 0xFF));
commands[8] = ((char) ((P >> 8) & 0xFF));
commands[9] = ((char) (P & 0xFF));
commands[10] = ((char) ((I >> 24) & 0xFF));
commands[11] = ((char) ((I >> 16) & 0xFF));
commands[12] = ((char) ((I >> 8) & 0xFF));
commands[13] = ((char) (I & 0xFF));
commands[14] = ((char) ((QQPS >> 24) & 0xFF));
commands[15] = ((char) ((QQPS >> 16) & 0xFF));
commands[16] = ((char) ((QQPS >> 8) & 0xFF));
commands[17] = ((char) (QQPS & 0xFF));
commands[18] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 19));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 19); //Send data
#endif
}
// Used to change the speed value of motor 1
void DriveRoboClaw::write_RoboClaw_speed_M1(char addr, int32_t speed)
{
char checkSUM;
checkSUM =
(addr + 35 + ((char) ((speed >> 24) & 0xFF)) +
((char) ((speed >> 16) & 0xFF)) + ((char) ((speed >> 8) & 0xFF)) +
((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[7];
commands[0] = addr;
commands[1] = 35;
commands[2] = ((char) ((speed >> 24) & 0xFF));
commands[3] = ((char) ((speed >> 16) & 0xFF));
commands[4] = ((char) ((speed >> 8) & 0xFF));
commands[5] = ((char) (speed & 0xFF));
commands[6] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 7));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 7); //Send data
#endif
}
// Used to change the speed value of motor 2
void DriveRoboClaw::write_RoboClaw_speed_M2(char addr, int32_t speed)
{
char checkSUM;
checkSUM =
(addr + 36 + ((char) ((speed >> 24) & 0xFF)) +
((char) ((speed >> 16) & 0xFF)) + ((char) ((speed >> 8) & 0xFF)) +
((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[7];
commands[0] = addr;
commands[1] = 36;
commands[2] = ((char) ((speed >> 24) & 0xFF));
commands[3] = ((char) ((speed >> 16) & 0xFF));
commands[4] = ((char) ((speed >> 8) & 0xFF));
commands[5] = ((char) (speed & 0xFF));
commands[6] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 7));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 7); //Send data
#endif
}
// Used to change the speed value of motors 1 and 2
void DriveRoboClaw::write_RoboClaw_speed_M1M2(char addr, int32_t speedM1, int32_t speedM2)
{
char checkSUM;
checkSUM =
(addr + 37 + ((char) ((speedM1 >> 24) & 0xFF)) +
((char) ((speedM1 >> 16) & 0xFF)) +
((char) ((speedM1 >> 8) & 0xFF)) + ((char) (speedM1 & 0xFF)) +
((char) ((speedM2 >> 24) & 0xFF)) +
((char) ((speedM2 >> 16) & 0xFF)) +
((char) ((speedM2 >> 8) & 0xFF)) +
((char) (speedM2 & 0xFF))) & 0x7F;
unsigned char commands[11];
commands[0] = addr;
commands[1] = 37;
commands[2] = ((char) ((speedM1 >> 24) & 0xFF));
commands[3] = ((char) ((speedM1 >> 16) & 0xFF));
commands[4] = ((char) ((speedM1 >> 8) & 0xFF));
commands[5] = ((char) (speedM1 & 0xFF));
commands[6] = ((char) ((speedM2 >> 24) & 0xFF));
commands[7] = ((char) ((speedM2 >> 16) & 0xFF));
commands[8] = ((char) ((speedM2 >> 8) & 0xFF));
commands[9] = ((char) (speedM2 & 0xFF));
commands[10] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 11));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 11); //Send data
#endif
}
// Used to change the speed value of motor 1 and 2 during a specific distance
void DriveRoboClaw::write_RoboClaw_speed_dist_M1M2(char addr, int32_t speedM1,
int32_t distanceM1,
int32_t speedM2,
int32_t distanceM2)
{
char checkSUM;
checkSUM =
(addr + 43 + ((char) ((speedM1 >> 24) & 0xFF)) +
((char) ((speedM1 >> 16) & 0xFF)) +
((char) ((speedM1 >> 8) & 0xFF)) + ((char) (speedM1 & 0xFF)) +
((char) ((speedM2 >> 24) & 0xFF)) +
((char) ((speedM2 >> 16) & 0xFF)) +
((char) ((speedM2 >> 8) & 0xFF)) + ((char) (speedM2 & 0xFF)) +
((char) ((distanceM1 >> 24) & 0xFF)) +
((char) ((distanceM1 >> 16) & 0xFF)) +
((char) ((distanceM1 >> 8) & 0xFF)) +
((char) (distanceM1 & 0xFF)) +
((char) ((distanceM2 >> 24) & 0xFF)) +
((char) ((distanceM2 >> 16) & 0xFF)) +
((char) ((distanceM2 >> 8) & 0xFF)) +
((char) (distanceM2 & 0xFF)) + 1) & 0x7F;
unsigned char commands[20];
commands[0] = addr;
commands[1] = 43;
commands[2] = ((char) ((speedM1 >> 24) & 0xFF));
commands[3] = ((char) ((speedM1 >> 16) & 0xFF));
commands[4] = ((char) ((speedM1 >> 8) & 0xFF));
commands[5] = ((char) (speedM1 & 0xFF));
commands[6] = ((char) ((distanceM1 >> 24) & 0xFF));
commands[7] = ((char) ((distanceM1 >> 16) & 0xFF));
commands[8] = ((char) ((distanceM1 >> 8) & 0xFF));
commands[9] = ((char) (distanceM1 & 0xFF));
commands[10] = ((char) ((speedM2 >> 24) & 0xFF));
commands[11] = ((char) ((speedM2 >> 16) & 0xFF));
commands[12] = ((char) ((speedM2 >> 8) & 0xFF));
commands[13] = ((char) (speedM2 & 0xFF));
commands[14] = ((char) ((distanceM2 >> 24) & 0xFF));
commands[15] = ((char) ((distanceM2 >> 16) & 0xFF));
commands[16] = ((char) ((distanceM2 >> 8) & 0xFF));
commands[17] = ((char) (distanceM2 & 0xFF));
commands[18] = 1;
commands[19] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 20));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 20); //Send data
#endif
}
void DriveRoboClaw::rotate(int32_t speed)
{
char checkSUM;
checkSUM =
(128 + 35 + ((char) ((speed >> 24) & 0xFF)) +
((char) ((speed >> 16) & 0xFF)) + ((char) ((speed >> 8) & 0xFF)) +
((char) (speed & 0xFF))) & 0x7F;
unsigned char commands[7];
commands[0] = 128;
commands[1] = 35;
commands[2] = ((char) ((speed >> 24) & 0xFF));
commands[3] = ((char) ((speed >> 16) & 0xFF));
commands[4] = ((char) ((speed >> 8) & 0xFF));
commands[5] = ((char) (speed & 0xFF));
commands[6] = checkSUM;
#ifdef USE_BOOST
serial_->write_some(boost::asio::buffer(commands, 7));
//boost::asio::write(serial_,boost::asio::buffer(commands,4));
#else
write(fd, commands, 7); //Send data
#endif
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "RoboClaw_Driver");
DriveRoboClaw drive;
// Refresh rate
ros::Rate loop_rate(60); // 35 with bluetooth
while (ros::ok()) {
ros::spinOnce();
loop_rate.sleep();
}
ros::Duration(2.0).sleep();
ros::shutdown();
}
| [
"[email protected]"
] | |
88e1a6037e83529ff05d3d1bd156487ea9ba1dae | f09f7c3b6167bc45494fad928976feccb3b1f8a0 | /code/userprog/addrspace.h | e4c7a44dbc308c6ffe9884f25c70d1ff9a24a9ac | [
"MIT-Modern-Variant"
] | permissive | EslamJamal/NachOS | e17e330f80d98ea2593217432379c503eacf8274 | 04bf3d559db57b340d856a76d2ad61fb28145565 | refs/heads/main | 2023-07-29T02:38:20.703135 | 2021-09-05T21:12:31 | 2021-09-05T21:12:31 | 403,413,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,469 | h | // addrspace.h
// Data structures to keep track of executing user programs
// (address spaces).
//
// For now, we don't keep any information about address spaces.
// The user level CPU state is saved and restored in the thread
// executing the user program (see thread.h).
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#ifndef ADDRSPACE_H
#define ADDRSPACE_H
#include "copyright.h"
#include "filesys.h"
#include "bitmap.h"
#define UserStackSize 1024 // increase this as necessary!
#define MAXUSERTHREAD UserStackSize / (2*PageSize)
#define MAX_THREAD_ALLOWED 20
#define MAX_SEMAPHORES_ALLOWED 10
#define MAX_BRK_Per_AddrSpace 100
class Semaphore;
class Thread;
class AddrSpace
{
public:
unsigned int size;
BitMap *myStackMap;
Semaphore *threadMainLock;
Semaphore *threadCountLock;
Semaphore *bitmapLock;
Semaphore *maxThreadNumber; //blocks thread creation when reaching the limit,
// and allows it when a free space in the stack is available.
// Semaphore *trial1;
int pid;
int nbUserThread;
Thread *initializedThread[MAX_THREAD_ALLOWED]; //FIXME: what is max thread allowed
Semaphore *semCreateLock;
Semaphore *userLevelSemaphores[MAX_SEMAPHORES_ALLOWED];
Semaphore *brkLock;
BitMap *semaphoreIdMap;
AddrSpace (OpenFile * executable); // Create an address space,
// initializing it with the program
// stored in the file "executable"
~AddrSpace (); // De-allocate an address space
void InitRegisters (); // Initialize user-level CPU registers,
// before jumping to user code
void SaveState (); // Save/restore address space-specific
void RestoreState (); // info on a context switch
int GetSize();
void rmIndex(int index);
void setPid(int id);
int getPid();
int Sbrk(unsigned int n);
static void ReadAtVirtual(OpenFile * executable, int virtualaddr, int numBytes,
int position, TranslationEntry *pageTable, unsigned numPages);
private:
TranslationEntry * pageTable; // Assume linear page table translation
// for now!
unsigned int numPages; // Number of pages in the virtual
unsigned int brk;
unsigned int brkMax;
// address space
};
#endif // ADDRSPACE_H
| [
"[email protected]"
] | |
cbee741acdef0525300f0bab423526ac2cc59138 | df8589f7f0c3920a299f9b8e4265da2496d7e105 | /gpu/dot.h | a16db39f5ee15d6ea7c021dcc03d7ee174f2082d | [] | no_license | karanchahal/buildTensorflow | aaf354b92aa9adfd8a67273a7f63462c56d721af | 674d192662cdcaeff427b01407a5012e3b6482a5 | refs/heads/develop | 2020-04-20T09:21:09.763751 | 2019-05-24T06:31:50 | 2019-05-24T06:31:50 | 168,763,307 | 34 | 3 | null | 2019-04-11T18:39:53 | 2019-02-01T21:36:30 | C++ | UTF-8 | C++ | false | false | 229 | h | #ifndef __GPU_DOT_INCLUDED__
#define __GPU_DOT_INCLUDED__
template<typename T>
struct Matrix;
template<typename T>
void dotGPU(vector<T> &res, const Matrix<T>* lhs, const Matrix<T> &rhs, int start, int startRes);
#endif
| [
"[email protected]"
] | |
e9d0714903b248b200265d6f0c14048a3dd66205 | a12d3d9469f3eb59e908b37960b5d87768d8b654 | /examples/grpc_greeter/greeter_client.cc | 7b571d0398178a81b9e93f843e0a9a75606be2be | [
"Apache-2.0"
] | permissive | siqili0308/zipkin-cpp | b95a2b358540b9b4b9fdc5ab9ac47ef57d98952b | f86357f6e302c98ab8a070267e3f7ba85ec2c59f | refs/heads/master | 2021-09-01T06:29:51.290262 | 2017-10-12T04:04:19 | 2017-10-12T04:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,935 | cc | /*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <iostream>
#include <memory>
#include <string>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <grpc++/grpc++.h>
#include <folly/Format.h>
#include <folly/String.h>
#include <folly/Uri.h>
#include "zipkin.hpp"
#include "helloworld.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;
class GreeterClient
{
public:
GreeterClient(std::shared_ptr<Channel> channel, std::shared_ptr<zipkin::Collector> collector)
: stub_(Greeter::NewStub(channel)), tracer_(zipkin::Tracer::create(collector.get()))
{
}
// Assembles the client's payload, sends it and presents the response back
// from the server.
std::string SayHello(const std::string &user)
{
zipkin::Span &span = *tracer_->span("SayHello");
zipkin::Span::Scope scope(span);
// Data we are sending to the server.
HelloRequest request;
request.set_name(user);
// Container for the data we expect from the server.
HelloReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
zipkin::Propagation::inject(context, span);
zipkin::Endpoint endpoint("greeter_client");
span << std::make_pair("name", user) << endpoint
<< zipkin::TraceKeys::CLIENT_SEND << endpoint;
// The actual RPC.
Status status = stub_->SayHello(&context, request, &reply);
span << zipkin::TraceKeys::CLIENT_RECV << endpoint;
// Act upon its status.
if (status.ok())
{
return reply.message();
}
else
{
span << std::make_pair(zipkin::TraceKeys::ERROR, status.error_message());
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return "RPC failed";
}
}
private:
std::unique_ptr<Greeter::Stub> stub_;
std::unique_ptr<zipkin::Tracer> tracer_;
};
DEFINE_string(grpc_addr, "localhost:50051", "GRPC server address");
DEFINE_string(collector_uri, "", "Collector URI for tracing");
int main(int argc, char **argv)
{
google::InitGoogleLogging(argv[0]);
int arg = gflags::ParseCommandLineFlags(&argc, &argv, true);
std::shared_ptr<zipkin::Collector> collector;
if (!FLAGS_collector_uri.empty())
{
collector.reset(zipkin::Collector::create(FLAGS_collector_uri));
}
// Instantiate the client. It requires a channel, out of which the actual RPCs
// are created. This channel models a connection to an endpoint (in this case,
// localhost at port 50051). We indicate that the channel isn't authenticated
// (use of InsecureChannelCredentials()).
std::shared_ptr<Channel> channel = grpc::CreateChannel(FLAGS_grpc_addr, grpc::InsecureChannelCredentials());
GreeterClient greeter(channel, collector);
std::string user(arg < argc ? argv[arg] : "world");
std::string reply = greeter.SayHello(user);
std::cout << "Greeter received: " << reply << std::endl;
if (collector.get())
collector->shutdown(std::chrono::seconds(5));
google::ShutdownGoogleLogging();
return 0;
}
| [
"[email protected]"
] | |
954d728c6f1396ac08f9edd7140d7f1b5f6f00e8 | c80a7e1815f49d3fdcd828c271735da5eb58216f | /fptaylor/sine/all-64/sine-all-64-10.cpp | 585f5e6f5c15a2c816d1e42c25883f48a5a0a0ad | [] | no_license | wfchiang/energy-measurement-benchmarks | 4c9cb150d6b26295e695623fef8dd25effb814a7 | 0044f99464ddc9a2d553851dc9986adb4c11e057 | refs/heads/master | 2021-01-21T04:55:47.255147 | 2016-07-02T23:26:21 | 2016-07-02T23:26:21 | 53,980,001 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include <iostream>
using namespace std;
int main (int argc, char **argv) {
double x = 0.41403704384;
double __const_2 = 5040.0;
double __const_1 = 120.0;
double __const_0 = 6.0;
for (int ii = 0 ; ii < 10000000 ; ii++) {
double ____expr_0 = (((x - (((x * x) * x) / __const_0)) + (((x * x) * ((x * x) * x)) / __const_1)) - (((x * x) * ((x * x) * ((x * x) * x))) / __const_2));
}
return 0;
}
| [
"[email protected]"
] | |
d83c723e8ff82b7ce2368959bfc95e2aa2bc7491 | 64ce9d40c49d9008ef660c2f9d1671be140a5005 | /d04/ex00/Peon.hpp | edae167fa31f4e4872fce8797a6b43d73a7c90e3 | [] | no_license | fmallaba/cpp | 33b4ac79a9800ab1e1c7fc24dd258b86b1468f69 | 79674e3b6e09b5b83952a71ff3d0590dd6d72108 | refs/heads/master | 2021-04-09T14:40:29.060979 | 2018-04-09T17:04:24 | 2018-04-09T17:04:24 | 125,549,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | hpp | #ifndef PEON_HPP
# define PEON_HPP
# include "Victim.hpp"
class Peon : public Victim
{
public:
Peon(std::string name);
~Peon();
void getPolymorphed(void) const;
};
std::ostream & operator<<(std::ostream & os, Peon const & tmp);
#endif
| [
"[email protected]"
] | |
fbb2f56a9e8357b8d8855acb177d4b9d86739b7b | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/squid/old_hunk_3911.cpp | 5d4437b1c05ed95e470b226a9057a1bd74ed6f89 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | cpp | }
/* calls memBufVPrintf */
#if STDC_HEADERS
void
MemBuf::Printf(const char *fmt,...)
{
va_list args;
va_start(args, fmt);
#else
void
MemBuf::Printf(va_alist)
va_dcl {
va_list args;
mb_size_t sz = 0;
va_start(args);
const char *fmt = va_arg(args, char *);
#endif
vPrintf(fmt, args);
va_end(args);
}
| [
"[email protected]"
] | |
30d72e6e9788444bf18a20bc05dfbdd03691125a | 9aaa160fb4e092266cc856ae203cb7c0ac411ef2 | /heal2.h | 7900203a86ecbeb2fc8f8c2da6816124db66cd67 | [] | no_license | Zeniz/farland | 0711f67d4a20b98122c62359ec855e1a1c345f0f | 54d4483a4a951c4a0a271442b97c89b048275965 | refs/heads/master | 2020-04-26T12:41:22.937420 | 2019-03-31T22:38:00 | 2019-03-31T22:38:00 | 173,557,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 531 | h | #pragma once
#include "skillNode.h"
class heal2 : public skillNode
{
private:
const float MULTI_NUM_PHYSIC = 0.f;
const float MULTI_NUM_MAGIC = 2.f;
const int AUG_X = 0;
const int AUG_Y = -32;
const SKILL_ATTR ATTR = SKILL_ATTR::SKILL_ATTR_NONE;
const float ATTR_ADJUST_RATIO = 0.f;
const int CASTCOUNT_MAX = 700;
const int RANGE = 5;
const float MANACOST = 20;
public:
heal2();
~heal2();
HRESULT init() override;
void release() override;
void StartSkillEffect(POINT curMapIdx, int dir, int zLvl) override;
};
| [
"[email protected]"
] | |
0efeb9705b256d4db65095836b7daa4422c3d66c | e38284c7578f084dd726e5522b3eab29b305385b | /Wml/Source/Graphics/WmlPlanarReflection.cpp | 3ac7f60fa5bdd864ef11cb49a1d67a2fec02262f | [
"MIT"
] | permissive | changjiayi6322/deform2d | 99d73136b493833fa4d6788120f6bfb71035bc4d | 1a350dd20f153e72de1ea9cffb873eb67bf3d668 | refs/heads/master | 2020-06-02T19:38:45.240018 | 2018-07-04T20:26:35 | 2018-07-04T20:26:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,625 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2004. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlRenderer.h"
#include "WmlPlanarReflection.h"
using namespace Wml;
WmlImplementRTTI(PlanarReflection,Node);
WmlImplementStream(PlanarReflection);
int PlanarReflection::ms_iNextFreeStencilValue = 1;
//----------------------------------------------------------------------------
PlanarReflection::PlanarReflection (Node* pkCaster, TriMesh* pkPlane,
float fReflectance)
:
m_spkCaster(pkCaster),
m_spkPlane(pkPlane),
m_fReflectance(fReflectance),
m_iStencilValue(ms_iNextFreeStencilValue++)
{
assert( pkPlane && pkPlane->GetTriangleQuantity() > 0 );
// Save the cull state of the casters and plane. These objects will be
// force-culled by 'this' to make sure they are not drawn by the regular
// traversal.
m_bForceCullCaster = pkCaster->ForceCull();
m_bForceCullPlane = pkPlane->ForceCull();
pkCaster->ForceCull() = true;
pkPlane->ForceCull() = true;
// Get a point on the plane and compute the plane normal by using the
// first triangle in the mesh of the plane. At render time, these need
// to be transformed to world coordinates.
Vector3f kV1, kV2;
pkPlane->GetTriangle(0,m_kPointOnPlane,kV1,kV2);
Vector3f kEdge1 = kV1 - m_kPointOnPlane;
Vector3f kEdge2 = kV2 - m_kPointOnPlane;
m_kNormal = kEdge1.UnitCross(kEdge2);
}
//----------------------------------------------------------------------------
PlanarReflection::PlanarReflection ()
:
m_kNormal(0.0f,0.0f,0.0f),
m_kPointOnPlane(0.0f,0.0f,0.0f)
{
m_bForceCullCaster = false;
m_bForceCullPlane = false;
m_iStencilValue = 0;
m_fReflectance = 0.0f;
}
//----------------------------------------------------------------------------
PlanarReflection::~PlanarReflection ()
{
// restore the cull state
m_spkCaster->ForceCull() = m_bForceCullCaster;
m_spkPlane->ForceCull() = m_bForceCullPlane;
// release the render effect objects
m_spkCaster = NULL;
m_spkPlane = NULL;
}
//----------------------------------------------------------------------------
void PlanarReflection::UpdateWorldBound ()
{
m_kWorldBound = m_spkCaster->WorldBound();
m_kWorldBound += m_spkPlane->WorldBound();
}
//----------------------------------------------------------------------------
void PlanarReflection::Draw (Renderer& rkRenderer)
{
// Restore the original cull state in case the user is trying to do
// something clever, like render an object's reflection, but not the
// object itself.
m_spkCaster->ForceCull() = m_bForceCullCaster;
m_spkPlane->ForceCull() = m_bForceCullPlane;
// if no objects, just cull and draw the mirror
if ( !m_spkCaster )
{
// no shadow caster, just cull/draw the plane
m_spkPlane->OnDraw(rkRenderer);
m_spkPlane->ForceCull() = true;
return;
}
rkRenderer.Draw(*this);
// prevent drawing of the caster and plane during the regular traversal
m_spkCaster->ForceCull() = true;
m_spkPlane->ForceCull() = true;
}
//----------------------------------------------------------------------------
Object* PlanarReflection::GetObjectByName (const char* acName)
{
Object* pkFound = Node::GetObjectByName(acName);
if ( pkFound )
return pkFound;
// The subtree m_spkCaster is not searched to avoid the possibility of
// infinite recursion.
if ( m_spkPlane )
{
pkFound = m_spkPlane->GetObjectByName(acName);
if ( pkFound )
return pkFound;
}
return NULL;
}
//----------------------------------------------------------------------------
void PlanarReflection::GetAllObjectsByName (const char* acName,
std::vector<Object*>& rkObjects)
{
Node::GetAllObjectsByName(acName,rkObjects);
// The subtree m_spkCaster is not searched to avoid the possibility of
// infinite recursion.
if ( m_spkPlane )
m_spkPlane->GetAllObjectsByName(acName,rkObjects);
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// streaming
//----------------------------------------------------------------------------
Object* PlanarReflection::Factory (Stream& rkStream)
{
PlanarReflection* pkObject = new PlanarReflection;
Stream::Link* pkLink = new Stream::Link(pkObject);
pkObject->Load(rkStream,pkLink);
return pkObject;
}
//----------------------------------------------------------------------------
void PlanarReflection::Load (Stream& rkStream, Stream::Link* pkLink)
{
Node::Load(rkStream,pkLink);
// native data
StreamRead(rkStream,m_kNormal);
StreamRead(rkStream,m_kPointOnPlane);
StreamRead(rkStream,m_iStencilValue);
StreamRead(rkStream,m_fReflectance);
// link data (caster and plane, in that order)
Spatial* pkChild;
StreamRead(rkStream,pkChild);
pkLink->Add(pkChild);
StreamRead(rkStream,pkChild);
pkLink->Add(pkChild);
}
//----------------------------------------------------------------------------
void PlanarReflection::Link (Stream& rkStream, Stream::Link* pkLink)
{
Node::Link(rkStream,pkLink);
Object* pkLinkID = pkLink->GetLinkID();
m_spkCaster = (Node*)rkStream.GetFromMap(pkLinkID);
pkLinkID = pkLink->GetLinkID();
m_spkPlane = (TriMesh*)rkStream.GetFromMap(pkLinkID);
// initialize the cull status for correct toggling during rendering
m_bForceCullCaster = m_spkCaster->ForceCull();
m_bForceCullPlane = m_spkPlane->ForceCull();
m_spkCaster->ForceCull() = true;
m_spkPlane->ForceCull() = true;
}
//----------------------------------------------------------------------------
bool PlanarReflection::Register (Stream& rkStream)
{
if ( !Node::Register(rkStream) )
return false;
if ( m_spkCaster )
m_spkCaster->Register(rkStream);
if ( m_spkPlane )
m_spkPlane->Register(rkStream);
return true;
}
//----------------------------------------------------------------------------
void PlanarReflection::Save (Stream& rkStream)
{
Node::Save(rkStream);
// native data
StreamWrite(rkStream,m_kNormal);
StreamWrite(rkStream,m_kPointOnPlane);
StreamWrite(rkStream,m_iStencilValue);
StreamWrite(rkStream,m_fReflectance);
// link data
StreamWrite(rkStream,m_spkCaster);
StreamWrite(rkStream,m_spkPlane);
}
//----------------------------------------------------------------------------
StringTree* PlanarReflection::SaveStrings ()
{
int iCQuantity = 1;
if ( m_spkCaster )
iCQuantity++;
if ( m_spkPlane )
iCQuantity++;
StringTree* pkTree = new StringTree(5,0,iCQuantity,0);
// strings
pkTree->SetString(0,MakeString(&ms_kRTTI,GetName()));
pkTree->SetString(1,MakeString("normal =",m_kNormal));
pkTree->SetString(2,MakeString("point on plane =",m_kPointOnPlane));
pkTree->SetString(3,MakeString("stencil value =",m_iStencilValue));
pkTree->SetString(4,MakeString("reflectance = ",m_fReflectance));
// children
pkTree->SetChild(0,Node::SaveStrings());
int iSlot = 1;
if ( m_spkCaster )
pkTree->SetChild(iSlot++,m_spkCaster->SaveStrings());
if ( m_spkPlane )
pkTree->SetChild(iSlot++,m_spkPlane->SaveStrings());
return pkTree;
}
//----------------------------------------------------------------------------
int PlanarReflection::GetMemoryUsed () const
{
int iBaseSize = sizeof(PlanarReflection) - sizeof(Node);
int iTotalSize = iBaseSize + Node::GetMemoryUsed();
return iTotalSize;
}
//----------------------------------------------------------------------------
int PlanarReflection::GetDiskUsed () const
{
return Node::GetDiskUsed() +
sizeof(m_kNormal) +
sizeof(m_kPointOnPlane) +
sizeof(m_iStencilValue) +
sizeof(m_fReflectance) +
sizeof(m_spkCaster) +
sizeof(m_spkPlane);
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | |
7628d8acc23c12429b63bee4b36555ec50bac549 | 81b93a8bc16023e31171ce68da0751b3a428696f | /src/fsm/include/state_operation.h | b18c28701b6fe760472224aca840159bfd3eea8e | [] | no_license | github188/agv | 3373b9b86203b0b2b98019abfc1058112eb394e2 | 3577ea7f0b561eb791241327a4c05e325d76808c | refs/heads/master | 2022-04-03T20:29:43.938463 | 2019-12-19T10:22:05 | 2019-12-19T10:22:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,208 | h | #ifndef FSM_INCLUDE_STATE_OPERATION_H_
#define FSM_INCLUDE_STATE_OPERATION_H_
#include "ros/ros.h"
#include "state_base_machine.h"
#include "state_define.h"
namespace superg_agv
{
namespace fsm
{
class OperationState : public StateBase
{
public:
OperationState(int id_, StateMachine *fsm_) : StateBase(id, p_machine)
{
this->id = id_;
this->p_machine = fsm_;
this->status_ = 0;
this->vms_status_ = 0;
this->control_pub_id = 0;
time_reset_tip_ = 0;
state_status_pub_tip = 0;
cur_state_status.time_in = ros::Time::now();
cur_state_status.time_out = ros::Time::now();
cur_state_status.cur_state = OPERATION;
ad_status_tip_ = cur_state_status.cur_state;
hmi_status_tip_ = cur_state_status.cur_state;
}
virtual int doStateLoop()
{
onEnter();
onStay();
onExit();
return cur_state_status.next_state;
}
virtual void onEnter()
{
//获取上次状态
cur_state_status.late_state = p_machine->getLateState();
if (time_reset_tip_ == 0)
{
ROS_INFO("enter %s state, late state is %s", AgvStateStr[cur_state_status.cur_state].c_str(),
AgvStateStr[cur_state_status.late_state].c_str());
cur_state_status.time_in = ros::Time::now();
time_reset_tip_ = 1;
}
//进入动作
doEnterAction(cur_state_status.late_state);
}
virtual void onStay()
{
p_machine->doStateMachineSpinOnce();
if (0 < (status_ + vms_status_))
{
//判断任务发布状态
if (!isTaskControlPubOK(m_cur_task_status.recieve_task_num))
{
//重新发布未执行的控制命令
p_machine->taskControlRePub(m_cur_task_status.recieve_task_num);
}
//判断AD状态
if (ad_status_tip_ != NULL_STATE_ID && status_ > 0)
{
cur_state_status.next_state = ad_status_tip_;
}
else
{
cur_state_status.next_state = cur_state_status.cur_state;
}
//判断任务执行状态
if (cur_state_status.next_state == cur_state_status.cur_state && vms_status_ > 0)
{
cur_state_status.next_state = hmi_status_tip_;
}
}
else
{
cur_state_status.next_state = cur_state_status.cur_state;
}
}
virtual void onExit()
{
doExitAction(cur_state_status.next_state);
cur_state_status.time_out = ros::Time::now();
status_ = 0;
vms_status_ = 0;
if (cur_state_status.cur_state != cur_state_status.next_state)
{
ROS_INFO("%s -->> %.8lf(s) -->> %s", AgvStateStr[cur_state_status.cur_state].c_str(),
cur_state_status.time_out.toSec() - cur_state_status.time_in.toSec(),
AgvStateStr[cur_state_status.next_state].c_str());
time_reset_tip_ = 0;
}
}
virtual void doEnterAction(int state_)
{
//通用初始化状态切换标志
status_ = 0;
vms_status_ = 0;
node_enable_value_ = p_machine->getNodeEnableValue();
node_enable_status_ = p_machine->getAdEnableValue();
node_fsm_control_ = fsmControlOperation();
//根据前置状态选择不同的动作
if (state_ == STANDBY)
{
}
else if (state_ == PLANNING)
{
}
else if (state_ == OPERATION)
{
}
else
{
}
}
virtual void doExitAction(int &state_)
{
//根据后续状态选择不同的动作
node_enable_value_ = changeNodeEnableValue(node_enable_value_, state_);
if (state_ == STANDBY)
{
node_enable_status_ = nodeAdDisable();
node_fsm_control_ = fsmControlNull();
}
else if (state_ == PLANNING)
{
node_enable_status_ = nodeAdEnable();
node_fsm_control_ = fsmControlOperation();
//下发任务
if (vms_status_ > 0)
{
control_pub_id = p_machine->taskControlPub(node_fsm_control_, state_);
}
}
else if (state_ == OPERATION)
{
node_enable_status_ = nodeAdEnable();
node_fsm_control_ = fsmControlOperation();
//下发任务
if (vms_status_ > 0)
{
control_pub_id = p_machine->taskControlPub(node_fsm_control_, state_);
}
}
else if (state_ == EXCEPTION) //区分任务和故障
{
node_enable_status_ = nodeAdEnable();
if ((vms_status_ + status_) > 0)
{
//取消当前节点任务
node_fsm_control_ = fsmControlCancel();
control_pub_id = p_machine->taskControlPub(node_fsm_control_, cur_state_status.cur_state);
//下发故障任务
node_fsm_control_ = fsmControlOperation();
control_pub_id = p_machine->taskControlPub(node_fsm_control_, state_);
}
}
else if (state_ == REMOTE)
{
//下发任务
node_enable_status_ = nodeAdDisable();
node_fsm_control_ = fsmControlNull();
}
else
{
node_enable_status_ = nodeAdDisable();
node_fsm_control_ = fsmControlNull();
}
//改变控制权
enableNode(node_enable_value_, node_enable_status_);
if (1 == state_status_pub_tip)
{
state_status_pub_tip = 0;
//心跳
p_machine->vcuControlPub();
//状态
p_machine->fsmStatusPub();
}
}
virtual int doAdStatusJudge(const AdStatusValue &cur_ad_status_)
{
ROS_INFO("%s do adstatus judge", AgvStateStr[cur_state_status.cur_state].c_str());
int updata_num_ = p_machine->updateTaskCache();
if (updata_num_ > 0)
{
ROS_WARN("%s adstatus had update, get new Task", AgvStateStr[cur_state_status.cur_state].c_str());
m_cur_task_status = p_machine->getCurTask();
}
if (isRemoteState(cur_ad_status_))
{
return REMOTE;
}
else if (isExceptionState(cur_ad_status_))
{
return EXCEPTION;
}
else if (isAdStatusOK(cur_ad_status_))
{
if (0 == m_cur_task_status.recieve_task_num && 0 == m_cur_task_status.task_id && 0 == m_cur_task_status.cmd_type)
{
ROS_INFO("%s get NULL task", AgvStateStr[cur_state_status.cur_state].c_str());
return cur_state_status.cur_state;
}
else
{
return doCurTaskJudge();
}
}
else
{
return cur_state_status.cur_state;
}
}
virtual int doCurTaskJudge()
{
ROS_INFO("%s do task judge", AgvStateStr[cur_state_status.cur_state].c_str());
int state_temp_ = taskReciever2State(m_cur_task_status.reciever);
if (state_temp_ == NULL_STATE_ID)
{
return cur_state_status.cur_state;
}
else if (state_temp_ == cur_state_status.cur_state)
{
if (0 == m_cur_task_status.is_send_ok)
{
ROS_ERROR("%s do task rsn:%d id:%u cmd:%u status judge ---- wait task recieve",
AgvStateStr[cur_state_status.cur_state].c_str(), m_cur_task_status.recieve_task_num,
m_cur_task_status.task_id, m_cur_task_status.cmd_type);
return cur_state_status.cur_state;
}
else
{
if (m_cur_task_status.status < 3)
{
//等待任务完成
ROS_WARN("%s do task rsn:%d id:%u cmd:%u status judge ---- wait task done",
AgvStateStr[cur_state_status.cur_state].c_str(), m_cur_task_status.recieve_task_num,
m_cur_task_status.task_id, m_cur_task_status.cmd_type);
return doAdTaskStatusJudge(m_cur_task_status.status);
}
else
{
if (0 == m_cur_task_status.result)
{
ROS_WARN("%s do task rsn:%d id:%u cmd:%u status judge ---- task had done update result",
AgvStateStr[cur_state_status.cur_state].c_str(), m_cur_task_status.recieve_task_num,
m_cur_task_status.task_id, m_cur_task_status.cmd_type);
p_machine->updateCurCacheTaskResult(m_cur_task_status.recieve_task_num);
m_cur_task_status.result = 1;
return doAdTaskStatusJudge(m_cur_task_status.status);
}
else
{
ROS_WARN("%s do task rsn:%d id:%u cmd:%u status judge ---- task had done RESET cur",
AgvStateStr[cur_state_status.cur_state].c_str(), m_cur_task_status.recieve_task_num,
m_cur_task_status.task_id, m_cur_task_status.cmd_type);
m_cur_task_status = p_machine->getCurTask();
ROS_INFO("%s cur task rsn:%d id:%u cmd:%u", AgvStateStr[cur_state_status.cur_state].c_str(),
m_cur_task_status.recieve_task_num, m_cur_task_status.task_id, m_cur_task_status.cmd_type);
return STANDBY;
}
}
}
}
else
{
return state_temp_;
}
}
virtual int doAdTaskStatusJudge(const int &cur_status_)
{
switch (cur_status_)
{
case 0: // 0– 未执行
return cur_state_status.cur_state;
break;
case 1: // 1– 执行任务中
return cur_state_status.cur_state;
break;
case 2: // 2– 等待任务执行结果
return cur_state_status.cur_state;
break;
case 3: // 3– 任务结束,成功,离开当前状态
return STANDBY;
break;
case 4: // 4– 任务结束,失败,离开当前状态
return STANDBY;
break;
case 5: // 5– 任务结束,故障,切换到Exception
return EXCEPTION;
break;
case 6: // 6– 按照命令任务中止,返回STANDBY
return STANDBY;
break;
case 7: // 7– 自动判断任务中止,离开当前状态
return STANDBY;
break;
default:
return cur_state_status.cur_state;
}
}
virtual int doHmiControlJudge(const HmiControlValue &cur_hmi_control_value_) //根据命令更新ad状态
{
switch (cur_hmi_control_value_.cmd_type)
{
case 0: // 0 – 空操作
return cur_state_status.cur_state;
break;
case 1: // 1 – 行走
return PLANNING;
break;
case 2: // 2 – 顶升上升
return OPERATION;
break;
case 3: // 3 – 顶升下降
return OPERATION;
break;
case 4: // 4 – 充电
return OPERATION;
break;
case 5: // 5 – 停止充电
return OPERATION;
break;
case 6: // 6 – 紧停
return EXCEPTION;
break;
case 7: // 7 – 复位
return EXCEPTION;
break;
case 8: // 8 – 任务暂停
return cur_state_status.cur_state;
break;
case 9: // 9 – 任务继续
return cur_state_status.cur_state;
break;
case 10: // 10 – 任务取消
return cur_state_status.late_state;
break;
case 11: // 11 – 停稳
return PLANNING;
break;
case 12: // 12 – 滑停
return EXCEPTION;
break;
default: //任务外命令,报错误
return EXCEPTION;
}
}
virtual bool isTaskControlPubOK(const int &recieve_task_num_)
{
if (recieve_task_num_ > 0)
{
return p_machine->getTaskSendStatus(recieve_task_num_);
}
else
{
return 1;
}
}
public:
int control_pub_id;
bool control_pub_status;
int msg_operation_status;
};
} // namespace fsm
} // namespace superg_agv
#endif | [
"[email protected]"
] | |
2462e28e979bd576b6e3a0622145c0680b765ca1 | 0e3697eae327b5e86e6dbc7295ceaf8fb620364c | /School/Clasa a VIII-a/Octombrie 2013/Pitagorice/main.cpp | 1d540747bd4d72db30aa57af9863979cc001351b | [
"MIT"
] | permissive | AbeleMM/Algorithmic-Problems | f89cd9a11660ad0f54819a50739df8cc4ba32c89 | 212ad9dd6a3f04f426ad7789b3de11605c426906 | refs/heads/master | 2023-01-11T20:45:33.392652 | 2022-12-06T09:03:17 | 2022-12-26T11:03:29 | 201,615,751 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 426 | cpp | #include <iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Introduceti primul numar: ";
cin>>a;
cout<<"Introduceti al doilea numar: ";
cin>>b;
cout<<"Introduceti al treilea numar: ";
cin>>c;
if (a*a+b*b==c*c || a*a+c*c==b*b || b*b+c*c==a*a)
{
cout<<"Numerele sunt pitagorice!";
}
else
{
cout<<"Numerele nu sunt pitagorice!";
}
return 0;
}
| [
"[email protected]"
] | |
e330d209c447d3e1b823647de0bd780a92729dec | aa805ffe17db9b37282408cdf30edb5ceb168a4c | /src/lib/dll/lib_win/wnd_wnd.cpp | 939a89c04a85f37dd3810e5f1fe1e19570aa0696 | [] | no_license | nomissbowling/KuinInKuin | 3852383889ab87d8f314333dec7a47c048d56233 | a220a04d43ff00197c3eaa01e4f18ed4a0a51c64 | refs/heads/master | 2022-11-12T22:34:12.573235 | 2020-07-05T10:04:57 | 2020-07-05T10:04:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,029 | cpp | #include "wnd_wnd.h"
#include <ShlObj.h>
static int WndCnt;
static Bool ExitAct;
static void* OnKeyPress;
static Char FileDialogDir[KUIN_MAX_PATH + 1];
static LRESULT CALLBACK CommonWndProc(HWND wnd, SWndBase* wnd2, SWnd* wnd3, UINT msg, WPARAM w_param, LPARAM l_param);
static LRESULT CALLBACK WndProcWndNormal(HWND wnd, UINT msg, WPARAM w_param, LPARAM l_param);
static LRESULT CALLBACK WndProcWndFix(HWND wnd, UINT msg, WPARAM w_param, LPARAM l_param);
static LRESULT CALLBACK WndProcWndAspect(HWND wnd, UINT msg, WPARAM w_param, LPARAM l_param);
static Char* ParseFilter(const U8* filter, int* num);
static void NormPath(Char* path, Bool dir);
EXPORT_CPP void _init(void* heap, S64* heap_cnt, S64 app_code, const U8* use_res_flags)
{
InitEnvVars(heap, heap_cnt, app_code, use_res_flags);
WndCnt = 0;
ExitAct = False;
Instance = (HINSTANCE)GetModuleHandle(nullptr);
HICON icon = LoadIcon(Instance, reinterpret_cast<LPCWSTR>(static_cast<S64>(0x65))); // 0x65 is the resource ID of the application icon.
{
WNDCLASSEX wnd_class;
wnd_class.cbSize = sizeof(WNDCLASSEX);
wnd_class.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
wnd_class.lpfnWndProc = WndProcWndNormal;
wnd_class.cbClsExtra = 0;
wnd_class.cbWndExtra = 0;
wnd_class.hInstance = Instance;
wnd_class.hIcon = icon;
wnd_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
wnd_class.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1);
wnd_class.lpszMenuName = nullptr;
wnd_class.lpszClassName = L"KuinWndNormalClass";
wnd_class.hIconSm = icon;
RegisterClassEx(&wnd_class);
}
{
WNDCLASSEX wnd_class;
wnd_class.cbSize = sizeof(WNDCLASSEX);
wnd_class.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
wnd_class.lpfnWndProc = WndProcWndFix;
wnd_class.cbClsExtra = 0;
wnd_class.cbWndExtra = 0;
wnd_class.hInstance = Instance;
wnd_class.hIcon = icon;
wnd_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
wnd_class.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1);
wnd_class.lpszMenuName = nullptr;
wnd_class.lpszClassName = L"KuinWndFixClass";
wnd_class.hIconSm = icon;
RegisterClassEx(&wnd_class);
}
{
WNDCLASSEX wnd_class;
wnd_class.cbSize = sizeof(WNDCLASSEX);
wnd_class.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
wnd_class.lpfnWndProc = WndProcWndFix;
wnd_class.cbClsExtra = 0;
wnd_class.cbWndExtra = 0;
wnd_class.hInstance = Instance;
wnd_class.hIcon = nullptr;
wnd_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
wnd_class.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1);
wnd_class.lpszMenuName = nullptr;
wnd_class.lpszClassName = L"KuinWndDialogClass";
wnd_class.hIconSm = nullptr;
RegisterClassEx(&wnd_class);
}
{
WNDCLASSEX wnd_class;
wnd_class.cbSize = sizeof(WNDCLASSEX);
wnd_class.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
wnd_class.lpfnWndProc = WndProcWndAspect;
wnd_class.cbClsExtra = 0;
wnd_class.cbWndExtra = 0;
wnd_class.hInstance = Instance;
wnd_class.hIcon = icon;
wnd_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
wnd_class.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1);
wnd_class.lpszMenuName = nullptr;
wnd_class.lpszClassName = L"KuinWndAspectClass";
wnd_class.hIconSm = icon;
RegisterClassEx(&wnd_class);
}
{
HDC dc = GetDC(nullptr);
FontCtrl = CreateFont(-MulDiv(9, GetDeviceCaps(dc, LOGPIXELSY), 72), 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DRAFT_QUALITY, DEFAULT_PITCH, L"MS UI Gothic");
ReleaseDC(nullptr, dc);
}
OnKeyPress = nullptr;
FileDialogDir[0] = L'\0';
}
EXPORT_CPP void _fin()
{
DeleteObject(static_cast<HGDIOBJ>(FontCtrl));
}
EXPORT_CPP void _menuDtor(SClass* me_)
{
DestroyMenu(reinterpret_cast<SMenu*>(me_)->MenuHandle);
}
EXPORT_CPP void _menuAdd(SClass* me_, S64 id, const U8* text)
{
THROWDBG(id < 0x0001 || 0xffff < id, 0xe9170006);
THROWDBG(text == nullptr, EXCPT_ACCESS_VIOLATION);
AppendMenu(reinterpret_cast<SMenu*>(me_)->MenuHandle, MF_ENABLED | MF_STRING, static_cast<UINT_PTR>(id), reinterpret_cast<const Char*>(text + 0x10));
}
EXPORT_CPP void _menuAddLine(SClass* me_)
{
AppendMenu(reinterpret_cast<SMenu*>(me_)->MenuHandle, MF_ENABLED | MF_SEPARATOR, 0, nullptr);
}
EXPORT_CPP void _menuAddPopup(SClass* me_, const U8* text, const U8* popup)
{
THROWDBG(popup == nullptr, EXCPT_ACCESS_VIOLATION);
THROWDBG(text == nullptr, EXCPT_ACCESS_VIOLATION);
AppendMenu(reinterpret_cast<SMenu*>(me_)->MenuHandle, MF_ENABLED | MF_STRING | MF_POPUP, reinterpret_cast<UINT_PTR>(reinterpret_cast<const SMenu*>(popup)->MenuHandle), reinterpret_cast<const Char*>(text + 0x10));
}
EXPORT_CPP void _menuIns(SClass* me_, S64 targetId, S64 id, const U8* text)
{
THROWDBG(targetId < 0x0001 || 0xffff < targetId, 0xe9170006);
THROWDBG(id < 0x0001 || 0xffff < id, 0xe9170006);
THROWDBG(text == nullptr, EXCPT_ACCESS_VIOLATION);
InsertMenu(reinterpret_cast<SMenu*>(me_)->MenuHandle, static_cast<UINT>(targetId), MF_ENABLED | MF_STRING, static_cast<UINT_PTR>(id), reinterpret_cast<const Char*>(text + 0x10));
}
EXPORT_CPP void _menuInsPopup(SClass* me_, const U8* target, const U8* text, const U8* popup)
{
THROWDBG(target == nullptr, EXCPT_ACCESS_VIOLATION);
THROWDBG(popup == nullptr, EXCPT_ACCESS_VIOLATION);
THROWDBG(text == nullptr, EXCPT_ACCESS_VIOLATION);
// This cast is due to bad specifications of Windows API.
InsertMenu(reinterpret_cast<SMenu*>(me_)->MenuHandle, static_cast<UINT>(reinterpret_cast<UINT_PTR>(reinterpret_cast<const SMenu*>(target)->MenuHandle)), MF_ENABLED | MF_STRING | MF_POPUP, reinterpret_cast<UINT_PTR>(reinterpret_cast<const SMenu*>(popup)->MenuHandle), reinterpret_cast<const Char*>(text + 0x10));
}
EXPORT_CPP void _menuDel(SClass* me_, S64 id)
{
THROWDBG(id < 0x0001 || 0xffff < id, 0xe9170006);
RemoveMenu(reinterpret_cast<SMenu*>(me_)->MenuHandle, static_cast<UINT>(id), MF_BYCOMMAND);
}
EXPORT_CPP void _menuDelPopup(SClass* me_, const U8* popup)
{
THROWDBG(popup == nullptr, EXCPT_ACCESS_VIOLATION);
// This cast is due to bad specifications of Windows API.
RemoveMenu(reinterpret_cast<SMenu*>(me_)->MenuHandle, static_cast<UINT>(reinterpret_cast<UINT_PTR>(reinterpret_cast<const SMenu*>(popup)->MenuHandle)), MF_BYCOMMAND);
}
EXPORT_CPP Bool _tabOrderChk(SClass* me_, S64 key, S64 shiftCtrl)
{
if (key != VK_TAB || (shiftCtrl & 0x02) != 0)
return False;
STabOrder* me2 = reinterpret_cast<STabOrder*>(me_);
U8* ctrls = static_cast<U8*>(me2->Ctrls);
S64 len = *reinterpret_cast<S64*>(ctrls + 0x08);
if (len == 0)
return False;
HWND wnd = GetFocus();
void** ptr = reinterpret_cast<void**>(ctrls + 0x10);
for (S64 i = 0; i < len; i++)
{
SWndBase* wnd2 = static_cast<SWndBase*>(ptr[i]);
if (wnd2->WndHandle == wnd)
{
S64 step = shiftCtrl == 0 ? 1 : len - 1;
S64 idx = (i + step) % len;
while (idx != i)
{
if (ptr[idx] != nullptr)
{
SWndBase* wnd3 = static_cast<SWndBase*>(ptr[idx]);
if (IsWindowEnabled(wnd3->WndHandle))
{
SetFocus(wnd3->WndHandle);
return True;
}
}
idx = (idx + step) % len;
}
break;
}
}
return False;
}
EXPORT_CPP void _wndAcceptDraggedFiles(SClass* me_, Bool is_accepted)
{
DragAcceptFiles(reinterpret_cast<SWndBase*>(me_)->WndHandle, is_accepted ? TRUE : FALSE);
}
EXPORT_CPP void _wndActivate(SClass* me_)
{
SetActiveWindow(reinterpret_cast<SWndBase*>(me_)->WndHandle);
}
EXPORT_CPP Bool _wndActivated(SClass* me_)
{
return GetActiveWindow() == reinterpret_cast<SWndBase*>(me_)->WndHandle;
}
EXPORT_CPP void _wndClose(SClass* me_)
{
SendMessage(reinterpret_cast<SWndBase*>(me_)->WndHandle, WM_CLOSE, 0, 0);
}
EXPORT_CPP void _wndExit(SClass* me_)
{
DestroyWindow(reinterpret_cast<SWndBase*>(me_)->WndHandle);
}
EXPORT_CPP Bool _wndFocusedWnd(SClass* me_)
{
HWND wnd = GetFocus();
if (wnd == nullptr)
return False;
SWndBase* wnd2 = ToWnd(wnd);
while (wnd2 != nullptr && static_cast<int>(wnd2->Kind) >= 0x80)
{
wnd = GetParent(wnd);
if (wnd == nullptr)
return False;
wnd2 = ToWnd(wnd);
}
if (wnd2 == nullptr)
return False;
return wnd == reinterpret_cast<SWndBase*>(me_)->WndHandle;
}
EXPORT_CPP S64 _wndGetAlpha(SClass* me_)
{
BYTE alpha;
GetLayeredWindowAttributes(reinterpret_cast<SWndBase*>(me_)->WndHandle, nullptr, &alpha, nullptr);
return static_cast<S64>(alpha);
}
EXPORT_CPP const U8* _wndGetText(SClass* me_)
{
HWND wnd = reinterpret_cast<SWndBase*>(me_)->WndHandle;
int len = GetWindowTextLength(wnd);
Char* buf = static_cast<Char*>(AllocMem(sizeof(Char) * static_cast<size_t>(len + 1)));
GetWindowText(wnd, buf, len + 1);
const U8* result = RNToN(buf);
FreeMem(buf);
return result;
}
EXPORT_CPP void _wndMinMax(SClass* me_, S64 minWidth, S64 minHeight, S64 maxWidth, S64 maxHeight)
{
THROWDBG(minWidth != -1 && minWidth <= 0 || minHeight != -1 && minHeight <= 0 || maxWidth != -1 && maxWidth < minWidth || maxHeight != -1 && maxHeight < minHeight, 0xe9170006);
SWnd* me2 = reinterpret_cast<SWnd*>(me_);
me2->MinWidth = static_cast<U16>(minWidth);
me2->MinHeight = static_cast<U16>(minHeight);
me2->MaxWidth = static_cast<U16>(maxWidth);
me2->MaxHeight = static_cast<U16>(maxHeight);
}
EXPORT_CPP void _wndSetModalLock(SClass* me_)
{
HWND parent = GetWindow(reinterpret_cast<SWndBase*>(me_)->WndHandle, GW_OWNER);
if (parent != nullptr)
EnableWindow(parent, FALSE);
reinterpret_cast<SWnd*>(me_)->ModalLock = True;
}
EXPORT_CPP void _wndSetAlpha(SClass* me_, S64 alpha)
{
THROWDBG(alpha < 0 || 255 < alpha, 0xe9170006);
SetLayeredWindowAttributes(reinterpret_cast<SWndBase*>(me_)->WndHandle, 0, static_cast<BYTE>(alpha), LWA_ALPHA);
}
EXPORT_CPP void _wndSetMenu(SClass* me_, SClass* menu)
{
SetMenu(reinterpret_cast<SWndBase*>(me_)->WndHandle, menu == nullptr ? nullptr : reinterpret_cast<SMenu*>(menu)->MenuHandle);
}
EXPORT_CPP void _wndSetText(SClass* me_, const U8* text)
{
const U8* text2 = NToRN(text == nullptr ? L"" : reinterpret_cast<const Char*>(text + 0x10));
SetWindowText(reinterpret_cast<SWndBase*>(me_)->WndHandle, reinterpret_cast<const Char*>(text2 + 0x10));
FreeMem(const_cast<U8*>(text2));
}
EXPORT_CPP void _wndUpdateMenu(SClass* me_)
{
DrawMenuBar(reinterpret_cast<SWndBase*>(me_)->WndHandle);
}
EXPORT_CPP void _wndBaseDtor(SClass* me_)
{
SWndBase* me2 = reinterpret_cast<SWndBase*>(me_);
DestroyWindow(me2->WndHandle);
}
EXPORT_CPP void _wndBaseClientToScreen(SClass* me_, S64* screenX, S64* screenY, S64 clientX, S64 clientY)
{
POINT point;
point.x = static_cast<LONG>(clientX);
point.y = static_cast<LONG>(clientY);
ClientToScreen(reinterpret_cast<SWndBase*>(me_)->WndHandle, &point);
*screenX = static_cast<S64>(point.x);
*screenY = static_cast<S64>(point.y);
}
EXPORT_CPP void _wndBaseFocus(SClass* me_)
{
SetFocus(reinterpret_cast<SWndBase*>(me_)->WndHandle);
}
EXPORT_CPP Bool _wndBaseFocused(SClass* me_)
{
return GetFocus() == reinterpret_cast<SWndBase*>(me_)->WndHandle;
}
EXPORT_CPP Bool _wndBaseGetEnabled(SClass* me_)
{
return IsWindowEnabled(reinterpret_cast<SWndBase*>(me_)->WndHandle) != FALSE;
}
EXPORT_CPP void _wndBaseGetPos(SClass* me_, S64* x, S64* y, S64* width, S64* height)
{
SWndBase* me2 = reinterpret_cast<SWndBase*>(me_);
RECT rect;
GetClientRect(me2->WndHandle, &rect);
*x = static_cast<S64>(rect.left);
*y = static_cast<S64>(rect.top);
*width = static_cast<S64>(rect.right - rect.left);
*height = static_cast<S64>(rect.bottom - rect.top);
}
EXPORT_CPP void _wndBaseGetPosScreen(SClass* me_, S64* x, S64* y, S64* width, S64* height)
{
SWndBase* me2 = reinterpret_cast<SWndBase*>(me_);
RECT rect;
GetWindowRect(me2->WndHandle, &rect);
*x = static_cast<S64>(rect.left);
*y = static_cast<S64>(rect.top);
*width = static_cast<S64>(rect.right - rect.left);
*height = static_cast<S64>(rect.bottom - rect.top);
}
EXPORT_CPP Bool _wndBaseGetVisible(SClass* me_)
{
return IsWindowVisible(reinterpret_cast<SWndBase*>(me_)->WndHandle) != FALSE;
}
EXPORT_CPP void _wndBaseScreenToClient(SClass* me_, S64* clientX, S64* clientY, S64 screenX, S64 screenY)
{
POINT point;
point.x = static_cast<LONG>(screenX);
point.y = static_cast<LONG>(screenY);
ScreenToClient(reinterpret_cast<SWndBase*>(me_)->WndHandle, &point);
*clientX = static_cast<S64>(point.x);
*clientY = static_cast<S64>(point.y);
}
EXPORT_CPP void _wndBaseSetEnabled(SClass* me_, Bool is_enabled)
{
EnableWindow(reinterpret_cast<SWndBase*>(me_)->WndHandle, is_enabled ? TRUE : FALSE);
}
EXPORT_CPP void _wndBaseSetPos(SClass* me_, S64 x, S64 y, S64 width, S64 height)
{
THROWDBG(width < 0 || height < 0, 0xe9170006);
SetWindowPos(reinterpret_cast<SWndBase*>(me_)->WndHandle, nullptr, (int)x, (int)y, (int)width, (int)height, SWP_NOZORDER);
}
EXPORT_CPP void _wndBaseSetRedraw(SClass* me_, Bool is_enabled)
{
SWndBase* me2 = reinterpret_cast<SWndBase*>(me_);
HWND wnd = me2->WndHandle;
if (me2->RedrawEnabled != is_enabled)
{
me2->RedrawEnabled = is_enabled;
if (is_enabled)
{
SendMessage(wnd, WM_SETREDRAW, TRUE, 0);
InvalidateRect(wnd, nullptr, TRUE);
}
else
SendMessage(wnd, WM_SETREDRAW, FALSE, 0);
}
}
EXPORT_CPP void _wndBaseSetVisible(SClass* me_, Bool is_visible)
{
ShowWindow(reinterpret_cast<SWndBase*>(me_)->WndHandle, is_visible ? SW_SHOW : SW_HIDE);
}
EXPORT_CPP Bool _act()
{
if (ExitAct || WndCnt == 0)
return False;
{
MSG msg;
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
switch (msg.message)
{
case WM_QUIT:
ExitAct = True;
return False;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (OnKeyPress != nullptr)
{
U64 shiftCtrl = 0;
shiftCtrl |= (GetKeyState(VK_SHIFT) & 0x8000) != 0 ? 1 : 0;
shiftCtrl |= (GetKeyState(VK_CONTROL) & 0x8000) != 0 ? 2 : 0;
if (static_cast<Bool>(reinterpret_cast<U64>(Call2Asm(reinterpret_cast<void*>(static_cast<U64>(msg.wParam)), reinterpret_cast<void*>(shiftCtrl), OnKeyPress))))
continue;
}
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
Sleep(1);
return True;
}
EXPORT_CPP S64 _colorDialog(SClass* parent, S64 default_color)
{
THROWDBG(default_color < 0 || 0xffffff < default_color, 0xe9170006);
CHOOSECOLOR choose_color = { 0 };
choose_color.lStructSize = sizeof(CHOOSECOLOR);
choose_color.hwndOwner = parent == nullptr ? nullptr : reinterpret_cast<SWndBase*>(parent)->WndHandle;
choose_color.rgbResult = static_cast<COLORREF>(((default_color & 0xff) << 16) | (default_color & 0xff00) | ((default_color & 0xff0000) >> 16));
choose_color.Flags = CC_FULLOPEN | CC_RGBINIT;
DWORD colors[16];
for (int i = 0; i < 16; i++)
colors[i] = 0xffffff;
choose_color.lpCustColors = colors;
if (ChooseColor(&choose_color))
{
S64 result = static_cast<S64>(choose_color.rgbResult);
return ((result & 0xff) << 16) | (result & 0xff00) | ((result & 0xff0000) >> 16);
}
return -1;
}
EXPORT_CPP void* _exeDir()
{
size_t len = wcslen(EnvVars.ResRoot);
U8* result = (U8*)AllocMem(0x10 + sizeof(Char) * (len + 1));
*(S64*)(result + 0x00) = DefaultRefCntFunc;
*(S64*)(result + 0x08) = len;
memcpy(result + 0x10, EnvVars.ResRoot, sizeof(Char) * (len + 1));
return result;
}
EXPORT_CPP void _fileDialogDir(const U8* defaultDir)
{
if (defaultDir == nullptr)
{
FileDialogDir[0] = L'\0';
return;
}
const Char* path = reinterpret_cast<const Char*>(defaultDir + 0x10);
size_t len = wcslen(path);
if (len > KUIN_MAX_PATH)
{
FileDialogDir[0] = L'\0';
return;
}
for (size_t i = 0; i < len; i++)
FileDialogDir[i] = path[i] == L'/' ? L'\\' : path[i];
FileDialogDir[len] = L'\0';
}
EXPORT_CPP void _getCaretPos(S64* x, S64* y)
{
POINT point;
if (!GetCaretPos(&point))
{
*x = -1;
*y = -1;
}
else
{
*x = static_cast<S64>(point.x);
*y = static_cast<S64>(point.y);
}
}
EXPORT_CPP void* _getClipboardStr()
{
if (IsClipboardFormatAvailable(CF_UNICODETEXT) == 0)
return nullptr;
if (OpenClipboard(nullptr) == 0)
return nullptr;
HGLOBAL handle = GetClipboardData(CF_UNICODETEXT);
if (handle == nullptr)
{
CloseClipboard();
return nullptr;
}
U8* result = nullptr;
{
const Char* buf = static_cast<Char*>(GlobalLock(handle));
if (buf == nullptr)
{
CloseClipboard();
return nullptr;
}
size_t len = 0;
{
const Char* ptr = buf;
while (*ptr != L'\0')
{
if (*ptr != L'\r')
len++;
ptr++;
}
}
result = static_cast<U8*>(AllocMem(0x10 + sizeof(Char) * (len + 1)));
*reinterpret_cast<S64*>(result + 0x00) = DefaultRefCntFunc;
*reinterpret_cast<S64*>(result + 0x08) = len;
{
const Char* src = buf;
Char* dst = reinterpret_cast<Char*>(result + 0x10);
const Char* top = dst;
UNUSED(top);
while (*src != L'\0')
{
if (*src != L'\r')
{
*dst = *src;
dst++;
}
src++;
}
*dst = L'\0';
ASSERT(top + len == dst);
}
}
GlobalUnlock(handle);
CloseClipboard();
return result;
}
EXPORT_CPP void* _getOnKeyPress()
{
return OnKeyPress;
}
EXPORT_CPP Bool _key(S64 key)
{
return (GetKeyState(static_cast<int>(key)) & 0x8000) != 0;
}
EXPORT_CPP SClass* _makeMenu(SClass* me_)
{
SMenu* me2 = reinterpret_cast<SMenu*>(me_);
me2->MenuHandle = CreateMenu();
if (me2->MenuHandle == nullptr)
THROW(0xe9170009);
me2->Children = AllocMem(0x28);
*(S64*)me2->Children = 1;
memset((U8*)me2->Children + 0x08, 0x00, 0x20);
return me_;
}
EXPORT_CPP SClass* _makePopup(SClass* me_)
{
SMenu* me2 = reinterpret_cast<SMenu*>(me_);
me2->MenuHandle = CreatePopupMenu();
if (me2->MenuHandle == nullptr)
THROW(0xe9170009);
me2->Children = AllocMem(0x28);
*(S64*)me2->Children = 1;
memset((U8*)me2->Children + 0x08, 0x00, 0x20);
return me_;
}
EXPORT_CPP SClass* _makeTabOrder(SClass* me_, U8* ctrls)
{
STabOrder* me2 = reinterpret_cast<STabOrder*>(me_);
THROWDBG(ctrls == nullptr, EXCPT_ACCESS_VIOLATION);
S64 len = *reinterpret_cast<S64*>(ctrls + 0x08);
void** ptr = reinterpret_cast<void**>(ctrls + 0x10);
void* result = AllocMem(0x10 + sizeof(void*) * static_cast<size_t>(len));
static_cast<S64*>(result)[0] = 1;
static_cast<S64*>(result)[1] = len;
void** result2 = reinterpret_cast<void**>(static_cast<U8*>(result) + 0x10);
for (S64 i = 0; i < len; i++)
{
if (ptr[i] == nullptr)
result2[i] = nullptr;
else
{
(*static_cast<S64*>(ptr[i]))++;
result2[i] = ptr[i];
}
}
me2->Ctrls = result;
return me_;
}
EXPORT_CPP SClass* _makeWnd(SClass* me_, SClass* parent, S64 style, S64 width, S64 height, const U8* text)
{
SWndBase* me2 = reinterpret_cast<SWndBase*>(me_);
me2->Kind = static_cast<EWndKind>(static_cast<S64>(WndKind_WndNormal) + (style & 0xffff));
THROWDBG(width < 0 || height < 0, 0xe9170006);
int width2 = static_cast<int>(width);
int height2 = static_cast<int>(height);
HWND parent2 = parent == nullptr ? nullptr : reinterpret_cast<SWndBase*>(parent)->WndHandle;
DWORD ex_style = 0;
if ((style & static_cast<S64>(WndKind_WndLayered)) != 0)
ex_style |= WS_EX_LAYERED;
switch (me2->Kind)
{
case WndKind_WndNormal:
me2->WndHandle = CreateWindowEx(ex_style, L"KuinWndNormalClass", text == nullptr ? L"" : reinterpret_cast<const Char*>(text + 0x10), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, width2, height2, parent2, nullptr, Instance, nullptr);
break;
case WndKind_WndFix:
me2->WndHandle = CreateWindowEx(ex_style, L"KuinWndFixClass", text == nullptr ? L"" : reinterpret_cast<const Char*>(text + 0x10), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, width2, height2, parent2, nullptr, Instance, nullptr);
break;
case WndKind_WndAspect:
me2->WndHandle = CreateWindowEx(ex_style, L"KuinWndAspectClass", text == nullptr ? L"" : reinterpret_cast<const Char*>(text + 0x10), (WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX) | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, width2, height2, parent2, nullptr, Instance, nullptr);
break;
case WndKind_WndPopup:
me2->WndHandle = CreateWindowEx(ex_style | WS_EX_TOOLWINDOW, L"KuinWndDialogClass", text == nullptr ? L"" : reinterpret_cast<const Char*>(text + 0x10), WS_POPUP | WS_BORDER | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, width2, height2, parent2, nullptr, Instance, nullptr);
break;
case WndKind_WndDialog:
me2->WndHandle = CreateWindowEx(ex_style | WS_EX_TOOLWINDOW, L"KuinWndDialogClass", text == nullptr ? L"" : reinterpret_cast<const Char*>(text + 0x10), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, width2, height2, parent2, nullptr, Instance, nullptr);
break;
default:
THROWDBG(True, 0xe9170006);
break;
}
if (me2->WndHandle == nullptr)
THROW(0xe9170009);
if ((style & static_cast<S64>(WndKind_WndLayered)) != 0)
SetLayeredWindowAttributes(me2->WndHandle, 0, 255, LWA_ALPHA);
if ((style & static_cast<S64>(WndKind_WndNoMinimize)) != 0)
SetWindowLongPtr(me2->WndHandle, GWL_STYLE, GetWindowLongPtr(me2->WndHandle, GWL_STYLE) & ~WS_MINIMIZEBOX);
int border_x;
int border_y;
{
RECT window;
RECT client;
GetWindowRect(me2->WndHandle, &window);
GetClientRect(me2->WndHandle, &client);
border_x = static_cast<int>((window.right - window.left) - (client.right - client.left));
border_y = static_cast<int>((window.bottom - window.top) - (client.bottom - client.top));
}
me2->Name = nullptr;
me2->DefaultWndProc = nullptr;
me2->CtrlFlag = static_cast<U64>(CtrlFlag_AnchorLeft) | static_cast<U64>(CtrlFlag_AnchorTop);
me2->DefaultX = 0;
me2->DefaultY = 0;
me2->DefaultWidth = static_cast<U16>(width);
me2->DefaultHeight = static_cast<U16>(height);
me2->RedrawEnabled = True;
me2->Children = AllocMem(0x28);
*(S64*)me2->Children = 1;
memset((U8*)me2->Children + 0x08, 0x00, 0x20);
SetWindowPos(me2->WndHandle, nullptr, 0, 0, static_cast<int>(width) + border_x, static_cast<int>(height) + border_y, SWP_NOMOVE | SWP_NOZORDER);
if (me2->Kind == WndKind_WndAspect)
{
RECT rect;
GetClientRect(me2->WndHandle, &rect);
double w = static_cast<double>(rect.right) - static_cast<double>(rect.left);
double h = static_cast<double>(rect.bottom) - static_cast<double>(rect.top);
if (w / h > static_cast<double>(width) / static_cast<double>(height))
w = h * static_cast<double>(width) / static_cast<double>(height);
else
h = w * static_cast<double>(height) / static_cast<double>(width);
SetWindowPos(me2->WndHandle, nullptr, 0, 0, static_cast<int>(w) + border_x, static_cast<int>(h) + border_y, SWP_NOMOVE | SWP_NOZORDER);
}
SetWindowLongPtr(me2->WndHandle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(me2));
{
SWnd* me3 = reinterpret_cast<SWnd*>(me_);
me3->MinWidth = 128;
me3->MinHeight = 128;
me3->MaxWidth = static_cast<U16>(-1);
me3->MaxHeight = static_cast<U16>(-1);
me3->OnClose = nullptr;
me3->OnActivate = nullptr;
me3->OnPushMenu = nullptr;
me3->OnDropFiles = nullptr;
me3->OnResize = nullptr;
me3->ModalLock = False;
}
SendMessage(me2->WndHandle, WM_SETFONT, reinterpret_cast<WPARAM>(FontCtrl), static_cast<LPARAM>(FALSE));
ShowWindow(me2->WndHandle, SW_SHOWNORMAL);
WndCnt++;
return me_;
}
EXPORT_CPP S64 _msgBox(SClass* parent, const U8* text, const U8* title, S64 icon, S64 btn)
{
return MessageBox(parent == nullptr ? nullptr : reinterpret_cast<SWndBase*>(parent)->WndHandle, text == nullptr ? L"" : reinterpret_cast<const Char*>(text + 0x10), title == nullptr ? L"" : reinterpret_cast<const Char*>(title + 0x10), static_cast<UINT>(icon | btn));
}
EXPORT_CPP void* _openFileDialog(SClass* parent, const U8* filter, S64 defaultFilter)
{
Char path[KUIN_MAX_PATH + 1];
path[0] = L'\0';
int filter_num;
Char* filter_mem = ParseFilter(filter, &filter_num);
THROWDBG(!(filter_num == 0 && defaultFilter == 0 || filter_num != 0 && 0 <= defaultFilter && defaultFilter < filter_num), 0xe9170006);
OPENFILENAME open_file_name;
memset(&open_file_name, 0, sizeof(OPENFILENAME));
open_file_name.lStructSize = sizeof(OPENFILENAME);
open_file_name.hwndOwner = parent == nullptr ? nullptr : reinterpret_cast<SWndBase*>(parent)->WndHandle;
open_file_name.lpstrFilter = filter_mem;
open_file_name.nFilterIndex = filter_num == 0 ? 0 : static_cast<DWORD>(defaultFilter + 1);
open_file_name.lpstrFile = path;
open_file_name.nMaxFile = KUIN_MAX_PATH + 1;
open_file_name.lpstrInitialDir = FileDialogDir[0] == L'\0' ? nullptr : FileDialogDir;
open_file_name.lpstrTitle = nullptr;
open_file_name.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
BOOL success = GetOpenFileName(&open_file_name);
if (filter_mem != nullptr)
FreeMem(filter_mem);
if (success == FALSE)
return nullptr;
size_t len = wcslen(path);
U8* result = static_cast<U8*>(AllocMem(0x10 + sizeof(Char) * static_cast<size_t>(len + 1)));
*reinterpret_cast<S64*>(result + 0x00) = DefaultRefCntFunc;
*reinterpret_cast<S64*>(result + 0x08) = static_cast<S64>(len);
Char* dst = reinterpret_cast<Char*>(result + 0x10);
for (size_t i = 0; i <= len; i++)
dst[i] = path[i] == L'\\' ? L'/' : path[i];
return result;
}
EXPORT_CPP void* _saveFileDialog(SClass* parent, const U8* filter, S64 defaultFilter, const U8* defaultExt)
{
Char path[KUIN_MAX_PATH + 1];
path[0] = L'\0';
int filter_num;
Char* filter_mem = ParseFilter(filter, &filter_num);
THROWDBG(!(filter_num == 0 && defaultFilter == 0 || filter_num != 0 && 0 <= defaultFilter && defaultFilter < filter_num), 0xe9170006);
OPENFILENAME open_file_name;
memset(&open_file_name, 0, sizeof(OPENFILENAME));
open_file_name.lStructSize = sizeof(OPENFILENAME);
open_file_name.hwndOwner = parent == nullptr ? nullptr : reinterpret_cast<SWndBase*>(parent)->WndHandle;
open_file_name.lpstrFilter = filter_mem;
open_file_name.nFilterIndex = filter_num == 0 ? 0 : static_cast<DWORD>(defaultFilter + 1);
open_file_name.lpstrFile = path;
open_file_name.nMaxFile = KUIN_MAX_PATH + 1;
open_file_name.lpstrInitialDir = FileDialogDir[0] == L'\0' ? nullptr : FileDialogDir;
open_file_name.lpstrTitle = nullptr;
open_file_name.lpstrDefExt = defaultExt == nullptr ? nullptr : reinterpret_cast<const Char*>(defaultExt + 0x10);
open_file_name.Flags = OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
BOOL success = GetSaveFileName(&open_file_name);
if (filter_mem != nullptr)
FreeMem(filter_mem);
if (success == FALSE)
return nullptr;
size_t len = wcslen(path);
U8* result = static_cast<U8*>(AllocMem(0x10 + sizeof(Char) * static_cast<size_t>(len + 1)));
*reinterpret_cast<S64*>(result + 0x00) = DefaultRefCntFunc;
*reinterpret_cast<S64*>(result + 0x08) = static_cast<S64>(len);
Char* dst = reinterpret_cast<Char*>(result + 0x10);
for (size_t i = 0; i <= len; i++)
dst[i] = path[i] == L'\\' ? L'/' : path[i];
return result;
}
EXPORT_CPP void _screenSize(S64* width, S64* height)
{
*width = static_cast<S64>(GetSystemMetrics(SM_CXSCREEN));
*height = static_cast<S64>(GetSystemMetrics(SM_CYSCREEN));
}
EXPORT_CPP void _setClipboardStr(const U8* str)
{
size_t len = static_cast<size_t>(*reinterpret_cast<const S64*>(str + 0x08));
{
const Char* ptr = reinterpret_cast<const Char*>(str + 0x10);
while (*ptr != L'\0')
{
if (*ptr == L'\n')
len++;
ptr++;
}
}
HGLOBAL handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GHND, sizeof(Char) * (len + 1));
if (handle == nullptr)
return;
{
const Char* ptr = reinterpret_cast<const Char*>(str + 0x10);
Char* buf = static_cast<Char*>(GlobalLock(handle));
if (buf == nullptr)
{
GlobalFree(handle);
return;
}
const Char* top = buf;
UNUSED(top);
while (*ptr != L'\0')
{
if (*ptr == L'\n')
{
*buf = L'\r';
buf++;
}
*buf = *ptr;
buf++;
ptr++;
}
*buf = L'\0';
ASSERT(top + len == buf);
GlobalUnlock(handle);
}
if (OpenClipboard(nullptr) == 0)
{
GlobalFree(handle);
return;
}
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, static_cast<HANDLE>(handle));
CloseClipboard();
}
EXPORT_CPP void _setOnKeyPress(void* onKeyPressFunc)
{
OnKeyPress = onKeyPressFunc;
}
EXPORT_CPP void* _sysDir(S64 kind)
{
Char path[KUIN_MAX_PATH + 2];
if (!SHGetSpecialFolderPath(NULL, path, (int)kind, TRUE))
return NULL;
NormPath(path, True);
size_t len = wcslen(path);
U8* result = (U8*)AllocMem(0x10 + sizeof(Char) * (len + 1));
*(S64*)(result + 0x00) = DefaultRefCntFunc;
*(S64*)(result + 0x08) = (S64)len;
wcscpy((Char*)(result + 0x10), path);
return result;
}
static LRESULT CALLBACK CommonWndProc(HWND wnd, SWndBase* wnd2, SWnd* wnd3, UINT msg, WPARAM w_param, LPARAM l_param)
{
switch (msg)
{
case WM_CLOSE:
if (wnd3->OnClose != nullptr)
{
if (!static_cast<Bool>(reinterpret_cast<U64>(Call1Asm(IncWndRef(reinterpret_cast<SClass*>(wnd2)), wnd3->OnClose))))
return 0;
}
DestroyWindow(wnd);
return 0;
case WM_DESTROY:
WndCnt--;
if (wnd3->ModalLock)
{
HWND parent = GetWindow(wnd2->WndHandle, GW_OWNER);
if (parent != nullptr)
{
EnableWindow(parent, TRUE);
SetActiveWindow(parent);
}
wnd3->ModalLock = False;
}
return 0;
case WM_ACTIVATE:
if (wnd3->OnActivate != nullptr)
Call3Asm(IncWndRef(reinterpret_cast<SClass*>(wnd2)), reinterpret_cast<void*>(static_cast<S64>(LOWORD(w_param) != 0)), reinterpret_cast<void*>(static_cast<S64>(HIWORD(w_param) != 0)), wnd3->OnActivate);
return 0;
case WM_DROPFILES:
if (wnd3->OnDropFiles != nullptr)
{
HDROP drop = reinterpret_cast<HDROP>(w_param);
UINT num = DragQueryFile(drop, 0xffffffff, nullptr, 0);
void* buf = AllocMem(0x10 + sizeof(void*) * static_cast<size_t>(num));
(static_cast<S64*>(buf))[0] = 1;
(static_cast<S64*>(buf))[1] = static_cast<S64>(num);
void** ptr = reinterpret_cast<void**>(static_cast<U8*>(buf) + 0x10);
for (UINT i = 0; i < num; i++)
{
UINT len = DragQueryFile(drop, i, nullptr, 0);
void* buf2 = AllocMem(0x10 + sizeof(Char) * (static_cast<size_t>(len) + 1));
(static_cast<S64*>(buf2))[0] = 1;
(static_cast<S64*>(buf2))[1] = static_cast<S64>(len);
Char* str = static_cast<Char*>(buf2) + 0x08;
DragQueryFile(drop, i, str, len + 1);
for (UINT j = 0; j < len; j++)
str[j] = str[j] == L'\\' ? L'/' : str[j];
ptr[i] = buf2;
}
DragFinish(drop);
Call2Asm(IncWndRef(reinterpret_cast<SClass*>(wnd2)), buf, wnd3->OnDropFiles);
}
return 0;
case WM_COMMAND:
case WM_NOTIFY:
CommandAndNotify(wnd, msg, w_param, l_param);
return 0;
}
return DefWindowProc(wnd, msg, w_param, l_param);
}
static LRESULT CALLBACK WndProcWndNormal(HWND wnd, UINT msg, WPARAM w_param, LPARAM l_param)
{
SWndBase* wnd2 = ToWnd(wnd);
SWnd* wnd3 = reinterpret_cast<SWnd*>(wnd2);
if (wnd2 == nullptr)
return DefWindowProc(wnd, msg, w_param, l_param);
ASSERT(wnd2->Kind == WndKind_WndNormal);
switch (msg)
{
case WM_SIZE:
EnumChildWindows(wnd, ResizeCallback, 0);
if (wnd3->OnResize != nullptr)
{
Call1Asm(IncWndRef(reinterpret_cast<SClass*>(wnd2)), wnd3->OnResize);
}
return 0;
case WM_GETMINMAXINFO:
{
LPMINMAXINFO info = reinterpret_cast<LPMINMAXINFO>(l_param);
if (wnd3->MinWidth != -1)
info->ptMinTrackSize.x = static_cast<LONG>(wnd3->MinWidth);
if (wnd3->MinHeight != -1)
info->ptMinTrackSize.y = static_cast<LONG>(wnd3->MinHeight);
if (wnd3->MaxWidth != -1)
info->ptMaxTrackSize.x = static_cast<LONG>(wnd3->MaxWidth);
if (wnd3->MaxHeight != -1)
info->ptMaxTrackSize.y = static_cast<LONG>(wnd3->MaxHeight);
}
return 0;
}
return CommonWndProc(wnd, wnd2, wnd3, msg, w_param, l_param);
}
static LRESULT CALLBACK WndProcWndFix(HWND wnd, UINT msg, WPARAM w_param, LPARAM l_param)
{
SWndBase* wnd2 = ToWnd(wnd);
SWnd* wnd3 = reinterpret_cast<SWnd*>(wnd2);
if (wnd2 == nullptr)
return DefWindowProc(wnd, msg, w_param, l_param);
ASSERT(wnd2->Kind == WndKind_WndFix || wnd2->Kind == WndKind_WndPopup || wnd2->Kind == WndKind_WndDialog);
return CommonWndProc(wnd, wnd2, wnd3, msg, w_param, l_param);
}
static LRESULT CALLBACK WndProcWndAspect(HWND wnd, UINT msg, WPARAM w_param, LPARAM l_param)
{
SWndBase* wnd2 = ToWnd(wnd);
SWnd* wnd3 = reinterpret_cast<SWnd*>(wnd2);
if (wnd2 == nullptr)
return DefWindowProc(wnd, msg, w_param, l_param);
ASSERT(wnd2->Kind == WndKind_WndAspect);
switch (msg)
{
case WM_SIZE:
EnumChildWindows(wnd, ResizeCallback, 0);
if (wnd3->OnResize != nullptr)
{
Call1Asm(IncWndRef(reinterpret_cast<SClass*>(wnd2)), wnd3->OnResize);
}
return 0;
case WM_GETMINMAXINFO:
{
LPMINMAXINFO info = reinterpret_cast<LPMINMAXINFO>(l_param);
if (wnd3->MinWidth != -1)
info->ptMinTrackSize.x = static_cast<LONG>(wnd3->MinWidth);
if (wnd3->MinHeight != -1)
info->ptMinTrackSize.y = static_cast<LONG>(wnd3->MinHeight);
if (wnd3->MaxWidth != -1)
info->ptMaxTrackSize.x = static_cast<LONG>(wnd3->MaxWidth);
if (wnd3->MaxHeight != -1)
info->ptMaxTrackSize.y = static_cast<LONG>(wnd3->MaxHeight);
}
return 0;
case WM_SIZING:
{
RECT* r = reinterpret_cast<RECT*>(l_param);
double caption = static_cast<double>(GetSystemMetrics(SM_CYCAPTION));
double border = static_cast<double>(GetSystemMetrics(SM_CYFRAME));
double w = static_cast<double>(r->right) - static_cast<double>(r->left) - border * 2.0;
double h = static_cast<double>(r->bottom) - static_cast<double>(r->top) - caption - border * 2.0;
switch (w_param)
{
case WMSZ_TOP:
case WMSZ_BOTTOM:
r->right = static_cast<LONG>(static_cast<double>(r->left) + h * static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight) + border * 2.0);
return 0;
case WMSZ_LEFT:
case WMSZ_RIGHT:
r->bottom = static_cast<LONG>(static_cast<double>(r->top) + w * static_cast<double>(wnd2->DefaultHeight) / static_cast<double>(wnd2->DefaultWidth) + caption + border * 2.0);
return 0;
case WMSZ_TOPLEFT:
if (w / h < static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight))
r->left = static_cast<LONG>(static_cast<double>(r->right) - h * static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight) - border * 2.0);
else
r->top = static_cast<LONG>(static_cast<double>(r->bottom) - w * static_cast<double>(wnd2->DefaultHeight) / static_cast<double>(wnd2->DefaultWidth) - caption - border * 2.0);
return 0;
case WMSZ_TOPRIGHT:
if (w / h < static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight))
r->right = static_cast<LONG>(static_cast<double>(r->left) + h * static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight) + border * 2.0);
else
r->top = static_cast<LONG>(static_cast<double>(r->bottom) - w * static_cast<double>(wnd2->DefaultHeight) / static_cast<double>(wnd2->DefaultWidth) - caption - border * 2.0);
return 0;
case WMSZ_BOTTOMLEFT:
if (w / h < static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight))
r->left = static_cast<LONG>(static_cast<double>(r->right) - h * static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight) - border * 2.0);
else
r->bottom = static_cast<LONG>(static_cast<double>(r->top) + w * static_cast<double>(wnd2->DefaultHeight) / static_cast<double>(wnd2->DefaultWidth) + caption + border * 2.0);
return 0;
case WMSZ_BOTTOMRIGHT:
if (w / h < static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight))
r->right = static_cast<LONG>(static_cast<double>(r->left) + h * static_cast<double>(wnd2->DefaultWidth) / static_cast<double>(wnd2->DefaultHeight) + border * 2.0);
else
r->bottom = static_cast<LONG>(static_cast<double>(r->top) + w * static_cast<double>(wnd2->DefaultHeight) / static_cast<double>(wnd2->DefaultWidth) + caption + border * 2.0);
return 0;
}
}
break;
}
return CommonWndProc(wnd, wnd2, wnd3, msg, w_param, l_param);
}
static Char* ParseFilter(const U8* filter, int* num)
{
if (filter == nullptr)
{
*num = 0;
return nullptr;
}
S64 len_parent = *reinterpret_cast<const S64*>(filter + 0x08);
THROWDBG(len_parent % 2 != 0, 0xe9170006);
S64 total = 0;
{
const void* const* ptr = reinterpret_cast<const void* const*>(filter + 0x10);
for (S64 i = 0; i < len_parent; i++)
{
S64 len = *reinterpret_cast<const S64*>(static_cast<const U8*>(*ptr) + 0x08);
total += len + 1;
ptr++;
}
}
Char* result = static_cast<Char*>(AllocMem(sizeof(Char) * static_cast<size_t>(total + 1)));
{
const void* const* ptr = reinterpret_cast<const void* const*>(filter + 0x10);
Char* ptr2 = result;
for (S64 i = 0; i < len_parent; i++)
{
S64 len = *reinterpret_cast<const S64*>(static_cast<const U8*>(*ptr) + 0x08);
memcpy(ptr2, static_cast<const U8*>(*ptr) + 0x10, sizeof(Char) * static_cast<size_t>(len + 1));
ptr++;
ptr2 += len + 1;
}
*ptr2 = L'\0';
}
*num = (int)(len_parent / 2);
return result;
}
static void NormPath(Char* path, Bool dir)
{
if (*path == L'\0')
return;
do
{
if (*path == L'\\')
*path = L'/';
path++;
} while (*path != L'\0');
if (dir && path[-1] != L'/')
{
path[0] = L'/';
path[1] = L'\0';
}
}
| [
"[email protected]"
] | |
5a0ac6b8ea7b23fe49ffda41546d788416d5b6f0 | 3129437c0a52c8cf5e98cdf05dcc5942dac747a7 | /src/home_base_motion_behavior.cc | 8ab971ecc3072fa6aa60de660748a09edefaad46 | [] | no_license | atturner2/cplusplus_robot_simulator | d1722a865a68aac3965ae6129e89923097dd63d0 | 9a169effd3953fcffcc41d286d60a19c0c699a34 | refs/heads/master | 2020-03-29T04:01:49.590455 | 2018-09-19T21:33:53 | 2018-09-19T21:33:53 | 149,512,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | cc | /**
* @file home_base_motion_behavior.cc
*
* @copyright 2017 3081 Staff, All rights reserved.
*/
// Includes
#include "src/home_base_motion_behavior.h"
#include "src/arena_mobile_entity.h"
///< <AS you can see this is a blatant copy of robot>
NAMESPACE_BEGIN(csci3081);
///< Member Functions
void HomeBaseMotionBehavior::UpdatePosition(ArenaMobileEntity * const ent,
unsigned int dt) {
///< save positon for debuggin purposes
Position new_pos = ent->get_pos();
Position old_pos = ent->get_pos();
///< Movement is always along the heading_angle (i.e. the hypotenuse)
new_pos.x += cos(ent->get_heading_angle()*M_PI/180.0)*ent->get_speed()*dt;
new_pos.y += sin(ent->get_heading_angle()*M_PI/180.0)*ent->get_speed()*dt;
ent->set_pos(new_pos);
///< Print stuff here if it's not working
}
NAMESPACE_END(csci3081)
| [
"[email protected]"
] | |
1be1f6e82cf4d1d8f51b6f47e4b543682c0e4040 | 401a917133c8af95cd66c8f9135de0cd2586c630 | /wsn/HnGui/hnmptablewidget.h | b4e6645dbe12db3ede4041d1e04fbd3c76fadf53 | [] | no_license | 63830708/Qt-DispelSystem | 7a8cf286142d9ed790fdab629195618daf577517 | 71be6f6e6583dd2bbfd9c28e7ff032b70b6c5209 | refs/heads/master | 2020-03-26T22:57:59.770263 | 2017-11-13T13:58:28 | 2017-11-13T13:58:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,061 | h | #ifndef HNMPTABLEWIDGET_H
#define HNMPTABLEWIDGET_H
#include <QWidget>
#include <QSqlRelationalTableModel>
#include <QHeaderView>
#include <QTableView>
#include "hntablewidget.h"
namespace Ui {
class HNMPTableWidget;
}
/**
* @brief The HNMPTableWidget class
* 关于视图规格的改变改变到上层
* 这里的控件使用默认视图
* 这里的控件只是Table-DB关系,没有Tree/List模型
*/
class HNMPTableWidget : public QWidget
{
Q_OBJECT
public:
explicit HNMPTableWidget(QWidget *parent = 0);
~HNMPTableWidget();
void setDB(QString db);
void setTable(QString table);
void setRecordNumPerPage(int num);
void setColumnHidden(int key, bool value = true);
void setSelectionMode(QAbstractItemView::SelectionMode mode = QAbstractItemView::MultiSelection);
void setResizeMode(QHeaderView::ResizeMode mode = QHeaderView::ResizeToContents);
void setResizeMode(int column, QHeaderView::ResizeMode mode = QHeaderView::ResizeToContents);
void setAlternatingRowColors(bool alt = true);
void setHeaderData(int i, Qt::Orientation, QString data);
void setColumnWidth(int column, int width);
void query(QString filter = "1=1");
void selectedRows(int column, QVector<QStringList> & strl);
HNTableWidget* selectedRows(int column = 0);
int pageNum();
int currentPage();
void setCurrentPage(int page);
public slots:
void removeSelectedRows(int column = 0);
private slots:
void on_btnLeft_clicked();
void on_btnRight_clicked();
void on_btnJump_clicked();
void on_btnLeftHead_clicked();
void on_btnRightHead_clicked();
private:
Ui::HNMPTableWidget *ui;
QSqlDatabase m_db;
QString m_name;
QString m_table;
int m_numPerPage ;
QHash<int, bool> m_columnHidden;
QHash<int, QString> m_headerData;
QHash<int, int> m_columnWidth;
QHeaderView::ResizeMode resizeMode;
QHash<int, QHeaderView::ResizeMode> m_resizeMode;
QAbstractItemView::SelectionMode selectionMode;
bool altColor;
};
#endif // HNMPTABLEWIDGET_H
| [
"[email protected]"
] | |
e382a18daec051cc96075a51e56148c4477cae42 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_old_hunk_1704.cpp | 9d7a9f9d701eb03401bd3d6ba13ae97cfbeb18ca | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 266 | cpp |
printf("\n");
show_progress();
}
static void handle_tail(struct object_array *commits, struct rev_info *revs)
{
struct commit *commit;
while (commits->nr) {
commit = (struct commit *)commits->objects[commits->nr - 1].item;
if (has_unshown_parent(commit))
| [
"[email protected]"
] | |
feb057f7ef2c250bc2ca51523247ea2cf8cbcedb | 51c1c5e9b8489ef8afa029b162aaf4c8f8bda7fc | /easytexpacker/src/libtexpacker/Sprite.h | 6796cc4b27531c54ed27b6946bf9fb10669965e0 | [
"MIT"
] | permissive | aimoonchen/easyeditor | 3e5c77f0173a40a802fd73d7b741c064095d83e6 | 9dabdbfb8ad7b00c992d997d6662752130d5a02d | refs/heads/master | 2021-04-26T23:06:27.016240 | 2018-02-12T02:28:50 | 2018-02-12T02:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 827 | h | #ifndef _EASYTEXPACKER_SPRITE_H_
#define _EASYTEXPACKER_SPRITE_H_
#include <algorithm>
namespace etexpacker
{
struct Sprite
{
Sprite(const RectSize* size, Rect* pos)
: size(size), pos(pos) {}
const RectSize* size;
Rect* pos;
}; // Sprite
enum SortStrategy
{
e_area,
e_max_edge,
e_tot_edges
};
struct SpriteCmp
{
SpriteCmp(SortStrategy strategy) : m_strategy(strategy) {}
bool operator() (const Sprite& s0, const Sprite& s1) const {
int w0 = s0.size->width, h0 = s0.size->height;
int w1 = s1.size->width, h1 = s1.size->height;
if (m_strategy == e_area) {
return w0 * h0 > w1 * h1;
} else if (m_strategy == e_max_edge) {
return std::max(w0, h0) > std::max(w1, h1);
} else {
return w0 + h0 > w1 + h1;
}
}
SortStrategy m_strategy;
}; // SpriteCmp
}
#endif // _EASYTEXPACKER_SPRITE_H_ | [
"[email protected]"
] | |
c992ed3a155ed0840d953018ff83e1349743cb1d | fc7fec631d38ca4267ba393e6d16ba804e980be7 | /Stack/StackClass.cpp | 83268dc5f856434efc4873f53931795b14eda958 | [] | no_license | TanyaZheleva/DataStructures | a45f6a1816ffdd101c76c4410f2d131621b72cee | 72ecb6a99df768115889020e50637c290e609efe | refs/heads/master | 2020-07-21T17:24:35.167236 | 2020-01-23T15:35:22 | 2020-01-23T15:35:22 | 206,931,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 783 | cpp | #include "Stack.h"
#include <iostream>
Stack::Stack(int size)
{
arr = new student[size];
}
Stack::~Stack()
{
delete[] arr;
}
Stack::Stack(const Stack& old):size(old.size),top(old.top)
{
for (int i = 0; i < top; i++)
{
arr[i] = old.arr[i];
}
}
Stack& Stack::operator=(const Stack& other)
{
if (&other != this)
{
size = other.size;
top = other.top;
for (int i = 0; i < top; i++)
{
arr[i] = other.arr[i];
}
}
return *this;
}
void Stack::push(student x)
{
if (top >= size)
{
std::cout << "Stack is already full.\n";
}
else
{
arr[top] = x;
top++;
}
}
student& Stack::pop()
{
if (top == 0)
{
std::cout << "Empty stack.\n";
}
else
{
return arr[--top];
}
}
bool Stack::isEmpty()const
{
if (top == 0)
{
return true;
}
return false;
} | [
"[email protected]"
] | |
b7e975f7f2d609e6c7dc46a68ccb640efe86c68b | 7a2ffb549ed0e851739d9678c1cbf21b996feaa3 | /engine/Graphics/Animation.cpp | 972d022998b4202323c5c4bffa98b90873424e20 | [] | no_license | benit8/GameEngine | c270515f222fad81c806a8840e47ce1f85fea398 | 5a66b0148892f4ea650676dfdd103f386ca6716c | refs/heads/master | 2020-05-14T11:02:18.510592 | 2019-05-14T18:15:35 | 2019-05-14T18:15:35 | 181,770,553 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,619 | cpp | /*
** EPITECH PROJECT, 2018
** R-Type client
** File description:
** Animation.cpp
*/
#include <iostream>
#include "Animation.hpp"
////////////////////////////////////////////////////////////////////////////////
Animation::Animation(sf::Sprite &target)
: m_target(target)
, m_progress(sf::Time::Zero)
, m_nextProgressStep(sf::Time::Zero)
, m_frameIndex(0)
, m_finished(false)
{
}
////////////////////////////////////////////////////////////////////////////////
void Animation::addFrame(sf::IntRect rect, sf::Time duration)
{
addFrame({rect, duration});
}
void Animation::addFrame(Frame frame)
{
m_frames.push_back(frame);
}
void Animation::update(const sf::Time &elapsed, bool loop, bool reset)
{
if (m_frames.empty()) {
std::cerr << "Animation has no frames" << std::endl;
return;
}
if (m_finished)
return;
if (m_nextProgressStep == sf::Time::Zero) {
m_nextProgressStep = m_frames[0].duration;
}
m_progress += elapsed;
if (m_progress >= m_nextProgressStep) {
m_frameIndex++;
if (m_frameIndex >= m_frames.size()) {
if (loop) {
m_frameIndex = 0;
m_nextProgressStep = sf::Time::Zero;
}
else if (reset) {
m_finished = true;
m_frameIndex = 0;
m_nextProgressStep = sf::Time::Zero;
}
else
m_frameIndex--;
}
m_target.setTextureRect(m_frames[m_frameIndex].rect);
m_nextProgressStep += m_frames[m_frameIndex].duration;
}
}
void Animation::reset()
{
m_progress = sf::Time::Zero;
m_nextProgressStep = sf::Time::Zero;
m_frameIndex = 0;
m_finished = false;
}
const std::vector<Animation::Frame> &Animation::getFrames() const
{
return m_frames;
} | [
"[email protected]"
] | |
ead208af9b11943b1214a6327013a41190d5d5a9 | f929f6056f7225ff8a1fd908fe0f0f2e75768a1e | /service/escape-analysis/LocalPointersAnalysis.h | ce2367f93f0bd0ea8b0e6cb1d9844f58bf786c76 | [
"MIT"
] | permissive | Harry-L/redex | 5c63ffb67af43dc7abfd187991c48ed84dd37eed | c5696c06727ff9cb79279a08a3bae0f4553bd04c | refs/heads/master | 2020-11-26T17:53:33.670640 | 2019-12-19T17:07:44 | 2019-12-19T17:10:04 | 229,165,403 | 0 | 0 | MIT | 2019-12-20T01:13:30 | 2019-12-20T01:13:29 | null | UTF-8 | C++ | false | false | 10,809 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <ostream>
#include "BaseIRAnalyzer.h"
#include "CallGraph.h"
#include "ConcurrentContainers.h"
#include "ControlFlow.h"
#include "DexClass.h"
#include "ObjectDomain.h"
#include "PatriciaTreeMapAbstractPartition.h"
#include "PatriciaTreeSetAbstractDomain.h"
#include "ReducedProductAbstractDomain.h"
#include "S_Expression.h"
/*
* This analysis identifies heap values that are allocated within a given
* method and have not escaped it. Specifically, it determines all the pointers
* that a given register may contain, and figures out which of these pointers
* must not have escaped on any path from the method entry to the current
* program point.
*
* Note that we do not model instance fields or array elements, so any values
* written to them will be treated as escaping, even if the containing object
* does not escape the method.
*/
namespace local_pointers {
using PointerSet = sparta::PatriciaTreeSetAbstractDomain<const IRInstruction*>;
using PointerEnvironment =
sparta::PatriciaTreeMapAbstractEnvironment<reg_t, PointerSet>;
inline bool may_alloc(IROpcode op) {
return op == OPCODE_NEW_INSTANCE || op == OPCODE_NEW_ARRAY ||
op == OPCODE_FILLED_NEW_ARRAY || is_invoke(op);
}
/*
* A model of pointer values on the stack and the heap values they point to in
* the store. This acts as an interface over EnvironmentWithStoreImpl<Store>,
* allowing us to write generic algorithms that are indifferent to the specific
* type of Store used.
*/
class EnvironmentWithStore {
public:
virtual ~EnvironmentWithStore() {}
virtual const PointerEnvironment& get_pointer_environment() const = 0;
virtual bool may_have_escaped(const IRInstruction* ptr) const = 0;
PointerSet get_pointers(reg_t reg) const {
return get_pointer_environment().get(reg);
}
virtual void set_pointers(reg_t reg, PointerSet pset) = 0;
virtual void set_fresh_pointer(reg_t reg, const IRInstruction* pointer) = 0;
virtual void set_may_escape_pointer(reg_t reg,
const IRInstruction* pointer) = 0;
/*
* Consider all pointers that may be contained in this register to point to
* escaping values.
*/
virtual void set_may_escape(reg_t reg) = 0;
};
template <class Store>
class EnvironmentWithStoreImpl final
: public sparta::ReducedProductAbstractDomain<
EnvironmentWithStoreImpl<Store>,
PointerEnvironment,
typename Store::Domain>,
public EnvironmentWithStore {
public:
using StoreDomain = typename Store::Domain;
using Base =
sparta::ReducedProductAbstractDomain<EnvironmentWithStoreImpl<Store>,
PointerEnvironment,
StoreDomain>;
using typename Base::ReducedProductAbstractDomain;
static void reduce_product(
const std::tuple<PointerEnvironment, StoreDomain>&) {}
const PointerEnvironment& get_pointer_environment() const override {
return Base::template get<0>();
}
const StoreDomain& get_store() const { return Base::template get<1>(); }
bool may_have_escaped(const IRInstruction* ptr) const override {
if (is_always_escaping(ptr)) {
return true;
}
return Store::may_have_escaped(Base::template get<1>(), ptr);
}
void set_pointers(reg_t reg, PointerSet pset) override {
Base::template apply<0>(
[&](PointerEnvironment* penv) { penv->set(reg, pset); });
}
void set_fresh_pointer(reg_t reg, const IRInstruction* pointer) override {
set_pointers(reg, PointerSet(pointer));
Base::template apply<1>(
[&](StoreDomain* store) { Store::set_fresh(pointer, store); });
}
void set_may_escape_pointer(reg_t reg,
const IRInstruction* pointer) override {
set_pointers(reg, PointerSet(pointer));
if (!is_always_escaping(pointer)) {
Base::template apply<1>(
[&](StoreDomain* store) { Store::set_may_escape(pointer, store); });
}
}
template <class F>
void update_store(reg_t reg, F updater) {
auto pointers = get_pointers(reg);
if (!pointers.is_value()) {
return;
}
Base::template apply<1>([&](StoreDomain* store) {
for (const auto* pointer : pointers.elements()) {
updater(pointer, store);
}
});
}
void set_may_escape(reg_t reg) override {
update_store(reg, [](const IRInstruction* pointer, StoreDomain* store) {
if (!is_always_escaping(pointer)) {
Store::set_may_escape(pointer, store);
}
});
}
private:
/*
* This method tells us whether we should always treat as may-escapes all the
* non-null pointers written by the given instruction to its dest register.
* This is a small performance optimization -- it means we don't have to
* populate our may_escape set with as many pointers.
*
* For instructions that don't write any non-null pointer values to their
* dests, this method will be vacuously true.
*/
static bool is_always_escaping(const IRInstruction* ptr) {
auto op = ptr->opcode();
return !may_alloc(op) && op != IOPCODE_LOAD_PARAM_OBJECT;
}
};
using ParamSet = sparta::PatriciaTreeSetAbstractDomain<uint16_t>;
// For denoting that a returned value is freshly allocated in the summarized
// method and only escaped at the return opcode(s).
constexpr uint16_t FRESH_RETURN = std::numeric_limits<uint16_t>::max();
struct EscapeSummary {
// The elements of this set represent the indexes of the src registers that
// escape.
std::unordered_set<uint16_t> escaping_parameters;
// The indices of the src registers that are returned. This is useful for
// modeling methods that return `this`, though it is also able to model the
// general case. It is a set instead of a single value since a method may
// return different values depending on its inputs.
//
// Note that if only some of the returned values are parameters, this will be
// set to Top. A non-extremal value indicates that the return value must be
// an element of the set.
ParamSet returned_parameters;
EscapeSummary() = default;
EscapeSummary(std::initializer_list<uint16_t> l) : escaping_parameters(l) {}
EscapeSummary(ParamSet ps, std::initializer_list<uint16_t> l)
: escaping_parameters(l), returned_parameters(ps) {}
static EscapeSummary from_s_expr(const sparta::s_expr&);
};
std::ostream& operator<<(std::ostream& o, const EscapeSummary& summary);
sparta::s_expr to_s_expr(const EscapeSummary&);
using InvokeToSummaryMap =
std::unordered_map<const IRInstruction*, EscapeSummary>;
/*
* A basic model of the heap, only tracking whether an object has escaped.
*/
class MayEscapeStore {
public:
using Domain = PointerSet;
static void set_may_escape(const IRInstruction* ptr, Domain* dom) {
dom->add(ptr);
}
static void set_fresh(const IRInstruction* ptr, Domain* dom) {
dom->remove(ptr);
}
static bool may_have_escaped(const Domain& dom, const IRInstruction* ptr) {
return dom.contains(ptr);
}
};
using Environment = EnvironmentWithStoreImpl<MayEscapeStore>;
/*
* Analyze the given method to determine which pointers escape. Note that we do
* not mark returned or thrown pointers as escaping here. This makes it easier
* to use as part of an interprocedural analysis -- the analysis of the caller
* can choose whether to track these pointers or treat them as having escaped.
* Check-casts would not let source value escape in normal cases. But for
* OptimizeEnumsPass which replaces enum object with boxed integer, check-casts
* may result in cast error. So we add the option `escape_check_cast` to make
* OptimizeEnumsPass able to treat check-cast as an escaping instruction.
*/
class FixpointIterator final : public ir_analyzer::BaseIRAnalyzer<Environment> {
public:
explicit FixpointIterator(
const cfg::ControlFlowGraph& cfg,
InvokeToSummaryMap invoke_to_summary_map = InvokeToSummaryMap(),
bool escape_check_cast = false)
: ir_analyzer::BaseIRAnalyzer<Environment>(cfg),
m_invoke_to_summary_map(invoke_to_summary_map),
m_escape_check_cast(escape_check_cast) {}
void analyze_instruction(IRInstruction* insn,
Environment* env) const override;
private:
// A map of the invoke instructions in the analyzed method to their respective
// summaries. If an invoke instruction is not present in the method, we treat
// it as an unknown method which could do anything (so all arguments may
// escape).
//
// By taking this map as a parameter -- instead of trying to resolve callsites
// ourselves -- we are able to switch easily between different call graph
// construction strategies.
InvokeToSummaryMap m_invoke_to_summary_map;
const bool m_escape_check_cast;
};
void escape_heap_referenced_objects(const IRInstruction* insn,
EnvironmentWithStore* env);
void default_instruction_handler(const IRInstruction* insn,
EnvironmentWithStore* env);
using FixpointIteratorMap =
ConcurrentMap<const DexMethodRef*, FixpointIterator*>;
struct FixpointIteratorMapDeleter final {
void operator()(FixpointIteratorMap*);
};
using FixpointIteratorMapPtr =
std::unique_ptr<FixpointIteratorMap, FixpointIteratorMapDeleter>;
using SummaryMap = std::unordered_map<const DexMethodRef*, EscapeSummary>;
using SummaryCMap = ConcurrentMap<const DexMethodRef*, EscapeSummary>;
/*
* Analyze all methods in scope, making sure to analyze the callees before
* their callers.
*
* If a non-null SummaryCMap pointer is passed in, it will get populated
* with the escape summaries of the methods in scope.
*/
FixpointIteratorMapPtr analyze_scope(const Scope&,
const call_graph::Graph&,
SummaryCMap* = nullptr);
/*
* Join over all possible returned and thrown values.
*/
void collect_exiting_pointers(const FixpointIterator& fp_iter,
const IRCode& code,
PointerSet* returned_ptrs,
PointerSet* thrown_pointers);
/*
* Summarize the effect a method has on its input parameters -- e.g. whether
* they may have escaped, and whether they are being returned. Note that we
* don't have a way to represent thrown pointers in our summary, so any such
* pointers are treated as escaping.
*/
EscapeSummary get_escape_summary(const FixpointIterator& fp_iter,
const IRCode& code);
} // namespace local_pointers
| [
"[email protected]"
] | |
958c43f2fe496b83ec3adbabeff65f8ee6f82792 | 387abaa47af408b66e071802468e49663668a891 | /Challenges/Maximum subarray sum.cpp | 0ff762fb8243c46d7cc1ffe0dc3828082546c429 | [] | no_license | gargVader/CPP-Data-Structures-Algorithms-Launchpad | 22eac05476f6d2d3a9ecdff90c5e6235b3895d7b | af2647a343d6d7b27c0313a745dfcf470639cad8 | refs/heads/master | 2023-07-27T09:26:21.125449 | 2021-09-09T04:42:19 | 2021-09-09T04:42:19 | 289,625,432 | 61 | 36 | null | 2020-12-10T06:25:20 | 2020-08-23T05:54:40 | C++ | UTF-8 | C++ | false | false | 409 | cpp | #include <bits/stdc++.h>
#define int long long
using namespace std;
void solve() {
int n; cin >> n;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int currSum = 0, maxSum = 0;
for (int i = 0; i < n; i++) {
currSum += a[i];
if (currSum < 0) currSum = 0;
maxSum = max(maxSum, currSum);
}
cout << maxSum << endl;
}
signed main() {
int t; cin >> t;
while (t--) {
solve();
}
}
| [
"[email protected]"
] | |
6ee88f354148da852b2d26dc3be27ea41aad73a7 | 5456502f97627278cbd6e16d002d50f1de3da7bb | /chrome/browser/chromeos/system/device_disabling_manager.h | 4a0ce147fa7fd92cd345c6ed25b7539382fb4a0f | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,460 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_SYSTEM_DEVICE_DISABLING_MANAGER_H_
#define CHROME_BROWSER_CHROMEOS_SYSTEM_DEVICE_DISABLING_MANAGER_H_
#include <memory>
#include <string>
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
namespace policy {
class BrowserPolicyConnectorChromeOS;
}
namespace user_manager {
class UserManager;
}
namespace chromeos {
namespace system {
// If an enrolled device is lost or stolen, it can be remotely disabled by its
// owner. The disabling is triggered in two different ways, depending on the
// state the device is in:
// - If the device has been wiped, it will perform a hash dance during OOBE to
// find out whether any persistent state has been stored for it on the server.
// If so, persistent state is retrieved as a |DeviceStateRetrievalResponse|
// protobuf, parsed and written to the |prefs::kServerBackedDeviceState| local
// state pref. At the appropriate place in the OOBE flow, the
// |WizardController| will call CheckWhetherDeviceDisabledDuringOOBE() to find
// out whether the device is disabled, causing it to either show or skip the
// device disabled screen.
// - If the device has not been wiped, the disabled state is retrieved with
// every device policy fetch as part of the |PolicyData| protobuf, parsed and
// written to the |chromeos::kDeviceDisabled| cros setting. This class
// monitors the cros setting. When the device becomes disabled, one of two
// actions is taken:
// 1) If no session is in progress, the device disabled screen is shown
// immediately.
// 2) If a session is in progress, the session is terminated. After Chrome has
// restarted on the login screen, the disabled screen is shown per 1).
// This ensures that when a device is disabled, there is never any user
// session running in the backround.
// When the device is re-enabled, Chrome is restarted once more to resume the
// regular login screen flows from a known-good point.
class DeviceDisablingManager {
public:
using DeviceDisabledCheckCallback = base::Callback<void(bool)>;
class Observer {
public:
virtual ~Observer();
virtual void OnDisabledMessageChanged(
const std::string& disabled_message) = 0;
private:
DISALLOW_ASSIGN(Observer);
};
class Delegate {
public:
virtual ~Delegate();
// Terminate the current session (if any) and restart Chrome to show the
// login screen.
virtual void RestartToLoginScreen() = 0;
// Show the device disabled screen.
virtual void ShowDeviceDisabledScreen() = 0;
private:
DISALLOW_ASSIGN(Delegate);
};
// |delegate| must outlive |this|.
DeviceDisablingManager(Delegate* delegate,
CrosSettings* cros_settings,
user_manager::UserManager* user_manager);
~DeviceDisablingManager();
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
// Returns the cached domain that owns the device. The domain is only
// guaranteed to be up to date if the disabled screen was triggered.
const std::string& enrollment_domain() const { return enrollment_domain_; }
// Returns the cached disabled message. The message is only guaranteed to be
// up to date if the disabled screen was triggered.
const std::string& disabled_message() const { return disabled_message_; }
// Performs a check whether the device is disabled during OOBE. |callback|
// will be invoked with the result of the check.
void CheckWhetherDeviceDisabledDuringOOBE(
const DeviceDisabledCheckCallback& callback);
// Whenever trusted cros settings indicate that the device is disabled, this
// method should be used to check whether the device disabling is to be
// honored. If this method returns false, the device should not be disabled.
static bool HonorDeviceDisablingDuringNormalOperation();
private:
void Init();
// Cache the disabled message and inform observers if it changed.
void CacheDisabledMessageAndNotify(const std::string& disabled_message);
void UpdateFromCrosSettings();
Delegate* delegate_;
policy::BrowserPolicyConnectorChromeOS* browser_policy_connector_;
CrosSettings* cros_settings_;
user_manager::UserManager* user_manager_;
base::ObserverList<Observer> observers_;
std::unique_ptr<CrosSettings::ObserverSubscription>
device_disabled_subscription_;
std::unique_ptr<CrosSettings::ObserverSubscription>
disabled_message_subscription_;
// Indicates whether the device was disabled when the cros settings were last
// read.
bool device_disabled_;
// A cached copy of the domain that owns the device.
std::string enrollment_domain_;
// A cached copy of the message to show on the device disabled screen.
std::string disabled_message_;
base::WeakPtrFactory<DeviceDisablingManager> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(DeviceDisablingManager);
};
} // namespace system
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_SYSTEM_DEVICE_DISABLING_MANAGER_H_
| [
"[email protected]"
] | |
30843118ae28a9bd247117f0c78f573f1e2cc3f6 | e5d9aa86573fac6f3f3e38ee5d0212035f5fc7c0 | /test/gtest_main.cpp | dd60d673f7b172a1f08995f177234cdfc4d288bc | [] | no_license | infogt/infotainmentTest | 216dce8e4f31fc8a0d418aff99e65e6800beb9ef | 73d831fed868878f1168cae89d86a0fa2d73880c | refs/heads/master | 2021-01-10T09:47:42.496450 | 2015-11-05T14:19:08 | 2015-11-05T14:19:08 | 45,610,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 318 | cpp | /*
* gtest_main.cpp
*
* Created on: 05.11.2015
* Author: sthangavelmurugesa
*/
// gtest_main.cpp
#include <stdio.h>
#include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) {
printf("Running main() from gtest_main.cc\n");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"[email protected]"
] | |
e3a6630b8e98485ac358f3a0aebbecc50ca3da7d | 030f32be0a6bd60e741c87d9d30c549ac83f7c40 | /task1/task1-2_2.0/build-copy-Desktop_Qt_5_12_0_GCC_64bit-Debug/moc_mainwindow.cpp | 280e09e0de72621faf548214f479babeeb6fefd5 | [] | no_license | ingdex/OS_design | bd8c30e836fc04e0322cd3870cfad8a3fe66dc75 | e6d60486bb6de646c0fbf174013c7c180c2a4fde | refs/heads/master | 2020-04-24T18:08:14.486224 | 2019-02-28T14:35:32 | 2019-02-28T14:35:32 | 172,170,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,374 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../copy/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[3];
char stringdata0[18];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "MainWindow"
QT_MOC_LITERAL(1, 11, 5), // "mcopy"
QT_MOC_LITERAL(2, 17, 0) // ""
},
"MainWindow\0mcopy\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MainWindow *_t = static_cast<MainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->mcopy(); break;
default: ;
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = { {
&QMainWindow::staticMetaObject,
qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
fe92b25c97fb0124f03ec4097d240ccbbc1411a4 | 53671078d0f8bde2914e391bdc20c19c600fec8c | /libs/binder/tests/binderBinderUnitTest.cpp | ce2770f9439c3c91d07eedac6d9d0c402ce72637 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | SuperiorOS/android_frameworks_native | de45879d8c7564a9da64cd41238a1545077730e2 | 7e1bee5f27f011c9573cfcdbbe64dcc6a786a9ec | refs/heads/thirteen | 2023-06-25T20:24:44.848214 | 2022-11-15T10:44:22 | 2023-06-21T10:06:30 | 149,220,650 | 2 | 34 | NOASSERTION | 2023-02-23T01:10:58 | 2018-09-18T03:01:34 | C++ | UTF-8 | C++ | false | false | 1,841 | cpp | /*
* Copyright (C) 2020 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
*
* 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.
*/
#include <binder/Binder.h>
#include <binder/IBinder.h>
#include <gtest/gtest.h>
using android::BBinder;
using android::OK;
using android::sp;
const void* kObjectId1 = reinterpret_cast<const void*>(1);
const void* kObjectId2 = reinterpret_cast<const void*>(2);
void* kObject1 = reinterpret_cast<void*>(101);
void* kObject2 = reinterpret_cast<void*>(102);
void* kObject3 = reinterpret_cast<void*>(103);
TEST(Binder, AttachObject) {
auto binder = sp<BBinder>::make();
EXPECT_EQ(nullptr, binder->attachObject(kObjectId1, kObject1, nullptr, nullptr));
EXPECT_EQ(nullptr, binder->attachObject(kObjectId2, kObject2, nullptr, nullptr));
EXPECT_EQ(kObject1, binder->attachObject(kObjectId1, kObject3, nullptr, nullptr));
}
TEST(Binder, DetachObject) {
auto binder = sp<BBinder>::make();
EXPECT_EQ(nullptr, binder->attachObject(kObjectId1, kObject1, nullptr, nullptr));
EXPECT_EQ(kObject1, binder->detachObject(kObjectId1));
EXPECT_EQ(nullptr, binder->attachObject(kObjectId1, kObject2, nullptr, nullptr));
}
TEST(Binder, AttachExtension) {
auto binder = sp<BBinder>::make();
auto ext = sp<BBinder>::make();
binder->setExtension(ext);
EXPECT_EQ(ext, binder->getExtension());
}
| [
"[email protected]"
] | |
19fb33f019ff586cf4d12def843c145d7d2ea4c9 | a2733d71e387d04a7964743aea214d0e45b87934 | /third_party/sol2/sol/variadic_args.hpp | 67937c1b1ca24cdf051f2b2dd366386892dc9fc4 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | holmansv/osrm-backend | 63ea992889e28e86e3c8059f9d66dff8cdf514aa | 662a8d0a12087a967cde3e193d7a702ae677cdc6 | refs/heads/master | 2022-03-04T16:09:13.047610 | 2022-02-16T21:18:28 | 2022-02-16T21:18:28 | 141,156,746 | 1 | 0 | BSD-2-Clause | 2018-11-30T19:11:38 | 2018-07-16T15:20:24 | C++ | UTF-8 | C++ | false | false | 5,393 | hpp | // sol2
// The MIT License (MIT)
// Copyright (c) 2013-2018 Rapptz, ThePhD and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef SOL_VARIADIC_ARGS_HPP
#define SOL_VARIADIC_ARGS_HPP
#include "stack.hpp"
#include "stack_proxy.hpp"
#include "stack_iterator.hpp"
#include <limits>
#include <iterator>
namespace sol {
struct variadic_args {
private:
lua_State* L;
int index;
int stacktop;
public:
typedef stack_proxy reference_type;
typedef stack_proxy value_type;
typedef stack_proxy* pointer;
typedef std::ptrdiff_t difference_type;
typedef std::size_t size_type;
typedef stack_iterator<stack_proxy, false> iterator;
typedef stack_iterator<stack_proxy, true> const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
variadic_args() = default;
variadic_args(lua_State* luastate, int stackindex = -1)
: L(luastate), index(lua_absindex(luastate, stackindex)), stacktop(lua_gettop(luastate)) {
}
variadic_args(lua_State* luastate, int stackindex, int lastindex)
: L(luastate), index(lua_absindex(luastate, stackindex)), stacktop(lastindex) {
}
variadic_args(const variadic_args&) = default;
variadic_args& operator=(const variadic_args&) = default;
variadic_args(variadic_args&& o)
: L(o.L), index(o.index), stacktop(o.stacktop) {
// Must be manual, otherwise destructor will screw us
// return count being 0 is enough to keep things clean
// but will be thorough
o.L = nullptr;
o.index = 0;
o.stacktop = 0;
}
variadic_args& operator=(variadic_args&& o) {
L = o.L;
index = o.index;
stacktop = o.stacktop;
// Must be manual, otherwise destructor will screw us
// return count being 0 is enough to keep things clean
// but will be thorough
o.L = nullptr;
o.index = 0;
o.stacktop = 0;
return *this;
}
iterator begin() {
return iterator(L, index, stacktop + 1);
}
iterator end() {
return iterator(L, stacktop + 1, stacktop + 1);
}
const_iterator begin() const {
return const_iterator(L, index, stacktop + 1);
}
const_iterator end() const {
return const_iterator(L, stacktop + 1, stacktop + 1);
}
const_iterator cbegin() const {
return begin();
}
const_iterator cend() const {
return end();
}
reverse_iterator rbegin() {
return std::reverse_iterator<iterator>(begin());
}
reverse_iterator rend() {
return std::reverse_iterator<iterator>(end());
}
const_reverse_iterator rbegin() const {
return std::reverse_iterator<const_iterator>(begin());
}
const_reverse_iterator rend() const {
return std::reverse_iterator<const_iterator>(end());
}
const_reverse_iterator crbegin() const {
return std::reverse_iterator<const_iterator>(cbegin());
}
const_reverse_iterator crend() const {
return std::reverse_iterator<const_iterator>(cend());
}
int push() const {
return push(L);
}
int push(lua_State* target) const {
int pushcount = 0;
for (int i = index; i <= stacktop; ++i) {
lua_pushvalue(L, i);
pushcount += 1;
}
if (target != L) {
lua_xmove(L, target, pushcount);
}
return pushcount;
}
template <typename T>
decltype(auto) get(difference_type index_offset = 0) const {
return stack::get<T>(L, index + static_cast<int>(index_offset));
}
type get_type(difference_type index_offset = 0) const noexcept {
return type_of(L, index + static_cast<int>(index_offset));
}
stack_proxy operator[](difference_type index_offset) const {
return stack_proxy(L, index + static_cast<int>(index_offset));
}
lua_State* lua_state() const {
return L;
};
int stack_index() const {
return index;
};
int leftover_count() const {
return stacktop - (index - 1);
}
std::size_t size() const {
return static_cast<std::size_t>(leftover_count());
}
int top() const {
return stacktop;
}
};
namespace stack {
template <>
struct getter<variadic_args> {
static variadic_args get(lua_State* L, int index, record& tracking) {
tracking.last = 0;
return variadic_args(L, index);
}
};
template <>
struct pusher<variadic_args> {
static int push(lua_State* L, const variadic_args& ref) {
return ref.push(L);
}
};
} // namespace stack
} // namespace sol
#endif // SOL_VARIADIC_ARGS_HPP
| [
"[email protected]"
] | |
b9d50c712b854abfc81be6bda88232c5f7b2fa3a | 4aa73c0395f349aad6a9bb88ae5e637ac736a45b | /The-Programmer/Interpol/functions.cpp | c29b5200f99ac101590de3282e22ba85d40a02b2 | [] | no_license | CHL198011/BGv1.cedarpoint | 23ba1341b9c829c2a4d71a1672a6d3a8fb0377a0 | 455aba0fd55bff05a5bc01bfebc5a49c0227c2e2 | refs/heads/master | 2020-11-25T16:07:48.500759 | 2019-08-13T15:11:13 | 2019-08-13T15:11:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | class Maxence_interpol {
tag = "max_interpol";
class functions {
file = "The-Programmer\Interpol\scripts";
class interpolInsert {};
class interpolAddMenu {};
class interpolMenuList {};
class interpolEdit {};
class interpolSearch {};
class interpolEditMenu {};
class interpolLbChanged {};
class interpolAddCrime {};
class interpolCrimeMenu {};
class interpolDeleteCrime {};
class localize {};
class interpolChangeStatus {};
class getPlayerCrimes {};
class interpolLbChangedCrimes {};
class interpolSendMSG {};
};
}; | [
"[email protected]"
] | |
cf0ddd3739a0715de02c198097a1fa660783fdd6 | 0dbc770a07ef5dd63068ddcf21d07df8c4416bda | /Arduino PoC/GEVE/GEVE.ino | 6f675489a336a73317cfeab25ebd983d07df187a | [] | no_license | GEVE-VENTILATOR/Arduino-Code | ab94099753d4c5a83ec0749762bd565da609ee6f | aa68a0570e30a481b6e9a8f74b199ccb55e743e1 | refs/heads/master | 2023-05-03T16:53:57.788733 | 2021-05-17T08:47:04 | 2021-05-17T08:47:04 | 255,650,468 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,124 | ino |
/* ----------------------
GEVE - Ventilator monitoring system V1.0
Date : 07.04.20
Authors :
Stoeckli H. - HEPIA
Rossel R. - ANGARA TECHNOLOGY
Inputs :
ON/OFF - Switch
Error acknowledgment - Switch
Breath per minute - bpm (breath/minute) - Potentiometer - 8 to 30 - typical 12
Tidal Volumne - VT (ml) - Potentiometer - 200 to 800 ml - need to be calibrated (better start low)
Inspiration/expiration ratio - IE (-) - Potentiometer - 1:3 to 1:1 - typical 1:2
Pressure - Pressure sensor SSCDRNN160MDAA5 +/- 163 cmH2O (ideally SSCDRNN100MDAA5 but unavailable, nother +/- 60 to 100 cmH20 sensor can fit)
Outputs :
LCD screen 4X20 2004A - Displays BPM, VT, IE, Pressure, Plateau Pressure, PEEP and errors
Motor driver LECPA OM04505
Buzzer - CMT-8540S-SMT-TR (to be tested)
LED
Timers :
Timer 0 : Used with Time function
Timer 1 : Set Repiratory rythm trough motor control
Timer 2 : Used with Tone() function (alarm)
Modes :
Mode 1 : Volume control - selected breaths delivered at constant rate, pressure monitored only for
safety. - Only suitable for sedated or paralyzed patients.
Mode 2 : **** NOT IMPLEMENTED YET **** Assist control - When the patient tries to breathe in,
the pressure sensor will see a pressure drop, and the machine will begin squeezing the bag in order
to assist in the breath.
Because the compression is triggered by the patient’s breath,
the machine will be operating in sync with the patient’s natural breathing.
A maximum time-between-breath timeout will also be used to deliver a breath after a certain time,
even if the patient doesn’t trigger it. This is so that the machine will still deliver a minimum amount of breathing,
even if the patient becomes unable to breathe for themselves. An alert will sound.
Code related to the PC interface is marked with 'PCIF' to easily find it.
*/
// ================= CHANGE LCD MODEL HERE ====================0
//#define LCD_NEWHAVEN 0 // NOT FULLY OPERATIONNAL !
#define LCD_2004A 1
#include <Wire.h>
#ifdef LCD_2004A
#include "LiquidCrystal_I2C.h"
#endif
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdbool.h>
//---- MIN/MAX entry values and pressure limits ----//
#define MIN_BPM 8 // in breath/minute
#define MAX_BPM 30 // in breath/minute
#define DELTA_BPM (MAX_BPM-MIN_BPM) // used to optimize calculus
#define MIN_VT 200 // in ml
#define MAX_VT 800 // in ml
#define DELTA_VT (MAX_VT-MIN_VT)/100 // In ml, used to optimize calculus
#define MIN_IE 1 // in ratio E/I
#define MAX_IE 3 // in ratio E/I
#define DELTA_IE (MAX_IE-MIN_IE) // In ratio, used to optimize calculus
#define MIN_PEEP 1 // in cmH2O
#define MAX_PEEP 20 // in cmH2O
#define DELTA_PEEP (MAX_PEEP-MIN_PEEP) // In cmH2O, used to optimize calculus
#define PEEP_MARGIN 3 // in cmH2O, added pressure value to PEEP to start at initialization
//---- Fixed parameters ----//
// Mechanical
#define DISTANCE_PER_PULSE 0.0125 // In mm, linear motor displacement for each pulse
#define SQUEEZED_VOLUME 1000 // In ml, total volume when bag squeezed (not total bag volume)
//#define TOTAL_RANGE 110
#define TOTAL_RANGE 50 // In mm
#define VOLUME_PER_DISTANCE SQUEEZED_VOLUME/TOTAL_RANGE // In ml/mm (approximated total volume 1L/20cm approximated total range)
#define VOLUME_PER_PULSE VOLUME_PER_DISTANCE*DISTANCE_PER_PULSE // In ml/pulse
#define MOTOR_POSITION_LIMIT_INIT_MM 170 // Max init range before error in mm
#define MOTOR_POSITION_LIMIT_INIT_PULSE MOTOR_POSITION_LIMIT_INIT_MM/DISTANCE_PER_PULSE // Max init range before error in pulses
#define MOTOR_PULSE_WIDTH 4 // In us, note that due to the execution time, the real value will be a little bit higher (few us more )
// Pressure sensor
#define PRESSURE_SENSOR_POS_DYNAMIC 163 // Pressure sensor positive dynamic in cmH2O
#define MAX_PRESSURE 38 // Max pressure at any moment in cmH2O
#define ALARM_FREQUENCY 4000 // Alarm sound frequency
#define ALARM_SPEED 10000 // Repetitive speed of alarm
#define STATE_OK 0 // System state ok
#define STATE_ERR_HIGH_PRESSURE 1 // Overpressure occured, need acknowledgement
#define STATE_ERR_LOW_PRESSURE 2 // Low pressure occured, need acknowledgement
#define STATE_ERR_FAIL_INIT 3 // Initialisation failure occured
#define STATE_ERR_MOTOR 4 // Motor failure detected
#define ON 1
#define OFF 0
#define BUTTON_PUSHED 0
#define BUTTON_RELEASED 1
//---- Machine state definition ----//
#define STOP 0
#define SET_INIT 1
#define INIT 2
#define SET_INHALE 3
#define INHALE 4
#define SET_PAUSE 5
#define PAUSE 6
#define SET_EXHALE 7
#define EXHALE 8
//---- Pins definition ----//
//Analog inputs
#define PIN_BPM_IN A0
#define PIN_VT_IN A1
#define PIN_IE_IN A2
#define PIN_PRESSURE_IN A3
// A4 AND A5 RESERVED FOR I2C
//Digital inputs
#define PIN_SWITCH_ONOFF 2
#define PIN_SWITCH_ERR_ACK 3
#define PIN_WAREA 4 // Motor position between W-AREA1 and W-AREA2 (defined in driver)
#define PIN_BUSY 5 // If ON, Motor is positioning
#define PIN_SETON 6 // ON, if motor went back once to origin and knows his position
#define PIN_INP 7 // ON, if motor at desired position
//Digital outputs
#define PIN_BUZZER 9
#define PIN_MOTOR_STEP_BACK 10
#define PIN_MOTOR_STEP_FORTH 11
#define PIN_MOTOR_ORIGIN 12
#define PIN_LED 13
//------- Functions definitions -------//
#ifdef LCD_NEWHAVEN
void LCDsetCursor(int Column, byte Line);
void LCDWrite(const char* text);
void LCDclear();
#endif
void SendPulse(int pin, int timeus); // Motor pulse function
void ActiveCount1(float timetointerruptus, long Ninterrupt); // Enable Counter 2 with interruption after timetointerrupt second
void StopCount1();
int interrtime1; // global variable to reload the counter
long Ninter1 = 0; // Number of interrupt
int cnt1 = 0; // interruption counter
//----------- User Inputs variables declaration -----------//
float bpm = 0; // In breath/minute
float IE = 0; // Inspiration/expiration ratio 1:x
int VT = 0; // In pulses //MAY CHANGE
int peep = 5; // In cmH20
bool start = 1; // ON/OFF switch
//----------- Measured variables declaration -----------//
int pressure = 15; // in cmH2O
int plateau_pressure = 0; // in cmH2O
//----------- Internal variables declaration -----------//
float T = 0; // INHALE/EXHALE period in seconds
float Tin = 0; // INHALE period in seconds
float Tex = 0; // EXHALE period in seconds
float Vin = 0; // flowrate in pulses/second //MAY CHANGE
float Vex = 0; // flowrate in pulses/second //MAY CHANGE
float Psin = 0; // time/pulse //MAY CHANGE
float Psex = 0; // time/pulse //MAY CHANGE
long Npulse = 0; // Total cycle pulses //MAY CHANGE
float Tplateau = 150; // Pause time to measure plateau pressure in millisec
int state = STOP; // Initial system state machine
byte error_state = STATE_OK; // System error state
bool restarted = 0;
bool first_stop = 1;
bool firststop = 1;
float Tinitmax = 5; // Max time to init before sending an error
bool initialized = 0;
int cnt_alarm = 0;
int cnt_positioning;
//----------- LCD management variable -----------//
int lastbpm = 0;
int lastpressure = 0;
int lastplatpressure = 0;
int lastpeep = 0;
bool laststate = 1;
int blink_error = 0;
bool printerror = 0;
#ifdef LCD_2004A
LiquidCrystal_I2C lcd(0x27, 20, 4); //Set the LCD address to 0x27 for a 20 chars and 4 lines display
#endif
#ifdef LCD_NEWHAVEN
const byte LCDa = 0x28; //LCD address on I2C bus
#endif
//----------- Motor driver variable declaration -----------//
long PEEP_relative_origine = 0;
int motorposition = 0;
//----------- Debug variable declaration -----------//
long timestart = 0;
long interuptcnt = 0;
// PCIF------ Type declaration of runtime data for GEVE Ventilator Monitoring ---------- //
struct GEVE_VeMon_Data
{
bool on_off;
bool error_ack;
double breath_pm;
double tidal_volume;
double in_ex_ratio;
double peep;
double pressure;
double pressure_plateau;
double motor_position;
bool alarm_p_high;
bool alarm_p_low;
bool alarm_init;
};
// PCIF------ Variable definition of type GEVE runtime data for communication ---------- //
GEVE_VeMon_Data geve_status =
{
false,
false,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
false,
false,
false
};
void setup()
{
//----------- I/O init. -----------//
// Input
pinMode(PIN_SWITCH_ONOFF, INPUT_PULLUP);
pinMode(PIN_SWITCH_ERR_ACK, INPUT_PULLUP);
pinMode(PIN_WAREA, INPUT);
pinMode(PIN_BUSY, INPUT);
pinMode(PIN_SETON, INPUT);
pinMode(PIN_INP, INPUT);
//TIMSK0 = 0;
//Output
pinMode(PIN_BUZZER, OUTPUT);
pinMode(PIN_MOTOR_STEP_BACK, OUTPUT);
pinMode(PIN_MOTOR_STEP_FORTH, OUTPUT);
pinMode(PIN_MOTOR_ORIGIN, OUTPUT);
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_MOTOR_STEP_BACK, LOW);
digitalWrite(PIN_MOTOR_STEP_FORTH, LOW);
digitalWrite(PIN_MOTOR_ORIGIN, HIGH);
//------------Serial comm. init.------------//
Serial.begin(9600);
// ----------- LCD init.------------//
#ifdef LCD_2004A
lcd.begin();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("BPM:");
lcd.setCursor(8, 1);
lcd.print("Tid.Vol.:");
lcd.setCursor(0, 2);
lcd.print("IE:");
lcd.setCursor(12, 2);
lcd.print("PEEP.:");
lcd.setCursor(0, 3);
lcd.print("Press:");
lcd.setCursor(10, 3);
lcd.print("PressPl:");
#endif
#ifdef LCD_NEWHAVEN
TWBR = 100000; //sets I2C speed to 100kHz very important
LCDclear();
//delay(500); // for observation only can be removed
LCDsetCursor(0, 1);
LCDWrite("BPM:");
LCDsetCursor(8, 1);
LCDWrite("Tid.Vol.:");
LCDsetCursor(0, 2);
LCDWrite("IE:");
LCDsetCursor(12, 2);
LCDWrite("PEEP.:");
LCDsetCursor(0, 3);
LCDWrite("Press:");
LCDsetCursor(10, 3);
LCDWrite("PressPl:");
#endif
}
int starttimemesure = 0;
void loop()
{
// ================START OF Read potentiometers & display values ======================//
bpm = analogRead(PIN_BPM_IN) * DELTA_BPM / 1024 + MIN_BPM;
VT = analogRead(PIN_VT_IN) * DELTA_VT / 10 + MIN_VT;
IE = (float)(analogRead(PIN_IE_IN)) * DELTA_IE / 1024 + MIN_IE;
// read pressure
pressure = ((analogRead(PIN_PRESSURE_IN) - 512) * PRESSURE_SENSOR_POS_DYNAMIC / 1024) * 5 / 2 ;
// PCIF -----vvvvv----- comment out to test PC interface ----------
//Serial.print("Pressure : ");
//Serial.println(pressure);
// PCIF -----^^^^^----- end commenting out ----------
geve_status.motor_position = motorposition; // <--- PCIF ---
// ====================== START OF Update display =======================//
if ((bpm < 10) && (bpm != lastbpm))
{
#ifdef LCD_2004A
lcd.setCursor(4, 1);
lcd.print(" ");
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(4, 1);
LCDWrite(" ");
#endif
}
lastbpm = bpm;
geve_status.breath_pm = bpm; // <--- PCIF ---
geve_status.tidal_volume = VT; // <--- PCIF ---
geve_status.in_ex_ratio = IE; // <--- PCIF ---
#ifdef LCD_2004A
lcd.setCursor(4, 1);
lcd.print((int)bpm);
lcd.setCursor(17, 1);
lcd.print(VT);
lcd.setCursor(4, 2);
lcd.print(IE);
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(4, 1);
LCDWrite((int)bpm);
LCDsetCursor(17, 1);
LCDWrite(VT);
LCDsetCursor(4, 2);
LCDWrite((char) IE);
#endif
if ((peep < 10) && (peep != lastpeep))
{
#ifdef LCD_2004A
lcd.setCursor(18, 2);
lcd.print(" ");
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(18, 2);
LCDWrite(" ");
#endif
}
lastpeep = peep;
geve_status.peep = peep; // <--- PCIF ---
#ifdef LCD_2004A
lcd.setCursor(18, 2);
lcd.print(peep);
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(18, 2);
LCDWrite(peep);
#endif
if ((pressure < 10) && (pressure != lastpressure))
{
#ifdef LCD_2004A
lcd.setCursor(6, 3);
lcd.print(" ");
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(6, 3);
LCDWrite(" ");
#endif
}
lastpressure = pressure;
geve_status.pressure = pressure; // <--- PCIF ---
#ifdef LCD_2004A
lcd.setCursor(6, 3);
lcd.print(pressure);
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(6, 3);
LCDWrite(pressure);
#endif
// ====================== END OF Update display =======================//
// ---------- Check ON/OFF ---------- //
if (digitalRead(PIN_SWITCH_ONOFF) == OFF)
{
TIMSK2 = 0;
cnt1 = 0;
error_state = STATE_OK;
if (firststop) laststate = 1;
firststop = 0;
state = STOP;
geve_status.on_off = false; // <--- PCIF ---
}
else
{
firststop = 1;
geve_status.on_off = true; // <--- PCIF ---
}
// ---------- Check ALARMS (pressure) ---------- //
if ((pressure > MAX_PRESSURE) || (initialized && (pressure < peep)))
{
if (pressure > MAX_PRESSURE)
{
error_state = STATE_ERR_HIGH_PRESSURE; // IN CASE OF HIGH PRESSURE, THE SYSTEM STOPS AND GENERATES AN ALARM
TIMSK2 = 0;
cnt1 = 0;
state = STOP;
}
if (pressure < peep)
{
error_state = STATE_ERR_LOW_PRESSURE; // IN CASE OF LOW PRESSURE, THE SYSTEM CONTINUE ITS CYCLE, BUT GENERATES AN ALARM
}
}
// ---------- Check ERROR ACK ---------- //
if (digitalRead(PIN_SWITCH_ERR_ACK) == BUTTON_PUSHED) // Allow user to acknowledge an occured error and display again system state on LCD
{
error_state = STATE_OK;
geve_status.error_ack = true; // <--- PCIF ---
}
else
{
geve_status.error_ack = false; // <--- PCIF ---
}
// ---------- Check & handle error states ---------- //
if (error_state) // if an error occured alarm is activated and error message is displayed on LCD
{
if (blink_error < 7)
{
printerror = 1;
}
else if (blink_error < 14)
{
printerror = 0;
}
else
{
blink_error = 0;
}
blink_error++;
// START OF ERROR HANDLING State Machine
switch (error_state)
{
case STATE_ERR_HIGH_PRESSURE :
if (printerror)
{
tone(PIN_BUZZER, ALARM_FREQUENCY, 2000);
geve_status.alarm_p_high = true; // <--- PCIF ---
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("HIGH PRESSURE ERROR ");
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("HIGH PRESSURE ERROR ");
#endif
}
else
{
noTone(PIN_BUZZER);
geve_status.alarm_p_high = false; // <--- PCIF ---
}
break;
// ----- end ERROR case STATE_ERR_HIGH_PRESSURE
case STATE_ERR_LOW_PRESSURE :
if (printerror)
{
tone(PIN_BUZZER, ALARM_FREQUENCY, 2000);
geve_status.alarm_p_low = true; // <--- PCIF ---
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("LOW PRESSURE ERROR ");
#endif;
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("LOW PRESSURE ERROR ");
#endif;
}
else
{
noTone(PIN_BUZZER);
geve_status.alarm_p_low = false; // <--- PCIF ---
}
break;
// ----- end ERROR case STATE_ERR_LOW_PRESSURE
case STATE_ERR_FAIL_INIT :
if (printerror)
{
tone(PIN_BUZZER, ALARM_FREQUENCY, 2000);
geve_status.alarm_init = true; // <--- PCIF ---
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("INIT. ERROR ");
#endif;
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("INIT. ERROR ");
#endif;
}
else
{
noTone(PIN_BUZZER);
geve_status.alarm_init = false; // <--- PCIF ---
}
break;
// ----- end ERROR case STATE_ERR_FAIL_INIT
case STATE_ERR_MOTOR:
if (printerror)
{
tone(PIN_BUZZER, ALARM_FREQUENCY, 2000);
geve_status.alarm_init = true; // <--- PCIF ---
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("MOTOR ERROR ");
#endif;
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("MOTOR ERROR ");
#endif;
}
else
{
noTone(PIN_BUZZER);
geve_status.alarm_init = false; // <--- PCIF ---
}
break;
// ----- end ERROR case STATE_ERR_FAIL_INIT
}
// END OF ERROR HANDLING State Machine
}
else // No error (error_state = STATE_OK), reset all alarms to false.
{
noTone(PIN_BUZZER);
printerror = 0;
geve_status.alarm_p_high = false; // <--- PCIF ---
geve_status.alarm_p_low = false; // <--- PCIF ---
geve_status.alarm_init = false; // <--- PCIF ---
}
// END OF Read potentiometers & display values =====================================================
// START OF System state Machine
switch (state)
{
case STOP :
initialized = 0;
if (digitalRead(PIN_INP))
{
digitalWrite(PIN_MOTOR_ORIGIN, 0); // open system
delay(1000);
}
else
{
digitalWrite(PIN_MOTOR_ORIGIN, 1); // open system
}
if (laststate && !printerror)
{
first_stop = 1;
}
if (!printerror)
{
#ifdef LCD_2004A
//lcd.setCursor(0, 0);
//lcd.print(" ");
lcd.setCursor(0, 0);
lcd.print("STOP ");
#endif;
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite(" ");
LCDsetCursor(0, 0);
LCDWrite("STOP ");
#endif;
}
// PCIF -----vvvvv----- comment out to test PC interface ----------
//Serial.println("Stop system");
// PCIF -----^^^^^----- end commenting out ----------
laststate = 0;
if (digitalRead(PIN_SWITCH_ONOFF)) {
if (first_stop) ActiveCount1(6000, 3000);
first_stop = 0;
if (digitalRead(PIN_INP) == true) //waiting on system to be open
{
state = SET_INIT;
laststate = 1;
}
}
// PCIF ----- Should the ON/OFF variable be changed here instead of the 'Check ON/OFF' part?
break;
// ----- end case STOP -----
case SET_INIT : // ------ System squeeze bag until PEEP reached, if not at 30% course => alarm -------
if (!printerror)
{
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("INITIALIZATION ");
#endif;
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("INITIALIZATION ");
#endif;
}
if (digitalRead(PIN_INP) == true)
{
digitalWrite(PIN_MOTOR_ORIGIN, 0); // open system
}
if ((digitalRead(PIN_INP) == true) && (digitalRead(PIN_SETON) == true) ) //waiting on system to be open
{
digitalWrite(PIN_MOTOR_ORIGIN, 1);
motorposition = 0;
state = INIT;
}
break;
// ----- end case SET_INIT -----
case INIT :
if (!printerror)
{
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("INITIALIZATION ");
#endif;
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("INITIALIZATION ");
#endif;
}
// PCIF -----vvvvv----- comment out to test PC interface ----------
//Serial.println(MOTOR_POSITION_LIMIT_INIT_PULSE);
// PCIF -----^^^^^----- end commenting out ----------
if ((motorposition < MOTOR_POSITION_LIMIT_INIT_PULSE) && (pressure < (peep + PEEP_MARGIN)))
{
if (digitalRead(PIN_INP) == true) // if motor took desired position
{
for (int j = 0; j < 100; j++)
{
SendPulse(PIN_MOTOR_STEP_FORTH, MOTOR_PULSE_WIDTH);
motorposition++;
delayMicroseconds(500);
}
}
}
else if (pressure >= (peep + PEEP_MARGIN))
{
PEEP_relative_origine = motorposition;
initialized = 1;
motorposition = 0;
StopCount1();
state = SET_INHALE;
}
else
{
initialized = 0;
StopCount1();
state = STOP;
error_state = STATE_ERR_FAIL_INIT;
}
break;
// ----- end case INIT -----
case SET_INHALE :
// PCIF -----vvvvv----- comment out to test PC interface ----------
if (digitalRead(PIN_INP) == true) {
cnt_positioning = 0;
//Serial.print("Expiration time : ");
//Serial.println(millis() - timestart);
//Serial.print("Motor position after expiration: ");
//Serial.println(motorposition);
// PCIF -----^^^^^----- end commenting out ----------
interuptcnt = 0;
// TO BE DISCUSS : does the rythm variables must change only at the end of a cycle (better for motor control?) ?
// Rythm variable update
T = 60 / bpm;
Tin = T / (1 + IE);
Tex = T - Tin;
Vin = VT / (Tin * VOLUME_PER_PULSE) ;
Vex = VT / (Tex * VOLUME_PER_PULSE);
Npulse = Vin * Tin;
Psin = 1000000 / Vin;
Psex = 1000000 / Vex;
// set motor speed Vin -----------------
// PCIF -----vvvvv----- comment out to test PC interface ----------
//Serial.println("INHALATION");
// PCIF -----^^^^^----- end commenting out ----------
if (!printerror)
{
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("INHALATION ");
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("INHALATION ");
#endif
}
// Set Tin timer
ActiveCount1(Psin, Npulse);
timestart = millis();
digitalWrite(PIN_LED, HIGH);
if (state == SET_INHALE) state = INHALE;
}
else
{
if (++cnt_positioning > 100) {
state = STOP;
error_state = STATE_ERR_MOTOR;
cnt_positioning = 0;
}
}
break;
// ----- end case SET_INHALE -----
case INHALE : //INHALE phase
if (!printerror)
{
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("INHALATION ");
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("INHALATION ");
#endif
}
break;
// ----- end case INAHLE -----
case SET_PAUSE : //Set Plateau pressure measurement
// PCIF -----vvvvv----- comment out to test PC interface ----------
//Serial.print("Inhalation time : ");
//Serial.println(millis() - timestart);
//Serial.print("Motor position after inspiration: ");
//Serial.println(motorposition);
// PCIF -----^^^^^----- end commenting out ----------
interuptcnt = 0;
ActiveCount1((Tplateau) * 10, 100);
timestart = millis();
if (state == SET_PAUSE) state = PAUSE;
break;
// ----- end case SET_PAUSE -----
case PAUSE :
plateau_pressure = pressure;
geve_status.pressure_plateau = pressure; // <--- PCIF ---
#ifdef LCD_2004A
lcd.setCursor(18, 3);
lcd.print(" ");
lcd.setCursor(18, 3);
lcd.print(plateau_pressure);
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(18, 3);
LCDWrite(" ");
LCDsetCursor(18, 3);
LCDWrite(plateau_pressure);
#endif
break;
// ----- end case PAUSE -----
case SET_EXHALE :
if (digitalRead(PIN_INP) == true) {
cnt_positioning = 0;
// PCIF -----vvvvv----- comment out to test PC interface ----------
//Serial.print("Pause time : ");
//Serial.println(millis() - timestart);
// set motor speed Vin-----------------
//Serial.println("EXPIRATION");
// PCIF -----^^^^^----- end commenting out ----------
// Set Tin timer
ActiveCount1(Psex, Npulse);
timestart = millis();
if (!printerror)
{
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("EXPIRATION ");
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("EXPIRATION ");
#endif
}
digitalWrite(PIN_LED, LOW);
if (state == SET_EXHALE) state = EXHALE;
}
else
{
if (++cnt_positioning > 100) {
state = STOP;
error_state = STATE_ERR_MOTOR;
cnt_positioning = 0;
}
}
break;
// ----- end case SET_EXHALE -----
case EXHALE :
if (!printerror)
{
#ifdef LCD_2004A
lcd.setCursor(0, 0);
lcd.print("EXPIRATION ");
#endif
#ifdef LCD_NEWHAVEN
LCDsetCursor(0, 0);
LCDWrite("EXPIRATION ");
#endif
}
break;
// ----- end case EXHALE -----
}
// END OF State Machine
//
// PCIF------ Communicate status to PC interface ---------- //
Serial.print(geve_status.on_off);
Serial.print("_");
Serial.print(geve_status.error_ack);
Serial.print("_");
Serial.print(geve_status.breath_pm);
Serial.print("_");
Serial.print(geve_status.tidal_volume);
Serial.print("_");
Serial.print(geve_status.in_ex_ratio);
Serial.print("_");
Serial.print(geve_status.peep);
Serial.print("_");
Serial.print(geve_status.pressure);
Serial.print("_");
Serial.print(geve_status.pressure_plateau);
Serial.print("_");
Serial.print(geve_status.motor_position);
Serial.print("_");
Serial.print(geve_status.alarm_p_high);
Serial.print("_");
Serial.print(geve_status.alarm_p_low);
Serial.print("_");
Serial.print(geve_status.alarm_init);
Serial.println();
//
}
void ActiveCount1(float timetointerruptus, long Ninterrupt)
{
cli();
cnt1 = 0;
Ninter1 = Ninterrupt;
bitClear (TCCR1A, WGM10); // WGM20 = 0
bitClear (TCCR1A, WGM11); // WGM21 = 0
TCCR1B = 0b00000010; // Clock / 8 soit 0.5 micro-s et WGM22 = 0
TIMSK1 = 0b00000001; // Interruption locale autorisée par TOIE2
interrtime1 = 65536 - timetointerruptus * 2;
TCNT1 = interrtime1;
//cnt_time =timetointerrupt*31250;
sei(); // Active l'interruption globale
}
void StopCount1() {
TIMSK1 = 0;
}
ISR(TIMER1_OVF_vect) {
TCNT1 = interrtime1;
if ((state == INHALE) || (state == SET_INHALE)) {
SendPulse(PIN_MOTOR_STEP_FORTH, MOTOR_PULSE_WIDTH);
motorposition++;
};
if (state == EXHALE || (state == SET_EXHALE)) {
SendPulse(PIN_MOTOR_STEP_BACK, MOTOR_PULSE_WIDTH);
motorposition--;
};
if (cnt1++ == (Ninter1 - 1))
{
cnt1 = 0;
TIMSK1 = 0;
switch (state)
{
case STOP:
error_state = STATE_ERR_FAIL_INIT;
break;
case SET_INIT: state = STOP;
error_state = STATE_ERR_FAIL_INIT;
break;
case INIT: state = STOP;
error_state = STATE_ERR_FAIL_INIT;
break;
case INHALE: state = SET_PAUSE;
break;
case EXHALE: state = SET_INHALE;
break;
case PAUSE: state = SET_EXHALE;
break;
}
}
}
void SendPulse(int pin, int timeus)
{
digitalWrite(pin, LOW);
digitalWrite(pin, HIGH);
delayMicroseconds(timeus);
digitalWrite(pin, LOW);
}
#ifdef LCD_NEWHAVEN
// Clear the NHD Extended LCD Screen
void LCDclear() {
Wire.beginTransmission(LCDa);
Wire.write (0xFE);
Wire.write(0x51);
Wire.endTransmission();
delay(2);
}
void LCDWrite(const char* text)
{
Wire.beginTransmission(LCDa);
Wire.write(text);
Wire.endTransmission();
}
void LCDsetCursor(int Column, byte Line)
{
int pos = 0;
switch (Line)
{
case 1: pos |= 0x40; break;
case 2: pos |= 0x14; break;
case 3: pos |= 0x54; break;
}
Wire.beginTransmission(LCDa);
Wire.write (0xFE);
Wire.write(0x45);
Wire.write(pos + Column);
Wire.endTransmission();
delay(2);
}
#endif
| [
"[email protected]"
] | |
7aef28a9be8c29ea6bab5c99a5a462ee12d7dd91 | c0cb680871a278ae96d628270aa6fbb4807d02cf | /Kinght/C++/第 6 课 - 内联函数/test1.cpp | dfaf8cbe4255ad8ab96b190a6815bdeadf8c08f8 | [] | no_license | Angelalisa-x/YuSoftware | 06b7d5cfd05519244e1615dc12c20cba84a023c8 | b650b80963c97b0fac3b5c3585a85dc9a7124f72 | refs/heads/master | 2023-07-08T15:26:10.183749 | 2021-08-11T11:41:51 | 2021-08-11T11:41:51 | 247,637,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | cpp | #include <stdio.h>
#define FUNC(a,b) (a < b) ? a : b
inline int func(int a, int b){
return ((a < b) ? a : b);
}
int main(int argc, char* argv[])
{
int a1 = 1;
int a2 = 1;
int b = 3;
printf("FUNC(++a, b): %d\n", FUNC(++a1, b)); //++a1 < b ? ++a1 : b 3
printf("func(++a, b): %d\n", func(++a2, b));//2
return 0;
} | [
"[email protected]"
] | |
84b046f770a48ca5e5c97af629cb2b85e4fa4197 | ee2af225537176c4a5e63321b87a72c07de955ea | /WinApi/WindowsWithChilds/new_frac/frac/main1.cpp | 97d1d0cfca0737d26a58d81fb9116ecd1e40caca | [] | no_license | DenisMath/Overview | 7bf3896624534292fb85490e87eff747446ab68e | 0c52c2fe8580904f9cc7d9e9f307903a5bfbe125 | refs/heads/master | 2020-04-02T12:44:00.299590 | 2013-07-04T19:32:30 | 2013-07-04T19:32:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | cpp | #include<iostream>
#include<cmath>
#include "matrix.h"
using namespace std;
int main()
{
float a11, a12, a21, a22, b1, b2, alpha, tension;
while(1){
cout<<"a11 = ";
cin>> a11;
cout<<"a12 = ";
cin>> a12;
cout<<"a21 = ";
cin>> a21;
cout<<"a22 = ";
cin>> a22;
cout<<"b1 = ";
cin>> b1;
cout<<"b2 = ";
cin>> b2;
/*cout << "alpha = " ;
cin >> alpha ;
cout << "tension = " ;
cin >> tension ;
cout<<"b1 = ";*/
/*cin>> b1;
cout<<"b2 = ";
cin>> b2;*/
//Matrix a(tension*cos((PI/180)*alpha) , -tension*sin((PI/180)*alpha) ,tension*sin((PI/180)*alpha) ,tension*cos((PI/180)*alpha) );
Matrix a(a11, a12, a21, a22 );
Extpair b(b1, b2);
Extpair result = getStablePoint(a,b);
cout<<"result = ("<< result.xKoord << "," << result.yKoord << ")"<<endl;}
system("pause");
return 0;
} | [
"[email protected]"
] | |
46a3369aa8b6678212fb526629d69fea90828c85 | b19b7e9a3e69e28c0961a0567f63bee0dd9b58b9 | /Editor/Source/Editor/Public/User/PCUI/Win_RecommendStyleUMG.h | dee2cfaa36ae7810b61f1b2807487365e17b15ee | [] | no_license | 1097195326/Editor | ef80d49379675815ba2e3e58d524a7f000e6e7ca | 9bbb97bca0fcd648a9a8a68afc00b9d4bd00212b | refs/heads/master | 2020-03-17T20:59:25.173542 | 2018-05-18T10:20:36 | 2018-05-18T10:20:36 | 118,855,172 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,799 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "MainModule.h"
#include "Win_SelectCell.h"
#include "System/UI/BaseUI.h"
#include "DownloadImageTool.h"
#include "Win_ButtonSuitType.h"
#include "Win_RecommendStyleUMG.generated.h"
/**
*
*/
UCLASS()
class UWin_RecommendStyleUMG : public UBaseUI
{
GENERATED_BODY()
private:
TArray<UWin_SelectCell *> m_AllSyles;
ResHttp m_ResHttp;
int32 m_CurrentCatId;
public:
// ¸´Đ´BaseUI.
virtual bool OnStart() override;
virtual void OnInit();
virtual void OnRelease();
virtual void OnSetParams(int32 _pid, FString & _content, ...);
virtual void OnTick(float InDeltaTimeSecond);
void OnClick(int _id);
void UpdateHead();
void UpdateShow();
UWin_ButtonSuitType* CreateNewHead(FString Name,bool Last,int CategooryID);
void ShowTypeStyle(int32 id);
bool CheckCanLoad();
UPROPERTY(BlueprintReadOnly)
bool mIsLoading;
UFUNCTION(BlueprintCallable,Category = AddPage)
void AddTypeStyle();
void CreateSelectCell();
void BackToMainPage(int32 id);
void EnterRecommend();
void OnRecommendSuitIconFinished(msg_ptr _msg);
public:
static int32 m_ParentId;
UScrollBox* m_Head;
UGridPanel* m_GridPanelSuit;
UGridPanel* m_HeadGrid;
UScrollBox* m_ScrollBoxItem;
UGridPanel* m_GridPanelSuitItem;
UScrollBox* m_ScrollBoxItem1;
UGridPanel* m_GridPanelSuitItem1;
UScrollBox* m_ScrollBoxItem2;
UGridPanel* m_GridPanelSuitItem2;
UCanvasPanel* m_SpecialShowView;
UButton * m_BackButton;
TArray<UWin_ButtonSuitType*> ArrButtonSuitType;
TArray<UDownloadImageTool *> m_DownloadImageTools;
};
| [
"[email protected]"
] | |
8b8f9535cd9f08af18e4fb94b7e8283a39564c28 | 5386865e2ea964397b8127aba4b2592d939cd9f2 | /grupa C/olimpiada/nacionalen/2009/2009-05-05-studentsC/submitsC/Log32009/metro.cpp | 74e84c1fa4ffe53114c52dad57bc699ce603122b | [] | no_license | HekpoMaH/Olimpiads | e380538b3de39ada60b3572451ae53e6edbde1be | d358333e606e60ea83e0f4b47b61f649bd27890b | refs/heads/master | 2021-07-07T14:51:03.193642 | 2017-10-04T16:38:11 | 2017-10-04T16:38:11 | 105,790,126 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | /*
TASK:metro
LANG:C++
*/
#include<cstdio>
#include<algorithm>
#include<ctime>
using namespace std;
int dp[1025][150];
int lev[1025];
int n;
int main()
{
memset(dp,0x7F,sizeof(dp));
scanf("%d",&n);
for(int i=0;i<=140;i++)
dp[0][i]=0;
for(int i=1;i<=n;i++)
scanf("%d",&lev[i]);
int token=0x7F8F8F8F;
int mini=token;
for(int j=1;j<=n;j++)
for(int i=0;i<=120;i++)
{
token=min(dp[j-1][i+2],min(dp[j-1][i+1],min(dp[j-1][i],dp[j-1][max(0,i-1)])));
// printf("the chosen one is - %d on pos %d %d",token,j,i);
// system("pause");
if(i==lev[j]) token+=1;
else if(i>lev[j]) token+=(i-lev[j])*7;
else token+=(lev[j]-i)*(lev[j]-i);
dp[j][i]=token;
if(j==n)
if(token<mini) mini=token;
}
printf("%d\n",mini);
return 0;
}
| [
"dgg30"
] | dgg30 |
8bea001caafdd2c57444b18e8d7fdd91a72a0f68 | e45f197f56ec6d81728e7aa857a536db9220f9e4 | /SkProjects/GNSS_Viewer_V2/ParallelDownloadDlg.h | 4fdddf4dd8a5fe4bc81c75eec45f80c631878f6d | [] | no_license | asion0/AsionGitCodes | 82bfbaf5bf14eebeb375f3d83ecbcee5c45989ad | 7f493fb2a67e053387026a5652fc28f53e76f73c | refs/heads/master | 2016-09-10T20:12:25.665716 | 2013-12-31T09:11:47 | 2013-12-31T09:11:47 | 15,427,503 | 1 | 2 | null | null | null | null | BIG5 | C++ | false | false | 854 | h | #pragma once
// CParallelDownloadDlg 對話方塊
class CParallelDownloadDlg : public CDialog
{
DECLARE_DYNAMIC(CParallelDownloadDlg)
public:
CParallelDownloadDlg(CWnd* pParent = NULL); // 標準建構函式
virtual ~CParallelDownloadDlg();
// 對話方塊資料
// enum { IDD = IDD_FIRMWARE_DL };
virtual BOOL OnInitDialog();
int GetBaudrateIndex() { return m_nBaudrateIdx; };
int GetFlashType() { return m_nFlashType; };
CString GetFilePath() { return m_strPath; };
//BOOL IsInternal() { return m_isInternal; };
//int GetBufferIndex() { return m_nBufferIdx; };
protected:
int m_nBaudrateIdx;
int m_nFlashType;
CString m_strPath;
//BOOL m_isInternal;
//int m_nBufferIdx;
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支援
virtual void OnOK();
afx_msg void OnBnClickedBrowse();
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
] | |
aba3814a58817888c1cffb08dee0bc190ae16e82 | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Game Programming Gems/SourceCode/Mathematics/01Olsen/MainFrm.h | f3e0a6a6ed6e75ba00638a627428fb71cc698383 | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 1,752 | h | /* Copyright (C) John Olsen, 2000.
* All rights reserved worldwide.
*
* This software is provided "as is" without express or implied
* warranties. You may freely copy and compile this source into
* applications you distribute provided that the copyright text
* below is included in the resulting source code, for example:
* "Portions Copyright (C) John Olsen, 2000"
*/
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__04D78088_FEA4_11D3_9A3F_004F49077001__INCLUDED_)
#define AFX_MAINFRM_H__04D78088_FEA4_11D3_9A3F_004F49077001__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
class CMainFrame : public CFrameWnd
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CMainFrame)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__04D78088_FEA4_11D3_9A3F_004F49077001__INCLUDED_)
| [
"[email protected]"
] | |
86fbe1f5e0c7b43d07773205f6081f680be6f742 | 69570f66ad07298b8624f87021c48c8e6993e77b | /Intermediate/Build/Win64/UE4Editor/Inc/RPGBR/CB_PlayerController.generated.h | 3811d24c1747a0cf52897ef5a6e36d70360da0a6 | [] | no_license | PatrickSHYee/WonderlandDeathSphere | bc5f5c58d10aacd0163b79bb42f1bd2872e5ffe0 | e10a0905a75f29917a749b26d55fc771dcf4bca9 | refs/heads/master | 2023-08-23T13:51:31.772896 | 2021-10-19T01:55:19 | 2021-10-19T01:55:19 | 418,733,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,097 | h | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef RPGBR_CB_PlayerController_generated_h
#error "CB_PlayerController.generated.h already included, missing '#pragma once' in CB_PlayerController.h"
#endif
#define RPGBR_CB_PlayerController_generated_h
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_SPARSE_DATA
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_RPC_WRAPPERS
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_RPC_WRAPPERS_NO_PURE_DECLS
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesACB_PlayerController(); \
friend struct Z_Construct_UClass_ACB_PlayerController_Statics; \
public: \
DECLARE_CLASS(ACB_PlayerController, APlayerController, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/RPGBR"), NO_API) \
DECLARE_SERIALIZER(ACB_PlayerController)
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_INCLASS \
private: \
static void StaticRegisterNativesACB_PlayerController(); \
friend struct Z_Construct_UClass_ACB_PlayerController_Statics; \
public: \
DECLARE_CLASS(ACB_PlayerController, APlayerController, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/RPGBR"), NO_API) \
DECLARE_SERIALIZER(ACB_PlayerController)
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API ACB_PlayerController(const FObjectInitializer& ObjectInitializer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ACB_PlayerController) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ACB_PlayerController); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ACB_PlayerController); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ACB_PlayerController(ACB_PlayerController&&); \
NO_API ACB_PlayerController(const ACB_PlayerController&); \
public:
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ACB_PlayerController(ACB_PlayerController&&); \
NO_API ACB_PlayerController(const ACB_PlayerController&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ACB_PlayerController); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ACB_PlayerController); \
DEFINE_DEFAULT_CONSTRUCTOR_CALL(ACB_PlayerController)
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_PRIVATE_PROPERTY_OFFSET
#define RPGBR_Source_RPGBR_CB_PlayerController_h_12_PROLOG
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_PRIVATE_PROPERTY_OFFSET \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_SPARSE_DATA \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_RPC_WRAPPERS \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_INCLASS \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define RPGBR_Source_RPGBR_CB_PlayerController_h_15_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_PRIVATE_PROPERTY_OFFSET \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_SPARSE_DATA \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_RPC_WRAPPERS_NO_PURE_DECLS \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_INCLASS_NO_PURE_DECLS \
RPGBR_Source_RPGBR_CB_PlayerController_h_15_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> RPGBR_API UClass* StaticClass<class ACB_PlayerController>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID RPGBR_Source_RPGBR_CB_PlayerController_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"[email protected]"
] | |
3635cc783aef174ae1568412a92a0724f6b6677c | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-8548.cpp | ccafbf4653d6c3bd115df4a64543e404c6a05f1a | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,007 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : virtual c0, virtual c1
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c2*)(this);
tester1(p1_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c1, virtual c0
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c3*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c3, virtual c1, c2
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c3*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c2*)(c4*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c3*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c4*)(this);
tester1(p1_1);
c1 *p1_2 = (c1*)(c2*)(c4*)(this);
tester1(p1_2);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
c3 *p3_0 = (c3*)(c4*)(this);
tester3(p3_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active2)
p->f2();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active3)
p->f3();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c2*)(new c2());
ptrs0[2] = (c0*)(c3*)(new c3());
ptrs0[3] = (c0*)(c3*)(c4*)(new c4());
ptrs0[4] = (c0*)(c2*)(c4*)(new c4());
for (int i=0;i<5;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c2*)(new c2());
ptrs1[2] = (c1*)(c3*)(new c3());
ptrs1[3] = (c1*)(c3*)(c4*)(new c4());
ptrs1[4] = (c1*)(c4*)(new c4());
ptrs1[5] = (c1*)(c2*)(c4*)(new c4());
for (int i=0;i<6;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
ptrs3[1] = (c3*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"[email protected]"
] | |
e56b865b89f15563de7d13da8db9e51800aea628 | e4d601b0750bd9dcc0e580f1f765f343855e6f7a | /kaldi-wangke/src/latbin/nbest-to-linear.cc | d63c380133ac7094d9e0777727e593f169d3a967 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | PeiwenWu/Adaptation-Interspeech18 | 01b426cd6d6a2d7a896aacaf4ad01eb3251151f7 | 576206abf8d1305e4a86891868ad97ddfb2bbf84 | refs/heads/master | 2021-03-03T04:16:43.146100 | 2019-11-25T05:44:27 | 2019-11-25T05:44:27 | 245,930,967 | 1 | 0 | MIT | 2020-03-09T02:57:58 | 2020-03-09T02:57:57 | null | UTF-8 | C++ | false | false | 3,512 | cc | // latbin/nbest-to-linear.cc
// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "fstext/fstext-lib.h"
#include "lat/kaldi-lattice.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
typedef kaldi::int32 int32;
typedef kaldi::int64 int64;
using fst::SymbolTable;
using fst::VectorFst;
using fst::StdArc;
const char *usage =
"Takes as input lattices/n-bests which must be linear (single path);\n"
"convert from lattice to up to 4 archives containing transcriptions, alignments,\n"
"and acoustic and LM costs (note: use ark:/dev/null for unwanted outputs)\n"
"Usage: nbest-to-linear [options] <nbest-rspecifier> <alignments-wspecifier> "
"[<transcriptions-wspecifier> [<lm-cost-wspecifier> [<ac-cost-wspecifier>]]]\n"
" e.g.: lattice-to-nbest --n=10 ark:1.lats ark:- | \\\n"
" nbest-to-linear ark:1.lats ark,t:1.ali 'ark,t:|int2sym.pl -f 2- words.txt > text'\n";
ParseOptions po(usage);
po.Read(argc, argv);
if (po.NumArgs() < 2 || po.NumArgs() > 5) {
po.PrintUsage();
exit(1);
}
std::string lats_rspecifier = po.GetArg(1),
ali_wspecifier = po.GetArg(2),
trans_wspecifier = po.GetOptArg(3),
lm_cost_wspecifier = po.GetOptArg(4),
ac_cost_wspecifier = po.GetOptArg(5);
SequentialLatticeReader lattice_reader(lats_rspecifier);
Int32VectorWriter ali_writer(ali_wspecifier);
Int32VectorWriter trans_writer(trans_wspecifier);
BaseFloatWriter lm_cost_writer(lm_cost_wspecifier);
BaseFloatWriter ac_cost_writer(ac_cost_wspecifier);
int32 n_done = 0, n_err = 0;
for (; !lattice_reader.Done(); lattice_reader.Next()) {
std::string key = lattice_reader.Key();
Lattice lat = lattice_reader.Value();
std::vector<int32> ilabels;
std::vector<int32> olabels;
LatticeWeight weight;
if (!GetLinearSymbolSequence(lat, &ilabels, &olabels, &weight)) {
KALDI_WARN << "Lattice/nbest for key " << key << " had wrong format: "
"note, this program expects input with one path, e.g. from "
"lattice-to-nbest.";
n_err++;
} else {
if (ali_wspecifier != "") ali_writer.Write(key, ilabels);
if (trans_wspecifier != "") trans_writer.Write(key, olabels);
if (lm_cost_wspecifier != "") lm_cost_writer.Write(key, weight.Value1());
if (ac_cost_wspecifier!= "") ac_cost_writer.Write(key, weight.Value2());
n_done++;
}
}
KALDI_LOG << "Done " << n_done << " n-best entries, "
<< n_err << " had errors.";
return (n_done != 0 ? 0 : 1);
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| [
"[email protected]"
] | |
9fd8f76c76ebfb06aeb72fb8a8e07893488e75ab | 73711c12ced25410ce39f6a6d83439772761c983 | /SQLWindows.UserInterface/SQLWindows.UserInterface/PaintManager.cpp | 9410ddff26a8fa88b4f2c167570891b5b136da8a | [
"MIT"
] | permissive | Opzet/SQLWindows.UserInterface | 5d6a90a23d09e53f3153f1ff4fdcb0032f4affd6 | 4d0aff61056aa5fd1f4fdd189d26dbf37adcc6bc | refs/heads/master | 2023-06-07T03:11:42.884099 | 2019-12-31T08:02:04 | 2019-12-31T08:02:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | #include "stdafx.h"
#include "Prof-UIS.h"
extern "C" __declspec(dllexport) COLORREF WINAPI UISalPaintManagerGetColor(int colorIndex)
{
// use global Paint Manager
CExtPaintManager* paintManager = g_PaintManager.GetPM();
if (paintManager != NULL)
{
COLORREF test = paintManager->GetColor(colorIndex);
return paintManager->GetColor(colorIndex);
}
return 0;
}
extern "C" __declspec(dllexport) COLORREF WINAPI UISalPaintManagerSetColor(int colorIndex, COLORREF color)
{
// use global Paint Manager
CExtPaintManager* paintManager = g_PaintManager.GetPM();
if (paintManager != NULL)
{
COLORREF previousColor = paintManager->GetColor(colorIndex);
paintManager->InstallColor(color, colorIndex);
return previousColor;
}
return 0;
}
extern "C" __declspec(dllexport) HPALETTE WINAPI UISalPaintManagerGetPalette()
{
// use global Paint Manager
CExtPaintManager* paintManager = g_PaintManager.GetPM();
if (paintManager != NULL)
{
// get palette
return (HPALETTE)paintManager->m_PaletteWide.GetSafeHandle();
}
return 0;
}
| [
"[email protected]"
] | |
d0472971be41bf9404949a0ca56d5106513d0913 | 06a4c6d5376d2d067472a85b3cc74c385bbe50c7 | /libs/rtk++/test/osa/test_osa_semaphore1.cpp | 9dd780d20d6140859d2faf848c434efcdd297cbf | [] | no_license | UAVWorks/SimpGCS | 1452869ae72e477ec184593405d70e414c3fb65f | 0a6cecd720abf67ae9c6dfbfc4aaddd41b9481a8 | refs/heads/master | 2020-04-10T16:15:24.700934 | 2015-07-08T10:45:39 | 2015-07-08T10:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,871 | cpp | /******************************************************************************
Robot Toolkit ++ (RTK++)
Copyright (c) 2007-2013 Shuhui Bu <[email protected]>
http://www.adv-ci.com
----------------------------------------------------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
#include <stdio.h>
#include "rtk_osa.h"
#include "rtk_test_module.h"
using namespace rtk;
int osa_test_semaphore1(void);
static OSA_RESULT _thread1_proc(OSA_T_ARGS arg);
OSA_HANDLE _test_semaphore1;
ru32 _test_sm1_ready;
int osa_test_semaphore1(void)
{
OSA_RESULT res;
OSA_HANDLE hThread;
test_db("[Function] osa_test_semaphore1()\n");
test_db("[Description] To test the basic functinality of mutex\n");
test_db("[Description] If you cann't 'Success' message this test failed!\n");
_test_sm1_ready = false;
/* Create semaphore with count 0 */
res = osa_sem_create(&_test_semaphore1, 0, 0);
if( 0 != res ) {
test_db("[ERROR] Fail at osa_sem_create, res=%d\n", res);
test_db("[RESULT] Fail\n");
return 0;
}
/* Create a thread */
res = osa_t_create(&hThread, _thread1_proc, 0, 16 * 1024, 0);
if( 0 != res ) {
test_db("[ERROR] Fail at osa_t_create, res=%d\n", res);
test_db("[RESULT] Fail\n");
return 0;
}
/* Wait for locking semaphore */
res = osa_sem_wait(_test_semaphore1);
if( 0 != res ) {
test_db("[ERROR] Fail at osa_sem_wait, res=%d\n", res);
test_db("[RESULT] Fail\n");
return 0;
}
if (_test_sm1_ready == false) {
test_db("[ERROR] The osa_sem_wait didn['t wait until sm is available\n");
test_db("[RESULT] Fail\n");
return 0;
}
/* Try to lock semaphore without waiting: Expect OSA_WAIT_NO */
res = osa_sem_wait_timeout(_test_semaphore1, OSA_WAIT_NO);
if( res != E_OSA_SEM_TIMEOUT ) {
test_db("[ERROR] Fail at osa_sem_wait_timeout, res=%d\n", res);
test_db("[MSG 1] E_OSA_SEM_TIMEOUT(%d) must be returned\n", E_OSA_SEM_TIMEOUT);
test_db("[RESULT] Fail\n");
return 0;
}
/* Try to lock semaphore with timeout: Expect E_OSA_SEM_TIMEOUT */
res = osa_sem_wait_timeout(_test_semaphore1, 100);
if( res != E_OSA_SEM_TIMEOUT ) {
test_db("[ERROR] Fail at osa_sem_wait, res=%d\n", res);
test_db("[MSG 1] E_OSA_SEM_TIMEOUT(%d) must be returned\n", E_OSA_SEM_TIMEOUT);
test_db("[RESULT] Fail\n");
return 0;
}
/* Delete semaphore */
res = osa_sem_delete(_test_semaphore1);
if( res != 0 ) {
test_db("[ERROR] Fail at osa_sem_delete, res=%d\n", res);
test_db("[RESULT] Fail\n");
return 0;
}
osa_t_kill(hThread);
osa_t_delete(hThread);
test_db("[RESULT] Success\n");
test_db("\n");
return 0;
}
OSA_RESULT _thread1_proc(OSA_T_ARGS arg)
{
OSA_RESULT res;
res = osa_t_sleep(2000);
if( res != 0 ) {
test_db("[ERROR] Fail at osa_t_sleep, res=%d\n", res);
test_db("[RESULT] Fail\n");
return 0;
}
_test_sm1_ready = true;
res = osa_sem_signal(_test_semaphore1);
if( res != 0 ) {
test_db("[ERROR] Fail at osa_sem_signal, res=%d\n", res);
test_db("[RESULT] Fail\n");
return 0;
}
return 0;
}
| [
"[email protected]"
] | |
2bbec0d9131524a15ce6207783135bb2e98aa305 | 9d9c217d265515738bd2889cf7512d796169c243 | /Problems/TeamSelection/DayOne/H/main.cpp | 8dd5c134f66d0cd14e10185ca4ce46c24e3ac061 | [] | no_license | Evalir/Algorithms | f4d70f6b5cb7a20b5304a8543dd9dd443d2e7d7d | c58507d9f79eb388dd98b8e22302598eb29876e0 | refs/heads/master | 2021-07-08T16:52:15.820629 | 2019-09-21T23:45:52 | 2019-09-21T23:45:52 | 99,495,180 | 0 | 0 | null | 2017-10-24T22:07:37 | 2017-08-06T15:20:17 | Makefile | UTF-8 | C++ | false | false | 755 | cpp | #include <iostream>
#include <cmath>
#include <stack>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
using ll = long long;
int main() {
ll n;
cin >> n;
vector<ll> o, e;
ll ans = 0;
for(int i = 0; i < n; i++) {
ll x;
cin >> x;
ans += x;
if (x & 1) o.push_back(x);
else e.push_back(x);
}
sort(o.begin(), o.end());
sort(e.begin(), e.end());
int p, t;
p = t = 0;
if (!(ans & 1)) {
cout << ans << endl;
return 0;
}
else {
while(p < o.size() && ans & 1) {
ans -= o[p];
p++;
}
}
if (!(ans & 1))
cout << ans << endl;
else
cout << 0 << endl;
return 0;
} | [
"[email protected]"
] | |
14c815545b7a098c445062fc20cb25902b086527 | 1af49694004c6fbc31deada5618dae37255ce978 | /chrome/browser/chromeos/phonehub/phone_hub_manager_factory.cc | 828d1c0c1a39cb63318bd5dfc26e71ed959c6674 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 4,978 | cc | // Copyright 2020 The Chromium 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 "chrome/browser/chromeos/phonehub/phone_hub_manager_factory.h"
#include "ash/public/cpp/system_tray.h"
#include "chrome/browser/chromeos/device_sync/device_sync_client_factory.h"
#include "chrome/browser/chromeos/multidevice_setup/multidevice_setup_client_factory.h"
#include "chrome/browser/chromeos/phonehub/browser_tabs_metadata_fetcher_impl.h"
#include "chrome/browser/chromeos/phonehub/browser_tabs_model_provider_impl.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/secure_channel/nearby_connector_factory.h"
#include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h"
#include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/session_sync_service_factory.h"
#include "chrome/browser/ui/webui/chromeos/multidevice_setup/multidevice_setup_dialog.h"
#include "chromeos/components/phonehub/multidevice_setup_state_updater.h"
#include "chromeos/components/phonehub/notification_access_manager_impl.h"
#include "chromeos/components/phonehub/onboarding_ui_tracker_impl.h"
#include "chromeos/components/phonehub/phone_hub_manager_impl.h"
#include "chromeos/constants/chromeos_features.h"
#include "chromeos/services/multidevice_setup/public/cpp/prefs.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/pref_registry/pref_registry_syncable.h"
namespace chromeos {
namespace phonehub {
namespace {
bool IsProhibitedByPolicy(Profile* profile) {
return !multidevice_setup::IsFeatureAllowed(
multidevice_setup::mojom::Feature::kPhoneHub, profile->GetPrefs());
}
bool IsLoggedInAsPrimaryUser(Profile* profile) {
// Guest/incognito profiles cannot use Phone Hub.
if (profile->IsOffTheRecord())
return false;
// Likewise, kiosk users are ineligible.
if (user_manager::UserManager::Get()->IsLoggedInAsAnyKioskApp())
return false;
return ProfileHelper::IsPrimaryProfile(profile);
}
} // namespace
// static
PhoneHubManager* PhoneHubManagerFactory::GetForProfile(Profile* profile) {
return static_cast<PhoneHubManagerImpl*>(
PhoneHubManagerFactory::GetInstance()->GetServiceForBrowserContext(
profile, /*create=*/true));
}
// static
PhoneHubManagerFactory* PhoneHubManagerFactory::GetInstance() {
return base::Singleton<PhoneHubManagerFactory>::get();
}
PhoneHubManagerFactory::PhoneHubManagerFactory()
: BrowserContextKeyedServiceFactory(
"PhoneHubManager",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(device_sync::DeviceSyncClientFactory::GetInstance());
DependsOn(multidevice_setup::MultiDeviceSetupClientFactory::GetInstance());
DependsOn(secure_channel::NearbyConnectorFactory::GetInstance());
DependsOn(SessionSyncServiceFactory::GetInstance());
DependsOn(HistoryUiFaviconRequestHandlerFactory::GetInstance());
}
PhoneHubManagerFactory::~PhoneHubManagerFactory() = default;
KeyedService* PhoneHubManagerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
if (!features::IsPhoneHubEnabled())
return nullptr;
Profile* profile = Profile::FromBrowserContext(context);
// Only available to the primary profile.
if (!IsLoggedInAsPrimaryUser(profile))
return nullptr;
if (IsProhibitedByPolicy(profile))
return nullptr;
PhoneHubManagerImpl* phone_hub_manager = new PhoneHubManagerImpl(
profile->GetPrefs(),
device_sync::DeviceSyncClientFactory::GetForProfile(profile),
multidevice_setup::MultiDeviceSetupClientFactory::GetForProfile(profile),
secure_channel::SecureChannelClientProvider::GetInstance()->GetClient(),
std::make_unique<BrowserTabsModelProviderImpl>(
multidevice_setup::MultiDeviceSetupClientFactory::GetForProfile(
profile),
SessionSyncServiceFactory::GetInstance()->GetForProfile(profile),
std::make_unique<BrowserTabsMetadataFetcherImpl>(
HistoryUiFaviconRequestHandlerFactory::GetInstance()
->GetForBrowserContext(context))),
base::BindRepeating(&multidevice_setup::MultiDeviceSetupDialog::Show));
// Provide |phone_hub_manager| to the system tray so that it can be used by
// the UI.
ash::SystemTray::Get()->SetPhoneHubManager(phone_hub_manager);
return phone_hub_manager;
}
bool PhoneHubManagerFactory::ServiceIsCreatedWithBrowserContext() const {
return true;
}
void PhoneHubManagerFactory::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
MultideviceSetupStateUpdater::RegisterPrefs(registry);
NotificationAccessManagerImpl::RegisterPrefs(registry);
OnboardingUiTrackerImpl::RegisterPrefs(registry);
}
} // namespace phonehub
} // namespace chromeos
| [
"[email protected]"
] | |
311910de9057870cad826087f41568a7441f8105 | e4b96695bc6a6e64b50ed25a643f307cacef4cf8 | /vector/base_vector.hpp | 958bccde132bcd46b8602c105d845988ab7010be | [] | no_license | MexicanMan/Carcass-Visualizer | eb3dd823e3f1e05fa2fb17852e3e31775b7a3fbb | 554c9e33a3f781ab4b9cb3927fe8a0f38d4f7a69 | refs/heads/master | 2020-08-02T23:20:06.136254 | 2019-09-28T19:10:09 | 2019-09-28T19:10:09 | 211,542,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | hpp | #ifndef BASE_VECTORWORK_HPP
#define BASE_VECTORWORK_HPP
#include "base_vector.h"
// Real vector length
inline int BaseVector::length() const
{
return this->len;
}
// Vector emptiness check
inline bool BaseVector::isEmpty() const
{
if (this->len)
return false;
else
return true;
}
#endif // BASE_VECTORWORK_HPP
| [
"[email protected]"
] | |
8cb2cfca7173b8babaa6a196ded0a6866f15034f | 706f61d9536f82714e82c2f3f018dea24feedbe9 | /TextSearch-Windows/TextSearchCom/TextSearch.cpp | d2332c955621d68d14c7945d81d1ede785cbb421 | [] | no_license | Travelsnaker/TextSearch_Windows | 7e74759945002d1c8260a8c5eeab49971377c735 | 6864a5fe00db5218ea1ecc412e6ac47cda64d29f | refs/heads/master | 2020-12-02T21:34:36.607359 | 2016-08-23T20:02:32 | 2016-08-23T20:02:32 | 66,399,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,621 | cpp | ///////////////////////////////////////////////////////////////
// TextSearch.cpp - Implementation of TextSearch Interface //
// //
// Platform: Lenovo Y470, Core i3, Windows 7 SP1 //
// Application: Demonstration for CSE775 - Distrib. Objs //
// Authors: Wei Sun, Computer Engineering,Syracuse Univ//
// [email protected] //
///////////////////////////////////////////////////////////////
// TextSearch.cpp : Implementation of CTextSearch
#include "stdafx.h"
#include "TextSearch.h"
// CTextSearch
//-----< enqueue the fully specified file name for text search >-----
STDMETHODIMP CTextSearch::enqueue(BSTR filename)
{
// TODO: Add your implementation code here
string _filename = Utilities::ConvertBSTRToMBS(filename);
store.enQ(_filename);
return S_OK;
}
//-----< Specify the number of threads and target text>-----
STDMETHODIMP CTextSearch::setupSearch(LONG num,BSTR text)
{
// TODO: Add your implementation code here
_stop = false;
string txt = Utilities::ConvertBSTRToMBS(text);
for (int i = 0; i <num; ++i)
{
threads.push_back(thread(&CTextSearch::textSearch, this, txt));
}
return S_OK;
}
//-----< Start asychronously text search >-----
STDMETHODIMP CTextSearch::startSearch()
{
// TODO: Add your implementation code here
for (auto& t : threads)
t.detach();
return S_OK;
}
//-----< Search target text in a single file >-----
bool CTextSearch::TxtSearch(const std::string&file, const std::string&TargetText)
{
std::ostringstream temp;
std::ifstream in(file);
if (in.good())
{
temp << in.rdbuf();
std::string& contents = temp.str();
size_t pos = contents.find(TargetText);
if (pos != std::string::npos)
return true;
}
return false;
}
//----< Search text >----
void CTextSearch::textSearch(string txt)
{
while (true)
{
if (_stop)
break;
string filename = store.deQ();
if (TxtSearch(filename, txt))
{
result.enQ(filename);
}
}
}
//----< get search results >----
STDMETHODIMP CTextSearch::get(BSTR* filename)
{
// TODO: Add your implementation code here
string file = result.deQ();
BSTR _file = Utilities::ConvertMBSToBSTR(file);
*filename = _file;
SysFreeString(_file);
return S_OK;
}
//----< stop asychronous search >----
STDMETHODIMP CTextSearch::stopSearch()
{
// TODO: Add your implementation code here
_stop = true;
return S_OK;
}
//----< Get the number of searching results >-----
STDMETHODIMP CTextSearch::getNumRes(LONG* num)
{
// TODO: Add your implementation code here
*num = result.size();
return S_OK;
}
| [
"[email protected]"
] | |
28c2dbeec9e96f5e84c83ff296f1a40e910fada6 | 3a3a8b9e6ebb22912b0b157df3cb13750619710f | /mikrodenetleyiciler/ders/laboratuvar-soruları/calismalarim/rapor4-sorua/rapor4-sorua.ino | b6bc8d4c6bde372d02754f9527728f1ab642cce0 | [] | no_license | MuhammedKaradas/okul | 31f2b4935ca18af56b3e6ffb45a3c877cf3addae | ac4f45604823007c3e9e0e598f9e8fd88ca7bf69 | refs/heads/master | 2021-07-07T14:03:46.844300 | 2020-10-21T20:53:04 | 2020-10-21T20:53:04 | 192,000,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153 | ino | int pin=13;
void setup() {
pinMode(pin,OUTPUT);
}
void loop() {
digitalWrite(pin,HIGH);
delay(8000);
digitalWrite(pin,LOW);
delay(8000);
}
| [
"[email protected]"
] | |
ba6afc270a415e7bd56e0fae8bdb02bc67fb5d68 | 74ef11065048fcf08ee5b9ef1c11c0ce10079301 | /expansion_js/src/dependencies/fdeep/layers/zero_padding_2d_layer.hpp | 44747d9322b9f7a08c0f8b60ab35050b54dc9069 | [
"MIT"
] | permissive | kliment-olechnovic/voronota | fa2548c9ccc3dd6f5a10a054300aca8b6d31ecf4 | 52c2b0d55f2979d0eef478ed0be20376cb3d561a | refs/heads/master | 2023-09-04T05:09:11.275304 | 2023-08-30T07:59:07 | 2023-08-30T07:59:07 | 203,789,299 | 19 | 6 | MIT | 2023-07-04T06:25:54 | 2019-08-22T12:20:48 | C++ | UTF-8 | C++ | false | false | 1,106 | hpp | // Copyright 2016, Tobias Hermann.
// https://github.com/Dobiasd/frugally-deep
// Distributed under the MIT License.
// (See accompanying LICENSE file or at
// https://opensource.org/licenses/MIT)
#pragma once
#include "fdeep/layers/layer.hpp"
#include <string>
namespace fdeep { namespace internal
{
class zero_padding_2d_layer : public layer
{
public:
explicit zero_padding_2d_layer(const std::string& name,
std::size_t top_pad,
std::size_t bottom_pad,
std::size_t left_pad,
std::size_t right_pad) :
layer(name),
top_pad_(top_pad),
bottom_pad_(bottom_pad),
left_pad_(left_pad),
right_pad_(right_pad)
{
}
protected:
tensors apply_impl(const tensors& inputs) const override
{
const auto& input = single_tensor_from_tensors(inputs);
return {pad_tensor(0, top_pad_, bottom_pad_, left_pad_, right_pad_, input)};
}
std::size_t top_pad_;
std::size_t bottom_pad_;
std::size_t left_pad_;
std::size_t right_pad_;
};
} } // namespace fdeep, namespace internal
| [
"[email protected]"
] | |
c3ce6d595fa5f2141fd2120016f3a7a129ebba82 | 2410fa2248b1d7bba4645f274d8055a9027fad7f | /server/games/bam/GamePlayer.hpp | 6e29edffeff6642b1cae69267d047bbefcb55474 | [] | no_license | Pocsel/rtype | 2324733314c3b18c919c59743356d3c1412fd5ec | d21f161d47cbc4097f2a2d646be37128ba1c3e7e | refs/heads/master | 2021-06-19T10:40:32.176836 | 2011-03-31T18:53:20 | 2011-03-31T18:53:20 | 97,037,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | hpp | #ifndef __GAMEPLAYER_HPP__
#define __GAMEPLAYER_HPP__
#include "BasicPlayer.hpp"
namespace Gmgp
{
namespace Server
{
class PlayerEntity;
class GameEntity;
class Game;
template<typename Entity, typename GamePlayer> class BasicGame;
class ITcpSocketProxy;
class GamePlayer :
public BasicPlayer
{
public:
explicit GamePlayer(uint16_t id, String const& nick, ITcpSocketProxy* socketProxy, BasicGame<GameEntity, GamePlayer>& game);
~GamePlayer();
size_t GetScore() const;
void AddScore(size_t score);
private:
Game& _game;
PlayerEntity* _player;
size_t _score;
};
}
}
#endif
| [
"[email protected]"
] | |
577555c404b265782e339779740f011b84f8539b | 3d88f7f8c06b4cb20cfb6ce32e2a884b8d54be8d | /randomstuffs/banned-words.cpp | 875c32873b401949d91dd691929947364fd3a072 | [
"MIT"
] | permissive | NotNotQuinn/cpp-game-stuff | 238c361e57a79f44114d39244c0459b70dbf52a7 | 7fb2f346a2e0fb5b7119352a31d9238f012e52c1 | refs/heads/main | 2023-03-03T06:18:31.293102 | 2021-02-11T00:43:21 | 2021-02-11T00:43:21 | 335,457,792 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 369 | cpp | #include <string>
#include <cmath>
#include <iostream>
using std::string;
using std::cin;
using std::cout;
string sensor(string, int);
int main()
{
int a;
cin >> a;
cout << sensor("YOOOOOO");
return 0;
}
string sensor(string unsensored, int sensor_level = 2)
{
if (sensor_level == 0)
{
return unsensored;
}
return "";
}
| [
"[email protected]"
] | |
b36ae276dc434b9276495b7776cd723a474fa2fd | 26309a202bfc2b61151555b926295e119a0f5d87 | /28.cpp | 166cf5098f3c8bbd58659c249b2d9d952fb1d2fa | [] | no_license | ClearSeve/Old-Codes | 7696ecb9816ac8c972ede66a88dc7a2a3ff3b3be | c2bc55bd94da84d404e6ed3be92b81ffcfbaa74f | refs/heads/master | 2023-03-18T17:13:36.472947 | 2014-10-19T15:19:06 | 2014-10-19T15:19:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,615 | cpp | #include<iostream>
#include<stdio.h>
int main()
{
int n,i,j,spoon,c,r;//shayas g++ me thik se chalta ho
char a[101][101];
scanf("%d",&n);
while(n--)
{scanf("%d%d",&r,&c);
spoon=0;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%c",&a[i][j]);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(a[i][j]=='S' || a[i][j]=='s')
{
if(a[i][j+1]=='P' ||a[i][j+1]=='p')//AAge bhai
{
if(a[i][j+2]=='O' ||a[i][j+2]=='o')
if(a[i][j+3]=='O' ||a[i][j+3]=='o' )
if(a[i][j+4]=='N' ||a[i][j+4]=='n')
spoon++;
}
else if(a[i+1][j]=='P' || a[i+1][j]=='p')
{ if(a[i+2][j]=='O' || a[i+2][j]=='o')
if(a[i+3][j]=='O' || a[i+3][j]=='o' )
if(a[i+4][j]=='N' || a[i+4][j]=='n')
spoon++;
}
}
}
}//chalo for
printf("%d \n",spoon);
if(spoon)
printf("There is a spoon!\n");
else
printf("There is indeed no spoon!\n");
}
scanf("%d",&n);
return 0;
}
| [
"[email protected]"
] | |
ff76a3e6bf8f82dab4c3a9e367fc12c81da9e236 | 828767a8c81c9aea805f2ae26ec906e9011607db | /60.cpp | 9d4530e1afd3a8ff725dc5a04791bb7066b58b43 | [] | no_license | Jian-Yin-Shine/nowcoder-offer | c3c453f41163c6ad382d6ecf5db6d984a3367a51 | fadc34ccc15b1d5996af574d5466cca81b614569 | refs/heads/master | 2020-06-10T16:36:35.614398 | 2019-07-05T04:32:13 | 2019-07-05T04:32:13 | 193,677,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,176 | cpp | //
// main.cpp
// 60
//
// Created by 小尹 on 2019/6/25.
// Copyright © 2019 小尹. All rights reserved.
//
// 剑指offer60
// 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
// 思路:bfs 时记录该层节点。只是,现在是用树,指针表示。
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL){}
};
class Solution {
public:
vector<vector<int> > Print(TreeNode *pRoot) {
vector<vector<int> > ans;
vector<int> tmp;
if (pRoot==NULL) return ans;
queue<TreeNode*> q;
q.push(pRoot);
int now_level = 1;
int next_level = 0;
while (!q.empty()) {
TreeNode* fr = q.front();
q.pop();
tmp.push_back(fr->val);
if(fr->left != NULL) {
q.push(fr->left);
next_level += 1;
}
if(fr->right!= NULL) {
q.push(fr->right);
next_level += 1;
}
--now_level;
if(now_level==0){
now_level = next_level;
next_level = 0;
ans.push_back(tmp);
for(int i = 0; i < (int)tmp.size(); i++) {
printf("%d ", tmp[i]);
}
puts("");
tmp.clear();
}
}
return ans;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
TreeNode a = TreeNode(1);
TreeNode b = TreeNode(2);
TreeNode c = TreeNode(3);
TreeNode d = TreeNode(4);
TreeNode e = TreeNode(5);
TreeNode f = TreeNode(6);
TreeNode g = TreeNode(7);
TreeNode h = TreeNode(8);
a.left = &b;
a.right = &c;
b.left = &d;
b.right = &e;
c.left = &f;
e.left = &g;
e.right = &h;
Solution solu = Solution();
solu.Print(&a);
return 0;
}
| [
"[email protected]"
] | |
10d30610697d51192e3a81ec7a6e7dc8d1cb789a | 6e20207f8aff0f0ad94f05bd025810c6b10a1d5f | /SDK/SimpleSuit_classes.h | 33f3faf0bac2e81736f01664e697f1ebe2c6858c | [] | no_license | zH4x-SDK/zWeHappyFew-SDK | 2a4e246d8ee4b58e45feaa4335f1feb8ea618a4a | 5906adc3edfe1b5de86b7ef0a0eff38073e12214 | refs/heads/main | 2023-08-17T06:05:18.561339 | 2021-08-27T13:36:09 | 2021-08-27T13:36:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 817 | h | #pragma once
// Name: WeHappyFew, Version: 1.8.8
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass SimpleSuit.SimpleSuit_C
// 0x0008 (0x07B8 - 0x07B0)
class ASimpleSuit_C : public AGlimpsePickupOutfit
{
public:
unsigned char UnknownData00[0x8]; // 0x07B0(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass SimpleSuit.SimpleSuit_C");
return ptr;
}
void UserConstructionScript();
void ReceiveBeginPlay();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
10015183708efd57f438c359e263fa74eac3b3e6 | 12dd7c753dbef7c05bc2a6c1843785eb2c9c802d | /CQUPT/自定义/00谭浩强习题选做/05第六章/01例题/6.04-二维数组行列互换.cpp | 573f39d90c35adcf0b5224c4a162066843d454cc | [] | no_license | Echo002/the-Best-of-C | 3b82fa4589a076d6deafa8b9ed8ef971cca6aee6 | 3008bf847b841994b618cab15edb812fd04ac6ad | refs/heads/master | 2021-05-04T12:05:28.454758 | 2018-03-18T15:57:48 | 2018-03-18T15:57:48 | 120,286,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | cpp | #include <stdio.h>
void main()
{
int a[2][3]={1,2,3,4,5,6};
int b[3][2]={0};
int i,j;
for(i=0;i<3;i++)
for(j=0;j<2;j++)
b[i][j]=a[j][i];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%d",a[i][j]);
printf("\n");
}
printf("\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf("%d",b[i][j]);
printf("\n");
}
} | [
"[email protected]"
] | |
7f3c7c1f10b9c08607dc93f1e2e0784d08400784 | 19f039b593be9401d479b15f97ecb191ef478f46 | /RSA-SW/PSME/application/src/core/dto/storage/storage_services_info_dto.hpp | 5d5025b9015e06716064524c3d1a9ed55a83af0c | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | isabella232/IntelRackScaleArchitecture | 9a28e34a7f7cdc21402791f24dad842ac74d07b6 | 1206d2316e1bd1889b10a1c4f4a39f71bdfa88d3 | refs/heads/master | 2021-06-04T08:33:27.191735 | 2016-09-29T09:18:10 | 2016-09-29T09:18:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,539 | hpp | /*!
* @section LICENSE
*
* @copyright
* Copyright (c) 2015 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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.
*
* @section DESCRIPTION
*
* @file core/dto/storage/storage_services_info_dto.hpp
* @brief Request transfer object declaration.
* */
#ifndef PSME_CORE_DTO_STORAGE_STORAGE_SERVICES_INFO_DTO_HPP
#define PSME_CORE_DTO_STORAGE_STORAGE_SERVICES_INFO_DTO_HPP
#include "core/dto/request_dto.hpp"
#include "core/dto/response_dto.hpp"
#include "core/dto/collections_dto.hpp"
#include "core/dto/status_dto.hpp"
#include "core/dto/oem_data_dto.hpp"
/*! PSME namespace */
namespace psme {
/*! Core namespace */
namespace core {
/*! DTO namespace */
namespace dto {
/*! Storage namespace */
namespace storage {
/*! StorageServicesInfo request object */
class StorageServicesInfoDTO {
public:
/*! Copy constructor */
StorageServicesInfoDTO(const StorageServicesInfoDTO&) = default;
/*! Assigment constructor */
StorageServicesInfoDTO& operator=(const StorageServicesInfoDTO&) = default;
/*! Default constructor */
StorageServicesInfoDTO() {}
/*! StorageServicesInfo DTO request */
class Request : public RequestDTO {
std::string m_services{};
public:
/*! Default constructor. */
Request() : RequestDTO(){}
/*!
* Sets services UUID
*
* @param services Services UUID
* */
void set_services(const std::string& services) {
m_services = services;
}
/*!
* Gets services UUID
*
* @return Services UUID
* */
const std::string& get_services() const {
return m_services;
}
/*! Serializes object to JSON
*
* @return Request object serialized to JSON.
* */
const Json::Value to_json() const;
virtual ~Request();
};
/*! StorageServicesInfo DTO response */
class Response : public ResponseDTO {
public:
/*! Copy constructor */
Response(const Response &) = default;
/*! Assigment constructor */
Response& operator=(const Response &) = default;
/*! Default constructor */
Response() : ResponseDTO(){}
/*!
* Desarializes drives response object to JSON
*
* @param response Response JSON
* */
void to_object(const Json::Value& response);
/*!
* Adds collection
*
* @param collection Collection
* */
void add_collection(const CollectionsDTO::Collection& collection) {
m_collections.add_collection(collection);
}
/*!
* Gets collections
*
* @return Collections
* */
const CollectionsDTO::Response& get_collections() const {
return m_collections;
}
/*!
* Sets status
*
* @param status Status
* */
void set_status(const StatusDTO::Response& status) {
m_status = status;
}
/*!
* Gets status
*
* @return Status
* */
const StatusDTO::Response& get_status() const {
return m_status;
}
/*!
* Sets OEM specific data
*
* @param oem_data OEM specific data
* */
void set_oem_data(const OEMDataDTO::Response& oem_data) {
m_oem_data = oem_data;
}
/*!
* Gets OEM specific data
*
* @return OEM specific data
* */
const OEMDataDTO::Response& get_oem_data() const {
return m_oem_data;
}
virtual ~Response();
private:
CollectionsDTO::Response m_collections{};
StatusDTO::Response m_status{};
OEMDataDTO::Response m_oem_data{};
};
~StorageServicesInfoDTO();
};
}
}
}
}
#endif /* PSME_CORE_DTO_STORAGE_STORAGE_SERVICES_INFO_DTO_HPP */
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.