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
9916a2a5b757c7ae37fe48a9d4c5d8af7a9cc2ad
c60b1221b9b14b773feda4ee45a2eba13c416354
/KernelIPC/Sources/VComponentLibrary.cpp
b4bfbfab98e8ffd31699de1613d78a6fe82d89c6
[]
no_license
sanyaade-iot/core-XToolbox
ff782929e0581970834f3a2f9761c3ad8c01ec38
507914e3f1b973fc8d372bcf1eeba23d16f2d096
refs/heads/master
2021-01-17T13:26:13.179402
2013-05-16T15:05:10
2013-05-16T15:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,296
cpp
/* * This file is part of Wakanda software, licensed by 4D under * (i) the GNU General Public License version 3 (GNU GPL v3), or * (ii) the Affero General Public License version 3 (AGPL v3) or * (iii) a commercial license. * This file remains the exclusive property of 4D and/or its licensors * and is protected by national and international legislations. * In any event, Licensee's compliance with the terms and conditions * of the applicable license constitutes a prerequisite to any use of this file. * Except as otherwise expressly stated in the applicable license, * such license does not include any other license or rights on this file, * 4D's and/or its licensors' trademarks and/or other proprietary rights. * Consequently, no title, copyright or other proprietary rights * other than those specified in the applicable license is granted. */ // CodeWarrior seems to 'loose' some flags with Mach-O compiler - JT 6/08/2002 #ifndef USE_AUTO_MAIN_CALL #define USE_AUTO_MAIN_CALL 0 // Set to 1 to let the system init/deinit the lib (via main) #endif #include "VKernelIPCPrecompiled.h" #include "VComponentLibrary.h" // Receipe: // // 1) To write a component library, define your component class deriving it // from CComponent. You will provide this class with your library as a header file. // // class CComponent1 : public CComponent // { // public: // enum { Component_Type = 'cmp1' }; // // Blah, blah - Public Interface // }; // // Note that a component has no constructor, no data and only pure virtuals (= 0) // // 2) Then define a custom class deriving from VComponentImp<YourComponent> // and implement your public and private functions. If you want to receive messages, // override ListenToMessage(). You may define several components using the same pattern. // // class VComponentImp1 : public VComponentImp<CComponent1> // { // public: // Blah, blah - Public Interface // // protected: // Blah, blah - Private Stuff // }; // // 3) Declare a kCOMPONENT_TYPE_LIST constant. // This constant will automate the CreateComponent() in the dynamic lib: // // const sLONG kCOMPONENT_TYPE_COUNT = 1; // const CImpDescriptor kCOMPONENT_TYPE_LIST[] = { { CComponent1::Component_Type, // VImpCreator<VComponentImp1>::CreateImp } }; // // 4) Finally define a xDllMain and instantiate a VComponentLibrary* object (with the new operator). // You'll pass your kCOMPONENT_TYPE_LIST array to the constructor. If you need custom library // initialisations, you can write your own class and override contructor, DoRegister, DoUnregister... // // On Mac remember to customize library (PEF) entry-points with __EnterLibrary and __LeaveLibrary // User's main declaration // You should define it in your code and instanciate a VComponentLibrary* object. // // void xbox::ComponentMain (void) // { // new VComponentLibrary(kCOMPONENT_TYPE_LIST, kCOMPONENT_TYPE_COUNT); // } // Statics declaration VComponentLibrary* VComponentLibrary::sComponentLibrary = NULL; Boolean VComponentLibrary::sQuietUnloadLibrary = false; // Shared lib initialisation // On Windows, all job is done by the DllMain function // On Mac/CFM, __initialize and __terminate PEF entries must be set to __EnterLibrary and __LeaveLibrary // On Mac/Mach-O, job is done in the main entry point. // // NOTE: currently the ComponentManager call the main entry-point manually to ensure // the Toolbox is initialized before components (USE_AUTO_MAIN_CALL flag) #if VERSIONWIN BOOL WINAPI DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { BOOL result = true; #if USE_AUTO_MAIN_CALL switch (fdwReason) { case DLL_PROCESS_ATTACH: xDllMain(); // To be renamed ComponentMain(); result = (VComponentLibrary::GetComponentLibrary() != NULL); break; case DLL_PROCESS_DETACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; } #else if (fdwReason == DLL_PROCESS_ATTACH) XWinStackCrawl::RegisterUser( hinstDLL); #endif return result; } #elif VERSION_LINUX //jmo - Be coherent with code in XLinuxDLLMain.cpp extern "C" { void __attribute__ ((constructor)) LibraryInit(); void __attribute__ ((destructor)) LibraryFini(); } void LibraryInit() { #if USE_AUTO_MAIN_CALL xDllMain(); bool ok=VComponentLibrary::GetComponentLibrary()!=NULL; //jmo - I lack ideas, but I'm sure we can do something clever with this 'ok' result ! #endif } void LibraryFini() { //Nothing to do. } #elif VERSION_MACHO #if USE_AUTO_MAIN_CALL #error "Mach-O main entry point isn't defined" #endif #elif VERSIONMAC // Version CFM // L.E. 11/10/01 Drop-Ins MUST have their private destructor chain. // but the global __global_destructor_chain is in global_destructor_chain.c // which is compiled for both MSL DropInRuntime and MSL All-ShlbRuntime... // So I have to define a private chain list and swap the value of the global one when needed. // see MSL StartupDropIn.c extern "C" { // See StartupSharedLib.c for complete PEF entry points informations pascal OSErr __initialize (const CFragInitBlock* theInitBlock); pascal OSErr __EnterLibrary (const CFragInitBlock* theInitBlock); pascal void __terminate (void); pascal void __LeaveLibrary (void); } struct DestructorChain; static DestructorChain* __private_global_destructor_chain; extern DestructorChain* __global_destructor_chain; pascal OSErr __EnterLibrary (const CFragInitBlock* theInitBlock) { DestructorChain *oldChain = __global_destructor_chain; __global_destructor_chain = NULL; OSErr error = __initialize(theInitBlock); __private_global_destructor_chain = __global_destructor_chain; __global_destructor_chain = oldChain; #if USE_AUTO_MAIN_CALL // Call the user's main to allow custom initialization xDllMain(); if (VComponentLibrary::GetComponentLibrary() == NULL) error = cfragInitFunctionErr; #endif return error; } pascal void __LeaveLibrary (void) { DestructorChain *oldChain = __global_destructor_chain; __global_destructor_chain = __private_global_destructor_chain; __terminate(); __global_destructor_chain = oldChain; } #endif // VERSIONMAC // Unmangled export mecanism // #if USE_UNMANGLED_EXPORTS EXPORT_UNMANGLED_API(VError) Main (OsType inEvent, VLibrary* inLibrary); EXPORT_UNMANGLED_API(void) Lock (); EXPORT_UNMANGLED_API(void) Unlock (); EXPORT_UNMANGLED_API(Boolean) CanUnloadLibrary (); EXPORT_UNMANGLED_API(CComponent*) CreateComponent (CType inType, CType inFamily); EXPORT_UNMANGLED_API(Boolean) GetNthComponentType (sLONG inTypeIndex, CType& outType); EXPORT_UNMANGLED_API(CComponent*) CreateComponent (CType inType, CType inFamily) { return VComponentLibrary::CreateComponent(inType, inFamily); } EXPORT_UNMANGLED_API(Boolean) GetNthComponentType (sLONG inTypeIndex, CType& outType) { return VComponentLibrary::GetNthComponentType(inTypeIndex, outType); } EXPORT_UNMANGLED_API(void) Lock () { VComponentLibrary::Lock(); } EXPORT_UNMANGLED_API(void) Unlock () { VComponentLibrary::Unlock(); } EXPORT_UNMANGLED_API(Boolean) CanUnloadLibrary () { return VComponentLibrary::CanUnloadLibrary(); } EXPORT_UNMANGLED_API(VError) Main (OsType inEvent, VLibrary* inLibrary) { return VComponentLibrary::Main(inEvent, inLibrary); } #endif // USE_UNMANGLED_EXPORTS // --------------------------------------------------------------------------- // VComponentLibrary::VComponentLibrary // --------------------------------------------------------------------------- // VComponentLibrary::VComponentLibrary() { Init(); } // --------------------------------------------------------------------------- // VComponentLibrary::VComponentLibrary // --------------------------------------------------------------------------- // VComponentLibrary::VComponentLibrary(const CImpDescriptor* inTypeList, sLONG inTypeCount) { Init(); fComponentTypeList = inTypeList; fComponentTypeCount = inTypeCount; } // --------------------------------------------------------------------------- // VComponentLibrary::~VComponentLibrary // --------------------------------------------------------------------------- // VComponentLibrary::~VComponentLibrary() { xbox_assert(sComponentLibrary == this); sComponentLibrary = NULL; // Make sure all instances has been released if (!sQuietUnloadLibrary) { xbox_assert(fDebugInstanceCount == 0); } } // --------------------------------------------------------------------------- // VComponentLibrary::Main [static][exported] // --------------------------------------------------------------------------- // Cross-platform main entry point // VError VComponentLibrary::Main(OsType inEvent, VLibrary* inLibrary) { VError error = VE_COMP_CANNOT_LOAD_LIBRARY; #if !USE_AUTO_MAIN_CALL // Call the user's main to allow custom initialization // This is done here if not handled automatically if (inEvent == kDLL_EVENT_REGISTER) xDllMain(); #endif VComponentLibrary* componentLibrary = VComponentLibrary::GetComponentLibrary(); if (componentLibrary == NULL) DebugMsg(L"You must instantiate a VComponentLibrary* in your xDllMain\n"); if (componentLibrary != NULL) { switch (inEvent) { case kDLL_EVENT_REGISTER: componentLibrary->fLibrary = inLibrary; componentLibrary->Register(); error = VE_OK; break; case kDLL_EVENT_UNREGISTER: componentLibrary->Unregister(); error = VE_OK; break; } } return error; } // --------------------------------------------------------------------------- // VComponentLibrary::Lock [static][exported] // --------------------------------------------------------------------------- // Call when you want to block component creation (typically before // releasing the library) // void VComponentLibrary::Lock() { if (sComponentLibrary == NULL) { DebugMsg(L"You must customize library entry points\n"); return; } VTaskLock locker(&sComponentLibrary->fCreatingCriticalSection); sComponentLibrary->fLockCount++; } // --------------------------------------------------------------------------- // VComponentLibrary::Unlock [static][exported] // --------------------------------------------------------------------------- // Call if you no longer want to block component creation // void VComponentLibrary::Unlock() { if (sComponentLibrary == NULL) { DebugMsg(L"You must customize library entry points\n"); return; } VTaskLock locker(&sComponentLibrary->fCreatingCriticalSection); sComponentLibrary->fLockCount--; } // --------------------------------------------------------------------------- // VComponentLibrary::CanUnloadLibrary [static][exported] // --------------------------------------------------------------------------- // Call to known if library can be unloaded. Make sure you locked before. // // This code is automatically called while the library is unloading: // 1) if the library is unloaded by the toolbox, we're called from VLibrary's destructor // 2) if the library is unloaded by the OS, the VLibrary hasn't been deleted // In any cases library has still valid datas (globals). Boolean VComponentLibrary::CanUnloadLibrary() { if (sComponentLibrary == NULL) { DebugMsg(L"You must customize library entry points\n"); return false; } // Each component in the library as increased the refcount (will be decreased later // by the Component Manager). A greater refcount means some component instances are // still running. VLibrary* library = sComponentLibrary->fLibrary; return ((library != NULL) ? library->GetRefCount() == sComponentLibrary->fComponentTypeCount : true); } // --------------------------------------------------------------------------- // VComponentLibrary::CreateComponent [static][exported] // --------------------------------------------------------------------------- // Entry point in the library for creating any component it defines // CComponent* VComponentLibrary::CreateComponent(CType inType, CType inGroup) { if (sComponentLibrary == NULL) { DebugMsg(L"You must customize library entry points\n"); return NULL; } if (sComponentLibrary->fComponentTypeList == NULL) { DebugMsg(L"You must specify a TypeList for your lib\n"); return NULL; } CComponent* component = NULL; sLONG typeIndex = 0; // Look for the type index while (sComponentLibrary->fComponentTypeList[typeIndex].componentType != inType && typeIndex < sComponentLibrary->fComponentTypeCount) { typeIndex++; } // If found, instanciate the component using factory's member address if (sComponentLibrary->fComponentTypeList[typeIndex].componentType == inType) { VTaskLock locker(&sComponentLibrary->fCreatingCriticalSection); // Make sure component creation isn't locked if (sComponentLibrary->fLockCount == 0) component = (sComponentLibrary->fComponentTypeList[typeIndex].impCreator)(inGroup); } return component; } // --------------------------------------------------------------------------- // VComponentLibrary::GetNthComponentType [static][exported] // --------------------------------------------------------------------------- // Return the list of component types it may create /// Boolean VComponentLibrary::GetNthComponentType(sLONG inTypeIndex, CType& outType) { if (sComponentLibrary == NULL) { DebugMsg(L"You must customize library entry points\n"); return false; } if (sComponentLibrary->fComponentTypeList == NULL) { DebugMsg(L"You must specify a TypeList for your lib\n"); return false; } if (inTypeIndex < 1 || inTypeIndex > sComponentLibrary->fComponentTypeCount) return false; outType = sComponentLibrary->fComponentTypeList[inTypeIndex - 1].componentType; return true; } // --------------------------------------------------------------------------- // VComponentLibrary::RegisterOneInstance(CType inType) // --------------------------------------------------------------------------- // Increase component instance count // VIndex VComponentLibrary::RegisterOneInstance(CType /*inType*/) { // Increase library's refcount as the component may use global datas if (fLibrary != NULL) fLibrary->Retain(); fDebugInstanceCount++; return VInterlocked::Increment(&fUniqueInstanceIndex); } // --------------------------------------------------------------------------- // VComponentLibrary::UnRegisterOneInstance(CType inType) // --------------------------------------------------------------------------- // Decrease component instance count // void VComponentLibrary::UnRegisterOneInstance(CType /*inType*/) { // Decrease library's refcount as the component no longer need it if (fLibrary != NULL) fLibrary->Release(); fDebugInstanceCount--; } // --------------------------------------------------------------------------- // VComponentLibrary::Register // --------------------------------------------------------------------------- // Entry point for library initialisation // void VComponentLibrary::Register() { DoRegister(); } // --------------------------------------------------------------------------- // VComponentLibrary::Unregister // --------------------------------------------------------------------------- // Entry point for library termination // void VComponentLibrary::Unregister() { DoUnregister(); } // --------------------------------------------------------------------------- // VComponentLibrary::DoRegister // --------------------------------------------------------------------------- // Override to handle custom initialisation // void VComponentLibrary::DoRegister() { } // --------------------------------------------------------------------------- // VComponentLibrary::DoUnregister // --------------------------------------------------------------------------- // Override to handle custom termination // void VComponentLibrary::DoUnregister() { } // --------------------------------------------------------------------------- // VComponentLibrary::Init [private] // --------------------------------------------------------------------------- // void VComponentLibrary::Init() { fLockCount = 0; fUniqueInstanceIndex = 0; fComponentTypeList = NULL; fComponentTypeCount = 0; fLibrary = NULL; fDebugInstanceCount = 0; if (sComponentLibrary != NULL) DebugMsg(L"You must instanciate only ONE VComponentLibrary object\n"); sComponentLibrary = this; }
[ "stephane.hamel@4d.com" ]
stephane.hamel@4d.com
f2c1269a7d30a2d3cbcafa5c517b5988336674ed
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE762_Mismatched_Memory_Management_Routines/s03/CWE762_Mismatched_Memory_Management_Routines__delete_int_malloc_52c.cpp
44a1b82471275852fbdde508e093a7a39572adf9
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
1,533
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_int_malloc_52c.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-52c.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: malloc Allocate data using malloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_int_malloc_52 { #ifndef OMITBAD void badSink_c(int * data) { /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(int * data) { /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink_c(int * data) { /* FIX: Deallocate the memory using free() */ free(data); } #endif /* OMITGOOD */ } /* close namespace */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
62a8704249ab345c972c35ce95bd9272ac375bdd
442cb88aa69ea9f8c85bf476d3afb130da886e9c
/src/PathBuilder.cpp
a8fad0d33e92f2a9c8619441468eaaf946b7d746
[ "Apache-2.0" ]
permissive
jim-bcom/xpcf
bcb4e3b6a76e2266a86a68f1f36a0dad313bab08
26ce21929ff6209ef69117270cf49844348c988f
refs/heads/master
2023-09-01T15:22:02.488646
2021-10-04T11:56:09
2021-10-04T11:56:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,018
cpp
/** * @copyright Copyright (c) 2017 B-com http://www.b-com.com/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Loïc Touraine * * @file * @brief description of file * @date 2017-11-23 */ #include "PathBuilder.h" #include <boost/filesystem/detail/utf8_codecvt_facet.hpp> #include <boost/predef/os.h> #ifdef WIN32 #include <stdlib.h> #else #include <pwd.h> #include <sys/types.h> #endif #include <regex> #include <boost/filesystem/detail/utf8_codecvt_facet.hpp> namespace fs = boost::filesystem; namespace org { namespace bcom { namespace xpcf { PathBuilder::PathBuilder() { } fs::path PathBuilder::findRegistries() { return ""; } fs::path PathBuilder::getUTF8PathObserver(const char * sourcePath) { fs::detail::utf8_codecvt_facet utf8; fs::path utf8ObservedPath(sourcePath, utf8); return utf8ObservedPath; } fs::path PathBuilder::getUTF8PathObserver(const std::string & sourcePath) { return getUTF8PathObserver(sourcePath.c_str()); } fs::path PathBuilder::replaceRootEnvVars(const std::string & sourcePath) { // find any $ENVVAR and substitut fs::path completePath = getUTF8PathObserver(sourcePath); // howto manage i18n on env vars ? : env vars don't support accented characters std::string regexStr="^\\$([a-zA-Z0-9_]*)/"; std::regex envVarRegex(regexStr, std::regex_constants::extended); std::smatch sm; if (std::regex_search(sourcePath, sm, envVarRegex)) { std::string matchStr = sm.str(1); char * envVar = getenv(matchStr.c_str()); if (envVar != nullptr) { fs::path envStr (envVar); std::string replacedStr = std::regex_replace(sourcePath, envVarRegex, ""); fs::path subdir (replacedStr); completePath = envStr / subdir; } } return completePath; } fs::path PathBuilder::buildModuleFolderPath(const std::string & filePathStr) { fs::path filePath(replaceRootEnvVars(filePathStr)); #ifdef XPCFSUBDIRSEARCH fs::path modeSubDir = XPCFSUBDIRSEARCH; if ( fs::exists( filePath / modeSubDir ) ) { filePath /= modeSubDir; } #endif return filePath; } fs::path PathBuilder::buildModuleFilePath(const std::string & moduleName, const std::string & filePathStr) { fs::path filePath = buildModuleFolderPath(filePathStr); fs::path moduleFileName = getUTF8PathObserver(moduleName.c_str()); filePath /= moduleFileName; return filePath; } fs::path PathBuilder::getHomePath() { char * homePathStr; fs::path homePath; #ifdef WIN32 homePathStr = getenv("USERPROFILE"); if (homePathStr == nullptr) { homePathStr = getenv("HOMEDRIVE"); if (homePathStr) { homePath = getUTF8PathObserver(homePathStr); homePath /= getenv("HOMEPATH"); } } else { homePath = getUTF8PathObserver(homePathStr); } #else struct passwd* pwd = getpwuid(getuid()); if (pwd) { homePathStr = pwd->pw_dir; } else { // try the $HOME environment variable homePathStr = getenv("HOME"); } homePath = getUTF8PathObserver(homePathStr); #endif return homePath; } fs::path PathBuilder::getXPCFHomePath() { fs::path xpcfHomePath = getHomePath(); xpcfHomePath /= ".xpcf"; return xpcfHomePath; } static fs::path suffix() { // https://sourceforge.net/p/predef/wiki/OperatingSystems/ #if BOOST_OS_MACOS || BOOST_OS_IOS return ".dylib"; #elif BOOST_OS_WINDOWS return L".dll"; #else return ".so"; #endif } fs::path PathBuilder::appendModuleDecorations(const fs::path & sl) { fs::path actual_path = sl; if ( actual_path.stem() == actual_path.filename() ) { // there is no suffix actual_path += suffix().native(); } #if BOOST_OS_WINDOWS if (!fs::exists(actual_path)) { // MinGW loves 'lib' prefix and puts it even on Windows platform actual_path = (actual_path.has_parent_path() ? actual_path.parent_path() / L"lib" : L"lib").native() + actual_path.filename().native(); } #else //posix actual_path = (std::strncmp(actual_path.filename().string().c_str(), "lib", 3) ? (actual_path.has_parent_path() ? actual_path.parent_path() / L"lib" : L"lib").native() + actual_path.filename().native() : actual_path); #endif return actual_path; } fs::path PathBuilder::appendModuleDecorations(const char * sl) { fs::path currentPath = getUTF8PathObserver(sl); return appendModuleDecorations(currentPath); } }}}
[ "loic.touraine@gmail.com" ]
loic.touraine@gmail.com
de2cf38e4079dc82cc5f6471ea34f65e5e79461b
810837f2641e2a20826cb75b161ca3458917b1c2
/ash/login/ui/pin_request_view.cc
30824210cb72a13072b5a185bd03d8ee49f0e106
[ "BSD-3-Clause" ]
permissive
kan25/chromium
c425d4e1901816815bbde82c9c8d403507cbf588
27dc5aad16333a7be11602f4adb502cdc8759051
refs/heads/master
2023-02-24T09:04:16.104622
2020-03-13T18:03:42
2020-03-13T18:03:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
41,378
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/login/ui/pin_request_view.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include "ash/login/login_screen_controller.h" #include "ash/login/ui/arrow_button_view.h" #include "ash/login/ui/login_button.h" #include "ash/login/ui/login_pin_view.h" #include "ash/login/ui/non_accessible_view.h" #include "ash/login/ui/pin_request_widget.h" #include "ash/public/cpp/login_constants.h" #include "ash/public/cpp/login_types.h" #include "ash/public/cpp/shelf_config.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_provider.h" #include "ash/wallpaper/wallpaper_controller_impl.h" #include "base/bind.h" #include "base/logging.h" #include "base/optional.h" #include "base/strings/strcat.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "components/session_manager/session_manager_types.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/event.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_analysis.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/font.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/background.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/vector_icons.h" namespace ash { namespace { // Identifier of pin request input views group used for focus traversal. constexpr int kPinRequestInputGroup = 1; constexpr int kPinRequestViewWidthDp = 340; constexpr int kPinKeyboardHeightDp = 224; constexpr int kPinRequestViewRoundedCornerRadiusDp = 8; constexpr int kPinRequestViewVerticalInsetDp = 8; // Inset for all elements except the back button. constexpr int kPinRequestViewMainHorizontalInsetDp = 36; // Minimum inset (= back button inset). constexpr int kPinRequestViewHorizontalInsetDp = 8; constexpr int kCrossSizeDp = 20; constexpr int kBackButtonSizeDp = 36; constexpr int kLockIconSizeDp = 24; constexpr int kBackButtonLockIconVerticalOverlapDp = 8; constexpr int kHeaderHeightDp = kBackButtonSizeDp + kLockIconSizeDp - kBackButtonLockIconVerticalOverlapDp; constexpr int kIconToTitleDistanceDp = 24; constexpr int kTitleToDescriptionDistanceDp = 8; constexpr int kDescriptionToAccessCodeDistanceDp = 32; constexpr int kAccessCodeToPinKeyboardDistanceDp = 16; constexpr int kPinKeyboardToFooterDistanceDp = 16; constexpr int kSubmitButtonBottomMarginDp = 28; constexpr int kTitleFontSizeDeltaDp = 4; constexpr int kTitleLineWidthDp = 268; constexpr int kTitleLineHeightDp = 24; constexpr int kTitleMaxLines = 4; constexpr int kDescriptionFontSizeDeltaDp = 0; constexpr int kDescriptionLineWidthDp = 268; constexpr int kDescriptionTextLineHeightDp = 18; constexpr int kDescriptionMaxLines = 4; constexpr int kAccessCodeFlexLengthWidthDp = 192; constexpr int kAccessCodeFlexUnderlineThicknessDp = 1; constexpr int kAccessCodeFontSizeDeltaDp = 4; constexpr int kObscuredGlyphSpacingDp = 6; constexpr int kAccessCodeInputFieldWidthDp = 24; constexpr int kAccessCodeInputFieldUnderlineThicknessDp = 2; constexpr int kAccessCodeInputFieldHeightDp = 24 + kAccessCodeInputFieldUnderlineThicknessDp; constexpr int kAccessCodeBetweenInputFieldsGapDp = 8; constexpr int kArrowButtonSizeDp = 48; constexpr int kPinRequestViewMinimumHeightDp = kPinRequestViewMainHorizontalInsetDp + kLockIconSizeDp + kIconToTitleDistanceDp + kTitleToDescriptionDistanceDp + kDescriptionToAccessCodeDistanceDp + kAccessCodeInputFieldHeightDp + kAccessCodeToPinKeyboardDistanceDp + kPinKeyboardToFooterDistanceDp + kArrowButtonSizeDp + kPinRequestViewMainHorizontalInsetDp; // = 266 constexpr int kAlpha70Percent = 178; constexpr int kAlpha74Percent = 189; constexpr SkColor kTextColor = SK_ColorWHITE; constexpr SkColor kErrorColor = gfx::kGoogleRed300; constexpr SkColor kArrowButtonColor = SkColorSetARGB(0x2B, 0xFF, 0xFF, 0xFF); bool IsTabletMode() { return Shell::Get()->tablet_mode_controller()->InTabletMode(); } } // namespace PinRequest::PinRequest() = default; PinRequest::PinRequest(PinRequest&&) = default; PinRequest& PinRequest::operator=(PinRequest&&) = default; PinRequest::~PinRequest() = default; // Label button that displays focus ring. class PinRequestView::FocusableLabelButton : public views::LabelButton { public: FocusableLabelButton(views::ButtonListener* listener, const base::string16& text) : views::LabelButton(listener, text) { SetInstallFocusRingOnFocus(true); focus_ring()->SetColor(ShelfConfig::Get()->shelf_focus_border_color()); } FocusableLabelButton(const FocusableLabelButton&) = delete; FocusableLabelButton& operator=(const FocusableLabelButton&) = delete; ~FocusableLabelButton() override = default; }; class PinRequestView::AccessCodeInput : public views::View, public views::TextfieldController { public: AccessCodeInput() = default; ~AccessCodeInput() override = default; // Deletes the last character. virtual void Backspace() = 0; // Appends a digit to the code. virtual void InsertDigit(int value) = 0; // Returns access code as string. virtual base::Optional<std::string> GetCode() const = 0; // Sets the color of the input text. virtual void SetInputColor(SkColor color) = 0; virtual void SetInputEnabled(bool input_enabled) = 0; // Clears the input field(s). virtual void ClearInput() = 0; }; class PinRequestView::FlexCodeInput : public AccessCodeInput { public: using OnInputChange = base::RepeatingCallback<void(bool enable_submit)>; using OnEnter = base::RepeatingClosure; using OnEscape = base::RepeatingClosure; // Builds the view for an access code that consists out of an unknown number // of digits. |on_input_change| will be called upon digit insertion, deletion // or change. |on_enter| will be called when code is complete and user presses // enter to submit it for validation. |on_escape| will be called when pressing // the escape key. |obscure_pin| determines whether the entered pin is // displayed as clear text or as bullet points. FlexCodeInput(OnInputChange on_input_change, OnEnter on_enter, OnEscape on_escape, bool obscure_pin) : on_input_change_(std::move(on_input_change)), on_enter_(std::move(on_enter)), on_escape_(std::move(on_escape)) { DCHECK(on_input_change_); DCHECK(on_enter_); DCHECK(on_escape_); SetLayoutManager(std::make_unique<views::FillLayout>()); code_field_ = AddChildView(std::make_unique<views::Textfield>()); code_field_->set_controller(this); code_field_->SetTextColor(login_constants::kAuthMethodsTextColor); code_field_->SetFontList(views::Textfield::GetDefaultFontList().Derive( kAccessCodeFontSizeDeltaDp, gfx::Font::FontStyle::NORMAL, gfx::Font::Weight::NORMAL)); code_field_->SetBorder(views::CreateSolidSidedBorder( 0, 0, kAccessCodeFlexUnderlineThicknessDp, 0, kTextColor)); code_field_->SetBackgroundColor(SK_ColorTRANSPARENT); code_field_->SetFocusBehavior(FocusBehavior::ALWAYS); code_field_->SetPreferredSize( gfx::Size(kAccessCodeFlexLengthWidthDp, kAccessCodeInputFieldHeightDp)); if (obscure_pin) { code_field_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); code_field_->SetObscuredGlyphSpacing(kObscuredGlyphSpacingDp); } else { code_field_->SetTextInputType(ui::TEXT_INPUT_TYPE_NUMBER); } } FlexCodeInput(const FlexCodeInput&) = delete; FlexCodeInput& operator=(const FlexCodeInput&) = delete; ~FlexCodeInput() override = default; // Appends |value| to the code void InsertDigit(int value) override { DCHECK_LE(0, value); DCHECK_GE(9, value); if (code_field_->GetEnabled()) { code_field_->SetText(code_field_->GetText() + base::NumberToString16(value)); on_input_change_.Run(true); } } // Deletes the last character or the selected text. void Backspace() override { // Instead of just adjusting code_field_ text directly, fire a backspace key // event as this handles the various edge cases (ie, selected text). // views::Textfield::OnKeyPressed is private, so we call it via views::View. auto* view = static_cast<views::View*>(code_field_); view->OnKeyPressed(ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_BACK, ui::DomCode::BACKSPACE, ui::EF_NONE)); view->OnKeyPressed(ui::KeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_BACK, ui::DomCode::BACKSPACE, ui::EF_NONE)); // This triggers ContentsChanged(), which calls |on_input_change_|. } // Returns access code as string if field contains input. base::Optional<std::string> GetCode() const override { base::string16 code = code_field_->GetText(); if (!code.length()) { return base::nullopt; } return base::UTF16ToUTF8(code); } // Sets the color of the input text. void SetInputColor(SkColor color) override { code_field_->SetTextColor(color); } void SetInputEnabled(bool input_enabled) override { code_field_->SetEnabled(input_enabled); } // Clears text in input text field. void ClearInput() override { code_field_->SetText(base::string16()); on_input_change_.Run(false); } void RequestFocus() override { code_field_->RequestFocus(); } // views::TextfieldController void ContentsChanged(views::Textfield* sender, const base::string16& new_contents) override { const bool has_content = new_contents.length() > 0; on_input_change_.Run(has_content); } // views::TextfieldController bool HandleKeyEvent(views::Textfield* sender, const ui::KeyEvent& key_event) override { // Only handle keys. if (key_event.type() != ui::ET_KEY_PRESSED) return false; // Default handling for events with Alt modifier like spoken feedback. if (key_event.IsAltDown()) return false; // FlexCodeInput class responds to a limited subset of key press events. // All events not handled below are sent to |code_field_|. const ui::KeyboardCode key_code = key_event.key_code(); // Allow using tab for keyboard navigation. if (key_code == ui::VKEY_TAB || key_code == ui::VKEY_BACKTAB) return false; if (key_code == ui::VKEY_RETURN) { if (GetCode().has_value()) { on_enter_.Run(); } return true; } if (key_code == ui::VKEY_ESCAPE) { on_escape_.Run(); return true; } // We only expect digits in the PIN, so we swallow all letters. if (key_code >= ui::VKEY_A && key_code <= ui::VKEY_Z) return true; return false; } private: views::Textfield* code_field_; // To be called when access input code changes (digit is inserted, deleted or // updated). Passes true when code non-empty. OnInputChange on_input_change_; // To be called when user pressed enter to submit. OnEnter on_enter_; // To be called when user presses escape to go back. OnEscape on_escape_; }; // Accessible input field for a single digit in fixed length codes. // Customizes field description and focus behavior. class AccessibleInputField : public views::Textfield { public: AccessibleInputField() = default; ~AccessibleInputField() override = default; void set_accessible_description(const base::string16& description) { accessible_description_ = description; } // views::View: void GetAccessibleNodeData(ui::AXNodeData* node_data) override { views::Textfield::GetAccessibleNodeData(node_data); // The following property setup is needed to match the custom behavior of // pin input. It results in the following a11y vocalizations: // * when input field is empty: "Next number, {current field index} of // {number of fields}" // * when input field is populated: "{value}, {current field index} of // {number of fields}" node_data->RemoveState(ax::mojom::State::kEditable); node_data->role = ax::mojom::Role::kListItem; base::string16 description = views::Textfield::GetText().empty() ? accessible_description_ : GetText(); node_data->AddStringAttribute(ax::mojom::StringAttribute::kRoleDescription, base::UTF16ToUTF8(description)); } bool IsGroupFocusTraversable() const override { return false; } View* GetSelectedViewForGroup(int group) override { return parent() ? parent()->GetSelectedViewForGroup(group) : nullptr; } void OnGestureEvent(ui::GestureEvent* event) override { if (event->type() == ui::ET_GESTURE_TAP_DOWN) { RequestFocusWithPointer(event->details().primary_pointer_type()); return; } views::Textfield::OnGestureEvent(event); } private: base::string16 accessible_description_; DISALLOW_COPY_AND_ASSIGN(AccessibleInputField); }; // Digital access code input view for variable length of input codes. // Displays a separate underscored field for every input code digit. class PinRequestView::FixedLengthCodeInput : public AccessCodeInput { public: using OnInputChange = base::RepeatingCallback<void(bool last_field_active, bool complete)>; using OnEnter = base::RepeatingClosure; using OnEscape = base::RepeatingClosure; class TestApi { public: explicit TestApi( PinRequestView::FixedLengthCodeInput* fixed_length_code_input) : fixed_length_code_input_(fixed_length_code_input) {} ~TestApi() = default; views::Textfield* GetInputTextField(int index) { DCHECK_LT(static_cast<size_t>(index), fixed_length_code_input_->input_fields_.size()); return fixed_length_code_input_->input_fields_[index]; } private: PinRequestView::FixedLengthCodeInput* fixed_length_code_input_; }; // Builds the view for an access code that consists out of |length| digits. // |on_input_change| will be called upon access code digit insertion, deletion // or change. True will be passed if the current code is complete (all digits // have input values) and false otherwise. |on_enter| will be called when code // is complete and user presses enter to submit it for validation. |on_escape| // will be called when pressing the escape key. |obscure_pin| determines // whether the entered pin is displayed as clear text or as bullet points. FixedLengthCodeInput(int length, OnInputChange on_input_change, OnEnter on_enter, OnEscape on_escape, bool obscure_pin) : on_input_change_(std::move(on_input_change)), on_enter_(std::move(on_enter)), on_escape_(std::move(on_escape)) { DCHECK_LT(0, length); DCHECK(on_input_change_); SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(), kAccessCodeBetweenInputFieldsGapDp)); SetGroup(kPinRequestInputGroup); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); for (int i = 0; i < length; ++i) { auto* field = new AccessibleInputField(); field->set_controller(this); field->SetPreferredSize(gfx::Size(kAccessCodeInputFieldWidthDp, kAccessCodeInputFieldHeightDp)); field->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_CENTER); field->SetBackgroundColor(SK_ColorTRANSPARENT); if (obscure_pin) { field->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); } else { field->SetTextInputType(ui::TEXT_INPUT_TYPE_NUMBER); } field->SetTextColor(kTextColor); field->SetFontList(views::Textfield::GetDefaultFontList().Derive( kAccessCodeFontSizeDeltaDp, gfx::Font::FontStyle::NORMAL, gfx::Font::Weight::NORMAL)); field->SetBorder(views::CreateSolidSidedBorder( 0, 0, kAccessCodeInputFieldUnderlineThicknessDp, 0, kTextColor)); field->SetGroup(kPinRequestInputGroup); field->set_accessible_description(l10n_util::GetStringUTF16( IDS_ASH_LOGIN_PIN_REQUEST_NEXT_NUMBER_PROMPT)); input_fields_.push_back(field); AddChildView(field); } } ~FixedLengthCodeInput() override = default; FixedLengthCodeInput(const FixedLengthCodeInput&) = delete; FixedLengthCodeInput& operator=(const FixedLengthCodeInput&) = delete; // Inserts |value| into the |active_field_| and moves focus to the next field // if it exists. void InsertDigit(int value) override { DCHECK_LE(0, value); DCHECK_GE(9, value); ActiveField()->SetText(base::NumberToString16(value)); bool was_last_field = IsLastFieldActive(); // Moving focus is delayed by using PostTask to allow for proper // a11y announcements. Without that some of them are skipped. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&FixedLengthCodeInput::FocusNextField, weak_ptr_factory_.GetWeakPtr())); on_input_change_.Run(was_last_field, GetCode().has_value()); } // Clears input from the |active_field_|. If |active_field| is empty moves // focus to the previous field (if exists) and clears input there. void Backspace() override { if (ActiveInput().empty()) { FocusPreviousField(); } ActiveField()->SetText(base::string16()); on_input_change_.Run(IsLastFieldActive(), false /*complete*/); } // Returns access code as string if all fields contain input. base::Optional<std::string> GetCode() const override { std::string result; size_t length; for (auto* field : input_fields_) { length = field->GetText().length(); if (!length) return base::nullopt; DCHECK_EQ(1u, length); base::StrAppend(&result, {base::UTF16ToUTF8(field->GetText())}); } return result; } // Sets the color of the input text. void SetInputColor(SkColor color) override { for (auto* field : input_fields_) { field->SetTextColor(color); } } // views::View: bool IsGroupFocusTraversable() const override { return false; } View* GetSelectedViewForGroup(int group) override { return ActiveField(); } void RequestFocus() override { ActiveField()->RequestFocus(); } void GetAccessibleNodeData(ui::AXNodeData* node_data) override { views::View::GetAccessibleNodeData(node_data); node_data->role = ax::mojom::Role::kGroup; } // views::TextfieldController: bool HandleKeyEvent(views::Textfield* sender, const ui::KeyEvent& key_event) override { if (key_event.type() != ui::ET_KEY_PRESSED) return false; // Default handling for events with Alt modifier like spoken feedback. if (key_event.IsAltDown()) return false; // FixedLengthCodeInput class responds to limited subset of key press // events. All key pressed events not handled below are ignored. const ui::KeyboardCode key_code = key_event.key_code(); if (key_code == ui::VKEY_TAB || key_code == ui::VKEY_BACKTAB) { // Allow using tab for keyboard navigation. return false; } else if (key_code >= ui::VKEY_0 && key_code <= ui::VKEY_9) { InsertDigit(key_code - ui::VKEY_0); } else if (key_code >= ui::VKEY_NUMPAD0 && key_code <= ui::VKEY_NUMPAD9) { InsertDigit(key_code - ui::VKEY_NUMPAD0); } else if (key_code == ui::VKEY_LEFT) { FocusPreviousField(); } else if (key_code == ui::VKEY_RIGHT) { // Do not allow to leave empty field when moving focus with arrow key. if (!ActiveInput().empty()) FocusNextField(); } else if (key_code == ui::VKEY_BACK) { Backspace(); } else if (key_code == ui::VKEY_RETURN) { if (GetCode().has_value()) on_enter_.Run(); } else if (key_code == ui::VKEY_ESCAPE) { on_escape_.Run(); } return true; } bool HandleMouseEvent(views::Textfield* sender, const ui::MouseEvent& mouse_event) override { if (!(mouse_event.IsOnlyLeftMouseButton() || mouse_event.IsOnlyRightMouseButton())) { return false; } // Move focus to the field that was selected with mouse input. for (size_t i = 0; i < input_fields_.size(); ++i) { if (input_fields_[i] == sender) { active_input_index_ = i; RequestFocus(); break; } } return true; } bool HandleGestureEvent(views::Textfield* sender, const ui::GestureEvent& gesture_event) override { if (gesture_event.details().type() != ui::EventType::ET_GESTURE_TAP) return false; // Move focus to the field that was selected with gesture. for (size_t i = 0; i < input_fields_.size(); ++i) { if (input_fields_[i] == sender) { active_input_index_ = i; RequestFocus(); break; } } return true; } // Enables/disables entering a PIN. Currently, there is no use-case the uses // this with fixed length PINs. void SetInputEnabled(bool input_enabled) override { NOTIMPLEMENTED(); } // Clears the PIN fields. Currently, there is no use-case the uses this with // fixed length PINs. void ClearInput() override { NOTIMPLEMENTED(); } private: // Moves focus to the previous input field if it exists. void FocusPreviousField() { if (active_input_index_ == 0) return; --active_input_index_; ActiveField()->RequestFocus(); } // Moves focus to the next input field if it exists. void FocusNextField() { if (IsLastFieldActive()) return; ++active_input_index_; ActiveField()->RequestFocus(); } // Returns whether last input field is currently active. bool IsLastFieldActive() const { return active_input_index_ == (static_cast<int>(input_fields_.size()) - 1); } // Returns pointer to the active input field. AccessibleInputField* ActiveField() const { return input_fields_[active_input_index_]; } // Returns text in the active input field. const base::string16& ActiveInput() const { return ActiveField()->GetText(); } // To be called when access input code changes (digit is inserted, deleted or // updated). Passes true when code is complete (all digits have input value) // and false otherwise. OnInputChange on_input_change_; // To be called when user pressed enter to submit. OnEnter on_enter_; // To be called when user pressed escape to close view. OnEscape on_escape_; // An active/focused input field index. Incoming digit will be inserted here. int active_input_index_ = 0; // Unowned input textfields ordered from the first to the last digit. std::vector<AccessibleInputField*> input_fields_; base::WeakPtrFactory<FixedLengthCodeInput> weak_ptr_factory_{this}; }; PinRequestView::TestApi::TestApi(PinRequestView* view) : view_(view) { DCHECK(view_); } PinRequestView::TestApi::~TestApi() = default; LoginButton* PinRequestView::TestApi::back_button() { return view_->back_button_; } views::Label* PinRequestView::TestApi::title_label() { return view_->title_label_; } views::Label* PinRequestView::TestApi::description_label() { return view_->description_label_; } views::View* PinRequestView::TestApi::access_code_view() { return view_->access_code_view_; } views::LabelButton* PinRequestView::TestApi::help_button() { return view_->help_button_; } ArrowButtonView* PinRequestView::TestApi::submit_button() { return view_->submit_button_; } LoginPinView* PinRequestView::TestApi::pin_keyboard_view() { return view_->pin_keyboard_view_; } views::Textfield* PinRequestView::TestApi::GetInputTextField(int index) { return PinRequestView::FixedLengthCodeInput::TestApi( static_cast<PinRequestView::FixedLengthCodeInput*>( view_->access_code_view_)) .GetInputTextField(index); } PinRequestViewState PinRequestView::TestApi::state() const { return view_->state_; } // static SkColor PinRequestView::GetChildUserDialogColor(bool using_blur) { SkColor color = AshColorProvider::Get()->GetBaseLayerColor( AshColorProvider::BaseLayerType::kOpaque, AshColorProvider::AshColorMode::kDark); SkColor extracted_color = Shell::Get()->wallpaper_controller()->GetProminentColor( color_utils::ColorProfile(color_utils::LumaRange::DARK, color_utils::SaturationRange::MUTED)); if (extracted_color != kInvalidWallpaperColor && extracted_color != SK_ColorTRANSPARENT) { color = color_utils::GetResultingPaintColor( SkColorSetA(SK_ColorBLACK, kAlpha70Percent), extracted_color); } return using_blur ? SkColorSetA(color, kAlpha74Percent) : color; } // TODO(crbug.com/1061008): Make dialog look good on small screens with high // zoom factor. PinRequestView::PinRequestView(PinRequest request, Delegate* delegate) : delegate_(delegate), on_pin_request_done_(std::move(request.on_pin_request_done)), pin_keyboard_always_enabled_(request.pin_keyboard_always_enabled), default_title_(request.title), default_description_(request.description), default_accessible_title_(request.accessible_title.empty() ? request.title : request.accessible_title) { // Main view contains all other views aligned vertically and centered. auto layout = std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(kPinRequestViewVerticalInsetDp, kPinRequestViewHorizontalInsetDp), 0); layout->set_main_axis_alignment(views::BoxLayout::MainAxisAlignment::kStart); layout->set_cross_axis_alignment( views::BoxLayout::CrossAxisAlignment::kCenter); SetLayoutManager(std::move(layout)); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); layer()->SetRoundedCornerRadius( gfx::RoundedCornersF(kPinRequestViewRoundedCornerRadiusDp)); layer()->SetBackgroundBlur(ShelfConfig::Get()->shelf_blur_radius()); const int child_view_width = kPinRequestViewWidthDp - 2 * kPinRequestViewMainHorizontalInsetDp; // Header view which contains the back button that is aligned top right and // the lock icon which is in the bottom center. auto header_layout = std::make_unique<views::FillLayout>(); auto* header = new NonAccessibleView(); header->SetLayoutManager(std::move(header_layout)); AddChildView(header); auto* header_spacer = new NonAccessibleView(); header_spacer->SetPreferredSize(gfx::Size(0, kHeaderHeightDp)); header->AddChildView(header_spacer); // Back button. auto* back_button_view = new NonAccessibleView(); back_button_view->SetPreferredSize( gfx::Size(child_view_width + 2 * (kPinRequestViewMainHorizontalInsetDp - kPinRequestViewHorizontalInsetDp), kHeaderHeightDp)); auto back_button_layout = std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(), 0); back_button_layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kEnd); back_button_layout->set_cross_axis_alignment( views::BoxLayout::CrossAxisAlignment::kStart); back_button_view->SetLayoutManager(std::move(back_button_layout)); header->AddChildView(back_button_view); back_button_ = new LoginButton(this); back_button_->SetPreferredSize( gfx::Size(kBackButtonSizeDp, kBackButtonSizeDp)); back_button_->SetBackground( views::CreateSolidBackground(SK_ColorTRANSPARENT)); back_button_->SetImage( views::Button::STATE_NORMAL, gfx::CreateVectorIcon(views::kIcCloseIcon, kCrossSizeDp, SK_ColorWHITE)); back_button_->SetImageHorizontalAlignment(views::ImageButton::ALIGN_CENTER); back_button_->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); back_button_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_ASH_LOGIN_BACK_BUTTON_ACCESSIBLE_NAME)); back_button_->SetFocusBehavior(FocusBehavior::ALWAYS); back_button_view->AddChildView(back_button_); // Main view icon. auto* icon_view = new NonAccessibleView(); icon_view->SetPreferredSize(gfx::Size(0, kHeaderHeightDp)); auto icon_layout = std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(), 0); icon_layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kEnd); icon_layout->set_cross_axis_alignment( views::BoxLayout::CrossAxisAlignment::kCenter); icon_view->SetLayoutManager(std::move(icon_layout)); header->AddChildView(icon_view); views::ImageView* icon = new views::ImageView(); icon->SetPreferredSize(gfx::Size(kLockIconSizeDp, kLockIconSizeDp)); icon->SetImage(gfx::CreateVectorIcon(kPinRequestLockIcon, SK_ColorWHITE)); icon_view->AddChildView(icon); auto add_spacer = [&](int height) { auto* spacer = new NonAccessibleView(); spacer->SetPreferredSize(gfx::Size(0, height)); AddChildView(spacer); }; add_spacer(kIconToTitleDistanceDp); auto decorate_label = [](views::Label* label) { label->SetSubpixelRenderingEnabled(false); label->SetAutoColorReadabilityEnabled(false); label->SetEnabledColor(kTextColor); label->SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); }; // Main view title. title_label_ = new views::Label(default_title_, views::style::CONTEXT_LABEL, views::style::STYLE_PRIMARY); title_label_->SetMultiLine(true); title_label_->SetMaxLines(kTitleMaxLines); title_label_->SizeToFit(kTitleLineWidthDp); title_label_->SetLineHeight(kTitleLineHeightDp); title_label_->SetFontList(gfx::FontList().Derive( kTitleFontSizeDeltaDp, gfx::Font::NORMAL, gfx::Font::Weight::MEDIUM)); decorate_label(title_label_); AddChildView(title_label_); add_spacer(kTitleToDescriptionDistanceDp); // Main view description. description_label_ = new views::Label(default_description_, views::style::CONTEXT_LABEL, views::style::STYLE_PRIMARY); description_label_->SetMultiLine(true); description_label_->SetMaxLines(kDescriptionMaxLines); description_label_->SizeToFit(kDescriptionLineWidthDp); description_label_->SetLineHeight(kDescriptionTextLineHeightDp); description_label_->SetFontList( gfx::FontList().Derive(kDescriptionFontSizeDeltaDp, gfx::Font::NORMAL, gfx::Font::Weight::NORMAL)); decorate_label(description_label_); AddChildView(description_label_); add_spacer(kDescriptionToAccessCodeDistanceDp); // Access code input view. if (request.pin_length.has_value()) { CHECK_GT(request.pin_length.value(), 0); access_code_view_ = AddChildView(std::make_unique<FixedLengthCodeInput>( request.pin_length.value(), base::BindRepeating(&PinRequestView::OnInputChange, base::Unretained(this)), base::BindRepeating(&PinRequestView::SubmitCode, base::Unretained(this)), base::BindRepeating(&PinRequestView::OnBack, base::Unretained(this)), request.obscure_pin)); } else { access_code_view_ = AddChildView(std::make_unique<FlexCodeInput>( base::BindRepeating(&PinRequestView::OnInputChange, base::Unretained(this), false), base::BindRepeating(&PinRequestView::SubmitCode, base::Unretained(this)), base::BindRepeating(&PinRequestView::OnBack, base::Unretained(this)), request.obscure_pin)); } access_code_view_->SetFocusBehavior(FocusBehavior::ALWAYS); add_spacer(kAccessCodeToPinKeyboardDistanceDp); // Pin keyboard. Note that the keyboard's own submit button is disabled via // passing a null |on_submit| callback. pin_keyboard_view_ = new LoginPinView(LoginPinView::Style::kAlphanumeric, base::BindRepeating(&AccessCodeInput::InsertDigit, base::Unretained(access_code_view_)), base::BindRepeating(&AccessCodeInput::Backspace, base::Unretained(access_code_view_)), /*on_submit=*/LoginPinView::OnPinSubmit()); // Backspace key is always enabled and |access_code_| field handles it. pin_keyboard_view_->OnPasswordTextChanged(false); AddChildView(pin_keyboard_view_); add_spacer(kPinKeyboardToFooterDistanceDp); // Footer view contains help text button aligned to its start, submit // button aligned to its end and spacer view in between. auto* footer = new NonAccessibleView(); footer->SetPreferredSize(gfx::Size(child_view_width, kArrowButtonSizeDp)); auto* bottom_layout = footer->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(), 0)); AddChildView(footer); help_button_ = new FocusableLabelButton( this, l10n_util::GetStringUTF16(IDS_ASH_LOGIN_PIN_REQUEST_HELP)); help_button_->SetPaintToLayer(); help_button_->layer()->SetFillsBoundsOpaquely(false); help_button_->SetTextSubpixelRenderingEnabled(false); help_button_->SetTextColor(views::Button::STATE_NORMAL, kTextColor); help_button_->SetTextColor(views::Button::STATE_HOVERED, kTextColor); help_button_->SetTextColor(views::Button::STATE_PRESSED, kTextColor); help_button_->SetFocusBehavior(FocusBehavior::ALWAYS); help_button_->SetVisible(request.help_button_enabled); footer->AddChildView(help_button_); auto* horizontal_spacer = new NonAccessibleView(); footer->AddChildView(horizontal_spacer); bottom_layout->SetFlexForView(horizontal_spacer, 1); submit_button_ = new ArrowButtonView(this, kArrowButtonSizeDp); submit_button_->SetBackgroundColor(kArrowButtonColor); submit_button_->SetPreferredSize( gfx::Size(kArrowButtonSizeDp, kArrowButtonSizeDp)); submit_button_->SetEnabled(false); submit_button_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_ASH_LOGIN_SUBMIT_BUTTON_ACCESSIBLE_NAME)); submit_button_->SetFocusBehavior(FocusBehavior::ALWAYS); footer->AddChildView(submit_button_); add_spacer(kSubmitButtonBottomMarginDp); pin_keyboard_view_->SetVisible(PinKeyboardVisible()); tablet_mode_observer_.Add(Shell::Get()->tablet_mode_controller()); SetPreferredSize(GetPinRequestViewSize()); } PinRequestView::~PinRequestView() = default; void PinRequestView::OnPaint(gfx::Canvas* canvas) { views::View::OnPaint(canvas); cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFill_Style); flags.setColor(GetChildUserDialogColor(true)); canvas->DrawRoundRect(GetContentsBounds(), kPinRequestViewRoundedCornerRadiusDp, flags); } void PinRequestView::RequestFocus() { access_code_view_->RequestFocus(); } gfx::Size PinRequestView::CalculatePreferredSize() const { return GetPinRequestViewSize(); } ui::ModalType PinRequestView::GetModalType() const { // MODAL_TYPE_SYSTEM is used to get a semi-transparent background behind the // pin request view, when it is used directly on a widget. The overlay // consumes all the inputs from the user, so that they can only interact with // the pin request view while it is visible. return ui::MODAL_TYPE_SYSTEM; } views::View* PinRequestView::GetInitiallyFocusedView() { return access_code_view_; } base::string16 PinRequestView::GetAccessibleWindowTitle() const { return default_accessible_title_; } void PinRequestView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender == back_button_) { OnBack(); } else if (sender == help_button_) { delegate_->OnHelp(GetWidget()->GetNativeWindow()); } else if (sender == submit_button_) { SubmitCode(); } } void PinRequestView::OnTabletModeStarted() { if (!pin_keyboard_always_enabled_) { VLOG(1) << "Showing PIN keyboard in PinRequestView"; pin_keyboard_view_->SetVisible(true); // This will trigger ChildPreferredSizeChanged in parent view and Layout() // in view. As the result whole hierarchy will go through re-layout. UpdatePreferredSize(); } } void PinRequestView::OnTabletModeEnded() { if (!pin_keyboard_always_enabled_) { VLOG(1) << "Hiding PIN keyboard in PinRequestView"; DCHECK(pin_keyboard_view_); pin_keyboard_view_->SetVisible(false); // This will trigger ChildPreferredSizeChanged in parent view and Layout() // in view. As the result whole hierarchy will go through re-layout. UpdatePreferredSize(); } } void PinRequestView::OnTabletControllerDestroyed() { tablet_mode_observer_.RemoveAll(); } void PinRequestView::SubmitCode() { base::Optional<std::string> code = access_code_view_->GetCode(); DCHECK(code.has_value()); SubmissionResult result = delegate_->OnPinSubmitted(*code); switch (result) { case SubmissionResult::kPinAccepted: { std::move(on_pin_request_done_).Run(true /* success */); return; } case SubmissionResult::kPinError: { // Caller is expected to call UpdateState() to allow for customization of // error messages. return; } case SubmissionResult::kSubmitPending: { // Waiting on validation result - do nothing for now. return; } } } void PinRequestView::OnBack() { delegate_->OnBack(); if (PinRequestWidget::Get()) { PinRequestWidget::Get()->Close(false /* success */); } } void PinRequestView::UpdateState(PinRequestViewState state, const base::string16& title, const base::string16& description) { state_ = state; title_label_->SetText(title); description_label_->SetText(description); UpdatePreferredSize(); switch (state_) { case PinRequestViewState::kNormal: { access_code_view_->SetInputColor(kTextColor); title_label_->SetEnabledColor(kTextColor); return; } case PinRequestViewState::kError: { access_code_view_->SetInputColor(kErrorColor); title_label_->SetEnabledColor(kErrorColor); // Read out the error. title_label_->NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true); return; } } } void PinRequestView::ClearInput() { access_code_view_->ClearInput(); } void PinRequestView::SetInputEnabled(bool input_enabled) { access_code_view_->SetInputEnabled(input_enabled); } void PinRequestView::UpdatePreferredSize() { SetPreferredSize(CalculatePreferredSize()); if (GetWidget()) GetWidget()->CenterWindow(GetPreferredSize()); } void PinRequestView::FocusSubmitButton() { submit_button_->RequestFocus(); } void PinRequestView::OnInputChange(bool last_field_active, bool complete) { if (state_ == PinRequestViewState::kError) { UpdateState(PinRequestViewState::kNormal, default_title_, default_description_); } submit_button_->SetEnabled(complete); if (complete && last_field_active) { if (auto_submit_enabled_) { auto_submit_enabled_ = false; SubmitCode(); return; } // Moving focus is delayed by using PostTask to allow for proper // a11y announcements. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&PinRequestView::FocusSubmitButton, weak_ptr_factory_.GetWeakPtr())); } } void PinRequestView::GetAccessibleNodeData(ui::AXNodeData* node_data) { views::View::GetAccessibleNodeData(node_data); node_data->role = ax::mojom::Role::kDialog; node_data->SetName(default_accessible_title_); } // If |pin_keyboard_always_enabled_| is not set, pin keyboard is only shown in // tablet mode. bool PinRequestView::PinKeyboardVisible() const { return pin_keyboard_always_enabled_ || IsTabletMode(); } gfx::Size PinRequestView::GetPinRequestViewSize() const { int height = kPinRequestViewMinimumHeightDp + std::min(int{title_label_->GetRequiredLines()}, kTitleMaxLines) * kTitleLineHeightDp + std::min(int{description_label_->GetRequiredLines()}, kDescriptionMaxLines) * kDescriptionTextLineHeightDp; if (PinKeyboardVisible()) height += kPinKeyboardHeightDp; return gfx::Size(kPinRequestViewWidthDp, height); } } // namespace ash
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
16092d95a04d92472d52fa6346eacc9c34d223af
d643ff48cdd4661e2a924a02a8458819b9aa23ac
/chapter3/3.36/main.cpp
0ac0a0fb4ec6dfa88d0293fa7fa1eda119761e64
[]
no_license
grayondream/Primer-Learing
d9bc1116d0b562b3650b7df22ae64d640c54f0a5
a0f4acb47770c11d3c1eb34e70f4f770d0255957
refs/heads/master
2021-05-11T04:09:33.206964
2018-01-24T06:30:12
2018-01-24T06:30:12
117,933,818
0
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
/************************************************************************* > File Name: main.cpp > Author: > Mail: > Created Time: 2018年01月05日 星期五 23时40分57秒 ************************************************************************/ #include <iostream> using namespace std; bool com(int *a,size_t len1,int *b,size_t len2) { if(len1 != len2) return false; for(size_t i = 0;i < len1;i ++) { if(*(a + i) != *(b + i)) { return false; } } return true; } int main(int argc, char **argv) { cout<<"primer 3.36\n"; int a[4] = {12,13,4,5}; int b[4] = {12,13,4,5}; cout<<com(a,4,b,4); return 0; }
[ "GrayOnDream@outlook.com" ]
GrayOnDream@outlook.com
652f1876c863909db583af1688029ce2e768562b
88a47e88a59cfbe818168f8fb9d4cbb5bfcbb8b5
/src/piece.cpp
a52d538d83c6f2d6d3fd76699b4deabd9d8565c4
[]
no_license
fiedosiukr/reversi
7c0a0bf5f560ceb09e151055cd304f86d91e0faf
4719bb1cc6214339817ef09b2ea8dd4ac005b996
refs/heads/master
2020-05-27T10:53:27.811693
2019-05-27T16:02:32
2019-05-27T16:02:32
187,537,250
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include "../include/piece.hpp" #include <iostream> Piece::Piece(char representation) { this->representation = representation; } char Piece::get_representation() { return representation; } void Piece::render() { std::cout << representation; }
[ "fiedosiukr@gmail.com" ]
fiedosiukr@gmail.com
d09c9a9f8f710801c76fb4e0fd13fde3933b3aa4
bff39d66e3f49e7e560f9ec03f12b15a6f244ed8
/src/SoAppRunner/SoProgram.cpp
17af1cb05dee79eeb265b90c77bcec9c2e26f7c6
[]
no_license
sololxy/solo-apprunner
2efe8695a00a558e8f27544e9d8206be7d9a786f
e3c2316aef0b37361d889c6ecef85bbd6ad5eb7b
refs/heads/master
2021-01-01T04:28:50.663908
2017-07-21T05:15:44
2017-07-21T05:15:44
97,184,768
0
1
null
2017-07-21T05:15:45
2017-07-14T02:34:12
C++
UTF-8
C++
false
false
559
cpp
#include <SoAppRunner/SoProgram.h> SoProgram::SoProgram() { _name = "Unknown Program"; _path = "/none/test.exe"; _web = "https://github.com/sololxy"; } SoProgram::SoProgram(QString name) { _name = name; _path = "/none/test.exe"; _web = "https://github.com/sololxy"; }; SoProgram::SoProgram(QString name, QString path, QString desc, QString detailDesc, QString icon, QString doc, QString web) { _name = name; _path = path; _desc = desc; _detailDesc = detailDesc; _icon = icon; _doc = doc; _web = web; } SoProgram::~SoProgram() { }
[ "solo_lxy@126.com" ]
solo_lxy@126.com
3b955d196234bd062c3085bcd2e0b1ef5d365189
a7a0d98dba2bc19a0bdc7a28cd732cd105e3b02f
/BAEKJOON/1085.cpp
06e6b4252c3136eb8c2cd3639116d97915e8af40
[]
no_license
stalker5217/algorithm
905317b9b24f26bfac2f50a250698d057e21be62
b635b13512c0057b81d714f14857fc3a9cd84582
refs/heads/master
2021-06-26T19:47:10.980335
2020-11-18T14:54:35
2020-11-18T14:54:35
190,971,508
2
0
null
null
null
null
UTF-8
C++
false
false
470
cpp
#define DEBUG 0 #define LOG(string) cout << string #include <iostream> #include <cstring> #include <vector> #include <algorithm> #include <functional> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int w, h, x, y; cin >> x >> y >> w >> h; int minWidth = ((w-x) > x) ? x : (w-x); int minHeight = ((h-y) > y) ? y : (h-y); int min = (minWidth > minHeight) ? minHeight : minWidth; cout << min; return 0; }
[ "stalker5217@gmail.com" ]
stalker5217@gmail.com
45d8f77f01e12ce0f5b35cac2858994492a6b56f
e6d4a87dcf98e93bab92faa03f1b16253b728ac9
/algorithms/cpp/maximum69Number/maximum69Number.cpp
980ace4b93fa6960456ded11061ef3f86c3bfd94
[]
no_license
MichelleZ/leetcode
b5a58e1822e3f6ef8021b29d9bc9aca3fd3d416f
a390adeeb71e997b3c1a56c479825d4adda07ef9
refs/heads/main
2023-03-06T08:16:54.891699
2023-02-26T07:17:47
2023-02-26T07:17:47
326,904,500
3
0
null
null
null
null
UTF-8
C++
false
false
387
cpp
// Source: https://leetcode.com/problems/maximum-69-number/ // Author: Miao Zhang // Date: 2021-04-23 class Solution { public: int maximum69Number (int num) { string s = to_string(num); for (int i = 0; i < s.length(); i++) { if (s[i] == '6') { s[i] = '9'; break; } } return stoi(s); } };
[ "zhangdaxiaomiao@163.com" ]
zhangdaxiaomiao@163.com
280bd1f107b71a0cf4e5d2ecc60163d0d6471d7e
5d69e513e1518739c5d5cdd569999ec0c19ef803
/src/mac/pxWindowNative.cpp
7c40b5f55fdf9c1d92844c00f4e75755cd539334
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive" ]
permissive
rrao002c/pxCore
5541827abe3256bbf9fc8e4c25b300f6e20b27b1
b9b35600c291e3a39a16e0959060ff1511631f70
refs/heads/master
2021-01-17T11:03:28.457364
2016-04-22T16:47:22
2016-04-22T16:47:22
59,513,283
0
0
null
2016-05-23T19:42:56
2016-05-23T19:42:56
null
UTF-8
C++
false
false
15,363
cpp
// pxCore CopyRight 2007 John Robinson // Portable Framebuffer and Windowing Library // pwWindowNative.cpp #include "pxWindow.h" #include "pxWindowNative.h" // pxWindow pxError pxWindow::init(int left, int top, int width, int height) { Rect r; r.top = top; r.left = left; r.bottom = top+height; r.right = left+width; CreateNewWindow(kDocumentWindowClass, kWindowCloseBoxAttribute | kWindowResizableAttribute | kWindowLiveResizeAttribute | kWindowResizeTransitionAction | kWindowCollapseBoxAttribute | kWindowStandardHandlerAttribute, &r, &mWindowRef); if (mWindowRef) { EventTypeSpec eventType; EventHandlerUPP handlerUPP; EventHandlerRef handler; eventType.eventClass = kEventClassKeyboard; eventType.eventKind = kEventRawKeyDown; handlerUPP = NewEventHandlerUPP(doKeyDown); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventRawKeyUp; handlerUPP = NewEventHandlerUPP(doKeyUp); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventRawKeyRepeat; handlerUPP = NewEventHandlerUPP(doKeyDown); // 'key repeat' is translated to 'key down' InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventRawKeyModifiersChanged; handlerUPP = NewEventHandlerUPP(doKeyModifierChanged); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventWindowDrawContent; eventType.eventClass = kEventClassWindow; handlerUPP = NewEventHandlerUPP(doWindowDrawContent); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventWindowBoundsChanging; eventType.eventClass = kEventClassWindow; handlerUPP = NewEventHandlerUPP(doWindowResizeComplete); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventWindowResizeCompleted; //kEventWindowBoundsChanged; eventType.eventClass = kEventClassWindow; handlerUPP = NewEventHandlerUPP(doWindowResizeComplete); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventWindowClose; handlerUPP = NewEventHandlerUPP(doWindowCloseRequest); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventWindowClosed; eventType.eventClass = kEventClassWindow; handlerUPP = NewEventHandlerUPP(doWindowClosed); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventMouseDown; eventType.eventClass = kEventClassMouse; handlerUPP = NewEventHandlerUPP(doMouseDown); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventMouseUp; eventType.eventClass = kEventClassMouse; handlerUPP = NewEventHandlerUPP(doMouseUp); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventMouseMoved; eventType.eventClass = kEventClassMouse; handlerUPP = NewEventHandlerUPP(doMouseMove); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventMouseExited; eventType.eventClass = kEventClassMouse; handlerUPP = NewEventHandlerUPP(doMouseLeave); InstallWindowEventHandler (mWindowRef, handlerUPP, 1, &eventType, this, &handler); eventType.eventKind = kEventMouseDragged; eventType.eventClass = kEventClassMouse; handlerUPP = NewEventHandlerUPP(doMouseMove); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); { Rect r; GetWindowBounds(mWindowRef,kWindowContentRgn ,&r); onSize(r.right-r.left, r.bottom-r.top); } createMouseTrackingRegion(); onCreate(); } return mWindowRef?PX_OK:PX_FAIL; } pxError pxWindow::term() { if (mWindowRef) { DisposeWindow(mWindowRef); mWindowRef = NULL; } return PX_OK; } void pxWindow::invalidateRect(pxRect* pxr) { Rect r; if (!pxr) { GetWindowBounds(mWindowRef,kWindowContentRgn ,&r); r.right -= r.left; r.bottom -= r.top; r.left = 0; r.top = 0; } else { r.left = pxr->left(); r.right = pxr->right(); r.top = pxr->top(); r.bottom = pxr->bottom(); } InvalWindowRect(mWindowRef,&r); } bool pxWindow::visibility() { return IsWindowVisible(mWindowRef); } void pxWindow::setVisibility(bool visible) { if (visible) ShowWindow(mWindowRef); else HideWindow(mWindowRef); } pxError pxWindow::setAnimationFPS(long fps) { if (theTimer) { RemoveEventLoopTimer(theTimer); } if (fps > 0) { EventLoopRef mainLoop; EventLoopTimerUPP timerUPP; mainLoop = GetMainEventLoop(); timerUPP = NewEventLoopTimerUPP (doPeriodicTask); InstallEventLoopTimer (mainLoop, 0, (1000/fps) * kEventDurationMillisecond, timerUPP, this, &theTimer); } return PX_OK; } void pxWindow::setTitle(char* title) { SetWindowTitleWithCFString(mWindowRef,CFStringCreateWithCString(nil,title,kCFStringEncodingASCII)); } pxError pxWindow::beginNativeDrawing(pxSurfaceNative& s) { s = GetWindowPort(this->mWindowRef); return PX_OK; } pxError pxWindow::endNativeDrawing(pxSurfaceNative& s) { // Don't need to do anything return PX_OK; } // pxWindowNative void pxWindowNative::createMouseTrackingRegion() { if (mTrackingRegion) { ReleaseMouseTrackingRegion(mTrackingRegion); mTrackingRegion = NULL; } { RgnHandle windowRgn = NewRgn(); //RgnHandle sizeBoxRgn = NewRgn(); GetWindowRegion(mWindowRef, kWindowContentRgn, windowRgn); //GetWindowRegion(mWindowRef, kWindowGrowRgn, sizeBoxRgn); //UnionRgn(windowRgn, sizeBoxRgn, windowRgn); //DisposeRgn(sizeBoxRgn); MouseTrackingRegionID mTrackingRegionId; mTrackingRegionId.signature = 'blah'; mTrackingRegionId.id = 1; CreateMouseTrackingRegion (mWindowRef, windowRgn, NULL, kMouseTrackingOptionsGlobalClip, mTrackingRegionId, NULL, NULL, &mTrackingRegion); DisposeRgn(windowRgn); } } pascal OSStatus pxWindowNative::doKeyDown (EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { char key_code; UInt32 modifier; GetEventParameter (theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(char), NULL, &key_code); GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifier); UInt32 kc; GetEventParameter (theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(UInt32), NULL, &kc); if (kc == 0x24) kc = 0x4c; pxWindowNative* w = (pxWindowNative*)userData; unsigned long flags = 0; if (modifier & shiftKey) flags |= PX_MOD_SHIFT; if (modifier & optionKey) flags |= PX_MOD_ALT; if (modifier & controlKey) flags |= PX_MOD_CONTROL; w->onKeyDown(kc, flags); return CallNextEventHandler (nextHandler, theEvent); } //------------------------------------------------------------------------ pascal OSStatus pxWindowNative::doKeyUp (EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { char key_code; char char_code; UInt32 modifier; GetEventParameter (theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(char), NULL, &key_code); GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifier); UInt32 kc; GetEventParameter (theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(UInt32), NULL, &kc); // printf("VK UP: %lx\n", kc); pxWindowNative* w = (pxWindowNative*)userData; if (kc == 0x24) kc = 0x4c; unsigned long flags = 0; if (modifier & shiftKey) flags |= PX_MOD_SHIFT; if (modifier & optionKey) flags |= PX_MOD_ALT; if (modifier & controlKey) flags |= PX_MOD_CONTROL; w->onKeyUp(kc, flags); return CallNextEventHandler (nextHandler, theEvent); } pascal OSStatus pxWindowNative::doKeyModifierChanged (EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { UInt32 modifier; GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifier); pxWindowNative* w = (pxWindowNative*)userData; if (!(w->mLastModifierState & shiftKey) && (modifier & shiftKey)) w->onKeyDown(PX_KEY_SHIFT, 0); else if ((w->mLastModifierState & shiftKey) && !(modifier & shiftKey)) w->onKeyUp(PX_KEY_SHIFT, 0); if (!(w->mLastModifierState & optionKey) && (modifier & optionKey)) w->onKeyDown(PX_KEY_ALT, 0); else if ((w->mLastModifierState & optionKey) && !(modifier & optionKey)) w->onKeyUp(PX_KEY_ALT, 0); if (!(w->mLastModifierState & controlKey) && (modifier & controlKey)) w->onKeyDown(PX_KEY_CONTROL, 0); else if ((w->mLastModifierState & controlKey) && !(modifier & controlKey)) w->onKeyUp(PX_KEY_CONTROL, 0); if (!(w->mLastModifierState & alphaLock) && (modifier & alphaLock)) w->onKeyDown(PX_KEY_CAPSLOCK, 0); else if ((w->mLastModifierState & alphaLock) && !(modifier & alphaLock)) w->onKeyUp(PX_KEY_CAPSLOCK, 0); w->mLastModifierState = modifier; return CallNextEventHandler (nextHandler, theEvent); } pascal OSStatus pxWindowNative::doWindowDrawContent (EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; //SetPort(GetWindowPort(w->mWindowRef)); //w->onDraw(GetPortPixMap(GetWindowPort(w->mWindowRef))); w->onDraw(GetWindowPort(w->mWindowRef)); return CallNextEventHandler (nextHandler, theEvent); } pascal OSStatus pxWindowNative::doWindowResizeComplete(EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; Rect rect; GetEventParameter(theEvent, kEventParamCurrentBounds, typeQDRectangle, NULL, sizeof(Rect), NULL, &rect); w->onSize(rect.right-rect.left, rect.bottom-rect.top); Rect r; GetWindowBounds(w->mWindowRef,kWindowContentRgn ,&r); r.right -= r.left; r.bottom -= r.top; r.left = r.top = 0; InvalWindowRect(w->mWindowRef,&r); OSStatus s = CallNextEventHandler (nextHandler, theEvent); w->createMouseTrackingRegion(); return s; } pascal OSStatus pxWindowNative::doWindowCloseRequest(EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; printf("here\n"); w->onCloseRequest(); return noErr; // Don't use default handler } pascal void pxWindowNative::doPeriodicTask (EventLoopTimerRef theTimer, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; w->onAnimationTimer(); } pascal OSStatus pxWindowNative::doWindowClosed(EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; w->onClose(); return CallNextEventHandler (nextHandler, theEvent); } pascal OSStatus pxWindowNative::doMouseDown(EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; Point loc; UInt16 button; UInt32 modifier; GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, NULL, sizeof(Point), NULL, &loc); SetPort(GetWindowPort(w->mWindowRef)); RgnHandle r = NewRgn(); GetWindowRegion(w->mWindowRef, kWindowContentRgn, r); bool inContent = PtInRgn(loc, r); DisposeRgn(r); GlobalToLocal (&loc); GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(button), NULL, &button); GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifier); unsigned long flags = 0; if (button == kEventMouseButtonPrimary) flags |= PX_LEFTBUTTON; else if (button == kEventMouseButtonSecondary) flags |= PX_RIGHTBUTTON; else if (button == kEventMouseButtonTertiary) flags |= PX_MIDDLEBUTTON; if (modifier & shiftKey) flags |= PX_MOD_SHIFT; if (modifier & optionKey) flags |= PX_MOD_ALT; if (modifier & controlKey) flags |= PX_MOD_CONTROL; if (inContent) { if (w->mTrackingRegion) SetMouseTrackingRegionEnabled(w->mTrackingRegion, false); w->mDragging = true; w->onMouseDown(loc.h, loc.v, flags); } return CallNextEventHandler (nextHandler, theEvent); } pascal OSStatus pxWindowNative::doMouseUp(EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; Point loc; UInt16 button; UInt32 modifier; GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, NULL, sizeof(Point), NULL, &loc); SetPort(GetWindowPort(w->mWindowRef)); RgnHandle r = NewRgn(); GetWindowRegion(w->mWindowRef, kWindowContentRgn, r); bool inContent = PtInRgn(loc, r); DisposeRgn(r); GlobalToLocal(&loc); GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(button), NULL, &button); GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifier); unsigned long flags = 0; if (button == kEventMouseButtonPrimary) flags |= PX_LEFTBUTTON; else if (button == kEventMouseButtonSecondary) flags |= PX_RIGHTBUTTON; else if (button == kEventMouseButtonTertiary) flags |= PX_MIDDLEBUTTON; if (modifier & shiftKey) flags |= PX_MOD_SHIFT; if (modifier & optionKey) flags |= PX_MOD_ALT; if (modifier & controlKey) flags |= PX_MOD_CONTROL; if (w->mTrackingRegion) SetMouseTrackingRegionEnabled(w->mTrackingRegion, true); w->mDragging = false; w->onMouseUp(loc.h, loc.v, flags); // Simulate onMouseLeave event if (!inContent) w->onMouseLeave(); return CallNextEventHandler (nextHandler, theEvent); } pascal OSStatus pxWindowNative::doMouseMove(EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; Point loc; GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, NULL, sizeof(Point), NULL, &loc); SetPort(GetWindowPort(w->mWindowRef)); RgnHandle r = NewRgn(); GetWindowRegion(w->mWindowRef, kWindowContentRgn, r); bool inContent = PtInRgn(loc, r); DisposeRgn(r); if (w->mDragging || inContent) { // Shouldn't need to do this here. But the Window region obtained from // GetWindowRegion doesn't appear to be updated immediately after a resize event // forcing us to update on every mousemove event w->createMouseTrackingRegion(); GlobalToLocal (&loc); printf("onMouseMove %d %d, %d\n", loc.h, loc.v, w->mDragging); w->onMouseMove(loc.h, loc.v); } return CallNextEventHandler (nextHandler, theEvent); } pascal OSStatus pxWindowNative::doMouseLeave(EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) { pxWindowNative* w = (pxWindowNative*)userData; #if 0 Point loc; GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, NULL, sizeof(Point), NULL, &loc); SetPort(GetWindowPort(w->mWindowRef)); GlobalToLocal (&loc); #endif printf("onMouseLeave\n"); w->onMouseLeave(); return CallNextEventHandler (nextHandler, theEvent); }
[ "johnrobinson@ubuntu.(none)" ]
johnrobinson@ubuntu.(none)
b5f16d6587cb0ac10a4e89ec4e28c8e75a09d736
e1eeac6e69b4b85b7c22f374fd068f9370476803
/instruction/gt.h
83a0179006ce09332e96c537483be5c128ed9e56
[]
no_license
trigrass2/PLCSim
fb32d58bf61fc0c2228464a9ec651bf624683cdf
c468c45363a396afaf7d1a77440ded6f82e1af86
refs/heads/master
2022-02-25T11:33:06.730980
2019-11-05T08:22:45
2019-11-05T08:22:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
419
h
#ifndef PLC_EMULATOR_INSTRUCTION_GT_H_ #define PLC_EMULATOR_INSTRUCTION_GT_H_ #include "instruction.h" namespace plc_emulator { class GT : public Instruction { public: GT(ResourceImpl *associated_resource, bool is_negated) { SetResource(associated_resource); SetNegation(is_negated); SetName("GT"); }; void Execute(Variable *curr_result, std::vector<Variable *> &ops); }; } #endif
[ "wisedier@gmail.com" ]
wisedier@gmail.com
4c7ae582c068af8cf298fad944644b1f101e0688
8f729ce5b7f0bb45f323b2625890dbb87d121c9d
/Segment.h
3c2fc8a4a0f8a55bbf52b598f445e385e775ecbc
[]
no_license
aitzaz960/Centipede-Game
a27765dbd5da0f0ea9044412d8df3fbea20fe5ba
10c2add82a6672b5bf55864dc9bdcf964ca06477
refs/heads/master
2023-01-08T22:20:36.424692
2020-11-13T04:13:13
2020-11-13T04:13:13
312,563,833
0
0
null
null
null
null
UTF-8
C++
false
false
288
h
#ifndef SEGMENT_H #define SEGMENT_H class Segment { private: protected: public: virtual void setCX(int i); virtual void setCY(int i); virtual int getCX() const; virtual int getCY() const; virtual bool isMagic() const; }; #endif
[ "i180589@nu.edu.pk" ]
i180589@nu.edu.pk
4625688f8632dfcaff7791dc462c85f8b2144473
5742e5df1240da9be4955d42e4f402ca9f51cf0f
/ros2-osx/include/map_msgs/msg/detail/point_cloud2_update__traits.hpp
d3e4a73bc47aa5a6e8955d825eb228c82e20bcc9
[]
no_license
unmelted/ros_prj
b15b9961c313eff210636e7f65d40292f7252e9c
ec5e926147d7d9ac0606ea847cc4f5c4fb8fceed
refs/heads/master
2023-02-13T08:44:25.007130
2021-01-18T21:21:35
2021-01-18T21:21:35
330,076,208
0
0
null
null
null
null
UTF-8
C++
false
false
1,539
hpp
// generated from rosidl_generator_cpp/resource/idl__traits.hpp.em // with input from map_msgs:msg/PointCloud2Update.idl // generated code does not contain a copyright notice #ifndef MAP_MSGS__MSG__DETAIL__POINT_CLOUD2_UPDATE__TRAITS_HPP_ #define MAP_MSGS__MSG__DETAIL__POINT_CLOUD2_UPDATE__TRAITS_HPP_ #include "map_msgs/msg/detail/point_cloud2_update__struct.hpp" #include <rosidl_runtime_cpp/traits.hpp> #include <stdint.h> #include <type_traits> // Include directives for member types // Member 'header' #include "std_msgs/msg/detail/header__traits.hpp" // Member 'points' #include "sensor_msgs/msg/detail/point_cloud2__traits.hpp" namespace rosidl_generator_traits { template<> inline const char * data_type<map_msgs::msg::PointCloud2Update>() { return "map_msgs::msg::PointCloud2Update"; } template<> inline const char * name<map_msgs::msg::PointCloud2Update>() { return "map_msgs/msg/PointCloud2Update"; } template<> struct has_fixed_size<map_msgs::msg::PointCloud2Update> : std::integral_constant<bool, has_fixed_size<sensor_msgs::msg::PointCloud2>::value && has_fixed_size<std_msgs::msg::Header>::value> {}; template<> struct has_bounded_size<map_msgs::msg::PointCloud2Update> : std::integral_constant<bool, has_bounded_size<sensor_msgs::msg::PointCloud2>::value && has_bounded_size<std_msgs::msg::Header>::value> {}; template<> struct is_message<map_msgs::msg::PointCloud2Update> : std::true_type {}; } // namespace rosidl_generator_traits #endif // MAP_MSGS__MSG__DETAIL__POINT_CLOUD2_UPDATE__TRAITS_HPP_
[ "unmelted@naver.com" ]
unmelted@naver.com
91783e2e6126992b98bbe3ac2382e05b5323db92
fc08ff32c2a5bf83d92eb815aeb3f70ac527163a
/include/ShadowFrameBuffer.h
b3cd67ba73ef6c89ea09762a04fdc34c641ccb3d
[]
no_license
flyhex/SandboxOGL
a587dbb8b062ff97be05fbbf675aacdc951161ab
7edc8694e8af7710893266405cd9f77ddee71459
refs/heads/master
2021-06-22T00:38:02.702210
2017-08-01T05:09:06
2017-08-01T05:09:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
412
h
#pragma once namespace OGL { class TextureManager; class SMFrameBuffer { public: SMFrameBuffer(); SMFrameBuffer(TextureManager& tm, u32 size); ~SMFrameBuffer(); void Load(TextureManager& tm); void startFrame(); void bindForShadowPass(); u32 getFBO() const; u32 getSize() const; void setShadowMap(TextureManager& tm, u32 shadowMap); u32 m_size; u32 m_fbo; u32 m_shadowMap; }; }
[ "naitsidous.mehdi@gmail.com" ]
naitsidous.mehdi@gmail.com
724302528c12a784deedc6b4befa9d073fe09795
fc515a72800f3fc7b3de998cb944eab91e0baf7b
/Other Works/SAMS2/howmuch.cpp
0ec9fbaaa070ec4debb93eb1dfad4d6640c58818
[]
no_license
jbji/2019-Programming-Basics-C-
4211e0c25dd1fc88de71716ad6a37d41cd7b8b04
014d3d8a5f1d6a95c132699e98ef4bfb25ef845f
refs/heads/master
2022-12-30T08:12:09.214502
2020-10-13T14:17:57
2020-10-13T14:17:57
303,658,050
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
#include <howmuch.h> int howMuch(string filename){ ifstream filein(filename, ios::app | ios::binary); //打开文件 if (!filein) //读取失败 { filein.close(); return 0; } string getName, getId, getScore; int i = 0; while (getline(filein, getName, DEliM) && getline(filein, getId, DEliM) && getline(filein, getScore, DEliM)) { i++; //统计学生数目 } filein.close(); return i; }
[ "jbji@foxmail.com" ]
jbji@foxmail.com
4ba4312ac9de18e7bd010b3f1aff9e11bb2145f0
553e8a8c36d52580b85e572bf1ba071e304932e9
/casablanca/Release/src/pplx/threadpool.cpp
febe7bb81a63cc505cdb63fe328067cf47acbcbe
[ "Apache-2.0" ]
permissive
mentionllc/traintracks-cpp-sdk
ba0d62bc5289d4d82d0c17b282788d65e1863cec
c294a463ef2d55bc7b27e35fe7f903d51104c6bd
refs/heads/master
2020-04-19T06:40:23.949106
2015-02-05T04:45:24
2015-02-05T04:45:24
28,652,489
0
0
null
null
null
null
UTF-8
C++
false
false
1,948
cpp
/*** * ==++== * * Copyright (c) Microsoft Corporation. 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. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ==--== * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ **/ #include "stdafx.h" #if defined(__ANDROID__) #include <android/log.h> #include <jni.h> #endif namespace crossplat { #if (defined(ANDROID) || defined(__ANDROID__)) // This pointer will be 0-initialized by default (at load time). std::atomic<JavaVM*> JVM; static void abort_if_no_jvm() { if (JVM == nullptr) { __android_log_print(ANDROID_LOG_ERROR, "CPPRESTSDK", "%s", "The CppREST SDK must be initialized before first use on android: https://casablanca.codeplex.com/wikipage?title=Use%20on%20Android"); std::abort(); } } JNIEnv* get_jvm_env() { abort_if_no_jvm(); JNIEnv* env = nullptr; auto result = JVM.load()->AttachCurrentThread(&env, nullptr); if (result != JNI_OK) { throw std::runtime_error("Could not attach to JVM"); } return env; } threadpool& threadpool::shared_instance() { abort_if_no_jvm(); static threadpool s_shared(40); return s_shared; } #else // initialize the static shared threadpool threadpool threadpool::s_shared(40); #endif } #if defined(__ANDROID__) void cpprest_init(JavaVM* vm) { crossplat::JVM = vm; } #endif
[ "heisenberg@traintracks.io" ]
heisenberg@traintracks.io
565e606f3bd0668bfa08acf64d6731e1533db79e
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE126_Buffer_Overread/s02/CWE126_Buffer_Overread__new_wchar_t_memcpy_14.cpp
1d253c5e6dc660f9961eca679e42efba6bc33d81
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
4,004
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE126_Buffer_Overread__new_wchar_t_memcpy_14.cpp Label Definition File: CWE126_Buffer_Overread__new.label.xml Template File: sources-sink-14.tmpl.cpp */ /* * @description * CWE: 126 Buffer Over-read * BadSource: Use a small buffer * GoodSource: Use a large buffer * Sink: memcpy * BadSink : Copy data to string using memcpy * Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5) * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE126_Buffer_Overread__new_wchar_t_memcpy_14 { #ifndef OMITBAD void bad() { wchar_t * data; data = NULL; if(globalFive==5) { /* FLAW: Use a small buffer */ data = new wchar_t[50]; wmemset(data, L'A', 50-1); /* fill with 'A's */ data[50-1] = L'\0'; /* null terminate */ } { wchar_t dest[100]; wmemset(dest, L'C', 100-1); dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, wcslen(dest)*sizeof(wchar_t)); dest[100-1] = L'\0'; printWLine(dest); delete [] data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the globalFive==5 to globalFive!=5 */ static void goodG2B1() { wchar_t * data; data = NULL; if(globalFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a large buffer */ data = new wchar_t[100]; wmemset(data, L'A', 100-1); /* fill with 'A's */ data[100-1] = L'\0'; /* null terminate */ } { wchar_t dest[100]; wmemset(dest, L'C', 100-1); dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, wcslen(dest)*sizeof(wchar_t)); dest[100-1] = L'\0'; printWLine(dest); delete [] data; } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { wchar_t * data; data = NULL; if(globalFive==5) { /* FIX: Use a large buffer */ data = new wchar_t[100]; wmemset(data, L'A', 100-1); /* fill with 'A's */ data[100-1] = L'\0'; /* null terminate */ } { wchar_t dest[100]; wmemset(dest, L'C', 100-1); dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, wcslen(dest)*sizeof(wchar_t)); dest[100-1] = L'\0'; printWLine(dest); delete [] data; } } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE126_Buffer_Overread__new_wchar_t_memcpy_14; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
bd0720dbb643ccaf821cde092a07279aa40eae01
40b0530ef3eb345c49fc0d2face8bed9088a58c5
/v1.3/lib/hall-stm32/hall.h
c135d1373b0789eb54816716167d65285b37ad1d
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
Enjection/monty
1262974ab1c74b82fc0ce4cef7906b36eea77bdb
e7f2ecaf1b7f2ed0ce24f5aaa4c14e801d18dfde
refs/heads/main
2023-07-18T16:17:08.465840
2021-08-25T09:30:01
2021-08-25T09:30:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,643
h
#include "boss.h" namespace hall { using namespace boss; enum struct STM { F1, F3, F4, F7, G0, G4, H7, L0, L4 }; #if STM32F1 constexpr auto FAMILY = STM::F1; #elif STM32F3 constexpr auto FAMILY = STM::F3; #elif STM32F4 constexpr auto FAMILY = STM::F4; #elif STM32F7 constexpr auto FAMILY = STM::F7; #elif STM32G0 constexpr auto FAMILY = STM::G0; #elif STM32G4 constexpr auto FAMILY = STM::G4; #elif STM32L0 constexpr auto FAMILY = STM::L0; #elif STM32L4 constexpr auto FAMILY = STM::L4; #endif auto fastClock (bool pll =true) -> uint32_t; auto slowClock (bool low =true) -> uint32_t; auto systemHz () -> uint32_t; void idle (); [[noreturn]] void systemReset (); template <typename TYPE, uint32_t ADDR> struct IoBase { constexpr static auto addr = ADDR; auto& operator() (int off) const { return *(volatile TYPE*) (ADDR+off); } }; template <uint32_t ADDR> using Io8 = IoBase<uint8_t,ADDR>; template <uint32_t ADDR> using Io16 = IoBase<uint16_t,ADDR>; template <uint32_t ADDR> struct Io32 : IoBase<uint32_t,ADDR> { using IoBase<uint32_t,ADDR>::operator(); auto operator() (int off, int bit, uint8_t num =1) const { struct IOMask { int o; uint8_t b, w; operator uint32_t () const { auto& a = *(volatile uint32_t*) (ADDR+o); auto m = (1<<w)-1; return (a >> b) & m; } auto operator= (uint32_t v) const { auto& a = *(volatile uint32_t*) (ADDR+o); auto m = (1<<w)-1; a = (a & ~(m<<b)) | ((v & m)<<b); return v & m; } }; return IOMask {off + (bit >> 5), (uint8_t) (bit & 0x1F), num}; } }; template <uint32_t ADDR> struct Io32b : Io32<ADDR> { using Io32<ADDR>::operator(); auto& operator() (int off, int bit) const { uint32_t a = ADDR + off + (bit>>5); return *(volatile uint32_t*) ((a & 0xF000'0000) + 0x0200'0000 + (a<<5) + ((bit&0x1F)<<2)); } }; constexpr Io32<0> anyIo32; namespace dev { //CG< devs constexpr Io32 <0x50040000> ADC1; constexpr Io32 <0x50040100> ADC2; constexpr Io32 <0x50040300> ADC_Common; constexpr Io32 <0x50060000> AES; constexpr Io32b <0x40006400> CAN1; constexpr Io32b <0x40010200> COMP; constexpr Io32b <0x40023000> CRC; constexpr Io32b <0x40006000> CRS; constexpr Io32b <0x40007400> DAC1; constexpr Io32 <0xE0042000> DBGMCU; constexpr Io32b <0x40016000> DFSDM; constexpr Io32b <0x40020000> DMA1; constexpr Io32b <0x40020400> DMA2; constexpr Io32b <0x40010400> EXTI; constexpr Io32b <0x40011C00> FIREWALL; constexpr Io32b <0x40022000> FLASH; constexpr Io32 <0xE000EF34> FPU; constexpr Io32 <0xE000ED88> FPU_CPACR; constexpr Io32b <0x48000000> GPIOA; constexpr Io32b <0x48000400> GPIOB; constexpr Io32b <0x48000800> GPIOC; constexpr Io32b <0x48000C00> GPIOD; constexpr Io32b <0x48001000> GPIOE; constexpr Io32b <0x48001C00> GPIOH; constexpr Io32b <0x40005400> I2C1; constexpr Io32b <0x40005800> I2C2; constexpr Io32b <0x40005C00> I2C3; constexpr Io32b <0x40008400> I2C4; constexpr Io32b <0x40003000> IWDG; constexpr Io32b <0x40002400> LCD; constexpr Io32b <0x40007C00> LPTIM1; constexpr Io32b <0x40009400> LPTIM2; constexpr Io32b <0x40008000> LPUART1; constexpr Io32 <0xE000ED90> MPU; constexpr Io32 <0xE000E100> NVIC; constexpr Io32 <0xE000EF00> NVIC_STIR; constexpr Io32b <0x40007800> OPAMP; constexpr Io32b <0x40007000> PWR; constexpr Io32 <0xA0001000> QUADSPI; constexpr Io32b <0x40021000> RCC; constexpr Io32 <0x50060800> RNG; constexpr Io32b <0x40002800> RTC; constexpr Io32b <0x40015400> SAI1; constexpr Io32 <0xE000ED00> SCB; constexpr Io32 <0xE000E008> SCB_ACTRL; constexpr Io32b <0x40012800> SDMMC; constexpr Io32b <0x40013000> SPI1; constexpr Io32b <0x40003800> SPI2; constexpr Io32b <0x40003C00> SPI3; constexpr Io32 <0xE000E010> STK; constexpr Io32b <0x40008800> SWPMI1; constexpr Io32b <0x40010000> SYSCFG; constexpr Io32b <0x40012C00> TIM1; constexpr Io32b <0x40014000> TIM15; constexpr Io32b <0x40014400> TIM16; constexpr Io32b <0x40000000> TIM2; constexpr Io32b <0x40000400> TIM3; constexpr Io32b <0x40001000> TIM6; constexpr Io32b <0x40001400> TIM7; constexpr Io32b <0x40024000> TSC; constexpr Io32b <0x40004C00> UART4; constexpr Io32b <0x40013800> USART1; constexpr Io32b <0x40004400> USART2; constexpr Io32b <0x40004800> USART3; constexpr Io32b <0x40006800> USB; constexpr Io32b <0x40010030> VREFBUF; constexpr Io32b <0x40002C00> WWDG; //CG> } namespace irq { //CG1 irqs-n constexpr auto limit = 85; enum : uint8_t { //CG< irqs-e ADC1_2 = 18, AES = 79, CAN1_RX0 = 20, CAN1_RX1 = 21, CAN1_SCE = 22, CAN1_TX = 19, COMP = 64, CRS = 82, DFSDM1 = 61, DFSDM1_FLT2 = 63, DFSDM1_FLT3 = 42, DFSDM2 = 62, DMA1_CH1 = 11, DMA1_CH2 = 12, DMA1_CH3 = 13, DMA1_CH4 = 14, DMA1_CH5 = 15, DMA1_CH6 = 16, DMA1_CH7 = 17, DMA2_CH1 = 56, DMA2_CH2 = 57, DMA2_CH3 = 58, DMA2_CH4 = 59, DMA2_CH5 = 60, DMA2_CH6 = 68, DMA2_CH7 = 69, EXTI0 = 6, EXTI1 = 7, EXTI15_10 = 40, EXTI2 = 8, EXTI3 = 9, EXTI4 = 10, EXTI9_5 = 23, FLASH = 4, FPU = 81, I2C1_ER = 32, I2C1_EV = 31, I2C2_ER = 34, I2C2_EV = 33, I2C3_ER = 73, I2C3_EV = 72, I2C4_ER = 84, I2C4_EV = 83, LCD = 78, LPTIM1 = 65, LPTIM2 = 66, LPUART1 = 70, PVD_PVM = 1, QUADSPI = 71, RCC = 5, RNG = 80, RTC_ALARM = 41, RTC_TAMP_STAMP = 2, RTC_WKUP = 3, SAI1 = 74, SDMMC1 = 49, SPI1 = 35, SPI2 = 36, SPI3 = 51, SWPMI1 = 76, TIM1_BRK_TIM15 = 24, TIM1_CC = 27, TIM1_TRG_COM = 26, TIM1_UP_TIM16 = 25, TIM2 = 28, TIM3 = 29, TIM6_DACUNDER = 54, TIM7 = 55, TSC = 77, UART4 = 52, USART1 = 37, USART2 = 38, USART3 = 39, USB = 67, WWDG = 0, //CG> }; } struct Pin { uint8_t port :4, pin :4; constexpr Pin () : port (15), pin (0) {} auto read () const { return (gpio32(IDR)>>pin) & 1; } void write (int v) const { gpio32(BSRR) = (v ? 1 : 1<<16)<<pin; } // shorthand void toggle () const { write(!read()); } operator int () const { return read(); } void operator= (int v) const { write(v); } // pin definition string: [A-O][<pin#>]:[AFPO][DU][LNHV][<alt#>][,] // return -1 on error, 0 if no mode set, or the mode (always > 0) auto config (char const*) -> int; // define multiple pins, return nullptr if ok, else ptr to error static auto define (char const*, Pin* =nullptr, int =0) -> char const*; private: constexpr static auto OFF = FAMILY == STM::F1 ? 0x0 : 0x8; enum { IDR=0x08+OFF, ODR=0x0C+OFF, BSRR=0x10+OFF }; auto gpio32 (int off) const -> volatile uint32_t& { return dev::GPIOA(0x400*port+off); } auto gpio32 (int off, int bit, uint8_t num =1) const { return dev::GPIOA(0x400*port+off, bit, num); } auto mode (int) const -> int; auto mode (char const* desc) const -> int; }; struct BlockIRQ { BlockIRQ () { asm ("cpsid i"); } ~BlockIRQ () { asm ("cpsie i"); } }; inline void nvicEnable (uint8_t irq) { dev::NVIC(0x00+4*(irq>>5)) = 1 << (irq&0x1F); } inline void nvicDisable (uint8_t irq) { dev::NVIC(0x80+4*(irq>>5)) = 1 << (irq&0x1F); } namespace systick { extern void (*expirer)(uint16_t,uint16_t&); void init (uint8_t ms =100); void deinit (); auto millis () -> uint32_t; auto micros () -> uint32_t; } namespace cycles { constexpr Io32<0xE000'1000> DWT; void init (); void deinit (); inline void clear () { DWT(0x04) = 0; } inline auto count () -> uint32_t { return DWT(0x04); } } namespace watchdog { auto resetCause () -> int; // watchdog: -1, nrst: 1, power: 2, other: 0 void init (int rate =6); // max timeout, 0 ≈ 500 ms, 6 ≈ 32 s void reload (int n); // 0..4095 x 125 µs (0) .. 8 ms (6) void kick (); } namespace rtc { struct DateTime { uint8_t yr, mo, dy, hh, mm, ss; }; void init (); auto get () -> DateTime; void set (DateTime dt); auto getData (int reg) -> uint32_t; void setData (int reg, uint32_t val); } namespace uart { void init (int n, char const* desc, int baud =115200); void deinit (int n); auto getc (int n) -> int; void putc (int n, int c); } }
[ "jc@wippler.nl" ]
jc@wippler.nl
78bb9cd5dbd11b0db911bf332a02609f44d6611a
b389755eed095f67bac67bde8690adf0217d8470
/modules/core/engine/src/Logger/LoggerServiceInterface.cpp
10bf206362e0ac0c164316c66dffc84c09941d49
[ "JSON", "MIT", "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
shoesel/aac-sdk
4fdbb85d4d51aaaad7adb5d7ae69dfd65559dbd6
8370f7c71c73dd1af53469dfa3de1eaf7aa2d347
refs/heads/master
2020-06-10T14:00:11.911393
2019-06-24T22:46:22
2019-06-24T23:04:52
193,653,787
1
0
Apache-2.0
2019-06-25T07:06:17
2019-06-25T07:06:17
null
UTF-8
C++
false
false
819
cpp
/* * Copyright 2017-2019 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. */ #include "AACE/Engine/Logger/LoggerServiceInterface.h" namespace aace { namespace engine { namespace logger { LoggerServiceInterface::~LoggerServiceInterface() { } } // aace::engine::logger } // aace::engine } // aace
[ "muni.sakkuru@gmail.com" ]
muni.sakkuru@gmail.com
b6daaa546edb8da66ff5de7f02a232f83054a98a
3626089e86884038dc59104aa6fb1c5a7f6ba88a
/spf/bk2_spf.cpp
572da4976c69676e0674d88a3d33159d70dedf50
[]
no_license
costain/parallel
93568b9429a3d44c3d16e5247e75557e1a3f138d
a658b88de236a160427aff41b97bacb84dc60963
refs/heads/master
2020-09-02T13:44:40.315416
2019-11-27T00:10:19
2019-11-27T00:10:19
219,234,447
0
0
null
null
null
null
UTF-8
C++
false
false
3,210
cpp
#include <iostream> #include <mpi.h> #include <string.h> //using namespace std; #include <stdio.h> #include <stdlib.h> const int SIZE = 6; //maximum size of the graph char G[SIZE][SIZE]; //adjacency matrix bool OK[SIZE]; //nodes done int D[SIZE]; //distance int path[SIZE]; //we came to this node from const int INFINITY=9999; //big enough number, bigger than any possible path #define buffer_size 2024 const char *filename = "edge.txt"; int nproc, id; MPI_Status status; int N; int Read_G_Adjacency_Matrix(){ //actual G[][] adjacency matrix read in int u,v = 0; for ( u = 0; u < SIZE; u++){ for(int v = 0; v < SIZE; v++){ if( u==v){ G[u][v]=0; } else { G[u][v] = 'i'; } } } char nodeU = 'a'; char nodeV= 'a' ; char nodeZ ='a'; const char *delimiter_characters = " "; FILE *input_file = fopen( filename, "r" ); char buffer[ buffer_size ]; char *last_token; int nodes = SIZE; if( input_file == NULL ){ fprintf( stderr, "Unable to open file %s\n", filename ); }else { while (fgets(buffer, buffer_size, input_file) != NULL) { last_token = strtok(buffer, delimiter_characters); while (last_token != NULL) { nodeU = last_token[0]; nodeV = strtok(NULL, delimiter_characters)[0]; nodeZ = strtok(NULL, delimiter_characters)[0]; G[nodeU][nodeV] = nodeZ; printf("Adding: (%d,%d, %d)\n", nodeU, nodeV,nodeZ); last_token = strtok(NULL, delimiter_characters); } } if (ferror(input_file)) { perror("The following error occurred"); } fclose(input_file); return 0; } } void dijk(int s){ int i,j; int tmp, x; int pair[2]; int tmp_pair[2]; for(i=id;i<N;i+=nproc){ D[i]=G[s][i]; OK[i]=false; path[i]=s; } OK[s]=true; path[s]=-1; for(j=1;j<N;j++){ tmp=INFINITY; for(i=id;i<N;i+=nproc){ if(!OK[i] && D[i]<tmp){ x=i; tmp=D[i]; } } pair[0]=x; pair[1]=tmp; if(id!=0){ //Slave MPI_Send(pair,2,MPI_INT,0,1,MPI_COMM_WORLD); }else{ // id==0, Master for(i=1;i<nproc;++i){ MPI_Recv(tmp_pair,2,MPI_INT,i,1,MPI_COMM_WORLD, &status); if(tmp_pair[1]<pair[1]){ pair[0]=tmp_pair[0]; pair[1]=tmp_pair[1]; } } } MPI_Bcast(pair,2,MPI_INT,0,MPI_COMM_WORLD); x=pair[0]; D[x]=pair[1]; OK[x]=true; for(i=id;i<N;i+=nproc){ if(!OK[i] && D[i]>D[x]+G[x][i]){ D[i]=D[x]+G[x][i]; path[i]=x; } } } } main(int argc, char** argv){ double t1, t2; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); // get totalnodes MPI_Comm_rank(MPI_COMM_WORLD, &id); // get mynode N=Read_G_Adjacency_Matrix(); //read in the G[][] //set actual size printf("We are here"); if(id==0){ t1=MPI_Wtime(); } dijk(200); //call the algorithm with the choosen node if(id==0){ t2=MPI_Wtime(); //check the results with some output from G[][] and D[] printf("time elapsed:%d ",(t2-t1)); } MPI_Finalize(); }
[ "costain01@gmail.com" ]
costain01@gmail.com
0b78bde641b30a8e33324395aaa6630677993cae
60db84d8cb6a58bdb3fb8df8db954d9d66024137
/android-cpp-sdk/platforms/android-4/java/sql/Date.hpp
78accf359b3cf311f2ea7113bf983986e64f23b5
[ "BSL-1.0" ]
permissive
tpurtell/android-cpp-sdk
ba853335b3a5bd7e2b5c56dcb5a5be848da6550c
8313bb88332c5476645d5850fe5fdee8998c2415
refs/heads/master
2021-01-10T20:46:37.322718
2012-07-17T22:06:16
2012-07-17T22:06:16
37,555,992
5
4
null
null
null
null
UTF-8
C++
false
false
6,618
hpp
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.sql.Date ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SQL_DATE_HPP_DECL #define J2CPP_JAVA_SQL_DATE_HPP_DECL namespace j2cpp { namespace java { namespace io { class Serializable; } } } namespace j2cpp { namespace java { namespace util { class Date; } } } namespace j2cpp { namespace java { namespace lang { class Comparable; } } } namespace j2cpp { namespace java { namespace lang { class Cloneable; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } #include <java/io/Serializable.hpp> #include <java/lang/Cloneable.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <java/util/Date.hpp> namespace j2cpp { namespace java { namespace sql { class Date; class Date : public object<Date> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) explicit Date(jobject jobj) : object<Date>(jobj) { } operator local_ref<java::io::Serializable>() const; operator local_ref<java::util::Date>() const; operator local_ref<java::lang::Comparable>() const; operator local_ref<java::lang::Cloneable>() const; operator local_ref<java::lang::Object>() const; Date(jint, jint, jint); Date(jlong); jint getHours(); jint getMinutes(); jint getSeconds(); void setHours(jint); void setMinutes(jint); void setSeconds(jint); void setTime(jlong); local_ref< java::lang::String > toString(); static local_ref< java::sql::Date > valueOf(local_ref< java::lang::String > const&); }; //class Date } //namespace sql } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_SQL_DATE_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SQL_DATE_HPP_IMPL #define J2CPP_JAVA_SQL_DATE_HPP_IMPL namespace j2cpp { java::sql::Date::operator local_ref<java::io::Serializable>() const { return local_ref<java::io::Serializable>(get_jobject()); } java::sql::Date::operator local_ref<java::util::Date>() const { return local_ref<java::util::Date>(get_jobject()); } java::sql::Date::operator local_ref<java::lang::Comparable>() const { return local_ref<java::lang::Comparable>(get_jobject()); } java::sql::Date::operator local_ref<java::lang::Cloneable>() const { return local_ref<java::lang::Cloneable>(get_jobject()); } java::sql::Date::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } java::sql::Date::Date(jint a0, jint a1, jint a2) : object<java::sql::Date>( call_new_object< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(0), java::sql::Date::J2CPP_METHOD_SIGNATURE(0) >(a0, a1, a2) ) { } java::sql::Date::Date(jlong a0) : object<java::sql::Date>( call_new_object< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(1), java::sql::Date::J2CPP_METHOD_SIGNATURE(1) >(a0) ) { } jint java::sql::Date::getHours() { return call_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(2), java::sql::Date::J2CPP_METHOD_SIGNATURE(2), jint >(get_jobject()); } jint java::sql::Date::getMinutes() { return call_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(3), java::sql::Date::J2CPP_METHOD_SIGNATURE(3), jint >(get_jobject()); } jint java::sql::Date::getSeconds() { return call_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(4), java::sql::Date::J2CPP_METHOD_SIGNATURE(4), jint >(get_jobject()); } void java::sql::Date::setHours(jint a0) { return call_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(5), java::sql::Date::J2CPP_METHOD_SIGNATURE(5), void >(get_jobject(), a0); } void java::sql::Date::setMinutes(jint a0) { return call_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(6), java::sql::Date::J2CPP_METHOD_SIGNATURE(6), void >(get_jobject(), a0); } void java::sql::Date::setSeconds(jint a0) { return call_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(7), java::sql::Date::J2CPP_METHOD_SIGNATURE(7), void >(get_jobject(), a0); } void java::sql::Date::setTime(jlong a0) { return call_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(8), java::sql::Date::J2CPP_METHOD_SIGNATURE(8), void >(get_jobject(), a0); } local_ref< java::lang::String > java::sql::Date::toString() { return call_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(9), java::sql::Date::J2CPP_METHOD_SIGNATURE(9), local_ref< java::lang::String > >(get_jobject()); } local_ref< java::sql::Date > java::sql::Date::valueOf(local_ref< java::lang::String > const &a0) { return call_static_method< java::sql::Date::J2CPP_CLASS_NAME, java::sql::Date::J2CPP_METHOD_NAME(10), java::sql::Date::J2CPP_METHOD_SIGNATURE(10), local_ref< java::sql::Date > >(a0); } J2CPP_DEFINE_CLASS(java::sql::Date,"java/sql/Date") J2CPP_DEFINE_METHOD(java::sql::Date,0,"<init>","(III)V") J2CPP_DEFINE_METHOD(java::sql::Date,1,"<init>","(J)V") J2CPP_DEFINE_METHOD(java::sql::Date,2,"getHours","()I") J2CPP_DEFINE_METHOD(java::sql::Date,3,"getMinutes","()I") J2CPP_DEFINE_METHOD(java::sql::Date,4,"getSeconds","()I") J2CPP_DEFINE_METHOD(java::sql::Date,5,"setHours","(I)V") J2CPP_DEFINE_METHOD(java::sql::Date,6,"setMinutes","(I)V") J2CPP_DEFINE_METHOD(java::sql::Date,7,"setSeconds","(I)V") J2CPP_DEFINE_METHOD(java::sql::Date,8,"setTime","(J)V") J2CPP_DEFINE_METHOD(java::sql::Date,9,"toString","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::sql::Date,10,"valueOf","(Ljava/lang/String;)Ljava/sql/Date;") } //namespace j2cpp #endif //J2CPP_JAVA_SQL_DATE_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
[ "baldzar@gmail.com" ]
baldzar@gmail.com
799dbeda52c6c164cd422f53023ec403dfa1db79
47ebf27cd965269321b5d07beea10aec6da494d9
/Tests/DerivativeUnitTests/DerivativeUnitTests.cpp
039692ba38d5ec8a9b62796184eb8e91ee8444a9
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
JamieBamber/GRChombo
9220fa67eeaa97eee17bc3c0a8ad17bfd3d02d0e
4399e51f71618754282049d6f2946b69ad2c12ee
refs/heads/master
2022-03-21T18:49:41.668222
2020-11-24T23:21:14
2020-11-24T23:21:14
201,951,780
0
0
BSD-3-Clause
2020-03-11T10:19:26
2019-08-12T14:55:47
C++
UTF-8
C++
false
false
2,985
cpp
/* GRChombo * Copyright 2012 The GRChombo collaboration. * Please refer to LICENSE in GRChombo's root directory. */ #include "FArrayBox.H" #include <iostream> #include "BoxIterator.H" #include "BoxLoops.hpp" #include "DerivativeTestsCompute.hpp" #include "UserVariables.hpp" bool is_wrong(double value, double correct_value, std::string deriv_type) { if (abs(value - correct_value) > 1e-10) { std::cout.precision(17); std::cout << "Test of " << deriv_type << " failed " << " with value " << value << " instad of " << correct_value << ".\n"; return true; } else { return false; } } int main() { const int num_cells = 512; // box is flat in y direction to make test cheaper IntVect domain_hi_vect(num_cells - 1, 0, num_cells - 1); Box box(IntVect(0, 0, 0), domain_hi_vect); Box ghosted_box(IntVect(-3, -3, -3), IntVect(num_cells + 2, 3, num_cells + 2)); FArrayBox in_fab(ghosted_box, NUM_VARS); FArrayBox out_fab(box, NUM_VARS); const double dx = 1.0 / num_cells; BoxIterator bit_ghost(ghosted_box); for (bit_ghost.begin(); bit_ghost.ok(); ++bit_ghost) { const double x = (0.5 + bit_ghost()[0]) * dx; const double z = (0.5 + bit_ghost()[2]) * dx; for (int i = 0; i < NUM_VARS; ++i) { in_fab(bit_ghost(), i) = x * z * (z - 1); } // The dissipation component is special: in_fab(bit_ghost(), c_diss) = (pow(z - 0.5, 6) - 0.015625) / 720. + (z - 1) * z * pow(x, 6) / 720.; } // Compute the derivatives for the timing comparison BoxLoops::loop(DerivativeTestsCompute(dx), in_fab, out_fab); BoxIterator bit(box); for (bit.begin(); bit.ok(); ++bit) { const double x = (0.5 + bit()[0]) * dx; const double z = (0.5 + bit()[2]) * dx; bool error = false; error |= is_wrong(out_fab(bit(), c_d1), 2 * x * (z - 0.5), "diff1"); error |= is_wrong(out_fab(bit(), c_d2), 2 * x, "diff2"); error |= is_wrong(out_fab(bit(), c_d2_mixed), 2 * (z - 0.5), "mixed diff2"); double correct_dissipation = (1. + z * (z - 1)) * pow(dx, 5) / 64; error |= is_wrong(out_fab(bit(), c_diss), correct_dissipation, "dissipation"); double correct_advec_down = -2 * z * (z - 1) - 3 * x * (2 * z - 1); error |= is_wrong(out_fab(bit(), c_advec_down), correct_advec_down, "advection down"); double correct_advec_up = 2 * z * (z - 1) + 3 * x * (2 * z - 1); error |= is_wrong(out_fab(bit(), c_advec_up), correct_advec_up, "advection up"); if (error) { std::cout << "Derivative unit tests NOT passed.\n"; return error; } } std::cout << "Derivative unit tests passed.\n"; return 0; }
[ "m.kunesch@damtp.cam.ac.uk" ]
m.kunesch@damtp.cam.ac.uk
bf403d235a36de8087397b60ed2186a1da0ff548
95bde36b21aef0f2b4053e6c8aadbf01ac958b04
/page2.h
be6bb3f96eea5585d1e37b1b705dc952c76e7444
[]
no_license
bjk12/Engineering-Assistant
c33c3c48c0cd683ed023a0bad9fdc8fca10b7eda
a7c321a8c1c1ce6a541ba56f995a28487e1b8593
refs/heads/main
2023-04-08T11:33:41.394727
2021-04-22T09:35:16
2021-04-22T09:35:16
357,164,738
1
0
null
null
null
null
UTF-8
C++
false
false
611
h
#ifndef PAGE2_H #define PAGE2_H #include <QDialog> namespace Ui { class page2; } class page2 : public QDialog { Q_OBJECT public: explicit page2(QWidget *parent = 0); ~page2(); private slots: void on_backButton_clicked(); void on_timeout () ; //定时溢出处理槽函数 void on_startButton_clicked(); void on_suspendButton_clicked(); void on_calculate51Button_clicked(); void on_changetButton_clicked(); private: Ui::page2 *ui; void reject(); QTimer* Timer1; signals: void back2page1(); }; #endif // PAGE2_H
[ "1838336514@qq.com" ]
1838336514@qq.com
1bef7beeca64b058ed3488d3d065ea49677d81f0
33868f8d4a0b5795290c4f628108ff6b29e90716
/Client/Client.Core/Game/GameOverlay.h
b630b826ba0f427febd4995f03e7c4c86cd86aa3
[]
no_license
grasmanek94/v-plus-mod
cdc87c77bd703c4b846b48139746e52ec8b6de94
9c4127fdf6c227f1dd5fbc75d377d98306c03a76
refs/heads/master
2021-03-26T10:05:45.896887
2016-08-13T15:01:10
2016-08-13T15:01:10
63,270,812
0
0
null
null
null
null
UTF-8
C++
false
false
874
h
#pragma once class Vector2; class Vector3; class GameUI; typedef HRESULT (__stdcall *DXGISwapChainPresent) (IDXGISwapChain *pSwapChain, UINT SyncInterval, UINT Flags); typedef bool (__fastcall *EngineWorldToScreen_t)(Vector3 worldPos, float *pRelativeScreenPositionX, float *pRelativeScreenPositionY); class GameOverlay { private: static bool bInitialized; static GameUI *pGameUI; static DXGISwapChainPresent pRealPresent; static uintptr_t hkSwapChainVFTable[64]; static EngineWorldToScreen_t EngineWorldToScreen; static HRESULT __stdcall HookedPresent(IDXGISwapChain* pSwapChain, UINT SyncInterval, UINT Flags); public: static bool IsInitialized() { return bInitialized; } static GameUI * GetGameUI() { return pGameUI; } static bool Setup(); static void Shutdown(); static bool WorldToScreen(const Vector3 &worldPosition, Vector2 &screenPosition); };
[ "p3ti@hotmail.hu" ]
p3ti@hotmail.hu
00ba09a986451f21c92fec82846975d42699a666
b00c54389a95d81a22e361fa9f8bdf5a2edc93e3
/external/deqp/modules/egl/teglQueryContextTests.cpp
c6edb9d1ed1c2e0e20c4728f1de6f3995cbbaa03
[ "Apache-2.0" ]
permissive
mirek190/x86-android-5.0
9d1756fa7ff2f423887aa22694bd737eb634ef23
eb1029956682072bb7404192a80214189f0dc73b
refs/heads/master
2020-05-27T01:09:51.830208
2015-10-07T22:47:36
2015-10-07T22:47:36
41,942,802
15
20
null
2020-03-09T00:21:03
2015-09-05T00:11:19
null
UTF-8
C++
false
false
18,379
cpp
/*------------------------------------------------------------------------- * drawElements Quality Program EGL Module * --------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Config query tests. *//*--------------------------------------------------------------------*/ #include "teglQueryContextTests.hpp" #include "teglSimpleConfigCase.hpp" #include "teglRenderCase.hpp" #include "egluCallLogWrapper.hpp" #include "egluStrUtil.hpp" #include "tcuCommandLine.hpp" #include "tcuTestLog.hpp" #include "tcuTestContext.hpp" #include "egluUtil.hpp" #include "egluNativeDisplay.hpp" #include "egluNativeWindow.hpp" #include "egluNativePixmap.hpp" #include "deUniquePtr.hpp" #include <vector> #include <EGL/eglext.h> #if !defined(EGL_OPENGL_ES3_BIT_KHR) # define EGL_OPENGL_ES3_BIT_KHR 0x0040 #endif #if !defined(EGL_CONTEXT_MAJOR_VERSION_KHR) # define EGL_CONTEXT_MAJOR_VERSION_KHR EGL_CONTEXT_CLIENT_VERSION #endif namespace deqp { namespace egl { using eglu::ConfigInfo; using tcu::TestLog; struct ContextCaseInfo { EGLint surfaceType; EGLint clientType; EGLint clientVersion; }; class ContextCase : public SimpleConfigCase, protected eglu::CallLogWrapper { public: ContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const std::vector<EGLint>& configIds, EGLint surfaceTypeMask); virtual ~ContextCase (void); void executeForConfig (tcu::egl::Display& display, EGLConfig config); void executeForSurface (tcu::egl::Display& display, EGLConfig config, EGLSurface surface, ContextCaseInfo& info); virtual void executeForContext (tcu::egl::Display& display, EGLConfig config, EGLSurface surface, EGLContext context, ContextCaseInfo& info) = 0; private: EGLint m_surfaceTypeMask; }; ContextCase::ContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const std::vector<EGLint>& configIds, EGLint surfaceTypeMask) : SimpleConfigCase (eglTestCtx, name, description, configIds) , CallLogWrapper (eglTestCtx.getTestContext().getLog()) , m_surfaceTypeMask (surfaceTypeMask) { } ContextCase::~ContextCase (void) { } void ContextCase::executeForConfig (tcu::egl::Display& display, EGLConfig config) { tcu::TestLog& log = m_testCtx.getLog(); const int width = 64; const int height = 64; const EGLint configId = display.getConfigAttrib(config, EGL_CONFIG_ID); eglu::NativeDisplay& nativeDisplay = m_eglTestCtx.getNativeDisplay(); bool isOk = true; std::string failReason = ""; if (m_surfaceTypeMask & EGL_WINDOW_BIT) { log << TestLog::Message << "Creating window surface with config ID " << configId << TestLog::EndMessage; try { de::UniquePtr<eglu::NativeWindow> window (m_eglTestCtx.createNativeWindow(display.getEGLDisplay(), config, DE_NULL, width, height, eglu::parseWindowVisibility(m_testCtx.getCommandLine()))); tcu::egl::WindowSurface surface (display, eglu::createWindowSurface(nativeDisplay, *window, display.getEGLDisplay(), config, DE_NULL)); ContextCaseInfo info; info.surfaceType = EGL_WINDOW_BIT; executeForSurface(m_eglTestCtx.getDisplay(), config, surface.getEGLSurface(), info); } catch (const tcu::TestError& e) { log << e; isOk = false; failReason = e.what(); } log << TestLog::Message << TestLog::EndMessage; } if (m_surfaceTypeMask & EGL_PIXMAP_BIT) { log << TestLog::Message << "Creating pixmap surface with config ID " << configId << TestLog::EndMessage; try { de::UniquePtr<eglu::NativePixmap> pixmap (m_eglTestCtx.createNativePixmap(display.getEGLDisplay(), config, DE_NULL, width, height)); tcu::egl::PixmapSurface surface (display, eglu::createPixmapSurface(nativeDisplay, *pixmap, display.getEGLDisplay(), config, DE_NULL)); ContextCaseInfo info; info.surfaceType = EGL_PIXMAP_BIT; executeForSurface(display, config, surface.getEGLSurface(), info); } catch (const tcu::TestError& e) { log << e; isOk = false; failReason = e.what(); } log << TestLog::Message << TestLog::EndMessage; } if (m_surfaceTypeMask & EGL_PBUFFER_BIT) { log << TestLog::Message << "Creating pbuffer surface with config ID " << configId << TestLog::EndMessage; try { const EGLint surfaceAttribs[] = { EGL_WIDTH, width, EGL_HEIGHT, height, EGL_NONE }; tcu::egl::PbufferSurface surface(display, config, surfaceAttribs); ContextCaseInfo info; info.surfaceType = EGL_PBUFFER_BIT; executeForSurface(display, config, surface.getEGLSurface(), info); } catch (const tcu::TestError& e) { log << e; isOk = false; failReason = e.what(); } log << TestLog::Message << TestLog::EndMessage; } if (!isOk && m_testCtx.getTestResult() == QP_TEST_RESULT_PASS) m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, failReason.c_str()); } void ContextCase::executeForSurface (tcu::egl::Display& display, EGLConfig config, EGLSurface surface, ContextCaseInfo& info) { TestLog& log = m_testCtx.getLog(); EGLint apiBits = display.getConfigAttrib(config, EGL_RENDERABLE_TYPE); static const EGLint es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE }; static const EGLint es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; static const EGLint es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR, 3, EGL_NONE }; static const struct { const char* name; EGLenum api; EGLint apiBit; const EGLint* ctxAttrs; EGLint apiVersion; } apis[] = { { "OpenGL", EGL_OPENGL_API, EGL_OPENGL_BIT, DE_NULL, 0 }, { "OpenGL ES 1", EGL_OPENGL_ES_API, EGL_OPENGL_ES_BIT, es1Attrs, 1 }, { "OpenGL ES 2", EGL_OPENGL_ES_API, EGL_OPENGL_ES2_BIT, es2Attrs, 2 }, { "OpenGL ES 3", EGL_OPENGL_ES_API, EGL_OPENGL_ES3_BIT_KHR, es3Attrs, 3 }, { "OpenVG", EGL_OPENVG_API, EGL_OPENVG_BIT, DE_NULL, 0 } }; for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(apis); apiNdx++) { if ((apiBits & apis[apiNdx].apiBit) == 0) continue; // Not supported API TCU_CHECK_EGL_CALL(eglBindAPI(apis[apiNdx].api)); log << TestLog::Message << "Creating " << apis[apiNdx].name << " context" << TestLog::EndMessage; const EGLContext context = eglCreateContext(display.getEGLDisplay(), config, EGL_NO_CONTEXT, apis[apiNdx].ctxAttrs); TCU_CHECK_EGL(); TCU_CHECK(context != EGL_NO_CONTEXT); TCU_CHECK_EGL_CALL(eglMakeCurrent(display.getEGLDisplay(), surface, surface, context)); info.clientType = apis[apiNdx].api; info.clientVersion = apis[apiNdx].apiVersion; executeForContext(display, config, surface, context, info); // Destroy TCU_CHECK_EGL_CALL(eglMakeCurrent(display.getEGLDisplay(), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); TCU_CHECK_EGL_CALL(eglDestroyContext(display.getEGLDisplay(), context)); } } class GetCurrentContextCase : public ContextCase { public: GetCurrentContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const std::vector<EGLint>& configIds, EGLint surfaceTypeMask) : ContextCase(eglTestCtx, name, description, configIds, surfaceTypeMask) { } void executeForContext (tcu::egl::Display& display, EGLConfig config, EGLSurface surface, EGLContext context, ContextCaseInfo& info) { TestLog& log = m_testCtx.getLog(); DE_UNREF(display); DE_UNREF(config && surface); DE_UNREF(info); enableLogging(true); const EGLContext gotContext = eglGetCurrentContext(); TCU_CHECK_EGL(); if (gotContext == context) { log << TestLog::Message << " Pass" << TestLog::EndMessage; } else if (gotContext == EGL_NO_CONTEXT) { log << TestLog::Message << " Fail, got EGL_NO_CONTEXT" << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Unexpected EGL_NO_CONTEXT"); } else if (gotContext != context) { log << TestLog::Message << " Fail, call returned the wrong context. Expected: " << tcu::toHex(context) << ", got: " << tcu::toHex(gotContext) << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid context"); } enableLogging(false); } }; class GetCurrentSurfaceCase : public ContextCase { public: GetCurrentSurfaceCase (EglTestContext& eglTestCtx, const char* name, const char* description, const std::vector<EGLint>& configIds, EGLint surfaceTypeMask) : ContextCase(eglTestCtx, name, description, configIds, surfaceTypeMask) { } void executeForContext (tcu::egl::Display& display, EGLConfig config, EGLSurface surface, EGLContext context, ContextCaseInfo& info) { TestLog& log = m_testCtx.getLog(); DE_UNREF(display); DE_UNREF(config && context); DE_UNREF(info); enableLogging(true); const EGLContext gotReadSurface = eglGetCurrentSurface(EGL_READ); TCU_CHECK_EGL(); const EGLContext gotDrawSurface = eglGetCurrentSurface(EGL_DRAW); TCU_CHECK_EGL(); if (gotReadSurface == surface && gotDrawSurface == surface) { log << TestLog::Message << " Pass" << TestLog::EndMessage; } else { log << TestLog::Message << " Fail, read surface: " << tcu::toHex(gotReadSurface) << ", draw surface: " << tcu::toHex(gotDrawSurface) << ", expected: " << tcu::toHex(surface) << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid surface"); } enableLogging(false); } }; class GetCurrentDisplayCase : public ContextCase { public: GetCurrentDisplayCase (EglTestContext& eglTestCtx, const char* name, const char* description, const std::vector<EGLint>& configIds, EGLint surfaceTypeMask) : ContextCase(eglTestCtx, name, description, configIds, surfaceTypeMask) { } void executeForContext (tcu::egl::Display& display, EGLConfig config, EGLSurface surface, EGLContext context, ContextCaseInfo& info) { TestLog& log = m_testCtx.getLog(); DE_UNREF(config && surface && context); DE_UNREF(info); enableLogging(true); const EGLDisplay gotDisplay = eglGetCurrentDisplay(); TCU_CHECK_EGL(); if (gotDisplay == display.getEGLDisplay()) { log << TestLog::Message << " Pass" << TestLog::EndMessage; } else if (gotDisplay == EGL_NO_DISPLAY) { log << TestLog::Message << " Fail, got EGL_NO_DISPLAY" << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Unexpected EGL_NO_DISPLAY"); } else if (gotDisplay != display.getEGLDisplay()) { log << TestLog::Message << " Fail, call returned the wrong display. Expected: " << tcu::toHex(display.getEGLDisplay()) << ", got: " << tcu::toHex(gotDisplay) << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid display"); } enableLogging(false); } }; class QueryContextCase : public ContextCase { public: QueryContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const std::vector<EGLint>& configIds, EGLint surfaceTypeMask) : ContextCase(eglTestCtx, name, description, configIds, surfaceTypeMask) { } EGLint getContextAttrib (tcu::egl::Display& display, EGLContext context, EGLint attrib) { EGLint value; TCU_CHECK_EGL_CALL(eglQueryContext(display.getEGLDisplay(), context, attrib, &value)); return value; } void executeForContext (tcu::egl::Display& display, EGLConfig config, EGLSurface surface, EGLContext context, ContextCaseInfo& info) { TestLog& log = m_testCtx.getLog(); const eglu::Version version (display.getEGLMajorVersion(), display.getEGLMinorVersion()); DE_UNREF(surface); enableLogging(true); // Config ID { const EGLint configID = getContextAttrib(display, context, EGL_CONFIG_ID); const EGLint surfaceConfigID = display.getConfigAttrib(config, EGL_CONFIG_ID); if (configID != surfaceConfigID) { log << TestLog::Message << " Fail, config ID doesn't match the one used to create the context." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid config ID"); } } // Client API type if (version >= eglu::Version(1, 2)) { const EGLint clientType = getContextAttrib(display, context, EGL_CONTEXT_CLIENT_TYPE); if (clientType != info.clientType) { log << TestLog::Message << " Fail, client API type doesn't match." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid client API type"); } } // Client API version if (version >= eglu::Version(1, 3)) { const EGLint clientVersion = getContextAttrib(display, context, EGL_CONTEXT_CLIENT_VERSION); if (info.clientType == EGL_OPENGL_ES_API && clientVersion != info.clientVersion) { log << TestLog::Message << " Fail, client API version doesn't match." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid client API version"); } } // Render buffer if (version >= eglu::Version(1, 2)) { const EGLint renderBuffer = getContextAttrib(display, context, EGL_RENDER_BUFFER); if (info.surfaceType == EGL_PIXMAP_BIT && renderBuffer != EGL_SINGLE_BUFFER) { log << TestLog::Message << " Fail, render buffer should be EGL_SINGLE_BUFFER for a pixmap surface." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid render buffer"); } else if (info.surfaceType == EGL_PBUFFER_BIT && renderBuffer != EGL_BACK_BUFFER) { log << TestLog::Message << " Fail, render buffer should be EGL_BACK_BUFFER for a pbuffer surface." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid render buffer"); } else if (info.surfaceType == EGL_WINDOW_BIT && renderBuffer != EGL_SINGLE_BUFFER && renderBuffer != EGL_BACK_BUFFER) { log << TestLog::Message << " Fail, render buffer should be either EGL_SINGLE_BUFFER or EGL_BACK_BUFFER for a window surface." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid render buffer"); } } enableLogging(false); log << TestLog::Message << " Pass" << TestLog::EndMessage; } }; class QueryAPICase : public TestCase, protected eglu::CallLogWrapper { public: QueryAPICase (EglTestContext& eglTestCtx, const char* name, const char* description) : TestCase(eglTestCtx, name, description) , CallLogWrapper(eglTestCtx.getTestContext().getLog()) { } void init (void) { m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); } IterateResult iterate (void) { tcu::TestLog& log = m_testCtx.getLog(); const EGLenum apis[] = { EGL_OPENGL_API, EGL_OPENGL_ES_API, EGL_OPENVG_API }; enableLogging(true); { const EGLenum api = eglQueryAPI(); if (api != EGL_OPENGL_ES_API && m_eglTestCtx.isAPISupported(EGL_OPENGL_ES_API)) { log << TestLog::Message << " Fail, initial value should be EGL_OPENGL_ES_API if OpenGL ES is supported." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid default value"); } else if(api != EGL_NONE && !m_eglTestCtx.isAPISupported(EGL_OPENGL_ES_API)) { log << TestLog::Message << " Fail, initial value should be EGL_NONE if OpenGL ES is not supported." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid default value"); } } for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(apis); ndx++) { const EGLenum api = apis[ndx]; log << TestLog::Message << TestLog::EndMessage; if (m_eglTestCtx.isAPISupported(api)) { eglBindAPI(api); if (api != eglQueryAPI()) { log << TestLog::Message << " Fail, return value does not match previously bound API." << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Invalid return value"); } } else { log << TestLog::Message << eglu::getAPIStr(api) << " not supported." << TestLog::EndMessage; } } enableLogging(false); return STOP; } }; QueryContextTests::QueryContextTests (EglTestContext& eglTestCtx) : TestCaseGroup(eglTestCtx, "query_context", "Rendering context query tests") { } QueryContextTests::~QueryContextTests (void) { } template<class QueryContextClass> void createQueryContextGroups (EglTestContext& eglTestCtx, tcu::TestCaseGroup* group) { std::vector<RenderConfigIdSet> configSets; eglu::FilterList filters; getDefaultRenderConfigIdSets(configSets, eglTestCtx.getConfigs(), filters); for (std::vector<RenderConfigIdSet>::const_iterator setIter = configSets.begin(); setIter != configSets.end(); setIter++) group->addChild(new QueryContextClass(eglTestCtx, setIter->getName(), "", setIter->getConfigIds(), setIter->getSurfaceTypeMask())); } void QueryContextTests::init (void) { { tcu::TestCaseGroup* simpleGroup = new tcu::TestCaseGroup(m_testCtx, "simple", "Simple API tests"); addChild(simpleGroup); simpleGroup->addChild(new QueryAPICase(m_eglTestCtx, "query_api", "eglQueryAPI() test")); } // eglGetCurrentContext { tcu::TestCaseGroup* getCurrentContextGroup = new tcu::TestCaseGroup(m_testCtx, "get_current_context", "eglGetCurrentContext() tests"); addChild(getCurrentContextGroup); createQueryContextGroups<GetCurrentContextCase>(m_eglTestCtx, getCurrentContextGroup); } // eglGetCurrentSurface { tcu::TestCaseGroup* getCurrentSurfaceGroup = new tcu::TestCaseGroup(m_testCtx, "get_current_surface", "eglGetCurrentSurface() tests"); addChild(getCurrentSurfaceGroup); createQueryContextGroups<GetCurrentSurfaceCase>(m_eglTestCtx, getCurrentSurfaceGroup); } // eglGetCurrentDisplay { tcu::TestCaseGroup* getCurrentDisplayGroup = new tcu::TestCaseGroup(m_testCtx, "get_current_display", "eglGetCurrentDisplay() tests"); addChild(getCurrentDisplayGroup); createQueryContextGroups<GetCurrentDisplayCase>(m_eglTestCtx, getCurrentDisplayGroup); } // eglQueryContext { tcu::TestCaseGroup* queryContextGroup = new tcu::TestCaseGroup(m_testCtx, "query_context", "eglQueryContext() tests"); addChild(queryContextGroup); createQueryContextGroups<QueryContextCase>(m_eglTestCtx, queryContextGroup); } } } // egl } // deqp
[ "mirek190@gmail.com" ]
mirek190@gmail.com
7ba2134432f4861832e335af273f0efcc7464a46
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtbase/src/plugins/platforms/ios/qiostheme.h
58144cb239839b1ea3b2b82c295c42340eca6125
[ "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
2,478
h
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the plugins 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$ ** ****************************************************************************/ #ifndef QIOSTHEME_H #define QIOSTHEME_H #include <QtCore/QHash> #include <QtGui/QPalette> #include <qpa/qplatformtheme.h> QT_BEGIN_NAMESPACE class QIOSTheme : public QPlatformTheme { public: QIOSTheme(); ~QIOSTheme(); const QPalette *palette(Palette type = SystemPalette) const Q_DECL_OVERRIDE; QVariant themeHint(ThemeHint hint) const Q_DECL_OVERRIDE; QPlatformMenuItem* createPlatformMenuItem() const Q_DECL_OVERRIDE; QPlatformMenu* createPlatformMenu() const Q_DECL_OVERRIDE; bool usePlatformNativeDialog(DialogType type) const Q_DECL_OVERRIDE; QPlatformDialogHelper *createPlatformDialogHelper(DialogType type) const Q_DECL_OVERRIDE; const QFont *font(Font type = SystemFont) const Q_DECL_OVERRIDE; static const char *name; private: mutable QHash<QPlatformTheme::Font, QFont *> m_fonts; QPalette m_systemPalette; }; QT_END_NAMESPACE #endif
[ "p_pavlov@wargaming.net" ]
p_pavlov@wargaming.net
c2b1e1ef5841c6d986df8a77d4cd8bd732d63536
84934b30b21e5f074e3c6d37821cf581da7d9784
/HPSS/Method2/hpss.h
7826ef4da61945ae111b806e6c0a1c8f356382ee
[]
no_license
vinson0526/Master_Graduate_Thesis
41645359a0130b200d2bcf92ec7c900fae1f0f9d
2d53d401722931e6c6e02a32466c65fde5f1ea10
refs/heads/master
2016-09-05T22:50:25.722218
2014-04-25T14:22:42
2014-04-25T14:22:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
936
h
#ifndef HPSS_H #define HPSS_H #include <vector> #include <string> #include <cmath> #include <iomanip> #include <fstream> #include <iostream> using namespace std; class HPSS { public: HPSS(){}; HPSS(string fileNameCome, int frameSizeCome, int maxIterCome = 500, double gammaCome = 0.5, double sigmaHCome = 0.3, double sigmaPCome = 0.3); ~HPSS(); void computeHP(string HFileName, string PFileName); private: void method1(); void method2(); void initial(); void computeABC(); void computeM(); vector<vector<double>> W; vector<vector<double>> H; vector<vector<double>> P; vector<vector<double>> mH; vector<vector<double>> mP; double aH; double aP; vector<vector<double>> bH; vector<vector<double>> bP; vector<vector<double>> cH; vector<vector<double>> cP; double alpha; double gamma; double sigmaH2; double sigmaP2; double Q; string fileName; int frameSize; int frameNum; int maxIter; }; #endif
[ "vinson0526@gmail.com" ]
vinson0526@gmail.com
09f9561ebf16dcab03c0531db741da0116b03422
641ab842216b3c8bee128e23ff8020a25a50af53
/src/Menu.hpp
a0a624ea8f2472bccfb6daff4ca81bba4a428135
[ "MIT" ]
permissive
saugkim/aalto_cs1
9f25e1ebc720d1112b1161eafd0110aced6d198f
c2c3f2ff152959914d91376a2fc8668846bbac90
refs/heads/main
2023-01-23T09:13:20.000453
2020-11-25T14:13:14
2020-11-25T14:13:14
314,247,915
0
0
null
null
null
null
UTF-8
C++
false
false
184
hpp
#include <string> using namespace std; class Menu { public: Menu(char* text) { text_ = text; }; void Show(string& action, bool menuActive); private: char* text_; };
[ "ugkimm@naver.com" ]
ugkimm@naver.com
3c81fc9aca6fd63746864a8a913e152809ab9fce
30771c41966bbc4c0f2e6b80f73e0507e6dbf321
/temp/Stack/getMin.cpp
286d94f88323801166dac66f643288928bdd3878
[]
no_license
ShubhamS156/daaGFG
1dae47fb0847a0fdf490a33365d8bcb260a35428
959c8f8f4748d5a9433c15bfa68240e90fa70971
refs/heads/master
2022-12-03T02:42:53.798625
2020-08-18T13:09:27
2020-08-18T13:09:27
282,121,950
0
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
#include<iostream> #include<stack> using namespace std; //implementing stack using supposedly linked list /* IDEA: maintain an stack while pushing that keeps track of the smallest element yet. */ stack<int> ms; //main stack stack<int> as; //auxilary stack's top contatins the minimum element yet int ModeifiedPush(int key){ ms.push(key); if(ms.top()<=as.top()) as.push(key); } int ModifiedPop(){ if(as.top()==ms.top()){ as.pop(); } ms.pop(); }
[ "sharmashubh428@gmail.com" ]
sharmashubh428@gmail.com
2a4a98c6d2a9112b85334e2584862ab048eee7d5
2b6cb51c20ce7930af6cbbfa718c13d33491e814
/main.cpp
a7d39981af7a3a3d9f53f420abdaaa3ce7d19d70
[]
no_license
b0w1d/Othello
658be19e2df7f2ee83c79573f9640d88953f56f1
4ce69284759d010342fc623cb6d8262c8abe993f
refs/heads/master
2021-09-02T00:15:11.207447
2017-12-29T10:37:07
2017-12-29T10:37:07
115,713,734
0
0
null
null
null
null
UTF-8
C++
false
false
8,851
cpp
#define CONCAT(func, name) func##name #define HAND(name) CONCAT(I2P_, name) #define FIRST RANDOM // computer #define SECOND 106000135 // change to your student ID (ex: 105062999) #define _CRT_SECURE_NO_WARNINGS #ifndef FIRST #error you have to specify macro FIRST #endif #ifndef SECOND #error you have to specify macro SECOND #endif #include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <string> #include <vector> using namespace std; const int N = 10; extern pair<int, int> HAND(FIRST)(int Board[][N], int player, vector<pair<int, int>> ValidPoint); extern pair<int, int> HAND(SECOND)(int Board[][N], int player, vector<pair<int, int>> ValidPoint); void InitialBoard(int a[N][N]) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) a[i][j] = 0; a[4][4] = 2; a[5][5] = 2; a[4][5] = 1; a[5][4] = 1; for (int j = 0; j < N; j++) a[0][j] = -1; for (int j = 0; j < N; j++) a[N - 1][j] = -1; for (int i = 0; i < N; i++) a[i][0] = -1; for (int i = 0; i < N; i++) a[i][N - 1] = -1; } void BoardShow(int Board[N][N]) { cout << " |-+-+-+-+-+-+-+-|\n"; for (int i = 1; i < N - 1; i++) { cout << " "; cout << i; cout << "|"; for (int j = 1; j < N; j++) { if (Board[j][i] == 1) cout << "x" << "|"; else if (Board[j][i] == 2) cout << "o" << "|"; else if (Board[j][i] == 0) cout << " " << "|"; } cout << "\n"; if (i != N - 2) cout << " |-+-+-+-+-+-+-+-|\n"; } cout << " |-+-+-+-+-+-+-+-|\n"; cout << " 1 2 3 4 5 6 7 8\n"; cout << endl; } // player=1: black number // player=2: white number // valid: return whether the chess can be put at this place or not bool PointValid(int board[N][N], // board 10*10 int player, pair<int, int> point) { int opponent = 3 - player; vector<pair<int, int>> mydirection; mydirection = {{-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}}; for (int i = 0; i < 8; i++) { bool lock = false; int px = point.first; int py = point.second; for (;;) { px = px + mydirection[i].first; py = py + mydirection[i].second; if (board[px][py] == -1) break; else if (board[px][py] == 0) break; else if (board[px][py] == opponent) { lock = true; continue; } else if (board[px][py] == player) { if (lock == true) return true; else break; } } } return false; } vector<pair<int, int>> BoardPointValid(int board[N][N], int player) { vector<pair<int, int>> ans; for (int i = 1; i < N - 1; i++) { for (int j = 1; j < N - 1; j++) { pair<int, int> point(i, j); if (board[i][j] == 0) { if (PointValid(board, player, point) == true) { ans.push_back(point); } else { continue; } } } } return ans; } void BoardCopy(int boardA[N][N], int boardB[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { boardA[i][j] = boardB[i][j]; } } } void show_ValidPoint(vector<pair<int, int>> ValidPoint) { cout << " Next point you can put: "; for (int i = 0; i < ValidPoint.size(); i++) { cout << "(" << ValidPoint[i].first << "," << ValidPoint[i].second << ")" << " "; } cout << endl; } bool PlayReversi(int MBoard[N][N], int player, pair<int, int> point, vector<pair<int, int>> ValidPoint) { bool ValidLock = false; for (int i = 0; i < ValidPoint.size(); i++) { if (point == ValidPoint[i]) ValidLock = true; else continue; } if (ValidLock == false) return false; // invalid int px = point.first; int py = point.second; MBoard[px][py] = player; int opponent = 3 - player; vector<pair<int, int>> mydirection = { pair<int, int>(-1, 1), pair<int, int>(0, 1), pair<int, int>(1, 1), pair<int, int>(1, 0), pair<int, int>(1, -1), pair<int, int>(0, -1), pair<int, int>(-1, -1), pair<int, int>(-1, 0), }; for (int i = 0; i < 8; i++) { bool lock = false; int px = point.first; int py = point.second; for (int in = 0;; in++) { px = px + mydirection[i].first; py = py + mydirection[i].second; if (MBoard[px][py] == -1) break; else if (MBoard[px][py] == 0) break; else if (MBoard[px][py] == opponent) { lock = true; continue; } else if (MBoard[px][py] == player) { if (lock == true) { int ppx = point.first; int ppy = point.second; for (int j = 0; j < in; j++) { ppx = ppx + mydirection[i].first; ppy = ppy + mydirection[i].second; MBoard[ppx][ppy] = player; } break; } else break; } } } return true; } int main() { if (freopen("Chess.txt", "w", stdout) == NULL) { cout << "fail to read file" << endl; return 1; } srand(time(NULL)); int MainBoard[N][N]; int ModeBlackWhite = 0; int GP0_win = 0; // computer win int GP1_win = 0; // student win int tie = 0; ModeBlackWhite = rand() % 2; // random first // if(ModeBlackWhite==0){ // cout << "GP1 First" << endl; // } // else{ // cout << "GP0 First" << endl; // } for (int game = 0; game < 3; ++game) { InitialBoard(MainBoard); cout << "GAME: " << game << endl; if (ModeBlackWhite == 0) cout << "Student: x" << endl << "Computer: o" << endl; else cout << "Student: o" << endl << "Computer: x" << endl; for (int i = 1, k = 0; k < 2; i = i % 2 + 1) { // cout << "i = " << i << ", mode = " << ModeBlackWhite << endl; int CounterpartBoard[N][N]; BoardCopy(CounterpartBoard, MainBoard); BoardShow(MainBoard); vector<pair<int, int>> ValidPoint; ValidPoint = BoardPointValid(CounterpartBoard, i); if (i == 1) cout << " (x black)" << endl; else if (i == 2) cout << " (o white)" << endl; show_ValidPoint(ValidPoint); if (ValidPoint.size() == 0) { k++; } else { k = 0; pair<int, int> point; // if(ModeBlackWhite==0) // { // if(i==1) // point=HAND(SECOND)(CounterpartBoard,i,ValidPoint); // else // point=HAND(FIRST)(CounterpartBoard,3-i,ValidPoint); // } // else // { // if(i==1) // point=HAND(FIRST)(CounterpartBoard,3-i,ValidPoint); // else // point=HAND(SECOND)(CounterpartBoard,i,ValidPoint); // } if ((ModeBlackWhite + i) != 2) { cout << " (Student): "; point = HAND(SECOND)(CounterpartBoard, i, ValidPoint); } else { cout << " (Computer): "; point = HAND(FIRST)(CounterpartBoard, i, ValidPoint); } bool boolplay = PlayReversi(MainBoard, i, point, ValidPoint); int px = point.first; int py = point.second; if (i == 1) cout << " x"; else cout << " o"; cout << "(" << px << "," << py << ")"; if (boolplay == false) { cout << " Error!"; break; } } cout << endl; } int black_num = 0; int white_num = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (MainBoard[i][j] == 1) black_num++; if (MainBoard[i][j] == 2) white_num++; } } if (ModeBlackWhite == 0) { if (black_num > white_num) GP1_win++; else if (black_num < white_num) GP0_win++; else tie++; } else { if (black_num > white_num) GP0_win++; else if (black_num < white_num) GP1_win++; else tie++; } cout << "black num: " << black_num << " white num: " << white_num << endl; // if(black_num > white_num) // cout << "1" << endl; // else if(black_num < white_num) // cout << "0" << endl; // else // cout << "2" << endl; // system("pause"); ModeBlackWhite = !ModeBlackWhite; } if (GP1_win > GP0_win) { cout << "Student Win" << endl; // cout<<"1"<<endl; } else if (GP1_win < GP0_win) { cout << "Computer Win" << endl; // cout<<"0"<<endl; } else { cout << "Tie" << endl; // cout<<"2"<<endl; } return 0; }
[ "61a5t0@gmail.com" ]
61a5t0@gmail.com
8fc2ceb1c7ed539051e8c79edd9ee9c677de972c
bbadb0f47158d4b85ae4b97694823c8aab93d50e
/apps/c/CloverLeaf_3D/Tiled/update_halo_kernel5_minus_2_back_seq_kernel.cpp
837c0638e1f2c0d160131927b9ae0f8687092b45
[]
no_license
yshoraka/OPS
197d8191dbedc625f3669b511a8b4eadf7a365c4
708c0c78157ef8c711fc6118e782f8e5339b9080
refs/heads/master
2020-12-24T12:39:49.585629
2016-11-02T09:50:54
2016-11-02T09:50:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,839
cpp
// // auto-generated by ops.py // #define OPS_ACC0(x, y, z) \ (n_x * 1 + n_y * xdim0_update_halo_kernel5_minus_2_back * 1 + \ n_z * xdim0_update_halo_kernel5_minus_2_back * \ ydim0_update_halo_kernel5_minus_2_back * 1 + \ x + xdim0_update_halo_kernel5_minus_2_back * (y) + \ xdim0_update_halo_kernel5_minus_2_back * \ ydim0_update_halo_kernel5_minus_2_back * (z)) #define OPS_ACC1(x, y, z) \ (n_x * 1 + n_y * xdim1_update_halo_kernel5_minus_2_back * 1 + \ n_z * xdim1_update_halo_kernel5_minus_2_back * \ ydim1_update_halo_kernel5_minus_2_back * 1 + \ x + xdim1_update_halo_kernel5_minus_2_back * (y) + \ xdim1_update_halo_kernel5_minus_2_back * \ ydim1_update_halo_kernel5_minus_2_back * (z)) // user function // host stub function void ops_par_loop_update_halo_kernel5_minus_2_back_execute( ops_kernel_descriptor *desc) { int dim = desc->dim; int *range = desc->range; ops_arg arg0 = desc->args[0]; ops_arg arg1 = desc->args[1]; ops_arg arg2 = desc->args[2]; // Timing double t1, t2, c1, c2; ops_arg args[3] = {arg0, arg1, arg2}; #ifdef CHECKPOINTING if (!ops_checkpointing_before(args, 3, range, 138)) return; #endif if (OPS_diags > 1) { ops_timing_realloc(138, "update_halo_kernel5_minus_2_back"); OPS_kernels[138].count++; ops_timers_core(&c2, &t2); } // compute locally allocated range for the sub-block int start[3]; int end[3]; for (int n = 0; n < 3; n++) { start[n] = range[2 * n]; end[n] = range[2 * n + 1]; } #ifdef OPS_DEBUG ops_register_args(args, "update_halo_kernel5_minus_2_back"); #endif // set up initial pointers and exchange halos if necessary int base0 = args[0].dat->base_offset; double *__restrict__ vol_flux_z = (double *)(args[0].data + base0); int base1 = args[1].dat->base_offset; double *__restrict__ mass_flux_z = (double *)(args[1].data + base1); const int *__restrict__ fields = (int *)args[2].data; // initialize global variable with the dimension of dats int xdim0_update_halo_kernel5_minus_2_back = args[0].dat->size[0]; int ydim0_update_halo_kernel5_minus_2_back = args[0].dat->size[1]; int xdim1_update_halo_kernel5_minus_2_back = args[1].dat->size[0]; int ydim1_update_halo_kernel5_minus_2_back = args[1].dat->size[1]; // Halo Exchanges ops_H_D_exchanges_host(args, 3); ops_halo_exchanges(args, 3, range); ops_H_D_exchanges_host(args, 3); if (OPS_diags > 1) { ops_timers_core(&c1, &t1); OPS_kernels[138].mpi_time += t1 - t2; } #pragma omp parallel for collapse(2) for (int n_z = start[2]; n_z < end[2]; n_z++) { for (int n_y = start[1]; n_y < end[1]; n_y++) { #ifdef intel #pragma omp simd #else #pragma simd #endif for (int n_x = start[0]; n_x < end[0]; n_x++) { if (fields[FIELD_VOL_FLUX_Z] == 1) vol_flux_z[OPS_ACC0(0, 0, 0)] = -vol_flux_z[OPS_ACC0(0, 0, 2)]; if (fields[FIELD_MASS_FLUX_Z] == 1) mass_flux_z[OPS_ACC1(0, 0, 0)] = -mass_flux_z[OPS_ACC1(0, 0, 2)]; } } } if (OPS_diags > 1) { ops_timers_core(&c2, &t2); OPS_kernels[138].time += t2 - t1; } ops_set_dirtybit_host(args, 3); ops_set_halo_dirtybit3(&args[0], range); ops_set_halo_dirtybit3(&args[1], range); if (OPS_diags > 1) { // Update kernel record ops_timers_core(&c1, &t1); OPS_kernels[138].mpi_time += t1 - t2; OPS_kernels[138].transfer += ops_compute_transfer(dim, start, end, &arg0); OPS_kernels[138].transfer += ops_compute_transfer(dim, start, end, &arg1); } } #undef OPS_ACC0 #undef OPS_ACC1 void ops_par_loop_update_halo_kernel5_minus_2_back(char const *name, ops_block block, int dim, int *range, ops_arg arg0, ops_arg arg1, ops_arg arg2) { ops_kernel_descriptor *desc = (ops_kernel_descriptor *)malloc(sizeof(ops_kernel_descriptor)); desc->name = name; desc->block = block; desc->dim = dim; desc->index = 138; #ifdef OPS_MPI sub_block_list sb = OPS_sub_block_list[block->index]; if (!sb->owned) return; for (int n = 0; n < 3; n++) { desc->range[2 * n] = sb->decomp_disp[n]; desc->range[2 * n + 1] = sb->decomp_disp[n] + sb->decomp_size[n]; if (desc->range[2 * n] >= range[2 * n]) { desc->range[2 * n] = 0; } else { desc->range[2 * n] = range[2 * n] - desc->range[2 * n]; } if (sb->id_m[n] == MPI_PROC_NULL && range[2 * n] < 0) desc->range[2 * n] = range[2 * n]; if (desc->range[2 * n + 1] >= range[2 * n + 1]) { desc->range[2 * n + 1] = range[2 * n + 1] - sb->decomp_disp[n]; } else { desc->range[2 * n + 1] = sb->decomp_size[n]; } if (sb->id_p[n] == MPI_PROC_NULL && (range[2 * n + 1] > sb->decomp_disp[n] + sb->decomp_size[n])) desc->range[2 * n + 1] += (range[2 * n + 1] - sb->decomp_disp[n] - sb->decomp_size[n]); } #else // OPS_MPI for (int i = 0; i < 6; i++) { desc->range[i] = range[i]; } #endif // OPS_MPI desc->nargs = 3; desc->args = (ops_arg *)malloc(3 * sizeof(ops_arg)); desc->args[0] = arg0; desc->args[1] = arg1; desc->args[2] = arg2; char *tmp = (char *)malloc(NUM_FIELDS * sizeof(int)); memcpy(tmp, arg2.data, NUM_FIELDS * sizeof(int)); desc->args[2].data = tmp; desc->function = ops_par_loop_update_halo_kernel5_minus_2_back_execute; ops_enqueue_kernel(desc); }
[ "mudalige@octon.arc.ox.ac.uk" ]
mudalige@octon.arc.ox.ac.uk
a20b0bda4822ab4f0a75f475e07c23f3fe8c5c09
5318b60b7185251023d5658fa4a5742a4d508051
/UltrasonicSensor/SerialDistance/SerialDistance.ino
c73c89791e3c95fc056c34529db4fc8971854fd7
[]
no_license
TechStuffBoy/ArduinoDev
ccede08da30ab55ef8c83f5acf8fb3caed3aa893
f76509d16bf831dadc751eb348cb06e30911a8da
refs/heads/master
2020-03-29T21:23:22.207583
2018-11-15T12:20:16
2018-11-15T12:20:16
150,363,936
0
0
null
null
null
null
UTF-8
C++
false
false
671
ino
#include<SoftwareSerial.h> SoftwareSerial mySerial(10, 11); // RX, TX int incomingByte = 0; // for incoming serial data String data=""; int i=0; byte incoming = 0; void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps mySerial.begin(9600); } void loop() { //46 to 57 ascii if (mySerial.available()) { incoming = mySerial.read(); if(incoming == 13 ) { //Serial.println(); Serial.print("Data :"); Serial.println(data); data = ""; } else { //Serial.print((char)incoming); data += (char)incoming; } } }
[ "nandhu03.m@gmail.com" ]
nandhu03.m@gmail.com
5031c21cc93267405ece331fb832eb7a8b56b615
c24a5cdd5584748a70454736cb73df0704f51e06
/Arduino/unity_whisperer/02_demo_scene.ino
3d809dc20354522b0c785f0b27683f0847da1daf
[]
no_license
OMeyer973/zos
b7b046ed0c38cb2dabc381eb2ee9656759de83a0
4c05b6f386efe45dd497c14fedda88d95a53bfed
refs/heads/master
2020-09-23T05:41:46.610696
2020-01-07T18:05:48
2020-01-07T18:05:48
225,418,296
0
1
null
null
null
null
UTF-8
C++
false
false
1,815
ino
// --------------------------------------------------------------------- // DEMO SCENE // --------------------------------------------------------------------- //declaring the class class DemoScene { public: // initialise global values for demo scene void init() { for(int i=0; i<4; i++) { lianaFront[i] = -1; lianaBack[i] = -1; sensorStates[i] = 0; // optional } } // - - - - - - - - - - - - - - - - - - - - - - - // start an animation on a liana for the Demo scene // has no effect if an animation is allready running // on the given liana void beginLianaAnimationOnCommand(String str) { //Serial.print("begin liana "); //Serial.println(str); if(serialCommunication.getCommand(str) == 'L') { int liana = serialCommunication.getLiana(str); if (0 <= liana && liana < 4) { lianaFront[liana] ++; // moving the lianaFront from -1 to 0 triggers // the animation cycle in updateLianas_D } } } // - - - - - - - - - - - - - - - - - - - - - - - // goes one step forward in the liana animation // scene D : chase void updateLianas() { for (int i=0; i<4; i++) { if (lianaFront[i] < stripLen && lianaFront[i] >= 0) { lianaFront[i] ++; } if (lianaFront[i] >= stripLen && lianaBack[i] <= stripLen) { lianaBack[i] ++; } if (lianaFront[i] >= stripLen && lianaBack[i] >= stripLen) { lianaBack[i] = -1; lianaFront[i] = -1; } // updating mask for animations lianaMin[i] = -1; lianaMax[i] = lianaFront[i]; } } }; //and declaring the variable which will be used in main DemoScene demoScene;
[ "olivio" ]
olivio
f0f95109381bd6498a01540d8c14d90f9796ae4a
54050becc6ea37a5eaae4c1a64cf6dc3df627a5f
/tree/Leaf.cpp
0c5435723c41241db5823c52799090a445d7c592
[]
no_license
monikahedman/tree
953cd729ee4a5ce7ff56830ce750146333bab6bc
9d8c2ddcd62c6efa4e8e567aadb9286e6aceacc1
refs/heads/master
2021-03-08T08:06:41.061927
2020-03-10T15:15:04
2020-03-10T15:15:04
246,332,858
0
0
null
null
null
null
UTF-8
C++
false
false
1,166
cpp
#include "Leaf.h" Leaf::Leaf(): m_renderer(std::make_unique<OpenGLShape>()) { } void Leaf::loadRenderer() { std::vector<GLfloat> vertex_data = {0.f, 0.f, 0.f, \ 0.f, 0.f, 1.f, \ 0.f, 0.f, \ 1.f, 0.f, 0.f, \ 0.f, 0.f, 1.f, \ 1.f, 0.f, \ 0.f, 1.f, 0.f, \ 0.f, 0.f, 1.f, \ 0.f, 1.f}; m_renderer->setAttribute(ShaderAttrib::POSITION, 3, 0, VBOAttribMarker::DATA_TYPE::FLOAT, false); m_renderer->setAttribute(ShaderAttrib::NORMAL, 3, 3 * sizeof (GLfloat), VBOAttribMarker::DATA_TYPE::FLOAT, false); m_renderer->setAttribute(ShaderAttrib::TEXCOORD0, 2, 6 * sizeof (GLfloat), VBOAttribMarker::DATA_TYPE::FLOAT, false); m_renderer->setVertexData(&vertex_data[0], 24, VBO::GEOMETRY_LAYOUT::LAYOUT_TRIANGLES, 3); m_renderer->buildVAO(); } /* * The shape's renderer draws the shape. */ void Leaf::renderShape() { m_renderer->draw(); }
[ "monika_hedman@brown.edu" ]
monika_hedman@brown.edu
33b20ac0d49b77ca720e2ee36a7d1ca349115ee8
ab2b453904fc4467c608cb3229e843d2254e18f1
/simpleChuanQi/ChuanQiGuaJi/src/game/friend.cpp
d39f0a1fcf7f35ab302dbf247cefa4de53af541e
[]
no_license
Crasader/niuniu_master
ca7ca199f044c3857d8c612180d61012cb7abd24
38892075e247172e28aa2be552988b303a5d2105
refs/heads/master
2020-07-15T16:31:05.745413
2016-02-23T12:58:33
2016-02-23T12:58:33
null
0
0
null
null
null
null
GB18030
C++
false
false
6,372
cpp
#include "friend.h" #include "roleCtrl.h" #include <algorithm> FriendInfo::FriendInfo(ROLE * role) { memset(this, 0, sizeof(*this)); if (role == NULL) { return; } strncpy(this->szName, role->roleName.c_str(), sizeof(this->szName)); this->dwID = role->dwRoleID; this->bySex = role->bySex; this->byJob = role->byJob; this->dwFightValue = role->dwFightValue; this->wLevel = role->wLevel; } OneFriendInfo::OneFriendInfo(ROLE * role) { memset(this, 0, sizeof(*this)); if (role == NULL) { return; } strncpy(this->szName, role->roleName.c_str(), sizeof(this->szName)); this->dwID = role->dwRoleID; this->bySex = role->bySex; this->byJob = role->byJob; this->dwFightValue = role->dwFightValue; this->wLevel = role->wLevel; } int FRIEND::compare(const FriendInfo &frione, const FriendInfo &fritwo)//是先按战力降序,若值相等则按等级 { if (frione.dwFightValue > fritwo.dwFightValue) { return 1; } else if(frione.dwFightValue == fritwo.dwFightValue) { if( frione.wLevel > fritwo.wLevel ) return 1; else return 0; } else { return 0; } } void FRIEND::getFriendsInfo(ROLE* role, string &strData) { vector<FriendInfo> vevFriendInfos; for (size_t i=0; i < role->vecFriends.size(); i++) { ROLE* frinendRole = RoleMgr::getMe().getRoleByID( role->vecFriends[i] ); if (frinendRole == NULL) { continue; } FriendInfo friInfo(frinendRole); vevFriendInfos.push_back(friInfo); //S_APPEND_NBYTES( strData, (char*)&friInfo, sizeof(friInfo) ); } FriendInfo friInfoMe(role); vevFriendInfos.push_back(friInfoMe); sort(vevFriendInfos.begin(), vevFriendInfos.end(),compare); for (size_t i=0; i < vevFriendInfos.size(); i++) { //logwm("get vevFriendInfos[%d].dwID = %d",i,vevFriendInfos[i].dwID); S_APPEND_NBYTES( strData, (char*)&vevFriendInfos[i], sizeof(FriendInfo) ); } } void FRIEND::addFriend(ROLE* role, string &strData, DWORD id) { BYTE byCode; if (role->vecFriends.size() >= MAX_FRIEND_NUM) { byCode = FRIEND_FULL; S_APPEND_BYTE(strData, byCode); return; } if (role->dwRoleID == id) { byCode = FRIEND_YOURSELF; S_APPEND_BYTE(strData, byCode); return; } vector<DWORD>::iterator itdword = find(role->vecFriends.begin(), role->vecFriends.end(), id); if (itdword != role->vecFriends.end()) { byCode = FRIEND_ALREADY; S_APPEND_BYTE(strData, byCode); return; } ROLE* frinendRole = RoleMgr::getMe().getRoleByID( id ); if (frinendRole == NULL) { byCode = FRIEND_NO_EXISTS; S_APPEND_BYTE(strData, byCode); return; } //logwm("add id = %d",id); byCode = FRIEND_SUCCESS; S_APPEND_BYTE(strData, byCode); role->vecFriends.push_back(id); } void FRIEND::delFriend(ROLE* role, string &strData, DWORD id) { vector<DWORD>::iterator it = find(role->vecFriends.begin(), role->vecFriends.end(), id); if (it != role->vecFriends.end()) { role->vecFriends.erase(it); } //logwm("del id = %d",id); } void FRIEND::searchFriend(ROLE* role, string &strData, string name) { BYTE byCode = FRIEND_SUCCESS; ROLE* frinendRole = RoleMgr::getMe().getRoleByName( name ); if (frinendRole == NULL) { byCode = FRIEND_NO_EXISTS; S_APPEND_BYTE(strData, byCode); return; } //vector<DWORD>::iterator itdword = find(role->vecFriends.begin(), role->vecFriends.end(), frinendRole->dwRoleID); //if (itdword != role->vecFriends.end()) //{ // byCode = FRIEND_ALREADY; // S_APPEND_BYTE(strData, byCode); //} //else //{ // byCode = FRIEND_NEW; // S_APPEND_BYTE(strData, byCode); //} S_APPEND_BYTE(strData, byCode); FriendInfo friendInfo(frinendRole); S_APPEND_SZ( strData, (char*)&friendInfo, sizeof(FriendInfo) ); //logwm("search fid = %d",frinendRole->dwRoleID); } void FRIEND::dianZhan(ROLE* role, string &strData, DWORD id) { BYTE byCode = FRIEND_SUCCESS; ROLE* frinendRole = RoleMgr::getMe().getRoleByID( id ); if (frinendRole == NULL) { byCode = FRIEND_NO_EXISTS; S_APPEND_BYTE(strData, byCode); return; } if (role->vecDianZhanIDs.size() >= DIANZHAN_NUM) { byCode = ENOUGH_YIDIAN; S_APPEND_BYTE(strData, byCode); return; } for (auto tempid : role->vecDianZhanIDs) { if (tempid == id) { byCode = FRIEND_YIDIAN; S_APPEND_BYTE(strData, byCode); return; } } role->vecDianZhanIDs.push_back(id); S_APPEND_BYTE(strData, byCode); } void FRIEND::recommondFriends(ROLE* role, string &strData) { //return; vector<DWORD> recommondIDs; RoleMgr::getMe().getRecommondIDs( role, recommondIDs ); for (size_t i=0; i < recommondIDs.size(); i++) { ROLE* frinendRole = RoleMgr::getMe().getRoleByID( recommondIDs[i] ); if (frinendRole == NULL) { continue; } FriendInfo friInfo(frinendRole); S_APPEND_NBYTES( strData, (char*)&friInfo, sizeof(FriendInfo) ); //logwm("recommond friInfo[%d].dwID = %d",i,friInfo.dwID); } //logwm("role.dwID = %d",role->dwRoleID); } int FRIEND::dealFriends(ROLE *role, unsigned char * data, size_t dataLen ,WORD cmd) { //logwm("\n cmd:%x",cmd); if (role == NULL) { return 0; } if (cmd == S_GET_FRIENDS) { string strData; FRIEND::getFriendsInfo(role, strData); PROTOCAL::sendClient( role->client, PROTOCAL::cmdPacket(S_GET_FRIENDS, strData) ); } if (cmd == S_ADD_FRIEND) { DWORD id; if ( !BASE::parseDWORD( data, dataLen, id) ) return -1; string strData; FRIEND::addFriend(role, strData, id); PROTOCAL::sendClient( role->client, PROTOCAL::cmdPacket(S_ADD_FRIEND, strData) ); } if (cmd == S_DEL_FRIEND) { DWORD id; if ( !BASE::parseDWORD( data, dataLen, id) ) return -1; string strData; FRIEND::delFriend(role, strData, id); PROTOCAL::sendClient( role->client, PROTOCAL::cmdPacket(S_DEL_FRIEND, strData) ); } if (cmd == S_SEARCH_FRIEND) { string roleName; if ( !BASE::parseBSTR( data, dataLen, roleName) ) return -1; string strData; FRIEND::searchFriend(role, strData, roleName); PROTOCAL::sendClient( role->client, PROTOCAL::cmdPacket(S_SEARCH_FRIEND, strData) ); } if (cmd == S_RECOMMOND_FRIENDS) { string strData; FRIEND::recommondFriends(role, strData); PROTOCAL::sendClient( role->client, PROTOCAL::cmdPacket(S_RECOMMOND_FRIENDS, strData) ); } if (cmd == S_DIANZAN) { DWORD id; if ( !BASE::parseDWORD( data, dataLen, id) ) return -1; string strData; FRIEND::dianZhan(role, strData, id); PROTOCAL::sendClient( role->client, PROTOCAL::cmdPacket(S_DIANZAN, strData) ); } return 0; }
[ "617179715@qq.com" ]
617179715@qq.com
11f3b512ff273b81d4f79259c1609e68c7f9b586
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_hunk_1539.cpp
2e852164fdb58fe5d79423b714c4c959c0ad29b6
[]
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
493
cpp
rv = apr_file_mktemp(&dobj->hfd, dobj->tempfile, APR_CREATE | APR_WRITE | APR_BINARY | APR_BUFFERED | APR_EXCL, r->pool); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_WARNING, rv, r->server, "disk_cache: could not create temp file %s", dobj->tempfile); return rv; } disk_info.format = DISK_FORMAT_VERSION; disk_info.date = info->date; disk_info.expire = info->expire;
[ "993273596@qq.com" ]
993273596@qq.com
2d29318f14081edd2adb8617bf58cff1ead48411
d7896f4dc83445c792fd5123472adc6569460340
/HttpLib/FormDataHandler.h
5bd5985c17e21b93fc80ef8116fe704009ac6065
[ "Unlicense" ]
permissive
mayimchen/local-file-server
b45f7bfd5f2db63c73a25c217357ce431e6ed795
801343b772f010ab21e215fa7258fa4be524b640
refs/heads/main
2023-03-22T01:55:19.968056
2021-03-16T14:46:07
2021-03-16T14:46:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
338
h
#pragma once #include <string> namespace net { class UploadHandler; class FormDataHandler { public: virtual void addDataPair(const std::string& name, const std::string& value) = 0; virtual std::unique_ptr<UploadHandler> createUploadHandler(const std::string& id, const std::string& fname) = 0; }; }
[ "56758042+tcjohnson123@users.noreply.github.com" ]
56758042+tcjohnson123@users.noreply.github.com
eb2cc2affbdd28a1ff4a61002247323a10084e3e
ae55d33d245ca8b1ca82ee191507a86742cd8851
/lib/core/configreader.cpp
ac674c5654c5c8ded3de488f2d74611713c52737
[]
no_license
wjossowski/lazyfarmer-client
2464f2d05f384c3c099803e849c1919e94c7290f
31aa99f6ef9a5bfbf17d26c513790c5167c58906
refs/heads/master
2021-10-20T07:19:20.722225
2019-02-26T11:21:28
2019-02-26T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,805
cpp
/** ** This file is part of the LazyFarmer project. ** Copyright 2018 Wojciech Ossowski <w.j.ossowski@gmail.com>. ** ** 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 3 of the ** License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU 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, see <http://www.gnu.org/licenses/>. **/ #include "configreader.h" #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QJsonDocument> #include <QtCore/QVariantList> #include <QDebug> using namespace Core; using namespace Core::Data; ResourceInfo::ResourceInfo(const QString &url, const QVariantList eraseAt, int baseSize) : url(url) , baseSize(baseSize) { for (auto ommiter : eraseAt) { spritesToOmmit.append(ommiter.toInt()); } } bool ConfigReader::loadConfig(const QByteArray &contents) { const auto json = QJsonDocument::fromJson(contents).toVariant(); if (!json.isValid()) { return false; } const auto configObject = json.toMap(); const auto imageUrls = configObject["urls-images"].toMap(); for (auto iterator = imageUrls.cbegin(); iterator != imageUrls.cend(); iterator++) { const QVariantMap resource = iterator.value().toMap(); const int size = resource.value("size").toInt(); const QString url = resource.value("url").toString(); const QVariantList eraseAt = resource.value("erase-at").toList(); m_resourceInfos.insert(iterator.key(), ResourceInfo::Ptr::create(url, eraseAt, size)); } m_availableDomains = configObject["available-domains"].toStringList(); const auto buildingTypeInfo = configObject["building-config"].toMap(); for (auto iterator = buildingTypeInfo.cbegin(); iterator != buildingTypeInfo.cend(); iterator++) { const auto storedBuildingType = iterator.key(); const auto buildingTypeIds = iterator.value().toList(); BuildingType mappedBuildingType = BuildingHelper::fromString(storedBuildingType); if (!BuildingHelper::isBuildingValid(mappedBuildingType)) { continue; } for (auto id : buildingTypeIds) { m_buildingTypes.insert(id.toInt(), mappedBuildingType); } } return true; } bool ConfigReader::hasDownloadedResources() { if (m_resourceInfos.isEmpty()) return false; auto found = std::find_if (m_resourceInfos.cbegin(), m_resourceInfos.cend(), [] (const ResourceInfo::Ptr &iterator) { return iterator->icons.isEmpty(); }); return found == m_resourceInfos.cend(); } QUrl ConfigReader::urlAt(const QString &key) { return m_resourceInfos.value(key, ResourceInfo::Ptr::create())->url; } QPixmap ConfigReader::pixmapAt(const QString &key, int id) { const auto icons = m_resourceInfos.value(key, ResourceInfo::Ptr::create())->icons; return (id > 0 && icons.size() >= id) ? icons.at(id - 1) : QPixmap(1, 1); } void ConfigReader::storeResource(const QString &key, const QByteArray &data) { auto info = m_resourceInfos.find(key); if (info == m_resourceInfos.end()) { return; } auto resource = *info; const auto image = QImage::fromData(data); int baseSize = resource->baseSize; int totalWidth = image.width(); int totalHeight = image.height(); if (totalWidth % baseSize != 0) { return; } else if (totalHeight % baseSize != 0) { return; } QList<QPixmap> icons; int index = 0; // used for filtering unnecessary pictures for (int h = 0; h < totalHeight; h += baseSize) { for (int w = 0; w < totalWidth; w += baseSize) { if (!resource->spritesToOmmit.contains(index)) { icons.append(QPixmap::fromImage(image.copy(w, h, baseSize, baseSize))); } index++; } } #ifdef DEBUG_MODE for (int i = 0; i < icons.size(); i++) { const auto icon = icons.at(i); QDir temp("/tmp"); temp.mkdir(key); icon.save(QString("/tmp/%1/%1_%2.png").arg(key).arg(i+1)); } #endif resource->icons = std::move(icons); } ConfigReader &ConfigReader::instance() { static ConfigReader reader; return reader; } ConfigReader::ConfigReader() { qDebug() << "Creating config reader"; }
[ "zavafoj@gmail.com" ]
zavafoj@gmail.com
1716a055477be8589c424aa4bd8d5c2a2fc7b392
ee1f37311a4edc3d5ffc5554b8d7520fb20c6975
/tryout.cpp
10feeb81dbc545aa182ad6893181be2661c6e6ba
[]
no_license
smartestbeaverever/hh
dd670475b61a4984c60cbeee8838d92c0b94bf87
e773e5fb6b921d8892e36527207840316530148d
refs/heads/master
2020-12-09T09:00:57.317983
2020-01-11T19:10:24
2020-01-11T19:10:24
233,257,018
0
0
null
null
null
null
UTF-8
C++
false
false
32
cpp
kjfdfkjfhjhuhgjhndssdhjsdgcvsgc
[ "haley@Haleys-MacBook-Pro.local" ]
haley@Haleys-MacBook-Pro.local
78e7dd1ff2ee529be09f33ecc156b64fd9654bd7
a27ad1911c68050448e79e7d2d6a38beb416c239
/hybris/tests/test_glesv2.cpp
7e9e9e77cb4dde1da40f7bbb7368f3c5b87bdde4
[ "Apache-2.0" ]
permissive
vakkov/libhybris
dd5015f98920a5bba9a5107082b0f1c59512a653
fb03e26648720711d38b506a7b89d04fbcf150b4
refs/heads/master
2021-09-10T02:37:14.961919
2018-03-20T18:44:21
2018-03-20T18:50:18
126,066,604
0
0
null
null
null
null
UTF-8
C++
false
false
12,028
cpp
/* * Copyright (c) 2012 Carsten Munk <carsten.munk@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <EGL/egl.h> #include <GLES2/gl2.h> #include <assert.h> #include <stdio.h> #include <math.h> #include <stddef.h> #include <stdlib.h> #include <hwcomposer_window.h> #include <hardware/hardware.h> #include <hardware/hwcomposer.h> #include <malloc.h> #include <sync/sync.h> const char vertex_src [] = " \ attribute vec4 position; \ varying mediump vec2 pos; \ uniform vec4 offset; \ \ void main() \ { \ gl_Position = position + offset; \ pos = position.xy; \ } \ "; const char fragment_src [] = " \ varying mediump vec2 pos; \ uniform mediump float phase; \ \ void main() \ { \ gl_FragColor = vec4( 1., 0.9, 0.7, 1.0 ) * \ cos( 30.*sqrt(pos.x*pos.x + 1.5*pos.y*pos.y) \ + atan(pos.y,pos.x) - phase ); \ } \ "; GLuint load_shader(const char *shader_source, GLenum type) { GLuint shader = glCreateShader(type); glShaderSource(shader, 1, &shader_source, NULL); glCompileShader(shader); return shader; } GLfloat norm_x = 0.0; GLfloat norm_y = 0.0; GLfloat offset_x = 0.0; GLfloat offset_y = 0.0; GLfloat p1_pos_x = 0.0; GLfloat p1_pos_y = 0.0; GLint phase_loc; GLint offset_loc; GLint position_loc; const float vertexArray[] = { 0.0, 1.0, 0.0, -1., 0.0, 0.0, 0.0, -1.0, 0.0, 1., 0.0, 0.0, 0.0, 1., 0.0 }; class HWComposer : public HWComposerNativeWindow { private: hwc_layer_1_t *fblayer; hwc_composer_device_1_t *hwcdevice; hwc_display_contents_1_t **mlist; protected: void present(HWComposerNativeWindowBuffer *buffer); public: HWComposer(unsigned int width, unsigned int height, unsigned int format, hwc_composer_device_1_t *device, hwc_display_contents_1_t **mList, hwc_layer_1_t *layer); void set(); }; HWComposer::HWComposer(unsigned int width, unsigned int height, unsigned int format, hwc_composer_device_1_t *device, hwc_display_contents_1_t **mList, hwc_layer_1_t *layer) : HWComposerNativeWindow(width, height, format) { fblayer = layer; hwcdevice = device; mlist = mList; } void HWComposer::present(HWComposerNativeWindowBuffer *buffer) { int oldretire = mlist[0]->retireFenceFd; mlist[0]->retireFenceFd = -1; fblayer->handle = buffer->handle; fblayer->acquireFenceFd = getFenceBufferFd(buffer); fblayer->releaseFenceFd = -1; int err = hwcdevice->prepare(hwcdevice, HWC_NUM_DISPLAY_TYPES, mlist); assert(err == 0); err = hwcdevice->set(hwcdevice, HWC_NUM_DISPLAY_TYPES, mlist); // in android surfaceflinger ignores the return value as not all display types may be supported setFenceBufferFd(buffer, fblayer->releaseFenceFd); if (oldretire != -1) { sync_wait(oldretire, -1); close(oldretire); } } inline static uint32_t interpreted_version(hw_device_t *hwc_device) { uint32_t version = hwc_device->version; if ((version & 0xffff0000) == 0) { // Assume header version is always 1 uint32_t header_version = 1; // Legacy version encoding version = (version << 16) | header_version; } return version; } int main(int argc, char **argv) { EGLDisplay display; EGLConfig ecfg; EGLint num_config; EGLint attr[] = { // some attributes to set up our egl-interface EGL_BUFFER_SIZE, 32, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE }; EGLSurface surface; EGLint ctxattr[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLContext context; EGLBoolean rv; int err; hw_module_t const* module = NULL; err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module); assert(err == 0); framebuffer_device_t* fbDev = NULL; framebuffer_open(module, &fbDev); hw_module_t *hwcModule = 0; hwc_composer_device_1_t *hwcDevicePtr = 0; err = hw_get_module(HWC_HARDWARE_MODULE_ID, (const hw_module_t **) &hwcModule); assert(err == 0); err = hwc_open_1(hwcModule, &hwcDevicePtr); assert(err == 0); hw_device_t *hwcDevice = &hwcDevicePtr->common; uint32_t hwc_version = interpreted_version(hwcDevice); #ifdef HWC_DEVICE_API_VERSION_1_4 if (hwc_version == HWC_DEVICE_API_VERSION_1_4) { hwcDevicePtr->setPowerMode(hwcDevicePtr, 0, HWC_POWER_MODE_NORMAL); } else #endif #ifdef HWC_DEVICE_API_VERSION_1_5 if (hwc_version == HWC_DEVICE_API_VERSION_1_5) { hwcDevicePtr->setPowerMode(hwcDevicePtr, 0, HWC_POWER_MODE_NORMAL); } else #endif hwcDevicePtr->blank(hwcDevicePtr, 0, 0); uint32_t configs[5]; size_t numConfigs = 5; err = hwcDevicePtr->getDisplayConfigs(hwcDevicePtr, 0, configs, &numConfigs); assert (err == 0); int32_t attr_values[2]; uint32_t attributes[] = { HWC_DISPLAY_WIDTH, HWC_DISPLAY_HEIGHT, HWC_DISPLAY_NO_ATTRIBUTE }; hwcDevicePtr->getDisplayAttributes(hwcDevicePtr, 0, configs[0], attributes, attr_values); printf("width: %i height: %i\n", attr_values[0], attr_values[1]); size_t size = sizeof(hwc_display_contents_1_t) + 2 * sizeof(hwc_layer_1_t); hwc_display_contents_1_t *list = (hwc_display_contents_1_t *) malloc(size); hwc_display_contents_1_t **mList = (hwc_display_contents_1_t **) malloc(HWC_NUM_DISPLAY_TYPES * sizeof(hwc_display_contents_1_t *)); const hwc_rect_t r = { 0, 0, attr_values[0], attr_values[1] }; int counter = 0; for (; counter < HWC_NUM_DISPLAY_TYPES; counter++) mList[counter] = list; hwc_layer_1_t *layer = &list->hwLayers[0]; memset(layer, 0, sizeof(hwc_layer_1_t)); layer->compositionType = HWC_FRAMEBUFFER; layer->hints = 0; layer->flags = 0; layer->handle = 0; layer->transform = 0; layer->blending = HWC_BLENDING_NONE; #ifdef HWC_DEVICE_API_VERSION_1_3 layer->sourceCropf.top = 0.0f; layer->sourceCropf.left = 0.0f; layer->sourceCropf.bottom = (float) attr_values[1]; layer->sourceCropf.right = (float) attr_values[0]; #else layer->sourceCrop = r; #endif layer->displayFrame = r; layer->visibleRegionScreen.numRects = 1; layer->visibleRegionScreen.rects = &layer->displayFrame; layer->acquireFenceFd = -1; layer->releaseFenceFd = -1; #if (ANDROID_VERSION_MAJOR >= 4) && (ANDROID_VERSION_MINOR >= 3) || (ANDROID_VERSION_MAJOR >= 5) // We've observed that qualcomm chipsets enters into compositionType == 6 // (HWC_BLIT), an undocumented composition type which gives us rendering // glitches and warnings in logcat. By setting the planarAlpha to non- // opaque, we attempt to force the HWC into using HWC_FRAMEBUFFER for this // layer so the HWC_FRAMEBUFFER_TARGET layer actually gets used. bool tryToForceGLES = getenv("QPA_HWC_FORCE_GLES") != NULL; layer->planeAlpha = tryToForceGLES ? 1 : 255; #endif #ifdef HWC_DEVICE_API_VERSION_1_5 layer->surfaceDamage.numRects = 0; #endif layer = &list->hwLayers[1]; memset(layer, 0, sizeof(hwc_layer_1_t)); layer->compositionType = HWC_FRAMEBUFFER_TARGET; layer->hints = 0; layer->flags = 0; layer->handle = 0; layer->transform = 0; layer->blending = HWC_BLENDING_NONE; #ifdef HWC_DEVICE_API_VERSION_1_3 layer->sourceCropf.top = 0.0f; layer->sourceCropf.left = 0.0f; layer->sourceCropf.bottom = (float) attr_values[1]; layer->sourceCropf.right = (float) attr_values[0]; #else layer->sourceCrop = r; #endif layer->displayFrame = r; layer->visibleRegionScreen.numRects = 1; layer->visibleRegionScreen.rects = &layer->displayFrame; layer->acquireFenceFd = -1; layer->releaseFenceFd = -1; #if (ANDROID_VERSION_MAJOR >= 4) && (ANDROID_VERSION_MINOR >= 3) || (ANDROID_VERSION_MAJOR >= 5) layer->planeAlpha = 0xff; #endif #ifdef HWC_DEVICE_API_VERSION_1_5 layer->surfaceDamage.numRects = 0; #endif list->retireFenceFd = -1; list->flags = HWC_GEOMETRY_CHANGED; list->numHwLayers = 2; HWComposer *win = new HWComposer(attr_values[0], attr_values[1], HAL_PIXEL_FORMAT_RGBA_8888, hwcDevicePtr, mList, &list->hwLayers[1]); display = eglGetDisplay(NULL); assert(eglGetError() == EGL_SUCCESS); assert(display != EGL_NO_DISPLAY); rv = eglInitialize(display, 0, 0); assert(eglGetError() == EGL_SUCCESS); assert(rv == EGL_TRUE); eglChooseConfig((EGLDisplay) display, attr, &ecfg, 1, &num_config); assert(eglGetError() == EGL_SUCCESS); assert(rv == EGL_TRUE); //surface = eglCreateWindowSurface((EGLDisplay) display, ecfg, (EGLNativeWindowType) ((struct ANativeWindow*) win), NULL); surface = eglCreateWindowSurface((EGLDisplay) display, ecfg, (EGLNativeWindowType) static_cast<ANativeWindow *> (win), NULL); assert(eglGetError() == EGL_SUCCESS); assert(surface != EGL_NO_SURFACE); context = eglCreateContext((EGLDisplay) display, ecfg, EGL_NO_CONTEXT, ctxattr); assert(eglGetError() == EGL_SUCCESS); assert(context != EGL_NO_CONTEXT); assert(eglMakeCurrent((EGLDisplay) display, surface, surface, context) == EGL_TRUE); const char *version = (const char *)glGetString(GL_VERSION); assert(version); printf("%s\n",version); GLuint vertexShader = load_shader ( vertex_src , GL_VERTEX_SHADER ); // load vertex shader GLuint fragmentShader = load_shader ( fragment_src , GL_FRAGMENT_SHADER ); // load fragment shader GLuint shaderProgram = glCreateProgram (); // create program object glAttachShader ( shaderProgram, vertexShader ); // and attach both... glAttachShader ( shaderProgram, fragmentShader ); // ... shaders to it glLinkProgram ( shaderProgram ); // link the program glUseProgram ( shaderProgram ); // and select it for usage //// now get the locations (kind of handle) of the shaders variables position_loc = glGetAttribLocation ( shaderProgram , "position" ); phase_loc = glGetUniformLocation ( shaderProgram , "phase" ); offset_loc = glGetUniformLocation ( shaderProgram , "offset" ); if ( position_loc < 0 || phase_loc < 0 || offset_loc < 0 ) { return 1; } //glViewport ( 0 , 0 , 800, 600); // commented out so it uses the initial window dimensions glClearColor ( 1. , 1. , 1. , 1.); // background color float phase = 0; int frames = -1; if(argc == 2) { frames = atoi(argv[1]); } if(frames < 0) { frames = 30 * 60; } int i; for (i = 0; i < frames; ++i) { if(i % 60 == 0) printf("frame:%i\n", i); glClear(GL_COLOR_BUFFER_BIT); glUniform1f ( phase_loc , phase ); // write the value of phase to the shaders phase phase = fmodf ( phase + 0.5f , 2.f * 3.141f ); // and update the local variable glUniform4f ( offset_loc , offset_x , offset_y , 0.0 , 0.0 ); glVertexAttribPointer ( position_loc, 3, GL_FLOAT, GL_FALSE, 0, vertexArray ); glEnableVertexAttribArray ( position_loc ); glDrawArrays ( GL_TRIANGLE_STRIP, 0, 5 ); eglSwapBuffers ( (EGLDisplay) display, surface ); // get the rendered buffer to the screen } printf("stop\n"); #if 0 (*egldestroycontext)((EGLDisplay) display, context); printf("destroyed context\n"); (*egldestroysurface)((EGLDisplay) display, surface); printf("destroyed surface\n"); (*eglterminate)((EGLDisplay) display); printf("terminated\n"); android_dlclose(baz); #endif } // vim:ts=4:sw=4:noexpandtab
[ "vakko_vakko@abv.bg" ]
vakko_vakko@abv.bg
cb01ccef118cdbecfddcb5e825950cd3a9f64bdb
a13e24b39fab4f5d9bc57d0bd5eb536c38a5eef1
/source/Core/Castor3D/Gui/Controls/CtrlLayoutControl.cpp
5e5c937c44520c76888563e59f22d00de323aaf0
[ "MIT" ]
permissive
DragonJoker/Castor3D
2bbd0eeba403a37570bfc959d58a6c8a01429c60
32a2e4bc5c6ea0d0a27f3c58f8edb74fbc7e59ce
refs/heads/development
2023-09-04T15:46:36.438955
2023-08-30T05:37:14
2023-08-30T12:34:39
34,847,313
424
18
MIT
2023-09-14T11:10:10
2015-04-30T09:53:00
C++
UTF-8
C++
false
false
3,416
cpp
#include "Castor3D/Gui/Controls/CtrlLayoutControl.hpp" #include "Castor3D/Engine.hpp" #include "Castor3D/Cache/OverlayCache.hpp" #include "Castor3D/Gui/ControlsManager.hpp" #include "Castor3D/Gui/Layout/Layout.hpp" #include "Castor3D/Gui/Theme/StyleScrollable.hpp" #include "Castor3D/Material/Material.hpp" #include "Castor3D/Material/Pass/Pass.hpp" #include "Castor3D/Material/Texture/TextureUnit.hpp" #include "Castor3D/Overlay/Overlay.hpp" #include "Castor3D/Overlay/BorderPanelOverlay.hpp" #include "Castor3D/Overlay/TextOverlay.hpp" #include "Castor3D/Scene/Scene.hpp" CU_ImplementSmartPtr( castor3d, LayoutControl ) namespace castor3d { //************************************************************************************************ bool isLayoutControl( ControlType type ) { return type == ControlType::ePanel; } bool isLayoutControl( Control const & control ) { return isLayoutControl( control.getType() ); } //************************************************************************************************ LayoutControl::LayoutControl( ControlType type , SceneRPtr scene , castor::String const & name , ControlStyleRPtr controlStyle , ScrollableStyleRPtr scrollableStyle , ControlRPtr parent , castor::Position const & position , castor::Size const & size , ControlFlagType flags , bool visible ) : Control{ type , scene , name , controlStyle , parent , position , size , flags , visible } , ScrollableCtrl{ *this , scrollableStyle } { doUpdateFlags(); } void LayoutControl::setLayout( LayoutUPtr layout ) { m_layout = std::move( layout ); } void LayoutControl::doCreate() { createScrollBars(); } void LayoutControl::doDestroy() { destroyScrollBars(); } void LayoutControl::doAddChild( ControlRPtr control ) { registerControl( *control ); } void LayoutControl::doRemoveChild( ControlRPtr control ) { unregisterControl( *control ); } void LayoutControl::doUpdateStyle() { updateScrollBarsStyle(); } void LayoutControl::doUpdateFlags() { checkScrollBarFlags(); } void LayoutControl::doUpdateZIndex( uint32_t & index ) { updateScrollZIndex( index ); } void LayoutControl::doAdjustZIndex( uint32_t offset ) { adjustScrollZIndex( offset ); } castor::Point4ui LayoutControl::doUpdateClientRect( castor::Point4ui const & clientRect ) { return doSubUpdateClientRect( updateScrollableClientRect( clientRect ) ); } void LayoutControl::doSetBorderSize( castor::Point4ui const & value ) { if ( m_layout ) { m_layout->markDirty(); } doSubSetBorderSize( value ); updateScrollBars(); } void LayoutControl::doSetPosition( castor::Position const & value ) { if ( m_layout ) { m_layout->markDirty(); } doSubSetPosition( value ); updateScrollBars(); } void LayoutControl::doSetSize( castor::Size const & value ) { if ( m_layout ) { m_layout->markDirty(); } doSubSetSize( value ); updateScrollBars(); } void LayoutControl::doSetCaption( castor::U32String const & caption ) { if ( m_layout ) { m_layout->markDirty(); } doSubSetCaption( caption ); } void LayoutControl::doSetVisible( bool value ) { if ( m_layout ) { m_layout->markDirty(); } doSubSetVisible( value ); setScrollBarsVisible( value ); } //************************************************************************************************ }
[ "DragonJoker@users.noreply.github.com" ]
DragonJoker@users.noreply.github.com
a5e35da3689e91326606507d91ce364aed73eaca
e217eaf05d0dab8dd339032b6c58636841aa8815
/IfcRoad/src/OpenInfraPlatform/IfcRoad/entity/include/IfcProduct.h
ab2830a3e95836eccde0aa209b19e8ede4fbf3f4
[]
no_license
bigdoods/OpenInfraPlatform
f7785ebe4cb46e24d7f636e1b4110679d78a4303
0266e86a9f25f2ea9ec837d8d340d31a58a83c8e
refs/heads/master
2021-01-21T03:41:20.124443
2016-01-26T23:20:21
2016-01-26T23:20:21
57,377,206
0
1
null
2016-04-29T10:38:19
2016-04-29T10:38:19
null
UTF-8
C++
false
false
3,244
h
/*! \verbatim * \copyright Copyright (c) 2015 Julian Amann. All rights reserved. * \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann) * \brief This file is part of the OpenInfraPlatform. * \endverbatim */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "OpenInfraPlatform/IfcRoad/model/shared_ptr.h" #include "OpenInfraPlatform/IfcRoad/model/IfcRoadObject.h" #include "IfcProductSelect.h" #include "IfcObject.h" namespace OpenInfraPlatform { namespace IfcRoad { class IfcObjectPlacement; class IfcProductRepresentation; class IfcRelAssignsToProduct; //ENTITY class IfcProduct : public IfcProductSelect, public IfcObject { public: IfcProduct(); IfcProduct( int id ); ~IfcProduct(); // method setEntity takes over all attributes from another instance of the class virtual void setEntity( shared_ptr<IfcRoadEntity> other ); virtual void getStepLine( std::stringstream& stream ) const; virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; virtual void readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<IfcRoadEntity> >& map ); virtual void setInverseCounterparts( shared_ptr<IfcRoadEntity> ptr_self ); virtual void unlinkSelf(); virtual const char* classname() const { return "IfcProduct"; } // IfcRoot ----------------------------------------------------------- // attributes: // shared_ptr<IfcGloballyUniqueId> m_GlobalId; // shared_ptr<IfcOwnerHistory> m_OwnerHistory; //optional // shared_ptr<IfcLabel> m_Name; //optional // shared_ptr<IfcText> m_Description; //optional // IfcObjectDefinition ----------------------------------------------------------- // inverse attributes: // std::vector<weak_ptr<IfcRelAssigns> > m_HasAssignments_inverse; // std::vector<weak_ptr<IfcRelNests> > m_Nests_inverse; // std::vector<weak_ptr<IfcRelNests> > m_IsNestedBy_inverse; // std::vector<weak_ptr<IfcRelDeclares> > m_HasContext_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_IsDecomposedBy_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_Decomposes_inverse; // std::vector<weak_ptr<IfcRelAssociates> > m_HasAssociations_inverse; // IfcObject ----------------------------------------------------------- // attributes: // shared_ptr<IfcLabel> m_ObjectType; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelDefinesByObject> > m_IsDeclaredBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByObject> > m_Declares_inverse; // std::vector<weak_ptr<IfcRelDefinesByType> > m_IsTypedBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByProperties> > m_IsDefinedBy_inverse; // IfcProduct ----------------------------------------------------------- // attributes: shared_ptr<IfcObjectPlacement> m_ObjectPlacement; //optional shared_ptr<IfcProductRepresentation> m_Representation; //optional // inverse attributes: std::vector<weak_ptr<IfcRelAssignsToProduct> > m_ReferencedBy_inverse; }; } // end namespace IfcRoad } // end namespace OpenInfraPlatform
[ "planung.cms.bv@tum.de" ]
planung.cms.bv@tum.de
461fbc6769d7ddc744cd40f6c6c1adf7657188d7
d29b14abf9c69ecb5d64cea45259e0c91d4b9ad9
/examples/C&C++/USB2CANFD/USB2XXX_CANFD_Test/source/USB2XXX_CANFD_Test.cpp
e155ecbe59a343fdfb6888d5b65439648486bcd9
[]
no_license
jerry750134428/USB2XXX_Example
f6a8e295d4706787e533d650e41074b0835c1518
406d7f95b3841856a6c941eb1b45103e707d3497
refs/heads/master
2022-04-09T14:59:51.137576
2020-03-16T02:16:58
2020-03-16T02:16:58
null
0
0
null
null
null
null
GB18030
C++
false
false
4,724
cpp
/* ****************************************************************************** * @file : USB2XXX_CANFD_Test.cpp * @Copyright: TOOMOSS * @Revision : ver 1.0 * @Date : 2019/12/19 9:33 * @brief : USB2XXX CANFD test demo ****************************************************************************** * @attention * * Copyright 2009-2019, TOOMOSS * http://www.toomoss.com/ * All Rights Reserved * ****************************************************************************** */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "usb_device.h" #include "usb2canfd.h" int main(int argc, const char* argv[]) { DEVICE_INFO DevInfo; int DevHandle[10]; int CANIndex = 0;//CAN通道号 bool state; int ret; //扫描查找设备 ret = USB_ScanDevice(DevHandle); if(ret <= 0){ printf("No device connected!\n"); return 0; } //打开设备 state = USB_OpenDevice(DevHandle[0]); if(!state){ printf("Open device error!\n"); return 0; } char FunctionStr[256]={0}; //获取固件信息 state = DEV_GetDeviceInfo(DevHandle[0],&DevInfo,FunctionStr); if(!state){ printf("Get device infomation error!\n"); return 0; }else{ printf("Firmware Info:\n"); printf("Firmware Name:%s\n",DevInfo.FirmwareName); printf("Firmware Build Date:%s\n",DevInfo.BuildDate); printf("Firmware Version:v%d.%d.%d\n",(DevInfo.FirmwareVersion>>24)&0xFF,(DevInfo.FirmwareVersion>>16)&0xFF,DevInfo.FirmwareVersion&0xFFFF); printf("Hardware Version:v%d.%d.%d\n",(DevInfo.HardwareVersion>>24)&0xFF,(DevInfo.HardwareVersion>>16)&0xFF,DevInfo.HardwareVersion&0xFFFF); printf("Firmware Functions:%s\n",FunctionStr); } //初始化配置CAN CANFD_INIT_CONFIG CANFDConfig; CANFDConfig.Mode = 1; //0-正常模式,1-自发自收模式 CANFDConfig.RetrySend = 1; //使能自动重传 CANFDConfig.ISOCRCEnable = 1;//使能ISOCRC CANFDConfig.ResEnable = 1; //使能内部终端电阻(若总线上没有终端电阻,则必须使能终端电阻才能正常传输数据) //波特率参数可以用TCANLINPro软件里面的波特率计算工具计算 //仲裁段波特率参数,波特率=40M/NBT_BRP*(1+NBT_SEG1+NBT_SEG2) CANFDConfig.NBT_BRP = 1; CANFDConfig.NBT_SEG1 = 63; CANFDConfig.NBT_SEG2 = 16; CANFDConfig.NBT_SJW = 16; //数据域波特率参数,波特率=40M/DBT_BRP*(1+DBT_SEG1+DBT_SEG2) CANFDConfig.DBT_BRP = 1; CANFDConfig.DBT_SEG1 = 15; CANFDConfig.DBT_SEG2 = 4; CANFDConfig.DBT_SJW = 4; ret = CANFD_Init(DevHandle[0],CANIndex,&CANFDConfig); if(ret != CANFD_SUCCESS){ printf("CANFD Init Error!\n"); return 0; }else{ printf("CANFD Init Success!\n"); } //启动CAN数据接收 ret = CANFD_StartGetMsg(DevHandle[0], CANIndex); if (ret != CANFD_SUCCESS){ printf("Start receive CANFD failed!\n"); return 0; }else{ printf("Start receive CANFD Success!\n"); } //发送CAN数据 CANFD_MSG CanMsg[5]; for (int i = 0; i < 5; i++){ CanMsg[i].Flags = 0;//bit[0]-BRS,bit[1]-ESI,bit[2]-FDF,bit[6..5]-Channel,bit[7]-RXD CanMsg[i].DLC = 8; CanMsg[i].ID = i; for (int j = 0; j < CanMsg[i].DLC; j++){ CanMsg[i].Data[j] = j; } } int SendedMsgNum = CANFD_SendMsg(DevHandle[0], CANIndex, CanMsg, 5); if (SendedMsgNum >= 0){ printf("Success send frames:%d\n", SendedMsgNum); }else{ printf("Send CAN data failed!\n"); return 0; } //接收数据 //延时 #ifndef OS_UNIX Sleep(50); #else usleep(50*1000); #endif //读取接收数据缓冲中的数据 CANFD_MSG CanMsgBuffer[1024]; int GetMsgNum = CANFD_GetMsg(DevHandle[0], CANIndex, CanMsgBuffer, 1024); if (GetMsgNum > 0){ for (int i = 0; i < GetMsgNum; i++){ printf("CanMsg[%d].ID = 0x%08X\n", i, CanMsgBuffer[i].ID & CANFD_MSG_FLAG_ID_MASK); printf("CanMsg[%d].TimeStamp = %d\n", i, CanMsgBuffer[i].TimeStamp); printf("CanMsg[%d].Data = ", i); for (int j = 0; j < CanMsgBuffer[i].DLC; j++) { printf("0x%02X ", CanMsgBuffer[i].Data[j]); } printf("\n"); } }else if (GetMsgNum < 0){ printf("Get CAN data error!\n"); } //停止接收数据 ret = CANFD_StopGetMsg(DevHandle[0], CANIndex); if (ret != CANFD_SUCCESS){ printf("Stop receive CANFD failed!\n"); return 0; }else{ printf("Stop receive CANFD Success!\n"); } return 0; }
[ "wdluo@embed-net.com" ]
wdluo@embed-net.com
d432bea486df91a007dd231b13360b34a26e195f
65601b728b1f46344c1e7ea3aa96a03cdf26a4cb
/Src/MainLib/GLIntercept.cpp
550726b6b6b302413f6155aa51c41f36b8d263e6
[]
no_license
c-song/GLCapture
dc74f5c9c45cd0595a46bfd5659493a939f0529a
f010f647d0706483154f662394727d3067c70309
refs/heads/master
2021-01-10T12:56:25.841982
2015-09-28T13:39:50
2015-09-28T13:39:50
43,301,611
0
0
null
null
null
null
UTF-8
C++
false
false
5,441
cpp
/*============================================================================= GLIntercept - OpenGL intercept/debugging tool Copyright (C) 2004 Damian Trebilco Licensed under the MIT license - See Docs\license.txt for details. =============================================================================*/ // GLIntercept.cpp : Defines the entry point for the DLL application. #include "GLIntercept.h" #include "GLDriver.h" #include <string> #include <FileUtils.h> #include <time.h> #include <stdlib.h> using namespace std; //The main error log ErrorLog *gliLog=NULL; //The main OpenGL driver GLDriver glDriver QUICK_CONSTRUCT; //The path to the dll location (including trailing seperator) string dllPath QUICK_CONSTRUCT; #ifdef GLI_BUILD_WINDOWS #include <direct.h> #include <crtdbg.h> //The handle of the DLL HANDLE dllHandle = NULL; /////////////////////////////////////////////////////////////////////////////// // BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { //Assign the DLL handle for later usage dllHandle = hModule; //Enable memory debugging //_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE ); //_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR ); _CrtSetDbgFlag ( _CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF /*|_CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF*/); //Get the module's file name static char dllName[1024]; GetModuleFileName((HMODULE)hModule,dllName,1023); //Get the path dllPath = dllName; string::size_type pathEnd = dllPath.rfind(FileUtils::dirSeparator); if(pathEnd != string::npos) { //Remove the file name part dllPath.erase(pathEnd+1,dllPath.size()-pathEnd-1); } else { //If we could not even find a back slash, just set the path as the current directory if(_getcwd( dllName, 1024 ) != NULL) { //Assign the path and a trailing seperator dllPath = dllName; dllPath = dllPath + FileUtils::dirSeparator; } else { dllPath = ""; } } //Create the log gliLog = new ErrorLog((dllPath + "glCaptureLog.txt").c_str()); //Get the current time time_t aclock; time( &aclock ); //Convert it struct tm *newtime = localtime( &aclock ); //Set the error log to always flush gliLog->SetLogFlush(true); //gliLog->LogError("GL Intercept Log. Version : %s Compile Date: %s Run on: %s",__GLI_BUILD_VER_STR,__DATE__,asctime(newtime)); //gliLog->LogError("==================================================="); gliLog->SetDebuggerLogEnabled(true); break; } //NOTE: GLIntercept does not currently support multiple threads case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: { break; } } return TRUE; } #endif //GLI_BUILD_WINDOWS #ifdef GLI_BUILD_LINUX //Support for getting the .so path #include <prefix.h> /////////////////////////////////////////////////////////////////////////////// // void init(void) __attribute__ ((constructor(102))); void init(void) { //Check for the GLIntercept environment variable first const char * envPathTest = getenv("GLI_CONFIG_PATH"); if(envPathTest != NULL) { dllPath = envPathTest; //If the last character is not a directory seperator, add one if(dllPath.length() > 0 && dllPath[dllPath.length()-1] != FileUtils::dirSeparator) { dllPath = dllPath + FileUtils::dirSeparator; } } //Assign the path to the .so if(dllPath.length() == 0) { const char * libPathTest = SELFPATH; if(libPathTest != NULL) { dllPath = libPathTest; //Strip the .so name string::size_type pathEnd = dllPath.rfind(FileUtils::dirSeparator); if(pathEnd != string::npos) { //Remove the file name part dllPath.erase(pathEnd+1,dllPath.size()-pathEnd-1); } else { dllPath = ""; } } } //Check if a valid path was assigned if(dllPath.length() == 0) { //Get the path from the current working directory static char dllName[1024]; if(getcwd(dllName, 1023) != NULL) { dllPath = dllName; dllPath = dllPath + FileUtils::dirSeparator; } else { ErrorLog::LogDebuggerMessage("Unable to retrieve startup path"); dllPath = ""; } } //Create the log gliLog = new ErrorLog((dllPath + "gliLog.txt").c_str()); //Get the current time time_t aclock; time( &aclock ); //Convert it struct tm *newtime = localtime( &aclock ); //Set the error log to always flush gliLog->SetLogFlush(true); gliLog->LogError("GL Intercept Log. Version : %s Compile Date: %s Run on: %s",__GLI_BUILD_VER_STR,__DATE__,asctime(newtime)); gliLog->LogError("==================================================="); gliLog->SetDebuggerLogEnabled(true); } /////////////////////////////////////////////////////////////////////////////// // void fini(void) __attribute__ ((destructor)); void fini(void) { //Note: The Logger is shutdown in the driver } #endif //GLI_BUILD_LINUX
[ "csong@zjsu.edu.cn" ]
csong@zjsu.edu.cn
cce1ed9d4250320dff81569420faa5edd3d33408
634120df190b6262fccf699ac02538360fd9012d
/Develop/Server/GameServer/main/GRelationChecker.h
7bdde7ca026c0feea46386b2d87e6fe5310c7af2
[]
no_license
ktj007/Raiderz_Public
c906830cca5c644be384e68da205ee8abeb31369
a71421614ef5711740d154c961cbb3ba2a03f266
refs/heads/master
2021-06-08T03:37:10.065320
2016-11-28T07:50:57
2016-11-28T07:50:57
74,959,309
6
4
null
2016-11-28T09:53:49
2016-11-28T09:53:49
null
UTF-8
C++
false
false
532
h
#pragma once class GEntityActor; class GRelationSelector; class GParty; class GRelationChecker { public: GRelationChecker(); ~GRelationChecker(); bool IsAll(GEntityActor* pReqActor, GEntityActor* pTarActor); bool IsAlly(GEntityActor* pReqActor, GEntityActor* pTarActor); bool IsEnemy(GEntityActor* pReqActor, GEntityActor* pTarActor); bool IsParty(GEntityActor* pReqActor, GEntityActor* pTarActor); bool IsAllyDead(GEntityActor* pReqActor, GEntityActor* pTarActor); private: GRelationSelector* m_pRelationSelector; };
[ "espause0703@gmail.com" ]
espause0703@gmail.com
49804c9f37f75c5b2019c94a7e6c23be2880bf5d
7973d7cf1e3ea2f0743b046ec78b1ed07d13920e
/C++/iLab/Minggu 1/Activity/celsius.cpp
a9e31f72c723e6640b45ca434ab385cbcae85e4c
[ "MIT" ]
permissive
rafipriatna/Belajar-Bahasa-Pemrograman
35e7010af30c2e9a076f1d7ba8155cf0e07eb9d5
e6e1f00526897a9d37065d70f9509cb4db5a61f8
refs/heads/master
2021-07-15T09:30:20.677657
2020-11-10T14:36:40
2020-11-10T14:36:40
223,768,692
1
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
// Program untuk mengonversi Fahrenheit ke Celsius #include <iostream> using namespace std; int main(){ // Deklarasi variabel float fahren, celsius; // Input cout << "Nilai derajat Fahrenheit: "; cin >> fahren; // Hitung celsius = (fahren - 32) * 5 / 9; // Output cout << "Identik dengan " << celsius << " derajat Celsius" << endl; return 0; }
[ "stormrider136@gmail.com" ]
stormrider136@gmail.com
c0e6e1bd3ff1777d41f0354e0ab5dcf55911dd37
e65e6b345e98633cccc501ad0d6df9918b2aa25e
/POJ/2236.cpp
4388b09fb9e2b6aefaedfa2ce6c296c920529a59
[]
no_license
wcysai/CodeLibrary
6eb99df0232066cf06a9267bdcc39dc07f5aab29
6517cef736f1799b77646fe04fb280c9503d7238
refs/heads/master
2023-08-10T08:31:58.057363
2023-07-29T11:56:38
2023-07-29T11:56:38
134,228,833
5
2
null
null
null
null
UTF-8
C++
false
false
1,144
cpp
#include<cstdio> #include<cstring> #include<algorithm> #include<cstdlib> #include<cmath> using namespace std; int p[1002]; int find(int x) {return p[x]==x ? x : p[x]=find(p[x]);} bool same(int x,int y) {return find(x)==find(y);} int abv(int x){return max(x,-x);} void unite(int x,int y) { int u = find(x); int v = find(y); if(u != v) p[u] = v; } int main() { int n,d,m,k; char c; int coord[1002][2],jud[1002]; memset(jud,0,sizeof(jud)); scanf("%d %d",&n,&d); for(int i=1;i<=n;i++) p[i] = i; for(int i=1;i<=n;i++) scanf("%d %d",&coord[i][0],&coord[i][1]); while(scanf("%c %d",&c,&m)!=(EOF)) { if(c=='O') { jud[m]=1; for(int i=1;i<=n;i++) { if(i!=m&&jud[i]&&(coord[m][0]-coord[i][0])*(coord[m][0]-coord[i][0])+(coord[m][1]-coord[i][1])*(coord[m][1]-coord[i][1])<=d*d) { unite(m,i); } } } if(c=='S') { scanf("%d",&k); if(same(m,k)) printf("SUCCESS\n"); else printf("FAIL\n"); } } return 0; }
[ "wcysai@foxmail.com" ]
wcysai@foxmail.com
4aefe03314274d8295aa458b102e808a42dc72fa
dde4e9c0ab539884c63e56ef46984c6482b91070
/Camera.h
f6f02d1c18ce83f543d84a025bf6739f11482c29
[]
no_license
awthomps/CSE168HW2
0ecc7b5773e43828e04707aacc80e2d3087be143
4c084c5b6a3e90d8b1388837e05315beb8c1ad21
refs/heads/master
2016-09-11T09:36:41.429756
2014-04-25T18:33:13
2014-04-25T18:33:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
779
h
#pragma once #ifndef CSE168_CAMERA_H #define CSE168_CAMERA_H #include "Matrix34.h" #include "Vector3.h" #include "Bitmap.h" #include "Scene.h" #include "Material.h" #include "StopWatch.h" #include <iostream> class Camera { public: Camera(); ~Camera(); void SetFOV(float f); void SetAspect(float a); void SetResolution(int x, int y); void LookAt(Vector3 &pos, Vector3 &target, Vector3 &up); void LookAt(Vector3 &pos, Vector3 &target); void Render(Scene &s); void SaveBitmap(char *filename); void RenderPixel(int x, int y, Scene &s); private: int XRes, YRes; Matrix34 WorldMatrix; float VerticalFOV; float Aspect; Bitmap BMP; Vector3 topLeft, topRight, bottomLeft, bottomRight, right, up; float rightDelta; float downDelta; StopWatch watch; }; #endif
[ "killosquirrel@gmail.com" ]
killosquirrel@gmail.com
15b4562bc7e785c7e87ac91fa8fefee1564667dd
b85ac3eeea556ba27a91f28e48e44b3e6ba486d4
/edgeextract/findoutercontour.cpp
65c0ae8bb4a7d487de4ab747c83298c0e7dfff33
[]
no_license
FelixWang95/weiyiwork
8e2a0a2875e48f000d48f845d1a0714ca80207d0
180c5797f21f64f47de122568fba31ab6ec586dd
refs/heads/master
2023-04-03T07:54:50.565228
2021-04-13T08:55:29
2021-04-13T08:55:29
355,809,337
0
0
null
null
null
null
UTF-8
C++
false
false
13,519
cpp
#include "findoutercontour.h" FindOuterContour::FindOuterContour() { th1 = CV_PI/180*5, th2=CV_PI/180*85,th3=CV_PI/180*90*(-1); NN=2; Point2f tm; tm.x=0,tm.y=0; srcTri[0]=tm,srcTri[1]=tm,srcTri[2]=tm,srcTri[3]=tm; dstTri[0]=tm,dstTri[1]=tm,dstTri[2]=tm,dstTri[3]=tm; } void FindOuterContour::ScanPoints(cv::Mat imgGray,std::vector<float> &source_x, std::vector<float> &source_y) { for(float th=th1;th<=th2;th+=(CV_PI/180)) { for(int i=0;i<imgGray.cols;i++) { int j=0; j=int(tan(th)*float(i)); if(j>=(imgGray.rows-1))break; if(imgGray.at<uchar>(j,i)>200&&imgGray.at<uchar>(j,i)!=100) { source_x.push_back(float(i)); source_y.push_back(float(j)); imgGray.at<uchar>(j,i)=100; break; } } } for(float th=th1;th<=th2;th+=(CV_PI/180)) { for(int i=imgGray.cols-1;i>=0;i--) { int j=0; j=int(tan(th)*abs(float(i-(imgGray.cols-1)))); if(j>=(imgGray.rows-1))break; if(imgGray.at<uchar>(j,i)>200&&imgGray.at<uchar>(j,i)!=100) { source_x.push_back(float(i)); source_y.push_back(float(j)); imgGray.at<uchar>(j,i)=100; break; } } } for(float th=th1;th<=th2;th+=(CV_PI/180)) { for(int i=imgGray.cols-1;i>=0;i--) { int j=0; j=imgGray.rows-int(tan(th)*abs(float(i-(imgGray.cols-1)))); if(j>=(imgGray.rows-1))break; if(imgGray.at<uchar>(j,i)>200&&imgGray.at<uchar>(j,i)!=100) { source_x.push_back(float(i)); source_y.push_back(float(j)); imgGray.at<uchar>(j,i)=100; break; } } } for(float th=th1;th<=th2;th+=(CV_PI/180)) { for(int i=0;i<imgGray.cols;i++) { int j=0; j=imgGray.rows-1-int(tan(th)*float(i)); if(j>=(imgGray.rows-1))break; if(imgGray.at<uchar>(j,i)>200&&imgGray.at<uchar>(j,i)!=100) { source_x.push_back(float(i)); source_y.push_back(float(j)); imgGray.at<uchar>(j,i)=100; break; } } } } void FindOuterContour::setNN(int nn) { NN=nn; } void FindOuterContour::PeripheralTraversa(cv::Mat srcImg,std::vector<float> &source_x, std::vector<float> &source_y) { cv::Mat imgGray,imgGray01,imgGray02; cv::Mat image01,image02,image03,image04,image05,image06; medianBlur(srcImg,srcImg,5); resize(srcImg, image01, Size(srcImg.cols / NN, srcImg.rows / NN), (0, 0), (0, 0), INTER_LINEAR); if(image01.channels()>1) cvtColor(image01, imgGray, CV_RGB2GRAY); else imgGray=image01.clone(); threshold(imgGray, imgGray, 50, 255, CV_THRESH_BINARY); //threshold(imgGray, imgGray, 0, 255, CV_THRESH_OTSU); //ScanPoints(imgGray,source_x, source_y); image02= cv::Mat::zeros(imgGray.rows,imgGray.cols,CV_8UC1); hconcat(image02,image02,image03),hconcat(image03,image02,image03); hconcat(image02,imgGray,image04),hconcat(image04,image02,image04); hconcat(image02,image02,image05),hconcat(image05,image02,image05); vconcat(image03,image04,image06),vconcat(image06,image05,image06); imgGray01=image06.clone(); float th[6]={0}; th[0]=0,th[0]=CV_PI/180*30,th[1]=CV_PI/180*60,th[2]=CV_PI/180*90,th[3]=CV_PI/180*120,th[4]=CV_PI/180*150,th[5]= CV_PI/180; //#pragma omp parallel for //for(float th=0;th<CV_PI;th+=(CV_PI/180*30)) for(int ii=0;ii<6;ii++) { th3=th[ii]; imgGray02=cv::Mat::zeros(imgGray01.rows,imgGray01.cols,CV_8UC1); int xc=imgGray01.cols/2, yc=imgGray01.rows/2; //double Time0 = (double)cvGetTickCount(); // #pragma omp parallel for for(int i=imgGray.cols;i<imgGray.cols*2;i++) { for(int j=imgGray.rows;j<imgGray.rows*2;j++) { if(imgGray01.at<uchar>(j,i)<80)continue; else { int ix=0,jy=0; ix=xc+(i-xc)*cos(th3)-(j-yc)*sin(th3); jy=yc+(j-yc)*cos(th3)+(i-xc)*sin(th3); imgGray02.at<uchar>(jy,ix)=imgGray01.at<uchar>(j,i); } } } //Time0 = (double)cvGetTickCount() - Time0; //printf("run time0 = %gms\n", Time0 / (cvGetTickFrequency() * 1000));//ms vector<float> source_xt,source_yt; //imwrite("tt.png",imgGray02); //double Time0 = (double)cvGetTickCount(); ScanPoints(imgGray02,source_xt, source_yt); // Time0 = (double)cvGetTickCount() - Time0; // printf("run time0 = %gms\n", Time0 / (cvGetTickFrequency() * 1000));//ms for(int i=0;i<int(source_xt.size());i++) { float tx=0,ty=0; tx=xc + source_xt[i]*cos(th3) - xc*cos(th3) + source_yt[i]*sin(th3) - yc*sin(th3); ty=yc + source_yt[i]*cos(th3) - yc*cos(th3) - source_xt[i]*sin(th3) + xc*sin(th3); source_x.push_back(tx-imgGray.cols),source_y.push_back(ty-imgGray.rows); } } } // helper function: // finds a cosine of angle between vectors // from pt0->pt1 and from pt0->pt2 double FindOuterContour::angle( Point pt1, Point pt2, Point pt0 ) { double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } void FindOuterContour::PerspectiveTransformation(const cv::Mat &image,cv::Mat &dstImage) { vector<vector<Point>> squares; //vector<Point> dstTri; // Point2f srcTri[4]; // Point2f dstTri[4]; findSquares(image, squares); cv::Mat warp_mat( 3, 3, CV_32FC1 ); if(squares.size()>0) { vector<float> dis0,dis1,dis2,dis3; for(int i=0;i<4;i++) { dis0.push_back(sqrt(gsl_pow_2(squares[0][i].x-0)+gsl_pow_2(squares[0][i].y-0))); dis1.push_back(sqrt(gsl_pow_2(squares[0][i].x-image.cols)+gsl_pow_2(squares[0][i].y-0))); dis2.push_back(sqrt(gsl_pow_2(squares[0][i].x-image.cols)+gsl_pow_2(squares[0][i].y-image.rows))); dis3.push_back(sqrt(gsl_pow_2(squares[0][i].x-0)+gsl_pow_2(squares[0][i].y-image.rows))); } vector<float>::iterator minnest0 = min_element(dis0.begin(), dis0.end()); int minId0 = distance(dis0.begin(), minnest0); vector<float>::iterator minnest1 = min_element(dis1.begin(), dis1.end()); int minId1 = distance(dis1.begin(), minnest1); vector<float>::iterator minnest2 = min_element(dis2.begin(), dis2.end()); int minId2 = distance(dis2.begin(), minnest2); vector<float>::iterator minnest3 = min_element(dis3.begin(), dis3.end()); int minId3 = distance(dis3.begin(), minnest3); srcTri[0]=squares[0][minId0],srcTri[1]=squares[0][minId1],srcTri[2]=squares[0][minId2],srcTri[3]=squares[0][minId3]; dstTri[0].x =0; dstTri[0].y =0; dstTri[1].x =(int)(sqrt(gsl_pow_2((srcTri[1].x-srcTri[0].x))+gsl_pow_2((srcTri[1].y-srcTri[0].y)))); dstTri[1].y =0; dstTri[2].x =(int)(sqrt(gsl_pow_2((srcTri[1].x-srcTri[0].x))+gsl_pow_2((srcTri[1].y-srcTri[0].y)))); dstTri[2].y =(int)(sqrt(gsl_pow_2((srcTri[2].x-srcTri[1].x))+gsl_pow_2((srcTri[2].y-srcTri[1].y)))); dstTri[3].x =0; dstTri[3].y =(int)(sqrt(gsl_pow_2((srcTri[2].x-srcTri[1].x))+gsl_pow_2((srcTri[2].y-srcTri[1].y)))); dstImage=cv::Mat::zeros(int(dstTri[2].y), int(dstTri[2].x),CV_8UC1); warp_mat=getPerspectiveTransform(srcTri,dstTri); warpPerspective(image, dstImage, warp_mat, dstImage.size() ); } //imwrite("/home/qzs/DataFile/WyData/0/imag.jpg",dstImage); } void FindOuterContour::getsrcTri(vector<Point2f> &srcAns) { for(int i=0;i<4;i++) { srcAns.push_back(srcTri[i]); } } // returns sequence of squares detected on the image. // the sequence is stored in the specified memory storage void FindOuterContour::findSquares( const cv::Mat& image, vector<vector<Point> >& squares ) { squares.clear(); cv::Mat timg(image); medianBlur(image, timg, 9); cv::Mat gray0(timg.size(), CV_8U), gray; vector<vector<Point> > contours; threshold(timg, gray, 0, 255, CV_THRESH_OTSU); //Canny(gray0, gray, 5, thresh, 5); // find contours and store them all as a list findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE); vector<Point> approx; // test each contour for( size_t i = 0; i < contours.size(); i++ ) { // approximate contour with accuracy proportional // to the contour perimeter approxPolyDP(cv::Mat(contours[i]), approx, arcLength(cv::Mat(contours[i]), true)*0.02, true); // square contours should have 4 vertices after approximation // relatively large area (to filter out noisy contours) // and be convex. // Note: absolute value of an area is used because // area may be positive or negative - in accordance with the // contour orientation if( approx.size() == 4 && fabs(contourArea(cv::Mat(approx))) > 13000000 && isContourConvex(cv::Mat(approx)) ) { double maxCosine = 0; for( int j = 2; j < 5; j++ ) { // find the maximum cosine of the angle between joint edges double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1])); maxCosine = MAX(maxCosine, cosine); } // if cosines of all angles are small // (all angles are ~90 degree) then write quandrange // vertices to resultant sequence if( maxCosine < 0.3 ) squares.push_back(approx); } } if(squares.size()>1) { vector<Point> approx2=squares[0]; for(int i=0;i<int(squares.size()-1);i++) { if(fabs(contourArea(cv::Mat(approx2)))<fabs(contourArea(cv::Mat(squares[i+1])))) { approx2=squares[i+1]; } } squares[0]=approx2; } } // the function draws all the squares in the image void FindOuterContour::drawSquares( cv::Mat& image, const vector<vector<Point> >& squares ) { for( size_t i = 0; i < squares.size(); i++ ) { const Point* p = &squares[i][0]; int n = (int)squares[i].size(); //dont detect the border if (p-> x > 3 && p->y > 3) polylines(image, &p, &n, 1, true, cv::Scalar(0,255,255), 3); //imwrite("/home/qzs/DataFile/WyData/0/imag.jpg",image); } // imwrite("/home/qzs/DataFile/WyData/0/imag.jpg",image); // imshow("imgt", image); // int c = waitKey(); // if( (char)c == 27 ) // return ; } vector<cv::Point> FindOuterContour::SortContour(vector<cv::Point> contour){ cv::Point2f center(0,0); for(int i=0;i<contour.size();++i){ center.x+=contour[i].x; center.y+=contour[i].y; } center.x/=contour.size(); center.y/=contour.size(); multimap<float,cv::Point,greater<float>> sortedcontours; for(int i=0;i<contour.size();++i){ float theta=GetAngle(center, cv::Point(center.x+10,center.y), center, contour[i]); if(contour[i].y>center.y) theta=360.0-theta; pair<float,cv::Point> fp(theta,contour[i]); sortedcontours.insert(fp); } vector<cv::Point> sortcontour(contour.size()); multimap<float,cv::Point>::iterator i,iend; iend=sortedcontours.end(); int count=0; for (i=sortedcontours.begin();i!=iend;i++){ //cout<<(*i).second<< "dian "<<(*i).first<< "jiaodu"<<endl; sortcontour[count]=(*i).second; count++; } return sortcontour; } vector<cv::Point> FindOuterContour::SortContourCenter(vector<cv::Point> contour, cv::Point center){ multimap<float,cv::Point,greater<float>> sortedcontours; for(int i=0;i<contour.size();++i){ float theta=GetAngle(center, cv::Point(center.x+10,center.y), center, contour[i]); if(contour[i].y>center.y) theta=360.0-theta; pair<float,cv::Point> fp(theta,contour[i]); sortedcontours.insert(fp); } vector<cv::Point> sortcontour(contour.size()); multimap<float,cv::Point>::iterator i,iend; iend=sortedcontours.end(); int count=0; for (i=sortedcontours.begin();i!=iend;i++){ //cout<<(*i).second<< "dian "<<(*i).first<< "jiaodu"<<endl; sortcontour[count]=(*i).second; count++; } return sortcontour; } float FindOuterContour::GetAngle(cv::Point A, cv::Point B, cv::Point C, cv::Point D){ float ABx=B.x-A.x; float ABy=B.y-A.y; float CDx=D.x-C.x; float CDy=D.y-C.y; if((ABx==0&&ABy==0)||(CDx==0&&CDy==0)) return 0; float cosa=(ABx*CDx+ABy*CDy)/(sqrt(ABx*ABx+ABy*ABy)*sqrt(CDx*CDx+CDy*CDy)); if(cosa>=1) cosa=0.999999; float angle=acos(cosa)*180/PI; if(isnan(angle)) cout<<cosa<<endl; return angle; }
[ "1072955947@qq.com" ]
1072955947@qq.com
71f8ed7d887f23935ceb816ffe5baa815827bab6
245afd9f4adb8d868fa1228ac5898083e4140d4a
/Figures/MyFigure.cpp
e369b6d2bcf59beab8f6e66db81e0b6e90046c17
[]
no_license
Ars-eniy-Cheis/ProgramLanguages
3e50c5eaa7d0f2c2bcdda7651d873484c912c78e
3b79cef726a347188bb25d468b092e0c59ef6ecf
refs/heads/master
2021-01-01T11:29:51.555886
2020-12-21T16:58:16
2020-12-21T16:58:16
239,254,881
0
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
#include "MyFigure.h" MyFigure::MyFigure() { Cir = new Circle(0); Trap = new Trapezium(0, 0, 0); Par = new Parallelogram(0, 0); Tri = new Triangle(0, 0); Rect = new Rectangle(0, 0); } MyFigure::MyFigure(Circle* new_Cir, Rectangle* new_Rect, Parallelogram* new_Par, Trapezium* new_Trap, Triangle* new_Tri) { Cir = new_Cir; Trap = new_Trap; Par = new_Par; Tri = new_Tri; Rect = new_Rect; } float MyFigure::Area() { return (Cir->Area()/2) + Trap->Area() + Par->Area() + Tri->Area() + Rect->Area(); } Figure* MyFigure::Clone() { return new MyFigure(); }
[ "mr.4eis@yandex.ru" ]
mr.4eis@yandex.ru
906a34f0bc7ff8a81f90e6a223405cfb65cc3900
b8586ade568cc2a20460506ddb7a533931176b3a
/rfid/rfid.ino
29b37fd96e771507651a1f826e149ae147c1564b
[]
no_license
FelixSchmidmeir/hb-school
f8ec8cc1414ea93af7cf7573556b7c202a3f93ee
4cb21af7f56665fb7a50438f10fb324c32f9d09e
refs/heads/master
2021-02-25T20:34:23.764813
2020-03-07T10:11:15
2020-03-07T10:11:15
245,463,540
0
0
null
null
null
null
UTF-8
C++
false
false
1,605
ino
#include <SPI.h> // SPI-Bibiothek hinzufügen #include <MFRC522.h> // RFID-Bibiothek hinzufügen #define SS_PIN 10 // SDA an Pin 10 (bei MEGA anders) #define RST_PIN 9 // RST an Pin 9 (bei MEGA anders) MFRC522 mfrc522(SS_PIN, RST_PIN); // RFID-Empfänger benennen void setup() // Beginn des Setups: { Serial.begin(9600); // Serielle Verbindung starten (Monitor) SPI.begin(); // SPI-Verbindung aufbauen mfrc522.PCD_Init(); // Initialisierung des RFID-Empfängers } void loop() // Hier beginnt der Loop-Teil { if ( ! mfrc522.PICC_IsNewCardPresent()) // Wenn keine Karte in Reichweite ist... { return; // ...springt das Programm zurück vor die if-Schleife, womit sich die Abfrage wiederholt. } if ( ! mfrc522.PICC_ReadCardSerial()) // Wenn kein RFID-Sender ausgewählt wurde { return; // ...springt das Programm zurück vor die if-Schleife, womit sich die Abfrage wiederholt. } Serial.print("Die ID des RFID-TAGS lautet:"); // "Die ID des RFID-TAGS lautet:" wird auf den Serial Monitor geschrieben. for (byte i = 0; i < mfrc522.uid.size; i++) { Serial.print(mfrc522.uid.uidByte[i], HEX); // Dann wird die UID ausgelesen, die aus vier einzelnen Blöcken besteht und der Reihe nach an den Serial Monitor gesendet. Die Endung Hex bedeutet, dass die vier Blöcke der UID als HEX-Zahl (also auch mit Buchstaben) ausgegeben wird Serial.print(" "); // Der Befehl „Serial.print(" ");“ sorgt dafür, dass zwischen den einzelnen ausgelesenen Blöcken ein Leerzeichen steht. } Serial.println(); // Mit dieser Zeile wird auf dem Serial Monitor nur ein Zeilenumbruch gemacht. }
[ "felix.schmidmeir@gmx.de" ]
felix.schmidmeir@gmx.de
f1655a5955e0872d9eb3ab88be73575f8709c40c
5d8f75e6e7138a9647eb3668acabab5f7b7feb9c
/mainwindow.h
abd24505799de4c203e3b8da0da0259a1083ac47
[]
no_license
belabelabela/Qt_widgets_dragAndDrop
477d648c2569e589a7ca80959d6daa60f2c4abb8
6200bf57980f22a2f4c54286d2358cb6a37e181f
refs/heads/master
2022-11-03T22:51:37.824414
2020-06-18T14:47:57
2020-06-18T14:47:57
273,264,383
0
0
null
2020-06-18T14:46:20
2020-06-18T14:46:19
null
UTF-8
C++
false
false
385
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGlobal> #if QT_VERSION < 0x050000 #include <QtGui> #else #include <QtWidgets> #endif namespace Ui { class MainWindow; } class CThread; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
[ "demonist616@gmail.com" ]
demonist616@gmail.com
2dbf923fa5bb3109aa84d17f59d50d6a21852a92
8903737d0460227d47723f1924302cfd9f59d223
/ch04/06/main.cpp
3b603eb75a47246882290fea0929ac914015ce40
[]
no_license
sha-ou/cppPrimerPlus
9692a9a00949394b58dbe6b82256ff360251d993
44cc383c27f0e4b76e1f6b896cd76a78621fec22
refs/heads/master
2021-02-17T12:55:17.457639
2020-03-21T05:38:43
2020-03-21T05:38:43
245,098,677
0
0
null
null
null
null
UTF-8
C++
false
false
734
cpp
#include <iostream> #include <string> using namespace std; struct CandyBar { string type; float weight; int cal; }; int main(void) { struct CandyBar candys[3] = { {"type1", 1.1, 100}, {"type2", 2.2, 200}, {"type3", 3.3, 300}, }; cout << "Type: " << candys[0].type << endl; cout << "Weight: " << candys[0].weight << endl; cout << "Cal: " << candys[0].cal << endl; cout << "Type: " << candys[1].type << endl; cout << "Weight: " << candys[1].weight << endl; cout << "Cal: " << candys[1].cal << endl; cout << "Type: " << candys[2].type << endl; cout << "Weight: " << candys[2].weight << endl; cout << "Cal: " << candys[2].cal << endl; return 0; }
[ "sha-ou@outlook.com" ]
sha-ou@outlook.com
0eeea922d0acb390568242d986ccacddca764a1d
c1b03b59b3974058e3dc4e3aa7a46a7ab9cc3b29
/include/gura/Class_any.h
0cca42422ce343b746b1c66592974a4862f4ada8
[]
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
929
h
//============================================================================= // Gura class: any //============================================================================= #ifndef __GURA_CLASS_ANY_H__ #define __GURA_CLASS_ANY_H__ #include "Class.h" namespace Gura { //----------------------------------------------------------------------------- // Class_any //----------------------------------------------------------------------------- class GURA_DLLDECLARE Class_any : public ClassPrimitive { public: Class_any(Environment *pEnvOuter); virtual void DoPrepare(Environment &env); virtual bool CastFrom(Environment &env, Value &value, ULong flags); virtual SerializeFmtVer GetSerializeFmtVer() const; virtual bool Serialize(Environment &env, Stream &stream, const Value &value) const; virtual bool Deserialize(Environment &env, Stream &stream, Value &value, SerializeFmtVer serializeFmtVer) const; }; } #endif
[ "ypsitau@nifty.com" ]
ypsitau@nifty.com
21093d6bb886d9e8516266a147a79546687c1b87
6f61cc0e07f2248e759c561c1d4aa30d2a778941
/FrameWork/DeviceFont.cpp
7ad11cc149c47ff03646eae34e0aab9094be6cf0
[]
no_license
Ektoba/D3D
80eadc0cd572dbf26e2c61c2a25c6234e3448f1e
d83b68a42fe7af74bcd7df031d6ff3e38628d003
refs/heads/master
2023-05-06T17:47:33.420329
2021-05-24T09:57:52
2021-05-24T09:57:52
370,284,224
0
0
null
null
null
null
UHC
C++
false
false
2,337
cpp
#include "Include.h" g_DeviceFont dv_font; g_DeviceFont::g_DeviceFont(void) { // 폰트 리소스 추가 AddFontResourceEx("./Typo_SsangmunDongB.ttf", FR_PRIVATE, 0); } g_DeviceFont::~g_DeviceFont(void) { } bool g_DeviceFont::Create( HWND g_hWnd ) { Direct3D = Direct3DCreate9( D3D_SDK_VERSION ); ZeroMemory( &d3dpp, sizeof( d3dpp ) ); d3dpp.Windowed = TRUE; // 전체 화면 모드로 생성 d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // 가장 효율적인 SWAP 효과 d3dpp.hDeviceWindow = g_hWnd; d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; // 현재 바탕화면 모드에 맞춰 후면 버퍼를 생성 d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE ; d3dpp.BackBufferWidth = SCREEN_WITH; d3dpp.BackBufferHeight = SCREEN_HEIGHT; Direct3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &Device9 ); // 스프라이트/폰트 그리기 위해 생성. D3DXCreateSprite( Device9 , &Sprite ) ; ZeroMemory( &fdesc , sizeof(fdesc) ) ; fdesc.Height = 25 ; fdesc.Width = 12 ; fdesc.Weight = 500 ; fdesc.Italic = FALSE ; fdesc.CharSet = DEFAULT_CHARSET ; //fdesc.FaceName[LF_FACESIZE]; //strcpy( fdesc.FaceName , "돋움" ) ; strcpy( fdesc.FaceName, "타이포_쌍문동 B" ) ; D3DXCreateFontIndirect( Device9 , &fdesc , &Fonts ) ; mHWND = g_hWnd; return true; } bool g_DeviceFont::DrawString( const char* msg , int x , int y , D3DCOLOR color ) { RECT rect = { x , y , fdesc.Width*strlen(msg) , fdesc.Height } ; Sprite->Begin( D3DXSPRITE_ALPHABLEND ) ; //Fonts->DrawText(Sprite, msg, strlen(msg), &rect, DT_NOCLIP, color(원하는 칼러 전달 시)); Fonts->DrawText( Sprite , msg , strlen( msg ) , &rect , DT_NOCLIP , D3DCOLOR_XRGB(255,0,255) ) ; Sprite->End() ; return true; } bool g_DeviceFont::DrawMousePoint(HWND hWnd) { static char temp[]= "x=%3d,y=%3d"; static POINT mouse; ::GetCursorPos(&mouse); ::ScreenToClient(hWnd,&mouse); sprintf(temp, "x=%d,y=%d", mouse.x, mouse.y); RECT rect = { mouse.x , mouse.y , fdesc.Width * strlen(temp)+1 , fdesc.Height }; Sprite->Begin(D3DXSPRITE_ALPHABLEND); Fonts->DrawText(Sprite, temp, strlen(temp)+1, &rect, DT_NOCLIP, D3DCOLOR_XRGB(255, 0, 255)); Sprite->End(); return true; } HWND g_DeviceFont::GetHWND() { return mHWND; }
[ "42265781+Ektoba@users.noreply.github.com" ]
42265781+Ektoba@users.noreply.github.com
35a462d440874970d0c6ad3e1b6d0f1897022d3d
0dca74ba205f42b38c1d1a474350e57ff78352b4
/L1Trigger/L1TMuonCPPF/plugins/L1TMuonCPPFDigiProducer.cc
a5951b6d0a1e39739c3b88d1dd6685a281a981c9
[ "Apache-2.0" ]
permissive
jaimeleonh/cmssw
7fd567997a244934d6c78e9087cb2843330ebe09
b26fdc373052d67c64a1b5635399ec14525f66e8
refs/heads/AM_106X_dev
2023-04-06T14:42:57.263616
2019-08-09T09:08:29
2019-08-09T09:08:29
181,003,620
1
0
Apache-2.0
2019-04-12T12:28:16
2019-04-12T12:28:15
null
UTF-8
C++
false
false
1,430
cc
// Emulator that takes RPC hits and produces CPPFDigis to send to EMTF // Author Alejandro Segura -- Universidad de los Andes #include "L1TMuonCPPFDigiProducer.h" L1TMuonCPPFDigiProducer::L1TMuonCPPFDigiProducer(const edm::ParameterSet& iConfig) : cppf_emulator_(std::make_unique<EmulateCPPF>(iConfig, consumesCollector())) //cppf_emulator_(new EmulateCPPF(iConfig, consumesCollector())) { // produces<l1t::CPPFDigiCollection>("rpcDigi"); produces<l1t::CPPFDigiCollection>("recHit"); } L1TMuonCPPFDigiProducer::~L1TMuonCPPFDigiProducer() { } void L1TMuonCPPFDigiProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { // Create pointers to the collections which will store the cppfDigis // auto cppf_rpcDigi = std::make_unique<l1t::CPPFDigiCollection>(); auto cppf_recHit = std::make_unique<l1t::CPPFDigiCollection>(); // Main CPPF emulation process: emulates CPPF output from RPCDigi or RecHit inputs // From src/EmulateCPPF.cc // cppf_emulator_->process(iEvent, iSetup, *cppf_rpcDigi, *cppf_recHit); cppf_emulator_->process(iEvent, iSetup, *cppf_recHit); // Fill the output collections // iEvent.put(std::move(cppf_rpcDigi), "rpcDigi"); iEvent.put(std::move(cppf_recHit), "recHit"); } void L1TMuonCPPFDigiProducer::beginStream(edm::StreamID iID) { } void L1TMuonCPPFDigiProducer::endStream(){ } // Define this as a plug-in DEFINE_FWK_MODULE(L1TMuonCPPFDigiProducer);
[ "manuel.segura@cern.ch" ]
manuel.segura@cern.ch
818ef1f03400352735bf1186b2da16006c9e0d8d
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/make/new_hunk_720.cpp
34f57e81b077f910adb7f70b8f06e3ee49ef6649
[]
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
451
cpp
return o; } static char * func_flavor (char *o, char **argv, const char *funcname UNUSED) { register struct variable *v = lookup_variable (argv[0], strlen (argv[0])); if (v == 0) o = variable_buffer_output (o, "undefined", 9); else if (v->recursive) o = variable_buffer_output (o, "recursive", 9); else o = variable_buffer_output (o, "simple", 6); return o; } #ifdef VMS # define IS_PATHSEP(c) ((c) == ']') #else
[ "993273596@qq.com" ]
993273596@qq.com
ba33f17539bfb12005be97d664fecd7ae7e7dd35
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/sync/sessions/status_controller_unittest.cc
c29bc5f717ad537dcaed68475bc2b06dfda4dd3f
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
1,620
cc
// Copyright (c) 2012 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 "sync/sessions/sync_session.h" #include "sync/test/engine/test_id_factory.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { namespace sessions { class StatusControllerTest : public testing::Test { }; // This test is useful, as simple as it sounds, due to the copy-paste prone // nature of status_controller.cc (we have had bugs in the past where a set_foo // method was actually setting |bar_| instead!). TEST_F(StatusControllerTest, ReadYourWrites) { StatusController status; status.set_num_server_changes_remaining(13); EXPECT_EQ(13, status.num_server_changes_remaining()); status.set_last_download_updates_result(SYNCER_OK); EXPECT_EQ(SYNCER_OK, status.model_neutral_state().last_download_updates_result); status.set_commit_result(SYNC_AUTH_ERROR); EXPECT_EQ(SYNC_AUTH_ERROR, status.model_neutral_state().commit_result); for (int i = 0; i < 14; i++) status.increment_num_successful_commits(); EXPECT_EQ(14, status.model_neutral_state().num_successful_commits); } // Test TotalNumConflictingItems TEST_F(StatusControllerTest, TotalNumConflictingItems) { StatusController status; EXPECT_EQ(0, status.TotalNumConflictingItems()); status.increment_num_server_conflicts(); status.increment_num_hierarchy_conflicts_by(3); status.increment_num_encryption_conflicts_by(2); EXPECT_EQ(6, status.TotalNumConflictingItems()); } } // namespace sessions } // namespace syncer
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
9f1875f95d998225ede96800a79c8f3100f815d6
f0318890dbefa572108457093e08e415d1be2cff
/C_CPP/104_1_NCUE_IM_CPP_II/1007/1007.cpp
dd89e75e3c6ea0c73a734e2803ef4f518c686d3a
[ "MIT" ]
permissive
jason40418/practices
75ddf008c981546ae9a9b492a3aa0cf9fd2ee804
898d77bc574696b2e7d0407c3b2bfaa66e80f29f
refs/heads/master
2023-02-20T20:03:13.314161
2021-01-24T08:49:51
2021-01-24T08:57:54
291,240,159
0
0
MIT
2021-01-24T08:41:29
2020-08-29T09:23:25
C++
UTF-8
C++
false
false
7,759
cpp
/** * @file 1007.cpp * * @brief * 1. Make a simple calculator. * 2. Only need to identify the ., +, -, *, / only. * 3. System would point out the wrong position. * - Before the decimal need a digit. * - Before the expression need a digit. * - Expression could not at first or last place. * * @example * [Input] * 12+16.+ * * [Output] * ====== Result ====== * Arrrgh!*#!! There's an error * 12+16.+ * ^ * * @author Jason Lin * * @date * - Revision: Nov. 07, 2020 * - Orignial: Oct. 07, 2015 * * @version 2.0.0 * */ #include <iostream> #include <limits> #include <cstdlib> // For the exit() function #include <cctype> // For the isdigit() function #define MAX_LEN 80 void eatspaces(char *str); // Function to remove the blank space double expr(char *str); // Function evaluating an expression double term(char *str, int &index); // Function analyzing a term double number(char *str, int &index); // Function to recognize a number void error(char *str); int main(int argc, char *argv[]) { // Declare the varialbe char buffer[MAX_LEN] = {0}; // User input std::cout << "Please enter formula only with + or - or * or /." << std::endl; // User Input: Formula 1 std::cout << "Please enter formula: " << std::endl; std::cin.getline(buffer, sizeof buffer); // Check if not enter anything if(!buffer[0]) return EXIT_SUCCESS; // Preprocess & Logic // Clean the space part eatspaces(buffer); // Output std::cout << "====== Result ======" << std::endl; std::cout << "\t= " << expr(buffer) << std::endl; return EXIT_SUCCESS; } /** * Remove the input text space. * * @param str [pointer of char] A array of characters. * * @return None */ void eatspaces(char *str) { int i(0), j(0); // pointer + offset while ((*(str + i) = *(str + j++)) != '\0') { if (*(str + i) != ' ') { // if it not space, need to add one i++; } } } /** * Read a series of term, separate with expression and decimal. * * @param str [pointer of char] A array of string. (User input formula.) * * @return value [double] Calculate the formula result. */ double expr(char *str) { double value(0.0); int index(0); value = term(str, index); // Iteration the whole string for(;;) { // Choose action based on current character switch(*(str + index++)) { // Touch the end of the string case '\0': return value; case '+': value += term(str, index); break; case '-': value -= term(str, index); break; default: std::cout << std::endl << "Arrrgh!*#!! There's an error" << std::endl; error(str); exit(EXIT_FAILURE); } } } /** * To calculate the multiply or divide part. * * @param str [pointer of char] A array of string. (User input formula.) * @param index [pointer of int] Record current read index location. * * @return value [double] The current cumulate value in this part. */ double term(char *str, int &index) { double value(0.0); // Get the first number in term value = number(str, index); // To find the operator if it is multiply or divide while(true) { if(*(str + index) == '*') value *= number(str, ++index); else if(*(str + index) == '/') value /= number(str, ++index); else break; } return value; } /** * Read the value from the string. * * @param str [pointer of char] A array of string. (User input formula.) * @param index [pointer of int] Record current read index location. * * @return value [double] The current number in this part. */ double number(char *str, int &index) { double value(0.0), factor(1.0); // Check if here has one digit at least if(!isdigit(*(str + index))) { std::cout << std::endl << "Arrrgh!*#!! There's an error" << std::endl; error(str); exit(EXIT_FAILURE); } // Calculate the number while(isdigit(*(str + index))) value = 10 * value + (*(str + index++) - '0'); // If the input is not number, check if it is decimal if(*(str + index) != '.') return value; while(isdigit(*(str + (++index)))) { factor *= 0.1; value = value + (*(str + index) - '0') * factor; } return value; } /** * To find the illegal formula position. * * @param str [pointer of char] A array of string. (User input formula.) * * @return None */ void error(char *str) { char word, prior_word; int idx(0), temp(-1); // Iteration to print the whole string for(idx = 0 ; *(str + idx) != '\0' ; idx++) { std::cout << *(str + idx); } std::cout << std::endl; idx = 0; // Need to identify the space while(*(str + idx) != '\0') { // Get the pointer current character word = *(str + idx); // If the current character is mathematical operators if (word == '+' || word == '-' || word == '*' || word == '/') { temp = idx; temp--; // To get the prior character while (*(str + temp) == ' ' && temp > 0) temp--; prior_word = *(str + temp); // If prior word is 0-9 or decimal point if ((prior_word >= 48 && prior_word <= 57) || prior_word == '.') { temp = idx; temp++; // To get the next character while (*(str + temp) == ' ' && *(str + temp) != '\0') temp++; // If next word is last word if (*(str + temp) == '\0') std::cout << "^"; else std::cout << " "; } // If the prior word is illegal else if (word == '+' || word == '-' || word == '*' || word == '/') std::cout << "^"; // Check the next word is digit else { temp = idx; temp++; // To get the next character while (*(str + temp) == ' ' && *(str + temp) != '\0') temp++; // If next character is 0-9 if (*(str + temp) >= 48 && *(str + temp) <= 57) std::cout << " "; else std::cout << "^"; } } // If current character is decimal point else if (*(str + idx) == '.') { temp = idx; temp--; // To get the prior character while (*(str + temp) == ' ' && temp > 0) temp--; // Check if prior character is 0-9 if (*(str + temp) >= 48 && *(str + temp) <= 57) std::cout << " "; else std::cout << "^"; } // If current character is 0-9 else if (*(str + idx) >= 48 && *(str + idx) <= 57) std::cout << " "; // If current character is space else if (*(str + idx) == ' ') std::cout << " "; // Other character identify as illegal character else std::cout << "^"; idx++; } std::cout << std::endl; }
[ "jason40418@gmail.com" ]
jason40418@gmail.com
192eab34d0951955615cd99886a7b614e1788785
3a8240d9698d037df7cc0c3884a5930b69ba6027
/src/hal_quadrotor/src/control/VelocityHeight.cpp
cadc1ff846e907ba513254e3a18fcfb97359ba78
[ "BSD-2-Clause" ]
permissive
jiangchenzhu/crates_zhejiang
797cbf246f2b7f0e0fc950e420816cda58bf16a9
711c9fafbdc775114345ab0ca389656db9d20df7
refs/heads/master
2021-01-10T09:09:26.385627
2015-12-17T15:54:57
2015-12-17T15:54:57
48,175,740
0
0
null
null
null
null
UTF-8
C++
false
false
3,839
cpp
#include <hal_quadrotor/control/VelocityHeight.h> // Controller constants #define _X 0 #define _Y 1 #define _Z 2 #define _YAW 3 #define _Kvp 0.25 /* xy velocity proportional constant */ #define _Kvi 0.15 /* xy velocity integrative constant */ #define _Kvd 0.00 /* xy velocity derivative constant */ #define _Kiz 0.0008 /* altitude integrative constant */ #define _Kpz 0.03 /* altitude proportional constant */ #define _Kdz 0.04 /* altitude derivative constant */ #define _th_hover 0.59 /* throttle hover offset */ #define _maxtilt 0.34 /* max pitch/roll angle */ #define _Kya 6.0 /* yaw proportional constant */ #define _maxyawrate 4.4 /* max allowed yaw rate */ #define _maxv 3.0 /* max allowed xy velocity */ using namespace hal::quadrotor; // Incoming velocity and height control bool VelocityHeight::SetGoal( hal_quadrotor::VelocityHeight::Request &req, hal_quadrotor::VelocityHeight::Response &res ) { // Horizontal velocity sp[_X] = req.dx; sp[_Y] = req.dy; sp[_Z] = req.z; sp[_YAW] = req.yaw; // Try and switch control res.success = true; res.status = "Successfully switched to VelocityHeight controller"; return true; } // Update the control void VelocityHeight::Update(const hal_quadrotor::State &state, double dt, hal_quadrotor::Control &control) { ///////////////// PID CONTROLLER FOR PITCH AND ROLL ///////////////////// // Body-frame velocity (v) and b < n frame rotation (r) double vt[3], r[3]; // Get the Euler orientation r[0] = state.roll; r[1] = state.pitch; r[2] = state.yaw; // Make a copy of the n-frame velocity vt[0] = sp[_X]; vt[1] = sp[_Y]; vt[2] = 0.0; // Get the n-frame (x,y) velocity in the b-frame n2b(r,vt); // Used for calculations below double e, de; // Pitch e = (limit(vt[0],-_maxv,_maxv) - state.u); de = (dt > 0 ? (e - ep[_X]) / dt : 0); ei[_X] += e * dt; ep[_X] = e; double desP = limit(_Kvp * e + _Kvi * ei[_X] + _Kvd * de,-_maxtilt,_maxtilt); // Roll e = -(limit(vt[1],-_maxv,_maxv) - state.v); de = (dt > 0 ? (e - ep[_Y]) / dt : 0); ei[_Y] += e * dt; ep[_Y] = e; double desR = limit(_Kvp * e + _Kvi * ei[_Y] + _Kvd * de,-_maxtilt,_maxtilt); ////////////////////////// PID THROTTLE CONTROLLER ////////////////////////// // Get the (P)roportional component double ez_ = sp[_Z] - state.z; // Get the (I)ntegral component iz += ez_ * dt; // Get the (D)erivative component double de_ = (dt > 0 ? (ez_ - ez) / dt : 0); double desth = _th_hover + _Kpz * ez_ + _Kiz * iz + de_ * _Kdz; double th = limit(desth,0.0,1.0); // Save (P) contribution for next derivative calculation ez = ez_; // Save (I) contribution for next derivative calculation iz = iz - (desth - th) * 2.0; //////////////////// P CONTROLLER FOR YAW ////////////////////// double desY = limit(_Kya * (sp[_YAW] - state.yaw), -_maxyawrate, _maxyawrate); //////////////////////// CONTROL PACKAGING ///////////////////////// // This will be returned control.roll = desR; control.pitch = desP; control.yaw = desY; control.throttle = th; } // Goal reach implementations bool VelocityHeight::HasGoalBeenReached() { return false; } // Reset implementations void VelocityHeight::Reset() { // For roll, pitch, height for (int i = 0; i < 3; i++) { ei[i] = 0.0; ep[i] = 0.0; } }
[ "jiangchengzhu@bitbucket.com" ]
jiangchengzhu@bitbucket.com
88c058c9d8a5793663331c359020bb56d997207d
1e58ee167a1d2b03931a908ff18a11bd4b4005b4
/groups/bbl/bbldc/bbldc_basicnl365.h
6a8a6c14bed037c0e57209c2ca7567b949e5f89b
[ "Apache-2.0" ]
permissive
dhbaird/bde
23a2592b753bc8f7139d7c94bc56a2d6c9a8a360
a84bc84258ccdd77b45c41a277632394ebc032d7
refs/heads/master
2021-01-19T16:34:04.040918
2017-06-06T14:35:05
2017-06-08T11:27:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,080
h
// bbldc_basicnl365.h -*-C++-*- #ifndef INCLUDED_BBLDC_BASICNL365 #define INCLUDED_BBLDC_BASICNL365 #ifndef INCLUDED_BSLS_IDENT #include <bsls_ident.h> #endif BSLS_IDENT("$Id: $") //@PURPOSE: Provide stateless functions for the NL/365 convention. // //@CLASSES: // bbldc::BasicNl365: NL/365 convention stateless functions // //@DESCRIPTION: This component provides a 'struct', 'bbldc::BasicNl365', that // serves as a namespace for defining a suite of date-related functions used to // compute the day count and the year fraction between two dates as per the // NL/365 day-count convention. In this day-count convention, we simply // measure the number of non-leap days occurring in a time period, and to // calculate years, divide that by 365. Note that this means the number of // years between January 1, 2004 and January 1, 2005 is 1.0. No end-of-month // rule adjustments are made. // ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Computing Day Count and Year Fraction ///- - - - - - - - - - - - - - - - - - - - - - - - // The following snippets of code illustrate how to use 'bbldc::BasicNl365' // methods. First, create four 'bdlt::Date' variables: //.. // const bdlt::Date dA(2004, 2, 1); // const bdlt::Date dB(2004, 3, 1); // const bdlt::Date dC(2004, 5, 1); // const bdlt::Date dD(2005, 2, 1); //.. // Then, compute the day count between some pairs of these dates: //.. // int daysDiff; // daysDiff = bbldc::BasicNl365::daysDiff(dA, dB); // assert( 28 == daysDiff); // daysDiff = bbldc::BasicNl365::daysDiff(dA, dC); // assert( 89 == daysDiff); // daysDiff = bbldc::BasicNl365::daysDiff(dA, dD); // assert(365 == daysDiff); // daysDiff = bbldc::BasicNl365::daysDiff(dB, dC); // assert( 61 == daysDiff); //.. // Finally, compute the year fraction between some of the dates: //.. // double yearsDiff; // yearsDiff = bbldc::BasicNl365::yearsDiff(dA, dC); // // Need fuzzy comparison since 'yearsDiff' is a 'double'. // assert(yearsDiff < 0.2439 && yearsDiff > 0.2438); // yearsDiff = bbldc::BasicNl365::yearsDiff(dA, dD); // assert(1.0 == yearsDiff); //.. #ifndef INCLUDED_BBLSCM_VERSION #include <bblscm_version.h> #endif #ifndef INCLUDED_BDLT_DATE #include <bdlt_date.h> #endif namespace BloombergLP { namespace bbldc { // ================= // struct BasicNl365 // ================= struct BasicNl365 { // This 'struct' provides a namespace for a suite of pure functions that // compute values based on dates according to the NL/365 day-count // convention. // CLASS METHODS static int daysDiff(const bdlt::Date& beginDate, const bdlt::Date& endDate); // Return the (signed) number of days between the specified 'beginDate' // and 'endDate' according to the NL/365 day-count convention. If // 'beginDate <= endDate' then the result is non-negative. Note that // reversing the order of 'beginDate' and 'endDate' negates the result. static double yearsDiff(const bdlt::Date& beginDate, const bdlt::Date& endDate); // Return the (signed fractional) number of years between the specified // 'beginDate' and 'endDate' according to the NL/365 day-count // convention. If 'beginDate <= endDate' then the result is // non-negative. Note that reversing the order of 'beginDate' and // 'endDate' negates the result; specifically, // '|yearsDiff(b, e) + yearsDiff(e, b)| <= 1.0e-15' for all dates 'b' // and 'e'. }; // ============================================================================ // INLINE DEFINITIONS // ============================================================================ // ----------------- // struct BasicNl365 // ----------------- // CLASS METHODS inline double BasicNl365::yearsDiff(const bdlt::Date& beginDate, const bdlt::Date& endDate) { return daysDiff(beginDate, endDate) / 365.0; } } // close package namespace } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2016 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
[ "abeels@bloomberg.net" ]
abeels@bloomberg.net
cfedf4f829acffcbc97039da2a2442e8ce56e1b1
b6716aec9729cac4fc71e59f80ab92791545ab8d
/vex/sdk/vexv5/gcc/include/c++/4.9.3/tr1/ctype.h
2a617b0e1655a495e11260d241e715a047ebf5f7
[]
no_license
RIT-VEX-U/2020-2021-LITTLE
99a54e9a908760c94e9baa314d690c4394fb49bd
bdfa54d5c4f6968a1affc758055eaf6bdac23741
refs/heads/master
2021-05-21T02:25:17.788991
2021-03-30T02:16:15
2021-03-30T02:16:15
252,501,126
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
h
// TR1 ctype.h -*- C++ -*- // Copyright (C) 2006-2014 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file tr1/ctype.h * This is a TR1 C++ Library header. */ #ifndef _TR1_CTYPE_H #define _TR1_CTYPE_H 1 #include <tr1/cctype> #endif
[ "ramtech51@comcast.net" ]
ramtech51@comcast.net
121fb3774516293bcd865826784f65d24130c5de
5df1d69d604c22a8f9bff5d2f9a78e460f9fab19
/src/main.cpp
42b25d0a1e756cbcc9dfc522efb67d4e0b51c3fe
[]
no_license
craftycodie/NetworksLogParser
f45d790c9d1b1fa9d1471c93aab7dda2efa9a94c
2d2fb395d591097eb05f12af7acc9ab52568f1bd
refs/heads/master
2022-01-10T15:49:33.687013
2019-05-09T19:29:01
2019-05-09T19:29:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,607
cpp
// // NetworksLogParser - Alex Newark // // This log parser was created for a uni assessment. // It currently supports parsing of ping, traceroute and wget logs. // Following a somewhat Object-Oriented design, the program is fairly extendable, // and more log types could be added in future. // // Potential Future Improvements: // - Implementing a base class for logtypes, with a virtual function to detect if a log is of that type // so that detecting a log type and handling output could be done genericly. // - Better error handling of logs, at the moment suitable logs are expected. // - More information from logs, eg ping hopcount. // #include <string> #include <iostream> #include <fstream> #include <vector> #include "logtypes/wget.h" #include "logtypes/ping.h" #include "logtypes/traceroute.h" using namespace std; using namespace logparser::logtypes; int main(int argc, char* argv[]) { std::cout << "Log Parser" << endl; // If there's no files to parse, tell the user. if (argc < 2) { cout << "Drag files onto the exe or launch with paths as arguments." << endl; } // For every file to parse... for (int i = 1; i < argc; ++i) { cout << endl << "Parsing log " << i << ": " << argv[i] << endl; ifstream currentLogFile; ofstream currentCsvFile; // Create and open a csv file to string csvPath = (new string(argv[i]))->append(".csv"); currentLogFile.open(argv[i], ifstream::in); currentCsvFile.open(csvPath, ifstream::out); // Get the first line to determine the log type. string firstLine; getline(currentLogFile, firstLine); if (firstLine.rfind("PING") == 0) { cout << "Detected ping log type..." << endl; vector<ping> rtts; ping rtt; while (currentLogFile >> rtt) { rtts.push_back(rtt); cout << "Parsed RTT: " << rtt.rttAvg << " ms" << endl; } cout << "Writing csv file... (" << csvPath << ')' << endl; for (ping rtt : rtts) { currentCsvFile << rtt << endl << endl; } cout << "Done." << endl; } else if (firstLine.rfind("traceroute") == 0) { cout << "Detected traceroute log type..." << endl; vector<traceroute> traceroutes; traceroute _traceroute; while (currentLogFile >> _traceroute) { traceroutes.push_back(_traceroute); cout << "Parsed Traceroute: " << endl << _traceroute; } traceroutes.push_back(_traceroute); cout << "Parsed Traceroute." << endl; cout << "Writing csv file... (" << csvPath << ')' << endl; for (traceroute _traceroute : traceroutes) { currentCsvFile << _traceroute; } cout << "Done." << endl; } // If the log isn't a traceroute or ping, wget is assumed. else { cout << "Detected throughput log type..." << endl; vector<wget> throughputs; wget throughput; while (currentLogFile >> throughput) { throughputs.push_back(throughput); cout << "Parsed Throughput: " << throughput.kbps << " KB/s" << endl; } float throughputSum = 0; for (wget throughput : throughputs) { throughputSum += throughput.kbps; } float throughputAverage = throughputSum / throughputs.size(); cout << "Average Throughput: " << throughputAverage << " KB/s" << endl; cout << "Writing csv file... (" << csvPath << ')' << endl; currentCsvFile << "Throughputs (KB/s),"; for (wget throughput : throughputs) { currentCsvFile << throughput << ","; } currentCsvFile << endl << "Average Throughput (KB/s)," << throughputAverage; cout << "Done." << endl; } currentLogFile.close(); currentCsvFile.close(); } cout << endl << "Press any key to exit." << endl; getchar(); return 0; }
[ "git@alex231.com" ]
git@alex231.com
f647f9e0c8ba33befd0ffd95960f200bcf97519a
5d3db9e0e18dad1e243c5cb01822bbcd9b66d9d3
/Source/AudioClipList.h
99d5c875c786a8fd2f9115e3746f026f4e8e33d2
[ "MIT" ]
permissive
Hybrid-Music-Lab/Unicycle
ed6a2ec1a6b15b503093413701b32394eca80a0d
c550b6c5e021a75b516db598d077b176ae8258b9
refs/heads/main
2023-04-01T05:10:01.417392
2021-04-09T11:34:16
2021-04-09T11:34:16
356,242,228
0
0
null
null
null
null
UTF-8
C++
false
false
2,067
h
// Copyright (c) 2019 Christoph Mann (christoph.mann@gmail.com) #pragma once #include "MainHeaders.h" #include "LookAndFeel.h" #include "AudioClip.h" #include "AudioCommands.h" #include "Commands.h" #include "MainInterface.h" namespace unc { class AudioClipListModel : public ListBoxModel { public: AudioClipListModel( AudioClips* clips, class AudioClipList* clipList ); // ListBoxModel int getNumRows() override; void paintListBoxItem( int rowNumber, Graphics& g, int width, int height, bool rowIsSelected ) override; void selectedRowsChanged( int lastRowSelected )override; AudioClips* clips = nullptr; AudioClipList* clipList = nullptr; }; class AudioClipList : public Component, public ApplicationCommandTarget, public ChangeListener, public FileDragAndDropTarget { public: AudioClipList(); ~AudioClipList(); // view void display( AudioClips* other ); // Component void paint( Graphics& g )override; void resized() override; void mouseDown( const MouseEvent& e )override; // modify void selectRow( int row ); // access Array<AudioClip*> getListSelection() const; int getRowHeight() const{ return lnf::dims::h + lnf::dims::pad; } // ApplicationCommandTarget ApplicationCommandTarget* getNextCommandTarget() override; void getAllCommands( Array<CommandID>& commands ) override; void getCommandInfo( CommandID commandID, ApplicationCommandInfo& result ) override; bool perform( const InvocationInfo& info ) override; // ChangeListener void changeListenerCallback( ChangeBroadcaster* source )override; // FileDragAndDropTarget bool isInterestedInFileDrag( const StringArray& files )override; void filesDropped( const StringArray& files, int x, int y )override; AudioClips* clips = nullptr; private: std::unique_ptr<ListBoxModel> listModel{ nullptr }; ListBox listBox; TextButton outButton{ "Outpath" }; Label outDisplay{ "outDisplay" }; File outPath; TextButton renderButton{ "Render" }; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR( AudioClipList ); }; }
[ "christoph.mann@gmail.com" ]
christoph.mann@gmail.com
c9106198398680d7fa09f2ebf7f171ab9e434e1a
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/folly/2017/4/NestedCommandLineAppTestHelper.cpp
da404613087679d2faf864511c93655ef83e0c23
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
1,662
cpp
/* * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/experimental/NestedCommandLineApp.h> #include <folly/portability/GFlags.h> DEFINE_int32(global_foo, 42, "Global foo"); namespace po = ::boost::program_options; namespace { void init(const std::string& cmd, const po::variables_map& /* options */, const std::vector<std::string>& /* args */) { printf("running %s\n", cmd.c_str()); } void foo(const po::variables_map& options, const std::vector<std::string>& args) { printf("foo global-foo %d\n", options["global-foo"].as<int32_t>()); printf("foo local-foo %d\n", options["local-foo"].as<int32_t>()); for (auto& arg : args) { printf("foo arg %s\n", arg.c_str()); } } } // namespace int main(int argc, char *argv[]) { folly::NestedCommandLineApp app("", "0.1", "", "", init); app.addGFlags(); app.addCommand("foo", "[args...]", "Do some foo", "Does foo", foo) .add_options() ("local-foo", po::value<int32_t>()->default_value(42), "Local foo"); app.addAlias("bar", "foo"); app.addAlias("baz", "bar"); return app.run(argc, argv); }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
789e1b52a21ad260b087231bc60155e947100bc6
8fc3ff051a0d6c93ff5b245b514df04757c5f38b
/src/OpcUaWebServer/WebGateway/LogoutResponse.cpp
8fea5b07e549fb0c945569e2d532a7f63d9917a6
[ "Apache-2.0" ]
permissive
huebl/OpcUaWebServer
37147f9a0fafbc532e0bea76181f07380da7093e
8ae1741c88783d6c263b27dbb22fd37fd3d97db0
refs/heads/master
2021-01-06T19:29:28.450395
2020-01-18T15:33:34
2020-01-27T08:46:26
241,460,173
1
0
null
2020-02-18T20:26:58
2020-02-18T20:26:57
null
UTF-8
C++
false
false
1,089
cpp
/* Copyright 2019 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include <OpcUaWebServer/WebGateway/LogoutResponse.h> namespace OpcUaWebServer { LogoutResponse::LogoutResponse(void) { } LogoutResponse::~LogoutResponse(void) { } bool LogoutResponse::jsonEncodeImpl(boost::property_tree::ptree& pt) const { return true; } bool LogoutResponse::jsonDecodeImpl(const boost::property_tree::ptree& pt) { return true; } }
[ "kai@huebl-sgh.de" ]
kai@huebl-sgh.de
7d2394bf44993d81e7777a35ce11cfe07155c34b
4ebca7bab6e3aa1a9d0da68d786b70dec6a397e9
/Code/cocos2d-2.0-x-2.0.3/ProtectLand/Classes/Layers/MenuLayer.cpp
76903a466ed6e17c82c3adc444052b5ebef0c257
[ "MIT" ]
permissive
chiehfc/protect-land
9cb9f17b9ecd0b2cb8eaaa5d40526489db707d95
f93bb4b1ab4f71fd919a3605782f074af9a0b791
refs/heads/master
2016-09-03T06:46:31.136540
2012-12-07T07:36:31
2012-12-07T07:36:31
40,037,018
0
0
null
null
null
null
UTF-8
C++
false
false
3,651
cpp
#include "GameConfig.h" #include "MenuLayer.h" #include "GamePlay.h" #include "MainMenuScene.h" #include "SelectLevelScene.h" #include "GameObjectLayer.h" #include "SkillUpgradeScene.h" #include "AudioManager.h" //#include "SpritesLayer.h" #include "IncludeHelper.h" USING_NS_CC; bool CMenuLayer::init() { if(!CCLayer::init()) { return false; } CCSize size = CCDirector::sharedDirector()->getWinSize(); CCMenuItemImage *pContinueItem = CCMenuItemImage::create( "Button\\button_play_down.png", "Button\\button_home_up.png", this, menu_selector(CMenuLayer::menuContinueCallback)); pContinueItem->setPosition( ccp(size.width/2 , size.height/2 + size.height*120/HEIGHT_SCREEN_STANDARD)); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::create(pContinueItem, NULL); pMenu->setPosition( CCPointZero ); CCMenuItemImage *pMainMenu = CCMenuItemImage::create( "Button\\button_return_down.png", "Button\\button_return_up.png", this, menu_selector(CMenuLayer::menuSkillUpgradeCallback)); pMainMenu->setPosition(ccp(size.width/2, size.height/2 + size.height*40/HEIGHT_SCREEN_STANDARD)); pMenu->addChild(pMainMenu); CCMenuItemImage *pMuteMenu = CCMenuItemImage::create( "Button\\button_home_down.png", "Button\\button_home_up.png", this, menu_selector(CMenuLayer::menuMainMenuCallback)); pMuteMenu->setPosition(ccp(size.width/2, size.height/2 - size.height*40/HEIGHT_SCREEN_STANDARD)); pMenu->addChild(pMuteMenu); this->addChild(pMenu); return true; } /************************************************************************/ /* Menu call back funtions */ /************************************************************************/ void CMenuLayer::menuContinueCallback(CCObject* pSender) { /*CAudioManager::instance()->stopAllEff(); CAudioManager::instance()->stopBGMusic();*/ //if(CAudioManager::instance()->GetSound()==SOUND_BG_EFF) CAudioManager::instance()->playEff(SOUND_BUTTON); CGamePlay::removeLayerByTag(TAG_GAMEPLAY_MENU_LAYER); CGamePlay::removeLayerByTag(TAG_GAMEPLAY_COLOR_LAYER); CCDirector::sharedDirector()->resume(); CGamePlay::setEnableMenu(true); } void CMenuLayer::menuSkillUpgradeCallback(CCObject* pSender) { CAudioManager::instance()->stopAllEff(); CAudioManager::instance()->stopBGMusic(); //if(CAudioManager::instance()->GetSound()==SOUND_BG_EFF) CAudioManager::instance()->playEff(SOUND_BUTTON); CCDirector::sharedDirector()->resume(); CGamePlay::removeLayerByTag(TAG_GAMEPLAY_COLOR_LAYER); CGamePlay::removeLayerByTag(TAG_GAMEPLAY_MENU_LAYER); CCScene* selectLevel = CSkillUpgradeScene::scene(); CCScene* pScene = CCTransitionFade::create(TRANSITION_DURATION, selectLevel); if (pScene) { CCDirector::sharedDirector()->replaceScene(pScene); } CGamePlay::destroy(); } void CMenuLayer::menuMainMenuCallback(CCObject* pSender) { CAudioManager::instance()->stopAllEff(); CAudioManager::instance()->stopBGMusic(); //if(CAudioManager::instance()->GetSound()==SOUND_BG_EFF) CAudioManager::instance()->playEff(SOUND_BUTTON); CCDirector::sharedDirector()->resume(); CGamePlay::removeLayerByTag(TAG_GAMEPLAY_COLOR_LAYER); CGamePlay::removeLayerByTag(TAG_GAMEPLAY_MENU_LAYER); CGamePlay::destroy(); CCScene *mainmenuScene = CMainMenuScene::scene(); CCScene* pScene =CCTransitionFade::create(TRANSITION_DURATION, mainmenuScene, ccWHITE); if (pScene) { CCDirector::sharedDirector()->replaceScene(pScene); } } void CMenuLayer::onExit() { this->removeAllChildrenWithCleanup(true); }
[ "nhanltv.bd@gmail.com" ]
nhanltv.bd@gmail.com
922a36c40beda58736ee4e438b28ad3a465c426a
2a0e1052acd5d9fe1f75a93e906175306c412b3e
/Mark Lizzimore CGP600 Tutorial 9/main.cpp
b330dde46ee057125ded87a68525d42468587555
[]
no_license
Paramedic293-S/Advanced-Games-Programming
8a4adf050fc3c9ab5bc9d5ef59aec45615c96e85
805427351f86d65a30fa3644647b260a3792247f
refs/heads/master
2021-08-31T10:24:12.381505
2017-12-21T02:06:55
2017-12-21T02:06:55
105,126,416
0
0
null
null
null
null
UTF-8
C++
false
false
20,158
cpp
#include <windows.h> #include <d3d11.h> #include <d3dx11.h> #include <dxerr.h> #include <stdio.h> #include "camera.h" #include "text2D.h" #define _XM_NO_INTRINSICS_ #define XM_NO_ALIGNMENT #include <xnamath.h> int (WINAPIV * __vsnprintf_s)(char *, size_t, const char*, va_list) = _vsnprintf; ////////////////////////////////////////////////////////////////////////////////////// // Global Variables ////////////////////////////////////////////////////////////////////////////////////// HINSTANCE g_hInst = NULL; HWND g_hWnd = NULL; // Rename for each tutorial char g_TutorialName[100] = "Tutorial 09 Exercise 01\0"; D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; ID3D11Device* g_pD3DDevice = NULL; ID3D11DeviceContext* g_pImmediateContext = NULL; IDXGISwapChain* g_pSwapChain = NULL; ID3D11RenderTargetView* g_pBackBufferRTView = NULL; ID3D11Buffer* g_pVertexBuffer; ID3D11VertexShader* g_pVertexShader; ID3D11PixelShader* g_pPixelShader; ID3D11InputLayout* g_pInputLayout; ID3D11Buffer* g_pConstantBuffer0; ID3D11DepthStencilView* g_pZBuffer; ID3D11ShaderResourceView* g_pTexture0; ID3D11SamplerState* g_pSampler0; camera* camera1; Text2D* g_2DText; XMVECTOR g_directional_light_shines_from; XMVECTOR g_directional_light_colour; XMVECTOR g_ambient_light_colour; struct POS_COL_TEX_NORM_VERTEX { XMFLOAT3 Pos; XMFLOAT4 Col; XMFLOAT2 Texture0; XMFLOAT3 Normal; }; struct CONSTANT_BUFFER0 { XMMATRIX WorldViewProjection; XMVECTOR directional_light_vector; XMVECTOR directional_light_colour; XMVECTOR ambient_light_colour; /*XMMATRIX WorldViewProjection2;*/ /*float RedAmount; float Scale;*/ /*XMFLOAT2 packing_bytes;*/ }; ////////////////////////////////////////////////////////////////////////////////////// // Forward declarations ////////////////////////////////////////////////////////////////////////////////////// HRESULT InitialiseWindow(HINSTANCE hInstance, int nCmdShow); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); HRESULT InitialiseD3D(); void ShutdownD3D(); void RenderFrame(void); HRESULT InitialiseGraphics(void); ////////////////////////////////////////////////////////////////////////////////////// // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. ////////////////////////////////////////////////////////////////////////////////////// int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); if (FAILED(InitialiseWindow(hInstance, nCmdShow))) { DXTRACE_MSG("Failed to create Window"); return 0; } if (FAILED(InitialiseD3D())) { DXTRACE_MSG("Failed to create Device"); return 0; } if (FAILED(InitialiseGraphics())) { DXTRACE_MSG("Failed to initialise graphics"); return 0; } // Main message loop MSG msg = { 0 }; while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { RenderFrame(); } } ShutdownD3D(); return (int)msg.wParam; } ////////////////////////////////////////////////////////////////////////////////////// // Register class and create window ////////////////////////////////////////////////////////////////////////////////////// HRESULT InitialiseWindow(HINSTANCE hInstance, int nCmdShow) { // Give your app window your own name char Name[100] = "Mark Lizzimore\0"; // Register class WNDCLASSEX wcex = { 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); // wcex.hbrBackground = (HBRUSH )( COLOR_WINDOW + 1); // Needed for non-D3D apps wcex.lpszClassName = Name; if (!RegisterClassEx(&wcex)) return E_FAIL; // Create window g_hInst = hInstance; RECT rc = { 0, 0, 640, 480 }; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); g_hWnd = CreateWindow(Name, g_TutorialName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance, NULL); if (!g_hWnd) return E_FAIL; ShowWindow(g_hWnd, nCmdShow); return S_OK; } ////////////////////////////////////////////////////////////////////////////////////// // Called every time the application receives a message ////////////////////////////////////////////////////////////////////////////////////// LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_KEYDOWN: if (wParam == VK_ESCAPE) DestroyWindow(g_hWnd); return 0; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } ////////////////////////////////////////////////////////////////////////////////////// // Create D3D device and swap chain ////////////////////////////////////////////////////////////////////////////////////// HRESULT InitialiseD3D() { HRESULT hr = S_OK; RECT rc; GetClientRect(g_hWnd, &rc); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, // comment out this line if you need to test D3D 11.0 functionality on hardware that doesn't support it D3D_DRIVER_TYPE_WARP, // comment this out also to use reference device D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = ARRAYSIZE(driverTypes); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = true; for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { g_driverType = driverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain(NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pD3DDevice, &g_featureLevel, &g_pImmediateContext); if (SUCCEEDED(hr)) break; } if (FAILED(hr)) return hr; // Get pointer to back buffer texture ID3D11Texture2D *pBackBufferTexture; hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBufferTexture); if (FAILED(hr)) return hr; // Use the back buffer texture pointer to create the render target view hr = g_pD3DDevice->CreateRenderTargetView(pBackBufferTexture, NULL, &g_pBackBufferRTView); pBackBufferTexture->Release(); if (FAILED(hr)) return hr; D3D11_TEXTURE2D_DESC tex2dDesc; ZeroMemory(&tex2dDesc, sizeof(tex2dDesc)); tex2dDesc.Width = width; tex2dDesc.Height = height; tex2dDesc.ArraySize = 1; tex2dDesc.MipLevels = 1; tex2dDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; tex2dDesc.SampleDesc.Count = sd.SampleDesc.Count; tex2dDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; tex2dDesc.Usage = D3D11_USAGE_DEFAULT; ID3D11Texture2D *pZBufferTexture; hr = g_pD3DDevice->CreateTexture2D(&tex2dDesc, NULL, &pZBufferTexture); if (FAILED(hr)) return hr; D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; ZeroMemory(&dsvDesc, sizeof(dsvDesc)); dsvDesc.Format = tex2dDesc.Format; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; g_pD3DDevice->CreateDepthStencilView(pZBufferTexture, &dsvDesc, &g_pZBuffer); pZBufferTexture->Release(); // Set the render target view g_pImmediateContext->OMSetRenderTargets(1, &g_pBackBufferRTView, g_pZBuffer); // Set the viewport D3D11_VIEWPORT viewport; viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = width; viewport.Height = height; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; g_pImmediateContext->RSSetViewports(1, &viewport); g_2DText = new Text2D("ASSETS/font1.bmp", g_pD3DDevice, g_pImmediateContext); return S_OK; if (FAILED(InitialiseGraphics())) { DXTRACE_MSG("Failed to initialise graphics"); return 0; } } ////////////////////////////////////////////////////////////////////////////////////// // Clean up D3D objects ////////////////////////////////////////////////////////////////////////////////////// void ShutdownD3D() { if (camera1) delete camera1; if (g_2DText) delete g_2DText; if (g_pBackBufferRTView) g_pBackBufferRTView->Release(); if (g_pVertexBuffer) g_pVertexBuffer->Release(); if (g_pInputLayout) g_pInputLayout->Release(); if (g_pVertexShader) g_pVertexShader->Release(); if (g_pPixelShader) g_pPixelShader->Release(); if (g_pSwapChain) g_pSwapChain->Release(); if (g_pConstantBuffer0) g_pConstantBuffer0->Release(); if (g_pTexture0) g_pTexture0->Release(); if (g_pSampler0) g_pSampler0->Release(); if (g_pImmediateContext) g_pImmediateContext->Release(); if (g_pD3DDevice) g_pD3DDevice->Release(); } HRESULT InitialiseGraphics() { HRESULT hr = S_OK; POS_COL_TEX_NORM_VERTEX vertices[] = { { XMFLOAT3(-1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f)}, { XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }, { XMFLOAT3(1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }, { XMFLOAT3(1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }, { XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }, { XMFLOAT3(1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }, { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }, { XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }, { XMFLOAT3(1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }, { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }, { XMFLOAT3(1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }, { XMFLOAT3(1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }, { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }, { XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }, { XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }, { XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }, { XMFLOAT3(-1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }, { XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }, { XMFLOAT3(1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }, { XMFLOAT3(1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }, { XMFLOAT3(1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }, { XMFLOAT3(1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }, { XMFLOAT3(1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }, { XMFLOAT3(1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }, { XMFLOAT3(1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }, { XMFLOAT3(1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }, { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }, { XMFLOAT3(1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }, { XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }, { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }, { XMFLOAT3(1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }, { XMFLOAT3(1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }, { XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }, { XMFLOAT3(-1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }, { XMFLOAT3(1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }, { XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) } }; D3DX11CreateShaderResourceViewFromFile(g_pD3DDevice, "ASSETS/face.bmp", NULL, NULL, &g_pTexture0, NULL); D3D11_BUFFER_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(bufferDesc)); bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = sizeof(vertices); bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; hr = g_pD3DDevice->CreateBuffer(&bufferDesc, NULL, &g_pVertexBuffer); if (FAILED(hr)) { return hr; } D3D11_BUFFER_DESC constant_buffer_desc; ZeroMemory(&constant_buffer_desc, sizeof(constant_buffer_desc)); constant_buffer_desc.Usage = D3D11_USAGE_DEFAULT; constant_buffer_desc.ByteWidth = 112; constant_buffer_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; hr = g_pD3DDevice->CreateBuffer(&constant_buffer_desc, NULL, &g_pConstantBuffer0); if (FAILED(hr)) return hr; D3D11_MAPPED_SUBRESOURCE ms; g_pImmediateContext->Map(g_pVertexBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); memcpy(ms.pData, vertices, sizeof(vertices)); g_pImmediateContext->Unmap(g_pVertexBuffer, NULL); ID3DBlob *VS, *PS, *error; hr = D3DX11CompileFromFile("shaders.hlsl", 0, 0, "VShader", "vs_4_0", 0, 0, 0, &VS, &error, 0); if (error != 0) { OutputDebugStringA((char*)error->GetBufferPointer()); error->Release(); if (FAILED(hr)) { return hr; }; } hr = D3DX11CompileFromFile("shaders.hlsl", 0, 0, "PShader", "ps_4_0", 0, 0, 0, &PS, &error, 0); if (error != 0) { OutputDebugStringA((char*)error->GetBufferPointer()); error -> Release(); if (FAILED(hr)) { return hr; }; } hr = g_pD3DDevice->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &g_pVertexShader); if (FAILED(hr)) { return hr; } hr = g_pD3DDevice->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &g_pPixelShader); if (FAILED(hr)) { return hr; } g_pImmediateContext->VSSetShader(g_pVertexShader, 0, 0); g_pImmediateContext->PSSetShader(g_pPixelShader, 0, 0); D3D11_INPUT_ELEMENT_DESC iedesc[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0} }; hr = g_pD3DDevice->CreateInputLayout(iedesc, ARRAYSIZE(iedesc), VS->GetBufferPointer(), VS->GetBufferSize(), &g_pInputLayout); if (FAILED(hr)) { return hr; } D3D11_SAMPLER_DESC sampler_desc; ZeroMemory(&sampler_desc, sizeof(sampler_desc)); sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampler_desc.MaxLOD = D3D11_FLOAT32_MAX; g_pD3DDevice->CreateSamplerState(&sampler_desc, &g_pSampler0); g_pImmediateContext->IASetInputLayout(g_pInputLayout); camera1 = new camera(5.0, 2.0, 1.0, 0.0); return S_OK; } // Render frame void RenderFrame(void) { // Clear the back buffer - choose a colour you like float rgba_clear_colour[4] = { 0.1f, 0.2f, 0.6f, 1.0f }; g_pImmediateContext->ClearRenderTargetView(g_pBackBufferRTView, rgba_clear_colour); g_pImmediateContext->ClearDepthStencilView(g_pZBuffer, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); XMMATRIX transpose; CONSTANT_BUFFER0 cb0_values; /*cb0_values.RedAmount = 0.5f; cb0_values.Scale = 0.5f;*/ g_pImmediateContext->VSSetShader(g_pVertexShader, 0, 0); g_pImmediateContext->PSSetShader(g_pPixelShader, 0, 0); g_pImmediateContext->IASetInputLayout(g_pInputLayout); XMMATRIX projection, world, view; transpose = XMMatrixTranspose(world); g_directional_light_shines_from = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f); g_directional_light_colour = XMVectorSet(1.0f, 0.0f, 1.0f, 0.0f); g_ambient_light_colour = XMVectorSet(0.1f, 0.1f, 0.1f, 1.0f); cb0_values.directional_light_colour = g_directional_light_colour; cb0_values.ambient_light_colour = g_ambient_light_colour; cb0_values.directional_light_vector = XMVector3Transform(g_directional_light_shines_from, transpose); cb0_values.directional_light_vector = XMVector3Normalize(cb0_values.directional_light_vector); world = XMMatrixRotationZ(XMConvertToRadians(15)); world *= XMMatrixTranslation(2, 0, 15); projection = XMMatrixPerspectiveFovLH(XMConvertToRadians(45.0), 640.0 / 480.0, 1.0, 100.0); view = XMMatrixIdentity(); view = camera1->GetViewMatrix(); cb0_values.WorldViewProjection = world * view * projection; g_pImmediateContext->UpdateSubresource(g_pConstantBuffer0, 0, 0, &cb0_values, 0, 0); g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer0); UINT stride = sizeof(POS_COL_TEX_NORM_VERTEX); UINT offset = 0; g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset); g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); g_pImmediateContext->PSSetSamplers(0, 1, &g_pSampler0); g_pImmediateContext->PSSetShaderResources(0, 1, &g_pTexture0); g_pImmediateContext->Draw(36, 0); world = XMMatrixRotationZ(XMConvertToRadians(65)); world *= XMMatrixTranslation(2, 4, 15); projection = XMMatrixPerspectiveFovLH(XMConvertToRadians(45.0), 640.0 / 480.0, 1.0, 100.0); view = XMMatrixIdentity(); cb0_values.WorldViewProjection = world * view * projection; g_pImmediateContext->UpdateSubresource(g_pConstantBuffer0, 0, 0, &cb0_values, 0, 0); g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer0); g_pImmediateContext->Draw(36, 0); //g_pImmediateContext->IASetVertexBuffers(); //g_pImmediateContext->IASetPrimitiveTopology(); //g_pImmediateContext->VSSetConstantBuffers(); //g_pImmediateContext->PSSetSamplers(); //g_pImmediateContext->PSSetShaderResources(); //g_pImmediateContext->VSSetShader(); //g_pImmediateContext->PSSetShader(); //g_pImmediateContext->IASetInputLayout(); g_2DText->AddText("some text", -1.0, +1.0, 0.2); /*if (g_pConstantBuffer0) g_pConstantBuffer0->Release();*/ // RENDER HERE // Display what has just been rendered g_2DText->RenderText(); g_pSwapChain->Present(0, 0); }
[ "Paramedic292@hotmail.co.uk" ]
Paramedic292@hotmail.co.uk
07afe2339bb7839c45e0881cbc949504abc445f9
ce38c8ac3af32fc95799c61fcae280159d947b81
/EzwiX/EzwiX/ModuleGraphics.cpp
de70267d54cdd1aa10cc85492d8ac44798c6c4a4
[ "MIT" ]
permissive
traguill/EzwiX
d243b554a75d63fb63c25c18a916cbff74331900
3002d842b7a27287af28f0db29d7d51ef04c7302
refs/heads/master
2020-04-05T13:06:28.874961
2017-07-16T10:37:28
2017-07-16T10:37:28
95,096,983
1
0
null
null
null
null
UTF-8
C++
false
false
3,189
cpp
#include "ModuleGraphics.h" #include "log.h" #include "Application.h" #include "D3DModule.h" #include "ModuleCamera.h" #include "ShaderClass.h" #include "TextureShaderClass.h" #include "GameObject.h" #include "ComponentTransform.h" #include "ComponentMesh.h" #include "ComponentTexture.h" #include "ImGui\imgui.h" #include "ImGui\imgui_impl_dx11.h" #include "Devil/include/il.h" #include "Devil/include/ilut.h" #pragma comment ( lib, "Devil/libx86/DevIL.lib" ) #pragma comment ( lib, "Devil/libx86/ILU.lib" ) #pragma comment ( lib, "Devil/libx86/ILUT.lib" ) ModuleGraphics::ModuleGraphics(const char * name, bool start_enabled) : Module(name, start_enabled) { } ModuleGraphics::~ModuleGraphics() { } bool ModuleGraphics::Init() { LOG("Init Graphics"); bool ret = true; d3d = new D3DModule(); ret = d3d->Init(); if (!ret) { MessageBox(App->hWnd, "Could not initialize Direct3D", "Error", MB_OK); return false; } texture = new ComponentTexture(ComponentType::C_TEXTURE, nullptr);//Testing texture->Initialize(d3d->GetDevice(), "img.dds"); //shader_class = new ShaderClass(); texture_shader = new TextureShaderClass(); ret = texture_shader->Init(d3d->GetDevice(), App->hWnd); if (!ret) { LOG("Could not initialzie Shader Class"); return false; } //Init ImGui ImGui_ImplDX11_Init(App->hWnd, d3d->GetDevice(), d3d->GetDeviceContext()); //Init Devil ilInit(); iluInit(); return ret; } bool ModuleGraphics::CleanUp() { LOG("Clean Up Graphics"); models.clear(); ImGui_ImplDX11_Shutdown(); texture_shader->CleanUp(); delete texture_shader; texture_shader = nullptr; d3d->CleanUp(); delete d3d; ilShutDown(); return true; } update_status ModuleGraphics::PreUpdate() { d3d->BeginScene(0.0f, 0.0f, 0.0f, 1.0f); ImGui_ImplDX11_NewFrame(); models.clear(); return update_status::UPDATE_CONTINUE; } update_status ModuleGraphics::PostUpdate() { D3DXMATRIX view_matrix, projection_matrix, world_matrix; App->camera->GetViewMatrix(view_matrix); d3d->GetWorldMatrix(world_matrix); App->camera->GetProjectionMatrix(projection_matrix); //Render all the objects. ComponentTexture* tex = nullptr; ComponentTexture* model_texture = nullptr; for (vector<ComponentMesh*>::iterator model = models.begin(); model != models.end(); ++model) { (*model)->Render(); //TODO: Improve this approach model_texture = texture; //Texture by default tex = (ComponentTexture*)(*model)->GetGameObject()->GetComponent(C_TEXTURE); if (tex) { if (tex->GetTexturePath().size() > 0) model_texture = tex; } texture_shader->Render(d3d->GetDeviceContext(), (*model)->GetIndexCount(), D3DXMATRIX((*model)->GetGameObject()->transform->GetGlobalMatrixTransposed().ptr()), view_matrix, projection_matrix, model_texture->GetTexture()); } ImGui::Render(); d3d->EndScene(); return update_status::UPDATE_CONTINUE; } float ModuleGraphics::GetScreenDepth() const { return screen_depth; } float ModuleGraphics::GetScreenNear() const { return screen_near; } bool ModuleGraphics::IsVsyncEnabled() const { return vsync_enabled; } void ModuleGraphics::AddToDraw(ComponentMesh * mesh) { if (mesh) { models.push_back(mesh); } }
[ "traguill1@gmail.com" ]
traguill1@gmail.com
5966e5fd02e80330e3eb01fc8fd200183cf459aa
86df6f8f4f3c03cccc96459ad82bcdf3bf942492
/leetcode/maximum-product-of-word-lengths.cc
ca221011c8dfe58ce14b77ad90986db75cfad1f1
[]
no_license
bdliyq/algorithm
369d1fd2ae3925a559ebae3fa8f5deab233daab1
e1c993a5d1531e1fb10cd3c8d686f533c9a5cbc8
refs/heads/master
2016-08-11T21:49:31.259393
2016-04-05T11:10:30
2016-04-05T11:10:30
44,576,582
0
0
null
null
null
null
UTF-8
C++
false
false
1,135
cc
// Question: https://leetcode.com/problems/maximum-product-of-word-lengths/ #include "headers.h" class Solution { public: int maxProduct(vector<string>& words) { int ans = 0; vector<int> dicts(words.size(), 0); for (int i = 0; i < words.size(); ++i) { for (char c : words[i]) { dicts[i] |= (1 << (c - 'a')); } } for (int i = 0; i < words.size(); ++i) { for (int j = 0; j < words.size(); ++j) { if (dicts[i] & dicts[j]) { continue; } ans = max(ans, (int)words[i].size() * (int)words[j].size()); } } return ans; } }; int main(int argc, char** argv) { Solution s; { vector<string> words{"abc", "a", "b", ""}; cout << s.maxProduct(words) << endl; } { vector<string> words{"abcw", "baz", "foo", "bar", "xtfn", "abcdef"}; cout << s.maxProduct(words) << endl; } { vector<string> words{"a", "aa", "aaa", "aaaa"}; cout << s.maxProduct(words) << endl; } return 0; }
[ "liyongqiang01@baidu.com" ]
liyongqiang01@baidu.com
6a63f9b3b4997c36c4f04572e26f9ec52d5b826b
f750e5825ae6bdc529ea885e8d0bf6e21ef4ebb3
/program_options.hpp
44dee498581f58de2665b3e88f239701f9c9bf24
[ "MIT" ]
permissive
liu0hy/program_options
3de304fbe316e022b34b0d03d4ac10c21c5276ad
f1f061dbccce6f5bc22b922e75f88a88a2839977
refs/heads/master
2021-01-17T05:28:32.919031
2016-08-03T12:43:21
2016-08-03T12:43:21
64,545,313
0
0
null
null
null
null
UTF-8
C++
false
false
21,165
hpp
#pragma once #include <algorithm> #include <cstdint> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <typeinfo> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> namespace program_options { using string_t = std::string; namespace detail { template <typename Target, typename Source, bool IsSame> class lexical_cast_t { public: static Target cast(Source&& arg) { Target ret; std::stringstream ss; if (!(ss << std::forward<Source>(arg) && ss >> ret && ss.eof())) throw std::bad_cast(); return ret; } }; template <typename Target, typename Source> class lexical_cast_t<Target, Source, true> { public: static Target cast(Source&& arg) { return std::forward<Source>(arg); } }; template <typename Target> class lexical_cast_t<Target, string_t, false> { public: static Target cast(string_t&& arg) { Target ret; std::istringstream ss(arg); if (!(ss >> ret && ss.eof())) throw std::bad_cast(); return ret; } }; template <typename Source> class lexical_cast_t<string_t, Source, false> { public: static string_t cast(Source&& arg) { std::ostringstream ss; if (!(ss << std::forward<Source>(arg))) throw std::bad_cast(); return ss.str(); } }; template <typename Target, typename Source> constexpr bool is_same_v = std::is_same<Target, Source>::value; template <typename Target, typename Source> Target lexical_cast(Source&& arg) { return lexical_cast_t<Target, Source, is_same_v<Target, Source>>::cast( std::forward<Source>(arg)); }; template <typename T> struct is_string : std::integral_constant< bool, is_same_v<string_t, typename std::remove_cv<T>::type>> {}; template <typename T> constexpr bool is_string_v = is_string<T>::value; template <typename T> string_t as_string(T&& arg) { string_t str{lexical_cast<string_t>(std::forward<T>(arg))}; if (is_string_v<std::remove_reference_t<T>>) { return "\"" + str + "\""; } else { return str; } } template <typename T> constexpr bool is_integral_v = std::is_integral<T>::value; template <typename T> constexpr bool is_floating_point_v = std::is_floating_point<T>::value; template <typename T> struct is_legal_type : std::integral_constant<bool, is_string_v<T> || is_integral_v<T> || is_floating_point_v<T>> {}; template <typename T> constexpr bool is_legal_type_v = is_legal_type<T>::value; enum class type_category { IllegalType = 0, Integral, FloatingPoint, String }; template <typename T, bool is_integral, bool is_floating_point, bool is_string> struct type_name_impl { static constexpr auto value = type_category::IllegalType; }; template <typename T> struct type_name_impl<T, true, false, false> { static constexpr auto value = type_category::Integral; }; template <typename T> struct type_name_impl<T, false, true, false> { static constexpr auto value = type_category::FloatingPoint; }; template <typename T> struct type_name_impl<T, false, false, true> { static constexpr auto value = type_category::String; }; #ifdef _MSC_VER using type_category_t = enum class type_category; #else using type_category_t = enum type_category; #endif template <typename T> string_t type_name() { static std::unordered_map<type_category_t, string_t> names { std::make_pair(type_category::IllegalType, "IllegalType"), std::make_pair(type_category::Integral, "Integral"), std::make_pair(type_category::FloatingPoint, "FloatingPoint"), std::make_pair(type_category::String, "String") }; auto category = type_name_impl<T, is_integral_v<T>, is_floating_point_v<T>, is_string_v<T>>::value; return names[category]; }; } // namespace detail class program_options_error : public std::exception { public: template <typename T> program_options_error(T&& msg) : msg_(std::forward<T>(msg)) {} const char* what() const noexcept { return msg_.c_str(); } private: string_t msg_; }; template <typename T> class default_reader { public: T operator()(const string_t& str) const { return detail::lexical_cast<T>(str); } }; template <typename T> class range_reader { public: range_reader(T&& begin, T&& end) : begin_(std::forward<T>(begin)), end_(std::forward<T>(end)) {} T operator()(const string_t& str) const { T ret{default_reader<T>()(str)}; if (ret > end_ || ret < begin_) throw program_options_error("range error"); return ret; } private: T begin_, end_; }; template <typename T> range_reader<T> range(T&& begin, T&& end) { return range_reader<T>(std::forward<T>(begin), std::forward<T>(end)); } template <typename T> class oneof_reader { public: T operator()(const string_t& str) { T ret{default_reader<T>()(str)}; if (allowed_.find(ret) == allowed_.end()) throw program_options_error("oneof error"); return ret; } void add(T&& val) { allowed_.insert(std::forward<T>(val)); } template <typename... U> void add(T&& val, U&&... vals) { allowed_.insert(std::forward<T>(val)); add(std::forward<U>(vals)...); } private: std::unordered_set<T> allowed_; }; template <typename T, typename... U> oneof_reader<T> oneof(U&&... vals) { oneof_reader<T> ret; ret.add(std::forward<U>(vals)...); return ret; } class parser { public: parser& add(const string_t& name, char short_name = 0, const string_t& description = "") { if (options_.count(name)) throw program_options_error("multiple definition: " + name); options_.insert( std::make_pair(name, option_ptr(new option_without_value( name, short_name, description)))); ordered_.push_back(options_.at(name)); return *this; } template <typename T> parser& add(const string_t& name, char short_name = 0, const string_t& description = "", bool is_required = true, T&& default_value = T()) { if (!detail::is_legal_type_v<T>) throw program_options_error("illegal type: " + name); return add(name, short_name, description, is_required, std::forward<T>(default_value), default_reader<T>()); } template <typename T, typename U> parser& add(const string_t& name, char short_name = 0, const string_t& description = "", bool is_required = true, T&& default_value = T(), U&& reader = U()) { if (!detail::is_legal_type_v<T>) throw program_options_error("illegal type: " + name); if (options_.count(name)) throw program_options_error("multiple definition: " + name); options_.insert(std::make_pair( name, option_ptr(new option_with_value_with_reader<T, U>( name, short_name, is_required, std::forward<T>(default_value), description, std::forward<U>(reader))))); ordered_.push_back(options_.at(name)); return *this; }; void set_footer(const string_t& footer) { footer_ = footer; } void set_program_name(const string_t& program_name) { program_name_ = program_name; } bool exist(const string_t& name) const { auto iter = options_.find(name); if (iter == options_.end()) throw program_options_error("there is no flag: --" + name); return iter->second->has_set(); } template <typename T> const T& get(const string_t& name) const { if (options_.count(name) == 0) throw program_options_error("there is no flag: --" + name); auto p = dynamic_cast<const option_with_value<T>*>( options_.find(name)->second.get()); if (p == nullptr) throw program_options_error("type mismatch flag '" + name + "'"); return p->get(); } const std::vector<string_t>& rest() const { return others_; } bool parse(const string_t& arg) { std::vector<string_t> args; string_t buf; bool in_quote{false}; for (string_t::size_type i = 0; i != arg.length(); ++i) { if (arg[i] == '\"') { in_quote = !in_quote; continue; } if (arg[i] == ' ' && !in_quote) { args.push_back(buf); buf.clear(); continue; } if (arg[i] == '\\') { ++i; if (i >= arg.length()) { errors_.emplace_back( "unexpected occurrence of '\\' at end of string"); return false; } } buf += arg[i]; } if (in_quote) { errors_.emplace_back("quote is not closed"); return false; } if (!buf.empty()) { args.push_back(buf); } return parse(args); } bool parse(const std::vector<string_t>& args) { auto argc = args.size(); std::vector<const char*> argv(argc); std::transform(args.begin(), args.end(), argv.begin(), [](const string_t& str) { return str.c_str(); }); return parse(argc, argv.data()); } bool parse(int argc, const char* const argv[]) { errors_.clear(); others_.clear(); if (argc < 1) { errors_.emplace_back("argument number must be longer than 0"); return false; } if (program_name_.empty()) { program_name_ = argv[0]; } std::unordered_map<char, string_t> lookup; for (auto& item : options_) { if (item.first.empty()) continue; char short_name{item.second->short_name()}; if (short_name) { if (lookup.count(short_name)) { lookup[short_name].clear(); errors_.push_back(string_t("short option '") + short_name + "' is ambiguous"); return false; } lookup[short_name] = item.first; } } for (int i = 1; i != argc; ++i) { if (strncmp(argv[i], "--", 2) == 0) { const char* p{strchr(argv[i] + 2, '=')}; if (p) { string_t name{argv[i] + 2, p}; string_t value{p + 1}; set_option(name, value); } else { string_t name{argv[i] + 2}; if (options_.count(name) == 0) { errors_.push_back("undefined option: --" + name); continue; } if (options_[name]->has_value()) { if (i + 1 >= argc) { errors_.push_back("option needs value: --" + name); continue; } else { set_option(name, argv[i++]); } } else { set_option(name); } } } else if (strncmp(argv[i], "-", 1) == 0) { if (!argv[i][1]) continue; char last{argv[i][1]}; for (int j = 2; argv[i][j]; ++j) { if (lookup.count(last) == 0) { errors_.push_back( string_t("undefined short option: -") + last); } else if (lookup[last].empty()) { errors_.push_back( string_t("ambiguous short options: -") + last); } else { set_option(lookup[last]); } last = argv[i][j]; } if (lookup.count(last) == 0) { errors_.push_back(string_t("undefined short option: -") + last); continue; } else if (lookup[last].empty()) { errors_.push_back(string_t("ambiguous short options: -") + last); continue; } if (i + 1 < argc && options_[lookup[last]]->has_value()) { set_option(lookup[last], argv[++i]); } else { set_option(lookup[last]); } } else { others_.push_back(argv[i]); } } for (auto& item : options_) { if (!item.second->is_valid()) { errors_.push_back("need option: --" + item.first); } } return errors_.empty(); } void parse_check(const string_t& arg) { if (!options_.count("help")) add("help", '?', "print this message"); check(0, parse(arg)); } void parse_check(const std::vector<string_t>& args) { if (!options_.count("help")) add("help", '?', "print this message"); check(args.size(), parse(args)); } void parse_check(int argc, const char* const argv[]) { if (!options_.count("help")) add("help", '?', "print this message"); check(argc, parse(argc, argv)); } string_t error() const { return errors_.empty() ? "" : errors_[0]; } string_t all_errors() const { std::ostringstream oss; for (auto& error : errors_) { oss << error << std::endl; } return oss.str(); } string_t usage() const { std::ostringstream oss; oss << "Usage: " << program_name_ << " "; for (auto& item : ordered_) { if (item->is_required()) oss << item->short_description() << " "; } oss << "[options] ... " << footer_ << std::endl; oss << "Options:" << std::endl; using length_t = decltype(ordered_)::size_type; length_t max_width{(*std::max_element(ordered_.begin(), ordered_.end(), [](const option_ptr& lhs, const option_ptr& rhs) { return lhs->name().length() < rhs->name().length(); })) ->name() .length()}; for (auto& item : ordered_) { if (item->short_name()) { oss << " -" << item->short_name() << ", "; } else { oss << " "; } oss << "--" << item->name(); for (length_t j = item->name().length(); j != max_width + 4; ++j) oss << ' '; oss << item->description() << std::endl; } return oss.str(); } private: void check(int argc, bool ok) { if ((argc == 1 && !ok) || exist("help")) { std::cerr << usage(); exit(0); } if (!ok) { std::cerr << error() << std::endl << usage(); exit(-1); } } void set_option(const string_t& name) { if (options_.count(name) == 0) { errors_.push_back("undefined options: --" + name); return; } if (!options_[name]->set()) { errors_.push_back("option needs value: --" + name); return; } } void set_option(const string_t& name, const string_t& value) { if (options_.count(name) == 0) { errors_.push_back("undefined options: --" + name); return; } if (!options_[name]->set(value)) { errors_.push_back("option value is invalid: --" + name + "=" + value); return; } } class option_base { public: virtual ~option_base() = default; virtual bool has_value() const = 0; virtual bool set() = 0; virtual bool set(const string_t& value) = 0; virtual bool has_set() const = 0; virtual bool is_valid() const = 0; virtual bool is_required() const = 0; virtual const string_t& name() const = 0; virtual char short_name() const = 0; virtual const string_t& description() const = 0; virtual string_t short_description() const = 0; }; class option_without_value : public option_base { public: option_without_value(const string_t& name, char short_name, const string_t& description) : name_(name), short_name_(short_name), description_(description), has_set_(false) {} virtual bool has_value() const override { return false; } virtual bool set() override { return (has_set_ = true); } virtual bool set(const string_t&) override { return false; } virtual bool has_set() const override { return has_set_; } virtual bool is_valid() const override { return true; } virtual bool is_required() const override { return false; } virtual const string_t& name() const override { return name_; } virtual char short_name() const override { return short_name_; } virtual const string_t& description() const override { return description_; } virtual string_t short_description() const override { return "--" + name_; } private: string_t name_; char short_name_; string_t description_; bool has_set_; }; template <typename T> class option_with_value : public option_base { public: option_with_value(const string_t& name, char short_name, bool is_required, const T& default_value, const string_t& description) : name_(name), short_name_(short_name), is_required_(is_required), has_set_(false), default_value_(default_value), actual_value_(default_value), description_(full_description(description)) {} const T& get() const { return actual_value_; } virtual bool has_value() const override { return true; } virtual bool set() override { return false; } virtual bool set(const string_t& value) override { try { actual_value_ = read(value); } catch (const std::exception&) { return false; } return has_set_ = true; } virtual bool has_set() const override { return has_set_; } virtual bool is_valid() const override { return (!is_required_) || has_set_; } virtual bool is_required() const override { return is_required_; } virtual const string_t& name() const override { return name_; } virtual char short_name() const override { return short_name_; } virtual const string_t& description() const override { return description_; } virtual string_t short_description() const override { return "--" + name_ + "=" + detail::type_name<T>(); } protected: string_t full_description(const string_t& description) { return description + " (" + detail::type_name<T>() + (is_required_ ? "" : (" [=" + detail::as_string(default_value_) + "]")) + ")"; } virtual T read(const string_t& str) = 0; string_t name_; char short_name_; bool is_required_; bool has_set_; T default_value_; T actual_value_; string_t description_; }; template <typename T, typename U> class option_with_value_with_reader : public option_with_value<T> { public: option_with_value_with_reader(const string_t& name, char short_name, bool is_required, const T& default_value, const string_t& description, U&& reader) : option_with_value<T>(name, short_name, is_required, default_value, description), reader_(std::forward<U>(reader)) {} private: T read(const string_t& str) { return reader_(str); } U reader_; }; using option_ptr = std::shared_ptr<option_base>; std::unordered_map<string_t, option_ptr> options_; std::vector<option_ptr> ordered_; string_t footer_; string_t program_name_; std::vector<string_t> others_; std::vector<string_t> errors_; }; } // namespace program_options
[ "liu0hy@gmail.com" ]
liu0hy@gmail.com
ba60416a0279de5d069637eb5a960155adc3b5de
1edf31363b3da6083d729bef8e4a9c1b50eda821
/Backups/challenge_1.1.cpp
3fadcf32db0eba1b2e2c9932262e50e282a79f62
[]
no_license
bozender/HW2
8e09d39c49651fefcce79ba1cac1e59ffe9e6410
9c81674703ebe943f1d960dd6f4ef80f23ced5b6
refs/heads/main
2023-02-13T13:49:58.253752
2021-01-16T23:04:00
2021-01-16T23:04:00
328,737,465
0
0
null
null
null
null
UTF-8
C++
false
false
3,349
cpp
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> using namespace std; //DECLARATIONS void calculate(string a, vector<string> &vec1, vector<int> &vec2); inline int add(int a, int b){ return a+b;} int search(string, vector<string>&); void assign(int, int, vector<int>&); int main(){ vector<string> variable_names; vector<int> variable_values; stringstream stream; string input_string; ifstream InputFile("deneme.inp"); ofstream TempFile("temp.inp"); while(getline(InputFile, input_string)){ string temp; stream.clear(); stream.str(input_string); while(stream >> temp){ TempFile<<temp; } TempFile<<endl; } InputFile.close(); InputFile.open("temp.inp"); while(getline(InputFile, input_string)){ calculate(input_string, variable_names, variable_values); } system("PAUSE"); } void calculate(string a, vector<string> &vec1, vector<int> &vec2){ ofstream OutputFile("deneme.out"); if(a.find('=') != string::npos){ string left_side = a.substr(0, a.find('+')); string right_side = a.substr(a.find('=') + 1, a.length()-1); //created streams to turn strings into integer in places necessary stringstream left_stream; left_stream.clear(); stringstream right_stream; right_stream.clear(); if(search(left_side, vec1) == -1){//assign left side of string as a variable if it does not already exist vec1.push_back(left_side); } if(right_side.find('+') != string::npos){ string left_of_plus = right_side.substr(0, right_side.find('+'));//separate the values at left and right of the '+' string right_of_plus = right_side.substr(right_side.find('+') + 1, right_side.length()-1); int index_left_of_plus = search(left_of_plus, vec1); int index_right_of_plus = search(right_of_plus, vec1); cout<<left_of_plus<<endl; cout<<right_of_plus<<endl; cout<<index_left_of_plus<<endl; cout<<index_right_of_plus<<endl; /* if(index_left_of_plus != -1 && index_right_of_plus != -1){ vec2[search(right_side, vec1)] = add(vec2[index_left_of_plus], vec2[index_right_of_plus]); } else if(index_left_of_plus == -1 && index_right_of_plus != -1){ vec2[search(right_side, vec1)] = add(stoi(left_of_plus), vec2[index_right_of_plus]); } else if(index_left_of_plus!= -1 && index_right_of_plus == -1){ vec2[search(right_side, vec1)] = add(vec2[index_left_of_plus], stoi(right_of_plus)); } else{ vec2[search(right_side, vec1)] = add(stoi(left_of_plus), stoi(right_of_plus)); }*/ } } if(a.find("OUT") != string::npos){ string output_str = a.substr(a.find("OUT") + 3, a.length()-1); cout<<output_str; OutputFile<<output_str<<endl; } OutputFile.close(); } void assign(int index, int value, vector<int>& vec){ vec[index] = value; } int search(string a, vector<string> &vec){ for(int i = 0; i < vec.size(); i++){ if(vec[i]==a){ return i; } } return -1; }
[ "b.ozender59@gmail.com" ]
b.ozender59@gmail.com
12638cd82685a745e15788d7ad43d726d059ef1b
7463b590abe4afd9d5987ff478901694236acd9b
/ana/PwbAsm.cxx
e8cee862e944a847f168dd209ebd2e33ab6a813a
[]
no_license
Estifaa/Laseranalysis
04b659e90133c9768faeca5d2db6b63599caf1c4
7f32688031870b20c9cf9306e846d486f16c73f9
refs/heads/master
2020-03-29T20:51:42.548557
2018-09-30T20:23:22
2018-09-30T20:23:22
150,335,243
0
1
null
2018-09-30T14:05:21
2018-09-25T22:10:17
C++
UTF-8
C++
false
false
38,579
cxx
// // Unpacking PWB data // K.Olchanski // #include "PwbAsm.h" #include <stdio.h> // NULL, printf() #include <math.h> // fabs() #include <assert.h> // assert() /* crc32c.c -- compute CRC-32C using the Intel crc32 instruction * Copyright (C) 2013 Mark Adler * Version 1.1 1 Aug 2013 Mark Adler */ #ifndef CRC32C_INCLUDE #define CRC32C_INCLUDE #include <stdint.h> #include <string.h> uint32_t crc32c_hw(uint32_t crc, const void *buf, size_t len); uint32_t crc32c_sw(uint32_t crc, const void *buf, size_t len); uint32_t crc32c(uint32_t crc, const void *buf, size_t len); #endif // CRC32C code taken from // http://stackoverflow.com/questions/17645167/implementing-sse-4-2s-crc32c-in-software/17646775#17646775 // on 29 July 2015 // // See also: // https://tools.ietf.org/html/rfc3309 // https://tools.ietf.org/html/rfc3720#appendix-B.4 // and // http://stackoverflow.com/questions/20963944/test-vectors-for-crc32c // //#include "crc32c.h" #ifdef __SSE__ #define HAVE_HWCRC32C 1 #endif /* crc32c.c -- compute CRC-32C using the Intel crc32 instruction * Copyright (C) 2013 Mark Adler * Version 1.1 1 Aug 2013 Mark Adler */ /* This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Mark Adler madler@alumni.caltech.edu */ /* Use hardware CRC instruction on Intel SSE 4.2 processors. This computes a CRC-32C, *not* the CRC-32 used by Ethernet and zip, gzip, etc. A software version is provided as a fall-back, as well as for speed comparisons. */ /* Version history: 1.0 10 Feb 2013 First version 1.1 1 Aug 2013 Correct comments on why three crc instructions in parallel */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <pthread.h> /* CRC-32C (iSCSI) polynomial in reversed bit order. */ #define POLY 0x82f63b78 /* Table for a quadword-at-a-time software crc. */ static pthread_once_t crc32c_once_sw = PTHREAD_ONCE_INIT; static uint32_t crc32c_table[8][256]; /* Construct table for software CRC-32C calculation. */ static void crc32c_init_sw(void) { uint32_t n, crc, k; for (n = 0; n < 256; n++) { crc = n; crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1; crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1; crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1; crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1; crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1; crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1; crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1; crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1; crc32c_table[0][n] = crc; } for (n = 0; n < 256; n++) { crc = crc32c_table[0][n]; for (k = 1; k < 8; k++) { crc = crc32c_table[0][crc & 0xff] ^ (crc >> 8); crc32c_table[k][n] = crc; } } } /* Table-driven software version as a fall-back. This is about 15 times slower than using the hardware instructions. This assumes little-endian integers, as is the case on Intel processors that the assembler code here is for. */ uint32_t crc32c_sw(uint32_t crci, const void *buf, size_t len) { const unsigned char *next = (const unsigned char*)buf; uint64_t crc; pthread_once(&crc32c_once_sw, crc32c_init_sw); crc = crci ^ 0xffffffff; while (len && ((uintptr_t)next & 7) != 0) { crc = crc32c_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8); len--; } while (len >= 8) { crc ^= *(uint64_t *)next; crc = crc32c_table[7][crc & 0xff] ^ crc32c_table[6][(crc >> 8) & 0xff] ^ crc32c_table[5][(crc >> 16) & 0xff] ^ crc32c_table[4][(crc >> 24) & 0xff] ^ crc32c_table[3][(crc >> 32) & 0xff] ^ crc32c_table[2][(crc >> 40) & 0xff] ^ crc32c_table[1][(crc >> 48) & 0xff] ^ crc32c_table[0][crc >> 56]; next += 8; len -= 8; } while (len) { crc = crc32c_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8); len--; } return (uint32_t)crc ^ 0xffffffff; } /* Multiply a matrix times a vector over the Galois field of two elements, GF(2). Each element is a bit in an unsigned integer. mat must have at least as many entries as the power of two for most significant one bit in vec. */ static inline uint32_t gf2_matrix_times(uint32_t *mat, uint32_t vec) { uint32_t sum; sum = 0; while (vec) { if (vec & 1) sum ^= *mat; vec >>= 1; mat++; } return sum; } /* Multiply a matrix by itself over GF(2). Both mat and square must have 32 rows. */ static inline void gf2_matrix_square(uint32_t *square, uint32_t *mat) { int n; for (n = 0; n < 32; n++) square[n] = gf2_matrix_times(mat, mat[n]); } #ifdef HAVE_HWCRC32C /* Construct an operator to apply len zeros to a crc. len must be a power of two. If len is not a power of two, then the result is the same as for the largest power of two less than len. The result for len == 0 is the same as for len == 1. A version of this routine could be easily written for any len, but that is not needed for this application. */ static void crc32c_zeros_op(uint32_t *even, size_t len) { int n; uint32_t row; uint32_t odd[32]; /* odd-power-of-two zeros operator */ /* put operator for one zero bit in odd */ odd[0] = POLY; /* CRC-32C polynomial */ row = 1; for (n = 1; n < 32; n++) { odd[n] = row; row <<= 1; } /* put operator for two zero bits in even */ gf2_matrix_square(even, odd); /* put operator for four zero bits in odd */ gf2_matrix_square(odd, even); /* first square will put the operator for one zero byte (eight zero bits), in even -- next square puts operator for two zero bytes in odd, and so on, until len has been rotated down to zero */ do { gf2_matrix_square(even, odd); len >>= 1; if (len == 0) return; gf2_matrix_square(odd, even); len >>= 1; } while (len); /* answer ended up in odd -- copy to even */ for (n = 0; n < 32; n++) even[n] = odd[n]; } /* Take a length and build four lookup tables for applying the zeros operator for that length, byte-by-byte on the operand. */ static void crc32c_zeros(uint32_t zeros[][256], size_t len) { uint32_t n; uint32_t op[32]; crc32c_zeros_op(op, len); for (n = 0; n < 256; n++) { zeros[0][n] = gf2_matrix_times(op, n); zeros[1][n] = gf2_matrix_times(op, n << 8); zeros[2][n] = gf2_matrix_times(op, n << 16); zeros[3][n] = gf2_matrix_times(op, n << 24); } } #endif /* Apply the zeros operator table to crc. */ static inline uint32_t crc32c_shift(uint32_t zeros[][256], uint32_t crc) { return zeros[0][crc & 0xff] ^ zeros[1][(crc >> 8) & 0xff] ^ zeros[2][(crc >> 16) & 0xff] ^ zeros[3][crc >> 24]; } /* Block sizes for three-way parallel crc computation. LONG and SHORT must both be powers of two. The associated string constants must be set accordingly, for use in constructing the assembler instructions. */ #define LONG 8192 #define LONGx1 "8192" #define LONGx2 "16384" #define SHORT 256 #define SHORTx1 "256" #define SHORTx2 "512" #ifdef HAVE_HWCRC32C /* Tables for hardware crc that shift a crc by LONG and SHORT zeros. */ static pthread_once_t crc32c_once_hw = PTHREAD_ONCE_INIT; static uint32_t crc32c_long[4][256]; static uint32_t crc32c_short[4][256]; /* Initialize tables for shifting crcs. */ static void crc32c_init_hw(void) { crc32c_zeros(crc32c_long, LONG); crc32c_zeros(crc32c_short, SHORT); } /* Compute CRC-32C using the Intel hardware instruction. */ uint32_t crc32c_hw(uint32_t crc, const void *buf, size_t len) { const unsigned char *next = (const unsigned char*)buf; const unsigned char *end; uint64_t crc0, crc1, crc2; /* need to be 64 bits for crc32q */ /* populate shift tables the first time through */ pthread_once(&crc32c_once_hw, crc32c_init_hw); /* pre-process the crc */ crc0 = crc ^ 0xffffffff; /* compute the crc for up to seven leading bytes to bring the data pointer to an eight-byte boundary */ while (len && ((uintptr_t)next & 7) != 0) { __asm__("crc32b\t" "(%1), %0" : "=r"(crc0) : "r"(next), "0"(crc0)); next++; len--; } /* compute the crc on sets of LONG*3 bytes, executing three independent crc instructions, each on LONG bytes -- this is optimized for the Nehalem, Westmere, Sandy Bridge, and Ivy Bridge architectures, which have a throughput of one crc per cycle, but a latency of three cycles */ while (len >= LONG*3) { crc1 = 0; crc2 = 0; end = next + LONG; do { __asm__("crc32q\t" "(%3), %0\n\t" "crc32q\t" LONGx1 "(%3), %1\n\t" "crc32q\t" LONGx2 "(%3), %2" : "=r"(crc0), "=r"(crc1), "=r"(crc2) : "r"(next), "0"(crc0), "1"(crc1), "2"(crc2)); next += 8; } while (next < end); crc0 = crc32c_shift(crc32c_long, crc0) ^ crc1; crc0 = crc32c_shift(crc32c_long, crc0) ^ crc2; next += LONG*2; len -= LONG*3; } /* do the same thing, but now on SHORT*3 blocks for the remaining data less than a LONG*3 block */ while (len >= SHORT*3) { crc1 = 0; crc2 = 0; end = next + SHORT; do { __asm__("crc32q\t" "(%3), %0\n\t" "crc32q\t" SHORTx1 "(%3), %1\n\t" "crc32q\t" SHORTx2 "(%3), %2" : "=r"(crc0), "=r"(crc1), "=r"(crc2) : "r"(next), "0"(crc0), "1"(crc1), "2"(crc2)); next += 8; } while (next < end); crc0 = crc32c_shift(crc32c_short, crc0) ^ crc1; crc0 = crc32c_shift(crc32c_short, crc0) ^ crc2; next += SHORT*2; len -= SHORT*3; } /* compute the crc on the remaining eight-byte units less than a SHORT*3 block */ end = next + (len - (len & 7)); while (next < end) { __asm__("crc32q\t" "(%1), %0" : "=r"(crc0) : "r"(next), "0"(crc0)); next += 8; } len &= 7; /* compute the crc for up to seven trailing bytes */ while (len) { __asm__("crc32b\t" "(%1), %0" : "=r"(crc0) : "r"(next), "0"(crc0)); next++; len--; } /* return a post-processed crc */ return (uint32_t)crc0 ^ 0xffffffff; } /* Check for SSE 4.2. SSE 4.2 was first supported in Nehalem processors introduced in November, 2008. This does not check for the existence of the cpuid instruction itself, which was introduced on the 486SL in 1992, so this will fail on earlier x86 processors. cpuid works on all Pentium and later processors. */ #define SSE42(have) \ do { \ uint32_t eax, ecx; \ eax = 1; \ __asm__("cpuid" \ : "=c"(ecx) \ : "a"(eax) \ : "%ebx", "%edx"); \ (have) = (ecx >> 20) & 1; \ } while (0) #endif // HAVE_HWCRC32C /* Compute a CRC-32C. If the crc32 instruction is available, use the hardware version. Otherwise, use the software version. */ uint32_t crc32c(uint32_t crc, const void *buf, size_t len) { #ifdef HAVE_HWCRC32C int sse42; SSE42(sse42); return sse42 ? crc32c_hw(crc, buf, len) : crc32c_sw(crc, buf, len); #else #warning Hardware accelerated CRC32C is not available. return crc32c_sw(crc, buf, len); #endif // HAVE_HWCRC32C } #ifdef TEST #define SIZE (262144*3) #define CHUNK SIZE int main(int argc, char **argv) { char *buf; ssize_t got; size_t off, n; uint32_t crc; (void)argv; crc = 0; buf = (char*)malloc(SIZE); if (buf == NULL) { fputs("out of memory", stderr); return 1; } while ((got = read(0, buf, SIZE)) > 0) { off = 0; do { n = (size_t)got - off; if (n > CHUNK) n = CHUNK; crc = argc > 1 ? crc32c_sw(crc, buf + off, n) : crc32c(crc, buf + off, n); off += n; } while (off < (size_t)got); } free(buf); if (got == -1) { fputs("read error\n", stderr); return 1; } printf("%08x\n", crc); return 0; } #endif /* TEST */ PwbUdpPacket::PwbUdpPacket(const char* ptr, int size) // ctor { const uint32_t* p32 = (const uint32_t*)ptr; int n32 = size/4; fError = false; fPacketSize = size; if (n32 < 6) { fError = true; printf("PwbUdpPacket: Error: invalid value of n32: %d\n", n32); return; } uint32_t crc = crc32c(0, ptr+0, 4*4); DEVICE_ID = p32[0]; PKT_SEQ = p32[1]; CHANNEL_SEQ = (p32[2] >> 0) & 0xFFFF; CHANNEL_ID = (p32[2] >> 16) & 0xFF; FLAGS = (p32[2] >> 24) & 0xFF; CHUNK_ID = (p32[3] >> 0) & 0xFFFF; CHUNK_LEN = (p32[3] >> 16) & 0xFFFF; HEADER_CRC = p32[4]; start_of_payload = 5*4; end_of_payload = start_of_payload + CHUNK_LEN; if (HEADER_CRC != ~crc) { printf("PwbUdpPacket: Error: header CRC mismatch: HEADER_CRC 0x%08x, computed 0x%08x\n", HEADER_CRC, ~crc); fError = true; return; } if (end_of_payload + 4 > fPacketSize) { printf("PwbUdpPacket: Error: invalid byte counter, end_of_payload %d, packet size %d\n", end_of_payload, fPacketSize); fError = true; return; } payload_crc = p32[end_of_payload/4]; uint32_t payload_crc_ours = crc32c(0, ptr+start_of_payload, CHUNK_LEN); if (payload_crc != ~payload_crc_ours) { printf("PwbUdpPacket: Error: payload CRC mismatch: CRC 0x%08x, computed 0x%08x\n", payload_crc, ~payload_crc_ours); fError = true; return; } } void PwbUdpPacket::Print() const { printf("PwbUdpPacket: DEVICE_ID 0x%08x, PKT_SEQ 0x%08x, CHAN SEQ 0x%02x, ID 0x%02x, FLAGS 0x%02x, CHUNK ID 0x%04x, LEN 0x%04x, CRC 0x%08x, bank bytes %d, end of payload %d, CRC 0x%08x\n", DEVICE_ID, PKT_SEQ, ((int)CHANNEL_SEQ)&0xFFFF, CHANNEL_ID, FLAGS, CHUNK_ID, CHUNK_LEN, HEADER_CRC, fPacketSize, end_of_payload, payload_crc); }; PwbEventHeader::PwbEventHeader(const char* ptr, int size) { const uint32_t* p32 = (const uint32_t*)ptr; int nw32 = size/4; if (nw32 < 16) { printf("PwbEventHeader::ctor: Error: event header size %d words is too small\n", nw32); fError = true; return; } fError = false; FormatRevision = (p32[5]>> 0) & 0xFF; ScaId = (p32[5]>> 8) & 0xFF; CompressionType = (p32[5]>>16) & 0xFF; TriggerSource = (p32[5]>>24) & 0xFF; if (FormatRevision == 0) { HardwareId1 = p32[6]; HardwareId2 = (p32[7]>> 0) & 0xFFFF; TriggerDelay = (p32[7]>>16) & 0xFFFF; // NB timestamp clock is 125 MHz TriggerTimestamp1 = p32[8]; TriggerTimestamp2 = (p32[9]>> 0) & 0xFFFF; Reserved1 = (p32[9]>>16) & 0xFFFF; ScaLastCell = (p32[10]>> 0) & 0xFFFF; ScaSamples = (p32[10]>>16) & 0xFFFF; ScaChannelsSent1 = p32[11]; ScaChannelsSent2 = p32[12]; ScaChannelsSent3 = (p32[13]>> 0) & 0xFF; ScaChannelsThreshold1 = (p32[13]>> 8) & 0xFFFFFF; ScaChannelsThreshold2 = p32[14]; ScaChannelsThreshold3 = p32[15] & 0xFFFF; Reserved2 = (p32[15]>>16) & 0xFFFF; start_of_data = 16*4; } else if (FormatRevision == 1) { HardwareId1 = p32[6]; HardwareId2 = (p32[7]>> 0) & 0xFFFF; TriggerDelay = (p32[7]>>16) & 0xFFFF; // NB timestamp clock is 125 MHz TriggerTimestamp1 = p32[8]; TriggerTimestamp2 = (p32[9]>> 0) & 0xFFFF; Reserved1 = (p32[9]>>16) & 0xFFFF; ScaLastCell = (p32[10]>> 0) & 0xFFFF; ScaSamples = (p32[10]>>16) & 0xFFFF; ScaChannelsSent1 = p32[11]; ScaChannelsSent2 = p32[12]; ScaChannelsSent3 = (p32[13]>> 0) & 0xFFFF; ScaChannelsThreshold1 = (p32[13]>>16) & 0xFFFF; ScaChannelsThreshold1 |= ((p32[14] & 0xFFFF) << 16) & 0xFFFF0000; ScaChannelsThreshold2 = (p32[14]>>16) & 0xFFFF; ScaChannelsThreshold2 |= ((p32[15] & 0xFFFF) << 16) & 0xFFFF0000; ScaChannelsThreshold3 = (p32[15]>>16) & 0xFFFF; Reserved2 = 0; start_of_data = 16*4; } else { printf("PwbEventHeader::ctor: Error: invalid FormatRevision %d, expected 0 or 1\n", FormatRevision); fError = true; } } void PwbEventHeader::Print() const { if (1) { printf("PwbEventHeader: F 0x%02x, Sca 0x%02x, C 0x%02x, T 0x%02x, H 0x%08x, 0x%04x, Delay 0x%04x, TS 0x%08x, 0x%04x, R1 0x%04x, SCA LastCell 0x%04x, Samples 0x%04x, Sent 0x%08x 0x%08x 0x%08x, Thr 0x%08x 0x%08x 0x%08x, R2 0x%04x\n", FormatRevision, ScaId, CompressionType, TriggerSource, HardwareId1, HardwareId2, TriggerDelay, TriggerTimestamp1, TriggerTimestamp2, Reserved1, ScaLastCell, ScaSamples, ScaChannelsSent1, ScaChannelsSent2, ScaChannelsSent3, ScaChannelsThreshold1, ScaChannelsThreshold2, ScaChannelsThreshold3, Reserved2); } if (0) { printf("S Sca 0x%02x, TS 0x%08x, 0x%04x, SCA LastCell 0x%04x, Samples 0x%04x\n", ScaId, TriggerTimestamp1, TriggerTimestamp2, ScaLastCell, ScaSamples); } } #define PWB_CA_ST_ERROR -1 #define PWB_CA_ST_INIT 0 #define PWB_CA_ST_DATA 1 #define PWB_CA_ST_LAST 2 static bool gTrace = false; PwbChannelAsm::PwbChannelAsm(int module, int column, int ring, int sca) // ctor { fTrace = gTrace; fModule = module; fColumn = column; fRing = ring; fSca = sca; Reset(); } PwbChannelAsm::~PwbChannelAsm() // dtor { if (fCountErrors) { printf("PwbChannelAsm: module %d sca %d: %d errors\n", fModule, fSca, fCountErrors); } } void PwbChannelAsm::Reset() { fLast_CHANNEL_SEQ = 0; fState = 0; fSaveChannel = 0; fSaveSamples = 0; fSaveNw = 0; fSavePos = 0; if (fCurrent) { delete fCurrent; fCurrent = NULL; } for (unsigned i=0; i<fOutput.size(); i++) { if (fOutput[i]) { delete fOutput[i]; fOutput[i] = NULL; } } } void PwbChannelAsm::AddSamples(int channel, const uint16_t* samples, int count) { const int16_t* signed_samples = (const int16_t*)samples; int ri = -1; if (fFormatRevision == 0) { ri = channel + 1; } else if (fFormatRevision == 1) { ri = channel; } else { printf("PwbChannelAsm::AddSamples: Error: module %d sca %d state %d: invalid FormatRevision %d\n", fModule, fSca, fState, fFormatRevision); fCountErrors++; fState = PWB_CA_ST_ERROR; fError = true; return; } if (fTrace) { printf("pwb module %d, sca %d, channel %d, ri %d, add %d samples\n", fModule, fSca, channel, ri, count); } if (fCurrent) { if (ri != fCurrent->sca_readout) { fOutput.push_back(fCurrent); fCurrent = NULL; } } if (!fCurrent) { fCurrent = new FeamChannel; fCurrent->imodule = fModule; fCurrent->pwb_column = fColumn; fCurrent->pwb_ring = fRing; fCurrent->sca = fSca; fCurrent->sca_readout = ri; fCurrent->sca_chan = 0; // filled by Build() fCurrent->threshold_bit = 0; // filled by Build() fCurrent->pad_col = 0; // filled by Build() fCurrent->pad_row = 0; // filled by Build() fCurrent->first_bin = 0; } for (int i=0; i<count; i++) { fCurrent->adc_samples.push_back(signed_samples[i]); } if (0) { if (fSca == 0 && ri==1) { printf("pwb module %d, sca %d, channel %d, ri %d, add %d samples: \n", fModule, fSca, channel, ri, count); for (int i=0; i<count; i++) { printf(" %4d", signed_samples[i]); } printf("\n"); } } } void PwbChannelAsm::CopyData(const uint16_t* s, const uint16_t* e) { const uint16_t* p = s; while (1) { int r = e-p; if (r < 2) { printf("PwbChannelAsm::CopyData: module %d sca %d state %d: Error: need to en-buffer a partial header, r: %d!\n", fModule, fSca, fState, r); fCountErrors++; break; } if (p[0] == 0xCCCC && p[1] == 0xCCCC && r == 2) { printf("PwbChannelAsm::CopyData: module %d sca %d: ignoring unexpected 0xCCCC words at the end of a packet\n", fModule, fSca); //fCountErrors++; break; } if (p[0] == 0xCCCC && p[1] == 0xCCCC) { printf("PwbChannelAsm::CopyData: module %d sca %d state %d: Error: unexpected 0xCCCC words, r %d!\n", fModule, fSca, fState, r); fCountErrors++; break; } int channel = p[0]; int samples = p[1]; if (channel < 0 || channel >= 80) { printf("PwbChannelAsm::CopyData: module %d sca %d state %d: Error: invalid channel %d\n", fModule, fSca, fState, channel); fCountErrors++; } if (samples != 511) { printf("PwbChannelAsm::CopyData: module %d sca %d state %d: Error: invalid number of samples %d\n", fModule, fSca, fState, samples); fCountErrors++; } int nw = samples; if (samples&1) nw+=1; if (nw <= 0) { printf("PwbChannelAsm::CopyData: module %d sca %d state %d: Error: invalid word counter nw: %d\n", fModule, fSca, fState, nw); fCountErrors++; break; } if (fTrace) { printf("adc samples ptr %d, end %d, r %d, channel %d, samples %d, nw %d\n", (int)(p-s), (int)(e-s), r, channel, samples, nw); } p += 2; r = e-p; int h = nw; int s = samples; bool truncated = false; if (nw > r) { h = r; s = r; if (fTrace) { printf("split data nw %d, with %d here, %d to follow\n", nw, h, nw-h); } fSaveChannel = channel; fSaveSamples = samples; fSaveNw = nw; fSavePos = h; truncated = true; } AddSamples(channel, p, s); p += h; if (truncated) { assert(p == e); break; } if (p == e) { break; } } } void PwbChannelAsm::BeginData(const char* ptr, int size, int start_of_data, int end_of_data, uint32_t ts) { fTs = ts; const uint16_t* s = (const uint16_t*)(ptr+start_of_data); const uint16_t* e = (const uint16_t*)(ptr+end_of_data); CopyData(s, e); } void PwbChannelAsm::AddData(const char* ptr, int size, int start_of_data, int end_of_data) { const uint16_t* s = (const uint16_t*)(ptr+start_of_data); const uint16_t* e = (const uint16_t*)(ptr+end_of_data); const uint16_t* p = s; if (fSaveNw > 0) { int r = (e-p); int h = fSaveNw - fSavePos; int s = fSaveSamples - fSavePos; bool truncated = false; if (h > r) { h = r; s = r; truncated = true; } if (fTrace) { printf("AddData: save channel %d, samples %d, nw %d, pos %d, remaining %d, have %d, truncated %d\n", fSaveChannel, fSaveSamples, fSaveNw, fSavePos, r, h, truncated); } AddSamples(fSaveChannel, p, s); if (!truncated) { fSaveChannel = 0; fSaveSamples = 0; fSaveNw = 0; fSavePos = 0; } p += h; } if (p < e) { CopyData(p, e); } else if (p == e) { // good, no more data in this packet } else { printf("PwbChannelAsm::AddData: module %d sca %d state %d: Error!\n", fModule, fSca, fState); assert(!"this cannot happen"); } } void PwbChannelAsm::EndData() { if (fSaveNw > 0) { if (fState != PWB_CA_ST_ERROR) { printf("PwbChannelAsm::EndData: module %d sca %d state %d: Error: missing some data at the end\n", fModule, fSca, fState); fCountErrors++; fState = PWB_CA_ST_ERROR; fError = true; } else { if (fTrace) { printf("PwbChannelAsm::EndData: module %d sca %d state %d: Error: missing some data at the end\n", fModule, fSca, fState); } } } else { if (fTrace) { printf("PwbChannelAsm::EndData: ok!\n"); } } fSaveChannel = 0; fSaveSamples = 0; fSaveNw = 0; fSavePos = 0; if (fCurrent) { fOutput.push_back(fCurrent); fCurrent = NULL; } if (fTrace) { PrintFeamChannels(fOutput); } } void PwbChannelAsm::BuildEvent(FeamEvent* e) { if (!CheckComplete()) { EndData(); } if (fError) { e->error = true; } bool present[MAX_FEAM_READOUT]; for (int i=0; i<MAX_FEAM_READOUT; i++) { present[i] = false; } for (unsigned i=0; i<fOutput.size(); i++) { if (fOutput[i]) { FeamChannel* c = fOutput[i]; fOutput[i] = NULL; // FIXME: bad data from PWB!!! if (c->sca_readout >= MAX_FEAM_READOUT) { printf("PwbChannelAsm::BuildEvent: module %d sca %d state %d: Error: skipping invalid channel, sca_readout: %d\n", fModule, fSca, fState, c->sca_readout); delete c; e->error = true; fCountErrors++; continue; } if (present[c->sca_readout]) { printf("PwbChannelAsm::BuildEvent: module %d sca %d state %d: Error: skipping duplicate channel, sca_readout: %d\n", fModule, fSca, fState, c->sca_readout); delete c; e->error = true; fCountErrors++; continue; } present[c->sca_readout] = true; if (fFormatRevision == 1) { unsigned i = c->sca_readout-1; unsigned iword = i/32; unsigned ibit = i%32; bool tbit = false; if (iword==0) tbit = fScaChannelsThreshold1 & (1<<ibit); else if (iword==1) tbit = fScaChannelsThreshold2 & (1<<ibit); else tbit = fScaChannelsThreshold3 & (1<<ibit); if (tbit) c->threshold_bit = 1; else c->threshold_bit = 0; } c->sca_chan = PwbPadMap::Map()->channel[c->sca_readout]; bool scachan_is_pad = (c->sca_chan > 0); //bool scachan_is_fpn = (c->sca_chan >= -4) && (c->sca_chan <= -1); if (scachan_is_pad) { c->pad_col = PwbPadMap::Map()->padcol[c->sca][c->sca_chan]; c->pad_row = PwbPadMap::Map()->padrow[c->sca][c->sca_chan]; } e->hits.push_back(c); } } fOutput.clear(); // verify against the ScaChannelsSent bitmap if (fFormatRevision == 1 && fState != PWB_CA_ST_ERROR) { for (unsigned i=0; i<79; i++) { int ri = i+1; assert(ri < MAX_FEAM_READOUT); unsigned iword = i/32; unsigned ibit = i%32; bool rbit = false; if (iword==0) rbit = fScaChannelsSent1 & (1<<ibit); else if (iword==1) rbit = fScaChannelsSent2 & (1<<ibit); else rbit = fScaChannelsSent3 & (1<<ibit); if (present[ri] != rbit) { printf("PwbChannelAsm::BuildEvent: module %d sca %d state %d: Error: ScaChannelsSent bitmap mismatch: channel %d present %d vs %d in bitmap: 0x%08x 0x%08x 0x%08x, word %d, bit %d\n", fModule, fSca, fState, ri, present[ri], rbit, fScaChannelsSent1, fScaChannelsSent2, fScaChannelsSent3, iword, ibit); e->error = true; fCountErrors++; } } } // make sure no stale data if left behind after this event assert(fCurrent == NULL); assert(fOutput.size() == 0); fScaChannelsSent1 = 0; fScaChannelsSent2 = 0; fScaChannelsSent3 = 0; fScaChannelsThreshold1 = 0; fScaChannelsThreshold2 = 0; fScaChannelsThreshold3 = 0; } void PwbChannelAsm::AddPacket(PwbUdpPacket* udp, const char* ptr, int size) { if (fLast_CHANNEL_SEQ == 0) { fLast_CHANNEL_SEQ = udp->CHANNEL_SEQ; } else if (udp->CHANNEL_SEQ != ((fLast_CHANNEL_SEQ + 1)&0xFFFF)) { if (fState == PWB_CA_ST_ERROR) { printf("PwbChannelAsm::AddPacket: module %d sca %d state %d: misordered or lost UDP packet: CHANNEL_SEQ jump 0x%04x to 0x%04x\n", fModule, fSca, fState, fLast_CHANNEL_SEQ, udp->CHANNEL_SEQ); fError = true; } else { printf("PwbChannelAsm::AddPacket: Error: module %d sca %d state %d: misordered or lost UDP packet: CHANNEL_SEQ jump 0x%04x to 0x%04x\n", fModule, fSca, fState, fLast_CHANNEL_SEQ, udp->CHANNEL_SEQ); fLast_CHANNEL_SEQ = udp->CHANNEL_SEQ; fCountErrors++; fState = PWB_CA_ST_ERROR; fError = true; } } else { fLast_CHANNEL_SEQ++; } if (fState == PWB_CA_ST_INIT || fState == PWB_CA_ST_LAST || fState == PWB_CA_ST_ERROR) { if (udp->CHUNK_ID == 0) { PwbEventHeader* eh = new PwbEventHeader(ptr, size); uint32_t ts = eh->TriggerTimestamp1; fFormatRevision = eh->FormatRevision; fScaChannelsSent1 = eh->ScaChannelsSent1; fScaChannelsSent2 = eh->ScaChannelsSent2; fScaChannelsSent3 = eh->ScaChannelsSent3; fScaChannelsThreshold1 = eh->ScaChannelsThreshold1; fScaChannelsThreshold2 = eh->ScaChannelsThreshold2; fScaChannelsThreshold3 = eh->ScaChannelsThreshold3; if (fTrace) { eh->Print(); } if (0) { printf("module %d sca %d bitmaps 0x%08x 0x%08x 0x%08x - 0x%08x 0x%08x 0x%08x\n", fModule, fSca, fScaChannelsSent1, fScaChannelsSent2, fScaChannelsSent3, fScaChannelsThreshold1, fScaChannelsThreshold2, fScaChannelsThreshold3 ); } if (eh->fError) { printf("PwbChannelAsm::AddPacket: Error: module %d sca %d state %d: error in event header\n", fModule, fSca, fState); fCountErrors++; fState = PWB_CA_ST_ERROR; fError = true; } else { fState = PWB_CA_ST_DATA; fError = false; BeginData(ptr, size, eh->start_of_data, udp->end_of_payload, ts); if (udp->FLAGS & 1) { fState = PWB_CA_ST_LAST; EndData(); } } delete eh; } else { printf("PwbChannelAsm::AddPacket: module %d sca %d state %d: Ignoring UDP packet with CHUNK_ID 0x%02x while waiting for an event header\n", fModule, fSca, fState, udp->CHUNK_ID); } } else if (fState == PWB_CA_ST_DATA) { AddData(ptr, size, udp->start_of_payload, udp->end_of_payload); if (udp->FLAGS & 1) { fState = PWB_CA_ST_LAST; EndData(); } } else { printf("PwbChannelAsm::AddPacket: Error: module %d sca %d state %d: invalid state\n", fModule, fSca, fState); fCountErrors++; } } bool PwbChannelAsm::CheckComplete() const { if (fState == PWB_CA_ST_INIT) return true; if (fState == PWB_CA_ST_LAST) return true; return false; } PwbModuleAsm::PwbModuleAsm(int module, int column, int ring) // ctor { fTrace = gTrace; fModule = module; fColumn = column; fRing = ring; Reset(); } PwbModuleAsm::~PwbModuleAsm() // dtor { for (unsigned i=0; i<fChannels.size(); i++) { if (fChannels[i]) { delete fChannels[i]; fChannels[i] = NULL; } } if (fCountErrors) { printf("PwbModuleAsm: module %d: %d errors, lost %d/%d/%d/%d\n", fModule, fCountErrors, fCountLost1, fCountLost2, fCountLost3, fCountLostN); } } void PwbModuleAsm::Reset() { fLast_PKT_SEQ = 0; for (unsigned i=0; i<fChannels.size(); i++) { if (fChannels[i]) fChannels[i]->Reset(); } } void PwbModuleAsm::AddPacket(const char* ptr, int size) { PwbUdpPacket* udp = new PwbUdpPacket(ptr, size); if (fTrace) { udp->Print(); } #if 0 if (fLast_PKT_SEQ == 0) { fLast_PKT_SEQ = udp->PKT_SEQ; } else if (udp->PKT_SEQ == fLast_PKT_SEQ + 1) { fLast_PKT_SEQ++; } else if (udp->PKT_SEQ == fLast_PKT_SEQ + 2) { printf("PwbModuleAsm::AddPacket: Error: module %d lost one UDP packet: PKT_SEQ jump 0x%08x to 0x%08x\n", fModule, fLast_PKT_SEQ, udp->PKT_SEQ); fCountErrors++; fCountLost1++; fLast_PKT_SEQ = udp->PKT_SEQ; } else if (udp->PKT_SEQ == fLast_PKT_SEQ + 3) { printf("PwbModuleAsm::AddPacket: Error: module %d lost two UDP packets: PKT_SEQ jump 0x%08x to 0x%08x\n", fModule, fLast_PKT_SEQ, udp->PKT_SEQ); fCountErrors++; fCountLost2++; fLast_PKT_SEQ = udp->PKT_SEQ; } else if (udp->PKT_SEQ == fLast_PKT_SEQ + 4) { printf("PwbModuleAsm::AddPacket: Error: module %d lost three UDP packets: PKT_SEQ jump 0x%08x to 0x%08x\n", fModule, fLast_PKT_SEQ, udp->PKT_SEQ); fCountErrors++; fCountLost3++; fLast_PKT_SEQ = udp->PKT_SEQ; } else { int skip = udp->PKT_SEQ - fLast_PKT_SEQ - 1; printf("PwbModuleAsm::AddPacket: Error: module %d misordered or lost UDP packets: PKT_SEQ jump 0x%08x to 0x%08x, skipped %d\n", fModule, fLast_PKT_SEQ, udp->PKT_SEQ, skip); fCountErrors++; fCountLostN++; fLast_PKT_SEQ = udp->PKT_SEQ; } #endif int s = udp->CHANNEL_ID; if (s < 0 || s > 4) { printf("PwbModuleAsm::AddPacket: Error: invalid CHANNEL_ID 0x%08x\n", udp->CHANNEL_ID); fCountErrors++; } else { while (s >= (int)fChannels.size()) { fChannels.push_back(NULL); } if (!fChannels[s]) { fChannels[s] = new PwbChannelAsm(fModule, fColumn, fRing, s); } fChannels[s]->AddPacket(udp, ptr, size); } delete udp; } bool PwbModuleAsm::CheckComplete() const { for (unsigned i=0; i<fChannels.size(); i++) { if (fChannels[i]) { if (!fChannels[i]->CheckComplete()) return false; } } return true; } void PwbModuleAsm::BuildEvent(FeamEvent* e) { fTs = 0; for (unsigned i=0; i<fChannels.size(); i++) { if (fChannels[i]) { fChannels[i]->BuildEvent(e); if (fChannels[i]->fError) { fCountErrors++; e->error = true; } if (fTs == 0) { fTs = fChannels[i]->fTs; } else { if (fChannels[i]->fTs != fTs) { printf("PwbModuleAsm::BuildEvent: Error: channel %d timestamp mismatch 0x%08x should be 0x%08x\n", i, fChannels[i]->fTs, fTs); fCountErrors++; e->error = true; } } } } double ts_freq = 125000000.0; // 125 MHz if (e->counter == 1) { fTsFirstEvent = fTs; fTsLastEvent = 0; fTsEpoch = 0; fTimeFirstEvent = fTs/ts_freq; } if (fTs < fTsLastEvent) fTsEpoch++; fTime = fTs/ts_freq - fTimeFirstEvent + fTsEpoch*2.0*0x80000000/ts_freq; fTimeIncr = fTime - fTimeLastEvent; fTsLastEvent = fTs; fTimeLastEvent = fTime; } PwbAsm::PwbAsm() // ctor { //fTrace = gTrace; } PwbAsm::~PwbAsm() // dtor { int errors = 0; int lost1 = 0; int lost2 = 0; int lost3 = 0; int lostN = 0; for (unsigned i=0; i<fModules.size(); i++) { if (fModules[i]) { errors += fModules[i]->fCountErrors; lost1 += fModules[i]->fCountLost1; lost2 += fModules[i]->fCountLost2; lost3 += fModules[i]->fCountLost3; lostN += fModules[i]->fCountLostN; delete fModules[i]; fModules[i] = NULL; } } printf("PwbAsm: %d events, %d errors, lost %d/%d/%d/%d\n", fCounter, errors, lost1, lost2, lost3, lostN); } void PwbAsm::Reset() { fCounter = 0; fLastTime = 0; for (unsigned i=0; i<fModules.size(); i++) { if (fModules[i]) { fModules[i]->Reset(); } } } void PwbAsm::AddPacket(int module, int column, int ring, const char* ptr, int size) { while (module >= (int)fModules.size()) { fModules.push_back(NULL); } if (!fModules[module]) { fModules[module] = new PwbModuleAsm(module, column, ring); } fModules[module]->AddPacket(ptr, size); } bool PwbAsm::CheckComplete() const { for (unsigned i=0; i<fModules.size(); i++) { if (fModules[i]) { if (!fModules[i]->CheckComplete()) return false; } } return true; } void PwbAsm::BuildEvent(FeamEvent* e) { e->complete = true; e->error = false; e->counter = ++fCounter; e->time = 0; e->timeIncr = 0; bool first_ts = true; for (unsigned i=0; i<fModules.size(); i++) { if (fModules[i]) { fModules[i]->BuildEvent(e); if (first_ts) { first_ts = false; e->time = fModules[i]->fTime; } else { if (fabs(e->time - fModules[i]->fTime) > 1e9) { printf("PwbModuleAsm::BuildEvent: Error: module %d event time mismatch %f should be %f sec, diff %f ns\n", i, fModules[i]->fTime, e->time, (fModules[i]->fTime - e->time)*1e9); e->error = true; } } } } e->timeIncr = e->time - fLastTime; fLastTime = e->time; } /* emacs * Local Variables: * tab-width: 8 * c-basic-offset: 3 * indent-tabs-mode: nil * End: */
[ "estizaid@gmail.com" ]
estizaid@gmail.com
e34f99575706b96db7df2fdf7db25407583fc5eb
b16027325ccfbbcef34109776ec4879a8deab108
/common-all/src/iOSMain/c_interop/firestore/gRPC-C++.framework/Headers/grpcpp/create_channel.h
7a505a71271b88f954ff55b39ed34d7ba4a6d7e4
[ "Apache-2.0" ]
permissive
RubyLichtenstein/Kotlin-Multiplatform-Firebase
dc385e683d5116a4abb56ddcecaa35b318c24212
a6654b5c81a122735e9339dd7897e4fbe4b1f4f2
refs/heads/master
2021-06-07T09:52:40.752288
2021-05-24T08:03:12
2021-05-24T08:03:12
154,049,137
127
19
Apache-2.0
2019-04-25T20:38:53
2018-10-21T20:26:29
C
UTF-8
C++
false
false
1,955
h
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 GRPCPP_CREATE_CHANNEL_H #define GRPCPP_CREATE_CHANNEL_H #include <memory> #include <grpcpp/channel.h> #include <grpcpp/security/credentials.h> #include <grpcpp/support/channel_arguments.h> #include <grpcpp/support/config.h> namespace grpc { /// Create a new \a Channel pointing to \a target. /// /// \param target The URI of the endpoint to connect to. /// \param creds Credentials to use for the created channel. If it does not /// hold an object or is invalid, a lame channel (one on which all operations /// fail) is returned. std::shared_ptr<Channel> CreateChannel( const grpc::string& target, const std::shared_ptr<ChannelCredentials>& creds); /// Create a new \em custom \a Channel pointing to \a target. /// /// \warning For advanced use and testing ONLY. Override default channel /// arguments only if necessary. /// /// \param target The URI of the endpoint to connect to. /// \param creds Credentials to use for the created channel. If it does not /// hold an object or is invalid, a lame channel (one on which all operations /// fail) is returned. /// \param args Options for channel creation. std::shared_ptr<Channel> CreateCustomChannel( const grpc::string& target, const std::shared_ptr<ChannelCredentials>& creds, const ChannelArguments& args); } // namespace grpc #endif // GRPCPP_CREATE_CHANNEL_H
[ "or.noyman@citi.com" ]
or.noyman@citi.com
af9d3d89246bc89f354975e93f68bc6c1602a70b
051839cfdc698f7dc53c08de696c925dc3cde79e
/codeforces/codeforces354/C.cpp
9b4f11a6617d20383d083a62c17ef778739d3d09
[]
no_license
juangil/programmingContests
37645ba582921cb104a66cd5332dfd94d59a9deb
dc0e7b11003411ebfee8f4fcb4024a10e5649b07
refs/heads/master
2021-01-17T13:40:07.398771
2016-07-13T15:25:50
2016-07-13T15:25:50
10,767,650
0
0
null
null
null
null
UTF-8
C++
false
false
505
cpp
# include <cstdio> # include <iostream> # include <cstdlib> # include <cmath> # include <set> # include <vector> using namespace std; int main(){ int n; cin >> n; vector<int> mio(n); int pos1, posn; for(int i = 0; i < n; ++i){ cin >> mio[i]; if(mio[i] == 1) pos1 = i; else if(mio[i] == n) posn = i; } int a = min(pos1, posn); int b = max(pos1, posn); int mdist = b - a; int gano = max(a, n - 1 - b); //cout << a << " " << n - b << endl; cout << mdist + gano << endl; return 0; }
[ "juangilopez@juancho-2.local" ]
juangilopez@juancho-2.local
eddcf667bd63657265b0829a7a22a763d7c1d88d
df256c2663bcd2a61fff9950759debd2760d0ce9
/State/State/States/Ready.cpp
61a52b6d630ca9867cfd1c97c813996389a8ef92
[ "BSD-2-Clause" ]
permissive
jayavardhanravi/DesignPatterns
d4adbb80c2b781affd531f8887c4634e35788353
aa6a37790f447c7caf69c6a1a9c6107074309a03
refs/heads/master
2021-07-25T05:21:02.690532
2021-01-02T14:17:54
2021-01-02T14:17:54
233,955,558
15
2
null
null
null
null
UTF-8
C++
false
false
812
cpp
#include "Ready.h" Ready::Ready() { } Ready::~Ready() { } bool Ready::ReadyRobot(Controller *controller) { state_ = std::make_unique<Ready>(); controller->SetCurrentState(std::move(state_)); std::cout << "[Ready] Preparing the Robot to ReadyState..." << std::endl; return true; } bool Ready::RunningRobot(Controller *controller) { std::cout << "[Ready] -> [Running] Ready State changed to Running State" << std::endl; controller->SetCurrentState(std::move(std::make_unique<Running>())); return controller->SendCommand(Command::RUNNING); } bool Ready::StoppedRobot(Controller *controller) { std::cout << "[Ready] -> [Running] Ready State changed to Stopped State" << std::endl; controller->SetCurrentState(std::move(std::make_unique<Stopped>())); return controller->SendCommand(Command::STOPPED); }
[ "8674552+jayavardhanravi@users.noreply.github.com" ]
8674552+jayavardhanravi@users.noreply.github.com
0aff809dd6a78bf0df1b8bb6ca67e3fa773de543
a2111a80faf35749d74a533e123d9da9da108214
/raw/pmsb13/pmsb13-data-20130530/sources/24xc47o54r0zzgyu/2013-05-14T12-32-45.427+0200/sandbox/my_sandbox/apps/SeqDPT/demultiplex.h
26b7307a3d2558e1405f5eda6433f1fe6934a947
[ "MIT" ]
permissive
bkahlert/seqan-research
f2c550d539f511825842a60f6b994c1f0a3934c2
21945be863855077eec7cbdb51c3450afcf560a3
refs/heads/master
2022-12-24T13:05:48.828734
2015-07-01T01:56:22
2015-07-01T01:56:22
21,610,669
1
0
null
null
null
null
UTF-8
C++
false
false
18,412
h
// ========================================================================== // readTrimming.h // ========================================================================== // Copyright (c) 2006-2012, Knut Reinert, FU Berlin // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Sebastian Roskosch // ========================================================================== /*! \file demultiplex.h \brief Contains the functions for barcode demultiplexing. */ #ifndef SANDBOX_GROUP3_APPS_SEQDPT_DEMULTIPLEX_H_ #define SANDBOX_GROUP3_APPS_SEQDPT_DEMULTIPLEX_H_ // ============================================================================ // Tags, Classes, Enums // ============================================================================ #include <seqan/find.h> #include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/index.h> #include <seqan/seq_io.h> using namespace seqan; typedef String<Dna5Q> TAlphabet; // ============================================================================ // Functions // ============================================================================ /*! \brief Function for controlling the sequences and deleting too short ones. Also checks the barcodes The Function deletes the ID and sequence from the given StringSet if the sequence length is <= barcode length. \param seqs StringSet of forward reads. \param seqsRev StringSet of backward reads. \param ids StringSet of IDs. \param barcodes StringSet of barcodes \return A bool: \b false on different lengths of the barcodes, \b true otherwise. \remark The n-th entries of all given StringSets must be associated. \warning If the programm is not terminated uppon return of \b false, crashes or wrong results are to be exspected. */ template <typename TSeqs, typename TIds, typename TBarcodes> bool check(TSeqs& seqs, TSeqs& seqsRev, TIds& ids, TBarcodes& barcodes) //returns false on errors with the barcodes, true otherwise { unsigned len = length(barcodes[0]); for(unsigned i = 1; i < length(barcodes); ++i) { if(len != length(barcodes[i])) { std::cerr << "ERROR: Barcodes differ in length. All barcodes must be of equal length.\n"; return false; //In this case the programm must be terminated, otherwise erros might occur later or wrong results are likely to be produced } } unsigned limit = length(seqs); unsigned i = 0; while(i < limit) { if(length(seqs[i]) <= len) { std::cout << "WARNING: Sequence " << ids[i] << " has length <= barcode length. Sequence will be excluded.\n"; removeValueById(seqs, i); removeValueById(seqsRev, i); removeValueById(ids, i); --limit; } else ++i; } return true; } /*! \brief Overload of ::check(TSeqs& seqs, TSeqs& seqsRev, TIds& ids, TBarcodes& barcodes) for single-end data. \param seqs StringSet of reads. \param ids StringSet of IDs. \param barcodes StringSet of barcodes */ template <typename TSeqs, typename TIds, typename TBarcodes> bool check(TSeqs& seqs, TIds& ids,TBarcodes& barcodes) { unsigned len = length(barcodes[0]); for(unsigned i = 1; i < length(barcodes); ++i) { if(len != length(barcodes[i])) { std::cerr << "ERROR: Barcodes differ in length. All barcodes must be of equal length.\n"; return false; } } unsigned limit = length(seqs); unsigned i = 0; while(i < limit) { if(length(seqs[i]) <= len) { std::cout << "WARNING: Sequence " << ids[i] << " has length <= barcode length. Sequence will be excluded.\n"; removeValueById(seqs, i); removeValueById(ids, i); --limit; } else ++i; } return true; } /*! \brief Function for extracting the prefices of all given sequences. \param seqs StringSet of sequences. \param len Unsigned integer representing the desired prefix length. \return A StringSet of prefices of length \b len */ template <typename TSeqs> TSeqs getPrefix(TSeqs& seqs, unsigned len) { TSeqs prefices; unsigned limit = length(seqs); unsigned i = 0; while( i < limit) { appendValue(prefices, prefix(seqs[i], len)); ++i; } return prefices; } /*! \brief Function for exact search for one prefix in the barcode indices. \param prefix Prefix of a sequence. \param finder Finder-object holding the preprocessed barcodes. \return An integer representing the position of the matching barcode. If no hit occured \b -1 is returned. \warning Only the first hit is reported. */ template <typename TPrefix, typename TFinder> int findExactIndex(const TPrefix& prefix, TFinder& finder) { clear(finder); if(find(finder, prefix)) { return getSeqNo(position(finder)); //returns index of barcode -> ONLY THE FIRST HIT! } else return -1; //return -1 if no hit occured } /*! \brief Function for performing ::findAllExactIndex on all given prefices and barcodes \param prefices StringSet of prefices. \param finder Finder-object holding the preprocessed barcodes. \return A Vector of integers representing the positions of the matched barcodes. If a sequence could not be matched, the position is replaced by \b -1. \remark The n-th element of the resulting vector is associated with the n-th prefix/sequence. \warning Only the first hit of each prefix is repoted. */ template <typename TPrefices, typename TFinder> std::vector<int> findAllExactIndex(const TPrefices& prefices, TFinder& finder) { std::vector<int> matches(length(prefices)); //initialises the result vector for(unsigned i = 0; i < length(prefices); ++i) { matches[i] = findExactIndex(prefices[i], finder); //returns vector of barcode indices. Element i belongs to sequence i. } return matches; } /*! *\brief Function for creating a vector of patterns used by ::findApprox and ::findApproxAll. The pattern-objects generated use DPSearch and a simple score of 0,-1,-2 (match, mismatch, gap) \param barcodes StringSet of barcodes. \return A vector of pattern-Objects. */ template <typename TBarcodes> std::vector<Pattern<String<Dna5Q>, DPSearch<SimpleScore> > > makePatterns(TBarcodes& barcodes) { std::vector<Pattern<String<Dna5Q>, DPSearch<SimpleScore> > > patterns; resize(patterns, length(barcodes)); for(unsigned i = 0; i < length(barcodes); ++i) { String<Dna5Q> currentBc = barcodes[i]; Pattern<String<Dna5Q>, DPSearch<SimpleScore> > pattern(currentBc, SimpleScore(0, -1, -2)); patterns[i] = pattern; } return patterns; } /*! \brief Function for approximate search for one prefix in all barcodes. \param prefix Prefix of a sequence. \param patterns Vector of pattern-objects generated by ::makePatterns. \return An integer representing the position of the matched barcode. If no hit occured \b -1 is returned. \warning Only the first hit is reported. */ template <typename TPrefix, typename TPatterns> int findApprox(TPrefix& prefix, TPatterns& patterns) { for (unsigned i = 0; i < length(patterns); ++i) { Finder<TPrefix> finder(prefix); //resets Finder if(find(finder, patterns[i], -1)) { return i; //returns index of matched barcode } } return -1; //returns -1 if no hit occured } /*! \brief Function for performing ::findApprox on all given prefices and barcodes. \param prefices StringSet of prefices. \param patterns Vector of pattern-objects generated by ::makePatterns. \return A vector of integers representing the positions of the matched barcodes. \remark The n-th element of the vector is associated with the n-th sequence. \warning Only the first hit of each is reported. */ template <typename TPrefices, typename TPatterns> //must get the StringSet of prefices and the vector of patterns(i.e. preprocessed barcodes) std::vector<int> findAllApprox(const TPrefices& prefices, TPatterns& patterns ) { std::vector<int> matches(length(prefices)); //initialises the result vector for(unsigned i = 0; i < length(prefices); ++i) { matches[i] = findApprox(prefices[i], patterns); } return matches; } /*! \brief Function for clipping the barcodes from the sequences if they could be matched beforehand. \param seqs StringSet of sequences. \param matches Vector produced by ::findAllExactIndex or ::findAllApprox, holding information about the matched barcodes. \param len Unsigned integer representing the length of the barcodes. \remark The n-th element of seq must be associated with the n-th element of matches. \warning If the length of the sequences in seq has not been controlled beforehand by ::check the program might crash. */ template <typename TSeqs> void clipBarcodes(TSeqs& seqs, const std::vector<int>& matches, unsigned len) { for(unsigned i = 0; i < length(matches); ++i) { if(matches[i] != -1) //only erases barcode from sequence if it could be matched { erase(seqs[i], 0 , len); } } } /*! \brief Overload of ::clipBarcodes<seqs, matches, len> if the first len bases of every sequence shall be clipped regardless of the matching(or not matching) barcodes. \param seqs StringSet of sequences. \param len unsigned integer representing the length of the barcodes. \warning Only to be used if the first len bases of every sequence are sure to hold a barcode. \warning If the length of the sequences in seq has not been controlled beforehand by ::check the program might crash. */ template <typename TSeqs> void clipBarcodes(TSeqs& seqs, int len) { for(unsigned i = 0; i < length(seqs); ++i) { erase(seqs[i], 0 , len); } } /*! \brief Function for resizing the groups of the vector produced by ::group and used by it. \param groups Two-dimensional vector containing pointers to sequences. Produced by ::group. */ void resizeGroups(std::vector<std::vector<TAlphabet*> >& groups) { for(unsigned i = 0; i < length(groups); ++i) { (groups[i]).shrink_to_fit(); //resizes groups } groups.shrink_to_fit(); //resizes the whole vector } /*! \brief Function for sorting the matched and clipped sequences into one vector. The function creates pointers to sequences from the results of ::findAllExactIndex or ::findAllApprox and sorts them into a two dimensional vector. \param matches Vector holding information about the matched barcodes. Produced by ::findAllExactIndex or ::findAllApprox functions. \param barcodes StringSet of barcodes. \return A two-dimensional vector of pointers to sequences. \remark The 0-th group (i.e. 0-th collum of the vector) contains the unidentified sequences. */ template <typename TSeqs, typename TMatches, typename TBarcodes> //must get the StringSet of sequences (NOT Prefices!), the vector containing the matches and the StringSet of barcodes std::vector<std::vector<TAlphabet*> > group(TSeqs& seqs, const TMatches& matches, const TBarcodes& barcodes) { std::vector<std::vector<TAlphabet*> > sortedSequences; //initialises the result vector resize(sortedSequences, length(barcodes)+1); for(unsigned i = 0; i < length(matches); ++i) { appendValue(sortedSequences[matches[i]+1], &seqs[i]); //adds pointer to sequence to respective group (offset by 1 is necessary since group 0 is reserved for unidentified sequences). } resizeGroups(sortedSequences); //resizes the groups to take minimal space. return sortedSequences; } /*! \brief Function for performing all demultiplexing operations. \param seqs StringSet of sequences. \param ids StringSet of IDs. \param barcodes StringSet of barcodes. \param approx search Boolean indication whether approximate search (true) or exact search (false) shall be applied. \param hardClip Boolean indication wheter the first Bases of each sequence shall be clipped without considering the barcodes (true). \return A two-dimensional vector of pointers to sequences. \remark The 0-th group (i.e. 0-th collum of the vector) contains the unidentified sequences. \remark All following groups hold the sequences associated with the i-1-th barcode. */ template<typename TSeqs, typename TIds, typename TBarcodes> std::vector<std::vector<TAlphabet*> > DoAll(TSeqs& seqs, TIds& ids, TBarcodes& barcodes, bool approxSearch, bool hardClip) { if(!check(seqs, ids, barcodes)) { std::vector<std::vector<TAlphabet*> > sortedSequences; assignValue(sortedSequences[0][0], NULL); return sortedSequences; } TSeqs prefices = getPrefix(seqs, length(barcodes[0])); std::vector<int> matches; if(!approxSearch) //if exact search is selected { Index<TBarcodes, IndexEsa<> > indexSet(barcodes); Finder<Index<TBarcodes>, IndexEsa<> > esaFinder(indexSet); matches = findAllExactIndex(prefices, esaFinder); } else //if approximate search is selected { std::vector<Pattern<String<Dna5Q>, DPSearch<SimpleScore> > > patterns = makePatterns(barcodes); matches = findAllApprox(seqs, patterns); } if(!hardClip) //clip barcodes according to selected method { clipBarcodes(seqs, matches, length(barcodes[0])); } else { clipBarcodes(seqs, length(barcodes[0])); } std::vector<std::vector<TAlphabet*> > sortedSequences = group(seqs, matches, barcodes); return sortedSequences; } /*! \brief Overload of ::DoAll(TSeqs& seqs, TIds& ids, TBarcodes& barcodes, bool approxSearch, bool hardClip) for paired-end data. \param seqs StringSet of forward reads. \param seqsRev StringSet of backward reads. \param ids StringSet of IDs. \param barcodes StringSet of barcodes. \param approx search Boolean indication whether approximate search (true) or exact search (false) shall be applied. \param hardClip Boolean indication wheter the first Bases of each sequence shall be clipped without considering the barcodes (true). \return A two-dimensional vector of pointers to sequences. \remark The 0-th group (i.e. 0-th collum of the vector) contains the unidentified sequences. \remark All following groups hold the sequences associated with the i-1-th barcode. */ template<typename TSeqs, typename TIds, typename TBarcodes> std::vector<std::vector<TAlphabet*> > DoAll(TSeqs& seqs, TSeqs& seqsRev, TIds& ids, TBarcodes& barcodes, bool approxSearch, bool hardClip) { if(!check(seqs, seqsRev, ids, barcodes)) { std::vector<std::vector<TAlphabet*> > sortedSequences; assignValue(sortedSequences[0][0], NULL); return sortedSequences; } TSeqs prefices = getPrefix(seqs, length(barcodes[0])); std::vector<int> matches; if(!approxSearch) //if exact search is selected { Index<TBarcodes, IndexEsa<> > indexSet(barcodes); Finder<Index<TBarcodes>, IndexEsa<> > esaFinder(indexSet); matches = findAllExactIndex(prefices, esaFinder); } else //if approximate search is selected { std::vector<Pattern<String<Dna5Q>, DPSearch<SimpleScore> > > patterns = makePatterns(barcodes); matches = findAllApprox(seqs, patterns); } if(!hardClip) //clip barcodes according to selected method { clipBarcodes(seqs, matches, length(barcodes[0])); } else { clipBarcodes(seqs, length(barcodes[0])); } std::vector<std::vector<TAlphabet*> > sortedSequences = group(seqs, matches, barcodes); return sortedSequences; } /*! \brief Overload of ::DoAll(TSeqs& seqs, TIds& ids, TQuals& quals, TBarcodes& barcodes, bool approxSearch, bool hardClip) for multiplex barcode single-end or paired-end data. \param seqs StringSet of forward reads. \param ids StringSet of IDs. \param multiplex StringSet of multiplex barcodes. \param barcodes StringSet of barcodes. \param approx search Boolean indication whether approximate search (true) or exact search (false) shall be applied. \return A two-dimensional vector of pointers to sequences. \remark The 0-th group (i.e. 0-th collum of the vector) contains the unidentified sequences. \remark All following groups hold the sequences associated with the i-1-th barcode. */ template<typename TSeqs, typename TIds, typename TBarcodes> std::vector<std::vector<TAlphabet*> > DoAll(TSeqs& seqs, TIds& ids, TBarcodes& multiplex, TBarcodes& barcodes, bool approxSearch) { std::vector<int> matches; if(!approxSearch) //if exact search is selected { Index<TBarcodes, IndexEsa<> > indexSet(barcodes); Finder<Index<TBarcodes>, IndexEsa<> > esaFinder(indexSet); matches = findAllExactIndex(multiplex, esaFinder); } else //if approximate search is selected { std::vector<Pattern<String<Dna5Q>, DPSearch<SimpleScore> > > patterns = makePatterns(barcodes); matches = findAllApprox(multiplex, patterns); } std::vector<std::vector<TAlphabet*> > sortedSequences = group(seqs, matches, barcodes); return sortedSequences; } #endif // #ifndef SANDBOX_GROUP3_APPS_SEQDPT_DEMULTIPLEX_H_
[ "mail@bkahlert.com" ]
mail@bkahlert.com
ddaa232c0f5e0132a3dbf94525e6505e03b6fb91
53733f73b922407a958bebde5e674ec7f045d1ba
/ABC/ABC177/F/main.cpp
61db95e22790e82fe86ef08c94fc562cb04eb7f2
[]
no_license
makio93/atcoder
040c3982e5e867b00a0d0c34b2a918dd15e95796
694a3fd87b065049f01f7a3beb856f8260645d94
refs/heads/master
2021-07-23T06:22:59.674242
2021-03-31T02:25:55
2021-03-31T02:25:55
245,409,583
0
0
null
null
null
null
UTF-8
C++
false
false
1,517
cpp
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; #define ull unsigned long long #define ld long double #define vi vector<int> #define vll vector<ll> #define vc vector<char> #define vs vector<string> #define vpii vector<pii> #define vpll vector<pll> #define rep(i, n) for (int i = 0, i##_len = (n); i < i##_len; i++) #define rep1(i, n) for (int i = 1, i##_len = (n); i <= i##_len; i++) #define repr(i, n) for (int i = ((int)(n)-1); i >= 0; i--) #define rep1r(i, n) for (int i = ((int)(n)); i >= 1; i--) #define sz(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define SORT(v, n) sort(v, v + n); #define VSORT(v) sort(v.begin(), v.end()); #define RSORT(x) sort(rall(x)); #define pb push_back #define mp make_pair #define INF (1e9) #define PI (acos(-1)) #define EPS (1e-7) ull gcd(ull a, ull b) { return b ? gcd(b, a % b) : a; } ull lcm(ull a, ull b) { return a / gcd(a, b) * b; } int main(){ int h, w; cin >> h >> w; int ans = 0, p = 0; rep(i, h) { int a, b; cin >> a >> b; --a; --b; if (ans == -1) { cout << -1 << endl; continue; } if (p >= a) { if (b==w-1) ans = -1; else { ans += (b+1-p); p = b+1; } } if (ans != -1) ++ans; cout << ans << endl; } return 0; }
[ "mergon-nitro-pale_fluorelight@hotmail.co.jp" ]
mergon-nitro-pale_fluorelight@hotmail.co.jp
c0d7049e276f25c28c06c532f6b4375311a015b1
68d19f0993e8409120ab6d775762f79a1a456e81
/binarysearch/2143.cpp
1c2f2bc93a83e1875fc0e8904c1cf61f73b41f7c
[]
no_license
hanjongho/baekjoon
e1fb6a9e5f685ab33890945c325550ebe512fc24
f03249886b06f6844bb02e417d7eedd8f0dc32c5
refs/heads/master
2021-11-22T08:12:30.462904
2021-08-18T14:34:34
2021-08-18T14:34:34
228,543,047
1
0
null
null
null
null
UTF-8
C++
false
false
1,005
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); vector<long long> v1, v2; long long T, ans = 0; int N, M; int arr[1001], brr[1001]; cin >> T; cin >> N; for (int i = 0; i < N; i++) cin >> arr[i]; cin >> M; for (int i = 0; i < M; i++) cin >> brr[i]; for (int i = 0; i < N; i++) { long long sum = arr[i]; v1.push_back(sum); for (int j = i + 1; j < N; j++) { sum += arr[j]; v1.push_back(sum); } } for (int i = 0; i < M; i++) { long long sum = brr[i]; v2.push_back(sum); for (int j = i + 1; j < M; j++) { sum += brr[j]; v2.push_back(sum); } } sort(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); for (int i = 0; i < v1.size(); i++) { int low = lower_bound(v2.begin(), v2.end(), T - v1[i]) - v2.begin(); int high = upper_bound(v2.begin(), v2.end(), T - v1[i]) - v2.begin(); ans += high - low; } cout << ans << "\n"; return (0); }
[ "lgwl81@gmail.com" ]
lgwl81@gmail.com
70a0e6064a47b5b781dd04d9a92a43f4c2feb7ed
40ca9a30b887f22da378c038165dbb80641f347e
/FunBrainz/FunBrainz/GlobalFuncs.h
a142bd1e5f76d6cdfe3faef2bf1fe0ce37f95caa
[]
no_license
Rounak14/FunBrainz-Assignment-3
0b1424687a235e207f63fa70f6a31b263121885f
4361d41987c865ffbf20d8fa3e7416708c2f36ab
refs/heads/master
2020-05-03T03:49:19.467659
2019-03-28T14:27:16
2019-03-28T14:27:16
178,406,593
1
0
null
2019-03-29T13:03:39
2019-03-29T13:03:39
null
UTF-8
C++
false
false
2,039
h
#pragma once #include <stdio.h> #include <utility> #include<cmath> #include<ctime> #include<string> #include<iostream> using namespace std; ref class GlobalFuncs { public: GlobalFuncs(void); public: static std::pair <std::string, int> generateQuestion(int operatorIndex, int level) { if (operatorIndex == 4) { operatorIndex = rand() % 4; std::pair < std::string, int > temp; temp = generateQuestion(operatorIndex, level); return temp; } else { std::pair < std::string, int > temp; int range; if (operatorIndex < 2) { range = pow((double)2, level + 3); } else { range = pow((double)2, level); } int num1, num2; num1 = rand() % range; num2 = rand() % range; if (operatorIndex >= 2) { if (range >= 100) { num2 = rand() % 100 + 1; } } // cout << num << " "; int result; std::string question = ""; question += std::to_string((long long)num1); if (operatorIndex == 0) { result = num1 + num2; question += '+'; } else if (operatorIndex == 1) { result = num1 - num2; question += '-'; } else if (operatorIndex == 2) { result = num1 * num2; question += '*'; } else if (operatorIndex == 3) { result = rand() % range + 1; if (result > 50) { result = rand() % 50 + 1; } num2 = rand() % range + 1; if (num2 >= 100) num2 = rand() % 100 + 1; num1 = num2 * result; question = ""; question += std::to_string((long long)num1); question += '/'; } question += std::to_string((long long)num2); temp.first = question; temp.second = result; return temp; } } };
[ "mayank343@gmail.com" ]
mayank343@gmail.com
617ff4d46a5eef9cdda6dc4b2ebe4ea93d804613
b35b0e874c2d04e68fab4c6fd75023fb407c2965
/pegasus/src/Providers/TestProviders/OOPModuleFailureProvider/OOPModuleFailureTestProvider.cpp
cd36abf33eac000c7bdc8daf5553c2b860117c98
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
xenserver/openpegasus
38de7f2062adf1f039ef9ead222c40d75d8acaaa
57e10a2ca29c17e5dca26a1c6c40a1a5fc4ba20d
refs/heads/master
2020-05-17T16:22:40.019817
2013-11-19T00:42:25
2014-04-07T16:25:45
10,623,043
3
2
null
2013-12-04T14:44:02
2013-06-11T14:19:20
C++
UTF-8
C++
false
false
11,707
cpp
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////////// #include <Pegasus/Common/Config.h> #include <Pegasus/Common/CIMDateTime.h> #include <Pegasus/Common/PegasusAssert.h> #include <Pegasus/Common/System.h> #include "OOPModuleFailureTestProvider.h" PEGASUS_USING_STD; PEGASUS_USING_PEGASUS; static IndicationResponseHandler * _handler = 0; static Boolean _enabled = false; static Uint32 _numSubscriptions = 0; static String _providerName; extern "C" PEGASUS_EXPORT CIMProvider * PegasusCreateProvider ( const String & providerName) { _providerName = providerName; if (String::equalNoCase (providerName, "OOPModuleInitFailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleCreateFailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleCreate2FailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleEnableFailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleModifyFailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleInvokeFailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleDeleteFailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleDelete2FailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleDisableFailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } else if (String::equalNoCase (providerName, "OOPModuleTermFailureTestProvider")) { return (new OOPModuleFailureTestProvider ()); } return (0); } void _generateIndication ( IndicationResponseHandler * handler, const String & identifier) { if (_enabled) { CIMInstance indicationInstance (CIMName ("FailureTestIndication")); CIMObjectPath path; path.setNameSpace ("test/testProvider"); path.setClassName ("FailureTestIndication"); indicationInstance.setPath (path); indicationInstance.addProperty (CIMProperty ("IndicationIdentifier", identifier)); CIMDateTime currentDateTime = CIMDateTime::getCurrentDateTime (); indicationInstance.addProperty (CIMProperty ("IndicationTime", currentDateTime)); Array <String> correlatedIndications; indicationInstance.addProperty (CIMProperty ("CorrelatedIndications", correlatedIndications)); indicationInstance.addProperty (CIMProperty ("Description", String ("Failure Test Indication"))); indicationInstance.addProperty (CIMProperty ("AlertingManagedElement", System::getFullyQualifiedHostName ())); indicationInstance.addProperty (CIMProperty ("AlertingElementFormat", Uint16 (0))); indicationInstance.addProperty (CIMProperty ("AlertType", Uint16 (1))); indicationInstance.addProperty (CIMProperty ("OtherAlertType", String ("Test"))); indicationInstance.addProperty (CIMProperty ("PerceivedSeverity", Uint16 (2))); indicationInstance.addProperty (CIMProperty ("ProbableCause", Uint16 (1))); indicationInstance.addProperty (CIMProperty ("ProbableCauseDescription", String ("Test"))); indicationInstance.addProperty (CIMProperty ("Trending", Uint16 (4))); Array <String> recommendedActions; recommendedActions.append ("Test"); indicationInstance.addProperty (CIMProperty ("RecommendedActions", recommendedActions)); indicationInstance.addProperty (CIMProperty ("EventID", String ("Test"))); CIMDateTime eventTime = CIMDateTime::getCurrentDateTime (); indicationInstance.addProperty (CIMProperty ("EventTime", eventTime)); indicationInstance.addProperty (CIMProperty ("SystemCreationClassName", System::getSystemCreationClassName ())); indicationInstance.addProperty (CIMProperty ("SystemName", System::getFullyQualifiedHostName ())); indicationInstance.addProperty (CIMProperty ("ProviderName", _providerName)); CIMIndication cimIndication (indicationInstance); handler->deliver (cimIndication); } } OOPModuleFailureTestProvider::OOPModuleFailureTestProvider () { } OOPModuleFailureTestProvider::~OOPModuleFailureTestProvider () { } void OOPModuleFailureTestProvider::initialize (CIMOMHandle & cimom) { // // save cimom handle // _cimom = cimom; // // If I am the OOPModuleInitFailureTestProvider, fail (i.e. exit) // if (String::equalNoCase (_providerName, "OOPModuleInitFailureTestProvider")) { exit (-1); } } void OOPModuleFailureTestProvider::terminate () { // // If I am the OOPModuleTermFailureTestProvider, and there are // subscriptions, fail (i.e. exit) // if (String::equalNoCase (_providerName, "OOPModuleTermFailureTestProvider")) { if (_numSubscriptions > 0) { exit (-1); } } delete this; } void OOPModuleFailureTestProvider::enableIndications ( IndicationResponseHandler & handler) { // // enableIndications should not be called if indications have already been // enabled // if (_enabled) { PEGASUS_ASSERT (false); } _enabled = true; _handler = &handler; // // If I am the OOPModuleEnableFailureTestProvider, fail (i.e. exit) // if (String::equalNoCase (_providerName, "OOPModuleEnableFailureTestProvider")) { exit (-1); } } void OOPModuleFailureTestProvider::disableIndications () { _enabled = false; _handler->complete (); // // If I am the OOPModuleDisableFailureTestProvider, fail (i.e. exit) // if (String::equalNoCase (_providerName, "OOPModuleDisableFailureTestProvider")) { exit (-1); } } void OOPModuleFailureTestProvider::createSubscription ( const OperationContext & context, const CIMObjectPath & subscriptionName, const Array <CIMObjectPath> & classNames, const CIMPropertyList & propertyList, const Uint16 repeatNotificationPolicy) { _numSubscriptions++; // // If I am the OOPModuleCreateFailureTestProvider, fail (i.e. exit) // if (String::equalNoCase (_providerName, "OOPModuleCreateFailureTestProvider")) { exit (-1); } // // If I am the OOPModuleCreate2FailureTestProvider, and this subscription // is not my first, fail (i.e. exit) // else if (String::equalNoCase (_providerName, "OOPModuleCreate2FailureTestProvider")) { if (_numSubscriptions > 1) { exit (-1); } } } void OOPModuleFailureTestProvider::modifySubscription ( const OperationContext & context, const CIMObjectPath & subscriptionName, const Array <CIMObjectPath> & classNames, const CIMPropertyList & propertyList, const Uint16 repeatNotificationPolicy) { // // If I am the OOPModuleModifyFailureTestProvider, fail (i.e. exit) // if (String::equalNoCase (_providerName, "OOPModuleModifyFailureTestProvider")) { exit (-1); } } void OOPModuleFailureTestProvider::deleteSubscription ( const OperationContext & context, const CIMObjectPath & subscriptionName, const Array <CIMObjectPath> & classNames) { _numSubscriptions--; if (_numSubscriptions == 0) _enabled = false; // // If I am the OOPModuleDeleteFailureTestProvider, fail (i.e. exit) // if (String::equalNoCase (_providerName, "OOPModuleDeleteFailureTestProvider")) { exit (-1); } // // If I am the OOPModuleDelete2FailureTestProvider, and there are // remaining subscriptions, fail (i.e. exit) // else if (String::equalNoCase (_providerName, "OOPModuleDelete2FailureTestProvider")) { if (_numSubscriptions > 0) { exit (-1); } } } void OOPModuleFailureTestProvider::invokeMethod ( const OperationContext & context, const CIMObjectPath & objectReference, const CIMName & methodName, const Array <CIMParamValue> & inParameters, MethodResultResponseHandler & handler) { Boolean sendIndication = false; String identifier; handler.processing (); if (objectReference.getClassName ().equal ("FailureTestIndication") && _enabled) { if (methodName.equal ("SendTestIndication")) { if ((inParameters.size() > 0) && (inParameters[0].getParameterName () == "identifier")) { inParameters[0].getValue().get(identifier); } sendIndication = true; handler.deliver (CIMValue (0)); } } else { handler.deliver (CIMValue (1)); PEGASUS_STD (cout) << "Provider is not enabled." << PEGASUS_STD (endl); } handler.complete (); if (sendIndication) { _generateIndication (_handler, identifier); } // // If I am the OOPModuleInvokeFailureTestProvider, fail (i.e. exit) // if (String::equalNoCase (_providerName, "OOPModuleInvokeFailureTestProvider")) { if (methodName.equal ("Fail")) { exit (-1); } } }
[ "rob@rdobson.co.uk" ]
rob@rdobson.co.uk
1d4d9e66754b16b35f4d9efe04bf890891fdd0c1
adcab6ba28cc7646f314e13121e05be277dc74fd
/Source/VoxRender/Interface/animatewidget.h
e1631dc7ae3e75fc6cba7863182b225327f55531
[]
no_license
nagyistoce/voxrender
60a7b7c04be8e34d21ca47a34b6656b9d0ffbc41
558c147197b3970ffb836f37a3dfe0d392e8afb9
refs/heads/master
2021-01-14T10:04:01.237554
2015-04-01T13:13:44
2015-04-01T13:13:44
34,286,211
0
1
null
2015-04-20T21:00:18
2015-04-20T21:00:17
null
UTF-8
C++
false
false
2,516
h
/* =========================================================================== Project: VoxRender Description: Implements an interface for for animation management Copyright (C) 2014 Lucas Sherman Lucas Sherman, email: LucasASherman@gmail.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. =========================================================================== */ // Begin Definition #ifndef ANIMATE_WIDGET_H #define ANIMATE_WIDGET_H // QT Includes #include <QtWidgets/QWidget> #include <QtWidgets/QGraphicsScene> #include "VoxScene/Animator.h" #include "VoxScene/Scene.h" namespace Ui { class AnimateWidget; } class AnimateView; // Volume data histogram widget class AnimateWidget : public QWidget { Q_OBJECT public: explicit AnimateWidget(QWidget *parent = 0); ~AnimateWidget(); void setFrame(int value); void setFrameHover(int value); private: Ui::AnimateWidget * ui; void updateControls(); void onAddKey(int index, std::shared_ptr<vox::KeyFrame> key, bool suppress); void onRemoveKey(int index, std::shared_ptr<vox::KeyFrame> key, bool suppress); float m_frameOffset; ///< Frame at left edge of window QGraphicsScene m_scene; AnimateView * m_animateView; private slots: void sceneChanged(vox::Scene & scene, void * userInfo); void on_spinBox_frame_valueChanged(int value); void on_spinBox_framerate_valueChanged(int value); void on_pushButton_render_clicked(); void on_pushButton_preview_clicked(); void on_pushButton_key_clicked(); void on_pushButton_delete_clicked(); void on_pushButton_load_clicked(); void on_pushButton_next_clicked(); void on_pushButton_prev_clicked(); void on_pushButton_first_clicked(); void on_pushButton_last_clicked(); }; // End definition #endif // ANIMATE_WIDGET_H
[ "LucasASherman@gmail.com@860efb89-3126-5ccb-708a-13cdb6cb0f7d" ]
LucasASherman@gmail.com@860efb89-3126-5ccb-708a-13cdb6cb0f7d
8646db66d0cacd8bc9e01541517a5f9a3832b9a1
f2907f4f6a99ad6f183ea9469cf4588d1d9af753
/PC_ClientSDK.201804142014/PPPCS_ClientUI/PreviewPanel.h
c78661923ca29888eb908f57dbd5556fbb4d04c0
[]
no_license
intWang/BDY
797da5afa3c1d8374fc2d0018a6de207ffce49df
02f55e0962c510c23d1e4b656fa7d68dba9b82b8
refs/heads/master
2023-02-04T05:09:11.621949
2020-12-28T02:51:25
2020-12-28T02:51:25
285,232,966
0
0
null
null
null
null
UTF-8
C++
false
false
2,850
h
#pragma once #include <QWidget> #include "AreableWidget.h" #include "ui_PreviewPanel.h" #include "PreviewRealWnd.h" #include "DataStruct.h" #include <QIcon> class PreviewPanel : public AreableWidget<QWidget> { Q_OBJECT public: using Ptr = PreviewPanel*; PreviewPanel(QWidget *parent = Q_NULLPTR); ~PreviewPanel(); void OnScreenDevideChange(DevideScreen newMode); signals: void PreviewStatuChanged(const QString& strUid, bool bStatu); void SelectPreviewWnd(PreviewRealWnd::Ptr pWnd); void PanelModeChanged(PanelMode emMode, DevNode::Ptr pNode); void CallPopUpTreeWnd(); void FullScreen(bool bFull); void RequestActiveDev(std::string& strUid); protected: virtual BarWidget::Ptr InitTopBar(); virtual BarWidget::Ptr InitBottomBar(); void InitPreviewRealWnds(); void PraperPreviewRealWnds(int nNums); void SetSelectWnd(PreviewRealWnd::Ptr pWnd, bool bForceSel = false); void SetCurrentMode(PanelMode emMode); void SetPreviewWndMode(PanelMode nModetype); void StartPreview4PreviewMode(DevNode::Ptr pChannel); PreviewRealWnd::Ptr GetFreeWnd(); void StartTopBarCheck(); void StopTopBarCheck(); void ClearAllWnd(); void UpdateBottomBtn(); virtual void keyPressEvent(QKeyEvent *event) override; public slots: void OnStartPreview(DevNode::Ptr pChannel); void OnDevNodeUpdated(DevNode::Ptr pChannel); void OnPreviewStopped(const QString& strUid, PreviewRealWnd::Ptr pWnd); void OnPreviewStarted(const QString& strUid, PreviewRealWnd::Ptr pWnd); void OnRequestActiveDev(std::string& strUid); void OnDeviceLostConnect(const QString& strUID); void OnPreveiwWndSelChange(); void OnPreveiwWndSelFull(int nFull); void OnScreenDevideModeChange(int nIndex); void OnStreamSnapShot(SnapData::Ptr pFrame); void SetCustomWndLayout(int row, int column); void OnLayoutDirChanged(bool bChanged); void OnFullScreen(); void OnTimeout(); private: Ui::PreviewPanel ui; PanelMode m_curPanelmode = PanelMode::PreviewMode; std::vector<PreviewRealWnd::Ptr> m_vcPreviewRealWnds; std::map<PanelMode, ::vector<QWidgetPtr>> m_mapModeWidgets; PreviewRealWnd::Ptr m_pCurSelWnd = nullptr; DevideScreen m_curScreenMode = DevideScreen::Screen_1X1; DevideScreen m_lastScreenMode = DevideScreen::Screen_1X1; QGridLayoutPtr m_pRealWnds = nullptr; QComboBoxPtr m_pCbbDevideScreen = nullptr; QPushButtonPtr m_pSnapMode = nullptr; QPushButtonPtr m_pFullScrren = nullptr; QIcon m_icon1X1; QIcon m_icon2X2; QIcon m_icon3X3; QIcon m_icon4X3; int m_nCustomRow = 0; int m_nCustomColumn = 0; bool m_bDirExchanged = false; bool m_bFull = false; QWidget* m_pParent = nullptr; QWidget* m_pViewWndWidget = nullptr; QTimer* m_pTimerTopBarCheck = nullptr; };
[ "xiaohwa2@cisco.com" ]
xiaohwa2@cisco.com
9b50609862b84462d60fd9569b4fc11951ddc2a0
0cf94ba93e29f574a08f1c9b0d9dbf98e5984c6e
/Module/Flow/BoxAlignFlow.h
05e93bdca69fc69f6f56bfc69adaed2a4eba4ad4
[]
no_license
jtendless/G8H_VisionAgent
aa1c41bcdb0e9f54471ef5f7cfa5b5720d2f32f2
07a613533cadf0741cfaa31b65f41c441e1267cc
refs/heads/main
2023-08-21T14:03:50.921147
2021-09-24T00:42:35
2021-09-24T00:42:35
409,556,921
0
1
null
2023-07-21T07:59:10
2021-09-23T11:05:39
C++
UTF-8
C++
false
false
2,315
h
#pragma once class CBoxAlignFlow : public CBaseFlow { public: CBoxAlignFlow(); ~CBoxAlignFlow(); private: BOOL m_FlowFinish; void(*m_StateComplete)(void *pArgument); CWinThread* pThread; VOID ThreadFunctionEntry(VOID); static UINT ThreadFunction(LPVOID lpParam); public: BOOL m_bFlowDone; BOOL m_bStopBit; BOOL InitProcess(); BOOL EndProcess(); HANDLE hHandle; BOOL m_bTerminate; BOOL IsTerminate() { return m_bTerminate; } BOOL IsFlowDone() { return m_bFlowDone; } BOOL Start(int nStep); BOOL Stop(); CTime m_timeStart; //KJT 20210329 CString m_strFilePath; BOOL FlowInterlock(); int SaveBoxAlignResult(); #pragma region //BoxAlign double m_AlignPointValue[2][2]; //Inspection Pos double m_AlignVisionResultValue[2][2]; double m_dDiffPos[3]; double m_dTarget[3]; int m_nGrabRetryCount; int m_AlignCnt; BOOL m_bBoxAlignGrabDone; #pragma endregion double m_dCurPos, m_dPrevPos; //[1] enum eBoxAlignFlow { _eBOX_ALIGN_FLOW_ERROR = -1, _eBOX_ALIGN_FLOW_IDLE = 0, _eBOX_ALIGN_FLOW_START, _eBOX_ALIGN_FLOW_INTERLOCK_CHECK, #pragma region //Unloader Ready _eBOX_ALIGN_FLOW_UNLOADER_READY, _eBOX_ALIGN_FLOW_UNLOADER_READY_CHECK, #pragma endregion #pragma region //Gantry ZXY Ready _eBOX_ALIGN_FLOW_GANTRY_ZXY_READY, _eBOX_ALIGN_FLOW_GANTRY_ZXY_READY_CHECK, #pragma endregion #pragma region //LoaderZ Ready _eBOX_ALIGN_FLOW_LOADER_Z_READY, _eBOX_ALIGN_FLOW_LOADER_Z_READY_CHECK, #pragma endregion #pragma region //PaperUnloader Ready _eBOX_ALIGN_FLOW_PAPER_UNLOADER_ZX_READY, _eBOX_ALIGN_FLOW_PAPER_UNLOADER_ZX_READY_CHECK, _eBOX_ALIGN_FLOW_PAPER_UNLOADER_Y_SAFETY_POS, _eBOX_ALIGN_FLOW_PAPER_UNLOADER_Y_SAFETY_POS_CHECK, #pragma endregion _eBOX_ALIGN_FLOW_UVW_WAIT_POS, //KJT 20210316 _eBOX_ALIGN_FLOW_UVW_WAIT_POS_CHECK, _eBOX_ALIGN_FLOW_LOADER_Y_ALIGN_POS, _eBOX_ALIGN_FLOW_LOADER_Y_ALIGN_POS_CHECK, _eBOX_ALIGN_FLOW_LOADER_X_ALIGN_POS, _eBOX_ALIGN_FLOW_LOADER_X_ALIGN_POS_CHECK, _eBOX_ALIGN_FLOW_LOADER_Z_ALIGN_POS, _eBOX_ALIGN_FLOW_LOADER_Z_ALIGN_POS_CHECK, _eBOX_ALIGN_FLOW_GRAB_START, _eBOX_ALIGN_FLOW_UVW_MOVE_START, _eBOX_ALIGN_FLOW_UVW_MOVE_CHECK, _eBOX_ALIGN_FLOW_LOADER_Z_WAIT_POS_2ND, _eBOX_ALIGN_FLOW_LOADER_Z_WAIT_POS_2ND_CHECK, _eBOX_ALIGN_FLOW_DONE, }; };
[ "jt-endless@daum.net" ]
jt-endless@daum.net
c61c4a10e871350911909b92070060fd7b6b7c1d
04ec68ae803e65a0108ce2b319a36471f4f941a1
/crest/xpro_seq_v1_sept30/zzl/Utility.h
5c4c15c0b867e6e8aa4a575425dfa6cb4acd0b3c
[]
no_license
Seasonsky/Steiner
9a850b852393cac79d30e73031e28a85450337c2
c71df4e9aa61968433d4a8573c6232c8aeecd0b8
refs/heads/master
2021-01-01T04:26:16.563402
2016-11-16T08:39:40
2016-11-16T08:39:40
59,816,397
0
0
null
null
null
null
UTF-8
C++
false
false
447
h
#include "Def.h" #include "Atom.h" class Utility { public: // Permutation<->String string permutation2string(vector<int> sequence); vector<int> string2permutation(string line); // Printing void print_vector(vector<int> sequence); void print_vector(vector<vector<int> > sequences); void print_vector_string(vector<string>); void print_vector_atom(vector<Atom> atoms); void print_vector_atom(vector<vector<Atom> > atoms); };
[ "zhang.2013@live.com" ]
zhang.2013@live.com
949aa48c9b9d74ea323978df745c9fd4ac65deae
bedcc7dab33f83ff5493cc0b4e07c2e657ccc309
/generator/graph_and_vertices_generator.hpp
e594e2993ff6a85299368f893163693dc87828f4
[]
no_license
nijelic/OMPSearch
30344cb665ad7b9fbf4da10c54824e27ef17affc
00178bde370d6a84a8187082f1a8a3f5e689cb57
refs/heads/master
2020-09-02T07:41:31.058806
2019-11-02T15:02:47
2019-11-02T15:02:47
219,169,773
0
0
null
null
null
null
UTF-8
C++
false
false
364
hpp
#ifndef GRAPH_AND_VERTICES_GENERATOR_HPP #define GRAPH_AND_VERTICES_GENERATOR_HPP #include <string> #include <utility> std::pair<int, int> createPair(int, int); void makeBaseGraph(int, int); void markEdge(int, int); void makeItConnected(int, int); void saveGraph(std::string); void saveNode(int, int, unsigned); void saveVertices(std::string, int, int); #endif
[ "nikola.jelic995@gmail.com" ]
nikola.jelic995@gmail.com
b8bae1b4098b637bd47718405faa856dd5e8c925
aedec0779dca9bf78daeeb7b30b0fe02dee139dc
/Modules/Image/test/testInterpolateExtrapolateImageFunction.cc
91806fc728557e7a9e6276dfc726944fe6baf62c
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BioMedIA/MIRTK
ca92f52b60f7db98c16940cd427a898a461f856c
973ce2fe3f9508dec68892dbf97cca39067aa3d6
refs/heads/master
2022-08-08T01:05:11.841458
2022-07-28T00:03:25
2022-07-28T10:18:00
48,962,880
171
78
Apache-2.0
2022-07-28T10:18:01
2016-01-03T22:25:55
C++
UTF-8
C++
false
false
26,226
cc
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2015 Imperial College London * Copyright 2013-2015 Andreas Schuh * * 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. */ // TODO: Rewrite test using GTest library. -as12312 #include "mirtk/GenericImage.h" #include "mirtk/InterpolateImageFunction.h" #include "mirtk/ExtrapolateImageFunction.h" using namespace mirtk; // =========================================================================== // Macros // =========================================================================== // --------------------------------------------------------------------------- #define TEST(id) \ const char *_id = id; \ int _nfail = 0; \ cout << "Test case: " << _id << endl // --------------------------------------------------------------------------- #define RESULT _nfail // --------------------------------------------------------------------------- #define NULLPTR(actual, message, exit_if_not) \ do { \ void *_actual = (actual); \ if (_actual != NULL) { \ _nfail++; \ cerr << message << endl; \ cerr << " Actual: " << _actual << endl; \ cerr << " Expected: NULL" << endl; \ if (exit_if_not) exit(_nfail); \ } \ }while(false) // --------------------------------------------------------------------------- #define NOT_NULLPTR(actual, message, exit_if_not) \ do { \ void *_actual = (actual); \ if (_actual == NULL) { \ _nfail++; \ cerr << message << endl; \ cerr << " Actual: " << _actual << endl; \ cerr << " Expected: !NULL" << endl; \ if (exit_if_not) exit(_nfail); \ } \ }while(false) // --------------------------------------------------------------------------- #define EQUAL(actual, expected, message, exit_if_not) \ do { \ double _actual = (actual); \ double _expected = (expected); \ if (fabs(_actual - _expected) >= 1e-10) { \ _nfail++; \ cerr << message << endl; \ cerr << " Actual: " << setprecision(15) << _actual << endl; \ cerr << " Expected: " << setprecision(15) << _expected << endl; \ if (exit_if_not) exit(_nfail); \ } \ }while(false) // --------------------------------------------------------------------------- #define NOT_EQUAL(actual, expected, message, exit_if_not) \ do { \ double _actual = (actual); \ double _expected = (expected); \ if (fabs(_actual - _expected) < 1e-10) { \ _nfail++; \ cerr << message << endl; \ cerr << " Actual: " << setprecision(15) << _actual << endl; \ cerr << " Expected: " << setprecision(15) << _expected << endl; \ if (exit_if_not) exit(_nfail); \ } \ }while(false) // --------------------------------------------------------------------------- #define STREQUAL(actual, expected, message, exit_if_not) \ do { \ string _actual = (actual); \ string _expected = (expected); \ if (_actual != _expected) { \ _nfail++; \ cerr << message << endl; \ cerr << " Actual: " << _actual << endl; \ cerr << " Expected: " << _expected << endl; \ if (exit_if_not) exit(_nfail); \ } \ }while(false) // --------------------------------------------------------------------------- #define EXPECT_NULL(actual, message) NULLPTR(actual, message, false) #define EXPECT_NOT_NULL(actual, message) NOT_NULLPTR(actual, message, false) #define EXPECT_EQUAL(actual, expected, message) EQUAL(actual, expected, message, false) #define EXPECT_NOT_EQUAL(actual, expected, message) NOT_EQUAL(actual, expected, message, false) #define EXPECT_STREQUAL (actual, expected, message) STREQUAL(actual, expected, message, false) // --------------------------------------------------------------------------- #define ASSERT_NULL(actual, message) NULLPTR(actual, message, true) #define ASSERT_NOT_NULL(actual, message) NOT_NULLPTR(actual, message, true) #define ASSERT_EQUAL(actual, expected, message) EQUAL(actual, expected, message, true) #define ASSERT_NOT_EQUAL(actual, expected, message) NOT_EQUAL(actual, expected, message, true) #define ASSERT_STREQUAL(actual, expected, message) STREQUAL(actual, expected, message, true) // =========================================================================== // Test images // =========================================================================== // --------------------------------------------------------------------------- template <class VoxelType> GenericImage<VoxelType> *create_test_image(int x = 16, int y = 16, int z = 1, int t = 1, int n = 1) { // Instantiate image GenericImage<VoxelType> *image = new GenericImage<double>(x, y, z, t, n); // Fill test image for (int l = 0; l < image->T(); l++) { for (int k = 0; k < image->Z(); k++) { for (int j = 0; j < image->Y(); j++) { for (int i = 0; i < image->X(); i++) { image->Put(i, j, k, l, static_cast<VoxelType>(image->VoxelToIndex(i, j, k, l))); } } } } return image; } // =========================================================================== // Tests // =========================================================================== // --------------------------------------------------------------------------- int test_Initialize() { TEST("test_Initialize"); GenericImage<double> *image = create_test_image<double>(16, 16); InterpolateImageFunction *inter = InterpolateImageFunction::New(Interpolation_NN, Extrapolation_Const, image); ExtrapolateImageFunction *extra = inter->Extrapolator(); inter->Initialize(); extra->Initialize(); // not required, but shall also not hurt (ie., recurse infinitely) inter->Initialize(); return RESULT; } // --------------------------------------------------------------------------- int test_IsInsideOutside() { TEST("test_IsInsideOutside"); GenericImage<double> *image = NULL; InterpolateImageFunction *inter = NULL; //ExtrapolateImageFunction *extra = NULL; // -------------------------------------------------------------------------- // 2D image = create_test_image<double>(16, 16); inter = InterpolateImageFunction::New(Interpolation_NN, Extrapolation_Const, image); //extra = inter->Extrapolator(); inter->Initialize(); EXPECT_EQUAL(inter->IsInside (3.0, 2.0), true, "Check if voxel is inside image domain"); EXPECT_EQUAL(inter->IsInside (3.4, 2.1), true, "Check if sub-voxel is inside image domain"); EXPECT_EQUAL(inter->IsInside (-3.0, 0.0), false, "Check if voxel is outside image domain"); EXPECT_EQUAL(inter->IsInside (-3.4, 2.1), false, "Check if sub-voxel is outside image domain"); delete image; delete inter; // -------------------------------------------------------------------------- // 3D image = create_test_image<double>(16, 16, 16); inter = InterpolateImageFunction::New(Interpolation_NN, Extrapolation_Const, image); //extra = inter->Extrapolator(); inter->Initialize(); EXPECT_EQUAL(inter->IsInside (3.0, 2.0, 5.0), true, "Check if voxel is inside image domain"); EXPECT_EQUAL(inter->IsInside (3.4, 2.1, 5.5), true, "Check if sub-voxel is inside image domain"); EXPECT_EQUAL(inter->IsInside (-3.0, 0.0, 1.0), false, "Check if voxel is outside image domain"); EXPECT_EQUAL(inter->IsInside (-3.4, 2.1, 1.0), false, "Check if sub-voxel is outside image domain"); delete image; delete inter; return RESULT; } // --------------------------------------------------------------------------- int test_Interpolation_NN_Extrapolation_Default() { TEST("test_Interpolation_NN_Extrapolation_Default"); GenericImage<double> *image = create_test_image<double>(16, 16, 16); InterpolateImageFunction *func = InterpolateImageFunction::New(Interpolation_NN, image); // Initialize image function EXPECT_NULL(func->Extrapolator(), "Extrapolator not instantiated yet"); func->Initialize(); ASSERT_NOT_NULL(func->Extrapolator(), "Extrapolator initialized"); // Check instantiated image function ASSERT_STREQUAL(func->NameOfClass(), "GenericNearestNeighborInterpolateImageFunction", "Type of interpolator"); ASSERT_STREQUAL(func->Extrapolator()->NameOfClass(), "GenericConstExtrapolateImageFunction", "Type of extrapolator"); EXPECT_EQUAL(func->Extrapolator()->DefaultValue(), 0, "Constant outside value"); // Interpolate inside of image domain EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.0), image->VoxelToIndex(3, 2, 5), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.1, 5.5), image->VoxelToIndex(3, 2, 6), "Interpolate image value at sub-voxel position"); // Extrapolate outside of image domain EXPECT_EQUAL(func->Evaluate(-3.0, 0.0, 1.0), 0, "Extrapolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(-3.4, 2.1, 1.0), 0, "Extrapolate image value at sub-voxel position"); // Clean up delete image; delete func; return RESULT; } // --------------------------------------------------------------------------- int test_Interpolation_NN_Extrapolation_Const() { TEST("test_Interpolation_NN_Extrapolation_Const"); GenericImage<double> *image = NULL; InterpolateImageFunction *func = NULL; // ------------------------------------------------------------------------- // 2D image = create_test_image<double>(16, 16); func = InterpolateImageFunction::New(Interpolation_NN, Extrapolation_Const, image); // Initialize image function func->Initialize(); // Check instantiated image function ASSERT_STREQUAL(func->NameOfClass(), "GenericNearestNeighborInterpolateImageFunction", "Type of interpolator"); ASSERT_STREQUAL(func->Extrapolator()->NameOfClass(), "GenericConstExtrapolateImageFunction", "Type of extrapolator"); EXPECT_EQUAL(func->Extrapolator()->DefaultValue(), 0, "Constant outside value"); // Interpolate inside of image domain EXPECT_EQUAL(func->Evaluate(3.0, 2.0), image->VoxelToIndex(3, 2), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.1), image->VoxelToIndex(3, 2), "Interpolate image value at sub-voxel position"); // Extrapolate outside of image domain EXPECT_EQUAL(func->Evaluate(-3.0, 0.0), 0, "Extrapolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(-3.4, 2.1), 0, "Extrapolate image value at sub-voxel position"); // Clean up delete image; delete func; // ------------------------------------------------------------------------- // 3D image = create_test_image<double>(16, 16, 16); func = InterpolateImageFunction::New(Interpolation_NN, Extrapolation_Const, image); // Initialize image function func->Initialize(); // Check instantiated image function ASSERT_STREQUAL(func->NameOfClass(), "GenericNearestNeighborInterpolateImageFunction", "Type of interpolator"); ASSERT_STREQUAL(func->Extrapolator()->NameOfClass(), "GenericConstExtrapolateImageFunction", "Type of extrapolator"); EXPECT_EQUAL(func->Extrapolator()->DefaultValue(), 0, "Constant outside value"); // Interpolate inside of image domain EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.0), image->VoxelToIndex(3, 2, 5), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.1, 5.5), image->VoxelToIndex(3, 2, 6), "Interpolate image value at sub-voxel position"); // Extrapolate outside of image domain EXPECT_EQUAL(func->Evaluate(-3.0, 0.0, 1.0), 0, "Extrapolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(-3.4, 2.1, 1.0), 0, "Extrapolate image value at sub-voxel position"); // Clean up delete image; delete func; return RESULT; } // --------------------------------------------------------------------------- int test_Interpolation_Linear_Extrapolation_Const() { TEST("test_Interpolation_Linear_Extrapolation_Const"); GenericImage<double> *image = NULL; InterpolateImageFunction *func = NULL; // ------------------------------------------------------------------------- // 2D image = create_test_image<double>(16, 16); func = InterpolateImageFunction::New(Interpolation_Linear, Extrapolation_Const, image); // Initialize image function func->Initialize(); func->Extrapolator()->DefaultValue(-1); // Check instantiated image function ASSERT_STREQUAL(func->NameOfClass(), "GenericLinearInterpolateImageFunction2D", "Type of interpolator"); ASSERT_STREQUAL(func->Extrapolator()->NameOfClass(), "GenericConstExtrapolateImageFunction", "Type of extrapolator"); // Interpolate inside image domain EXPECT_EQUAL(func->Evaluate(3.0, 2.0), image->VoxelToIndex(3, 2), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.0), 0.6 * image->VoxelToIndex(3, 2) + 0.4 * image->VoxelToIndex(4, 2), "Interpolate image value at sub-voxel position along x"); EXPECT_EQUAL(func->Evaluate(3.0, 2.7), 0.3 * image->VoxelToIndex(3, 2) + 0.7 * image->VoxelToIndex(3, 3), "Interpolate image value at sub-voxel position along y"); // Extrapolate outside image domain ASSERT_EQUAL(func->Extrapolator()->DefaultValue(), -1, "Default value of extrapolator"); EXPECT_EQUAL(func->Evaluate(-0.1, -0.1), -0.19, "Extrapolate image value outside of image domain"); EXPECT_EQUAL(func->Evaluate(-1.1, 0.0), -1, "Extrapolate image value outside of image domain in x"); EXPECT_EQUAL(func->Evaluate(16.1, 0.0), -1, "Extrapolate image value outside of image domain in x"); EXPECT_EQUAL(func->Evaluate( 0.0, -1.1), -1, "Extrapolate image value outside of image domain in y"); EXPECT_EQUAL(func->Evaluate( 0.0, 16.1), -1, "Extrapolate image value outside of image domain in y"); EXPECT_EQUAL(func->Evaluate(-1.1, -1.1), -1, "Extrapolate image value outside of image domain in x and y"); EXPECT_EQUAL(func->Evaluate(16.1, 16.1), -1, "Extrapolate image value outside of image domain in x and y"); // Clean up delete image; delete func; // ------------------------------------------------------------------------- // 3D image = create_test_image<double>(16, 16, 16); func = InterpolateImageFunction::New(Interpolation_Linear, Extrapolation_Const, image); // Initialize image function func->Initialize(); func->Extrapolator()->DefaultValue(-1); // Check instantiated image function ASSERT_STREQUAL(func->NameOfClass(), "GenericLinearInterpolateImageFunction3D", "Type of interpolator"); ASSERT_STREQUAL(func->Extrapolator()->NameOfClass(), "GenericConstExtrapolateImageFunction", "Type of extrapolator"); // Interpolate inside image domain EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.0), image->VoxelToIndex(3, 2, 5), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.0, 5.0), 0.6 * image->VoxelToIndex(3, 2, 5) + 0.4 * image->VoxelToIndex(4, 2, 5), "Interpolate image value at sub-voxel position along x"); EXPECT_EQUAL(func->Evaluate(3.0, 2.7, 5.0), 0.3 * image->VoxelToIndex(3, 2, 5) + 0.7 * image->VoxelToIndex(3, 3, 5), "Interpolate image value at sub-voxel position along y"); EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.1), 0.9 * image->VoxelToIndex(3, 2, 5) + 0.1 * image->VoxelToIndex(3, 2, 6), "Interpolate image value at sub-voxel position along z"); // Extrapolate outside image domain ASSERT_EQUAL(func->Extrapolator()->DefaultValue(), -1, "Default value of extrapolator"); EXPECT_EQUAL(func->Evaluate(-1.1, 0.0, 0.0), -1, "Extrapolate image value slightly outside of image domain in x"); EXPECT_EQUAL(func->Evaluate(16.1, 0.0, 0.0), -1, "Extrapolate image value slightly outside of image domain in x"); EXPECT_EQUAL(func->Evaluate( 0.0, -1.1, 0.0), -1, "Extrapolate image value slightly outside of image domain in y"); EXPECT_EQUAL(func->Evaluate( 0.0, 16.1, 0.0), -1, "Extrapolate image value slightly outside of image domain in y"); EXPECT_EQUAL(func->Evaluate( 0.0, 0.0, -1.1), -1, "Extrapolate image value slightly outside of image domain in z"); EXPECT_EQUAL(func->Evaluate( 0.0, 0.0, 16.1), -1, "Extrapolate image value slightly outside of image domain in z"); EXPECT_EQUAL(func->Evaluate(-1.1, -1.1, 0.0), -1, "Extrapolate image value slightly outside of image domain in x and y"); EXPECT_EQUAL(func->Evaluate(16.1, 16.1, 0.0), -1, "Extrapolate image value slightly outside of image domain in x and y"); EXPECT_EQUAL(func->Evaluate(-1.1, 0.0, -1.1), -1, "Extrapolate image value slightly outside of image domain in x and z"); EXPECT_EQUAL(func->Evaluate(16.1, 0.0, 16.1), -1, "Extrapolate image value slightly outside of image domain in x and z"); EXPECT_EQUAL(func->Evaluate( 0.0, -1.1, -1.1), -1, "Extrapolate image value slightly outside of image domain in y and z"); EXPECT_EQUAL(func->Evaluate( 0.0, 16.1, 16.1), -1, "Extrapolate image value slightly outside of image domain in y and z"); // Clean up delete image; delete func; // ------------------------------------------------------------------------- // 3D vector field image = create_test_image<double>(16, 16, 16, 1, 3); func = InterpolateImageFunction::New(Interpolation_Linear, Extrapolation_Const, image); // Initialize image function func->Initialize(); func->Extrapolator()->DefaultValue(-1); // Check instantiated image function ASSERT_STREQUAL(func->NameOfClass(), "GenericLinearInterpolateImageFunction3D", "Type of interpolator"); ASSERT_STREQUAL(func->Extrapolator()->NameOfClass(), "GenericConstExtrapolateImageFunction", "Type of extrapolator"); // Interpolate inside image domain EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.0, 0.0), image->VoxelToIndex(3, 2, 5, 0), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.0, 5.0, 0.0), 0.6 * image->VoxelToIndex(3, 2, 5, 0) + 0.4 * image->VoxelToIndex(4, 2, 5, 0), "Interpolate image value at sub-voxel position along x"); EXPECT_EQUAL(func->Evaluate(3.0, 2.7, 5.0, 0.0), 0.3 * image->VoxelToIndex(3, 2, 5, 0) + 0.7 * image->VoxelToIndex(3, 3, 5, 0), "Interpolate image value at sub-voxel position along y"); EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.1, 0.0), 0.9 * image->VoxelToIndex(3, 2, 5, 0) + 0.1 * image->VoxelToIndex(3, 2, 6, 0), "Interpolate image value at sub-voxel position along z"); EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.0, 1.0), image->VoxelToIndex(3, 2, 5, 1), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.0, 5.0, 1.0), 0.6 * image->VoxelToIndex(3, 2, 5, 1) + 0.4 * image->VoxelToIndex(4, 2, 5, 1), "Interpolate image value at sub-voxel position along x"); EXPECT_EQUAL(func->Evaluate(3.0, 2.7, 5.0, 1.0), 0.3 * image->VoxelToIndex(3, 2, 5, 1) + 0.7 * image->VoxelToIndex(3, 3, 5, 1), "Interpolate image value at sub-voxel position along y"); EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.1, 1.0), 0.9 * image->VoxelToIndex(3, 2, 5, 1) + 0.1 * image->VoxelToIndex(3, 2, 6, 1), "Interpolate image value at sub-voxel position along z"); EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.0, 2.0), image->VoxelToIndex(3, 2, 5, 2), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.0, 5.0, 2.0), 0.6 * image->VoxelToIndex(3, 2, 5, 2) + 0.4 * image->VoxelToIndex(4, 2, 5, 2), "Interpolate image value at sub-voxel position along x"); EXPECT_EQUAL(func->Evaluate(3.0, 2.7, 5.0, 2.0), 0.3 * image->VoxelToIndex(3, 2, 5, 2) + 0.7 * image->VoxelToIndex(3, 3, 5, 2), "Interpolate image value at sub-voxel position along y"); EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.1, 2.0), 0.9 * image->VoxelToIndex(3, 2, 5, 2) + 0.1 * image->VoxelToIndex(3, 2, 6, 2), "Interpolate image value at sub-voxel position along z"); // Clean up delete image; delete func; return RESULT; } // --------------------------------------------------------------------------- int test_Interpolation_Linear_Extrapolation_NN() { TEST("test_Interpolation_Linear_Extrapolation_NN"); GenericImage<double> *image = NULL; InterpolateImageFunction *func = NULL; // ------------------------------------------------------------------------- // 2D image = create_test_image<double>(16, 16); func = InterpolateImageFunction::New(Interpolation_Linear, Extrapolation_NN, image); // Initialize image function func->Initialize(); // Check instantiated image function ASSERT_STREQUAL(func->NameOfClass(), "GenericLinearInterpolateImageFunction2D", "Type of interpolator"); ASSERT_STREQUAL(func->Extrapolator()->NameOfClass(), "GenericNearestNeighborExtrapolateImageFunction", "Type of extrapolator"); // Interpolate inside image domain EXPECT_EQUAL(func->Evaluate(3.0, 2.0), image->VoxelToIndex(3, 2), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.0), 0.6 * image->VoxelToIndex(3, 2) + 0.4 * image->VoxelToIndex(4, 2), "Interpolate image value at sub-voxel position along x"); EXPECT_EQUAL(func->Evaluate(3.0, 2.7), 0.3 * image->VoxelToIndex(3, 2) + 0.7 * image->VoxelToIndex(3, 3), "Interpolate image value at sub-voxel position along y"); // Extrapolate outside image domain EXPECT_EQUAL(func->Evaluate(-0.1, 0.0), image->VoxelToIndex( 0, 0), "Extrapolate image value slightly outside of image domain in x"); EXPECT_EQUAL(func->Evaluate(15.1, 0.0), image->VoxelToIndex(15, 0), "Extrapolate image value slightly outside of image domain in x"); EXPECT_EQUAL(func->Evaluate( 0.0, -0.1), image->VoxelToIndex( 0, 0), "Extrapolate image value slightly outside of image domain in y"); EXPECT_EQUAL(func->Evaluate( 0.0, 15.1), image->VoxelToIndex( 0, 15), "Extrapolate image value slightly outside of image domain in y"); EXPECT_EQUAL(func->Evaluate(-0.1, -0.1), image->VoxelToIndex( 0, 0), "Extrapolate image value slightly outside of image domain in x and y"); EXPECT_EQUAL(func->Evaluate(15.1, 15.1), image->VoxelToIndex(15, 15), "Extrapolate image value slightly outside of image domain in x and y"); // Clean up delete image; delete func; // ------------------------------------------------------------------------- // 3D image = create_test_image<double>(16, 16, 16); func = InterpolateImageFunction::New(Interpolation_Linear, Extrapolation_NN, image); // Initialize image function func->Initialize(); // Check instantiated image function ASSERT_STREQUAL(func->NameOfClass(), "GenericLinearInterpolateImageFunction3D", "Type of interpolator"); ASSERT_STREQUAL(func->Extrapolator()->NameOfClass(), "GenericNearestNeighborExtrapolateImageFunction", "Type of extrapolator"); // Interpolate inside image domain EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.0), image->VoxelToIndex(3, 2, 5), "Interpolate image value at voxel position"); EXPECT_EQUAL(func->Evaluate(3.4, 2.0, 5.0), 0.6 * image->VoxelToIndex(3, 2, 5) + 0.4 * image->VoxelToIndex(4, 2, 5), "Interpolate image value at sub-voxel position along x"); EXPECT_EQUAL(func->Evaluate(3.0, 2.7, 5.0), 0.3 * image->VoxelToIndex(3, 2, 5) + 0.7 * image->VoxelToIndex(3, 3, 5), "Interpolate image value at sub-voxel position along y"); EXPECT_EQUAL(func->Evaluate(3.0, 2.0, 5.1), 0.9 * image->VoxelToIndex(3, 2, 5) + 0.1 * image->VoxelToIndex(3, 2, 6), "Interpolate image value at sub-voxel position along z"); // Extrapolate outside image domain EXPECT_EQUAL(func->Evaluate(-0.1, 0.0, 0.0), image->VoxelToIndex( 0, 0, 0), "Extrapolate image value slightly outside of image domain in x"); EXPECT_EQUAL(func->Evaluate(15.1, 0.0, 0.0), image->VoxelToIndex(15, 0, 0), "Extrapolate image value slightly outside of image domain in x"); EXPECT_EQUAL(func->Evaluate( 0.0, -0.1, 0.0), image->VoxelToIndex( 0, 0, 0), "Extrapolate image value slightly outside of image domain in y"); EXPECT_EQUAL(func->Evaluate( 0.0, 15.1, 0.0), image->VoxelToIndex( 0, 15, 0), "Extrapolate image value slightly outside of image domain in y"); EXPECT_EQUAL(func->Evaluate( 0.0, 0.0, -0.1), image->VoxelToIndex( 0, 0, 0), "Extrapolate image value slightly outside of image domain in z"); EXPECT_EQUAL(func->Evaluate( 0.0, 0.0, 15.1), image->VoxelToIndex( 0, 0, 15), "Extrapolate image value slightly outside of image domain in z"); EXPECT_EQUAL(func->Evaluate(-0.1, -0.1, 0.0), image->VoxelToIndex( 0, 0, 0), "Extrapolate image value slightly outside of image domain in x and y"); EXPECT_EQUAL(func->Evaluate(15.1, 15.1, 0.0), image->VoxelToIndex(15, 15, 0), "Extrapolate image value slightly outside of image domain in x and y"); EXPECT_EQUAL(func->Evaluate(-0.1, 0.0, -0.1), image->VoxelToIndex( 0, 0, 0), "Extrapolate image value slightly outside of image domain in x and z"); EXPECT_EQUAL(func->Evaluate(15.1, 0.0, 15.1), image->VoxelToIndex(15, 0, 15), "Extrapolate image value slightly outside of image domain in x and z"); EXPECT_EQUAL(func->Evaluate( 0.0, -0.1, -0.1), image->VoxelToIndex( 0, 0, 0), "Extrapolate image value slightly outside of image domain in y and z"); EXPECT_EQUAL(func->Evaluate( 0.0, 15.1, 15.1), image->VoxelToIndex( 0, 15, 15), "Extrapolate image value slightly outside of image domain in y and z"); // Clean up delete image; delete func; return RESULT; } // =========================================================================== // Main // =========================================================================== // --------------------------------------------------------------------------- int InterpolateExtrapolateImageFunctionTest(int, char *[]) { int retval = 0; retval += test_Initialize(); retval += test_IsInsideOutside(); retval += test_Interpolation_NN_Extrapolation_Default(); retval += test_Interpolation_NN_Extrapolation_Const(); retval += test_Interpolation_Linear_Extrapolation_Const(); retval += test_Interpolation_Linear_Extrapolation_NN(); return retval; }
[ "andreas.schuh.84@gmail.com" ]
andreas.schuh.84@gmail.com
f5c5c3f83dcbf37207f99c4e83be685e99276a08
7466f46b164630386bd46ec64c9f204e1500b82f
/OpenCV/Practice/Include/Background.h
3771c1c116f0f3ff7428baeb127640ed689a5490
[]
no_license
pray92/CPL-20162-Team4
8875c26c1efffa8fb4de86048e96150d5764c923
777c1929c3e784dc1b34c6b933522aa8532c6dfb
refs/heads/master
2020-09-21T16:46:27.445241
2016-11-23T11:32:31
2016-11-23T11:32:31
67,261,869
0
0
null
null
null
null
UTF-8
C++
false
false
329
h
#pragma once #include "Obj.h" class CBackground : public CObj { private: static bool m_bTextCalled; private: RECT m_rcFrame; public: virtual HRESULT Initialize(void); virtual SCENE Progress(void); virtual void Render(void); virtual void Release(void); public: CBackground(); CBackground(int _iID); ~CBackground(); };
[ "redgem92@gmail.com" ]
redgem92@gmail.com
0c211a265b793ca689ed94b4f5ef5e4c9d611e72
e55cd096872867e619811e6ad52cfed9226d9b10
/Culling2D/Culling/culling2d.Object.cpp
a0498646be82c5ac0b85a899d23438853b8c808e
[]
no_license
altseed/Culling2D
e81e7ad2314df7e8340ba8cc4dc4e43cbe0576da
ecb2d0200ed3d1d98c28f3756605056e0f73b3b4
refs/heads/master
2020-04-13T13:01:21.214691
2018-01-06T10:46:44
2018-01-06T10:46:44
21,387,328
0
0
null
null
null
null
UTF-8
C++
false
false
1,961
cpp
#include "../Culling2D.h" #include "../../culling2d_common/src/Culling2DCommon.h" namespace culling2d { Object::Object(void* userdata, World *worldRef) : userData(userdata) , worldRef(worldRef) , sortedKey(0) , isInWorld(true) { SafeAddRef(worldRef); circle = culling2d::Circle(culling2d::Vector2DF(0, 0), 0); } bool Object::GetIsInWorld() const { return isInWorld; } void Object::SetIsInWorld(bool isinworld) { isInWorld = isinworld; } Object::~Object() { SafeRelease(worldRef); } const Circle& Object::GetCircle() const { return circle; } void Object::SetCircle(Circle circle) { if (this->circle != circle) { this->circle = circle; worldRef->NotifyMoved(this); } } void* Object::GetUserData() const { return userData; } void Object::SetUserData(void* userData) { this->userData = userData; } RectF Object::GetCurrentRange() const { return currentRange; } void Object::SetCurrentRange(RectF range) { this->currentRange = range; } bool Object::IsProperPosition() const { auto position = circle.Position; auto diameter = circle.Radius * 2; return currentRange.GetIsContainingPoint(position) && currentRange.Height >= diameter&&currentRange.Width >= diameter; } void Object::SetSecondSortedKey(uint32_t secondKey) { uint64_t conv = secondKey; sortedKey |= conv; } uint32_t Object::GetSecondSortedKey() { uint64_t mask = 0x00000000ffffffff; uint64_t conv = sortedKey & mask; return (uint32_t)conv; } void Object::SetFirstSortedKey(uint32_t firstKey) { uint64_t conv = firstKey; conv <<= 32; sortedKey |= conv; } uint32_t Object::GetFirstSortedKey() { uint64_t mask = 0xffffffff00000000; uint64_t conv = sortedKey & mask; return (uint32_t)(conv >> 32); } Object* Object::Create(void *userdata, World* worldRef) { return new Object(userdata, worldRef); } uint64_t Object::GetSortedKey() const { return sortedKey; } };
[ "dtm.music.producer@gmail.com" ]
dtm.music.producer@gmail.com
a3a0a856cdb016894dbcd50302783a94d61e8e90
697d8dcb9b39ef858cad57d7eced694590821ded
/EquationsOfMathematicalMagic.cpp
39f10de615c804cba4060ac4ac5613585bb2dfbb
[]
no_license
KevinMathewT/Competitive-Programming
e1dcdffd087f8a1d5ca29ae6189ca7fddbdc7754
e7805fe870ad9051d53cafcba4ce109488bc212d
refs/heads/master
2022-02-14T09:37:31.637330
2020-09-26T16:15:26
2020-09-26T16:15:26
147,362,660
4
4
null
2022-02-07T11:13:38
2018-09-04T14:52:29
C++
UTF-8
C++
false
false
567
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; // Author - Kevin Mathew // Birla Institute of Technology, Mesra void te(){ ll a; cin >> a; for(ll j=0;j<50;j++){ a = j; ll c = 0; for(ll i=0;i<=a+10;i++) if((a - (a ^ i) - i) >= 0) c++; cout << a << " " << c << "\n"; } } int main() { freopen("input.txt", "r", stdin); //Comment freopen("output.txt", "w", stdout); //this out. ios::sync_with_stdio(false); //Not cin.tie(NULL); //this. cout.tie(0); //or this. ll T; cin >> T; while(T--) te(); return 0; }
[ "mathewtkevin@gmail.com" ]
mathewtkevin@gmail.com
d7a265eefabb33afcacc971e6ea1ec3d3980904f
da810b0113f427ebddb0d22ea5321e81ef74baa7
/Assignment2/main.cpp
f57dd777ac282458103e67900d39565cd6b3d11e
[ "MIT" ]
permissive
HEYHO8037/POCU
8f8a6f50d9e4860de3feec1246ee7eee89df5e23
811979ec56ec6401807e6967845c6f4581884d5f
refs/heads/master
2023-06-28T07:40:44.596847
2021-07-29T12:54:40
2021-07-29T12:54:40
363,791,190
0
0
null
null
null
null
UTF-8
C++
false
false
3,570
cpp
#include <cassert> #include <iostream> #include <iomanip> #include "Vehicle.h" #include "Airplane.h" #include "Boat.h" #include "Boatplane.h" #include "Motorcycle.h" #include "Sedan.h" #include "UBoat.h" #include "Trailer.h" #include "DeusExMachina.h" #include "Person.h" #define _CRTDBG_MAP_ALLOC #include <cstdlib> #include <crtdbg.h> #ifdef _DEBUG #define new new ( _NORMAL_BLOCK , __FILE__ , __LINE__ ) #endif #define STR(name) #name using namespace assignment2; using namespace std; int main() { const char* MAX_SPEED_LABLE = "Max Speed: "; const char* CUR_P_LABLE = "Current Person: "; const unsigned int MAX_CAPACITY = 10; Vehicle* air = new Airplane(MAX_CAPACITY); Person* toAdd; const unsigned int personWeight = 10; for (size_t i = 0; i < MAX_CAPACITY + 10; i++) { toAdd = new Person(STR(i), i); if (air->AddPassenger(toAdd) == false) { delete toAdd; } cout << MAX_SPEED_LABLE << air->GetMaxSpeed() << endl << CUR_P_LABLE << air->GetPassengersCount() << endl; } while (air->RemovePassenger(0)) { cout << CUR_P_LABLE << air->GetPassengersCount() << endl;; } Person* overlapTest = new Person("Overlap Test", 100); air->AddPassenger(overlapTest); //air->AddPassenger(overlapTest); //assert(air->GetPassengersCount() == 1); // 빌드봇은 이런 테스트 안함 //toAdd = NULL; //assert(air->AddPassenger(toAdd) == false); // 빌드봇은 이런 테스트 안함 delete air; Airplane dockingTest1(10); Boat dockingTest2(10); for (size_t i = 0; i < 5; i++) { dockingTest1.AddPassenger(new Person(STR(i), i)); dockingTest2.AddPassenger(new Person(STR(i), i)); } const Person* comp1 = dockingTest1.GetPassenger(0); Boatplane bp1 = dockingTest1 + dockingTest2; Boatplane bp2 = dockingTest2 + dockingTest1; const Person* comp2 = bp1.GetPassenger(0); //assert(comp1 == comp2); // 빌드봇은 이런 테스트 안함 assert(dockingTest1.GetPassengersCount() == 0); assert(dockingTest2.GetPassengersCount() == 0); assert(bp1.GetPassengersCount() == 10); assert(bp2.GetPassengersCount() == 0); Boatplane copyConstuctorTest(bp1); for (size_t i = 0; i < bp1.GetPassengersCount(); i++) { const Person* p1 = bp1.GetPassenger(i); const Person* p2 = copyConstuctorTest.GetPassenger(i); assert(p1 != p2); } assert(bp1.GetMaxPassengersCount() == copyConstuctorTest.GetMaxPassengersCount()); assert(bp1.GetPassengersCount() == copyConstuctorTest.GetPassengersCount()); assert(bp1.GetMaxSpeed() == copyConstuctorTest.GetMaxSpeed()); Sedan sedanTest; Trailer* t1 = new Trailer(10); Trailer* t2 = new Trailer(20); assert(sedanTest.AddTrailer(t1)); assert(!sedanTest.AddTrailer(t1)); assert(!sedanTest.AddTrailer(t2)); assert(sedanTest.RemoveTrailer()); assert(sedanTest.AddTrailer(t2)); assert(sedanTest.RemoveTrailer()); DeusExMachina* d = DeusExMachina::GetInstance(); Vehicle* demAirplain = new Airplane(MAX_CAPACITY); Vehicle* demBoat = new Airplane(MAX_CAPACITY); Vehicle* demBoatplain = new Boatplane(MAX_CAPACITY); Vehicle* demMotorcycle = new Motorcycle(); Vehicle* demSedan1 = new Sedan(); Vehicle* demSedan2 = new Sedan(); Trailer* demTrailer = new Trailer(10); static_cast<Sedan*>(demSedan2)->AddTrailer(demTrailer); Vehicle* demUBoat = new UBoat(); d->AddVehicle(demAirplain); d->AddVehicle(demBoat); d->AddVehicle(demBoatplain); d->AddVehicle(demMotorcycle); d->AddVehicle(demSedan1); d->AddVehicle(demSedan2); d->AddVehicle(demUBoat); for (size_t i = 0; i < 10; i++) { d->Travel(); } delete d; return 0; _CrtDumpMemoryLeaks(); }
[ "haeho8037@gmail.com" ]
haeho8037@gmail.com
782efe2d68ec986c278a31f8b6316693f05b797a
e8971f7cc6afc0cd0ccb6b9635e4b8b3eb658ca2
/rtos/teststates.hpp
e345779c73584e6bffb7c296ad881a6166eff96d
[ "MIT" ]
permissive
NikitaFedotovKE-415/CortexLib
1c5d0ba17c66034974f06983e1541d811d33c778
6746c668e3f874da18da8d1d33c2c198878bcbf2
refs/heads/master
2022-12-29T17:09:51.217934
2020-10-17T14:15:35
2020-10-17T14:15:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,515
hpp
// Filename: testthread.hpp // Created by by Sergey aka Lamerok on 30.03.2020. #pragma once #include <iostream> // for cout #include "taskbase.hpp" // for TaskBase #include "gpiocregisters.hpp" struct TargetThread: public TaskBase<TargetThread> { constexpr TargetThread() { } void OnEvent() const { GPIOC::ODR::Toggle(1<<8); // std::cout << "TargetThread" << std::endl; } }; inline constexpr TargetThread targetThread; template<typename SimpleTasker, auto& threadToSignal> struct Thread1 : public TaskBase<Thread1<SimpleTasker, threadToSignal>> { constexpr Thread1() { } void OnEvent() const { // std::cout << " Thread1Start" << std::endl; GPIOC::ODR::Toggle(1<<9); SimpleTasker::PostEvent<threadToSignal>(1); // std::cout << " Thread1End" << std::endl; } }; template<typename SimpleTasker, auto& threadToSignal> struct Thread2 : public TaskBase<Thread2<SimpleTasker, threadToSignal>> { constexpr Thread2() { } void OnEvent() const { GPIOC::ODR::Toggle(1<<5); // std::cout << " Thread2Start" << std::endl; for (int i = 0; i < 4000000; ++i) { }; SimpleTasker::PostEvent<threadToSignal>(1); // std::cout << " Thread2End: " << test << std::endl; test ++ ; } private: inline static int test ; }; class myTasker; inline constexpr Thread1<myTasker, targetThread> myThread1; inline constexpr Thread2<myTasker, targetThread> myThread2;
[ "sergey.kolody@gmail.com" ]
sergey.kolody@gmail.com
ede918e7d69a6b1d2d7516932717384d4eecf686
ebe880db8a4f2341913bb2b79e4bbd6a6295793f
/tracce/traccia12ALBN/Tree.h
e00169e49a61cbdf886902360acc0ed4d0c66731
[]
no_license
donakunn/CPPfiles
51a4132c006ad1830cc23a959163a863170bb91a
ea29a6ef7c528ce9061f1a2c46abe8ed8cd04d71
refs/heads/main
2023-02-24T11:06:34.922032
2021-02-02T11:39:26
2021-02-02T11:39:26
311,754,812
0
0
null
null
null
null
UTF-8
C++
false
false
1,667
h
#ifndef TREE_H #define TREE_H template<class I, class N> class Tree { public: typedef I item; typedef N node; virtual void create () = 0; virtual bool empty () const = 0; virtual void insRoot () = 0; virtual node root () const = 0; virtual node parent (const node) const = 0; virtual bool leaf (const node) const = 0; virtual node firstChild (const node) const = 0; virtual bool lastSibling (const node) const = 0; virtual node nextSibling (const node) const = 0; virtual void insFirst(node, const item) = 0; virtual void ins(node, const item) = 0; //virtual void insFirstSubTree (node, Tree<I,N> &) = 0; //virtual void insSubTree (node, Tree<I,N> &) = 0; virtual void removeSubTree (node) = 0; virtual void writeNode (node, const item) = 0; virtual item readNode (const node) const = 0; virtual void preorder(node); virtual void postorder(node); virtual void inorder(node); }; template <class I, class N> void Tree<I,N>::preorder(node n) { //visita il nodo if (!leaf(n)) { node k = firstChild(n); while (!lastSibling(k)) { preorder(k); k = nextSibling(k); } preorder(k); } } template <class I, class N> void Tree<I,N>::postorder(node n) { if (!leaf(n)) { node k = firstChild(n); while (!lastSibling(k)) { postorder(k); k = nextSibling(k); } postorder(k); } //visita il nodo } template <class I, class N> void Tree<I,N>::inorder(node n) { if (leaf(n)) { //esamina nodo } else { node k = firstChild(n); inorder(k); //esamina nodo n while(!lastSibling(k)) { k = nextSibling(k); inorder(k); } } } #endif
[ "donalara.@gmail.com" ]
donalara.@gmail.com
e333fd9affb8cf6c1d5b4c180708d3b174e3b89b
d64aa7397b92356cec1ae9f380e664a44044a0c8
/Project1/shape.h
c68acdc657a867663cc8f2596e46f1fb9539fb6d
[ "MIT" ]
permissive
Lentono/Riddle.ioArtificialIntelligence
5e03310b3c7e29d0c81d1edc542435105510c8a7
7e1b008854df53ae81b464f50ea9b31b66cf8041
refs/heads/master
2020-05-02T15:37:39.650292
2019-03-27T17:54:53
2019-03-27T17:54:53
178,047,614
0
0
null
null
null
null
UTF-8
C++
false
false
8,068
h
// Christos Savvopoulos <savvopoulos@gmail.com> // Elias Sprengel <blockbattle@webagent.eu> #ifndef __SHAPE_H #define __SHAPE_H #include <memory> #include <vector> #include <string> #include "cell.h" #include "field.h" using namespace std; /** * Represents the shapes that appear in the field. * Some basic methods have already been implemented, but * actual move actions, etc. should still be created. */ class Shape { public: // Enum for all possible Shape types. enum ShapeType { I, J, L, O, S, T, Z, NONE }; Shape(ShapeType type, const Field& field, int x, int y) : type_(type), x_(x), y_(y), field_(field) { SetShape(); SetBlockLocations(); } int x() const { return x_; } int y() const { return y_; } static ShapeType StringToShapeType(string name) { if (name == "I") { return ShapeType::I; } if (name == "J") { return ShapeType::J; } if (name == "L") { return ShapeType::L; } if (name == "O") { return ShapeType::O; } if (name == "S") { return ShapeType::S; } if (name == "T") { return ShapeType::T; } if (name == "Z") { return ShapeType::Z; } // Could not find a matching shape_, return NONE. return ShapeType::NONE; } void SetLocation(int x, int y) { x_ = x; y_ = y; SetBlockLocations(); } const vector<Cell*> GetBlocks() const { return blocks_; } pair<int, int> Location() const { return make_pair(x_, y_); } ShapeType type() const { return type_; } bool IsValid() const { for (const Cell* cell : blocks_) { if (cell == nullptr) { return false; } const Cell& c = *cell; if (field_.HasCollision(c)) { return false; } } return true; } // ACTIONS (no checks for errors are performed in the actions!) /** * Rotates the shape counter-clockwise */ void TurnLeft() { // cout << "Turning left" << endl; // cout << AsString() << endl; vector<vector<Cell>> temp = TransposeShape(); for (size_t x = 0; x < size_; ++x) { for (size_t y = 0; y < size_; ++y) { shape_[x][y] = temp[size_ - x - 1][y]; } } SetBlockLocations(); RecomputeBlocks(); // cout << AsString() << endl; } /** * Rotates the shape clockwise */ void TurnRight() { vector<vector<Cell>> temp = TransposeShape(); for (size_t x = 0; x < size_; ++x) { for (size_t y = 0; y < size_; ++y) { shape_[x][y] = temp[x][size_ - y - 1]; } } SetBlockLocations(); RecomputeBlocks(); } void OneDown() { y_++; SetBlockLocations(); } void OneRight() { x_++; SetBlockLocations(); } void OneLeft() { x_--; SetBlockLocations(); } size_t size() const { return size_; } const vector<vector<Cell>>& shape() const { return shape_; } bool Equals(const Shape& shape) const { if (shape.type() != type_) { return false; } if (shape.size() != size_) { return false; } if (shape.x() != x_) { return false; } if (shape.y() != y_) { return false; } const vector<vector<Cell>>& layout = shape.shape(); for (size_t x = 0; x < size_; ++x) { for (size_t y = 0; y < size_; ++y) { if (!layout[x][y].Equals(shape_[x][y])) { return false; } } } return true; } string AsString() const { string output = "Shape at (x,y) " + to_string(x_) + "," + to_string(y_) + ":\n"; for (size_t x = 0; x < shape_.size(); ++x) { for (size_t y = 0; y < shape_[x].size(); ++y) { output = output + shape_[x][y].AsString(); } output = output + "\n"; } output = output + "Blocks: "; for (size_t i = 0; i < blocks_.size(); ++i) { output = output + "(" + to_string(blocks_[i]->x()) + "," + to_string(blocks_[i]->y()) + "),"; } return output; } unique_ptr<Shape> Copy() const { // cout << "Copying this shape: " << endl << AsString() << endl; unique_ptr<Shape> copy(new Shape(type_, field_, x_, y_)); // We need to set the shape here manually because the shape could be // rotated. copy->size_ = size_; copy->shape_ = vector<vector<Cell>>(shape_.size(), vector<Cell>(shape_[0].size(), Cell())); for (size_t x = 0; x < shape_.size(); ++x) { for (size_t y = 0; y < shape_[x].size(); ++y) { copy->shape_[x][y].set_state(shape_[x][y].state()); copy->shape_[x][y].SetLocation(shape_[x][y].x(), shape_[x][y].y()); } } // Copy over the block references. copy->blocks_.clear(); for (size_t i = 0; i < blocks_.size(); ++i) { size_t xFound, yFound; for (size_t x = 0; x < shape_.size(); ++x) { for (size_t y = 0; y < shape_[x].size(); ++y) { // cout << (*blocks_.at(i)).AsString() << shape_[x][y].AsString() << // endl; if ((*blocks_.at(i)).Equals(shape_[x][y])) { xFound = x; yFound = y; // cout << "Found break" << endl; break; } } } copy->blocks_.push_back(&copy->shape_[xFound][yFound]); } // cout << "Copied to this shape: " << endl << copy->AsString() << endl; return copy; } private: /** * Used for rotations */ vector<vector<Cell>> TransposeShape() { vector<vector<Cell>> temp(size_, vector<Cell>()); for (size_t x = 0; x < size_; ++x) { for (size_t y = 0; y < size_; ++y) { temp[x].push_back( Cell(shape_[y][x].x(), shape_[y][x].y(), shape_[y][x].state())); } } return temp; } /** * Uses the shape's current orientation and position to * set the actual location of the block-type cells on the field */ void SetBlockLocations() { for (size_t x = 0; x < size_; ++x) { for (size_t y = 0; y < size_; ++y) { if (shape_[x][y].IsShape()) { shape_[x][y].SetLocation(x_ + x, y_ + y); } } } } /** * Reconstructs the block array after it got broken by a rotation. */ void RecomputeBlocks() { int counter = 0; for (size_t x = 0; x < size_; ++x) { for (size_t y = 0; y < size_; ++y) { if (shape_[x][y].IsShape()) { blocks_[counter] = &shape_[x][y]; counter++; } } } } /** * Set shape_ in square box. * Creates new Cells that can be checked against the actual * playing field. * */ void SetShape() { blocks_ = vector<Cell*>(); switch (type_) { case ShapeType::I: size_ = 4; InitializeShape(); blocks_.push_back(&shape_[1][0]); blocks_.push_back(&shape_[1][1]); blocks_.push_back(&shape_[1][2]); blocks_.push_back(&shape_[1][3]); break; case ShapeType::J: size_ = 3; InitializeShape(); blocks_.push_back(&shape_[0][0]); blocks_.push_back(&shape_[1][0]); blocks_.push_back(&shape_[1][1]); blocks_.push_back(&shape_[1][2]); break; case ShapeType::L: size_ = 3; InitializeShape(); blocks_.push_back(&shape_[0][2]); blocks_.push_back(&shape_[1][0]); blocks_.push_back(&shape_[1][1]); blocks_.push_back(&shape_[1][2]); break; case ShapeType::O: size_ = 2; InitializeShape(); blocks_.push_back(&shape_[0][0]); blocks_.push_back(&shape_[0][1]); blocks_.push_back(&shape_[1][0]); blocks_.push_back(&shape_[1][1]); break; case ShapeType::S: size_ = 3; InitializeShape(); blocks_.push_back(&shape_[0][1]); blocks_.push_back(&shape_[0][2]); blocks_.push_back(&shape_[1][0]); blocks_.push_back(&shape_[1][1]); break; case ShapeType::T: size_ = 3; InitializeShape(); blocks_.push_back(&shape_[0][1]); blocks_.push_back(&shape_[1][0]); blocks_.push_back(&shape_[1][1]); blocks_.push_back(&shape_[1][2]); break; case ShapeType::Z: size_ = 3; InitializeShape(); blocks_.push_back(&shape_[0][0]); blocks_.push_back(&shape_[0][1]); blocks_.push_back(&shape_[1][1]); blocks_.push_back(&shape_[1][2]); break; default: size_ = 0; InitializeShape(); } // set type to SHAPE for (size_t i = 0; i < blocks_.size(); ++i) { blocks_[i]->set_state(Cell::CellState::SHAPE); } } /** * Creates the matrix for the shape_ * @return */ void InitializeShape() { shape_ = vector<vector<Cell>>(size_, vector<Cell>(size_, Cell())); } ShapeType type_; vector<vector<Cell>> shape_; vector<Cell*> blocks_; size_t size_; int x_; int y_; const Field& field_; }; #endif // __SHAPE_H
[ "callumlenton@outlook.com" ]
callumlenton@outlook.com
dcc2268569586fe5834f6675a7f3190bf0e1957d
672e2076ea4e3570712989d534ab66afef0a5707
/implementations/Direct3D12/texture.hpp
56f611eece4ea78f8ec894694ee8e46dea70a34a
[ "MIT" ]
permissive
RebeccaMorganKSE/abstract-gpu
a72a8dcea58b8d9d17717b75ea0d8714fe2369e8
29c47639f0462216e82da0dfef9bec45835e69fe
refs/heads/master
2020-07-05T10:48:44.922148
2019-08-07T12:22:07
2019-08-07T12:22:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,657
hpp
#ifndef AGPU_D3D12_TEXTURE_HPP #define AGPU_D3D12_TEXTURE_HPP #include "device.hpp" struct _agpu_texture : public Object<_agpu_texture> { public: _agpu_texture(); void lostReferences(); static agpu_texture* create(agpu_device* device, agpu_texture_description* description); static agpu_texture* createFromResource(agpu_device* device, agpu_texture_description* description, const ComPtr<ID3D12Resource> &resource); agpu_pointer mapLevel(agpu_int level, agpu_int arrayIndex, agpu_mapping_access flags); agpu_error unmapLevel(); agpu_error readTextureData(agpu_int level, agpu_int arrayIndex, agpu_int pitch, agpu_int slicePitch, agpu_pointer data); agpu_error uploadTextureData(agpu_int level, agpu_int arrayIndex, agpu_int pitch, agpu_int slicePitch, agpu_pointer data); agpu_error discardUploadBuffer(); agpu_error discardReadbackBuffer(); agpu_error getFullViewDescription(agpu_texture_view_description *description); public: UINT subresourceIndexFor(agpu_uint level, agpu_uint arrayIndex); bool isArray(); agpu_device* device; agpu_texture_description description; D3D12_RESOURCE_DESC resourceDescription; D3D12_RESOURCE_DESC transferResourceDescription; UINT transferBufferNumRows; UINT64 transferBufferPitch; ComPtr<ID3D12Resource> gpuResource; ComPtr<ID3D12Resource> uploadResource; ComPtr<ID3D12Resource> readbackResource; private: std::mutex mapMutex; agpu_uint mapCount; agpu_int mappedLevel; agpu_uint mappedArrayIndex; agpu_pointer mappedPointer; agpu_mapping_access mappingFlags; }; #endif //AGPU_D3D12_TEXTURE_HPP
[ "roniesalg@gmail.com" ]
roniesalg@gmail.com
c267977884e048171f3785051c9b17b565a2abf3
0cf94ba93e29f574a08f1c9b0d9dbf98e5984c6e
/Module/Flow/Origin_LoaderY_Flow.cpp
e4b6b3411071461a32bc8beba04185363fb802ae
[]
no_license
jtendless/G8H_VisionAgent
aa1c41bcdb0e9f54471ef5f7cfa5b5720d2f32f2
07a613533cadf0741cfaa31b65f41c441e1267cc
refs/heads/main
2023-08-21T14:03:50.921147
2021-09-24T00:42:35
2021-09-24T00:42:35
409,556,921
0
1
null
2023-07-21T07:59:10
2021-09-23T11:05:39
C++
UTF-8
C++
false
false
5,171
cpp
#include "stdafx.h" #include "Origin_LoaderY_Flow.h" #include "Vision/Devs.h" #include "VisionAgentDlg.h" #include "Data/ManualData.h" COrigin_LoaderY_Flow::COrigin_LoaderY_Flow() { } COrigin_LoaderY_Flow::~COrigin_LoaderY_Flow() { } BOOL COrigin_LoaderY_Flow::InitProcess() { m_StateComplete = NULL; m_FlowFinish = TRUE; m_bTerminate = FALSE; m_bFlowDone = TRUE; //SetProcessLog(Process_Msg); //SetAlarmLog(LogMsg_Alarm); hHandle = CreateEvent(NULL, TRUE, FALSE, NULL); SetHandle(hHandle); pThread = AfxBeginThread(ThreadFunction, this); return TRUE; } BOOL COrigin_LoaderY_Flow::EndProcess() { m_FlowFinish = FALSE; SetStep(_eORIGIN_LOADER_Y_FLOW_IDLE, _T("_eORIGIN_LOADER_Y_FLOW_IDLE")); do { Sleep(10); } while (IsTerminate() == 0); if (hHandle != NULL) { CloseHandle(hHandle); } return TRUE; } BOOL COrigin_LoaderY_Flow::Start() { eRemoteAxis = REMOTE_AXIS_AJIN_LOADER_YL; m_bStopBit = FALSE; m_bFlowDone = FALSE; SharedInfo::bMachineStopFlag = FALSE; SetStep(_eORIGIN_LOADER_Y_FLOW_START, _T("_eORIGIN_LOADER_Y_FLOW_START")); return TRUE; } BOOL COrigin_LoaderY_Flow::Stop() { m_bStopBit = TRUE; SetStop(); //!! return TRUE; } UINT COrigin_LoaderY_Flow::ThreadFunction(LPVOID lpParam) { COrigin_LoaderY_Flow* pFlow = NULL; pFlow = (COrigin_LoaderY_Flow*)lpParam; pFlow->ThreadFunctionEntry(); pFlow->SetTerminate(TRUE); return 0; } VOID COrigin_LoaderY_Flow::ThreadFunctionEntry(VOID) { DWORD dwResult = 0; double dStrt_Time = GetTickCount(); double dEnd_Time = GetTickCount(); double dWait_Time = GetTickCount(); int nWork_Mask_Mode = -1; int nWork_Mask_Index = -1; BOOL bComplete_Step = FALSE; CVisionAgentDlg *pMain = (CVisionAgentDlg*)AfxGetMainWnd(); CString Str = _T(""); while (m_FlowFinish) { WaitForSingleObject(hHandle, INFINITE); ResetEvent(hHandle); if (SharedInfo::bMachineStopFlag == TRUE)// && m_bStopBit == FALSE) { m_bStopBit = TRUE; SetCurrentStep(_eORIGIN_LOADER_Y_FLOW_IDLE); //KJT 20210318 continue; //!! } switch (GetCurrentTotalStep()) { case _eORIGIN_LOADER_Y_FLOW_IDLE: { break; } case _eORIGIN_LOADER_Y_FLOW_START: SetStep(_eORIGIN_LOADER_Y_FLOW_INTERLOCK_CHECK, _T("_eORIGIN_LOADER_Y_FLOW_INTERLOCK_CHECK")); break; case _eORIGIN_LOADER_Y_FLOW_INTERLOCK_CHECK: if (FlowInterlock() == FALSE) { m_bFlowDone = TRUE; SetStep(_eORIGIN_LOADER_Y_FLOW_IDLE, _T("_eORIGIN_LOADER_Y_FLOW_IDLE")); } else { SetStep(_eORIGIN_LOADER_Y_FLOW_HOME_START, _T("_eORIGIN_LOADER_Y_FLOW_HOME_START")); } break; case _eORIGIN_LOADER_Y_FLOW_HOME_START: Devs::MotionIf.AxisHomeStart(eRemoteAxis); Sleep(3000); //!! SetStep(_eORIGIN_LOADER_Y_FLOW_HOME_COMP_CHECK, _T("_eORIGIN_LOADER_Y_FLOW_HOME_COMP_CHECK")); SetTimeOut(TIME_OUT_MOTION); break; case _eORIGIN_LOADER_Y_FLOW_HOME_COMP_CHECK: if (SharedInfo::AxisInMotionStatus[eRemoteAxis] == FALSE && SharedInfo::AxisHomeStatus[eRemoteAxis]) { SetStep(_eORIGIN_LOADER_Y_FLOW_WAIT_POS, _T("_eORIGIN_LOADER_Y_FLOW_WAIT_POS")); } else if (IsTimeOut()) { SharedInfo::SetAlarm(_T("_eORIGIN_LOADER_Y_FLOW_HOME_COMP_CHECK : Time Out !!!"), eORIGIN_LOADER_Y_FLOW + 0); SetStep(_eORIGIN_LOADER_Y_FLOW_ERROR, _T("_eORIGIN_LOADER_Y_FLOW_ERROR")); } else { SetCheckStep(_eORIGIN_LOADER_Y_FLOW_HOME_COMP_CHECK, _T("_eORIGIN_LOADER_Y_FLOW_HOME_COMP_CHECK")); } break; case _eORIGIN_LOADER_Y_FLOW_WAIT_POS: Devs::m_LoaderMotion.LoaderY_WaitPos(); SetStep(_eORIGIN_LOADER_Y_FLOW_WAIT_POS_CHECK, _T("_eORIGIN_LOADER_Y_FLOW_WAIT_POS_CHECK")); SetTimeOut(TIME_OUT_MOTION); break; case _eORIGIN_LOADER_Y_FLOW_WAIT_POS_CHECK: if (Devs::m_LoaderMotion.Is_LoaderY_WaitPos()) { SetStep(_eORIGIN_LOADER_Y_FLOW_DONE, _T("_eORIGIN_LOADER_Y_FLOW_DONE")); } else if (IsTimeOut()) { SharedInfo::SetAlarm(_T("_eORIGIN_LOADER_Y_FLOW_WAIT_POS_CHECK : Time Out !!!"), eORIGIN_LOADER_Y_FLOW + 1); SetStep(_eORIGIN_LOADER_Y_FLOW_ERROR, _T("_eORIGIN_LOADER_Y_FLOW_ERROR")); } else { SetCheckStep(_eORIGIN_LOADER_Y_FLOW_WAIT_POS_CHECK, _T("_eORIGIN_LOADER_Y_FLOW_WAIT_POS_CHECK")); } break; case _eORIGIN_LOADER_Y_FLOW_DONE: { m_bFlowDone = TRUE; SetStep(_eORIGIN_LOADER_Y_FLOW_IDLE, _T("(_eORIGIN_LOADER_Y_FLOW_IDLE")); break; } default: { break; } } Sleep(100); //!! } } BOOL COrigin_LoaderY_Flow::FlowInterlock() { CString Str = _T(""); double dPos = 0.0; if (SharedInfo::GetServoOnStatus(AXIS_LOADER_YL) != TRUE) { Total_Msg(_T("Loader YL Servo On Check !!!")); SharedInfo::SetAlarm(_T("Origin_LoaderY_Flow : Loader YL Servo On Check !!!"), eORIGIN_LOADER_Y_FLOW + 20); return FALSE; } //dPos = SharedInfo::GetActPos(AXIS_VIRTUAL_GANTRY_Y); ////if (dPos < CManualData::m_ManualDataGantry.Info.m_dGantry_Y_Paper_Unload_Pos) //if (dPos < CManualData::m_ManualDataGantry.Info.m_dGantry_Y_Wait_Pos) //{ // Total_Msg(_T("Gantry Y Paper Unload Pos Check !!!")); // SharedInfo::SetAlarm(_T("Origin_LoaderY_Flow : Gantry Y Paper Unload Pos Check !!!"), eORIGIN_LOADER_Y_FLOW + 22); // return FALSE; //} return TRUE; }
[ "jt-endless@daum.net" ]
jt-endless@daum.net
85c97f71931e531c96c2e270a139bf9663b7a94d
8017d1dd2f8ab8aba69651ab4ceee0381d708ff6
/microcode_sliding_window/mvm/mvm_aarch64.cpp
e75482d9ff1b97f780e5a17dfc842d1a785588b2
[]
no_license
ElvisBlue/Hexext
7f2d9d4e87686b418f600358fbed4ac70c7003cd
718698ffa55643faeaf80c190121afd3c11f6a0b
refs/heads/master
2022-02-19T16:53:46.655056
2019-08-04T19:03:32
2019-08-04T19:03:32
441,787,878
1
0
null
2021-12-26T01:27:21
2021-12-26T01:27:20
null
UTF-8
C++
false
false
1,121
cpp
#include "mvm_defs_internal.hpp" #ifdef __EA64__ #include "mvm_aarch64.hpp" #include "../mixins/set_codegen_small.mix" /* it looks like there are FOUR DIFFERENT FUCKING POSSIBLE REGISTER FILE LAYOUTS FOR AARCH64 in every layout the tempregs have different predecessors in the file but off, the last tempreg, always comes before q0 */ void mvm_aarch64_init() { using namespace _mvm_internal; auto q0 = find_mreg_by_name("q0"); /* t0,t1,t2,off */ /* in two cases, cs comes after q31 */ if (find_mreg_by_name("q31")->m_micro_reg == 832) { insert_abs_mreg("cs", 848, 2); mr_code_seg = 848; mr_data_seg = 848; } else { warning("We don't know the offset of CS in the mreg register file!"); cs_assert(false); } unsigned base = q0->m_micro_reg - (16 * 4); insert_abs_mreg("t0", base, 16); insert_abs_mreg("t1", base + 16, 16); insert_abs_mreg("t2", base + 32, 16); insert_abs_mreg("off", base + 48, 16); add_tempregs_to_list("t0", "t1", "t2", "off"); //insert_abs_mreg("cs", find_mreg_by_name("pc")->m_micro_reg + sizeof(ea_t), 2); } #include "../mixins/revert_codegen.mix" #endif
[ "chss95cs@gmail.com" ]
chss95cs@gmail.com
8861a1ff39596e4937143ef07ea0fbae9fc2c9d0
ca6c13ac1ccb738652261b93ec27db63f981291b
/psLab/fluxus/public/FluxFunction.h
c0dda889751dfb495fa6dd948556565a0c085e87
[]
no_license
stephanie-bron/monthly_tdep_analysis
9f9f0e3d05ffb03a3beeec546964717450be0b42
7c32f7278ab10e63688b74a5e1e6fcbed041b722
refs/heads/master
2020-12-02T23:55:06.628342
2017-07-01T15:17:14
2017-07-01T15:17:14
95,959,702
0
0
null
null
null
null
UTF-8
C++
false
false
2,079
h
#ifndef FLUXUS_FLUXFUNCTION_H_ #define FLUXUS_FLUXFUNCTION_H_ #include "TF1.h" // For now, units are: // * energy will be GeV // * flux will be GeV^-1 cm^-2 s^-1 // * spectralIndex must include sign, i.e. E^gamma, where gamma = -2 class FluxBase { public: virtual ~FluxBase() { } virtual double GetFlux(double energy) const = 0; }; // THE WRAPPER FN (makes class accessible with a simple fn call) /* EXAMPLE: PowerLawFlux pf(1e-8, -2); // flux constant and spectral index FluxFunction(0, &pf); FluxFunction(1e3); // get flux calculated at 1 TeV */ double FluxFunction(double energy, const FluxBase *myFluxPtr = NULL); // POWER LAW FLUX class PowerLawFlux : public FluxBase { public: PowerLawFlux(); PowerLawFlux(double fluxConstant, double spectralIndex); ~PowerLawFlux() { } double GetFluxConstant() const; double GetSpectralIndex() const; double GetFlux(double energy) const; private: double fluxConstant_; double spectralIndex_; }; //TRUNCATED POWER LAW FLUX (power law only between eMin eMax) class TruncatedPowerLawFlux : public FluxBase { public: TruncatedPowerLawFlux(); TruncatedPowerLawFlux(double fluxConstant, double spectralIndex, double eMin, double eMax); ~TruncatedPowerLawFlux() { } double GetFluxConstant() const; double GetSpectralIndex() const; double GetEnergyMin() const; double GetEnergyMax() const; double GetFlux(double energy) const; private: double fluxConstant_; double spectralIndex_; double eMin_; double eMax_; }; // FORMULA FLUX class FormulaFlux : public FluxBase { public: FormulaFlux(); FormulaFlux(const char* formula); FormulaFlux(const TF1& f); // copy constructor (default doesn't work with TF1 data member in class!!!) FormulaFlux(const FormulaFlux& rhs); // assignment operator FormulaFlux& operator=(const FormulaFlux& rhs); // destructor ~FormulaFlux() { } const char* GetFormula() const; TF1 GetTF1() const; double GetFlux(double energy) const; private: TF1 f_; }; #endif // FLUXUS_FLUXFUNCTION_H_
[ "stephaniecl.bron@gmail.com" ]
stephaniecl.bron@gmail.com
8da296b6f712ecc6a1f3f6da48d15b400096dd04
480f507747e64e15cac968d1b86364757ea05271
/DirectXTK/Src/WICTextureLoader.cpp
d5fc622b5bd567965a14b490dd9c45f984b29fcb
[ "MIT" ]
permissive
aklemets/directx-sdk-samples
8749091c87174596028cf5dc5aef6afdddc3e5d0
3879e6a8a4d10ad27bb4c56f8e37f0ef1458e027
refs/heads/master
2020-12-20T15:18:14.469158
2020-01-30T01:55:05
2020-01-30T01:55:05
236,120,994
0
0
MIT
2020-01-25T03:31:13
2020-01-25T03:31:12
null
UTF-8
C++
false
false
40,293
cpp
//-------------------------------------------------------------------------------------- // File: WICTextureLoader.cpp // // Function for loading a WIC image and creating a Direct3D runtime texture for it // (auto-generating mipmaps if possible) // // Note: Assumes application has already called CoInitializeEx // // Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for // auto-gen mipmap support. // // Note these functions are useful for images created as simple 2D textures. For // more complex resources, DDSTextureLoader is an excellent light-weight runtime loader. // For a full-featured DDS file reader, writer, and texture processing pipeline see // the 'Texconv' sample and the 'DirectXTex' library. // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 // http://go.microsoft.com/fwlink/?LinkId=248929 //-------------------------------------------------------------------------------------- // We could load multi-frame images (TIFF/GIF) into a texture array. // For now, we just load the first frame (note: DirectXTex supports multi-frame images) #include "pch.h" #include "WICTextureLoader.h" #include "DirectXHelpers.h" #include "PlatformHelpers.h" #include "LoaderHelpers.h" using namespace DirectX; using Microsoft::WRL::ComPtr; namespace { //------------------------------------------------------------------------------------- // WIC Pixel Format Translation Data //------------------------------------------------------------------------------------- struct WICTranslate { GUID wic; DXGI_FORMAT format; }; const WICTranslate g_WICFormats[] = { { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, { GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM }, { GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM }, { GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1 { GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1 { GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1 { GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM }, { GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM }, { GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM }, { GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT }, { GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT }, { GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM }, { GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM }, { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, }; //------------------------------------------------------------------------------------- // WIC Pixel Format nearest conversion table //------------------------------------------------------------------------------------- struct WICConvert { GUID source; GUID target; }; const WICConvert g_WICConvert [] = { // Note target GUID in this conversion table must be one of those directly supported formats (above). { GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM { GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM { GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM { GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM { GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM { GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM { GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM { GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM { GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM { GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM { GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT { GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT { GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT { GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT { GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT { GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT { GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT { GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT { GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT { GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT { GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT { GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT { GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM { GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT #endif // We don't support n-channel formats }; bool g_WIC2 = false; BOOL WINAPI InitializeWICFactory(PINIT_ONCE, PVOID, PVOID *ifactory) noexcept { #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) HRESULT hr = CoCreateInstance( CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory2), ifactory ); if (SUCCEEDED(hr)) { // WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed g_WIC2 = true; return TRUE; } else { hr = CoCreateInstance( CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), ifactory ); return SUCCEEDED(hr) ? TRUE : FALSE; } #else return SUCCEEDED(CoCreateInstance( CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), ifactory)) ? TRUE : FALSE; #endif } } //-------------------------------------------------------------------------------------- namespace DirectX { bool _IsWIC2(); IWICImagingFactory* _GetWIC(); // Also used by ScreenGrab bool _IsWIC2() { return g_WIC2; } IWICImagingFactory* _GetWIC() { static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; IWICImagingFactory* factory = nullptr; (void)InitOnceExecuteOnce( &s_initOnce, InitializeWICFactory, nullptr, reinterpret_cast<LPVOID*>(&factory)); return factory; } } // namespace DirectX namespace { //--------------------------------------------------------------------------------- DXGI_FORMAT _WICToDXGI(const GUID& guid) { for (size_t i = 0; i < _countof(g_WICFormats); ++i) { if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0) return g_WICFormats[i].format; } #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) if (g_WIC2) { if (memcmp(&GUID_WICPixelFormat96bppRGBFloat, &guid, sizeof(GUID)) == 0) return DXGI_FORMAT_R32G32B32_FLOAT; } #endif return DXGI_FORMAT_UNKNOWN; } //--------------------------------------------------------------------------------- size_t _WICBitsPerPixel(REFGUID targetGuid) { auto pWIC = _GetWIC(); if (!pWIC) return 0; ComPtr<IWICComponentInfo> cinfo; if (FAILED(pWIC->CreateComponentInfo(targetGuid, cinfo.GetAddressOf()))) return 0; WICComponentType type; if (FAILED(cinfo->GetComponentType(&type))) return 0; if (type != WICPixelFormat) return 0; ComPtr<IWICPixelFormatInfo> pfinfo; if (FAILED(cinfo.As(&pfinfo))) return 0; UINT bpp; if (FAILED(pfinfo->GetBitsPerPixel(&bpp))) return 0; return bpp; } //--------------------------------------------------------------------------------- HRESULT CreateTextureFromWIC( _In_ ID3D11Device* d3dDevice, _In_opt_ ID3D11DeviceContext* d3dContext, #if defined(_XBOX_ONE) && defined(_TITLE) _In_opt_ ID3D11DeviceX* d3dDeviceX, _In_opt_ ID3D11DeviceContextX* d3dContextX, #endif _In_ IWICBitmapFrameDecode *frame, _In_ size_t maxsize, _In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ unsigned int loadFlags, _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView) { UINT width, height; HRESULT hr = frame->GetSize(&width, &height); if (FAILED(hr)) return hr; if (maxsize > UINT32_MAX) return E_INVALIDARG; assert(width > 0 && height > 0); if (!maxsize) { // This is a bit conservative because the hardware could support larger textures than // the Feature Level defined minimums, but doing it this way is much easier and more // performant for WIC than the 'fail and retry' model used by DDSTextureLoader switch (d3dDevice->GetFeatureLevel()) { case D3D_FEATURE_LEVEL_9_1: case D3D_FEATURE_LEVEL_9_2: maxsize = 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; break; case D3D_FEATURE_LEVEL_9_3: maxsize = 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; break; case D3D_FEATURE_LEVEL_10_0: case D3D_FEATURE_LEVEL_10_1: maxsize = 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; break; default: maxsize = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; break; } } assert(maxsize > 0); UINT twidth, theight; if (width > maxsize || height > maxsize) { float ar = static_cast<float>(height) / static_cast<float>(width); if (width > height) { twidth = static_cast<UINT>(maxsize); theight = std::max<UINT>(1, static_cast<UINT>(static_cast<float>(maxsize) * ar)); } else { theight = static_cast<UINT>(maxsize); twidth = std::max<UINT>(1, static_cast<UINT>(static_cast<float>(maxsize) / ar)); } assert(twidth <= maxsize && theight <= maxsize); } else { twidth = width; theight = height; } // Determine format WICPixelFormatGUID pixelFormat; hr = frame->GetPixelFormat(&pixelFormat); if (FAILED(hr)) return hr; WICPixelFormatGUID convertGUID; memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &pixelFormat, sizeof(GUID)); size_t bpp = 0; DXGI_FORMAT format = _WICToDXGI(pixelFormat); if (format == DXGI_FORMAT_UNKNOWN) { if (memcmp(&GUID_WICPixelFormat96bppRGBFixedPoint, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) { #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) if (g_WIC2) { memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat96bppRGBFloat, sizeof(GUID)); format = DXGI_FORMAT_R32G32B32_FLOAT; bpp = 96; } else #endif { memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat128bppRGBAFloat, sizeof(GUID)); format = DXGI_FORMAT_R32G32B32A32_FLOAT; bpp = 128; } } else { for (size_t i = 0; i < _countof(g_WICConvert); ++i) { if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) { memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &g_WICConvert[i].target, sizeof(GUID)); format = _WICToDXGI(g_WICConvert[i].target); assert(format != DXGI_FORMAT_UNKNOWN); bpp = _WICBitsPerPixel(convertGUID); break; } } } if (format == DXGI_FORMAT_UNKNOWN) { DebugTrace("ERROR: WICTextureLoader does not support all DXGI formats (WIC GUID {%8.8lX-%4.4X-%4.4X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X}). Consider using DirectXTex.\n", pixelFormat.Data1, pixelFormat.Data2, pixelFormat.Data3, pixelFormat.Data4[0], pixelFormat.Data4[1], pixelFormat.Data4[2], pixelFormat.Data4[3], pixelFormat.Data4[4], pixelFormat.Data4[5], pixelFormat.Data4[6], pixelFormat.Data4[7]); return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } else { bpp = _WICBitsPerPixel(pixelFormat); } #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) if ((format == DXGI_FORMAT_R32G32B32_FLOAT) && d3dContext && textureView) { // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT UINT fmtSupport = 0; hr = d3dDevice->CheckFormatSupport(DXGI_FORMAT_R32G32B32_FLOAT, &fmtSupport); if (FAILED(hr) || !(fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) { // Use R32G32B32A32_FLOAT instead which is required for Feature Level 10.0 and up memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat128bppRGBAFloat, sizeof(GUID)); format = DXGI_FORMAT_R32G32B32A32_FLOAT; bpp = 128; } } #endif if (!bpp) return E_FAIL; // Handle sRGB formats if (loadFlags & WIC_LOADER_FORCE_SRGB) { format = LoaderHelpers::MakeSRGB(format); } else if (!(loadFlags & WIC_LOADER_IGNORE_SRGB)) { ComPtr<IWICMetadataQueryReader> metareader; if (SUCCEEDED(frame->GetMetadataQueryReader(metareader.GetAddressOf()))) { GUID containerFormat; if (SUCCEEDED(metareader->GetContainerFormat(&containerFormat))) { // Check for sRGB colorspace metadata bool sRGB = false; PROPVARIANT value; PropVariantInit(&value); if (memcmp(&containerFormat, &GUID_ContainerFormatPng, sizeof(GUID)) == 0) { // Check for sRGB chunk if (SUCCEEDED(metareader->GetMetadataByName(L"/sRGB/RenderingIntent", &value)) && value.vt == VT_UI1) { sRGB = true; } } #if defined(_XBOX_ONE) && defined(_TITLE) else if (memcmp(&containerFormat, &GUID_ContainerFormatJpeg, sizeof(GUID)) == 0) { if (SUCCEEDED(metareader->GetMetadataByName(L"/app1/ifd/exif/{ushort=40961}", &value)) && value.vt == VT_UI2 && value.uiVal == 1) { sRGB = true; } } else if (memcmp(&containerFormat, &GUID_ContainerFormatTiff, sizeof(GUID)) == 0) { if (SUCCEEDED(metareader->GetMetadataByName(L"/ifd/exif/{ushort=40961}", &value)) && value.vt == VT_UI2 && value.uiVal == 1) { sRGB = true; } } #else else if (SUCCEEDED(metareader->GetMetadataByName(L"System.Image.ColorSpace", &value)) && value.vt == VT_UI2 && value.uiVal == 1) { sRGB = true; } #endif (void)PropVariantClear(&value); if (sRGB) format = LoaderHelpers::MakeSRGB(format); } } } // Verify our target format is supported by the current device // (handles WDDM 1.0 or WDDM 1.1 device driver cases as well as DirectX 11.0 Runtime without 16bpp format support) UINT support = 0; hr = d3dDevice->CheckFormatSupport(format, &support); if (FAILED(hr) || !(support & D3D11_FORMAT_SUPPORT_TEXTURE2D)) { // Fallback to RGBA 32-bit format which is supported by all devices memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat32bppRGBA, sizeof(GUID)); format = DXGI_FORMAT_R8G8B8A8_UNORM; bpp = 32; } // Allocate temporary memory for image uint64_t rowBytes = (uint64_t(twidth) * uint64_t(bpp) + 7u) / 8u; uint64_t numBytes = rowBytes * uint64_t(height); if (rowBytes > UINT32_MAX || numBytes > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); auto rowPitch = static_cast<size_t>(rowBytes); auto imageSize = static_cast<size_t>(numBytes); std::unique_ptr<uint8_t[]> temp(new (std::nothrow) uint8_t[imageSize]); if (!temp) return E_OUTOFMEMORY; // Load image data if (memcmp(&convertGUID, &pixelFormat, sizeof(GUID)) == 0 && twidth == width && theight == height) { // No format conversion or resize needed hr = frame->CopyPixels(nullptr, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get()); if (FAILED(hr)) return hr; } else if (twidth != width || theight != height) { // Resize auto pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; ComPtr<IWICBitmapScaler> scaler; hr = pWIC->CreateBitmapScaler(scaler.GetAddressOf()); if (FAILED(hr)) return hr; hr = scaler->Initialize(frame, twidth, theight, WICBitmapInterpolationModeFant); if (FAILED(hr)) return hr; WICPixelFormatGUID pfScaler; hr = scaler->GetPixelFormat(&pfScaler); if (FAILED(hr)) return hr; if (memcmp(&convertGUID, &pfScaler, sizeof(GUID)) == 0) { // No format conversion needed hr = scaler->CopyPixels(nullptr, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get()); if (FAILED(hr)) return hr; } else { ComPtr<IWICFormatConverter> FC; hr = pWIC->CreateFormatConverter(FC.GetAddressOf()); if (FAILED(hr)) return hr; BOOL canConvert = FALSE; hr = FC->CanConvert(pfScaler, convertGUID, &canConvert); if (FAILED(hr) || !canConvert) { return E_UNEXPECTED; } hr = FC->Initialize(scaler.Get(), convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); if (FAILED(hr)) return hr; hr = FC->CopyPixels(nullptr, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get()); if (FAILED(hr)) return hr; } } else { // Format conversion but no resize auto pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; ComPtr<IWICFormatConverter> FC; hr = pWIC->CreateFormatConverter(FC.GetAddressOf()); if (FAILED(hr)) return hr; BOOL canConvert = FALSE; hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert); if (FAILED(hr) || !canConvert) { return E_UNEXPECTED; } hr = FC->Initialize(frame, convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); if (FAILED(hr)) return hr; hr = FC->CopyPixels(nullptr, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get()); if (FAILED(hr)) return hr; } // See if format is supported for auto-gen mipmaps (varies by feature level) bool autogen = false; if (d3dContext && textureView) // Must have context and shader-view to auto generate mipmaps { UINT fmtSupport = 0; hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) { autogen = true; #if defined(_XBOX_ONE) && defined(_TITLE) if (!d3dDeviceX || !d3dContextX) return E_INVALIDARG; #endif } } // Create texture D3D11_TEXTURE2D_DESC desc; desc.Width = twidth; desc.Height = theight; desc.MipLevels = (autogen) ? 0u : 1u; desc.ArraySize = 1; desc.Format = format; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Usage = usage; desc.CPUAccessFlags = cpuAccessFlags; if (autogen) { desc.BindFlags = bindFlags | D3D11_BIND_RENDER_TARGET; desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS; } else { desc.BindFlags = bindFlags; desc.MiscFlags = miscFlags; } D3D11_SUBRESOURCE_DATA initData; initData.pSysMem = temp.get(); initData.SysMemPitch = static_cast<UINT>(rowPitch); initData.SysMemSlicePitch = static_cast<UINT>(imageSize); ID3D11Texture2D* tex = nullptr; hr = d3dDevice->CreateTexture2D(&desc, (autogen) ? nullptr : &initData, &tex); if (SUCCEEDED(hr) && tex) { if (textureView) { D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; SRVDesc.Format = desc.Format; SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MipLevels = (autogen) ? unsigned(-1) : 1u; hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); if (FAILED(hr)) { tex->Release(); return hr; } if (autogen) { assert(d3dContext != nullptr); #if defined(_XBOX_ONE) && defined(_TITLE) ID3D11Texture2D *pStaging = nullptr; CD3D11_TEXTURE2D_DESC stagingDesc(format, twidth, theight, 1, 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ, 1, 0, 0); initData.pSysMem = temp.get(); initData.SysMemPitch = static_cast<UINT>(rowPitch); initData.SysMemSlicePitch = static_cast<UINT>(imageSize); hr = d3dDevice->CreateTexture2D(&stagingDesc, &initData, &pStaging); if (SUCCEEDED(hr)) { d3dContext->CopySubresourceRegion(tex, 0, 0, 0, 0, pStaging, 0, nullptr); UINT64 copyFence = d3dContextX->InsertFence(0); while (d3dDeviceX->IsFencePending(copyFence)) { SwitchToThread(); } pStaging->Release(); } #else d3dContext->UpdateSubresource(tex, 0, nullptr, temp.get(), static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize)); #endif d3dContext->GenerateMips(*textureView); } } if (texture) { *texture = tex; } else { SetDebugObjectName(tex, "WICTextureLoader"); tex->Release(); } } return hr; } //-------------------------------------------------------------------------------------- void SetDebugTextureInfo( _In_z_ const wchar_t* fileName, _In_opt_ ID3D11Resource** texture, _In_opt_ ID3D11ShaderResourceView** textureView) { #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) if (texture || textureView) { #if defined(_XBOX_ONE) && defined(_TITLE) const wchar_t* pstrName = wcsrchr(fileName, '\\'); if (!pstrName) { pstrName = fileName; } else { pstrName++; } if (texture && *texture) { (*texture)->SetName(pstrName); } if (textureView && *textureView) { (*textureView)->SetName(pstrName); } #else CHAR strFileA[MAX_PATH]; int result = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, fileName, -1, strFileA, MAX_PATH, nullptr, nullptr ); if (result > 0) { const char* pstrName = strrchr(strFileA, '\\'); if (!pstrName) { pstrName = strFileA; } else { pstrName++; } if (texture && *texture) { (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strnlen_s(pstrName, MAX_PATH)), pstrName ); } if (textureView && *textureView) { (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strnlen_s(pstrName, MAX_PATH)), pstrName ); } } #endif } #else UNREFERENCED_PARAMETER(fileName); UNREFERENCED_PARAMETER(texture); UNREFERENCED_PARAMETER(textureView); #endif } } // anonymous namespace //-------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemory( ID3D11Device* d3dDevice, const uint8_t* wicData, size_t wicDataSize, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, size_t maxsize) { return CreateWICTextureFromMemoryEx(d3dDevice, wicData, wicDataSize, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, texture, textureView); } _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) HRESULT DirectX::CreateWICTextureFromMemory( ID3D11DeviceX* d3dDevice, ID3D11DeviceContextX* d3dContext, #else HRESULT DirectX::CreateWICTextureFromMemory( ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, #endif const uint8_t* wicData, size_t wicDataSize, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, size_t maxsize) { return CreateWICTextureFromMemoryEx(d3dDevice, d3dContext, wicData, wicDataSize, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, texture, textureView); } _Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemoryEx( ID3D11Device* d3dDevice, const uint8_t* wicData, size_t wicDataSize, size_t maxsize, D3D11_USAGE usage, unsigned int bindFlags, unsigned int cpuAccessFlags, unsigned int miscFlags, unsigned int loadFlags, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView) { if (texture) { *texture = nullptr; } if (textureView) { *textureView = nullptr; } if (!d3dDevice || !wicData || (!texture && !textureView)) return E_INVALIDARG; if (!wicDataSize) return E_FAIL; if (wicDataSize > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); auto pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; // Create input stream for memory ComPtr<IWICStream> stream; HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); if (FAILED(hr)) return hr; hr = stream->InitializeFromMemory(const_cast<uint8_t*>(wicData), static_cast<DWORD>(wicDataSize)); if (FAILED(hr)) return hr; // Initialize WIC ComPtr<IWICBitmapDecoder> decoder; hr = pWIC->CreateDecoderFromStream(stream.Get(), nullptr, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); if (FAILED(hr)) return hr; ComPtr<IWICBitmapFrameDecode> frame; hr = decoder->GetFrame(0, frame.GetAddressOf()); if (FAILED(hr)) return hr; hr = CreateTextureFromWIC(d3dDevice, nullptr, #if defined(_XBOX_ONE) && defined(_TITLE) nullptr, nullptr, #endif frame.Get(), maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView); if (FAILED(hr)) return hr; if (texture && *texture) { SetDebugObjectName(*texture, "WICTextureLoader"); } if (textureView && *textureView) { SetDebugObjectName(*textureView, "WICTextureLoader"); } return hr; } _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) HRESULT DirectX::CreateWICTextureFromMemoryEx( ID3D11DeviceX* d3dDevice, ID3D11DeviceContextX* d3dContext, #else HRESULT DirectX::CreateWICTextureFromMemoryEx( ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, #endif const uint8_t* wicData, size_t wicDataSize, size_t maxsize, D3D11_USAGE usage, unsigned int bindFlags, unsigned int cpuAccessFlags, unsigned int miscFlags, unsigned int loadFlags, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView) { if (texture) { *texture = nullptr; } if (textureView) { *textureView = nullptr; } if (!d3dDevice || !wicData || (!texture && !textureView)) return E_INVALIDARG; if (!wicDataSize) return E_FAIL; if (wicDataSize > UINT32_MAX) return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); auto pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; // Create input stream for memory ComPtr<IWICStream> stream; HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); if (FAILED(hr)) return hr; hr = stream->InitializeFromMemory(const_cast<uint8_t*>(wicData), static_cast<DWORD>(wicDataSize)); if (FAILED(hr)) return hr; // Initialize WIC ComPtr<IWICBitmapDecoder> decoder; hr = pWIC->CreateDecoderFromStream(stream.Get(), nullptr, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); if (FAILED(hr)) return hr; ComPtr<IWICBitmapFrameDecode> frame; hr = decoder->GetFrame(0, frame.GetAddressOf()); if (FAILED(hr)) return hr; hr = CreateTextureFromWIC(d3dDevice, d3dContext, #if defined(_XBOX_ONE) && defined(_TITLE) d3dDevice, d3dContext, #endif frame.Get(), maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView); if (FAILED(hr)) return hr; if (texture && *texture) { SetDebugObjectName(*texture, "WICTextureLoader"); } if (textureView && *textureView) { SetDebugObjectName(*textureView, "WICTextureLoader"); } return hr; } //-------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFile( ID3D11Device* d3dDevice, const wchar_t* fileName, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, size_t maxsize) { return CreateWICTextureFromFileEx(d3dDevice, fileName, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, texture, textureView); } _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) HRESULT DirectX::CreateWICTextureFromFile( ID3D11DeviceX* d3dDevice, ID3D11DeviceContextX* d3dContext, #else HRESULT DirectX::CreateWICTextureFromFile( ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, #endif const wchar_t* fileName, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView, size_t maxsize) { return CreateWICTextureFromFileEx(d3dDevice, d3dContext, fileName, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, texture, textureView); } _Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFileEx( ID3D11Device* d3dDevice, const wchar_t* fileName, size_t maxsize, D3D11_USAGE usage, unsigned int bindFlags, unsigned int cpuAccessFlags, unsigned int miscFlags, unsigned int loadFlags, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView) { if (texture) { *texture = nullptr; } if (textureView) { *textureView = nullptr; } if (!d3dDevice || !fileName || (!texture && !textureView)) return E_INVALIDARG; auto pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; // Initialize WIC ComPtr<IWICBitmapDecoder> decoder; HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); if (FAILED(hr)) return hr; ComPtr<IWICBitmapFrameDecode> frame; hr = decoder->GetFrame(0, frame.GetAddressOf()); if (FAILED(hr)) return hr; hr = CreateTextureFromWIC(d3dDevice, nullptr, #if defined(_XBOX_ONE) && defined(_TITLE) nullptr, nullptr, #endif frame.Get(), maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView); if (SUCCEEDED(hr)) { SetDebugTextureInfo(fileName, texture, textureView); } return hr; } _Use_decl_annotations_ #if defined(_XBOX_ONE) && defined(_TITLE) HRESULT DirectX::CreateWICTextureFromFileEx( ID3D11DeviceX* d3dDevice, ID3D11DeviceContextX* d3dContext, #else HRESULT DirectX::CreateWICTextureFromFileEx( ID3D11Device* d3dDevice, ID3D11DeviceContext* d3dContext, #endif const wchar_t* fileName, size_t maxsize, D3D11_USAGE usage, unsigned int bindFlags, unsigned int cpuAccessFlags, unsigned int miscFlags, unsigned int loadFlags, ID3D11Resource** texture, ID3D11ShaderResourceView** textureView) { if (texture) { *texture = nullptr; } if (textureView) { *textureView = nullptr; } if (!d3dDevice || !fileName || (!texture && !textureView)) return E_INVALIDARG; auto pWIC = _GetWIC(); if (!pWIC) return E_NOINTERFACE; // Initialize WIC ComPtr<IWICBitmapDecoder> decoder; HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); if (FAILED(hr)) return hr; ComPtr<IWICBitmapFrameDecode> frame; hr = decoder->GetFrame(0, frame.GetAddressOf()); if (FAILED(hr)) return hr; hr = CreateTextureFromWIC(d3dDevice, d3dContext, #if defined(_XBOX_ONE) && defined(_TITLE) d3dDevice, d3dContext, #endif frame.Get(), maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, texture, textureView); if (SUCCEEDED(hr)) { SetDebugTextureInfo(fileName, texture, textureView); } return hr; }
[ "chuckw@windows.microsoft.com" ]
chuckw@windows.microsoft.com
19695ed6ac400690fc2fb67033a7e0bff81736a3
30e55c13af4fbdfb422ef8a9d7f7b8ffd354e027
/src/dtypes/FiniteFields.cpp
5e68d068426e15f7029094ae61a5376b7dd06ed6
[]
no_license
jweir136/crud-bitcoin-cpp
d7e1fbe0bad348aca27a5910104082b5e83dcbec
79dd346733042028e6d4664bbffc76883eeb60f3
refs/heads/master
2023-03-25T23:26:58.541956
2021-03-25T20:55:23
2021-03-25T20:55:23
350,922,139
0
0
null
null
null
null
UTF-8
C++
false
false
539
cpp
#include "bigint/src/bigint.h" #include "FiniteFields.h" using namespace Dodecahedron; FieldElement::FieldElement(Bigint num, Bigint prime) { if (num >= prime || num < 0) throw "Invalid Input. Num must be in range [0,prime)"; this->num = num; this->prime = prime; } Bigint FieldElement::getPrime() { return this->prime; } Bigint FieldElement::getNum() { return this->num; } bool FieldElement::operator==(FieldElement& other) { return (this->prime == other.getPrime() && this->num == other.getNum()); }
[ "jacobweir@Jacobs-MacBook-Pro.local" ]
jacobweir@Jacobs-MacBook-Pro.local