blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
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
listlengths
1
1
author_id
stringlengths
0
158
fac1a308e600b1e8277f210843072d0541c3dd13
ed7f6c319832eea157538da4df093686b328ddb6
/Programmation de Jeux Vidéos III/Semaine 04/TP1_Prog/remise/Imagwzit/Imagwzit/Character.cpp
6fe37d89c9974d4429ea8f09c84666f6edbc4db1
[]
no_license
smasson99/Session-03
47013a02d5640513b09cb2d097680d50bf085890
eeeb3b81eb41055e57ba8c12acc3c5d437e1224e
refs/heads/master
2021-01-19T18:20:41.198880
2017-10-30T03:56:13
2017-10-30T03:56:13
101,121,137
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,352
cpp
#include "Character.h" /// <summary> /// Constructeur dont le rôle est d'initialiser les variables par défaut de la classe Character /// </summary> Character::Character() { //Initialiser les variables par défaut targetPos.x = 1; targetPos.y = 0; } /// <summary> /// Fonction dont le rôle est de setter la position du personnage en x et en y /// </summary> /// <param name="x">La position en X</param> /// <param name="y">La position en Y</param> void Character::SetPosition(float x, float y) { //Setter la position en x et en y Movable::SetPosition(x, y); } /// <summary> /// Fonction dont le rôle est d'updater la position de la cible à pointer en x et en y /// </summary> /// <param name="x">La position de la cible en x.</param> /// <param name="y">La position de la cible en y.</param> void Character::UpdateTargetPosistion(float x, float y) { //Setter la position de la cible en x et en y targetPos = sf::Vector2f(x, y); } /// <summary> /// Fonction dont le rôle est de calculer l'angle pour pointer vers la cible et pointer la sprite vers celle-ci /// </summary> void Character::LookAtTarget() { //Calculer l'angle pour pointer vers la cible float angle = (float)atan2((targetPos.y - GetY()), (targetPos.x - GetX())); //Pointer vers la cible currentAngle = Movable::SetRotation(angle, true); }
[ "smasson99@gmail.com" ]
smasson99@gmail.com
8178a2c45b43cb1fa18cc001964f5dcd45945d53
8319097d116501d562c0d1cbaafe3fcdebebb119
/interface/sources/LoginInWidget.cpp
6d53f4b158eef508fca55934ab3da6042a4c967a
[]
no_license
GiantClam/jubangktv
e6d596d33b4193e2c891e1f69021142b5078f811
51dd618ce38b9628669e5973c75cf3f1344b0bbf
refs/heads/master
2020-05-20T11:09:02.341186
2012-09-16T17:19:42
2012-09-16T17:19:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,903
cpp
#include "LoginInWidget.h" #include "../../baselib/headers/GlobalData.h" #include "../../sqlite/DbUtil.h" #include "UserInfo.h" const QString TOP_LEFT_IMAGE = IMAGE_PATH_PREFIX + "collection/topleft.png"; const QString TOP_RIGHT_IMAGE = IMAGE_PATH_PREFIX + "collection/topright.png"; const QString CENTER_IMAGE = IMAGE_PATH_PREFIX + "collection/center.png"; const QString DELETE_IMAGE = IMAGE_PATH_PREFIX + "collection/delete.png"; const QString CONFIRM_IMAGE = IMAGE_PATH_PREFIX + "collection/confirm.png"; const QString INPUT_BOX_IMAGE = IMAGE_PATH_PREFIX + "collection/inputbox.png"; const QString BACKGROUND_IMAGE = IMAGE_PATH_PREFIX + "collection/background.png"; LoginInWidget::LoginInWidget(QWidget *_parent) : numberOneButton(TOP_LEFT_IMAGE, this), numberTwoButton(CENTER_IMAGE, this), numberThreeButton(TOP_RIGHT_IMAGE, this), numberFourButton(CENTER_IMAGE, this), numberFiveButton(CENTER_IMAGE, this), numberSixButton(CENTER_IMAGE, this), numberSevenButton(CENTER_IMAGE, this), numberEightButton(CENTER_IMAGE, this), numberNightButton(CENTER_IMAGE, this), numberZeroButton(CENTER_IMAGE, this), confirmButton(CONFIRM_IMAGE, this), deleteButton(DELETE_IMAGE, this), lineEditor(this), parent(_parent), KTVDialog(_parent) { QPalette palette; QImage inputboxImage(INPUT_BOX_IMAGE); palette.setBrush(lineEditor.backgroundRole(),QBrush(inputboxImage)); lineEditor.setPalette(palette); lineEditor.setGeometry(40, 50, inputboxImage.width(), inputboxImage.height()); QFont font; font.setPointSize(15); font.setBold(true); constructButton(&numberOneButton, font, QPoint(40, 120), "1"); constructButton(&numberTwoButton, font, QPoint(161, 120), "2"); constructButton(&numberThreeButton, font, QPoint(282, 120), "3"); constructButton(&numberFourButton, font, QPoint(40, 183), "4"); constructButton(&numberFiveButton, font, QPoint(161, 183), "5"); constructButton(&numberSixButton, font, QPoint(282, 183), "6"); constructButton(&numberSevenButton, font, QPoint(40, 246), "7"); constructButton(&numberEightButton, font, QPoint(161, 246), "8"); constructButton(&numberNightButton, font, QPoint(282, 246), "9"); constructButton(&numberZeroButton, font, QPoint(161, 309), "0"); deleteButton.setPos(QPoint(40, 309)); confirmButton.setPos(QPoint(282, 309)); setBackgroundImage(BACKGROUND_IMAGE); setupConnection(); } LoginInWidget::~LoginInWidget() { } void LoginInWidget::constructButton(KTVButton *_button, const QFont &_font, const QPoint &_point, const QString &_text) { _button->setPos(_point); /*_button->setFont(_font);*/ _button->setText(_text); } void LoginInWidget::setupConnection() { connect(&numberOneButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberTwoButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberThreeButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberFourButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberFiveButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberSixButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberSevenButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberEightButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberNightButton, SIGNAL(click()), this, SLOT(setText())); connect(&numberZeroButton, SIGNAL(click()), this, SLOT(setText())); connect(&deleteButton, SIGNAL(click()), this, SLOT(deleteCharacter())); connect(&confirmButton, SIGNAL(click()), this, SLOT(login())); } void LoginInWidget::setText() { KTVButton* button = (KTVButton*)this->sender(); QString text = lineEditor.text(); lineEditor.setText(text + button->getText()); } void LoginInWidget::login() { parent->hide(); UserInfo::Instance()->setUserID(DbUtil::Login(lineEditor.text())); } void LoginInWidget::deleteCharacter() { QString text = lineEditor.text(); text = text.left(text.length() - 1); lineEditor.setText(text); }
[ "liulanggoukk@gmail.com" ]
liulanggoukk@gmail.com
3b9a2a1ed0badfa72364065e3012224a71c1ae36
45154dfe316699b375ee5f4a5527296378af9d78
/src/orm/templates/php/laravel/LaravelControllerMethodStoreTemplate.h
bb349944f780ac270ff34d182467743fa5c7fd12
[ "MIT" ]
permissive
victormwenda/dbcrudgen-cpp
163d9c7da966dd84f5fc71810151c1973e5e60c5
0447c50bd8560e1865f0aa3ef53c7d0ffe07d435
refs/heads/master
2023-05-03T10:44:35.668694
2023-04-20T13:29:06
2023-04-20T13:29:51
92,381,769
0
2
null
null
null
null
UTF-8
C++
false
false
788
h
// // Created by victor on 3/19/20. // #ifndef DBCRUDGEN_CPP_LARAVELCONTROLLERMETHODSTORETEMPLATE_H #define DBCRUDGEN_CPP_LARAVELCONTROLLERMETHODSTORETEMPLATE_H #include "../../FileSourceCodeTemplate.h" #include "../../../codegen/Languages.h" #include "LaravelTemplateFiles.h" namespace dbcrudgen { namespace orm { class LaravelControllerMethodStoreTemplate : public FileSourceCodeTemplate { protected: std::string getSourceFile() override { return std::string{LaravelTemplateFiles::METHOD_CONTROLLER_STORE}; } private: std::string getLanguage() override { return std::string{Languages::PHP}; } }; } } #endif //DBCRUDGEN_CPP_LARAVELCONTROLLERMETHODSTORETEMPLATE_H
[ "vmwenda.vm@gmail.com" ]
vmwenda.vm@gmail.com
c4932ea016fa5c60582bd42f83d641e3737ede30
9a6821064a75ddbdde6fd9867bceb6b9f8fc9a63
/coterie/src/coterie/EllipsoidSolver.cpp
afcdb88919edc57e9c1be780acd78bcba20687d5
[]
no_license
a-price/coterie
9db2ed25f6a41cb63efc5198f23367abe0dd2e4d
e3b88fa174f8524b09f27110a4ce7c37b7d449a2
refs/heads/master
2023-01-23T02:07:02.894213
2020-11-07T09:01:55
2020-11-07T09:01:55
219,613,062
0
0
null
null
null
null
UTF-8
C++
false
false
5,249
cpp
/** * \file EllipsoidSolver.cpp * \brief * * \author Andrew Price * \date 2017-9-10 * * \copyright * * Copyright (c) 2017, Georgia Tech Research Corporation * All rights reserved. * * This file is provided under the following "BSD-style" License: * 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. * 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 "coterie/EllipsoidSolver.h" #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // Disallow NumPy APIs older than 1.7 #include <Python.h> #include <numpy/arrayobject.h> namespace coterie { // NB: you have to call import_array() or PyArray_SimpleNewFromData will segfault void init_numpy() { import_array1(); } class EllipsoidSolver::EllipsoidSolverImpl { public: const std::string moduleName = "coterie.ellipsoids"; const std::string functionName = "ellipsoid_contains"; PyObject *pModuleName; PyObject *pModule, *pFunc; PyObject *pArgs, *pValue; EllipsoidSolverImpl() : pArgs(nullptr), pValue(nullptr) { Py_Initialize(); init_numpy(); pModuleName = PyUnicode_FromString(moduleName.c_str()); pModule = PyImport_Import(pModuleName); Py_DECREF(pModuleName); if (pModule) { pFunc = PyObject_GetAttrString(pModule, functionName.c_str()); /* pFunc is a new reference */ if (!(pFunc && PyCallable_Check(pFunc))) { if (PyErr_Occurred()) PyErr_Print(); throw std::runtime_error("Cannot find Python function " + functionName); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); const char* envROSPath = getenv("PYTHONPATH"); throw std::runtime_error("Failed to load Python module " + moduleName + " " + std::string(envROSPath)); } } ~EllipsoidSolverImpl() { Py_Finalize(); } bool contains(const Eigen::VectorXd& c1, const Eigen::MatrixXd& Q1, const Eigen::VectorXd& c2, const Eigen::MatrixXd& Q2) { const int dim = static_cast<int>(c1.size()); const int ND{ 2 }; npy_intp c_dims[2]{dim, 1}; npy_intp Q_dims[2]{dim, dim}; // Do we need to worry about row vs column storage order? The matrices are symmetric... PyArrayObject *np_arg_c1, *np_arg_Q1, *np_arg_c2, *np_arg_Q2; np_arg_c1 = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, c_dims, NPY_DOUBLE, const_cast<void*>(reinterpret_cast<const void*>(c1.data())))); np_arg_Q1 = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, Q_dims, NPY_DOUBLE, const_cast<void*>(reinterpret_cast<const void*>(Q1.data())))); np_arg_c2 = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, c_dims, NPY_DOUBLE, const_cast<void*>(reinterpret_cast<const void*>(c2.data())))); np_arg_Q2 = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, Q_dims, NPY_DOUBLE, const_cast<void*>(reinterpret_cast<const void*>(Q2.data())))); pArgs = PyTuple_New(4); PyTuple_SetItem(pArgs, 0, reinterpret_cast<PyObject*>(np_arg_c1)); PyTuple_SetItem(pArgs, 1, reinterpret_cast<PyObject*>(np_arg_Q1)); PyTuple_SetItem(pArgs, 2, reinterpret_cast<PyObject*>(np_arg_c2)); PyTuple_SetItem(pArgs, 3, reinterpret_cast<PyObject*>(np_arg_Q2)); pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { bool res = static_cast<bool>(PyObject_IsTrue(pValue)); Py_DECREF(pValue); return res; } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); throw std::runtime_error("Python call for ellipsoid containment failed."); } } }; EllipsoidSolver::EllipsoidSolver() { impl = std::make_unique<EllipsoidSolverImpl>(); } EllipsoidSolver::~EllipsoidSolver() = default; bool EllipsoidSolver::contains(const Eigen::VectorXd& c1, const Eigen::MatrixXd& Q1, const Eigen::VectorXd& c2, const Eigen::MatrixXd& Q2) { assert(c1.size() == c2.size()); assert(c1.size() == Q1.rows() && c1.size() == Q1.cols()); assert(c2.size() == Q2.rows() && c2.size() == Q2.cols()); if (c1 == c2 && Q1 == Q2) { return true; } return impl->contains(c1, Q1, c2, Q2); } } // namespace coterie
[ "arprice@gatech.edu" ]
arprice@gatech.edu
ea8d7c7759331a4d6ea7f7e003a6a939be9cb8fd
ebe422519443dbe9c4acd3c7fd527d05cf444c59
/increment_problem.cpp
928938076cfdb122b6f8a3444a9d8d471ea7b1e6
[]
no_license
SaiSudhaV/coding_platforms
2eba22d72fdc490a65e71daca41bb3d71b5d0a7b
44d0f80104d0ab04ef93716f058b4b567759a699
refs/heads/master
2023-06-19T18:05:37.876791
2021-07-15T18:02:19
2021-07-15T18:02:19
355,178,342
0
0
null
null
null
null
UTF-8
C++
false
false
452
cpp
vector<int> Solution::solve(vector<int> &A) { unordered_map<int, set<int>> temp; vector<int> res; int n = A.size(), i = 0; for(; i < n; i++){ if(temp.find(A[i]) != temp.end()){ int idx = *(temp[A[i]].begin()); res[idx]++; temp[A[i]].erase(temp[A[i]].begin()); temp[res[idx]].insert(idx); } res.push_back(A[i]); temp[A[i]].insert(i); } return res; }
[ "saisudhavadisina@gmail.com" ]
saisudhavadisina@gmail.com
e8c738a035e57e082cb74f9a1d9c63e9956a103e
e40d5e30fb375589aa22efe2a4258f45cee99ce8
/src/render/meshSystem/meshSystem.h
ca75e89b12a7cc193dc13f4865ce26331089e696
[]
no_license
mironside/rabid
dfc0868a43b01fd4453981f50739af092e9889fe
70c7d4c27202b518a9412ae8a9a29ab6097c39c0
refs/heads/master
2016-09-10T11:23:09.351459
2013-04-23T16:15:55
2013-04-23T16:15:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
562
h
/** @file meshSystem.h @author Christopher Olsen @date Mon Dec 6 02:36:24 2004 */ #ifndef __MESH_SYSTEM__ #define __MESH_SYSTEM__ #include "public/meshSystem.h" #include "libsn/hashMap.h" class Mesh; class DynamicMeshInstance; class MeshSystem : public IMeshSystem { protected: snSHashMap<Mesh*> m_meshMap; Mesh* m_defaultMesh; public: MeshSystem(); virtual ~MeshSystem(); void Initialize(); void Release(); IMesh* GetMesh(const char* meshName); void FreeMesh(IMesh* mesh); IMesh* DefaultMesh(); void Print(); }; #endif
[ "chrisaolsen@gmail.com" ]
chrisaolsen@gmail.com
e54b5c10066d6bc72e4a2d5f153f3bb39ee4cc9e
f926639250ab2f47d1b35b012c143f1127cc4965
/legacy/platform/mt6755/metadata/templateRequest/TemplateRequest.cpp
8b56f27a2d0ef3f6bb5c85fd1d9a3110e58e4ae5
[]
no_license
cllanjim/stereoCam
4c5b8f18808c96581ccd14be2593d41de9e0cf35
e2df856ed1a2c45f6ab8dd52b67d7eae824174cf
refs/heads/master
2020-03-17T11:26:49.570352
2017-03-14T08:48:08
2017-03-14T08:48:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,444
cpp
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ #define LOG_TAG "MtkCam/TemplateRequest" // #include "MyUtils.h" #include <hardware/camera3.h> // #include <dlfcn.h> // converter #include <mtkcam/metadata/client/TagMap.h> #include <mtkcam/metadata/IMetadataTagSet.h> #include <mtkcam/metadata/IMetadataConverter.h> #include <mtkcam/metadata/IMetadataProvider.h> #include <system/camera_metadata.h> #include <mtkcam/Log.h> #include <mtkcam/common.h> #include <mtkcam/metadata/mtk_metadata_types.h> #include <mtkcam/hal/IHalSensor.h> // /****************************************************************************** * ******************************************************************************/ #define MY_LOGV(fmt, arg...) CAM_LOGV("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGD(fmt, arg...) CAM_LOGD("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGI(fmt, arg...) CAM_LOGI("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGW(fmt, arg...) CAM_LOGW("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGE(fmt, arg...) CAM_LOGE("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGA(fmt, arg...) CAM_LOGA("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGF(fmt, arg...) CAM_LOGF("[%s] " fmt, __FUNCTION__, ##arg) // #define MY_LOGV_IF(cond, ...) do { if ( (cond) ) { MY_LOGV(__VA_ARGS__); } }while(0) #define MY_LOGD_IF(cond, ...) do { if ( (cond) ) { MY_LOGD(__VA_ARGS__); } }while(0) #define MY_LOGI_IF(cond, ...) do { if ( (cond) ) { MY_LOGI(__VA_ARGS__); } }while(0) #define MY_LOGW_IF(cond, ...) do { if ( (cond) ) { MY_LOGW(__VA_ARGS__); } }while(0) #define MY_LOGE_IF(cond, ...) do { if ( (cond) ) { MY_LOGE(__VA_ARGS__); } }while(0) #define MY_LOGA_IF(cond, ...) do { if ( (cond) ) { MY_LOGA(__VA_ARGS__); } }while(0) #define MY_LOGF_IF(cond, ...) do { if ( (cond) ) { MY_LOGF(__VA_ARGS__); } }while(0) /****************************************************************************** * ******************************************************************************/ status_t TemplateRequest:: impConstructRequestMetadata_by_SymbolName( String8 const& s8Symbol, IMetadata& metadata, int const requestType ) { typedef status_t (*PFN_T)( IMetadata & metadata, int const requestType ); // PFN_T pfn = (PFN_T)::dlsym(RTLD_DEFAULT, s8Symbol.string()); if ( ! pfn ) { MY_LOGW("%s not found", s8Symbol.string()); return NAME_NOT_FOUND; } // status_t const status = pfn(metadata, requestType); MY_LOGW_IF(OK != status, "%s returns status[%s(%d)]", s8Symbol.string(), ::strerror(-status), -status); // return status; } /****************************************************************************** * ******************************************************************************/ status_t TemplateRequest:: impConstructRequestMetadata( IMetadata& metadata, int const requestType ) { status_t status = OK; // { #if 1 String8 const s8Symbol_Sensor = String8::format("%s_DEVICE_%s", PREFIX_FUNCTION_REQUEST_METADATA, mInfo.getSensorDrvName()); status = impConstructRequestMetadata_by_SymbolName(s8Symbol_Sensor, metadata, requestType); if ( OK == status ) { goto lbDevice; } #endif // String8 const s8Symbol_Common = String8::format("%s_DEVICE_%s", PREFIX_FUNCTION_REQUEST_METADATA, "COMMON"); status = impConstructRequestMetadata_by_SymbolName(s8Symbol_Common, metadata, requestType); if ( OK == status ) { goto lbDevice; } } // lbDevice: { #if 1 String8 const s8Symbol_Sensor = String8::format("%s_PROJECT_%s", PREFIX_FUNCTION_REQUEST_METADATA, mInfo.getSensorDrvName()); status = impConstructRequestMetadata_by_SymbolName(s8Symbol_Sensor, metadata, requestType); if ( OK == status ) { return OK; } #endif // String8 const s8Symbol_Common = String8::format("%s_PROJECT_%s", PREFIX_FUNCTION_REQUEST_METADATA, "COMMON"); status = impConstructRequestMetadata_by_SymbolName(s8Symbol_Common, metadata, requestType); if ( OK == status ) { return OK; } } // return OK; } /****************************************************************************** * ******************************************************************************/ static bool setTagInfo(IMetadataTagSet &rtagInfo) { #define _IMP_SECTION_INFO_(...) #undef _IMP_TAG_INFO_ #define _IMP_TAG_INFO_(_tag_, _type_, _name_) \ rtagInfo.addTag(_tag_, _name_, Type2TypeEnum<_type_>::typeEnum); #include <mtkcam/metadata/client/mtk_metadata_tag_info.inl> #undef _IMP_TAG_INFO_ #undef _IMP_TAGCONVERT_ #define _IMP_TAGCONVERT_(_android_tag_, _mtk_tag_) \ rtagInfo.addTagMap(_android_tag_, _mtk_tag_); #if (PLATFORM_SDK_VERSION >= 21) ADD_ALL_MEMBERS; #endif #undef _IMP_TAGCONVERT_ return MTRUE; } /****************************************************************************** * ******************************************************************************/ status_t TemplateRequest:: constructRequestMetadata( int const requestType, camera_metadata*& rpMetadata, IMetadata& rMtkMetadata ) { MY_LOGD("constructRequestMetadata"); status_t status = OK; //-----(1)-----// //get static informtation from customization (with camera_metadata format) //calculate its entry count and data count if ( OK != (status = impConstructRequestMetadata(rMtkMetadata, requestType)) ) { MY_LOGE("Unable evaluate the size for camera static info - status[%s(%d)]\n", ::strerror(-status), -status); return status; } MY_LOGD("Allocating %d entries from customization", rMtkMetadata.count()); //calculate its entry count and data count // init converter IMetadataTagSet tagInfo; setTagInfo(tagInfo); sp<IMetadataConverter> pConverter = IMetadataConverter::createInstance(tagInfo); size_t entryCount = 0; size_t dataCount = 0; MBOOL ret = pConverter->get_data_count(rMtkMetadata, entryCount, dataCount); if ( ret != OK ) { MY_LOGE("get Imetadata count error\n"); return UNKNOWN_ERROR; } MY_LOGD("Allocating %d entries, %d extra bytes from HAL modules", entryCount, dataCount); //-----(2)-----// // overwrite updateData(rMtkMetadata); //-----(3)-----// // convert to android metadata pConverter->convert(rMtkMetadata, rpMetadata); ::sort_camera_metadata(rpMetadata); return status; } /****************************************************************************** * ******************************************************************************/ void TemplateRequest:: updateData(IMetadata &rMetadata) { sp<IMetadataProvider> pMetadataProvider = IMetadataProvider::create(mInfo.getDeviceId()); IMetadata static_meta = pMetadataProvider->geMtktStaticCharacteristics(); { MRect cropRegion; IMetadata::IEntry active_array_entry = static_meta.entryFor(MTK_SENSOR_INFO_ACTIVE_ARRAY_REGION); if( !active_array_entry.isEmpty() ) { cropRegion = active_array_entry.itemAt(0, Type2Type<MRect>()); cropRegion.p.x=0; cropRegion.p.y=0; IMetadata::IEntry entry(MTK_SCALER_CROP_REGION); entry.push_back(cropRegion, Type2Type< MRect >()); rMetadata.update(MTK_SCALER_CROP_REGION, entry); } } } /****************************************************************************** * ******************************************************************************/ status_t TemplateRequest:: onCreate(int iOpenId) { MY_LOGD("+"); // int32_t sensorType = IHalSensorList::get()->queryType(iOpenId); const char* sensorDrvName = IHalSensorList::get()->queryDriverName(iOpenId); mInfo = Info(iOpenId, sensorType, sensorDrvName); // Standard template types for (int type = CAMERA3_TEMPLATE_PREVIEW; type < CAMERA3_TEMPLATE_COUNT; type++) { camera_metadata* metadata = NULL; IMetadata mtkMetadata; status_t status = constructRequestMetadata(type, metadata, mtkMetadata); if ( OK != status || NULL == metadata || mtkMetadata.isEmpty()) { MY_LOGE("constructRequestMetadata - type:%#x metadata:%p status[%s(%d)]", type, metadata, ::strerror(-status), -status); return status; } // mMapRequestTemplate.add(type, metadata); mMapRequestTemplateMetadata.add(type, mtkMetadata); } #if 0 // vendor-defined request templates for (int type = CAMERA3_VENDOR_TEMPLATE_START; type < CAMERA3_VENDOR_TEMPLATE_COUNT; type++) { camera_metadata* metadata = NULL; status = constructRequestMetadata(type, metadata); if ( OK != status || NULL == metadata ) { MY_LOGE("constructRequestMetadata - type:%#x metadata:%p status[%s(%d)]", type, metadata, ::strerror(-status), -status); return status; } // MapRequestTemplate.add(type, metadata); } #endif return OK; } /****************************************************************************** * ******************************************************************************/ camera_metadata const* TemplateRequest:: getData(int requestType) { return mMapRequestTemplate.valueFor(requestType); } /****************************************************************************** * ******************************************************************************/ IMetadata const& TemplateRequest:: getMtkData(int requestType) { return mMapRequestTemplateMetadata.valueFor(requestType); } /****************************************************************************** * ******************************************************************************/ ITemplateRequest* ITemplateRequest:: getInstance(int iOpenId) { TemplateRequest* p = new TemplateRequest(); if(p != NULL) { p->onCreate(iOpenId); } return p; }
[ "Bret_liu@tw.shuttle.com" ]
Bret_liu@tw.shuttle.com
db4153a34fc3be0253c2390652fc3ee51e1b7c18
31f5e36d5a5ca0a40c091d164b01fbca98cb665b
/SCore/SCore/AutoCriticalSection.h
f23c9a3342f61eec7aa0359dac8e90e1d9b94e9f
[]
no_license
Pascal1000/SilkroadProject
150b83c913cba718a7367052bad1fda276ae1e92
c878a0604b23cec2f124b1555e1d267ee4d029fe
refs/heads/master
2020-03-25T12:25:18.376058
2018-08-06T19:55:04
2018-08-06T19:55:04
143,775,332
0
0
null
2018-08-06T19:46:04
2018-08-06T19:46:04
null
UTF-8
C++
false
false
569
h
#pragma once #define WIN32_LEAN_AND_MEAN #include <Windows.h> namespace SCore { namespace Native { class AutoCriticalSection { private: CRITICAL_SECTION m_cs; public: AutoCriticalSection(); AutoCriticalSection(DWORD dwSpinCount); ~AutoCriticalSection(); void Lock(); bool TryLock(); void Unlock(); }; class AutoLockScope { private: AutoCriticalSection *m_pAcs; public: AutoLockScope(AutoCriticalSection *pAcs) : m_pAcs(pAcs) { m_pAcs->Lock(); } ~AutoLockScope() { m_pAcs->Unlock(); } }; } }
[ "mail@sezercantanisman.com.tr" ]
mail@sezercantanisman.com.tr
e31a4d5c4f9ad7fcff97353087bab3ce7ee292ed
bccf73a4a13918940a7b33832afdc7eccf57f535
/Project2-2/Project1/project2_q02.cpp
c0db58236dba4649da19eca650feedd3ec3a76d4
[]
no_license
LeeWooil/C_plusplus_study
a4fb8e9aebc637c6ae6d436231164df3ec6853a8
744388c23939dc2239731b1660626caa80e93a20
refs/heads/master
2023-07-24T01:04:49.142695
2023-07-08T07:39:58
2023-07-08T07:39:58
300,300,214
0
0
null
null
null
null
UHC
C++
false
false
489
cpp
/************************************************************** * 빌더 패턴을 사용하는 애플리케이션 파일 * **************************************************************/ #include "director.h" int main() { // 여행 유형 선택 int type = 1; while (type >= 1 && type <= 3) { cout << "Enter the type of vacation(1, 2, 3):"; cin >> type; // 여행 계획 확인 Director::book(type); } return 0; }
[ "lwi2765@khu.ac.kr" ]
lwi2765@khu.ac.kr
058f18a06fbb63002229d8b498e1a8e4b6dd47f8
ef883f8c97288411e50832be8a2470241b0fea30
/host/src/core/kernelentry.cpp
28ad354f2ac146945ebe8a0934a336f963f05a91
[]
no_license
rcn-ee/ti-opencl
d11e9db52f4f348c65838832720cdf2358667abb
b1dfed9af21a1236380b9d643c432e4f0c619fce
refs/heads/master
2021-01-19T02:32:04.415153
2019-12-23T19:32:41
2019-12-23T19:32:41
37,145,122
9
4
null
null
null
null
UTF-8
C++
false
false
2,109
cpp
/* * Copyright (c) 2017, Texas Instruments Incorporated - http://www.ti.com/ * 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 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 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. */ /** * \file core/kernelentry.cpp * \brief KernelEntry */ #include "kernelentry.h" namespace Coal { KernelEntry::KernelEntry(const std::string& name, cl_uint index) { this->name = name; this->index = index; } cl_uint KernelEntry::addArg(unsigned short vec_dim, Kernel::Arg::File file, Kernel::Arg::Kind kind, bool is_subword_int_uns) { Kernel::Arg arg(vec_dim, file, kind, is_subword_int_uns); args.push_back(arg); return CL_SUCCESS; } }
[ "yuanzhao@ti.com" ]
yuanzhao@ti.com
e18bb9e9a8519db74bf25e1e088e5c91ad82109b
690f166a0cd5c13966cc46c20ef467f66c672b03
/AP-12 on ATMEAGA 16/main/main.ino
570c8d339e2efb881b204c187f99e22ec62ef93f
[]
no_license
panomZA1/arduino
4aa302b714f9ccdb5c4b9acd9994cab54eed8833
d4c79e3106352c5adcb502a61c1d016474d6f1c8
refs/heads/master
2022-11-21T21:28:14.266625
2020-07-22T09:11:34
2020-07-22T09:11:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,081
ino
#include <avr/wdt.h> /////////////////////////////////////////////////////////////////////////// #include <IRremote.h> int RECV_PIN = 23; IRrecv irrecv(RECV_PIN); decode_results results; #define OUTPUT_COUNT 5 long remote_key[] = {0xDF40BF, 0xDF609F, 0xDF48B7, 0xDF50AF, 0xDF708F}; const byte outputPins[OUTPUT_COUNT] = {0, 1, 2, 3, 4}; bool status1[5] = {0, 0, 0, 0, 0}; struct keypad { boolean state; }; keypad output[OUTPUT_COUNT]; /////////////////////////////////////////////////////////////////////////// // input pins const short int Bpow = 20; // power button input pin const short int Bspeed = 21; // speed input pin const short int Btimer = 22; // Timer button input pin //output pins const short int POW = 10; const short int s1 = 24; // speeed output pin const short int s2 = 25; // speeed output pin const short int s3 = 26; // speeed output pin const short int s4 = 27; // speeed output pin const short int AUTO = 28; const short int timerled = 4; const short int h1 = 3; const short int h2 = 2; const short int h4 = 1; const short int h8 = 0; const short int dim = 13; const short int wifi_L = 29; const short int filtor = 30; const short int BUZ = 12; // buzzer output pin const short int M1 = 19; // motor output pin const short int M2 = 18; // motor output pin const short int M3 = 17; // motor output pin const short int M4 = 16; // motor output pin ////////////////////////////////////////////////////////////////////////// // state variables //////////////////////power////////////////////// bool Bp = 1; //power button state bool Lp = 1; //previous power button state byte stateP = 1; //power output state bool powercount = 0; // count if the power button is pushed unsigned int powert0 = 0; /////////////////////speed//////////////////// bool Bs = 1; // speed input state bool Ls = 1; // previous speed input state bool speedcount = 0; // check if button is pressed in the last loop byte index = 0; // case counter unsigned int speedt0 = 0; ////////////////////Timer//////////////////// bool Bt = 1; bool Lt = 1; byte Settime = 0; unsigned int timer0; unsigned int timedown = 0; // remaining time unsigned int timetrig = 0; unsigned int runtime = 0; /////////////////Auto//////////////////// bool Ba = 1; bool La = 1; bool stateA = 0; //auto state bool autocount = 0; unsigned int autotime = 0; unsigned int auto0 = 0; ///////////////delays//////////////////// unsigned int buttondelay = 200; // delay between each button press in ms unsigned int currenttime = 0; //////////////dust sensor/////////////// const short int measurePin = 31; const short int ledPower = 11; const short int numaverage = 100; ///number of values for taking average unsigned int count; unsigned int dust[numaverage]; unsigned int averagedust = 0; ///////////////beep/////////////////// bool songindex = 0; bool beepvarB = 0; bool beepvarS = 0; bool beepstarted = 0; bool beepstartedS = 0; byte beeppowervar = 0; unsigned int beeptime = 0; unsigned int beeptimeS = 0; int play = 0; int soundtime = 0; //unsigned int bwf = 0; byte bnum = 0; ///////////////Bright//////////////// byte bright7 = 7; byte brightdim = 30; bool ck = 0; bool Rd = 1; // speed input state bool Ld = 1; // previous speed input state bool dimcount = 0; // case counter unsigned int Rdim0 = 0; ////////////////////////////////////VOID///////////////////////////////////////////////// ///////////////////////////////////SETUP///////////////////////////////////////////////// void setup() { Serial.begin(9600); tm1637_init_pin_for_sent_I2C(); irrecv.enableIRIn(); // Start the receiver // wdt_enable(WDTO_120MS); // Watch dog function start int inputpins[3] = {Bpow, Bspeed, Btimer}; int ledpins[14] ={ POW, s1, s2, s3, s4, AUTO, dim, timerled, h1, h2, h4, h8,wifi_L,filtor}; int outputpins[6] = { M1, M2, M3, M4, BUZ,ledPower }; for (int j = 0; j < sizeof(inputpins) / sizeof(1); j++) { pinMode(inputpins[j], INPUT); } for (int j = 0; j < sizeof(ledpins) / sizeof(1); j++) { pinMode(ledpins[j], OUTPUT); } for (int j = 0; j < sizeof(outputpins) / sizeof(1); j++) { pinMode(outputpins[j], OUTPUT); } digitalWrite(outputpins[6],0); beepvarS = 1; clearspeed(); // Serial.println("Bord Reset"); } //////////////////////////////////////VOID//////////////////////////////////// //////////////////////////////////////LOOP//////////////////////////////////// int HHH=0; void loop() { currenttime = millis(); delay(300); HHH++; if(HHH>9){HHH=0;} // Dimmer(); // beep(); // statebutton(); // Remote(); Display(); // sensor_dust(); // powerset(); // speedset(); // TIMER(); // Auto(); // wdt_reset(); // Watch dog reset }
[ "za.keuanten@gmail.com" ]
za.keuanten@gmail.com
f9e50c64facba51ef9f34c512eaed8e6df94049d
99b5c119a350cbd1acb61e25c917afe2a8bd6187
/cobol/copy/CPTENSUNAMETBL.INC
540f42c6f7445cc08b654ff3b6db3cf6297174a7
[]
no_license
miyucy/jma-receipt
917c88b17cff4d7bb6f81604ff98b186174ed3d4
7d4659852d1a019e6f133df41fd1f3f5616490ad
refs/heads/master
2020-03-21T03:01:07.640412
2019-03-27T08:21:18
2019-03-27T08:21:18
138,032,734
0
0
null
2018-06-20T12:54:33
2018-06-20T12:54:33
null
EUC-JP
C++
false
false
23,439
inc
******************************************************************* * Project code name "ORCA" * 日医標準レセプトソフト(JMA standard receipt software) * Copyright(C) 2002 JMA (Japan Medical Association) * * This program is part of "JMA standard receipt software". * * This program is distributed in the hope that it will be useful * for further advancement in medical care, according to JMA Open * Source License, but WITHOUT ANY WARRANTY. * Everyone is granted permission to use, copy, modify and * redistribute this program, but only under the conditions described * in the JMA Open Source License. You should have received a copy of * this license along with this program. If not, stop using this * program and contact JMA, 2-28-16 Honkomagome, Bunkyo-ku, Tokyo, * 113-8621, Japan. ******************************************************************** *----------------------------------------------------------------* * 点数テーブル項目名称テーブル COPY (CPTENSUNAMETBL.INC) *----------------------------------------------------------------* ***************************************************************** * コピー句修正履歴 * Maj/Min/Rev 修正者 日付 内容 ***************************************************************** * 01 TBL-TENSU-NAME-AREA. 03 FILLER PIC X(41) VALUE "001 srycd 診療行為コード ". 03 FILLER PIC X(41) VALUE "002 yukostymd 有効開始日 ". 03 FILLER PIC X(41) VALUE "003 yukoedymd 有効終了日 ". 03 FILLER PIC X(41) VALUE "004 srykbn 診療行為区分 ". 03 FILLER PIC X(41) VALUE "005 srysyukbn 診療種別区分 ". 03 FILLER PIC X(41) VALUE "006 yukoketa 漢字名称桁数 ". 03 FILLER PIC X(41) VALUE "007 name 漢字名称 ". 03 FILLER PIC X(41) VALUE "008 kanayukoketa カナ名称桁数 ". 03 FILLER PIC X(41) VALUE "009 kananame カナ名称 ". 03 FILLER PIC X(41) VALUE "010 formalyukoketa 正式名称桁数 ". * 03 FILLER PIC X(41) VALUE "011 formalname 正式名称 ". 03 FILLER PIC X(41) VALUE "012 tensikibetu 点数識別 ". 03 FILLER PIC X(41) VALUE "013 ten 点数/金額 ". 03 FILLER PIC X(41) VALUE "014 tanicd 単位コード ". 03 FILLER PIC X(41) VALUE "015 tanimojisu 単位名称桁数 ". 03 FILLER PIC X(41) VALUE "016 taniname 単位名称 ". 03 FILLER PIC X(41) VALUE "017 datakbn データ区分 ". 03 FILLER PIC X(41) VALUE "018 hkntekkbn 保険適用区分 ". 03 FILLER PIC X(41) VALUE "019 nyugaitekkbn 入外適用区分 ". 03 FILLER PIC X(41) VALUE "020 routekkbn 後期高齢者適用区分". * 03 FILLER PIC X(41) VALUE "021 hospsrykbn 病院・診療所区分 ". 03 FILLER PIC X(41) VALUE "022 osinkbn 往診区分(未使用)". 03 FILLER PIC X(41) VALUE "023 houksnkbn 包括対象検査 ". 03 FILLER PIC X(41) VALUE "024 byokanrenkbn 傷病名関連区分 ". 03 FILLER PIC X(41) VALUE "025 sdokanryo 医学管理料 ". 03 FILLER PIC X(41) VALUE "026 jituday 実日数 ". 03 FILLER PIC X(41) VALUE "027 daycnt 日数・回数 ". 03 FILLER PIC X(41) VALUE "028 ykzknrkbn 医薬品関連区分 ". 03 FILLER PIC X(41) VALUE "029 kzmcompsikibetu きざみ値計算識別 ". 03 FILLER PIC X(41) VALUE "030 kzmkgn きざみ値下限値 ". * 03 FILLER PIC X(41) VALUE "031 kzmjgn きざみ値上限値 ". 03 FILLER PIC X(41) VALUE "032 kzm きざみ値 ". 03 FILLER PIC X(41) VALUE "033 kzmten きざみ点数 ". 03 FILLER PIC X(41) VALUE "034 kzmerr きざみ値エラー処理". 03 FILLER PIC X(41) VALUE "035 jgncnt 上限回数1月 ". 03 FILLER PIC X(41) VALUE "036 jgncnt1d 上限回数1日 ". 03 FILLER PIC X(41) VALUE "037 jgncnt1w 上限回数1週 ". 03 FILLER PIC X(41) VALUE "038 jgncntetcm 上限回数他月数 ". 03 FILLER PIC X(41) VALUE "039 jgncntetc 上限回数他月 ". 03 FILLER PIC X(41) VALUE "040 jgncnterr 上限回数エラー処理". * 03 FILLER PIC X(41) VALUE "041 chuksncd 注加算コード ". 03 FILLER PIC X(41) VALUE "042 chuksntsuban 注加算通番 ". 03 FILLER PIC X(41) VALUE "043 tsusokuage 通則年齢 ". 03 FILLER PIC X(41) VALUE "044 kgnage 下限年齢 ". 03 FILLER PIC X(41) VALUE "045 jgnage 上限年齢 ". 03 FILLER PIC X(41) VALUE "046 timeksnkbn 時間加算区分 ". 03 FILLER PIC X(41) VALUE "047 kijunteigenkbn 基準適合区分 ". 03 FILLER PIC X(41) VALUE "048 kijunteigencd 基準適合施設基準 ". 03 FILLER PIC X(41) VALUE "049 laserksn 処置乳幼児加算区分". 03 FILLER PIC X(41) VALUE "050 chpmesuksn 極低出生体重児加算". * 03 FILLER PIC X(41) VALUE "051 micmesuksn 入院基本料等減算 ". 03 FILLER PIC X(41) VALUE "052 donorkbn ドナー分集計区分 ". 03 FILLER PIC X(41) VALUE "053 knsjiskbn 検査等実施判断区分". 03 FILLER PIC X(41) VALUE "054 knsjisgrpkbn 検査等実施判断G ". 03 FILLER PIC X(41) VALUE "055 teigenkbn 逓減対象区分 ". 03 FILLER PIC X(41) VALUE "056 sekizuisokutei 脊髄誘発電位測定 ". 03 FILLER PIC X(41) VALUE "057 keibujyutu 頸部郭清術併施加算". 03 FILLER PIC X(41) VALUE "058 autohougo 自動縫合器加算区分". 03 FILLER PIC X(41) VALUE "059 gaikanrikbn 外来管理加算区分 ". 03 FILLER PIC X(41) VALUE "060 tusokugaikbn 通則加算所定点数 ". * 03 FILLER PIC X(41) VALUE "061 hokatuteigenkbn 包括逓減区分 ". 03 FILLER PIC X(41) VALUE "062 chpnaisiksn 超音波内視鏡加算 ". 03 FILLER PIC X(41) VALUE "063 autofungo 自動吻合器加算区分". 03 FILLER PIC X(41) VALUE "064 chiikiksn 地域加算 ". 03 FILLER PIC X(41) VALUE "065 byosyokbn 病床数区分 ". 03 FILLER PIC X(41) VALUE "066 chpgyokosotiksn 超音波凝固切開措置". 03 FILLER PIC X(41) VALUE "067 shortstayope 短期滞在手術 ". 03 FILLER PIC X(41) VALUE "068 buikbn 部位区分 ". 03 FILLER PIC X(41) VALUE "069 santeirrkkbn 算定履歴区分 ". 03 FILLER PIC X(41) VALUE "070 sstkijuncd1 施設基準1 ". * 03 FILLER PIC X(41) VALUE "071 sstkijuncd2 施設基準2 ". 03 FILLER PIC X(41) VALUE "072 sstkijuncd3 施設基準3 ". 03 FILLER PIC X(41) VALUE "073 sstkijuncd4 施設基準4 ". 03 FILLER PIC X(41) VALUE "074 sstkijuncd5 施設基準5 ". 03 FILLER PIC X(41) VALUE "075 sstkijuncd6 施設基準6 ". 03 FILLER PIC X(41) VALUE "076 sstkijuncd7 施設基準7 ". 03 FILLER PIC X(41) VALUE "077 sstkijuncd8 施設基準8 ". 03 FILLER PIC X(41) VALUE "078 sstkijuncd9 施設基準9 ". 03 FILLER PIC X(41) VALUE "079 sstkijuncd10 施設基準10 ". 03 FILLER PIC X(41) VALUE "080 ageksnkgn1 年齢加算下限年齢1". * 03 FILLER PIC X(41) VALUE "081 ageksnjgn1 年齢加算上限年齢1". 03 FILLER PIC X(41) VALUE "082 ageksnsrycd1 年齢加算コード1 ". 03 FILLER PIC X(41) VALUE "083 ageksnkgn2 年齢加算下限年齢2". 03 FILLER PIC X(41) VALUE "084 ageksnjgn2 年齢加算上限年齢2". 03 FILLER PIC X(41) VALUE "085 ageksnsrycd2 年齢加算コード2 ". 03 FILLER PIC X(41) VALUE "086 ageksnkgn3 年齢加算下限年齢3". 03 FILLER PIC X(41) VALUE "087 ageksnjgn3 年齢加算上限年齢3". 03 FILLER PIC X(41) VALUE "088 ageksnsrycd3 年齢加算コード3 ". 03 FILLER PIC X(41) VALUE "089 ageksnkgn4 年齢加算下限年齢4". 03 FILLER PIC X(41) VALUE "090 ageksnjgn4 年齢加算上限年齢4". * 03 FILLER PIC X(41) VALUE "091 ageksnsrycd4 年齢加算コード4 ". 03 FILLER PIC X(41) VALUE "092 kentaicomment 検体検査コメント ". 03 FILLER PIC X(41) VALUE "093 nyukhnkbn 入院基本料区分 ". 03 FILLER PIC X(41) VALUE "094 nyukhnksnkbn 入院基本料加算区分". 03 FILLER PIC X(41) VALUE "095 kangoksn 看護加算 ". 03 FILLER PIC X(41) VALUE "096 oldtenskb 旧点数識別 ". 03 FILLER PIC X(41) VALUE "097 oldten 旧点数/金額 ". 03 FILLER PIC X(41) VALUE "098 madokukbn 麻薬・毒薬等区分 ". 03 FILLER PIC X(41) VALUE "099 sinkeihakaikbn 神経破壊剤 ". 03 FILLER PIC X(41) VALUE "100 seibutugakukbn 生物学的製剤 ". * 03 FILLER PIC X(41) VALUE "101 zoeizaikbn 造影(補助)剤 ". 03 FILLER PIC X(41) VALUE "102 csyyouryo 注射容量 ". 03 FILLER PIC X(41) VALUE "103 ykzkbn 薬剤区分 ". 03 FILLER PIC X(41) VALUE "104 zaigatakbn 剤形 ". 03 FILLER PIC X(41) VALUE "105 kouhatukbn 後発品 ". 03 FILLER PIC X(41) VALUE "106 longtoyokbn 長期投与(未使用)". 03 FILLER PIC X(41) VALUE "107 meiuseskb 名称使用識別 ". 03 FILLER PIC X(41) VALUE "108 tokukizaiageksnkbn 年齢加算区分 ". 03 FILLER PIC X(41) VALUE "109 sansokbn 酸素等区分 ". 03 FILLER PIC X(41) VALUE "110 tokukizaisbt1 特定器材種別 ". * 03 FILLER PIC X(41) VALUE "111 tokukizaisbt2 上限価格 ". 03 FILLER PIC X(41) VALUE "112 jgnten 上限点数 ". 03 FILLER PIC X(41) VALUE "113 gaitenttlkbn 点数欄集計先・外来". 03 FILLER PIC X(41) VALUE "114 nyutenttlkbn 点数欄集計先・入院". 03 FILLER PIC X(41) VALUE "115 cdkbn_kbn コード表・区分 ". 03 FILLER PIC X(41) VALUE "116 cdkbn_syo コード表・章 ". 03 FILLER PIC X(41) VALUE "117 cdkbn_bu コード表・部 ". 03 FILLER PIC X(41) VALUE "118 cdkbn_kbnnum コード表・区分番号". 03 FILLER PIC X(41) VALUE "119 cdkbn_kbnnum_eda コード表・枝番 ". 03 FILLER PIC X(41) VALUE "120 cdkbn_kouban コード表・項番 ". * 03 FILLER PIC X(41) VALUE "121 kokuchi_kbn 告知通知・区分 ". 03 FILLER PIC X(41) VALUE "122 kokuchi_syo 告知通知・章 ". 03 FILLER PIC X(41) VALUE "123 kokuchi_bu 告知通知・部 ". 03 FILLER PIC X(41) VALUE "124 kokuchi_kbnnum 告知通知・区分番号". 03 FILLER PIC X(41) VALUE "125 kokuchi_kbnnum_eda 告知通知・枝番 ". 03 FILLER PIC X(41) VALUE "126 kokuchi_kouban 告知通知・項番 ". 03 FILLER PIC X(41) VALUE "127 kokujiskbkbn1 告示等識別区分1 ". 03 FILLER PIC X(41) VALUE "128 kokujiskbkbn2 告示等識別区分2 ". 03 FILLER PIC X(41) VALUE "129 namechgkbn 漢字名称変更区分 ". 03 FILLER PIC X(41) VALUE "130 kananamechgkbn カナ名称変更区分 ". * 03 FILLER PIC X(41) VALUE "131 idokanren 異動関連 ". 03 FILLER PIC X(41) VALUE "132 kouhyojyunnum 公表順序番号 ". 03 FILLER PIC X(41) VALUE "133 yakkakjncd 薬価基準コード ". 03 FILLER PIC X(41) VALUE "134 syusaiskb 収戴方式等識別 ". 03 FILLER PIC X(41) VALUE "135 syomeikanren 商品名等関連 ". 03 FILLER PIC X(41) VALUE "136 chgymd 変更年月日 ". 03 FILLER PIC X(41) VALUE "137 haisiymd 廃止年月日 ". 03 FILLER PIC X(41) VALUE "138 keikasochiymd 経過措置年月日 ". 03 FILLER PIC X(41) VALUE "139 termid 端末ID ". 03 FILLER PIC X(41) VALUE "140 opid オペレーターID ". * 03 FILLER PIC X(41) VALUE "141 creymd 作成年月日 ". 03 FILLER PIC X(41) VALUE "142 upymd 更新年月日 ". 03 FILLER PIC X(41) VALUE "143 uphms 更新時間 ". 03 FILLER PIC X(41) VALUE "144 hospnum 医療機関識別番号 ". 03 FILLER PIC X(41) VALUE "145 gazoopesup 画像等手術支援加算". 03 FILLER PIC X(41) VALUE "146 iryokansatukbn 医療観察法対象区分". 03 FILLER PIC X(41) VALUE "147 masuiskbkbn 麻酔識別区分 ". *H24.4追加4つ 03 FILLER PIC X(41) VALUE "148 fukubikunaikbn 副鼻腔内視鏡 ". 03 FILLER PIC X(41) VALUE "149 fukubikukotukbn 副鼻腔骨軟部 ". 03 FILLER PIC X(41) VALUE "150 timemasuikbn 長時間麻酔 ". 03 FILLER PIC X(41) VALUE "151 dpckbn DPC区分 ". *H28.4追加5つ 03 FILLER PIC X(41) VALUE "152 hisinsyumonitorksn 非侵襲的血行動態モ". 03 FILLER PIC X(41) VALUE "153 touketuhozonksn 凍結保存同種組織加". 03 FILLER PIC X(41) VALUE "154 kubunbangou 点数表区分番号 ". 03 FILLER PIC X(41) VALUE "155 rosaikbn 労災算定不可 ". 03 FILLER PIC X(41) VALUE "156 sisiksn 四肢加算(労災) ". *H30.4追加1つ 03 FILLER PIC X(41) VALUE "157 akuseibyoriksn 悪性腫瘍病理組織 ". * 01 TBL-TENSU-NAME-AREA-R REDEFINES TBL-TENSU-NAME-AREA. 03 TBL-TENSU-NAME-OCC OCCURS 157 INDEXED TBL-TNM. 05 TBL-TNM-NUM PIC 9(03). 05 TBL-TNM-FILLER1 PIC X(01). 05 TBL-TNM-CNAME PIC X(18). 05 TBL-TNM-FILLER2 PIC X(01). 05 TBL-TNM-NAME PIC X(18). * 01 TBL-TENSU-NAME-MAX PIC 9(04) VALUE 157.
[ "tosihiko@cvs.orca.med.or.jp" ]
tosihiko@cvs.orca.med.or.jp
1c42aa81a417e10d4098138ae051c707be17282a
22ebcde0f235b60c1c5cff32461f477ac4f72ecf
/QtSrc/xmlpatterns/data/qnodemodel.cpp
91e44995fa95b3ac93b452d91bdd774dfb3ed3a0
[]
no_license
kystyn/ui
13dc1e7c0e01761b0658be101528bea440be70d9
083a011a735f6dc65c271bc92e397c75155ca61f
refs/heads/master
2020-07-29T03:45:08.929517
2020-06-17T23:42:05
2020-06-17T23:42:05
209,656,041
0
0
null
null
null
null
UTF-8
C++
false
false
1,889
cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QUrl> #include "qnamespaceresolver_p.h" #include "qitem_p.h" QT_BEGIN_NAMESPACE QT_END_NAMESPACE
[ "konstantindamaskinskiy@gmail.com" ]
konstantindamaskinskiy@gmail.com
76865d05d64828e946dca5c30f9f167f88acd80f
fe9e5e8b20cce3cc01000474fd4c47a3a82bc42c
/Chatwindow.cpp
92a44a82614a799dc81e2cf0cbda9c6871dca81e
[]
no_license
Bananenkiste/Client
2702f57c90a6d9b28c856ac9038a7e2c9a9ae11d
69a5754be4494fc25fae3706675f85253da6316b
refs/heads/master
2016-09-06T04:52:23.368122
2013-04-14T01:48:48
2013-04-14T01:48:48
8,881,437
0
1
null
null
null
null
UTF-8
C++
false
false
9,843
cpp
#include "Chatwindow.hpp" #include "Game.hpp" #include "Message.hpp" #include "Network.hpp" #include "TextureBuffer.hpp" #include "Config.hpp" #include "Mutex.hpp" #include <sfml/system.hpp> std::vector<Message*> Chatwindow::chat; sf::Text Chatwindow::text; bool Chatwindow::active=false; float Chatwindow::keytime=0.15; float Chatwindow::responsetime=keytime; float Chatwindow::spkeytime=0.4; float Chatwindow::spkeyrtime=spkeytime; void Chatwindow::update(float step,sf::RenderWindow* window) { sf::Event event; if(responsetime<keytime) { responsetime-=step; if(responsetime<0) { responsetime=keytime; } } if(spkeyrtime<spkeytime) { spkeyrtime-=step; if(spkeyrtime<0) { spkeyrtime=spkeytime; } } if(!active&&spkeyrtime==spkeytime) { if(sf::Keyboard::isKeyPressed(sf::Keyboard::Return)) { active=true; spkeyrtime-=step; text.setCharacterSize(12); //text.setFont(TextureBuffer::getFont()); text.setStyle(sf::Text::Regular); text.setColor(sf::Color::Blue); text.setPosition(20,Config::getValue("resolution_y")-20); } } else { if(active&&responsetime==keytime) { if(sf::Keyboard::isKeyPressed(sf::Keyboard::Return)&&spkeyrtime==spkeytime) { std::string cmp = text.getString(); if(strcmp(cmp.substr(0,2).c_str(),"c_")==0) { Game::console(cmp.substr(2,cmp.length()).c_str()); } else if(strcmp(cmp.c_str(),"")!=0) { Game::tcpsend("MSG|"+text.getString()); } text.setString(""); active=false; spkeyrtime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) { text.setString(text.getString()+"q"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { text.setString(text.getString()+"w"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::E)) { text.setString(text.getString()+"e"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::R)) { text.setString(text.getString()+"r"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::T)) { text.setString(text.getString()+"t"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z)) { text.setString(text.getString()+"z"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::U)) { text.setString(text.getString()+"u"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::I)) { text.setString(text.getString()+"i"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::O)) { text.setString(text.getString()+"o"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::P)) { text.setString(text.getString()+"p"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { text.setString(text.getString()+"a"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { text.setString(text.getString()+"s"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { text.setString(text.getString()+"d"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::F)) { text.setString(text.getString()+"f"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::G)) { text.setString(text.getString()+"g"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::H)) { text.setString(text.getString()+"h"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::J)) { text.setString(text.getString()+"j"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::K)) { text.setString(text.getString()+"k"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::L)) { text.setString(text.getString()+"l"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Y)) { text.setString(text.getString()+"y"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::X)) { text.setString(text.getString()+"x"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::C)) { text.setString(text.getString()+"c"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::V)) { text.setString(text.getString()+"v"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::B)) { text.setString(text.getString()+"b"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::N)) { text.setString(text.getString()+"n"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::M)) { text.setString(text.getString()+"m"); responsetime-=step; } //num key if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num0)) { text.setString(text.getString()+"0"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num1)) { text.setString(text.getString()+"1"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num2)) { text.setString(text.getString()+"2"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num3)) { text.setString(text.getString()+"3"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num4)) { text.setString(text.getString()+"4"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num5)) { text.setString(text.getString()+"5"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num6)) { text.setString(text.getString()+"6"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num7)) { text.setString(text.getString()+"7"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num8)) { text.setString(text.getString()+"8"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Num9)) { text.setString(text.getString()+"9"); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Back)) { std::string ntext = text.getString(); if(ntext.size()>0) { ntext.resize(ntext.size()-1); text.setString(ntext); } responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { text.setString(text.getString()+" "); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Period)) { text.setString(text.getString()+"."); responsetime-=step; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Dash)) { text.setString(text.getString()+"_"); responsetime-=step; } } } } void Chatwindow::draw(sf::RenderWindow* window) { for(std::vector<Message*>::iterator it = chat.begin();it!=chat.end();++it) { (*it)->draw(window); } if(active) { window->draw(text); } } void Chatwindow::addText(std::string msg) { //Mutex::chat.lock(); chat.insert(chat.begin(),new Message(msg)); if(chat.size()>10) { chat.resize(10); } for(int x=0;x<chat.size();++x) { chat[x]->setPosition(20,Config::getValue("resolution_y")-40-(20*x)); } //Mutex::chat.unlock(); }
[ "daniel-theunissen@freenet.de" ]
daniel-theunissen@freenet.de
06cd24dc63d13864d88bf121f2fd46dcbbe22dec
5bccf2d2118008c0af6a51a92a042e967e4f2abe
/Support/Modules/GSXML/xercesc/framework/XMLValidityCodes.hpp
82a96e5b694afe7b43735b971fe918e05238d959
[ "Apache-2.0" ]
permissive
graphisoft-python/DGLib
fa42fadebedcd8daaddde1e6173bd8c33545041d
66d8717eb4422b968444614ff1c0c6c1bf50d080
refs/heads/master
2020-06-13T21:38:18.089834
2020-06-12T07:27:54
2020-06-12T07:27:54
194,795,808
3
0
Apache-2.0
2020-06-12T07:27:55
2019-07-02T05:45:00
C++
UTF-8
C++
false
false
5,914
hpp
// This file is generated, don't edit it!! #if !defined(XERCESC_INCLUDE_GUARD_ERRHEADER_XMLValid) #define XERCESC_INCLUDE_GUARD_ERRHEADER_XMLValid #include <xercesc/framework/XMLErrorReporter.hpp> #include <xercesc/util/XercesDefs.hpp> #include <xercesc/dom/DOMError.hpp> XERCES_CPP_NAMESPACE_BEGIN class XMLValid { public : enum Codes { NoError = 0 , E_LowBounds = 1 , ElementNotDefined = 2 , AttNotDefined = 3 , NotationNotDeclared = 4 , RootElemNotLikeDocType = 5 , RequiredAttrNotProvided = 6 , ElementNotValidForContent = 7 , BadIDAttrDefType = 8 , InvalidEmptyAttValue = 9 , ElementAlreadyExists = 10 , MultipleIdAttrs = 11 , ReusedIDValue = 12 , IDNotDeclared = 13 , UnknownNotRefAttr = 14 , UndeclaredElemInDocType = 15 , EmptyNotValidForContent = 16 , AttNotDefinedForElement = 17 , BadEntityRefAttr = 18 , UnknownEntityRefAttr = 19 , ColonNotValidWithNS = 20 , NotEnoughElemsForCM = 21 , NoCharDataInCM = 22 , DoesNotMatchEnumList = 23 , AttrValNotName = 24 , NoMultipleValues = 25 , NotSameAsFixedValue = 26 , RepElemInMixed = 27 , FeatureUnsupported = 28 , GroupContentRestricted = 29 , UnknownBaseDatatype = 30 , NoContentForRef = 31 , DatatypeError = 32 , ProhibitedAttributePresent = 33 , IllegalXMLSpace = 34 , WrongTargetNamespace = 35 , SimpleTypeHasChild = 36 , NoDatatypeValidatorForSimpleType = 37 , GrammarNotFound = 38 , DisplayErrorMessage = 39 , NillNotAllowed = 40 , NilAttrNotEmpty = 41 , FixedDifferentFromActual = 42 , NoDatatypeValidatorForAttribute = 43 , GenericError = 44 , ElementNotQualified = 45 , ElementNotUnQualified = 46 , VC_IllegalRefInStandalone = 47 , NoDefAttForStandalone = 48 , NoAttNormForStandalone = 49 , NoWSForStandalone = 50 , VC_EntityNotFound = 51 , PartialMarkupInPE = 52 , DatatypeValidationFailure = 53 , UniqueParticleAttributionFail = 54 , NoAbstractInXsiType = 55 , NoDirectUseAbstractElement = 56 , NoUseAbstractType = 57 , BadXsiType = 58 , NonDerivedXsiType = 59 , NoSubforBlock = 60 , AttributeNotQualified = 61 , AttributeNotUnQualified = 62 , IC_FieldMultipleMatch = 63 , IC_UnknownField = 64 , IC_AbsentKeyValue = 65 , IC_KeyNotEnoughValues = 66 , IC_KeyMatchesNillable = 67 , IC_DuplicateUnique = 68 , IC_DuplicateKey = 69 , IC_KeyRefOutOfScope = 70 , IC_KeyNotFound = 71 , NonWSContent = 72 , EmptyElemNotationAttr = 73 , EmptyElemHasContent = 74 , ElemOneNotationAttr = 75 , AttrDupToken = 76 , ElemChildrenHasInvalidWS = 77 , E_HighBounds = 78 , W_LowBounds = 79 , W_HighBounds = 80 , F_LowBounds = 81 , F_HighBounds = 82 }; static bool isFatal(const XMLValid::Codes toCheck) { return ((toCheck >= F_LowBounds) && (toCheck <= F_HighBounds)); } static bool isWarning(const XMLValid::Codes toCheck) { return ((toCheck >= W_LowBounds) && (toCheck <= W_HighBounds)); } static bool isError(const XMLValid::Codes toCheck) { return ((toCheck >= E_LowBounds) && (toCheck <= E_HighBounds)); } static XMLErrorReporter::ErrTypes errorType(const XMLValid::Codes toCheck) { if ((toCheck >= W_LowBounds) && (toCheck <= W_HighBounds)) return XMLErrorReporter::ErrType_Warning; else if ((toCheck >= F_LowBounds) && (toCheck <= F_HighBounds)) return XMLErrorReporter::ErrType_Fatal; else if ((toCheck >= E_LowBounds) && (toCheck <= E_HighBounds)) return XMLErrorReporter::ErrType_Error; return XMLErrorReporter::ErrTypes_Unknown; } static DOMError::ErrorSeverity DOMErrorType(const XMLValid::Codes toCheck) { if ((toCheck >= W_LowBounds) && (toCheck <= W_HighBounds)) return DOMError::DOM_SEVERITY_WARNING; else if ((toCheck >= F_LowBounds) && (toCheck <= F_HighBounds)) return DOMError::DOM_SEVERITY_FATAL_ERROR; else return DOMError::DOM_SEVERITY_ERROR; } private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- XMLValid(); }; XERCES_CPP_NAMESPACE_END #endif
[ "445212619@qqcom" ]
445212619@qqcom
0132ad7eecc9920610a9ad28756d0ae4fcf9fba5
c120f72a42d2f202fc50e3569ae217220359a49c
/src/.history/main_20210809113105.cpp
ccac7eda38f0cca19b75130162a93b68b397733f
[]
no_license
zlatkovnik/Crius
c5888fca8c2c572ce5b151adf6073f965b3914d6
414fb380823c5a38e33dd47818487290405ecde7
refs/heads/main
2023-07-07T04:35:12.126132
2021-08-09T14:51:03
2021-08-09T14:51:03
388,804,001
0
0
null
null
null
null
UTF-8
C++
false
false
3,452
cpp
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <vector> #include "shader.h" #include "mesh.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; struct position { float x; float y; float z; }; int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } { // int dim = 10; // float size = 1.0f; // std::vector<struct position> vertices; // for(int i = 0; i < dim; i++){ // for(int j = 0; j < dim; j++){ // float x = j * size; // float y = i * size; // struct position pt; // } // } float vertices[] = { 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f }; Mesh cube(vertices, sizeof(vertices) / sizeof(float)); Shader basicShader("./src/res/shaders/basic.vert", "./src/res/shaders/basic.frag"); while (!glfwWindowShouldClose(window)) { //Input processInput(window); //Render glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glm::mat4 model = glm::mat4(1.0f); model = glm::rotate(model, glm::radians(45.0f), glm::vec3(0.0f, 0.0f, 1.0f)); //model = glm::translate(model, glm::vec3(0.0f, 0.0f, -3.0f)); glm::mat4 view = glm::mat4(1.0f); view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 projection = glm::perspective( glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f ); glm::mat4 mvp = projection * view * model; basicShader.setMat4("mvp", mvp); cube.draw(basicShader); //Swap poll glfwSwapBuffers(window); glfwPollEvents(); } } glfwTerminate(); return 0; } void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); }
[ "zlatkovnik@dualsoft.net" ]
zlatkovnik@dualsoft.net
c99d5151e5f9812671b4a44d4a3622bc212bce01
1754a20778101b8971c057ec6c358d6b45ed940b
/src/test/test_bitcoin_fuzzy.cpp
ce5b571d46302278411e239a5e6ec7e44f779cad
[ "MIT" ]
permissive
valeamoris/platopia
33ad24e97fa77f09cab94a35705f2180d9904064
563c616db768f813aa4482d39d8ed1d8aacaad4f
refs/heads/master
2020-04-11T06:48:50.911653
2018-05-15T06:15:27
2018-05-15T06:15:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,081
cpp
// Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "addrman.h" #include "chain.h" #include "coins.h" #include "compressor.h" #include "consensus/merkle.h" #include "net.h" #include "primitives/block.h" #include "protocol.h" #include "pubkey.h" #include "script/script.h" #include "streams.h" #include "undo.h" #include "version.h" #include <cstdint> #include <unistd.h> #include <algorithm> #include <vector> enum TEST_ID { CBLOCK_DESERIALIZE = 0, CTRANSACTION_DESERIALIZE, CBLOCKLOCATOR_DESERIALIZE, CBLOCKMERKLEROOT, CADDRMAN_DESERIALIZE, CBLOCKHEADER_DESERIALIZE, CBANENTRY_DESERIALIZE, CTXUNDO_DESERIALIZE, CBLOCKUNDO_DESERIALIZE, COIN_DESERIALIZE, CNETADDR_DESERIALIZE, CSERVICE_DESERIALIZE, CMESSAGEHEADER_DESERIALIZE, CADDRESS_DESERIALIZE, CINV_DESERIALIZE, CBLOOMFILTER_DESERIALIZE, CDISKBLOCKINDEX_DESERIALIZE, CTXOUTCOMPRESSOR_DESERIALIZE, TEST_ID_END }; bool read_stdin(std::vector<char> &data) { char buffer[1024]; ssize_t length = 0; while ((length = read(STDIN_FILENO, buffer, 1024)) > 0) { data.insert(data.end(), buffer, buffer + length); if (data.size() > (1 << 20)) return false; } return length == 0; } int main(int argc, char **argv) { ECCVerifyHandle globalVerifyHandle; std::vector<char> buffer; if (!read_stdin(buffer)) return 0; if (buffer.size() < sizeof(uint32_t)) return 0; uint32_t test_id = 0xffffffff; memcpy(&test_id, &buffer[0], sizeof(uint32_t)); buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t)); if (test_id >= TEST_ID_END) return 0; CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION); try { int nVersion; ds >> nVersion; ds.SetVersion(nVersion); } catch (const std::ios_base::failure &e) { return 0; } switch (test_id) { case CBLOCK_DESERIALIZE: { try { CBlock block; ds >> block; } catch (const std::ios_base::failure &e) { return 0; } break; } case CTRANSACTION_DESERIALIZE: { try { CTransaction tx(deserialize, ds); } catch (const std::ios_base::failure &e) { return 0; } break; } case CBLOCKLOCATOR_DESERIALIZE: { try { CBlockLocator bl; ds >> bl; } catch (const std::ios_base::failure &e) { return 0; } break; } case CBLOCKMERKLEROOT: { try { CBlock block; ds >> block; bool mutated; BlockMerkleRoot(block, &mutated); } catch (const std::ios_base::failure &e) { return 0; } break; } case CADDRMAN_DESERIALIZE: { try { CAddrMan am; ds >> am; } catch (const std::ios_base::failure &e) { return 0; } break; } case CBLOCKHEADER_DESERIALIZE: { try { CBlockHeader bh; ds >> bh; } catch (const std::ios_base::failure &e) { return 0; } break; } case CBANENTRY_DESERIALIZE: { try { CBanEntry be; ds >> be; } catch (const std::ios_base::failure &e) { return 0; } break; } case CTXUNDO_DESERIALIZE: { try { CTxUndo tu; ds >> tu; } catch (const std::ios_base::failure &e) { return 0; } break; } case CBLOCKUNDO_DESERIALIZE: { try { CBlockUndo bu; ds >> bu; } catch (const std::ios_base::failure &e) { return 0; } break; } case COIN_DESERIALIZE: { try { Coin coin; ds >> coin; } catch (const std::ios_base::failure &e) { return 0; } break; } case CNETADDR_DESERIALIZE: { try { CNetAddr na; ds >> na; } catch (const std::ios_base::failure &e) { return 0; } break; } case CSERVICE_DESERIALIZE: { try { CService s; ds >> s; } catch (const std::ios_base::failure &e) { return 0; } break; } case CMESSAGEHEADER_DESERIALIZE: { CMessageHeader::MessageMagic pchMessageStart = {0x00, 0x00, 0x00, 0x00}; try { CMessageHeader mh(pchMessageStart); ds >> mh; if (!mh.IsValid(pchMessageStart)) { return 0; } } catch (const std::ios_base::failure &e) { return 0; } break; } case CADDRESS_DESERIALIZE: { try { CAddress a; ds >> a; } catch (const std::ios_base::failure &e) { return 0; } break; } case CINV_DESERIALIZE: { try { CInv i; ds >> i; } catch (const std::ios_base::failure &e) { return 0; } break; } case CBLOOMFILTER_DESERIALIZE: { try { CBloomFilter bf; ds >> bf; } catch (const std::ios_base::failure &e) { return 0; } break; } case CDISKBLOCKINDEX_DESERIALIZE: { try { CDiskBlockIndex dbi; ds >> dbi; } catch (const std::ios_base::failure &e) { return 0; } break; } case CTXOUTCOMPRESSOR_DESERIALIZE: { CTxOut to; CTxOutCompressor toc(to); try { ds >> toc; } catch (const std::ios_base::failure &e) { return 0; } break; } default: return 0; } return 0; }
[ "d4ptakr@gmail.com" ]
d4ptakr@gmail.com
9dd00ef2563aabccc6b2d9b43ce657578f31b10f
c254c37b30fba0c41b3157dd5581e03035df43c1
/C++ Solutions/URI/1153 - Simple Factorial.cpp
5aa442e8ef3b31efd45294beb7c1dc723f7a0868
[]
no_license
AntonioSanchez115/Competitive-Programming
12c8031bbb0c82d99b4615d414f5eb727ac5a113
49dac0119337a45fe8cbeae50d7d8563140a3119
refs/heads/master
2022-02-14T10:51:19.125143
2022-01-26T07:59:34
2022-01-26T07:59:34
186,081,160
1
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
#include <bits/stdc++.h> using namespace std; long long fact(long long n){ if(n==1) return n; return n*=fact(n-1); } int main() { int n; cin >> n; cout << fact(n) << '\n'; return 0; }
[ "sanchezantonio.115@gmail.com" ]
sanchezantonio.115@gmail.com
644d4a5714fb0d23b05269708e6d08ef816f6b22
97f69dbdac0abcb4caaefac3286d1957f3b2c687
/src/utiltime.h
c9feb3335a0a12e63a530892abcdc02139d299f0
[ "MIT" ]
permissive
TBC-Project/TongBaoCoin
3522b9919f1988f78869dc3dcaf24c4a9f3ae149
ea6ebee91aae504cf3956837a164362e064a361c
refs/heads/master
2022-11-18T14:02:53.828351
2020-07-03T10:13:45
2020-07-03T10:13:45
270,630,154
0
0
null
null
null
null
UTF-8
C++
false
false
708
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2017 The PIVX developers // Copyright (c) 2018 The TBC developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTILTIME_H #define BITCOIN_UTILTIME_H #include <stdint.h> #include <string> int64_t GetTime(); int64_t GetTimeMillis(); int64_t GetTimeMicros(); void SetMockTime(int64_t nMockTimeIn); void MilliSleep(int64_t n); std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime); std::string DurationToDHMS(int64_t nDurationTime); #endif // BITCOIN_UTILTIME_H
[ "xingtongwei12@163.com" ]
xingtongwei12@163.com
ec25c502beceda520f35bdf7d1290b5d3c217095
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/Handle_PGeom2d_Curve.hxx
42fb245d3f6c479d79822a25656e5facc3272523
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
835
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Handle_PGeom2d_Curve_HeaderFile #define _Handle_PGeom2d_Curve_HeaderFile #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Handle_PGeom2d_Geometry_HeaderFile #include <Handle_PGeom2d_Geometry.hxx> #endif class Standard_Persistent; class Handle(Standard_Type); class Handle(PGeom2d_Geometry); class PGeom2d_Curve; DEFINE_STANDARD_PHANDLE(PGeom2d_Curve,PGeom2d_Geometry) #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
395ab4c95d135d2c2748ac709e35d9a7dea70152
34076478a8d8ac3107d3970d58ba10a60d4251fb
/src/slate2d.cpp
bcf4ad4068e0983ba26c480b911f777fa3539d60
[]
no_license
brucelevis/slate2d
91f0fb8cd87b89fed0f73bf7002077c1465749a7
1654326af00cc209ded65615f382cd4d894aa30e
refs/heads/master
2023-02-14T22:00:45.488029
2021-01-03T18:37:03
2021-01-03T18:37:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,485
cpp
#include <iostream> #include <cmath> #include <chrono> #include <thread> #include <stdint.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #ifdef __EMSCRIPTEN__ #include "GLES2/gl2.h" #include "GLES2/gl2ext.h" #define NO_SDL_GLEXT #else #define GLEW_STATIC #include <GL/glew.h> #endif #include <SDL/SDL.h> #include <SDL/SDL_opengl.h> extern "C" { #include "rlgl.h" extern bool initGL(int width, int height); } #include <imgui.h> #include "imgui_impl_sdl.h" #include "files.h" #include "input.h" #include "keys.h" #include "cvar_main.h" #include "imgui_console.h" #include "slate2d.h" #include <soloud.h> #include <soloud_thread.h> #include "filewatcher.h" #include "crunch_frontend.h" #include "assetloader.h" extern "C" { #include "console.h" #include "external/sds.h" } #include "external/fontstash.h" #include "main.h" #include "rendercommands.h" conState_t console; SoLoud::Soloud soloud; int64_t last_update_musec = 0, frame_musec = 0, com_frameTime = 0; //float frame_accum; bool frameAdvance = false; long long now = 0; static renderCommandList_t cmdList; SDL_Window *window; SDL_GLContext context; bool shouldQuit = false; bool frameStarted = false; void(*hostErrHandler)(int level, const char *msg); const char * __cdecl tempstr(const char *format, ...) { va_list argptr; static char string[2][32000]; // in case va is called by nested functions static int index = 0; char *buf; buf = string[index & 1]; index++; va_start(argptr, format); vsprintf(buf, format, argptr); va_end(argptr); return buf; } void SetWindowTitle(const char *title) { SDL_SetWindowTitle(window, title); } void Cmd_FrameAdvance_f(void) { if (!eng_pause->integer) { Con_SetVar("engine.pause", "1"); } else { frameAdvance = true; } } void Cmd_Vid_Restart_f(void) { SDL_SetWindowSize(window, vid_width->integer, vid_height->integer); SDL_GL_SetSwapInterval(vid_swapinterval->integer); SDL_SetWindowFullscreen(window, vid_fullscreen->integer == 2 ? SDL_WINDOW_FULLSCREEN : vid_fullscreen->integer == 1 ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); } void Cmd_Exec_f() { if (Con_GetArgsCount() != 2) { Con_Printf("exec <filename> - runs the contents of filename as a console script\n"); return; } sds name = sdsnew(Con_GetArg(1)); if (strcmp(&name[sdslen(name) - 4], ".cfg") == 0) { } if (!FS_Exists(name)) { Con_Printf("couldn't exec file %s\n", name); return; } void *buffer; auto sz = FS_ReadFile(name, &buffer); const char *str = (const char *)buffer; Con_Execute(str); free(buffer); sdsfree(name); } void Cmd_Clear_f() { IMConsole()->ClearLog(); } void ConH_Print(const char *line) { IMConsole()->AddLog("%s", line); printf("%s", line); } void ConH_Error(int level, const char *message) { Con_Print(message); #if defined(_WIN32) && defined(DEBUG) if (level == ERR_FATAL) { __debugbreak(); } #else if (level == ERR_FATAL) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal Error", message, NULL); } #endif if (level == ERR_FATAL) { exit(1); } else { Con_SetVar("engine.errorMessage", message); hostErrHandler(level, message); } } static void Cmd_Quit_f(void) { shouldQuit = true; } auto start = std::chrono::steady_clock::now(); static inline long long measure_now() { return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count(); } SLT_API double SLT_StartFrame() { if (shouldQuit) { return -1; } if (frameStarted) { return 0; } now = measure_now(); frame_musec = now - com_frameTime; com_frameTime = now; SDL_Event ev; ImGuiIO &io = ImGui::GetIO(); while (SDL_PollEvent(&ev)) { ImGui_ImplSdl_ProcessEvent(&ev); switch (ev.type) { case SDL_QUIT: return -1; case SDL_KEYDOWN: if (ev.key.keysym.sym == SDLK_BACKQUOTE) { IMConsole()->consoleActive = !IMConsole()->consoleActive; ImGui::SetWindowFocus(nullptr); break; } default: ProcessInputEvent(ev); } } frameStarted = true; memset(&cmdList, 0, sizeof(cmdList)); if (snd_volume->modified) { soloud.setGlobalVolume(snd_volume->value); snd_volume->modified = false; } FileWatcher_Tick(); ImGui_ImplSdl_NewFrame(window); if (eng_errorMessage->string[0] != '\0') { ImGui::SetNextWindowPos(ImVec2(vid_width->integer / 2, vid_height->integer), 0, ImVec2(0.5, 0.5)); ImGui::Begin("Error", NULL, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize); ImGui::Text("%s", eng_errorMessage->string); ImGui::Text("%s", eng_lastErrorStack->string); ImGui::NewLine(); if (ImGui::Button("Close")) { Con_SetVar("engine.errorMessage", nullptr); Con_SetVar("engine.lastErrorStack", nullptr); } ImGui::End(); } rlMatrixMode(RL_PROJECTION); // Enable internal projection matrix rlLoadIdentity(); // Reset internal projection matrix rlOrtho(0.0, vid_width->integer, vid_height->integer, 0.0, 0.0, 1.0); // Recalculate internal projection matrix rlMatrixMode(RL_MODELVIEW); // Enable internal modelview matrix rlLoadIdentity(); // Reset internal modelview matrix return !eng_pause->integer || frameAdvance ? frame_musec / 1E6 : 0; } SLT_API void SLT_EndFrame() { if (!frameStarted) { return; } frameStarted = false; if (!eng_pause->integer || frameAdvance) { frameAdvance = false; } IMConsole()->Draw(vid_width->integer, vid_height->integer); Asset_DrawInspector(); ImGui::Render(); ImGui_ImplSdl_RenderDrawData(ImGui::GetDrawData()); if (debug_fontAtlas->integer) { rlLoadIdentity(); if (ctx != nullptr) fonsDrawDebug(ctx, 0, 32); rlglDraw(); } SDL_GL_SwapWindow(window); // OSes seem to not be able to sleep for shorter than a millisecond. so let's sleep until // we're close-ish and then burn loop the rest. we get a majority of the cpu/power gains // while still remaining pretty accurate on frametimes. if (vid_maxfps->integer > 0) { long long target = now + (long long)(1000.0f / vid_maxfps->integer * 1000); long long currentSleepTime = measure_now(); while (currentSleepTime <= target) { long long amt = (target - currentSleepTime) - 2000; if (amt > 0) { std::this_thread::sleep_for(std::chrono::microseconds(amt)); } currentSleepTime = measure_now(); } } } SLT_API void SLT_Init(int argc, char* argv[]) { // initialize console. construct imgui console, setup handlers, and then initialize the actual console IMConsole(); console.handlers.print = &ConH_Print; console.handlers.getKeyForString = &In_GetKeyNum; console.handlers.getStringForKey = &In_GetKeyName; console.handlers.error = &ConH_Error; Con_Init(&console); Con_AllocateKeys(MAX_KEYS); // setup some default buttons so you don't have to do anything to get generic input const char* defaultButtons[] = { "up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select" }; Con_AllocateButtons(&defaultButtons[0], 12); // setup console to pull cvars from command line Con_SetupCommandLine(argc, argv); // we don't have a filesystem yet so we don't want to run the whole command line // yet. pick out the convars that are important for FS initialization, and then later on // we'll run the rest. Con_SetVarFromStartup("fs.basepath"); Con_SetVarFromStartup("fs.basegame"); Con_SetVarFromStartup("fs.game"); FS_Init(argv[0]); // add engine level commands here Con_AddCommand("exec", Cmd_Exec_f); Con_AddCommand("quit", Cmd_Quit_f); Con_AddCommand("vid_restart", Cmd_Vid_Restart_f); Con_AddCommand("frame_advance", Cmd_FrameAdvance_f); Con_AddCommand("clear", Cmd_Clear_f); RegisterMainCvars(); FileWatcher_Init(); Crunch_Init(); if (!FS_Exists("default.cfg")) { Con_Error(ERR_FATAL, "Filesystem error, check fs.basepath is set correctly. (Could not find default.cfg)"); } Con_Execute("exec default.cfg\n"); if (FS_Exists("autoexec.cfg")) { Con_Execute("exec autoexec.cfg\n"); } SDL_SetMainReady(); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER) < 0) { Con_Errorf(ERR_FATAL, "There was an error initing SDL2: %s", SDL_GetError()); } atexit(SDL_Quit); #ifdef __EMSCRIPTEN__ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GLprofile::SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #endif window = SDL_CreateWindow("Slate2D", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, vid_width->integer, vid_height->integer, SDL_WINDOW_OPENGL); if (window == NULL) { Con_Errorf(ERR_FATAL, "There was an error creating the window: %s", SDL_GetError()); } SDL_SetWindowFullscreen(window, vid_fullscreen->integer == 2 ? SDL_WINDOW_FULLSCREEN : vid_fullscreen->integer == 1 ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); context = SDL_GL_CreateContext(window); if (!initGL(vid_width->integer, vid_height->integer)) { Con_Error(ERR_FATAL, "Could not init GL."); } SDL_GL_SetSwapInterval(vid_swapinterval->integer); if (context == NULL) { Con_Errorf(ERR_FATAL, "There was an error creating OpenGL context: %s", SDL_GetError()); } const unsigned char* version = glGetString(GL_VERSION); if (version == NULL) { Con_Error(ERR_FATAL, "There was an error with OpenGL configuration."); } SoLoud::result result = soloud.init(); if (result != 0) { Con_Errorf(ERR_FATAL, "Error initializing audio: %s", soloud.getErrorString(result)); } SDL_GL_MakeCurrent(window, context); ImGui::CreateContext(); ImGui_ImplSdl_Init(window); ImGui::StyleColorsDark(); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0); ImGuiIO& io = ImGui::GetIO(); #ifdef RELEASE io.IniFilename = NULL; #endif // not working in emscripten for some reason? assert on ImGuiKey_Space not being mapped #ifndef __EMSCRIPTEN__ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; #endif // now that we've ran the user configs and initialized everything else, apply everything else on the // command line here. this will set the rest of the variables and run any commands specified. Con_ExecuteCommandLine(); } SLT_API void SLT_Shutdown() { Con_Shutdown(); Asset_ClearAll(); ImGui_ImplSdl_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(context); } SLT_API void SLT_Con_SetErrorHandler(void(*errHandler)(int level, const char *msg)) { hostErrHandler = errHandler; } SLT_API void SLT_Con_SetDefaultCommandHandler(bool(*cmdHandler)()) { console.handlers.unhandledCommand = cmdHandler; } SLT_API void SLT_SendConsoleCommand(const char* text) { Con_Execute(text); } SLT_API void SLT_Print(const char* fmt, ...) { va_list args; va_start(args, fmt); Con_PrintfV(fmt, args); va_end(args); } SLT_API void SLT_Error(int level, const char* error, ...) { va_list args; va_start(args, error); Con_RawErrorV(level, error, args); va_end(args); } SLT_API void SLT_SetWindowTitle(const char* title) { SetWindowTitle(title); } SLT_API const conVar_t* SLT_Con_GetVarDefault(const char* var_name, const char* var_value, int flags) { return Con_GetVarDefault(var_name, var_value, flags); } SLT_API const conVar_t* SLT_Con_GetVar(const char* name) { return Con_GetVar(name); } SLT_API const conVar_t* SLT_Con_SetVar(const char* var_name, const char* value) { return Con_SetVar(var_name, value); } SLT_API int SLT_Con_GetArgCount(void) { return Con_GetArgsCount(); } SLT_API const char* SLT_Con_GetArg(int arg) { return Con_GetArg(arg); } SLT_API const char* SLT_Con_GetArgs(int start) { return Con_GetArgs(start); } SLT_API void SLT_Con_AddCommand(const char *name, conCmd_t cmd) { Con_AddCommand(name, cmd); } SLT_API int SLT_FS_ReadFile(const char* path, void** buffer) { return FS_ReadFile(path, buffer); } SLT_API uint8_t SLT_FS_Exists(const char* file) { return FS_Exists(file) ? 1 : 0; } SLT_API char** SLT_FS_List(const char* path) { return FS_List(path); } SLT_API void SLT_FS_FreeList(void* listVar) { FS_FreeList(listVar); } SLT_API void SLT_In_AllocateButtons(const char** buttonNames, int buttonCount) { Con_AllocateButtons(buttonNames, buttonCount); } SLT_API const buttonState_t* SLT_In_GetButton(int buttonNum) { return Con_GetButton(buttonNum); } SLT_API uint8_t SLT_In_ButtonPressed(int buttonId, unsigned int delay, int repeat) { return In_ButtonPressed(buttonId, delay, repeat) ? 1 : 0; } SLT_API MousePosition SLT_In_MousePosition() { return In_MousePosition(); } SLT_API void SLT_SubmitRenderCommands(renderCommandList_t* list) { SubmitRenderCommands(list); } SLT_API AssetHandle SLT_Asset_Create(AssetType_t assetType, const char* name, const char* path, int flags) { return Asset_Create(assetType, name, path, flags); } SLT_API AssetHandle SLT_Asset_Find(const char* name) { return Asset_Find(name); } SLT_API void SLT_Asset_Load(AssetHandle assetHandle) { Asset_Load(assetHandle); } SLT_API void SLT_Asset_LoadAll() { Asset_LoadAll(); } SLT_API void SLT_Asset_ClearAll() { Asset_ClearAll(); } SLT_API void SLT_Asset_LoadINI(const char* path) { Asset_LoadINI(path); } SLT_API void SLT_Asset_BMPFNT_Set(AssetHandle assetHandle, const char* glyphs, int glyphWidth, int charSpacing, int spaceWidth, int lineHeight) { BMPFNT_Set(assetHandle, glyphs, glyphWidth, charSpacing, spaceWidth, lineHeight); } SLT_API int SLT_Asset_TextWidth(AssetHandle assetHandle, const char* string, float scale) { return Asset_TextWidth(assetHandle, string, scale); } SLT_API const char* SLT_Asset_BreakString(int width, const char* in) { return TTF_BreakString(width, in); } SLT_API void SLT_Asset_Sprite_Set(AssetHandle assetHandle, int width, int height, int marginX, int marginY) { Sprite_Set(assetHandle, width, height, marginX, marginY); } SLT_API void SLT_Asset_Canvas_Set(AssetHandle assetHandle, int width, int height) { Canvas_Set(assetHandle, width, height); } SLT_API void SLT_Asset_Shader_Set(AssetHandle id, uint8_t isFile, const char* vs, const char* fs) { Shader_Set(id, isFile > 0, vs, fs); } SLT_API const Image* SLT_Get_Img(AssetHandle id) { return Get_Img(id); } SLT_API const tmx_map* SLT_Get_TMX(AssetHandle id) { return Get_TMX(id); } SLT_API unsigned int SLT_Snd_Play(AssetHandle asset, float volume, float pan, uint8_t loop) { return Snd_Play(asset, volume, pan, loop > 0); } SLT_API void SLT_Snd_Stop(unsigned int handle) { Snd_Stop(handle); } SLT_API void SLT_Snd_PauseResume(unsigned int handle, uint8_t pause) { Snd_PauseResume(handle, pause > 0); } SLT_API void SLT_GetResolution(int* width, int* height) { *width = vid_width->integer; *height = vid_height->integer; } SLT_API const void* SLT_GetImguiContext() { return ImGui::GetCurrentContext(); } SLT_API void SLT_UpdateLastFrameTime() { last_update_musec = com_frameTime; } #define GET_COMMAND(type, id) type *cmd; cmd = (type *)R_GetCommandBuffer(sizeof(*cmd)); if (!cmd) { return; } cmd->commandId = id; void* R_GetCommandBuffer(int bytes) { // always leave room for the end of list command if (cmdList.used + bytes + 4 > MAX_RENDER_COMMANDS) { if (bytes > MAX_RENDER_COMMANDS - 4) { SLT_Error(ERR_FATAL, "%s: bad size %i", __func__, bytes); } // if we run out of room, just start dropping commands return NULL; } cmdList.used += bytes; return cmdList.cmds + cmdList.used - bytes; } SLT_API void DC_Submit() { SLT_SubmitRenderCommands(&cmdList); memset(&cmdList, 0, sizeof(cmdList)); } SLT_API void DC_Clear(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { GET_COMMAND(clearCommand_t, RC_CLEAR); cmd->color[0] = r; cmd->color[1] = g; cmd->color[2] = b; cmd->color[3] = a; } SLT_API void DC_SetColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { GET_COMMAND(setColorCommand_t, RC_SET_COLOR) cmd->color[0] = r; cmd->color[1] = g; cmd->color[2] = b; cmd->color[3] = a; } SLT_API void DC_ResetTransform() { GET_COMMAND(resetTransformCommand_t, RC_RESET_TRANSFORM) } SLT_API void DC_Scale(float x, float y) { GET_COMMAND(scaleCommand_t, RC_SCALE) cmd->x = x; cmd->y = y; } SLT_API void DC_Rotate(float angle) { GET_COMMAND(rotateCommand_t, RC_ROTATE); cmd->angle = angle; } SLT_API void DC_Translate(float x, float y) { GET_COMMAND(translateCommand_t, RC_TRANSLATE); cmd->x = x; cmd->y = y; } SLT_API void DC_SetScissor(int x, int y, int w, int h) { GET_COMMAND(setScissorCommand_t, RC_SET_SCISSOR) cmd->x = x; cmd->y = y; cmd->w = w; cmd->h = h; } SLT_API void DC_ResetScissor() { DC_SetScissor(0, 0, 0, 0); } SLT_API void DC_UseCanvas(AssetHandle canvasId) { GET_COMMAND(useCanvasCommand_t, RC_USE_CANVAS) cmd->canvasId = canvasId; } SLT_API void DC_ResetCanvas() { GET_COMMAND(resetCanvasCommand_t, RC_RESET_CANVAS) } SLT_API void DC_UseShader(AssetHandle shaderId) { GET_COMMAND(useShaderCommand_t, RC_USE_SHADER) cmd->shaderId = shaderId; } SLT_API void DC_ResetShader() { GET_COMMAND(resetShaderCommand_t, RC_RESET_SHADER) } SLT_API void DC_DrawRect(float x, float y, float w, float h, uint8_t outline) { GET_COMMAND(drawRectCommand_t, RC_DRAW_RECT) cmd->outline = outline > 0; cmd->x = x; cmd->y = y; cmd->w = w; cmd->h = h; } SLT_API void DC_SetTextStyle(AssetHandle fntId, float size, float lineHeight, int align) { GET_COMMAND(setTextStyleCommand_t, RC_SET_TEXT_STYLE) cmd->fntId = fntId; cmd->size = size; cmd->lineHeight = lineHeight; cmd->align = align; } SLT_API void DC_DrawText(float x, float y, float w, const char* text, int len) { GET_COMMAND(drawTextCommand_t, RC_DRAW_TEXT) cmd->x = x; cmd->y = y; cmd->w = w; cmd->len = len; cmd->strSz = (unsigned int)strlen(text) + 1; void* strStart = R_GetCommandBuffer(cmd->strSz); strncpy((char*)strStart, text, cmd->strSz - 1); } SLT_API void DC_DrawImage(unsigned int imgId, float x, float y, float w, float h, float scale, uint8_t flipBits, float ox, float oy) { GET_COMMAND(drawImageCommand_t, RC_DRAW_IMAGE) cmd->x = x; cmd->y = y; cmd->w = w; cmd->h = h; cmd->ox = ox; cmd->oy = oy; cmd->scale = scale; cmd->flipBits = flipBits; cmd->imgId = imgId; } SLT_API void DC_DrawSprite(unsigned int spr, int id, float x, float y, float scale, uint8_t flipBits, int w, int h) { GET_COMMAND(drawSpriteCommand_t, RC_DRAW_SPRITE); cmd->spr = spr; cmd->id = id; cmd->x = x; cmd->y = y; cmd->scale = scale; cmd->flipBits = flipBits; cmd->w = w; cmd->h = h; } SLT_API void DC_DrawLine(float x1, float y1, float x2, float y2) { GET_COMMAND(drawLineCommand_t, RC_DRAW_LINE); cmd->x1 = x1; cmd->y1 = y1; cmd->x2 = x2; cmd->y2 = y2; } SLT_API void DC_DrawCircle(float x, float y, float radius, uint8_t outline) { GET_COMMAND(drawCircleCommand_t, RC_DRAW_CIRCLE); cmd->outline = outline > 0; cmd->x = x; cmd->y = y; cmd->radius = radius; } SLT_API void DC_DrawTri(float x1, float y1, float x2, float y2, float x3, float y3, uint8_t outline) { GET_COMMAND(drawTriCommand_t, RC_DRAW_TRI); cmd->outline = outline > 0; cmd->x1 = x1; cmd->y1 = y1; cmd->x2 = x2; cmd->y2 = y2; cmd->x3 = x3; cmd->y3 = y3; } SLT_API void DC_DrawMapLayer(unsigned int mapId, unsigned int layer, float x, float y, unsigned int cellX, unsigned int cellY, unsigned int cellW, unsigned int cellH) { GET_COMMAND(drawMapCommand_t, RC_DRAW_MAP_LAYER); cmd->mapId = mapId; cmd->layer = layer; cmd->x = x; cmd->y = y; cmd->cellX = cellX; cmd->cellY = cellY; cmd->cellW = cellW; cmd->cellH = cellH; }
[ "sponge@d8d.org" ]
sponge@d8d.org
810615e01f32ddc7b702931203bacf195582ab7f
2b5f0ccd2832775fcc6cf85b321087c443560f39
/Assign02-OutputManipulation/stdafx.cpp
bb7678e1ad79ccad1145df26855a68d8988c797a
[]
no_license
neilpirch/CSIS123_Assign02_OutputManipulation
5bf6142ea85ca5768948a04371bbf48e24fa2eaf
65d67df484e59f3eb5bd3d68923140fcceaef3c8
refs/heads/master
2021-08-28T15:18:43.755299
2017-12-12T15:32:56
2017-12-12T15:32:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
// stdafx.cpp : source file that includes just the standard includes // Assign02-OutputManipulation.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
[ "neil.pirch@gmail.com" ]
neil.pirch@gmail.com
83673960b4f279a8cdb2c5a5454ed7e64e9f44ac
3674c76452699205d34280347099dcfca38c1f01
/ShadowPack/PasswordDlg.cpp
64da3018acf405c910eaeca27babd900d6fe0e95
[]
no_license
sTeeLM/shadowpack
c6677f02cb2c8baf87f5aad3aa3ca9a8f4df0504
ad3a3b9a888fdb014725bbd4e6a57ffe1b08c89b
refs/heads/main
2022-05-18T17:37:12.955042
2022-03-29T13:27:56
2022-03-29T13:27:56
11,245,741
6
2
null
null
null
null
UTF-8
C++
false
false
907
cpp
// PasswordDlg.cpp: 实现文件 // #include "pch.h" #include "ShadowPack.h" #include "PasswordDlg.h" #include "afxdialogex.h" // CPasswordDlg 对话框 IMPLEMENT_DYNAMIC(CPasswordDlg, CDialogEx) CPasswordDlg::CPasswordDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_PASSWORD, pParent) , m_strPassword(_T("")) { } CPasswordDlg::~CPasswordDlg() { } CString CPasswordDlg::GetPassword() { if (DoModal() == IDOK) { return m_strPassword; } else { return _T(""); } } void CPasswordDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_PASSWORD, m_strPassword); if (pDX->m_bSaveAndValidate && m_strPassword.GetLength() == 0) { AfxMessageBox(IDS_PASSWORD_CAN_NOT_NULL); pDX->Fail(); } } BEGIN_MESSAGE_MAP(CPasswordDlg, CDialogEx) END_MESSAGE_MAP() // CPasswordDlg 消息处理程序
[ "steel.mental@gmail.com" ]
steel.mental@gmail.com
ac92845ede1d4c59f4e9f23fce40cb422d151f2f
45e0fbd9a9dbcdd4fbe6aaa2fdb2aed296f81e33
/FindSecret/Classes/Native/mscorlib_System_Array_InternalEnumerator_1_gen3645660533.h
6384f4b295ccb9f8ca9094723767bf0537ed73d2
[ "MIT" ]
permissive
GodIsWord/NewFindSecret
d4a5d2d810ee1f9d6b3bc91168895cc808bac817
4f98f316d29936380f9665d6a6d89962d9ee5478
refs/heads/master
2020-03-24T09:54:50.239014
2018-10-27T05:22:11
2018-10-27T05:22:11
142,641,511
0
0
null
null
null
null
UTF-8
C++
false
false
1,470
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_ValueType3640485471.h" // System.Array struct Il2CppArray; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array/InternalEnumerator`1<System.IEquatable`1<System.String>> struct InternalEnumerator_1_t3645660533 { public: // System.Array System.Array/InternalEnumerator`1::array Il2CppArray * ___array_0; // System.Int32 System.Array/InternalEnumerator`1::idx int32_t ___idx_1; public: inline static int32_t get_offset_of_array_0() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t3645660533, ___array_0)); } inline Il2CppArray * get_array_0() const { return ___array_0; } inline Il2CppArray ** get_address_of_array_0() { return &___array_0; } inline void set_array_0(Il2CppArray * value) { ___array_0 = value; Il2CppCodeGenWriteBarrier(&___array_0, value); } inline static int32_t get_offset_of_idx_1() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t3645660533, ___idx_1)); } inline int32_t get_idx_1() const { return ___idx_1; } inline int32_t* get_address_of_idx_1() { return &___idx_1; } inline void set_idx_1(int32_t value) { ___idx_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "zhangyide@9fbank.cc" ]
zhangyide@9fbank.cc
9c41b4703ef6404e4f3eb71338483dbd437fa736
fc978d04bfeeab93639f75a432872ce16ed0a08d
/vs2017/test/WinThread/WinThread/thread1.cpp
7295266a725ebb45b2999da3af93f58b0a81721b
[]
no_license
coderfamer/visual-studio-study
566fac7e17d81482536a49fac831ab79592092d2
c768797a252420461705ebc41e64b9a53b184dde
refs/heads/master
2020-03-18T11:00:27.084057
2018-08-03T02:08:49
2018-08-03T02:08:49
134,645,255
3
0
null
null
null
null
UTF-8
C++
false
false
2,057
cpp
#include <iostream> #include <string> #include <Windows.h> #include <process.h> using namespace std; class ThreadX { public: string thread_name; ThreadX(int start_value, int end_value, int frequency) { loop_start = start_value; loop_end = end_value; disp_frequency = frequency; } static unsigned __stdcall ThreadStaticEntryPoint(void* pThis) { ThreadX* pthx = (ThreadX*)pThis; pthx->threadEntryPoint(); return 1; } void threadEntryPoint() { for (int i = loop_start; i <= loop_end; ++i) { if (i % disp_frequency == 0) { cout << thread_name.c_str() << ": i = " << i << endl; } } cout << thread_name.c_str() << " thread terminating" << endl; } private: int loop_start; int loop_end; int disp_frequency; }; int main() { ThreadX* thd1 = new ThreadX(0, 3, 2000); HANDLE hth1; unsigned uiThread1Id; hth1 = (HANDLE)_beginthreadex(NULL, 0, ThreadX::ThreadStaticEntryPoint, thd1, CREATE_SUSPENDED, &uiThread1Id); if (hth1 == 0) cout << "Failed to create thread 1 " << endl; DWORD dwExitCode; GetExitCodeThread(hth1, &dwExitCode); cout << "initial thread1 exit code = " << dwExitCode << endl; thd1->thread_name = "t1"; ThreadX* thd2 = new ThreadX(-100000, 0, 2000); HANDLE hth2; unsigned uiThread2Id; hth2 = (HANDLE)_beginthreadex(NULL, 0, ThreadX::ThreadStaticEntryPoint, thd2, CREATE_SUSPENDED, &uiThread2Id); if (hth2 == 0) cout << "Failed to create thread 2" << endl; GetExitCodeProcess(hth2, &dwExitCode); cout << "initial thread2 exit code = " << dwExitCode << endl; thd2->thread_name = "t2"; ResumeThread(hth1); ResumeThread(hth2); WaitForSingleObject(hth1, INFINITE); WaitForSingleObject(hth2, INFINITE); GetExitCodeThread(hth1, &dwExitCode); cout << "thread 1 exit with code " << dwExitCode << endl; GetExitCodeThread(hth2, &dwExitCode); cout << "thread 2 exited with code " << dwExitCode << endl; CloseHandle(hth1); CloseHandle(hth2); delete thd1; thd1 = NULL; delete thd2; thd2 = NULL; cout << "Primary thread terminating." << endl; return 0; }
[ "13625611069@163.com" ]
13625611069@163.com
fc902b1763f9a3a8d96b56e86fddee9106c49059
a4aa9a4d5cfbe491666d45b6cce5af0ffc15198c
/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.cpp
c7d5141d5934caee48c31b813bb477494a54a523
[]
no_license
Royal-Pal/LeetCode-Contributions
4265f2c839dcdad0542b3998d81194fb47882ee5
a139d9102b2cc0b87e5f842787b09279412804e6
refs/heads/main
2023-07-28T00:06:00.636488
2021-09-11T18:15:32
2021-09-11T18:15:32
393,603,355
0
0
null
null
null
null
UTF-8
C++
false
false
816
cpp
class Solution { public: int lengthOfLongestSubstring(string s) { int n = s.length(); vector<int> occ(257, 0); int max_len = 0, start = 0; for(int i = 0; i < n; i++) { int idx = (int)((char)s[i]); occ[idx]++; if(occ[idx] > 1) { max_len = max(max_len, i - start); while(start < i) { occ[(int)((char)s[start])]--; if(occ[idx] == 1) { start++; break; } start++; } } } max_len = max(max_len, n - start); return max_len; } };
[ "64102513+Royal-Pal@users.noreply.github.com" ]
64102513+Royal-Pal@users.noreply.github.com
da28c46ecc98aa7a9859e9bb33f1deda64617f45
52ca17dca8c628bbabb0f04504332c8fdac8e7ea
/boost/fusion/view/reverse_view/detail/value_of_data_impl.hpp
f0b9e7645d80cc095c6a8745c3006768e97d8ea2
[]
no_license
qinzuoyan/thirdparty
f610d43fe57133c832579e65ca46e71f1454f5c4
bba9e68347ad0dbffb6fa350948672babc0fcb50
refs/heads/master
2021-01-16T17:47:57.121882
2015-04-21T06:59:19
2015-04-21T06:59:19
33,612,579
0
0
null
2015-04-08T14:39:51
2015-04-08T14:39:51
null
UTF-8
C++
false
false
96
hpp
#include "thirdparty/boost_1_58_0/boost/fusion/view/reverse_view/detail/value_of_data_impl.hpp"
[ "qinzuoyan@xiaomi.com" ]
qinzuoyan@xiaomi.com
52c03aeca2bf6fc46d2c00935b93f948dfdea21d
4e6aed2f4a4437a393d361f41dfc3db6a964f85d
/user/uploaduj_zadacu.cpp
64dd5f0b9c20471b96dde8be67ba9feed865876b
[]
no_license
zayim/eDnevnik
d42a52cdc1337836164c20a918796487678e76e9
093d4cb1f6321165d7ff2e9579a15e972ca0e019
refs/heads/master
2021-01-18T01:41:33.329235
2016-09-20T23:13:36
2016-09-20T23:13:36
68,760,724
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
2,490
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "uploaduj_zadacu.h" #include "data_module.h" #include <fstream> //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TFormUploadujZadacu *FormUploadujZadacu; //--------------------------------------------------------------------------- __fastcall TFormUploadujZadacu::TFormUploadujZadacu(TComponent* Owner) : TForm(Owner) { tamnoSiva = TColor(RGB(15,15,30)); svijetloSiva = TColor(RGB(49,49,64)); svijetloPlava = TColor(RGB(0,163,217)); Color = tamnoSiva; me_tekstZadace->Color = svijetloSiva; l_tekstZadaceNaslov->Font->Color = svijetloPlava; ed_format->Color=svijetloSiva; l_formatNaslov->Font->Color = svijetloPlava; } //--------------------------------------------------------------------------- void __fastcall TFormUploadujZadacu::FormUploadujZadacuOnShow( TObject *Sender) { dm_dataModule->qy_zadaca->Active=false; dm_dataModule->qy_zadaca->Parameters->ParamByName("id_zadace")->Value=id_zadace; dm_dataModule->qy_zadaca->Active=true; me_tekstZadace -> Text = dm_dataModule->ds_QYzadaca->DataSet->FieldByName("tekst_zadace")->AsString; ed_format->Text = dm_dataModule->ds_QYzadaca->DataSet->FieldByName("format_fajla")->AsString; } //--------------------------------------------------------------------------- void __fastcall TFormUploadujZadacu::bt_izaberiFajlClick(TObject *Sender) { od_openDialog->Execute(); std::fstream zayim(od_openDialog->FileName.c_str(),std::ios::in | std::ios::binary); zayim.read(sadrzaj,1280000); zayim.close(); } //--------------------------------------------------------------------------- void __fastcall TFormUploadujZadacu::bt_dodajZadacuClick(TObject *Sender) { AnsiString upit = AnsiString("INSERT INTO rjesenja_zadace_") + id_zadace + "(ucenik_id,fajl) VALUES(" + id_ucenika + ",'" + sadrzaj + "');"; dm_dataModule->izvrsiUpit(upit); upit = AnsiString("UPDATE ucenici_predmeti SET zadaca_status=1 WHERE predmet_id=") + id_predmeta + " AND ucenik_id=" + id_ucenika + ";"; dm_dataModule->izvrsiUpit(upit); ShowMessage("Uspješno dodano!"); this->Close(); } //---------------------------------------------------------------------------
[ "zayim92@gmail.com" ]
zayim92@gmail.com
a9521b413ebad626086ff2bd1b3465ec595ec7e9
936f628e39cbfdd5c5830ddf9ded1cf87c84d987
/vmath.h
7387dd1b510c011cd12e235b65e0279d8d595f92
[ "MIT" ]
permissive
sidharth-r/bedrock
4c938ce6b5fec715163921bc541200c276588c16
bcb999c4f0a2e44b4b10a059c89260255e335308
refs/heads/master
2020-06-22T22:13:40.281571
2017-06-25T15:44:04
2017-06-25T15:44:04
94,215,465
0
0
null
null
null
null
UTF-8
C++
false
false
348
h
#pragma once namespace vmath { struct vec2d { double x, y; }; vec2d operator+(const vec2d &a, const vec2d &b); vec2d operator-(const vec2d &a, const vec2d &b); double operator*(const vec2d &a, const vec2d &b); double magnitude(vec2d a); double angle(vec2d a, vec2d b); double angle_raw(vec2d a, vec2d b); vec2d normalize(vec2d a); };
[ "na" ]
na
ec99d2e2a21239dd440219f3cb4b95434d633a01
d7c9cffbb3e0ae1e010b6da7c69cfc90b001ef68
/LightWalker/modes/EqualizerMode.cpp
01a6c6d29a1c0c2dff2f7473963b0cd1f6d6578c
[ "Apache-2.0" ]
permissive
gerstle/LightWalker
e5012d59cb87be67940395c0c0d40efccfe5de08
e865befc119e477c0ae301ba67457cbe903b60fe
refs/heads/master
2021-01-21T04:37:01.015269
2019-07-27T23:01:25
2019-07-27T23:01:25
7,833,299
0
0
null
null
null
null
UTF-8
C++
false
false
3,456
cpp
#include "EqualizerMode.h" namespace modes { EqualizerMode::EqualizerMode(config::Properties *properties, config::LedStripConfig *config) : Mode(properties, config) { _perlinsTracker = random16(); _x = random16(); _y = random16(); _lastChangeTimer = millis(); _direction = 1; } EqualizerMode::~EqualizerMode() { } void EqualizerMode::setup() { } void EqualizerMode::frame(bool stepDetected) { float eqLevel = properties->getFloat(Preferences::eqLevel, 0.0); // 0.0 -> 1.0 int minValue = properties->getInt(eqMinValue, 100); EqMode mode = static_cast<EqMode>(properties->getInt(eqMode, EQDoubleRainbow)); CHSV color = CHSV(180, 255, 255); properties->getCHSV(Preferences::eqColor, &color); int i = 0; int lower_threshold = config->pixelHalf - (eqLevel * config->pixelHalf); int upper_threshold = (eqLevel * config->pixelHalf) + config->pixelHalf; unsigned long currentTime = millis(); if (currentTime > (_lastChangeTimer + 400)) { _lastChangeTimer = currentTime; if (random8(2) == 0) _direction = -1; else _direction = 1; } _x += (2 * _direction); _y += (2 * _direction); for (i = 0; i < config->pixelCount; i++) { // <cgerstle> this is the "OFF" if (((i <= config->pixelHalf) && (i < lower_threshold)) || ((i > config->pixelHalf) && (i > upper_threshold))) { if (minValue > 0) { _perlinsTracker += 0.0005; byte value = inoise8(_x + i * 20, _y + i * 10, _perlinsTracker); // <cgerstle> 0-255, scale down a bit value = map(value, 20, 255, 0, minValue); if (mode == EQSingleRainbow) config->pixels[i].setHSV(map(i, 0, config->pixelCount, 0, 255), 255, value); else if (mode == EQDoubleRainbow) { // <gerstle> setting config->pixels[config->pixelCount - 1 - i] to config->pixels[i] would work if half // was actually half... so, run through both sides... :( if (i < config->pixelHalf) config->pixels[i].setHSV(map(i, 0, config->pixelHalf, 0, 255), 255, value); else if (i > config->pixelHalf) config->pixels[i].setHSV(map((config->pixelCount - i - 1), 0, (config->pixelCount - config->pixelHalf - 1), 0, 255), 255, value); } else config->pixels[i].setHSV(color.hue, color.saturation, value); } else config->pixels[i] = CRGB::Black; } // <cgerstle> this is the "ON" for rainbow else if (mode == EQSingleRainbow) config->pixels[i].setHSV(map(i, 0, config->pixelCount, 0, 255), 255, 255); else if (mode == EQDoubleRainbow) { if (i <= config->pixelHalf) config->pixels[i].setHSV(map(i, 0, config->pixelHalf, 0, 255), 255, 255); else if (i > config->pixelHalf) config->pixels[i].setHSV(map((config->pixelCount - i - 1), 0, (config->pixelCount - config->pixelHalf - 1), 0, 255), 255, 255); } // <gerstle> this is the "ON" for not rainbow else config->pixels[i] = color; } } const char* EqualizerMode::getName() { return "equalizer"; } } /* namespace modes */
[ "gerstle@gmail.com" ]
gerstle@gmail.com
6b757ef73831f2fc96eb6b0e8ea25ee1dd12045b
785438e579f820f145396b31ac1be065007b5531
/GameEngines4/Engine/Core/Window.h
06e96a39dc35965bc325206c10acdc5d552e952c
[]
no_license
CharlieCharlie79/GameEngine_ParticleSystem
8fa342e0bf73235d5fef50f652351c49da26fa5d
00732dae8ddadfd168e79b971ee5affb04588718
refs/heads/main
2023-01-10T19:30:24.773058
2020-11-11T20:38:06
2020-11-11T20:38:06
311,727,175
0
0
null
null
null
null
UTF-8
C++
false
false
510
h
#ifndef WINDOW_H #define WINDOW_H #include <SDL.h> #include <glew.h> #include <SDL_opengl.h> #include <string> #include <iostream> #include "../Core/Debugger.h" class Window { public: Window(); ~Window(); bool OnCreate(std::string name_, int width_, int height_); void OnDestroy(); int GetWidth(); int GetHeight(); SDL_Window* GetWindow() const; private: void SetPreAttributes(); void SetPostAttributes(); int width; int height; SDL_Window* window; SDL_GLContext context; }; #endif
[ "carloswork067@hotmail.com" ]
carloswork067@hotmail.com
d08c184af23addd092486ff8bb1718d1d83355aa
151b2e5d2052d4275fd0cd2af50d0beb1bce2af7
/Ex1/Source.cpp
b5d049ccf6f3bf1b0479173d615ecf1b523e1da1
[]
no_license
TokyGhoul/CodeForces
e6d4931d0eb0f2437cf9059a5fc0c2b1498f14a8
d9c1ebe4eade6e4bffbacea72d4a926ef54c66ae
refs/heads/master
2021-09-02T03:25:18.081769
2017-12-29T22:54:56
2017-12-29T22:54:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
412
cpp
#include <iostream> #include <string> using namespace std; int main() { cout << ""; int n; cin >> n; string a[100]; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n; i++) { string current = a[i]; if (current.size() > 10) { cout << current[0] << current.size() - 2 << current[current.size() - 1] << endl; } else { cout << current << endl; } } //system("pause"); }
[ "oleksandrkozachukk@gmail.com" ]
oleksandrkozachukk@gmail.com
c735568c154f08efce0bb2d969d07f0fe5b71a81
c804cff06c1e8f2b31301fa40362583dba54e490
/Luolalentely/ColliderComponent.cpp
ecc18396148057df0338454e26c56f2a4b53d746
[]
no_license
Sarielius/Luolalentely
b8c00cf712a31d7978627c7a8a5a94dd42743c2d
77e7d3597ef7b273edb7894d428fa72db80a5096
refs/heads/master
2023-02-08T16:46:07.000806
2015-05-14T13:29:19
2015-05-14T13:29:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,741
cpp
#include "ColliderComponent.h" #include "SpriteComponent.h" #include "GameObject.h" #include "Convert.h" #define RADTODEG 57.295779513082320876f ColliderComponent::ColliderComponent(GameObject* g, b2World& world, sf::FloatRect dimensions) : GameComponent(g), world(world), sprite(nullptr) { SpriteComponent* temp = getOwner()->getComponent<SpriteComponent>(); if (temp) { sprite = temp->getSprite(); } b2BodyDef def; def.fixedRotation = false; def.type = b2_dynamicBody; // Change from default static def.angularDamping = 8.f; def.linearDamping = 0.7f; def.position = Convert::worldToBox2d(dimensions.left, dimensions.top); collider = world.CreateBody(&def); // Object creation in world collider->SetUserData(g); b2Vec2 vertices[3]; // Hitbox shape vertices[0].Set(0.0f, -1.0f * Convert::worldToBox2d(dimensions.height)); vertices[1].Set(0.8f * Convert::worldToBox2d(dimensions.width), 0.8f * Convert::worldToBox2d(dimensions.height)); vertices[2].Set(-0.8f * Convert::worldToBox2d(dimensions.width), 0.8f * Convert::worldToBox2d(dimensions.height)); int32 count = 3; b2PolygonShape Shape; Shape.Set(vertices, count); b2FixtureDef FixtureDef; FixtureDef.density = 0.1f; FixtureDef.friction = 0.1f; FixtureDef.restitution = 0.5f; FixtureDef.shape = &Shape; collider->CreateFixture(&FixtureDef); } ColliderComponent::~ColliderComponent() { world.DestroyBody(collider); } void ColliderComponent::update(sf::Time &elapsed) { if (sprite) { b2Vec2 pos = Convert::box2dToWorld(collider->GetPosition()); sprite->setPosition(pos.x, pos.y); sprite->setRotation(collider->GetAngle()*RADTODEG); } } void ColliderComponent::draw() { } b2Body* ColliderComponent::getBody() { return collider; }
[ "sarielirc@gmail.com" ]
sarielirc@gmail.com
897c584ff62d1aa0f6643b630e551f9f3499d69a
0a4b8d82dad4fc11c91fe148626658d72ce77092
/q243.cpp
d779080c1983751b7a3d9c24c9fe2a44e0b11087
[ "BSD-2-Clause" ]
permissive
asokolsky/oddeven
82bd1a14cd538eae9394f5a731b5e0b68d1d4eeb
c2f88f72c996f0398aa2352074d9780cd0d705ef
refs/heads/master
2023-05-15T08:43:25.440770
2023-04-29T00:10:21
2023-04-29T00:10:21
154,430,363
0
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
#include <iostream> #include <set> #include <vector> #include <algorithm> #include <numeric> using namespace std; void print(const char *msg, const vector<int> &v) { cout << msg; for(int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl; } int main() { vector <int> v = {1, 2, 3, 1, 5, 2, 1}; auto it1 = is_sorted_until(begin(v), end(v)); auto it2 = is_sorted_until(rbegin(v), rend(v)); // Максимальный суффикс (участок в конце) вектора, отсортированный по убыванию. return 0; }
[ "asokolsky@yahoo.com" ]
asokolsky@yahoo.com
9af6b233c907b4142ea10c53285af4af1cc35c0f
d56c46a1a40d32349667c5e8be5f2950a2ff5397
/9Apr/2.cpp
f79710e707aaa2bcfcced3100bedd73bc6d13087
[ "Apache-2.0" ]
permissive
s10singh97/DAA
08909ca56997043b349b2d14831d477b3eaa1e39
7eec38f14b2c4159c9dbd931f749eed565db9e4d
refs/heads/master
2020-04-17T20:50:45.763644
2019-04-15T16:06:50
2019-04-15T16:06:50
166,923,318
0
0
null
null
null
null
UTF-8
C++
false
false
2,018
cpp
// Closest Pair of points #include<iostream> #include<math.h> #include<stdlib.h> #include<float.h> using namespace std; class Point { public: int x, y; Point(){}; Point(int a, int b) { x = a; y = b; } }; int compareX(const void* a, const void* b) { Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->x - p2->x); } int compareY(const void* a, const void* b) { Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->y - p2->y); } float dist(Point p1, Point p2) { return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y)); } float bf(Point P[], int n) { float min = FLT_MAX; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) if (dist(P[i], P[j]) < min) min = dist(P[i], P[j]); return min; } float min(float x, float y) { return (x < y) ? x : y; } float stripUtil(Point strip[], int size, float d) { float min = d; qsort(strip, size, sizeof(Point), compareY); for (int i = 0; i < size; ++i) for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j) if (dist(strip[i],strip[j]) < min) min = dist(strip[i], strip[j]); return min; } float Util(Point P[], int n) { if (n <= 3) return bf(P, n); int mid = n/2; Point midp = P[mid]; float dl = Util(P, mid); float dr = Util(P + mid, n-mid); float d = min(dl, dr); Point strip[n]; int j = 0; for (int i = 0; i < n; i++) if (abs(P[i].x - midp.x) < d) strip[j] = P[i], j++; return min(d, stripUtil(strip, j, d) ); } float closest(Point P[], int n) { qsort(P, n, sizeof(Point), compareX); return Util(P, n); } int main(int argc, char const *argv[]) { Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; int n = sizeof(P) / sizeof(P[0]); cout<<"Minimum distance is: "<<closest(P, n)<<"\n"; return 0; }
[ "s10singh97@yahoo.in" ]
s10singh97@yahoo.in
4117c5c75d07af5f21afb34c87ea238d632a5fef
847cc466560422975013bc92a48d4371a4ab56ae
/tests/MatrixTests.cpp
f1f1f4104ab5c1d836a79db79b6eaa77498fd2fa
[ "Apache-2.0" ]
permissive
clement-z/MathGeoLib
baf883a30fc02bbf7ef0aa00bf0c438c6bcf824e
811b5fb0fed5fef0cf121307142781f35ac83817
refs/heads/master
2021-01-18T15:59:49.498499
2014-02-19T08:52:11
2014-02-19T08:52:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,612
cpp
#include <stdio.h> #include <stdlib.h> #include "../src/MathGeoLib.h" #include "../src/Math/myassert.h" #include "TestRunner.h" #include "TestData.h" #include "../src/Math/SSEMath.h" #include "../src/Math/float4_sse.h" #include "../src/Math/float4x4_sse.h" #include "../src/Math/float4x4_neon.h" MATH_IGNORE_UNUSED_VARS_WARNING using namespace TestData; TEST(Float3x4ScaleRow) { float3x4 m2; m2.Set(-1,-1,-1,-1, 2, 2, 2, 2, 4, 4, 4, 4); float3x4 m = float3x4::nan; m.Set(m2); // Test float3x4::Set() to properly copy data. m.ScaleRow(0, -8.f); m.ScaleRow(1, 4.f); m.ScaleRow(2, 2.f); m -= float3x4(8,8,8,8,8,8,8,8,8,8,8,8); assert(m.IsSymmetric()); assert(m.IsSkewSymmetric()); assert((m+float3x4::identity).IsIdentity()); } TEST(Float3x4SetRow) { float3x4 m; m.SetRow(0, 1,2,3,4); m.SetRow(1, float4(5,6,7,8)); float v[4] = {9,10,11,12}; m.SetRow(2, v); assert(m.Equals(float3x4(1,2,3,4, 5,6,7,8, 9,10,11,12))); } TEST(Float3x4SwapRows) { float3x4 v; v.SetIdentity(); v.SwapRows(0,1); v.SwapRows(1,2); v.SwapRows(1,0); float3x4 v3 = v; float3x4 v4 = float3x4::nan; float3x4 v2; v2.SetRotatePart(float3x3(0,0,1, 0,1,0, 1,0,0)); v2.SetTranslatePart(0,0,0); assert(v.Equals(v2)); v4 = v2; assert(v3.Equals(v4)); } Line RandomLineContainingPoint(const vec &pt); RANDOMIZED_TEST(Float3x4TransformFloat4) { Line l = RandomLineContainingPoint(POINT_VEC_SCALAR(0.f)); l.pos = POINT_VEC(float3::zero); assert(l.dir.IsNormalized()); float4 pt = POINT_TO_FLOAT4(l.GetPoint(rng.Float(-3.f, 3.f))); float3x4 rot = Quat::RandomRotation(rng).ToFloat3x4(); float4 newDir = rot.Transform(DIR_TO_FLOAT4(l.dir)); assert(newDir.w == 0.f); l.dir = FLOAT4_TO_DIR(newDir); assert(l.dir.IsNormalized(1e-1f)); l.dir.Normalize(); pt = rot.Transform(pt); assert(pt.w == 1.f); float d = l.Distance(FLOAT4_TO_POINT(pt)); assert(EqualAbs(d, 0.f)); assert(l.Contains(FLOAT4_TO_POINT(pt))); } RANDOMIZED_TEST(Float3x4TransformPosDir) { Line l = RandomLineContainingPoint(POINT_VEC_SCALAR(0.f)); l.pos = POINT_VEC(float3::zero); assert(l.dir.IsNormalized()); vec pt = l.GetPoint(rng.Float(-3.f, 3.f)); float3x4 rot = Quat::RandomRotation(rng).ToFloat3x4(); l.dir = rot.TransformDir(l.dir); assert(l.dir.IsNormalized(1e-1f)); l.dir.Normalize(); pt = POINT_VEC(rot.TransformPos(POINT_TO_FLOAT3(pt))); float d = l.Distance(pt); assert(EqualAbs(d, 0.f)); assert(l.Contains(pt)); } RANDOMIZED_TEST(Float3x4MulFloat3x4) { float3x4 m = float3x4::RandomGeneral(rng, -10.f, 10.f); float3x4 m2 = float3x4::RandomGeneral(rng, -10.f, 10.f); float3x4 m3 = m * m2; float3x4 m4; for(int i = 0; i < 4; ++i) { float4 v = float4(m2.Col(i), i < 3 ? 0.f : 1.f); v = m * v; m4.SetCol(i, v.xyz()); } assert(m3.Equals(m4)); } RANDOMIZED_TEST(Float3x4MulScalar) { float3x4 m = float3x4::RandomGeneral(rng, -10.f, 10.f); float scalar = rng.Float(-10.f, 10.f); float3x4 m2 = m * scalar; float3x4 m3 = m; m3 *= scalar; float3x4 m4; for(int i = 0; i < 12; ++i) m4.ptr()[i] = m.ptr()[i] * scalar; assert(m2.Equals(m4)); assert(m3.Equals(m4)); } RANDOMIZED_TEST(Float3x4DivScalar) { float3x4 m = float3x4::RandomGeneral(rng, -10.f, 10.f); float scalar = rng.Float(-10.f, -2.f); float3x4 m2 = m / scalar; float3x4 m3 = m; m3 /= scalar; float3x4 m4; for(int i = 0; i < 12; ++i) m4.ptr()[i] = m.ptr()[i] / scalar; assert(m2.Equals(m4)); assert(m3.Equals(m4)); } RANDOMIZED_TEST(Float3x4AddFloat3x4) { float3x4 m = float3x4::RandomGeneral(rng, -10.f, 10.f); float3x4 m2 = float3x4::RandomGeneral(rng, -10.f, 10.f); float3x4 m3 = m + m2; float3x4 m5 = m; m5 += m2; float3x4 m4; for(int y = 0; y < 3; ++y) for(int x = 0; x < 4; ++x) m4.At(y,x) = m.At(y,x) + m2.At(y,x); assert(m3.Equals(m4)); assert(m5.Equals(m4)); } TEST(Float3x3AddUnary) { float3x3 m(1,2,3, 4,5,6, 7,8,9); float3x3 m2 = +m; assert(m.Equals(m2)); } TEST(Float3x4AddUnary) { float3x4 m(1,2,3,4, 5,6,7,8, 9,10,11,12); float3x4 m2 = +m; assert(m.Equals(m2)); } TEST(Float4x4AddUnary) { float4x4 m(1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16); float4x4 m2 = +m; assert(m.Equals(m2)); } ///\todo Create and move to QuatTests.cpp TEST(QuatAddUnary) { Quat q(1,2,3,4); Quat q2 = +q; assert(q.Equals(q2)); } RANDOMIZED_TEST(Float3x4SubFloat3x4) { float3x4 m = float3x4::RandomGeneral(rng, -10.f, 10.f); float3x4 m2 = float3x4::RandomGeneral(rng, -10.f, 10.f); float3x4 m3 = m - m2; float3x4 m4; float3x4 m5 = m; m5 -= m2; for(int y = 0; y < 3; ++y) for(int x = 0; x < 4; ++x) m4.At(y,x) = m.At(y,x) - m2.At(y,x); assert(m3.Equals(m4)); assert(m5.Equals(m4)); } RANDOMIZED_TEST(Float3x4Neg) { float3x4 m = float3x4::RandomGeneral(rng, -10.f, 10.f); float3x4 m2 = -m; float3x4 m3; for(int y = 0; y < 3; ++y) for(int x = 0; x < 4; ++x) m3.At(y,x) = -m.At(y,x); assert(m2.Equals(m3)); } RANDOMIZED_TEST(Float3x3SolveAxb) { float3x3 A = float3x3::RandomGeneral(rng, -10.f, 10.f); bool mayFail = EqualAbs(A.Determinant(), 0.f, 1e-2f); float3 b = float3::RandomBox(rng, float3::FromScalar(-10.f), float3::FromScalar(10.f)); float3 x; bool success = A.SolveAxb(b, x); assert(success || mayFail); if (success) { float3 b2 = A*x; assert(b2.Equals(b, 1e-1f)); } } RANDOMIZED_TEST(Float3x3Inverse) { float3x3 A = float3x3::RandomGeneral(rng, -10.f, 10.f); bool mayFail = EqualAbs(A.Determinant(), 0.f, 1e-2f); float3x3 A2 = A; bool success = A2.Inverse(); assert(success || mayFail); if (success) { float3x3 id = A * A2; float3x3 id2 = A2 * A; assert(id.Equals(float3x3::identity, 0.3f)); assert(id2.Equals(float3x3::identity, 0.3f)); } } RANDOMIZED_TEST(Float3x3InverseFast) { float3x3 A = float3x3::RandomGeneral(rng, -10.f, 10.f); bool mayFail = EqualAbs(A.Determinant(), 0.f, 1e-2f); float3x3 A2 = A; bool success = A2.InverseFast(); assert(success || mayFail); if (success) { float3x3 id = A * A2; float3x3 id2 = A2 * A; assert(id.Equals(float3x3::identity, 0.3f)); assert(id2.Equals(float3x3::identity, 0.3f)); } } RANDOMIZED_TEST(Float4x4Ctor) { float3x3 m = float3x3::RandomGeneral(rng, -10.f, 10.f); float4x4 m2(m); for(int y = 0; y < 3; ++y) for(int x = 0; x < 3; ++x) assert2(EqualAbs(m.At(y,x), m2.At(y,x)), m.At(y,x), m2.At(y,x)); assert(EqualAbs(m2[0][3], 0.f)); assert(EqualAbs(m2[1][3], 0.f)); assert(EqualAbs(m2[2][3], 0.f)); assert(EqualAbs(m2[3][0], 0.f)); assert(EqualAbs(m2[3][1], 0.f)); assert(EqualAbs(m2[3][2], 0.f)); assert(EqualAbs(m2[3][3], 1.f)); float3x4 m3 = float3x4::RandomGeneral(rng, -10.f, 10.f); m2 = float4x4(m3); for(int y = 0; y < 3; ++y) for(int x = 0; x < 4; ++x) assert(EqualAbs(m3.At(y,x), m2.At(y,x))); assert(EqualAbs(m2[3][0], 0.f)); assert(EqualAbs(m2[3][1], 0.f)); assert(EqualAbs(m2[3][2], 0.f)); assert(EqualAbs(m2[3][3], 1.f)); } TEST(Float4x4SetRow) { float4x4 m; m.SetRow(0, 1,2,3,4); m.SetRow(1, float4(5,6,7,8)); m.SetRow(2, 9,10,11,12); m.SetRow(3, 13,14,15,16); float4x4 m3(1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16); float4x4 m2; m2.Set(1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16); assert(m.Equals(m2)); assert(m.Equals(m3)); } RANDOMIZED_TEST(Float4x4Set3x4Part) { float4x4 m = float4x4::RandomGeneral(rng, -10.f, 10.f); float4x4 m2 = m; float4x4 m4; m4 = m2; assert(m4.Equals(m2)); float3x4 m3 = float3x4::RandomGeneral(rng, -10.f, 10.f); m2.Set3x4Part(m3); for(int y = 0; y < 3; ++y) for(int x = 0; x < 4; ++x) assert(EqualAbs(m2[y][x], m3.At(y,x))); assert(EqualAbs(m2[3][0], m[3][0])); assert(EqualAbs(m2[3][1], m[3][1])); assert(EqualAbs(m2[3][2], m[3][2])); assert(EqualAbs(m2[3][3], m[3][3])); } TEST(Float4x4SwapRows) { float4x4 m(1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16); float4x4 m2(13,14,15,16, 9,10,11,12, 5,6,7,8, 1,2,3,4); m.SwapRows(0,3); m.SwapRows(1,2); assert(m.Equals(m2)); } RANDOMIZED_TEST(Float4x4AssignFloat3x4) { float4x4 m = float4x4::RandomGeneral(rng, -10.f, 10.f); float3x4 m2 = float3x4::RandomGeneral(rng, -10.f, 10.f); m = m2; for(int y = 0; y < 3; ++y) for(int x = 0; x < 4; ++x) assert(EqualAbs(m[y][x], m2.At(y,x))); assert(EqualAbs(m[3][0], 0.f)); assert(EqualAbs(m[3][1], 0.f)); assert(EqualAbs(m[3][2], 0.f)); assert(EqualAbs(m[3][3], 1.f)); } TEST(Float4x4CtorCols) { float4x4 m(float4(1,2,3,4), float4(5,6,7,8), float4(9,10,11,12), float4(13,14,15,16)); float4x4 m2(1,5,9,13, 2,6,10,14, 3,7,11,15, 4,8,12,16); assert(m.Equals(m2)); } RANDOMIZED_TEST(Float4x4CtorFromQuat) { Quat q = Quat::RandomRotation(rng); float4x4 m(q); float3 v = float3(-1, 5, 20.f); float3 v1 = q * v; float3 v2 = m.TransformPos(v); assert(v1.Equals(v2)); } RANDOMIZED_TEST(Float4x4CtorFromQuatTrans) { float3 t = float3::RandomBox(rng, float3(-SCALE, -SCALE, -SCALE), float3(SCALE, SCALE, SCALE)); Quat q = Quat::RandomRotation(rng); float4x4 m(q, t); float3 v = float3(-1, 5, 20.f); float3 v1 = q * v + t; float3 v2 = m.TransformPos(v); assert(v1.Equals(v2)); } RANDOMIZED_TEST(Float4x4Translate) { float3 t = float3::RandomBox(rng, float3(-SCALE, -SCALE, -SCALE), float3(SCALE, SCALE, SCALE)); float3 t2 = float3::RandomBox(rng, float3(-SCALE, -SCALE, -SCALE), float3(SCALE, SCALE, SCALE)); float4x4 m = float4x4::Translate(t); float4x4 m2 = float4x4::Translate(t.x, t.y, t.z); float3 v = t + t2; float3 v1 = m.TransformPos(t2); float3 v2 = m2.TransformPos(t2); assert(v1.Equals(v2)); assert(v.Equals(v1)); } TEST(Float4x4Scale) { float4x4 m = float4x4::Scale(2,4,6); float4x4 m2(2,0,0,0, 0,4,0,0, 0,0,6,0, 0,0,0,1); assert(m.Equals(m2)); } BENCHMARK(Float3x4Inverse, "float3x4::Inverse") { m[i].Float3x4Part().Inverse(); } BENCHMARK_END; BENCHMARK(Float4x4Inverse, "float4x4::Inverse") { m[i].Inverse(); } BENCHMARK_END; #ifdef MATH_SSE BENCHMARK(inverse_ps, "test against Float4x4Inverse") { mat4x4_inverse(m[i].row, m[i].row); } BENCHMARK_END; #endif BENCHMARK(float4x4_InverseOrthogonalUniformScale, "float4x4::InverseOrthogonalUniformScale") { m[i] = ogm[i]; m[i].InverseOrthogonalUniformScale(); } BENCHMARK_END; BENCHMARK(float4x4_InverseOrthonormal, "float4x4::InverseOrthonormal") { m[i] = om[i]; m[i].InverseOrthonormal(); } BENCHMARK_END; BENCHMARK(float3x4_InverseOrthonormal, "float3x4::InverseOrthonormal") { m[i].Float3x4Part() = om[i].Float3x4Part(); m[i].Float3x4Part().InverseOrthonormal(); } BENCHMARK_END; #ifdef MATH_SSE RANDOMIZED_TEST(mat_inverse_orthonormal_correctness) { float4x4 m = float4x4(Quat::RandomRotation(rng), float3::RandomDir(rng)); float4x4 m2 = m; float4x4 m3 = m; m2.InverseOrthonormal(); mat3x4_inverse_orthonormal(m3.row, m3.row); assert(m2.Equals(m3)); } BENCHMARK(mat3x4_inverse_orthonormal, "test against float3x4_InverseOrthonormal") { mat3x4_inverse_orthonormal(m[i].row, m[i].row); } BENCHMARK_END; #endif float RelError(const float4x4 &m1, const float4x4 &m2) { float relError = 0.f; for(int y = 0; y < 4; ++y) for(int x = 0; x < 4; ++x) relError = Max(relError, m1[y][x], m2[y][x]); return relError; } float AbsError(const float4x4 &m1, const float4x4 &m2) { float absError = 0.f; for(int y = 0; y < 4; ++y) for(int x = 0; x < 4; ++x) absError = Max(absError, Abs(m1[y][x] - m2[y][x])); return absError; } #ifdef MATH_SSE UNIQUE_TEST(mat_inverse_correctness) { float maxRelError = 0.f; float maxAbsError = 0.f; for(int k = 0; k < 2; ++k) { for(int i = 0; i < 10000; ++i) { float4x4 m; if (k == 0) m = float3x4::RandomRotation(rng); else m = float4x4::RandomGeneral(rng, -1.f, 1.f); if (m.IsInvertible()) { float4x4 m2 = m.Inverted(); float4x4 m3 = m; mat4x4_inverse(m3.row, m3.row); maxRelError = Max(maxRelError, RelError(m2, m3)); maxAbsError = Max(maxAbsError, AbsError(m2, m3)); } } if (k == 0) LOGI("mat4x4_inverse max. relative error with rotation matrices: %f, Max abs error: %f", maxRelError, maxAbsError); else LOGI("mat4x4_inverse max. relative error with general [0,1] matrices: %f, Max abs error: %f", maxRelError, maxAbsError); } } UNIQUE_TEST(mat_determinant_correctness) { float maxRelError = 0.f; float maxAbsError = 0.f; for(int k = 0; k < 2; ++k) { for(int i = 0; i < 10000; ++i) { float4x4 m; if (k == 0) m = float3x4::RandomRotation(rng); else m = float4x4::RandomGeneral(rng, -1.f, 1.f); float d = m.Determinant4(); float d2 = mat4x4_determinant(m.row); maxRelError = Max(maxRelError, RelativeError(d, d2)); maxAbsError = Max(maxAbsError, Abs(d - d2)); } if (k == 0) LOGI("mat4x4_determinant max. relative error with rotation matrices: %f, Max abs error: %f", maxRelError, maxAbsError); else LOGI("mat4x4_determinant max. relative error with general [0,1] matrices: %f, Max abs error: %f", maxRelError, maxAbsError); } } UNIQUE_TEST(mat_determinant3_correctness) { float maxRelError = 0.f; float maxAbsError = 0.f; for(int k = 0; k < 2; ++k) { for(int i = 0; i < 10000; ++i) { float4x4 m; if (k == 0) m = float3x4::RandomRotation(rng); else m = float4x4::RandomGeneral(rng, -1.f, 1.f); float d = m.Determinant3(); float d2 = mat3x4_determinant(m.row); maxRelError = Max(maxRelError, RelativeError(d, d2)); maxAbsError = Max(maxAbsError, Abs(d - d2)); } if (k == 0) LOGI("mat3x4_determinant max. relative error with rotation matrices: %f, Max abs error: %f", maxRelError, maxAbsError); else LOGI("mat3x4_determinant max. relative error with general [0,1] matrices: %f, Max abs error: %f", maxRelError, maxAbsError); } } #endif BENCHMARK(float4x4_Determinant3, "float4x4::Determinant3") { f[i] = m[i].Determinant3(); } BENCHMARK_END; BENCHMARK(float4x4_Determinant4, "float4x4::Determinant4") { f[i] = m[i].Determinant4(); } BENCHMARK_END; UNIQUE_TEST(float4x4_Determinant_Correctness) { float4x4 m(1,0,0,0, 2,2,0,0, 3,3,3,0, 4,4,4,4); asserteq(m.Determinant3(), 6.f); asserteq(m.Determinant4(), 24.f); asserteq(m.Float3x3Part().Determinant(), 6.f); asserteq(m.Float3x4Part().Determinant(), 6.f); } #ifdef MATH_SSE BENCHMARK(mat4x4_determinant, "test against float4x4_Determinant4") { f[i] = mat4x4_determinant(m[i].row); } BENCHMARK_END; BENCHMARK(mat3x4_determinant, "test against float3x4_Determinant") { f[i] = mat3x4_determinant(m[i].row); } BENCHMARK_END; #endif BENCHMARK(float4x4_op_mul, "float4x4 * float4x4") { m2[i] = m[i] * m2[i]; } BENCHMARK_END; #ifdef MATH_SIMD BENCHMARK(mat4x4_mul_mat4x4, "test against float4x4_op_mul") { mat4x4_mul_mat4x4(m2[i].row, m[i].row, m2[i].row); } BENCHMARK_END; #ifdef ANDROID BENCHMARK(mat4x4_mul_mat4x4_asm, "test against float4x4_op_mul") { mat4x4_mul_mat4x4_asm(m2[i].row, m[i].row, m2[i].row); } BENCHMARK_END; #endif RANDOMIZED_TEST(mat4x4_mul_mat4x4) { float4x4 m = float4x4::RandomGeneral(rng, -10.f, 10.f); float4x4 m2 = float4x4::RandomGeneral(rng, -10.f, 10.f); float4x4 m3; mat4x4_mul_mat4x4(m3.row, m.row, m2.row); float4x4 correct = m*m2; assert(m3.Equals(correct)); } #ifdef ANDROID RANDOMIZED_TEST(mat4x4_mul_mat4x4_asm) { float4x4 m = float4x4::RandomGeneral(rng, -10.f, 10.f); float4x4 m2 = float4x4::RandomGeneral(rng, -10.f, 10.f); float4x4 m3; mat4x4_mul_mat4x4_asm(m3.row, m.row, m2.row); float4x4 correct = m*m2; assert(m3.Equals(correct)); } #endif BENCHMARK(float4x4_Transposed, "float4x4::Transposed") { m2[i] = m[i].Transposed(); } BENCHMARK_END; #if !defined(ANDROID) ///\bug Android GCC 4.6.6 gives internal compiler error! BENCHMARK(mat4x4_transpose, "test against float4x4_Transposed") { mat4x4_transpose(m2[i].row, m[i].row); } BENCHMARK_END; #endif #if !defined(ANDROID) ///\bug Android GCC 4.6.6 gives internal compiler error! RANDOMIZED_TEST(mat4x4_transpose) { float4x4 m = float4x4::RandomGeneral(rng, -10.f, 10.f); float4x4 correct = m.Transposed(); float4x4 m2; mat4x4_transpose(m2.row, m.row); mat4x4_transpose(m.row, m.row); assert(m.Equals(correct)); assert(m2.Equals(correct)); } #endif BENCHMARK(float4x4_mul_float4, "float4x4 * float4") { v2[i] = m[i] * v[i]; } BENCHMARK_END; BENCHMARK(float4_mul_float4x4, "float4 * float4x4") { v2[i] = v[i] * m[i]; } BENCHMARK_END; #if !defined(ANDROID) ///\bug Android GCC 4.6.6 gives internal compiler error! BENCHMARK(mat4x4_mul_vec4, "test against float4x4_mul_float4") { v2[i] = mat4x4_mul_vec4(m[i].row, v[i].v); } BENCHMARK_END; #endif BENCHMARK(vec4_mul_mat4x4, "test against float4_mul_float4x4") { v2[i] = vec4_mul_mat4x4(v[i].v, m[i].row); } BENCHMARK_END; #if !defined(ANDROID) ///\bug Android GCC 4.6.6 gives internal compiler error! RANDOMIZED_TEST(mat4x4_mul_vec4) { float4x4 m = float4x4::RandomGeneral(rng, -10.f, 10.f); float4 v = float4::RandomGeneral(rng, -10.f, 10.f); float4 correct = m*v; float4 v2 = mat4x4_mul_vec4(m.row, v.v); assert(v2.Equals(correct)); } #endif RANDOMIZED_TEST(vec4_mul_mat4x4) { float4x4 m = float4x4::RandomGeneral(rng, -10.f, 10.f); float4 v = float4::RandomGeneral(rng, -10.f, 10.f); float4 correct = v*m; float4 v2 = vec4_mul_mat4x4(v.v, m.row); assert(v2.Equals(correct)); } #endif BENCHMARK(matrix_copy0, "matrix-copy-default") { m2[i] = m[i]; } BENCHMARK_END; BENCHMARK(matrix_copy1, "matrix-copy-memcpy") { memcpy(&m2[i], &m[i], sizeof(float4x4)); } BENCHMARK_END; BENCHMARK(matrix_copy2, "matrix-copy-for-loop") { float *dst = (float*)&m2[i]; float *src = (float*)&m[i]; for(int j = 0; j < 16; ++j) dst[j] = src[j]; } BENCHMARK_END; BENCHMARK(matrix_copy3, "matrix-copy-unrolled") { float *dst = (float*)&m2[i]; float *src = (float*)&m[i]; dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; dst[8] = src[8]; dst[9] = src[9]; dst[10] = src[10]; dst[11] = src[11]; dst[12] = src[12]; dst[13] = src[13]; dst[14] = src[14]; dst[15] = src[15]; } BENCHMARK_END; #ifdef MATH_SSE BENCHMARK(matrix_copy4, "matrix-copy-sse") { simd4f *dst = (simd4f *)&m2[i]; simd4f *src = (simd4f *)&m[i]; for (int j = 0; j < 4; ++j) dst[j] = src[j]; } BENCHMARK_END; BENCHMARK(matrix_copy5, "matrix-copy-sse-unrolled") { simd4f *dst = (simd4f *)&m2[i]; simd4f *src = (simd4f *)&m[i]; dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } BENCHMARK_END; #endif #ifdef MATH_AVX BENCHMARK(matrix_copy6, "matrix-copy-avx") { __m256 *dst = (__m256 *)&m2[i]; __m256 *src = (__m256 *)&m[i]; for (int j = 0; j < 2; ++j) dst[j] = src[j]; } BENCHMARK_END; BENCHMARK(matrix_copy7, "matrix-copy-avx-unrolled") { __m256 *dst = (__m256 *)&m2[i]; __m256 *src = (__m256 *)&m[i]; dst[0] = src[0]; dst[1] = src[1]; } BENCHMARK_END; #endif
[ "jujjyl@gmail.com" ]
jujjyl@gmail.com
e3a77c8a7e6807f222896e5242c8f65c57b22b7f
bc7b44dfa96345c92d15951c42576d33c3ec6558
/URI/1221.cpp
8ddbf71220648a5b0d1fcd7030cdd220911b27ec
[]
no_license
cjlcarvalho/maratona
e1a29bc90701e808ff395e7452e7fffc8411fac9
e16b95c5d831dc48a3d8c69781f757b210e66730
refs/heads/master
2022-02-22T13:07:53.897259
2022-02-12T00:42:02
2022-02-12T00:42:02
91,300,520
2
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
#include <bits/stdc++.h> using namespace std; bool isPrime(int64_t n){ if(n < 2) return false; // se for menor que 2 if(n <= 3) return true; // se for 2 ou 3 if(!(n%2) || !(n%3)) return false; // se n%2 ou n%3 derem 0 for(int64_t i = 5; i*i <= n; i+=6) if(!(n%i) || !(n%(i+2))) return false; return true; } int main(){ int n; int64_t x; cin >> n; while(n--){ cin >> x; if(isPrime(x)) cout << "Prime" << endl; else cout << "Not Prime" << endl; } return 0; }
[ "cjlcarvalho@live.com" ]
cjlcarvalho@live.com
20af93c0f3e33e7e68148c79a0b1a86cc355a95a
97aa1181a8305fab0cfc635954c92880460ba189
/torch/csrc/jit/frontend/exit_transforms.h
abffd65634ad41d801c52e732e3894a5daa9208d
[ "BSD-2-Clause" ]
permissive
zhujiang73/pytorch_mingw
64973a4ef29cc10b96e5d3f8d294ad2a721ccacb
b0134a0acc937f875b7c4b5f3cef6529711ad336
refs/heads/master
2022-11-05T12:10:59.045925
2020-08-22T12:10:32
2020-08-22T12:10:32
123,688,924
8
4
NOASSERTION
2022-10-17T12:30:52
2018-03-03T12:15:16
C++
UTF-8
C++
false
false
232
h
#pragma once #include <torch/csrc/WindowsTorchApiMacro.h> #include <torch/csrc/jit/ir/ir.h> namespace torch { namespace jit { TORCH_API void TransformExits(std::shared_ptr<Graph>& graph); } // namespace jit } // namespace torch
[ "zhujiangmail@hotmail.com" ]
zhujiangmail@hotmail.com
04120b5aa1e75fc2cc06a87424af6625f9b460ae
30de1715726832afc55714216139c9d11735044e
/Suggestion.cpp
e084ca7665654e678d9b63b6ca8a69abbb00d410
[]
no_license
mcbridez-oregonstate-edu/OSUClue
a98404295a4268d12c0d7677a34ffb84d3789277
3726f89856953bcd9b197afcfbd62a56bbb8b801
refs/heads/master
2022-10-30T11:10:33.988273
2020-06-08T06:29:45
2020-06-08T06:29:45
254,716,374
0
0
null
null
null
null
UTF-8
C++
false
false
11,127
cpp
/************************************************************************************************ * Program Name: Suggestion.hpp * Date: 6/3/20 * Author: Adam Pham (with modifications by Abigail Minchella) * Description: The header file for the Suggestion class. ************************************************************************************************/ #include "Suggestion.hpp" #include <iostream> using std::cout; using std::endl; /************************************************************************************************ Suggestion::Suggestion(sf::Font* font) * Description: The constructor for Suggestion ************************************************************************************************/ Suggestion::Suggestion(sf::Font* font) { b_people = createButtonArray(0); b_weapons = createButtonArray(1); b_rooms = createButtonArray(2); suggestionText.setFont(*font); suggestionText.setCharacterSize(40); suggestionText.setPosition(sf::Vector2f(350, 25)); suspect = "NONE"; weapon = "NONE"; revealedCard = "NONE"; revealedCardButton = nullptr; } /*********************************************************************************************** void Suggestion::suggestSuspect(const sf::Vector2f mouse) * Description: Gets the suspect suggested by the player ***********************************************************************************************/ void Suggestion::suggestSuspect(const sf::Vector2f mouse) { for (int i = 0; i < b_people.size(); i++) { b_people[i]->update(mouse); if (b_people[i]->isPressed()) { suspect = b_people[i]->getName(); } } } /*********************************************************************************************** void Suggestion::suggestWeapon(const sf::Vector2f mouse) * Description: Gets the weapon suggested by the player ***********************************************************************************************/ void Suggestion::suggestWeapon(const sf::Vector2f mouse) { for (int i = 0; i < b_weapons.size(); i++) { b_weapons[i]->update(mouse); if (b_weapons[i]->isPressed()) { weapon = b_weapons[i]->getName(); } } } /************************************************************************************************ void Suggestion::findRevealCards(string suspect, string weapon, string room, vector<Card> cards) * Description: Figures out which cards are in the player's hand that match the suggestion. ************************************************************************************************/ void Suggestion::findRevealCards(string suspect, string weapon, string room, vector<Card> cards) { for (int i = 0; i < cards.size(); i++) { if (cards[i].getName() == suspect || cards[i].getName() == weapon || cards[i].getName() == room) { for (int j = 0; j < b_people.size(); j++) { if (b_people[j]->getName() == cards[i].getName()) { suggestCards.push_back(b_people[j]); } } for (int j = 0; j < b_weapons.size(); j++) { if (b_weapons[j]->getName() == cards[i].getName()) { suggestCards.push_back(b_weapons[j]); } } for (int j = 0; j < b_rooms.size(); j++) { if (b_rooms[j]->getName() == cards[i].getName()) { suggestCards.push_back(b_rooms[j]); } } } } if (suggestCards.size() == 1) { suggestCards[0]->setButtonPos(sf::Vector2f(575, 140)); } else if (suggestCards.size() == 2) { suggestCards[0]->setButtonPos(sf::Vector2f(475, 140)); suggestCards[1]->setButtonPos(sf::Vector2f(675, 140)); } else { suggestCards[0]->setButtonPos(sf::Vector2f(375, 140)); suggestCards[1]->setButtonPos(sf::Vector2f(575, 140)); suggestCards[2]->setButtonPos(sf::Vector2f(775, 140)); } } /**************************************************************************************************************** void Suggestion::chooseRevealCard(const sf::Vector2f mouse) * Description: Allows the revealing player to choose the card to reveal ****************************************************************************************************************/ void Suggestion::chooseRevealCard(const sf::Vector2f mouse) { for (int i = 0; i < suggestCards.size(); i++) { suggestCards[i]->update(mouse); if (suggestCards[i]->isPressed()) { revealedCard = suggestCards[i]->getName(); } } } /************************************************************************************************ void Suggestion::showRevealCard(string cardName, string revealingPlayer) * Description: Shows the revealed card to the suggesting player ************************************************************************************************/ void Suggestion::showRevealCard(string cardName, string revealingPlayer) { suggestionText.setString(revealingPlayer + " revealed: (Press Enter to continue...)"); suggestionText.setPosition(sf::Vector2f(350, 25)); for (int i = 0; i < b_people.size(); i++) { if (b_people[i]->getName() == cardName) { revealedCardButton = b_people[i]; } } for (int i = 0; i < b_weapons.size(); i++) { if (b_weapons[i]->getName() == cardName) { revealedCardButton = b_weapons[i]; } } for (int i = 0; i < b_rooms.size(); i++) { if (b_rooms[i]->getName() == cardName) { revealedCardButton = b_rooms[i]; } } revealedCardButton->setButtonPos(sf::Vector2f(575, 340)); } /************************************************************************************************ string Suggestion::getSuspect() * Description: Returns the suspect suggested by the player ************************************************************************************************/ string Suggestion::getSuspect() { return suspect; } /************************************************************************************************ string Suggestion::getWeapon() * Description: Returns the weapon suggested by the player ************************************************************************************************/ string Suggestion::getWeapon() { return weapon; } /************************************************************************************************ string Suggestion::getRevealCard() * Description: Returns the card chosen to be revealed by the player ************************************************************************************************/ string Suggestion::getRevealCard() { return revealedCard; } /************************************************************************************************ void Suggestion::renderSuspects(sf::RenderTarget* window) * Description: Renders the suggestion buttons to the target window ************************************************************************************************/ void Suggestion::renderSuspects(sf::RenderTarget* window) { suggestionText.setString("Suggestion: Choose a Suspect and press Enter"); suggestionText.setPosition(sf::Vector2f(350, 25)); window->draw(suggestionText); for (int i = 0; i < b_people.size(); i++) { b_people[i]->resetPos(); b_people[i]->render(window); } } /************************************************************************************************ void Suggestion::renderWeapons(sf::RenderTarget* window) * Description: Renders the suggestion buttons to the target window ************************************************************************************************/ void Suggestion::renderWeapons(sf::RenderTarget* window) { suggestionText.setString("Suggestion: Choose a Weapon and press Enter"); suggestionText.setPosition(sf::Vector2f(350, 25)); window->draw(suggestionText); for (int i = 0; i < b_weapons.size(); i++) { b_weapons[i]->resetPos(); b_weapons[i]->render(window); } } /************************************************************************************************************* void Suggestion::renderSuggestion(sf::RenderTarget* window, string suspect, string weapon, string room) * Description: Renders the player's suggestion to the target window *************************************************************************************************************/ void Suggestion::renderSuggestion(sf::RenderTarget* window, string room) { suggestionText.setString("You have Suggested: (Press 'Enter' to continue . . .)"); suggestionText.setPosition(sf::Vector2f(350, 25)); window->draw(suggestionText); int suspectNum = -1; int weaponNum = -1; int roomNum = -1; for (int i = 0; i < b_people.size(); i++) { if (b_people[i]->getName() == suspect) { suspectNum = i; } } for (int i = 0; i < b_weapons.size(); i++) { if (b_weapons[i]->getName() == weapon) { weaponNum = i; } } for (int i = 0; i < b_rooms.size(); i++) { if (b_rooms[i]->getName() == room) { roomNum = i; } } b_people[suspectNum]->setButtonPos(sf::Vector2f(375, 140)); b_people[suspectNum]->setIdle(); b_people[suspectNum]->render(window); b_weapons[weaponNum]->setButtonPos(sf::Vector2f(575, 140)); b_weapons[weaponNum]->setIdle(); b_weapons[weaponNum]->render(window); b_rooms[roomNum]->setButtonPos(sf::Vector2f(775, 140)); b_rooms[roomNum]->render(window); } /************************************************************************************************************* void Suggestion::renderRevealChoice(sf::RenderTarget* window, string suspect, string weapon, string room) * Description: Renders the buttons for the revealing player to choose their reveal with *************************************************************************************************************/ void Suggestion::renderRevealChoice(sf::RenderTarget* window) { suggestionText.setString("Choose a card to reveal and press Enter:"); suggestionText.setPosition(sf::Vector2f(400, 25)); for (int i = 0; i < suggestCards.size(); i++) { suggestCards[i]->render(window); } window->draw(suggestionText); } /**************************************************************************************** void Suggestion::renderReveal(sf::RenderTarget* window) * Description: Renders the objects for the card reveal in the target window ****************************************************************************************/ void Suggestion::renderReveal(sf::RenderTarget* window) { window->draw(suggestionText); revealedCardButton->render(window); } /**************************************************************************************** void Suggestion::reset() * Description: Resets the variables and positions of objects so that the next time * a suggestion is made, things don't get wonky. ****************************************************************************************/ void Suggestion::reset() { suspect = "NONE"; weapon = "NONE"; revealedCard = "NONE"; revealedCardButton = nullptr; suggestCards.clear(); for (int j = 0; j < b_people.size(); j++) { b_people[j]->resetPos(); b_people[j]->setIdle(); } for (int j = 0; j < b_weapons.size(); j++) { b_weapons[j]->resetPos(); b_weapons[j]->setIdle(); } for (int j = 0; j < b_rooms.size(); j++) { b_rooms[j]->resetPos(); b_rooms[j]->setIdle(); } }
[ "56110943+this-is-my-serious-account@users.noreply.github.com" ]
56110943+this-is-my-serious-account@users.noreply.github.com
551aad65476ba97aa156610ddbf1b9623cbd49f2
fb408595c1edee0be293302c6d7bfc0c77d37c46
/c++/Dijkstra/Graph.h
631887b49744cb53b7441707a73dabcd996060f7
[]
no_license
as950118/Algorithm
39ad25519fd0e42b90ddf3797a61239862ad79b5
739a7d4b569057cdb6b6faa74254512b83d02bb1
refs/heads/master
2023-07-21T12:38:00.653579
2023-07-19T06:57:17
2023-07-19T06:57:17
125,176,176
1
0
null
null
null
null
UTF-8
C++
false
false
2,760
h
#ifndef GRAPH_H #define GRAPH_H #include <unordered_map> #include <queue> #include <functional> #include <climits> #include "Vertex.h" using namespace std; class Graph { unordered_map<int, Vertex> _vertices; public: void addVertex(Vertex vertex) { _vertices[vertex.getId()] = vertex; } //MA #12 TODO: IMPLEMENT! unordered_map<Vertex, int> computeShortestPath(Vertex *start) { //holds known distances unordered_map<Vertex, int> distances; unordered_map<Vertex, bool> known; // initiate distances to inf for (auto vertex : _vertices) { distances[vertex.second.getId()] = INT_MAX; } //underlying heap priority_queue<Vertex, vector<Vertex>, PathWeightComparer> dijkstra_queue{}; //reset start's path weight start->setPathWeight(0); //make sure that the starting vertex is in the graph if (containsVertex(*start)) { //push on starting vertex dijkstra_queue.push(_vertices[start->getId()]); distances[_vertices[start->getId()]] = 0; known[_vertices[start->getId()]] = true; //while queue not empty while (!dijkstra_queue.empty()) { auto vert = dijkstra_queue.top(); auto edges = vert.getEdges(); dijkstra_queue.pop(); for (auto ed : edges) // For each edge adjacent to the vertex { if (vert.getEdgeWeight(ed.first) + vert.getPathWeight() < distances[ed.first->getId()]) // if this path is less than current distance logged { // update new path weight _vertices[ed.first->getId()].setPathWeight(vert.getEdgeWeight(ed.first) + vert.getPathWeight()); // update new distance to vertice distances[ed.first->getId()] = vert.getEdgeWeight(ed.first) + vert.getPathWeight(); } // push vertice onto priority queue if (known[_vertices[ed.first->getId()]] == false) { known[_vertices[ed.first->getId()]] = true; dijkstra_queue.push(_vertices[ed.first->getId()]); } } //Top of heap not known (in distances)? //make known } //push on outgoing edges } return distances; } bool containsVertex(Vertex vert) { bool contains = false; for (auto vertex : _vertices) { if (vertex.second == vert) { contains = true; break; } } return contains; } }; #endif
[ "ideo@DESKTOP-5HB9EDT.localdomain" ]
ideo@DESKTOP-5HB9EDT.localdomain
c2d16aa8cafbc0154ca6318d089a304f90f06186
3778ea723990be084aaf8db7260f6a73d5667e32
/BallTree.cpp
115868b3e48acfabc79560a4b31e901a27f564ee
[]
no_license
quangloc99/demo_fast_feature_matching_using_method_SSD
a8343b864c5356b0c5039c4c9f8e1393588e3e69
ae40711bc1f353ed7306d0904a54bc23cbaf61cc
refs/heads/master
2020-03-21T21:05:45.216873
2018-06-28T17:03:13
2018-06-28T17:03:13
139,045,880
1
0
null
null
null
null
UTF-8
C++
false
false
3,599
cpp
#include <algorithm> #include <cassert> #include <iostream> #include <cmath> #include <utility> #include "BallTree.hpp" using namespace std; float distance(const vector<float>& a, const vector<float>& b) { float ans = 0; for (int i = a.size(); i--; ) { float t = a[i] - b[i]; ans += t * t; } return sqrt(ans); } struct BallTreeNode { int pivot; float radius; BallTreeNode *left, *right; vector<int> pointList; BallTreeNode(int id, float rad) : pivot(id) , radius(rad) , left(NULL) , right(NULL) {} ~BallTreeNode() { if (this->left) delete this->left; if (this->right) delete this->right; } }; BallTree::BallTree(const vector<vector<float>>& _points, int leafCapacity) : points(_points) , leafCapacity(leafCapacity) { int *idx = new int[_points.size()]; for (int i = _points.size(); i--; ) { idx[i] = i; } this->root = this->build(idx, _points.size()); delete[] idx; } BallTreeNode* BallTree::build(int *idx, int n) { if (n <= 0) return NULL; int dimension = 0; float maxSpread = 0; float minDimensionVal; for (int f = this->points[0].size(); f--; ) { float minval = this->points[idx[0]][f]; float maxval = minval; for (int i = n; i--; ) { int trueI = idx[i]; minval = min(minval, this->points[trueI][f]); maxval = max(maxval, this->points[trueI][f]); } float spread = maxval - minval; if (spread > maxSpread) { maxSpread = spread; dimension = f; minDimensionVal = minval; } } int centerPoint = idx[0]; float dis = abs(this->points[centerPoint][dimension] - minDimensionVal - maxSpread / 2); for (int i = 1; i < n; ++i) { int trueI = idx[i]; float td = abs(this->points[trueI][dimension] - minDimensionVal - maxSpread / 2); if (td > dis) continue; centerPoint = trueI; dis = td; } float radius = 0; for (int i = n; i--; ) { int trueI = idx[i]; radius = max(radius, distance(this->points[trueI], this->points[centerPoint])); } BallTreeNode* ans = new BallTreeNode(centerPoint, radius); if (n <= this->leafCapacity) { ans->pointList.insert(ans->pointList.end(), idx, idx + n); return ans; } auto comparator = [&](int u, int v) -> bool { return this->points[u][dimension] < this->points[v][dimension]; }; nth_element(idx, idx + n / 2, idx + n, comparator); ans->left = this->build(idx, n / 2); ans->right = this->build(idx + n / 2, n - n / 2); return ans; } BallTree::~BallTree() { delete this->root; } void BallTree::nearestNeighbor( const vector<float>& point, priority_queue<pair<float, int>>& pq, int k /* 1 */ ) { this->nearestNeighbor(this->root, point, pq, k); } void BallTree::nearestNeighbor( BallTreeNode* node, const vector<float>& point, priority_queue<pair<float, int>>& pq, int k ) { if (!node) return ; vector<float>& pivot = this->points[node->pivot]; float dis = distance(pivot, point); float threshold = pq.size() ? pq.top().first : dis; if (dis - node->radius > threshold and pq.size() == k) return; if (!node->left && !node->right) { // is leaf for (auto i: node->pointList) { float d = distance(this->points[i], point); pq.push({d, i}); if (pq.size() > k) pq.pop(); } return ; } float dis1 = 0, dis2 = 0; dis1 = distance(point, this->points[node->left->pivot]); dis2 = distance(point, this->points[node->right->pivot]); if (dis1 > dis2) swap(node->left, node->right); this->nearestNeighbor(node->left, point, pq, k); this->nearestNeighbor(node->right, point, pq, k); }
[ "phongcachhiphop@gmail.com" ]
phongcachhiphop@gmail.com
25e97f6b3b8772b13141f17a4ad481320406d9a5
71514a039ef28f7d4cbb6655be57440f0fbd67c0
/interfaces/innerkits/native/include/media_lib_service_const.h
8cd1828f2c9eefc160f90dc9beb9ae559422018c
[ "Apache-2.0" ]
permissive
chaoyangcui/multimedia_medialibrary_standard
d18fda9d4c1dbd690c190af952825b7e0451d8f6
4b3db4e3c2796179f3a6dd7ce5fca6c0993e7da6
refs/heads/master
2023-08-09T18:18:00.412771
2021-09-09T10:34:11
2021-09-09T10:34:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,015
h
/* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MEDIA_LIB_SERVICE_CONST_H #define MEDIA_LIB_SERVICE_CONST_H #include <unordered_set> namespace OHOS { namespace Media { enum { MEDIA_GET_MEDIA_ASSETS = 0, MEDIA_GET_IMAGE_ASSETS = 1, MEDIA_GET_AUDIO_ASSETS = 2, MEDIA_GET_VIDEO_ASSETS = 3, MEDIA_GET_IMAGEALBUM_ASSETS = 4, MEDIA_GET_VIDEOALBUM_ASSETS = 5, MEDIA_CREATE_MEDIA_ASSET = 6, MEDIA_DELETE_MEDIA_ASSET = 7, MEDIA_MODIFY_MEDIA_ASSET = 8, MEDIA_COPY_MEDIA_ASSET = 9, MEDIA_CREATE_MEDIA_ALBUM_ASSET = 10, MEDIA_DELETE_MEDIA_ALBUM_ASSET = 11, MEDIA_MODIFY_MEDIA_ALBUM_ASSET = 12, }; enum MediaType { MEDIA_TYPE_DEFAULT = 0, MEDIA_TYPE_FILE, MEDIA_TYPE_MEDIA, MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, MEDIA_TYPE_AUDIO, MEDIA_TYPE_ALBUM_LIST, MEDIA_TYPE_ALBUM_LIST_INFO }; /* ENUM Asset types */ enum AssetType { ASSET_MEDIA = 0, ASSET_IMAGE, ASSET_AUDIO, ASSET_VIDEO, ASSET_GENERIC_ALBUM, ASSET_IMAGEALBUM, ASSET_VIDEOALBUM, ASSET_NONE }; const int32_t SUCCESS = 0; const int32_t FAIL = -1; const int32_t MEDIA_ASSET_READ_FAIL = 1; const int32_t IMAGE_ASSET_READ_FAIL = 2; const int32_t AUDIO_ASSET_READ_FAIL = 3; const int32_t VIDEO_ASSET_READ_FAIL = 4; const int32_t IMAGEALBUM_ASSET_READ_FAIL = 5; const int32_t VIDEOALBUM_ASSET_READ_FAIL = 6; const int32_t MEDIA_ASSET_WRITE_FAIL = 7; const int32_t IMAGE_ASSET_WRITE_FAIL = 8; const int32_t AUDIO_ASSET_WRITE_FAIL = 9; const int32_t VIDEO_ASSET_WRITE_FAIL = 10; const int32_t IMAGEALBUM_ASSET_WRITE_FAIL = 11; const int32_t VIDEOALBUM_ASSET_WRITE_FAIL = 12; const int32_t ALBUM_ASSET_WRITE_FAIL = 13; const int32_t COMMON_DATA_WRITE_FAIL = 14; const int32_t COMMON_DATA_READ_FAIL = 15; const int32_t DEFAULT_MEDIA_ID = 0; const int32_t DEFAULT_ALBUM_ID = 0; const uint64_t DEFAULT_MEDIA_SIZE = 0; const uint64_t DEFAULT_MEDIA_DATE_ADDED = 0; const uint64_t DEFAULT_MEDIA_DATE_MODIFIED = 0; const std::string DEFAULT_MEDIA_URI = ""; const MediaType DEFAULT_MEDIA_TYPE = MEDIA_TYPE_FILE; const std::string DEFAULT_MEDIA_NAME = "Unknown"; const std::string DEFAULT_ALBUM_NAME = "Unknown"; const std::string ROOT_MEDIA_DIR = "/data/media"; const char SLASH_CHAR = '/'; const int OPEN_FDS = 64; const int32_t MILLISECONDS = 1000; const char DOT_CHAR = '.'; /** Supported audio container types */ const std::string AUDIO_CONTAINER_TYPE_AAC = "aac"; const std::string AUDIO_CONTAINER_TYPE_MP3 = "mp3"; const std::string AUDIO_CONTAINER_TYPE_FLAC = "flac"; const std::string AUDIO_CONTAINER_TYPE_WAV = "wav"; const std::string AUDIO_CONTAINER_TYPE_OGG = "ogg"; /** Supported video container types */ const std::string VIDEO_CONTAINER_TYPE_MP4 = "mp4"; const std::string VIDEO_CONTAINER_TYPE_3GP = "3gp"; const std::string VIDEO_CONTAINER_TYPE_MPG = "mpg"; const std::string VIDEO_CONTAINER_TYPE_MOV = "mov"; const std::string VIDEO_CONTAINER_TYPE_WEBM = "webm"; const std::string VIDEO_CONTAINER_TYPE_MKV = "mkv"; /** Supported image types */ const std::string IMAGE_CONTAINER_TYPE_BMP = "bmp"; const std::string IMAGE_CONTAINER_TYPE_GIF = "gif"; const std::string IMAGE_CONTAINER_TYPE_JPG = "jpg"; const std::string IMAGE_CONTAINER_TYPE_PNG = "png"; const std::string IMAGE_CONTAINER_TYPE_WEBP = "webp"; const std::string IMAGE_CONTAINER_TYPE_RAW = "raw"; const std::string IMAGE_CONTAINER_TYPE_SVG = "svg"; const std::string IMAGE_CONTAINER_TYPE_HEIF = "heif"; // Unordered set contains list supported audio formats const std::unordered_set<std::string> SUPPORTED_AUDIO_FORMATS_SET { AUDIO_CONTAINER_TYPE_AAC, AUDIO_CONTAINER_TYPE_MP3, AUDIO_CONTAINER_TYPE_FLAC, AUDIO_CONTAINER_TYPE_WAV, AUDIO_CONTAINER_TYPE_OGG }; // Unordered set contains list supported video formats const std::unordered_set<std::string> SUPPORTED_VIDEO_FORMATS_SET { VIDEO_CONTAINER_TYPE_MP4, VIDEO_CONTAINER_TYPE_3GP, VIDEO_CONTAINER_TYPE_MPG, VIDEO_CONTAINER_TYPE_MOV, VIDEO_CONTAINER_TYPE_WEBM, VIDEO_CONTAINER_TYPE_MKV }; // Unordered set contains list supported image formats const std::unordered_set<std::string> SUPPORTED_IMAGE_FORMATS_SET { IMAGE_CONTAINER_TYPE_BMP, IMAGE_CONTAINER_TYPE_GIF, IMAGE_CONTAINER_TYPE_JPG, IMAGE_CONTAINER_TYPE_PNG, IMAGE_CONTAINER_TYPE_WEBP, IMAGE_CONTAINER_TYPE_RAW, IMAGE_CONTAINER_TYPE_SVG, IMAGE_CONTAINER_TYPE_HEIF }; } // namespace OHOS } // namespace Media #endif // MEDIA_LIB_SERVICE_CONST_H
[ "sonali1@huawei.com" ]
sonali1@huawei.com
df6e19496e16f6433695efd640086a87a376dff2
64bd2dbc0d2c8f794905e3c0c613d78f0648eefc
/Cpp/SDK/BP_hair_col_brown_06_Desc_classes.h
5fdbe34c3c273676821d0073ad299a71e065f6fd
[]
no_license
zanzo420/SoT-Insider-SDK
37232fa74866031dd655413837813635e93f3692
874cd4f4f8af0c58667c4f7c871d2a60609983d3
refs/heads/main
2023-06-18T15:48:54.547869
2021-07-19T06:02:00
2021-07-19T06:02:00
387,354,587
1
2
null
null
null
null
UTF-8
C++
false
false
779
h
#pragma once // Name: SoT Insider, Version: 1.103.4306.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_hair_col_brown_06_Desc.BP_hair_col_brown_06_Desc_C // 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0]) class UBP_hair_col_brown_06_Desc_C : public UClothingDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_hair_col_brown_06_Desc.BP_hair_col_brown_06_Desc_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
f8e6a5a37298a415f8092f47b8bada9b2efe2b0a
735920e24ac91b36912ff2610406d1f43f8f240a
/sstmac/hardware/pisces/pisces_stats_fwd.h
9a608c4e1132744e8918a7a1a274cf7f979992ea
[ "BSD-3-Clause" ]
permissive
deanchester/sst-macro
d418186fc1fdf5d376d23f451f988839ca987e98
b590e7a5c604e38c840569de0e2b80bfc85539a0
refs/heads/master
2021-04-28T05:43:11.279646
2018-02-11T14:48:12
2018-02-11T14:48:12
122,183,455
0
0
BSD-3-Clause
2018-02-20T10:23:49
2018-02-20T10:23:49
null
UTF-8
C++
false
false
2,239
h
/** Copyright 2009-2017 National Technology and Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government retains certain rights in this software. Sandia National Laboratories is a multimission laboratory managed and operated by National Technology and Engineering Solutions of Sandia, LLC., a wholly owned subsidiary of Honeywell International, Inc., for the U.S. Department of Energy's National Nuclear Security Administration under contract DE-NA0003525. Copyright (c) 2009-2017, NTESS 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 Sandia Corporation 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. Questions? Contact sst-macro-help@sandia.gov */ #ifndef pisces_STATS_FWD_H #define pisces_STATS_FWD_H namespace sstmac { namespace hw { class stat_bytes_sent; } } #endif // pisces_STATS_FWD_H
[ "jjwilke@sandia.gov" ]
jjwilke@sandia.gov
f37d942648fd50e70c27eb1d74c12fcfbedcc512
889626966d3f108522c753db83a1a23318d4d6fd
/src/test/util_tests.cpp
9e0df9ac6e797c6fc767dd73aeab3e0b7bc3a8a0
[ "MIT" ]
permissive
safepeofficial/safepeofficial
5a14d0aeaa140c52d3d96f3e7bb892cd28e143c0
aca67695fedfabbdd6dc512358fee54fefc912de
refs/heads/master
2023-06-23T08:00:42.237747
2021-07-22T14:06:58
2021-07-22T14:06:58
386,934,834
0
0
null
null
null
null
UTF-8
C++
false
false
26,899
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util.h" #include "clientversion.h" #include "primitives/transaction.h" #include "sync.h" #include "utilstrencodings.h" #include "utilmoneystr.h" #include "test/test_safepe.h" #include "test/test_random.h" #include <stdint.h> #include <vector> #include <boost/test/unit_test.hpp> extern std::unordered_map<std::string, std::string> mapArgs; BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(util_criticalsection) { CCriticalSection cs; do { LOCK(cs); break; BOOST_ERROR("break was swallowed!"); } while(0); do { TRY_LOCK(cs, lockTest); if (lockTest) break; BOOST_ERROR("break was swallowed!"); } while(0); } static const unsigned char ParseHex_expected[65] = { 0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, 0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, 0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, 0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, 0x5f }; BOOST_AUTO_TEST_CASE(util_ParseHex) { std::vector<unsigned char> result; std::vector<unsigned char> expected(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)); // Basic test vector result = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end()); // Spaces between bytes must be supported result = ParseHex("12 34 56 78"); BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78); // Leading space must be supported (used in CDBEnv::Salvage) result = ParseHex(" 89 34 56 78"); BOOST_CHECK(result.size() == 4 && result[0] == 0x89 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78); // Stop parsing at invalid value result = ParseHex("1234 invalid 1234"); BOOST_CHECK(result.size() == 2 && result[0] == 0x12 && result[1] == 0x34); } BOOST_AUTO_TEST_CASE(util_HexStr) { BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)), "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + 5, true), "04 67 8a fd b0"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected, true), ""); std::vector<unsigned char> ParseHex_vec(ParseHex_expected, ParseHex_expected + 5); BOOST_CHECK_EQUAL( HexStr(ParseHex_vec, true), "04 67 8a fd b0"); } BOOST_AUTO_TEST_CASE(util_DateTimeStrFormat) { BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 0), "1970-01-01 00:00:00"); BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 0x7FFFFFFF), "2038-01-19 03:14:07"); BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", 1317425777), "2011-09-30 23:36:17"); BOOST_CHECK_EQUAL(DateTimeStrFormat("%Y-%m-%d %H:%M", 1317425777), "2011-09-30 23:36"); BOOST_CHECK_EQUAL(DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", 1317425777), "Fri, 30 Sep 2011 23:36:17 +0000"); } BOOST_AUTO_TEST_CASE(util_ParseParameters) { const char *argv_test[] = {"-ignored", "-a", "-b", "-ccc=argument", "-ccc=multiple", "f", "-d=e"}; ParseParameters(0, (char**)argv_test); BOOST_CHECK(mapArgs.empty() && mapMultiArgs.empty()); ParseParameters(1, (char**)argv_test); BOOST_CHECK(mapArgs.empty() && mapMultiArgs.empty()); ParseParameters(5, (char**)argv_test); // expectation: -ignored is ignored (program name argument), // -a, -b and -ccc end up in map, -d ignored because it is after // a non-option argument (non-GNU option parsing) BOOST_CHECK(mapArgs.size() == 3 && mapMultiArgs.size() == 3); BOOST_CHECK(IsArgSet("-a") && IsArgSet("-b") && IsArgSet("-ccc") && !IsArgSet("f") && !IsArgSet("-d")); BOOST_CHECK(mapMultiArgs.count("-a") && mapMultiArgs.count("-b") && mapMultiArgs.count("-ccc") && !mapMultiArgs.count("f") && !mapMultiArgs.count("-d")); BOOST_CHECK(mapArgs["-a"] == "" && mapArgs["-ccc"] == "multiple"); BOOST_CHECK(mapMultiArgs.at("-ccc").size() == 2); } BOOST_AUTO_TEST_CASE(util_GetArg) { mapArgs.clear(); mapArgs["strtest1"] = "string..."; // strtest2 undefined on purpose mapArgs["inttest1"] = "12345"; mapArgs["inttest2"] = "81985529216486895"; // inttest3 undefined on purpose mapArgs["booltest1"] = ""; // booltest2 undefined on purpose mapArgs["booltest3"] = "0"; mapArgs["booltest4"] = "1"; BOOST_CHECK_EQUAL(GetArg("strtest1", "default"), "string..."); BOOST_CHECK_EQUAL(GetArg("strtest2", "default"), "default"); BOOST_CHECK_EQUAL(GetArg("inttest1", -1), 12345); BOOST_CHECK_EQUAL(GetArg("inttest2", -1), 81985529216486895LL); BOOST_CHECK_EQUAL(GetArg("inttest3", -1), -1); BOOST_CHECK_EQUAL(GetBoolArg("booltest1", false), true); BOOST_CHECK_EQUAL(GetBoolArg("booltest2", false), false); BOOST_CHECK_EQUAL(GetBoolArg("booltest3", false), false); BOOST_CHECK_EQUAL(GetBoolArg("booltest4", false), true); } BOOST_AUTO_TEST_CASE(util_FormatMoney) { BOOST_CHECK_EQUAL(FormatMoney(0), "0.00"); BOOST_CHECK_EQUAL(FormatMoney((COIN/10000)*123456789), "12345.6789"); BOOST_CHECK_EQUAL(FormatMoney(-COIN), "-1.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000), "100000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000), "10000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000), "1000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100000), "100000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10000), "10000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*1000), "1000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100), "100.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10), "10.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN), "1.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10), "0.10"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100), "0.01"); BOOST_CHECK_EQUAL(FormatMoney(COIN/1000), "0.001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10000), "0.0001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100000), "0.00001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/1000000), "0.000001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10000000), "0.0000001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100000000), "0.00000001"); } BOOST_AUTO_TEST_CASE(util_ParseMoney) { CAmount ret = 0; BOOST_CHECK(ParseMoney("0.0", ret)); BOOST_CHECK_EQUAL(ret, 0); BOOST_CHECK(ParseMoney("12345.6789", ret)); BOOST_CHECK_EQUAL(ret, (COIN/10000)*123456789); BOOST_CHECK(ParseMoney("100000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100000000); BOOST_CHECK(ParseMoney("10000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10000000); BOOST_CHECK(ParseMoney("1000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*1000000); BOOST_CHECK(ParseMoney("100000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100000); BOOST_CHECK(ParseMoney("10000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10000); BOOST_CHECK(ParseMoney("1000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*1000); BOOST_CHECK(ParseMoney("100.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100); BOOST_CHECK(ParseMoney("10.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10); BOOST_CHECK(ParseMoney("1.00", ret)); BOOST_CHECK_EQUAL(ret, COIN); BOOST_CHECK(ParseMoney("1", ret)); BOOST_CHECK_EQUAL(ret, COIN); BOOST_CHECK(ParseMoney("0.1", ret)); BOOST_CHECK_EQUAL(ret, COIN/10); BOOST_CHECK(ParseMoney("0.01", ret)); BOOST_CHECK_EQUAL(ret, COIN/100); BOOST_CHECK(ParseMoney("0.001", ret)); BOOST_CHECK_EQUAL(ret, COIN/1000); BOOST_CHECK(ParseMoney("0.0001", ret)); BOOST_CHECK_EQUAL(ret, COIN/10000); BOOST_CHECK(ParseMoney("0.00001", ret)); BOOST_CHECK_EQUAL(ret, COIN/100000); BOOST_CHECK(ParseMoney("0.000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/1000000); BOOST_CHECK(ParseMoney("0.0000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/10000000); BOOST_CHECK(ParseMoney("0.00000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/100000000); // Attempted 63 bit overflow should fail BOOST_CHECK(!ParseMoney("92233720368.54775808", ret)); // Parsing negative amounts must fail BOOST_CHECK(!ParseMoney("-1", ret)); } BOOST_AUTO_TEST_CASE(util_IsHex) { BOOST_CHECK(IsHex("00")); BOOST_CHECK(IsHex("00112233445566778899aabbccddeeffAABBCCDDEEFF")); BOOST_CHECK(IsHex("ff")); BOOST_CHECK(IsHex("FF")); BOOST_CHECK(!IsHex("")); BOOST_CHECK(!IsHex("0")); BOOST_CHECK(!IsHex("a")); BOOST_CHECK(!IsHex("eleven")); BOOST_CHECK(!IsHex("00xx00")); BOOST_CHECK(!IsHex("0x0000")); } BOOST_AUTO_TEST_CASE(util_seed_insecure_rand) { seed_insecure_rand(true); for (int mod=2;mod<11;mod++) { int mask = 1; // Really rough binomal confidence approximation. int err = 30*10000./mod*sqrt((1./mod*(1-1./mod))/10000.); //mask is 2^ceil(log2(mod))-1 while(mask<mod-1)mask=(mask<<1)+1; int count = 0; //How often does it get a zero from the uniform range [0,mod)? for (int i = 0; i < 10000; i++) { uint32_t rval; do{ rval=insecure_rand()&mask; }while(rval>=(uint32_t)mod); count += rval==0; } BOOST_CHECK(count<=10000/mod+err); BOOST_CHECK(count>=10000/mod-err); } } BOOST_AUTO_TEST_CASE(util_TimingResistantEqual) { BOOST_CHECK(TimingResistantEqual(std::string(""), std::string(""))); BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string(""))); BOOST_CHECK(!TimingResistantEqual(std::string(""), std::string("abc"))); BOOST_CHECK(!TimingResistantEqual(std::string("a"), std::string("aa"))); BOOST_CHECK(!TimingResistantEqual(std::string("aa"), std::string("a"))); BOOST_CHECK(TimingResistantEqual(std::string("abc"), std::string("abc"))); BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("aba"))); } /* Test strprintf formatting directives. * Put a string before and after to ensure sanity of element sizes on stack. */ #define B "check_prefix" #define E "check_postfix" BOOST_AUTO_TEST_CASE(strprintf_numbers) { int64_t s64t = -9223372036854775807LL; /* signed 64 bit test value */ uint64_t u64t = 18446744073709551615ULL; /* unsigned 64 bit test value */ BOOST_CHECK(strprintf("%s %d %s", B, s64t, E) == B" -9223372036854775807 " E); BOOST_CHECK(strprintf("%s %u %s", B, u64t, E) == B" 18446744073709551615 " E); BOOST_CHECK(strprintf("%s %x %s", B, u64t, E) == B" ffffffffffffffff " E); size_t st = 12345678; /* unsigned size_t test value */ ssize_t sst = -12345678; /* signed size_t test value */ BOOST_CHECK(strprintf("%s %d %s", B, sst, E) == B" -12345678 " E); BOOST_CHECK(strprintf("%s %u %s", B, st, E) == B" 12345678 " E); BOOST_CHECK(strprintf("%s %x %s", B, st, E) == B" bc614e " E); ptrdiff_t pt = 87654321; /* positive ptrdiff_t test value */ ptrdiff_t spt = -87654321; /* negative ptrdiff_t test value */ BOOST_CHECK(strprintf("%s %d %s", B, spt, E) == B" -87654321 " E); BOOST_CHECK(strprintf("%s %u %s", B, pt, E) == B" 87654321 " E); BOOST_CHECK(strprintf("%s %x %s", B, pt, E) == B" 5397fb1 " E); } #undef B #undef E /* Check for mingw/wine issue #3494 * Remove this test before time.ctime(0xffffffff) == 'Sun Feb 7 07:28:15 2106' */ BOOST_AUTO_TEST_CASE(gettime) { BOOST_CHECK((GetTime() & ~0xFFFFFFFFLL) == 0); } BOOST_AUTO_TEST_CASE(test_ParseInt32) { int32_t n; // Valid values BOOST_CHECK(ParseInt32("1234", NULL)); BOOST_CHECK(ParseInt32("0", &n) && n == 0); BOOST_CHECK(ParseInt32("1234", &n) && n == 1234); BOOST_CHECK(ParseInt32("01234", &n) && n == 1234); // no octal BOOST_CHECK(ParseInt32("2147483647", &n) && n == 2147483647); BOOST_CHECK(ParseInt32("-2147483648", &n) && n == (-2147483647 - 1)); // (-2147483647 - 1) equals INT_MIN BOOST_CHECK(ParseInt32("-1234", &n) && n == -1234); // Invalid values BOOST_CHECK(!ParseInt32("", &n)); BOOST_CHECK(!ParseInt32(" 1", &n)); // no padding inside BOOST_CHECK(!ParseInt32("1 ", &n)); BOOST_CHECK(!ParseInt32("1a", &n)); BOOST_CHECK(!ParseInt32("aap", &n)); BOOST_CHECK(!ParseInt32("0x1", &n)); // no hex BOOST_CHECK(!ParseInt32("0x1", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseInt32(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseInt32("-2147483649", NULL)); BOOST_CHECK(!ParseInt32("2147483648", NULL)); BOOST_CHECK(!ParseInt32("-32482348723847471234", NULL)); BOOST_CHECK(!ParseInt32("32482348723847471234", NULL)); } BOOST_AUTO_TEST_CASE(test_ParseInt64) { int64_t n; // Valid values BOOST_CHECK(ParseInt64("1234", NULL)); BOOST_CHECK(ParseInt64("0", &n) && n == 0LL); BOOST_CHECK(ParseInt64("1234", &n) && n == 1234LL); BOOST_CHECK(ParseInt64("01234", &n) && n == 1234LL); // no octal BOOST_CHECK(ParseInt64("2147483647", &n) && n == 2147483647LL); BOOST_CHECK(ParseInt64("-2147483648", &n) && n == -2147483648LL); BOOST_CHECK(ParseInt64("9223372036854775807", &n) && n == (int64_t)9223372036854775807); BOOST_CHECK(ParseInt64("-9223372036854775808", &n) && n == (int64_t)-9223372036854775807-1); BOOST_CHECK(ParseInt64("-1234", &n) && n == -1234LL); // Invalid values BOOST_CHECK(!ParseInt64("", &n)); BOOST_CHECK(!ParseInt64(" 1", &n)); // no padding inside BOOST_CHECK(!ParseInt64("1 ", &n)); BOOST_CHECK(!ParseInt64("1a", &n)); BOOST_CHECK(!ParseInt64("aap", &n)); BOOST_CHECK(!ParseInt64("0x1", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseInt64(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseInt64("-9223372036854775809", NULL)); BOOST_CHECK(!ParseInt64("9223372036854775808", NULL)); BOOST_CHECK(!ParseInt64("-32482348723847471234", NULL)); BOOST_CHECK(!ParseInt64("32482348723847471234", NULL)); } BOOST_AUTO_TEST_CASE(test_ParseUInt32) { uint32_t n; // Valid values BOOST_CHECK(ParseUInt32("1234", NULL)); BOOST_CHECK(ParseUInt32("0", &n) && n == 0); BOOST_CHECK(ParseUInt32("1234", &n) && n == 1234); BOOST_CHECK(ParseUInt32("01234", &n) && n == 1234); // no octal BOOST_CHECK(ParseUInt32("2147483647", &n) && n == 2147483647); BOOST_CHECK(ParseUInt32("2147483648", &n) && n == (uint32_t)2147483648); BOOST_CHECK(ParseUInt32("4294967295", &n) && n == (uint32_t)4294967295); // Invalid values BOOST_CHECK(!ParseUInt32("", &n)); BOOST_CHECK(!ParseUInt32(" 1", &n)); // no padding inside BOOST_CHECK(!ParseUInt32(" -1", &n)); BOOST_CHECK(!ParseUInt32("1 ", &n)); BOOST_CHECK(!ParseUInt32("1a", &n)); BOOST_CHECK(!ParseUInt32("aap", &n)); BOOST_CHECK(!ParseUInt32("0x1", &n)); // no hex BOOST_CHECK(!ParseUInt32("0x1", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseUInt32(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseUInt32("-2147483648", &n)); BOOST_CHECK(!ParseUInt32("4294967296", &n)); BOOST_CHECK(!ParseUInt32("-1234", &n)); BOOST_CHECK(!ParseUInt32("-32482348723847471234", NULL)); BOOST_CHECK(!ParseUInt32("32482348723847471234", NULL)); } BOOST_AUTO_TEST_CASE(test_ParseUInt64) { uint64_t n; // Valid values BOOST_CHECK(ParseUInt64("1234", NULL)); BOOST_CHECK(ParseUInt64("0", &n) && n == 0LL); BOOST_CHECK(ParseUInt64("1234", &n) && n == 1234LL); BOOST_CHECK(ParseUInt64("01234", &n) && n == 1234LL); // no octal BOOST_CHECK(ParseUInt64("2147483647", &n) && n == 2147483647LL); BOOST_CHECK(ParseUInt64("9223372036854775807", &n) && n == 9223372036854775807ULL); BOOST_CHECK(ParseUInt64("9223372036854775808", &n) && n == 9223372036854775808ULL); BOOST_CHECK(ParseUInt64("18446744073709551615", &n) && n == 18446744073709551615ULL); // Invalid values BOOST_CHECK(!ParseUInt64("", &n)); BOOST_CHECK(!ParseUInt64(" 1", &n)); // no padding inside BOOST_CHECK(!ParseUInt64(" -1", &n)); BOOST_CHECK(!ParseUInt64("1 ", &n)); BOOST_CHECK(!ParseUInt64("1a", &n)); BOOST_CHECK(!ParseUInt64("aap", &n)); BOOST_CHECK(!ParseUInt64("0x1", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseUInt64(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseUInt64("-9223372036854775809", NULL)); BOOST_CHECK(!ParseUInt64("18446744073709551616", NULL)); BOOST_CHECK(!ParseUInt64("-32482348723847471234", NULL)); BOOST_CHECK(!ParseUInt64("-2147483648", &n)); BOOST_CHECK(!ParseUInt64("-9223372036854775808", &n)); BOOST_CHECK(!ParseUInt64("-1234", &n)); } BOOST_AUTO_TEST_CASE(test_ParseDouble) { double n; // Valid values BOOST_CHECK(ParseDouble("1234", NULL)); BOOST_CHECK(ParseDouble("0", &n) && n == 0.0); BOOST_CHECK(ParseDouble("1234", &n) && n == 1234.0); BOOST_CHECK(ParseDouble("01234", &n) && n == 1234.0); // no octal BOOST_CHECK(ParseDouble("2147483647", &n) && n == 2147483647.0); BOOST_CHECK(ParseDouble("-2147483648", &n) && n == -2147483648.0); BOOST_CHECK(ParseDouble("-1234", &n) && n == -1234.0); BOOST_CHECK(ParseDouble("1e6", &n) && n == 1e6); BOOST_CHECK(ParseDouble("-1e6", &n) && n == -1e6); // Invalid values BOOST_CHECK(!ParseDouble("", &n)); BOOST_CHECK(!ParseDouble(" 1", &n)); // no padding inside BOOST_CHECK(!ParseDouble("1 ", &n)); BOOST_CHECK(!ParseDouble("1a", &n)); BOOST_CHECK(!ParseDouble("aap", &n)); BOOST_CHECK(!ParseDouble("0x1", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseDouble(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseDouble("-1e10000", NULL)); BOOST_CHECK(!ParseDouble("1e10000", NULL)); } BOOST_AUTO_TEST_CASE(test_FormatParagraph) { BOOST_CHECK_EQUAL(FormatParagraph("", 79, 0), ""); BOOST_CHECK_EQUAL(FormatParagraph("test", 79, 0), "test"); BOOST_CHECK_EQUAL(FormatParagraph(" test", 79, 0), " test"); BOOST_CHECK_EQUAL(FormatParagraph("test test", 79, 0), "test test"); BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 0), "test\ntest"); BOOST_CHECK_EQUAL(FormatParagraph("testerde test", 4, 0), "testerde\ntest"); BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 4), "test\n test"); // Make sure we don't indent a fully-new line following a too-long line ending BOOST_CHECK_EQUAL(FormatParagraph("test test\nabc", 4, 4), "test\n test\nabc"); BOOST_CHECK_EQUAL(FormatParagraph("This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length until it gets here", 79), "This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length\nuntil it gets here"); // Test wrap length is exact BOOST_CHECK_EQUAL(FormatParagraph("a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p", 79), "a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\nf g h i j k l m n o p"); BOOST_CHECK_EQUAL(FormatParagraph("x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p", 79), "x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\nf g h i j k l m n o p"); // Indent should be included in length of lines BOOST_CHECK_EQUAL(FormatParagraph("x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg h i j k", 79, 4), "x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\n f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg\n h i j k"); BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string. This is a second sentence in the very long test string.", 79), "This is a very long test string. This is a second sentence in the very long\ntest string."); BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string.\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string.", 79), "This is a very long test string.\nThis is a second sentence in the very long test string. This is a third\nsentence in the very long test string."); BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string.\n\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string.", 79), "This is a very long test string.\n\nThis is a second sentence in the very long test string. This is a third\nsentence in the very long test string."); BOOST_CHECK_EQUAL(FormatParagraph("Testing that normal newlines do not get indented.\nLike here.", 79), "Testing that normal newlines do not get indented.\nLike here."); } BOOST_AUTO_TEST_CASE(test_FormatSubVersion) { std::vector<std::string> comments; comments.push_back(std::string("comment1")); std::vector<std::string> comments2; comments2.push_back(std::string("comment1")); comments2.push_back(SanitizeString(std::string("Comment2; .,_?@-; !\"#$%&'()*+/<=>[]\\^`{|}~"), SAFE_CHARS_UA_COMMENT)); // Semicolon is discouraged but not forbidden by BIP-0014 BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, std::vector<std::string>()),std::string("/Test:0.9.99/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments),std::string("/Test:0.9.99(comment1)/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments2),std::string("/Test:0.9.99(comment1; Comment2; .,_?@-; )/")); } BOOST_AUTO_TEST_CASE(test_ParseFixedPoint) { int64_t amount = 0; BOOST_CHECK(ParseFixedPoint("0", 8, &amount)); BOOST_CHECK_EQUAL(amount, 0LL); BOOST_CHECK(ParseFixedPoint("1", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000LL); BOOST_CHECK(ParseFixedPoint("0.0", 8, &amount)); BOOST_CHECK_EQUAL(amount, 0LL); BOOST_CHECK(ParseFixedPoint("-0.1", 8, &amount)); BOOST_CHECK_EQUAL(amount, -10000000LL); BOOST_CHECK(ParseFixedPoint("1.1", 8, &amount)); BOOST_CHECK_EQUAL(amount, 110000000LL); BOOST_CHECK(ParseFixedPoint("1.10000000000000000", 8, &amount)); BOOST_CHECK_EQUAL(amount, 110000000LL); BOOST_CHECK(ParseFixedPoint("1.1e1", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1100000000LL); BOOST_CHECK(ParseFixedPoint("1.1e-1", 8, &amount)); BOOST_CHECK_EQUAL(amount, 11000000LL); BOOST_CHECK(ParseFixedPoint("1000", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000000LL); BOOST_CHECK(ParseFixedPoint("-1000", 8, &amount)); BOOST_CHECK_EQUAL(amount, -100000000000LL); BOOST_CHECK(ParseFixedPoint("0.00000001", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1LL); BOOST_CHECK(ParseFixedPoint("0.0000000100000000", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1LL); BOOST_CHECK(ParseFixedPoint("-0.00000001", 8, &amount)); BOOST_CHECK_EQUAL(amount, -1LL); BOOST_CHECK(ParseFixedPoint("1000000000.00000001", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000000000001LL); BOOST_CHECK(ParseFixedPoint("9999999999.99999999", 8, &amount)); BOOST_CHECK_EQUAL(amount, 999999999999999999LL); BOOST_CHECK(ParseFixedPoint("-9999999999.99999999", 8, &amount)); BOOST_CHECK_EQUAL(amount, -999999999999999999LL); BOOST_CHECK(!ParseFixedPoint("", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("a-1000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-a1000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-1000a", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-01000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("00.1", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(".1", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("--0.1", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("0.000000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-0.000000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("0.00000001000000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-10000000000.00000000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("10000000000.00000000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-10000000000.00000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("10000000000.00000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-10000000000.00000009", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("10000000000.00000009", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-99999999999.99999999", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("99999909999.09999999", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("92233720368.54775807", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("92233720368.54775808", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-92233720368.54775808", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-92233720368.54775809", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("1.1e", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("1.1e-", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("1.", 8, &amount)); } BOOST_AUTO_TEST_CASE(version_info_helper) { BOOST_CHECK(StringVersionToInt("1.1.1") == 0x010101); BOOST_CHECK(IntVersionToString(0x010101) == "1.1.1"); BOOST_CHECK_THROW(StringVersionToInt("1.1.hgdghfgf"), std::bad_cast); BOOST_CHECK_THROW(StringVersionToInt("1.1"), std::bad_cast); BOOST_CHECK_THROW(StringVersionToInt("1.1.1f"), std::bad_cast); BOOST_CHECK_THROW(StringVersionToInt("1.1.1000"), std::bad_cast); BOOST_CHECK_THROW(StringVersionToInt("10"), std::bad_cast); BOOST_CHECK_THROW(StringVersionToInt("1.1.1.1"), std::bad_cast); BOOST_CHECK_THROW(IntVersionToString(0x01010101), std::bad_cast); BOOST_CHECK_THROW(IntVersionToString(0), std::bad_cast); } BOOST_AUTO_TEST_SUITE_END()
[ "dev.vanshtah@gmail.com" ]
dev.vanshtah@gmail.com
5e380d8337c2d32a9421382aa9ca4d6ad95b8b07
4d6c0c4f85361a858714bfaee69f092f024a0836
/Assignments/Graphics/Texture/main.cpp
74d23a05cb3d8ffde816bb251ce77d9307d0352a
[]
no_license
Jeunna/Univ
4ff5f140d1d71a1cc4aa2e872a9ef2fdd5f55480
0e29946fd92a1bd909d9fa5911c386dafa46ac06
refs/heads/master
2023-06-02T18:04:13.674251
2021-06-20T02:13:15
2021-06-20T02:13:15
148,912,187
0
0
null
null
null
null
UTF-8
C++
false
false
9,715
cpp
// Defines the entry point for the console application. // #include <GL/glew.h> #include <GL/freeglut.h> #include <iostream> #include <string> #include <fstream> #include <chrono> #include "transform.hpp" #include "Shader.h" #include "SOIL.h" void init(); void display(); void reshape(int, int); void idle(); GLuint program; GLint loc_a_vertex; GLint loc_a_normal; GLint loc_a_texcoord; GLint loc_u_pvm_matrix; GLint loc_u_view_matrix; GLint loc_u_model_matrix; GLint loc_u_normal_matrix; GLint loc_u_light_vector; GLint loc_u_light_ambient; GLint loc_u_light_diffuse; GLint loc_u_light_specular; GLint loc_u_material_ambient; GLint loc_u_material_diffuse; GLint loc_u_material_specular; GLint loc_u_material_shininess; GLint loc_u_texid; GLint loc_u_texid_frame; GLuint texid; GLuint texid_frame; float model_scale = 1.0f; float model_angle = 0.0f; kmuvcl::math::mat4x4f mat_PVM; kmuvcl::math::mat3x3f mat_Normal; kmuvcl::math::vec4f light_vector = kmuvcl::math::vec4f(10.0f, 10.0f, 10.0f); kmuvcl::math::vec4f light_ambient = kmuvcl::math::vec4f(1.0f, 1.0f, 1.0f, 1.0f); kmuvcl::math::vec4f light_diffuse = kmuvcl::math::vec4f(1.0f, 1.0f, 1.0f, 1.0f); kmuvcl::math::vec4f light_specular = kmuvcl::math::vec4f(1.0f, 1.0f, 1.0f, 1.0f); kmuvcl::math::vec4f material_ambient = kmuvcl::math::vec4f(0.464f, 0.393f, 0.094f, 1.0f); kmuvcl::math::vec4f material_diffuse = kmuvcl::math::vec4f(0.464f, 0.393f, 0.094f, 1.0f); kmuvcl::math::vec4f material_specular = kmuvcl::math::vec4f(1.0f, 1.0f, 1.0f, 1.0f); float material_shininess= 50.0f; GLfloat vertices[] = { // front -1, 1, 1, 1, 1, 1, 1,-1, 1, -1,-1, 1, // back 1, 1, -1, -1, 1, -1, -1,-1, -1, 1,-1, -1, // top -1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, // bottom -1,-1, 1, 1,-1, 1, 1,-1, -1, -1,-1, -1, // right 1, 1, 1, 1, 1, -1, 1,-1, -1, 1,-1, 1, // left -1, 1, -1, -1, 1, 1, -1,-1, 1, -1,-1, -1, }; GLfloat normals[] = { //front 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, //back 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, //top 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, //bottom 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, //right 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, //left -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, }; GLfloat texcoords[] = { // front 0,1, 1,1, 1,0, 0,0, // back 0,1, 1,1, 1,0, 0,0, // top 0,1, 1,1, 1,0, 0,0, // bottom 0,1, 1,1, 1,0, 0,0, // right 0,1, 1,1, 1,0, 0,0, // left 0,1, 1,1, 1,0, 0,0, }; GLushort indices[] = { //front 0, 3, 2, 2, 1, 0, //back 4, 7, 6, 6, 5, 4, // top 8,11,10, 10, 9, 8, // bottom 12,15,14, 14,13,12, //right 16,19,18, 18,17,16, //left 20,23,22, 22,21,20, }; std::chrono::time_point<std::chrono::system_clock> prev, curr; int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(640, 640); glutCreateWindow("Modeling & Navigating Your Studio"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutIdleFunc(idle); if (glewInit() != GLEW_OK) { std::cerr << "failed to initialize glew" << std::endl; return -1; } init(); glutMainLoop(); return 0; } void init() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glFrontFace(GL_CCW); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // for wireframe rendering glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glEnable(GL_DEPTH_TEST); program = Shader::create_program("./shader/texture_vert.glsl", "./shader/texture_frag.glsl"); // TODO: get shader variable locations loc_u_pvm_matrix = glGetUniformLocation(program, "u_pvm_matrix"); loc_u_view_matrix = glGetUniformLocation(program, "u_view_matrix"); loc_u_model_matrix = glGetUniformLocation(program, "u_model_matrix"); loc_u_normal_matrix = glGetUniformLocation(program, "u_normal_matrix"); loc_u_light_vector = glGetUniformLocation(program, "u_light_vector"); loc_u_light_ambient = glGetUniformLocation(program, "u_light_ambient"); loc_u_light_diffuse = glGetUniformLocation(program, "u_light_diffuse"); loc_u_light_specular = glGetUniformLocation(program, "u_light_specular"); loc_u_material_ambient = glGetUniformLocation(program, "u_material_ambient"); loc_u_material_diffuse = glGetUniformLocation(program, "u_material_diffuse"); loc_u_material_specular = glGetUniformLocation(program, "u_material_specular"); loc_u_material_shininess = glGetUniformLocation(program, "u_material_shininess"); loc_u_texid = glGetUniformLocation(program, "u_texid"); loc_u_texid_frame= glGetUniformLocation(program, "u_texid_frame"); loc_a_vertex = glGetAttribLocation(program, "a_vertex"); loc_a_normal = glGetAttribLocation(program, "a_normal"); loc_a_texcoord = glGetAttribLocation(program, "a_texcoord"); int width, height, channels; unsigned char* image = SOIL_load_image("tex.jpg", &width, &height, &channels, SOIL_LOAD_RGB); // TODO: generate texture glGenTextures(1, &texid); glBindTexture(GL_TEXTURE_2D, texid); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); SOIL_free_image_data(image); unsigned char* frame = SOIL_load_image("frame.jpg", &width, &height, &channels, SOIL_LOAD_RGB); glGenTextures(1, &texid_frame); glBindTexture(GL_TEXTURE_2D, texid_frame); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, frame); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); SOIL_free_image_data(frame); prev = curr = std::chrono::system_clock::now(); } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(program); // Camera setting kmuvcl::math::mat4x4f mat_Proj, mat_View_inv, mat_Model; kmuvcl::math::mat4x4f mat_R_X, mat_R_Y, mat_R_Z; // camera intrinsic param mat_Proj = kmuvcl::math::perspective(60.0f, 1.0f, 0.001f, 10000.0f); // camera extrinsic param mat_View_inv = kmuvcl::math::lookAt( 0.0f, 0.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); mat_Model = kmuvcl::math::scale (model_scale, model_scale, model_scale); mat_R_Z = kmuvcl::math::rotate(model_angle*0.7f, 0.0f, 0.0f, 1.0f); mat_R_Y = kmuvcl::math::rotate(model_angle, 0.0f, 1.0f, 0.0f); mat_R_X = kmuvcl::math::rotate(model_angle*0.5f, 1.0f, 0.0f, 0.0f); mat_Model = mat_R_X*mat_R_Y*mat_R_Z*mat_Model; mat_PVM = mat_Proj*mat_View_inv*mat_Model; mat_Normal(0, 0) = mat_Model(0, 0); mat_Normal(0, 1) = mat_Model(0, 1); mat_Normal(0, 2) = mat_Model(0, 2); mat_Normal(1, 0) = mat_Model(1, 0); mat_Normal(1, 1) = mat_Model(1, 1); mat_Normal(1, 2) = mat_Model(1, 2); mat_Normal(2, 0) = mat_Model(2, 0); mat_Normal(2, 1) = mat_Model(2, 1); mat_Normal(2, 2) = mat_Model(2, 2); kmuvcl::math::mat4x4f mat_View = kmuvcl::math::inverse(mat_View_inv); glUniformMatrix4fv(loc_u_pvm_matrix, 1, false, mat_PVM); glUniformMatrix4fv(loc_u_model_matrix, 1, false, mat_Model); glUniformMatrix4fv(loc_u_view_matrix, 1, false, mat_View); glUniformMatrix3fv(loc_u_normal_matrix, 1, false, mat_Normal); glUniform3fv(loc_u_light_vector, 1, light_vector); glUniform4fv(loc_u_light_ambient, 1, light_ambient); glUniform4fv(loc_u_light_diffuse, 1, light_diffuse); glUniform4fv(loc_u_light_specular, 1, light_specular); glUniform4fv(loc_u_material_ambient, 1, material_ambient); glUniform4fv(loc_u_material_diffuse, 1, material_diffuse); glUniform4fv(loc_u_material_specular, 1, material_specular); glUniform1f(loc_u_material_shininess, material_shininess); // TODO: using texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texid); glUniform1i(loc_u_texid, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texid_frame); glUniform1i(loc_u_texid_frame, 1); // TODO: send gpu texture coordinate glVertexAttribPointer(loc_a_vertex, 3, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(loc_a_normal, 3, GL_FLOAT, GL_FALSE, 0, normals); glVertexAttribPointer(loc_a_texcoord, 2, GL_FLOAT, GL_FALSE, 0, texcoords); glEnableVertexAttribArray(loc_a_vertex); glEnableVertexAttribArray(loc_a_normal); glEnableVertexAttribArray(loc_a_texcoord); glDrawElements(GL_TRIANGLES, sizeof(indices)/sizeof(GLushort), GL_UNSIGNED_SHORT, indices); glDisableVertexAttribArray(loc_a_vertex); glDisableVertexAttribArray(loc_a_normal); glDisableVertexAttribArray(loc_a_texcoord); glUseProgram(0); Shader::check_gl_error("draw"); glutSwapBuffers(); } void reshape(int width, int height) { glViewport(0, 0, width, height); } void idle() { curr = std::chrono::system_clock::now(); std::chrono::duration<float> elaped_seconds = (curr - prev); model_angle += 10 * elaped_seconds.count(); prev = curr; glutPostRedisplay(); }
[ "xjeunna@naver.com" ]
xjeunna@naver.com
a7bd17fc48febe743c503197c9ad745d005cb9af
294110983cb3fbe84288a1b4aa4ebafc3eea4cbb
/projects/space/subsystems/control/lib/tb6612fng_mbed/motor.cpp
d8d26cf6256763012954f3bb03ab23f0a1aaef60
[]
no_license
johntron/johntron
6ac652dfbfc295030dcd2061d52bb731892cfbf0
207b583a97581be781b574f87a09acca5f279a42
refs/heads/master
2023-05-25T18:52:16.424468
2023-05-01T04:03:19
2023-05-01T04:03:19
131,776,319
2
0
null
2023-03-05T19:22:03
2018-05-02T00:11:41
OpenSCAD
UTF-8
C++
false
false
1,185
cpp
/****************************************************************************** TB6612FNG H-Bridge Motor Driver for mbed Based on Michelle @ SparkFun Electronics' library for Arduino (thanks!) 8/20/16 https://github.com/sparkfun/SparkFun_TB6612FNG_Arduino_Library ******************************************************************************/ #include "motor.h" // TODO how to ensure mbed is loaded? //#include "mbed.h" namespace tb6612 { Motor::Motor(PinName In1pin, PinName In2pin, PinName PWMpin, PinName STBYpin) : In1(In1pin), In2(In2pin), PWM(PWMpin), Standby(STBYpin) {} void Motor::drive(float speed) { Standby = 1; if (speed >= 0) fwd(speed); else rev(-speed); } void Motor::drive(float speed, int duration_ms) { drive(speed); wait_ms(duration_ms); } void Motor::stop() { Standby = 1; In1 = 1; In2 = 1; PWM = 1.0; } void Motor::fwd(float speed) { Standby = 1; In1 = 1; In2 = 0; PWM = speed; } void Motor::rev(float speed) { In1 = 0; In2 = 1; PWM = speed; } void Motor::brake() { In1 = 1; In2 = 1; PWM = 0.0; } void Motor::standby() { Standby = 0; } float Motor::speed() { return PWM; } } // namespace tb6612
[ "john.syrinek@gmail.com" ]
john.syrinek@gmail.com
89345e0e96ec64a9c0ab505a23c1a35dd798ec97
002617d09a2d99f0d71886a4278bbc1208b9dfdb
/Source/FirstProjectUdemy/FGAIAssignment/BTTask_IncrementPatrolPointIndex.h
a88ec5be79aafd6cbaafbd6266bc4491ded7be36
[]
no_license
ManChunFu/FGAIUnreal
18202ce7065ec9d5e9c3a9abddc70df9452efd61
fe6091c07a4162c9b1d1b848a69b4c0e571d5541
refs/heads/main
2023-02-19T13:03:22.614697
2021-01-04T16:18:30
2021-01-04T16:18:30
303,459,758
0
0
null
null
null
null
UTF-8
C++
false
false
848
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "BehaviorTree/Tasks/BTTask_BlackboardBase.h" #include "BTTask_IncrementPatrolPointIndex.generated.h" /** * */ UENUM(BlueprintType) enum class EDirectionType :uint8 { EDT_Forward UMETA(DisplayName = "Forward"), EDT_Reverse UMETA(DisplayName = "Reverse"), EDT_MAX UMETA(DisplayName = "Default_MAX") }; UCLASS() class FIRSTPROJECTUDEMY_API UBTTask_IncrementPatrolPointIndex : public UBTTask_BlackboardBase { GENERATED_BODY() public: UBTTask_IncrementPatrolPointIndex(); EDirectionType Direction; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AI") bool BiDirection; protected: virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override; public: };
[ "man.chunfu@futuregames.nu" ]
man.chunfu@futuregames.nu
6a952dd651bb90cf45073c57dccd8f87fb2d3427
6c554125c49d4e3f0fac7a9b74251ae84191f23b
/fftreal_wrapper.h
0dac3a9188dfea2ba4f059a9a140f04b9075276c
[]
no_license
gonzoua/qt-demo-player
680f0f2345c21878eec70ccbff892c91995c915f
31af9118f8fca9f64854df2324c5447a8a090115
refs/heads/master
2021-01-10T10:51:36.473003
2016-03-10T20:35:01
2016-03-10T20:35:01
43,909,538
2
0
null
null
null
null
UTF-8
C++
false
false
372
h
#ifndef FFTREAL_WRAPPER_H #define FFTREAL_WRAPPER_H #include <QtCore/QtGlobal> class FFTRealWrapperPrivate; #define FFT_LENGTH_POWER_OF_TWO 12 class FFTRealWrapper { public: FFTRealWrapper(); ~FFTRealWrapper(); typedef float DataType; void calculateFFT(DataType in[], const DataType out[]); private: FFTRealWrapperPrivate* m_private; }; #endif
[ "gonzo@localhost.localdomain" ]
gonzo@localhost.localdomain
70b2ec5d60645be5994146317b0f4a2900ba40bb
5ebd5cee801215bc3302fca26dbe534e6992c086
/blazemark/src/eigen/TMat3TMat3Add.cpp
623b10e6f8920ba4aec948bca489d83104174511
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
4,554
cpp
//================================================================================================= /*! // \file src/eigen/TMat3TMat3Add.cpp // \brief Source file for the Eigen 3D transpose matrix/transpose matrix addition kernel // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <iostream> #include <vector> #include <Eigen/Dense> #include <blaze/util/Timing.h> #include <blazemark/eigen/init/Matrix.h> #include <blazemark/eigen/TMat3TMat3Add.h> #include <blazemark/system/Config.h> namespace blazemark { namespace eigen { //================================================================================================= // // KERNEL FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Eigen uBLAS 3-dimensional transpose matrix/transpose matrix addition kernel. // // \param N The number of 3x3 matrices to be computed. // \param steps The number of iteration steps to perform. // \return Minimum runtime of the kernel function. // // This kernel function implements the 3-dimensional transpose matrix/transpose matrix addition // by means of the Eigen functionality. */ double tmat3tmat3add( size_t N, size_t steps ) { using ::blazemark::element_t; using ::Eigen::Dynamic; using ::Eigen::ColMajor; ::blaze::setSeed( seed ); ::std::vector< ::Eigen::Matrix<element_t,3,3,ColMajor> > A( N ), B( N ), C( N ); ::blaze::timing::WcTimer timer; for( size_t i=0UL; i<N; ++i ) { init( A[i] ); init( B[i] ); } for( size_t i=0UL; i<N; ++i ) { C[i].noalias() = A[i] + B[i]; } for( size_t rep=0UL; rep<reps; ++rep ) { timer.start(); for( size_t step=0UL, i=0UL; step<steps; ++step, ++i ) { if( i == N ) i = 0UL; C[i].noalias() = A[i] + B[i]; } timer.end(); for( size_t i=0UL; i<N; ++i ) if( C[i](0,0) < element_t(0) ) std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n"; if( timer.last() > maxtime ) break; } const double minTime( timer.min() ); const double avgTime( timer.average() ); if( minTime * ( 1.0 + deviation*0.01 ) < avgTime ) std::cerr << " Eigen kernel 'tmat3tmat3add': Time deviation too large!!!\n"; return minTime; } //************************************************************************************************* } // namespace eigen } // namespace blazemark
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
3465a01af4da74c9a66d329caeffc841853b7573
20d3c1a579e6d17fe209bf5715fbf75a2e60987c
/Segment-Tree/poj3234.cpp
771f3848c3d261c6a6f31e022bad4b0a613be3c1
[]
no_license
brickgao/ACM_Workspace
c2b31e835cff2bdd600924f7a0532edd32613a3e
cf165d09c319cd2c2d46399a569faecd5c1058b3
refs/heads/master
2021-01-01T17:52:21.309965
2013-10-12T11:49:32
2013-10-12T11:49:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,753
cpp
//By Brickgao #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> using namespace std; #define out(v) cerr << #v << ": " << (v) << endl #define SZ(v) ((int)(v).size()) const int maxn = 200010; const int INF = 1000010; #define lson l, m, rt << 1 #define rson m + 1, r, rt << 1 | 1 template <class T> bool get_max(T& a, const T &b) {return b > a? a = b, 1: 0;} template <class T> bool get_min(T& a, const T &b) {return b < a? a = b, 1: 0;} typedef struct record { int mx, mi; } record; record sum[maxn << 2]; void PushUP(int rt) { sum[rt].mi = min(sum[rt << 1].mi, sum[rt << 1 | 1].mi); sum[rt].mx = max(sum[rt << 1].mx, sum[rt << 1 | 1].mx); } void build(int l, int r, int rt) { if(l == r) { scanf("%d", &sum[rt].mx); sum[rt].mi = sum[rt].mx; return; } int m = (l + r) >> 1; build(lson); build(rson); PushUP(rt); } record query(int L, int R, int l, int r, int rt) { if(L <= l && R >= r) { return sum[rt]; } int m = (l + r) >> 1; record ret; ret.mi = INF; ret.mx = -1; if(L <= m) { record tmp = query(L, R, lson); ret.mi = min(ret.mi, tmp.mi); ret.mx = max(ret.mx, tmp.mx); } if(R > m) { record tmp = query(L, R, rson); ret.mi = min(ret.mi, tmp.mi); ret.mx = max(ret.mx, tmp.mx); } return ret; } int main() { int n, q; while(scanf("%d%d", &n, &q) != EOF) { build(1, n, 1); for(int i = 0; i < q; i ++) { int a, b; scanf("%d%d", &a, &b); record ret = query(a, b, 1, n, 1); printf("%d\n", ret.mx - ret.mi); } } return 0; }
[ "brickgao@gmail.com" ]
brickgao@gmail.com
4e9c19fa512213e47444fbecaa108be7d24bf10a
75eb7a90cf99860a61af6d4ad5d5543778920d80
/swap/swap.cpp
20951dbc7168c5f0578ef63b90391a38287a9f91
[]
no_license
skyele/morgen-project
0059d77f5f853072c45976b3cd23d5f8807c575d
033a0be78ed910c0755865b6ff760ca5269d3be6
refs/heads/master
2020-12-02T23:55:24.979275
2017-07-01T12:39:59
2017-07-01T12:39:59
95,963,112
0
0
null
null
null
null
UTF-8
C++
false
false
8,712
cpp
#include"date.h" #include"holiday.h" #include"price_start_end.h" class date; class date_info; class holiday; class month_info; class date_info; string re_str(string ss, char replaced_char); //this function used to process lines; replace char like';' '{' ',' with replace bool is_holiday(string date, holiday holidays); //check whether if holiday or not void update_info(string& lines, int& trade_numb, string &Counterparty, char& trade_type, double&fixe_price, string& float_index, double& quantity, string&UOM, string& pricing_start, string& pricing_end); string get_standard_day1(int day, int month, int year);// form:20170516 string get_standard_day2(int day, int month, int year);// form:5/17/2017 string transform_month(int month); //12 - december; double stringtoint(string ss); //transform string to int int main() { date_info days; holiday holidays; price_start_end forwards; string user_date; cout << "today date: "; bool date_exist = false; while (cin >> user_date) //form: 20170515 { for (int i = 0; i < days.dates.size(); i++) { if (days.dates[i].the_date == user_date) date_exist = true; } if (!date_exist) { cout << "date information not found" << endl; cout << "today date: "; } else break; } string lines; string file_name1 = "Swap Trade Sample_Commodities.csv"; ifstream is1(file_name1); getline(is1, lines); while (getline(is1, lines)) //get trade infomation { string replace; int trade_numb;//1000001 string Counterparty;//company A char trade_type;//S B double fixed_price;//50 user price string float_index;//WTI1nb double quantity;//22000 string UOM;//bbl string pricing_start;// 5/1/2017 string pricing_end; // 5/31/2017 double standard_price=0; update_info(lines, trade_numb, Counterparty, trade_type, fixed_price, float_index, quantity, UOM, pricing_start, pricing_end); //10 parameters int contractmonth; int prosperity; int start_day; int end_day; int year; string temp_start = re_str(pricing_start, '/'); stringstream stringtoint1(temp_start); stringtoint1 >> contractmonth; stringtoint1 >> start_day; stringtoint1 >> year; prosperity = contractmonth; string temp_end = re_str(pricing_end, '/'); stringstream stringtoint2(temp_end); stringtoint2 >> end_day >> end_day; date contract_date; vector<map<string, string>> more_details; for (int i = 0; i < days.dates.size(); i++) { if (days.dates[i].the_date == user_date) { if (float_index == "WTI") more_details = days.dates[i].WTI; else more_details = days.dates[i].BRENT; } } int current_day = start_day; //loop int day_amounts=0; string enr_month = transform_month(contractmonth); double this_month_mark=0; double next_month_mark=0; for (int i = 0; i < more_details.size(); i++) { string standard_date2 = get_standard_day1(current_day, contractmonth, year);//transfer form if (more_details[i]["Date"] == standard_date2) { if (more_details[i]["Type"] == "SettlementPrice") //settlement prosperity++; } enr_month = transform_month(prosperity); if (more_details[i]["Type"] == "Forward") { //forward if (more_details[i]["ContractMonth"] == enr_month.substr(0, 3) + '-' + "17") { this_month_mark = stringtoint(more_details[i]["Mark"]); if (contractmonth != 12) next_month_mark = stringtoint(more_details[i + 1]["Mark"]); } } } string current_month_forward; if (float_index == "WTI"){ for (int i = 0; i < forwards.WTI_in_month.size(); i++) { if (forwards.WTI_in_month[i].the_month.substr(3) == transform_month(prosperity).substr(0, 3))//watch out! current_month_forward = forwards.WTI_in_month[i].st_en[1]; } } else if (float_index == "BRENT") { for (int i = 0; i < forwards.BRENT_in_month.size(); i++) { if (forwards.BRENT_in_month[i].the_month.substr(3) == transform_month(prosperity).substr(0, 3))//watch out! current_month_forward = forwards.BRENT_in_month[i].st_en[1]; } } current_month_forward = current_month_forward.substr(current_month_forward.size() - 2);//22 20 int int_month_forwad = stringtoint(current_month_forward); while (current_day <= end_day) { string standard_date1 = get_standard_day1(current_day, contractmonth, year); if (is_holiday(get_standard_day2(current_day, contractmonth, year), holidays)) { current_day++; continue; } bool isexist = false; for (int i = 0; i < more_details.size(); i++) { if (more_details[i]["Date"] == standard_date1) { if (more_details[i]["Type"] == "SettlementPrice") { string mark = more_details[i]["Mark"]; istringstream stringtodouble(mark); double today_price; stringtodouble >> today_price; standard_price += today_price; isexist = true; } } } if (!isexist) { if (current_day <= int_month_forwad) standard_price += this_month_mark; else standard_price += next_month_mark; } current_day++; day_amounts++; } double floating_price = standard_price / day_amounts; cout << "Trade number: " << trade_numb << endl; cout<<"floating price: " <<floating_price <<" "; if (trade_type == 'B') cout << "profit: " << setprecision(4)<< fixed << (floating_price - fixed_price) *quantity << endl; else cout << "profit: " << fixed << (fixed_price - floating_price)*quantity << endl; } keep_window_open(); } string re_str(string ss, char replaced_char) { string replace; for (int i = 0; i < ss.size(); i++) { if (ss[i] == replaced_char) { replace = replace + " "; } else replace = replace + ss[i]; } return replace; } bool is_holiday(string date, holiday holidays)// 5/1/2017 { date = re_str(date, '/'); stringstream holiday_stream(date); int month; int day; int year; holiday_stream >> month; holiday_stream >> day; holiday_stream >> year; if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int W; W = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7+1; if (W == 6 || W == 7) return true; for (int i = 0; i < holidays.holiday_in_law.size(); i++) { if (holidays.holiday_in_law[i] == date) return true; } return false; } void update_info(string& lines, int& trade_numb, string &Counterparty,char& trade_type,double&fixe_price, string& float_index, double& quantity, string&UOM,string& pricing_start,string& pricing_end) { string replace; replace = re_str(lines, ','); istringstream is(replace); is >> trade_numb; is >> Counterparty; string temp_counterparty; is >> temp_counterparty; Counterparty = Counterparty + ' ' + temp_counterparty; is >> trade_type; is >> fixe_price; is >> float_index; is >> quantity; is >> UOM; is >> pricing_start; is >> pricing_end; quantity = quantity; //* 2500; for (int i = 0; i < float_index.size(); i++) { if (isdigit(float_index[i])) float_index = float_index.substr(0, i); } } string get_standard_day1(int day, int month, int year)//20170515 { stringstream temp_stream1; temp_stream1 << year; string standard_date; string temp_std_date; temp_stream1 >> standard_date; stringstream temp_stream2; temp_stream2 <<month; temp_stream2 >> temp_std_date; if (month < 10) temp_std_date = '0' + temp_std_date; standard_date += temp_std_date; stringstream temp_stream3; temp_stream3 <<day; temp_stream3 >> temp_std_date; if (day < 10) temp_std_date = '0' + temp_std_date; standard_date += temp_std_date; return standard_date; } string get_standard_day2(int day, int month, int year)// 5/17/2017 { stringstream temp_stream1; temp_stream1 << month; string standard_date; string temp_std_date; temp_stream1 >> standard_date; stringstream temp_stream2; temp_stream2 << day; temp_stream2 >> temp_std_date; standard_date =standard_date+'/'+ temp_std_date; stringstream temp_stream3; temp_stream3 << year; temp_stream3 >> temp_std_date; standard_date = standard_date + '/' + temp_std_date; return standard_date; } string transform_month(int month) { if (month == 1) return "January"; else if (month == 2) return "February"; else if (month == 3) return "March"; else if (month == 4) return"April"; else if (month == 5) return"May"; else if (month == 6) return"June"; else if (month == 7) return "July"; else if (month == 8) return "August"; else if (month == 9) return "September"; else if (month == 10) return"October"; else if (month == 11) return"November"; else if (month == 12) return"December"; } double stringtoint(string ss) { stringstream stream(ss); double result; stream >> result; return result; }
[ "skyele@sjtu.edu.cn" ]
skyele@sjtu.edu.cn
3ac5b7846843a207bb0482d72d4097b645f558df
e15fff0f0e70a2fec8633116dfabeecedfb6eb3a
/quickUnion.h
d964a70b9a60676aa5e211a801ef9fc932ec4d19
[]
no_license
Alan-Solitar/Connection-Algorithms
ce78dd13f696c65130f7f4e6d8af5113e2815536
485734d649a3a96bb2cdeeae486e04c9c1e758a6
refs/heads/master
2021-01-19T18:11:39.119734
2015-09-12T01:26:47
2015-09-12T01:26:47
42,335,676
0
0
null
null
null
null
UTF-8
C++
false
false
288
h
#ifndef QUICKUNION_H #define QUICKUNION_H #include <vector> #include <string> class quickUnion { private: std::vector<int> id; public: std::string title; quickUnion(int n); int find(int a); void Union(int a, int b); std::vector<int> getID(); }; #endif
[ "alsolita1@gmail.com" ]
alsolita1@gmail.com
c14daf03c34e63a1b95c83572660093d782a608c
40095981cd158032c25ae5aa847b45b259c40480
/code/HostControllerFirmware/Onyx-HostFirmware-7-24-15/libraries/Onyx/Onyx.h
1915373e438dd55f370ec6c319187024fcf733e2
[]
no_license
MiddleMan5/Project-Onyx-Quadruped
712dd5f2e47c91a6d4b031272e2a4675ffadf7d1
7e8e3172420bdfeeb761f0eda585596349ec0821
refs/heads/master
2021-01-24T22:02:21.700807
2015-09-04T19:38:39
2015-09-04T19:38:39
36,832,368
0
0
null
null
null
null
UTF-8
C++
false
false
3,527
h
//Onyx library creates classes to represent the various functions and systems of the Onyx Robotic Quadruped. //The current CPU is an arduino-like Chipkit Uno32 #ifndef _Onyx_H #define _Onyx_H #if (ARDUINO >= 100) # include <Arduino.h> #endif //-Extra Includes- #include "SSC32.h" #include <math.h> //Onyx Definitions #define baudrate 115200 //Symbols per second. Default hardware set 115200 #define sscReturn 0 //Is SSC32 Connected bi-directionally? (default "0" = no) //Physical Dimensions //all in floating point millimetres accurate to the thousandth #define Trochanter_X 61.40 #define Trochanter_Y 4.34 //CAD Model Incorrect!! #define Femur_X 24.29 #define Femur_Y 50.78 #define Femur 56.29 //The L1 Value #define L1 56.29 #define Tibia 41.02 #define Tarsus 62.00 //Tibia + Tarsus = L2 Value #define L2 103.02 #define Body_Width 139.72 #define Body_Length 106.25 //---------------------------------------------------------------------------- //Servo-Power Relay Pin #define relayServos 27 //------------------------------------------------------------------------------------------------------------- //On Off Toggle References #define ON 1 #define OFF 0 #define HIGH 1 #define LOW 0 #define TOGGLE 2 //Movement Scopes #define BODY 0 #define LEG 1 #define SERVO 2 //runtime modes #define REBOOT 0 #define LOWPOWER 1 #define STARTUP 2 #define STANDBY 3 #define STOPPED 4 #define MOVING 5 #define DEBUG 6 #define VIRTUAL 7 #define SHUTDOWN 8 #define ERROR 9 //move types #define UP 0 #define DOWN 1 #define LEFT 2 #define RIGHT 3 #define STAND 4 #define SIT 5 #define X 0 #define Y 1 #define Z 2 #define PI 3.14159 class Onyx { private: int _attitude; //Needs to be further developed (similar to speed, the robots attitude is a prototype hardware-control emotion) greateer attitude = greater speed int _mode; int _ServoList[12]; int _Z_rotation; int _X_rotation; int _Y_rotation; public: Onyx(); void startup(); void setAttitude(int attitude); //Current servo "Speed Control" - Prototypical function void setMode(int mode); //sets runtime state void listen(); void reconnectSSC(); //reinitialize SSC instance communication void moveScope(int scope); void newMove(int type); void move(int type); void rotate(int axis, int degree); void Log(); }; class Power { private: int Main_Relay; bool _powerMain; //Power State (ON,OFF) public: Power(int Main_Relay); void setMainPin(int pin); void ToggleMain(int state); }; class Servo { private: int _pin; int _time; bool _isInvert; bool _isExternal; //is "on" another controller (the ssc-32 that has a different IO pin name) bool _isGroup; //Is the servo part of a group? int _groupNumber; int _position; public: Servo(); void move(int pulse); void setTime(int input); //time it takes to move void setGroup(int groupNumber); void setMax(int Max); void setMin(int Min); void invert(); void setPin(int pin); }; class Leg { private: int _speed; float _Trochanter_X; float _Trochanter_Y; float _Femur_X; float _Femur_Y; float _Femur; float _L1; float _Tibia; float _Tarsus; float _L2; int _quadrant; bool _isGroup; Servo Coxa; Servo Knee; Servo Ankle; public: Leg(); void rotate(int degree); void setSpeed(int speed); void setMaster(); void move(int pulse); void setQuadrant(int index); void moveFootTo(float x, float y); }; #endif
[ "mikelson.public@gmail.com" ]
mikelson.public@gmail.com
6759d1b13f303989ac0969298ac2864a25084763
2c0132195b3f84801cdbc61e37ea689a5086c82e
/Logo.h
ee99a4942e1c2374dafb59376c0e85d8bc407caf
[]
no_license
thijse/KamadoControl
31a31bd918ca6d202b546e8c2d9403497edc504a
3658f1b74e6225e9a548e4979cb08f851a3a87eb
refs/heads/master
2023-04-11T06:52:10.028192
2021-04-26T20:44:22
2021-04-26T20:44:22
336,391,802
0
0
null
null
null
null
UTF-8
C++
false
false
491
h
#pragma once #include "arduino.h" #include <GxEPD2_GFX.h> #include <GxEPD2_EPD.h> #include <GxEPD2_BW.h> #include <GxEPD2.h> #include "Screen.h" class Logo { protected: Screen* _display; int _posX; int _posY; int _width; int _height; const static unsigned char lilygo[]; public: Logo (const Logo& other) = delete; Logo& operator=(const Logo& other) = delete; Logo(Screen* display); void init(); void update(); void draw(); };
[ "thijs@contemplated.nl" ]
thijs@contemplated.nl
bc02933627f6b92dd878c07b8b601b75c5b9ec4a
bad8c2e0478c61ceb10ca1fc1cd545d391f553ea
/hlt/astar.cpp
adff09d5b7e0095bd691d99e751b998ae35e2d8a
[]
no_license
Rampagy/halite3
1a0a9b9844081177a2a8721bed915c3d5a10076a
cca0ab2ed7da8ae04b0f1930704dd35d2469bd1a
refs/heads/master
2020-04-20T14:25:29.671118
2019-03-05T17:36:11
2019-03-05T17:36:11
168,897,876
0
0
null
null
null
null
UTF-8
C++
false
false
6,244
cpp
#include "astar.hpp" float heuristic(Position a, Position b, const unique_ptr<GameMap>& game_map) { return (float)game_map->calculate_distance(a, b); } Direction astar(unordered_map<int, unordered_map<int, Halite>> halite_map, const Position start, const Position goal, const unordered_set<Position>& occupied_spaces, const unique_ptr<GameMap>& game_map, const unordered_map<EntityId, Position>& dropoffs, const unordered_map<EntityId, Position>& other_dropoffs, const unordered_map<EntityId, Position>& undesireable, const unordered_map<EntityId, shared_ptr<Ship>>& other_ships, Halite& path_halite, int& distance, bool end_game, bool target_is_drop) { if (start != goal) { unordered_set<Position> close_set; unordered_map<Position, Position> came_from; unordered_map<Position, float> gscore; unordered_map<Position, float> fscore; priority_queue<score_T, vector<score_T>, greater<score_T>> oheap; unordered_set<Position> oheap_copy; unordered_set<Position> unwalkable; bool goal_is_drop = false; for (const auto& drop_iter : dropoffs) { if (drop_iter.second == goal) { goal_is_drop = true; break; } } for (const Position occ_pos : occupied_spaces) { if (!end_game || !game_map->at(occ_pos)->has_structure()) { bool found = false; if (goal_is_drop) { for (const auto& drop_iter : dropoffs) { if (drop_iter.second == occ_pos) { found = true; break; } } } // do not add if occ_pos is drop off and goal to start distance is > 2 if ((!found) || (game_map->calculate_distance(start, goal) < 2)) { unwalkable.insert(occ_pos); } } } for (const auto& drop_iter : dropoffs) { halite_map[drop_iter.second.y][drop_iter.second.x] += (Halite)1000; } for (const auto& drop_iter : other_dropoffs) { halite_map[drop_iter.second.y][drop_iter.second.x] += (Halite)1000; } for (const auto& undesired : undesireable) { halite_map[undesired.second.y][undesired.second.x] += (Halite)1000; } for (const auto& o_ship_iter : other_ships) { unwalkable.insert(o_ship_iter.second->position); for (Position p : o_ship_iter.second->position.get_surrounding_cardinals()) { p = game_map->normalize(p); if (target_is_drop && (game_map->calculate_distance(start, goal) > 6)) { unwalkable.insert(p); } else { halite_map[p.y][p.x] += (Halite)500; } } } gscore[start] = 0; fscore[start] = heuristic(start, goal, game_map); oheap.push(make_pair(fscore[start], start)); oheap_copy.insert(start); while(!oheap.empty()) { Position current = oheap.top().second; oheap.pop(); oheap_copy.erase(current); if (current == goal) { vector<Position> data; while (came_from.find(current) != came_from.end()) { data.push_back(current); current = came_from[current]; path_halite += game_map->at(current)->halite; distance++; } // can only move 1 spot per turn, so only ret that spot Direction dir = Direction::STILL; for (const auto& curr_dir : ALL_CARDINALS) { Position check_pos = game_map->normalize( start.directional_offset(curr_dir)); if (check_pos == data.back()) { dir = curr_dir; } } return dir; } close_set.insert(current); array<Position, 4> neighbors = current.get_surrounding_cardinals(); for (Position neighbor : neighbors) { neighbor = game_map->normalize(neighbor); if (unwalkable.find(neighbor) != unwalkable.end()) { continue; } float tentative_g_score = gscore[current] + 300 + halite_map[current.y][current.x]; float current_gscore; if (gscore.find(neighbor) == gscore.end()) { current_gscore = 0; } else { current_gscore = gscore.find(neighbor)->second; } if ((close_set.find(neighbor) != close_set.end()) && (tentative_g_score >= current_gscore)) { continue; } if ((tentative_g_score < current_gscore) || (oheap_copy.find(neighbor) == oheap_copy.end())) { came_from[neighbor] = current; gscore[neighbor] = tentative_g_score; fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal, game_map); oheap.push(make_pair(fscore[neighbor], neighbor)); if (oheap_copy.find(neighbor) == oheap_copy.end()) { // don't add twice (keys must be unique) oheap_copy.insert(neighbor); } } } } } return Direction::STILL; }
[ "ajsimon@mtu.edu" ]
ajsimon@mtu.edu
335fd77a84dce2e02fd6cf831ed3bfb29e71fedf
9c6e7d86246e20578fd1f8cc6a9cdd960dfe0ea7
/switch/switch.ino
7b47b6934b899baa7dbad8cb83c460b791f7a419
[ "Apache-2.0" ]
permissive
uajith/A4Arduino
fa76f2198fe5a06aebfdd2e44473a24baca2d9c8
54429f095223db8016ede54188cc927784f4f02b
refs/heads/main
2023-05-08T04:21:14.158665
2021-05-31T09:45:20
2021-05-31T09:45:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,450
ino
void setup() { // initialize serial communication: Serial.begin(9600); // initialize the LED pins: for (int thisPin = 2; thisPin < 7; thisPin++) { pinMode(thisPin, OUTPUT); } } void loop() { // read the sensor: if (Serial.available() > 0) { char inByte = Serial.read(); Serial.println(inByte); // do something different depending on the character received. // The switch statement expects single number values for each case; in this // example, though, you're using single quotes to tell the controller to get // the ASCII value for the character. For example 'a' = 97, 'b' = 98, // and so forth: switch (inByte) { case 'a': digitalWrite(2, HIGH); Serial.println("A is entered"); delay(500); break; case 'b': digitalWrite(3, HIGH); Serial.println("B is entered"); delay(500); break; case 'c': digitalWrite(4, HIGH); Serial.println("C is entered"); delay(500); break; case 'd': Serial.println("D is entered"); digitalWrite(5, HIGH); delay(500); break; case 'e': Serial.println("E is entered"); digitalWrite(6, HIGH); delay(5000); break; default: // turn all the LEDs off: for (int thisPin = 2; thisPin < 7; thisPin++) { digitalWrite(thisPin, LOW); } } } }
[ "adinath.ajit@gmail.com" ]
adinath.ajit@gmail.com
5b71e6653e5a75ffd2d90d21872041990d859459
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/chromeos/dbus/concierge_client.h
5d0cfee8ef66122d888bb27713629fd776821704
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
3,985
h
// Copyright 2018 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 CHROMEOS_DBUS_CONCIERGE_CLIENT_H_ #define CHROMEOS_DBUS_CONCIERGE_CLIENT_H_ #include "chromeos/chromeos_export.h" #include "chromeos/dbus/concierge/service.pb.h" #include "chromeos/dbus/dbus_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "dbus/object_proxy.h" namespace chromeos { // ConciergeClient is used to communicate with Concierge, which is used to // start and stop VMs. class CHROMEOS_EXPORT ConciergeClient : public DBusClient { public: class Observer { public: // OnContainerStartupFailed is signaled by Concierge after the long-running // container startup process's failure is detected. Note the signal protocol // buffer type is the same as in OnContainerStarted. virtual void OnContainerStartupFailed( const vm_tools::concierge::ContainerStartedSignal& signal) = 0; protected: virtual ~Observer() = default; }; // Adds an observer. virtual void AddObserver(Observer* observer) = 0; // Removes an observer if added. virtual void RemoveObserver(Observer* observer) = 0; // IsContainerStartupFailedSignalConnected must return true before // StartContainer is called. virtual bool IsContainerStartupFailedSignalConnected() = 0; // Creates a disk image for the Termina VM. // |callback| is called after the method call finishes. virtual void CreateDiskImage( const vm_tools::concierge::CreateDiskImageRequest& request, DBusMethodCallback<vm_tools::concierge::CreateDiskImageResponse> callback) = 0; // Destroys a Termina VM and removes its disk image. // |callback| is called after the method call finishes. virtual void DestroyDiskImage( const vm_tools::concierge::DestroyDiskImageRequest& request, DBusMethodCallback<vm_tools::concierge::DestroyDiskImageResponse> callback) = 0; // Lists the Termina VMs. // |callback| is called after the method call finishes. virtual void ListVmDisks( const vm_tools::concierge::ListVmDisksRequest& request, DBusMethodCallback<vm_tools::concierge::ListVmDisksResponse> callback) = 0; // Starts a Termina VM if there is not alread one running. // |callback| is called after the method call finishes. virtual void StartTerminaVm( const vm_tools::concierge::StartVmRequest& request, DBusMethodCallback<vm_tools::concierge::StartVmResponse> callback) = 0; // Stops the named Termina VM if it is running. // |callback| is called after the method call finishes. virtual void StopVm( const vm_tools::concierge::StopVmRequest& request, DBusMethodCallback<vm_tools::concierge::StopVmResponse> callback) = 0; // Registers |callback| to run when the Concierge service becomes available. // If the service is already available, or if connecting to the name-owner- // changed signal fails, |callback| will be run once asynchronously. // Otherwise, |callback| will be run once in the future after the service // becomes available. virtual void WaitForServiceToBeAvailable( dbus::ObjectProxy::WaitForServiceToBeAvailableCallback callback) = 0; // Gets SSH server public key of container and trusted SSH client private key // which can be used to connect to the container. // |callback| is called after the method call finishes. virtual void GetContainerSshKeys( const vm_tools::concierge::ContainerSshKeysRequest& request, DBusMethodCallback<vm_tools::concierge::ContainerSshKeysResponse> callback) = 0; // Creates an instance of ConciergeClient. static ConciergeClient* Create(); ~ConciergeClient() override; protected: // Create() should be used instead. ConciergeClient(); private: DISALLOW_COPY_AND_ASSIGN(ConciergeClient); }; } // namespace chromeos #endif // CHROMEOS_DBUS_CONCIERGE_CLIENT_H_
[ "artem@brave.com" ]
artem@brave.com
963f99cb57365b3106e557ff0ecfb25530392d8e
83277c07fd14427925491ed863cb426707ccd78a
/Dynamic Programming/Best Time to Buy and Sell Stocks II.cpp
63d10ece1edabfec0783638a6b0222f14ea6810f
[]
no_license
sonali9696/InterviewBit
78edbd2d2dddf02bcd77ca2f74e3d367c84fa128
40fb6fb8cbdf3e9f3b6d643b94caed1fd3e53b51
refs/heads/master
2020-06-08T22:10:16.969319
2020-05-24T13:59:15
2020-05-24T13:59:15
193,315,514
1
0
null
null
null
null
UTF-8
C++
false
false
380
cpp
int Solution::maxProfit(const vector<int> &a) { int l = a.size(); if(l == 0 || l == 1) return 0; int p = 0, prev = a[0]; for(int i=1; i<l; i++) { if(a[i] > prev) { p += (a[i]-prev); prev = a[i]; } else if(a[i] < prev) { prev = a[i]; } } return p; }
[ "soagraw@microsoft.com" ]
soagraw@microsoft.com
1a33be276b24883e253cfca4e625616ecc61adcc
03beffff7a9bb403f9dff279d67116b511f4d70c
/ecuatii/Repository.h
a8dab5bde988ef3166ec0d96a92c79f0e079a52d
[]
no_license
dianatalpos/Object-Oriented-Programming
29d4000f5137e2c8b1e33ca7c6d0306902f0f058
587c8d10aff44a689392343526ca3ee09709c26a
refs/heads/master
2020-09-04T17:01:18.962828
2019-11-05T21:03:33
2019-11-05T21:03:33
219,823,683
0
0
null
null
null
null
UTF-8
C++
false
false
297
h
#pragma once #include <vector> #include <string> #include "Equation.h" class Repository { private: std::vector<Equation> elems; std::string file; public: Repository(std::string file); ~Repository(); std::vector<Equation> getAll(); private: void readAllFromFile(); };
[ "diana.talpos4@gmail.com" ]
diana.talpos4@gmail.com
bd1943a07b254b1505438f84759412ea70d6b4a7
7aa32aeb271e5336996db0b0108d0dc8d9fb468f
/dialog/Menutrol.hpp
4bfebd02f2790f3de9498771c611372a5d39b540
[]
no_license
Icaruk/Poplife2
1f3db20474974d1f62ae25c4b7168052b6b73c31
e958bfac338a7242f9771611967d324b7d8f2dfc
refs/heads/master
2020-08-07T23:16:05.605404
2019-10-08T22:25:22
2019-10-08T22:25:22
213,618,708
3
3
null
null
null
null
UTF-8
C++
false
false
4,670
hpp
class Menutrol_dialog { idd = -1; movingenable = true; onLoad = "uiNamespace setVariable ['Menutrol_dialog', _this select 0];"; onUnLoad = "uiNamespace setVariable ['Menutrol_dialog', nil];"; class controls { //////////////////////////////////////////////////////// // GUI EDITOR OUTPUT START (by TDR Acj, v1.063, #Vexero) //////////////////////////////////////////////////////// class imagen: RscPicture { type = CT_STATIC; style = ST_PICTURE; text = "\pop_iconos\paa\trol1.paa"; idc = -1; x = 0.396875 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.180469 * safezoneW; h = 0.517 * safezoneH; }; class Botonpineta: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\peineta.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Peineta"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.247 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class Botonpaja: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\paja.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Paja"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.291 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class BotonMear: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\mear.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Mear"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.335 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class BotonPlantarpino: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\plantar.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Plantar Pino"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.379 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class Botonazotes: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\azotes.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Azotar"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.423 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class Botontriste: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\triste.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Triste"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.467 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class BotonAmenazar: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\amenazar.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Amenazar"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.511 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class Botonapuntar: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\apuntar.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Apuntar"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.555 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class BotonSaludar: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\saludar.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Saludar"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.599 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class Botonok: RscButton { action = "closeDialog 0; execVM ""acj\animaciones\ok.sqf"""; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "ok"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.643 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class botonparar: RscButton { action = "closeDialog 0; player playMove ''"; colorBackground[] = {1,1,1,1}; colorDisabled[] = {1,1,1,1}; idc = -1; text = "Parar"; //--- ToDo: Localize; x = 0.438125 * safezoneW + safezoneX; y = 0.687 * safezoneH + safezoneY; w = 0.0979687 * safezoneW; h = 0.033 * safezoneH; }; class IGUIBack_2200: IGUIBack { idc = -1; x = 0.412344 * safezoneW + safezoneX; y = 0.247 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.473 * safezoneH; }; //////////////////////////////////////////////////////// // GUI EDITOR OUTPUT END //////////////////////////////////////////////////////// }; };
[ "adri-rk@hotmail.com" ]
adri-rk@hotmail.com
86196e05dc74bd5ad3059eb8b213f633799fdff0
5d01a2a16078b78fbb7380a6ee548fc87a80e333
/ETS/Components/MM/EtsMmIndexHedge/MmIhIndexAtom.cpp
7dbd35d146d095313c6538b4c4d040739547a12f
[]
no_license
WilliamQf-AI/IVRMstandard
2fd66ae6e81976d39705614cfab3dbfb4e8553c5
761bbdd0343012e7367ea111869bb6a9d8f043c0
refs/heads/master
2023-04-04T22:06:48.237586
2013-04-17T13:56:40
2013-04-17T13:56:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,524
cpp
// MmIhIndexAtom.cpp : Implementation of CMmIhIndexAtom #include "stdafx.h" #include "MmIhIndexAtom.h" // CMmIhIndexAtom ///////////////////////////////////////////////////////////////////////////// // void CMmIhIndexAtom::_GetBasketIndexDividends(REGULAR_DIVIDENDS* pDivs, LONG nMaxCount) throw() { EtsRegularDividend aDiv; for(LONG i = 0; i < nMaxCount; i++) { _CHK(m_spBasketIndex->get_BasketDiv(i, &aDiv), _T("Fail to get basket dividend.")); pDivs[i].nLastDivDate = static_cast<LONG>(aDiv.LastDate); pDivs[i].nFrequency = aDiv.Freq; pDivs[i].dAmount = aDiv.Amt; } } HRESULT CMmIhIndexAtom::CalcOptionGreeks(IMmIhOptAtomPtr aOpt, DOUBLE dSpotPriceMid, EtsCalcModelTypeEnum enCalcModel, VARIANT_BOOL bUseTheoVolatility, VARIANT_BOOL bUseTheoVolaNoBid, VARIANT_BOOL bUseTheoVolaBadMarket, DOUBLE dUndPriceTolerance, EtsPriceRoundingRuleEnum enPriceRoundingRule, ICalculationParametrs* pParams) { if(aOpt == NULL || pParams == NULL) return Error(L"Invalid objects passed.", IID_IMmIhIndexAtom, E_INVALIDARG); try { IMmIhOptAtomPtr spOpt(aOpt); CSafeArrayWrapper<double> saDates; CSafeArrayWrapper<double> saAmounts; DOUBLE dOptPriceMid = 0., dDelta = BAD_DOUBLE_VALUE; EtsReplacePriceStatusEnum enMidPriceStatus = enRpsNone; DOUBLE dOptBid = 0., dOptAsk = 0., dOptLast = 0.; _CHK(spOpt->get_PriceBid(&dOptBid)); _CHK(spOpt->get_PriceAsk(&dOptAsk)); _CHK(spOpt->get_PriceLast(&dOptLast)); dOptPriceMid = m_spOptPriceProfile->GetOptPriceMid(dOptBid, dOptAsk, dOptLast, enPriceRoundingRule, bUseTheoVolatility, 0, &enMidPriceStatus); if(dSpotPriceMid > DBL_EPSILON) { GREEKS aGreeks; memset(&aGreeks, 0, sizeof(aGreeks)); aGreeks.nMask = GT_DELTA; LONG nModel = static_cast<LONG>(enCalcModel); LONG nIsAmerican = (m_bIsAmerican ? 1L : 0L); DOUBLE dYield = 0.; LONG nDivCount = 0L, nRetCount = 0L; DOUBLE dRate = 0.; _CHK(spOpt->get_Rate(&dRate)); DOUBLE dHTBRate = BAD_DOUBLE_VALUE; _CHK(spOpt->get_HTBRate(&dHTBRate)); DOUBLE dStrike = 0.; _CHK(spOpt->get_Strike(&dStrike)); EtsOptionTypeEnum enOptType = enOtPut; _CHK(spOpt->get_OptType(&enOptType)); DATE dtTemp = 0., dtExpiryOV = 0., tmCloseTime = 0., dtNow = 0.; DOUBLE dYTE = 0.; _CHK(spOpt->get_ExpiryOV(&dtExpiryOV)); _CHK(spOpt->get_TradingClose(&tmCloseTime)); ::GetNYDateTimeAsDATE(&dtNow); ::GetCalculationParams(dtNow, dtExpiryOV, tmCloseTime, pParams->UseTimePrecision != VARIANT_FALSE, &dtNow, &dtExpiryOV, &tmCloseTime, &dYTE); if(m_spBasketIndex != NULL) { LONG nBaskDivCount = 0L; VARIANT_BOOL bIsBasket = VARIANT_FALSE; _CHK(m_spBasketIndex->get_IsBasket(&bIsBasket)); if(bIsBasket /*&& nBaskDivCount > 0L*/) { IEtsIndexDivCollPtr spBasketDivs; m_spBasketIndex->get_BasketDivs(&spBasketDivs); nDivCount = 0; spBasketDivs->GetDividendCount2(dtNow, dtExpiryOV, tmCloseTime, &nDivCount); if(nDivCount > 0L) { LPSAFEARRAY psaDates = NULL; LPSAFEARRAY psaAmounts = NULL; spBasketDivs->GetDividends2(dtNow, dtExpiryOV, tmCloseTime, nDivCount, &psaAmounts, &psaDates, &nDivCount); saDates.Attach(psaDates); saAmounts.Attach(psaAmounts); } } } else if(nDivCount <= 0.) dYield = m_dYield; // volatility calculation DOUBLE dVola = 0.; if (bUseTheoVolatility) _CHK(spOpt->get_Vola(&dVola)); else { dVola = 0; if (!bUseTheoVolaNoBid || (bUseTheoVolaNoBid && dOptBid > 0)) { if (dOptPriceMid > DBL_EPSILON) { LONG nFlag = VF_OK; dVola = ::CalcVolatilityMM3(dRate, dYield, dHTBRate, dSpotPriceMid, dOptPriceMid, dStrike, dYTE, enOptType, nIsAmerican, nDivCount, saAmounts.GetPlainData(), saDates.GetPlainData(), 100L, m_dSkew, m_dKurt, nModel, &nFlag); if (bUseTheoVolaBadMarket && nFlag != VF_OK) _CHK(spOpt->get_Vola(&dVola)); } else if (bUseTheoVolaBadMarket) _CHK(spOpt->get_Vola(&dVola)); } else _CHK(spOpt->get_Vola(&dVola)); } nRetCount = ::CalcGreeksMM2(dRate, dYield, dHTBRate, dSpotPriceMid, dStrike, dVola, dYTE, enOptType, nIsAmerican, nDivCount, saAmounts.GetPlainData(), saDates.GetPlainData(), 100L, m_dSkew, m_dKurt, nModel, &aGreeks); if(nRetCount != 0L) { if((aGreeks.nMask & GT_DELTA) && _finite(aGreeks.dDelta)) dDelta = aGreeks.dDelta; } } _CHK(spOpt->put_Delta(dDelta)); } catch(const _com_error& e) { return Error((PTCHAR)CComErrorWrapper::ErrorDescription(e), IID_IMmIhIndexAtom, e.Error()); } return S_OK; } //////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////// void CMmIhIndexAtom::_CalcSleep(LONG nCalcSleepFreq, LONG nCalcSleepAmt) { if(nCalcSleepAmt > 0L && nCalcSleepFreq > 0L) { if((m_nSleepStep % nCalcSleepFreq) == 0L) { if(m_hCalcSleepTimer) { LARGE_INTEGER liDueTime; liDueTime.LowPart = -10000L * nCalcSleepAmt; liDueTime.HighPart = -1L; if(::SetWaitableTimer(m_hCalcSleepTimer, &liDueTime, 0L, NULL, NULL, FALSE)) { MSG msg; while(WAIT_OBJECT_0 != ::MsgWaitForMultipleObjects(1, &m_hCalcSleepTimer, FALSE, INFINITE, QS_ALLEVENTS)) { while(::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::Sleep(0L); } } else ::Sleep(nCalcSleepAmt); } else ::Sleep(nCalcSleepAmt); m_nSleepStep = 0L; } m_nSleepStep++; } } /////////////////////////////////////////////////////////////////////////////////// //////////////////// STDMETHODIMP CMmIhIndexAtom::CalcAllOptions(EtsCalcModelTypeEnum enCalcModel, VARIANT_BOOL bUseTheoVolatility, VARIANT_BOOL bUseTheoVolaNoBid, VARIANT_BOOL bUseTheoVolaBadMarket, DOUBLE dUndPriceTolerance, enum EtsPriceRoundingRuleEnum enPriceRoundingRule, LONG nCalcSleepFreq, LONG nCalcSleepAmt, ICalculationParametrs* pParams) { try { IUnknownPtr spUnk; _variant_t varItem; ULONG nFetched = 0L; HRESULT hr; EtsReplacePriceStatusEnum enMidPriceStatus = enRpsNone; DOUBLE dSpotPriceMid = m_spUndPriceProfile->GetUndPriceMid(m_dPriceBid, m_dPriceAsk, m_dPriceLast, dUndPriceTolerance, enPriceRoundingRule, &enMidPriceStatus, FALSE); IMmIhOptAtomPtr spOption; _CHK(m_spOpt->get__NewEnum(&spUnk), _T("Fail to get options collection.")); IEnumVARIANTPtr spOptionEnum(spUnk); _CHK(spOptionEnum->Reset(), _T("Fail to reset options collection.")); while((hr = spOptionEnum->Next(1L, &varItem, &nFetched)) == S_OK) { ATLASSERT(varItem.vt == VT_DISPATCH); spOption = varItem; if(nFetched > 0 && spOption != NULL) { _CHK(CalcOptionGreeks(spOption, dSpotPriceMid, enCalcModel, bUseTheoVolatility, bUseTheoVolaNoBid, bUseTheoVolaBadMarket, dUndPriceTolerance, enPriceRoundingRule, pParams), _T("Fail to calculate option greeks.")); _CalcSleep(nCalcSleepFreq, nCalcSleepAmt); } } } catch(const _com_error& e) { return Error((PTCHAR)CComErrorWrapper::ErrorDescription(e), IID_IMmIhIndexAtom, e.Error()); } return S_OK; }
[ "chuchev@egartech.com" ]
chuchev@egartech.com
8cbbffbc2c81e59d934ad47cea2fb4f88822a6de
8585a8ffff1d0c66bc278ede6ca49e6d1a6b9b1c
/src/lightcouch/changeset.h
698c3843c007bd24f525a96a8512fcad646aa2c3
[ "MIT" ]
permissive
ondra-novak/lightcouch
24196ac5eddbc298388938b3035c83df93e619c3
c11ff4fcb25159f2a5a4809b57cf5c2094a6aa2e
refs/heads/master
2020-04-16T02:25:52.895414
2016-09-25T23:35:05
2016-09-25T23:35:05
57,080,508
0
0
null
null
null
null
UTF-8
C++
false
false
5,186
h
/* * changeSet.h * * Created on: 11. 3. 2016 * Author: ondra */ #ifndef LIBS_LIGHTCOUCH_SRC_LIGHTCOUCH_CHANGESET_H_ #define LIBS_LIGHTCOUCH_SRC_LIGHTCOUCH_CHANGESET_H_ #include <lightspeed/base/containers/constStr.h> #include <lightspeed/base/exceptions/exception.h> #include <lightspeed/utils/json/json.h> #include "couchDB.h" namespace LightCouch { class LocalView; using namespace LightSpeed; ///Collects changes and commits them as one request class Changeset { public: Changeset(CouchDB &db); Changeset(const Changeset& other); ///Updates document in database /** Function schedules document for update. Once document is scheduled, Document instance can * be destroyed, because document is kept inside of changeset. Changes are applied by function commit() * * @param document document to schedule for update * @return reference to this * * @note If document has no _id, it is created automatically by this function,so you can * Immediately read it. * */ Changeset &update(Document &document); ///Erases document defined only by documentId and revisionId. Useful to erase conflicts /** * @param docId document id as JSON-string. you can use doc["_id"] directly without parsing and composing * @param revId revision id as JSON-string. you can use dic["_rev"] directly without parsing and composing * * @return reference to Changeset to allow create chains * * @note erasing document without its content causes, that minimal tombstone will be created, however * any filters that triggers on content will not triggered. This is best for erasing conflicts because they are * no longer valid. */ Changeset &erase(ConstValue docId, ConstValue revId); ///Commits all changes in the database /** * @param db database where data will be committed * @param all_or_nothing ensures that whole batch of changes will be updated at * once. If some change is rejected, nothing written to the database. In this * mode, conflict are not checked, so you can easy created conflicted state similar * to conflict during replication. If you set this variable to false, function * writes documents one-by-one and also rejects conflicts * * @return reference to the Changeset to create chains */ Changeset &commit(CouchDB &db, bool all_or_nothing=true); ///Commits all changes in the database /** * @param all_or_nothing ensures that whole batch of changes will be updated at * once. If some change is rejected, nothing written to the database. In this * mode, conflict are not checked, so you can easy created conflicted state similar * to conflict during replication. If you set this variable to false, function * writes documents one-by-one and also rejects conflicts * * @note change will be committed to the database connection which was used for creation of this * changeset * * @return reference to the Changeset to create chains */ Changeset &commit(bool all_or_nothing=true); ///Preview all changes in a local view /** Function just only sends all changes to a local view, without making the * set "committed". You can use this function to preview all changes in the view * before it is committed to the database * @param view local view * * @return reference to the Changeset to create chains * * @note it is recomended to define map function to better preview, because the function * preview() will use updateDoc() */ Changeset &preview(LocalView &view); ///Mark current state of changeset /** you can use stored mark to revert unsaved changes later */ natural mark() const; ///Revert changes up to mark /** Function removes all document stored beyond that mark * * @param mark mark stored by mark() * * @note function only removes documents from the change-set. It cannot * revert changes made in the documents */ void revert(natural mark); ///Revert single document /** * @param doc document to remove. It must be exact reference to the document * * @note function only removes document from the change-set. It cannot * revert changes made in the document. * * @note function can be slow for large changesets because it searches document using * sequential scan. If you want to revert recent changes, use mark-revert * couple to achieve this. */ void revert(Value doc); ///Creates new document /** Function creates empty object and puts _id in it * * @return newly created document. It is already in edit mode, so you can set new atributes */ Document newDocument(); ///Creates new document /** Function creates empty object and puts _id in it * * @param suffix suffix append to the ID * @return newly created document. It is already in edit mode, so you can set new atributes */ Document newDocument(ConstStrA suffix); CouchDB &getDatabase() {return db;} const CouchDB &getDatabase() const {return db;} const JSON::Builder json; protected: JSON::Value docs; JSON::Container wholeRequest; CouchDB &db; void init(); void eraseConflicts(ConstValue docId, ConstValue conflictList); }; } /* namespace assetex */ #endif /* LIBS_LIGHTCOUCH_SRC_LIGHTCOUCH_CHANGESET_H_ */
[ "ondra-novak@email.cz" ]
ondra-novak@email.cz
3c1cead3cb5df72d54509d280bf51c9a5ee5c156
4c489086c4b87f9f044b3a6142f245750fdda85a
/examples/MarchingSquares/src/MeterGridUnit.cpp
e0010930dd10fc4f492bace270999422ce516203
[ "MIT" ]
permissive
davidbeermann/timely-matter
f3537ccd2bf3b1c98e3e8cff98578c7f28a04cbc
fca86fb5b48766c5371677a90ac5149c1b071149
refs/heads/master
2020-05-21T19:21:37.047953
2017-07-09T19:27:40
2017-07-09T19:27:40
64,660,541
3
0
null
null
null
null
UTF-8
C++
false
false
1,656
cpp
#include "MeterGridUnit.h" MeterGridUnit::MeterGridUnit( const unsigned long index, const MeterGridPoint &topLeft, const MeterGridPoint &topRight, const MeterGridPoint &bottomRight, const MeterGridPoint &bottomLeft ) : mIndex((int) index), mTopLeft(topLeft), mTopRight(topRight), mBottomRight(bottomRight), mBottomLeft(bottomLeft) { mCenter = ofVec2f( topLeft.x() + (topRight.x() - topLeft.x()) * 0.5f, topLeft.y() + (bottomLeft.y() - topLeft.y()) * 0.5f ); }; void MeterGridUnit::marchingSquareUpdate(const int weight, const float forceX, const float forceY) { mWeight = weight; mForce.x = forceX; mForce.y = forceY; }; const MeterGridPoint &MeterGridUnit::getTopLeft() const { return mTopLeft; }; const MeterGridPoint &MeterGridUnit::getTopRight() const { return mTopRight; }; const MeterGridPoint &MeterGridUnit::getBottomRight() const { return mBottomRight; }; const MeterGridPoint &MeterGridUnit::getBottomLeft() const { return mBottomLeft; }; // http://stackoverflow.com/questions/21492291/strange-member-function-not-viable-error-in-templated-linear-algebra-vector-cl#21492333 const int &MeterGridUnit::getIndex() const { return mIndex; } const ofVec2f *MeterGridUnit::getCenter() const { return &mCenter; }; const int MeterGridUnit::getWeight() const { return mWeight; } const ofVec2f MeterGridUnit::getForce() const { return mForce; } const int MeterGridUnit::getWidth() const { return mTopRight.x() - mTopLeft.x(); } const int MeterGridUnit::getHeight() const { return mBottomLeft.y() - mTopLeft.y(); }
[ "mail@davidbeermann.com" ]
mail@davidbeermann.com
2e565d3eb0a304c750e014bd6fba61a74852b0a5
ed22687f73b95c31beea9eb58b641c5cad7d72d4
/asgn2/PA3/src/model_obj.h
2e023a262008f580a7509451a10b05b1f0316874
[]
no_license
GYingchao/advancedCG
383608423f8fd7c6241f0103ebc72e48e739a19b
db770cb2db85557b18421803cb15fbdcdaed87ec
refs/heads/master
2021-01-18T23:39:23.997781
2013-12-02T08:23:53
2013-12-02T08:23:53
13,346,443
0
0
null
null
null
null
UTF-8
C++
false
false
6,894
h
// Copyright info of this file is left out for the assignment. #if !defined(MODEL_OBJ_H) #define MODEL_OBJ_H #include <cstdio> #include <map> #include <string> #include <vector> //----------------------------------------------------------------------------- // Alias|Wavefront OBJ file loader. // // This OBJ file loader contains the following restrictions: // 1. Group information is ignored. Faces are grouped based on the material // that each face uses. // 2. Object information is ignored. This loader will merge everything into a // single object. // 3. The MTL file must be located in the same directory as the OBJ file. If // it isn't then the MTL file will fail to load and a default material is // used instead. // 4. This loader triangulates all polygonal faces during importing. //----------------------------------------------------------------------------- class ModelOBJ { public: struct Material { float ambient[4]; float diffuse[4]; float specular[4]; float shininess; // [0 = min shininess, 1 = max shininess] float alpha; // [0 = fully transparent, 1 = fully opaque] std::string name; std::string colorMapFilename; std::string bumpMapFilename; }; struct Vertex { float position[3]; float texCoord[2]; float normal[3]; float tangent[4]; float bitangent[3]; }; struct Mesh { int startIndex; int triangleCount; const Material *pMaterial; }; struct Edge { int startIndex; // the smaller one int endIndex; // the larger one bool operator<(const Edge& rhs) const; }; ModelOBJ(); ~ModelOBJ(); void destroy(); bool import(const char *pszFilename, bool rebuildNormals = false); void normalize(float scaleTo = 1.0f, bool center = true); void reverseWinding(); // Getter methods. void getCenter(float &x, float &y, float &z) const; float getWidth() const; float getHeight() const; float getLength() const; float getRadius() const; const int *getIndexBuffer() const; const int *getIndexBufferAdj() const; int getIndexSize() const; const Material &getMaterial(int i) const; const Mesh &getMesh(int i) const; int getNumberOfIndices() const; int getNumberOfMaterials() const; int getNumberOfMeshes() const; int getNumberOfTriangles() const; int getNumberOfVertices() const; const std::string &getPath() const; const Vertex &getVertex(int i) const; const Vertex *getVertexBuffer() const; int getVertexSize() const; bool hasNormals() const; bool hasPositions() const; bool hasTangents() const; bool hasTextureCoords() const; private: void addTriangleWithAdj(int index, int v0, int v1, int v2); void addTrianglePos(int index, int material, int v0, int v1, int v2); void addTrianglePosNormal(int index, int material, int v0, int v1, int v2, int vn0, int vn1, int vn2); void addTrianglePosTexCoord(int index, int material, int v0, int v1, int v2, int vt0, int vt1, int vt2); void addTrianglePosTexCoordNormal(int index, int material, int v0, int v1, int v2, int vt0, int vt1, int vt2, int vn0, int vn1, int vn2); int addVertex(int hash, const Vertex *pVertex); void bounds(float center[3], float &width, float &height, float &length, float &radius) const; void buildMeshes(); void generateNormals(); void generateTangents(); void importGeometryFirstPass(FILE *pFile); void importGeometrySecondPass(FILE *pFile); bool importMaterials(const char *pszFilename); void scale(float scaleFactor, float offset[3]); void matchAdjVertex(int vert1Ind, int vert2Ind, int vert3IndBuf, int vert3OppPos); bool m_hasPositions; bool m_hasTextureCoords; bool m_hasNormals; bool m_hasTangents; int m_numberOfVertexCoords; int m_numberOfTextureCoords; int m_numberOfNormals; int m_numberOfTriangles; int m_numberOfMaterials; int m_numberOfMeshes; float m_center[3]; float m_width; float m_height; float m_length; float m_radius; std::string m_directoryPath; std::vector<Mesh> m_meshes; std::vector<Material> m_materials; std::vector<Vertex> m_vertexBuffer; std::vector<int> m_indexBuffer; std::vector<int> m_indexBufferAdj; std::vector<int> m_attributeBuffer; std::vector<float> m_vertexCoords; std::vector<float> m_textureCoords; std::vector<float> m_normals; std::map<std::string, int> m_materialCache; std::map<int, std::vector<int> > m_vertexCache; std::map<Edge, int> m_edgeAdjCache; }; //----------------------------------------------------------------------------- inline void ModelOBJ::getCenter(float &x, float &y, float &z) const { x = m_center[0]; y = m_center[1]; z = m_center[2]; } inline float ModelOBJ::getWidth() const { return m_width; } inline float ModelOBJ::getHeight() const { return m_height; } inline float ModelOBJ::getLength() const { return m_length; } inline float ModelOBJ::getRadius() const { return m_radius; } inline const int *ModelOBJ::getIndexBuffer() const { return &m_indexBuffer[0]; } inline const int *ModelOBJ::getIndexBufferAdj() const { return &m_indexBufferAdj[0]; } inline int ModelOBJ::getIndexSize() const { return static_cast<int>(sizeof(int)); } inline const ModelOBJ::Material &ModelOBJ::getMaterial(int i) const { return m_materials[i]; } inline const ModelOBJ::Mesh &ModelOBJ::getMesh(int i) const { return m_meshes[i]; } inline int ModelOBJ::getNumberOfIndices() const { return m_numberOfTriangles * 3; } inline int ModelOBJ::getNumberOfMaterials() const { return m_numberOfMaterials; } inline int ModelOBJ::getNumberOfMeshes() const { return m_numberOfMeshes; } inline int ModelOBJ::getNumberOfTriangles() const { return m_numberOfTriangles; } inline int ModelOBJ::getNumberOfVertices() const { return static_cast<int>(m_vertexBuffer.size()); } inline const std::string &ModelOBJ::getPath() const { return m_directoryPath; } inline const ModelOBJ::Vertex &ModelOBJ::getVertex(int i) const { return m_vertexBuffer[i]; } inline const ModelOBJ::Vertex *ModelOBJ::getVertexBuffer() const { return &m_vertexBuffer[0]; } inline int ModelOBJ::getVertexSize() const { return static_cast<int>(sizeof(Vertex)); } inline bool ModelOBJ::hasNormals() const { return m_hasNormals; } inline bool ModelOBJ::hasPositions() const { return m_hasPositions; } inline bool ModelOBJ::hasTangents() const { return m_hasTangents; } inline bool ModelOBJ::hasTextureCoords() const { return m_hasTextureCoords; } inline bool ModelOBJ::Edge::operator<(const Edge& rhs) const { return (startIndex == rhs.startIndex) ? endIndex < rhs.endIndex : startIndex < rhs.startIndex; } #endif
[ "cyc123bzd@gmail.com" ]
cyc123bzd@gmail.com
07f4519f2087fdd830d923d6b1dca01ac66bde29
084f5b9aa75c6e5df4592b50bfbb8e566c2207b7
/ProjectVillage - C++, SFML/ProjectVillage/random events/events/DesertionEvent.h
b3d50ab2e8e860cdc187eda52a40bfd824941629
[]
no_license
bwaszkiewicz/MyProjects
bb8d5d101f4f140f00bed373aee26a6869b85872
f1ddfc46eafd84dc4f40907efd686cb982ddf607
refs/heads/master
2020-04-30T17:09:44.601572
2019-03-21T15:31:09
2019-03-21T15:31:09
176,970,838
0
0
null
null
null
null
UTF-8
C++
false
false
334
h
#pragma once #include "../RandomEvent.h" class DesertionEvent : public RandomEvent { int _chance[MAX_TIER_EVENT]; public: void init(short int tier) override; int getChance(short int tier) const override; std::vector<int> getEvent(short int tier) const override; short int getEventID() const; std::string getCaption() const; };
[ "be.waszkiewicz@gmail.com" ]
be.waszkiewicz@gmail.com
5b6ecf355afcf8b7c22c74f2b7f886d2077b043a
634132d9ae2fd3a081d583e203217ca60a9f7d23
/render_pdf/src/pdfium_aux.h
fabe908a2ee89bbdee7c4a16f14656fff729d733
[ "BSD-3-Clause" ]
permissive
jwezorek/vs_pdfium
6491c8c189a35e3bc5fcace405739d0f8a336954
830cc8850f2538a7e9659447d1b8ac914669fc4e
refs/heads/master
2022-10-12T13:44:26.709456
2022-09-20T22:49:01
2022-09-20T22:49:01
185,276,695
37
14
BSD-3-Clause
2019-09-11T21:37:24
2019-05-06T21:49:21
C++
UTF-8
C++
false
false
446
h
#pragma once #include <string> #include <optional> #include "render_pdf_options.h" #include "public/fpdfview.h" #include "public/cpp/fpdf_scopers.h" void InitPdfium(const RenderPdfOptions& options); std::string GetImageFilename(const RenderPdfOptions& options, std::optional<int> page_number); ScopedFPDFBitmap RenderPage(FPDF_PAGE page, float scale); void WriteImage(FPDF_BITMAP bitmap, ImageFormat format, const std::string& output_filename);
[ "jwezorek@bluebeam.com" ]
jwezorek@bluebeam.com
f8f70c3e00131c792ae3c7f763ae87559f7b8e9a
9765707f705f66333c95491abba4031d89a97335
/reference/dbtool.cpp
8b839b86f9d637c09710d19a393bb7973b65b6ea
[]
no_license
Laucksy/CS-205-Lab-Repo
e58bade6afe78ccb88558c6e18907bf96b3821f3
b95d831d68a4f96928a850c9ee83fa835be08010
refs/heads/master
2021-01-19T16:41:24.952965
2017-03-18T03:56:10
2017-03-18T03:56:10
88,278,993
0
0
null
null
null
null
UTF-8
C++
false
false
2,838
cpp
/********************************************************************* Copyright (C) 2015 Jeffrey O. Pfaffmann 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 "dbtool.h" DBTool::DBTool() { std::cerr << "Name must be provided to DBTool Class " << "during creation.\n"; exit(-1); } DBTool::DBTool(std::string name) { //std::cerr << "constructing object 1\n"; db_name = name; db_location = "."; open_db(); } DBTool::DBTool(const char* name) { //std::cerr << "constructing object 2\n"; db_name = name; db_location = "."; open_db(); } DBTool::DBTool(const char* location, const char* name) { //std::cerr << "constructing object 3\n"; db_name = name; db_location = location; open_db(); } DBTool::DBTool(std::string location, std::string name) { //std::cerr << "constructing object 4\n"; db_name = name; db_location = location; open_db(); } DBTool::DBTool(DBTool &obj) { db_name = obj.db_name; db_location = obj.db_location; open_db(); } void DBTool::operator=(DBTool &obj) { db_name = obj.db_name; db_location = obj.db_location; open_db(); } DBTool::~DBTool() { //std::cerr << "closing object\n"; sqlite3_close(curr_db); curr_db = NULL; } /** Method that will open the provided database. */ int DBTool::open_db() { int retCode = 0; std::string full_name = db_location + "/" + db_name; // open the database -------------------- retCode = sqlite3_open(full_name.c_str(), &curr_db ); if( retCode ){ std::cerr << "Database does not open -- " << sqlite3_errmsg(curr_db) << std::endl; std::cerr << " File -- " << full_name << std::endl; exit(0); }else{ //std::cerr << "Opened database successfully\n"; } return retCode; } void DBTool::print(std::ostream &sout) { sout << "DB Name : " << db_name << std::endl; sout << "DB Loc : " << db_location << std::endl; sout << "Status : " << ( db_open() ? "open" : "closed" ) << std::endl; }
[ "lauckse@lafayette.edu" ]
lauckse@lafayette.edu
482c2ce21bcc211527d7885888f04fd195d453ee
19b10d2c280257de9425bf750d56d99b7b3bfb06
/Roy_Justin/Task2/Virtual functions example - Football VS project/Football/defense.cpp
8f16a61b1b2bb440191c3c1c40864face8f932f5
[]
no_license
RoyJustinWayne/OldCourseWork
dcc138de8e9de06a5e24e57fc0e23125d2e96e6a
8741c447ab37c2940e544ca1ae4078f1e264d3ed
refs/heads/master
2020-04-17T06:20:55.642803
2019-01-18T01:14:03
2019-01-18T01:14:03
166,321,312
0
0
null
null
null
null
UTF-8
C++
false
false
732
cpp
/* * Implementation for the defense class, this should include tackles made, * minutes played and printing starts. * * Will use Name from the base class. * * Justin Roy CSC 4111 Task 2 */ #include "defense.h" //Had to make changes to my naming convention (I wouldn't use lowercase name for file and uppercase for class, but main.CPP chose upper). Defense::Defense(string name) : Player(name) { //base class. } void Defense::setMinutesPlayed(int minutes) { //set Minutes. this->minutes = minutes; } void Defense::setTackles(int tackles) { //set Tackles. this->tackles = tackles; } void Defense::printStats() const { //Print Player::printStats(); cout << "\tMinutes: " << minutes << "\tTackles: " << tackles << endl; }
[ "ex8465@wayne.edu" ]
ex8465@wayne.edu
dc9edc9aff6c023e9c3a50099811dff12bf823fd
03675a095dcd16f61841383a299e049d90ee232c
/day04/ex03/ex01/main.cpp
8cfd48ee7aa0d51b95fa8dc489d21e30701db523
[]
no_license
braimbau/CPP
8f4f9c3e114db06b7070967480d2712e33974fc9
2ff08d24abc5214a15889e93b3ab7d36f655a872
refs/heads/master
2023-03-27T06:13:31.265464
2021-03-30T08:30:30
2021-03-30T08:30:30
335,687,173
0
0
null
null
null
null
UTF-8
C++
false
false
1,469
cpp
#include "PlasmaRifle.hpp" #include "PowerFist.hpp" #include "SuperMutant.hpp" #include "Character.hpp" #include "RadScorpion.hpp" int main() { SuperMutant *sm = new SuperMutant(); RadScorpion *rs = new RadScorpion(); Character *me = new Character("Me"); PlasmaRifle pr; PowerFist pf; std::cout << *me << std::endl; me->attack(sm); std::cout << "==========================" << std::endl; me->equip(&pf); std::cout << *me << std::endl; me->attack(sm); std::cout << "==========================" << std::endl; me->equip(&pr); std::cout << *me << std::endl; me->attack(sm); std::cout << "==========================" << std::endl; std::cout << *me << std::endl; me->recoverAP(); std::cout << *me << std::endl; std::cout << "==========================" << std::endl; me->attack(sm); me->attack(sm); me->attack(sm); me->attack(sm); me->attack(sm); me->attack(sm); std::cout << "==========================" << std::endl; me->attack(rs); me->attack(rs); std::cout << "==========================" << std::endl; me->recoverAP(); me->recoverAP(); me->recoverAP(); me->recoverAP(); me->recoverAP(); std::cout << *me << std::endl; std::cout << "==========================" << std::endl; me->attack(rs); me->attack(rs); me->attack(rs); me->attack(rs); me->attack(rs); me->attack(rs); me->attack(rs); me->attack(rs); std::cout << "==========================" << std::endl; std::cout << *me << std::endl; delete me; }
[ "braimbau@student.42.fr" ]
braimbau@student.42.fr
722e1747a5196e801a9fafad1b124d77318362a3
f88a9a487bae6be6db5ab3bcf13bb391da0e003d
/BattleOfBalls/Classes/Scene/MenuScene/GetLollyLayer.cpp
881ca1f55a52aaf8b8b623de9b25cb769d89a06d
[]
no_license
wangjinghui123/snowflake
49b6f390db53bfa765fb5f9fceb35e5036a698a4
3add1fc0560164191f9c293fbac023566c8b5c46
refs/heads/master
2020-03-17T17:15:03.193232
2018-05-28T10:04:00
2018-05-28T10:04:00
133,780,828
0
0
null
null
null
null
UTF-8
C++
false
false
4,433
cpp
#include "GetLollyLayer.h" #include "Tools/MaskLayer/MaskLayer.h" enum GetLollyTag { TAG_LOLLY, TAG_WEIXIN }; enum GetLollyZOrder { GETLOLLY_MASKLAYER_Z, GETLOLLY_BACKGROUND_Z, GETLOLLY_MENU_Z, GETLOLLY_LAYER_Z }; GetLollyLayer::GetLollyLayer() { } GetLollyLayer::~GetLollyLayer() { } bool GetLollyLayer::init() { if (!Layer::init()) { return false; } auto maskLayer = MaskLayer::create(); this->addChild(maskLayer, GETLOLLY_MASKLAYER_Z); _getLollyItem1 = MenuItemImage::create( "menuScene/getLollyLayer/getLolly_lolly_btn0.png", "menuScene/getLollyLayer/getLolly_lolly_btn0.png", CC_CALLBACK_1(GetLollyLayer::menuGetLollyCallback, this)); _getLollyItem1->setPosition(125,390); _getLollyItem1->setVisible(false); _getLollyItem2 = MenuItemImage::create( "menuScene/getLollyLayer/getLolly_lolly_btn1.png", "menuScene/getLollyLayer/getLolly_lolly_btn1.png", CC_CALLBACK_1(GetLollyLayer::menuGetLollyCallback, this)); _getLollyItem2->setPosition(125,390); _weiXinItem1 = MenuItemImage::create( "menuScene/getLollyLayer/getLolly_weixin_btn0.png", "menuScene/getLollyLayer/getLolly_weixin_btn0.png", CC_CALLBACK_1(GetLollyLayer::menuWeiXinCallback, this)); _weiXinItem1->setPosition(295,390); _weiXinItem2 = MenuItemImage::create( "menuScene/getLollyLayer/getLolly_weixin_btn1.png", "menuScene/getLollyLayer/getLolly_weixin_btn1.png", CC_CALLBACK_1(GetLollyLayer::menuWeiXinCallback, this)); _weiXinItem2->setPosition(295,390); _weiXinItem2->setVisible(false); auto closeItem = MenuItemImage::create( "menuScene/getLollyLayer/close.png", "menuScene/getLollyLayer/close.png", CC_CALLBACK_1(GetLollyLayer::menuCloseCallback, this)); closeItem->setPosition(719,389); auto menu = Menu::create(_getLollyItem1, _getLollyItem2, _weiXinItem1, _weiXinItem2, closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu,GETLOLLY_MENU_Z); auto background = Sprite::create("menuScene/getLollyLayer/getLolly_background.png"); background->setPosition(400, 225); this->addChild(background, GETLOLLY_BACKGROUND_Z); createLollyLayer(); return true; } void GetLollyLayer::menuGetLollyCallback(Ref * pSender) { _getLollyItem1->setVisible(false); _getLollyItem2->setVisible(true); _weiXinItem1->setVisible(true); _weiXinItem2->setVisible(false); auto lollyLayer = this->getChildByTag(TAG_LOLLY); auto weixinLayer = this->getChildByTag(TAG_WEIXIN); if (lollyLayer != NULL) { return; } if (weixinLayer != NULL) { this->removeChild(weixinLayer); } createLollyLayer(); } void GetLollyLayer::menuWeiXinCallback(Ref * pSender) { _getLollyItem1->setVisible(true); _getLollyItem2->setVisible(false); _weiXinItem1->setVisible(false); _weiXinItem2->setVisible(true); auto lollyLayer = this->getChildByTag(TAG_LOLLY); auto weixinLayer = this->getChildByTag(TAG_WEIXIN); if (lollyLayer != NULL) { this->removeChild(lollyLayer); } if (weixinLayer != NULL) { return; } createWeiXinLayer(); } void GetLollyLayer::menuMiaoLingCallback(Ref * pSender) { } void GetLollyLayer::menuSaveCallback(Ref * pSender) { } void GetLollyLayer::menuCopyCallback(Ref * pSender) { } void GetLollyLayer::menuLingQuCallback(Ref * pSender) { } void GetLollyLayer::menuCloseCallback(Ref * pSender) { this->removeFromParentAndCleanup(true); } void GetLollyLayer::createLollyLayer() { auto miaolingItem = MenuItemImage::create( "menuScene/getLollyLayer/getLolly_miaoling_btn0.png", "menuScene/getLollyLayer/getLolly_miaoling_btn1.png", CC_CALLBACK_1(GetLollyLayer::menuMiaoLingCallback, this)); miaolingItem->setPosition(333,110); auto copyItem = MenuItemImage::create( "menuScene/getLollyLayer/getLolly_lianjie_btn0.png", "menuScene/getLollyLayer/getLolly_lianjie_btn1.png", CC_CALLBACK_1(GetLollyLayer::menuCopyCallback, this)); copyItem->setPosition(591,113); auto saveItem = MenuItemImage::create( "menuScene/getLollyLayer/getLolly_save_btn0.png", "menuScene/getLollyLayer/getLolly_save_btn1.png", CC_CALLBACK_1(GetLollyLayer::menuSaveCallback, this)); saveItem->setPosition(591,67); auto menu = Menu::create(miaolingItem, copyItem, saveItem, NULL); menu->setPosition(Vec2::ZERO); auto layer = Layer::create(); layer->addChild(menu); this->addChild(layer, GETLOLLY_LAYER_Z,TAG_LOLLY); } void GetLollyLayer::createWeiXinLayer() { auto layer = Layer::create(); this->addChild(layer, GETLOLLY_LAYER_Z, TAG_WEIXIN); }
[ "321022311@qq.com" ]
321022311@qq.com
88d3b328aab6ff92ff28624b7eb7f73cd684748c
b19a03a27172029c25d2db3d246e790b3061faa4
/src/models/block.h
7aef9afaef1f01a1e0736d7bccbd2f6bb112dbc9
[ "MIT" ]
permissive
sharkprince/tank-game
b9be1ebb8cb41cbe085e540819967c9632d917a9
059f957e6993b72037dee86a9f792d7d94516c14
refs/heads/master
2023-05-04T08:59:09.394684
2021-05-27T16:34:16
2021-05-27T16:34:16
369,858,828
0
0
null
null
null
null
UTF-8
C++
false
false
693
h
#ifndef TANK_GAME_BLOCK_H #define TANK_GAME_BLOCK_H #include <SFML/Graphics/Sprite.hpp> #include <SFML/Graphics/Texture.hpp> #include "../core/game.h" class Block { public: Block(sf::Texture *texture, sf::Vector2f position, bool isBreakable, bool isSoft, bool isDeep); void Update(Game *g); bool Hit(float rotation); bool GetIsSoft(); bool GetIsDeep(); sf::Sprite *Sprite; constexpr static float BLOCK_WIDTH_PIXELS = 24.f; constexpr static float BLOCK_HEIGHT_PIXELS = 24.f; constexpr static float FLOAT_BLOCK_HIT_DAMAGE = 6.f; private: bool isBreakable; bool isSoft; bool isDeep; sf::Texture texture; }; #endif //TANK_GAME_BLOCK_H
[ "berkovets.polly@gmail.com" ]
berkovets.polly@gmail.com
42e02de5c1617c13851d295fecc1f96dc66b3ea4
c6fa53212eb03017f9e72fad36dbf705b27cc797
/Utilities/StaticAnalyzers/src/ClassChecker.cpp
b64f7eaca24f25886234717ba4a70f4c68c0a2c7
[]
no_license
gem-sw/cmssw
a31fc4ef2233b2157e1e7cbe9a0d9e6c2795b608
5893ef29c12b2718b3c1385e821170f91afb5446
refs/heads/CMSSW_6_2_X_SLHC
2022-04-29T04:43:51.786496
2015-12-16T16:09:31
2015-12-16T16:09:31
12,892,177
2
4
null
2018-11-22T13:40:31
2013-09-17T10:10:26
C++
UTF-8
C++
false
false
26,483
cpp
// ClassChecker.cpp by Patrick Gartung (gartung@fnal.gov) // // Objectives of this checker // // For each special function of a class (produce, beginrun, endrun, beginlumi, endlumi) // // 1) identify member data being modified // built-in types reseting values // calling non-const member function object if member data is an object // 2) for each non-const member functions of self called // do 1) above // 3) for each non member function (external) passed in a member object // complain if arguement passed in by non-const ref // pass by value OK // pass by const ref & pointer OK // // #include "ClassChecker.h" using namespace clang; using namespace clang::ento; using namespace llvm; namespace clangcms { class WalkAST : public clang::StmtVisitor<WalkAST> { clang::ento::BugReporter &BR; clang::AnalysisDeclContext *AC; typedef const clang::CXXMemberCallExpr * WorkListUnit; typedef clang::SmallVector<WorkListUnit, 50> DFSWorkList; /// A vector representing the worklist which has a chain of CallExprs. DFSWorkList WList; // PreVisited : A CallExpr to this FunctionDecl is in the worklist, but the // body has not been visited yet. // PostVisited : A CallExpr to this FunctionDecl is in the worklist, and the // body has been visited. enum Kind { NotVisited, Visiting, /**< A CallExpr to this FunctionDecl is in the worklist, but the body has not yet been visited. */ Visited /**< A CallExpr to this FunctionDecl is in the worklist, and the body has been visited. */ }; /// A DenseMap that records visited states of FunctionDecls. llvm::DenseMap<const clang::CXXMemberCallExpr *, Kind> VisitedFunctions; /// The CallExpr whose body is currently being visited. This is used for /// generating bug reports. This is null while visiting the body of a /// constructor or destructor. const clang::CXXMemberCallExpr *visitingCallExpr; public: WalkAST(clang::ento::BugReporter &br, clang::AnalysisDeclContext *ac) : BR(br), AC(ac), visitingCallExpr(0) {} bool hasWork() const { return !WList.empty(); } /// This method adds a CallExpr to the worklist void Enqueue(WorkListUnit WLUnit) { Kind &K = VisitedFunctions[WLUnit]; if (K = Visiting) { // llvm::errs()<<"\nRecursive call to "; // WLUnit->getDirectCallee()->printName(llvm::errs()); // llvm::errs()<<" , "; // WLUnit->dumpPretty(AC->getASTContext()); // llvm::errs()<<"\n"; return; } K = Visiting; WList.push_back(WLUnit); } /// This method returns an item from the worklist without removing it. WorkListUnit Dequeue() { assert(!WList.empty()); return WList.back(); } void Execute() { if (WList.empty()) return; WorkListUnit WLUnit = Dequeue(); // if (visitingCallExpr && WLUnit->getMethodDecl() == visitingCallExpr->getMethodDecl()) { // llvm::errs()<<"\nRecursive call to "; // WLUnit->getDirectCallee()->printName(llvm::errs()); // llvm::errs()<<" , "; // WLUnit->dumpPretty(AC->getASTContext()); // llvm::errs()<<"\n"; // WList.pop_back(); // return; // } const clang::CXXMethodDecl *FD = WLUnit->getMethodDecl(); if (!FD) return; llvm::SaveAndRestore<const clang::CXXMemberCallExpr *> SaveCall(visitingCallExpr, WLUnit); if (FD && FD->hasBody()) Visit(FD->getBody()); VisitedFunctions[WLUnit] = Visited; WList.pop_back(); } const clang::Stmt * ParentStmt(const Stmt *S) { const Stmt * P = AC->getParentMap().getParentIgnoreParens(S); if (!P) return 0; return P; } void WListDump(llvm::raw_ostream & os) { clang::LangOptions LangOpts; LangOpts.CPlusPlus = true; clang::PrintingPolicy Policy(LangOpts); if (!WList.empty()) { for (llvm::SmallVectorImpl<const clang::CXXMemberCallExpr *>::iterator I = WList.begin(), E = WList.end(); I != E; I++) { (*I)->printPretty(os, 0 , Policy); os <<" "; } } } // Stmt visitor methods. void VisitChildren(clang::Stmt *S); void VisitStmt( clang::Stmt *S) { VisitChildren(S); } void VisitMemberExpr(clang::MemberExpr *E); void VisitCXXMemberCallExpr( clang::CXXMemberCallExpr *CE); void VisitDeclRefExpr(clang::DeclRefExpr * DRE); void ReportDeclRef( const clang::DeclRefExpr * DRE); void CheckCXXOperatorCallExpr(const clang::CXXOperatorCallExpr *CE,const clang::Expr *E); void CheckBinaryOperator(const clang::BinaryOperator * BO,const clang::Expr *E); void CheckUnaryOperator(const clang::UnaryOperator * UO,const clang::Expr *E); void CheckExplicitCastExpr(const clang::ExplicitCastExpr * CE,const clang::Expr *E); void CheckReturnStmt(const clang::ReturnStmt * RS, const clang::Expr *E); void ReportCast(const clang::ExplicitCastExpr *CE,const clang::Expr *E); void ReportCall(const clang::CXXMemberCallExpr *CE); void ReportMember(const clang::MemberExpr *ME); void ReportCallReturn(const clang::ReturnStmt * RS); void ReportCallArg(const clang::CXXMemberCallExpr *CE, const int i); }; //===----------------------------------------------------------------------===// // AST walking. //===----------------------------------------------------------------------===// void WalkAST::VisitChildren( clang::Stmt *S) { for (clang::Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I) if (clang::Stmt *child = *I) { Visit(child); } } void WalkAST::CheckBinaryOperator(const clang::BinaryOperator * BO,const clang::Expr *E) { // BO->dump(); // llvm::errs()<<"\n"; if (BO->isAssignmentOp()) { if (clang::DeclRefExpr * DRE =dyn_cast<clang::DeclRefExpr>(BO->getLHS())){ ReportDeclRef(DRE); } else if (clang::MemberExpr * ME = dyn_cast<clang::MemberExpr>(BO->getLHS())){ if (ME->isImplicitAccess()) ReportMember(ME); } } } void WalkAST::CheckUnaryOperator(const clang::UnaryOperator * UO,const clang::Expr *E) { // UO->dump(); // llvm::errs()<<"\n"; if (UO->isIncrementDecrementOp()) { if ( dyn_cast<clang::DeclRefExpr>(E)) if (clang::DeclRefExpr * DRE =dyn_cast<clang::DeclRefExpr>(UO->getSubExpr()->IgnoreParenImpCasts())) { ReportDeclRef(DRE); } else if ( dyn_cast<clang::MemberExpr>(E)) if (clang::MemberExpr * ME = dyn_cast<clang::MemberExpr>(UO->getSubExpr()->IgnoreParenImpCasts())) { ReportMember(ME); } } } void WalkAST::CheckCXXOperatorCallExpr(const clang::CXXOperatorCallExpr *OCE,const clang::Expr *E) { // OCE->dump(); // llvm::errs()<<"\n"; switch ( OCE->getOperator() ) { case OO_Equal: case OO_PlusEqual: case OO_MinusEqual: case OO_StarEqual: case OO_SlashEqual: case OO_PercentEqual: case OO_AmpEqual: case OO_PipeEqual: case OO_LessLessEqual: case OO_GreaterGreaterEqual: if (const clang::DeclRefExpr * DRE =dyn_cast<clang::DeclRefExpr>(OCE->arg_begin()->IgnoreParenImpCasts())) { ReportDeclRef(DRE); } else if (const clang::MemberExpr * ME = dyn_cast<clang::MemberExpr>(OCE->arg_begin()->IgnoreParenImpCasts())){ if (ME->isImplicitAccess()) ReportMember(ME); } case OO_PlusPlus: case OO_MinusMinus: if ( dyn_cast<clang::DeclRefExpr>(E)) if (const clang::DeclRefExpr * DRE =dyn_cast<clang::DeclRefExpr>(OCE->arg_begin()->IgnoreParenCasts())) { ReportDeclRef(DRE); } else if ( dyn_cast<clang::MemberExpr>(E)) if (const clang::MemberExpr * ME = dyn_cast<clang::MemberExpr>(OCE->getCallee()->IgnoreParenCasts())) { if (ME->isImplicitAccess()) ReportMember(ME); } } } void WalkAST::CheckExplicitCastExpr(const clang::ExplicitCastExpr * CE,const clang::Expr *expr){ // CE->dump(); // llvm::errs()<<"\n"; const clang::Expr *E = CE->getSubExpr(); clang::ASTContext &Ctx = AC->getASTContext(); clang::QualType OrigTy = Ctx.getCanonicalType(E->getType()); clang::QualType ToTy = Ctx.getCanonicalType(CE->getType()); if (const clang::MemberExpr * ME = dyn_cast<clang::MemberExpr>(expr)) { if ( support::isConst( OrigTy ) && ! support::isConst(ToTy) ) ReportCast(CE,ME); } if (const clang::DeclRefExpr * DRE = dyn_cast<clang::DeclRefExpr>(expr)) { if ( support::isConst( OrigTy ) && ! support::isConst(ToTy) ) ReportCast(CE,DRE); } } void WalkAST::CheckReturnStmt(const clang::ReturnStmt * RS, const Expr * E){ // llvm::errs()<<"\nReturn Expression\n"; // RE->dump(); // llvm::errs()<<"\n"; // RQT->dump(); // llvm::errs()<<"\n"; if (const clang::Expr * RE = RS->getRetValue()) { clang::QualType QT = RE->getType(); clang::ASTContext &Ctx = AC->getASTContext(); clang::QualType Ty = Ctx.getCanonicalType(QT); const clang::CXXMethodDecl * MD; if (visitingCallExpr) MD = visitingCallExpr->getMethodDecl(); else MD = llvm::dyn_cast<clang::CXXMethodDecl>(AC->getDecl()); if ( llvm::isa<clang::CXXNewExpr>(RE) ) return; clang::QualType RQT = MD->getResultType(); clang::QualType RTy = Ctx.getCanonicalType(RQT); clang::QualType CQT = MD->getCallResultType(); clang::QualType CTy = Ctx.getCanonicalType(CQT); if ( (RTy->isPointerType() || RTy->isReferenceType() ) ) if( !support::isConst(RTy) ) { if ( const clang::MemberExpr *ME = dyn_cast<clang::MemberExpr>(E)) if (ME->isImplicitAccess()) { ReportCallReturn(RS); return; } } } } void WalkAST::VisitDeclRefExpr( clang::DeclRefExpr * DRE) { if (clang::VarDecl * D = llvm::dyn_cast<clang::VarDecl>(DRE->getDecl()) ) { clang::SourceLocation SL = DRE->getLocStart(); if (BR.getSourceManager().isInSystemHeader(SL) || BR.getSourceManager().isInExternCSystemHeader(SL)) return; Stmt * P = AC->getParentMap().getParent(DRE); while (AC->getParentMap().hasParent(P)) { if (const clang::UnaryOperator * UO = llvm::dyn_cast<clang::UnaryOperator>(P)) { WalkAST::CheckUnaryOperator(UO,DRE);} if (const clang::BinaryOperator * BO = llvm::dyn_cast<clang::BinaryOperator>(P)) { WalkAST::CheckBinaryOperator(BO,DRE);} if (const clang::CXXOperatorCallExpr *OCE = llvm::dyn_cast<clang::CXXOperatorCallExpr>(P)) { WalkAST::CheckCXXOperatorCallExpr(OCE,DRE);} if (const clang::ExplicitCastExpr * CE = llvm::dyn_cast<clang::ExplicitCastExpr>(P)) { WalkAST::CheckExplicitCastExpr(CE,DRE);} if (const clang::CXXNewExpr * NE = llvm::dyn_cast<clang::CXXNewExpr>(P)) break; P = AC->getParentMap().getParent(P); } // llvm::errs()<<"Declaration Ref Expr\t"; // dyn_cast<Stmt>(DRE)->dumpPretty(AC->getASTContext()); // DRE->dump(); // llvm::errs()<<"\n"; } } void WalkAST::ReportDeclRef( const clang::DeclRefExpr * DRE) { if (const clang::VarDecl * D = llvm::dyn_cast<clang::VarDecl>(DRE->getDecl())) { clang::QualType t = D->getType(); const clang::Stmt * PS = ParentStmt(DRE); CmsException m_exception; clang::LangOptions LangOpts; LangOpts.CPlusPlus = true; clang::PrintingPolicy Policy(LangOpts); clang::ento::PathDiagnosticLocation CELoc = clang::ento::PathDiagnosticLocation::createBegin(DRE, BR.getSourceManager(),AC); if (!m_exception.reportClass( CELoc, BR ) ) return; if ( D->isStaticLocal() && ! support::isConst( t ) ) { std::string buf; llvm::raw_string_ostream os(buf); os << "Non-const variable '" << D->getNameAsString() << "' is static local and modified in statement '"; PS->printPretty(os,0,Policy); os << "'.\n"; BugType * BT = new BugType("ClassChecker : non-const static local variable modified","ThreadSafety"); BugReport * R = new BugReport(*BT,os.str(),CELoc); BR.emitReport(R); return; } if ( D->isStaticDataMember() && ! support::isConst( t ) ) { std::string buf; llvm::raw_string_ostream os(buf); os << "Non-const variable '" << D->getNameAsString() << "' is static member data and modified in statement '"; PS->printPretty(os,0,Policy); os << "'.\n"; BugType * BT = new BugType("ClassChecker : non-const static member variable modified","ThreadSafety"); BugReport * R = new BugReport(*BT,os.str(),CELoc); BR.emitReport(R); return; } if ( (D->getStorageClass() == clang::SC_Static) && !D->isStaticDataMember() && !D->isStaticLocal() && !support::isConst( t ) ) { std::string buf; llvm::raw_string_ostream os(buf); os << "Non-const variable '" << D->getNameAsString() << "' is global static and modified in statement '"; PS->printPretty(os,0,Policy); os << "'.\n"; BugType * BT = new BugType("ClassChecker : non-const global static variable modified","ThreadSafety"); BugReport * R = new BugReport(*BT,os.str(),CELoc); BR.emitReport(R); return; } } } void WalkAST::VisitMemberExpr( clang::MemberExpr *ME) { clang::SourceLocation SL = ME->getExprLoc(); if (BR.getSourceManager().isInSystemHeader(SL) || BR.getSourceManager().isInExternCSystemHeader(SL)) return; if (!(ME->isImplicitAccess())) return; Stmt * P = AC->getParentMap().getParent(ME); while (AC->getParentMap().hasParent(P)) { if (const clang::UnaryOperator * UO = llvm::dyn_cast<clang::UnaryOperator>(P)) { WalkAST::CheckUnaryOperator(UO,ME);} if (const clang::BinaryOperator * BO = llvm::dyn_cast<clang::BinaryOperator>(P)) { WalkAST::CheckBinaryOperator(BO,ME);} if (const clang::CXXOperatorCallExpr *OCE = llvm::dyn_cast<clang::CXXOperatorCallExpr>(P)) { WalkAST::CheckCXXOperatorCallExpr(OCE,ME);} if (const clang::ExplicitCastExpr * CE = llvm::dyn_cast<clang::ExplicitCastExpr>(P)) { WalkAST::CheckExplicitCastExpr(CE,ME);} if (const clang::ReturnStmt * RS = llvm::dyn_cast<clang::ReturnStmt>(P)) { WalkAST::CheckReturnStmt(RS,ME); } if (const clang::CXXNewExpr * NE = llvm::dyn_cast<clang::CXXNewExpr>(P)) break; P = AC->getParentMap().getParent(P); } } void WalkAST::VisitCXXMemberCallExpr( clang::CXXMemberCallExpr *CE) { if (BR.getSourceManager().isInSystemHeader(CE->getExprLoc()) || BR.getSourceManager().isInExternCSystemHeader(CE->getExprLoc())) return; clang::CXXMethodDecl * MD = CE->getMethodDecl(); if (! MD) return; Enqueue(CE); Execute(); Visit(CE->getImplicitObjectArgument()); std::string name = MD->getNameAsString(); if (name == "end" || name == "begin" || name == "find") return; if (llvm::isa<clang::MemberExpr>(CE->getImplicitObjectArgument()->IgnoreParenCasts() ) ) if ( !MD->isConst() ) ReportCall(CE); for(int i=0, j=CE->getNumArgs(); i<j; i++) { if (CE->getArg(i)) if ( const clang::Expr *E = llvm::dyn_cast<clang::Expr>(CE->getArg(i))) { clang::QualType qual_arg = E->getType(); if (const clang::MemberExpr *ME=llvm::dyn_cast<clang::MemberExpr>(E)) if (ME->isImplicitAccess()) { // clang::ValueDecl * VD = llvm::dyn_cast<clang::ValueDecl>(ME->getMemberDecl()); // clang::QualType qual_decl = llvm::dyn_cast<clang::ValueDecl>(ME->getMemberDecl())->getType(); clang::ParmVarDecl *PVD=llvm::dyn_cast<clang::ParmVarDecl>(MD->getParamDecl(i)); clang::QualType QT = PVD->getOriginalType(); const clang::Type * T = QT.getTypePtr(); if (!support::isConst(QT)) if (T->isReferenceType()) { ReportCallArg(CE,i); } } } } // llvm::errs()<<"\n--------------------------------------------------------------\n"; // llvm::errs()<<"\n------CXXMemberCallExpression---------------------------------\n"; // llvm::errs()<<"\n--------------------------------------------------------------\n"; // CE->dump(); // llvm::errs()<<"\n--------------------------------------------------------------\n"; // return; } void WalkAST::ReportMember(const clang::MemberExpr *ME) { if ( visitingCallExpr ) { clang::Expr * IOA = visitingCallExpr->getImplicitObjectArgument(); if (!( IOA->isImplicitCXXThis() || llvm::dyn_cast<CXXThisExpr>(IOA->IgnoreParenCasts()))) return; } llvm::SmallString<100> buf; llvm::raw_svector_ostream os(buf); CmsException m_exception; clang::ento::PathDiagnosticLocation CELoc; clang::SourceRange R; clang::LangOptions LangOpts; LangOpts.CPlusPlus = true; clang::PrintingPolicy Policy(LangOpts); CELoc = clang::ento::PathDiagnosticLocation::createBegin(ME, BR.getSourceManager(),AC); R = ME->getSourceRange(); os << " Member data '"; // os << ME->getMemberDecl()->getQualifiedNameAsString(); ME->printPretty(os,0,Policy); os << "' is directly or indirectly modified in const function '"; llvm::errs() << os.str(); llvm::errs() << llvm::dyn_cast<clang::CXXMethodDecl>(AC->getDecl())->getQualifiedNameAsString(); if (visitingCallExpr) { llvm::errs() << "' in function call '"; visitingCallExpr->printPretty(os,0,Policy); } if (hasWork()) { llvm::errs() << "' in call stack '"; WListDump(llvm::errs()); } llvm::errs() << "'.\n"; // ME->printPretty(llvm::errs(),0,Policy); // llvm::errs()<<"\n"; // ME->dump(); // llvm::errs()<<"\n"; // WListDump(llvm::errs()); // llvm::errs()<<"\n"; // if (visitingCallExpr) visitingCallExpr->getImplicitObjectArgument()->dump(); // llvm::errs()<<"\n"; if (!m_exception.reportClass( CELoc, BR ) ) return; BR.EmitBasicReport(AC->getDecl(),"Class Checker : Member data modified in const function","ThreadSafety",os.str(),CELoc,R); } void WalkAST::ReportCall(const clang::CXXMemberCallExpr *CE) { llvm::SmallString<100> buf; llvm::raw_svector_ostream os(buf); CmsException m_exception; clang::LangOptions LangOpts; LangOpts.CPlusPlus = true; clang::PrintingPolicy Policy(LangOpts); CE->printPretty(os,0,Policy); os<<"' is a non-const member function that could modify member data object '"; CE->getImplicitObjectArgument()->printPretty(os,0,Policy); os << llvm::dyn_cast<clang::CXXMethodDecl>(AC->getDecl())->getQualifiedNameAsString(); os << "'.\n"; clang::ento::PathDiagnosticLocation CELoc = clang::ento::PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(),AC); if (!m_exception.reportClass( CELoc, BR ) ) return; BugType * BT = new BugType("Class Checker : Non-const member function could modify member data object","ThreadSafety"); BugReport * R = new BugReport(*BT,os.str(),CELoc); BR.emitReport(R); } void WalkAST::ReportCast(const clang::ExplicitCastExpr *CE,const clang::Expr *E) { llvm::SmallString<100> buf; llvm::raw_svector_ostream os(buf); CmsException m_exception; clang::LangOptions LangOpts; LangOpts.CPlusPlus = true; clang::PrintingPolicy Policy(LangOpts); os << "Const qualifier of data object '"; E->printPretty(os,0,Policy); os <<"' was removed via cast expression '"; CE->printPretty(os,0,Policy); os << "'.\n"; llvm::errs()<<os.str(); llvm::errs() << llvm::dyn_cast<clang::CXXMethodDecl>(AC->getDecl())->getQualifiedNameAsString(); if (visitingCallExpr) { llvm::errs() << "' in call stack '"; WListDump(llvm::errs()); } llvm::errs()<<"'.\n"; clang::ento::PathDiagnosticLocation CELoc = clang::ento::PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(),AC); if (!m_exception.reportClass( CELoc, BR ) ) return; BugType * BT = new BugType("Class Checker : Const cast away from member data in const function","ThreadSafety"); BugReport * R = new BugReport(*BT,os.str(),CELoc); BR.emitReport(R); } void WalkAST::ReportCallArg(const clang::CXXMemberCallExpr *CE,const int i) { llvm::SmallString<100> buf; llvm::raw_svector_ostream os(buf); CmsException m_exception; clang::LangOptions LangOpts; LangOpts.CPlusPlus = true; clang::PrintingPolicy Policy(LangOpts); clang::CXXMethodDecl * MD = llvm::dyn_cast<clang::CXXMemberCallExpr>(CE)->getMethodDecl(); const clang::MemberExpr *E = llvm::dyn_cast<clang::MemberExpr>(CE->getArg(i)); clang::ParmVarDecl *PVD=llvm::dyn_cast<clang::ParmVarDecl>(MD->getParamDecl(i)); clang::ValueDecl * VD = llvm::dyn_cast<clang::ValueDecl>(E->getMemberDecl()); os << " Member data " << VD->getQualifiedNameAsString(); os<< " is passed to a non-const reference parameter"; os <<" of CXX method '" << MD->getQualifiedNameAsString()<<"' in const function '"; os<< llvm::dyn_cast<clang::CXXMethodDecl>(AC->getDecl())->getQualifiedNameAsString(); if (visitingCallExpr) { os << "' in call stack '"; WListDump(os); } os<<"'.\n"; clang::ento::PathDiagnosticLocation ELoc = clang::ento::PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(),AC); clang::SourceLocation L = E->getExprLoc(); if (!m_exception.reportClass( ELoc, BR ) ) return; BR.EmitBasicReport(CE->getCalleeDecl(),"Class Checker : Member data passed to non-const reference","ThreadSafety",os.str(),ELoc,L); } void WalkAST::ReportCallReturn(const clang::ReturnStmt * RS) { llvm::SmallString<100> buf; llvm::raw_svector_ostream os(buf); CmsException m_exception; clang::LangOptions LangOpts; LangOpts.CPlusPlus = true; clang::PrintingPolicy Policy(LangOpts); os << "Returns a pointer or reference to a non-const member data object "; os << "in const function in statement '"; RS->printPretty(os,0,Policy); // llvm::errs() << llvm::dyn_cast<clang::CXXMethodDecl>(AC->getDecl())->getQualifiedNameAsString(); // if (visitingCallExpr) { // llvm::errs() << " in call stack "; // WListDump(llvm::errs()); // } // llvm::errs()<<"\n"; clang::ento::PathDiagnosticLocation CELoc = clang::ento::PathDiagnosticLocation::createBegin(RS, BR.getSourceManager(),AC); if (!m_exception.reportClass( CELoc, BR ) ) return; BugType * BT = new BugType("Class Checker : Const function returns pointer or reference to non-const member data object","ThreadSafety"); BugReport * R = new BugReport(*BT,os.str(),CELoc); BR.emitReport(R); } void ClassChecker::checkASTDecl(const clang::CXXRecordDecl *RD, clang::ento::AnalysisManager& mgr, clang::ento::BugReporter &BR) const { const clang::SourceManager &SM = BR.getSourceManager(); llvm::SmallString<100> buf; llvm::raw_svector_ostream os(buf); clang::FileSystemOptions FSO; clang::FileManager FM(FSO); if (!FM.getFile("/tmp/classes.txt") ) { llvm::errs()<<"\n\nChecker optional.ClassChecker cannot find /tmp/classes.txt. Run 'scram b checker' with USER_LLVM_CHECKERS='-enable-checker optional.ClassDumperCT -enable-checker optional.ClassDumperFT' to create /tmp/classes.txt.\n\n\n"; exit(1); } llvm::MemoryBuffer * buffer = FM.getBufferForFile(FM.getFile("/tmp/classes.txt")); os <<"class "<<RD->getQualifiedNameAsString()<<"\n"; llvm::StringRef Rname(os.str()); if (buffer->getBuffer().find(Rname) == llvm::StringRef::npos ) {return;} clang::ento::PathDiagnosticLocation DLoc =clang::ento::PathDiagnosticLocation::createBegin( RD, SM ); if ( !m_exception.reportClass( DLoc, BR ) ) return; // clangcms::WalkAST walker(BR, mgr.getAnalysisDeclContext(RD)); // clang::LangOptions LangOpts; // LangOpts.CPlusPlus = true; // clang::PrintingPolicy Policy(LangOpts); // RD->print(llvm::errs(),Policy,0,0); // llvm::errs() << s.str(); // llvm::errs()<<"\n\n\n\n"; // RD->dump(); // llvm::errs()<<"\n\n\n\n"; // Check the constructors. // for (clang::CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), E = RD->ctor_end(); // I != E; ++I) { // if (clang::Stmt *Body = I->getBody()) { // llvm::errs()<<"Visited Constructors for\n"; // llvm::errs()<<RD->getNameAsString(); // walker.Visit(Body); // walker.Execute(); // } // } // Check the class methods (member methods). for (clang::CXXRecordDecl::method_iterator I = RD->method_begin(), E = RD->method_end(); I != E; ++I) { clang::ento::PathDiagnosticLocation DLoc =clang::ento::PathDiagnosticLocation::createBegin( (*I) , SM ); if ( !m_exception.reportClass( DLoc, BR ) ) continue; if ( !llvm::isa<clang::CXXMethodDecl>((*I)) ) continue; if (!(*I)->isConst()) continue; clang::CXXMethodDecl * MD = llvm::cast<clang::CXXMethodDecl>((*I)->getMostRecentDecl()); // llvm::errs() << "\n\nmethod "<<MD->getQualifiedNameAsString()<<"\n\n"; // for (clang::CXXMethodDecl::method_iterator J = MD->begin_overridden_methods(), F = MD->end_overridden_methods(); J != F; ++J) { // llvm::errs()<<"\n\n overwritten method "<<(*J)->getQualifiedNameAsString()<<"\n\n"; // } // llvm::errs()<<"\n*****************************************************\n"; // llvm::errs()<<"\nVisited CXXMethodDecl\n"; // llvm::errs()<<RD->getNameAsString(); // llvm::errs()<<"::"; // llvm::errs()<<MD->getNameAsString(); // llvm::errs()<<"\n"; // llvm::errs()<<"\n*****************************************************\n"; if ( MD->hasBody() ) { clang::Stmt *Body = MD->getBody(); // clang::LangOptions LangOpts; // LangOpts.CPlusPlus = true; // clang::PrintingPolicy Policy(LangOpts); // std::string TypeS; // llvm::raw_string_ostream s(TypeS); // llvm::errs() << "\n\n+++++++++++++++++++++++++++++++++++++\n\n"; // llvm::errs() << "\n\nPretty Print\n\n"; // Body->printPretty(s, 0, Policy); // llvm::errs() << s.str(); // Body->dumpAll(); // llvm::errs() << "\n\n+++++++++++++++++++++++++++++++++++++\n\n"; clangcms::WalkAST walker(BR, mgr.getAnalysisDeclContext(MD)); walker.Visit(Body); clang::QualType CQT = MD->getCallResultType(); clang::QualType RQT = MD->getResultType(); clang::ASTContext &Ctx = BR.getContext(); clang::QualType RTy = Ctx.getCanonicalType(RQT); clang::QualType CTy = Ctx.getCanonicalType(CQT); // llvm::errs()<<"\n"<<MD->getQualifiedNameAsString()<<"\n\n"; // llvm::errs()<<"Call Result Type\n"; // CTy->dump(); // llvm::errs()<<"\n"; // llvm::errs()<<"Result Type\n"; // RTy->dump(); // llvm::errs()<<"\n"; clang::ento::PathDiagnosticLocation ELoc =clang::ento::PathDiagnosticLocation::createBegin( MD , SM ); if ((RTy->isPointerType() || RTy->isReferenceType() )) if (!support::isConst(RTy) ) if ( MD->getNameAsString().find("clone")==std::string::npos ) { llvm::SmallString<100> buf; llvm::raw_svector_ostream os(buf); os << MD->getQualifiedNameAsString() << " is a const member function that returns a pointer or reference to a non-const object"; os << "\n"; llvm::errs()<<os.str(); clang::SourceRange SR = MD->getSourceRange(); BR.EmitBasicReport(MD, "Class Checker : Const function returns pointer or reference to non-const object.","ThreadSafety",os.str(),ELoc); } } } /* end of methods loop */ } //end of class } //end namespace
[ "sha1-33476957b06a1bc61e5124243258241c72d1e027@cern.ch" ]
sha1-33476957b06a1bc61e5124243258241c72d1e027@cern.ch
9135bbbc568e6a422605a9c5624474058af62a70
ab13ec10d61795ad7ecfe9446b6cdf7cd5e03f15
/src/txdb.h
848cd7fe1b00ce5067eb61c15489def7d1dae8f3
[ "MIT" ]
permissive
Bitcoin-Lite-Project/bitcoin-lite
3cf4d449041a57fd4bdf252a31a55f99b2dcda8e
7d853c03530197a4fd15b07af2733e5a73441286
refs/heads/master
2021-05-15T13:03:43.847344
2017-10-27T07:10:40
2017-10-27T07:10:40
108,396,578
0
0
null
null
null
null
UTF-8
C++
false
false
2,123
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOINLITE_TXDB_H #define BITCOINLITE_TXDB_H #include "leveldbwrapper.h" #include "main.h" #include <map> #include <string> #include <utility> #include <vector> class CCoins; class uint256; //! -dbcache default (MiB) static const int64_t nDefaultDbCache = 100; //! max. -dbcache in (MiB) static const int64_t nMaxDbCache = sizeof(void*) > 4 ? 4096 : 1024; //! min. -dbcache in (MiB) static const int64_t nMinDbCache = 4; /** CCoinsView backed by the LevelDB coin database (chainstate/) */ class CCoinsViewDB : public CCoinsView { protected: CLevelDBWrapper db; public: CCoinsViewDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false); bool GetCoins(const uint256 &txid, CCoins &coins) const; bool HaveCoins(const uint256 &txid) const; uint256 GetBestBlock() const; bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock); bool GetStats(CCoinsStats &stats) const; }; /** Access to the block database (blocks/index/) */ class CBlockTreeDB : public CLevelDBWrapper { public: CBlockTreeDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false); private: CBlockTreeDB(const CBlockTreeDB&); void operator=(const CBlockTreeDB&); public: bool WriteBlockIndex(const CDiskBlockIndex& blockindex); bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo); bool WriteBlockFileInfo(int nFile, const CBlockFileInfo &fileinfo); bool ReadLastBlockFile(int &nFile); bool WriteLastBlockFile(int nFile); bool WriteReindexing(bool fReindex); bool ReadReindexing(bool &fReindex); bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos); bool WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> > &list); bool WriteFlag(const std::string &name, bool fValue); bool ReadFlag(const std::string &name, bool &fValue); bool LoadBlockIndexGuts(); }; #endif // BITCOINLITE_TXDB_H
[ "bitcoinlitecrypto@gmail.com" ]
bitcoinlitecrypto@gmail.com
eaa4a9fc62d0b7b3877a4ce2932b86307cc14f80
423f187dba54d6175e904d2d4c4719635ad0af95
/Standalone/VRUco Standalone/RoomSetup.cpp
e103f071363efeecc1e14a6885bdb98049966802
[]
no_license
demonzla/VRUco
cc8a069cde8df78fcedce2c28c923726f892799e
edd74f603a8cbe667c2ae1bd5986851f15a175bb
refs/heads/master
2021-09-04T20:00:11.746536
2018-01-22T00:26:42
2018-01-22T00:26:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,858
cpp
#include "RoomSetup.h" namespace RoomSetup { bool has_completed_setup = false; auto WriteLog = [](std::string info) {std::cout << info << std::endl;}; aruco::MarkerMap GetMarkerMap(ps3eye_context& camera_ctx, const aruco::CameraParameters& camera_params, std::string dictionary_name, float aruco_square_dims) { WriteLog("Calibration!"); auto mapper = aruco_mm::MarkerMapper::create(); mapper->setParams(camera_params, aruco_square_dims, 58, true); mapper->getMarkerDetector().setDictionary(dictionary_name); mapper->getMarkerDetector().setDetectionMode(aruco::DetectionMode::DM_NORMAL); const int CAMERA_WIDTH = 640; const int CAMERA_HEIGHT = 480; uint8_t* camera_data_raw = new uint8_t[CAMERA_WIDTH * CAMERA_HEIGHT * 3]; IplImage* camera_data_ipl = cvCreateImage(cvSize(CAMERA_WIDTH, CAMERA_HEIGHT), 8, 3); cv::Mat current_frame; cv::namedWindow("Calibration"); aruco::MarkerDetector marker_detector; marker_detector.setDictionary(aruco::Dictionary::ARUCO_MIP_36h12); long frame_count = 0; WriteLog("Press e to end calibration"); while (true) { char c = cv::waitKey(10); if (c == 'e') break; // Get next frame camera_ctx.eye->getFrame(camera_data_raw); cvSetData(camera_data_ipl, camera_data_raw, camera_data_ipl->widthStep); current_frame = cv::cvarrToMat(camera_data_ipl); std::vector<aruco::Marker> markers = marker_detector.detect(current_frame, camera_params, aruco_square_dims); if (markers.size() > 3) { mapper->process(current_frame, frame_count++, true); WriteLog("Frame count " + std::to_string(frame_count)); } mapper->drawDetectedMarkers(current_frame, 3); imshow("Calibration", current_frame); } mapper->optimize(); cv::destroyWindow("Calibration"); delete[] camera_data_raw; WriteLog("Done!"); return mapper->getMarkerMap(); } };
[ "infinitellamas@users.noreply.github.com" ]
infinitellamas@users.noreply.github.com
aba4477aef34bd9919230e82f4629ccd0a2479a4
2f9951bc5cadbf67c8d7da6353cd63a5c3efaac6
/webserver/timer.h
5f5cd8f7fbdcf0b683d804b28b86ab678261365c
[]
no_license
zhaobolin/WebServer
1bbd120aa7c12643f6a74fdd6d4a699944e5ffee
7a5788d70716ab1752a8b58c328e238d4a46922f
refs/heads/master
2020-04-24T14:45:56.934013
2019-03-08T09:06:08
2019-03-08T09:06:08
172,035,480
0
0
null
null
null
null
UTF-8
C++
false
false
2,449
h
#pragma once #include <stdio.h> #include <memory> #include <queue> #include <functional> #include <vector> typedef std::function<void()> TimerCallback; class TimerNode { public: TimerNode(TimerCallback cb,int timeout,double interval); ~TimerNode(); TimerNode(TimerNode &tn); void update(int timeout); //void run(){cb_();} bool isValid();//检查是否到期 void setDeleted(){deleted_=true;} bool isDeleted(){return deleted_;} size_t getExpTime(){return expiredTime_;} static int numCreated(){return numcreated_;} private: bool deleted_; size_t expiredTime_; double interval_;//超过时间间隔,对于一次性定时器,值为零 bool repeat_;//是否重复 TimerCallback cb_; static int numcreated_; }; struct TimerCmp//比较函数,用于排序 { bool operator()(std::shared_ptr<TimerNode>&a,std::shared_ptr<TimerNode>&b)//仿函数,a>b的时候,a在b后面 { return a->getExpTime()>b->getExpTime(); } }; typedef std::shared_ptr<TimerNode> SPTimerNode; class TimerManager//时间队列,待处理的延时事件在这里 { public: TimerManager(); ~TimerManager(); void addTimer(TimerCallback cb,int timeout,double interval); std::vector<SPTimerNode> getExpried(); private: std::priority_queue<SPTimerNode,std::deque<SPTimerNode>,TimerCmp> timerNodeQueue; }; /*class Timer { public: Timer(const Callback &cb,Timestamp when,double interval) :callback_(cb), expiration_(when), interval_(interval), repeat_(interval>0.0), sequence_(s_numCreated_.incrementAndGet()) {} private: typedef std::function<void> Callback; Callback callback_;//定时器回调函数 Timestamp expiration_; const double interval_;//超过时间间隔,对于一次性定时器,值为零 const bool repeat_;//是否重复 const int sequence_;//定时器序号 static int s_numCreated_; }; class TimerId { public: TimerId(): timer_(NULL), sequence_(0) { } TimerId(Timer* timer,int seq): timer_(timer), sequence_(seq) { } friend class TimerQueue; private: Timer* timer_; int sequence_; }; */
[ "1085066878@qq.com" ]
1085066878@qq.com
f7e47085ebffda924840f9db5dab91db4f0c6e2c
18d14b2186fedec23ae989cc09b9c9cf820c2f8d
/inc/BdpPacket.h
15931b870b253046ff377e99b1b1c00502f0d79a
[ "MIT" ]
permissive
9060/BonDriverProxy
8b5030d2f5101bfd21d3409f17b38188a4c23ab6
21b182473450c9973f8727f82a9f52c73b324310
refs/heads/master
2021-01-16T12:20:59.339115
2015-05-07T15:06:03
2015-05-07T15:06:03
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,942
h
#ifndef __BDPPACKET_H__ #define __BDPPACKET_H__ enum enumCommand { eSelectBonDriver = 0, eCreateBonDriver, eOpenTuner, eCloseTuner, eSetChannel1, eGetSignalLevel, eWaitTsStream, eGetReadyCount, eGetTsStream, ePurgeTsStream, eRelease, eGetTunerName, eIsTunerOpening, eEnumTuningSpace, eEnumChannelName, eSetChannel2, eGetCurSpace, eGetCurChannel, eGetTotalDeviceNum, eGetActiveDeviceNum, eSetLnbPower, }; #pragma pack(push, 1) struct stPacketHead { BYTE m_bSync; BYTE m_bCommand; BYTE m_bReserved1; BYTE m_bReserved2; DWORD m_dwBodyLength; }; struct stPacket { stPacketHead head; BYTE payload[1]; }; #pragma pack(pop) #define SYNC_BYTE 0xff class cPacketHolder { #ifdef __BONDRIVERPROXY_H__ friend class cProxyServer; #elif defined(__BONDRIVER_PROXYEX_H__) friend class cProxyServerEx; #else friend class cProxyClient; #endif union { stPacket *m_pPacket; BYTE *m_pBuf; }; size_t m_Size; BOOL m_bDelete; inline void init(size_t PayloadSize) { m_pBuf = new BYTE[sizeof(stPacketHead) + PayloadSize]; m_bDelete = TRUE; } public: cPacketHolder(size_t PayloadSize) { init(PayloadSize); } cPacketHolder(enumCommand eCmd, size_t PayloadSize) { init(PayloadSize); *(DWORD *)m_pBuf = 0; m_pPacket->head.m_bSync = SYNC_BYTE; SetCommand(eCmd); m_pPacket->head.m_dwBodyLength = ::htonl((DWORD)PayloadSize); m_Size = sizeof(stPacketHead) + PayloadSize; } ~cPacketHolder() { if (m_bDelete) delete[] m_pBuf; } inline BOOL IsValid(){ return (m_pPacket->head.m_bSync == SYNC_BYTE); } inline BOOL IsTS(){ return (m_pPacket->head.m_bCommand == (BYTE)eGetTsStream); } inline enumCommand GetCommand(){ return (enumCommand)m_pPacket->head.m_bCommand; } inline void SetCommand(enumCommand eCmd){ m_pPacket->head.m_bCommand = (BYTE)eCmd; } inline DWORD GetBodyLength(){ return ::ntohl(m_pPacket->head.m_dwBodyLength); } inline void SetDeleteFlag(BOOL b){ m_bDelete = b; } }; class cPacketFifo : protected std::queue<cPacketHolder *> { const size_t m_fifoSize; cCriticalSection m_Lock; cEvent m_Event; cPacketFifo &operator=(const cPacketFifo &); // shut up C4512 public: cPacketFifo() : m_fifoSize(g_PacketFifoSize), m_Event(TRUE, FALSE){} ~cPacketFifo() { LOCK(m_Lock); while (!empty()) { cPacketHolder *p = front(); pop(); delete p; } } void Push(cPacketHolder *p) { LOCK(m_Lock); if (size() >= m_fifoSize) { #if _DEBUG _RPT1(_CRT_WARN, "Packet Queue OVERFLOW : size[%d]\n", size()); #endif // TSの場合のみドロップ if (p->IsTS()) { delete p; return; } } push(p); m_Event.Set(); } void Pop(cPacketHolder **p) { LOCK(m_Lock); if (!empty()) { *p = front(); pop(); if (empty()) m_Event.Reset(); } else m_Event.Reset(); } HANDLE GetEventHandle() { return (HANDLE)m_Event; } #if _DEBUG inline size_t Size() { return size(); } #endif }; #endif // __BDPPACKET_H__
[ "unknown_@live.jp" ]
unknown_@live.jp
484330d3be5d8f0617bc1a7752b4089d0c666564
4ff7cfd989f2345416a9e8760077e75147f1dfca
/C++/tsoj/1427分数数列3.cpp
a5c8c40cdf81913c4844307a199c447e89c9db9a
[]
no_license
gqzcl/code_save
bc7de0974402e1ef85dbaeb51d38699d11d32a0f
47a817ab6e5c0ad16450c3d36263274c1ff3dcd1
refs/heads/master
2020-04-07T08:16:31.591946
2018-12-21T07:59:55
2018-12-21T07:59:55
158,206,968
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
#include<iostream> #include<cstring> using namespace std; char s[10000]; int a[5000]; int main() { int n; while(cin>>n) { int max=1; memset(s,0,sizeof(s)); a[1]=1; s[2]=s[1]=1; int t=1; for(int i=2;i<=n;i++) { while(s[t]!=0) { t++; } s[t]=1; a[i]=t; s[t+i]=1; if(a[max]*(t+i)<(a[max]+max)*t) max=i; } cout<<a[n]<<'/'<<a[n]+n<<endl; cout<<a[max]<<'/'<<a[max]+max<<endl; int emax=1; for(emax;emax<=n;emax++) { if(a[emax]*(a[max]+max)==(a[emax]+emax)*a[max]&&emax!=max) cout<<a[emax]<<'/'<<a[emax]+emax<<endl; } } }
[ "1476048558@qq.com" ]
1476048558@qq.com
57950ce409129fa4825959a5ff39d80a40978ffa
c71ebbc909b1b9019fe46a01022075853f1f852b
/Arduino Braccio/Arduino Related Stuff/New_API_Client_Code/New_API_Client_Code.ino
e5eceb2294c55cdae82457536e138bf3c855c5ec
[]
no_license
AmI-2018/BabySpy-code
339f87758fbf04b332a07910876de4d3ed85f7f9
18f65b3471d0333cd441b724bb6df26048a64fcf
refs/heads/master
2021-04-15T13:45:56.375034
2018-07-19T12:20:52
2018-07-19T12:20:52
126,826,756
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
ino
/* API Client Code This sketch allows the Yun to connect to a local http and receive a text file containin the code from the API you would like to run. This is a modifed sketch from Yun Client available in the Arduino Libraries. Modified by Yeshitha Amarasekara */ //Libraries #include <Bridge.h> #include <Braccio.h> #include <Servo.h> #include <HttpClient.h> #include <SPI.h> #include <SD.h> //Variables File file; char c; Servo base; Servo shoulder; Servo elbow; Servo wrist_ver; Servo wrist_rot; Servo gripper; void setup() { // Bridge takes about two seconds to start up // it can be helpful to use the on-board LED // as an indicator for when it has initialized pinMode(13, OUTPUT); digitalWrite(13, LOW); Bridge.begin(); Braccio.begin(); digitalWrite(13, HIGH); Serial.begin(9600); while (!Serial){ } } void loop() { // Initialize the client library HttpClient client; // Make a HTTP request: // Enter the Local URL on the network from where to download the file // Initializing the file client.get(""); file = SD.open("code.ino", FILE_WRITE); if(!SD.begin(4)){ Serial.println("Initialization Failed!"); } // If there are incoming bytes available // From the server, read them and print them: while (client.available()) { c = client.read(); if (file){ if(c != ';'){ file.print(c); } else{ file.println(); } } file.close(); //Running the code that was just received. //The main structure of the code alwasys has to start with void start(){ and end with } start(); //Delay before checking for new data delay(5000); } }
[ "s226587@studenti.polito.it" ]
s226587@studenti.polito.it
a479c8e2e71b737c7dedf317d3803ab6d3db7e94
2e8a05666d97c059500258fce9d88c59b9d55e40
/DSA-I/Lab5/q1.cpp
2809d97760be921f8edbe986481a51ee76115316
[]
no_license
aksh555/IT-Labs
b1d3128a0e685389ac0bf6fe522af77f8187da66
f14e8f94e5fa9a1083e00d2b66bf48bb9596d051
refs/heads/main
2023-07-10T03:01:58.244079
2021-08-09T11:16:11
2021-08-09T11:16:11
317,137,908
2
0
null
null
null
null
UTF-8
C++
false
false
1,851
cpp
#include<iostream> #include<stdlib.h> using namespace std; struct Node { int data; struct Node *next; }; struct Node* front = NULL; struct Node* rear = NULL; void insert(int val) { struct Node* newnode = (struct Node*) malloc(sizeof(struct Node)); newnode->data = val; newnode->next = NULL; if(rear==NULL){ front = newnode; rear = newnode;} else{ rear->next=newnode; rear=newnode; } } void sort(int n) { struct Node *ptr; struct Node *prev; if(front == NULL) cout<<"empty"; if(front->next==NULL) return; ptr = front; prev = front; while(n!=0) { if(ptr->data == 0 && ptr!=front) { prev-> next = ptr -> next; ptr ->next = front; front = ptr; ptr=prev->next; } else if(ptr->data == 2) { if(ptr!=front) { prev-> next = ptr-> next; rear->next = ptr; ptr->next = NULL; rear = ptr; ptr=prev->next; } else { front = ptr->next; rear ->next = ptr; ptr ->next = NULL; rear = ptr; ptr=front; } } else { prev=ptr; ptr=ptr->next; } n--; } } void display() { struct Node* ptr; if(front==NULL) cout<<"Queue is empty"; else { ptr = front; cout<<"Queue elements: "; while (ptr != NULL) { cout<< ptr->data <<" "; ptr = ptr->next; } } cout<<endl; } int main() { char ch = 'y'; int c, val; int n(0); while(ch =='y') { cout<<"Enter value to be enqueued:"<<endl; cin>>val; insert(val); n++; cout<<"Do you want to insert more? "<<endl; cin>>ch; } cout<<"Sorted:"; sort(n); display(); }
[ "akshblr555@gmail.com" ]
akshblr555@gmail.com
e53f0535bbf6e27cba5394e33947f61a2a52149e
e095aa0023ae8f6686c99ecfdad7e96c06d092fc
/src/main.cpp
3453ea858cf70cdea8f0b59f67ec9c693e7fbbe4
[]
no_license
ArgoText/Argo
e8553475ecc4ddd4ff85970f1591c015facc65c4
e18eff9cac6cc6fd0f1e6ef4e0b338bd666c0507
refs/heads/main
2023-08-08T02:46:00.220249
2021-09-14T02:29:02
2021-09-14T02:29:02
361,298,071
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include <QApplication> #include <QKeyEvent> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow window; window.show(); return app.exec(); }
[ "avpat02@gmail.com" ]
avpat02@gmail.com
2fc0e77a0d95a0a1619a67598d001b53a784bee9
6a82b383545f4500df5c26afd17cf03e0e89d292
/opendnp3/DNP3/LinkLayer.cpp
edae8f2341c74a84a9ebfafabe9dafaede93e43e
[]
no_license
nitesh-agsft/internal-projects
98f8de64c981601219ce07d80905a5d505beb310
c2bd16857a9701795b4ad1ba932a0fa63577c98c
refs/heads/master
2021-01-16T17:39:00.655783
2017-10-09T13:02:25
2017-10-09T13:02:25
100,011,951
0
0
null
null
null
null
UTF-8
C++
false
false
6,855
cpp
// // Licensed to Green Energy Corp (www.greenenergycorp.com) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Green Enery Corp 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 "LinkLayer.h" #include <assert.h> #include <boost/bind.hpp> #include <opendnp3/APL/Logger.h> #include <opendnp3/APL/Exception.h> #include "ILinkRouter.h" #include "PriLinkLayerStates.h" #include "SecLinkLayerStates.h" #include "DNPConstants.h" using namespace boost; namespace apl { namespace dnp { LinkLayer::LinkLayer(apl::Logger* apLogger, ITimerSource* apTimerSrc, const LinkConfig& arConfig) : Loggable(apLogger), ILowerLayer(apLogger), mCONFIG(arConfig), mRetryRemaining(0), mpTimerSrc(apTimerSrc), mpTimer(NULL), mNextReadFCB(false), mNextWriteFCB(false), mIsOnline(false), mpRouter(NULL), mpPriState(PLLS_SecNotReset::Inst()), mpSecState(SLLS_NotReset::Inst()) {} void LinkLayer::SetRouter(ILinkRouter* apRouter) { assert(mpRouter == NULL); assert(apRouter != NULL); mpRouter = apRouter; } void LinkLayer::ChangeState(PriStateBase* apState) { mpPriState = apState; } void LinkLayer::ChangeState(SecStateBase* apState) { mpSecState = apState; } bool LinkLayer::Validate(bool aIsMaster, boost::uint16_t aSrc, boost::uint16_t aDest) { if(!mIsOnline) throw InvalidStateException(LOCATION, "LowerLayerDown"); if(aIsMaster == mCONFIG.IsMaster) { ERROR_BLOCK(LEV_WARNING, (aIsMaster ? "Master frame received for master" : "Slave frame received for slave"), DLERR_MASTER_BIT_MATCH); return false; } if(aDest != mCONFIG.LocalAddr) { ERROR_BLOCK(LEV_WARNING, "Frame for unknown destintation", DLERR_UNKNOWN_DESTINATION); return false; } if(aSrc != mCONFIG.RemoteAddr) { ERROR_BLOCK(LEV_WARNING, "Frame from unknwon source", DLERR_UNKNOWN_SOURCE); return false; } return true; } //////////////////////////////// // ILinkContext //////////////////////////////// void LinkLayer::OnLowerLayerUp() { if(mIsOnline) throw InvalidStateException(LOCATION, "LowerLayerUp"); mIsOnline = true; if(mpUpperLayer) mpUpperLayer->OnLowerLayerUp(); } void LinkLayer::OnLowerLayerDown() { if(!mIsOnline) throw InvalidStateException(LOCATION, "LowerLayerDown"); if(mpTimer != NULL) this->CancelTimer(); mIsOnline = false; mpPriState = PLLS_SecNotReset::Inst(); mpSecState = SLLS_NotReset::Inst(); if(mpUpperLayer) mpUpperLayer->OnLowerLayerDown(); } void LinkLayer::Transmit(const LinkFrame& arFrame) { mpRouter->Transmit(arFrame); } void LinkLayer::SendAck() { mSecFrame.FormatAck(mCONFIG.IsMaster, false, mCONFIG.RemoteAddr, mCONFIG.LocalAddr); this->Transmit(mSecFrame); } void LinkLayer::SendLinkStatus() { mSecFrame.FormatLinkStatus(mCONFIG.IsMaster, false, mCONFIG.RemoteAddr, mCONFIG.LocalAddr); this->Transmit(mSecFrame); } void LinkLayer::SendResetLinks() { mPriFrame.FormatResetLinkStates(mCONFIG.IsMaster, mCONFIG.RemoteAddr, mCONFIG.LocalAddr); this->Transmit(mPriFrame); } void LinkLayer::SendUnconfirmedUserData(const boost::uint8_t* apData, size_t aLength) { mPriFrame.FormatUnconfirmedUserData(mCONFIG.IsMaster, mCONFIG.RemoteAddr, mCONFIG.LocalAddr, apData, aLength); this->Transmit(mPriFrame); this->DoSendSuccess(); } void LinkLayer::SendDelayedUserData(bool aFCB) { mDelayedPriFrame.ChangeFCB(aFCB); this->Transmit(mDelayedPriFrame); } void LinkLayer::StartTimer() { assert(mpTimer == NULL); mpTimer = this->mpTimerSrc->Start(mCONFIG.Timeout, bind(&LinkLayer::OnTimeout, this)); } void LinkLayer::CancelTimer() { assert(mpTimer); mpTimer->Cancel(); mpTimer = NULL; } void LinkLayer::ResetRetry() { this->mRetryRemaining = mCONFIG.NumRetry; } bool LinkLayer::Retry() { if(mRetryRemaining > 0) { --mRetryRemaining; return true; } else return false; } //////////////////////////////// // IFrameSink //////////////////////////////// void LinkLayer::Ack(bool aIsMaster, bool aIsRcvBuffFull, boost::uint16_t aDest, boost::uint16_t aSrc) { if(this->Validate(aIsMaster, aSrc, aDest)) mpPriState->Ack(this, aIsRcvBuffFull); } void LinkLayer::Nack(bool aIsMaster, bool aIsRcvBuffFull, boost::uint16_t aDest, boost::uint16_t aSrc) { if(this->Validate(aIsMaster, aSrc, aDest)) mpPriState->Nack(this, aIsRcvBuffFull); } void LinkLayer::LinkStatus(bool aIsMaster, bool aIsRcvBuffFull, boost::uint16_t aDest, boost::uint16_t aSrc) { if(this->Validate(aIsMaster, aSrc, aDest)) mpPriState->LinkStatus(this, aIsRcvBuffFull); } void LinkLayer::NotSupported (bool aIsMaster, bool aIsRcvBuffFull, boost::uint16_t aDest, boost::uint16_t aSrc) { if(this->Validate(aIsMaster, aSrc, aDest)) mpPriState->NotSupported(this, aIsRcvBuffFull); } void LinkLayer::TestLinkStatus(bool aIsMaster, bool aFcb, boost::uint16_t aDest, boost::uint16_t aSrc) { if(this->Validate(aIsMaster, aSrc, aDest)) mpSecState->TestLinkStatus(this, aFcb); } void LinkLayer::ResetLinkStates(bool aIsMaster, boost::uint16_t aDest, boost::uint16_t aSrc) { if(this->Validate(aIsMaster, aSrc, aDest)) mpSecState->ResetLinkStates(this); } void LinkLayer::RequestLinkStatus(bool aIsMaster, boost::uint16_t aDest, boost::uint16_t aSrc) { if(this->Validate(aIsMaster, aSrc, aDest)) mpSecState->RequestLinkStatus(this); } void LinkLayer::ConfirmedUserData(bool aIsMaster, bool aFcb, boost::uint16_t aDest, boost::uint16_t aSrc, const boost::uint8_t* apData, size_t aDataLength) { if(this->Validate(aIsMaster, aSrc, aDest)) mpSecState->ConfirmedUserData(this, aFcb, apData, aDataLength); } void LinkLayer::UnconfirmedUserData(bool aIsMaster, boost::uint16_t aDest, boost::uint16_t aSrc, const boost::uint8_t* apData, size_t aDataLength) { if(this->Validate(aIsMaster, aSrc, aDest)) mpSecState->UnconfirmedUserData(this, apData, aDataLength); } //////////////////////////////// // ILowerLayer //////////////////////////////// void LinkLayer::_Send(const boost::uint8_t* apData, size_t aDataLength) { if(!mIsOnline) throw InvalidStateException(LOCATION, "LowerLayerDown"); if(mCONFIG.UseConfirms) mpPriState->SendConfirmed(this, apData, aDataLength); else mpPriState->SendUnconfirmed(this, apData, aDataLength); } void LinkLayer::OnTimeout() { assert(mpTimer); mpTimer = NULL; mpPriState->OnTimeout(this); } } }
[ "nitesh@agsft.com" ]
nitesh@agsft.com
c88c5c04e9f356f2186d18b0cd18e69dade69a0e
1cea7f47e17037980045d128bcd7a74e18701c7c
/src/wasm/wasm-code-manager.h
bffe09ff85c418420ac87d408646ed6e443b2539
[ "BSD-3-Clause", "SunPro", "bzip2-1.0.6" ]
permissive
ZhangZexiao/v8
593a8ccfee27ea2834938af884b1321c319076fc
e4ca6f7a8124263891b28b7e45314f4cac5d4659
refs/heads/master
2020-03-21T05:21:00.801563
2018-06-21T10:48:54
2018-06-21T10:48:54
138,156,652
0
0
null
2018-06-21T10:37:59
2018-06-21T10:37:59
null
UTF-8
C++
false
false
18,738
h
// Copyright 2017 the V8 project 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 V8_WASM_WASM_CODE_MANAGER_H_ #define V8_WASM_WASM_CODE_MANAGER_H_ #include <functional> #include <list> #include <map> #include <unordered_map> #include "src/base/macros.h" #include "src/handles.h" #include "src/trap-handler/trap-handler.h" #include "src/vector.h" #include "src/wasm/module-compiler.h" namespace v8 { namespace internal { struct CodeDesc; class Code; class Histogram; namespace wasm { class NativeModule; class WasmCodeManager; struct WasmModule; // Convenience macro listing all wasm runtime stubs. Note that the first few // elements of the list coincide with {compiler::TrapId}, order matters. #define WASM_RUNTIME_STUB_LIST(V, VTRAP) \ FOREACH_WASM_TRAPREASON(VTRAP) \ V(WasmAllocateHeapNumber) \ V(WasmArgumentsAdaptor) \ V(WasmCallJavaScript) \ V(WasmStackGuard) \ V(WasmToNumber) \ V(DoubleToI) struct AddressRange { Address start; Address end; AddressRange(Address s, Address e) : start(s), end(e) { DCHECK_LE(start, end); DCHECK_IMPLIES(start == kNullAddress, end == kNullAddress); } AddressRange() : AddressRange(kNullAddress, kNullAddress) {} size_t size() const { return static_cast<size_t>(end - start); } bool is_empty() const { return start == end; } operator bool() const { return start == kNullAddress; } }; // Sorted, disjoint and non-overlapping memory ranges. A range is of the // form [start, end). So there's no [start, end), [end, other_end), // because that should have been reduced to [start, other_end). class V8_EXPORT_PRIVATE DisjointAllocationPool final { public: DisjointAllocationPool() = default; explicit DisjointAllocationPool(AddressRange range) : ranges_({range}) {} DisjointAllocationPool(DisjointAllocationPool&& other) = default; DisjointAllocationPool& operator=(DisjointAllocationPool&& other) = default; // Merge the parameter range into this object while preserving ordering of the // ranges. The assumption is that the passed parameter is not intersecting // this object - for example, it was obtained from a previous Allocate. void Merge(AddressRange); // Allocate a contiguous range of size {size}. Return an empty pool on // failure. AddressRange Allocate(size_t size); bool IsEmpty() const { return ranges_.empty(); } const std::list<AddressRange>& ranges() const { return ranges_; } private: std::list<AddressRange> ranges_; DISALLOW_COPY_AND_ASSIGN(DisjointAllocationPool) }; using ProtectedInstructions = std::vector<trap_handler::ProtectedInstructionData>; class V8_EXPORT_PRIVATE WasmCode final { public: enum Kind { kFunction, kWasmToJsWrapper, kLazyStub, kRuntimeStub, kInterpreterEntry, kJumpTable }; // Each runtime stub is identified by an id. This id is used to reference the // stub via {RelocInfo::WASM_STUB_CALL} and gets resolved during relocation. enum RuntimeStubId { #define DEF_ENUM(Name) k##Name, #define DEF_ENUM_TRAP(Name) kThrowWasm##Name, WASM_RUNTIME_STUB_LIST(DEF_ENUM, DEF_ENUM_TRAP) #undef DEF_ENUM_TRAP #undef DEF_ENUM kRuntimeStubCount }; // kOther is used if we have WasmCode that is neither // liftoff- nor turbofan-compiled, i.e. if Kind is // not a kFunction. enum Tier : int8_t { kLiftoff, kTurbofan, kOther }; Vector<byte> instructions() const { return instructions_; } Address instruction_start() const { return reinterpret_cast<Address>(instructions_.start()); } Vector<const byte> reloc_info() const { return {reloc_info_.get(), reloc_size_}; } Vector<const byte> source_positions() const { return {source_position_table_.get(), source_position_size_}; } uint32_t index() const { return index_.ToChecked(); } // Anonymous functions are functions that don't carry an index. bool IsAnonymous() const { return index_.IsNothing(); } Kind kind() const { return kind_; } NativeModule* native_module() const { return native_module_; } Tier tier() const { return tier_; } Address constant_pool() const; size_t constant_pool_offset() const { return constant_pool_offset_; } size_t safepoint_table_offset() const { return safepoint_table_offset_; } size_t handler_table_offset() const { return handler_table_offset_; } uint32_t stack_slots() const { return stack_slots_; } bool is_liftoff() const { return tier_ == kLiftoff; } bool contains(Address pc) const { return reinterpret_cast<Address>(instructions_.start()) <= pc && pc < reinterpret_cast<Address>(instructions_.end()); } const ProtectedInstructions& protected_instructions() const { // TODO(mstarzinger): Code that doesn't have trapping instruction should // not be required to have this vector, make it possible to be null. DCHECK_NOT_NULL(protected_instructions_); return *protected_instructions_.get(); } void Validate() const; void Print(Isolate* isolate) const; void Disassemble(const char* name, Isolate* isolate, std::ostream& os, Address current_pc = kNullAddress) const; static bool ShouldBeLogged(Isolate* isolate); void LogCode(Isolate* isolate) const; ~WasmCode(); enum FlushICache : bool { kFlushICache = true, kNoFlushICache = false }; // Offset of {instructions_.start()}. It is used for tiering, when // we check if optimized code is available during the prologue // of Liftoff-compiled code. static constexpr int kInstructionStartOffset = 0; private: friend class NativeModule; WasmCode(Vector<byte> instructions, std::unique_ptr<const byte[]> reloc_info, size_t reloc_size, std::unique_ptr<const byte[]> source_pos, size_t source_pos_size, NativeModule* native_module, Maybe<uint32_t> index, Kind kind, size_t constant_pool_offset, uint32_t stack_slots, size_t safepoint_table_offset, size_t handler_table_offset, std::unique_ptr<ProtectedInstructions> protected_instructions, Tier tier) : instructions_(instructions), reloc_info_(std::move(reloc_info)), reloc_size_(reloc_size), source_position_table_(std::move(source_pos)), source_position_size_(source_pos_size), native_module_(native_module), index_(index), kind_(kind), constant_pool_offset_(constant_pool_offset), stack_slots_(stack_slots), safepoint_table_offset_(safepoint_table_offset), handler_table_offset_(handler_table_offset), protected_instructions_(std::move(protected_instructions)), tier_(tier) { DCHECK_LE(safepoint_table_offset, instructions.size()); DCHECK_LE(constant_pool_offset, instructions.size()); DCHECK_LE(handler_table_offset, instructions.size()); DCHECK_EQ(kInstructionStartOffset, OFFSET_OF(WasmCode, instructions_)); } // Code objects that have been registered with the global trap handler within // this process, will have a {trap_handler_index} associated with them. size_t trap_handler_index() const; void set_trap_handler_index(size_t); bool HasTrapHandlerIndex() const; // Register protected instruction information with the trap handler. Sets // trap_handler_index. void RegisterTrapHandlerData(); Vector<byte> instructions_; std::unique_ptr<const byte[]> reloc_info_; size_t reloc_size_ = 0; std::unique_ptr<const byte[]> source_position_table_; size_t source_position_size_ = 0; NativeModule* native_module_ = nullptr; Maybe<uint32_t> index_; Kind kind_; size_t constant_pool_offset_ = 0; uint32_t stack_slots_ = 0; // we care about safepoint data for wasm-to-js functions, // since there may be stack/register tagged values for large number // conversions. size_t safepoint_table_offset_ = 0; size_t handler_table_offset_ = 0; intptr_t trap_handler_index_ = -1; std::unique_ptr<ProtectedInstructions> protected_instructions_; Tier tier_; DISALLOW_COPY_AND_ASSIGN(WasmCode); }; // Return a textual description of the kind. const char* GetWasmCodeKindAsString(WasmCode::Kind); class V8_EXPORT_PRIVATE NativeModule final { public: WasmCode* AddCode(const CodeDesc& desc, uint32_t frame_count, uint32_t index, size_t safepoint_table_offset, size_t handler_table_offset, std::unique_ptr<ProtectedInstructions>, Handle<ByteArray> source_position_table, WasmCode::Tier tier); // A way to copy over JS-allocated code. This is because we compile // certain wrappers using a different pipeline. WasmCode* AddCodeCopy(Handle<Code> code, WasmCode::Kind kind, uint32_t index); // Add an interpreter entry. For the same reason as AddCodeCopy, we // currently compile these using a different pipeline and we can't get a // CodeDesc here. When adding interpreter wrappers, we do not insert them in // the code_table, however, we let them self-identify as the {index} function WasmCode* AddInterpreterEntry(Handle<Code> code, uint32_t index); // When starting lazy compilation, provide the WasmLazyCompile builtin by // calling SetLazyBuiltin. It will be copied into this NativeModule and the // jump table will be populated with that copy. void SetLazyBuiltin(Handle<Code> code); // Initializes all runtime stubs by copying them over from the JS-allocated // heap into this native module. It must be called exactly once per native // module before adding other WasmCode so that runtime stub ids can be // resolved during relocation. void SetRuntimeStubs(Isolate* isolate); WasmCode* code(uint32_t index) const { DCHECK_LT(index, num_functions_); DCHECK_LE(num_imported_functions_, index); return code_table_[index - num_imported_functions_]; } bool has_code(uint32_t index) const { DCHECK_LT(index, num_functions_); DCHECK_LE(num_imported_functions_, index); return code_table_[index - num_imported_functions_] != nullptr; } WasmCode* runtime_stub(WasmCode::RuntimeStubId index) const { DCHECK_LT(index, WasmCode::kRuntimeStubCount); WasmCode* code = runtime_stub_table_[index]; DCHECK_NOT_NULL(code); return code; } bool is_jump_table_slot(Address address) const { return jump_table_->contains(address); } uint32_t GetFunctionIndexFromJumpTableSlot(Address slot_address); // Transition this module from code relying on trap handlers (i.e. without // explicit memory bounds checks) to code that does not require trap handlers // (i.e. code with explicit bounds checks). // This method must only be called if {use_trap_handler()} is true (it will be // false afterwards). All code in this {NativeModule} needs to be re-added // after calling this method. void DisableTrapHandler(); // Returns the target to call for the given function (returns a jump table // slot within {jump_table_}). Address GetCallTargetForFunction(uint32_t func_index) const; bool SetExecutable(bool executable); // For cctests, where we build both WasmModule and the runtime objects // on the fly, and bypass the instance builder pipeline. void ReserveCodeTableForTesting(uint32_t max_functions); void SetNumFunctionsForTesting(uint32_t num_functions); void SetCodeForTesting(uint32_t index, WasmCode* code); void LogWasmCodes(Isolate* isolate); CompilationState* compilation_state() { return compilation_state_.get(); } // TODO(mstarzinger): The link to the {WasmModuleObject} is deprecated and // all uses should vanish to make {NativeModule} independent of the Isolate. WasmModuleObject* module_object() const; void SetModuleObject(Handle<WasmModuleObject>); uint32_t num_functions() const { return num_functions_; } uint32_t num_imported_functions() const { return num_imported_functions_; } Vector<WasmCode*> code_table() const { return {code_table_.get(), num_functions_ - num_imported_functions_}; } bool use_trap_handler() const { return use_trap_handler_; } void set_lazy_compile_frozen(bool frozen) { lazy_compile_frozen_ = frozen; } bool lazy_compile_frozen() const { return lazy_compile_frozen_; } WasmCode* Lookup(Address) const; const size_t instance_id = 0; ~NativeModule(); private: friend class WasmCode; friend class WasmCodeManager; friend class NativeModuleSerializer; friend class NativeModuleDeserializer; friend class NativeModuleModificationScope; static base::AtomicNumber<size_t> next_id_; NativeModule(Isolate* isolate, uint32_t num_functions, uint32_t num_imported_functions, bool can_request_more, VirtualMemory* code_space, WasmCodeManager* code_manager, ModuleEnv& env); WasmCode* AddAnonymousCode(Handle<Code>, WasmCode::Kind kind); Address AllocateForCode(size_t size); // Primitive for adding code to the native module. All code added to a native // module is owned by that module. Various callers get to decide on how the // code is obtained (CodeDesc vs, as a point in time, Code*), the kind, // whether it has an index or is anonymous, etc. WasmCode* AddOwnedCode(Vector<const byte> orig_instructions, std::unique_ptr<const byte[]> reloc_info, size_t reloc_size, std::unique_ptr<const byte[]> source_pos, size_t source_pos_size, Maybe<uint32_t> index, WasmCode::Kind kind, size_t constant_pool_offset, uint32_t stack_slots, size_t safepoint_table_offset, size_t handler_table_offset, std::unique_ptr<ProtectedInstructions>, WasmCode::Tier, WasmCode::FlushICache); WasmCode* CreateEmptyJumpTable(uint32_t num_wasm_functions); void PatchJumpTable(uint32_t func_index, Address target, WasmCode::FlushICache); void set_code(uint32_t index, WasmCode* code) { DCHECK_LT(index, num_functions_); DCHECK_LE(num_imported_functions_, index); DCHECK_EQ(code->index(), index); code_table_[index - num_imported_functions_] = code; } // Holds all allocated code objects, is maintained to be in ascending order // according to the codes instruction start address to allow lookups. std::vector<std::unique_ptr<WasmCode>> owned_code_; uint32_t num_functions_; uint32_t num_imported_functions_; std::unique_ptr<WasmCode* []> code_table_; WasmCode* runtime_stub_table_[WasmCode::kRuntimeStubCount] = {nullptr}; // Jump table used to easily redirect wasm function calls. WasmCode* jump_table_ = nullptr; std::unique_ptr<CompilationState, CompilationStateDeleter> compilation_state_; // A phantom reference to the {WasmModuleObject}. It is intentionally not // typed {Handle<WasmModuleObject>} because this location will be cleared // when the phantom reference is cleared. WasmModuleObject** module_object_ = nullptr; DisjointAllocationPool free_code_space_; DisjointAllocationPool allocated_code_space_; std::list<VirtualMemory> owned_code_space_; WasmCodeManager* wasm_code_manager_; base::Mutex allocation_mutex_; size_t committed_code_space_ = 0; int modification_scope_depth_ = 0; bool can_request_more_memory_; bool use_trap_handler_ = false; bool is_executable_ = false; bool lazy_compile_frozen_ = false; DISALLOW_COPY_AND_ASSIGN(NativeModule); }; class V8_EXPORT_PRIVATE WasmCodeManager final { public: explicit WasmCodeManager(size_t max_committed); // Create a new NativeModule. The caller is responsible for its // lifetime. The native module will be given some memory for code, // which will be page size aligned. The size of the initial memory // is determined with a heuristic based on the total size of wasm // code. The native module may later request more memory. // TODO(titzer): isolate is only required here for CompilationState. std::unique_ptr<NativeModule> NewNativeModule(Isolate* isolate, ModuleEnv& env); // TODO(titzer): isolate is only required here for CompilationState. std::unique_ptr<NativeModule> NewNativeModule( Isolate* isolate, size_t memory_estimate, uint32_t num_functions, uint32_t num_imported_functions, bool can_request_more, ModuleEnv& env); NativeModule* LookupNativeModule(Address pc) const; WasmCode* LookupCode(Address pc) const; WasmCode* GetCodeFromStartAddress(Address pc) const; size_t remaining_uncommitted_code_space() const; void SetModuleCodeSizeHistogram(Histogram* histogram) { module_code_size_mb_ = histogram; } static size_t EstimateNativeModuleSize(const WasmModule* module); private: friend class NativeModule; void TryAllocate(size_t size, VirtualMemory*, void* hint = nullptr); bool Commit(Address, size_t); // Currently, we uncommit a whole module, so all we need is account // for the freed memory size. We do that in FreeNativeModule. // There's no separate Uncommit. void FreeNativeModule(NativeModule*); void Free(VirtualMemory* mem); void AssignRanges(Address start, Address end, NativeModule*); std::map<Address, std::pair<Address, NativeModule*>> lookup_map_; // Count of NativeModules not yet collected. Helps determine if it's // worth requesting a GC on memory pressure. size_t active_ = 0; std::atomic<size_t> remaining_uncommitted_code_space_; // Histogram to update with the maximum used code space for each NativeModule. Histogram* module_code_size_mb_ = nullptr; DISALLOW_COPY_AND_ASSIGN(WasmCodeManager); }; // Within the scope, the native_module is writable and not executable. // At the scope's destruction, the native_module is executable and not writable. // The states inside the scope and at the scope termination are irrespective of // native_module's state when entering the scope. // We currently mark the entire module's memory W^X: // - for AOT, that's as efficient as it can be. // - for Lazy, we don't have a heuristic for functions that may need patching, // and even if we did, the resulting set of pages may be fragmented. // Currently, we try and keep the number of syscalls low. // - similar argument for debug time. class NativeModuleModificationScope final { public: explicit NativeModuleModificationScope(NativeModule* native_module); ~NativeModuleModificationScope(); private: NativeModule* native_module_; }; } // namespace wasm } // namespace internal } // namespace v8 #endif // V8_WASM_WASM_CODE_MANAGER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1ff456cbb01d4d61f9348e77a2fc24db44813b90
2b50de87c37b19c1af88005a8f6407ac2a048920
/src/DuinoComm.cpp
dc231d7f2f106d6b0cff8356d6e9b6fff00da438
[]
no_license
Saint-Francis-Robotics-Team2367/Duino-Comm
dd55234f2ac727d946c4044f4a3d4c0f76edf7e4
46ee439cf31cd8d931c6d8009ef9c9cd7c682f1d
refs/heads/master
2016-08-12T13:31:20.977189
2016-02-20T19:53:30
2016-02-20T19:53:30
51,672,982
0
0
null
null
null
null
UTF-8
C++
false
false
1,117
cpp
/* * DuinoComm.cpp * * Created on: Feb 10, 2016 * Author: Harvey Dent */ #include <DuinoComm.h> DuinoComm::DuinoComm(int id, DriverStation *ds) { this->id = id; this->i2cComm = new I2C(I2C::kMXP, id); this->ds = ds; } DuinoComm::~DuinoComm() { // TODO Auto-generated destructor stub } void DuinoComm::write(char* msg) { this->i2cComm->WriteBulk((unsigned char*) msg, strlen(msg)); } std::string DuinoComm::read() { unsigned char msg[MAX_READ]; memset(msg, 0, MAX_READ); this->i2cComm->Read(id, MAX_READ, msg); DriverStation::ReportWarning((char*) msg); return std::string((char*) msg); } void DuinoComm::updateStatus() { char msg[8]; sprintf(msg, "B%.2f", ds->GetBatteryVoltage()); this->write(msg); memset(msg, 0, 8); msg[0] = 'C'; if (ds->IsDSAttached()) { strcat(msg, "DS"); if (ds->IsFMSAttached()) strcat(msg, "+FMS"); } else strcat(msg, "D/C"); this->write(msg); } int DuinoComm::getAutoMode() { std::string str = this->read(); if((str[0] - '0')>=0 && (str[0] - '0')<=9) return str[0] - '0'; else return -1; }
[ "daniel.d.j.grau@gmail.com" ]
daniel.d.j.grau@gmail.com
986efd5670e5185ae22dff2892736a5f7e9cf923
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chromeos/services/device_sync/proto/cryptauth_v2_test_util.cc
c80058363bc77fdd8710e7938184116a20526385
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
6,873
cc
// Copyright 2019 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 "chromeos/services/device_sync/proto/cryptauth_v2_test_util.h" #include "base/no_destructor.h" #include "base/strings/string_number_conversions.h" #include "chromeos/services/device_sync/public/cpp/gcm_constants.h" namespace cryptauthv2 { const char kTestDeviceSyncGroupName[] = "device_sync_group_name"; const char kTestGcmRegistrationId[] = "gcm_registraion_id"; const char kTestInstanceId[] = "instance_id"; const char kTestInstanceIdToken[] = "instance_id_token"; const char kTestLongDeviceId[] = "long_device_id"; const char kTestNoPiiDeviceName[] = "no_pii_device_name"; const char kTestUserPublicKey[] = "user_public_key"; // Attributes of test ClientDirective. const int32_t kTestClientDirectiveRetryAttempts = 3; const int64_t kTestClientDirectiveCheckinDelayMillis = 2592000000; // 30 days const int64_t kTestClientDirectivePolicyReferenceVersion = 2; const int64_t kTestClientDirectiveRetryPeriodMillis = 43200000; // 12 hours const int64_t kTestClientDirectiveCreateTimeMillis = 1566073800000; const char kTestClientDirectivePolicyReferenceName[] = "client_directive_policy_reference_name"; ClientMetadata BuildClientMetadata( int32_t retry_count, const ClientMetadata::InvocationReason& invocation_reason, const base::Optional<std::string>& session_id) { ClientMetadata client_metadata; client_metadata.set_retry_count(retry_count); client_metadata.set_invocation_reason(invocation_reason); if (session_id) client_metadata.set_session_id(*session_id); return client_metadata; } PolicyReference BuildPolicyReference(const std::string& name, int64_t version) { PolicyReference policy_reference; policy_reference.set_name(name); policy_reference.set_version(version); return policy_reference; } KeyDirective BuildKeyDirective(const PolicyReference& policy_reference, int64_t enroll_time_millis) { KeyDirective key_directive; key_directive.mutable_policy_reference()->CopyFrom(policy_reference); key_directive.set_enroll_time_millis(enroll_time_millis); return key_directive; } RequestContext BuildRequestContext(const std::string& group, const ClientMetadata& client_metadata, const std::string& device_id, const std::string& device_id_token) { RequestContext request_context; request_context.set_group(group); request_context.mutable_client_metadata()->CopyFrom(client_metadata); request_context.set_device_id(device_id); request_context.set_device_id_token(device_id_token); return request_context; } DeviceFeatureStatus BuildDeviceFeatureStatus( const std::string& device_id, const std::vector<std::pair<std::string /* feature_type */, bool /* enabled */>>& feature_statuses) { DeviceFeatureStatus device_feature_status; device_feature_status.set_device_id(device_id); for (const auto& feature_status : feature_statuses) { DeviceFeatureStatus::FeatureStatus* fs = device_feature_status.add_feature_statuses(); fs->set_feature_type(feature_status.first); fs->set_enabled(feature_status.second); } return device_feature_status; } BeaconSeed BuildBeaconSeedForTest(int64_t start_time_millis, int64_t end_time_millis) { BeaconSeed seed; seed.set_data("start_" + base::NumberToString(start_time_millis) + "_end_" + base::NumberToString(end_time_millis)); seed.set_start_time_millis(start_time_millis); seed.set_end_time_millis(end_time_millis); return seed; } const ClientAppMetadata& GetClientAppMetadataForTest() { static const base::NoDestructor<ClientAppMetadata> metadata([] { ApplicationSpecificMetadata app_specific_metadata; app_specific_metadata.set_gcm_registration_id(kTestGcmRegistrationId); app_specific_metadata.set_device_software_package( chromeos::device_sync::kCryptAuthGcmAppId); BetterTogetherFeatureMetadata beto_metadata; beto_metadata.add_supported_features( BetterTogetherFeatureMetadata::BETTER_TOGETHER_CLIENT); beto_metadata.add_supported_features( BetterTogetherFeatureMetadata::SMS_CONNECT_CLIENT); FeatureMetadata feature_metadata; feature_metadata.set_feature_type(FeatureMetadata::BETTER_TOGETHER); feature_metadata.set_metadata(beto_metadata.SerializeAsString()); ClientAppMetadata metadata; metadata.add_application_specific_metadata()->CopyFrom( app_specific_metadata); metadata.set_instance_id(kTestInstanceId); metadata.set_instance_id_token(kTestInstanceIdToken); metadata.set_long_device_id(kTestLongDeviceId); metadata.add_feature_metadata()->CopyFrom(feature_metadata); return metadata; }()); return *metadata; } const ClientDirective& GetClientDirectiveForTest() { static const base::NoDestructor<ClientDirective> client_directive([] { ClientDirective client_directive; client_directive.mutable_policy_reference()->CopyFrom( BuildPolicyReference(kTestClientDirectivePolicyReferenceName, kTestClientDirectivePolicyReferenceVersion)); client_directive.set_checkin_delay_millis( kTestClientDirectiveCheckinDelayMillis); client_directive.set_retry_attempts(kTestClientDirectiveRetryAttempts); client_directive.set_retry_period_millis( kTestClientDirectiveRetryPeriodMillis); client_directive.set_create_time_millis( kTestClientDirectiveCreateTimeMillis); return client_directive; }()); return *client_directive; } const RequestContext& GetRequestContextForTest() { static const base::NoDestructor<RequestContext> request_context([] { return BuildRequestContext( kTestDeviceSyncGroupName, BuildClientMetadata(0 /* retry_count */, ClientMetadata::MANUAL), kTestInstanceId, kTestInstanceIdToken); }()); return *request_context; } const BetterTogetherDeviceMetadata& GetBetterTogetherDeviceMetadataForTest() { static const base::NoDestructor<BetterTogetherDeviceMetadata> better_together_device_metadata([] { BetterTogetherDeviceMetadata metadata; metadata.set_public_key(kTestUserPublicKey); metadata.set_no_pii_device_name(kTestNoPiiDeviceName); metadata.add_beacon_seeds()->CopyFrom(BuildBeaconSeedForTest( 100 /* start_time_millis */, 200 /* end_time_millis */)); metadata.add_beacon_seeds()->CopyFrom(BuildBeaconSeedForTest( 200 /* start_time_millis */, 300 /* end_time_millis */)); return metadata; }()); return *better_together_device_metadata; } } // namespace cryptauthv2
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
ea4de04882885d82f29fc7b52cc87247503301ac
4e0a2e6e8136b54995594b43b2a71d75614a52bf
/AfterACM/POJ/[greedy-hard]1659.cpp
dcbe41b30adb364e9d76003dd1b5bfc8808276de
[]
no_license
AlbertWang0116/KrwlngsACMFile
884c84ba0afff0727448fc5b5b27b5cb76330936
23f0d9f6834f2b4fb2604ecbd50d5c41dd994b8f
refs/heads/master
2023-06-21T09:25:28.528059
2023-06-11T19:18:40
2023-06-11T19:18:40
2,345,592
1
2
null
null
null
null
UTF-8
C++
false
false
863
cpp
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<ctime> #include<cmath> #include<algorithm> #include<map> #include<string> using namespace std; #define N 110 int a[N], e[N][N], seq[N]; int n; int cmp(const int &i, const int &j) { return a[i]>a[j]; } void conduct() { int i, j; memset(e, 0, sizeof(e)); scanf("%d", &n); for (i=0; i<n; ++i) scanf("%d", &a[i]); for (i=0; i<n; ++i) seq[i]=i; for (i=0; i<n; ++i) { sort(seq+i, seq+n, cmp); for (j=i+1; j<n&&a[seq[j]]&&a[seq[i]]; ++j) { e[seq[i]][seq[j]]=e[seq[j]][seq[i]]=1; a[seq[i]]--; a[seq[j]]--; } if (a[seq[i]]) { printf("NO\n"); return; } } printf("YES\n"); for (i=0; i<n; ++i) { for (j=0; j<n; ++j) printf("%d ", e[i][j]); printf("\n"); } } int main() { int time; scanf("%d", &time); while (time--) { conduct(); if (time) printf("\n"); } return 0; }
[ "st.krwlng@gmail.com" ]
st.krwlng@gmail.com
75ae3124ea6084d2265515a4184f25bf7c0140d6
bb7645bab64acc5bc93429a6cdf43e1638237980
/Official Windows Platform Sample/Windows 8 app samples/[C++]-Windows 8 app samples/C++/Windows 8 app samples/DirectX marble maze game sample (Windows 8)/C++/SDKMesh.cpp
4535679e7527e17dfa9ee2a80c35432f50935417
[ "MIT" ]
permissive
Violet26/msdn-code-gallery-microsoft
3b1d9cfb494dc06b0bd3d509b6b4762eae2e2312
df0f5129fa839a6de8f0f7f7397a8b290c60ffbb
refs/heads/master
2020-12-02T02:00:48.716941
2020-01-05T22:39:02
2020-01-05T22:39:02
230,851,047
1
0
MIT
2019-12-30T05:06:00
2019-12-30T05:05:59
null
UTF-8
C++
false
false
36,924
cpp
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved // // The SDK Mesh format (.sdkmesh) is not a recommended file format for production games. // It was designed to meet the specific needs of the SDK samples. Any real-world // applications should avoid this file format in favor of a destination format that // meets the specific needs of the application. // #include "pch.h" using namespace DirectX; #include "DDSTextureLoader.h" #include "SDKMesh.h" #include "BasicLoader.h" void SDKMesh::LoadMaterials(ID3D11Device* d3dDevice, _In_reads_(numMaterials) SDKMESH_MATERIAL* materials, uint32 numMaterials) { BasicLoader^ loader = ref new BasicLoader(d3dDevice); wchar_t path[MAX_PATH]; wchar_t texturePath[MAX_PATH]; size_t convertedChars = 0; // This is a simple Mesh format that doesn't reuse texture data for (uint32 m = 0; m < numMaterials; m++) { materials[m].DiffuseTexture = nullptr; materials[m].NormalTexture = nullptr; materials[m].SpecularTexture = nullptr; materials[m].DiffuseRV = nullptr; materials[m].NormalRV = nullptr; materials[m].SpecularRV = nullptr; // load textures if (materials[m].DiffuseTextureName[0] != 0) { size_t size = strlen(materials[m].DiffuseTextureName) + 1; mbstowcs_s(&convertedChars, texturePath, size, materials[m].DiffuseTextureName, _TRUNCATE); swprintf_s(path, MAX_PATH, L"Media\\Textures\\%s", texturePath); loader->LoadTexture(ref new Platform::String(path), nullptr, &materials[m].DiffuseRV); } } } HRESULT SDKMesh::CreateVertexBuffer(ID3D11Device* d3dDevice, SDKMESH_VERTEX_BUFFER_HEADER* header, void* vertices) { HRESULT hr = S_OK; header->DataOffset = 0; // Vertex Buffer D3D11_BUFFER_DESC bufferDesc; bufferDesc.ByteWidth = static_cast<uint32>(header->SizeBytes); bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA initData; initData.pSysMem = vertices; hr = d3dDevice->CreateBuffer(&bufferDesc, &initData, &header->VertexBuffer); return hr; } HRESULT SDKMesh::CreateIndexBuffer(ID3D11Device* d3dDevice, SDKMESH_INDEX_BUFFER_HEADER* header, void* indices) { HRESULT hr = S_OK; header->DataOffset = 0; // Index Buffer D3D11_BUFFER_DESC bufferDesc; bufferDesc.ByteWidth = static_cast<uint32>(header->SizeBytes); bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA initData; initData.pSysMem = indices; hr = d3dDevice->CreateBuffer(&bufferDesc, &initData, &header->IndexBuffer); return hr; } HRESULT SDKMesh::CreateFromFile(ID3D11Device* d3dDevice, WCHAR* filename, bool createAdjacencyIndices) { HRESULT hr = S_OK; m_hFile = CreateFile2(filename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); if (INVALID_HANDLE_VALUE == m_hFile) { DWORD errorCode = GetLastError(); const int msgSize = 512; WCHAR message[msgSize]; DWORD result = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), message, msgSize, nullptr ); if ((result > 0) && (result < msgSize)) { OutputDebugString(message); } return E_FAIL; } // Store the directory path without the filename wcsncpy_s(m_path, MAX_PATH, filename, wcslen(filename)); WCHAR* lastBSlash = wcsrchr(m_path, L'\\'); if (lastBSlash) { *(lastBSlash + 1) = L'\0'; } else { *m_path = L'\0'; } // Get the file size FILE_STANDARD_INFO fileInfo = {0}; if (!GetFileInformationByHandleEx(m_hFile, FileStandardInfo, &fileInfo, sizeof(fileInfo))) { throw ref new Platform::FailureException(); } if (fileInfo.EndOfFile.HighPart != 0) { throw ref new Platform::OutOfMemoryException(); } uint32 byteCount = fileInfo.EndOfFile.LowPart; // Allocate memory m_staticMeshData = new byte[byteCount]; if (!m_staticMeshData) { CloseHandle(m_hFile); return E_OUTOFMEMORY; } // Read in the file DWORD bytesRead; if (!ReadFile(m_hFile, m_staticMeshData, byteCount, &bytesRead, nullptr)) { hr = E_FAIL; } CloseHandle(m_hFile); if (SUCCEEDED(hr)) { hr = CreateFromMemory(d3dDevice, m_staticMeshData, byteCount, createAdjacencyIndices, false); if (FAILED(hr)) { delete[] m_staticMeshData; } } return hr; } HRESULT SDKMesh::CreateFromMemory(ID3D11Device* d3dDevice, byte* data, uint32 byteCount, bool createAdjacencyIndices, bool copyStatic) { HRESULT hr = E_FAIL; XMFLOAT3 lower; XMFLOAT3 upper; m_d3dDevice = d3dDevice; m_numOutstandingResources = 0; if (copyStatic) { SDKMESH_HEADER* header = (SDKMESH_HEADER*)data; size_t staticSize = static_cast<size_t>(header->HeaderSize + header->NonBufferDataSize); m_heapData = new BYTE[staticSize]; if (m_heapData == nullptr) { return hr; } m_staticMeshData = m_heapData; CopyMemory(m_staticMeshData, data, staticSize); } else { m_heapData = data; m_staticMeshData = data; } // Pointer fixup m_meshHeader = (SDKMESH_HEADER*)m_staticMeshData; m_vertexBufferArray = (SDKMESH_VERTEX_BUFFER_HEADER*)(m_staticMeshData + m_meshHeader->VertexStreamHeadersOffset); m_indexBufferArray = (SDKMESH_INDEX_BUFFER_HEADER*)(m_staticMeshData + m_meshHeader->IndexStreamHeadersOffset); m_meshArray = (SDKMESH_MESH*)(m_staticMeshData + m_meshHeader->MeshDataOffset); m_subsetArray = (SDKMESH_SUBSET*)(m_staticMeshData + m_meshHeader->SubsetDataOffset); m_frameArray = (SDKMESH_FRAME*)(m_staticMeshData + m_meshHeader->FrameDataOffset); m_materialArray = (SDKMESH_MATERIAL*)(m_staticMeshData + m_meshHeader->MaterialDataOffset); // Setup subsets for (uint32 i = 0; i < m_meshHeader->NumMeshes; i++) { m_meshArray[i].Subsets = (uint32*)(m_staticMeshData + m_meshArray[i].SubsetOffset); m_meshArray[i].FrameInfluences = (uint32*)(m_staticMeshData + m_meshArray[i].FrameInfluenceOffset); } // error condition if (m_meshHeader->Version != SDKMESH_FILE_VERSION) { hr = E_NOINTERFACE; goto Error; } // Setup buffer data pointer byte* bufferData = data + m_meshHeader->HeaderSize + m_meshHeader->NonBufferDataSize; // Get the start of the buffer data uint64 bufferDataStart = m_meshHeader->HeaderSize + m_meshHeader->NonBufferDataSize; // Create vertex buffers m_vertices = new byte*[m_meshHeader->NumVertexBuffers]; for (uint32 i = 0; i < m_meshHeader->NumVertexBuffers; i++) { byte* vertices = nullptr; vertices = (byte*)(bufferData + (m_vertexBufferArray[i].DataOffset - bufferDataStart)); CreateVertexBuffer(d3dDevice, &m_vertexBufferArray[i], vertices); m_vertices[i] = vertices; } // Create index buffers m_indices = new byte*[m_meshHeader->NumIndexBuffers]; for (uint32 i = 0; i < m_meshHeader->NumIndexBuffers; i++) { byte* indices = nullptr; indices = (byte*)(bufferData + (m_indexBufferArray[i].DataOffset - bufferDataStart)); CreateIndexBuffer(d3dDevice, &m_indexBufferArray[i], indices); m_indices[i] = indices; } // Load Materials if (d3dDevice) { LoadMaterials(d3dDevice, m_materialArray, m_meshHeader->NumMaterials); } // Create a place to store our bind pose frame matrices m_bindPoseFrameMatrices = new XMMATRIX[m_meshHeader->NumFrames]; if (!m_bindPoseFrameMatrices) { goto Error; } // Create a place to store our transformed frame matrices m_transformedFrameMatrices = new XMMATRIX[m_meshHeader->NumFrames]; if (!m_transformedFrameMatrices) { goto Error; } m_worldPoseFrameMatrices = new XMMATRIX[m_meshHeader->NumFrames]; if (!m_worldPoseFrameMatrices) { goto Error; } SDKMESH_SUBSET* subset = nullptr; D3D11_PRIMITIVE_TOPOLOGY primitiveType; // update bounding volume SDKMESH_MESH* currentMesh = &m_meshArray[0]; int tris = 0; for (uint32 mesh = 0; mesh < m_meshHeader->NumMeshes; ++mesh) { lower.x = XMVectorGetX(g_XMFltMax); lower.y = XMVectorGetX(g_XMFltMax); lower.z = XMVectorGetX(g_XMFltMax); upper.x = -XMVectorGetX(g_XMFltMax); upper.y = -XMVectorGetX(g_XMFltMax); upper.z = -XMVectorGetX(g_XMFltMax); currentMesh = GetMesh(mesh); int indsize; if (m_indexBufferArray[currentMesh->IndexBuffer].IndexType == static_cast<uint32>(SDKMeshIndexType::Bits16)) { indsize = 2; } else { indsize = 4; } for (uint32 subsetIndex = 0; subsetIndex < currentMesh->NumSubsets; subsetIndex++) { subset = GetSubset(mesh, subsetIndex); // &m_pSubsetArray[currentMesh->pSubsets[subset]]; primitiveType = GetPrimitiveType(static_cast<SDKMeshPrimitiveType>(subset->PrimitiveType)); assert(primitiveType == D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // only triangle lists are handled. uint32 indexCount = (uint32)subset->IndexCount; uint32 indexStart = (uint32)subset->IndexStart; uint32* ind = (uint32*)m_indices[currentMesh->IndexBuffer]; float* verts = (float*)m_vertices[currentMesh->VertexBuffers[0]]; uint32 stride = (uint32)m_vertexBufferArray[currentMesh->VertexBuffers[0]].StrideBytes; assert (stride % 4 == 0); stride /= 4; for (uint32 vertind = indexStart; vertind < indexStart + indexCount; ++vertind) { uint32 currentIndex = 0; if (indsize == 2) { uint32 ind_div2 = vertind / 2; currentIndex = ind[ind_div2]; if ((vertind % 2) == 0) { currentIndex = currentIndex << 16; currentIndex = currentIndex >> 16; } else { currentIndex = currentIndex >> 16; } } else { currentIndex = ind[vertind]; } tris++; XMFLOAT3* pt = (XMFLOAT3*)&(verts[stride * currentIndex]); if (pt->x < lower.x) { lower.x = pt->x; } if (pt->y < lower.y) { lower.y = pt->y; } if (pt->z < lower.z) { lower.z = pt->z; } if (pt->x > upper.x) { upper.x = pt->x; } if (pt->y > upper.y) { upper.y = pt->y; } if (pt->z > upper.z) { upper.z = pt->z; } } } XMVECTOR u = XMLoadFloat3(&upper); XMVECTOR l = XMLoadFloat3(&lower); XMVECTOR half = XMVectorSubtract(u, l); XMVectorScale(half, 0.5f); XMStoreFloat3(&currentMesh->BoundingBoxExtents, half); half = XMVectorAdd(l, half); XMStoreFloat3(&currentMesh->BoundingBoxCenter, half); } // Update hr = S_OK; Error: return hr; } // Transform bind pose frame using a recursive traversal void SDKMesh::TransformBindPoseFrame(uint32 frame, CXMMATRIX parentWorld) { if (m_bindPoseFrameMatrices == nullptr) { return; } // Transform ourselves XMMATRIX localWorld = XMMatrixMultiply(XMLoadFloat4x4(&m_frameArray[frame].Matrix), parentWorld); m_bindPoseFrameMatrices[frame] = localWorld; // Transform our siblings if (m_frameArray[frame].SiblingFrame != INVALID_FRAME) { TransformBindPoseFrame(m_frameArray[frame].SiblingFrame, parentWorld); } // Transform our children if (m_frameArray[frame].ChildFrame != INVALID_FRAME) { TransformBindPoseFrame(m_frameArray[frame].ChildFrame, localWorld); } } // Transform frame using a recursive traversal void SDKMesh::TransformFrame(uint32 frame, CXMMATRIX parentWorld, double time) { // Get the tick data XMMATRIX localTransform; uint32 tick = GetAnimationKeyFromTime(time); if (INVALID_ANIMATION_DATA != m_frameArray[frame].AnimationDataIndex) { SDKANIMATION_FRAME_DATA* frameData = &m_animationFrameData[m_frameArray[frame].AnimationDataIndex]; SDKANIMATION_DATA* data = &frameData->AnimationData[tick]; // turn it into a matrix (ignore scaling for now) XMMATRIX translate = XMMatrixTranslation(data->Translation.x, data->Translation.y, data->Translation.z); XMVECTOR quatVector; XMMATRIX quatMatrix; if (data->Orientation.w == 0 && data->Orientation.x == 0 && data->Orientation.y == 0 && data->Orientation.z == 0) { quatVector = XMQuaternionIdentity(); } else { quatVector = XMLoadFloat4(&data->Orientation); quatVector = XMVectorSwizzle(quatVector, 3, 0, 1, 2); } quatVector = XMQuaternionNormalize(quatVector); quatMatrix = XMMatrixRotationQuaternion(quatVector); localTransform = (quatMatrix * translate); } else { localTransform = XMLoadFloat4x4(&m_frameArray[frame].Matrix); } // Transform ourselves XMMATRIX localWorld = XMMatrixMultiply(localTransform, parentWorld); m_transformedFrameMatrices[frame] = localWorld; m_worldPoseFrameMatrices[frame] = localWorld; // Transform our siblings if (m_frameArray[frame].SiblingFrame != INVALID_FRAME) { TransformFrame(m_frameArray[frame].SiblingFrame, parentWorld, time); } // Transform our children if (m_frameArray[frame].ChildFrame != INVALID_FRAME) { TransformFrame(m_frameArray[frame].ChildFrame, localWorld, time); } } // Transform frame assuming that it is an absolute transformation void SDKMesh::TransformFrameAbsolute(uint32 frame, double time) { XMMATRIX trans1; XMMATRIX trans2; XMMATRIX rot1; XMMATRIX rot2; XMVECTOR quat1; XMVECTOR quat2; XMMATRIX to; XMMATRIX invTo; XMMATRIX from; uint32 tick = GetAnimationKeyFromTime(time); if (INVALID_ANIMATION_DATA != m_frameArray[frame].AnimationDataIndex) { SDKANIMATION_FRAME_DATA* frameData = &m_animationFrameData[m_frameArray[frame].AnimationDataIndex]; SDKANIMATION_DATA* data = &frameData->AnimationData[tick]; SDKANIMATION_DATA* dataOrig = &frameData->AnimationData[0]; trans1 = XMMatrixTranslation(-dataOrig->Translation.x, -dataOrig->Translation.y, -dataOrig->Translation.z); trans2 = XMMatrixTranslation(data->Translation.x, data->Translation.y, data->Translation.z); quat1 = XMLoadFloat4(&dataOrig->Orientation); quat1 = XMQuaternionInverse(quat1); rot1 = XMMatrixRotationQuaternion(quat1); invTo = trans1 * rot1; quat2 = XMLoadFloat4(&data->Orientation); rot2 = XMMatrixRotationQuaternion(quat2); from = rot2 * trans2; XMMATRIX output = invTo * from; m_transformedFrameMatrices[frame] = output; } } #define MAX_D3D11_VERTEX_STREAMS D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT void SDKMesh::RenderMesh(uint32 meshIndex, bool adjacent, ID3D11DeviceContext* d3dContext, uint32 diffuseSlot, uint32 normalSlot, uint32 specularSlot) { if (0 < GetOutstandingBufferResources()) { return; } SDKMESH_MESH* mesh = &m_meshArray[meshIndex]; uint32 strides[MAX_D3D11_VERTEX_STREAMS]; uint32 offsets[MAX_D3D11_VERTEX_STREAMS]; ID3D11Buffer* vertexBuffer[MAX_D3D11_VERTEX_STREAMS]; ZeroMemory(strides, sizeof(uint32) * MAX_D3D11_VERTEX_STREAMS); ZeroMemory(offsets, sizeof(uint32) * MAX_D3D11_VERTEX_STREAMS); ZeroMemory(vertexBuffer, sizeof(ID3D11Buffer*) * MAX_D3D11_VERTEX_STREAMS); if (mesh->NumVertexBuffers > MAX_D3D11_VERTEX_STREAMS) { return; } for (uint64 i = 0; i < mesh->NumVertexBuffers; i++) { vertexBuffer[i] = m_vertexBufferArray[mesh->VertexBuffers[i]].VertexBuffer; strides[i] = static_cast<uint32>(m_vertexBufferArray[mesh->VertexBuffers[i]].StrideBytes); offsets[i] = 0; } SDKMESH_INDEX_BUFFER_HEADER* indexBufferArray; if (adjacent) { indexBufferArray = m_adjacencyIndexBufferArray; } else { indexBufferArray = m_indexBufferArray; } ID3D11Buffer* indexBuffer = indexBufferArray[mesh->IndexBuffer].IndexBuffer; DXGI_FORMAT indexBufferFormat = DXGI_FORMAT_R16_UINT; switch (indexBufferArray[mesh->IndexBuffer].IndexType) { case SDKMeshIndexType::Bits16: indexBufferFormat = DXGI_FORMAT_R16_UINT; break; case SDKMeshIndexType::Bits32: indexBufferFormat = DXGI_FORMAT_R32_UINT; break; }; d3dContext->IASetVertexBuffers(0, mesh->NumVertexBuffers, vertexBuffer, strides, offsets); d3dContext->IASetIndexBuffer(indexBuffer, indexBufferFormat, 0); SDKMESH_SUBSET* subset = nullptr; SDKMESH_MATERIAL* material = nullptr; D3D11_PRIMITIVE_TOPOLOGY primitiveType; for (uint32 i = 0; i < mesh->NumSubsets; i++) { subset = &m_subsetArray[mesh->Subsets[i]]; primitiveType = GetPrimitiveType(static_cast<SDKMeshPrimitiveType>(subset->PrimitiveType)); if (adjacent) { switch (primitiveType) { case D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST: primitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; break; case D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP: primitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; break; case D3D11_PRIMITIVE_TOPOLOGY_LINELIST: primitiveType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; break; case D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP: primitiveType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; break; } } d3dContext->IASetPrimitiveTopology(primitiveType); material = &m_materialArray[subset->MaterialID]; if (diffuseSlot != INVALID_SAMPLER_SLOT && !IsErrorResource(material->DiffuseRV)) { d3dContext->PSSetShaderResources(diffuseSlot, 1, &material->DiffuseRV); } if (normalSlot != INVALID_SAMPLER_SLOT && !IsErrorResource(material->NormalRV)) { d3dContext->PSSetShaderResources(normalSlot, 1, &material->NormalRV); } if (specularSlot != INVALID_SAMPLER_SLOT && !IsErrorResource(material->SpecularRV)) { d3dContext->PSSetShaderResources(specularSlot, 1, &material->SpecularRV); } uint32 indexCount = (uint32)subset->IndexCount; uint32 indexStart = (uint32)subset->IndexStart; uint32 vertexStart = (uint32)subset->VertexStart; if (adjacent) { indexCount *= 2; indexStart *= 2; } d3dContext->DrawIndexed(indexCount, indexStart, vertexStart); } } void SDKMesh::RenderFrame(uint32 frame, bool adjacent, ID3D11DeviceContext* d3dContext, uint32 diffuseSlot, uint32 normalSlot, uint32 specularSlot) { if (!m_staticMeshData || !m_frameArray) { return; } if (m_frameArray[frame].Mesh != INVALID_MESH) { RenderMesh(m_frameArray[frame].Mesh, adjacent, d3dContext, diffuseSlot, normalSlot, specularSlot); } // Render our children if (m_frameArray[frame].ChildFrame != INVALID_FRAME) { RenderFrame(m_frameArray[frame].ChildFrame, adjacent, d3dContext, diffuseSlot, normalSlot, specularSlot); } // Render our siblings if (m_frameArray[frame].SiblingFrame != INVALID_FRAME) { RenderFrame(m_frameArray[frame].SiblingFrame, adjacent, d3dContext, diffuseSlot, normalSlot, specularSlot); } } SDKMesh::SDKMesh() : m_numOutstandingResources(0), m_loading(false), m_hFile(0), m_hFileMappingObject(0), m_meshHeader(nullptr), m_staticMeshData(nullptr), m_heapData(nullptr), m_adjacencyIndexBufferArray(nullptr), m_animationData(nullptr), m_animationHeader(nullptr), m_vertices(nullptr), m_indices(nullptr), m_bindPoseFrameMatrices(nullptr), m_transformedFrameMatrices(nullptr), m_worldPoseFrameMatrices(nullptr), m_d3dDevice(nullptr) { } SDKMesh::~SDKMesh() { Destroy(); } HRESULT SDKMesh::Create(ID3D11Device* d3dDevice, WCHAR* filename, bool createAdjacencyIndices) { Destroy(); return CreateFromFile(d3dDevice, filename, createAdjacencyIndices); } HRESULT SDKMesh::Create(ID3D11Device* d3dDevice, byte* data, uint32 byteCount, bool createAdjacencyIndices, bool copyStatic) { Destroy(); return CreateFromMemory(d3dDevice, data, byteCount, createAdjacencyIndices, copyStatic); } HRESULT SDKMesh::LoadAnimation(WCHAR* filename) { HRESULT hr = E_FAIL; DWORD bytesRead = 0; LARGE_INTEGER move; HANDLE fileHandle = CreateFile2(filename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); if (INVALID_HANDLE_VALUE == fileHandle) { return E_FAIL; } SDKANIMATION_FILE_HEADER fileHeader; if (!ReadFile(fileHandle, &fileHeader, sizeof(SDKANIMATION_FILE_HEADER), &bytesRead, nullptr)) { goto Error; } SAFE_DELETE_ARRAY(m_animationData); m_animationData = new BYTE[static_cast<size_t>((sizeof(SDKANIMATION_FILE_HEADER) + fileHeader.AnimationDataSize))]; if (m_animationData == nullptr) { hr = E_OUTOFMEMORY; goto Error; } move.QuadPart = 0; if (!SetFilePointerEx(fileHandle, move, nullptr, FILE_BEGIN)) { goto Error; } if (!ReadFile(fileHandle, m_animationData, static_cast<DWORD>(sizeof(SDKANIMATION_FILE_HEADER) + fileHeader.AnimationDataSize), &bytesRead, nullptr)) { goto Error; } // pointer fixup m_animationHeader = (SDKANIMATION_FILE_HEADER*)m_animationData; m_animationFrameData = (SDKANIMATION_FRAME_DATA*)(m_animationData + m_animationHeader->AnimationDataOffset); uint64 baseOffset = sizeof(SDKANIMATION_FILE_HEADER); for (uint32 i = 0; i < m_animationHeader->NumFrames; i++) { m_animationFrameData[i].AnimationData = (SDKANIMATION_DATA*)(m_animationData + m_animationFrameData[i].DataOffset + baseOffset); SDKMESH_FRAME* frame = FindFrame(m_animationFrameData[i].FrameName); if (frame) { frame->AnimationDataIndex = i; } } hr = S_OK; Error: CloseHandle(fileHandle); return hr; } void SDKMesh::Destroy() { if (m_staticMeshData != nullptr) { if (m_materialArray != nullptr) { for (uint64 m = 0; m < m_meshHeader->NumMaterials; m++) { ID3D11Resource* resource = nullptr; if (m_materialArray[m].DiffuseRV && !IsErrorResource(m_materialArray[m].DiffuseRV)) { m_materialArray[m].DiffuseRV->GetResource(&resource); SAFE_RELEASE(resource); SAFE_RELEASE(m_materialArray[m].DiffuseRV); } if (m_materialArray[m].NormalRV && !IsErrorResource(m_materialArray[m].NormalRV)) { m_materialArray[m].NormalRV->GetResource(&resource); SAFE_RELEASE(resource); SAFE_RELEASE(m_materialArray[m].NormalRV); } if (m_materialArray[m].SpecularRV && !IsErrorResource(m_materialArray[m].SpecularRV)) { m_materialArray[m].SpecularRV->GetResource(&resource); SAFE_RELEASE(resource); SAFE_RELEASE(m_materialArray[m].SpecularRV); } } } } if (m_adjacencyIndexBufferArray != nullptr) { for (uint64 i = 0; i < m_meshHeader->NumIndexBuffers; i++) { SAFE_RELEASE(m_adjacencyIndexBufferArray[i].IndexBuffer); } } if (m_indexBufferArray != nullptr) { for (uint64 i = 0; i < m_meshHeader->NumIndexBuffers; i++) { SAFE_RELEASE(m_indexBufferArray[i].IndexBuffer); } } if (m_vertexBufferArray != nullptr) { for (uint64 i = 0; i < m_meshHeader->NumVertexBuffers; i++) { SAFE_RELEASE(m_vertexBufferArray[i].VertexBuffer); } } SAFE_DELETE_ARRAY(m_adjacencyIndexBufferArray); SAFE_DELETE_ARRAY(m_heapData); m_staticMeshData = nullptr; SAFE_DELETE_ARRAY(m_animationData); SAFE_DELETE_ARRAY(m_bindPoseFrameMatrices); SAFE_DELETE_ARRAY(m_transformedFrameMatrices); SAFE_DELETE_ARRAY(m_worldPoseFrameMatrices); SAFE_DELETE_ARRAY(m_vertices); SAFE_DELETE_ARRAY(m_indices); m_meshHeader = nullptr; m_vertexBufferArray = nullptr; m_indexBufferArray = nullptr; m_meshArray = nullptr; m_subsetArray = nullptr; m_frameArray = nullptr; m_materialArray = nullptr; m_animationHeader = nullptr; m_animationFrameData = nullptr; m_d3dDevice = nullptr; } // Transform the bind pose void SDKMesh::TransformBindPose(CXMMATRIX world) { TransformBindPoseFrame(0, world); } // Transform the mesh frames according to the animation for the given time void SDKMesh::TransformMesh(CXMMATRIX world, double time) { if (m_animationHeader == nullptr || FrameTransformType::Relative == static_cast<FrameTransformType>(m_animationHeader->FrameTransformType)) { TransformFrame(0, world, time); // For each frame, move the transform to the bind pose, then // move it to the final position XMMATRIX invBindPose; XMMATRIX final; for (uint32 i = 0; i < m_meshHeader->NumFrames; i++) { XMVECTOR determinant; invBindPose = XMMatrixInverse(&determinant, m_bindPoseFrameMatrices[i]); final = invBindPose * m_transformedFrameMatrices[i]; m_transformedFrameMatrices[i] = final; } } else if (FrameTransformType::Absolute == static_cast<FrameTransformType>(m_animationHeader->FrameTransformType)) { for (uint32 i = 0; i < m_animationHeader->NumFrames; i++) TransformFrameAbsolute(i, time); } } void SDKMesh::Render(ID3D11DeviceContext* d3dContext, uint32 diffuseSlot, uint32 normalSlot, uint32 specularSlot) { RenderFrame(0, false, d3dContext, diffuseSlot, normalSlot, specularSlot); } void SDKMesh::RenderAdjacent(ID3D11DeviceContext* d3dContext, uint32 diffuseSlot, uint32 normalSlot, uint32 specularSlot) { RenderFrame(0, true, d3dContext, diffuseSlot, normalSlot, specularSlot); } D3D11_PRIMITIVE_TOPOLOGY SDKMesh::GetPrimitiveType(SDKMeshPrimitiveType primitiveType) { D3D11_PRIMITIVE_TOPOLOGY returnType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; switch (primitiveType) { case SDKMeshPrimitiveType::TriangleList: returnType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; case SDKMeshPrimitiveType::TriangleStrip: returnType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break; case SDKMeshPrimitiveType::LineList: returnType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST; break; case SDKMeshPrimitiveType::LineStrip: returnType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP; break; case SDKMeshPrimitiveType::PointList: returnType = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; break; case SDKMeshPrimitiveType::TriangleListAdjacent: returnType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; break; case SDKMeshPrimitiveType::TriangleStripAdjacent: returnType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; break; case SDKMeshPrimitiveType::LineListAdjacent: returnType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; break; case SDKMeshPrimitiveType::LineStripAdjacent: returnType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; break; }; return returnType; } DXGI_FORMAT SDKMesh::GetIndexBufferFormat(uint32 mesh) { switch (m_indexBufferArray[m_meshArray[mesh].IndexBuffer].IndexType) { case SDKMeshIndexType::Bits16: return DXGI_FORMAT_R16_UINT; case SDKMeshIndexType::Bits32: return DXGI_FORMAT_R32_UINT; }; return DXGI_FORMAT_R16_UINT; } ID3D11Buffer* SDKMesh::GetVertexBuffer(uint32 mesh, uint32 vertexBuffer) { return m_vertexBufferArray[m_meshArray[mesh].VertexBuffers[vertexBuffer]].VertexBuffer; } ID3D11Buffer* SDKMesh::GetIndexBuffer(uint32 mesh) { return m_indexBufferArray[m_meshArray[mesh].IndexBuffer].IndexBuffer; } SDKMeshIndexType SDKMesh::GetIndexType(uint32 mesh) { return static_cast<SDKMeshIndexType>(m_indexBufferArray[m_meshArray[mesh].IndexBuffer].IndexType); } ID3D11Buffer* SDKMesh::GetAdjacencyIndexBuffer(uint32 mesh) { return m_adjacencyIndexBufferArray[m_meshArray[mesh].IndexBuffer].IndexBuffer; } WCHAR* SDKMesh::GetMeshPath() { return m_path; } uint32 SDKMesh::GetNumMeshes() { if (!m_meshHeader) { return 0; } return m_meshHeader->NumMeshes; } uint32 SDKMesh::GetNumMaterials() { if (!m_meshHeader) { return 0; } return m_meshHeader->NumMaterials; } uint32 SDKMesh::GetNumVertexBuffers() { if (!m_meshHeader) { return 0; } return m_meshHeader->NumVertexBuffers; } uint32 SDKMesh::GetNumIndexBuffers() { if (!m_meshHeader) { return 0; } return m_meshHeader->NumIndexBuffers; } ID3D11Buffer* SDKMesh::GetVertexBufferAt(uint32 vertexBuffer) { return m_vertexBufferArray[vertexBuffer].VertexBuffer; } ID3D11Buffer* SDKMesh::GetIndexBufferAt(uint32 indexBuffer) { return m_indexBufferArray[indexBuffer].IndexBuffer; } byte* SDKMesh::GetRawVerticesAt(uint32 vertexBuffer) { return m_vertices[vertexBuffer]; } byte* SDKMesh::GetRawIndicesAt(uint32 indexBuffer) { return m_indices[indexBuffer]; } SDKMESH_MATERIAL* SDKMesh::GetMaterial(uint32 material) { return &m_materialArray[material]; } SDKMESH_MESH* SDKMesh::GetMesh(uint32 mesh) { return &m_meshArray[mesh]; } uint32 SDKMesh::GetNumSubsets(uint32 mesh) { return m_meshArray[mesh].NumSubsets; } SDKMESH_SUBSET* SDKMesh::GetSubset(uint32 mesh, uint32 subset) { return &m_subsetArray[m_meshArray[mesh].Subsets[subset]]; } uint32 SDKMesh::GetVertexStride(uint32 mesh, uint32 vertexBuffer) { return static_cast<uint32>(m_vertexBufferArray[m_meshArray[mesh].VertexBuffers[vertexBuffer]].StrideBytes); } uint32 SDKMesh::GetNumFrames() { return m_meshHeader->NumFrames; } SDKMESH_FRAME* SDKMesh::GetFrame(uint32 frame) { assert(frame < m_meshHeader->NumFrames); if (frame < m_meshHeader->NumFrames) { return &m_frameArray[frame]; } return nullptr; } SDKMESH_FRAME* SDKMesh::FindFrame(char* name) { for (uint32 i = 0; i < m_meshHeader->NumFrames; i++) { if (_stricmp(m_frameArray[i].Name, name) == 0) { return &m_frameArray[i]; } } return nullptr; } uint64 SDKMesh::GetNumVertices(uint32 mesh, uint32 vertexBuffer) { return m_vertexBufferArray[m_meshArray[mesh].VertexBuffers[vertexBuffer]].NumVertices; } uint64 SDKMesh::GetNumIndices(uint32 mesh) { return m_indexBufferArray[m_meshArray[mesh].IndexBuffer].NumIndices; } XMFLOAT3 SDKMesh::GetMeshBoundingBoxCenter(uint32 mesh) { return m_meshArray[mesh].BoundingBoxCenter; } XMFLOAT3 SDKMesh::GetMeshBoundingBoxExtents(uint32 mesh) { return m_meshArray[mesh].BoundingBoxExtents; } uint32 SDKMesh::GetOutstandingResources() { uint32 outstandingResources = 0; if (m_meshHeader == nullptr) { return 1; } outstandingResources += GetOutstandingBufferResources(); if (m_d3dDevice != nullptr) { for (uint32 i = 0; i < m_meshHeader->NumMaterials; i++) { if (m_materialArray[i].DiffuseTextureName[0] != 0) { if (!m_materialArray[i].DiffuseRV && !IsErrorResource(m_materialArray[i].DiffuseRV)) { outstandingResources++; } } if (m_materialArray[i].NormalTextureName[0] != 0) { if (!m_materialArray[i].NormalRV && !IsErrorResource(m_materialArray[i].NormalRV)) { outstandingResources++; } } if (m_materialArray[i].SpecularTextureName[0] != 0) { if (!m_materialArray[i].SpecularRV && !IsErrorResource(m_materialArray[i].SpecularRV)) { outstandingResources++; } } } } return outstandingResources; } uint32 SDKMesh::GetOutstandingBufferResources() { uint32 outstandingResources = 0; if (m_meshHeader == nullptr) { return 1; } for (uint32 i = 0; i < m_meshHeader->NumVertexBuffers; i++) { if ((m_vertexBufferArray[i].VertexBuffer == nullptr) && !IsErrorResource(m_vertexBufferArray[i].VertexBuffer)) { outstandingResources++; } } for (uint32 i = 0; i < m_meshHeader->NumIndexBuffers; i++) { if ((m_indexBufferArray[i].IndexBuffer == nullptr) && !IsErrorResource(m_indexBufferArray[i].IndexBuffer)) { outstandingResources++; } } return outstandingResources; } bool SDKMesh::CheckLoadDone() { if (0 == GetOutstandingResources()) { m_loading = false; return true; } return false; } bool SDKMesh::IsLoaded() { if (m_staticMeshData && !m_loading) { return true; } return false; } bool SDKMesh::IsLoading() { return m_loading; } void SDKMesh::SetLoading(bool loading) { m_loading = loading; } bool SDKMesh::HadLoadingError() { if (m_meshHeader != nullptr) { for (uint32 i = 0; i < m_meshHeader->NumVertexBuffers; i++) { if (IsErrorResource(m_vertexBufferArray[i].VertexBuffer)) { return true; } } for (uint32 i = 0; i < m_meshHeader->NumIndexBuffers; i++) { if (IsErrorResource(m_indexBufferArray[i].IndexBuffer)) { return true; } } } return false; } uint32 SDKMesh::GetNumInfluences(uint32 mesh) { return m_meshArray[mesh].NumFrameInfluences; } uint32 SDKMesh::GetAnimationKeyFromTime(double time) { if (m_animationHeader == nullptr) { return 0; } uint32 tick = static_cast<uint32>(m_animationHeader->AnimationFPS * time); tick = tick % (m_animationHeader->NumAnimationKeys - 1); tick++; return tick; } bool SDKMesh::GetAnimationProperties(uint32* numKeys, float* frameTime) { if (m_animationHeader == nullptr) { return false; } *numKeys = m_animationHeader->NumAnimationKeys; *frameTime = 1.0f / static_cast<float>(m_animationHeader->AnimationFPS); return true; } const CXMMATRIX SDKMesh::GetMeshInfluenceMatrix(uint32 mesh, uint32 influence) { uint32 frame = m_meshArray[mesh].FrameInfluences[influence]; return m_transformedFrameMatrices[frame]; } const CXMMATRIX SDKMesh::GetWorldMatrix(uint32 frameIndex) { return m_worldPoseFrameMatrices[frameIndex]; } const CXMMATRIX SDKMesh::GetInfluenceMatrix(uint32 frameIndex) { return m_transformedFrameMatrices[frameIndex]; }
[ "v-tiafe@microsoft.com" ]
v-tiafe@microsoft.com
11af67e61c85c0722dd05c7a68f14496c92ce0a9
b96d7c41c30779eca34d70a81f4590a57d19ec3d
/Lecture26/src/testPQ.cpp
783e53e0abdb82cc7ab6358d0afbb819fcfac55f
[]
no_license
mmorri22/sp21-cse-20312
f60a01e6972e69fe60714ba26e2dca737c53c26d
a6d108b1e455754b291f87dfd50d66bd7cf3a062
refs/heads/main
2023-04-19T03:24:16.966229
2021-05-06T16:12:04
2021-05-06T16:12:04
331,125,014
0
7
null
null
null
null
UTF-8
C++
false
false
503
cpp
#include "../include/PriorityQueue.h" #include <iostream> #define COUT std::cout #define ENDL std::endl int main( ) { PriorityQueue<int> thePQ; COUT << "Begin test.\nInserting: "; for( int i = 45; i != 0; i = ( i + 45 ) % 500 ){ COUT << i << " "; thePQ.push( i ); } COUT << ENDL << ENDL; COUT << "Removing : "; while( !thePQ.empty( ) ) { COUT << thePQ.front( ) << " "; thePQ.pop( ); } COUT << "\nSuccessfully completed test!" << ENDL; return 0; }
[ "mmorri22@nd.edu" ]
mmorri22@nd.edu
3b66804955c6e701f38199ec3e28a30264e5e0da
1ea7bed7a17e44ec38dfa73be2d46a88b75c1932
/Google/EPI/countOnes.cc
9c7e550ec7fe18283e8d767b04e7e97cb20a1619
[ "MIT" ]
permissive
ChakreshSinghUC/CPPCodes
105df678876451a7b5a6e6dfaeefc1e38a51a8c6
d82a3f467303566afbfcc927b660b0f7bf7c0432
refs/heads/master
2021-12-30T08:53:58.355588
2021-12-24T17:44:26
2021-12-24T17:44:26
83,990,305
0
0
null
null
null
null
UTF-8
C++
false
false
356
cc
#include <iostream> using namespace std; int main() { int nums = 8; int count_ones = 0; while (nums) { count_ones += nums & 1; nums >>= 1; } cout << count_ones << endl; nums = 8; count_ones = 0; while (nums) { count_ones += nums % 2; nums = nums / 2; } cout << count_ones; }
[ "singhch@mail.uc.edu" ]
singhch@mail.uc.edu
7cf9b8d086de91c708050484791685b96b389850
354066554dd1c3ca7a2d45e3673a2da86330f816
/src/anova_lsqd.cpp
6a4037ee6da9fbe6870c3f75fe137fd3247c0163
[ "MIT" ]
permissive
elemosjr/planejamento
e8bfe3d0d9d255b1216a91d91a0a880fa2f3cb0c
f7cd310c6a59533b8d7b7ec8b03391a874f0cb51
refs/heads/master
2023-04-30T19:34:33.232372
2021-05-20T00:54:16
2021-05-20T00:54:16
366,199,524
0
0
null
null
null
null
UTF-8
C++
false
false
8,101
cpp
#include <Rcpp.h> #include "utilidades.h" using namespace Rcpp; //' Gera valores de anova para Quadrados Latinos //' //' @description Calcula valores utilizados para uma tabela de ANOVA de um delineamento em quadrados latinos //' //' @param dados Data frame com colunas separadas para os tratamentos, os blocos e os resultados a serem analisados //' @param x String com o nome da coluna dos tratamentos //' @param y String com o nome da coluna dos resultados //' @param linha String com o nome da coluna do data frame que representa a linha do quadrado latino //' @param coluna String com o nome da coluna do data frame que representa a coluna do quadrado latino //' @param replica String com o nome da coluna do data frame que representa as replicas //' //' @import glue //' @import tidyr //' //' @return Objeto de tipo lista contendo todos os valores utilizados para o calculo da tabela da ANOVA, os valores da tabela da ANOVA e os parâmetros estimados. //' //' @examples //' //' quadrados_latinos(4)$dados %>% //' anova_lsqd("tratamento", "resultado", "linha", "coluna") //' //' @export //' // [[Rcpp::export]] List anova_lsqd(DataFrame dados, std::string x, std::string y, std::string linha, std::string coluna, std::string replica = "") { Environment tidyr = Environment::namespace_env("tidyr"); Function drop_na = tidyr["drop_na"]; dados = drop_na(dados); CharacterVector X = dados[x]; NumericVector Y = dados[y]; CharacterVector Linha = dados[linha]; CharacterVector Coluna = dados[coluna]; CharacterVector Replica; double n; if(replica != "") { Replica = dados[replica]; n = unique(Replica).size(); } else { n = 1; } double N = dados.nrow(); double p = sqrt(N/n); double y___ = sum(Y); NumericVector yi__ = soma_grupo(Y, Linha); NumericVector y_j_ = soma_grupo(Y, X); NumericVector y__k = soma_grupo(Y, Coluna); double mu = mean(Y); NumericVector tau = y_j_ - mu; NumericVector alpha = yi__ - mu; NumericVector beta = y__k - mu; double sqt = sum(pow(Y, 2)) - pow(y___, 2) / N; double sqtrat = sum(pow(y_j_, 2)) / (p*n) - pow(y___, 2) / N; double sqlinha = sum(pow(yi__, 2)) / (p*n) - pow(y___, 2) / N; double sqcoluna = sum(pow(y__k, 2)) / (p*n) - pow(y___, 2) / N; double sqe = sqt- sqtrat - sqlinha - sqcoluna; double qmtrat = sqtrat / (p-1); double qmlinha = sqlinha / (p-1); double qmcoluna = sqcoluna / (p-1); double qme = sqe / ((p-2) * (p-1)); double f0 = qmtrat / qme; double pvalor = R::pf(f0, p-1, (p-2) * (p-1), false, false); // valores estimados double tau_ = mean(tau); double alpha_ = mean(alpha); double beta_ = mean(beta); double tau_i = mean(y_j_); double alpha_i = mean(yi__); double beta_i = mean(y__k); List L; if(replica == "") { // Bloco para quando NÃO há replicas List stat = List::create( Named("N") = N, Named("p") = p, Named("n") = n, Named("y...") = y___, Named("yi..") = yi__, Named("y.j.") = y_j_, Named("y..k") = y__k, Named("mu") = mu, Named("tau") = tau, Named("alpha") = alpha, Named("beta") = beta, Named("tau_") = tau_, Named("alpha_") = alpha_, Named("beta_") = beta_, Named("tau_i") = tau_i, Named("alpha_i") = alpha_i, Named("beta_i") = beta_i); // p valores double plinha = R::pf(qmlinha/qme, p-1, (p-2) * (p-1), false, false); double pcoluna = R::pf(qmcoluna/qme, p-1, (p-2) * (p-1), false, false); DataFrame anova_df = DataFrame::create( Named("Fonte de variação") = CharacterVector::create( x, linha, coluna, "Erros", "Total" ), Named("Graus de liberdade") = NumericVector::create( p-1, p-1, p-1, (p-1)*(p-1), pow(p, 2)-1 ), Named("Quadrado Médio") = NumericVector::create( qmtrat, qmlinha, qmcoluna, qme, R_NaN ), Named("F0") = NumericVector::create( f0, qmlinha/qme, qmcoluna/qme, qme, R_NaN ), Named("p-valor") = NumericVector::create( pvalor, plinha, pcoluna, R_NaN, R_NaN ) ); List anova_list = List::create( Named("sqt") = sqt, Named("sqtrat") = sqtrat, Named("sqlinha") = sqlinha, Named("sqcoluna") = sqcoluna, Named("sqe") = sqe, Named("qmtrat") = qmtrat, Named("qmlinha") = qmlinha, Named("qmcoluna") = qmcoluna, Named("f0") = f0, Named("pvalor") = pvalor ); DataFrame estimados = DataFrame::create( Named("$\\hat{\\mu}$") = mu, Named("$\\hat{\\tau}$") = tau_, Named("$\\hat{\\alpha}$") = alpha_, Named("$\\hat{\\beta}$") = beta_, Named("$\\hat{\\tau}_i$") = tau_i, Named("$\\hat{\\alpha}_i$") = alpha_i, Named("$\\hat{\\beta}_i$") = beta_i ); L = List::create(Named("stat") = stat, Named("anova_df") = anova_df, Named("anova_list") = anova_list, Named("estimados") = estimados, Named("pvalor") = pvalor); } else { // Bloco para quando há replicas NumericVector y___l = soma_grupo(Y, Replica); NumericVector lambda = y___l - mu; double sqrep = sum(pow(y___l, 2)) / pow(p, 2) - pow(y___, 2) / N; double qmrep = sqrep / (n-1); sqe -= sqrep; qme = sqe / ((p-1) * (n * (p+1) - 3)); f0 = qmtrat / qme; pvalor = R::pf(f0, p-1, ((p-1) * (n * (p+1) - 3)), false, false); // valores estimados double lambda_ = mean(lambda); double lambda_i = mean(y___l); List stat = List::create( Named("N") = N, Named("p") = p, Named("n") = n, Named("y...") = y___, Named("yi..") = yi__, Named("y.j.") = y_j_, Named("y..k") = y__k, Named("y...l") = y___l, Named("mu") = mu, Named("tau") = tau, Named("lambda") = lambda, Named("alpha") = alpha, Named("beta") = beta, Named("tau_") = tau_, Named("alpha_") = alpha_, Named("beta_") = beta_, Named("tau_i") = tau_i, Named("alpha_i") = alpha_i, Named("beta_i") = beta_i); // p valores double plinha = R::pf(qmlinha/qme, p-1, ((p-1) * (n * (p+1) - 3)), false, false); double pcoluna = R::pf(qmcoluna/qme, p-1, ((p-1) * (n * (p+1) - 3)), false, false); double prep = R::pf(qmrep/qme, n-1, ((p-1) * (n * (p+1) - 3)), false, false); DataFrame anova_df = DataFrame::create( Named("Fonte de variação") = CharacterVector::create( x, linha, coluna, replica, "Erros", "Total" ), Named("Graus de liberdade") = NumericVector::create( p-1, p-1, p-1, n-1, ((p-1) * (n * (p+1) - 3)), pow(p, 2)-1 ), Named("Quadrado Médio") = NumericVector::create( qmtrat, qmlinha, qmcoluna, qmrep, qme, R_NaN ), Named("F0") = NumericVector::create( f0, qmlinha/qme, qmcoluna/qme, qmrep/qme, qme, R_NaN ), Named("p-valor") = NumericVector::create( pvalor, plinha, pcoluna, prep, R_NaN, R_NaN ) ); List anova_list = List::create( Named("sqt") = sqt, Named("sqtrat") = sqtrat, Named("sqlinha") = sqlinha, Named("sqcoluna") = sqcoluna, Named("sqrep") = sqrep, Named("sqe") = sqe, Named("qmtrat") = qmtrat, Named("qmlinha") = qmlinha, Named("qmcoluna") = qmcoluna, Named("qmrep") = qmrep, Named("f0") = f0, Named("pvalor") = pvalor ); DataFrame estimados = DataFrame::create( Named("$\\hat{\\mu}$") = mu, Named("$\\hat{\\tau}$") = tau_, Named("$\\hat{\\alpha}$") = alpha_, Named("$\\hat{\\beta}$") = beta_, Named("$\\hat{\\lambda}$") = lambda_, Named("$\\hat{\\tau}_i$") = tau_i, Named("$\\hat{\\alpha}_i$") = alpha_i, Named("$\\hat{\\beta}_i$") = beta_i, Named("$\\hat{\\lambda}_i$") = lambda_i ); L = List::create(Named("stat") = stat, Named("anova_df") = anova_df, Named("anova_list") = anova_list, Named("estimados") = estimados, Named("pvalor") = pvalor); } return L; }
[ "elemosjr@gmail.com" ]
elemosjr@gmail.com
a0b7b4e2e97d135c2a176c56ccaa474958758c8c
d0d78d0c1fa8d7575a0c18052ea87f31037369c9
/Source/OceanMan/OceanManCharacter.cpp
23a93c953f741f8b92da371b2c266bd12d4c8a02
[]
no_license
WaerjakSC/OceanMan
b128c4efe4ae084cf489dd1c47fd14d6ba1fb979
9b9d6720f7787e54b73334b606e815c56931af55
refs/heads/master
2020-07-23T14:17:29.531645
2019-09-23T09:00:40
2019-09-23T09:00:40
207,588,615
0
0
null
2019-09-23T07:46:13
2019-09-10T14:56:52
C++
UTF-8
C++
false
false
5,135
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "OceanManCharacter.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "OceanController.h" #include "GameFramework/SpringArmComponent.h" ////////////////////////////////////////////////////////////////////////// // AOceanManCharacter AOceanManCharacter::AOceanManCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // declare overlap events GetCapsuleComponent()->OnComponentBeginOverlap.AddDynamic(this, &AOceanManCharacter::OnOverlapBegin); GetCapsuleComponent()->OnComponentEndOverlap.AddDynamic(this, &AOceanManCharacter::OnOverlapEnd); } ////////////////////////////////////////////////////////////////////////// // Input void AOceanManCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAction("ActivateShip", IE_Pressed, this, &AOceanManCharacter::ActivateShip); PlayerInputComponent->BindAxis("MoveForward", this, &AOceanManCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AOceanManCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &AOceanManCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &AOceanManCharacter::LookUpAtRate); } void AOceanManCharacter::ActivateShip() { } void AOceanManCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AOceanManCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void AOceanManCharacter::OnOverlapBegin(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { } void AOceanManCharacter::OnOverlapEnd(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { } void AOceanManCharacter::MoveForward(float Value) { if ((Controller != NULL) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); } } void AOceanManCharacter::MoveRight(float Value) { if ( (Controller != NULL) && (Value != 0.0f) ) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, Value); } }
[ "waerjaksc@gmail.com" ]
waerjaksc@gmail.com
48587d8885a1f75e460ab71f1c23723ff70d1016
d73cf4af65fffc16c2326281fb7de3344566d6a1
/TVM/ReceptionHeadDlg.h
ced6ab1219d179fbaa5490d5fdda1c55987dc016
[]
no_license
yongchaohu/WH_DEVICE
c3299ddd63ff15ca5ba3fa476cb90eee01ddb541
5212d3b15dfcf5a542c0936ebf0e72ed66b85d05
refs/heads/master
2020-05-27T20:38:35.562316
2019-06-24T03:02:29
2019-06-24T03:02:29
188,782,571
0
0
null
2019-05-27T06:18:48
2019-05-27T06:18:48
null
GB18030
C++
false
false
2,233
h
#pragma once #include "BaseDlg.h" #include "util.h" #include <atlimage.h> #include "StatusDisplayModuleHelper.h" #define TIMER_STS 1000 ///< 事件 class CReceptionHeadDlg : public CBaseDlg { DECLARE_DYNAMIC(CReceptionHeadDlg) DECLARE_MESSAGE_MAP() public: CReceptionHeadDlg(CWnd* pParent = NULL); // 标准构造函数 ~CReceptionHeadDlg(); // 对话框数据 enum { IDD = IDD_RECEPTION_HEAD_DLG }; void SetStationName(CString stationNameCN, CString stationNameEN = _T(""), CString stationNamePN = _T("")); // 设置车站名称 void SetServiceStatuse(OPERATION_MODE operationMode); // 设置服务状态 virtual void OnClientLanguageModeChanged(LANGUAGETYPE_T&); void OnChangeChanged(); void OnPaymentChanged(); void OnChangeOrPaymentChanged(); void updataStatusData(); void OnStatusChanged(); // TVM招援信息变化 private: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnDestroy(); void OnDraw(CDC* pDC); void ConvertPng(CImage* image); // 透明处理 private: const static UINT TIMER_INTERVAL = 1000; // 时间显示间隔(1 second) CImage m_Logo; // Logo CImage m_bkg; // 背景图片 CString m_deviceId; // 设备编号和版本 CString m_status; // 业务状态 CString m_stationName; // 车站名称 CString m_stationNameCN; // 车站名称 CString m_stationNameEN; // 车站名称 CString m_stationNamePN; // 车站名称 CString m_strWeekDay; // 星期几 CString m_strStatusDispMessage; // 提示信息(包括招援信息等) OPERATION_MODE m_operationMode; //CPictureEx m_gif; CImage m_hStatusPic; _DATE_TIME m_preTime; // 前次刷新时间 };
[ "1017943468@qq.com" ]
1017943468@qq.com
9497eaae58d3bf18f4d39ed412e6dcc7fd580a39
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/chrome/browser/ui/search/ntp_user_data_logger_unittest.cc
8226965bca637d7a2a30eecd9ff692396d84ba55
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
35,012
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 "chrome/browser/ui/search/ntp_user_data_logger.h" #include <memory> #include <string> #include <vector> #include "base/metrics/histogram.h" #include "base/metrics/statistics_recorder.h" #include "base/test/histogram_tester.h" #include "base/time/time.h" #include "chrome/common/search/ntp_logging_events.h" #include "chrome/common/url_constants.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::Bucket; using ntp_tiles::TileTitleSource; using ntp_tiles::TileSource; using ntp_tiles::TileVisualType; using testing::ElementsAre; using testing::IsEmpty; using testing::SizeIs; namespace { constexpr int kUnknownTitleSource = static_cast<int>(TileTitleSource::UNKNOWN); constexpr int kManifestTitleSource = static_cast<int>(TileTitleSource::MANIFEST); constexpr int kMetaTagTitleSource = static_cast<int>(TileTitleSource::META_TAG); constexpr int kTitleTagTitleSource = static_cast<int>(TileTitleSource::TITLE_TAG); constexpr int kInferredTitleSource = static_cast<int>(TileTitleSource::INFERRED); using Sample = base::HistogramBase::Sample; using Samples = std::vector<Sample>; class TestNTPUserDataLogger : public NTPUserDataLogger { public: explicit TestNTPUserDataLogger(const GURL& ntp_url) : NTPUserDataLogger(nullptr) { set_ntp_url_for_testing(ntp_url); } ~TestNTPUserDataLogger() override {} bool DefaultSearchProviderIsGoogle() const override { return is_google_; } bool is_google_ = true; }; MATCHER_P3(IsBucketBetween, lower_bound, upper_bound, count, "") { return arg.min >= lower_bound && arg.min <= upper_bound && arg.count == count; } } // namespace TEST(NTPUserDataLoggerTest, TestNumberOfTiles) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; // Ensure non-zero statistics. TestNTPUserDataLogger logger(GURL("chrome://newtab/")); base::TimeDelta delta = base::TimeDelta::FromMilliseconds(0); for (int i = 0; i < 8; ++i) { logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( i, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); } logger.LogEvent(NTP_ALL_TILES_LOADED, delta); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.NumberOfTiles"), ElementsAre(Bucket(8, 1))); // We should not log again for the same NTP. logger.LogEvent(NTP_ALL_TILES_LOADED, delta); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.NumberOfTiles"), ElementsAre(Bucket(8, 1))); // Navigating away and back resets stats. logger.NavigatedFromURLToURL(GURL("chrome://newtab/"), GURL("http://chromium.org")); logger.NavigatedFromURLToURL(GURL("http://chromium.org"), GURL("chrome://newtab/")); logger.LogEvent(NTP_ALL_TILES_LOADED, delta); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.NumberOfTiles"), ElementsAre(Bucket(0, 1), Bucket(8, 1))); } // TODO(https://crbug.com/767406): Split this test in readable units. TEST(NTPUserDataLoggerTest, TestLogMostVisitedImpression) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; TestNTPUserDataLogger logger(GURL("chrome://newtab/")); base::TimeDelta delta = base::TimeDelta::FromMilliseconds(0); // Impressions increment the associated bins. logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 0, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::INFERRED, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 1, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::INFERRED, TileVisualType::THUMBNAIL_FAILED, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 2, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::INFERRED, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 3, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::INFERRED, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 4, TileSource::TOP_SITES, TileTitleSource::TITLE_TAG, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 5, TileSource::TOP_SITES, TileTitleSource::MANIFEST, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 6, TileSource::POPULAR, TileTitleSource::TITLE_TAG, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 7, TileSource::POPULAR_BAKED_IN, TileTitleSource::META_TAG, TileVisualType::THUMBNAIL, base::Time(), GURL())); // Repeated impressions for the same bins are ignored. logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 0, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL_FAILED, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 1, TileSource::TOP_SITES, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL_FAILED, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 2, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 3, TileSource::TOP_SITES, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); // Impressions are silently ignored for tiles >= 8. logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 8, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 9, TileSource::TOP_SITES, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); // The actual histograms are emitted only after the ALL_TILES_LOADED event, so // at this point everything should still be empty. EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression"), IsEmpty()); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression.server"), IsEmpty()); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression.client"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileType"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileType.client"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileType.server"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle.client"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle.server"), IsEmpty()); // Send the ALL_TILES_LOADED event, this should trigger emitting histograms. logger.LogEvent(NTP_ALL_TILES_LOADED, delta); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression"), ElementsAre(Bucket(0, 1), Bucket(1, 1), Bucket(2, 1), Bucket(3, 1), Bucket(4, 1), Bucket(5, 1), Bucket(6, 1), Bucket(7, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression.server"), ElementsAre(Bucket(0, 1), Bucket(1, 1), Bucket(2, 1), Bucket(3, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression.client"), ElementsAre(Bucket(4, 1), Bucket(5, 1))); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.SuggestionsImpression.popular_fetched"), ElementsAre(Bucket(6, 1))); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.SuggestionsImpression.popular_baked_in"), ElementsAre(Bucket(7, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 7), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType.server"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 3), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileType.client"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 2))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType.popular_fetched"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType.popular_baked_in"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle"), ElementsAre(Bucket(kManifestTitleSource, 1), Bucket(kMetaTagTitleSource, 1), Bucket(kTitleTagTitleSource, 2), Bucket(kInferredTitleSource, 4))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle.server"), ElementsAre(Bucket(kInferredTitleSource, 4))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle.client"), ElementsAre(Bucket(kManifestTitleSource, 1), Bucket(kTitleTagTitleSource, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTitle.popular_fetched"), ElementsAre(Bucket(kTitleTagTitleSource, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTitle.popular_baked_in"), ElementsAre(Bucket(kMetaTagTitleSource, 1))); // After navigating away from the NTP and back, we record again. logger.NavigatedFromURLToURL(GURL("chrome://newtab/"), GURL("http://chromium.org")); logger.NavigatedFromURLToURL(GURL("http://chromium.org"), GURL("chrome://newtab/")); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 0, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::INFERRED, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 1, TileSource::POPULAR, TileTitleSource::MANIFEST, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 2, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::INFERRED, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 3, TileSource::TOP_SITES, TileTitleSource::MANIFEST, TileVisualType::THUMBNAIL_FAILED, base::Time(), GURL())); logger.LogEvent(NTP_ALL_TILES_LOADED, delta); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression"), ElementsAre(Bucket(0, 2), Bucket(1, 2), Bucket(2, 2), Bucket(3, 2), Bucket(4, 1), Bucket(5, 1), Bucket(6, 1), Bucket(7, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression.server"), ElementsAre(Bucket(0, 2), Bucket(1, 1), Bucket(2, 2), Bucket(3, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.SuggestionsImpression.client"), ElementsAre(Bucket(3, 1), Bucket(4, 1), Bucket(5, 1))); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.SuggestionsImpression.popular_fetched"), ElementsAre(Bucket(1, 1), Bucket(6, 1))); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.SuggestionsImpression.popular_baked_in"), ElementsAre(Bucket(7, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 10), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 2))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType.server"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 5), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType.client"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 2), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType.popular_fetched"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 2))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileType.popular_baked_in"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle"), ElementsAre(Bucket(kManifestTitleSource, 3), Bucket(kMetaTagTitleSource, 1), Bucket(kTitleTagTitleSource, 2), Bucket(kInferredTitleSource, 6))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle.server"), ElementsAre(Bucket(kInferredTitleSource, 6))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitle.client"), ElementsAre(Bucket(kManifestTitleSource, 2), Bucket(kTitleTagTitleSource, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTitle.popular_fetched"), ElementsAre(Bucket(kManifestTitleSource, 1), Bucket(kTitleTagTitleSource, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTitle.popular_baked_in"), ElementsAre(Bucket(kMetaTagTitleSource, 1))); } // TODO(https://crbug.com/767406): Split this test in readable units. TEST(NTPUserDataLoggerTest, TestLogMostVisitedNavigation) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; TestNTPUserDataLogger logger(GURL("chrome://newtab/")); logger.LogMostVisitedNavigation(ntp_tiles::NTPTileImpression( 0, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited"), ElementsAre(Bucket(0, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.server"), ElementsAre(Bucket(0, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.client"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.server"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.client"), IsEmpty()); logger.LogMostVisitedNavigation(ntp_tiles::NTPTileImpression( 1, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL_FAILED, base::Time(), GURL())); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited"), ElementsAre(Bucket(0, 1), Bucket(1, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.server"), ElementsAre(Bucket(0, 1), Bucket(1, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.client"), IsEmpty()); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.server"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.client"), IsEmpty()); logger.LogMostVisitedNavigation(ntp_tiles::NTPTileImpression( 2, TileSource::TOP_SITES, TileTitleSource::MANIFEST, TileVisualType::THUMBNAIL_FAILED, base::Time(), GURL())); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited"), ElementsAre(Bucket(0, 1), Bucket(1, 1), Bucket(2, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.server"), ElementsAre(Bucket(0, 1), Bucket(1, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.client"), ElementsAre(Bucket(2, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 2))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.server"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.client"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); logger.LogMostVisitedNavigation(ntp_tiles::NTPTileImpression( 3, TileSource::POPULAR, TileTitleSource::META_TAG, TileVisualType::THUMBNAIL, base::Time(), GURL())); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.MostVisited"), ElementsAre(Bucket(0, 1), Bucket(1, 1), Bucket(2, 1), Bucket(3, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.server"), ElementsAre(Bucket(0, 1), Bucket(1, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.client"), ElementsAre(Bucket(2, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.MostVisited.popular_fetched"), ElementsAre(Bucket(3, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 2), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 2))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.server"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.client"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.TileTypeClicked.popular_fetched"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitleClicked"), ElementsAre(Bucket(kUnknownTitleSource, 2), Bucket(kManifestTitleSource, 1), Bucket(kMetaTagTitleSource, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTitleClicked.server"), ElementsAre(Bucket(kUnknownTitleSource, 2))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTitleClicked.client"), ElementsAre(Bucket(kManifestTitleSource, 1))); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.TileTitleClicked.popular_fetched"), ElementsAre(Bucket(kMetaTagTitleSource, 1))); // Navigations always increase. logger.LogMostVisitedNavigation(ntp_tiles::NTPTileImpression( 0, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedNavigation(ntp_tiles::NTPTileImpression( 1, TileSource::TOP_SITES, TileTitleSource::TITLE_TAG, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedNavigation(ntp_tiles::NTPTileImpression( 2, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); logger.LogMostVisitedNavigation(ntp_tiles::NTPTileImpression( 3, TileSource::POPULAR, TileTitleSource::MANIFEST, TileVisualType::THUMBNAIL, base::Time(), GURL())); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.MostVisited"), ElementsAre(Bucket(0, 2), Bucket(1, 2), Bucket(2, 2), Bucket(3, 2))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.server"), ElementsAre(Bucket(0, 2), Bucket(1, 1), Bucket(2, 1))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.MostVisited.client"), ElementsAre(Bucket(1, 1), Bucket(2, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.MostVisited.popular_fetched"), ElementsAre(Bucket(3, 2))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 6), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 2))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.server"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 3), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTypeClicked.client"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 1), Bucket(ntp_tiles::TileVisualType::THUMBNAIL_FAILED, 1))); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.TileTypeClicked.popular_fetched"), ElementsAre(Bucket(ntp_tiles::TileVisualType::THUMBNAIL, 2))); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TileTitleClicked"), ElementsAre(Bucket(kUnknownTitleSource, 4), Bucket(kManifestTitleSource, 2), Bucket(kMetaTagTitleSource, 1), Bucket(kTitleTagTitleSource, 1))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTitleClicked.server"), ElementsAre(Bucket(kUnknownTitleSource, 4))); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TileTitleClicked.client"), ElementsAre(Bucket(kManifestTitleSource, 1), Bucket(kTitleTagTitleSource, 1))); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.TileTitleClicked.popular_fetched"), ElementsAre(Bucket(kManifestTitleSource, 1), Bucket(kMetaTagTitleSource, 1))); } TEST(NTPUserDataLoggerTest, TestLoadTime) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; TestNTPUserDataLogger logger(GURL("chrome://newtab/")); base::TimeDelta delta_tiles_received = base::TimeDelta::FromMilliseconds(10); base::TimeDelta delta_tiles_loaded = base::TimeDelta::FromMilliseconds(100); // Send the ALL_TILES_RECEIVED event. logger.LogEvent(NTP_ALL_TILES_RECEIVED, delta_tiles_received); // Log a TOP_SITES impression (for the .MostVisited vs .MostLikely split in // the time histograms). logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 0, TileSource::TOP_SITES, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); // Send the ALL_TILES_LOADED event, this should trigger emitting histograms. logger.LogEvent(NTP_ALL_TILES_LOADED, delta_tiles_loaded); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TilesReceivedTime"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.TilesReceivedTime.MostVisited"), SizeIs(1)); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TilesReceivedTime.MostLikely"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.MostVisited"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.MostLikely"), IsEmpty()); histogram_tester.ExpectTimeBucketCount("NewTabPage.TilesReceivedTime", delta_tiles_received, 1); histogram_tester.ExpectTimeBucketCount( "NewTabPage.TilesReceivedTime.MostVisited", delta_tiles_received, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.MostVisited", delta_tiles_loaded, 1); // We should not log again for the same NTP. logger.LogEvent(NTP_ALL_TILES_RECEIVED, delta_tiles_received); logger.LogEvent(NTP_ALL_TILES_LOADED, delta_tiles_loaded); histogram_tester.ExpectTimeBucketCount("NewTabPage.TilesReceivedTime", delta_tiles_received, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime", delta_tiles_loaded, 1); // After navigating away from the NTP and back, we record again. logger.NavigatedFromURLToURL(GURL("chrome://newtab/"), GURL("http://chromium.org")); logger.NavigatedFromURLToURL(GURL("http://chromium.org"), GURL("chrome://newtab/")); // This time, log a SUGGESTIONS_SERVICE impression, so the times will end up // in .MostLikely. logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 0, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time(), GURL())); base::TimeDelta delta_tiles_received2 = base::TimeDelta::FromMilliseconds(50); base::TimeDelta delta_tiles_loaded2 = base::TimeDelta::FromMilliseconds(500); logger.LogEvent(NTP_ALL_TILES_RECEIVED, delta_tiles_received2); logger.LogEvent(NTP_ALL_TILES_LOADED, delta_tiles_loaded2); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.TilesReceivedTime"), SizeIs(2)); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.TilesReceivedTime.MostVisited"), SizeIs(1)); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.TilesReceivedTime.MostLikely"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime"), SizeIs(2)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.MostVisited"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.MostLikely"), SizeIs(1)); histogram_tester.ExpectTimeBucketCount("NewTabPage.TilesReceivedTime", delta_tiles_received2, 1); histogram_tester.ExpectTimeBucketCount( "NewTabPage.TilesReceivedTime.MostLikely", delta_tiles_received2, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime", delta_tiles_loaded2, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.MostLikely", delta_tiles_loaded2, 1); } TEST(NTPUserDataLoggerTest, TestLoadTimeLocalNTPGoogle) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; TestNTPUserDataLogger logger((GURL(chrome::kChromeSearchLocalNtpUrl))); logger.is_google_ = true; base::TimeDelta delta_tiles_received = base::TimeDelta::FromMilliseconds(10); base::TimeDelta delta_tiles_loaded = base::TimeDelta::FromMilliseconds(100); // Send the ALL_TILES_RECEIVED event. logger.LogEvent(NTP_ALL_TILES_RECEIVED, delta_tiles_received); // Send the ALL_TILES_LOADED event, this should trigger emitting histograms. logger.LogEvent(NTP_ALL_TILES_LOADED, delta_tiles_loaded); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.LocalNTP"), SizeIs(1)); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.LoadTime.LocalNTP.Google"), SizeIs(1)); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.LoadTime.LocalNTP.Other"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.Web"), IsEmpty()); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.LocalNTP", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.LocalNTP.Google", delta_tiles_loaded, 1); } TEST(NTPUserDataLoggerTest, TestLoadTimeLocalNTPOther) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; TestNTPUserDataLogger logger((GURL(chrome::kChromeSearchLocalNtpUrl))); logger.is_google_ = false; base::TimeDelta delta_tiles_received = base::TimeDelta::FromMilliseconds(10); base::TimeDelta delta_tiles_loaded = base::TimeDelta::FromMilliseconds(100); // Send the ALL_TILES_RECEIVED event. logger.LogEvent(NTP_ALL_TILES_RECEIVED, delta_tiles_received); // Send the ALL_TILES_LOADED event, this should trigger emitting histograms. logger.LogEvent(NTP_ALL_TILES_LOADED, delta_tiles_loaded); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.LocalNTP"), SizeIs(1)); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.LoadTime.LocalNTP.Google"), IsEmpty()); EXPECT_THAT( histogram_tester.GetAllSamples("NewTabPage.LoadTime.LocalNTP.Other"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.Web"), IsEmpty()); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.LocalNTP", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.LocalNTP.Other", delta_tiles_loaded, 1); } TEST(NTPUserDataLoggerTest, TestLoadTimeRemoteNTPGoogle) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; TestNTPUserDataLogger logger(GURL("https://www.google.com/_/chrome/newtab")); logger.is_google_ = true; base::TimeDelta delta_tiles_received = base::TimeDelta::FromMilliseconds(10); base::TimeDelta delta_tiles_loaded = base::TimeDelta::FromMilliseconds(100); // Send the ALL_TILES_RECEIVED event. logger.LogEvent(NTP_ALL_TILES_RECEIVED, delta_tiles_received); // Send the ALL_TILES_LOADED event, this should trigger emitting histograms. logger.LogEvent(NTP_ALL_TILES_LOADED, delta_tiles_loaded); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.LocalNTP"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.Web"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.Web.Google"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.Web.Other"), IsEmpty()); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.Web", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.Web.Google", delta_tiles_loaded, 1); } TEST(NTPUserDataLoggerTest, TestLoadTimeRemoteNTPOther) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; TestNTPUserDataLogger logger(GURL("https://www.notgoogle.com/newtab")); logger.is_google_ = false; base::TimeDelta delta_tiles_received = base::TimeDelta::FromMilliseconds(10); base::TimeDelta delta_tiles_loaded = base::TimeDelta::FromMilliseconds(100); // Send the ALL_TILES_RECEIVED event. logger.LogEvent(NTP_ALL_TILES_RECEIVED, delta_tiles_received); // Send the ALL_TILES_LOADED event, this should trigger emitting histograms. logger.LogEvent(NTP_ALL_TILES_LOADED, delta_tiles_loaded); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.LocalNTP"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.Web"), SizeIs(1)); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.Web.Google"), IsEmpty()); EXPECT_THAT(histogram_tester.GetAllSamples("NewTabPage.LoadTime.Web.Other"), SizeIs(1)); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.Web", delta_tiles_loaded, 1); histogram_tester.ExpectTimeBucketCount("NewTabPage.LoadTime.Web.Other", delta_tiles_loaded, 1); } TEST(NTPUserDataLoggerTest, TestImpressionsAge) { base::StatisticsRecorder::Initialize(); base::HistogramTester histogram_tester; // Ensure non-zero statistics. TestNTPUserDataLogger logger(GURL("chrome://newtab/")); constexpr base::TimeDelta delta = base::TimeDelta::FromMilliseconds(0); constexpr base::TimeDelta kSuggestionAge = base::TimeDelta::FromMinutes(1); constexpr base::TimeDelta kBucketTolerance = base::TimeDelta::FromSeconds(20); logger.LogMostVisitedImpression(ntp_tiles::NTPTileImpression( 0, TileSource::SUGGESTIONS_SERVICE, TileTitleSource::UNKNOWN, TileVisualType::THUMBNAIL, base::Time::Now() - kSuggestionAge, GURL())); logger.LogEvent(NTP_ALL_TILES_LOADED, delta); EXPECT_THAT(histogram_tester.GetAllSamples( "NewTabPage.SuggestionsImpressionAge.server"), ElementsAre(IsBucketBetween( (kSuggestionAge - kBucketTolerance).InSeconds(), (kSuggestionAge + kBucketTolerance).InSeconds(), /*count=*/1))); }
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
64883fb54d668cfc6abe9f5ed3e3b607f24d3624
1d3b0b0d5337adb8335b1a970b0c34924b8baf96
/AtCoder/abc/61~90/abc073/A.cpp
5f37f253a29b4b0d27946e1078fed9b00f892711
[]
no_license
pyst1g/Programming-Cplus
6a2bdbbc63935fe7b4ebd00f6c9d13565cb05bcf
7d2c41075382e606e4c572c3ebd239755f36e72a
refs/heads/master
2021-05-14T16:14:49.720215
2020-01-26T09:53:16
2020-01-26T09:53:16
116,015,340
1
0
null
null
null
null
UTF-8
C++
false
false
493
cpp
// finish date: 2018/01/20 #include <iostream> #include <cmath> #include <vector> #include <bitset> #include <algorithm> #include <stack> #include <map> #include <climits> using namespace std; #define FOR(i, a, b) for(int (i)=a;(i)<(b);(i)++) #define rep(i, n) FOR(i,0,n) #define ll long long #define bigmod 1000000007 #define INF 500000000 int main() { string N; cin >> N; if (N[0] == '9' || N[1] == '9') cout << "Yes" << endl; else cout << "No" << endl; return 0; }
[ "s1511381@s.tsukuba.ac.jp" ]
s1511381@s.tsukuba.ac.jp
a3c78dcce5bbaf1fd5102039ffa8f14928de73b5
c97dd087a7b819f1ea030e5c3b03c5798915f970
/TheDarkThreat/UIRepeatLevel.cpp
72eb4f4eeb97425fb8eaf7b73f661aefe4999caf
[]
no_license
Safeheaded/TheDarkThreat
7260b5c06d57a21d3554e56b31180578624d39a9
b888a7026fa5da7a1e6ef95db2edcdda46b40556
refs/heads/master
2023-06-05T23:48:49.898342
2021-06-24T09:16:13
2021-06-24T09:16:13
372,039,257
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
#include "UIRepeatLevel.h" UIRepeatLevel::UIRepeatLevel(std::stack<Scene*>* scenes): scenes(scenes) { } UIRepeatLevel::~UIRepeatLevel() { } void UIRepeatLevel::execute(sf::RenderWindow* window) { auto* currentScene = this->scenes->top(); this->scenes->pop(); int savedLevel = Utils::getSavedLevel(); if (savedLevel == 1) { this->scenes->push(new Level1(window, this->scenes)); } else if (savedLevel == 2) { this->scenes->push(new Level2(window, this->scenes)); } }
[ "m.patryk@outlook.com" ]
m.patryk@outlook.com
8d4b3dcd1129f7d798552da58e020452bf1c3ffa
d10d58845013fd3c1ddd3f4ecbfa6d4f111ab83a
/ch1/1-9.cpp
618add4a4d25f91b5440b4d0f5a4f436e7e423c5
[]
no_license
burncode/The-C-Programming-Language
087ec059c58269d7fb6f0d4a3ef4a20899004ad8
a997c21097b748cf92e8918c6701f462d3bccb76
refs/heads/master
2020-03-11T18:06:15.245109
2016-12-07T16:07:28
2016-12-07T16:07:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
414
cpp
// Author: jrjbear@gmail.com // Date: Wed Oct 2 22:53:43 2013 // // File: 1-9.cpp // Description: Delete successive blanks #include <stdio.h> int main(int argc, char* argv[]) { int c = -1; int lastc = -1; while ((c = getchar()) != EOF) { if (lastc == ' ' && c == ' ') { continue; } else { putchar(c); lastc = c; } } return 0; }
[ "jrjbear@gmail.com" ]
jrjbear@gmail.com
7b0550a4f53c37d3c87fa6380d12abf5bf7f0bbb
c0e2fc2049cdb611b44af8c3a656d2cd64b3b62b
/src/Sys/UsbDisk/DiskEvent.h
b94487f51aee3abd66eedac4d0f892a5731fb3bb
[ "Apache-2.0" ]
permissive
github188/SimpleCode
f9e99fd6f3f73bb8cc6c1eea2a8fd84fff8dd77d
781500a3b820e979db64672e3f2b1dc6151c5246
refs/heads/master
2021-01-19T22:53:56.256905
2016-02-02T08:02:43
2016-02-02T08:02:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
389
h
#ifndef DiskEvent_H #define DiskEvent_H #include <string> namespace Hippo { class DiskEvent{ public: DiskEvent(const std::string &event); DiskEvent(){} ~DiskEvent(){} int report(); int buildEvent(const char* desc, const char* dev, int pvrFlag); void doUsbEvent(); private: std::string m_event; };//DiskEvent };//namespace Hippo #endif //DiskEvent_H
[ "echo_eric@yeah.net" ]
echo_eric@yeah.net
600a131133e7704d093df2a7468e2f2113a00569
46efdd43ea4d9fe61bf35c02a0f9bc6dd87d4890
/libs/videoInput/include/videoInput.h
68a2e827348b7ba28f86e67fc7007db87150185a
[ "MIT" ]
permissive
danjaf2/Assignement3
601a12028f29290c87ecc97eb52f32a414a4cf5a
5fb5f31730f2cff0d53715d1161d6ce77ea9c1da
refs/heads/main
2023-04-08T22:06:19.222514
2021-04-20T00:09:27
2021-04-20T00:09:27
359,552,266
0
0
null
null
null
null
UTF-8
C++
false
false
13,263
h
#ifndef _VIDEOINPUT #define _VIDEOINPUT //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. ////////////////////////////////////////////////////////// //Written by Theodore Watson - theo.watson@gmail.com // //Do whatever you want with this code but if you find // //a bug or make an improvement I would love to know! // // // //Warning This code is experimental // //use at your own risk :) // ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// /* Shoutouts Thanks to: Dillip Kumar Kara for crossbar code. Zachary Lieberman for getting me into this stuff and for being so generous with time and code. The guys at Potion Design for helping me with VC++ Josh Fisher for being a serious C++ nerd :) Golan Levin for helping me debug the strangest and slowest bug in the world! And all the people using this library who send in bugs, suggestions and improvements who keep me working on the next version - yeah thanks a lot ;) */ ///////////////////////////////////////////////////////// #ifdef _MSC_VER #pragma comment(lib,"Strmiids.lib") #endif #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <wchar.h> #include <string> #include <vector> //this is for TryEnterCriticalSection #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x501 #endif #include <windows.h> //Example Usage /* //create a videoInput object videoInput VI; //Prints out a list of available devices and returns num of devices found int numDevices = VI.listDevices(); int device1 = 0; //this could be any deviceID that shows up in listDevices int device2 = 1; //this could be any deviceID that shows up in listDevices //if you want to capture at a different frame rate (default is 30) //specify it here, you are not guaranteed to get this fps though. //VI.setIdealFramerate(dev, 60); //setup the first device - there are a number of options: VI.setupDevice(device1); //setup the first device with the default settings //VI.setupDevice(device1, VI_COMPOSITE); //or setup device with specific connection type //VI.setupDevice(device1, 320, 240); //or setup device with specified video size //VI.setupDevice(device1, 320, 240, VI_COMPOSITE); //or setup device with video size and connection type //VI.setFormat(device1, VI_NTSC_M); //if your card doesn't remember what format it should be //call this with the appropriate format listed above //NOTE: must be called after setupDevice! //optionally setup a second (or third, fourth ...) device - same options as above VI.setupDevice(device2); //As requested width and height can not always be accomodated //make sure to check the size once the device is setup int width = VI.getWidth(device1); int height = VI.getHeight(device1); int size = VI.getSize(device1); unsigned char * yourBuffer1 = new unsigned char[size]; unsigned char * yourBuffer2 = new unsigned char[size]; //to get the data from the device first check if the data is new if(VI.isFrameNew(device1)){ VI.getPixels(device1, yourBuffer1, false, false); //fills pixels as a BGR (for openCV) unsigned char array - no flipping VI.getPixels(device1, yourBuffer2, true, true); //fills pixels as a RGB (for openGL) unsigned char array - flipping! } //same applies to device2 etc //to get a settings dialog for the device VI.showSettingsWindow(device1); //Shut down devices properly VI.stopDevice(device1); VI.stopDevice(device2); */ ////////////////////////////////////// VARS AND DEFS ////////////////////////////////// //STUFF YOU DON'T CHANGE //videoInput defines #define VI_VERSION 0.200 #define VI_MAX_CAMERAS 20 #define VI_NUM_TYPES 19 //DON'T TOUCH #define VI_NUM_FORMATS 18 //DON'T TOUCH //defines for setPhyCon - tuner is not as well supported as composite and s-video #define VI_COMPOSITE 0 #define VI_S_VIDEO 1 #define VI_TUNER 2 #define VI_USB 3 #define VI_1394 4 //defines for formats #define VI_NTSC_M 0 #define VI_PAL_B 1 #define VI_PAL_D 2 #define VI_PAL_G 3 #define VI_PAL_H 4 #define VI_PAL_I 5 #define VI_PAL_M 6 #define VI_PAL_N 7 #define VI_PAL_NC 8 #define VI_SECAM_B 9 #define VI_SECAM_D 10 #define VI_SECAM_G 11 #define VI_SECAM_H 12 #define VI_SECAM_K 13 #define VI_SECAM_K1 14 #define VI_SECAM_L 15 #define VI_NTSC_M_J 16 #define VI_NTSC_433 17 // added by gameover #define VI_MEDIASUBTYPE_RGB24 0 #define VI_MEDIASUBTYPE_RGB32 1 #define VI_MEDIASUBTYPE_RGB555 2 #define VI_MEDIASUBTYPE_RGB565 3 #define VI_MEDIASUBTYPE_YUY2 4 #define VI_MEDIASUBTYPE_YVYU 5 #define VI_MEDIASUBTYPE_YUYV 6 #define VI_MEDIASUBTYPE_IYUV 7 #define VI_MEDIASUBTYPE_UYVY 8 #define VI_MEDIASUBTYPE_YV12 9 #define VI_MEDIASUBTYPE_YVU9 10 #define VI_MEDIASUBTYPE_Y411 11 #define VI_MEDIASUBTYPE_Y41P 12 #define VI_MEDIASUBTYPE_Y211 13 #define VI_MEDIASUBTYPE_AYUV 14 #define VI_MEDIASUBTYPE_Y800 15 #define VI_MEDIASUBTYPE_Y8 16 #define VI_MEDIASUBTYPE_GREY 17 #define VI_MEDIASUBTYPE_MJPG 18 //allows us to directShow classes here with the includes in the cpp struct ICaptureGraphBuilder2; struct IGraphBuilder; struct IBaseFilter; struct IAMCrossbar; struct IMediaControl; struct ISampleGrabber; struct IMediaEventEx; struct IAMStreamConfig; struct _AMMediaType; class SampleGrabberCallback; typedef _AMMediaType AM_MEDIA_TYPE; //////////////////////////////////////// VIDEO DEVICE /////////////////////////////////// class videoDevice{ public: videoDevice(); void setSize(int w, int h); void NukeDownstream(IBaseFilter *pBF); void destroyGraph(); ~videoDevice(); int videoSize; int width; int height; int tryWidth; int tryHeight; ICaptureGraphBuilder2 *pCaptureGraph; // Capture graph builder object IGraphBuilder *pGraph; // Graph builder object IMediaControl *pControl; // Media control object IBaseFilter *pVideoInputFilter; // Video Capture filter IBaseFilter *pGrabberF; IBaseFilter * pDestFilter; IAMStreamConfig *streamConf; ISampleGrabber * pGrabber; // Grabs frame AM_MEDIA_TYPE * pAmMediaType; IMediaEventEx * pMediaEvent; GUID videoType; long formatType; SampleGrabberCallback * sgCallback; bool tryDiffSize; bool useCrossbar; bool readyToCapture; bool sizeSet; bool setupStarted; bool specificFormat; bool autoReconnect; int nFramesForReconnect; unsigned long nFramesRunning; int connection; int storeConn; int myID; long requestedFrameTime; //ie fps char nDeviceName[255]; WCHAR wDeviceName[255]; unsigned char * pixels; char * pBuffer; }; ////////////////////////////////////// VIDEO INPUT ///////////////////////////////////// class videoInput{ public: videoInput(); ~videoInput(); //turns off console messages - default is to print messages static void setVerbose(bool _verbose); //this allows for multithreaded use of VI ( default is single threaded ). //call this before any videoInput calls. //note if your app has other COM calls then you should set VIs COM usage to match the other COM mode static void setComMultiThreaded(bool bMulti); //Functions in rough order they should be used. static int listDevices(bool silent = false); static std::vector <std::string> getDeviceList(); //needs to be called after listDevices - otherwise returns NULL static const char * getDeviceName(int deviceID); static int getDeviceIDFromName(const char * name); //needs to be called after listDevices - otherwise returns empty string static const std::wstring& getUniqueDeviceName(int deviceID); static int getDeviceIDFromUniqueName(const std::wstring& uniqueName); //choose to use callback based capture - or single threaded void setUseCallback(bool useCallback); //call before setupDevice //directshow will try and get the closest possible framerate to what is requested void setIdealFramerate(int deviceID, int idealFramerate); //some devices will stop delivering frames after a while - this method gives you the option to try and reconnect //to a device if videoInput detects that a device has stopped delivering frames. //you MUST CALL isFrameNew every app loop for this to have any effect void setAutoReconnectOnFreeze(int deviceNumber, bool doReconnect, int numMissedFramesBeforeReconnect); //Choose one of these four to setup your device bool setupDevice(int deviceID); bool setupDevice(int deviceID, int w, int h); //These two are only for capture cards //USB and Firewire cameras souldn't specify connection bool setupDevice(int deviceID, int connection); bool setupDevice(int deviceID, int w, int h, int connection); //If you need to you can set your NTSC/PAL/SECAM //preference here. if it is available it will be used. //see #defines above for available formats - eg VI_NTSC_M or VI_PAL_B //should be called after setupDevice //can be called multiple times bool setFormat(int deviceNumber, int format); void setRequestedMediaSubType(int mediatype); // added by gameover //Tells you when a new frame has arrived - you should call this if you have specified setAutoReconnectOnFreeze to true bool isFrameNew(int deviceID); bool isDeviceSetup(int deviceID); //Returns the pixels - flipRedAndBlue toggles RGB/BGR flipping - and you can flip the image too unsigned char * getPixels(int deviceID, bool flipRedAndBlue = true, bool flipImage = false); //Or pass in a buffer for getPixels to fill returns true if successful. bool getPixels(int id, unsigned char * pixels, bool flipRedAndBlue = true, bool flipImage = false); //Launches a pop up settings window //For some reason in GLUT you have to call it twice each time. void showSettingsWindow(int deviceID); //Manual control over settings thanks..... //These are experimental for now. bool setVideoSettingFilter(int deviceID, long Property, long lValue, long Flags = 0, bool useDefaultValue = false); bool setVideoSettingFilterPct(int deviceID, long Property, float pctValue, long Flags = 0); bool getVideoSettingFilter(int deviceID, long Property, long &min, long &max, long &SteppingDelta, long &currentValue, long &flags, long &defaultValue); bool setVideoSettingCamera(int deviceID, long Property, long lValue, long Flags = 0, bool useDefaultValue = false); bool setVideoSettingCameraPct(int deviceID, long Property, float pctValue, long Flags = 0); bool getVideoSettingCamera(int deviceID, long Property, long &min, long &max, long &SteppingDelta, long &currentValue, long &flags, long &defaultValue); //bool setVideoSettingCam(int deviceID, long Property, long lValue, long Flags = 0, bool useDefaultValue = false); //get width, height and number of pixels int getWidth(int deviceID); int getHeight(int deviceID); int getSize(int deviceID); //completely stops and frees a device void stopDevice(int deviceID); //as above but then sets it up with same settings bool restartDevice(int deviceID); //number of devices available int devicesFound; long propBrightness; long propContrast; long propHue; long propSaturation; long propSharpness; long propGamma; long propColorEnable; long propWhiteBalance; long propBacklightCompensation; long propGain; long propPan; long propTilt; long propRoll; long propZoom; long propExposure; long propIris; long propFocus; private: void setPhyCon(int deviceID, int conn); void setAttemptCaptureSize(int deviceID, int w, int h); bool setup(int deviceID); void processPixels(unsigned char * src, unsigned char * dst, int width, int height, bool bRGB, bool bFlip); int start(int deviceID, videoDevice * VD); int getDeviceCount(); void getMediaSubtypeAsString(GUID type, char * typeAsString); HRESULT getDevice(IBaseFilter **pSrcFilter, int deviceID, WCHAR * wDeviceName, char * nDeviceName); static HRESULT ShowFilterPropertyPages(IBaseFilter *pFilter); HRESULT SaveGraphFile(IGraphBuilder *pGraph, WCHAR *wszPath); HRESULT routeCrossbar(ICaptureGraphBuilder2 **ppBuild, IBaseFilter **pVidInFilter, int conType, GUID captureMode); //don't touch static bool comInit(); static bool comUnInit(); int connection; int callbackSetCount; bool bCallback; GUID CAPTURE_MODE; GUID requestedMediaSubType; //Extra video subtypes GUID MEDIASUBTYPE_Y800; GUID MEDIASUBTYPE_Y8; GUID MEDIASUBTYPE_GREY; videoDevice * VDList[VI_MAX_CAMERAS]; GUID mediaSubtypes[VI_NUM_TYPES]; long formatTypes[VI_NUM_FORMATS]; static void __cdecl basicThread(void * objPtr); static char deviceNames[VI_MAX_CAMERAS][255]; static std::vector<std::wstring> deviceUniqueNames; }; #endif
[ "57570285+KuroiRaku@users.noreply.github.com" ]
57570285+KuroiRaku@users.noreply.github.com
9e2acaf2dafd787a7c5a472c8f98501225f0d7ab
a319e7a22a1d2d3f798dd93f3afc2997e3fb2c7a
/kalman_filter/include/kalman_common.h
13bfc7c3b4c1a95b43e4f09aa1df3a192b8d3611
[]
no_license
yueyeyuniao/Human_Robot_Plug_Task
71e92ddb2b7719afdfeb5417d4675f588ae74ccb
55d110480a0895b1ace7116e5cd13a386b1ecab5
refs/heads/main
2023-07-03T07:21:28.277590
2021-08-13T23:06:03
2021-08-13T23:06:03
362,375,580
2
0
null
null
null
null
UTF-8
C++
false
false
2,671
h
#ifndef _KALMAN_COMMON #define _KALMAN_COMMON #include <Eigen/Dense> #include <cassert> class KalmanFilter { private: /* data */ Eigen::MatrixXd A, C, Q, R, P, K, P0; int m,n; double t0, t; double dt; bool initialized; Eigen::MatrixXd I; Eigen::VectorXd x_hat, x_hat_new; public: KalmanFilter(); KalmanFilter( double dt, const Eigen::MatrixXd& A, //system model matrix x_hat_new = A*x_hat + e const Eigen::MatrixXd& C, //measurement model matrix z = C*x_hat + e const Eigen::MatrixXd& Q, //system noise covariance const Eigen::MatrixXd& R, //measurement noise covariance const Eigen::MatrixXd& P //posteriori covariance ); void init(); void init(double start_time, const Eigen::VectorXd& x0); void predict_and_update(const Eigen::VectorXd& z); void predict_and_update(const Eigen::VectorXd& z, double dt); void predict_and_update(const Eigen::VectorXd& z, double dt, const Eigen::MatrixXd& A); //return current state; Eigen::VectorXd get_state() {return x_hat;}; //return current time; double get_time() {return t;}; }; KalmanFilter::KalmanFilter(double dt, const Eigen::MatrixXd& A, const Eigen::MatrixXd& C, const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R, const Eigen::MatrixXd& P) :dt(dt), A(A), C(C), Q(Q), R(R), P0(P), m(C.rows()), n(A.rows()), initialized(false), I(Eigen::MatrixXd::Identity(n,n)), x_hat(n), x_hat_new(n) { }; KalmanFilter::KalmanFilter(){}; void KalmanFilter::init() { x_hat.setZero(); P = P0; t0 = 0; t = t0; initialized = true; } void KalmanFilter::init(double start_time, const Eigen::VectorXd& x0) { x_hat = x0; t0 = start_time; t = t0; P = P0; initialized = true; } void KalmanFilter::predict_and_update(const Eigen::VectorXd& z) { assert(initialized); //predict x_hat_new = A * x_hat; P = A*P*A.transpose() + Q; //update auto y = z - C*x_hat_new; K = P*C.transpose()*(C*P*C.transpose() + R).inverse(); x_hat_new += K*y; P = (I - K*C)*P; x_hat = x_hat_new; t += dt; } void KalmanFilter::predict_and_update(const Eigen::VectorXd& z, double dt) { this->dt = dt; predict_and_update(z); } void KalmanFilter::predict_and_update(const Eigen::VectorXd& z, double dt, const Eigen::MatrixXd& A) { this->A = A; this->dt = dt; predict_and_update(z); } #endif
[ "changpengshuai@gmail.com" ]
changpengshuai@gmail.com
e3a20170435e893cb2cb31bf3c63fd6bc97225ba
22b2d4d18d8cabb13f004c927fc8ac9845955381
/IncQol/FilterPluginUtility.h
da77258a10528bc477934482e4cdb37bc490b444
[ "MIT" ]
permissive
pmartschei/Gw2Addon
db110b68f56fd27e7aecda6abd89ff1ae134feaa
a5b1c8f1fd7d47f0b4f9706a658dbc56f6de96ca
refs/heads/master
2022-03-19T03:12:07.685469
2019-12-28T11:12:50
2019-12-28T11:12:50
111,937,889
0
0
null
null
null
null
UTF-8
C++
false
false
473
h
#ifndef FILTER_PLUGIN_UTILITY_H #define FILTER_PLUGIN_UTILITY_H #include <string> #include <algorithm> #include "imgui.h" #define STARTUP_FILTERNAME ("startup.filter") std::string GetFilterFolder(); struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { int c = tolower(data->EventChar); if ((c >= 'a' &&c <= 'z') || (c >= '0' && c <= '9') || c == 32 || c == 95 || c == 45)/// 95 = '_' , 45 = '-' return 0; return 1; } }; #endif
[ "philipp.martschei@gmx.net" ]
philipp.martschei@gmx.net