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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
135b3473f8b452f11df2da65ae2052c1d6d4575f
b54829c3408a645bb0a13bccd4cc89df853ea3b3
/ReactionGameWithArcadianStyleLed.cydsn/Generated_Source/PSoC5/ErikaOS_1_ee_as_internal.inc
507c65267fd352bb524fee47dac6cc18c8557378
[]
no_license
aadarshkumar-singh/ReactionGameWithArcadianLeds
e023b437cf2b5735fc578ff981cab3b395e83688
f4b3e44e8dfa05c9fca23d32691c119ca7279577
refs/heads/master
2022-06-06T17:24:39.638079
2020-04-26T16:09:55
2020-04-26T16:09:55
259,063,626
0
0
null
null
null
null
UTF-8
C++
false
false
17,849
inc
/* ###*B*### * ERIKA Enterprise - a tiny RTOS for small microcontrollers * * Copyright (C) 2002-2012 Evidence Srl * * This file is part of ERIKA Enterprise. * * ERIKA Enterprise is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation, * (with a special exception described below). * * Linking this code statically or dynamically with other modules is * making a combined work based on this code. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * As a special exception, the copyright holders of this library give you * permission to link this code with independent modules to produce an * executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under * terms of your choice, provided that you also meet, for each linked * independent module, the terms and conditions of the license of that * module. An independent module is a module which is not derived from * or based on this library. If you modify this code, you may extend * this exception to your version of the code, but you are not * obligated to do so. If you do not wish to do so, delete this * exception statement from your version. * * ERIKA Enterprise 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 version 2 for more details. * * You should have received a copy of the GNU General Public License * version 2 along with ERIKA Enterprise; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * ###*E*### */ /** @file ee_as_internal.h * @brief Internals for Autosar layer * @author Errico Guidieri * @date 2012 */ /* * PSoC Port and API Generation * Carlos Fernando Meier Martinez * Hochschule Darmstadt, Germany. 2017. */ #ifndef PKG_KERNEL_AS_INC_EE_AS_INTERNAL_H #define PKG_KERNEL_AS_INC_EE_AS_INTERNAL_H #include "ErikaOS_1_ee_as_kernel.inc" #ifdef EE_AS_USER_SPINLOCKS__ /******************************************************************************* * Spinlock Internal Clean-Up ******************************************************************************/ __INLINE__ EE_TYPEBOOL EE_as_has_spinlocks_locked( EE_TID tid ) { SpinlockIdType const spinlock_id = EE_as_spinlocks_last[EE_CURRENTCPU]; return ( (spinlock_id != INVALID_SPINLOCK) && (EE_as_spinlocks_locker_task_or_isr2[spinlock_id] == tid) ); } /* Internal Clean-up function */ SpinlockIdType EE_as_release_all_spinlocks( EE_TID tid ); #else /* EE_AS_USER_SPINLOCKS__ */ #define EE_as_release_all_spinlocks(tid) ((void)0U) #endif /* EE_AS_USER_SPINLOCKS__ */ /******************************************************************************* * Schedule Tables Utilities ******************************************************************************/ #ifdef EE_AS_SCHEDULETABLES__ /* Utilities inline functions to check ticks and deviation values */ __INLINE__ TickType EE_as_tick_min( TickType t1, TickType t2 ) { if ( t1 <= t2 ) { return t1; } else { return t2; } } __INLINE__ EE_UREG EE_as_abs( TickType t ) { if ( t < EE_TYPETICK_HALF_VALUE ) { return t; } else { return -t; } } #endif /* EE_AS_SCHEDULETABLES__ */ #ifdef EE_AS_RPC__ /******************************************************************************* * Synchronous Remote Procedure Calls ******************************************************************************/ /** @brief Macro used to check if an id is a remote id */ #define EE_AS_ID_REMOTE(id) ((((EE_UINT32)(id)) & \ (EE_UINT32)EE_REMOTE_TID) != 0U) /** @brief Macro used to unmark a remote id */ #define EE_AS_UNMARK_REMOTE_ID(id) (((EE_UINT32)(id)) & (~EE_REMOTE_TID)) /** @brief define that identify an invalid ServiceId */ #define INVALID_SERVICE_ID ((OSServiceIdType)-1) #define INVALID_ERROR ((StatusType)-1) /** @brief RPC Handler to be called inside IIRQ handler */ extern void EE_as_rpc_handler( void ); /* If MemMap.h support is enabled (i.e. because memory protection): use it */ #ifdef EE_SUPPORT_MEMMAP_H /* The following code belong to ERIKA API section ee_api_text */ #define API_START_SEC_CODE #include "MemMap.inc" #endif /* EE_SUPPORT_MEMMAP_H */ #ifdef __EE_MEMORY_PROTECTION__ /** @brief The following implement a synchronous RPC kernel primitive from "user space" (so it's a syscall). */ extern StatusType EE_as_rpc_from_us( OSServiceIdType ServiceId, EE_os_param param1, EE_os_param param2, EE_os_param param3 ); #else /* __EE_MEMORY_PROTECTION__ */ __INLINE__ StatusType EE_as_rpc_from_us( OSServiceIdType ServiceId, EE_os_param param1, EE_os_param param2, EE_os_param param3 ) { StatusType ev; register EE_FREG const flag = EE_hal_begin_nested_primitive(); ev = EE_as_rpc(ServiceId, param1, param2, param3); EE_hal_end_nested_primitive(flag); return ev; } #endif /* __EE_MEMORY_PROTECTION__ */ #ifdef EE_SUPPORT_MEMMAP_H #define API_STOP_SEC_CODE #include "MemMap.inc" #endif /* EE_SUPPORT_MEMMAP_H */ #endif /* EE_AS_RPC__ */ #ifdef EE_AS_OSAPPLICATIONS__ /******************************************************************************* * OSApplication Utilities ******************************************************************************/ /** @brief Used to terminate current OS-Application. */ void EE_as_terminate_current_app_task( void ); /** @brief Used to terminate current OS-Application. */ #if defined(EE_MAX_ISR2) && (EE_MAX_ISR2 > 0) __INLINE__ void EE_as_terminate_current_app( void ) { if ( EE_hal_get_IRQ_nesting_level() == 0U ) { /* We are in a TASK */ EE_as_terminate_current_app_task(); } else { /* We are in the an ISR2 */ (void)EE_as_TerminateISR2(); } } #else /* EE_MAX_ISR2 > 0 */ __INLINE__ void EE_as_terminate_current_app( void ) { /* There are no ISR2: We are in a TASK */ EE_as_terminate_current_app_task(); } #endif /* EE_MAX_ISR2 > 0 */ /** * @brief Supposed to be called by EE_as_TerminateISR2 to restore trackin * OSApplication global variable and eventually terminate stacked. */ void EE_as_after_IRQ_interrupted_app ( ApplicationType interrupted_app ); /* @brief Function determines the currently running OS-Application. * (a unique identifier has to be allocated to each application). */ #if 0 ApplicationType EE_as_GetApplicationID_internal( void ); #endif /** @brief his service determines if the OS-Applications, given by ApplID, is * allowed to use the IDs of a Task, ISR, Resource, Counter, Alarm or * Schedule Table in API calls. */ ObjectAccessType EE_as_CheckObjectAccess_internal( ApplicationType ApplID, ObjectTypeType ObjectType, EE_UTID ObjectID ); /** @brief his service determines the OS-Applications to which the ID of a Task, ISR, Resource, Counter, Alarm or Schedule Table belong to. */ ApplicationType EE_as_CheckObjectOwnership_internal( ObjectTypeType ObjectType, EE_os_param_id ObjectID ); /** @brief Internal part of TerminateApplication service */ void EE_as_TerminateApplication_internal( ApplicationType Application, RestartType RestartOption ); /* THESE HAL FUNCTIONS DECLARATION ARE PUT HERE BECAUSE SIGNATURE DEPENDS ON AS KERNEL TYPES */ /** @brief Call application hook with right privileges */ void EE_hal_call_app_hook( EE_HOOKTYPE hook, ApplicationType app ); /** @brief Call status application hook with right privileges */ void EE_hal_call_app_status_hook( StatusType Error, EE_STATUSHOOKTYPE status_hook, ApplicationType app ); /** @brief Utility macro used to transform a Application ID in a bit mask */ #define EE_APP_TO_MASK(app_id) ((EE_TYPEACCESSMASK)1U << (app_id)) #ifdef EE_SERVICE_PROTECTION__ /******************************************************************************* * OSApplication Service Protection Access Data Structures ******************************************************************************/ /* [OS056] If an OS-object identifier is the parameter of an Operating System module's system service, and no sufficient access rights have been assigned to this OS-object at configuration time (Parameter Os[...]AccessingApplication) to the calling Task/Category 2 ISR, the Operating System module's system service shall return E_OS_ACCESS. (BSW11001, BSW11010, BSW11013) */ /* [OS448]: The Operating System module shall prevent access of OS-Applications, trusted or non-trusted, to objects not belonging to this OS-Application, except access rights for such objects are explicitly granted by configuration. */ /* [OS504] The Operating System module shall deny access to Operating System objects from other OS-Applications to an OS-Application which is not in state APPLICATION_ACCESSIBLE. */ /* [OS509] If a service call is made on an Operating System object that is owned by another OS-Application without state APPLICATION_ACCESSIBLE, then the Operating System module shall return E_OS_ACCESS. */ /** @var Contains access rules for TASKs */ extern EE_TYPEACCESSMASK const EE_as_task_access_rules[/*EE_MAX_TASK*/]; /** @var Contains access rules for ISRs */ extern EE_TYPEACCESSMASK const EE_as_isr_access_rules[/*EE_MAX_ISR_ID*/]; #ifndef __OO_NO_RESOURCES__ /** @var Contains access rules for RESOURCESs */ extern EE_TYPEACCESSMASK const EE_as_resource_access_rules[/*EE_MAX_RESOURCE*/]; #endif /* !__OO_NO_RESOURCES__ */ #if (!defined(__OO_NO_ALARMS__)) || defined(EE_AS_SCHEDULETABLES__) /** @var Contains access rules for COUNTERs */ extern EE_TYPEACCESSMASK const EE_as_counter_access_rules[/*EE_MAX_COUNTER*/]; #endif /* !__OO_NO_ALARMS__ || !EE_AS_SCHEDULETABLES__ */ #ifndef __OO_NO_ALARMS__ /** @var Contains access rules for ALARMs */ extern EE_TYPEACCESSMASK const EE_as_alarm_access_rules[/*EE_MAX_ALARM*/]; #endif /* !__OO_NO_ALARMS__ */ #ifdef EE_AS_SCHEDULETABLES__ /** @var Contains access rules for SCHEDULE TABLEs */ extern EE_TYPEACCESSMASK const EE_as_scheduletable_access_rules[/*EE_MAX_SCHEDULETABLE*/]; #endif /* EE_AS_SCHEDULETABLES__ */ #ifdef EE_AS_USER_SPINLOCKS__ /** @var Contains access rules for SCHEDULE TABLEs */ extern EE_TYPEACCESSMASK const EE_as_spinlock_access_rules[/*EE_MAX_SPINLOCK_USER*/]; #endif /* EE_AS_USER_SPINLOCKS__ */ /* OSApplication Objects belog to active Macros */ #define EE_OSAPP_TASK_ACCESS(TaskID) (EE_as_Application_RAM[\ EE_th_app[(TaskID + 1U)]].ApplState == APPLICATION_ACCESSIBLE) #define EE_OSAPP_ISR_ACCESS(ISRID) (EE_as_Application_RAM[\ EE_as_ISR_ROM[ISRID].ApplID].ApplState == APPLICATION_ACCESSIBLE) #define EE_OSAPP_COUNTER_ACCESS(CounterID) (EE_as_Application_RAM[\ EE_counter_ROM[CounterID].ApplID].ApplState == APPLICATION_ACCESSIBLE) #define EE_OSAPP_ALARM_ACCESS(AlarmID) (EE_as_Application_RAM[\ EE_alarm_ROM[AlarmID].ApplID].ApplState == APPLICATION_ACCESSIBLE) #define EE_OSAPP_SCHED_TABLE_ACCESS(SchedTableID) (EE_as_Application_RAM[\ EE_as_Schedule_Table_ROM[SchedTableID].ApplID].ApplState == \ APPLICATION_ACCESSIBLE) /* Access Macros */ #define EE_TASK_ACCESS(TaskID, ApplID) (((EE_as_task_access_rules[TaskID] & \ EE_APP_TO_MASK(ApplID)) && EE_OSAPP_TASK_ACCESS(TaskID))) #define EE_ISR_ACCESS(ISRID, ApplID) (((EE_as_isr_access_rules[ISRID] & \ EE_APP_TO_MASK(ApplID)) && EE_OSAPP_ISR_ACCESS(ISRID))) #define EE_COUNTER_ACCESS(CounterID, ApplID) \ (((EE_as_counter_access_rules[CounterID] & EE_APP_TO_MASK(ApplID)) && \ EE_OSAPP_COUNTER_ACCESS(CounterID))) #define EE_ALARM_ACCESS(AlarmID, ApplID) (((EE_as_alarm_access_rules[\ AlarmID] & EE_APP_TO_MASK(ApplID)) && EE_OSAPP_ALARM_ACCESS(AlarmID))) #define EE_SCHED_TABLE_ACCESS(SchedTableID, ApplID) \ (((EE_as_scheduletable_access_rules[SchedTableID] & EE_APP_TO_MASK(ApplID)) \ && EE_OSAPP_SCHED_TABLE_ACCESS(SchedTableID))) #define EE_RESOURCE_ACCESS(ResourceID, ApplID) \ ((EE_as_resource_access_rules[ResourceID] & EE_APP_TO_MASK(ApplID))) #define EE_SPINLOCK_ACCESS(SpinlockID, ApplID) \ ((EE_as_spinlock_access_rules[SpinlockID] & EE_APP_TO_MASK(ApplID))) /* Error Macros */ #define EE_TASK_ACCESS_ERR(TaskID, ApplID) (!EE_TASK_ACCESS(TaskID, ApplID)) #define EE_ISR_ACCESS_ERR(ISRID, ApplID) (!EE_ISR_ACCESS(ISRID, ApplID)) #define EE_COUNTER_ACCESS_ERR(CounterID, ApplID) (!EE_COUNTER_ACCESS(CounterID,\ ApplID)) #define EE_ALARM_ACCESS_ERR(AlarmID, ApplID) (!EE_ALARM_ACCESS(AlarmID, \ ApplID)) #define EE_SCHED_TABLE_ACCESS_ERR(SchedTableID, ApplID) \ (!EE_SCHED_TABLE_ACCESS(SchedTableID, ApplID)) #define EE_RESOURCE_ACCESS_ERR(ResourceID, ApplID) \ (!EE_RESOURCE_ACCESS(ResourceID, ApplID)) #define EE_SPINLOCK_ACCESS_ERR(SpinlockID, ApplID) \ (!EE_SPINLOCK_ACCESS(SpinlockID, ApplID)) #endif /* EE_SERVICE_PROTECTION__ */ #endif /* EE_AS_OSAPPLICATIONS__ */ #ifdef EE_AS_HAS_PROTECTIONHOOK__ /******************************************************************************* * ProtectionHook Internal Support ******************************************************************************/ #ifdef EE_AS_OSAPPLICATIONS__ /** * @brief This function wraps the call to the protection hook. * Also, it does what is required to do according to what the ProtectionHook * returns. * @param error_app the OS-Application that caused the error * @param error the error to send to the ProtectionHook function */ void EE_as_handle_protection_error( ApplicationType error_app, StatusType error ); #else /* EE_AS_OSAPPLICATIONS__ */ /** * @brief This function wraps the call to the protection hook. * Also, it does what is required to do according to what the ProtectionHook * returns. * @param error the error to send to the ProtectionHook function */ void EE_as_handle_protection_error( StatusType error ); #endif /* EE_AS_OSAPPLICATIONS__ */ #endif /* EE_AS_HAS_PROTECTIONHOOK__ */ #ifdef __EE_MEMORY_PROTECTION__ /******************************************************************************* * Memory Protection Internal Support ******************************************************************************/ /** Syscall table */ extern EE_FADDR const EE_syscall_table[/*EE_SYSCALL_NR*/]; /** @typedef for TRUSTED Function pointers */ typedef StatusType (*EE_TRUSTEDFUNCTYPE)(TrustedFunctionIndexType, TrustedFunctionParameterRefType); /* THIS HAL FUNCTIONS DECLARATION ARE PUT HERE BECAUSE SIGNATURE DEPENDS ON AS KERNEL TYPES */ /** * Return the access permission for the given memory area. Defined in the CPU * layer. */ AccessType EE_hal_get_app_mem_access(ApplicationType app, MemoryStartAddressType beg, MemorySizeType size); #if defined(EE_SYSCALL_NR) && defined(EE_MAX_SYS_SERVICEID) &&\ (EE_SYSCALL_NR > EE_MAX_SYS_SERVICEID) __INLINE__ EE_TYPEBOOL EE_as_active_app_is_inside_trusted_function_call ( void ) { return EE_as_Application_RAM[EE_as_active_app]. TrustedFunctionCallsCounter != 0U; } #else /* EE_SYSCALL_NR > EE_MAX_SYS_SERVICEID */ #define EE_as_active_app_is_inside_trusted_function_call() EE_FALSE #endif /* EE_SYSCALL_NR > EE_MAX_SYS_SERVICEID */ #else /* __EE_MEMORY_PROTECTION__ */ #define EE_as_active_app_is_inside_trusted_function_call() EE_FALSE #endif /* __EE_MEMORY_PROTECTION__ */ /******************************************************************************* * Stack Monitoring Internal Support ******************************************************************************/ #ifdef EE_STACK_MONITORING__ #ifdef EE_AS_OSAPPLICATIONS__ /* Functions used to check and handle Stack Overflow, with short cut to pass current application */ void EE_as_check_and_handle_stack_overflow( ApplicationType appid, EE_UREG stktop ); #else /* EE_AS_OSAPPLICATIONS__ */ /* Functions used to check and handle Stack Overflow. Have to be to be implemented in each porting that support stack monitoring */ void EE_as_check_and_handle_stack_overflow( EE_UREG stktop ); #endif /* EE_AS_OSAPPLICATIONS__ */ /* Used Internally in Kernel primitives */ void EE_as_monitoring_the_stack( void ); #else /* EE_STACK_MONITORING__ */ #ifdef EE_AS_OSAPPLICATIONS__ __INLINE__ void EE_as_check_and_handle_stack_overflow( ApplicationType appid, EE_UREG stktop ) {} #else /* EE_AS_OSAPPLICATIONS__ */ __INLINE__ void EE_as_check_and_handle_stack_overflow( EE_UREG stktop ) {} #endif /* EE_AS_OSAPPLICATIONS__ */ __INLINE__ void EE_as_monitoring_the_stack( void ) {} #endif /* EE_STACK_MONITORING__ */ /* Used to select witch system ERROR handling function call */ #ifdef EE_AS_HAS_PROTECTIONHOOK__ #ifdef EE_AS_OSAPPLICATIONS__ #define EE_as_call_protection_error(app, error) \ EE_as_handle_protection_error(app, error) #else /* EE_AS_OSAPPLICATIONS__ */ #define EE_as_call_protection_error(app, error) \ EE_as_handle_protection_error(error) #endif /* EE_AS_OSAPPLICATIONS__ */ #else /* EE_AS_HAS_PROTECTIONHOOK__ */ #define EE_as_call_protection_error(app, error) \ EE_oo_ShutdownOS_internal(error) #endif /* EE_AS_HAS_PROTECTIONHOOK__ */ #endif /* INCLUDE_EE_KERNEL_AS_INTERNAL__ */
[ "aadarshxp@gmail.com" ]
aadarshxp@gmail.com
b9a0089e9ff15372c8809bae2153da632e3fc563
7f6d2df4f97ee88d8614881b5fa0e30d51617e61
/武庆安/Experiment_3/SouceCode/example2_04-局部变量.cpp
311b7cbb672a69dfd339860f01fdf4f1afa044e8
[]
no_license
tsingke/Homework_Turing
79d36b18692ec48b1b65cfb83fc21abf87fd53b0
aa077a2ca830cdf14f4a0fd55e61822a4f99f01d
refs/heads/master
2021-10-10T02:03:53.951212
2019-01-06T07:44:20
2019-01-06T07:44:20
148,451,853
15
25
null
2018-10-17T15:20:24
2018-09-12T09:01:50
C++
UTF-8
C++
false
false
905
cpp
// example2_04:局部变量示例 #include <stdio.h> #include <windows.h> int n = 10; //全局变量 void func(int n) { n = 20; //局部变量 printf("func n: %d\n", n); } void func1() { int n = 20; //局部变量 printf("func1 n: %d\n", n); } void func2(int n) { printf("func2 n: %d\n", n); } void func3() { printf("func3 n: %d\n", n); } int main() { int n = 30; //局部变量 func(n); //20 子函数有,传参,输出自己的wqa func1(); //20 子函数有,不传参,输出自己的 func2(n); //30 子函数无,传参,输出mian()里的 func3(); //10 子函数无,不传参,输全局变量的 //代码块由{}包围 { int n = 40; //局部变量 printf("block n: %d\n", n); //40 代码块包围,输出代码块里的 } printf("main n: %d\n", n); //30 main---全局变量 system("pause"); return 0; }
[ "201711010304@stu.sdnu.edu.cn" ]
201711010304@stu.sdnu.edu.cn
000384326b414cc12fde586ff73a5ec5e224f532
633842301cd36cad562767da691ed5297ccd559f
/Accepted/zerojudge/a034. 二進位制轉換.cpp
643d1683c28f534d7835d148ab6ef72a0f26795d
[]
no_license
turtle11311/Codes
c5b87864f59802241b6784ccd5cd553fe5533748
7711679dffb421323ab2cc389662d106d50ab16c
refs/heads/master
2020-04-06T05:20:33.810466
2014-12-24T12:20:13
2014-12-24T12:20:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
292
cpp
#include <iostream> #include <string> using namespace std; int main () { long long int n, i; char ans[60]; while (cin >> n) { for (i=0;i<60;i++) ans[i]=' '; for (i=0;n != 0;n/=2,i++) ans[i]=n%2+'0'; for (i-=1;i>=0;i--) cout << ans[i]; cout << endl; } }
[ "turtle11311@hotmail.com" ]
turtle11311@hotmail.com
9282485cafc454aa7bbdae8f65515af9af9f4d4b
8ce1e9f1bef1a647f4c986a24df5340ffb17bc4e
/Linked List OO/LinkedListsOOPAssignment/LinkedListsOOPAssignment/Employee.h
a22ad6b25c73ef189d3ed24dee43fb4c1b93435b
[]
no_license
Nikhilvedi/University-Work
54ac1b22c3dba8bb65f493962b0fbef3bd6cc526
118705add1d105e753af5f7814484a3388f6645e
refs/heads/master
2021-01-10T15:06:22.126914
2015-10-17T16:12:04
2015-10-17T16:12:04
44,443,475
0
0
null
null
null
null
UTF-8
C++
false
false
831
h
#include "stdafx.h" #include <string> using namespace std; #ifndef EMPLOYEE_H #define EMPLOYEE_H class Employee { protected: string name; string startDate; int empNumber; int dept; public: Employee(); Employee(string, string, int, int); string getName(); string getStartDate(); int getEmpNo(); int getDept(); void setDept(int); void setName(string); virtual ~Employee(); }; class Manager : public Employee { private: int salary; public: Manager(); Manager(int,string, string, int, int); int getSalary(); void setSalary(int); virtual ~Manager(); }; class Staff : public Employee { private: int hoursPerWeek; double hourlyRate; public: Staff(); Staff(int, double, string, string, int, int); void setHours(int); void setRate(double); double getWage(); double getRate(); virtual ~Staff(); }; #endif
[ "nv94@hotmail.co.uk" ]
nv94@hotmail.co.uk
9cfd63ec381c30e60c8e82aac8f62958be1fe804
d43c3fbfd149d2ac0a051a0074585dce345ae967
/muduo/muduo/base/AsyncLogging.h
8aaa827df955de6b60c0a78c461f5d93061cb52b
[ "BSD-3-Clause" ]
permissive
wuzhl2018/AnnotatedVersion
3dad25b843a7ba5dd272dca61e9bde98483dd1af
bfdafa36e18e7212fac01762e628aef28633b9a4
refs/heads/master
2020-09-16T22:03:22.695817
2019-11-20T05:18:34
2019-11-20T05:18:34
223,900,026
1
1
null
null
null
null
UTF-8
C++
false
false
1,706
h
#ifndef MUDUO_BASE_ASYNCLOGGING_H #define MUDUO_BASE_ASYNCLOGGING_H #include <muduo/base/BlockingQueue.h> #include <muduo/base/BoundedBlockingQueue.h> #include <muduo/base/CountDownLatch.h> #include <muduo/base/Mutex.h> #include <muduo/base/Thread.h> #include <muduo/base/LogStream.h> #include <boost/bind.hpp> #include <boost/noncopyable.hpp> #include <boost/scoped_ptr.hpp> #include <boost/ptr_container/ptr_vector.hpp> namespace muduo { class AsyncLogging : boost::noncopyable { public: AsyncLogging(const string& basename, off_t rollSize, int flushInterval = 3); ~AsyncLogging() { if (running_) { stop(); } } void append(const char* logline, int len); void start() { running_ = true; thread_.start(); latch_.wait(); } void stop() NO_THREAD_SAFETY_ANALYSIS { running_ = false; cond_.notify(); thread_.join(); } private: // declare but not define, prevent compiler-synthesized functions AsyncLogging(const AsyncLogging&); // ptr_container void operator=(const AsyncLogging&); // ptr_container void threadFunc(); typedef muduo::detail::FixedBuffer<muduo::detail::kLargeBuffer> Buffer; typedef boost::ptr_vector<Buffer> BufferVector; typedef BufferVector::auto_type BufferPtr; const int flushInterval_; bool running_; const string basename_; const off_t rollSize_; muduo::Thread thread_; muduo::CountDownLatch latch_; muduo::MutexLock mutex_; muduo::Condition cond_ GUARDED_BY(mutex_); BufferPtr currentBuffer_ GUARDED_BY(mutex_); BufferPtr nextBuffer_ GUARDED_BY(mutex_); BufferVector buffers_ GUARDED_BY(mutex_); }; } #endif // MUDUO_BASE_ASYNCLOGGING_H
[ "805356546@qq.com" ]
805356546@qq.com
0dcc6931687b70e8737fbf4bf1b324537ebe98b5
563e3598843e0d7883c34d7d7fab130259cc0d60
/PalindromePermutation.cpp
89f7e88ea939c4ee42f408046b44d35f0560d3a1
[]
no_license
rshah918/Cracking-the-Coding-Interview
a315ba17bf590f23ebb343fa231df6c02d49e07f
e8d2fe39975f3dcad44bb931b6baa44ab7b4a9f9
refs/heads/master
2023-08-18T12:10:46.766123
2021-10-07T22:23:25
2021-10-07T22:23:25
270,379,968
0
0
null
null
null
null
UTF-8
C++
false
false
927
cpp
#include <iostream> #include <string> #include <unordered_map> using namespace std; bool palindromePermutation(string s){ unordered_map<char, int> char_count; int num_odd_chars = 0; for(int i = 0; i < s.length(); i++){ char curr = s[i]; //increment character count in hash table if(char_count.find(curr) == char_count.end()){ char_count[curr] = 1; } else{ char_count[curr] = char_count[curr] + 1; } //update the number of odd characters if(char_count[curr] % 2 != 0){ num_odd_chars += 1; } else{ num_odd_chars -= 1; } } //not a palindrome unless there is either 1 or 0 characters with an odd char_count. if(num_odd_chars <= 1){ return true; } else{ return false; } } int main(){ cout << palindromePermutation("tactcoa") << endl; }
[ "rahulshah512@gmail.com" ]
rahulshah512@gmail.com
52eb4760b11dac8c56eb9d276f17939a29590817
92e75166e42ff0715de0834a0a3c7a950f9a710e
/src/my_predictor.h
5f41bc83429fc99893ef032f47888a72562f5760
[]
no_license
chainy35/Dynamic-Branch-Prediction-with-Perceptrons
0a3737dd3b4476187d43927c36869df1e4d49e4a
31c3801ba4ee1b03955c9d53f6193f2f69759c8d
refs/heads/master
2021-05-10T11:24:12.746713
2018-01-22T06:08:59
2018-01-22T06:08:59
118,410,976
0
0
null
null
null
null
UTF-8
C++
false
false
2,733
h
// my_predictor.h // This file contains a sample my_predictor class. // It is a simple 32,768-entry gshare with a history length of 15. // Note that this predictor doesn't use the whole 8 kilobytes available // for the CBP-2 contest; it is just an example. #include <math.h> class my_update : public branch_update { public: unsigned int index; int percep_output; }; class my_predictor : public branch_predictor { public: #define HISTORY_LENGTH 30 #define TABLE_BITS 15 #define INDEX_LENGTH 1<<TABLE_BITS #define THETA floor(1.93 * HISTORY_LENGTH + 14) #define MAX_WT 127 #define MIN_WT -128 #define PERCEP_TABLE_SZ 268 my_update u; branch_info bi; unsigned long long int history; // the branch history rigister (BHR) char tab_percep[PERCEP_TABLE_SZ][HISTORY_LENGTH+1]; // the perceptron table my_predictor (void) { // initialize the branch history register and perceptron table to 0 history = 0; for(int i=0 ; i< (PERCEP_TABLE_SZ); i++) { for(int j=0; j < (HISTORY_LENGTH+1); j++) { tab_percep[i][j] = 0; } } } branch_update *predict (branch_info & b) { bi = b; if (b.br_flags & BR_CONDITIONAL) { u.index = b.address % (PERCEP_TABLE_SZ); // calculate the perceptron output using bits of branch history register and // the corresponding weights of the perceptron table u.percep_output = tab_percep[u.index][0]; for (int i=1; i < (HISTORY_LENGTH +1); i++ ) { if ( (history >> i ) & 0x1) { u.percep_output += tab_percep[u.index][i]; } else { u.percep_output -= tab_percep[u.index][i]; } } if ( u.percep_output >= 0) { u.direction_prediction (true); } else { u.direction_prediction (false); } } else { u.direction_prediction (true); // unconditional branch } u.target_prediction (0); return &u; } void update (branch_update *u, bool taken, unsigned int target) { if (bi.br_flags & BR_CONDITIONAL) { // if the prediction is wrong or the weight value is smaller than the threshold THETA, // then update the weight to train the perceptron if( ((my_update*)u)->direction_prediction() != taken || abs(((my_update*)u)->percep_output) < THETA) { unsigned int idx = ((my_update*)u)->index; if (taken) { tab_percep[idx][0] ++; } else { tab_percep[idx][0] --; } for (int i = 1; i < HISTORY_LENGTH + 1; i++) { if (taken == ((history >> i ) & 0x1)) { if (tab_percep[idx][i] < MAX_WT ) tab_percep[idx][i] ++; } else { if (tab_percep[idx][i] > MIN_WT) tab_percep[idx][i] --; } } } history <<= 1; history |= taken; history &= (1<<HISTORY_LENGTH)-1; } } };
[ "noreply@github.com" ]
chainy35.noreply@github.com
c9e31faedac8f4b1781a1c72c7b3ee9a885248c3
1111ac58ece117d2cd96bb5cabe07ab41220ad25
/class.h
f775453fb48ac05fcc2f9ae7ab64973378734389
[ "MIT" ]
permissive
Sophie-Williams/TAK-Game-playing-bot
f51f2a2c3b3498ecbe5f8f67c0730e4b2315075b
ee30166749669a03f7ecbb64caa8832bfa52ebc0
refs/heads/master
2020-05-19T15:39:17.191448
2016-11-12T15:45:40
2016-11-12T15:45:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
368
h
#include<bits/stdc++.h> using namespace std; class state{ public: state* parent; vector< vector< vector< int > > > boardState; double eval ; double alpha, beta ; int depth; string printM ; //define a constructor function //error vecotr state(int size); state() ; bool operator < (const state& st) const { return (eval > st.eval); } };
[ "singhmanish1997@gmail.com" ]
singhmanish1997@gmail.com
976290a73958d73cba75c59572bd703df53e2c98
0f23651b08fd5a8ce21b9e78e39e61618996073b
/tools/clang/test/Misc/ast-dump-decl.cpp
0df8a5a2b8fb78765b51f6a8db062befe01e20c6
[ "NCSA" ]
permissive
arcosuc3m/clang-contracts
3983773f15872514f7b6ae72d7fea232864d7e3d
99446829e2cd96116e4dce9496f88cc7df1dbe80
refs/heads/master
2021-07-04T03:24:03.156444
2018-12-12T11:41:18
2018-12-12T12:56:08
118,155,058
31
1
null
null
null
null
UTF-8
C++
false
false
19,304
cpp
// RUN: %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -fms-extensions -ast-dump -ast-dump-filter Test %s | FileCheck -strict-whitespace %s class testEnumDecl { enum class TestEnumDeclScoped; enum TestEnumDeclFixed : int; }; // CHECK: EnumDecl{{.*}} class TestEnumDeclScoped 'int' // CHECK: EnumDecl{{.*}} TestEnumDeclFixed 'int' class testFieldDecl { int TestFieldDeclInit = 0; }; // CHECK: FieldDecl{{.*}} TestFieldDeclInit 'int' // CHECK-NEXT: IntegerLiteral namespace testVarDeclNRVO { class A { }; A foo() { A TestVarDeclNRVO; return TestVarDeclNRVO; } } // CHECK: VarDecl{{.*}} TestVarDeclNRVO 'class testVarDeclNRVO::A' nrvo void testParmVarDeclInit(int TestParmVarDeclInit = 0); // CHECK: ParmVarDecl{{.*}} TestParmVarDeclInit 'int' // CHECK-NEXT: IntegerLiteral{{.*}} namespace TestNamespaceDecl { int i; } // CHECK: NamespaceDecl{{.*}} TestNamespaceDecl // CHECK-NEXT: VarDecl namespace TestNamespaceDecl { int j; } // CHECK: NamespaceDecl{{.*}} TestNamespaceDecl // CHECK-NEXT: original Namespace // CHECK-NEXT: VarDecl inline namespace TestNamespaceDeclInline { } // CHECK: NamespaceDecl{{.*}} TestNamespaceDeclInline inline namespace testUsingDirectiveDecl { namespace A { } } namespace TestUsingDirectiveDecl { using namespace testUsingDirectiveDecl::A; } // CHECK: NamespaceDecl{{.*}} TestUsingDirectiveDecl // CHECK-NEXT: UsingDirectiveDecl{{.*}} Namespace{{.*}} 'A' namespace testNamespaceAlias { namespace A { } } namespace TestNamespaceAlias = testNamespaceAlias::A; // CHECK: NamespaceAliasDecl{{.*}} TestNamespaceAlias // CHECK-NEXT: Namespace{{.*}} 'A' using TestTypeAliasDecl = int; // CHECK: TypeAliasDecl{{.*}} TestTypeAliasDecl 'int' namespace testTypeAliasTemplateDecl { template<typename T> class A; template<typename T> using TestTypeAliasTemplateDecl = A<T>; } // CHECK: TypeAliasTemplateDecl{{.*}} TestTypeAliasTemplateDecl // CHECK-NEXT: TemplateTypeParmDecl // CHECK-NEXT: TypeAliasDecl{{.*}} TestTypeAliasTemplateDecl 'A<T>' namespace testCXXRecordDecl { class TestEmpty {}; // CHECK: CXXRecordDecl{{.*}} class TestEmpty // CHECK-NEXT: DefinitionData pass_in_registers empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init // CHECK-NEXT: DefaultConstructor exists trivial constexpr // CHECK-NEXT: CopyConstructor simple trivial has_const_param // CHECK-NEXT: MoveConstructor exists simple trivial // CHECK-NEXT: CopyAssignment trivial has_const_param // CHECK-NEXT: MoveAssignment exists simple trivial // CHECK-NEXT: Destructor simple irrelevant trivial class A { }; class B { }; class TestCXXRecordDecl : virtual A, public B { int i; }; } // CHECK: CXXRecordDecl{{.*}} class TestCXXRecordDecl // CHECK-NEXT: DefinitionData{{$}} // CHECK-NEXT: DefaultConstructor exists non_trivial // CHECK-NEXT: CopyConstructor simple non_trivial has_const_param // CHECK-NEXT: MoveConstructor exists simple non_trivial // CHECK-NEXT: CopyAssignment non_trivial has_const_param // CHECK-NEXT: MoveAssignment exists simple non_trivial // CHECK-NEXT: Destructor simple irrelevant trivial // CHECK-NEXT: virtual private 'class testCXXRecordDecl::A' // CHECK-NEXT: public 'class testCXXRecordDecl::B' // CHECK-NEXT: CXXRecordDecl{{.*}} class TestCXXRecordDecl // CHECK-NEXT: FieldDecl template<class...T> class TestCXXRecordDeclPack : public T... { }; // CHECK: CXXRecordDecl{{.*}} class TestCXXRecordDeclPack // CHECK: public 'T'... // CHECK-NEXT: CXXRecordDecl{{.*}} class TestCXXRecordDeclPack thread_local int TestThreadLocalInt; // CHECK: TestThreadLocalInt {{.*}} tls_dynamic class testCXXMethodDecl { virtual void TestCXXMethodDeclPure() = 0; void TestCXXMethodDeclDelete() = delete; void TestCXXMethodDeclThrow() throw(); void TestCXXMethodDeclThrowType() throw(int); }; // CHECK: CXXMethodDecl{{.*}} TestCXXMethodDeclPure 'void (void)' virtual pure // CHECK: CXXMethodDecl{{.*}} TestCXXMethodDeclDelete 'void (void)' delete // CHECK: CXXMethodDecl{{.*}} TestCXXMethodDeclThrow 'void (void) throw()' // CHECK: CXXMethodDecl{{.*}} TestCXXMethodDeclThrowType 'void (void) throw(int)' namespace testCXXConstructorDecl { class A { }; class TestCXXConstructorDecl : public A { int I; TestCXXConstructorDecl(A &a, int i) : A(a), I(i) { } TestCXXConstructorDecl(A &a) : TestCXXConstructorDecl(a, 0) { } }; } // CHECK: CXXConstructorDecl{{.*}} TestCXXConstructorDecl 'void {{.*}}' // CHECK-NEXT: ParmVarDecl{{.*}} a // CHECK-NEXT: ParmVarDecl{{.*}} i // CHECK-NEXT: CXXCtorInitializer{{.*}}A // CHECK-NEXT: Expr // CHECK: CXXCtorInitializer{{.*}}I // CHECK-NEXT: Expr // CHECK: CompoundStmt // CHECK: CXXConstructorDecl{{.*}} TestCXXConstructorDecl 'void {{.*}}' // CHECK-NEXT: ParmVarDecl{{.*}} a // CHECK-NEXT: CXXCtorInitializer{{.*}}TestCXXConstructorDecl // CHECK-NEXT: CXXConstructExpr{{.*}}TestCXXConstructorDecl class TestCXXDestructorDecl { ~TestCXXDestructorDecl() { } }; // CHECK: CXXDestructorDecl{{.*}} ~TestCXXDestructorDecl 'void (void) noexcept' // CHECK-NEXT: CompoundStmt // Test that the range of a defaulted members is computed correctly. class TestMemberRanges { public: TestMemberRanges() = default; TestMemberRanges(const TestMemberRanges &Other) = default; TestMemberRanges(TestMemberRanges &&Other) = default; ~TestMemberRanges() = default; TestMemberRanges &operator=(const TestMemberRanges &Other) = default; TestMemberRanges &operator=(TestMemberRanges &&Other) = default; }; void SomeFunction() { TestMemberRanges A; TestMemberRanges B(A); B = A; A = static_cast<TestMemberRanges &&>(B); TestMemberRanges C(static_cast<TestMemberRanges &&>(A)); } // CHECK: CXXConstructorDecl{{.*}} <line:{{.*}}:3, col:30> // CHECK: CXXConstructorDecl{{.*}} <line:{{.*}}:3, col:59> // CHECK: CXXConstructorDecl{{.*}} <line:{{.*}}:3, col:54> // CHECK: CXXDestructorDecl{{.*}} <line:{{.*}}:3, col:31> // CHECK: CXXMethodDecl{{.*}} <line:{{.*}}:3, col:70> // CHECK: CXXMethodDecl{{.*}} <line:{{.*}}:3, col:65> class TestCXXConversionDecl { operator int() { return 0; } }; // CHECK: CXXConversionDecl{{.*}} operator int 'int (void)' // CHECK-NEXT: CompoundStmt namespace TestStaticAssertDecl { static_assert(true, "msg"); } // CHECK: NamespaceDecl{{.*}} TestStaticAssertDecl // CHECK-NEXT: StaticAssertDecl{{.*> .*$}} // CHECK-NEXT: CXXBoolLiteralExpr // CHECK-NEXT: StringLiteral namespace testFunctionTemplateDecl { class A { }; class B { }; class C { }; class D { }; template<typename T> void TestFunctionTemplate(T) { } // implicit instantiation void bar(A a) { TestFunctionTemplate(a); } // explicit specialization template<> void TestFunctionTemplate(B); // explicit instantiation declaration extern template void TestFunctionTemplate(C); // explicit instantiation definition template void TestFunctionTemplate(D); } // CHECK: FunctionTemplateDecl{{.*}} TestFunctionTemplate // CHECK-NEXT: TemplateTypeParmDecl // CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate 'void (T)' // CHECK-NEXT: ParmVarDecl{{.*}} 'T' // CHECK-NEXT: CompoundStmt // CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}A // CHECK-NEXT: TemplateArgument // CHECK-NEXT: ParmVarDecl // CHECK-NEXT: CompoundStmt // CHECK-NEXT: Function{{.*}} 'TestFunctionTemplate' {{.*}}B // CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}C // CHECK-NEXT: TemplateArgument // CHECK-NEXT: ParmVarDecl // CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}D // CHECK-NEXT: TemplateArgument // CHECK-NEXT: ParmVarDecl // CHECK-NEXT: CompoundStmt // CHECK: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}B // CHECK-NEXT: TemplateArgument // CHECK-NEXT: ParmVarDecl namespace testClassTemplateDecl { class A { }; class B { }; class C { }; class D { }; template<typename T> class TestClassTemplate { public: TestClassTemplate(); ~TestClassTemplate(); int j(); int i; }; // implicit instantiation TestClassTemplate<A> a; // explicit specialization template<> class TestClassTemplate<B> { int j; }; // explicit instantiation declaration extern template class TestClassTemplate<C>; // explicit instantiation definition template class TestClassTemplate<D>; // partial explicit specialization template<typename T1, typename T2> class TestClassTemplatePartial { int i; }; template<typename T1> class TestClassTemplatePartial<T1, A> { int j; }; } // CHECK: ClassTemplateDecl{{.*}} TestClassTemplate // CHECK-NEXT: TemplateTypeParmDecl // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK-NEXT: AccessSpecDecl{{.*}} public // CHECK-NEXT: CXXConstructorDecl{{.*}} <line:{{.*}}:5, col:23> // CHECK-NEXT: CXXDestructorDecl{{.*}} <line:{{.*}}:5, col:24> // CHECK-NEXT: CXXMethodDecl{{.*}} <line:{{.*}}:5, col:11> // CHECK-NEXT: FieldDecl{{.*}} i // CHECK-NEXT: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate // CHECK: TemplateArgument{{.*}}A // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK-NEXT: AccessSpecDecl{{.*}} public // CHECK-NEXT: CXXConstructorDecl{{.*}} <line:{{.*}}:5, col:23> // CHECK-NEXT: CXXDestructorDecl{{.*}} <line:{{.*}}:5, col:24> // CHECK-NEXT: CXXMethodDecl{{.*}} <line:{{.*}}:5, col:11> // CHECK-NEXT: FieldDecl{{.*}} i // CHECK: ClassTemplateSpecialization{{.*}} 'TestClassTemplate' // CHECK-NEXT: ClassTemplateSpecialization{{.*}} 'TestClassTemplate' // CHECK-NEXT: ClassTemplateSpecialization{{.*}} 'TestClassTemplate' // CHECK: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate // CHECK-NEXT: DefinitionData // CHECK: TemplateArgument{{.*}}B // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK-NEXT: FieldDecl{{.*}} j // CHECK: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate // CHECK: TemplateArgument{{.*}}C // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK-NEXT: AccessSpecDecl{{.*}} public // CHECK-NEXT: CXXConstructorDecl{{.*}} <line:{{.*}}:5, col:23> // CHECK-NEXT: CXXDestructorDecl{{.*}} <line:{{.*}}:5, col:24> // CHECK-NEXT: CXXMethodDecl{{.*}} <line:{{.*}}:5, col:11> // CHECK-NEXT: FieldDecl{{.*}} i // CHECK: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate // CHECK: TemplateArgument{{.*}}D // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK-NEXT: AccessSpecDecl{{.*}} public // CHECK-NEXT: CXXConstructorDecl{{.*}} <line:{{.*}}:5, col:23> // CHECK-NEXT: CXXDestructorDecl{{.*}} <line:{{.*}}:5, col:24> // CHECK-NEXT: CXXMethodDecl{{.*}} <line:{{.*}}:5, col:11> // CHECK-NEXT: FieldDecl{{.*}} i // CHECK: ClassTemplatePartialSpecializationDecl{{.*}} class TestClassTemplatePartial // CHECK: TemplateArgument // CHECK-NEXT: TemplateArgument{{.*}}A // CHECK-NEXT: TemplateTypeParmDecl // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplatePartial // CHECK-NEXT: FieldDecl{{.*}} j // PR15220 dump instantiation only once namespace testCanonicalTemplate { class A {}; template<typename T> void TestFunctionTemplate(T); template<typename T> void TestFunctionTemplate(T); void bar(A a) { TestFunctionTemplate(a); } // CHECK: FunctionTemplateDecl{{.*}} TestFunctionTemplate // CHECK-NEXT: TemplateTypeParmDecl // CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate 'void (T)' // CHECK-NEXT: ParmVarDecl{{.*}} 'T' // CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}A // CHECK-NEXT: TemplateArgument // CHECK-NEXT: ParmVarDecl // CHECK: FunctionTemplateDecl{{.*}} TestFunctionTemplate // CHECK-NEXT: TemplateTypeParmDecl // CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate 'void (T)' // CHECK-NEXT: ParmVarDecl{{.*}} 'T' // CHECK-NEXT: Function{{.*}} 'TestFunctionTemplate' // CHECK-NOT: TemplateArgument template<typename T1> class TestClassTemplate { template<typename T2> friend class TestClassTemplate; }; TestClassTemplate<A> a; // CHECK: ClassTemplateDecl{{.*}} TestClassTemplate // CHECK-NEXT: TemplateTypeParmDecl // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK-NEXT: FriendDecl // CHECK-NEXT: ClassTemplateDecl{{.*}} TestClassTemplate // CHECK-NEXT: TemplateTypeParmDecl // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate // CHECK-NEXT: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate // CHECK: TemplateArgument{{.*}}A // CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate } template <class T> class TestClassScopeFunctionSpecialization { template<class U> void foo(U a) { } template<> void foo<int>(int a) { } }; // CHECK: ClassScopeFunctionSpecializationDecl // CHECK-NEXT: CXXMethod{{.*}} 'foo' 'void (int)' // CHECK-NEXT: TemplateArgument{{.*}} 'int' namespace TestTemplateTypeParmDecl { template<typename ... T, class U = int> void foo(); } // CHECK: NamespaceDecl{{.*}} TestTemplateTypeParmDecl // CHECK-NEXT: FunctionTemplateDecl // CHECK-NEXT: TemplateTypeParmDecl{{.*}} typename depth 0 index 0 ... T // CHECK-NEXT: TemplateTypeParmDecl{{.*}} class depth 0 index 1 U // CHECK-NEXT: TemplateArgument type 'int' namespace TestNonTypeTemplateParmDecl { template<int I = 1, int ... J> void foo(); } // CHECK: NamespaceDecl{{.*}} TestNonTypeTemplateParmDecl // CHECK-NEXT: FunctionTemplateDecl // CHECK-NEXT: NonTypeTemplateParmDecl{{.*}} 'int' depth 0 index 0 I // CHECK-NEXT: TemplateArgument expr // CHECK-NEXT: IntegerLiteral{{.*}} 'int' 1 // CHECK-NEXT: NonTypeTemplateParmDecl{{.*}} 'int' depth 0 index 1 ... J namespace TestTemplateTemplateParmDecl { template<typename T> class A; template <template <typename> class T = A, template <typename> class ... U> void foo(); } // CHECK: NamespaceDecl{{.*}} TestTemplateTemplateParmDecl // CHECK: FunctionTemplateDecl // CHECK-NEXT: TemplateTemplateParmDecl{{.*}} T // CHECK-NEXT: TemplateTypeParmDecl{{.*}} typename // CHECK-NEXT: TemplateArgument{{.*}} template A // CHECK-NEXT: TemplateTemplateParmDecl{{.*}} ... U // CHECK-NEXT: TemplateTypeParmDecl{{.*}} typename namespace TestTemplateArgument { template<typename> class A { }; template<template<typename> class ...> class B { }; int foo(); template<typename> class testType { }; template class testType<int>; // CHECK: ClassTemplateSpecializationDecl{{.*}} class testType // CHECK: TemplateArgument{{.*}} type 'int' template<int fp(void)> class testDecl { }; template class testDecl<foo>; // CHECK: ClassTemplateSpecializationDecl{{.*}} class testDecl // CHECK: TemplateArgument{{.*}} decl // CHECK-NEXT: Function{{.*}}foo template class testDecl<nullptr>; // CHECK: ClassTemplateSpecializationDecl{{.*}} class testDecl // CHECK: TemplateArgument{{.*}} nullptr template<int> class testIntegral { }; template class testIntegral<1>; // CHECK: ClassTemplateSpecializationDecl{{.*}} class testIntegral // CHECK: TemplateArgument{{.*}} integral 1 template<template<typename> class> class testTemplate { }; template class testTemplate<A>; // CHECK: ClassTemplateSpecializationDecl{{.*}} class testTemplate // CHECK: TemplateArgument{{.*}} A template<template<typename> class ...T> class C { B<T...> testTemplateExpansion; }; // FIXME: Need TemplateSpecializationType dumping to test TemplateExpansion. template<int, int = 0> class testExpr; template<int I> class testExpr<I> { }; // CHECK: ClassTemplatePartialSpecializationDecl{{.*}} class testExpr // CHECK: TemplateArgument{{.*}} expr // CHECK-NEXT: DeclRefExpr{{.*}}I template<int, int ...> class testPack { }; template class testPack<0, 1, 2>; // CHECK: ClassTemplateSpecializationDecl{{.*}} class testPack // CHECK: TemplateArgument{{.*}} integral 0 // CHECK-NEXT: TemplateArgument{{.*}} pack // CHECK-NEXT: TemplateArgument{{.*}} integral 1 // CHECK-NEXT: TemplateArgument{{.*}} integral 2 } namespace testUsingDecl { int i; } namespace TestUsingDecl { using testUsingDecl::i; } // CHECK: NamespaceDecl{{.*}} TestUsingDecl // CHECK-NEXT: UsingDecl{{.*}} testUsingDecl::i // CHECK-NEXT: UsingShadowDecl{{.*}} Var{{.*}} 'i' 'int' namespace testUnresolvedUsing { class A { }; template<class T> class B { public: A a; }; template<class T> class TestUnresolvedUsing : public B<T> { using typename B<T>::a; using B<T>::a; }; } // CHECK: CXXRecordDecl{{.*}} TestUnresolvedUsing // CHECK: UnresolvedUsingTypenameDecl{{.*}} B<T>::a // CHECK: UnresolvedUsingValueDecl{{.*}} B<T>::a namespace TestLinkageSpecDecl { extern "C" void test1(); extern "C++" void test2(); } // CHECK: NamespaceDecl{{.*}} TestLinkageSpecDecl // CHECK-NEXT: LinkageSpecDecl{{.*}} C // CHECK-NEXT: FunctionDecl // CHECK-NEXT: LinkageSpecDecl{{.*}} C++ // CHECK-NEXT: FunctionDecl class TestAccessSpecDecl { public: private: protected: }; // CHECK: CXXRecordDecl{{.*}} class TestAccessSpecDecl // CHECK: CXXRecordDecl{{.*}} class TestAccessSpecDecl // CHECK-NEXT: AccessSpecDecl{{.*}} public // CHECK-NEXT: AccessSpecDecl{{.*}} private // CHECK-NEXT: AccessSpecDecl{{.*}} protected template<typename T> class TestFriendDecl { friend int foo(); friend class A; friend T; }; // CHECK: CXXRecord{{.*}} TestFriendDecl // CHECK: CXXRecord{{.*}} TestFriendDecl // CHECK-NEXT: FriendDecl // CHECK-NEXT: FunctionDecl{{.*}} foo // CHECK-NEXT: FriendDecl{{.*}} 'class A':'class A' // CHECK-NEXT: FriendDecl{{.*}} 'T' namespace TestFileScopeAsmDecl { asm("ret"); } // CHECK: NamespaceDecl{{.*}} TestFileScopeAsmDecl{{$}} // CHECK: FileScopeAsmDecl{{.*> .*$}} // CHECK-NEXT: StringLiteral namespace TestFriendDecl2 { void f(); struct S { friend void f(); }; } // CHECK: NamespaceDecl [[TestFriendDecl2:0x.*]] <{{.*}}> {{.*}} TestFriendDecl2 // CHECK: |-FunctionDecl [[TestFriendDecl2_f:0x.*]] <{{.*}}> {{.*}} f 'void (void)' // CHECK: `-CXXRecordDecl {{.*}} struct S // CHECK: |-CXXRecordDecl {{.*}} struct S // CHECK: `-FriendDecl // CHECK: `-FunctionDecl {{.*}} parent [[TestFriendDecl2]] prev [[TestFriendDecl2_f]] <{{.*}}> {{.*}} f 'void (void)' namespace Comment { extern int Test; /// Something here. extern int Test; extern int Test; } // CHECK: VarDecl {{.*}} Test 'int' extern // CHECK-NOT: FullComment // CHECK: VarDecl {{.*}} Test 'int' extern // CHECK: `-FullComment // CHECK: `-ParagraphComment // CHECK: `-TextComment // CHECK: VarDecl {{.*}} Test 'int' extern // CHECK-NOT: FullComment
[ "jalopezg@inf.uc3m.es" ]
jalopezg@inf.uc3m.es
59ac289351f134ec667d5077222717aaea8e15ad
225b9a9ce807b669f5da0224b374bbf496d0bc70
/lg3402.cpp
ec94854b618165b84c6374b974c2163dc6141ae3
[]
no_license
Kewth/OJStudy
2ed55f9802d430fc65647d8931c028b974935c03
153708467133338a19d5537408750b4732d6a976
refs/heads/master
2022-08-15T06:18:48.271942
2022-07-25T02:18:20
2022-07-25T02:18:20
172,679,963
6
2
null
null
null
null
UTF-8
C++
false
false
786
cpp
#include <bits/stdc++.h> inline long long input() { long long res ; scanf("%lld",&res); return res; } int find(int x,int *fa) { if(fa[x] == x) return x; return find(fa[x] , fa); } inline void add(int x,int y,int *fa,int *deep) { x = find(x , fa); y = find(y , fa); if(deep[x] < deep[y]) fa[x] = y; else fa[y] = x; if(deep[x] == deep[y]) deep[x] ++; } bool together(int x,int y,int *fa) { x = find(x , fa); y = find(y , fa); return x == y; } int main() { int n = input() , q = input(); int *fa = new int [n + 1]; int *deep = new int [n + 1]; for(int i=1;i<=n;i++) fa[i] = i , deep[i] = 1; while(q --) { int typ = input() , x = input() , y = input(); if(typ == 1) add(x , y , fa , deep); else together(x , y , fa) ? puts("Y") : puts("N"); } }
[ "wthdsg@foxmail.com" ]
wthdsg@foxmail.com
1e86a5fc01abe16157d2bf3c0f80fda6145a6255
e61a0ebe93280719d9bb34cac52d772f0d814e5f
/hdoj1207.cpp
3c6f23988b6b6fef0fddea83639ba9c787a9e0eb
[]
no_license
zhouwangyiteng/ACM_code
ba5df2215500a1482cf21362160ddbf71be0196d
ca3e888bd4908287dd822471333a38c24b0a05db
refs/heads/master
2020-04-12T06:35:10.160246
2017-04-22T07:44:09
2017-04-22T07:44:09
61,373,600
0
0
null
null
null
null
UTF-8
C++
false
false
1,049
cpp
/************************************************************************* > File Name: hdoj1207.cpp > Author: > Mail: > Blog: > Created Time: 2016年07月30日 星期六 19时50分41秒 ************************************************************************/ #include <iostream> #include <cstdio> #include <vector> #include <map> #include <queue> #include <stack> #include <algorithm> #include <cmath> #include <ctime> #include <string> #include <cstring> #include <set> #include <bitset> using namespace std; #define X first #define Y second #define ll long long #define INF 0x3f3f3f3f #define N 66 #define PB(X) push_back(X) #define MP(X,Y) make_pair(X,Y) #define REP(x,y) for(int x=0;x<y;x++) #define RDP(x,y) for(int x=y;x>=0;x--) #define RRP(x,L,R) for(int x=L;x<=R;x++) #define CLR(A,X) memset(A,X,sizeof(A)) int n; double ans[N]; int main() { ans[1]=1; ans[2]=3; for(int i=3;i<N;i++) { ans[i]=INF; for(int j=1;j<i;j++) ans[i]=min(ans[i],2*ans[j]+pow(2,i-j)-1); } while(cin>>n) cout<<ans[n]<<endl; return 0; }
[ "zhouwang122@qq.com" ]
zhouwang122@qq.com
16fba564cabd85a3f50fedaafec5b7e5d85d48f1
22153e138bb70e4ec27f121882971bdd28df3444
/src/HuffyBool.cpp
6b6a62d9fa927c0be9854ef0dd27b5c290f51c17
[]
no_license
AndyKelly/Huffy
f9486fa097276ee253711743cbe5c19002d0eb4d
0c67f012fe69edb03cb0377ec6666b7174ca21ac
refs/heads/master
2021-01-01T16:55:19.200574
2013-01-14T08:07:01
2013-01-14T08:07:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,725
cpp
/* * HuffyBool.cpp * * Author: Andy Kelly */ #include "HuffyBool.h" #include "HuffyConstants.h" #include "HuffyManager.h" using namespace std; HuffyBool::HuffyBool(void) { m_Value = 0; } HuffyBool::HuffyBool(bool Value) { m_Value = Value; } HuffyBool::HuffyBool(bool Value, string UniqueID) { m_Value = Value; m_Sendable = true; m_UniqueID = UniqueID; HuffyManager::RegisterHuffyTypeObject(m_UniqueID, this); } HuffyBool::~HuffyBool(void) { HuffyManager::RemoveType(m_UniqueID, e_HuffyBool); } int HuffyBool::GetType(void)const { return e_HuffyBool; } void HuffyBool::SetValue(bool NewValue) { UpdateHuffyManagaer(); m_Value = NewValue; } //Gets std::string HuffyBool::GetID(void) { return m_UniqueID; } bool HuffyBool::GetValue_C(void)const { return m_Value; } bool HuffyBool::GetValue(void) { return m_Value; } bool HuffyBool::isBeingSent() { return m_Sendable; } void HuffyBool::UpdateHuffyManagaer() { if(m_Sendable) { HuffyManager::HuffyTypeModified(e_HuffyBool, m_UniqueID); } } //Operator overloads #pragma region HuffyBoolOverloads HuffyBool HuffyBool::operator=(const HuffyBool& other) { UpdateHuffyManagaer(); m_Value = other.m_Value; return *this; } bool HuffyBool::operator==(const HuffyBool& other) { return m_Value == other.m_Value; } bool HuffyBool::operator!=(const HuffyBool& other) { return m_Value != other.m_Value; } #pragma endregion #pragma region BoolOverloads HuffyBool HuffyBool::operator=(const bool& other) { UpdateHuffyManagaer(); m_Value = other; return *this; } bool HuffyBool::operator==(const bool& other) { return m_Value == other; } bool HuffyBool::operator!=(const bool& other) { return m_Value != other; } #pragma endregion
[ "andykelly@outlook.com" ]
andykelly@outlook.com
58fbb260bec723b877a9cdf354dfeae517296cad
31ff2096bcc62be7fcf929ad098c83367d8170d0
/src/net.cpp
fb92ed4a7449682340b3e71914c9092bf38b3974
[ "MIT" ]
permissive
puredev321/Decentronium
be59c538bea4d4b276789747489f3d27099b7120
b0a4faff7f4a979f9a86ba8f7b93693bc8c3b39a
refs/heads/master
2020-04-02T22:10:00.961056
2018-10-26T11:26:49
2018-10-26T11:26:49
154,823,724
3
0
null
null
null
null
UTF-8
C++
false
false
66,352
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/decentronium-config.h" #endif #include "net.h" #include "addrman.h" #include "chainparams.h" #include "clientversion.h" #include "miner.h" #include "obfuscation.h" #include "primitives/transaction.h" #include "ui_interface.h" #include "wallet.h" #ifdef WIN32 #include <string.h> #else #include <fcntl.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniupnpc.h> #include <miniupnpc/miniwget.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif #include <boost/filesystem.hpp> #include <boost/thread.hpp> // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version. #ifdef WIN32 #ifndef PROTECTION_LEVEL_UNRESTRICTED #define PROTECTION_LEVEL_UNRESTRICTED 10 #endif #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 23 #endif #endif using namespace boost; using namespace std; namespace { const int MAX_OUTBOUND_CONNECTIONS = 16; struct ListenSocket { SOCKET socket; bool whitelisted; ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {} }; } // // Global state variables // bool fDiscover = true; bool fListen = true; uint64_t nLocalServices = NODE_NETWORK; CCriticalSection cs_mapLocalHost; map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; uint64_t nLocalHostNonce = 0; static std::vector<ListenSocket> vhListenSocket; CAddrMan addrman; int nMaxConnections = 125; bool fAddressesInitialized = false; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; NodeId nLastNodeId = 0; CCriticalSection cs_nLastNodeId; static CSemaphore* semOutbound = NULL; boost::condition_variable messageHandlerCondition; // Signals for message handling static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr* paddrPeer) { if (!fListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress // Otherwise, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CAddress GetLocalAddress(const CNetAddr* paddrPeer) { CAddress ret(CService("0.0.0.0", GetListenPort()), 0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); } ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; while (true) { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed LogPrint("net", "socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr)); return false; } } } } int GetnScore(const CService& addr) { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == LOCAL_NONE) return 0; return mapLocalHost[addr].nScore; } // Is our peer's addrLocal potentially useful as an external IP source? bool IsPeerAddrLocalGood(CNode* pnode) { return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() && !IsLimited(pnode->addrLocal.GetNetwork()); } // pushes our own address to a peer void AdvertizeLocal(CNode* pnode) { if (fListen && pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8 : 2) == 0)) { addrLocal.SetIP(pnode->addrLocal); } if (addrLocal.IsRoutable()) { pnode->PushAddress(addrLocal); } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo& info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } return true; } bool AddLocal(const CNetAddr& addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr& addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given network is one we can probably connect to */ bool IsReachable(enum Network net) { LOCK(cs_mapLocalHost); return vfReachable[net] && !vfLimited[net]; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { enum Network net = addr.GetNetwork(); return IsReachable(net); } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return NULL; } CNode* FindNode(const std::string& addrName) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (Params().NetworkID() == CBaseChainParams::REGTEST) { //if using regtest, just check the IP if ((CNetAddr)pnode->addr == (CNetAddr)addr) return (pnode); } else { if (pnode->addr == addr) return (pnode); } } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool obfuScationMaster) { if (pszDest == NULL) { // we clean masternode connections in CMasternodeMan::ProcessMasternodeConnections() // so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus() if (IsLocal(addrConnect) && !obfuScationMaster) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->fObfuScationMaster = obfuScationMaster; pnode->AddRef(); return pnode; } } /// debug print LogPrint("net", "trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0); // Connect SOCKET hSocket; bool proxyConnectionFailed = false; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) { if (!IsSelectableSocket(hSocket)) { LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n"); CloseSocket(hSocket); return NULL; } addrman.Attempt(addrConnect); // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); if (obfuScationMaster) pnode->fObfuScationMaster = true; return pnode; } else if (!proxyConnectionFailed) { // If connecting to the node failed, and failure is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect); } return NULL; } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { LogPrint("net", "disconnecting peer=%d\n", id); CloseSocket(hSocket); } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); } bool CNode::DisconnectOldProtocol(int nVersionRequired, string strLastCommand) { fDisconnect = false; if (nVersion < nVersionRequired) { LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersion); PushMessage("reject", strLastCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", ActiveProtocol())); fDisconnect = true; } return fDisconnect; } void CNode::PushVersion() { int nBestHeight = g_signals.GetHeight().get_value_or(0); /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0))); CAddress addrMe = GetLocalAddress(&addr); GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); if (fLogIPs) LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id); else LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true); } std::map<CNetAddr, int64_t> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Ban(const CNetAddr& addr) { int64_t banTime = GetTime() + GetArg("-bantime", 60 * 60 * 24); // Default 24-hour ban { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } return true; } std::vector<CSubNet> CNode::vWhitelistedRange; CCriticalSection CNode::cs_vWhitelistedRange; bool CNode::IsWhitelistedRange(const CNetAddr& addr) { LOCK(cs_vWhitelistedRange); BOOST_FOREACH (const CSubNet& subnet, vWhitelistedRange) { if (subnet.Match(addr)) return true; } return false; } void CNode::AddWhitelistedRange(const CSubNet& subnet) { LOCK(cs_vWhitelistedRange); vWhitelistedRange.push_back(subnet); } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats& stats) { stats.nodeid = this->GetId(); X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(cleanSubVer); X(fInbound); X(nStartingHeight); X(nSendBytes); X(nRecvBytes); X(fWhitelisted); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (DECN users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : ""; } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) { LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId()); return false; } pch += handled; nBytes -= handled; if (msg.complete()) { msg.nTime = GetTimeMicros(); messageHandlerCondition.notify_one(); } } return true; } int CNetMessage::readHeader(const char* pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (const std::exception&) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char* pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode* pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData& data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf("socket send error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH (CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH (CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket.socket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && (pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf("socket select error %s\n", NetworkErrorString(nErr)); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec / 1000); } // // Accept new connections // BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) { if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) LogPrintf("Warning: Unknown socket family\n"); bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr); { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr)); } else if (!IsSelectableSocket(hSocket)) { LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString()); CloseSocket(hSocket); } else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) { LogPrint("net", "connection from %s dropped (full)\n", addr.ToString()); CloseSocket(hSocket); } else if (CNode::IsBanned(addr) && !whitelisted) { LogPrintf("connection from %s dropped (banned)\n", addr.ToString()); CloseSocket(hSocket); } else { CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); pnode->fWhitelisted = whitelisted; { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH (CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH (CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) LogPrint("net", "socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf("socket recv error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90 * 60)) { LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodesCopy) pnode->Release(); } } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char* multicastif = 0; const char* minissdpdpath = 0; struct UPNPDev* devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #elif MINIUPNPC_API_VERSION < 14 /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #else /* miniupnpc 1.9.20150730 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if (r != UPNPCOMMAND_SUCCESS) LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if (externalIPAddress[0]) { LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "Decentronium " + FormatFullVersion(); try { while (true) { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if (r != UPNPCOMMAND_SUCCESS) LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else LogPrintf("UPnP Port Mapping successful.\n"); ; MilliSleep(20 * 60 * 1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif void ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute if ((addrman.size() > 0) && (!GetBoolArg("-forcednsseed", false))) { MilliSleep(11 * 1000); LOCK(cs_vNodes); if (vNodes.size() >= 2) { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); return; } } const vector<CDNSSeedData>& vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); BOOST_FOREACH (const CDNSSeedData& seed, vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { vector<CNetAddr> vIPs; vector<CAddress> vAdd; if (LookupHost(seed.host.c_str(), vIPs)) { BOOST_FOREACH (CNetAddr& ip, vIPs) { int nOneDay = 24 * 3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(seed.name, true)); } } LogPrintf("%d addresses found from DNS seeds\n", found); } void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH (string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1")); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { CAddress addr = addrman.Select(); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while (true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH (string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH (string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH (string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH (string& strAddNode, lAddresses) { vector<CService> vservNode(0); if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH (CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH (CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH (vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!pszDest) { if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort())) return false; } else if (FindNode(pszDest)) return false; CNode* pnode = ConnectNode(addrConnect, pszDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } void ThreadMessageHandler() { boost::mutex condition_mutex; boost::unique_lock<boost::mutex> lock(condition_mutex); SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH (CNode* pnode, vNodesCopy) { pnode->AddRef(); } } // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; BOOST_FOREACH (CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!g_signals.ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodesCopy) pnode->Release(); } if (fSleep) messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100)); } } // ppcoin: stake minter thread void static ThreadStakeMinter() { boost::this_thread::interruption_point(); LogPrintf("ThreadStakeMinter started\n"); CWallet* pwallet = pwalletMain; try { BitcoinMiner(pwallet, true); boost::this_thread::interruption_point(); } catch (std::exception& e) { LogPrintf("ThreadStakeMinter() exception \n"); } catch (...) { LogPrintf("ThreadStakeMinter() error \n"); } LogPrintf("ThreadStakeMinter exiting,\n"); } bool BindListenPort(const CService& addrBind, string& strError, bool fWhitelisted) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString()); LogPrintf("%s\n", strError); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } if (!IsSelectableSocket(hListenSocket)) { strError = "Error: Couldn't create a listenable socket for incoming connections"; LogPrintf("%s\n", strError); return false; } #ifndef WIN32 #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows! setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif // Set to non-blocking, incoming connections will also inherit this if (!SetSocketNonBlocking(hListenSocket, true)) { strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. Decentronium is probably already running."), addrBind.ToString()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr)); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } LogPrintf("Bound to %s\n", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted)); if (addrBind.IsRoutable() && fDiscover && !fWhitelisted) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[256] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr& addr, vaddr) { if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString()); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif } void StartNode(boost::thread_group& threadGroup) { uiInterface.InitMessage(_("Loading addresses...")); // Load addresses for peers.dat int64_t nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) LogPrintf("Invalid or missing peers.dat; recreating\n"); } LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); fAddressesInitialized = true; if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(threadGroup); // // Start threads // if (!GetBoolArg("-dnsseed", true)) LogPrintf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed)); // Map ports with UPnP MapPort(GetBoolArg("-upnp", DEFAULT_UPNP)); // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); // ppcoin:mint proof-of-stake blocks in the background if (GetBoolArg("-staking", true)) threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "stakemint", &ThreadStakeMinter)); } bool StopNode() { LogPrintf("StopNode()\n"); MapPort(false); if (semOutbound) for (int i = 0; i < MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); if (fAddressesInitialized) { DumpAddresses(); fAddressesInitialized = false; } return true; } class CNetCleanup { public: CNetCleanup() {} ~CNetCleanup() { // Close sockets BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) CloseSocket(pnode->hSocket); BOOST_FOREACH (ListenSocket& hListenSocket, vhListenSocket) if (hListenSocket.socket != INVALID_SOCKET) if (!CloseSocket(hListenSocket.socket)) LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError())); // clean up some globals (to help leak detection) BOOST_FOREACH (CNode* pnode, vNodes) delete pnode; BOOST_FOREACH (CNode* pnode, vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); vhListenSocket.clear(); delete semOutbound; semOutbound = NULL; delete pnodeLocalHost; pnodeLocalHost = NULL; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void CExplicitNetCleanup::callCleanup() { // Explicit call to destructor of CNetCleanup because it's not implicitly called // when the wallet is restarted from within the wallet itself. CNetCleanup* tmp = new CNetCleanup(); delete tmp; // Stroustrup's gonna kill me for that } void RelayTransaction(const CTransaction& tx) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, ss); } void RelayTransaction(const CTransaction& tx, const CDataStream& ss) { CInv inv(MSG_TX, tx.GetHash()); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); if (pnode->pfilter) { if (pnode->pfilter->IsRelevantAndUpdate(tx)) pnode->PushInventory(inv); } else pnode->PushInventory(inv); } } void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll) { CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash()); //broadcast the new lock LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!relayToAll && !pnode->fRelayTxes) continue; pnode->PushMessage("ix", tx); } } void RelayInv(CInv& inv) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes){ if((pnode->nServices==NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType())continue; if (pnode->nVersion >= ActiveProtocol()) pnode->PushInventory(inv); } } void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } void CNode::Fuzz(int nChance) { if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages switch (GetRand(3)) { case 0: // xor a random byte with a random value: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend[pos] ^= (unsigned char)(GetRand(256)); } break; case 1: // delete a random byte: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend.erase(ssSend.begin() + pos); } break; case 2: // insert a random byte at a random position { CDataStream::size_type pos = GetRand(ssSend.size()); char ch = (char)GetRand(256); ssSend.insert(ssSend.begin() + pos, ch); } break; } // Chance of more than one change half the time: // (more changes exponentially less likely): Fuzz(2); } // // CAddrDB // CAddrDB::CAddrDB() { pathAddr = GetDataDir() / "peers.dat"; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); std::string tmpfn = strprintf("peers.dat.%04x", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open output file, and associate with CAutoFile boost::filesystem::path pathAddr = GetDataDir() / "peers.dat"; FILE* file = fopen(pathAddr.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // Write and commit header, data try { fileout << ssPeers; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } FileCommit(fileout.Get()); fileout.fclose(); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE* file = fopen(pathAddr.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathAddr); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error("%s : Checksum mismatch, data corrupted", __func__); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("%s : Invalid network magic number", __func__); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } return true; } unsigned int ReceiveFloodSize() { return 1000 * GetArg("-maxreceivebuffer", 5 * 1000); } unsigned int SendBufferSize() { return 1000 * GetArg("-maxsendbuffer", 1 * 1000); } CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000) { nServices = 0; hSocket = hSocketIn; nRecvVersion = INIT_PROTO_VERSION; nLastSend = 0; nLastRecv = 0; nSendBytes = 0; nRecvBytes = 0; nTimeConnected = GetTime(); addr = addrIn; addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = ""; fWhitelisted = false; fOneShot = false; fClient = false; // set by version message fInbound = fInboundIn; fNetworkNode = false; fSuccessfullyConnected = false; fDisconnect = false; nRefCount = 0; nSendSize = 0; nSendOffset = 0; hashContinue = 0; nStartingHeight = -1; fGetAddr = false; fRelayTxes = false; setInventoryKnown.max_size(SendBufferSize() / 1000); pfilter = new CBloomFilter(); nPingNonceSent = 0; nPingUsecStart = 0; nPingUsecTime = 0; fPingQueued = false; fObfuScationMaster = false; { LOCK(cs_nLastNodeId); id = nLastNodeId++; } if (fLogIPs) LogPrint("net", "Added connection to %s peer=%d\n", addrName, id); else LogPrint("net", "Added connection peer=%d\n", id); // Be shy and don't send version until we hear if (hSocket != INVALID_SOCKET && !fInbound) PushVersion(); GetNodeSignals().InitializeNode(GetId(), this); } CNode::~CNode() { CloseSocket(hSocket); if (pfilter) delete pfilter; GetNodeSignals().FinalizeNode(GetId()); } void CNode::AskFor(const CInv& inv) { if (mapAskFor.size() > MAPASKFOR_MAX_SZ) return; // We're using mapAskFor as a priority queue, // the key is the earliest time the request can be sent int64_t nRequestTime; limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv); if (it != mapAlreadyAskedFor.end()) nRequestTime = it->second; else nRequestTime = 0; LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime / 1000000), id); // Make sure not to reuse time indexes to keep things in the same order int64_t nNow = GetTimeMicros() - 1000000; static int64_t nLastTime; ++nLastTime; nNow = std::max(nNow, nLastTime); nLastTime = nNow; // Each retry is 2 minutes after the last nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow); if (it != mapAlreadyAskedFor.end()) mapAlreadyAskedFor.update(it, nRequestTime); else mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime)); mapAskFor.insert(std::make_pair(nRequestTime, inv)); } void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend) { ENTER_CRITICAL_SECTION(cs_vSend); assert(ssSend.size() == 0); ssSend << CMessageHeader(pszCommand, 0); LogPrint("net", "sending: %s ", SanitizeString(pszCommand)); } void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend) { ssSend.clear(); LEAVE_CRITICAL_SECTION(cs_vSend); LogPrint("net", "(aborted)\n"); } void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend) { // The -*messagestest options are intentionally not documented in the help message, // since they are only used during development to debug the networking code and are // not intended for end-users. if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) { LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n"); AbortMessage(); return; } if (mapArgs.count("-fuzzmessagestest")) Fuzz(GetArg("-fuzzmessagestest", 10)); if (ssSend.size() == 0) return; // Set the size unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE; memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize)); // Set the checksum uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end()); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); assert(ssSend.size() >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum)); memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum)); LogPrint("net", "(%d bytes) peer=%d\n", nSize, id); std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData()); ssSend.GetAndClear(*it); nSendSize += (*it).size(); // If write queue empty, attempt "optimistic write" if (it == vSendMsg.begin()) SocketSendData(this); LEAVE_CRITICAL_SECTION(cs_vSend); }
[ "puredev321@gmail.com" ]
puredev321@gmail.com
7002cdc385ab345c27679e593dfb72df3e69d413
a63e739155d5b07bb9252501b64bf0d5de275087
/Ejercicio 4/src/common/Resultado.cpp
7329329f8038be5b00c8fdebf9220128a205a73d
[]
no_license
dario-ramos/testers-distribuidos7574
677b79588aadeb547d85f5f31f6c3912828cc8e4
5a8e992960f069a80491d49d270e52c4a8b95db6
refs/heads/master
2016-09-05T21:52:37.730168
2015-03-09T16:59:22
2015-03-09T16:59:22
33,097,578
0
0
null
null
null
null
UTF-8
C++
false
false
178
cpp
/* * File: Resultado.cpp * Author: knoppix * * Created on October 4, 2014, 10:28 PM */ #include "Resultado.h" Resultado::Resultado() { } Resultado::~Resultado() { }
[ "dario.fenix@gmail.com@18dcfaaf-94c9-9b71-9433-3f00c941b258" ]
dario.fenix@gmail.com@18dcfaaf-94c9-9b71-9433-3f00c941b258
cb318f5136d99c6a2d67e0a080b0a7529f8714a0
b904263df73ce56b3c6f7e05b2bafb5abf46f21a
/gdipp_demo_render/commandline.cpp
4dc7daba3681d44d27bd540d8db4288742e1993e
[ "MIT" ]
permissive
dbautsch/gdipp-conf-editor
cc1c9fbf8dfda81a80da927b4044d0c7ce340547
817acdc9464db172782f465a44b27bfa917ef86f
refs/heads/master
2021-07-02T14:56:02.149213
2020-12-21T18:26:14
2020-12-21T18:26:14
208,060,372
0
0
null
null
null
null
UTF-8
C++
false
false
3,183
cpp
/* Copyright (c) 2019 Dawid Bautsch 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 "commandline.h" #include <iostream> #include "../gdipp-conf-editor/util.h" CommandLine::CommandLine() { ParseCommands(); } void CommandLine::ParseCommands() { LPWSTR * commandsList = NULL; int argc; commandsList = CommandLineToArgvW(GetCommandLineW(), &argc); if (commandsList == NULL) { throw std::runtime_error("Unable to obtain program arguments list."); } for (int i = 0; i < argc; ++i) { try { LPWSTR argument = commandsList[i]; std::pair<MetaString, MetaString> programArgument = SplitArgument(argument); commands.insert(programArgument); } catch (const std::exception & e) { std::cerr << e.what() << std::endl; } } LocalFree(commandsList); } MetaString CommandLine::Get(const MetaString & name) const { CommandEntities::const_iterator it = commands.find(name); if (it == commands.end()) { return MetaString(); } return it->second; } std::pair<MetaString, MetaString> CommandLine::SplitArgument(LPWSTR argument) const { std::pair<MetaString, MetaString> result; MetaString argumentStr = Util::CreateMetaString(argument); size_t equalSignPos = argumentStr.find(TEXT("=")); if (equalSignPos == MetaString::npos) { // no equal sign, key is the same as the value // this is type of `flag` argument result = std::make_pair(Unquote(argumentStr), Unquote(argumentStr)); } else { MetaString key = Unquote(argumentStr.substr(0, equalSignPos)); MetaString value = Unquote(argumentStr.substr(equalSignPos + 1, argumentStr.length() - equalSignPos - 1)); result = std::make_pair(key, value); } return result; } MetaString CommandLine::Unquote(const MetaString & text) const { if (text[0] == TEXT('\"') && text[text.length() - 1] == TEXT('\"')) { // trim quotes return text.substr(1, text.length() - 2); } return text; }
[ "dawid@bautsch.pl" ]
dawid@bautsch.pl
af588588282fb1ecdd9a6712a6fddb4e09f06a95
41a08c02f23996fb2d7aeb78764443a63eed15eb
/greeting_10_24.cc
0bc1a58321df6799de73730a8fece1d150d74b06
[]
no_license
kmad1729/acpp
b28407ab007d18126601c03a05e4386bc1ed470a
7a933fbfa714c4459cff53d3fe364759118beb12
refs/heads/master
2020-04-29T02:18:11.154932
2014-01-05T18:45:27
2014-01-05T18:45:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
918
cc
#include<iostream> #include<string> using std::cout; using std::cin; using std::string; using std::endl; int main() { cout << "Please enter your first name: "; string name; cin >> name; const string greeting = "Hi, " + name + "! How are you"; const int pad = 5; const int rows = 2 * pad + 3; string::size_type cols = greeting.size() + 2 * pad + 2; string::size_type c = 0; for(int r = 0; r < rows; r++) { for (c = 0; c < cols; c++) { //if edge of the square, print * if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) { cout << "*"; } else { //if time to write the greeting if (r == pad + 1 && c == pad + 1) { cout << greeting; c += greeting.size(); } cout << " "; } } cout << endl; } }
[ "kashyap.mad@gmail.com" ]
kashyap.mad@gmail.com
d1ce092da27c2bfc9c353926f51085895022f3d9
95dcf1b68eb966fd540767f9315c0bf55261ef75
/build/pc/Boost_1_50_0/output/include/boost-1_50/boost/mpl/multiset/aux_/item.hpp
839c338e18241851ab2c45579dcdb96031efef79
[ "BSL-1.0" ]
permissive
quinsmpang/foundations.github.com
9860f88d1227ae4efd0772b3adcf9d724075e4d1
7dcef9ae54b7e0026fd0b27b09626571c65e3435
refs/heads/master
2021-01-18T01:57:54.298696
2012-10-14T14:44:38
2012-10-14T14:44:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,661
hpp
#ifndef BOOST_MPL_MULTISET_AUX_ITEM_HPP_INCLUDED #define BOOST_MPL_MULTISET_AUX_ITEM_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: item.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 14:19:02 +0800 (星期六, 2008-10-11) $ // $Revision: 49267 $ #include <boost/mpl/multiset/aux_/tag.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/aux_/type_wrapper.hpp> #include <boost/mpl/aux_/yes_no.hpp> #include <boost/mpl/aux_/value_wknd.hpp> #include <boost/mpl/aux_/static_cast.hpp> #include <boost/mpl/aux_/config/arrays.hpp> #include <boost/mpl/aux_/config/msvc.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) # include <boost/mpl/eval_if.hpp> # include <boost/mpl/next.hpp> # include <boost/type_traits/is_same.hpp> #endif namespace boost { namespace mpl { #if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) template< typename T, typename Base > struct ms_item { typedef aux::multiset_tag tag; template< typename U > struct prior_count { enum { msvc70_wknd_ = sizeof(Base::key_count(BOOST_MPL_AUX_STATIC_CAST(U*,0))) }; typedef int_< msvc70_wknd_ > count_; typedef typename eval_if< is_same<T,U>, next<count_>, count_ >::type c_; #if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES) typedef typename aux::weighted_tag<BOOST_MPL_AUX_MSVC_VALUE_WKND(c_)::value>::type type; #else typedef char (&type)[BOOST_MPL_AUX_MSVC_VALUE_WKND(c_)::value]; #endif }; template< typename U > struct prior_ref_count { typedef U (* u_)(); enum { msvc70_wknd_ = sizeof(Base::ref_key_count(BOOST_MPL_AUX_STATIC_CAST(u_,0))) }; typedef int_< msvc70_wknd_ > count_; typedef typename eval_if< is_same<T,U>, next<count_>, count_ >::type c_; #if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES) typedef typename aux::weighted_tag<BOOST_MPL_AUX_MSVC_VALUE_WKND(c_)::value>::type type; #else typedef char (&type)[BOOST_MPL_AUX_MSVC_VALUE_WKND(c_)::value]; #endif }; template< typename U > static typename prior_count<U>::type key_count(U*); template< typename U > static typename prior_ref_count<U>::type ref_key_count(U (*)()); }; #else // BOOST_WORKAROUND(BOOST_MSVC, <= 1300) namespace aux { template< typename U, typename Base > struct prior_key_count { enum { msvc71_wknd_ = sizeof(Base::key_count(BOOST_MPL_AUX_STATIC_CAST(aux::type_wrapper<U>*,0))) }; typedef int_< msvc71_wknd_ > count_; #if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES) typedef typename aux::weighted_tag< BOOST_MPL_AUX_VALUE_WKND(count_)::value >::type type; #else typedef char (&type)[count_::value]; #endif }; } template< typename T, typename Base > struct ms_item { typedef aux::multiset_tag tag; enum { msvc71_wknd_ = sizeof(Base::key_count(BOOST_MPL_AUX_STATIC_CAST(aux::type_wrapper<T>*,0))) + 1 }; typedef int_< msvc71_wknd_ > count_; #if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES) static typename aux::weighted_tag< BOOST_MPL_AUX_VALUE_WKND(count_)::value >::type key_count(aux::type_wrapper<T>*); #else static char (& key_count(aux::type_wrapper<T>*) )[count_::value]; #endif template< typename U > static typename aux::prior_key_count<U,Base>::type key_count(aux::type_wrapper<U>*); }; #endif // BOOST_WORKAROUND(BOOST_MSVC, <= 1300) }} #endif // BOOST_MPL_MULTISET_AUX_ITEM_HPP_INCLUDED
[ "wisbyme@yahoo.com" ]
wisbyme@yahoo.com
bc9d8bba86d16f2e545ac32ae3f79fe75999a993
85fcd407df2eb50ea6e015580986f950882f9fd4
/basics/Arrays/sortInLinearTime.cpp
0cf4cc6133c6ecf1846f1152302256f9f8e07e82
[]
no_license
naveen700/CodingPractice
ff26c3901b8721cb0c6de32f8df246b999893471
d4f7c756974a5eee16c79e8d98f86b546260aa6d
refs/heads/master
2021-01-16T02:19:27.387955
2020-04-26T17:41:08
2020-04-26T17:41:08
242,941,499
0
0
null
null
null
null
UTF-8
C++
false
false
708
cpp
#include <iostream> using namespace std; void sortInLinearTime(int [],int); int main(){ int len; cin>>len; int arr[len]; for(int i=0; i<len;i++){ cin>>arr[i]; } sortInLinearTime(arr,len); } void sortInLinearTime(int arr[] , int len){ int a=0, b=0 ,c=0; // to count no of zeroes ,ones, twos for(int i =0; i <len;i++){ if(arr[i] == 0){ a++; }else if(arr[i] == 1){ b++; }else{ c++; } } //print array for(int i=0; i<a;i++){ cout<<"0"<<endl; } for(int i=0; i<b;i++){ cout<<"1"<<endl; } for(int i=0; i<c;i++){ cout<<"2"<<endl; } }
[ "naveenrana921@gmail.com" ]
naveenrana921@gmail.com
d26dd617bf6912fea72dde546fbc6ceb92c4a240
2ca167503b276a48f232c9c179ec43f2214194e9
/InvokeTarget1/src/main.cpp
d64df089e13d910663e0e025199451796302ce87
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
ProLove365/Cascades-Community-Samples
6f3f81bfdc61ec57b4d0218d2c1ed5b2f59ee53c
4d723d37e5bf61df13a8fa7740acbdd1e422d230
refs/heads/master
2020-12-25T12:40:02.333653
2012-10-24T09:42:53
2012-10-24T09:42:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,467
cpp
/* Copyright (c) 2012 Research In Motion Limited. * * 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 "app.hpp" #include <bb/cascades/Application> #include <QLocale> #include <QTranslator> using ::bb::cascades::Application; int main(int argc, char **argv) { //-- this is where the server is started etc Application app(argc, argv); //-- localization support QTranslator translator; QString locale_string = QLocale().name(); QString filename = QString( "InvokeTarget_%1" ).arg( locale_string ); if (translator.load(filename, "app/native/qm")) { app.installTranslator( &translator ); } App mainApp; //-- we complete the transaction started in the app constructor and start the client event loop here return Application::exec(); //-- when loop is exited the Application deletes the scene which deletes all its children (per qt rules for children) }
[ "shaque@rim.com" ]
shaque@rim.com
53c1437ebeffabefd1dbb751de8387ba09f7ad1e
b9197c03b0abf40b71d60e707a05588d99511a51
/SOS.ino
742b155a646502d9b6de4c422781b71d4462e38c
[]
no_license
PirateGuy97/Arduino-SOS
d7744ced37c40792ce3e1f2fbf69a39969f7a52f
c3e71bd121a392f353213f17812c7ddb4c7e62b7
refs/heads/master
2020-06-20T00:05:44.643332
2019-07-15T04:09:10
2019-07-15T04:09:10
196,921,847
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
ino
void setup() { // put your setup code here, to run once: pinMode(LED_BUILTIN, OUTPUT); } void loop() { // put your main code here, to run repeatedly: // "S" digitalWrite(LED_BUILTIN, HIGH); delay(500); digitalWrite(LED_BUILTIN, LOW); delay(1000); digitalWrite(LED_BUILTIN, HIGH); delay(500); digitalWrite(LED_BUILTIN, LOW); delay(1000); digitalWrite(LED_BUILTIN, HIGH); delay(500); digitalWrite(LED_BUILTIN, LOW); delay(1500); // "O" digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(1000); digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(1000); digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(1500); // "S" digitalWrite(LED_BUILTIN, HIGH); delay(500); digitalWrite(LED_BUILTIN, LOW); delay(1000); digitalWrite(LED_BUILTIN, HIGH); delay(500); digitalWrite(LED_BUILTIN, LOW); delay(1000); digitalWrite(LED_BUILTIN, HIGH); delay(500); digitalWrite(LED_BUILTIN, LOW); delay(3000); }
[ "noreply@github.com" ]
PirateGuy97.noreply@github.com
02b5584684acbb23a3b18f28881499a34f68303a
1dae79fb96f0dbbd03104eac106285e1aef88197
/TI/Lab_2/UnitIDEA.h
a261e0fc89b5b2629e1f36f9345591e9effe2512
[ "Apache-2.0" ]
permissive
ilyacoding/bsuir
781e8f126d1f7d2db402b9d8083d1f4bcdcc6f4e
c1a09b63d5d66a3dc0f4545589608a18d1b5d9c9
refs/heads/master
2021-05-15T04:23:26.430221
2019-05-29T04:06:12
2019-05-29T04:06:12
75,403,020
0
0
Apache-2.0
2021-04-21T19:34:52
2016-12-02T14:35:01
Objective-C
UTF-8
C++
false
false
1,903
h
//--------------------------------------------------------------------------- #ifndef UnitIDEAH #define UnitIDEAH //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.WinXCtrls.hpp> #include <Vcl.ComCtrls.hpp> #include <Vcl.ToolWin.hpp> #include <Vcl.Menus.hpp> #include <Vcl.Dialogs.hpp> #include <Vcl.Samples.Spin.hpp> //--------------------------------------------------------------------------- class TFormIDEA : public TForm { __published: // IDE-managed Components TMemo *MemoEncKey; TMemo *MemoEncBlock; TMemo *MemoDecKey; TMemo *MemoDecBlock; TMainMenu *MainMenu1; TMenuItem *N3; TMenuItem *File1; TMenuItem *About1; TMenuItem *N1; TMenuItem *Create1; TMenuItem *Load1; TMenuItem *Select1; TMenuItem *N4; TMenuItem *N2; TMenuItem *N5; TEdit *EditKeyID; TLabel *LabelKey; TLabel *LabelKeyID; TToggleSwitch *ToggleSwitchKey; TOpenDialog *OpenDialogFile; TButton *ButtonSelectFile; TLabel *LabelFileName; TButton *ButtonEncrypt; TButton *ButtonDecrypt; TLabel *LabelNameExpKey; TLabel *LabelNameInvKey; TLabel *LabelEncBlock; TLabel *LabelDecBlock; void __fastcall FormCreate(TObject *Sender); void __fastcall Create1Click(TObject *Sender); void __fastcall EditKeyIDChange(TObject *Sender); void __fastcall ToggleSwitchKeyClick(TObject *Sender); void __fastcall ButtonSelectFileClick(TObject *Sender); void __fastcall ButtonEncryptClick(TObject *Sender); void __fastcall ButtonDecryptClick(TObject *Sender); private: // User declarations public: // User declarations __fastcall TFormIDEA(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TFormIDEA *FormIDEA; //--------------------------------------------------------------------------- #endif
[ "ilyacoding@yandex.com" ]
ilyacoding@yandex.com
e4592f4e8d5aae51a2be0ce2fa1da93e289dbf24
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/AggregateRedundancyComponent/UNIX_AggregateRedundancyComponent_LINUX.hxx
5d385a4adc902a9e9a28dbb4cd8fe37a866e560c
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
1,841
hxx
//%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. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifdef PEGASUS_OS_LINUX #ifndef __UNIX_AGGREGATEREDUNDANCYCOMPONENT_PRIVATE_H #define __UNIX_AGGREGATEREDUNDANCYCOMPONENT_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
55cac0b1df59f2c448c66ef59d722c32cd545e58
2a6a078d0073cfc78429f1f96370bac32bb5bd38
/src/node.h
effd6b13ce3c3bb313049a9834ebfc19053b9d18
[]
no_license
dieu-detruit/onnx2c
0466386ad96ab4eab6c1ecd231e83dee2ebb9acc
97e8d3913253e349b103c4dbdff30552d4137be0
refs/heads/master
2023-04-06T20:59:09.383733
2021-03-28T14:03:45
2021-03-31T19:39:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,089
h
#pragma once #include <string> #include "error.h" #include "onnx.pb.h" #include "util.h" namespace toC { class Tensor; /* The ONNX node, or computation kernel. * * Node is a virtual parent class for each of the * ONNX node "types" or "operands" (e.g. Add, Relu, ...) * Each individual node in the graph is then an instance of * these subclasses. */ class Node { public: bool isResolved; const onnx::NodeProto *onnx_node; std::string onnx_name; //ONNX name of the individual node std::string op_name; //ONNX name of node type static int64_t onnx_ir_version; /* Create the C source name. Replace all non a-z,A-Z,0-9 or _ * characters. Also prefix name since ONNX allows tensors and nodes * to have the same name */ std::string c_name(void) const { return "node_" + cify_name(onnx_name); } /* Print the C implmementation of the operator */ virtual void print(std::ostream &destination) const = 0; /* Print comma-separated list of function parameters. * Unused optional tensors skipped. e.g.: * "tensior_X, tensor_Y" * or decorated * "float tensor_X[1][2][3], float tensor_Y[2][3][4]" */ virtual void print_parameters(std::ostream &destination, bool decorate ) const = 0; /* Figure out in what format the output is in. * Return values are pointers to Tensor values, allocated with new. Ownership given to caller. * This function may not fail: call only with all inputs given & resolved */ virtual void resolveOutput(const std::vector< const Tensor*> &inputs, std::vector<Tensor *> &outputs) = 0; /* Check if an optional output is used in the network. * N is Nth output specified in the Operator.md specification for this node. * Start counting N from 0. */ bool is_output_N_used(unsigned N); /* Not all node types have attributes. Override where needed */ virtual void parseAttributes( onnx::NodeProto &node ) { ERROR("Attribute parsing not implemented for node operation type " << op_name); } /* TODO: these should be part of class Tensor... */ /* Check input constraints, as used in * https://github.com/onnx/onnx/blob/master/docs/Operators.md */ /* (u)int32, (u)int64, float16/32/64, bfloat*/ bool typeConstraint_highPrecisionNumeric(const Tensor *t) const; /* float16/32/64, bfloat */ bool typeConstraint_allFloatingPoints(const Tensor *t) const; /* float16/32/64, (not bfloat!) */ bool typeConstraint_plainFloatingPoints(const Tensor *t) const; bool typeConstraint_int64(const Tensor *t) const; /* int8 or uint8 */ bool typeConstraint_8bit(const Tensor *t) const; /* any integer, signed or not */ bool typeConstraint_integers(const Tensor *t) const; /* only unsigned integers */ bool typeConstraint_unsigned_integers(const Tensor *t) const; /* only signed integers */ bool typeConstraint_signed_integers(const Tensor *t) const; /* Do Multidirectional Broadcasting dimension extensions: * https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md */ void multidirectional_broadcast_size( const std::vector<int> A, const std::vector<int> B, std::vector<int> &result) const; }; }
[ "kraiskil@iki.fi" ]
kraiskil@iki.fi
33bf8fa0e925509c71891a6eeb87339bcf66a4fc
839aa2696f888cbe966f94614e11d8962cc27c74
/utils/cpp/point_score.cpp
a535b6d27bebc000b921c32a0563220908743913
[]
no_license
jiehanzheng/rpi_intercom
dfb254ecd42b12252c099ad036691982f1073931
5ec9109504f78afc8b30c26cc83d518a91967dc5
refs/heads/master
2016-09-08T01:29:46.455086
2013-02-22T06:48:06
2013-02-22T06:48:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
468
cpp
#include <math.h> score_info point_score(double x1, double y1, double x2, double y2) { double dx = std::abs(x1-x2); double y_ratio = y1/y2; double y_margin = pow(std::max(y1,y2),2.2)/1000000; double x_comp = pow((0.015*dx),4); double y_comp = pow(std::max((double)0,abs(y_ratio-1)-y_margin),(double)5); double point_weight = y_margin+1; score_info result = {(1/(x_comp+y_comp+1))*point_weight, point_weight}; return result; }
[ "zheng@jiehan.org" ]
zheng@jiehan.org
cb1164868c280c40ce464048f09bf6512ff8cc4f
f0c9b902901b2e70c004e24e07f6a30defa9f84a
/src/World/World.cpp
5fbfc72ecbbc1b0e65be701737d399b6e4bf1c1e
[]
no_license
lorenzofman/ComputerGraphicsTC
4f45a19356bec91da523e204e0436f8bf8af568e
a79ad136c3b26db212869b02561c18437ab11b3b
refs/heads/master
2022-06-02T14:55:18.850485
2020-05-05T16:52:22
2020-05-05T16:52:22
257,919,061
0
0
null
null
null
null
UTF-8
C++
false
false
844
cpp
#include "World.h" World::World() { EventSystem::UpdateCallback.Register([this] {this->OnUpdate(); }); EventSystem::KeyDownCallback.Register([this] (int key) {this->OnKeyDown(key); }); bezier = new BezierCurve(); } void World::OnUpdate() { Canvas2D::ClearScreen(Colors::Background); bezier->Render(); DisplayFramesPerSeconds(); } void World::DisplayFramesPerSeconds() { int fps = (int) (1.0 / EventSystem::LastFrameDuration); char* str = new char[11]; sprintf(str, "%i", fps); Canvas2D::DrawText(Float2::Zero, str); } void World::OnKeyDown(int key) { switch (key) { case ' ': { bezier->StartAnimation(); break; } case 'c': { bezier->SetDrawConstructionGraph(); break; } case 'f': { bezier->SetDrawBlendingFunctions(); break; } case 'g': { bezier->SetDrawControlGraph(); break; } default: break; } }
[ "lorenzofman@gmail.com" ]
lorenzofman@gmail.com
eb1955d5768754226c535e1f1fe360f376e88e7e
4051dc0d87d36c889aefb2864ebe32cd21e9d949
/practice/Level_order_non_recursive.cpp
19bbb674602a60cb3aba6abcb765d893905ac265
[]
no_license
adityax10/ProgrammingCodes
e239971db7f3c4de9f2b060434a073932925ba4d
8c9bb45e1a2a82f76b66f375607c65037343dcd9
refs/heads/master
2021-01-22T22:53:01.382230
2014-11-07T10:35:00
2014-11-07T10:35:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
#include<bits/stdc++.h> using namespace std; class node { public: int data; node *l,*r; node(int data) { this->data = data; l=r=0; } }; void levelorder(node *t) { queue<node*> v; v.push(t); while(!v.empty()) { t = v.front(); v.pop(); cout<<t->data<<" "; if(t->l) v.push(t->l); if(t->r) v.push(t->r); } } int main() { node *t; t = new node(1); t->l = new node(2); t->r = new node(3); t->l->l = new node(4); t->l->r = new node(5); t->r->l = new node(6); t->r->r = new node(7); levelorder(t); return 0; }
[ "androidaditya@gmail.com" ]
androidaditya@gmail.com
f2e39736ddeea4453e1404016a9c9cb0be23245c
a78390c58814a59998f330adab061c7f7678725e
/sources/srm/src/include/BaseSRF.h
3a832bfd854636bfc0b240eaa58f27142c155e1c
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Geo4Win/sedris-dynamic
d632c3c496bdd111b8cb27d69de359cd7cc7c420
cfb3b2f1605221bb1cfd86c8315ff0ca740767b8
refs/heads/master
2021-07-06T16:47:05.668696
2017-10-02T04:55:03
2017-10-02T04:55:03
105,417,233
0
1
null
null
null
null
UTF-8
C++
false
false
61,355
h
/** @file BaseSRF.h @author Warren Macchi, David Shen @brief Declaration of SRF base classes and includes of concrete SRF classes. */ // SRM SDK Release 4.1.4 - July 1, 2011 // - SRM spec. 4.1 /* * NOTICE * * This software is provided openly and freely for use in representing and * interchanging environmental data & databases. * * This software was developed for use by the United States Government with * unlimited rights. The software was developed under contract * DASG60-02-D-0006 TO-193 by Science Applications International Corporation. * The software is unclassified and is deemed as Distribution A, approved * for Public Release. * * Use by others is permitted only upon the ACCEPTANCE OF THE TERMS AND * CONDITIONS, AS STIPULATED UNDER THE FOLLOWING PROVISIONS: * * 1. Recipient may make unlimited copies of this software and give * copies to other persons or entities as long as the copies contain * this NOTICE, and as long as the same copyright notices that * appear on, or in, this software remain. * * 2. Trademarks. All trademarks belong to their respective trademark * holders. Third-Party applications/software/information are * copyrighted by their respective owners. * * 3. Recipient agrees to forfeit all intellectual property and * ownership rights for any version created from the modification * or adaptation of this software, including versions created from * the translation and/or reverse engineering of the software design. * * 4. Transfer. Recipient may not sell, rent, lease, or sublicense * this software. Recipient may, however enable another person * or entity the rights to use this software, provided that this * AGREEMENT and NOTICE is furnished along with the software and * /or software system utilizing this software. * * All revisions, modifications, created by the Recipient, to this * software and/or related technical data shall be forwarded by the * Recipient to the Government at the following address: * * SMDC * Attention SEDRIS (TO193) TPOC * P.O. Box 1500 * Huntsville, AL 35807-3801 * * or via electronic mail to: se-mgmt@sedris.org * * 5. No Warranty. This software is being delivered to you AS IS * and there is no warranty, EXPRESS or IMPLIED, as to its use * or performance. * * The RECIPIENT ASSUMES ALL RISKS, KNOWN AND UNKNOWN, OF USING * THIS SOFTWARE. The DEVELOPER EXPRESSLY DISCLAIMS, and the * RECIPIENT WAIVES, ANY and ALL PERFORMANCE OR RESULTS YOU MAY * OBTAIN BY USING THIS SOFTWARE OR DOCUMENTATION. THERE IS * NO WARRANTY, EXPRESS OR, IMPLIED, AS TO NON-INFRINGEMENT OF * THIRD PARTY RIGHTS, MERCHANTABILITY, OR FITNESS FOR ANY * PARTICULAR PURPOSE. IN NO EVENT WILL THE DEVELOPER, THE * UNITED STATES GOVERNMENT OR ANYONE ELSE ASSOCIATED WITH THE * DEVELOPMENT OF THIS SOFTWARE BE HELD LIABLE FOR ANY CONSEQUENTIAL, * INCIDENTAL OR SPECIAL DAMAGES, INCLUDING ANY LOST PROFITS * OR LOST SAVINGS WHATSOEVER. */ // $Id: BaseSRF.h,v 1.40.1.17 2009-11-05 16:17:06-05 worleym Exp $ /** @mainpage Spatial Reference Model (SRM) C++ API @section Introduction This is the documentation for the SRM C++ API. The SRM classes provide the following functionality: - Creation - SRFs - SRF templates (e.g., LSR 3D, TM, Celestiodetic, Celestiocentric) - SRF set members (e.g., UTM zone 12, GTRS GCS cell 1234, UPS northern pole) - SRFs (e.g., British National Grid Airy) - Coordinates - 2D coordinate - 3D coordinate - Surface coordinate - Directions - Orientations - Conversion - Coordinate conversion between SRFs - Direction conversion between SRFs - Orientation conversion between SRFs - Validation - Coordinate validation within a SRF - Direction validation within a SRF - Orientation validation within a SRF - Calculations - Euclidean distance - Geodesic distance - Point scale - Vertical separation offset - Convergence of the Meridian - Map azimuth A sample program to convert a Celestiodetic 3D coordinate to a Celestiocentric 3D coordinate is as follows: @code #include "BaseSRF.h" #include "srf_all.h" #include "Exception.h" #include <iostream> using namespace std; int main (int argc, char* argv[]) { cout << "Running SRM Sample test program... \n" << endl; srm::SRF_Celestiocentric* CC_SRF; srm::SRF_Celestiodetic* CD_SRF; try { // create CC and CD SRFs CC_SRF = srm::SRF_Celestiocentric::create( SRM_ORMCOD_WGS_1984, SRM_RTCOD_WGS_1984_IDENTITY ); CD_SRF = srm::SRF_Celestiodetic::create( SRM_ORMCOD_WGS_1984, SRM_RTCOD_WGS_1984_IDENTITY ); cout << "Source Celestiodetic SRF parameters: " << endl; cout << CD_SRF->toString() << endl; cout << "Target Celestiocentric SRF parameters: " << endl; cout << CC_SRF->toString() << endl; } catch ( srm::Exception( ex) ) { cout << "Caught an exception=> " << ex.getWhat() << endl; return 0; } // create CD and CC 3D coordinate srm::Coord3D_Celestiodetic CD_Coord( CD_SRF, 0.0, 0.785398163397, 0.0 ); srm::Coord3D_Celestiocentric CC_Coord( CC_SRF ); // Convert from CD SRF to CC SRF try { CC_SRF->changeCoordinate3DSRF( CD_Coord, CC_Coord ); cout << "Executed changeCoordinate3DSRF" << endl; } catch ( srm::Exception& ex) { cout << "Caught an exception=> " << ex.getWhat() << endl; return 0; } // Print Celestiocentric coordinate values cout << "Source Celestiodetic 3D coordinate: " << "[ " << CD_Coord.get_longitude() << ", " << CD_Coord.get_latitude() << ", " << CD_Coord.get_ellipsoidal_height() << " ]" << endl; cout << "Target (converted) Celestiocentric 3D coordinate: " << "[ " << CC_Coord.get_u() << ", " << CC_Coord.get_v() << ", " << CC_Coord.get_w() << " ]" << endl << endl; // Free SRFs CC_SRF->release(); cout << "Released CC SRF" << endl; CD_SRF->release(); cout << "Released CD SRF" << endl; return 0; } @endcode Running the sample program above will produce output as follows: @verbatim Running SRM Sample test program... Source Celestiodetic SRF parameters: orm=> 250 rt=> 341 Target Celestiocentric SRF parameters: orm=> 250 rt=> 341 Executed changeCoordinate3DSRF Source Celestiodetic 3D coordinate: [ 0, 0.785398, 0 ] Target (converted) Celestiocentric 3D coordinate: [ 4.51759e+06, -8.24624e-08, 4.48735e+06 ] Released CC SRF Released CD SRF @endverbatim */ #ifndef _BaseSRF_h #define _BaseSRF_h #if !defined(_WIN32) #define EXPORT_SRM_CPP_DLL #elif defined(BUILD_SRM_CPP) /* SRM CPP Case */ #if !defined(EXPORT_SRM_CPP_DLL) #if defined(_LIB) #define EXPORT_SRM_CPP_DLL #elif defined(_USRDLL) #define EXPORT_SRM_CPP_DLL __declspec(dllexport) #else #define EXPORT_SRM_CPP_DLL __declspec(dllimport) #endif #endif #else /* SRM C Case */ #define EXPORT_SRM_CPP_DLL #endif /* _WIN32 && EXPORT_DLL */ #include "srm_types.h" // global variable - controls whether SRF cache is used to speed // up coordinate conversion operations extern bool g_fast_mode; namespace srm { /// Forward referencing class Coord; class Coord2D; class CoordSurf; class Coord3D; class Direction; class Orientation; class SRF_LocalTangentSpaceEuclidean; /// Type for an array of two long float numbers typedef SRM_Long_Float SRM_Vector_2D[2]; typedef SRM_Vector_2D Vector2; typedef SRM_Vector_3D Vector3; typedef SRM_Matrix_3x3 Matrix3x3; /** The BaseSRF abstract class is the base class for all SRFs. SRFs are allocated by the API, and when no longer needed they should be released by calling the release() method. @author Warren Macchi, David Shen @see BaseSRF_2D, BaseSRF_3D */ class EXPORT_SRM_CPP_DLL BaseSRF { public: /// The type of an SRF enum SRF_ClassType { SRF_TYP_TWO_D, SRF_TYP_THREE_D, SRF_TYP_WITH_TANGENT_PLANE_SURFACE, SRF_TYP_WITH_ELLIPSOIDAL_HEIGHT, SRF_TYP_MAP_PROJECTION, SRF_TYP_LSA, SRF_TYP_CC, SRF_TYP_CD, SRF_TYP_CM, SRF_TYP_EC, SRF_TYP_EI, SRF_TYP_HAEC, SRF_TYP_HEEC, SRF_TYP_HEEQ, SRF_TYP_LCC, SRF_TYP_LCE_3D, SRF_TYP_LSR_2D, SRF_TYP_LSR_3D, SRF_TYP_LTSAS, SRF_TYP_LTSC, SRF_TYP_LTSE, SRF_TYP_M, SRF_TYP_OMS, SRF_TYP_PD, SRF_TYP_LSP, SRF_TYP_PS, SRF_TYP_SEC, SRF_TYP_SEQ, SRF_TYP_SME, SRF_TYP_SMD, SRF_TYP_TM }; /** Creates a Standard SRF from its SRF code. @note An SRF can be directly created from: <ol> <li>an SRF code and an RT code for a standard SRF (see createStandardSRF()),</li> <li>an SRF set code info and an RT code (see createSRFSetMember()), or</li> <li>a concrete template-based SRF class (see the concrete SRF classes).</li> </ol> @note The returned SRF should be freed by calling its release() method. @param srf_code in: the code for a standard SRF to create @param rt_code in: the RT code to use in the created SRF @return a pointer to an SRF if successful @exception This method throws srm::Exception */ static BaseSRF *createStandardSRF( SRM_SRF_Code srf_code, SRM_RT_Code rt_code ); /** Creates an SRF from a SRF set code, a set member code specific to that set, and an ORM code. @note An SRF can be directly created from: <ol> <li>an SRF code and an RT code for a standard SRF (see createStandardSRF()),</li> <li>an SRF set code info and an RT code (see createSRFSetMember()), or</li> <li>a concrete template-based SRF class (see the concrete SRF classes).</li> </ol> @note The returned SRF should be freed by calling its release() method. @param srfs_info in: the set code, member code and orm code. @param rt in: the RT code to use in the created SRF @return a pointer to an SRF set member if successful @exception This method throws srm::Exception */ static BaseSRF *createSRFSetMember( SRM_SRFS_Info srfs_info, SRM_RT_Code rt ); /** Releases the pointer to the SRF. SRF classes are reference counted, since coordinates maintain a reference to them. When all references to an SRF are released, the SRF's memory is deleted. @note If you need to store multiple pointers to an SRF, you should use the clone() method to obtain each pointer, and then call the release() method for each pointer when they are no longer needed. @exception This method throws srm::Exception @see clone() */ virtual void release(); /** Returns the codes that identify this class. An SRF can be directly created from: <ol> <li>an SRF code for a standard SRF (see createStandardSRF()),</li> <li>an SRF set code and a set member code (see createSRFSetMember()), or</li> <li>a concrete template-based SRF class (see the concrete SRF classes).</li> </ol> All SRFs are intrinsically created from a template, hence the appropriate template code will always be returned from this method. However, if the SRF was created by either of 1) or 2) above, then this method allows you to retrieve the codes used to create it. If a code is not applicable, its value will be set to 0. @param t_code out: the SRF Template code @param srf_code out: the standard SRF code. It returns SRM_SRFCOD_UNSPECIFIED (0) if not created using a Standard SRF Code @param srfs_code_info out: the SRF Set and its Member code. It returns SRM_SRFSCOD_UNSPECIFIED (0) if not created using a SRFS Code */ virtual void getCodes( SRM_SRFT_Code &t_code, SRM_SRF_Code &srf_code, SRM_SRFS_Code_Info &srfs_code_info ) const; /** Returns the CS code. @return a CS code */ virtual SRM_CS_Code getCSCode() const; /** Returns this SRF's Object Reference Model code. @return an ORM code @note This method is deprecated. Use getOrm() method. */ virtual SRM_ORM_Code get_orm() const; /** Returns this SRF's Object Reference Model code. @return an ORM code */ virtual SRM_ORM_Code getOrm() const; /** Returns this SRF's RT code. @return an RT code @note This method is deprecated. Use getRt() method. */ virtual SRM_RT_Code get_rt() const; /** Returns this SRF's RT code. @return an RT code */ virtual SRM_RT_Code getRt() const; /** Returns this SRF's major semi-axis value (a). @return a major semi-axis value */ virtual SRM_Long_Float getA() const; /** Returns this SRF's flattening value (f). @return a flattening value */ virtual SRM_Long_Float getF() const; /** Queries for the SRFT support by the implementation. @param srft_code in: the SRF Template code. @return true if the SRFT is supported by this implementation. @exception This method throws srm::Exception */ static bool querySRFTSupport( SRM_SRFT_Code srft_code ); /** Queries for the ORM/RT pair support by the implementation. @param orm_code in: the object reference model code. @param rt_code in: the reference transformation code. @return true if the ORM/RT pair is supported by this implementation. @exception This method throws srm::Exception @note Not all the supported SRFTs is compatible with all the supported ORM/RT pairs. */ static bool queryORMSupport( SRM_ORM_Code orm_code, SRM_RT_Code rt_code ); /** Returns the class type of this SRF instance. You can use the return value of this method to cast a pointer to an SRF to its concrete template-based class. @return an SRF template code */ virtual SRF_ClassType getClassType() const = 0; /** Returns true if this SRF is of the given class type */ virtual bool isA( SRF_ClassType type ) const; /** Changes a coordinate's values to this SRF. @note The destination coordinate must have been created using this SRF. @param src_coord in: the source coordinate in some other SRF @param des_coord out: the destination coordinate in this SRF @return validity code for the destination coordinate @exception This method throws srm::Exception @note The source and destination coordinatesmust be of the same base coordinate class. They have to be both Coord3D, Coord2D, or CoordSurf. @note The conversion from one surface coordinate to another is a convenience function equivalent to promoting the source surface coordinate to a 3D coordinate, performing the conversion, then deriving the destination surface coordinate from the resulting destination 3D coordinate. */ virtual SRM_Coordinate_Valid_Region changeCoordinateSRF( const Coord &src_coord, Coord &des_coord ); /** Checks a coordinate in this SRF for valid region. @param src in: the coodinate in this SRF @return validity code for the coordinate @exception This method throws srm::Exception */ virtual SRM_Coordinate_Valid_Region checkCoordinate( const Coord &src ); /** Frees a coordinate in this SRF. @exception This method throws srm::Exception */ virtual void freeCoordinate( Coord *coord ); /** Returns the euclidean distance (in metres) between two coordinates. @exception This method throws srm::Exception @note The input coordinates must be of the same dimension. @note The input coordinates can be created from any SRF. */ static SRM_Long_Float calculateEuclideanDistance( const Coord &coord1, const Coord &coord2 ); /** Sets the coordinate validation ON for the changeCoordinateSRF method @note The coordinate validation is ON by default. @note Users should not set the validation OFF unless the coordinates are known to be ALWAYS valid. */ void setCoordinateValidationOn(); /** Sets the coordinate validation OFF for the changeCoordinateSRF method @note The coordinate validation is ON by default. @note Users should not set the validation OFF unless the coordinates are known to be ALWAYS valid. */ void setCoordinateValidationOff(); /** Returns true is the coordinate validation is ON */ bool coordinateValidationIsOn(); /** Returns a string representation of this SRF. */ virtual const char *toString() = 0; /** Returns a new reference to this SRF. @see release() @return a new pointer to this SRF */ virtual BaseSRF *clone(); /** Returns the creation identifier of this SRF. @return the id */ SRM_Integer getId() const { return _id; } protected: friend class Coord3D; friend class BaseSRF_3D; friend class BaseSRF_2D; friend class BaseSRF_MapProjection; friend class BaseSRF_WithEllipsoidalHeight; friend class BaseSRF_WithTangentPlaneSurface; BaseSRF( void *impl ); ///< No stack allocation BaseSRF &operator =( const BaseSRF & ) { return *this; } ///< No copy constructor virtual ~BaseSRF() {} ///< Use release() /// Reference counting unsigned int _ref_cnt; /// ID for SRF creation identification SRM_Integer _id; /// Implementation data void *_impl, *_cache; bool _validate_coords; void *getImpl() const { return _impl; } }; inline BaseSRF *BaseSRF::clone() { ++_ref_cnt; return this; } inline bool BaseSRF::isA( SRF_ClassType type ) const { return false; } /** The BaseSRF_2D abstract class is the base class for the 2D SRFs. SRFs are allocated by the API, and when no longer needed they should be released by calling the release() method. @author Warren Macchi, David Shen @see BaseSRF, BaseSRF_3D */ class EXPORT_SRM_CPP_DLL BaseSRF_2D : public BaseSRF { public: /** Returns true if this SRF is of the given class type */ virtual bool isA( SRF_ClassType type ) const; /** Creates a 2D coordinate object. @see freeCoordinate2D() @return a 2D coordinate object */ virtual Coord2D *createCoordinate2D( SRM_Long_Float coord_comp1, SRM_Long_Float coord_comp2 ) = 0; /** Retrieves the 2D coordinate component values. @exception This method throws srm::Exception */ virtual void getCoordinate2DValues( const Coord2D &coord, SRM_Long_Float &coord_comp1, SRM_Long_Float &coord_comp2 ) const; /** Frees a 2D coordinate object. @exception This method throws srm::Exception */ virtual void freeCoordinate2D( Coord2D *coord ); /** Changes a coordinate's values to this SRF. @note The destination coordinate must have been created using this SRF. @param src_coord in: the source coordinate in some other SRF @param des_coord out: the destination coordinate in this SRF @exception This method throws srm::Exception */ virtual void changeCoordinate2DSRF( const Coord2D &src_coord, Coord2D &des_coord ); /** Changes an array of coordinate values to this SRF. @note The destination coordinates must have been created using this SRF. @note The source and destination arrays must be of same size. @note All the coordinates in an array must be associated with the same SRF. @note When an exception is raised, the index parameter is set to the offending coordinate. @param src_coord_array in: the array of source coordinates in some other SRF @param index in/out: (in) the array length/ (out) the array index of the offending coordinate @param des_coord_array out: the array of destination coordinates in this SRF @exception This method throws srm::Exception */ virtual void changeCoordinate2DArraySRF( Coord2D **src_coord_array, SRM_Integer_Positive *index, Coord2D **des_coord_array ); /** Changes a coordinate's values to this SRF using tranformation object. @note The destination coordinate must have been created using this SRF. @note The value of omega for hst must be within the range ( -2_PI, 2_PI ). @note The value of delta_s for hst must be strictly greater than -1.0. @param src_coord in: the source coordinate in some other SRF @param hst in: the ORM 2D transformation @param des_coord out: the destination coordinate in this SRF @exception This method throws srm::Exception */ virtual void changeCoordinate2DSRFObject( const Coord2D &src_coord, const SRM_ORM_Transformation_2D_Parameters hst, Coord2D &des_coord ); /** Changes an array of coordinate values to this SRF using tranformation object. @note The destination coordinates must have been created using this SRF. @note The source and destination arrays must be of same size. @note All the coordinates in an array must be associated with the same SRF. @note The value of omega for hst must be within the range ( -2_PI, 2_PI ). @note The value of delta_s for hst must be strictly greater than -1.0. @note When an exception is raised, the index parameter is set to the offending coordinate. @param src_coord_array in: the array of source coordinates in some other SRF @param hst in: the ORM 2D transformation @param index in/out: (in) the array length/ (out) the array index of the offending coordinate @param des_coord_array out: the array of destination coordinates in this SRF @exception This method throws srm::Exception */ virtual void changeCoordinate2DArraySRFObject( Coord2D **src_coord_array, const SRM_ORM_Transformation_2D_Parameters hst, SRM_Integer_Positive *index, Coord2D **des_coord_array ); /** Returns the euclidean distance (in metres) between two 2D coordinates. @note The input coordinates can be created from any SRF. @exception This method throws srm::Exception */ static SRM_Long_Float calculateEuclideanDistance( const Coord2D &coord1, const Coord2D &coord2 ); protected: BaseSRF_2D( void *impl ) : BaseSRF(impl) {} ///< No stack allocation BaseSRF_2D &operator =( const BaseSRF_2D & ) { return *this; } ///< No copy constructor virtual ~BaseSRF_2D() {} ///< Use release() }; inline bool BaseSRF_2D::isA( SRF_ClassType type ) const { if (type == BaseSRF::SRF_TYP_TWO_D) return true; else return BaseSRF::isA(type); } /** The BaseSRF_3D abstract class is the base class for the 3D SRFs. SRFs are allocated by the API, and when no longer needed they should be released by calling the release() method. @author Warren Macchi, David Shen @see BaseSRF, BaseSRF_2D */ class EXPORT_SRM_CPP_DLL BaseSRF_3D : public BaseSRF { public: /** Returns true if this SRF is of the given class type */ virtual bool isA( SRF_ClassType type ) const; /** Creates a 3D coordinate object. @see freeCoordinate3D() @return a 3D coordinate object @exception This method throws srm::Exception */ virtual Coord3D *createCoordinate3D( SRM_Long_Float coord_comp1, SRM_Long_Float coord_comp2, SRM_Long_Float coord_comp3 ) = 0; /** Frees a 3D coordinate object. @exception This method throws srm::Exception */ virtual void freeCoordinate3D( Coord3D *coord ); /** Retrieves the 3D coordinate component values. @exception This method throws srm::Exception */ virtual void getCoordinate3DValues( const Coord3D &coord, SRM_Long_Float &coord_comp1, SRM_Long_Float &coord_comp2, SRM_Long_Float &coord_comp3 ) const; /** Changes a coordinate's values to this SRF. @note The destination coordinate must have been created using this SRF. @param src_coord in: the source coordinate in some other SRF @param des_coord in/out: the destination coordinate in this SRF @return validity code for the destination coordinate @exception This method throws srm::Exception */ virtual SRM_Coordinate_Valid_Region changeCoordinate3DSRF( const Coord3D &src_coord, Coord3D &des_coord ); /** Changes an array of coordinate values to this SRF using tranformation object. @note The destination coordinates must have been created using this SRF. @note The source and destination arrays must be of same size. @note All the coordinates in an array must be associated with the same SRF. @note When an exception is raised, the index parameter is set to the offending coordinate. @param src_coord_array in: the array of source coordinates in some other SRF @param index in/out: (in) the array length/ (out) the array index of the offending coordinate @param des_coord_array out: the array of destination coordinate in this SRF @param region_array out: the array of valid regions associated with the destination coordinate @exception This method throws srm::Exception */ virtual void changeCoordinate3DArraySRF( Coord3D **src_coord_array, SRM_Integer_Positive *index, Coord3D **des_coord_array, SRM_Coordinate_Valid_Region *region_array ); /** Changes a coordinate's values to this SRF using tranformation object. @note The destination coordinate must have been created using this SRF. @note The value of omega_1, omega_2 and omega_3 for hst must be within the range ( -2_PI, 2_PI ). @note The value of delta_s for hst must be strictly greater than -1.0. @param src_coord in: the source coordinate in some other SRF @param hst in: the ORM 3D transformation @param des_coord out: the destination coordinate in this SRF @return validity code for the destination coordinate @exception This method throws srm::Exception */ virtual SRM_Coordinate_Valid_Region changeCoordinate3DSRFObject( const Coord3D &src_coord, const SRM_ORM_Transformation_3D_Parameters hst, Coord3D &des_coord ); /** Changes an array of coordinate values to this SRF using tranformation object. @note The destination coordinates must have been created using this SRF. @note The source and destination arrays must be of same size. @note All the coordinates in an array must be associated with the same SRF. @note When an exception is raised, the index parameter is set to the offending coordinate. @param src_coord_array in: the array of source coordinates in some other SRF @param hst in: the ORM 3D transformation @param index in/out: (in) the array length/ (out) the array index of the offending coordinate @param des_coord_array out: the array of destination coordinate in this SRF @param region_array out: the array of valid regions associated with the destination coordinate @exception This method throws srm::Exception */ virtual void changeCoordinate3DArraySRFObject( Coord3D **src_coord_array, const SRM_ORM_Transformation_3D_Parameters hst, SRM_Integer_Positive *index, Coord3D **des_coord_array, SRM_Coordinate_Valid_Region *region_array ); /** Set the Valid Region for this SRF. @note Given a coordinate component, the last invocation of this method or the setExtendedValidRegion method determines the valid and extended valid intervals of the coordinate component values. @note Upper or Lower value is ignored if the interval is a semi-interval or unbounded. @note The Lower value must be strictly less than the Upper value. @param component in: the coordinate component (1, 2, or 3) @param type in: the type of interval @param lower in: the lower value of the interval @param upper in: the upper value of the interval @exception This method throws srm::Exception */ virtual void setValidRegion( const SRM_Integer component, const SRM_Interval_Type type, const SRM_Long_Float lower, const SRM_Long_Float upper ); /** Set the Extended Valid Region for this SRF. @note Given a coordinate component, the last invocation of this method or the setValidRegion method determines the valid and extended valid intervals of the coordinate component values. @note Upper or Lower value is ignored if the interval is a semi-interval or unbounded. @note The Lower value must be strictly less than the Upper value. @note The Extended_Lower value must be strictly greater than the Lower value and the Extended_Upper value must be strictly smaller than the Lower value. @param component in: the coordinate component (1, 2, or 3) @param type in: the type of interval @param extended_lower in: the extended lower value of the interval @param lower in: the lower value of the interval @param upper in: the upper value of the interval @param extended_upper in: the extended_upper value of the interval @exception This method throws srm::Exception */ virtual void setExtendedValidRegion( const SRM_Integer component, const SRM_Interval_Type type, const SRM_Long_Float extended_lower, const SRM_Long_Float lower, const SRM_Long_Float upper, const SRM_Long_Float extended_upper ); /** Get the Valid Region for this SRF. @note Given a coordinate component, the last invocation of this method or the setExtendedValidRegion method determines the valid and extended valid intervals of the coordinate component values. @param component in: the coordinate component (1, 2, or 3) @param type out: the type of interval @param lower out: the lower value of the interval @param upper out: the upper value of the interval @exception This method throws srm::Exception */ virtual void getValidRegion( const SRM_Integer component, SRM_Interval_Type &type, SRM_Long_Float &lower, SRM_Long_Float &upper ); /** Get the Extended Valid Region for this SRF. @note Given a coordinate component, the last invocation of this method or the setValidRegion method determines the valid and extended valid intervals of the coordinate component values. @param component in: the coordinate component (1, 2, or 3) @param type out: the type of interval @param extended_lower out: the extended lower value of the interval @param lower out: the lower value of the interval @param upper out: the upper value of the interval @param extended_upper out: the extended_upper value of the interval @exception This method throws srm::Exception */ virtual void getExtendedValidRegion( const SRM_Integer component, SRM_Interval_Type &type, SRM_Long_Float &extended_lower, SRM_Long_Float &lower, SRM_Long_Float &upper, SRM_Long_Float &extended_upper ); /** Creates a direction object. @return a direction object @exception This method throws srm::Exception */ virtual Direction *createDirection( const Coord3D &ref_coord, const SRM_Vector_3D vec ); /** Creates a direction object. @return a direction object @exception This method throws srm::Exception */ virtual Direction *createDirection( const Coord3D &ref_coord, const SRM_Long_Float vectorComp1, const SRM_Long_Float vectorComp2, const SRM_Long_Float vectorComp3 ); /** Creates a direction object. @return a direction object @exception This method throws srm::Exception @note The returned "default" Direction object is intended to be used as the destination direction for the changeDirectionSRF method. The "default" reference location values cannot be changed except through that method. */ virtual Direction *createDirection(); /** Frees a direction object. @exception This method throws srm::Exception */ virtual void freeDirection( Direction *direction ); /** Retrieves the direction component values. @exception This method throws srm::Exception */ virtual void getDirectionValues( const Direction &direction, Coord3D &ref_coord, SRM_Vector_3D vec ) const; /** Changes a direction's values to this SRF. @note The destination direction must have been created using this SRF. @param src_dir in: the source direction in some other SRF @param des_dir out: the destination direction in this SRF @return valid region category for the reference location associated with the destination direction @exception This method throws srm::Exception */ virtual SRM_Coordinate_Valid_Region changeDirectionSRF( const Direction &src_dir, Direction &des_dir ); /** Changes a direction's values to this SRF using tranformation object. @note The destination directions must have been created using this SRF. @note The source and destination arrays must be of same size. @note All the directions in an array must be associated with the same SRF. @note When an exception is raised, the index parameter is set to the offending direction. @param src_direction_array in: the array of source direction in some other SRF @param index in/out: (in) the array length/ (out) the array index of the offending direction @param des_direction_array out: the array of destination direction in this SRF @param region_array out: the array of valid regions associated with the destination direction @exception This method throws srm::Exception */ void changeDirectionArraySRF( Direction **src_direction_array, SRM_Integer_Positive *index, Direction **des_direction_array, SRM_Coordinate_Valid_Region *region_array ); /** Changes a direction's values to this SRF using tranformation object. @note The destination direction must have been created using this SRF. @note The value of omega_1, omega_2 and omega_3 for hst must be within the range ( -2_PI, 2_PI ). @note The value of delta_s for hst must be strictly greater than -1.0. @param src_dir in: the source direction in some other SRF @param hst in: the ORM 3D transformation @param des_dir out: the destination direction in this SRF @return valid region category for the reference location associated with the destination direction @exception This method throws srm::Exception */ virtual SRM_Coordinate_Valid_Region changeDirectionSRFObject ( const Direction &src_dir, const SRM_ORM_Transformation_3D_Parameters hst, Direction &des_dir ); /** Changes a direction's values to this SRF using tranformation object. @note The destination directions must have been created using this SRF. @note The source and destination arrays must be of same size. @note All the directions in an array must be associated with the same SRF. @note The value of omega_1, omega_2 and omega_3 for hst must be within the range ( -2_PI, 2_PI ). @note The value of delta_s for hst must be strictly greater than -1.0. @note When an exception is raised, the index parameter is set to the offending direction. @param src_direction_array in: the array of source direction in some other SRF @param hst in: the ORM 3D transformation @param index in/out: (in) the array length/ (out) the array index of the offending direction @param des_direction_array out: the array of destination direction in this SRF @param region_array out: the array of valid regions associated with the destination direction @exception This method throws srm::Exception */ void changeDirectionArraySRFObject ( Direction **src_direction_array, const SRM_ORM_Transformation_3D_Parameters hst, SRM_Integer_Positive *index, Direction **des_direction_array, SRM_Coordinate_Valid_Region *region_array ); /** Check a direction in this SRF. */ virtual SRM_Coordinate_Valid_Region checkDirection( const Direction &direction ); /** Creates an orientation object. @param ref_coord in: the reference location for the orientation @param mat in: the orientation matrix @return an orientation object @exception This method throws srm::Exception */ virtual Orientation *createOrientation( const Coord3D &ref_coord, const SRM_Matrix_3x3 mat ); /** Creates an orientation object. @param ref_coord in: the reference location for the orientation @param vec1 in: the first component vector for the orientation matrix @param vec2 in: the second component vector for the orientation matrix @param vec3 in: the third component vector for the orientation matrix @return an orientation object @exception This method throws srm::Exception */ virtual Orientation *createOrientation( const Coord3D &ref_coord, const SRM_Vector_3D vec1, const SRM_Vector_3D vec2, const SRM_Vector_3D vec3 ); /** Creates an orientation object. @param dir1 in: the first component Direction for the orientation matrix @param dir2 in: the second component Direction for the orientation matrix @param dir3 in: the third component Direction for the orientation matrix @return an orientation object @exception This method throws srm::Exception @note The reference location must be the same for three input Direction objects. */ virtual Orientation *createOrientation( const Direction &dir1, const Direction &dir2, const Direction &dir3 ); /** Creates an orientation object. @return an orientation object @exception This method throws srm::Exception @note The returned "default" Orientation object is intended to be used as an output argument for the changeOrientationSRF method. The "default" reference location values cannot be changed except through that method. */ virtual Orientation *createOrientation(); /** Frees an orientation object. @exception This method throws srm::Exception */ virtual void freeOrientation( Orientation *orientation ); /** Retrieves the orientation component values. @exception This method throws srm::Exception */ virtual void getOrientationValues( const Orientation &orientation, Coord3D &ref_coord, SRM_Matrix_3x3 mat ) const; /** Check an orientation in this SRF. @exception This method throws srm::Exception */ virtual SRM_Coordinate_Valid_Region checkOrientation( const Orientation &orientation ); /** Changes an orientation's values to this SRF. @note The destination orientation must have been created using this SRF. @param src_orient in: the source orientation in some other SRF @param des_orient in/out: the destination orientation in this SRF @return valid region category for the reference location associated with the destination orientation @exception This method throws srm::Exception */ virtual SRM_Coordinate_Valid_Region changeOrientationSRF ( const Orientation &src_orient, Orientation &des_orient ); /** Instances a 3D source coordinate and orientation into this SRF. @exception This method throws srm::Exception */ virtual void instanceAbstractSpaceCoordinate( const Coord3D &src_coord, const Orientation &orientation, Coord3D &des_coord ); /** Computes the natural SRF Set member code (region) where the 3D coordinate is located in the target SRF Set. @param src_coord in : the source 3D coordinate in an SRF @param orm_dst in : the ORM for the destination SRF Set @param rt_dst in : the RT for the destination SRF Set @param tgt_srfs in : the destination SRF Set Code @return the SRF Set Member code for the destination SRF Set @exception This method throws srm::Exception */ static SRM_SRFS_Code_Info getNaturalSRFSetMemberCode(const Coord3D &src_coord, SRM_ORM_Code orm_dst, SRM_RT_Code rt_dst, SRM_SRFS_Code tgt_srfs); /** Returns the natural SRF Set member instance that the 3D coordinate is located in the target SRF Set. @param src_coord in : the source 3D coordinate in an SRF @param orm_dst in : the ORM for the destination SRF Set @param rt_dst in : the RT for the destination SRF Set @param tgt_srfs in : the destination SRF Set Code @return the SRF Set Member instance for the destination SRF Set @exception This method throws srm::Exception */ static BaseSRF_3D* getNaturalSRFSetMember( Coord3D &src_coord, SRM_ORM_Code orm_dst, SRM_RT_Code rt_dst, SRM_SRFS_Code tgt_srfs); /** Returns the euclidean distance (in metres) between two 3D coordinates. @note The input coordinates can be created from any SRF. @exception This method throws srm::Exception */ static SRM_Long_Float calculateEuclideanDistance( const Coord3D &coord1, const Coord3D &coord2 ); protected: BaseSRF_3D( void *impl ) : BaseSRF(impl) {} ///< No stack allocation BaseSRF_3D &operator =( const BaseSRF_3D & ) { return *this; } ///< No copy constructor virtual ~BaseSRF_3D() {} ///< Use release() }; inline bool BaseSRF_3D::isA( SRF_ClassType type ) const { if (type == BaseSRF::SRF_TYP_THREE_D) return true; else return BaseSRF::isA(type); } /** The BaseSRF_WithTangentPlaneSurface abstract class is the base class for the 3D SRFs with tangent plane surfaces. SRFs are allocated by the API, and when no longer needed they should be released by calling the release() method. @author @see BaseSRF_3D, BaseSRF */ class EXPORT_SRM_CPP_DLL BaseSRF_WithTangentPlaneSurface : public BaseSRF_3D { public: /** Returns true if this SRF is of the given class type */ virtual bool isA( SRF_ClassType type ) const; /** Creates a surface coordinate object. @exception This method throws srm::Exception */ virtual CoordSurf *createSurfaceCoordinate( SRM_Long_Float coord_surf_comp1, SRM_Long_Float coord_surf_comp2 ) = 0; /** Retrieves a coordinate surface component values @exception This method throws srm::Exception */ virtual void getSurfaceCoordinateValues( const CoordSurf &coord_surf, SRM_Long_Float &coord_surf_comp1, SRM_Long_Float &coord_surf_comp2 ) const; /** Frees a surface coordinate object. @exception This method throws srm::Exception */ virtual void freeSurfaceCoordinate( CoordSurf *coord_surf ); /** Returns a surface coordinate associated with a 3D coordinate. @exception This method throws srm::Exception */ virtual void getAssociatedSurfaceCoordinate( const Coord3D &coord, CoordSurf &on_surface_coord ); /** Returns a 3D coordinate representing the same location as specified by a surface coordinate. @exception This method throws srm::Exception */ virtual void getPromotedSurfaceCoordinate( const CoordSurf &surf_coord, Coord3D &three_d_coord ); /** Returns the euclidean distance (in metres) between two surface coordinates. @note The input coordinates can be created from any SRF. @exception This method throws srm::Exception */ static SRM_Long_Float calculateEuclideanDistance( const CoordSurf &coord1, const CoordSurf &coord2 ); protected: BaseSRF_WithTangentPlaneSurface( void *impl ) : BaseSRF_3D(impl) {} ///< No stack allocation BaseSRF_WithTangentPlaneSurface &operator =( const BaseSRF_WithTangentPlaneSurface & ) { return *this; } ///< No copy constructor virtual ~BaseSRF_WithTangentPlaneSurface() {} ///< Use release() }; inline bool BaseSRF_WithTangentPlaneSurface::isA( SRF_ClassType type ) const { if (type == BaseSRF::SRF_TYP_WITH_TANGENT_PLANE_SURFACE) return true; else return BaseSRF_3D::isA(type); } /** The BaseSRF_WithEllipsoidalHeight abstract class is the base class for the 3D SRFs with ellipsoidal heights. SRFs are allocated by the API, and when no longer needed they should be released by calling the release() method. @author Warren Macchi, David Shen @see BaseSRF_3D, BaseSRF */ class EXPORT_SRM_CPP_DLL BaseSRF_WithEllipsoidalHeight : public BaseSRF_3D { public: /** Returns true if this SRF is of the given class type */ virtual bool isA( SRF_ClassType type ) const; /** Creates a surface coordinate object. @exception This method throws srm::Exception */ virtual CoordSurf *createSurfaceCoordinate( SRM_Long_Float coord_surf_comp1, SRM_Long_Float coord_surf_comp2 ) = 0; /** Retrieves a coordinate surface component values @exception This method throws srm::Exception */ virtual void getSurfaceCoordinateValues( const CoordSurf &coord_surf, SRM_Long_Float &coord_surf_comp1, SRM_Long_Float &coord_surf_comp2 ) const; /** Frees a surface coordinate object. @exception This method throws srm::Exception */ virtual void freeSurfaceCoordinate( CoordSurf *coord_surf ); /** Returns a surface coordinate associated with a 3D coordinate. @exception This method throws srm::Exception */ virtual void getAssociatedSurfaceCoordinate( const Coord3D &coord, CoordSurf &on_surface_coord ); /** Returns a 3D coordinate representing the same location as specified by a surface coordinate. @exception This method throws srm::Exception */ virtual void getPromotedSurfaceCoordinate( const CoordSurf &surf_coord, Coord3D &three_d_coord ); /** Creates a Local Tangent Space Euclidean SRF with natural origin at a given position. @exception This method throws srm::Exception */ virtual SRF_LocalTangentSpaceEuclidean *createLocalTangentSpaceEuclideanSRF( const CoordSurf &surf_coord, SRM_Long_Float azimuth, SRM_Long_Float false_x_origin, SRM_Long_Float false_y_origin, SRM_Long_Float offset_height ); /** Computes the natural SRF Set member code (region) where the Surface coordinate is located in the target SRF Set. @param src_coord in : the source surface coordinate in an SRF @param orm_dst in : the ORM for the destination SRF Set @param rt_dst in : the RT for the destination SRF Set @param tgt_srfs in : the destination SRF Set Code @return the SRF Set Member code for the destination SRF Set @exception This method throws srm::Exception */ static SRM_SRFS_Code_Info getNaturalSRFSetMemberCode( CoordSurf &src_coord, SRM_ORM_Code orm_dst, SRM_RT_Code rt_dst, SRM_SRFS_Code tgt_srfs); /** Computes the natural SRF Set member instance that the surface coordinate is located in the target SRF Set. @param src_coord in : the source surface coordinate in an SRF @param orm_dst in : the ORM for the destination SRF Set @param rt_dst in : the Hsr for the destination SRF Set @param tgt_srfs in : the destination SRF Set Code @return the SRF Set Member instance for the destination SRF Set @exception This method throws srm::Exception */ static BaseSRF_3D* getNaturalSRFSetMember( CoordSurf &src_coord, SRM_ORM_Code orm_dst, SRM_RT_Code rt_dst, SRM_SRFS_Code tgt_srfs); /** Returns the euclidean distance (in metres) between two surface coordinates. @note The input coordinates can be created from any SRF. @exception This method throws srm::Exception */ static SRM_Long_Float calculateEuclideanDistance( const CoordSurf &coord1, const CoordSurf &coord2 ); /** Returns the geodesic distance (in metres) between two surface coordinates. @exception This method throws srm::Exception */ static SRM_Long_Float calculateGeodesicDistance( const CoordSurf &src_coord, const CoordSurf &des_coord ); /** Returns the vertical separation (in metres) at a position. @exception This method throws srm::Exception */ virtual SRM_Long_Float calculateVerticalSeparationOffset( SRM_DSS_Code vos, const CoordSurf &surf_coord ); protected: BaseSRF_WithEllipsoidalHeight( void *impl ) : BaseSRF_3D(impl) {} ///< No stack allocation BaseSRF_WithEllipsoidalHeight &operator =( const BaseSRF_WithEllipsoidalHeight & ) { return *this; } ///< No copy constructor virtual ~BaseSRF_WithEllipsoidalHeight() {} ///< Use release() }; inline bool BaseSRF_WithEllipsoidalHeight::isA( SRF_ClassType type ) const { if (type == BaseSRF::SRF_TYP_WITH_ELLIPSOIDAL_HEIGHT) return true; else return BaseSRF_3D::isA(type); } /** The BaseSRF_MapProjection abstract class is the base class for the 2D SRFs with map projections. SRFs are allocated by the API, and when no longer needed they should be released by calling the release() method. @author Warren Macchi, David Shen @see BaseSRF_WithEllipsoidalHeight, BaseSRF_3D */ class EXPORT_SRM_CPP_DLL BaseSRF_MapProjection : public BaseSRF_WithEllipsoidalHeight { public: /** Returns true if this SRF is of the given class type */ virtual bool isA( SRF_ClassType type ) const; /** Set the Valid Region for this SRF in geodetic coordinates (lon/lat). @note Given a coordinate component, the last invocation of this method or the setExtendedValidGeodeticRegion method determines the valid and extended valid intervals of the coordinate component values. @note Upper or Lower value is ignored if the interval is a semi-interval or unbounded. @note The Lower value must be strictly less than the Upper value. @param component in: the coordinate component (1 or 2) @param type in: the type of interval @param lower in: the lower value of the interval @param upper in: the upper value of the interval @exception This method throws srm::Exception */ virtual void setValidGeodeticRegion( const SRM_Integer component, const SRM_Interval_Type type, const SRM_Long_Float lower, const SRM_Long_Float upper ); /** Set the Extended Valid Geodetic Region for this SRF. @note Given a coordinate component, the last invocation of this method or the setValidGeodeticRegion method determines the valid and extended valid intervals of the coordinate component values. @note Upper or Lower value is ignored if the interval is a semi-interval or unbounded. @note The Lower value must be strictly less than the Upper value. @note The Extended_Lower value must be strictly greater than the Lower value and the Extended_Upper value must be strictly smaller than the Lower value. @param component in: the coordinate component (1 or 2) @param type in: the type of interval @param extended_lower in: the extended lower value of the interval @param lower in: the lower value of the interval @param upper in: the upper value of the interval @param extended_upper in: the extended_upper value of the interval @exception This method throws srm::Exception */ virtual void setExtendedValidGeodeticRegion( const SRM_Integer component, const SRM_Interval_Type type, const SRM_Long_Float extended_lower, const SRM_Long_Float lower, const SRM_Long_Float upper, const SRM_Long_Float extended_upper ); /** Get the Valid Geodetic Region for this SRF. @note Given a coordinate component, the last invocation of this method or the setExtendedValidGeodeticRegion method determines the valid and extended valid intervals of the coordinate component values. @param component in: the coordinate component (1 or 2) @param type out: the type of interval @param lower out: the lower value of the interval @param upper out: the upper value of the interval @exception This method throws srm::Exception */ virtual void getValidGeodeticRegion( const SRM_Integer component, SRM_Interval_Type &type, SRM_Long_Float &lower, SRM_Long_Float &upper ); /** Get the Extended Valid Geodetic Region for this SRF. @note Given a coordinate component, the last invocation of this method or the setValidGeodeticRegion method determines the valid and extended valid intervals of the coordinate component values. @param component in: the coordinate component (1, 2, or 3) @param type out: the type of interval @param extended_lower out: the extended lower value of the interval @param lower out: the lower value of the interval @param upper out: the upper value of the interval @param extended_upper out: the extended_upper value of the interval @exception This method throws srm::Exception */ virtual void getExtendedValidGeodeticRegion( const SRM_Integer component, SRM_Interval_Type &type, SRM_Long_Float &extended_lower, SRM_Long_Float &lower, SRM_Long_Float &upper, SRM_Long_Float &extended_upper ); /** Returns the Convergence of the Meridian in radians at a position on the surface of the oblate spheroid RD. @exception This method throws srm::Exception */ virtual SRM_Long_Float calculateConvergenceOfTheMeridian( const CoordSurf &surf_coord ); /** Returns the point distortion at a position on the surface of the ellipsoid RD. @exception This method throws srm::Exception */ virtual SRM_Long_Float calculatePointDistortion( const CoordSurf &surf_coord ); /** Returns the map azimuth in radians between two surface coordinates. @exception This method throws srm::Exception */ virtual SRM_Long_Float calculateMapAzimuth( const CoordSurf &src_coord, const CoordSurf &des_coord ); protected: BaseSRF_MapProjection( void *impl ) : BaseSRF_WithEllipsoidalHeight(impl) {} ///< No stack allocation BaseSRF_MapProjection &operator =( const BaseSRF_MapProjection & ) { return *this; } ///< No copy constructor virtual ~BaseSRF_MapProjection() {} ///< Use release() }; inline bool BaseSRF_MapProjection::isA( SRF_ClassType type ) const { if (type == BaseSRF::SRF_TYP_MAP_PROJECTION) return true; else return BaseSRF_WithEllipsoidalHeight::isA(type); } } // namespace srm #endif // _BaseSRF_h
[ "sysbender@gmail.com" ]
sysbender@gmail.com
03e3044cae601707e8a4950b6517b30fbd989931
35fbe1678a2b52fed50c754e5e2fbe2f39ef44d6
/windows/runner/main.cpp
07c35159228a2d7b11a679857dddec9603250d47
[]
no_license
deorwine/desktop-applications-with-flutter
2ae1d5f006800a01cd6b0385fd68ff0c51741498
ccc81e797b5ef1fb521959bc691d9e624639ca60
refs/heads/master
2023-06-20T11:44:14.246979
2021-07-23T06:58:22
2021-07-23T06:58:22
388,004,891
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
#include <flutter/dart_project.h> #include <flutter/flutter_view_controller.h> #include <windows.h> #include "flutter_window.h" #include "run_loop.h" #include "utils.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { CreateAndAttachConsole(); } // Initialize COM, so that it is available for use in the library and/or // plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); RunLoop run_loop; flutter::DartProject project(L"data"); std::vector<std::string> command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); FlutterWindow window(&run_loop, project); Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.CreateAndShow(L"Paras", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); run_loop.Run(); ::CoUninitialize(); return EXIT_SUCCESS; }
[ "paras.laxkar@deorwine.com" ]
paras.laxkar@deorwine.com
dc9ec1a25d7ab88f46d6e38fb016c6bbdfad80a8
f7458f81055c5458ae619b8e5469e3e018f05b1f
/IO/SegY/vtkSegY3DReader.h
06534530974e3bafbbc9996ef0a845280bb51710
[ "BSD-3-Clause" ]
permissive
CDAT/VTK
f4e2d5920533eee2009044cff99d722290d14870
840dcb68621a8aeef2b49be4a3ba64c9f5061987
refs/heads/uvcdat-master
2022-04-07T07:13:44.287885
2017-08-18T16:25:07
2017-08-18T16:25:07
13,934,856
0
0
NOASSERTION
2020-02-28T07:53:21
2013-10-28T18:37:31
C++
UTF-8
C++
false
false
1,504
h
/*========================================================================= Program: Visualization Toolkit Module: vtkSegY3DReader.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef vtkSegY3DReader_h #define vtkSegY3DReader_h #include "vtkImageAlgorithm.h" #include "vtkSegYReader.h" // For reader implementation #include "vtkSmartPointer.h" // For smart pointer #include <vtkIOSegYModule.h> // For export macro // Forward declarations class vtkImageData; class VTKIOSEGY_EXPORT vtkSegY3DReader : public vtkImageAlgorithm { public: static vtkSegY3DReader* New(); vtkTypeMacro(vtkSegY3DReader, vtkImageAlgorithm); void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE; vtkSetStringMacro(FileName); vtkGetStringMacro(FileName); virtual vtkImageData* GetImage(); protected: vtkSegY3DReader(); ~vtkSegY3DReader(); char* FileName; vtkSegYReader reader; vtkSmartPointer<vtkImageData> image; private: vtkSegY3DReader(const vtkSegY3DReader&) VTK_DELETE_FUNCTION; void operator=(const vtkSegY3DReader&) VTK_DELETE_FUNCTION; }; #endif // vtkSegY3DReader_h
[ "sankhesh.jhaveri@kitware.com" ]
sankhesh.jhaveri@kitware.com
72b3e573176a4672dcad4570563a226c76ff0d60
64c64f19d6028d3948263a0acd1e7e86f5bf38b1
/OJ/446.cpp
78fd05df8b6f3088c8c152140365157fb6f0e27f
[]
no_license
xiejun5/HaiZei
f765f2462b63fe87efe754096c80c5f2ec5ea3df
9f36757cadeb2f71434604eb16145dd5ef60e736
refs/heads/master
2020-09-22T08:16:44.318888
2020-08-11T15:25:10
2020-08-11T15:25:10
225,117,929
3
0
null
null
null
null
UTF-8
C++
false
false
1,013
cpp
/************************************************************************* > File Name: 446.cpp > Author: > Mail: > Created Time: 2020年01月08日 星期三 10时11分03秒 ************************************************************************/ #include<iostream> #include <cstring> using namespace std; #define N 100 int num[N][N]; int main() { int n, p, q, t; cin >> n; p = 1; q = n; t = 1; for (int j = 0; j <= n; j++, p++, q--) { for (int i = p; i <= q; i++) { num[p][i] = t; } for (int i = p; i <= q; i++) { num[i][q] = t; } for (int i = n - j; i >= p; i--) { num[q][i] = t; } for (int i = n - j; i >= p + 1; i--) { num[i][p] = t; } t++; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { j - 1 && cout << " "; cout << num[i][j]; } cout << endl; } return 0; }
[ "3406505842@qq.com" ]
3406505842@qq.com
dd59b9acea9bece9435b803d9b36c2b8f4e17a96
af665e07d1c18a8a15b39a980b01b2a55a33bb78
/kaldi/src/nnet3/nnet-descriptor.h
e2d2c41772d4ddb605875ba7faea7361c6cae716
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
lyapple2008/SpeakerVerification_based_on_Kaldi
cd52721fcf9b6d05326df5a7fcabd0bf66db7f08
838b60e8a5be31909f7d17941999ad2fa6f32b4a
refs/heads/master
2021-01-23T06:14:35.046951
2017-06-01T09:33:10
2017-06-01T09:33:10
93,015,037
5
1
null
null
null
null
UTF-8
C++
false
false
26,845
h
// nnet3/nnet-descriptor.h // Copyright 2012-2015 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #ifndef KALDI_NNET3_NNET_DESCRIPTOR_H_ #define KALDI_NNET3_NNET_DESCRIPTOR_H_ #include "base/kaldi-common.h" #include "util/kaldi-io.h" #include "matrix/matrix-lib.h" #include "nnet3/nnet-common.h" #include "nnet3/nnet-component-itf.h" #include <iostream> #include <sstream> #include <vector> #include <map> namespace kaldi { namespace nnet3 { /** \file nnet-descriptor.h This file contains class definitions for classes ForwardingDescriptor, SumDescriptor and Descriptor. Basically this is code that specifies how we glue together the outputs of possibly several other network-nodes, as the input of a particular network node (or as an output of the network). In the neural-network code we refer to the top-level descriptor which is Descriptor. The InputDescriptor is a concatenation of features; each part is a SumDescriptor. The SumDescriptor is a summation over a set of features of all the same dimension, each of which is represented by a ForwardingDescriptor. A ForwardingDescriptor in the simplest case just takes just points you to a particular network node, but in general can do things like adding time offsets, and selecting different rows of its matrix from different inputs. Unlike the other descriptors, a ForwardingDescriptor is in general a bit like a parse tree, in that it can in general contain other ForwardingDescriptors. The following gives an overview of the expressions that can appear in descriptors. Caution; this is a simplification that overgenerates descriptors. \verbatim <descriptor> ::= <node-name> ;; node name of kInput or kComponent node. <descriptor> ::= Append(<descriptor>, <descriptor> [, <descriptor> ... ] ) <descriptor> ::= Sum(<descriptor>, <descriptor>) ;; Failover or IfDefined might be useful for time t=-1 in a RNN, for instance. <descriptor> ::= Failover(<descriptor>, <descriptor>) ;; 1st arg if computable, else 2nd <descriptor> ::= IfDefined(<descriptor>) ;; the arg if defined, else zero. <descriptor> ::= Offset(<descriptor>, <t-offset> [, <x-offset> ] ) ;; offsets are integers ;; Switch(...) is intended to be used in clockwork RNNs or similar schemes. It chooses ;; one argument based on the value of t (in the requested Index) modulo the number of ;; arguments <descriptor> ::= Switch(<descriptor>, <descriptor> [, <descriptor> ...]) ;; For use in clockwork RNNs or similar, Round() rounds the time-index t of the ;; requested Index to the next-lowest multiple of the integer <t-modulus>, ;; and evaluates the input argument for the resulting Index. <descriptor> ::= Round(<descriptor>, <t-modulus>) ;; <t-modulus> is an integer ;; ReplaceIndex replaces some <variable-name> (t or x) in the requested Index ;; with a fixed integer <value>. E.g. might be useful when incorporating ;; iVectors; iVector would always have time-index t=0. <descriptor> ::= ReplaceIndex(<descriptor>, <variable-name>, <value>) \endverbatim */ // A ForwardingDescriptor describes how we copy data from another NetworkNode, // or from multiple other NetworkNodes. In the simplest case this can just be // equivalent to giving the name of another NetworkNode, but we also support // things like time-offsets, selecting depending on the index from multiple // different inputs, and things like that. // // note: nodes of type kOutput (i.e. output nodes of the network) cannot appear // as inputs in any descriptor. This is to simplify compilation. class ForwardingDescriptor { public: // Given an Index that's requested at the output of this descriptor, maps it // to a (node_index, Index) pair that says where we are to get the data from. virtual Cindex MapToInput(const Index &output) const = 0; // Return the feature dimension. virtual int32 Dim(const Nnet &nnet) const = 0; virtual ForwardingDescriptor *Copy() const = 0; /// This function is for use in things like clockwork RNNs, where shifting the /// time of the inputs and outputs of the network by some multiple integer n /// would leave things the same, but shifting by non-multiples would change the /// network structure. It returns the smallest modulus to which this /// descriptor is invariant; the lowest common multiple of all descriptors in /// the network gives you the modulus for the whole network. virtual int32 Modulus() const { return 1; } // Write to string that will be one line of a config-file-like format. The // opposite of Parse. virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const = 0; /// This function appends to "node_indexes" all the node indexes // that this descriptor may access. virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const = 0; virtual ~ForwardingDescriptor() { } ForwardingDescriptor() { } private: KALDI_DISALLOW_COPY_AND_ASSIGN(ForwardingDescriptor); }; // SimpleForwardingDescriptor is the base-case of ForwardingDescriptor, class SimpleForwardingDescriptor: public ForwardingDescriptor { public: virtual Cindex MapToInput(const Index &index) const; virtual int32 Dim(const Nnet &nnet) const; virtual ForwardingDescriptor *Copy() const; virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const; // Write to string that will be one line of a config-file-like format. The // opposite of Parse. // written form is just the node-name of src_node_. virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; SimpleForwardingDescriptor(int32 src_node): src_node_(src_node) { KALDI_ASSERT(src_node >= 0); } virtual ~SimpleForwardingDescriptor() { } private: int32 src_node_; // index of the source NetworkNode. }; class OffsetForwardingDescriptor: public ForwardingDescriptor { public: virtual Cindex MapToInput(const Index &ind) const; virtual int32 Dim(const Nnet &nnet) const { return src_->Dim(nnet); } virtual ForwardingDescriptor *Copy() const; // written form is: Offset(<src-written-form>, t-offset [, x-offset]) virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; virtual int32 Modulus() const { return src_->Modulus(); } virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const; // takes ownership of src. OffsetForwardingDescriptor(ForwardingDescriptor *src, Index offset): src_(src), offset_(offset) { } virtual ~OffsetForwardingDescriptor() { delete src_; } private: ForwardingDescriptor *src_; // Owned here. Index offset_; // The index-offset to be added to the index. }; // Chooses from different inputs based on the the time index modulo // (the number of ForwardingDescriptors given as inputs). class SwitchingForwardingDescriptor: public ForwardingDescriptor { public: virtual Cindex MapToInput(const Index &ind) const; virtual int32 Dim(const Nnet &nnet) const { return src_[0]->Dim(nnet); } virtual ForwardingDescriptor *Copy() const; // Written form is "Switch(<written-form-of-src1>, <written-form-of-src2>, ... )" virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; virtual int32 Modulus() const; /// This function appends to "node_indexes" all the node indexes // that this descriptor may access. virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const; // takes ownership of items in src. SwitchingForwardingDescriptor(std::vector<ForwardingDescriptor*> &src): src_(src) { } virtual ~SwitchingForwardingDescriptor() { DeletePointers(&src_); } private: // Pointers are owned here. std::vector<ForwardingDescriptor*> src_; }; /// For use in clockwork RNNs and the like, this forwarding-descriptor /// rounds the time-index t down to the the closest t' <= t that is /// an exact multiple of t_modulus_. class RoundingForwardingDescriptor: public ForwardingDescriptor { public: virtual Cindex MapToInput(const Index &ind) const; virtual int32 Dim(const Nnet &nnet) const { return src_->Dim(nnet); } virtual ForwardingDescriptor *Copy() const; // Written form is "Round(<written-form-of-src>, <t_modulus>)" virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; virtual int32 Modulus() const { return t_modulus_; } /// This function appends to "node_indexes" all the node indexes // that this descriptor may access. virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const; // takes ownership of src. RoundingForwardingDescriptor(ForwardingDescriptor *src, int32 t_modulus): src_(src), t_modulus_(t_modulus) { } virtual ~RoundingForwardingDescriptor() { delete src_; } private: ForwardingDescriptor *src_; int32 t_modulus_; }; /// This ForwardingDescriptor modifies the indexes (n, t, x) by replacing one /// of them (normally t) with a constant value and keeping the rest. class ReplaceIndexForwardingDescriptor: public ForwardingDescriptor { public: enum VariableName { kN = 0, kT = 1, kX = 2}; virtual Cindex MapToInput(const Index &ind) const; virtual int32 Dim(const Nnet &nnet) const { return src_->Dim(nnet); } virtual ForwardingDescriptor *Copy() const; // Written form is "ReplaceIndex(<written-form-of-src>, <variable-name>, <value>)" // where <variable-name> is either "t" or "x". virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; /// This function appends to "node_indexes" all the node indexes // that this descriptor may access. virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const; // takes ownership of src. ReplaceIndexForwardingDescriptor(ForwardingDescriptor *src, VariableName variable_name, int32 value): src_(src), variable_name_(variable_name), value_(value) { } virtual ~ReplaceIndexForwardingDescriptor() { delete src_; } private: ForwardingDescriptor *src_; VariableName variable_name_; int32 value_; }; /// Forward declaration. This is declared in nnet-computation-graph.h. class CindexSet; /// This is an abstract base-class. In the normal case a SumDescriptor is a sum /// over one or more terms, all each corresponding to a quantity of the same /// dimension, each of which is a ForwardingDescriptor. However, it also allows /// for logic for dealing with cases where only some terms in the sum are /// present, and only some are included in the sum: for example, not just /// expressions like A + B but also A + (B if present), or (A if present; if not, // B). class SumDescriptor { public: /// Given an Index at the output of this Descriptor, append to "dependencies" /// a list of Cindexes that describes what inputs we potentially depend on. /// The output list is not necessarily sorted, and this function doesn't make /// sure that it's unique. virtual void GetDependencies(const Index &ind, std::vector<Cindex> *dependencies) const = 0; /// This function exists to enable us to manage optional dependencies, /// i.e. for making sense of expressions like (A + (B is present)) and (A if /// present; if not, B). Suppose we are trying to compute the index "ind", /// and the user represents that "cindex_set" is the set of Cindexes are /// available to the computation; then this function will return true if we /// can compute the expression given these inputs; and if so, will output to /// "used_inputs" the list of Cindexes that this expression will be a /// summation over. /// /// @param [in] ind The index that we want to compute at the output of the /// Descriptor. /// @param [in] cindex_set The set of Cindexes that are available at the /// input of the Descriptor. /// @param [out] used_inputs If non-NULL, if this function returns true then /// to this vector will be *appended* the inputs that will /// actually participate in the computation. Else (if non-NULL) it /// will be left unchanged. /// @return Returns true if this output is computable given the provided /// inputs. virtual bool IsComputable(const Index &ind, const CindexSet &cindex_set, std::vector<Cindex> *used_inputs) const = 0; virtual int32 Dim(const Nnet &nnet) const = 0; virtual SumDescriptor *Copy() const = 0; virtual ~SumDescriptor() { } // This function appends to "node_indexes" a list (not necessarily sorted or // unique) of all the node indexes that this descriptor may forward data from. virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const = 0; // see Modulus function of ForwardingDescriptor for explanation. virtual int32 Modulus() const = 0; /// Write in config-file format. Conventional Read and Write methods are not /// supported. virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const = 0; }; /// This is the case of class SumDescriptor, in which we contain just one term, /// and that term is optional (an IfDefined() expression). That term is a /// general SumDescriptor. class OptionalSumDescriptor: public SumDescriptor { public: virtual void GetDependencies(const Index &ind, std::vector<Cindex> *dependencies) const; virtual bool IsComputable(const Index &ind, const CindexSet &cindex_set, std::vector<Cindex> *used_inputs) const { return src_->IsComputable(ind, cindex_set, used_inputs) || true; } virtual int32 Dim(const Nnet &nnet) const; // This function appends to "node_indexes" a list (not necessarily sorted or // unique) of all the node indexes that this descriptor may forward data from. virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const; virtual int32 Modulus() const { return src_->Modulus(); } /// written form is: if required_ == true, "<written-form-of-src>" /// else "IfDefined(<written-form-of-src>)". virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; virtual SumDescriptor *Copy() const; OptionalSumDescriptor(SumDescriptor *src): src_(src) { } virtual ~OptionalSumDescriptor() { delete src_; } private: SumDescriptor *src_; }; // This is the base-case of SumDescriptor which just wraps // a ForwardingDescriptor. class SimpleSumDescriptor: public SumDescriptor { public: virtual void GetDependencies(const Index &ind, std::vector<Cindex> *dependencies) const; virtual bool IsComputable(const Index &ind, const CindexSet &cindex_set, std::vector<Cindex> *used_inputs) const; virtual int32 Dim(const Nnet &nnet) const; // This function appends to "node_indexes" a list (not necessarily sorted or // unique) of all the node indexes that this descriptor may forward data from. virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const; virtual int32 Modulus() const { return src_->Modulus(); } /// written form is: if required_ == true, "<written-form-of-src>" /// else "IfDefined(<written-form-of-src>)". virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; virtual SumDescriptor *Copy() const; SimpleSumDescriptor(ForwardingDescriptor *src): src_(src) { } virtual ~SimpleSumDescriptor() { delete src_; } private: ForwardingDescriptor *src_; }; /// BinarySumDescriptor can represent either A + B, or (A if defined, else B). /// Other expressions such as A + (B if defined, else zero), (A if defined, else /// zero) + (B if defined, else zero), and (A if defined, else B if defined, /// else zero) can be expressed using combinations of the two provided options /// for BinarySumDescriptor and the variant class BinarySumDescriptor: public SumDescriptor { public: enum Operation { kSum, // A + B kFailover, // A if defined, else B. }; virtual void GetDependencies(const Index &ind, std::vector<Cindex> *dependencies) const; virtual bool IsComputable(const Index &ind, const CindexSet &cindex_set, std::vector<Cindex> *used_inputs) const; virtual int32 Dim(const Nnet &nnet) const; // This function appends to "node_indexes" a list (not necessarily sorted or // unique) of all the node indexes that this descriptor may forward data from. virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const; virtual int32 Modulus() const; /// Written form is: if op_ == kSum then "Sum(<src1>, <src2>)"; /// if op_ == kFailover, then "Failover(<src1>, <src2>)" /// If you need more than binary operations, just use Sum(a, Sum(b, c)). virtual void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; virtual SumDescriptor *Copy() const; BinarySumDescriptor(Operation op, SumDescriptor *src1, SumDescriptor *src2): op_(op), src1_(src1), src2_(src2) {} virtual ~BinarySumDescriptor() { delete src1_; delete src2_; } private: Operation op_; SumDescriptor *src1_; SumDescriptor *src2_; }; // A Descriptor concatenates over its parts, so its feature-dimension will // be the sum of the feature-dimensions of its parts. In a valid Descriptor, // "parts" will be nonempty. Each part may be (in general) a summation, but // usually a summation with just one term. class Descriptor { public: int32 Dim(const Nnet &nnet) const; // The Parse method is used for reading a config-file-style represenation. // Internally this uses class GeneralDescriptor to read and normalize the // input. Assumes the input has already been tokenized into an array of // strings by DescriptorTokenize(); it moves the begin-pointer "next_token" to // account for each token that it consumes. Prints warning and returns false on // error (including if there was junk after the last token). The input tokens // should be terminated with a token that says "end of input". bool Parse(const std::vector<std::string> &node_names, const std::string **next_token); // Write in config-file format. // if parts_.size() == 1, written form is just "<written-form-of-part0>" // otherwise, written form is "Append(<written-form-of-part0>, <written-form-of-part1>, ... )". void WriteConfig(std::ostream &os, const std::vector<std::string> &node_names) const; /// This function exists to enable us to manage optional dependencies, /// i.e. for making sense of expressions like (A + (B is present)) and (A if /// present; if not, B). Suppose we are trying to compute the index "ind", /// and the user represents that "cindex_set" is the set of Cindexes are /// available to the computation; then this function will return true if we /// can compute the expression given these inputs; and if so, will output to /// "used_inputs" the list of Cindexes (not necessarily unique) that this /// expression will include. Otherwise it will return false and set /// used_inputs to the empty vector. /// /// @param [in] ind The index that we want to compute at the output of the /// Descriptor. /// @param [in] cindex_set The set of Cindexes that are available at the /// input of the Descriptor. /// @param [out] used_inputs If non-NULL, if this function returns true then /// to this vector will be *appended* the inputs that will /// actually participate in the computation. Else (if non-NULL) it /// will be left unchanged. /// @return Returns true if this output is computable given the provided /// inputs. void GetDependencies(const Index &index, std::vector<Cindex> *used_inputs) const; /// Has the same purpose and interface as the IsComputable function of the /// SumDescriptor function. Outputs to used_inputs rather than appending /// to it, though. used_inputs will not be sorted or have repeats removed. bool IsComputable(const Index &ind, const CindexSet &cindex_set, std::vector<Cindex> *used_inputs) const; // This function outputs to "node_indexes" a list (not necessarily sorted or // unique) of all the node indexes that this descriptor may forward data from. void GetNodeDependencies(std::vector<int32> *node_indexes) const; // see Modulus function of ForwardingDescriptor for explanation. int32 Modulus() const; /// Returns the number of parts that are concatenated over. int32 NumParts() const { return parts_.size(); } /// returns the n'th part. const SumDescriptor &Part(int32 n) const; Descriptor() { } /// Copy constructor Descriptor(const Descriptor &other) { *this = other; } /// Assignment operator. Descriptor &operator = (const Descriptor &other); /// Takes ownership of pointers in "parts". Descriptor(const std::vector<SumDescriptor*> &parts): parts_(parts) { } /// Destructor ~Descriptor() { Destroy(); } private: void Destroy(); // empties parts_ after deleting its members. // the elements of parts_ are owned here. std::vector<SumDescriptor*> parts_; }; /** This class is only used when parsing Descriptors. It is useful for normalizing descriptors that are structured in an invalid or redundant way, into a form that can be turned into a real Descriptor. */ struct GeneralDescriptor { enum DescriptorType { kAppend, kSum, kFailover, kIfDefined, kOffset, kSwitch, kRound, kReplaceIndex, kNodeName }; // The Parse method is used for reading a config-file-style represenation. // Assumes the input has already been tokenized into an array of strings, and // it moves the begin-pointer "next_token" to account for token that it // consumes. Calls KALDI_ERR on error. The list of tokens should be // terminated with a string saying "end of input". Does not check that all // the input has been consumed-- the caller should do that [check that // **next_token == "end of input" after calling.] static GeneralDescriptor *Parse(const std::vector<std::string> &node_names, const std::string **next_token); explicit GeneralDescriptor(DescriptorType t, int32 value1 = -1, int32 value2 = -1): descriptor_type_(t), value1_(value1), value2_(value2) { } ~GeneralDescriptor() { DeletePointers(&descriptors_); } GeneralDescriptor *GetNormalizedDescriptor() const; Descriptor *ConvertToDescriptor(); // prints in text form-- this is really only used for debug. void Print(const std::vector<std::string> &node_names, std::ostream &os); private: KALDI_DISALLOW_COPY_AND_ASSIGN(GeneralDescriptor); DescriptorType descriptor_type_; // the following is only relevant if descriptor_type == kReplaceIndex [1 for t, 2 for ] // or kNodeName (the index of the node), or kOffset [the t offset]. int32 value1_; // the following is only relevant if descriptor_type == kReplaceIndex [the value // we replace the index with], or kOffset [the x offset] int32 value2_; // For any descriptor types that take args of type kDescriptor, a list of those // args. Pointers owned here. std::vector<GeneralDescriptor*> descriptors_; // parses an Append() or Sum() or Switch() expression after the "Append(" or // "Sum(" or "Switch(" has been read. void ParseAppendOrSumOrSwitch(const std::vector<std::string> &node_names, const std::string **next_token); // parse an IfDefined() expression after the IfDefined( has already been // read. void ParseIfDefined(const std::vector<std::string> &node_names, const std::string **next_token); // ... and so on. void ParseOffset(const std::vector<std::string> &node_names, const std::string **next_token); void ParseSwitch(const std::vector<std::string> &node_names, const std::string **next_token); void ParseFailover(const std::vector<std::string> &node_names, const std::string **next_token); void ParseRound(const std::vector<std::string> &node_names, const std::string **next_token); void ParseReplaceIndex(const std::vector<std::string> &node_names, const std::string **next_token); // Used inside NormalizeAppend(). Return the number of terms there // would be in a single consolidated Append() expressions, and asserts that in // whichever branch of any other expressions we take, the number of terms is // the same. int32 NumAppendTerms() const; // Used inside NormalizeAppend(). Gets one of the appended terms from this // descriptor, with 0 <= term < NumAppendTerms(). Answer is newly allocated. GeneralDescriptor *GetAppendTerm(int32 term) const; // Normalizes w.r.t. Append expressions by moving Append() to the outside. // Called only at the top level. GeneralDescriptor *NormalizeAppend() const; // This call does all other types of normalization except for normalizing // Append() expressions (which is assumed to have been done already). Returns // true if anything was changed. static bool Normalize(GeneralDescriptor *ptr); SumDescriptor *ConvertToSumDescriptor() const; ForwardingDescriptor *ConvertToForwardingDescriptor() const; }; } // namespace nnet3 } // namespace kaldi #endif
[ "ly_apple_2008@163.com" ]
ly_apple_2008@163.com
56297ae7e695111815692272683e8533b9c74c05
4416d4c599f175b68f54e0ee2aca97b18639567f
/DXBase/DXBase/sources/Field/MoveFloorRightLeft.h
0a4f557d028917ddbb6083d644e4831b356e2563
[]
no_license
kentatakiguchi/GameCompetition2016_2
292fa9ab574e581406ff146cc98b15efc0d66446
df1eb6bf29aba263f46b850d268f49ef417a134b
refs/heads/master
2021-01-11T18:21:34.377644
2017-03-03T08:25:39
2017-03-03T08:25:39
69,625,978
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,025
h
#pragma once #ifndef MOVE_FLOOR_RIGHT_LEFT_H_ #define MOVE_FLOOR_RIGHT_LEFT_H_ #include"../Actor/Base/Actor.h" #include"../Define.h" #include"MapChip.h" class MoveFloorRightLeft :public MapChip { public: //空のMapChipを生成 MoveFloorRightLeft() {} //マップチップの生成 MoveFloorRightLeft(IWorld* world, Vector2& position); MoveFloorRightLeft(int spriteID,IWorld* world, Vector2& position); MoveFloorRightLeft(std::shared_ptr<MoveFloorRightLeft> chip, IWorld* world, Vector2& position); MoveFloorRightLeft(MoveFloorRightLeft& chip, IWorld* world, Vector2& position); virtual void set(Vector2& pos); MoveFloorRightLeft& operator = (std::shared_ptr<MoveFloorRightLeft> other) { return MoveFloorRightLeft(other, world_, Vector2(0, 0)); }; private: virtual void onUpdate(float deltaTime)override; virtual void onDraw() const override; virtual void onCollide(Actor& other)override; private: Vector2 defaultPos_; float moveCount_; float moveVelocity; int spriteID_; }; #endif // !MAPCHIP_H_
[ "microbug7@gmail.com" ]
microbug7@gmail.com
dfe0bc8b82ef0d72a0797ecb955018c84d785065
f76e43b84e0b624de8aed0a4b9f9bb0a9be22b92
/src/dag-merger/BufferMaker.cpp
e999aabd23e5eab8f0ac68b8ebfa6bd91b57559a
[]
no_license
hansongfang/idb
8c2603a3b37d55e0f17d9f815c56cfa27b416941
5c160553a83548df30fad5bc125cc4f27b01473f
refs/heads/master
2021-09-13T04:52:29.246968
2018-04-25T05:33:26
2018-04-25T05:33:26
125,979,190
8
2
null
null
null
null
UTF-8
C++
false
false
5,050
cpp
#include "BufferMaker.h" #include "dag-lib/Log.h" #include "dag-lib/ViewPoint.h" #include "dag-lib/ViewFacet.h" #include <time.h> #include <random> #include <boost/filesystem.hpp> #include <boost/serialization/serialization.hpp> #include<boost/serialization/unordered_map.hpp> #include<boost/serialization/set.hpp> #include <boost/archive/text_iarchive.hpp> #include<boost/archive/text_oarchive.hpp> #include <fstream> #include <time.h> #include <math.h> namespace fs = boost::filesystem; BufferMaker::BufferMaker(ModelBase* pModel, DAGCenter* pDagCenter) :_pModel(pModel) ,_pDagCenter(pDagCenter) ,_pViewModel(0) { } BufferMaker::~BufferMaker() { if (_pDagMerger) delete _pDagMerger; if (_dagFanVCache) delete _dagFanVCache; if (_pViewModel) delete _pViewModel; } void BufferMaker::init(int nSplit, int metric) { auto center = _pModel->getCenter3d(); auto radius = _pModel->getRadius(); _pViewModel = new SFViewFacet(center, 3.0*radius, nSplit); _pViewModel->initViewNodes(); auto nDags = _pViewModel->getNumberOfNodes(); _pDagMerger = new DAGMerger(nDags, _pDagCenter,_pViewModel,metric); } void BufferMaker::merge() { while( _pDagMerger->hasQueue() ) { _pDagMerger->mergeTop(); } _pDagMerger->showResult(); } void BufferMaker::updateClusters() { int nNodes = _pViewModel->getNumberOfNodes(); _pDagMerger->updateClusterNbs(_pViewModel->getViewEdges()); std::default_random_engine generator(std::time(0)); std::uniform_int_distribution<unsigned> distribution(0,nNodes-1); int dagId = (int) distribution(generator); int clusterId = _pDagMerger->getClusterId(dagId); auto clusterNbs = _pDagMerger->getClusterNb(clusterId); clusterNbs.insert(clusterId); gLogInfo<<"relax cluster "<<clusterId; // ship from 1-ring to 2-ring for(auto cluster :clusterNbs){ if(cluster == clusterId) continue; std::unordered_map<int, std::set<int>> ignoreClusters; while(_pDagMerger->shipBoundDag(cluster,clusterNbs, ignoreClusters)){} } // ship from center to 1-ring neighbor std::set<int> temp{clusterId}; std::unordered_map<int, std::set<int>> ignoreClusters; while(_pDagMerger->shipBoundDag(clusterId,temp,ignoreClusters)){} _pDagMerger->cleanEmpty(clusterNbs); } int BufferMaker::getNClusters() { return _pDagMerger->getNumberOfClusters(); } void BufferMaker::saveAssign(string cacheDir) const { string fileName = cacheDir +"/assignments.txt"; ofstream ofs(fileName); auto assigns = _pDagMerger->getAssignments(); int nNodes = assigns.size(); auto center = _pModel->getCenter3d(); auto viewNodes = _pViewModel->getNodes(); for(int k=0;k<nNodes;k++){ auto tri = static_cast<const ViewNodeTriangle*>(viewNodes[k])->getTriangle(); auto triVec = (tri.getCenter() - center); triVec.Normalize(); double theta = acos(triVec[2]); double phi = atan2(triVec[1], triVec[0]); if(k != nNodes -1) ofs<< assigns[k]<<" "<< theta<<" "<<phi<<endl; else ofs<< assigns[k]<<" "<< theta<<" "<<phi; } ofs.close(); } // DAGMerger need add getClusterIds // DAGMerger move getClusterDag to public // DAGMerger add clean clusterDag void BufferMaker::vCacheOrder(string outDir) { _dagFanVCache = new DagFanVCache(_pModel->getNumberOfVertices(),_pModel->getNumberOfTriangles(),20); vector<int> clusterIds = _pDagMerger->getClusterIds(); for(auto clusterId : clusterIds){ this->_vCacheOrder(clusterId, outDir); //_pDagMerger->clearClusterDag(clusterId); } } void BufferMaker::_vCacheOrder(int clusterId, string outDir) { // compute DAG // Given a occlude b // change to b--> a from a --> b auto clusterDag = _pDagMerger->getClusterDag(clusterId); auto occGraph = clusterDag->getDagGraph(); auto occMap = occGraph.getDagMap(); DagGraph tempGraph; for(auto it = occMap.cbegin();it!= occMap.cend();it++){ for(auto innerIt = occMap.at(it->first).cbegin();innerIt != occMap.at(it->first).cend();innerIt++){ tempGraph.addEdge(innerIt->first,it->first,innerIt->second); } } auto revertMap = tempGraph.getDagMap(); auto oldIndices = _pModel->getIndices(); _dagFanVCache->init(revertMap,oldIndices); auto newIndices = _dagFanVCache->sort(oldIndices); //log the indices out and render to see the result //save the indices string fileName = outDir +"/Indices_"+to_string(clusterId)+".txt"; gLogInfo<<"save "<<fileName; std::ofstream fout(fileName); for(auto vid : newIndices) fout<<vid<<std::endl; fout.close(); //save the triOrder used in order-upsample auto triOrders = _dagFanVCache->getTriOrder(); fileName = outDir +"/triOrder_"+to_string(clusterId)+".txt"; gLogInfo<<"save "<<fileName; fout.open(fileName); for(auto triId : triOrders) fout<<triId<<std::endl; fout.close(); }
[ "shanaf@ust.hk" ]
shanaf@ust.hk
bf2a301bc1493c0c56cf7538f3051af1edbad9bf
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/multimedia/directx/dinput/diconfig/idftest.h
d557f9b8a05c0eea1966d582b5d5e2a530777260
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
943
h
#ifndef __IDFTEST_H__ #define __IDFTEST_H__ typedef enum _TUI_CONFIGTYPE { TUI_CONFIGTYPE_VIEW, TUI_CONFIGTYPE_EDIT, } TUI_CONFIGTYPE; typedef enum _TUI_VIA { TUI_VIA_DI, TUI_VIA_CCI, } TUI_VIA; typedef enum _TUI_DISPLAY { TUI_DISPLAY_GDI, TUI_DISPLAY_DDRAW, TUI_DISPLAY_D3D, } TUI_DISPLAY; typedef struct _TESTCONFIGUIPARAMS { DWORD dwSize; TUI_VIA eVia; TUI_DISPLAY eDisplay; TUI_CONFIGTYPE eConfigType; int nNumAcFors; LPCWSTR lpwszUserNames; int nColorScheme; BOOL bEditLayout; WCHAR wszErrorText[MAX_PATH]; } TESTCONFIGUIPARAMS, FAR *LPTESTCONFIGUIPARAMS; class IDirectInputConfigUITest : public IUnknown { public: //IUnknown fns STDMETHOD (QueryInterface) (REFIID iid, LPVOID *ppv) PURE; STDMETHOD_(ULONG, AddRef) () PURE; STDMETHOD_(ULONG, Release) () PURE; //own fns STDMETHOD (TestConfigUI) (LPTESTCONFIGUIPARAMS params) PURE; }; #endif //__IDFTEST_H__se
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
3490709c9d10c5f3a47928787cb12434bb27185e
e20b7293bba88babbd9b18ac731a2215cfac2c51
/src/qt/test/uritests.cpp
797bddb411771864f0d91c9a71c10f3a1b233258
[ "MIT" ]
permissive
thachpv91/hanhcoin-clone
af57bcc042e3584fdaad2b585f32daf83153910d
d7bd7f4b88066d4a4ca545857db59ba673103af5
refs/heads/master
2020-06-23T14:27:56.971235
2016-11-24T06:59:38
2016-11-24T06:59:38
74,646,122
0
0
null
null
null
null
UTF-8
C++
false
false
2,853
cpp
#include "uritests.h" #include "../guiutil.h" #include "../walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?label=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString("Wikipedia Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=100&label=Wikipedia Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Wikipedia Example")); uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("hanhcoin://LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address", &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); // We currently don't implement the message parameter (ok, yea, we break spec...) uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-message=Wikipedia Example Address")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000.0&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); }
[ "thachphanvan@gmail.com" ]
thachphanvan@gmail.com
900979ef0cd13453fcfc9d446a6dc5ccd5857ad0
73f70fa0176d4b40fe88f146fa12de5cf18b9c5f
/designPatterns/singleton/multiton.cpp
d71cd6fe2ecfe4b52754d88cd22e85ca0071d90d
[]
no_license
MichalDUnda/Cpp
93faf69e46b5f9155825addc447decdd0041b3bc
77bfabe04ffd47a514b98adf66b2d943cd2d6a40
refs/heads/master
2023-07-13T23:08:50.327335
2023-07-03T08:11:15
2023-07-03T08:11:15
384,334,021
0
0
null
null
null
null
UTF-8
C++
false
false
1,255
cpp
#include <map> #include <memory> #include <iostream> using namespace std; //helper enum class for instances of multitone enum class Importance { primary, secondary, tertiary }; template <typename T, typename Key = std::string> class Multiton { public: static shared_ptr<T> get(const Key& key) { if(const auto it = instances.find(key); it != instances.end()) { return it->second; } auto instance = make_shared<T>(); instances[key] = instance; return instance; } protected: Multiton() = default; virtual ~Multiton() = default; private: static map<Key, shared_ptr<T>> instances; }; template <typename T, typename Key> map<Key, shared_ptr<T>> Multiton<T, Key>::instances; class Printer { public: Printer() { ++Printer::totalInstanceCount; cout << "A total of " << Printer::totalInstanceCount << " instances created so far\n"; } private: static int totalInstanceCount; }; int Printer::totalInstanceCount = 0; int main() { using mt = Multiton<Printer, Importance>; auto main = mt::get(Importance::primary); auto aux = mt::get(Importance::secondary); auto aux2 = mt::get(Importance::secondary); }
[ "michal.dundo@gmail.com" ]
michal.dundo@gmail.com
98bf97e3e889e9da3b0bd53fdddd837f18f57695
5ae01ab82fcdedbdd70707b825313c40fb373fa3
/src/evaluators/Charon_ThermodiffCoeff_Default_impl.hpp
617a9633bd95bb0b77c5b7f3fd840f93ae94f5d3
[]
no_license
worthenmanufacturing/tcad-charon
efc19f770252656ecf0850e7bc4e78fa4d62cf9e
37f103306952a08d0e769767fe9391716246a83d
refs/heads/main
2023-08-23T02:39:38.472864
2021-10-29T20:15:15
2021-10-29T20:15:15
488,068,897
0
0
null
2022-05-03T03:44:45
2022-05-03T03:44:45
null
UTF-8
C++
false
false
4,873
hpp
#ifndef CHARON_THERMODIFFCOEFF_DEFAULT_IMPL_HPP #define CHARON_THERMODIFFCOEFF_DEFAULT_IMPL_HPP #include <cmath> #include "Panzer_Workset.hpp" #include "Panzer_Workset_Utilities.hpp" #include "Panzer_IntegrationRule.hpp" #include "Panzer_BasisIRLayout.hpp" #include "Charon_Names.hpp" #include "Charon_Physical_Constants.hpp" /* The model implements the ion thermodiffusion coefficient as D_{Ts} = u_{s} * T_{s} * S_{s} with all quantities in scaled units. This model is used when "Ion Thermodiffusion Coefficient" is not specified in the input xml file for DDIonLattice simulations. It is applicable to ions/vacancies only, neither electrons nor holes. */ namespace charon { /////////////////////////////////////////////////////////////////////////////// // // Constructor // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> ThermodiffCoeff_Default<EvalT, Traits>:: ThermodiffCoeff_Default( const Teuchos::ParameterList& p) { using std::string; using Teuchos::RCP; using PHX::DataLayout; using PHX::MDField; using panzer::IntegrationRule; using panzer::BasisIRLayout; using Teuchos::ParameterList; RCP<Teuchos::ParameterList> valid_params = this->getValidParameters(); p.validateParameters(*valid_params); const charon::Names& n = *(p.get< Teuchos::RCP<const charon::Names> >("Names")); // retrieve data layout RCP<DataLayout> scalar = p.get< RCP<DataLayout> >("Data Layout"); num_points = scalar->dimension(1); num_edges = num_points; // initialization // input from closure model factory isEdgedl = p.get<bool>("Is Edge Data Layout"); // retrieve edge data layout if isEdgedl = true RCP<DataLayout> output_dl = scalar; if (isEdgedl) { RCP<BasisIRLayout> basis = p.get<RCP<BasisIRLayout> >("Basis"); RCP<const panzer::CellTopologyInfo> cellTopoInfo = basis->getCellTopologyInfo(); output_dl = cellTopoInfo->edge_scalar; num_edges = output_dl->dimension(1); cellType = cellTopoInfo->getCellTopology(); } // evaluated field thermodiff_coeff = MDField<ScalarT,Cell,Point>(n.field.ion_thermodiff_coeff,output_dl); this->addEvaluatedField(thermodiff_coeff); // dependent fields mobility = MDField<const ScalarT,Cell,Point>(n.field.ion_mobility,output_dl); soret_coeff = MDField<const ScalarT,Cell,Point>(n.field.ion_soret_coeff,output_dl); latt_temp = MDField<const ScalarT,Cell,Point>(n.field.latt_temp,scalar); this->addDependentField(mobility); this->addDependentField(soret_coeff); this->addDependentField(latt_temp); std::string name = "Thermodiffusion_Coefficient_Default"; this->setName(name); } /////////////////////////////////////////////////////////////////////////////// // // evaluateFields() // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> void ThermodiffCoeff_Default<EvalT, Traits>:: evaluateFields( typename Traits::EvalData workset) { using panzer::index_t; if (isEdgedl) // evaluate thermodiff. coeff. at edge midpoints { for (index_t cell = 0; cell < workset.num_cells; ++cell) { for (int edge = 0; edge < num_edges; ++edge) { // get local node ids: first index 1 for edge (0 for vertex, 2 for face, 3 for volume) int node0 = cellType->getNodeMap(1,edge,0); int node1 = cellType->getNodeMap(1,edge,1); const ScalarT& latt = (latt_temp(cell,node0) + latt_temp(cell,node1)) / 2.0; // scaled const ScalarT& mob = mobility(cell,edge); // scaled const ScalarT& soret = soret_coeff(cell,edge); thermodiff_coeff(cell,edge) = mob * latt * soret; } } } else // evaluate thermodiff. coeff. at IP or BASIS points { for (index_t cell = 0; cell < workset.num_cells; ++cell) { for (int point = 0; point < num_points; ++point) { const ScalarT& mob = mobility(cell,point); // scaled const ScalarT& soret = soret_coeff(cell,point); const ScalarT& latt = latt_temp(cell,point); thermodiff_coeff(cell,point) = mob * latt * soret; } } } } /////////////////////////////////////////////////////////////////////////////// // // getValidParameters() // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> Teuchos::RCP<Teuchos::ParameterList> ThermodiffCoeff_Default<EvalT, Traits>::getValidParameters() const { Teuchos::RCP<Teuchos::ParameterList> p = Teuchos::rcp(new Teuchos::ParameterList); Teuchos::RCP<const charon::Names> n; p->set("Names", n); Teuchos::RCP<PHX::DataLayout> dl; p->set("Data Layout", dl); p->set<bool>("Is Edge Data Layout", false); Teuchos::RCP<panzer::BasisIRLayout> basis; p->set("Basis", basis); return p; } } #endif
[ "juan@tcad.com" ]
juan@tcad.com
803cb938a6e7bc3ca561cda88d7a10aa5d11e631
90af79681ba010c6a2a0f4da3f04c175c5805180
/C++_Basic/005继承重载等/三目运算符.cpp
81372082cad0c9025f191e6833e523890ce0a07a
[]
no_license
minxin126/C_Basic
a184c2e6902397dfff99e1406b912caa3a894a20
2225a66bd3826c81658a86f3cbee4bb70a3014c6
refs/heads/master
2021-07-14T20:23:14.691028
2020-06-26T14:10:13
2020-06-26T14:10:13
177,624,168
1
2
null
2019-03-29T16:49:51
2019-03-25T16:28:49
C++
GB18030
C++
false
false
294
cpp
#include<iostream> using namespace std; int main() { int a = 10; int b = 20; (a < b ? a : b)=30; //C++中三目运算符可以作为左值,返回的是变量本身。 cout << "a=" << a << endl; //左值是有内存空间的,寄存器没有内存空间。 cout << "b=" << b << endl; }
[ "359676107@qq.com" ]
359676107@qq.com
0495eeb126da1679a24b306efe5f4323feecf691
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/inetsrv/iis/iisrearc/iisplus/ulatq/ipm_io_c.cxx
ea88b141030c06bf486a82d7bca0ea606b878895
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,057
cxx
/*++ Copyright (c) 1999 Microsoft Corporation Module Name: ipm_io_c.hxx Abstract: This module contains classes for doing async io in the worker process. Author: Michael Courage (MCourage) 22-Feb-1999 Revision History: --*/ #include "precomp.hxx" #include "ipm.hxx" #include "ipm_io_c.hxx" /** * IPMOverlappedCompletionRoutine() * Callback function provided in ThreadPoolBindIoCompletionCallback. * This function is called by NT thread pool. * * dwErrorCode Error Code * dwNumberOfBytesTransfered Number of Bytes Transfered * lpOverlapped Overlapped structure */ VOID WINAPI IPMOverlappedCompletionRoutine( DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped ) { IO_CONTEXT_C * pIoContext = NULL; HRESULT hr = HRESULT_FROM_WIN32(dwErrorCode); // // get the context object // if (lpOverlapped != NULL) { pIoContext = CONTAINING_RECORD(lpOverlapped, IO_CONTEXT_C, m_Overlapped); } if ( pIoContext != NULL) { WpTrace(WPIPM, ( DBG_CONTEXT, "\n IPMOverlappedCompletionRoutine(%d, %x, pIoContext %x) %s\n", dwNumberOfBytesTransfered, dwErrorCode, pIoContext, pIoContext->m_IoType == IPM_IO_WRITE ? "WRITE" : "READ" )); // // do the notification // switch (pIoContext->m_IoType) { case IPM_IO_WRITE: pIoContext->m_pContext->NotifyWriteCompletion( pIoContext->m_pv, dwNumberOfBytesTransfered, hr ); break; case IPM_IO_READ: pIoContext->m_pContext->NotifyReadCompletion( pIoContext->m_pv, dwNumberOfBytesTransfered, hr ); break; default: DBG_ASSERT(FALSE); break; } delete pIoContext; } return; } /** * * Routine Description: * * * Creates an i/o handler * * Arguments: * * hPipe - A handle to the named pipe to be handled * ppPipeIoHandler - receives a pointer to the handler on success * * Return Value: * * HRESULT */ HRESULT IO_FACTORY_C::CreatePipeIoHandler( IN HANDLE hPipe, OUT PIPE_IO_HANDLER ** ppPipeIoHandler ) { HRESULT hr = S_OK; IO_HANDLER_C * pHandler; // // create the object // pHandler = new IO_HANDLER_C(hPipe); if (pHandler) { BOOL fBind; // // bind handle to completion port // fBind = ThreadPoolBindIoCompletionCallback( pHandler->GetAsyncHandle(), IPMOverlappedCompletionRoutine, 0 ); if (fBind) { *ppPipeIoHandler = pHandler; InterlockedIncrement(&m_cPipes); pHandler->Reference(); WpTrace(WPIPM, ( DBG_CONTEXT, "Created IO_HANDLER_C (%x) - m_cPipes = %d\n", pHandler, m_cPipes )); } else { // Error in XspBindIoCompletionCallback() LONG rc = GetLastError(); delete pHandler; pHandler = NULL; WpTrace(WPIPM, (DBG_CONTEXT, "Create IO_HANDLER_C failed, %d\n", rc)); hr = HRESULT_FROM_WIN32(rc); } } else { hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); } return hr; } /** * * Routine Description: * * Closes an i/o handler * * Arguments: * * pPipeIoHandler - pointer to the handler to be closed * * Return Value: * * HRESULT */ HRESULT IO_FACTORY_C::ClosePipeIoHandler( IN PIPE_IO_HANDLER * pPipeIoHandler ) { IO_HANDLER_C * pIoHandler = (IO_HANDLER_C *) pPipeIoHandler; LONG cPipes; if (pIoHandler) { cPipes = InterlockedDecrement(&m_cPipes); WpTrace(WPIPM, ( DBG_CONTEXT, "Closed IO_HANDLER_C (%x) - m_cPipes = %d\n", pPipeIoHandler, m_cPipes )); DBG_ASSERT( cPipes >= 0 ); pIoHandler->Dereference(); return S_OK; } else { return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } } /** * Disconnect() * Routine Description: * * Disconnects the named pipe * * Arguments: * * None. * * Return Value: * * HRESULT * */ HRESULT IO_HANDLER_C::Disconnect( VOID ) { HRESULT hr = S_OK; CheckSignature(); if (!CloseHandle(GetHandle())) { hr = HRESULT_FROM_WIN32(GetLastError()); } return hr; } /** * *Routine Description: * * Writes data to the pipe * *Arguments: * * pContext - the context to be notified on completion * pv - a parameter passed to the context * pBuff - the data to send * cbBuff - number of bytes in the data * *Return Value: * * HRESULT */ HRESULT IO_HANDLER_C::Write( IN IO_CONTEXT * pContext, IN PVOID pv, IN const BYTE * pBuff, IN DWORD cbBuff ) { HRESULT hr = S_OK; IO_CONTEXT_C * pIoContext; CheckSignature(); // // create a context // pIoContext = new IO_CONTEXT_C; if (pIoContext) { pIoContext->m_pContext = pContext; pIoContext->m_pv = pv; pIoContext->m_IoType = IPM_IO_WRITE; memset(&pIoContext->m_Overlapped, 0, sizeof(OVERLAPPED)); Reference(); // // write to the pipe // hr = IpmWriteFile( GetHandle(), (PVOID) pBuff, cbBuff, &pIoContext->m_Overlapped ); if (FAILED(hr)) { Dereference(); } } else { hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); } if (FAILED(hr)) { delete pIoContext; } return hr; } /** * *Routine Description: * * Reads data from the pipe * *Arguments: * * pContext - the context to be notified on completion * pv - a parameter passed to the context * pBuff - the buffer that receives the data * cbBuff - size of the buffer * *Return Value: * * HRESULT */ HRESULT IO_HANDLER_C::Read( IN IO_CONTEXT * pContext, IN PVOID pv, IN BYTE * pBuff, IN DWORD cbBuff ) { HRESULT hr = S_OK; IO_CONTEXT_C * pIoContext; CheckSignature(); // // create a context // pIoContext = new IO_CONTEXT_C; if (pIoContext) { pIoContext->m_pContext = pContext; pIoContext->m_pv = pv; pIoContext->m_IoType = IPM_IO_READ; memset(&pIoContext->m_Overlapped, 0, sizeof(OVERLAPPED)); Reference(); // // read from the pipe // hr = IpmReadFile( GetHandle(), pBuff, cbBuff, &pIoContext->m_Overlapped ); if (FAILED(hr)) { Dereference(); } } else { hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); } if (FAILED(hr)) { delete pIoContext; } return hr; } // // end ipm_io_c.cxx //
[ "112426112@qq.com" ]
112426112@qq.com
3b899af5d815f9b22371cc1977a7f604e8bc4d85
21f5356e9fd0b3ab9ee7a5c54e30fd94bb660ee4
/com/win32comext/adsi/src/PyADSIUtil.cpp
069877b6e2c4aace1e8b10f3b7a9c7cbd9a4ffca
[]
no_license
chevah/pywin32
90850232a557ecf054bc316e324aaf60188f2cca
d4ff0b440147ab65f1945991e81163fb1cf1ceaf
refs/heads/master
2020-03-29T09:46:04.465546
2014-10-24T09:11:17
2014-10-24T09:11:17
25,680,336
5
1
null
null
null
null
UTF-8
C++
false
false
21,345
cpp
// @doc #include "Python.h" #include "pyerrors.h" // for PyErr_Warn in 2.5... #include "Windows.h" #include "PyWinTypes.h" #include "PythonCOM.h" #include "PyADSIUtil.h" #include "structmember.h" #include "wchar.h" BOOL GetADSIErrorString( HRESULT hr, WCHAR *buf, int nchars ); PyObject *OleSetADSIError(HRESULT hr, IUnknown *pUnk, REFIID iid) { // If the HRESULT is an ADSI one, we do things differently! if (hr & 0x00005000) { WCHAR szErrorBuf[MAX_PATH] = {0}; WCHAR szNameBuf[MAX_PATH] = {0}; DWORD dwErrCode = 0; ADsGetLastError( &dwErrCode, szErrorBuf, MAX_PATH-1, szNameBuf, MAX_PATH-1); if (dwErrCode == 0) dwErrCode = hr; if (!szErrorBuf[0]) GetADSIErrorString( hr, szErrorBuf, MAX_PATH-1); // Trim trailing /r/n WCHAR *szEnd = szErrorBuf + wcslen(szErrorBuf) - 1; while (szEnd > szErrorBuf && (*szEnd == L'\r' || *szEnd == L'\n')) *szEnd-- = L'\0'; // Only do this if we have a useful message - otherwise // let the default handling do the best it can. if (szErrorBuf[0]) { EXCEPINFO info; memset(&info, 0, sizeof(info)); info.scode = dwErrCode; info.bstrSource = SysAllocString(szNameBuf); info.bstrDescription = SysAllocString(szErrorBuf); // Technically, we probably should return DISP_E_EXCEPTION so we // appear to follow COM's rules - however, we really dont // _need_ to (as only Python sees this result), and having the native // HRESULT is preferable. return PyCom_BuildPyExceptionFromEXCEPINFO(dwErrCode, &info); } } if (HRESULT_FACILITY(hr)==FACILITY_WIN32) { //Get extended error value. WCHAR szErrorBuf[MAX_PATH] = {0}; WCHAR szNameBuf[MAX_PATH] = {0}; DWORD dwErrCode = 0; ADsGetLastError( &dwErrCode, szErrorBuf, MAX_PATH-1, szNameBuf, MAX_PATH-1); // Only do this if we have a useful message - otherwise // let the default handling do the best it can. if (dwErrCode == 0) dwErrCode = hr; if (szErrorBuf[0]) { EXCEPINFO info; memset(&info, 0, sizeof(info)); info.scode = dwErrCode; info.bstrSource = SysAllocString(szNameBuf); info.bstrDescription = SysAllocString(szErrorBuf); // Technically, we probably should return DISP_E_EXCEPTION so we // appear to follow COM's rules - however, we really dont // _need_ to (as only Python sees this result), and having the native // HRESULT is preferable. return PyCom_BuildPyExceptionFromEXCEPINFO(dwErrCode, &info); } } // Do the normal thing. return PyCom_BuildPyException(hr, pUnk, iid); } // @object PyADSVALUE|A tuple: // @tupleitem 0|object|value|The value as a Python object. // @tupleitem 1|int|type|The AD type of the value. PyObject *PyADSIObject_FromADSVALUE(ADSVALUE &v) { PyObject *ob = NULL; switch (v.dwType) { case ADSTYPE_DN_STRING: ob = PyWinObject_FromWCHAR(v.DNString); break; case ADSTYPE_CASE_EXACT_STRING: ob = PyWinObject_FromWCHAR(v.CaseExactString); break; case ADSTYPE_CASE_IGNORE_STRING: ob = PyWinObject_FromWCHAR(v.CaseIgnoreString); break; case ADSTYPE_PRINTABLE_STRING: ob = PyWinObject_FromWCHAR(v.PrintableString); break; case ADSTYPE_NUMERIC_STRING: ob = PyWinObject_FromWCHAR(v.NumericString); break; case ADSTYPE_BOOLEAN: ob = v.Boolean ? Py_True : Py_False; Py_INCREF(ob); break; case ADSTYPE_INTEGER: ob = PyInt_FromLong(v.Integer); break; case ADSTYPE_OCTET_STRING: { void *buf; DWORD bufSize = v.OctetString.dwLength; if (!(ob=PyBuffer_New(bufSize))) return NULL; if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){ Py_DECREF(ob); return NULL; } memcpy(buf, v.OctetString.lpValue, bufSize); } break; case ADSTYPE_UTC_TIME: ob = PyWinObject_FromSYSTEMTIME(v.UTCTime); break; case ADSTYPE_LARGE_INTEGER: ob = PyWinObject_FromLARGE_INTEGER(v.LargeInteger); break; case ADSTYPE_OBJECT_CLASS: ob = PyWinObject_FromWCHAR(v.ClassName); break; case ADSTYPE_PROV_SPECIFIC: { void *buf; DWORD bufSize = v.ProviderSpecific.dwLength; if (!(ob=PyBuffer_New(bufSize))) return NULL; if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){ Py_DECREF(ob); return NULL; } memcpy(buf, v.ProviderSpecific.lpValue, bufSize); break; } case ADSTYPE_NT_SECURITY_DESCRIPTOR: { // Get a pointer to the security descriptor. PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)(v.SecurityDescriptor.lpValue); DWORD SDSize = v.SecurityDescriptor.dwLength; // eeek - we don't pass the length - pywintypes relies on // GetSecurityDescriptorLength - make noise if this may bite us. if (SDSize != GetSecurityDescriptorLength(pSD)) PyErr_Warn(PyExc_RuntimeWarning, "Security-descriptor size mis-match"); ob = PyWinObject_FromSECURITY_DESCRIPTOR(pSD); break; } default: { char msg[100]; sprintf(msg, "Unknown ADS type code 0x%x - None will be returned", v.dwType); PyErr_Warn(PyExc_RuntimeWarning, msg); ob = Py_None; Py_INCREF(ob); } } if (ob==NULL) return NULL; PyObject *ret = Py_BuildValue("Oi", ob, (int)v.dwType); Py_DECREF(ob); return ret; } BOOL PyADSIObject_AsTypedValue(PyObject *val, ADSVALUE &v) { BOOL ok = TRUE; switch (v.dwType) { // OK - get lazy - we know its a union! case ADSTYPE_DN_STRING: case ADSTYPE_CASE_EXACT_STRING: case ADSTYPE_CASE_IGNORE_STRING: case ADSTYPE_PRINTABLE_STRING: case ADSTYPE_NUMERIC_STRING: case ADSTYPE_OBJECT_CLASS: ok = PyWinObject_AsWCHAR(val, &v.DNString, FALSE); break; case ADSTYPE_BOOLEAN: v.Boolean = PyInt_AsLong(val); break; case ADSTYPE_INTEGER: v.Integer = PyInt_AsLong(val); break; case ADSTYPE_UTC_TIME: ok = PyWinObject_AsSYSTEMTIME(val, &v.UTCTime); break; case ADSTYPE_LARGE_INTEGER: ok = PyWinObject_AsLARGE_INTEGER(val, &v.LargeInteger); break; default: PyErr_SetString(PyExc_TypeError, "Cant convert to this type"); return FALSE; } return ok; } BOOL PyADSIObject_AsADSVALUE(PyObject *ob, ADSVALUE &v) { if (!PyTuple_Check(ob) || PyTuple_Size(ob) < 1 || PyTuple_Size(ob)>2) { PyErr_SetString(PyExc_ValueError, "ADSVALUE must be a tuple of (value, type) (but type may be None or omitted)"); return FALSE; } PyObject *val = PyTuple_GET_ITEM(ob, 0); PyObject *obtype = NULL; DWORD dwType; if (PyTuple_Size(ob)>1) obtype = PyTuple_GET_ITEM(ob, 1); if (obtype==NULL || obtype == Py_None) { if (PyString_Check(val) || PyUnicode_Check(val)) dwType = ADSTYPE_PRINTABLE_STRING; else if (val==Py_True || val==Py_False) dwType = ADSTYPE_BOOLEAN; else if (PyInt_Check(val)) dwType = ADSTYPE_INTEGER; else if (PyWinTime_Check(val)) dwType = ADSTYPE_UTC_TIME; else { PyErr_SetString(PyExc_ValueError, "No type given, and can't deduce it!"); return FALSE; } } else if (PyInt_Check(obtype)) dwType = PyInt_AsLong(obtype); else { PyErr_SetString(PyExc_TypeError, "The type specified must be None or a string"); return FALSE; } v.dwType = (ADSTYPE)dwType; return PyADSIObject_AsTypedValue(val, v); } void PyADSIObject_FreeADSVALUE(ADSVALUE &v) { switch (v.dwType) { case ADSTYPE_DN_STRING: case ADSTYPE_CASE_EXACT_STRING: case ADSTYPE_CASE_IGNORE_STRING: case ADSTYPE_PRINTABLE_STRING: case ADSTYPE_NUMERIC_STRING: case ADSTYPE_OBJECT_CLASS: PyWinObject_FreeWCHAR(v.DNString); default: ; } // force 'null' reset if called again. v.dwType = ADSTYPE_INTEGER; v.Integer = 0; } // Helpers for passing arrays of Unicode around. BOOL PyADSI_MakeNames(PyObject *obNames, WCHAR ***names, DWORD *pcnames) { if (!PySequence_Check(obNames)) { PyErr_SetString(PyExc_TypeError, "names must be a sequence of strings"); return FALSE; } *names = NULL; int cnames = PySequence_Length(obNames); WCHAR **buf = (WCHAR **)malloc(cnames * sizeof(WCHAR *)); if (buf==NULL) { PyErr_NoMemory(); return FALSE; } memset(buf, 0, cnames * sizeof(WCHAR *)); int i=0; for (i=0;i<cnames;i++) { PyObject *ob = PySequence_GetItem(obNames, i); if (ob==NULL) goto done; BOOL ok = PyWinObject_AsWCHAR(ob, &buf[i], FALSE); Py_DECREF(ob); if (!ok) goto done; } *names = buf; *pcnames = cnames; done: if (*names==NULL) { PyADSI_FreeNames(buf, cnames); } return (*names != NULL); } void PyADSI_FreeNames(WCHAR **names, DWORD cnames) { for (int i=0;i<(int)cnames;i++) if (names[i] != NULL) PyWinObject_FreeWCHAR(names[i]); free(names); } // @object PyADS_OBJECT_INFO|Represents a ADS_OBJECT_INFO structure. class PyADS_OBJECT_INFO : public PyObject { public: PyADS_OBJECT_INFO(void) { ob_type = &Type; _Py_NewReference(this); obRDN = obObjectDN = obParentDN = obClassName = NULL; } PyADS_OBJECT_INFO(const ADS_OBJECT_INFO *pInfo) { ob_type = &Type; _Py_NewReference(this); obRDN = PyWinObject_FromWCHAR(pInfo->pszRDN); obObjectDN = PyWinObject_FromWCHAR(pInfo->pszObjectDN); obParentDN = PyWinObject_FromWCHAR(pInfo->pszParentDN); obClassName = PyWinObject_FromWCHAR(pInfo->pszClassName); } ~PyADS_OBJECT_INFO() { Py_XDECREF(obRDN); Py_XDECREF(obObjectDN); Py_XDECREF(obParentDN); Py_XDECREF(obClassName); } /* Python support */ static void deallocFunc(PyObject *ob) { delete (PyADS_OBJECT_INFO *)ob; } static struct PyMemberDef memberlist[]; static PyTypeObject PyADS_OBJECT_INFO::Type; protected: PyObject *obRDN, *obObjectDN, *obParentDN, *obClassName; }; PyTypeObject PyADS_OBJECT_INFO::Type = { PYWIN_OBJECT_HEAD "PyADS_OBJECT_INFO", sizeof(PyADS_OBJECT_INFO), 0, PyADS_OBJECT_INFO::deallocFunc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ }; #define OFF(e) offsetof(PyADS_OBJECT_INFO, e) /*static*/ struct PyMemberDef PyADS_OBJECT_INFO::memberlist[] = { {"RDN", T_OBJECT, OFF(obRDN)}, // @prop unicode|RDN|The name {"ObjectDN", T_OBJECT, OFF(obObjectDN)}, // @prop unicode|ObjectDN| {"ParentDN", T_OBJECT, OFF(obParentDN)}, // @prop unicode|ParentDN| {"ClassName", T_OBJECT, OFF(obClassName)}, // @prop unicode|ClassName| {NULL} }; PyObject *PyADSIObject_FromADS_OBJECT_INFO(ADS_OBJECT_INFO *info) { return new PyADS_OBJECT_INFO(info); } // @object PyADS_ATTR_INFO|Represents a ADS_ATTR_INFO structure. class PyADS_ATTR_INFO : public PyObject { public: PyADS_ATTR_INFO(void) { ob_type = &Type; _Py_NewReference(this); dwControlCode = 0; dwADsType = ADSTYPE_INVALID; obValues = PyList_New(0); obName = Py_None; Py_INCREF(obName); bufName = NULL; bufValues = NULL; } PyADS_ATTR_INFO(const ADS_ATTR_INFO *pInfo) { ob_type = &Type; _Py_NewReference(this); bufName = NULL; bufValues = NULL; obName = PyWinObject_FromWCHAR(pInfo->pszAttrName); dwControlCode = pInfo->dwControlCode; dwADsType = pInfo->dwADsType; obValues = PyList_New(pInfo->dwNumValues); if (obValues) { for (DWORD i=0;i<pInfo->dwNumValues;i++) { PyList_SET_ITEM(obValues, i, PyADSIObject_FromADSVALUE(pInfo->pADsValues[i])); } } } ~PyADS_ATTR_INFO() { InvalidateName(); InvalidateValues(); Py_XDECREF(obName); Py_XDECREF(obValues); } void InvalidateName(void) { if (bufName) { PyWinObject_FreeWCHAR(bufName); bufName = NULL; } } void InvalidateValues(void) { if (bufValues) { for (int i=0;i<bufValuesNum;i++) { PyADSIObject_FreeADSVALUE(bufValues[i]); } free(bufValues); bufValues = NULL; } } BOOL FillADS_ATTR_INFO( ADS_ATTR_INFO *pInfo) { pInfo->dwControlCode = dwControlCode; pInfo->dwADsType = dwADsType; if (bufName == NULL) { if (!PyWinObject_AsWCHAR(obName, &bufName, FALSE)) return FALSE; } pInfo->pszAttrName = bufName; if (bufValues == NULL) { if (!PySequence_Check(obValues)) { PyErr_SetString(PyExc_TypeError, "Values attribute must be a sequence!"); return FALSE; } int n = bufValuesNum = PySequence_Length(obValues); bufValues = (ADSVALUE *)malloc(n * sizeof(ADSVALUE)); memset(bufValues, 0, n * sizeof(ADSVALUE)); if (bufValues==NULL) { PyErr_NoMemory(); return FALSE; } for (int i=0;i<n;i++) { PyObject *ob = PySequence_GetItem(obValues, i); if (ob==NULL) return FALSE; BOOL ok = PyADSIObject_AsADSVALUE(ob, bufValues[i]); Py_DECREF(ob); if (!ok) return FALSE; } } pInfo->pADsValues = bufValues; pInfo->dwNumValues = bufValuesNum; return TRUE; } /* Python support */ static void deallocFunc(PyObject *ob) { delete (PyADS_ATTR_INFO *)ob; } static PyObject *getattro(PyObject *self, PyObject *obname) { char *name=PYWIN_ATTR_CONVERT(obname); if (name==NULL) return NULL; if (strcmp(name, "__members__")==0) { PyObject *ret = PyList_New(4); if (ret) { PyList_SET_ITEM(ret, 0, PyString_FromString("AttrName")); PyList_SET_ITEM(ret, 1, PyString_FromString("ControlCode")); PyList_SET_ITEM(ret, 2, PyString_FromString("ADsType")); PyList_SET_ITEM(ret, 3, PyString_FromString("Values")); } return ret; } if (strcmp(name, "Values")==0) { PyObject *ret = ((PyADS_ATTR_INFO *)self)->obValues ? ((PyADS_ATTR_INFO *)self)->obValues : Py_None; Py_INCREF(ret); return ret; } return PyObject_GenericGetAttr(self, obname); } //#pragma warning( disable : 4251 ) static struct PyMemberDef memberlist[]; //#pragma warning( default : 4251 ) static PyTypeObject PyADS_ATTR_INFO::Type; protected: DWORD dwControlCode; ADSTYPE dwADsType; PyObject *obName; PyObject *obValues; WCHAR *bufName; ADSVALUE *bufValues; int bufValuesNum; }; PyTypeObject PyADS_ATTR_INFO::Type = { PYWIN_OBJECT_HEAD "PyADS_ATTR_INFO", sizeof(PyADS_ATTR_INFO), 0, PyADS_ATTR_INFO::deallocFunc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, 0, /* tp_call */ 0, /* tp_str */ PyADS_ATTR_INFO::getattro, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ }; #undef OFF #define OFF(e) offsetof(PyADS_ATTR_INFO, e) /*static*/ struct PyMemberDef PyADS_ATTR_INFO::memberlist[] = { {"AttrName", T_OBJECT, OFF(obName)}, // @prop unicode|AttrName|The name {"ControlCode", T_INT, OFF(dwControlCode)}, // @prop integer|ControlCode| {"ADsType", T_INT, OFF(dwADsType)}, // @prop integer|ADsType| {NULL} }; // @prop [<o PyADSVALUE>, ...]|Values| PyObject *PyADSIObject_FromADS_ATTR_INFOs(ADS_ATTR_INFO *infos, DWORD cinfos) { PyObject *ret = PyTuple_New(cinfos); for (DWORD i=0;ret != NULL && i<cinfos;i++) { PyObject *n = new PyADS_ATTR_INFO(infos+i); if (n==NULL) { Py_DECREF(ret); ret = NULL; break; } PyTuple_SET_ITEM(ret, (int)i, n); } return ret; } BOOL _Make_ATTR_INFO(PyObject *ob, ADS_ATTR_INFO *pBase, DWORD index) { PyObject *obName, *obValues; ADS_ATTR_INFO *pThis = pBase + index; PyObject *sub = PySequence_GetItem(ob, index); if (!sub) return FALSE; if (!PyArg_ParseTuple(sub, "OllO:ADS_ATTR_INFO tuple", &obName, &pThis->dwControlCode, &pThis->dwADsType, &obValues)) return FALSE; if (!PyWinObject_AsWCHAR(obName, &pThis->pszAttrName, FALSE)) return FALSE; if (!PySequence_Check(obValues)) { PyErr_Format(PyExc_TypeError, "4th item in an ATTR_INFO structure must be a sequence (got %s)", obValues->ob_type->tp_name); return FALSE; } DWORD nValues = PySequence_Length(obValues); pThis->pADsValues = (PADSVALUE)malloc(nValues * sizeof(ADSVALUE)); if (!pThis->pADsValues) { PyErr_NoMemory(); return FALSE; } memset(pThis->pADsValues, 0, nValues * sizeof(ADSVALUE)); pThis->dwNumValues = nValues; DWORD i; BOOL ok; for (i=0;i<nValues;i++) { PyObject *val = PySequence_GetItem(obValues, i); if (!val) return FALSE; pThis->pADsValues[i].dwType = pThis->dwADsType; ok = PyADSIObject_AsTypedValue(val, pThis->pADsValues[i]); Py_DECREF(val); } return TRUE; } void PyADSIObject_FreeADS_ATTR_INFOs(ADS_ATTR_INFO *pval, DWORD cinfos) { if (!pval) return; DWORD i; for (i=0;i<cinfos;i++) { ADS_ATTR_INFO *pThis = pval + i; PyWinObject_FreeWCHAR(pThis->pszAttrName); if (pThis->pADsValues) { DWORD valnum; for (valnum=0;valnum<pThis->dwNumValues;valnum++) PyADSIObject_FreeADSVALUE(pThis->pADsValues[valnum]); free(pThis->pADsValues); } } free(pval); } BOOL PyADSIObject_AsADS_ATTR_INFOs(PyObject *ob, ADS_ATTR_INFO **ppret, DWORD *pcinfos) { if (!PySequence_Check(ob)) { PyErr_SetString(PyExc_TypeError, "ADS_ATTR_INFOs must be a sequence"); return FALSE; } DWORD i; // Use C++ reference to make working with ppret more convenient. ADS_ATTR_INFO *&pret = *ppret; DWORD &nitems = *pcinfos; nitems = PySequence_Length(ob); pret = (PADS_ATTR_INFO)malloc(nitems * sizeof(ADS_ATTR_INFO)); if (!pret) { PyErr_NoMemory(); return FALSE; } memset(pret, 0, nitems * sizeof(ADS_ATTR_INFO)); BOOL ok = TRUE; for (i=0;ok && i<nitems;i++) { ok = _Make_ATTR_INFO(ob, pret, i); } if (!ok && pret) { PyADSIObject_FreeADS_ATTR_INFOs(pret, nitems); pret = 0; nitems = 0; } return ok; } // @object PyADS_SEARCHPREF_INFO|A tuple of: // @tupleitem 0|int|attr_id| // @tupleitem 1|<o PyADSVALUE>|value| void PyADSIObject_FreeADS_SEARCHPREF_INFOs(ADS_SEARCHPREF_INFO *pattr, DWORD cattr) { if (!pattr) return; DWORD i; for (i=0;i<cattr;i++) PyADSIObject_FreeADSVALUE(pattr[i].vValue); free(pattr); } BOOL PyADSIObject_AsADS_SEARCHPREF_INFOs(PyObject *ob, ADS_SEARCHPREF_INFO **ppret, DWORD *pcinfos) { BOOL ret = FALSE; if (!PySequence_Check(ob)) { PyErr_SetString(PyExc_TypeError, "ADS_SEARCHPREF_INFOs must be a sequence"); return FALSE; } // Use C++ reference to make working with ppret more convenient. ADS_SEARCHPREF_INFO *&pret = *ppret; DWORD &nitems = *pcinfos; nitems = PySequence_Length(ob); pret = (ADS_SEARCHPREF_INFO *)malloc(sizeof(ADS_SEARCHPREF_INFO) * nitems); if (!pret) { PyErr_NoMemory(); return NULL; } memset(pret, 0, sizeof(ADS_SEARCHPREF_INFO) * nitems); PyObject *sub = NULL; PyObject *obValue; // no reference DWORD i; for (i=0;i<nitems;i++) { PyObject *sub = PySequence_GetItem(ob, i); if (!sub) goto done; if (!PyArg_ParseTuple(sub, "iO:ADS_SEARCHPREF_INFO tuple", &pret[i].dwSearchPref, &obValue)) goto done; if (!PyADSIObject_AsADSVALUE(obValue, pret[i].vValue)) goto done; Py_DECREF(sub); sub = NULL; } ret = TRUE; done: Py_XDECREF(sub); if (!ret && pret) PyADSIObject_FreeADS_SEARCHPREF_INFOs(pret, nitems); return ret; } /////////////////////////////////////////////////////// // // Error string utility. // // ADSERR.h is built from a message file. // Therefore, there _must_ be a DLL around we can call // FormatMessage with. // However, its not obvious, and this code was cut directly from MSDN. #include "adserr.h" typedef struct tagADSERRMSG { HRESULT hr; LPCWSTR pszError; }ADSERRMSG; #define ADDADSERROR(x) x, L ## #x const ADSERRMSG adsErr[] = { ADDADSERROR(E_ADS_BAD_PATHNAME), ADDADSERROR(E_ADS_INVALID_DOMAIN_OBJECT), ADDADSERROR(E_ADS_INVALID_USER_OBJECT), ADDADSERROR(E_ADS_INVALID_COMPUTER_OBJECT), ADDADSERROR(E_ADS_UNKNOWN_OBJECT), ADDADSERROR(E_ADS_PROPERTY_NOT_SET), ADDADSERROR(E_ADS_PROPERTY_NOT_SUPPORTED), ADDADSERROR(E_ADS_PROPERTY_INVALID), ADDADSERROR(E_ADS_BAD_PARAMETER), ADDADSERROR(E_ADS_OBJECT_UNBOUND), ADDADSERROR(E_ADS_PROPERTY_NOT_MODIFIED), ADDADSERROR(E_ADS_PROPERTY_MODIFIED), ADDADSERROR(E_ADS_CANT_CONVERT_DATATYPE), ADDADSERROR(E_ADS_PROPERTY_NOT_FOUND), ADDADSERROR(E_ADS_OBJECT_EXISTS), ADDADSERROR(E_ADS_SCHEMA_VIOLATION), ADDADSERROR(E_ADS_COLUMN_NOT_SET), ADDADSERROR(E_ADS_INVALID_FILTER), ADDADSERROR(0), }; ///////////////////////////////////////////// // // Error message specific to ADSI // //////////////////////////////////////////// BOOL GetADSIErrorString( HRESULT hr, WCHAR *buf, int nchars ) { if ( hr & 0x00005000 ) { int idx=0; while (adsErr[idx].hr != 0 ) { if ( adsErr[idx].hr == hr ) { wcsncpy(buf, adsErr[idx].pszError, nchars); return TRUE; } idx++; } } buf[0] = L'\0'; return FALSE; }
[ "adi.roiban@chevah.com" ]
adi.roiban@chevah.com
c5d382b88950e00ecb382799cb72d9bdaad953aa
5fe2f231d31d86c2a18ea88303e08b95af94d19b
/line_follower.cpp
97b2b2371faa0e511c2bfd1d4c79ab031bf1b968
[]
no_license
abhishyantkhare/hibike
db608e33b8b98bec48c94e699e674091c2382c51
c5aec317aa2393e8439758392cf12625fad7ca8b
refs/heads/master
2021-01-16T01:07:12.057563
2015-08-27T07:50:01
2015-08-27T07:50:01
42,791,486
1
0
null
null
null
null
UTF-8
C++
false
false
1,156
cpp
#include "hibike_message.h" #define IN_PIN 1 #define CONTROLLER_ID 0 // arbitrarily chosen for now uint32_t data; uint32_t subscriptionDelay; HibikeMessage* m; void setup() { Serial.begin(115200); pinMode(IN_PIN, INPUT); } void loop() { data = digitalRead(IN_PIN); // uncomment the line below for fun data spoofing uint64_t currTime = millis(); data = (uint32_t) (currTime) & 0xFFFFFFFF; if (subscriptionDelay) { SensorUpdate(CONTROLLER_ID, SensorType::LineFollower, sizeof(data), (uint8_t*) &data).send(); delay(subscriptionDelay); } m = receiveHibikeMessage(); if (m) { switch (m->getMessageId()) { case HibikeMessageType::SubscriptionRequest: { subscriptionDelay = ((SubscriptionRequest*) m)->getSubscriptionDelay(); SubscriptionResponse(CONTROLLER_ID).send(); break; } case HibikeMessageType::SubscriptionResponse: case HibikeMessageType::SensorUpdate: case HibikeMessageType::Error: default: // TODO: implement error handling and retries // TODO: implement other message types break; } delete m; } }
[ "vincentdonato@pioneers.berkeley.edu" ]
vincentdonato@pioneers.berkeley.edu
ff4c63f35fb5971280736ca30ce0334040d407db
ac9b37f9523f62c67c819fae44ec5a33e33f23e4
/collatz_conjecture/collatz_OpenMP_MPI_CUDA.cpp
d0961deb8dde7807b851db3f55e060d0231fd54b
[]
no_license
M-Hernandez/Arcane-repo
6fee76d11b634321a40b345875c1ffe90361fe12
bfc0d678fdeccb1cb044882fcbd8a4e87e7b4dbb
refs/heads/master
2021-09-23T11:14:29.370733
2021-09-14T02:52:44
2021-09-14T02:52:44
208,671,875
0
0
null
null
null
null
UTF-8
C++
false
false
3,689
cpp
/* Collatz code for CS 4380 / CS 5351 Copyright (c) 2020 Texas State University. All rights reserved. Redistribution in source or binary form, with or without modification, is *not* permitted. Use in source or binary form, with or without modification, is only permitted for academic use in CS 4380 or CS 5351 at Texas State University. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Author: Martin Burtscher */ #include <cstdio> #include <algorithm> #include <sys/time.h> #include <mpi.h> void GPU_Init(void); void GPU_Exec(const long start, const long stop); int GPU_Fini(void); static int collatz(const long start, const long stop) { // compute sequence lengths int maxlen = 0; #pragma omp parallel for default(none) reduction(max : maxlen) schedule(static,1) for (long i = start; i <= stop; i++) { long val = i; int len = 1; while (val != 1) { len++; if ((val % 2) == 0) { val /= 2; // even } else { val = 3 * val + 1; // odd } } maxlen = std::max(maxlen, len); } // todo: OpenMP code with default(none), a reduction, and a cyclic schedule based on Project 4 return maxlen; } int main(int argc, char *argv[]) { int comm_sz, my_rank; MPI_Init(NULL, NULL); MPI_Comm_size(MPI_COMM_WORLD, &comm_sz); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if(my_rank == 0){ printf("Collatz v1.4\n"); printf("Num of processes: %d\n", comm_sz); } // check command line if (argc != 3) {fprintf(stderr, "USAGE: %s upper_bound cpu_percentage\n", argv[0]); exit(-1);} const long bound = atol(argv[1]); if (bound < 1) {fprintf(stderr, "ERROR: upper_bound must be at least 1\n"); exit(-1);} const int percentage = atoi(argv[2]); if ((percentage < 0) || (percentage > 100)) {fprintf(stderr, "ERROR: cpu_percentage must be between 0 and 100\n"); exit(-1);} const long cpu_start = 1 + my_rank * bound / comm_sz; const long gpu_stop = 1 + (my_rank + 1) * bound / comm_sz; const long my_range = gpu_stop - cpu_start; const long cpu_stop = cpu_start + my_range * percentage / 100; const long gpu_start = cpu_stop; if(my_rank == 0){ printf("upper bound: %ld\n", bound); printf("CPU percentage: %d\n", percentage); } GPU_Init(); // start time timeval start, end; MPI_Barrier(MPI_COMM_WORLD); gettimeofday(&start, NULL); // execute timed code GPU_Exec(gpu_start, gpu_stop); int globalMax; const int cpu_maxlen = collatz(cpu_start, cpu_stop); const int gpu_maxlen = GPU_Fini(); const int maxlen = std::max(cpu_maxlen, gpu_maxlen); MPI_Reduce(&maxlen,&globalMax,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD); // end time gettimeofday(&end, NULL); const double runtime = end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec) / 1000000.0; // print result if(my_rank == 0){ printf("compute time: %.6f s\n", runtime); printf("longest sequence length: %d elements\n", globalMax); } MPI_Finalize(); return 0; }
[ "miguelhernandez@Miguels-MacBook-Pro.local" ]
miguelhernandez@Miguels-MacBook-Pro.local
2b403221cd7fa81d34e98de06844f32e04eb1292
0c80aec0be5a600426006096a5c510c90b3ca949
/HackerRank/Practice/Sorting/Correctness_and_the_Loop_Invariant.cpp
1d00cbd3c0329d062bdd1df5acb329fd8ced5c30
[]
no_license
skywithlight/Algorithms
7b8fd78874afffc8ae7c2775b53d2402cc165e65
06a13fbb73ea1404a7d0eaab56765ec2423f9e07
refs/heads/master
2020-03-23T21:20:04.814645
2018-10-16T03:59:42
2018-10-16T03:59:42
142,098,756
0
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <assert.h> void insertionSort(int N, int arr[]) { int i,j; int value; for(i = 1; i < N; i++) { value = arr[i]; j = i - 1; while(j >= 0 && value < arr[j]) { arr[j+1] = arr[j]; j = j - 1; } arr[j + 1] = value; } for(j = 0;j < N; j++) { printf("%d",arr[j]); printf(" "); } } int main(void) { int N; scanf("%d", &N); int arr[N], i; for(i = 0; i < N; i++) { scanf("%d", &arr[i]); } insertionSort(N, arr); return 0; }
[ "noreply@github.com" ]
skywithlight.noreply@github.com
dc294122141a13c2a1d104495d46351e6fd64ce4
11ac20402a3bde71126f8c6d8734174fbcc409af
/note/test_code/stm/phch_recv.cc
7b66d3babe85148f98307b7db420de3fcd587789
[]
no_license
learning-lte/read-srslte
aa0bb1a0e711b9f6ba2eae65d78e691ea7293889
cfafa1df08a312bf467cb5c72bdc906849c07893
refs/heads/master
2021-10-11T22:57:28.892751
2019-01-30T11:14:05
2019-01-30T11:14:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
528
cc
#include "phch_recv.h" #include <stdio.h> sync_state phy_state; void * run_thread(void){ bool running = true; while(running){ switch(phy_state.run_state()){ case sync_state::CELL_SEARCH: printf("I'm in cell search\n"); phy_state.state_exit(); break; case sync_state::SFN_SYNC: printf("I'm in sfn_sync\n"); phy_state.state_exit(); break; case sync_state::CAMPING: printf("I'm in camping\n"); break; case sync_state::IDLE: printf("I'm in idle\n"); break; } } }
[ "651558476@qq.com" ]
651558476@qq.com
0cd1228640252d81f06a21c006aa52d318fbb1cd
95c241df67572e94798a216a6b75e2bc1bb17319
/Source.cpp
ee021c97af3ad92830973382c3e7e9e2af661a2b
[]
no_license
xhoic/GameY
8bc0d96ff13643e304d81daea20f7d45d76202d4
85065e407d5e861a903989fb8c0c5292f823456f
refs/heads/main
2023-02-17T21:04:09.183544
2021-01-18T02:36:45
2021-01-18T02:36:45
330,535,092
0
0
null
null
null
null
UTF-8
C++
false
false
2,640
cpp
//Xhoi Caveli #include <iostream> #include <map> #include <set> int main() { int diceNum; std::map<int, int> diceRoll; std::set<int> roll; std::cout << "Enter 5 numbers in range 1 to 6." << std::endl; for (int i = 1; i <= 5; i++) { std::cout << i << ". "; std::cin >> diceNum; while (diceNum < 1 or diceNum >6) { std::cout << "Invalid enty! Reenter a number in range 1 to 6." << std::endl; std::cout << i << ". "; std::cin >> diceNum; } ++diceRoll[diceNum]; } for (const std::pair<int, int>& dice : diceRoll) { roll.insert(dice.first); } if (roll.size() == 1) { std::cout << "Congrats! You have YATHZEE!!!" << std::endl; } else if (roll.size() == 2) { std::map<int, int>::reverse_iterator riter = diceRoll.rbegin(); if (diceRoll.begin()->second == 4 or riter->second == 4) { std::cout << "Congrats! You have 4 of a kind." << std::endl; } else { std::cout << "Congrats! You have a full house." << std::endl; } } else if (roll.size() == 3) { std::map<int, int>::iterator iter = diceRoll.begin(); while (iter != diceRoll.end()) { if (iter->second == 3) { std::cout << "Congrats! You have 3 of a kind!" << std::endl; } else if (iter->second == 2) { std::cout << "Oops! There is nothing!" << std::endl; break; } iter++; } } else if (roll.size() == 4) { bool flag = true; std::map<int, int>::iterator iter = diceRoll.begin(); iter++; std::map<int, int>::iterator iter1 = diceRoll.begin(); while (iter != diceRoll.end()) { if (iter->first != iter1->first + 1) { flag = false; } iter++; iter1++; } if (flag == true) { std::cout << "Congrats! You have a small straight!" << std::endl; } else { std::cout << "Oops! There is nothing!" << std::endl; } } else { bool flag = true; std::map<int, int>::iterator iter = diceRoll.begin(); iter++; std::map<int, int>::iterator iter1 = diceRoll.begin(); while (iter != diceRoll.end()) { if (iter->first != iter1->first + 1) { flag = false; } iter++; iter1++; } if (flag == true) { std::cout << "Congrats! You have a large straight!" << std::endl; } else { flag = true; iter = diceRoll.begin(); iter++; iter1 = diceRoll.begin(); for (int i = 0; i < 3; i++) { if (iter->first != iter1->first + 1) { flag = false; } iter++; iter1++; } if (flag == true) { std::cout << "Congrats! You have a small straight!" << std::endl; } else { std::cout << "Oops! There is nothing!" << std::endl; } } } system("PAUSE"); return 0; }
[ "caveli.xhoi@gmail.com" ]
caveli.xhoi@gmail.com
566e77f8dd6a0cc6aa2ce2669134e1597586548c
fbb6b85ea717ddbbaa149a233213f59369c00780
/src/governance-vote.h
dafbc6e6402f6851b04def7af1c30e45149b7c2d
[ "MIT" ]
permissive
agenanextproject/Agena
bd5368c554a0b0051f8ce98fd39a962e71cb6ec9
562aed54370e2d64921006f0f2e1ee5154c650d9
refs/heads/master
2020-03-21T03:45:36.170961
2018-03-15T18:18:10
2018-03-15T18:18:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,797
h
// Copyright (c) 2014-2017 The Agena Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef GOVERNANCE_VOTE_H #define GOVERNANCE_VOTE_H #include "key.h" #include "primitives/transaction.h" #include <boost/lexical_cast.hpp> using namespace std; class CGovernanceVote; // INTENTION OF MASTERNODES REGARDING ITEM enum vote_outcome_enum_t { VOTE_OUTCOME_NONE = 0, VOTE_OUTCOME_YES = 1, VOTE_OUTCOME_NO = 2, VOTE_OUTCOME_ABSTAIN = 3 }; // SIGNAL VARIOUS THINGS TO HAPPEN: enum vote_signal_enum_t { VOTE_SIGNAL_NONE = 0, VOTE_SIGNAL_FUNDING = 1, // -- fund this object for it's stated amount VOTE_SIGNAL_VALID = 2, // -- this object checks out in sentinel engine VOTE_SIGNAL_DELETE = 3, // -- this object should be deleted from memory entirely VOTE_SIGNAL_ENDORSED = 4, // -- officially endorsed by the network somehow (delegation) VOTE_SIGNAL_NOOP1 = 5, // FOR FURTHER EXPANSION VOTE_SIGNAL_NOOP2 = 6, VOTE_SIGNAL_NOOP3 = 7, VOTE_SIGNAL_NOOP4 = 8, VOTE_SIGNAL_NOOP5 = 9, VOTE_SIGNAL_NOOP6 = 10, VOTE_SIGNAL_NOOP7 = 11, VOTE_SIGNAL_NOOP8 = 12, VOTE_SIGNAL_NOOP9 = 13, VOTE_SIGNAL_NOOP10 = 14, VOTE_SIGNAL_NOOP11 = 15, VOTE_SIGNAL_CUSTOM1 = 16, // SENTINEL CUSTOM ACTIONS VOTE_SIGNAL_CUSTOM2 = 17, // 16-35 VOTE_SIGNAL_CUSTOM3 = 18, VOTE_SIGNAL_CUSTOM4 = 19, VOTE_SIGNAL_CUSTOM5 = 20, VOTE_SIGNAL_CUSTOM6 = 21, VOTE_SIGNAL_CUSTOM7 = 22, VOTE_SIGNAL_CUSTOM8 = 23, VOTE_SIGNAL_CUSTOM9 = 24, VOTE_SIGNAL_CUSTOM10 = 25, VOTE_SIGNAL_CUSTOM11 = 26, VOTE_SIGNAL_CUSTOM12 = 27, VOTE_SIGNAL_CUSTOM13 = 28, VOTE_SIGNAL_CUSTOM14 = 29, VOTE_SIGNAL_CUSTOM15 = 30, VOTE_SIGNAL_CUSTOM16 = 31, VOTE_SIGNAL_CUSTOM17 = 32, VOTE_SIGNAL_CUSTOM18 = 33, VOTE_SIGNAL_CUSTOM19 = 34, VOTE_SIGNAL_CUSTOM20 = 35 }; static const int MAX_SUPPORTED_VOTE_SIGNAL = VOTE_SIGNAL_ENDORSED; /** * Governance Voting * * Static class for accessing governance data */ class CGovernanceVoting { public: static vote_outcome_enum_t ConvertVoteOutcome(std::string strVoteOutcome); static vote_signal_enum_t ConvertVoteSignal(std::string strVoteSignal); static std::string ConvertOutcomeToString(vote_outcome_enum_t nOutcome); static std::string ConvertSignalToString(vote_signal_enum_t nSignal); }; // // CGovernanceVote - Allow a masternode node to vote and broadcast throughout the network // class CGovernanceVote { friend bool operator==(const CGovernanceVote& vote1, const CGovernanceVote& vote2); friend bool operator<(const CGovernanceVote& vote1, const CGovernanceVote& vote2); private: bool fValid; //if the vote is currently valid / counted bool fSynced; //if we've sent this to our peers int nVoteSignal; // see VOTE_ACTIONS above CTxIn vinMasternode; uint256 nParentHash; int nVoteOutcome; // see VOTE_OUTCOMES above int64_t nTime; std::vector<unsigned char> vchSig; public: CGovernanceVote(); CGovernanceVote(CTxIn vinMasternodeIn, uint256 nParentHashIn, vote_signal_enum_t eVoteSignalIn, vote_outcome_enum_t eVoteOutcomeIn); bool IsValid() const { return fValid; } bool IsSynced() const { return fSynced; } int64_t GetTimestamp() const { return nTime; } vote_signal_enum_t GetSignal() const { return vote_signal_enum_t(nVoteSignal); } vote_outcome_enum_t GetOutcome() const { return vote_outcome_enum_t(nVoteOutcome); } const uint256& GetParentHash() const { return nParentHash; } void SetTime(int64_t nTimeIn) { nTime = nTimeIn; } void SetSignature(const std::vector<unsigned char>& vchSigIn) { vchSig = vchSigIn; } bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode); bool IsValid(bool fSignatureCheck) const; void Relay() const; std::string GetVoteString() const { return CGovernanceVoting::ConvertOutcomeToString(GetOutcome()); } CTxIn& GetVinMasternode() { return vinMasternode; } const CTxIn& GetVinMasternode() const { return vinMasternode; } /** * GetHash() * * GET UNIQUE HASH WITH DETERMINISTIC VALUE OF THIS SPECIFIC VOTE */ uint256 GetHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vinMasternode; ss << nParentHash; ss << nVoteSignal; ss << nVoteOutcome; ss << nTime; return ss.GetHash(); } std::string ToString() const { std::ostringstream ostr; ostr << vinMasternode.ToString() << ":" << nTime << ":" << CGovernanceVoting::ConvertOutcomeToString(GetOutcome()) << ":" << CGovernanceVoting::ConvertSignalToString(GetSignal()); return ostr.str(); } /** * GetTypeHash() * * GET HASH WITH DETERMINISTIC VALUE OF MASTERNODE-VIN/PARENT-HASH/VOTE-SIGNAL * * This hash collides with previous masternode votes when they update their votes on governance objects. * With 12.1 there's various types of votes (funding, valid, delete, etc), so this is the deterministic hash * that will collide with the previous vote and allow the system to update. * * -- * * We do not include an outcome, because that can change when a masternode updates their vote from yes to no * on funding a specific project for example. * We do not include a time because it will be updated each time the vote is updated, changing the hash */ uint256 GetTypeHash() const { // CALCULATE HOW TO STORE VOTE IN governance.mapVotes CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vinMasternode; ss << nParentHash; ss << nVoteSignal; // -- no outcome // -- timeless return ss.GetHash(); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(vinMasternode); READWRITE(nParentHash); READWRITE(nVoteOutcome); READWRITE(nVoteSignal); READWRITE(nTime); READWRITE(vchSig); } }; /** * 12.1.1 - CGovernanceVoteManager * ------------------------------- * GetVote(name, yes_no): - caching function - mark last accessed votes - load serialized files from filesystem if needed - calc answer - return result CacheUnused(): - Cache votes if lastused > 12h/24/48/etc */ #endif
[ "agentaproject@gmail.com" ]
agentaproject@gmail.com
16a8823e1d2377f821d4075a7dc7aad3a4432ada
0c46b2988021dacf063778be69c12cf9466ff379
/INF/PrgT/Cpp/03-inheritance-and-polymorphism/diamond_problem/Boat.h
0b8690e4acee4a5692111981440ce7cf02a0001b
[]
no_license
AL5624/TH-Rosenheim-Backup
2db235cf2174b33f25758a36e83c3aa9150f72ee
fa01cb7459ab55cb25af79244912d8811a62f83f
refs/heads/master
2023-01-21T06:57:58.155166
2023-01-19T08:36:57
2023-01-19T08:36:57
219,547,187
0
0
null
2022-05-25T23:29:08
2019-11-04T16:33:34
C#
UTF-8
C++
false
false
327
h
#ifndef INC_03_INHERITANCE_AND_POLYMORPHISM_BOAT_H #define INC_03_INHERITANCE_AND_POLYMORPHISM_BOAT_H #include "Vehicle.h" // TODO: Define the Boat class class Boat : Vehicle { public: int maxKnots; Boat(int serial, int yearOfManufacture, int maxKnots); ~Boat(); }; #endif //INC_03_INHERITANCE_AND_POLYMORPHISM_BOAT_H
[ "anton.bertram@stud.fh-rosenheim.de" ]
anton.bertram@stud.fh-rosenheim.de
1c4d1474149a1281a811d815381d3aee57ecf79b
0d87d119aa8aa2cc4d486f49b553116b9650da50
/autom4te.cache/src/arith_uint256.h
54fc1e46287e47d4cb8a5f490b4512ac550cfe82
[ "MIT" ]
permissive
KingricharVD/Nests
af330cad884745cc68feb460d8b5547d3182e169
7b2ff6d27ccf19c94028973b7da20bdadef134a7
refs/heads/main
2023-07-07T12:21:09.232244
2021-08-05T01:25:23
2021-08-05T01:25:23
386,196,221
1
0
null
null
null
null
UTF-8
C++
false
false
11,097
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2020-2021 The NestEgg Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_ARITH_UINT256_H #define BITCOIN_ARITH_UINT256_H #include "blob_uint256.h" #include "uint512.h" #include <assert.h> #include <cstring> #include <stdexcept> #include <stdint.h> #include <string> #include <vector> class blob_uint512; class blob_uint256; class uint256; class uint512; class uint_error : public std::runtime_error { public: explicit uint_error(const std::string& str) : std::runtime_error(str) {} }; /** Template base class for unsigned big integers. */ template<unsigned int BITS> class base_uint { public: enum { WIDTH=BITS/32 }; uint32_t pn[WIDTH]; base_uint() { for (int i = 0; i < WIDTH; i++) pn[i] = 0; } base_uint(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] = b.pn[i]; } base_uint& operator=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] = b.pn[i]; return *this; } base_uint(uint64_t b) { pn[0] = (unsigned int)b; pn[1] = (unsigned int)(b >> 32); for (int i = 2; i < WIDTH; i++) pn[i] = 0; } explicit base_uint(const std::string& str); explicit base_uint(const std::vector<unsigned char>& vch); bool operator!() const { for (int i = 0; i < WIDTH; i++) if (pn[i] != 0) return false; return true; } const base_uint operator~() const { base_uint ret; for (int i = 0; i < WIDTH; i++) ret.pn[i] = ~pn[i]; return ret; } const base_uint operator-() const { base_uint ret; for (int i = 0; i < WIDTH; i++) ret.pn[i] = ~pn[i]; ret++; return ret; } double getdouble() const; base_uint& operator=(uint64_t b) { pn[0] = (unsigned int)b; pn[1] = (unsigned int)(b >> 32); for (int i = 2; i < WIDTH; i++) pn[i] = 0; return *this; } base_uint& operator^=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] ^= b.pn[i]; return *this; } base_uint& operator&=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] &= b.pn[i]; return *this; } base_uint& operator|=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] |= b.pn[i]; return *this; } base_uint& operator^=(uint64_t b) { pn[0] ^= (unsigned int)b; pn[1] ^= (unsigned int)(b >> 32); return *this; } base_uint& operator|=(uint64_t b) { pn[0] |= (unsigned int)b; pn[1] |= (unsigned int)(b >> 32); return *this; } base_uint& operator<<=(unsigned int shift); base_uint& operator>>=(unsigned int shift); base_uint& operator+=(const base_uint& b) { uint64_t carry = 0; for (int i = 0; i < WIDTH; i++) { uint64_t n = carry + pn[i] + b.pn[i]; pn[i] = n & 0xffffffff; carry = n >> 32; } return *this; } base_uint& operator-=(const base_uint& b) { *this += -b; return *this; } base_uint& operator+=(uint64_t b64) { base_uint b; b = b64; *this += b; return *this; } base_uint& operator-=(uint64_t b64) { base_uint b; b = b64; *this += -b; return *this; } base_uint& operator*=(uint32_t b32); base_uint& operator*=(const base_uint& b); base_uint& operator/=(const base_uint& b); base_uint& operator++() { // prefix operator int i = 0; while (++pn[i] == 0 && i < WIDTH-1) i++; return *this; } const base_uint operator++(int) { // postfix operator const base_uint ret = *this; ++(*this); return ret; } base_uint& operator--() { // prefix operator int i = 0; while (--pn[i] == (uint32_t)-1 && i < WIDTH-1) i++; return *this; } const base_uint operator--(int) { // postfix operator const base_uint ret = *this; --(*this); return ret; } int CompareTo(const base_uint& b) const; bool EqualTo(uint64_t b) const; friend inline const base_uint operator+(const base_uint& a, const base_uint& b) { return base_uint(a) += b; } friend inline const base_uint operator-(const base_uint& a, const base_uint& b) { return base_uint(a) -= b; } friend inline const base_uint operator*(const base_uint& a, const base_uint& b) { return base_uint(a) *= b; } friend inline const base_uint operator/(const base_uint& a, const base_uint& b) { return base_uint(a) /= b; } friend inline const base_uint operator|(const base_uint& a, const base_uint& b) { return base_uint(a) |= b; } friend inline const base_uint operator&(const base_uint& a, const base_uint& b) { return base_uint(a) &= b; } friend inline const base_uint operator^(const base_uint& a, const base_uint& b) { return base_uint(a) ^= b; } friend inline const base_uint operator>>(const base_uint& a, int shift) { return base_uint(a) >>= shift; } friend inline const base_uint operator<<(const base_uint& a, int shift) { return base_uint(a) <<= shift; } friend inline const base_uint operator*(const base_uint& a, uint32_t b) { return base_uint(a) *= b; } friend inline bool operator==(const base_uint& a, const base_uint& b) { return memcmp(a.pn, b.pn, sizeof(a.pn)) == 0; } friend inline bool operator!=(const base_uint& a, const base_uint& b) { return memcmp(a.pn, b.pn, sizeof(a.pn)) != 0; } friend inline bool operator>(const base_uint& a, const base_uint& b) { return a.CompareTo(b) > 0; } friend inline bool operator<(const base_uint& a, const base_uint& b) { return a.CompareTo(b) < 0; } friend inline bool operator>=(const base_uint& a, const base_uint& b) { return a.CompareTo(b) >= 0; } friend inline bool operator<=(const base_uint& a, const base_uint& b) { return a.CompareTo(b) <= 0; } friend inline bool operator==(const base_uint& a, uint64_t b) { return a.EqualTo(b); } friend inline bool operator!=(const base_uint& a, uint64_t b) { return !a.EqualTo(b); } std::string GetHex() const; void SetHex(const char* psz); void SetHex(const std::string& str); std::string ToString() const; std::string ToStringReverseEndian() const; unsigned char* begin() { return (unsigned char*)&pn[0]; } unsigned char* end() { return (unsigned char*)&pn[WIDTH]; } const unsigned char* begin() const { return (unsigned char*)&pn[0]; } const unsigned char* end() const { return (unsigned char*)&pn[WIDTH]; } unsigned int size() const { return sizeof(pn); } uint64_t Get64(int n = 0) const { return pn[2 * n] | (uint64_t)pn[2 * n + 1] << 32; } uint32_t Get32(int n = 0) const { return pn[2 * n]; } /** * Returns the position of the highest bit set plus one, or zero if the * value is zero. */ unsigned int bits() const; uint64_t GetLow64() const { assert(WIDTH >= 2); return pn[0] | (uint64_t)pn[1] << 32; } template<typename Stream> void Serialize(Stream& s) const { s.write((char*)pn, sizeof(pn)); } template<typename Stream> void Unserialize(Stream& s) { s.read((char*)pn, sizeof(pn)); } // Temporary for migration to blob160/256 uint64_t GetCheapHash() const { return GetLow64(); } void SetNull() { memset(pn, 0, sizeof(pn)); } bool IsNull() const { for (int i = 0; i < WIDTH; i++) if (pn[i] != 0) return false; return true; } friend class uint160; friend class uint256; friend class uint512; friend class arith_uint160; friend class arith_uint256; friend class arith_uint512; }; /** 160-bit unsigned big integer. */ class arith_uint160 : public base_uint<160> { public: arith_uint160() {} arith_uint160(const base_uint<160>& b) : base_uint<160>(b) {} arith_uint160(uint64_t b) : base_uint<160>(b) {} explicit arith_uint160(const std::string& str) : base_uint<160>(str) {} explicit arith_uint160(const std::vector<unsigned char>& vch) : base_uint<160>(vch) {} }; /** 256-bit unsigned big integer. */ class arith_uint256 : public base_uint<256> { public: arith_uint256() {} arith_uint256(const base_uint<256>& b) : base_uint<256>(b) {} arith_uint256(uint64_t b) : base_uint<256>(b) {} explicit arith_uint256(const std::string& str) : base_uint<256>(str) {} explicit arith_uint256(const std::vector<unsigned char>& vch) : base_uint<256>(vch) {} /** * The "compact" format is a representation of a whole * number N using an unsigned 32bit number similar to a * floating point format. * The most significant 8 bits are the unsigned exponent of base 256. * This exponent can be thought of as "number of bytes of N". * The lower 23 bits are the mantissa. * Bit number 24 (0x800000) represents the sign of N. * N = (-1^sign) * mantissa * 256^(exponent-3) * * Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn(). * MPI uses the most significant bit of the first byte as sign. * Thus 0x1234560000 is compact (0x05123456) * and 0xc0de000000 is compact (0x0600c0de) * * Bitcoin only uses this "compact" format for encoding difficulty * targets, which are unsigned 256bit quantities. Thus, all the * complexities of the sign bit and using base 256 are probably an * implementation accident. */ arith_uint256& SetCompact(uint32_t nCompact, bool *pfNegative = NULL, bool *pfOverflow = NULL); uint32_t GetCompact(bool fNegative = false) const; uint32_t Get32(int n = 0) const { return pn[2 * n]; } }; /** 512-bit unsigned big integer. */ class arith_uint512 : public base_uint<512> { public: arith_uint512() {} arith_uint512(const base_uint<512>& b) : base_uint<512>(b) {} arith_uint512(uint64_t b) : base_uint<512>(b) {} explicit arith_uint512(const std::string& str) : base_uint<512>(str) {} explicit arith_uint512(const std::vector<unsigned char>& vch) : base_uint<512>(vch) {} //friend arith_uint512 UintToArith512(const blob_uint512 &a); //friend blob_uint512 ArithToUint512(const arith_uint512 &a); }; /** Old classes definitions */ /** End classes definitions */ const arith_uint256 ARITH_UINT256_ZERO = arith_uint256(); #endif // BITCOIN_UINT256_H
[ "northerncommunity1@gmail.com" ]
northerncommunity1@gmail.com
80862b2e4e75a0d761b2793bc2c2b29d42e0447c
0441585e00e2d1ceddc2e4575e6c195075d6d3ca
/PersonItem.hpp
0b8ac2bf298527dee103ac1174e14d1d66058e67
[]
no_license
rherardi/ldif2pst
9efc00f0ac4816934e5328030a0447b219b9342f
766959056d448793240dcd0d199d47c122a37e28
refs/heads/master
2020-05-20T07:49:05.914074
2015-05-12T07:46:18
2015-05-12T07:46:18
35,469,393
0
0
null
null
null
null
UTF-8
C++
false
false
1,492
hpp
// MessageItem.hpp: interface for the CPersonItem class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PERSONITEM_HPP__EC66FE86_817C_4257_84C8_5D4905E2CCBE__INCLUDED_) #define AFX_PERSONITEM_HPP__EC66FE86_817C_4257_84C8_5D4905E2CCBE__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifdef NMAILXML_EXPORTS #define NMAILXML_API __declspec(dllexport) #else #define NMAILXML_API __declspec(dllimport) #endif class CPersonItem { public: CPersonItem(); virtual ~CPersonItem(); // Get/Set m_attribute NMAILXML_API _TCHAR const * GetName(); NMAILXML_API void SetName(const _TCHAR *name); // Get/Set m_value NMAILXML_API _TCHAR const * GetValue(); NMAILXML_API void SetValue(const _TCHAR *value); // Get/Set m_value NMAILXML_API long const GetValueNumeric(); NMAILXML_API void SetValueNumeric(const long value); // Get/Set m_numeric NMAILXML_API bool const IsNumeric(); NMAILXML_API void SetNumeric(const bool value); // Get/Set m_condition NMAILXML_API _TCHAR const * GetCondition(); NMAILXML_API void SetCondition(const _TCHAR *value); // Get/Set m_namedProperty NMAILXML_API bool const IsNamedProperty(); NMAILXML_API void SetNamedProperty(const bool namedProperty); protected: _TCHAR m_name[128]; _TCHAR m_value[512]; long m_valuenum; bool m_numeric; _TCHAR m_condition[128]; bool m_namedProperty; }; #endif // !defined(AFX_PERSONITEM_HPP__EC66FE86_817C_4257_84C8_5D4905E2CCBE__INCLUDED_)
[ "rherardi@alumni.stanford.edu" ]
rherardi@alumni.stanford.edu
1163d17edf30ae9a6d2509eab403396a1ddbf453
7e21c4f4793e886910a6b4135116bf3c744405aa
/Special positions in binary matrix.cpp
e30a35838a78fd488a3f6824f840cd737bb09915
[]
no_license
vriddhi1203/LeetCode-Solutions
944da388ff49ca1aff47233520d891bfefd64a19
59937b80b762275f2d90ebb246dbe5d231505c5b
refs/heads/main
2023-02-19T00:14:52.911229
2021-01-09T18:59:14
2021-01-09T18:59:14
327,352,322
0
0
null
null
null
null
UTF-8
C++
false
false
842
cpp
class Solution { public: int numSpecial(vector<vector<int>>& mat) { int ans=0; for(int i=0;i<mat.size();i++){ for(int j=0;j<mat[i].size();j++){ if(mat[i][j]==1){ bool c=true; for(int k=0;k<mat.size();k++){ if(k!=i && mat[k][j]!=0){ c=false; break; } } for(int z=0;z<mat[i].size();z++){ if(z!=j && mat[i][z]!=0){ c=false; break; } } if(c) ans++; } } } return ans; } };
[ "noreply@github.com" ]
vriddhi1203.noreply@github.com
5596d53e7e53f5dce98fd0bf7d55396f29f59902
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/constant/constants/maxexponent.hpp
4d628719ac4d9bb420da3445baefd976802cd47a
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
1,185
hpp
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_CONSTANT_CONSTANTS_MAXEXPONENT_HPP_INCLUDED #define NT2_CONSTANT_CONSTANTS_MAXEXPONENT_HPP_INCLUDED #include <boost/simd/constant/include/constants/maxexponent.hpp> #include <nt2/include/functor.hpp> namespace nt2 { namespace tag { #ifdef DOXYGEN_ONLY /*! \brief Same as \classref{boost::simd::tag::Maxexponent_} **/ struct maxexponent_ {}; #endif using boost::simd::tag::Maxexponent; } #ifdef DOXYGEN_ONLY /*! \brief Same as \funcref{boost::simd::Maxexponent} **/ template<class... Args> details::unspecified maxexponent(Args&&... args); #endif using boost::simd::Maxexponent; } #include <nt2/constant/common.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
ef9778e241885be5272027583fcfac02028b7ccc
1f465d0e9082b92115d1d65f4f27ee03850b05f9
/ReadFile/Store.h
8fc97c0b336cf27f053307d623eea7a09949bc04
[]
no_license
kjblkblt/ReadFile
25c8a7b2225f6627d6fd0c5dbb9dc3960a0f60fa
c75309d1dd0b89177ae930cfe5e0ad6e42c5a27e
refs/heads/master
2021-01-25T00:22:22.862937
2015-05-07T17:05:31
2015-05-07T17:05:31
34,702,589
0
1
null
null
null
null
UTF-8
C++
false
false
8,823
h
#include <string> #ifndef STORE_H_ #define STORE_H_ using namespace std; class Store { public: static bool RevenueComparator(const Store& c1, const Store& c2); static bool NPSComparator(const Store& c1, const Store& c2); static bool StoreComparator(const Store& c1, const Store& c2); Store(); ~Store(); int storeNumber(); void setStoreNumber(int s); void setFiscalMonth(string month); string getFiscalMonth(); void setTotalPoints(int t); int getTotalPoints(); void setTotalRank(int rank); int getTotalRank(); void setTotServ2Trgt(double val); double getTotServ2Trgt(); void setTotServ2TrgtRank(int rank); double getTotServ2TrgtRank(); void setRenewRev(double renew); double getRenewRev(); void setRevRank(int revRank); int getRevRank(); void setNPS(double NPS); double getNPS(); void setNPSRank(int NPSRank); int getNPSRank(); void setUtilization(double P_Util); double getUtilization(); void setATUtilization(double AT_Util); double getATUtilization(); void setTT(double TT); double getTT(); void set_TTRank(int TTRank); int get_TTRank(); void setCertified(double cert); double getCertified(); void setNPSKeepClient(double NPS_Keep) { _NPSKeepClient = NPS_Keep; }; double getNPSKeepClient() { return _NPSKeepClient; } void setNPSFollowUP(double NPS_Follow) { _NPSFollowUp = NPS_Follow; }; double getNPSFollowUp() { return _NPSFollowUp; } void setAJUAppl(int AJU_Appl) { _AJUAppl = AJU_Appl; }; int getAJUAppl() { return _AJUAppl; } void setAJUAttach(int AJU_Attach) { _AJUAttach = AJU_Attach; }; int getAJUAttach() { return _AJUAttach; } void setAJUPercent(double AJUcent) { _AJUPercent = AJUcent; }; double getAJUPercent() { return _AJUPercent; } void setAJUTT(double AJU_TT) { _AJUTT = AJU_TT; }; double getAJUTT(){ return _AJUTT; } void setAJUCost(double AJUCost) { _AJUCost = AJUCost; }; double getAJUCost() { return _AJUCost; } void setOverallC2S(double C2S) { _Create2Ship = C2S; }; double getOverallC2S(){ return _Create2Ship; } void setServiceC2S(double ServiceC2S) { _ServiceC2S = ServiceC2S; }; double getServiceC2S() { return _ServiceC2S; } void setDTVC2S(double DTVC2S) { _DTVC2S = DTVC2S; }; double getDTVC2S() { return _DTVC2S; } void setUPSC2S(double USPC2S) { _UPSC2S = USPC2S; }; double getUPSC2S() { return _UPSC2S; } void setRec2PU(double Rec2PU) { _Rec2PU = Rec2PU; }; double getRec2PU() { return _Rec2PU; } void setStoreComp2PU(double StoreComp2PU) { _StoreComp2PU = StoreComp2PU; }; double getStoreComp2PU() { return _StoreComp2PU; } void setSWTags(int SWTags) { _SWTags = SWTags; }; int getSWTags() { return _SWTags; } void setSWPercent(double SWPercent) { _SWPercent = SWPercent; }; double getSWPercent() { return _SWPercent; } void setJOTags(int JOTags) { _JOTags = JOTags; }; int getJOTags(){ return _JOTags; } void setJOPercent(double JOPercent) { _JOPercent = JOPercent; }; double getJOPercent() { return _JOPercent; } void setNPSTrouble(double NPSTrouble) { _NPSTrouble = NPSTrouble; }; double getNPSTrouble() { return _NPSTrouble; } void setNPSDemo(double NPSDemo) { _NPSDemo = NPSDemo; }; double getNPSDemo() { return _NPSDemo; } void setNPSKnow(double NPSKnow) { _NPSKnow = NPSKnow; }; double getNPSKnow(){ return _NPSKnow; } void setNOVAUse(double NOVAUse) { _NOVAUse = NOVAUse; }; double getNOVAUse(){ return _NOVAUse; } void setTotRenew(double TotRenew) { _TotRenew = TotRenew; }; double getTotRenew() { return _TotRenew; } void setTotRenewGoal(double TotRenewGoal) { _TotRenewGoal = TotRenewGoal; }; double getTotRenewGoal() { return _TotRenewGoal; } void setTotRenewPercent(double TotRenewPercent) { _TotRenewPercent = TotRenewPercent; }; double getTotRenewPercent() { return _TotRenewPercent; } void setRenew81Mix(double Renew81Mix) { _Renew81Mix = Renew81Mix; }; double getRenew81Mix() { return _Renew81Mix; } void setRenew404Mix(double Renew404Mix) { _Renew404Mix = Renew404Mix; }; double getRenew404Mix() { return _Renew404Mix; } void setShip2CTake(double Ship2CTake) { _Ship2CTake = Ship2CTake; }; double getShip2CTake() { return _Ship2CTake; } void setShip2CElig(int Ship2CElig) { _Ship2CElig = Ship2CElig; }; int getShip2CElig(){ return _Ship2CElig; } void setDBU2GSTS(double DBU2GSTS) { _DBU2GSTS = DBU2GSTS; }; double getDBU2GSTS(){ return _DBU2GSTS; } void setNewPCAttach(double NewPCAttach) { _NewPCAttach = NewPCAttach; }; double getNewPCAttach() { return _NewPCAttach; } void setGSTSAttach(double GSTSAttach) { _GSTSAttach = GSTSAttach; }; double getGSTSAttach(){ return _GSTSAttach; } void setSetupAttach(double SetupAttach) { _SetupAttach = SetupAttach; }; double getSetupAttach(){ return _SetupAttach; } void setRestoreAttach(double RestoreAttach){ _RestoreAttach = RestoreAttach; }; double getRestoreAttach(){ return _RestoreAttach; } void setTotServAttach(double TotServAttach) { _TotServAttach = TotServAttach; }; double getTotServAttach(){ return _TotServAttach; } void setNPSTT(double NPSTT){ _NPSTT = NPSTT; }; double getNPSTT(){ return _NPSTT; } void setNPSServQual(double NPSServQual){ _NPSServQual = NPSServQual; }; double getNPSServQual() { return _NPSServQual; } void setRenewTT(double RenewTT){ _RenewTT = RenewTT; }; double getRenewTT() { _RenewTT; } void setInstoreTT(double InstoreTT) { _InstoreTT = InstoreTT; }; double getInstoreTT() { _InstoreTT; } void setNewTT(double NewTT){ _NewTT = NewTT; }; double getNewTT() { return _NewTT; } void setSOOlder2(int SOOlder2){ _SOOlder2 = SOOlder2; }; int getSOOlder2() { return _SOOlder2; } void setSOOlder7(int SOOlder7){ _SOOlder7 = SOOlder7; }; int getSOOlder7() { return _SOOlder7; } void setHP2StoreTT(double HP2StoreTT){ _HP2StoreTT = HP2StoreTT; }; double getHP2StoreTT() { return _HP2StoreTT; } void setHP2StoreCmplt(int HP2StoreCmplt){ _HP2StoreCmplt = HP2StoreCmplt; }; int getHP2StoreCmplt() { return _HP2StoreCmplt; } void setHP2StoreServ(int HP2StoreServ){ _HP2StoreServ = HP2StoreServ; }; int getHP2StoreServ(){ return _HP2StoreServ; } void setHP2StoreSucc(double HP2StoreSucc){ _HP2StoreSucc = HP2StoreSucc; }; double getHP2StoreSucc(){ return _HP2StoreSucc; } void setGSPPhone(double GSPPhone){ _GSPPhoneScreen = GSPPhone; }; double getGSPPhone(){ return _GSPPhoneScreen; } void setTotalTags(int TotalTags){ _TotalTags = TotalTags; }; int getTotalTags(){ _TotalTags; } void setCmpltsPerDay(double CmpltsPerDay){ _CmpltsPerDay = CmpltsPerDay; }; double getCmpltsPerDay(){ return _CmpltsPerDay; } void setGSPSO(double GSPSO){ _GSPSO = GSPSO; }; double getGSPSO() { return _GSPSO; } void setCODSO(double CODSO){ _CODSO = CODSO; }; double getCODSO(){ return _CODSO; } void setGSTSSO(double GSTSSO){ _GSTSSO = GSTSSO; }; double getGSTSSO(){ return _GSTSSO; } void setStoreRedo(double StoreRedo){ _StoreRedo = StoreRedo; }; double getStoreRedo(){ return _StoreRedo; } void setRedo(int Redo){ _Redo = Redo; }; int getRedo(){ return _Redo; } void setGSTSRedo(double GSTSRedo){ _GSTSRedo = GSTSRedo; }; double getGSTSRedo(){ return _GSTSRedo; } void setOtherRedo(double OtherRedo){ _OtherRedo = OtherRedo; }; double getOtherRedo(){ return _OtherRedo; } void setClientRedo(double CllientRedo){ _ClientRedo = CllientRedo; }; double getClientRedo(){ _ClientRedo; } void setAgentRedo(double AgentRedo){ _AgentRedo = AgentRedo; }; double getAgentRedo(){ return _AgentRedo; } void printSBG(); void printOA(); void printARA(); void printCA(); private: int _storeNum; string _fiscalMonth; int _totalPoints; int _totalRank; double _totServ2Trgt; int _totServ2TrgtRank; double _renewRev; int _renewRevRank; double _nps; int _npsRank; double _utilization; double _atUtilization; double _tt; int _ttRank; double _certified; double _NPSKeepClient; double _NPSFollowUp; int _AJUAppl; int _AJUAttach; double _AJUPercent; double _AJUTT; double _AJUCost; double _Create2Ship; double _ServiceC2S; double _DTVC2S; double _UPSC2S; double _Rec2PU; double _StoreComp2PU; int _SWTags; double _SWPercent; int _JOTags; double _JOPercent; double _NPSTrouble; double _NPSDemo; double _NPSKnow; double _NOVAUse; double _TotRenew; double _TotRenewGoal; double _TotRenewPercent; double _Renew81Mix; double _Renew404Mix; double _Ship2CTake; int _Ship2CElig; double _DBU2GSTS; double _NewPCAttach; double _GSTSAttach; double _SetupAttach; double _RestoreAttach; double _TotServAttach; double _NPSTT; double _NPSServQual; double _RenewTT; double _InstoreTT; double _NewTT; int _SOOlder2; int _SOOlder7; double _HP2StoreTT; int _HP2StoreCmplt; int _HP2StoreServ; double _HP2StoreSucc; double _GSPPhoneScreen; int _TotalTags; double _CmpltsPerDay; double _GSPSO; double _CODSO; double _GSTSSO; double _StoreRedo; int _Redo; double _GSTSRedo; double _OtherRedo; double _ClientRedo; double _AgentRedo; }; #endif
[ "kim.x.johnson@gmail.com" ]
kim.x.johnson@gmail.com
e64a8543bc18e5018c4b735992b8ed19c9594fe6
27dbda0197096619145e80144f9a7bdc33099b08
/Core/Assembler.h
191bdee81301e110f4800c78b90f608c4be77643
[]
no_license
unknownbrackets/armips
f58941bc2307e8b72a150a00d0ab7b3749783bcb
f53a0949d11a29bda810811fc8b7647ecb630c78
refs/heads/master
2022-11-05T18:03:52.751621
2014-11-23T20:04:24
2014-11-23T20:04:24
27,045,572
2
0
null
null
null
null
UTF-8
C++
false
false
954
h
#pragma once #include "../Util/CommonClasses.h" #include "../Util/FileClasses.h" #include "../Util/Util.h" #include "FileManager.h" enum class ArmipsMode { File, Memory }; struct LabelDefinition { std::wstring name; int value; }; struct ArmipsArguments { // common ArmipsMode mode; int symFileVersion; bool errorOnWarning; bool silent; StringList* errorsResult; StringList equList; std::vector<LabelDefinition> labels; // file mode std::wstring inputFileName; std::wstring tempFileName; std::wstring symFileName; // memory mode AssemblerFile* memoryFile; std::wstring content; ArmipsArguments() { mode = ArmipsMode::File; errorOnWarning = false; silent = false; errorsResult = NULL; } }; bool runArmips(ArmipsArguments& arguments); void parseMacroDefinition(TextFile& Input, std::wstring& Args); void LoadAssemblyFile(const std::wstring& fileName, TextFile::Encoding encoding = TextFile::GUESS); bool EncodeAssembly();
[ "sorgts@googlemail.com" ]
sorgts@googlemail.com
bc60de19394bbef643f40ec3f01b587950df6859
059be4fd38c56117816d2541731e031325cab43b
/meshlib/algorithm/FindLoop.cpp
e3572b3b60ee58bedd983840c34702f809a6797c
[ "MIT" ]
permissive
seanchas116/meshlib
aeacfc03820b8352a52f7ec3cc044d65628adfa4
f2b48717667adaff9d70f0e927d1bdd44633beed
refs/heads/master
2020-11-24T06:37:06.947687
2019-12-14T16:08:15
2019-12-14T16:08:15
228,012,025
2
0
null
null
null
null
UTF-8
C++
false
false
1,771
cpp
#include "FindLoop.hpp" #include <range/v3/algorithm/find.hpp> namespace meshlib { std::vector<EdgeHandle> findLoop(const Mesh &mesh, EdgeHandle edge) { std::vector<EdgeHandle> edges; auto vertex = mesh.vertices(edge)[0]; edges.push_back(edge); if (ranges::distance(mesh.faces(edge)) != 2) { // non-manifold edge return {}; } while (true) { auto nextVertex = mesh.vertices(edge)[0] == vertex ? mesh.vertices(edge)[1] : mesh.vertices(edge)[0]; if (ranges::distance(mesh.faces(nextVertex)) != 4) { // extraordinary vertex return {}; } EdgeHandle nextEdge; bool nextEdgeFound = false; std::vector<FaceHandle> nextEdgeFaces; for (auto e : mesh.edges(nextVertex)) { if (ranges::distance(mesh.faces(e)) != 2) { // non-manifold edge continue; } bool allFacesDifferent = true; for (auto face : mesh.faces(e)) { for (auto edgeFace : mesh.faces(edge)) { if (edgeFace == face) { allFacesDifferent = false; } } } if (allFacesDifferent) { nextEdge = e; nextEdgeFound = true; break; } } if (!nextEdgeFound) { return {}; } if (nextEdge == edges[0]) { // loop found return edges; } if (ranges::find(edges, nextEdge) != edges.end()) { // 9 loop return {}; } edges.push_back(nextEdge); edge = nextEdge; vertex = nextVertex; } } } // namespace meshlib
[ "iofg2100@gmail.com" ]
iofg2100@gmail.com
5a9bdff4d70f193e5af9afd8974494c7bdca6536
874fd3e28319bf6042b72c580aad3018d2fa35fb
/src/binaryServer/logging/ClientSdkLoggerFactory.cpp
df8e22180be19037c7ef70935e52ba6b7fc8779b
[ "Apache-2.0" ]
permissive
menucha-de/OPC-UA.Server
43e50962afe631765693575bf80f5c6a6467f004
ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97
refs/heads/main
2023-03-24T16:29:13.864707
2021-03-19T14:28:36
2021-03-19T14:28:36
349,453,071
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
cpp
#include "ClientSdkLoggerFactory.h" #include "ClientSdkLogger.h" #include <common/Mutex.h> #include <common/MutexLock.h> #include <stdio.h> // fprintf #include <map> using namespace CommonNamespace; class ClientSdkLoggerFactoryPrivate { friend class ClientSdkLoggerFactory; private: std::map<const char*, Logger*> loggers; Mutex* mutex; }; ClientSdkLoggerFactory::ClientSdkLoggerFactory() /*throws MutexException*/ { d = new ClientSdkLoggerFactoryPrivate(); d->mutex = new Mutex(); // MutexException } ClientSdkLoggerFactory::~ClientSdkLoggerFactory() { // delete loggers for (std::map<const char*, Logger*>::const_iterator it = d->loggers.begin(); it != d->loggers.end(); it++) { delete it->second; } delete d; } Logger* ClientSdkLoggerFactory::getLogger(const char* name) { MutexLock lock(*d->mutex); std::map<const char*, Logger*>::const_iterator it = d->loggers.find(name); if (it == d->loggers.end()) { Logger* logger = new ClientSdkLogger(name); d->loggers[name] = logger; return logger; } return it->second; }
[ "info@menucha.de" ]
info@menucha.de
37439e54d41ddbea6a3a5b025fe73197ba67938c
eb0b9c66976c0aa0b1a5506c0d500161a47294f7
/WalkThrough/Queue.h
8ef7e12e4650e6ce52adf73cc3b3e8272808b112
[]
no_license
codeprecise/a-gentle-introduction-to-cpp
46eb99ac46e0b39c7962e685abfdd8e50b623d61
db933dee8fc06249437172a2b943a2b80f6e6de0
refs/heads/master
2020-06-02T17:51:40.529676
2019-06-11T05:09:10
2019-06-11T05:09:10
191,044,620
1
0
null
null
null
null
UTF-8
C++
false
false
481
h
#pragma once #include "Mutex.h" typedef void* ElementPtr; class Queue { public: Queue(int maxElementCount, int elementSize); ~Queue(); int GetSize(); bool Enqueue(ElementPtr element); bool Dequeue(ElementPtr element); private: void IncrementIndex(int* index); int _elementSize; int _maxElementCount; int _elementCount; int _writeIndex; int _readIndex; char* _elements; Mutex _mutex; };
[ "davids@codeprecise.com" ]
davids@codeprecise.com
e584b825b28a6150ba63281630eb0edd4e54e0c1
ecb2798c0529d23ed7e32f28578b23affd180ce1
/Assignment 3/src/Demos/SierpinskiBungeeJumpGUI.cpp
c61d366135a02bbac6e9a7c9752b020b8a3e01f3
[]
no_license
zjulsh/cs106b_2019
259305efbfce685ab91d5b771653a011b3aac478
9cd4a107fc24edfda18dc67372ce370b957d0404
refs/heads/master
2021-04-10T19:26:49.398285
2020-03-21T11:15:13
2020-03-21T11:15:13
248,958,721
1
0
null
null
null
null
UTF-8
C++
false
false
6,445
cpp
#include "ProblemHandler.h" #include "Sierpinski.h" #include "GUIUtils.h" #include "GVector.h" #include "gtimer.h" #include <algorithm> using namespace std; namespace { const string kBackgroundColor = "#FFFFFF"; const string kBorderColor = "#4C516D"; // Independence /* Timing parameters. */ const int kFramesPerSecond = 100; const double kPauseTime = 1000.0 / kFramesPerSecond; const int kFramesPerAnimation = 100; /* Triangle parameters. */ const int kOrder = 8; /* Height of an equilateral triangle with unit side length. */ const double kEquilateralHeight = sqrt(3.0) / 2.0; /* Computes the centroid of three points. */ GPoint centroidOf(const GPoint& p0, const GPoint& p1, const GPoint& p2) { return { (p0.getX() + p1.getX() + p2.getX()) / 3.0, (p0.getY() + p1.getY() + p2.getY()) / 3.0 }; } /* Problem handler to do a deep dive into the Sierpinski triangle. */ class SierpinskiBungeeJumpGUI: public ProblemHandler { public: SierpinskiBungeeJumpGUI(GWindow& window); ~SierpinskiBungeeJumpGUI(); void timerFired() override; protected: void repaint(GWindow& window) override; private: GTimer* mTimer; int mFrame = 0; // Which animation frame we're on GPoint mPoints[3]; // Control points of the triangle GPoint mCentroid; // Centroid of rotation }; } SierpinskiBungeeJumpGUI::SierpinskiBungeeJumpGUI(GWindow& window) : mTimer(new GTimer(kPauseTime)) { mTimer->start(); /* We want our triangle to be an equilateral triangle that's as large as possible * while still fitting into the window. Compute the scale factor to use assuming we * have a unit triangle. */ double scale = min(window.getCanvasWidth(), window.getCanvasHeight() / kEquilateralHeight); double width = 1.0 * scale; double height = kEquilateralHeight * scale; /* Use that to compute our origin points. */ double baseX = (window.getCanvasWidth() - width) / 2.0; double baseY = (window.getCanvasHeight() - height) / 2.0; /* Compute the points of the corners of our triangle. */ mPoints[0] = { baseX, baseY + height }; mPoints[1] = { baseX + width, baseY + height }; mPoints[2] = { baseX + width / 2, baseY }; mCentroid = centroidOf(mPoints[0], mPoints[1], mPoints[2]); } SierpinskiBungeeJumpGUI::~SierpinskiBungeeJumpGUI() { /* TODO: There seems to be a bug in GTimer that causes major problems if we use an * actual GTimer object here rather than a pointer to one. Fix the leak and * remove this destructor. */ mTimer->stop(); } void SierpinskiBungeeJumpGUI::timerFired() { if (mTimer->isStarted()) { mFrame++; if (mFrame == kFramesPerAnimation) mFrame = 0; requestRepaint(); } } void SierpinskiBungeeJumpGUI::repaint(GWindow& window) { clearDisplay(window, kBackgroundColor); /* See where we are in this animation. */ double alpha = mFrame / double(kFramesPerAnimation); /* Imagine we have this starting triangle * * p2 * /\ * /--\ * /\ /\ * /--\/--\ * /\ /\ * /--\ C/--\ * /\ /\ /\ /\ * /--\/--\/--\/--\ * p0 A^^^^B p1 * * We want to end up such that * * point A ends up where p2 used to be, * point B ends up where p0 used to be, and * point C ends up where p1 used to be. * * This corresponds to * * 1. rotating the entire figure around the centroid of triangle ABC by 120 degrees, then * 2. doubling the size of the entire figure, centering around the the centroid of ABC. * * We'll compute the rotation and scale based on the progress that we've made so far. * * There's one last effect to take into account. If we purely zoom into the center of this * triangle, we'll end up looking in pure whitespace. We need to also slightly translate * everything over a bit; specifically, so that the triangle in the top becomes the new * center point. * * To do this, we'll compute the centroid of that new triangle and interpolate it over * into position. */ GPoint sticky = mPoints[0]; auto anchor = centroidOf(mPoints[0] + (sticky - mPoints[0]) / 2, mPoints[1] + (sticky - mPoints[1]) / 2, mPoints[2] + (sticky - mPoints[2]) / 2); /* Rotate everything around that point. */ double theta = alpha * 2 * M_PI / 3; GPoint p0 = mCentroid + (rotate(mPoints[0] - mCentroid, theta)); GPoint p1 = mCentroid + (rotate(mPoints[1] - mCentroid, theta)); GPoint p2 = mCentroid + (rotate(mPoints[2] - mCentroid, theta)); anchor = mCentroid + (rotate(anchor - mCentroid, theta)); /* Scale everything around that point. */ p0 += alpha * (p0 - mCentroid); p1 += alpha * (p1 - mCentroid); p2 += alpha * (p2 - mCentroid); anchor += alpha * (anchor - mCentroid); /* Determine how much to shift everything over based on the anchor point. */ auto shift = (mCentroid - anchor) * alpha; p0 += shift; p1 += shift; p2 += shift; /* Draw our triangle! */ drawSierpinskiTriangle(window, p0.getX(), p0.getY(), p1.getX(), p1.getY(), p2.getX(), p2.getY(), kOrder); /* Draw the borders to avoid revealing the detail that when the rotation finishes, the * triangle isn't actually adjacent to bordering triangles in the same way that the original * one was. :-) */ window.setColor(kBorderColor); /* Sides */ window.fillRect(0, 0, mPoints[0].getX(), window.getCanvasHeight()); window.fillRect(mPoints[1].getX(), 0, window.getCanvasWidth() - mPoints[1].getX(), window.getCanvasHeight()); /* Top and bottom */ window.fillRect(0, 0, window.getCanvasWidth(), mPoints[2].getY()); window.fillRect(0, mPoints[0].getY(), window.getCanvasWidth(), window.getCanvasHeight() - mPoints[0].getY()); } shared_ptr<ProblemHandler> makeBungeeJumpGUI(GWindow& window) { return make_shared<SierpinskiBungeeJumpGUI>(window); }
[ "865835320@qq.com" ]
865835320@qq.com
485d67885c492eead74c16cc842bf57297cff38b
694d42f8e426ee1e7849688d9a332d9fafa99960
/SnowmanSTG/Memento.h
c366a2db78d8208f293ab237de62fa5ee8bb4132
[]
no_license
hazama-yuinyan/SnowmanSTG
23fcfbdc99f03bfd98c920c6e6af1bd7f8cb8848
0d59fc481701d99e64fdf13327c54239a7cf4a84
refs/heads/master
2016-09-05T13:23:08.161705
2011-06-25T18:08:29
2011-06-25T18:08:29
1,854,529
0
0
null
null
null
null
UTF-8
C++
false
false
255
h
#pragma once #include "stdafx.h" class MementoKey { friend class InputDeviceKeyBoard; private: MementoKey(void); boost::array<char, 256> key_state; void SetData(char In[]); boost::array<char, 256> &GetData(void); public: ~MementoKey(void){}; };
[ "Ryouta@.(none)" ]
Ryouta@.(none)
1d88fb9b79d7ac1b965e3969ba0457f15e975f47
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/admin/activec/designer/vb98ctls/mssnapr/mssnapr/ppgwrap.cpp
ab676430d1bbf99deec8fb943fc7749fe3bae6d2
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
50,359
cpp
//=--------------------------------------------------------------------------= // ppgwrap.cpp //=--------------------------------------------------------------------------= // Copyright (c) 1999, Microsoft Corp. // All Rights Reserved // Information Contained Herein Is Proprietary and Confidential. //=--------------------------------------------------------------------------= // // CPropertyPageWrapper class implementation // //=--------------------------------------------------------------------------= #include "pch.h" #include "common.h" #include "ppgwrap.h" #include "tls.h" // for ASSERT and FAIL // SZTHISFILE const UINT CPropertyPageWrapper::m_RedrawMsg = ::RegisterWindowMessage("Microsoft Visual Basic Snap-in Designer Property Page Redraw Message"); const UINT CPropertyPageWrapper::m_InitMsg = ::RegisterWindowMessage("Microsoft Visual Basic Snap-in Designer Property Page Init Message"); DLGTEMPLATE CPropertyPageWrapper::m_BaseDlgTemplate = { WS_TABSTOP | WS_CHILD | DS_CONTROL, // DWORD style; WS_EX_CONTROLPARENT, // DWORD dwExtendedStyle; 0, // WORD cdit; - no controls in this dialog box 0, // short x; dimensions are set per IPropertyPage::GetPageInfo() 0, // short y; 0, // short cx; 0 // short cy; }; #define MAX_DLGS 128 // Definition of data stored in TLS for each thread that displays property pages typedef struct { HHOOK hHook; // HHOOK for this thread UINT cPages; // number of existing property pages CPropertyPageWrapper *ppgActive; // ptr to the currently active page } TLSDATA; // These resource IDs are taken from \nt\private\shell\comctl32\rcids.h. // We need to know the IDs of the Back, Next and Finish buttons on a wizard // or else we can't make tabbing work. This is a nasty dependency but there is // no other way to handle this. #define IDD_BACK 0x3023 #define IDD_NEXT 0x3024 #define IDD_FINISH 0x3025 #pragma warning(disable:4355) // using 'this' in constructor CPropertyPageWrapper::CPropertyPageWrapper(IUnknown *punkOuter) : CSnapInAutomationObject(punkOuter, OBJECT_TYPE_PROPERTYPAGEWRAPPER, static_cast<IPropertyPageSite *>(this), static_cast<CPropertyPageWrapper *>(this), 0, // no property pages NULL, // no property pages NULL) // no persistence { InitMemberVariables(); } #pragma warning(default:4355) // using 'this' in constructor IUnknown *CPropertyPageWrapper::Create(IUnknown *punkOuter) { HRESULT hr = S_OK; CPropertyPageWrapper *pPropertyPage = New CPropertyPageWrapper(punkOuter); if (NULL == pPropertyPage) { hr = SID_E_OUTOFMEMORY; GLOBAL_EXCEPTION_CHECK_GO(hr); } if ( (0 == m_RedrawMsg) || (0 == m_InitMsg) ) { hr = SID_E_SYSTEM_ERROR; GLOBAL_EXCEPTION_CHECK_GO(hr); } Error: if (FAILEDHR(hr)) { if (NULL != pPropertyPage) { delete pPropertyPage; } return NULL; } else { return pPropertyPage->PrivateUnknown(); } } CPropertyPageWrapper::~CPropertyPageWrapper() { ULONG i = 0; IUnknown *punkObject = NULL; // Don't Release // Remove this dialog from the message hook TLS data. If there are // no more dialogs remaining then remove the hook. This should have happened // in OnDestroy during WM_DESTROY processing but just in case we double // check here. (void)RemoveMsgFilterHook(); if (NULL != m_pPropertySheet) { m_pPropertySheet->Release(); } if (NULL != m_pTemplate) { ::CtlFree(m_pTemplate); } // If the marshaling streams are still alive then we need to release // the marshal data. The easiest way to do this is to simply unmarshal // the interface pointer. We do this before releasing the held pointers // below. This case is actually not that rare because it can easily occur // if the user displays a multi-page property sheet and doesn't click // on all the tabs. In that case, the streams were created before the // pages were created but as no WM_INITDIALOG was received, they were // never unmarshaled. This can also occur in a wizard where the user // clicks cancel before visiting all of the pages in the wizard. if (NULL != m_apiObjectStreams) { for (i = 0; i < m_cObjects; i++) { if (NULL != m_apiObjectStreams[i]) { (void)::CoGetInterfaceAndReleaseStream( m_apiObjectStreams[i], IID_IUnknown, reinterpret_cast<void **>(&punkObject)); m_apiObjectStreams[i] = NULL; RELEASE(punkObject); } } CtlFree(m_apiObjectStreams); } if (NULL != m_piSnapInStream) { (void)::CoGetInterfaceAndReleaseStream(m_piSnapInStream, IID_ISnapIn, reinterpret_cast<void **>(&m_piSnapIn)); m_piSnapInStream = NULL; } if ( ISPRESENT(m_varInitData) && (NULL != m_piInitDataStream) ) { if (VT_UNKNOWN == m_varInitData.vt) { m_varInitData.punkVal = NULL; (void)::CoGetInterfaceAndReleaseStream(m_piInitDataStream, IID_IUnknown, reinterpret_cast<void **>(&m_varInitData.punkVal)); } else if (VT_DISPATCH == m_varInitData.vt) { m_varInitData.pdispVal = NULL; (void)::CoGetInterfaceAndReleaseStream(m_piInitDataStream, IID_IDispatch, reinterpret_cast<void **>(&m_varInitData.pdispVal)); } m_piInitDataStream = NULL; } if (NULL != m_piMMCPropertySheetStream) { (void)::CoGetInterfaceAndReleaseStream(m_piMMCPropertySheetStream, IID_IMMCPropertySheet, reinterpret_cast<void **>(&m_piMMCPropertySheet)); m_piMMCPropertySheetStream = NULL; } RELEASE(m_piSnapIn); RELEASE(m_pdispConfigObject); RELEASE(m_piPropertyPage); RELEASE(m_piMMCPropertyPage); RELEASE(m_piMMCPropertySheet); RELEASE(m_piWizardPage); (void)::VariantClear(&m_varInitData); InitMemberVariables(); } void CPropertyPageWrapper::InitMemberVariables() { m_pPropertySheet = NULL; m_piPropertyPage = NULL; m_piMMCPropertyPage = NULL; m_piMMCPropertySheet = NULL; m_piWizardPage = NULL; m_fWizard = FALSE; m_cObjects = 0; m_apiObjectStreams = NULL; m_piSnapInStream = NULL; m_piInitDataStream = NULL; m_piMMCPropertySheetStream = NULL; m_piSnapIn = NULL; m_pdispConfigObject = NULL; m_pTemplate = NULL; m_hwndDlg = NULL; m_hwndSheet = NULL; m_clsidPage = CLSID_NULL; ::VariantInit(&m_varInitData); m_fIsRemote = FALSE; m_fNeedToRemoveHook = FALSE; } HRESULT CPropertyPageWrapper::CreatePage ( CPropertySheet *pPropertySheet, CLSID clsidPage, BOOL fWizard, BOOL fConfigWizard, ULONG cObjects, IUnknown **apunkObjects, ISnapIn *piSnapIn, short cxPage, short cyPage, VARIANT varInitData, BOOL fIsRemote, DLGTEMPLATE **ppTemplate ) { HRESULT hr = S_OK; ULONG i = 0; // AddRef and store the owning property sheet pointer if (NULL != m_pPropertySheet) { m_pPropertySheet->Release(); } if (NULL == pPropertySheet) { hr = SID_E_INTERNAL; EXCEPTION_CHECK_GO(hr); } pPropertySheet->AddRef(); m_pPropertySheet = pPropertySheet; m_fWizard = fWizard; m_fConfigWizard = fConfigWizard; m_fIsRemote = fIsRemote; // Store the page's CLSID so that OnInitDialog() will have access to it // to create the real instance of the page. We cannot create the real // instance here because we are not running in the thread that will be used // for the property sheet. MMC will run the property sheet in a new thread // that it will create in order to keep it modeless and so that it will not // affect the console. m_clsidPage = clsidPage; // Create the dialog template and initialize it with common values m_pTemplate = (DLGTEMPLATE *)::CtlAllocZero(sizeof(m_BaseDlgTemplate) + (3 * sizeof(int))); // for menu, class, title if (NULL == m_pTemplate) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } ::memcpy(m_pTemplate, &m_BaseDlgTemplate, sizeof(*m_pTemplate)); m_pTemplate->cx = cxPage; m_pTemplate->cy = cyPage; // If this is a wizard then we have the ISnapIn so we can fire // ConfigurationComplete. Marshal the interface into a stream // and save the stream so that we can unmarshal it when the page is // created in MMC's property sheet thread. The returned IStream is free // threaded and can be kept in a member variable. if (NULL != piSnapIn) { hr = ::CoMarshalInterThreadInterfaceInStream(IID_ISnapIn, piSnapIn, &m_piSnapInStream); EXCEPTION_CHECK_GO(hr); } // Also need to marhshal the IMMCPropertySheet pointer that will be // passed to IMMCPropertyPage::Initialize as that call will occur during // WM_INITDIALOG which happens in MMC's property sheet thread. if (NULL != pPropertySheet) { hr = ::CoMarshalInterThreadInterfaceInStream(IID_IMMCPropertySheet, static_cast<IMMCPropertySheet *>(pPropertySheet), &m_piMMCPropertySheetStream); EXCEPTION_CHECK_GO(hr); } // Add a ref to ourselves. We need to do this because otherwise no one // else can be depended on to keep this object alive until the Win32 // property page is created by MMC's PropertSheet() call. ExternalAddRef(); // Marshal the objects' IUnknown pointers into streams. The returned // IStreams are free threaded and can be kept in a member variable. // // When the dialog is created, each IUnknown will be unmarshalled and passed // to the property page in IPropertyPage::SetObjects(). // // We check for NULL because the object may have come from an // IPropertySheet:AddWizardPage() which allows the VB dev to specify the // object. IfFalseGo(NULL != apunkObjects, S_OK); m_apiObjectStreams = (IStream **)CtlAllocZero(cObjects * sizeof(IStream *)); if (NULL == m_apiObjectStreams) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } m_cObjects = cObjects; for (i = 0; i < cObjects; i++) { hr = ::CoMarshalInterThreadInterfaceInStream(IID_IUnknown, apunkObjects[i], &m_apiObjectStreams[i]); EXCEPTION_CHECK_GO(hr); } // If there is an object in InitData then it also needs to be marshaled. if (VT_UNKNOWN == varInitData.vt) { m_varInitData.vt = VT_UNKNOWN; m_varInitData.punkVal = NULL; hr = ::CoMarshalInterThreadInterfaceInStream(IID_IUnknown, varInitData.punkVal, &m_piInitDataStream); EXCEPTION_CHECK_GO(hr); } else if (VT_DISPATCH == varInitData.vt) { m_varInitData.vt = VT_DISPATCH; m_varInitData.punkVal = NULL; hr = ::CoMarshalInterThreadInterfaceInStream(IID_IDispatch, varInitData.pdispVal, &m_piInitDataStream); EXCEPTION_CHECK_GO(hr); } else { hr = ::VariantCopy(&m_varInitData, &varInitData); EXCEPTION_CHECK_GO(hr); } Error: // We return the DLGTEMPLATE pointer to the caller even though we own it. // The caller must only use it as long as we are alive. *ppTemplate = m_pTemplate; RRETURN(hr); } BOOL CALLBACK CPropertyPageWrapper::DialogProc ( HWND hwndDlg, UINT uiMsg, WPARAM wParam, LPARAM lParam ) { HRESULT hr = S_OK; BOOL fDlgProcRet = FALSE; CPropertyPageWrapper *pPropertyPageWrapper = NULL; NMHDR *pnmhdr = NULL; LRESULT lresult = 0; if (WM_INITDIALOG == uiMsg) { if (NULL != hwndDlg) { fDlgProcRet = FALSE; // System should not set focus to any control // Get this pointer of CPropertyPageWrapper instance managing this // dialog. For property pages, lParam is a pointer to the // PROPSHEETPAGE used to define this page. The code in // CPropertySheet::AddPage put our this pointer into // PROPSHEETPAGE.lParam. PROPSHEETPAGE *pPropSheetPage = reinterpret_cast<PROPSHEETPAGE *>(lParam); pPropertyPageWrapper = reinterpret_cast<CPropertyPageWrapper *>(pPropSheetPage->lParam); IfFailGo(pPropertyPageWrapper->OnInitDialog(hwndDlg)); // Post ourselves a message so that we can initialize the page // after the dialog creation has completed. (void)::PostMessage(hwndDlg, m_InitMsg, 0, 0); } } else if (m_RedrawMsg == uiMsg) { // See comment for WM_ERASEBKGND below. We don't really have access to // the property page's HWND because IPropertyPage does not allow that. // We do know that our dialog window contains no controls and we set it // as the parent of the property page so it must be our only child. // Generate an immediate redraw for the entire area of our child and all // of its children. Cancel any pending WM_ERASEBKGND messages by // specifying RDW_NOERASE. fDlgProcRet = TRUE; ::RedrawWindow(::GetWindow(hwndDlg, GW_CHILD), NULL, NULL, RDW_INVALIDATE | RDW_NOERASE | RDW_UPDATENOW | RDW_ALLCHILDREN); } else { pPropertyPageWrapper = reinterpret_cast<CPropertyPageWrapper *>( ::GetWindowLong(hwndDlg, DWL_USER)); IfFalseGo(NULL != pPropertyPageWrapper, SID_E_INTERNAL); if (m_InitMsg == uiMsg) { IfFailGo(pPropertyPageWrapper->OnInitMsg()); goto Cleanup; } switch (uiMsg) { case WM_ERASEBKGND: { // Under a debug session property pages are erased and never // redrawn for some unknown reason. After much hair-pulling it // was determined that the work-around is to post ourselves a // message and force a redraw when that message is processed. (void)::PostMessage(hwndDlg, m_RedrawMsg, 0, 0); } break; case WM_SIZE: { fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnSize()); } break; case WM_DESTROY: { fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnDestroy()); } break; // Pass all CTLCOLOR messages to parent. This is what // OLE property frame does. case WM_CTLCOLORMSGBOX: case WM_CTLCOLOREDIT: case WM_CTLCOLORLISTBOX: case WM_CTLCOLORBTN: case WM_CTLCOLORDLG: case WM_CTLCOLORSCROLLBAR: case WM_CTLCOLORSTATIC: { fDlgProcRet = TRUE; ::SendMessage(::GetParent(hwndDlg), uiMsg, wParam, lParam); } break; case WM_NOTIFY: { pnmhdr = reinterpret_cast<NMHDR *>(lParam); IfFalseGo(NULL != pnmhdr, SID_E_SYSTEM_ERROR); // Check that the message is from the property sheet IfFalseGo(pnmhdr->hwndFrom == pPropertyPageWrapper->m_hwndSheet, S_OK); // Branch out to the appropriate handler switch (pnmhdr->code) { case PSN_APPLY: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnApply(&lresult)); break; case PSN_SETACTIVE: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnSetActive( ((PSHNOTIFY *)lParam)->hdr.hwndFrom, &lresult)); break; case PSN_KILLACTIVE: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnKillActive(&lresult)); break; case PSN_WIZBACK: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnWizBack(&lresult)); break; case PSN_WIZNEXT: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnWizNext(&lresult)); break; case PSN_WIZFINISH: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnWizFinish(&lresult)); break; case PSN_QUERYCANCEL: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnQueryCancel(&lresult)); break; case PSN_RESET: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnReset((BOOL)(((PSHNOTIFY *)lParam)->lParam))); break; case PSN_HELP: fDlgProcRet = TRUE; IfFailGo(pPropertyPageWrapper->OnHelp()); break; } // switch (pnmhdr->code) } // WM_NOTIFY break; } // switch(uiMsg) } // not WM_INITDIALOG Cleanup: Error: (void)::SetWindowLong(hwndDlg, DWL_MSGRESULT, static_cast<LONG>(lresult)); return fDlgProcRet; } UINT CALLBACK CPropertyPageWrapper::PropSheetPageProc ( HWND hwnd, UINT uMsg, PROPSHEETPAGE *pPropSheetPage ) { UINT uiRc = 0; if (PSPCB_CREATE == uMsg) { uiRc = 1; // allow the page to be created } else if (PSPCB_RELEASE == uMsg) { CPropertyPageWrapper *pPropertyPageWrapper = reinterpret_cast<CPropertyPageWrapper *>(pPropSheetPage->lParam); if (NULL != pPropertyPageWrapper) { // Release the ref on ourselves. This should result in this object // being destrotyed so do not reference any member variables after // this call pPropertyPageWrapper->ExternalRelease(); } } return uiRc; } HRESULT CPropertyPageWrapper::OnInitDialog(HWND hwndDlg) { HRESULT hr = S_OK; IUnknown **apunkObjects = NULL; ULONG i = 0; IDispatch *pdisp = NULL; m_pPropertySheet->SetOKToAlterPageCount(FALSE); // Store the hwnd and store our this pointer in the window words m_hwndDlg = hwndDlg; ::SetWindowLong(hwndDlg, DWL_USER, reinterpret_cast<LONG>(this)); // Store the property sheet HWND. For now assume it is the parent of // the dialog. When we get PSN_SETACTIVE we'll update it with that value. // Technically we should not make this assumption but there is a ton of // Win32 code that does and we have no choice because we need the HWND // before PSN_SETACTIVE m_hwndSheet = ::GetParent(hwndDlg); // Give it to our owning CPropertySheet m_pPropertySheet->SetHWNDSheet(m_hwndSheet); // Create the page RELEASE(m_piPropertyPage); // should never be necessary, but just in case hr = ::CoCreateInstance(m_clsidPage, NULL, // no aggregation, CLSCTX_INPROC_SERVER, IID_IPropertyPage, reinterpret_cast<void **>(&m_piPropertyPage)); EXCEPTION_CHECK_GO(hr); // Unmarshall the IMMCPropertySheet so we can pass it to // IMMCPropertyPage::Initialize if (NULL != m_piMMCPropertySheetStream) { hr = ::CoGetInterfaceAndReleaseStream(m_piMMCPropertySheetStream, IID_IMMCPropertySheet, reinterpret_cast<void **>(&m_piMMCPropertySheet)); m_piMMCPropertySheetStream = NULL; EXCEPTION_CHECK_GO(hr); } // Set this CPropertyPageWrapper object as the page site IfFailGo(m_piPropertyPage->SetPageSite(static_cast<IPropertyPageSite *>(this))); // Unmarshal the IUnknowns on the objects for which the page will be // displaying properties. This will also release the streams regardless of // whether it succeeds. if (NULL != m_apiObjectStreams) { apunkObjects = (IUnknown **)CtlAllocZero(m_cObjects * sizeof(IUnknown *)); if (NULL == apunkObjects) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } for (i = 0; i < m_cObjects; i++) { if (NULL == m_apiObjectStreams[i]) { continue; } hr = ::CoGetInterfaceAndReleaseStream( m_apiObjectStreams[i], IID_IUnknown, reinterpret_cast<void **>(&apunkObjects[i])); m_apiObjectStreams[i] = NULL; EXCEPTION_CHECK_GO(hr); } } // If this is a wizard then unmarshal the ISnapIn so we can fire // ConfigurationComplete. if (NULL != m_piSnapInStream) { hr = ::CoGetInterfaceAndReleaseStream(m_piSnapInStream, IID_ISnapIn, reinterpret_cast<void **>(&m_piSnapIn)); m_piSnapInStream = NULL; EXCEPTION_CHECK_GO(hr); } // Give the object to the page. Check for NULL because the snap-in // could have called PropertySheet.AddWizardPage passing Nothing // for its configuration object. if (NULL != apunkObjects) { IfFailGo(m_piPropertyPage->SetObjects(m_cObjects, apunkObjects)); } // If this is a wizard then check whether the page supports our IWizardPage // interface. If it does not, that is not considered an error and it simply // won't get the next/back/finish etc. notifications. hr = m_piPropertyPage->QueryInterface(IID_IWizardPage, reinterpret_cast<void **>(&m_piWizardPage)); if (FAILED(hr)) { // Just to be extra sure, NULL our IWizardPage pointer m_piWizardPage = NULL; // If the error was anything other than E_NOINTERFACE then consider it // a real error. if (E_NOINTERFACE == hr) { hr = S_OK; } IfFailGo(hr); } else { // It should be a wizard. Store the object so we can pass it to the // snap-in when the Finish button is pressed (see OnWizFinish). if (NULL != apunkObjects) { if (NULL != apunkObjects[0]) { IfFailGo(apunkObjects[0]->QueryInterface(IID_IDispatch, reinterpret_cast<void **>(&m_pdispConfigObject))); } } else { m_pdispConfigObject = NULL; } } // Add the MSGFILTER hook so that we can call // IPropertyPage::TranslateAccelerator when the user hits a key in a control // on the page. IfFailGo(AddMsgFilterHook()); // Activate the page and show it IfFailGo(ActivatePage()); m_pPropertySheet->SetOKToAlterPageCount(TRUE); Error: if (NULL != apunkObjects) { for (i = 0; i < m_cObjects; i++) { if (NULL != apunkObjects[i]) { apunkObjects[i]->Release(); } } CtlFree(apunkObjects); } RRETURN(hr); } HRESULT CPropertyPageWrapper::OnInitMsg() { HRESULT hr = S_OK; // If the snap-in supports IMMCPropertyPage then call Initialize if (SUCCEEDED(m_piPropertyPage->QueryInterface(IID_IMMCPropertyPage, reinterpret_cast<void **>(&m_piMMCPropertyPage)))) { IfFailGo(InitPage()); } Error: RRETURN(hr); } HRESULT CPropertyPageWrapper::InitPage() { HRESULT hr = S_OK; VARIANT varProvider; ::VariantInit(&varProvider); // If the snap-in passed an object in the InitData parameter of // MMCPropertySheet.AddPage then unmarshal it. if (ISPRESENT(m_varInitData)) { // If there is an object in InitData then it needs to be unmarshaled. if (VT_UNKNOWN == m_varInitData.vt) { m_varInitData.punkVal = NULL; hr = ::CoGetInterfaceAndReleaseStream(m_piInitDataStream, IID_IUnknown, reinterpret_cast<void **>(&m_varInitData.punkVal)); m_piInitDataStream = NULL; EXCEPTION_CHECK_GO(hr); } else if (VT_DISPATCH == m_varInitData.vt) { m_varInitData.pdispVal = NULL; hr = ::CoGetInterfaceAndReleaseStream(m_piInitDataStream, IID_IDispatch, reinterpret_cast<void **>(&m_varInitData.pdispVal)); m_piInitDataStream = NULL; EXCEPTION_CHECK_GO(hr); } } // Call IMMCPropertyPage::Initialize IfFailGo(m_piMMCPropertyPage->Initialize(m_varInitData, reinterpret_cast<MMCPropertySheet *>(m_piMMCPropertySheet))); Error: RRETURN(hr); } HRESULT CPropertyPageWrapper::AddMsgFilterHook() { HRESULT hr = S_OK; TLSDATA *pTlsData = NULL; // If we are remote then don't install the hook. It doesn't work correctly // and there is no need to handle tabbing under the debugger. IfFalseGo(!m_fIsRemote, S_OK); // Check if TLS data is already there for this thread. If not there // then create it, add the hook, and set the TLS data. If it is there // then increment the ref count on the HHOOK. IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData))); if (NULL == pTlsData) { pTlsData = (TLSDATA *)CtlAllocZero(sizeof(TLSDATA)); if (NULL == pTlsData) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } pTlsData->hHook = ::SetWindowsHookEx(WH_MSGFILTER, &MessageProc, GetResourceHandle(), ::GetCurrentThreadId()); if (NULL == pTlsData->hHook) { CtlFree(pTlsData); hr = HRESULT_FROM_WIN32(::GetLastError()); EXCEPTION_CHECK_GO(hr); } if (FAILED(CTls::Set(TLS_SLOT_PPGWRAP, pTlsData))) { (void)::UnhookWindowsHookEx(pTlsData->hHook); CtlFree(pTlsData); } } // Increment the existing page count pTlsData->cPages++; m_fNeedToRemoveHook = TRUE; Error: RRETURN(hr); } HRESULT CPropertyPageWrapper::RemoveMsgFilterHook() { HRESULT hr = S_OK; TLSDATA *pTlsData = NULL; UINT i = 0; // If we already removed the hook then nothing to do IfFalseGo(m_fNeedToRemoveHook, S_OK); // Check if TLS data is already there for this thread. If it is, // then remove this dialog's hwnd from the TLS. IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData))); IfFalseGo(NULL != pTlsData, S_OK); pTlsData->cPages--; m_fNeedToRemoveHook = FALSE; // If there are no more existing pages then remove the hook and free the TLS if (0 == pTlsData->cPages) { if (NULL != pTlsData->hHook) { (void)::UnhookWindowsHookEx(pTlsData->hHook); pTlsData->hHook = NULL; } IfFailGo(CTls::Set(TLS_SLOT_PPGWRAP, NULL)); CtlFree(pTlsData); } Error: RRETURN(hr); } LRESULT CALLBACK CPropertyPageWrapper::MessageProc ( int code, // hook code WPARAM wParam, // not used LPARAM lParam // message data ) { HRESULT hr = S_OK; LRESULT lResult = 0; // default ret value is pass msg to wndproc MSG *pMsg = reinterpret_cast<MSG *>(lParam); TLSDATA *pTlsData = NULL; HWND hwndTab = NULL; HWND hwndSheet = NULL; HWND hwndBack = NULL; HWND hwndNext = NULL; HWND hwndFinish = NULL; HWND hwndCancel = NULL; HWND hwndHelp = NULL; BOOL fTargetIsOnPage = FALSE; BOOL fPassToPropertyPage = FALSE; // Get the TLS data in all cases because the HHOOK is in there and we need // that for CallNextHookEx. IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData))); // If input event did not occur in a dialog box then pass to CallNextHookEx IfFalseGo(code >= 0, S_OK); // If this is not a key down message then just pass to CallNextHookEx IfFalseGo( ((WM_KEYFIRST <= pMsg->message) && (WM_KEYLAST >= pMsg->message)), S_OK); // If there is no pointer to the active page in TLS then just pass to // CallNextHookeEx IfFalseGo(NULL != pTlsData, S_OK); IfFalseGo(NULL != pTlsData->ppgActive, S_OK); // Get the HWND of the tab control hwndSheet = pTlsData->ppgActive->m_hwndSheet; if (NULL != hwndSheet) { hwndTab = (HWND)::SendMessage(hwndSheet, PSM_GETTABCONTROL, 0, 0); } // Check if the target of the message is a decendant of the wrapper dialog // window. If so then it is a control on the VB property page. fTargetIsOnPage = ::IsChild(pTlsData->ppgActive->m_hwndDlg, pMsg->hwnd); // If a tab was hit outside of the page then in some cases we need to // let the page handle it. if ( (VK_TAB == pMsg->wParam) && (!fTargetIsOnPage) ) { // If this is a back-tab if (::GetKeyState(VK_SHIFT) < 0) { // If the focus is on the OK button, let page handle shift-tab if (pMsg->hwnd == ::GetDlgItem(hwndSheet, IDOK)) { fPassToPropertyPage = TRUE; } else if (pTlsData->ppgActive->m_fWizard) { // Determine which wizard buttons are enabled and handle // back tabs from the left-most enabled button. // Wizard buttons can be: // Back | Next | Finish | Cancel | Help // The left-most enabled button could be Back, Next, Finish, or // Cancel // TODO: does this work on RTL locales such as Hebrew and Arabic? hwndBack = ::GetDlgItem(hwndSheet, IDD_BACK); hwndNext = ::GetDlgItem(hwndSheet, IDD_NEXT); hwndFinish = ::GetDlgItem(hwndSheet, IDD_FINISH); hwndCancel = ::GetDlgItem(hwndSheet, IDCANCEL); if (pMsg->hwnd == hwndBack) { fPassToPropertyPage = TRUE; } else if ( (pMsg->hwnd == hwndNext) && (!::IsWindowEnabled(hwndBack)) ) { // Back-tab is for Next button and Back button is disabled fPassToPropertyPage = TRUE; } else if ( (pMsg->hwnd == hwndFinish) && (!::IsWindowEnabled(hwndBack)) && (!::IsWindowEnabled(hwndNext)) ) { // Back-tab is for Finish button and Next and Back buttons // are disabled fPassToPropertyPage = TRUE; } else if ( (pMsg->hwnd == hwndFinish) && (!::IsWindowEnabled(hwndBack)) && (!::IsWindowEnabled(hwndNext)) ) { // Back-tab is for Finish button and Next and Back buttons // are disabled fPassToPropertyPage = TRUE; } } } else // forward tab { // If the focus is on the tab control, let page handle tab if (hwndTab == pMsg->hwnd) { fPassToPropertyPage = TRUE; } else if (pTlsData->ppgActive->m_fWizard) { // Determine which wizard buttons are enabled and handle // back tabs from the right-most enabled button. // Wizard buttons can be: // Back | Next | Finish | Cancel | Help // The right-most enabled button could be Cancel or Help // TODO: does this work on RTL locales such as Hebrew and Arabic? hwndCancel = ::GetDlgItem(hwndSheet, IDCANCEL); hwndHelp = ::GetDlgItem(hwndSheet, IDHELP); if (pMsg->hwnd == hwndHelp) { fPassToPropertyPage = TRUE; } else if ( (pMsg->hwnd == hwndCancel) && ( (!::IsWindowEnabled(hwndHelp)) || (!::IsWindowVisible(hwndHelp)) ) ) { // Tab is for Cancel button and Help button is disabled fPassToPropertyPage = TRUE; } } } } else if ( ( (VK_LEFT == pMsg->wParam) || (VK_RIGHT == pMsg->wParam) || (VK_UP == pMsg->wParam) || (VK_DOWN == pMsg->wParam) ) && (!fTargetIsOnPage) ) { fPassToPropertyPage = FALSE; } else // Not a tab, back-tab, or arrow key. Pass it to the page. { fPassToPropertyPage = TRUE; } if (fPassToPropertyPage) { if (S_OK == pTlsData->ppgActive->m_piPropertyPage->TranslateAccelerator(pMsg)) { // Property page handled the key. Don't pass msg to wndproc // and to other hooks. lResult = (LRESULT)1; } } Error: if ( (0 == lResult) && (NULL != pTlsData) ) { // Pass the message to other hooks if (NULL != pTlsData->hHook) { lResult = ::CallNextHookEx(pTlsData->hHook, code, wParam, lParam); } } return lResult; } HRESULT CPropertyPageWrapper::ActivatePage() { HRESULT hr = S_OK; HWND hwndPage = NULL; TLSDATA *pTlsData = NULL; HWND hwndTab = NULL; HWND hwndSheet = NULL; MSG msg; ::ZeroMemory(&msg, sizeof(msg)); RECT rect; ::ZeroMemory(&rect, sizeof(rect)); BYTE rgbKeys[256]; ::ZeroMemory(rgbKeys, sizeof(rgbKeys)); // Activate the property page. // // Use the dialog's hwnd as the parent. // // Set the rect to the dialog window's size // // Pass TRUE to indicate that the dialog box frame is modal. This is the // same way OleCreatePropertyFrame() and and OleCreatePropertyFrameIndirect() // work. GetClientRect(m_hwndDlg, &rect); IfFailGo(m_piPropertyPage->Activate(m_hwndDlg, &rect, TRUE)); hwndPage = ::GetTopWindow(m_hwndDlg); if (NULL != hwndPage) { ::SetWindowLong(hwndPage, GWL_STYLE, ::GetWindowLong(hwndPage, GWL_STYLE) & ~(DS_CONTROL | WS_TABSTOP)); ::SetWindowLong(hwndPage, GWL_EXSTYLE, ::GetWindowLong(hwndPage, GWL_EXSTYLE) & ~WS_EX_CONTROLPARENT); } // Tell the page to show itself and set focus to the first property in its // tab order. IfFailGo(m_piPropertyPage->Show(SW_SHOW)); IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData))); IfFalseGo(NULL != pTlsData, S_OK); pTlsData->ppgActive = this; // Fake a tab key to the property page so that the focus will move to // the first control in the page's tabbing order. // Ignore all return codes because if this doesn't work then it is not a // show-stopper. The user would simply have to tab to or click on the first // control. hwndTab = (HWND)::SendMessage(m_hwndSheet, PSM_GETTABCONTROL, 0, 0); IfFalseGo(NULL != hwndTab, S_OK); msg.hwnd = hwndTab; // message intended for focused control msg.message = WM_KEYDOWN; // key pressed msg.wParam = VK_TAB; // tab key msg.lParam = 0x000F0001; // tab key scan code with repeat count=1 msg.time = ::GetTickCount(); // use current time (void)::GetCursorPos(&msg.pt); // use current cursor position // Make sure shift/ctrl/alt keys are not set, since property // pages will interpret the key wrong. (void)::GetKeyboardState(rgbKeys); rgbKeys[VK_SHIFT] &= 0x7F; // remove hi bit (key down) rgbKeys[VK_CONTROL] &= 0x7F; // remove hi bit (key down) rgbKeys[VK_MENU] &= 0x7F; // remove hi bit (key down) (void)::SetKeyboardState(rgbKeys); (void)m_piPropertyPage->TranslateAccelerator(&msg); Error: RRETURN(hr); } HRESULT CPropertyPageWrapper::OnSize() { HRESULT hr = S_OK; RECT rect; ::ZeroMemory(&rect, sizeof(rect)); GetClientRect(m_hwndDlg, &rect); IfFailGo(m_piPropertyPage->Move(&rect)); Error: RRETURN(hr); } HRESULT CPropertyPageWrapper::OnDestroy() { HRESULT hr = S_OK; IUnknown *punkThisObject = PrivateUnknown(); m_pPropertySheet->SetOKToAlterPageCount(FALSE); // Remove the selected objects. We should pass NULL here but in a debugging // session the proxy will return an error if we do. To get around this we // pass a pointer to our own IUnknown. VB will not do anything with it // because the object count is zero. IfFailGo(m_piPropertyPage->SetObjects(0, &punkThisObject)); // Deactivate the property page. IfFailGo(m_piPropertyPage->Deactivate()); // Set the site to NULL so it will remove its ref on us. IfFailGo(m_piPropertyPage->SetPageSite(NULL)); // Release the property page RELEASE(m_piPropertyPage); // Remove this dialog from the message hook TLS data. If there are // no more dialogs remaining then remove the hook. IfFailGo(RemoveMsgFilterHook()); m_pPropertySheet->SetOKToAlterPageCount(TRUE); Error: RRETURN(hr); } HRESULT CPropertyPageWrapper::OnApply(LRESULT *plresult) { HRESULT hr = S_OK; m_pPropertySheet->SetOKToAlterPageCount(FALSE); // Tell the property page to apply its current values to the underlying // object. IfFailGo(m_piPropertyPage->Apply()); m_pPropertySheet->SetOKToAlterPageCount(TRUE); Error: if (FAILED(hr)) { *plresult = PSNRET_INVALID_NOCHANGEPAGE; } else { *plresult = PSNRET_NOERROR; } RRETURN(hr); } HRESULT CPropertyPageWrapper::OnSetActive(HWND hwndSheet, LRESULT *plresult) { HRESULT hr = S_OK; long lNextPage = 0; WizardPageButtonConstants NextOrFinish = EnabledNextButton; VARIANT_BOOL fvarEnableBack = VARIANT_TRUE; BSTR bstrFinishText = NULL; DWORD dwFlags = 0; m_pPropertySheet->SetOKToAlterPageCount(FALSE); // Store the property sheet's HWND and give it to our owning CPropertySheet m_hwndSheet = hwndSheet; m_pPropertySheet->SetHWNDSheet(m_hwndSheet); // If the page is in a wizard then set the wizard buttons if (m_fWizard && (NULL != m_piWizardPage)) { IfFailGo(m_piWizardPage->Activate(&fvarEnableBack, &NextOrFinish, &bstrFinishText)); IfFailGo(m_pPropertySheet->SetWizardButtons(fvarEnableBack, NextOrFinish)); if (NULL != bstrFinishText) { IfFailGo(m_pPropertySheet->SetFinishButtonText(bstrFinishText)); } } // Activate the page and show it IfFailGo(ActivatePage()); m_pPropertySheet->SetOKToAlterPageCount(TRUE); Error: FREESTRING(bstrFinishText); if (FAILED(hr)) { // If anything failed then don't allow the operation. lNextPage = -1L; } *plresult = static_cast<LRESULT>(lNextPage); RRETURN(hr); } HRESULT CPropertyPageWrapper::OnKillActive(LRESULT *plresult) { HRESULT hr = S_OK; TLSDATA *pTlsData = NULL; m_pPropertySheet->SetOKToAlterPageCount(FALSE); IfFailGo(CTls::Get(TLS_SLOT_PPGWRAP, reinterpret_cast<void **>(&pTlsData))); if (NULL != pTlsData) { pTlsData->ppgActive = NULL; } // Tell the property page to apply its current values to the underlying // object. IfFailGo(m_piPropertyPage->Apply()); m_pPropertySheet->SetOKToAlterPageCount(TRUE); Error: if (FAILED(hr)) { // Apply failed. Tell the property sheet to keep the page active *plresult = static_cast<LRESULT>(TRUE); } else { // Apply succeeded. Tell the property sheet it is OK to leave the page *plresult = static_cast<LRESULT>(FALSE); } RRETURN(hr); } HRESULT CPropertyPageWrapper::OnWizBack(LRESULT *plresult) { HRESULT hr = S_OK; long lNextPage = 0; // If the page doesn't support IWizardPage then allow the Back operation. IfFalseGo(NULL != m_piWizardPage, S_OK); IfFailGo(m_piWizardPage->Back(&lNextPage)); if (0 < lNextPage) { // Page requested to move to another page. Get its DLGTEMPLATE pointer. IfFailGo(GetNextPage(&lNextPage)); } Error: if (FAILED(hr)) { // If anything failed then don't allow the Back operation. lNextPage = -1L; } *plresult = static_cast<LRESULT>(lNextPage); RRETURN(hr); } HRESULT CPropertyPageWrapper::OnWizNext(LRESULT *plresult) { HRESULT hr = S_OK; long lNextPage = 0; // If the page doesn't support IWizardPage then allow the Next operation. IfFalseGo(NULL != m_piWizardPage, S_OK); IfFailGo(m_piWizardPage->Next(&lNextPage)); if (0 < lNextPage) { // Page requested to move to another page. Get its DLGTEMPLATE pointer. IfFailGo(GetNextPage(&lNextPage)); } Error: if (FAILED(hr)) { // If anything failed then don't allow the Next operation. lNextPage = -1L; } *plresult = static_cast<LRESULT>(lNextPage); RRETURN(hr); } HRESULT CPropertyPageWrapper::OnWizFinish(LRESULT *plresult) { HRESULT hr = S_OK; VARIANT_BOOL fvarAllow = VARIANT_TRUE; // If the page doesn't support IWizardPage then allow the Finish operation. IfFalseGo(NULL != m_piWizardPage, S_OK); IfFailGo(m_piWizardPage->Finish(&fvarAllow)); // If the finish is allowed and this is a configuration wizard then fire // SnapIn_ConfigurationComplete if ( (VARIANT_TRUE == fvarAllow) && (NULL != m_piSnapIn) && m_fConfigWizard) { IfFailGo(m_piSnapIn->FireConfigComplete(m_pdispConfigObject)); } Error: if (FAILED(hr)) { // If anything failed then don't allow the Finish operation. fvarAllow = VARIANT_FALSE; } else { if (VARIANT_TRUE == fvarAllow) { *plresult = 0; // Allow the property sheet to be destroyed } else { // Do not allow the property sheet to be destroyed *plresult = static_cast<LRESULT>(1); } } RRETURN(hr); } HRESULT CPropertyPageWrapper::OnQueryCancel(LRESULT *plresult) { HRESULT hr = S_OK; VARIANT_BOOL fvarAllow = VARIANT_TRUE; // If the page doesn't support IMMCPropertyPage then allow the Cancel // operation. IfFalseGo(NULL != m_piMMCPropertyPage, S_OK); IfFailGo(m_piMMCPropertyPage->QueryCancel(&fvarAllow)); Error: if (FAILED(hr)) { // If anything failed then don't allow the Cancel operation. fvarAllow = VARIANT_FALSE; } else { if (VARIANT_TRUE == fvarAllow) { // Allow the cancel operation *plresult = static_cast<LRESULT>(FALSE); } else { // Do not allow the cancel operation *plresult = static_cast<LRESULT>(TRUE); } } RRETURN(hr); } HRESULT CPropertyPageWrapper::OnReset(BOOL fClickedXButton) { HRESULT hr = S_OK; m_pPropertySheet->SetOKToAlterPageCount(FALSE); // If the page doesn't support IMMCPropertyPage then ignore this notification IfFalseGo(NULL != m_piMMCPropertyPage, S_OK); if (fClickedXButton) { IfFailGo(m_piMMCPropertyPage->Close()); } else { IfFailGo(m_piMMCPropertyPage->Cancel()); } m_pPropertySheet->SetOKToAlterPageCount(TRUE); Error: RRETURN(hr); } HRESULT CPropertyPageWrapper::OnHelp() { HRESULT hr = S_OK; // If the property page implements IMMCPropertyPage then call the Help // method otherwise call IPropertyPage::Help() if (NULL != m_piMMCPropertyPage) { hr = m_piMMCPropertyPage->Help(); } else { // Call IPropertyPage::Help() on the page. We don't pass the help dir // because VB doesn't register it and it doesn't use it. See the VB // source in vbdev\ruby\deskpage.cpp, DESKPAGE::Help(). hr = m_piPropertyPage->Help(NULL); } RRETURN(hr); } HRESULT CPropertyPageWrapper::GetNextPage(long *lNextPage) { HRESULT hr = S_OK; DLGTEMPLATE *pDlgTemplate = NULL; IfFalseGo(NULL != m_pPropertySheet, SID_E_INTERNAL); // The property sheet has the array of DLGTEMPLATE pointers. Ask it // for the one corresponding to the requested page. IfFailGo(m_pPropertySheet->GetTemplate(*lNextPage, &pDlgTemplate)); *lNextPage = reinterpret_cast<long>(pDlgTemplate); Error: RRETURN(hr); } //=--------------------------------------------------------------------------= // IPropertyPageSite Methods //=--------------------------------------------------------------------------= STDMETHODIMP CPropertyPageWrapper::OnStatusChange(DWORD dwFlags) { if ( PROPPAGESTATUS_DIRTY == (dwFlags & PROPPAGESTATUS_DIRTY) ) { // Enables the apply button ::SendMessage(m_hwndSheet, PSM_CHANGED, (WPARAM)m_hwndDlg, 0); } else { // Disables the apply button. Occurs when page has returned to original // state. In a VB page, would set Changed = False. ::SendMessage(m_hwndSheet, PSM_UNCHANGED, (WPARAM)m_hwndDlg, 0); } return S_OK; } STDMETHODIMP CPropertyPageWrapper::GetLocaleID(LCID *pLocaleID) { *pLocaleID = GetSystemDefaultLCID(); RRETURN((0 == *pLocaleID) ? E_FAIL : S_OK); } STDMETHODIMP CPropertyPageWrapper::GetPageContainer(IUnknown **ppunkContainer) { return E_NOTIMPL; } STDMETHODIMP CPropertyPageWrapper::TranslateAccelerator(MSG *pMsg) { return S_FALSE; } //=--------------------------------------------------------------------------= // CUnknownObject Methods //=--------------------------------------------------------------------------= HRESULT CPropertyPageWrapper::InternalQueryInterface(REFIID riid, void **ppvObjOut) { if (IID_IPropertyPageSite == riid) { *ppvObjOut = static_cast<IPropertyPageSite *>(this); ExternalAddRef(); return S_OK; } else return CSnapInAutomationObject::InternalQueryInterface(riid, ppvObjOut); }
[ "112426112@qq.com" ]
112426112@qq.com
6411c0a5dc9202061a2b7a1a7d246eb39933c93a
38702e29534e03742dedd1cc752990113059509c
/FrontEnd/front/windows/front/MainPage.h
2756305093e34c45c91c8735e4d932576a1a3d5e
[]
no_license
kandabior/Queries
6b9a2cb0aa20cea4dfcbd40b828b19dab2399f7c
6e94dab1e3141dedf613cee503289a873c0dccc1
refs/heads/master
2023-03-19T10:44:31.557522
2021-03-02T15:48:48
2021-03-02T15:48:48
337,340,539
0
0
null
null
null
null
UTF-8
C++
false
false
334
h
#pragma once #include "MainPage.g.h" #include <winrt/Microsoft.ReactNative.h> namespace winrt::front::implementation { struct MainPage : MainPageT<MainPage> { MainPage(); }; } namespace winrt::front::factory_implementation { struct MainPage : MainPageT<MainPage, implementation::MainPage> { }; }
[ "MJFC37@motorolasolutions.com" ]
MJFC37@motorolasolutions.com
0eecb3e8d75575e170659a44fe2232b3a78f9d05
57f624cd3cc3647fc0b8975bbdea821b3b6cba08
/adaboost/templates/instantiated_templates_naive_decision_stump.hpp
75c0308e29ee1c0cb394ead5135e4f0196bcfaae
[]
no_license
2537369758/adaboost
7b73c059f506b4a69ebe1118231d68d021d1ec1f
bbd7f2676cbe53f72324c862ddfcab27d0718259
refs/heads/master
2023-04-01T20:33:01.136821
2020-12-05T11:25:26
2020-12-05T11:25:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
779
hpp
#ifndef ADABOOST_TEMPLATES_INSTANTIATED_TEMPLATES_NAIVE_DECISION_STUMP_HPP #define ADABOOST_TEMPLATES_INSTANTIATED_TEMPLATES_NAIVE_DECISION_STUMP_HPP template class BinaryNaiveDecisionStump<bool>; template class BinaryNaiveDecisionStump<short>; template class BinaryNaiveDecisionStump<unsigned short>; template class BinaryNaiveDecisionStump<int>; template class BinaryNaiveDecisionStump<unsigned int>; template class BinaryNaiveDecisionStump<long>; template class BinaryNaiveDecisionStump<unsigned long>; template class BinaryNaiveDecisionStump<long long>; template class BinaryNaiveDecisionStump<unsigned long long>; template class BinaryNaiveDecisionStump<float>; template class BinaryNaiveDecisionStump<double>; template class BinaryNaiveDecisionStump<long double>; #endif
[ "noreply@github.com" ]
2537369758.noreply@github.com
ff1bc68ac1c1bcb6f6909fee8a169c5298998a4c
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/k_anonymity_service/k_anonymity_trust_token_getter.cc
488cfc357870df6582cba5bdc9fdb1883376ecd4
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
19,155
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/k_anonymity_service/k_anonymity_trust_token_getter.h" #include "base/json/json_writer.h" #include "base/json/values_util.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" #include "chrome/browser/k_anonymity_service/k_anonymity_service_metrics.h" #include "chrome/browser/k_anonymity_service/k_anonymity_service_urls.h" #include "chrome/common/chrome_features.h" #include "content/public/browser/browser_thread.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/google_api_keys.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "net/base/load_flags.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/simple_url_loader.h" namespace { constexpr base::TimeDelta kRequestMargin = base::Minutes(5); constexpr base::TimeDelta kRequestTimeout = base::Minutes(1); constexpr net::NetworkTrafficAnnotationTag kKAnonymityServiceGetTokenTrafficAnnotation = net::DefineNetworkTrafficAnnotation("k_anonymity_service_get_token", R"( semantics { sender: "Chrome k-Anonymity Service Client" description: "Request to the Chrome k-Anonymity Auth server to obtain a trust token" trigger: "The Chrome k-Anonymity Service Client is out of trust tokens" data: "Chrome sign-in OAuth Token" destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Disable features using k-anonymity, such as FLEDGE and Attribution " "Reporting." chrome_policy { } } comments: "" )"); } // namespace KAnonymityTrustTokenGetter::PendingRequest::PendingRequest( KAnonymityTrustTokenGetter::TryGetTrustTokenAndKeyCallback callback) : request_start(base::TimeTicks::Now()), callback(std::move(callback)) {} KAnonymityTrustTokenGetter::PendingRequest::~PendingRequest() = default; KAnonymityTrustTokenGetter::PendingRequest::PendingRequest( KAnonymityTrustTokenGetter::PendingRequest&&) noexcept = default; KAnonymityTrustTokenGetter::PendingRequest& KAnonymityTrustTokenGetter::PendingRequest::operator=( KAnonymityTrustTokenGetter::PendingRequest&&) noexcept = default; KAnonymityTrustTokenGetter::KAnonymityTrustTokenGetter( signin::IdentityManager* identity_manager, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, network::mojom::TrustTokenQueryAnswerer* answerer, KAnonymityServiceStorage* storage) : identity_manager_(identity_manager), url_loader_factory_(std::move(url_loader_factory)), trust_token_query_answerer_(answerer), storage_(storage) { auth_origin_ = url::Origin::Create(GURL(features::kKAnonymityServiceAuthServer.Get())); isolation_info_ = net::IsolationInfo::Create( net::IsolationInfo::RequestType::kOther, auth_origin_, auth_origin_, net::SiteForCookies()); } KAnonymityTrustTokenGetter::~KAnonymityTrustTokenGetter() = default; void KAnonymityTrustTokenGetter::TryGetTrustTokenAndKey( TryGetTrustTokenAndKeyCallback callback) { if ((!base::FeatureList::IsEnabled(network::features::kPrivateStateTokens) && !base::FeatureList::IsEnabled(network::features::kFledgePst)) || !identity_manager_ || !identity_manager_->HasPrimaryAccount(signin::ConsentLevel::kSignin)) { std::move(callback).Run(absl::nullopt); return; } RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kTryGetTrustTokenAndKey); bool currently_fetching = pending_callbacks_.size() > 0; pending_callbacks_.emplace_back(std::move(callback)); if (currently_fetching) return; TryGetTrustTokenAndKeyInternal(); } // This function is where we start for each queued request. void KAnonymityTrustTokenGetter::TryGetTrustTokenAndKeyInternal() { CheckAccessToken(); } void KAnonymityTrustTokenGetter::CheckAccessToken() { if (access_token_.expiration_time <= base::Time::Now() + kRequestMargin) { RequestAccessToken(); return; } CheckTrustTokenKeyCommitment(); } void KAnonymityTrustTokenGetter::RequestAccessToken() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kRequestAccessToken); // Choose scopes to obtain for the access token. signin::ScopeSet scopes; scopes.insert(GaiaConstants::kKAnonymityServiceOAuth2Scope); // Choose the mode in which to fetch the access token: // see AccessTokenFetcher::Mode below for definitions. auto mode = signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable; // Create the fetcher. access_token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( /*consumer_name=*/"KAnonymityService", identity_manager_, scopes, base::BindOnce( &KAnonymityTrustTokenGetter::OnAccessTokenRequestCompleted, weak_ptr_factory_.GetWeakPtr()), mode, signin::ConsentLevel::kSignin); } void KAnonymityTrustTokenGetter::OnAccessTokenRequestCompleted( GoogleServiceAuthError error, signin::AccessTokenInfo access_token_info) { access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kAccessTokenRequestFailed); FailAllCallbacks(); return; } access_token_ = access_token_info; CheckTrustTokenKeyCommitment(); } void KAnonymityTrustTokenGetter::CheckTrustTokenKeyCommitment() { absl::optional<KeyAndNonUniqueUserIdWithExpiration> key_commitment = storage_->GetKeyAndNonUniqueUserId(); if (!key_commitment || key_commitment->expiration <= base::Time::Now() + kRequestMargin) { FetchNonUniqueUserId(); return; } CheckTrustTokens(); } void KAnonymityTrustTokenGetter::FetchNonUniqueUserId() { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientID); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = auth_origin_.GetURL().Resolve(kGenNonUniqueUserIdPath); resource_request->headers.SetHeader( net::HttpRequestHeaders::kAuthorization, base::StrCat({"Bearer ", access_token_.token})); resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; resource_request->trusted_params.emplace(); resource_request->trusted_params->isolation_info = isolation_info_; url_loader_ = network::SimpleURLLoader::Create( std::move(resource_request), kKAnonymityServiceGetTokenTrafficAnnotation); url_loader_->SetTimeoutDuration(kRequestTimeout); // The response should just contain a JSON message containing a uint32. url_loader_->DownloadToString( url_loader_factory_.get(), base::BindOnce(&KAnonymityTrustTokenGetter::OnFetchedNonUniqueUserId, weak_ptr_factory_.GetWeakPtr()), /*max_body_size=*/1024); } void KAnonymityTrustTokenGetter::OnFetchedNonUniqueUserId( std::unique_ptr<std::string> response) { url_loader_.reset(); if (!response) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientIDFailed); FailAllCallbacks(); return; } data_decoder::DataDecoder::ParseJsonIsolated( *response, base::BindOnce(&KAnonymityTrustTokenGetter::OnParsedNonUniqueUserId, weak_ptr_factory_.GetWeakPtr())); } void KAnonymityTrustTokenGetter::OnParsedNonUniqueUserId( data_decoder::DataDecoder::ValueOrError result) { if (!result.has_value()) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientIDParseError); FailAllCallbacks(); return; } base::Value::Dict* response_dict = result->GetIfDict(); if (!response_dict) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientIDParseError); FailAllCallbacks(); return; } absl::optional<int> maybe_non_unique_user_id = response_dict->FindInt("shortClientIdentifier"); if (!maybe_non_unique_user_id) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchNonUniqueClientIDParseError); FailAllCallbacks(); return; } FetchTrustTokenKeyCommitment(*maybe_non_unique_user_id); } void KAnonymityTrustTokenGetter::FetchTrustTokenKeyCommitment( int non_unique_user_id) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKey); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = auth_origin_.GetURL().Resolve(base::StringPrintf( kFetchKeysPathFmt, non_unique_user_id, google_apis::GetAPIKey().c_str())); resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; // No credentials required for // key fetch. resource_request->trusted_params.emplace(); resource_request->trusted_params->isolation_info = isolation_info_; url_loader_ = network::SimpleURLLoader::Create( std::move(resource_request), kKAnonymityServiceGetTokenTrafficAnnotation); url_loader_->SetTimeoutDuration(kRequestTimeout); url_loader_->DownloadToString( url_loader_factory_.get(), base::BindOnce( &KAnonymityTrustTokenGetter::OnFetchedTrustTokenKeyCommitment, weak_ptr_factory_.GetWeakPtr(), non_unique_user_id), /*max_body_size=*/4096); } void KAnonymityTrustTokenGetter::OnFetchedTrustTokenKeyCommitment( int non_unique_user_id, std::unique_ptr<std::string> response) { if (url_loader_->NetError() != net::OK) { url_loader_.reset(); RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyFailed); FailAllCallbacks(); return; } url_loader_.reset(); data_decoder::DataDecoder::ParseJsonIsolated( *response, base::BindOnce( &KAnonymityTrustTokenGetter::OnParsedTrustTokenKeyCommitment, weak_ptr_factory_.GetWeakPtr(), non_unique_user_id)); } // The server sends the key commitment in a custom message format. We have to // reformat the response from the server into a format the browser understands // (V3 trust token key commitment). See the explainer here: // https://github.com/WICG/trust-token-api/blob/main/ISSUER_PROTOCOL.md void KAnonymityTrustTokenGetter::OnParsedTrustTokenKeyCommitment( int non_unique_user_id, data_decoder::DataDecoder::ValueOrError result) { if (!result.has_value()) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } base::Value::Dict* response_dict = result->GetIfDict(); if (!response_dict) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } std::string* maybe_version = response_dict->FindString("protocolVersion"); if (!maybe_version) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } const absl::optional<int> maybe_id = response_dict->FindInt("id"); if (!maybe_id) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } const absl::optional<int> maybe_batchsize = response_dict->FindInt("batchSize"); if (!maybe_batchsize) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } base::Value::List* maybe_keys = response_dict->FindList("keys"); if (!maybe_keys) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } if (maybe_keys->empty()) { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } int64_t max_expiry = 0; base::Value::Dict keys_out; for (base::Value& key_commitment : *maybe_keys) { base::Value::Dict* key_commit_dict = key_commitment.GetIfDict(); if (!key_commit_dict) { DLOG(ERROR) << "Key commitment not a dict: " << key_commitment.DebugString(); RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } const std::string* maybe_key = key_commit_dict->FindString("keyMaterial"); absl::optional<int> maybe_key_id = key_commit_dict->FindInt("keyIdentifier"); const std::string* maybe_expiry = key_commit_dict->FindString("expirationTimestampUsec"); int64_t expiry; if (!maybe_key || !maybe_key_id || !maybe_expiry) { DLOG(ERROR) << "Key commitment missing required field: " << key_commitment.DebugString(); RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } if (!base::StringToInt64(*maybe_expiry, &expiry)) { DLOG(ERROR) << "Key commitment expiry has invalid format: " << *maybe_expiry; RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenKeyParseError); FailAllCallbacks(); return; } max_expiry = std::max(max_expiry, expiry); base::Value::Dict key_out; key_out.Set("Y", *maybe_key); key_out.Set("expiry", *maybe_expiry); keys_out.Set(base::NumberToString(*maybe_key_id), std::move(key_out)); } base::Value::Dict key_commitment_value; key_commitment_value.Set("protocol_version", *maybe_version); key_commitment_value.Set("id", *maybe_id); key_commitment_value.Set("batchsize", *maybe_batchsize); key_commitment_value.Set("keys", std::move(keys_out)); base::Value::Dict outer_commitment; outer_commitment.Set(*maybe_version, std::move(key_commitment_value)); std::string key_commitment_str; base::JSONWriter::Write(outer_commitment, &key_commitment_str); KeyAndNonUniqueUserIdWithExpiration key_commitment{ KeyAndNonUniqueUserId{key_commitment_str, non_unique_user_id}, base::Time::UnixEpoch() + base::Microseconds(max_expiry)}; storage_->UpdateKeyAndNonUniqueUserId(key_commitment); CheckTrustTokens(); } void KAnonymityTrustTokenGetter::CheckTrustTokens() { trust_token_query_answerer_->HasTrustTokens( auth_origin_, base::BindOnce(&KAnonymityTrustTokenGetter::OnHasTrustTokensComplete, weak_ptr_factory_.GetWeakPtr())); } void KAnonymityTrustTokenGetter::OnHasTrustTokensComplete( network::mojom::HasTrustTokensResultPtr result) { if (!result || result->status != network::mojom::TrustTokenOperationStatus::kOk) { DLOG(ERROR) << "Failed checking trust tokens " << result->status; FailAllCallbacks(); return; } if (!result->has_trust_tokens) { FetchTrustToken(); return; } CompleteOneRequest(); } void KAnonymityTrustTokenGetter::FetchTrustToken() { auto key_commitment = storage_->GetKeyAndNonUniqueUserId(); DCHECK(key_commitment); RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustToken); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = auth_origin_.GetURL().Resolve(base::StringPrintf( kIssueTrustTokenPathFmt, key_commitment->key_and_id.non_unique_user_id)); resource_request->method = net::HttpRequestHeaders::kPostMethod; resource_request->headers.SetHeader( net::HttpRequestHeaders::kAuthorization, base::StrCat({"Bearer ", access_token_.token})); resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; // No cache read, always download // from the network. resource_request->load_flags = net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_CACHE; resource_request->trusted_params.emplace(); resource_request->trusted_params->isolation_info = isolation_info_; network::mojom::TrustTokenParamsPtr params = network::mojom::TrustTokenParams::New(); params->version = network::mojom::TrustTokenMajorVersion::kPrivateStateTokenV1; params->operation = network::mojom::TrustTokenOperationType::kIssuance; params->custom_key_commitment = key_commitment->key_and_id.key_commitment; resource_request->trust_token_params = *params; url_loader_ = network::SimpleURLLoader::Create( std::move(resource_request), kKAnonymityServiceGetTokenTrafficAnnotation); url_loader_->SetTimeoutDuration(kRequestTimeout); url_loader_->DownloadHeadersOnly( url_loader_factory_.get(), base::BindOnce(&KAnonymityTrustTokenGetter::OnFetchedTrustToken, weak_ptr_factory_.GetWeakPtr())); } void KAnonymityTrustTokenGetter::OnFetchedTrustToken( scoped_refptr<net::HttpResponseHeaders> headers) { if (url_loader_->NetError() != net::OK) { DLOG(ERROR) << "Couldn't get trust token: " << url_loader_->NetError(); url_loader_.reset(); RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kFetchTrustTokenFailed); FailAllCallbacks(); return; } url_loader_.reset(); // If the fetch succeeded, that means that the response included the trust // tokens we requested. They are stored in the network service so we can // redeem them later. CompleteOneRequest(); } void KAnonymityTrustTokenGetter::FailAllCallbacks() { while (!pending_callbacks_.empty()) DoCallback(false); } void KAnonymityTrustTokenGetter::CompleteOneRequest() { RecordTrustTokenGetterAction( KAnonymityTrustTokenGetterAction::kGetTrustTokenSuccess); // Only record timing UMA when we actually fetched a token. RecordTrustTokenGet(pending_callbacks_.front().request_start, base::TimeTicks::Now()); DoCallback(true); if (!pending_callbacks_.empty()) TryGetTrustTokenAndKeyInternal(); } void KAnonymityTrustTokenGetter::DoCallback(bool status) { DCHECK(!pending_callbacks_.empty()); absl::optional<KeyAndNonUniqueUserId> result; if (status) { auto key_commitment = storage_->GetKeyAndNonUniqueUserId(); DCHECK(key_commitment); result = key_commitment->key_and_id; } // We call the callback *before* removing the current request from the list. // It is possible that the callback may synchronously enqueue another request. // If we remove the current request first then enqueuing the request would // start another thread of execution since there was an empty queue. std::move(pending_callbacks_.front().callback).Run(result); pending_callbacks_.pop_front(); }
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
9d630978e4625bf2d710321d51cd4a17fd676938
31651f58f0fc7ab6cd5174eb406463531c563926
/datasets/ptb/simple-examples/rnnlm-0.2b/rnnlm.cpp
018f3ce196f38598f354af6df58b16b516e6f97c
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-2-Clause" ]
permissive
CavHack/pipeline
76ee26f016a9503b4ea62bb631930d7c452a1cfd
b397e283d22843d9e05e2f5625affacf9bede741
refs/heads/master
2021-07-03T20:00:39.734917
2016-09-24T01:59:59
2016-09-24T01:59:59
69,131,791
1
0
Apache-2.0
2021-06-04T02:48:48
2016-09-24T22:54:23
Jupyter Notebook
UTF-8
C++
false
false
14,551
cpp
/////////////////////////////////////////////////////////////////////// // // Recurrent neural network based statistical language modeling toolkit // Version 0.2b // (c) 2010 Tomas Mikolov (tmikolov@gmail.com) // /////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <fstream> #include <iostream> #include "rnnlmlib.h" using namespace std; #define MAX_STRING 100 int argPos(char *str, int argc, char **argv) { int a; for (a=1; a<argc; a++) if (!strcmp(str, argv[a])) return a; return -1; } int main(int argc, char **argv) { int i; int debug_mode=1; int train_mode=0; int valid_data_set=0; int test_data_set=0; int rnnlm_file_set=0; int alpha_set=0, train_file_set=0; int class_size=100; float lambda=0.75; float dynamic=0; float starting_alpha=0.1; float regularization=0.0000001; float min_improvement=1.003; int hidden_size=30; int direct=0; int bptt=0; int bptt_block=10; int gen=0; int rnnlm_exist=0; int use_lmprob=0; int rand_seed=1; int nbest=0; int one_iter=0; int anti_k=0; char train_file[MAX_STRING]; char valid_file[MAX_STRING]; char test_file[MAX_STRING]; char rnnlm_file[MAX_STRING]; char lmprob_file[MAX_STRING]; FILE *f; if (argc==1) { //printf("Help\n"); printf("Recurrent neural network based language modeling toolkit v 0.2b\n\n"); printf("Options:\n"); // printf("Parameters for training phase:\n"); printf("\t-train <file>\n"); printf("\t\tUse text data from <file> to train rnnlm model\n"); printf("\t-class <int>\n"); printf("\t\tWill use specified amount of classes to decompose vocabulary; default is 100\n"); printf("\t-rnnlm <file>\n"); printf("\t\tUse <file> to store rnnlm model\n"); printf("\t-valid <file>\n"); printf("\t\tUse <file> as validation data\n"); printf("\t-alpha <float>\n"); printf("\t\tSet starting learning rate; default is 0.1\n"); printf("\t-beta <float>\n"); printf("\t\tSet L2 regularization parameter; default is 1e-7\n"); printf("\t-hidden <int>\n"); printf("\t\tSet size of hidden layer; default is 30\n"); printf("\t-direct <int>\n"); printf("\t\tWill use direct connections between input and output layers for most frequent <int> words; default is 0\n"); printf("\t-bptt <int>\n"); printf("\t\tSet amount of steps to propagate error back in time; default is 0 (equal to simple RNN)\n"); printf("\t-bptt-block <int>\n"); printf("\t\tSpecifies amount of time steps after which the error is backpropagated through time in block mode (default 10, update at each time step = 1)\n"); printf("\t-one-iter\n"); printf("\t\tWill cause training to perform exactly one iteration over training data (useful for adapting final models on different data etc.)\n"); printf("\t-anti-kasparek <int>\n"); printf("\t\tModel will be saved during training after processing specified amount of words\n"); printf("\t-min-improvement <float>\n"); printf("\t\tSet minimal relative entropy improvement for training convergence; default is 1.003\n"); // printf("Parameters for testing phase:\n"); printf("\t-rnnlm <file>\n"); printf("\t\tRead rnnlm model from <file>\n"); printf("\t-test <file>\n"); printf("\t\tUse <file> as test data to report perplexity\n"); printf("\t-lm-prob\n"); printf("\t\tUse other LM probabilities for linear interpolation with rnnlm model; see examples/*** \n"); //*** printf("\t-lambda <float>\n"); printf("\t\tSet parameter for linear interpolation of rnnlm and other lm; default weight of rnnlm is 0.75\n"); printf("\t-dynamic <float>\n"); printf("\t\tSet learning rate for dynamic model updates during testing phase; default is 0 (static model)\n"); // printf("Parameters for data generation:\n"); printf("\t-gen <int>\n"); printf("\t\tGenerate specified amount of words given distribution from current model\n"); printf("\nExamples:\n"); printf("rnnlm -train train -rnnlm model -valid valid -hidden 50\n"); printf("rnnlm -rnnlm model -test test\n"); printf("\n"); return 0; //*** } //set debug mode i=argPos((char *)"-debug", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: debug mode not specified!\n"); return 0; } debug_mode=atoi(argv[i+1]); if (debug_mode>0) printf("debug mode: %d\n", debug_mode); } //search for train file i=argPos((char *)"-train", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: training data file not specified!\n"); return 0; } strcpy(train_file, argv[i+1]); if (debug_mode>0) printf("train file: %s\n", train_file); f=fopen(train_file, "rb"); if (f==NULL) { printf("ERROR: training data file not found!\n"); return 0; } train_mode=1; train_file_set=1; } //set one-iter i=argPos((char *)"-one-iter", argc, argv); if (i>0) { one_iter=1; if (debug_mode>0) printf("Training for one iteration\n"); } //search for validation file i=argPos((char *)"-valid", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: validation data file not specified!\n"); return 0; } strcpy(valid_file, argv[i+1]); if (debug_mode>0) printf("valid file: %s\n", valid_file); f=fopen(valid_file, "rb"); if (f==NULL) { printf("ERROR: validation data file not found!\n"); return 0; } valid_data_set=1; } if (train_mode && !valid_data_set) { if (one_iter==0) { printf("ERROR: validation data file must be specified for training!\n"); return 0; } } //search for test file i=argPos((char *)"-test", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: test data file not specified!\n"); return 0; } strcpy(test_file, argv[i+1]); if (debug_mode>0) printf("test file: %s\n", test_file); f=fopen(test_file, "rb"); if (f==NULL) { printf("ERROR: test data file not found!\n"); return 0; } test_data_set=1; } //set class size parameter i=argPos((char *)"-class", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: amount of classes not specified!\n"); return 0; } class_size=atoi(argv[i+1]); if (debug_mode>0) printf("class size: %d\n", class_size); } //set lambda i=argPos((char *)"-lambda", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: lambda not specified!\n"); return 0; } lambda=atof(argv[i+1]); if (debug_mode>0) printf("Lambda (interpolation coefficient between rnnlm and other lm): %f\n", lambda); } //set dynamic i=argPos((char *)"-dynamic", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: dynamic learning rate not specified!\n"); return 0; } dynamic=atof(argv[i+1]); if (debug_mode>0) printf("Dynamic learning rate: %f\n", dynamic); } //set gen i=argPos((char *)"-gen", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: gen parameter not specified!\n"); return 0; } gen=atoi(argv[i+1]); if (debug_mode>0) printf("Generating # words: %d\n", gen); } //set learning rate i=argPos((char *)"-alpha", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: alpha not specified!\n"); return 0; } starting_alpha=atof(argv[i+1]); if (debug_mode>0) printf("Starting learning rate: %f\n", starting_alpha); alpha_set=1; } //set regularization i=argPos((char *)"-beta", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: beta not specified!\n"); return 0; } regularization=atof(argv[i+1]); if (debug_mode>0) printf("Regularization: %f\n", regularization); } //set min improvement i=argPos((char *)"-min-improvement", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: minimal improvement value not specified!\n"); return 0; } min_improvement=atof(argv[i+1]); if (debug_mode>0) printf("Min improvement: %f\n", min_improvement); } //set anti kasparek i=argPos((char *)"-anti-kasparek", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: anti-kasparek parameter not set!\n"); return 0; } anti_k=atoi(argv[i+1]); if ((anti_k!=0) && (anti_k<10000)) anti_k=10000; if (debug_mode>0) printf("Model will be saved after each # words: %d\n", anti_k); } //set hidden layer size i=argPos((char *)"-hidden", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: hidden layer size not specified!\n"); return 0; } hidden_size=atoi(argv[i+1]); if (debug_mode>0) printf("Hidden layer size: %d\n", hidden_size); } //set direct connections i=argPos((char *)"-direct", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: direct connections not specified!\n"); return 0; } direct=atoi(argv[i+1]); if (debug_mode>0) printf("Direct connections: %d\n", direct); } //set bptt i=argPos((char *)"-bptt", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: bptt value not specified!\n"); return 0; } bptt=atoi(argv[i+1]); bptt++; if (bptt<1) bptt=0; if (debug_mode>0) printf("BPTT: %d\n", bptt-1); } //set bptt block i=argPos((char *)"-bptt-block", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: bptt block value not specified!\n"); return 0; } bptt_block=atoi(argv[i+1]); if (bptt_block<1) bptt_block=1; if (debug_mode>0) printf("BPTT block: %d\n", bptt_block); } //set random seed i=argPos((char *)"-rand-seed", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: Random seed variable not specified!\n"); return 0; } rand_seed=atoi(argv[i+1]); if (debug_mode>0) printf("Rand seed: %d\n", rand_seed); } //set nbest rescoring mode i=argPos((char *)"-nbest", argc, argv); if (i>0) { nbest=1; if (debug_mode>0) printf("Processing test data as list of nbests\n"); } //use other lm i=argPos((char *)"-lm-prob", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: other lm file not specified!\n"); return 0; } strcpy(lmprob_file, argv[i+1]); if (debug_mode>0) printf("other lm probabilities specified in: %s\n", lmprob_file); f=fopen(lmprob_file, "rb"); if (f==NULL) { printf("ERROR: other lm file not found!\n"); return 0; } use_lmprob=1; } //search for rnnlm file i=argPos((char *)"-rnnlm", argc, argv); if (i>0) { if (i+1==argc) { printf("ERROR: model file not specified!\n"); return 0; } strcpy(rnnlm_file, argv[i+1]); if (debug_mode>0) printf("rnnlm file: %s\n", rnnlm_file); f=fopen(rnnlm_file, "rb"); if (f!=NULL) { rnnlm_exist=1; } rnnlm_file_set=1; } if (train_mode && !rnnlm_file_set) { printf("ERROR: rnnlm file must be specified for training!\n"); return 0; } if (test_data_set && !rnnlm_file_set) { printf("ERROR: rnnlm file must be specified for testing!\n"); return 0; } if (!test_data_set && !train_mode && gen==0) { printf("ERROR: training or testing must be specified!\n"); return 0; } if ((gen>0) && !rnnlm_file_set) { printf("ERROR: rnnlm file must be specified to generate words!\n"); return 0; } srand(1); if (train_mode) { CRnnLM model1; model1.setTrainFile(train_file); model1.setRnnLMFile(rnnlm_file); model1.setOneIter(one_iter); if (one_iter==0) model1.setValidFile(valid_file); model1.setClassSize(class_size); model1.setLearningRate(starting_alpha); model1.setRegularization(regularization); model1.setMinImprovement(min_improvement); model1.setHiddenLayerSize(hidden_size); model1.setDirectSize(direct); model1.setBPTT(bptt); model1.setBPTTBlock(bptt_block); model1.setRandSeed(rand_seed); model1.setDebugMode(debug_mode); model1.setAntiKasparek(anti_k); model1.alpha_set=alpha_set; model1.train_file_set=train_file_set; model1.trainNet(); } if (test_data_set && rnnlm_file_set) { CRnnLM model1; model1.setLambda(lambda); model1.setRegularization(regularization); model1.setDynamic(dynamic); model1.setTestFile(test_file); model1.setRnnLMFile(rnnlm_file); model1.setRandSeed(rand_seed); model1.useLMProb(use_lmprob); if (use_lmprob) model1.setLMProbFile(lmprob_file); model1.setDebugMode(debug_mode); if (nbest==0) model1.testNet(); else model1.testNbest(); } if (gen>0) { CRnnLM model1; model1.setRnnLMFile(rnnlm_file); model1.setDebugMode(debug_mode); model1.setRandSeed(rand_seed); model1.setGen(gen); model1.testGen(); } return 0; }
[ "chris@fregly.com" ]
chris@fregly.com
6d593282f13b69af8e64f415bd10d754ec71d582
971574c9d61071b8de016ca98b8579885143af82
/src/hypotheses/hypothesis_with_points.cpp
f124aa4ecf58da26fcd72fa8eb0874b24631aa49
[ "BSD-3-Clause" ]
permissive
AIS-Bonn/multi_hypothesis_tracking
6066982e998a69db849ee71f83ba35d2347629da
e9854feee98001a1ea5190fcab4930d1880574f4
refs/heads/master
2023-07-01T01:27:36.727692
2021-07-27T15:05:43
2021-07-27T15:05:43
389,998,243
3
1
null
null
null
null
UTF-8
C++
false
false
2,719
cpp
/** @file * * Implementation of a hypothesis extended with point measurements on detected objects. * * @author Jan Razlaw */ #include "multi_hypothesis_tracking/hypotheses/hypothesis_with_points.h" namespace MultiHypothesisTracker { HypothesisWithPoints::HypothesisWithPoints(const Detection& detection, unsigned int id, double time_stamp, bool accumulate_detection_points_in_hypothesis) : HypothesisBase(detection, id, time_stamp) , m_accumulate_detection_points_in_hypothesis(accumulate_detection_points_in_hypothesis) { m_points = detection.points; } void HypothesisWithPoints::predict(float time_difference) { HypothesisBase::predict(time_difference); HypothesisWithPoints::updatePointsAfterPrediction(); } void HypothesisWithPoints::updatePointsAfterPrediction() { const auto& current_position = m_history.position_history.end()[-2]; const auto& predicted_position = m_history.position_history.end()[-1]; const auto& translation_from_current_to_predicted_position = (predicted_position - current_position).eval(); transformPoints(m_points, translation_from_current_to_predicted_position); } void HypothesisWithPoints::transformPoints(std::vector<Eigen::Vector3f>& points, const Eigen::Vector3f& translation) { for(auto& point : points) point += translation; } void HypothesisWithPoints::correct(const Detection& detection) { const auto predicted_position = m_history.position_history.back(); HypothesisBase::correct(detection); if(m_accumulate_detection_points_in_hypothesis) { updatePointsAfterCorrection(predicted_position); appendDetectionPoints(detection); } else m_points = detection.points; } void HypothesisWithPoints::updatePointsAfterCorrection(const Eigen::Vector3f& predicted_position) { const auto& corrected_position = m_history.position_history.back(); auto translation_from_predicted_to_corrected_position = (corrected_position - predicted_position).eval(); transformPoints(m_points, translation_from_predicted_to_corrected_position); } void HypothesisWithPoints::appendDetectionPoints(const Detection& detection) { const auto transform_detection_to_corrected = (getPosition() - detection.position).eval(); std::vector<Eigen::Vector3f> corrected_detection_points = detection.points; transformPoints(corrected_detection_points, transform_detection_to_corrected); m_points.reserve(m_points.size() + corrected_detection_points.size()); m_points.insert(m_points.end(), corrected_detection_points.begin(), corrected_detection_points.end()); } };
[ "s6jarazl@uni-bonn.de" ]
s6jarazl@uni-bonn.de
f3033af10cbf5ec1bb20718be6f63168eced9cb8
f05155d1c9c41fcc6e31686505f856fd2fbc06de
/2019/octobor 2019/atl bangla 18 part 2.cpp
d820369f2af9ec4c15cb8e41c62c0d55975b267b
[]
no_license
T-tasir/Competetive-Programming
22308db58c827a8dfa9d2f879f7a1c135f3ab96a
b56ab712fd2147a69b90b7300e281b9b6ed85852
refs/heads/main
2023-08-18T07:35:22.656508
2021-10-14T13:20:33
2021-10-14T13:20:33
368,572,215
0
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
//#include<bits/stdc++.h> #include<iostream> #include<set> #include<map> #include<iterator> using namespace std; int main() { multiset<int>s; multiset<int>::iterator it; s.insert(100); s.insert(100); s.insert(100); s.insert(1); for(it=s.begin();it!=s.end();it++){ cout<< *it <<endl; } return 0; }
[ "allmoontasir256@gmail.com" ]
allmoontasir256@gmail.com
d77d40327ab44d7a33742b5ff6f8a1e2e7cb3b16
f6ef1f50a476c3ed58b4f268feb6fb438996f06a
/有OJ/刷题指南(包含leetcode, POJ, PAT等)/POJ-1/problems/3020.cpp
f1d0d18308fe77a0b88bb5ce26d65a93be763c57
[]
no_license
February13/OJ_Guide
f9d6c72fc2863f5b6f3ad80b0d6c68b51f9a07db
a190942fae29a0dbee306adc81ee245be7fda44a
refs/heads/master
2020-04-25T09:01:48.458939
2018-01-18T08:31:30
2018-01-18T08:31:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,454
cpp
#include<iostream> #define MN 401 bool GE[MN][MN],check[MN]; int h,w,q,point[MN][2],map[40][10]; int match[MN],min,x,y; bool DFS(int p); void construct(); int main() { int i,j,k,n,s; scanf("%d",&n); for (i=0;i<n;i++) { q=1; scanf("%d%d",&h,&w); for (j=0;j<h;j++) { getchar(); for (k=0;k<w;k++) { if (getchar()=='*') map[j][k]=q++; else map[j][k]=0; } } memset(GE,false,sizeof(GE)); x=1; y=q-1; for (j=0;j<h;j++) { for (k=0;k<w;k++) { if (map[j][k]>0) { if ((j+k)%2==0) { point[x][0]=j; point[x][1]=k; map[j][k]=x++; } else{ point[y][0]=j; point[y][1]=k; map[j][k]=y--; } } } } construct(); memset(match,-1,sizeof(match)); s=0; for(k=1;k<x;k++) { memset(check,false,sizeof(check)); if (DFS(k)) s++; } min=q-1-s; printf("%d\n",min); } return 0; } bool DFS(int p) { int i,t,a,b; if (p<x) a=x,b=q; else a=1,b=x; for(i=a;i<b;i++) { if (GE[i][p] && !check[i]) { check[i]=true; t=match[i]; match[i]=p; if (t==-1 || DFS(t)) return true; match[i]=t; } } return false; } void construct() { int i,p,a,b; for (i=1;i<q;i++) { a=point[i][0]; b=point[i][1]; if (a>0 && (p=map[a-1][b])>0) GE[i][p]=true; if (a<h-1 && (p=map[a+1][b])>0) GE[i][p]=true; if (b>0 && (p=map[a][b-1])>0) GE[i][p]=true; if (b<w-1 && (p=map[a][b+1])>0) GE[i][p]=true; } }
[ "zhaoqijie@pku.edu.cn" ]
zhaoqijie@pku.edu.cn
2fabb0fe19a9f48de6d164d1cda43172e1a503ea
f6f55778056b4c008bfd5897a028faf20c6927a7
/src/qt/privacydialog.cpp
fd55a10cb40370b228b94c4b624e4db71f78be74
[ "MIT" ]
permissive
bright-project/brightcoin
f3b3c140a669be11dfc54d797397a46c70c14cab
b42683d82a65b96861383d8b3e4c7d22b92acc70
refs/heads/master
2020-03-29T20:06:59.302242
2018-09-25T16:33:53
2018-09-25T16:33:53
150,296,212
0
0
null
null
null
null
UTF-8
C++
false
false
28,569
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privacydialog.h" #include "ui_privacydialog.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "coincontroldialog.h" #include "libzerocoin/Denominations.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "coincontrol.h" #include "zbrightcoincontroldialog.h" #include "spork.h" #include <QClipboard> #include <QSettings> #include <utilmoneystr.h> #include <QtWidgets> PrivacyDialog::PrivacyDialog(QWidget* parent) : QDialog(parent), ui(new Ui::PrivacyDialog), walletModel(0), currentBalance(-1) { nDisplayUnit = 0; // just make sure it's not unitialized ui->setupUi(this); // "Spending 999999 zBRIGHTCOIN ought to be enough for anybody." - Bill Gates, 2017 ui->zBRIGHTCOINpayAmount->setValidator( new QDoubleValidator(0.0, 21000000.0, 20, this) ); ui->labelMintAmountValue->setValidator( new QIntValidator(0, 999999, this) ); // Default texts for (mini-) coincontrol ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); ui->labelzBRIGHTCOINSyncStatus->setText("(" + tr("out of sync") + ")"); // Sunken frame for minting messages ui->TEMintStatus->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); ui->TEMintStatus->setLineWidth (2); ui->TEMintStatus->setMidLineWidth (2); ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Coin Control signals connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); // Denomination labels ui->labelzDenom1Text->setText("Denom. with value <b>1</b>:"); ui->labelzDenom2Text->setText("Denom. with value <b>5</b>:"); ui->labelzDenom3Text->setText("Denom. with value <b>10</b>:"); ui->labelzDenom4Text->setText("Denom. with value <b>50</b>:"); ui->labelzDenom5Text->setText("Denom. with value <b>100</b>:"); ui->labelzDenom6Text->setText("Denom. with value <b>500</b>:"); ui->labelzDenom7Text->setText("Denom. with value <b>1000</b>:"); ui->labelzDenom8Text->setText("Denom. with value <b>5000</b>:"); // BRIGHTCOIN settings QSettings settings; if (!settings.contains("nSecurityLevel")){ nSecurityLevel = 42; settings.setValue("nSecurityLevel", nSecurityLevel); } else{ nSecurityLevel = settings.value("nSecurityLevel").toInt(); } if (!settings.contains("fMinimizeChange")){ fMinimizeChange = false; settings.setValue("fMinimizeChange", fMinimizeChange); } else{ fMinimizeChange = settings.value("fMinimizeChange").toBool(); } ui->checkBoxMinimizeChange->setChecked(fMinimizeChange); // Start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // Hide those placeholder elements needed for CoinControl interaction ui->WarningLabel->hide(); // Explanatory text visible in QT-Creator ui->dummyHideWidget->hide(); // Dummy widget with elements to hide //temporary disable for maintenance if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { ui->pushButtonMintzBRIGHTCOIN->setEnabled(false); ui->pushButtonMintzBRIGHTCOIN->setToolTip(tr("zBRIGHTCOIN is currently disabled due to maintenance.")); ui->pushButtonSpendzBRIGHTCOIN->setEnabled(false); ui->pushButtonSpendzBRIGHTCOIN->setToolTip(tr("zBRIGHTCOIN is currently disabled due to maintenance.")); } } PrivacyDialog::~PrivacyDialog() { delete ui; } void PrivacyDialog::setModel(WalletModel* walletModel) { this->walletModel = walletModel; if (walletModel && walletModel->getOptionsModel()) { // Keep up to date with wallet setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); connect(walletModel, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); ui->securityLevel->setValue(nSecurityLevel); } } void PrivacyDialog::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void PrivacyDialog::on_addressBookButton_clicked() { if (!walletModel) return; AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(walletModel->getAddressTableModel()); if (dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->zBRIGHTCOINpayAmount->setFocus(); } } void PrivacyDialog::on_pushButtonMintzBRIGHTCOIN_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zBRIGHTCOIN is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Reset message text ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet was cancelled ui->TEMintStatus->setPlainText(tr("Error: Your wallet is locked. Please enter the wallet passphrase first.")); return; } } QString sAmount = ui->labelMintAmountValue->text(); CAmount nAmount = sAmount.toInt() * COIN; // Minting amount must be > 0 if(nAmount <= 0){ ui->TEMintStatus->setPlainText(tr("Message: Enter an amount > 0.")); return; } ui->TEMintStatus->setPlainText(tr("Minting ") + ui->labelMintAmountValue->text() + " zBRIGHTCOIN..."); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); CWalletTx wtx; vector<CZerocoinMint> vMints; string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl); // Return if something went wrong during minting if (strError != ""){ ui->TEMintStatus->setPlainText(QString::fromStdString(strError)); return; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; // Minting successfully finished. Show some stats for entertainment. QString strStatsHeader = tr("Successfully minted ") + ui->labelMintAmountValue->text() + tr(" zBRIGHTCOIN in ") + QString::number(fDuration) + tr(" sec. Used denominations:\n"); // Clear amount to avoid double spending when accidentally clicking twice ui->labelMintAmountValue->setText ("0"); QString strStats = ""; ui->TEMintStatus->setPlainText(strStatsHeader); for (CZerocoinMint mint : vMints) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); strStats = strStats + QString::number(mint.GetDenomination()) + " "; ui->TEMintStatus->setPlainText(strStatsHeader + strStats); ui->TEMintStatus->repaint (); } // Available balance isn't always updated, so force it. setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); coinControlUpdateLabels(); return; } void PrivacyDialog::on_pushButtonMintReset_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; ui->TEMintStatus->setPlainText(tr("Starting ResetMintZerocoin: rescanning complete blockchain, this will need up to 30 minutes depending on your hardware. \nPlease be patient...")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetMintResult = pwalletMain->ResetMintZerocoin(false); // do not do the extended search from GUI double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetMintResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); return; } void PrivacyDialog::on_pushButtonSpentReset_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; ui->TEMintStatus->setPlainText(tr("Starting ResetSpentZerocoin: ")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetSpentResult = pwalletMain->ResetSpentZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetSpentResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); return; } void PrivacyDialog::on_pushButtonSpendzBRIGHTCOIN_clicked() { if (!walletModel || !walletModel->getOptionsModel() || !pwalletMain) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zBRIGHTCOIN is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet was cancelled return; } // Wallet is unlocked now, sedn zBRIGHTCOIN sendzBRIGHTCOIN(); return; } // Wallet already unlocked or not encrypted at all, send zBRIGHTCOIN sendzBRIGHTCOIN(); } void PrivacyDialog::on_pushButtonZBrightCoinControl_clicked() { ZBrightCoinControlDialog* zBrightCoinControl = new ZBrightCoinControlDialog(this); zBrightCoinControl->setModel(walletModel); zBrightCoinControl->exec(); } void PrivacyDialog::setZBrightCoinControlLabels(int64_t nAmount, int nQuantity) { ui->labelzBrightCoinSelected_int->setText(QString::number(nAmount)); ui->labelQuantitySelected_int->setText(QString::number(nQuantity)); } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } void PrivacyDialog::sendzBRIGHTCOIN() { QSettings settings; // Handle 'Pay To' address options CBitcoinAddress address(ui->payTo->text().toStdString()); if(ui->payTo->text().isEmpty()){ QMessageBox::information(this, tr("Spend Zerocoin"), tr("No 'Pay To' address provided, creating local payment"), QMessageBox::Ok, QMessageBox::Ok); } else{ if (!address.IsValid()) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid BrightCoin Address"), QMessageBox::Ok, QMessageBox::Ok); ui->payTo->setFocus(); return; } } // Double is allowed now double dAmount = ui->zBRIGHTCOINpayAmount->text().toDouble(); CAmount nAmount = roundint64(dAmount* COIN); // Check amount validity if (!MoneyRange(nAmount) || nAmount <= 0.0) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Send Amount"), QMessageBox::Ok, QMessageBox::Ok); ui->zBRIGHTCOINpayAmount->setFocus(); return; } // Convert change to zBRIGHTCOIN bool fMintChange = ui->checkBoxMintChange->isChecked(); // Persist minimize change setting fMinimizeChange = ui->checkBoxMinimizeChange->isChecked(); settings.setValue("fMinimizeChange", fMinimizeChange); // Warn for additional fees if amount is not an integer and change as zBRIGHTCOIN is requested bool fWholeNumber = floor(dAmount) == dAmount; double dzFee = 0.0; if(!fWholeNumber) dzFee = 1.0 - (dAmount - floor(dAmount)); if(!fWholeNumber && fMintChange){ QString strFeeWarning = "You've entered an amount with fractional digits and want the change to be converted to Zerocoin.<br /><br /><b>"; strFeeWarning += QString::number(dzFee, 'f', 8) + " BRIGHTCOIN </b>will be added to the standard transaction fees!<br />"; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm additional Fees"), strFeeWarning, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled ui->zBRIGHTCOINpayAmount->setFocus(); return; } } // Persist Security Level for next start nSecurityLevel = ui->securityLevel->value(); settings.setValue("nSecurityLevel", nSecurityLevel); // Spend confirmation message box // Add address info if available QString strAddressLabel = ""; if(!ui->payTo->text().isEmpty() && !ui->addAsLabel->text().isEmpty()){ strAddressLabel = "<br />(" + ui->addAsLabel->text() + ") "; } // General info QString strQuestionString = tr("Are you sure you want to send?<br /><br />"); QString strAmount = "<b>" + QString::number(dAmount, 'f', 8) + " zBRIGHTCOIN</b>"; QString strAddress = tr(" to address ") + QString::fromStdString(address.ToString()) + strAddressLabel + " <br />"; if(ui->payTo->text().isEmpty()){ // No address provided => send to local address strAddress = tr(" to a newly generated (unused and therefore anonymous) local address <br />"); } QString strSecurityLevel = tr("with Security Level ") + ui->securityLevel->text() + " ?"; strQuestionString += strAmount + strAddress + strSecurityLevel; // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), strQuestionString, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled return; } int64_t nTime = GetTimeMillis(); ui->TEMintStatus->setPlainText(tr("Spending Zerocoin.\nComputationally expensive, might need several minutes depending on the selected Security Level and your hardware. \nPlease be patient...")); ui->TEMintStatus->repaint(); // use mints from zBrightCoin selector if applicable vector<CZerocoinMint> vMintsSelected; if (!ZBrightCoinControlDialog::listSelectedMints.empty()) { vMintsSelected = ZBrightCoinControlDialog::GetSelectedMints(); } // Spend zBRIGHTCOIN CWalletTx wtxNew; CZerocoinSpendReceipt receipt; bool fSuccess = false; if(ui->payTo->text().isEmpty()){ // Spend to newly generated local address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange); } else { // Spend to supplied destination address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address); } // Display errors during spend if (!fSuccess) { int nNeededSpends = receipt.GetNeededSpends(); // Number of spends we would need for this transaction const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zBRIGHTCOIN transaction if (nNeededSpends > nMaxSpends) { QString strStatusMessage = tr("Too much inputs (") + QString::number(nNeededSpends, 10) + tr(") needed. \nMaximum allowed: ") + QString::number(nMaxSpends, 10); strStatusMessage += tr("\nEither mint higher denominations (so fewer inputs are needed) or reduce the amount to spend."); QMessageBox::warning(this, tr("Spend Zerocoin"), strStatusMessage.toStdString().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(strStatusMessage.toStdString())); } else { QMessageBox::warning(this, tr("Spend Zerocoin"), receipt.GetStatusMessage().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(receipt.GetStatusMessage())); } ui->zBRIGHTCOINpayAmount->setFocus(); ui->TEMintStatus->repaint(); return; } // Clear zbrightcoin selector in case it was used ZBrightCoinControlDialog::listSelectedMints.clear(); // Some statistics for entertainment QString strStats = ""; CAmount nValueIn = 0; int nCount = 0; for (CZerocoinSpend spend : receipt.GetSpends()) { strStats += tr("zBrightCoin Spend #: ") + QString::number(nCount) + ", "; strStats += tr("denomination: ") + QString::number(spend.GetDenomination()) + ", "; strStats += tr("serial: ") + spend.GetSerial().ToString().c_str() + "\n"; strStats += tr("Spend is 1 of : ") + QString::number(spend.GetMintCount()) + " mints in the accumulator\n"; nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination()); } CAmount nValueOut = 0; for (const CTxOut& txout: wtxNew.vout) { strStats += tr("value out: ") + FormatMoney(txout.nValue).c_str() + " BrightCoin, "; nValueOut += txout.nValue; strStats += tr("address: "); CTxDestination dest; if(txout.scriptPubKey.IsZerocoinMint()) strStats += tr("zBrightCoin Mint"); else if(ExtractDestination(txout.scriptPubKey, dest)) strStats += tr(CBitcoinAddress(dest).ToString().c_str()); strStats += "\n"; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; strStats += tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"); strStats += tr("Sending successful, return code: ") + QString::number(receipt.GetStatus()) + "\n"; QString strReturn; strReturn += tr("txid: ") + wtxNew.GetHash().ToString().c_str() + "\n"; strReturn += tr("fee: ") + QString::fromStdString(FormatMoney(nValueIn-nValueOut)) + "\n"; strReturn += strStats; // Clear amount to avoid double spending when accidentally clicking twice ui->zBRIGHTCOINpayAmount->setText ("0"); ui->TEMintStatus->setPlainText(strReturn); ui->TEMintStatus->repaint(); } void PrivacyDialog::on_payTo_textChanged(const QString& address) { updateLabel(address); } // Coin Control: copy label "Quantity" to clipboard void PrivacyDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void PrivacyDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: button inputs -> show actual coin control dialog void PrivacyDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(walletModel); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: update labels void PrivacyDialog::coinControlUpdateLabels() { if (!walletModel || !walletModel->getOptionsModel() || !walletModel->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); if (CoinControlDialog::coinControl->HasSelected()) { // Actual coin control calculation CoinControlDialog::updateLabels(walletModel, this); } else { ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); } } bool PrivacyDialog::updateLabel(const QString& address) { if (!walletModel) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = walletModel->getAddressTableModel()->labelForAddress(address); if (!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; } void PrivacyDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; currentZerocoinBalance = zerocoinBalance; currentUnconfirmedZerocoinBalance = unconfirmedZerocoinBalance; currentImmatureZerocoinBalance = immatureZerocoinBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(true, false, true); std::map<libzerocoin::CoinDenomination, CAmount> mapDenomBalances; std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed; std::map<libzerocoin::CoinDenomination, int> mapImmature; for (const auto& denom : libzerocoin::zerocoinDenomList){ mapDenomBalances.insert(make_pair(denom, 0)); mapUnconfirmed.insert(make_pair(denom, 0)); mapImmature.insert(make_pair(denom, 0)); } for (auto& mint : listMints){ // All denominations mapDenomBalances.at(mint.GetDenomination())++; if (!mint.GetHeight() || chainActive.Height() - mint.GetHeight() <= Params().Zerocoin_MintRequiredConfirmations()) { // All unconfirmed denominations mapUnconfirmed.at(mint.GetDenomination())++; } else { // After a denomination is confirmed it might still be immature because < 3 of the same denomination were minted after it CBlockIndex *pindex = chainActive[mint.GetHeight() + 1]; int nMintsAdded = 0; while (pindex->nHeight < chainActive.Height() - 30) { // 30 just to make sure that its at least 2 checkpoints from the top block nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), mint.GetDenomination()); if (nMintsAdded >= Params().Zerocoin_RequiredAccumulation()) break; pindex = chainActive[pindex->nHeight + 1]; } if (nMintsAdded < Params().Zerocoin_RequiredAccumulation()){ // Immature denominations mapImmature.at(mint.GetDenomination())++; } } } int64_t nCoins = 0; int64_t nSumPerCoin = 0; int64_t nUnconfirmed = 0; int64_t nImmature = 0; QString strDenomStats, strUnconfirmed = ""; for (const auto& denom : libzerocoin::zerocoinDenomList) { nCoins = libzerocoin::ZerocoinDenominationToInt(denom); nSumPerCoin = nCoins * mapDenomBalances.at(denom); nUnconfirmed = mapUnconfirmed.at(denom); nImmature = mapImmature.at(denom); strUnconfirmed = ""; if (nUnconfirmed) { strUnconfirmed += QString::number(nUnconfirmed) + QString(" unconf. "); } if(nImmature) { strUnconfirmed += QString::number(nImmature) + QString(" immature "); } if(nImmature || nUnconfirmed) { strUnconfirmed = QString("( ") + strUnconfirmed + QString(") "); } strDenomStats = strUnconfirmed + QString::number(mapDenomBalances.at(denom)) + " x " + QString::number(nCoins) + " = <b>" + QString::number(nSumPerCoin) + " zBRIGHTCOIN </b>"; switch (nCoins) { case libzerocoin::CoinDenomination::ZQ_ONE: ui->labelzDenom1Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE: ui->labelzDenom2Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_TEN: ui->labelzDenom3Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIFTY: ui->labelzDenom4Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED: ui->labelzDenom5Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED: ui->labelzDenom6Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND: ui->labelzDenom7Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND: ui->labelzDenom8Amount->setText(strDenomStats); break; default: // Error Case: don't update display break; } } CAmount matureZerocoinBalance = zerocoinBalance - immatureZerocoinBalance; CAmount nLockedBalance = 0; if (walletModel) { nLockedBalance = walletModel->getLockedBalance(); } ui->labelzAvailableAmount->setText(QString::number(zerocoinBalance/COIN) + QString(" zBRIGHTCOIN ")); ui->labelzAvailableAmount_2->setText(QString::number(matureZerocoinBalance/COIN) + QString(" zBRIGHTCOIN ")); ui->labelzBRIGHTCOINAmountValue->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance - nLockedBalance, false, BitcoinUnits::separatorAlways)); } void PrivacyDialog::updateDisplayUnit() { if (walletModel && walletModel->getOptionsModel()) { nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit(); if (currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance, currentUnconfirmedZerocoinBalance, currentImmatureZerocoinBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); } } void PrivacyDialog::showOutOfSyncWarning(bool fShow) { ui->labelzBRIGHTCOINSyncStatus->setVisible(fShow); } void PrivacyDialog::keyPressEvent(QKeyEvent* event) { if (event->key() != Qt::Key_Escape) // press esc -> ignore { this->QDialog::keyPressEvent(event); } else { event->ignore(); } }
[ "admin@brightcoin.cc" ]
admin@brightcoin.cc
913c1f1457f5c78be61214878d65c5d729111bfe
b056b8adad52ca1ceb994a811be4da8498c8cdde
/tests/cpp/include/test_legacy_op.h
30bdf07b8b51f5cb4a7283769b42e44eb358bdf8
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-2-Clause-Views", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SidHard/mxnet
1a5cc8e958f5cb454ce5bf75f56b66ec8cb7a032
f95832d73cf3f1413ce1c77fbef0f295a7fbc57f
refs/heads/master
2022-11-09T00:22:36.043583
2017-12-21T05:10:40
2017-12-21T05:10:40
114,964,884
1
1
Apache-2.0
2022-10-22T09:57:52
2017-12-21T05:06:17
C++
UTF-8
C++
false
false
20,560
h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file test_op.h * \brief operator unit test utility functions * \author Chris Olivier * * These classes offer a framework for developing, testing and debugging operators * in C++. They work for both CPU and GPU modes, as well as offer a timing * infrastructure in order to test inidividual operator performance. * * Operator data can be validated against general logic, * stored scalar values (which can be generated by this code from an existing operator via * BasicOperatorData::dumpC(), as well as against each other (ie check that * GPU, CPU, MKL, and CUDNN operators produce the same output given the same input. * * test_util.h: General testing utility functionality * test_perf.h: Performance-related classes * test_op.h: Operator-specific testing classes */ #ifndef TEST_LEGACY_OP_H_ #define TEST_LEGACY_OP_H_ #include <list> #include <string> #include <algorithm> #include <map> #include <vector> #include <list> #include "../../../include/mxnet/operator.h" #include "./test_op.h" #include "./test_op_runner.h" namespace mxnet { namespace test { namespace op { /*! * \brief Manage test blobs and context, and universal logic * Create an operator from its "Prop" class and sets up the operator * and resources for both forward and backward passes * \tparam DType */ template <typename DType, typename AccReal> class LegacyOperatorExecutor : public OperatorDataInitializer<DType> , public OperatorExecutorTiming { public: typedef DType DataType; typedef AccReal AccRealType; /*! \brief Manage test blobs and context */ LegacyOperatorExecutor(const bool isGPU, const std::vector<TShape>& topShapes) #if !MXNET_USE_CUDA : isGPU_(false) #else : isGPU_(isGPU) #endif , initializeForward_(0) // unit testing may call inits in any order based , initializeBackward_(0) // upon its use-case (ie may not want to run forward pass first) , initializeCallback_(0) { opContext_.is_train = true; opContext_.run_ctx.stream = nullptr; CHECK(!topShapes.empty()); shape_input_vec_ = topShapes; } inline mxnet::Context getContext() { return isGPU_ ? mxnet::Context::GPU(0) : mxnet::Context{}; } /*! \brief Initialize forward blob data values */ virtual void resetForward() {} /*! \brief Initialize backward blob data values */ virtual void resetBackward() {} /*! \brief Initialize auxiliary and output blobs */ template<typename OperatorPropertyType> bool initForward(const OperatorPropertyType &opProp, std::vector<int> *in_type) { if (!initializeForward_++) { shape_input_vec_.resize(opProp.ListArguments().size()); op_.reset(opProp.CreateOperatorEx(getContext(), &shape_input_vec_, in_type)); if (op_) { const size_t output_count = opProp.ListOutputs().size(); const size_t aux_count = opProp.ListAuxiliaryStates().size(); // Figure out what sort of blobs we need to allocate std::vector<TShape> out_shape, aux_shape; out_shape.resize(output_count); aux_shape.resize(aux_count); opProp.InferShape(&shape_input_vec_, &out_shape, &aux_shape); std::vector<int> out_type(output_count, -1), aux_type(aux_count, -1); opProp.InferType(in_type, &out_type, &aux_type); // Allocate top blobs (input) for (size_t x = 0, n = shape_input_vec_.size(); x < n; ++x) { int type; if (x < in_type->size()) { type = (*in_type)[x]; } else { type = x ? mshadow::DataType<AccReal>::kFlag : mshadow::DataType<DType>::kFlag; } allocateBlob(&c_.blob_input_vec_, shape_input_vec_[x], false, type); } // Allocate aux blobs (scratch, hidden, etc.) for (size_t x = 0, n = aux_shape.size(); x < n; ++x) { CHECK(x < aux_type.size()); allocateBlob(&c_.blob_aux_states_, aux_shape[x], false, aux_type[x]); } // Allocate bottom blobs (output) for (size_t x = 0, n = out_shape.size(); x < n; ++x) { CHECK(x < out_type.size()); allocateBlob(&c_.blob_output_vec_, out_shape[x], false, out_type[x]); } // Get the resource of temporal space std::vector<TShape> inputShapes; for (size_t x = 0, n = shape_input_vec_.size(); x < n; ++x) { inputShapes.push_back(shape_input_vec_[x]); } allocateResources(opProp.ForwardResource(inputShapes)); resetForward(); return true; } return false; } else { return true; } } /*! \brief Initialize auxiliary and output blobs */ template<typename OperatorPropertyType> bool initBackward(const OperatorPropertyType &opProp, std::vector<int> *in_type) { initForward(opProp, in_type); if (!initializeBackward_++) { for (size_t x = 0, n = static_cast<size_t>(opProp.NumVisibleOutputs()); x < n; ++x) { CHECK_LT(x, c_.blob_output_vec_.size()); allocateBlob(&c_.blob_out_grad_, c_.blob_output_vec_[x].shape_, false, c_.blob_output_vec_[x].type_flag_); } for (size_t x = 0, n = c_.blob_input_vec_.size(); x < n; ++x) { allocateBlob(&c_.blob_in_grad_, c_.blob_input_vec_[x].shape_, false, c_.blob_input_vec_[x].type_flag_); } // Get the resource of temporal space std::vector<TShape> ishapes; allocateResources(opProp.BackwardResource(ishapes)); resetBackward(); return false; } else { return true; } } /*! \brief Run operator forward */ void forward(const size_t count = 1) { const std::vector<OpReqType> req(c_.blob_output_vec_.size(), kWriteTo); // Possibly move data to/from CPU and GPU (outside of timing scope) MXNET_CUDA_ONLY(std::unique_ptr<GPUOpData> gpuData(isGPU_ ? new GPUOpData(c_, &opContext_) : nullptr)); perf::TimingItem timeF(&OperatorExecutorTiming::GetTiming(), Forward, "Forward", count); if (!isGPU_) { VTuneResume profile; // VTune sample only this scope for (size_t x = 0; x < count; ++x) { op()->Forward(opContext_, c_.blob_input_vec_, req, c_.blob_output_vec_, c_.blob_aux_states_); } } else { for (size_t x = 0; x < count; ++x) { MXNET_CUDA_ONLY(op()->Forward(opContext_, gpuData->blob_input_vec_, req, gpuData->blob_output_vec_, gpuData->blob_aux_states_)); } } } /*! \brief Run operator backwards */ void backward(const size_t count = 1) { const std::vector<OpReqType> req(c_.blob_in_grad_.size(), kWriteTo); // Possibly move data to/from CPU and GPU (outside of timing scope) MXNET_CUDA_ONLY(std::unique_ptr<GPUOpData> gpuData(isGPU_ ? new GPUOpData(c_, &opContext_) : nullptr)); perf::TimingItem timeB(&OperatorExecutorTiming::GetTiming(), Backward, "Backward", count); if (!isGPU_) { VTuneResume profile; // VTune sample only this scope for (size_t x = 0; x < count; ++x) { op()->Backward(opContext_, c_.blob_out_grad_, c_.blob_input_vec_, c_.blob_output_vec_, req, c_.blob_in_grad_, c_.blob_aux_states_); } } else { for (size_t x = 0; x < count; ++x) { MXNET_CUDA_ONLY(op()->Backward(opContext_, gpuData->blob_out_grad_, gpuData->blob_input_vec_, gpuData->blob_output_vec_, req, gpuData->blob_in_grad_, gpuData->blob_aux_states_)); } } } /*! * \brief Test if operator has a backward pass * \return true if this operator has a backward pass */ MSHADOW_CINLINE bool HasBackward() const { return true; } /*! \brief Getter functions for the operator */ inline Operator *op() { return op_.get(); } inline const Operator *op() const { return op_.get(); } enum BlobVectorType { kInput, kOutput, kAux, kInGrad, kOutGrad, kBlobVectorTypeCount }; #define CASE_STR(__v$) case (__v$): return #__v$ /*! \brief Convert BlobVectorType enum into a string */ static inline const char *bvt2String(const BlobVectorType bvt) { switch (bvt) { CASE_STR(kInput); CASE_STR(kOutput); CASE_STR(kAux); CASE_STR(kInGrad); CASE_STR(kOutGrad); default: CHECK(false); return ""; } } #undef CASE_STR /*! \brief Return a particular blob in a test data set */ inline const std::vector<TBlob>& getBlobVect(const BlobVectorType bvt) const { switch (bvt) { case kInput: return c_.blob_input_vec_; case kOutput: return c_.blob_output_vec_; case kAux: return c_.blob_aux_states_; case kInGrad: return c_.blob_in_grad_; case kOutGrad: return c_.blob_out_grad_; default: CHECK(false); return c_.blob_input_vec_; } } /*! \brief Dump an operator's data set into compilable C++ data code for runtime validation * When writing an operator test, you can generate a "known good operator data state" in C++ * code with this function, and then use load() to load the blob states into this * class (BasicOperatorData). * After that, you can compare with the "actual" operator state (BasicOperatorData) of * the operator that you are testing. */ template<typename Stream> inline void dumpC(Stream *_os, const std::string& label) { Stream& os = *_os; os << "static const std::vector< std::vector< std::vector<float> > > ___" << label << "_data_shape_"; const TShape& shape = shape_input_vec_[0]; for (size_t i = 0, n = shape.ndim(); i < n; ++i) { os << shape[i] << "_"; } os << "__ =" << std::endl << "{" << std::endl; for (size_t x = 0; x < kBlobVectorTypeCount; ++x) { os << " { /* " << bvt2String(BlobVectorType(x)) << " */" << std::endl; const std::vector<TBlob>& blobVect = getBlobVect(BlobVectorType(x)); for (size_t i = 0, n = blobVect.size(); i < n; ++i) { os << " { "; test::dump<DType>(&os, blobVect[i]); os << " }"; if (i < n - 1) { os << ","; } os << std::endl; } os << " }"; if (x < kBlobVectorTypeCount - 1) { os << ","; } os << std::endl; } os << "};" << std::endl; } static inline void copy(const TBlob& blob, const DType array[], const size_t start, const size_t end) { const size_t blobSize = blob.Size(); DType *p = blob.dptr<DType>(); for (size_t i = 0, n = end - start; i < n; ++i) { CHECK_LT(i, blobSize); p[i] = array[i + start]; } } /*! \brief Runtime load of the C++ data code generated by dumpC() */ void load(const std::vector<std::vector<std::vector<DType>>>& cData) { for (size_t i = 0, ni = cData.size(); i < ni; ++i) { for (size_t j = 0, nj = cData[i].size(); j < nj; ++j) { const TBlob& blob = getBlobVect(BlobVectorType(i))[j]; const size_t sourceDataSize = cData[i][j].size(); CHECK_EQ(sourceDataSize, blob.Size()); const DType *sourceData = &cData[i][j][0]; copy(blob, sourceData, 0, sourceDataSize); } } } /*! \brief Runtime load of the C++ data code generated by dumpC() */ void load(const std::vector<std::vector<std::vector<DType>>>& cData, const BlobVectorType type) { CHECK_LT(type, cData.size()); for (size_t j = 0, nj = cData[type].size(); j < nj; ++j) { const TBlob& blob = getBlobVect(type)[j]; const size_t sourceDataSize = cData[type][j].size(); CHECK_EQ(sourceDataSize, blob.Size()); const DType *sourceData = &cData[type][j][0]; copy(blob, sourceData, 0, sourceDataSize); } } /*! \brief Runtime load of the C++ data code generated by dumpC() */ void load(const std::vector<std::vector<std::vector<DType>>>& cData, const BlobVectorType type, const int idx) { CHECK_LT(type, cData.size()); CHECK_LT(idx, cData[type].size()); const TBlob& blob = getBlobVect(type)[idx]; const size_t sourceDataSize = cData[type][idx].size(); CHECK_EQ(sourceDataSize, blob.Size()); const DType *sourceData = &cData[type][idx][0]; copy(blob, sourceData, 0, sourceDataSize); } void FillRandom() { for (size_t j = 0, jn = this->c_.all_blob_vects_.size(); j < jn; ++j) { std::vector<TBlob> *data_vect = this->c_.all_blob_vects_[j]; if (data_vect) { for (size_t i = 0, n = data_vect->size(); i < n; ++i) { OperatorDataInitializer<DType>::FillRandom((*data_vect)[i]); } } } } std::vector<TBlob>& inputs() { return c_.blob_input_vec_; } const std::vector<TBlob>& inputs() const { return c_.blob_input_vec_; } std::vector<TBlob>& outputs() { return c_.blob_output_vec_; } const std::vector<TBlob>& outputs() const { return c_.blob_output_vec_; } std::vector<TBlob>& bwd_inputs() { return c_.blob_out_grad_; } std::vector<TBlob>& bwd_outputs() { return c_.blob_in_grad_; } /*! \brief Input and output blobs */ OpContext opContext_; std::vector<TShape> shape_input_vec_; struct OpData { std::vector<TBlob> blob_input_vec_; std::vector<TBlob> blob_output_vec_; std::vector<TBlob> blob_aux_states_; std::vector<TBlob> blob_in_grad_; std::vector<TBlob> blob_out_grad_; // Remaining err (loss) pushing back upstream std::vector<std::vector<TBlob> *> all_blob_vects_; inline OpData() { all_blob_vects_.push_back(&blob_input_vec_); all_blob_vects_.push_back(&blob_output_vec_); all_blob_vects_.push_back(&blob_aux_states_); all_blob_vects_.push_back(&blob_in_grad_); all_blob_vects_.push_back(&blob_out_grad_); // Remaining err (loss) pushing back upstream } virtual ~OpData() {} }; #if MXNET_USE_CUDA class GPUOpData : public OpData { GPUOpData() = delete; GPUOpData(const GPUOpData& o) = delete; public: inline GPUOpData(const OpData& cpuData, OpContext *opContext) : cpuData_(cpuData) , allocGPUStream_(opContext) { // Copy CPU->GPU CHECK_EQ(gpuBlobs_.size(), 0U); CHECK_EQ(cpuData_.all_blob_vects_.size(), this->all_blob_vects_.size()); for (size_t bvt = 0, nbvt = cpuData_.all_blob_vects_.size(); bvt < nbvt; ++bvt) { std::vector<TBlob>& bv_src = *cpuData_.all_blob_vects_[bvt]; std::vector<TBlob>& bvt_dest = *this->all_blob_vects_[bvt]; for (size_t i = 0, n = bv_src.size(); i < n; ++i) { const TBlob& srcBlob = bv_src[i]; TBlob *destBlob = allocateBlob(&gpuBlobs_, &bvt_dest, srcBlob.shape_, true, srcBlob.type_flag_); Context cpu_ctx, gpu_ctx; cpu_ctx.dev_type = Context::kCPU; gpu_ctx.dev_type = Context::kGPU; cpu_ctx.dev_id = gpu_ctx.dev_id = 0; mxnet::ndarray::Copy<cpu, gpu>(srcBlob, destBlob, cpu_ctx, gpu_ctx, allocGPUStream_.opContext_.run_ctx); } } cudaDeviceSynchronize(); } inline ~GPUOpData() { // Copy GPU->CPU cudaDeviceSynchronize(); for (size_t bvt = 0, nbvt = this->all_blob_vects_.size(); bvt < nbvt; ++bvt) { std::vector<TBlob>& bv_src = *this->all_blob_vects_[bvt]; std::vector<TBlob>& bvt_dest = *cpuData_.all_blob_vects_[bvt]; for (size_t i = 0, n = bv_src.size(); i < n; ++i) { const TBlob& srcBlob = bv_src[i]; TBlob *destBlob = &bvt_dest[i]; Context cpu_ctx, gpu_ctx; cpu_ctx.dev_type = Context::kCPU; gpu_ctx.dev_type = Context::kGPU; cpu_ctx.dev_id = gpu_ctx.dev_id = 0; mxnet::ndarray::Copy<gpu, cpu>(srcBlob, destBlob, gpu_ctx, cpu_ctx, allocGPUStream_.opContext_.run_ctx); } } gpuBlobs_.clear(); // Force deallocation of the GPU blob data cudaDeviceSynchronize(); } private: /*! \brief Reference to the src/dest CPU data */ const OpData& cpuData_; /*! \brief The GPU-allocated blobs */ std::list<std::unique_ptr<test::StandaloneBlob>> gpuBlobs_; /*! \brief Scoped GPU stream */ GPUStreamScope allocGPUStream_; }; #endif // MXNET_USE_CUDA protected: OpData c_; /*! \brief Allocate the operator's resource requests */ void allocateResources(const std::vector<ResourceRequest>& reqs) { std::map<Context, Resource> cached_temp; Context ctx; ctx.dev_type = isGPU_ ? Context::kGPU : Context::kCPU; ctx.dev_id = 0; for (const ResourceRequest& req : reqs) { if (req.type == ResourceRequest::kTempSpace) { if (cached_temp.count(ctx) != 0) { opContext_.requested.push_back(cached_temp.at(ctx)); } else { Resource r = ResourceManager::Get()->Request(ctx, req); opContext_.requested.push_back(r); cached_temp[ctx] = r; } } else if (req.type == ResourceRequest::kRandom) { opContext_.requested.push_back(ResourceManager::Get()->Request(ctx, req)); } else { LOG(FATAL) << "resource type not yet supported"; } } } /*! \brief Locally allocate a managed TBlob and insert into the supplied vector */ static TBlob *allocateBlob(std::list<std::unique_ptr<test::StandaloneBlob>> *standalone_blobs, std::vector<TBlob> *dest, const TShape& shape, const bool isGPU, const int dtype) { test::StandaloneBlob *blob = new test::StandaloneBlob(shape, isGPU, dtype); CHECK_NE(blob, static_cast<TBlob *>(nullptr)); standalone_blobs->push_back(std::unique_ptr<test::StandaloneBlob>(blob)); (*dest).push_back(*blob); return blob; } /*! \brief Locally allocate a managed TBlob and insert into the supplied vector */ inline TBlob *allocateBlob(std::vector<TBlob> *dest, const TShape& shape, const bool isGPU, const int dtype) { return allocateBlob(&standalone_blobs_, dest, shape, isGPU, dtype); } /*! \brief Performance timing categories */ enum TimingId { Forward, Backward }; /*! \brief The operator */ std::unique_ptr<Operator> op_; /*! \brief Is this for a GPU? */ const bool isGPU_; /*! \brief Assure that the Forward initialized only once */ std::atomic<int> initializeForward_; /*! \brief Assure that the Forward initialized only once */ std::atomic<int> initializeBackward_; /*! \brief Assure that the callback is initialized only once */ std::atomic<int> initializeCallback_; /*! \brief scoped lifecycle management of allocated blobs */ std::list<std::unique_ptr<test::StandaloneBlob>> standalone_blobs_; }; template<typename OperatorProp, typename DType, typename AccReal> using LegacyOpRunner = mxnet::test::OperatorRunner<OperatorProp, LegacyOperatorExecutor<DType, AccReal>>; } // namespace op } // namespace test } // namespace mxnet #endif // TEST_LEGACY_OP_H_
[ "wangxb-1986@163.com" ]
wangxb-1986@163.com
4a833c031131726463a1a5a5d4c5856d3def3ddd
95025210b9131d8bbddfe2f4b85e0cf683596c1f
/Src/GeneralInput/DeckBMOptionDlg.cpp
650be7aeda809367227c11f01e7cd92225f31cd8
[]
no_license
SamuelBacaner1112/APlate
ece78b86f4cda173c7e1c3d3776d3aaf0ef1d341
0d89bd5beadc811d9d33c75f3110903f8b4f256e
refs/heads/master
2023-01-24T07:50:59.851986
2020-12-09T00:19:05
2020-12-09T00:19:05
319,794,441
0
2
null
null
null
null
UHC
C++
false
false
120,856
cpp
// DeckBMOptionDlg.cpp : implementation file // #include "stdafx.h" #include "GeneralInput.h" #include "../APlateCalc/APlateCalc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDeckBMOptionDlg dialog CDeckBMOptionDlg::CDeckBMOptionDlg(CWnd* pParent /*=NULL*/) : CGeneralBaseDlg(CDeckBMOptionDlg::IDD, pParent) { //{{AFX_DATA_INIT(CDeckBMOptionDlg) //}}AFX_DATA_INIT AfxInitRichEdit(); } void CDeckBMOptionDlg::DoDataExchange(CDataExchange* pDX) { CGeneralBaseDlg::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDeckBMOptionDlg) DDX_Control(pDX, IDC_CHECK_ELECWIREHOLE, m_ElecWireHole); DDX_Control(pDX, IDC_CHECK_TIMBER, m_Timber); DDX_Control(pDX, IDC_CHECK_WING_WALL, m_WingWall); // DDX_Control(pDX, IDC_BUTTON_ALL_CANCEL, m_AllCancel); // DDX_Control(pDX, IDC_BUTTON_ALL_CHECK, m_AllCheck); DDX_Control(pDX, IDC_CHECK_DRAIN_BRIDGESURFACE, m_DrainBridgeSurface); DDX_Control(pDX, IDC_CHECK_SHADE, m_Shade); DDX_Control(pDX, IDC_CHECK_PAVE, m_Pave); DDX_Control(pDX, IDC_CHECK_NOTCH, m_Notch); DDX_Control(pDX, IDC_CHECK_WATER_DRAW, m_WaterDraw); DDX_Control(pDX, IDC_CHECK_TACK_COATING, m_TackCoating); DDX_Control(pDX, IDC_CHECK_STYROFOAM, m_Styrofoam); DDX_Control(pDX, IDC_CHECK_STEEL_QUANTITY, m_SteelQuantity); DDX_Control(pDX, IDC_CHECK_SPACER, m_Spacer); DDX_Control(pDX, IDC_CHECK_SOUND_PROOF, m_SoundProof); DDX_Control(pDX, IDC_CHECK_SHRINKAGE_CONCRETE, m_ShrinkageConcrete); DDX_Control(pDX, IDC_CHECK_REBAR_MANUFACTURE, m_RebarManufacture); DDX_Control(pDX, IDC_CHECK_PARAPET, m_Parapet); DDX_Control(pDX, IDC_CHECK_PAINT, m_Paint); DDX_Control(pDX, IDC_CHECK_MOLD, m_Mold); DDX_Control(pDX, IDC_CHECK_GUARD_FENCE, m_GuardFence); DDX_Control(pDX, IDC_CHECK_EXPLAIN_PLATE, m_ExplainPlate); DDX_Control(pDX, IDC_CHECK_EXPANSIONJOINT_COVER, m_ExpansionJointCover); DDX_Control(pDX, IDC_CHECK_EXPANSIONJOINT, m_ExpansionJoint); DDX_Control(pDX, IDC_CHECK_ESTABLISH_TBM, m_EstablishTBM); DDX_Control(pDX, IDC_CHECK_DROPPING_PREVENT, m_DroppingPreVent); DDX_Control(pDX, IDC_CHECK_DRAIN_ESTABLISH, m_DrainEstablish); DDX_Control(pDX, IDC_CHECK_CONCRETE_PLACING, m_ConcretePlacing); DDX_Control(pDX, IDC_CHECK_CONCRETE_BUY, m_ConcreteBuy); DDX_Control(pDX, IDC_CHECK_BRIDGE_NAMEPLATE, m_BridgeNamePlate); DDX_Control(pDX, IDC_CHECK_BRIDGE_NAME, m_BridgeName); DDX_Control(pDX, IDC_RICHEDIT_CONTENTS, m_OptContents); //}}AFX_DATA_MAP DDX_GridControl(pDX, IDC_GRID, m_Grid); // 반드시 IDC_GRID 로 정의 DDX_Control(pDX, IDC_BUTTON_OPTION_SAVE, m_btnOptSave); DDX_Control(pDX, IDC_BUTTON_OPTION_LOAD, m_btnOptLoad); DDX_Control(pDX, IDC_BUTTON_ALL_CHECK, m_AllCheck); DDX_Control(pDX, IDC_BUTTON_ALL_CANCEL, m_AllCancel); } BEGIN_MESSAGE_MAP(CDeckBMOptionDlg, CGeneralBaseDlg) //{{AFX_MSG_MAP(CDeckBMOptionDlg) ON_BN_CLICKED(IDC_CHECK_CONCRETE_BUY, OnCheckConcreteBuy) ON_BN_CLICKED(IDC_CHECK_CONCRETE_PLACING, OnCheckConcretePlacing) ON_BN_CLICKED(IDC_CHECK_MOLD, OnCheckMold) ON_BN_CLICKED(IDC_CHECK_SPACER, OnCheckSpacer) ON_BN_CLICKED(IDC_CHECK_REBAR_MANUFACTURE, OnCheckRebarManufacture) ON_BN_CLICKED(IDC_CHECK_PAVE, OnCheckPave) ON_BN_CLICKED(IDC_CHECK_TACK_COATING, OnCheckTackCoating) ON_BN_CLICKED(IDC_CHECK_DRAIN_BRIDGESURFACE, OnCheckDrainBridgesurface) ON_BN_CLICKED(IDC_CHECK_BRIDGE_NAME, OnCheckBridgeName) ON_BN_CLICKED(IDC_CHECK_BRIDGE_NAMEPLATE, OnCheckBridgeNameplate) ON_BN_CLICKED(IDC_CHECK_EXPLAIN_PLATE, OnCheckExplainPlate) ON_BN_CLICKED(IDC_CHECK_ESTABLISH_TBM, OnCheckEstablishTbm) ON_BN_CLICKED(IDC_CHECK_STYROFOAM, OnCheckStyrofoam) ON_BN_CLICKED(IDC_CHECK_EXPANSIONJOINT, OnCheckExpansionjoint) ON_BN_CLICKED(IDC_CHECK_EXPANSIONJOINT_COVER, OnCheckExpansionjointCover) ON_BN_CLICKED(IDC_CHECK_SHRINKAGE_CONCRETE, OnCheckShrinkageConcrete) ON_BN_CLICKED(IDC_CHECK_WATER_DRAW, OnCheckWaterDraw) ON_BN_CLICKED(IDC_CHECK_NOTCH, OnCheckNotch) ON_BN_CLICKED(IDC_CHECK_GUARD_FENCE, OnCheckGuardFence) ON_BN_CLICKED(IDC_CHECK_SOUND_PROOF, OnCheckSoundProof) ON_BN_CLICKED(IDC_CHECK_PARAPET, OnCheckParapet) ON_BN_CLICKED(IDC_CHECK_SHADE, OnCheckShade) ON_BN_CLICKED(IDC_CHECK_DROPPING_PREVENT, OnCheckDroppingPrevent) ON_BN_CLICKED(IDC_CHECK_STEEL_QUANTITY, OnCheckSteelQuantity) ON_BN_CLICKED(IDC_CHECK_PAINT, OnCheckPaint) ON_BN_CLICKED(IDC_CHECK_DRAIN_ESTABLISH, OnCheckDrainEstablish) ON_BN_CLICKED(IDC_BUTTON_ALL_CHECK, OnButtonAllCheck) ON_BN_CLICKED(IDC_BUTTON_ALL_CANCEL, OnButtonAllCancel) ON_BN_CLICKED(IDC_CHECK_WING_WALL, OnCheckWingWall) ON_BN_CLICKED(IDC_CHECK_TIMBER, OnCheckTimber) ON_BN_CLICKED(IDC_CHECK_ELECWIREHOLE, OnCheckElecWireHole) ON_BN_CLICKED(IDC_BUTTON_OPTION_SAVE, OnButtonOptionSave) ON_BN_CLICKED(IDC_BUTTON_OPTION_LOAD, OnButtonOptionLoad) //}}AFX_MSG_MAP ON_MESSAGE(WM_USER_BUTTON_PUSH, OnReceive) ON_NOTIFY(GVN_CELL_CHANGED_DATA, IDC_GRID, OnCellChangedData) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDeckBMOptionDlg message handlers void CDeckBMOptionDlg::OnPreInitDialog() { CSteelUWeight *pUWeight = m_pStd->m_pDataManage->GetSteelUWeight(); m_nSelectedOpt = 0; m_nCols = 2; m_nRows = 1; m_Grid.SetColumnCount(m_nCols); m_Grid.SetRowCount(m_nRows); m_Grid.SetFiexedRows(1); m_Grid.SetFixedCols(1); m_Grid.SetTextMatrix(0, 0, _T("구 분")); m_Grid.SetTextMatrix(0, 1, _T("적용 여부")); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 140); m_OptContents.SetReadOnly(); m_OptContents.SetBackgroundColor(FALSE, RGB(230, 255, 255)); CString sText = _T(""); sText.Format("%s포장", pUWeight->GetTypePave()); m_Pave.SetWindowText(sText); SetResize(IDC_RICHEDIT_CONTENTS, SZ_TOP_LEFT, SZ_BOTTOM_CENTER); SetResize(IDC_STATIC_OPT_DETAIL, SZ_MIDDLE_CENTER, SZ_MIDDLE_RIGHT); SetResize(IDC_GRID, SZ_MIDDLE_CENTER, SZ_BOTTOM_RIGHT); SetResize(IDC_CHECK_CONCRETE_BUY, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_CONCRETE_PLACING, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_MOLD, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_SPACER, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_REBAR_MANUFACTURE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_PAVE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_TACK_COATING, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_DRAIN_BRIDGESURFACE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_BRIDGE_NAME, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_BRIDGE_NAMEPLATE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_EXPLAIN_PLATE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_ESTABLISH_TBM, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_STYROFOAM, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_EXPANSIONJOINT, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_EXPANSIONJOINT_COVER, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_SHRINKAGE_CONCRETE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_WATER_DRAW, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_NOTCH, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_GUARD_FENCE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_SOUND_PROOF, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_PARAPET, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_SHADE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_DROPPING_PREVENT, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_STEEL_QUANTITY, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_PAINT, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_DRAIN_ESTABLISH, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_WING_WALL, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_TIMBER, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_CHECK_ELECWIREHOLE, SZ_TOP_CENTER, SZ_TOP_CENTER); SetResize(IDC_BUTTON_ALL_CHECK, SZ_BOTTOM_RIGHT, SZ_BOTTOM_RIGHT); SetResize(IDC_BUTTON_ALL_CANCEL, SZ_BOTTOM_RIGHT, SZ_BOTTOM_RIGHT); SetResize(IDC_BUTTON_OPTION_LOAD, SZ_BOTTOM_LEFT, SZ_BOTTOM_LEFT); SetResize(IDC_BUTTON_OPTION_SAVE, SZ_BOTTOM_LEFT, SZ_BOTTOM_LEFT); } void CDeckBMOptionDlg::SetGridTitle() { long nRow = 0; long nCol = 0; for(nRow=0; nRow<m_Grid.GetRowCount(); nRow++) { for(nCol=0; nCol<m_Grid.GetColumnCount(); nCol++) { m_Grid.SetItemState(nRow,nCol,0); m_Grid.SetCellType(nRow,nCol,CT_EDIT); m_Grid.SetTextBkColor(RGBEDITABLE); if(nRow != 0 && nCol != 0) m_Grid.SetItemBkColour(nRow, nCol, RGBEDITABLE); } } m_Grid.SetColumnCount(m_nCols); m_Grid.SetRowCount(m_nRows); m_Grid.SetRowHeightAll(20); m_Grid.SetFiexedRows(1); m_Grid.SetFixedCols(1); m_Grid.SetTextMatrix(0, 0, _T("구 분")); m_Grid.SetTextMatrix(0, 1, _T("적용 여부")); for(nRow=1; nRow<m_nRows; nRow++) { for(nCol=1; nCol<m_nCols; nCol++) m_Grid.SetItemBkColour(nRow, nCol, RGB(230, 255, 255)); } } void CDeckBMOptionDlg::SetDataInit() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CStringArray szArray; GetBMOptionContents(szArray); m_OptContents.SetSel(0, -1); m_OptContents.Clear(); for(long n = 0; n < szArray.GetSize(); n++) m_OptContents.ReplaceSel(szArray.GetAt(n)); m_ConcreteBuy.SetCheck(pBMOpt->m_bConcreteBuy); m_ConcreteBuy.Invalidate(); m_ConcretePlacing.SetCheck(pBMOpt->m_bConcretePlacing); m_Mold.SetCheck(pBMOpt->m_bMold); m_Spacer.SetCheck(pBMOpt->m_bSpacer); m_RebarManufacture.SetCheck(pBMOpt->m_structRebarManufacture.m_bApply); m_Pave.SetCheck(pBMOpt->m_structPave.m_bApply); m_TackCoating.SetCheck(pBMOpt->m_structTackCoating.m_bApply); m_DrainBridgeSurface.SetCheck(pBMOpt->m_bDrainBridgeSurface); m_BridgeName.SetCheck(pBMOpt->m_structBridgeName.m_bApply); m_BridgeNamePlate.SetCheck(pBMOpt->m_structBridgeNamePlate.m_bApply); m_ExplainPlate.SetCheck(pBMOpt->m_structExplainPlate.m_bApply); m_EstablishTBM.SetCheck(pBMOpt->m_structEstablishTBM.m_bApply); m_Styrofoam.SetCheck(pBMOpt->m_structStyrofoam.m_bApply); m_ExpansionJoint.SetCheck(pBMOpt->m_structExpansionJoint.m_bApply); m_ExpansionJointCover.SetCheck(pBMOpt->m_structExpansionJointCover.m_bApply); m_ShrinkageConcrete.SetCheck(pBMOpt->m_structShrinkageConcrete.m_bApply); m_WaterDraw.SetCheck(pBMOpt->m_bWaterDraw); m_Notch.SetCheck(pBMOpt->m_structNotch.m_bApply); m_GuardFence.SetCheck(pBMOpt->m_structGuardFence.m_bApply); m_SoundProof.SetCheck(pBMOpt->m_structSoundProof.m_bApply); m_Parapet.SetCheck(pBMOpt->m_structParapet.m_bApply); m_Shade.SetCheck(pBMOpt->m_bShade); m_DroppingPreVent.SetCheck(pBMOpt->m_structDroppingPrevent.m_bApply); m_SteelQuantity.SetCheck(pBMOpt->m_bSteelQuantity); m_Paint.SetCheck(pBMOpt->m_bPaint); m_DrainEstablish.SetCheck(pBMOpt->m_bDrainEstablish); m_WingWall.SetCheck(pBMOpt->m_structWingWall.m_bApply); m_Timber.SetCheck(pBMOpt->m_structTimber.m_bApply); m_ElecWireHole.SetCheck(pBMOpt->m_structElecWireHole.m_bApply); UpdateData(FALSE); } void CDeckBMOptionDlg::SetDataSave() { } BOOL CDeckBMOptionDlg::IsLeft(CString szApply) { if(szApply == _T("좌측적용")) return TRUE; else if(szApply == _T("우측적용")) return FALSE; else return FALSE; return FALSE; } BOOL CDeckBMOptionDlg::IsApply(CString szApply) { if(szApply == _T("적용") || szApply == _T("좌측적용") || szApply == _T("우측적용") || szApply == _T("시점적용") || szApply == _T("종점적용") || szApply == _T("편측적용") || szApply == _T("단위 m당 수량")) return TRUE; if(szApply == _T("미적용") || szApply == _T("좌측미적용") || szApply == _T("우측미적용") || szApply == _T("시점미적용") || szApply == _T("종점미적용") || szApply == _T("양측적용") || szApply == _T("지점별 수량")) return FALSE; ASSERT(FALSE); return FALSE; } CString CDeckBMOptionDlg::IsApply(BOOL bApply) { CString szApply = _T(""); if(bApply) szApply = _T("적용"); else szApply = _T("미적용"); return szApply; } CString CDeckBMOptionDlg::IsApplyStt(BOOL bApply) { CString szApply = _T(""); if(bApply) szApply = _T("시점적용"); else szApply = _T("시점미적용"); return szApply; } CString CDeckBMOptionDlg::IsApplyEnd(BOOL bApply) { CString szApply = _T(""); if(bApply) szApply = _T("종점적용"); else szApply = _T("종점미적용"); return szApply; } CString CDeckBMOptionDlg::IsApplyLeft(BOOL bApply) { CString szApply = _T(""); if(bApply) szApply = _T("좌측적용"); else szApply = _T("좌측미적용"); return szApply; } CString CDeckBMOptionDlg::IsApplyRight(BOOL bApply) { CString szApply = _T(""); if(bApply) szApply = _T("우측적용"); else szApply = _T("우측미적용"); return szApply; } void CDeckBMOptionDlg::OnGridRedraw() { switch(m_nSelectedOpt) { case BMOPT_CONCRETE_BYE : OnCheckConcreteBuy(); break; case BMOPT_CONCRETE_PLACING : OnCheckConcretePlacing(); break; case BMOPT_MOLD : OnCheckMold(); break; case BMOPT_SPACER : OnCheckSpacer(); break; case BMOPT_REBAR_MANUFACTURE : OnCheckRebarManufacture(); break; case BMOPT_PAVE : OnCheckPave(); break; case BMOPT_TACKCOATING : OnCheckTackCoating(); break; case BMOPT_DRAINBRIDGESURFACE : OnCheckDrainBridgesurface(); break; case BMOPT_BRIDGENAME : OnCheckBridgeName(); break; case BMOPT_BRIDGENAME_PLATE : OnCheckBridgeNameplate(); break; case BMOPT_EXPLAIN_PLATE : OnCheckExplainPlate(); break; case BMOPT_ESTABLISH_TBM : OnCheckEstablishTbm(); break; case BMOPT_STYROFOAM : OnCheckStyrofoam(); break; case BMOPT_EXPANSIONJOINT : OnCheckExpansionjoint(); break; case BMOPT_EXPANSIONJOINT_COVER : OnCheckExpansionjointCover(); break; case BMOPT_SHRINKAGE_CONCRETE : OnCheckShrinkageConcrete(); break; case BMOPT_WATER_DRAW : OnCheckWaterDraw(); break; case BMOPT_NOTCH : OnCheckNotch(); break; case BMOPT_GUARD_FENCE : OnCheckGuardFence(); break; case BMOPT_SOUND_PROOF : OnCheckSoundProof(); break; case BMOPT_PARAPET : OnCheckParapet(); break; case BMOPT_SHADE : OnCheckShade(); break; case BMOPT_DROPPING_PREVENT : OnCheckDroppingPrevent(); break; case BMOPT_STEEL_QUANTITY : OnCheckSteelQuantity(); break; case BMOPT_PAINT : OnCheckPaint(); break; case BMOPT_DRAIN_ESTABLISH : OnCheckDrainEstablish(); break; case BMOPT_WING_WALL : OnCheckWingWall(); break; case BMOPT_TIMBER : OnCheckTimber(); break; case BMOPT_ELECWIREHOLE : OnCheckElecWireHole(); break; } } void CDeckBMOptionDlg::SetDataDefault() { CPlateBridgeApp *pDB = m_pStd->m_pDataManage->GetBridge(); CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CCalcData *pData = m_pStd->m_pDataManage->GetCalcData(); CCalcFloor CalcFloor(m_pStd->m_pDataManage); CCentSeparation *pLCen = NULL; CCentSeparation *pRCen = NULL; double dGuardHeightL = 0, dGuardHeightR = 0; if(pDB->GetGuardFencesu() > 0) { pLCen = pDB->GetGuardFence(0); pRCen = pDB->GetGuardFence(pDB->GetGuardWallSu()-1); dGuardHeightL = pLCen->GetHeight(); dGuardHeightR = pRCen->GetHeight(); } pBMOpt->SetDataDefault(); double dWingLeftStt = pBMOpt->m_structWingWall.m_dLengthLeftStt; double dWingLeftEnd = pBMOpt->m_structWingWall.m_dLengthLeftEnd; double dWingRighStt = pBMOpt->m_structWingWall.m_dLengthRighStt; double dWingRighEnd = pBMOpt->m_structWingWall.m_dLengthRighEnd; pBMOpt->m_structParapet.m_dGuardLength[0] = pADeckData->GetLengthSlabTotal(JONGBASEPOS_SLABLEFT) + dWingLeftStt + dWingLeftEnd; pBMOpt->m_structParapet.m_dGuardLength[1] = pADeckData->GetLengthSlabTotal(JONGBASEPOS_SLABRIGHT) + dWingRighStt + dWingRighEnd; pBMOpt->m_structParapet.m_dCurbLength = (pBMOpt->m_structParapet.m_dGuardLength[0] + pBMOpt->m_structParapet.m_dGuardLength[1])/2; double dLHeight = pData->DESIGN_FLOOR_DATA[FLOOR_LEFT].m_dBangEmHeight; double dRHeight = pData->DESIGN_FLOOR_DATA[FLOOR_RIGHT].m_dBangEmHeight; long nGuardTypeL = CalcFloor.GetGuardWallType(FLOOR_LEFT); long nGuardTypeR = CalcFloor.GetGuardWallType(FLOOR_RIGHT); BOOL bBangEmExistL = (pData->DESIGN_FLOOR_DATA[FLOOR_LEFT].m_bBangEm && nGuardTypeL<=8) ? TRUE : FALSE; BOOL bBangEmExistR = (pData->DESIGN_FLOOR_DATA[FLOOR_RIGHT].m_bBangEm && nGuardTypeR<=8) ? TRUE : FALSE; if(bBangEmExistL) pBMOpt->m_structSoundProof.m_dLHeight = frM(dLHeight - toM(dGuardHeightL)); if(bBangEmExistR) pBMOpt->m_structSoundProof.m_dRHeight = frM(dRHeight - toM(dGuardHeightR)); OnGridRedraw(); } void CDeckBMOptionDlg::DrawInputDomyunView(BOOL bZoomAll) { CDomyun *pDom = m_pView->GetDomyun(); pDom->ClearEtt(TRUE); CGeneralBaseDlg::DrawInputDomyunView(bZoomAll); } BOOL CDeckBMOptionDlg::PreTranslateMessage(MSG* pMsg) { if(m_Grid.TranslateMsg(pMsg)) return m_Grid.PreTranslateMessage(pMsg); BOOL bReturn = CGeneralBaseDlg::PreTranslateMessage(pMsg); CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CStringArray strCombo; if(pMsg->message == WM_LBUTTONDOWN || pMsg->message == WM_LBUTTONDBLCLK) { CCellID next = m_Grid.GetFocusCell(); switch(m_nSelectedOpt) { case BMOPT_CONCRETE_BYE : case BMOPT_CONCRETE_PLACING : case BMOPT_MOLD : case BMOPT_SPACER : case BMOPT_PAVE : case BMOPT_TACKCOATING : case BMOPT_DRAINBRIDGESURFACE : case BMOPT_SHRINKAGE_CONCRETE : case BMOPT_WATER_DRAW : case BMOPT_GUARD_FENCE : case BMOPT_SOUND_PROOF : case BMOPT_SHADE : case BMOPT_STEEL_QUANTITY : case BMOPT_PAINT : case BMOPT_BRIDGENAME : case BMOPT_BRIDGENAME_PLATE : case BMOPT_EXPLAIN_PLATE : case BMOPT_ESTABLISH_TBM : case BMOPT_EXPANSIONJOINT_COVER : case BMOPT_PARAPET : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } break; case BMOPT_STYROFOAM : if(next.col == 1) { if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } else if(next.row == 2 && next.col == 1) { strCombo.Add("좌측적용"); strCombo.Add("우측적용"); m_Grid.SetComboString(strCombo); } else if(next.row ==3 && next.col == 1) { strCombo.Add("10"); strCombo.Add("20"); m_Grid.SetComboString(strCombo); } } break; case BMOPT_EXPANSIONJOINT : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } else if(next.row == 2 && next.col == 1) { // strCombo.Add("단위 m당 수량"); strCombo.Add("지점별 수량"); m_Grid.SetComboString(strCombo); } else if(next.row == 4 || next.row == 5 || next.row == 6 || next.row == 8) { if(next.col == 1) GetComboRebarDia(strCombo); m_Grid.SetComboString(strCombo); } break; case BMOPT_NOTCH : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } else if(next.row == 2 && next.col == 1) { strCombo.Add("좌측적용"); strCombo.Add("우측적용"); strCombo.Add("양측적용"); m_Grid.SetComboString(strCombo); } break; case BMOPT_WING_WALL : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } break; case BMOPT_DRAIN_ESTABLISH : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } else if(next.row == 2 && next.col == 1) { strCombo.Add("하천용"); strCombo.Add("육교용"); strCombo.Add("하천및육교용"); m_Grid.SetComboString(strCombo); } else if(next.row == 3 && next.col == 1) { if(pBMOpt->m_nDrainEstablishType == WALKWAY || pBMOpt->m_nDrainEstablishType == RIVERWALKWAY) { strCombo.Add("TYPE 1 (건교부)"); strCombo.Add("TYPE 2"); m_Grid.SetComboString(strCombo); } } break; case BMOPT_TIMBER : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } else if(next.row == 2 && next.col == 1) { strCombo.Add("목재"); strCombo.Add("강관"); m_Grid.SetComboString(strCombo); } else if(next.row == 3 && next.col == 1) { strCombo.Add("미적용"); strCombo.Add("좌측적용"); strCombo.Add("우측적용"); strCombo.Add("양측적용"); m_Grid.SetComboString(strCombo); } break; case BMOPT_REBAR_MANUFACTURE : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } else if((next.row == 2 || next.row == 3 || next.row == 4) && next.col == 1) { strCombo.Add("매우복잡"); strCombo.Add("복잡"); strCombo.Add("보통"); strCombo.Add("간단"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } break; case BMOPT_DROPPING_PREVENT : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } else if(next.row == 2 && next.col == 1) { strCombo.Add("수평적용"); strCombo.Add("수평수직적용"); m_Grid.SetComboString(strCombo); } break; case BMOPT_ELECWIREHOLE : if(next.row == 1 && next.col == 1) { strCombo.Add("적용"); strCombo.Add("미적용"); m_Grid.SetComboString(strCombo); } break; } } return bReturn; } void CDeckBMOptionDlg::GetComboRebarDia(CStringArray &strComboArr) { CADeckData *pADeckData = m_pStd->m_pDeckData; double dSigmaY = toKgPCm2(pADeckData->m_SigmaY); CString szFy; szFy = GetCharRebarMark(dSigmaY); strComboArr.Add(szFy+"13"); strComboArr.Add(szFy+"16"); strComboArr.Add(szFy+"19"); strComboArr.Add(szFy+"22"); strComboArr.Add(szFy+"25"); strComboArr.Add(szFy+"29"); strComboArr.Add(szFy+"32"); strComboArr.Add(szFy+"35"); } void CDeckBMOptionDlg::GetBMOptionContents(CStringArray &Arr) { CPlateBridgeApp *pDB = m_pStd->m_pDataManage->GetBridge(); CGlobarOption *pGlopt = m_pStd->m_pDataManage->GetGlobalOption(); CSteelUWeight *pUWeight = m_pStd->m_pDataManage->GetSteelUWeight(); CADeckData *pADeckData = m_pStd->m_pDeckData; CCalcData *pData = m_pStd->m_pDataManage->GetCalcData(); CCalcFloor CalcFloor(m_pStd->m_pDataManage); CBMOption *pBMOpt = &pADeckData->m_BMOption; CString sText = _T(""); double dSigmaY = toKgPCm2(pADeckData->m_SigmaY); sText.Format("\n"); Arr.Add(sText); sText.Format(" ☞ 수량 출력 옵션 설정 내용 ☜ \n\n"); Arr.Add(sText); sText.Format(" 1. 콘크리트 구입 : %s\n", IsApply(pBMOpt->m_bConcreteBuy)); Arr.Add(sText); sText.Format(" 2. 콘크리트 타설 : %s\n", IsApply(pBMOpt->m_bConcretePlacing)); Arr.Add(sText); sText.Format(" 3. 거 푸 집 : %s\n", IsApply(pBMOpt->m_bMold)); Arr.Add(sText); sText.Format(" 4. 스페이셔 : %s\n", IsApply(pBMOpt->m_bSpacer)); Arr.Add(sText); sText.Format(" 5. 철근가공 조립 : %s\n", IsApply(pBMOpt->m_structRebarManufacture.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structRebarManufacture.m_bApply) { CString szSpace = pDB->IsTUGir() ? _T(" ") : _T(""); sText.Format(" - 슬 래 브%s : %s \n", szSpace, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nSlabType)); Arr.Add(sText); if(pDB->GetGuardWallSu() > 0) { sText.Format(" - 방 호 벽%s : %s \n", szSpace, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nGuardFenceType)); Arr.Add(sText); } if(pBMOpt->m_structExpansionJoint.m_bApply) { sText.Format(" - 신축이음%s : %s \n", szSpace, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nExpansionJointType)); Arr.Add(sText); } if(pDB->IsTUGir()) { sText.Format(" - 구속콘크리트 : %s \n", pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nBindConcType)); Arr.Add(sText); } } // 포장 if(pBMOpt->m_structPave.m_bApply) sText.Format(" 6. %s 포장 : %.0f mm\n", pUWeight->GetTypePave(), pBMOpt->m_structPave.m_dPaveThick); else sText.Format(" 6. %s 포장 : %s\n", pUWeight->GetTypePave(), IsApply(pBMOpt->m_structPave.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structTackCoating.m_bApply) sText.Format(" 7. 택 코 팅 : %.1f 배\n", pBMOpt->m_structTackCoating.m_dTackCoating); else sText.Format(" 7. 택 코 팅 : %s\n", IsApply(pBMOpt->m_structTackCoating.m_bApply)); Arr.Add(sText); sText.Format(" 8. 교면방수 : %s\n", IsApply(pBMOpt->m_bDrainBridgeSurface)); Arr.Add(sText); sText.Format(" 9. 교 명 주 : %s\n", IsApply(pBMOpt->m_structBridgeName.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structBridgeName.m_bApply) { sText.Format(" - 설치갯수 : %d EA\n", pBMOpt->m_structBridgeName.m_nQty); Arr.Add(sText); } sText.Format(" 10. 교 명 판 : %s\n", IsApply(pBMOpt->m_structBridgeNamePlate.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structBridgeNamePlate.m_bApply) { sText.Format(" - 설치갯수 : %d EA\n", pBMOpt->m_structBridgeNamePlate.m_nQty); Arr.Add(sText); } sText.Format(" 11. 설 명 판 : %s\n", IsApply(pBMOpt->m_structExplainPlate.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structExplainPlate.m_bApply) { sText.Format(" - 설치갯수 : %d EA\n", pBMOpt->m_structExplainPlate.m_nQty); Arr.Add(sText); } sText.Format(" 12. TBM 설치 : %s\n", IsApply(pBMOpt->m_structEstablishTBM.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structEstablishTBM.m_bApply) { sText.Format(" - 설치갯수 : %d EA\n", pBMOpt->m_structEstablishTBM.m_nQty); Arr.Add(sText); } if(pBMOpt->m_structStyrofoam.m_bApply) { if(pBMOpt->m_structStyrofoam.m_bLeft) sText.Format(" 13. 스티로폼 : 좌측적용 %.0f mm\n", pBMOpt->m_structStyrofoam.m_dThick); else sText.Format(" 13. 스티로폼 : 우측적용 %.0f mm\n", pBMOpt->m_structStyrofoam.m_dThick); } else sText.Format(" 13. 스티로폼 : %s\n", IsApply(pBMOpt->m_structStyrofoam.m_bApply)); Arr.Add(sText); sText.Format(" 14. 신축이음 : %s\n", IsApply(pBMOpt->m_structExpansionJoint.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structExpansionJoint.m_bApply) { if(pBMOpt->m_structExpansionJoint.m_bUnitLength) { sText.Format(" - 수량기준 : 단위 m당 수량 (Kgf/m)\n"); Arr.Add(sText); sText.Format(" - 시점 : %s - 종점 : %s\n", pBMOpt->m_structExpansionJoint.m_szSttName, pBMOpt->m_structExpansionJoint.m_szEndName); Arr.Add(sText); sText.Format(" %s %.3f Kgf/m %s %.3f Kgf/m\n", pBMOpt->GetExpansionJointDia(TRUE, 0, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[0]), pBMOpt->GetExpansionJointDia(FALSE, 0, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[0])); Arr.Add(sText); sText.Format(" %s %.3f Kgf/m %s %.3f Kgf/m\n", pBMOpt->GetExpansionJointDia(TRUE, 1, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[1]), pBMOpt->GetExpansionJointDia(FALSE, 1, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[1])); Arr.Add(sText); } else { sText.Format(" - 수량기준 : 지점별 수량 (tonf)\n"); Arr.Add(sText); sText.Format(" - 시점 : %s - 종점 : %s\n", pBMOpt->m_structExpansionJoint.m_szSttName, pBMOpt->m_structExpansionJoint.m_szEndName); Arr.Add(sText); sText.Format(" %s %.3f tonf %s %.3f tonf\n", pBMOpt->GetExpansionJointDia(TRUE, 0, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[0]), pBMOpt->GetExpansionJointDia(FALSE, 0, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[0])); Arr.Add(sText); sText.Format(" %s %.3f tonf %s %.3f tonf\n", pBMOpt->GetExpansionJointDia(TRUE, 1, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[1]), pBMOpt->GetExpansionJointDia(FALSE, 1, dSigmaY), toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[1])); Arr.Add(sText); } sText.Format(" - 여유치수 : %.0f mm\n", pBMOpt->m_structExpansionJoint.m_dMargin); Arr.Add(sText); sText.Format(" - 여유치적용 개수 : %d EA\n", pBMOpt->m_structExpansionJoint.m_nMarginsu); Arr.Add(sText); } sText.Format(" 15. 신축이음덮개 : %s\n", IsApply(pBMOpt->m_structExpansionJointCover.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structExpansionJointCover.m_bApply) { for(long n=0; n<7; n++) { sText.Format(" - %s 높이 : %.3f m %d EA\n", pBMOpt->GetExpansionJointCoverPos(n), toM(pBMOpt->m_structExpansionJointCover.m_dHeight[n]), pBMOpt->m_structExpansionJointCover.m_nQty[n]); Arr.Add(sText); } } double dExpJointSttHeight = pGlopt->GetSttExpansionJointHeight(); double dExpJointSttWidth = pGlopt->GetSttExpansionJointWidth(); double dExpJointEndHeight = pGlopt->GetEndExpansionJointHeight(); double dExpJointEndWidth = pGlopt->GetEndExpansionJointWidth(); sText.Format(" 16. 무수축 콘크리트 : %s\n", IsApply(pBMOpt->m_structShrinkageConcrete.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structShrinkageConcrete.m_bApply) { sText.Format(" - 시점적용 갯수 : %.0f × %.0f %d EA\n", dExpJointSttWidth, dExpJointSttHeight, pBMOpt->m_structShrinkageConcrete.m_nSttQty); Arr.Add(sText); sText.Format(" - 종점적용 갯수 : %.0f × %.0f %d EA\n", dExpJointEndWidth, dExpJointEndHeight, pBMOpt->m_structShrinkageConcrete.m_nEndQty); Arr.Add(sText); } sText.Format(" 17. 교면 물빼기 : %s\n", IsApply(pBMOpt->m_bWaterDraw)); Arr.Add(sText); sText.Format(" 18. NOTCH : %s\n", IsApply(pBMOpt->m_structNotch.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structNotch.m_bApply) { sText.Format(" - 적용위치 : %s\n", pBMOpt->GetNotchPos(pBMOpt->m_structNotch.m_nApplyPos)); Arr.Add(sText); sText.Format(" - NOTCH 종류 : %s\n", pBMOpt->m_structNotch.m_szNotchType); Arr.Add(sText); } if(pBMOpt->m_structGuardFence.m_bApply) sText.Format(" 19. 가드펜스 : %.3f m\n", toM(pBMOpt->m_structGuardFence.m_dHeight)); else sText.Format(" 19. 가드펜스 : %s\n", IsApply(pBMOpt->m_structGuardFence.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structSoundProof.m_bApply) { //방음벽 있나 없나 체크....070111....KB... long nGuardTypeL = CalcFloor.GetGuardWallType(FLOOR_LEFT); long nGuardTypeR = CalcFloor.GetGuardWallType(FLOOR_RIGHT); BOOL bBangEmExistL = (pData->DESIGN_FLOOR_DATA[FLOOR_LEFT].m_bBangEm && nGuardTypeL<=8) ? TRUE : FALSE; BOOL bBangEmExistR = (pData->DESIGN_FLOOR_DATA[FLOOR_RIGHT].m_bBangEm && nGuardTypeR<=8) ? TRUE : FALSE; if(bBangEmExistL && bBangEmExistR) sText.Format(" 20. 방음판넬 : %.3f m (좌) %.3f m (우)\n", toM(pBMOpt->m_structSoundProof.m_dLHeight), toM(pBMOpt->m_structSoundProof.m_dRHeight)); else if(bBangEmExistL && !bBangEmExistR) sText.Format(" 20. 방음판넬 : %.3f m (좌)\n", toM(pBMOpt->m_structSoundProof.m_dLHeight)); else if(!bBangEmExistL && bBangEmExistR) sText.Format(" 20. 방음판넬 : %.3f m (우)\n", toM(pBMOpt->m_structSoundProof.m_dRHeight)); } else sText.Format(" 20. 방음판넬 : %s\n", IsApply(pBMOpt->m_structSoundProof.m_bApply)); Arr.Add(sText); sText.Format(" 21. 난 간 : %s\n", IsApply(pBMOpt->m_structParapet.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structParapet.m_bApply) { sText.Format(" - %s : %s %s %.3f m\n", pBMOpt->GetParapetType(DRIVEWAY), IsApplyLeft(pBMOpt->m_structParapet.m_bLeft[DRIVEWAY]), IsApplyRight(pBMOpt->m_structParapet.m_bRight[DRIVEWAY]), toM(pBMOpt->m_structParapet.m_dHeight[DRIVEWAY])); Arr.Add(sText); sText.Format(" - %s : %s %s %.3f m\n", pBMOpt->GetParapetType(FOOTWAY), IsApplyLeft(pBMOpt->m_structParapet.m_bLeft[FOOTWAY]), IsApplyRight(pBMOpt->m_structParapet.m_bRight[FOOTWAY]), toM(pBMOpt->m_structParapet.m_dHeight[FOOTWAY])); Arr.Add(sText); sText.Format(" - %s : %s %s %.3f m\n", pBMOpt->GetParapetType(DRIVE_FOOT_BOUNDARY), IsApplyLeft(pBMOpt->m_structParapet.m_bLeft[DRIVE_FOOT_BOUNDARY]), IsApplyRight(pBMOpt->m_structParapet.m_bRight[DRIVE_FOOT_BOUNDARY]), toM(pBMOpt->m_structParapet.m_dHeight[DRIVE_FOOT_BOUNDARY]));Arr.Add(sText); } sText.Format(" 22. 차광망 : %s\n", IsApply(pBMOpt->m_bShade)); Arr.Add(sText); sText.Format(" 23. 낙하물 방지공 : %s\n", IsApply(pBMOpt->m_structDroppingPrevent.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structDroppingPrevent.m_bApply) { sText.Format(" - 적 용 위 치 : %s", pBMOpt->GetDroppingPrevent(pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal));Arr.Add(sText); sText.Format(" - 수평여유높이 : %.3f m\n", toM(pBMOpt->m_structDroppingPrevent.m_dHorSpaceHeight));Arr.Add(sText); if(!pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal) { sText.Format(" - 수직여유높이 : %.3f m\n", toM(pBMOpt->m_structDroppingPrevent.m_dVerSpaceHeight)); Arr.Add(sText); } } sText.Format(" 24. 강재수량 : %s\n", IsApply(pBMOpt->m_bSteelQuantity)); Arr.Add(sText); sText.Format(" 25. 강교도장 : %s\n", IsApply(pBMOpt->m_bPaint)); Arr.Add(sText); sText.Format(" 26. 배수시설 : %s\n", IsApply(pBMOpt->m_bDrainEstablish)); Arr.Add(sText); if(pBMOpt->m_bDrainEstablish && (pBMOpt->m_nDrainEstablishType == RIVER || pBMOpt->m_nDrainEstablishType == RIVERWALKWAY)) { sText.Format(" ⊙ 하 천 용\n"); Arr.Add(sText); sText.Format(" - 집 수 구 (스테인레스 Plate) : %d EA\n", pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect); Arr.Add(sText); sText.Format(" - 배 수 구 (스테인레스 강관) : %.3f m\n", toM(pBMOpt->m_structRiverDrainEstablish.m_dDrain)); Arr.Add(sText); } if(pBMOpt->m_bDrainEstablish && (pBMOpt->m_nDrainEstablishType == WALKWAY || pBMOpt->m_nDrainEstablishType == RIVERWALKWAY)) { if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0) { sText.Format(" ⊙ 육 교 용 TYPE 1 (건교부)\n"); Arr.Add(sText); sText.Format(" - 집 수 구 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect); Arr.Add(sText); sText.Format(" - 연결집수거 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect); Arr.Add(sText); sText.Format(" - 직 관 : %.3f m\n", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0])); Arr.Add(sText); sText.Format(" - 곡 관 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]); Arr.Add(sText); sText.Format(" - 연 결 부 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nJoint); Arr.Add(sText); } else { sText.Format(" ⊙ 육 교 용 TYPE 2\n"); Arr.Add(sText); sText.Format(" - 집 수 구 (스테인레스 강관) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect); Arr.Add(sText); sText.Format(" - 배 수 구 (스테인레스 강관) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nDrain); Arr.Add(sText); sText.Format(" - 연결배수구 (8"" × 10"") : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain); Arr.Add(sText); sText.Format(" - 직 관 (150A) : %.3f m\n", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0])); Arr.Add(sText); sText.Format(" - 직 관 (200A) : %.3f m\n", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1])); Arr.Add(sText); sText.Format(" - 곡 관 (150A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]); Arr.Add(sText); sText.Format(" - 곡 관 (200A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1]); Arr.Add(sText); sText.Format(" - 청 소 구 (150A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0]); Arr.Add(sText); sText.Format(" - 청 소 구 (200A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1]); Arr.Add(sText); sText.Format(" - 상부고정대 (150A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0]); Arr.Add(sText); sText.Format(" - 상부고정대 (200A) : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1]); Arr.Add(sText); sText.Format(" - 침 전 조 : %d EA\n", pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting); Arr.Add(sText); } } sText.Format(" 27. 날 개 벽 : %s\n", IsApply(pBMOpt->m_structWingWall.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structWingWall.m_bApply) { sText.Format(" - 좌측 => 시점 : %.3f m 종점 : %.3f m\n", toM(pBMOpt->m_structWingWall.m_dLengthLeftStt), toM(pBMOpt->m_structWingWall.m_dLengthLeftEnd));Arr.Add(sText); sText.Format(" - 우측 => 시점 : %.3f m 종점 : %.3f m\n", toM(pBMOpt->m_structWingWall.m_dLengthRighStt), toM(pBMOpt->m_structWingWall.m_dLengthRighEnd));Arr.Add(sText); } sText.Format(" 28. 동 바 리 : %s\n", IsApply(pBMOpt->m_structTimber.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structTimber.m_bApply) { sText.Format(" - 동 바 리 재질 : %s\n", pBMOpt->GetTimberQuality(pBMOpt->m_structTimber.m_nQuality));Arr.Add(sText); sText.Format(" - 데크피니셔 위치 : %s\n", pBMOpt->GetPosDeckFinisher(pBMOpt->m_structTimber.m_nPosDeckFinisher));Arr.Add(sText); sText.Format(" - 데크피니셔 작업폭 : %.3f m\n", toM(pBMOpt->m_structTimber.m_dDeckFinisherWorkWidth));Arr.Add(sText); } sText.Format(" 29. 전 선 관 : %s\n", IsApply(pBMOpt->m_structElecWireHole.m_bApply)); Arr.Add(sText); if(pBMOpt->m_structElecWireHole.m_bApply) { sText.Format(" - φ100 => 좌측 : %d EA 우측 : %d EA\n", pBMOpt->m_structElecWireHole.m_nEA100[0], pBMOpt->m_structElecWireHole.m_nEA100[1]);Arr.Add(sText); sText.Format(" - φ125 => 좌측 : %d EA 우측 : %d EA\n", pBMOpt->m_structElecWireHole.m_nEA125[0], pBMOpt->m_structElecWireHole.m_nEA125[1]);Arr.Add(sText); sText.Format(" - φ150 => 좌측 : %d EA 우측 : %d EA\n", pBMOpt->m_structElecWireHole.m_nEA150[0], pBMOpt->m_structElecWireHole.m_nEA150[1]);Arr.Add(sText); } } void CDeckBMOptionDlg::OnCellChangedData(NMHDR* nmgv, LRESULT*) { CPlateBridgeApp *pDB = m_pStd->m_pDataManage->GetBridge(); CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; if(m_nSelectedOpt == BMOPT_CONCRETE_BYE) pBMOpt->m_bConcreteBuy = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_CONCRETE_PLACING) pBMOpt->m_bConcretePlacing = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_MOLD) pBMOpt->m_bMold = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_SPACER) pBMOpt->m_bSpacer = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_REBAR_MANUFACTURE) { pBMOpt->m_structRebarManufacture.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structRebarManufacture.m_nSlabType = pBMOpt->GetIdxRebarManufactureType(m_Grid.GetTextMatrix(2, 1)); long nRow = 3; if(pDB->GetGuardWallSu() > 0) pBMOpt->m_structRebarManufacture.m_nGuardFenceType = pBMOpt->GetIdxRebarManufactureType(m_Grid.GetTextMatrix(nRow++, 1)); if(pBMOpt->m_structExpansionJoint.m_bApply) pBMOpt->m_structRebarManufacture.m_nExpansionJointType = pBMOpt->GetIdxRebarManufactureType(m_Grid.GetTextMatrix(nRow++, 1)); if(pDB->IsTUGir()) pBMOpt->m_structRebarManufacture.m_nBindConcType = pBMOpt->GetIdxRebarManufactureType(m_Grid.GetTextMatrix(nRow++, 1)); OnCheckRebarManufacture(); } if(m_nSelectedOpt == BMOPT_PAVE) { pBMOpt->m_structPave.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structPave.m_dPaveThick = m_Grid.GetTextMatrixDouble(1, 2); OnCheckPave(); } if(m_nSelectedOpt == BMOPT_TACKCOATING) { pBMOpt->m_structTackCoating.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structTackCoating.m_dTackCoating = m_Grid.GetTextMatrixDouble(1, 2); OnCheckTackCoating(); } if(m_nSelectedOpt == BMOPT_DRAINBRIDGESURFACE) pBMOpt->m_bDrainBridgeSurface = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_BRIDGENAME) { pBMOpt->m_structBridgeName.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structBridgeName.m_nQty = m_Grid.GetTextMatrixLong(2, 1); OnCheckBridgeName(); } if(m_nSelectedOpt == BMOPT_BRIDGENAME_PLATE) { pBMOpt->m_structBridgeNamePlate.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structBridgeNamePlate.m_nQty = m_Grid.GetTextMatrixLong(2, 1); OnCheckBridgeNameplate(); } if(m_nSelectedOpt == BMOPT_EXPLAIN_PLATE) { pBMOpt->m_structExplainPlate.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structExplainPlate.m_nQty = m_Grid.GetTextMatrixLong(2, 1); OnCheckExplainPlate(); } if(m_nSelectedOpt == BMOPT_ESTABLISH_TBM) { pBMOpt->m_structEstablishTBM.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structEstablishTBM.m_nQty = m_Grid.GetTextMatrixLong(2, 1); OnCheckEstablishTbm(); } if(m_nSelectedOpt == BMOPT_STYROFOAM) { pBMOpt->m_structStyrofoam.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structStyrofoam.m_bLeft = IsLeft(m_Grid.GetTextMatrix(2, 1)); pBMOpt->m_structStyrofoam.m_dThick = m_Grid.GetTextMatrixDouble(3, 1); OnCheckStyrofoam(); } if(m_nSelectedOpt == BMOPT_EXPANSIONJOINT) { pBMOpt->m_structExpansionJoint.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structExpansionJoint.m_bUnitLength = IsApply(m_Grid.GetTextMatrix(2, 1)); pBMOpt->m_structExpansionJoint.m_szSttName = m_Grid.GetTextMatrix(3, 1); pBMOpt->m_structExpansionJoint.m_nSttDiaIdx[0] = pBMOpt->GetRebarDiaIndex(m_Grid.GetTextMatrix(4, 1)); pBMOpt->m_structExpansionJoint.m_dSttWeight[0] = pBMOpt->m_structExpansionJoint.m_bUnitLength ? m_Grid.GetTextMatrixDouble(4, 2) : frTon(m_Grid.GetTextMatrixDouble(4, 2)); pBMOpt->m_structExpansionJoint.m_nSttDiaIdx[1] = pBMOpt->GetRebarDiaIndex(m_Grid.GetTextMatrix(5, 1)); pBMOpt->m_structExpansionJoint.m_dSttWeight[1] = pBMOpt->m_structExpansionJoint.m_bUnitLength ? m_Grid.GetTextMatrixDouble(5, 2) : frTon(m_Grid.GetTextMatrixDouble(5, 2)); pBMOpt->m_structExpansionJoint.m_szEndName = m_Grid.GetTextMatrix(6, 1); pBMOpt->m_structExpansionJoint.m_nEndDiaIdx[0] = pBMOpt->GetRebarDiaIndex(m_Grid.GetTextMatrix(7, 1)); pBMOpt->m_structExpansionJoint.m_dEndWeight[0] = pBMOpt->m_structExpansionJoint.m_bUnitLength ? m_Grid.GetTextMatrixDouble(7, 2) : frTon(m_Grid.GetTextMatrixDouble(7, 2)); pBMOpt->m_structExpansionJoint.m_nEndDiaIdx[1] = pBMOpt->GetRebarDiaIndex(m_Grid.GetTextMatrix(8, 1)); pBMOpt->m_structExpansionJoint.m_dEndWeight[1] = pBMOpt->m_structExpansionJoint.m_bUnitLength ? m_Grid.GetTextMatrixDouble(8, 2) : frTon(m_Grid.GetTextMatrixDouble(8, 2)); pBMOpt->m_structExpansionJoint.m_dMargin = m_Grid.GetTextMatrixDouble(9, 1); pBMOpt->m_structExpansionJoint.m_nMarginsu = m_Grid.GetTextMatrixLong(10, 1); OnCheckExpansionjoint(); } if(m_nSelectedOpt == BMOPT_EXPANSIONJOINT_COVER) { pBMOpt->m_structExpansionJointCover.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); for(long nRow = 2; nRow < 9; nRow++) { pBMOpt->m_structExpansionJointCover.m_dHeight[nRow-2] = frM(m_Grid.GetTextMatrixDouble(nRow, 1)); pBMOpt->m_structExpansionJointCover.m_nQty[nRow-2] = m_Grid.GetTextMatrixLong(nRow, 3); } OnCheckExpansionjointCover(); } if(m_nSelectedOpt == BMOPT_SHRINKAGE_CONCRETE) { pBMOpt->m_structShrinkageConcrete.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structShrinkageConcrete.m_nSttQty = m_Grid.GetTextMatrixLong(2, 2); pBMOpt->m_structShrinkageConcrete.m_nEndQty = m_Grid.GetTextMatrixLong(3, 2); OnCheckShrinkageConcrete(); } if(m_nSelectedOpt == BMOPT_WATER_DRAW) pBMOpt->m_bWaterDraw = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_NOTCH) { pBMOpt->m_structNotch.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structNotch.m_nApplyPos = pBMOpt->GetNotchPos(m_Grid.GetTextMatrix(2, 1)); pBMOpt->m_structNotch.m_szNotchType = m_Grid.GetTextMatrix(3, 1); OnCheckNotch(); } if(m_nSelectedOpt == BMOPT_GUARD_FENCE) { pBMOpt->m_structGuardFence.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structGuardFence.m_dHeight = frM(m_Grid.GetTextMatrixDouble(1, 2)); OnCheckGuardFence(); } if(m_nSelectedOpt == BMOPT_SOUND_PROOF) { pBMOpt->m_structSoundProof.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structSoundProof.m_dLHeight = frM(m_Grid.GetTextMatrixDouble(2, 1)); pBMOpt->m_structSoundProof.m_dRHeight = frM(m_Grid.GetTextMatrixDouble(3, 1)); OnCheckSoundProof(); } if(m_nSelectedOpt == BMOPT_PARAPET) { pBMOpt->m_structParapet.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structParapet.m_dGuardLength[0] = frM(m_Grid.GetTextMatrixDouble(2, 2)); pBMOpt->m_structParapet.m_dGuardLength[1] = frM(m_Grid.GetTextMatrixDouble(3, 2)); pBMOpt->m_structParapet.m_dCurbLength = frM(m_Grid.GetTextMatrixDouble(4, 2)); pBMOpt->m_structParapet.m_nCurbQty = m_Grid.GetTextMatrixLong(5, 2); OnCheckParapet(); } if(m_nSelectedOpt == BMOPT_SHADE) pBMOpt->m_bShade = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_DROPPING_PREVENT) { pBMOpt->m_structDroppingPrevent.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal = pBMOpt->GetDroppingPrevent(m_Grid.GetTextMatrix(2, 1)); pBMOpt->m_structDroppingPrevent.m_dHorSpaceHeight = frM(m_Grid.GetTextMatrixDouble(3, 1)); if(!pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal) pBMOpt->m_structDroppingPrevent.m_dVerSpaceHeight = frM(m_Grid.GetTextMatrixDouble(4, 1)); OnCheckDroppingPrevent(); } if(m_nSelectedOpt == BMOPT_STEEL_QUANTITY) pBMOpt->m_bSteelQuantity = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_PAINT) pBMOpt->m_bPaint = IsApply(m_Grid.GetTextMatrix(1, 1)); if(m_nSelectedOpt == BMOPT_DRAIN_ESTABLISH) { pBMOpt->m_bDrainEstablish = IsApply(m_Grid.GetTextMatrix(1, 1)); if(pBMOpt->m_nDrainEstablishType == RIVER) { pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(3, 2); // 집수구 pBMOpt->m_structRiverDrainEstablish.m_dDrain = frM(m_Grid.GetTextMatrixDouble(4, 2)); // 배수구 } else if(pBMOpt->m_nDrainEstablishType == WALKWAY || pBMOpt->m_nDrainEstablishType == RIVERWALKWAY) { if(m_Grid.GetTextMatrix(3, 1) == _T("TYPE 1 (건교부)")) pBMOpt->m_structWalkWayDrainEstablish.m_nType = 0; else pBMOpt->m_structWalkWayDrainEstablish.m_nType = 1; if(pBMOpt->m_nDrainEstablishType == WALKWAY && pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0) { pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(4, 2); // 집수구 pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect = m_Grid.GetTextMatrixLong(5, 2); // 연결집수거 pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0] = frM(m_Grid.GetTextMatrixDouble(6, 2)); // 직관 pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0] = m_Grid.GetTextMatrixLong(7, 2); // 곡관 pBMOpt->m_structWalkWayDrainEstablish.m_nJoint = m_Grid.GetTextMatrixLong(8, 2); // 연결부 } else if(pBMOpt->m_nDrainEstablishType == WALKWAY && pBMOpt->m_structWalkWayDrainEstablish.m_nType == 1) { pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(4, 2); // 집수구 pBMOpt->m_structWalkWayDrainEstablish.m_nDrain = m_Grid.GetTextMatrixLong(5, 2); // 배수구 pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain = m_Grid.GetTextMatrixLong(6, 2); // 연결배수구 pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0] = frM(m_Grid.GetTextMatrixDouble(7, 2)); // 직관 pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1] = frM(m_Grid.GetTextMatrixDouble(8, 2)); // 직관 pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0] = m_Grid.GetTextMatrixLong(9, 2); // 곡관 pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1] = m_Grid.GetTextMatrixLong(10, 2); // 곡관 pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0] = m_Grid.GetTextMatrixLong(11, 2); // 청소구 pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1] = m_Grid.GetTextMatrixLong(12, 2); // 청소구 pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0] = m_Grid.GetTextMatrixLong(13, 2); // 상부고정대 pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1] = m_Grid.GetTextMatrixLong(14, 2); // 상부고정대 pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting = m_Grid.GetTextMatrixLong(15, 2); // 침전조 } else if(pBMOpt->m_nDrainEstablishType == RIVERWALKWAY) { pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(4, 2); // 집수구 pBMOpt->m_structRiverDrainEstablish.m_dDrain = frM(m_Grid.GetTextMatrixDouble(5, 2)); // 배수구 if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0) { pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(6, 2); // 집수구 pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect = m_Grid.GetTextMatrixLong(7, 2); // 연결집수거 pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0] = frM(m_Grid.GetTextMatrixDouble(8, 2));// 직관 pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0] = m_Grid.GetTextMatrixLong(9, 2); // 곡관 pBMOpt->m_structWalkWayDrainEstablish.m_nJoint = m_Grid.GetTextMatrixLong(10, 2); // 연결부 } else { pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect = m_Grid.GetTextMatrixLong(6, 2); // 집수구 pBMOpt->m_structWalkWayDrainEstablish.m_nDrain = m_Grid.GetTextMatrixLong(7, 2); // 배수구 pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain = m_Grid.GetTextMatrixLong(8, 2); // 연결배수구 pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0] = frM(m_Grid.GetTextMatrixDouble(9, 2));// 직관 pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1] = frM(m_Grid.GetTextMatrixDouble(10, 2));// 직관 pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0] = m_Grid.GetTextMatrixLong(11, 2); // 곡관 pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1] = m_Grid.GetTextMatrixLong(12, 2); // 곡관 pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0] = m_Grid.GetTextMatrixLong(13, 2); // 청소구 pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1] = m_Grid.GetTextMatrixLong(14, 2); // 청소구 pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0] = m_Grid.GetTextMatrixLong(15, 2); // 상부고정대 pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1] = m_Grid.GetTextMatrixLong(16, 2); // 상부고정대 pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting = m_Grid.GetTextMatrixLong(17, 2); // 침전조 } } } pBMOpt->m_nDrainEstablishType = pBMOpt->GetIdxDrainEstablishType(m_Grid.GetTextMatrix(2, 1)); OnCheckDrainEstablish(); } if(m_nSelectedOpt == BMOPT_WING_WALL) { pBMOpt->m_structWingWall.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structWingWall.m_dLengthLeftStt = frM(m_Grid.GetTextMatrixDouble(2, 2)); pBMOpt->m_structWingWall.m_dLengthLeftEnd = frM(m_Grid.GetTextMatrixDouble(3, 2)); pBMOpt->m_structWingWall.m_dLengthRighStt = frM(m_Grid.GetTextMatrixDouble(4, 2)); pBMOpt->m_structWingWall.m_dLengthRighEnd = frM(m_Grid.GetTextMatrixDouble(5, 2)); OnCheckWingWall(); } if(m_nSelectedOpt == BMOPT_TIMBER) { pBMOpt->m_structTimber.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structTimber.m_nQuality = pBMOpt->GetIdxTimberQuality(m_Grid.GetTextMatrix(2, 1)); pBMOpt->m_structTimber.m_nPosDeckFinisher = pBMOpt->GetIdxDeckFinisher(m_Grid.GetTextMatrix(3, 1)); pBMOpt->m_structTimber.m_dDeckFinisherWorkWidth = frM(m_Grid.GetTextMatrixDouble(4, 1)); OnCheckTimber(); } if(m_nSelectedOpt == BMOPT_ELECWIREHOLE) { pBMOpt->m_structElecWireHole.m_bApply = IsApply(m_Grid.GetTextMatrix(1, 1)); pBMOpt->m_structElecWireHole.m_nEA100[0] = m_Grid.GetTextMatrixLong(2, 2); pBMOpt->m_structElecWireHole.m_nEA100[1] = m_Grid.GetTextMatrixLong(3, 2); pBMOpt->m_structElecWireHole.m_nEA125[0] = m_Grid.GetTextMatrixLong(4, 2); pBMOpt->m_structElecWireHole.m_nEA125[1] = m_Grid.GetTextMatrixLong(5, 2); pBMOpt->m_structElecWireHole.m_nEA150[0] = m_Grid.GetTextMatrixLong(6, 2); pBMOpt->m_structElecWireHole.m_nEA150[1] = m_Grid.GetTextMatrixLong(7, 2); OnCheckElecWireHole(); } SetDataInit(); } // 콘크리트 구입 void CDeckBMOptionDlg::OnCheckConcreteBuy() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_CONCRETE_BYE; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bConcreteBuy)); m_ConcreteBuy.SetCheck(pBMOpt->m_bConcreteBuy); m_ConcreteBuy.Invalidate(); m_Grid.SetRedraw(TRUE,TRUE); } // 콘크리트 타설 void CDeckBMOptionDlg::OnCheckConcretePlacing() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_CONCRETE_PLACING; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bConcretePlacing)); m_ConcretePlacing.SetCheck(pBMOpt->m_bConcretePlacing); m_Grid.SetRedraw(TRUE,TRUE); } // 거푸집 void CDeckBMOptionDlg::OnCheckMold() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_MOLD; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bMold)); m_Mold.SetCheck(pBMOpt->m_bMold); m_Grid.SetRedraw(TRUE,TRUE); } // 스페이셔 void CDeckBMOptionDlg::OnCheckSpacer() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_SPACER; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bSpacer)); m_Spacer.SetCheck(pBMOpt->m_bSpacer); m_Grid.SetRedraw(TRUE,TRUE); } // 철근가공조립 void CDeckBMOptionDlg::OnCheckRebarManufacture() { CPlateBridgeApp *pDB = m_pStd->m_pDataManage->GetBridge(); CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_REBAR_MANUFACTURE; m_nCols = 2; m_nRows = 3; BOOL bGuard = FALSE; BOOL bExp = FALSE; BOOL bTUGir = pDB->IsTUGir(); if(pDB->GetGuardWallSu()>0) bGuard = TRUE; if(pBMOpt->m_structExpansionJoint.m_bApply) bExp = TRUE; if(bGuard) m_nRows++; if(bExp) m_nRows++; if(bTUGir) m_nRows++; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); long nRow = 3; if(bGuard) m_Grid.SetCellType(nRow++, 1, CT_COMBO); if(bExp) m_Grid.SetCellType(nRow++, 1, CT_COMBO); if(bTUGir) m_Grid.SetCellType(nRow++, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structRebarManufacture.m_bApply)); m_Grid.SetTextMatrix(2, 0, "슬 래 브"); nRow = 3; if(bGuard) m_Grid.SetTextMatrix(nRow++, 0, "방 호 벽"); if(bExp) m_Grid.SetTextMatrix(nRow++, 0, "신축이음"); if(bTUGir) m_Grid.SetTextMatrix(nRow++, 0, "구속콘크리트"); m_Grid.SetTextMatrix(2, 1, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nSlabType)); nRow = 3; if(bGuard) m_Grid.SetTextMatrix(nRow++, 1, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nGuardFenceType)); if(bExp) m_Grid.SetTextMatrix(nRow++, 1, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nExpansionJointType)); if(bTUGir) m_Grid.SetTextMatrix(nRow++, 1, pBMOpt->GetRebarManufactureType(pBMOpt->m_structRebarManufacture.m_nBindConcType)); if(!pBMOpt->m_structRebarManufacture.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); nRow = 3; if(bGuard) { m_Grid.SetItemState(nRow, 1, m_Grid.GetItemState(nRow, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(nRow++, 1, RGBREADONLY); } if(bExp) { m_Grid.SetItemState(nRow, 1, m_Grid.GetItemState(nRow, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(nRow++, 1, RGBREADONLY); } if(bTUGir) { m_Grid.SetItemState(nRow, 1, m_Grid.GetItemState(nRow, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(nRow++, 1, RGBREADONLY); } } m_RebarManufacture.SetCheck(pBMOpt->m_structRebarManufacture.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 포장 void CDeckBMOptionDlg::OnCheckPave() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_PAVE; m_nCols = 4; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 70); m_Grid.SetColumnWidth(2, 70); m_Grid.SetColumnWidth(3, 70); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(0, 2, "두께"); m_Grid.SetTextMatrix(0, 3, "단위"); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structPave.m_bApply)); m_Grid.SetTextMatrix(1, 2, "%.0f", pBMOpt->m_structPave.m_dPaveThick); m_Grid.SetTextMatrix(1, 3, "mm"); if(!pBMOpt->m_structPave.m_bApply) { m_Grid.SetItemState(1, 2, m_Grid.GetItemState(1, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 2, RGBREADONLY); m_Grid.SetItemState(1, 3, m_Grid.GetItemState(1, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 3, RGBREADONLY); } m_Pave.SetCheck(pBMOpt->m_structPave.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 택코팅 void CDeckBMOptionDlg::OnCheckTackCoating() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_TACKCOATING; m_nCols = 4; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 70); m_Grid.SetColumnWidth(2, 70); m_Grid.SetColumnWidth(3, 70); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(0, 2, "도포"); m_Grid.SetTextMatrix(0, 3, "단위"); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structTackCoating.m_bApply)); m_Grid.SetTextMatrix(1, 2, "%.1f", pBMOpt->m_structTackCoating.m_dTackCoating); m_Grid.SetTextMatrix(1, 3, "배"); if(!pBMOpt->m_structTackCoating.m_bApply) { m_Grid.SetItemState(1, 2, m_Grid.GetItemState(1, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 2, RGBREADONLY); m_Grid.SetItemState(1, 3, m_Grid.GetItemState(1, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 3, RGBREADONLY); } m_TackCoating.SetCheck(pBMOpt->m_structTackCoating.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 교면방수 void CDeckBMOptionDlg::OnCheckDrainBridgesurface() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_DRAINBRIDGESURFACE; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainBridgeSurface)); m_DrainBridgeSurface.SetCheck(pBMOpt->m_bDrainBridgeSurface); m_Grid.SetRedraw(TRUE,TRUE); } // 교명주 void CDeckBMOptionDlg::OnCheckBridgeName() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CString sText = _T(""); m_nSelectedOpt = BMOPT_BRIDGENAME; m_nCols = 3; m_nRows = 3; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 180); m_Grid.SetColumnWidth(2, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 2); m_Grid.SetMergeCol(1, 1, 2); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structBridgeName.m_bApply)); m_Grid.SetTextMatrix(2, 0, "설치갯수"); sText.Format("%d", pBMOpt->m_structBridgeName.m_nQty); m_Grid.SetTextMatrix(2, 1, sText); m_Grid.SetTextMatrix(2, 2, "EA"); if(!pBMOpt->m_structBridgeName.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY); } m_BridgeName.SetCheck(pBMOpt->m_structBridgeName.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 교명판 void CDeckBMOptionDlg::OnCheckBridgeNameplate() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CString sText = _T(""); m_nSelectedOpt = BMOPT_BRIDGENAME_PLATE; m_nCols = 3; m_nRows = 3; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 180); m_Grid.SetColumnWidth(2, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 2); m_Grid.SetMergeCol(1, 1, 2); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structBridgeNamePlate.m_bApply)); m_Grid.SetTextMatrix(2, 0, "설치갯수"); sText.Format("%d", pBMOpt->m_structBridgeNamePlate.m_nQty); m_Grid.SetTextMatrix(2, 1, sText); m_Grid.SetTextMatrix(2, 2, "EA"); if(!pBMOpt->m_structBridgeNamePlate.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY); } m_BridgeNamePlate.SetCheck(pBMOpt->m_structBridgeNamePlate.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 설명판 void CDeckBMOptionDlg::OnCheckExplainPlate() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CString sText = _T(""); m_nSelectedOpt = BMOPT_EXPLAIN_PLATE; m_nCols = 3; m_nRows = 3; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 180); m_Grid.SetColumnWidth(2, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 2); m_Grid.SetMergeCol(1, 1, 2); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structExplainPlate.m_bApply)); m_Grid.SetTextMatrix(2, 0, "설치갯수"); sText.Format("%d", pBMOpt->m_structExplainPlate.m_nQty); m_Grid.SetTextMatrix(2, 1, sText); m_Grid.SetTextMatrix(2, 2, "EA"); if(!pBMOpt->m_structExplainPlate.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY); } m_ExplainPlate.SetCheck(pBMOpt->m_structExplainPlate.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // TBM 설치 void CDeckBMOptionDlg::OnCheckEstablishTbm() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CString sText = _T(""); m_nSelectedOpt = BMOPT_ESTABLISH_TBM; m_nCols = 3; m_nRows = 3; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 180); m_Grid.SetColumnWidth(2, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 2); m_Grid.SetMergeCol(1, 1, 2); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structEstablishTBM.m_bApply)); m_Grid.SetTextMatrix(2, 0, "설치갯수"); sText.Format("%d", pBMOpt->m_structEstablishTBM.m_nQty); m_Grid.SetTextMatrix(2, 1, sText); m_Grid.SetTextMatrix(2, 2, "EA"); if(!pBMOpt->m_structEstablishTBM.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY); } m_EstablishTBM.SetCheck(pBMOpt->m_structEstablishTBM.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 스티로폼 void CDeckBMOptionDlg::OnCheckStyrofoam() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_STYROFOAM; m_nCols = 3; m_nRows = 4; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 100); m_Grid.SetColumnWidth(1, 140); m_Grid.SetColumnWidth(2, 70); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetCellType(3, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 2); m_Grid.SetMergeCol(1, 1, 2); m_Grid.SetMergeCol(2, 1, 2); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(2, 0, "위 치"); m_Grid.SetTextMatrix(3, 0, "두 께"); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structStyrofoam.m_bApply)); if(pBMOpt->m_structStyrofoam.m_bLeft) m_Grid.SetTextMatrix(2, 1, "좌측적용"); else m_Grid.SetTextMatrix(2, 1, "우측적용"); m_Grid.SetTextMatrix(3, 1, "%.0f", pBMOpt->m_structStyrofoam.m_dThick); m_Grid.SetTextMatrix(3, 2, "mm"); if(!pBMOpt->m_structStyrofoam.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 2, RGBREADONLY); } m_Styrofoam.SetCheck(pBMOpt->m_structStyrofoam.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 신축이음 void CDeckBMOptionDlg::OnCheckExpansionjoint() { CADeckData *pADeckData = m_pStd->m_pDeckData; CPlateBridgeApp *pDB = m_pStd->GetBridge(); CBMOption *pBMOpt = &pADeckData->m_BMOption; BOOL bWalkRoad = FALSE; for(long nHDan=0; nHDan<pDB->GetQtyHDanNode(); nHDan++) { if(pDB->GetValueTypeHDan(nHDan, 1)==3) bWalkRoad = TRUE; } m_nSelectedOpt = BMOPT_EXPANSIONJOINT; m_nCols = 4; m_nRows = 12; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 100); m_Grid.SetColumnWidth(1, 85); m_Grid.SetColumnWidth(2, 85); m_Grid.SetColumnWidth(3, 85); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetMergeCol(2, 1, 3); m_Grid.SetMergeCol(3, 1, 3); m_Grid.SetMergeRow(4, 6, 0); m_Grid.SetMergeRow(7, 9, 0); m_Grid.SetMergeCol(4, 1, 3); m_Grid.SetMergeCol(7, 1, 3); m_Grid.SetMergeCol(10, 1, 2); m_Grid.SetMergeCol(11, 1, 2); m_Grid.SetCellType(1, 1, CT_COMBO); // m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetCellType(3, 1, CT_COMBO); m_Grid.SetCellType(5, 1, CT_COMBO); m_Grid.SetCellType(6, 1, CT_COMBO); m_Grid.SetCellType(8, 1, CT_COMBO); m_Grid.SetCellType(9, 1, CT_COMBO); m_Grid.SetTextMatrix(2, 0, "수량기준"); m_Grid.SetTextMatrix(3, 0, "보도구간포함"); m_Grid.SetTextMatrix(4, 0, "시점"); m_Grid.SetTextMatrix(7, 0, "종점"); m_Grid.SetTextMatrix(10, 0, "여유치수"); m_Grid.SetTextMatrix(11, 0, "여유치수개수"); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structExpansionJoint.m_bApply)); if(pBMOpt->m_structExpansionJoint.m_bUnitLength) m_Grid.SetTextMatrix(2, 1, "단위 m당 수량"); else m_Grid.SetTextMatrix(2, 1, "지점별 수량"); if(!bWalkRoad) { pBMOpt->m_structExpansionJoint.m_bIncludeWalkLoad = FALSE; m_Grid.SetRowHeight(3, 0); } m_Grid.SetTextMatrix(3, 1, IsApply(pBMOpt->m_structExpansionJoint.m_bIncludeWalkLoad)); m_Grid.SetTextMatrix(4, 1, pBMOpt->m_structExpansionJoint.m_szSttName); m_Grid.SetTextMatrix(5, 1, pBMOpt->GetRebarDia(pBMOpt->m_structExpansionJoint.m_nSttDiaIdx[0], toKgPCm2(pADeckData->m_SigmaY))); if(pBMOpt->m_structExpansionJoint.m_bUnitLength) { m_Grid.SetTextMatrix(5, 2, "%.3f", pBMOpt->m_structExpansionJoint.m_dSttWeight[0]); m_Grid.SetTextMatrix(5, 3, "Kgf/m"); } else { m_Grid.SetTextMatrix(5, 2, "%.3f", toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[0])); m_Grid.SetTextMatrix(5, 3, "tonf"); } m_Grid.SetTextMatrix(6, 1, pBMOpt->GetRebarDia(pBMOpt->m_structExpansionJoint.m_nSttDiaIdx[1], toKgPCm2(pADeckData->m_SigmaY))); if(pBMOpt->m_structExpansionJoint.m_bUnitLength) { m_Grid.SetTextMatrix(6, 2, "%.3f", pBMOpt->m_structExpansionJoint.m_dSttWeight[1]); m_Grid.SetTextMatrix(6, 3, "Kgf/m"); } else { m_Grid.SetTextMatrix(6, 2, "%.3f", toTon(pBMOpt->m_structExpansionJoint.m_dSttWeight[1])); m_Grid.SetTextMatrix(6, 3, "tonf"); } m_Grid.SetTextMatrix(7, 1, pBMOpt->m_structExpansionJoint.m_szEndName); m_Grid.SetTextMatrix(8, 1, pBMOpt->GetRebarDia(pBMOpt->m_structExpansionJoint.m_nEndDiaIdx[0], toKgPCm2(pADeckData->m_SigmaY))); if(pBMOpt->m_structExpansionJoint.m_bUnitLength) { m_Grid.SetTextMatrix(8, 2, "%.3f", pBMOpt->m_structExpansionJoint.m_dEndWeight[0]); m_Grid.SetTextMatrix(8, 3, "Kgf/m"); } else { m_Grid.SetTextMatrix(8, 2, "%.3f", toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[0])); m_Grid.SetTextMatrix(8, 3, "tonf"); } m_Grid.SetTextMatrix(9, 1, pBMOpt->GetRebarDia(pBMOpt->m_structExpansionJoint.m_nEndDiaIdx[1], toKgPCm2(pADeckData->m_SigmaY))); if(pBMOpt->m_structExpansionJoint.m_bUnitLength) { m_Grid.SetTextMatrix(9, 2, "%.3f", pBMOpt->m_structExpansionJoint.m_dEndWeight[1]); m_Grid.SetTextMatrix(9, 3, "Kgf/m"); } else { m_Grid.SetTextMatrix(9, 2, "%.3f", toTon(pBMOpt->m_structExpansionJoint.m_dEndWeight[1])); m_Grid.SetTextMatrix(9, 3, "tonf"); } m_Grid.SetTextMatrix(10, 1, "%.0f", pBMOpt->m_structExpansionJoint.m_dMargin); m_Grid.SetTextMatrix(10, 3, "mm"); CString sText; sText.Format("%d", pBMOpt->m_structExpansionJoint.m_nMarginsu); m_Grid.SetTextMatrix(11, 1, sText); m_Grid.SetTextMatrix(11, 3, "EA"); if(!pBMOpt->m_structExpansionJoint.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(4, 1, RGBREADONLY); m_Grid.SetItemState(5, 1, m_Grid.GetItemState(5, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(5, 1, RGBREADONLY); m_Grid.SetItemState(5, 2, m_Grid.GetItemState(5, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(5, 2, RGBREADONLY); m_Grid.SetItemState(6, 1, m_Grid.GetItemState(6, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(6, 1, RGBREADONLY); m_Grid.SetItemState(6, 2, m_Grid.GetItemState(6, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(6, 2, RGBREADONLY); m_Grid.SetItemState(7, 1, m_Grid.GetItemState(7, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(7, 1, RGBREADONLY); m_Grid.SetItemState(8, 1, m_Grid.GetItemState(8, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(8, 1, RGBREADONLY); m_Grid.SetItemState(8, 2, m_Grid.GetItemState(8, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(8, 2, RGBREADONLY); m_Grid.SetItemState(9, 1, m_Grid.GetItemState(9, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(9, 1, RGBREADONLY); m_Grid.SetItemState(9, 2, m_Grid.GetItemState(9, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(9, 2, RGBREADONLY); m_Grid.SetItemState(5, 3, m_Grid.GetItemState(5, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(5, 3, RGBREADONLY); m_Grid.SetItemState(6, 3, m_Grid.GetItemState(6, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(6, 3, RGBREADONLY); m_Grid.SetItemState(8, 3, m_Grid.GetItemState(8, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(8, 3, RGBREADONLY); m_Grid.SetItemState(9, 3, m_Grid.GetItemState(9, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(9, 3, RGBREADONLY); m_Grid.SetItemState(10, 1, m_Grid.GetItemState(10, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(10, 1, RGBREADONLY); m_Grid.SetItemState(10, 3, m_Grid.GetItemState(10, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(10, 3, RGBREADONLY); m_Grid.SetItemState(11, 1, m_Grid.GetItemState(11, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(11, 1, RGBREADONLY); m_Grid.SetItemState(11, 3, m_Grid.GetItemState(11, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(11, 3, RGBREADONLY); } m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_ExpansionJoint.SetCheck(pBMOpt->m_structExpansionJoint.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 신축이음 덮개 void CDeckBMOptionDlg::OnCheckExpansionjointCover() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CString sText = _T(""); m_nSelectedOpt = BMOPT_EXPANSIONJOINT_COVER; m_nCols = 5; m_nRows = 9; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 90); m_Grid.SetColumnWidth(1, 80); m_Grid.SetColumnWidth(2, 80); m_Grid.SetColumnWidth(3, 50); m_Grid.SetColumnWidth(4, 50); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 4); m_Grid.SetMergeCol(1, 1, 4); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structExpansionJointCover.m_bApply)); m_Grid.SetTextMatrix(2, 0, pBMOpt->GetExpansionJointCoverPos(GENERAL_GUARDFENCE)); m_Grid.SetTextMatrix(3, 0, pBMOpt->GetExpansionJointCoverPos(ABSOLUTE_GUARDFENCE)); m_Grid.SetTextMatrix(4, 0, pBMOpt->GetExpansionJointCoverPos(GENERAL_SOUNDPROOF)); m_Grid.SetTextMatrix(5, 0, pBMOpt->GetExpansionJointCoverPos(ABSOLUTE_SOUNDPROOF)); m_Grid.SetTextMatrix(6, 0, pBMOpt->GetExpansionJointCoverPos(CENTER_GUARDFENCE)); m_Grid.SetTextMatrix(7, 0, pBMOpt->GetExpansionJointCoverPos(PARAPET)); m_Grid.SetTextMatrix(8, 0, pBMOpt->GetExpansionJointCoverPos(CURB)); for(long nRow = 2; nRow < 9; nRow++) { m_Grid.SetTextMatrix(nRow, 1, "%.3f", toM(pBMOpt->m_structExpansionJointCover.m_dHeight[nRow-2])); m_Grid.SetTextMatrix(nRow, 2, "m"); sText.Format("%d", pBMOpt->m_structExpansionJointCover.m_nQty[nRow-2]); m_Grid.SetTextMatrix(nRow, 3, sText); m_Grid.SetTextMatrix(nRow, 4, "EA"); } if(!pBMOpt->m_structExpansionJointCover.m_bApply) { for(long nRow = 2; nRow < 9; nRow++) { for(long nCol = 1; nCol < 5; nCol++) { m_Grid.SetItemState(nRow, nCol, m_Grid.GetItemState(nRow, nCol) | GVIS_READONLY); m_Grid.SetItemBkColour(nRow, nCol, RGBREADONLY); } } } m_ExpansionJointCover.SetCheck(pBMOpt->m_structExpansionJointCover.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 무수축 콘크리트 void CDeckBMOptionDlg::OnCheckShrinkageConcrete() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CGlobarOption *pGlopt = m_pStd->m_pDataManage->GetGlobalOption(); CString sText = _T(""); double dExpJointSttHeight = pGlopt->GetSttExpansionJointHeight(); double dExpJointSttWidth = pGlopt->GetSttExpansionJointWidth(); double dExpJointEndHeight = pGlopt->GetEndExpansionJointHeight(); double dExpJointEndWidth = pGlopt->GetEndExpansionJointWidth(); m_nSelectedOpt = BMOPT_SHRINKAGE_CONCRETE; m_nCols = 4; m_nRows = 4; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 100); m_Grid.SetColumnWidth(2, 80); m_Grid.SetColumnWidth(3, 80); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetTextMatrix(2, 0, "시점적용 갯수"); m_Grid.SetTextMatrix(3, 0, "종점적용 갯수"); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structShrinkageConcrete.m_bApply)); sText.Format("%.0f × %.0f", dExpJointSttWidth, dExpJointSttHeight); m_Grid.SetTextMatrix(2, 1, sText); sText.Format("%d", pBMOpt->m_structShrinkageConcrete.m_nSttQty); m_Grid.SetTextMatrix(2, 2, sText); m_Grid.SetTextMatrix(2, 3, "EA"); sText.Format("%.0f × %.0f", dExpJointEndWidth, dExpJointEndHeight); m_Grid.SetTextMatrix(3, 1, sText); sText.Format("%d", pBMOpt->m_structShrinkageConcrete.m_nSttQty); m_Grid.SetTextMatrix(3, 2, sText); m_Grid.SetTextMatrix(3, 3, "EA"); if(!pBMOpt->m_structShrinkageConcrete.m_bApply) { } m_ShrinkageConcrete.SetCheck(pBMOpt->m_structShrinkageConcrete.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 교면 물빼기 void CDeckBMOptionDlg::OnCheckWaterDraw() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_WATER_DRAW; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bWaterDraw)); m_WaterDraw.SetCheck(pBMOpt->m_bWaterDraw); m_Grid.SetRedraw(TRUE,TRUE); } // NOTCH void CDeckBMOptionDlg::OnCheckNotch() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_NOTCH; m_nCols = 2; m_nRows = 4; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetMergeRow(1, 2, 0); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structNotch.m_bApply)); m_Grid.SetTextMatrix(2, 1, pBMOpt->GetNotchPos(pBMOpt->m_structNotch.m_nApplyPos)); m_Grid.SetTextMatrix(3, 0, "NOTCH 종류"); m_Grid.SetTextMatrix(3, 1, pBMOpt->m_structNotch.m_szNotchType); if(!pBMOpt->m_structNotch.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); } m_Notch.SetCheck(pBMOpt->m_structNotch.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 가드펜스 void CDeckBMOptionDlg::OnCheckGuardFence() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_GUARD_FENCE; m_nCols = 4; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 70); m_Grid.SetColumnWidth(2, 70); m_Grid.SetColumnWidth(3, 70); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(0, 2, "높이"); m_Grid.SetTextMatrix(0, 3, "단위"); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structGuardFence.m_bApply)); m_Grid.SetTextMatrix(1, 2, "%.1f", toM(pBMOpt->m_structGuardFence.m_dHeight)); m_Grid.SetTextMatrix(1, 3, "m"); if(!pBMOpt->m_structGuardFence.m_bApply) { m_Grid.SetItemState(1, 2, m_Grid.GetItemState(1, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 2, RGBREADONLY); m_Grid.SetItemState(1, 3, m_Grid.GetItemState(1, 3) | GVIS_READONLY); m_Grid.SetItemBkColour(1, 3, RGBREADONLY); } m_GuardFence.SetCheck(pBMOpt->m_structGuardFence.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 방음판넬 void CDeckBMOptionDlg::OnCheckSoundProof() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CCalcData *pData = m_pStd->m_pDataManage->GetCalcData(); CCalcFloor CalcFloor(m_pStd->m_pDataManage); m_nSelectedOpt = BMOPT_SOUND_PROOF; m_nCols = 3; m_nRows = 4; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 180); m_Grid.SetColumnWidth(2, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structSoundProof.m_bApply)); m_Grid.SetMergeCol(0, 1, 2, TRUE); m_Grid.SetMergeCol(1, 1, 2, TRUE); long nGuardTypeL = CalcFloor.GetGuardWallType(FLOOR_LEFT); long nGuardTypeR = CalcFloor.GetGuardWallType(FLOOR_RIGHT); BOOL bBangEmExistL = (pData->DESIGN_FLOOR_DATA[FLOOR_LEFT].m_bBangEm && nGuardTypeL<=8) ? TRUE : FALSE; BOOL bBangEmExistR = (pData->DESIGN_FLOOR_DATA[FLOOR_RIGHT].m_bBangEm && nGuardTypeR<=8) ? TRUE : FALSE; if(bBangEmExistL) { m_Grid.SetTextMatrix(2, 0, "높이(좌)"); m_Grid.SetTextMatrix(2, 1, "%.3f", toM(pBMOpt->m_structSoundProof.m_dLHeight)); m_Grid.SetTextMatrix(2, 2, "m"); if(!pBMOpt->m_structSoundProof.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 2, RGBREADONLY); } } else m_Grid.SetRowHeight(2, 0); if(bBangEmExistR) { m_Grid.SetTextMatrix(3, 0, "높이(우)"); m_Grid.SetTextMatrix(3, 1, "%.3f", toM(pBMOpt->m_structSoundProof.m_dRHeight)); m_Grid.SetTextMatrix(3, 2, "m"); if(!pBMOpt->m_structSoundProof.m_bApply) { m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 2, RGBREADONLY); } } else m_Grid.SetRowHeight(3, 0); m_SoundProof.SetCheck(pBMOpt->m_structSoundProof.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 난간 void CDeckBMOptionDlg::OnCheckParapet() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; CCalcData *pData = m_pStd->m_pDataManage->GetCalcData(); CCalcFloor CalcFloor(m_pStd->m_pDataManage); CString sText = _T(""); m_nSelectedOpt = BMOPT_PARAPET; m_nCols = 4; m_nRows = 6; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 100); m_Grid.SetColumnWidth(1, 120); m_Grid.SetColumnWidth(2, 120); m_Grid.SetColumnWidth(3, 70); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetMergeRow(2, 3, 0); m_Grid.SetMergeRow(4, 5, 0); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structParapet.m_bApply)); m_Grid.SetTextMatrix(2, 0, "방호벽용"); m_Grid.SetTextMatrix(2, 1, "좌측길이"); m_Grid.SetTextMatrix(3, 1, "우측길이"); m_Grid.SetTextMatrix(4, 0, "연석용"); m_Grid.SetTextMatrix(4, 1, "난간길이"); m_Grid.SetTextMatrix(5, 1, "적용갯수"); m_Grid.SetTextMatrix(2, 2, "%.3f", toM(pBMOpt->m_structParapet.m_dGuardLength[0])); m_Grid.SetTextMatrix(2, 3, "m"); m_Grid.SetTextMatrix(3, 2, "%.3f", toM(pBMOpt->m_structParapet.m_dGuardLength[1])); m_Grid.SetTextMatrix(3, 3, "m"); m_Grid.SetTextMatrix(4, 2, "%.3f", toM(pBMOpt->m_structParapet.m_dCurbLength)); m_Grid.SetTextMatrix(4, 3, "m"); sText.Format("%d", pBMOpt->m_structParapet.m_nCurbQty); m_Grid.SetTextMatrix(5, 2, sText); m_Grid.SetTextMatrix(5, 3, "EA"); long nGuardTypeL = CalcFloor.GetGuardWallType(FLOOR_LEFT); long nGuardTypeR = CalcFloor.GetGuardWallType(FLOOR_RIGHT); if(!pBMOpt->m_structParapet.m_bApply) { for(long nRow = 2; nRow < 6; nRow++) { for(long nCol = 1; nCol < 4; nCol++) { m_Grid.SetItemState(nRow, nCol, m_Grid.GetItemState(nRow, nCol) | GVIS_READONLY); m_Grid.SetItemBkColour(nRow, nCol, RGBREADONLY); } } } m_Parapet.SetCheck(pBMOpt->m_structParapet.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 차광망 void CDeckBMOptionDlg::OnCheckShade() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_SHADE; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bShade)); m_Shade.SetCheck(pBMOpt->m_bShade); m_Grid.SetRedraw(TRUE,TRUE); } // 낙하물 방지공 void CDeckBMOptionDlg::OnCheckDroppingPrevent() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_DROPPING_PREVENT; m_nCols = 3; m_nRows = 5; if(pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal) m_nRows = 4; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 180); m_Grid.SetColumnWidth(2, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 2); m_Grid.SetMergeCol(1, 1, 2); m_Grid.SetMergeCol(2, 1, 2); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structDroppingPrevent.m_bApply)); m_Grid.SetTextMatrix(2, 0, "적용 방향"); m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDroppingPrevent(pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal)); m_Grid.SetTextMatrix(3, 0, "수평 여유폭"); m_Grid.SetTextMatrix(3, 1, "%.3f", toM(pBMOpt->m_structDroppingPrevent.m_dHorSpaceHeight)); m_Grid.SetTextMatrix(3, 2, "m"); if(!pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal) { m_Grid.SetTextMatrix(4, 0, "수직 여유폭"); m_Grid.SetTextMatrix(4, 1, "%.3f", toM(pBMOpt->m_structDroppingPrevent.m_dVerSpaceHeight)); m_Grid.SetTextMatrix(4, 2, "m"); } if(!pBMOpt->m_structDroppingPrevent.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(3, 2, RGBREADONLY); if(!pBMOpt->m_structDroppingPrevent.m_bIsOnlyHorizontal) { m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY); m_Grid.SetItemBkColour(4, 1, RGBREADONLY); m_Grid.SetItemState(4, 2, m_Grid.GetItemState(4, 2) | GVIS_READONLY); m_Grid.SetItemBkColour(4, 2, RGBREADONLY); } } m_DroppingPreVent.SetCheck(pBMOpt->m_structDroppingPrevent.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 강재수량 void CDeckBMOptionDlg::OnCheckSteelQuantity() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_STEEL_QUANTITY; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bSteelQuantity)); m_SteelQuantity.SetCheck(pBMOpt->m_bSteelQuantity); m_Grid.SetRedraw(TRUE,TRUE); } // 강교도장 void CDeckBMOptionDlg::OnCheckPaint() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_PAINT; m_nCols = 2; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 235); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bPaint)); m_Paint.SetCheck(pBMOpt->m_bPaint); m_Grid.SetRedraw(TRUE,TRUE); } // 배수시설 void CDeckBMOptionDlg::OnCheckDrainEstablish() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_DRAIN_ESTABLISH; CString sText = _T(""); if(!pBMOpt->m_bDrainEstablish) { m_nCols = 4; m_nRows = 2; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 90); m_Grid.SetColumnWidth(1, 120); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish)); m_DrainEstablish.SetCheck(pBMOpt->m_bDrainEstablish); m_Grid.SetRedraw(TRUE,TRUE); return; } if(pBMOpt->m_nDrainEstablishType == RIVER) { m_nCols = 4; m_nRows = 5; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 90); m_Grid.SetColumnWidth(1, 110); m_Grid.SetColumnWidth(2, 90); m_Grid.SetColumnWidth(3, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetMergeCol(2, 1, 3); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish)); m_Grid.SetTextMatrix(2, 0, "타입 설정"); m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDrainEstablishType()); m_Grid.SetTextMatrix(3, 0, "집 수 구"); m_Grid.SetTextMatrix(3, 1, "스테인레스 Plate"); sText.Format("%d", pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect); m_Grid.SetTextMatrix(3, 2, sText); m_Grid.SetTextMatrix(3, 3, "EA"); m_Grid.SetTextMatrix(4, 0, "배 수 구"); m_Grid.SetTextMatrix(4, 1, "스테인레스 강관"); m_Grid.SetTextMatrix(4, 2, "%.3f", toM(pBMOpt->m_structRiverDrainEstablish.m_dDrain)); m_Grid.SetTextMatrix(4, 3, "m"); } else if(pBMOpt->m_nDrainEstablishType == WALKWAY) { if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0) { m_nCols = 4; m_nRows = 9; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 90); m_Grid.SetColumnWidth(1, 110); m_Grid.SetColumnWidth(2, 90); m_Grid.SetColumnWidth(3, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetCellType(3, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetMergeCol(2, 1, 3); m_Grid.SetMergeCol(3, 1, 3); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish)); m_Grid.SetTextMatrix(2, 0, "타입 설정"); m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDrainEstablishType()); m_Grid.SetTextMatrix(3, 0, "형 식"); if(pBMOpt->m_structWalkWayDrainEstablish.m_nType==0) sText.Format("TYPE 1 (건교부)"); else sText.Format("TYPE 2"); m_Grid.SetTextMatrix(3, 1, sText); m_Grid.SetTextMatrix(4, 0, "집 수 구"); m_Grid.SetTextMatrix(4, 1, "-"); m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect); m_Grid.SetTextMatrix(4, 2, sText); m_Grid.SetTextMatrix(4, 3, "EA"); m_Grid.SetTextMatrix(5, 0, "연결집수거"); m_Grid.SetTextMatrix(5, 1, "-"); m_Grid.SetItemState(5, 1, m_Grid.GetItemState(5, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect); m_Grid.SetTextMatrix(5, 2, sText); m_Grid.SetTextMatrix(5, 3, "EA"); m_Grid.SetTextMatrix(6, 0, "직 관"); m_Grid.SetTextMatrix(6, 1, "-"); m_Grid.SetItemState(6, 1, m_Grid.GetItemState(6, 1) | GVIS_READONLY); m_Grid.SetTextMatrix(6, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0])); m_Grid.SetTextMatrix(6, 3, "m"); m_Grid.SetTextMatrix(7, 0, "곡 관"); m_Grid.SetTextMatrix(7, 1, "-"); m_Grid.SetItemState(7, 1, m_Grid.GetItemState(7, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]); m_Grid.SetTextMatrix(7, 2, sText); m_Grid.SetTextMatrix(7, 3, "EA"); m_Grid.SetTextMatrix(8, 0, "연 결 부"); m_Grid.SetTextMatrix(8, 1, "-"); m_Grid.SetItemState(8, 1, m_Grid.GetItemState(8, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoint); m_Grid.SetTextMatrix(8, 2, sText); m_Grid.SetTextMatrix(8, 3, "EA"); } else if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 1) { m_nCols = 4; m_nRows = 16; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 90); m_Grid.SetColumnWidth(1, 110); m_Grid.SetColumnWidth(2, 90); m_Grid.SetColumnWidth(3, 60); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetCellType(3, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetMergeCol(2, 1, 3); m_Grid.SetMergeCol(3, 1, 3); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish)); m_Grid.SetTextMatrix(2, 0, "타입 설정"); m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDrainEstablishType()); m_Grid.SetTextMatrix(3, 0, "형 식"); if(pBMOpt->m_structWalkWayDrainEstablish.m_nType==0) sText.Format("TYPE 1 (건교부)"); else sText.Format("TYPE 2"); m_Grid.SetTextMatrix(3, 1, sText); m_Grid.SetTextMatrix(4, 0, "집 수 구"); m_Grid.SetTextMatrix(4, 1, "스테인레스 강관"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect); m_Grid.SetTextMatrix(4, 2, sText); m_Grid.SetTextMatrix(4, 3, "EA"); m_Grid.SetTextMatrix(5, 0, "배 수 구"); m_Grid.SetTextMatrix(5, 1, "스테인레스강관"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nDrain); m_Grid.SetTextMatrix(5, 2, sText); m_Grid.SetTextMatrix(5, 3, "EA"); m_Grid.SetTextMatrix(6, 0, "연결배수구"); m_Grid.SetTextMatrix(6, 1, "8""×10"""); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain); m_Grid.SetTextMatrix(6, 2, sText); m_Grid.SetTextMatrix(6, 3, "EA"); m_Grid.SetTextMatrix(7, 0, "직 관"); m_Grid.SetTextMatrix(7, 1, "150A"); m_Grid.SetTextMatrix(7, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0])); m_Grid.SetTextMatrix(7, 3, "m"); m_Grid.SetTextMatrix(8, 0, "직 관"); m_Grid.SetTextMatrix(8, 1, "200A"); m_Grid.SetTextMatrix(8, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1])); m_Grid.SetTextMatrix(8, 3, "m"); m_Grid.SetTextMatrix(9, 0, "곡 관"); m_Grid.SetTextMatrix(9, 1, "150A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]); m_Grid.SetTextMatrix(9, 2, sText); m_Grid.SetTextMatrix(9, 3, "EA"); m_Grid.SetTextMatrix(10, 0, "곡 관"); m_Grid.SetTextMatrix(10, 1, "200A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1]); m_Grid.SetTextMatrix(10, 2, sText); m_Grid.SetTextMatrix(10, 3, "EA"); m_Grid.SetTextMatrix(11, 0, "청 소 구"); m_Grid.SetTextMatrix(11, 1, "150A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0]); m_Grid.SetTextMatrix(11, 2, sText); m_Grid.SetTextMatrix(11, 3, "EA"); m_Grid.SetTextMatrix(12, 0, "청 소 구"); m_Grid.SetTextMatrix(12, 1, "200A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1]); m_Grid.SetTextMatrix(12, 2, sText); m_Grid.SetTextMatrix(12, 3, "EA"); m_Grid.SetTextMatrix(13, 0, "상부고정대"); m_Grid.SetTextMatrix(13, 1, "150A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0]); m_Grid.SetTextMatrix(13, 2, sText); m_Grid.SetTextMatrix(13, 3, "EA"); m_Grid.SetTextMatrix(14, 0, "상부고정대"); m_Grid.SetTextMatrix(14, 1, "200A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1]); m_Grid.SetTextMatrix(14, 2, sText); m_Grid.SetTextMatrix(14, 3, "EA"); m_Grid.SetTextMatrix(15, 0, "침 전 조"); m_Grid.SetTextMatrix(15, 1, "-"); m_Grid.SetItemState(15, 1, m_Grid.GetItemState(15, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting); m_Grid.SetTextMatrix(15, 2, sText); m_Grid.SetTextMatrix(15, 3, "EA"); } else return; } else if(pBMOpt->m_nDrainEstablishType == RIVERWALKWAY) { if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0) { m_nCols = 4; m_nRows = 11; } else { m_nCols = 4; m_nRows = 18; } SetGridTitle(); m_Grid.SetColumnWidth(0, 90); m_Grid.SetColumnWidth(1, 110); m_Grid.SetColumnWidth(2, 90); m_Grid.SetColumnWidth(3, 60); m_Grid.SetRowHeightAll(20); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetCellType(3, 1, CT_COMBO); m_Grid.SetMergeCol(0, 1, m_nCols-1); m_Grid.SetMergeCol(1, 1, m_nCols-1); m_Grid.SetMergeCol(2, 1, m_nCols-1); m_Grid.SetMergeCol(3, 1, m_nCols-1); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_bDrainEstablish)); m_Grid.SetTextMatrix(2, 0, "타입 설정"); m_Grid.SetTextMatrix(2, 1, pBMOpt->GetDrainEstablishType()); if(pBMOpt->m_structWalkWayDrainEstablish.m_nType==0) sText.Format("TYPE 1 (건교부)"); else sText.Format("TYPE 2"); m_Grid.SetTextMatrix(3, 1, sText); m_Grid.SetTextMatrix(4, 0, "집 수 구"); m_Grid.SetTextMatrix(4, 1, "스테인레스 Plate"); sText.Format("%d", pBMOpt->m_structRiverDrainEstablish.m_nWaterCollect); m_Grid.SetTextMatrix(4, 2, sText); m_Grid.SetTextMatrix(4, 3, "EA"); m_Grid.SetTextMatrix(5, 0, "배 수 구"); m_Grid.SetTextMatrix(5, 1, "스테인레스 강관"); m_Grid.SetTextMatrix(5, 2, "%.3f", toM(pBMOpt->m_structRiverDrainEstablish.m_dDrain)); m_Grid.SetTextMatrix(5, 3, "m"); if(pBMOpt->m_structWalkWayDrainEstablish.m_nType == 0) { m_Grid.SetTextMatrix(6, 0, "집 수 구"); m_Grid.SetTextMatrix(6, 1, "-"); m_Grid.SetItemState(6, 1, m_Grid.GetItemState(6, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect); m_Grid.SetTextMatrix(6, 2, sText); m_Grid.SetTextMatrix(6, 3, "EA"); m_Grid.SetTextMatrix(7, 0, "연결집수거"); m_Grid.SetTextMatrix(7, 1, "-"); m_Grid.SetItemState(7, 1, m_Grid.GetItemState(7, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinWaterCollect); m_Grid.SetTextMatrix(7, 2, sText); m_Grid.SetTextMatrix(7, 3, "EA"); m_Grid.SetTextMatrix(8, 0, "직 관"); m_Grid.SetTextMatrix(8, 1, "-"); m_Grid.SetItemState(8, 1, m_Grid.GetItemState(8, 1) | GVIS_READONLY); m_Grid.SetTextMatrix(8, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0])); m_Grid.SetTextMatrix(8, 3, "m"); m_Grid.SetTextMatrix(9, 0, "곡 관"); m_Grid.SetTextMatrix(9, 1, "-"); m_Grid.SetItemState(9, 1, m_Grid.GetItemState(9, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]); m_Grid.SetTextMatrix(9, 2, sText); m_Grid.SetTextMatrix(9, 3, "EA"); m_Grid.SetTextMatrix(10, 0, "연 결 부"); m_Grid.SetTextMatrix(10, 1, "-"); m_Grid.SetItemState(10, 1, m_Grid.GetItemState(10, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoint); m_Grid.SetTextMatrix(10, 2, sText); m_Grid.SetTextMatrix(10, 3, "EA"); } else { m_Grid.SetTextMatrix(6, 0, "집 수 구"); m_Grid.SetTextMatrix(6, 1, "스테인레스 강관"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nWaterCollect); m_Grid.SetTextMatrix(6, 2, sText); m_Grid.SetTextMatrix(6, 3, "EA"); m_Grid.SetTextMatrix(7, 0, "배 수 구"); m_Grid.SetTextMatrix(7, 1, "스테인레스강관"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nDrain); m_Grid.SetTextMatrix(7, 2, sText); m_Grid.SetTextMatrix(7, 3, "EA"); m_Grid.SetTextMatrix(8, 0, "연결배수구"); m_Grid.SetTextMatrix(8, 1, "8""×10"""); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nJoinDrain); m_Grid.SetTextMatrix(8, 2, sText); m_Grid.SetTextMatrix(8, 3, "EA"); m_Grid.SetTextMatrix(9, 0, "직 관"); m_Grid.SetTextMatrix(9, 1, "150A"); m_Grid.SetTextMatrix(9, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[0])); m_Grid.SetTextMatrix(9, 3, "m"); m_Grid.SetTextMatrix(10, 0, "직 관"); m_Grid.SetTextMatrix(10, 1, "200A"); m_Grid.SetTextMatrix(10, 2, "%.3f", toM(pBMOpt->m_structWalkWayDrainEstablish.m_dStraightTube[1])); m_Grid.SetTextMatrix(10, 3, "m"); m_Grid.SetTextMatrix(11, 0, "곡 관"); m_Grid.SetTextMatrix(11, 1, "150A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[0]); m_Grid.SetTextMatrix(11, 2, sText); m_Grid.SetTextMatrix(11, 3, "EA"); m_Grid.SetTextMatrix(12, 0, "곡 관"); m_Grid.SetTextMatrix(12, 1, "200A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCurveTube[1]); m_Grid.SetTextMatrix(12, 2, sText); m_Grid.SetTextMatrix(12, 3, "EA"); m_Grid.SetTextMatrix(13, 0, "청 소 구"); m_Grid.SetTextMatrix(13, 1, "150A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[0]); m_Grid.SetTextMatrix(13, 2, sText); m_Grid.SetTextMatrix(13, 3, "EA"); m_Grid.SetTextMatrix(14, 0, "청 소 구"); m_Grid.SetTextMatrix(14, 1, "200A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCleanTube[1]); m_Grid.SetTextMatrix(14, 2, sText); m_Grid.SetTextMatrix(14, 3, "EA"); m_Grid.SetTextMatrix(15, 0, "상부고정대"); m_Grid.SetTextMatrix(15, 1, "150A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[0]); m_Grid.SetTextMatrix(15, 2, sText); m_Grid.SetTextMatrix(15, 3, "EA"); m_Grid.SetTextMatrix(16, 0, "상부고정대"); m_Grid.SetTextMatrix(16, 1, "200A"); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nUpperFixed[1]); m_Grid.SetTextMatrix(16, 2, sText); m_Grid.SetTextMatrix(16, 3, "EA"); m_Grid.SetTextMatrix(17, 0, "침 전 조"); m_Grid.SetTextMatrix(17, 1, "-"); m_Grid.SetItemState(17, 1, m_Grid.GetItemState(17, 1) | GVIS_READONLY); sText.Format("%d", pBMOpt->m_structWalkWayDrainEstablish.m_nCollecting); m_Grid.SetTextMatrix(17, 2, sText); m_Grid.SetTextMatrix(17, 3, "EA"); } long nRow = 0; for(nRow = 4; nRow < 6; nRow++) { for(long nCol = 1; nCol < m_nCols; nCol++) m_Grid.SetItemBkColour(nRow, nCol, RGB(255, 255, 200)); } for(nRow = 6; nRow < m_nRows; nRow++) { for(long nCol = 1; nCol < m_nCols; nCol++) m_Grid.SetItemBkColour(nRow, nCol, RGB(200, 255, 255)); } } else return; m_DrainEstablish.SetCheck(pBMOpt->m_bDrainEstablish); m_Grid.SetRedraw(TRUE,TRUE); } // 날개벽 void CDeckBMOptionDlg::OnCheckWingWall() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_WING_WALL; m_nCols = 4; m_nRows = 6; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 70); m_Grid.SetColumnWidth(2, 70); m_Grid.SetColumnWidth(3, 70); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(2, 0, "좌측"); m_Grid.SetTextMatrix(2, 1, "시점"); m_Grid.SetTextMatrix(3, 1, "종점"); m_Grid.SetTextMatrix(4, 0, "우측"); m_Grid.SetTextMatrix(4, 1, "시점"); m_Grid.SetTextMatrix(5, 1, "종점"); m_Grid.SetMergeRow(2, 3, 0); m_Grid.SetMergeRow(4, 5, 0); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structWingWall.m_bApply)); m_Grid.SetTextMatrix(2, 2, "%.1f", toM(pBMOpt->m_structWingWall.m_dLengthLeftStt)); m_Grid.SetTextMatrix(2, 3, "m"); m_Grid.SetTextMatrix(3, 2, "%.1f", toM(pBMOpt->m_structWingWall.m_dLengthLeftEnd)); m_Grid.SetTextMatrix(3, 3, "m"); m_Grid.SetTextMatrix(4, 2, "%.1f", toM(pBMOpt->m_structWingWall.m_dLengthRighStt)); m_Grid.SetTextMatrix(4, 3, "m"); m_Grid.SetTextMatrix(5, 2, "%.1f", toM(pBMOpt->m_structWingWall.m_dLengthRighEnd)); m_Grid.SetTextMatrix(5, 3, "m"); if(!pBMOpt->m_structWingWall.m_bApply) { m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemBkColour(4, 1, RGBREADONLY); m_Grid.SetItemBkColour(5, 1, RGBREADONLY); m_Grid.SetItemBkColour(2, 3, RGBREADONLY); m_Grid.SetItemBkColour(3, 3, RGBREADONLY); m_Grid.SetItemBkColour(4, 3, RGBREADONLY); m_Grid.SetItemBkColour(5, 3, RGBREADONLY); m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(2, 2, RGBREADONLY); m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(3, 2, RGBREADONLY); m_Grid.SetItemState(4, 2, m_Grid.GetItemState(4, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(4, 2, RGBREADONLY); m_Grid.SetItemState(5, 2, m_Grid.GetItemState(5, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(5, 2, RGBREADONLY); } m_Grid.SetItemState(2, 1, m_Grid.GetItemState(1, 2) | GVIS_READONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(1, 3) | GVIS_READONLY); m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY); m_Grid.SetItemState(5, 1, m_Grid.GetItemState(5, 1) | GVIS_READONLY); m_Grid.SetItemState(2, 3, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemState(3, 3, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemState(4, 3, m_Grid.GetItemState(4, 1) | GVIS_READONLY); m_Grid.SetItemState(5, 3, m_Grid.GetItemState(5, 1) | GVIS_READONLY); m_GuardFence.SetCheck(pBMOpt->m_structWingWall.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } // 동바리 void CDeckBMOptionDlg::OnCheckTimber() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_TIMBER; m_nCols = 3; m_nRows = 5; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 140); m_Grid.SetColumnWidth(2, 80); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetCellType(2, 1, CT_COMBO); m_Grid.SetCellType(3, 1, CT_COMBO); m_Grid.SetTextMatrix(1, 0, "동바리종류"); m_Grid.SetTextMatrix(2, 0, "동바리재질"); m_Grid.SetTextMatrix(3, 0, "데크피니셔 위치"); m_Grid.SetTextMatrix(4, 0, "데크피니셔 작업폭"); m_Grid.SetMergeCol(0, 1, 2); m_Grid.SetMergeCol(1, 1, 2); m_Grid.SetMergeCol(2, 1, 2); m_Grid.SetMergeCol(3, 1, 2); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structTimber.m_bApply)); m_Grid.SetTextMatrix(2, 1, pBMOpt->GetTimberQuality(pBMOpt->m_structTimber.m_nQuality)); m_Grid.SetTextMatrix(3, 1, pBMOpt->GetPosDeckFinisher(pBMOpt->m_structTimber.m_nPosDeckFinisher)); m_Grid.SetTextMatrix(4, 1, "%.3f", toM(pBMOpt->m_structTimber.m_dDeckFinisherWorkWidth)); m_Grid.SetTextMatrix(4, 2, "m"); if(!pBMOpt->m_structTimber.m_bApply) { m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY);m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY);m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY);m_Grid.SetItemBkColour(4, 1, RGBREADONLY); m_Grid.SetItemBkColour(4, 2, RGBREADONLY); } m_Grid.SetItemState(4, 2, m_Grid.GetItemState(4, 2) | GVIS_READONLY); m_GuardFence.SetCheck(pBMOpt->m_structTimber.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } void CDeckBMOptionDlg::OnButtonAllCheck() { SetOptionAll(TRUE); OnGridRedraw(); SetDataInit(); } void CDeckBMOptionDlg::OnButtonAllCancel() { SetOptionAll(FALSE); OnGridRedraw(); SetDataInit(); } void CDeckBMOptionDlg::SetOptionAll(BOOL bApply) { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; pBMOpt->m_bConcreteBuy = bApply; pBMOpt->m_bConcretePlacing = bApply; pBMOpt->m_bMold = bApply; pBMOpt->m_bSpacer = bApply; pBMOpt->m_structRebarManufacture.m_bApply = bApply; pBMOpt->m_structPave.m_bApply = bApply; pBMOpt->m_structTackCoating.m_bApply = bApply; pBMOpt->m_bDrainBridgeSurface = bApply; pBMOpt->m_structBridgeName.m_bApply = bApply; pBMOpt->m_structBridgeNamePlate.m_bApply = bApply; pBMOpt->m_structExplainPlate.m_bApply = bApply; pBMOpt->m_structEstablishTBM.m_bApply = bApply; pBMOpt->m_structStyrofoam.m_bApply = bApply; pBMOpt->m_structExpansionJoint.m_bApply = bApply; pBMOpt->m_structExpansionJointCover.m_bApply = bApply; pBMOpt->m_structShrinkageConcrete.m_bApply = bApply; pBMOpt->m_bWaterDraw = bApply; pBMOpt->m_structNotch.m_bApply = bApply; pBMOpt->m_structGuardFence.m_bApply = bApply; pBMOpt->m_structSoundProof.m_bApply = bApply; pBMOpt->m_structParapet.m_bApply = bApply; pBMOpt->m_bShade = bApply; pBMOpt->m_structDroppingPrevent.m_bApply = bApply; pBMOpt->m_bSteelQuantity = bApply; pBMOpt->m_bPaint = bApply; pBMOpt->m_bDrainEstablish = bApply; pBMOpt->m_structWingWall.m_bApply = bApply; pBMOpt->m_structTimber.m_bApply = bApply; pBMOpt->m_structElecWireHole.m_bApply = bApply; } LRESULT CDeckBMOptionDlg::OnReceive(WPARAM wp,LPARAM lp) { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; switch(wp) { case IDC_CHECK_CONCRETE_BUY : pBMOpt->m_bConcreteBuy = m_ConcreteBuy.GetCheck(); OnCheckConcreteBuy(); break; case IDC_CHECK_CONCRETE_PLACING : pBMOpt->m_bConcretePlacing = m_ConcretePlacing.GetCheck(); OnCheckConcretePlacing(); break; case IDC_CHECK_MOLD : pBMOpt->m_bMold = m_Mold.GetCheck(); OnCheckMold(); break; case IDC_CHECK_SPACER : pBMOpt->m_bSpacer= m_Spacer.GetCheck(); OnCheckSpacer(); break; case IDC_CHECK_REBAR_MANUFACTURE : pBMOpt->m_structRebarManufacture.m_bApply = m_RebarManufacture.GetCheck(); OnCheckRebarManufacture(); break; case IDC_CHECK_PAVE : pBMOpt->m_structPave.m_bApply = m_Pave.GetCheck(); OnCheckPave(); break; case IDC_CHECK_TACK_COATING : pBMOpt->m_structTackCoating.m_bApply = m_TackCoating.GetCheck(); OnCheckTackCoating(); break; case IDC_CHECK_DRAIN_BRIDGESURFACE : pBMOpt->m_bDrainBridgeSurface = m_DrainBridgeSurface.GetCheck(); OnCheckDrainBridgesurface(); break; case IDC_CHECK_BRIDGE_NAME : pBMOpt->m_structBridgeName.m_bApply = m_BridgeName.GetCheck(); OnCheckBridgeName(); break; case IDC_CHECK_BRIDGE_NAMEPLATE : pBMOpt->m_structBridgeNamePlate.m_bApply = m_BridgeNamePlate.GetCheck(); OnCheckBridgeNameplate(); break; case IDC_CHECK_EXPLAIN_PLATE : pBMOpt->m_structExplainPlate.m_bApply = m_ExplainPlate.GetCheck(); OnCheckExplainPlate(); break; case IDC_CHECK_ESTABLISH_TBM : pBMOpt->m_structEstablishTBM.m_bApply = m_EstablishTBM.GetCheck(); OnCheckEstablishTbm(); break; case IDC_CHECK_STYROFOAM : pBMOpt->m_structStyrofoam.m_bApply = m_Styrofoam.GetCheck(); OnCheckStyrofoam(); break; case IDC_CHECK_EXPANSIONJOINT : pBMOpt->m_structExpansionJoint.m_bApply = m_ExpansionJoint.GetCheck(); OnCheckExpansionjoint(); break; case IDC_CHECK_EXPANSIONJOINT_COVER : pBMOpt->m_structExpansionJointCover.m_bApply = m_ExpansionJointCover.GetCheck(); OnCheckExpansionjointCover(); break; case IDC_CHECK_SHRINKAGE_CONCRETE : pBMOpt->m_structShrinkageConcrete.m_bApply = m_ShrinkageConcrete.GetCheck(); OnCheckShrinkageConcrete(); break; case IDC_CHECK_WATER_DRAW : pBMOpt->m_bWaterDraw = m_WaterDraw.GetCheck(); OnCheckWaterDraw(); break; case IDC_CHECK_NOTCH : pBMOpt->m_structNotch.m_bApply = m_Notch.GetCheck(); OnCheckNotch(); break; case IDC_CHECK_GUARD_FENCE : pBMOpt->m_structGuardFence.m_bApply = m_GuardFence.GetCheck(); OnCheckGuardFence(); break; case IDC_CHECK_SOUND_PROOF : pBMOpt->m_structSoundProof.m_bApply = m_SoundProof.GetCheck(); OnCheckSoundProof(); break; case IDC_CHECK_PARAPET : pBMOpt->m_structParapet.m_bApply = m_Parapet.GetCheck(); OnCheckParapet(); break; case IDC_CHECK_SHADE : pBMOpt->m_bShade = m_Shade.GetCheck(); OnCheckShade(); break; case IDC_CHECK_DROPPING_PREVENT : pBMOpt->m_structDroppingPrevent.m_bApply = m_DroppingPreVent.GetCheck(); OnCheckDroppingPrevent(); break; case IDC_CHECK_STEEL_QUANTITY : pBMOpt->m_bSteelQuantity = m_SteelQuantity.GetCheck(); OnCheckSteelQuantity(); break; case IDC_CHECK_PAINT : pBMOpt->m_bPaint = m_Paint.GetCheck(); OnCheckPaint(); break; case IDC_CHECK_DRAIN_ESTABLISH : pBMOpt->m_bDrainEstablish = m_DrainEstablish.GetCheck(); OnCheckDrainEstablish(); break; case IDC_CHECK_WING_WALL : pBMOpt->m_structWingWall.m_bApply = m_WingWall.GetCheck(); OnCheckWingWall(); break; case IDC_CHECK_TIMBER : pBMOpt->m_structTimber.m_bApply = m_Timber.GetCheck(); OnCheckTimber(); case IDC_CHECK_ELECWIREHOLE : pBMOpt->m_structElecWireHole.m_bApply = m_ElecWireHole.GetCheck(); OnCheckElecWireHole(); } SetDataInit(); return 0; } BOOL CDeckBMOptionDlg::IsValid() { return m_pStd->m_bInclude_Module_Deck; } void CDeckBMOptionDlg::OnCheckElecWireHole() { CADeckData *pADeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pADeckData->m_BMOption; m_nSelectedOpt = BMOPT_ELECWIREHOLE; m_nCols = 4; m_nRows = 8; SetGridTitle(); m_Grid.SetRowHeightAll(20); m_Grid.SetColumnWidth(0, 140); m_Grid.SetColumnWidth(1, 70); m_Grid.SetColumnWidth(2, 70); m_Grid.SetColumnWidth(3, 70); m_Grid.SetCellType(1, 1, CT_COMBO); m_Grid.SetTextMatrix(2, 0, "φ100"); m_Grid.SetTextMatrix(2, 1, "좌측"); m_Grid.SetTextMatrix(3, 1, "우측"); m_Grid.SetTextMatrix(4, 0, "φ125"); m_Grid.SetTextMatrix(4, 1, "좌측"); m_Grid.SetTextMatrix(5, 1, "우측"); m_Grid.SetTextMatrix(6, 0, "φ150"); m_Grid.SetTextMatrix(6, 1, "좌측"); m_Grid.SetTextMatrix(7, 1, "우측"); m_Grid.SetMergeRow(2, 3, 0); m_Grid.SetMergeRow(4, 5, 0); m_Grid.SetMergeRow(6, 7, 0); m_Grid.SetMergeCol(0, 1, 3); m_Grid.SetMergeCol(1, 1, 3); m_Grid.SetTextMatrix(1, 0, pBMOpt->GetBMOptItem(m_nSelectedOpt)); m_Grid.SetTextMatrix(1, 1, IsApply(pBMOpt->m_structElecWireHole.m_bApply)); m_Grid.SetTextMatrix(2, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA100[0])); m_Grid.SetTextMatrix(2, 3, "EA"); m_Grid.SetTextMatrix(3, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA100[1])); m_Grid.SetTextMatrix(3, 3, "EA"); m_Grid.SetTextMatrix(4, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA125[0])); m_Grid.SetTextMatrix(4, 3, "EA"); m_Grid.SetTextMatrix(5, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA125[1])); m_Grid.SetTextMatrix(5, 3, "EA"); m_Grid.SetTextMatrix(6, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA150[0])); m_Grid.SetTextMatrix(6, 3, "EA"); m_Grid.SetTextMatrix(7, 2, "%.0f", (double)(pBMOpt->m_structElecWireHole.m_nEA150[1])); m_Grid.SetTextMatrix(7, 3, "EA"); if(!pBMOpt->m_structElecWireHole.m_bApply) { m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemBkColour(2, 1, RGBREADONLY); m_Grid.SetItemBkColour(3, 1, RGBREADONLY); m_Grid.SetItemBkColour(4, 1, RGBREADONLY); m_Grid.SetItemBkColour(5, 1, RGBREADONLY); m_Grid.SetItemBkColour(6, 1, RGBREADONLY); m_Grid.SetItemBkColour(7, 1, RGBREADONLY); m_Grid.SetItemBkColour(2, 3, RGBREADONLY); m_Grid.SetItemBkColour(3, 3, RGBREADONLY); m_Grid.SetItemBkColour(4, 3, RGBREADONLY); m_Grid.SetItemBkColour(5, 3, RGBREADONLY); m_Grid.SetItemBkColour(6, 3, RGBREADONLY); m_Grid.SetItemBkColour(7, 3, RGBREADONLY); m_Grid.SetItemState(2, 2, m_Grid.GetItemState(2, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(2, 2, RGBREADONLY); m_Grid.SetItemState(3, 2, m_Grid.GetItemState(3, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(3, 2, RGBREADONLY); m_Grid.SetItemState(4, 2, m_Grid.GetItemState(4, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(4, 2, RGBREADONLY); m_Grid.SetItemState(5, 2, m_Grid.GetItemState(5, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(5, 2, RGBREADONLY); m_Grid.SetItemState(6, 2, m_Grid.GetItemState(6, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(6, 2, RGBREADONLY); m_Grid.SetItemState(7, 2, m_Grid.GetItemState(7, 2) | GVIS_READONLY);m_Grid.SetItemBkColour(7, 2, RGBREADONLY); } m_Grid.SetItemState(2, 1, m_Grid.GetItemState(1, 2) | GVIS_READONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(1, 3) | GVIS_READONLY); m_Grid.SetItemState(2, 1, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemState(3, 1, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemState(4, 1, m_Grid.GetItemState(4, 1) | GVIS_READONLY); m_Grid.SetItemState(5, 1, m_Grid.GetItemState(5, 1) | GVIS_READONLY); m_Grid.SetItemState(6, 1, m_Grid.GetItemState(6, 1) | GVIS_READONLY); m_Grid.SetItemState(7, 1, m_Grid.GetItemState(7, 1) | GVIS_READONLY); m_Grid.SetItemState(2, 3, m_Grid.GetItemState(2, 1) | GVIS_READONLY); m_Grid.SetItemState(3, 3, m_Grid.GetItemState(3, 1) | GVIS_READONLY); m_Grid.SetItemState(4, 3, m_Grid.GetItemState(4, 1) | GVIS_READONLY); m_Grid.SetItemState(5, 3, m_Grid.GetItemState(5, 1) | GVIS_READONLY); m_Grid.SetItemState(6, 3, m_Grid.GetItemState(6, 1) | GVIS_READONLY); m_Grid.SetItemState(7, 3, m_Grid.GetItemState(7, 1) | GVIS_READONLY); m_ElecWireHole.SetCheck(pBMOpt->m_structElecWireHole.m_bApply); m_Grid.SetRedraw(TRUE,TRUE); } void CDeckBMOptionDlg::OnButtonOptionSave() { CADeckData *pDeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pDeckData->m_BMOption; CFileDialog dlg(FALSE, "*.abm",NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "ARoad 수량 옵션파일(*.abm)|*.abm||",NULL); dlg.m_ofn.lpstrTitle = "수량옵션 저장"; if(dlg.DoModal()==IDOK) { UpdateData(); CFile file; if(!file.Open(dlg.GetPathName(),CFile::modeWrite | CFile::modeCreate)) return; CArchive ar(&file,CArchive::store); pBMOpt->Serialize(ar); ar.Close(); file.Close(); } } void CDeckBMOptionDlg::OnButtonOptionLoad() { CADeckData *pDeckData = m_pStd->m_pDeckData; CBMOption *pBMOpt = &pDeckData->m_BMOption; CFileDialog dlg(TRUE, "*.abm",NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "APlate 수량 옵션파일(*.abm)|*.abm||",NULL); dlg.m_ofn.lpstrTitle = "수량옵션 불러오기"; if(dlg.DoModal()==IDOK) { CFile file; if(!file.Open(dlg.GetPathName(),CFile::modeRead)) return; CArchive ar(&file,CArchive::load); pBMOpt->Serialize(ar); ar.Close(); file.Close(); SetDataInit(); } }
[ "75705234+SamuelBacaner1112@users.noreply.github.com" ]
75705234+SamuelBacaner1112@users.noreply.github.com
df549bd23ed9cb01fe14515520c3e6bae78bf49c
f3a879985834f8528baf132eee8b8e0c4813b683
/src/RequestHandlerFactory.cpp
20df298937851a945600afcc8dda191bdb119aee
[ "Apache-2.0" ]
permissive
feniksa/tinyhttpd
c92a60971241ff810317d12401ed0110c3eaf4e6
ba90ddf8dd36eac2ac3f755c01f4e5458d5d533e
refs/heads/master
2021-04-29T00:00:39.479299
2020-03-27T13:23:15
2020-03-27T13:23:15
77,691,647
0
0
null
null
null
null
UTF-8
C++
false
false
2,872
cpp
#include "RequestHandlerFactory.h" #include <Poco/Net/HTTPRequestHandler.h> #include <Poco/Net/HTTPServerRequest.h> #include <Poco/Util/Application.h> #include <Poco/URI.h> #include "api/DirectoryHandler.h" #include "HandleStaticFile.h" #include "cpsp/DirectoryHandler.h" #include "HandleNotFound.h" #include <boost/filesystem.hpp> #include <boost/algorithm/string/predicate.hpp> RequestHandlerFactory::RequestHandlerFactory(const WebDirectories& webDirectories) : m_webDirectories(webDirectories) { } bool RequestHandlerFactory::processUrlSufix(const std::string& prefix, const std::string& path, std::string& sufix) { std::string::const_iterator prefi = prefix.begin(); std::string::const_iterator pathi = path.begin(); while (prefi != prefix.end() && pathi != path.end() && *prefi == *pathi) { ++prefi; ++pathi; } if (prefi != prefix.end()) return false; sufix.clear(); sufix.reserve(std::distance(pathi, path.end())); while (pathi != path.end()) { sufix += *pathi; ++pathi; } return true; } Poco::Net::HTTPRequestHandler *RequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &request) { Poco::Util::Application &app = Poco::Util::Application::instance(); app.logger().information("Request URI " + request.getURI()); //Poco::URI uri(request.getURI()); /*using callback_t = std::function<Poco::Net::HTTPRequestHandler*()>; using callmap_t = std::map<std::string, callback_t>;*/ //static callmap_t callmap { //std::make_pair("/api/dir", [&]() { return new api::DirectoryHandler(_docroot); }) //}; std::string path; std::string sufixPath; bool result; for (WebDirectories::const_iterator i = m_webDirectories.begin(); i != m_webDirectories.end(); ++i) { const WebDirectory& webDirectory = *i; Poco::URI uri(request.getURI()); result = processUrlSufix(webDirectory.m_alias, uri.getPath(), sufixPath); if (!result) continue; if (!webDirectory.m_alias.empty()) { path = webDirectory.m_path + boost::filesystem::path::preferred_separator + sufixPath; } else { path = sufixPath; } //const std::string path = request.getURI(); /*webDirectory.m_path + boost::filesystem::path::preferred_separator + request.getURI()*/; if (!boost::filesystem::exists(path)) continue; if (boost::filesystem::is_directory(path)) { if (webDirectory.m_showContent) return new DirectoryHandler(path); else return new HandleNotFound(); } else if (boost::filesystem::is_symlink(path)) { if (webDirectory.m_followSymLink) { return new HandleStaticFile(path); } else { return new HandleNotFound(); } } else if (boost::filesystem::is_regular_file(path)) { return new HandleStaticFile(path); } } /*callmap_t::const_iterator iter = callmap.find(uri.getPath()); if (iter != callmap.end()) { return iter->second(); }*/ return new HandleNotFound(); }
[ "msditanov@200volts.com" ]
msditanov@200volts.com
82627bb8ed682a284db14df4a533e5813953b1a6
1ee1f217f14aec3fe1bfe5fab6b9f11f78e2e937
/CHEDAN_Universe/database.h
0add48669a5171589ca1634bdd5f9d3fd855550c
[ "Apache-2.0" ]
permissive
Kwongrf/CHEDAN_Universe_v2
31ac72dc6c53a2540ed86d73ff50b411e4de035c
6d001ce08def738c4a145b4c4752e6b63298ed76
refs/heads/master
2022-07-08T02:54:00.872522
2020-05-12T04:55:57
2020-05-12T04:55:57
104,554,806
0
0
null
null
null
null
UTF-8
C++
false
false
2,722
h
<<<<<<< HEAD #ifndef DATABASE_H #define DATABASE_H #include "user.h" #include "question.h" #include "answer.h" #include "notification.h" #include <QTextCodec> #include <QSqlDatabase> #include <QSqlQuery> #include <QTime> #include <QSqlError> #include <QtDebug> #include <QSqlDriver> #include <QSqlRecord> class Database { public: bool createConnection(); //创建一个连接 bool createTable(); //创建4张数据库表 bool insert(User user); //插入数据 bool insert(Question ques); //出入数据 bool insert(Answer ans); //出入数据 bool insert(Notification notif); bool queryById(const int id,User& user); //查询用户信息 bool queryById(const int id,Question& ques); //查询问题信息 bool queryById(const int id,Answer& ans); //查询问题信息 vector<User> queryAllUser(); vector<Question> queryAllQues(); vector<Answer> queryAllAns(); vector<Answer> queryAllAns(vector<int> ids); vector<Notification> queryAllNotif(); bool update(User user); //更新 bool update(Question ques); //更新 bool update(Answer ans); //更新 //bool deleteById(int id); //删除 //bool sortById(); //排序 }; #endif // DATABASE_H ======= #ifndef DATABASE_H #define DATABASE_H #include "user.h" #include "question.h" #include "answer.h" #include "notification.h" #include <QTextCodec> #include <QSqlDatabase> #include <QSqlQuery> #include <QTime> #include <QSqlError> #include <QtDebug> #include <QSqlDriver> #include <QSqlRecord> class Database { public: bool createConnection(); //创建一个连接 bool createTable(); //创建4张数据库表 bool insert(User user); //插入数据 bool insert(Question ques); //出入数据 bool insert(Answer ans); //出入数据 bool insert(Notification notif); bool queryById(const int id,User& user); //查询用户信息 bool queryById(const int id,Question& ques); //查询问题信息 bool queryById(const int id,Answer& ans); //查询问题信息 vector<User> queryAllUser(); vector<Question> queryAllQues(); vector<Answer> queryAllAns(); vector<Answer> queryAllAns(vector<int> ids); vector<Notification> queryAllNotif(); bool update(User user); //更新 bool update(Question ques); //更新 bool update(Answer ans); //更新 //bool deleteById(int id); //删除 //bool sortById(); //排序 }; #endif // DATABASE_H >>>>>>> cfdf638c3bdfa8efdbbb0c911ad54fe243c63989
[ "kuangruifeng@bupt.edu.cn" ]
kuangruifeng@bupt.edu.cn
55755e777ebe321b8afbd55dde35274993acb0de
ea49dd7d31d2e0b65ce6aadf1274f3bb70abfaf9
/problems/0141_Linked_List_Cycle/0141_Linked_List_Cycle.cpp
152aef7cc268e5e7f9000b9f30d0f01115ba5d27
[]
no_license
yychuyu/LeetCode
907a3d7d67ada9714e86103ac96422381e75d683
48384483a55e120caf5d8d353e9aa287fce3cf4a
refs/heads/master
2020-03-30T15:02:12.492378
2019-06-19T01:52:45
2019-06-19T01:52:45
151,345,944
134
331
null
2019-08-01T02:56:10
2018-10-03T01:26:28
C++
UTF-8
C++
false
false
509
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { ListNode* slow=head; ListNode* fast=head; while(fast && fast->next && fast->next->next){ slow=slow->next; fast=fast->next->next; if(slow==fast){ return true; } } return false; } };
[ "noreply@github.com" ]
yychuyu.noreply@github.com
d39faf6cdac13ccaf766daf5ff1b7d62d7b73202
099c2076771c1fd5bba80e5f1465410dfa70375a
/PE050_Consecutive_prime_sum/pe050.cpp
af8dfcf5e878fb87b09f3674d5c8726cc05fbb73
[]
no_license
Jul-Le/project-euler
73595411effa3c150c9bae04ae8f155b4c69aae6
17fc9e0ad252931ba0dbaeb033a139727eb99e45
refs/heads/master
2021-10-07T23:45:29.106429
2018-12-05T18:24:00
2018-12-05T18:24:00
159,533,336
0
0
null
null
null
null
UTF-8
C++
false
false
1,604
cpp
#include <iostream> #include "isprime.h" int main() { // The final answer int answer = 0; // Temp answer int num = 0; // Number of consecutive primes int consecutivePrimes = 0; // ^^Temp int temp = 0; // Count how many consecutive primes int counter = 0; // How many to find before test the answer int terms = 21; int i; int a = 2; while (a < 10) { terms = 21; // 547 of smallest consecutive primes add up to over a million while (terms < 547) { num = 0; temp = 0; counter = 0; for (i = a; i < 500000; i++) { if (isPrime(i)) { num += i; counter++; temp++; if (counter >= terms) { if (isPrime(num)) { if (temp > consecutivePrimes && num < 1000000) { consecutivePrimes = temp; answer = num; } } else { terms++; std::cout << answer << " is a sum of " << consecutivePrimes << " consecutive primes." << std::endl; break; } } } } } a++; } }
[ "unconfigured@null.spigotmc.org" ]
unconfigured@null.spigotmc.org
369ff84ed0fe739311a8ea2971775372331315b3
5fd1de174f907a7625e798df35c8d07a7fce3f2b
/tests/formatstest.cpp
25172101a671292b61d0504c3cc53a134b749381
[ "BSD-3-Clause" ]
permissive
jeremyrearle/XtalOpt
1172b1e2c6eff2d5b58eb03d46619d0c61706729
a87aed2cf55db97d072db5f5a9fc03344c9ed46d
refs/heads/master
2021-07-07T02:10:40.315890
2017-09-21T14:02:16
2017-09-21T14:04:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,010
cpp
/********************************************************************** Formats test - test our file format readers and writers Copyright (C) 2017 Patrick Avery This source code is released under the New BSD License, (the "License"). 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 <globalsearch/formats/obconvert.h> #include <globalsearch/formats/cmlformat.h> #include <globalsearch/formats/poscarformat.h> #include <globalsearch/formats/formats.h> #include <globalsearch/structure.h> #include <QDebug> #include <QString> #include <QtTest> #include <sstream> using GlobalSearch::Vector3; class FormatsTest : public QObject { Q_OBJECT // Members GlobalSearch::Structure m_rutile; GlobalSearch::Structure m_caffeine; private slots: /** * Called before the first test function is executed. */ void initTestCase(); /** * Called after the last test function is executed. */ void cleanupTestCase(); /** * Called before each test function is executed. */ void init(); /** * Called after every test function. */ void cleanup(); // Tests void readPoscar(); void writePoscar(); void readCml(); void writeCml(); void OBConvert(); // Different optimizer formats void readCastep(); void readGulp(); void readPwscf(); void readSiesta(); void readVasp(); }; void FormatsTest::initTestCase() { } void FormatsTest::cleanupTestCase() { } void FormatsTest::init() { } void FormatsTest::cleanup() { } void FormatsTest::readPoscar() { /**** Rutile ****/ QString rutileFileName = QString(TESTDATADIR) + "/data/rutile.POSCAR"; GlobalSearch::Structure rutile; QVERIFY(GlobalSearch::Formats::read(&rutile, rutileFileName, "POSCAR")); // Our structure should have a unit cell, 6 atoms, and no bonds // The unit cell volume should be about 62.423 QVERIFY(rutile.hasUnitCell()); QVERIFY(rutile.numAtoms() == 6); QVERIFY(rutile.numBonds() == 0); QVERIFY(abs(62.4233 - rutile.unitCell().volume()) < 1.e-5); // The sixth atom should be Ti and should have cartesian coordinates of // (1.47906 2.29686 2.29686) double tol = 1.e-5; Vector3 rutileAtom2Pos(1.47906, 2.29686, 2.29686); QVERIFY(rutile.atom(5).atomicNumber() == 22); QVERIFY(GlobalSearch::fuzzyCompare(rutile.atom(5).pos(), rutileAtom2Pos, tol)); // The first atom should be O and should have fractional coordinates of // 0, 0.3053, 0.3053 tol = 1.e-5; Vector3 rutileAtom3Ref = rutile.unitCell().toFractional(rutile.atom(0).pos()); Vector3 rutileAtom3PosFrac(0.0, 0.3053, 0.3053); QVERIFY(rutile.atom(0).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare(rutileAtom3Ref, rutileAtom3PosFrac, tol)); // Let's set rutile to be used for the write test m_rutile = rutile; } void FormatsTest::writePoscar() { // First, write the POSCAR file to a stringstream std::stringstream ss; QVERIFY(GlobalSearch::PoscarFormat::write(m_rutile, ss)); // Now read from it and run the same tests we tried above /**** Rutile ****/ GlobalSearch::Structure rutile; QVERIFY(GlobalSearch::PoscarFormat::read(rutile, ss)); // Our structure should have a unit cell, 6 atoms, and no bonds // The unit cell volume should be about 62.423 QVERIFY(rutile.hasUnitCell()); QVERIFY(rutile.numAtoms() == 6); QVERIFY(rutile.numBonds() == 0); QVERIFY(abs(62.4233 - rutile.unitCell().volume()) < 1.e-5); // The sixth atom should be Ti and should have cartesian coordinates of // (1.47906 2.29686 2.29686) double tol = 1.e-5; Vector3 rutileAtom2Pos(1.47906, 2.29686, 2.29686); QVERIFY(rutile.atom(5).atomicNumber() == 22); QVERIFY(GlobalSearch::fuzzyCompare(rutile.atom(5).pos(), rutileAtom2Pos, tol)); // The first atom should be O and should have fractional coordinates of // 0, 0.3053, 0.3053 tol = 1.e-5; Vector3 rutileAtom3Ref = rutile.unitCell().toFractional(rutile.atom(0).pos()); Vector3 rutileAtom3PosFrac(0.0, 0.3053, 0.3053); QVERIFY(rutile.atom(0).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare(rutileAtom3Ref, rutileAtom3PosFrac, tol)); } void FormatsTest::readCml() { /**** Rutile ****/ QString rutileFileName = QString(TESTDATADIR) + "/data/rutile.cml"; GlobalSearch::Structure rutile; QVERIFY(GlobalSearch::Formats::read(&rutile, rutileFileName, "cml")); // Our structure should have a unit cell, 6 atoms, and no bonds // The unit cell volume should be about 62.423 QVERIFY(rutile.hasUnitCell()); QVERIFY(rutile.numAtoms() == 6); QVERIFY(rutile.numBonds() == 0); QVERIFY(abs(62.4233 - rutile.unitCell().volume()) < 1.e-5); // The second atom should be Ti and should have cartesian coordinates of // (1.47906 2.29686 2.29686) double tol = 1.e-5; Vector3 rutileAtom2Pos(1.47906, 2.29686, 2.29686); QVERIFY(rutile.atom(1).atomicNumber() == 22); QVERIFY(GlobalSearch::fuzzyCompare(rutile.atom(1).pos(), rutileAtom2Pos, tol)); // The third atom should be O and should have fractional coordinates of // 0, 0.3053, 0.3053 tol = 1.e-5; Vector3 rutileAtom3Ref = rutile.unitCell().toFractional(rutile.atom(2).pos()); Vector3 rutileAtom3PosFrac(0.0, 0.3053, 0.3053); QVERIFY(rutile.atom(2).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare(rutileAtom3Ref, rutileAtom3PosFrac, tol)); // Let's set rutile to be used for the write test m_rutile = rutile; /**** Ethane ****/ QString ethaneFileName = QString(TESTDATADIR) + "/data/ethane.cml"; GlobalSearch::Structure ethane; QVERIFY(GlobalSearch::Formats::read(&ethane, ethaneFileName, "cml")); // Our structure should have no unit cell, 8 atoms, and 7 bonds QVERIFY(!ethane.hasUnitCell()); QVERIFY(ethane.numAtoms() == 8); QVERIFY(ethane.numBonds() == 7); /**** Caffeine ****/ QString caffeineFileName = QString(TESTDATADIR) + "/data/caffeine.cml"; GlobalSearch::Structure caffeine; QVERIFY(GlobalSearch::Formats::read(&caffeine, caffeineFileName, "cml")); // Our structure should have no unit cell, 24 atoms, and 25 bonds QVERIFY(!caffeine.hasUnitCell()); QVERIFY(caffeine.numAtoms() == 24); QVERIFY(caffeine.numBonds() == 25); // Caffeine should also have 4 double bonds. Make sure of this. size_t numDoubleBonds = 0; for (const GlobalSearch::Bond& bond: caffeine.bonds()) { if (bond.bondOrder() == 2) ++numDoubleBonds; } QVERIFY(numDoubleBonds == 4); m_caffeine = caffeine; } // A note: this test will also fail if readCml() doesn't work properly // This function assumes that readCml() was already ran successfully, and // it uses it to confirm that the CML was written properly void FormatsTest::writeCml() { // First, write the cml file to a stringstream std::stringstream ss; QVERIFY(GlobalSearch::CmlFormat::write(m_rutile, ss)); // Now read from it and run the same tests we tried above /**** Rutile ****/ GlobalSearch::Structure rutile; QVERIFY(GlobalSearch::CmlFormat::read(rutile, ss)); // Our structure should have a unit cell, 6 atoms, and no bonds // The unit cell volume should be about 62.423 QVERIFY(rutile.hasUnitCell()); QVERIFY(rutile.numAtoms() == 6); QVERIFY(rutile.numBonds() == 0); QVERIFY(abs(62.4233 - rutile.unitCell().volume()) < 1.e-5); // The second atom should be Ti and should have cartesian coordinates of // (1.47906 2.29686 2.29686) double tol = 1.e-5; Vector3 rutileAtom2Pos(1.47906, 2.29686, 2.29686); QVERIFY(rutile.atom(1).atomicNumber() == 22); QVERIFY(GlobalSearch::fuzzyCompare(rutile.atom(1).pos(), rutileAtom2Pos, tol)); // The third atom should be O and should have fractional coordinates of // 0, 0.3053, 0.3053 tol = 1.e-5; Vector3 rutileAtom3Ref = rutile.unitCell().toFractional(rutile.atom(2).pos()); Vector3 rutileAtom3PosFrac(0.0, 0.3053, 0.3053); QVERIFY(rutile.atom(2).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare(rutileAtom3Ref, rutileAtom3PosFrac, tol)); // Do the same thing with caffeine std::stringstream css; QVERIFY(GlobalSearch::CmlFormat::write(m_caffeine, css)); /**** Caffeine ****/ GlobalSearch::Structure caffeine; QVERIFY(GlobalSearch::CmlFormat::read(caffeine, css)); // Our structure should have no unit cell, 24 atoms, and 25 bonds QVERIFY(!caffeine.hasUnitCell()); QVERIFY(caffeine.numAtoms() == 24); QVERIFY(caffeine.numBonds() == 25); // Caffeine should also have 4 double bonds. Make sure of this. size_t numDoubleBonds = 0; for (const GlobalSearch::Bond& bond: caffeine.bonds()) { if (bond.bondOrder() == 2) ++numDoubleBonds; } QVERIFY(numDoubleBonds == 4); } void FormatsTest::OBConvert() { /**** Caffeine PDB ****/ QString caffeineFileName = QString(TESTDATADIR) + "/data/caffeine.pdb"; QFile file(caffeineFileName); QVERIFY(file.open(QIODevice::ReadOnly)); QByteArray caffeinePDBData(file.readAll()); // First, use OBConvert to convert it to cml QByteArray caffeineCMLData; QVERIFY(GlobalSearch::OBConvert::convertFormat("pdb", "cml", caffeinePDBData, caffeineCMLData)); std::stringstream css(caffeineCMLData.data()); // Now read it GlobalSearch::Structure caffeine; QVERIFY(GlobalSearch::CmlFormat::read(caffeine, css)); // Our structure should have no unit cell, 24 atoms, and 25 bonds QVERIFY(!caffeine.hasUnitCell()); QVERIFY(caffeine.numAtoms() == 24); QVERIFY(caffeine.numBonds() == 25); // Caffeine should also have 4 double bonds. Make sure of this. size_t numDoubleBonds = 0; for (const GlobalSearch::Bond& bond: caffeine.bonds()) { if (bond.bondOrder() == 2) ++numDoubleBonds; } QVERIFY(numDoubleBonds == 4); // We can make sure the energy and enthalpy can be read correctly here /**** Caffeine SDF ****/ caffeineFileName = QString(TESTDATADIR) + "/data/caffeine-mmff94.sdf"; QFile fileSDF(caffeineFileName); QVERIFY(fileSDF.open(QIODevice::ReadOnly)); QByteArray caffeineSDFData(fileSDF.readAll()); // First, use OBConvert to convert it to cml QByteArray caffeineCMLDataWithEnergy; // If we want obabel to print the energy and enthalpy in the // cml output, we HAVE to pass "-xp" to it. QStringList options; options << "-xp"; QVERIFY(GlobalSearch::OBConvert::convertFormat("sdf", "cml", caffeineSDFData, caffeineCMLDataWithEnergy, options)); std::stringstream csdfss(caffeineCMLDataWithEnergy.data()); // Now read it GlobalSearch::Structure caffeineSDF; QVERIFY(GlobalSearch::CmlFormat::read(caffeineSDF, csdfss)); // Our structure should have no unit cell, 24 atoms, and 25 bonds QVERIFY(!caffeineSDF.hasUnitCell()); QVERIFY(caffeineSDF.numAtoms() == 24); QVERIFY(caffeineSDF.numBonds() == 25); // Caffeine should also have 4 double bonds. Make sure of this. numDoubleBonds = 0; for (const GlobalSearch::Bond& bond: caffeineSDF.bonds()) { if (bond.bondOrder() == 2) ++numDoubleBonds; } QVERIFY(numDoubleBonds == 4); // We should have enthalpy here. It should be -122.350, and energy should // be -122.351. QVERIFY(caffeineSDF.hasEnthalpy()); QVERIFY(std::fabs(caffeineSDF.getEnthalpy() - -122.350) < 1.e-5); QVERIFY(std::fabs(caffeineSDF.getEnergy() - -122.351) < 1.e-5); } void FormatsTest::readCastep() { /**** Some random CASTEP output ****/ QString fileName = QString(TESTDATADIR) + "/data/optimizerSamples/castep/xtal.castep"; GlobalSearch::Structure s; GlobalSearch::Formats::read(&s, fileName, "castep"); double tol = 1.e-5; // b should be 2.504900, gamma should be 103.045287, and the volume should // be 8.358635. QVERIFY(fabs(s.unitCell().b() - 2.504900) < tol); QVERIFY(fabs(s.unitCell().gamma() - 103.045287) < tol); QVERIFY(fabs(s.unitCell().volume() - 8.358635) < tol); // We should have two atoms QVERIFY(s.numAtoms() == 2); // Atom #1 should be H and have a fractional position of // -0.037144, 0.000195, 0.088768 QVERIFY(s.atom(0).atomicNumber() == 1); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(0).pos()), GlobalSearch::Vector3(-0.037144, 0.000195, 0.088768), tol ) ); // Atom #2 should be H and have a fractional position of // 0.474430, 0.498679, 0.850082 QVERIFY(s.atom(1).atomicNumber() == 1); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(1).pos()), GlobalSearch::Vector3(0.474430, 0.498679, 0.850082), tol ) ); // Energy should be -29.55686228188 QVERIFY(fabs(s.getEnergy() - -29.55686228188) < tol); // Enthalpy should be -29.5566434 QVERIFY(fabs(s.getEnthalpy() - -29.5566434) < tol); } void FormatsTest::readGulp() { /**** Some random GULP output ****/ QString gulpFileName = QString(TESTDATADIR) + "/data/optimizerSamples/gulp/xtal.got"; GlobalSearch::Structure s; GlobalSearch::Formats::read(&s, gulpFileName, "gulp"); double tol = 1.e-5; // b should be 4.3098, gamma should be 102.5730, and the volume should // be 67.7333397. QVERIFY(fabs(s.unitCell().b() - 3.398685) < tol); QVERIFY(fabs(s.unitCell().gamma() - 120.000878) < tol); QVERIFY(fabs(s.unitCell().volume() - 55.508520) < tol); // NumAtoms should be 6 QVERIFY(s.numAtoms() == 6); // Atom #2 should be Ti and have a fractional position of // 0.499957, 0.999999, 0.500003 QVERIFY(s.atom(1).atomicNumber() == 22); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(1).pos()), GlobalSearch::Vector3(0.499957, 0.999999, 0.500003), tol ) ); // Atom #3 should be O and have a fractional position of // 0.624991, 0.250020, 0.874996 QVERIFY(s.atom(2).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(2).pos()), GlobalSearch::Vector3(0.624991, 0.250020, 0.874996), tol ) ); // Energy should be -78.44239332 QVERIFY(fabs(s.getEnergy() - -78.44239332) < tol); } void FormatsTest::readPwscf() { /**** Some random PWSCF output ****/ QString fileName = QString(TESTDATADIR) + "/data/optimizerSamples/pwscf/xtal.out"; GlobalSearch::Structure s; GlobalSearch::Formats::read(&s, fileName, "pwscf"); double tol = 1.e-5; // b should be 4.13754, gamma should be 75.31465, and the volume should // be 70.0484. QVERIFY(fabs(s.unitCell().b() - 4.13754) < tol); QVERIFY(fabs(s.unitCell().gamma() - 75.31465) < tol); QVERIFY(fabs(s.unitCell().volume() - 70.0484) < tol); // We should have two atoms QVERIFY(s.numAtoms() == 2); // Atom #1 should be O and have a fractional position of // 0.040806225, 0.100970667, 0.003304159 QVERIFY(s.atom(0).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(0).pos()), GlobalSearch::Vector3(0.040806225, 0.100970667, 0.003304159), tol ) ); // Atom #2 should be O and have a fractional position of // 0.577212775, 0.316072333, 0.629713841 QVERIFY(s.atom(1).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(1).pos()), GlobalSearch::Vector3(0.577212775, 0.316072333, 0.629713841), tol ) ); static const double RYDBERG_TO_EV = 13.605698066; // We need to reduce the tolerance a little bit for these. tol = 1.e-3; // Energy should be -63.35870913 Rydbergs. QVERIFY(fabs(s.getEnergy() - (-63.35870913 * RYDBERG_TO_EV)) < tol); // Enthalpy should be -62.9446011092 Rydbergs QVERIFY(fabs(s.getEnthalpy() - (-62.9446011092 * RYDBERG_TO_EV)) < tol); } void FormatsTest::readSiesta() { /**** Some random SIESTA output ****/ QString fileName = QString(TESTDATADIR) + "/data/optimizerSamples/siesta/xtal.out"; GlobalSearch::Structure s; GlobalSearch::Formats::read(&s, fileName, "siesta"); double tol = 1.e-4; // b should be 3.874763, gamma should be 74.2726, and the volume should // be 75.408578. QVERIFY(fabs(s.unitCell().b() - 3.874763) < tol); QVERIFY(fabs(s.unitCell().gamma() - 74.2726) < tol); QVERIFY(fabs(s.unitCell().volume() - 75.408578) < tol); // We should have six atoms QVERIFY(s.numAtoms() == 6); // Atom #2 should be Ti and have a fractional position of // 0.40338285, 0.38896410, 0.75921162 QVERIFY(s.atom(1).atomicNumber() == 22); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(1).pos()), GlobalSearch::Vector3(0.40338285, 0.38896410, 0.75921162), tol ) ); // Atom #3 should be O and have a fractional position of // 0.38568921, 0.74679127, 0.21473350 QVERIFY(s.atom(2).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(2).pos()), GlobalSearch::Vector3(0.38568921, 0.74679127, 0.21473350), tol ) ); // Energy should be -2005.342641 eV QVERIFY(fabs(s.getEnergy() - -2005.342641) < tol); } void FormatsTest::readVasp() { /**** Some random VASP output ****/ QString fileName = QString(TESTDATADIR) + "/data/optimizerSamples/vasp/CONTCAR"; GlobalSearch::Structure s; GlobalSearch::Formats::read(&s, fileName, "vasp"); double tol = 1.e-5; // b should be 2.52221, gamma should be 86.32327, and the volume should // be 6.01496. QVERIFY(fabs(s.unitCell().b() - 2.52221) < tol); QVERIFY(fabs(s.unitCell().gamma() - 86.32327) < tol); QVERIFY(fabs(s.unitCell().volume() - 6.01496) < tol); // We should have three atoms QVERIFY(s.numAtoms() == 3); // Atom #2 should be H and have a fractional position of // 0.9317195263978, 0.20419595775, 0.4923304223199 QVERIFY(s.atom(1).atomicNumber() == 1); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(1).pos()), GlobalSearch::Vector3(0.9317195263978, 0.20419595775, 0.4923304223199), tol ) ); // Atom #3 should be O and have a fractional position of // 0.087068957523, -0.1465596214494, 0.1524183445695 QVERIFY(s.atom(2).atomicNumber() == 8); QVERIFY(GlobalSearch::fuzzyCompare( s.unitCell().toFractional(s.atom(2).pos()), GlobalSearch::Vector3(0.087068957523, -0.1465596214494, 0.1524183445695), tol ) ); // Energy should be 5.56502673 eV. QVERIFY(fabs(s.getEnergy() - 5.56502673) < tol); // Enthalpy should be 43.10746559 eV QVERIFY(fabs(s.getEnthalpy() - 43.10746559) < tol); } QTEST_MAIN(FormatsTest) #include "formatstest.moc"
[ "psavery@buffalo.edu" ]
psavery@buffalo.edu
fbeb76d32c37017fe31321e4545cdb0df18c90f9
99f4b183c575d0a476a99a6a851bc7ba5660bdb0
/755529/20200912.cpp
e3bbce2caec9b5a1cc794af0be22ad169aad2d74
[]
no_license
XWJWPIY/20200910-homework-basic
041ec01e0774266a2299bce424ccabd7c9c6e765
9541056bcd43ba0fb15b9b3b7b2c61f3430c1a32
refs/heads/master
2022-12-10T19:01:40.156838
2020-09-12T08:58:14
2020-09-12T08:58:14
294,898,988
0
0
null
2020-09-12T08:04:12
2020-09-12T08:04:11
null
UTF-8
C++
false
false
178
cpp
#include <iostream> using namespace std; int main() { string str; std::cout << "請輸入你的名字:"; std::cin >> str; std::cout << "你的名字是" + str; }
[ "piy.angrybirds.minecraft@gmail.com" ]
piy.angrybirds.minecraft@gmail.com
6495bab4408baf0e3f71f8ddfe1c626d27ceac87
b80b82c336e2d59b0573f4515a26d4684aff9f1a
/projekt/Options.h
07f7dd7cda864fc9d0be73211754d9d631f2e9cc
[]
no_license
ancf/sfml-2d-game
3127a3412915ca5af7194ee747584b82bf76c441
b408d59d20d38610342b7fb3b44fff691d713611
refs/heads/master
2023-05-02T10:12:25.204459
2021-05-26T11:04:07
2021-05-26T11:04:07
371,001,376
0
0
null
null
null
null
UTF-8
C++
false
false
582
h
#pragma once #include "SFML/Graphics.hpp" class Options { public: Options(float width, float height); ~Options(); enum DifficultyLevel { Easy, Medium, Hard }; int SelectedVolume; std::string SelectedName; // void draw(sf::RenderWindow &menu_window); // void draw_test(sf::RenderWindow &menu_window); // void upwards(); // void downwards(); // int GetPressedIndex() { return SelectedIndex; } private: // int ButtonWidth = 300; // int ButtonHeight = 50; // sf::Font def; // sf::Text MenuText[POSITIONS_NUMBER]; // sf::RectangleShape MenuButton[POSITIONS_NUMBER]; };
[ "krystian1998k@gmail.com" ]
krystian1998k@gmail.com
95a8c077432fb9699d7a8b142d5af3ed6f6b0578
a0bdedcc814dfcbf6f1742c398b64a31619af4df
/ideccmbd/CrdIdecNav/PnlIdecNavPre_blks.cpp
a7856813874a260a40b4296d61833d58366e4101
[ "BSD-2-Clause" ]
permissive
mpsitech/idec_public
ec7231939b8987fd66482d99276609e16d4ad3f7
a74cf1c7095e08ee61b237fddc1642f83dbb852d
refs/heads/master
2021-05-13T20:43:55.046131
2018-06-09T16:11:30
2018-06-09T16:11:30
116,916,593
0
0
null
null
null
null
UTF-8
C++
false
false
7,558
cpp
/** * \file PnlIdecNavPre_blks.cpp * job handler for job PnlIdecNavPre (implementation of blocks) * \author Alexander Wirthmueller * \date created: 30 Dec 2017 * \date modified: 30 Dec 2017 */ /****************************************************************************** class PnlIdecNavPre::VecVDo ******************************************************************************/ uint PnlIdecNavPre::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butmisremoveclick") return BUTMISREMOVECLICK; else if (s == "buttouremoveclick") return BUTTOUREMOVECLICK; return(0); }; string PnlIdecNavPre::VecVDo::getSref( const uint ix ) { if (ix == BUTMISREMOVECLICK) return("ButMisRemoveClick"); else if (ix == BUTTOUREMOVECLICK) return("ButTouRemoveClick"); return(""); }; /****************************************************************************** class PnlIdecNavPre::ContInf ******************************************************************************/ PnlIdecNavPre::ContInf::ContInf( const string& TxtMis , const string& TxtTou ) : Block() { this->TxtMis = TxtMis; this->TxtTou = TxtTou; mask = {TXTMIS, TXTTOU}; }; void PnlIdecNavPre::ContInf::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfIdecNavPre"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfIdecNavPre"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "TxtMis", TxtMis); writeStringAttr(wr, itemtag, "sref", "TxtTou", TxtTou); xmlTextWriterEndElement(wr); }; set<uint> PnlIdecNavPre::ContInf::comm( const ContInf* comp ) { set<uint> items; if (TxtMis == comp->TxtMis) insert(items, TXTMIS); if (TxtTou == comp->TxtTou) insert(items, TXTTOU); return(items); }; set<uint> PnlIdecNavPre::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TXTMIS, TXTTOU}; for (auto it=commitems.begin();it!=commitems.end();it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlIdecNavPre::StatShr ******************************************************************************/ PnlIdecNavPre::StatShr::StatShr( const bool TxtMisAvail , const bool TxtTouAvail ) : Block() { this->TxtMisAvail = TxtMisAvail; this->TxtTouAvail = TxtTouAvail; mask = {TXTMISAVAIL, TXTTOUAVAIL}; }; void PnlIdecNavPre::StatShr::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrIdecNavPre"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrIdecNavPre"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "TxtMisAvail", TxtMisAvail); writeBoolAttr(wr, itemtag, "sref", "TxtTouAvail", TxtTouAvail); xmlTextWriterEndElement(wr); }; set<uint> PnlIdecNavPre::StatShr::comm( const StatShr* comp ) { set<uint> items; if (TxtMisAvail == comp->TxtMisAvail) insert(items, TXTMISAVAIL); if (TxtTouAvail == comp->TxtTouAvail) insert(items, TXTTOUAVAIL); return(items); }; set<uint> PnlIdecNavPre::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TXTMISAVAIL, TXTTOUAVAIL}; for (auto it=commitems.begin();it!=commitems.end();it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlIdecNavPre::Tag ******************************************************************************/ void PnlIdecNavPre::Tag::writeXML( const uint ixIdecVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagIdecNavPre"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemIdecNavPre"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixIdecVLocale == VecIdecVLocale::ENUS) { writeStringAttr(wr, itemtag, "sref", "CptMis", "mission"); writeStringAttr(wr, itemtag, "sref", "CptTou", "tour"); } else if (ixIdecVLocale == VecIdecVLocale::DECH) { writeStringAttr(wr, itemtag, "sref", "CptMis", "Mission"); writeStringAttr(wr, itemtag, "sref", "CptTou", "Tour"); }; xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlIdecNavPre::DpchAppDo ******************************************************************************/ PnlIdecNavPre::DpchAppDo::DpchAppDo() : DpchAppIdec(VecIdecVDpch::DPCHAPPIDECNAVPREDO) { ixVDo = 0; }; string PnlIdecNavPre::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlIdecNavPre::DpchAppDo::readXML( pthread_mutex_t* mScr , map<string,ubigint>& descr , xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; string srefIxVDo; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppIdecNavPreDo"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(mScr, descr, scrJref); add(JREF); }; if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) { ixVDo = VecVDo::getIx(srefIxVDo); add(IXVDO); }; } else { }; }; /****************************************************************************** class PnlIdecNavPre::DpchEngData ******************************************************************************/ PnlIdecNavPre::DpchEngData::DpchEngData( const ubigint jref , ContInf* continf , StatShr* statshr , const set<uint>& mask ) : DpchEngIdec(VecIdecVDpch::DPCHENGIDECNAVPREDATA, jref) { if (find(mask, ALL)) this->mask = {JREF, CONTINF, STATSHR, TAG}; else this->mask = mask; if (find(this->mask, CONTINF) && continf) this->continf = *continf; if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr; }; string PnlIdecNavPre::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTINF)) ss.push_back("continf"); if (has(STATSHR)) ss.push_back("statshr"); if (has(TAG)) ss.push_back("tag"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlIdecNavPre::DpchEngData::merge( DpchEngIdec* dpcheng ) { DpchEngData* src = (DpchEngData*) dpcheng; if (src->has(JREF)) {jref = src->jref; add(JREF);}; if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);}; if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);}; if (src->has(TAG)) add(TAG); }; void PnlIdecNavPre::DpchEngData::writeXML( const uint ixIdecVLocale , pthread_mutex_t* mScr , map<ubigint,string>& scr , map<string,ubigint>& descr , xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchEngIdecNavPreData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/idec"); if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(mScr, scr, descr, jref)); if (has(CONTINF)) continf.writeXML(wr); if (has(STATSHR)) statshr.writeXML(wr); if (has(TAG)) Tag::writeXML(ixIdecVLocale, wr); xmlTextWriterEndElement(wr); };
[ "mpsitech@ungenio.local" ]
mpsitech@ungenio.local
0893d92971311ed0274713d310284408f4295504
82770c7bc5e2f27a48b8c370b0bab2ee41f24d86
/graph-tool/src/graph/search/graph_search_bind.cc
97d3a28910c3ce68f5104858e8d71101593aa8fc
[ "Apache-2.0", "GPL-3.0-only", "LicenseRef-scancode-philippe-de-muyter", "GPL-3.0-or-later" ]
permissive
johankaito/fufuka
77ddb841f27f6ce8036d7b38cb51dc62e85b2679
32a96ecf98ce305c2206c38443e58fdec88c788d
refs/heads/master
2022-07-20T00:51:55.922063
2015-08-21T20:56:48
2015-08-21T20:56:48
39,845,849
2
0
Apache-2.0
2022-06-29T23:30:11
2015-07-28T16:39:54
Python
UTF-8
C++
false
false
1,166
cc
// graph-tool -- a general graph modification and manipulation thingy // // Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <boost/python.hpp> using namespace boost; void export_bfs(); void export_dfs(); void export_dijkstra(); void export_bellman_ford(); void export_astar(); void export_astar_implicit(); BOOST_PYTHON_MODULE(libgraph_tool_search) { export_bfs(); export_dfs(); export_dijkstra(); export_bellman_ford(); export_astar(); export_astar_implicit(); }
[ "john.g.keto@gmail.com" ]
john.g.keto@gmail.com
f2bf1d6e67e0119a78c795e6830b798cd77d0f5d
d669ad659f7f91a3f00ee677c5d5866433adaf41
/do_best_holdem_hands.cpp
3c55d90256e77f198ee630c46fc07ac29d337f4b
[]
no_license
neostreet/poker_odds_calculators
8db5921dd0dbd025c895d8f8b9c714ab2c527cd9
5c6a3b68802e99a25800e4a7a077ac13c2e8aaab
refs/heads/master
2022-10-24T16:34:17.450169
2022-09-29T20:42:20
2022-09-29T20:42:20
1,309,216
6
2
null
null
null
null
UTF-8
C++
false
false
1,774
cpp
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; #define MAIN_MODULE #include "poker_hand.h" static char usage[] = "usage: best_holdem_hand (-unevaluate) (-verbose) (-plain) (-no_stream)"; static char couldnt_open[] = "couldn't open %s\n"; static char parse_error[] = "couldn't parse line %d, card %d: %d\n"; int main(int argc,char **argv) { int curr_arg; bool bUnEvaluate; bool bVerbose; bool bPlain; bool bNoStream; int n; int cards[NUM_CARDS_IN_DECK]; HoldemPokerHand board_poker_hand; PokerHand best_poker_hand; if ((argc < 1) || (argc > 5)) { cout << usage << endl; return 1; } bUnEvaluate = false; bVerbose = false; bPlain = false; bNoStream = false; for (curr_arg = 1; curr_arg < argc; curr_arg++) { if (!strcmp(argv[curr_arg],"-unevaluate")) bUnEvaluate = true; else if (!strcmp(argv[curr_arg],"-verbose")) bVerbose = true; else if (!strcmp(argv[curr_arg],"-plain")) bPlain = true; else if (!strcmp(argv[curr_arg],"-no_stream")) bNoStream = true; else break; } if (argc != curr_arg) { cout << usage << endl; return 2; } for (n = 0; n < NUM_CARDS_IN_DECK; n++) cards[n] = n; for (n = 0; n < NUM_CARDS_IN_DECK - 7 + 1; n++) { board_poker_hand.NewCards(cards[n],cards[n+1],cards[n+2], cards[n+3],cards[n+4],cards[n+5],cards[n+6]); best_poker_hand = board_poker_hand.BestPokerHand(); if (bUnEvaluate) best_poker_hand.UnEvaluate(); else { if (bVerbose) best_poker_hand.Verbose(); if (bPlain) best_poker_hand.Plain(); } if (!bNoStream) cout << best_poker_hand << endl; else cout << best_poker_hand.GetHand() << endl; } return 0; }
[ "lloyd.aidan@gmail.com" ]
lloyd.aidan@gmail.com
1fdb9ab0ea94f1ca190e892f14e6b91ca859aa07
e8ff6a43129804f611e32f8129bc849e6d5e9255
/All Nodes Distance K in Binary Tree.cpp
e04e3047adcb20db6727a879394fb0b5714a90d1
[]
no_license
hirasaha-backcountry/Codes
00879dec6e9ed73a69b853b8cdfc2fa44f8c9b22
c6982dc70c78aeae9aff378ade0ee5dabde55c0d
refs/heads/master
2023-08-01T08:12:48.415214
2021-09-13T20:07:07
2021-09-13T20:07:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,184
cpp
/* Problem Description : (LC 863) ------------------------------------------------ We are given a binary tree (with root node root), a target node, and an integer value K. Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order. Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2 Output: [7,4,1] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png Note that the inputs "root" and "target" are actually TreeNodes. The descriptions of the inputs above are just serializations of these objects. Note: The given tree is non-empty. Each node in the tree has unique values 0 <= node.val <= 500. The target node is a node in the tree. 0 <= K <= 1000. */ #1: COde: ---------------------------------------- /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void undirectedGraphCreate(TreeNode* root, map<int, TreeNode*> &m, TreeNode* parent){ if(root == NULL) return ; if(parent != NULL){ m[root->val] = parent; cout<<"root->val : "<<root->val<<" parent"<<parent->val<<"\n"; } undirectedGraphCreate(root->left, m, root); undirectedGraphCreate(root->right, m, root); } vector<int> distanceK(TreeNode* root, TreeNode* target, int K) { map<int, TreeNode*> m; map<int, int> seen; m[root->val] = NULL; undirectedGraphCreate(root, m, NULL); queue<TreeNode*> q; q.push(target); seen[target->val] = 1; int currLevel = 0; while(!q.empty()){ if(currLevel == K){ break; }else{ int size = q.size(); for(int i = 0 ; i < size ; i++){ TreeNode* temp = q.front(); cout<<"queue values : "<<temp->val<<"\n"; q.pop(); if(temp->left){ if(seen.find(temp->left->val) == seen.end()){ seen[temp->left->val] = 1; q.push(temp->left); } } if(temp->right){ if(seen.find(temp->right->val) == seen.end()){ seen[temp->right->val] = 1; q.push(temp->right); } } TreeNode* parent = m[temp->val]; if(parent){ cout<<"parent->val : "<<parent->val<<"\n"; if(seen.find(parent->val) == seen.end()){ seen[parent->val] = 1; q.push(parent); } } } currLevel++; } } vector<int> res; while(!q.empty()){ TreeNode* val = q.front(); res.push_back(val->val); q.pop(); } return res; } }; #2:; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> distanceK(TreeNode* root, TreeNode* target, int K) { unordered_map<TreeNode*, TreeNode*> parent_map; queue<TreeNode*> q; unordered_map<TreeNode*, bool> visited; parent_map[root] = NULL; q.push(root); while(!q.empty()){ TreeNode* curr = q.front(); q.pop(); if(curr->left){ q.push(curr->left); parent_map[curr->left] = curr; } if(curr->right){ q.push(curr->right); parent_map[curr->right] = curr; } } q.push(target); visited[target] = true; int currLevel = 0; while(!q.empty()){ if(currLevel++ == K) break; int size = q.size(); while(size--){ TreeNode* curr = q.front(); q.pop(); if(curr->left && !visited[curr->left]){ q.push(curr->left); visited[curr->left] = true; } if(curr->right && !visited[curr->right]){ q.push(curr->right); visited[curr->right] = true; } if(parent_map[curr] && !visited[parent_map[curr]]){ q.push(parent_map[curr]); visited[parent_map[curr]] = true; } } } vector<int> res; while(!q.empty()){ TreeNode* node = q.front(); q.pop(); res.push_back(node->val); } return res; } };
[ "noreply@github.com" ]
hirasaha-backcountry.noreply@github.com
60b04fe2ec36ad5f0fe2c1463dadc9fd8fdb9f9c
96825cf87690c768a60b0fbc7138a43ca22edaa9
/Source/BlueprintRetarget/Public/BlueprintRetarget.h
6e963f4623464174b676580c9c90aa0a9e23a74d
[ "Apache-2.0" ]
permissive
Hengle/BlueprintRetarget
1ff639ff1866af73676af04f4f9e348f88f315e6
a7e3cb959dd4a8902d29d3a6947dfbb21b575524
refs/heads/master
2022-11-09T01:57:07.599744
2020-06-20T07:42:48
2020-06-20T07:42:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
429
h
// Copyright 2015-2020 Piperift. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Modules/ModuleManager.h" DECLARE_LOG_CATEGORY_EXTERN(LogBlueprintReparent, All, All); class FToolBarBuilder; class FMenuBuilder; class FBlueprintRetargetModule : public IModuleInterface { public: /** IModuleInterface implementation */ virtual void StartupModule() override; virtual void ShutdownModule() override; };
[ "muit@piperift.com" ]
muit@piperift.com
4efd3c8c0e8ff0f2749316a0e8d8990a4c5d4ff0
7b48fcad9a50b8fe2315e20efc7bc2ddefdafea3
/longest_palindromic_substring/lsp_extend.cpp
e32abb78b25450de4064fb75e28a78f3d18ac725
[]
no_license
TheWaySoFar/LeetCode_Solution
c96ea26f30c310ae4cc917d21d69809a98eb7b28
1ae152d9e261a3587100ccfcadc5097dc1d1ea08
refs/heads/master
2020-03-10T00:57:45.025959
2018-08-01T14:04:22
2018-08-01T14:04:22
129,096,499
0
0
null
null
null
null
UTF-8
C++
false
false
852
cpp
#include<iostream> #include<string> using namespace std; class Solution { public: string longestPalindrome(string s) { int len = s.size(); int ans = 1, ansl = 0; for(int i=0; i<len; i++){ extend(i, i, s, ans, ansl); extend(i, i+1, s, ans, ansl); } //return string(s.begin()+ansl, s.begin()+ansl+ans); return s.substr(ansl, ans); } void extend(int l, int r, string s,int & ans, int & ansl){ int len = s.size(); while(l>=0&&r<len&&s[l]==s[r]){ l--,r++; } if(ans < r-l-1){ ans = r-l-1; ansl = l+1; } } }; int main(){ Solution s; cout<<s.longestPalindrome("babad")<<endl; cout<<s.longestPalindrome("cbbd")<<endl; cout<<s.longestPalindrome("abcddcba")<<endl; return 0; }
[ "103664210@qq.com" ]
103664210@qq.com
9f6fdb582f429d3eb9c06b3638fdc09a9fad06fd
a3947da58918e8508178e75c05d38ea1bef6d5ae
/DataHeaders/mission.h
8fc3aae804caa90826513cc00339d228a43c2fab
[]
no_license
oygx210/cute42
a4f59a716cd8d7f647823458d99210849a4aade5
6150275f082d01dde3fe12630d669fd7f14998c2
refs/heads/main
2023-03-17T22:14:33.807296
2021-03-04T09:07:08
2021-03-04T09:07:08
384,966,099
0
1
null
2021-07-11T14:16:52
2021-07-11T14:16:52
null
UTF-8
C++
false
false
3,550
h
#ifndef MISSION_H #define MISSION_H #include <QString> #include <QVector> #include <QVariant> #include <QDataStream> #include <QDebug> #include "qt42baseclass.h" #include "qt42_headers.h" class SpacecraftHeader; class OrbitHeader; class MissionHolder; class Spacecraft; class Orbit; class Mission : public Qt42BaseClass { public: Mission(MissionHolder* MH = nullptr); Mission(const Mission& otherMission); ~Mission() override; Mission& operator=(const Mission& otherMission); bool operator==(const Mission& otherMission) const; objectType type() const override { return m_type;} QString name() const override {return m_name;} int index() const override {return m_index;} void updateIndex(); int numberOfSpacecraft() const; int numberOfOrbit() const; bool hasName(const QString& name); bool createSpacecraft(); bool removeSpacecraft(Spacecraft* SC); Spacecraft* spacecraft(const int& index); bool createOrbit(); bool removeOrbit(Orbit* SC); Orbit* orbit(const int& index); int numberOfHeaders() const {return m_numberOfHeaders;} const QString defaultName = "Default Mission"; void rename(const QString& newName); void setDirectroy(const QString& dir) {m_directory = dir;} QString directory() const {return m_directory;} SpacecraftHeader* spacecraftheader() const {return m_SpacecraftHeader;} OrbitHeader* orbitheader() const {return m_OrbitHeader;} InpSimHeader* inpsimheader() const {return m_InpSimHeader;} FOVHeader* fOVHeader() {return m_FOVHeader;} InpIPCHeader* inpIpcHeader() const {return m_InpIPCHeader;} GraphicsHeader* graphisHeader() const {return m_graphisHeader;} InpTDRs* inpTDRs() const {return m_inpTDRs;} RegionHeader* regionHeader() const {return m_regionHeader;} /** void "setMissionHolder(MissionHolder* mh)" and "void setIndex(const int& index)" are * for data seriaization (operator << and operator >>) **/ void setMissionHolder(MissionHolder* mh) {m_MissionHolder = mh;} void setIndex(const int& index) {m_index = index;} SpacecraftHeader m_SpacecraftHeaderObject = SpacecraftHeader(); OrbitHeader m_OrbitHeaderObejct = OrbitHeader(); InpSimHeader m_InpSimHeaderObject = InpSimHeader(); FOVHeader m_FOVHeaderObject = FOVHeader(); InpIPCHeader m_InpIPCHeaderObject = InpIPCHeader(); GraphicsHeader m_GraphisHeaderObject = GraphicsHeader(); InpTDRs m_inpTDRsObject = InpTDRs(); RegionHeader m_regionHeaderObject = RegionHeader(); /** end **/ friend QDataStream& operator<< (QDataStream& dataStream, const Mission& m); friend QDataStream& operator>> (QDataStream& dataStream, Mission& m); friend QDebug operator<< (QDebug dataStream, const Mission& m); private: void changeType(const objectType& type) override {Qt42BaseClass::changeType(type);} const objectType m_type = MISSION; QString m_name = "Mission"; // the name of the mission; QString m_directory = QString(); int m_index = -1; // the index of the mission; MissionHolder* m_MissionHolder = nullptr; SpacecraftHeader* m_SpacecraftHeader = nullptr; OrbitHeader* m_OrbitHeader = nullptr; InpSimHeader* m_InpSimHeader = nullptr; FOVHeader* m_FOVHeader = nullptr; InpIPCHeader* m_InpIPCHeader = nullptr; GraphicsHeader* m_graphisHeader = nullptr; InpTDRs* m_inpTDRs = nullptr; RegionHeader* m_regionHeader = nullptr; int m_numberOfHeaders = 5; }; Q_DECLARE_METATYPE(Mission); #endif // MISSION_H
[ "ytsoroy@gmail.com" ]
ytsoroy@gmail.com
5739ae036b5019955b259653a89a32c8411223a3
5fe209e8fb8891f0fa0981be60b724961a8ebf41
/day6.cpp
07636bbb323ec4cca3416226991ce5febc2449af
[]
no_license
Jluxcs/CPP_learning
b7d87fe1e1c98ea5f3f203d8db8c706a82d208bb
9ec057ca6fc5000e3b126bcd49e269043dfcab17
refs/heads/master
2020-06-17T02:23:47.588776
2019-07-08T08:20:59
2019-07-08T08:20:59
195,767,170
3
0
null
null
null
null
UTF-8
C++
false
false
287
cpp
//c++传递指针给函数 #include <iostream> #include <ctime> using namespace std; void gerSeconds(unsigned long *par); int main(){ unsigned long sec; gerSeconds(&sec); cout<<"当前的秒数:"<<sec<<endl; } void gerSeconds(unsigned long *par){ *par = time(NULL); return; }
[ "852306873@qq.com" ]
852306873@qq.com
3d395af9d17064c76e703b2b7c46530b25cb4749
ec93acb118d5db08c2ac97b667648db2161d2f6d
/android/cpp/src/objects/asmediacontainer.cpp
b778eb8137a5abf8813ce5df895a1fbadc4c9176
[]
no_license
ActivLearning/flipchartparser
cb315e698fbd3c3869b978a099c2dbbae93536e2
dfbe159f4680a0396d3761490376884878cef6e3
refs/heads/master
2022-12-07T12:18:28.258572
2020-09-04T03:42:48
2020-09-04T03:42:48
290,667,276
1
0
null
null
null
null
UTF-8
C++
false
false
19,463
cpp
#include <QMutexLocker> #include <QObject> #include <QObjectList> #include "asmediacontainer.h" #include "../resources/asimageres.h" #include "../resources/asmediafileres.h" #include "../asfactory.h" #include "../resources/asresourcemanager.h" #include "../util/asutil.h" #include "asflipchart.h" #include "../util/commonlog.h" #ifdef Q_OS_WIN32 #include "asaxwidget.h" #endif AsMediaContainer::AsMediaContainer( AsFactory *pFactory ) : AsWidgetContainer( pFactory ), m_creationMutex( QMutex::Recursive ), m_bSelected(false), m_autoTakePlaceHolderImage( false ) { this->asClear(); } AsMediaContainer::AsMediaContainer( const AsMediaContainer & container ) : AsWidgetContainer( container ), m_creationMutex( QMutex::Recursive ) { this->asClear(); this->asCopy( container ); } AsMediaContainer::~AsMediaContainer() { this->asDestroyMediaObjectAndSurface(); } void AsMediaContainer::asDestroyMediaObjectAndSurface() { } void AsMediaContainer::asSetVisible( bool bVisible ) { if( asIsVisible() == bVisible ) { // do nothing. return; } AsRenderable::asSetVisible( bVisible ); // restart the media, well start this->asRestartMediaObject(); } void AsMediaContainer::asResetPropertyIndex( void ) { AsObject::asSetPropertyIterator( &m_lProperties ); } void AsMediaContainer::asClear() { this->asSetType( AsObject::AS_OBJECT_MEDIACONTAINER ); this->m_isContextCreated = false; this->m_pTheSurfaceWidget = NULL; this->m_pMediaFileRes = NULL; this->m_pMultiMediaObject = NULL; this->m_autoPlay = false; this->m_loop = false; this->m_hideControls = false; this->m_forceAspect = false; this->m_mediaFileResource = 0; this->m_transparentBackground = false; this->m_unableToCreateMultiMediaObject = false; this->m_unableToCreateController = false; this->m_unableToCreateSurfaceWidget = false; this->m_unableToCreateSurface = false; this->m_creationState = AsMediaContainer::NotCreated; this->m_giveFocusOnCreate = false; this->m_firstRenderDone = false; this->m_currentRenderMode = AsWidgetContainer::AS_PAINTER_RENDER_IMAGE; this->m_knownDeviceSpaceRectChange = false; this->m_cachedForceOverlay = true; this->m_cachedAutoPlay = false; this->m_cachedLoop = false; this->m_cachedHideControls = true; this->m_cachedForceAspect = true; this->m_cachedTransparentBackground = false; this->m_cahcedRestartWasPlaying = false; this->m_needToDoMainSignalsAndSlotsConnection = true; } void AsMediaContainer::asCopy( const AsMediaContainer & container ) { AsWidgetContainer::operator = ( container ); this->m_autoPlay = container.m_autoPlay; this->m_loop = container.m_loop; this->m_hideControls = container.m_hideControls; this->m_forceAspect = container.m_forceAspect; this->m_transparentBackground = container.m_transparentBackground; } void AsMediaContainer::operator = ( const AsMediaContainer & container ) { this->asCopy( container ); } bool AsMediaContainer::operator == ( const AsMediaContainer & ) { return false; } void AsMediaContainer::asOnObjectEditing( AsNode *, AsNode *pObjectNode ) { } void AsMediaContainer::asOnObjectEdited( AsNode *, AsNode *pObjectNode ) { } bool AsMediaContainer::asGetAutoPlay() const { return this->m_autoPlay; } bool AsMediaContainer::asGetLoop() const { return this->m_loop; } bool AsMediaContainer::asGetHideControls() const { return this->m_hideControls; } bool AsMediaContainer::asGetForceAspect() const { return this->m_forceAspect; } unsigned int AsMediaContainer::asGetMediaFileResource() const { return this->m_mediaFileResource; } bool AsMediaContainer::asGetTransparentBackground() const { return this->m_transparentBackground; } void AsMediaContainer::asSetAutoPlay( bool & v ) { this->m_autoPlay = v; } void AsMediaContainer::asSetLoop( bool & v ) { this->m_loop = v; } void AsMediaContainer::asSetHideControls( bool & v ) { this->m_hideControls = v; } void AsMediaContainer::asSetForceAspect( bool & v ) { this->m_forceAspect = v; } void AsMediaContainer::asSetMediaFileResource( unsigned int & id ) { this->m_pMediaFileRes = NULL; this->m_mediaFileResource = id; } void AsMediaContainer::asSetTransparentBackground( bool & value ) { this->m_transparentBackground = value; } QHash<QString, quint16> & AsMediaContainer::m_lProperties( void ) { static QHash<QString, quint16> HashProperties; if ( HashProperties.isEmpty() ) { // From AsObject... // HashProperties.insert( "asDateTimeCreated", ( quint16 )AsMediaContainer::AS_PROPERTY_DATETIMECREATED ); // From AsRenderable... HashProperties.insert( "transform", ( quint16 )AsMediaContainer::AS_PROPERTY_TRANSFORM ); // HashProperties.insert( "asTwips", ( quint16 )AsMediaContainer::AS_PROPERTY_TWIPS ); HashProperties.insert( "name", ( quint16 )AsMediaContainer::AS_PROPERTY_NAME ); // HashProperties.insert( "asKeywords", ( quint16 )AsMediaContainer::AS_PROPERTY_KEYWORDS ); // HashProperties.insert( "asVisible", ( quint16 )AsMediaContainer::AS_PROPERTY_VISIBLE ); HashProperties.insert( "boundingRect", ( quint16 )AsMediaContainer::AS_PROPERTY_BOUNDINGRECT ); HashProperties.insert( "layer", ( quint16 )AsMediaContainer::AS_PROPERTY_LAYER ); HashProperties.insert( "zOrder", ( quint16 )AsMediaContainer::AS_PROPERTY_Z ); HashProperties.insert( "ink", ( quint16 )AsMediaContainer::AS_PROPERTY_INK ); HashProperties.insert( "scaleOrigin", ( quint16 )AsMediaContainer::AS_PROPERTY_SCALEORIGIN ); HashProperties.insert( "rotateOrigin", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATEORIGIN ); HashProperties.insert( "moveType", ( quint16 )AsMediaContainer::AS_PROPERTY_CANMOVE ); // HashProperties.insert( "asCanSize", ( quint16 )AsMediaContainer::AS_PROPERTY_CANSIZE ); // HashProperties.insert( "asCanRotate", ( quint16 )AsMediaContainer::AS_PROPERTY_CANROTATE ); // HashProperties.insert( "asCanBlock", ( quint16 )AsMediaContainer::AS_PROPERTY_CANBLOCK ); // HashProperties.insert( "asCanSnap", ( quint16 )AsMediaContainer::AS_PROPERTY_CANSNAP ); HashProperties.insert( "locked", ( quint16 )AsMediaContainer::AS_PROPERTY_LOCKED ); // HashProperties.insert( "asSnapback", ( quint16 )AsMediaContainer::AS_PROPERTY_SNAPBACK ); // HashProperties.insert( "asPathPointer", ( quint16 )AsMediaContainer::AS_PROPERTY_PATHPOINTER ); // HashProperties.insert( "asRotateAboutPointer", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATEABOUTPOINTER ); // HashProperties.insert( "asRotatePoint", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATEPOINT ); // HashProperties.insert( "asRotateAbout", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATEABOUT ); // HashProperties.insert( "asRotateStep", ( quint16 )AsMediaContainer::AS_PROPERTY_ROTATESTEP ); // HashProperties.insert( "asSnapToPointer", ( quint16 )AsMediaContainer::AS_PROPERTY_SNAPTOPOINTER ); // HashProperties.insert( "asSnapPoint", ( quint16 )AsMediaContainer::AS_PROPERTY_SNAPPOINT ); // HashProperties.insert( "asSnapTo", ( quint16 )AsMediaContainer::AS_PROPERTY_SNAPTO ); // HashProperties.insert( "asCanContain", ( quint16 )AsMediaContainer::AS_PROPERTY_CANCONTAIN ); // HashProperties.insert( "asContainPointer", ( quint16 )AsMediaContainer::AS_PROPERTY_CONTAINPOINTER ); // HashProperties.insert( "asContainWords", ( quint16 )AsMediaContainer::AS_PROPERTY_CONTAINWORDS ); // HashProperties.insert( "asContainRule", ( quint16 )AsMediaContainer::AS_PROPERTY_CONTAINRULE ); // HashProperties.insert( "asV2Type", ( quint16 )AsMediaContainer::AS_PROPERTY_V2TYPE ); // HashProperties.insert( "asConnectorList", ( quint16 )AsMediaContainer::AS_PROPERTY_CONNECTORLIST ); // HashProperties.insert( "asLabel", ( quint16 )AsMediaContainer::AS_PROPERTY_LABEL ); // HashProperties.insert( "asQuestionItem", ( quint16 )AsMediaContainer::AS_PROPERTY_QUESTIONITEM ); // HashProperties.insert( "asQuestionItemID", ( quint16 )AsMediaContainer::AS_PROPERTY_QUESTIONITEMID ); // HashProperties.insert( "asQuestionTag", ( quint16 )AsMediaContainer::AS_PROPERTY_QUESTIONTAG ); // HashProperties.insert( "asAllowSnapback", ( quint16 )AsMediaContainer::AS_PROPERTY_ALLOWSNAPBACK ); // HashProperties.insert( "asDragACopy", ( quint16 )AsMediaContainer::AS_PROPERTY_DRAGACOPY ); // HashProperties.insert( "asAsyncTestTag", ( quint16 )AsMediaContainer::AS_PROPERTY_ASYNCTESTTAG ); // HashProperties.insert( "asInteractMode", ( quint16 )AsMediaContainer::AS_PROPERTY_INTERACTMODE ); // From AsWidgetContainer HashProperties.insert( "placeHolderResource", ( quint16 )AsMediaContainer::AS_PROPERTY_RESOURCE ); // HashProperties.insert( "asForceOverLay", ( quint16 )AsMediaContainer::AS_PROPERTY_FORCEOVERLAY ); // From AsMediaContainer HashProperties.insert( "autoPlay", ( quint16 )AsMediaContainer::AS_PROPERTY_AUTOPLAY ); HashProperties.insert( "loop", ( quint16 )AsMediaContainer::AS_PROPERTY_LOOP ); // HashProperties.insert( "asHideControls", ( quint16 )AsMediaContainer::AS_PORPERTY_HIDECONTROLS ); // HashProperties.insert( "asForceAspect", ( quint16 )AsMediaContainer::AS_PROPERTY_FORCEASPECT ); HashProperties.insert( "resource", ( quint16 )AsMediaContainer::AS_PROPERTY_MEDIAFILERESOURCE ); HashProperties.insert( "transparentBackground", ( quint16 )AsMediaContainer::AS_PROPERTY_TRANSPARENTBACKGROUND ); } return HashProperties; } void AsMediaContainer::asSetMediaFileResource( AsMediaFileRes *pMediaFileResource ) { } AsMediaFileRes* AsMediaContainer::asGetMediaFileResourcePointer() { if( this->m_pMediaFileRes == NULL ) { if( m_mediaFileResource != 0 ) { this->m_pMediaFileRes = ( AsMediaFileRes* )this->m_pAsFactory->getResourceManager()->asLoadResource( AsObject::AS_OBJECT_MEDIAFILERES, asGetResource() ); if( m_pMediaFileRes && m_mediaFileResource != m_pMediaFileRes->asGetID() ) { QString sDataFilename = this->m_pAsFactory->getResourceManager()->asGetResourceDataFilename( m_pMediaFileRes ); QString sWorkingPath = this->m_pAsFactory->getResourceManager()->asGetWorkingPath(); m_sResFilePath = sWorkingPath + "/" + sDataFilename; //this can happen when duplicating multiple pages where a page which is not the current page ( so its resources are not loaded ) has content that has a storage of //AsInternalPathLink. AsInternalPathLink storage does not use a data file so the duplicated page uses the same resource as the existing page. The resource has a //reference in the resource manager with the id as per the existing page. The resource created above has a new id due to the duplication being classed as import in the //factory. The resource id needs to match the reference id so the resource is not unloaded when it should not be and can be found in the resource manager when needed. m_pMediaFileRes->asSetID( m_mediaFileResource ); } } } return this->m_pMediaFileRes; } bool AsMediaContainer::asCreateWidgetSurface() { return true; } bool AsMediaContainer::asCreateSurface() { return true; } bool AsMediaContainer::asCreateController() { return true; } bool AsMediaContainer::asDoDelayedInitMultiMedia() { return true; } QRect AsMediaContainer::asGetSurfaceRect() { return QRect(); } void AsMediaContainer::asOnLoseKeyboardFocus() { } void AsMediaContainer::asOnGainKeyboardFocus() { } void AsMediaContainer::asOnLoseHoverFocus() { } void AsMediaContainer::asOnGainHoverFocus() { } void AsMediaContainer::asOnActiveItem() { } void AsMediaContainer::asOnDeactiveItem() { } QPoint AsMediaContainer::asGetOrigin() { return QPoint(); } void AsMediaContainer::asMediaObjectStarted() { } void AsMediaContainer::asMediaObjectFinished( QObject* ) { } QString AsMediaContainer::asGetNewObjectName(quint32 nIndex) { QString strNextName; return strNextName; } enum AsWidgetContainer::AsPainterCanvasPaintBufferType AsMediaContainer::asCanvasPaintSourceType() { enum AsWidgetContainer::AsPainterCanvasPaintBufferType ret = AsWidgetContainer::AS_PAINTER_CANVAS_BUFFER_NULL; return ret; } QMutex* AsMediaContainer::asGetCanvasModeBufferProtection() { return NULL; } QPixmap *AsMediaContainer::asCanvasModeGetQPixmap() { QPixmap *pPixmap = NULL; return pPixmap; } void AsMediaContainer::asDoForceUpdate() { } enum AsWidgetContainer::AsPainterRenderMode AsMediaContainer::asPainterToRender() { return this->m_currentRenderMode; } void AsMediaContainer::asUpdateSurfacePosition() { } void AsMediaContainer::asDoPosForceDraw() { } void AsMediaContainer::asUpdateControllerPosition( const QRect & devicePositionOfSurface ) { } void AsMediaContainer::asGuiPluginUnloaded() { // we are just about to lose the GUI so destroy all media. this->asDestroyMediaObjectAndSurface(); } void AsMediaContainer::asGuiPluginLoaded() { } #include <QDebug> QPixmap* AsMediaContainer::asCaptureCurrentSurface() { QPixmap *pRet = NULL; return pRet; } void AsMediaContainer::asVideoCaptureInsertIntoFlipchart() { } void AsMediaContainer::asVideoCapturePlaceHolderImage() { this->asCapturePlaceHolderImage(); } bool AsMediaContainer::asIsControllerVisable() { return false; } void AsMediaContainer::asControllerShow() { // we don't show the controller if we have nothing active. } void AsMediaContainer::asControllerHide() { } void AsMediaContainer::asDoSurfaceDeviceSpaceRectChange( const QRect & newDeviceSpaceRect ) { } bool AsMediaContainer::event( QEvent *pEvent ) { return false; } bool AsMediaContainer::asInitMultiMedia() { return true; } void AsMediaContainer::asSetPlaceHolderOnFirstPaint( bool doIt ) { qDebug() << "AsMediaContainer::asSetPlaceHolderOnFirstPaint : " << this << ", doit : " << doIt; this->m_autoTakePlaceHolderImage = doIt; this->m_autoTakePlaceHolderFrameNumber = 1; this->m_surfacePaintCount = 0; } void AsMediaContainer::asOnFirstFrame() { } void AsMediaContainer::asOnDragAndDropFinished() { this->m_firstRenderDone = true; } void AsMediaContainer::asMediaObjectReleased() { if( this->m_pMultiMediaObject != NULL ) { this->m_firstRenderDone = false; this->m_currentRenderMode = AsWidgetContainer::AS_PAINTER_RENDER_IMAGE; this->m_pMultiMediaObject = NULL; this->asDestroyMediaObjectAndSurface(); } } bool AsMediaContainer::asIsActive() const { return false; } void AsMediaContainer::asOnSelected() { if( AsWidgetContainer::asIsActive() == false ) { } } void AsMediaContainer::asOnDeselected() { if( AsWidgetContainer::asIsActive() == false ) { } } void AsMediaContainer::asPushMediaSettingsToCache() { this->m_cachedForceOverlay = this->asGetForceOverlay(); this->m_cachedAutoPlay = this->m_autoPlay; this->m_cachedLoop = this->m_loop; this->m_cachedHideControls = this->m_hideControls; this->m_cachedForceAspect = this->m_forceAspect; this->m_cachedTransparentBackground = this->m_transparentBackground; } bool AsMediaContainer::asMediaSettingsDifferantThanCached() { if( this->m_cachedForceOverlay != this->asGetForceOverlay() ) { return true; } if( this->m_cachedAutoPlay != this->m_autoPlay ) { return true; } if( this->m_cachedLoop != this->m_loop ) { return true; } if( this->m_cachedHideControls != this->m_hideControls ) { return true; } if( this->m_cachedForceAspect != this->m_forceAspect ) { return true; } if( this->m_cachedTransparentBackground != this->m_transparentBackground ) { return true; } return false; } void AsMediaContainer::asRestartMediaObject() { if( this->m_pMultiMediaObject != NULL ) { // cache the current play/capture state so when we to the restart we know what to do. this->asDestroyMediaObjectAndSurface(); } if( this->asIsVisible() ) { this->asInitMultiMedia(); } } bool AsMediaContainer::asDoesSupportZReOrderingCommands() const { if (m_pMultiMediaObject) { } return true; } void AsMediaContainer::asMediaContainerProxyForMouseEvents( int , int , int ) { } bool AsMediaContainer::asGetPlaceholderRequired() { return m_autoTakePlaceHolderImage; } QString AsMediaContainer::getPropertyNameById(int nID) { return m_lProperties().key(nID); } int AsMediaContainer::getPropertyIdByName(QString name) const { return m_lProperties().value(name); } const Json::Value &AsMediaContainer::asResourceSerialized() { asGetMediaResourcePointer(); asGetResourcePointer(); if(m_pMediaFileRes){ m_resourceJsonObject["mediaUrl"] = m_sResFilePath.toStdString(); } if(m_pImageRes){ m_resourceJsonObject["tumbFileUrl"] = m_sTumbFilePath.toStdString(); } return m_resourceJsonObject; } AsResource *AsMediaContainer::asGetMediaResourcePointer(void) { if( this->m_pMediaFileRes == NULL ) { Variant var = property(AsMediaContainer::AS_PROPERTY_MEDIAFILERESOURCE); this->m_pMediaFileRes = ( AsMediaFileRes* )this->m_pAsFactory->getResourceManager()->asLoadResource( AsObject::AS_OBJECT_MEDIAFILERES, *static_cast<int*>(var.value)); if( m_pMediaFileRes && m_mediaFileResource != m_pMediaFileRes->asGetID() ) { QString sDataFilename = this->m_pAsFactory->getResourceManager()->asGetResourceDataFilename( m_pMediaFileRes ); QString sWorkingPath = this->m_pAsFactory->getResourceManager()->asGetWorkingPath(); m_sResFilePath = sWorkingPath + "/" + sDataFilename; //this can happen when duplicating multiple pages where a page which is not the current page ( so its resources are not loaded ) has content that has a storage of //AsInternalPathLink. AsInternalPathLink storage does not use a data file so the duplicated page uses the same resource as the existing page. The resource has a //reference in the resource manager with the id as per the existing page. The resource created above has a new id due to the duplication being classed as import in the //factory. The resource id needs to match the reference id so the resource is not unloaded when it should not be and can be found in the resource manager when needed. m_pMediaFileRes->asSetID( m_mediaFileResource ); } } return this->m_pMediaFileRes; } bool AsMediaContainer::isPropertyNeededSerialized(int nID) { if(getPropertyNameById(nID) == "ink"){ return false; } return true; } QString AsMediaContainer::typeName() { return "mediaContainer"; }
[ "zhangyi.sina@gmail.com" ]
zhangyi.sina@gmail.com
ab86e3926a4ddb7825b3674fc79a98e3bb9d7e29
8b5db3bc9f2afe52fce03a843e79454319f3c950
/hardware/invensense/65xx/libsensors_iio/SensorBase.cpp
c01d394dc76648d808f4232ee58a6008cc28bbf7
[ "Apache-2.0" ]
permissive
10114395/android-5.0.0_r5
619a6ea78ebcbb6d2c44a31ed0c3f9d5b64455b2
d023f08717af9bb61c2a273a040d3986a87422e1
refs/heads/master
2021-01-21T19:57:16.122808
2015-04-02T04:39:50
2015-04-02T04:39:50
33,306,407
2
2
null
2020-03-09T00:07:10
2015-04-02T11:58:28
C
UTF-8
C++
false
false
5,020
cpp
/* * Copyright (C) 2012 Invensense, 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 <fcntl.h> #include <errno.h> #include <math.h> #include <poll.h> #include <unistd.h> #include <stdlib.h> #include <dirent.h> #include <sys/select.h> #include <cutils/log.h> #include <linux/input.h> #include <cutils/properties.h> #include "SensorBase.h" /*****************************************************************************/ // static vars bool SensorBase::PROCESS_VERBOSE = false; bool SensorBase::EXTRA_VERBOSE = false; bool SensorBase::SYSFS_VERBOSE = false; bool SensorBase::FUNC_ENTRY = false; bool SensorBase::HANDLER_ENTRY = false; bool SensorBase::ENG_VERBOSE = false; bool SensorBase::INPUT_DATA = false; bool SensorBase::HANDLER_DATA = false; SensorBase::SensorBase(const char* dev_name, const char* data_name) : dev_name(dev_name), data_name(data_name), dev_fd(-1), data_fd(-1) { if (data_name) { data_fd = openInput(data_name); } char value[PROPERTY_VALUE_MAX]; property_get("invn.hal.verbose.basic", value, "0"); if (atoi(value)) { PROCESS_VERBOSE = true; } property_get("invn.hal.verbose.extra", value, "0"); if (atoi(value)) { EXTRA_VERBOSE = true; } property_get("invn.hal.verbose.sysfs", value, "0"); if (atoi(value)) { SYSFS_VERBOSE = true; } property_get("invn.hal.verbose.engineering", value, "0"); if (atoi(value)) { ENG_VERBOSE = true; } property_get("invn.hal.entry.function", value, "0"); if (atoi(value)) { FUNC_ENTRY = true; } property_get("invn.hal.entry.handler", value, "0"); if (atoi(value)) { HANDLER_ENTRY = true; } property_get("invn.hal.data.input", value, "0"); if (atoi(value)) { INPUT_DATA = true; } property_get("invn.hal.data.handler", value, "0"); if (atoi(value)) { HANDLER_DATA = true; } } SensorBase::~SensorBase() { if (data_fd >= 0) { close(data_fd); } if (dev_fd >= 0) { close(dev_fd); } } int SensorBase::open_device() { if (dev_fd<0 && dev_name) { dev_fd = open(dev_name, O_RDONLY); LOGE_IF(dev_fd<0, "Couldn't open %s (%s)", dev_name, strerror(errno)); } return 0; } int SensorBase::close_device() { if (dev_fd >= 0) { close(dev_fd); dev_fd = -1; } return 0; } int SensorBase::getFd() const { if (!data_name) { return dev_fd; } return data_fd; } int SensorBase::setDelay(int32_t handle, int64_t ns) { return 0; } bool SensorBase::hasPendingEvents() const { return false; } int64_t SensorBase::getTimestamp() { struct timespec t; t.tv_sec = t.tv_nsec = 0; clock_gettime(CLOCK_MONOTONIC, &t); return int64_t(t.tv_sec) * 1000000000LL + t.tv_nsec; } int SensorBase::openInput(const char *inputName) { int fd = -1; const char *dirname = "/dev/input"; char devname[PATH_MAX]; char *filename; DIR *dir; struct dirent *de; dir = opendir(dirname); if(dir == NULL) return -1; strcpy(devname, dirname); filename = devname + strlen(devname); *filename++ = '/'; while((de = readdir(dir))) { if(de->d_name[0] == '.' && (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0'))) continue; strcpy(filename, de->d_name); fd = open(devname, O_RDONLY); LOGV_IF(EXTRA_VERBOSE, "path open %s", devname); LOGI("path open %s", devname); if (fd >= 0) { char name[80]; if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) { name[0] = '\0'; } LOGV_IF(EXTRA_VERBOSE, "name read %s", name); if (!strcmp(name, inputName)) { strcpy(input_name, filename); break; } else { close(fd); fd = -1; } } } closedir(dir); LOGE_IF(fd < 0, "couldn't find '%s' input device", inputName); return fd; } int SensorBase::enable(int32_t handle, int enabled) { return 0; } int SensorBase::query(int what, int* value) { return 0; } int SensorBase::batch(int handle, int flags, int64_t period_ns, int64_t timeout) { return 0; } int SensorBase::flush(int handle) { return 0; }
[ "xdtianyu@gmail.com" ]
xdtianyu@gmail.com
3a44f2cdf257768de2add16bff061e58650d061b
250a85858a7f74ce26a200d3e5292ba3bb81624e
/Classes/Stone/Stone_Crab.h
5d39a96f1f3f76b1afa85f84fe84a4b6c839de83
[]
no_license
EEEEMAN/cocosOmok
459944b4e6c770ed101e6f6d710d00d72dac4aba
5492e11fec5f91177d3915a3e1edca5e1d95e9d3
refs/heads/master
2021-07-11T08:13:08.158375
2021-03-11T15:04:13
2021-03-11T15:04:13
31,811,057
0
0
null
null
null
null
UTF-8
C++
false
false
138
h
#ifndef __STONE_CRAB_H__ #define __STONE_CRAB_H__ #include "Stone.h" class Stone_Crab : public Stone { public: Stone_Crab(); }; #endif
[ "skrnfn2@gmail.com" ]
skrnfn2@gmail.com
2fb86e128bbe2cf6b6a1951019e86f179e8dd808
b2119eea95c182c183913cc3574e75e8689d3130
/SOURCES/sim/digi/wvrengage.cpp
4e4d25b1ad11d3a33a23dd25d10602433ea0862d
[ "Unlicense" ]
permissive
1059444127/Negev-Storm
11233b1b3741f643ff14b5aa7b6ee08de40ab69f
86de63e195577339f6e4a94198bedd31833a8be8
refs/heads/master
2021-05-28T10:48:53.536896
2015-02-08T10:42:15
2015-02-08T10:42:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,006
cpp
#include "stdhdr.h" #include "digi.h" #include "simveh.h" #include "object.h" #include "aircrft.h" #include "airframe.h" #include "simdrive.h" #include "classtbl.h" #include "entity.h" #include "fakerand.h" #include "flight.h" #include "wingorder.h" #include "playerop.h" #include "radar.h" // 2002-02-09 S.G. // #define DEBUG_WVR_ENGAGE #define MANEUVER_DEBUG #ifdef MANEUVER_DEBUG #include "Graphics\include\drawbsp.h" extern int g_nShowDebugLabels; #endif extern bool g_bUseNewCanEnage; // 2002-03-11 S.G. #ifdef DEBUG_WVR_ENGAGE #define PrintWVRMode(a) MonoPrint(a) #else #define PrintWVRMode(a) #endif int CanEngage (AircraftClass *self, int combatClass, SimObjectType* targetPtr, int type); // 2002-03-11 MODIFIED BY S.G. Added the 'type' parameter FalconEntity* SpikeCheck (AircraftClass* self, FalconEntity *byHim = NULL, int *data = NULL);// 2002-02-10 S.G. /* Check for Entry/Exit condition into WVR */ void DigitalBrain::WvrEngageCheck(void) { float engageRange; engageRange = 3.0F * NM_TO_FT; /*---------------------*/ /* return if no target */ /*---------------------*/ if (targetPtr == NULL || (mpActionFlags[AI_ENGAGE_TARGET] != AI_AIR_TARGET && missionClass != AAMission && !missionComplete) || curMode == RTBMode) // 2002-03-04 MODIFIED BY S.G. Use new enum type { //me123 ClearTarget(); engagementTimer = 0; } /*-------*/ /* entry */ /*-------*/ else if (curMode != WVREngageMode && targetData->range < engageRange && (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter()) && // 2002-03-05 MODIFIED BY S.G. airplane, choppers and fligth are ok in here (choppers only makes it here if it passed the SensorFusion test first) SimLibElapsedTime > engagementTimer && CanEngage (self, self->CombatClass(), targetPtr, WVRManeuver)) // 2002-03-11 MODIFIED BY S.G. Added parameter WVRManeuver { AddMode(WVREngageMode); } else if (curMode == WVREngageMode && targetPtr->localData->range < 1.5F * engageRange && CanEngage(self, self->CombatClass(), targetPtr, WVRManeuver)) // 2002-03-11 MODIFIED BY S.G. Added parameter WVRManeuver { AddMode(WVREngageMode); } else { engagementTimer = 0; } } /* ** Name: WVREngage ** Description: ** Main function for within visual range engagement. ** Basically this function just checks the tactics timer to determiine ** when we next need to eval our BFM stuff. It then runs the current ** tactic. */ void DigitalBrain::WvrEngage(void) { int lastTactic = wvrCurrTactic; float left=0.0F, right=0.0F, cur=0.0F; int myCombatClass = self->CombatClass(); int hisCombatClass=0; ManeuverChoiceTable *theIntercept=NULL; int numChoices=0, myChoice=0; #ifdef MANEUVER_DEBUG char tmpchr[40]; strcpy(tmpchr, "WvrEngage"); #endif radModeSelect = 3;//default // 2002-01-27 MN No need to go through all the stuff if we need to avoid the ground if(groundAvoidNeeded) return; int mergeTime = -1 * (int)(SimLibElapsedTime + 2); /*-------------------*/ /* bail if no target */ /*-------------------*/ if (targetPtr == NULL) { wvrCurrTactic = WVR_NONE; #ifdef MANEUVER_DEBUG strcpy(tmpchr,"Wvr NoTarget"); if (g_nShowDebugLabels & 0x10) { if (g_nShowDebugLabels & 0x8000) { if (((AircraftClass*) self)->af->GetSimpleMode()) strcat(tmpchr, " SIMP"); else strcat(tmpchr, " COMP"); } if ( self->drawPointer ) ((DrawableBSP*)self->drawPointer)->SetLabel (tmpchr, ((DrawableBSP*)self->drawPointer)->LabelColor()); } #endif return; } // do we need to evaluate our position? if ( SimLibElapsedTime > wvrTacticTimer || wvrCurrTactic == WVR_NONE ) { // 2002-02-09 ADDED BY S.G. Change our radarMode to digiSTT if we have been detected and we have a radar to start with // Look up intercept type for all A/C if (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter()) { // Find the data table for these two types of A/C hisCombatClass = targetPtr->BaseData()->CombatClass(); // 2002-02-26 MODIFIED BY S.G. Removed the AircraftClass cast // 2002-03-27 MN CTD fix - hisCombatClass is 999 in case of a FalcEnt. Need to add CombatClass() return call to helo.h F4Assert(hisCombatClass < NumMnvrClasses); if (hisCombatClass >= NumMnvrClasses) hisCombatClass = NumMnvrClasses - 1; theIntercept = &(maneuverData[myCombatClass][hisCombatClass]); numChoices = theIntercept->numMerges; if (numChoices) { myChoice = rand() % numChoices;// changed back WvrMergeUnlimited;// me123 status test. lets do smart merge for now. switch (theIntercept->merge[myChoice]) { case WvrMergeHitAndRun: mergeTime = 15 * SEC_TO_MSEC; break; case WvrMergeLimited: mergeTime = 60 * SEC_TO_MSEC; break; case WvrMergeUnlimited: mergeTime = -1 * (int)(SimLibElapsedTime + 2); break; } } } // run logic for next tactic WvrChooseTactic(); // When do we get out of the fight if (SimLibElapsedTime > engagementTimer) { engagementTimer = SimLibElapsedTime + mergeTime; } // chooose next time to check // based on current tactic switch( wvrCurrTactic ) { case WVR_RANDP: PrintWVRMode( "DIGI WVR RANDP\n" ); wvrTacticTimer = SimLibElapsedTime + 1000;//me123 status test chenged from 10 break; case WVR_ROOP: PrintWVRMode( "DIGI WVR ROOP\n" ); wvrTacticTimer = SimLibElapsedTime + 250;//me123 from 5000 break; case WVR_OVERB: PrintWVRMode( "DIGI WVR OVERB\n" ); wvrTacticTimer = SimLibElapsedTime + 3000;//me123 from 5000 break; case WVR_GUNJINK: PrintWVRMode( "DIGI WVR GUN JINK\n" ); wvrTacticTimer = SimLibElapsedTime + 500;//me123 status test chenged from 6 break; case WVR_STRAIGHT: // note: we'll likely want to set how long we go straight // for by pilot skill level PrintWVRMode( "DIGI WVR STRAIGHT\n" ); wvrTacticTimer = SimLibElapsedTime + 1500; if (lastTactic != wvrCurrTactic) { if (af->theta > 0.0F) holdAlt = max (5000.0F, -self->ZPos()); else holdAlt = 0.0F; } break; case WVR_AVOID: PrintWVRMode( "DIGI WVR AVOID\n" ); wvrTacticTimer = SimLibElapsedTime + 1500; if (lastTactic != wvrCurrTactic) { holdAlt = max (5000.0F, -self->ZPos()); } holdPsi = targetPtr->BaseData()->Yaw() + 180.0F * DTR; if (holdPsi > 180.0F * DTR) holdPsi -= 360.0F * DTR; break; case WVR_BEAM_RETURN: if (lastTactic != wvrCurrTactic) { PrintWVRMode( "DIGI WVR BEAM RETURN\n" ); wvrTacticTimer = SimLibElapsedTime + 10000; holdAlt = max (5000.0F, -self->ZPos()); // Find left and right beam angles // Note: Yaw is 0 - 359.9999 left = targetPtr->BaseData()->Yaw() - 90.0F * DTR; right = targetPtr->BaseData()->Yaw() + 90.0F * DTR; // Normalize if (right > 180.0F * DTR) right -= 360.0F * DTR; if (left > 180.0F * DTR) left -= 360.0F * DTR; cur = self->Yaw(); if (cur > 180.0F * DTR) cur -= 360.0F * DTR; // Go to the closer if (fabs (left - cur) < fabs (right - cur)) { holdPsi = left; } else { holdPsi = right; } } break; case WVR_BEAM: PrintWVRMode( "DIGI WVR BEAM\n" ); wvrTacticTimer = SimLibElapsedTime + 1500; if (lastTactic != wvrCurrTactic) { holdAlt = max (5000.0F, -self->ZPos()); } // Find left and right beam angles // Note: Yaw is 0 - 359.9999 left = targetPtr->BaseData()->Yaw() - 90.0F * DTR; right = targetPtr->BaseData()->Yaw() + 90.0F * DTR; // Normalize if (right > 180.0F * DTR) right -= 360.0F * DTR; if (left > 180.0F * DTR) left -= 360.0F * DTR; cur = self->Yaw(); if (cur > 180.0F * DTR) cur -= 360.0F * DTR; // Go to the closer if (fabs (left - cur) < fabs (right - cur)) { holdPsi = left; } else { holdPsi = right; } break; case WVR_BUGOUT: PrintWVRMode( "DIGI WVR BUGOUT\n" ); wvrTacticTimer = SimLibElapsedTime + 5000; if (lastTactic != wvrCurrTactic) { holdAlt = max (5000.0F, -self->ZPos()); } // Find a heading directly away from the target cur = TargetAz (self, targetPtr); if (cur > 0.0F) cur = self->Yaw() - (180.0F*DTR - cur); else cur = self->Yaw() - (-180.0F*DTR - cur); // Normalize if (cur > 180.0F * DTR) cur -= 360.0F * DTR; holdPsi = cur; break; default: PrintWVRMode( "DIGI NO MODE\n" ); wvrTacticTimer = SimLibElapsedTime + 500;//me123 from 5000 } } // run the tactic switch( wvrCurrTactic ) { case WVR_RANDP: RollAndPull(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr Roll&Pull"); #endif break; case WVR_ROOP: WvrRollOutOfPlane(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr RollOutOfPlane"); #endif break; case WVR_BUGOUT: WvrBugOut(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr Bugout"); #endif break; case WVR_STRAIGHT: WvrStraight(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr straight"); #endif break; case WVR_GUNJINK: WvrGunJink(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr Gunjink"); #endif break; case WVR_OVERB: WvrOverBank( 45.0f * DTR ); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr overbank"); #endif break; case WVR_AVOID: WvrAvoid(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr avoid"); #endif break; case WVR_BEAM: WvrBeam(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr beam"); #endif break; case WVR_BEAM_RETURN: if (SimLibElapsedTime > wvrTacticTimer) { RollAndPull(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr RandP"); #endif } else { WvrBeam(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr Beam"); #endif } break; default: RollAndPull(); #ifdef MANEUVER_DEBUG sprintf(tmpchr,"Wvr Roll&Pull"); #endif break; } // last tactic executed wvrPrevTactic = wvrCurrTactic; #ifdef MANEUVER_DEBUG if (g_nShowDebugLabels & 0x10) { if (g_nShowDebugLabels & 0x50) // add radar mode { RadarClass* theRadar = (RadarClass*)FindSensor(self, SensorClass::Radar); if (theRadar) { if (theRadar->digiRadarMode = RadarClass::DigiSTT) strcat(tmpchr, " STT"); else if (theRadar->digiRadarMode = RadarClass::DigiSAM) strcat(tmpchr, " SAM"); else if (theRadar->digiRadarMode = RadarClass::DigiTWS) strcat(tmpchr, " TWS"); else if (theRadar->digiRadarMode = RadarClass::DigiRWS) strcat(tmpchr, " RWS"); else if (theRadar->digiRadarMode = RadarClass::DigiOFF) strcat(tmpchr, " OFF"); else strcat(tmpchr, " UNKNOWN"); } } if (g_nShowDebugLabels & 0x8000) { if (((AircraftClass*) self)->af->GetSimpleMode()) strcat(tmpchr, " SIMP"); else strcat(tmpchr, " COMP"); } if ( self->drawPointer ) ((DrawableBSP*)self->drawPointer)->SetLabel (tmpchr, ((DrawableBSP*)self->drawPointer)->LabelColor()); } #endif } /* ** Name: WvrChooseTactic ** Description: ** Try and make some not completely idiotic decisions.... */ void DigitalBrain::WvrChooseTactic(void) { int myCombatClass = self->CombatClass(); int hisCombatClass; ManeuverChoiceTable *theIntercept; int aceAvoid = FALSE; if (!IsSetATC(AceGunsEngage) && SkillLevel() >= 3) { if (maxAAWpnRange > 0 && maxAAWpnRange < 1.0F * NM_TO_FT) aceAvoid = TRUE; } //TJL 12/06/03 Change to targetPtr //if (threatPtr) if (targetPtr) { // Look up intercept type for all A/C // if (targetPtr->BaseData()->IsSim() && targetPtr->BaseData()->IsAirplane()) if (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter()) // 2002-03-05 MODIFIED BY S.G. airplane, choppers and fligth are ok in here (choppers only makes it here if it passed the SensorFusion test first) { // Find the data table for these two types of A/C hisCombatClass = targetPtr->BaseData()->CombatClass(); // 2002-02-26 MODIFIED BY S.G. Removed the AircraftClass cast theIntercept = &(maneuverData[myCombatClass][hisCombatClass]); // No intercepts or Choose not to, or no weapons, or Guns only and ACE in campaign if (theIntercept->numIntercepts == 0 || theIntercept->intercept[0] == BvrNoIntercept || maxAAWpnRange == 0 || aceAvoid) { // Can't go offensive, should we be defensive, or just keep running? if (targetData->range > 1.5F * NM_TO_FT || targetData->ataFrom > 25.0F * DTR) wvrCurrTactic = WVR_BUGOUT; else wvrCurrTactic = WVR_GUNJINK; // Check for reload WeaponSelection(); } else {// hmm this beaming stuff should be bwr tactics, we dont' do that when at visual range // it takes place outside 10nm which is not within this rutine's paremeters so it's kinda disregarded if (targetData->range > 25.0F * NM_TO_FT) wvrCurrTactic = WVR_AVOID; else if (targetData->range > 15.0F * NM_TO_FT) wvrCurrTactic = WVR_BEAM ;//me123 status test chenged from WVR_BEAM_RETURN else if (targetData->range > 10.0F * NM_TO_FT && wvrCurrTactic != WVR_BEAM_RETURN)//me123 status test chenged from >3 { wvrCurrTactic = WVR_BEAM_RETURN; } else { wvrCurrTactic = WVR_RANDP; } } } else { wvrCurrTactic = WVR_AVOID; } } else /*-----------------------------*/ /* logic is geometry dependent */ /*-----------------------------*/ //ME123 WE DEFINATLY NEED TO THINK ABOUT NOSE TO NOSE OR NOSE TO TAIL FIGHT HERE ! // AT THE MOMENT WE JUST ROLL AND PULL NOMATTER WHAT :-( // we are pointing at him and him at us and we are too slow // so let's exploit that we are not emidiatly threatened and get some energy //TJL 12/06/03 Appears someone forgot a * DTR //if (targetData->ata <= 90.0F * DTR && targetData->ataFrom <= 90.0F) if (targetData->ata <= 90.0F * DTR && targetData->ataFrom <= 90.0F * DTR) { // how stupid are we? // MODIFIED BY S.G. af->vt is in feet/second. cornerSpeed is in knot/hour! // NEEDS TO BE DONE IN THE 1.08 EXE FIRST TO BE CONSISTANT if ( af->vt < cornerSpeed * 0.3F ) // if ( self->GetKias() < cornerSpeed * 0.3F ) { wvrCurrTactic = WVR_STRAIGHT; } /*--------------*/ /* me -> <- him */ /*--------------*/ else if (targetData->ataFrom <= 90.0F * DTR) { wvrCurrTactic = WVR_RANDP; } /*--------------*/ /* me -> him -> */ /*--------------*/ else if (targetData->ataFrom >= 90.0F * DTR) { wvrCurrTactic = WVR_RANDP; } } /*--------------*/ /* him -> me -> */ /*--------------*/ else if (targetData->ata > 90.0F * DTR) { if ( self->GetKias() < cornerSpeed * 0.6f )//me123 status test. accelerate if we are below 210cas changed from 0.3 { wvrCurrTactic = WVR_RANDP;//me123 WVR_STRAIGHT; } else { wvrCurrTactic = WVR_RANDP; } } } void DigitalBrain::WvrRollOutOfPlane(void) { float eroll; /*-----------------------*/ /* first pass, save roll */ /*-----------------------*/ if ( wvrPrevTactic != WVR_ROOP ) { /*----------------------------------------------------*/ /* want to roll toward the vertical but limit to keep */ /* droll < 45 degrees. */ /*----------------------------------------------------*/ if (self->Roll() >= 0.0) { newroll = self->Roll() - 45.0F*DTR;//me123 from 45. smaller repossition } else { newroll = self->Roll() + 45.0F*DTR;//me123 from 45. smaller repossition } } /*------------*/ /* roll error */ /*------------*/ eroll = newroll - self->Roll(); /*-----------------------------*/ /* roll the shortest direction */ /*-----------------------------*/ /* if (eroll < -180.0F*DTR) eroll += 360.0F*DTR; else if (eroll > 180.0F*DTR) eroll -= 360.0F*DTR; */ // me123 hmm nonono we are too fast that's why we need to do this MachHold(cornerSpeed, self->GetKias(), TRUE); MachHold(150.0f, self->GetKias(), TRUE); SetPstick(af->GsAvail(), maxGs, AirframeClass::GCommand); SetRstick(eroll * RTD); } void DigitalBrain::WvrOverBank (float delta) { float eroll; //-----------------------*/ // Find a new roll angle */ // relative to target //-----------------------*/ if ( wvrPrevTactic != WVR_OVERB ) { if (self->Roll() > 0.0F) newroll = targetData->droll + delta; else newroll = targetData->droll - delta; if (newroll > 180.0F * DTR) newroll -= 360.0F * DTR; else if (newroll < -180.0F * DTR) newroll += 360.0F * DTR; } eroll = newroll - self->Roll(); MachHold(cornerSpeed, self->GetKias(), TRUE); SetRstick(eroll * RTD); SetPstick(af->GsAvail(), maxGs, AirframeClass::GCommand); } /* ** Name: WvrStraight ** Description: ** Level out and fly straight at high speed. */ void DigitalBrain::WvrStraight ( void ) { if (holdAlt < 0.0F) AltitudeHold (holdAlt); else pStick = 0.0F; MachHold(2.0F*cornerSpeed, self->GetKias(), TRUE); // If alpha > alphamax/2 unload to accel if (af->alpha > 15.0F) SetPstick (-1.0F, maxGs, AirframeClass::GCommand); } /* ** Name: WvrAvoid ** Description: ** Try to fly around the threat */ void DigitalBrain::WvrAvoid ( void ) { HeadingAndAltitudeHold (holdPsi, holdAlt); MachHold(2.0F*cornerSpeed, self->GetKias(), TRUE); } /* ** Name: WvrBeam ** Description: ** Keep aspect at 90 */ void DigitalBrain::WvrBeam ( void ) { HeadingAndAltitudeHold (holdPsi, holdAlt); MachHold(2.0F*cornerSpeed, self->GetKias(), TRUE); // We be chaff'n and flare'n if (((AircraftClass*)self)->HasPilot()) { if (SimLibElapsedTime > self->ChaffExpireTime() + 500) { ((AircraftClass*)self)->dropChaffCmd = TRUE; } if (SimLibElapsedTime > self->FlareExpireTime() + 500) { ((AircraftClass*)self)->dropFlareCmd = TRUE; } } } /* ** Name: WvrBugOut ** Description: ** Level out and fly straight at high speed. ** Head for the hills */ void DigitalBrain::WvrBugOut ( void ) { HeadingAndAltitudeHold (holdPsi, holdAlt); MachHold(2.0F*cornerSpeed, self->GetKias(), TRUE); } /* ** Name: Guns Jink ** Description: ** Jink around */ void DigitalBrain::WvrGunJink ( void ) { GunsJink(); } /* ** Name: SetThreat ** Description: ** Creates a SimObjectType struct for the entity, sets the threatPtr, ** References the target. Any pre-existing target is dereferenced. */ void DigitalBrain::SetThreat( FalconEntity *obj ) { short edata[6]; int randNum, response; // don't pre-empt current threat with a new threat until we've been // dealing with the threat for a while unless the threat is NULL if ( obj != NULL && threatTimer > 0.0f ) return; F4Assert (!obj || !obj->IsSim() || !obj->IsHelicopter()); if (obj && obj->OnGround())//Cobra We want to nail those targeting us! { SetGroundTarget(obj); return; } if ( obj && !obj->OnGround() ) { // if the threat is the same as our target, we don't // need to do anything since we're already dealing // with it if ( targetPtr && targetPtr->BaseData() == obj ) { return; } // create new target data and reference it #ifdef DEBUG //threatPtr = new SimObjectType( OBJ_TAG, self, obj ); #else threatPtr = new SimObjectType( obj ); #endif threatTimer = 10.0f; SetTarget (threatPtr); // Occasionally send a radio call stating defensive or ask for help randNum = rand() % 100; if (randNum < 5) { // Yell for help edata[0] = ((FlightClass*)self->GetCampaignObject())->callsign_id; edata[1] = (((FlightClass*)self->GetCampaignObject())->callsign_num - 1) * 4 + self->GetCampaignObject()->GetComponentIndex(self) + 1; AiMakeRadioResponse( self, rcHELPNOW, edata ); } else if (randNum < 40) { //Inform flight if(threatPtr->localData->range > 2.0F * NM_TO_FT) { if(PlayerOptions.BullseyeOn()) { response = rcENGDEFENSIVEA; } else { response = rcENGDEFENSIVEB; } edata[0] = ((FlightClass*)self->GetCampaignObject())->callsign_id; edata[1] = (((FlightClass*)self->GetCampaignObject())->callsign_num - 1) * 4 + isWing; edata[2] = (short) SimToGrid(threatPtr->BaseData()->YPos()); edata[3] = (short) SimToGrid(threatPtr->BaseData()->XPos()); edata[4] = (short) threatPtr->BaseData()->ZPos(); } else { edata[0] = isWing; response = rcENGDEFENSIVEC; } // Send the message AiMakeRadioResponse( self, response, edata ); } threatPtr = NULL; } } // 2002-03-11 MODIFIED BY S.G. Too many changes to track them all, rewrite it... #if 1 int CanEngage (AircraftClass *self, int combatClass, SimObjectType* targetPtr, int type) { int hisCombatClass; DigitalBrain::ManeuverChoiceTable *theIntercept; int retBvr = TRUE; int retWvr = TRUE; // Check for aircraft, choppers or flights if (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter()) { // If asked to use the new code, then honor the request if (g_bUseNewCanEnage) { // Find the data table for these two types of flying objects // But don't assume you know it, see if id'ed first... CampBaseClass *campBaseObj; if (targetPtr->BaseData()->IsSim()) campBaseObj = ((SimBaseClass*)targetPtr->BaseData())->GetCampaignObject(); else campBaseObj = ((CampBaseClass *)targetPtr->BaseData()); // If it doesn't have a campaign object or it's identified... END OF ADDED SECTION plus the use of campBaseObj below if (!campBaseObj || campBaseObj->GetIdentified(self->GetTeam())) { // Yes, now you can get its combat class! hisCombatClass = targetPtr->BaseData()->CombatClass(); } else { //TJL Combatclass numbers are kinda hosed, assume the worst at all times if you can't determine // No :-( Then guestimate it... (from RIK's BVR code) hisCombatClass = 4; /*if ((targetPtr->BaseData()->GetVt() * FTPSEC_TO_KNOTS > 300.0f || targetPtr->BaseData()->ZPos() < -10000.0f)) { //this might be a combat jet.. asume the worst hisCombatClass = 4; } else if (targetPtr->BaseData()->GetVt() * FTPSEC_TO_KNOTS > 250.0f) { // this could be a a-a capable thingy, but if it's is it's low level so it's a-a long range shoot capabilitys are not great hisCombatClass = 1; } else { // this must be something unthreatening...it's below 250 knots but it's still unidentified so... hisCombatClass = 0; }*/ } } else hisCombatClass = targetPtr->BaseData()->CombatClass(); theIntercept = &(DigitalBrain::maneuverData[combatClass][hisCombatClass]); if (type & DigitalBrain::WVRManeuver) { // If no capability, don't go say you can engage!!! if (theIntercept->numMerges == 0) retWvr = FALSE; else if (theIntercept->numMerges == 1) { // Need to be real close for a hit and run if (theIntercept->merge[0] == DigitalBrain::WvrMergeHitAndRun && targetPtr->localData->ata > 45.0F * DTR) { retWvr = FALSE; } // Can't be behind you for limited else if (theIntercept->merge[0] == DigitalBrain::WvrMergeLimited && targetPtr->localData->ata > 90.0F * DTR) { retWvr = FALSE; } } } else retWvr = FALSE; // Check for intercepts if in BVR... if (type & DigitalBrain::BVRManeuver) { if (theIntercept->numIntercepts == 0) retBvr = FALSE; } else retBvr = FALSE; // Fail safe if (type == 0) { retWvr = FALSE; retBvr = FALSE; } } // 2002-03-11 ADDED BY S.G. If it's not even an air thingy, why do you say you can engage it??? else { retWvr = FALSE; retBvr = FALSE; } return retBvr | retWvr; } #else int CanEngage (int combatClass, SimObjectType* targetPtr) { int hisCombatClass; DigitalBrain::ManeuverChoiceTable *theIntercept; int retval = TRUE; // Assume you can engage // Only check for A/C // if (targetPtr->BaseData()->IsSim() && targetPtr->BaseData()->IsAirplane()) if (targetPtr->BaseData()->IsAirplane() || targetPtr->BaseData()->IsFlight() || targetPtr->BaseData()->IsHelicopter()) // 2002-03-05 MODIFIED BY S.G. airplane, choppers and fligth are ok in here (choppers only makes it here if it passed the SensorFusion test first) { // Find the data table for these two types of A/C hisCombatClass = targetPtr->BaseData()->CombatClass(); // 2002-02-26 MODIFIED BY S.G. Removed the AircraftClass cast theIntercept = &(DigitalBrain::maneuverData[combatClass][hisCombatClass]); if (theIntercept->numMerges == 1) { // Need to be real close for a hit and run if (theIntercept->merge[0] == DigitalBrain::WvrMergeHitAndRun && targetPtr->localData->ata > 45.0F * DTR) { retval = FALSE; } // Can't be behind you for limited else if (theIntercept->merge[0] == DigitalBrain::WvrMergeLimited && targetPtr->localData->ata > 90.0F * DTR) { retval = FALSE; } } } return retval; } #endif
[ "israelyflightsimulator@gmail.com" ]
israelyflightsimulator@gmail.com
24f474e4b694f16c8e54d0878ae215a8e83425df
9c0af3a75a7ca3250ff6bebcb17e76af5315a31a
/loam_velodyne/include/loam_velodyne/BasicScanRegistration.h
7693be710cc894c7c27410232230c81dc82313d6
[ "BSD-3-Clause" ]
permissive
arjo129/darpa_ugv_highlevel
7fa45fb070803b9f99a2bfe6e91f745908454b76
806ff902616ca3252b0099c21e0a07a09c65b4e5
refs/heads/master
2023-06-20T18:06:26.023670
2020-08-21T07:21:32
2020-08-21T07:21:32
210,164,633
2
0
null
null
null
null
UTF-8
C++
false
false
9,391
h
#pragma once #include <utility> #include <vector> #include <pcl/point_cloud.h> #include "Angle.h" #include "Vector3.h" #include "CircularBuffer.h" #include "time_utils.h" namespace loam { /** \brief A pair describing the start end end index of a range. */ typedef std::pair<size_t, size_t> IndexRange; /** Point label options. */ enum PointLabel { CORNER_SHARP = 2, ///< sharp corner point CORNER_LESS_SHARP = 1, ///< less sharp corner point SURFACE_LESS_FLAT = 0, ///< less flat surface point SURFACE_FLAT = -1 ///< flat surface point }; /** Scan Registration configuration parameters. */ class RegistrationParams { public: RegistrationParams(const float& scanPeriod_ = 0.1, const int& imuHistorySize_ = 200, const int& nFeatureRegions_ = 6, const int& curvatureRegion_ = 5, const int& maxCornerSharp_ = 2, const int& maxSurfaceFlat_ = 4, const float& lessFlatFilterSize_ = 0.2, const float& surfaceCurvatureThreshold_ = 0.1); /** The time per scan. */ float scanPeriod; /** The size of the IMU history state buffer. */ int imuHistorySize; /** The number of (equally sized) regions used to distribute the feature extraction within a scan. */ int nFeatureRegions; /** The number of surrounding points (+/- region around a point) used to calculate a point curvature. */ int curvatureRegion; /** The maximum number of sharp corner points per feature region. */ int maxCornerSharp; /** The maximum number of less sharp corner points per feature region. */ int maxCornerLessSharp; /** The maximum number of flat surface points per feature region. */ int maxSurfaceFlat; /** The voxel size used for down sizing the remaining less flat surface points. */ float lessFlatFilterSize; /** The curvature threshold below / above a point is considered a flat / corner point. */ float surfaceCurvatureThreshold; }; /** IMU state data. */ typedef struct IMUState { /** The time of the measurement leading to this state (in seconds). */ Time stamp; /** The current roll angle. */ Angle roll; /** The current pitch angle. */ Angle pitch; /** The current yaw angle. */ Angle yaw; /** The accumulated global IMU position in 3D space. */ Vector3 position; /** The accumulated global IMU velocity in 3D space. */ Vector3 velocity; /** The current (local) IMU acceleration in 3D space. */ Vector3 acceleration; /** \brief Interpolate between two IMU states. * * @param start the first IMUState * @param end the second IMUState * @param ratio the interpolation ratio * @param result the target IMUState for storing the interpolation result */ static void interpolate(const IMUState& start, const IMUState& end, const float& ratio, IMUState& result) { float invRatio = 1 - ratio; result.roll = start.roll.rad() * invRatio + end.roll.rad() * ratio; result.pitch = start.pitch.rad() * invRatio + end.pitch.rad() * ratio; if (start.yaw.rad() - end.yaw.rad() > M_PI) { result.yaw = start.yaw.rad() * invRatio + (end.yaw.rad() + 2 * M_PI) * ratio; } else if (start.yaw.rad() - end.yaw.rad() < -M_PI) { result.yaw = start.yaw.rad() * invRatio + (end.yaw.rad() - 2 * M_PI) * ratio; } else { result.yaw = start.yaw.rad() * invRatio + end.yaw.rad() * ratio; } result.velocity = start.velocity * invRatio + end.velocity * ratio; result.position = start.position * invRatio + end.position * ratio; }; } IMUState; class BasicScanRegistration { public: /** \brief Process a new cloud as a set of scanlines. * * @param relTime the time relative to the scan time */ void processScanlines(const Time& scanTime, std::vector<pcl::PointCloud<pcl::PointXYZI>> const& laserCloudScans); bool configure(const RegistrationParams& config = RegistrationParams()); /** \brief Update new IMU state. NOTE: MUTATES ARGS! */ void updateIMUData(Vector3& acc, IMUState& newState); /** \brief Project a point to the start of the sweep using corresponding IMU data * * @param point The point to modify * @param relTime The time to project by */ void projectPointToStartOfSweep(pcl::PointXYZI& point, float relTime); auto const& imuTransform () { return _imuTrans ; } auto const& sweepStart () { return _sweepStart ; } auto const& laserCloud () { return _laserCloud ; } auto const& cornerPointsSharp () { return _cornerPointsSharp ; } auto const& cornerPointsLessSharp () { return _cornerPointsLessSharp; } auto const& surfacePointsFlat () { return _surfacePointsFlat ; } auto const& surfacePointsLessFlat () { return _surfacePointsLessFlat; } auto const& config () { return _config ; } // auto const& laserCloudGroundScansDeep () { return _laserCloudGroundScansDeep ; } private: /** \brief Check is IMU data is available. */ inline bool hasIMUData() { return _imuHistory.size() > 0; }; /** \brief Set up the current IMU transformation for the specified relative time. * * @param relTime the time relative to the scan time */ void setIMUTransformFor(const float& relTime); /** \brief Project the given point to the start of the sweep, using the current IMU state and position shift. * * @param point the point to project */ void transformToStartIMU(pcl::PointXYZI& point); /** \brief Prepare for next scan / sweep. * * @param scanTime the current scan time * @param newSweep indicator if a new sweep has started */ void reset(const Time& scanTime); /** \brief Extract features from current laser cloud. * * @param beginIdx the index of the first scan to extract features from */ void extractFeatures(const uint16_t& beginIdx = 0); /** \brief Set up region buffers for the specified point range. * * @param startIdx the region start index * @param endIdx the region end index */ void setRegionBuffersFor(const size_t& startIdx, const size_t& endIdx); /** \brief Set up scan buffers for the specified point range. * * @param startIdx the scan start index * @param endIdx the scan start index */ void setScanBuffersFor(const size_t& startIdx, const size_t& endIdx); /** \brief Mark a point and its neighbors as picked. * * This method will mark neighboring points within the curvature region as picked, * as long as they remain within close distance to each other. * * @param cloudIdx the index of the picked point in the full resolution cloud * @param scanIdx the index of the picked point relative to the current scan */ void markAsPicked(const size_t& cloudIdx, const size_t& scanIdx); /** \brief Try to interpolate the IMU state for the given time. * * @param relTime the time relative to the scan time * @param outputState the output state instance */ void interpolateIMUStateFor(const float& relTime, IMUState& outputState); void updateIMUTransform(); private: RegistrationParams _config; ///< registration parameter pcl::PointCloud<pcl::PointXYZI> _laserCloud; ///< full resolution input cloud std::vector<IndexRange> _scanIndices; ///< start and end indices of the individual scans withing the full resolution cloud pcl::PointCloud<pcl::PointXYZI> _cornerPointsSharp; ///< sharp corner points cloud pcl::PointCloud<pcl::PointXYZI> _cornerPointsLessSharp; ///< less sharp corner points cloud pcl::PointCloud<pcl::PointXYZI> _surfacePointsFlat; ///< flat surface points cloud pcl::PointCloud<pcl::PointXYZI> _surfacePointsLessFlat; ///< less flat surface points cloud // pcl::PointCloud<pcl::PointXYZI> _laserCloudGroundScansDeep; ///Ground scan data points Time _sweepStart; ///< time stamp of beginning of current sweep Time _scanTime; ///< time stamp of most recent scan IMUState _imuStart; ///< the interpolated IMU state corresponding to the start time of the currently processed laser scan IMUState _imuCur; ///< the interpolated IMU state corresponding to the time of the currently processed laser scan point Vector3 _imuPositionShift; ///< position shift between accumulated IMU position and interpolated IMU position size_t _imuIdx = 0; ///< the current index in the IMU history CircularBuffer<IMUState> _imuHistory; ///< history of IMU states for cloud registration pcl::PointCloud<pcl::PointXYZ> _imuTrans = { 4,1 }; ///< IMU transformation information std::vector<float> _regionCurvature; ///< point curvature buffer std::vector<PointLabel> _regionLabel; ///< point label buffer std::vector<size_t> _regionSortIndices; ///< sorted region indices based on point curvature std::vector<int> _scanNeighborPicked; ///< flag if neighboring point was already picked }; }
[ "paulroopson.pradeep@gmail.com" ]
paulroopson.pradeep@gmail.com
09d78e7bbd0bdc09242aabb50b6577aa26fc6f60
9aab638297189a859e0a19420cc2697afe03b1ef
/13_chap_inherit/text/brass/usebrass2.cpp
7a6735209f79553aa3b0b1579e2d42b1e566bf26
[]
no_license
inpeterfomax/cplusplus
3e92657544e80c93aeb45de6323e86821a93175d
3d01c361157dc1a6d4d9b315cfcb2f8f89acc7d0
refs/heads/master
2022-12-08T03:16:24.059550
2022-11-26T13:49:03
2022-11-26T13:49:03
14,574,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,568
cpp
#include <iostream> #include "brass.h" const int CLIENTS = 4; const int LEN = 40; int main() { using std::cin; using std::cout; using std::endl; Brass * p_clients[CLIENTS]; int i; char temp[LEN]; long tempnum; double tempbal; char kind; for(i = 0; i < CLIENTS; i ++) { char temp[LEN]; long tempnum; double tempbal; char kind; cout << "Enter client's name: "; cin.getline (temp,LEN); cout << "Enter client's account number: "; cin >> tempnum; cout << "Enter openning balance: $"; cin >> tempbal; cout << "Enter 1 for Bras Account or 2 for BrassPlus Account: "; while (cin >> kind && (kind !='1' && kind != '2')) { cout << "Enter either 1 or 2: "; } if (kind == '1') { p_clients[i] = new Brass (temp, tempnum, tempbal); } else { double tmax, trate; cout << "Enter the overdraft limit: $"; cin >> tmax; cout << "Enter the interest rate as a decimal fraction: "; cin >> trate; p_clients[i] = new BrassPlus (temp, tempnum, tempbal,tmax,trate); } while (cin.get()!='\n') { continue; } } cout << endl; for (i = 0; i < CLIENTS; i ++) { p_clients[i]->ViewAcct(); cout << endl; } for (i = 0; i < CLIENTS; i ++) { delete p_clients[i]; } cout << "Done. \n"; return 0; }
[ "gupingchang@126.com" ]
gupingchang@126.com
95c6dd3e3c8fcdae7ad418c1c16b51d404afc663
6dcb5aca877030e9d3367ab45abb9611192ca13e
/src/libs/sound/ISoundPlaylistObserver.h
000a0382e741c0bc978aacd16e0597dec5994ef5
[ "MIT" ]
permissive
moneytech/dhas
d510dedfd26499093f8a26bf43f260c5c95f2e87
424212d4766c02f5df9e363ddb8ad2c295ed49d8
refs/heads/master
2021-09-03T18:24:07.451825
2018-01-10T23:23:59
2018-01-10T23:23:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
169
h
#pragma once namespace Dumais{ namespace Sound{ class ISoundPlaylistObserver { public: ~ISoundPlaylistObserver(){} virtual void onSoundQueueEmpty()=0; }; } }
[ "git@dumaisnet.ca" ]
git@dumaisnet.ca
868c9408a0627877f97e325c75688396bf3b6b3d
e398e90159a51b850b9b82540369e98b582468fe
/bioStation/src/main.cpp
f826f4e6b362fc2147bf71376a909f9d1e5ba75a
[]
no_license
unloquer/TalleresESP
f23529b375f494872d2e449d8a040e38960ee031
a5901fc568285bb9ac925714bd3e4a68976341a5
refs/heads/master
2021-01-23T05:44:45.201473
2018-03-17T03:09:30
2018-03-17T03:09:30
92,982,414
1
0
null
null
null
null
UTF-8
C++
false
false
2,010
cpp
/* This a simple example of the aREST UI Library for the ESP8266. See the README file for more details. Written in 2014-2016 by Marco Schwartz under a GPL license. */ // Import required libraries #include <ESP8266WiFi.h> #include <aREST.h> #include <aREST_UI.h> #include <DHT.h> #define DHTPIN 12 // what pin we're connected to // Uncomment whatever type you're using! #define DHTTYPE DHT11 // DHT 11 // Initialize DHT sensor for normal 16mhz Arduino DHT dht(DHTPIN, DHTTYPE); // Create aREST instance aREST_UI rest = aREST_UI(); // WiFi parameters const char* ssid = "K5"; const char* password = "seracambiar9"; // The port to listen for incoming TCP connections #define LISTEN_PORT 80 // Create an instance of the server WiFiServer server(LISTEN_PORT); // Variables to be exposed to the API float temperature; float humidity; void setup(void) { // Start Serial Serial.begin(115200); // Set the title rest.title("aREST UI Demo"); // Init variables and expose them to REST API temperature = 0; humidity = 0; rest.variable("temperature", &temperature); rest.variable("humidity", &humidity); // Labels rest.label("temperature"); rest.label("humidity"); // Give name and ID to device rest.set_id("1"); rest.set_name("esp8266"); // Connect to WiFi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // Start the server server.begin(); Serial.println("Server started"); // Print the IP address Serial.println(WiFi.localIP()); } void loop() { // Handle REST calls WiFiClient client = server.available(); temperature = dht.readTemperature(); humidity = dht.readHumidity(); //Serial.print("temperature ");Serial.println(temperature); //Serial.print("humidity ");Serial.println(humidity); if (!client) { return; } while (!client.available()) { delay(1); } rest.handle(client); }
[ "brolin108@gmail.com" ]
brolin108@gmail.com
43e4872221012b3ce2525be93ab85cdc3b181491
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/media/base/video_util.h
b40331c0293b2f6957b0f89197b92736b6725254
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
7,923
h
// 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. #ifndef MEDIA_BASE_VIDEO_UTIL_H_ #define MEDIA_BASE_VIDEO_UTIL_H_ #include <stdint.h> #include "base/memory/ref_counted.h" #include "media/base/media_export.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" namespace media { class VideoFrame; // Computes the pixel aspect ratio of a given |visible_rect| from its // |natural_size|. // // See https://en.wikipedia.org/wiki/Pixel_aspect_ratio for a detailed // definition. // // Returns NaN or Infinity if |visible_rect| or |natural_size| are empty. // // Note: Something has probably gone wrong if you need to call this function; // pixel aspect ratios should be the source of truth. // // TODO(crbug.com/837337): Decide how to encode 'not provided' for pixel aspect // ratios, and return that if one of the inputs is empty. MEDIA_EXPORT double GetPixelAspectRatio(const gfx::Rect& visible_rect, const gfx::Size& natural_size); // Increases (at most) one of the dimensions of |visible_rect| to produce // a |natural_size| with the given pixel aspect ratio. // // Returns gfx::Size() if |pixel_aspect_ratio| is not finite and positive. MEDIA_EXPORT gfx::Size GetNaturalSize(const gfx::Rect& visible_rect, double pixel_aspect_ratio); // Overload that takes the pixel aspect ratio as an integer fraction (and // |visible_size| instead of |visible_rect|). // // Returns gfx::Size() if numerator or denominator are not positive. MEDIA_EXPORT gfx::Size GetNaturalSize(const gfx::Size& visible_size, int aspect_ratio_numerator, int aspect_ratio_denominator); // Fills |frame| containing YUV data to the given color values. MEDIA_EXPORT void FillYUV(VideoFrame* frame, uint8_t y, uint8_t u, uint8_t v); // Fills |frame| containing YUVA data with the given color values. MEDIA_EXPORT void FillYUVA(VideoFrame* frame, uint8_t y, uint8_t u, uint8_t v, uint8_t a); // Creates a border in |frame| such that all pixels outside of |view_area| are // black. Only YV12 and ARGB format video frames are currently supported. If // format is YV12, the size and position of |view_area| must be even to align // correctly with the color planes. MEDIA_EXPORT void LetterboxVideoFrame(VideoFrame* frame, const gfx::Rect& view_area); // Rotates |src| plane by |rotation| degree with possible flipping vertically // and horizontally. // |rotation| is limited to {0, 90, 180, 270}. // |width| and |height| are expected to be even numbers. // Both |src| and |dest| planes are packed and have same |width| and |height|. // When |width| != |height| and rotated by 90/270, only the maximum square // portion located in the center is rotated. For example, for width=640 and // height=480, the rotated area is 480x480 located from row 0 through 479 and // from column 80 through 559. The leftmost and rightmost 80 columns are // ignored for both |src| and |dest|. // The caller is responsible for blanking out the margin area. MEDIA_EXPORT void RotatePlaneByPixels(const uint8_t* src, uint8_t* dest, int width, int height, int rotation, // Clockwise. bool flip_vert, bool flip_horiz); // Return the largest centered rectangle with the same aspect ratio of |content| // that fits entirely inside of |bounds|. If |content| is empty, its aspect // ratio would be undefined; and in this case an empty Rect would be returned. MEDIA_EXPORT gfx::Rect ComputeLetterboxRegion(const gfx::Rect& bounds, const gfx::Size& content); // Same as ComputeLetterboxRegion(), except ensure the result has even-numbered // x, y, width, and height. |bounds| must already have even-numbered // coordinates, but the |content| size can be anything. // // This is useful for ensuring content scaled and converted to I420 does not // have color distortions around the edges in a letterboxed video frame. Note // that, in cases where ComputeLetterboxRegion() would return a 1x1-sized Rect, // this function could return either a 0x0-sized Rect or a 2x2-sized Rect. MEDIA_EXPORT gfx::Rect ComputeLetterboxRegionForI420(const gfx::Rect& bounds, const gfx::Size& content); // Return a scaled |size| whose area is less than or equal to |target|, where // one of its dimensions is equal to |target|'s. The aspect ratio of |size| is // preserved as closely as possible. If |size| is empty, the result will be // empty. MEDIA_EXPORT gfx::Size ScaleSizeToFitWithinTarget(const gfx::Size& size, const gfx::Size& target); // Return a scaled |size| whose area is greater than or equal to |target|, where // one of its dimensions is equal to |target|'s. The aspect ratio of |size| is // preserved as closely as possible. If |size| is empty, the result will be // empty. MEDIA_EXPORT gfx::Size ScaleSizeToEncompassTarget(const gfx::Size& size, const gfx::Size& target); // Returns |size| with only one of its dimensions increased such that the result // matches the aspect ratio of |target|. This is different from // ScaleSizeToEncompassTarget() in two ways: 1) The goal is to match the aspect // ratio of |target| rather than that of |size|. 2) Only one of the dimensions // of |size| may change, and it may only be increased (padded). If either // |size| or |target| is empty, the result will be empty. MEDIA_EXPORT gfx::Size PadToMatchAspectRatio(const gfx::Size& size, const gfx::Size& target); // Copy an RGB bitmap into the specified |region_in_frame| of a YUV video frame. // Fills the regions outside |region_in_frame| with black. MEDIA_EXPORT void CopyRGBToVideoFrame(const uint8_t* source, int stride, const gfx::Rect& region_in_frame, VideoFrame* frame); // Converts a frame with YV12A format into I420 by dropping alpha channel. MEDIA_EXPORT scoped_refptr<VideoFrame> WrapAsI420VideoFrame( scoped_refptr<VideoFrame> frame); // Copy I420 video frame to match the required coded size and pad the region // outside the visible rect repeatly with the last column / row up to the coded // size of |dst_frame|. Return false when |dst_frame| is empty or visible rect // is empty. // One application is content mirroring using HW encoder. As the required coded // size for encoder is unknown before capturing, memory copy is needed when the // coded size does not match the requirement. Padding can improve the encoding // efficiency in this case, as the encoder will encode the whole coded region. // Performance-wise, this function could be expensive as it does memory copy of // the whole visible rect. // Note: // 1. |src_frame| and |dst_frame| should have same size of visible rect. // 2. The visible rect's origin of |dst_frame| should be (0,0). // 3. |dst_frame|'s coded size (both width and height) should be larger than or // equal to the visible size, since the visible region in both frames should be // identical. MEDIA_EXPORT bool I420CopyWithPadding(const VideoFrame& src_frame, VideoFrame* dst_frame) WARN_UNUSED_RESULT; } // namespace media #endif // MEDIA_BASE_VIDEO_UTIL_H_
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
ea64730e77e81c0c0ff3ff2be219ea4cbcecf882
e1661d124821ea15d09eec04e2d214a4d6bdbcd2
/files/djinni/shared-data/generated-src/jni/com/ezored/data/EZRSharedDataPlatformService.cpp
099576bb0ea9551ba0bb07fe01d6d9b4f38a80bb
[ "MIT" ]
permissive
uilianries/ezored
b6ff656bdecbde830e37066ea154d0326fa823d8
8c45a6753ddffce1fe406e6e062ff2b455dbb5a1
refs/heads/master
2020-04-29T03:32:12.886679
2019-03-15T02:46:28
2019-03-15T02:46:28
175,813,572
0
0
MIT
2019-03-15T12:10:24
2019-03-15T12:10:23
null
UTF-8
C++
false
false
15,332
cpp
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from proj.djinni #include "com/ezored/data/EZRSharedDataPlatformService.hpp" // my header #include "Marshal.hpp" namespace djinni_generated { EZRSharedDataPlatformService::EZRSharedDataPlatformService() : ::djinni::JniInterface<::ezored::data::SharedDataPlatformService, EZRSharedDataPlatformService>() {} EZRSharedDataPlatformService::~EZRSharedDataPlatformService() = default; EZRSharedDataPlatformService::JavaProxy::JavaProxy(JniType j) : Handle(::djinni::jniGetThreadEnv(), j) { } EZRSharedDataPlatformService::JavaProxy::~JavaProxy() = default; void EZRSharedDataPlatformService::JavaProxy::setString(const std::string & c_key, const std::string & c_value) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_setString, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_value))); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::setInteger(const std::string & c_key, int32_t c_value) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_setInteger, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::I32::fromCpp(jniEnv, c_value))); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::setLong(const std::string & c_key, int64_t c_value) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_setLong, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::I64::fromCpp(jniEnv, c_value))); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::setBool(const std::string & c_key, bool c_value) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_setBool, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::Bool::fromCpp(jniEnv, c_value))); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::setFloat(const std::string & c_key, float c_value) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_setFloat, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::F32::fromCpp(jniEnv, c_value))); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::setDouble(const std::string & c_key, double c_value) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_setDouble, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::F64::fromCpp(jniEnv, c_value))); ::djinni::jniExceptionCheck(jniEnv); } std::string EZRSharedDataPlatformService::JavaProxy::getString(const std::string & c_key) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = (jstring)jniEnv->CallObjectMethod(Handle::get().get(), data.method_getString, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::String::toCpp(jniEnv, jret); } int32_t EZRSharedDataPlatformService::JavaProxy::getInteger(const std::string & c_key) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallIntMethod(Handle::get().get(), data.method_getInteger, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::I32::toCpp(jniEnv, jret); } int64_t EZRSharedDataPlatformService::JavaProxy::getLong(const std::string & c_key) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallLongMethod(Handle::get().get(), data.method_getLong, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::I64::toCpp(jniEnv, jret); } bool EZRSharedDataPlatformService::JavaProxy::getBool(const std::string & c_key) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallBooleanMethod(Handle::get().get(), data.method_getBool, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::Bool::toCpp(jniEnv, jret); } float EZRSharedDataPlatformService::JavaProxy::getFloat(const std::string & c_key) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallFloatMethod(Handle::get().get(), data.method_getFloat, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::F32::toCpp(jniEnv, jret); } double EZRSharedDataPlatformService::JavaProxy::getDouble(const std::string & c_key) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallDoubleMethod(Handle::get().get(), data.method_getDouble, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::F64::toCpp(jniEnv, jret); } std::string EZRSharedDataPlatformService::JavaProxy::getStringWithDefaultValue(const std::string & c_key, const std::string & c_defaultValue) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = (jstring)jniEnv->CallObjectMethod(Handle::get().get(), data.method_getStringWithDefaultValue, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_defaultValue))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::String::toCpp(jniEnv, jret); } int32_t EZRSharedDataPlatformService::JavaProxy::getIntegerWithDefaultValue(const std::string & c_key, int32_t c_defaultValue) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallIntMethod(Handle::get().get(), data.method_getIntegerWithDefaultValue, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::I32::fromCpp(jniEnv, c_defaultValue))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::I32::toCpp(jniEnv, jret); } int64_t EZRSharedDataPlatformService::JavaProxy::getLongWithDefaultValue(const std::string & c_key, int64_t c_defaultValue) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallLongMethod(Handle::get().get(), data.method_getLongWithDefaultValue, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::I64::fromCpp(jniEnv, c_defaultValue))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::I64::toCpp(jniEnv, jret); } bool EZRSharedDataPlatformService::JavaProxy::getBoolWithDefaultValue(const std::string & c_key, bool c_defaultValue) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallBooleanMethod(Handle::get().get(), data.method_getBoolWithDefaultValue, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::Bool::fromCpp(jniEnv, c_defaultValue))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::Bool::toCpp(jniEnv, jret); } float EZRSharedDataPlatformService::JavaProxy::getFloatWithDefaultValue(const std::string & c_key, float c_defaultValue) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallFloatMethod(Handle::get().get(), data.method_getFloatWithDefaultValue, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::F32::fromCpp(jniEnv, c_defaultValue))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::F32::toCpp(jniEnv, jret); } double EZRSharedDataPlatformService::JavaProxy::getDoubleWithDefaultValue(const std::string & c_key, double c_defaultValue) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallDoubleMethod(Handle::get().get(), data.method_getDoubleWithDefaultValue, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key)), ::djinni::get(::djinni::F64::fromCpp(jniEnv, c_defaultValue))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::F64::toCpp(jniEnv, jret); } bool EZRSharedDataPlatformService::JavaProxy::has(const std::string & c_key) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); auto jret = jniEnv->CallBooleanMethod(Handle::get().get(), data.method_has, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::Bool::toCpp(jniEnv, jret); } void EZRSharedDataPlatformService::JavaProxy::remove(const std::string & c_key) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_remove, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_key))); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::clear() { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_clear); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::save(bool c_async, bool c_autoFinish) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_save, ::djinni::get(::djinni::Bool::fromCpp(jniEnv, c_async)), ::djinni::get(::djinni::Bool::fromCpp(jniEnv, c_autoFinish))); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::saveAsync() { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_saveAsync); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::saveSync() { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_saveSync); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::start(const std::string & c_groupName) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_start, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_groupName))); ::djinni::jniExceptionCheck(jniEnv); } void EZRSharedDataPlatformService::JavaProxy::finish() { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::EZRSharedDataPlatformService>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_finish); ::djinni::jniExceptionCheck(jniEnv); } } // namespace djinni_generated
[ "paulo@prsolucoes.com" ]
paulo@prsolucoes.com
722706dc1714c5d85f184c2cbb7047db93f140bb
d92e9933b8a4ed840d1d87d95727243c1626d747
/src/Bonus.cpp
cb0e2456e29551b5abef5507c8074d9d13bdb19c
[]
no_license
EricGadbin/Bomberman
dc97197b3709c62e775d67f453e5be4a4d085ec6
e1567be5ae1fcbbd913f51eb49fcaa0c9faa8225
refs/heads/master
2020-07-31T09:24:19.670503
2019-09-25T14:34:07
2019-09-25T14:34:07
210,558,930
5
0
null
null
null
null
UTF-8
C++
false
false
2,808
cpp
/* ** EPITECH PROJECT, 2019 ** INDIE_STUDIO ** File description: ** Bonus */ #include "../include/Bonus.hpp" using namespace Indie; std::string assets[] = { "../assets/wallbonus.png", "../assets/speedbonus.png", "../assets/bombbonus.png", "../assets/firebonus.png" }; Bonus::Bonus(btype_t type, irr::core::vector3df pos, irr::scene::ISceneManager* sceneManager, irr::video::IVideoDriver* driver) : _btype(type), _pos(pos), _sound(new sf::Music) { _block = Indie::Block(pos, sceneManager, driver); _block.getCube()->setMaterialTexture(0, driver->getTexture(assets[type].c_str())); _block.getCube()->setScale(irr::core::vector3df(0.8,0.8,0.8)); _sound->openFromFile("../powerUP.wav"); } void powerUpSound() { sf::Music sound; sound.openFromFile("../powerUP.wav"); sound.play(); while (sound.getStatus() == sf::SoundSource::Playing); } void Bonus::applyBonus(IPlayer *player) const { switch (_btype) { case wUP: player->setWallpass(true); break; case sUP: player->setSpeed(player->getSpeed() * 1.25); if (player->getSpeed() > 15 && player->getSpeed() < 16) player->setSanic(true); break; case bUP: player->setBombNb(player->getBombNb() + 1); break; case fUP: player->setRange(player->getRange() + 1); if (player->getRange() == 10) player->setMeg(true); break; default: return; } _sound->play(); //std::thread pow(&powerUpSound); //pow.detach(); } bool Bonus::checkCollision(irr::core::vector3df nodePosition, IPlayer *player) { if (nodePosition.X + 0.2 > _pos.X && nodePosition.X + 0.2 < _pos.X + 1 && nodePosition.Z > _pos.Z && nodePosition.Z < _pos.Z + 1 || nodePosition.X + 0.9 > _pos.X && nodePosition.X + 0.9 < _pos.X + 1 && nodePosition.Z > _pos.Z && nodePosition.Z < _pos.Z + 1 || nodePosition.X + 0.2 > _pos.X && nodePosition.X + 0.2 < _pos.X + 1 && nodePosition.Z + 0.7 > _pos.Z && nodePosition.Z + 0.7 < _pos.Z + 1 || nodePosition.X + 0.9 > _pos.X && nodePosition.X + 0.9 < _pos.X + 1 && nodePosition.Z + 0.7 > _pos.Z && nodePosition.Z + 0.7 < _pos.Z + 1) { applyBonus(player); return (true); } return (false); } bool Bonus::get_time() const { return ((std::clock() - _clock) / static_cast<double>(CLOCKS_PER_SEC) >= _iFrames); } Bonus::btype_t Bonus::getBonusType() const { return _btype; } void Bonus::setBonusType(Bonus::btype_t btype) { _btype = btype; } irr::core::vector3df Bonus::getPos() const { return _pos; } void Bonus::setPos(irr::core::vector3df pos) { _pos = pos; } IObject::type_t Bonus::getType() const { return _type; }
[ "benjamin.renaud@epitech.eu" ]
benjamin.renaud@epitech.eu
477e89b2440a136f640f2b0fe6c0aae967e1a6dc
89b7e4a17ae14a43433b512146364b3656827261
/testcases/CWE122_Heap_Based_Buffer_Overflow/s11/CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad.cpp
280b0ff3dfd509b7dcfd9556258b1ba84d15b220
[]
no_license
tuyen1998/Juliet_test_Suite
7f50a3a39ecf0afbb2edfd9f444ee017d94f99ee
4f968ac0376304f4b1b369a615f25977be5430ac
refs/heads/master
2020-08-31T23:40:45.070918
2019-11-01T07:43:59
2019-11-01T07:43:59
218,817,337
0
1
null
null
null
null
UTF-8
C++
false
false
1,501
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__sizeof.label.xml Template File: sources-sink-83_bad.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Initialize the source buffer using the size of a pointer * GoodSource: Initialize the source buffer using the size of the DataElementType * Sinks: * BadSink : Print then free data * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83.h" namespace CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83 { CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad::CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad(twoIntsStruct * dataCopy) { data = dataCopy; /* INCIDENTAL: CWE-467 (Use of sizeof() on a pointer type) */ /* FLAW: Using sizeof the pointer and not the data type in malloc() */ data = (twoIntsStruct *)malloc(sizeof(data)); if (data == NULL) {exit(-1);} data->intOne = 1; data->intTwo = 2; } CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad::~CWE122_Heap_Based_Buffer_Overflow__sizeof_struct_83_bad() { /* POTENTIAL FLAW: Attempt to use data, which may not have enough memory allocated */ printStructLine(data); free(data); } } #endif /* OMITBAD */
[ "35531872+tuyen1998@users.noreply.github.com" ]
35531872+tuyen1998@users.noreply.github.com
097a93bee74000f7668218c4942858d384d4a51f
26fd4d615946f73ee3964cd48fa06120611bf449
/104_Maximum_Depth_of_Binary_Tree.cpp
2e0b80fad7d359bc8fb7b14689deeb60e684680f
[]
no_license
xujie-nm/Leetcode
1aab8a73a33f954bfb3382a286626a56d2f14617
eb8a7282083e2d2a6c94475759ba01bd4220f354
refs/heads/master
2020-04-12T07:25:51.621189
2016-12-03T09:29:36
2016-12-03T09:29:36
28,400,113
2
0
null
null
null
null
UTF-8
C++
false
false
1,553
cpp
#include <iostream> #include <string> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; int maxDepth(TreeNode* root){ if(root == NULL) return 0; else{ int left = 1 + maxDepth(root->left); int right = 1 + maxDepth(root->right); return left >= right ? left : right; } } int main(int argc, const char *argv[]) { TreeNode n1(3); TreeNode n2(9); TreeNode n3(20); TreeNode n6(15); TreeNode n7(7); n1.left = &n2; n1.right = &n3; n3.left = &n6; n3.right = &n7; cout << maxDepth(&n1) << endl; return 0; } /** * * ━━━━━━神兽出没━━━━━━ *    ┏┓  ┏┓ *    ┛┻━━━┛┻┓ *   ┃     ┃ *   ┃   ━  ┃ *   ┃ ┳┛ ┗┳ ┃ *   ┃      ┃ *   ┃   ┻  ┃ *   ┃      ┃ *   ┗━┓   ┏ ┛Code is far away from bug with the animal protecting *     ┃   ┃ 神兽保佑,代码无bug *     ┃   ┃ *     ┃   ┗━━━┓ *     ┃      ┣┓ *     ┃      ┏┛ *     ┗┓┓┏━┳┓┏┛ *     ┃┫┫ ┃┫┫ *     ┗┻┛ ┗┻┛ * */
[ "xujie_nm@163.com" ]
xujie_nm@163.com
17f67977d81a8ea145ea22c3826460f7752b9678
15419e6b114d5b89e78648dbae52a0aae276b673
/Contests/Weekly Team Practice Contests/Week 22 - 13th Iran Internet ACM ICPC 2015 - Shiraz/D - AC.cpp
1779f05d8bccd578645df1309f8eff03f04e589d
[]
no_license
ImnIrdst/ICPC-Practice-2015-TiZii
7cde07617d8ebf90dc8a4baec4d9faec49f79d13
73bb0f84e7a003e154d685fa598002f8b9498878
refs/heads/master
2021-01-10T16:29:34.490848
2016-04-08T04:13:37
2016-04-08T04:13:37
55,749,815
1
0
null
null
null
null
UTF-8
C++
false
false
1,595
cpp
#include<iostream> #include<algorithm> #include<vector> #include<functional> #include<sstream> #include<string> #include<set> #include<map> using namespace std; int main() { int tc; cin >> tc; while (tc--) { int n, m; cin >> n >> m; vector<int> vote_hist(n + 1, 0); map<int, vector<int> > votes; int today = 0; cin.ignore(); string line; //read & save input for (int i = 1; i <= m; ++i) { getline(cin, line); stringstream sstr(line); int day_id, free_day; sstr >> day_id; if (!votes.count(day_id)) { votes[day_id] = vector<int>(n + 1, 0); } while (sstr >> free_day) { votes[day_id][free_day]++; } } bool cond = true; int last_day = -1; while(today <= n - 1 && cond){ //add vote of today int tommorow = today + 1; if (votes.count(today)) { last_day = today;//???????????????? //add next day votes to histogram for (int i = tommorow; i <= n; ++i) { vote_hist[i] += votes[today][i]; } } //check if there is someday better that next day exist cond = false; for (int i = tommorow + 1; i <= n; ++i) { if (vote_hist[i] >= vote_hist[tommorow]) { cond = true; break; } } today++; } if (today <= n - 1 || last_day == -1) { cout << today << endl; } else { int m = vote_hist[last_day+1]; int index = last_day+1; for (int i = index + 1; i <= n; ++i) { if (vote_hist[i] >= m) { m = vote_hist[i]; index = i; } } cout << index << endl; } } return 0; }
[ "imn.irdst@gmail.com" ]
imn.irdst@gmail.com
9c71230bdbe1edb40a8a23715fb8959a9dd61b27
b3c47795e8b6d95ae5521dcbbb920ab71851a92f
/Leetcode/Algorithm/cpp/02382-Maximum Segment Sum After Removals.cc
7de56eb5be2e84e8d2c583ef65287f2075964e6a
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Wizmann/ACM-ICPC
6afecd0fd09918c53a2a84c4d22c244de0065710
7c30454c49485a794dcc4d1c09daf2f755f9ecc1
refs/heads/master
2023-07-15T02:46:21.372860
2023-07-09T15:30:27
2023-07-09T15:30:27
3,009,276
51
23
null
null
null
null
UTF-8
C++
false
false
1,634
cc
typedef long long llint; struct Segment { int st, end; llint value; }; class Solution { public: vector<long long> maximumSegmentSum(vector<int>& nums_, vector<int>& removeQueries) { multiset<llint> st; map<int, Segment> mp; vector<llint> nums; for (auto num : nums_) { nums.push_back(num); } const int n = nums.size(); for (int i = 1; i < n; i++) { nums[i] += nums[i - 1]; } st.insert(0); st.insert(nums[n - 1]); mp[n - 1] = {0, n - 1, nums[n - 1]}; auto presum = [&](int a, int b) -> llint { assert(b < n); assert(a - 1 < n); return nums[b] - (a - 1 < 0 ? 0 : nums[a - 1]); }; vector<llint> res; for (auto q : removeQueries) { auto iter = mp.lower_bound(q); assert(iter != mp.end()); const auto seg = iter->second; mp.erase(iter); llint tot = seg.value; st.erase(st.find(tot)); if (seg.st <= q - 1) { llint a = presum(seg.st, q - 1); st.insert(a); mp[q - 1] = {seg.st, q - 1, a}; } if (q + 1 <= seg.end) { llint b = presum(q + 1, seg.end); st.insert(b); mp[seg.end] = {q + 1, seg.end, b}; } res.push_back(*st.rbegin()); // cout << *st.rbegin() << endl; } return res; } };
[ "noreply@github.com" ]
Wizmann.noreply@github.com
29f282accb576680779b0e44c7832430e6edc6ad
c8b596ba5f07009b646665916a1084d985ef34bc
/mpi_inputfield.h
2afa953c71acd8720281429a99d073510db2ee0b
[]
no_license
jmerten82/my_first
f5a3c416cf2731b75b0c0863555bcafab0d2eebf
daa7c077903cdcf83b27f89949ed68b250eade86
refs/heads/master
2021-06-13T21:28:56.557312
2015-03-10T11:24:10
2015-03-10T11:24:10
254,449,345
0
0
null
null
null
null
UTF-8
C++
false
false
11,724
h
#ifndef INPUTFIELD_H_ # define INPUTFIELD_H_ #include <iostream> #include <fstream> #include <string> #include <sstream> #include <gsl/gsl_matrix.h> #include <gsl/gsl_statistics.h> #include <cmath> #include <ctime> #include "rw_fits.h" #include "util.h" #include "soph_math.h" #include "options.h" #include "masked_fin_dif.h" #include "mpi.h" #include "mpi_comm.h" using namespace std; //auxilliary functions string parametercut2(string); // cuts out substring between two kinds of given string int countsymbol2(string, const char&); // counts the given char in a string void cutints2(string, string, gsl_vector_int*,int); //gives all integers separated by string in a string to gsl_vector_int void cutdoubles2(string, string, gsl_vector*,int); //same for doubles class DataGrid { /** Central class of the field preparation process which contains and calculates all relevant quantities which are written to a FITS file later. **/ private: double fieldx; /* physical x-dimension of the DataGrid. */ double fieldy; /* physcial y-dimension of the DataGrid. */ double fieldsize; /* physical area of the DataGrid, fieldy*fieldy */ int x_dim; /* pixel x-dimension of the DataGrid */ int y_dim; /* pixel y-dimension of the DataGrid */ double xcentre; /* physical x-coordinate of the centre of the bottom left pixel of the DataGrid */ double ycentre; /* physical y-coordinate of the centre of the bottom left pixel of the DataGrid */ double pixelsize; /* physical sidelength of one pixel of the DataGrid */ int fieldpixels; /* Number of non-masked pixels in the DataGrid */ gsl_matrix_int *maskcheck; /* Identifier for masked pixels in the DataGrid */ bool desshear; /* For memory deallocation reasons. States if the DataGrid calculates shear. */ bool desflexion; /* For memory deallocation reasons. States if the DataGrid calculates flexion. */ bool desccurve; /* For memory deallocation reasons. States if the DataGrid calculates a critical curve estimator. */ bool desmsystems; /* For memory deallocation reasons. States if the DataGrid calculates mutliple image systems. */ bool smallindex; /* Again for deallocation */ bool medindex; /* see above */ bool root; /* Am I the root process? */ int numgalshear; /* Number of galaxies used for shear estimation in the DataGrid. */ double galaxydensityshear; /* Number density of the galaxies used for shear estimation in the DataGrid. numgalshear/fieldsize */ gsl_vector *rec; /* Contains the RA coordinates of the shear catalogue. */ gsl_vector *dec; /* Contains the declination coordinates of the shear catalogue. */ gsl_vector *ellip1; /* Contains the first reduced shear component of the shear catalogue. */ gsl_vector *ellip2; /* Contains the second reduced shear component of the shear catalogue. */ gsl_vector *shearweight; /* Contains the weighting function for the reduced shear in the shear catalogue. */ gsl_matrix *meanellip1; /* Contains the averaged first reduced shear component for each pixel of the DataGrid. */ gsl_matrix *finalmeanellip1; /* The full matrix, patched together with all the MPI pieces. */ gsl_matrix *meanellip2; /* Contains the averaged second reduced shear component for each pixel of the DataGrid. */ gsl_matrix *finalmeanellip2; /* The full matrix, patched together with all the MPI pieces. */ gsl_matrix *ellip1sd; /* Contains the standard deviation of the first reduced shear component for each pixel of the DataGrid. */ gsl_matrix *finalellip1sd; /* The full matrix, patched together with all the MPI pieces. */ gsl_matrix *ellip2sd; /* Contains the standard deviation of the second reduced shear component for each pixel of the DataGrid. */ gsl_matrix *finalellip2sd; /* The full matrix, patched together with all the MPI pieces. */ gsl_vector *internalellip1; /* Contains the averaged first reduced shear component for each non-masked pixel of the DataGrid. */ gsl_vector *internalellip2; /* Contains the averaged second reduced shear component for each non-masked pixel of the DataGrid. */ gsl_vector *internalellip1sd; /* Contains the standard deviation of the first reduced shear component for each non-masked pixel of the DataGrid. */ gsl_vector *internalellip2sd; /* Contains the standard deviation of the second reduced shear component for each non-masked pixel of the DataGrid. */ gsl_matrix_uchar *galaxyownersellip; /* Matrix which indicates which galaxy in the original catalogue is used for each pixel in the DataGrid. This is needed to perform covariances. */ gsl_matrix_uchar *finalgalaxyownersellip; /* The gathering matrix which collects from all processes. */ gsl_matrix_int *galaxyshareellip; /* Matrix which visualises the galaxy overlap in each pixel. This is used to calculate the covariances. */ gsl_matrix_int *finalgalaxyshareellip; /* The full matrix, patched together with all the MPI pieces. */ gsl_matrix *ellip1covariance; /* Covariance matrix for thr first shear component. */ gsl_matrix *finalellip1covariance; /* The full matrix, patched together with all the MPI pieces. */ gsl_matrix *ellip2covariance; /* Covariance matrix for thr second shear component. */ gsl_matrix *finalellip2covariance; /* The full matrix, patched together with all the MPI pieces. */ int numgalflexion; /* Number of galaxies used for flexion estimation in the DataGrid. */ double galaxydensityflexion; /* Number density of the galaxies used for flexion estimation in the DataGrid. numgalflexion/fieldsize */ gsl_vector *recflexion; /* Contains the RA coordinates of the flexion catalogue. */ gsl_vector *decflexion; /* Contains the Declination coordinates of the flexion catalogue. */ gsl_vector *f1; /* Contains the first F component of the flexion catalogue. */ gsl_vector *f2; /* Contains the second F component of the flexion catalogue. */ gsl_vector *g1; /* Contains the first G component of the flexion catalogue. */ gsl_vector *g2; /* Contains the second G component of the flexion catalogue. */ gsl_vector *flexionweight; /* Contains the weighting function for the flexion in the flexion catalogue. */ gsl_matrix *meanf1; /* Contains the averaged first F component for each pixel of the DataGrid. */ gsl_matrix *finalmeanf1; gsl_matrix *meanf2; /* Contains the averaged second F component for each pixel of the DataGrid. */ gsl_matrix *finalmeanf2; gsl_matrix *f1sd; /* Contains the standard deviation of the first F component for each pixel of the DataGrid. */ gsl_matrix *finalf1sd; gsl_matrix *f2sd; /* Contains the standard deviation of the second Fcomponent for each pixel of the DataGrid. */ gsl_matrix *finalf2sd; gsl_matrix *meang1; /* Contains the averaged first G component for each pixel of the DataGrid. */ gsl_matrix *finalmeang1; gsl_matrix *meang2; /* Contains the averaged second G component for each pixel of the DataGrid. */ gsl_matrix *finalmeang2; gsl_matrix *g1sd; /* Contains the standard deviation of the first G component for each pixel of the DataGrid. */ gsl_matrix *finalg1sd; gsl_matrix *g2sd; /* Contains the standard deviation of the second G component for each pixel of the DataGrid. */ gsl_matrix *finalg2sd; gsl_vector *internalf1; /* Contains the averaged first F component for each non-masked pixel of the DataGrid. */ gsl_vector *internalf2; /* Contains the averaged second F component for each non-masked pixel of the DataGrid. */ gsl_vector *internalf1sd; /* Contains the standard deviation of the first F component for each non-masked pixel of the DataGrid. */ gsl_vector *internalf2sd; /* Contains the standard deviation of the second F component for each non-masked pixel of the DataGrid. */ gsl_vector *internalg1; /* Contains the averaged first G component for each non-masked pixel of the DataGrid. */ gsl_vector *internalg2; /* Contains the averaged second G component for each non-masked pixel of the DataGrid. */ gsl_vector *internalg1sd; /* Contains the standard deviation of the first G component for each non-masked pixel of the DataGrid. */ gsl_vector *internalg2sd; /* Contains the standard deviation of the second G component for each non-masked pixel of the DataGrid. */ gsl_matrix_uchar *galaxyownersflexion; /* Matrix which indicates which galaxy in the original catalogue is used for each pixel in the DataGrid. This is needed to perform covariances. */ gsl_matrix_uchar *finalgalaxyownersflexion; /* Gathering matrix for galaxyowners. */ gsl_matrix_int *galaxyshareflexion; /* Matrix which visualises the galaxy overlap in each pixel. This is used to calculate the covariances. */ gsl_matrix_int *finalgalaxyshareflexion; gsl_matrix *f1covariance; /* Covariance matrix for the first F component. */ gsl_matrix *finalf1covariance; gsl_matrix *f2covariance; /* Covariance matrix for the second F component. */ gsl_matrix *finalf2covariance; gsl_matrix *g1covariance; /* Covariance matrix for the first G component. */ gsl_matrix *finalg1covariance; gsl_matrix *g2covariance; /* Covariance matrix for the second G component. */ gsl_matrix *finalg2covariance; int numccurvepts; /* Number of points in the DataGrid, indicated as part of the critical curve estimate. */ gsl_vector *ccurverec; /* RA coordinates of the crtical curve estimators. */ gsl_vector *ccurvedec; /* Declination coordinates of the crtical curve estimators. */ gsl_vector *ccurvered; /* Redshift information on the critical curve estimators. */ gsl_matrix_int *ccurve; /* Indicator for the actual critical curve estimate position in the final DataGrid. */ gsl_matrix *ccurveerror; /* Error on the critical curve estimation. */ gsl_matrix *ccurveredshift; /* Redshift information on the critical curve estimator in the actual DataGrid. */ int nummsystems; /* Number of multiple image systems. */ gsl_matrix *msysteminfo; /* Abstract data matrix containing information about position, gridposition and redshift of multiple image systems. */ /* Insert for an issue in Charles' project! NOT MEMORY EFFICIENT! */ gsl_matrix *pure_covariance1; gsl_matrix *pure_covariance2; public: DataGrid(FieldOptions&,int,int my_rank,int p); /* Constructor, which needs an options class and an iterationindex. Reads the catalogues and allocates memory, the rank makes sure that only the leading process reads data. */ ~DataGrid(); /* Standard destructor, free (a lot of) memory. */ void analyse(FieldOptions&,int my_rank, int p); /* Performs averaging pixel associations and covariances. The time consuming part. */ void write(FieldOptions&,int,int my_rank); /* Write the results to FITS resp. ASCII, depending on the options class and the iterationindex which contain the right filenames. */ }; #endif /* !INPUTFIELD_H_ */
[ "julian.merten@physics.ox.ac.uk" ]
julian.merten@physics.ox.ac.uk