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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f8fb9422866f1cdf6da492172965bf2029e6c709 | f08b521ef07000f15e73d605bdae35b97c270053 | /Libraries/WTL/AppWizard/Files/Templates/1033/MainDlg.h | b77daf578e2eb6f6635ab143719d9f7e6594e3b2 | [
"BSL-1.0"
] | permissive | udoe/DebugViewPP | cd604c3a22d15d41c317f5e9d91a9606039905b0 | 92d9308d9f1052530bc8eec9167a9fdafe672f21 | refs/heads/master | 2020-04-25T00:29:25.756645 | 2019-03-17T17:36:19 | 2019-03-17T17:36:19 | 172,379,679 | 0 | 0 | BSL-1.0 | 2019-02-24T19:21:30 | 2019-02-24T19:21:29 | null | UTF-8 | C++ | false | false | 7,316 | h | // [!output WTL_MAINDLG_FILE].h : interface of the [!output WTL_MAINDLG_CLASS] class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
[!if WTL_APPTYPE_DLG && !WTL_APPTYPE_DLG_MODAL]
class [!output WTL_MAINDLG_CLASS] : public [!output WTL_MAINDLG_BASE_CLASS]<[!output WTL_MAINDLG_CLASS]>, public CUpdateUI<[!output WTL_MAINDLG_CLASS]>,
public CMessageFilter, public CIdleHandler
{
public:
enum { IDD = IDD_MAINDLG };
[!if WTL_USE_CPP_FILES]
virtual BOOL PreTranslateMessage(MSG* pMsg);
[!else]
virtual BOOL PreTranslateMessage(MSG* pMsg)
{
[!if WTL_HOST_AX]
if((pMsg->message < WM_KEYFIRST || pMsg->message > WM_KEYLAST) &&
(pMsg->message < WM_MOUSEFIRST || pMsg->message > WM_MOUSELAST))
return FALSE;
HWND hWndCtl = ::GetFocus();
if(IsChild(hWndCtl))
{
// find a direct child of the dialog from the window that has focus
while(::GetParent(hWndCtl) != m_hWnd)
hWndCtl = ::GetParent(hWndCtl);
// give control a chance to translate this message
if(::SendMessage(hWndCtl, WM_FORWARDMSG, 0, (LPARAM)pMsg) != 0)
return TRUE;
}
[!endif]
return CWindow::IsDialogMessage(pMsg);
}
[!endif]
[!if WTL_USE_CPP_FILES]
virtual BOOL OnIdle();
[!else]
virtual BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
[!endif]
BEGIN_UPDATE_UI_MAP([!output WTL_MAINDLG_CLASS])
END_UPDATE_UI_MAP()
BEGIN_MSG_MAP([!output WTL_MAINDLG_CLASS])
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
COMMAND_ID_HANDLER(IDOK, OnOK)
COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
END_MSG_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
[!if WTL_USE_CPP_FILES]
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// center the dialog on the screen
CenterWindow();
// set icons
HICON hIcon = AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON));
SetIcon(hIcon, TRUE);
HICON hIconSmall = AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON));
SetIcon(hIconSmall, FALSE);
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
UIAddChildWindowContainer(m_hWnd);
return TRUE;
}
[!endif]
[!if WTL_USE_CPP_FILES]
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// unregister message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->RemoveMessageFilter(this);
pLoop->RemoveIdleHandler(this);
[!if WTL_COM_SERVER]
// if UI is the last thread, no need to wait
if(_Module.GetLockCount() == 1)
{
_Module.m_dwTimeOut = 0L;
_Module.m_dwPause = 0L;
}
_Module.Unlock();
[!endif]
return 0;
}
[!endif]
[!if WTL_USE_CPP_FILES]
LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAboutDlg dlg;
dlg.DoModal();
return 0;
}
[!endif]
[!if WTL_USE_CPP_FILES]
LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
// TODO: Add validation code
CloseDialog(wID);
return 0;
}
[!endif]
[!if WTL_USE_CPP_FILES]
LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CloseDialog(wID);
return 0;
}
[!endif]
[!if WTL_USE_CPP_FILES]
void CloseDialog(int nVal);
[!else]
void CloseDialog(int nVal)
{
DestroyWindow();
::PostQuitMessage(nVal);
}
[!endif]
};
[!endif]
[!if WTL_APPTYPE_DLG && WTL_APPTYPE_DLG_MODAL]
class [!output WTL_MAINDLG_CLASS] : public [!output WTL_MAINDLG_BASE_CLASS]<[!output WTL_MAINDLG_CLASS]>
{
public:
enum { IDD = IDD_MAINDLG };
BEGIN_MSG_MAP([!output WTL_MAINDLG_CLASS])
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
[!if WTL_COM_SERVER]
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
[!endif]
COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
COMMAND_ID_HANDLER(IDOK, OnOK)
COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
END_MSG_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
[!if WTL_USE_CPP_FILES]
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
[!if WTL_COM_SERVER]
_Module.Lock();
[!endif]
// center the dialog on the screen
CenterWindow();
// set icons
HICON hIcon = AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON));
SetIcon(hIcon, TRUE);
HICON hIconSmall = AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON));
SetIcon(hIconSmall, FALSE);
return TRUE;
}
[!endif]
[!if WTL_COM_SERVER]
[!if WTL_USE_CPP_FILES]
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// if UI is the last thread, no need to wait
if(_Module.GetLockCount() == 1)
{
_Module.m_dwTimeOut = 0L;
_Module.m_dwPause = 0L;
}
_Module.Unlock();
return 0;
}
[!endif]
[!endif]
[!if WTL_USE_CPP_FILES]
LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CSimpleDialog<IDD_ABOUTBOX, FALSE> dlg;
dlg.DoModal();
return 0;
}
[!endif]
[!if WTL_USE_CPP_FILES]
LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
// TODO: Add validation code
EndDialog(wID);
return 0;
}
[!endif]
[!if WTL_USE_CPP_FILES]
LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
[!else]
LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
EndDialog(wID);
return 0;
}
[!endif]
};
[!endif]
| [
"janwilmans@gmail.com"
] | janwilmans@gmail.com |
04fcd395a7f3e9ac7eda6c35c21ae7556591519c | da2c40817423735c3300e8745b12c5ff7d13358b | /rocksdb-6.15.5/memtable/write_buffer_manager.cc | 9b74708708175d627b64d27193630f99c3c8b335 | [
"MIT",
"Apache-2.0",
"GPL-2.0-only",
"BSD-3-Clause"
] | permissive | pch6828/HYU_Graduation_Project | b894e9d19f52fc22036efdfb236b98ca6cae8991 | 5e40c8e6657da2ad912cc8c2590c5722e0907d23 | refs/heads/master | 2023-08-25T01:15:40.445679 | 2021-10-21T14:39:29 | 2021-10-21T14:39:29 | 342,797,543 | 0 | 0 | MIT | 2021-09-09T15:40:01 | 2021-02-27T07:29:27 | C++ | UTF-8 | C++ | false | false | 5,584 | cc | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "rocksdb/write_buffer_manager.h"
#include <mutex>
#include "util/coding.h"
namespace ROCKSDB_NAMESPACE {
#ifndef ROCKSDB_LITE
namespace {
const size_t kSizeDummyEntry = 256 * 1024;
// The key will be longer than keys for blocks in SST files so they won't
// conflict.
const size_t kCacheKeyPrefix = kMaxVarint64Length * 4 + 1;
} // namespace
struct WriteBufferManager::CacheRep {
std::shared_ptr<Cache> cache_;
std::mutex cache_mutex_;
std::atomic<size_t> cache_allocated_size_;
// The non-prefix part will be updated according to the ID to use.
char cache_key_[kCacheKeyPrefix + kMaxVarint64Length];
uint64_t next_cache_key_id_ = 0;
std::vector<Cache::Handle*> dummy_handles_;
explicit CacheRep(std::shared_ptr<Cache> cache)
: cache_(cache), cache_allocated_size_(0) {
memset(cache_key_, 0, kCacheKeyPrefix);
size_t pointer_size = sizeof(const void*);
assert(pointer_size <= kCacheKeyPrefix);
memcpy(cache_key_, static_cast<const void*>(this), pointer_size);
}
Slice GetNextCacheKey() {
memset(cache_key_ + kCacheKeyPrefix, 0, kMaxVarint64Length);
char* end =
EncodeVarint64(cache_key_ + kCacheKeyPrefix, next_cache_key_id_++);
return Slice(cache_key_, static_cast<size_t>(end - cache_key_));
}
};
#else
struct WriteBufferManager::CacheRep {};
#endif // ROCKSDB_LITE
WriteBufferManager::WriteBufferManager(size_t _buffer_size,
std::shared_ptr<Cache> cache)
: buffer_size_(_buffer_size),
mutable_limit_(buffer_size_ * 7 / 8),
memory_used_(0),
memory_active_(0),
cache_rep_(nullptr) {
#ifndef ROCKSDB_LITE
if (cache) {
// Construct the cache key using the pointer to this.
cache_rep_.reset(new CacheRep(cache));
}
#else
(void)cache;
#endif // ROCKSDB_LITE
}
WriteBufferManager::~WriteBufferManager() {
#ifndef ROCKSDB_LITE
if (cache_rep_) {
for (auto* handle : cache_rep_->dummy_handles_) {
if (handle != nullptr) {
cache_rep_->cache_->Release(handle, true);
}
}
}
#endif // ROCKSDB_LITE
}
// Should only be called from write thread
void WriteBufferManager::ReserveMemWithCache(size_t mem) {
#ifndef ROCKSDB_LITE
assert(cache_rep_ != nullptr);
// Use a mutex to protect various data structures. Can be optimized to a
// lock-free solution if it ends up with a performance bottleneck.
std::lock_guard<std::mutex> lock(cache_rep_->cache_mutex_);
size_t new_mem_used = memory_used_.load(std::memory_order_relaxed) + mem;
memory_used_.store(new_mem_used, std::memory_order_relaxed);
while (new_mem_used > cache_rep_->cache_allocated_size_) {
// Expand size by at least 256KB.
// Add a dummy record to the cache
Cache::Handle* handle = nullptr;
Status s =
cache_rep_->cache_->Insert(cache_rep_->GetNextCacheKey(), nullptr,
kSizeDummyEntry, nullptr, &handle);
s.PermitUncheckedError(); // TODO: What to do on error?
// We keep the handle even if insertion fails and a null handle is
// returned, so that when memory shrinks, we don't release extra
// entries from cache.
// Ideallly we should prevent this allocation from happening if
// this insertion fails. However, the callers to this code path
// are not able to handle failures properly. We'll need to improve
// it in the future.
cache_rep_->dummy_handles_.push_back(handle);
cache_rep_->cache_allocated_size_ += kSizeDummyEntry;
}
#else
(void)mem;
#endif // ROCKSDB_LITE
}
void WriteBufferManager::FreeMemWithCache(size_t mem) {
#ifndef ROCKSDB_LITE
assert(cache_rep_ != nullptr);
// Use a mutex to protect various data structures. Can be optimized to a
// lock-free solution if it ends up with a performance bottleneck.
std::lock_guard<std::mutex> lock(cache_rep_->cache_mutex_);
size_t new_mem_used = memory_used_.load(std::memory_order_relaxed) - mem;
memory_used_.store(new_mem_used, std::memory_order_relaxed);
// Gradually shrink memory costed in the block cache if the actual
// usage is less than 3/4 of what we reserve from the block cache.
// We do this because:
// 1. we don't pay the cost of the block cache immediately a memtable is
// freed, as block cache insert is expensive;
// 2. eventually, if we walk away from a temporary memtable size increase,
// we make sure shrink the memory costed in block cache over time.
// In this way, we only shrink costed memory showly even there is enough
// margin.
if (new_mem_used < cache_rep_->cache_allocated_size_ / 4 * 3 &&
cache_rep_->cache_allocated_size_ - kSizeDummyEntry > new_mem_used) {
assert(!cache_rep_->dummy_handles_.empty());
auto* handle = cache_rep_->dummy_handles_.back();
// If insert failed, handle is null so we should not release.
if (handle != nullptr) {
cache_rep_->cache_->Release(handle, true);
}
cache_rep_->dummy_handles_.pop_back();
cache_rep_->cache_allocated_size_ -= kSizeDummyEntry;
}
#else
(void)mem;
#endif // ROCKSDB_LITE
}
} // namespace ROCKSDB_NAMESPACE
| [
"pch6828@naver.com"
] | pch6828@naver.com |
4e8f8fa981d1c4b3980cfdc8562150932d22c118 | 1a9462cf8bf332d5171afe1913fba9a0fec262f8 | /externals/boost/boost/test/detail/global_typedef.hpp | 4b540f16c39a0c7e1fb13ef1aba042b8def37de5 | [
"BSD-2-Clause"
] | permissive | ugozapad/g-ray-engine | 4184fd96cd06572eb7e847cc48fbed1d0ab5767a | 6a28c26541a6f4d50b0ca666375ab45f815c9299 | refs/heads/main | 2023-06-24T06:45:37.003158 | 2021-07-23T01:16:34 | 2021-07-23T01:16:34 | 377,952,802 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,917 | hpp | // (C) Copyright Gennadiy Rozental 2001-2005.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile: global_typedef.hpp,v $
//
// Version : $Revision: 1.2 $
//
// Description : some trivial global typedefs
// ***************************************************************************
#ifndef BOOST_TEST_GLOBAL_TYPEDEF_HPP_021005GER
#define BOOST_TEST_GLOBAL_TYPEDEF_HPP_021005GER
#include <boost/test/utils/basic_cstring/basic_cstring.hpp>
#define BOOST_TEST_L( s ) boost::unit_test::const_string( s, sizeof( s ) - 1 )
#define BOOST_TEST_STRINGIZE( s ) BOOST_TEST_L( BOOST_STRINGIZE( s ) )
#define BOOST_TEST_EMPTY_STRING BOOST_TEST_L( "" )
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
typedef unsigned long counter_t;
//____________________________________________________________________________//
enum report_level { CONFIRMATION_REPORT, SHORT_REPORT, DETAILED_REPORT, NO_REPORT, INV_REPORT_LEVEL };
//____________________________________________________________________________//
enum output_format { CLF /* compiler log format */, XML /* XML */ };
//____________________________________________________________________________//
enum test_unit_type { tut_case = 0x01, tut_suite = 0x10, tut_any = 0x11 };
//____________________________________________________________________________//
typedef unsigned long test_unit_id;
const test_unit_id INV_TEST_UNIT_ID = 0xFFFFFFFF;
const test_unit_id MAX_TEST_CASE_ID = 0xFFFFFFFE;
const test_unit_id MIN_TEST_CASE_ID = 0x00010000;
const test_unit_id MAX_TEST_SUITE_ID = 0x0000FF00;
const test_unit_id MIN_TEST_SUITE_ID = 0x00000001;
//____________________________________________________________________________//
inline test_unit_type
test_id_2_unit_type( test_unit_id id )
{
return (id & 0xFFFF0000) != 0 ? tut_case : tut_suite;
}
//____________________________________________________________________________//
} // namespace unit_test
} // namespace boost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
// ***************************************************************************
// Revision History :
//
// $Log: global_typedef.hpp,v $
// Revision 1.2 2006/03/15 03:18:29 rogeeff
// made literal resizable
//
// Revision 1.1 2005/02/20 08:27:06 rogeeff
// This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// ***************************************************************************
#endif // BOOST_TEST_GLOBAL_TYPEDEF_HPP_021005GER
| [
"hp1link2@gmail.com"
] | hp1link2@gmail.com |
634b59a2a9cd22c4bd961f3e3c775b108ae3c7cd | 2e0d0f46edd5dd116aef39ab5db12653e9303e20 | /MindFlayer4.0/mfViewport.cpp | a2084f3eb201670b1ffeaefc6c9e05900db9b1a5 | [] | no_license | charre2017idv/DirectXTesting | 3f63ab740d3cd809012e6d07ea9489bc3623fc38 | a3da7be7cd9c2921558bdc30178919ee5f44c632 | refs/heads/master | 2020-08-30T09:51:27.046531 | 2019-10-29T16:57:26 | 2019-10-29T16:57:26 | 218,338,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | /**
* @LC : 13/10/2019
* @file : mfViewport.h
* @Author : Roberto Charreton (idv17c.rcharreton@uartesdigitales.edu.mx)
* @date : 13/10/2019
* @brief : Class in charge of setting the viewport.
* @bug : No known bugs.
*/
#include "mfViewport.h"
mfViewport::mfViewport()
{
}
mfViewport::~mfViewport()
{
}
void mfViewport::Init(mfViewportDesc _Desc)
{
m_descriptor = _Desc;
mfRenderManager::getSingleton().RSSetViewports(*this);
}
mfViewportDesc & mfViewport::getDescriptor()
{
return m_descriptor;
} | [
"idv17c.rcharreton@uartesdigitales.edu.mx"
] | idv17c.rcharreton@uartesdigitales.edu.mx |
a166419bc3405cce5698bfe8b4fe54cc6b247717 | 77170cbcd2c87952763f770d50abd2d8b671f9d2 | /aws-cpp-sdk-route53/include/aws/route53/model/ListHostedZonesRequest.h | 46fe85b0f0339ba5b795e4efe38046827d391140 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | bittorrent/aws-sdk-cpp | 795f1cdffb92f6fccb4396d8f885f7bf99829ce7 | 3f84fee22a0f4d5926aadf8d3303ea15a76421fd | refs/heads/master | 2020-12-03T00:41:12.194688 | 2016-03-04T01:41:51 | 2016-03-04T01:41:51 | 53,150,048 | 1 | 1 | null | 2016-03-04T16:43:12 | 2016-03-04T16:43:12 | null | UTF-8 | C++ | false | false | 7,207 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/route53/Route53_EXPORTS.h>
#include <aws/route53/Route53Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Http
{
class URI;
} //namespace Http
namespace Route53
{
namespace Model
{
/**
* <p>To retrieve a list of your hosted zones, send a <code>GET</code> request to
* the <code>/<i>Route 53 API version</i>/hostedzone</code> resource. The response
* to this request includes a <code>HostedZones</code> element with zero or more
* <code>HostedZone</code> child elements. By default, the list of hosted zones is
* displayed on a single page. You can control the length of the page that is
* displayed by using the <code>MaxItems</code> parameter. You can use the
* <code>Marker</code> parameter to control the hosted zone that the list begins
* with. For more information about listing hosted zones, see <a
* href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ListInfoOnHostedZone.html">Listing
* the Hosted Zones for an AWS Account</a> in the <i>Amazon Route 53 Developer
* Guide</i>.</p> <note> Amazon Route 53 returns a maximum of 100 items. If you set
* <code>MaxItems</code> to a value greater than 100, Amazon Route 53 returns only
* the first 100.</note>
*/
class AWS_ROUTE53_API ListHostedZonesRequest : public Route53Request
{
public:
ListHostedZonesRequest();
Aws::String SerializePayload() const override;
void AddQueryStringParameters(Aws::Http::URI& uri) const override;
/**
* <p>If the request returned more than one page of results, submit another request
* and specify the value of <code>NextMarker</code> from the last response in the
* <code>marker</code> parameter to get the next page of results.</p>
*/
inline const Aws::String& GetMarker() const{ return m_marker; }
/**
* <p>If the request returned more than one page of results, submit another request
* and specify the value of <code>NextMarker</code> from the last response in the
* <code>marker</code> parameter to get the next page of results.</p>
*/
inline void SetMarker(const Aws::String& value) { m_markerHasBeenSet = true; m_marker = value; }
/**
* <p>If the request returned more than one page of results, submit another request
* and specify the value of <code>NextMarker</code> from the last response in the
* <code>marker</code> parameter to get the next page of results.</p>
*/
inline void SetMarker(Aws::String&& value) { m_markerHasBeenSet = true; m_marker = value; }
/**
* <p>If the request returned more than one page of results, submit another request
* and specify the value of <code>NextMarker</code> from the last response in the
* <code>marker</code> parameter to get the next page of results.</p>
*/
inline void SetMarker(const char* value) { m_markerHasBeenSet = true; m_marker.assign(value); }
/**
* <p>If the request returned more than one page of results, submit another request
* and specify the value of <code>NextMarker</code> from the last response in the
* <code>marker</code> parameter to get the next page of results.</p>
*/
inline ListHostedZonesRequest& WithMarker(const Aws::String& value) { SetMarker(value); return *this;}
/**
* <p>If the request returned more than one page of results, submit another request
* and specify the value of <code>NextMarker</code> from the last response in the
* <code>marker</code> parameter to get the next page of results.</p>
*/
inline ListHostedZonesRequest& WithMarker(Aws::String&& value) { SetMarker(value); return *this;}
/**
* <p>If the request returned more than one page of results, submit another request
* and specify the value of <code>NextMarker</code> from the last response in the
* <code>marker</code> parameter to get the next page of results.</p>
*/
inline ListHostedZonesRequest& WithMarker(const char* value) { SetMarker(value); return *this;}
/**
* <p>Specify the maximum number of hosted zones to return per page of results.</p>
*/
inline const Aws::String& GetMaxItems() const{ return m_maxItems; }
/**
* <p>Specify the maximum number of hosted zones to return per page of results.</p>
*/
inline void SetMaxItems(const Aws::String& value) { m_maxItemsHasBeenSet = true; m_maxItems = value; }
/**
* <p>Specify the maximum number of hosted zones to return per page of results.</p>
*/
inline void SetMaxItems(Aws::String&& value) { m_maxItemsHasBeenSet = true; m_maxItems = value; }
/**
* <p>Specify the maximum number of hosted zones to return per page of results.</p>
*/
inline void SetMaxItems(const char* value) { m_maxItemsHasBeenSet = true; m_maxItems.assign(value); }
/**
* <p>Specify the maximum number of hosted zones to return per page of results.</p>
*/
inline ListHostedZonesRequest& WithMaxItems(const Aws::String& value) { SetMaxItems(value); return *this;}
/**
* <p>Specify the maximum number of hosted zones to return per page of results.</p>
*/
inline ListHostedZonesRequest& WithMaxItems(Aws::String&& value) { SetMaxItems(value); return *this;}
/**
* <p>Specify the maximum number of hosted zones to return per page of results.</p>
*/
inline ListHostedZonesRequest& WithMaxItems(const char* value) { SetMaxItems(value); return *this;}
inline const Aws::String& GetDelegationSetId() const{ return m_delegationSetId; }
inline void SetDelegationSetId(const Aws::String& value) { m_delegationSetIdHasBeenSet = true; m_delegationSetId = value; }
inline void SetDelegationSetId(Aws::String&& value) { m_delegationSetIdHasBeenSet = true; m_delegationSetId = value; }
inline void SetDelegationSetId(const char* value) { m_delegationSetIdHasBeenSet = true; m_delegationSetId.assign(value); }
inline ListHostedZonesRequest& WithDelegationSetId(const Aws::String& value) { SetDelegationSetId(value); return *this;}
inline ListHostedZonesRequest& WithDelegationSetId(Aws::String&& value) { SetDelegationSetId(value); return *this;}
inline ListHostedZonesRequest& WithDelegationSetId(const char* value) { SetDelegationSetId(value); return *this;}
private:
Aws::String m_marker;
bool m_markerHasBeenSet;
Aws::String m_maxItems;
bool m_maxItemsHasBeenSet;
Aws::String m_delegationSetId;
bool m_delegationSetIdHasBeenSet;
};
} // namespace Model
} // namespace Route53
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
e02bde0aed91226ea089652ca91baf73995bc919 | 1e4398a2f32ad03df63f7ff33f14e86368fafed5 | /Source/Main.cpp | d97e3959ceffc787e4bcb9c53d074ad52ca5b6f9 | [] | no_license | scristianpopa/Skyroads | 9924fd6e9cce308f123471a5b3eba23f042fb16e | 39d9835bcbf850b284d6e32b765045b046cb9ec9 | refs/heads/main | 2023-01-30T00:04:04.453569 | 2020-12-14T17:35:50 | 2020-12-14T17:35:50 | 321,424,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | cpp | #include <ctime>
#include <iostream>
using namespace std;
#include <Core/Engine.h>
#include <Headers.h>
int main(int argc, char **argv)
{
srand((unsigned int)time(NULL));
// Create a window property structure
WindowProperties wp;
wp.resolution = glm::ivec2(1280, 720);
wp.name = "EGC";
// Init the Engine and create a new window with the defined properties
WindowObject* window = Engine::Init(wp);
// Create a new 3D world and start running it
World *world = new Skyroads();
world->Init();
world->Run();
// Signals to the Engine to release the OpenGL context
Engine::Exit();
return 0;
} | [
"sodracri1999@gmail.com"
] | sodracri1999@gmail.com |
96101ef5f33c1a3b2e1e20426856ac8b52609252 | 77fe2e69f968ad5d413b909f2e833d2137331115 | /mainwindow.cpp | d62fd45b8598cef797cd4d794465df0f15950189 | [] | no_license | leoska/qt_dbclient | 8727b5da7205bb41b99c26bf2334380be34994f8 | 96cba6f8178c49ce182b20a1b283b45762ff61f3 | refs/heads/master | 2021-01-18T22:29:08.800426 | 2016-11-01T16:41:15 | 2016-11-01T16:41:15 | 72,555,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,141 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
app = new LoginForm();
connect(app, SIGNAL(DBAllow()), this, SLOT(DBAllowed()));
work = new WorkerForm();
connect(work, SIGNAL(WorkAdd(QString, QString, int)), this, SLOT(WorkerAdd(QString ,QString, int)));
depr = new DepartForm();
connect(depr, SIGNAL(DeprAdd(QString, QString, QString, QDateTime)), this, SLOT(DepartmentAdd(QString, QString, QString, QDateTime)));
vis = new VisitForm();
connect(vis, SIGNAL(VisAdd(int,int,QDateTime,QDateTime,QDateTime,QString,QString)), this, SLOT(VisitAdd(int,int,QDateTime,QDateTime,QDateTime,QString,QString)));
db = QSqlDatabase::addDatabase("QODBC");
}
MainWindow::~MainWindow()
{
delete ui;
delete app;
delete work;
delete depr;
db.close();
}
void MainWindow::AddLog(const QString str)
{
QDateTime tim(QDateTime::currentDateTime());
ui->textEdit->insertPlainText("[" + tim.toString("H:mm:ss") + "] " + str + "\n");
}
void MainWindow::DBAllowed()
{
qDebug() << "Eeeee";
modelka = new QSqlQueryModel();
modelka->setQuery("SELECT ID, FirstName, LastName FROM dbo.info");
ui->tableView->setModel(modelka);
ui->tableView->show();
/*modelka = new QSqlTableModel(this, db);
modelka->setTable("info");
modelka->setEditStrategy(QSqlTableModel::OnFieldChange);
modelka->select();
ui->tableView->setModel(modelka);*/
AddLog("Successful connection!");
}
void MainWindow::WorkerAdd(QString fname, QString lname, int age)
{
QSqlQuery qry;
qry.prepare("{ CALL dbo.NewWorker(?, ?, ?) }");
qry.bindValue(0, fname);
qry.bindValue(1, lname);
qry.bindValue(2, age);
AddLog((qry.exec()) ? "Worker is successfully added!" : "Error: Worker is not added!");
}
void MainWindow::DepartmentAdd(QString man, QString prj, QString subdiv, QDateTime tim)
{
QSqlQuery qry;
qry.prepare("{ CALL dbo.NewDepartment(?, ?, ?, ?) }");
qry.bindValue(0, man);
qry.bindValue(1, prj);
qry.bindValue(2, subdiv);
qry.bindValue(3, tim);
AddLog((qry.exec()) ? "Department is successfully added!" : "Error: Department is not added!");
}
void MainWindow::VisitAdd(int id1, int id2, QDateTime date, QDateTime enter, QDateTime leave, QString code, QString comments)
{
QSqlQuery qry;
qry.prepare("{ CALL dbo.NewVisit(?, ?, ?, ?, ?, ?, ?) }");
qry.bindValue(0, id1);
qry.bindValue(1, id2);
qry.bindValue(2, date);
qry.bindValue(3, enter);
qry.bindValue(4, leave);
qry.bindValue(5, code);
qry.bindValue(6, comments);
AddLog((qry.exec()) ? "Visit is successfully added!" : "Error: Visit is not added!");
}
void MainWindow::on_actionConnect_to_Database_triggered()
{
app->setDBPointer(&db);
app->show();
}
void MainWindow::on_actionAdd_New_Worker_triggered()
{
work->show();
}
void MainWindow::on_actionAdd_New_Department_triggered()
{
depr->show();
}
void MainWindow::on_actionAdd_New_Visit_triggered()
{
vis->DataUpdate(db);
vis->show();
}
| [
"leo77551@gmail.com"
] | leo77551@gmail.com |
86eb2b47aae74616441a81381fe4b98b38cbc42b | 8fdea23d0eb541bb076f77f9ba02ebf5446de1a0 | /src/ofxCv/ContourFinder.cpp | 116d4068c21df9d4af287ddb217ac1547169e478 | [] | no_license | brannondorsey/LEDWallInteractive | 928790a7bf1c54f986df6048c6a42aeff74a95f2 | c8d582061c3811b738ddfe11a06c1d7363ada96e | refs/heads/master | 2021-01-10T14:21:03.476893 | 2016-02-08T18:30:32 | 2016-02-08T18:30:32 | 50,591,829 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,891 | cpp | #include "ContourFinder.h"
#include "Wrappers.h"
namespace ofxCv {
struct CompareContourArea
{
CompareContourArea(const std::vector<double>& areaVec)
: mAreaVec(areaVec) {}
// Sort contour indices into decreasing order, based on a vector of
// contour areas. Later, we will use these indices to order the
// contours (which are stored in a separate vector).
bool operator()(size_t a, size_t b) const
{
return mAreaVec[a] > mAreaVec[b];
}
const std::vector<double>& mAreaVec;
};
using namespace cv;
ContourFinder::ContourFinder()
:autoThreshold(true)
,invert(false)
,simplify(true)
,thresholdValue(128.)
,useTargetColor(false)
,contourFindingMode(CV_RETR_EXTERNAL)
,sortBySize(false) {
resetMinArea();
resetMaxArea();
}
void ContourFinder::findContours(Mat img) {
// threshold the image using a tracked color or just binary grayscale
if(useTargetColor) {
Scalar offset(thresholdValue, thresholdValue, thresholdValue);
Scalar base = toCv(targetColor);
if(trackingColorMode == TRACK_COLOR_RGB) {
inRange(img, base - offset, base + offset, thresh);
} else {
if(trackingColorMode == TRACK_COLOR_H) {
offset[1] = 255;
offset[2] = 255;
}
if(trackingColorMode == TRACK_COLOR_HS) {
offset[2] = 255;
}
cvtColor(img, hsvBuffer, CV_RGB2HSV);
base = toCv(convertColor(targetColor, CV_RGB2HSV));
Scalar lowerb = base - offset;
Scalar upperb = base + offset;
inRange(hsvBuffer, lowerb, upperb, thresh);
}
} else {
copyGray(img, thresh);
}
if(autoThreshold) {
threshold(thresh, thresholdValue, invert);
}
// run the contour finder
vector<vector<cv::Point> > allContours;
int simplifyMode = simplify ? CV_CHAIN_APPROX_SIMPLE : CV_CHAIN_APPROX_NONE;
cv::findContours(thresh, allContours, contourFindingMode, simplifyMode);
// filter the contours
bool needMinFilter = (minArea > 0);
bool needMaxFilter = maxAreaNorm ? (maxArea < 1) : (maxArea < numeric_limits<float>::infinity());
vector<size_t> allIndices;
vector<double> allAreas;
if(needMinFilter || needMaxFilter) {
double imgArea = img.rows * img.cols;
double imgMinArea = minAreaNorm ? (minArea * imgArea) : minArea;
double imgMaxArea = maxAreaNorm ? (maxArea * imgArea) : maxArea;
for(size_t i = 0; i < allContours.size(); i++) {
double curArea = contourArea(Mat(allContours[i]));
allAreas.push_back(curArea);
if((!needMinFilter || curArea >= imgMinArea) &&
(!needMaxFilter || curArea <= imgMaxArea)) {
allIndices.push_back(i);
}
}
} else {
for(size_t i = 0; i < allContours.size(); i++) {
if (sortBySize) {
allAreas.push_back(contourArea(allContours[i]));
}
allIndices.push_back(i);
}
}
if (allIndices.size() > 1 && sortBySize) {
// Sort contour indices, based on a separate vector of areas.
std::sort(allIndices.begin(), allIndices.end(), CompareContourArea(allAreas));
}
// generate polylines and bounding boxes from the contours
contours.clear();
polylines.clear();
boundingRects.clear();
for(size_t i = 0; i < allIndices.size(); i++) {
contours.push_back(allContours[allIndices[i]]);
polylines.push_back(toOf(contours[i]));
boundingRects.push_back(boundingRect(contours[i]));
}
// track bounding boxes
tracker.track(boundingRects);
}
void ContourFinder::setFindHoles(bool findHoles){
if(findHoles){
contourFindingMode = CV_RETR_LIST;
}else{
contourFindingMode = CV_RETR_EXTERNAL;
}
}
void ContourFinder::setSortBySize(bool sizeSort) {
sortBySize = sizeSort;
}
const vector<vector<cv::Point> >& ContourFinder::getContours() const {
return contours;
}
const vector<ofPolyline>& ContourFinder::getPolylines() const {
return polylines;
}
const vector<cv::Rect>& ContourFinder::getBoundingRects() const {
return boundingRects;
}
unsigned int ContourFinder::size() const {
return contours.size();
}
vector<cv::Point>& ContourFinder::getContour(unsigned int i) {
return contours[i];
}
ofPolyline& ContourFinder::getPolyline(unsigned int i) {
return polylines[i];
}
cv::Rect ContourFinder::getBoundingRect(unsigned int i) const {
return boundingRects[i];
}
cv::Point2f ContourFinder::getCenter(unsigned int i) const {
cv::Rect box = getBoundingRect(i);
return cv::Point2f(box.x + box.width / 2, box.y + box.height / 2);
}
cv::Point2f ContourFinder::getCentroid(unsigned int i) const {
Moments m = moments(contours[i]);
return cv::Point2f(m.m10 / m.m00, m.m01 / m.m00);
}
cv::Point2f ContourFinder::getAverage(unsigned int i) const {
Scalar average = mean(contours[i]);
return cv::Point2f(average[0], average[1]);
}
cv::Vec2f ContourFinder::getBalance(unsigned int i) const {
return cv::Vec2f(getCentroid(i) - getCenter(i));
}
double ContourFinder::getContourArea(unsigned int i) const {
return contourArea(contours[i]);
}
double ContourFinder::getArcLength(unsigned int i) const {
return arcLength(contours[i], true);
}
vector<cv::Point> ContourFinder::getConvexHull(unsigned int i) const {
vector<cv::Point> hull;
convexHull(contours[i], hull);
return hull;
}
vector<cv::Vec4i> ContourFinder::getConvexityDefects(unsigned int i) const {
return convexityDefects(contours[i]);
}
cv::RotatedRect ContourFinder::getMinAreaRect(unsigned int i) const {
return minAreaRect(contours[i]);
}
cv::Point2f ContourFinder::getMinEnclosingCircle(unsigned int i, float& radius) const {
cv::Point2f center;
minEnclosingCircle(contours[i], center, radius);
return center;
}
cv::RotatedRect ContourFinder::getFitEllipse(unsigned int i) const {
if(contours[i].size() < 5) {
return getMinAreaRect(i);
}
return fitEllipse(contours[i]);
}
vector<cv::Point> ContourFinder::getFitQuad(unsigned int i) const {
vector<cv::Point> convexHull = getConvexHull(i);
vector<cv::Point> quad = convexHull;
static const unsigned int targetPoints = 4;
static const unsigned int maxIterations = 16;
static const double infinity = numeric_limits<double>::infinity();
double minEpsilon = 0;
double maxEpsilon = infinity;
double curEpsilon = 16; // good initial guess
// unbounded binary search to simplify the convex hull until it's 4 points
if(quad.size() > 4) {
for(int i = 0; i <(int) maxIterations; i++) {
approxPolyDP(Mat(convexHull), quad, curEpsilon, true);
if(quad.size() == targetPoints) {
break;
}
if(quad.size() > targetPoints) {
minEpsilon = curEpsilon;
if(maxEpsilon == infinity) {
curEpsilon = curEpsilon * 2;
} else {
curEpsilon = (maxEpsilon + minEpsilon) / 2;
}
}
if(quad.size() < targetPoints) {
maxEpsilon = curEpsilon;
curEpsilon = (maxEpsilon + minEpsilon) / 2;
}
}
}
return quad;
}
cv::Vec2f ContourFinder::getVelocity(unsigned int i) const {
return tracker.getVelocity(i);
}
unsigned int ContourFinder::getLabel(unsigned int i) const {
return tracker.getCurrentLabels()[i];
}
RectTracker& ContourFinder::getTracker() {
return tracker;
}
void ContourFinder::setAutoThreshold(bool autoThreshold) {
this->autoThreshold = autoThreshold;
}
void ContourFinder::setThreshold(float thresholdValue) {
this->thresholdValue = thresholdValue;
}
void ContourFinder::setInvert(bool invert) {
this->invert = invert;
}
void ContourFinder::setUseTargetColor(bool useTargetColor) {
this->useTargetColor = useTargetColor;
}
void ContourFinder::setTargetColor(ofColor targetColor, TrackingColorMode trackingColorMode) {
useTargetColor = true;
this->targetColor = targetColor;
this->trackingColorMode = trackingColorMode;
}
void ContourFinder::setSimplify(bool simplify) {
this->simplify = simplify;
}
void ContourFinder::draw() {
ofPushStyle();
ofNoFill();
for(int i = 0; i < (int)polylines.size(); i++) {
polylines[i].draw();
ofRect(toOf(getBoundingRect(i)));
}
ofPopStyle();
}
void ContourFinder::resetMinArea() {
setMinArea(0);
}
void ContourFinder::resetMaxArea() {
setMaxArea(numeric_limits<float>::infinity());
}
void ContourFinder::setMinArea(float minArea) {
this->minArea = minArea;
minAreaNorm = false;
}
void ContourFinder::setMaxArea(float maxArea) {
this->maxArea = maxArea;
maxAreaNorm = false;
}
void ContourFinder::setMinAreaRadius(float minAreaRadius) {
minArea = PI * minAreaRadius * minAreaRadius;
minAreaNorm = false;
}
void ContourFinder::setMaxAreaRadius(float maxAreaRadius) {
maxArea = PI * maxAreaRadius * maxAreaRadius;
maxAreaNorm = false;
}
void ContourFinder::setMinAreaNorm(float minAreaNorm) {
minArea = minAreaNorm;
this->minAreaNorm = true;
}
void ContourFinder::setMaxAreaNorm(float maxAreaNorm) {
maxArea = maxAreaNorm;
this->maxAreaNorm = true;
}
}
| [
"brannon@brannondorsey.com"
] | brannon@brannondorsey.com |
83f66c9658d77b91170afb616b51e89de1deb840 | 5bb50c2565a7e38f6635873989faa944473d5663 | /VanyaOpenGL/RigidBody.h | 6c170fd0b3b62719563709b95e5d5f491dc757d4 | [] | no_license | liuwei792966953/cloth191210-opengl | ce3ab89fca04ef4e724bd7d47fba5eb61118ec8b | a392923a6ea1cd00772037413b783c5b4bc813e7 | refs/heads/master | 2020-09-29T19:02:45.187081 | 2017-04-02T21:10:36 | 2017-04-02T21:10:36 | 227,100,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,343 | h | #pragma once
#ifndef _RIGIDBODY_H_
#define _RIGIDBODY_H_
#include <vector>
#include <glm/glm.hpp> // GLM Mathematics
#include <glm/gtc/matrix_access.hpp>
#include "Mesh.h"
#include "Model.h"
#include "BoundingObject.h"
#include "DistanceChecks.h"
#define NUM_RIGIDBODIES 3
class RigidBody
{
private:
float IbodyVal;
public:
int bodyID;
/* Constant quantities */
//Mass
float mass; //doesn't change
//Inverse mass
float massInv;
//Ibody
glm::mat3 Ibody;
//Inverse Ibody
glm::mat3 IbodyInv;
/* State variables */
//position x(t)
glm::vec3 position;
//Orientation Matrix R(t)
glm::mat3 orientationMatrix;
//P(t)
glm::vec3 linearMomentum;
//L(t)
glm::vec3 angularMomentum;
/* Derived quantities (auxiliary variables) */
//Inertial tensor matrix Iinv
glm::mat3 tensorMatrix;
//velocity v(t)
glm::vec3 velocity;
//angular velocity w(t)
glm::vec3 angVelocity;
/* Computed quantities */
std::vector <glm::vec3> forces;
glm::vec3 netforce;
glm::vec3 nettorque;
//Model
Model model;
Model modelCopy;
// 12 cube vertices vector (removes repitition of vertices)
vector <glm::vec3> modelVertices;
// For setting the bounding box
GLfloat minX = 0.0f, maxX = 0.0f, minY = 0.0f, maxY = 0.0f, minZ = 0.0f, maxZ = 0.0f;
GLfloat xDist, yDist, zDist;
//Collision
BoundingSphere boundSphere;
AABoundingBox boundBox;
DistanceChecker dChecker;
bool gravityF = true;
bool dragF = true;
bool springF = false;
bool broadPhaseCollision = false;
bool narrowPhaseCollision = false;
glm::vec4 boundBoxColour;
//default constructor
RigidBody()
{
mass = 2.0f;
massInv = 1 / mass;
position = glm::vec3(0.0f, 0.0f, 0.0f);
velocity = glm::vec3(0.0f, 0.0f, 0.0f);
angVelocity = glm::vec3(0.0f, 0.0f, 0.0f);
Ibody = calcIbody();
IbodyInv = glm::inverse(Ibody);
boundSphere.center = position;
}
// Update position + orientation matrix
void Update(float timestep)
{
//Update the vertices
vertexUpdate();
//Update
position += velocity * timestep;
glm::mat3 AngVMatrix(0.0f);
AngVMatrix[0].x = 0.0f;
AngVMatrix[0].y = angVelocity.z;
AngVMatrix[0].z = -angVelocity.y;
AngVMatrix[1].x = -angVelocity.z;
AngVMatrix[1].y = 0.0f;
AngVMatrix[1].z = angVelocity.x;
AngVMatrix[2].x = angVelocity.y;
AngVMatrix[2].y = -angVelocity.x;
AngVMatrix[2].z = 0.0f;
orientationMatrix = orientationMatrix + (orientationMatrix * AngVMatrix * timestep);
//reorthonormalize the R(t)
orientationMatrix = glm::orthonormalize(orientationMatrix);
ApplyForceAndTorque(timestep);
//collision update
BroadPhase();
}
#pragma region "Collision Handling"
void BroadPhase()
{
getBoundingSphere();
getBoundingBox();
flagCollision();
}
void flagCollision()
{
if (broadPhaseCollision)
this->boundBoxColour = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);
else
this->boundBoxColour = glm::vec4(0.0f, 1.0f, 0.0f, 1.0f);
}
void getBoundingSphere()
{
boundSphere.center = position;
//boundSphere.radius = 0.45f;
boundSphere.radius = 0.5f;
}
void getBoundingBox()
{
xDist = glm::abs(minX - maxX) + 0.01f;
yDist = glm::abs(minY - maxY) + 0.01f;
zDist = glm::abs(minZ - maxZ) + 0.01f;
/*boundBox.posX = position.x + xDist / 2;
boundBox.negX = position.x - xDist / 2;
boundBox.posY = position.y + yDist / 2;
boundBox.negY = position.y - yDist / 2;
boundBox.posZ = position.z + zDist / 2;
boundBox.negZ = position.z - zDist / 2;*/
boundBox.posX = position.x + maxX + 0.1f;
boundBox.negX = position.x + minX + 0.1f;
boundBox.posY = position.y + maxY + 0.1f;
boundBox.negY = position.y + minY + 0.1f;
boundBox.posZ = position.z + maxZ + 0.1f;
boundBox.negZ = position.z + minZ + 0.1f;
}
void getModelMaxMin(glm::vec3 vertexPos)
{
//Sets the max and min for xyz everytime the model is drawn
GLfloat vPx = glm::normalize(vertexPos.x);
GLfloat vPy = glm::normalize(vertexPos.y);
GLfloat vPz = glm::normalize(vertexPos.z);
if (vertexPos.x < minX) minX = vertexPos.x;
if (vertexPos.y < minY) minY = vertexPos.y;
if (vertexPos.z < minZ) minZ = vertexPos.z;
if (vertexPos.x > maxX) maxX = vertexPos.x;
if (vertexPos.y > maxY) maxY = vertexPos.y;
if (vertexPos.z > maxZ) maxZ = vertexPos.z;
}
#pragma endregion
#pragma region "Forces/Torques"
void ApplyForceAndTorque(float timestep)
{
calcNetForce(gravityF, dragF, springF);
calcNetTorque();
//apply force(s)
for (int i = 0; i < forces.size(); i++)
{
//glm::vec3 force1 = forces[i];
applyForce(forces[i], timestep);
}
// applyTorque(timestep);
}
void applyImpulseForce(glm::vec3 Jmpulse)
{
velocity += Jmpulse * massInv;
}
void applyImpulseTorque(glm::vec3 Jmpulse, glm::vec3 ra)
{
angVelocity += tensorMatrix * glm::cross(ra, Jmpulse);
}
void applyForce(glm::vec3 force, float timestep)
{
velocity += (force * timestep) / mass;
}
void applyTorque(float timestep)
{
calcIinv();
angVelocity += tensorMatrix * nettorque * timestep;
}
void calcNetForce(bool grav, bool drag, bool spring)
{
//recalculate force
forces.clear();
if (grav)
{
glm::vec3 gravity(0.0f, -0.0981, 0.0f);
gravity = gravity * mass;
forces.push_back(gravity);
}
if (drag)
{
float dragCoefficient = 0.08f;
glm::vec3 dragForce = -velocity * dragCoefficient;
forces.push_back(dragForce);
}
if (spring)
{
// NB not working currently
float springK = 0.52f;
float kDrag = 0.5f;
glm::vec3 springCenter;
springCenter.x = -springK * (glm::length(position.x) - 2.0f); // +kDrag *(glm::dot(velocity.x, position.x) / glm::length(position.x)) * (position.x / glm::length(position.x));
springCenter.y = -springK * (glm::length(position.y) - 2.0f); // +kDrag * (glm::dot(velocity.y, position.y) / glm::length(position.y)) * (position.y / glm::length(position.y));
springCenter.z = -springK * (glm::length(position.z) - 2.0f); // +kDrag * (glm::dot(velocity.z, position.z) / glm::length(position.z)) * (position.z / glm::length(position.z));
springCenter = -springCenter;
glm::vec3 nSpringCenter = -springCenter;
//forces.push_back(springCenter);
}
//force = gravity + dragForce + springCenter;
}
void calcNetTorque()
{
glm::vec3 torqueSum;
//for (int i = 0; i < model.meshes.size(); i++)
//{
// for (int j = 0; j < model.meshes[i].vertices.size(); j++)
// {
// Vertex &vertex = model.meshes[i].vertices[j];
// //Calc the torque at that vertex
// for (int i = 0; i < forces.size(); i++)
// {
// torqueSum += glm::cross((vertex.Position - position), forces[i]);
// }
// }
//}
for (int i = 0; i < modelVertices.size(); i++)
{
//if(narrowPhaseCollision)
//Calc the torque at that vertex
for (int j = 0; j < forces.size(); j++)
{
torqueSum += glm::cross((modelVertices[1] - position), forces[j]); // apply force to one position?
}
}
//Calc net torque
this->nettorque = torqueSum;
}
#pragma endregion
#pragma region "Updating/Correcting"
void vertexUpdate()
{
//Reset the vertices vector
modelVertices.clear();
//Reset the bounding box
minX = position.x - 0.5f, maxX = position.x + 0.5f, minY = position.y - 0.5f, maxY = position.y + 0.5f, minZ = position.z - 0.5f, maxZ = position.z + 0.5f;
//Update the model vertex positions
for (int i = 0; i < model.meshes.size(); i++)
{
for (int j = 0; j < model.meshes[i].vertices.size(); j++)
{
Vertex &vertex = model.meshes[i].vertices[j];
Vertex &unchanged = modelCopy.meshes[i].vertices[j];
vertex.Position = geometryDrawUpdatePerVertex(unchanged.Position);
vertex.Normal = orientationMatrix * vertex.Normal;
getModelMaxMin(vertex.Position);
if (j < 8)
{
//add to the vertices
modelVertices.push_back(vertex.Position);
//std::cout << j << " : " << modelVertices[j].x << " " << modelVertices[j].y << " " << modelVertices[j].z << std::endl;
}
}
model.meshes[i].setupMesh();
}
}
glm::vec3 geometryDrawUpdatePerVertex(glm::vec3 vertex)
{
glm::vec3 newvertex = (orientationMatrix * vertex) + position;
return newvertex;
}
glm::mat3 reorthonormOrientationMatrix(glm::mat3 orientationMatrix)
{
glm::vec3 Cx = orientationMatrix[0];
glm::vec3 Cy = orientationMatrix[1];
glm::vec3 Cz = orientationMatrix[2];
Cx = Cx / (glm::length(Cx));
Cy = glm::cross(Cz, Cx);
Cy = Cy / (glm::length(Cy));
Cz = glm::cross(Cz, Cx);
Cz = Cz / (glm::length(Cz));
orientationMatrix[0] = Cx;
orientationMatrix[1] = Cy;
orientationMatrix[2] = Cz;
}
glm::mat3 gramSchmidt(glm::mat3 orientationMatrix)
{
glm::vec3 r1 = glm::row(orientationMatrix, 0);
glm::vec3 r2 = glm::row(orientationMatrix, 1);
glm::vec3 r3 = glm::row(orientationMatrix, 2);
float k = 0.25f;
for (int i = 0; i < 10; i++)
{
r1 = r1 - k*((glm::dot(r1, r2))/glm::dot(r2,r2))*r2 - k*((glm::dot(r1, r3)) / glm::dot(r3, r3))*r3;
r2 = r2 - k*((glm::dot(r2, r1)) / glm::dot(r1, r1))*r1 - k*((glm::dot(r2, r3)) / glm::dot(r3, r3))*r3;
r3 = r3 - k*((glm::dot(r3, r2)) / glm::dot(r1, r1))*r1 - k*((glm::dot(r3, r2)) / glm::dot(r2, r2))*r2;
}
glm::mat3 orthonormalisedOM;
//reset the matrix
glm::row(orthonormalisedOM, 0, r1);
glm::row(orthonormalisedOM, 1, r2);
glm::row(orthonormalisedOM, 2, r3);
return orthonormalisedOM;
}
#pragma endregion
#pragma region "Inertial Tensor"
void calcIinv() //double check inverse!
{
//glm::mat3 InertM = orientationMatrix * Ibody * glm::transpose(orientationMatrix);
glm::mat3 tensorMatrix0 = orientationMatrix * IbodyInv * glm::transpose(orientationMatrix);
this->tensorMatrix = tensorMatrix0;
//return glm::inverse(tensorMatrix0);
}
//Calculates inertial tensor cube approximation
glm::mat3 calcIbody()
{
//Assumes cube of dimension 1.0
IbodyVal = ((1.0 / 12.0) * mass * (1.0f + 1.0f));
Ibody[0].x = IbodyVal;
Ibody[1].y = IbodyVal;
Ibody[2].z = IbodyVal;
IbodyInv = glm::inverse(Ibody);
return IbodyInv;
}
#pragma endregion
//Creating
void setModel(GLchar* path)
{
this->model = Model(path);
this->modelCopy = Model(path);
}
//Body ID
int getID()
{
return bodyID;
}
};
#endif | [
"ecclesva@tcd.ie"
] | ecclesva@tcd.ie |
646b5b76e013cac7087ef516291c424c4b1d8908 | 7babc9d56dfd4dfb0e5b06315423dafb7e0df4cf | /smb_ompl_planner/include/smb_ompl_planner/ompl_planner.h | 0454a01444c75fe8c04c3bf189cbd73627264a61 | [
"BSD-3-Clause"
] | permissive | Idate96/smb_path_planner | a9e0f7696dbc593261448076596f0b80bff1ddd2 | 33711d637a5faf63b4f211ada1ef8163b1bd9ee5 | refs/heads/master | 2023-06-13T23:37:07.220582 | 2021-07-08T11:18:22 | 2021-07-08T11:18:22 | 384,097,008 | 0 | 0 | BSD-3-Clause | 2021-07-08T11:10:06 | 2021-07-08T11:10:05 | null | UTF-8 | C++ | false | false | 5,751 | h | /*
* Copyright (c) 2020, Vision for Robotics Lab
* 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 Vision for Robotics Lab, ETH Zurich 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.
*
*/
/*
* ompl_planner.h
* @brief Header file for the main class
* @author: Luca Bartolomei
* Created on: March 11, 2020
*/
#pragma once
#include <vector>
#include <costmap_2d/costmap_2d.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/PoseStamped.h>
#include <nav_core/base_global_planner.h>
#include <nav_msgs/GetPlan.h>
#include <nav_msgs/Odometry.h>
#include <nav_msgs/Path.h>
#include <ros/ros.h>
#include "smb_ompl_planner/orientation_filter.h"
#include "smb_ompl_planner/rrt_planner.h"
namespace smb_ompl_planner
{
class OmplPlanner : public nav_core::BaseGlobalPlanner
{
public:
/**
* @brief Default constructor for the OmplPlanner object
*/
OmplPlanner();
/**
* @brief Constructor for the PlannerCore object
* @param name The name of this planner
* @param costmap A pointer to the costmap to use
* @param frame_id Frame of the costmap
*/
OmplPlanner(std::string name, costmap_2d::Costmap2D* costmap,
std::string frame_id);
/**
* @brief Default deconstructor for the PlannerCore object
*/
~OmplPlanner();
/**
* @brief Initialization function for the PlannerCore object
* @param name The name of this planner
* @param costmap_ros A pointer to the ROS wrapper of the costmap to use for
* planning
*/
void initialize(std::string name, costmap_2d::Costmap2DROS* costmap_ros);
void initialize(std::string name, costmap_2d::Costmap2D* costmap,
std::string frame_id);
/**
* @brief Given a goal pose in the world, compute a plan
* @param start The start pose
* @param goal The goal pose
* @param plan The plan... filled by the planner
* @return True if a valid plan was found, false otherwise
*/
bool makePlan(const geometry_msgs::PoseStamped& start,
const geometry_msgs::PoseStamped& goal,
std::vector<geometry_msgs::PoseStamped>& plan);
/**
* @brief Given a goal pose in the world, compute a plan
* @param start The start pose
* @param goal The goal pose
* @param tolerance The tolerance on the goal point for the planner
* @param plan The plan... filled by the planner
* @return True if a valid plan was found, false otherwise
*/
bool makePlan(const geometry_msgs::PoseStamped& start,
const geometry_msgs::PoseStamped& goal, const double tolerance,
std::vector<geometry_msgs::PoseStamped>& plan);
/**
* @brief Publish a path for visualization purposes
*/
void publishPlan(const std::vector<geometry_msgs::PoseStamped>& path);
/**
* @brief Callbacks
*/
bool makePlanService(nav_msgs::GetPlan::Request& req,
nav_msgs::GetPlan::Response& resp);
void odometryCallback(const nav_msgs::OdometryConstPtr& odom_msg);
void collisionTimerCallback(const ros::TimerEvent&);
protected:
/**
* @brief Store a copy of the current costmap in \a costmap. Called by
* makePlan.
*/
costmap_2d::Costmap2D* costmap_;
std::string frame_id_;
ros::Publisher plan_pub_;
ros::Subscriber odometry_sub_;
ros::Timer timer_collisions_;
bool initialized_;
bool has_odometry_;
std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>>
global_path_;
Eigen::Vector2d odometry_;
Eigen::Vector2d goal_;
private:
void mapToWorld(double mx, double my, double& wx, double& wy);
bool worldToMap(double wx, double wy, double& mx, double& my);
void clearRobotCell(const geometry_msgs::PoseStamped& global_pose,
unsigned int mx, unsigned int my);
void outlineMap(unsigned char* costarr, int nx, int ny, unsigned char value);
// Planner
std::shared_ptr<smb_ompl_planner::RrtPlanner> ompl_planner_;
std::shared_ptr<OrientationFilter> orientation_filter_;
// Utilities
boost::mutex mutex_;
ros::ServiceServer make_plan_srv_;
unsigned char* cost_array_;
unsigned int start_x_, start_y_, end_x_, end_y_;
double default_tolerance_;
double min_distance_waypoints_;
double dist_goal_reached_;
bool old_navfn_behavior_;
float convert_offset_;
}; // end class OmplPlanner
} // end namespace smb_ompl_planner
| [
"bartolomei-luca@virgilio.it"
] | bartolomei-luca@virgilio.it |
59ff35cf5b3ded85db16f20bbd68c972508d2ddd | 986c21d401983789d9b3e5255bcf9d76070f65ec | /src/util/sll/tests/monadplustest.cpp | 8fb1c58aa3634ffad48476d15888dfd44d8283a8 | [
"BSL-1.0"
] | permissive | 0xd34df00d/leechcraft | 613454669be3a0cecddd11504950372c8614c4c8 | 15c091d15262abb0a011db03a98322248b96b46f | refs/heads/master | 2023-07-21T05:08:21.348281 | 2023-06-04T16:50:17 | 2023-06-04T16:50:17 | 119,854 | 149 | 71 | null | 2017-09-03T14:16:15 | 2009-02-02T13:52:45 | C++ | UTF-8 | C++ | false | false | 2,315 | cpp | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "monadplustest.h"
#include "monadtest.h"
#include <QtTest>
#include <monadplus.h>
#include <lazy.h>
#include <typelist.h>
QTEST_MAIN (LC::Util::MonadPlusTest)
namespace LC
{
namespace Util
{
void MonadPlusTest::testBoostOptionalMplus ()
{
const std::optional<int> val1 { 1 };
const std::optional<int> val2 { 2 };
const auto nothing = Mzero<std::optional<int>> ();
const auto res1 = val1 + val2;
const auto res2 = val1 + nothing;
const auto res3 = nothing + val1;
const auto res4 = nothing + nothing;
QCOMPARE (res1, val1);
QCOMPARE (res2, val1);
QCOMPARE (res3, val1);
QCOMPARE (res4, nothing);
}
void MonadPlusTest::testBoostOptionalMsum ()
{
const std::optional<int> val1 { 1 };
const std::optional<int> val2 { 2 };
const std::optional<int> val3 { 3 };
const auto nothing = Mzero<std::optional<int>> ();
const auto res1 = Msum ({ val1, val2, val3 });
const auto res2 = Msum ({ val1, nothing });
const auto res3 = Msum ({ nothing, val1 });
const auto res4 = Msum ({ nothing, nothing });
const auto res5 = Msum ({ nothing });
QCOMPARE (res1, val1);
QCOMPARE (res2, val1);
QCOMPARE (res3, val1);
QCOMPARE (res4, nothing);
QCOMPARE (res5, nothing);
}
void MonadPlusTest::testLazyBoostOptionalMsum ()
{
const auto val1 = MakeLazy (std::optional<int> { 1 });
const auto val2 = MakeLazy (std::optional<int> { 2 });
const auto val3 = MakeLazy (std::optional<int> { 3 });
const auto nothing = MakeLazy (Mzero<std::optional<int>> ());
const auto res1 = Msum ({ val1, val2, val3 });
const auto res2 = Msum ({ val1, nothing });
const auto res3 = Msum ({ nothing, val1 });
const auto res4 = Msum ({ nothing, nothing });
const auto res5 = Msum ({ nothing });
QCOMPARE (res1 (), val1 ());
QCOMPARE (res2 (), val1 ());
QCOMPARE (res3 (), val1 ());
QCOMPARE (res4 (), nothing ());
QCOMPARE (res5 (), nothing ());
}
}
}
| [
"0xd34df00d@gmail.com"
] | 0xd34df00d@gmail.com |
f7b352aa15407c9adf143c368d24627bfa3290f2 | d093e5dbdf4fb08eacbe2ec3cfc070e4c58c0f3e | /Source/Tools/ContainerCodeGeneratorLib/Sources/Systems/Aggregator/Handler/TypeFactory/GenerateAggregatorCppSystem.h | ee0a241bf4ee46eabc665be1a2835bfaec25c55e | [
"MIT"
] | permissive | RamilGauss/MMO-Framework | 3bd57e800f20b6447b494009eb3d7a49dfeb1402 | fa4ec6427a3a891954f97311af626f8753023ec2 | refs/heads/master | 2023-09-02T17:50:25.742920 | 2023-09-01T09:17:26 | 2023-09-01T09:17:26 | 15,496,543 | 32 | 20 | MIT | 2023-05-11T07:10:07 | 2013-12-28T17:54:28 | C++ | UTF-8 | C++ | false | false | 467 | h | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information LICENSE.md.
*/
#pragma once
#include <ECS/include/ExecuteSystem.h>
namespace nsContainerCodeGenerator::nsAggregator::nsHandler::nsTypeFactory
{
class DllExport TGenerateAggregatorCppSystem : public nsECSFramework::TExecuteSystem
{
public:
void Execute() override;
};
} | [
"ramil2085@mail.ru"
] | ramil2085@mail.ru |
e28cc58ed197ea633d04531699e0692dfc10dd3e | 4169f15797a718661f6a576b6f408b4d82d27f06 | /src/bayesian_filtering/nonlinearanalyticconditionalgaussian3D.cpp | 55e058f81a1490ec351b7a28a7beb1f2fa1f6e05 | [] | no_license | vislab-tecnico-lisboa/foveated_stereo_ros | c0c7d524ef86033ecd84ca8798903a6de8f655a1 | 4b75ddc66861c563268b755addfb443cdaac9c1c | refs/heads/master | 2020-03-30T13:23:24.237066 | 2018-08-31T12:23:07 | 2018-08-31T12:23:07 | 33,476,810 | 1 | 0 | null | 2016-09-05T10:02:18 | 2015-04-06T10:24:35 | C++ | UTF-8 | C++ | false | false | 3,451 | cpp | // $Id: NonLinearAnalyticConditionalGaussian3D.cpp 5823 2005-10-27 13:43:02Z TDeLaet $
// Copyright (C) 2006 Tinne De Laet <first dot last at mech dot kuleuven dot be>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "bayesian_filtering/nonlinearanalyticconditionalgaussian3D.h"
#include <wrappers/rng/rng.h> // Wrapper around several rng
// libraries
#define NUMCONDARGUMENTS_MOBILE 2
namespace BFL
{
using namespace MatrixWrapper;
NonLinearAnalyticConditionalGaussian3D::NonLinearAnalyticConditionalGaussian3D(const Gaussian& additiveNoise)
: AnalyticConditionalGaussianAdditiveNoise(additiveNoise,NUMCONDARGUMENTS_MOBILE)
{}
NonLinearAnalyticConditionalGaussian3D::~NonLinearAnalyticConditionalGaussian3D(){}
ColumnVector NonLinearAnalyticConditionalGaussian3D::ExpectedValueGet() const
{
ColumnVector state = ConditionalArgumentGet(0);
ColumnVector input = ConditionalArgumentGet(1); // Transformation
// Construct homogeneous transformation matrix
Matrix T_homogeneous(4,4);
T_homogeneous=0;
// Rotation
T_homogeneous(1,1)=1.0;
T_homogeneous(2,2)=1.0;
T_homogeneous(3,3)=1.0;
// Translation
T_homogeneous(1,4)=input(1); // delta_x
T_homogeneous(2,4)=input(2); // delta_y
T_homogeneous(3,4)=input(3); // delta_z
T_homogeneous(4,4)=1.0;
// Construct homogeneous state vector
ColumnVector state_homogeneous(4);
state_homogeneous=0;
state_homogeneous(1)=state(1); state_homogeneous(2)=state(2); state_homogeneous(3)=state(3); state_homogeneous(4)=1.0;
// Apply transformation
state_homogeneous=T_homogeneous * state_homogeneous;
// Convert back to state coordinates
state(1)=state_homogeneous(1); state(2)=state_homogeneous(2); state(3)=state_homogeneous(3);
return state + AdditiveNoiseMuGet();
}
Matrix NonLinearAnalyticConditionalGaussian3D::dfGet(unsigned int i) const
{
if (i==0)//derivative to the first conditional argument (x)
{
ColumnVector state = ConditionalArgumentGet(0);
ColumnVector vel = ConditionalArgumentGet(1);
Matrix df(3,3);
df(1,1)=1;
df(1,2)=0;
df(1,3)=-vel(1)*sin(state(3));
df(2,1)=0;
df(2,2)=1;
df(2,3)=vel(1)*cos(state(3));
df(3,1)=0;
df(3,2)=0;
df(3,3)=1;
return df;
}
else
{
if (i >= NumConditionalArgumentsGet())
{
cerr << "This pdf Only has " << NumConditionalArgumentsGet() << " conditional arguments\n";
exit(-BFL_ERRMISUSE);
}
else
{
cerr << "The df is not implemented for the" <<i << "th conditional argument\n";
exit(-BFL_ERRMISUSE);
}
}
}
}//namespace BFL
| [
"ruihortafigueiredo@gmail.com"
] | ruihortafigueiredo@gmail.com |
37b2a8ac2f8087051b9d7d72b614ce018bdadfd7 | ee09cc1c8435d3230f98ae230c05986a788b7bed | /salaDeReuniones_TPI/src/ejercicios.h | 147171333a15816feff4812378dd464ba9e4ae33 | [] | no_license | rus1147/TPIalgo1 | 66b3d4cf930261b633fb1d9a5c04edec3de43347 | d68caa684dbb3d44900da38e5761ec3e1e9a665a | refs/heads/master | 2021-03-27T14:01:22.619363 | 2017-11-13T04:01:00 | 2017-11-13T04:01:00 | 106,972,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | h | #ifndef SALADEREUNION_EJERCICIOS_H
#define SALADEREUNION_EJERCICIOS_H
#include <iostream>
#include <vector>
#include <math.h>
#include <tuple>
#include "definiciones.h"
using namespace std;
bool grabacionValida(audio s, int prof, int freq);
int elAcaparador(sala m, int freq, int prof);
sala ardillizar(sala m, int prof, int freq);
sala flashElPerezoso(sala m, int prof, int freq);
lista_intervalos silencios(audio s, int prof, int freq, int umbral);
bool hayQuilombo(sala m, int prof, int freq, int umbral);
tuple<int,lista_distancias> medirLaDistancia(sala m, audio frase, int freq, int prof);
float compararSilencios(audio x, int freq, int prof, int locutor, int umbralSilencio);
float resultadoFinal(sala m, int freq, int prof, int umbralSilencio);
int encontrarAparicion(audio x, audio y, int freq, int prof);
audio sinSilencios(audio s, int freq, int prof, int umbral);
#endif //SALADEREUNION_EJERCICIOS_H
| [
"rus1147@gmail.com"
] | rus1147@gmail.com |
5523a0136c4db34a58704608b319d55495a9e7c0 | 56e5ecd068f93d4263b0dedfd36c3d9f7d599594 | /DarkEdif/Bluewing Client/LacewingFunctions.cpp | 634c6b1a562d9741ca2d31026d09e5f827c35cfd | [] | no_license | Toonlink3000/MMF2Exts | 90709d179a95e53034fd8fe2e2d33255d882c4e6 | 9918e8e8cdfe23782748c9ceb04273e3bb79f928 | refs/heads/master | 2020-11-25T12:23:33.523428 | 2019-11-27T21:21:20 | 2019-11-27T21:21:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,605 | cpp | // Handles all Lacewing functions.
#include "Common.h"
#define Ext (*((GlobalInfo *) Client.tag)->_ext)
#define globals ((GlobalInfo *) Client.tag)
#define GThread globals->_thread
void OnError(lacewing::relayclient &Client, lacewing::error error)
{
if (GThread)
EnterCriticalSectionDebug(&globals->lock);
char * c = _strdup(error->tostring());
if (c)
globals->AddEvent1(0, nullptr, nullptr, c);
else
globals->AddEvent1(0, nullptr, nullptr, "Error copying Lacewing error string to local buffer.");
if (GThread)
LeaveCriticalSectionDebug(&globals->lock);
}
void OnConnect(lacewing::relayclient &Client)
{
lacewing::address addr = Client.serveraddress();
char ipAddr[64];
lw_addr_prettystring(addr->tostring(), ipAddr, sizeof(ipAddr));
HostIP = ipAddr;
globals->AddEvent1(1);
}
void OnConnectDenied(lacewing::relayclient &Client, const char * DenyReason)
{
// On Connect is not called during TCP Connect but Connect Response message.
// Ditto for Connect Denied. The serveraddress() is set during TCP Connect, so it should be valid here.
lacewing::address addr = Client.serveraddress();
char ipAddr[64];
lw_addr_prettystring(addr->tostring(), ipAddr, sizeof(ipAddr));
HostIP = ipAddr;
// Old deny reason? Free it.
free(DenyReasonBuffer);
DenyReasonBuffer = _strdup(DenyReason);
if (!DenyReasonBuffer)
globals->CreateError("Error copying deny reason from Lacewing to local buffer.");
globals->AddEvent1(2); // no 0xFFFF; Disconnect should be called separately
}
void OnDisconnect(lacewing::relayclient &Client)
{
if (GThread)
EnterCriticalSectionDebug(&globals->lock);
// Close all channels/peers in our copy
for (auto j : Channels)
j->close();
if (GThread)
LeaveCriticalSectionDebug(&globals->lock);
// 0xFFFF: Empty all channels and peers, and reset HostIP
globals->AddEvent2(3, 0xFFFF);
}
void OnChannelListReceived(lacewing::relayclient &Client)
{
globals->AddEvent1(26);
}
void OnJoinChannel(lacewing::relayclient &Client, lacewing::relayclient::channel &Target)
{
if (GThread)
EnterCriticalSectionDebug(&globals->lock);
ChannelCopy * channel = new ChannelCopy(&Target);
Channels.push_back(channel);
#if 0
// Autoselect the first channel?
if (Channels.size() == 1U)
Ext.threadData.channel = channel;
#endif
if (GThread)
LeaveCriticalSectionDebug(&globals->lock);
globals->AddEvent1(4, channel);
}
void OnJoinChannelDenied(lacewing::relayclient &Client, const char * ChannelName, const char * DenyReason)
{
// Old deny reason? Free it.
free(DenyReasonBuffer);
DenyReasonBuffer = _strdup(DenyReason);
if (!DenyReasonBuffer)
globals->CreateError("Error copying deny reason from Lacewing to local buffer.");
globals->AddEvent1(5, nullptr, nullptr, _strdup(ChannelName));
}
void OnLeaveChannel(lacewing::relayclient &Client, lacewing::relayclient::channel &Target)
{
if (GThread)
EnterCriticalSectionDebug(&globals->lock);
// Close client in our copy
for (auto j : Channels)
{
if (j->id() == Target.id())
{
j->close();
// 0xFFFF: Clear channel copy after this event is handled
globals->AddEvent2(43, 0xFFFF, j);
if (GThread)
LeaveCriticalSectionDebug(&globals->lock);
return;
}
}
if (GThread)
LeaveCriticalSectionDebug(&globals->lock);
globals->CreateError("Couldn't find channel copy.");
}
void OnLeaveChannelDenied(lacewing::relayclient &Client, lacewing::relayclient::channel &Target, const char * DenyReason)
{
// Old deny reason? Free it.
free(DenyReasonBuffer);
DenyReasonBuffer = _strdup(DenyReason);
if (!DenyReasonBuffer)
globals->CreateError("Error copying deny reason from Lacewing to local buffer.");
globals->AddEvent1(44, &Target);
}
void OnNameSet(lacewing::relayclient &Client)
{
globals->AddEvent1(6);
}
void OnNameDenied(lacewing::relayclient &Client, const char * DeniedName, const char * DenyReason)
{
// Old deny reason? Free it.
free(DenyReasonBuffer);
DenyReasonBuffer = _strdup(DenyReason);
if (!DenyReasonBuffer)
globals->CreateError("Error copying deny reason from Lacewing to local buffer.");
globals->AddEvent1(7);
}
void OnNameChanged(lacewing::relayclient &Client, const char * OldName)
{
// Old name? Free it.
free(PreviousName);
PreviousName = _strdup(OldName);
if (!PreviousName)
globals->CreateError("Error copying self previous name from Lacewing to local buffer.");
globals->AddEvent1(53);
}
void OnPeerConnect(lacewing::relayclient &Client, lacewing::relayclient::channel &channel, lacewing::relayclient::channel::peer &peer)
{
// Add peer to our copy
for (auto j : Channels)
{
if (j->id() == channel.id())
{
PeerCopy * PeerCopy = j->addpeer(&peer);
if (PeerCopy)
globals->AddEvent1(10, j, PeerCopy);
return;
}
}
globals->CreateError("Couldn't find peer copy.");
}
void OnPeerDisconnect(lacewing::relayclient &Client, lacewing::relayclient::channel &channel,
lacewing::relayclient::channel::peer &peer)
{
// Disconnect makes write impossible. To prevent Fusion being halfway through writing on another thread,
// lock the event loop.
if (GThread)
EnterCriticalSectionDebug(&globals->lock);
// Close peer in our copy.
// Original peer will be deleted after OnPeerDisconnect (this func) ends.
// Then once 0xFFFF triggers, copy will be deleted too.
for (auto j : Channels)
{
if (j->id() == channel.id())
{
PeerCopy * PeerCopy = j->closepeer(peer);
if (GThread)
LeaveCriticalSectionDebug(&globals->lock);
if (PeerCopy)
globals->AddEvent2(11, 0xFFFF, j, PeerCopy);
return;
}
}
if (GThread)
LeaveCriticalSectionDebug(&globals->lock);
globals->CreateError("Couldn't find copy of channel for peer disconnect.");
}
void OnPeerNameChanged(lacewing::relayclient &Client, lacewing::relayclient::channel &channel,
lacewing::relayclient::channel::peer &peer, const char * OldName)
{
for (auto j : Channels)
{
if (j->id() == channel.id())
{
PeerCopy * k = j->updatepeername(peer);
if (k)
globals->AddEvent1(45, j, k);
else
globals->CreateError("Couldn't find copy of peer on copy of channel for peer name change.");
return;
}
}
globals->CreateError("Couldn't find copy of channel for peer name change.");
return;
}
void OnPeerMessage(lacewing::relayclient &Client, lacewing::relayclient::channel &channel,
lacewing::relayclient::channel::peer &peer,
bool Blasted, int subchannel, const char * Data, size_t size, int Variant)
{
auto cc = std::find_if(Channels.begin(), Channels.end(), [&](ChannelCopy *&c) {
return &c->orig() == &channel;
});
if (cc == Channels.end())
{
globals->CreateError("Couldn't find copy of channel for peer message.");
return;
}
ChannelCopy * channelCopy = *cc;
auto& peers = channelCopy->getpeers();
auto pp = std::find_if(peers.begin(), peers.end(), [&](PeerCopy * p) {
return &p->orig() == &peer;
});
if (pp == peers.end())
{
globals->CreateError("Couldn't find copy of peer on copy of channel for peer message.");
return;
}
PeerCopy * peerCopy = *pp;
char * Dup = (char *)malloc(size);
if (!Dup)
{
globals->CreateError("Failed to create local buffer for copying received message from Lacewing. Message discarded.");
return;
}
if (memcpy_s(Dup, size, Data, size))
{
free(Dup);
globals->CreateError("Failed to copy message from Lacewing to local buffer. Message discarded.");
return;
}
if (Blasted)
{
// text
if (Variant == 0)
globals->AddEvent2(52, 39, channelCopy, peerCopy, Dup, size, subchannel);
// Number
else if (Variant == 1)
globals->AddEvent2(52, 40, channelCopy, peerCopy, Dup, size, subchannel);
// Binary
else if (Variant == 2)
globals->AddEvent2(52, 41, channelCopy, peerCopy, Dup, size, subchannel);
// ???
else
{
free(Dup);
globals->CreateError("Warning: message type is neither binary, number nor text.");
}
}
else // Sent
{
// text
if (Variant == 0)
globals->AddEvent2(49, 36, channelCopy, peerCopy, Dup, size, subchannel);
// Number
else if (Variant == 1)
globals->AddEvent2(49, 37, channelCopy, peerCopy, Dup, size, subchannel);
// Binary
else if (Variant == 2)
globals->AddEvent2(49, 38, channelCopy, peerCopy, Dup, size, subchannel);
// ???
else
{
free(Dup);
globals->CreateError("Warning: message type is neither binary, number nor text.");
}
}
}
void OnChannelMessage(lacewing::relayclient &Client, lacewing::relayclient::channel &channel,
lacewing::relayclient::channel::peer &peer,
bool Blasted, int subchannel, const char * Data, size_t size, int Variant)
{
auto cc = std::find_if(Channels.begin(), Channels.end(), [&](ChannelCopy *&c) {
return &c->orig() == &channel;
});
if (cc == Channels.end())
{
globals->CreateError("Couldn't find copy of channel for channel message.");
return;
}
ChannelCopy * channelCopy = *cc;
auto& peers = channelCopy->getpeers();
auto pp = std::find_if(peers.begin(), peers.end(), [&](PeerCopy * p) {
return &p->orig() == &peer;
});
if (pp == peers.end())
{
globals->CreateError("Couldn't find copy of peer on copy of channel for channel message.");
return;
}
PeerCopy * peerCopy = *pp;
char * Dup = (char *)malloc(size);
if (!Dup)
{
globals->CreateError("Failed to create local buffer for copying received message from Lacewing. Message discarded.");
return;
}
if (memcpy_s(Dup, size, Data, size))
{
free(Dup);
globals->CreateError("Failed to copy message from Lacewing to local buffer. Message discarded.");
return;
}
if (Blasted)
{
// text
if (Variant == 0)
globals->AddEvent2(51, 22, channelCopy, peerCopy, Dup, size, subchannel);
// Number
else if (Variant == 1)
globals->AddEvent2(51, 23, channelCopy, peerCopy, Dup, size, subchannel);
// Binary
else if (Variant == 2)
globals->AddEvent2(51, 35, channelCopy, peerCopy, Dup, size, subchannel);
// ???
else
{
free(Dup);
globals->CreateError("Warning: message type is neither binary, number nor text.");
}
}
else // Sent
{
// text
if (Variant == 0)
globals->AddEvent2(48, 9, channelCopy, peerCopy, Dup, size, subchannel);
// Number
else if (Variant == 1)
globals->AddEvent2(48, 16, channelCopy, peerCopy, Dup, size, subchannel);
// Binary
else if (Variant == 2)
globals->AddEvent2(48, 33, channelCopy, peerCopy, Dup, size, subchannel);
// ???
else
{
free(Dup);
globals->CreateError("Warning: message type is neither binary, number nor text.");
}
}
}
void OnServerMessage(lacewing::relayclient &Client,
bool Blasted, int subchannel, const char * Data, size_t size, int Variant)
{
char * Dup = (char *)malloc(size);
if (!Dup)
{
globals->CreateError("Failed to create local buffer for copying received message from Lacewing. Message discarded.");
return;
}
if (memcpy_s(Dup, size, Data, size))
{
free(Dup);
globals->CreateError("Failed to copy message from Lacewing to local buffer. Message discarded.");
return;
}
if (Blasted)
{
// text
if (Variant == 0)
globals->AddEvent2(50, 20, nullptr, nullptr, Dup, size, subchannel);
// Number
else if (Variant == 1)
globals->AddEvent2(50, 21, nullptr, nullptr, Dup, size, subchannel);
// Binary
else if (Variant == 2)
globals->AddEvent2(50, 34, nullptr, nullptr, Dup, size, subchannel);
// ???
else
{
free(Dup);
globals->CreateError("Warning: message type is neither binary, number nor text.");
}
}
else // Sent
{
// text
if (Variant == 0)
globals->AddEvent2(47, 8, nullptr, nullptr, Dup, size, subchannel);
// Number
else if (Variant == 1)
globals->AddEvent2(47, 15, nullptr, nullptr, Dup, size, subchannel);
// Binary
else if (Variant == 2)
globals->AddEvent2(47, 32, nullptr, nullptr, Dup, size, subchannel);
// ???
else
{
free(Dup);
globals->CreateError("Warning: message type is neither binary, number nor text.");
}
}
}
void OnServerChannelMessage(lacewing::relayclient &Client, lacewing::relayclient::channel &channel,
bool Blasted, int subchannel, const char * Data, size_t size, int Variant)
{
auto cc = std::find_if(Channels.begin(), Channels.end(), [&](ChannelCopy *&c) {
return &c->orig() == &channel;
});
if (cc == Channels.end())
{
globals->CreateError("Couldn't find copy of channel for server-to-channel message.");
return;
}
ChannelCopy * channelCopy = *cc;
char * Dup = (char *)malloc(size);
if (!Dup)
{
globals->CreateError("Failed to create local buffer for copying received message from Lacewing. Message discarded.");
return;
}
if (memcpy_s(Dup, size, Data, size))
{
free(Dup);
globals->CreateError("Failed to copy message from Lacewing to local buffer. Message discarded.");
return;
}
if (Blasted)
{
// text
if (Variant == 0)
globals->AddEvent2(72, 69, channelCopy, nullptr, Dup, size, subchannel);
// Number
else if (Variant == 1)
globals->AddEvent2(72, 70, channelCopy, nullptr, Dup, size, subchannel);
// Binary
else if (Variant == 2)
globals->AddEvent2(72, 71, channelCopy, nullptr, Dup, size, subchannel);
// ???
else
{
free(Dup);
globals->CreateError("Warning: message type is neither binary, number nor text.");
}
}
else // Sent
{
// text
if (Variant == 0)
globals->AddEvent2(68, 65, channelCopy, nullptr, Dup, size, subchannel);
// Number
else if (Variant == 1)
globals->AddEvent2(68, 66, channelCopy, nullptr, Dup, size, subchannel);
// Binary
else if (Variant == 2)
globals->AddEvent2(68, 67, channelCopy, nullptr, Dup, size, subchannel);
// ???
else
{
free(Dup);
globals->CreateError("Warning: message type is neither binary, number nor text.");
}
}
}
#undef Ext
#undef globals | [
"phi@dark-wire.com"
] | phi@dark-wire.com |
17ced0a97d11364749ba13bbc9b70bb0872670b0 | cadb836d9ac9c9e3b618cf44c936015a0aea24a8 | /ge2300/LT2302_2022-06-14_Count_Subarrays_With_Score_Less_Than_K.cpp | 9658a7db1f72c2a574aefb330dbefb114aeac9b2 | [] | no_license | checkoutb/LeetCodeCCpp | c6341a9fa5583a69046555a892bb41052624e83c | 38832f7ccadf26b781cd8c9783c50916d1380554 | refs/heads/master | 2023-09-03T22:35:50.266523 | 2023-09-03T06:31:51 | 2023-09-03T06:31:51 | 182,722,336 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 802 | cpp |
#include "../header/myheader.h"
class LT2302
{
public:
// D D
//Runtime: 203 ms, faster than 87.04 % of C++ online submissions for Count Subarrays With Score Less Than K.
//Memory Usage : 95 MB, less than 53.05 % of C++ online submissions for Count Subarrays With Score Less Than K.
long long lt2302a(vector<int>& nums, long long k)
{
long long sum2 = 0LL;
int cnt = 0;
int st = 0;
long long ans = 0LL;
for (int i = 0; i < nums.size(); ++i)
{
sum2 += nums[i];
cnt++;
while (sum2 * cnt >= k)
{
sum2 -= nums[st++];
cnt--;
}
ans += (i - st + 1);
}
return ans;
}
};
int main()
{
LT2302 lt;
return 0;
}
| [
"f12.628@hotmail.com"
] | f12.628@hotmail.com |
1272848a5ad8b3bf5d5d5bc28be173017f37e113 | 8f369ff88d419cf51dbec04c0d77c067629ba35b | /parser/statement/SelectStatement.h | ce219860de05fef24f55e35025ffd28c104bd560 | [] | no_license | DwarfMason/UDBMS | ccba5de4f33d3576ca2496f2bc4ac7dccf4ee740 | a602803895f1451ba4871d1681f72d213102d0a3 | refs/heads/master | 2020-08-03T19:59:55.028805 | 2019-12-25T17:04:53 | 2019-12-25T17:04:53 | 211,868,887 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 483 | h | //
// Created by veto on 09.10.19.
//
#ifndef SELECTSTATEMENT_H
#define SELECTSTATEMENT_H
#include <string>
#include <vector>
#include <any>
#include "BaseStatement.h"
struct SelectStatement : public BaseStatement
{
struct Statement
{
std::string name;
std::vector<std::string> selector;
/* example
* `id` = `qwe`
* */
std::pair<std::string,std::any> expr;
bool useExpr = false;
};
};
#endif //SELECTSTATEMENT_H
| [
"vetosmg@gmail.com"
] | vetosmg@gmail.com |
812fed296d0b538fbd28d73d195cb6e7edb15b5d | 0cb7f86d705e0a8a3dd395ad94ebeda4f87aab0b | /include/Game.h | 9fc08895c2dc8cef9d72c2d0337904b885740c42 | [] | no_license | rylo5688/Battleship | eb5e1e74f93b4c8c5a94396a16cb2c695e7d30ee | dc75e0303dd8f054eb0beabe6cfeeec79ef440c4 | refs/heads/master | 2021-01-12T02:28:01.988052 | 2017-07-12T22:58:14 | 2017-07-12T22:58:14 | 77,959,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | h | #ifndef GAME_H
#define GAME_H
#include "Player.h"
#include "Computer.h"
#include <iostream>
using namespace std;
class Game
{
public:
Game(string fileName);
virtual ~Game();
void singlePlayerSetup();
void singlePlayerRun();
void multiPlayerSetup();
void multiPlayerRun();
private:
void printNewLine(int n);
Player *player1;
Player *player2;
Computer *computer;
};
#endif // GAME_H
| [
"loi.ryan18@gmail.com"
] | loi.ryan18@gmail.com |
4e380b14aa2c009fc58a113c8f818c7c96e40512 | b5648642fd2e05589cab760a909ce1dc38556d5d | /touchGFX/Application/generated/images/src/batty/battry03.cpp | 4ac16d3ef06bf6adff1b568a4be61e4e228bd365 | [] | no_license | sunklCoin/MCU | 862c8f8ee48872b3fc703d54c2d76bbb74cca1a4 | 9cc7a45fae3b18821c722f78d901034086ccc98c | refs/heads/master | 2021-07-14T00:58:51.259827 | 2017-10-16T14:12:55 | 2017-10-16T14:12:55 | 105,020,651 | 0 | 0 | null | 2017-10-16T14:12:56 | 2017-09-27T13:19:03 | C++ | UTF-8 | C++ | false | false | 7,620 | cpp | // Generated by imageconverter. Please, do not edit!
#include <touchgfx/hal/Config.hpp>
LOCATION_EXTFLASH_PRAGMA
KEEP extern const unsigned char _battry03[] LOCATION_EXTFLASH_ATTRIBUTE = { // 32x15 RGB565 pixels.
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00
};
LOCATION_EXTFLASH_PRAGMA
KEEP extern const unsigned char _battry03_alpha_channel[] LOCATION_EXTFLASH_ATTRIBUTE = { // 32x15 alpha pixels.
0x10,0x96,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x59,0x00,0x00,0x00,
0xaa,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x3c,0x00,0x00,
0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x00,0x00,
0xff,0x00,0x00,0x00,0x51,0x7d,0x30,0x00,0x00,0x00,0x51,0x7d,0x30,0x00,0x00,0x00,
0x20,0x7d,0x5d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xdf,0x8a,
0xff,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,
0xae,0xff,0xff,0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf3,0xff,0xef,
0xff,0x00,0x00,0x00,0xff,0xff,0xc3,0x00,0x00,0x00,0xff,0xff,0xc3,0x00,0x00,0x00,
0xc3,0xff,0xff,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf3,0xff,0xef,
0xff,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,
0xbe,0xff,0xff,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf3,0xff,0xef,
0xff,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,
0xc3,0xff,0xff,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf3,0xff,0xef,
0xff,0x00,0x00,0x00,0xff,0xff,0xc3,0x00,0x00,0x00,0xff,0xff,0xc3,0x00,0x00,0x00,
0xbe,0xff,0xff,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf3,0xff,0xef,
0xff,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,
0xbe,0xff,0xff,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf3,0xff,0xef,
0xff,0x00,0x00,0x00,0xff,0xff,0xc3,0x00,0x00,0x00,0xff,0xff,0xbe,0x00,0x00,0x00,
0xc3,0xff,0xff,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf3,0xff,0xef,
0xff,0x00,0x00,0x00,0x8e,0xbe,0x82,0x00,0x00,0x00,0xa2,0xbe,0x82,0x00,0x00,0x00,
0x51,0xbe,0xae,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xdf,0x8a,
0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0xff,0x00,0x00,
0x92,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0xff,0x3c,0x00,0x00,
0x10,0x49,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3c,0x00,0x00,0x00
};
| [
"sunkl.coin@gmail.com"
] | sunkl.coin@gmail.com |
782dd0ecce49106e04af7ecea075dbc83a93e54b | c809ceec2467f0b56cca2cbae7c2e12a8b853701 | /365 DaysX10=3000 programming challenge/standard dfs.cpp | 0f68a34361145d7df52f133a55e303f8dd225f09 | [] | no_license | shubhampathak09/graphs-and-graph-algorithm. | afc5e54566636a7a36e58b73b02af9f6ff12588b | 2fba8b97cd294e800dc69fc1280c44c3beddd472 | refs/heads/master | 2021-08-18T01:20:52.215268 | 2020-07-27T12:42:41 | 2020-07-27T12:55:20 | 207,623,593 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | // standard dfs
#include<bits/stdc++.h>
using namespace std;
void addedge(int u,int v,vector<int>*adj)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfsutil(int v,vector<int>*adj,bool *visited)
{
visited[v]=true;
cout<<v<<endl;
vector<int>::iterator i;
for(i=adj[v].begin();i!=adj[v].end();i++)
if(visited[*i]==false)
dfsutil(*i,adj,visited);
}
void dfs(int V,vector<int>*adj)
{
bool visited[V];
for(int i=0;i<V;i++)
visited[i]=false;
for(int i=0;i<V;i++)
if(!visited[i])
dfsutil(i,adj,visited);
}
int main()
{
int V=5;
vector<int>adj[V];
addedge(0,1,adj);
addedge(0,2,adj);
addedge(1,3,adj);
addedge(1,4,adj);
dfs(V,adj);
}
| [
"shubham.pathak@cgi.com"
] | shubham.pathak@cgi.com |
df04459648bf7d46805e559d0a3d230468636dc1 | 9ac04b991c81f2b3fcda636b02c6601950fda29f | /CudaGui/loaddialog.cpp | 1637c29938d7fd934a03ecf82d253adc88fcb29b | [] | no_license | sl4sh1337/geo | ba5d3439898f84cb4eb6ba70e6d4e8be96797e60 | bf80468aba9c44baf84d188409100693171e1443 | refs/heads/master | 2021-01-13T21:53:55.356649 | 2020-10-27T13:17:06 | 2020-10-27T13:17:06 | 242,505,956 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 453 | cpp | #include "loaddialog.h"
#include "ui_loaddialog.h"
#include <QMovie>
LoadDialog::LoadDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::LoadDialog)
{
ui->setupUi(this);
setWindowFlag(Qt::FramelessWindowHint);
QMovie *movie = new QMovie(":/download.gif");
movie->setScaledSize(QSize(ui->label->width(), ui->label->height()));
ui->label->setMovie(movie);
movie->start();
}
LoadDialog::~LoadDialog()
{
delete ui;
}
| [
"gmarshalk@gmail.ru"
] | gmarshalk@gmail.ru |
8fa5716322c218d89fd904e079372acbf623bd70 | 2b29046a1539f942e9737eaeb36a8271d093ac16 | /1º/fp/Prácticas 2013_14/Soluciones/Soluciones_7/III_ProgresionGeom_Funcs.cpp | dd1c370adcb51248e641b5e981c27eea1add971f | [] | no_license | JJavier98/Support | 283d0e47ae3af3f150c65ee7150b1e374a3142ad | ad28ace97b6c35132c43a3f0b512a893c278f7b6 | refs/heads/master | 2020-03-19T06:46:28.669531 | 2018-06-04T16:42:47 | 2018-06-04T16:42:47 | 136,053,726 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 8,805 | cpp | /*********************************************************************/
// FUNDAMENTOS DE PROGRAMACIÓN
// GRADO EN INGENIERÍA INFORMÁTICA
//
// CURSO 2013-2014
// (C) JUAN CARLOS CUBERO TALAVERA
// (C) FRANCISCO JOSÉ CORTIJO BON
// DEPARTAMENTO DE CIENCIAS DE LA COMPUTACIÓN E INTELIGENCIA ARTIFICIAL
//
// RELACIÓN DE PROBLEMAS 3
// EJERCICIO 9
//
// Ampliación del ejercicio 19 de la Relación II
/*
Progresión geométrica:
Supongamos una serie numérica cuyo término general es:
i-1
a_i = a_1 * r = a_{i-1} * r
donde "a_1" es el primer término de la serie, y "r" es la razón
El programa lee r, a_1 y un índice k y calcula:
a) la suma de los primeros k valores de la serie, es decir:
i=k i=k
__ __
< < i-1
> a_i = > a_1 * r
< __ < __
i=1 i=1
Recordar que a_i = a_{i-1} * r para i=2,3,... lo que hace
posible escribir otra versión de esta sumatoria.
i=k i=k i=k
__ __ __
< < i-1 <
> a_i = > a_1 * r = > a_{i-1} * r
< __ < __ < __
i=1 i=1 i=2
b) b) la suma anterior pero sustituyendo la sumatoria por
k
r - 1
a_1 * --------
r - 1
c) la suma "hasta infinito" de la serie, es decir:
i=OO
__
< a_1
> a_i = ------- siempre que |r| < 1
< __ 1 - r
i=1
d) el producto de los primeros k valores de la serie, es decir:
i=k i=k
__ __
| | | | _____________________
| | | | i-1 / k
| | a_i = | | a_1 * r = V (a_1 * a_k)
i=1 i=1
Entradas: El primer término de la progresión (termino_primero)
La razón de la progresión (razon)
Indice del último término para la suma (tope)
*/
/*********************************************************************/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
/*****************************************************************/
// Cálculo del término i-ésimo
// i-1
// a_i = a_1 * r
double Termino (int i, double termino_primero, double razon)
{
return (termino_primero * pow (razon, i-1));
}
/*****************************************************************/
// Cálculo de la sumatoria, usando la expresión directa de a_i:
//
// i=k i=k
// __ __
// < < i-1
// > a_i = > a_1 * r
// < __ < __
// i=1 i=1
//
double SumaHasta_ver1 (double termino_primero, double razon, int tope)
{
double suma_total = termino_primero;
// El ciclo for no se inicia a 1 porque la asignación anterior
// hace, implícitamente, la suma desde i=1 hasta 1
for (int i=2; i <= tope; i++) {
suma_total += Termino(i, termino_primero, razon);
}
return (suma_total);
}
/*****************************************************************/
// Cálculo de la sumatoria, usando en cada iteración el valor del
/// término calculado en la iteración anterior.
//
// i=k i=k i=k
// __ __ __
// < < i-1 <
// > a_i = > a_1 * r = > a_{i-1} * r
// < __ < __ < __
// i=1 i=1 i=1
//
double SumaHasta_ver2 (double termino_primero, double razon, int tope)
{
double suma_total = termino_primero;
double termino_ant = termino_primero;
double termino_act;
// El ciclo for no se inicia a 1 porque las asignaciones anteriores
// hacen, implícitamente, la suma desde i=1 hasta 1
for (int i=2; i <= tope; i++) {
termino_act = termino_ant * razon;
suma_total += termino_act;
termino_ant = termino_act;
}
return (suma_total);
}
/*****************************************************************/
// Cálculo de la sumatoria por la expresión directa:
//
// i=k
// __ k
// < r - 1
// > a_i = a_1 * --------
// < __ r - 1
// i=1
//
double SumaHasta_ver3 (double termino_primero, double razon, int tope)
{
return (termino_primero * ((pow(razon,tope) - 1) / (razon-1)));
}
/*****************************************************************/
// Cálculo de la sumatoria hasta infinito:
//
// i=OO
// __
// < a_1
// > a_i = ------- siempre que |r| < 1
// < __ 1 - r
// i=1
//
// PRECONDICION: |r| < 1
double SumaHastaInfinito (double termino_primero, double razon)
{
return (termino_primero / (1 - razon));
}
/*****************************************************************/
// Cálculo del producto de los primeros k valores de la serie:
//
// i=k i=k
// __ __
// | | | |
// | | | | i-1
// | | a_i = | | a_1 * r
// i=1 i=1
//
//
double MultiplicaHasta_ver1 (double termino_primero, double razon, int tope)
{
int producto_total = termino_primero;
// El ciclo for no se inicia a 1 porque la asignación anterior
// hace, implícitamente, el producto desde i=1 hasta 1
for (int i=2; i <= tope; i++) {
producto_total *= termino_primero * pow (razon, i-1);
}
return (producto_total);
}
/*****************************************************************/
// Cálculo (directo) del producto de los primeros k valores de la serie:
//
// i=k i=k
// __ __
// | | | | ________________
// | | | | i-1 / k
// | | a_i = | | a_1 * r = V (a_1 * a_k)
// i=1 i=1
//
//
double MultiplicaHasta_ver2 (double termino_primero, double razon, int tope)
{
return (sqrt (pow (termino_primero *
Termino (tope, termino_primero, razon), tope)));
}
/*****************************************************************/
int main()
{
double termino_primero, razon; // Parámetros de la serie
int tope; // Máximo índice para la suma
// Resultados
double suma_total_ver1, suma_total_ver2, suma_total_ver3;
double suma_total_inf;
double producto_total_ver1, producto_total_ver2;
cout.setf(ios::fixed); // Notación de punto fijo para los reales
cout.setf(ios::showpoint); // Mostrar siempre decimales
// Lecutra de los parámetros que definen la serie
cout << "Primer término de la progresión: ";
cin >> termino_primero;
cout << "Razón de la progresión: ";
cin >> razon;
// Lectura del máximo índice para la suma
do {
cout << "Indice (debe ser >=1) del último término a sumar: ";
cin >> tope;
} while (tope < 1);
// Cálculos y resultados de la sumatoria hasta "tope"
suma_total_ver1 = SumaHasta_ver1 (termino_primero, razon, tope);
suma_total_ver2 = SumaHasta_ver2 (termino_primero, razon, tope);
suma_total_ver3 = SumaHasta_ver3 (termino_primero, razon, tope);
cout << "\nVersión 1: Suma hasta " << setw(3) << tope
<< " = " << setw(10) << setprecision (2) << suma_total_ver1 << "\n\n";
cout << "\nVersión 2: Suma hasta " << setw(3) << tope
<< " = " << setw(10) << setprecision (2) << suma_total_ver2 << "\n\n";
cout << "\nVersión 3: Suma hasta " << setw(3) << tope
<< " = " << setw(10) << setprecision (2) << suma_total_ver3 << "\n\n";
// Cálculo y resultado de la sumatoria hasta "infinito"
if (abs(razon) < 1) {
suma_total_inf = SumaHastaInfinito (termino_primero, razon);
cout << "\nSuma hasta infinito = "
<< setw(10) << setprecision (2) << suma_total_inf << "\n\n";
}
else
cout << "\n No puede calcularse suma hasta infinito "
<< "porque |" << setprecision (2) << razon << "| >= 1";
cout << "\n\n";
// Lectura del máximo índice para el producto
do {
cout << "Indice (debe ser >=1) del último término a multiplicar: ";
cin >> tope;
} while (tope < 1);
// Cálculos y resultados del producto hasta "tope"
producto_total_ver1 = MultiplicaHasta_ver1 (termino_primero, razon, tope);
producto_total_ver2 = MultiplicaHasta_ver2 (termino_primero, razon, tope);
cout << "\nVersión 1: Producto hasta " << setw(3) << tope
<< " = " << setw(10) << setprecision (2) << producto_total_ver1 << "\n\n";
cout << "\nVersión 2: Producto hasta " << setw(3) << tope
<< " = " << setw(10) << setprecision (2) << producto_total_ver2 << "\n\n";
system("pause");
} | [
"jota.jota.98@hotmail.com"
] | jota.jota.98@hotmail.com |
77aa96ff478610c37c3c245e8840bac852fe0efb | 8056397c905fa86f4f3489c6f34176f0a167a351 | /contest/1055/b/45527630_wrong_answer_2.cpp | 0ba012af62c9d98502029edcc0a5969ad00272cd | [] | no_license | priyankjairaj100/Codeforces-Solutions | e9ac35b339ebd71e17882873ae2150d0c17101f6 | 540f30d8741e5d84bc983cb7abcee0a0dc03bfbb | refs/heads/master | 2022-04-23T06:14:52.931737 | 2020-04-25T03:16:24 | 2020-04-25T03:16:24 | 258,675,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,041 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long double LD;
const int MAX = 1e5 + 5;
const int MOD = 1e9 + 7;
const LD EPS = 1e-10;
const LD PI = acos(-1.0);
#define fastio ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
#define rep(i,a,b,d) for(LL i = a; i<=b; i+=d)
#define brep(i,a,b,d) for(LL i = a; i>=b; i-=d)
#define pb push_back
#define f first
#define s second
#define pii pair<LL, LL>
#define all(c) (c).begin(),(c).end()
int main() {
fastio
LL n,m,l; cin>>n>>m>>l;
LL a[n+2], b[n+2]; rep(i,1,n,1) {cin>>a[i]; b[i] = a[i];} a[n+1] = 0; a[0] = 0; b[n+1] = 0; b[0] = 0;
rep(i,1,n,1){if(a[i]<=l) a[i]=0; else a[i]=1;}
LL c = 0;
rep(i,1,n,1) if(a[i]==1 and a[i+1] == 0) c++;
while(m--){
LL t; cin>>t;
if(!t){
cout<<c<<endl;
}
else{
LL p,d; cin>>p>>d;
b[p]+=d;
if(a[p]==0 and b[p]<l);
else{
if(a[p-1] and a[p+1]) c--;
if(!a[p-1] and !a[p+1]) c++;
a[p] = !a[p];
}
}
}
return 0;
} | [
"f2016615@pilani.bits-pilani.ac.in"
] | f2016615@pilani.bits-pilani.ac.in |
acd645a91c1278511b79f532d037a4e761b01fa7 | c5e3ca2a2038b897e079a530074f2630ed1cba96 | /week 5/bubbleSort.cpp | e0111fa796793e0045e34b51c3594e2ac9c6d5ca | [] | no_license | NazerkeY/ADS | 001134597c909fc34c1e1743577208b5bb6c98a0 | c7c1e787d572c6dbaf516492a185208b3532e4e5 | refs/heads/master | 2022-12-09T09:11:43.426945 | 2020-09-07T12:37:58 | 2020-09-07T12:37:58 | 293,523,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | cpp | #include <iostream>
using namespace std;
int a[1000];
int n;
//убывающий сорт
int main(){
cin >> n;
for(int i = 0; i < n; i++)
cin >> a[i];
for(int i = 0; i < n - 1; i++){
for (int j = i + 1; j < n; j++)
if(a[i] < a[j]){ //a[i] > a[j];
swap(a[i], a[j]);
}
}
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
return 0;
} | [
"nazerke_5@inbox.ru"
] | nazerke_5@inbox.ru |
1631c085712de30d22a9f23f20b39b3093106099 | eba5ff0a3568dc9265bdc3929a8dd2e77e0f5560 | /Servers/ServerManager/vtkSMCaveRenderViewProxy.cxx | be69de580c558f2dfecd3dac939143cff0f87e23 | [
"LicenseRef-scancode-paraview-1.2"
] | permissive | kmorel/ParaView | 4b53b2279bb34a01290dcfee9d2ff8e42e9e6945 | 006cf719b9e07b0ee2c56f66fdf744bad4d18259 | refs/heads/master | 2021-01-17T16:25:02.519331 | 2010-08-04T22:10:14 | 2010-08-04T22:10:14 | 685,857 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,432 | cxx | /*=========================================================================
Program: ParaView
Module: vtkSMCaveRenderViewProxy.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSMCaveRenderViewProxy.h"
#include "vtkClientServerStream.h"
#include "vtkInformation.h"
#include "vtkInformationIntegerKey.h"
#include "vtkObjectFactory.h"
#include "vtkProcessModule.h"
#include "vtkPVOptions.h"
#include "vtkPVServerInformation.h"
#include "vtkSMIntVectorProperty.h"
#include "vtkSMDoubleVectorProperty.h"
#include "vtkSMIntVectorProperty.h"
#include "vtkSMRepresentationStrategy.h"
vtkStandardNewMacro(vtkSMCaveRenderViewProxy);
//-----------------------------------------------------------------------------
vtkSMCaveRenderViewProxy::vtkSMCaveRenderViewProxy()
{
}
//-----------------------------------------------------------------------------
vtkSMCaveRenderViewProxy::~vtkSMCaveRenderViewProxy()
{
}
//-----------------------------------------------------------------------------
void vtkSMCaveRenderViewProxy::ConfigureRenderManagerFromServerInformation()
{
vtkProcessModule* pm = vtkProcessModule::GetProcessModule();
vtkPVServerInformation* serverInfo = pm->GetServerInformation(
this->ConnectionID);
unsigned int idx;
unsigned int numMachines = serverInfo->GetNumberOfMachines();
vtkSMIntVectorProperty* ivp = vtkSMIntVectorProperty::SafeDownCast(
this->ParallelRenderManager->GetProperty("NumberOfDisplays"));
if (ivp)
{
ivp->SetElements1(numMachines);
}
// the property must be applied to the vtkobject before
// the property Displays is set.
this->ParallelRenderManager->UpdateProperty("NumberOfDisplays");
double* displays = new double[ numMachines*10];
for (idx = 0; idx < numMachines; idx++)
{
displays[idx*10+0] = idx;
displays[idx*10+1] = serverInfo->GetLowerLeft(idx)[0];
displays[idx*10+2] = serverInfo->GetLowerLeft(idx)[1];
displays[idx*10+3] = serverInfo->GetLowerLeft(idx)[2];
displays[idx*10+4] = serverInfo->GetLowerRight(idx)[0];
displays[idx*10+5] = serverInfo->GetLowerRight(idx)[1];
displays[idx*10+6] = serverInfo->GetLowerRight(idx)[2];
displays[idx*10+7] = serverInfo->GetUpperLeft(idx)[0];
displays[idx*10+8] = serverInfo->GetUpperLeft(idx)[1];
displays[idx*10+9] = serverInfo->GetUpperLeft(idx)[2];
}
vtkSMDoubleVectorProperty* dvp = vtkSMDoubleVectorProperty::SafeDownCast(
this->ParallelRenderManager->GetProperty("Displays"));
if (dvp)
{
dvp->SetElements(displays, numMachines*10);
}
this->ParallelRenderManager->UpdateVTKObjects();
}
//-----------------------------------------------------------------------------
void vtkSMCaveRenderViewProxy::EndCreateVTKObjects()
{
this->Superclass::EndCreateVTKObjects();
this->ConfigureRenderManagerFromServerInformation();
}
//-----------------------------------------------------------------------------
void vtkSMCaveRenderViewProxy::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| [
"julien.finet@kitware.com"
] | julien.finet@kitware.com |
992df743bfd9edaae61fa2758f17df5cb2d3252a | bc35a1498a8f9d61e1ed6d3c20489c18219793a3 | /io-utils.h | 95e0f7ecfe2f169d763c6ac89eec6af2a2ae3c63 | [] | no_license | tallisson/fluxo-enza | b2bd69f08dc81c5a34e00c1ef7308514b14e5163 | 3ab817e64c86b1ac6a233beb27080c618815e9b3 | refs/heads/master | 2020-05-21T01:45:45.399270 | 2017-03-10T11:27:13 | 2017-03-10T11:27:13 | 84,553,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | h | #ifndef IO_UTILS_H_
#define IO_UTILS_H_
#include "graph.h"
#include <vector>
#include <string>
namespace lf
{
struct data
{
public:
std::string m_label;
double m_value;
};
typedef data Data_t;
class IOUtils {
public:
IOUtils();
virtual ~IOUtils();
static std::string Print(std::vector<Data_t> values, int numSpace = 8);
static std::string Format(double v, int p = 5, int maxS = 10);
static std::string Format (std::string v, int maxS = 9);
static std::string WriteCdf(Graph* graph, double getBase);
static std::string WriteCnz(Graph* graph, double getBase);
static void WriteFile (std::string filename, int choose, Graph* graph, double base = 100);
static const std::string SEP;
};
}
#endif /* BRANCH_H_ */
| [
"allissonribeiro02@gmail.com"
] | allissonribeiro02@gmail.com |
9d7eacc9597a1851bab30a195dce403a84e0803e | d58ea99847a5ba1ee1e65326e506d685ed74c79d | /libocc/draw_primitives.h | eb0fc3818ca6a84bbb3037355ab6e08bd55d6c74 | [] | no_license | 15831944/DxfView | f43ad51e61820679497cb95ecc95d33c6c71bf9a | c28d4ecb561ccdc7b389d6bb70b8c227cf82bd19 | refs/heads/main | 2023-07-15T17:47:30.285591 | 2021-08-28T16:30:16 | 2021-08-28T16:30:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,401 | h | #ifndef DRAW_PRIMITIVES_H
#define DRAW_PRIMITIVES_H
#include <OSD.hxx>
#include <AIS_Shape.hxx>
#include <AIS_Trihedron.hxx>
#include <AIS_ViewCube.hxx>
#include <AIS_Selection.hxx>
#include <AIS_ColoredShape.hxx>
#include <AIS_ColoredDrawer.hxx>
#include <AIS_InteractiveContext.hxx>
#include <BRepLib.hxx>
#include <BRepOffsetAPI_ThruSections.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_Transform.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepPrimAPI_MakePrism.hxx>
#include <BRepPrimAPI_MakeSphere.hxx>
#include <BRepPrimAPI_MakeCone.hxx>
#include <BRepPrimAPI_MakeTorus.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRepFilletAPI_MakeFillet.hxx>
#include <BRepOffsetAPI_MakeThickSolid.hxx>
#include <BRepPrimAPI_MakeCylinder.hxx>
#include <BRepAlgoAPI_Fuse.hxx>
#include <BRepTools_ReShape.hxx>
#include <BRepTools.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <gp_Trsf.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Solid.hxx>
#include <TopExp.hxx>
#include <TopTools_IndexedMapOfShape.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS_Compound.hxx>
#include <TPrsStd_AISPresentation.hxx>
#include <STEPControl_Writer.hxx>
#include <STEPControl_Reader.hxx>
#include <STEPCAFControl_Reader.hxx>
#include <STEPCAFControl_Controller.hxx>
#include <Geom_Line.hxx>
#include <Geom_Circle.hxx>
#include <Geom_TrimmedCurve.hxx>
#include <Geom_CartesianPoint.hxx>
#include <GC_MakeArcOfCircle.hxx>
#include <GC_MakeArcOfEllipse.hxx>
#include <GC_MakeCircle.hxx>
#include <GC_MakeEllipse.hxx>
#include <GC_MakeSegment.hxx>
#include <gce_MakeRotation.hxx>
#include <TopExp.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS_Edge.hxx>
#include <TDocStd_Document.hxx>
#include <TDocStd_Application.hxx>
#include <TDF_Label.hxx>
#include <TDF_AttributeIterator.hxx>
#include <TDF_ChildIterator.hxx>
#include <TDF_LabelSequence.hxx>
#include <TDataStd_Name.hxx>
#include <TDataStd_TreeNode.hxx>
#include <TDataStd_UAttribute.hxx>
#include <TNaming_NamedShape.hxx>
#include <TopTools.hxx>
#include <Geom_Plane.hxx>
#include <Geom_CylindricalSurface.hxx>
#include <Geom2d_Ellipse.hxx>
#include <Geom2d_TrimmedCurve.hxx>
#include "Geom_Axis2Placement.hxx"
#include <GCE2d_MakeSegment.hxx>
#include <GC_MakeArcOfCircle.hxx>
#include <XCAFDoc_Area.hxx>
#include <XCAFDoc_Centroid.hxx>
#include <XCAFDoc_Datum.hxx>
#include <XCAFDoc_Dimension.hxx>
#include <XCAFDoc_Location.hxx>
#include <XCAFDoc_Volume.hxx>
#include <XCAFDoc_DocumentTool.hxx>
#include <XCAFDoc_ColorTool.hxx>
#include <XCAFDoc_ShapeTool.hxx>
#include <XCAFApp_Application.hxx>
#include <XCAFDoc_ColorTool.hxx>
#include <XCAFDoc_ShapeTool.hxx>
#include <XCAFDoc_DocumentTool.hxx>
#include <Quantity_Color.hxx>
#include <Quantity_ColorRGBA.hxx>
#include "XCAFPrs_DocumentExplorer.hxx"
#include <TDataStd_Name.hxx>
#include <XCAFDoc_AssemblyItemId.hxx>
#include <XCAFDoc_AssemblyItemRef.hxx>
#include <Font_BRepFont.hxx>
#include <Font_BRepTextBuilder.hxx>
#include <Bnd_Box.hxx>
#include "gp_Elips.hxx"
#include <OpenGl_GraphicDriver.hxx>
#include <V3d_View.hxx>
#include <Aspect_Handle.hxx>
#include <Aspect_DisplayConnection.hxx>
#include <Graphic3d_GraphicDriver.hxx>
#include <NCollection_Mat4.hxx>
#include <gp_Quaternion.hxx>
#include <gce_MakeCirc.hxx>
#include <GCPnts_AbscissaPoint.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <GCPnts_UniformAbscissa.hxx>
#ifdef Success
#undef Success
#endif
#include <cubic_spline.h>
//using namespace Eigen;
class OCCT
{
public:
// draw_primitives();
//! Draw 2d primitives:
static Handle(AIS_Shape) draw_2d_circle(gp_Pnt center,double radius);//
static Handle(AIS_Shape) draw_cp_2d_arc(gp_Pnt center, gp_Pnt point1, gp_Pnt point2);//! alpha1,2 in radians
static Handle(AIS_Shape) draw_2d_acad_arc(gp_Pnt center, double radius, const Standard_Real alpha1, const Standard_Real alpha2);//
static Handle(AIS_Shape) draw_2d_ellipse(gp_Pnt center, gp_Pnt secpoint, double alpha_start, double alpha_end, double ratio);//
static Handle(AIS_Shape) draw_2d_text(std::string str, int textheight, gp_Pnt point, double rot_deg);//
//! Draw 3d primitives:
static Handle(AIS_Shape) draw_3d_point(gp_Pnt point);//
static Handle(AIS_Shape) draw_3d_line(gp_Pnt point1, gp_Pnt point2);//
static Handle(AIS_Shape) draw_3d_line_wire(std::vector<gp_Pnt> points);//
static Handle(AIS_Shape) draw_3p_3d_arc(gp_Pnt point1, gp_Pnt point2, gp_Pnt point3);//
static Handle(AIS_Shape) draw_3p_3d_circle(gp_Pnt point1,gp_Pnt point2,gp_Pnt point3);//
static Handle(AIS_Shape) draw_3d_spline(std::vector<gp_Pnt> pointvec, int divisions);
// Divisions is spline resolution (number of line fragments / segmentation value).
//! Draw 3d solids:
static Handle(AIS_Shape) draw_3d_cone(gp_Pnt centerpoint, double bottomdiameter, double topdiameter, double height);//
static Handle(AIS_Shape) draw_3d_tcp_cone(gp_Pnt centerpoint, double bottomdiameter, double topdiameter, double height);//
static Handle(AIS_Shape) draw_3d_cilinder(double radius, double height);//
static Handle(AIS_Shape) draw_3d_sphere(double radius, gp_Pnt center);//
static Handle(AIS_Shape) draw_3d_box(double dx, double dy, double dz);//
//! Draw 3d tools:
static std::vector<Handle(AIS_Shape)> draw_3d_arc_lenght(gp_Pnt point1,
gp_Pnt point2,
gp_Pnt point3);
static double get_3d_line_lenght(gp_Pnt point1, gp_Pnt point2);
static double get_3d_arc_lenght(gp_Pnt point1,
gp_Pnt point2,
gp_Pnt point3,
int divisions);
static gp_Pnt get_3d_arc_point_given_arclenght_fromstartpoint(gp_Pnt point1,
gp_Pnt point2,
gp_Pnt point3,
double arclenght_from_startpoint); //
static Handle(AIS_Shape) rotate_3d(Handle(AIS_Shape) shape, gp_Pnt center, double euler_z, double euler_y, double euler_x);//
static Handle(AIS_Shape) rotate_translate_3d_quaternion(Handle(AIS_Shape) shape, gp_Pnt translation, double euler_z, double euler_y, double euler_x);//
static Handle(AIS_Shape) translate_3d(Handle(AIS_Shape) shape, gp_Pnt current, gp_Pnt target);//
static Handle(AIS_Shape) colorize(Handle(AIS_Shape) shape, Quantity_Color color, double transparancy);//
static gp_Pnt midpoint(gp_Pnt point1, gp_Pnt point2);
//! Draw 3d sets:
static Handle(AIS_Shape) draw_3d_origin(gp_Pnt origin, double linelenght);//
static Handle(AIS_Shape) draw_3d_point_origin_cone(gp_Pnt point, gp_Pnt euler);//
static Handle(AIS_Shape) draw_3d_point_origin_cone_text(gp_Pnt point, gp_Pnt euler, std::string text, int textheight, int textrotation);//
static Handle(AIS_Shape) draw_3d_line_origin_cone_text(gp_Pnt point1, gp_Pnt point2, gp_Pnt euler1, gp_Pnt euler2, std::string text, int textheight);static Handle(AIS_Shape) draw_3d_wire_origin_cone_text(std::vector<gp_Pnt> points, std::vector<gp_Pnt> euler, std::string text, int textheight);static Handle(AIS_Shape) draw_3d_arc_origin_cone_text(std::vector<gp_Pnt> points, std::vector<gp_Pnt> euler, std::string text, int textheight);static Handle(AIS_Shape) draw_3d_circle_origin_cone_text(std::vector<gp_Pnt> points, std::vector<gp_Pnt> euler, std::string text, int textheight);static Handle(AIS_Shape) draw_3d_spline_origin_cone_text(std::vector<gp_Pnt> points, std::vector<gp_Pnt> euler, int divisions, std::string text, int textheight);
//! Autocad colors:
static Quantity_Color autocad_color(int colornr);
//! Get arc startpoint[0], controlpoint[1], endpoint[2], alpha 1,2 in radians
static std::vector<gp_Pnt> get_cp_2d_acad_arc_points(gp_Pnt center,
double radius,
double alpha1,
double alpha2);
//! Get extra circle circumfence points, gp_Pnt input = 3x circle circumfence point.
static std::vector<gp_Pnt> get_cirlce_circumfence_points(gp_Pnt center,
double radius,
int division);
//! Get extra arc circumfence points.
static std::vector<gp_Pnt> get_arc_circumfence_points(gp_Pnt center,
double radius,
double alpha1,
double alpha2,
int division);
//! Get extra ellipse circumfence points.
static std::vector<gp_Pnt> get_ellipse_circumfence_points(gp_Pnt center,
gp_Pnt secpoint,
double alpha_start,
double alpha_end,
double ratio,
int division);
};
#endif // DRAW_PRIMITIVES_H
| [
"django013@nobodiesfool.com"
] | django013@nobodiesfool.com |
665b2fca77caf571940ee4c8f10720a7b444da2b | 146698dcc3a2cbc9bdbf855add3fd7d6a1934c50 | /SampleCodes/Polymorphism/overring_pointer.cc | f23e4dfe211c38f55d98380a2c15f5d160341921 | [] | no_license | geunkim/CPPLectures | 1e0d80a6f7348d5abae6ea4fe7b0b0be3de3afee | a402e912777c2d280a2103fa968e6c91dab63435 | refs/heads/master | 2023-07-20T14:57:25.165971 | 2023-07-17T01:28:40 | 2023-07-17T01:28:40 | 210,631,519 | 32 | 104 | null | 2023-03-21T23:52:22 | 2019-09-24T15:05:32 | C++ | UTF-8 | C++ | false | false | 1,119 | cc | #include <iostream>
using namespace std;
class Base
{
public:
virtual void print() {
cout << "print() in base class" << endl;
}
void show() {
cout << "show() in base class" << endl;
}
};
class Derived : public Base
{
public:
void print() {
cout << "print() in derived class" << endl;
}
void show() {
cout << "show() in derived class" << endl;
}
};
int main(int argc, char const *argv[])
{
Base b, *bptr;
Derived d, *dptr;
b.print(); // Base 클래스의 print() 함수 호출
d.print(); // Derived 클래스의 print() 함수 호출
bptr = &d; // Derived의 객체 d를 Base 자료형의 포인터 변수에 저장
cout << endl;
cout << "Base 객체 b의 주소: " << &b << endl;
bptr->print(); // Base 포인터 변수를 통해 Derived 객체의 print() 함수 호출
bptr->show(); // Base 포인터 변수를 통해 Base 객체의 show() 함수 호출
cout << endl;
cout << "Derived 객체 d의 주소: " << &d << endl;
bptr->Base::print(); // Base 포인터 변수를 통해 Derived 객체의 print() 함수 호출
cout << "bptr 주소: " << bptr << endl;
return 0;
} | [
"geunkim@deu.ac.kr"
] | geunkim@deu.ac.kr |
ac57a71351107ad6b854c65e07ff45d102bcd2ad | 614369bd9a9452f6b48b9c667b12daacf153d6b8 | /Dongmin/SWEA/핀볼게임/P5650.cpp | 3c26930d3b47b24effdc5e66ed2afd723d210ed1 | [] | no_license | minji0320/Algorithm_for_CodingTest | 339ad05a81a89b2645dfab73d7bcbc2df9775d77 | 7fc091f93693d549fa1975044f4b4ff5ee056520 | refs/heads/master | 2022-06-26T05:14:27.149435 | 2021-06-30T00:16:38 | 2021-06-30T00:16:38 | 242,951,278 | 2 | 0 | null | 2020-02-25T08:43:49 | 2020-02-25T08:43:48 | null | UTF-8 | C++ | false | false | 3,570 | cpp | #include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
typedef struct Pos{
int row;
int col;
}Pos;
typedef struct Ball{
Pos pos;
int dir;
} Ball;
bool operator==(const Pos& a, const Pos& b) {
return a.row==b.row && a.col==b.col;
}
Pos operator+(const Pos& a, const Pos& b) {
return Pos{a.row+b.row,a.col+b.col};
}
bool operator<(const Pos& a, const Pos& b) {
if(a.row<b.row) {
return true;
} else if(a.row==b.row){
return a.col<b.col;
}
return false;
}
int N;
vector<vector<int> > board;
int dr[4] = {-1,0,1,0};
int dc[4] = {0,1,0,-1};
vector<int> blocks[6];
vector<Pos> holes[5];
map<Pos, Pos> wormhole;
Ball ball;
void getInput() {
cin>>N;
board.assign(N,vector<int>(N,0));
wormhole.clear();
for(int i=0;i<5;i++){
holes[i].clear();
}
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cin >> board[i][j];
if(board[i][j]==6){
holes[0].push_back(Pos{i,j});
} else if(board[i][j]==7){
holes[1].push_back(Pos{i,j});
} else if(board[i][j]==8){
holes[2].push_back(Pos{i,j});
} else if(board[i][j]==9){
holes[3].push_back(Pos{i,j});
} else if(board[i][j]==10){
holes[4].push_back(Pos{i,j});
}
}
}
for(int i=0; i<5; i++){
if(holes[i].size()>0){
wormhole.insert(make_pair(holes[i][0],holes[i][1]));
wormhole.insert(make_pair(holes[i][1],holes[i][0]));
}
}
blocks[1]={2,3,1,0};
blocks[2]={1,3,0,2};
blocks[3]={3,2,0,1};
blocks[4]={2,0,3,1};
blocks[5]={2,3,0,1};
}
bool isWall(Pos pos){
return !(pos.row>=0 && pos.row<N && pos.col>=0 && pos.col<N);
}
void pinBall(Pos init, int& max) {
int score = 0;
bool hitWall=false;
do {
Pos newpos=hitWall?ball.pos:ball.pos + Pos{dr[ball.dir],dc[ball.dir]};
if(isWall(newpos)) {
ball.dir=blocks[5][ball.dir];
score += 1;
hitWall=true;
}
else if(board[newpos.row][newpos.col] > 0) {
if(board[newpos.row][newpos.col] < 6) {
int blocknum = board[newpos.row][newpos.col];
ball.pos=newpos;
ball.dir=blocks[blocknum][ball.dir];
score += 1;
hitWall=false;
}
else {
ball.pos=wormhole.find(newpos)->second;
hitWall=false;
}
}
else{
ball.pos=newpos;
hitWall=false;
}
//printf("ball pos = (%d,%d) dir=%d, init = (%d,%d)\n", ball.pos.row, ball.pos.col, ball.dir,init.row,init.col);
}while(!(ball.pos==init) && board[ball.pos.row][ball.pos.col]!=-1);
if(score>max){
max=score;
}
}
void solution(int testnum) {
int ans=0;
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
for(int k=0; k<4; k++){
if(board[i][j]==0) {
ball.pos = {i,j};
ball.dir = k;
//printf("start ball.pos=(%d,%d), dir=%d\n", ball.pos.row,ball.pos.col,ball.dir);
pinBall(Pos{i,j}, ans);
}
}
}
}
printf("#%d %d\n", testnum, ans);
}
int main(int argc, char** argv)
{
int test_case;
int T;
cin>>T;
for(test_case = 1; test_case <= T; ++test_case)
{
getInput();
solution(test_case);
}
return 0;
} | [
"pkalsh345@gmail.com"
] | pkalsh345@gmail.com |
e27665d12a3fa8e2ee24a8b4fca02d1450c7dd2b | 0956bbe8ac9564845aa49f1185f53fd3e3c76e95 | /CSC564-concurrency/river-crossing-problem.cpp | 2a4455cd6c2084b9a3b97df3bb040babbf34a2f6 | [] | no_license | sheoranjs24/grad-school | d7879ddd9e064ddc1f8964cf96de0459bc1b8ece | eefc38f53c6211cade7427e502b7526ad27d3942 | refs/heads/master | 2016-08-05T17:49:22.061437 | 2015-01-17T22:17:47 | 2015-01-17T22:17:47 | 29,404,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,428 | cpp | /*
River Crossing Problem
Solution:
3 semaphores are used for Go_thread queue, Pthread queue and boarding.
1 global mutex mt.
Two variables cGo, cPt to count no of threads waiting for boarding.
One local isCaptian.
Go Thread function :
When go thread arrives, it checks if there are enough threads present
to board the boat, if yes then it declares itself as captain, wakes up
exactly 3 threads and then waits on those 3 threads to board the boat,
then the thread will call row_boat.
PThread function: works the same way.
Mutex mt is used to access shared info - cGo and cPt. Threads must
release mt before going on wait/sleep. Only captain thread keeps the
mutex mt untill it calls row_boat.
*/
#include<cstdio>
#include<iostream>
#include<thread>
#include<chrono>
#include<cstdlib>
#include<queue>
#include<string>
#include"river-crossing-problem.hpp"
using namespace std;
using namespace std::chrono;
// semaphore defined
class semaphore{
private:
mutex mtx;
condition_variable cv;
unsigned int count;
public:
semaphore(unsigned int count_ = 0):count(count_){;}
void notify(unsigned numRes=1)
{
unique_lock<mutex> lck(mtx);
count += numRes;
for (; numRes>0; --numRes) {
cv.notify_one();
}
}
void wait(unsigned int numRes = 1)
// can pass arg (thread_id) for queue notify order
{
unique_lock<mutex> lck(mtx);
while(count < numRes){ //==0
cv.wait(lck);
}
count -= numRes;
}
};
// global variables
collector mdata;
thread tgo[THREAD_COUNT];
semaphore sGo, sPt, sboard, smain;
mutex mt, mlk;
int cGo=0, cPt=0,j,k;
string board;
atomic_int boat_count, passenger_count;
atomic_bool first_boat;
chrono::high_resolution_clock::time_point start_time, stop_time;
//funcitons
void go_fn(int i);
void pthread_fn(int i);
void generate_threads();
void generate_threads()
{
boat_count=0; first_boat=true;
while (1){
if ((rand()%2) == 0) {
go_fn(++passenger_count);
} else {
pthread_fn(++passenger_count);
}
//std::this_thread::sleep_for(chrono::milliseconds(5));
}
}
void go_fn(int i) {
bool isCaptain;
isCaptain = false;
//printf("Arrived : %u from GO\n",i);
mt.lock();
cGo++;
if (cGo >= 4 ) {
sGo.notify(3);
cGo -= 4;
isCaptain = true;
} else if ( (cGo >= 2) && (cPt >= 2)) {
sGo.notify(1);
sPt.notify(2);
cPt -= 2;
cGo -= 2;
isCaptain = true;
} else {
mt.unlock();
sGo.wait();
//printf("G");
sboard.notify();
}
//printf("Boarded :%d of GO\n",i);
if (isCaptain) {
// wait for others to board
sboard.wait(3);
if (first_boat) {
start_time = chrono::high_resolution_clock::now();
first_boat = false;
}
//printf("Rowing Boat : %u of GO\n",i);
if (++boat_count >= TOTAL_BOAT_COUNT) {
stop_time = chrono::high_resolution_clock::now();
smain.notify();
return;
}
mt.unlock();
}
}
void pthread_fn (int i){
bool isCaptain;
isCaptain = false;
//printf("Arrived : %u from PT\n",i);
mt.lock();
cPt++;
if (cPt >= 4 ) {
sPt.notify(3);
cPt -= 4;
isCaptain = true;
} else if ( (cPt >= 2) && (cGo >= 2)) {
sPt.notify(1);
sGo.notify(2);
cGo -= 2;
cPt -= 2;
isCaptain = true;
} else {
mt.unlock();
sPt.wait();
sboard.notify();
}
//printf("Boarded :%d of PT\n",i);
if (isCaptain) {
//printf("Rowing Boat : %u of PT\n",i);
sboard.wait(3);
//printf("Rowing Boat : %u of P\n",i);
if (++boat_count >= TOTAL_BOAT_COUNT) {
stop_time = chrono::high_resolution_clock::now();
smain.notify();
return;
}
mt.unlock();
}
//generate_threads();
}
int main(int argc, char **argv){
//Declare variables
int i;
high_resolution_clock::duration avg_time(0);
size_t boarded_count=0;
// Intialize them
srand(time(0));
passenger_count =0;
printf("Program starting..\n");
// start threads : random order
for(i = 0; i < THREAD_COUNT; i++) {
tgo[i] = thread(&generate_threads);
}
smain.wait();
printf("Program exiting.\n");
auto time = stop_time - start_time;
cout<<"total time for 1000 boats :"<<duration<double, micro>(time).count()<< "micro seconds"<<endl;
exit(0);
/* sleeps
/std::this_thread::sleep_for(chrono::seconds(10));
for(i=0; i< THREAD_COUNT; i++) {
tgo[i].join();
tpt[i].join();
} */
printf("Program completed.\n");
} | [
"sheoranjs24@gmail.com"
] | sheoranjs24@gmail.com |
58e1a194731a4545947fca9c670f01b67f758e32 | 5f67658f61d03a786005752583077a40b42d03b1 | /UtilityClasses/TraceEvents.cc | 9627b06bbef916bd14cbfd1702703734a033fb13 | [] | no_license | newtonresearch/newton-framework | d0e5c23dfdc5394e0c94e7e1b7de756eac4ed212 | f922bb3ac508c295b155baa0d4dc7c7982b9e2a2 | refs/heads/master | 2022-06-26T21:20:18.121059 | 2022-06-01T17:39:47 | 2022-06-01T17:39:47 | 31,951,762 | 22 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,003 | cc | /*
File: TraceEvents.cc
Contains: Event history collector implementation.
Written by: Newton Research Group, 2010.
*/
#include "TraceEvents.h"
/*--------------------------------------------------------------------------------
C H i s t o r y C o l l e c t o r
--------------------------------------------------------------------------------*/
class CHistoryCollector : public CEventCollector
PROTOCOLVERSION(1.0)
{
public:
PROTOCOL_IMPL_HEADER_MACRO(CHistoryCollector)
CHistoryCollector * make(void);
void destroy(void);
NewtonErr init(unsigned int, char*, char*, int, int);
void addAddressReset(void);
void addAddress(void);
void addDescriptions(EventTraceCauseDesc*, int);
void addReset(const void*);
void addReset(unsigned char);
void addReset(unsigned long);
void add(const void*);
void add(unsigned char);
void add(unsigned long);
void collectionControl(int);
};
void
InitEvents(void)
{
// CHistoryCollector::classInfo()->registerProtocol();
}
| [
"simon@newtonresearch.org"
] | simon@newtonresearch.org |
98ea6b058d403b6441755cc99dd78d6a2f4abcaa | cd2bf52d6f31268d07b8f25276fd19042622d3b7 | /hinchee_sean.assignment-1.10/sprite.cpp | 23e2d72a1dfce562a05dfee12b55c3e3e0d6a1c0 | [] | no_license | henesy/cs327 | 12b2e17319191d620feb5db1185d37474ee1be04 | 879af12b7b075168c2d68105122f0c9df7cfd899 | refs/heads/master | 2021-04-30T22:22:33.393881 | 2018-02-14T07:38:33 | 2018-02-14T07:38:33 | 66,587,003 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 6,289 | cpp | #include "dungeon_generator.h"
/***
setter functions
***/
Sprite * initSprite() {
return new Sprite;
}
Sprite * initSprites(int n) {
return new Sprite[n];
}
/***
copy function, deep copy
***/
void copySprite(Sprite * to, Sprite * from) {
to->p.x = from->p.x ;
to->p.y = from->p.y ;
to->c = from->c ;
to->s.in = from->s.in;
to->s.te = from->s.te;
to->s.tu = from->s.tu;
to->s.eb = from->s.eb;
to->s.s = from->s.s ;
to->t = from->t ;
to->to.x = from->to.x;
to->to.y = from->to.y;
to->sn = from->sn ;
to->pc.x = from->pc.x;
to->pc.y = from->pc.y;
to->a = from->a ;
}
void copyPC(PC * to, PC * from) {
to->p.x = from->p.x;
to->p.y = from->p.y ;
to->c = from->c ;
to->s.in = from->s.in;
to->s.te = from->s.te;
to->s.tu = from->s.tu;
to->s.eb = from->s.eb;
to->s.pa = from->s.pa;
to->s.s = from->s.s ;
to->t = from->t ;
to->to.x = from->to.x;
to->to.y = from->to.y;
to->sn = from->sn ;
to->pc.x = from->pc.x;
to->pc.y = from->pc.y;
to->a = from->a ;
to->color= from->color;
int i;
for(i = 0; i < 12; i++) {
to->eqs[i] = from->eqs[i];
to->eqsp[i] = from->eqsp[i];
}
for(i = 0; i < 10; i++) {
to->inv[i] = from->inv[i];
to->invp[i] = from->invp[i];
}
}
void copyASprite(Sprite * to, int n, Sprite * from) {
(to[n]).p.x = from->p.x ;
(to[n]).p.y = from->p.y ;
(to[n]).c = from->c ;
(to[n]).s.a = from->s.a;
(to[n]).s.in = from->s.in;
(to[n]).s.te = from->s.te;
(to[n]).s.tu = from->s.tu;
(to[n]).s.eb = from->s.eb;
(to[n]).s.pa = from->s.pa;
(to[n]).s.s = from->s.s ;
(to[n]).t = from->t ;
(to[n]).to.x = from->to.x;
(to[n]).to.y = from->to.y;
(to[n]).sn = from->sn ;
(to[n]).pc.x = from->pc.x;
(to[n]).pc.y = from->pc.y;
(to[n]).a = from->a ;
(to[n]).color= from->color;
}
Sprite * thisASprite(Sprite * arr, int i) {
return arr[i].thisSprite();
}
Sprite * Sprite::thisSprite() {
return this;
}
/***
getter functions
***/
/* singleton */
int getSpritePX(Sprite * s) {
return s->p.x;
}
int getSpritePY(Sprite * s) {
return s->p.y;
}
char getSpriteC(Sprite * s) {
return s->c;
}
bool getSpriteSIn(Sprite * s) {
return s->s.in;
}
bool getSpriteSTe(Sprite * s) {
return s->s.te;
}
bool getSpriteSTu(Sprite * s) {
return s->s.tu;
}
bool getSpriteSEb(Sprite * s) {
return s->s.eb;
}
int getSpriteSS(Sprite * s) {
return s->s.s;
}
int getSpriteT(Sprite * s) {
return s->t;
}
int getSpriteToX(Sprite * s) {
return s->to.x;
}
int getSpriteToY(Sprite * s) {
return s->to.y;
}
int getSpriteSn(Sprite * s) {
return s->sn;
}
int getSpritePcX(Sprite * s) {
return s->pc.x;
}
int getSpritePcY(Sprite * s) {
return s->pc.y;
}
bool getSpriteA(Sprite * s) {
return s->a;
}
/* array-based */
int getSpriteAPX(Sprite * s, int i) {
return s[i].p.x;
}
int getSpriteAPY(Sprite * s, int i) {
return s[i].p.y;
}
char getSpriteAC(Sprite * s, int i) {
return s[i].c;
}
bool getSpriteASIn(Sprite * s, int i) {
return s[i].c;
}
bool getSpriteASTe(Sprite * s, int i) {
return s[i].s.te;
}
bool getSpriteASTu(Sprite * s, int i) {
return s[i].s.tu;
}
bool getSpriteASEb(Sprite * s, int i) {
return s[i].s.eb;
}
int getSpriteASS(Sprite * s, int i) {
return s[i].s.s;
}
int getSpriteAT(Sprite * s, int i) {
return s[i].t;
}
int getSpriteAToX(Sprite * s, int i) {
return s[i].to.x;
}
int getSpriteAToY(Sprite * s, int i) {
return s[i].to.y;
}
int getSpriteASn(Sprite * s, int i) {
return s[i].sn;
}
int getSpriteAPcX(Sprite * s, int i) {
return s[i].pc.x;
}
int getSpriteAPcY(Sprite * s, int i) {
return s[i].pc.y;
}
bool getSpriteAA(Sprite * s, int i) {
return s[i].a;
}
/***
Setter functions
kill me
***/
/* singleton */
void setSpritePX(Sprite * s, int n) {
s->p.x = n;
}
void setSpritePY(Sprite * s, int n) {
s->p.y = n;
}
void setSpriteC(Sprite * s, char c) {
s->c = c;
}
void setSpriteSIn(Sprite * s, bool b) {
s->s.in = b;
}
void setSpriteSTe(Sprite * s, bool b) {
s->s.te = b;
}
void setSpriteSTu(Sprite * s, bool b) {
s->s.tu = b;
}
void setSpriteSEb(Sprite * s, bool b) {
s->s.eb = b;
}
void setSpriteSS(Sprite * s, int n) {
s->s.s = n;
}
void setSpriteT(Sprite * s, int n) {
s->t = n;
}
void setSpriteToX(Sprite * s, int n) {
s->to.x = n;
}
void setSpriteToY(Sprite * s, int n) {
s->to.y = n;
}
void setSpriteSn(Sprite * s, int n) {
s->sn = n;
}
void setSpritePcX(Sprite * s, int n) {
s->pc.x = n;
}
void setSpritePcY(Sprite * s, int n) {
s->pc.y = n;
}
void setSpriteA(Sprite * s, bool b) {
s->a = b;
}
/* array-based */
void setSpriteAPX(Sprite * s, int i, int n) {
s[i].p.x = n;
}
void setSpriteAPY(Sprite * s, int i, int n) {
s[i].p.y = n;
}
void setSpriteAC(Sprite * s, int i, char c) {
s[i].c = c;
}
void setSpriteASIn(Sprite * s, int i, bool b) {
s[i].s.in = b;
}
void setSpriteASTe(Sprite * s, int i, bool b) {
s[i].s.te = b;
}
void setSpriteASTu(Sprite * s, int i, bool b) {
s[i].s.tu = b;
}
void setSpriteASEb(Sprite * s, int i, bool b) {
s[i].s.eb = b;
}
void setSpriteASS(Sprite * s, int i, int n) {
s[i].s.s = n;
}
void setSpriteAT(Sprite * s, int i, int n) {
s[i].t = n;
}
void setSpriteAToX(Sprite * s, int i, int n) {
s[i].to.x = n;
}
void setSpriteAToY(Sprite * s, int i, int n) {
s[i].to.y = n;
}
void setSpriteASn(Sprite * s, int i, int n) {
s[i].sn = n;
}
void setSpriteAPcX(Sprite * s, int i, int n) {
s[i].pc.x = n;
}
void setSpriteAPcY(Sprite * s, int i, int n) {
s[i].pc.y = n;
}
void setSpriteAA(Sprite * s, int i, bool b) {
s[i].a = b;
}
/***
Position functions
### These exist because positions are used outside of classes for this project ###
can be safely moved out of sprite at a later time
***/
int getPosX(Position * p) {
return p->x;
}
int getPosY(Position * p) {
return p->y;
}
void setPosX(Position * p, int n) {
p->x = n;
}
void setPosY(Position * p, int n) {
p->y = n;
}
Position * initPos(void) {
return new Position;
}
| [
"henesy.dev@gmail.com"
] | henesy.dev@gmail.com |
1d8c23cbb1b2c796da26f00fb768e6535bea8804 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_6875.cpp | 80e8e32356ee457e1b28803b3ba6c8bf01ea23c8 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | cpp | {
failf(data, "unsupported max version passed via CURLOPT_SSLVERSION");
return result;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
697605af695c69e5e92ac7e962b573aefe078f17 | b170ae97dfc59078f04fbfc21719d4991ef3fdc3 | /volume_appendix.cpp | 612324bd1994f98eae977626d6ea16fb3e1bf1ae | [] | no_license | bolverk/adiabatic_bow_shock | 56f2a05d49160b139f4f43a0ce18f45bc1dc178b | f44d8ba0f31d330f61434394bff2366cd0e1ecee | refs/heads/master | 2021-01-10T20:43:49.250319 | 2018-11-15T15:02:18 | 2018-11-15T15:02:18 | 39,457,295 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | #include "volume_appendix.hpp"
VolumeAppendix::VolumeAppendix(void) {}
string VolumeAppendix::getName(void) const
{
return "volumes";
}
vector<double> VolumeAppendix::operator()(const hdsim& sim) const
{
const CacheData& cd = sim.getCacheData();
vector<double> res(cd.volumes.size(),0);
for(size_t i=0;i<cd.volumes.size();++i)
res[i] = cd.volumes[i];
return res;
}
| [
"almog.yalin@gmail.com"
] | almog.yalin@gmail.com |
283bbe72439c2b8d81685cc9756790b32a661e8c | 65e00876bdb944938fc9f80f74c98372268d4d3d | /Linked Lists/4.cpp | 646e586d3bc082af787c4e0c9ad5bb9e5a4be81f | [] | no_license | nipunarora-eGov/Coding-Interview-101 | 372086b1e80f03e3f00a7b5b8616e0966c0a29f6 | 9fda66bfe0afedc2d161b1657e75a286a0ccdb9e | refs/heads/main | 2023-02-15T07:59:33.433792 | 2021-01-06T09:57:42 | 2021-01-06T09:57:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | cpp | //https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/(refer it for other method)
//mathematically proove krna seekho ki jab loop node milta h then head aur loop node are equidistant(circularly) from the firts node in loop
| [
"aroranipun1@gmail.com"
] | aroranipun1@gmail.com |
c492cbcdd5a12a737d569c7277c13ef8402dbe8f | 04dd3fb4c383c3a84f7e7dbf6abfe8936c5744e3 | /Desdinova Engine/DEInput.cpp | 73879f42e7962a583aa9f8de9d34e9de58c29802 | [] | no_license | desdinovait/DesdinovaEngineCplusplus | d33f391dd710a26a8b0c189929075966afd784bc | e5a18e80ba40695d33b01431be2b8327d65ac1a5 | refs/heads/main | 2023-01-12T14:21:28.104181 | 2020-11-19T08:15:24 | 2020-11-19T08:15:24 | 314,180,835 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 22,419 | cpp | #include "DEGeneralIncludes.h"
LPDIRECTINPUT8 DEInput::DirectInputObject=NULL;
LPDIRECTINPUTDEVICE8 DEInput::KeyboardDevice=NULL;
LPDIRECTINPUTDEVICE8 DEInput::MouseDevice=NULL;
LPDIRECTINPUTDEVICE8 DEInput::JoyDevice=NULL;
DLL_API BOOL CALLBACK EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance, VOID* pContext )
{
HRESULT hr;
hr = DEInput::DirectInputObject->CreateDevice( pdidInstance->guidInstance, &DEInput::JoyDevice, NULL );
if( FAILED(hr) )
return DIENUM_CONTINUE;
return DIENUM_STOP;
}
DLL_API BOOL CALLBACK EnumObjectsCallback( const DIDEVICEOBJECTINSTANCE* pdidoi, VOID* pContext )
{
static int nSliderCount = 0; // Number of returned slider controls
static int nPOVCount = 0; // Number of returned POV controls
// For axes that are returned, set the DIPROP_RANGE property for the
// enumerated axis in order to scale min/max values.
if( pdidoi->dwType & DIDFT_AXIS )
{
DIPROPRANGE diprg;
diprg.diph.dwSize = sizeof(DIPROPRANGE);
diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diprg.diph.dwHow = DIPH_BYID;
diprg.diph.dwObj = pdidoi->dwType; // Specify the enumerated axis
diprg.lMin = -1000;
diprg.lMax = +1000;
// Set the range for the axis
if( FAILED( DEInput::JoyDevice->SetProperty( DIPROP_RANGE, &diprg.diph ) ) )
return DIENUM_STOP;
}
return DIENUM_CONTINUE;
}
DLL_API void DEInput::Release()
{
if(KeyboardDevice != NULL)
{
KeyboardDevice->Unacquire();
SafeRelease(KeyboardDevice);
}
if(MouseDevice != NULL)
{
MouseDevice->Unacquire();
SafeRelease(MouseDevice);
}
if(JoyDevice != NULL)
{
JoyDevice->Unacquire();
SafeRelease(JoyDevice);
}
SafeRelease(DirectInputObject);
isCreated = false;
keyboardCreated = false;
mouseCreated = false;
joyCreated = false;
mainHWND = NULL;
}
DLL_API bool DEInput::Init(HWND engineHWND)
{
DirectInputObject = NULL;
KeyboardDevice = NULL;
MouseDevice = NULL;
isCreated = false;
keyboardCreated = false;
mouseCreated = false;
DELog::LogInfo("<br><b>DirectInput Initialization</b>");
D3DVIEWPORT9 currentViewport;
hr = DECore::D3DDevice->GetViewport(¤tViewport);
if (hr == D3D_OK)
{
m_fCursorX = (float)currentViewport.Width / 2;
m_fCursorY = (float)currentViewport.Height / 2;
m_dwScreenWidth = currentViewport.Width;
m_dwScreenHeight = currentViewport.Height;
DELog::LogInfo("<li>CurrentViewport Dimensions: %dx%d", m_dwScreenWidth, m_dwScreenHeight);
}
else
{
DELog::LogWarning("<li>Device->GetViewport(...): %s - Impossible to retrive viewport informations", DXGetErrorDescription9(hr));
}
//DirectInput
hr = DirectInput8Create(GetModuleHandle(NULL),DIRECTINPUT_VERSION,IID_IDirectInput8,(void**)&DirectInputObject,NULL);
if (hr==DI_OK)
{
DELog::LogInfo("<li>DirectInput8Create(...): %s", DXGetErrorDescription9(hr));
isCreated = true;
}
else
{
DELog::LogError("<li>DirectInput8Create(...): %s", DXGetErrorDescription9(hr));
isCreated = false;
}
//Creazione periferiche
if (isCreated)
{
//Keyboard
hr = DirectInputObject->CreateDevice(GUID_SysKeyboard,&KeyboardDevice,NULL);
if (hr==DI_OK)
{
hr = KeyboardDevice->SetDataFormat(&c_dfDIKeyboard);
if (hr==DI_OK)
{
hr = KeyboardDevice->SetCooperativeLevel(engineHWND, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE);
if (hr==DI_OK)
{
hr = KeyboardDevice->Acquire();
if (hr==DI_OK)
{
DELog::LogInfo("<li>KeyboardDevice->Acquire(...): %s", DXGetErrorDescription9(hr));
keyboardCreated = true;
}
else
{
DELog::LogError("<li>KeyboardDevice->Acquire(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>KeyboardDevice->SetCooperativeLevel(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>KeyboardDevice->SetDataFormat(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>KeyboardDevice: NULL - %s", DXGetErrorDescription9(hr));
}
//Mouse
DIDEVCAPS MouseCapabilities;
hr = DirectInputObject->CreateDevice(GUID_SysMouse,&MouseDevice,NULL);
if (hr==DI_OK)
{
hr = MouseDevice->SetDataFormat(&c_dfDIMouse2);
if (hr==DI_OK)
{
hr = MouseDevice->SetCooperativeLevel(engineHWND,DISCL_BACKGROUND | DISCL_NONEXCLUSIVE);
if (hr==DI_OK)
{
hr = MouseDevice->Acquire();
if (hr==DI_OK)
{
DELog::LogInfo("<li>MouseDevice->Acquire(...): %s", DXGetErrorDescription9(hr));
MouseCapabilities.dwSize = sizeof(MouseCapabilities);
MouseDevice->GetCapabilities(&MouseCapabilities);
if(!(MouseCapabilities.dwFlags & DIDC_ATTACHED))
{
DELog::LogWarning("<li>MouseCapabilities.dwFlags: Mouse not currently attached");
}
m_dwAxes = MouseCapabilities.dwAxes;
m_dwButtons = MouseCapabilities.dwButtons;
mouseCreated=true;
}
else
{
DELog::LogError("<li>MouseDevice->Acquire(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>MouseDevice->SetCooperativeLevel(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>MouseDevice->SetDataFormat(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>MouseDevice: NULL - %s", DXGetErrorDescription9(hr));
}
//Joy
hr = DirectInputObject->EnumDevices( DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, NULL, DIEDFL_ATTACHEDONLY );
if (hr==DI_OK)
{
if( JoyDevice != NULL )
{
hr = JoyDevice->SetDataFormat( &c_dfDIJoystick2 );
if (hr==DI_OK)
{
hr = JoyDevice->SetCooperativeLevel( engineHWND, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE );
if (hr==DI_OK)
{
hr = JoyDevice->EnumObjects( EnumObjectsCallback, NULL, DIDFT_ALL );
if (hr==DI_OK)
{
hr = JoyDevice->Poll();
if (FAILED(hr))
{
hr = JoyDevice->Acquire();
while(hr == DIERR_INPUTLOST)
{
hr = JoyDevice->Acquire();
}
DIDEVICEINSTANCE joyInfo;
hr = JoyDevice->GetDeviceInfo(&joyInfo);
DELog::LogInfo("<li>JoyDevice->Acquire(...): %s", DXGetErrorDescription9(hr));
joyCreated=true;
}
}
else
{
DELog::LogInfo("<li>JoyDevice->EnumObjects(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>JoyDevice->SetCooperativeLevel(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>JoyDevice->SetDataFormat(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogWarning("<li>JoyDevice: NULL");
}
}
else
{
DELog::LogInfo("<li>JoyDevice->EnumDevices(...): %s", DXGetErrorDescription9(hr));
}
}
else
{
DELog::LogError("<li>DirectInputObject: NULL");
}
if (isCreated) DELog::LogInfo("<li>Created successfully");
else DELog::LogError("<li>NOT Created");
return isCreated;
}
DLL_API bool DEInput::Update(bool useKeyboard, bool useMouse, bool useJoy)
{
if ((useKeyboard)&&(keyboardCreated))
{
hr = KeyboardDevice->GetDeviceState(sizeof(m_KeyBuffer),(LPVOID)&m_KeyBuffer);
if (hr==DIERR_INPUTLOST)
{
KeyboardDevice->Acquire();
}
}
if ((useMouse)&&(mouseCreated))
{
hr=MouseDevice->GetDeviceState(sizeof(DIMOUSESTATE2),(LPVOID)&m_MouseState);
if (hr==DIERR_INPUTLOST)
{
MouseDevice->Acquire();
}
//Asse X
m_fCursorX += m_MouseState.lX * m_fSensitivity;
if(m_fCursorX < 0) m_fCursorX = 0;
else if(m_fCursorX > m_dwScreenWidth) m_fCursorX = (float)m_dwScreenWidth;
//Asse Y
if(m_bInverted) m_fCursorY -= m_MouseState.lY * m_fSensitivity;
else m_fCursorY += m_MouseState.lY * m_fSensitivity;
if(m_fCursorY < 0) m_fCursorY = 0;
else if(m_fCursorY > m_dwScreenHeight) m_fCursorY = (float)m_dwScreenHeight;
}
if ((useJoy)&&(joyCreated))
{
hr = JoyDevice->Poll();
if (hr==DIERR_INPUTLOST)
{
JoyDevice->Acquire();
}
hr = JoyDevice->GetDeviceState(sizeof(DIJOYSTATE2), &m_JoyState);
if (hr==DIERR_INPUTLOST)
{
hr = JoyDevice->Acquire();
}
}
return true;
}
DLL_API bool DEInput::Pressed_Keyboard(int Key, bool loop)
{
bool ret=false;
if (keyboardCreated)
{
if (loop)
{
if(KEYDOWN(m_KeyBuffer, Key))
{
ret=true;
}
}
else
{
if(KEYDOWN(m_KeyBuffer, Key) && !KEYDOWN(m_KeyBufferLoop, Key))
{
ret=true;
}
}
}
if (loop==false) m_KeyBufferLoop[Key] = m_KeyBuffer[Key];
return ret;
}
DLL_API char DEInput::Pressed_KeyboardKey()
{
char key;
key = '\0';
//Lettere
if(KEYDOWN(m_KeyBuffer, DIK_A) && !KEYDOWN(m_KeyBufferPrev, DIK_A))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'A';
else
key = 'a';
}
if(KEYDOWN(m_KeyBuffer, DIK_B) && !KEYDOWN(m_KeyBufferPrev, DIK_B))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'B';
else
key = 'b';
}
if(KEYDOWN(m_KeyBuffer, DIK_C) && !KEYDOWN(m_KeyBufferPrev, DIK_C))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'C';
else
key = 'c';
}
if(KEYDOWN(m_KeyBuffer, DIK_D) && !KEYDOWN(m_KeyBufferPrev, DIK_D))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'D';
else
key = 'd';
}
if(KEYDOWN(m_KeyBuffer, DIK_E) && !KEYDOWN(m_KeyBufferPrev, DIK_E))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'E';
else
key = 'e';
}
if(KEYDOWN(m_KeyBuffer, DIK_F) && !KEYDOWN(m_KeyBufferPrev, DIK_F))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'F';
else
key = 'f';
}
if(KEYDOWN(m_KeyBuffer, DIK_G) && !KEYDOWN(m_KeyBufferPrev, DIK_G))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'G';
else
key = 'g';
}
if(KEYDOWN(m_KeyBuffer, DIK_H) && !KEYDOWN(m_KeyBufferPrev, DIK_H))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'H';
else
key = 'h';
}
if(KEYDOWN(m_KeyBuffer, DIK_I) && !KEYDOWN(m_KeyBufferPrev, DIK_I))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'I';
else
key = 'i';
}
if(KEYDOWN(m_KeyBuffer, DIK_J) && !KEYDOWN(m_KeyBufferPrev, DIK_J))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'J';
else
key = 'j';
}
if(KEYDOWN(m_KeyBuffer, DIK_K) && !KEYDOWN(m_KeyBufferPrev, DIK_K))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'K';
else
key = 'k';
}
if(KEYDOWN(m_KeyBuffer, DIK_L) && !KEYDOWN(m_KeyBufferPrev, DIK_L))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'L';
else
key = 'l';
}
if(KEYDOWN(m_KeyBuffer, DIK_M) && !KEYDOWN(m_KeyBufferPrev, DIK_M))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'M';
else
key = 'm';
}
if(KEYDOWN(m_KeyBuffer, DIK_N) && !KEYDOWN(m_KeyBufferPrev, DIK_N))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'N';
else
key = 'n';
}
if(KEYDOWN(m_KeyBuffer, DIK_O) && !KEYDOWN(m_KeyBufferPrev, DIK_O))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'O';
else
key = 'o';
}
if(KEYDOWN(m_KeyBuffer, DIK_P) && !KEYDOWN(m_KeyBufferPrev, DIK_P))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'P';
else
key = 'p';
}
if(KEYDOWN(m_KeyBuffer, DIK_Q) && !KEYDOWN(m_KeyBufferPrev, DIK_Q))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'Q';
else
key = 'q';
}
if(KEYDOWN(m_KeyBuffer, DIK_R) && !KEYDOWN(m_KeyBufferPrev, DIK_R))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'R';
else
key = 'r';
}
if(KEYDOWN(m_KeyBuffer, DIK_S) && !KEYDOWN(m_KeyBufferPrev, DIK_S))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'S';
else
key = 's';
}
if(KEYDOWN(m_KeyBuffer, DIK_T) && !KEYDOWN(m_KeyBufferPrev, DIK_T))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'T';
else
key = 't';
}
if(KEYDOWN(m_KeyBuffer, DIK_U) && !KEYDOWN(m_KeyBufferPrev, DIK_U))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'U';
else
key = 'u';
}
if(KEYDOWN(m_KeyBuffer, DIK_V) && !KEYDOWN(m_KeyBufferPrev, DIK_V))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'V';
else
key = 'v';
}
if(KEYDOWN(m_KeyBuffer, DIK_W) && !KEYDOWN(m_KeyBufferPrev, DIK_W))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'W';
else
key = 'w';
}
if(KEYDOWN(m_KeyBuffer, DIK_X) && !KEYDOWN(m_KeyBufferPrev, DIK_X))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'X';
else
key = 'x';
}
if(KEYDOWN(m_KeyBuffer, DIK_Y) && !KEYDOWN(m_KeyBufferPrev, DIK_Y))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'Y';
else
key = 'y';
}
if(KEYDOWN(m_KeyBuffer, DIK_Z) && !KEYDOWN(m_KeyBufferPrev, DIK_Z))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = 'Z';
else
key = 'z';
}
//Numeri
if((KEYDOWN(m_KeyBuffer, DIK_1) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD1)) && !KEYDOWN(m_KeyBufferPrev, DIK_1) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD1))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '!';
else
key = '1';
}
if((KEYDOWN(m_KeyBuffer, DIK_2) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD2)) && !KEYDOWN(m_KeyBufferPrev, DIK_2) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD2))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '"';
else
key = '2';
}
if((KEYDOWN(m_KeyBuffer, DIK_3) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD3)) && !KEYDOWN(m_KeyBufferPrev, DIK_3) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD3))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '£';
else
key = '3';
}
if((KEYDOWN(m_KeyBuffer, DIK_4) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD4)) && !KEYDOWN(m_KeyBufferPrev, DIK_4) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD4))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '$';
else
key = '4';
}
if((KEYDOWN(m_KeyBuffer, DIK_5) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD5)) && !KEYDOWN(m_KeyBufferPrev, DIK_5) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD5))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '%';
else
key = '5';
}
if((KEYDOWN(m_KeyBuffer, DIK_6) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD6)) && !KEYDOWN(m_KeyBufferPrev, DIK_6) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD6))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '&';
else
key = '6';
}
if((KEYDOWN(m_KeyBuffer, DIK_7) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD7)) && !KEYDOWN(m_KeyBufferPrev, DIK_7) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD7))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '/';
else
key = '7';
}
if((KEYDOWN(m_KeyBuffer, DIK_8) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD8)) && !KEYDOWN(m_KeyBufferPrev, DIK_8) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD8))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '(';
else
key = '8';
}
if((KEYDOWN(m_KeyBuffer, DIK_9) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD9)) && !KEYDOWN(m_KeyBufferPrev, DIK_9) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD9))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = ')';
else
key = '9';
}
if((KEYDOWN(m_KeyBuffer, DIK_0) || KEYDOWN(m_KeyBuffer, DIK_NUMPAD0)) && !KEYDOWN(m_KeyBufferPrev, DIK_0) && !KEYDOWN(m_KeyBufferPrev, DIK_NUMPAD0))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '=';
else
key = '0';
}
//Simboli
if(KEYDOWN(m_KeyBuffer, DIK_SLASH) && !KEYDOWN(m_KeyBufferPrev, DIK_SLASH))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = '_';
else
key = '-';
}
if(KEYDOWN(m_KeyBuffer, DIK_SPACE) && !KEYDOWN(m_KeyBufferPrev, DIK_SPACE))
{
key = ' ';
}
if(KEYDOWN(m_KeyBuffer, DIK_COMMA) && !KEYDOWN(m_KeyBufferPrev, DIK_COMMA))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = ';';
else
key = ',';
}
if(KEYDOWN(m_KeyBuffer,DIK_PERIOD) && !KEYDOWN(m_KeyBufferPrev, DIK_PERIOD))
{
if(KEYDOWN(m_KeyBuffer, DIK_LSHIFT) || KEYDOWN(m_KeyBuffer, DIK_RSHIFT))
key = ':';
else
key = '.';
}
//Imposta il vecchio valore come quello attuale
//Permette che se si tiene premuto il pulsante non riscrive la lettere
memcpy(m_KeyBufferPrev, m_KeyBuffer, 256);
return key;
}
DLL_API bool DEInput::Pressed_MouseDown(ENUM_DE_MOUSEBUTTON Button)
{
if (mouseCreated)
{
if(m_MouseState.rgbButtons[Button] & 0x80)
{
return true;
}
}
return false;
}
DLL_API bool DEInput::Pressed_MouseUp(ENUM_DE_MOUSEBUTTON Button)
{
if (mouseCreated)
{
if(m_MouseState.rgbButtons[Button] & 0x80)
{
mouseTemp[Button] = true;
return false;
}
else
{
if (mouseTemp[Button] == true)
{
mouseTemp[Button] = false;
return true;
}
else
{
return false;
}
}
}
return false;
}
DLL_API LONG DEInput::Wheel_Mouse()
{
if (mouseCreated)
{
return m_MouseState.lZ;
}
return false;
}
DLL_API bool DEInput::Pressed_Joy(ENUM_DE_JOYBUTTON Button)
{
if (joyCreated)
{
if (Button<=8)
{
if(m_JoyState.rgbButtons[Button] & 0x80)
{
return true;
}
}
else
{
if ((Button==DE_JOYBUTTON_LEFT)&&(m_JoyState.lX<=-1000)) return true;
if ((Button==DE_JOYBUTTON_RIGHT)&&(m_JoyState.lX>=1000)) return true;
if ((Button==DE_JOYBUTTON_UP)&&(m_JoyState.lY<=-1000)) return true;
if ((Button==DE_JOYBUTTON_DOWN)&&(m_JoyState.lY>=1000)) return true;
}
}
return false;
}
DLL_API bool DEInput::RunControlPanel()
{
if (isCreated)
{
HRESULT hr = DirectInputObject->RunControlPanel(NULL, 0);
if (FAILED(hr)) return false;
else return true;
}
return false;
}
DLL_API bool DEInput::RunControlPanel_Keyboard()
{
if (keyboardCreated)
{
HRESULT hr = KeyboardDevice->RunControlPanel(NULL, 0);
if (FAILED(hr)) return false;
else return true;
}
return false;
}
DLL_API bool DEInput::RunControlPanel_Mouse()
{
if (mouseCreated)
{
HRESULT hr = MouseDevice->RunControlPanel(NULL, 0);
if (FAILED(hr)) return false;
else return true;
}
return false;
}
DLL_API bool DEInput::RunControlPanel_Joy()
{
if (joyCreated)
{
HRESULT hr = JoyDevice->RunControlPanel(NULL, 0);
if (FAILED(hr)) return false;
else return true;
}
return false;
}
DLL_API LPDIDEVCAPS DEInput::GetCapabilities_Keyboard()
{
DIDEVCAPS DIDevCaps;
DIDevCaps.dwSize = sizeof(DIDEVCAPS);
if (keyboardCreated)
{
KeyboardDevice->GetCapabilities(&DIDevCaps);
}
return &DIDevCaps;
}
DLL_API LPDIDEVCAPS DEInput::GetCapabilities_Mouse()
{
DIDEVCAPS DIDevCaps;
DIDevCaps.dwSize = sizeof(DIDEVCAPS);
if (mouseCreated)
{
MouseDevice->GetCapabilities(&DIDevCaps);
}
return &DIDevCaps;
}
DLL_API LPDIDEVCAPS DEInput::GetCapabilities_Joy()
{
DIDEVCAPS DIDevCaps;
DIDevCaps.dwSize = sizeof(DIDEVCAPS);
if (joyCreated)
{
JoyDevice->GetCapabilities(&DIDevCaps);
}
return &DIDevCaps;
}
DLL_API LPDIDEVICEINSTANCE DEInput::GetDeviceInfo_Keyboard()
{
DIDEVICEINSTANCE pdidi;
pdidi.dwSize = sizeof(DIDEVICEINSTANCE);
if (keyboardCreated)
{
KeyboardDevice->GetDeviceInfo(&pdidi);
}
return &pdidi;
}
DLL_API LPDIDEVICEINSTANCE DEInput::GetDeviceInfo_Mouse()
{
DIDEVICEINSTANCE pdidi;
pdidi.dwSize = sizeof(DIDEVICEINSTANCE);
if (mouseCreated)
{
MouseDevice->GetDeviceInfo(&pdidi);
}
return &pdidi;
}
DLL_API LPDIDEVICEINSTANCE DEInput::GetDeviceInfo_Joy()
{
DIDEVICEINSTANCE pdidi;
pdidi.dwSize = sizeof(DIDEVICEINSTANCE);
if (joyCreated)
{
JoyDevice->GetDeviceInfo(&pdidi);
}
return &pdidi;
}
DLL_API DIMOUSESTATE2 DEInput::GetState_Mouse()
{
return m_MouseState;
}
DLL_API DIJOYSTATE2 DEInput::GetState_Joy()
{
return m_JoyState;
}
DLL_API void DEInput::SetCursorAttributes(bool bInvert,float fNewSensitivity)
{
m_bInverted = bInvert;
m_fSensitivity = fNewSensitivity;
}
DLL_API void DEInput::SetCursorPosition(float fNewX,float fNewY)
{
m_fCursorX = fNewX;
m_fCursorY = fNewY;
}
DLL_API void DEInput::SetCursorClip(HWND clipHWND)
{
RECT rcClip;
GetWindowRect(clipHWND, &rcClip);
ClipCursor(&rcClip);
}
DLL_API void DEInput::ShowWindowCursor(bool showCursor)
{
ShowCursor(showCursor);
}
DLL_API D3DXVECTOR2 DEInput::GetCursorPosition()
{
D3DXVECTOR2 ptCursor;
POINT winCursor;
GetCursorPos(&winCursor);
if (mainWindowed)
{
ScreenToClient(mainHWND, &winCursor);
ptCursor.x = (float)winCursor.x;
ptCursor.y = (float)winCursor.y;
}
else
{
ptCursor.x = (float)winCursor.x;
ptCursor.y = (float)winCursor.y;
}
return ptCursor;
}
DLL_API float DEInput::GetRelativeX_Mouse(void)
{
return (float)m_MouseState.lX * m_fSensitivity;
}
DLL_API float DEInput::GetRelativeY_Mouse(void)
{
return (float)m_MouseState.lY * m_fSensitivity;
}
DLL_API float DEInput::GetRelativeZ_Mouse(void)
{
return (float)m_MouseState.lZ * m_fSensitivity;
}
DLL_API float DEInput::GetAbsoluteX_Mouse(void)
{
return m_fCursorX;
}
DLL_API float DEInput::GetAbsoluteY_Mouse(void)
{
return m_fCursorY;
}
DLL_API bool DEInput::GetCreated()
{
return isCreated;
}
DLL_API bool DEInput::isCreated_Keyboard()
{
return keyboardCreated;
}
DLL_API bool DEInput::isCreated_Mouse()
{
return mouseCreated;
}
DLL_API bool DEInput::isCreated_Joy()
{
return joyCreated;
}
DLL_API HWND DEInput::GetHWND()
{
return mainHWND;
}
DLL_API void DEInput::SetHWND(HWND cursorHWND)
{
mainHWND = cursorHWND;
}
DLL_API bool DEInput::GetWindowed()
{
return mainWindowed;
}
DLL_API void DEInput::SetWindowed(bool inWindow)
{
mainWindowed = inWindow;
if (inWindow==false)
{
//Clippa e nasconde il cursore
SetCursorClip(mainHWND);
ShowWindowCursor(false);
}
else
{
//Non clippare e mostra il cursore
SetCursorClip(NULL);
ShowWindowCursor(true);
}
}
| [
"54738360+desdinovait@users.noreply.github.com"
] | 54738360+desdinovait@users.noreply.github.com |
441c77a1edec9c3275126ff93be2fcf4fb945ff4 | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtbase/tests/auto/corelib/tools/qstringiterator/tst_qstringiterator.cpp | f05caf0033f120974bc9feecd8df137df7bd8b2d | [
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-commercial-license",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"LicenseRef-scancode-qt-commercial-1.1",
"LGPL-3.0-only",
"LicenseRef-scancode-qt-company-exception-lgpl-2.1",
... | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 23,638 | cpp | /****************************************************************************
**
** Copyright (C) 2014 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtCore/QString>
#include <private/qstringiterator_p.h>
class tst_QStringIterator : public QObject
{
Q_OBJECT
private slots:
void sweep_data();
void sweep();
void position();
};
void tst_QStringIterator::sweep_data()
{
QTest::addColumn<QString>("string");
QTest::addColumn<bool>("valid");
QTest::addColumn<int>("count");
QTest::newRow("sweep_00") << QString::fromUtf8("", 0) << true << 0;
QTest::newRow("sweep_01") << QString::fromUtf8("a", 1) << true << 1;
QTest::newRow("sweep_02") << QString::fromUtf8("a string", 8) << true << 8;
QTest::newRow("sweep_03") << QString::fromUtf8("\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9", 10) << true << 5;
QTest::newRow("sweep_04") << QString::fromUtf8("\xc3\x9f\xe2\x80\x94\xc2\xa1", 7) << true << 3;
QTest::newRow("sweep_05") << QString::fromUtf8("\xe6\xb0\xb4\xe6\xb0\xb5\xe6\xb0\xb6\xe6\xb0\xb7\xe6\xb0\xb8\xe6\xb0\xb9", 18) << true << 6;
QTest::newRow("sweep_06") << QString::fromUtf8("\xf0\x9f\x98\x81\xf0\x9f\x98\x82\x61\x62\x63\xf0\x9f\x98\x83\xc4\x91\xc3\xa8\xef\xac\x80\xf0\x9f\x98\x84\xf0\x9f\x98\x85", 30) << true << 11;
QTest::newRow("sweep_07") << QString::fromUtf8("\xf0\x9f\x82\xaa\xf0\x9f\x82\xab\xf0\x9f\x82\xad\xf0\x9f\x82\xae\xf0\x9f\x82\xa1\x20\x52\x4f\x59\x41\x4c\x20\x46\x4c\x55\x53\x48\x20\x4f\x46\x20\x53\x50\x41\x44\x45\x53", 42) << true << 27;
QTest::newRow("sweep_08") << QString::fromUtf8("abc\0def", 7) << true << 7;
QTest::newRow("sweep_09") << QString::fromUtf8("\xc3\xa0\xce\xb2\xc3\xa7\xf0\x9f\x80\xb9\xf0\x9f\x80\xb8\x00\xf0\x9f\x80\xb1\x00\xf0\x9f\x80\xb3\xf0\x9f\x81\x85\xe1\xb8\x8a\xc4\x99\xc6\x92", 35) << true << 13;
QTest::newRow("sweep_invalid_00") << QString(QChar(0xd800)) << false << 1;
QTest::newRow("sweep_invalid_01") << QString(QChar(0xdc00)) << false << 1;
QTest::newRow("sweep_invalid_02") << QString(QChar(0xdbff)) << false << 1;
QTest::newRow("sweep_invalid_03") << QString(QChar(0xdfff)) << false << 1;
#define QSTRING_FROM_QCHARARRAY(x) (QString((x), sizeof(x)/sizeof((x)[0])))
static const QChar invalid_04[] = {
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d'), QChar(0xd800)
};
QTest::newRow("sweep_invalid_04") << QSTRING_FROM_QCHARARRAY(invalid_04) << false << 8;
static const QChar invalid_05[] = {
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d'), QChar(0xd800), QLatin1Char('x')
};
QTest::newRow("sweep_invalid_05") << QSTRING_FROM_QCHARARRAY(invalid_05) << false << 9;
static const QChar invalid_06[] = {
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d'), QChar(0xdc00)
};
QTest::newRow("sweep_invalid_06") << QSTRING_FROM_QCHARARRAY(invalid_06) << false << 8;
static const QChar invalid_07[] = {
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d'), QChar(0xdc00), QLatin1Char('x')
};
QTest::newRow("sweep_invalid_07") << QSTRING_FROM_QCHARARRAY(invalid_07) << false << 9;
static const QChar invalid_08[] = {
QChar(0xd800),
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d')
};
QTest::newRow("sweep_invalid_08") << QSTRING_FROM_QCHARARRAY(invalid_08) << false << 8;
static const QChar invalid_09[] = {
QChar(0xdc00),
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d')
};
QTest::newRow("sweep_invalid_09") << QSTRING_FROM_QCHARARRAY(invalid_09) << false << 8;
static const QChar invalid_10[] = {
QChar(0xd800), QChar(0xd800),
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d')
};
QTest::newRow("sweep_invalid_10") << QSTRING_FROM_QCHARARRAY(invalid_10) << false << 9;
static const QChar invalid_11[] = {
QChar(0xdc00), QChar(0xd800),
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d')
};
QTest::newRow("sweep_invalid_11") << QSTRING_FROM_QCHARARRAY(invalid_11) << false << 9;
static const QChar invalid_12[] = {
QChar(0xdc00), QChar(0xdc00),
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d')
};
QTest::newRow("sweep_invalid_12") << QSTRING_FROM_QCHARARRAY(invalid_12) << false << 9;
static const QChar invalid_13[] = {
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QChar(0xd800), QChar(0xdf00), // U+10300 OLD ITALIC LETTER A
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d'), QChar(0xd800)
};
QTest::newRow("sweep_invalid_13") << QSTRING_FROM_QCHARARRAY(invalid_13) << false << 9;
static const QChar invalid_14[] = {
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QChar(0xd800), QChar(0xdf00), // U+10300 OLD ITALIC LETTER A
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d'), QChar(0xd800), QLatin1Char('x')
};
QTest::newRow("sweep_invalid_14") << QSTRING_FROM_QCHARARRAY(invalid_14) << false << 10;
static const QChar invalid_15[] = {
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QChar(0xd800), QChar(0xdf00), // U+10300 OLD ITALIC LETTER A
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d'), QChar(0xdc00)
};
QTest::newRow("sweep_invalid_15") << QSTRING_FROM_QCHARARRAY(invalid_15) << false << 9;
static const QChar invalid_16[] = {
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QChar(0xd800), QChar(0xdf00), // U+10300 OLD ITALIC LETTER A
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d'), QChar(0xdc00), QLatin1Char('x')
};
QTest::newRow("sweep_invalid_16") << QSTRING_FROM_QCHARARRAY(invalid_16) << false << 10;
static const QChar invalid_17[] = {
QChar(0xd800),
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QChar(0xd800), QChar(0xdf00), // U+10300 OLD ITALIC LETTER A
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d')
};
QTest::newRow("sweep_invalid_17") << QSTRING_FROM_QCHARARRAY(invalid_17) << false << 9;
static const QChar invalid_18[] = {
QChar(0xdc00),
QLatin1Char('i'), QLatin1Char('n'), QLatin1Char('v'),
QChar(0xd800), QChar(0xdf00), // U+10300 OLD ITALIC LETTER A
QLatin1Char('a'), QLatin1Char('l'), QLatin1Char('i'),
QLatin1Char('d')
};
QTest::newRow("sweep_invalid_18") << QSTRING_FROM_QCHARARRAY(invalid_18) << false << 9;
#undef QSTRING_FROM_QCHARARRAY
}
void tst_QStringIterator::sweep()
{
QFETCH(QString, string);
QFETCH(bool, valid);
QStringIterator i(string);
int count = 0;
QString rebuiltString;
while (i.hasNext()) {
const uint peekedCodePoint = i.peekNext(~0u);
const uint codePoint = i.next(~0u);
QVERIFY(peekedCodePoint == codePoint);
if (codePoint == ~0u)
rebuiltString += *(i.position() - 1);
else
rebuiltString += QString::fromUcs4(&codePoint, 1);
++count;
}
QTEST(count, "count");
QTEST(rebuiltString, "string");
rebuiltString.clear();
while (i.hasPrevious()) {
const uint peekedCodePoint = i.peekPrevious(~0u);
const uint codePoint = i.previous(~0u);
QVERIFY(peekedCodePoint == codePoint);
--count;
}
QCOMPARE(count, 0);
while (i.hasNext()) {
i.advance();
++count;
}
QTEST(count, "count");
while (i.hasPrevious()) {
i.recede();
--count;
}
QCOMPARE(count, 0);
if (valid) {
while (i.hasNext()) {
const uint peekedCodePoint = i.peekNextUnchecked();
const uint codePoint = i.nextUnchecked();
QVERIFY(peekedCodePoint == codePoint);
QVERIFY(codePoint <= 0x10FFFFu);
rebuiltString += QString::fromUcs4(&codePoint, 1);
++count;
}
QTEST(count, "count");
QTEST(rebuiltString, "string");
while (i.hasPrevious()) {
const uint peekedCodePoint = i.peekPreviousUnchecked();
const uint codePoint = i.previousUnchecked();
QVERIFY(peekedCodePoint == codePoint);
--count;
}
QCOMPARE(count, 0);
while (i.hasNext()) {
i.advanceUnchecked();
++count;
}
QTEST(count, "count");
while (i.hasPrevious()) {
i.recedeUnchecked();
--count;
}
QCOMPARE(count, 0);
}
}
void tst_QStringIterator::position()
{
static const QChar stringData[] =
{
// codeunit count: 0
QLatin1Char('a'), QLatin1Char('b'), QLatin1Char('c'),
// codeunit count: 3
QChar(0x00A9), // U+00A9 COPYRIGHT SIGN
// codeunit count: 4
QChar(0x00AE), // U+00AE REGISTERED SIGN
// codeunit count: 5
QLatin1Char('d'), QLatin1Char('e'), QLatin1Char('f'),
// codeunit count: 8
QLatin1Char('\0'),
// codeunit count: 9
QLatin1Char('g'), QLatin1Char('h'), QLatin1Char('i'),
// codeunit count: 12
QChar(0xD834), QChar(0xDD1E), // U+1D11E MUSICAL SYMBOL G CLEF
// codeunit count: 14
QChar(0xD834), QChar(0xDD21), // U+1D121 MUSICAL SYMBOL C CLEF
// codeunit count: 16
QLatin1Char('j'),
// codeunit count: 17
QChar(0xD800), // stray high surrogate
// codeunit count: 18
QLatin1Char('k'),
// codeunit count: 19
QChar(0xDC00), // stray low surrogate
// codeunit count: 20
QLatin1Char('l'),
// codeunit count: 21
QChar(0xD800), QChar(0xD800), // two high surrogates
// codeunit count: 23
QLatin1Char('m'),
// codeunit count: 24
QChar(0xDC00), QChar(0xDC00), // two low surrogates
// codeunit count: 26
QLatin1Char('n'),
// codeunit count: 27
QChar(0xD800), QChar(0xD800), QChar(0xDC00), // stray high surrogate followed by valid pair
// codeunit count: 30
QLatin1Char('o'),
// codeunit count: 31
QChar(0xDC00), QChar(0xD800), QChar(0xDC00), // stray low surrogate followed by valid pair
// codeunit count: 34
QLatin1Char('p')
// codeunit count: 35
};
const QString string(stringData, sizeof(stringData) / sizeof(stringData[0]));
QStringIterator i(string);
QCOMPARE(i.position(), string.constBegin());
QVERIFY(i.hasNext());
QVERIFY(!i.hasPrevious());
i.setPosition(string.constEnd());
QCOMPARE(i.position(), string.constEnd());
QVERIFY(!i.hasNext());
QVERIFY(i.hasPrevious());
#define QCHAR_UNICODE_VALUE(x) ((uint)(QChar(x).unicode()))
const QString::const_iterator begin = string.constBegin();
i.setPosition(begin);
QCOMPARE(i.position(), begin);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('a')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('a')));
QCOMPARE(i.position(), begin + 1);
i.setPosition(begin + 2);
QCOMPARE(i.position(), begin + 2);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('c')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('c')));
QCOMPARE(i.position(), begin + 3);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(0x00A9));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(0x00A9));
QCOMPARE(i.position(), begin + 4);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(0x00AE));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(0x00AE));
QCOMPARE(i.position(), begin + 5);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(0x00AE));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(0x00AE));
QCOMPARE(i.position(), begin + 4);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(0x00A9));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(0x00A9));
QCOMPARE(i.position(), begin + 3);
i.setPosition(begin + 8);
QCOMPARE(i.position(), begin + 8);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('\0')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('\0')));
QCOMPARE(i.position(), begin + 9);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('g')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('g')));
QCOMPARE(i.position(), begin + 10);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('g')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('g')));
QCOMPARE(i.position(), begin + 9);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('\0')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('\0')));
QCOMPARE(i.position(), begin + 8);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('f')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('f')));
QCOMPARE(i.position(), begin + 7);
i.advanceUnchecked();
i.advanceUnchecked();
i.advanceUnchecked();
i.advanceUnchecked();
i.advanceUnchecked();
QCOMPARE(i.position(), begin + 12);
QCOMPARE(i.peekNext(), 0x1D11Eu);
QCOMPARE(i.next(), 0x1D11Eu);
QCOMPARE(i.position(), begin + 14);
QCOMPARE(i.peekNext(), 0x1D121u);
QCOMPARE(i.next(), 0x1D121u);
QCOMPARE(i.position(), begin + 16);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('j')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('j')));
QCOMPARE(i.position(), begin + 17);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('j')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('j')));
QCOMPARE(i.position(), begin + 16);
QCOMPARE(i.peekPrevious(), 0x1D121u);
QCOMPARE(i.previous(), 0x1D121u);
QCOMPARE(i.position(), begin + 14);
QCOMPARE(i.peekPrevious(), 0x1D11Eu);
QCOMPARE(i.previous(), 0x1D11Eu);
QCOMPARE(i.position(), begin + 12);
i.setPosition(begin + 13);
QCOMPARE(i.position(), begin + 13);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 14);
QCOMPARE(i.peekNext(), 0x1D121u);
QCOMPARE(i.next(), 0x1D121u);
QCOMPARE(i.position(), begin + 16);
i.setPosition(begin + 15);
QCOMPARE(i.position(), begin + 15);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 14);
QCOMPARE(i.peekPrevious(), 0x1D11Eu);
QCOMPARE(i.previous(), 0x1D11Eu);
QCOMPARE(i.position(), begin + 12);
i.advanceUnchecked();
i.advanceUnchecked();
QCOMPARE(i.position(), begin + 16);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('j')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('j')));
QCOMPARE(i.position(), begin + 17);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 18);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('k')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('k')));
QCOMPARE(i.position(), begin + 19);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 20);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('l')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('l')));
QCOMPARE(i.position(), begin + 21);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 22);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 23);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('m')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('m')));
QCOMPARE(i.position(), begin + 24);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 25);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 26);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('n')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('n')));
QCOMPARE(i.position(), begin + 27);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 28);
QCOMPARE(i.peekNext(), 0x10000u);
QCOMPARE(i.next(), 0x10000u);
QCOMPARE(i.position(), begin + 30);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('o')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('o')));
QCOMPARE(i.position(), begin + 31);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 32);
QCOMPARE(i.peekNext(), 0x10000u);
QCOMPARE(i.next(), 0x10000u);
QCOMPARE(i.position(), begin + 34);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('p')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('p')));
QVERIFY(!i.hasNext());
QCOMPARE(i.position(), begin + 35);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('p')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('p')));
QCOMPARE(i.position(), begin + 34);
QCOMPARE(i.peekPrevious(), 0x10000u);
QCOMPARE(i.previous(), 0x10000u);
QCOMPARE(i.position(), begin + 32);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 31);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('o')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('o')));
QCOMPARE(i.position(), begin + 30);
QCOMPARE(i.peekPrevious(), 0x10000u);
QCOMPARE(i.previous(), 0x10000u);
QCOMPARE(i.position(), begin + 28);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 27);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('n')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('n')));
QCOMPARE(i.position(), begin + 26);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 25);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 24);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('m')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('m')));
QCOMPARE(i.position(), begin + 23);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 22);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 21);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('l')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('l')));
QCOMPARE(i.position(), begin + 20);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 19);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('k')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('k')));
QCOMPARE(i.position(), begin + 18);
QCOMPARE(i.peekPrevious(), 0xFFFDu);
QCOMPARE(i.previous(), 0xFFFDu);
QCOMPARE(i.position(), begin + 17);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('j')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('j')));
i.setPosition(begin + 29);
QCOMPARE(i.position(), begin + 29);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 30);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('o')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('o')));
QCOMPARE(i.position(), begin + 31);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('o')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('o')));
QCOMPARE(i.position(), begin + 30);
QCOMPARE(i.peekPrevious(), 0x10000u);
QCOMPARE(i.previous(), 0x10000u);
QCOMPARE(i.position(), begin + 28);
i.setPosition(begin + 33);
QCOMPARE(i.position(), begin + 33);
QCOMPARE(i.peekNext(), 0xFFFDu);
QCOMPARE(i.next(), 0xFFFDu);
QCOMPARE(i.position(), begin + 34);
QCOMPARE(i.peekNext(), QCHAR_UNICODE_VALUE(QLatin1Char('p')));
QCOMPARE(i.next(), QCHAR_UNICODE_VALUE(QLatin1Char('p')));
QCOMPARE(i.position(), begin + 35);
QCOMPARE(i.peekPrevious(), QCHAR_UNICODE_VALUE(QLatin1Char('p')));
QCOMPARE(i.previous(), QCHAR_UNICODE_VALUE(QLatin1Char('p')));
QCOMPARE(i.position(), begin + 34);
QCOMPARE(i.peekPrevious(), 0x10000u);
QCOMPARE(i.previous(), 0x10000u);
QCOMPARE(i.position(), begin + 32);
i.setPosition(begin + 16);
QCOMPARE(i.position(), begin + 16);
i.recedeUnchecked();
i.recedeUnchecked();
QCOMPARE(i.position(), begin + 12);
i.recedeUnchecked();
i.recedeUnchecked();
i.recedeUnchecked();
i.recedeUnchecked();
QCOMPARE(i.position(), begin + 8);
i.recedeUnchecked();
i.recedeUnchecked();
i.recedeUnchecked();
i.recedeUnchecked();
i.recedeUnchecked();
i.recedeUnchecked();
QCOMPARE(i.position(), begin + 2);
#undef QCHAR_UNICODE_VALUE
}
QTEST_APPLESS_MAIN(tst_QStringIterator)
#include "tst_qstringiterator.moc"
| [
"p_pavlov@wargaming.net"
] | p_pavlov@wargaming.net |
25448dfe880ba5c65c15202e7c4323abfe58dd01 | 7ababa53f162fa7bc9c591bf9b9d42abfbd7f1f7 | /flight_source/UCSB/Test_CCITT0/Test_CCITT0.cpp | 7215f0ebc163553132fe9f39ee9e61fda1f0c4cd | [] | no_license | woody62/cofe-fts-flight-code-archive | 938f045f17770e3959e77c944cf064e2de1b154f | 5a97da37608df75d5e308f94bee64f7c3c8d09e7 | refs/heads/master | 2021-01-12T10:08:47.669158 | 2013-08-21T21:47:39 | 2013-08-21T21:47:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 605 | cpp | // Test_CCITT0.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "lib_crc.h"
unsigned char buffer[] =
{
0x6E,
0x00,
0x00,
0x0C,
0x00,
0x00,
0xAA,
0xDA,
0x00,
0x00,
};
unsigned short UpdateCRC(unsigned short crcIn, unsigned char const* pBuffer, unsigned int len)
{
unsigned short crcOut = crcIn;
for(unsigned int i=0; i < len; ++i, ++pBuffer)
{
crcOut = update_crc_ccitt(crcOut, *pBuffer);
}
return crcOut;
}
int _tmain(int argc, _TCHAR* argv[])
{
unsigned short crc = UpdateCRC(0, buffer, 6);
return 0;
}
| [
"peterm@deepspace.ucsb.edu"
] | peterm@deepspace.ucsb.edu |
3c938305e59d2f318b688b5058db345290c39fae | 4913acda8fa6a4f5fe8c2b51e2383cff7a986d84 | /PolynomialTest/test_polynom.cpp | b296c3487b796f44d93e5ab9a727ca432fc249ca | [] | no_license | 3817061ShashkinEV/Shashkin_All_Labs | 6a7bf683e95bed5b5c8eb446e9cbf197140e6f1a | 59a6c184f726be93e2a04d46af76a27e1e64e9eb | refs/heads/master | 2020-03-30T12:41:32.559626 | 2019-06-11T19:34:23 | 2019-06-11T19:34:23 | 151,235,253 | 0 | 0 | null | 2019-06-11T19:34:24 | 2018-10-02T10:07:56 | C++ | UTF-8 | C++ | false | false | 10,966 | cpp | #include "gtest.h"
#include "Polynom.h"
TEST(Monom, can_create_monom)
{
int degrees[] = { 1,2,3,4,5 };
ASSERT_NO_THROW(TMonom monom(5, degrees, 1));
}
// ---------------------------------------------------------------------------
TEST(Monom, throw_when_create_monom_with_negative_size)
{
int degrees[] = { 1,2,3,4,5 };
ASSERT_ANY_THROW(TMonom monom(-5, degrees, 1));
}
// ---------------------------------------------------------------------------
TEST(Monom, throw_when_create_monom_with_negative_degrees)
{
int degrees[] = { 1,2,-3,-4,5 };
ASSERT_ANY_THROW(TMonom monom(5, degrees, 1));
}
// ---------------------------------------------------------------------------
TEST(Monom, can_create_copied_monom)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom1(5, degrees, 1);
ASSERT_NO_THROW(TMonom monom2(monom1));
}
// ---------------------------------------------------------------------------
TEST(Monom, can_set_next)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(5, degrees2, 1);
ASSERT_NO_THROW(monom1.SetNext(&monom2));
}
// ---------------------------------------------------------------------------
TEST(Monom, can_get_next)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(5, degrees2, 1);
monom1.SetNext(&monom2);
EXPECT_EQ(&monom2, monom1.GetNext());
}
// ---------------------------------------------------------------------------
TEST(Monom, can_set_degree)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom(5, degrees1, 1);
ASSERT_NO_THROW(monom.SetDegree(degrees2));
}
// ---------------------------------------------------------------------------
TEST(Monom, can_get_degree)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom(5, degrees1, 1);
monom.SetDegree(degrees2);
EXPECT_EQ(degrees2[0], monom.GetDegree()[0]);
EXPECT_EQ(degrees2[1], monom.GetDegree()[1]);
EXPECT_EQ(degrees2[2], monom.GetDegree()[2]);
EXPECT_EQ(degrees2[3], monom.GetDegree()[3]);
EXPECT_EQ(degrees2[4], monom.GetDegree()[4]);
}
// ---------------------------------------------------------------------------
TEST(Monom, can_set_count)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom(5, degrees, 1);
ASSERT_NO_THROW(monom.SetCount(4));
}
// ---------------------------------------------------------------------------
TEST(Monom, can_get_count)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom(5, degrees, 1);
monom.SetCount(4);
EXPECT_EQ(4, monom.GetCount());
}
// ---------------------------------------------------------------------------
TEST(Monom, assign_operator_works_correctly)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(5, degrees2, 2);
ASSERT_NO_THROW(monom1=monom2);
EXPECT_EQ(degrees2[0], monom1.GetDegree()[0]);
EXPECT_EQ(degrees2[1], monom1.GetDegree()[1]);
EXPECT_EQ(degrees2[2], monom1.GetDegree()[2]);
EXPECT_EQ(degrees2[3], monom1.GetDegree()[3]);
EXPECT_EQ(degrees2[4], monom1.GetDegree()[4]);
EXPECT_EQ(2, monom1.GetCoefficient());
}
// ---------------------------------------------------------------------------
TEST(Monom, throw_when_assign_monoms_with_different_sizes)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 6,5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(6, degrees2, 2);
ASSERT_ANY_THROW(monom1 = monom2);
}
// ---------------------------------------------------------------------------
TEST(Monom, can_add_monoms)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom1(5, degrees, 1);
TMonom monom2(5, degrees, 2);
TMonom monom3(5, degrees, 1);
ASSERT_NO_THROW(monom1 + monom2);
monom3 = monom1 + monom2;
EXPECT_EQ(3, monom3.GetCoefficient());
}
// ---------------------------------------------------------------------------
TEST(Monom, throw_when_add_different_monoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(5, degrees2, 2);
ASSERT_ANY_THROW(monom1 + monom2);
}
// ---------------------------------------------------------------------------
TEST(Monom, can_subtract_monoms)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom1(5, degrees, 3.4);
TMonom monom2(5, degrees, 2.0);
TMonom monom3(5, degrees, 1);
ASSERT_NO_THROW(monom1 - monom2);
monom3 = monom1 - monom2;
EXPECT_EQ(1.4, monom3.GetCoefficient());
}
// ---------------------------------------------------------------------------
TEST(Monom, throw_when_subtract_different_monoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(5, degrees2, 2);
ASSERT_ANY_THROW(monom2 - monom1);
}
// ---------------------------------------------------------------------------
TEST(Monom, can_multiply_monoms)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom1(5, degrees, 3.4);
TMonom monom2(5, degrees, 2.0);
TMonom monom3(5, degrees, 1);
ASSERT_NO_THROW(monom1 * monom2);
monom3 = monom1 * monom2;
EXPECT_EQ(6.8, monom3.GetCoefficient());
}
// ---------------------------------------------------------------------------
TEST(Monom, throw_when_multiply_different_monoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 6,5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(6, degrees2, 1);
ASSERT_ANY_THROW(monom1 * monom2);
}
// ---------------------------------------------------------------------------
TEST(Monom, can_equal_monoms_correctly)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom1(5, degrees, 2.0);
TMonom monom2(5, degrees, 2.0);
ASSERT_TRUE(monom1 == monom2);
}
// ---------------------------------------------------------------------------
TEST(Monom, thorw_when_euqal_monoms_with_different_sizes)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 6,5,4,3,2,1 };
TMonom monom1(5, degrees1, 2.0);
TMonom monom2(6, degrees2, 2.0);
ASSERT_ANY_THROW(monom1 == monom2);
}
// ---------------------------------------------------------------------------
TEST(Monom, can_compare_monoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 3.1);
TMonom monom2(5, degrees2, 2.2);
ASSERT_TRUE(monom2 > monom1);
}
// ---------------------------------------------------------------------------
TEST(Polynom, can_create_polynom)
{
ASSERT_NO_THROW(TPolynom polynom(5));
}
// ---------------------------------------------------------------------------
TEST(Polynom, throw_when_create_polynom_with_negative_size)
{
ASSERT_ANY_THROW(TPolynom polynom(-5));
}
// ---------------------------------------------------------------------------
TEST(Polynom, can_create_copied_polynom)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom(5,degrees,1);
TPolynom polynom1(5);
polynom1 += monom;
ASSERT_NO_THROW(TPolynom polynom2(polynom1));
}
// ---------------------------------------------------------------------------
TEST(Polynom, can_get_size)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom(5, degrees, 1);
TPolynom polynom(5);
polynom += monom;
EXPECT_EQ(1,polynom.GetSize());
}
// ---------------------------------------------------------------------------
TEST(Polynom, can_add_polynoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(5, degrees2, 2);
TPolynom polynom1(5);
TPolynom polynom2(5);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_NO_THROW(polynom1+polynom2);
}
// ---------------------------------------------------------------------------
TEST(Polynom, throw_when_add_different_polynoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 6,5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(6, degrees2, 2);
TPolynom polynom1(5);
TPolynom polynom2(6);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_ANY_THROW(polynom1 + polynom2);
}
// ---------------------------------------------------------------------------
TEST(Polynom, can_subtract_polynoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(5, degrees2, 2);
TPolynom polynom1(5);
TPolynom polynom2(5);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_NO_THROW(polynom1 - polynom2);
}
// ---------------------------------------------------------------------------
TEST(Polynom, throw_when_subtract_different_polynoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 6,5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(6, degrees2, 2);
TPolynom polynom1(5);
TPolynom polynom2(6);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_ANY_THROW(polynom2 - polynom1);
}
// ---------------------------------------------------------------------------
TEST(Polynom, can_muliply_polynoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(5, degrees2, 2);
TPolynom polynom1(5);
TPolynom polynom2(5);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_NO_THROW(polynom1 * polynom2);
}
// ---------------------------------------------------------------------------
TEST(Polynom, throw_when_multiply_different_polynoms)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 6,5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(6, degrees2, 2);
TPolynom polynom1(5);
TPolynom polynom2(6);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_ANY_THROW(polynom2 * polynom1);
}
// ---------------------------------------------------------------------------
TEST(Polynom, assign_operator_works_correctly)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom1(5, degrees, 1);
TMonom monom2(5, degrees, 4);
TPolynom polynom1(5);
TPolynom polynom2(5);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_NO_THROW(polynom1 = polynom2);
TMonom* tmp = polynom1.GetStart();
ASSERT_TRUE(*tmp == monom1);
ASSERT_EQ(4, tmp->GetCoefficient());
}
// ---------------------------------------------------------------------------
TEST(Polynom, throw_when_assign_polynoms_with_different_sizes)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 6,5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(6, degrees2, 4);
TPolynom polynom1(5);
TPolynom polynom2(6);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_ANY_THROW(polynom1 = polynom2);
}
// ---------------------------------------------------------------------------
TEST(Polynom, can_equeal_polynoms)
{
int degrees[] = { 1,2,3,4,5 };
TMonom monom(5, degrees, 1);
TPolynom polynom1(5);
TPolynom polynom2(5);
polynom1 += monom;
polynom2 += monom;
ASSERT_TRUE(polynom1 == polynom2);
}
// ---------------------------------------------------------------------------
TEST(Polynom, throw_when_equal_polynoms_with_different_sizes)
{
int degrees1[] = { 1,2,3,4,5 };
int degrees2[] = { 6,5,4,3,2,1 };
TMonom monom1(5, degrees1, 1);
TMonom monom2(6, degrees2, 4);
TPolynom polynom1(5);
TPolynom polynom2(6);
polynom1 += monom1;
polynom2 += monom2;
ASSERT_ANY_THROW(polynom1 == polynom2);
}
| [
"evg.shashkin@yandex.ru"
] | evg.shashkin@yandex.ru |
d916289202a68bab6fde9291b1e290a315455a48 | bb2367e5b85789e63b7dd7654b838c6914e760ad | /Leetcode1-20/Prob2/Solution1.cpp | fae8c703661b4a182b20cd64c33b4cc00780d198 | [] | no_license | liuxin00738/Leetcode | 35a16af7e08de38248270a5cda9c97fa966d5bc3 | 8cad331d9a10ebc597888bf9f9fc0dfc4b5c5b6a | refs/heads/master | 2021-01-13T14:29:28.985732 | 2019-04-19T04:03:33 | 2019-04-19T04:03:33 | 72,872,046 | 0 | 0 | null | 2019-04-19T04:03:34 | 2016-11-04T17:51:46 | C++ | UTF-8 | C++ | false | false | 1,001 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1==nullptr) return l2;
if(l2==nullptr) return l1;
ListNode* result (new ListNode(0));
ListNode* Root=result;
int overflow=0;
while(l1 != nullptr || l2 != nullptr){
int Sum=0;
Sum+=overflow;
if(l1 != nullptr) Sum+=l1->val;
if(l2 != nullptr) Sum+=l2->val;
overflow= (Sum>9)? 1 : 0;
Sum= (Sum>9)? (Sum-10) : Sum;
ListNode* tempPtr =new ListNode(Sum);
result->next=tempPtr;
result=result->next;
if(l1 != nullptr) l1=l1->next;
if(l2 != nullptr) l2=l2->next;
}
/// deal with case when need to have one more bit
if(overflow==1){
ListNode* tempPtr =new ListNode(overflow);
result->next=tempPtr;
}
return Root->next;
}
};
| [
"liuxin00738@gmail.com"
] | liuxin00738@gmail.com |
8be3a659cacf49de1053e962d1577c54a51589e7 | c1b03b59b3974058e3dc4e3aa7a46a7ab9cc3b29 | /src/module-wx.new/generated/Class_wx_HelpController.h | 77eedbaccc6474bbf914a6867f3f34f5dbae5b08 | [] | no_license | gura-lang/gura | 972725895c93c22e0ec87c17166df4d15bdbe338 | 03aff5e2b7fe4f761a16400ae7cc6fa7fec73a47 | refs/heads/master | 2021-01-25T08:04:38.269289 | 2020-05-09T12:42:23 | 2020-05-09T12:42:23 | 7,141,465 | 25 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,824 | h | //----------------------------------------------------------------------------
// wxHelpController
//----------------------------------------------------------------------------
#ifndef __CLASS_WX_HELPCONTROLLER_H__
#define __CLASS_WX_HELPCONTROLLER_H__
#include <wx/help.h>
Gura_BeginModuleScope(wx)
//----------------------------------------------------------------------------
// Class declaration for wxHelpController
//----------------------------------------------------------------------------
Gura_DeclareUserClass(wx_HelpController);
//----------------------------------------------------------------------------
// Object declaration for wxHelpController
//----------------------------------------------------------------------------
class Object_wx_HelpController : public Object_wx_HelpControllerBase {
public:
Gura_DeclareObjectAccessor(wx_HelpController)
public:
inline Object_wx_HelpController(wxHelpController *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) :
Object_wx_HelpControllerBase(Gura_UserClass(wx_HelpController), pEntity, pObserver, ownerFlag) {}
inline Object_wx_HelpController(Class *pClass, wxHelpController *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) :
Object_wx_HelpControllerBase(pClass, pEntity, pObserver, ownerFlag) {}
virtual ~Object_wx_HelpController();
virtual Object *Clone() const;
virtual String ToString(bool exprFlag);
inline wxHelpController *GetEntity() {
return static_cast<wxHelpController *>(_pEntity);
}
inline wxHelpController *ReleaseEntity() {
wxHelpController *pEntity = GetEntity();
InvalidateEntity();
return pEntity;
}
inline bool IsInvalid(Environment &env) const {
if (_pEntity != nullptr) return false;
SetError_InvalidWxObject(env, "wxHelpController");
return true;
}
};
Gura_EndModuleScope(wx)
#endif
| [
"ypsitau@nifty.com"
] | ypsitau@nifty.com |
6baab660313ffb73cbc04e2b99a58f5d36216642 | 63c71060f36866bca4ac27304cef6d5755fdc35c | /src/PacketCheck/HttpPCTestcase.h | 3a8d10ec7e482ead235840990dd80213b69c3979 | [] | no_license | 15831944/barry_dev | bc8441cbfbd4b62fbb42bee3dcb79ff7f5fcaf8a | d4a83421458aa28ca293caa7a5567433e9358596 | refs/heads/master | 2022-03-24T07:00:26.810732 | 2015-12-22T07:19:58 | 2015-12-22T07:19:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,332 | h | #ifndef _Aos_HTTPPCTESTCASE
#define _Aos_HTTPPCTESTCASE
#include "PCTestcase.h"
class AosHttpPCTestcase : public AosPCTestcase
{
OmnDefineRCObject;
public:
AosHttpPCTestcase();
~AosHttpPCTestcase();
virtual int check(char* recvBuffer, int recvLen);
virtual void msgRecved(const AosTcpTrafficGenClientPtr &client,
const OmnConnBuffPtr &buff);
virtual void connCreated(const AosTcpTrafficGenClientPtr &client,
const OmnTcpClientPtr &conn);
virtual void connClosed(const AosTcpTrafficGenClientPtr &client,
const OmnTcpClientPtr &conn);
virtual void readyToSend(const AosTcpTrafficGenClientPtr &client,
const char *data,
const int dataLen,
bool &needToSend);
virtual void sendFinished(const AosTcpTrafficGenClientPtr &client);
virtual void dataSent(const AosTcpTrafficGenClientPtr &client,
const char *data,
const int dataLen);
virtual void sendFailed(const AosTcpTrafficGenClientPtr &client,
const char *data,
const int dataLen,
const OmnRslt &rslt);
virtual void recvFailed(const AosTcpTrafficGenClientPtr &client,
const OmnConnBuffPtr &buff,
AosTcpTrafficGen::Action &action);
virtual void trafficGenFinished(OmnVList<AosTcpTrafficGenClientPtr> &clients);
};
#endif
| [
"barryniu@jimodb.com"
] | barryniu@jimodb.com |
b22d8e43136a060818ff06cf369fd8a2d9c64aaf | c1d6f79edb2bec9f2f31046f319e1f952b67756e | /Trees/Kth_Smallest_Element_In_Tree.cpp | 16cac98a7a6c98e83fe2d8d5b9f610dbfba46a0c | [] | no_license | nishchay121/Scaler-Academy-1 | dfed677bd7fe8cf8bf7da25dd105a8183751ea90 | b803cedc78ab1d82bfee20e203ff24a4237b4bc2 | refs/heads/master | 2023-04-09T14:10:59.256311 | 2021-04-24T16:39:55 | 2021-04-24T16:39:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void findKth(TreeNode* root, int& k,int& ans,int B)
{
if(!root)
return;
findKth(root -> left, k, ans, B);
k++;
if(k == B)
ans = root -> val;
findKth(root -> right, k, ans, B);
}
int Solution::kthsmallest(TreeNode* A, int B) {
if(!A)
return 0;
if(!A -> left && !A -> right){
if(B == 1)
return A -> val;
return 0;
}
int k = 0;
int ans = 0;
findKth(A,k,ans,B);
return ans;
}
| [
"yash1998sarda@gmail.com"
] | yash1998sarda@gmail.com |
840ba0230d3bb6cea2877515b8698fa415ebd448 | 6b18776554b58970ffeb1dda0a9d10bcc0fb8b98 | /TeamFiles/App-wAbstraction/src/torus.cpp | 4d5c7d9843cc9cf4ae62c3fc85bd705cd8c96afc | [] | no_license | sm-rogrp/CG-Proyecto | e1daa4afe908ca4cfbf79378540c2e46aa4989f7 | 2087d0f4eb21e276f585862164109c00c789cf8b | refs/heads/master | 2022-12-14T15:43:40.982514 | 2020-09-18T01:17:13 | 2020-09-18T01:17:13 | 286,052,537 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,119 | cpp | #include "torus.h"
#include <math.h>
#include <vector>
#include <GL\glew.h>
#include <iostream>
#define PI 3.14
void Torus::initData()
{
num_vertices = (seg_x + 1) * (seg_y + 1);
restart_index = num_vertices;
num_indices = (seg_x * 2 * (seg_y + 1)) + seg_x - 1;
// build vertices and normals
std::vector<float> vertices, normales;
float dTheta = 2 * PI / float(seg_x);
float dPhi = 2 * PI / float(seg_y);
float theta = 0.0f;
for (int i = 0; i <= seg_x; i++)
{
float phi = 0.0f;
float sinTheta = sin(theta);
float cosTheta = cos(theta);
for (int j = 0; j <= seg_y; j++)
{
float sinPhi = sin(phi);
float cosPhi = cos(phi);
vertices.push_back((R + r * cosPhi)* cosTheta); // x
vertices.push_back((R + r * cosPhi)* sinTheta); // y
vertices.push_back(r * sinPhi); // z
normales.push_back(cosTheta * cosPhi); // x
normales.push_back(sinTheta * cosPhi); // y
normales.push_back(sinPhi); // z
phi += dPhi;
}
theta += dTheta;
}
// concatenando vertices y normales
std::vector<float> vert_and_norm;
for (int i = 0; i < normales.size(); i+=3) {
vert_and_norm.push_back(vertices[i]);
vert_and_norm.push_back(vertices[i+1]);
vert_and_norm.push_back(vertices[i+2]);
vert_and_norm.push_back(normales[i]);
vert_and_norm.push_back(normales[i+1]);
vert_and_norm.push_back(normales[i+2]);
}
// build vertices to paint normals
std::vector<float> lineas_de_normales;
float long_linea = 0.024f;
for (int i = 0; i < normales.size(); i+=3) {
lineas_de_normales.push_back(vertices[i]);
lineas_de_normales.push_back(vertices[i+1]);
lineas_de_normales.push_back(vertices[i+2]);
lineas_de_normales.push_back(vertices[i] + normales[i] * long_linea);
lineas_de_normales.push_back(vertices[i+1] + normales[i+1] * long_linea);
lineas_de_normales.push_back(vertices[i+2] + normales[i+2] * long_linea);
}
// build indices
std::vector<unsigned int> indices;
GLuint index = 0;
for (auto i = 0; i < seg_x; i++)
{
for (auto j = 0; j <= seg_y; j++)
{
indices.push_back(index);
indices.push_back(index + seg_y + 1);
index++;
}
if (i != seg_x - 1) {
indices.push_back(restart_index);
}
}
unsigned int index_b = (1+seg_y)*seg_x;
index = 0;
for (auto j = 0; j <= seg_y; j++)
{
indices.push_back(index_b);
indices.push_back(index + seg_y + 1);
index++;
index_b++;
}
num_indices = indices.size();
// vao for paint normals
vao_2.bind();
vbo_2.allocate(&lineas_de_normales[0], lineas_de_normales.size() * sizeof(float));
VertexBufferLayout layout_2;
layout_2.AddFloat(3);
vao_2.addBuffer(vbo_2, layout_2);
vao_2.unbind();
// vao for paint torus (vertices and normals)
vao.bind();
vbo.allocate(&vert_and_norm[0], vert_and_norm.size() * sizeof(float));
VertexBufferLayout layout;
layout.AddFloat(3); // vertices
layout.AddFloat(3); // normales
vao.addBuffer(vbo, layout);
vao.unbind();
ibo.allocate(&indices[0], indices.size());
}
void Torus::renderFill() const{
// draw torus fill
vao.bind();
ibo.bind();
glEnable(GL_PRIMITIVE_RESTART);
glPrimitiveRestartIndex(restart_index);
glDrawElements(GL_TRIANGLE_STRIP, num_indices, GL_UNSIGNED_INT, (void *)(0));
glDisable(GL_PRIMITIVE_RESTART);
}
void Torus::renderNormals() const{
// draw torus normals
vao_2.bind();
glDrawArrays(GL_LINES, 0, num_vertices*2);
}
void Torus::renderWire() const{
// draw "wire" mode
vao.bind();
ibo.bind();
glEnable(GL_PRIMITIVE_RESTART);
glPrimitiveRestartIndex(restart_index);
glDrawElements(GL_LINE_STRIP, num_indices, GL_UNSIGNED_INT, (void *)(0));
glDisable(GL_PRIMITIVE_RESTART);
}
| [
"yihsic@gmail.com"
] | yihsic@gmail.com |
ddd3a24a5622a7272199bdbb53161c8e99549a9c | d7001be7468a0b0193804596a864b7126f5fcb52 | /yamiHikariGame/Classes/ResultScene.cpp | 69933e6375973346ec977e9bed5d72d97b3994b6 | [
"MIT"
] | permissive | slightair/yamiHikariGame | 6a13274c71562516bfc7851c968159a163dddf9e | 435e0c8fae38df0aec5165938b6a83a9ee63d096 | refs/heads/master | 2021-01-10T18:38:37.275180 | 2017-04-02T13:56:56 | 2017-04-02T13:56:56 | 11,450,598 | 2 | 0 | null | 2017-04-01T06:15:12 | 2013-07-16T13:46:22 | C++ | UTF-8 | C++ | false | false | 6,889 | cpp | //
// ResultScene.cpp
// yamiHikariGame
//
// Created by slightair on 2013/08/10.
//
//
#include "ResultScene.h"
#include "Constants.h"
#include "GameEngine.h"
#include "Item.h"
#define kItemCountMax 999
#define kBraveImageMarginTop (TitleBarHeight + 48)
#define kBraveMessageMarginTop (TitleBarHeight + 72)
#define kBraveMessageAdjustX 32
#define kBoxFillColor ((ccColor4F){0.0, 0.0, 0.0, 0.0})
#define kBoxBorderColor ((ccColor4F){1.0, 1.0, 1.0, 1.0})
#define kBoxMarginHorizontal 16
#define kBoxMarginTop (TitleBarHeight + 160)
#define kScoreLabelMarginTop (TitleBarHeight + 140)
#define kItemCountLabelMarginTop (TitleBarHeight + 184)
#define kItemImageAreaMarginTop (TitleBarHeight + 234)
#define kNumberOfLineItems 8
#define kItemImageSize 24
#define kItemImageMarginHorizontal 8
#define kItemImageMarginVertical 16
#define kItemImageCountLabelAdjustY 6
#define kCommandAreaHeight 32
#define kCommandAreaMarginTop 14
#define kCommandAreaMarginBottom 18
#define kCommandButtonWidth 88
#define kCommandButtonHeight 64
#define kCommandButtonPadding 32
CCScene* ResultScene::scene()
{
CCScene *scene = CCScene::create();
ResultScene *layer = ResultScene::create();
scene->addChild(layer);
return scene;
}
bool ResultScene::init()
{
bool result = GradientLayer::init();
if (result) {
setTitle(MessageResultTitle);
CCSize windowSize = CCDirector::sharedDirector()->getWinSize();
GameEngine *engine = GameEngine::sharedEngine();
CCSprite *braveImage = CCSprite::createWithSpriteFrameName("brave.png");
braveImage->setRotation(90);
braveImage->setPosition(ccp(windowSize.width / 2, windowSize.height - kBraveImageMarginTop - braveImage->getContentSize().height / 2));
this->addChild(braveImage);
CCLabelTTF *messageLabel = CCLabelTTF::create(engine->getResultMessage(), DefaultFontName, FontSizeSmall);
messageLabel->setPosition(ccp(windowSize.width / 2 + kBraveMessageAdjustX, windowSize.height - kBraveMessageMarginTop));
messageLabel->setAnchorPoint(ccp(0.0, 0.0));
this->addChild(messageLabel);
float boxBottom = kCommandAreaHeight + kCommandAreaMarginTop + kCommandAreaMarginBottom;
CCDrawNode *boxNode = CCDrawNode::create();
CCPoint contentBox[] = {ccp(kBoxMarginHorizontal, windowSize.height - kBoxMarginTop),
ccp(windowSize.width - kBoxMarginHorizontal, windowSize.height - kBoxMarginTop),
ccp(windowSize.width - kBoxMarginHorizontal, boxBottom),
ccp(kBoxMarginHorizontal, boxBottom)};
boxNode->drawPolygon(contentBox, 4, kBoxFillColor, 1, kBoxBorderColor);
this->addChild(boxNode);
CCString *scoreText = CCString::createWithFormat("%s:%d", MessageScoreText, engine->getScore());
CCLabelTTF *scoreLabel = CCLabelTTF::create(scoreText->getCString(), DefaultFontName, FontSizeNormal);
scoreLabel->setPosition(ccp(windowSize.width / 2, windowSize.height - kScoreLabelMarginTop));
this->addChild(scoreLabel);
map<hiberlite::sqlid_t, int> *foundItems = engine->getFoundItems();
map<hiberlite::sqlid_t, int>::iterator foundItemsIterator = foundItems->begin();
vector<Item> *items = engine->getItems();
float itemImageAreaMarginLeft = windowSize.width / 2 - ((kNumberOfLineItems / 2 - 1) * (kItemImageSize + kItemImageMarginHorizontal)) - kItemImageMarginHorizontal / 2 - kItemImageSize / 2;
int sumFoundItems = 0;
int index = 0;
while (foundItemsIterator != foundItems->end()) {
hiberlite::sqlid_t itemID = (*foundItemsIterator).first;
Item item = items->at(itemID - 1);
int count = (*foundItemsIterator).second;
const char *imageFileName = item->image.c_str();
int posX = index % kNumberOfLineItems;
int posY = index / kNumberOfLineItems;
CCPoint imagePosition = ccp(itemImageAreaMarginLeft + (kItemImageSize + kItemImageMarginHorizontal) * posX,
windowSize.height - kItemImageAreaMarginTop - (kItemImageSize + kItemImageMarginVertical) * posY);
CCSprite *itemImage = CCSprite::createWithSpriteFrameName(imageFileName);
itemImage->setPosition(imagePosition);
this->addChild(itemImage);
sumFoundItems += count;
if (count > kItemCountMax) {
count = kItemCountMax;
}
CCString *countText = CCString::createWithFormat("%d", count);
CCLabelTTF *countLabel = CCLabelTTF::create(countText->getCString(), DefaultFontName, FontSizeSmall);
countLabel->setPosition(ccpAdd(imagePosition, ccp(0, -kItemImageSize / 2 - kItemImageCountLabelAdjustY)));
this->addChild(countLabel);
foundItemsIterator++;
index++;
}
CCString *itemCountText = CCString::createWithFormat("%s:%d", MessageNumberOfFoundItemsText, sumFoundItems);
CCLabelTTF *itemCountLabel = CCLabelTTF::create(itemCountText->getCString(), DefaultFontName, FontSizeNormal);
itemCountLabel->setPosition(ccp(windowSize.width / 2, windowSize.height - kItemCountLabelMarginTop));
this->addChild(itemCountLabel);
CCLayerColor *retryLayer = CCLayerColor::create((ccColor4B){0x00, 0x00, 0x00, 0x00}, kCommandButtonWidth, kCommandButtonHeight);
CCLabelTTF *retryLabel = CCLabelTTF::create(MessageRetryButtonTitle, DefaultFontName, FontSizeNormal);
retryLabel->setPosition(ccp(kCommandButtonWidth / 2, kCommandButtonHeight / 2));
retryLayer->addChild(retryLabel);
CCMenuItem *retryItem = CCMenuItemLabel::create(retryLayer,
GameEngine::sharedEngine(),
menu_selector(GameEngine::startNewGame));
CCLayerColor *backTitleLayer = CCLayerColor::create((ccColor4B){0x00, 0x00, 0x00, 0x00}, kCommandButtonWidth, kCommandButtonHeight);
CCLabelTTF *backTitleLabel = CCLabelTTF::create(MessageBackTitleButtonTitle, DefaultFontName, FontSizeNormal);
backTitleLabel->setPosition(ccp(kCommandButtonWidth / 2, kCommandButtonHeight / 2));
backTitleLayer->addChild(backTitleLabel);
CCMenuItem *backTitleItem = CCMenuItemLabel::create(backTitleLayer,
GameEngine::sharedEngine(),
menu_selector(GameEngine::showTitle));
CCMenu *menu = CCMenu::create(retryItem, backTitleItem, NULL);
menu->alignItemsHorizontallyWithPadding(kCommandButtonPadding);
menu->setPosition(ccp(windowSize.width / 2, kCommandAreaMarginBottom + kCommandAreaHeight / 2));
this->addChild(menu);
}
return result;
} | [
"arksutite@gmail.com"
] | arksutite@gmail.com |
ca77220bf2da800f70767c750526243b9c28ee04 | a53f8d2859477f837c81f943c81ceed56cf37238 | /RTL/Component/Culling/CIFXOctreeCollection.h | daed4e6ccae28ae1d2b2a3fd280aba6a6ad34790 | [
"Apache-2.0"
] | permissive | ClinicalGraphics/u3d | ffd062630cde8c27a0792370c158966d51182d4d | a2dc4bf9ead5400939f698d5834b7c5d43dbf42a | refs/heads/master | 2023-04-13T17:25:55.126360 | 2023-03-30T07:34:12 | 2023-03-31T18:20:43 | 61,121,064 | 11 | 5 | Apache-2.0 | 2023-09-01T04:23:31 | 2016-06-14T12:29:13 | C++ | UTF-8 | C++ | false | false | 4,404 | h | //***************************************************************************
//
// Copyright (c) 1999 - 2006 Intel Corporation
//
// 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 _CIFXOCTREE_COLLECTION_H_
#define _CIFXOCTREE_COLLECTION_H_
#include "IFXVector4.h"
#include "IFXCollection.h"
#include "IFXRenderingCIDs.h"
class COctreeNode;
class CIFXOctreeCollection : public IFXCollection
{
private :
protected :
// Max World size that is being partitioned by the tree
IFXVector4 m_worldBound;
// needs to be Computed depending on Scene data distribution
U32 m_minDepth;
// needs to be Computed depending on Scene data distribution
// the max upper limit specified by user to limit recursion
U32 m_maxDepth;
// To adjust the Looseness i.e overlap of the nodes.
F32 m_looseK;
U32 m_uRefCount;
// directional Ligths are not spatials bcos they are infinite
// so we will store these at the root node,
COctreeNode * m_pRootNode;
U32 m_overflowCount;
IFXRESULT InCorporateSpatialBound( IFXSpatial** pInSpatials,
U32 uInNumberOfSpatials,
IFXVector4& rSphere );
BOOL FitsInBox( const IFXVector4 & inSpatialBound,
F32 cx, F32 cy, F32 cz,
F32 octHalfSize) const;
BOOL FitsInBox( IFXSpatial* o,
U32 Instance,
const IFXVector4& c ) const;
BOOL FitsInBox( const IFXVector4& in,
const IFXVector4& c ) const;
U32 InsertRecursivelyIntoBestFitOctreeNode( COctreeNode* q,
IFXSpatial* spatial, U32 Instance);
void ResursivelyAddSpatialsToList( COctreeNode *pCurrNode, IFXSpatial**& rpOutSpatials,
U32& ruOutNumberOfSpatials, U32& ruListStart,
IFXSpatial::eType eIntype );
CIFXOctreeCollection(): m_maxDepth(0),m_looseK(0),
m_uRefCount(0),m_pRootNode(0),DepthTotals(0){}
virtual ~CIFXOctreeCollection();
void CleanUp();
public :
// Statistical / Debug info
U32 * DepthTotals;
IFXRESULT Initialize(IFXVector4 worldBound = IFXVector4(0,0,0,1024.0),F32 k = 1, U32 maxD = 4);
COctreeNode* GetRootNode() const{return m_pRootNode;}
F32 GetWorldSize() const{return m_worldBound.Radius()*2;}
U32 GetMaxDepth () const{return m_maxDepth;}
F32 GetLooseK() const{return m_looseK;}
U32 Insert(IFXSpatial* o, U32 Instance);
U32 Insert(COctreeNode* q, IFXSpatial* pInSpatial, U32 Instance);
void TraverseNodes(COctreeNode *on,void (*nf)(COctreeNode * on));
void TraverseNodes(COctreeNode *on,void (*nf)(COctreeNode * on,void * data));
void TraverseNodes(COctreeNode *on,void (*pre)(COctreeNode * on),void (*post)(COctreeNode * on));
void TraverseTree(void (*nf)(COctreeNode * on)){ TraverseNodes(m_pRootNode, nf);}
// IFXUnknown
U32 IFXAPI AddRef ();
U32 IFXAPI Release ();
IFXRESULT IFXAPI QueryInterface ( IFXREFIID interfaceId,void **ppv);
// Factory Function for Octree Creation
friend IFXRESULT IFXAPI_CALLTYPE CIFXOctreeCollection_Factory(IFXREFIID interfaceId, void** ppinterface);
// Collection Functionality
IFXRESULT IFXAPI InitializeCollection( IFXSpatial** pInSpatials,
U32 uInNumberOfSpatials,
IFXSpatial::eType eIntype );
IFXRESULT IFXAPI InitializeCollection( IFXCollection* pInCollection );
IFXRESULT IFXAPI AddSpatials( IFXSpatial** pInSpatials,
U32 uInNumberOfSpatials,
IFXSpatial::eType eIntype );
IFXRESULT IFXAPI RemoveSpatials( IFXSpatial** pInSpatials,
U32 uInNumberOfSpatials,
IFXSpatial::eType eIntype );
IFXRESULT IFXAPI GetSpatials( IFXSpatial**& rpOutSpatials,
U32& ruOutNumberOfSpatials,
IFXSpatial::eType eIntype );
const IFXGUID& GetCID() { return CID_IFXOctreeCollection; }
};
#endif
| [
"ningfei.li@gmail.com"
] | ningfei.li@gmail.com |
2f5e9e2c3b233af6d79b783d52d08e24015e2cf2 | a32dbb46dff80f43755245c1a13f3c9751cb4c47 | /SVMDice.cpp | a35a7c1af7c528ccc8e33188440eb77a979aba12 | [] | no_license | gaetanbahl/DiceDetection | 0b879049c6693117eb60ccad5779969f17cf992a | c07cc48a31b857bdd865bc552abda174cbdeee87 | refs/heads/master | 2021-01-17T20:01:25.419146 | 2016-06-13T16:41:26 | 2016-06-13T16:41:26 | 59,890,047 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,091 | cpp | /*
* SVMDice.cpp
*
* OCR to train and recognize digits with the SVM model.
*
*/
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/ml/ml.hpp>
#include <exception>
#include "SVMDice.h"
using namespace ml;
SVMDice::SVMDice() :
_pModel() {
}
SVMDice::~SVMDice() {
if (_pModel) {
delete _pModel;
}
}
/**
* Learn a single digit.
*/
int SVMDice::learn(const cv::Mat & img, int n) {
_responses.push_back(cv::Mat(1, 1, CV_32S, n));
_samples.push_back(prepareSample(img));
return (int) n;
}
/**
* Save training data to file.
*/
void SVMDice::saveTrainingData() {
cv::FileStorage fs("../modeldataSVM", cv::FileStorage::WRITE);
fs << "samples" << _samples;
fs << "responses" << _responses;
fs.release();
}
/**
* Load training data from file and init model.
*/
bool SVMDice::loadTrainingData() {
cv::FileStorage fs("../modeldataSVM", cv::FileStorage::READ);
if (fs.isOpened()) {
fs["samples"] >> _samples;
fs["responses"] >> _responses;
fs.release();
initModel();
} else {
return false;
}
return true;
}
/**
* Recognize a single digit.
*/
int SVMDice::recognize(const cv::Mat& img) {
char cres = '?';
if (!_pModel) {
throw std::runtime_error("Model is not initialized");
}
cv::Mat results, neighborResponses, dists;
cres = _pModel->predict(prepareSample(img));
return cres;
}
/**
* Prepare an image of a digit to work as a sample for the model.
*/
cv::Mat SVMDice::prepareSample(const cv::Mat& img) {
cv::Mat roi, sample;
cv::resize(img, roi, cv::Size(10, 10));
roi.reshape(1, 1).convertTo(sample, CV_32F);
return sample;
}
/**
* Initialize the model.
*/
void SVMDice::initModel() {
_pModel = ml::SVM::create();
_pModel->setType(ml::SVM::C_SVC);
_pModel->setKernel(ml::SVM::LINEAR);
_pModel->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));
_pModel->train(_samples,ROW_SAMPLE, _responses);
}
| [
"gaetan.bahl@arm.com"
] | gaetan.bahl@arm.com |
2b394eeba29b06cd684ba183b788e2f88916259a | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/old_hunk_5361.cpp | 8652cae03e58a3d7f75fb382b4e7a758061c4a09 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | int ch = *eol;
int eflags = 0;
*eol = '\0';
while (next_match(opt, bol, eol, ctx, &match, eflags)) {
if (match.rm_so == match.rm_eo)
break;
opt->output(opt, bol, match.rm_so);
output_color(opt, bol + match.rm_so,
match.rm_eo - match.rm_so,
opt->color_match);
| [
"993273596@qq.com"
] | 993273596@qq.com |
028db73fa6f39d72dabd1703358386a6258b6725 | 872d5a0212838797ceb54a7d7580ba22d9b42872 | /repos/Sample402/Sample402/Car.cpp | a4a31ceb9c62d213407f8e36748b9e1342772400 | [] | no_license | jun-yoshiyoshi/7days-traning-for-Cpp | 30baf9f1f7cfdf01181fd2e091fd43519fc9af8a | 61b42302ff181546bfc590ddcf6997ca35398d85 | refs/heads/main | 2023-07-28T03:40:50.868019 | 2021-09-13T20:28:46 | 2021-09-13T20:28:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | cpp | #include "Car.h"
#include <iostream>
using namespace std;
Car::Car() :m_speed(0.0), m_migration(0.0) {
cout << "Car instance" << endl;
}
Car::~Car() {
cout << "Delete car instance";
}
void Car::setSpeed(double speed) {
m_speed = speed;
}
double Car::getSpeed() {
return m_speed;
}
double Car::getMigration() {
return m_migration;
}
void Car::drive(double hour) {
cout << "speed:" << m_speed << " time:" << hour << endl;
cout << "drive for:" << m_speed * hour << "km" << endl;
m_migration += hour * m_speed;
}
| [
"yoshi.jun.yoshi.jun0621@gmail.com"
] | yoshi.jun.yoshi.jun0621@gmail.com |
ff2d511845acd4327a75c01a7451ebdfc10ee155 | c7a49574631c6935444839d01afbb1636274001c | /lab24/lab24.cpp | 232143b43943fec86e18d9d42c062240fe5b5bdc | [] | no_license | jsannar14/CSCI20-Fall2017 | 714d861a7afbe0bd59d52435ab93324f406c909f | a7fdda336c60e8e708e13b342ab02782a4458a96 | refs/heads/master | 2021-01-19T18:22:10.044181 | 2017-10-27T04:46:32 | 2017-10-27T04:46:32 | 101,127,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,618 | cpp | //Created By: John Sannar
//Created On: 9/26/2017
//A random number generator thing
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int randomNumber(int& firstNumber , int& secondNumber){ // This is the main fuction that calculates the random number
int lowRange = 1;
int highRange = 100;
cout << "Please enter the first number: " << endl;
cin >> lowRange;
cout << "Please enter the Second Number: " << endl;
cin >> highRange;
srand(time(0));
int randNum = rand()%((highRange - lowRange) + 1); // equation for calculating random number from given range
cout << "Your random number is "<< randNum << " " << endl;
return randNum;
}
double poundsToKilo(int weightPounds){
const double kgPerPound = .45;
int randomKgValue = 0;
double kgValue = 0.0;
randomKgValue = (weightPounds * kgPerPound); // pounds to kg conversion line
return randomKgValue;
}
int main(){
int randNum;
int firstNumber;
int secondNumber;
int Kilogram;
int pounds;
double kiloToPounds;
double kgConversion;
double kgPerPound = .45;
double poundPerkg = 2.2;
randNum = randomNumber(firstNumber, secondNumber);
pounds = randNum;
cout << "Pounds: " << pounds << endl;
kgConversion = randNum * kgPerPound;
cout << "Kilograms: " << kgConversion << endl;
kiloToPounds = kgConversion * poundPerkg;
cout << "Final Pounds: " << kiloToPounds << endl;
}
| [
"jsannar003@student.butte.edu"
] | jsannar003@student.butte.edu |
837a8fd058f9a2694b267668677bddac3710d7b9 | 51c1c5e9b8489ef8afa029b162aaf4c8f8bda7fc | /coceditor/src/coceditor/GenPentagon.h | 2725b01b67b22f73ea457d5fe05ab62e1682e5de | [
"MIT"
] | permissive | aimoonchen/easyeditor | 3e5c77f0173a40a802fd73d7b741c064095d83e6 | 9dabdbfb8ad7b00c992d997d6662752130d5a02d | refs/heads/master | 2021-04-26T23:06:27.016240 | 2018-02-12T02:28:50 | 2018-02-12T02:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 158 | h | #pragma once
namespace coceditor
{
class GenPentagon
{
public:
static void trigger(float edge, float val[5], ee::Vector out[5]);
}; // GenPentagon
} | [
"zhuguang@ejoy.com"
] | zhuguang@ejoy.com |
f7a0645cd9ca5b9524ca190034f75a3c46fce857 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /third_party/android_crazy_linker/src/tests/test_dl_wrappers_with_android_dlopen_ext.cpp | 71faae946c933c012418cf21600a62f4252bc67e | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"BSD-2-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 4,803 | cpp | // 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.
// A crazy linker test to:
// - Load a library (LIB_NAME) with the linker.
// - Find the address of the "OpenExtFindRunClose" function in LIB_NAME.
// - Call the OpenExtFindRunClose() function, which will use
// android_dlopen_ext() /
// dlsym() to find libbar.so (which depends on libfoo.so).
// - Close the library.
// This tests the android_dlopen_ext/dlsym/dlclose wrappers provided by the
// crazy linker to loaded libraries.
#include <crazy_linker.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#ifdef __ANDROID__
#include <android/dlext.h>
#else
#error "This source file only compiles for Android!"
#endif
#include "test_util.h"
typedef bool (*OpenExtFindRunCloseFunctionPtr)(const char* lib_name,
const char* func_name,
const android_dlextinfo* info);
#define LIB_NAME "libcrazy_linker_tests_libzoo_with_android_dlopen_ext.so"
#define FUNC_NAME "OpenExtFindRunClose"
#define LIB2_NAME "libcrazy_linker_tests_libbar.so"
#define FUNC2_NAME "Bar"
int main() {
crazy_context_t* context = crazy_context_create();
crazy_library_t* library;
// Load LIB_NAME
if (!crazy_library_open(&library, LIB_NAME, context)) {
Panic("Could not open library: %s\n", crazy_context_get_error(context));
}
// Find the "OpenExtFindRunClose" symbol from LIB_NAME
OpenExtFindRunCloseFunctionPtr lib_func;
if (!crazy_library_find_symbol(library, "OpenExtFindRunClose",
reinterpret_cast<void**>(&lib_func))) {
Panic("Could not find '" FUNC_NAME "' in " LIB_NAME "\n");
}
bool ret;
// Call it, without dlext info.
printf("////////////////////////// FIRST CALL WITHOUT DLEXT INFO\n");
ret = (*lib_func)(LIB2_NAME, FUNC2_NAME, nullptr);
if (!ret)
Panic("'" FUNC_NAME "' function failed!");
// Call it again, this time load the library from a file descriptor.
printf("////////////////////////// SECOND CALL WITH LIBRARY FD\n");
{
android_dlextinfo info = {};
info.flags = ANDROID_DLEXT_USE_LIBRARY_FD;
info.library_fd = ::open(LIB2_NAME, O_RDONLY | O_CLOEXEC);
if (info.library_fd < 0)
PanicErrno("Could not open library file directly");
ret = (*lib_func)(nullptr, FUNC2_NAME, &info);
if (!ret)
Panic("'" FUNC_NAME "' function failed with file descriptor!");
close(info.library_fd);
}
fflush(stdout);
printf("////////////////////////// THIRD CALL WITH RESERVED MAP\n");
{
android_dlextinfo info = {};
info.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
info.reserved_size = 64 * 4096;
info.reserved_addr = ::mmap(nullptr, info.reserved_size, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (info.reserved_addr == MAP_FAILED)
PanicErrno("Could not reserve address map region");
ret = (*lib_func)(LIB2_NAME, FUNC2_NAME, &info);
if (!ret)
Panic("'" FUNC_NAME "' function failed with reserved map!");
::munmap(info.reserved_addr, info.reserved_size);
}
fflush(stdout);
printf("////////////////////////// FOURTH CALL WITH TINY RESERVED MAP\n");
{
android_dlextinfo info = {};
info.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
info.reserved_size = 1 * 4096;
info.reserved_addr = ::mmap(nullptr, info.reserved_size, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (info.reserved_addr == MAP_FAILED)
PanicErrno("Could not reserve address map region");
ret = (*lib_func)(LIB2_NAME, FUNC2_NAME, &info);
if (ret)
Panic("'" FUNC_NAME "' function succeeded with tiny reserved map!");
::munmap(info.reserved_addr, info.reserved_size);
}
fflush(stdout);
printf("////////////////////////// FIFTH CALL WITH RESERVED MAP + HINT\n");
{
android_dlextinfo info = {};
info.flags =
ANDROID_DLEXT_RESERVED_ADDRESS | ANDROID_DLEXT_RESERVED_ADDRESS_HINT;
info.reserved_size = 1 * 4096;
info.reserved_addr = ::mmap(nullptr, info.reserved_size, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (info.reserved_addr == MAP_FAILED)
PanicErrno("Could not reserve address map region");
ret = (*lib_func)(LIB2_NAME, FUNC2_NAME, &info);
if (!ret)
Panic("'" FUNC_NAME "' failed with tiny reserved map and hint!");
::munmap(info.reserved_addr, info.reserved_size);
}
fflush(stdout);
printf("//////////////////////////\n");
// Close the library.
printf("Closing " LIB_NAME "\n");
crazy_library_close(library);
crazy_context_destroy(context);
printf("OK\n");
return 0;
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
df5f37fde1b08c3711046f2a77c46c1a1d9c6468 | 91dd40450b8f251e96b70da424e3c5b82d3493ba | /relational_operator.cpp | 42f49d39cc7e7aff8a29b5a0aa2aef3fba6201a9 | [] | no_license | danielecappuccio/UVa-online-judge | 3cfa2cdafeb5deec9048483964dbe7969b719650 | b3a6c65a56aad98cd5e86325cd1f29082892b86f | refs/heads/master | 2021-07-06T09:56:05.257214 | 2017-10-01T11:51:28 | 2017-10-01T11:51:28 | 85,356,118 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 465 | cpp | /*
* Competitive Programming
*
* @author Daniele Cappuccio
* @link (https://github.com/daniele-cappuccio/UVa-online-judge)
* @license MIT License (https://opensource.org/licenses/MIT)
*/
#include <iostream>
using namespace std;
int main(){
int N, a, b;
cin >> N;
for (int i=0; i<N; ++i){
cin >> a >> b;
if (a < b) cout << "<" << endl;
else if (a == b) cout << "=" << endl;
else cout << ">" << endl;
}
return 0;
}
| [
"daniele97bsk@gmail.com"
] | daniele97bsk@gmail.com |
f0ca73458004e92681bb990775bf648ef45c53a4 | 2cd6a9e853aedf8c9433aea2d546c9b8e9fe015f | /Playlist.cpp | 84d3aaa127d316cdd89de1ff63368521153bd037 | [] | no_license | herlmanoel/projeto_linguagem_de_programacao_i | f52e403e5e9e953f929b43dc3bbba3a9eebd51f3 | 8f8e278f6f696b8120aad2f48b0621b238ed51c9 | refs/heads/main | 2023-03-19T21:23:26.422966 | 2021-03-09T09:55:00 | 2021-03-09T09:55:00 | 344,619,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,814 | cpp | #include <iostream>
#include "Musica.h"
#include "Lista.h"
#include "Playlist.h"
using namespace std;
using std::cin;
using std::cout;
using std::endl;
// Construtor
Playlist::Playlist()
{
nome = "";
Lista *lista = new Lista();
this->lista = lista;
}
/** Método constructor passando como parametro o nome da Playlist
* @param nome - string - nome da playlist
*/
Playlist::Playlist(string nome)
{
this->nome = nome;
Lista *lista = new Lista();
this->lista = lista;
}
/** Método construtor cópia
* @param Playlist &p - referencia para a Playlist
*/
Playlist::Playlist(const Playlist &p)
{
this->nome = p.nome;
Lista *nova_lista = p.lista;
this->lista = nova_lista;
}
/** Método para setar nome
* @param nome - string - nome da playlist
*/
void Playlist::setNome(string nome)
{
this->nome = nome;
}
/** Método para acessar o nome
* @return nome - string - nome da playlist
*/
string Playlist::getNome()
{
return nome;
}
/** Método para acessar a lista
* @return lista - Lista* - lista de musicas
*/
Lista *Playlist::getLista()
{
return lista;
}
/** Método para setar lista
* @param lista - Lista* - lista de musicas
*/
void Playlist::setLista(Lista *lista)
{
this->lista = lista;
}
/** Método para adicionar musica na lista
* @param nome - string - nome do artista
* @param titulo - string - titulo da musica
*/
void Playlist::adicionarMusicaPlaylist(string nome, string titulo)
{
lista->inserirNoInicio(nome, titulo);
}
/** Método sobrecarregado para unir duas Playlists
* @param Playlist &p- referencia para a Playlist
*/
void Playlist::adicionarMusicaPlaylist(Playlist &p)
{
lista->inserirNoInicio(*(p.getLista()));
}
/** Método para remover musica na lista
* @param nome - string - nome do artista
* @param titulo - string - titulo da musica
*/
void Playlist::removerMusica(string nome, string titulo)
{
lista->remover(nome, titulo);
}
/** Método sobrecarregado para remover uma Playlist de outra Playlist
* @param Playlist &p- referencia para a Playlist
*/
void Playlist::removerMusica(Playlist &p)
{
lista->remover(*(p.getLista()));
}
/** Método para pegar a proxima musica na lista
* @param musica - Musica* - instancia da musica
*/
Musica *Playlist::getProximaMusica(Musica *musica)
{
return musica->getProxima();
}
/** Método recursivo para imprimir todas as musicas
* @param musica - Musica* - instancia da primeira musica da lista
*/
void Playlist::imprimirTodasMusicas(Musica *musica)
{
if (musica == NULL)
{
cout << endl;
return;
}
cout << musica->getNome() << " | " << musica->getTitulo() << endl;
cout << "-----------------------------" << endl;
return Playlist::imprimirTodasMusicas(musica->getProxima());
}
/** Método destructor
* Liberar o espaço da lista
*/
Playlist::~Playlist()
{
delete lista;
}
/** Método sobrecarregando o operador "+" unindo duas Playlists
* @param Playlist &p- referencia para a Playlist
*/
Playlist Playlist::operator+(Playlist &p)
{
Playlist nova_playlist;
Lista *nova_lista = nova_playlist.getLista();
Musica *m_p = lista->getPrimeira();
while (m_p != NULL)
{
nova_lista->inserirNoInicio(m_p->getNome(), m_p->getTitulo());
m_p = m_p->getProxima();
}
Musica *musica = p.getLista()->getPrimeira();
while (musica != NULL)
{
if (!nova_lista->buscarPeloNomeTitulo(musica->getNome(), musica->getTitulo()))
{
nova_lista->inserirNoInicio(musica->getNome(), musica->getTitulo());
}
musica = musica->getProxima();
}
return nova_playlist;
}
/** Método sobrecarregando o operador "+" add uma música ao final da playlist
* @param Musica &m - referencia para a Música
*/
Playlist Playlist::operator+(Musica &m)
{
Playlist nova_playlist;
Lista *nova_lista = nova_playlist.getLista();
Musica *m_p = lista->getPrimeira();
while (m_p != NULL)
{
nova_lista->inserirNoInicio(m_p->getNome(), m_p->getTitulo());
m_p = m_p->getProxima();
}
nova_lista->getUltima()->setProxima(&m);
return nova_playlist;
}
/** Método sobrecarregando o operador "-" removendo uma Playlist de outra Playlist
* @param Playlist &p- referencia para a Playlist
*/
Playlist Playlist::operator-(Playlist &p)
{
Playlist nova_playlist;
Lista *nova_lista = nova_playlist.getLista();
Musica *m_p = lista->getPrimeira();
while (m_p != NULL)
{
nova_lista->inserirNoInicio(m_p->getNome(), m_p->getTitulo());
m_p = m_p->getProxima();
}
nova_lista->remover(*(p.getLista()));
return nova_playlist;
}
/** Método sobrecarregando o operador "-" removendo uma música de uma Playlist
* @param Musica &m - referencia da Música
*/
Playlist Playlist::operator-(Musica &m)
{
Playlist nova_playlist;
Lista *nova_lista = nova_playlist.getLista();
Musica *m_p = lista->getPrimeira();
while (m_p != NULL)
{
nova_lista->inserirNoInicio(m_p->getNome(), m_p->getTitulo());
m_p = m_p->getProxima();
}
nova_lista->remover(m.getNome(), m.getTitulo());
return nova_playlist;
}
/** Método sobrecarregando o operador ">>" add a última música da Playlist na referencia de musica e removendo
* @param Musica &m - referencia da Música
*/
void Playlist::operator>>(Musica &m)
{
if (lista->getPrimeira() != NULL)
{
m.setNome(lista->getUltima()->getNome());
m.setTitulo(lista->getUltima()->getTitulo());
lista->removerUltima();
}
}
/** Método sobrecarregando o operador "<<" add uma música ao final da Playlist
* @param Musica &m - referencia da Música
*/
void Playlist::operator<<(Musica &m)
{
if (lista->getPrimeira() != NULL)
{
lista->getUltima()->setProxima(&m);
}
}
| [
"herlmanoelfernandes@gmail.com"
] | herlmanoelfernandes@gmail.com |
600ed8a9fc1bc20fe4efa7ef6dffe4662ebf4bfb | 18e4b5ca2d2d0b98f2aa1611766ffcebd6ff1007 | /D6-Graphs/topo_sort.cpp | 89d4f0ed7529d529ad6ae36458a44eeb32303091 | [] | no_license | webdeveloper13/Leetcode_practiceForSDE | 3cb4b2575825ced624daa13b0cd7a46a536cb88a | 04131f2bcf9cf4dd946419275a47e937472d0757 | refs/heads/master | 2023-08-23T06:53:26.743144 | 2021-10-13T15:04:23 | 2021-10-13T15:04:23 | 274,382,785 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,830 | cpp | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector <int> topoSort(int N, vector<int> adj[]);
/* Function to check if elements returned by user
* contains the elements in topological sorted form
* V: number of vertices
* *res: array containing elements in topological sorted form
* adj[]: graph input
*/
bool check(int V, vector <int> &res, vector<int> adj[]) {
vector<int> map(V, -1);
for (int i = 0; i < V; i++) {
map[res[i]] = i;
}
for (int i = 0; i < V; i++) {
for (int v : adj[i]) {
if (map[i] > map[v]) return false;
}
}
return true;
}
// Driver Code
int main() {
int T;
cin >> T;
while (T--) {
int N, E;
cin >> E >> N;
int u, v;
vector<int> adj[N];
for (int i = 0; i < E; i++) {
cin >> u >> v;
adj[u].push_back(v);
}
vector <int> res = topoSort(N, adj);
cout << check(N, res, adj) << endl;
}
}// } Driver Code Ends
// The Graph structure is as folows
/* Function which sorts the graph vertices in topological form
* N: number of vertices
* adj[]: input graph
*/
vector<int> topoSort(int V, vector<int> adj[]) {
// Your code here
vector<int> indegree(V,0);
for(int u=0;u<V;u++)
{
for(auto it: adj[u])
{
indegree[it]++;
}
}
queue<int> q1;
for(int i=0;i<V;i++)
{
if(indegree[i]==0)
q1.push(i);
}
vector<int> topo_order;
while(!q1.empty())
{
int u = q1.front();
topo_order.push_back(u);
q1.pop();
for(auto it : adj[u])
{
if(--indegree[it]==0)
{
q1.push(it);
}
}
}
return topo_order;
}
| [
"suryanshsharma132@gmail.com"
] | suryanshsharma132@gmail.com |
19a6d9419637f0222fc8e9f7b92963098e09f517 | 44407e4350d23d71bb1e55df18ff4cff693ad2cb | /Server/SingleThreaded/src/edServer.cpp | 84c57a20f3648f85864082089b1ec029f28eab5f | [] | no_license | iskettan/ServerArchitectures | 5c94228908beca3ccac4f524b53ee8e246ecd373 | e42da32a1c1a630910b63ccc3395e9cd87c5faa0 | refs/heads/main | 2023-04-13T22:37:58.827267 | 2021-04-22T22:21:27 | 2021-04-22T22:21:27 | 358,110,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,256 | cpp | // event driven server.
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <cerrno>
#include <iostream>
#include <vector>
#include <socketHelper.h>
#include <thread>
#include "spdlog/spdlog.h"
#include "configParser.h"
#include <arpa/inet.h>
#include "config.h"
#include "utils.h"
#include <unordered_map>
#include "clientConnection.h"
void serve_client( int client_fd, struct sockaddr_in client_address )
/*******************************************************************/
{
current_active_connections++;
while( true ) {
char buf[1024];
u_int16_t message_size;
read_message_max_1024( client_fd, buf, message_size );
if( message_size == 0 ) {
// Client closed connection.
break;
}
if( !handle_client_request( client_fd, client_address, buf, message_size ) ) {
break;
}
}
current_active_connections--;
}
void accept_client( int server_fd )
{
while(true) {
struct sockaddr_in client_address;
int client_fd = server_socket_accept( server_fd, client_address );
char client_ip[INET_ADDRSTRLEN];
inet_ntop( AF_INET, &( client_address.sin_addr ), client_ip, sizeof( client_address ) );
spdlog::debug( "Client {}:{} has connected to the server.", client_ip, ntohs( client_address.sin_port ) );
serve_client( client_fd, client_address );
}
}
int main(int argc, const char *argv[])
{
/************************************/
ConfigParser cp;
cp.commandLineParser( argc, argv );
spdlog::info( "Server started." );
struct sockaddr_in server_address;
// Creating a server socket.
int server_fd = server_socket_create( server_address, CONFIG::SERVER_PORT );
// Attaching socket to the port
server_socket_bind( server_address, server_fd );
// Set socket as non-blocking
set_non_blocking_socket( server_fd );
// Prepare socket for listening
server_socket_listen( server_fd );
spdlog::info( "Server listening to port {}.", CONFIG::SERVER_PORT );
// Create epoll fd
int epoll_fd = epoll_create();
// Add the server socket to the epoll_fd
struct epoll_event event;
event.data.fd = server_fd;
event.events = EPOLLIN | EPOLLET;
if ( epoll_ctl( epoll_fd, EPOLL_CTL_ADD, server_fd, &event ) == -1 )
if ( epoll_fd == -1 )
{
perror("epoll_ctl failed");
exit(EXIT_FAILURE);
}
const int MAX_EVENTS = 128;
std::array<struct epoll_event, MAX_EVENTS> events;
t1 = std::chrono::high_resolution_clock::now();
while (true)
{
auto n = epoll_wait(epoll_fd, events.data(), MAX_EVENTS, -1);
for (int i = 0; i < n; ++i)
{
if (events[i].events & EPOLLERR ||
events[i].events & EPOLLHUP ||
!(events[i].events & EPOLLIN)) // error
{
std::cerr << "[E] epoll event error\n";
close(events[i].data.fd);
}
else if (server_fd == events[i].data.fd) // new connection
{
struct sockaddr_in client_addr;
int client_fd = -1;
while ( ( client_fd = accept_connection(server_fd, event, epoll_fd, client_addr) ) == -1 );
clientConnection *cc = new clientConnection( client_fd, client_addr );
clientsConnections[client_fd] = cc;
std::cout << "client fd added: " << client_fd << std::endl;
char client_ip[INET_ADDRSTRLEN];
inet_ntop( AF_INET, &( client_addr.sin_addr ), client_ip, sizeof( client_addr ) );
spdlog::debug( "Client {}:{} has connected to the server.", client_ip, ntohs( client_addr.sin_port ) );
}
else // data to read
{
auto client_fd = events[i].data.fd;
std::cout << "client fd sent data on fd: " << client_fd << std::endl;
clientConnection *cc = clientsConnections[client_fd];
while (cc->read_data());
}
}
}
spdlog::critical("should never reach here");
return 0;
} | [
"iskettan@uwaterloo.ca"
] | iskettan@uwaterloo.ca |
079dd7064d35b9899f88579996ffbe86e64f3e9f | 29d33871009e3f5bb4d4655b8be34abc36b1f38e | /class/class3/game.h | f8044e8cc1d3aa21b22e2106eafd5657c99b7042 | [] | no_license | duchevich/c-plus-plus-VS2017-course | 7132464dc0fada1e053028f3f6dbe17e503329cd | f6945fd8188cdbc1d511b111dfa77920d15895ab | refs/heads/master | 2021-09-01T04:24:24.837465 | 2017-12-24T19:22:26 | 2017-12-24T19:22:26 | 115,279,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 205 | h | #pragma once
#include <iostream>
#include "player.h"
class game
{
public:
player play[2];
game();
~game();
void setGame();
void printScreen();
void playGame();
bool checkField(int ver, int hor);
}; | [
"duchevich274@gmail.com"
] | duchevich274@gmail.com |
df7059037975b2b74317e475ee4d535fe0c2ce35 | ca01d5871546037014f3d800a0f2f46b04c0d20d | /Array/kidswithMaxCanadies.cpp | 9d27af22d77aad0184eb29f104ab63ebe923f521 | [] | no_license | Sanjeetkushwaha11111/Important-DSA-programs | 590142db51d06e519ff536b27432cf74359dfcc9 | 9f891525ea0740a0499444c54bfd5b8a3a107bec | refs/heads/master | 2023-07-07T04:17:27.216735 | 2021-08-07T07:28:12 | 2021-08-07T07:28:12 | 369,685,710 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 818 | cpp | #include<bits/stdc++.h>
using namespace std;
void maxCandies(std::vector<int> Candies,int EC) {
std::vector<bool> result;
std::vector<int> sumCandies;
int n=Candies.size();
int maxCandies=0;
for (int i = 0; i < n; i++) {
if (Candies[i]> maxCandies) {
maxCandies=Candies[i];
}
}
for (int i = 0; i < n; i++) {
if (Candies[i]+EC>=maxCandies) {
result.push_back(true);
}
else
result.push_back(false);
}
for (int i = 0; i < result.size(); i++) {
std::cout << result[i] << '\n';
result.pop_back();
}
}
int main(int argc, char const *argv[]) {
std::vector<int> v;
std::cout << "Extra Candies:" << '\n';
int EC;
std::cin >> EC;
int d;
std::cin >> d;
while (d!=-1) {
v.push_back(d);
std::cin >> d;
}
maxCandies(v,EC);
return 0;
}
| [
"sanjeetkushwaha1111gmailom"
] | sanjeetkushwaha1111gmailom |
58f93f37fe6f304356704c32363a7598b59e69ff | bb38c44037a99d0a12a12d92059678f2faebbc80 | /src/common/interfaces/libpq/client_logic_processor/raw_values_cont.h | f577849f682002320161067567b9d3ad42c7efa4 | [
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference",
"PostgreSQL",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"curl",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"CC-BY-4.0",
... | permissive | opengauss-mirror/openGauss-server | a9c5a62908643492347830826c56da49f0942796 | 310e84631c68c8bf37b004148b66f94064f701e4 | refs/heads/master | 2023-07-26T19:29:12.495484 | 2023-07-17T12:23:32 | 2023-07-17T12:23:32 | 276,117,477 | 591 | 208 | MulanPSL-2.0 | 2023-04-28T12:30:18 | 2020-06-30T14:08:59 | C++ | UTF-8 | C++ | false | false | 2,913 | h | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* raw_values_cont.h
*
* IDENTIFICATION
* src\common\interfaces\libpq\client_logic_processor\raw_values_cont.h
*
* -------------------------------------------------------------------------
*/
#ifndef RAW_VALUES_CONT_H
#define RAW_VALUES_CONT_H
#include <cstddef>
#include <ctype.h>
#include <unistd.h>
#include <stdint.h>
#include "client_logic_common/statement_data.h"
typedef struct pg_conn PGconn;
struct InsertStmt;
struct SelectStmt;
struct UpdateStmt;
struct ExecuteStmt;
struct A_Expr;
struct ExprParts;
class ExprPartsList;
class RawValuesList;
class RawValues {
public:
static bool get_raw_values_from_insert_statement(const InsertStmt * const insert_stmt,
StatementData *statement_data, RawValuesList *raw_values_list);
static bool get_raw_values_from_update_statement(const UpdateStmt * const update_stmt,
StatementData *statement_data, RawValuesList *raw_values_list);
static bool get_raw_values_from_execute_statement(const ExecuteStmt * const execute_stmt,
StatementData *statement_data, RawValuesList *raw_values_list);
static bool get_raw_values_from_consts_vec(const ExprPartsList *expr_parts_list, StatementData *statement_data,
int offset, RawValuesList *raw_values_list);
static bool get_unprocessed_data(const RawValuesList *raw_values_list, const unsigned char *processed_data,
unsigned char *unprocessed_data, size_t &size);
private:
static size_t count_literals(const char *str, size_t size);
static bool get_cached_default_values(const char *db_name, const char *schema_name, const char *table_name,
RawValuesList *raw_values_list);
static bool get_raw_values_from_insert_select_statement(const SelectStmt * const select_stmt,
StatementData *statement_data, RawValuesList *raw_values_list);
static bool get_raw_values_from_value_lists(List * const exprList, StatementData *statement_data,
RawValuesList *raw_values_list);
static void get_raw_values_from_nodetag(const Value *value, int &end, int loc, const ExprParts *xpr,
bool &is_emptyb, bool &is_str, const StatementData *statement_data);
static RawValue *get_raw_values_from_ExprParts(
const ExprParts *expr_parts, StatementData *statement_data, size_t offset);
};
#endif | [
"dengxuyue@huawei.com"
] | dengxuyue@huawei.com |
9eb1f35a2bdd77e68bf544ed053e7947c0302b44 | 7d97b0c20d6f8512b3bd4c4599a5dbd40551bc89 | /Simulation/HEPDSW_v4/source/Dataformats/include/Interaction.hh | 6f027df74b0da5ae798e93acaf75e1b9c2225057 | [] | no_license | 92Luke92/LimadouHEPD | 43207bdb89248fc4517bed1111f095a4af65b784 | fc2f255a1f755795e3137658f45ce2d7c33784ef | refs/heads/master | 2020-04-24T08:38:30.538645 | 2020-01-31T14:53:16 | 2020-01-31T14:53:16 | 171,837,356 | 0 | 0 | null | 2019-02-21T09:06:08 | 2019-02-21T09:06:07 | null | UTF-8 | C++ | false | false | 3,263 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
#ifndef Interaction_h
#define Interaction_h 1
#include "G4VHit.hh"
#include "G4THitsCollection.hh"
#include "G4Allocator.hh"
#include "G4ThreeVector.hh"
class Interaction : public G4VHit
{
public:
Interaction();
Interaction(G4ThreeVector,G4int,G4double,G4String,G4int,G4String,G4int);
~Interaction();
Interaction(const Interaction &right);
const Interaction& operator=(const Interaction &right);
G4int operator==(const Interaction &right) const;
inline void *operator new(size_t);
inline void operator delete(void *aHit);
void Draw();
void Print();
void SetIntPoint(G4ThreeVector aIntPoint);
void AddKinEnergy(G4double aKin);
inline G4ThreeVector GetIntPoint(){return theIntPoint;}
inline G4int GetParticleType(){return theParticleType;}
inline G4double GetKinEnergy(){return theKinEnergy;}
inline G4String GetDetName(){return theDetName;}
inline G4int GetDetID(){return theDetID;}
inline G4String GetIntName(){return theIntName;}
inline G4int GetIntNameID(){return theIntNameID;}
private:
G4ThreeVector theIntPoint;
G4int theParticleType;
G4double theKinEnergy;
G4String theDetName;
G4int theDetID;
G4String theIntName;
G4int theIntNameID;
};
typedef G4THitsCollection<Interaction> InteractionsCollection;
extern G4Allocator<Interaction> InteractionAllocator;
inline void* Interaction::operator new(size_t)
{
void *aHit;
aHit = (void *) InteractionAllocator.MallocSingle();
return aHit;
}
inline void Interaction::operator delete(void *aHit)
{
InteractionAllocator.FreeSingle((Interaction*) aHit);
}
#endif
| [
"luca.carfora.2@hotmail.it"
] | luca.carfora.2@hotmail.it |
dba76cc29b32ed128a05b00731a9f21df85a422f | fdd836226529a1d0098a8dd9c2014a53e645bcc9 | /rocksdb/quizup/quizup/main.cpp | cae8cd5243f317772cb7669e8156c4be98ed9fb2 | [] | no_license | hobinyoon/mutant-misc | 41520b952964421c016d973dbd6cd29356da1f25 | b6ea031b00cda723dbd20a79884ec460c8e7c5ff | refs/heads/master | 2021-01-02T23:02:51.782760 | 2018-03-09T18:03:25 | 2018-03-09T18:03:25 | 99,450,632 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | cpp | #include <csignal>
#include <cstdio>
#include <string>
#include <boost/format.hpp>
#include "conf.h"
#include "cons.h"
#include "db-client.h"
#include "simtime.h"
#include "util.h"
#include "workload-player.h"
using namespace std;
void on_signal(int sig) {
if (sig == SIGINT) {
cout << "Interrupted. Stopping workers ...\n";
WorkloadPlayer::Stop();
return;
}
cout << boost::format("\nGot a signal: %d\n%s\n") % sig % Util::Indent(Util::StackTrace(1), 2);
exit(1);
}
// Copy the DB LOG file and client log file to log archive directory, and zip them.
// Archiving logs here is easier so that we don't have to pass the simulation_time_begin to the calling script.
void ArchiveLogs() {
Cons::MT _("Archiving logs ...");
string sbt = Util::ToString(SimTime::SimulationTimeBegin());
// DB LOG
string fn_db0 = str(boost::format("%s/LOG") % Conf::GetDir("db_path"));
string dn1 = str(boost::format("%s/rocksdb") % Conf::GetDir("log_archive_dn"));
string fn_db1 = str(boost::format("%s/%s") % dn1 % sbt);
boost::filesystem::create_directories(dn1);
boost::filesystem::copy_file(fn_db0, fn_db1);
// QuizUp client log
const string& fn_c0 = ProgMon::FnClientLog();
dn1 = str(boost::format("%s/quizup") % Conf::GetDir("log_archive_dn"));
string fn_c1 = str(boost::format("%s/%s") % dn1 % sbt);
boost::filesystem::create_directories(dn1);
boost::filesystem::copy_file(fn_c0, fn_c1);
// Zip them
Util::RunSubprocess(str(boost::format("7z a -mx %s.7z %s >/dev/null 2>&1") % fn_db1 % fn_db1));
// Quizup client log will be zipped by the calling script after the configuration parameters added.
//Util::RunSubprocess(str(boost::format("7z a -mx %s.7z %s >/dev/null 2>&1") % fn_c1 % fn_c1));
}
int main(int argc, char* argv[]) {
try {
signal(SIGSEGV, on_signal);
signal(SIGINT, on_signal);
Conf::Init(argc, argv);
DbClient::Init();
WorkloadPlayer::Run();
DbClient::Cleanup();
ArchiveLogs();
} catch (const exception& e) {
cerr << "Got an exception: " << e.what() << "\n";
return 1;
}
return 0;
}
| [
"hobinyoon@gmail.com"
] | hobinyoon@gmail.com |
87bb195bbb296408ad529a00537591b8fa9ae767 | 71c1c86b30c1518e21728f7d5e0f09b5e602baac | /Algo_Engine/ROM_Handler/ExchangeServers/CBOE/CBOEDoc.h | d4ec36cc958cc33494b95dfb975e85a31f399c09 | [] | no_license | ssh352/ronin | 3ddf360fec5f106015c6902b5107aedefe934836 | 33301b6c5e68fa9d02c7d54bc86f6b7732985fc2 | refs/heads/master | 2023-05-03T11:00:39.368460 | 2021-05-17T18:41:08 | 2021-05-17T18:41:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | h | // CBOEDoc.h : interface of the CCBOEDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_CBOEDOC_H__47DDFC7A_63B3_41F6_9DE6_A6520C37E9BE__INCLUDED_)
#define AFX_CBOEDOC_H__47DDFC7A_63B3_41F6_9DE6_A6520C37E9BE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CCBOEDoc : public CDocument
{
protected: // create from serialization only
CCBOEDoc();
DECLARE_DYNCREATE(CCBOEDoc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CCBOEDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CCBOEDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CCBOEDoc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CBOEDOC_H__47DDFC7A_63B3_41F6_9DE6_A6520C37E9BE__INCLUDED_)
| [
"pflynn@sumocap.com"
] | pflynn@sumocap.com |
d4a90d1e1fedae511c8cf0bef48b1ce8bf859d54 | e2152ed7843cf742ad758d51153b66afc0271f78 | /LoopPatternAnal.h | 54735924d5b1bd8520568efa94111cedf9a20c2c | [] | no_license | corelab-src/CorelabVerilog | 3314a90a458b1423dfb77abeb0c9d76c375f9810 | e8cc64f0a895378fe3015db7e2c507d92c902417 | refs/heads/master | 2023-02-25T02:05:42.400042 | 2021-01-27T06:18:41 | 2021-01-27T06:18:41 | 333,029,961 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 14,410 | h | //Written by csKim
#ifndef LLVM_CORELAB_HLSLOOPANAL_H
#define LLVM_CORELAB_HLSLOOPANAL_H
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/ADT/DenseMap.h"
#include <set>
#include <list>
#include <vector>
#include <iostream>
#include <fstream>
#include "PABuilder.h"
namespace corelab
{
using namespace llvm;
using namespace std;
struct ElementInfo{
unsigned dataWidth;
unsigned numOfElements;
};
class MemObj
{
public:
MemObj(Value *, bool, bool, const DataLayout &);
StringRef getName(void) { return v->getName(); };
Value *getValue(void) { return v; };
bool isCallInstBased(void) { return isCallInst; };
bool isExternalValue(void) { return isExternal; };
// ---------------Get Memory Information ----------//
unsigned getNumOfElements(void) { return numOfElements; };
unsigned getDataBitSize(void) { return dataBitSize; };
unsigned getDimSize(unsigned);
unsigned getMaxDimSize(void) { return maxDim; };
private:
ElementInfo getElementInfo(Type *, const DataLayout &);
Value *v;
Type *ty;
Type *eTy;
bool isCallInst;
bool isExternal;
list<unsigned> nestArrayStructure;
//DIM : Array[4][3][2][1]
DenseMap<unsigned, unsigned> dim2Size;
unsigned maxDim;
unsigned numOfElements;
unsigned dataBitSize;
};
//Access Pattern of an Object in a Loop
class AccessPattern
{
public:
AccessPattern(const Loop *L, MemObj *memObj_) : outMostLoop(L), memObj(memObj_) {};
enum SimpleAP{
CONSTANT, ROW, COLUMN, MIXED, RANDOM, UNKNOWN
};
enum MemType{
LOAD, STORE, BOTH
};
SimpleAP getSimpleAP(void) { return simpleAP; };
MemObj *getMemObj(void) { return memObj; };
list<Instruction *> getInstList(void) { return accessInstList; };
unsigned getNestOfInst(Instruction *inst) { return inst2Nest[inst]; };
vector<pair<unsigned, unsigned>> getStridePair(Instruction *inst)
{ return inst2StridePair[inst]; };
SimpleAP getSAPOfInst(Instruction *inst)
{
if (inst2SAP.count(inst))
return inst2SAP[inst];
else
return UNKNOWN;
}
StringRef getAPName(SimpleAP sap)
{
switch(sap)
{
case ROW:
return StringRef("ROW");
case COLUMN:
return StringRef("COLUMN");
case MIXED:
return StringRef("MIXED");
case RANDOM:
return StringRef("RANDOM");
case CONSTANT:
return StringRef("CONST");
case UNKNOWN:
return StringRef("UNKNOWN");
}
}
// -------------Build Up Methods----------------//
void setSimpleAP(SimpleAP sap) { simpleAP = sap; };
void setInst2Nest(Instruction *inst, unsigned nest) { inst2Nest[inst] = nest; };
void insertAccessInstList(Instruction *inst) { accessInstList.push_back(inst); };
void setInst2StridePair(Instruction *inst, unsigned nest, unsigned stride)
{ inst2StridePair[inst].push_back(make_pair(nest,stride)); };
void setInst2SAP(Instruction *inst, SimpleAP sap) { inst2SAP[inst] = sap; };
private:
const Loop *outMostLoop;
MemObj *memObj;
SimpleAP simpleAP;
list<Instruction *> accessInstList;
DenseMap<Instruction *, unsigned> inst2Nest;
DenseMap<Instruction *, vector<pair<unsigned, unsigned>>> inst2StridePair;
DenseMap<Instruction *, SimpleAP> inst2SAP;
// DenseMap<unsigned, unsigned> nest2Stride;
// DenseMap<unsigned, MemType> nest2Type;
};
class LoopNode
{
public:
LoopNode(const Loop *L) : outMostLoop(L) {}
StringRef getName(void) { return outMostLoop->getName(); };
const Loop *getOutMostLoop(void) { return outMostLoop; };
bool getObjDetermined(void) { return determined; };
bool getStructureDetermined(void) { return Sdetermined; };
// --------------Get Memory Information----------------//
AccessPattern *getAccessPattern(MemObj *memObj) { return memObj2AP[memObj]; };
set<MemObj *> getUsedMemObjFromNest(unsigned nest) { return nest2MemObj[nest]; };
//structure fail can use
set<MemObj *> getUsedMemObjList(void) { return usedMemObjList; };
MemObj *getMemObjFromInst(Instruction *inst) { return memInst2Obj[inst]; };
set<Instruction *> getInstSet(MemObj *obj) { return obj2Inst[obj]; };
const Loop *getLoopOfInst(Instruction *inst) { return inst2Loop[inst]; };
// --------------Get Loop Information-------------------//
unsigned getMaxNestLevel(void) { return maxNestLevel; };
const Loop *getLoopFromNest(unsigned nestLevel) { return nest2Loop[nestLevel]; };
unsigned getNestFromLoop(const Loop *loop)
{
for ( auto mapIter : nest2Loop )
{
if (mapIter.second == loop)
return mapIter.first;
}
return 0;
}
unsigned getNestFromIndV(PHINode *indV) { return indV2Nest[indV]; };
unsigned getIterCount(unsigned nestLevel) { return nest2Iter[nestLevel]; };
list<Instruction *> getFailList(void) { return failedList; };
// --------------Build Up Methods---------------//
void setObjDetermined(bool dm) { determined = dm; };
void setStructureDetermined(bool sdm) { Sdetermined = sdm; };
void insertMemObj(MemObj *memObj) { usedMemObjList.insert(memObj); };
void insertMemObjAP(MemObj *memObj, AccessPattern *AP) { memObj2AP[memObj] = AP; };
void setNestMemObj(unsigned nest, MemObj *memObj) { nest2MemObj[nest].insert(memObj); };
void setMaxNestLevel(unsigned mnl) { maxNestLevel = mnl; };
void setIndV2Nest(PHINode *indV, unsigned nest) { indV2Nest[indV] = nest; };
void setLoopFromNest(unsigned nestLevel, const Loop *tL) { nest2Loop[nestLevel] = tL; };
void setIterCount(unsigned nestLevel, unsigned iterCount)
{ nest2Iter[nestLevel] = iterCount; };
void setMemInst2MemObj(Instruction *inst, MemObj *memObj) { memInst2Obj[inst] = memObj; };
void setObj2Inst(MemObj *obj, Instruction *inst) { obj2Inst[obj].insert(inst); };
void setInst2Loop(Instruction *inst, const Loop *lp) { inst2Loop[inst] = lp; };
void setFailInst(Instruction *inst) { failedList.push_back(inst); };
private:
const Loop *outMostLoop;
bool determined;
bool Sdetermined;
set<MemObj *> usedMemObjList;
DenseMap<MemObj *, AccessPattern *> memObj2AP;
DenseMap<unsigned, set<MemObj *>> nest2MemObj;
DenseMap<PHINode *, unsigned> indV2Nest;
DenseMap<Instruction *, MemObj *> memInst2Obj;
DenseMap<MemObj *, set<Instruction *>> obj2Inst;
DenseMap<Instruction *, const Loop *> inst2Loop;
unsigned maxNestLevel;
DenseMap<unsigned, const Loop *> nest2Loop;
// DenseMap<const Loop *,unsigned> loop2Nest;
DenseMap<unsigned, unsigned> nest2Iter;
list<Instruction *> failedList;
};
class LoopAliasInfo
{
public:
LoopAliasInfo(const Loop *L, list<BasicBlock *> bb, list<Instruction *> exitList_) :
targetL(L), targetBB(bb), exitList(exitList_), variousDist(false) {}
struct AccessInfo{
Value *value;
bool store;
bool array;
bool constant;
list<Instruction *> operationList;
//TODO : the location of constant access
} AccessInfo_;
enum LoopType{
NORMAL, EDGE, PREHEADER
};
enum DepType{
Intra, Inter, Constant
};
struct AliasInfo{
DepType type;
int distance;
} AliasInfo_;
// --------- Usage -----------
const Loop *getLoop(void) { return targetL; };
list<BasicBlock *> getBB(void) { return targetBB; };
list<Instruction *> getExitList(void) { return exitList; };
bool isForExitInst(Instruction *inst) {
for ( auto iter : exitList )
if ( iter == inst )
return true;
return false;
}
PHINode *getIndPHINode(void) { return indNode; };
list<Instruction *> getInterDefList(Instruction *inst) { return interDefList[inst]; };
list<Instruction *> getInterUseList(Instruction *inst) { return interUseList[inst]; };
bool getObjDetermined(void) { return objDetermined; };
AccessInfo getAccessInfo(Instruction *inst) { return inst2AInfo[inst]; };
list<pair<Instruction *, AliasInfo>> getUseAliasList(Instruction *inst) {
return memUseMap[inst];
}
list<pair<Instruction *, AliasInfo>> getDefAliasList(Instruction *inst) {
return memDefMap[inst];
}
bool isVariousDist(void) { return variousDist; };
LoopType getLoopType(void) { return lt; };
// --------- Build -----------
void setIndPHINode(PHINode *ind) { indNode = ind; };
void setInterDefList(Instruction *use, Instruction *def)
{ interDefList[use].push_back(def); };
void setInterUseList(Instruction *use, Instruction *def)
{ interUseList[def].push_back(use); };
void setObjDetermined(bool dd) { objDetermined = dd; };
void setInst2AInfo(Instruction *inst, AccessInfo ai) { inst2AInfo[inst] = ai; };
AccessInfo genAInfo(Value *v, bool st, bool arr,
bool constant, list<Instruction *> &operList) {
AccessInfo ai;
ai.value = v;
ai.store = st;
ai.array = arr;
ai.constant = constant;
ai.operationList = operList;
return ai;
}
void setUseAliasInfo(Instruction *use, Instruction *key,
DepType dt, int dist) {
AliasInfo ai;
ai.type = dt;
ai.distance = dist;
memUseMap[key].push_back(make_pair(use, ai));
}
void setDefAliasInfo(Instruction *def, Instruction *key,
DepType dt, int dist) {
AliasInfo ai;
ai.type = dt;
ai.distance = dist;
memDefMap[key].push_back(make_pair(def, ai));
}
void setVariousDist(void) { variousDist = true; };
void setLoopType(LoopType lt_) { lt = lt_; };
private:
const Loop *targetL;
list<BasicBlock *> targetBB;
list<Instruction *> exitList;
PHINode *indNode;
LoopType lt;
bool objDetermined;
bool variousDist;
DenseMap<Instruction *, list<Instruction *>> interUseList;
DenseMap<Instruction *, list<Instruction *>> interDefList;
DenseMap<Instruction *, AccessInfo> inst2AInfo;
// Write Instruction -> set of instruction that alias the address after write
DenseMap<Instruction *, list<pair<Instruction *, AliasInfo>>> memUseMap;
// Read Instruction -> set of write instruction that alias the address after read
DenseMap<Instruction *, list<pair<Instruction *, AliasInfo>>> memDefMap;
};
class LoopPatternAnal : public ModulePass
{
public:
static char ID;
LoopPatternAnal() : ModulePass(ID) {};
virtual void getAnalysisUsage( AnalysisUsage &AU ) const;
StringRef getPassName() const { return "Loop Pattern Analysis"; };
bool runOnModule(Module& M);
void analysisOnLoop(const Loop *L);
LoopAliasInfo *collectAliasInfo(const Loop *L, list<BasicBlock *> &,
list<Instruction *> &);
LoopPatternAnal *getLPA(void) { return this; };
// --------- Usage -----------
list<MemObj *> getMemObjList(void) { return memObjList; };
MemObj *getMemObjFromValue(Value *v) { return v2MemObj[v]; };
list<LoopNode *> getLoopNodeList(void) { return loopNodeList; };
LoopNode *getLoopNodeFromLoop(const Loop *l)
{
for ( auto LNIter : loopNodeList )
{
if (LNIter->getOutMostLoop() == l)
return LNIter;
}
return NULL;
}
LoopAliasInfo *getLoopAFromLoop(const Loop *l)
{
for ( auto LAIter : loopAList )
{
if (LAIter->getLoop() == l)
return LAIter;
}
return NULL;
}
bool isBBForPipeline(BasicBlock *bb) {
if ( bb2Pipeline.count(bb) )
return bb2Pipeline[bb];
else
return false;
}
LoopAliasInfo *getLoopAFromBB(BasicBlock *bb) {
for ( auto LAIter : loopAList )
for ( auto bi : LAIter->getBB() )
if ( bi == bb )
return LAIter;
return NULL;
}
set<LoopNode> getLNListOfMemObj(MemObj *mem) { return memObj2LoopNode[mem]; };
// --------- Memory Object -----------
void searchGV();
void searchAlloca();
void searchAllocaCall();
// --------- Build LoopNode -----------
void setLNList(LoopNode *LN) { loopNodeList.push_back(LN); };
void setLAList(LoopAliasInfo *LA) { loopAList.push_back(LA); };
// void setL2LN(const Loop *l, LoopNode *LN) { loop2LoopNode[l] = LN; };
PHINode *getCanonicalInductionVariableAux(const Loop*);
PHINode *getCanonicalInductionVariableAuxForAlias(const Loop*);
bool setLoopStructure(LoopNode *);
void collectUsedObjects(const Loop *, unsigned, LoopNode *);
MemObj *traceUsedObject(Value *, unsigned);
list<Instruction *> getCallInstList(Function *);
bool simpleLoopCheck(const Loop *, unsigned *);
void collectLoopPattern(LoopNode *);
bool collectIndStride(DenseMap<PHINode *, unsigned> &,
GetElementPtrInst *, MemObj *);
std::pair<PHINode*, unsigned> getStride(Value *);
unsigned getStrideSizeFromArray(MemObj *, unsigned);
bool isUniqueBB(const Loop *, const BasicBlock *);
unsigned getIterationCount(const Loop *);
BasicBlock *getOutsideExitBlock(const Loop *);
bool collectIndOperation(LoopAliasInfo *, Instruction *,
list<Instruction *>&, GetElementPtrInst *, PHINode *);
int getRefIndex(list<Instruction *> &, int);
//Alias for Pipelining
const Loop *getInnerMostLoop(const Loop *);
list<BasicBlock *> getOnlyOneBB(const Loop *);
void setBBForPipeline(list<BasicBlock *> bb) {
for ( auto bi : bb )
bb2Pipeline[bi] = true;
}
list<Instruction *> getExitList(list<BasicBlock *> &);
bool collectCMPOperation(list<Instruction *>&, list<BasicBlock *> &, Instruction *);
// --------- print -----------
void printLoopPattern(const Loop *, raw_fd_ostream &);
void printAllInfo(raw_fd_ostream &);
void printMemoryObject(raw_fd_ostream &);
void printAliasInfo(raw_fd_ostream &);
void printRegDependence(raw_fd_ostream &, LoopAliasInfo *);
void printMemDependence(raw_fd_ostream &, LoopAliasInfo *);
private:
Module *module;
// LoopAA *loopaa;
LoopInfo *li;
PADriver *pa;
DenseMap<Function *, Instruction *> fcn2CallInst;
// ---------- Memory Object -----------
list<MemObj *> memObjList;
DenseMap<Value *, MemObj *> v2MemObj;
// ---------- Loop Node --------------
list<LoopNode *> loopNodeList;
list<LoopAliasInfo *> loopAList;
// DenseMap<const Loop *, LoopNode *> loop2LoopNode;
DenseMap<MemObj *, set< LoopNode >> memObj2LoopNode;
DenseMap<const Function *, LoopInfo *> loopInfoOf;
DenseMap<BasicBlock *, bool> bb2Pipeline;
};
}
#endif
| [
"changsu@corelab.or.kr"
] | changsu@corelab.or.kr |
49a00e5743d06e234cf8e24d664d400a6b9d815e | d514636c43099f00a264da7846fcee5842468429 | /Labs/AI/TicTacToe/src/TicTacToeAIPlayerRandom.hpp | 9ec9f0887e0bb12209a7fb4cc34ccb7cd58dffc5 | [
"MIT"
] | permissive | jadnohra/jad-pre-2015-dabblings | 92de27c6184a255dfdb4ed9ee2148d4bf71ced1e | 368cbd39c6371b3e48b0c67d9a83fc20eee41346 | refs/heads/master | 2021-07-22T20:07:18.651650 | 2017-11-03T11:31:18 | 2017-11-03T11:31:18 | 109,386,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 668 | hpp | #include "TicTacToeGame.hpp"
namespace tictactoe {
/*
* Random AI, useful for testing
*/
class PlayerAIRandom : public Player {
public:
virtual void playTurn(TicTacToeGame& game) {
int targetIndex = game.getRandom(0, game.gridWidth() * game.gridHeight() * 2);
int currIndex = 0;
while (true) {
for (CellIndex i = 0; i < game.gridWidth(); ++i) {
for (CellIndex j = 0; j < game.gridHeight(); ++j) {
if (game.getCell(i, j).isEmpty()) {
if (currIndex == targetIndex) {
game.tickCell(i, j);
return;
}
++currIndex;
}
}
}
}
}
};
}
| [
"pinkfish@e0e46c49-be69-4f5a-ad62-21024a331aea"
] | pinkfish@e0e46c49-be69-4f5a-ad62-21024a331aea |
73aa267b2d7d06667226e0f0256f88a432deeb20 | ec53a36ccdf7128ce4249a4f9f4359a8c390b4ff | /algorithms/hanoi-game/hanoi.hpp | 848baa9c504796924a585faa1096e5f042e318c1 | [] | no_license | jdbr99/web-cv-flab | c73bb7b72073eee9aef99d6ec6fa765baae49d68 | b4796ffd6ead59c4533801598ee959c56797b9f1 | refs/heads/master | 2021-06-27T12:08:39.236631 | 2020-01-16T02:20:55 | 2020-01-16T02:20:55 | 222,038,308 | 1 | 1 | null | 2021-03-20T02:30:31 | 2019-11-16T02:57:45 | JavaScript | UTF-8 | C++ | false | false | 164 | hpp | #include "stack.hpp"
class Hanoi {
private:
Stack tower[3];
public:
Hanoi(int discs);
~Hanoi();
bool move(int from, int to);
void print();
bool isOver();
};
| [
"jdbr@localhost.localdomain"
] | jdbr@localhost.localdomain |
de2e00e42e0c3c8b3dfb03efdfeec21268af3ffa | d52f97fe5fde17e354491b7f111f3eb6f8834f2a | /ArbetsprovFPS2 4.22/Intermediate/Build/Win64/UE4Editor/Inc/ArbetsprovFPS2/SpawnVolume.generated.h | 9165e1d3827adec0b1c6692262f042eecfcc405f | [] | no_license | AgilityLars/ArbetsprovDoubleMoose | 4642331f80bc3d35c73766c37c2d64381ec721c6 | e82986a1aba0159319d7b8c6cda0e2f90c8b8f90 | refs/heads/master | 2022-02-09T02:28:16.414734 | 2019-08-05T09:24:00 | 2019-08-05T09:24:00 | 200,561,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,798 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
struct FVector;
#ifdef ARBETSPROVFPS2_SpawnVolume_generated_h
#error "SpawnVolume.generated.h already included, missing '#pragma once' in SpawnVolume.h"
#endif
#define ARBETSPROVFPS2_SpawnVolume_generated_h
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_RPC_WRAPPERS \
\
DECLARE_FUNCTION(execGetRandomPointInVolume) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(FVector*)Z_Param__Result=P_THIS->GetRandomPointInVolume(); \
P_NATIVE_END; \
}
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_RPC_WRAPPERS_NO_PURE_DECLS \
\
DECLARE_FUNCTION(execGetRandomPointInVolume) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(FVector*)Z_Param__Result=P_THIS->GetRandomPointInVolume(); \
P_NATIVE_END; \
}
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesASpawnVolume(); \
friend struct Z_Construct_UClass_ASpawnVolume_Statics; \
public: \
DECLARE_CLASS(ASpawnVolume, AActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/ArbetsprovFPS2"), NO_API) \
DECLARE_SERIALIZER(ASpawnVolume)
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_INCLASS \
private: \
static void StaticRegisterNativesASpawnVolume(); \
friend struct Z_Construct_UClass_ASpawnVolume_Statics; \
public: \
DECLARE_CLASS(ASpawnVolume, AActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/ArbetsprovFPS2"), NO_API) \
DECLARE_SERIALIZER(ASpawnVolume)
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API ASpawnVolume(const FObjectInitializer& ObjectInitializer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ASpawnVolume) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ASpawnVolume); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASpawnVolume); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ASpawnVolume(ASpawnVolume&&); \
NO_API ASpawnVolume(const ASpawnVolume&); \
public:
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ASpawnVolume(ASpawnVolume&&); \
NO_API ASpawnVolume(const ASpawnVolume&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ASpawnVolume); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASpawnVolume); \
DEFINE_DEFAULT_CONSTRUCTOR_CALL(ASpawnVolume)
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_PRIVATE_PROPERTY_OFFSET \
FORCEINLINE static uint32 __PPO__WhatToSpawn() { return STRUCT_OFFSET(ASpawnVolume, WhatToSpawn); } \
FORCEINLINE static uint32 __PPO__SpawnDelayRangeLow() { return STRUCT_OFFSET(ASpawnVolume, SpawnDelayRangeLow); } \
FORCEINLINE static uint32 __PPO__SpawnDelayRangeHigh() { return STRUCT_OFFSET(ASpawnVolume, SpawnDelayRangeHigh); } \
FORCEINLINE static uint32 __PPO__WhereToSpawn() { return STRUCT_OFFSET(ASpawnVolume, WhereToSpawn); }
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_9_PROLOG
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_PRIVATE_PROPERTY_OFFSET \
ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_RPC_WRAPPERS \
ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_INCLASS \
ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_PRIVATE_PROPERTY_OFFSET \
ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_RPC_WRAPPERS_NO_PURE_DECLS \
ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_INCLASS_NO_PURE_DECLS \
ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h_12_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> ARBETSPROVFPS2_API UClass* StaticClass<class ASpawnVolume>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID ArbetsprovFPS2_4_22_Source_ArbetsprovFPS2_SpawnVolume_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"southparkourify@gmail.com"
] | southparkourify@gmail.com |
d8f33360c5a4cc9272edb48e5386ad0bd75f08eb | a7606c8002a84aa5e7cce9b0446b242386316b82 | /shapes/primitives/axisalignedbox.cpp | 0548075c02d15da48bf6e22d28ea1ea0f8a80812 | [] | no_license | cache-tlb/rt-from-the-ground-up | 5fdcfadccb686c65a6be43c6e165786471e8a4a1 | 2784799e5124bc8bc09e673d65e5b8bf8f149758 | refs/heads/master | 2016-09-11T09:37:44.312899 | 2012-10-12T16:04:36 | 2012-10-12T16:04:36 | 32,261,877 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,681 | cpp | #include "axisalignedbox.h"
#include "maths.h"
AxisAlignedBox::AxisAlignedBox(void)
: x0(0),x1(1),
y0(0),y1(1),
z0(0),z1(1)
{}
AxisAlignedBox::AxisAlignedBox(const Vector3D &p1, const Vector3D &p2)
: x0(min(p1.x,p2.x)), x1(max(p1.x,p2.x)),
y0(min(p1.y,p2.y)), y1(max(p1.y,p2.y)),
z0(min(p1.z,p2.z)), z1(max(p1.z,p2.z))
{}
AxisAlignedBox::AxisAlignedBox(const AxisAlignedBox &a)
: x0(a.x0), x1(a.x1),
y0(a.y0), y1(a.y1),
z0(a.z0), z1(a.z1)
{}
AxisAlignedBox*
AxisAlignedBox::clone(void) const
{
return (new AxisAlignedBox(*this));
}
// ------ assignment operator
AxisAlignedBox&
AxisAlignedBox::operator= (const AxisAlignedBox& rhs)
{
if (this == &rhs){
return (*this);
}
Shape::operator= (rhs);
x0 = rhs.x0; x1 = rhs.x1;
y0 = rhs.y0; y1 = rhs.y1;
z0 = rhs.z0; z1 = rhs.z1;
return (*this) ;
}
AxisAlignedBox::~AxisAlignedBox() {}
BBox
AxisAlignedBox::get_bounding_box(void) {
return BBox(x0,x1,y0,y1,z0,z1);
}
bool
AxisAlignedBox::hit(const Ray &ray, double &tmin, ShadeRec &sr) const
{
double ox = ray.o.x; double oy = ray.o.y; double oz = ray.o.z;
double dx = ray.d.x; double dy = ray.d.y; double dz = ray.d.z;
double tx_min, ty_min, tz_min;
double tx_max, ty_max, tz_max;
double a = 1.0 / dx;
if (a >= 0) {
tx_min = (x0 - ox) * a;
tx_max = (x1 - ox) * a;
}
else {
tx_min = (x1 - ox) * a;
tx_max = (x0 - ox) * a;
}
double b = 1.0 / dy;
if (b >= 0) {
ty_min = (y0 - oy) * b;
ty_max = (y1 - oy) * b;
}
else {
ty_min = (y1 - oy) * b;
ty_max = (y0 - oy) * b;
}
double c = 1.0 / dz;
if (c >= 0) {
tz_min = (z0 - oz) * c;
tz_max = (z1 - oz) * c;
}
else {
tz_min = (z1 - oz) * c;
tz_max = (z0 - oz) * c;
}
double t0, t1;
// find largest entering t value
if (tx_min > ty_min){
t0 = tx_min;
}
else{
t0 = ty_min;
}
if (tz_min > t0){
t0 = tz_min;
}
// find smallest exiting t value
if (tx_max < ty_max){
t1 = tx_max;
}
else{
t1 = ty_max;
}
if (tz_max < t1){
t1 = tz_max;
}
// t0 is max(tx_min,ty_min,tz_min)
// t1 is min(tx_max,ty_max,tz_max)
// normal is all point opposite ray.d
if(t0 < t1 && t1 > kEpsilon) {
if(t0 > kEpsilon){
// ray.o is outside the box
tmin = t0;
if(t0 == tx_min){
if(dx < 0)
sr.normal = Normal(1,0,0);
else
sr.normal = Normal(-1,0,0);
}
else if(t0 == ty_min){
if(dy < 0)
sr.normal = Normal(0,1,0);
else
sr.normal = Normal(0,-1,0);
}
else{
if(dz < 0)
sr.normal = Normal(0,0,1);
else
sr.normal = Normal(0,0,-1);
}
}
else{
// ray.o is inside the box
tmin = t1;
if(t1 == tx_max){
if(dx < 0)
sr.normal = Normal(-1,0,0);
else
sr.normal = Normal(1,0,0);
}
else if(t1 == ty_max){
if(dy < 0)
sr.normal = Normal(0,-1,0);
else
sr.normal = Normal(0,1,0);
}
else{
if(dz < 0)
sr.normal = Normal(0,0,-1);
else
sr.normal = Normal(0,0,1);
}
}
sr.local_hit_point = ray.o + tmin * ray.d;
return true;
}
else{
return false;
}
}
bool
AxisAlignedBox::shadow_hit(const Ray &ray, float &tmin) const
{
double ox = ray.o.x; double oy = ray.o.y; double oz = ray.o.z;
double dx = ray.d.x; double dy = ray.d.y; double dz = ray.d.z;
double tx_min, ty_min, tz_min;
double tx_max, ty_max, tz_max;
double a = 1.0 / dx;
if (a >= 0) {
tx_min = (x0 - ox) * a;
tx_max = (x1 - ox) * a;
}
else {
tx_min = (x1 - ox) * a;
tx_max = (x0 - ox) * a;
}
double b = 1.0 / dy;
if (b >= 0) {
ty_min = (y0 - oy) * b;
ty_max = (y1 - oy) * b;
}
else {
ty_min = (y1 - oy) * b;
ty_max = (y0 - oy) * b;
}
double c = 1.0 / dz;
if (c >= 0) {
tz_min = (z0 - oz) * c;
tz_max = (z1 - oz) * c;
}
else {
tz_min = (z1 - oz) * c;
tz_max = (z0 - oz) * c;
}
double t0, t1;
// find largest entering t value
if (tx_min > ty_min){
t0 = tx_min;
}
else{
t0 = ty_min;
}
if (tz_min > t0){
t0 = tz_min;
}
// find smallest exiting t value
if (tx_max < ty_max){
t1 = tx_max;
}
else{
t1 = ty_max;
}
if (tz_max < t1){
t1 = tz_max;
}
// t0 is max(tx_min,ty_min,tz_min)
// t1 is min(tx_max,ty_max,tz_max)
if(t0 < t1 && t1 > kEpsilon) {
if(t0 > kEpsilon){ // ray.o is outside the box
tmin = t0;
}
else{ // ray.o is inside the box
tmin = t1;
}
return true;
}
else{
return false;
}
}
| [
"liub91@gmail.com@66790ea4-9dcb-8dae-10e5-9860326c6d77"
] | liub91@gmail.com@66790ea4-9dcb-8dae-10e5-9860326c6d77 |
309c39a031c701f31c37a10b19a4d2d9e9ad7f0f | 8ae31e5db1f7c25b6ce1c708655ab55c15dde14e | /比赛/学校/2019-9-17测试/source/PC11_LCX/mst.cpp | 5c23fa6fadb458a58a5a548545f9ee8ec1ab3de9 | [] | no_license | LeverImmy/Codes | 99786afd826ae786b5024a3a73c8f92af09aae5d | ca28e61f55977e5b45d6731bc993c66e09f716a3 | refs/heads/master | 2020-09-03T13:00:29.025752 | 2019-12-16T12:11:23 | 2019-12-16T12:11:23 | 219,466,644 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | #include<bits/stdc++.h>
#define int long long
using namespace std;
inline int read() {
int x = 0, f = 1;
char c = getchar();
while(!isdigit(c)) {
if(c == '-') {
f = -1;
}
c = getchar();
}
while(isdigit(c)) {
x = x * 10 + c - '0';
c = getchar();
}
return x * f;
}
struct node {
int x, y, a, b;
} c[1000001];
int f[1000001];
inline bool cmp(node x, node y) {
if(x.a * y.b != x.b * y.a) {
return x.a * y.b < x.b * y.a;
} else if(x.b != y.b) {
return x.b > y.b;
}
return x.a < y.a;
}
inline int fa(int x) {
if(f[x] != x) {
f[x] = fa(f[x]);
}
return f[x];
}
signed main() {
freopen("mst.in", "r", stdin);
freopen("mst.out", "w", stdout);
int n = read(), m = read();
for(int i = 1; i <= m; i++) {
int x = read(), y = read(), aa = read(), bb = read();
node t1;
t1.y = y, t1.x = x, t1.a = aa, t1.b = bb;
c[i] = t1;
}
for(int i = 1; i <= n; i++) {
f[i] = i;
}
sort(c + 1, c + 1 + m, cmp);
double ansa = 0, ansb = 0;
int j = 0;
for(int i = 1; i <= m; i++) {
int q1 = fa(c[i].x);
int q2 = fa(c[i].y);
if(q1 != q2) {
f[q1] = q2, ansa += c[i].a, ansb += c[i].b;
j++;
}
if(j == n - 1) {
break;
}
}
printf("%.6f\n", ansa / ansb);
return 0;
}
| [
"506503360@qq.com"
] | 506503360@qq.com |
4af004f11564b61389b5c20f202a738465127243 | 7abfb608f9a560d4f504f51d94192836489e0aac | /src/Entity/EntityUnitTests.cpp | e4882f9cef202ff4203386827cf50f7b71f5f382 | [] | no_license | kladarak/Sunspear | d284f0a4a5ac6dcaf6fcffe17e1dfb1b9de24acf | bdc3a362d7003a30fdd80db76cbeea0e3226abd5 | refs/heads/master | 2020-06-26T23:18:52.428652 | 2017-07-15T15:33:34 | 2017-07-15T15:33:34 | 97,035,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | #include <stdafx.h>
#include <assert.h>
#include "Entity.h"
namespace Sunspear
{
namespace
{
class ComponentA : public IComponent
{
DECLARE_RTTI(ComponentA, IComponent)
};
class ComponentB : public IComponent
{
DECLARE_RTTI(ComponentB, IComponent)
};
class ComponentC : public ComponentA
{
DECLARE_RTTI(ComponentC, ComponentA)
};
}
void DoEntityUnitTests()
{
Entity e;
auto& a = e.CreateComponent<ComponentA>();
auto& b = e.CreateComponent<ComponentB>();
auto& c = e.CreateComponent<ComponentC>();
// Note, C is an A, but due to order of
// insertion, A is found first when looking for A
// rather than finding C (which also matches)
assert(e.FindComponent<ComponentA>() == &a);
assert(e.FindComponent<ComponentB>() == &b);
assert(e.FindComponent<ComponentC>() == &c);
}
}
| [
"scottjenkins88@gmail.com"
] | scottjenkins88@gmail.com |
3451db9c77f914509388b1aa93dc3aca7d8dcc60 | 70b2f8731dc39bd02eed6fde857d5d59fe7ce4bf | /src/test/limitedmap_tests.cpp | 4b15374d39ef1fa6c78798181acdf65e0636eabb | [
"MIT"
] | permissive | RegulusBit/coinium | a441b6d77d25ec7124b0ee0ebcb226fc9ef6ae2f | 13472e0f83c469ca83c2d1023e7308032de5f514 | refs/heads/master | 2020-03-19T20:39:32.745303 | 2018-06-11T11:35:18 | 2018-06-11T11:35:18 | 136,910,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,710 | cpp | // Copyright (c) 2012-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 "limitedmap.h"
#include "test/test_coinium.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(limitedmap_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(limitedmap_test)
{
// create a limitedmap capped at 10 items
limitedmap<int, int> map(10);
// check that the max size is 10
BOOST_CHECK(map.max_size() == 10);
// check that it's empty
BOOST_CHECK(map.size() == 0);
// insert (-1, -1)
map.insert(std::pair<int, int>(-1, -1));
// make sure that the size is updated
BOOST_CHECK(map.size() == 1);
// make sure that the new items is in the map
BOOST_CHECK(map.count(-1) == 1);
// insert 10 new items
for (int i = 0; i < 10; i++) {
map.insert(std::pair<int, int>(i, i + 1));
}
// make sure that the map now contains 10 items...
BOOST_CHECK(map.size() == 10);
// ...and that the first item has been discarded
BOOST_CHECK(map.count(-1) == 0);
// iterate over the map, both with an index and an iterator
limitedmap<int, int>::const_iterator it = map.begin();
for (int i = 0; i < 10; i++) {
// make sure the item is present
BOOST_CHECK(map.count(i) == 1);
// use the iterator to check for the expected key adn value
BOOST_CHECK(it->first == i);
BOOST_CHECK(it->second == i + 1);
// use find to check for the value
BOOST_CHECK(map.find(i)->second == i + 1);
// update and recheck
map.update(it, i + 2);
BOOST_CHECK(map.find(i)->second == i + 2);
it++;
}
// check that we've exhausted the iterator
BOOST_CHECK(it == map.end());
// resize the map to 5 items
map.max_size(5);
// check that the max size and size are now 5
BOOST_CHECK(map.max_size() == 5);
BOOST_CHECK(map.size() == 5);
// check that items less than 5 have been discarded
// and items greater than 5 are retained
for (int i = 0; i < 10; i++) {
if (i < 5) {
BOOST_CHECK(map.count(i) == 0);
} else {
BOOST_CHECK(map.count(i) == 1);
}
}
// erase some items not in the map
for (int i = 100; i < 1000; i += 100) {
map.erase(i);
}
// check that the size is unaffected
BOOST_CHECK(map.size() == 5);
// erase the remaining elements
for (int i = 5; i < 10; i++) {
map.erase(i);
}
// check that the map is now empty
BOOST_CHECK(map.empty());
}
BOOST_AUTO_TEST_SUITE_END()
| [
"icdct1995@gmail.com"
] | icdct1995@gmail.com |
25f295f9c7bf1cee46d50d41a3e6475d8afd4b4b | e3ab0fbb14d408eddc90db3a7a9b96562317b41f | /src/A-Protect/SnifferSetting.h | f5e96e35fdd5e0d715f896b078ed43495b1fc1a8 | [] | no_license | jilvan1234/A-Protect | 30ca67687fece8e6bc9da7e882172b8c733c107a | a498141c9e156846f6a0c153715cc90294e33977 | refs/heads/master | 2022-02-22T14:08:06.913558 | 2019-10-27T04:52:40 | 2019-10-27T04:52:40 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 446 | h | #pragma once
// CSnifferSetting 对话框
class CSnifferSetting : public CDialogEx
{
DECLARE_DYNAMIC(CSnifferSetting)
public:
CSnifferSetting(CWnd* pParent = NULL); // 标准构造函数
virtual ~CSnifferSetting();
// 对话框数据
enum { IDD = IDD_DLG_SNIFFERSETTING };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
CString m_strData;
CString m_strDataDescription;
};
| [
"xiaoqiang23"
] | xiaoqiang23 |
2cae8bc41c5fdc3bbea3034b882a2b0347762d2e | e0b2d73f29ea6973e69d4e710c7d7fb30d7d3d39 | /trunk/winvnc/winvnc/.svn/text-base/vsocket.h.svn-base | 634892eeb5e62113f546d3445b839f8ed0bfd994 | [] | no_license | runsoftcorp/runremote | 8bbf33f2b448c297280c531c5875bf16db5496b5 | a8e76746d7b22605d6c4c8747dae81ccf0d2eef1 | refs/heads/master | 2020-06-05T16:33:27.153131 | 2015-05-13T07:59:25 | 2015-05-13T07:59:25 | 25,139,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,348 | // Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
// Copyright (C) 2001 HorizonLive.com, Inc. All Rights Reserved.
//
// This file is part of the VNC system.
//
// The VNC system 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// If the source code for the VNC system is not available from the place
// whence you received this file, check http://www.uk.research.att.com/vnc or contact
// the authors on vnc@uk.research.att.com for information on obtaining it.
// VSocket.h
// RFB V3.0
// The VSocket class provides simple socket functionality,
// independent of platform. Hurrah.
//#define FLOWCONTROL
class VSocket;
#if (!defined(_ATT_VSOCKET_DEFINED))
#define _ATT_VSOCKET_DEFINED
#include "vtypes.h"
#include <DSMPlugin/DSMPlugin.h>
////////////////////////////
#include <Iphlpapi.h>
extern "C" {
typedef ULONG (WINAPI *t_GetPerTcpConnectionEStats)(
PMIB_TCPROW Row, TCP_ESTATS_TYPE EstatsType,
PUCHAR Rw, ULONG RwVersion, ULONG RwSize,
PUCHAR Ros, ULONG RosVersion, ULONG RosSize,
PUCHAR Rod, ULONG RodVersion, ULONG RodSize);
typedef ULONG (WINAPI *t_SetPerTcpConnectionEStats)(
PMIB_TCPROW Row, TCP_ESTATS_TYPE EstatsType,
PUCHAR Rw, ULONG RwVersion, ULONG RwSize,
ULONG Offset);
}
// Socket implementation
// Create one or more VSocketSystem objects per application
class VSocketSystem
{
public:
VSocketSystem();
~VSocketSystem();
VBool Initialised() {return m_status;};
private:
VBool m_status;
};
// The main socket class
class VSocket
{
public:
// Constructor/Destructor
VSocket();
virtual ~VSocket();
////////////////////////////
// Socket implementation
// Create
// Create a socket and attach it to this VSocket object
VBool Create();
// Shutdown
// Shutdown the currently attached socket
VBool Shutdown();
// Close
// Close the currently attached socket
VBool Close();
// Bind
// Bind the attached socket to the specified port
// If localOnly is VTrue then the socket is bound only
// to the loopback adapter.
VBool Bind(const VCard port, const VBool localOnly=VFalse);
// Connect
// Make a stream socket connection to the specified port
// on the named machine.
VBool Connect(const VString address, const VCard port);
// Listen
// Set the attached socket to listen for connections
VBool Listen();
// Accept
// If the attached socket is set to listen then this
// call blocks waiting for an incoming connection, then
// returns a new socket object for the new connection
VSocket *Accept();
// GetPeerName
// If the socket is connected then this returns the name
// of the machine to which it is connected.
// This string MUST be copied before the next socket call...
VString GetPeerName();
// GetSockName
// If the socket exists then the name of the local machine
// is returned. This string MUST be copied before the next
// socket call!
VString GetSockName();
// Resolve
// Uses the Winsock API to resolve the supplied DNS name to
// an IP address and returns it as an Int32
static VCard32 Resolve(const VString name);
// SetTimeout
// Sets the socket timeout on reads and writes.
VBool SetTimeout(VCard32 msecs);
VBool SetSendTimeout(VCard32 msecs);
VBool SetRecvTimeout(VCard32 msecs);
// adzm 2010-08
VBool SetDefaultSocketOptions();
// adzm 2010-08
static void SetSocketKeepAliveTimeoutDefault(int timeout) { m_defaultSocketKeepAliveTimeout = timeout; }
bool GetPeerAddress(char *address, int size);
VBool Http_CreateConnect(const VString address);
SOCKET GetChannel() const { return (SOCKET) sock; }
// I/O routines
#ifdef HTTP_SAMEPORT
// Check to see if the socket becomes readable within <to> msec.
// Added to support HTTP-via-RFB.
VBool ReadSelect(VCard to);
#endif
// Send and Read return the number of bytes sent or recieved.
VInt Send(const char *buff, const VCard bufflen);
VInt SendQueued(const char *buff, const VCard bufflen);
VInt Read(char *buff, const VCard bufflen);
// SendExact and ReadExact attempt to send and recieve exactly
// the specified number of bytes.
VBool SendExact(const char *buff, const VCard bufflen);
VBool SendExact(const char *buff, const VCard bufflen, unsigned char msgType); // sf@2002 - DSMPlugin
VBool SendExactQueue(const char *buff, const VCard bufflen);
//adzm 2010-09 - minimize packets. SendExact flushes the queue.
VBool SendExactQueue(const char *buff, const VCard bufflen, unsigned char msgType);
VBool ReadExact(char *buff, const VCard bufflen);
VBool ClearQueue();
// sf@2002 - DSMPlugin
//adzm 2009-06-20
void SetDSMPluginPointer(CDSMPlugin* pDSMPlugin);
void EnableUsePlugin(bool fEnable) { m_fUsePlugin = fEnable;};
bool IsUsePluginEnabled(void) { return m_fUsePlugin;};
//adzm 2010-05-12 - dsmplugin config
void SetDSMPluginConfig(char* szDSMPluginConfig);
// adzm 2010-09
void SetPluginStreamingIn() { m_fPluginStreamingIn = true; }
void SetPluginStreamingOut() { m_fPluginStreamingOut = true; }
bool IsPluginStreamingIn(void) { return m_fPluginStreamingIn; }
bool IsPluginStreamingOut(void) { return m_fPluginStreamingOut; }
void SetWriteToNetRectBuffer(bool fEnable) {m_fWriteToNetRectBuf = fEnable;};
bool GetWriteToNetRectBuffer(void) {return m_fWriteToNetRectBuf;};
int GetNetRectBufOffset(void) {return m_nNetRectBufOffset;};
void SetNetRectBufOffset(int nValue) {m_nNetRectBufOffset = nValue;};
BYTE* GetNetRectBuf(void) {return m_pNetRectBuf;};
void CheckNetRectBufferSize(int nBufSize);
VBool SendExactHTTP(const char *buff, const VCard bufflen);
VBool ReadExactHTTP(char *buff, const VCard bufflen);
//adzm 2010-05-10
IIntegratedPlugin* GetIntegratedPlugin() { return m_pIntegratedPluginInterface; };
//adzm 2010-08-01
DWORD GetLastSentTick() { return m_LastSentTick; };
IIntegratedPlugin* m_pIntegratedPluginInterface;
////////////////////////////
// Internal structures
protected:
// The internal socket id
int sock;
//adzm 2010-08-01
DWORD m_LastSentTick;
CDSMPlugin* m_pDSMPlugin; // sf@2002 - DSMPlugin
//adzm 2009-06-20
IPlugin* m_pPluginInterface;
//adzm 2010-05-10
bool m_fUsePlugin;
bool m_fPluginStreamingIn; //adzm 2010-09
bool m_fPluginStreamingOut; //adzm 2010-09
omni_mutex m_TransMutex;
omni_mutex m_RestMutex;
omni_mutex m_CheckMutex;
//adzm 2009-06-20
BYTE* TransformBuffer(BYTE* pDataBuffer, int nDataLen, int* nTransformedDataLen);
BYTE* RestoreBufferStep1(BYTE* pDataBuffer, int nDataLen, int* nRestoredDataLen);
BYTE* RestoreBufferStep2(BYTE* pDataBuffer, int nDataLen, int* nRestoredDataLen);
// All this should be private with accessors -> later
BYTE* m_pNetRectBuf;
bool m_fWriteToNetRectBuf;
int m_nNetRectBufOffset;
int m_nNetRectBufSize;
char queuebuffer[9000];
DWORD queuebuffersize;
// adzm 2010-08
static int m_defaultSocketKeepAliveTimeout;
HMODULE s_hIPHlp;
t_GetPerTcpConnectionEStats s_pGetPerTcpConnectionEStats;
t_SetPerTcpConnectionEStats s_pSetPerTcpConnectionEStats;
MIB_TCPROW m_SocketInfo;
bool CanUseFlow;
bool GetOptimalSndBuf();
unsigned int G_SENDBUFFER;
};
#endif // _ATT_VSOCKET_DEFINED
| [
"root@runtalk.co.kr"
] | root@runtalk.co.kr | |
2bc0f6b8fc7dec9737ddbcb358538c457dd58277 | 817cc371e2eb56f37c400b7f96d658d0683476b1 | /201911_practice/1242/c/c.cpp | fe08e16b0b483f96549b17164e59baaf267de68f | [] | no_license | KanadeSiina/PracticeCode | c696495bd71395648ac62a41d0a41869f50c5eb4 | 146c8d5889eee7917a355feb8b03d1415a29ae9d | refs/heads/master | 2020-09-05T00:49:29.165600 | 2020-06-30T12:48:15 | 2020-06-30T12:48:15 | 219,937,221 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,406 | cpp | #include<bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
#define dbg(x...) do{cout << "\033[32;1m" << #x << "->" ; err(x);} while(0)
void err(){cout << "\033[39;0m" << endl;}
template<template<typename...> class T,typename t,typename... A>
void err(T<t> a,A... x){for (auto v:a) cout << v << ' '; err(x...);}
template<typename T,typename... A>
void err(T a,A... x){cout << a << ' '; err(x...);}
#else
#define dbg(...)
#endif
typedef long long ll;
typedef pair<int,int> PII;
const int INF=0x3f3f3f3f;
const int maxn=5005;
int org[1<<15];
int dp[1<<15];
int pre[1<<15];
int cnt[15];
ll sum[15];
ll a[15][maxn];
map<ll,PII> pos;
bool vis[15];
PII G[15][maxn];
vector<PII> path[1<<15];
PII ans[15];
void getpath(int st,int ed,int i,int j,int state,vector<PII> pa)
{
if(i==-1||j==-1) return;
if(vis[i])
{
if(st==i&&ed==j)
{
org[state]=dp[state]=1;
path[state]=pa;
}
return;
}
vis[i]=1;
pa.push_back(make_pair(i,j));
getpath(st,ed,G[i][j].first,G[i][j].second,state|(1<<i),pa);
}
void getans(int state)
{
if(org[state])
{
int sz=path[state].size();
for(int i=0;i<sz;i++)
{
//cout<<i<<":"<<path[state][i].first<<" "<<path[state][i].second<<endl;
int pre=(i-1+sz)%sz;
ans[path[state][i].first]=make_pair(path[state][i].second,path[state][pre].first);
}
return;
}
getans(pre[state]);
getans(state^pre[state]);
}
int main()
{
memset(G,-1,sizeof(G));
int k;
scanf("%d",&k);
ll tot=0;
for(int i=0;i<k;i++)
{
scanf("%d",&cnt[i]);
for(int j=0;j<cnt[i];j++)
{
scanf("%lld",&a[i][j]);
tot+=a[i][j];
pos[a[i][j]]=make_pair(i,j);
sum[i]+=a[i][j];
}
}
if(tot%k!=0) puts("No");
else{
ll tar=tot/k;
for(int i=0;i<k;i++)
{
for(int j=0;j<cnt[i];j++)
{
ll delta=tar-(sum[i]-a[i][j]);
if(pos.count(delta))
{
if(pos[delta].first==i)
continue;
G[i][j]=pos[delta];
}
}
}
for(int i=0;i<k;i++)
{
if(sum[i]==tar)
{
org[1<<i]=dp[1<<i]=1;
path[1<<i]={make_pair(i,0)};
}
for(int j=0;j<cnt[i];j++)
{
if(G[i][j].first!=-1)
{
memset(vis,0,sizeof(vis));
vis[i]=1;
vector<PII> tmp={make_pair(i,j)};
getpath(i,j,G[i][j].first,G[i][j].second,1<<i,tmp);
}
}
}
for(int S=1;S<(1<<k);S++)
{
for(int T = S; T; T = (T - 1) & S)
{
if(dp[T]&&org[S-T])
{
pre[S]=T;
dp[S]=1;
}
}
}
if(!dp[(1<<k)-1]) puts("No");
else
{
puts("Yes");
getans((1<<k)-1);
for(int i=0;i<k;i++)
printf("%lld %d\n",a[i][ans[i].first],ans[i].second+1);
}
}
} | [
"820233016@qq.com"
] | 820233016@qq.com |
085f7f6d7072a2819c5cdab8bb1dc7528f98bb59 | 6a5902e3211019ac17a8e7ac49b3739be0b55007 | /WebServer/Timer.h | 26b2e102cad48a4654a4d48176dcd4f1360c0e39 | [
"MIT"
] | permissive | hdulixian/WebServer | 0096ea62ebb4275a7c84dbcfb93c82ed0c627646 | 4c2a2576cfb156093475dfc7b69203cb504c74c2 | refs/heads/master | 2023-01-10T21:04:32.071202 | 2020-11-24T14:24:19 | 2020-11-24T14:32:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | h | // Copyright (C) 2020 by Lixian. All rights reserved.
// Date: 2020-07-03
#ifndef _TIMER_H_
#define _TIMER_H_
#include <unistd.h>
#include <deque>
#include <memory>
#include <queue>
#include "HttpData.h"
#include "base/MutexLock.h"
#include "base/noncopyable.h"
class HttpData;
class TimerNode {
public:
TimerNode(std::shared_ptr<HttpData> requestData, int timeout);
~TimerNode();
TimerNode(TimerNode &tn);
void update(int timeout);
bool isValid();
void clearReq();
void setDeleted() { deleted_ = true; }
bool isDeleted() const { return deleted_; }
size_t getExpTime() const { return expiredTime_; }
private:
bool deleted_;
size_t expiredTime_;
std::shared_ptr<HttpData> SPHttpData;
};
struct TimerCmp {
bool operator()(std::shared_ptr<TimerNode> &a, std::shared_ptr<TimerNode> &b) const {
return a->getExpTime() > b->getExpTime();
}
};
class TimerManager {
public:
TimerManager();
~TimerManager();
void addTimer(std::shared_ptr<HttpData> SPHttpData, int timeout);
void handleExpiredEvent();
private:
typedef std::shared_ptr<TimerNode> SPTimerNode;
std::priority_queue<SPTimerNode, std::deque<SPTimerNode>, TimerCmp>
timerNodeQueue;
// MutexLock lock;
};
#endif // _TIMER_H_ | [
"lixian_94@163.com"
] | lixian_94@163.com |
d3089e05bc064e89f5ca8fa4162b54bc2881cdb4 | 801f7ed77fb05b1a19df738ad7903c3e3b302692 | /optimisationRefactoring/differentiatedCAD/occt-min-topo-src/src/XmlMDataStd/XmlMDataStd_ReferenceListDriver.hxx | 091a32326382c183fbd26352c2be7b9336ecf409 | [] | no_license | salvAuri/optimisationRefactoring | 9507bdb837cabe10099d9481bb10a7e65331aa9d | e39e19da548cb5b9c0885753fe2e3a306632d2ba | refs/heads/master | 2021-01-20T03:47:54.825311 | 2017-04-27T11:31:24 | 2017-04-27T11:31:24 | 89,588,404 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,911 | hxx | // Created on: 2007-05-29
// Created by: Vlad Romashko
// Copyright (c) 2007-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _XmlMDataStd_ReferenceListDriver_HeaderFile
#define _XmlMDataStd_ReferenceListDriver_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <XmlMDF_ADriver.hxx>
#include <Standard_Boolean.hxx>
#include <XmlObjMgt_RRelocationTable.hxx>
#include <XmlObjMgt_SRelocationTable.hxx>
class CDM_MessageDriver;
class TDF_Attribute;
class XmlObjMgt_Persistent;
class XmlMDataStd_ReferenceListDriver;
DEFINE_STANDARD_HANDLE(XmlMDataStd_ReferenceListDriver, XmlMDF_ADriver)
class XmlMDataStd_ReferenceListDriver : public XmlMDF_ADriver
{
public:
Standard_EXPORT XmlMDataStd_ReferenceListDriver(const Handle(CDM_MessageDriver)& theMessageDriver);
Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const;
Standard_EXPORT Standard_Boolean Paste (const XmlObjMgt_Persistent& Source, const Handle(TDF_Attribute)& Target, XmlObjMgt_RRelocationTable& RelocTable) const;
Standard_EXPORT void Paste (const Handle(TDF_Attribute)& Source, XmlObjMgt_Persistent& Target, XmlObjMgt_SRelocationTable& RelocTable) const;
DEFINE_STANDARD_RTTI(XmlMDataStd_ReferenceListDriver,XmlMDF_ADriver)
protected:
private:
};
#endif // _XmlMDataStd_ReferenceListDriver_HeaderFile
| [
"salvatore.auriemma@opencascade.com"
] | salvatore.auriemma@opencascade.com |
0f6e64d5edcda469d9a995ea6f892e6a7be718a2 | 09ddd2df75bce4df9e413d3c8fdfddb7c69032b4 | /src/Browser/dvd.h | 8e2d82bb5e9a3c7d10130feb2400a65d01949958 | [] | no_license | sigurdle/FirstProject2 | be22e4824da8cd2cb5047762478050a04a4ac63b | dee78c62a1b95e55fcdf3bf2a9bc79c69705bf94 | refs/heads/master | 2021-01-16T18:45:41.042140 | 2020-08-18T16:57:13 | 2020-08-18T16:57:13 | 3,554,336 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 38 | h | namespace System
{
int DecodeDVD();
}
| [
"sigurd.lerstad@gmail.com"
] | sigurd.lerstad@gmail.com |
0e8c347b8c46a35c02ac6eea2d4be27b2d4fce08 | ab1c643f224197ca8c44ebd562953f0984df321e | /wmi/wbem/providers/jobobjectprov/jobase.cpp | 012f9261c45c2bfe4754c1bca000ae91027c6a19 | [] | no_license | KernelPanic-OpenSource/Win2K3_NT_admin | e162e0452fb2067f0675745f2273d5c569798709 | d36e522f16bd866384bec440517f954a1a5c4a4d | refs/heads/master | 2023-04-12T13:25:45.807158 | 2021-04-13T16:33:59 | 2021-04-13T16:33:59 | 357,613,696 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,644 | cpp | // Copyright (c) 2000-2001 Microsoft Corporation, All Rights Reserved
// JOBase.cpp
#include "precomp.h"
//#include <windows.h>
//#include <cominit.h>
//#include <objbase.h>
//#include <comdef.h>
#include "CUnknown.h"
#include <wbemprov.h>
#include "FRQueryEx.h"
#include "globals.h"
#include "CVARIANT.h"
#include "CObjProps.h"
#include "JOBase.h"
#include "Factory.h"
#include "helpers.h"
#include <map>
#include <vector>
#include "SmartHandle.h"
#include "AssertBreak.h"
HRESULT CJOBase::Initialize(
LPWSTR pszUser,
LONG lFlags,
LPWSTR pszNamespace,
LPWSTR pszLocale,
IWbemServices *pNamespace,
IWbemContext *pCtx,
IWbemProviderInitSink *pInitSink)
{
if(pNamespace) pNamespace->AddRef();
m_pNamespace = pNamespace;
m_chstrNamespace = pszNamespace;
//Let CIMOM know you are initialized
pInitSink->SetStatus(
WBEM_S_INITIALIZED,
0);
return WBEM_S_NO_ERROR;
}
HRESULT CJOBase::GetObjectAsync(
const BSTR ObjectPath,
long lFlags,
IWbemContext __RPC_FAR *pCtx,
IWbemObjectSink __RPC_FAR *pResponseHandler,
CObjProps& objprops,
PFN_CHECK_PROPS pfnChk,
LPWSTR wstrClassName,
LPCWSTR wstrKeyProp)
{
HRESULT hr = WBEM_E_NOT_FOUND;
// We need the name of the instance they requested...
WCHAR wstrObjInstKeyVal[MAX_PATH];
hr = GetObjInstKeyVal(
ObjectPath,
wstrClassName,
wstrKeyProp,
wstrObjInstKeyVal,
sizeof(wstrObjInstKeyVal) - sizeof(WCHAR));
if(SUCCEEDED(hr))
{
// wstrObjInstKeyVal now contains the name of the object. See if
// it exists...
SmartHandle hJob;
hJob = ::OpenJobObject(
MAXIMUM_ALLOWED,
FALSE,
wstrObjInstKeyVal);
if(hJob)
{
// We seem to have found one matching the specified name,
// so create a return instance...
objprops.SetJobHandle(hJob);
IWbemClassObjectPtr pIWCO = NULL;
hr = CreateInst(
m_pNamespace,
&pIWCO,
_bstr_t(wstrClassName),
pCtx);
if(SUCCEEDED(hr))
{
// see what properties are requested...
hr = objprops.GetWhichPropsReq(
ObjectPath,
pCtx,
wstrClassName,
pfnChk);
}
if(SUCCEEDED(hr))
{
// set the key properties...
hr = objprops.SetKeysFromPath(
ObjectPath,
pCtx);
}
if(SUCCEEDED(hr))
{
// set the non-key requested properties...
hr = objprops.SetNonKeyReqProps();
}
if(SUCCEEDED(hr))
{
// Load requested non-key properties
// to the instance...
hr = objprops.LoadPropertyValues(
pIWCO);
// Commit the instance...
if(SUCCEEDED(hr))
{
hr = pResponseHandler->Indicate(
1,
&pIWCO);
}
}
}
}
// Set Status
pResponseHandler->SetStatus(0, hr, NULL, NULL);
return hr;
}
HRESULT CJOBase::ExecQueryAsync(
const BSTR QueryLanguage,
const BSTR Query,
long lFlags,
IWbemContext __RPC_FAR *pCtx,
IWbemObjectSink __RPC_FAR *pResponseHandler,
CObjProps& objprops,
LPCWSTR wstrClassName,
LPCWSTR wstrKeyProp)
{
HRESULT hr = WBEM_S_NO_ERROR;
// We will optimize for those cases in which
// a particular set of named job objects
// (e.g., 1 or more). Enumerate also
// optimizes for the properties that were
// requested.
CFrameworkQuery cfwq;
hr = cfwq.Init(
QueryLanguage,
Query,
lFlags,
m_chstrNamespace);
std::vector<_bstr_t> rgNamedJOs;
if(SUCCEEDED(hr))
{
hr = cfwq.GetValuesForProp(
_bstr_t(wstrKeyProp),
rgNamedJOs);
}
if(SUCCEEDED(hr))
{
hr = Enumerate(
pCtx,
pResponseHandler,
rgNamedJOs,
objprops,
wstrClassName);
}
return hr;
}
HRESULT CJOBase::CreateInstanceEnumAsync(
const BSTR Class,
long lFlags,
IWbemContext __RPC_FAR *pCtx,
IWbemObjectSink __RPC_FAR *pResponseHandler,
CObjProps& objprops,
LPCWSTR wstrClassName)
{
HRESULT hr = WBEM_S_NO_ERROR;
if(wcsicmp(
Class,
wstrClassName) != NULL)
{
hr = WBEM_E_INVALID_CLASS;
}
// For every job object, return all accounting
// info properties...
if(SUCCEEDED(hr))
{
// Get a list of named jobs...
std::vector<_bstr_t> rgNamedJOs;
hr = GetJobObjectList(rgNamedJOs);
if(SUCCEEDED(hr))
{
hr = Enumerate(
pCtx,
pResponseHandler,
rgNamedJOs,
objprops,
wstrClassName);
}
}
return hr;
}
HRESULT CJOBase::Enumerate(
IWbemContext __RPC_FAR *pCtx,
IWbemObjectSink __RPC_FAR *pResponseHandler,
std::vector<_bstr_t>& rgNamedJOs,
CObjProps& objprops,
LPCWSTR wstrClassName)
{
HRESULT hr = S_OK;
long lNumJobs = rgNamedJOs.size();
try // CVARIANT can throw and I want the error...
{
if(lNumJobs > 0)
{
// Create an object path...
_bstr_t bstrtObjPath;
bstrtObjPath = wstrClassName;
// Get which props requested...
hr = objprops.GetWhichPropsReq(
bstrtObjPath,
pCtx);
if(SUCCEEDED(hr))
{
SmartHandle hJob;
for(long m = 0L; m < lNumJobs; m++)
{
// We have the name of a JO; need to open it up
// and get its properties...
hJob = ::OpenJobObject(
MAXIMUM_ALLOWED,
FALSE,
(LPCWSTR)(rgNamedJOs[m]));
// (NOTE: hJob smarthandle class automatically
// closes its handle on destruction and on
// reassignment.)
if(hJob)
{
// Set the handle...
objprops.SetJobHandle(hJob);
// Set the key properties directly...
std::vector<CVARIANT> vecvKeys;
CVARIANT vID(rgNamedJOs[m]);
vecvKeys.push_back(vID);
hr = objprops.SetKeysDirect(vecvKeys);
if(SUCCEEDED(hr))
{
// set the non-key requested
// properties...
hr = objprops.SetNonKeyReqProps();
}
// Create a new outgoing instance...
IWbemClassObjectPtr pIWCO = NULL;
if(SUCCEEDED(hr))
{
hr = CreateInst(
m_pNamespace,
&pIWCO,
_bstr_t(wstrClassName),
pCtx);
}
// Load the properties of the
// new outgoing instance...
if(SUCCEEDED(hr))
{
hr = objprops.LoadPropertyValues(pIWCO);
}
// And send it out...
if(SUCCEEDED(hr))
{
hr = pResponseHandler->Indicate(
1,
&pIWCO);
}
}
else
{
ASSERT_BREAK(0);
}
}
}
}
}
catch(CVARIANTError& cve)
{
hr = cve.GetWBEMError();
}
return hr;
}
| [
"polarisdp@gmail.com"
] | polarisdp@gmail.com |
bac33005f33a98d2be1e25c0f09352764d337c21 | fa1fea506a1bc70371804c677d9f5fed71b642ed | /CompTest/CompTestClass.cpp | 2e494dd0411324a2d014df5076c5c9c6f4a90727 | [] | no_license | luoqianlin/ComTest | 5c90cddc633f2ac19403a58182789ddc9bd7b2a0 | dac3bbff538c3d81997e046343ac669db90a89ea | refs/heads/master | 2020-09-30T12:29:25.453670 | 2019-12-11T06:06:48 | 2019-12-11T06:06:48 | 227,287,768 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,526 | cpp | /**
* @file CompTestClass.cpp
* @author LiWang112358
* @date 2012/3/17
* @version 1.0
* @brief CompTestClass类的实现
*/
#include "stdafx.h"
#include "CompTestClass.h"
ULONG CompTestClass::m_objNum = 0;//组件中CompTestClass对象的个数,用于判断是否可以卸载本组建,如值为0则可以卸载
CRITICAL_SECTION CompTestClass::m_cs;//为了多线程调用对m_objNum加的锁
CompTestClass::CompTestClass()
{
m_Ref = 0;
// autoLock tlock(m_cs);
m_objNum++; //构造了一个对象
}
CompTestClass::~CompTestClass()
{
//autoLock tlock(m_cs);
m_objNum--; //释放了一个对象
}
HRESULT _stdcall CompTestClass::QueryInterface(const IID &riid, void **ppvObject)
{
if (IID_IUnknown == riid) {
*ppvObject = (IUnknown*)this;
((IUnknown*)(*ppvObject))->AddRef();
}
else if (IID_ICompTest == riid) {
*ppvObject = (ICompTest*)this;
((ICompTest*)(*ppvObject))->AddRef();
}
else {
*ppvObject = NULL;
return E_NOINTERFACE;
}
return S_OK;
}
ULONG _stdcall CompTestClass::AddRef()
{
m_Ref++;
return m_Ref;
}
ULONG _stdcall CompTestClass::Release()
{
m_Ref--;
if (0 == m_Ref) {
delete this;
return 0;
}
return m_Ref;
}
int _stdcall CompTestClass::HelloWorld()//ICompTest接口的实现,返回一个整数89
{
return 89;
}
std::string _stdcall CompTestClass::TestHello() {
return std::string{ "TestHello" };
}
int CompTestClass::Init()
{
m_objNum = 0;
InitializeCriticalSection(&m_cs);
return 0;
}
ULONG CompTestClass::ObjNum()
{
return m_objNum;
} | [
"luoqianlin@sansi.com"
] | luoqianlin@sansi.com |
db840154680ce8a5f077f25aea7e00efe96d6840 | a70c3dfa9ac41c436dce5ffdbef26a9a04e6e03c | /worker/src/handles/TcpServer.hpp | a91094c92f8e35812b03b34dc5fc7d2fe6089922 | [
"ISC"
] | permissive | taktod/mediasoup | 09a5b7eb869f0e1728c1eb9361d5ed220a6f3e5f | 3a58ba36cc69a6a9ef340583d0c07f19dbe9908e | refs/heads/master | 2021-01-19T14:17:32.359502 | 2017-08-24T00:11:51 | 2017-08-24T00:11:51 | 100,894,560 | 0 | 0 | null | 2017-08-20T23:28:06 | 2017-08-20T23:28:06 | null | UTF-8 | C++ | false | false | 2,356 | hpp | #ifndef MS_TCP_SERVER_HPP
#define MS_TCP_SERVER_HPP
#include "../common.hpp"
#include "TcpConnection.hpp"
#include <uv.h>
#include <string>
#include <unordered_set>
class TcpServer : public TcpConnection::Listener
{
public:
TcpServer(const std::string& ip, uint16_t port, int backlog);
/**
* uvHandle must be an already initialized and binded uv_tcp_t pointer.
*/
TcpServer(uv_tcp_t* uvHandle, int backlog);
protected:
~TcpServer() override;
public:
void Destroy();
virtual void Dump() const;
bool IsClosing() const;
const struct sockaddr* GetLocalAddress() const;
int GetLocalFamily() const;
const std::string& GetLocalIP() const;
uint16_t GetLocalPort() const;
size_t GetNumConnections() const;
private:
bool SetLocalAddress();
/* Pure virtual methods that must be implemented by the subclass. */
protected:
virtual void UserOnTcpConnectionAlloc(TcpConnection** connection) = 0;
virtual void UserOnNewTcpConnection(TcpConnection* connection) = 0;
virtual void UserOnTcpConnectionClosed(TcpConnection* connection, bool isClosedByPeer) = 0;
virtual void UserOnTcpServerClosed() = 0;
/* Callbacks fired by UV events. */
public:
void OnUvConnection(int status);
void OnUvClosed();
/* Methods inherited from TcpConnection::Listener. */
public:
void OnTcpConnectionClosed(TcpConnection* connection, bool isClosedByPeer) override;
private:
// Allocated by this (may be passed by argument).
uv_tcp_t* uvHandle{ nullptr };
// Others.
std::unordered_set<TcpConnection*> connections;
bool isClosing{ false };
protected:
struct sockaddr_storage localAddr;
std::string localIP;
uint16_t localPort{ 0 };
};
/* Inline methods. */
inline bool TcpServer::IsClosing() const
{
return this->isClosing;
}
inline size_t TcpServer::GetNumConnections() const
{
return this->connections.size();
}
inline const struct sockaddr* TcpServer::GetLocalAddress() const
{
return reinterpret_cast<const struct sockaddr*>(&this->localAddr);
}
inline int TcpServer::GetLocalFamily() const
{
return reinterpret_cast<const struct sockaddr*>(&this->localAddr)->sa_family;
}
inline const std::string& TcpServer::GetLocalIP() const
{
return this->localIP;
}
inline uint16_t TcpServer::GetLocalPort() const
{
return this->localPort;
}
#endif
| [
"poepoemix@hotmail.com"
] | poepoemix@hotmail.com |
fd40fff0b3752bb56007a1a41e84f9aa9be4a8f0 | 83b8a9e0ba13a792f44fca455ba01043b9a81c78 | /201909_Algorithm/201909_Algorithm/BOJ_12865.cpp | 237491f98685262d31e944e56ba76ae01e8e308a | [] | no_license | BoGyuPark/VS_BOJ | 0799a0c62fd72a6fc1e6f7e34fc539a742c0782b | 965973600dedbd5f3032c3adb4b117cc43c62a8f | refs/heads/master | 2020-04-14T12:45:53.930735 | 2019-12-04T03:06:44 | 2019-12-04T03:06:44 | 163,849,994 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 509 | cpp | /* BOJ 12865 평범한 배낭*/
#include<iostream>
#include<algorithm>
using namespace std;
int n, k, w[101], v[101], d[101][100001];
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> w[i] >> v[i];
}
//보석 종류
for (int i = 1; i <= n; i++) {
//가방 무게
for (int j = 1; j <= k; j++) {
if (j - w[i] < 0) d[i][j] = d[i - 1][j];
else {
d[i][j] = max(d[i - 1][j - w[i]] + v[i], d[i - 1][j]);
}
}
}
cout << d[n][k];
} | [
"shaing123@naver.com"
] | shaing123@naver.com |
70697cd4997c2288ae7f9b00a3e7ae151b65cc35 | 54b8fa244ff0dae2018efedcb81e1bb03376e5e2 | /src/qt/intro.cpp | 18aa17b7b5aae3317f2187eab1434fdae513732f | [
"MIT"
] | permissive | afghany/castletmp | e15677a88f9a1878486b6becf93d26c0ee9dbeaf | 9d0daed2a6abaf7d93f9308f5c602db6eeb42c8b | refs/heads/master | 2022-11-27T14:58:47.802781 | 2020-08-08T21:26:12 | 2020-08-08T21:26:12 | 284,464,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,284 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The CASTLE developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "intro.h"
#include "ui_intro.h"
#include "fs.h"
#include "guiutil.h"
#include "util.h"
#include "qt/castle/qtutils.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>
/* Minimum free space (in bytes) needed for data directory */
static const uint64_t GB_BYTES = 1000000000LL;
static const uint64_t BLOCK_CHAIN_SIZE = 1LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro* intro);
enum Status {
ST_OK,
ST_ERROR
};
public Q_SLOTS:
void check();
Q_SIGNALS:
void reply(int status, const QString& message, quint64 available);
private:
Intro* intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro* intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while (parentDir.has_parent_path() && !fs::exists(parentDir)) {
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if (fs::exists(dataDir)) {
if (fs::is_directory(dataDir)) {
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch (const fs::filesystem_error& e) {
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
this->setStyleSheet(GUIUtil::loadStyleSheet());
setCssProperty(ui->frame, "container-welcome-step2");
setCssProperty(ui->container, "container-welcome-stack");
setCssProperty(ui->frame_2, "container-welcome");
setCssProperty(ui->label_2, "text-title-welcome");
setCssProperty(ui->label_4, "text-intro-white");
setCssProperty(ui->sizeWarningLabel, "text-intro-white");
setCssProperty(ui->freeSpace, "text-intro-white");
setCssProperty(ui->errorMessage, "text-intro-white");
setCssProperty({ui->dataDirDefault, ui->dataDirCustom}, "radio-welcome");
setCssProperty(ui->dataDirectory, "edit-primary-welcome");
ui->dataDirectory->setAttribute(Qt::WA_MacShowFocusRect, 0);
setCssProperty(ui->ellipsisButton, "btn-dots-welcome");
setCssBtnPrimary(ui->pushButtonOk);
setCssBtnSecondary(ui->pushButtonCancel);
connect(ui->pushButtonOk, &QPushButton::clicked, this, &Intro::accept);
connect(ui->pushButtonCancel, &QPushButton::clicked, this, &Intro::close);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE / GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
Q_EMIT stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString& dataDir)
{
ui->dataDirectory->setText(dataDir);
if (dataDir == getDefaultDataDirectory()) {
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
updateDataDirStatus(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
updateDataDirStatus(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
bool Intro::pickDataDirectory()
{
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if (!GetArg("-datadir", "").empty())
return true;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if (!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false)) {
// If current default data directory does not exist, let the user choose one
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while (true) {
if (!intro.exec()) {
// Cancel clicked
return false;
}
dataDir = intro.getDataDirectory();
try {
TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));
break;
} catch (const fs::filesystem_error& e) {
QMessageBox::critical(0, tr("CASTLE Core"),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
// fall through, back to choosing screen
}
}
settings.setValue("strDataDir", dataDir);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the castle.conf file in the default data directory
* (to be consistent with castled behavior)
*/
if (dataDir != getDefaultDataDirectory())
SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
return true;
}
void Intro::setStatus(int status, const QString& message, quint64 bytesAvailable)
{
switch (status) {
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #f84444 }");
break;
}
/* Indicate number of bytes available */
if (status == FreespaceChecker::ST_ERROR) {
ui->freeSpace->setText("");
} else {
QString freeString = tr("%1 GB of free space available").arg(bytesAvailable / GB_BYTES);
if (bytesAvailable < BLOCK_CHAIN_SIZE) {
freeString += " " + tr("(of %1 GB needed)").arg(BLOCK_CHAIN_SIZE / GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->pushButtonOk->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::updateDataDirStatus(bool enabled){
if(enabled){
setCssProperty(ui->dataDirectory, "edit-primary-welcome", true);
} else {
setCssProperty(ui->dataDirectory, "edit-primary-welcome-disabled", true);
}
}
void Intro::on_dataDirectory_textChanged(const QString& dataDirStr)
{
/* Disable OK button until check result comes in */
ui->pushButtonOk->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if (!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
updateDataDirStatus(false);
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
updateDataDirStatus(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker* executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus);
connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check);
/* make sure executor object is deleted in its own thread */
connect(this, &Intro::stopThread, executor, &QObject::deleteLater);
connect(this, &Intro::stopThread, thread, &QThread::quit);
thread->start();
}
void Intro::checkPath(const QString& dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if (!signalled) {
signalled = true;
Q_EMIT requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
| [
"shagolo@gmail.com"
] | shagolo@gmail.com |
9227f1de8a908e0540c457bce9548ef5785992cd | be0282afa8dd436619c71d6118c9db455eaf1a29 | /Intermediate/Build/Win64/Design3D/Inc/UnrealEd/MaterialFunctionInstanceFactory.gen.cpp | bfb8fcd8b38a86d6c555a01a141c43015ce0af42 | [] | no_license | Quant2017/Design3D | 0f915580b222af40ab911021cceef5c26375d7f9 | 94a22386be4aa37aa0f546354cc62958820a4bf6 | refs/heads/master | 2022-04-23T10:44:12.398772 | 2020-04-22T01:02:39 | 2020-04-22T01:02:39 | 262,966,755 | 1 | 0 | null | 2020-05-11T07:12:37 | 2020-05-11T07:12:36 | null | UTF-8 | C++ | false | false | 12,040 | cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "UnrealEd/Classes/Factories/MaterialFunctionInstanceFactory.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeMaterialFunctionInstanceFactory() {}
// Cross Module References
UNREALED_API UClass* Z_Construct_UClass_UMaterialFunctionInstanceFactory_NoRegister();
UNREALED_API UClass* Z_Construct_UClass_UMaterialFunctionInstanceFactory();
UNREALED_API UClass* Z_Construct_UClass_UFactory();
UPackage* Z_Construct_UPackage__Script_UnrealEd();
ENGINE_API UClass* Z_Construct_UClass_UMaterialFunctionInterface_NoRegister();
UNREALED_API UClass* Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_NoRegister();
UNREALED_API UClass* Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory();
UNREALED_API UClass* Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_NoRegister();
UNREALED_API UClass* Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory();
// End Cross Module References
void UMaterialFunctionInstanceFactory::StaticRegisterNativesUMaterialFunctionInstanceFactory()
{
}
UClass* Z_Construct_UClass_UMaterialFunctionInstanceFactory_NoRegister()
{
return UMaterialFunctionInstanceFactory::StaticClass();
}
struct Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_InitialParent_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_InitialParent;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UFactory,
(UObject* (*)())Z_Construct_UPackage__Script_UnrealEd,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Object" },
{ "IncludePath", "Factories/MaterialFunctionInstanceFactory.h" },
{ "ModuleRelativePath", "Classes/Factories/MaterialFunctionInstanceFactory.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::NewProp_InitialParent_MetaData[] = {
{ "ModuleRelativePath", "Classes/Factories/MaterialFunctionInstanceFactory.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::NewProp_InitialParent = { "InitialParent", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialFunctionInstanceFactory, InitialParent), Z_Construct_UClass_UMaterialFunctionInterface_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::NewProp_InitialParent_MetaData, ARRAY_COUNT(Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::NewProp_InitialParent_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::NewProp_InitialParent,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UMaterialFunctionInstanceFactory>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::ClassParams = {
&UMaterialFunctionInstanceFactory::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::PropPointers,
nullptr,
ARRAY_COUNT(DependentSingletons),
0,
ARRAY_COUNT(Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::PropPointers),
0,
0x000820A0u,
METADATA_PARAMS(Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UMaterialFunctionInstanceFactory()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMaterialFunctionInstanceFactory_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UMaterialFunctionInstanceFactory, 2721100671);
template<> UNREALED_API UClass* StaticClass<UMaterialFunctionInstanceFactory>()
{
return UMaterialFunctionInstanceFactory::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UMaterialFunctionInstanceFactory(Z_Construct_UClass_UMaterialFunctionInstanceFactory, &UMaterialFunctionInstanceFactory::StaticClass, TEXT("/Script/UnrealEd"), TEXT("UMaterialFunctionInstanceFactory"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UMaterialFunctionInstanceFactory);
void UMaterialFunctionMaterialLayerInstanceFactory::StaticRegisterNativesUMaterialFunctionMaterialLayerInstanceFactory()
{
}
UClass* Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_NoRegister()
{
return UMaterialFunctionMaterialLayerInstanceFactory::StaticClass();
}
struct Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UMaterialFunctionInstanceFactory,
(UObject* (*)())Z_Construct_UPackage__Script_UnrealEd,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Object Object" },
{ "IncludePath", "Factories/MaterialFunctionInstanceFactory.h" },
{ "ModuleRelativePath", "Classes/Factories/MaterialFunctionInstanceFactory.h" },
};
#endif
const FCppClassTypeInfoStatic Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UMaterialFunctionMaterialLayerInstanceFactory>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_Statics::ClassParams = {
&UMaterialFunctionMaterialLayerInstanceFactory::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
nullptr,
nullptr,
ARRAY_COUNT(DependentSingletons),
0,
0,
0,
0x000820A0u,
METADATA_PARAMS(Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UMaterialFunctionMaterialLayerInstanceFactory, 408520894);
template<> UNREALED_API UClass* StaticClass<UMaterialFunctionMaterialLayerInstanceFactory>()
{
return UMaterialFunctionMaterialLayerInstanceFactory::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UMaterialFunctionMaterialLayerInstanceFactory(Z_Construct_UClass_UMaterialFunctionMaterialLayerInstanceFactory, &UMaterialFunctionMaterialLayerInstanceFactory::StaticClass, TEXT("/Script/UnrealEd"), TEXT("UMaterialFunctionMaterialLayerInstanceFactory"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UMaterialFunctionMaterialLayerInstanceFactory);
void UMaterialFunctionMaterialLayerBlendInstanceFactory::StaticRegisterNativesUMaterialFunctionMaterialLayerBlendInstanceFactory()
{
}
UClass* Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_NoRegister()
{
return UMaterialFunctionMaterialLayerBlendInstanceFactory::StaticClass();
}
struct Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UMaterialFunctionInstanceFactory,
(UObject* (*)())Z_Construct_UPackage__Script_UnrealEd,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Object Object" },
{ "IncludePath", "Factories/MaterialFunctionInstanceFactory.h" },
{ "ModuleRelativePath", "Classes/Factories/MaterialFunctionInstanceFactory.h" },
};
#endif
const FCppClassTypeInfoStatic Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UMaterialFunctionMaterialLayerBlendInstanceFactory>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_Statics::ClassParams = {
&UMaterialFunctionMaterialLayerBlendInstanceFactory::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
nullptr,
nullptr,
ARRAY_COUNT(DependentSingletons),
0,
0,
0,
0x000820A0u,
METADATA_PARAMS(Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UMaterialFunctionMaterialLayerBlendInstanceFactory, 3100865507);
template<> UNREALED_API UClass* StaticClass<UMaterialFunctionMaterialLayerBlendInstanceFactory>()
{
return UMaterialFunctionMaterialLayerBlendInstanceFactory::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory(Z_Construct_UClass_UMaterialFunctionMaterialLayerBlendInstanceFactory, &UMaterialFunctionMaterialLayerBlendInstanceFactory::StaticClass, TEXT("/Script/UnrealEd"), TEXT("UMaterialFunctionMaterialLayerBlendInstanceFactory"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UMaterialFunctionMaterialLayerBlendInstanceFactory);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"Snake_Jenny@126.com"
] | Snake_Jenny@126.com |
53fddb7762b921e10aa5746042838194853a6352 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/graph/example/roget_components.cpp | 67ef454ac4b40b0fdfc767c82732689d02e895f1 | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,913 | cpp | //=======================================================================
// Copyright 2001 University of Notre Dame.
// Authors: Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstd/boost/graph/stanford_graph.hpp>
#include <sstd/boost/graph/strong_components.hpp>
#define specs(v) \
(filename ? index_map[v] : v->cat_no) << " " << v->name
int main(int argc, char* argv[])
{
using namespace boost;
Graph* g;
typedef graph_traits<Graph*>::vertex_descriptor vertex_t;
unsigned long n = 0;
unsigned long d = 0;
unsigned long p = 0;
long s = 0;
char* filename = NULL;
int c, i;
while (--argc) {
if (sscanf(argv[argc], "-n%lu", &n) == 1);
else if (sscanf(argv[argc], "-d%lu", &d) == 1);
else if (sscanf(argv[argc], "-p%lu", &p) == 1);
else if (sscanf(argv[argc], "-s%ld", &s) == 1);
else if (strncmp(argv[argc], "-g", 2) == 0)
filename = argv[argc] + 2;
else {
fprintf(stderr, "Usage: %s [-nN][-dN][-pN][-sN][-gfoo]\n", argv[0]);
return -2;
}
}
g = (filename ? restore_graph(filename) : roget(n, d, p, s));
if (g == NULL) {
fprintf(stderr, "Sorry, can't create the graph! (error code %ld)\n",
panic_code);
return -1;
}
printf("Reachability analysis of %s\n\n", g->id);
// - The root map corresponds to what Knuth calls the "min" field.
// - The discover time map is the "rank" field
// - Knuth uses the rank field for double duty, to record the
// discover time, and to keep track of which vertices have
// been visited. The BGL strong_components() function needs
// a separate field for marking colors, so we use the w field.
std::vector<int> comp(num_vertices(g));
property_map<Graph*, vertex_index_t>::type
index_map = get(vertex_index, g);
property_map<Graph*, v_property<vertex_t> >::type
root = get(v_property<vertex_t>(), g);
int num_comp = strong_components
(g, make_iterator_property_map(comp.begin(), index_map),
root_map(root).
discover_time_map(get(z_property<long>(), g)).
color_map(get(w_property<long>(), g)));
std::vector< std::vector<vertex_t> > strong_comp(num_comp);
// First add representative vertices to each component's list
graph_traits<Graph*>::vertex_iterator vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
if (root[*vi] == *vi)
strong_comp[comp[index_map[*vi]]].push_back(*vi);
// Then add the other vertices of the component
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
if (root[*vi] != *vi)
strong_comp[comp[index_map[*vi]]].push_back(*vi);
// We do not print out the "from" and "to" information as Knuth
// does because we no longer have easy access to that information
// from outside the algorithm.
for (c = 0; c < num_comp; ++c) {
vertex_t v = strong_comp[c].front();
std::cout << "Strong component `" << specs(v) << "'";
if (strong_comp[c].size() > 1) {
std::cout << " also includes:\n";
for (i = 1; i < strong_comp[c].size(); ++i)
std::cout << " " << specs(strong_comp[c][i]) << std::endl;
} else
std::cout << std::endl;
}
// Next we print out the "component graph" or "condensation", that
// is, we consider each component to be a vertex in a new graph
// where there is an edge connecting one component to another if there
// is one or more edges connecting any of the vertices from the
// first component to any of the vertices in the second. We use the
// name of the representative vertex as the name of the component.
printf("\nLinks between components:\n");
// This array provides an efficient way to check if we've already
// created a link from the current component to the component
// of the target vertex.
std::vector<int> mark(num_comp, (std::numeric_limits<int>::max)());
// We go in reverse order just to mimic the output ordering in
// Knuth's version.
for (c = num_comp - 1; c >= 0; --c) {
vertex_t u = strong_comp[c][0];
for (i = 0; i < strong_comp[c].size(); ++i) {
vertex_t v = strong_comp[c][i];
graph_traits<Graph*>::out_edge_iterator ei, ei_end;
for (boost::tie(ei, ei_end) = out_edges(v, g); ei != ei_end; ++ei) {
vertex_t x = target(*ei, g);
int comp_x = comp[index_map[x]];
if (comp_x != c && mark[comp_x] != c) {
mark[comp_x] = c;
vertex_t w = strong_comp[comp_x][0];
std::cout << specs(u) << " -> " << specs(w)
<< " (e.g., " << specs(v) << " -> " << specs(x) << ")\n";
} // if
} // for
} // for
} // for
}
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
2838af1b7b4f84d61f9cc1b0c0ee96c60b1f2a8e | bfe2472651b6920965828498ef5bae93fdd5440e | /test.cpp | bf901134eae089dc3e2b69d3bfd76a39ca5b30bb | [] | no_license | NeonRice/students | b21c46faec4405a40b121bc4f3f66d9c04249b9a | d3bd43522447b6c96427d0493e1b8e6a3e4538d3 | refs/heads/master | 2021-01-06T03:33:50.777054 | 2020-04-23T20:20:16 | 2020-04-23T20:20:16 | 241,212,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,480 | cpp | #include "headers/Input.h"
#include "headers/Output.h"
#include <chrono>
#include <deque>
#include <list>
#include <algorithm>
const int GENERATION_START = 1000;
const int GENERATION_OFFSET = 10;
const int FILE_AMOUNT = 5;
const int GRADE_COUNT = 15;
// Comparison inline functions
inline bool compareByFinalGrade(Student &a, Student &b) //Comparison Utility function
{
return a.getAverage() > b.getAverage();
}
//A comparison function here for strong and weak students
inline bool IsWeakStudent(Student &s) { return ((s.getAverage() < 5.0) == 0); }
inline bool IsStrongStudent(Student &s) { return ((s.getAverage() >= 5.0) == 0); }
//Container seperation algorithms
template <typename Container>
void seperateSortedContainer(Container &students, Container &weakStudents) // Vector must be sorted in decreasing grade order in order for the function to work correctly
{
auto it = students.begin();
auto b = students.begin();
for (; it != students.end(); ++it)
{
if ((*it).getAverage() < 5.0)
weakStudents.push_back(*it);
if ((*it).getAverage() >= 5.0)
b = it;
}
students.erase(b, it);
}
template <typename Container>
void seperateContainer1(Container &students, Container &weakStudents, Container &newStudents)
{
std::remove_copy_if(students.begin(), students.end(), std::back_inserter(weakStudents), IsWeakStudent);
std::remove_copy_if(students.begin(), students.end(), std::back_inserter(newStudents), IsStrongStudent);
}
template <typename Container>
void seperateContainer2(Container &students, Container &weakStudents, Container &goodStudents) //Faster than seperateContainer2
{
auto it = students.begin();
for (; it != students.end(); ++it)
{
if ((*it).getAverage() < 5.0)
weakStudents.push_back(*it);
if ((*it).getAverage() >= 5.0)
goodStudents.push_back(*it);
}
}
template <typename Container>
void seperateContainer(Container &students, Container &weakStudents)
{
std::remove_copy_if(students.begin(), students.end(), std::back_inserter(weakStudents), IsWeakStudent);
students.erase(
std::remove_if(students.begin(), students.end(), IsStrongStudent),
students.end());
}
//Test case
void testVector(bool sort)
{
int GENERATION_AMOUNT = GENERATION_START;
for (int i = 0; i < FILE_AMOUNT; ++i)
{
std::vector<Student> students, weakStudents, goodStudents;
std::cout << "Using vectors for storing data..." << std::endl;
std::cout << "Starting generation and analysis of students" << GENERATION_AMOUNT << ".txt..." << std::endl;
auto programStart = std::chrono::system_clock::now();
auto start = std::chrono::system_clock::now();
generateTestFile(GENERATION_AMOUNT, GRADE_COUNT);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "Elapsed time for generation " << elapsed_seconds.count() << " s" << std::endl;
start = std::chrono::system_clock::now();
students = readStudentsFromFile<std::vector<Student>>("students" + std::to_string(GENERATION_AMOUNT) + ".txt", false);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for reading " << elapsed_seconds.count() << " s" << std::endl;
if (!sort)
{
start = std::chrono::system_clock::now();
seperateContainer1(students, weakStudents, goodStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating using 1st method " << elapsed_seconds.count() << " s" << std::endl;
weakStudents.clear();
goodStudents.clear();
start = std::chrono::system_clock::now();
seperateContainer2(students, weakStudents, goodStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating using 2nd method " << elapsed_seconds.count() << " s" << std::endl;
weakStudents.clear();
start = std::chrono::system_clock::now();
seperateContainer(students, weakStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating using 3rd method " << elapsed_seconds.count() << " s" << std::endl;
}
else if (sort)
{
start = std::chrono::system_clock::now();
std::sort(students.begin(), students.end(), compareByFinalGrade);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for sorting by grade " << elapsed_seconds.count() << " s" << std::endl;
start = std::chrono::system_clock::now();
seperateSortedContainer(students, weakStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating sorted vectors " << elapsed_seconds.count() << " s" << std::endl;
}
start = std::chrono::system_clock::now();
std::ofstream f1("smartStudents" + std::to_string(GENERATION_AMOUNT) + ".txt");
std::ofstream f2("lameStudents" + std::to_string(GENERATION_AMOUNT) + ".txt");
printStudentInfo(students, f1);
printStudentInfo(weakStudents, f2);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for printing out the seperated results " << elapsed_seconds.count() << " s" << std::endl;
f1.close();
f2.close();
GENERATION_AMOUNT *= GENERATION_OFFSET;
auto programStop = std::chrono::system_clock::now();
elapsed_seconds = programStop - programStart;
std::cout << "Total elapsed time for printing out the seperated results " << elapsed_seconds.count() << " s" << std::endl;
std::cout << "\n\n"
<< std::endl;
}
}
void testDeque(bool sort)
{
int GENERATION_AMOUNT = GENERATION_START;
for (int i = 0; i < FILE_AMOUNT; ++i)
{
std::deque<Student> students, weakStudents, goodStudents;
std::cout << "Using deque for storing data..." << std::endl;
std::cout << "Starting generation and analysis of students" << GENERATION_AMOUNT << ".txt..." << std::endl;
auto programStart = std::chrono::system_clock::now();
auto start = std::chrono::system_clock::now();
generateTestFile(GENERATION_AMOUNT, GRADE_COUNT);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "Elapsed time for generation " << elapsed_seconds.count() << " s" << std::endl;
start = std::chrono::system_clock::now();
students = readStudentsFromFile<std::deque<Student>>("students" + std::to_string(GENERATION_AMOUNT) + ".txt", false);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for reading " << elapsed_seconds.count() << " s" << std::endl;
if (sort)
{
start = std::chrono::system_clock::now();
std::sort(students.begin(), students.end(), compareByFinalGrade);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for sorting by grade " << elapsed_seconds.count() << " s" << std::endl;
start = std::chrono::system_clock::now();
seperateSortedContainer(students, weakStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating sorted deque " << elapsed_seconds.count() << " s" << std::endl;
}
else if (!sort)
{
start = std::chrono::system_clock::now();
seperateContainer1(students, weakStudents, goodStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating deque using 1st method " << elapsed_seconds.count() << " s" << std::endl;
weakStudents.clear();
goodStudents.clear();
start = std::chrono::system_clock::now();
seperateContainer2(students, weakStudents, goodStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating deque using 2nd method " << elapsed_seconds.count() << " s" << std::endl;
weakStudents.clear();
start = std::chrono::system_clock::now();
seperateContainer(students, weakStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating deque using 3rd method " << elapsed_seconds.count() << " s" << std::endl;
}
start = std::chrono::system_clock::now();
std::ofstream f1("smartStudents" + std::to_string(GENERATION_AMOUNT) + ".txt");
std::ofstream f2("lameStudents" + std::to_string(GENERATION_AMOUNT) + ".txt");
printStudentInfo(students, f1);
printStudentInfo(weakStudents, f2);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for printing out the seperated results " << elapsed_seconds.count() << " s" << std::endl;
f1.close();
f2.close();
GENERATION_AMOUNT *= GENERATION_OFFSET;
auto programStop = std::chrono::system_clock::now();
elapsed_seconds = programStop - programStart;
std::cout << "Total elapsed time for printing out the seperated results " << elapsed_seconds.count() << " s" << std::endl;
std::cout << "\n\n"
<< std::endl;
}
}
void testList(bool sort)
{
int GENERATION_AMOUNT = GENERATION_START;
for (int i = 0; i < FILE_AMOUNT; ++i)
{
std::list<Student> students, weakStudents, goodStudents;
std::cout << "Using lists for storing data..." << std::endl;
std::cout << "Starting generation and analysis of students" << GENERATION_AMOUNT << ".txt..." << std::endl;
auto programStart = std::chrono::system_clock::now();
auto start = std::chrono::system_clock::now();
generateTestFile(GENERATION_AMOUNT, GRADE_COUNT);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "Elapsed time for list generation " << elapsed_seconds.count() << " s" << std::endl;
start = std::chrono::system_clock::now();
students = readStudentsFromFile<std::list<Student>>("students" + std::to_string(GENERATION_AMOUNT) + ".txt", false);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for reading " << elapsed_seconds.count() << " s" << std::endl;
if (sort)
{
start = std::chrono::system_clock::now();
students.sort(compareByFinalGrade);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for sorting list by grade " << elapsed_seconds.count() << " s" << std::endl;
start = std::chrono::system_clock::now();
seperateSortedContainer(students, weakStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating sorted lists " << elapsed_seconds.count() << " s" << std::endl;
}
else if(!sort)
{
start = std::chrono::system_clock::now();
seperateContainer1(students, weakStudents, goodStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating lists using 1st method " << elapsed_seconds.count() << " s" << std::endl;
weakStudents.clear();
goodStudents.clear();
start = std::chrono::system_clock::now();
seperateContainer2(students, weakStudents, goodStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating lists using 2nd method " << elapsed_seconds.count() << " s" << std::endl;
weakStudents.clear();
start = std::chrono::system_clock::now();
seperateContainer(students, weakStudents);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for seperating lists using 3rd method " << elapsed_seconds.count() << " s" << std::endl;
}
start = std::chrono::system_clock::now();
std::ofstream f1("smartStudents" + std::to_string(GENERATION_AMOUNT) + ".txt");
std::ofstream f2("lameStudents" + std::to_string(GENERATION_AMOUNT) + ".txt");
printStudentInfo(students, f1);
printStudentInfo(weakStudents, f2);
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
std::cout << "Elapsed time for printing out the seperated results " << elapsed_seconds.count() << " s" << std::endl;
f1.close();
f2.close();
GENERATION_AMOUNT *= GENERATION_OFFSET;
auto programStop = std::chrono::system_clock::now();
elapsed_seconds = programStop - programStart;
std::cout << "Total elapsed time for printing out the seperated results " << elapsed_seconds.count() << " s" << std::endl;
std::cout << "\n\n"
<< std::endl;
}
}
//Program entry point
int main(int argc, char *argv[])
{
bool sort = false;
if (argc == 3)
{
if (toupper(*argv[2]) == 'S')
{
sort = true;
} //Should we sort or not??
}
if (argc < 2)
{
std::cout << "Specify test container type: v for vector, d for deque, l for list, a for all" << std::endl;
return -1;
}
else
{
if (*argv[1] == 'v' || *argv[1] == 'V')
testVector(sort);
else if (*argv[1] == 'd' || *argv[1] == 'D')
testDeque(sort);
else if (*argv[1] == 'l' || *argv[1] == 'L')
testList(sort);
else if (*argv[1] == 'a' || *argv[1] == 'A')
{
testVector(sort);
testDeque(sort);
testList(sort);
}
else
{
std::cout << "Specify test container type: v for vector, d for deque, l for list" << std::endl;
return -1;
}
}
std::cout << "End of test..." << std::endl;
return 0;
} | [
"zanas.kovaliovas@inbox.lt"
] | zanas.kovaliovas@inbox.lt |
6df31988450e4bb76a8b1e6c1c35b16ec73e622f | f0a26ec6b779e86a62deaf3f405b7a83868bc743 | /Engine/Source/Editor/UnrealEd/Private/Commandlets/PackageUtilities.cpp | a53c9c8fff307328675c46741298e4345adbd87f | [] | no_license | Tigrouzen/UnrealEngine-4 | 0f15a56176439aef787b29d7c80e13bfe5c89237 | f81fe535e53ac69602bb62c5857bcdd6e9a245ed | refs/heads/master | 2021-01-15T13:29:57.883294 | 2014-03-20T15:12:46 | 2014-03-20T15:12:46 | 18,375,899 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 89,326 | cpp | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
PackageUtilities.cpp: Commandlets for viewing information about package files
=============================================================================*/
#include "UnrealEd.h"
#include "ISourceControlModule.h"
#include "PackageHelperFunctions.h"
#include "PackageUtilityWorkers.h"
#include "AnimationUtils.h"
#include "AnimationCompression.h"
#include "CollectionManagerModule.h"
DEFINE_LOG_CATEGORY(LogPackageHelperFunctions);
DEFINE_LOG_CATEGORY_STATIC(LogPackageUtilities, Log, All);
/*-----------------------------------------------------------------------------
Package Helper Functions (defined in PackageHelperFunctions.h
-----------------------------------------------------------------------------*/
void SearchDirectoryRecursive( const FString& SearchPathMask, TArray<FString>& out_PackageNames, TArray<FString>& out_PackageFilenames )
{
const FString SearchPath = FPaths::GetPath(SearchPathMask);
TArray<FString> PackageNames;
IFileManager::Get().FindFiles( PackageNames, *SearchPathMask, true, false );
if ( PackageNames.Num() > 0 )
{
for ( int32 PkgIndex = 0; PkgIndex < PackageNames.Num(); PkgIndex++ )
{
new(out_PackageFilenames) FString( SearchPath / PackageNames[PkgIndex] );
}
out_PackageNames += PackageNames;
}
// now search all subdirectories
TArray<FString> Subdirectories;
IFileManager::Get().FindFiles( Subdirectories, *(SearchPath / TEXT("*")), false, true );
for ( int32 DirIndex = 0; DirIndex < Subdirectories.Num(); DirIndex++ )
{
SearchDirectoryRecursive( SearchPath / Subdirectories[DirIndex] / FPaths::GetCleanFilename(SearchPathMask), out_PackageNames, out_PackageFilenames);
}
}
/**
* Takes an array of package names (in any format) and converts them into relative pathnames for each package.
*
* @param PackageNames the array of package names to normalize. If this array is empty, the complete package list will be used.
* @param PackagePathNames will be filled with the complete relative path name for each package name in the input array
* @param PackageWildcard if specified, allows the caller to specify a wildcard to use for finding package files
* @param PackageFilter allows the caller to limit the types of packages returned.
*
* @return true if packages were found successfully, false otherwise.
*/
bool NormalizePackageNames( TArray<FString> PackageNames, TArray<FString>& PackagePathNames, const FString& PackageWildcard, uint8 PackageFilter )
{
if ( PackageNames.Num() == 0 )
{
IFileManager::Get().FindFiles( PackageNames, *PackageWildcard, true, false );
}
const FString DeveloperFolder = IFileManager::Get().ConvertToAbsolutePathForExternalAppForRead(*FPaths::GameDevelopersDir());
if( PackageNames.Num() == 0 )
{
TArray<FString> Paths;
if ( GConfig->GetArray( TEXT("Core.System"), TEXT("Paths"), Paths, GEngineIni ) > 0 )
{
for ( int32 i = 0; i < Paths.Num(); i++ )
{
FString SearchWildcard = Paths[i] / PackageWildcard;
SearchDirectoryRecursive( SearchWildcard, PackageNames, PackagePathNames );
}
}
if ( PackageNames.Num() == 0 )
{
// Check if long package name is provided and if it exists on disk.
FString Filename;
if ( FPackageName::IsValidLongPackageName(PackageWildcard, true) && FPackageName::DoesPackageExist(PackageWildcard, NULL, &Filename) )
{
PackagePathNames.Add(Filename);
}
}
}
else
{
// re-add the path information so that GetPackageLinker finds the correct version of the file.
const FString WildcardPath = FPaths::GetPath(PackageWildcard);
for ( int32 FileIndex = 0; FileIndex < PackageNames.Num(); FileIndex++ )
{
PackagePathNames.Add(WildcardPath / PackageNames[FileIndex]);
}
}
if ( PackagePathNames.Num() == 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("No packages found using '%s'!"), *PackageWildcard);
return false;
}
// now apply any filters to the list of packages
for ( int32 PackageIndex = PackagePathNames.Num() - 1; PackageIndex >= 0; PackageIndex-- )
{
FString PackageExtension = FPaths::GetExtension(PackagePathNames[PackageIndex], true);
if ( !FPackageName::IsPackageExtension(*PackageExtension) )
{
// not a valid package file - remove it
PackagePathNames.RemoveAt(PackageIndex);
}
else
{
if ( (PackageFilter&NORMALIZE_ExcludeMapPackages) != 0 )
{
if ( PackageExtension == FPackageName::GetMapPackageExtension() )
{
PackagePathNames.RemoveAt(PackageIndex);
continue;
}
}
if ( (PackageFilter&NORMALIZE_ExcludeContentPackages) != 0 )
{
if ( PackageExtension == FPackageName::GetAssetPackageExtension() )
{
PackagePathNames.RemoveAt(PackageIndex);
continue;
}
}
if ( (PackageFilter&NORMALIZE_ExcludeEnginePackages) != 0 )
{
if (PackagePathNames[PackageIndex].StartsWith(FPaths::EngineDir()))
{
PackagePathNames.RemoveAt(PackageIndex);
continue;
}
}
FString Filename = IFileManager::Get().ConvertToAbsolutePathForExternalAppForRead(*PackagePathNames[PackageIndex]);
if ( (PackageFilter&NORMALIZE_ExcludeDeveloperPackages) != 0 )
{
if (Filename.StartsWith(DeveloperFolder))
{
PackagePathNames.RemoveAt(PackageIndex);
continue;
}
}
else if ( (PackageFilter&NORMALIZE_ExcludeNonDeveloperPackages) != 0 )
{
if (!Filename.StartsWith(DeveloperFolder))
{
PackagePathNames.RemoveAt(PackageIndex);
continue;
}
}
}
}
if ( (PackageFilter&NORMALIZE_ResetExistingLoaders) != 0 )
{
// reset the loaders for the packages we want to load so that we don't find the wrong version of the file
for ( int32 PackageIndex = 0; PackageIndex < PackageNames.Num(); PackageIndex++ )
{
// (otherwise, attempting to run a commandlet on e.g. Engine.xxx will always return results for Engine.u instead)
const FString& PackageName = FPackageName::PackageFromPath(*PackageNames[PackageIndex]);
UPackage* ExistingPackage = FindObject<UPackage>(NULL, *PackageName, true);
if ( ExistingPackage != NULL )
{
ResetLoaders(ExistingPackage);
}
}
}
return true;
}
/**
* Helper function to save a package that may or may not be a map package
*
* @param Package The package to save
* @param Filename The location to save the package to
* @param KeepObjectFlags Objects with any these flags will be kept when saving even if unreferenced.
* @param ErrorDevice the output device to use for warning and error messages
* @param LinkerToConformAgainst
* @param optional linker to use as a base when saving Package; if specified, all common names, imports and exports
* in Package will be sorted in the same order as the corresponding entries in the LinkerToConformAgainst
* @return true if successful
*/
bool SavePackageHelper(UPackage* Package, FString Filename, EObjectFlags KeepObjectFlags, FOutputDevice* ErrorDevice, ULinkerLoad* LinkerToConformAgainst, ESaveFlags SaveFlags)
{
// look for a world object in the package (if there is one, there's a map)
UWorld* World = UWorld::FindWorldInPackage(Package);
bool bSavedCorrectly;
if (World)
{
bSavedCorrectly = GEditor->SavePackage(Package, World, RF_NoFlags, *Filename, ErrorDevice, LinkerToConformAgainst, false, true, SaveFlags);
}
else
{
bSavedCorrectly = GEditor->SavePackage(Package, NULL, KeepObjectFlags, *Filename, ErrorDevice, LinkerToConformAgainst, false, true, SaveFlags);
}
// return success
return bSavedCorrectly;
}
/**
* Policy that marks Asset Sets via the CollectionManager module
*/
class FCollectionPolicy
{
public:
static bool CreateAssetSet(FName InSetName, ECollectionShareType::Type InSetType)
{
FCollectionManagerModule& CollectionManagerModule = FModuleManager::LoadModuleChecked<FCollectionManagerModule>(TEXT("CollectionManager"));
return CollectionManagerModule.Get().CreateCollection(InSetName, InSetType);
}
static bool DestroyAssetSet(FName InSetName, ECollectionShareType::Type InSetType )
{
FCollectionManagerModule& CollectionManagerModule = FModuleManager::LoadModuleChecked<FCollectionManagerModule>(TEXT("CollectionManager"));
return CollectionManagerModule.Get().DestroyCollection(InSetName, InSetType);
}
static bool RemoveAssetsFromSet(FName InSetName, ECollectionShareType::Type InSetType, const TArray<FName>& InAssetPathNames )
{
FCollectionManagerModule& CollectionManagerModule = FModuleManager::LoadModuleChecked<FCollectionManagerModule>(TEXT("CollectionManager"));
return CollectionManagerModule.Get().RemoveFromCollection(InSetName, InSetType, InAssetPathNames);
}
static bool AddAssetsToSet(FName InSetName, ECollectionShareType::Type InSetType, const TArray<FName>& InAssetPathNames )
{
FCollectionManagerModule& CollectionManagerModule = FModuleManager::LoadModuleChecked<FCollectionManagerModule>(TEXT("CollectionManager"));
return CollectionManagerModule.Get().AddToCollection(InSetName, InSetType, InAssetPathNames);
}
static bool QueryAssetsInSet(FName InSetName, ECollectionShareType::Type InSetType, TArray<FName>& OutAssetPathNames )
{
FCollectionManagerModule& CollectionManagerModule = FModuleManager::LoadModuleChecked<FCollectionManagerModule>(TEXT("CollectionManager"));
return CollectionManagerModule.Get().GetAssetsInCollection(InSetName, InSetType, OutAssetPathNames);
}
};
template <class AssetSetPolicy>
bool FContentHelper::CreateAssetSet(FName InSetName, ECollectionShareType::Type InSetType )
{
return AssetSetPolicy::CreateAssetSet(InSetName, InSetType);
}
/** Clears the content of a Tag or Collection */
template <class AssetSetPolicy>
bool FContentHelper::ClearAssetSet(FName InSetName, ECollectionShareType::Type InSetType )
{
if (bInitialized == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper is not initialized."));
return false;
}
if ( AssetSetPolicy::DestroyAssetSet( InSetName, InSetType ) == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to destroy collection %s."), *InSetName.ToString());
return false;
}
return true;
}
/** Sets the contents of a Tag or Collection to be the InAssetList. Assets not mentioned in the list will be untagged. */
template <class AssetSetPolicy>
bool FContentHelper::AssignSetContent(FName InSetName, ECollectionShareType::Type InType, const TArray<FName>& InAssetList )
{
bool bResult = true;
if (bInitialized == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper is not initialized."));
return false;
}
// We ALWAYS want to create the collection.
// Even when there is nothing to add, it will indicate the operation was a success.
// For example, if a commandlet is run and a collection isn't generated, it would
// not be clear whether the commandlet actually completed successfully.
if (AssetSetPolicy::CreateAssetSet(InSetName, InType) == true)
{
// If there is nothing to update, we are done.
if (InAssetList.Num() >= 0)
{
bool bAddCompleteInAssetList = true;
TArray<FName> AssetsInCollection;
AssetSetPolicy::QueryAssetsInSet(InSetName, InType, AssetsInCollection);
int32 CurrentAssetCount = AssetsInCollection.Num();
if (CurrentAssetCount != 0)
{
// Generate the lists
TArray<FName> TrueAddList;
TArray<FName> TrueRemoveList;
// See how many items are really being added/removed
for (int32 CheckIdx = 0; CheckIdx < AssetsInCollection.Num(); CheckIdx++)
{
FName CheckAsset = AssetsInCollection[CheckIdx];
if (InAssetList.Find(CheckAsset) != INDEX_NONE)
{
TrueAddList.AddUnique(CheckAsset);
}
else
{
TrueRemoveList.AddUnique(CheckAsset);
}
}
if ((TrueRemoveList.Num() + TrueAddList.Num()) < CurrentAssetCount)
{
// Remove and add only the required assets.
bAddCompleteInAssetList = false;
if (TrueRemoveList.Num() > 0)
{
if (AssetSetPolicy::RemoveAssetsFromSet(InSetName, InType, TrueRemoveList) == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to remove assets from collection %s."), *InSetName.ToString());
bResult = false;
}
}
if (TrueAddList.Num() > 0)
{
if (AssetSetPolicy::AddAssetsToSet(InSetName, InType, TrueAddList) == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to add assets to collection %s."), *InSetName.ToString());
bResult = false;
}
}
}
else
{
// Clear the collection and fall into the add all case
bAddCompleteInAssetList = ClearAssetSet<AssetSetPolicy>(InSetName, InType);
if (bAddCompleteInAssetList == false)
{
// this is a problem!!!
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to clear assets for collection %s."), *InSetName.ToString());
bResult = false;
}
}
}
if (bAddCompleteInAssetList == true)
{
// Just add 'em all...
if (AssetSetPolicy::AddAssetsToSet(InSetName, InType, InAssetList) == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to add assets to collection %s."), *InSetName.ToString());
bResult = false;
}
}
}
}
else
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to create collection %s."), *InSetName.ToString());
bResult = false;
}
return bResult;
}
/** Add and remove assets for the specified Tag or Connection. Assets from InAddList are added; assets from InRemoveList are removed. */
template <class AssetSetPolicy>
bool FContentHelper::UpdateSetContent(FName InSetName, ECollectionShareType::Type InType, const TArray<FName>& InAddList, const TArray<FName>& InRemoveList )
{
bool bResult = true;
if (bInitialized == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper is not initialized."));
return false;
}
// We ALWAYS want to create the collection.
// Even when there is nothing to add, it will indicate the operation was a success.
// For example, if a commandlet is run and a collection isn't generated, it would
// not be clear whether the commandlet actually completed successfully.
if (AssetSetPolicy::CreateAssetSet(InSetName, InType) == true)
{
// If there is nothing to update, we are done.
if ((InAddList.Num() >= 0) || (InRemoveList.Num() >= 0))
{
TArray<FName> AssetsInCollection;
AssetSetPolicy::QueryAssetsInSet(InSetName, InType, AssetsInCollection);
if (AssetsInCollection.Num() != 0)
{
// Clean up the lists
TArray<FName> TrueAddList;
TArray<FName> TrueRemoveList;
// Generate the true Remove list, only removing items that are actually in the collection.
for (int32 RemoveIdx = 0; RemoveIdx < InRemoveList.Num(); RemoveIdx++)
{
if (AssetsInCollection.Contains(InRemoveList[RemoveIdx]) == true)
{
TrueRemoveList.AddUnique(InRemoveList[RemoveIdx]);
}
}
if (TrueRemoveList.Num() > 0)
{
if (AssetSetPolicy::RemoveAssetsFromSet(InSetName, InType, TrueRemoveList) == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to remove assets from collection %s."), *InSetName.ToString());
bResult = false;
}
}
// Generate the true Add list, only adding items that are not already in the collection.
for (int32 AddIdx = 0; AddIdx < InAddList.Num(); AddIdx++)
{
if (AssetsInCollection.Contains(InAddList[AddIdx]) == false)
{
TrueAddList.AddUnique(InAddList[AddIdx]);
}
}
if (TrueAddList.Num() > 0)
{
if (AssetSetPolicy::AddAssetsToSet(InSetName, InType, TrueAddList) == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to add assets to collection %s."), *InSetName.ToString());
bResult = false;
}
}
}
else
{
// Just add 'em all...
if (AssetSetPolicy::AddAssetsToSet(InSetName, InType, InAddList) == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to add assets to collection %s."), *InSetName.ToString());
bResult = false;
}
}
}
}
else
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper failed to create collection %s."), *InSetName.ToString());
bResult = false;
}
return bResult;
}
/** Get the list of all assets in the specified Collection or Tag */
template <class AssetSetPolicy>
bool FContentHelper::QuerySetContent(FName InSetName, ECollectionShareType::Type InType, TArray<FName>& OutAssetPathNames)
{
if (bInitialized == false)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Collection Helper is not initialized."));
return false;
}
return AssetSetPolicy::QueryAssetsInSet(InSetName, InType, OutAssetPathNames);
}
/**
* Initialize the Collection helper
*
* @return bool true if successful, false if failed
*/
bool FContentHelper::Initialize()
{
// We no longer need to initialize anything. Keep this here in case we need to in the future.
bInitialized = true;
return bInitialized;
}
/**
* Shutdown the collection helper
*/
void FContentHelper::Shutdown()
{
// We no longer need to shut down anything. Keep this here in case we need to in the future.
bInitialized = false;
}
bool FContentHelper::CreateCollection(FName CollectionName, ECollectionShareType::Type InType)
{
return this->CreateAssetSet<FCollectionPolicy>(CollectionName, InType);
}
/**
* Clear the given collection
*
* @param InCollectionName The name of the collection to create
* @param InType Type of collection
*
* @return bool true if successful, false if failed
*/
bool FContentHelper::ClearCollection(FName InCollectionName, ECollectionShareType::Type InType)
{
return this->ClearAssetSet<FCollectionPolicy>( InCollectionName, InType );
}
/**
* Fill the given collection with the given list of assets
*
* @param InCollectionName The name of the collection to fill
* @param InType Type of collection
* @param InAssetList The list of items to fill the collection with (can be empty)
*
* @return bool true if successful, false if not.
*/
bool FContentHelper::SetCollection(FName InCollectionName, ECollectionShareType::Type InType, const TArray<FName>& InAssetList)
{
return this->AssignSetContent<FCollectionPolicy>(InCollectionName, InType, InAssetList);
}
/**
* Update the given collection with the lists of adds/removes
*
* @param InCollectionName The name of the collection to update
* @param InType Type of collection
* @param InAddList The list of items to ADD to the collection (can be empty)
* @param InRemoveList The list of items to REMOVE from the collection (can be empty)
*
* @return bool true if successful, false if not.
*/
bool FContentHelper::UpdateCollection(FName InCollectionName, ECollectionShareType::Type InType, const TArray<FName>& InAddList, const TArray<FName>& InRemoveList)
{
return this->UpdateSetContent<FCollectionPolicy>( InCollectionName, InType, InAddList, InRemoveList );
}
/**
* Retrieve the assets contained in the given collection.
*
* @param InCollectionName Name of collection to query
* @param InType Type of collection
* @param OutAssetPathNames The assets contained in the collection
*
* @return True if collection was created successfully
*/
bool FContentHelper::QueryAssetsInCollection(FName InCollectionName, ECollectionShareType::Type InType, TArray<FName>& OutAssetPathNames)
{
return this->QuerySetContent<FCollectionPolicy>(InCollectionName, InType, OutAssetPathNames);
}
/*-----------------------------------------------------------------------------
ULoadPackageCommandlet
-----------------------------------------------------------------------------*/
ULoadPackageCommandlet::ULoadPackageCommandlet(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
LogToConsole = false;
}
bool ULoadPackageCommandlet::ParseLoadListFile(FString& LoadListFilename, TArray<FString>& Tokens)
{
//Open file
FString Data;
if (FFileHelper::LoadFileToString(Data, *LoadListFilename) == true)
{
const TCHAR* Ptr = *Data;
FString StrLine;
while (FParse::Line(&Ptr, StrLine))
{
//UE_LOG(LogPackageUtilities, Log, TEXT("Read in: %s"), *StrLine);
Tokens.AddUnique(StrLine);
}
// debugging...
//UE_LOG(LogPackageUtilities, Log, TEXT("\nPACKAGES TO LOAD:"));
for (int32 TokenIdx = 0; TokenIdx < Tokens.Num(); TokenIdx++)
{
//UE_LOG(LogPackageUtilities, Log, TEXT("\t%s"), *(Tokens(TokenIdx)));
}
return (Tokens.Num() > 0);
}
return false;
}
int32 ULoadPackageCommandlet::Main( const FString& Params )
{
TArray<FString> Tokens, Switches;
ParseCommandLine(*Params, Tokens, Switches);
bool bLoadAllPackages = Switches.Contains(TEXT("ALL"));
bool bCheckForLegacyPackages = Switches.Contains(TEXT("CheckForLegacyPackages"));
bool bFast = Switches.Contains(TEXT("FAST"));
int32 MinVersion = MAX_int32;
// Check for a load list file...
for (int32 TokenIdx = 0; TokenIdx < Tokens.Num(); TokenIdx++)
{
FString LoadListFilename = TEXT("");
if (FParse::Value(*(Tokens[TokenIdx]), TEXT("LOADLIST="), LoadListFilename))
{
// Found one - this will be a list of packages to load
//UE_LOG(LogPackageUtilities, Log, TEXT("LoadList in file %s"), *LoadListFilename);
TArray<FString> TempTokens;
if (ParseLoadListFile(LoadListFilename, TempTokens) == true)
{
bLoadAllPackages = false;
Tokens.Empty(TempTokens.Num());
Tokens = TempTokens;
}
}
}
TArray<FString> FilesInPath;
if ( bLoadAllPackages )
{
Tokens.Empty(2);
Tokens.Add(FString("*") + FPackageName::GetAssetPackageExtension());
Tokens.Add(FString("*") + FPackageName::GetMapPackageExtension());
}
if ( Tokens.Num() == 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("You must specify a package name (multiple files can be delimited by spaces) or wild-card, or specify -all to include all registered packages"));
return 1;
}
uint8 PackageFilter = NORMALIZE_DefaultFlags;
if ( Switches.Contains(TEXT("MAPSONLY")) )
{
PackageFilter |= NORMALIZE_ExcludeContentPackages;
}
// assume the first token is the map wildcard/pathname
TArray<FString> Unused;
for ( int32 TokenIndex = 0; TokenIndex < Tokens.Num(); TokenIndex++ )
{
TArray<FString> TokenFiles;
if ( !NormalizePackageNames( Unused, TokenFiles, Tokens[TokenIndex], PackageFilter) )
{
UE_LOG(LogPackageUtilities, Display, TEXT("No packages found for parameter %i: '%s'"), TokenIndex, *Tokens[TokenIndex]);
continue;
}
FilesInPath += TokenFiles;
}
if ( FilesInPath.Num() == 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("No files found."));
return 1;
}
GIsClient = !Switches.Contains(TEXT("NOCLIENT"));
GIsServer = !Switches.Contains(TEXT("NOSERVER"));
GIsEditor = !Switches.Contains(TEXT("NOEDITOR"));
for( int32 FileIndex = 0; FileIndex < FilesInPath.Num(); FileIndex++ )
{
const FString& Filename = FilesInPath[FileIndex];
UE_LOG(LogPackageUtilities, Warning, TEXT("Loading %s"), *Filename );
const FString& PackageName = FPackageName::PackageFromPath(*Filename);
UPackage* Package = FindObject<UPackage>(NULL, *PackageName, true);
if ( Package != NULL && !bLoadAllPackages )
{
ResetLoaders(Package);
}
if (bCheckForLegacyPackages)
{
BeginLoad();
ULinkerLoad* Linker = GetPackageLinker(NULL,*Filename,LOAD_NoVerify,NULL,NULL);
EndLoad();
MinVersion = FMath::Min<int32>(MinVersion, Linker->Summary.GetFileVersionUE4());
}
else
{
Package = LoadPackage( NULL, *Filename, LOAD_None );
if( Package == NULL )
{
UE_LOG(LogPackageUtilities, Error, TEXT("Error loading %s!"), *Filename );
}
}
if (!bFast || FileIndex % 100 == 99)
{
CollectGarbage( RF_Native );
}
}
GIsEditor = GIsServer = GIsClient = true;
if (bCheckForLegacyPackages)
{
UE_LOG(LogPackageUtilities, Log, TEXT("%d minimum UE4 version number."), MinVersion );
}
return 0;
}
/*-----------------------------------------------------------------------------
UPkgInfo commandlet.
-----------------------------------------------------------------------------*/
struct FExportInfo
{
FObjectExport Export;
int32 ExportIndex;
FString PathName;
FString OuterPathName;
FExportInfo( ULinkerLoad* Linker, int32 InIndex )
: Export(Linker->ExportMap[InIndex]), ExportIndex(InIndex)
, OuterPathName(TEXT("NULL"))
{
PathName = Linker->GetExportPathName(ExportIndex);
SetOuterPathName(Linker);
}
void SetOuterPathName( ULinkerLoad* Linker )
{
if ( !Export.OuterIndex.IsNull() )
{
OuterPathName = Linker->GetPathName(Export.OuterIndex);
}
}
};
namespace
{
enum EExportSortType
{
EXPORTSORT_ExportSize,
EXPORTSORT_ExportIndex,
EXPORTSORT_ObjectPathname,
EXPORTSORT_OuterPathname,
EXPORTSORT_MAX
};
struct FObjectExport_Sorter
{
static EExportSortType SortPriority[EXPORTSORT_MAX];
// Comparison method
bool operator()( const FExportInfo& A, const FExportInfo& B ) const
{
int32 Result = 0;
for ( int32 PriorityType = 0; PriorityType < EXPORTSORT_MAX; PriorityType++ )
{
switch ( SortPriority[PriorityType] )
{
case EXPORTSORT_ExportSize:
Result = B.Export.SerialSize - A.Export.SerialSize;
break;
case EXPORTSORT_ExportIndex:
Result = A.ExportIndex - B.ExportIndex;
break;
case EXPORTSORT_ObjectPathname:
Result = A.PathName.Len() - B.PathName.Len();
if ( Result == 0 )
{
Result = FCString::Stricmp(*A.PathName, *B.PathName);
}
break;
case EXPORTSORT_OuterPathname:
Result = A.OuterPathName.Len() - B.OuterPathName.Len();
if ( Result == 0 )
{
Result = FCString::Stricmp(*A.OuterPathName, *B.OuterPathName);
}
break;
case EXPORTSORT_MAX:
return !!Result;
}
if ( Result != 0 )
{
break;
}
}
return Result < 0;
}
};
EExportSortType FObjectExport_Sorter::SortPriority[EXPORTSORT_MAX] =
{ EXPORTSORT_ExportIndex, EXPORTSORT_ExportSize, EXPORTSORT_OuterPathname, EXPORTSORT_ObjectPathname };
}
/**
* Writes information about the linker to the log.
*
* @param InLinker if specified, changes this reporter's Linker before generating the report.
*/
void FPkgInfoReporter_Log::GeneratePackageReport( ULinkerLoad* InLinker/*=NULL*/ )
{
check(InLinker);
if ( InLinker != NULL )
{
SetLinker(InLinker);
}
if ( PackageCount++ > 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT(""));
}
// Display information about the package.
FName LinkerName = Linker->LinkerRoot->GetFName();
// Display summary info.
UE_LOG(LogPackageUtilities, Warning, TEXT("********************************************") );
UE_LOG(LogPackageUtilities, Warning, TEXT("Package '%s' Summary"), *LinkerName.ToString() );
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t Filename: %s"), *Linker->Filename);
UE_LOG(LogPackageUtilities, Warning, TEXT("\t File Version: %i"), Linker->UE3Ver() );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t Engine Version: %s"), *Linker->Summary.EngineVersion.ToString());
UE_LOG(LogPackageUtilities, Warning, TEXT("\t PackageFlags: %X"), Linker->Summary.PackageFlags );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t NameCount: %d"), Linker->Summary.NameCount );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t NameOffset: %d"), Linker->Summary.NameOffset );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t ImportCount: %d"), Linker->Summary.ImportCount );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t ImportOffset: %d"), Linker->Summary.ImportOffset );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t ExportCount: %d"), Linker->Summary.ExportCount );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t ExportOffset: %d"), Linker->Summary.ExportOffset );
UE_LOG(LogPackageUtilities, Warning, TEXT("\tCompression Flags: %X"), Linker->Summary.CompressionFlags);
UE_LOG(LogPackageUtilities, Warning, TEXT("\t Custom Versions:\n%s"), *Linker->Summary.GetCustomVersionContainer().ToString("\t\t"));
FString szGUID = Linker->Summary.Guid.ToString();
UE_LOG(LogPackageUtilities, Warning, TEXT("\t Guid: %s"), *szGUID );
GWarn->Log ( TEXT("\t Generations:"));
for( int32 i = 0; i < Linker->Summary.Generations.Num(); ++i )
{
const FGenerationInfo& generationInfo = Linker->Summary.Generations[ i ];
UE_LOG(LogPackageUtilities, Warning,TEXT("\t\t\t%d) ExportCount=%d, NameCount=%d "), i, generationInfo.ExportCount, generationInfo.NameCount );
}
if( (InfoFlags&PKGINFO_Chunks) != 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
GWarn->Log ( TEXT("Compression Chunks"));
GWarn->Log ( TEXT("=========="));
for ( int32 ChunkIndex = 0; ChunkIndex < Linker->Summary.CompressedChunks.Num(); ChunkIndex++ )
{
FCompressedChunk& Chunk = Linker->Summary.CompressedChunks[ChunkIndex];
GWarn->Log ( TEXT("\t*************************"));
UE_LOG(LogPackageUtilities, Warning, TEXT("\tChunk %d:"), ChunkIndex );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\tUncompressedOffset: %d"), Chunk.UncompressedOffset);
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t UncompressedSize: %d"), Chunk.UncompressedSize);
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t CompressedOffset: %d"), Chunk.CompressedOffset);
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t CompressedSize: %d"), Chunk.CompressedSize);
}
}
if( (InfoFlags&PKGINFO_Names) != 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
GWarn->Log ( TEXT("Name Map"));
GWarn->Log ( TEXT("========"));
for( int32 i = 0; i < Linker->NameMap.Num(); ++i )
{
FName& name = Linker->NameMap[ i ];
UE_LOG(LogPackageUtilities, Warning, TEXT("\t%d: Name '%s' Index %d [Internal: %s, %d]"), i, *name.ToString(), name.GetIndex(), *name.GetPlainNameString(), name.GetNumber() );
}
}
// if we _only_ want name info, skip this part completely
if ( InfoFlags != PKGINFO_Names )
{
if( (InfoFlags&PKGINFO_Imports) != 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
GWarn->Log ( TEXT("Import Map"));
GWarn->Log ( TEXT("=========="));
}
TArray<FName> DependentPackages;
for( int32 i = 0; i < Linker->ImportMap.Num(); ++i )
{
FObjectImport& import = Linker->ImportMap[ i ];
FName PackageName = NAME_None;
FName OuterName = NAME_None;
if ( !import.OuterIndex.IsNull() )
{
if ( (InfoFlags&PKGINFO_Paths) != 0 )
{
OuterName = *Linker->GetPathName(import.OuterIndex);
}
else
{
OuterName = Linker->ImpExp(import.OuterIndex).ObjectName;
}
// Find the package which contains this import. import.SourceLinker is cleared in EndLoad, so we'll need to do this manually now.
FPackageIndex OutermostLinkerIndex = import.OuterIndex;
for ( FPackageIndex LinkerIndex = import.OuterIndex; !LinkerIndex.IsNull(); )
{
OutermostLinkerIndex = LinkerIndex;
LinkerIndex = Linker->ImpExp(LinkerIndex).OuterIndex;
}
check(!OutermostLinkerIndex.IsNull());
PackageName = Linker->ImpExp(OutermostLinkerIndex).ObjectName;
}
if ( (InfoFlags&PKGINFO_Imports) != 0 )
{
GWarn->Log ( TEXT("\t*************************"));
UE_LOG(LogPackageUtilities, Display, TEXT("\tImport %d: '%s'"), i, *import.ObjectName.ToString() );
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t Outer: '%s' (%d)"), *OuterName.ToString(), import.OuterIndex.ForDebugging());
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t Package: '%s'"), *PackageName.ToString());
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t Class: '%s'"), *import.ClassName.ToString() );
UE_LOG(LogPackageUtilities, Display, TEXT("\t\tClassPackage: '%s'"), *import.ClassPackage.ToString() );
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t XObject: %s"), import.XObject ? TEXT("VALID") : TEXT("NULL"));
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t SourceIndex: %d"), import.SourceIndex );
// dump depends info
if (InfoFlags & PKGINFO_Depends)
{
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t All Depends:"));
TSet<FDependencyRef> AllDepends;
Linker->GatherImportDependencies(i, AllDepends);
int32 DependsIndex = 0;
for(TSet<FDependencyRef>::TConstIterator It(AllDepends);It;++It)
{
const FDependencyRef& Ref = *It;
if (Ref.Linker)
{
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t\t%i) %s"), DependsIndex++, *Ref.Linker->GetExportFullName(Ref.ExportIndex));
}
else
{
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t\t%i) NULL"), DependsIndex++);
}
}
}
}
if ( PackageName == NAME_None && import.ClassName == NAME_Package )
{
PackageName = import.ObjectName;
}
if ( PackageName != NAME_None && PackageName != LinkerName )
{
DependentPackages.AddUnique(PackageName);
}
if ( import.ClassPackage != NAME_None && import.ClassPackage != LinkerName )
{
DependentPackages.AddUnique(import.ClassPackage);
}
}
if ( DependentPackages.Num() )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
UE_LOG(LogPackageUtilities, Warning, TEXT("\tPackages referenced by %s:"), *LinkerName.ToString());
for ( int32 i = 0; i < DependentPackages.Num(); i++ )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t%i) %s"), i, *DependentPackages[i].ToString());
}
}
}
if( (InfoFlags&PKGINFO_Exports) != 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
GWarn->Log ( TEXT("Export Map"));
GWarn->Log ( TEXT("=========="));
if ( (InfoFlags&PKGINFO_Compact) == 0 )
{
TArray<FExportInfo> SortedExportMap;
SortedExportMap.Empty(Linker->ExportMap.Num());
for( int32 i = 0; i < Linker->ExportMap.Num(); ++i )
{
new(SortedExportMap) FExportInfo(Linker, i);
}
FString SortingParms;
if ( FParse::Value(FCommandLine::Get(), TEXT("SORT="), SortingParms) )
{
TArray<FString> SortValues;
SortingParms.ParseIntoArray(&SortValues, TEXT(","), true);
for ( int32 i = 0; i < EXPORTSORT_MAX; i++ )
{
if ( i < SortValues.Num() )
{
const FString Value = SortValues[i];
if ( Value == TEXT("index") )
{
FObjectExport_Sorter::SortPriority[i] = EXPORTSORT_ExportIndex;
}
else if ( Value == TEXT("size") )
{
FObjectExport_Sorter::SortPriority[i] = EXPORTSORT_ExportSize;
}
else if ( Value == TEXT("name") )
{
FObjectExport_Sorter::SortPriority[i] = EXPORTSORT_ObjectPathname;
}
else if ( Value == TEXT("outer") )
{
FObjectExport_Sorter::SortPriority[i] = EXPORTSORT_OuterPathname;
}
}
else
{
FObjectExport_Sorter::SortPriority[i] = EXPORTSORT_MAX;
}
}
}
SortedExportMap.Sort( FObjectExport_Sorter() );
for( int32 SortedIndex = 0; SortedIndex < SortedExportMap.Num(); ++SortedIndex )
{
GWarn->Log ( TEXT("\t*************************"));
FExportInfo& ExportInfo = SortedExportMap[SortedIndex];
FObjectExport& Export = ExportInfo.Export;
UE_LOG(LogPackageUtilities, Warning, TEXT("\tExport %d: '%s'"), ExportInfo.ExportIndex, *Export.ObjectName.ToString() );
// find the name of this object's class
FPackageIndex ClassIndex = Export.ClassIndex;
FName ClassName = ClassIndex.IsNull() ? FName(NAME_Class) : Linker->ImpExp(ClassIndex).ObjectName;
// find the name of this object's parent...for UClasses, this will be the parent class
// for UFunctions, this will be the SuperFunction, if it exists, etc.
FString ParentName;
if ( !Export.SuperIndex.IsNull() )
{
if ( (InfoFlags&PKGINFO_Paths) != 0 )
{
ParentName = *Linker->GetPathName(Export.SuperIndex);
}
else
{
ParentName = Linker->ImpExp(Export.SuperIndex).ObjectName.ToString();
}
}
// find the name of this object's Outer. For UClasses, this will generally be the
// top-level package itself. For properties, a UClass, etc.
FString OuterName;
if ( !Export.OuterIndex.IsNull() )
{
if ( (InfoFlags&PKGINFO_Paths) != 0 )
{
OuterName = *Linker->GetPathName(Export.OuterIndex);
}
else
{
OuterName = Linker->ImpExp(Export.OuterIndex).ObjectName.ToString();
}
}
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t Class: '%s' (%i)"), *ClassName.ToString(), ClassIndex.ForDebugging() );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t Parent: '%s' (%d)"), *ParentName, Export.SuperIndex.ForDebugging() );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t Outer: '%s' (%d)"), *OuterName, Export.OuterIndex.ForDebugging() );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t Pkg Guid: %s"), *Export.PackageGuid.ToString());
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t ObjectFlags: 0x%08X"), (uint32)Export.ObjectFlags );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t Size: %d"), Export.SerialSize );
if ( !bHideOffsets )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t Offset: %d"), Export.SerialOffset );
}
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t Object: %s"), Export.Object ? TEXT("VALID") : TEXT("NULL"));
if ( !bHideOffsets )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t HashNext: %d"), Export.HashNext );
}
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t bNotForClient: %d"), Export.bNotForClient );
UE_LOG(LogPackageUtilities, Warning, TEXT("\t\t bNotForServer: %d"), Export.bNotForServer );
// dump depends info
if (InfoFlags & PKGINFO_Depends)
{
if (ExportInfo.ExportIndex < Linker->DependsMap.Num())
{
TArray<FPackageIndex>& Depends = Linker->DependsMap[ExportInfo.ExportIndex];
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t DependsMap:"));
for (int32 DependsIndex = 0; DependsIndex < Depends.Num(); DependsIndex++)
{
UE_LOG(LogPackageUtilities, Warning,TEXT("\t\t\t%i) %s (%i)"),
DependsIndex,
*Linker->GetFullImpExpName(Depends[DependsIndex]),
Depends[DependsIndex].ForDebugging()
);
}
TSet<FDependencyRef> AllDepends;
Linker->GatherExportDependencies(ExportInfo.ExportIndex, AllDepends);
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t All Depends:"));
int32 DependsIndex = 0;
for(TSet<FDependencyRef>::TConstIterator It(AllDepends);It;++It)
{
const FDependencyRef& Ref = *It;
if (Ref.Linker)
{
UE_LOG(LogPackageUtilities, Warning,TEXT("\t\t\t%i) %s (%i)"),
DependsIndex++,
*Ref.Linker->GetExportFullName(Ref.ExportIndex),
Ref.ExportIndex);
}
else
{
UE_LOG(LogPackageUtilities, Warning,TEXT("\t\t\t%i) NULL (%i)"),
DependsIndex++,
Ref.ExportIndex);
}
}
}
}
}
}
else
{
for( int32 ExportIndex=0; ExportIndex<Linker->ExportMap.Num(); ExportIndex++ )
{
const FObjectExport& Export = Linker->ExportMap[ExportIndex];
UE_LOG(LogPackageUtilities, Warning, TEXT(" %8i %10i %32s %s"), ExportIndex, Export.SerialSize,
*(Linker->GetExportClassName(ExportIndex).ToString()),
(InfoFlags&PKGINFO_Paths) != 0 ? *Linker->GetExportPathName(ExportIndex) : *Export.ObjectName.ToString());
}
}
}
if( (InfoFlags&PKGINFO_Thumbs) != 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
GWarn->Log ( TEXT("Thumbnail Data"));
GWarn->Log ( TEXT("=========="));
if ( Linker->SerializeThumbnails(true) )
{
if ( Linker->LinkerRoot->HasThumbnailMap() )
{
FThumbnailMap& LinkerThumbnails = Linker->LinkerRoot->AccessThumbnailMap();
int32 MaxObjectNameSize = 0;
for ( TMap<FName, FObjectThumbnail>::TIterator It(LinkerThumbnails); It; ++It )
{
FName& ObjectPathName = It.Key();
MaxObjectNameSize = FMath::Max(MaxObjectNameSize, ObjectPathName.ToString().Len());
}
int32 ThumbIdx=0;
for ( TMap<FName, FObjectThumbnail>::TIterator It(LinkerThumbnails); It; ++It )
{
FName& ObjectFullName = It.Key();
FObjectThumbnail& Thumb = It.Value();
UE_LOG(LogPackageUtilities, Warning,TEXT("\t\t%i) %*s: %ix%i\t\tImage Data:%i bytes"), ThumbIdx++, MaxObjectNameSize, *ObjectFullName.ToString(), Thumb.GetImageWidth(), Thumb.GetImageHeight(), Thumb.GetCompressedDataSize());
}
}
else
{
UE_LOG(LogPackageUtilities, Warning,TEXT("%s has no thumbnail map!"), *LinkerName.ToString());
}
}
else
{
if ( Linker->Summary.ThumbnailTableOffset > 0 )
{
UE_LOG(LogPackageUtilities, Warning,TEXT("Failed to load thumbnails for package %s!"), *LinkerName.ToString());
}
}
}
if( (InfoFlags&PKGINFO_Lazy) != 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
GWarn->Log ( TEXT("Lazy Pointer Data"));
GWarn->Log ( TEXT("==============="));
}
if( (InfoFlags&PKGINFO_AssetRegistry) != 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("--------------------------------------------") );
GWarn->Log ( TEXT("Asset Registry Data"));
GWarn->Log ( TEXT("=========="));
if( Linker->Summary.AssetRegistryDataOffset > 0 )
{
// Seek to the AssetRegistry table of contents
Linker->Loader->Seek( Linker->Summary.AssetRegistryDataOffset );
// Load the number of assets in the tag map
int32 AssetCount = 0;
*Linker << AssetCount;
UE_LOG(LogPackageUtilities, Display, TEXT("Number of assets with Asset Registry data: %d"), AssetCount );
// If there are any Asset Registry tags, print them
for (int32 AssetIdx = 0; AssetIdx < AssetCount; ++AssetIdx)
{
// Display the asset class and path
FString ObjectPath;
FString ObjectClassName;
int32 TagCount = 0;
*Linker << ObjectPath;
*Linker << ObjectClassName;
*Linker << TagCount;
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t%d) %s'%s' (%d Tags)"), AssetIdx, *ObjectClassName, *ObjectPath, TagCount );
// Now display all tags on this asset
for (int32 TagIdx = 0; TagIdx < TagCount; ++TagIdx)
{
FString Key;
FString Value;
*Linker << Key;
*Linker << Value;
UE_LOG(LogPackageUtilities, Display, TEXT("\t\t\t\"%s\": \"%s\""), *Key, *Value );
}
}
}
}
}
UPkgInfoCommandlet::UPkgInfoCommandlet(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
LogToConsole = false;
}
int32 UPkgInfoCommandlet::Main( const FString& Params )
{
// turn off as it makes diffing hard
auto bOldGPrintLogTimes = GPrintLogTimes;
GPrintLogTimes = ELogTimes::None;
const TCHAR* Parms = *Params;
TArray<FString> Tokens, Switches;
ParseCommandLine(Parms, Tokens, Switches);
// find out which type of info we're looking for
uint32 InfoFlags = PKGINFO_None;
if ( Switches.Contains(TEXT("names")) )
{
InfoFlags |= PKGINFO_Names;
}
if ( Switches.Contains(TEXT("imports")) )
{
InfoFlags |= PKGINFO_Imports;
}
if ( Switches.Contains(TEXT("exports")) )
{
InfoFlags |= PKGINFO_Exports;
}
if ( Switches.Contains(TEXT("simple")) )
{
InfoFlags |= PKGINFO_Compact;
}
if ( Switches.Contains(TEXT("chunks")) )
{
InfoFlags |= PKGINFO_Chunks;
}
if ( Switches.Contains(TEXT("depends")) )
{
InfoFlags |= PKGINFO_Depends;
}
if ( Switches.Contains(TEXT("paths")) )
{
InfoFlags |= PKGINFO_Paths;
}
if ( Switches.Contains(TEXT("thumbnails")) )
{
InfoFlags |= PKGINFO_Thumbs;
}
if ( Switches.Contains(TEXT("lazy")) )
{
InfoFlags |= PKGINFO_Lazy;
}
if ( Switches.Contains(TEXT("assetregistry")) )
{
InfoFlags |= PKGINFO_AssetRegistry;
}
if ( Switches.Contains(TEXT("all")) )
{
InfoFlags |= PKGINFO_All;
}
const bool bHideOffsets = Switches.Contains(TEXT("HideOffsets"));
FPkgInfoReporter* Reporter = new FPkgInfoReporter_Log(InfoFlags, bHideOffsets);
TArray<FString> FilesInPath;
if( Switches.Contains(TEXT("AllPackages")) )
{
FEditorFileUtils::FindAllPackageFiles(FilesInPath);
}
else
{
for ( int32 TokenIndex = 0; TokenIndex < Tokens.Num(); TokenIndex++ )
{
FString& PackageWildcard = Tokens[TokenIndex];
TArray<FString> PerTokenFilesInPath;
IFileManager::Get().FindFiles( PerTokenFilesInPath, *PackageWildcard, true, false );
if( PerTokenFilesInPath.Num() == 0 )
{
TArray<FString> Paths;
if ( GConfig->GetArray( TEXT("Core.System"), TEXT("Paths"), Paths, GEngineIni ) > 0 )
{
for ( int32 i = 0; i < Paths.Num(); i++ )
{
IFileManager::Get().FindFiles( PerTokenFilesInPath, *(Paths[i] / PackageWildcard), 1, 0 );
}
}
if ( PerTokenFilesInPath.Num() == 0 )
{
// Check if long package name is provided and if it exists on disk.
FString Filename;
if ( FPackageName::IsValidLongPackageName(PackageWildcard, true) && FPackageName::DoesPackageExist(PackageWildcard, NULL, &Filename) )
{
PerTokenFilesInPath.Add(Filename);
}
}
}
else
{
// re-add the path information so that GetPackageLinker finds the correct version of the file.
FString WildcardPath = PackageWildcard;
for ( int32 FileIndex = 0; FileIndex < PerTokenFilesInPath.Num(); FileIndex++ )
{
PerTokenFilesInPath[FileIndex] = FPaths::GetPath(WildcardPath) / PerTokenFilesInPath[FileIndex];
}
}
if ( PerTokenFilesInPath.Num() == 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("No packages found using '%s'!"), *PackageWildcard);
continue;
}
FilesInPath += PerTokenFilesInPath;
}
}
for( int32 FileIndex = 0; FileIndex < FilesInPath.Num(); FileIndex++ )
{
const FString &Filename = FilesInPath[FileIndex];
{
// reset the loaders for the packages we want to load so that we don't find the wrong version of the file
// (otherwise, attempting to run pkginfo on e.g. Engine.xxx will always return results for Engine.u instead)
const FString& PackageName = FPackageName::PackageFromPath(*Filename);
UPackage* ExistingPackage = FindObject<UPackage>(NULL, *PackageName, true);
if ( ExistingPackage != NULL )
{
ResetLoaders(ExistingPackage);
}
}
BeginLoad();
ULinkerLoad* Linker = GetPackageLinker( NULL, *Filename, LOAD_NoVerify, NULL, NULL );
EndLoad();
if( Linker )
{
Reporter->GeneratePackageReport(Linker);
}
CollectGarbage(RF_Native);
}
// turn off as it makes diffing hard
GPrintLogTimes = bOldGPrintLogTimes;
delete Reporter;
Reporter = NULL;
return 0;
}
/*-----------------------------------------------------------------------------
CompressAnimations Commandlet
-----------------------------------------------------------------------------*/
static int32 AnalyzeCompressionCandidates = 0;
static TArray<FString> PackagesThatCouldNotBeSavedList;
struct AddAllSkeletalMeshesToListFunctor
{
template< typename OBJECTYPE >
void DoIt( UCommandlet* Commandlet, UPackage* Package, TArray<FString>& Tokens, TArray<FString>& Switches )
{
for( TObjectIterator<OBJECTYPE> It; It; ++It )
{
OBJECTYPE* SkelMesh = *It;
SkelMesh->AddToRoot();
}
}
};
/**
*
*/
struct CompressAnimationsFunctor
{
template< typename OBJECTYPE >
void DoIt( UCommandlet* Commandlet, UPackage* Package, TArray<FString>& Tokens, TArray<FString>& Switches )
{
// @todoanim: we expect this won't work properly since it won't have any skeletalmesh,
// but soon, the compression will changed based on skeleton.
// when that happens, this doesn't have to worry about skeletalmesh not loaded
float LastSaveTime = FPlatformTime::Seconds();
bool bDirtyPackage = false;
const FName& PackageName = Package->GetFName();
FString PackageFileName;
FPackageName::DoesPackageExist( PackageName.ToString(), NULL, &PackageFileName );
// Ensure source control is initialized and shut down properly
FScopedSourceControl SourceControl;
const bool bSkipCinematicPackages = Switches.Contains(TEXT("SKIPCINES"));
const bool bSkipLongAnimations = Switches.Contains(TEXT("SKIPLONGANIMS"));
// Reset compression, don't do incremental compression, start from scratch
const bool bResetCompression = Switches.Contains(TEXT("RESETCOMPRESSION"));
/** Clear bDoNotOverrideCompression flag in animations */
const bool bClearNoCompressionOverride = Switches.Contains(TEXT("CLEARNOCOMPRESSIONOVERRIDE"));
/** If we're analyzing, we're not actually going to recompress, so we can skip some significant work. */
const bool bAnalyze = Switches.Contains(TEXT("ANALYZE"));
// See if we can save this package. If we can't, don't bother...
/** if we should auto checkout packages that need to be saved **/
const bool bAutoCheckOut = Switches.Contains(TEXT("AUTOCHECKOUTPACKAGES"));
FSourceControlStatePtr SourceControlState = SourceControl.GetProvider().GetState(PackageFileName, EStateCacheUsage::ForceUpdate);
// check to see if we need to check this package out
if( !bAnalyze && SourceControlState.IsValid() && SourceControlState->CanCheckout() )
{
// Cant check out, check to see why
if (bAutoCheckOut == true)
{
// Checked out by other.. fail :(
if( SourceControlState->IsCheckedOutOther() )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Package (%s) checked out by other, skipping."), *PackageFileName);
PackagesThatCouldNotBeSavedList.Add( PackageFileName );
return;
}
// Package not at head revision
else if ( !SourceControlState->IsCurrent() )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Package (%s) is not at head revision, skipping."), *PackageFileName );
PackagesThatCouldNotBeSavedList.Add( PackageFileName );
return;
}
// Package marked for delete
else if ( SourceControlState->IsDeleted() )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Package (%s) is marked for delete, skipping."), *PackageFileName );
PackagesThatCouldNotBeSavedList.Add( PackageFileName );
return;
}
}
// not allowed to auto check out :(
else
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Package (%s) cannot be checked out. Switch AUTOCHECKOUTPACKAGES not set. Skip."), *PackageFileName);
PackagesThatCouldNotBeSavedList.AddUnique( PackageFileName );
return;
}
}
if (bSkipCinematicPackages && (PackageFileName.Contains(TEXT("CINE"))))
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Package (%s) name contains 'cine' and switch SKIPCINES is set. Skip."), *PackageFileName);
PackagesThatCouldNotBeSavedList.AddUnique( PackageFileName );
return;
}
// Get version number. Bump this up every time you want to recompress all animations.
int32 CompressCommandletVersion = 0;
GConfig->GetInt( TEXT("AnimationCompression"), TEXT("CompressCommandletVersion"), (int32&)CompressCommandletVersion, GEngineIni );
// Count the number of animations to provide some limited progress indication
int32 NumAnimationsInPackage = 0;
for (TObjectIterator<OBJECTYPE> It; It; ++It)
{
++NumAnimationsInPackage;
}
int32 ActiveAnimationIndex = 0;
for (TObjectIterator<OBJECTYPE> It; It; ++It)
{
OBJECTYPE* AnimSeq = *It;
++ActiveAnimationIndex;
if (!AnimSeq->IsIn(Package))
{
continue;
}
// If animation hasn't been compressed, force it.
bool bForceCompression = (AnimSeq->CompressedTrackOffsets.Num() == 0);
// If animation has already been compressed with the commandlet and version is the same. then skip.
// We're only interested in new animations.
if( !bAnalyze && !bForceCompression && AnimSeq->CompressCommandletVersion == CompressCommandletVersion )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Same CompressCommandletVersion (%i) skip animation: %s (%s)"), CompressCommandletVersion, *AnimSeq->GetName(), *AnimSeq->GetFullName());
continue;
}
if( !bAnalyze && !bForceCompression && bSkipLongAnimations && (AnimSeq->NumFrames > 300) )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Animation (%s) has more than 300 frames (%i frames) and SKIPLONGANIMS switch is set. Skipping."), *AnimSeq->GetName(), AnimSeq->NumFrames);
continue;
}
USkeleton * Skeleton = AnimSeq->GetSkeleton();
check (Skeleton);
if( bAnalyze )
{
static int32 NumTotalAnimations = 0;
static int32 NumTotalSize = 0;
static int32 Trans96Savings = 0;
static int32 Trans48Savings = 0;
static int32 Rot96Savings = 0;
static int32 Rot48Savings = 0;
static int32 Scale96Savings = 0;
static int32 Scale48Savings = 0;
static int32 Num96TransTracks = 0;
static int32 Num96RotTracks = 0;
static int32 Num96ScaleTracks = 0;
static int32 Num48TransTracks = 0;
static int32 Num48RotTracks = 0;
static int32 Num48ScaleTracks = 0;
static int32 Num32TransTracks = 0;
static int32 Num32ScaleTracks = 0;
static int32 UnknownTransTrack = 0;
static int32 UnknownRotTrack = 0;
static int32 UnknownScaleTrack = 0;
static int32 RotationOnlySavings = 0;
static int32 RotationOnlyManyKeys = 0;
NumTotalAnimations++;
FArchiveCountMem CountBytesSize( AnimSeq );
int32 ResourceSize = CountBytesSize.GetNum();
NumTotalSize += ResourceSize;
// Looking for PerTrackCompression using 96bit translation compression.
if( AnimSeq->KeyEncodingFormat == AKF_PerTrackCompression && AnimSeq->CompressedByteStream.Num() > 0 )
{
bool bCandidate = false;
for(int32 i=0; i<AnimSeq->TrackToSkeletonMapTable.Num(); i++)
{
const int32 TrackIndex = i;
// Translation
{
// Use the CompressedTrackOffsets stream to find the data addresses
const int32* RESTRICT TrackDataForTransKey = AnimSeq->CompressedTrackOffsets.GetTypedData() + (TrackIndex * 2);
const int32 TransKeysOffset = TrackDataForTransKey[0];
if( TransKeysOffset != INDEX_NONE )
{
const uint8* RESTRICT TrackData = AnimSeq->CompressedByteStream.GetTypedData() + TransKeysOffset + 4;
const int32 Header = *((int32*)(AnimSeq->CompressedByteStream.GetTypedData() + TransKeysOffset));
int32 KeyFormat;
int32 NumKeys;
int32 FormatFlags;
int32 BytesPerKey;
int32 FixedBytes;
FAnimationCompression_PerTrackUtils::DecomposeHeader(Header, /*OUT*/ KeyFormat, /*OUT*/ NumKeys, /*OUT*/ FormatFlags, /*OUT*/BytesPerKey, /*OUT*/ FixedBytes);
if( KeyFormat == ACF_Float96NoW )
{
Num96TransTracks++;
// Determine which components we could let go, and bytes we could save.
const FBox KeyBounds((FVector*)(TrackData + FixedBytes), NumKeys);
const bool bHasX = (FMath::Abs(KeyBounds.Max.X) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.X) >= 0.0002f);
const bool bHasY = (FMath::Abs(KeyBounds.Max.Y) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.Y) >= 0.0002f);
const bool bHasZ = (FMath::Abs(KeyBounds.Max.Z) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.Z) >= 0.0002f);
if( !bHasX )
{
Trans96Savings += (4 * NumKeys);
bCandidate = true;
}
if( !bHasY )
{
Trans96Savings += (4 * NumKeys);
bCandidate = true;
}
if( !bHasZ )
{
Trans96Savings += (4 * NumKeys);
bCandidate = true;
}
}
// Measure savings on 48bits translations
else if( KeyFormat == ACF_Fixed48NoW )
{
Num48TransTracks++;
const int32 SavedBytes = (6 - BytesPerKey) * NumKeys;
if( SavedBytes > 0 )
{
bCandidate = true;
Trans48Savings += SavedBytes;
}
}
else if( KeyFormat == ACF_IntervalFixed32NoW )
{
Num32TransTracks++;
}
else
{
UnknownTransTrack++;
}
// Measure how much we'd save if we used "rotation only" for compression
// root bone is true if BoneTreeIndex == 0
const int32 BoneTreeIndex = AnimSeq->GetSkeletonIndexFromTrackIndex(i);
const FName BoneTreeName = Skeleton->GetReferenceSkeleton().GetBoneName(BoneTreeIndex);
// @todoanim : @fixmelh : AnimRotationOnly fix
if( BoneTreeIndex > 0 )
// && ((AnimSet->UseTranslationBoneNames.Num() > 0 && AnimSet->UseTranslationBoneNames.FindItemIndex(BoneName) == INDEX_NONE)
// || (AnimSet->ForceMeshTranslationBoneNames.FindItemIndex(BoneName) != INDEX_NONE))
// )
{
RotationOnlySavings += (BytesPerKey * NumKeys);
if( NumKeys > 1 )
{
const uint8* RESTRICT KeyData0 = TrackData + FixedBytes;
FVector V0;
FAnimationCompression_PerTrackUtils::DecompressTranslation(KeyFormat, FormatFlags, V0, TrackData, KeyData0);
float MaxErrorFromFirst = 0.f;
float MaxErrorFromDefault = 0.f;
const TArray<FTransform> & LocalRefPoses = Skeleton->GetRefLocalPoses();
for(int32 KeyIdx=0; KeyIdx<NumKeys; KeyIdx++)
{
const uint8* RESTRICT KeyDataN = TrackData + FixedBytes + KeyIdx * BytesPerKey;
FVector VN;
FAnimationCompression_PerTrackUtils::DecompressTranslation(KeyFormat, FormatFlags, VN, TrackData, KeyDataN);
// @todoanim: we will need more discussion, but we might use Skeleton->RefLocalPoses for compression
MaxErrorFromDefault = FMath::Max(MaxErrorFromDefault, FMath::Abs(VN.X - LocalRefPoses[BoneTreeIndex].GetLocation().X));
MaxErrorFromDefault = FMath::Max(MaxErrorFromDefault, FMath::Abs(VN.Y - LocalRefPoses[BoneTreeIndex].GetLocation().Y));
MaxErrorFromDefault = FMath::Max(MaxErrorFromDefault, FMath::Abs(VN.Z - LocalRefPoses[BoneTreeIndex].GetLocation().Z));
MaxErrorFromFirst = FMath::Max(MaxErrorFromFirst, FMath::Abs(VN.X - V0.X));
MaxErrorFromFirst = FMath::Max(MaxErrorFromFirst, FMath::Abs(VN.Y - V0.Y));
MaxErrorFromFirst = FMath::Max(MaxErrorFromFirst, FMath::Abs(VN.Z - V0.Z));
}
UE_LOG(LogPackageUtilities, Warning, TEXT("RotationOnly translation track that is animated! %s, %s (%s) NumKeys: %i, MaxErrorFromDefault: %f, MaxErrorFromFirst: %f"),
*BoneTreeName.ToString(), *AnimSeq->GetName(), *AnimSeq->GetFullName(), NumKeys, MaxErrorFromDefault, MaxErrorFromFirst);
RotationOnlyManyKeys += (BytesPerKey * (NumKeys-1));
}
}
}
}
// Rotation
{
// Use the CompressedTrackOffsets stream to find the data addresses
const int32* RESTRICT TrackDataForRotKey = AnimSeq->CompressedTrackOffsets.GetTypedData() + (TrackIndex * 2);
const int32 RotKeysOffset = TrackDataForRotKey[1];
if( RotKeysOffset != INDEX_NONE )
{
const uint8* RESTRICT TrackData = AnimSeq->CompressedByteStream.GetTypedData() + RotKeysOffset + 4;
const int32 Header = *((int32*)(AnimSeq->CompressedByteStream.GetTypedData() + RotKeysOffset));
int32 KeyFormat;
int32 NumKeys;
int32 FormatFlags;
int32 BytesPerKey;
int32 FixedBytes;
FAnimationCompression_PerTrackUtils::DecomposeHeader(Header, /*OUT*/ KeyFormat, /*OUT*/ NumKeys, /*OUT*/ FormatFlags, /*OUT*/BytesPerKey, /*OUT*/ FixedBytes);
if( KeyFormat == ACF_Float96NoW )
{
Num96RotTracks++;
// Determine which components we could let go, and bytes we could save.
const FBox KeyBounds((FVector*)(TrackData + FixedBytes), NumKeys);
const bool bHasX = (FMath::Abs(KeyBounds.Max.X) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.X) >= 0.0002f);
const bool bHasY = (FMath::Abs(KeyBounds.Max.Y) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.Y) >= 0.0002f);
const bool bHasZ = (FMath::Abs(KeyBounds.Max.Z) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.Z) >= 0.0002f);
if( !bHasX )
{
Rot96Savings += (4 * NumKeys);
bCandidate = true;
}
if( !bHasY )
{
Rot96Savings += (4 * NumKeys);
bCandidate = true;
}
if( !bHasZ )
{
Rot96Savings += (4 * NumKeys);
bCandidate = true;
}
}
// Measure savings on 48bits rotations.
else if( KeyFormat == ACF_Fixed48NoW )
{
Num48RotTracks++;
const int32 SavedBytes = (6 - BytesPerKey) * NumKeys;
if( SavedBytes > 0 )
{
bCandidate = true;
Rot48Savings += SavedBytes;
}
}
else
{
UnknownRotTrack++;
}
}
}
// Scale
{
// Use the CompressedTrackOffsets stream to find the data addresses
const int32 ScaleKeysOffset = AnimSeq->CompressedScaleOffsets.GetOffsetData(TrackIndex, 0);
if( ScaleKeysOffset != INDEX_NONE )
{
const uint8* RESTRICT TrackData = AnimSeq->CompressedByteStream.GetTypedData() + ScaleKeysOffset + 4;
const int32 Header = *((int32*)(AnimSeq->CompressedByteStream.GetTypedData() + ScaleKeysOffset));
int32 KeyFormat;
int32 NumKeys;
int32 FormatFlags;
int32 BytesPerKey;
int32 FixedBytes;
FAnimationCompression_PerTrackUtils::DecomposeHeader(Header, /*OUT*/ KeyFormat, /*OUT*/ NumKeys, /*OUT*/ FormatFlags, /*OUT*/BytesPerKey, /*OUT*/ FixedBytes);
if( KeyFormat == ACF_Float96NoW )
{
Num96ScaleTracks++;
// Determine which components we could let go, and bytes we could save.
const FBox KeyBounds((FVector*)(TrackData + FixedBytes), NumKeys);
const bool bHasX = (FMath::Abs(KeyBounds.Max.X) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.X) >= 0.0002f);
const bool bHasY = (FMath::Abs(KeyBounds.Max.Y) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.Y) >= 0.0002f);
const bool bHasZ = (FMath::Abs(KeyBounds.Max.Z) >= 0.0002f) || (FMath::Abs(KeyBounds.Min.Z) >= 0.0002f);
if( !bHasX )
{
Scale96Savings += (4 * NumKeys);
bCandidate = true;
}
if( !bHasY )
{
Scale96Savings += (4 * NumKeys);
bCandidate = true;
}
if( !bHasZ )
{
Scale96Savings += (4 * NumKeys);
bCandidate = true;
}
}
// Measure savings on 48bits Scales
else if( KeyFormat == ACF_Fixed48NoW )
{
Num48ScaleTracks++;
const int32 SavedBytes = (6 - BytesPerKey) * NumKeys;
if( SavedBytes > 0 )
{
bCandidate = true;
Scale48Savings += SavedBytes;
}
}
else if( KeyFormat == ACF_IntervalFixed32NoW )
{
Num32ScaleTracks++;
}
else
{
UnknownScaleTrack++;
}
// Measure how much we'd save if we used "rotation only" for compression
// root bone is true if BoneTreeIndex == 0
const int32 BoneTreeIndex = AnimSeq->GetSkeletonIndexFromTrackIndex(i);
const FName BoneTreeName = Skeleton->GetReferenceSkeleton().GetBoneName(BoneTreeIndex);
// @todoanim : @fixmelh : AnimRotationOnly fix
if( BoneTreeIndex > 0 )
// && ((AnimSet->UseScaleBoneNames.Num() > 0 && AnimSet->UseScaleBoneNames.FindItemIndex(BoneName) == INDEX_NONE)
// || (AnimSet->ForceMeshScaleBoneNames.FindItemIndex(BoneName) != INDEX_NONE))
// )
{
RotationOnlySavings += (BytesPerKey * NumKeys);
if( NumKeys > 1 )
{
const uint8* RESTRICT KeyData0 = TrackData + FixedBytes;
FVector V0;
FAnimationCompression_PerTrackUtils::DecompressScale(KeyFormat, FormatFlags, V0, TrackData, KeyData0);
float MaxErrorFromFirst = 0.f;
float MaxErrorFromDefault = 0.f;
const TArray<FTransform> & LocalRefPoses = Skeleton->GetRefLocalPoses();
for(int32 KeyIdx=0; KeyIdx<NumKeys; KeyIdx++)
{
const uint8* RESTRICT KeyDataN = TrackData + FixedBytes + KeyIdx * BytesPerKey;
FVector VN;
FAnimationCompression_PerTrackUtils::DecompressScale(KeyFormat, FormatFlags, VN, TrackData, KeyDataN);
// @todoanim: we will need more discussion, but we might use Skeleton->RefLocalPoses for compression
MaxErrorFromDefault = FMath::Max(MaxErrorFromDefault, FMath::Abs(VN.X - LocalRefPoses[BoneTreeIndex].GetLocation().X));
MaxErrorFromDefault = FMath::Max(MaxErrorFromDefault, FMath::Abs(VN.Y - LocalRefPoses[BoneTreeIndex].GetLocation().Y));
MaxErrorFromDefault = FMath::Max(MaxErrorFromDefault, FMath::Abs(VN.Z - LocalRefPoses[BoneTreeIndex].GetLocation().Z));
MaxErrorFromFirst = FMath::Max(MaxErrorFromFirst, FMath::Abs(VN.X - V0.X));
MaxErrorFromFirst = FMath::Max(MaxErrorFromFirst, FMath::Abs(VN.Y - V0.Y));
MaxErrorFromFirst = FMath::Max(MaxErrorFromFirst, FMath::Abs(VN.Z - V0.Z));
}
UE_LOG(LogPackageUtilities, Warning, TEXT("RotationOnly Scale track that is animated! %s, %s (%s) NumKeys: %i, MaxErrorFromDefault: %f, MaxErrorFromFirst: %f"),
*BoneTreeName.ToString(), *AnimSeq->GetName(), *AnimSeq->GetFullName(), NumKeys, MaxErrorFromDefault, MaxErrorFromFirst);
RotationOnlyManyKeys += (BytesPerKey * (NumKeys-1));
}
}
}
}
}
if( bCandidate )
{
++AnalyzeCompressionCandidates;
UE_LOG(LogPackageUtilities, Warning, TEXT("[%i] Animation could be recompressed: %s (%s), Trans96Savings: %i, Rot96Savings: %i, Scale96Savings: %i, Trans48Savings: %i, Rot48Savings: %i, Scale48Savings: %i, \
RotationOnlySavings: %i, RotationOnlyManyKeys: %i (bytes)"),
AnalyzeCompressionCandidates, *AnimSeq->GetName(), *AnimSeq->GetFullName(), Trans96Savings, Rot96Savings, Scale96Savings, Trans48Savings, Rot48Savings, Scale48Savings, RotationOnlySavings, RotationOnlyManyKeys);
UE_LOG(LogPackageUtilities, Warning, TEXT("Translation Track Count, Num96TransTracks: %i, Num48TransTracks: %i, Num32TransTracks: %i, UnknownTransTrack: %i"),
Num96TransTracks, Num48TransTracks, Num32TransTracks, UnknownTransTrack);
UE_LOG(LogPackageUtilities, Warning, TEXT("Rotation Track Count, Num96RotTracks: %i, Num48RotTracks: %i, UnknownRotTrack: %i"),
Num96RotTracks, Num48RotTracks, UnknownRotTrack);
UE_LOG(LogPackageUtilities, Warning, TEXT("Scale Track Count, Num96ScaleTracks: %i, Num48ScaleTracks: %i, Num32ScaleTracks: %i, UnknownScaleTrack: %i"),
Num96ScaleTracks, Num48ScaleTracks, Num32ScaleTracks, UnknownScaleTrack);
}
}
// if( AnimSeq->NumFrames > 1 && AnimSeq->KeyEncodingFormat != AKF_PerTrackCompression )
// {
// ++AnalyzeCompressionCandidates;
//
// FArchiveCountMem CountBytesSize( AnimSeq );
// int32 ResourceSize = CountBytesSize.GetNum();
//
// UE_LOG(LogPackageUtilities, Warning, TEXT("[%i] Animation could be recompressed: %s (%s), frames: %i, length: %f, size: %i bytes, compression scheme: %s"),
// AnalyzeCompressionCandidates, *AnimSeq->GetName(), *AnimSet->GetFullName(), AnimSeq->NumFrames, AnimSeq->SequenceLength, ResourceSize, AnimSeq->CompressionScheme ? *AnimSeq->CompressionScheme->GetClass()->GetName() : TEXT("NULL"));
// }
continue;
}
float HighestRatio = 0.f;
#if 0 // @todoanim: not sure why we need this here
USkeletalMesh* BestSkeletalMeshMatch = NULL;
// Test preview skeletal mesh
USkeletalMesh* DefaultSkeletalMesh = LoadObject<USkeletalMesh>(NULL, *AnimSet->PreviewSkelMeshName.ToString(), NULL, LOAD_None, NULL);
float DefaultMatchRatio = 0.f;
if( DefaultSkeletalMesh )
{
DefaultMatchRatio = AnimSet->GetSkeletalMeshMatchRatio(DefaultSkeletalMesh);
}
// If our default mesh doesn't have a full match ratio, then see if we can find a better fit.
if( DefaultMatchRatio < 1.f )
{
// Find the most suitable SkeletalMesh for this AnimSet
for( TObjectIterator<USkeletalMesh> ItMesh; ItMesh; ++ItMesh )
{
USkeletalMesh* SkelMeshCandidate = *ItMesh;
if( SkelMeshCandidate != DefaultSkeletalMesh )
{
float MatchRatio = AnimSet->GetSkeletalMeshMatchRatio(SkelMeshCandidate);
if( MatchRatio > HighestRatio )
{
BestSkeletalMeshMatch = SkelMeshCandidate;
HighestRatio = MatchRatio;
// If we have found a perfect match, we can abort.
if( FMath::Abs(1.f - MatchRatio) <= KINDA_SMALL_NUMBER )
{
break;
}
}
}
}
// If we have found a best match
if( BestSkeletalMeshMatch )
{
// if it is different than our preview mesh and his match ratio is higher
// then replace preview mesh with this one, as it's a better match.
if( BestSkeletalMeshMatch != DefaultSkeletalMesh && HighestRatio > DefaultMatchRatio )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Found more suitable preview mesh for %s (%s): %s (%f) instead of %s (%f)."),
*AnimSeq->GetName(), *AnimSet->GetFullName(), *BestSkeletalMeshMatch->GetFName().ToString(), HighestRatio, *AnimSet->PreviewSkelMeshName.ToString(), DefaultMatchRatio);
// We'll now use this one from now on as it's a better fit.
AnimSet->PreviewSkelMeshName = FName( *BestSkeletalMeshMatch->GetPathName() );
AnimSet->MarkPackageDirty();
DefaultSkeletalMesh = BestSkeletalMeshMatch;
bDirtyPackage = true;
}
}
else
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Could not find suitable mesh for %s (%s) !!! Default was %s"),
*AnimSeq->GetName(), *AnimSet->GetFullName(), *AnimSet->PreviewSkelMeshName.ToString());
}
}
#endif
int32 OldSize;
int32 NewSize;
{
FArchiveCountMem CountBytesSize( AnimSeq );
OldSize = CountBytesSize.GetNum();
}
// Clear bDoNotOverrideCompression flag
if( bClearNoCompressionOverride && AnimSeq->bDoNotOverrideCompression )
{
AnimSeq->bDoNotOverrideCompression = false;
bDirtyPackage = true;
}
// Reset to default compressor
if( bResetCompression )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("%s (%s) Resetting with BitwiseCompressOnly."), *AnimSeq->GetName(), *AnimSeq->GetFullName());
UAnimCompress* CompressionAlgorithm = ConstructObject<UAnimCompress_BitwiseCompressOnly>( UAnimCompress_BitwiseCompressOnly::StaticClass() );
CompressionAlgorithm->RotationCompressionFormat = ACF_Float96NoW;
CompressionAlgorithm->TranslationCompressionFormat = ACF_None;
CompressionAlgorithm->ScaleCompressionFormat = ACF_Float96NoW;
CompressionAlgorithm->Reduce(AnimSeq, false);
// Force an update.
AnimSeq->CompressCommandletVersion = 0;
}
UE_LOG(LogPackageUtilities, Warning, TEXT("Compressing animation '%s' [#%d / %d in package '%s']"),
*AnimSeq->GetName(),
ActiveAnimationIndex,
NumAnimationsInPackage,
*PackageFileName);
// @todoanim: expect this won't work
FAnimationUtils::CompressAnimSequence(AnimSeq, true, false);
{
FArchiveCountMem CountBytesSize( AnimSeq );
NewSize = CountBytesSize.GetNum();
}
// Set version since we've checked this animation for recompression.
if( AnimSeq->CompressCommandletVersion != CompressCommandletVersion )
{
AnimSeq->CompressCommandletVersion = CompressCommandletVersion;
bDirtyPackage = true;
}
// Only save package if size has changed.
bDirtyPackage = (bDirtyPackage || bForceCompression || (OldSize != NewSize));
// if Dirty, then we need to be able to write to this package.
// If we can't, abort, don't want to waste time!!
if( bDirtyPackage )
{
// Save dirty package every 10 minutes at least, to avoid losing work in case of a crash on very large packages.
float const CurrentTime = FPlatformTime::Seconds();
UE_LOG(LogPackageUtilities, Warning, TEXT("Time since last save: %f seconds"), (CurrentTime - LastSaveTime) );
if( (CurrentTime - LastSaveTime) > 10.f * 60.f )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("It's been over 10 minutes (%f seconds), try to save package."), (CurrentTime - LastSaveTime) );
bool bCorrectlySaved = false;
SourceControlState = SourceControl.GetProvider().GetState(Package, EStateCacheUsage::ForceUpdate);
if( SourceControlState.IsValid() && SourceControlState->CanCheckout() && bAutoCheckOut )
{
SourceControl.GetProvider().Execute(ISourceControlOperation::Create<FCheckOut>(), Package);
}
SourceControlState = SourceControl.GetProvider().GetState(Package, EStateCacheUsage::ForceUpdate);
if( !SourceControlState.IsValid() || SourceControlState->CanEdit() )
{
if( SavePackageHelper( Package, PackageFileName ) == true )
{
bCorrectlySaved = true;
UE_LOG(LogPackageUtilities, Warning, TEXT("Correctly saved: [%s]."), *PackageFileName );
}
else
{
UE_LOG(LogPackageUtilities, Error, TEXT("Error saving [%s]"), *PackageFileName );
}
}
// Log which packages could not be saved
if( !bCorrectlySaved )
{
PackagesThatCouldNotBeSavedList.AddUnique( PackageFileName );
UE_LOG(LogPackageUtilities, Warning, TEXT("%s couldn't be saved, so abort this package, don't waste time on it."), *PackageFileName );
// Abort!
return;
}
// Correctly saved
LastSaveTime = CurrentTime;
bDirtyPackage = false;
}
}
}
// End of recompression
// Does package need to be saved?
bDirtyPackage = bDirtyPackage || Package->IsDirty();
// If we need to save package, do so.
if( bDirtyPackage && !bAnalyze )
{
bool bCorrectlySaved = false;
// see if we should skip read only packages.
bool bIsReadOnly = IFileManager::Get().IsReadOnly( *PackageFileName);
// check to see if we need to check this package out
SourceControlState = SourceControl.GetProvider().GetState(Package, EStateCacheUsage::ForceUpdate);
if( SourceControlState.IsValid() && SourceControlState->CanCheckout() && bAutoCheckOut == true )
{
SourceControl.GetProvider().Execute(ISourceControlOperation::Create<FCheckOut>(), Package);
}
SourceControlState = SourceControl.GetProvider().GetState(Package, EStateCacheUsage::ForceUpdate);
if( !SourceControlState.IsValid() || SourceControlState->CanEdit() )
{
if( SavePackageHelper( Package, PackageFileName ) == true )
{
bCorrectlySaved = true;
UE_LOG(LogPackageUtilities, Warning, TEXT("Correctly saved: [%s]."), *PackageFileName );
}
else
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Error saving [%s]"), *PackageFileName );
}
}
// Log which packages could not be saved
if( !bCorrectlySaved )
{
PackagesThatCouldNotBeSavedList.AddUnique( PackageFileName );
}
}
}
};
UCompressAnimationsCommandlet::UCompressAnimationsCommandlet(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
LogToConsole = false;
}
int32 UCompressAnimationsCommandlet::Main( const FString& Params )
{
// Parse command line.
TArray<FString> Tokens;
TArray<FString> Switches;
// want everything in upper case, it's a mess otherwise
const FString ParamsUpperCase = Params.ToUpper();
const TCHAR* Parms = *ParamsUpperCase;
UCommandlet::ParseCommandLine(Parms, Tokens, Switches);
/** If we're analyzing, we're not actually going to recompress, so we can skip some significant work. */
bool bAnalyze = Switches.Contains(TEXT("ANALYZE"));
if (bAnalyze)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Analyzing content for uncompressed animations..."));
DoActionToAllPackages<UAnimSequence, CompressAnimationsFunctor>(this, ParamsUpperCase);
UE_LOG(LogPackageUtilities, Warning, TEXT("Done analyzing. Potential canditates: %i"), AnalyzeCompressionCandidates);
}
else
{
// First scan all Skeletal Meshes
UE_LOG(LogPackageUtilities, Warning, TEXT("Scanning for all SkeletalMeshes..."));
// If we have SKIPREADONLY, then override this, as we need to scan all packages for skeletal meshes.
FString SearchAllMeshesParams = ParamsUpperCase;
SearchAllMeshesParams += FString(TEXT(" -OVERRIDEREADONLY"));
SearchAllMeshesParams += FString(TEXT(" -OVERRIDELOADMAPS"));
// Prevent recompression here, we'll do it after we gathered all skeletal meshes
GDisableAnimationRecompression = true;
DoActionToAllPackages<USkeletalMesh, AddAllSkeletalMeshesToListFunctor>(this, SearchAllMeshesParams);
GDisableAnimationRecompression = false;
int32 Count = 0;
for( TObjectIterator<USkeletalMesh> It; It; ++It )
{
USkeletalMesh* SkelMesh = *It;
UE_LOG(LogPackageUtilities, Warning, TEXT("[%i] %s"), Count, *SkelMesh->GetFName().ToString());
Count++;
}
UE_LOG(LogPackageUtilities, Warning, TEXT("%i SkeletalMeshes found!"), Count);
// Then do the animation recompression
UE_LOG(LogPackageUtilities, Warning, TEXT("Recompressing all animations..."));
DoActionToAllPackages<UAnimSequence, CompressAnimationsFunctor>(this, ParamsUpperCase);
UE_LOG(LogPackageUtilities, Warning, TEXT("\n*** Packages that could not be recompressed: %i"), PackagesThatCouldNotBeSavedList.Num());
for(int32 i=0; i<PackagesThatCouldNotBeSavedList.Num(); i++)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("\t%s"), *PackagesThatCouldNotBeSavedList[i]);
}
}
return 0;
}
//======================================================================
// UReplaceActorCommandlet
//======================================================================
UReplaceActorCommandlet::UReplaceActorCommandlet(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{
LogToConsole = false;
}
int32 UReplaceActorCommandlet::Main(const FString& Params)
{
const TCHAR* Parms = *Params;
// // get the specified filename/wildcard
// FString PackageWildcard;
// if (!FParse::Token(Parms, PackageWildcard, 0))
// {
// UE_LOG(LogPackageUtilities, Warning, TEXT("Syntax: replaceactor <file/wildcard> <Package.Class to remove> <Package.Class to replace with>"));
// return 1;
// }
// find all the files matching the specified filename/wildcard
// TArray<FString> FilesInPath;
// IFileManager::Get().FindFiles(FilesInPath, *PackageWildcard, 1, 0);
// if (FilesInPath.Num() == 0)
// {
// UE_LOG(LogPackageUtilities, Error, TEXT("No packages found matching %s!"), *PackageWildcard);
// return 2;
// }
// Retrieve list of all packages in .ini paths.
TArray<FString> PackageList;
FString PackageWildcard;
FString PackagePrefix;
// if(FParse::Token(Parms,PackageWildcard,false))
// {
// IFileManager::Get().FindFiles(PackageList,*PackageWildcard,true,false);
// PackagePrefix = FPaths::GetPath(PackageWildcard) * TEXT("");
// }
// else
// {
FEditorFileUtils::FindAllPackageFiles(PackageList);
// }
if( !PackageList.Num() )
{
UE_LOG(LogPackageUtilities, Warning, TEXT( "Found no packages to run UReplaceActorCommandlet on!" ) );
return 0;
}
// get the directory part of the filename
int32 ChopPoint = FMath::Max(PackageWildcard.Find(TEXT("/"), ESearchCase::CaseSensitive, ESearchDir::FromEnd) + 1, PackageWildcard.Find(TEXT("\\"), ESearchCase::CaseSensitive, ESearchDir::FromEnd) + 1);
if (ChopPoint < 0)
{
ChopPoint = PackageWildcard.Find( TEXT("*"), ESearchCase::CaseSensitive, ESearchDir::FromEnd );
}
FString PathPrefix = (ChopPoint < 0) ? TEXT("") : PackageWildcard.Left(ChopPoint);
// get the class to remove and the class to replace it with
FString ClassName;
if (!FParse::Token(Parms, ClassName, 0))
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Syntax: replaceactor <file/wildcard> <Package.Class to remove> <Package.Class to replace with>"));
return 1;
}
UClass* ClassToReplace = (UClass*)StaticLoadObject(UClass::StaticClass(), NULL, *ClassName, NULL, LOAD_NoWarn | LOAD_Quiet, NULL);
if (ClassToReplace == NULL)
{
UE_LOG(LogPackageUtilities, Error, TEXT("Invalid class to remove: %s"), *ClassName);
return 4;
}
else
{
ClassToReplace->AddToRoot();
}
if (!FParse::Token(Parms, ClassName, 0))
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Syntax: replaceactor <file/wildcard> <Package.Class to remove> <Package.Class to replace with>"));
return 1;
}
UClass* ReplaceWithClass = (UClass*)StaticLoadObject(UClass::StaticClass(), NULL, *ClassName, NULL, LOAD_NoWarn | LOAD_Quiet, NULL);
if (ReplaceWithClass == NULL)
{
UE_LOG(LogPackageUtilities, Error, TEXT("Invalid class to replace with: %s"), *ClassName);
return 5;
}
else
{
ReplaceWithClass->AddToRoot();
}
// find the most derived superclass common to both classes
UClass* CommonSuperclass = NULL;
for (UClass* BaseClass1 = ClassToReplace; BaseClass1 != NULL && CommonSuperclass == NULL; BaseClass1 = BaseClass1->GetSuperClass())
{
for (UClass* BaseClass2 = ReplaceWithClass; BaseClass2 != NULL && CommonSuperclass == NULL; BaseClass2 = BaseClass2->GetSuperClass())
{
if (BaseClass1 == BaseClass2)
{
CommonSuperclass = BaseClass1;
}
}
}
checkSlow(CommonSuperclass != NULL);
const bool bAutoCheckOut = FParse::Param(*Params,TEXT("AutoCheckOutPackages"));
// Ensure source control is initialized and shut down properly
FScopedSourceControl SourceControl;
for (int32 i = 0; i < PackageList.Num(); i++)
{
const FString& PackageName = PackageList[i];
// get the full path name to the file
FString FileName = PathPrefix + PackageName;
const bool bIsAutoSave = FString(*FileName).ToUpper().Contains( TEXT("AUTOSAVES") );
FSourceControlStatePtr SourceControlState = SourceControl.GetProvider().GetState(FileName, EStateCacheUsage::ForceUpdate);
// skip if read-only
if( !bAutoCheckOut && SourceControlState.IsValid() && SourceControlState->CanCheckout() )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Skipping %s: the file can be checked out, but auto check out is disabled"), *FileName);
continue;
}
else if(bIsAutoSave)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Skipping %s (non map)"), *FileName);
continue;
}
else if ( bAutoCheckOut && SourceControlState.IsValid() && !SourceControlState->IsCurrent() )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Skipping %s (Not at head source control revision)"), *PackageName );
continue;
}
else
{
UWorld* World = GWorld;
// clean up any previous world
if (World != NULL)
{
World->CleanupWorld();
World->RemoveFromRoot();
}
// load the package
UE_LOG(LogPackageUtilities, Warning, TEXT("Loading %s..."), *FileName);
UPackage* Package = LoadPackage(NULL, *FileName, LOAD_None);
// load the world we're interested in
World = UWorld::FindWorldInPackage(Package);
// this is the case where .uasset objects have class references (e.g. prefabs, animnodes, etc)
if( World == NULL )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("%s (not a map)"), *FileName);
for( FObjectIterator It; It; ++It )
{
UObject* OldObject = *It;
if( ( OldObject->GetOutermost() == Package )
)
{
TMap<UClass*, UClass*> ReplaceMap;
ReplaceMap.Add(ClassToReplace, ReplaceWithClass);
FArchiveReplaceObjectRef<UClass> ReplaceAr(OldObject, ReplaceMap, false, false, false);
if( ReplaceAr.GetCount() > 0 )
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Replaced %i class references in an Object: %s"), ReplaceAr.GetCount(), *OldObject->GetName() );
Package->MarkPackageDirty();
}
}
}
if( Package->IsDirty() == true )
{
if( SourceControlState.IsValid() && SourceControlState->CanCheckout() && bAutoCheckOut == true )
{
SourceControl.GetProvider().Execute(ISourceControlOperation::Create<FCheckOut>(), Package);
}
UE_LOG(LogPackageUtilities, Warning, TEXT("Saving %s..."), *FileName);
GEditor->SavePackage( Package, NULL, RF_Standalone, *FileName, GWarn );
}
}
else
{
// We shouldnt need this - but just in case
GWorld = World;
// need to have a bool so we dont' save every single map
bool bIsDirty = false;
World->WorldType = EWorldType::Editor;
// add the world to the root set so that the garbage collection to delete replaced actors doesn't garbage collect the whole world
World->AddToRoot();
// initialize the levels in the world
World->InitWorld(UWorld::InitializationValues().AllowAudioPlayback(false));
World->GetWorldSettings()->PostEditChange();
World->UpdateWorldComponents( true, false );
// iterate through all the actors in the world, looking for matches with the class to replace (must have exact match, not subclass)
for (FActorIterator It(World); It; ++It)
{
AActor* OldActor = *It;
if (OldActor->GetClass() == ClassToReplace)
{
// replace an instance of the old actor
UE_LOG(LogPackageUtilities, Warning, TEXT("Replacing actor %s"), *OldActor->GetName());
bIsDirty = true;
// make sure we spawn the new actor in the same level as the old
//@warning: this relies on the outer of an actor being the level
FVector OldLocation = OldActor->GetActorLocation();
FRotator OldRotator = OldActor->GetActorRotation();
// Cache the level this actor is in.
ULevel* Level = OldActor->GetLevel();
// destroy the old actor, which removes it from the array but doesn't destroy it until GC
OldActor->Destroy();
FActorSpawnParameters SpawnInfo;
SpawnInfo.OverrideLevel = Level;
SpawnInfo.bNoCollisionFail = true;
// spawn the new actor
AActor* NewActor = World->SpawnActor<AActor>( ReplaceWithClass, OldLocation, OldRotator, SpawnInfo );
// copy non-native non-transient properties common to both that were modified in the old actor to the new actor
for (UProperty* Property = CommonSuperclass->PropertyLink; Property != NULL; Property = Property->PropertyLinkNext)
{
if ( !(Property->PropertyFlags & CPF_Transient) &&
!(Property->PropertyFlags & (CPF_InstancedReference | CPF_ContainsInstancedReference)) &&
!Property->Identical_InContainer(OldActor, OldActor->GetClass()->GetDefaultObject()) )
{
Property->CopyCompleteValue_InContainer(NewActor, OldActor);
Package->MarkPackageDirty();
}
}
if (ClassToReplace->IsChildOf(AWorldSettings::StaticClass()))
{
// Find the index in the array the worldsettings has been spawned at.
const int32 WorldSettingsActorIndex = Level->Actors.Find( NewActor );
// The worldsettings needs to reside at index 0.
Exchange(Level->Actors[0],Level ->Actors[WorldSettingsActorIndex]);
}
check(OldActor->IsValidLowLevel()); // make sure DestroyActor() doesn't immediately trigger GC since that'll break the reference replacement
// check for any references to the old Actor and replace them with the new one
TMap<AActor*, AActor*> ReplaceMap;
ReplaceMap.Add(OldActor, NewActor);
FArchiveReplaceObjectRef<AActor> ReplaceAr(World, ReplaceMap, false, false, false);
if (ReplaceAr.GetCount() > 0)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Replaced %i actor references in %s"), ReplaceAr.GetCount(), *It->GetName());
Package->MarkPackageDirty();
}
}
else
{
// check for any references to the old class and replace them with the new one
TMap<UClass*, UClass*> ReplaceMap;
ReplaceMap.Add(ClassToReplace, ReplaceWithClass);
FArchiveReplaceObjectRef<UClass> ReplaceAr(*It, ReplaceMap, false, false, false);
if (ReplaceAr.GetCount() > 0)
{
UE_LOG(LogPackageUtilities, Warning, TEXT("Replaced %i class references in actor %s"), ReplaceAr.GetCount(), *It->GetName());
Package->MarkPackageDirty();
bIsDirty = true;
}
}
}
// collect garbage to delete replaced actors and any objects only referenced by them (components, etc)
World->PerformGarbageCollection();
// save the world
if( ( Package->IsDirty() == true ) && ( bIsDirty == true ) )
{
SourceControlState = SourceControl.GetProvider().GetState(FileName, EStateCacheUsage::ForceUpdate);
if( SourceControlState.IsValid() && SourceControlState->CanCheckout() && bAutoCheckOut == true )
{
SourceControl.GetProvider().Execute(ISourceControlOperation::Create<FCheckOut>(), Package);
}
UE_LOG(LogPackageUtilities, Warning, TEXT("Saving %s..."), *FileName);
GEditor->SavePackage(Package, World, RF_NoFlags, *FileName, GWarn);
}
// clear GWorld by removing it from the root set and replacing it with a new one
World->CleanupWorld();
World->RemoveFromRoot();
World = GWorld = NULL;
}
}
// get rid of the loaded world
UE_LOG(LogPackageUtilities, Warning, TEXT("GCing..."));
CollectGarbage(RF_Native);
}
// UEditorEngine::FinishDestroy() expects GWorld to exist
if( GWorld )
{
GWorld->DestroyWorld( false );
}
GWorld = UWorld::CreateWorld(EWorldType::Editor, false );
return 0;
} | [
"michaellam430@gmail.com"
] | michaellam430@gmail.com |
c8a3cf4ff7a5fad605e9b33cbd4cd68004ef5f1c | a2b49d0b5414134df2dbfd690b1fbab66db2d01f | /Functions/Q1_great_friend_function.cpp | ef490aaaa2816623088124e53cdc9c0c6cd076fe | [] | no_license | Ngufuli/cpp | 7296e6cae38af27b314a156478899b2dd4a0b3be | c7acc1ea19f2f25c8dc2fe9be52a8ca92af9ae77 | refs/heads/master | 2020-06-28T16:29:51.833907 | 2019-08-03T01:39:33 | 2019-08-03T01:39:33 | 200,281,571 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | using namespace std;
#include<iostream>
class abc
{
int a, b, c;
public:
void get()
{
cout<<"Enter the first number";
cin>>a;
cout<<"Enter the second number";
cin>>b;
cout<<"Enter the third number";
cin>>c;
}
friend void great(abc ob);
};
void great(abc ob)
{
if(ob.a>ob.b&&ob.a>ob.c)
cout<<"Greatest number is:"<<ob.a;
else if(ob.b>ob.c)
cout<<"Greatest number is:"<<ob.b;
else
cout<<"Greatest number is:"<<ob.c;
}
int main()
{
abc x;
x.get();
great(x);
}
| [
"ngufuli@outlook.com"
] | ngufuli@outlook.com |
9af973a95fb8065a27f22f67b5cf7c410e9cf077 | 532b0899862c4e754ed45e4963da8b5cd4b486ac | /vpub-core-dev/src/smsg/keystore.cpp | 575ef23bcc9413b59e89ddd3a33f2c94b1e05feb | [
"MIT"
] | permissive | benyuan001/Source-Blockchain | 6fba9c93917ccf678791dc23fa53480e4cfb162c | 6f2b2ade4f4051205db1d9c4c791e023dd542881 | refs/heads/master | 2023-01-04T23:30:26.435487 | 2020-10-28T10:01:27 | 2020-10-28T10:01:27 | 307,964,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | cpp | // Copyright (c) 2018 The Vpub Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <smsg/keystore.h>
namespace smsg {
bool SecMsgKeyStore::AddKey(const CKeyID &idk, SecMsgKey &key)
{
LOCK(cs_KeyStore);
key.pubkey = key.key.GetPubKey();
mapKeys[idk] = key;
return true;
};
bool SecMsgKeyStore::HaveKey(const CKeyID &idk) const
{
LOCK(cs_KeyStore);
return mapKeys.count(idk) > 0;
}
bool SecMsgKeyStore::EraseKey(const CKeyID &idk)
{
LOCK(cs_KeyStore);
mapKeys.erase(idk);
return true;
};
bool SecMsgKeyStore::GetPubKey(const CKeyID &idk, CPubKey &pk)
{
LOCK(cs_KeyStore);
std::map<CKeyID, SecMsgKey>::const_iterator it = mapKeys.find(idk);
if (it != mapKeys.end())
{
pk = it->second.pubkey;
return true;
};
return false;
};
bool SecMsgKeyStore::Clear()
{
LOCK(cs_KeyStore);
mapKeys.clear();
return true;
};
} // namespace smsg
| [
"stvenyindeveloper@126.com"
] | stvenyindeveloper@126.com |
6b08789d824861143b687c93222456f1b3f6b1c7 | 1fc6e41b062e5fa4a606d71330dfbf5366b081fb | /Samples/BasicHologram/cppwinrt/Common/DeviceResources.cpp | af79573111d029a5761eb19f631fddcec5cea4aa | [
"MIT"
] | permissive | ichpuchtli/Windows-universal-samples | dac210f7e9b7e66b7455751c3cbbcbb6a760e6cc | ba3384798ed6e24785c05dab32bcb0e7300a2427 | refs/heads/master | 2020-03-31T08:26:23.647997 | 2018-10-08T09:58:50 | 2018-10-08T09:58:50 | 152,057,072 | 1 | 0 | MIT | 2018-10-08T09:56:36 | 2018-10-08T09:56:35 | null | UTF-8 | C++ | false | false | 11,794 | cpp |
#include "pch.h"
#include "DeviceResources.h"
#include "DirectXHelper.h"
using namespace D2D1;
using namespace Microsoft::WRL;
using namespace winrt::Windows::Graphics::DirectX::Direct3D11;
using namespace winrt::Windows::Graphics::Display;
using namespace winrt::Windows::Graphics::Holographic;
// Constructor for DeviceResources.
DX::DeviceResources::DeviceResources()
{
CreateDeviceIndependentResources();
}
// Configures resources that don't depend on the Direct3D device.
void DX::DeviceResources::CreateDeviceIndependentResources()
{
// Initialize Direct2D resources.
D2D1_FACTORY_OPTIONS options{};
#if defined(_DEBUG)
// If the project is in a debug build, enable Direct2D debugging via SDK Layers.
options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
#endif
// Initialize the Direct2D Factory.
winrt::check_hresult(
D2D1CreateFactory(
D2D1_FACTORY_TYPE_SINGLE_THREADED,
__uuidof(ID2D1Factory2),
&options,
&m_d2dFactory
));
// Initialize the DirectWrite Factory.
winrt::check_hresult(
DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory2),
&m_dwriteFactory
));
// Initialize the Windows Imaging Component (WIC) Factory.
winrt::check_hresult(
CoCreateInstance(
CLSID_WICImagingFactory2,
nullptr,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&m_wicFactory)
));
}
void DX::DeviceResources::SetHolographicSpace(HolographicSpace holographicSpace)
{
// Cache the holographic space. Used to re-initalize during device-lost scenarios.
m_holographicSpace = holographicSpace;
InitializeUsingHolographicSpace();
}
void DX::DeviceResources::InitializeUsingHolographicSpace()
{
// The holographic space might need to determine which adapter supports
// holograms, in which case it will specify a non-zero PrimaryAdapterId.
LUID id =
{
m_holographicSpace.PrimaryAdapterId().LowPart,
m_holographicSpace.PrimaryAdapterId().HighPart
};
// When a primary adapter ID is given to the app, the app should find
// the corresponding DXGI adapter and use it to create Direct3D devices
// and device contexts. Otherwise, there is no restriction on the DXGI
// adapter the app can use.
if ((id.HighPart != 0) || (id.LowPart != 0))
{
UINT createFlags = 0;
#ifdef DEBUG
if (DX::SdkLayersAvailable())
{
createFlags |= DXGI_CREATE_FACTORY_DEBUG;
}
#endif
// Create the DXGI factory.
ComPtr<IDXGIFactory1> dxgiFactory;
winrt::check_hresult(
CreateDXGIFactory2(
createFlags,
IID_PPV_ARGS(&dxgiFactory)
));
ComPtr<IDXGIFactory4> dxgiFactory4;
winrt::check_hresult(dxgiFactory.As(&dxgiFactory4));
// Retrieve the adapter specified by the holographic space.
winrt::check_hresult(
dxgiFactory4->EnumAdapterByLuid(
id,
IID_PPV_ARGS(&m_dxgiAdapter)
));
}
else
{
m_dxgiAdapter.Reset();
}
CreateDeviceResources();
m_holographicSpace.SetDirect3D11Device(m_d3dInteropDevice);
}
// Configures the Direct3D device, and stores handles to it and the device context.
void DX::DeviceResources::CreateDeviceResources()
{
// This flag adds support for surfaces with a different color channel ordering
// than the API default. It is required for compatibility with Direct2D.
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#if defined(_DEBUG)
if (DX::SdkLayersAvailable())
{
// If the project is in a debug build, enable debugging via SDK Layers with this flag.
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
}
#endif
// This array defines the set of DirectX hardware feature levels this app will support.
// Note the ordering should be preserved.
// Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
// of running on graphics cards starting with feature level 10.0.
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_12_1,
D3D_FEATURE_LEVEL_12_0,
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0
};
// Create the Direct3D 11 API device object and a corresponding context.
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
const D3D_DRIVER_TYPE driverType = m_dxgiAdapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN;
const HRESULT hr = D3D11CreateDevice(
m_dxgiAdapter.Get(), // Either nullptr, or the primary adapter determined by Windows Holographic.
driverType, // Create a device using the hardware graphics driver.
0, // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
creationFlags, // Set debug and Direct2D compatibility flags.
featureLevels, // List of feature levels this app can support.
ARRAYSIZE(featureLevels), // Size of the list above.
D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
&device, // Returns the Direct3D device created.
&m_d3dFeatureLevel, // Returns feature level of device created.
&context // Returns the device immediate context.
);
if (FAILED(hr))
{
// If the initialization fails, fall back to the WARP device.
// For more information on WARP, see:
// http://go.microsoft.com/fwlink/?LinkId=286690
winrt::check_hresult(
D3D11CreateDevice(
nullptr, // Use the default DXGI adapter for WARP.
D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
0,
creationFlags,
featureLevels,
ARRAYSIZE(featureLevels),
D3D11_SDK_VERSION,
&device,
&m_d3dFeatureLevel,
&context
));
}
// Store pointers to the Direct3D device and immediate context.
winrt::check_hresult(device.As(&m_d3dDevice));
winrt::check_hresult(context.As(&m_d3dContext));
// Acquire the DXGI interface for the Direct3D device.
ComPtr<IDXGIDevice3> dxgiDevice;
winrt::check_hresult(m_d3dDevice.As(&dxgiDevice));
// Wrap the native device using a WinRT interop object.
winrt::com_ptr<::IInspectable> object;
winrt::check_hresult(CreateDirect3D11DeviceFromDXGIDevice(
dxgiDevice.Get(),
winrt::put_abi(object)));
m_d3dInteropDevice = object.as<IDirect3DDevice>();
// Cache the DXGI adapter.
// This is for the case of no preferred DXGI adapter, or fallback to WARP.
ComPtr<IDXGIAdapter> dxgiAdapter;
winrt::check_hresult(dxgiDevice->GetAdapter(&dxgiAdapter));
winrt::check_hresult(dxgiAdapter.As(&m_dxgiAdapter));
// Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
{
m_supportsVprt = true;
}
}
// Validates the back buffer for each HolographicCamera and recreates
// resources for back buffers that have changed.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::EnsureCameraResources(
HolographicFrame frame,
HolographicFramePrediction prediction)
{
UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
{
for (HolographicCameraPose const& cameraPose : prediction.CameraPoses())
{
HolographicCameraRenderingParameters renderingParameters = frame.GetRenderingParameters(cameraPose);
CameraResources* pCameraResources = cameraResourceMap[cameraPose.HolographicCamera().Id()].get();
pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
}
});
}
// Prepares to allocate resources and adds resource views for a camera.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::AddHolographicCamera(HolographicCamera camera)
{
UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
{
cameraResourceMap[camera.Id()] = std::make_unique<CameraResources>(camera);
});
}
// Deallocates resources for a camera and removes the camera from the set.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera camera)
{
UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
{
CameraResources* pCameraResources = cameraResourceMap[camera.Id()].get();
if (pCameraResources != nullptr)
{
pCameraResources->ReleaseResourcesForBackBuffer(this);
cameraResourceMap.erase(camera.Id());
}
});
}
// Recreate all device resources and set them back to the current state.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::HandleDeviceLost()
{
if (m_deviceNotify != nullptr)
{
m_deviceNotify->OnDeviceLost();
}
UseHolographicCameraResources<void>([this](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
{
for (auto& pair : cameraResourceMap)
{
CameraResources* pCameraResources = pair.second.get();
pCameraResources->ReleaseResourcesForBackBuffer(this);
}
});
InitializeUsingHolographicSpace();
if (m_deviceNotify != nullptr)
{
m_deviceNotify->OnDeviceRestored();
}
}
// Register our DeviceNotify to be informed on device lost and creation.
void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
{
m_deviceNotify = deviceNotify;
}
// Call this method when the app suspends. It provides a hint to the driver that the app
// is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
void DX::DeviceResources::Trim()
{
m_d3dContext->ClearState();
ComPtr<IDXGIDevice3> dxgiDevice;
winrt::check_hresult(m_d3dDevice.As(&dxgiDevice));
dxgiDevice->Trim();
}
// Present the contents of the swap chain to the screen.
// Locks the set of holographic camera resources until the function exits.
void DX::DeviceResources::Present(HolographicFrame frame)
{
// By default, this API waits for the frame to finish before it returns.
// Holographic apps should wait for the previous frame to finish before
// starting work on a new frame. This allows for better results from
// holographic frame predictions.
HolographicFramePresentResult presentResult = frame.PresentUsingCurrentPrediction();
// The PresentUsingCurrentPrediction API will detect when the graphics device
// changes or becomes invalid. When this happens, it is considered a Direct3D
// device lost scenario.
if (presentResult == HolographicFramePresentResult::DeviceRemoved)
{
// The Direct3D device, context, and resources should be recreated.
HandleDeviceLost();
}
}
| [
"oldnewthing@users.noreply.github.com"
] | oldnewthing@users.noreply.github.com |
aa0efe8d70d43fdec4ac6ec510045451da74c875 | 9192182cfcfcf4ce9f9bbb4003106e29b37b5bd1 | /mame-0.141/src/mame/includes/ninjaw.h | 16ba3107ab263872c5f3ea21bf178a1be88bafa4 | [] | no_license | johkelly/MAME_hi | a2b9ea9d4f089f75e57de5963af187718733fccd | ccbec44e4c82e5ca83ba80de19bfb9c100dbd349 | refs/heads/master | 2020-05-17T13:29:54.978078 | 2012-07-13T19:03:50 | 2012-07-13T19:03:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | h | /*************************************************************************
Taito Triple Screen Games
*************************************************************************/
class ninjaw_state : public driver_device
{
public:
ninjaw_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT16 * spriteram;
size_t spriteram_size;
/* misc */
UINT16 cpua_ctrl;
INT32 banknum;
int pandata[4];
/* devices */
device_t *maincpu;
device_t *audiocpu;
device_t *subcpu;
device_t *tc0140syt;
device_t *tc0100scn_1;
device_t *tc0100scn_2;
device_t *tc0100scn_3;
device_t *lscreen;
device_t *mscreen;
device_t *rscreen;
device_t *_2610_1l;
device_t *_2610_1r;
device_t *_2610_2l;
device_t *_2610_2r;
};
/*----------- defined in video/ninjaw.c -----------*/
VIDEO_START( ninjaw );
VIDEO_UPDATE( ninjaw );
| [
"john.kelly@readytalk.com"
] | john.kelly@readytalk.com |
3f587585e05714b1c23c4311542f5d8be63ec519 | 7119554f4726c4c3cd46823ee695ae3e433eccc7 | /nntrainer/layers/lstmcell.cpp | 6e84220de766fca481003e4b11115151a8ef9235 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | myungjoo/nntrainer | 7fdc88cdec3e9bd12916b8892a137672bcbb0d39 | 4813b20d869b33d00a9e098d6955072858286533 | refs/heads/master | 2023-08-17T01:41:32.521247 | 2022-03-16T07:56:56 | 2022-03-20T03:32:51 | 249,907,471 | 0 | 0 | Apache-2.0 | 2020-03-25T06:52:04 | 2020-03-25T06:52:03 | null | UTF-8 | C++ | false | false | 13,847 | cpp | // SPDX-License-Identifier: Apache-2.0
/**
* Copyright (C) 2021 Parichay Kapoor <pk.kapoor@samsung.com>
*
* @file lstmcell.cpp
* @date 17 March 2021
* @brief This is LSTMCell Layer Class of Neural Network
* @see https://github.com/nnstreamer/nntrainer
* @author Parichay Kapoor <pk.kapoor@samsung.com>
* @bug No known bugs except for NYI items
*
*/
#include <layer_context.h>
#include <lstmcell.h>
#include <lstmcell_core.h>
#include <nntrainer_error.h>
#include <nntrainer_log.h>
#include <node_exporter.h>
namespace nntrainer {
enum LSTMCellParams {
weight_ih,
weight_hh,
bias_h,
bias_ih,
bias_hh,
ifgo,
dropout_mask
};
LSTMCellLayer::LSTMCellLayer() :
LayerImpl(),
lstmcell_props(props::Unit(), props::IntegrateBias(),
props::HiddenStateActivation() = ActivationType::ACT_TANH,
props::RecurrentActivation() = ActivationType::ACT_SIGMOID,
props::DropOutRate()),
acti_func(ActivationType::ACT_NONE, true),
recurrent_acti_func(ActivationType::ACT_NONE, true),
epsilon(1e-3) {
wt_idx.fill(std::numeric_limits<unsigned>::max());
}
void LSTMCellLayer::finalize(InitLayerContext &context) {
const Tensor::Initializer weight_initializer =
std::get<props::WeightInitializer>(*layer_impl_props).get();
const Tensor::Initializer bias_initializer =
std::get<props::BiasInitializer>(*layer_impl_props).get();
const WeightRegularizer weight_regularizer =
std::get<props::WeightRegularizer>(*layer_impl_props).get();
const float weight_regularizer_constant =
std::get<props::WeightRegularizerConstant>(*layer_impl_props).get();
auto &weight_decay = std::get<props::WeightDecay>(*layer_impl_props);
auto &bias_decay = std::get<props::BiasDecay>(*layer_impl_props);
const bool disable_bias =
std::get<props::DisableBias>(*layer_impl_props).get();
NNTR_THROW_IF(std::get<props::Unit>(lstmcell_props).empty(),
std::invalid_argument)
<< "unit property missing for lstmcell layer";
const unsigned int unit = std::get<props::Unit>(lstmcell_props).get();
const bool integrate_bias =
std::get<props::IntegrateBias>(lstmcell_props).get();
const ActivationType hidden_state_activation_type =
std::get<props::HiddenStateActivation>(lstmcell_props).get();
const ActivationType recurrent_activation_type =
std::get<props::RecurrentActivation>(lstmcell_props).get();
const float dropout_rate = std::get<props::DropOutRate>(lstmcell_props).get();
if (context.getNumInputs() != 3) {
throw std::invalid_argument(
"Number of input is not 3. LSTMCell layer should takes 3 inputs");
}
// input_dim = [ batch_size, 1, 1, feature_size ]
const TensorDim &input_dim = context.getInputDimensions()[INOUT_INDEX::INPUT];
if (input_dim.channel() != 1 || input_dim.height() != 1) {
throw std::invalid_argument(
"Input must be single time dimension for LSTMCell (shape should be "
"[batch_size, 1, 1, feature_size])");
}
// input_hidden_state_dim = [ batch, 1, 1, unit ]
const TensorDim &input_hidden_state_dim =
context.getInputDimensions()[INOUT_INDEX::INPUT_HIDDEN_STATE];
if (input_hidden_state_dim.channel() != 1 ||
input_hidden_state_dim.height() != 1) {
throw std::invalid_argument("Input hidden state's dimension should be "
"[batch, 1, 1, unit] for LSTMCell");
}
// input_cell_state_dim = [ batch, 1, 1, unit ]
const TensorDim &input_cell_state_dim =
context.getInputDimensions()[INOUT_INDEX::INPUT_CELL_STATE];
if (input_cell_state_dim.channel() != 1 ||
input_cell_state_dim.height() != 1) {
throw std::invalid_argument("Input cell state's dimension should be "
"[batch, 1, 1, unit] for LSTMCell");
}
const unsigned int batch_size = input_dim.batch();
const unsigned int feature_size = input_dim.width();
// output_hidden_state_dim = [ batch_size, 1, 1, unit ]
const TensorDim output_hidden_state_dim = input_hidden_state_dim;
// output_cell_state_dim = [ batch_size, 1, 1, unit ]
const TensorDim output_cell_state_dim = input_cell_state_dim;
std::vector<VarGradSpecV2> out_specs;
out_specs.push_back(
InitLayerContext::outSpec(output_hidden_state_dim, "output_hidden_state",
TensorLifespan::FORWARD_FUNC_LIFESPAN));
out_specs.push_back(
InitLayerContext::outSpec(output_cell_state_dim, "output_cell_state",
TensorLifespan::FORWARD_GRAD_LIFESPAN));
context.requestOutputs(std::move(out_specs));
// weight_initializer can be set seperately. weight_ih initializer,
// weight_hh initializer kernel initializer & recurrent_initializer in keras
// for now, it is set same way.
// - weight_ih ( input to hidden )
// : [ 1, 1, feature_size, NUM_GATE x unit ] -> i, f, g, o
TensorDim weight_ih_dim({feature_size, NUM_GATE * unit});
wt_idx[LSTMCellParams::weight_ih] = context.requestWeight(
weight_ih_dim, weight_initializer, weight_regularizer,
weight_regularizer_constant, weight_decay, "weight_ih", true);
// - weight_hh ( hidden to hidden )
// : [ 1, 1, unit, NUM_GATE x unit ] -> i, f, g, o
TensorDim weight_hh_dim({unit, NUM_GATE * unit});
wt_idx[LSTMCellParams::weight_hh] = context.requestWeight(
weight_hh_dim, weight_initializer, weight_regularizer,
weight_regularizer_constant, weight_decay, "weight_hh", true);
if (!disable_bias) {
if (integrate_bias) {
// - bias_h ( input bias, hidden bias are integrate to 1 bias )
// : [ 1, 1, 1, NUM_GATE x unit ] -> i, f, g, o
TensorDim bias_h_dim({NUM_GATE * unit});
wt_idx[LSTMCellParams::bias_h] = context.requestWeight(
bias_h_dim, bias_initializer, WeightRegularizer::NONE, 1.0f, bias_decay,
"bias_h", true);
} else {
// - bias_ih ( input bias )
// : [ 1, 1, 1, NUM_GATE x unit ] -> i, f, g, o
TensorDim bias_ih_dim({NUM_GATE * unit});
wt_idx[LSTMCellParams::bias_ih] = context.requestWeight(
bias_ih_dim, bias_initializer, WeightRegularizer::NONE, 1.0f,
bias_decay, "bias_ih", true);
// - bias_hh ( hidden bias )
// : [ 1, 1, 1, NUM_GATE x unit ] -> i, f, g, o
TensorDim bias_hh_dim({NUM_GATE * unit});
wt_idx[LSTMCellParams::bias_hh] = context.requestWeight(
bias_hh_dim, bias_initializer, WeightRegularizer::NONE, 1.0f,
bias_decay, "bias_hh", true);
}
}
/** ifgo_dim = [ batch_size, 1, 1, NUM_GATE * unit ] */
const TensorDim ifgo_dim(batch_size, 1, 1, NUM_GATE * unit);
wt_idx[LSTMCellParams::ifgo] =
context.requestTensor(ifgo_dim, "ifgo", Tensor::Initializer::NONE, true,
TensorLifespan::ITERATION_LIFESPAN);
if (dropout_rate > epsilon) {
// dropout_mask_dim = [ batch_size, 1, 1, unit ]
const TensorDim dropout_mask_dim(batch_size, 1, 1, unit);
wt_idx[LSTMCellParams::dropout_mask] = context.requestTensor(
dropout_mask_dim, "dropout_mask", Tensor::Initializer::NONE, false,
TensorLifespan::ITERATION_LIFESPAN);
}
acti_func.setActiFunc(hidden_state_activation_type);
recurrent_acti_func.setActiFunc(recurrent_activation_type);
}
void LSTMCellLayer::setProperty(const std::vector<std::string> &values) {
const std::vector<std::string> &remain_props =
loadProperties(values, lstmcell_props);
LayerImpl::setProperty(remain_props);
}
void LSTMCellLayer::exportTo(Exporter &exporter,
const ExportMethods &method) const {
LayerImpl::exportTo(exporter, method);
exporter.saveResult(lstmcell_props, method, this);
}
void LSTMCellLayer::forwarding(RunLayerContext &context, bool training) {
const bool disable_bias =
std::get<props::DisableBias>(*layer_impl_props).get();
const unsigned int unit = std::get<props::Unit>(lstmcell_props).get();
const float dropout_rate = std::get<props::DropOutRate>(lstmcell_props).get();
const bool integrate_bias =
std::get<props::IntegrateBias>(lstmcell_props).get();
const Tensor &input = context.getInput(INOUT_INDEX::INPUT);
const Tensor &prev_hidden_state =
context.getInput(INOUT_INDEX::INPUT_HIDDEN_STATE);
const Tensor &prev_cell_state =
context.getInput(INOUT_INDEX::INPUT_CELL_STATE);
Tensor &hidden_state = context.getOutput(INOUT_INDEX::OUTPUT_HIDDEN_STATE);
Tensor &cell_state = context.getOutput(INOUT_INDEX::OUTPUT_CELL_STATE);
const unsigned int batch_size = input.getDim().batch();
const Tensor &weight_ih =
context.getWeight(wt_idx[LSTMCellParams::weight_ih]);
const Tensor &weight_hh =
context.getWeight(wt_idx[LSTMCellParams::weight_hh]);
Tensor empty;
const Tensor &bias_h = !disable_bias && integrate_bias
? context.getWeight(wt_idx[LSTMCellParams::bias_h])
: empty;
const Tensor &bias_ih = !disable_bias && !integrate_bias
? context.getWeight(wt_idx[LSTMCellParams::bias_ih])
: empty;
const Tensor &bias_hh = !disable_bias && !integrate_bias
? context.getWeight(wt_idx[LSTMCellParams::bias_hh])
: empty;
Tensor &ifgo = context.getTensor(wt_idx[LSTMCellParams::ifgo]);
lstmcell_forwarding(unit, batch_size, disable_bias, integrate_bias, acti_func,
recurrent_acti_func, input, prev_hidden_state,
prev_cell_state, hidden_state, cell_state, weight_ih,
weight_hh, bias_h, bias_ih, bias_hh, ifgo);
if (dropout_rate > epsilon && training) {
Tensor &dropout_mask =
context.getTensor(wt_idx[LSTMCellParams::dropout_mask]);
dropout_mask.dropout_mask(dropout_rate);
hidden_state.multiply_i(dropout_mask);
}
}
void LSTMCellLayer::calcDerivative(RunLayerContext &context) {
Tensor &d_ifgo = context.getTensorGrad(wt_idx[LSTMCellParams::ifgo]);
const Tensor &weight_ih =
context.getWeight(wt_idx[LSTMCellParams::weight_ih]);
Tensor &outgoing_derivative =
context.getOutgoingDerivative(INOUT_INDEX::INPUT);
lstmcell_calcDerivative(d_ifgo, weight_ih, outgoing_derivative);
}
void LSTMCellLayer::calcGradient(RunLayerContext &context) {
const bool disable_bias =
std::get<props::DisableBias>(*layer_impl_props).get();
const unsigned int unit = std::get<props::Unit>(lstmcell_props).get();
const bool integrate_bias =
std::get<props::IntegrateBias>(lstmcell_props).get();
const float dropout_rate = std::get<props::DropOutRate>(lstmcell_props);
const Tensor &input = context.getInput(INOUT_INDEX::INPUT);
const Tensor &prev_hidden_state =
context.getInput(INOUT_INDEX::INPUT_HIDDEN_STATE);
Tensor &d_prev_hidden_state =
context.getOutgoingDerivative(INOUT_INDEX::INPUT_HIDDEN_STATE);
const Tensor &prev_cell_state =
context.getInput(INOUT_INDEX::INPUT_CELL_STATE);
Tensor &d_prev_cell_state =
context.getOutgoingDerivative(INOUT_INDEX::INPUT_CELL_STATE);
const Tensor &d_hidden_state =
context.getIncomingDerivative(INOUT_INDEX::OUTPUT_HIDDEN_STATE);
const Tensor &cell_state = context.getOutput(INOUT_INDEX::OUTPUT_CELL_STATE);
const Tensor &d_cell_state =
context.getIncomingDerivative(INOUT_INDEX::OUTPUT_CELL_STATE);
unsigned int batch_size = input.getDim().batch();
Tensor &d_weight_ih =
context.getWeightGrad(wt_idx[LSTMCellParams::weight_ih]);
const Tensor &weight_hh =
context.getWeight(wt_idx[LSTMCellParams::weight_hh]);
Tensor &d_weight_hh =
context.getWeightGrad(wt_idx[LSTMCellParams::weight_hh]);
Tensor empty;
Tensor &d_bias_h = !disable_bias && integrate_bias
? context.getWeightGrad(wt_idx[LSTMCellParams::bias_h])
: empty;
Tensor &d_bias_ih = !disable_bias && !integrate_bias
? context.getWeightGrad(wt_idx[LSTMCellParams::bias_ih])
: empty;
Tensor &d_bias_hh = !disable_bias && !integrate_bias
? context.getWeightGrad(wt_idx[LSTMCellParams::bias_hh])
: empty;
const Tensor &ifgo = context.getTensor(wt_idx[LSTMCellParams::ifgo]);
Tensor &d_ifgo = context.getTensorGrad(wt_idx[LSTMCellParams::ifgo]);
if (context.isGradientFirstAccess(wt_idx[LSTMCellParams::weight_ih])) {
d_weight_ih.setZero();
}
if (context.isGradientFirstAccess(wt_idx[LSTMCellParams::weight_hh])) {
d_weight_hh.setZero();
}
if (!disable_bias) {
if (integrate_bias) {
if (context.isGradientFirstAccess(wt_idx[LSTMCellParams::bias_h])) {
d_bias_h.setZero();
}
} else {
if (context.isGradientFirstAccess(wt_idx[LSTMCellParams::bias_ih])) {
d_bias_ih.setZero();
}
if (context.isGradientFirstAccess(wt_idx[LSTMCellParams::bias_hh])) {
d_bias_hh.setZero();
}
}
}
Tensor d_hidden_state_masked;
if (dropout_rate > epsilon) {
Tensor &dropout_mask =
context.getTensor(wt_idx[LSTMCellParams::dropout_mask]);
d_hidden_state.multiply(dropout_mask, d_hidden_state_masked);
}
lstmcell_calcGradient(
unit, batch_size, disable_bias, integrate_bias, acti_func,
recurrent_acti_func, input, prev_hidden_state, d_prev_hidden_state,
prev_cell_state, d_prev_cell_state,
dropout_rate > epsilon ? d_hidden_state_masked : d_hidden_state, cell_state,
d_cell_state, d_weight_ih, weight_hh, d_weight_hh, d_bias_h, d_bias_ih,
d_bias_hh, ifgo, d_ifgo);
}
void LSTMCellLayer::setBatch(RunLayerContext &context, unsigned int batch) {
const float dropout_rate = std::get<props::DropOutRate>(lstmcell_props);
context.updateTensor(wt_idx[LSTMCellParams::ifgo], batch);
if (dropout_rate > epsilon) {
context.updateTensor(wt_idx[LSTMCellParams::dropout_mask], batch);
}
}
} // namespace nntrainer
| [
"jijoong.moon@samsung.com"
] | jijoong.moon@samsung.com |
5c8c6d4fc7a113915b5780414e4f8ae7a3415f04 | 2ec8f8ce6b487e8a19abbd756acdcdc661606e0a | /Data_Structures/tests/LinkedList_test.cpp | 3211dd47620a26c0070f204a51efb6f655ffe86b | [] | no_license | radusqrt/CTCI-1 | 92c285d63be448fb7409306cff2c6851d2d134dc | 460470b7b37dfd9e161ea4ca4849d2fdef2f79bc | refs/heads/master | 2020-03-22T11:52:56.970257 | 2018-07-08T18:11:40 | 2018-07-08T18:11:40 | 140,002,174 | 0 | 0 | null | 2018-07-06T15:33:45 | 2018-07-06T15:33:45 | null | UTF-8 | C++ | false | false | 1,622 | cpp | #include "../src/LinkedList.h"
#include <gtest/gtest.h>
TEST(LinkedListTest, EmptyList) {
LinkedList<int> l;
ASSERT_EQ(true, l.isEmpty());
}
TEST(LinkedListTest, NotEmptyListAfterAddFirst) {
LinkedList<int> l;
l.addFirst(2);
ASSERT_EQ(false, l.isEmpty());
}
TEST(LinkedListTest, NotEmptyListAfterAddLast) {
LinkedList<int> l;
l.addLast(2);
ASSERT_EQ(false, l.isEmpty());
}
TEST(LinkedListTest, AddFirst) {
LinkedList<int> l;
l.addLast(2);
ASSERT_EQ(2, l.getFirstPtr()->value);
ASSERT_EQ(2, l.getLastPtr()->value);
}
TEST(LinkedListTest, AddLast) {
LinkedList<int> l;
l.addLast(2);
ASSERT_EQ(2, l.getFirstPtr()->value);
ASSERT_EQ(2, l.getLastPtr()->value);
}
TEST(LinkedListTest, RemoveFirst) {
LinkedList<int> l;
l.removeFirst();
ASSERT_EQ(true, l.isEmpty());
l.addFirst(2);
l.addLast(3);
l.addFirst(1);
l.removeFirst();
ASSERT_EQ(2, l.getFirstPtr()->value);
}
TEST(LinkedListTest, Equals) {
LinkedList<int> l1, l2;
l1.addFirst(1);
l1.addFirst(2);
l1.addFirst(3);
l2.addFirst(1);
l2.addFirst(2);
l2.addFirst(3);
ASSERT_EQ(true, l1.equals(l2));
}
TEST(LinkedListTest, CopyConstructorAssignmentOperator) {
LinkedList<std::string> l1;
l1.addLast("Last");
l1.addFirst("Middle");
l1.addFirst("First");
LinkedList<std::string> l2(l1);
ASSERT_EQ(true, l1.equals(l2));
LinkedList<std::string> l3 = l1;
ASSERT_EQ(true, l1.equals(l3));
}
/* MORE TO COME */
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | [
"radu.stochitoiu@gmail.com"
] | radu.stochitoiu@gmail.com |
fc6f9675feac3151d84f9fe6c09819c212bd37d7 | 8f0d71bd0a814cd1ad7d6b9bb142fb202c2d9f86 | /goblin/src/include/ExampleFrameListener.h | 4f04da179062bc5d5293d9c41d59242f7ea7cc29 | [] | no_license | fufie/lambdarock | 89a95ff2dd8ba4c9a2c210d176ad41b39d2924e4 | e1f57d3110082720e7a24a4ea87cd621d9b9b207 | refs/heads/master | 2022-04-24T09:36:25.941681 | 2020-04-16T16:27:00 | 2020-04-16T16:27:00 | 256,203,187 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,814 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
You may use this sample code for anything you like, it is not covered by the
LGPL like the rest of the engine.
-----------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------
Filename: ExampleFrameListener.h
Description: Defines an example frame listener which responds to frame events.
This frame listener just moves a specified camera around based on
keyboard and mouse movements.
Mouse: Freelook
W or Up: Forward
S or Down:Backward
A: Step left
D: Step right
PgUp: Move upwards
PgDown: Move downwards
F: Toggle frame rate stats on/off
R: Render mode
T: Cycle texture filtering
Bilinear, Trilinear, Anisotropic(8)
P: Toggle on/off display of camera position / orientation
-----------------------------------------------------------------------------
*/
#ifndef __ExampleFrameListener_H__
#define __ExampleFrameListener_H__
#include "Ogre.h"
#include "OgreStringConverter.h"
#include "OgreException.h"
//Use this define to signify OIS will be used as a DLL
//(so that dll import/export macros are in effect)
#define OIS_DYNAMIC_LIB
#include <OIS/OIS.h>
using namespace Ogre;
class ExampleFrameListener: public FrameListener, public WindowEventListener
{
protected:
virtual void updateStats(void)
{
static String currFps = "Current FPS: ";
static String avgFps = "Average FPS: ";
static String bestFps = "Best FPS: ";
static String worstFps = "Worst FPS: ";
static String tris = "Triangle Count: ";
static String batches = "Batch Count: ";
// update stats when necessary
try {
OverlayElement* guiAvg = OverlayManager::getSingleton().getOverlayElement("Core/AverageFps");
OverlayElement* guiCurr = OverlayManager::getSingleton().getOverlayElement("Core/CurrFps");
OverlayElement* guiBest = OverlayManager::getSingleton().getOverlayElement("Core/BestFps");
OverlayElement* guiWorst = OverlayManager::getSingleton().getOverlayElement("Core/WorstFps");
const RenderTarget::FrameStats& stats = mWindow->getStatistics();
guiAvg->setCaption(avgFps + StringConverter::toString(stats.avgFPS));
guiCurr->setCaption(currFps + StringConverter::toString(stats.lastFPS));
guiBest->setCaption(bestFps + StringConverter::toString(stats.bestFPS)
+" "+StringConverter::toString(stats.bestFrameTime)+" ms");
guiWorst->setCaption(worstFps + StringConverter::toString(stats.worstFPS)
+" "+StringConverter::toString(stats.worstFrameTime)+" ms");
OverlayElement* guiTris = OverlayManager::getSingleton().getOverlayElement("Core/NumTris");
guiTris->setCaption(tris + StringConverter::toString(stats.triangleCount));
OverlayElement* guiBatches = OverlayManager::getSingleton().getOverlayElement("Core/NumBatches");
guiBatches->setCaption(batches + StringConverter::toString(stats.batchCount));
OverlayElement* guiDbg = OverlayManager::getSingleton().getOverlayElement("Core/DebugText");
guiDbg->setCaption(mDebugText);
}
catch(...) { /* ignore */ }
}
public:
// Constructor takes a RenderWindow because it uses that to determine input context
ExampleFrameListener(RenderWindow* win, Camera* cam, bool bufferedKeys = false, bool bufferedMouse = false,
bool bufferedJoy = false ) :
mCamera(cam), mTranslateVector(Vector3::ZERO), mCurrentSpeed(0), mWindow(win), mStatsOn(true), mNumScreenShots(0),
mMoveScale(0.0f), mRotScale(0.0f), mTimeUntilNextToggle(0), mFiltering(TFO_BILINEAR),
mAniso(1), mSceneDetailIndex(0), mMoveSpeed(100), mRotateSpeed(36), mDebugOverlay(0),
mInputManager(0), mMouse(0), mKeyboard(0), mJoy(0)
{
mDebugOverlay = OverlayManager::getSingleton().getByName("Core/DebugOverlay");
LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
OIS::ParamList pl;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
win->getCustomAttribute("WINDOW", &windowHnd);
windowHndStr << windowHnd;
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
mInputManager = OIS::InputManager::createInputSystem( pl );
//Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, bufferedKeys ));
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, bufferedMouse ));
try {
mJoy = static_cast<OIS::JoyStick*>(mInputManager->createInputObject( OIS::OISJoyStick, bufferedJoy ));
}
catch(...) {
mJoy = 0;
}
//Set initial mouse clipping size
windowResized(mWindow);
showDebugOverlay(true);
//Register as a Window listener
WindowEventUtilities::addWindowEventListener(mWindow, this);
}
//Adjust mouse clipping area
virtual void windowResized(RenderWindow* rw)
{
unsigned int width, height, depth;
int left, top;
rw->getMetrics(width, height, depth, left, top);
const OIS::MouseState &ms = mMouse->getMouseState();
ms.width = width;
ms.height = height;
}
//Unattach OIS before window shutdown (very important under Linux)
virtual void windowClosed(RenderWindow* rw)
{
//Only close for window that created OIS (the main window in these demos)
if( rw == mWindow )
{
if( mInputManager )
{
mInputManager->destroyInputObject( mMouse );
mInputManager->destroyInputObject( mKeyboard );
mInputManager->destroyInputObject( mJoy );
OIS::InputManager::destroyInputSystem(mInputManager);
mInputManager = 0;
}
}
}
virtual ~ExampleFrameListener()
{
//Remove ourself as a Window listener
WindowEventUtilities::removeWindowEventListener(mWindow, this);
windowClosed(mWindow);
}
virtual bool processUnbufferedKeyInput(const FrameEvent& evt)
{
if(mKeyboard->isKeyDown(OIS::KC_A))
mTranslateVector.x = -mMoveScale; // Move camera left
if(mKeyboard->isKeyDown(OIS::KC_D))
mTranslateVector.x = mMoveScale; // Move camera RIGHT
if(mKeyboard->isKeyDown(OIS::KC_UP) || mKeyboard->isKeyDown(OIS::KC_W) )
mTranslateVector.z = -mMoveScale; // Move camera forward
if(mKeyboard->isKeyDown(OIS::KC_DOWN) || mKeyboard->isKeyDown(OIS::KC_S) )
mTranslateVector.z = mMoveScale; // Move camera backward
if(mKeyboard->isKeyDown(OIS::KC_PGUP))
mTranslateVector.y = mMoveScale; // Move camera up
if(mKeyboard->isKeyDown(OIS::KC_PGDOWN))
mTranslateVector.y = -mMoveScale; // Move camera down
if(mKeyboard->isKeyDown(OIS::KC_RIGHT))
mCamera->yaw(-mRotScale);
if(mKeyboard->isKeyDown(OIS::KC_LEFT))
mCamera->yaw(mRotScale);
if( mKeyboard->isKeyDown(OIS::KC_ESCAPE) || mKeyboard->isKeyDown(OIS::KC_Q) )
return false;
if( mKeyboard->isKeyDown(OIS::KC_F) && mTimeUntilNextToggle <= 0 )
{
mStatsOn = !mStatsOn;
showDebugOverlay(mStatsOn);
mTimeUntilNextToggle = 1;
}
if( mKeyboard->isKeyDown(OIS::KC_T) && mTimeUntilNextToggle <= 0 )
{
switch(mFiltering)
{
case TFO_BILINEAR:
mFiltering = TFO_TRILINEAR;
mAniso = 1;
break;
case TFO_TRILINEAR:
mFiltering = TFO_ANISOTROPIC;
mAniso = 8;
break;
case TFO_ANISOTROPIC:
mFiltering = TFO_BILINEAR;
mAniso = 1;
break;
default: break;
}
MaterialManager::getSingleton().setDefaultTextureFiltering(mFiltering);
MaterialManager::getSingleton().setDefaultAnisotropy(mAniso);
showDebugOverlay(mStatsOn);
mTimeUntilNextToggle = 1;
}
if(mKeyboard->isKeyDown(OIS::KC_SYSRQ) && mTimeUntilNextToggle <= 0)
{
std::ostringstream ss;
ss << "screenshot_" << ++mNumScreenShots << ".png";
mWindow->writeContentsToFile(ss.str());
mTimeUntilNextToggle = 0.5;
mDebugText = "Saved: " + ss.str();
}
if(mKeyboard->isKeyDown(OIS::KC_R) && mTimeUntilNextToggle <=0)
{
mSceneDetailIndex = (mSceneDetailIndex+1)%3 ;
switch(mSceneDetailIndex) {
case 0 : mCamera->setPolygonMode(PM_SOLID); break;
case 1 : mCamera->setPolygonMode(PM_WIREFRAME); break;
case 2 : mCamera->setPolygonMode(PM_POINTS); break;
}
mTimeUntilNextToggle = 0.5;
}
static bool displayCameraDetails = false;
if(mKeyboard->isKeyDown(OIS::KC_P) && mTimeUntilNextToggle <= 0)
{
displayCameraDetails = !displayCameraDetails;
mTimeUntilNextToggle = 0.5;
if (!displayCameraDetails)
mDebugText = "";
}
// Print camera details
if(displayCameraDetails)
mDebugText = "P: " + StringConverter::toString(mCamera->getDerivedPosition()) +
" " + "O: " + StringConverter::toString(mCamera->getDerivedOrientation());
// Return true to continue rendering
return true;
}
virtual bool processUnbufferedMouseInput(const FrameEvent& evt)
{
// Rotation factors, may not be used if the second mouse button is pressed
// 2nd mouse button - slide, otherwise rotate
const OIS::MouseState &ms = mMouse->getMouseState();
if( ms.buttonDown( OIS::MB_Right ) )
{
mTranslateVector.x += ms.X.rel * 0.13;
mTranslateVector.y -= ms.Y.rel * 0.13;
}
else
{
mRotX = Degree(-ms.X.rel * 0.13);
mRotY = Degree(-ms.Y.rel * 0.13);
}
return true;
}
virtual void moveCamera()
{
// Make all the changes to the camera
// Note that YAW direction is around a fixed axis (freelook style) rather than a natural YAW
//(e.g. airplane)
mCamera->yaw(mRotX);
mCamera->pitch(mRotY);
mCamera->moveRelative(mTranslateVector);
}
virtual void showDebugOverlay(bool show)
{
if (mDebugOverlay)
{
if (show)
mDebugOverlay->show();
else
mDebugOverlay->hide();
}
}
// Override frameRenderingQueued event to process that (don't care about frameEnded)
bool frameRenderingQueued(const FrameEvent& evt)
{
if(mWindow->isClosed()) return false;
mSpeedLimit = mMoveScale * evt.timeSinceLastFrame;
//Need to capture/update each device
mKeyboard->capture();
mMouse->capture();
if( mJoy ) mJoy->capture();
bool buffJ = (mJoy) ? mJoy->buffered() : true;
Ogre::Vector3 lastMotion = mTranslateVector;
//Check if one of the devices is not buffered
if( !mMouse->buffered() || !mKeyboard->buffered() || !buffJ )
{
// one of the input modes is immediate, so setup what is needed for immediate movement
if (mTimeUntilNextToggle >= 0)
mTimeUntilNextToggle -= evt.timeSinceLastFrame;
// Move about 100 units per second
mMoveScale = mMoveSpeed * evt.timeSinceLastFrame;
// Take about 10 seconds for full rotation
mRotScale = mRotateSpeed * evt.timeSinceLastFrame;
mRotX = 0;
mRotY = 0;
mTranslateVector = Ogre::Vector3::ZERO;
}
//Check to see which device is not buffered, and handle it
if( !mKeyboard->buffered() )
if( processUnbufferedKeyInput(evt) == false )
return false;
if( !mMouse->buffered() )
if( processUnbufferedMouseInput(evt) == false )
return false;
// ramp up / ramp down speed
if (mTranslateVector == Ogre::Vector3::ZERO)
{
// decay (one third speed)
mCurrentSpeed -= evt.timeSinceLastFrame * 0.3;
mTranslateVector = lastMotion;
}
else
{
// ramp up
mCurrentSpeed += evt.timeSinceLastFrame;
}
// Limit motion speed
if (mCurrentSpeed > 1.0)
mCurrentSpeed = 1.0;
if (mCurrentSpeed < 0.0)
mCurrentSpeed = 0.0;
mTranslateVector *= mCurrentSpeed;
if( !mMouse->buffered() || !mKeyboard->buffered() || !buffJ )
moveCamera();
return true;
}
bool frameEnded(const FrameEvent& evt)
{
updateStats();
return true;
}
protected:
Camera* mCamera;
Vector3 mTranslateVector;
Real mCurrentSpeed;
RenderWindow* mWindow;
bool mStatsOn;
std::string mDebugText;
unsigned int mNumScreenShots;
float mMoveScale;
float mSpeedLimit;
Degree mRotScale;
// just to stop toggles flipping too fast
Real mTimeUntilNextToggle ;
Radian mRotX, mRotY;
TextureFilterOptions mFiltering;
int mAniso;
int mSceneDetailIndex ;
Real mMoveSpeed;
Degree mRotateSpeed;
Overlay* mDebugOverlay;
//OIS Input devices
OIS::InputManager* mInputManager;
OIS::Mouse* mMouse;
OIS::Keyboard* mKeyboard;
OIS::JoyStick* mJoy;
};
#endif
| [
"ses@vizrt.com"
] | ses@vizrt.com |
db0259842a5c5a1ece5bc5f04fb22788877640b7 | fc6ad3f5a9c823053269c2a290325ecbae326acd | /extras/vMap Extractor/vmapextract/format.h | 3cc4a727e5f021a0349c55563b697da606b0424d | [] | no_license | h4s0n/Sandshroud | cd9414dd040eced359d9b8cba20d3ec0942e657a | 6e72df913d5640d024289dc01e61b654ec10954c | refs/heads/master | 2021-01-21T01:06:11.333760 | 2013-09-08T07:09:28 | 2013-09-08T07:09:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,738 | h | /***
* Demonstrike Core
*/
#pragma once
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <cstdarg>
// If your platform does not have vsnprintf, you can find a
// implementation at http://www.ijs.si/software/snprintf/
#if defined(_MSC_VER) && (_MSC_VER >= 1300) && PLATFORM == PLATFORM_WIN
// Both MSVC seems to use the non-standard vsnprintf
// so we are using vscprintf to determine buffer size, however
// only MSVC7 and up headers include vscprintf for some reason.
std::string vformat(const char *fmt, va_list argPtr)
{
// We draw the line at a 1MB string.
const int maxSize = 1000000;
// If the string is less than 161 characters,
// allocate it on the stack because this saves
// the malloc/free time.
const int bufSize = 161;
char stackBuffer[bufSize];
// MSVC does not support va_copy
int actualSize = _vscprintf(fmt, argPtr) + 1;
if (actualSize > bufSize)
{
// Now use the heap.
char* heapBuffer = NULL;
if (actualSize < maxSize)
{
heapBuffer = (char*)malloc(maxSize + 1);
_vsnprintf(heapBuffer, maxSize, fmt, argPtr);
heapBuffer[maxSize] = '\0';
}
else
{
heapBuffer = (char*)malloc(actualSize);
vsprintf(heapBuffer, fmt, argPtr);
}
std::string formattedString(heapBuffer);
free(heapBuffer);
return formattedString;
}
else
{
vsprintf(stackBuffer, fmt, argPtr);
return std::string(stackBuffer);
}
}
#elif defined(_MSC_VER) && (_MSC_VER < 1300) && PLATFORM == PLATFORM_WIN
std::string vformat(const char *fmt, va_list argPtr) {
// We draw the line at a 1MB string.
const int maxSize = 1000000;
// If the string is less than 161 characters,
// allocate it on the stack because this saves
// the malloc/free time.
const int bufSize = 161;
char stackBuffer[bufSize];
// MSVC6 doesn't support va_copy, however it also seems to compile
// correctly if we just pass our argument list along. Note that
// this whole code block is only compiled if we're on MSVC6 anyway
int actualWritten = _vsnprintf(stackBuffer, bufSize, fmt, argPtr);
// Not a big enough buffer, bufSize characters written
if (actualWritten == -1) {
int heapSize = 512;
double powSize = 1.0;
char* heapBuffer = (char*)malloc(heapSize);
while ((_vsnprintf(heapBuffer, heapSize, fmt, argPtr) == -1) &&
(heapSize < maxSize)) {
heapSize = iCeil(heapSize * ::pow((double)2.0, powSize++));
heapBuffer = (char*)realloc(heapBuffer, heapSize);
}
heapBuffer[heapSize-1] = '\0';
std::string heapString(heapBuffer);
free(heapBuffer);
return heapString;
} else {
return std::string(stackBuffer);
}
}
#else
// glibc 2.1 has been updated to the C99 standard
std::string vformat(const char* fmt, va_list argPtr) {
// If the string is less than 161 characters,
// allocate it on the stack because this saves
// the malloc/free time. The number 161 is chosen
// to support two lines of text on an 80 character
// console (plus the null terminator).
const int bufSize = 161;
char stackBuffer[bufSize];
va_list argPtrCopy;
va_copy(argPtrCopy, argPtr);
int numChars = vsnprintf(stackBuffer, bufSize, fmt, argPtrCopy);
va_end(argPtrCopy);
if (numChars >= bufSize) {
// We didn't allocate a big enough string.
char* heapBuffer = (char*)malloc((numChars + 1) * sizeof(char));
ASSERT(heapBuffer);
int numChars2 = vsnprintf(heapBuffer, numChars + 1, fmt, argPtr);
ASSERT(numChars2 == numChars);
(void)numChars2;
std::string result(heapBuffer);
free(heapBuffer);
return result;
} else {
return std::string(stackBuffer);
}
}
#endif
std::string format(const char* fmt,...)
{
va_list argList;
va_start(argList,fmt);
std::string result = vformat(fmt, argList);
va_end(argList);
return result;
}
| [
"Crow5736@yahoo.com"
] | Crow5736@yahoo.com |
f0c22285f9a67aac108ce71b30fc92816f6e2cee | 9596182c6505cb4b2b746b501d799eb3e083d479 | /include/world/TestMapGenerator.h | 3c74efd154243a3e9986c75a8f7439a2ebf90c7e | [] | no_license | ColinGilbert/projectzombie | 2b55361c6f1c5d41d82d2fb03d200fd4e3be2f19 | af772cd66fabf899eb124602dcbd4e6c4a21b467 | refs/heads/master | 2021-01-22T02:07:58.275092 | 2015-04-06T00:57:57 | 2015-04-06T00:57:57 | 33,460,671 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,041 | h | #pragma once
#include "ZPrerequisites.h"
#include "world/MapGenerator.h"
namespace ZGame
{
namespace World
{
class TestMapGenerator : public MapGenerator
{
public:
~TestMapGenerator(){}
void
generate(PVolume* data, PolyVox::Region,
Ogre::Real pageX, Ogre::Real pageY);
private:
void
createSphereInVolume(PVolume& volData, PolyVox::Region ®ion, float fRadius, uint8_t uValue);
void
createCubeInVolume(PVolume& volData, Vector3DUint16 lowerCorner, Vector3DUint16 upperCorner, uint8_t uValue);
};
}
}
using namespace ZGame::World;
using namespace PolyVox;
inline void
TestMapGenerator::generate(Volume<Material8>* data, PolyVox::Region region,
Ogre::Real pageX, Ogre::Real pageY)
{
const int width = region.width();
const int height = region.height() - 10;
const int depth = region.depth();
const float halfHeight = (float)(height) / 2.0f;
const float oceanFloor = halfHeight;
createSphereInVolume(*data, region, width - 15,
//Ogre::Math::RangeRandom(width-15, width),
Ogre::Math::RangeRandom(1.0, 256.0));
return;
}
inline void
TestMapGenerator::createSphereInVolume(PVolume& volData, PolyVox::Region ®ion,
float fRadius, uint8_t uValue)
{
//This vector hold the position of the center of the volume
Vector3DFloat v3dVolCenter(region.getLowerCorner().getX() + region.depth() / 2,
region.getLowerCorner().getY() + region.height() / 2, region.getLowerCorner().getZ() + region.width() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = region.getLowerCorner().getZ(); z < region.getUpperCorner().getZ(); z++)
{
for (int y = region.getLowerCorner().getY(); y < region.getUpperCorner().getY(); y++)
{
for (int x = region.getLowerCorner().getX(); x < region.getUpperCorner().getX(); x++)
{
//Store our current position as a vector...
Vector3DFloat v3dCurrentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
//If the current voxel is less than 'radius' units from the center
//then we make it solid, otherwise we make it empty space.
if(fDistToCenter <= fRadius)
{
volData.setVoxelAt(x,y,z, uValue);
}
}
}
}
}
inline void
TestMapGenerator::createCubeInVolume(PVolume& volData, Vector3DUint16 lowerCorner, Vector3DUint16 upperCorner, uint8_t uValue)
{
//This three-level for loop iterates over every voxel between the specified corners
for (int z = lowerCorner.getZ(); z <= upperCorner.getZ(); z++)
{
for (int y = lowerCorner.getY(); y <= upperCorner.getY(); y++)
{
for (int x = lowerCorner.getX() ; x <= upperCorner.getX(); x++)
{
volData.setVoxelAt(x,y,z, uValue);
}
}
}
}
| [
"llwijk@200bf698-8c57-11dd-a017-db29c870d619"
] | llwijk@200bf698-8c57-11dd-a017-db29c870d619 |
b6844808917e97b57c93f0e654e075fb9904781d | e0cd22a3dbf1589cee37c33374607ed2ce66e95e | /cpp/opensourcesrcs/ace/docs/tutorials/011/message_queue.cpp | a074e12ad131815de881a2a3b30d4b28ed503db4 | [] | no_license | CodeOpsTech/DesignPatternsCpp | 1335402e2c88a4b8715430210ec153af7bb733be | 2c67495ffdc65443fae98b2879f7b608e3562876 | refs/heads/master | 2021-01-11T19:19:48.498940 | 2017-07-19T02:52:56 | 2017-07-19T02:52:56 | 79,355,314 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,147 | cpp | // message_queue.cpp,v 1.8 2000/11/27 17:56:43 othman Exp
/* Most of this is the same as the previous tutorial, so I'll just
point out the differences. */
#include "task.h"
#include "block.h"
#include "data.h"
static int
run_test (int iterations,
int threads)
{
Task task (threads);
if (task.open () == -1)
ACE_ERROR_RETURN ((LM_ERROR,
"%p\n",
"open"),
-1);
ACE_OS::sleep (ACE_Time_Value (1));
int i;
for (i = 0; i < iterations; ++i)
{
/* Construct a Data object that we'll put into the Queue. */
Data data (i);
/* Create a block large enough for our Data object as well as a
text message. */
Block *message;
ACE_NEW_RETURN (message,
Block (sizeof (data) + 128),
-1);
/* As before, put a text message into the block. */
ACE_OS::sprintf (message->wr_ptr (), "This is message %d.", i);
message->wr_ptr (strlen (message->rd_ptr ()));
message->wr_ptr (1); // Move beyond the NULL
/* To copy arbitrary data into a message block, we use the
copy() method. Since it wants a 'const char*', we have to
cast our Data pointer.
Note that copy() will advance the wr_ptr() for us. This means
we don't have to do it ourselves! If you do advance it, it
will be way beyond what you want. */
message->copy ((const char *) &data,
sizeof (data));
if (task.putq (message) == -1)
break;
}
Block *message;
ACE_NEW_RETURN (message,
Block,
-1);
message->msg_type (ACE_Message_Block::MB_HANGUP);
task.putq (message);
task.wait ();
return 0;
}
int
main (int argc, char *argv[])
{
int iterations = argc > 1 ? atoi (argv[1]) : 4;
int threads = argc > 2 ? atoi (argv[2]) : 2;
run_test (iterations,
threads);
ACE_DEBUG ((LM_DEBUG,
"(%P|%t) Application exiting\n"));
return 0;
}
| [
"ganesh@codeops.tech"
] | ganesh@codeops.tech |
9dfe518cdb635b8164a7afde53b4ae5a36cf4e30 | f8b838e3805a4dde783da142e6c46062be4ff606 | /components/display_compositor/gpu_compositor_frame_sink.cc | 58b833dfe56cf8cc01f8c306715ed15634c85caf | [
"BSD-3-Clause"
] | permissive | trusslab/sugar_chromium | 1cc0eec4dd52d8b2b7bc2d871090a518495539f8 | 5f1dd3da9f21c65c4f1388f22e10585941f0cbc9 | refs/heads/master | 2022-11-08T17:36:48.367045 | 2018-02-17T07:00:15 | 2018-02-17T07:00:15 | 121,314,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,040 | cc | // Copyright 2015 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 "components/display_compositor/gpu_compositor_frame_sink.h"
#include "cc/surfaces/surface_reference.h"
namespace display_compositor {
GpuCompositorFrameSink::GpuCompositorFrameSink(
GpuCompositorFrameSinkDelegate* delegate,
cc::SurfaceManager* surface_manager,
const cc::FrameSinkId& frame_sink_id,
cc::mojom::MojoCompositorFrameSinkRequest request,
cc::mojom::MojoCompositorFrameSinkPrivateRequest
compositor_frame_sink_private_request,
cc::mojom::MojoCompositorFrameSinkClientPtr client)
: delegate_(delegate),
support_(base::MakeUnique<cc::CompositorFrameSinkSupport>(
this,
surface_manager,
frame_sink_id,
false /* is_root */,
true /* handles_frame_sink_id_invalidation */,
true /* needs_sync_points */)),
client_(std::move(client)),
compositor_frame_sink_binding_(this, std::move(request)),
compositor_frame_sink_private_binding_(
this,
std::move(compositor_frame_sink_private_request)) {
compositor_frame_sink_binding_.set_connection_error_handler(base::Bind(
&GpuCompositorFrameSink::OnClientConnectionLost, base::Unretained(this)));
compositor_frame_sink_private_binding_.set_connection_error_handler(
base::Bind(&GpuCompositorFrameSink::OnPrivateConnectionLost,
base::Unretained(this)));
}
GpuCompositorFrameSink::~GpuCompositorFrameSink() {}
void GpuCompositorFrameSink::EvictFrame() {
support_->EvictFrame();
}
void GpuCompositorFrameSink::SetNeedsBeginFrame(bool needs_begin_frame) {
support_->SetNeedsBeginFrame(needs_begin_frame);
}
void GpuCompositorFrameSink::SubmitCompositorFrame(
const cc::LocalSurfaceId& local_surface_id,
cc::CompositorFrame frame) {
support_->SubmitCompositorFrame(local_surface_id, std::move(frame));
}
void GpuCompositorFrameSink::Require(const cc::LocalSurfaceId& local_surface_id,
const cc::SurfaceSequence& sequence) {
support_->Require(local_surface_id, sequence);
}
void GpuCompositorFrameSink::Satisfy(const cc::SurfaceSequence& sequence) {
support_->Satisfy(sequence);
}
void GpuCompositorFrameSink::DidReceiveCompositorFrameAck() {
if (client_)
client_->DidReceiveCompositorFrameAck();
}
void GpuCompositorFrameSink::AddChildFrameSink(
const cc::FrameSinkId& child_frame_sink_id) {
support_->AddChildFrameSink(child_frame_sink_id);
}
void GpuCompositorFrameSink::RemoveChildFrameSink(
const cc::FrameSinkId& child_frame_sink_id) {
support_->RemoveChildFrameSink(child_frame_sink_id);
}
void GpuCompositorFrameSink::RequestCopyOfSurface(
std::unique_ptr<cc::CopyOutputRequest> request) {
support_->RequestCopyOfSurface(std::move(request));
}
void GpuCompositorFrameSink::OnBeginFrame(const cc::BeginFrameArgs& args) {
if (client_)
client_->OnBeginFrame(args);
}
void GpuCompositorFrameSink::ReclaimResources(
const cc::ReturnedResourceArray& resources) {
if (client_)
client_->ReclaimResources(resources);
}
void GpuCompositorFrameSink::WillDrawSurface(
const cc::LocalSurfaceId& local_surface_id,
const gfx::Rect& damage_rect) {
if (client_)
client_->WillDrawSurface(local_surface_id, damage_rect);
}
void GpuCompositorFrameSink::OnClientConnectionLost() {
client_connection_lost_ = true;
// Request destruction of |this| only if both connections are lost.
delegate_->OnClientConnectionLost(support_->frame_sink_id(),
private_connection_lost_);
}
void GpuCompositorFrameSink::OnPrivateConnectionLost() {
private_connection_lost_ = true;
// Request destruction of |this| only if both connections are lost.
delegate_->OnPrivateConnectionLost(support_->frame_sink_id(),
client_connection_lost_);
}
} // namespace display_compositor
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
686278a7a79b427bdf88150418b94ad685e1c9d8 | 31bf321f4f6cc6957635e4ae0f4964e3d6a92ddf | /test/memorypool/tst_sharedmemorypool.cpp | 406bd94dc423dd9a2eec8891eca7e41c136e9c96 | [
"BSD-2-Clause"
] | permissive | kaidokert/weos | b30e0c558bdebb9ecf3db7217735fe59109961b5 | 977758532b3336afb2f6d1ba33455491a36b4fbf | refs/heads/master | 2021-01-18T02:33:40.507755 | 2015-01-19T21:31:54 | 2015-01-19T21:32:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,072 | cpp | /*******************************************************************************
WEOS - Wrapper for embedded operating systems
Copyright (c) 2013-2014, Manuel Freiberger
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.
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 <memorypool.hpp>
#include "../common/testutils.hpp"
#include "gtest/gtest.h"
#include <set>
template <typename T>
class SharedMemoryPoolTestFixture : public testing::Test
{
};
// Define a list of types with which the memory pool will be instantiated.
typedef testing::Types<
std::int8_t, std::int16_t, std::int32_t, std::int64_t, std::intptr_t, std::intmax_t,
std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t, std::uintptr_t, std::uintmax_t,
float, double, long double> TypesToTest;
TYPED_TEST_CASE(SharedMemoryPoolTestFixture, TypesToTest);
TYPED_TEST(SharedMemoryPoolTestFixture, Constructor)
{
{
weos::shared_memory_pool<TypeParam, 1> p;
ASSERT_FALSE(p.empty());
ASSERT_EQ(1, p.capacity());
ASSERT_EQ(1, p.size());
}
{
weos::shared_memory_pool<TypeParam, 10> p;
ASSERT_FALSE(p.empty());
ASSERT_EQ(10, p.capacity());
ASSERT_EQ(10, p.size());
}
}
TYPED_TEST(SharedMemoryPoolTestFixture, allocate)
{
const unsigned POOL_SIZE = 10;
weos::shared_memory_pool<TypeParam, POOL_SIZE> p;
char* chunks[POOL_SIZE];
for (unsigned i = 0; i < POOL_SIZE; ++i)
{
ASSERT_EQ(POOL_SIZE - i, p.size());
ASSERT_FALSE(p.empty());
void* c = p.allocate();
ASSERT_TRUE(c != 0);
ASSERT_EQ(POOL_SIZE - i - 1, p.size());
// Check the alignment of the allocated chunk.
char* addr = static_cast<char*>(c);
ASSERT_TRUE(reinterpret_cast<uintptr_t>(addr)
% weos::alignment_of<TypeParam>::value == 0);
for (unsigned j = 0; j < i; ++j)
{
// No chunk can be returned twice from the pool.
ASSERT_FALSE(chunks[j] == addr);
// Chunks must not overlap.
if (chunks[j] < addr)
ASSERT_TRUE(chunks[j] + sizeof(TypeParam) <= addr);
if (chunks[j] > addr)
ASSERT_TRUE(addr + sizeof(TypeParam) <= chunks[j]);
}
chunks[i] = addr;
}
ASSERT_TRUE(p.empty());
ASSERT_EQ(POOL_SIZE, p.capacity());
}
TYPED_TEST(SharedMemoryPoolTestFixture, try_allocate)
{
const unsigned POOL_SIZE = 10;
weos::shared_memory_pool<TypeParam, POOL_SIZE> p;
for (unsigned i = 0; i < POOL_SIZE; ++i)
{
void* c = p.try_allocate();
ASSERT_TRUE(c != 0);
}
ASSERT_TRUE(p.empty());
ASSERT_EQ(POOL_SIZE, p.capacity());
for (unsigned i = 0; i < POOL_SIZE; ++i)
{
ASSERT_TRUE(p.try_allocate() == 0);
}
}
TYPED_TEST(SharedMemoryPoolTestFixture, allocate_and_free)
{
const unsigned POOL_SIZE = 10;
weos::shared_memory_pool<TypeParam, POOL_SIZE> p;
void* chunks[POOL_SIZE];
for (unsigned j = 1; j <= POOL_SIZE; ++j)
{
for (unsigned i = 0; i < j; ++i)
{
ASSERT_EQ(POOL_SIZE - i, p.size());
void* c = p.allocate();
ASSERT_TRUE(c != 0);
ASSERT_EQ(POOL_SIZE - i - 1, p.size());
ASSERT_EQ(POOL_SIZE, p.capacity());
chunks[i] = c;
}
for (unsigned i = 0; i < j; ++i)
{
ASSERT_EQ(POOL_SIZE - j + i, p.size());
p.free(chunks[i]);
ASSERT_EQ(POOL_SIZE - j + i + 1, p.size());
}
}
}
TYPED_TEST(SharedMemoryPoolTestFixture, random_allocate_and_free)
{
const unsigned POOL_SIZE = 10;
weos::shared_memory_pool<TypeParam, POOL_SIZE> p;
void* chunks[POOL_SIZE];
std::set<void*> uniqueChunks;
int numAllocatedChunks = 0;
for (unsigned i = 0; i < POOL_SIZE; ++i)
{
void* c = p.allocate();
ASSERT_TRUE(c != 0);
chunks[i] = c;
uniqueChunks.insert(c);
}
ASSERT_TRUE(p.empty());
ASSERT_EQ(POOL_SIZE, uniqueChunks.size());
for (unsigned i = 0; i < POOL_SIZE; ++i)
{
p.free(chunks[i]);
chunks[i] = 0;
}
for (unsigned i = 0; i < 10000; ++i)
{
unsigned index = testing::random() % POOL_SIZE;
if (chunks[index] == 0)
{
void* c = p.allocate();
ASSERT_TRUE(c != 0);
ASSERT_TRUE(uniqueChunks.find(c) != uniqueChunks.end());
chunks[index] = c;
++numAllocatedChunks;
}
else
{
p.free(chunks[index]);
chunks[index] = 0;
--numAllocatedChunks;
}
ASSERT_EQ(POOL_SIZE - numAllocatedChunks, p.size());
ASSERT_EQ(POOL_SIZE, p.capacity());
}
}
| [
"manuel.freiberger@gmx.at"
] | manuel.freiberger@gmx.at |
f8c81e43262fbc8b22c39faa28d30f5e449b006d | 4e1e2a74279ed35b60cdcbad9561190723b61d80 | /string14.cpp | 5eee45859d77195bc9863966dcb3e8e9897734be | [] | no_license | futre1529/Dsa_Implementations | eb56fef501386f6dd6bdbc26daac9e96e4ffe64e | c9252853f8b73a600b8f9b761664bb07a22b9152 | refs/heads/master | 2016-09-06T07:37:39.530363 | 2014-03-18T19:12:13 | 2014-03-18T19:12:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | cpp | //Find the smallest window in a string containing all characters of another string
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
void window(string str1,string str2)
{
for(int i=str2.length();i<str1.length();i++)
{
for(int j=0;j<str1.length()-i;j++)
{
int *arr=(int *)calloc(256,sizeof(int));
for(int i1=0;i1<str2.length();i1++)
{
arr[str2[i1]]++;
}
string a=str1.substr(j,i);
int count=0;
for(int k=0;k<a.length();k++)
{
if(arr[a[k]]>0)
{
count++;
arr[a[k]]--;
}
}
if(count==str2.length())
{
cout<<" Answer is: "<<a<<"\n";
return;
// break;
// flag=1;
}
free(arr);
}
// if(flag==1)
// break;
}
}
int main()
{
int flag=0;
string str1,str2;
getline(cin,str1);
getline(cin,str2);
window(str1,str2);
return 0;
} | [
"codered@ubuntu.(none)"
] | codered@ubuntu.(none) |
b46dd5515584d90ef6c0d7a507e865a6d498809f | eab41b18da7382a0b75f4cd0d73bfbfb05754444 | /src/utils.h | 193e734845bfe698c2437d307a21702062928b3a | [] | no_license | charlinone/Climber | 8d9d96e4b69127a269b3f6e5692b985c05eb6662 | e37ae612714875156a8b4c2dd519e6709cdecbe6 | refs/heads/master | 2022-10-26T14:09:50.688925 | 2020-06-16T07:58:23 | 2020-06-16T07:58:23 | 272,642,630 | 0 | 0 | null | 2020-06-16T07:43:23 | 2020-06-16T07:43:22 | null | UTF-8 | C++ | false | false | 12,215 | h | //
// Created by Climber on 2020/6/9.
//
#ifndef CLIMBER_UTILS_H
#define CLIMBER_UTILS_H
#include <array>
#include <fstream>
#include <sstream>
#include <wx/wx.h>
#include <wx/clipbrd.h>
#include <wx/tokenzr.h>
#include <wx/sckaddr.h>
#include <wx/socket.h>
#include "Paths.h"
#ifdef CLIMBER_WINDOWS
#include <wx/msw/registry.h>
#include <Windows.h>
#endif
static inline void killProcess(long pid) {
#ifdef CLIMBER_WINDOWS
wxExecute(wxString::Format("taskkill /f /pid %ld", pid), wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
#endif
#ifdef CLIMBER_DARWIN
wxExecute(wxString::Format("kill %ld", pid), wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
#endif
#ifdef CLIMBER_LINUX
wxExecute(wxString::Format("kill %ld", pid), wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
#endif
}
static inline void killProcessByName(const wxString &name) {
#ifdef CLIMBER_WINDOWS
wxExecute(wxString::Format("taskkill /f /im %s", name), wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
#endif
#ifdef CLIMBER_DARWIN
wxExecute(wxString::Format("killall %s", name), wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
#endif
#ifdef CLIMBER_LINUX
wxExecute(wxString::Format("killall %s", name), wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
#endif
}
static wxString
readTextFile(const wxString &file, const wxString &defaultValue = wxEmptyString, bool promptOnFail = false) {
std::ifstream in(file.ToStdString(), std::ios::in);
if (!in.is_open()) {
if (promptOnFail) {
wxMessageDialog(nullptr, wxString::Format("Open file \"%s\" failed!", file), _("Error"))
.ShowModal();
}
return defaultValue;
}
std::stringstream ss;
ss << in.rdbuf();
in.close();
return wxString(ss.str());
}
static void writeTextFile(const wxString &file, const wxString &content) {
std::ofstream out(file.ToStdString(), std::ios::out);
if (!out.is_open()) {
wxMessageDialog(nullptr, wxString::Format("Open file \"%s\" failed! %s", file, strerror(errno)), _("Error"))
.ShowModal();
}
out << content.ToStdString();
out.close();
}
static bool getAutoStart() {
auto name = wxString("Climber");
auto path = Paths::GetExecutablePath();
#ifdef CLIMBER_WINDOWS
wxRegKey regKey(wxRegKey::HKCU, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
if (regKey.HasValue(name)) {
wxString value;
regKey.QueryValue(name, value);
return value == wxString::Format("\"%s\"", path);
} else {
return false;
}
#endif
#ifdef CLIMBER_DARWIN
wxString plistFile = Paths::GetHomePath() + "/Library/LaunchAgents/io.github.climber.plist";
if (!wxFileExists(plistFile)) {
return false;
}
auto plistContent = readTextFile(plistFile);
if (plistContent.find(path) == wxNOT_FOUND) {
return false;
} else {
return true;
}
#endif
#ifdef CLIMBER_LINUX
wxString desktopFile = Paths::GetHomePath() + "/.config/autostart/Climber.desktop";
if (!wxFileExists(desktopFile)) {
return false;
}
auto desktopContent = readTextFile(desktopFile);
if (desktopContent.find(path) == wxNOT_FOUND) {
return false;
} else {
return true;
}
#endif
}
static void setAutoStart(bool enable) {
auto name = wxString("Climber");
auto path = Paths::GetExecutablePath();
#ifdef CLIMBER_WINDOWS
wxRegKey regKey(wxRegKey::HKCU, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
if (enable) {
regKey.SetValue(name, wxString::Format("\"%s\"", path));
} else {
regKey.DeleteValue(name);
}
#endif
#ifdef CLIMBER_DARWIN
wxString plistFile = Paths::GetHomePath() + "/Library/LaunchAgents/io.github.climber.plist";
if (enable) {
wxString plistContent = R"(<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>io.github.climber</string>
<key>ProgramArguments</key>
<array>
<string>__EXECUTABLE__</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/dev/null</string>
<key>StandardOutPath</key>
<string>/dev/null</string>
</dict>
</plist>
)";
plistContent.Replace("__EXECUTABLE__", path);
writeTextFile(plistFile, plistContent);
} else {
if (wxFileExists(plistFile)) {
wxRemoveFile(plistFile);
}
}
#endif
#ifdef CLIMBER_LINUX
wxString desktopFile = Paths::GetHomePath() + "/.config/autostart/Climber.desktop";
if (enable) {
wxString desktopContent = R"[Desktop Entry]
Name=__NAME__
Exec=__EXECUTABLE__
Type=Application
Terminal=false
X-GNOME-Autostart-enabled=true
)";
desktopContent.Replace("__NAME__", name);
desktopContent.Replace("__EXECUTABLE__", path);
writeTextFile(desktopFile, desktopContent);
} else {
if(wxFileExists(desktopFile)) {
wxRemoveFile(desktopFile);
}
}
#endif
}
#ifdef CLIMBER_WINDOWS
static wxString normBypass(const wxString &bypass) {
wxString bypassArgs = wxEmptyString;
wxStringTokenizer tokens(bypass, ";\n,");
while (tokens.HasMoreTokens()) {
auto item = tokens.GetNextToken();
item.Trim();
item.Trim(false);
if (item.empty()) continue;
bypassArgs += wxString::Format("%s;", item);
}
if (bypassArgs.size() > 0) {
bypassArgs = bypassArgs.substr(0, bypassArgs.size() - 1);
}
return bypassArgs;
}
static void setProxy(
const wxString &socksHost, int socksPort,
const wxString &httpHost, int httpPort,
const wxString &bypass) {
auto sysproxy = Paths::GetBinDirFile("climber_sysproxy");
wxExecute(wxString::Format("\"%s\" global \"%s:%d\" \"%s\"", sysproxy, httpHost, httpPort, normBypass(bypass)),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
}
static void setProxyPac(const wxString &pacUrl, const wxString &bypass) {
auto sysproxy = Paths::GetBinDirFile("climber_sysproxy");
wxExecute(wxString::Format("\"%s\" pac \"%s\"", sysproxy, pacUrl), wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
}
static void clearProxy() {
auto sysproxy = Paths::GetBinDirFile("climber_sysproxy");
wxExecute(wxString::Format("\"%s\" off", sysproxy), wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
}
#endif
#ifdef CLIMBER_DARWIN
static wxArrayString getNetworkServices() {
wxArrayString lines;
wxExecute("networksetup -listallnetworkservices", lines, wxEXEC_SYNC | wxEXEC_HIDE_CONSOLE);
lines.erase(lines.begin(), lines.begin() + 1);
return lines;
}
static bool isNetworkServicesActive(const wxString &service) {
wxArrayString lines;
wxExecute(wxString::Format("networksetup -getinfo \"%s\"", service), lines, wxEXEC_SYNC | wxEXEC_HIDE_CONSOLE);
for (auto &line : lines) {
if ((line.find("IP address:") == 0 && line.find("IP address: none") == wxNOT_FOUND)
|| (line.find("IPv6 IP address:") == 0 && line.find("IPv6 IP address: none") == wxNOT_FOUND)) {
return true;
}
}
return false;
}
static wxString normBypass(const wxString &bypass) {
wxString bypassArgs = wxEmptyString;
wxStringTokenizer tokens(bypass, ";\n,");
while (tokens.HasMoreTokens()) {
auto item = tokens.GetNextToken();
item.Trim();
item.Trim(false);
if (item.empty()) continue;
bypassArgs += wxString::Format("\"%s\" ", item);
}
return bypassArgs;
}
static void setProxy(
const wxString &socksHost, int socksPort,
const wxString &httpHost, int httpPort,
const wxString &bypass) {
auto services = getNetworkServices();
for (auto &service : services) {
if (!isNetworkServicesActive(service)) continue;
wxExecute(
wxString::Format("networksetup -setsocksfirewallproxy \"%s\" \"%s\" %d", service, socksHost, socksPort),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setwebproxy \"%s\" \"%s\" %d", service, httpHost, httpPort),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setsecurewebproxy \"%s\" \"%s\" %d", service, httpHost, httpPort),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setautoproxystate \"%s\" off", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setproxybypassdomains \"%s\" %s", service, normBypass(bypass)),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
}
}
static void setProxyPac(const wxString &pacUrl, const wxString &bypass) {
auto services = getNetworkServices();
for (auto &service : services) {
if (!isNetworkServicesActive(service)) continue;
wxExecute(wxString::Format("networksetup -setautoproxyurl \"%s\" \"%s\"", service, pacUrl),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setsocksfirewallproxystate \"%s\" off", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setwebproxystate \"%s\" off", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setsecurewebproxystate \"%s\" off", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setproxybypassdomains \"%s\" %s", service, normBypass(bypass)),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
}
}
static void clearProxy() {
auto services = getNetworkServices();
for (auto &service : services) {
if (!isNetworkServicesActive(service)) continue;
wxExecute(wxString::Format("networksetup -setsocksfirewallproxystate \"%s\" off", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setwebproxystate \"%s\" off", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setsecurewebproxystate \"%s\" off", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setautoproxystate \"%s\" off", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
wxExecute(wxString::Format("networksetup -setproxybypassdomains \"%s\" \"\"", service),
wxEXEC_BLOCK | wxEXEC_HIDE_CONSOLE);
}
}
#endif
static void setClipboardText(const wxString &text) {
if (wxTheClipboard->Open()) {
wxTheClipboard->Clear();
wxTheClipboard->SetData(new wxTextDataObject(text));
wxTheClipboard->Flush();
wxTheClipboard->Close();
}
}
static int compareVersion(wxString v1, wxString v2) {
std::array<long, 3> l1;
wxStringTokenizer tokens1(v1, ".");
for (int i = 0; i < 3; ++i) {
if (tokens1.HasMoreTokens()) {
l1[i] = std::strtol(tokens1.GetNextToken().c_str().AsChar(), nullptr, 10);
} else {
l1[i] = 0;
}
}
std::array<long, 3> l2;
wxStringTokenizer tokens2(v2, ".");
for (int i = 0; i < 3; ++i) {
if (tokens2.HasMoreTokens()) {
l2[i] = std::strtol(tokens2.GetNextToken().c_str().AsChar(), nullptr, 10);
} else {
l2[i] = 0;
}
}
if (l1[0] != l2[0]) {
return l1[0] - l2[0];
} else if (l1[1] != l2[1]) {
return l1[1] - l2[1];
} else {
return l1[2] - l2[2];
}
}
static bool isPortInUse(int port) {
std::function<bool(int)> isPortInUseOnce = [](int port) {
wxIPV4address addr;
addr.Service(port);
wxSocketServer socket(addr);
if (socket.Ok()) {
socket.Close();
return false;
} else {
return true;
}
};
int retry = 3;
while (retry > 0) {
retry--;
if (isPortInUseOnce(port)) {
wxMilliSleep(100);
} else {
return false;
}
}
return true;
}
#endif //CLIMBER_UTILS_H
| [
"wandawaguespack10701@gmail.com"
] | wandawaguespack10701@gmail.com |
e39a59e84219c26297272566f9dc14eae843c78b | fc8a283e0fc71a14732e06ecf464ce5eec3d5235 | /Pandigital/main.cpp | 60f1d273995ae8c2f9a346eec8c8fe36e6d73775 | [] | no_license | alex-t0/clang_examples | b0af2eb1eb268a2cb5b17257cbdd93ab88bc58da | c6bc2566e47139e1ba9d51a3ac33a9c59bf6165a | refs/heads/master | 2021-01-09T06:05:28.213407 | 2017-02-20T21:51:05 | 2017-02-20T21:51:05 | 80,910,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71 | cpp | #include <iostream>
int main(int argc, char **argv)
{
return 0;
}
| [
"alex-t@tiger.lan"
] | alex-t@tiger.lan |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.