hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
96bc18f49667ca4c8c31f5167020e62a49ba064a
939
cpp
C++
Nacro/SDK/FN_ActiveModifierItemHUD_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_ActiveModifierItemHUD_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_ActiveModifierItemHUD_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ActiveModifierItemHUD.ActiveModifierItemHUD_C.AssignIcon // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // struct FSlateBrush inIconSlateBrush (Parm) void UActiveModifierItemHUD_C::AssignIcon(const struct FSlateBrush& inIconSlateBrush) { static auto fn = UObject::FindObject<UFunction>("Function ActiveModifierItemHUD.ActiveModifierItemHUD_C.AssignIcon"); UActiveModifierItemHUD_C_AssignIcon_Params params; params.inIconSlateBrush = inIconSlateBrush; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
23.475
118
0.630458
Milxnor
96bd4eeea431d1ab6081e3c4929ad3e00773362e
3,757
cpp
C++
09_Course_Scheduling/09.cpp
Moreonenight/Data-Structure-of-TJSSE
088fcd32e8d16e1532514ca501dcfce7d6895a4b
[ "MIT" ]
null
null
null
09_Course_Scheduling/09.cpp
Moreonenight/Data-Structure-of-TJSSE
088fcd32e8d16e1532514ca501dcfce7d6895a4b
[ "MIT" ]
null
null
null
09_Course_Scheduling/09.cpp
Moreonenight/Data-Structure-of-TJSSE
088fcd32e8d16e1532514ca501dcfce7d6895a4b
[ "MIT" ]
null
null
null
#include "09.h" int main() { std::string location = R"(./09_Input.txt)"; //Read in the Input files std::ifstream Input(location); if (!Input.is_open()) { std::cout << "Failed to open " << location << ". " << std::endl; std::cin.clear(); std::cin.sync(); getchar(); exit(0); } Graph graph; Course course; std::string line; getline(Input, line); while (getline(Input, line)) { //Read in the Points and Edges of the graph std::stringstream stream(line); stream >> course; graph.AddCourse(course); } Input.close(); std::ifstream InputEdges(location); getline(InputEdges, line); while (getline(InputEdges, line)) { std::stringstream stream(line); stream >> course; std::string tmp; while (stream >> tmp) { graph.AddEdges(tmp); } graph.currentCourse++; } std::cout << "Course information is stored in " << location << ", the output is stored in ./Output.txt. " << std::endl; std::cout << "Enter 0 to decide numbers of courses in each term by default, enter 1 to input them manually: "; char option; while (true) { std::cin >> option; if (std::cin.fail() != true && (option == '1' || option == '0')) { std::cin.clear(); std::cin.sync(); break; } //Reset and clear the input stream if input data is incorrect. std::cin.clear(); std::cin.sync(); std::cout << std::endl; std::cout << "Please enter as required: "; } switch (option) { //Whether to input the numbers of courses in each term manually case '0': { long long sum = 0; for (int i = 0; i < 8; i++) { sum += courses_each_term[i]; } if (sum != graph.totalCourses) { std::cout << "Default numbers failed. Please enter them manually. " << std::endl; option = 1; //if default numbers fail, switch to case '1' } else { break; } } case '1': { std::cout << "NOTICE: It can be proved that 'Course Scheduling' is an NP-hard problem, and it is not guaranteed this program can find a solution (even if there is a solution)." << std::endl; std::cout << "There are " << graph.totalCourses << " courses in total, please enter eight numbers for term 1 to 8. Sum of the eight numbers must be " << graph.totalCourses << "." << std::endl; while (true) { long long sum = 0; for (int i = 0; i < 8; i++) { std::cin >> courses_each_term[i]; sum += courses_each_term[i]; } if (std::cin.fail() != true && sum == graph.totalCourses) { std::cin.clear(); std::cin.sync(); break; } //Reset and clear the input stream if input data is incorrect. std::cin.clear(); std::cin.sync(); std::cout << std::endl; std::cout << "Please enter as required! " << std::endl; } break; } } graph.TopologicalSort(); std::cout << "Course Scheduling Success! " << std::endl; std::string destination = R"(./09_Output.txt)"; //Print the Schedule std::ofstream Output(destination); for (int term = 0; term < TERMS; term++) { Output << "Term " << 1 + term << std::endl; Output << "\t" << "\t" << " "; for (int day = 0; day < 5; day++) { Output << "Day " << 1 + day << "\t" << "\t"; } Output << std::endl; for (int class_ = 0; class_ < 10; class_++) { if (class_ <= 8) { Output << "Class " << 1 + class_ << " " << "\t"; } else { Output << "Class " << 1 + class_ << "\t"; } for (int day = 0; day < 5; day++) { if (graph.plan[term][day][class_].empty()) { Output << "None" << "\t" << "\t"; } else { Output << graph.plan[term][day][class_] << "\t" << "\t"; } } Output << std::endl; } Output << std::endl; } std::cout << "Please Check ./09_Output.txt for the Scheduling! " << std::endl; std::cout << "Press any key to exit... " << std::endl; std::cin.clear(); std::cin.sync(); getchar(); return 0; }
29.81746
194
0.584775
Moreonenight
96beef18081b7735ce5c4d9cf42b4db3184df2e3
553
cpp
C++
atcoder/Educational DP Contest/C.cpp
ApocalypseMac/CP
b2db9aa5392a362dc0d979411788267ed9a5ff1d
[ "MIT" ]
null
null
null
atcoder/Educational DP Contest/C.cpp
ApocalypseMac/CP
b2db9aa5392a362dc0d979411788267ed9a5ff1d
[ "MIT" ]
null
null
null
atcoder/Educational DP Contest/C.cpp
ApocalypseMac/CP
b2db9aa5392a362dc0d979411788267ed9a5ff1d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> const int maxn = 100005; int N, h[maxn][3], dp[maxn][3]; int main(){ std::cin >> N; memset(dp, 0, sizeof(dp)); for (int i = 1; i <= N; i++) std::cin >> h[i][0] >> h[i][1] >> h[i][2]; for (int i = 1; i <= N; i++){ dp[i][0] = h[i][0] + std::max(dp[i-1][1], dp[i-1][2]); dp[i][1] = h[i][1] + std::max(dp[i-1][0], dp[i-1][2]); dp[i][2] = h[i][2] + std::max(dp[i-1][0], dp[i-1][1]); } std::cout << *std::max_element(std::begin(dp[N]), std::end(dp[N])); return 0; }
34.5625
71
0.426763
ApocalypseMac
96bf34023f5eda6a9b69bfbc5b8ca83db5ea852b
1,089
cpp
C++
Algorithms on Graphs/week1_decomposition1/1_reachability/reachability.cpp
18Pranjul/Data-Structures-and-Algorithms-Specialization-Coursera
1d2f3a4ee390f0297de29de84205ef5f2a40f31d
[ "MIT" ]
null
null
null
Algorithms on Graphs/week1_decomposition1/1_reachability/reachability.cpp
18Pranjul/Data-Structures-and-Algorithms-Specialization-Coursera
1d2f3a4ee390f0297de29de84205ef5f2a40f31d
[ "MIT" ]
null
null
null
Algorithms on Graphs/week1_decomposition1/1_reachability/reachability.cpp
18Pranjul/Data-Structures-and-Algorithms-Specialization-Coursera
1d2f3a4ee390f0297de29de84205ef5f2a40f31d
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <math.h> #include <cstring> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <set> #include <utility> #include <iomanip> #include <climits> using namespace std; #define ll long long #define MOD 1000000007 #define MAX 1000000000000000000 #define ln "\n" #define pb push_back #define pll pair<ll,ll> #define mp make_pair #define f first #define s second #define Test ll t;cin>>t; while(t--) #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL); ll root(ll a[],ll x) { while(a[x]!=x) { a[x]=a[a[x]]; x=a[x]; } return x; } void Union(ll a[],ll x,ll y) { ll rx=root(a,x),ry=root(a,y); if(rx<ry) a[ry]=rx; else a[rx]=ry; } int main() { fast_io; ll n,m; cin>>n>>m; ll a[n+5],i; for(i=1;i<=n;i++) a[i]=i; for(i=0;i<m;i++) { ll x,y; cin>>x>>y; Union(a,x,y); } ll x,y; cin>>x>>y; if(root(a,x)==root(a,y)) cout<<"1"; else cout<<"0"; return 0; }
17.852459
64
0.56933
18Pranjul
96c0185362867e4e3e36f3c8955b8fbf71da18ee
58,438
cpp
C++
net/rras/ip/nathlp/dns/dnsquery.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/rras/ip/nathlp/dns/dnsquery.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/rras/ip/nathlp/dns/dnsquery.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1998, Microsoft Corporation Module Name: dnsquery.c Abstract: This module contains code for the DNS proxy's query-management. Author: Abolade Gbadegesin (aboladeg) 11-Mar-1998 Revision History: Raghu Gatta (rgatta) 1-Dec-2000 Added ICSDomain registry key change notify code. --*/ #include "precomp.h" #pragma hdrstop #include "dnsmsg.h" // // Structure: DNS_QUERY_TIMEOUT_CONTEXT // // This structure is used to pass context information // to the timeout callback-routine for DNS queries. // typedef struct _DNS_QUERY_TIMEOUT_CONTEXT { ULONG Index; USHORT QueryId; } DNS_QUERY_TIMEOUT_CONTEXT, *PDNS_QUERY_TIMEOUT_CONTEXT; // // GLOBAL DATA DEFINITIONS // const WCHAR DnsDhcpNameServerString[] = L"DhcpNameServer"; const WCHAR DnsNameServerString[] = L"NameServer"; HANDLE DnsNotifyChangeKeyEvent = NULL; IO_STATUS_BLOCK DnsNotifyChangeKeyIoStatus; HANDLE DnsNotifyChangeKeyWaitHandle = NULL; HANDLE DnsNotifyChangeAddressEvent = NULL; OVERLAPPED DnsNotifyChangeAddressOverlapped; HANDLE DnsNotifyChangeAddressWaitHandle = NULL; PULONG DnsServerList[DnsProxyCount] = { NULL, NULL }; HANDLE DnsTcpipInterfacesKey = NULL; const WCHAR DnsTcpipInterfacesString[] = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services" L"\\Tcpip\\Parameters\\Interfaces"; HANDLE DnsNotifyChangeKeyICSDomainEvent = NULL; IO_STATUS_BLOCK DnsNotifyChangeKeyICSDomainIoStatus; HANDLE DnsNotifyChangeKeyICSDomainWaitHandle = NULL; HANDLE DnsTcpipParametersKey = NULL; const WCHAR DnsTcpipParametersString[] = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services" L"\\Tcpip\\Parameters"; const WCHAR DnsICSDomainValueName[] = L"ICSDomain"; PWCHAR DnsICSDomainSuffix = NULL; // // FORWARD DECLARATIONS // VOID NTAPI DnsNotifyChangeAddressCallbackRoutine( PVOID Context, BOOLEAN TimedOut ); VOID NTAPI DnspQueryTimeoutCallbackRoutine( PVOID Context, BOOLEAN TimedOut ); VOID APIENTRY DnspQueryTimeoutWorkerRoutine( PVOID Context ); VOID DnsReadCompletionRoutine( ULONG ErrorCode, ULONG BytesTransferred, PNH_BUFFER Bufferp ); VOID DnsDeleteQuery( PDNS_INTERFACE Interfacep, PDNS_QUERY Queryp ) /*++ Routine Description: This routine is called to delete a pending query. Arguments: Interfacep - the query's interface Queryp - the query to be deleted Return Value: none. Environment: Invoked with 'Interfacep' locked by the caller. --*/ { PROFILE("DnsDeleteQuery"); if (Queryp->Bufferp) { NhReleaseBuffer(Queryp->Bufferp); } if (Queryp->TimerHandle) { // // This query is associated with a timer; // Rather than cancel the timeout-routine, we let it run, // so that it can release any references it has on the component. // When it does run, though, the routine won't find this query. // Queryp->TimerHandle = NULL; } RemoveEntryList(&Queryp->Link); NH_FREE(Queryp); } // DnsDeleteQuery BOOLEAN DnsIsPendingQuery( PDNS_INTERFACE Interfacep, PNH_BUFFER QueryBuffer ) /*++ Routine Description: This routine is invoked to determine whether a query is already pending for the client-request in the given buffer. The list of queries is sorted on 'QueryId', but we will be searching on 'SourceId' and 'SourceAddress' and 'SourcePort'; hence, we must do an exhaustive search of the pending-query list. Arguments: Interfacep - the interface on which to look QueryBuffer - the query to be searched for Return Value: BOOLEAN - TRUE if the query is already pending, FALSE otherwise. Environment: Invoked with 'Interfacep' locked by the caller. --*/ { BOOLEAN Exists; PDNS_HEADER Headerp; PLIST_ENTRY Link; PDNS_QUERY Queryp; PROFILE("DnsIsPendingQuery"); Exists = FALSE; Headerp = (PDNS_HEADER)QueryBuffer->Buffer; for (Link = Interfacep->QueryList.Flink; Link != &Interfacep->QueryList; Link = Link->Flink ) { Queryp = CONTAINING_RECORD(Link, DNS_QUERY, Link); if (Queryp->SourceId != Headerp->Xid || Queryp->SourceAddress != QueryBuffer->ReadAddress.sin_addr.s_addr || Queryp->SourcePort != QueryBuffer->ReadAddress.sin_port ) { continue; } Exists = TRUE; break; } return Exists; } // DnsIsPendingQuery PDNS_QUERY DnsMapResponseToQuery( PDNS_INTERFACE Interfacep, USHORT ResponseId ) /*++ Routine Description: This routine is invoked to map an incoming response from a DNS server to a pending query for a DNS client. Arguments: Interfacep - the interface holding the pending query, if any ResponseId - the ID in the response received from the server Return Value: PDNS_QUERY - the pending query, if any Environment: Invoked with 'Interfacep' locked by the caller. --*/ { PLIST_ENTRY Link; PDNS_QUERY Queryp; PROFILE("DnsMapResponseToQuery"); for (Link = Interfacep->QueryList.Flink; Link != &Interfacep->QueryList; Link = Link->Flink ) { Queryp = CONTAINING_RECORD(Link, DNS_QUERY, Link); if (ResponseId > Queryp->QueryId) { continue; } else if (ResponseId < Queryp->QueryId) { break; } return Queryp; } return NULL; } // DnsMapResponseToQuery VOID NTAPI DnsNotifyChangeAddressCallbackRoutine( PVOID Context, BOOLEAN TimedOut ) /*++ Routine Description: This routine is invoked to notify us of when changes occur in the (system) table that maps IP addresses to interfaces. Arguments: Context - unused TimedOut - indicates a time-out occurred Return Value: none. Environment: The routine runs in the context of an Rtl wait-thread. (See 'RtlRegisterWait'.) A reference to the component will have been made on our behalf when 'RtlRegisterWait' was called. The reference is released when the wait is cancelled, unless an error occurs here, in which case it is released immediately. --*/ { ULONG Error; HANDLE UnusedTcpipHandle; PROFILE("DnsNotifyChangeAddressCallbackRoutine"); EnterCriticalSection(&DnsGlobalInfoLock); if (!DnsNotifyChangeAddressEvent) { LeaveCriticalSection(&DnsGlobalInfoLock); DEREFERENCE_DNS(); return; } // // Rebuild the list of DNS servers // DnsQueryServerList(); // // Repost the address change-notification // ZeroMemory(&DnsNotifyChangeAddressOverlapped, sizeof(OVERLAPPED)); DnsNotifyChangeAddressOverlapped.hEvent = DnsNotifyChangeAddressEvent; Error = NotifyAddrChange( &UnusedTcpipHandle, &DnsNotifyChangeAddressOverlapped ); if (Error != ERROR_IO_PENDING) { if (DnsNotifyChangeAddressWaitHandle) { RtlDeregisterWait(DnsNotifyChangeAddressWaitHandle); DnsNotifyChangeAddressWaitHandle = NULL; } NtClose(DnsNotifyChangeAddressEvent); DnsNotifyChangeAddressEvent = NULL; LeaveCriticalSection(&DnsGlobalInfoLock); DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsNotifyChangeAddressCallbackRoutine: error %08x " "for change address", Error ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_NOTIFY_FAILED, Error, "" ); return; } LeaveCriticalSection(&DnsGlobalInfoLock); } // DnsNotifyChangeAddressCallbackRoutine VOID NTAPI DnsNotifyChangeKeyCallbackRoutine( PVOID Context, BOOLEAN TimedOut ) /*++ Routine Description: This routine is invoked to notify us of a change to the TCP/IP parameters subkey containing the DNS adapter information. Arguments: Context - unused TimedOut - indicates a time-out occurred Return Value: none. Environment: The routine runs in the context of an Rtl wait-thread. (See 'RtlRegisterWait'.) A reference to the component will have been made on our behalf when 'RtlRegisterWait' was called. The reference is released when the wait is cancelled, unless an error occurs here, in which case it is released immediately. --*/ { NTSTATUS status; PROFILE("DnsNotifyChangeKeyCallbackRoutine"); EnterCriticalSection(&DnsGlobalInfoLock); if (!DnsNotifyChangeKeyEvent) { LeaveCriticalSection(&DnsGlobalInfoLock); DEREFERENCE_DNS(); return; } // // Rebuild the list of DNS servers // DnsQueryServerList(); // // Repost the change-notification // status = NtNotifyChangeKey( DnsTcpipInterfacesKey, DnsNotifyChangeKeyEvent, NULL, NULL, &DnsNotifyChangeKeyIoStatus, REG_NOTIFY_CHANGE_LAST_SET, TRUE, NULL, 0, TRUE ); if (!NT_SUCCESS(status)) { if (DnsNotifyChangeKeyWaitHandle) { RtlDeregisterWait(DnsNotifyChangeKeyWaitHandle); DnsNotifyChangeKeyWaitHandle = NULL; } NtClose(DnsNotifyChangeKeyEvent); DnsNotifyChangeKeyEvent = NULL; LeaveCriticalSection(&DnsGlobalInfoLock); NhTrace( TRACE_FLAG_DNS, "DnsNotifyChangeKeyCallbackRoutine: status %08x " "enabling change notify", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); DEREFERENCE_DNS(); return; } LeaveCriticalSection(&DnsGlobalInfoLock); } // DnsNotifyChangeKeyCallbackRoutine VOID NTAPI DnsNotifyChangeKeyICSDomainCallbackRoutine( PVOID Context, BOOLEAN TimedOut ) /*++ Routine Description: This routine is invoked to notify us of a change to the TCP/IP parameters subkey containing the ICS Domain suffix string information. Arguments: Context - unused TimedOut - indicates a time-out occurred Return Value: none. Environment: The routine runs in the context of an Rtl wait-thread. (See 'RtlRegisterWait'.) A reference to the component will have been made on our behalf when 'RtlRegisterWait' was called. The reference is released when the wait is cancelled, unless an error occurs here, in which case it is released immediately. --*/ { NTSTATUS status; PROFILE("DnsNotifyChangeKeyICSDomainCallbackRoutine"); EnterCriticalSection(&DnsGlobalInfoLock); if (!DnsNotifyChangeKeyICSDomainEvent) { LeaveCriticalSection(&DnsGlobalInfoLock); DEREFERENCE_DNS(); return; } // // Check to see if the domain string changed; // if it doesnt exist - create one. // DnsQueryICSDomainSuffix(); // // Repost the change-notification // status = NtNotifyChangeKey( DnsTcpipParametersKey, DnsNotifyChangeKeyICSDomainEvent, NULL, NULL, &DnsNotifyChangeKeyICSDomainIoStatus, REG_NOTIFY_CHANGE_LAST_SET, FALSE, // not interested in the subtree NULL, 0, TRUE ); if (!NT_SUCCESS(status)) { if (DnsNotifyChangeKeyICSDomainWaitHandle) { RtlDeregisterWait(DnsNotifyChangeKeyICSDomainWaitHandle); DnsNotifyChangeKeyICSDomainWaitHandle = NULL; } NtClose(DnsNotifyChangeKeyICSDomainEvent); DnsNotifyChangeKeyICSDomainEvent = NULL; LeaveCriticalSection(&DnsGlobalInfoLock); NhTrace( TRACE_FLAG_DNS, "DnsNotifyChangeKeyICSDomainCallbackRoutine: status %08x " "enabling change notify", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_ICSD_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); DEREFERENCE_DNS(); return; } LeaveCriticalSection(&DnsGlobalInfoLock); } // DnsNotifyChangeKeyICSDomainCallbackRoutine VOID NTAPI DnspQueryTimeoutCallbackRoutine( PVOID Context, BOOLEAN TimedOut ) /*++ Routine Description: This routine is called when the timeout for a query expires. We may need to resubmit the query and install a new timer, but we cannot do this in the context of an Rtl timer-routine. Therefore, queue an RTUTILS.DLL work-item to handle the timeout. Arguments: Context - holds the timer context TimedOut - unused. Return Value: none. Environment: Invoked in the context of an Rtl timer-thread with a reference made to the component on our behalf at the time 'RtlCreateTimer' was invoked. --*/ { ULONG Error; PDNS_INTERFACE Interfacep; PDNS_QUERY Queryp; NTSTATUS status; PDNS_QUERY_TIMEOUT_CONTEXT TimeoutContext; PROFILE("DnspQueryTimeoutCallbackRoutine"); TimeoutContext = (PDNS_QUERY_TIMEOUT_CONTEXT)Context; // // Look up the interface for the timeout // EnterCriticalSection(&DnsInterfaceLock); Interfacep = DnsLookupInterface(TimeoutContext->Index, NULL); if (!Interfacep || !DNS_REFERENCE_INTERFACE(Interfacep)) { LeaveCriticalSection(&DnsInterfaceLock); NhTrace( TRACE_FLAG_DNS, "DnspQueryTimeoutCallbackRoutine: interface %d not found", TimeoutContext->Index ); NH_FREE(TimeoutContext); DEREFERENCE_DNS(); return; } LeaveCriticalSection(&DnsInterfaceLock); // // Look up the query which timed out // ACQUIRE_LOCK(Interfacep); Queryp = DnsMapResponseToQuery(Interfacep, TimeoutContext->QueryId); if (!Queryp) { RELEASE_LOCK(Interfacep); DNS_DEREFERENCE_INTERFACE(Interfacep); NhTrace( TRACE_FLAG_DNS, "DnspQueryTimeoutCallbackRoutine: query %d interface %d not found", TimeoutContext->QueryId, TimeoutContext->Index ); NH_FREE(TimeoutContext); DEREFERENCE_DNS(); return; } Queryp->TimerHandle = NULL; // // Try to queue a work-item for the timeout; // if this succeeds, keep the reference on the component. // Otherwise, we have to drop the reference here. // status = RtlQueueWorkItem( DnspQueryTimeoutWorkerRoutine, Context, WT_EXECUTEINIOTHREAD ); if (NT_SUCCESS(status)) { RELEASE_LOCK(Interfacep); DNS_DEREFERENCE_INTERFACE(Interfacep); } else { NH_FREE(TimeoutContext); NhTrace( TRACE_FLAG_DNS, "DnspQueryTimeoutCallbackRoutine: RtlQueueWorkItem=%d, aborting", status ); DnsDeleteQuery(Interfacep, Queryp); RELEASE_LOCK(Interfacep); DNS_DEREFERENCE_INTERFACE(Interfacep); DEREFERENCE_DNS(); } } // DnspQueryTimeoutCallbackRoutine VOID APIENTRY DnspQueryTimeoutWorkerRoutine( PVOID Context ) /*++ Routine Description: This routine is called when the timeout for a query expires. It is queued by the query's timer-handler. Arguments: Context - holds the timer context Return Value: none. Environment: Invoked in the context of an RTUTILS worker-thread with a reference made to the component on our behalf at the time 'RtlCreateTimer' was invoked. --*/ { ULONG Error; PDNS_INTERFACE Interfacep; PDNS_QUERY Queryp; PDNS_QUERY_TIMEOUT_CONTEXT TimeoutContext; PROFILE("DnspQueryTimeoutWorkerRoutine"); TimeoutContext = (PDNS_QUERY_TIMEOUT_CONTEXT)Context; // // Look up the interface for the timeout // EnterCriticalSection(&DnsInterfaceLock); Interfacep = DnsLookupInterface(TimeoutContext->Index, NULL); if (!Interfacep || !DNS_REFERENCE_INTERFACE(Interfacep)) { LeaveCriticalSection(&DnsInterfaceLock); NhTrace( TRACE_FLAG_DNS, "DnspQueryTimeoutWorkerRoutine: interface %d not found", TimeoutContext->Index ); NH_FREE(TimeoutContext); DEREFERENCE_DNS(); return; } LeaveCriticalSection(&DnsInterfaceLock); // // Look up the query which timed out // ACQUIRE_LOCK(Interfacep); Queryp = DnsMapResponseToQuery(Interfacep, TimeoutContext->QueryId); if (!Queryp) { RELEASE_LOCK(Interfacep); DNS_DEREFERENCE_INTERFACE(Interfacep); NhTrace( TRACE_FLAG_DNS, "DnspQueryTimeoutWorkerRoutine: query %d interface %d not found", TimeoutContext->QueryId, TimeoutContext->Index ); NH_FREE(TimeoutContext); DEREFERENCE_DNS(); return; } NH_FREE(TimeoutContext); // // Have 'DnsSendQuery' repost the timed-out query. // Note that we retain our reference to the interface // on behalf of the send to be initiated in 'DnsSendQuery'. // Error = DnsSendQuery( Interfacep, Queryp, TRUE ); if (!Error) { RELEASE_LOCK(Interfacep); } else { DnsDeleteQuery(Interfacep, Queryp); RELEASE_LOCK(Interfacep); DNS_DEREFERENCE_INTERFACE(Interfacep); } DEREFERENCE_DNS(); } // DnspQueryTimeoutWorkerRoutine ULONG DnsQueryServerList( VOID ) /*++ Routine Description: This routine is invoked to read the list of DNS servers from the registry. Arguments: none. Return Value: ULONG - Win32 status code. Environment: Invoked in an arbitrary context with 'DnsGlobalInfoLock' acquired by the caller. --*/ { PUCHAR Buffer; ULONG Error; PKEY_VALUE_PARTIAL_INFORMATION Information; PDNS_INTERFACE Interfacep; OBJECT_ATTRIBUTES ObjectAttributes; NTSTATUS status; UNICODE_STRING UnicodeString; PROFILE("DnsQueryServerList"); if (!DnsTcpipInterfacesKey) { RtlInitUnicodeString(&UnicodeString, DnsTcpipInterfacesString); InitializeObjectAttributes( &ObjectAttributes, &UnicodeString, OBJ_CASE_INSENSITIVE, NULL, NULL ); // // Open the 'Tcpip\Parameters\Interfaces' registry key // status = NtOpenKey( &DnsTcpipInterfacesKey, KEY_READ, &ObjectAttributes ); if (!NT_SUCCESS(status)) { Error = RtlNtStatusToDosError(status); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: error %x opening registry key", status ); NhErrorLog( IP_DNS_PROXY_LOG_NO_SERVER_LIST, Error, "" ); return Error; } } // // See if we need to install change-notification, // and reference ourselves if so. // The reference is made on behalf of the change-notification routine // which will be invoked by a wait-thread when a change occurs. // if (!DnsNotifyChangeKeyEvent && REFERENCE_DNS()) { // // Attempt to set up change notification on the key // status = NtCreateEvent( &DnsNotifyChangeKeyEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE ); if (!NT_SUCCESS(status)) { DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: status %08x creating notify-change event", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); } else { // // Register a wait on the notify-change event // status = RtlRegisterWait( &DnsNotifyChangeKeyWaitHandle, DnsNotifyChangeKeyEvent, DnsNotifyChangeKeyCallbackRoutine, NULL, INFINITE, 0 ); if (!NT_SUCCESS(status)) { NtClose(DnsNotifyChangeKeyEvent); DnsNotifyChangeKeyEvent = NULL; DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: status %08x registering wait", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); } else { // // Register for change-notification on the key // status = NtNotifyChangeKey( DnsTcpipInterfacesKey, DnsNotifyChangeKeyEvent, NULL, NULL, &DnsNotifyChangeKeyIoStatus, REG_NOTIFY_CHANGE_LAST_SET, TRUE, NULL, 0, TRUE ); if (!NT_SUCCESS(status)) { RtlDeregisterWait(DnsNotifyChangeKeyWaitHandle); DnsNotifyChangeKeyWaitHandle = NULL; NtClose(DnsNotifyChangeKeyEvent); DnsNotifyChangeKeyEvent = NULL; DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: status %08x (%08x) " "enabling change notify", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); } } } } // // See if we need to install address-change-notification, // and reference ourselves if so. // The reference is made on behalf of the address-change-notification // routine which will be invoked by a wait-thread when a change occurs. // if (!DnsNotifyChangeAddressEvent && REFERENCE_DNS()) { // // Attempt to set up address change notification // status = NtCreateEvent( &DnsNotifyChangeAddressEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE ); if (!NT_SUCCESS(status)) { DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: status %08x creating " "notify-change address event", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); } else { // // Register a wait on the notify-change address event // status = RtlRegisterWait( &DnsNotifyChangeAddressWaitHandle, DnsNotifyChangeAddressEvent, DnsNotifyChangeAddressCallbackRoutine, NULL, INFINITE, 0 ); if (!NT_SUCCESS(status)) { NtClose(DnsNotifyChangeAddressEvent); DnsNotifyChangeAddressEvent = NULL; DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: status %08x registering wait" "for change address", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); } else { HANDLE UnusedTcpipHandle; // // Register for change-notification // ZeroMemory( &DnsNotifyChangeAddressOverlapped, sizeof(OVERLAPPED) ); DnsNotifyChangeAddressOverlapped.hEvent = DnsNotifyChangeAddressEvent; Error = NotifyAddrChange( &UnusedTcpipHandle, &DnsNotifyChangeAddressOverlapped ); if (Error != ERROR_IO_PENDING) { RtlDeregisterWait(DnsNotifyChangeAddressWaitHandle); DnsNotifyChangeAddressWaitHandle = NULL; NtClose(DnsNotifyChangeAddressEvent); DnsNotifyChangeAddressEvent = NULL; DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: error %08x" "for change address", Error ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_NOTIFY_FAILED, Error, "" ); } } } } { PIP_ADAPTER_INFO AdapterInfo; PIP_ADAPTER_INFO AdaptersInfo = NULL; ULONG Address; PIP_ADDR_STRING AddrString; ULONG dnsLength = 0; PULONG dnsServerList = NULL; PFIXED_INFO FixedInfo = NULL; LONG i; ULONG Length; PIP_PER_ADAPTER_INFO PerAdapterInfo; ULONG tempLength; PULONG tempServerList; ULONG winsLength; PULONG winsServerList = NULL; // // Read the DNS and WINS server lists. // 'GetAdaptersInfo' provides the WINS servers for each adapter, // while 'GetPerAdapterInfo' provides the DNS servers for each adapter. // While 'GetAdaptersInfo' returns an array of all adapters, // 'GetPerAdapterInfo' must be invoked for each individual adapter. // Hence we begin with 'GetAdaptersInfo', and enumerate each adapter // building the WINS and DNS server lists in parallel. // do { // // Retrieve the size of the adapter list // Length = 0; Error = GetAdaptersInfo(NULL, &Length); if (!Error) { break; } else if (Error != ERROR_BUFFER_OVERFLOW) { NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: GetAdaptersInfo=%d", Error ); NhErrorLog( IP_DNS_PROXY_LOG_ERROR_SERVER_LIST, Error, "" ); break; } // // Allocate a buffer to hold the list // AdaptersInfo = (PIP_ADAPTER_INFO)NH_ALLOCATE(Length); if (!AdaptersInfo) { NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: error allocating %d bytes", Length ); NhErrorLog( IP_DNS_PROXY_LOG_ALLOCATION_FAILED, 0, "%d", Length ); break; } // // Retrieve the list // Error = GetAdaptersInfo(AdaptersInfo, &Length); if (Error) { NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: GetAdaptersInfo=%d", Error ); NhErrorLog( IP_DNS_PROXY_LOG_NO_SERVER_LIST, Error, "" ); break; } // // Count the WINS servers // for (AdapterInfo = AdaptersInfo, winsLength = 1; AdapterInfo; AdapterInfo = AdapterInfo->Next ) { Address = inet_addr(AdapterInfo->PrimaryWinsServer.IpAddress.String); if (Address != INADDR_ANY && Address != INADDR_NONE) { ++winsLength; } Address = inet_addr(AdapterInfo->SecondaryWinsServer.IpAddress.String); if (Address != INADDR_ANY && Address != INADDR_NONE) { ++winsLength; } } // // Allocate space for the WINS servers // winsServerList = (PULONG)NH_ALLOCATE(winsLength * sizeof(ULONG)); if (!winsServerList) { NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: error allocating %d-byte WINS server list", winsLength * sizeof(ULONG) ); NhErrorLog( IP_DNS_PROXY_LOG_ALLOCATION_FAILED, 0, "%d", winsLength * sizeof(ULONG) ); break; } // // Now fill in the WINS server names from each adapter. // In the process, we pick up the DNS server lists for each adapter. // for (AdapterInfo = AdaptersInfo, Length = 0; AdapterInfo; AdapterInfo = AdapterInfo->Next ) { Address = inet_addr(AdapterInfo->PrimaryWinsServer.IpAddress.String); if (Address != INADDR_ANY && Address != INADDR_NONE) { for (i = 0; i < (LONG)Length; i++) { if (Address == winsServerList[i]) { break; } } if (i >= (LONG)Length) { winsServerList[Length++] = Address; } } Address = inet_addr(AdapterInfo->SecondaryWinsServer.IpAddress.String); if (Address != INADDR_ANY && Address != INADDR_NONE) { for (i = 0; i < (LONG)Length; i++) { if (Address == winsServerList[i]) { break; } } if (i >= (LONG)Length) { winsServerList[Length++] = Address; } } // // Now obtain the DNS servers for the adapter. // Error = GetPerAdapterInfo(AdapterInfo->Index, NULL, &tempLength); if (Error != ERROR_BUFFER_OVERFLOW) { continue; } // // Allocate memory for the per-adapter info // PerAdapterInfo = reinterpret_cast<PIP_PER_ADAPTER_INFO>( NH_ALLOCATE(tempLength) ); if (!PerAdapterInfo) { NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: error allocating %d bytes", tempLength ); NhErrorLog( IP_DNS_PROXY_LOG_ALLOCATION_FAILED, 0, "%d", tempLength ); continue; } // // Retrieve the per-adapter info // Error = GetPerAdapterInfo( AdapterInfo->Index, PerAdapterInfo, &tempLength ); if (Error) { NH_FREE(PerAdapterInfo); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: GetPerAdapterInfo=%d", Error ); NhErrorLog( IP_DNS_PROXY_LOG_NO_SERVER_LIST, Error, "" ); continue; } // // Count the DNS servers for the adapter // for (AddrString = &PerAdapterInfo->DnsServerList, tempLength = 0; AddrString; AddrString = AddrString->Next ) { Address = inet_addr(AddrString->IpAddress.String); if (Address != INADDR_ANY && Address != INADDR_NONE) { ++tempLength; } } if (!tempLength) { NH_FREE(PerAdapterInfo); continue; } // // Allocate space for the adapter's DNS servers // tempServerList = reinterpret_cast<PULONG>( NH_ALLOCATE((dnsLength + tempLength + 1) * sizeof(ULONG)) ); if (!tempServerList) { NH_FREE(PerAdapterInfo); NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: error allocating %d bytes", (dnsLength + tempLength + 1) * sizeof(ULONG) ); NhErrorLog( IP_DNS_PROXY_LOG_ALLOCATION_FAILED, 0, "%d", (dnsLength + tempLength + 1) * sizeof(ULONG) ); continue; } // // Copy the existing servers // if (dnsServerList) { CopyMemory( tempServerList, dnsServerList, dnsLength * sizeof(ULONG) ); } // // Read the new servers into the new server list // for (AddrString = &PerAdapterInfo->DnsServerList; AddrString; AddrString = AddrString->Next ) { Address = inet_addr(AddrString->IpAddress.String); if (Address == INADDR_ANY || Address == INADDR_NONE) { continue; } for (i = 0; i < (LONG)dnsLength; i++) { if (Address == tempServerList[i]) { break; } } if (i < (LONG)dnsLength) { continue; } // // The current DNS server goes in the front of the list, // while any other server is appended. // if (PerAdapterInfo->CurrentDnsServer != AddrString) { tempServerList[dnsLength] = Address; } else { MoveMemory( tempServerList + sizeof(ULONG), tempServerList, dnsLength * sizeof(ULONG) ); tempServerList[0] = Address; } ++dnsLength; } tempServerList[dnsLength] = 0; NH_FREE(PerAdapterInfo); // // Replace the existing server list // if (dnsServerList) { NH_FREE(dnsServerList); } dnsServerList = tempServerList; } winsServerList[Length] = 0; } while(FALSE); if (AdaptersInfo) { NH_FREE(AdaptersInfo); } // // Store the new server lists // NhTrace( TRACE_FLAG_DNS, "DnsQueryServerList: new server list lengths are : DNS (%d) WINS (%d)", dnsLength, Length ); if (DnsServerList[DnsProxyDns]) { NH_FREE(DnsServerList[DnsProxyDns]); } DnsServerList[DnsProxyDns] = dnsServerList; if (DnsServerList[DnsProxyWins]) { NH_FREE(DnsServerList[DnsProxyWins]); } DnsServerList[DnsProxyWins] = winsServerList; } return NO_ERROR; } // DnsQueryServerList VOID DnsQueryRegistryICSDomainSuffix( VOID ) /*++ Routine Description: This routine is invoked to read the ICS Domain suffix from the registry. Arguments: none. Return Value: VOID. Environment: Invoked in an arbitrary context with 'DnsGlobalInfoLock' acquired by the caller. --*/ { NTSTATUS status; PKEY_VALUE_PARTIAL_INFORMATION Information = NULL; DWORD dwSize = 0; LPVOID lpMsgBuf; BOOL fSuffixChanged = FALSE; BOOL fUseDefaultSuffix = FALSE; // // retrieve current suffix string (if any) // status = NhQueryValueKey( DnsTcpipParametersKey, DnsICSDomainValueName, &Information ); if (!NT_SUCCESS(status) || !Information) { NhTrace( TRACE_FLAG_DNS, "DnsQueryRegistryICSDomainSuffix: error (0x%08x) querying " "ICS Domain suffix name", status ); // // if we did not find it in the registry and we had previously // got some suffix - we revert to default string (happens below) // if ((STATUS_OBJECT_NAME_NOT_FOUND == status) && DnsICSDomainSuffix) { NH_FREE(DnsICSDomainSuffix); DnsICSDomainSuffix = NULL; } // // if we have no idea of the string, set our copy to default string // if (NULL == DnsICSDomainSuffix) { dwSize = wcslen(DNS_HOMENET_SUFFIX) + 1; DnsICSDomainSuffix = reinterpret_cast<PWCHAR>( NH_ALLOCATE(sizeof(WCHAR) * dwSize) ); if (!DnsICSDomainSuffix) { NhTrace( TRACE_FLAG_DNS, "DnsQueryRegistryICSDomainSuffix: allocation " "failed for DnsICSDomainSuffix" ); return; } wcscpy(DnsICSDomainSuffix, DNS_HOMENET_SUFFIX); fSuffixChanged = TRUE; } } else { // // check to see that what we read is a null terminated string // if (REG_SZ != Information->Type || L'\0' != *(PWCHAR) (Information->Data + (Information->DataLength - sizeof(WCHAR)))) { NH_FREE(Information); NhTrace( TRACE_FLAG_REG, "DnsQueryRegistryICSDomainSuffix: Registry contains invalid data" ); return; } // // overwrite our current version of suffix string // dwSize = lstrlenW((PWCHAR)Information->Data); if (dwSize) { // // we have a nonzero string // dwSize++; // add 1 for terminating null } else { // // the data is a null string - use default suffix // dwSize = wcslen(DNS_HOMENET_SUFFIX) + 1; fUseDefaultSuffix = TRUE; } if (DnsICSDomainSuffix) { NH_FREE(DnsICSDomainSuffix); DnsICSDomainSuffix = NULL; } DnsICSDomainSuffix = reinterpret_cast<PWCHAR>( NH_ALLOCATE(sizeof(WCHAR) * dwSize) ); if (!DnsICSDomainSuffix) { NH_FREE(Information); NhTrace( TRACE_FLAG_DNS, "DnsQueryRegistryICSDomainSuffix: allocation " "failed for DnsICSDomainSuffix" ); return; } if (!fUseDefaultSuffix) { wcscpy(DnsICSDomainSuffix, (PWCHAR) Information->Data); } else { wcscpy(DnsICSDomainSuffix, DNS_HOMENET_SUFFIX); } fSuffixChanged = TRUE; NH_FREE(Information); } if (fSuffixChanged) { // // enumerate existing entries and replace old ones // + we must do this because otherwise forward and reverse lookups // are dependent on the way in which the entries are ordered in // the hosts.ics file // //DnsReplaceOnSuffixChange(); } } // DnsQueryRegistryICSDomainSuffix ULONG DnsQueryICSDomainSuffix( VOID ) /*++ Routine Description: This routine invokes DnsQueryRegistryICSDomainSuffix and installs change notification for this reg key if necessary. Arguments: none. Return Value: ULONG - Win32 status code. Environment: Invoked in an arbitrary context with 'DnsGlobalInfoLock' acquired by the caller. --*/ { PUCHAR Buffer; ULONG Error; PKEY_VALUE_PARTIAL_INFORMATION Information; OBJECT_ATTRIBUTES ObjectAttributes; NTSTATUS status; UNICODE_STRING UnicodeString; PROFILE("DnsQueryICSDomainSuffix"); if (!DnsTcpipParametersKey) { RtlInitUnicodeString(&UnicodeString, DnsTcpipParametersString); InitializeObjectAttributes( &ObjectAttributes, &UnicodeString, OBJ_CASE_INSENSITIVE, NULL, NULL ); // // Open the 'Tcpip\Parameters' registry key // status = NtOpenKey( &DnsTcpipParametersKey, KEY_READ, &ObjectAttributes ); if (!NT_SUCCESS(status)) { Error = RtlNtStatusToDosError(status); NhTrace( TRACE_FLAG_DNS, "DnsQueryICSDomainSuffix: error %x opening registry key", status ); NhErrorLog( IP_DNS_PROXY_LOG_NO_ICSD_SUFFIX, Error, "" ); return Error; } } // // See if we need to install change-notification, // and reference ourselves if so. // The reference is made on behalf of the change-notification routine // which will be invoked by a wait-thread when a change occurs. // if (!DnsNotifyChangeKeyICSDomainEvent && REFERENCE_DNS()) { // // Attempt to set up change notification on the key // status = NtCreateEvent( &DnsNotifyChangeKeyICSDomainEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE ); if (!NT_SUCCESS(status)) { DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryICSDomainSuffix: status %08x creating notify-change event", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_ICSD_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); } else { // // Register a wait on the notify-change event // status = RtlRegisterWait( &DnsNotifyChangeKeyICSDomainWaitHandle, DnsNotifyChangeKeyICSDomainEvent, DnsNotifyChangeKeyICSDomainCallbackRoutine, NULL, INFINITE, 0 ); if (!NT_SUCCESS(status)) { NtClose(DnsNotifyChangeKeyICSDomainEvent); DnsNotifyChangeKeyICSDomainEvent = NULL; DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryICSDomainSuffix: status %08x registering wait", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_ICSD_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); } else { // // Register for change-notification on the key // status = NtNotifyChangeKey( DnsTcpipParametersKey, DnsNotifyChangeKeyICSDomainEvent, NULL, NULL, &DnsNotifyChangeKeyICSDomainIoStatus, REG_NOTIFY_CHANGE_LAST_SET, FALSE, // not interested in the subtree NULL, 0, TRUE ); if (!NT_SUCCESS(status)) { RtlDeregisterWait(DnsNotifyChangeKeyICSDomainWaitHandle); DnsNotifyChangeKeyICSDomainWaitHandle = NULL; NtClose(DnsNotifyChangeKeyICSDomainEvent); DnsNotifyChangeKeyICSDomainEvent = NULL; DEREFERENCE_DNS(); NhTrace( TRACE_FLAG_DNS, "DnsQueryICSDomainSuffix: status %08x (%08x) " "enabling change notify", status ); NhWarningLog( IP_DNS_PROXY_LOG_CHANGE_ICSD_NOTIFY_FAILED, RtlNtStatusToDosError(status), "" ); } } } } DnsQueryRegistryICSDomainSuffix(); return NO_ERROR; } // DnsQueryICSDomainSuffix PDNS_QUERY DnsRecordQuery( PDNS_INTERFACE Interfacep, PNH_BUFFER QueryBuffer ) /*++ Routine Description: This routine is invoked to create a pending-query entry for a client's DNS query. Arguments: Interfacep - the interface on which to create the record QueryBuffer - the DNS request for which to create a record Return Value: PDNS_QUERY - the pending query if created Environment: Invoked with 'Interfacep' locked by the caller. --*/ { BOOLEAN ConflictFound; PDNS_HEADER Headerp; PLIST_ENTRY Link; USHORT QueryId; PDNS_QUERY Queryp; ULONG RetryCount = MAXCHAR; ULONG Seed = GetTickCount(); PROFILE("DnsRecordQuery"); // // Attempt to generate a random ID for the query. // Assuming we succeed, we leave the loop with 'Link' // set to the correct insertion-point for the new query. // do { QueryId = (USHORT)((RtlRandom(&Seed) & 0xffff0000) >> 16); ConflictFound = FALSE; for (Link = Interfacep->QueryList.Flink; Link != &Interfacep->QueryList; Link = Link->Flink) { Queryp = CONTAINING_RECORD(Link, DNS_QUERY, Link); if (QueryId > Queryp->QueryId) { continue; } else if (QueryId < Queryp->QueryId) { break; } ConflictFound = TRUE; break; } } while(ConflictFound && --RetryCount); if (ConflictFound) { return NULL; } // // Allocate and initialize the new query // Queryp = reinterpret_cast<PDNS_QUERY>(NH_ALLOCATE(sizeof(DNS_QUERY))); if (!Queryp) { NhTrace( TRACE_FLAG_DNS, "DnsRecordQuery: allocation failed for DNS query" ); NhErrorLog( IP_DNS_PROXY_LOG_ALLOCATION_FAILED, 0, "%d", sizeof(DNS_QUERY) ); return NULL; } Headerp = (PDNS_HEADER)QueryBuffer->Buffer; Queryp->QueryId = QueryId; Queryp->SourceId = Headerp->Xid; Queryp->SourceAddress = QueryBuffer->ReadAddress.sin_addr.s_addr; Queryp->SourcePort = QueryBuffer->ReadAddress.sin_port; Queryp->Type = DNS_PROXY_PORT_TO_TYPE(NhQueryPortSocket(QueryBuffer->Socket)); Queryp->QueryLength = QueryBuffer->BytesTransferred; Queryp->Bufferp = QueryBuffer; Queryp->Interfacep = Interfacep; Queryp->TimerHandle = NULL; Queryp->RetryCount = 0; // // Insert the new query in the location determined above. // InsertTailList(Link, &Queryp->Link); return Queryp; } // DnsRecordQuery ULONG DnsSendQuery( PDNS_INTERFACE Interfacep, PDNS_QUERY Queryp, BOOLEAN Resend ) /*++ Routine Description: This routine is invoked to forward a query to our DNS servers. Arguments: Interfacep - the interface on which to send the query Queryp - the DNS request to be sent Resend - if TRUE, the buffer is being resent; otherwise, the buffer is being sent for the first time. Return Value: ULONG - Win32 status code. On success, 'Queryp' may have been deleted. Environment: Invoked with 'Interfacep' locked by the caller, and with a reference made to it for the send which occurs here. If the routine fails, it is the caller's responsibility to release that reference. --*/ { PNH_BUFFER Bufferp; ULONG Error; ULONG i, j; PULONG ServerList; SOCKET Socket; NTSTATUS status; PDNS_QUERY_TIMEOUT_CONTEXT TimeoutContext; ULONG TimeoutSeconds; PROFILE("DnsSendQuery"); // // For WINS queries, we use a global socket to work around the fact that // even though we're bound to the WINS port, responses will only be // delivered to the first socket bound to the socket, which is // the kernel-mode NetBT driver. // EnterCriticalSection(&DnsGlobalInfoLock); if (Queryp->Type == DnsProxyDns) { Socket = Queryp->Bufferp->Socket; ServerList = DnsServerList[DnsProxyDns]; } else { Socket = DnsGlobalSocket; ServerList = DnsServerList[DnsProxyWins]; } LeaveCriticalSection(&DnsGlobalInfoLock); // // See if there are any servers to be tried. // if (!ServerList || !ServerList[0] || Queryp->RetryCount++ > DNS_QUERY_RETRY) { if (!ServerList) { NhTrace( TRACE_FLAG_DNS, "DnsSendQuery: no server list" ); } else if (!ServerList[0]) { NhTrace( TRACE_FLAG_DNS, "DnsSendQuery: no server entries in list" ); } else { NhTrace( TRACE_FLAG_DNS, "DnsSendQuery: retry count for query %d " "greater than DNS_QUERY_RETRY(%d)", Queryp->QueryId, DNS_QUERY_RETRY ); } if (REFERENCE_DNS()) { // // Initiate an attempt to connect the default interface, if any. // status = RtlQueueWorkItem( DnsConnectDefaultInterface, NULL, WT_EXECUTEINIOTHREAD ); if (!NT_SUCCESS(status)) { DEREFERENCE_DNS(); } } NhInformationLog( IP_DNS_PROXY_LOG_NO_SERVERS_LEFT, 0, "%I", Queryp->SourceAddress ); return ERROR_NO_MORE_ITEMS; } // // Send the query to each server on the list // for (i = 0; ServerList[i]; i++) { for (j = 0; j < Interfacep->BindingCount; j++) { if (Interfacep->BindingArray[j].Address == ServerList[i]) { break; } } if (j < Interfacep->BindingCount) { NhTrace( TRACE_FLAG_DNS, "DnsSendQuery: server %s is self, ignoring", INET_NTOA(ServerList[i]) ); continue; } if (!DNS_REFERENCE_INTERFACE(Interfacep) || !(Bufferp = NhDuplicateBuffer(Queryp->Bufferp))) { continue; } NhTrace( TRACE_FLAG_DNS, "DnsSendQuery: sending query %d interface %d to %s", (PVOID)((PDNS_HEADER)Bufferp->Buffer)->Xid, Interfacep->Index, INET_NTOA(ServerList[i]) ); // // Send the message // Error = NhWriteDatagramSocket( &DnsComponentReference, Socket, ServerList[i], DNS_PROXY_TYPE_TO_PORT(Queryp->Type), Bufferp, Queryp->QueryLength, DnsWriteCompletionRoutine, Interfacep, (PVOID)Queryp->QueryId ); if (!Error) { InterlockedIncrement( reinterpret_cast<LPLONG>(&DnsStatistics.QueriesSent) ); } else { NhTrace( TRACE_FLAG_DNS, "DnsSendQuery: error %d sending query %d interface %d", Error, Queryp->QueryId, Interfacep->Index ); NhErrorLog( IP_DNS_PROXY_LOG_QUERY_FAILED, Error, "%I%I%I", Queryp->SourceAddress, ServerList[i], NhQueryAddressSocket(Bufferp->Socket) ); Error = NO_ERROR; NhReleaseBuffer(Bufferp); DNS_DEREFERENCE_INTERFACE(Interfacep); } } // // Set up the query's timeout. // Note that we are now certain that the write-completion routine // will be executed. However, if the timeout cannot be set, // we want to be assured that the query will still be deleted. // Therefore, on failure we delete the query immediately, // and the write-completion routine will simply not find it. // status = STATUS_UNSUCCESSFUL; EnterCriticalSection(&DnsGlobalInfoLock); TimeoutSeconds = DnsGlobalInfo->TimeoutSeconds; LeaveCriticalSection(&DnsGlobalInfoLock); if (Queryp->TimerHandle) { // // Update the timer-queue entry for the query // status = NhUpdateTimer( Queryp->TimerHandle, TimeoutSeconds * 1000 ); } else { // // Allocate a timer-queue entry context block // TimeoutContext = reinterpret_cast<PDNS_QUERY_TIMEOUT_CONTEXT>( NH_ALLOCATE(sizeof(*TimeoutContext)) ); if (!TimeoutContext) { NhTrace( TRACE_FLAG_DNS, "DnsSendQuery: error allocating query %d timeout context", Queryp->QueryId ); status = STATUS_UNSUCCESSFUL; } else { TimeoutContext->Index = Interfacep->Index; TimeoutContext->QueryId = Queryp->QueryId; // // Insert a timer-queue entry to check the status of the query // status = NhSetTimer( &DnsComponentReference, &Queryp->TimerHandle, DnspQueryTimeoutCallbackRoutine, TimeoutContext, TimeoutSeconds * 1000 ); if (!NT_SUCCESS(status)) { NH_FREE(TimeoutContext); Queryp->TimerHandle = NULL; } } } // // If the above failed, delete the query now. // if (!NT_SUCCESS(status)) { NhTrace( TRACE_FLAG_DNS, "DnsSendQuery: status %08x setting timer for query %d", status, Queryp->QueryId ); DnsDeleteQuery(Interfacep, Queryp); } DNS_DEREFERENCE_INTERFACE(Interfacep); return NO_ERROR; } // DnsSendQuery
26.74508
85
0.519593
npocmaka
96c360efe5ceec388a286236c77b3ed67a4b1eeb
478
cpp
C++
smart_ptr_test.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
1
2019-03-21T04:06:13.000Z
2019-03-21T04:06:13.000Z
smart_ptr_test.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
null
null
null
smart_ptr_test.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
null
null
null
/* Copyright (C) 2019 hnqiu. All rights reserved. * Licensed under the MIT License. See LICENSE for details. */ #include <iostream> #include <memory> #include <vector> #include "class_test.h" int smart_ptr_test() { std::shared_ptr<Agent> agt = std::make_shared<Agent>(1); std::vector<decltype(agt)> agents; agents.push_back(agt); auto first_elem = agents.begin(); std::cout << "agent's id is " << (*first_elem)->get_id() << std::endl; return 0; }
22.761905
74
0.658996
hnqiu
96c85c75575dc9b33ecabf72f8e2b8f699068fd8
1,629
cpp
C++
Arrays/DesignStackIncrementOps.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
1
2021-01-31T03:43:59.000Z
2021-01-31T03:43:59.000Z
Arrays/DesignStackIncrementOps.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
null
null
null
Arrays/DesignStackIncrementOps.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
1
2021-01-25T14:27:08.000Z
2021-01-25T14:27:08.000Z
#include <iostream> using namespace std; class CustomStack_Array { int *stkArr; int stkSize; // keep a track of number of elements or top position int stkTop; public: // constructor CustomStack_Array(int maxSize) { stkArr = new int[maxSize]; stkTop = 0; stkSize = maxSize; } // destructor ~CustomStack_Array() { delete stkArr; } // push an element to the stack void push(int x) { if (stkTop < stkSize) { stkArr[stkTop++] = x; } } // pop an element from the top of the stack and return it, if empty return -1 int pop() { if (stkTop) { // 0 based indexing return stkArr[--stkTop]; } return -1; } // increment the bottom k elements of the stack by val void increment(int k, int val) { for (int i = 0; i < stkTop && i < k; i++) { stkArr[i] += val; } } void printElements() { for (int i = 0; i < stkTop; i++) { cout << stkArr[i] << " "; } cout << endl; } }; int main() { CustomStack_Array csa(10); csa.push(6); csa.push(66); csa.push(7); csa.push(5); csa.push(99); csa.push(8); csa.push(4); cout << "Elements in the stack are: "; csa.printElements(); int x = csa.pop(); x = csa.pop(); x = csa.pop(); x = csa.pop(); cout << "Top element of stack is: " << csa.pop() << endl; cout << "Elements in the stack are: "; csa.printElements(); return 0; }
19.626506
81
0.493554
karan2808
96ccf681f5512d65eee912482db5800a9f1ff0c3
13,223
cpp
C++
Code/Sumo_RTOS/FREERTOS_SHELL/Source/lib/serial/rs232int.cpp
ryanforsberg/me507
5a9fd25e2062fec3c9d0cb141d360ad67709488b
[ "MIT" ]
null
null
null
Code/Sumo_RTOS/FREERTOS_SHELL/Source/lib/serial/rs232int.cpp
ryanforsberg/me507
5a9fd25e2062fec3c9d0cb141d360ad67709488b
[ "MIT" ]
null
null
null
Code/Sumo_RTOS/FREERTOS_SHELL/Source/lib/serial/rs232int.cpp
ryanforsberg/me507
5a9fd25e2062fec3c9d0cb141d360ad67709488b
[ "MIT" ]
null
null
null
//************************************************************************************* /** \file rs232int.cpp * This file contains a class which allows the use of a serial port on an AVR * microcontroller. This version of the class uses the serial port receiver * interrupt and a buffer to allow characters to be received in the background. * The port is used in "text mode"; that is, the information which is sent and * received is expected to be plain ASCII text, and the set of overloaded left-shift * operators "<<" in emstream.* can be used to easily send all sorts of data * to the serial port in a manner similar to iostreams (like "cout") in regular C++. * * Revised: * \li 09-14-2017 CTR Adapted from JRR code for AVR to be compatibile with xmega series * * License: * This file is copyright 2012 by JR Ridgely and released under the Lesser GNU * Public License, version 2. It intended for educational use only, but its use * is not limited thereto. */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN- * TIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //************************************************************************************* #include <stdint.h> #include <stdlib.h> #include <avr/io.h> #include "rs232int.h" uint8_t* rcvC0_buffer = NULL; uint8_t* rcvC1_buffer = NULL; uint8_t* rcvD0_buffer = NULL; uint8_t* rcvD1_buffer = NULL; uint8_t* rcvE0_buffer = NULL; uint8_t* rcvE1_buffer = NULL; uint8_t* rcvF0_buffer = NULL; /// This index is used to write into serial character receiver buffer 0. uint16_t rcvC0_read_index; uint16_t rcvC1_read_index; uint16_t rcvD0_read_index; uint16_t rcvD1_read_index; uint16_t rcvE0_read_index; uint16_t rcvE1_read_index; uint16_t rcvF0_read_index; /// This index is used to read from serial character receiver buffer 0. uint16_t rcvC0_write_index; uint16_t rcvC1_write_index; uint16_t rcvD0_write_index; uint16_t rcvD1_write_index; uint16_t rcvE0_write_index; uint16_t rcvE1_write_index; uint16_t rcvF0_write_index; //------------------------------------------------------------------------------------- /** This method sets up the AVR UART for communications. It calls the emstream * constructor, which prepares to convert numbers to text strings, and the base232 * constructor, which does the work of setting up the serial port. Note that the user * program must call sei() somewhere to enable global interrupts so that this driver * will work. It is not called in this constructor because it's common to construct * many drivers which use interrupts, including this one, and then enable interrupts * globally using sei() after all the constructors have been called. * @param baud_rate The desired baud rate for serial communications. Default is 9600 * @param p_usart A pointer to the desired USART c-struct. The default is USARTC0. On an * XMGEGA choices are C0, C1, D0, D1, E0, E1, F0 */ rs232::rs232 (uint16_t baud_rate, USART_t* p_usart) : emstream (), base232 (baud_rate, p_usart) { if(p_usart == &USARTC0) { p_rcv_buffer = &rcvC0_buffer; p_rcv_read_index = &rcvC0_read_index; p_rcv_write_index = &rcvC0_write_index; } #ifdef USARTC1 else if(p_usart == &USARTC1) { p_rcv_buffer = &rcvC1_buffer; p_rcv_read_index = &rcvC1_read_index; p_rcv_write_index = &rcvC1_write_index; } #endif #ifdef USARTD0 else if(p_usart == &USARTD0) { p_rcv_buffer = &rcvD0_buffer; p_rcv_read_index = &rcvD0_read_index; p_rcv_write_index = &rcvD0_write_index; } #endif #ifdef USARTD1 else if(p_usart == &USARTD1) { p_rcv_buffer = &rcvD1_buffer; p_rcv_read_index = &rcvD1_read_index; p_rcv_write_index = &rcvD1_write_index; } #endif #ifdef USARTE0 else if(p_usart == &USARTE0) { p_rcv_buffer = &rcvE0_buffer; p_rcv_read_index = &rcvE0_read_index; p_rcv_write_index = &rcvE0_write_index; } #endif #ifdef USARTE1 else if(p_usart == &USARTE1) { p_rcv_buffer = &rcvE1_buffer; p_rcv_read_index = &rcvE1_read_index; p_rcv_write_index = &rcvE1_write_index; } #endif #ifdef USARTF0 else if(p_usart == &USARTF0) { p_rcv_buffer = &rcvF0_buffer; p_rcv_read_index = &rcvF0_read_index; p_rcv_write_index = &rcvF0_write_index; } #endif else { } *p_rcv_buffer = new uint8_t[RSINT_BUF_SIZE]; *p_rcv_read_index = 0; *p_rcv_write_index = 0; } //------------------------------------------------------------------------------------- /** This method sends one character to the serial port. It waits until the port is * ready, so it can hold up the system for a while. It times out if it waits too * long to send the character; you can check the return value to see if the character * was successfully sent, or just cross your fingers and ignore the return value. * Note 1: It's possible that at slower baud rates and/or higher processor speeds, * this routine might time out even when the port is working fine. A solution would * be to change the count variable to an integer and use a larger starting number. * Note 2: Fixed! The count is now an integer and it works at lower baud rates. * @param chout The character to be sent out * @return True if everything was OK and false if there was a timeout */ bool rs232::putchar (char chout) { // Now wait for the serial port transmitter buffer to be empty for (uint16_t count = 0; ((*p_USR & mask_UDRE) == 0); count++) { if (count > UART_TX_TOUT) return (false); } // Clear the TXCn bit so it can be used to check if the serial port is busy. This // check needs to be done prior to putting the processor into sleep mode. Oddly, // the TXCn bit is cleared by writing a one to its bit location *p_USR |= mask_TXC; // The CTS line is 0 and the transmitter buffer is empty, so send the character *p_UDR = chout; return (true); } //------------------------------------------------------------------------------------- /** This method gets one character from the serial port, if one is there. If not, it * waits until there is a character available. This can sometimes take a long time * (even forever), so use this function carefully. One should almost always use * check_for_char() to ensure that there's data available first. * @return The character which was found in the serial port receive buffer */ int16_t rs232::getchar (void) { uint8_t recv_char; // Character read from the queue // Wait until there's a character in the receiver queue while (*p_rcv_read_index == *p_rcv_write_index); recv_char = (*p_rcv_buffer)[*p_rcv_read_index]; if (++(*p_rcv_read_index) >= RSINT_BUF_SIZE) *p_rcv_read_index = 0; return (recv_char); } //------------------------------------------------------------------------------------- /** This method checks if there is a character in the serial port's receiver queue. * The queue will have been filled if a character came in through the serial port and * caused an interrupt. * @return True for character available, false for no character available */ bool rs232::check_for_char (void) { return (*p_rcv_read_index != *p_rcv_write_index); } //------------------------------------------------------------------------------------- /** This method sends the ASCII code to clear a display screen. It is called when the * format modifier 'clrscr' is inserted in a line of "<<" stuff. */ void rs232::clear_screen (void) { putchar (CLRSCR_STYLE); } //------------------------------------------------------------------------------------- /** \cond NOT_ENABLED (This ISR is not to be documented by Doxygen) * This interrupt service routine runs whenever a character has been received by the * first serial port (number 0). It saves that character into the receiver buffer. */ #ifdef USARTC0_RXC_vect ISR (USARTC0_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvC0_buffer[rcvC0_write_index] = USARTC0.DATA; // Increment the write pointer if (++rcvC0_write_index >= RSINT_BUF_SIZE) rcvC0_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvC0_write_index == rcvC0_read_index) if (++rcvC0_read_index >= RSINT_BUF_SIZE) rcvC0_read_index = 0; } #endif #ifdef USARTC1_RXC_vect ISR (USARTC1_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvC1_buffer[rcvC1_write_index] = USARTC1.DATA; // Increment the write pointer if (++rcvC1_write_index >= RSINT_BUF_SIZE) rcvC1_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvC1_write_index == rcvC1_read_index) if (++rcvC1_read_index >= RSINT_BUF_SIZE) rcvC1_read_index = 0; } #endif #ifdef USARTD0_RXC_vect ISR (USARTD0_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvD0_buffer[rcvD0_write_index] = USARTD0.DATA; // Increment the write pointer if (++rcvD0_write_index >= RSINT_BUF_SIZE) rcvD0_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvD0_write_index == rcvD0_read_index) if (++rcvD0_read_index >= RSINT_BUF_SIZE) rcvD0_read_index = 0; } #endif #ifdef USARTD1_RXC_vect ISR (USARTD1_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvD1_buffer[rcvD1_write_index] = USARTD1.DATA; // Increment the write pointer if (++rcvD1_write_index >= RSINT_BUF_SIZE) rcvD1_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvD1_write_index == rcvD1_read_index) if (++rcvD1_read_index >= RSINT_BUF_SIZE) rcvD1_read_index = 0; } #endif #ifdef USARTE0_RXC_vect ISR (USARTE0_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvE0_buffer[rcvE0_write_index] = USARTE0.DATA; // Increment the write pointer if (++rcvE0_write_index >= RSINT_BUF_SIZE) rcvE0_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvE0_write_index == rcvE0_read_index) if (++rcvE0_read_index >= RSINT_BUF_SIZE) rcvE0_read_index = 0; } #endif #ifdef USARTE1_RXC_vect ISR (USARTE1_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvE1_buffer[rcvE1_write_index] = USARTE1.DATA; // Increment the write pointer if (++rcvE1_write_index >= RSINT_BUF_SIZE) rcvE1_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvE1_write_index == rcvE1_read_index) if (++rcvE1_read_index >= RSINT_BUF_SIZE) rcvE1_read_index = 0; } #endif #ifdef USARTF0_RXC_vect ISR (USARTF0_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvF0_buffer[rcvF0_write_index] = USARTF0.DATA; // Increment the write pointer if (++rcvF0_write_index >= RSINT_BUF_SIZE) rcvF0_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvF0_write_index == rcvF0_read_index) if (++rcvF0_read_index >= RSINT_BUF_SIZE) rcvF0_read_index = 0; } #endif
35.641509
90
0.703547
ryanforsberg
96cddc003fed9b2b7e4054d6b2ba569b08966190
1,618
cpp
C++
call_thunk.cpp
znone/call_thunk
f4b16151f15a27bbc5ac939ee9053ebc4bf71790
[ "Apache-2.0" ]
23
2018-08-15T13:25:23.000Z
2022-02-24T15:17:28.000Z
call_thunk.cpp
znone/call_thunk
f4b16151f15a27bbc5ac939ee9053ebc4bf71790
[ "Apache-2.0" ]
3
2020-03-07T04:07:08.000Z
2022-01-05T08:10:40.000Z
call_thunk.cpp
znone/call_thunk
f4b16151f15a27bbc5ac939ee9053ebc4bf71790
[ "Apache-2.0" ]
6
2019-08-07T13:47:50.000Z
2021-08-01T08:13:06.000Z
#include "call_thunk.h" #ifdef _WIN32 #include <windows.h> #else #include <sys/mman.h> #ifndef offsetof #define offsetof(s,m) ((size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m))) #endif //offsetof #ifndef _countof #define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0])) #endif //_countof #endif //_WIN32 #include <string.h> #include <assert.h> #include <memory> namespace call_thunk { #pragma pack(push, 1) #if defined(_M_IX86) || defined(__i386__) #include "thunk_code_x86.cpp" #elif defined(_M_X64) || defined(__x86_64__) #include "thunk_code_x64.cpp" #endif void base_thunk::init_code(call_declare caller, call_declare callee, size_t argc, const argument_info* arginfos) throw(bad_call) { _thunk_size = thunk_code::calc_size(caller, callee, argc, arginfos); #if defined(_WIN32) _code = (char*)VirtualAlloc(NULL, _thunk_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); #else _code = (char*)mmap(NULL, _thunk_size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #endif //_WIN32 _thunk = reinterpret_cast<thunk_code*>(_code); _code += sizeof(thunk_code); new(_thunk) thunk_code(caller, callee, argc, arginfos); } void base_thunk::destroy_code() { if (_thunk) { #if defined(_WIN32) VirtualFree(_thunk, 0, MEM_RELEASE); #else munmap(_thunk, _thunk_size); #endif //_WIN32 _thunk = NULL; _code = NULL; _thunk_size = 0; } } void base_thunk::flush_cache() { #ifdef _WIN32 FlushInstructionCache(GetCurrentProcess(), _thunk, _thunk_size); #else #endif //_WIN32 } void base_thunk::bind_impl(void* object, void* proc) { _thunk->bind(object, proc); } }
21.012987
128
0.729913
znone
96ce1059bdea666f57aa7bc1cd3481c4a62737b1
4,324
cpp
C++
win/catfish/pickdir.cpp
KOLANICH/metakit
b05ed925f7aab8dc102bc42f1942869b4f72317e
[ "MIT" ]
null
null
null
win/catfish/pickdir.cpp
KOLANICH/metakit
b05ed925f7aab8dc102bc42f1942869b4f72317e
[ "MIT" ]
null
null
null
win/catfish/pickdir.cpp
KOLANICH/metakit
b05ed925f7aab8dc102bc42f1942869b4f72317e
[ "MIT" ]
2
2019-11-26T21:34:10.000Z
2020-03-10T14:26:27.000Z
// pickdir.cpp - directory picker sample code // // Copyright (C) 1996-2000 Jean-Claude Wippler. All rights reserved. ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "scandisk.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMyFileDlg dialog, adapted from DIRPKR sample code (EMS_9502.1\CUTIL) #include "dlgs.h" class CMyFileDlg : public CFileDialog { public: // Public data members BOOL m_bDlgJustCameUp; // Constructors CMyFileDlg(BOOL bOpenFileDialog, // TRUE for FileOpen, FALSE for FileSaveAs LPCSTR lpszDefExt = NULL, LPCSTR lpszFileName = NULL, DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, LPCSTR lpszFilter = NULL, CWnd* pParentWnd = NULL); // Implementation protected: //{{AFX_MSG(CMyFileDlg) virtual BOOL OnInitDialog(); afx_msg void OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(CMyFileDlg, CFileDialog) //{{AFX_MSG_MAP(CMyFileDlg) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() CMyFileDlg::CMyFileDlg (BOOL bOpenFileDialog, // TRUE for FileOpen, FALSE for FileSaveAs LPCSTR lpszDefExt, LPCSTR lpszFileName, DWORD dwFlags, LPCSTR lpszFilter, CWnd* pParentWnd) : CFileDialog (bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd) { //{{AFX_DATA_INIT(CMyFileDlg) //}}AFX_DATA_INIT } BOOL CMyFileDlg::OnInitDialog() { CenterWindow(); //Let's hide these windows so the user cannot tab to them. Note that in //the private template (in cddemo.dlg) the coordinates for these guys are //*outside* the coordinates of the dlg window itself. Without the following //ShowWindow()'s you would not see them, but could still tab to them. GetDlgItem(stc2)->ShowWindow(SW_HIDE); GetDlgItem(stc3)->ShowWindow(SW_HIDE); GetDlgItem(edt1)->ShowWindow(SW_HIDE); GetDlgItem(lst1)->ShowWindow(SW_HIDE); GetDlgItem(cmb1)->ShowWindow(SW_HIDE); //We must put something in this field, even though it is hidden. This is //because if this field is empty, or has something like "*.txt" in it, //and the user hits OK, the dlg will NOT close. We'll jam something in //there (like "Junk") so when the user hits OK, the dlg terminates. //Note that we'll deal with the "Junk" during return processing (see below) SetDlgItemText(edt1, "Junk"); //Now set the focus to the directories listbox. Due to some painting //problems, we *must* also process the first WM_PAINT that comes through //and set the current selection at that point. Setting the selection //here will NOT work. See comment below in the on paint handler. GetDlgItem(lst2)->SetFocus(); m_bDlgJustCameUp=TRUE; CFileDialog::OnInitDialog(); return(FALSE); } void CMyFileDlg::OnPaint() { CPaintDC dc(this); // device context for painting //This code makes the directory listbox "highlight" an entry when it first //comes up. W/O this code, the focus is on the directory listbox, but no //focus rectangle is drawn and no entries are selected. Ho hum. if (m_bDlgJustCameUp) { m_bDlgJustCameUp=FALSE; SendDlgItemMessage(lst2, LB_SETCURSEL, 0, 0L); } // Do not call CFileDialog::OnPaint() for painting messages } CString PickDirectory(CWnd* pParentWnd) { if (!pParentWnd) pParentWnd = AfxGetApp()->m_pMainWnd; DWORD flags = OFN_SHOWHELP | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ENABLETEMPLATE | OFN_NOCHANGEDIR; if (DirScanner::CanUseLongNames()) flags |= 0x00200000L; // special flag to display long dir names CMyFileDlg cfdlg(FALSE, NULL, NULL, flags, NULL, pParentWnd); cfdlg.m_ofn.hInstance = AfxGetInstanceHandle(); cfdlg.m_ofn.lpTemplateName = MAKEINTRESOURCE(FILEOPENORD); #ifdef _WIN32 cfdlg.m_ofn.Flags &= ~ OFN_EXPLORER; #endif if (cfdlg.DoModal() != IDOK) return ""; cfdlg.m_ofn.lpstrFile[cfdlg.m_ofn.nFileOffset-1] = 0; //Nuke the "Junk" return cfdlg.m_ofn.lpstrFile; } /////////////////////////////////////////////////////////////////////////////
30.237762
88
0.657956
KOLANICH
96ce91a331a98a1c93cd3e79e232ef016e48705e
2,932
cpp
C++
adbase/Head/Binary.cpp
weiboad/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
62
2017-02-15T11:36:46.000Z
2022-03-14T09:11:10.000Z
adbase/Head/Binary.cpp
AraHaan/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
5
2017-02-21T05:32:14.000Z
2017-05-21T13:15:07.000Z
adbase/Head/Binary.cpp
AraHaan/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
22
2017-02-16T02:11:25.000Z
2020-02-12T18:12:44.000Z
#include <adbase/Head.hpp> #include <adbase/Utility.hpp> #include <adbase/Logging.hpp> namespace adbase { namespace head { // {{{ Binary::Binary() Binary::Binary(Interface* interface) : _interface(interface) { } // }}} // {{{ Binary::~Binary() Binary::~Binary() { } // }}} // {{{ void Binary::processData() void Binary::processData(const TcpConnectionPtr& conn, evbuffer* evbuf) { while (1) { ssize_t len = evbuffer_get_length(evbuf); ssize_t headerLen = static_cast<ssize_t>(sizeof(ProtocolBinaryHeader)); if (len < headerLen) { // 协议包数据不完整 LOG_TRACE << "Read request header len less " << headerLen << " real len:" << len; break; } ProtocolBinaryHeader header; if (evbuffer_copyout(evbuf, &header, headerLen) != headerLen) { // 读取错误,关闭连接 LOG_ERROR << "Read buffer error, conn:" << conn->getCookie(); conn->shutdown(); return; } ssize_t bodyLen = static_cast<ssize_t>(networkToHost32(header.head.bodylen)); if (bodyLen > len - headerLen) { // 协议包数据不完整 LOG_TRACE << "Read request body len less " << bodyLen << " real len:" << len; break; } if (evbuffer_drain(evbuf, headerLen) == -1) { // 读取错误,关闭连接 LOG_ERROR << "Read header error, conn:" << conn->getCookie(); conn->shutdown(); break; } std::unique_ptr<char[]> buffer(new char[bodyLen]); if (evbuffer_copyout(evbuf, buffer.get(), bodyLen) != bodyLen) { // 读取错误,关闭连接 LOG_TRACE << "Read request real len:" << len; LOG_ERROR << "Read body buffer error, conn:" << conn->getCookie(); conn->shutdown(); break; } if (evbuffer_drain(evbuf, bodyLen) == -1) { // 读取错误,关闭连接 LOG_ERROR << "Read body buffer error, conn:" << conn->getCookie(); conn->shutdown(); break; } LOG_DEBUG << "Body len: " << bodyLen; LOG_DEBUG << "Header len: " << headerLen; ReadHandler readHandler = _interface->getReadHandler(); if (readHandler) { ProtocolBinaryResponseStatus rval = PROTOCOL_BINARY_RESPONSE_SUCCESS; Buffer responseBuffer; ProtocolBinaryDataType responseDataType; rval = readHandler(static_cast<ProtocolBinaryDataType>(header.head.datatype), buffer.get(), bodyLen, &responseDataType, &responseBuffer); ProtocolBinaryHeader response; response.head.magic = PROTOCOL_BINARY_RES; response.head.datatype = responseDataType; response.head.masterversion = header.head.masterversion; response.head.secondversion = header.head.secondversion; response.head.opaque = header.head.opaque; response.head.status = hostToNetwork16(rval); response.head.appkey = header.head.appkey; uint32_t textlen = static_cast<uint32_t>(responseBuffer.readableBytes()); response.head.bodylen = hostToNetwork32(textlen); conn->send(response.bytes, sizeof(response.bytes)); if (textlen != 0) { conn->send(responseBuffer.peek(), textlen); responseBuffer.retrieveAll(); } } LOG_DEBUG << "Proccess complete."; } } // }}} } }
28.192308
140
0.675989
weiboad
96d19af0424f7f70651e129c71a3676e4a3c106d
1,853
cpp
C++
src/chrono/assets/ChTriangleMeshShape.cpp
felixvd/chrono
4c437fc1fc8964310d53206dda45e8ba9c734fa2
[ "BSD-3-Clause" ]
1
2020-11-05T12:55:52.000Z
2020-11-05T12:55:52.000Z
src/chrono/assets/ChTriangleMeshShape.cpp
felixvd/chrono
4c437fc1fc8964310d53206dda45e8ba9c734fa2
[ "BSD-3-Clause" ]
null
null
null
src/chrono/assets/ChTriangleMeshShape.cpp
felixvd/chrono
4c437fc1fc8964310d53206dda45e8ba9c734fa2
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alesandro Tasora, Radu Serban // ============================================================================= #include "chrono/assets/ChTriangleMeshShape.h" namespace chrono { // Register into the object factory, to enable run-time dynamic creation and persistence CH_FACTORY_REGISTER(ChTriangleMeshShape) ChTriangleMeshShape::ChTriangleMeshShape() : name(""), scale(ChVector<>(1)), wireframe(false), backface_cull(false) { trimesh = chrono_types::make_shared<geometry::ChTriangleMeshConnected>(); }; void ChTriangleMeshShape::ArchiveOUT(ChArchiveOut& marchive) { // version number marchive.VersionWrite<ChTriangleMeshShape>(); // serialize parent class ChVisualization::ArchiveOUT(marchive); // serialize all member data: marchive << CHNVP(trimesh); marchive << CHNVP(wireframe); marchive << CHNVP(backface_cull); marchive << CHNVP(name); marchive << CHNVP(scale); } void ChTriangleMeshShape::ArchiveIN(ChArchiveIn& marchive) { // version number int version = marchive.VersionRead<ChTriangleMeshShape>(); // deserialize parent class ChVisualization::ArchiveIN(marchive); // stream in all member data: marchive >> CHNVP(trimesh); marchive >> CHNVP(wireframe); marchive >> CHNVP(backface_cull); marchive >> CHNVP(name); marchive >> CHNVP(scale); } } // end namespace chrono
34.962264
117
0.628171
felixvd
96d3c5189455bae96243c9cfdbd58238cbdb2b53
4,997
cpp
C++
app/perfclient.cpp
HarryKBD/raperf
0a2d3876dd5923722bffa3dce5f7ee1e83253b00
[ "BSD-3-Clause" ]
null
null
null
app/perfclient.cpp
HarryKBD/raperf
0a2d3876dd5923722bffa3dce5f7ee1e83253b00
[ "BSD-3-Clause" ]
null
null
null
app/perfclient.cpp
HarryKBD/raperf
0a2d3876dd5923722bffa3dce5f7ee1e83253b00
[ "BSD-3-Clause" ]
null
null
null
#include <unistd.h> #include <cstdlib> #include <cstring> #include <netdb.h> #include <iostream> #include <udt.h> #include "cc.h" #include "test_util.h" #include <sys/time.h> using namespace std; //#define SEND_BUF_SIZE 50000 #define SEND_BUF_SIZE 8000 int64_t SEND_FILE_SIZE = 1024*1024*1024; //5GB void * monitor(void *); char send_buf[SEND_BUF_SIZE] = {0x03, }; int main(int argc, char * argv[]) { if ((4 != argc) || (0 == atoi(argv[2]))) { cout << "usage: appclient server_ip server_port filename" << endl; return 0; } // Automatically start up and clean up UDT module. UDTUpDown _udt_; struct addrinfo hints, *local, *peer; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; //hints.ai_socktype = SOCK_DGRAM; if (0 != getaddrinfo(NULL, "9000", &hints, &local)) { cout << "incorrect network address.\n" << endl; return 0; } UDTSOCKET client = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol); // UDT Options //UDT::setsockopt(client, 0, UDT_CC, new CCCFactory<CUDPBlast>, sizeof(CCCFactory<CUDPBlast>)); //UDT::setsockopt(client, 0, UDT_MSS, new int(9000), sizeof(int)); UDT::setsockopt(client, 0, UDT_SNDBUF, new int(10000000), sizeof(int)); //UDT::setsockopt(client, 0, UDP_SNDBUF, new int(10000000), sizeof(int)); //UDT::setsockopt(client, 0, UDT_MAXBW, new int64_t(12500000), sizeof(int)); // Windows UDP issue // For better performance, modify HKLM\System\CurrentControlSet\Services\Afd\Parameters\FastSendDatagramThreshold // for rendezvous connection, enable the code below /* UDT::setsockopt(client, 0, UDT_RENDEZVOUS, new bool(true), sizeof(bool)); if (UDT::ERROR == UDT::bind(client, local->ai_addr, local->ai_addrlen)) { cout << "bind: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } */ freeaddrinfo(local); if (0 != getaddrinfo(argv[1], argv[2], &hints, &peer)) { cout << "incorrect server/peer address. " << argv[1] << ":" << argv[2] << endl; return 0; } // connect to the server, implict bind if (UDT::ERROR == UDT::connect(client, peer->ai_addr, peer->ai_addrlen)) { cout << "connect: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } freeaddrinfo(peer); // send name information of the requested file int len = strlen(argv[3]); if (UDT::ERROR == UDT::send(client, (char*)&len, sizeof(int), 0)) { cout << "send: " << UDT::getlasterror().getErrorMessage() << endl; return -1; } if (UDT::ERROR == UDT::send(client, argv[3], len, 0)) { cout << "send: " << UDT::getlasterror().getErrorMessage() << endl; return -1; } int64_t send_size = SEND_FILE_SIZE*20; // send file size information if (UDT::ERROR == UDT::send(client, (char*)&send_size, sizeof(int64_t), 0)) { cout << "send: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } cout << "sending file: " << argv[3] << " size: " << send_size << endl; pthread_create(new pthread_t, NULL, monitor, &client); int64_t total_sent = 0; int ss; struct timeval tv_start, tv_end; gettimeofday(&tv_start, NULL); while(total_sent < send_size) { int ssize = 0; int frag = 0; while (ssize < SEND_BUF_SIZE) { if (UDT::ERROR == (ss = UDT::send(client, send_buf + ssize, SEND_BUF_SIZE - ssize, 0))) { cout << "send:" << UDT::getlasterror().getErrorMessage() << endl; break; } //cout << ss << endl; frag++; ssize += ss; } //cout << "frag " << frag << endl; if (ssize < SEND_BUF_SIZE) break; total_sent += ssize; } gettimeofday(&tv_end, NULL); time_t taken = tv_end.tv_sec - tv_start.tv_sec; cout << "sending file done. saved file name : " << argv[3] << " total sent: " << total_sent << "( " << total_sent/(double)taken/1000000.0 << " MB/s) expected: " << SEND_FILE_SIZE << endl; UDT::close(client); return 0; } void * monitor(void * s) { UDTSOCKET u = *(UDTSOCKET *)s; UDT::TRACEINFO perf; cout << "SendRate(Mb/s)\tRTT(ms)\tCWnd\tPktSndPeriod(us)\tRecvACK\tRecvNAK" << endl; while (true) { sleep(1); if (UDT::ERROR == UDT::perfmon(u, &perf)) { cout << "perfmon: " << UDT::getlasterror().getErrorMessage() << endl; break; } cout << perf.mbpsSendRate << "\t\t" << perf.msRTT << "\t" << perf.pktCongestionWindow << "\t" << perf.usPktSndPeriod << "\t\t\t" << perf.pktRecvACK << "\t" << perf.pktRecvNAK << endl; } return NULL; }
27.010811
191
0.571743
HarryKBD
96d59dc54e46397f6fafa6dcadce847d7560dbc0
2,665
cpp
C++
fon9/FileRevRead_UT.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
21
2019-01-29T14:41:46.000Z
2022-03-11T00:22:56.000Z
fon9/FileRevRead_UT.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
null
null
null
fon9/FileRevRead_UT.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
9
2019-01-27T14:19:33.000Z
2022-03-11T06:18:24.000Z
/// \file fon9/FileRevRead_UT.cpp /// \author fonwinz@gmail.com #include "fon9/FileRevRead.hpp" #include "fon9/RevPrint.hpp" //--------------------------------------------------------------------------// bool OpenFile(const char* info, fon9::File& fd, const char* fname, fon9::FileMode fm) { printf("%s %s\n", info, fname); auto res = fd.Open(fname, fm); if (res) return true; puts(fon9::RevPrintTo<std::string>("Open error: ", res).c_str()); return false; } //--------------------------------------------------------------------------// int main(int argc, char** args) { #if defined(_MSC_VER) && defined(_DEBUG) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); //_CrtSetBreakAlloc(176); #endif if(argc < 3) { printf("Reverse InputFile lines to OutputFile.\n" "Usage: InputFile OutputFile\n"); return 3; } fon9::File fdin; if (!OpenFile("Input file: ", fdin, args[1], fon9::FileMode::Read)) return 3; fon9_MSC_WARN_DISABLE_NO_PUSH(4820 4355); struct RevReader : public fon9::RevReadSearcher<fon9::FileRevReadBuffer<1024*4>, fon9::FileRevSearch> { fon9_NON_COPY_NON_MOVE(RevReader); // using base = fon9::RevReadSearcher<fon9::FileRevReadBuffer<1024 * 4>, fon9::FileRevSearch>; RevReader() = default; unsigned long LineCount_{0}; fon9::File FdOut_; virtual fon9::LoopControl OnFileBlock(size_t rdsz) override { if (this->RevSearchBlock(this->GetBlockPos(), '\n', rdsz) == fon9::LoopControl::Break) return fon9::LoopControl::Break; if (this->GetBlockPos() == 0 && this->LastRemainSize_ > 0) this->AppendLine(this->BlockBuffer_, this->LastRemainSize_); return fon9::LoopControl::Continue; } virtual fon9::LoopControl OnFoundChar(char* pbeg, char* pend) override { ++pbeg; // *pbeg=='\n'; => 應放在行尾. if (pbeg == pend && this->LineCount_ == 0) ++this->LineCount_; else this->AppendLine(pbeg, static_cast<size_t>(pend - pbeg)); return fon9::LoopControl::Continue; } void AppendLine(char* pbeg, size_t lnsz) { this->FdOut_.Append(pbeg, lnsz); this->FdOut_.Append("\n", 1); ++this->LineCount_; } }; RevReader reader; if (!OpenFile("Output file: ", reader.FdOut_, args[2], fon9::FileMode::Append | fon9::FileMode::CreatePath | fon9::FileMode::Trunc)) return 3; auto res = reader.Start(fdin); printf("Line count: %lu\n", reader.LineCount_); if (!res) puts(fon9::RevPrintTo<std::string>("Error: ", res).c_str()); return 0; }
37.535211
135
0.586867
fonwin
96d5be95ce9e37030eb3c39a32acfe308746443f
2,668
cpp
C++
src/renderer.cpp
kacejot/ray-tracer-se
8543826db12bda41e99bf37a6beef7a4acd79cff
[ "MIT" ]
null
null
null
src/renderer.cpp
kacejot/ray-tracer-se
8543826db12bda41e99bf37a6beef7a4acd79cff
[ "MIT" ]
null
null
null
src/renderer.cpp
kacejot/ray-tracer-se
8543826db12bda41e99bf37a6beef7a4acd79cff
[ "MIT" ]
null
null
null
#include <algorithm> #include <future> #include <thread> #include "renderer.h" #include "utils.h" #include "vec3.h" #include "ray.h" std::vector<vec3*> divide_vector_to_chunks(std::vector<vec3>& vector, size_t chunk_size) { std::vector<vec3*> result{}; size_t current_chunk = 0; for (; current_chunk < vector.size(); current_chunk += chunk_size) { result.push_back(vector.data() + current_chunk); } return result; } void write_fraction_color(std::ostream &out, vec3 vec) { vec *= 255.0f; // Write the translated [0,255] value of each color component. out << static_cast<int>(std::clamp(vec.r, 0.0, 255.0)) << ' ' << static_cast<int>(std::clamp(vec.g, 0.0, 255.0)) << ' ' << static_cast<int>(std::clamp(vec.b, 0.0, 255.0)) << '\n'; } void p3_renderer::render(){ auto threads = static_cast<size_t>(std::thread::hardware_concurrency()); auto rows_per_thread = image_height / threads + 1; out << "P3\n" << image_width << " " << image_height << "\n255\n"; std::vector<std::future<std::vector<vec3>>> futures; for (size_t i = 0; i < threads; ++i) { auto end_heigth = std::clamp((threads - i) * rows_per_thread, size_t{0}, image_height); auto start_height = std::clamp(end_heigth - rows_per_thread, size_t{0}, image_height); futures.push_back(std::async(std::launch::async, &p3_renderer::render_parallel, this, start_height, end_heigth)); } for (auto&& future : futures) { future.wait(); } for (auto&& future : futures) { for (auto&& color : future.get()) { write_fraction_color(out, color); } } std::cout << "\nDone.\n"; } std::vector<vec3> p3_renderer::render_parallel(size_t start_height, size_t end_heigth) { std::vector<vec3> result; for (int j = static_cast<int>(end_heigth) - 1; j >= static_cast<int>(start_height); --j) { // some dirty code here if (start_height == 0) { std::cout << std::endl << "Row's to render: " << j << ' ' << std::flush; } for (int i = 0; i < static_cast<int>(image_width); ++i) { vec3 color{}; for (int s = 0; s < samples_per_pixel; ++s) { auto u = (i + random_double()) / image_width; auto v = (j + random_double()) / image_height; ray r = cam.cast_ray(u, v); color += ray_color(r, world, max_depth); } color /= static_cast<double>(samples_per_pixel); gamma_correct(color, 0.5); result.push_back(color); } } return result; }
31.388235
121
0.574588
kacejot
96d71c62e8c5eb74a046150c71861d615e84d54c
3,137
hpp
C++
Source/Common/Delegate.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/Common/Delegate.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/Common/Delegate.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
#pragma once #include "Precompiled.hpp" // // Delegate // Implementation based on: http://molecularmusings.wordpress.com/2011/09/19/generic-type-safe-delegates-and-events-in-c/ // Be careful not to invoke a delagate to a method of an instance that no longer exists. // // Binding and invoking a function: // bool Function(const char* c, int i) { /*...*/ } // Delegate<bool(const char*, int)> delegate; // delegate.Bind<&Function>(); // delegate.Invoke("hello", 5); // // Binding and invoking a functor: // auto Object = [](const char* c, int i) { /*...*/ }; // Delegate<bool(const char*, int)> delegate; // delegate.Bind(&Object); // delegate.Invoke("hello", 5); // // Binding and invoking a method: // bool Class::Function(const char* c, int i) { /*...*/ } // Class instance; // Delegate<bool(const char*, int)> delegate; // delegate.Bind<Class, &Class::Function>(&instance); // delegate.Invoke("hello", 5); // template<typename Type> class Delegate; template<typename ReturnType, typename... Arguments> class Delegate<ReturnType(Arguments...)> { private: // Type declarations. typedef void* InstancePtr; typedef ReturnType (*FunctionPtr)(InstancePtr, Arguments...); // Compile time invocation stubs. template<ReturnType (*Function)(Arguments...)> static ReturnType FunctionStub(InstancePtr instance, Arguments... arguments) { return (Function)(std::forward<Arguments>(arguments)...); } template<class InstanceType> static ReturnType FunctorStub(InstancePtr instance, Arguments... arguments) { return (*static_cast<InstanceType*>(instance))(std::forward<Arguments>(arguments)...); } template<class InstanceType, ReturnType (InstanceType::*Function)(Arguments...)> static ReturnType MethodStub(InstancePtr instance, Arguments... arguments) { return (static_cast<InstanceType*>(instance)->*Function)(std::forward<Arguments>(arguments)...); } public: Delegate() : m_instance(nullptr), m_function(nullptr) { } void Cleanup() { m_instance = nullptr; m_function = nullptr; } // Binds a static function. template<ReturnType (*Function)(Arguments...)> void Bind() { m_instance = nullptr; m_function = &FunctionStub<Function>; } // Binds a functor object. template<class InstanceType> void Bind(InstanceType* instance) { m_instance = instance; m_function = &FunctorStub<InstanceType>; } // Binds an instance method. template<class InstanceType, ReturnType (InstanceType::*Function)(Arguments...)> void Bind(InstanceType* instance) { m_instance = instance; m_function = &MethodStub<InstanceType, Function>; } // Invokes the delegate. ReturnType Invoke(Arguments... arguments) { if(m_function == nullptr) return ReturnType(); return m_function(m_instance, std::forward<Arguments>(arguments)...); } private: InstancePtr m_instance; FunctionPtr m_function; };
28.518182
122
0.64329
gunstarpl
96d85fed9c2efee4fbd53b3c8b07ef38e8e6abb6
3,365
cpp
C++
Demo App/Demos/BlackHoleDemo.cpp
aderussell/ARPhysics
2669db7cd9e31918d8573e5a6bde654b443b0961
[ "MIT" ]
null
null
null
Demo App/Demos/BlackHoleDemo.cpp
aderussell/ARPhysics
2669db7cd9e31918d8573e5a6bde654b443b0961
[ "MIT" ]
null
null
null
Demo App/Demos/BlackHoleDemo.cpp
aderussell/ARPhysics
2669db7cd9e31918d8573e5a6bde654b443b0961
[ "MIT" ]
null
null
null
// // BlackHoleDemo.cpp // Drawing // // Created by Adrian Russell on 16/12/2013. // Copyright (c) 2013 Adrian Russell. All rights reserved. // #include "BlackHoleDemo.h" //#include "TestingIndexing.h" #define NUMBER_OF_PARTICLES 90 #define COLLISION_LEVEL 1 // TODO: add ball bounce demo, roll down hill then fall off and bounce on floor BlackHoleDemo::BlackHoleDemo() { BruteForceIndexing *bruteForce = new BruteForceIndexing(); World *world = new World(320, 240, bruteForce); this->world = world; bruteForce->release(); _particles = new Array(); _blackHoles = new Array(); //_blackHole = new CircleBody(6.0, Vector2(150.0, 130.0), 5.0); //world->addBody(_blackHole); GravityToPointForceGenerator *gravityGenerator = new GravityToPointForceGenerator(30.0, Vector2(150.0, 130.0)); world->addForceGenerator(gravityGenerator); _blackHoles->addObject(gravityGenerator); gravityGenerator->release(); //gravityGenerator = new GravityToPointForceGenerator(10.0, Vector2(140.0, 130.0)); //world->addForceGenerator(gravityGenerator); //_blackHoles->addObject(gravityGenerator); for (unsigned int i = 0; i < NUMBER_OF_PARTICLES; i++) { CircleBody *particle = new CircleBody(1, Vector2(10.0, 2.0 + 3 * i), 1.0); particle->setGroups(COLLISION_LEVEL); world->addBody(particle); _particles->addObject(particle); particle->release(); } } BlackHoleDemo::~BlackHoleDemo() { this->world->release(); _particles->release(); _blackHoles->release(); } void BlackHoleDemo::mouseEvent(int button, int state, int x, int y) { if (button == 0 && state == 0) { GravityToPointForceGenerator *gravityGenerator = (GravityToPointForceGenerator *)_blackHoles->objectAtIndex(0); gravityGenerator->setPoint(Vector2(x, y)); } else if (button == 2 && state == 0) { GravityToPointForceGenerator *gravityGenerator = new GravityToPointForceGenerator(30.0, Vector2(x, y)); world->addForceGenerator(gravityGenerator); _blackHoles->addObject(gravityGenerator); gravityGenerator->release(); } // create a new circle // or delete a circle } void BlackHoleDemo::mouseMoved(int x, int y) { } void BlackHoleDemo::keyPressed(unsigned char key, int x, int y) { if (key == '1') { for (unsigned int i = 0; i < _particles->count(); i++) { CircleBody *particle = (CircleBody *)_particles->objectAtIndex(i); if (particle->collisionGroups() == COLLISION_LEVEL) { particle->setGroups(0); } else { particle->setGroups(COLLISION_LEVEL); } } } } void BlackHoleDemo::draw() { for (unsigned int i = 0; i < _blackHoles->count(); i++) { GravityToPointForceGenerator *gravityGenerator = (GravityToPointForceGenerator *)_blackHoles->objectAtIndex(i); drawCircle(gravityGenerator->position(), gravityGenerator->force() / 5.0, 0.0, kBlackColor, kNoColor); } for (unsigned int i = 0; i < _particles->count(); i++) { CircleBody *particle = (CircleBody *)_particles->objectAtIndex(i); drawCircle(particle->position(), particle->radius(), particle->rotation(), kWhiteColor, kWhiteColor); } }
29.008621
119
0.645468
aderussell
96dbe09ef61a26a313e8873b00859c7873396fe1
55,122
cpp
C++
qws/src/gui/QProgressDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
42
2015-02-16T19:29:16.000Z
2021-07-25T11:09:03.000Z
qws/src/gui/QProgressDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
1
2017-11-23T12:49:25.000Z
2017-11-23T12:49:25.000Z
qws/src/gui/QProgressDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
5
2015-10-15T21:25:30.000Z
2017-11-22T13:18:24.000Z
///////////////////////////////////////////////////////////////////////////// // // File : QProgressDialog.cpp // Copyright : (c) David Harley 2010 // Project : qtHaskell // Version : 1.1.4 // Modified : 2010-09-02 17:02:01 // // Warning : this file is machine generated - do not modify. // ///////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <wchar.h> #include <qtc_wrp_core.h> #include <qtc_wrp_gui.h> #include <qtc_subclass.h> #include <gui/QProgressDialog_DhClass.h> extern "C" { QTCEXPORT(void*,qtc_QProgressDialog)() { DhQProgressDialog*tr = new DhQProgressDialog(); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog1)(void* x1) { QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); DhQProgressDialog*tr = new DhQProgressDialog((QWidget*)tx1); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog2)(void* x1, long x2) { QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); DhQProgressDialog*tr = new DhQProgressDialog((QWidget*)tx1, (Qt::WindowFlags)x2); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog3)(wchar_t* x1, wchar_t* x2, int x3, int x4) { DhQProgressDialog*tr = new DhQProgressDialog(from_method(x1), from_method(x2), (int)x3, (int)x4); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog4)(wchar_t* x1, wchar_t* x2, int x3, int x4, void* x5) { QObject*tx5 = *((QPointer<QObject>*)x5); if ((tx5!=NULL)&&((QObject *)tx5)->property(QTC_PROP).isValid()) tx5 = ((QObject*)(((qtc_DynamicQObject*)tx5)->parent())); DhQProgressDialog*tr = new DhQProgressDialog(from_method(x1), from_method(x2), (int)x3, (int)x4, (QWidget*)tx5); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog5)(wchar_t* x1, wchar_t* x2, int x3, int x4, void* x5, long x6) { QObject*tx5 = *((QPointer<QObject>*)x5); if ((tx5!=NULL)&&((QObject *)tx5)->property(QTC_PROP).isValid()) tx5 = ((QObject*)(((qtc_DynamicQObject*)tx5)->parent())); DhQProgressDialog*tr = new DhQProgressDialog(from_method(x1), from_method(x2), (int)x3, (int)x4, (QWidget*)tx5, (Qt::WindowFlags)x6); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(int,qtc_QProgressDialog_autoClose)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->autoClose(); } QTCEXPORT(int,qtc_QProgressDialog_autoReset)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->autoReset(); } QTCEXPORT(void,qtc_QProgressDialog_cancel)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->cancel(); } QTCEXPORT(void,qtc_QProgressDialog_changeEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhchangeEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_changeEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhchangeEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_closeEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhcloseEvent((QCloseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_closeEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhcloseEvent((QCloseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_forceShow)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhforceShow(); } QTCEXPORT(void*,qtc_QProgressDialog_labelText)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QString * tq = new QString(((QProgressDialog*)tx0)->labelText()); return (void*)(tq); } QTCEXPORT(int,qtc_QProgressDialog_maximum)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->maximum(); } QTCEXPORT(int,qtc_QProgressDialog_minimum)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->minimum(); } QTCEXPORT(int,qtc_QProgressDialog_minimumDuration)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->minimumDuration(); } QTCEXPORT(void,qtc_QProgressDialog_reset)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->reset(); } QTCEXPORT(void,qtc_QProgressDialog_resizeEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhresizeEvent((QResizeEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_resizeEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhresizeEvent((QResizeEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_setAutoClose)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setAutoClose((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_setAutoReset)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setAutoReset((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_setBar)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QProgressDialog*)tx0)->setBar((QProgressBar*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_setCancelButton)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QProgressDialog*)tx0)->setCancelButton((QPushButton*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_setCancelButtonText)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setCancelButtonText(from_method(x1)); } QTCEXPORT(void,qtc_QProgressDialog_setLabel)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QProgressDialog*)tx0)->setLabel((QLabel*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_setLabelText)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setLabelText(from_method(x1)); } QTCEXPORT(void,qtc_QProgressDialog_setMaximum)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setMaximum((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_setMinimum)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setMinimum((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_setMinimumDuration)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setMinimumDuration((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_setRange)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setRange((int)x1, (int)x2); } QTCEXPORT(void,qtc_QProgressDialog_setValue)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setValue((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_showEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhshowEvent((QShowEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_showEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhshowEvent((QShowEvent*)x1); } QTCEXPORT(void*,qtc_QProgressDialog_sizeHint)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize * tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = new QSize(((DhQProgressDialog*)tx0)->DhsizeHint()); } else { tc = new QSize(((QProgressDialog*)tx0)->sizeHint()); } return (void*)(tc); } QTCEXPORT(void*,qtc_QProgressDialog_sizeHint_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize * tc = new QSize(((DhQProgressDialog*)tx0)->DvhsizeHint()); return (void*)(tc); } QTCEXPORT(void,qtc_QProgressDialog_sizeHint_qth)(void* x0, int* _ret_w, int* _ret_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = ((DhQProgressDialog*)tx0)->DhsizeHint(); } else { tc = ((QProgressDialog*)tx0)->sizeHint(); } *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(void,qtc_QProgressDialog_sizeHint_qth_h)(void* x0, int* _ret_w, int* _ret_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tc = ((DhQProgressDialog*)tx0)->DvhsizeHint(); *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(int,qtc_QProgressDialog_value)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->value(); } QTCEXPORT(int,qtc_QProgressDialog_wasCanceled)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->wasCanceled(); } QTCEXPORT(void,qtc_QProgressDialog_finalizer)(void* x0) { delete ((QPointer<QProgressDialog>*)x0); } QTCEXPORT(void*,qtc_QProgressDialog_getFinalizer)() { return (void*)(&qtc_QProgressDialog_finalizer); } QTCEXPORT(void,qtc_QProgressDialog_delete)(void* x0) { QObject* tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&(((QObject*)tx0)->property(QTC_PROP).isValid())) { qtc_DynamicQObject* ttx0 = (qtc_DynamicQObject*)tx0; tx0 = ((QObject*)(tx0->parent())); ttx0->freeDynamicSlots(); delete ttx0; } if ((tx0!=NULL)&&(((QObject*)tx0)->property(QTC_DHPROP).isValid())) { ((DhQProgressDialog*)tx0)->freeDynamicHandlers(); delete((DhQProgressDialog*)tx0); } else { delete((QProgressDialog*)tx0); } } QTCEXPORT(void,qtc_QProgressDialog_deleteLater)(void* x0) { QObject* tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&(((QObject*)tx0)->property(QTC_PROP).isValid())) { qtc_DynamicQObject* ttx0 = (qtc_DynamicQObject*)tx0; tx0 = ((QObject*)(tx0->parent())); ttx0->freeDynamicSlots(); ttx0->deleteLater(); } if ((tx0!=NULL)&&(((QObject*)tx0)->property(QTC_DHPROP).isValid())) { ((DhQProgressDialog*)tx0)->freeDynamicHandlers(); ((DhQProgressDialog*)tx0)->deleteLater(); } else { ((QProgressDialog*)tx0)->deleteLater(); } } QTCEXPORT(void,qtc_QProgressDialog_accept)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { ((DhQProgressDialog*)tx0)->Dhaccept(); } else { ((QDialog*)tx0)->accept(); } } QTCEXPORT(void,qtc_QProgressDialog_accept_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dvhaccept(); } QTCEXPORT(void,qtc_QProgressDialog_adjustPosition)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((DhQProgressDialog*)tx0)->DhadjustPosition((QWidget*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_contextMenuEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhcontextMenuEvent((QContextMenuEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_contextMenuEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhcontextMenuEvent((QContextMenuEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_done)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { ((DhQProgressDialog*)tx0)->Dhdone((int)x1); } else { ((QDialog*)tx0)->done((int)x1); } } QTCEXPORT(void,qtc_QProgressDialog_done_h)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dvhdone((int)x1); } QTCEXPORT(int,qtc_QProgressDialog_event)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->Dhevent((QEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_event_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->Dvhevent((QEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_eventFilter)(void* x0, void* x1, void* x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); return (int)((DhQProgressDialog*)tx0)->DheventFilter((QObject*)tx1, (QEvent*)x2); } QTCEXPORT(void,qtc_QProgressDialog_keyPressEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhkeyPressEvent((QKeyEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_keyPressEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhkeyPressEvent((QKeyEvent*)x1); } QTCEXPORT(void*,qtc_QProgressDialog_minimumSizeHint)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize * tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = new QSize(((DhQProgressDialog*)tx0)->DhminimumSizeHint()); } else { tc = new QSize(((QDialog*)tx0)->minimumSizeHint()); } return (void*)(tc); } QTCEXPORT(void*,qtc_QProgressDialog_minimumSizeHint_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize * tc = new QSize(((DhQProgressDialog*)tx0)->DvhminimumSizeHint()); return (void*)(tc); } QTCEXPORT(void,qtc_QProgressDialog_minimumSizeHint_qth)(void* x0, int* _ret_w, int* _ret_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = ((DhQProgressDialog*)tx0)->DhminimumSizeHint(); } else { tc = ((QDialog*)tx0)->minimumSizeHint(); } *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(void,qtc_QProgressDialog_minimumSizeHint_qth_h)(void* x0, int* _ret_w, int* _ret_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tc = ((DhQProgressDialog*)tx0)->DvhminimumSizeHint(); *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(void,qtc_QProgressDialog_reject)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { ((DhQProgressDialog*)tx0)->Dhreject(); } else { ((QDialog*)tx0)->reject(); } } QTCEXPORT(void,qtc_QProgressDialog_reject_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dvhreject(); } QTCEXPORT(void,qtc_QProgressDialog_setVisible)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { ((DhQProgressDialog*)tx0)->DhsetVisible((bool)x1); } else { ((QDialog*)tx0)->setVisible((bool)x1); } } QTCEXPORT(void,qtc_QProgressDialog_setVisible_h)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhsetVisible((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_actionEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhactionEvent((QActionEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_actionEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhactionEvent((QActionEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_addAction)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QProgressDialog*)tx0)->addAction((QAction*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_create)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhcreate(); } QTCEXPORT(void,qtc_QProgressDialog_create1)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhcreate((WId)x1); } QTCEXPORT(void,qtc_QProgressDialog_create2)(void* x0, void* x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhcreate((WId)x1, (bool)x2); } QTCEXPORT(void,qtc_QProgressDialog_create3)(void* x0, void* x1, int x2, int x3) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhcreate((WId)x1, (bool)x2, (bool)x3); } QTCEXPORT(void,qtc_QProgressDialog_destroy)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhdestroy(); } QTCEXPORT(void,qtc_QProgressDialog_destroy1)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhdestroy((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_destroy2)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhdestroy((bool)x1, (bool)x2); } QTCEXPORT(int,qtc_QProgressDialog_devType)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { return (int)((DhQProgressDialog*)tx0)->DhdevType(); } else { return (int)((QWidget*)tx0)->devType(); } } QTCEXPORT(int,qtc_QProgressDialog_devType_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DvhdevType(); } QTCEXPORT(void,qtc_QProgressDialog_dragEnterEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhdragEnterEvent((QDragEnterEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragEnterEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhdragEnterEvent((QDragEnterEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragLeaveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhdragLeaveEvent((QDragLeaveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragLeaveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhdragLeaveEvent((QDragLeaveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragMoveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhdragMoveEvent((QDragMoveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragMoveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhdragMoveEvent((QDragMoveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dropEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhdropEvent((QDropEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dropEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhdropEvent((QDropEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_enabledChange)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhenabledChange((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_enterEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhenterEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_enterEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhenterEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_focusInEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhfocusInEvent((QFocusEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_focusInEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhfocusInEvent((QFocusEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_focusNextChild)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DhfocusNextChild(); } QTCEXPORT(int,qtc_QProgressDialog_focusNextPrevChild)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DhfocusNextPrevChild((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_focusOutEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhfocusOutEvent((QFocusEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_focusOutEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhfocusOutEvent((QFocusEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_focusPreviousChild)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DhfocusPreviousChild(); } QTCEXPORT(void,qtc_QProgressDialog_fontChange)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhfontChange((const QFont&)(*(QFont*)x1)); } QTCEXPORT(int,qtc_QProgressDialog_heightForWidth)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { return (int)((DhQProgressDialog*)tx0)->DhheightForWidth((int)x1); } else { return (int)((QWidget*)tx0)->heightForWidth((int)x1); } } QTCEXPORT(int,qtc_QProgressDialog_heightForWidth_h)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DvhheightForWidth((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_hideEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhhideEvent((QHideEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_hideEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhhideEvent((QHideEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_inputMethodEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhinputMethodEvent((QInputMethodEvent*)x1); } QTCEXPORT(void*,qtc_QProgressDialog_inputMethodQuery)(void* x0, long x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QVariant * tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = new QVariant(((DhQProgressDialog*)tx0)->DhinputMethodQuery((Qt::InputMethodQuery)x1)); } else { tc = new QVariant(((QWidget*)tx0)->inputMethodQuery((Qt::InputMethodQuery)x1)); } return (void*)(tc); } QTCEXPORT(void*,qtc_QProgressDialog_inputMethodQuery_h)(void* x0, long x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QVariant * tc = new QVariant(((DhQProgressDialog*)tx0)->DvhinputMethodQuery((int)x1)); return (void*)(tc); } QTCEXPORT(void,qtc_QProgressDialog_keyReleaseEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhkeyReleaseEvent((QKeyEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_keyReleaseEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhkeyReleaseEvent((QKeyEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_languageChange)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhlanguageChange(); } QTCEXPORT(void,qtc_QProgressDialog_leaveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhleaveEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_leaveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhleaveEvent((QEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_metric)(void* x0, long x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->Dhmetric((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseDoubleClickEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmouseDoubleClickEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseDoubleClickEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmouseDoubleClickEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseMoveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmouseMoveEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseMoveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmouseMoveEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mousePressEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmousePressEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mousePressEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmousePressEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseReleaseEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmouseReleaseEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseReleaseEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmouseReleaseEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_move)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->move((const QPoint&)(*(QPoint*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_move_qth)(void* x0, int x1_x, int x1_y) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QPoint tx1(x1_x, x1_y); ((QProgressDialog*)tx0)->move(tx1); } QTCEXPORT(void,qtc_QProgressDialog_move1)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->move((int)x1, (int)x2); } QTCEXPORT(void,qtc_QProgressDialog_moveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmoveEvent((QMoveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_moveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmoveEvent((QMoveEvent*)x1); } QTCEXPORT(void*,qtc_QProgressDialog_paintEngine)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { return (void*)((DhQProgressDialog*)tx0)->DhpaintEngine(); } else { return (void*)((QWidget*)tx0)->paintEngine(); } } QTCEXPORT(void*,qtc_QProgressDialog_paintEngine_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (void*)((DhQProgressDialog*)tx0)->DvhpaintEngine(); } QTCEXPORT(void,qtc_QProgressDialog_paintEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhpaintEvent((QPaintEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_paintEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhpaintEvent((QPaintEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_paletteChange)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhpaletteChange((const QPalette&)(*(QPalette*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_repaint)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->repaint(); } QTCEXPORT(void,qtc_QProgressDialog_repaint1)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->repaint((const QRegion&)(*(QRegion*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_repaint2)(void* x0, int x1, int x2, int x3, int x4) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->repaint((int)x1, (int)x2, (int)x3, (int)x4); } QTCEXPORT(void,qtc_QProgressDialog_resetInputContext)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhresetInputContext(); } QTCEXPORT(void,qtc_QProgressDialog_resize)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->resize((const QSize&)(*(QSize*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_resize_qth)(void* x0, int x1_w, int x1_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tx1(x1_w, x1_h); ((QProgressDialog*)tx0)->resize(tx1); } QTCEXPORT(void,qtc_QProgressDialog_resize1)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->resize((int)x1, (int)x2); } QTCEXPORT(void,qtc_QProgressDialog_setGeometry)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setGeometry((const QRect&)(*(QRect*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_setGeometry_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QRect tx1(x1_x, x1_y, x1_w, x1_h); ((QProgressDialog*)tx0)->setGeometry(tx1); } QTCEXPORT(void,qtc_QProgressDialog_setGeometry1)(void* x0, int x1, int x2, int x3, int x4) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setGeometry((int)x1, (int)x2, (int)x3, (int)x4); } QTCEXPORT(void,qtc_QProgressDialog_setMouseTracking)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setMouseTracking((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_tabletEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhtabletEvent((QTabletEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_tabletEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhtabletEvent((QTabletEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_updateMicroFocus)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhupdateMicroFocus(); } QTCEXPORT(void,qtc_QProgressDialog_wheelEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhwheelEvent((QWheelEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_wheelEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhwheelEvent((QWheelEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_windowActivationChange)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhwindowActivationChange((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_childEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhchildEvent((QChildEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_connectNotify)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QString tx1(from_method(x1)); QByteArray txa1(tx1.toAscii()); ((DhQProgressDialog*)tx0)->DhconnectNotify(txa1.data()); } QTCEXPORT(void,qtc_QProgressDialog_customEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhcustomEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_disconnectNotify)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QString tx1(from_method(x1)); QByteArray txa1(tx1.toAscii()); ((DhQProgressDialog*)tx0)->DhdisconnectNotify(txa1.data()); } QTCEXPORT(int,qtc_QProgressDialog_receivers)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QString tx1(from_method(x1)); QByteArray txa1(tx1.toAscii()); return (int)((DhQProgressDialog*)tx0)->Dhreceivers(txa1.data()); } QTCEXPORT(void*,qtc_QProgressDialog_sender)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); QObject * tc = (QObject*)(((DhQProgressDialog*)tx0)->Dhsender()); QPointer<QObject> * ttc = new QPointer<QObject>(tc); return (void*)(ttc); } QTCEXPORT(void,qtc_QProgressDialog_timerEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhtimerEvent((QTimerEvent*)x1); } QTCEXPORT(void, qtc_QProgressDialog_userMethod)(void * evt_obj, int evt_typ) { QObject * te = *((QPointer<QObject>*)evt_obj); if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); ((DhQProgressDialog*)te)->userDefined(evt_typ); } QTCEXPORT(void*, qtc_QProgressDialog_userMethodVariant)(void * evt_obj, int evt_typ, void * xv) { QObject * te = *((QPointer<QObject>*)evt_obj); if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); return (void*)(((DhQProgressDialog*)te)->userDefinedVariant(evt_typ, (QVariant*)xv)); } QTCEXPORT(int, qtc_QProgressDialog_setUserMethod)(void * evt_obj, int evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { QObject * te = *((QPointer<QObject>*)evt_obj); QObject * tr = te; if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); QPointer<QObject> * ttr = new QPointer<QObject>(tr); return (int) ((DhQProgressDialog*)te)->setDynamicQHandlerud(0, (void*)ttr, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setUserMethodVariant)(void * evt_obj, int evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { QObject * te = *((QPointer<QObject>*)evt_obj); QObject * tr = te; if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); QPointer<QObject> * ttr = new QPointer<QObject>(tr); return (int) ((DhQProgressDialog*)te)->setDynamicQHandlerud(1, (void*)ttr, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_unSetUserMethod)(void * evt_obj, int udm_typ, int evt_typ) { QObject * te = *((QPointer<QObject>*)evt_obj); if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); return (int) ((DhQProgressDialog*)te)->unSetDynamicQHandlerud(udm_typ, evt_typ); } QTCEXPORT(int, qtc_QProgressDialog_setHandler)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { QObject * te = *((QPointer<QObject>*)evt_obj); QObject * tr = te; if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); QString tq_evt(from_method((wchar_t *)evt_typ)); QByteArray tqba_evt(tq_evt.toAscii()); QPointer<QObject> * ttr = new QPointer<QObject>(tr); return (int) ((DhQProgressDialog*)te)->setDynamicQHandler((void*)ttr, tqba_evt.data(), rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_unSetHandler)(void * evt_obj, wchar_t * evt_typ) { QObject * te = *((QPointer<QObject>*)evt_obj); if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); QString tq_evt(from_method((wchar_t *)evt_typ)); QByteArray tqba_evt(tq_evt.toAscii()); return (int) ((DhQProgressDialog*)te)->unSetDynamicQHandler(tqba_evt.data()); } QTCEXPORT(int, qtc_QProgressDialog_setHandler1)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler2)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler3)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler4)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler5)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler6)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler7)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler8)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler9)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler10)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } }
48.267951
135
0.67971
keera-studios
96de99ba8f18f5e0ec9b5bf4e4908ac862177a55
1,022
cpp
C++
src/statistics/OFLatencyStats.cpp
csieber/hvbench
07e6520110ce7e2359baee1a4223c29b1e68efa6
[ "MIT" ]
2
2017-04-19T12:12:03.000Z
2017-07-22T13:32:51.000Z
src/statistics/OFLatencyStats.cpp
csieber/hvbench
07e6520110ce7e2359baee1a4223c29b1e68efa6
[ "MIT" ]
null
null
null
src/statistics/OFLatencyStats.cpp
csieber/hvbench
07e6520110ce7e2359baee1a4223c29b1e68efa6
[ "MIT" ]
null
null
null
#include "OFLatencyStats.h" #include "StatsVisitor.h" OFLatencyStats::OFLatencyStats() { this->reset(); } OFLatencyStats::~OFLatencyStats() { } void OFLatencyStats::reset() { boost::mutex::scoped_lock lock(this->mutex_); for (auto e : OFPT::latency_types) stats_latency_[e] = boost_acc_mean_min_max(); } void OFLatencyStats::sent(int32_t xid, OFPT::OFPT_T type, time_point_t tp) { reply_waiting_list.try_enqueue(std::make_tuple(xid, type, tp)); } void OFLatencyStats::received(int32_t xid, OFPT::OFPT_T type, time_point_t tp) { while (true) { sent_msg_t last; if (!reply_waiting_list.try_dequeue(last)){ break; } if (std::get<0>(last) != xid) continue; const auto& latency = tp - std::get<2>(last); { boost::mutex::scoped_lock lock(this->mutex_); stats_latency_[std::get<1>(last)](boost::chrono::duration_cast<boost::chrono::microseconds>(latency).count()); } break; } } void OFLatencyStats::accept(std::shared_ptr<StatsVisitor> v) { v->visit(shared_from_this()); }
18.925926
113
0.69863
csieber
96e1e49ae8dba4e59abad2e9f02a32ebe7b6fd59
777
cpp
C++
bucket_BE/firebird40/patches/patch-src_remote_inet.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
17
2017-04-22T21:53:52.000Z
2021-01-21T16:57:55.000Z
bucket_BE/firebird40/patches/patch-src_remote_inet.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
186
2017-09-12T20:46:52.000Z
2021-11-27T18:15:14.000Z
bucket_BE/firebird40/patches/patch-src_remote_inet.cpp
jrmarino/ravensource
91d599fd1f2af55270258d15e72c62774f36033e
[ "FTL" ]
74
2017-09-06T14:48:01.000Z
2021-08-28T02:48:27.000Z
--- src/remote/inet.cpp.orig 2021-05-29 15:05:06 UTC +++ src/remote/inet.cpp @@ -959,7 +959,7 @@ rem_port* INET_connect(const TEXT* name, gai_hints.ai_family = ((host.hasData() || !ipv6) ? AF_UNSPEC : AF_INET6); gai_hints.ai_socktype = SOCK_STREAM; -#if !defined(WIN_NT) && !defined(__clang__) +#if !defined(WIN_NT) && !defined(FREEBSD) && !defined(DRAGONFLY) gai_hints.ai_protocol = SOL_TCP; #else gai_hints.ai_protocol = IPPROTO_TCP; @@ -1167,6 +1167,12 @@ static rem_port* listener_socket(rem_por inet_ports->registerPort(port); + char *parent_pid; + if (parent_pid = getenv("FB_SIGNAL_PROCESS")) + { + kill(atoi(parent_pid), SIGUSR1); + } + if (flag & SRVR_multi_client) { // Prevent the generation of dummy keepalive packets on the connect port.
31.08
76
0.697555
jrmarino
96e2a92c38fe1e45583205eb8ea321c47b2bd92d
8,143
cpp
C++
OpenEXR_CTL/exrdpx/exrToDpx.cpp
DerouineauNicolas/CTL
3512a25c2d03a55287dbce493408c6943a44df6a
[ "AMPAS" ]
163
2015-01-13T20:43:21.000Z
2022-03-17T12:51:30.000Z
OpenEXR_CTL/exrdpx/exrToDpx.cpp
dracwyrm/CTL
57b48a273438159698a72d1e94a580b49337d234
[ "AMPAS" ]
21
2015-02-11T21:30:56.000Z
2020-10-29T08:14:45.000Z
OpenEXR_CTL/exrdpx/exrToDpx.cpp
dracwyrm/CTL
57b48a273438159698a72d1e94a580b49337d234
[ "AMPAS" ]
40
2015-01-30T05:40:13.000Z
2022-03-17T12:51:37.000Z
/////////////////////////////////////////////////////////////////////////// // Copyright (c) 2013 Academy of Motion Picture Arts and Sciences // ("A.M.P.A.S."). Portions contributed by others as indicated. // All rights reserved. // // A worldwide, royalty-free, non-exclusive right to copy, modify, create // derivatives, and use, in source and binary forms, is hereby granted, // subject to acceptance of this license. Performance of any of the // aforementioned acts indicates acceptance to be bound by the following // terms and conditions: // // * Copies of source code, in whole or in part, must retain the // above copyright notice, this list of conditions and the // Disclaimer of Warranty. // // * Use in binary form must retain the above copyright notice, // this list of conditions and the Disclaimer of Warranty in the // documentation and/or other materials provided with the distribution. // // * Nothing in this license shall be deemed to grant any rights to // trademarks, copyrights, patents, trade secrets or any other // intellectual property of A.M.P.A.S. or any contributors, except // as expressly stated herein. // // * Neither the name "A.M.P.A.S." nor the name of any other // contributors to this software may be used to endorse or promote // products derivative of or based on this software without express // prior written permission of A.M.P.A.S. or the contributors, as // appropriate. // // This license shall be construed pursuant to the laws of the State of // California, and any disputes related thereto shall be subject to the // jurisdiction of the courts therein. // // Disclaimer of Warranty: THIS SOFTWARE IS PROVIDED BY A.M.P.A.S. AND // CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO // EVENT SHALL A.M.P.A.S., OR ANY CONTRIBUTORS OR DISTRIBUTORS, BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, RESITUTIONARY, // 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. // // WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE ACADEMY // SPECIFICALLY DISCLAIMS ANY REPRESENTATIONS OR WARRANTIES WHATSOEVER // RELATED TO PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS IN THE ACADEMY // COLOR ENCODING SYSTEM, OR APPLICATIONS THEREOF, HELD BY PARTIES OTHER // THAN A.M.P.A.S., WHETHER DISCLOSED OR UNDISCLOSED. /////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------- // // Read the R, G and B channels from an OpenEXR file, and // store them in a 10-bit log-encoded printing-density DPX file. // //---------------------------------------------------------------------------- #include <exrToDpx.h> #include <dpxHeader.h> #include <applyCtl.h> #include <ImfHeader.h> #include <ImfRgbaFile.h> #include <ImfArray.h> #include <ImathFun.h> #include <Iex.h> #include <string.h> #include <fstream> using namespace std; using namespace Imf; using namespace Imath; using namespace Iex; namespace { void writeHeader (ofstream &out, const char fileName[], unsigned int width, unsigned int height) { union { struct { FileInformation fileInfo; ImageInformation imageInfo; ImageOrientation orientation; MotionPictureFilmHeader mph; TelevisionHeader tvh; }; unsigned char padding[8192]; } header; memset (header.padding, 0xff, sizeof (header)); setU32 (0x53445058, header.fileInfo.magicNumber, BO_BIG); setU32 (sizeof (header), header.fileInfo.offsetToImageData, BO_BIG); strcpy (header.fileInfo.versionNumber, "V2.0"); setU32 (sizeof (header) + 4 * width * height, header.fileInfo.fileSize, BO_BIG); header.fileInfo.fileName[0] = 0; header.fileInfo.creationTime[0] = 0; header.fileInfo.creator[0] = 0; header.fileInfo.projectName[0] = 0; header.fileInfo.copyright[0] = 0; setU16 (0, header.imageInfo.imageOrientation, BO_BIG); setU16 (1, header.imageInfo.numberOfElements, BO_BIG); setU32 (width, header.imageInfo.pixelsPerLine, BO_BIG); setU32 (height, header.imageInfo.linesPerImageElement, BO_BIG); setU32 (0, header.imageInfo.imageElements[0].dataSign, BO_BIG); // unsigned header.imageInfo.imageElements[0].descriptor = 50; // RGB header.imageInfo.imageElements[0].transferCharacteristic = 3; // log header.imageInfo.imageElements[0].colorimetricSpecification = 1; // density header.imageInfo.imageElements[0].bitSize = 10; setU16 (1, header.imageInfo.imageElements[0].packing, BO_BIG); // filled setU16 (0, header.imageInfo.imageElements[0].encoding, BO_BIG); // none setU32 (sizeof (header), header.imageInfo.imageElements[0].offsetToData, BO_BIG); // none for (int i = 0; i < 7; ++i) header.imageInfo.imageElements[i].description[0] = 0; header.orientation.sourceImageFileName[0] = 0; header.orientation.creationTime[0] = 0; header.orientation.inputDev[0] = 0; header.orientation.inputSerial[0] = 0; header.mph.filmManufacturerId[0] = 0; header.mph.filmType[0] = 0; header.mph.offset[0] = 0; header.mph.prefix[0] = 0; header.mph.count[0] = 0; header.mph.format[0] = 0; if (!out.write ((const char *)&header, sizeof (header))) THROW_ERRNO ("Cannot write header to file " << fileName << " (%T)."); } void writePixels (ofstream &out, const char fileName[], unsigned int width, unsigned int height, const Array2D<Rgba> &pixels) { Array<unsigned char> rawLine (width * 4); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { const Rgba &pixel = pixels[y][x]; unsigned int r = (unsigned int) (clamp (float (pixel.r), 0.0f, 1023.0f) + 0.5f); unsigned int g = (unsigned int) (clamp (float (pixel.g), 0.0f, 1023.0f) + 0.5f); unsigned int b = (unsigned int) (clamp (float (pixel.b), 0.0f, 1023.0f) + 0.5f); unsigned int word = (r << 22) | (g << 12) | (b << 2); setU32 (word, rawLine + 4 * x, BO_BIG); } if (!out.write ((const char *)&rawLine[0], width * 4)) THROW_ERRNO ("Cannot write scan line " << y << " " "to DPX file " << fileName << " (%T)."); } } } // namespace void exrToDpx (const char exrFileName[], const char dpxFileName[], std::vector<std::string> transformNames, bool verbose) { // // Read the OpenEXR file // if (verbose) cout << "reading file " << exrFileName << endl; RgbaInputFile in (exrFileName); Box2i dw = in.dataWindow(); unsigned int width = (unsigned int) (dw.max.x - dw.min.x + 1); unsigned int height = (unsigned int) (dw.max.y - dw.min.y + 1); Array2D<Rgba> pixels (height, width); in.setFrameBuffer (&pixels[0][0] - dw.min.x - dw.min.y * width, 1, width); in.readPixels (dw.min.y, dw.max.y); // // Apply the CTL transforms // if (verbose) { cout << "applyging CTL transforms:"; for (int i = 0; i < transformNames.size(); ++i) cout << " " << transformNames[i]; cout << endl; } applyCtlExrToDpx (transformNames, in.header(), pixels, width, height, pixels); // // Write the DPX file // if (verbose) cout << "writing file " << dpxFileName << endl; ofstream out (dpxFileName, ios_base::binary); if (!out) { THROW_ERRNO ("Cannot open file " << dpxFileName << " " "for writing (%T)."); } writeHeader (out, dpxFileName, width, height); writePixels (out, dpxFileName, width, height, pixels); if (verbose) cout << "done" << endl; }
31.684825
79
0.643743
DerouineauNicolas
96e926f31d8751147f189670acb00d398d85fe05
3,743
inl
C++
libgpos/include/gpos/common/CSyncList.inl
bhuvnesh2703/gpos
bce4ed761ef35e2852691a86b8099d820844a3e8
[ "ECL-2.0", "Apache-2.0" ]
28
2016-01-29T08:27:42.000Z
2021-03-11T01:42:33.000Z
libgpos/include/gpos/common/CSyncList.inl
bhuvnesh2703/gpos
bce4ed761ef35e2852691a86b8099d820844a3e8
[ "ECL-2.0", "Apache-2.0" ]
22
2016-02-01T16:31:50.000Z
2017-07-13T13:25:53.000Z
libgpos/include/gpos/common/CSyncList.inl
bhuvnesh2703/gpos
bce4ed761ef35e2852691a86b8099d820844a3e8
[ "ECL-2.0", "Apache-2.0" ]
23
2016-01-28T03:19:24.000Z
2021-05-28T07:32:51.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CSyncList.inl // // @doc: // Implementation of template-based synchronized stack class with // minimum synchronization overhead; it provides a minimal set of // thread-safe operations through atomic primitives (lock-free); // // It requires that the elements are only inserted once, as their address // is used for identification; if elements are concurrently deleted, // iteration through the list is not thread safe; // // In order to be useful for system programming the class must be // allocation-less, i.e. manage elements without additional allocation, // to work in exception or OOM situations; //--------------------------------------------------------------------------- #include "gpos/sync/atomic.h" namespace gpos { //--------------------------------------------------------------------------- // @function: // CSyncList<T>::~CSyncList // // @doc: // Dtor; // //--------------------------------------------------------------------------- template<class T> CSyncList<T>::~CSyncList() {} //--------------------------------------------------------------------------- // @function: // CSyncList<T>::Push // // @doc: // Insert element at the head of the list; // //--------------------------------------------------------------------------- template<class T> void CSyncList<T>::Push ( T *pt ) { GPOS_ASSERT(NULL != pt); GPOS_ASSERT(m_list.PtFirst() != pt); ULONG ulAttempts = 0; SLink &linkElem = m_list.Link(pt); #ifdef GPOS_DEBUG void *pvHeadNext = linkElem.m_pvNext; #endif // GPOS_DEBUG GPOS_ASSERT(NULL == linkElem.m_pvNext); // keep spinning until passed element becomes the head while (true) { T *ptHead = m_list.PtFirst(); GPOS_ASSERT(pt != ptHead && "Element is already inserted"); GPOS_ASSERT(pvHeadNext == linkElem.m_pvNext && "Element is concurrently accessed"); // set current head as next element linkElem.m_pvNext = ptHead; #ifdef GPOS_DEBUG pvHeadNext = linkElem.m_pvNext; #endif // GPOS_DEBUG // attempt to set element as head if (FCompareSwap<T>((volatile T**) &m_list.m_ptHead, ptHead, pt)) { break; } CheckBackOff(ulAttempts); } } //--------------------------------------------------------------------------- // @function: // CSyncList<T>::Pop // // @doc: // Remove element from the head of the list; // //--------------------------------------------------------------------------- template<class T> T * CSyncList<T>::Pop() { ULONG ulAttempts = 0; T *ptHeadOld = NULL; // keep spinning until the head is removed while (true) { // get current head ptHeadOld = m_list.PtFirst(); if (NULL == ptHeadOld) { break; } // second element becomes the new head SLink &linkElem = m_list.Link(ptHeadOld); T *ptHeadNew = static_cast<T*>(linkElem.m_pvNext); // attempt to set new head if (FCompareSwap<T>((volatile T**) &m_list.m_ptHead, ptHeadOld, ptHeadNew)) { // reset link linkElem.m_pvNext = NULL; break; } CheckBackOff(ulAttempts); } return ptHeadOld; } //--------------------------------------------------------------------------- // @function: // CSyncList<T>::CheckBackOff // // @doc: // Back-off after too many attempts; // //--------------------------------------------------------------------------- template<class T> void CSyncList<T>::CheckBackOff ( ULONG &ulAttempts ) const { if (++ulAttempts == GPOS_SPIN_ATTEMPTS) { // back-off clib::USleep(GPOS_SPIN_BACKOFF); ulAttempts = 0; GPOS_CHECK_ABORT; } } } // EOF
22.413174
86
0.517499
bhuvnesh2703
96f150ddfa567903a3e58731a42fbd60268c4681
9,603
cpp
C++
test/ImageJPEG4Test.cpp
jbruchanov/NativeImage
faa739faa0e89d47c572ee0bf3faa806f9601afc
[ "Apache-2.0" ]
null
null
null
test/ImageJPEG4Test.cpp
jbruchanov/NativeImage
faa739faa0e89d47c572ee0bf3faa806f9601afc
[ "Apache-2.0" ]
null
null
null
test/ImageJPEG4Test.cpp
jbruchanov/NativeImage
faa739faa0e89d47c572ee0bf3faa806f9601afc
[ "Apache-2.0" ]
null
null
null
// // Created by scurab on 04/04/17. // #include <googletest/include/gtest/gtest.h> #include "../src/Errors.h" #include "../src/ImageProcessor.hpp" #include "../src/Image.hpp" #include "../src/JpegImageProcessor.h" #include "Assets.h" typedef bytep_t *string1; typedef string1 string2; static JpegImageProcessor prc; TEST(ImageJPEG4, LoadingImage) { string f = JPEG_1X1_PX; Image image(4); IOResult ior = image.loadImage(&prc, f.c_str()); ASSERT_EQ(NO_ERR, ior.result); } TEST(ImageJPEG4, MetaDataImageSize) { string f = JPEG_3X1_PX; Image image(4); image.loadImage(&prc, f.c_str()); ImageMetaData data = image.getMetaData(); ASSERT_EQ(1, data.imageHeight); ASSERT_EQ(3, data.imageWidth); } TEST(ImageJPEG4, LoadInvalidImage) { string f = JPEG_INVALID; Image image(4); IOResult ior = image.loadImage(&prc, f.c_str()); ASSERT_NE(NO_ERR, ior.result); string err = image.getAndClearLastError(); string err2 = image.getAndClearLastError(); ASSERT_EQ(0, err2.length()); } TEST(ImageJPEG4, LoadRawData_1PX) { string f = JPEG_1X1_PX; Image image(4); image.loadImage(&prc, f.c_str()); ImageData raw = image.getImageData(); bytep_t *ptr = raw.data; ASSERT_EQ(1, raw.metaData.pixelCount()); bytep_t exp[] = {0xFF, 0x00, 0x00, 0xFE}; for (int i = 0; i < 4; i++) { bytep_t pc = ptr[i]; ASSERT_EQ(exp[i], pc); } } TEST(ImageJPEG4, LoadRawData_3PX) { string f = JPEG_3X1_PX; Image image(4); image.loadImage(&prc, f.c_str()); ImageData raw = image.getImageData(); bytep_t *ptr = raw.data; ASSERT_EQ(3, raw.metaData.pixelCount()); bytep_t exp[] = {0xFF, 0x25, 0x27, 0xA4, 0xFF, 0xD8, 0xDA, 0xFF, 0xFF, 0x00, 0x00, 0x00}; for (int i = 0; i < 12; i++) { bytep_t pc = ptr[i]; ASSERT_EQ(exp[i], pc); } } TEST(ImageJPEG4, FreesMemoryOnNewLoad) { string f = JPEG_3X1_PX; Image image(4); image.loadImage(&prc, f.c_str()); f = JPEG_INVALID; image.loadImage(&prc, f.c_str()); ImageData data = image.getImageData(); ASSERT_EQ(nullptr, data.data); ASSERT_EQ(0, data.metaData.pixelCount()); } TEST(ImageJPEG4, Rotate180) { Image image(4); string2 imageData = new bytep_t[48] {11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 61, 62, 63, 64, 71, 72, 73, 74, 81, 82, 83, 84, 91, 92, 93, 94, 101, 102, 103, 104, 111, 112, 113, 114, 121, 122, 123, 124}; bytep_t imageDataExpected[] = {121, 122, 123, 124, 111, 112, 113, 114, 101, 102, 103, 104, 91, 92, 93, 94, 81, 82, 83, 84, 71, 72, 73, 74, 61, 62, 63, 64, 51, 52, 53, 54, 41, 42, 43, 44, 31, 32, 33, 34, 21, 22, 23, 24, 11, 12, 13, 14}; image.setRawData(imageData, 4, 3, 4); image.rotate180(); for (int i = 0, n = sizeof(imageData) / sizeof(bytep_t); i < n; i++) { ASSERT_EQ(imageDataExpected[i], imageData[i]); } } TEST(ImageJPEG4, Rotate90_1Slow) { Image image(4); bytep_t *imageData = new bytep_t[16]{11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44}; bytep_t imageDataExpected[] = {11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44}; image.setRawData(imageData, 4, 1, 4); image.rotate90(false); for (int i = 0, n = sizeof(imageData) / sizeof(bytep_t); i < n; i++) { ASSERT_EQ(imageDataExpected[i], imageData[i]); } } TEST(ImageJPEG4, Rotate90_1Fast) { Image image(4); bytep_t *imageData = new bytep_t[16]{11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44}; bytep_t imageDataExpected[] = {11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44}; image.setRawData(imageData, 4, 1, 4); image.rotate90(true); imageData = image.getImageData().data; for (int i = 0, n = sizeof(imageData) / sizeof(bytep_t); i < n; i++) { ASSERT_EQ(imageDataExpected[i], imageData[i]); } } TEST(ImageJPEG4, Rotate90_2Slow) { Image image(4); bytep_t *imageData = new bytep_t[24]{11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 61, 62, 63, 64}; bytep_t imageDataExpected[] = {41, 42, 43, 44, 11, 12, 13, 14, 51, 52, 53, 54, 21, 22, 23, 24, 61, 62, 63, 64, 31, 32, 33, 34}; image.setRawData(imageData, 3, 2, 4); image.rotate90(false); for (int i = 0, n = sizeof(imageData) / sizeof(bytep_t); i < n; i++) { ASSERT_EQ(imageDataExpected[i], imageData[i]); } } TEST(ImageJPEG4, Rotate90_2Fast) { Image image(4); bytep_t *imageData = new bytep_t[24]{11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 61, 62, 63, 64}; bytep_t imageDataExpected[] = {41, 42, 43, 44, 11, 12, 13, 14, 51, 52, 53, 54, 21, 22, 23, 24, 61, 62, 63, 64, 31, 32, 33, 34}; image.setRawData(imageData, 3, 2, 4); image.rotate90(true); imageData = image.getImageData().data; for (int i = 0, n = sizeof(imageData) / sizeof(bytep_t); i < n; i++) { ASSERT_EQ(imageDataExpected[i], imageData[i]); } } TEST(ImageJPEG4, Rotate90_3Slow) { Image image(4); bytep_t *imageData = new bytep_t[48] {11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 61, 62, 63, 64, 71, 72, 73, 74, 81, 82, 83, 84, 91, 92, 93, 94, 101, 102, 103, 104, 111, 112, 113, 114, 121, 122, 123, 124}; bytep_t imageDataExpected[] = {91, 92, 93, 94, 51, 52, 53, 54, 11, 12, 13, 14, 101, 102, 103, 104, 61, 62, 63, 64, 21, 22, 23, 24, 111, 112, 113, 114, 71, 72, 73, 74, 31, 32, 33, 34, 121, 122, 123, 124, 81, 82, 83, 84, 41, 42, 43, 44}; image.setRawData(imageData, 4, 3, 4); image.rotate90(false); for (int i = 0, n = sizeof(imageData) / sizeof(bytep_t); i < n; i++) { ASSERT_EQ(imageDataExpected[i], imageData[i]); } } TEST(ImageJPEG4, Rotate90_3Fast) { Image image(4); bytep_t *imageData = new bytep_t[48] {11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 61, 62, 63, 64, 71, 72, 73, 74, 81, 82, 83, 84, 91, 92, 93, 94, 101, 102, 103, 104, 111, 112, 113, 114, 121, 122, 123, 124}; bytep_t imageDataExpected[] = {91, 92, 93, 94, 51, 52, 53, 54, 11, 12, 13, 14, 101, 102, 103, 104, 61, 62, 63, 64, 21, 22, 23, 24, 111, 112, 113, 114, 71, 72, 73, 74, 31, 32, 33, 34, 121, 122, 123, 124, 81, 82, 83, 84, 41, 42, 43, 44}; image.setRawData(imageData, 4, 3, 4); image.rotate90(true); imageData = image.getImageData().data; for (int i = 0, n = sizeof(imageData) / sizeof(bytep_t); i < n; i++) { ASSERT_EQ(imageDataExpected[i], imageData[i]); } } TEST(ImageJPEG4, SaveImage) { Image image(4); string f = JPEG_SAMPLE_ASSET; image.loadImage(&prc, f.c_str()); const char *path = "pokus4.jpg"; image.saveImage(&prc, path); Image image2(4); image2.loadImage(&prc, f.c_str()); const ImageMetaData metaData = image.getMetaData(); ASSERT_EQ(image.getMetaData().imageWidth, metaData.imageWidth); ASSERT_EQ(image.getMetaData().imageHeight, metaData.imageHeight); remove(path); } TEST(ImageJPEG4, SetPixelsCrop) { Image image(4); bytep_t *imageData = new bytep_t[48] {0x11, 0x12, 0x13, 0x14, 0x21, 0x22, 0x23, 0x24, 0x31, 0x32, 0x33, 0x34, 0x41, 0x42, 0x43, 0x44, 0x51, 0x52, 0x53, 0x54, 0x61, 0x62, 0x63, 0x64, 0x71, 0x72, 0x73, 0x74, 0x81, 0x82, 0x83, 0x84, 0x91, 0x92, 0x93, 0x94, 0xA1, 0xA2, 0xA3, 0xA4, 0xB1, 0xB2, 0xB3, 0xB4, 0xC1, 0xC2, 0xC3, 0xC4}; image.setRawData(imageData, 4, 3, 4); int target[4]; //NO BITMAP_COLOR, because it's simple set! memset(target, 0, sizeof(target)); image.setPixels((int *) &target, 0, 0, 1, 1); ASSERT_EQ((0x11121314), target[0]); memset(target, 0, sizeof(target)); image.setPixels((int *) &target, 1, 1, 1, 1); ASSERT_EQ((0x61626364), target[0]); memset(target, 0, sizeof(target)); image.setPixels((int *) &target, 2, 2, 1, 1); ASSERT_EQ((0xB1B2B3B4), target[0]); memset(target, 0, sizeof(target)); image.setPixels((int *) &target, 2, 2, 2, 1); ASSERT_EQ((0xB1B2B3B4), target[0]); ASSERT_EQ((0xC1C2C3C4), target[1]); memset(target, 0, sizeof(target)); image.setPixels((int *) &target, 3, 0, 1, 3); ASSERT_EQ((0x41424344), target[0]); ASSERT_EQ((0x81828384), target[1]); ASSERT_EQ((0xC1C2C3C4), target[2]); memset(target, 0, sizeof(target)); image.setPixels((int *) &target, 0, 2, 4, 1); ASSERT_EQ((0x91929394), target[0]); ASSERT_EQ((0xA1A2A3A4), target[1]); ASSERT_EQ((0xB1B2B3B4), target[2]); ASSERT_EQ((0xC1C2C3C4), target[3]); }
35.83209
110
0.542851
jbruchanov
96f156ccdb9c67f31f042ece100ebb43991f3b5d
3,534
cpp
C++
eval/src/tests/instruction/sparse_dot_product_function/sparse_dot_product_function_test.cpp
gsmcwhirter/vespa
afe876252b56b5a30735865047d7392958835f6a
[ "Apache-2.0" ]
null
null
null
eval/src/tests/instruction/sparse_dot_product_function/sparse_dot_product_function_test.cpp
gsmcwhirter/vespa
afe876252b56b5a30735865047d7392958835f6a
[ "Apache-2.0" ]
null
null
null
eval/src/tests/instruction/sparse_dot_product_function/sparse_dot_product_function_test.cpp
gsmcwhirter/vespa
afe876252b56b5a30735865047d7392958835f6a
[ "Apache-2.0" ]
1
2020-12-08T19:56:35.000Z
2020-12-08T19:56:35.000Z
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/eval/eval/fast_value.h> #include <vespa/eval/eval/simple_value.h> #include <vespa/eval/instruction/sparse_dot_product_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/vespalib/gtest/gtest.h> using namespace vespalib::eval; using namespace vespalib::eval::test; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); const ValueBuilderFactory &test_factory = SimpleValueBuilderFactory::get(); //----------------------------------------------------------------------------- EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add_variants("v1_x", GenSpec(3.0).map("x", 32, 1)) .add_variants("v2_x", GenSpec(7.0).map("x", 16, 2)) .add("v3_y", GenSpec().map("y", 10, 1)) .add("v4_xd", GenSpec().idx("x", 10)) .add("m1_xy", GenSpec(3.0).map("x", 32, 1).map("y", 16, 2)) .add("m2_xy", GenSpec(7.0).map("x", 16, 2).map("y", 32, 1)) .add("m3_xym", GenSpec().map("x", 8, 1).idx("y", 5)); } EvalFixture::ParamRepo param_repo = make_params(); void assert_optimized(const vespalib::string &expr) { EvalFixture fast_fixture(prod_factory, expr, param_repo, true); EvalFixture test_fixture(test_factory, expr, param_repo, true); EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EXPECT_EQ(fast_fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQ(test_fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQ(slow_fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQ(fast_fixture.find_all<SparseDotProductFunction>().size(), 1u); EXPECT_EQ(test_fixture.find_all<SparseDotProductFunction>().size(), 1u); EXPECT_EQ(slow_fixture.find_all<SparseDotProductFunction>().size(), 0u); } void assert_not_optimized(const vespalib::string &expr) { EvalFixture fast_fixture(prod_factory, expr, param_repo, true); EXPECT_EQ(fast_fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQ(fast_fixture.find_all<SparseDotProductFunction>().size(), 0u); } //----------------------------------------------------------------------------- TEST(SparseDotProduct, expression_can_be_optimized) { assert_optimized("reduce(v1_x*v2_x,sum,x)"); assert_optimized("reduce(v2_x*v1_x,sum)"); assert_optimized("reduce(v1_x_f*v2_x_f,sum)"); } TEST(SparseDotProduct, multi_dimensional_expression_can_be_optimized) { assert_optimized("reduce(m1_xy*m2_xy,sum,x,y)"); assert_optimized("reduce(m1_xy*m2_xy,sum)"); } TEST(SparseDotProduct, embedded_dot_product_is_not_optimized) { assert_not_optimized("reduce(m1_xy*v1_x,sum,x)"); assert_not_optimized("reduce(v1_x*m1_xy,sum,x)"); } TEST(SparseDotProduct, similar_expressions_are_not_optimized) { assert_not_optimized("reduce(m1_xy*v1_x,sum)"); assert_not_optimized("reduce(v1_x*v3_y,sum)"); assert_not_optimized("reduce(v2_x*v1_x,max)"); assert_not_optimized("reduce(v2_x+v1_x,sum)"); assert_not_optimized("reduce(v4_xd*v4_xd,sum)"); assert_not_optimized("reduce(m3_xym*m3_xym,sum)"); } TEST(SparseDotProduct, mixed_cell_types_are_not_optimized) { assert_not_optimized("reduce(v1_x*v2_x_f,sum)"); assert_not_optimized("reduce(v1_x_f*v2_x,sum)"); } //----------------------------------------------------------------------------- GTEST_MAIN_RUN_ALL_TESTS()
40.159091
112
0.681098
gsmcwhirter
96f36a536c81d16403e31c0e0626bcdedbbc42f9
70,589
cpp
C++
SOMTRANSIT/MAXTRANSIT/samples/objects/particles/sflectrs/monoflector.cpp
SOM-Firmwide/SOMTRANSIT
a83879c3b60bd24c45bcf4c01fcd11632e799973
[ "MIT" ]
null
null
null
SOMTRANSIT/MAXTRANSIT/samples/objects/particles/sflectrs/monoflector.cpp
SOM-Firmwide/SOMTRANSIT
a83879c3b60bd24c45bcf4c01fcd11632e799973
[ "MIT" ]
null
null
null
SOMTRANSIT/MAXTRANSIT/samples/objects/particles/sflectrs/monoflector.cpp
SOM-Firmwide/SOMTRANSIT
a83879c3b60bd24c45bcf4c01fcd11632e799973
[ "MIT" ]
null
null
null
#include "MonoflectDialog.h" #include "sflectr.h" #include "MouseCursors.h" #define PLANAR 0 #define SPHERE 1 #define MESH 2 #define MONODEF_CUSTNAME_CHUNK 0x0100 static TriObject *IsUseable(Object *pobj,TimeValue t) { if (pobj->SuperClassID()==GEOMOBJECT_CLASS_ID) { if (pobj->IsSubClassOf(triObjectClassID)) return (TriObject*)pobj; else { if (pobj->CanConvertToType(triObjectClassID)) return (TriObject*)pobj->ConvertToType(t,triObjectClassID); } } return NULL; } //--- ClassDescriptor and class vars --------------------------------- class BasicFlectorModClassDesc:public ClassDesc { public: int IsPublic() {return 0;} void * Create(BOOL loading = FALSE) { return new BasicFlectorMod();} const TCHAR * ClassName() {return GetString(IDS_EP_BASICDEFLECTORMOD);} SClass_ID SuperClassID() {return WSM_CLASS_ID; } Class_ID ClassID() {return BASICFLECTORMOD_CLASSID;} const TCHAR* Category() {return _T("");} }; static BasicFlectorModClassDesc BasicFlectorModDesc; ClassDesc* GetBasicFlectorModDesc() {return &BasicFlectorModDesc;} IObjParam* BasicFlectorObj::ip = NULL; class FlectorPickOperand : public PickModeCallback, public PickNodeCallback { public: BasicFlectorObj *po; FlectorPickOperand() {po=NULL;} BOOL HitTest(IObjParam *ip,HWND hWnd,ViewExp *vpt,IPoint2 m,int flags); BOOL Pick(IObjParam *ip,ViewExp *vpt); void EnterMode(IObjParam *ip); void ExitMode(IObjParam *ip); BOOL RightClick(IObjParam *ip, ViewExp * /*vpt*/) { return TRUE; } BOOL Filter(INode *node); PickNodeCallback *GetFilter() {return this;} }; class CreateFlectorPickNode : public RestoreObj { public: BasicFlectorObj *obj; INode *oldn; CreateFlectorPickNode(BasicFlectorObj *o, INode *n) { obj = o; oldn=n; } void Restore(int isUndo) { INode* cptr=obj->st->pblock2->GetINode(PB_MESHNODE); TSTR custname; if (cptr) { custname = TSTR(cptr->GetName()); } else { custname=_T(""); } obj->st->ShowName(); } void Redo() { int type; obj->pblock2->GetValue(PB_TYPE,0,type,FOREVER); if ((type==2)&&(obj->st->pmap[pbType_subani])) obj->st->ShowName(oldn); } TSTR Description() {return GetString(IDS_AP_FPICK);} }; #define CID_CREATEBasicFlectorMODE CID_USER +23 FlectorPickOperand BasicFlectorObj::pickCB; IParamMap2Ptr BasicFlectorObj::pmap[numpblocks]={NULL,NULL}; class CreateBasicFlectorProc : public MouseCallBack,ReferenceMaker { private: IObjParam *ip; void Init(IObjParam *i) {ip=i;} CreateMouseCallBack *createCB; INode *CloudNode; BasicFlectorObj *BasicFlectorObject; int attachedToNode; IObjCreate *createInterface; ClassDesc *cDesc; Matrix3 mat; // the nodes TM relative to the CP Point3 p0,p1; IPoint2 sp0, sp1; BOOL square; int ignoreSelectionChange; int lastPutCount; void CreateNewObject(); virtual void GetClassName(MSTR& s) { s = _M("CreateBasicFlectorProc"); } // from Animatable int NumRefs() { return 1; } RefTargetHandle GetReference(int i) { return (RefTargetHandle)CloudNode; } void SetReference(int i, RefTargetHandle rtarg) { CloudNode = (INode *)rtarg; } // StdNotifyRefChanged calls this, which can change the partID to new value // If it doesnt depend on the particular message& partID, it should return // REF_DONTCARE BOOL SupportAutoGrid(){return TRUE;} RefResult NotifyRefChanged(const Interval& changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message, BOOL propagate); public: void Begin( IObjCreate *ioc, ClassDesc *desc ); void End(); void SetIgnore(BOOL sw) { ignoreSelectionChange = sw; } CreateBasicFlectorProc() { ignoreSelectionChange = FALSE; } int createmethod(ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat); int proc( HWND hwnd, int msg, int point, int flag, IPoint2 m ); }; class CreateBasicFlectorMode : public CommandMode { public: CreateBasicFlectorProc proc; IObjParam *ip; BasicFlectorObj *obj; void Begin( IObjCreate *ioc, ClassDesc *desc ) { proc.Begin( ioc, desc ); } void End() { proc.End(); } void JumpStart(IObjParam *i,BasicFlectorObj*o); int Class() {return CREATE_COMMAND;} int ID() { return CID_CREATEBasicFlectorMODE; } MouseCallBack *MouseProc(int *numPoints) {*numPoints = 10000; return &proc;} ChangeForegroundCallback *ChangeFGProc() {return CHANGE_FG_SELECTED;} BOOL ChangeFG( CommandMode *oldMode ) { return (oldMode->ChangeFGProc() != CHANGE_FG_SELECTED); } void EnterMode() { GetCOREInterface()->PushPrompt(GetString(IDS_AP_CREATEMODE)); SetCursor(UI::MouseCursors::LoadMouseCursor(UI::MouseCursors::Crosshair)); } void ExitMode() {GetCOREInterface()->PopPrompt();SetCursor(LoadCursor(NULL, IDC_ARROW));} }; static CreateBasicFlectorMode theCreateBasicFlectorMode; IParamMap2Ptr BasicFlectorType::pmap[numpblocks]={NULL,NULL}; MonoFlectorParamPtr BasicFlectorType::theParam[numpblocks]={NULL,NULL}; class BasicFlectorTypeObjDlgProc : public BasicFlectorDlgProc { public: HWND hw; int dtype; ParamID which; IParamBlock2* pblk; BasicFlectorTypeObjDlgProc(BasicFlectorObj* sso_in) { sso = sso_in; st = NULL; dtype = pbType_subani; which = PB_TYPE; } void Update(TimeValue t); INT_PTR DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); }; class BasicFlectorComplexDlgProc : public BasicFlectorDlgProc { public: HWND hw; int dtype; ParamID which; IParamBlock2* pblk; BasicFlectorComplexDlgProc(BasicFlectorObj* sso_in) { sso = sso_in; st = NULL; dtype = pbComplex_subani; which = PB_COMPLEX; } void Update(TimeValue t); INT_PTR DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); }; // this classdesc2 for the object class BasicFlectorObjClassDesc:public ClassDesc2 { public: int IsPublic() { return TRUE; } void * Create( BOOL loading ) { return new BasicFlectorObj(); } const TCHAR * ClassName() { return GetString(IDS_AP_MONONAME); } SClass_ID SuperClassID() { return WSM_OBJECT_CLASS_ID; } Class_ID ClassID() { return BASICFLECTOR_CLASSID; } const TCHAR* Category() { return GetString(IDS_EP_SW_DEFLECTORS); } int BeginCreate(Interface *i); int EndCreate(Interface *i); // Hardwired name, used by MAX Script as unique identifier const TCHAR* InternalName() { return _T("BasicFlectorObj"); } HINSTANCE HInstance() { return hInstance; } }; static BasicFlectorObjClassDesc BasicFlectorOCD; ClassDesc* GetBasicFlectorObjDesc() {return &BasicFlectorOCD;} BOOL BasicFlectorObj::creating = FALSE; void BasicFlectorTypeObjDlgProc::Update(TimeValue t) { sdlgs = GetDlgItem(hw, IDC_FLECTTYPELIST); SetUpList(sdlgs,hw,sso->st->GetNameList(dtype)); int oldval; pblk->GetValue(which,0,oldval,FOREVER); SendMessage(sdlgs, CB_SETCURSEL, oldval, 0); } //each one of these takes input from a listbox and creates/destroys the subrollups INT_PTR BasicFlectorTypeObjDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { int id = LOWORD(wParam); pblk=sso->pblock2; hw=hWnd; switch (msg) { case WM_INITDIALOG: Update(t); break; case WM_DESTROY: if (sso->st->theParam[dtype]) { sso->st->theParam[dtype]->DeleteThis(); sso->st->theParam[dtype]=NULL; } break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_FLECTTYPELIST: int curSel = SendMessage(sdlgs, CB_GETCURSEL, 0, 0); if (curSel<0) return TRUE; int oldval; pblk->GetValue(which,0,oldval,FOREVER); if (oldval!=curSel) { pblk->SetValue(which,0,curSel); sso->st->CreateMonoFlectorParamDlg(GetCOREInterface(),curSel,dtype,sso->st->pmap[dtype]->GetHWnd()); } return TRUE; } break; } return FALSE; } void BasicFlectorComplexDlgProc::Update(TimeValue t) { sdlgs = GetDlgItem(hw, IDC_FLECTCOMPLEXITYLIST); SetUpList(sdlgs,hw,sso->st->GetNameList(dtype)); int oldval;pblk->GetValue(which,0,oldval,FOREVER); SendMessage(sdlgs, CB_SETCURSEL, oldval, 0); } INT_PTR BasicFlectorComplexDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { int id = LOWORD(wParam); pblk=sso->pbComplex;hw=hWnd; switch (msg) { case WM_INITDIALOG: Update(t); break; case WM_DESTROY: if (sso->st->theParam[dtype]) { sso->st->theParam[dtype]->DeleteThis();sso->st->theParam[dtype]=NULL; } break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_FLECTCOMPLEXITYLIST: int curSel = SendMessage(sdlgs, CB_GETCURSEL, 0, 0); if (curSel<0) return TRUE; int oldval; pblk->GetValue(which,0,oldval,FOREVER); if (oldval!=curSel) { pblk->SetValue(which,0,curSel); sso->st->CreateMonoFlectorParamDlg(GetCOREInterface(),curSel,dtype,sso->st->pmap[dtype]->GetHWnd()); } return TRUE; } break; } return FALSE; } static BOOL IsGEOM(Object *obj) { if (obj!=NULL) { if (obj->SuperClassID()==GEOMOBJECT_CLASS_ID) { if (obj->IsSubClassOf(triObjectClassID)) return TRUE; else { if (obj->CanConvertToType(triObjectClassID)) return TRUE; } } } return FALSE; } BOOL FlectorPickOperand::Filter(INode *node) { if ((node)&&(!node->IsGroupHead())) { ObjectState os = node->GetObjectRef()->Eval(po->ip->GetTime()); if (os.obj->IsParticleSystem() || os.obj->SuperClassID()!=GEOMOBJECT_CLASS_ID) { node = NULL; return FALSE; } node->BeginDependencyTest(); po->NotifyDependents(FOREVER,0,REFMSG_TEST_DEPENDENCY); if(node->EndDependencyTest()) { node = NULL; return FALSE; } } return node ? TRUE : FALSE; } BOOL FlectorPickOperand::HitTest( IObjParam *ip,HWND hWnd,ViewExp *vpt,IPoint2 m,int flags) { if ( ! vpt || ! vpt->IsAlive() || ! hWnd) { // why are we here DbgAssert(!_T("Invalid viewport!")); return FALSE; } INode *node = ip->PickNode(hWnd,m,this); if ((node)&&(!node->IsGroupHead())) { ObjectState os = node->GetObjectRef()->Eval(ip->GetTime()); if ((os.obj->SuperClassID()!=GEOMOBJECT_CLASS_ID)||(!IsGEOM(os.obj))) { node = NULL; return FALSE; } } return node ? TRUE : FALSE; } BOOL FlectorPickOperand::Pick(IObjParam *ip,ViewExp *vpt) { if ( ! vpt || ! vpt->IsAlive() ) { // why are we here DbgAssert(!_T("Invalid viewport!")); return FALSE; } BOOL groupflag=0; INode *node = vpt->GetClosestHit(); assert(node); INodeTab nodes; if (node->IsGroupMember()) { groupflag=1; while (node->IsGroupMember()) node=node->GetParentNode(); } int subtree=0; if (groupflag) MakeGroupNodeList(node,&nodes,subtree,ip->GetTime()); else{ nodes.SetCount(1);nodes[0]=node;} ip->FlashNodes(&nodes); theHold.Begin(); theHold.Put(new CreateFlectorPickNode(po,node)); po->st->pblock2->SetValue(PB_MESHNODE,ip->GetTime(),node); theHold.Accept(GetString(IDS_AP_FPICK)); po->st->ShowName(node); if (po->creating) { theCreateBasicFlectorMode.JumpStart(ip,po); ip->SetCommandMode(&theCreateBasicFlectorMode); ip->RedrawViews(ip->GetTime()); return FALSE; } else { return TRUE; } } void FlectorPickOperand::EnterMode(IObjParam *ip) { ICustButton *iBut; iBut=GetICustButton(GetDlgItem(po->st->hParams,IDC_EP_PICKBUTTON)); if (iBut) iBut->SetCheck(TRUE); ReleaseICustButton(iBut); GetCOREInterface()->PushPrompt(GetString(IDS_AP_PICKMODE)); } void FlectorPickOperand::ExitMode(IObjParam *ip) { ICustButton *iBut; iBut=GetICustButton(GetDlgItem(po->st->hParams,IDC_EP_PICKBUTTON)); if (iBut) iBut->SetCheck(FALSE); ReleaseICustButton(iBut); GetCOREInterface()->PopPrompt(); } //pb2s for each static dialog static ParamBlockDesc2 BasicFlectorPB ( pbType_subani, _T("BasicFlectorParams"), 0, &BasicFlectorOCD, P_AUTO_CONSTRUCT + P_AUTO_UI, pbType_subani, //rollout IDD_MF_0100_FLECTTYPESELECT, IDS_DLG_FTYPE, 0, 0, NULL, // params PB_TYPE, _T("FlectorType"), TYPE_INT, 0, IDS_FLECTORTYPETBLE, p_end, //watje ref to hold the collision engine monoflect_colliderp, _T("colliderplane"), TYPE_REFTARG, 0, IDS_FLECTORTYPETBLE, p_end, monoflect_colliders, _T("collidersphere"), TYPE_REFTARG, 0, IDS_FLECTORTYPETBLE, p_end, monoflect_colliderm, _T("collidermesh"), TYPE_REFTARG, 0, IDS_FLECTORTYPETBLE, p_end, p_end ); static ParamBlockDesc2 BasicFComplexPB ( pbComplex_subani, _T("FlectorComplexityParams"), 0, &BasicFlectorOCD, P_AUTO_CONSTRUCT + P_AUTO_UI, pbComplex_subani, //rollout IDD_MF_0200_FLECTCOMPLEXITYSELECT, IDS_DLG_FCOMPLEX, 0, 0, NULL, // params PB_COMPLEX, _T("FlectorComplex"), TYPE_INT, 0, IDS_FLECTORCOMPTBLE, p_end, p_end ); RefResult CreateBasicFlectorProc::NotifyRefChanged( const Interval& changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message, BOOL propagate) { switch (message) { case REFMSG_TARGET_SELECTIONCHANGE: if ( ignoreSelectionChange ) { break; } if ( BasicFlectorObject && CloudNode==hTarget ) { // this will set camNode== NULL; theHold.Suspend(); DeleteReference(0); theHold.Resume(); goto endEdit; } // fall through case REFMSG_TARGET_DELETED: if (BasicFlectorObject && CloudNode==hTarget ) { endEdit: if (createInterface->GetCommandMode()->ID() == CID_STDPICK) { if (BasicFlectorObject->creating) { theCreateBasicFlectorMode.JumpStart(BasicFlectorObject->ip,BasicFlectorObject); createInterface->SetCommandMode(&theCreateBasicFlectorMode); } else {createInterface->SetStdCommandMode(CID_OBJMOVE);} } BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); BasicFlectorObject->EndEditParams( (IObjParam*)createInterface, 0, NULL); BasicFlectorObject = NULL; CloudNode = NULL; CreateNewObject(); attachedToNode = FALSE; } else if (CloudNode==hTarget ) CloudNode = NULL; break; } return REF_SUCCEED; } void AddMesh(BasicFlectorObj *obj, TriObject *triOb, Matrix3 tm, BOOL nottop) { int lastv = obj->nv, lastf = obj->nf; obj->nv += triOb->GetMesh().getNumVerts(); obj->nf += triOb->GetMesh().getNumFaces(); if (!nottop) obj->dmesh->DeepCopy(&triOb->GetMesh(),PART_GEOM|PART_TOPO); else { obj->dmesh->setNumFaces(obj->nf,obj->dmesh->getNumFaces()); obj->dmesh->setNumVerts(obj->nv,obj->dmesh->getNumVerts()); tm = tm*obj->invtm; for (int vc=0;vc<triOb->GetMesh().getNumFaces();vc++) { obj->dmesh->faces[lastf]=triOb->GetMesh().faces[vc]; for (int vs=0;vs<3;vs++) obj->dmesh->faces[lastf].v[vs]+=lastv; lastf++; } } for (int vc=0;vc<triOb->GetMesh().getNumVerts();vc++) { if (nottop) obj->dmesh->verts[lastv]=triOb->GetMesh().verts[vc]*tm; else obj->dmesh->verts[lastv]=triOb->GetMesh().verts[vc]; lastv++; } } void CreateBasicFlectorProc::Begin( IObjCreate *ioc, ClassDesc *desc ) { ip=(IObjParam*)ioc; createInterface = ioc; cDesc = desc; attachedToNode = FALSE; createCB = NULL; CloudNode = NULL; BasicFlectorObject = NULL; CreateNewObject(); } void CreateBasicFlectorProc::CreateNewObject() { SuspendSetKeyMode(); createInterface->GetMacroRecorder()->BeginCreate(cDesc); BasicFlectorObject = (BasicFlectorObj*)cDesc->Create(); lastPutCount = theHold.GetGlobalPutCount(); // Start the edit params process if ( BasicFlectorObject ) { BasicFlectorObject->BeginEditParams( (IObjParam*)createInterface, BEGIN_EDIT_CREATE, NULL ); BasicFlectorObject->SetAFlag(A_OBJ_CREATING); BasicFlectorObject->SetAFlag(A_OBJ_LONG_CREATE); } ResumeSetKeyMode(); } //LACamCreationManager::~LACamCreationManager void CreateBasicFlectorProc::End() { if ( BasicFlectorObject ) { BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); BasicFlectorObject->EndEditParams( (IObjParam*)createInterface, END_EDIT_REMOVEUI, NULL); if ( !attachedToNode ) { // RB 4-9-96: Normally the hold isn't holding when this // happens, but it can be in certain situations (like a track view paste) // Things get confused if it ends up with undo... theHold.Suspend(); BasicFlectorObject->DeleteAllRefsFromMe(); BasicFlectorObject->DeleteAllRefsToMe(); theHold.Resume(); BasicFlectorObject->DeleteThis(); BasicFlectorObject = NULL; createInterface->GetMacroRecorder()->Cancel(); if (theHold.GetGlobalPutCount()!=lastPutCount) GetSystemSetting(SYSSET_CLEAR_UNDO); } else if ( CloudNode ) { theHold.Suspend(); DeleteReference(0); // sets cloudNode = NULL theHold.Resume(); } } } void CreateBasicFlectorMode::JumpStart(IObjParam *i,BasicFlectorObj *o) { ip = i; obj = o; obj->BeginEditParams(i,BEGIN_EDIT_CREATE,NULL); } int BasicFlectorObjClassDesc::BeginCreate(Interface *i) { SuspendSetKeyMode(); IObjCreate *iob = i->GetIObjCreate(); theCreateBasicFlectorMode.Begin(iob,this); iob->PushCommandMode(&theCreateBasicFlectorMode); return TRUE; } int BasicFlectorObjClassDesc::EndCreate(Interface *i) { ResumeSetKeyMode(); theCreateBasicFlectorMode.End(); i->RemoveMode(&theCreateBasicFlectorMode); macroRec->EmitScript(); // 10/00 return TRUE; } int CreateBasicFlectorProc::proc(HWND hwnd,int msg,int point,int flag, IPoint2 m ) { int res=TRUE; ViewExp& vpx = createInterface->GetViewExp(hwnd); assert( vpx.IsAlive() ); DWORD snapdim = SNAP_IN_3D; switch ( msg ) { case MOUSE_POINT: switch ( point ) { case 0: { assert( BasicFlectorObject ); vpx.CommitImplicitGrid(m, flag ); if ( createInterface->SetActiveViewport(hwnd) ) { return FALSE; } if (createInterface->IsCPEdgeOnInView()) { res = FALSE; goto done; } if ( attachedToNode ) { // send this one on its way BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); BasicFlectorObject->EndEditParams( (IObjParam*)createInterface, 0, NULL); createInterface->GetMacroRecorder()->EmitScript(); // Get rid of the reference. if (CloudNode) { theHold.Suspend(); DeleteReference(0); theHold.Resume(); } // new object CreateNewObject(); // creates BasicFlectorObject } theHold.Begin(); // begin hold for undo mat.IdentityMatrix(); // link it up INode *l_CloudNode = createInterface->CreateObjectNode( BasicFlectorObject); attachedToNode = TRUE; BasicFlectorObject->ClearAFlag(A_OBJ_CREATING); assert( l_CloudNode ); createCB = NULL; createInterface->SelectNode( l_CloudNode ); // Reference the new node so we'll get notifications. theHold.Suspend(); ReplaceReference( 0, l_CloudNode); theHold.Resume(); mat.SetTrans(vpx.SnapPoint(m,m,NULL,snapdim)); macroRec->Disable(); // 10/00 createInterface->SetNodeTMRelConstPlane(CloudNode, mat); macroRec->Enable(); } default: res = createmethod(vpx.ToPointer(),msg,point,flag,m,mat); createInterface->SetNodeTMRelConstPlane(CloudNode, mat); if (res==CREATE_ABORT) goto abort; if (res==CREATE_STOP) { BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); theHold.Accept(GetString(IDS_EP_CREATE)); } createInterface->RedrawViews(createInterface->GetTime()); //DS break; } break; case MOUSE_MOVE: res = createmethod(vpx.ToPointer(),msg,point,flag,m,mat); macroRec->Disable(); // 10/2/00 createInterface->SetNodeTMRelConstPlane(CloudNode, mat); macroRec->Enable(); if (res==CREATE_ABORT) goto abort; if (res==CREATE_STOP) { BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); theHold.Accept(GetString(IDS_EP_CREATE)); // TH } createInterface->RedrawViews(createInterface->GetTime(),REDRAW_INTERACTIVE); //DS // macroRec->SetProperty(BasicFlectorObject, _T("target"), // JBW 4/23/99 // mr_create, Class_ID(TARGET_CLASS_ID, 0), GEOMOBJECT_CLASS_ID, 1, _T("transform"), mr_matrix3, &mat); break; case MOUSE_FREEMOVE: SetCursor(UI::MouseCursors::LoadMouseCursor(UI::MouseCursors::Crosshair)); res = createmethod(vpx.ToPointer(),msg,point,flag,m,mat); vpx.TrackImplicitGrid(m); break; case MOUSE_PROPCLICK: createInterface->SetStdCommandMode(CID_OBJMOVE); break; case MOUSE_ABORT: abort: assert( BasicFlectorObject ); BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); BasicFlectorObject->EndEditParams( (IObjParam*)createInterface,0,NULL); theHold.Cancel(); // deletes both the Cloudera and target. if (theHold.GetGlobalPutCount()!=lastPutCount) GetSystemSetting(SYSSET_CLEAR_UNDO); BasicFlectorObject=NULL; createInterface->RedrawViews(createInterface->GetTime()); CreateNewObject(); attachedToNode = FALSE; res = FALSE; } done: if ((res == CREATE_STOP)||(res==CREATE_ABORT)) vpx.ReleaseImplicitGrid(); return res; } void BasicFlectorDlgProc::SetUpList(HWND cwnd,HWND hWnd,dlglist ilist) { SendMessage(cwnd,CB_RESETCONTENT,0,0); for (int i=0; i<ilist.cnt; i++) { SendMessage(cwnd,CB_ADDSTRING,0,(LPARAM)(TCHAR*)GetString(ilist.namelst[i])); } } BasicFlectorObj::BasicFlectorObj() { gf = NULL; mf = NULL; pbComplex = NULL; st = NULL; BasicFlectorOCD.MakeAutoParamBlocks(this); assert(pblock2); assert(pbComplex); ReplaceReference(monoflecdlg,new MonoFlector(this)); int tpf=GetTicksPerFrame(); int timeoff=100*tpf; ffdata.FlectForce = Zero; ffdata.ApplyAt = Zero; ffdata.Num = 0; dmesh=NULL; vnorms=NULL; fnorms=NULL; srand(lastrnd=12345); t=99999; custnode=NULL; custname=_T(" "); nv=0;nf=0; ctime=99999; pblock2->SetValue(PB_TYPE,0,0); macroRec->Disable(); //watje create a new ref to our collision engine CollisionPlane *colp = (CollisionPlane*)CreateInstance(REF_MAKER_CLASS_ID, PLANAR_COLLISION_ID); if (colp) { pblock2->SetValue(monoflect_colliderp,0,(ReferenceTarget*)colp); } CollisionSphere *cols = (CollisionSphere*)CreateInstance(REF_MAKER_CLASS_ID, SPHERICAL_COLLISION_ID); if (cols) { pblock2->SetValue(monoflect_colliders,0,(ReferenceTarget*)cols); } CollisionMesh *colm = (CollisionMesh*)CreateInstance(REF_MAKER_CLASS_ID, MESH_COLLISION_ID); if (colm) { pblock2->SetValue(monoflect_colliderm,0,(ReferenceTarget*)colm); } macroRec->Enable(); } BasicFlectorObj::~BasicFlectorObj() { DeleteAllRefsFromMe(); if (gf) delete gf; if (mf) delete mf; if (vnorms) delete[] vnorms; if (fnorms) delete[] fnorms; if (dmesh) delete dmesh; DbgAssert(NULL == pblock2); } void BasicFlectorObj::MapKeys(TimeMap *map,DWORD flags) { Animatable::MapKeys(map,flags); TimeValue TempTime; float ftemp,tpf=GetTicksPerFrame(); pbComplex->GetValue(PB_TIMEON,0,ftemp,FOREVER); TempTime=ftemp*tpf; TempTime = map->map(TempTime); pbComplex->SetValue(PB_TIMEON,0,((float)ftemp)/tpf); pbComplex->GetValue(PB_TIMEOFF,0,ftemp,FOREVER); TempTime=ftemp*tpf; TempTime = map->map(TempTime); pbComplex->SetValue(PB_TIMEOFF,0,((float)ftemp)/tpf); } Modifier *BasicFlectorObj::CreateWSMMod(INode *node) { return new BasicFlectorMod(node,this); } void BasicFlectorObj::IntoPickMode() { if (ip->GetCommandMode()->ID() == CID_STDPICK) { if (creating) { theCreateBasicFlectorMode.JumpStart(ip,this); ip->SetCommandMode(&theCreateBasicFlectorMode); } else {ip->SetStdCommandMode(CID_OBJMOVE);} } else { pickCB.po = this; ip->SetPickMode(&pickCB); } } Object *BasicFlectorField::GetSWObject() { return obj; } BOOL BasicFlectorField::CheckCollision(TimeValue t,Point3 &inp,Point3 &vel,float dt,int index,float *ct, BOOL UpdatePastCollide) { if (obj == NULL) return FALSE; //667105 watje xrefs can change the base object type through proxies which will cause this to be null or the user can copy a new object type over ours BOOL donewithparticle = FALSE; float K=(float)GetMasterScale(UNITS_CENTIMETERS); float stepsize = dt; Point3 InVel, SaveVel = vel; int typeofdeflector; obj->pblock2->GetValue(PB_TYPE,t,typeofdeflector,FOREVER); int enableAdvanced, enableDynamics; obj->pbComplex->GetValue(PB_COMPLEX,t,enableAdvanced,FOREVER); enableDynamics = (enableAdvanced>1?1:0); enableAdvanced = (enableAdvanced>0?1:0); switch(typeofdeflector) { case PLANAR: // PLANAR COLLISION CODE BLOCK BEGINS HERE { ReferenceTarget *rt; obj->pblock2->GetValue(monoflect_colliderp,t,rt,obj->tmValid); colp = (CollisionPlane *) rt; if (!((obj->mValid.InInterval(t))&&(obj->tmValid.InInterval(t)))) { obj->tmValid = FOREVER; obj->st->pblock2->GetValue(PB_WIDTH,t,width,obj->tmValid); obj->st->pblock2->GetValue(PB_LENGTH,t,height,obj->tmValid); obj->st->pblock2->GetValue(PB_QUALITY,t,quality,obj->tmValid); if (colp) { colp->SetWidth(t,width); colp->SetHeight(t,height); colp->SetQuality(t,quality); colp->SetNode(t,node); } if (colp) colp->PreFrame(t,(TimeValue) dt); obj->st->pbComplex->GetValue(PB_BOUNCE,t,bounce,obj->tmValid); obj->st->pbComplex->GetValue(PB_BVAR,t,bvar,obj->tmValid); obj->st->pbComplex->GetValue(PB_CHAOS,t,chaos,obj->tmValid); obj->st->pbComplex->GetValue(PB_INHERVEL,t,vinher,obj->tmValid); obj->st->pbComplex->GetValue(PB_FRICTION,t,friction,obj->tmValid); // vinher *= 0.01f; // bvar *= 0.01f; // chaos *= 0.01f; // friction *= 0.01f; obj->st->pbComplex->GetValue(PB_DISTORTION,t,refvol,obj->tmValid); // refvol *= 0.01f; obj->st->pbComplex->GetValue(PB_DISTORTIONVAR,t,refvar,FOREVER); // refvar *= 0.01f; obj->st->pbComplex->GetValue(PB_PASSVEL,t,decel,FOREVER); obj->st->pbComplex->GetValue(PB_PASSVELVAR,t,decelvar,FOREVER); // decelvar *= 0.01f; width *= 0.5f; height *= 0.5f; Interval tmpValid = FOREVER; } if ((curtime!=t)&&(enableDynamics)) { totalforce = Zero; applyat = Zero; totalnumber = 0; curtime = t; } float fstartt,fendt; TimeValue startt,endt; obj->st->pbComplex->GetValue(PB_TIMEON,t,fstartt,FOREVER); obj->st->pbComplex->GetValue(PB_TIMEOFF,t,fendt,FOREVER); startt=fstartt*GetTicksPerFrame();endt=fendt*GetTicksPerFrame(); if ((t<startt)||(t>endt)) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } if (!colp) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } else { srand(obj->lastrnd); float reflects; obj->st->pbComplex->GetValue(PB_REFLECTS,t,reflects,FOREVER); // reflects *= 0.01f; if (RND01()<reflects) { donewithparticle = TRUE; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colp->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float rvariation = 1.0f; float rchaos = 1.0f; if (bvar != 0.0f) { rvariation =1.0f-( bvar * randomFloat[index%500]); } if (chaos != 0.0f) { rchaos =1.0f-( chaos * randomFloat[index%500]); } vel = bnorm*(bounce*rvariation) + frict*(1.0f-(friction*rchaos)) + (inheritedVel * vinher); inp = hitpoint; if (UpdatePastCollide) { inp += vel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } vel += (inheritedVel * vinher); InVel = vel; applyat = hitpoint; } // particle was not reflected and not tested for refraction! float refracts; obj->st->pbComplex->GetValue(PB_REFRACTS,t,refracts,FOREVER); // refracts *= 0.01f; if ((RND01()<refracts)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colp->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float dirapproach,theta = 0.0f; Point3 ZVec = bnorm; dirapproach = (DotProd(InVel,ZVec)<0.0f?1.0f:-1.0f); Point3 MZVec = -bnorm; InVel *= decel*(1.0f-decelvar*RND01()); float maxref,refangle,maxvarref; refangle = 0.0f; if (!FloatEQ0(refvol)) { if (dirapproach>0.0f) theta = (float)acos(DotProd(Normalize(-InVel),ZVec)); else theta = (float)acos(DotProd(Normalize(-InVel),MZVec)); if ((refvol>0.0f)==(dirapproach>0.0f)) maxref = -theta; else maxref = HalfPI-theta; refangle = maxref*(float)fabs(refvol); float frefangle = (float)fabs(refangle); if ((refvol>0.0f)==(dirapproach>0.0f)) maxvarref = HalfPI-theta-frefangle; else maxvarref = theta-frefangle; refangle += maxvarref*RND11()*refvar; Point3 c,d; if (theta<0.01f) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); d = Point3(xtmp,ytmp,ztmp); c = Normalize(InVel^d); } else { if (dirapproach>0.0f) c = Normalize(ZVec^(-InVel)); else c = Normalize(MZVec^(-InVel)); } RotateOnePoint(InVel,&Zero.x,&c.x,refangle); } float maxdiff,diffuse,diffvar,diffangle; obj->st->pbComplex->GetValue(PB_DIFFUSION,t,diffuse,FOREVER); // diffuse *= 0.01f; obj->st->pbComplex->GetValue(PB_DIFFUSIONVAR,t,diffvar,FOREVER); // diffvar *= 0.01f; maxdiff = HalfPI-theta-refangle; if (!FloatEQ0(diffuse)) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); Point3 d = Point3(xtmp,ytmp,ztmp); Point3 c = Normalize(InVel^d); diffangle = 0.5f*maxdiff*diffuse*(1.0f+RND11()*diffvar); RotateOnePoint(InVel,&Zero.x,&c.x,diffangle); } if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } // particle was neither reflected nor refracted nor tested for either! float spawnonly; obj->st->pbComplex->GetValue(PB_COLAFFECTS,t,spawnonly,FOREVER); // spawnonly *= 0.01f; if ((RND01()<spawnonly)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colp->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float passvel,passvelvar; obj->st->pbComplex->GetValue(PB_COLPASSVEL,t,passvel,FOREVER); obj->st->pbComplex->GetValue(PB_COLPASSVELVAR,t,passvelvar,FOREVER); // passvelvar *= 0.01f; InVel *= passvel*(1.0f+passvelvar*RND11()); float holddt = dt; dt -= at; if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } } } // PLANAR COLLISION CODE BLOCK ENDS HERE break; case SPHERE: // SPHERE COLLISION CODE BLOCK BEGINS HERE { ReferenceTarget *rt; obj->pblock2->GetValue(monoflect_colliders,t,rt,obj->tmValid); cols = (CollisionSphere *) rt; if (!((obj->mValid.InInterval(t))&&(obj->tmValid.InInterval(t)))) { obj->tmValid = FOREVER; obj->st->pblock2->GetValue(PB_WIDTH,t,width,obj->tmValid); if (cols) { cols->SetRadius(t,width); cols->SetNode(t,node); cols->PreFrame(t,(TimeValue) dt); } obj->st->pbComplex->GetValue(PB_BOUNCE,t,bounce,obj->tmValid); obj->st->pbComplex->GetValue(PB_BVAR,t,bvar,obj->tmValid); obj->st->pbComplex->GetValue(PB_CHAOS,t,chaos,obj->tmValid); obj->st->pbComplex->GetValue(PB_INHERVEL,t,vinher,obj->tmValid); obj->st->pbComplex->GetValue(PB_FRICTION,t,friction,obj->tmValid); // vinher *= 0.01f; // bvar *= 0.01f; // chaos *= 0.01f; // friction *= 0.01f; obj->st->pbComplex->GetValue(PB_DISTORTION,t,refvol,obj->tmValid); // refvol *= 0.01f; obj->st->pbComplex->GetValue(PB_DISTORTIONVAR,t,refvar,FOREVER); // refvar *= 0.01f; obj->st->pbComplex->GetValue(PB_PASSVEL,t,decel,FOREVER); obj->st->pbComplex->GetValue(PB_PASSVELVAR,t,decelvar,FOREVER); // decelvar *= 0.01f; Interval tmpValid = FOREVER; } if ((curtime!=t)&&(enableDynamics)) { totalforce = Zero; applyat = Zero; totalnumber = 0; curtime = t; } float fstartt,fendt; TimeValue startt,endt; obj->st->pbComplex->GetValue(PB_TIMEON,t,fstartt,FOREVER); obj->st->pbComplex->GetValue(PB_TIMEOFF,t,fendt,FOREVER); startt=fstartt*GetTicksPerFrame();endt=fendt*GetTicksPerFrame(); if ((t<startt)||(t>endt)) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } if (!cols) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } else { srand(obj->lastrnd); float reflects; obj->st->pbComplex->GetValue(PB_REFLECTS,t,reflects,FOREVER); // reflects *= 0.01f; if (RND01()<reflects) { donewithparticle = TRUE; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = cols->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float rvariation = 1.0f; float rchaos = 1.0f; if (bvar != 0.0f) { rvariation =1.0f-( bvar * randomFloat[index%500]); } if (chaos != 0.0f) { rchaos =1.0f-( chaos * randomFloat[index%500]); } vel = bnorm*(bounce*rvariation) + frict*(1.0f-(friction*rchaos)) + (inheritedVel * vinher); inp = hitpoint; if (UpdatePastCollide) { inp += vel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } vel += (inheritedVel * vinher); InVel = vel; applyat = hitpoint; } // particle was not reflected and not tested for refraction! float refracts; obj->st->pbComplex->GetValue(PB_REFRACTS,t,refracts,FOREVER); // refracts *= 0.01f; if ((RND01()<refracts)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = cols->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float q1 = DotProd(-InVel,bnorm); float theta = (float)acos(q1); if (theta>=HalfPI) theta -= PI; InVel *= decel*(1.0f-decelvar*RND01()); float maxref,refangle,maxvarref; refangle = 0.0f; if (!FloatEQ0(refvol)) { if (refvol>0.0f) maxref = -theta; else maxref = HalfPI-theta; refangle = maxref*(float)fabs(refvol); float frefangle = (float)fabs(refangle); if (refvol>0.0f) maxvarref = HalfPI-theta-frefangle; else maxvarref = theta-frefangle; refangle += maxvarref*RND11()*refvar; Point3 c,d; if (theta<0.01f) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); d = Point3(xtmp,ytmp,ztmp); c = Normalize(InVel^d); } else c = Normalize(bnorm^(-InVel)); RotateOnePoint(InVel,&Zero.x,&c.x,refangle); } float maxdiff,diffuse,diffvar,diffangle; obj->st->pbComplex->GetValue(PB_DIFFUSION,t,diffuse,FOREVER); // diffuse *= 0.01f; obj->st->pbComplex->GetValue(PB_DIFFUSIONVAR,t,diffvar,FOREVER); // diffvar *= 0.01f; maxdiff = HalfPI-theta-refangle; if (!FloatEQ0(diffuse)) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); Point3 d = Point3(xtmp,ytmp,ztmp); Point3 c = Normalize(InVel^d); diffangle = 0.5f*maxdiff*diffuse*(1.0f+RND11()*diffvar); RotateOnePoint(InVel,&Zero.x,&c.x,diffangle); } if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } // particle was neither reflected nor refracted nor tested for either! float spawnonly; obj->st->pbComplex->GetValue(PB_COLAFFECTS,t,spawnonly,FOREVER); // spawnonly *= 0.01f; if ((RND01()<spawnonly)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = cols->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float passvel,passvelvar; obj->st->pbComplex->GetValue(PB_COLPASSVEL,t,passvel,FOREVER); obj->st->pbComplex->GetValue(PB_COLPASSVELVAR,t,passvelvar,FOREVER); // passvelvar *= 0.01f; InVel *= passvel*(1.0f+passvelvar*RND11()); float holddt = dt; dt -= at; if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } } } // SPHERE COLLISION CODE BLOCK ENDS HERE break; case MESH: // MESH COLLISION CODE BLOCK BEGINS HERE { if (badmesh) { obj->ReturnThreeStateValue = DONTCARE; return(0); } Point3 iw; ReferenceTarget *rt; obj->pblock2->GetValue(monoflect_colliderm,t,rt,obj->tmValid); colm = (CollisionMesh *) rt; if (!((obj->mValid.InInterval(t))&&(obj->tmValid.InInterval(t)))) { obj->tmValid = FOREVER; if (colm) colm->SetNode(t,obj->custnode); if (colm) colm->PreFrame(t,(TimeValue) dt); obj->tm = obj->custnode->GetObjectTM(t,&obj->tmValid); obj->tmNoTrans = obj->tm; obj->tmNoTrans.NoTrans(); obj->invtm = Inverse(obj->tm); obj->invtmNoTrans = Inverse(obj->tmNoTrans); obj->st->pbComplex->GetValue(PB_BOUNCE,t,bounce,obj->tmValid); obj->st->pbComplex->GetValue(PB_BVAR,t,bvar,obj->tmValid); obj->st->pbComplex->GetValue(PB_CHAOS,t,chaos,obj->tmValid); obj->st->pbComplex->GetValue(PB_INHERVEL,t,vinher,obj->tmValid); obj->st->pbComplex->GetValue(PB_FRICTION,t,friction,obj->tmValid); obj->st->pbComplex->GetValue(PB_DISTORTION,t,refvol,obj->tmValid); obj->st->pbComplex->GetValue(PB_DISTORTIONVAR,t,refvar,obj->tmValid); obj->st->pbComplex->GetValue(PB_PASSVEL,t,decel,obj->tmValid); obj->st->pbComplex->GetValue(PB_PASSVELVAR,t,decelvar,obj->tmValid); // vinher *= 0.01f; // bvar *= 0.01f; // chaos *= 0.01f; // friction *= 0.01f; if (obj->dmesh) delete obj->dmesh; obj->dmesh = new Mesh; obj->dmesh->setNumFaces(0); if (obj->vnorms) { delete[] obj->vnorms; obj->vnorms=NULL; } if (obj->fnorms) { delete[] obj->fnorms; obj->fnorms=NULL; } obj->nv = (obj->nf=0); Interval tmpValid=FOREVER; obj->ptm = obj->custnode->GetObjectTM(t+(TimeValue)dt,&tmpValid); obj->dvel = (Zero*obj->ptm-Zero*obj->tm)/dt; Object *pobj; pobj = obj->custnode->EvalWorldState(t).obj; obj->mValid = pobj->ObjectValidity(t); TriObject *triOb=NULL; badmesh = TRUE; if ((triOb=IsUseable(pobj,t))!=NULL) AddMesh(obj,triOb,obj->tm,FALSE); if (obj->custnode->IsGroupHead()) { for (int ch=0;ch<obj->custnode->NumberOfChildren();ch++) { INode *cnode=obj->custnode->GetChildNode(ch); if (cnode->IsGroupMember()) { pobj = cnode->EvalWorldState(t).obj; if ((triOb=IsUseable(pobj,t))!=NULL) { Matrix3 tm=cnode->GetObjectTM(t,&obj->tmValid); obj->mValid=obj->mValid & pobj->ObjectValidity(t); AddMesh(obj,triOb,tm,TRUE); } } } } if (obj->nf>0) { obj->vnorms=new MaxSDK::VertexNormal[obj->nv]; obj->fnorms=new Point3[obj->nf]; GetVFLst(obj->dmesh,obj->vnorms,obj->fnorms); badmesh=FALSE; } if ((triOb)&&(triOb!=pobj)) triOb->DeleteThis(); } if (badmesh) { obj->ReturnThreeStateValue = DONTCARE; return 0; } if ((curtime!=t)&&(enableDynamics)) { totalforce = Zero; applyat = Zero; totalnumber = 0; curtime = t; } float fstartt,fendt; TimeValue startt,endt; obj->st->pbComplex->GetValue(PB_TIMEON,t,fstartt,FOREVER); obj->st->pbComplex->GetValue(PB_TIMEOFF,t,fendt,FOREVER); startt=fstartt*GetTicksPerFrame();endt=fendt*GetTicksPerFrame(); if ((t<startt)||(t>endt)) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } if (!colm) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } else { srand(obj->lastrnd); float TempDP; float reflects; obj->st->pbComplex->GetValue(PB_REFLECTS,t,reflects,FOREVER); // reflects *= 0.01f; if (RND01()<reflects) { donewithparticle = TRUE; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colm->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float rvariation = 1.0f; float rchaos = 1.0f; if (bvar != 0.0f) { rvariation = 1.0f - (bvar * randomFloat[index%500]); } if (chaos != 0.0f) { rchaos = 1.0f - (chaos * randomFloat[index%500]); } vel = bnorm*(bounce*rvariation) + frict*(1.0f-(friction*rchaos)) ; inp = hitpoint; if (UpdatePastCollide) { inp += vel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } vel += (inheritedVel * vinher); InVel = vel; applyat = hitpoint; } // particle was not reflected and not tested for refraction! float refracts; obj->st->pbComplex->GetValue(PB_REFRACTS,t,refracts,FOREVER); // refracts *= 0.01f; if ((RND01()<refracts)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colm->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } Point3 c2,c1; Point3 Vdirbase = Normalize(InVel); float q1 = DotProd(-Vdirbase,bnorm); float theta=(float)acos(q1); if (theta>=HalfPI) theta-=PI; c1 = Normalize((-InVel)^bnorm); c2=Normalize(bnorm^c1); Point3 Drag = friction*c2*DotProd(c2,-InVel); InVel *= decel*(1.0f-decelvar*RND01()); // rotate velocity vector float maxref,refangle,maxvarref; refangle = 0.0f; if (!FloatEQ0(refvol)) { if (refvol>0.0f) maxref = -theta; else maxref = HalfPI-theta; refangle = maxref*(float)fabs(refvol); float frefangle = (float)fabs(refangle); if (refvol>0.0f) maxvarref = HalfPI-theta-frefangle; else maxvarref = theta-frefangle; refangle += maxvarref*RND11()*refvar; Point3 c,d; if (theta<0.01f) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); d = Point3(xtmp,ytmp,ztmp); c = Normalize(InVel^d); } else { c = Normalize(bnorm^(-InVel)); } RotateOnePoint(InVel,&Zero.x,&c.x,refangle); TempDP = DotProd(InVel,bnorm); if (TempDP>0.0f) InVel = InVel - TempDP*bnorm; } float maxdiff,diffuse,diffvar,diffangle; obj->st->pbComplex->GetValue(PB_DIFFUSION,t,diffuse,FOREVER); // diffuse *= 0.01f; obj->st->pbComplex->GetValue(PB_DIFFUSIONVAR,t,diffvar,FOREVER); // diffvar *= 0.01f; maxdiff = HalfPI-theta-refangle; if (!FloatEQ0(diffuse)) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); Point3 d = Point3(xtmp,ytmp,ztmp); Point3 c = Normalize(InVel^d); diffangle = 0.5f*maxdiff*diffuse*(1.0f+RND11()*diffvar); RotateOnePoint(InVel,&Zero.x,&c.x,diffangle); TempDP = DotProd(InVel,bnorm); if (TempDP>0.0f) InVel = InVel - TempDP*bnorm; } float holddt = dt; dt -= at; inp = hitpoint; if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } // particle was neither reflected nor refracted nor tested for either! float spawnonly; obj->st->pbComplex->GetValue(PB_COLAFFECTS,t,spawnonly,FOREVER); // spawnonly *= 0.01f; if ((RND01()<spawnonly)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colm->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float passvel,passvelvar; obj->st->pbComplex->GetValue(PB_COLPASSVEL,t,passvel,FOREVER); obj->st->pbComplex->GetValue(PB_COLPASSVELVAR,t,passvelvar,FOREVER); // passvelvar *= 0.01f; InVel *= passvel*(1.0f+passvelvar*RND11()); float holddt = dt; dt -= at; inp = hitpoint; if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } } } // MESH COLLISION CODE BLOCK ENDS HERE break; } if (donewithparticle) { if (enableDynamics) { float mass = 0.001f; if (t==obj->ctime) { totalnumber += 1; totalforce += (SaveVel-InVel)*K*mass/stepsize; obj->ffdata.FlectForce += totalforce; obj->ffdata.ApplyAt = applyat; obj->ffdata.Num = totalnumber; } } obj->ReturnThreeStateValue = 1; obj->lastrnd = rand(); return TRUE; } else { obj->ReturnThreeStateValue = DONTCARE; obj->lastrnd=rand(); return FALSE; } } void BasicFlectorObj::InvalidateUI() { BasicFlectorPB.InvalidateUI(pblock2->LastNotifyParamID()); BasicFComplexPB.InvalidateUI(pbComplex->LastNotifyParamID()); } void BasicFlectorObj::BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev ) { this->ip = ip; if (flags & BEGIN_EDIT_CREATE) { creating = TRUE; } else { creating = FALSE; } SimpleWSMObject2::BeginEditParams(ip,flags,prev); if (!pmap[pbType_subani]) { pmap[pbType_subani] = CreateCPParamMap2(pblock2,ip,hInstance,MAKEINTRESOURCE(IDD_MF_0100_FLECTTYPESELECT),GetString(IDS_DLG_FTYPE),0); } pmap[pbType_subani]->SetUserDlgProc(new BasicFlectorTypeObjDlgProc(this)); pmap[pbType_subani]->SetParamBlock(GetParamBlockByID(pbType_subani)); int oldval; pblock2->GetValue(PB_TYPE,pbType_subani,oldval,FOREVER); if (!st->theParam[pbType_subani]) st->CreateMonoFlectorParamDlg(ip,oldval,pbType_subani); else st->pmap[pbType_subani]->SetParamBlock(st->GetParamBlockByID(pbType_subani)); if (!pmap[pbComplex_subani]) { pmap[pbComplex_subani] = CreateCPParamMap2(pbComplex,ip,hInstance,MAKEINTRESOURCE(IDD_MF_0200_FLECTCOMPLEXITYSELECT),GetString(IDS_DLG_FCOMPLEX),0); } pmap[pbComplex_subani]->SetUserDlgProc(new BasicFlectorComplexDlgProc(this)); pmap[pbComplex_subani]->SetParamBlock(GetParamBlockByID(pbComplex_subani)); pbComplex->GetValue(PB_COMPLEX,pbComplex_subani,oldval,FOREVER); if (!st->theParam[pbComplex_subani]) st->CreateMonoFlectorParamDlg(ip,oldval,pbComplex_subani); else st->pmap[pbComplex_subani]->SetParamBlock(st->GetParamBlockByID(pbComplex_subani)); } void Reinit(IParamMap2Ptr *pm,TimeValue t) { ParamBlockDesc2* pbd = (*pm)->GetDesc(); if (!(pbd->flags & P_CLASS_PARAMS)) for (int i = 0; i < pbd->count; i++) { ParamDef& pd = pbd->paramdefs[i]; if (!(pd.flags & P_RESET_DEFAULT)) switch (pd.type) { case TYPE_ANGLE: case TYPE_PCNT_FRAC: case TYPE_WORLD: case TYPE_COLOR_CHANNEL: case TYPE_FLOAT: pd.cur_def.f = (*pm)->GetParamBlock()->GetFloat(pd.ID, t); pd.flags |= P_HAS_CUR_DEFAULT; break; case TYPE_BOOL: case TYPE_TIMEVALUE: case TYPE_RADIOBTN_INDEX: case TYPE_INT: pd.cur_def.i = (*pm)->GetParamBlock()->GetInt(pd.ID, t); pd.flags |= P_HAS_CUR_DEFAULT; break; case TYPE_HSV: case TYPE_RGBA: case TYPE_POINT3: { if (pd.cur_def.p != NULL) delete pd.cur_def.p; pd.cur_def.p = new Point3((*pm)->GetParamBlock()->GetPoint3(pd.ID, t)); pd.flags |= P_HAS_CUR_DEFAULT; break; } case TYPE_STRING: { const TCHAR* s = (*pm)->GetParamBlock()->GetStr(pd.ID, t); if (s != NULL) { pd.cur_def.ReplaceString(s); pd.flags |= P_HAS_CUR_DEFAULT; } break; } case TYPE_FILENAME: { const TCHAR* s = (*pm)->GetParamBlock()->GetStr(pd.ID, t); if (s != NULL) { if (pd.cur_def.s != NULL) { MaxSDK::AssetManagement::IAssetManager::GetInstance()->ReleaseReference(pd.cur_def.s); } pd.cur_def.ReplaceString(s); if (s) MaxSDK::AssetManagement::IAssetManager::GetInstance()->AddReference(s); pd.flags |= P_HAS_CUR_DEFAULT; } break; } } } } void BasicFlectorObj::EndEditParams( IObjParam *ip, ULONG flags,Animatable *next ) { SimpleWSMObject2::EndEditParams(ip,flags,next); ip->ClearPickMode(); this->ip = NULL; if (flags & END_EDIT_REMOVEUI ) { if (pmap[pbType_subani]) { DestroyCPParamMap2(pmap[pbType_subani]); pmap[pbType_subani]=NULL; } if (pmap[pbComplex_subani]) { DestroyCPParamMap2(pmap[pbComplex_subani]); pmap[pbComplex_subani]=NULL; } } else { if (pmap[pbType_subani]) pmap[pbType_subani]->SetUserDlgProc(nullptr); if (pmap[pbComplex_subani]) pmap[pbComplex_subani]->SetUserDlgProc(nullptr); } creating=FALSE; } IOResult BasicFlectorObj::Save(ISave *isave) { isave->BeginChunk(MONODEF_CUSTNAME_CHUNK); isave->WriteWString(custname); isave->EndChunk(); return IO_OK; } class BasicFlectorObjLoad : public PostLoadCallback { public: BasicFlectorObj *n; BasicFlectorObjLoad(BasicFlectorObj *ns) {n = ns;} void proc(ILoad *iload) { ReferenceTarget *rt; Interval iv; n->pblock2->GetValue(monoflect_colliderp,0,rt,iv); if (rt == NULL) { CollisionPlane *colp = (CollisionPlane*)CreateInstance(REF_MAKER_CLASS_ID, PLANAR_COLLISION_ID); if (colp) n->pblock2->SetValue(monoflect_colliderp,0,(ReferenceTarget*)colp); } n->pblock2->GetValue(monoflect_colliders,0,rt,iv); if (rt == NULL) { CollisionSphere *cols = (CollisionSphere*)CreateInstance(REF_MAKER_CLASS_ID, SPHERICAL_COLLISION_ID); if (cols) n->pblock2->SetValue(monoflect_colliders,0,(ReferenceTarget*)cols); } n->pblock2->GetValue(monoflect_colliderm,0,rt,iv); if (rt == NULL) { CollisionMesh *colm = (CollisionMesh*)CreateInstance(REF_MAKER_CLASS_ID, MESH_COLLISION_ID); if (colm) n->pblock2->SetValue(monoflect_colliderm,0,(ReferenceTarget*)colm); } delete this; } }; IOResult BasicFlectorObj::Load(ILoad *iload) { IOResult res = IO_OK; // Default names custname = _T(" "); while (IO_OK==(res=iload->OpenChunk())) { switch (iload->CurChunkID()) { case MONODEF_CUSTNAME_CHUNK: { TCHAR *buf; res=iload->ReadWStringChunk(&buf); custname = TSTR(buf); break; } } iload->CloseChunk(); if (res!=IO_OK) return res; } iload->RegisterPostLoadCallback(new BasicFlectorObjLoad(this)); return IO_OK; } FlectForces BasicFlectorObj::ForceData(TimeValue t) { float ft1,ft2; pbComplex->GetValue(PB_TIMEON,t,ft1,FOREVER); pbComplex->GetValue(PB_TIMEOFF,t,ft2,FOREVER); ffdata.t1=ft1*GetTicksPerFrame();ffdata.t2=ft2*GetTicksPerFrame(); return ffdata; } RefTargetHandle BasicFlectorObj::Clone(RemapDir& remap) { BasicFlectorObj* newob = new BasicFlectorObj(); if (pblock2) newob->ReplaceReference(pbType_subani, remap.CloneRef(pblock2)); if (pbComplex) newob->ReplaceReference(pbComplex_subani, remap.CloneRef(pbComplex)); if (st) newob->ReplaceReference(monoflecdlg, remap.CloneRef(st)); // if (custnode) // newob->ReplaceReference(CUSTNODE,custnode); newob->custname=custname; newob->dmesh=NULL; newob->vnorms=NULL; newob->fnorms=NULL; newob->ivalid.SetEmpty(); BaseClone(this, newob, remap); return(newob); } BOOL BasicFlectorObj::OKtoDisplay(TimeValue t) { float size; st->pblock2->GetValue(PB_WIDTH,t,size,FOREVER); if (size==0.0f) return FALSE; else return TRUE; } /*int BasicFlectorObj::IntersectRay(TimeValue t, Ray& ray, float& at, Point3& norm) { // pass to SimpleObject to do this return SimpleWSMObject2::IntersectRay(t, ray, at, norm); }*/ int BasicFlectorObj::CanConvertToType(Class_ID obtype) { return FALSE; } int CreateBasicFlectorProc::createmethod( ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat) { if ( ! vpt || ! vpt->IsAlive() ) { // why are we here DbgAssert(!_T("Invalid viewport!")); return FALSE; } Point3 p1, center; DWORD snapdim = SNAP_IN_3D; if (msg == MOUSE_FREEMOVE) { vpt->SnapPreview(m, m, NULL, snapdim); } if (msg==MOUSE_POINT||msg==MOUSE_MOVE) { switch(point) { // point one - where we measure from case 0: GetCOREInterface()->SetHideByCategoryFlags( GetCOREInterface()->GetHideByCategoryFlags() & ~(HIDE_OBJECTS|HIDE_PARTICLES)); sp0 = m; p0 = vpt->SnapPoint(m, m, NULL, snapdim); BasicFlectorObject->st->pblock2->SetValue(PB_WIDTH,0,0.01f); BasicFlectorObject->st->pblock2->SetValue(PB_LENGTH,0,0.01f); p1 = p0 + Point3(.01,.01,.01); mat.SetTrans(float(.5)*(p0+p1)); BasicFlectorObject->st->pmap[pbType_subani]->Invalidate(); break; // point two - where we measure to in worldspace case 1: sp1 = m; p1 = vpt->SnapPoint(m, m, NULL, snapdim); p1.z = p0.z +(float).01; // if(flags&MOUSE_CTRL) // { mat.SetTrans(p0); // } // else mat.SetTrans(float(.5)*(p0+p1)); Point3 d = p1-p0; float len; if (fabs(d.x) > fabs(d.y)) len = d.x; else len = d.y; d.x = d.y = 2.0f * len; BasicFlectorObject->st->pblock2->SetValue(PB_WIDTH,0,(float)fabs(p1.x-p0.x)); BasicFlectorObject->st->pblock2->SetValue(PB_LENGTH,0,(float)fabs(p1.y-p0.y)); BasicFlectorObject->st->pmap[pbType_subani]->Invalidate(); if (msg==MOUSE_POINT) { if (Length(sp1-sp0)<3 || Length(d)<0.1f) return CREATE_ABORT; else { return CREATE_STOP; } } break; } } else { if (msg == MOUSE_ABORT) return CREATE_ABORT; } return TRUE; } BOOL BasicFlectorObj::SupportsDynamics() { int supportsdynamics; pbComplex->GetValue(PB_COMPLEX,0,supportsdynamics,ivalid); return (supportsdynamics>1); } void BasicFlectorObj::BuildMesh(TimeValue t) { int typeofdeflector; pblock2->GetValue(PB_TYPE,0,typeofdeflector,ivalid); float sz0,sz1; ivalid = FOREVER; st->pblock2->GetValue(PB_WIDTH,t,sz0,ivalid); sz0 *= 0.5f; st->pblock2->GetValue(PB_LENGTH,t,sz1,ivalid); sz1 *= 0.5f; switch(typeofdeflector) { case PLANAR: { float w, h; float w2,h2,h3,h4; ivalid = FOREVER; w = sz0; w2=w*0.5f; h = sz1; h2=h*0.5f; h3=h2*0.15f; h4=h2*0.25f; mesh.setNumVerts(19); mesh.setNumFaces(11); mesh.setVert(0, Point3(-w,-h, 0.0f)); mesh.setVert(1, Point3( w,-h, 0.0f)); mesh.setVert(2, Point3( w, h, 0.0f)); mesh.setVert(3, Point3(-w, h, 0.0f)); mesh.setVert( 4, Point3(0.0f,0.0f,0.0f)); mesh.setVert( 5, Point3(0.0f, h2, h2)); mesh.setVert( 6, Point3(0.0f, -h2, h2)); mesh.setVert( 7, Point3(0.0f, h2+h3, h2)); mesh.setVert( 8, Point3(0.0f, h2, h2+h3)); mesh.setVert( 9, Point3(0.0f, -h2, h2-h3)); mesh.setVert(10, Point3(0.0f, -h2+h3, h2)); mesh.setVert(11, Point3(0.0f, h4, 0.0f)); mesh.setVert(12, Point3(0.0f, h4, -h2)); mesh.setVert(13, Point3(0.0f, h4+h3, -h2)); mesh.setVert(14, Point3(0.0f, 0.0f, -h2-h3-h3)); mesh.setVert(15, Point3(0.0f,-h4-h3, -h2)); mesh.setVert(16, Point3(0.0f,-h4, -h2)); mesh.setVert(17, Point3(0.0f,-h4, 0.0f)); mesh.setVert(18, Point3(0.0f,0.0f,-h4)); mesh.faces[0].setEdgeVisFlags(1,1,0); mesh.faces[0].setSmGroup(1); mesh.faces[0].setVerts(0,1,2); mesh.faces[1].setEdgeVisFlags(1,1,0); mesh.faces[1].setSmGroup(1); mesh.faces[1].setVerts(2,3,0); mesh.faces[2].setEdgeVisFlags(1,0,1); mesh.faces[2].setSmGroup(1); mesh.faces[2].setVerts(4,6,5); mesh.faces[3].setEdgeVisFlags(1,0,1); mesh.faces[3].setSmGroup(1); mesh.faces[3].setVerts(6,9,10); mesh.faces[4].setEdgeVisFlags(1,0,1); mesh.faces[4].setSmGroup(1); mesh.faces[4].setVerts(5,8,7); mesh.faces[5].setEdgeVisFlags(1,0,1); mesh.faces[5].setSmGroup(1); mesh.faces[5].setVerts(11,12,18); mesh.faces[6].setEdgeVisFlags(0,0,0); mesh.faces[6].setSmGroup(1); mesh.faces[6].setVerts(12,16,18); mesh.faces[7].setEdgeVisFlags(1,1,0); mesh.faces[7].setSmGroup(1); mesh.faces[7].setVerts(16,17,18); mesh.faces[8].setEdgeVisFlags(1,1,0); mesh.faces[8].setSmGroup(1); mesh.faces[8].setVerts(12,13,14); mesh.faces[9].setEdgeVisFlags(0,0,0); mesh.faces[9].setSmGroup(1); mesh.faces[9].setVerts(12,14,16); mesh.faces[10].setEdgeVisFlags(1,1,0); mesh.faces[10].setSmGroup(1); mesh.faces[10].setVerts(14,15,16); mesh.InvalidateGeomCache(); return; } case SPHERE: { float r,r2,r3,r4,u; #define NUM_SEGS 24 r = 2.0f * sz0; r2=0.5f*r; r3=0.15f*r2; r4=0.25f*r2; mesh.setNumVerts(3*NUM_SEGS+16); mesh.setNumFaces(3*NUM_SEGS+9); for (int i=0; i<NUM_SEGS; i++) { u=float(i)/float(NUM_SEGS) * TWOPI; mesh.setVert(i, Point3((float)cos(u) * r, (float)sin(u) * r, 0.0f)); } for (int i=0; i<NUM_SEGS; i++) { u=float(i)/float(NUM_SEGS) * TWOPI; mesh.setVert(i+NUM_SEGS, Point3(0.0f, (float)cos(u) * r, (float)sin(u) * r)); } for (int i=0; i<NUM_SEGS; i++) { u=float(i)/float(NUM_SEGS) * TWOPI; mesh.setVert(i+2*NUM_SEGS, Point3((float)cos(u) * r, 0.0f, (float)sin(u) * r)); } mesh.setVert(72, Point3(0.0f,0.0f,0.0f)); mesh.setVert(73, Point3(0.0f,0.0f, r )); mesh.setVert(74, Point3(0.0f, r2 ,r+r2)); mesh.setVert(75, Point3(0.0f,-r2 ,r+r2)); mesh.setVert(76, Point3(0.0f, r2+r3,r+r2)); mesh.setVert(77, Point3(0.0f, r2,r+r2+r3)); mesh.setVert(78, Point3(0.0f,-r2,r+r2-r3)); mesh.setVert(79, Point3(0.0f,-r2+r3,r+r2)); mesh.setVert(80, Point3(0.0f, r4 ,-r )); mesh.setVert(81, Point3(0.0f, r4 ,-r-r2)); mesh.setVert(82, Point3(0.0f, r4+r3,-r-r2)); mesh.setVert(83, Point3(0.0f,0.0f ,-r-r2-r3-r3)); mesh.setVert(84, Point3(0.0f,-r4-r3,-r-r2)); mesh.setVert(85, Point3(0.0f,-r4 ,-r-r2)); mesh.setVert(86, Point3(0.0f,-r4 ,-r)); mesh.setVert(87, Point3(0.0f,0.0f ,-r-r4)); for (int i=0; i<3*NUM_SEGS; i++) { int i1 = i+1; if (i1%NUM_SEGS==0) i1 -= NUM_SEGS; mesh.faces[i].setEdgeVisFlags(1,0,0); mesh.faces[i].setSmGroup(1); mesh.faces[i].setVerts(i,i1,3*NUM_SEGS); } mesh.faces[72].setEdgeVisFlags(1,0,1); mesh.faces[72].setSmGroup(1); mesh.faces[72].setVerts(73,75,74); mesh.faces[73].setEdgeVisFlags(1,0,1); mesh.faces[73].setSmGroup(1); mesh.faces[73].setVerts(75,78,79); mesh.faces[74].setEdgeVisFlags(1,0,1); mesh.faces[74].setSmGroup(1); mesh.faces[74].setVerts(74,77,76); mesh.faces[75].setEdgeVisFlags(1,0,1); mesh.faces[75].setSmGroup(1); mesh.faces[75].setVerts(80,81,87); mesh.faces[76].setEdgeVisFlags(0,0,0); mesh.faces[76].setSmGroup(1); mesh.faces[76].setVerts(81,85,87); mesh.faces[77].setEdgeVisFlags(1,1,0); mesh.faces[77].setSmGroup(1); mesh.faces[77].setVerts(85,86,87); mesh.faces[78].setEdgeVisFlags(1,1,0); mesh.faces[78].setSmGroup(1); mesh.faces[78].setVerts(81,82,83); mesh.faces[79].setEdgeVisFlags(0,0,0); mesh.faces[79].setSmGroup(1); mesh.faces[79].setVerts(81,83,85); mesh.faces[80].setEdgeVisFlags(1,1,0); mesh.faces[80].setSmGroup(1); mesh.faces[80].setVerts(83,84,85); mesh.InvalidateGeomCache(); return; } case MESH: { int shouldIhide; st->pblock2->GetValue(PB_HIDEICON,0,shouldIhide,ivalid); if (shouldIhide) { mesh.setNumVerts(0); mesh.setNumFaces(0); mesh.InvalidateGeomCache(); return; } else { float l,h2,h3,h4; l = sz0; h2=l*0.5f; h3=h2*0.15f; h4=h2*0.25f; mesh.setNumVerts(23); mesh.setNumFaces(21); mesh.setVert(0,Point3( l, l, l)); mesh.setVert(1,Point3( l, l,-l)); mesh.setVert(2,Point3( l,-l, l)); mesh.setVert(3,Point3( l,-l,-l)); mesh.setVert(4,Point3(-l, l, l)); mesh.setVert(5,Point3(-l, l,-l)); mesh.setVert(6,Point3(-l,-l, l)); mesh.setVert(7,Point3(-l,-l,-l)); mesh.setVert( 8, Point3(0.0f,0.0f,l)); mesh.setVert( 9, Point3(0.0f, h2,l+h2)); mesh.setVert(10, Point3(0.0f, -h2,l+h2)); mesh.setVert(11, Point3(0.0f, h2+h3,l+h2)); mesh.setVert(12, Point3(0.0f, h2,l+h2+h3)); mesh.setVert(13, Point3(0.0f, -h2,l+h2-h3)); mesh.setVert(14, Point3(0.0f, -h2+h3,l+h2)); mesh.setVert(15, Point3(0.0f, h4, -l)); mesh.setVert(16, Point3(0.0f, h4, -h2-l)); mesh.setVert(17, Point3(0.0f, h4+h3, -h2-l)); mesh.setVert(18, Point3(0.0f, 0.0f, -h2-h3-h3-l)); mesh.setVert(19, Point3(0.0f,-h4-h3, -h2-l)); mesh.setVert(20, Point3(0.0f,-h4, -h2-l)); mesh.setVert(21, Point3(0.0f,-h4, -l)); mesh.setVert(22, Point3(0.0f,0.0f,-h4-l)); mesh.faces[0].setVerts(1,0,2); mesh.faces[0].setEdgeVisFlags(1,1,0); mesh.faces[0].setSmGroup(0); mesh.faces[1].setVerts(2,3,1); mesh.faces[1].setEdgeVisFlags(1,1,0); mesh.faces[1].setSmGroup(0); mesh.faces[2].setVerts(2,0,4); mesh.faces[2].setEdgeVisFlags(1,1,0); mesh.faces[2].setSmGroup(1); mesh.faces[3].setVerts(4,6,2); mesh.faces[3].setEdgeVisFlags(1,1,0); mesh.faces[3].setSmGroup(1); mesh.faces[4].setVerts(3,2,6); mesh.faces[4].setEdgeVisFlags(1,1,0); mesh.faces[4].setSmGroup(2); mesh.faces[5].setVerts(6,7,3); mesh.faces[5].setEdgeVisFlags(1,1,0); mesh.faces[5].setSmGroup(2); mesh.faces[6].setVerts(7,6,4); mesh.faces[6].setEdgeVisFlags(1,1,0); mesh.faces[6].setSmGroup(3); mesh.faces[7].setVerts(4,5,7); mesh.faces[7].setEdgeVisFlags(1,1,0); mesh.faces[7].setSmGroup(3); mesh.faces[8].setVerts(4,0,1); mesh.faces[8].setEdgeVisFlags(1,1,0); mesh.faces[8].setSmGroup(4); mesh.faces[9].setVerts(1,5,4); mesh.faces[9].setEdgeVisFlags(1,1,0); mesh.faces[9].setSmGroup(4); mesh.faces[10].setVerts(1,3,7); mesh.faces[10].setEdgeVisFlags(1,1,0); mesh.faces[10].setSmGroup(5); mesh.faces[11].setVerts(7,5,1); mesh.faces[11].setEdgeVisFlags(1,1,0); mesh.faces[11].setSmGroup(5); mesh.faces[12].setEdgeVisFlags(1,0,1); mesh.faces[12].setSmGroup(1); mesh.faces[12].setVerts(8,10,9); mesh.faces[13].setEdgeVisFlags(1,0,1); mesh.faces[13].setSmGroup(1); mesh.faces[13].setVerts(10,13,14); mesh.faces[14].setEdgeVisFlags(1,0,1); mesh.faces[14].setSmGroup(1); mesh.faces[14].setVerts(9,12,11); mesh.faces[15].setEdgeVisFlags(1,0,1); mesh.faces[15].setSmGroup(1); mesh.faces[15].setVerts(15,16,22); mesh.faces[16].setEdgeVisFlags(0,0,0); mesh.faces[16].setSmGroup(1); mesh.faces[16].setVerts(16,20,22); mesh.faces[17].setEdgeVisFlags(1,1,0); mesh.faces[17].setSmGroup(1); mesh.faces[17].setVerts(20,21,22); mesh.faces[18].setEdgeVisFlags(1,1,0); mesh.faces[18].setSmGroup(1); mesh.faces[18].setVerts(16,17,18); mesh.faces[19].setEdgeVisFlags(0,0,0); mesh.faces[19].setSmGroup(1); mesh.faces[19].setVerts(16,18,20); mesh.faces[20].setEdgeVisFlags(1,1,0); mesh.faces[20].setSmGroup(1); mesh.faces[20].setVerts(18,19,20); mesh.InvalidateGeomCache(); return; } } } } BOOL BasicFlectorObj::HasUVW() { BOOL genUVs = FALSE; // pblock2->GetValue(particlepodobj_genuv, 0, genUVs, FOREVER); return genUVs; } void BasicFlectorObj::SetGenUVW(BOOL sw) { if (sw==HasUVW()) return; // pblock2->SetValue(particlepodobj_genuv, 0, sw); } Animatable* BasicFlectorObj::SubAnim(int i) { switch(i) { // paramblock2s case pbType_subani: return pblock2; case pbComplex_subani: return pbComplex; case monoflecdlg: return st; default: return 0; } } void BasicFlectorObj::SetReference(int i, RefTargetHandle rtarg) { switch(i) { case pbType_subani: SimpleWSMObject2::SetReference(i, rtarg); break; case pbComplex_subani: pbComplex=(IParamBlock2*)rtarg; break; case monoflecdlg: st=(MonoFlector*)rtarg; break; } } RefTargetHandle BasicFlectorObj::GetReference(int i) { switch(i) { // paramblock2s case pbType_subani: return SimpleWSMObject2::GetReference(i); case pbComplex_subani: return pbComplex; case monoflecdlg: return st; default: return 0; } } TSTR BasicFlectorObj::SubAnimName(int i) { switch(i) { case pbType_subani: return GetString(IDS_DLG_FTYPE); case pbComplex_subani: return GetString(IDS_DLG_FCOMPLEX); case monoflecdlg: return GetString(IDS_DLG_MONOF); default: return _T(""); } } IParamBlock2* BasicFlectorObj::GetParamBlock(int i) { switch(i) { case pbType_subani: return pblock2; case pbComplex_subani: return pbComplex; default: return NULL; } } IParamBlock2* BasicFlectorObj::GetParamBlockByID(BlockID id) { if(pblock2->ID() == id) return pblock2; else if(pbComplex->ID() == id) return pbComplex; else return NULL; } RefResult BasicFlectorObj::NotifyRefChanged(const Interval& changeInt,RefTargetHandle hTarget, PartID& partID, RefMessage message, BOOL propagate ) { // switch (message) // { default: SimpleWSMObject2::NotifyRefChanged(changeInt,hTarget,partID,message,propagate); // } return REF_SUCCEED; } BasicFlectorMod::BasicFlectorMod(INode *node,BasicFlectorObj *obj) { ReplaceReference(SIMPWSMMOD_NODEREF,node); } Interval BasicFlectorMod::GetValidity(TimeValue t) { if (obRef && nodeRef) { Interval valid = FOREVER; Matrix3 tm; BasicFlectorObj *obj = (BasicFlectorObj*)GetWSMObject(t); tm = nodeRef->GetObjectTM(t,&valid); float TempT; obj->st->pbComplex->GetValue(PB_TIMEON,t,TempT,valid); obj->st->pbComplex->GetValue(PB_TIMEOFF,t,TempT,valid); float f; obj->st->pbComplex->GetValue(PB_REFLECTS,t,f,valid); obj->st->pbComplex->GetValue(PB_BOUNCE,t,f,valid); obj->st->pbComplex->GetValue(PB_BVAR,t,f,valid); obj->st->pbComplex->GetValue(PB_CHAOS,t,f,valid); obj->st->pbComplex->GetValue(PB_FRICTION,t,f,valid); obj->st->pbComplex->GetValue(PB_INHERVEL,t,f,valid); obj->st->pbComplex->GetValue(PB_REFRACTS,t,f,valid); obj->st->pbComplex->GetValue(PB_PASSVEL,t,f,valid); obj->st->pbComplex->GetValue(PB_PASSVELVAR,t,f,valid); obj->st->pbComplex->GetValue(PB_DISTORTION,t,f,valid); obj->st->pbComplex->GetValue(PB_DISTORTIONVAR,t,f,valid); obj->st->pbComplex->GetValue(PB_DIFFUSION,t,f,valid); obj->st->pbComplex->GetValue(PB_DIFFUSIONVAR,t,f,valid); obj->st->pbComplex->GetValue(PB_COLAFFECTS,t,f,valid); obj->st->pbComplex->GetValue(PB_COLPASSVEL,t,f,valid); obj->st->pbComplex->GetValue(PB_COLPASSVELVAR,t,f,valid); obj->st->pblock2->GetValue(PB_WIDTH,t,f,valid); obj->st->pblock2->GetValue(PB_LENGTH,t,f,valid); return valid; } else { return FOREVER; } } class BasicFlectorDeformer : public Deformer { public: Point3 Map(int i, Point3 p) {return p;} }; static BasicFlectorDeformer BasicFlectordeformer; Deformer& BasicFlectorMod::GetDeformer( TimeValue t,ModContext &mc,Matrix3& mat,Matrix3& invmat) { return BasicFlectordeformer; } RefTargetHandle BasicFlectorMod::Clone(RemapDir& remap) { BasicFlectorMod *newob = new BasicFlectorMod(nodeRef,(BasicFlectorObj*)obRef); newob->SimpleWSMModClone(this, remap); BaseClone(this, newob, remap); return newob; } void BasicFlectorMod::ModifyObject(TimeValue t, ModContext &mc, ObjectState *os, INode *node) { ParticleObject *obj = GetParticleInterface(os->obj); if (obj) { deflect.obj = (BasicFlectorObj*)GetWSMObject(t); deflect.node = nodeRef; if (deflect.obj) { deflect.obj->custnode = deflect.obj->st->pblock2->GetINode(PB_MESHNODE); deflect.obj->tmValid.SetEmpty(); deflect.obj->mValid.SetEmpty(); deflect.badmesh = (deflect.obj->custnode==NULL); if (t<=deflect.obj->t) deflect.obj->lastrnd = 12345; deflect.obj->t=t; deflect.obj->dvel = Zero; deflect.totalforce = Zero; deflect.applyat = Zero; deflect.totalnumber = 0; TimeValue tmpt = GetCOREInterface()->GetTime(); if (deflect.obj->ctime != tmpt) { deflect.obj->ctime = tmpt; deflect.obj->ffdata.FlectForce = deflect.totalforce; deflect.obj->ffdata.ApplyAt = deflect.applyat; deflect.obj->ffdata.Num = deflect.totalnumber; } obj->ApplyCollisionObject(&deflect); } } } CollisionObject *BasicFlectorObj::GetCollisionObject(INode *node) { BasicFlectorField *gf = new BasicFlectorField; gf->obj = this; gf->node = node; gf->obj->tmValid.SetEmpty(); return gf; } /* // Bayboro 9/18/01 void* BasicFlectorObj::GetInterface(ULONG id) { switch (id) { case I_NEWPARTTEST: return (ITestInterface*)this; } return Object::GetInterface(id); } */ // Bayboro 9/18/01 void BasicFlectorObj::SetUpModifier(TimeValue t,INode *node) { custnode = st->pblock2->GetINode(PB_MESHNODE); mf->deflect.obj = (BasicFlectorObj*)(mf->GetWSMObject(t)); mf->deflect.node = mf->nodeRef; // mf->deflect.obj->tmValid.SetEmpty(); // mf->deflect.obj->mValid.SetEmpty(); tmValid.SetEmpty(); mValid.SetEmpty(); mf->deflect.badmesh = (custnode==NULL); // if (t <= mf->deflect.obj->t) // mf->deflect.obj->lastrnd = 12345; mf->deflect.obj->t = t; mf->deflect.obj->dvel = Zero; mf->deflect.totalforce = Zero; mf->deflect.applyat = Zero; mf->deflect.totalnumber = 0; TimeValue tmpt = GetCOREInterface()->GetTime(); if (mf->deflect.obj->ctime != tmpt) { mf->deflect.obj->ctime = tmpt; mf->deflect.obj->ffdata.FlectForce = mf->deflect.totalforce; mf->deflect.obj->ffdata.ApplyAt = mf->deflect.applyat; mf->deflect.obj->ffdata.Num = mf->deflect.totalnumber; } } /* // Bayboro 9/18/01 int BasicFlectorObj::NPTestInterface(TimeValue t,BOOL UpdatePastCollide,ParticleData *part,float dt,INode *node,int index) { ReturnThreeStateValue = DONTCARE; if (!mf) mf = (BasicFlectorMod *)CreateWSMMod(node); SetUpModifier(t,node); float ct = 0; UpdatePastCollide = TRUE; mf->deflect.CheckCollision(t,part->position,part->velocity,dt,index,&ct,UpdatePastCollide); return (ReturnThreeStateValue); } */ // Bayboro 9/18/01
26.962949
183
0.674638
SOM-Firmwide
96f3a91b777a300e031c7123617be8c4982f9042
2,902
cc
C++
stapl_release/src/skeletons/memento.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/src/skeletons/memento.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/src/skeletons/memento.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #include <stapl/skeletons/executors/memento.hpp> namespace stapl { namespace skeletons { memento::memento() : callbacks(new internal_stack_t()) { } ////////////////////////////////////////////////////////////////////// /// @brief the front element of the memento stack at times needs to /// stays untouched until some criteria is met. The entities that can /// remain untouched are called lazy. This method checks if the /// element is lazy. /// /// @return true only if the element on top of the memento stack is /// lazy ////////////////////////////////////////////////////////////////////// bool memento::front_is_lazy() { return callbacks->front().is_lazy(); } std::size_t memento::size() const { return callbacks->size(); } bool memento::is_empty() { return callbacks->empty(); } void memento::pop() { stapl_assert(callbacks->size() > 0, "Pop is called on an empty memento stack"); callbacks->pop_front_and_dispose( skeletons_impl::memento_element_disposer()); } ////////////////////////////////////////////////////////////////////// /// @brief This method resumes the spawning process of the front /// element of the memento dequeue as long as there is nothing else to /// do and the front element is not lazy. If all the elements of the /// memento double-ended queue are already resumed and there is nothing /// else left to do nothing will be done. /// /// The skeleton manager which holds this memento stack will finish /// the spawning process if there is nothing left to spawn in this /// memento stack. /// /// @param ignore_lazyness if true, continue the spawning process even /// if the front element of the memento is lazy ////////////////////////////////////////////////////////////////////// void memento::resume(bool ignore_lazyness) { if ((ignore_lazyness || !this->front_is_lazy()) && !is_empty()) { auto&& f = callbacks->front(); //store f as f() may modify the memento this->pop_keep(); f(); skeletons_impl::memento_element_disposer()(&f); } } void memento::pop_keep() { stapl_assert(callbacks->size() > 0, "Pop is called on an empty memento stack"); callbacks->pop_front(); } void memento::push_back(element_type* element, bool is_lazy) { element->set_is_lazy(is_lazy); callbacks->push_back(*element); } void memento::push_front(element_type* element, bool is_lazy) { element->set_is_lazy(is_lazy); callbacks->push_front(*element); } } // namespace skeletons } // namespace stapl
29.612245
74
0.63439
parasol-ppl
96f88728b851258c268edfef31d14199305c1a94
114
hpp
C++
src/events/event_data_main_menu.hpp
sfod/quoridor
a82b045fcf26ada34b802895f097c955103fbc14
[ "MIT" ]
null
null
null
src/events/event_data_main_menu.hpp
sfod/quoridor
a82b045fcf26ada34b802895f097c955103fbc14
[ "MIT" ]
31
2015-03-24T10:07:37.000Z
2016-04-20T15:11:18.000Z
src/events/event_data_main_menu.hpp
sfod/quoridor
a82b045fcf26ada34b802895f097c955103fbc14
[ "MIT" ]
null
null
null
#pragma once #include "event_data.hpp" class EventData_MainMenu : public EventDataCRTP<EventData_MainMenu> { };
16.285714
69
0.789474
sfod
96fce3f353f8351594637a8bee987e5bd6d13d02
2,628
cpp
C++
WholesomeEngine/WholesomeEngine/ModuleRender.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
WholesomeEngine/WholesomeEngine/ModuleRender.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
WholesomeEngine/WholesomeEngine/ModuleRender.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
#include "ModuleRender.h" #include "VulkanLogicalDevice.h" #include <SDL2/SDL_vulkan.h> ModuleRender::ModuleRender() : Module(), vulkan_logic_device(std::make_unique<VulkanLogicalDevice>()) { DEBUG::LOG("CREATING MODULE RENDER", nullptr); } ModuleRender::~ModuleRender() { } ENGINE_STATUS ModuleRender::Init() { ENGINE_STATUS ret = ENGINE_STATUS::SUCCESS; VkResult result = VkResult::VK_SUCCESS; //Create Vulkan Instance if (event_recieved.has_value()) { if (result = vulkan_instance.CreateInstance(event_recieved.value().sdl_window); result == VK_ERROR_INCOMPATIBLE_DRIVER) { DEBUG::LOG("[ERROR] Creating Vulkan Instance Failure: COMPATIBLE DRIVER NOT FOUND", nullptr); ret = ENGINE_STATUS::FAIL; } else if (result != VkResult::VK_SUCCESS) { //Vicente ftw DEBUG::LOG("[ERROR] Creating Vulkan Instance Failure: unknown error", nullptr); ret = ENGINE_STATUS::FAIL; } } DEBUG::LOG("[SUCCESS] Creating Vulkan Instance Success", nullptr); //Optional event will have value if we have recieved the Surface creation event if (event_recieved.has_value()) { //Create Vulkan Surface Instance if (SDL_Vulkan_CreateSurface(const_cast<SDL_Window*>(event_recieved.value().sdl_window), vulkan_instance.GetInstance(), &vulkan_surface) != SDL_TRUE) { DEBUG::LOG("[ERROR] VULKAN SURFACE CREATION FAILURE: %", SDL_GetError()); } else DEBUG::LOG("[SUCCESS] SDL_Vulkan_CreateSurface successfully", nullptr); } //Init Physical Devices if (result = vulkan_instance.GetPhysicalDevices(); result != VK_SUCCESS) { DEBUG::LOG("[ERROR] Getting Physical Device Failure", nullptr); ret = ENGINE_STATUS::FAIL; } //Select physiscal Device if (result = vulkan_instance.SelectPhysicalDevice(vulkan_surface); result != VK_SUCCESS) { DEBUG::LOG("[ERROR] Selecting Physical Device Failure", nullptr); ret = ENGINE_STATUS::FAIL; } //Create Logical Device if (result = vulkan_logic_device->InitDevice(vulkan_instance); result != VK_SUCCESS) { DEBUG::LOG("[ERROR] Creating Logical Device Failure", nullptr); ret = ENGINE_STATUS::FAIL; } return ret; } ENGINE_STATUS ModuleRender::CleanUp() { DEBUG::LOG("...Cleaning Render...", nullptr); //Destroy Surface vkDestroySurfaceKHR(vulkan_instance.GetInstance(), vulkan_surface, nullptr); //Destroy device vulkan_logic_device->DestroyDevice(); //Destroy instance vulkan_instance.DestroyInstance(); return ENGINE_STATUS::SUCCESS; } void ModuleRender::OnEventRecieved(const WEWindowCreation& event_recieved) { //As I'm not gonna use the info of this event right now I store it this->event_recieved = event_recieved; }
27.663158
151
0.741248
HeladodePistacho
96fde3b7187eb6a6d4cc1b4ecc4a2f1fd0b2dcdc
1,410
cpp
C++
src/main.cpp
CP-Panizza/EventLoop2.0
1f9786c74ef56fd1c9d9f15f2d5d3aeac366db9d
[ "MIT" ]
null
null
null
src/main.cpp
CP-Panizza/EventLoop2.0
1f9786c74ef56fd1c9d9f15f2d5d3aeac366db9d
[ "MIT" ]
null
null
null
src/main.cpp
CP-Panizza/EventLoop2.0
1f9786c74ef56fd1c9d9f15f2d5d3aeac366db9d
[ "MIT" ]
null
null
null
#include <iostream> #include <string.h> #include <unistd.h> #include <fcntl.h> #include "../deps/EL/EventLoop.hpp" #include "../deps/socket/socket_header.h" #include "../utils/utils.h" #include "Service/Service.h" #define DEFAULT_HEART_CHECK_TIME 30 #define DEFAULT_PULL_DATA_TIME 20 int main() { /** * 读取并解析配置文件 */ auto conf = getConf("EL_SERVICE.conf"); std::string node_type, master_ip, node_name; node_type = conf.count("node_type") ? conf["node_type"] : "single"; NodeType type = node_type == "master" ? NodeType::Master : (node_type == "slave" ? NodeType::Slave : NodeType::Single); master_ip = conf.count("master_ip") ? conf["master_ip"] : ""; node_name = conf.count("node_name") ? conf["node_name"] : ""; int64_t heart_check_time = conf.count("heart_check") ? stringToNum<int64_t >(conf["heart_check"]) : DEFAULT_HEART_CHECK_TIME; int64_t pull_data_time = conf.count("pull_data_time") ? stringToNum<int64_t>(conf["pull_data_time"]) : DEFAULT_PULL_DATA_TIME; auto server = new Service; /** * 初始化eventloop,包括io事件,定时器事件 */ server->InitEL(); /** * 初始化socket,tcp,http */ server->InitSockets(); /** * 初始化http接口 */ server->initHttpServer(); /** * 构造配置项,依据配置启动相应的服务 */ server->ConfigAndRun(new Config(node_name, type, master_ip, heart_check_time, pull_data_time)); return 0; }
28.77551
130
0.655319
CP-Panizza
8c014f51a2cab44ee6711e258b41c8dcac4991fb
8,596
hpp
C++
src/control/modules/motion-control/PidMotionController.hpp
CollinAvidano/robocup-firmware
847900af9a4a4b3aef4b9aab494b75723b3e10a4
[ "Apache-2.0" ]
null
null
null
src/control/modules/motion-control/PidMotionController.hpp
CollinAvidano/robocup-firmware
847900af9a4a4b3aef4b9aab494b75723b3e10a4
[ "Apache-2.0" ]
null
null
null
src/control/modules/motion-control/PidMotionController.hpp
CollinAvidano/robocup-firmware
847900af9a4a4b3aef4b9aab494b75723b3e10a4
[ "Apache-2.0" ]
null
null
null
#pragma once #include <array> #include <rc-fshare/pid.hpp> #include <rc-fshare/robot_model.hpp> #include "FPGA.hpp" #include "MPU6050.h" #include "RobotDevices.hpp" /** * Robot controller that runs a PID loop on each of the four wheels. */ class PidMotionController { public: PidMotionController() : imu(shared_i2c, MPU6050_DEFAULT_ADDRESS), ax_offset(0), ay_offset(0), az_offset(0), gx_offset(0), gy_offset(0), gz_offset(0), ax(0), ay(0), az(0), gx(0), gy(0), gz(0), rotation(0), target_rotation(0), angular_vel(0), angle_hold(false) { setPidValues(1.0, 0, 0, 50, 0); rotation_pid.kp = 15; rotation_pid.ki = 0; rotation_pid.kd = 300; rotation_pid.setWindup(40); rotation_pid.derivAlpha = 0.0f; // 1 is all old, 0 is all new } // can't init gyro in constructor because i2c not fully up? void startGyro(int16_t ax, int16_t ay, int16_t az, int16_t gx, int16_t gy, int16_t gz) { imu.initialize(); // Thread::wait(100); imu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000); imu.setFullScaleAccelRange(MPU6050_ACCEL_FS_8); imu.setXAccelOffset(ax); imu.setYAccelOffset(ay); imu.setZAccelOffset(az); imu.setXGyroOffset(gx); imu.setYGyroOffset(gy); imu.setZGyroOffset(gz); } void setPidValues(float p, float i, float d, unsigned int windup, float derivAlpha) { for (Pid& ctl : _controllers) { ctl.kp = p; ctl.ki = i; ctl.kd = d; ctl.setWindup(windup); ctl.derivAlpha = derivAlpha; } } void updatePValues(float p) { for (Pid& ctl : _controllers) { ctl.kp = p; } } void updateIValues(float i) { for (Pid& ctl : _controllers) { ctl.ki = i; } } void updateDValues(float d) { for (Pid& ctl : _controllers) { ctl.kd = d; } } void setTargetVel(Eigen::Vector3f target) { _targetVel = target; } /** * Return the duty cycle values for the motors to drive at the target * velocity. * * @param encoderDeltas Encoder deltas for the four drive motors * @param dt Time in ms since the last calll to run() * * @return Duty cycle values for each of the 4 motors */ std::array<int16_t, 4> run(const std::array<int16_t, 4>& encoderDeltas, float dt, Eigen::Vector4d* errors = nullptr, Eigen::Vector4d* wheelVelsOut = nullptr, Eigen::Vector4d* targetWheelVelsOut = nullptr) { // update control targets // in the future, we can get the rotation angle soccer wants and // directly command that // as our target, or integrate the rotational velocities given to us to // create the target. // For now though, we only do an angle hold when soccer is not // commanding rotational velocities // (this should help with strafing quickly) // target_rotation += _targetVel[2] * dt; // get sensor data imu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); // convert sensor readings to mathematically valid values Eigen::Vector4d wheelVels; wheelVels << encoderDeltas[0], encoderDeltas[1], encoderDeltas[2], encoderDeltas[3]; wheelVels *= 2.0 * M_PI / ENC_TICKS_PER_TURN / dt; auto bot_vel = RobotModel::get().WheelToBot * wheelVels; // we have two redundent sensor measurements for rotation // 32.8 comes from data sheet, units are LSB / (deg/s) float ang_vel_gyro = (gz / 32.8f) * M_PI / 180.0f; float ang_vel_enc = bot_vel[2]; // printf("%f\r\n", ang_vel_enc); // std::printf("%f %f\r\n", ang_vel_gyro, ang_vel_enc); // perform sensor fusion // the higher this is, the more gyro measurements are used instead of // encoders float sensor_fuse_ratio = 1; float ang_vel_update = ang_vel_gyro * sensor_fuse_ratio + ang_vel_enc * (1 - sensor_fuse_ratio); // perform state update based on fused value, passed through a low // passed filter // so far noise on the gyro seems pretty minimal, that's why this filter // is off float alpha = 1.0; // 0->1 (higher means less filtering) angular_vel = (alpha * ang_vel_update + (1 - alpha) * angular_vel); // current rotation estimate rotation += angular_vel * dt; // printf("%f\r\n", rotation * 180.0f / M_PI); // velocity we are actually basing control off of, not the latest // command auto target_vel_act = _targetVel; // std::printf("%f\r\n", rot_error); const auto epsilon = 0.0001f; // soccer tells us to "halt" by sending 0 vel commands, we want to // freeze the // rotational controller too so bots dont' react when getting handled bool soccer_stop = (std::abs(target_vel_act[0]) < epsilon) && (std::abs(target_vel_act[1]) < epsilon); if (!soccer_stop && std::abs(target_vel_act[2]) < epsilon) { if (!angle_hold) { target_rotation = rotation; angle_hold = true; } // get the smallest difference between two angles float rot_error = target_rotation - rotation; while (rot_error < -M_PI) rot_error += 2 * M_PI; while (rot_error > M_PI) rot_error -= 2 * M_PI; target_vel_act[2] = rotation_pid.run(rot_error); } else { // let target_vel_act be exactly what soccer commanded angle_hold = false; } // conversion to commanded wheel velocities Eigen::Vector4d targetWheelVels = RobotModel::get().BotToWheel * target_vel_act.cast<double>(); if (targetWheelVelsOut) { *targetWheelVelsOut = targetWheelVels; } Eigen::Vector4d wheelVelErr = targetWheelVels - wheelVels; if (errors) { *errors = wheelVelErr; } if (wheelVelsOut) { *wheelVelsOut = wheelVels; } // Calculated by checking for slippage at max accel, and decreasing // appropriately // Binary search works really well in this case // Caution: This is dependent on the PID values so increasing the // agressiveness of that will change this double max_error = 3.134765625; double scale = 1; for (int i = 0; i < 4; i++) { if (abs(wheelVelErr[i]) > max_error) { scale = max(scale, abs(wheelVelErr[i]) / max_error); } } wheelVelErr /= scale; targetWheelVels = wheelVels + wheelVelErr; std::array<int16_t, 4> dutyCycles; for (int i = 0; i < 4; i++) { float dc = targetWheelVels[i] * RobotModel::get().DutyCycleMultiplier + copysign(4, targetWheelVels[i]); dc += _controllers[i].run(wheelVelErr[i]); if (std::abs(dc) > FPGA::MAX_DUTY_CYCLE) { // Limit to max duty cycle dc = copysign(FPGA::MAX_DUTY_CYCLE, dc); // Conditional integration indicating open loop control _controllers[i].set_saturated(true); } else { _controllers[i].set_saturated(false); } dutyCycles[i] = static_cast<int16_t>(dc); } return dutyCycles; } // 2048 ticks per turn. Theres is a 3:1 gear ratio between the motor and the // wheel. static const uint16_t ENC_TICKS_PER_TURN = 2048 * 3; private: /// controllers for each wheel std::array<Pid, 4> _controllers{}; Pid rotation_pid; Eigen::Vector3f _targetVel{}; MPU6050 imu; int ax_offset, ay_offset, az_offset, gx_offset, gy_offset, gz_offset; int16_t ax, ay, az, gx, gy, gz; float rotation; // state estimate for rotation // We want to preserve the interface of soccer commanding rotational // velocities // for now, so that requires us to have a separate estimate of soccer's // desired rotation float target_rotation; float angular_vel; bool angle_hold; };
32.315789
80
0.57201
CollinAvidano
8c0422bc0b394df7c14b4328c54ed9f928c1776c
4,990
hpp
C++
include/MixerSplitter.hpp
hidenorly/audioframework
764a164d651f58c6f99a817410aaead228a4d79e
[ "Apache-2.0" ]
null
null
null
include/MixerSplitter.hpp
hidenorly/audioframework
764a164d651f58c6f99a817410aaead228a4d79e
[ "Apache-2.0" ]
null
null
null
include/MixerSplitter.hpp
hidenorly/audioframework
764a164d651f58c6f99a817410aaead228a4d79e
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2021 hidenorly Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __MIXERSPLITTER_HPP__ #define __MIXERSPLITTER_HPP__ #include "Sink.hpp" #include "Pipe.hpp" #include "InterPipeBridge.hpp" #include "AudioFormat.hpp" #include "ThreadBase.hpp" #include "PipeMixer.hpp" #include <vector> #include <mutex> #include <atomic> #include <thread> #include <map> #include <memory> class MixerSplitter : public ThreadBase { public: class MapCondition { public: MapCondition(){}; virtual ~MapCondition(){}; virtual bool canHandle(AudioFormat srcFormat)=0; }; class MapAnyCondition : public MapCondition { public: MapAnyCondition():MapCondition(){}; virtual ~MapAnyCondition(){}; virtual bool canHandle(AudioFormat srcFormat){return true;}; }; class MapAnyCompressedCondition : public MapCondition { public: MapAnyCompressedCondition():MapCondition(){}; virtual ~MapAnyCompressedCondition(){}; virtual bool canHandle(AudioFormat srcFormat){return srcFormat.isEncodingCompressed();}; }; class MapAnyPcmCondition : public MapCondition { public: MapAnyPcmCondition():MapCondition(){}; virtual ~MapAnyPcmCondition(){}; virtual bool canHandle(AudioFormat srcFormat){return srcFormat.isEncodingPcm();}; }; protected: class SourceSinkMapper { public: std::shared_ptr<ISink> source; std::shared_ptr<ISink> sink; public: SourceSinkMapper(){}; SourceSinkMapper(std::shared_ptr<SourceSinkMapper> mapper):source(mapper->source),sink(mapper->sink){}; SourceSinkMapper(SourceSinkMapper& mapper):source(mapper.source),sink(mapper.sink){}; SourceSinkMapper(std::shared_ptr<ISink> srcSink, std::shared_ptr<ISink> dstSink):source(srcSink),sink(dstSink){}; virtual ~SourceSinkMapper(){}; }; class SourceSinkConditionMapper : public SourceSinkMapper { public: std::shared_ptr<MapCondition> condition; public: SourceSinkConditionMapper():SourceSinkMapper(){}; SourceSinkConditionMapper(std::shared_ptr<SourceSinkConditionMapper> mapper){ SourceSinkConditionMapper( mapper->source, mapper->sink, mapper->condition ); }; SourceSinkConditionMapper(SourceSinkConditionMapper& mapper){ SourceSinkConditionMapper( mapper.source, mapper.sink, mapper.condition ); }; SourceSinkConditionMapper(std::shared_ptr<ISink> srcSink, std::shared_ptr<ISink> dstSink, std::shared_ptr<MapCondition> argCondition):SourceSinkMapper(srcSink, dstSink), condition(argCondition){}; virtual ~SourceSinkConditionMapper(){}; }; protected: std::mutex mMutexSourceSink; std::vector<std::shared_ptr<ISink>> mpSinks; std::vector<std::shared_ptr<ISink>> mpSources; std::map<std::shared_ptr<ISink>, std::shared_ptr<AudioFormat>> mpSourceAudioFormats; std::map<std::shared_ptr<ISink>, std::weak_ptr<IPipe>> mpSourcePipes; std::vector<std::shared_ptr<SourceSinkConditionMapper>> mSourceSinkMapper; std::map<std::shared_ptr<ISink>, std::shared_ptr<PipeMixer>> mpMixers; std::atomic<bool> mbOnChanged; protected: virtual void process(void); virtual void unlockToStop(void); bool isSinkAvailableLocked(std::shared_ptr<ISink> pSink); bool isSourceAvailableLocked(std::shared_ptr<ISink> pSink); std::shared_ptr<SourceSinkConditionMapper> getSourceSinkMapperLocked(std::shared_ptr<ISink> pSource, std::shared_ptr<ISink> pSink); std::shared_ptr<SourceSinkMapper> getSourceSinkMapperLocked(std::shared_ptr<ISink> pSource); bool removeMapperLocked(std::shared_ptr<ISink> srcSink); bool isPipeRunningOrNotRegistered(std::shared_ptr<ISink> srcSink); bool isSituationChanged(void); public: MixerSplitter(); virtual ~MixerSplitter(); virtual std::vector<std::shared_ptr<ISink>> getAllOfSinks(void); virtual void attachSink(std::shared_ptr<ISink> pSink); virtual bool detachSink(std::shared_ptr<ISink> pSink); virtual std::vector<std::shared_ptr<ISink>> getAllOfSinkAdaptors(void); virtual std::shared_ptr<ISink> allocateSinkAdaptor(AudioFormat format = AudioFormat(), std::shared_ptr<IPipe> pPipe = nullptr); virtual bool releaseSinkAdaptor(std::shared_ptr<ISink> pSink); virtual bool conditionalMap(std::shared_ptr<ISink> srcSink, std::shared_ptr<ISink> dstSink, std::shared_ptr<MapCondition> conditions); virtual bool map(std::shared_ptr<ISink> srcSink, std::shared_ptr<ISink> dstSink); virtual bool unmap(std::shared_ptr<ISink> srcSink); virtual void dump(void); }; #endif /* __MIXSPLITTER_HPP__ */
37.238806
200
0.755311
hidenorly
8c043f05a9ad5aefd9c51302f83445567f85b19f
2,512
hxx
C++
opencascade/StepAP214_AppliedExternalIdentificationAssignment.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/StepAP214_AppliedExternalIdentificationAssignment.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/StepAP214_AppliedExternalIdentificationAssignment.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 2000-05-10 // Created by: Andrey BETENEV // Copyright (c) 2000-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepAP214_AppliedExternalIdentificationAssignment_HeaderFile #define _StepAP214_AppliedExternalIdentificationAssignment_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepAP214_HArray1OfExternalIdentificationItem.hxx> #include <StepBasic_ExternalIdentificationAssignment.hxx> class TCollection_HAsciiString; class StepBasic_IdentificationRole; class StepBasic_ExternalSource; class StepAP214_AppliedExternalIdentificationAssignment; DEFINE_STANDARD_HANDLE(StepAP214_AppliedExternalIdentificationAssignment, StepBasic_ExternalIdentificationAssignment) //! Representation of STEP entity AppliedExternalIdentificationAssignment class StepAP214_AppliedExternalIdentificationAssignment : public StepBasic_ExternalIdentificationAssignment { public: //! Empty constructor Standard_EXPORT StepAP214_AppliedExternalIdentificationAssignment(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aIdentificationAssignment_AssignedId, const Handle(StepBasic_IdentificationRole)& aIdentificationAssignment_Role, const Handle(StepBasic_ExternalSource)& aExternalIdentificationAssignment_Source, const Handle(StepAP214_HArray1OfExternalIdentificationItem)& aItems); //! Returns field Items Standard_EXPORT Handle(StepAP214_HArray1OfExternalIdentificationItem) Items() const; //! Set field Items Standard_EXPORT void SetItems (const Handle(StepAP214_HArray1OfExternalIdentificationItem)& Items); DEFINE_STANDARD_RTTIEXT(StepAP214_AppliedExternalIdentificationAssignment,StepBasic_ExternalIdentificationAssignment) protected: private: Handle(StepAP214_HArray1OfExternalIdentificationItem) theItems; }; #endif // _StepAP214_AppliedExternalIdentificationAssignment_HeaderFile
33.052632
334
0.841959
valgur
8c04536827b6cd7253ac2c9620a3e66ef580ce61
743
cpp
C++
modules/engine/src/Render/Shape/Cuboid.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
1
2016-11-12T02:43:29.000Z
2016-11-12T02:43:29.000Z
modules/engine/src/Render/Shape/Cuboid.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
modules/engine/src/Render/Shape/Cuboid.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
#include <randar/Render/Shape.hpp> randar::Geometry randar::cuboid( float width, float height, float depth, const randar::Palette& palette) { randar::Geometry geo; Vertex vert; float rw = width / 2.0f; float rh = height / 2.0f; float rd = depth / 2.0f; // Front faces. vert.color = palette.color(); vert.position.set(-rw, -rh, -rd); geo.append(vert); vert.position.set(rw, rh, -rd); geo.append(vert); vert.position.set(-rw, rh, -rd); geo.append(vert); vert.position.set(-rw, -rh, -rd); geo.append(vert); vert.position.set(rw, -rh, -rd); geo.append(vert); vert.position.set(rw, rh, -rd); geo.append(vert); // Back faces. return geo; }
19.051282
37
0.585464
litty-studios
8c0680ec2084903e6148d1e00d79894413a00246
708
cpp
C++
dds/InfoRepo/FederationId.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
dds/InfoRepo/FederationId.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
dds/InfoRepo/FederationId.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
/* * $Id: FederationId.cpp 6240 2014-06-04 16:54:28Z johnsonb $ * * * Distributed under the OpenDDS License. * See: http://www.opendds.org/license.html */ #include "DcpsInfo_pch.h" #include "FederationId.h" TAO_DDS_DCPSFederationId::TAO_DDS_DCPSFederationId(RepoKey initId) : id_(initId) , overridden_(false) { } void TAO_DDS_DCPSFederationId::id(RepoKey fedId) { this->id_ = fedId; this->overridden_ = true; } TAO_DDS_DCPSFederationId::RepoKey TAO_DDS_DCPSFederationId::id() const { return this->id_; } /* void TAO_DDS_DCPSFederationId::overridden(bool overrideId) { this->overridden_ = overrideId; }*/ bool TAO_DDS_DCPSFederationId::overridden() const { return this->overridden_; }
15.733333
66
0.738701
binary42
8c076bb1dcc30a6ef07be1b58b7d4608d8839627
26,180
cpp
C++
TommyGun/Plugins/Common/ZXPlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/Plugins/Common/ZXPlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/Plugins/Common/ZXPlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
/*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #ifdef BUILDING_CORE #include "core_pch.h" #else #include "pch.h" #endif #pragma hdrstop //--------------------------------------------------------------------------- using namespace Scorpio; using namespace Plugin; using namespace Logging; //--------------------------------------------------------------------------- const int g_iNotFound = -1; //--------------------------------------------------------------------------- __fastcall ZXPlugin::ZXPlugin(const String& sFilename, ZXPluginManager* PluginManager) : m_PluginManager(PluginManager) , m_iLoadOrder(-1) , m_sFileName(sFilename) , m_sDescription("") , m_sComments("") , m_sProductVersion("Unknown") , m_sFileVersion("Unknown") , m_sInternalName("Unknown") , m_sVendor("Unknown") , m_sParentSignature("") , m_bLoaded(false) , m_bDoNotLoad(false) , m_bUnloading(false) , m_bInitialized(false) , m_bExceptionCaught(false) , m_hInstance(NULL) , m_hParentInstance(NULL) , m_NotifyFunc(NULL) , m_ReleaseFunc(NULL) , m_ModuleAddress(0) , m_dwModuleSize(0) , m_dwVersion(0) , m_dwFlags(0) , m_dwInterface(0) , m_Icon(NULL) { } //--------------------------------------------------------------------------- __fastcall ZXPlugin::~ZXPlugin() { // unload the plugin if it hasn't already been done if (true == m_bLoaded) { Unload(); } // reset some member variables just in case m_ModuleAddress = NULL; m_bInitialized = false; m_bUnloading = false; m_bLoaded = false; m_sFileName = ""; } //--------------------------------------------------------------------------- // Load /** * Loads a plugin into memory and initializes it if required * @param GetModuleInformation the pointer to the GetModuleInformation function in PSAPI.dll * @return S_OK if loaded successful, else E_FAIL if failed to load * @author Tony Thompson * @date Last Modified 30 October 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::Load(GetModuleInformationPtr GetModuleInformation) { HRESULT hResult = E_FAIL; bool bFreeLibrary = false; // try to load the DLL String DllPath = ExtractFilePath(Application->ExeName) + String("Plugins\\") + m_sFileName; HINSTANCE hInstance = NULL; ZX_LOG_INFO(lfPlugin, "Loading Plugin: " + DllPath); DWORD dwStartTime = timeGetTime(); try { hInstance = LoadLibrary(DllPath.c_str()); // get the details of the module if (NULL != hInstance) { MODULEINFO ModuleInfo; ModuleInfo.lpBaseOfDll = hInstance; ModuleInfo.SizeOfImage = 0; ModuleInfo.EntryPoint = 0; DWORD SizeOfModuleInfo = sizeof(ModuleInfo); HANDLE hProcess = GetCurrentProcess(); if (true == SAFE_CODE_PTR(GetModuleInformation) && GetModuleInformation(hProcess, hInstance, &ModuleInfo, SizeOfModuleInfo)) { m_dwModuleSize = ModuleInfo.SizeOfImage; } else { m_dwModuleSize = 0; } m_ModuleAddress = hInstance; } else { DWORD dwErrorCode = GetLastError(); ZXMessageBox MessageBox; MessageBox.ShowWindowsErrorMessage("LoadLibrary Failed: " + DllPath, dwErrorCode, __FILE__, __FUNC__, __LINE__); ZX_LOG_ERROR(lfPlugin, "LoadLibrary Error: " + IntToStr(dwErrorCode)); } } catch(...) { ZX_LOG_EXCEPTION(lfException, m_sFileName + "caused an exception while try to load the DLL"); hInstance = NULL; } if (NULL != hInstance) { m_hInstance = hInstance; // Get Plugin file version details hResult = GetPluginVersionInfo(); if (S_OK == hResult) { // We have version info in the file, so check the // interface version and initialise functions from the loaded DLL if ((m_sParentSignature == "" && S_OK == CheckInterfaceRequirements()) || (m_sParentSignature != "" && S_OK == CheckPluginSignature(m_sParentSignature))) { InitialisePtr InitialiseFunc = NULL; InitialiseFunc = reinterpret_cast<InitialisePtr>(GetProcAddress(hInstance, "Initialise")); // Do we have a valid initialise function to call? if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(InitialiseFunc))) { // NOTE: It is not important that we check the LastError value if the GetProcAddresses fail. This maybe because // the dll we are trying to load is not a valid plugin, there maybe other programs out there that use the same // extension we do. Thus we can only assume a valid plugin, if all functions are satisfied. m_NotifyFunc = reinterpret_cast<NotifyPtr> (GetProcAddress(hInstance, "Notify")); m_ReleaseFunc = reinterpret_cast<ReleasePtr>(GetProcAddress(hInstance, "Release")); // Are all the functions required, present? if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(m_NotifyFunc )) && FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(m_ReleaseFunc))) { // yes, the DLL is valid. m_bLoaded = true; hResult = S_OK; // does the plugin have a flags function? FlagsPtr FlagsFunc = reinterpret_cast<FlagsPtr> (GetProcAddress(hInstance, "Flags")); DWORD Flags = 0L; if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(FlagsFunc))) { if (S_FALSE == FlagsFunc(Flags)) { Flags = 0L; } if (FLAG_IsNotUnloadable == (Flags & FLAG_IsNotUnloadable)) { // must always load this plugin m_bDoNotLoad = false; } } m_dwFlags = Flags; // Does the user want us to load the plugin, or do we have to load it because it has to be loaded if (false == m_bDoNotLoad) { bool bExceptionCaught = false; try { m_bLoaded = false; hResult = S_FALSE; // initialize the loaded DLL if (S_OK != InitialiseFunc(this)) { // failed to initialize do not load next time ZX_LOG_ERROR(lfPlugin, "Failed to Initialize Plugin: " + m_sFileName); m_bExceptionCaught = true; m_bDoNotLoad = true; bFreeLibrary = true; } else { m_bLoaded = true; hResult = S_OK; // set the default icon for the plugin if the plugin hasn't already done so in initialize #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->AddPluginIcon(m_hInstance, NULL, m_sDescription); } #endif ZX_LOG_INFO(lfPlugin, "Initialized Plugin: " + m_sFileName); m_bInitialized = true; } } catch(...) { bExceptionCaught = true; ZX_LOG_EXCEPTION(lfException, m_sFileName + " caused an exception during Initialization") } if (true == bExceptionCaught) { // plugin caused an exception during initialization, so unload it m_bExceptionCaught = true; m_bDoNotLoad = true; bFreeLibrary = true; hResult = S_FALSE; } } else { ZX_LOG_WARNING(lfPlugin, "Instructed not to load Plugin: " + m_sFileName); m_bLoaded = true; bFreeLibrary = false; } } else { ZX_LOG_WARNING(lfPlugin, "The File " + m_sFileName + " may not be a TommyGun Plugin"); } } else { ZX_LOG_WARNING(lfPlugin, "The File " + m_sFileName + " may not be a TommyGun Plugin"); } } else { ZX_LOG_ERROR(lfPlugin, "The File " + m_sFileName + " is incompatible with this version of the Framework"); // report that we tried to load a plugin but its interface requirements where incorrect! String Msg = "Failed to Load Plugin: " + m_sFileName; #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->ShowGeneralMessage(Msg, "Incompatible Interface Requirements", __FILE__, __FUNC__, __LINE__); } #endif m_bLoaded = true; Unload(); m_bDoNotLoad = true; bFreeLibrary = false; hResult = S_FALSE; } } else { ZX_LOG_ERROR(lfPlugin, "Plugin " + m_sFileName + " has no Version Info and its interface requirements cannot be validated"); } if (S_FALSE == hResult || true == bFreeLibrary) { ZX_LOG_INFO(lfPlugin, "Unloading " + m_sFileName + " due to error while Loading and Initializing") m_ReleaseFunc = NULL; m_NotifyFunc = NULL; Unload(); } } else { // we failed to load a suspected plugin. ZX_LOG_ERROR(lfPlugin, "LoadLibrary FAILED on the file " + m_sFileName); } DWORD dwEndTime = timeGetTime(); ZX_LOG_INFO(lfPlugin, "Loading took " + IntToStr(dwEndTime - dwStartTime) + "ms for " + m_sFileName); return hResult; } //--------------------------------------------------------------------------- // Unload /** * Unloads a plugin its resources and the dll * @param GetModuleInformation the pointer to the GetModuleInformation function in PSAPI.dll * @return S_OK if loaded successful, else E_FAIL if failed to load * @author Tony Thompson * @date Last Modified 30 October 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::Unload(bool bFreeOptions) { RL_HRESULT(E_FAIL); // clear the events m_Events.clear(); if (true == m_bLoaded) { DWORD dwStartTime = timeGetTime(); try { ZX_LOG_WARNING(lfPlugin, "Unloading Plugin " + m_sFileName); m_bUnloading = true; // release the plugin resources if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(m_ReleaseFunc)) && true == m_bInitialized) { try { m_ReleaseFunc(); } catch(...) { ZX_LOG_EXCEPTION(lfException, m_sFileName + " caused an exception during Release()") ZX_LOG_ERROR(lfPlugin, "Unable to Release Plugin: " + m_sFileName + " due to an exception"); m_bExceptionCaught = true; m_ReleaseFunc = NULL; } } else { ZX_LOG_ERROR(lfPlugin, "No Release function or Plugin is not initialized [" + m_sFileName + "]"); } } __finally { // free the DLL if (NULL != m_hInstance) { #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->Free(m_hInstance, bFreeOptions); } #endif if (FALSE == FreeLibrary(m_hInstance)) { // failed to free the DLL ZX_LOG_ERROR(lfPlugin, "Failed to Unload the DLL of the Plugin: " + m_sFileName); } else { ZX_LOG_INFO(lfPlugin, "Successfully Unloaded the DLL of the Plugin: " + m_sFileName); hResult = S_OK; } m_hInstance = NULL; m_bLoaded = false; } } DWORD dwEndTime = timeGetTime(); ZX_LOG_INFO(lfPlugin, "Unloading took " + IntToStr(dwEndTime - dwStartTime) + "ms for " + m_sFileName); } return hResult; } //--------------------------------------------------------------------------- // GetPluginVersionInfo /** * Gets the File Version information for the plugin file * @param PluginIt The plugin iterator * @return HRESULT S_OK information retrieved, else failed * @author Tony Thompson * @date Created 12 March 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::GetPluginVersionInfo(void) { HRESULT hResult = E_FAIL; // get the detals of the plugin String DllPath = ExtractFilePath(Application->ExeName) + "Plugins\\" + m_sFileName; KFileInfo* FileInfo = NULL; try { FileInfo = new KFileInfo(NULL); } catch(EOutOfMemory&) { ZX_LOG_EXCEPTION(lfException, "Failed to create the FileInfo object") FileInfo = NULL; } if (true == SAFE_PTR(FileInfo)) { FileInfo->FileName = DllPath; if (true == FileInfo->FileInfoValid) { m_sDescription = FileInfo->FileDescription; m_sComments = FileInfo->Comments; m_sVendor = FileInfo->CompanyName; m_sFileVersion = FileInfo->FileVersion; m_sProductVersion = FileInfo->ProductVersion; m_sInternalName = FileInfo->InternalName; hResult = S_OK; } SAFE_DELETE(FileInfo); } return hResult; } //--------------------------------------------------------------------------- // CheckInterfaceRequirements /** * Checks the Plugin Interface Requirements can be met by Core.dll * @param PluginIt The plugin iterator * @return HRESULT S_OK Requirements can be met * @author Tony Thompson * @date Created 12 March 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::CheckInterfaceRequirements(void) { HRESULT hResult = E_FAIL; // convert the product version string to a major and minor number int iDotPos = m_sProductVersion.Pos('.'); ZX_LOG_INFO(lfPlugin, m_sFileName + ", Version: " + m_sProductVersion); if (0 != iDotPos) { AnsiString sMajor = m_sProductVersion.SubString(1, iDotPos - 1); String sProductVersion = m_sProductVersion.SubString(iDotPos + 1, m_sProductVersion.Length()); iDotPos = sProductVersion.Pos('.'); if (0 != iDotPos) { AnsiString sMinor = sProductVersion.SubString(1, iDotPos - 1); int iMajor = 0; int iMinor = 0; iMajor = StrToInt(sMajor); iMinor = StrToInt(sMinor); WORD iVersion = (iMajor << 8) | iMinor; // check the requirements of the plugin against the cores functionality if (g_dwCoreInterfaceVersion >= iVersion && iVersion >= g_dwCompatibleBaseVersion) { hResult = S_OK; } } } return hResult; } //--------------------------------------------------------------------------- // ReadLoadOrder /** * Reads a plugin loading information from the registry * @param NextAvailableLoadOrder the next available load order id to use * @author Tony Thompson * @date Created 22 September 2003 */ //--------------------------------------------------------------------------- void __fastcall ZXPlugin::ReadLoadOrder(unsigned int& NextAvailableLoadOrder) { // assume the plugin has no load order defined int iLoadOrder = g_iNotFound; // reset the plugin flags to zero m_dwFlags = 0L; // try to read a load order from the registry #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager) && true == m_PluginManager->GuiManager->Registry()->Read("Plugins", m_sFileName, iLoadOrder)) { // plugin is known, and an order has been given bool bDoNotLoad; m_iLoadOrder = iLoadOrder; // does it have a DoNotLoad entry if (true == m_PluginManager->GuiManager->Registry()->Read("Plugins", "DNL_" + m_sFileName, bDoNotLoad)) { // yes, assign the DNL value m_bDoNotLoad = bDoNotLoad; if (true == bDoNotLoad) ZX_LOG_INFO(lfPlugin, m_sFileName + " is set NOT to load") } else { // DNL is false by default m_bDoNotLoad = false; } } else { // this is a new plugin, make it welcome and give it a load order m_iLoadOrder = NextAvailableLoadOrder; m_bDoNotLoad = false; ++NextAvailableLoadOrder; } #endif } //--------------------------------------------------------------------------- // AddToOptions /** * Adds a plugin to the options dialog * @param iNewLoadOrder the new load order of the plugin * @author Tony Thompson * @date Created 22 September 2003 */ //--------------------------------------------------------------------------- void __fastcall ZXPlugin::AddToOptions(int iNewLoadOrder) { m_iLoadOrder = iNewLoadOrder; #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->Registry()->Write("Plugins", m_sFileName, (int)m_iLoadOrder); m_PluginManager->GuiManager->Registry()->Write("Plugins", "DNL_" + m_sFileName, m_bDoNotLoad); m_PluginManager->GuiManager->OptionsPluginsAdd(m_hInstance, m_sDescription, m_sFileName, m_sVendor, m_sProductVersion, m_sFileVersion, (FLAG_IsNotUnloadable != (m_dwFlags & FLAG_IsNotUnloadable)), m_bDoNotLoad, FLAG_IsNotVisibleInOptionsPage == (m_dwFlags & FLAG_IsNotVisibleInOptionsPage), m_dwFlags & FLAG_PluginLoadPriorityMask, m_iLoadOrder, m_Icon ); } #endif } //--------------------------------------------------------------------------- bool __fastcall ZXPlugin::InterestedInEvent(TZX_EVENT Event) { return std::find(m_Events.begin(), m_Events.end(), Event) != m_Events.end(); } //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::NotifyEvent(TZX_EVENT Event, LPDATA lpData, DWORD Param, DWORD Arg) { RL_HRESULT(S_FALSE); if (true == InterestedInEvent(Event)) { try { if (true == SAFE_CODE_PTR(m_NotifyFunc)) { hResult = m_NotifyFunc(Event, lpData, Param, Arg); } else { ZX_LOG_ERROR(lfPlugin, m_sFileName + " has an invalid NotifyFunc pointer") } } catch(...) { // plugin caused an exception m_bExceptionCaught = true; ZX_LOG_EXCEPTION(lfException, m_sFileName + " caused an exception while processing NotifyEvent with message 0x" + IntToHex(Event, 8)) // unload the plugin due to exception Unload(); #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->ShowMessage(mbtError, "Plugin has caused an Exception", "A plugin has exploded in a heap and crashed", "Plugin: " + m_sDescription + "\n\nThis plugin has caused a fault and as such has been booted out of the TommyGun environment for being a naughty little plugin.\n\nPlease send the exception.log and plugin.log files to KiwiWare.", "OK", "", "" ); } #endif } } return hResult; } //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::RegisterEvent(TZX_EVENT Event) { RL_HRESULT(E_FAIL); // find the event (or lack of it) if (m_Events.end() == std::find(m_Events.begin(), m_Events.end(), Event)) { // register the event m_Events.push_back(Event); hResult = S_OK; } else { // event already registered hResult = S_FALSE; } return hResult; } //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::UnRegisterEvent(TZX_EVENT Event) { RL_HRESULT(E_FAIL); ZXEventsIterator EventsIt = std::find(m_Events.begin(), m_Events.end(), Event); if (m_Events.end() != EventsIt) { // unregister the event m_Events.erase(EventsIt); hResult = S_OK; } else { // event already unregistered hResult = S_FALSE; } return hResult; } //--------------------------------------------------------------------------- bool __fastcall ZXPlugin::OwnsMemory(void *Address) { DWORD dwAddress = (DWORD)Address; DWORD dwModule = (DWORD)m_ModuleAddress; return (dwModule <= dwAddress && dwAddress <= dwModule + m_dwModuleSize); } //--------------------------------------------------------------------------- // CheckPluginSignature /** * Checks the Plugin Interface Requirements can be met by Core.dll * @param PluginIt The plugin iterator * @return HRESULT S_OK Requirements can be met * @author Tony Thompson * @date Created 12 March 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::CheckPluginSignature(String sRequiredSignature) { HRESULT hResult = E_FAIL; String sSignature = ""; SignaturePtr SignatureFunc = reinterpret_cast<SignaturePtr>(GetProcAddress(Handle, "Signature")); if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(SignatureFunc))) { if (S_OK != SignatureFunc(sSignature)) { sSignature = ""; } if (sRequiredSignature == sSignature) { hResult = S_OK; } } m_sParentSignature = sSignature; // convert the product version string to a major and minor number /*int iDotPos = m_sProductVersion.Pos('.'); ZX_LOG_INFO(lfPlugin, m_sFileName + ", Version: " + m_sProductVersion); if (0 != iDotPos) { AnsiString sMajor = m_sProductVersion.SubString(1, iDotPos - 1); String sProductVersion = m_sProductVersion.SubString(iDotPos + 1, m_sProductVersion.Length()); iDotPos = sProductVersion.Pos('.'); if (0 != iDotPos) { AnsiString sMinor = sProductVersion.SubString(1, iDotPos - 1); int iMajor = 0; int iMinor = 0; iMajor = StrToInt(sMajor); iMinor = StrToInt(sMinor); WORD iVersion = (iMajor << 8) | iMinor; // check the requirements of the plugin against the cores functionality if (g_dwCoreInterfaceVersion >= iVersion && iVersion >= g_dwCompatibleBaseVersion) { hResult = S_OK; } } }*/ return hResult; } //---------------------------------------------------------------------------
40.463679
270
0.48793
tonyt73
8c07da3fe4b50973e03618f2de87c2ac0e99eb98
680
cpp
C++
base/5class4friend.cpp
chenliangold4j/beBetter
e30b66c6c8def4c65e0de9364cd9199558ea3253
[ "Apache-2.0" ]
null
null
null
base/5class4friend.cpp
chenliangold4j/beBetter
e30b66c6c8def4c65e0de9364cd9199558ea3253
[ "Apache-2.0" ]
null
null
null
base/5class4friend.cpp
chenliangold4j/beBetter
e30b66c6c8def4c65e0de9364cd9199558ea3253
[ "Apache-2.0" ]
null
null
null
#include <iostream> // 类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。 // 友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元。 using namespace std; class Box { double width; public: friend void printWidth( Box box ); void setWidth( double wid ); }; // 成员函数定义 void Box::setWidth( double wid ) { width = wid; } // 请注意:printWidth() 不是任何类的成员函数 void printWidth( Box box ) { /* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */ cout << "Width of box : " << box.width <<endl; } // 程序的主函数 int main( ) { Box box; // 使用成员函数设置宽度 box.setWidth(10.0); // 使用友元函数输出宽度 printWidth( box ); return 0; }
17
91
0.663235
chenliangold4j
8c0a9cd2062d826b977614b57fe2acfe61bef795
2,220
cpp
C++
inetsrv/msmq/src/admin/mqsnap/msgsndr.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/msmq/src/admin/mqsnap/msgsndr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/msmq/src/admin/mqsnap/msgsndr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// msgsndr.cpp : implementation file // #include "stdafx.h" #include "mqsnap.h" #include "resource.h" #include "mqPPage.h" #include "msgsndr.h" #include "msgsndr.tmh" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMessageSenderPage property page IMPLEMENT_DYNCREATE(CMessageSenderPage, CMqPropertyPage) CMessageSenderPage::CMessageSenderPage() : CMqPropertyPage(CMessageSenderPage::IDD) { //{{AFX_DATA_INIT(CMessageSenderPage) m_szAuthenticated = _T(""); m_szEncrypt = _T(""); m_szEncryptAlg = _T(""); m_szHashAlg = _T(""); m_szGuid = _T(""); m_szPathName = _T(""); m_szSid = _T(""); m_szUser = _T(""); //}}AFX_DATA_INIT } CMessageSenderPage::~CMessageSenderPage() { } void CMessageSenderPage::DoDataExchange(CDataExchange* pDX) { CMqPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMessageSenderPage) DDX_Text(pDX, IDC_MSGAUTHENTICATED, m_szAuthenticated); DDX_Text(pDX, IDC_MSGENCRYPT, m_szEncrypt); DDX_Text(pDX, IDC_MSGENCRYPTALG, m_szEncryptAlg); DDX_Text(pDX, IDC_MSGHASHALG, m_szHashAlg); DDX_Text(pDX, IDC_MSGGUID, m_szGuid); DDX_Text(pDX, IDC_MSGPATHNAME, m_szPathName); DDX_Text(pDX, IDC_MSGSID, m_szSid); DDX_Text(pDX, IDC_MSGUSER, m_szUser); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMessageSenderPage, CMqPropertyPage) //{{AFX_MSG_MAP(CMessageSenderPage) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMessageSenderPage message handlers BOOL CMessageSenderPage::OnInitDialog() { // // PATCH!!!! // Defining this method to override the default OnInitDialog of // CMqPropertyPage, because it asserts. // // This function must be in the context of MMC.EXE so dont // put an "AFX_MANAGE_STATE(AfxGetStaticModuleState());" unless // it is bracketted inside a {....} statement. // // UpdateData( FALSE ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
26.117647
84
0.647297
npocmaka
8c0f4a16c4ad021c7425668ee79e817ec0537b17
4,186
hpp
C++
TBDAnnotation/src/Model/CustomPermutation.hpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
1
2021-06-13T10:49:43.000Z
2021-06-13T10:49:43.000Z
TBDAnnotation/src/Model/CustomPermutation.hpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
null
null
null
TBDAnnotation/src/Model/CustomPermutation.hpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
null
null
null
/* * CustomPermutation.hpp * * Created on: 16/mag/2013 * Author: alessandro */ #ifndef CUSTOMPERMUTATION_HPP_ #define CUSTOMPERMUTATION_HPP_ #include <vector> #include <algorithm> #include <numeric> namespace cp { /* * Custom next combination generator */ template<typename T> class NextCombinationGenerator { std::vector<std::vector<T> > combinations; unsigned int m; template<typename Iterator> bool next_combination(const Iterator first, Iterator k, const Iterator last) { if ((first == last) || (first == k) || (last == k)) return false; Iterator itr1 = first; Iterator itr2 = last; ++itr1; if (last == itr1) return false; itr1 = last; --itr1; itr1 = k; --itr2; while (first != itr1) { if (*--itr1 < *itr2) { Iterator j = k; while (!(*itr1 < *j)) ++j; std::iter_swap(itr1, j); ++itr1; ++j; itr2 = k; std::rotate(itr1, j, last); while (last != j) { ++j; ++itr2; } std::rotate(k, itr2, last); return true; } } std::rotate(first, k, last); return false; } /* * Extract a subvector given a set of indexes */ template<typename R> std::vector<R> getValuesFromIndexesVector(const std::vector<R>& originals, const std::vector<unsigned int>& indexes) { std::vector<R> values(indexes.size()); for (unsigned int i = 0; i < indexes.size(); i++) { values[i] = originals[indexes[i]]; } return values; } public: typedef typename std::vector<std::vector<T> >::iterator iterator; typedef typename std::vector<std::vector<T> >::const_iterator const_iterator; NextCombinationGenerator(const std::vector<T>& _elements, unsigned int _m) : m(_m) { std::vector<unsigned int> elementsIndexes(_elements.size()); std::iota(std::begin(elementsIndexes), std::end(elementsIndexes), 0); do { std::vector<unsigned int> mIndexes(elementsIndexes.begin(), elementsIndexes.begin() + m); combinations.push_back(getValuesFromIndexesVector(_elements, mIndexes)); } while (next_combination(elementsIndexes.begin(), elementsIndexes.begin() + m, elementsIndexes.end())); } iterator begin() { return combinations.begin(); } const_iterator begin() const { return combinations.begin(); } iterator end() { return combinations.end(); } const_iterator end() const { return combinations.end(); } unsigned int size() const { return combinations.size(); } }; /* * Custom next cyclic permutation generator */ template<typename T> class NextCyclicPermutationGenerator { std::vector<std::vector<T> > cyclicPermutations; template<typename Iterator, typename R> static bool next_cyclic_permutation(const Iterator first, const Iterator last, const R terminationValue) { Iterator itr1 = first; Iterator itr2 = last; std::rotate(itr1, itr2 - 1, itr2); if (*itr1 == terminationValue) return false; return true; } /* * Extract a subvector given a set of indexes */ template<typename R> std::vector<R> getValuesFromIndexesVector(const std::vector<R>& originals, const std::vector<unsigned int>& indexes) { std::vector<R> values(indexes.size()); for (unsigned int i = 0; i < indexes.size(); i++) { values[i] = originals[indexes[i]]; } return values; } public: typedef typename std::vector<std::vector<T> >::iterator iterator; typedef typename std::vector<std::vector<T> >::const_iterator const_iterator; NextCyclicPermutationGenerator(const std::vector<T>& _elements) { std::vector<unsigned int> cyclicIndexes(_elements.size()); std::iota(std::begin(cyclicIndexes), std::end(cyclicIndexes), 0); unsigned int firstIndex = cyclicIndexes[0]; do { cyclicPermutations.push_back(getValuesFromIndexesVector(_elements, cyclicIndexes)); } while (next_cyclic_permutation(cyclicIndexes.begin(), cyclicIndexes.end(), firstIndex)); } iterator begin() { return cyclicPermutations.begin(); } const_iterator begin() const { return cyclicPermutations.begin(); } iterator end() { return cyclicPermutations.end(); } const_iterator end() const { return cyclicPermutations.end(); } unsigned int size() const { return cyclicPermutations.size(); } }; } #endif /* CUSTOMPERMUTATION_HPP_ */
23.649718
119
0.685141
marcorighini
8c110ee1d74b8c5c653df52a16a392ac74ba6d7c
3,697
cpp
C++
x_track/Application/X-Track.cpp
liushiwei/lv_port_linux_frame_buffer
17b822a68f8390df1e3b2c09319899c9c61dd72d
[ "MIT" ]
null
null
null
x_track/Application/X-Track.cpp
liushiwei/lv_port_linux_frame_buffer
17b822a68f8390df1e3b2c09319899c9c61dd72d
[ "MIT" ]
null
null
null
x_track/Application/X-Track.cpp
liushiwei/lv_port_linux_frame_buffer
17b822a68f8390df1e3b2c09319899c9c61dd72d
[ "MIT" ]
null
null
null
/* * PROJECT: LVGL ported to Linux * FILE: X-Track.cpp * PURPOSE: Implementation for LVGL ported to Linux * * LICENSE: The MIT License * * DEVELOPER: AlgoIdeas */ #include "App.h" #include "Common/HAL/HAL.h" #include <stdio.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <time.h> #include "lvgl/lvgl.h" #include "lvgl/examples/lv_examples.h" #include "lv_drivers/display/fbdev.h" #include "lv_fs_if/lv_fs_if.h" #include "lv_drivers/display/fbdev.h" static bool g_keyboard_pressed = false; static int g_keyboard_value = 0; // uint32_t custom_tick_get(void) // { // static uint32_t basic_ms = 0; // uint32_t ms = 0; // struct timespec monotonic_time; // memset(&monotonic_time, 0, sizeof(struct timespec)); // if (basic_ms == 0) // { // clock_gettime(CLOCK_MONOTONIC, &monotonic_time); // basic_ms = monotonic_time.tv_sec * 1000 + monotonic_time.tv_nsec/1000000; // } // clock_gettime(CLOCK_MONOTONIC, &monotonic_time); // ms = monotonic_time.tv_sec * 1000 + monotonic_time.tv_nsec/1000000; // return (ms - basic_ms); // } static void lv_keyboard_driver_read_callback( lv_indev_drv_t* indev_drv, lv_indev_data_t* data) { data->state = (lv_indev_state_t)( g_keyboard_pressed ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL); data->key = g_keyboard_value; } static void lv_lencoder_driver_read_callback( lv_indev_drv_t* indev_drv, lv_indev_data_t* data) { static bool lastState; data->enc_diff = HAL::Encoder_GetDiff(); bool isPush = HAL::Encoder_GetIsPush(); data->state = isPush ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL; if (isPush != lastState) { HAL::Buzz_Tone(isPush ? 500 : 700, 20); lastState = isPush; } } static void lv_display_init(void) { /*Linux frame buffer device init*/ fbdev_init(); /*Initialize a descriptor for the buffer*/ static lv_disp_draw_buf_t draw_buf; lv_disp_draw_buf_init(&draw_buf, (lv_color_t*)malloc(DISP_HOR_RES * DISP_VER_RES * sizeof(lv_color_t)), (lv_color_t*)malloc(DISP_HOR_RES * DISP_VER_RES * sizeof(lv_color_t)), DISP_HOR_RES * DISP_VER_RES * sizeof(lv_color_t)); /*Initialize and register a display driver*/ static lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.hor_res = DISP_HOR_RES; disp_drv.ver_res = DISP_VER_RES; disp_drv.flush_cb = fbdev_flush; disp_drv.draw_buf = &draw_buf; lv_disp_drv_register(&disp_drv); static lv_indev_drv_t kb_drv; lv_indev_drv_init(&kb_drv); kb_drv.type = LV_INDEV_TYPE_KEYPAD; kb_drv.read_cb = lv_keyboard_driver_read_callback; lv_indev_drv_register(&kb_drv); static lv_indev_drv_t enc_drv; lv_indev_drv_init(&enc_drv); enc_drv.type = LV_INDEV_TYPE_ENCODER; enc_drv.read_cb = lv_lencoder_driver_read_callback; lv_indev_drv_register(&enc_drv); } static int lv_usleep(unsigned int usec) { int ret; struct timespec requst; struct timespec remain; remain.tv_sec = usec / 1000000; remain.tv_nsec = (usec % 1000000) * 1000; do { requst = remain; ret = nanosleep(&requst, &remain); } while (-1 == ret && errno == EINTR); return ret; } // int main() // { // lv_init(); // lv_fs_if_init(); // HAL::HAL_Init(); // /* Display init */ // lv_display_init(); // App_Init(); // while (1) // { // lv_task_handler(); // HAL::HAL_Update(); // lv_usleep(5 * 1000); // lv_tick_inc(5000); // } // App_Uninit(); // return 0; // }
24.163399
84
0.660536
liushiwei
8c125419a34f74d1be5ad5615039f6221abe8b11
4,895
cpp
C++
src/epowfm_main.cpp
manicken/esp-ota-wifi_manager
9c1edc94a6550185de0dcea5f533f5973c74606a
[ "MIT" ]
null
null
null
src/epowfm_main.cpp
manicken/esp-ota-wifi_manager
9c1edc94a6550185de0dcea5f533f5973c74606a
[ "MIT" ]
null
null
null
src/epowfm_main.cpp
manicken/esp-ota-wifi_manager
9c1edc94a6550185de0dcea5f533f5973c74606a
[ "MIT" ]
null
null
null
/* */ #include <ESP8266WiFi.h> #include <WiFiManager.h> #include <ESP8266httpUpdate.h> #include <EEPROM.h> #include "TCP2UART.h" #include <ArduinoOTA.h> static int otaPartProcentCount = 0; #include <ESP8266WebServer.h> #define DEBUG_UART Serial1 TCP2UART tcp2uart; extern const char index_html[]; extern const char main_js[]; // QUICKFIX...See https://github.com/esp8266/Arduino/issues/263 #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)>(b)?(a):(b)) #define LED_PIN 5 // 0 = GPIO0, 2=GPIO2 #define LED_COUNT 50 #define WIFI_TIMEOUT 30000 // checks WiFi every ...ms. Reset after this time, if WiFi cannot reconnect. #define HTTP_PORT 80 unsigned long auto_last_change = 0; unsigned long last_wifi_check_time = 0; ESP8266WebServer server(HTTP_PORT); void printESP_info(void); void checkForUpdates(void); void setup_BasicOTA(void); void setup() { DEBUG_UART.begin(115200); DEBUG_UART.println(F("\r\n!!!!!Start of MAIN Setup!!!!!\r\n")); printESP_info(); WiFiManager wifiManager; DEBUG_UART.println(F("trying to connect to saved wifi")); wifiManager.autoConnect(); // using ESP.getChipId() internally checkForUpdates(); setup_BasicOTA(); tcp2uart.begin(); DEBUG_UART.println(F("\r\n!!!!!End of MAIN Setup!!!!!\r\n")); } void loop() { tcp2uart.BridgeMainTask(); ArduinoOTA.handle(); } void checkForUpdates(void) { //EEPROM.put(SPI_FLASH_SEC_SIZE, "hello"); DEBUG_UART.println(F("checking for updates")); String updateUrl = "http://espOtaServer/esp_ota/" + String(ESP.getChipId(), HEX) + ".bin"; t_httpUpdate_return ret = ESPhttpUpdate.update(updateUrl.c_str()); DEBUG_UART.print(F("HTTP_UPDATE_")); switch (ret) { case HTTP_UPDATE_FAILED: DEBUG_UART.println(F("FAIL Error ")); DEBUG_UART.printf("(%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); break; case HTTP_UPDATE_NO_UPDATES: DEBUG_UART.println(F("NO_UPDATES")); break; case HTTP_UPDATE_OK: DEBUG_UART.println(F("OK")); break; } } // called from setup() function void printESP_info(void) { uint32_t realSize = ESP.getFlashChipRealSize(); uint32_t ideSize = ESP.getFlashChipSize(); FlashMode_t ideMode = ESP.getFlashChipMode(); DEBUG_UART.print(F("Flash real id: ")); DEBUG_UART.printf("%08X\r\n", ESP.getFlashChipId()); DEBUG_UART.print(F("Flash real size: ")); DEBUG_UART.printf("%u 0\r\n\r\n", realSize); DEBUG_UART.print(F("Flash ide size: ")); DEBUG_UART.printf("%u\r\n", ideSize); DEBUG_UART.print(F("Flash ide speed: ")); DEBUG_UART.printf("%u\r\n", ESP.getFlashChipSpeed()); DEBUG_UART.print(F("Flash ide mode: ")); DEBUG_UART.printf("%s\r\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN")); if(ideSize != realSize) { DEBUG_UART.println(F("Flash Chip configuration wrong!\r\n")); } else { DEBUG_UART.println(F("Flash Chip configuration ok.\r\n")); } DEBUG_UART.printf(" ESP8266 Chip id = %08X\n", ESP.getChipId()); } void setup_BasicOTA() { ArduinoOTA.onStart([]() { otaPartProcentCount = 0; String type; if (ArduinoOTA.getCommand() == U_FLASH) { type = "sketch"; } else { // U_SPIFFS type = "filesystem"; } // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() DEBUG_UART.println(F("OTA Start\rOTA Progress: ")); }); ArduinoOTA.onEnd([]() { DEBUG_UART.println("\n100%\nOTA End"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { //DEBUG_UART.printf("Progress: %u%%\r", (progress / (total / 100))); //Serial1.printf("%u%%\r", (progress / (total / 100))); DEBUG_UART.print("-"); if (otaPartProcentCount < 10) otaPartProcentCount++; else { otaPartProcentCount = 0; DEBUG_UART.printf(" %u%%\r", (progress / (total / 100))); } }); ArduinoOTA.onError([](ota_error_t error) { DEBUG_UART.printf("OTA Error"); DEBUG_UART.printf("[%u]: ", error); if (error == OTA_AUTH_ERROR) DEBUG_UART.println(F("Auth Failed")); else if (error == OTA_BEGIN_ERROR) DEBUG_UART.println(F("Begin Failed")); else if (error == OTA_CONNECT_ERROR) DEBUG_UART.println(F("Connect Failed")); else if (error == OTA_RECEIVE_ERROR) DEBUG_UART.println(F("Receive Failed")); else if (error == OTA_END_ERROR) DEBUG_UART.println(F("End Failed")); }); ArduinoOTA.begin(); DEBUG_UART.println("Ready"); DEBUG_UART.print("IP address: "); DEBUG_UART.println(WiFi.localIP()); }
28.625731
203
0.626762
manicken
8c12dfa6df04559d418f5ecef17d10b0e9dd4d55
2,294
cpp
C++
platform/Android/source/premierlibrary/src/main/jni/utils/ass/JavaAssUtils.cpp
aliyun/CicadaPlayer
9d2b515a52403034a6e764e30fd0c9508edec889
[ "MIT" ]
38
2019-12-16T14:31:00.000Z
2020-01-11T03:01:26.000Z
platform/Android/source/premierlibrary/src/main/jni/utils/ass/JavaAssUtils.cpp
aliyun/CicadaPlayer
9d2b515a52403034a6e764e30fd0c9508edec889
[ "MIT" ]
11
2020-01-07T06:32:11.000Z
2020-01-13T03:52:37.000Z
platform/Android/source/premierlibrary/src/main/jni/utils/ass/JavaAssUtils.cpp
aliyun/CicadaPlayer
9d2b515a52403034a6e764e30fd0c9508edec889
[ "MIT" ]
14
2019-12-30T01:19:04.000Z
2020-01-11T02:12:35.000Z
// // Created by SuperMan on 6/29/21. // #include "JavaAssUtils.h" #include "JavaAssDialogue.h" #include "JavaAssHeader.h" #include <utils/Android/FindClass.h> #include <utils/Android/GetStringUTFChars.h> #include <utils/Android/JniException.h> static char *AssUtilsPath = (char *) ("com/cicada/player/utils/ass/AssUtils"); jclass gj_AssUtils_Class = nullptr; void JavaAssUtils::init(JNIEnv *env) { if (gj_AssUtils_Class == nullptr) { FindClass cls(env, AssUtilsPath); gj_AssUtils_Class = (jclass) env->NewGlobalRef(cls.getClass()); } } void JavaAssUtils::unInit(JNIEnv *pEnv) { if (gj_AssUtils_Class != nullptr) { pEnv->DeleteGlobalRef(gj_AssUtils_Class); gj_AssUtils_Class = nullptr; JniException::clearException(pEnv); } } static JNINativeMethod assUtils_method_table[] = { {"nParseAssHeader", "(Ljava/lang/String;)Ljava/lang/Object;", (void *) JavaAssUtils::java_ParseAssHeader}, {"nParseAssDialogue", "(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;", (void *) JavaAssUtils::java_ParseAssDialogue}, }; int JavaAssUtils::registerMethod(JNIEnv *pEnv) { if (gj_AssUtils_Class == nullptr) { return JNI_FALSE; } if (pEnv->RegisterNatives(gj_AssUtils_Class, assUtils_method_table, sizeof(assUtils_method_table) / sizeof(JNINativeMethod)) < 0) { JniException::clearException(pEnv); return JNI_FALSE; } return JNI_TRUE; } jobject JavaAssUtils::java_ParseAssHeader(JNIEnv *pEnv, jclass clz, jstring header) { GetStringUTFChars headerStr(pEnv, header); Cicada::AssHeader assHeader = Cicada::AssUtils::parseAssHeader(headerStr.getChars() == nullptr ? "" : headerStr.getChars()); jobject jHeader = JavaAssHeader::convertToJHeader(pEnv, assHeader); return jHeader; } jobject JavaAssUtils::java_ParseAssDialogue(JNIEnv *pEnv, jclass clz, jobject header, jstring data) { Cicada::AssHeader headerObj{}; JavaAssHeader::covertToHeader(pEnv, header, &headerObj); GetStringUTFChars dataStr(pEnv, data); Cicada::AssDialogue dialogue = Cicada::AssUtils::parseAssDialogue(headerObj, dataStr.getChars() == nullptr ? "" : dataStr.getChars()); jobject jDialogue = JavaAssDialogue::convertToJDialogue(pEnv, dialogue); return jDialogue; }
32.309859
138
0.719268
aliyun
8c134d4fd889fb13b168ff1f4b94faeda16499d8
870
cpp
C++
ishxiao/2503/12033282_AC_1500MS_17296K.cpp
ishx/poj
b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d
[ "MIT" ]
null
null
null
ishxiao/2503/12033282_AC_1500MS_17296K.cpp
ishx/poj
b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d
[ "MIT" ]
null
null
null
ishxiao/2503/12033282_AC_1500MS_17296K.cpp
ishx/poj
b4e5498117d7c8fc3d96eca2fa7f71f2dfa13c2d
[ "MIT" ]
null
null
null
//2503 #include<iostream> #include<string> #include<map> using namespace std; int main(void) { char english[11],foreign[11]; map<string,bool>appear; //记录foreign与engliash的配对映射是否出现 map<string,string>translate; //记录foreign到engliash的映射 /*Input the dictionary*/ while(true) { char t; //temporary if((t=getchar())=='\n') //判定是否输入了空行 break; else //输入english { english[0]=t; int i=1; while(true) { t=getchar(); if(t==' ') { english[i]='\0'; break; } else english[i++]=t; } } cin>>foreign; getchar(); //吃掉 输入foreign后的 回车符 appear[foreign]=true; translate[foreign]=english; } /*Translate*/ char word[11]; while(cin>>word) { if(appear[word]) cout<<translate[word]<<endl; else cout<<"eh"<<endl; } return 0; }
14.745763
56
0.552874
ishx
8c1400d2fdce9df0a094b0a7c626130b8c534a96
641
cpp
C++
CarbonService.cpp
finneyj/energy-in-schools
0b585e9a8262f88e33e8314570f91b5bd66d0885
[ "MIT" ]
null
null
null
CarbonService.cpp
finneyj/energy-in-schools
0b585e9a8262f88e33e8314570f91b5bd66d0885
[ "MIT" ]
null
null
null
CarbonService.cpp
finneyj/energy-in-schools
0b585e9a8262f88e33e8314570f91b5bd66d0885
[ "MIT" ]
null
null
null
#include "CarbonService.h" CarbonService::CarbonService(PeridoRESTClient& r) : radio(r) { } ManagedString CarbonService::getCarbonIndex(ManagedString endpoint) { ManagedString res = radio.get("/carbon/" + endpoint + "/"); return PeridoUtil::getString(res, 0); } ManagedString CarbonService::getCarbonValue(ManagedString endpoint) { ManagedString res = radio.get("/carbon/" + endpoint + "/"); return PeridoUtil::getString(res, 0); } ManagedString CarbonService::getCarbonGenerationMix(ManagedString endpoint) { ManagedString res = radio.get("/carbon/" + endpoint + "/"); return PeridoUtil::getString(res, 0); }
32.05
77
0.720749
finneyj
8c15797d0b5214691dd3a7baf2b83c5bab34cf0e
854
cpp
C++
snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocumentFragment.OwnerDocument Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-03-12T19:26:36.000Z
2022-01-10T21:45:33.000Z
snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocumentFragment.OwnerDocument Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocumentFragment.OwnerDocument Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <Snippet1> #using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; int main() { // Create the XmlDocument. XmlDocument^ doc = gcnew XmlDocument; doc->LoadXml( "<items/>" ); // Create a document fragment. XmlDocumentFragment^ docFrag = doc->CreateDocumentFragment(); // Display the owner document of the document fragment. Console::WriteLine( docFrag->OwnerDocument->OuterXml ); // Add nodes to the document fragment. Notice that the // new element is created using the owner document of // the document fragment. XmlElement^ elem = doc->CreateElement( "item" ); elem->InnerText = "widget"; docFrag->AppendChild( elem ); Console::WriteLine( "Display the document fragment..." ); Console::WriteLine( docFrag->OuterXml ); } // </Snippet1>
25.878788
64
0.68267
BohdanMosiyuk
22c5954e42da3d4b70d11c6e28f6facac8537e77
874
cpp
C++
modules/task_2/yashin_k_topology_star/topology_star.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
1
2021-12-09T17:20:25.000Z
2021-12-09T17:20:25.000Z
modules/task_2/yashin_k_topology_star/topology_star.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/yashin_k_topology_star/topology_star.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
3
2022-02-23T14:20:50.000Z
2022-03-30T09:00:02.000Z
// Copyright 2021 Yashin Kirill #include <mpi.h> #include <algorithm> #include <random> #include "../../../modules/task_2/yashin_k_topology_star/topology_star.h" int getRand(int min, int max) { if (min == max) { return max; } else { std::mt19937 gen; std::uniform_int_distribution<> distr{min, max}; return distr(gen); } } MPI_Comm Star(int ProcNum) { MPI_Comm starcomm; int* index = new int[ProcNum]; int* edges = new int[2 * ProcNum - 2]; index[0] = ProcNum - 1; for (int i = 1; i < ProcNum; i++) { index[i] = index[i - 1] + 1; } for (int i = 0; i < 2 * ProcNum - 2; i++) { if (i < ProcNum - 1) { edges[i] = i + 1; } else { edges[i] = 0; } } MPI_Graph_create(MPI_COMM_WORLD, ProcNum, index, edges, 1, &starcomm); return starcomm; }
21.317073
74
0.543478
Stepakrap
22c6082b118ca58824432a9561c72c53a5c49d74
10,452
cpp
C++
lib/libstereo/src/stereo_sgmp.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
4
2020-12-28T15:29:15.000Z
2021-06-27T12:37:15.000Z
lib/libstereo/src/stereo_sgmp.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
null
null
null
lib/libstereo/src/stereo_sgmp.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
2
2021-01-13T05:28:39.000Z
2021-05-04T03:37:11.000Z
#include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include "stereo.hpp" #include "matching_cost.hpp" #include "stereo_common.hpp" #include "dsi.hpp" #include "cost_aggregation.hpp" #ifdef __GNUG__ #include <chrono> #include <iostream> /* static std::chrono::time_point<std::chrono::system_clock> start; static void timer_set() { start = std::chrono::high_resolution_clock::now(); } static void timer_print(const std::string &msg, const bool reset=true) { auto stop = std::chrono::high_resolution_clock::now(); char buf[24]; snprintf(buf, sizeof(buf), "%5i ms ", (int) std::chrono::duration_cast<std::chrono::milliseconds>(stop-start).count()); std::cout << buf << msg << "\n" << std::flush; if (reset) { timer_set(); } } */ static void timer_set() {} static void timer_print(const std::string &msg, const bool reset=true) {} #else static void timer_set() {} static void timer_print(const std::string &msg, const bool reset=true) {} #endif using cv::Mat; using cv::Size; static int ct_windows_w = 9; static int ct_windows_h = 7; struct StereoCensusSgmP::Impl { DisparitySpaceImage<unsigned short> dsi; CensusMatchingCost cost; Mat cost_min; Mat cost_min_paths; Mat uncertainty; Mat confidence; Mat disparity_r; Mat prior_disparity; Mat l; Mat r; Mat prior; Mat search; Impl(int width, int height, int min_disp, int max_disp) : dsi(width, height, min_disp, max_disp, ct_windows_w*ct_windows_h), cost(width, height, min_disp, max_disp, ct_windows_w, ct_windows_h), cost_min(height, width, CV_16UC1), cost_min_paths(height, width, CV_16UC1), uncertainty(height, width, CV_16UC1), confidence(height, width, CV_32FC1), disparity_r(height, width, CV_32FC1), prior_disparity(height, width, CV_32FC1) {} void cvtColor(const cv::Mat &iml, const cv::Mat &imr) { switch (iml.channels()) { case 4: cv::cvtColor(iml, l, cv::COLOR_BGRA2GRAY); break; case 3: cv::cvtColor(iml, l, cv::COLOR_BGR2GRAY); break; case 1: l = iml; break; default: throw std::exception(); } switch (imr.channels()) { case 4: cv::cvtColor(imr, r, cv::COLOR_BGRA2GRAY); break; case 3: cv::cvtColor(imr, r, cv::COLOR_BGR2GRAY); break; case 1: r = imr; break; default: throw std::exception(); } } }; static void compute_P2(const cv::Mat &prior, cv::Mat &P2) { } // prior CV32_FC1 // out CV8_UC2 // // TODO: range could be in depth units to get more meningful bounds static void compute_search_range(const cv::Mat &prior, cv::Mat &out, int dmin, int dmax, int range) { out.create(prior.size(), CV_8UC2); out.setTo(0); for (int y = 0; y < out.rows; y++) { for (int x = 0; x < out.cols; x ++) { int d = round(prior.at<float>(y,x)); auto &v = out.at<cv::Vec2b>(y,x); if ((d != 0) && (d >= dmin) && (d <= dmax)) { v[0] = std::max(dmin, d-range); v[1] = std::min(dmax, d+range); } else { v[0] = dmin; v[1] = dmax; } } } } /** * Compute 2D offset image. SGM sweeping direction set with dx and dy. * * Scharstein, D., Taniai, T., & Sinha, S. N. (2018). Semi-global stereo * matching with surface orientation priors. Proceedings - 2017 International * Conference on 3D Vision, 3DV 2017. https://doi.org/10.1109/3DV.2017.00033 */ static void compute_offset_image(const cv::Mat &prior, cv::Mat &out, const int dx, const int dy) { if (prior.empty()) { return; } out.create(prior.size(), CV_16SC1); out.setTo(0); int y_start; int y_stop; int x_start; int x_stop; if (dy < 0) { y_start = -dy; y_stop = prior.rows; } else { y_start = 0; y_stop = prior.rows - dy; } if (dx < 0) { x_start = -dx; x_stop = prior.cols; } else { x_start = 0; x_stop = prior.cols - dx; } for (int y = y_start; y < y_stop; y++) { const float *ptr_prior = prior.ptr<float>(y); const float *ptr_prior_r = prior.ptr<float>(y+dy); short *ptr_out = out.ptr<short>(y); for (int x = x_start; x < x_stop; x++) { // TODO types (assumes signed ptr_out and floating point ptr_prior) if (ptr_prior[x] != 0.0 && ptr_prior_r[x+dx] != 0.0) { ptr_out[x] = round(ptr_prior[x] - ptr_prior_r[x+dx]); } } } } struct AggregationParameters { Mat &prior; // Mat &search; // search range for each pixel CV_8UC2 Mat &min_cost; const StereoCensusSgmP::Parameters &params; }; inline int get_jump(const int y, const int x, const int d, const int dy, const int dx, const cv::Mat &prior) { if (prior.empty()) { return 0; } else if (dx == 1 && dy == 0) { return prior.at<short>(y, x); } else if (dx == -1 && dy == 0) { if (x == prior.cols - 1) { return 0; } return -prior.at<short>(y, x+1); } else if (dx == 0 && dy == 1) { return prior.at<short>(y, x); } else if (dx == 0 && dy == -1) { if (y == prior.rows - 1) { return 0; } return -prior.at<short>(y+1, x); } else if (dx == 1 && dy == 1) { return prior.at<short>(y, x); } else if (dx == -1 && dy == -1) { if (y == prior.rows - 1 || x == prior.cols - 1) { return 0; } return -prior.at<short>(y+1, x+1); } else if (dx == 1 && dy == -1) { return prior.at<short>(y, x); } else if (dx == -1 && dy == 1) { if (y == prior.rows - 1 || x == 0) { return 0; } return -prior.at<short>(y+1, x-1); } } template<typename T=unsigned short> inline void aggregate( AggregationData<CensusMatchingCost, DisparitySpaceImage<T>, T> &data, AggregationParameters &params) { auto &previous_cost_min = data.previous_cost_min; auto &previous = data.previous; auto &updates = data.updates; auto &out = data.out; const auto &in = data.in; const auto &x = data.x; const auto &y = data.y; const auto &i = data.i; const T P1 = params.params.P1; const T P2 = params.params.P2; T cost_min = in.cost_max; //int d_start = params.search.at<cv::Vec2b>(y,x)[0]; //int d_stop = params.search.at<cv::Vec2b>(y,x)[1]; int d_start = in.disp_min; int d_stop = in.disp_max; for (int d = d_start; d <= d_stop; d++) { const int j = get_jump(y, x, d, data.dy, data.dx, params.prior); const int d_j = std::max(std::min(d+j, previous.disp_max), previous.disp_min); const T L_min = std::min<T>(previous(0,i,d_j), std::min<T>(T(previous_cost_min + P2), std::min<T>(T(previous(0,i,std::min(d_j+1, previous.disp_max)) + P1), T(previous(0,i,std::max(d_j-1, previous.disp_min)) + P1)) ) ); T C = in(y,x,d); T cost_update = L_min + C - previous_cost_min; // stop if close to overflow if (cost_update > (std::numeric_limits<T>::max() - T(in.cost_max))) { throw std::exception(); } updates(0,i,d) = cost_update; cost_min = cost_update * (cost_update < cost_min) + cost_min * (cost_update >= cost_min); } /*const T update_skipped = params.params.P3; for (int d = out.disp_min; d < d_start; d++) { previous(0,i,d) = update_skipped; out(y,x,d) += update_skipped; }*/ for (int d = d_start; d <= d_stop; d++) { previous(0,i,d) = updates(0,i,d); out(y,x,d) += updates(0,i,d); } /*for (int d = d_stop+1; d <= out.disp_max; d++) { previous(0,i,d) = update_skipped; out(y,x,d) += update_skipped; }*/ params.min_cost.at<T>(y, x) = cost_min; previous_cost_min = cost_min; } StereoCensusSgmP::StereoCensusSgmP() : impl_(nullptr) { impl_ = new Impl(0, 0, 0, 0); } void StereoCensusSgmP::setPrior(const cv::Mat &prior) { prior.copyTo(impl_->prior_disparity); } void StereoCensusSgmP::compute(const cv::Mat &l, const cv::Mat &r, cv::Mat disparity) { impl_->dsi.clear(); impl_->uncertainty.setTo(0); if (l.rows != impl_->dsi.height || r.cols != impl_->dsi.width) { Mat prior = impl_->prior_disparity; delete impl_; impl_ = nullptr; impl_ = new Impl(l.cols, l.rows, params.d_min, params.d_max); if (prior.size() == l.size()) { impl_->prior_disparity = prior; } } impl_->cvtColor(l, r); timer_set(); // CT impl_->cost.setLeft(impl_->l); impl_->cost.setRight(impl_->r); if (params.debug) { timer_print("census transform"); } // cost aggregation AggregationParameters aggr_params = {impl_->prior, impl_->search, impl_->cost_min_paths, params}; compute_search_range(impl_->prior_disparity, impl_->search, params.d_min, params.d_max, params.range); if (params.paths & AggregationDirections::HORIZONTAL) { compute_offset_image(impl_->prior_disparity, impl_->prior, 1, 0); aggregate_horizontal_all<unsigned short>( aggregate<unsigned short>, impl_->cost, impl_->dsi, aggr_params); if (params.debug) { timer_print("horizontal aggregation"); } } if (params.paths & AggregationDirections::VERTICAL) { compute_offset_image(impl_->prior_disparity, impl_->prior, 0, 1); aggregate_vertical_all<unsigned short>( aggregate<unsigned short>, impl_->cost, impl_->dsi, aggr_params); if (params.debug) { timer_print("vertical aggregation"); } } if (params.paths & AggregationDirections::DIAGONAL1) { compute_offset_image(impl_->prior_disparity, impl_->prior, 1, 1); aggregate_diagonal_upper_all<unsigned short>( aggregate<unsigned short>, impl_->cost, impl_->dsi, aggr_params); if (params.debug) { timer_print("upper diagonal aggregation"); } } if (params.paths & AggregationDirections::DIAGONAL2) { compute_offset_image(impl_->prior_disparity, impl_->prior, 1, -1); aggregate_diagonal_lower_all<unsigned short>( aggregate<unsigned short>, impl_->cost, impl_->dsi, aggr_params); if (params.debug) { timer_print("lower diagonal aggregation"); } } if (!(params.paths & AggregationDirections::ALL)) { throw std::exception(); } // wta + consistency wta(impl_->dsi, disparity, impl_->cost_min, params.subpixel); wta_diagonal(impl_->disparity_r, impl_->dsi); consistency_check(disparity, impl_->disparity_r); // confidence estimate // Drory, A., Haubold, C., Avidan, S., & Hamprecht, F. A. (2014). // Semi-global matching: A principled derivation in terms of // message passing. Lecture Notes in Computer Science (Including Subseries // Lecture Notes in Artificial Intelligence and Lecture Notes in //Bioinformatics). https://doi.org/10.1007/978-3-319-11752-2_4 impl_->uncertainty = impl_->cost_min - impl_->cost_min_paths; // instead of difference, use ratio cv::divide(impl_->cost_min, impl_->cost_min_paths, impl_->confidence, CV_32FC1); // confidence threshold disparity.setTo(0.0f, impl_->uncertainty > params.uniqueness); cv::medianBlur(disparity, disparity, 3); } StereoCensusSgmP::~StereoCensusSgmP() { if (impl_) { delete impl_; impl_ = nullptr; } }
26.460759
110
0.658821
knicos
22c903e26bd1f49b47f303acf4b87d8f598391ea
5,789
hpp
C++
gsa/wit/COIN/include/Presolve.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
1
2019-10-25T05:25:23.000Z
2019-10-25T05:25:23.000Z
gsa/wit/COIN/include/Presolve.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
2
2019-09-04T17:34:59.000Z
2020-09-16T08:10:57.000Z
gsa/wit/COIN/include/Presolve.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
18
2019-07-22T19:01:25.000Z
2022-03-03T15:36:11.000Z
// Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. #ifndef Presolve_H #define Presolve_H #include "ClpSimplex.hpp" class PresolveAction; class PresolveMatrix; class PostsolveMatrix; /** This class stores information generated by the presolve procedure. */ class Presolve { public: /**@name Constructor and destructor No copy method is defined. I have not attempted to prevent the default copy method from being generated. */ //@{ /// Default constructor Presolve(); /// Virtual destructor virtual ~Presolve(); //@} // taken out for now #if 0 /**@name presolve - presolves a model, transforming the model * and saving information in the Presolve object needed for postsolving. * This is method is virtual; the idea is that in the future, * one could override this method to customize how the various * presolve techniques are applied. */ virtual void presolve(ClpSimplex& si); /**@name postsolve - postsolve the problem. The problem must have been solved to optimality. If you are using an algorithm like simplex that has a concept of "basic" rows/cols, then pass in two arrays that indicate which cols/rows are basic in the problem passed in (si); on return, they will indicate which rows/cols in the original problem are basic in the solution. These two arrays must have enough room for ncols/nrows in the *original* problem, not the problem being passed in. If you aren't interested in this information, or it doesn't make sense, then pass in 0 for each array. Note that if you modified the problem after presolving it, then you must ``undo'' these modifications before calling postsolve. */ virtual void postsolve(ClpSimplex& si, unsigned char *colstat, unsigned char *rowstat); #endif /**@name presolve - presolves a model, transforming the model * and saving information in the Presolve object needed for postsolving. * This is method is virtual; the idea is that in the future, * one could override this method to customize how the various * presolve techniques are applied. This version of presolve returns a pointer to a new presolved model. NULL if infeasible or unbounded. This should be paired with postsolve below. The adavantage of going back to original model is that it will be exactly as it was i.e. 0.0 will not become 1.0e-19. If keepIntegers is true then bounds may be tightened in original. Bounds will be moved by up to feasibilityTolerance to try and stay feasible. Names will be dropped in presolved model if asked */ virtual ClpSimplex * presolvedModel(ClpSimplex & si, double feasibilityTolerance=0.0, bool keepIntegers=true, int numberPasses=5, bool dropNames=false); /** Return pointer to presolved model, Up to user to destroy */ ClpSimplex * model() const; /// Return pointer to original model ClpSimplex * originalModel() const; /// Set pointer to original model void setOriginalModel(ClpSimplex * model); /// return pointer to original columns const int * originalColumns() const; /** "Magic" number. If this is non-zero then any elements with this value may change and so presolve is very limited in what can be done to the row and column. This is for non-linear problems. */ inline void setNonLinearValue(double value) { nonLinearValue_ = value;}; inline double nonLinearValue() const { return nonLinearValue_;}; /**@name postsolve - postsolve the problem. If the problem has not been solved to optimality, there are no guarantees. If you are using an algorithm like simplex that has a concept of "basic" rows/cols, then set updateStatus Note that if you modified the original problem after presolving, then you must ``undo'' these modifications before calling postsolve. This version updates original*/ virtual void postsolve(bool updateStatus=true); /**@name private or protected data */ private: /// Original model - must not be destroyed before postsolve ClpSimplex * originalModel_; /// Presolved model - up to user to destroy by deletePresolvedModel ClpSimplex * presolvedModel_; /** "Magic" number. If this is non-zero then any elements with this value may change and so presolve is very limited in what can be done to the row and column. This is for non-linear problems. One could also allow for cases where sign of coefficient is known. */ double nonLinearValue_; /// Original column numbers int * originalColumn_; /// The list of transformations applied. const PresolveAction *paction_; /// The postsolved problem will expand back to its former size /// as postsolve transformations are applied. /// It is efficient to allocate data structures for the final size /// of the problem rather than expand them as needed. /// These fields give the size of the original problem. int ncols_; int nrows_; CoinBigIndex nelems_; /// Number of major passes int numberPasses_; protected: /// If you want to apply the individual presolve routines differently, /// or perhaps add your own to the mix, /// define a derived class and override this method virtual const PresolveAction *presolve(PresolveMatrix *prob); /// Postsolving is pretty generic; just apply the transformations /// in reverse order. /// You will probably only be interested in overriding this method /// if you want to add code to test for consistency /// while debugging new presolve techniques. virtual void postsolve(PostsolveMatrix &prob); /// Gets rid of presolve actions (e.g.when infeasible) void gutsOfDestroy(); }; #endif
37.836601
75
0.723441
kant
22ca19b51714960e5459af0656ec9209608229a3
238
cpp
C++
assign2/Sir/MechanicTasks.cpp
chakravardhan/cpp-course
6748e042ca6a81d62f9a48a38118f0fd2cc8209d
[ "MIT" ]
null
null
null
assign2/Sir/MechanicTasks.cpp
chakravardhan/cpp-course
6748e042ca6a81d62f9a48a38118f0fd2cc8209d
[ "MIT" ]
null
null
null
assign2/Sir/MechanicTasks.cpp
chakravardhan/cpp-course
6748e042ca6a81d62f9a48a38118f0fd2cc8209d
[ "MIT" ]
null
null
null
#include "Mechanic.h" #include "FrontDesk.h" int main(int argc, char* argv[]) { Mechanic mechanic; FrontDesk fdesk(mechanic); fdesk.processRequests(); return 0; } #if 0 R 15 R 21 N N N R 92 R 401 R 827 N N R 82 R 910 E #endif
7.4375
32
0.663866
chakravardhan
22cb1f7aa560abcfe5ddf7fa1312befebf6cbc17
7,376
cc
C++
src/s390/code-stubs-s390.cc
RiyoCoder/v8
e073edfc7dc990cc5f71c4e51ac27b19be16fcb7
[ "BSD-3-Clause" ]
null
null
null
src/s390/code-stubs-s390.cc
RiyoCoder/v8
e073edfc7dc990cc5f71c4e51ac27b19be16fcb7
[ "BSD-3-Clause" ]
null
null
null
src/s390/code-stubs-s390.cc
RiyoCoder/v8
e073edfc7dc990cc5f71c4e51ac27b19be16fcb7
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if V8_TARGET_ARCH_S390 #include "src/api-arguments-inl.h" #include "src/assembler-inl.h" #include "src/base/bits.h" #include "src/bootstrapper.h" #include "src/code-stubs.h" #include "src/frame-constants.h" #include "src/frames.h" #include "src/ic/ic.h" #include "src/ic/stub-cache.h" #include "src/isolate.h" #include "src/macro-assembler.h" #include "src/objects/api-callbacks.h" #include "src/regexp/jsregexp.h" #include "src/regexp/regexp-macro-assembler.h" #include "src/runtime/runtime.h" namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) void JSEntryStub::Generate(MacroAssembler* masm) { // r2: code entry // r3: function // r4: receiver // r5: argc // r6: argv Label invoke, handler_entry, exit; { NoRootArrayScope no_root_array(masm); // saving floating point registers #if V8_TARGET_ARCH_S390X // 64bit ABI requires f8 to f15 be saved __ lay(sp, MemOperand(sp, -8 * kDoubleSize)); __ std(d8, MemOperand(sp)); __ std(d9, MemOperand(sp, 1 * kDoubleSize)); __ std(d10, MemOperand(sp, 2 * kDoubleSize)); __ std(d11, MemOperand(sp, 3 * kDoubleSize)); __ std(d12, MemOperand(sp, 4 * kDoubleSize)); __ std(d13, MemOperand(sp, 5 * kDoubleSize)); __ std(d14, MemOperand(sp, 6 * kDoubleSize)); __ std(d15, MemOperand(sp, 7 * kDoubleSize)); #else // 31bit ABI requires you to store f4 and f6: // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN417 __ lay(sp, MemOperand(sp, -2 * kDoubleSize)); __ std(d4, MemOperand(sp)); __ std(d6, MemOperand(sp, kDoubleSize)); #endif // zLinux ABI // Incoming parameters: // r2: code entry // r3: function // r4: receiver // r5: argc // r6: argv // Requires us to save the callee-preserved registers r6-r13 // General convention is to also save r14 (return addr) and // sp/r15 as well in a single STM/STMG __ lay(sp, MemOperand(sp, -10 * kPointerSize)); __ StoreMultipleP(r6, sp, MemOperand(sp, 0)); // Set up the reserved register for 0.0. // __ LoadDoubleLiteral(kDoubleRegZero, 0.0, r0); // Push a frame with special values setup to mark it as an entry frame. // Bad FP (-1) // SMI Marker // SMI Marker // kCEntryFPAddress // Frame type __ lay(sp, MemOperand(sp, -5 * kPointerSize)); // Push a bad frame pointer to fail if it is used. __ LoadImmP(r10, Operand(-1)); StackFrame::Type marker = type(); __ Load(r9, Operand(StackFrame::TypeToMarker(marker))); __ Load(r8, Operand(StackFrame::TypeToMarker(marker))); // Save copies of the top frame descriptor on the stack. __ mov(r7, Operand(ExternalReference::Create( IsolateAddressId::kCEntryFPAddress, isolate()))); __ LoadP(r7, MemOperand(r7)); __ StoreMultipleP(r7, r10, MemOperand(sp, kPointerSize)); // Set up frame pointer for the frame to be pushed. // Need to add kPointerSize, because sp has one extra // frame already for the frame type being pushed later. __ lay(fp, MemOperand( sp, -EntryFrameConstants::kCallerFPOffset + kPointerSize)); __ InitializeRootRegister(); } // If this is the outermost JS call, set js_entry_sp value. Label non_outermost_js; ExternalReference js_entry_sp = ExternalReference::Create(IsolateAddressId::kJSEntrySPAddress, isolate()); __ mov(r7, Operand(js_entry_sp)); __ LoadAndTestP(r8, MemOperand(r7)); __ bne(&non_outermost_js, Label::kNear); __ StoreP(fp, MemOperand(r7)); __ Load(ip, Operand(StackFrame::OUTERMOST_JSENTRY_FRAME)); Label cont; __ b(&cont, Label::kNear); __ bind(&non_outermost_js); __ Load(ip, Operand(StackFrame::INNER_JSENTRY_FRAME)); __ bind(&cont); __ StoreP(ip, MemOperand(sp)); // frame-type // Jump to a faked try block that does the invoke, with a faked catch // block that sets the pending exception. __ b(&invoke, Label::kNear); __ bind(&handler_entry); handler_offset_ = handler_entry.pos(); // Caught exception: Store result (exception) in the pending exception // field in the JSEnv and return a failure sentinel. Coming in here the // fp will be invalid because the PushStackHandler below sets it to 0 to // signal the existence of the JSEntry frame. __ mov(ip, Operand(ExternalReference::Create( IsolateAddressId::kPendingExceptionAddress, isolate()))); __ StoreP(r2, MemOperand(ip)); __ LoadRoot(r2, RootIndex::kException); __ b(&exit, Label::kNear); // Invoke: Link this frame into the handler chain. __ bind(&invoke); // Must preserve r2-r6. __ PushStackHandler(); // If an exception not caught by another handler occurs, this handler // returns control to the code after the b(&invoke) above, which // restores all kCalleeSaved registers (including cp and fp) to their // saved values before returning a failure to C. // Invoke the function by calling through JS entry trampoline builtin. // Notice that we cannot store a reference to the trampoline code directly in // this stub, because runtime stubs are not traversed when doing GC. // Expected registers by Builtins::JSEntryTrampoline // r2: code entry // r3: function // r4: receiver // r5: argc // r6: argv __ Call(EntryTrampoline(), RelocInfo::CODE_TARGET); // Unlink this frame from the handler chain. __ PopStackHandler(); __ bind(&exit); // r2 holds result // Check if the current stack frame is marked as the outermost JS frame. Label non_outermost_js_2; __ pop(r7); __ CmpP(r7, Operand(StackFrame::OUTERMOST_JSENTRY_FRAME)); __ bne(&non_outermost_js_2, Label::kNear); __ mov(r8, Operand::Zero()); __ mov(r7, Operand(js_entry_sp)); __ StoreP(r8, MemOperand(r7)); __ bind(&non_outermost_js_2); // Restore the top frame descriptors from the stack. __ pop(r5); __ mov(ip, Operand(ExternalReference::Create( IsolateAddressId::kCEntryFPAddress, isolate()))); __ StoreP(r5, MemOperand(ip)); // Reset the stack to the callee saved registers. __ lay(sp, MemOperand(sp, -EntryFrameConstants::kCallerFPOffset)); // Reload callee-saved preserved regs, return address reg (r14) and sp __ LoadMultipleP(r6, sp, MemOperand(sp, 0)); __ la(sp, MemOperand(sp, 10 * kPointerSize)); // saving floating point registers #if V8_TARGET_ARCH_S390X // 64bit ABI requires f8 to f15 be saved __ ld(d8, MemOperand(sp)); __ ld(d9, MemOperand(sp, 1 * kDoubleSize)); __ ld(d10, MemOperand(sp, 2 * kDoubleSize)); __ ld(d11, MemOperand(sp, 3 * kDoubleSize)); __ ld(d12, MemOperand(sp, 4 * kDoubleSize)); __ ld(d13, MemOperand(sp, 5 * kDoubleSize)); __ ld(d14, MemOperand(sp, 6 * kDoubleSize)); __ ld(d15, MemOperand(sp, 7 * kDoubleSize)); __ la(sp, MemOperand(sp, 8 * kDoubleSize)); #else // 31bit ABI requires you to store f4 and f6: // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN417 __ ld(d4, MemOperand(sp)); __ ld(d6, MemOperand(sp, kDoubleSize)); __ la(sp, MemOperand(sp, 2 * kDoubleSize)); #endif __ b(r14); } #undef __ } // namespace internal } // namespace v8 #endif // V8_TARGET_ARCH_S390
34.306977
80
0.684111
RiyoCoder
22cee953f58e9055de70a31e4c95f1b9cf0eae73
368
hpp
C++
mercury/include/mercury/ping/TestConfig.hpp
ZachAnders/OPLabs
085030e60c23292c7860817233373ab6e1b19165
[ "BSD-2-Clause" ]
1
2018-02-06T17:43:51.000Z
2018-02-06T17:43:51.000Z
mercury/include/mercury/ping/TestConfig.hpp
ZachAnders/OPLabs
085030e60c23292c7860817233373ab6e1b19165
[ "BSD-2-Clause" ]
null
null
null
mercury/include/mercury/ping/TestConfig.hpp
ZachAnders/OPLabs
085030e60c23292c7860817233373ab6e1b19165
[ "BSD-2-Clause" ]
null
null
null
#ifndef TESTCONFIG_HPP_ #define TESTCONFIG_HPP_ /* * Author: jrahm * created: 2015/03/15 * TestConfig.hpp: <description> */ #include <vector> #include <io/Inet4Address.hpp> namespace ping { class TestConfig { public: /* the list of address to test ping speed to */ std::vector< uptr<io::SocketAddress> > ping_addrs; }; } #endif /* TESTCONFIG_HPP_ */
15.333333
54
0.690217
ZachAnders
22d08200e045cb2e90a91c9eef307a2a9ede4614
7,052
hpp
C++
ChapelScheduler.hpp
ct-clmsn/mesos4chpl
33d3f5f87aeeff09f464fa351d021d30ac76be80
[ "Apache-2.0" ]
1
2015-11-08T20:39:05.000Z
2015-11-08T20:39:05.000Z
ChapelScheduler.hpp
ct-clmsn/mesos4chpl
33d3f5f87aeeff09f464fa351d021d30ac76be80
[ "Apache-2.0" ]
null
null
null
ChapelScheduler.hpp
ct-clmsn/mesos4chpl
33d3f5f87aeeff09f464fa351d021d30ac76be80
[ "Apache-2.0" ]
null
null
null
/** * 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. */ /* * ChapelScheduler.hpp * * A mesos-scheduler for Chapel programs! * * ct.clmsn at gmail dot com * 24AUG2015 * */ #ifndef __MESOS_FRAMEWORK_CHPL_SCHEDULER__ #define __MESOS_FRAMEWORK_CHPL_SCHEDULER__ 1 #include <stdlib.h> #include <string> #include <vector> #include <map> #include <iostream> #include <mesos/resources.hpp> #include <mesos/scheduler.hpp> using namespace std; using namespace mesos; using mesos::Resources; class ChapelScheduler : public Scheduler { private: // coresReq, processing unit precent required - precent of nodes in a mesos offer current has available // memReq, RAM required to run the program // cpusReq, number of cores to limit thread processing, if -1, then use *all* threads available // const double coresReq; const int cpusReq, numAttempts; const uint64_t memReq; const string numLocalesReq, mesosReq, leaderHostname, exec, remoteCmd, user_id; size_t tasksLaunched, tasksFinished, tasksFailed, frameworkMessagesReceived; bool taskExecError; map<string, TaskInfo> launchedTsks; CommandInfo chplCmdInfo; public: ChapelScheduler(const int cpus_req, const uint64_t mem_req, const double cores_req, const string& leader_hostname, const string& executable, const string& remote_cmd, const string& usr, const int num_attempts=10); // added function to terminate all active tasks being tracked by this scheduler void terminateAllTAsks(SchedulerDriver* driver); /* * Invoked when the scheduler successfully registers with a Mesos * master. A unique ID (generated by the master) used for * distinguishing this framework from others and MasterInfo * with the ip and port of the current master are provided as arguments. */ void registered(SchedulerDriver* driver, const FrameworkID& frameworkId, const MasterInfo& masterInfo); /* * Invoked when the scheduler re-registers with a newly elected Mesos master. * This is only called when the scheduler has previously been registered. * MasterInfo containing the updated information about the elected master * is provided as an argument. */ void reregistered(SchedulerDriver* driver, const MasterInfo& masterInfo); /* * Invoked when the scheduler becomes "disconnected" from the master * (e.g., the master fails and another is taking over). */ void disconnected(SchedulerDriver* driver); /* * Invoked when resources have been offered to this framework. A * single offer will only contain resources from a single slave. * Resources associated with an offer will not be re-offered to * _this_ framework until either (a) this framework has rejected * those resources (see SchedulerDriver::launchTasks) or (b) those * resources have been rescinded (see Scheduler::offerRescinded). * Note that resources may be concurrently offered to more than one * framework at a time (depending on the allocator being used). In * that case, the first framework to launch tasks using those * resources will be able to use them while the other frameworks * will have those resources rescinded (or if a framework has * already launched tasks with those resources then those tasks will * fail with a TASK_LOST status and a message saying as much). */ void resourceOffers(SchedulerDriver* driver, const vector<Offer>& offers); /* * Invoked when an offer is no longer valid (e.g., the slave was * lost or another framework used resources in the offer). If for * whatever reason an offer is never rescinded (e.g., dropped * message, failing over framework, etc.), a framework that attempts * to launch tasks using an invalid offer will receive TASK_LOST * status updats for those tasks (see Scheduler::resourceOffers). */ void offerRescinded(SchedulerDriver* driver, const OfferID& offerId); /* * Invoked when the status of a task has changed (e.g., a slave is * lost and so the task is lost, a task finishes and an executor * sends a status update saying so, etc). If implicit * acknowledgements are being used, then returning from this * callback _acknowledges_ receipt of this status update! If for * whatever reason the scheduler aborts during this callback (or * the process exits) another status update will be delivered (note, * however, that this is currently not true if the slave sending the * status update is lost/fails during that time). If explicit * acknowledgements are in use, the scheduler must acknowledge this * status on the driver. */ void statusUpdate(SchedulerDriver* driver, const TaskStatus& status); /* * Invoked when an executor sends a message. These messages are best * effort; do not expect a framework message to be retransmitted in * any reliable fashion. */ void frameworkMessage(SchedulerDriver* driver, const ExecutorID& executorId, const SlaveID& slaveId, const string& data); /* * Invoked when a slave has been determined unreachable (e.g., * machine failure, network partition). Most frameworks will need to * reschedule any tasks launched on this slave on a new slave. */ void slaveLost(SchedulerDriver* driver, const SlaveID& slaveId); /* * Invoked when an executor has exited/terminated. Note that any * tasks running will have TASK_LOST status updates automagically * generated. */ void executorLost(SchedulerDriver* driver, const ExecutorID& executorId, const SlaveID& slaveId, int status); /* * Invoked when there is an unrecoverable error in the scheduler or * scheduler driver. The driver will be aborted BEFORE invoking this * callback. */ void error(SchedulerDriver* driver, const string& message); }; #endif
36.729167
106
0.688032
ct-clmsn
22d08658b777409f18733b12d901ad175b0232e0
3,435
cpp
C++
src/devices/bus/pce_ctrl/multitap.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/bus/pce_ctrl/multitap.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/bus/pce_ctrl/multitap.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:cam900 /********************************************************************** NEC PC Engine/TurboGrafx-16 Multi Tap emulation Based on SMS controller port emulation (devices\bus\sms_ctrl\*.*) by Fabio Priuli, PC engine emulation (mame\*\pce.*) by Charles MacDonald, Wilbert Pol, Angelo Salese First party model (PI-PD003, and US released TurboTap and DuoTap) has allowed up to 5 controllers, Third-party Multi Taps are has allowed up to 2-4 controllers, and also compatible? **********************************************************************/ #include "emu.h" #include "multitap.h" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** DEFINE_DEVICE_TYPE(PCE_MULTITAP, pce_multitap_device, "pce_multitap", "NEC PC Engine/TurboGrafx-16 Multi Tap") //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // pce_multitap_device - constructor //------------------------------------------------- pce_multitap_device::pce_multitap_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : device_t(mconfig, PCE_MULTITAP, tag, owner, clock), device_pce_control_port_interface(mconfig, *this), m_subctrl_port(*this, "ctrl%u", 1U), m_port_sel(0), m_prev_sel(0) { } //------------------------------------------------- // device_add_mconfig - add device configuration //------------------------------------------------- void pce_multitap_device::device_add_mconfig(machine_config &config) { for (auto & elem : m_subctrl_port) PCE_CONTROL_PORT(config, elem, pce_control_port_devices, "joypad2"); } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void pce_multitap_device::device_start() { save_item(NAME(m_port_sel)); save_item(NAME(m_prev_sel)); } //------------------------------------------------- // device_reset - device-specific reset //------------------------------------------------- void pce_multitap_device::device_reset() { m_port_sel = 0; m_prev_sel = false; } //------------------------------------------------- // peripheral_r - multitap read //------------------------------------------------- u8 pce_multitap_device::peripheral_r() { u8 data = 0xf; if (m_port_sel < 5) // up to 5 controller ports data = m_subctrl_port[m_port_sel]->port_r(); return data; } //------------------------------------------------- // sel_w - SEL pin write, with port select //------------------------------------------------- void pce_multitap_device::sel_w(int state) { for (auto & elem : m_subctrl_port) elem->sel_w(state); // bump counter on a low-to-high transition of SEL bit if ((!m_prev_sel) && state) m_port_sel = (m_port_sel + 1) & 7; m_prev_sel = state; } //------------------------------------------------- // clr_w - CLR pin write, with reset multitap //------------------------------------------------- void pce_multitap_device::clr_w(int state) { for (auto & elem : m_subctrl_port) elem->clr_w(state); // clear counter if Reset bit is set if (state) m_port_sel = 0; }
27.701613
118
0.477438
Robbbert
22d3f75ea7462e11aa08df5a39b79dc99476d536
5,437
cpp
C++
dev/Code/Framework/AzCore/Tests/BehaviorContext.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Code/Framework/AzCore/Tests/BehaviorContext.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
null
null
null
dev/Code/Framework/AzCore/Tests/BehaviorContext.cpp
santosh90n/lumberyard-1
9608bcf905bb60e9f326bd3fe8297381c22d83a6
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "TestTypes.h" #include <AzCore/RTTI/BehaviorContext.h> namespace UnitTest { using Counter0 = CreationCounter<16, 0>; class BehaviorClassTest : public AllocatorsFixture { public: void SetUp() override { AllocatorsFixture::SetUp(); Counter0::Reset(); m_context.Class<Counter0>("Counter0") ->Property("val", static_cast<int& (Counter0::*)()>(&Counter0::val), nullptr); m_counter0Class = m_context.m_typeToClassMap[azrtti_typeid<Counter0>()]; } AZ::BehaviorContext m_context; AZ::BehaviorClass* m_counter0Class; }; TEST_F(BehaviorClassTest, BehaviorClass_Create_WasCreated) { EXPECT_EQ(0, Counter0::s_count); auto instance1 = m_counter0Class->Create(); EXPECT_TRUE(instance1.IsValid()); EXPECT_EQ(1, Counter0::s_count); EXPECT_EQ(0, Counter0::s_copied); EXPECT_EQ(0, Counter0::s_moved); } TEST_F(BehaviorClassTest, BehaviorClass_CopyValid_WasCopied) { EXPECT_EQ(0, Counter0::s_count); auto instance1 = m_counter0Class->Create(); EXPECT_TRUE(instance1.IsValid()); EXPECT_EQ(1, Counter0::s_count); EXPECT_EQ(0, Counter0::s_copied); EXPECT_EQ(0, Counter0::s_moved); auto instance2 = m_counter0Class->Clone(instance1); EXPECT_TRUE(instance2.IsValid()); EXPECT_EQ(2, Counter0::s_count); EXPECT_EQ(1, Counter0::s_copied); EXPECT_EQ(0, Counter0::s_moved); } TEST_F(BehaviorClassTest, BehaviorClass_CopyInvalid_WasNoop) { EXPECT_EQ(0, Counter0::s_count); auto instance1 = m_counter0Class->Clone(AZ::BehaviorObject()); EXPECT_FALSE(instance1.IsValid()); EXPECT_EQ(0, Counter0::s_count); EXPECT_EQ(0, Counter0::s_copied); EXPECT_EQ(0, Counter0::s_moved); } TEST_F(BehaviorClassTest, BehaviorClass_Move_WasMoved) { EXPECT_EQ(0, Counter0::s_count); auto instance1 = m_counter0Class->Create(); EXPECT_TRUE(instance1.IsValid()); EXPECT_EQ(1, Counter0::s_count); EXPECT_EQ(0, Counter0::s_copied); EXPECT_EQ(0, Counter0::s_moved); auto instance2 = m_counter0Class->Move(AZStd::move(instance1)); EXPECT_TRUE(instance2.IsValid()); EXPECT_EQ(1, Counter0::s_count); EXPECT_EQ(0, Counter0::s_copied); EXPECT_EQ(1, Counter0::s_moved); } TEST_F(BehaviorClassTest, BehaviorClass_MoveInvalid_WasNoop) { EXPECT_EQ(0, Counter0::s_count); auto instance1 = m_counter0Class->Move(AZ::BehaviorObject()); EXPECT_FALSE(instance1.IsValid()); EXPECT_EQ(0, Counter0::s_count); EXPECT_EQ(0, Counter0::s_copied); EXPECT_EQ(0, Counter0::s_moved); } class ClassWithConstMethod { public: AZ_TYPE_INFO(ClassWithConstMethod, "{39235130-3339-41F6-AC70-0D6EF6B5145D}"); void ConstMethod() const { } }; using BehaviorContextConstTest = AllocatorsFixture; TEST_F(BehaviorContextConstTest, BehaviorContext_BindConstMethods_Compiles) { AZ::BehaviorContext bc; bc.Class<ClassWithConstMethod>() ->Method("ConstMethod", &ClassWithConstMethod::ConstMethod) ; } class EBusWithConstEvent : public AZ::EBusTraits { public: virtual void ConstEvent() const = 0; }; using EBusWithConstEventBus = AZ::EBus<EBusWithConstEvent>; TEST_F(BehaviorContextConstTest, BehaviorContext_BindConstEvents_Compiles) { AZ::BehaviorContext bc; bc.EBus<EBusWithConstEventBus>("EBusWithConstEventBus") ->Event("ConstEvent", &EBusWithConstEvent::ConstEvent) ; } void MethodAcceptingTemplate(const AZStd::string&) { } using BehaviorContext = AllocatorsFixture; TEST_F(BehaviorContext, OnDemandReflection_Unreflect_IsRemoved) { AZ::BehaviorContext behaviorContext; // Test reflecting with OnDemandReflection behaviorContext.Method("TestTemplatedOnDemandReflection", &MethodAcceptingTemplate); EXPECT_TRUE(behaviorContext.IsOnDemandTypeReflected(azrtti_typeid<AZStd::string>())); EXPECT_NE(behaviorContext.m_typeToClassMap.find(azrtti_typeid<AZStd::string>()), behaviorContext.m_typeToClassMap.end()); // Test unreflecting OnDemandReflection behaviorContext.EnableRemoveReflection(); behaviorContext.Method("TestTemplatedOnDemandReflection", &MethodAcceptingTemplate); behaviorContext.DisableRemoveReflection(); EXPECT_FALSE(behaviorContext.IsOnDemandTypeReflected(azrtti_typeid<AZStd::string>())); EXPECT_EQ(behaviorContext.m_typeToClassMap.find(azrtti_typeid<AZStd::string>()), behaviorContext.m_typeToClassMap.end()); } }
31.982353
129
0.672246
crazyskateface
22d4efa61a2022a19c855203188626d17ad1e5c2
1,343
cpp
C++
tests/code/pdu/UserIdentityAC.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
72
2016-02-04T00:41:02.000Z
2022-03-18T18:10:34.000Z
tests/code/pdu/UserIdentityAC.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
74
2016-01-11T16:04:46.000Z
2021-11-18T16:36:11.000Z
tests/code/pdu/UserIdentityAC.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
23
2016-04-27T07:14:56.000Z
2021-09-28T21:59:31.000Z
#define BOOST_TEST_MODULE UserIdentityAC #include <boost/test/unit_test.hpp> #include <sstream> #include <string> #include "odil/Exception.h" #include "odil/pdu/UserIdentityAC.h" BOOST_AUTO_TEST_CASE(ConstructorDefault) { odil::pdu::UserIdentityAC const user_identity; BOOST_REQUIRE_EQUAL(user_identity.get_server_response(), ""); } BOOST_AUTO_TEST_CASE(ConstructorString) { odil::pdu::UserIdentityAC const user_identity("foo"); BOOST_REQUIRE_EQUAL(user_identity.get_server_response(), "foo"); } BOOST_AUTO_TEST_CASE(FromStream) { std::string const data( "\x59\x00\x00\x05" "\x00\x03" "foo", 9 ); std::istringstream stream(data); odil::pdu::UserIdentityAC const user_identity(stream); BOOST_REQUIRE_EQUAL(user_identity.get_server_response(), "foo"); } BOOST_AUTO_TEST_CASE(Type) { odil::pdu::UserIdentityAC user_identity; user_identity.set_server_response("foo"); BOOST_REQUIRE_EQUAL(user_identity.get_server_response(), "foo"); } BOOST_AUTO_TEST_CASE(Write) { odil::pdu::UserIdentityAC user_identity; user_identity.set_server_response("foo"); std::ostringstream data; data << user_identity; std::string const expected( "\x59\x00\x00\x05" "\x00\x03" "foo", 9 ); BOOST_REQUIRE_EQUAL(data.str(), expected); }
22.762712
68
0.71035
genisysram
22d57303f15f7f6fd1e9daf4d8331cb929c38c91
849
cpp
C++
Array/luobiao/DeleteNode.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
39
2020-05-31T06:14:39.000Z
2021-01-09T11:06:39.000Z
Array/luobiao/DeleteNode.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
7
2020-06-02T11:04:14.000Z
2020-06-11T14:11:58.000Z
Array/luobiao/DeleteNode.cpp
JessonYue/LeetCodeLearning
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
[ "MIT" ]
20
2020-05-31T06:21:57.000Z
2020-10-01T04:48:38.000Z
/** 请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 现有一个链表 -- head = [4,5,1,9],它可以表示为:   示例 1: 输入: head = [4,5,1,9], node = 5 输出: [4,1,9] 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9. 示例 2: 输入: head = [4,5,1,9], node = 1 输出: [4,5,9] 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.   说明: 链表至少包含两个节点。 链表中所有节点的值都是唯一的。 给定的节点为非末尾节点并且一定是链表中的一个有效节点。 不要从你的函数中返回任何结果。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/delete-node-in-a-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 解题思路:这道题主要考察链表,通过量表指向下下一个的值即可删除当前节点 **/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void deleteNode(ListNode* node) { node->val = node->next->val; node->next = node->next->next; } };
16.326923
64
0.639576
JessonYue
22d62a307f51a45b8905990dacdfc65973ff971f
6,313
cpp
C++
engine/source/kernel/storage/pack/storage_pack.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
engine/source/kernel/storage/pack/storage_pack.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
engine/source/kernel/storage/pack/storage_pack.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
#include "kernel/storage/pack/storage_pack.h" #include "kernel/core/core.h" #include "kernel/storage/logical/storage_system.h" namespace coffee { namespace storage { //-CONSTRUCTORS-------------------------------------------------------------------------------// Pack::Pack() : _FileAccess(NULL), _ItIsOpen(false) { } //--------------------------------------------------------------------------------------------// Pack::~Pack() { if (_FileAccess!=NULL) COFFEE_Delete(_FileAccess); } //-ACCESSORS----------------------------------------------------------------------------------// bool Pack::IsOpen() const { return _ItIsOpen; } //-QUERIES------------------------------------------------------------------------------------// uint32 Pack::FindFile(const Path& file_path) const { for (uint32 file_index=0 ; file_index<_FileArray.GetSize() ; ++file_index) { if (_FileArray[file_index]->GetPath()==file_path) return file_index; } return NONE; } //-OPERATIONS---------------------------------------------------------------------------------// bool Pack::Open(const Path& path, const MODE& mode) { if (_ItIsOpen) return true; COFFEE_Assert(_FileAccess==NULL, core::ERROR_CODE_Unexpected, "Unexpected error"); if (mode==MODE_Output && !System::Get().HasPath(path)) System::Get().SetFileData(path, Data(), true); _FileAccess = System::Get().GetFileAccess(path); if (_FileAccess==NULL) return false; _Mode = mode; if (mode==MODE_Output) { if (!System::Get().HasPath(path)) System::Get().SetFileData(path, Data(), true); if (!_FileAccess->Open(MODE_Input)) return false; _ReadFileList(); _FileAccess->Close(); if (!_FileAccess->Open(MODE_Output)) return false; } else { if (!_FileAccess->Open(MODE_Input)) return false; _ReadFileList(); } _ItIsOpen = true; return true; } //--------------------------------------------------------------------------------------------// void Pack::Close() { if (_ItIsOpen) { if (_Mode==MODE_Output) _WriteFileList(); _ItIsOpen = false; _FileAccess->Close(); COFFEE_Delete(_FileAccess); _FileAccess = NULL; _FileArray.Erase(); } } //--------------------------------------------------------------------------------------------// void Pack::AddFile(const Path& file_path, Stream& data_stream) { COFFEE_Assert(_Mode==MODE_Output, core::ERROR_CODE_IncorrectUsage, "Failed to write pack"); uint32 file_index = FindFile(file_path); PackFile* file; if (file_index!=NONE) { file = _FileArray[file_index]; } else { file = COFFEE_New(PackFile); _FileArray.AddItem(file); } file->SetPath(file_path); file->SetStream(&data_stream); } //--------------------------------------------------------------------------------------------// void Pack::RemoveFile(const Path& file_path) { COFFEE_Assert(_Mode==MODE_Output, core::ERROR_CODE_IncorrectUsage, "Failed to write pack"); uint32 file_index = FindFile(file_path); if (file_index!=NONE) _FileArray.Remove(file_index); } //--------------------------------------------------------------------------------------------// bool Pack::GetFile(const Path& file_path, Stream& data_stream) { COFFEE_Assert(_Mode==MODE_Input, core::ERROR_CODE_IncorrectUsage, "Failed to read pack"); uint32 file_index = FindFile(file_path); if (file_index!=NONE) { PackFile* file = _FileArray[file_index]; _FileAccess->SetOffset(file->GetOffset()); if (!data_stream.HasData()) data_stream.SetData(COFFEE_New(Data)); data_stream.GetData().Resize(file->GetSize()); _FileAccess->Read(data_stream.GetData().GetBuffer(), file->GetSize()); return true; } return false; } //-OPERATIONS---------------------------------------------------------------------------------// void Pack::_ReadFileList() { while (_FileAccess->GetOffset()<_FileAccess->GetSize()) { PackFile* file; basic::String path; ulong size; _FileAccess->ReadString(path); _FileAccess->Read((char*) &size, sizeof(ulong)); file = COFFEE_New(PackFile); file->SetPath(path); file->SetOffset(_FileAccess->GetOffset()); file->SetSize(size); if (_Mode==MODE_Output) { Stream* data_stream = COFFEE_New(Stream); data_stream->SetData(COFFEE_New(Data)); data_stream->GetData().Resize(file->GetSize()); _FileAccess->Read(data_stream->GetData().GetBuffer(), file->GetSize()); file->SetStream(data_stream); } else { _FileAccess->SetOffset(file->GetOffset() + size); } _FileArray.AddItem(file); } _FileAccess->SetOffset(0); } //--------------------------------------------------------------------------------------------// void Pack::_WriteFileList() { COFFEE_Assert(_Mode==MODE_Output, core::ERROR_CODE_IncorrectUsage, "Failed to write pack"); for (uint32 file_index=0 ; file_index<_FileArray.GetSize() ; ++file_index) { PackFile* file = _FileArray[file_index]; basic::String path = file->GetPath(); ulong size = file->GetStream().GetSize(); _FileAccess->WriteString(path); _FileAccess->Write((char *) &size, sizeof(ulong)); _FileAccess->Write(file->GetStream().GetData().GetBuffer(), size); } } } }
30.795122
100
0.456994
skarab
22e9d3b20d72b678ea7e97fcb5e007aa1610185d
256
cpp
C++
c++/day14/16.cpp
msoild/sword-to-offer
6c15c78ad773da0b66cb76c9e01292851aca45c5
[ "MIT" ]
null
null
null
c++/day14/16.cpp
msoild/sword-to-offer
6c15c78ad773da0b66cb76c9e01292851aca45c5
[ "MIT" ]
null
null
null
c++/day14/16.cpp
msoild/sword-to-offer
6c15c78ad773da0b66cb76c9e01292851aca45c5
[ "MIT" ]
null
null
null
class Solution { public: //notite size string replaceSpaces(string &str) { string retStr; for(auto&x : str) { if(x == ' ') retStr += "%20"; else retStr += x; } return retStr; } };
19.692308
41
0.445313
msoild
22ea37b938f0b2c9100cf6ee41dedbb3405887b2
805
cpp
C++
collection/cp/ACM_Notebook_new-master/tests/Graph/MaxFlow/Timus1664.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
1
2019-03-24T13:12:01.000Z
2019-03-24T13:12:01.000Z
collection/cp/ACM_Notebook_new-master/tests/Graph/MaxFlow/Timus1664.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
collection/cp/ACM_Notebook_new-master/tests/Graph/MaxFlow/Timus1664.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
// Problem: http://acm.timus.ru/problem.aspx?space=1&num=1664 #include "template.h" #include "buffered_reader.h" #include "Graph/MaxFlow/MaxFlow.h" int main() { freopen("input.txt", "r", stdin); int n, m; GN(n); REP(i,n) { int x, y; GN(x); GN(y); } MaxFlow flow(n); GN(m); while (m--) { int u, v, c; GN(u); GN(v); GN(c); --u; --v; flow.addEdge(u, v, c, true); } int res = flow.getFlow(0, n-1); printf("%d\n", res); for(int i = 0; i < flow.edges.size(); i += 2) { if (flow.edges[i].f > 0) { printf("%d %d %d\n", 1+flow.edges[i].u, 1+flow.edges[i].v, flow.edges[i].f); } else { printf("%d %d %d\n", 1+flow.edges[i].v, 1+flow.edges[i].u, flow.edges[i^1].f); } } }
23.676471
90
0.475776
daemonslayer
22ea8aa40bb2221e5d8ac46021c8a5e9d8647bfc
832
cpp
C++
1553f.cpp
wky32768/Mr.Shua
9c6c7f22c9f80f9af51e9e6e88ea91ac7965fb21
[ "MIT" ]
null
null
null
1553f.cpp
wky32768/Mr.Shua
9c6c7f22c9f80f9af51e9e6e88ea91ac7965fb21
[ "MIT" ]
null
null
null
1553f.cpp
wky32768/Mr.Shua
9c6c7f22c9f80f9af51e9e6e88ea91ac7965fb21
[ "MIT" ]
null
null
null
//https://www.cnblogs.com/alex-wei/p/CF1553.html #include <bits/stdc++.h> #define int long long #define For(i,a,b) for(int i=a;i<=b;i++) #define lb(x) x&(-x) using namespace std; const int N=500005; int n,a[N],ans,s; struct bit { int t[N]; void add(int x,int v) {while(x<N) {t[x]+=v;x+=lb(x);}} int query(int x) { //求前缀和 int ans=0; while(x) {ans+=t[x];x-=lb(x);} return ans; } } now,sav; signed main() { cin>>n; For(i,1,n) { cin>>a[i]; ans+=a[i]*(i-1)+s-sav.query(a[i]); for(int j=a[i];j<=N;j+=a[i]) { int mn=min(j+a[i],N); ans-=(now.query(mn-1)-now.query(j-1))*j; sav.add(j,j); sav.add(mn,-j); } now.add(a[i],1); s+=a[i]; cout<<ans<<' '; } return 0; }
25.212121
59
0.454327
wky32768
22f70065301093b05120eb7368a31226b284e244
482
cpp
C++
Teaching-Algorithms/lectures/02 - greedy algorithms/02 - dijkstras shortest path/lecture code/cpp/lecture/lecture/main.cpp
AshleighRobie/Spring-2019-CS-212
12dd7252d1d1580ff6132985a5f1d752c3d1a2d8
[ "Apache-2.0" ]
null
null
null
Teaching-Algorithms/lectures/02 - greedy algorithms/02 - dijkstras shortest path/lecture code/cpp/lecture/lecture/main.cpp
AshleighRobie/Spring-2019-CS-212
12dd7252d1d1580ff6132985a5f1d752c3d1a2d8
[ "Apache-2.0" ]
null
null
null
Teaching-Algorithms/lectures/02 - greedy algorithms/02 - dijkstras shortest path/lecture code/cpp/lecture/lecture/main.cpp
AshleighRobie/Spring-2019-CS-212
12dd7252d1d1580ff6132985a5f1d752c3d1a2d8
[ "Apache-2.0" ]
null
null
null
#include "CampusGraph.h"; #include "CsvParser.h" int main(void) { //Example of how to parse a CSV file for graph building CsvStateMachine csm{ "data.csv" }; vector<vector<string>> data = csm.processFile(); CampusGraph graph{}; graph.addVertex("a"); graph.addVertex("b"); graph.addVertex("c"); graph.connectVertex("a", "b", 3, true); graph.connectVertex("a", "c", 15); graph.connectVertex("b", "c", 7, true); auto distances = graph.computeShortestPath("a"); return 0; }
25.368421
56
0.682573
AshleighRobie
22f8b342aba95d8164beb293b3881536556a0fda
2,251
cpp
C++
day3/2.cpp
gian21391/advent_of_code-2021
2aa55a96e73cf7bb5ad152677e2136ca4eca1552
[ "MIT" ]
null
null
null
day3/2.cpp
gian21391/advent_of_code-2021
2aa55a96e73cf7bb5ad152677e2136ca4eca1552
[ "MIT" ]
null
null
null
day3/2.cpp
gian21391/advent_of_code-2021
2aa55a96e73cf7bb5ad152677e2136ca4eca1552
[ "MIT" ]
null
null
null
// // Created by Gianluca on 03/12/2021. // SPDX-License-Identifier: MIT // #include <utility/enumerate.hpp> #include <fstream> #include <cassert> #include <vector> #include <iostream> struct bit_values { int zeros = 0; int ones = 0; }; int main() { auto file = std::ifstream("../day3/input"); assert(file.is_open()); std::vector<bit_values> common_bits; std::vector<std::string> values; bool first_iteration = true; for(std::string line; std::getline(file, line);) { values.emplace_back(line); if (first_iteration) { common_bits.resize(line.size()); first_iteration = false; } for (auto [i, item] : enumerate(line)) { if (item == '0') common_bits[i].zeros++; else common_bits[i].ones++; } } std::vector<std::string> oxygen_values(values); std::vector<bit_values> oxygen_common_bits(common_bits); int i = 0; int remove_bit = -1; while (oxygen_values.size() > 1) { if (oxygen_common_bits[i].zeros > oxygen_common_bits[i].ones) remove_bit = 0; else remove_bit = 1; std::erase_if(oxygen_values, [&](auto value){ return (value[i] - '0') == remove_bit; }); oxygen_common_bits.clear(); oxygen_common_bits.resize(common_bits.size()); for (const auto& line : oxygen_values) { for (auto [j, item]: enumerate(line)) { if (item == '0') oxygen_common_bits[j].zeros++; else oxygen_common_bits[j].ones++; } } i++; } std::vector<std::string> co2_values(values); std::vector<bit_values> co2_common_bits(common_bits); i = 0; remove_bit = -1; while (co2_values.size() > 1) { if (co2_common_bits[i].zeros <= co2_common_bits[i].ones) remove_bit = 0; else remove_bit = 1; std::erase_if(co2_values, [&](auto value){ return (value[i] - '0') == remove_bit;}); co2_common_bits.clear(); co2_common_bits.resize(common_bits.size()); for (const auto& line : co2_values) { for (auto [j, item]: enumerate(line)) { if (item == '0') co2_common_bits[j].zeros++; else co2_common_bits[j].ones++; } } i++; } int oxygen = std::stoi(oxygen_values[0], nullptr, 2); int co2 = std::stoi(co2_values[0], nullptr, 2); std::cout << oxygen * co2 << std::endl; return 0; }
26.797619
92
0.625944
gian21391
22f92505909979895d6ff6045bbe2e6634e2477a
2,313
cpp
C++
thirdparty/threadpool/util.cpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
thirdparty/threadpool/util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
thirdparty/threadpool/util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
#define NOMINMAX #include "util.h" #include "hwloc.h" #include <algorithm> namespace concurrency { static hwloc_topology_t hwloc_topology_handle; bool HaveHWLocTopology() { // One time initialization static bool init = []() { if (hwloc_topology_init(&hwloc_topology_handle)) { //LOG(ERROR) << "Call to hwloc_topology_init() failed"; return false; } if (hwloc_topology_load(hwloc_topology_handle)) { //LOG(ERROR) << "Call to hwloc_topology_load() failed"; return false; } return true; }(); return init; } // Return the first hwloc object of the given type whose os_index // matches 'index'. hwloc_obj_t GetHWLocTypeIndex(hwloc_obj_type_t tp, int index) { hwloc_obj_t obj = nullptr; if (index >= 0) { while ((obj = hwloc_get_next_obj_by_type(hwloc_topology_handle, tp, obj)) != nullptr) { if (obj->os_index == index) break; } } return obj; } bool NUMAEnabled() { return (NUMANumNodes() > 1); } int NUMANumNodes() { if (HaveHWLocTopology()) { int num_numanodes = hwloc_get_nbobjs_by_type(hwloc_topology_handle, HWLOC_OBJ_NUMANODE); return std::max(1, num_numanodes); } else { return 1; } } void NUMASetThreadNodeAffinity(int node) { // Find the corresponding NUMA node topology object. hwloc_obj_t obj = GetHWLocTypeIndex(HWLOC_OBJ_NUMANODE, node); if (obj) { hwloc_set_cpubind(hwloc_topology_handle, obj->cpuset, HWLOC_CPUBIND_THREAD | HWLOC_CPUBIND_STRICT); } else { //LOG(ERROR) << "Could not find hwloc NUMA node " << node; } } int NUMAGetThreadNodeAffinity() { int node_index = kNUMANoAffinity; if (HaveHWLocTopology()) { hwloc_cpuset_t thread_cpuset = hwloc_bitmap_alloc(); hwloc_get_cpubind(hwloc_topology_handle, thread_cpuset, HWLOC_CPUBIND_THREAD); hwloc_obj_t obj = nullptr; // Return the first NUMA node whose cpuset is a (non-proper) superset of // that of the current thread. while ((obj = hwloc_get_next_obj_by_type( hwloc_topology_handle, HWLOC_OBJ_NUMANODE, obj)) != nullptr) { if (hwloc_bitmap_isincluded(thread_cpuset, obj->cpuset)) { node_index = obj->os_index; break; } } hwloc_bitmap_free(thread_cpuset); } return node_index; } }
28.207317
80
0.675746
lynex
22f9a3ef4f2362a80ba6c70ed0535f554d603db7
987
cc
C++
src/leetcode/leetcode226_invert_binary_tree.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
src/leetcode/leetcode226_invert_binary_tree.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
src/leetcode/leetcode226_invert_binary_tree.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
// https://leetcode-cn.com/problems/Invert-Binary-Tree/ #include <algorithm> using namespace std; #include "treenode.hpp" class Solution { public: TreeNode *invertTree(TreeNode *root) { if (root == nullptr) { return nullptr; } TreeNode *right_tree = root->right; root->right = invertTree(root->left); root->left = invertTree(right_tree); return root; } }; #include "gtest/gtest.h" TEST(leetcode226, sampleInputByProblem) { Solution solution; HeapTree in_nodes = {TNode(4), TNode(2), TNode(7), TNode(1), TNode(3), TNode(6), TNode(9)}; HeapTree expect_nodes = { TNode(4), TNode(7), TNode(2), TNode(9), TNode(6), TNode(3), TNode(9)}; ASSERT_EQ(7, solution.invertTree(BuildTree(in_nodes))->left->val); ASSERT_EQ(2, solution.invertTree(BuildTree(in_nodes))->right->val); ASSERT_EQ(6, solution.invertTree(BuildTree(in_nodes))->left->right->val); ASSERT_EQ(3, solution.invertTree(BuildTree(in_nodes))->right->left->val); }
25.973684
93
0.676798
zhaozigu
fe032b56a835584d8e8f23f127d456a6eeed5a7f
6,826
cpp
C++
Tests/C++/datastructures/RangeMinimumQuery2DStressTest.cpp
GoatGirl98/Resources
429c0ff357365dfff0b7df0c52346466d828ce93
[ "CC0-1.0" ]
36
2017-05-10T08:00:56.000Z
2022-03-18T15:21:57.000Z
Tests/C++/datastructures/RangeMinimumQuery2DStressTest.cpp
GoatGirl98/Resources
429c0ff357365dfff0b7df0c52346466d828ce93
[ "CC0-1.0" ]
90
2017-04-15T03:51:15.000Z
2020-06-16T00:39:33.000Z
Tests/C++/datastructures/RangeMinimumQuery2DStressTest.cpp
GoatGirl98/Resources
429c0ff357365dfff0b7df0c52346466d828ce93
[ "CC0-1.0" ]
17
2020-02-19T01:02:32.000Z
2021-12-21T06:28:34.000Z
#include <bits/stdc++.h> #include "../../../Content/C++/datastructures/SparseTable2D.h" #include "../../../Content/C++/datastructures/FischerHeunStructure2D.h" #include "../../../Content/C++/datastructures/trees/segmenttrees/SegmentTreeBottomUp2D.h" using namespace std; void test1() { const auto start_time = chrono::system_clock::now(); mt19937_64 rng(0); struct Min { int operator () (int a, int b) { return min(a, b); } }; int N = 500, M = 1000; vector<vector<int>> A(N, vector<int>(M)); for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1; SparseTable2D<int, Min> ST(A); int Q = 1; vector<int> ans; for (int i = 0; i < Q; i++) { int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M; if (u > d) swap(u, d); if (l > r) swap(l, r); ans.push_back(ST.query(u, d, l, r)); } const auto end_time = chrono::system_clock::now(); double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den)); cout << "Subtest 1 (Sparse Table) Passed" << endl; cout << " N: " << N << endl; cout << " M: " << M << endl; cout << " Q: " << Q << endl; cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl; long long checkSum = 0; for (auto &&a : ans) checkSum = 31 * checkSum + a; cout << " Checksum: " << checkSum << endl; } void test2() { const auto start_time = chrono::system_clock::now(); mt19937_64 rng(0); struct Min { int operator () (int a, int b) { return min(a, b); } }; int N = 500, M = 1000; vector<vector<int>> A(N, vector<int>(M)); for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1; SparseTable2D<int, Min> ST(A); int Q = 1e7; vector<int> ans; for (int i = 0; i < Q; i++) { int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M; if (u > d) swap(u, d); if (l > r) swap(l, r); ans.push_back(ST.query(u, d, l, r)); } const auto end_time = chrono::system_clock::now(); double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den)); cout << "Subtest 2 (Sparse Table) Passed" << endl; cout << " N: " << N << endl; cout << " M: " << M << endl; cout << " Q: " << Q << endl; cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl; long long checkSum = 0; for (auto &&a : ans) checkSum = 31 * checkSum + a; cout << " Checksum: " << checkSum << endl; } void test3() { const auto start_time = chrono::system_clock::now(); mt19937_64 rng(0); int N = 500, M = 1000; vector<vector<int>> A(N, vector<int>(M)); for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1; FischerHeunStructure2D<int, greater<int>> FHS(A); int Q = 1; vector<int> ans; for (int i = 0; i < Q; i++) { int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M; if (u > d) swap(u, d); if (l > r) swap(l, r); ans.push_back(FHS.query(u, d, l, r)); } const auto end_time = chrono::system_clock::now(); double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den)); cout << "Subtest 3 (Fischer Heun Structure) Passed" << endl; cout << " N: " << N << endl; cout << " M: " << M << endl; cout << " Q: " << Q << endl; cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl; long long checkSum = 0; for (auto &&a : ans) checkSum = 31 * checkSum + a; cout << " Checksum: " << checkSum << endl; } void test4() { const auto start_time = chrono::system_clock::now(); mt19937_64 rng(0); int N = 500, M = 1000; vector<vector<int>> A(N, vector<int>(M)); for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1; FischerHeunStructure2D<int, greater<int>> FHS(A); int Q = 1e7; vector<int> ans; for (int i = 0; i < Q; i++) { int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M; if (u > d) swap(u, d); if (l > r) swap(l, r); ans.push_back(FHS.query(u, d, l, r)); } const auto end_time = chrono::system_clock::now(); double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den)); cout << "Subtest 4 (Fischer Heun Structure) Passed" << endl; cout << " N: " << N << endl; cout << " M: " << M << endl; cout << " Q: " << Q << endl; cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl; long long checkSum = 0; for (auto &&a : ans) checkSum = 31 * checkSum + a; cout << " Checksum: " << checkSum << endl; } struct C { using Data = int; using Lazy = int; static Data qdef() { return numeric_limits<int>::max(); } static Data merge(const Data &l, const Data &r) { return min(l, r); } static Data applyLazy(const Data &, const Lazy &r) { return r; } }; void test5() { const auto start_time = chrono::system_clock::now(); mt19937_64 rng(0); int N = 500, M = 1000; vector<vector<int>> A(N, vector<int>(M)); for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1; SegmentTreeBottomUp2D<C> ST(A); int Q = 1; vector<int> ans; for (int i = 0; i < Q; i++) { int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M; if (u > d) swap(u, d); if (l > r) swap(l, r); ans.push_back(ST.query(u, d, l, r)); } const auto end_time = chrono::system_clock::now(); double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den)); cout << "Subtest 5 (Segment Tree) Passed" << endl; cout << " N: " << N << endl; cout << " M: " << M << endl; cout << " Q: " << Q << endl; cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl; long long checkSum = 0; for (auto &&a : ans) checkSum = 31 * checkSum + a; cout << " Checksum: " << checkSum << endl; } void test6() { const auto start_time = chrono::system_clock::now(); mt19937_64 rng(0); int N = 500, M = 1000; vector<vector<int>> A(N, vector<int>(M)); for (auto &&ai : A) for (auto &&aij : ai) aij = rng() % int(1e9) + 1; SegmentTreeBottomUp2D<C> ST(A); int Q = 1e7; vector<int> ans; for (int i = 0; i < Q; i++) { int u = rng() % N, d = rng() % N, l = rng() % M, r = rng() % M; if (u > d) swap(u, d); if (l > r) swap(l, r); ans.push_back(ST.query(u, d, l, r)); } const auto end_time = chrono::system_clock::now(); double sec = ((end_time - start_time).count() / double(chrono::system_clock::period::den)); cout << "Subtest 6 (Segment Tree) Passed" << endl; cout << " N: " << N << endl; cout << " M: " << M << endl; cout << " Q: " << Q << endl; cout << " Time: " << fixed << setprecision(3) << sec << "s" << endl; long long checkSum = 0; for (auto &&a : ans) checkSum = 31 * checkSum + a; cout << " Checksum: " << checkSum << endl; } int main() { test1(); test2(); test3(); test4(); test5(); test6(); cout << "Test Passed" << endl; return 0; }
35.367876
93
0.543217
GoatGirl98
fe083697651f5529af34a59b39b2229678d9ad23
1,479
cpp
C++
Conta/src/conta.cpp
Italo1994/LAB03
6a0137690174c15f64cf54df9c4ceec7f05c2c19
[ "MIT" ]
null
null
null
Conta/src/conta.cpp
Italo1994/LAB03
6a0137690174c15f64cf54df9c4ceec7f05c2c19
[ "MIT" ]
null
null
null
Conta/src/conta.cpp
Italo1994/LAB03
6a0137690174c15f64cf54df9c4ceec7f05c2c19
[ "MIT" ]
null
null
null
#include <string> #include "conta.h" using std::string; Conta::Conta(string m_agencia, int m_numero, double m_saldo, string m_status, double m_limite, double m_limiteDisponivel, int m_movimentacao, int m_numMovimentacoes) : agencia(m_agencia), numero(m_numero), saldo(m_saldo), status(m_status), limite(m_limite), limiteDisponivel(m_limiteDisponivel), movimentacoes(m_movimentacao), numMovimentacao(m_numMovimentacoes) { } Conta::Conta(){ } Conta::~Conta(){ } void Conta::setAgencia(string m_agencia){ agencia = m_agencia; } void Conta::setNumero(int m_numero){ numero = m_numero; } void Conta::setSaldo(double m_saldo){ saldo = m_saldo; } void Conta::setStatus(string m_status){ status = m_status; } void Conta::setLimite(double m_limite){ limite = m_limite; } void Conta::setMovimentacoes(int m_movimentacoes){ movimentacoes = m_movimentacoes; } void Conta::setNumMovimentacoes(int m_numMov){ numMovimentacao = m_numMov; } void Conta::setId(int m_idConta){ idConta = m_idConta; } string Conta::getAgencia(){ return agencia; } int Conta::getNumero(){ return numero; } double Conta::getSaldo(){ return saldo; } string Conta::getStatus(){ return status; } double Conta::getLimite(){ return limite; } int Conta::getMovimentacoes(){ return movimentacoes; } int Conta::getId(){ return idConta; } int Conta::getNumMovimentacoes(){ return numMovimentacao; } int Conta::totalContas = 0;
17.4
198
0.716024
Italo1994
fe0911dcb842e5ffe140d34cc914a5fbd5fc8d6b
1,295
cc
C++
file_position.cc
codedumper1/mysql-ripple
bb9e3656519597c97d2c67ace918022c9b669d58
[ "Apache-2.0" ]
358
2019-01-25T22:47:12.000Z
2022-03-25T09:35:03.000Z
file_position.cc
codedumper1/mysql-ripple
bb9e3656519597c97d2c67ace918022c9b669d58
[ "Apache-2.0" ]
30
2019-01-29T22:13:30.000Z
2022-01-07T01:50:33.000Z
file_position.cc
codedumper1/mysql-ripple
bb9e3656519597c97d2c67ace918022c9b669d58
[ "Apache-2.0" ]
44
2019-01-28T06:34:45.000Z
2022-01-15T09:36:58.000Z
// Copyright 2018 The Ripple Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "file_position.h" #include "absl/strings/numbers.h" namespace mysql_ripple { bool FilePosition::Parse(absl::string_view sv) { if (sv.size() <= 1) { return false; } if (sv.front() == '\'' && sv.back() == '\'') { sv = sv.substr(1, sv.size() - 2); } else { if (sv.front() == '\'' || sv.back() == '\'') { return false; } } auto pos = sv.find(':'); if (pos == 0 || pos == absl::string_view::npos) { return false; } filename = std::string(sv.substr(0, pos)); return absl::SimpleAtoi(sv.substr(pos + 1), &offset); } std::string FilePosition::ToString() const { return filename + ":" + std::to_string(offset); } } // namespace mysql_ripple
26.979167
75
0.648649
codedumper1
fe09186af8bdb23aa48d1b950473fe8d7e26f176
230
cpp
C++
SculptEngine/CppLib/src/Collisions/Ray.cpp
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
2
2019-12-14T02:06:52.000Z
2022-01-12T19:25:03.000Z
SculptEngine/CppLib/src/Collisions/Ray.cpp
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
1
2020-02-08T07:34:49.000Z
2020-02-08T07:34:49.000Z
SculptEngine/CppLib/src/Collisions/Ray.cpp
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
1
2019-01-27T22:32:49.000Z
2019-01-27T22:32:49.000Z
#include "Ray.h" #ifdef __EMSCRIPTEN__ #include <emscripten/bind.h> using namespace emscripten; EMSCRIPTEN_BINDINGS(Ray) { class_<Ray>("Ray") .constructor<Vector3 const&, Vector3 const&, float>(); } #endif // __EMSCRIPTEN__
17.692308
56
0.734783
ErwanLeGoffic
fe0af7278502ff2500ff9a70862a33d3c134cb55
2,177
hpp
C++
Lab2/Lab2/CircularQueue.hpp
erickque/mte-140
d6d48a72b51c8223fa95655be132fe5b18bd8e7d
[ "BSD-4-Clause-UC" ]
null
null
null
Lab2/Lab2/CircularQueue.hpp
erickque/mte-140
d6d48a72b51c8223fa95655be132fe5b18bd8e7d
[ "BSD-4-Clause-UC" ]
null
null
null
Lab2/Lab2/CircularQueue.hpp
erickque/mte-140
d6d48a72b51c8223fa95655be132fe5b18bd8e7d
[ "BSD-4-Clause-UC" ]
null
null
null
// CircularQueue implements a queue using an array as a circular track. #ifndef CIRCULAR_QUEUE_HPP #define CIRCULAR_QUEUE_HPP class CircularQueue { friend class CircularQueueTest; public: // Can be seen outside as CircularQueue::QueueItem typedef int QueueItem; // Used as an indicator of empty queue. static const QueueItem EMPTY_QUEUE; // Default constructor used to initialise the circular queue class. // Default capacity is 16. CircularQueue(); CircularQueue(unsigned int capacity); // Destructor. ~CircularQueue(); // Takes as an argument a QueueItem value. If the queue is not full, it // inserts the value at the rear of the queue (after the last item), and // returns true. It returns false if the process fails. bool enqueue(QueueItem value); // Returns the value at the front of the queue. If the queue is not empty, // the front item is removed from it. If the queue was empty before the // dequeue, the EMPTY_QUEUE constant is returned. QueueItem dequeue(); // Returns the value at the front of the queue without removing it from the // queue. If the queue was empty before the peek, the EMPTY_QUEUE constant is // returned. QueueItem peek() const; // Returns true if the queue is empty and false otherwise. bool empty() const; // Returns true if the queue is full and false otherwise. bool full() const; // Returns the number of items in the queue. int size() const; // Rrints the queue items sequentially ordered from the front to the rear of // the queue. void print() const; private: // Override copy constructor and assignment operator in private so we can't // use them. CircularQueue(const CircularQueue& other) {} //CircularQueue operator=(const CircularQueue& other) {} private: // As the capacity is fixed, you may as well use an array here. QueueItem *items_; // Indices for keeping track of the circular array int head_, tail_; int capacity_; int size_; }; #endif
31.550725
82
0.663757
erickque
fe0d2a60ce5d58d05d1990d4b2b789db6efd05f9
7,042
cpp
C++
src/pose_predictor.cpp
asr-ros/asr_lib_pose_prediction_ism
656aca32a9f96080f4e4627b93e81e59030f0d27
[ "BSD-3-Clause" ]
1
2019-10-29T13:37:21.000Z
2019-10-29T13:37:21.000Z
src/pose_predictor.cpp
asr-ros/asr_lib_pose_prediction_ism
656aca32a9f96080f4e4627b93e81e59030f0d27
[ "BSD-3-Clause" ]
null
null
null
src/pose_predictor.cpp
asr-ros/asr_lib_pose_prediction_ism
656aca32a9f96080f4e4627b93e81e59030f0d27
[ "BSD-3-Clause" ]
1
2019-11-03T13:58:52.000Z
2019-11-03T13:58:52.000Z
/** Copyright (c) 2016, Heizmann Heinrich, Heller Florian, Meißner Pascal, Stöckle Patrick All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "pose_prediction_ism/pose_predictor.h" #include "ISM/utility/GeometryHelper.hpp" #include "Eigen/Geometry" namespace pose_prediction_ism { PosePredictor::PosePredictor(std::string database_filename, std::string name_space, PredictorType predictor_type): NAME_SPACE_(name_space), PREDICTOR_TYPE_(predictor_type) { ROS_INFO_STREAM("Pose prediction is run with database " << database_filename); table_helper_ = ISM::TableHelperPtr(new ISM::TableHelper(database_filename)); int counter = 0; for(std::string pattern_name : table_helper_->getModelPatternNames()) { IsmObjectSet objects_in_pattern = table_helper_->getObjectTypesAndIdsBelongingToPattern(pattern_name); ISM::ObjectToVoteMap object_votes = table_helper_->getVoteSpecifiersForPatternAndObjects(pattern_name, objects_in_pattern); votes_[pattern_name] = object_votes; for (IsmObject object : objects_in_pattern) { specifiers_size_map_[object] = votes_ .at(pattern_name) .at(object.first) .at(object.second).size(); average_votes_ += specifiers_size_map_[object]; break; } counter ++; } average_votes_ = (average_votes_/counter); ROS_INFO("PosePredictor: averageVotes: %f", average_votes_); } PosePredictor::~PosePredictor() { } void PosePredictor::traverseISM(std::string pattern_name, unsigned int level) { std::string s = ""; for (unsigned int i = 0; i < level; ++i) s += "-"; s += ">"; ROS_DEBUG_STREAM(s << " patternName: " << pattern_name); IsmObjectSet objects_in_pattern = table_helper_->getObjectTypesAndIdsBelongingToPattern(pattern_name); for (IsmObject object : objects_in_pattern) traverseISM(object.first, level + 1); } ISM::PosePtr PosePredictor::predictPose(ISM::PosePtr reference_pose_ptr, IsmObjects path_to_object) { ROS_ASSERT_MSG(path_to_object.size() > 1 , "There must be more than one predecessor, otherwise all objects are in the reference"); ISM::PosePtr current_pose(reference_pose_ptr); for (IsmObjects::iterator predecessors_it = path_to_object.begin(); predecessors_it + 1 != path_to_object.end(); ++predecessors_it) { using namespace ISM; std::vector<VoteSpecifierPtr> specifiers = votes_ .at(predecessors_it->first) .at((predecessors_it + 1)->first) .at((predecessors_it + 1)->second); unsigned int index = rand() % specifiers.size(); VoteSpecifierPtr specifier = specifiers.at(index); PointPtr absolute_position = GeometryHelper::getSourcePoint(current_pose, specifier->refToObjectQuat, specifier->radius); Eigen::Quaterniond q; if(USE_RANDOMS){ double r_x, r_y, r_z; do{ r_x = udg_dist_->operator ()(); r_y = udg_dist_->operator ()(); r_z = udg_dist_->operator ()(); }while(std::sqrt(r_x * r_x + r_y * r_y + r_z * r_z) > SPHERE_RADIUS); absolute_position->eigen.x() = absolute_position->eigen.x() + r_x; absolute_position->eigen.y() = absolute_position->eigen.y() + r_y; absolute_position->eigen.z() = absolute_position->eigen.z() + r_z; r_x = udg_rot_->operator ()(); r_y = udg_rot_->operator ()(); r_z = udg_rot_->operator ()(); q = Eigen::AngleAxisd(GeometryHelper::deg2rad(r_x), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(GeometryHelper::deg2rad(r_y), Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(GeometryHelper::deg2rad(r_z), Eigen::Vector3d::UnitZ()); } PosePtr absolute_pose = GeometryHelper::getSourcePose(current_pose, absolute_position, specifier->refToObjectPoseQuat); current_pose = absolute_pose; if(USE_RANDOMS){ current_pose->quat = ISM::GeometryHelper::eigenQuatToQuat(ISM::GeometryHelper::quatToEigenQuat(current_pose->quat) * q); } } return current_pose; } /* ----------------- Setters ------------------ */ void PosePredictor::setFoundObjects(const FoundObjects &value) { found_objects_ = value; } /* ----------------- Getters ------------------ */ std::string PosePredictor::getMarkerNameSpace() const { return NAME_SPACE_; } AttributedPointCloud PosePredictor::getAttributedPointCloud() const { return attributed_point_cloud_; } PredictorType PosePredictor::getPredictorType() const { return PREDICTOR_TYPE_; } std::ostream &operator <<(std::ostream &strm, const PosePredictorPtr &pPtr) { return strm << (*pPtr); } std::ostream&operator <<(std::ostream &strm, const PosePredictor &p) { std::string type_string; switch (p.getPredictorType()) { case Shortest: type_string = "ShortestPath"; break; case Best: type_string = "BestPath";break; case Random: type_string = "RandomPath";break; case PPNonNor: type_string = "PaperPredictionNonNormalized";break; case PPNor: type_string = "PaperPredictionNormalized";break; default: type_string = "Unknown Predictor"; } return strm << type_string; } }
38.906077
755
0.665862
asr-ros
fe0f2bfa19b0795c6ee8bb1c7c22539c7de6030a
3,600
cpp
C++
source/kaldi_edit_distance.cpp
ShigekiKarita/kaldi-edit-distance
16987e0643f45097510af93ae7ced8a4bdc380fb
[ "Apache-2.0" ]
2
2019-09-09T07:52:29.000Z
2019-09-29T19:49:45.000Z
source/kaldi_edit_distance.cpp
ShigekiKarita/kaldi-edit-distance
16987e0643f45097510af93ae7ced8a4bdc380fb
[ "Apache-2.0" ]
null
null
null
source/kaldi_edit_distance.cpp
ShigekiKarita/kaldi-edit-distance
16987e0643f45097510af93ae7ced8a4bdc380fb
[ "Apache-2.0" ]
null
null
null
#include <sstream> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "edit-distance-inl.h" namespace py = pybind11; template <class T> kaldi::int32 edit_distance(const std::vector<T> &ref, const std::vector<T>& hyp) { return kaldi::LevenshteinEditDistance(ref, hyp); } struct ErrorStats { kaldi::int32 ins; kaldi::int32 del; kaldi::int32 sub; kaldi::int32 total; // minimum total cost to the current alignment. std::size_t ref; std::string to_string() const { std::stringstream ss; ss << "ErrorStats(total=" << total << ", ins_num=" << ins << ", del_num=" << del << ", sub_num=" << sub << ", ref_num=" << ref << ")"; return ss.str(); } static ErrorStats add(const ErrorStats& a, const ErrorStats& b) { return {a.ins + b.ins, a.del + b.del, a.sub + b.sub, a.total + b.total, a.ref + b.ref}; } }; template <class T> ErrorStats edit_distance_stats(const std::vector<T> &ref, const std::vector<T>& hyp) { ErrorStats e; e.total = kaldi::LevenshteinEditDistance(ref, hyp, &e.ins, &e.del, &e.sub); e.ref = ref.size(); return e; } template <class T> struct Alignment { T eps; std::vector<std::pair<T, T>> alignment; kaldi::int32 distance; }; template <class T> Alignment<T> align(const std::vector<T>& a, const std::vector<T>& b, T eps) { Alignment<T> ret = {eps}; ret.alignment.reserve(std::max(a.size(), b.size())); ret.distance = kaldi::LevenshteinAlignment(a, b, eps, &ret.alignment); return ret; } PYBIND11_MODULE(kaldi_edit_distance, m) { m.doc() = "python wrapper of kaldi edit-distance-inl.h"; py::class_<ErrorStats>(m, "ErrorStats", "error stats in Levelshtein edit distance") .def(py::init<>()) .def_readwrite("ins_num", &ErrorStats::ins) .def_readwrite("del_num", &ErrorStats::del) .def_readwrite("sub_num", &ErrorStats::sub) .def_readwrite("distance", &ErrorStats::total) .def_readwrite("ref_num", &ErrorStats::ref) .def("__repr__", &ErrorStats::to_string) .def("__add__", &ErrorStats::add); m.def("edit_distance", edit_distance<std::int64_t>, "Levelshtein edit distance between hyp and ref", py::arg("ref"), py::arg("hyp")); m.def("edit_distance", edit_distance<std::string>, "Levelshtein edit distance between hyp and ref", py::arg("ref"), py::arg("hyp")); m.def("edit_distance_stats", edit_distance_stats<std::int64_t>, "Levelshtein edit distance between hyp and ref", py::arg("ref"), py::arg("hyp")); m.def("edit_distance_stats", edit_distance_stats<std::string>, "Levelshtein edit distance between hyp and ref", py::arg("ref"), py::arg("hyp")); m.def("align", align<std::int64_t>, "Levelshtein alignment between hyp and ref", py::arg("a"), py::arg("b"), py::arg("eps")); m.def("align", align<std::string>, "Levelshtein alignment between hyp and ref", py::arg("a"), py::arg("b"), py::arg("eps")); py::class_<Alignment<std::int64_t>>(m, "IntAlignment", "alignment in Levelshtein edit distance") .def(py::init<>()) .def_readwrite("alignment", &Alignment<std::int64_t>::alignment) .def_readwrite("eps", &Alignment<std::int64_t>::eps); py::class_<Alignment<std::string>>(m, "StrAlignment", "alignment in Levelshtein edit distance") .def(py::init<>()) .def_readwrite("alignment", &Alignment<std::string>::alignment) .def_readwrite("eps", &Alignment<std::string>::eps); }
34.615385
116
0.619444
ShigekiKarita
fe107a95debad2e1e40da444af800d98800874c2
524
cpp
C++
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheModule.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
null
null
null
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheModule.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
null
null
null
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheModule.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
1
2021-01-22T09:11:51.000Z
2021-01-22T09:11:51.000Z
// Copyright Epic Games, Inc. All Rights Reserved. #include "GeometryCacheModule.h" #if WITH_EDITOR #include "GeometryCacheEdModule.h" #endif // WITH_EDITOR #include "CodecV1.h" IMPLEMENT_MODULE(FGeometryCacheModule, GeometryCache) void FGeometryCacheModule::StartupModule() { #if WITH_EDITOR FGeometryCacheEdModule& Module = FModuleManager::LoadModuleChecked<FGeometryCacheEdModule>(TEXT("GeometryCacheEd")); #endif FCodecV1Decoder::InitLUT(); } void FGeometryCacheModule::ShutdownModule() { }
22.782609
118
0.767176
greenrainstudios
fe155892e9600cdb57dc1b1cb6824d236828ed01
9,902
cpp
C++
drlvm/vm/gc_gen/src/mark_sweep/wspace_sweep.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
8
2015-11-04T06:06:35.000Z
2021-07-04T13:47:36.000Z
drlvm/vm/gc_gen/src/mark_sweep/wspace_sweep.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
1
2021-10-17T13:07:28.000Z
2021-10-17T13:07:28.000Z
drlvm/vm/gc_gen/src/mark_sweep/wspace_sweep.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
13
2015-11-27T03:14:50.000Z
2022-02-26T15:12:20.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "wspace_chunk.h" #include "wspace_mark_sweep.h" static Chunk_Header_Basic *volatile next_chunk_for_sweep; void gc_init_chunk_for_sweep(GC *gc, Wspace *wspace) { next_chunk_for_sweep = (Chunk_Header_Basic*)space_heap_start((Space*)wspace); next_chunk_for_sweep->adj_prev = NULL; unsigned int i = gc->num_collectors; while(i--){ Free_Chunk_List *list = gc->collectors[i]->free_chunk_list; assert(!list->head); assert(!list->tail); assert(list->lock == FREE_LOCK); } } void zeroing_free_chunk(Free_Chunk *chunk) { //Modified this assertion for concurrent sweep //assert(chunk->status == CHUNK_FREE); assert(chunk->status & CHUNK_FREE); void *start = (void*)((POINTER_SIZE_INT)chunk + sizeof(Free_Chunk)); POINTER_SIZE_INT size = CHUNK_SIZE(chunk) - sizeof(Free_Chunk); memset(start, 0, size); } /* Zeroing should be optimized to do it while sweeping index word */ static void zeroing_free_areas_in_pfc(Chunk_Header *chunk, unsigned int live_num) { assert(live_num); assert(chunk->status & CHUNK_NORMAL); unsigned int slot_num = chunk->slot_num; unsigned int slot_size = chunk->slot_size; POINTER_SIZE_INT chunk_base = (POINTER_SIZE_INT)chunk->base; POINTER_SIZE_INT *table = chunk->table; POINTER_SIZE_INT base = (POINTER_SIZE_INT)NULL; assert(slot_num >= live_num); unsigned int free_slot_num = slot_num - live_num; unsigned int cur_free_slot_num = 0; unsigned int slot_index = chunk->slot_index; unsigned int word_index = slot_index / SLOT_NUM_PER_WORD_IN_TABLE; assert(live_num >= slot_index); live_num -= slot_index; POINTER_SIZE_INT index_word = table[word_index]; POINTER_SIZE_INT mark_color = cur_mark_black_color << (COLOR_BITS_PER_OBJ * (slot_index % SLOT_NUM_PER_WORD_IN_TABLE)); for(; slot_index < slot_num; ++slot_index){ assert(!(index_word & ~cur_mark_mask)); if(index_word & mark_color){ if(cur_free_slot_num){ memset((void*)base, 0, slot_size*cur_free_slot_num); assert(free_slot_num >= cur_free_slot_num); free_slot_num -= cur_free_slot_num; cur_free_slot_num = 0; if(!free_slot_num) break; } assert(live_num); --live_num; } else { if(cur_free_slot_num){ ++cur_free_slot_num; } else { base = chunk_base + slot_size * slot_index; cur_free_slot_num = 1; if(!live_num) break; } } mark_color <<= COLOR_BITS_PER_OBJ; if(!mark_color){ mark_color = cur_mark_black_color; ++word_index; index_word = table[word_index]; while(index_word == cur_mark_mask && cur_free_slot_num == 0 && slot_index < slot_num){ slot_index += SLOT_NUM_PER_WORD_IN_TABLE; ++word_index; index_word = table[word_index]; assert(live_num >= SLOT_NUM_PER_WORD_IN_TABLE); live_num -= SLOT_NUM_PER_WORD_IN_TABLE; } while(index_word == 0 && cur_free_slot_num > 0 && slot_index < slot_num){ slot_index += SLOT_NUM_PER_WORD_IN_TABLE; ++word_index; index_word = table[word_index]; cur_free_slot_num += SLOT_NUM_PER_WORD_IN_TABLE; } } } assert((cur_free_slot_num>0 && live_num==0) || (cur_free_slot_num==0 && live_num>0)); if(cur_free_slot_num) memset((void*)base, 0, slot_size*free_slot_num); } static void collector_sweep_normal_chunk(Collector *collector, Wspace *wspace, Chunk_Header *chunk) { unsigned int slot_num = chunk->slot_num; unsigned int live_num = 0; unsigned int first_free_word_index = MAX_SLOT_INDEX; POINTER_SIZE_INT *table = chunk->table; unsigned int index_word_num = (slot_num + SLOT_NUM_PER_WORD_IN_TABLE - 1) / SLOT_NUM_PER_WORD_IN_TABLE; for(unsigned int i=0; i<index_word_num; ++i){ table[i] &= cur_mark_mask; unsigned int live_num_in_word = (table[i] == cur_mark_mask) ? SLOT_NUM_PER_WORD_IN_TABLE : word_set_bit_num(table[i]); live_num += live_num_in_word; if((first_free_word_index == MAX_SLOT_INDEX) && (live_num_in_word < SLOT_NUM_PER_WORD_IN_TABLE)){ first_free_word_index = i; pfc_set_slot_index((Chunk_Header*)chunk, first_free_word_index, cur_mark_black_color); } } assert(live_num <= slot_num); collector->live_obj_size += live_num * chunk->slot_size; collector->live_obj_num += live_num; if(!live_num){ /* all objects in this chunk are dead */ collector_add_free_chunk(collector, (Free_Chunk*)chunk); } else { chunk->alloc_num = live_num; if(chunk_is_reusable(chunk)){ /* most objects in this chunk are swept, add chunk to pfc list*/ //chunk_pad_last_index_word((Chunk_Header*)chunk, cur_mark_mask); wspace_put_pfc(wspace, chunk); assert(chunk->next != chunk); }else{ /* the rest: chunks with free rate < PFC_REUSABLE_RATIO. we don't use them */ chunk->status = CHUNK_USED | CHUNK_NORMAL; wspace_reg_used_chunk(wspace,chunk); } } } static inline void collector_sweep_abnormal_chunk(Collector *collector, Wspace *wspace, Chunk_Header *chunk) { assert(chunk->status & CHUNK_ABNORMAL); POINTER_SIZE_INT *table = chunk->table; table[0] &= cur_mark_mask; if(!table[0]){ collector_add_free_chunk(collector, (Free_Chunk*)chunk); } else { chunk->status = CHUNK_ABNORMAL| CHUNK_USED; wspace_reg_used_chunk(wspace,chunk); collector->live_obj_size += CHUNK_SIZE(chunk); collector->live_obj_num++; } } void wspace_sweep(Collector *collector, Wspace *wspace) { Chunk_Header_Basic *chunk; collector->live_obj_size = 0; collector->live_obj_num = 0; chunk = wspace_grab_next_chunk(wspace, &next_chunk_for_sweep, TRUE); while(chunk){ /* chunk is free before GC */ if(chunk->status == CHUNK_FREE){ collector_add_free_chunk(collector, (Free_Chunk*)chunk); } else if(chunk->status & CHUNK_NORMAL){ /* chunk is used as a normal sized obj chunk */ collector_sweep_normal_chunk(collector, wspace, (Chunk_Header*)chunk); } else { /* chunk is used as a super obj chunk */ collector_sweep_abnormal_chunk(collector, wspace, (Chunk_Header*)chunk); } chunk = wspace_grab_next_chunk(wspace, &next_chunk_for_sweep, TRUE); } } /************ For merging free chunks in wspace ************/ static void merge_free_chunks_in_list(Wspace *wspace, Free_Chunk_List *list) { Free_Chunk *wspace_ceiling = (Free_Chunk*)space_heap_end((Space*)wspace); Free_Chunk *chunk = list->head; while(chunk){ assert(chunk->status == (CHUNK_FREE | CHUNK_TO_MERGE)); /* Remove current chunk from the chunk list */ list->head = chunk->next; if(list->head) list->head->prev = NULL; /* Check if the prev adjacent chunks are free */ Free_Chunk *prev_chunk = (Free_Chunk*)chunk->adj_prev; while(prev_chunk && prev_chunk->status == (CHUNK_FREE | CHUNK_TO_MERGE)){ assert(prev_chunk < chunk); /* Remove prev_chunk from list */ free_list_detach_chunk(list, prev_chunk); prev_chunk->adj_next = chunk->adj_next; chunk = prev_chunk; prev_chunk = (Free_Chunk*)chunk->adj_prev; } /* Check if the back adjcent chunks are free */ Free_Chunk *back_chunk = (Free_Chunk*)chunk->adj_next; while(back_chunk < wspace_ceiling && back_chunk->status == (CHUNK_FREE | CHUNK_TO_MERGE)){ assert(chunk < back_chunk); /* Remove back_chunk from list */ free_list_detach_chunk(list, back_chunk); back_chunk = (Free_Chunk*)back_chunk->adj_next; chunk->adj_next = (Chunk_Header_Basic*)back_chunk; } if(back_chunk < wspace_ceiling) back_chunk->adj_prev = (Chunk_Header_Basic*)chunk; /* put the free chunk to the according free chunk list */ wspace_put_free_chunk(wspace, chunk); chunk = list->head; } } void wspace_merge_free_chunks(GC *gc, Wspace *wspace) { Free_Chunk_List free_chunk_list; free_chunk_list.head = NULL; free_chunk_list.tail = NULL; /* Collect free chunks from collectors to one list */ for(unsigned int i=0; i<gc->num_collectors; ++i){ Free_Chunk_List *list = gc->collectors[i]->free_chunk_list; move_free_chunks_between_lists(&free_chunk_list, list); } merge_free_chunks_in_list(wspace, &free_chunk_list); } void wspace_remerge_free_chunks(GC *gc, Wspace *wspace) { Free_Chunk_List free_chunk_list; free_chunk_list.head = NULL; free_chunk_list.tail = NULL; /* If a new chunk is partitioned from a bigger one in the forwarding phase, * its adj_prev has not been set yet. * And the adj_prev field of the chunk next to it will be wrong either. * So a rebuilding operation is needed here. */ wspace_rebuild_chunk_chain(wspace); /* Collect free chunks from wspace free chunk lists to one list */ wspace_collect_free_chunks_to_list(wspace, &free_chunk_list); /* Collect free chunks from collectors to one list */ for(unsigned int i=0; i<gc->num_collectors; ++i){ Free_Chunk_List *list = gc->collectors[i]->free_chunk_list; move_free_chunks_between_lists(&free_chunk_list, list); } merge_free_chunks_in_list(wspace, &free_chunk_list); }
36.404412
122
0.707938
sirinath
fe1773f4e57c483aeb5dd5e7c9771ca215ff0e08
4,298
cpp
C++
expressions/aggregation/AggregationHandleMax.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
expressions/aggregation/AggregationHandleMax.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
expressions/aggregation/AggregationHandleMax.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include "expressions/aggregation/AggregationHandleMax.hpp" #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include "catalog/CatalogTypedefs.hpp" #include "expressions/aggregation/AggregationID.hpp" #include "storage/ValueAccessorMultiplexer.hpp" #include "types/Type.hpp" #include "types/TypedValue.hpp" #include "types/operations/comparisons/Comparison.hpp" #include "types/operations/comparisons/ComparisonFactory.hpp" #include "types/operations/comparisons/ComparisonID.hpp" #include "glog/logging.h" namespace quickstep { class ColumnVector; AggregationHandleMax::AggregationHandleMax(const Type &type) : AggregationConcreteHandle(AggregationID::kMax), type_(type) { fast_comparator_.reset( ComparisonFactory::GetComparison(ComparisonID::kGreater) .makeUncheckedComparatorForTypes(type, type.getNonNullableVersion())); } AggregationState* AggregationHandleMax::accumulateValueAccessor( const std::vector<MultiSourceAttributeId> &argument_ids, const ValueAccessorMultiplexer &accessor_mux) const { DCHECK_EQ(1u, argument_ids.size()) << "Got wrong number of attributes for MAX: " << argument_ids.size(); const ValueAccessorSource argument_source = argument_ids.front().source; const attribute_id argument_id = argument_ids.front().attr_id; DCHECK(argument_source != ValueAccessorSource::kInvalid); DCHECK_NE(argument_id, kInvalidAttributeID); return new AggregationStateMax(fast_comparator_->accumulateValueAccessor( type_.getNullableVersion().makeNullValue(), accessor_mux.getValueAccessorBySource(argument_source), argument_id)); } void AggregationHandleMax::mergeStates(const AggregationState &source, AggregationState *destination) const { const AggregationStateMax &max_source = static_cast<const AggregationStateMax &>(source); AggregationStateMax *max_destination = static_cast<AggregationStateMax *>(destination); if (!max_source.max_.isNull()) { compareAndUpdate(max_destination, max_source.max_); } } void AggregationHandleMax::mergeStates(const std::uint8_t *source, std::uint8_t *destination) const { const TypedValue *src_max_ptr = reinterpret_cast<const TypedValue *>(source); TypedValue *dst_max_ptr = reinterpret_cast<TypedValue *>(destination); if (!(src_max_ptr->isNull())) { compareAndUpdate(dst_max_ptr, *src_max_ptr); } } ColumnVector* AggregationHandleMax::finalizeHashTable( const AggregationStateHashTableBase &hash_table, const std::size_t index, std::vector<std::vector<TypedValue>> *group_by_keys) const { return finalizeHashTableHelper<AggregationHandleMax>( type_, hash_table, index, group_by_keys); } AggregationState* AggregationHandleMax::aggregateOnDistinctifyHashTableForSingle( const AggregationStateHashTableBase &distinctify_hash_table) const { return aggregateOnDistinctifyHashTableForSingleUnaryHelper< AggregationHandleMax, AggregationStateMax>( distinctify_hash_table); } void AggregationHandleMax::aggregateOnDistinctifyHashTableForGroupBy( const AggregationStateHashTableBase &distinctify_hash_table, const std::size_t index, AggregationStateHashTableBase *aggregation_hash_table) const { aggregateOnDistinctifyHashTableForGroupByUnaryHelper<AggregationHandleMax>( distinctify_hash_table, index, aggregation_hash_table); } } // namespace quickstep
38.035398
81
0.769195
Hacker0912
fe1c6d9cf0ecdbdb8208238cd6a9b65aadee961b
1,993
cc
C++
chrome/renderer/navigation_state.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/renderer/navigation_state.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/renderer/navigation_state.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/navigation_state.h" #include "chrome/renderer/user_script_idle_scheduler.h" #include "webkit/glue/alt_error_page_resource_fetcher.h" #include "webkit/glue/password_form.h" NavigationState::~NavigationState() {} void NavigationState::set_user_script_idle_scheduler( UserScriptIdleScheduler* scheduler) { user_script_idle_scheduler_.reset(scheduler); } void NavigationState::set_password_form_data(webkit_glue::PasswordForm* data) { password_form_data_.reset(data); } void NavigationState::set_alt_error_page_fetcher( webkit_glue::AltErrorPageResourceFetcher* f) { alt_error_page_fetcher_.reset(f); } NavigationState::NavigationState(PageTransition::Type transition_type, const base::Time& request_time, bool is_content_initiated, int32 pending_page_id, int pending_history_list_offset) : transition_type_(transition_type), load_type_(UNDEFINED_LOAD), request_time_(request_time), load_histograms_recorded_(false), request_committed_(false), is_content_initiated_(is_content_initiated), pending_page_id_(pending_page_id), pending_history_list_offset_(pending_history_list_offset), postpone_loading_data_(false), cache_policy_override_set_(false), cache_policy_override_(WebKit::WebURLRequest::UseProtocolCachePolicy), user_script_idle_scheduler_(NULL), http_status_code_(0), was_fetched_via_spdy_(false), was_npn_negotiated_(false), was_alternate_protocol_available_(false), was_fetched_via_proxy_(false), was_translated_(false), was_within_same_page_(false), was_prefetcher_(false), was_referred_by_prefetcher_(false) { }
36.907407
79
0.73156
Gitman1989
fe2243b3722b197b9f5544425a57ac2fb289dfc5
14,942
cpp
C++
Rendering/Renderer.cpp
CakeWithSteak/fpf
e3a48478215a5b8623f0df76f730534b545ae9c3
[ "MIT" ]
null
null
null
Rendering/Renderer.cpp
CakeWithSteak/fpf
e3a48478215a5b8623f0df76f730534b545ae9c3
[ "MIT" ]
null
null
null
Rendering/Renderer.cpp
CakeWithSteak/fpf
e3a48478215a5b8623f0df76f730534b545ae9c3
[ "MIT" ]
null
null
null
#include "glad/glad.h" #include "Renderer.h" #include <vector> #include <stdexcept> #include <cuda_runtime.h> #include <cuda_gl_interop.h> #include <driver_types.h> #include <algorithm> #include "../Computation/safeCall.h" #include "utils.h" #include "../Computation/shared_types.h" float data[] = { //XY position and UV coordinates -1, 1, 0, 0, //top left -1, -1, 0, 1, //bottom left 1, 1, 1, 0, //top right 1, 1, 1, 0, //top right -1, -1, 0, 1, //bottom left 1, -1, 1, 1, //bottom right }; void Renderer::init(std::string_view cudaCode) { glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); unsigned int VAOs[2]; glGenVertexArrays(2, VAOs); mainVAO = VAOs[0]; overlayVAO = VAOs[1]; unsigned int VBOs[2]; glGenBuffers(2, VBOs); unsigned int mainVBO = VBOs[0]; overlayLineVBO = VBOs[1]; //Init overlay structures glBindVertexArray(overlayVAO); glBindBuffer(GL_ARRAY_BUFFER, overlayLineVBO); glBufferData(GL_ARRAY_BUFFER, 2 * std::max(MAX_PATH_STEPS, SHAPE_TRANS_DEFAULT_POINTS) * sizeof(double), nullptr, GL_DYNAMIC_DRAW); //Line vertices glVertexAttribLPointer(0, 2, GL_DOUBLE, sizeof(double) * 2, nullptr); glEnableVertexAttribArray(0); //Init main structures glBindVertexArray(mainVAO); glBindBuffer(GL_ARRAY_BUFFER, mainVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); //Position glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(float) * 4, nullptr); glEnableVertexAttribArray(0); //UV glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(float) * 4, (void*)(sizeof(float) * 2)); glEnableVertexAttribArray(1); glLineWidth(2); glPointSize(4); initTextures(); initShaders(); initCuda(); initKernels(cudaCode); } void Renderer::initTextures(bool setupProxy) { unsigned int textures[2]; glGenTextures(setupProxy ? 2 : 1, textures); distTexture = textures[0]; if(setupProxy) { proxyTexture = textures[1]; //Init proxy texture glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, proxyTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, proxyTexture, 0); } //Init dist texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, distTexture); //Allocates one-channel float32 texture glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, width, height); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void Renderer::initShaders() { mainShader.use(); mainShader.setUniform("distances", 0); mainShader.setUniform("maxHue", mode.maxHue); minimumUniform = mainShader.getUniformLocation("minDist"); maximumUniform = mainShader.getUniformLocation("maxDist"); if(mode.staticMinMax.has_value()) { mainShader.setUniform(minimumUniform, mode.staticMinMax->first); mainShader.setUniform(maximumUniform, mode.staticMinMax->second); } overlayShader.use(); viewCenterUniform = overlayShader.getUniformLocation("viewportCenter"); viewBreadthUniform = overlayShader.getUniformLocation("viewportBreadth"); proxyShader.use(); proxyShader.setUniform("tex", 1); } void Renderer::initCuda(bool registerPathRes) { CUDA_SAFE(cudaSetDevice(0)); numBlocks = ceilDivide(width * height, 1024); CUDA_SAFE(cudaMallocManaged(&cudaBuffer, 2 * numBlocks * sizeof(float))); //Buffer for min/max fpdist values CUDA_SAFE(cudaGraphicsGLRegisterImage(&cudaSurfaceRes, distTexture, GL_TEXTURE_2D, cudaGraphicsRegisterFlagsSurfaceLoadStore)); cudaSurfaceDesc.resType = cudaResourceTypeArray; if(mode.isAttractor) { size_t numAttractors = static_cast<int>(width * ATTRACTOR_RESOLUTION_MULT) * static_cast<int>(height * ATTRACTOR_RESOLUTION_MULT); CUDA_SAFE(cudaMalloc(&attractorsDeviceBuffer, numAttractors * sizeof(HostFloatComplex))); attractorsHostBuffer = std::make_unique<HostFloatComplex[]>(numAttractors); } if(registerPathRes) { CUDA_SAFE(cudaMallocManaged(&cudaPathLengthPtr, sizeof(int))); CUDA_SAFE(cudaGraphicsGLRegisterBuffer(&overlayBufferRes, overlayLineVBO, cudaGraphicsRegisterFlagsWriteDiscard)); } } Renderer::~Renderer() { CUDA_SAFE(cudaGraphicsUnregisterResource(cudaSurfaceRes)); CUDA_SAFE(cudaGraphicsUnregisterResource(overlayBufferRes)); CUDA_SAFE(cudaFree(cudaBuffer)); CUDA_SAFE(cudaFree(cudaPathLengthPtr)); CUDA_SAFE(cudaFree(attractorsDeviceBuffer)); } void Renderer::render(int maxIters, double metricArg, const std::complex<double>& p, float colorCutoff) { pm.enter(PERF_RENDER); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); auto [start, end] = viewport.getCorners(); size_t numAttractors = (mode.isAttractor) ? findAttractors(maxIters, metricArg, p) : 0; CUDA_SAFE(cudaGraphicsMapResources(1, &cudaSurfaceRes)); auto surface = createSurface(); pm.enter(PERF_KERNEL); if(doublePrec) launch_kernel_double(kernel, start.real(), end.real(), start.imag(), end.imag(), maxIters, cudaBuffer, surface, width, height, p.real(), p.imag(), mode.prepMetricArg(metricArg), attractorsDeviceBuffer, numAttractors); else launch_kernel_float(kernel, start.real(), end.real(), start.imag(), end.imag(), maxIters, cudaBuffer, surface, width, height, p.real(), p.imag(), mode.prepMetricArg(metricArg), attractorsDeviceBuffer, numAttractors); CUDA_SAFE(cudaDeviceSynchronize()); pm.exit(PERF_KERNEL); CUDA_SAFE(cudaDestroySurfaceObject(surface)); CUDA_SAFE(cudaGraphicsUnmapResources(1, &cudaSurfaceRes)); mainShader.use(); if(!mode.staticMinMax.has_value()) { auto [min, max] = (mode.isAttractor) ? std::make_pair(0.0f, static_cast<float>(numAttractors)) : interleavedMinmax(cudaBuffer, 2 * numBlocks); mainShader.setUniform(minimumUniform, min); mainShader.setUniform(maximumUniform, std::min(max, colorCutoff)); std::cout << "Min: " << min << " max: " << max << "\n"; } glBindVertexArray(mainVAO); glDrawArrays(GL_TRIANGLES, 0, 6); if(isOverlayActive()) { refreshOverlayIfNeeded(p, metricArg); pm.enter(PERF_OVERLAY_RENDER); glBindVertexArray(overlayVAO); overlayShader.use(); overlayShader.setUniform(viewCenterUniform, viewport.getCenter().real(), viewport.getCenter().imag()); overlayShader.setUniform(viewBreadthUniform, viewport.getBreadth()); glDrawArrays(GL_POINTS, 0, getOverlayLength()); if(connectOverlayPoints) glDrawArrays(GL_LINE_STRIP, 0, getOverlayLength()); pm.exit(PERF_OVERLAY_RENDER); } pm.exit(PERF_RENDER); } void Renderer::paint() { glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindVertexArray(mainVAO); proxyShader.use(); glDrawArrays(GL_TRIANGLES, 0, 6); } cudaSurfaceObject_t Renderer::createSurface() { CUDA_SAFE(cudaGraphicsSubResourceGetMappedArray(&cudaSurfaceDesc.res.array.array, cudaSurfaceRes, 0, 0)); cudaSurfaceObject_t surface; CUDA_SAFE(cudaCreateSurfaceObject(&surface, &cudaSurfaceDesc)); return surface; } void Renderer::initKernels(std::string_view cudaCode) { auto funcs = compiler.Compile(cudaCode, "runtime.cu", {"kernel", "genFixedPointPath", "transformShape", "findAttractors"}, mode, doublePrec); kernel = funcs[0]; pathKernel = funcs[1]; shapeTransformKernel = funcs[2]; findAttractorsKernel = funcs[3]; } std::string Renderer::getPerformanceReport() { return pm.generateReports(); } void Renderer::resize(int newWidth, int newHeight) { width = newWidth; height = newHeight; CUDA_SAFE(cudaFree(cudaBuffer)); CUDA_SAFE(cudaFree(attractorsDeviceBuffer)); CUDA_SAFE(cudaGraphicsUnregisterResource(cudaSurfaceRes)); glBindTexture(GL_TEXTURE_2D, 0); glDeleteTextures(1, &distTexture); glActiveTexture(GL_TEXTURE1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, newWidth, newHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); initTextures(false); initCuda(false); } int Renderer::generatePath(const std::complex<double>& z, double metricArg, const std::complex<double>& p) { pm.enter(PERF_OVERLAY_GEN); lastP = p; double tolerance = (mode.argIsTolerance) ? metricArg : DEFAULT_PATH_TOLERANCE; lastTolerance = tolerance; pathStart = z; void* bufferPtr; CUDA_SAFE(cudaGraphicsMapResources(1, &overlayBufferRes)); CUDA_SAFE(cudaGraphicsResourceGetMappedPointer(&bufferPtr, nullptr, overlayBufferRes)); if(doublePrec) { launch_kernel_generic(pathKernel, 1, 1, z.real(), z.imag(), MAX_PATH_STEPS, tolerance * tolerance, bufferPtr, cudaPathLengthPtr, p.real(), p.imag()); } else { std::complex<float> fz(z), fp(p); launch_kernel_generic(pathKernel, 1, 1, fz.real(), fz.imag(), MAX_PATH_STEPS, static_cast<float>(tolerance * tolerance), bufferPtr, cudaPathLengthPtr, fp.real(), fp.imag()); } CUDA_SAFE(cudaDeviceSynchronize()); CUDA_SAFE(cudaGraphicsUnmapResources(1, &overlayBufferRes)); pathEnabled = true; pm.exit(PERF_OVERLAY_GEN); return *cudaPathLengthPtr; } void Renderer::refreshOverlayIfNeeded(const std::complex<double>& p, double metricArg) { double tolerance = (mode.argIsTolerance) ? metricArg : DEFAULT_PATH_TOLERANCE; if(std::abs(lastP - p) > PATH_PARAM_UPDATE_THRESHOLD || (std::abs(lastTolerance - tolerance) > PATH_TOL_UPDATE_THRESHOLD && pathEnabled)) { lastP = p; lastTolerance = tolerance; if(pathEnabled) generatePath(pathStart, tolerance, p); else if(shapeTransEnabled) generateShapeTransformImpl(p); } } void Renderer::hideOverlay() { pathEnabled = false; shapeTransEnabled = false; } std::vector<unsigned char> Renderer::exportImageData() { pm.enter(PERF_FRAME_EXPORT_TIME); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glReadBuffer(GL_COLOR_ATTACHMENT0); glPixelStorei(GL_PACK_ALIGNMENT, 1); long size = width * height * 3; std::vector<unsigned char> data(size); glReadnPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, size, data.data()); pm.exit(PERF_FRAME_EXPORT_TIME); return data; } void Renderer::generateShapeTransform(ShapeProps shape, int iteration, const std::complex<double>& p, int numShapePoints) { shapeTransProps = shape; shapeTransIteration = iteration; shapeTransEnabled = true; //Make sure we don't overflow the overlay VBO if(numShapePoints > SHAPE_TRANS_DEFAULT_POINTS) { std::cerr << "ERROR: Number of shape transform points can't exceed " << SHAPE_TRANS_DEFAULT_POINTS << "." << std::endl; numShapePoints = SHAPE_TRANS_DEFAULT_POINTS; } shapeTransNumPoints = (numShapePoints == -1) ? SHAPE_TRANS_DEFAULT_POINTS : numShapePoints; generateShapeTransformImpl(p); } void Renderer::setShapeTransformIteration(int iteration, const std::complex<double>& p, bool disableIncremental) { auto lastIterations = shapeTransIteration; shapeTransIteration = iteration; if(!disableIncremental) generateShapeTransformImpl(p, lastIterations); else generateShapeTransformImpl(p); } void Renderer::generateShapeTransformImpl(const std::complex<double>& p, int lastIterations) { pm.enter(PERF_LINE_TRANS_GEN); constexpr int BLOCK_SIZE = 1024; lastP = p; int itersToDo; bool incremental = false; if(lastIterations == -1 || shapeTransIteration < lastIterations || mode.capturing) { itersToDo = shapeTransIteration; } else { itersToDo = shapeTransIteration - lastIterations; incremental = true; } void* bufferPtr; CUDA_SAFE(cudaGraphicsMapResources(1, &overlayBufferRes)); CUDA_SAFE(cudaGraphicsResourceGetMappedPointer(&bufferPtr, nullptr, overlayBufferRes)); if(doublePrec) { launch_kernel_generic(shapeTransformKernel, shapeTransNumPoints, BLOCK_SIZE, *shapeTransProps, p.real(), p.imag(), shapeTransNumPoints, itersToDo, incremental, bufferPtr); } else { std::complex<float> fp(p); launch_kernel_generic(shapeTransformKernel, shapeTransNumPoints, BLOCK_SIZE, *shapeTransProps, fp.real(), fp.imag(), shapeTransNumPoints, itersToDo, incremental, bufferPtr); } CUDA_SAFE(cudaDeviceSynchronize()); CUDA_SAFE(cudaGraphicsUnmapResources(1, &overlayBufferRes)); pm.exit(PERF_LINE_TRANS_GEN); } int Renderer::getOverlayLength() { if(pathEnabled) return *cudaPathLengthPtr; else if(shapeTransEnabled) return shapeTransNumPoints; else throw std::runtime_error("getOverlayLength called without overlay active"); } void Renderer::togglePointConnections() { connectOverlayPoints = !connectOverlayPoints; } size_t Renderer::findAttractors(int maxIters, double metricArg, const std::complex<double>& p) { constexpr int BLOCK_SIZE = 256; pm.enter(PERF_ATTRACTOR); int aWidth = width * ATTRACTOR_RESOLUTION_MULT; int aHeight = height * ATTRACTOR_RESOLUTION_MULT; size_t bufSize = aWidth * aHeight; auto [start, end] = viewport.getCorners(); auto tolerance = (mode.argIsTolerance) ? metricArg : 0.05f; if(doublePrec) { launch_kernel_generic(findAttractorsKernel, bufSize, BLOCK_SIZE, start.real(), end.real(), start.imag(), end.imag(), maxIters, p.real(), p.imag(), tolerance * tolerance, aWidth, aHeight, attractorsDeviceBuffer, ATTRACTOR_MATCH_TOL); } else { std::complex<float> fstart(start), fend(end), fp(p); float ftol = tolerance, F_ATTRACTOR_MATCH_TOL = ATTRACTOR_MATCH_TOL; launch_kernel_generic(findAttractorsKernel, bufSize, BLOCK_SIZE, fstart.real(), fend.real(), fstart.imag(), fend.imag(), maxIters, fp.real(), fp.imag(), ftol * ftol, aWidth, aHeight, attractorsDeviceBuffer, F_ATTRACTOR_MATCH_TOL); } CUDA_SAFE(cudaDeviceSynchronize()); CUDA_SAFE(cudaMemcpy(attractorsHostBuffer.get(), attractorsDeviceBuffer, bufSize * sizeof(HostFloatComplex), cudaMemcpyDeviceToHost)); auto res = deduplicateWithTol(attractorsHostBuffer.get(), aWidth * aHeight, ATTRACTOR_MATCH_TOL, MAX_ATTRACTORS); CUDA_SAFE(cudaMemcpy(attractorsDeviceBuffer, attractorsHostBuffer.get(), res * sizeof(HostFloatComplex), cudaMemcpyHostToDevice)); std::cout << "Attractors: " << res; if(res == MAX_ATTRACTORS) std::cout << " (max)"; std::cout << std::endl; pm.exit(PERF_ATTRACTOR); return res; }
37.923858
240
0.715433
CakeWithSteak
fe23c392a0a037b38d10ad324be8d6883ac24f62
1,444
cpp
C++
lightoj.com/ChocolateThief.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
lightoj.com/ChocolateThief.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
lightoj.com/ChocolateThief.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: http://lightoj.com/volume_showproblem.php?problem=1249 Name: Chocolate Thief Number: 1249 Date: 26/07/2014 */ #include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <queue> #include <deque> #include <set> #include <map> #include <iterator> #include <utility> #include <list> #include <stack> #include <iomanip> #include <bitset> #define MAX_INT 2147483647 #define MAX_LONG 9223372036854775807ll #define MAX_ULONG 18446744073709551615ull #define MAX_DBL 1.7976931348623158e+308 #define EPS 1e-9 const double PI = 2.0*acos(0.0); #define INF 1000000000 using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<int, pair<int, int> > iii; struct cmp { bool operator() (const pair<int, string> &a, const pair<int, string> &b) { return (a.first < b.first); } }; int n, l, w, h; set<pair<int, string>, cmp> volumes; string s; int main () { int t, i, j; cin>>t; for (int it=1; it<=t; it++) { volumes.clear(); cin>>n; for (i=0; i<n; i++) { cin>>s>>l>>w>>h; volumes.insert(make_pair(l*w*h, s)); } if (volumes.size() == 1) cout<<"Case "<<it<<": no thief\n"; else cout<<"Case "<<it<<": "<<(*(--(volumes.end()))).second<<" took chocolate from "<<(*(volumes.begin())).second<<"\n"; } return 0; }
20.927536
124
0.626039
facug91
fe2616d15d918ea2abc95cd86f753a5351b1eb7a
5,200
cpp
C++
example/offscreen.cpp
UsiTarek/vkfw
ed25b204146ce4013597706ccce3e72f49ae3462
[ "Apache-2.0" ]
33
2021-01-20T17:10:26.000Z
2022-03-27T03:32:21.000Z
example/offscreen.cpp
UsiTarek/vkfw
ed25b204146ce4013597706ccce3e72f49ae3462
[ "Apache-2.0" ]
1
2022-03-25T22:55:27.000Z
2022-03-26T06:55:29.000Z
example/offscreen.cpp
UsiTarek/vkfw
ed25b204146ce4013597706ccce3e72f49ae3462
[ "Apache-2.0" ]
5
2021-06-29T03:30:06.000Z
2022-03-25T22:57:02.000Z
//======================================================================== // Offscreen rendering example // Copyright (c) Camilla Löwy <elmindreda@glfw.org> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // //======================================================================== // // Conversion to vkfw (and C++): John Cvelth <cvelth.mail@gmail.com> #include <glad/glad.h> #define VKFW_NO_INCLUDE_VULKAN_HPP #include <vkfw/vkfw.hpp> #if USE_NATIVE_OSMESA #define GLFW_EXPOSE_NATIVE_OSMESA #include <GLFW/glfw3native.h> #endif #include "linmath.h" #include <stdlib.h> #include <stdio.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> static const struct { float x, y; float r, g, b; } vertices[3] = { { -0.6f, -0.4f, 1.f, 0.f, 0.f }, { 0.6f, -0.4f, 0.f, 1.f, 0.f }, { 0.f, 0.6f, 0.f, 0.f, 1.f } }; static const char *vertex_shader_text = "#version 110\n" "uniform mat4 MVP;\n" "attribute vec3 vCol;\n" "attribute vec2 vPos;\n" "varying vec3 color;\n" "void main()\n" "{\n" " gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n" " color = vCol;\n" "}\n"; static const char *fragment_shader_text = "#version 110\n" "varying vec3 color;\n" "void main()\n" "{\n" " gl_FragColor = vec4(color, 1.0);\n" "}\n"; static void error_callback(int error, const char *description) { fprintf(stderr, "Error #%d: %s\n", error, description); } int main(void) { try { vkfw::setErrorCallback(error_callback); vkfw::InitHints init_hints; init_hints.cocoaMenubar = false; auto instance = vkfw::initUnique(init_hints); vkfw::WindowHints hints; hints.clientAPI = vkfw::ClientAPI::eOpenGL; hints.contextVersionMajor = 2u; hints.contextVersionMinor = 0u; hints.visible = false; auto window = vkfw::createWindowUnique(640, 480, "Simple example", hints); window->makeContextCurrent(); gladLoadGLLoader((GLADloadproc) &vkfw::getProcAddress); // NOTE: OpenGL error checks have been omitted for brevity GLuint vertex_buffer, vertex_shader, fragment_shader, program; glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL); glCompileShader(vertex_shader); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL); glCompileShader(fragment_shader); program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); GLint mvp_location, vpos_location, vcol_location; mvp_location = glGetUniformLocation(program, "MVP"); vpos_location = glGetAttribLocation(program, "vPos"); vcol_location = glGetAttribLocation(program, "vCol"); glEnableVertexAttribArray(vpos_location); glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void *) 0); glEnableVertexAttribArray(vcol_location); glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void *) (sizeof(float) * 2)); auto size = window->getFramebufferSize(); int width = static_cast<int>(std::get<0>(size)), height = static_cast<int>(std::get<1>(size)); float ratio = (float) width / (float) height; glViewport(0, 0, (GLsizei) width, (GLsizei) height); glClear(GL_COLOR_BUFFER_BIT); mat4x4 mvp; mat4x4_ortho(mvp, -ratio, ratio, -1.f, 1.f, 1.f, -1.f); glUseProgram(program); glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat *) mvp); glDrawArrays(GL_TRIANGLES, 0, 3); glFinish(); #if USE_NATIVE_OSMESA char *buffer; glfwGetOSMesaColorBuffer(window, &width, &height, NULL, (void **) &buffer); #else char *buffer = static_cast<char *>(calloc(4, width * height)); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); #endif // Write image Y-flipped because OpenGL stbi_write_png("offscreen.png", width, height, 4, buffer + (width * 4 * (height - 1)), -width * 4); #if USE_NATIVE_OSMESA // Here is where there's nothing #else free(buffer); #endif } catch (std::system_error &err) { char error_message[] = "An error has occured: "; strcat(error_message, err.what()); fprintf(stderr, error_message); return -1; } }
29.885057
77
0.693846
UsiTarek
fe2838a58a50c1f33922597e95e8dbd43e86961e
2,850
cpp
C++
day2/placement/data/data_maker/6/std.cpp
DiamondJack/CTSC2018
a3a6ed27d61915ce08bcce4160970a9aeea39a0c
[ "Apache-2.0" ]
2
2019-03-22T11:13:53.000Z
2020-08-28T03:05:02.000Z
day2/placement/data/data_maker/6/std.cpp
DiamondJack/CTSC2018
a3a6ed27d61915ce08bcce4160970a9aeea39a0c
[ "Apache-2.0" ]
null
null
null
day2/placement/data/data_maker/6/std.cpp
DiamondJack/CTSC2018
a3a6ed27d61915ce08bcce4160970a9aeea39a0c
[ "Apache-2.0" ]
null
null
null
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; const int maxn=2010; int n,m,k,en; int t[maxn][maxn],r[maxn][maxn],in[maxn]; int res[maxn]; bool use[maxn][maxn]; char args[100][100]; char djm[1000]; int ans=0x3f3f3f3f; struct edge { int e,f; edge *next,*op; }*v[maxn],ed[maxn*maxn]; void add_edge(int s,int e) { en++; ed[en].next=v[s];v[s]=ed+en;v[s]->e=e; } int judge() { sprintf(djm,"..\\simulator.exe %s %s",args[1],args[2]); system(djm); FILE *f=fopen("res.txt","r"); int v; fscanf(f,"%d",&v); fclose(f); return v; } //start from here void init() { FILE *f = fopen(args[1],"r"); fscanf(f,"%d%d%d%*d",&n,&m,&k); for (int a=1;a<=m;a++) { int s,e; fscanf(f,"%d%d",&s,&e); add_edge(s,e); use[s][e]=true; in[e]++; } for (int a=1;a<=n;a++) for (int b=1;b<=k;b++) fscanf(f,"%d",&t[a][b]); for (int a=1;a<=k;a++) for (int b=1;b<=k;b++) fscanf(f,"%d",&r[a][b]); fclose(f); } int depth[maxn],q[maxn]; void add_edge(int s,int e,int f) { en++; ed[en].next=v[s];v[s]=ed+en;v[s]->e=e;v[s]->f=f; en++; ed[en].next=v[e];v[e]=ed+en;v[e]->e=s;v[e]->f=0; v[s]->op=v[e];v[e]->op=v[s]; } bool bfs() { memset(depth,0,sizeof(depth)); int front=1,tail=1; q[1]=0; depth[0]=1; for (;front<=tail;) { int now=q[front++]; for (edge *e=v[now];e;e=e->next) if (e->f && !depth[e->e]) { depth[e->e]=depth[now]+1; q[++tail]=e->e; } } return depth[n<<1|1]!=0; } int dfs(int now,int flow) { if (now==(n<<1|1)) return flow; int rest=flow; for (edge *e=v[now];e && rest;e=e->next) if (e->f && depth[e->e]==depth[now]+1) { int cur_flow=dfs(e->e,min(e->f,rest)); rest-=cur_flow; e->f-=cur_flow; e->op->f+=cur_flow; } return flow-rest; } int dinic() { int ans=0; while (bfs()) ans+=dfs(0,0x3f3f3f3f); return ans; } void work() { en=0; memset(v,0,sizeof(v)); for (int a=1;a<=n;a++) { add_edge(0,a,t[a][1]); add_edge(a,a+n,0x3f3f3f3f); add_edge(a+n,n<<1|1,t[a][2]); } for (int a=1;a<=n;a++) for (int b=1;b<=n;b++) if (use[a][b]) { add_edge(a,b+n,r[2][1]); add_edge(b,a+n,r[1][2]); } int ans=dinic(); for (edge *e=v[0];e;e=e->next) if (!e->f) res[e->e]=1; else res[e->e]=2; for (edge *e=v[n<<1|1];e;e=e->next) if (!e->op->f) { if (res[e->e-n]==1) printf("%d gg\n",e->e-n); } else { if (res[e->e-n]==2) printf("%d gg\n",e->e-n); } FILE *f=fopen(args[2],"w"); for (int a=1;a<=n;a++) fprintf(f,"%d%c",res[a],a==n?'\n':' '); fclose(f); int v=judge(); if (v!=ans) { printf("%d sb\n",ans); } } void output() { FILE *f=fopen(args[2],"w"); for (int a=1;a<=n;a++) fprintf(f,"%d%c",res[a],a==n?'\n':' '); fclose(f); } int main(int argc,char *argss[]) { for (int a=0;a<argc;a++) sprintf(args[a],"%s",argss[a]); init(); work(); output(); return 0; }
15.405405
56
0.521754
DiamondJack
fe28838b65cb6cc2348a1f6f9aa9ec0361548e42
4,765
cpp
C++
src/memory.cpp
Keithcat1/synthizer
242a06855a36b9a9049d5fb00630800cda4a2984
[ "Unlicense" ]
null
null
null
src/memory.cpp
Keithcat1/synthizer
242a06855a36b9a9049d5fb00630800cda4a2984
[ "Unlicense" ]
null
null
null
src/memory.cpp
Keithcat1/synthizer
242a06855a36b9a9049d5fb00630800cda4a2984
[ "Unlicense" ]
null
null
null
#include "synthizer.h" #include "synthizer/error.hpp" #include "synthizer/logging.hpp" #include "synthizer/memory.hpp" #include "synthizer/vector_helpers.hpp" #include <concurrentqueue.h> #include <atomic> #include <cassert> #include <chrono> #include <memory> #include <mutex> #include <shared_mutex> #include <thread> #include <unordered_map> #include <utility> namespace synthizer { CExposable::CExposable() { } std::shared_ptr<CExposable> getExposableFromHandle(syz_Handle handle) { CExposable *exposable = (CExposable *)handle; auto out = exposable->getInternalReference(); if (out == nullptr || out->isPermanentlyDead()) { throw EInvalidHandle("This handle is already dead. Synthizer cannot catch all cases of invalid handles; change your program to use only valid handles or risk crashes."); } return out; } /* * Infrastructure for deferred frees and holding handles * to delete on library shutdown. * */ static std::mutex registered_handles_lock{}; static deferred_vector<std::weak_ptr<CExposable>> registered_handles; /* Get rid of any handles which have died. */ static void purgeDeadRegisteredHandles() { auto guard = std::lock_guard(registered_handles_lock); vector_helpers::filter(registered_handles, [](auto &p) { return p.lock() != nullptr; }); } void registerObjectForShutdownImpl(const std::shared_ptr<CExposable> &obj) { purgeDeadRegisteredHandles(); auto guard = std::lock_guard(registered_handles_lock); registered_handles.emplace_back(obj); } struct DeferredFreeEntry { freeCallback *cb; void *value; }; /* * The queue. 1000 items and 64 of each type of producer. * */ static moodycamel::ConcurrentQueue<DeferredFreeEntry> deferred_free_queue{1000, 64, 64}; static std::thread deferred_free_thread; static std::atomic<int> deferred_free_thread_running = 0; thread_local static bool is_deferred_free_thread = false; /* * Drain the deferred freeing callback queue and drain all registered handles which are now dead. * */ unsigned int deferredFreeTick() { decltype(deferred_free_queue)::consumer_token_t token{deferred_free_queue}; DeferredFreeEntry ent; unsigned int processed = 0; while (deferred_free_queue.try_dequeue(token, ent)) { try { ent.cb(ent.value); } catch(...) { logDebug("Exception on memory freeing thread. This should never happen"); } processed++; } purgeDeadRegisteredHandles(); return processed; } static void deferredFreeWorker() { std::size_t processed = 0; is_deferred_free_thread = true; while (deferred_free_thread_running.load(std::memory_order_relaxed)) { processed += deferredFreeTick(); /* Sleep for a bit so that we don't overload the system when we're not freeing. */ std::this_thread::sleep_for(std::chrono::milliseconds(30)); } logDebug("Deferred free processed %zu frees in a background thread", processed); } void deferredFreeCallback(freeCallback *cb, void *value) { if (deferred_free_thread_running.load() ==0 ) { cb(value); return; } if (value == nullptr) { return; } if (is_deferred_free_thread || deferred_free_queue.try_enqueue({ cb, value }) == false) { cb(value); } } void clearAllCHandles() { auto guard = std::lock_guard(registered_handles_lock); for (auto &h: registered_handles) { auto s = h.lock(); if (s == nullptr) { continue; } s->dieNow(); } return; } void initializeMemorySubsystem() { deferred_free_thread_running.store(1); deferred_free_thread = std::thread{deferredFreeWorker}; } void shutdownMemorySubsystem() { deferred_free_thread_running.store(0); deferred_free_thread.join(); /* * Now get rid of anything that might still be around. */ deferredFreeTick(); } UserdataDef::~UserdataDef() { this->maybeFreeUserdata(); } void UserdataDef::set(void *ud, syz_UserdataFreeCallback *ud_free_callback) { this->maybeFreeUserdata(); this->userdata.store(ud, std::memory_order_relaxed); this->userdata_free_callback = ud_free_callback; } void *UserdataDef::getAtomic() { return this->userdata.load(std::memory_order_relaxed); } void UserdataDef::maybeFreeUserdata() { void *ud = this->userdata.load(std::memory_order_relaxed); if (ud != nullptr && this->userdata_free_callback != nullptr) { deferredFreeCallback(this->userdata_free_callback, ud); } this->userdata = nullptr; this->userdata_free_callback = nullptr; } void *CExposable::getUserdata() { auto *inner = this->userdata.unsafeGetInner(); return inner->getAtomic(); } void CExposable::setUserdata(void *ud, syz_UserdataFreeCallback *ud_free_callback) { bool did_set = this->userdata.withLock([&] (auto *u) { u->set(ud, ud_free_callback); }); /* We lost the race. */ if (did_set == false && ud != nullptr && ud_free_callback != nullptr) { deferredFreeCallback(ud_free_callback, ud); } } }
25.756757
171
0.740399
Keithcat1
fe2a8e7b53edce67e0b7e90a6ec41f4a104a6f01
1,866
cpp
C++
classes/input/pointer.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
24
2017-08-22T15:55:34.000Z
2022-03-06T11:41:31.000Z
classes/input/pointer.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
6
2018-07-21T12:17:55.000Z
2021-08-12T11:27:27.000Z
classes/input/pointer.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
9
2017-09-13T02:32:18.000Z
2022-03-06T11:41:32.000Z
/* The smooth Class Library * Copyright (C) 1998-2013 Robert Kausch <robert.kausch@gmx.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of "The Artistic License, Version 2.0". * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <smooth/input/pointer.h> #include <smooth/input/backends/pointerbackend.h> #include <smooth/init.h> S::Int addPointerInitTmp = S::AddInitFunction(&S::Input::Pointer::Initialize); S::Int addPointerFreeTmp = S::AddFreeFunction(&S::Input::Pointer::Free); S::Input::PointerBackend *S::Input::Pointer::backend = NIL; const S::GUI::Window *S::Input::Pointer::pointerWindow = NIL; S::GUI::Point S::Input::Pointer::mousePosition = S::GUI::Point(); S::Input::Pointer::Pointer() { } S::Input::Pointer::Pointer(const Pointer &) { } S::Int S::Input::Pointer::Initialize() { backend = PointerBackend::CreateBackendInstance(); return Success(); } S::Int S::Input::Pointer::Free() { delete backend; return Success(); } S::Bool S::Input::Pointer::SetCursor(const GUI::Window *window, CursorType mouseCursor) { return backend->SetCursor(window, mouseCursor); } const S::GUI::Point &S::Input::Pointer::GetPosition() { return mousePosition; } const S::GUI::Window *S::Input::Pointer::GetPointerWindow() { return pointerWindow; } S::Void S::Input::Pointer::UpdatePosition(const GUI::Window *window, Int x, Int y) { pointerWindow = window; mousePosition.x = x; mousePosition.y = y; /* FixMe: The -2 offsets seem to be necessary on * all X11 systems. However, I somehow feel * this can't be the right way to do it. */ #ifndef __WIN32__ mousePosition.x -= 2; mousePosition.y -= 2; #endif }
24.552632
87
0.706324
Patriccollu
fe2d1ca9457dab40358687e3dbbfcc157a13a13f
640
cpp
C++
test/unit-tests/mapper/map_flushed_event_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
test/unit-tests/mapper/map_flushed_event_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
test/unit-tests/mapper/map_flushed_event_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
#include "src/mapper/map_flushed_event.h" #include <gtest/gtest.h> #include "test/unit-tests/mapper/i_map_manager_mock.h" using ::testing::_; using ::testing::AtLeast; using testing::NiceMock; using ::testing::Return; using ::testing::ReturnRef; namespace pos { TEST(MapFlushedEvent, Execute_) { // given NiceMock<MockIMapManagerInternal>* mapMan = new NiceMock<MockIMapManagerInternal>(); MapFlushedEvent* e = new MapFlushedEvent(0, mapMan); // when EXPECT_CALL(*mapMan, MapFlushDone).Times(1); int ret = e->Execute(); // then EXPECT_EQ(true, ret); delete mapMan; delete e; } } // namespace pos
22.068966
88
0.7
so931
fe2d3154917901af60089b6e1e1fe7d232382fd4
17,861
cpp
C++
src/universe/vehicle/plumbing/VehiclePlumbing.cpp
TheOpenSpaceProgram/new-ospgl
646ee5229ce4c35856aae0d41b514c86c33791a2
[ "MIT" ]
22
2019-11-15T22:07:17.000Z
2022-01-13T16:40:01.000Z
src/universe/vehicle/plumbing/VehiclePlumbing.cpp
TheOpenSpaceProgram/new-ospgl
646ee5229ce4c35856aae0d41b514c86c33791a2
[ "MIT" ]
25
2020-03-03T00:54:21.000Z
2021-12-30T16:24:22.000Z
src/universe/vehicle/plumbing/VehiclePlumbing.cpp
TheOpenSpaceProgram/new-ospgl
646ee5229ce4c35856aae0d41b514c86c33791a2
[ "MIT" ]
3
2020-03-04T00:36:13.000Z
2020-06-01T20:53:51.000Z
#include "VehiclePlumbing.h" #include "../Vehicle.h" // A reasonable multiplier to prevent extreme flow velocities // I don't know enough fluid mechanics as to determine a reasonable value // so it's arbitrary, chosen to approximate real life rocket values #define FLOW_MULTIPLIER 0.0002 void VehiclePlumbing::update_pipes(float dt, Vehicle* in_veh) { assign_flows(dt); sanify_flow(dt); simulate_flow(dt); } void VehiclePlumbing::assign_flows(float dt) { for(const PipeJunction& jnc : junctions) { junction_flow_rate(jnc, dt); } for(Pipe& p : pipes) { if(p.junction != nullptr) continue; // TODO: Obtain density by averaging or something float sqrt_density = 1.0f; float pa = p.ma->plumbing.get_pressure(p.port_a); float pb = p.mb->plumbing.get_pressure(p.port_b); float sign = pa > pb ? -1.0f : 1.0f; float constant = p.surface * sqrt(2.0f) / sqrt_density; p.flow = sign * constant * sqrt(glm::abs(pb - pa)) * FLOW_MULTIPLIER; } } void VehiclePlumbing::sanify_flow(float dt) { for(PipeJunction& jnc : junctions) { // Liquid volume, gases always fit as they are compressible! float total_accepted_volume = 0.0f; float total_given_volume = 0.0f; StoredFluids f_total = StoredFluids(); // Find how much will be given for(Pipe* p : jnc.pipes) { if(p->flow < 0.0f) continue; // This pipe gives to the junction, find how much would it give StoredFluids f = p->mb->plumbing.out_flow(p->port_b, p->flow * dt, false); float vol = f.get_total_liquid_volume(); if(vol == 0.0f && f.get_total_gas_mass() != 0.0f && f.get_total_liquid_mass() == 0.0f) { // We are draining gases, no need to change flow } else if(vol < p->flow * dt) { // This pipe cannot supply enough, flow is clamped p->flow = vol; } total_given_volume += vol; f_total.modify(f); } // Find how much will be taken for(const Pipe* p : jnc.pipes) { if(p->flow > 0.0f) continue; // This pipe takes from the junction, find how much would it take // We don't care about gases here as they can be taken in infinite ammounts StoredFluids in = f_total.modify(f_total.multiply(-p->flow * dt)); StoredFluids not_taken = p->mb->plumbing.in_flow(p->port_b, in, false); total_accepted_volume += -dt * p->flow - not_taken.get_total_liquid_volume(); } if(total_accepted_volume < total_given_volume) { // Sanify flow, the giving pipes must give less. This is done // in a uniform manner, by multiplying flow of every pipe float factor = total_accepted_volume / total_given_volume; for(Pipe* p : jnc.pipes) { if(p->flow < 0.0f) p->flow *= factor; } } } for(Pipe& p : pipes) { if(p.junction != nullptr) continue; } } // Very similar to sanify but does the actual flow and handles gases void VehiclePlumbing::simulate_flow(float dt) { for(PipeJunction& jnc : junctions) { StoredFluids f_total = StoredFluids(); // Take from pipes for(const Pipe* p : jnc.pipes) { if(p->flow < 0.0f) continue; StoredFluids f = p->mb->plumbing.out_flow(p->port_b, p->flow * dt, true); f_total.modify(f); } for(const Pipe* p : jnc.pipes) { if(p->flow > 0.0f) continue; StoredFluids in = f_total.modify(f_total.multiply(-p->flow * dt)); StoredFluids not_taken = p->mb->plumbing.in_flow(p->port_b, in, true); // TODO: Handle gases? logger->check(not_taken.get_total_liquid_mass() < 0.001f, "Fluids were not conserved!"); } } for(Pipe& p : pipes) { } } void VehiclePlumbing::junction_flow_rate(const PipeJunction& junction, float dt) { size_t jsize = junction.pipes.size(); // We impose the condition that sum(flow) = 0, and // as flow = ct * sqrt(deltaP), we can solve // 0 = sqrt(Pj - Pa) + sqrt(Pj - Pb) ... // Receiving tanks are added as -sqrt(Pa - Pj) as Pj > Pa // This setup divides our function into at max n parts, // with edges that we can determine: They are simply the // pressures sorted from high to low. // Sorted from highest pressure to lowest, safe to keep short-lived pointer std::vector<std::pair<Pipe*, float>> pipe_pressure; pipe_pressure.reserve(jsize); for(auto& pipe : junction.pipes) { float pr = pipe->mb->plumbing.get_pressure(pipe->port_b); pipe_pressure.emplace_back(pipe, pr); } std::sort(pipe_pressure.begin(), pipe_pressure.end(), [](const std::pair<Pipe*, float>& a, const std::pair<Pipe*, float>& b) { return a.second > b.second; }); // TODO: Obtain density by averaging or something float sqrt_density = 1.0f; auto evaluate = [pipe_pressure, jsize, sqrt_density](float x, size_t section, bool diff = false) -> std::pair<float, float> { // These later on will be read from the pipe float sum = 0.0f; float diff_sum = 0.0f; for(size_t i = 0; i < jsize; i++) { float sign = i > (jsize - 2 - section) ? -1.0f : 1.0f; float dP = (pipe_pressure[i].second - x); float constant = pipe_pressure[i].first->surface * sqrt(2.0f) / sqrt_density; float radical = sqrt(glm::abs(dP)); if(diff) { diff_sum -= constant / (2.0f * radical); } sum += sign * constant * radical; } return std::make_pair(sum, diff_sum); }; size_t solution_section = 0; float x = 0.0f, fx; for(size_t i = 0; i < jsize - 1; i++) { float lP = pipe_pressure[i].second; float rP = pipe_pressure[i + 1].second; float left = evaluate(lP, i).first; float right = evaluate(rP, i).first; if(left * right < 0.0f) { solution_section = i; x = (lP + rP) / 2.0f; break; } } // Find an approximation of the solution, we use the Newton Rhapson method as // it's well behaved in this kind of function and converges VERY fast // TODO: Check if the closed form solution is faster AND // TODO: if simply running the method on the whole piece-wise function // TODO: converges (fast) too! for(size_t it = 0; it < 2; it++) { auto pair = evaluate(x, solution_section, true); fx = pair.first; float dfx = pair.second; // if the derivative is small, we are near constant and can early quit if(glm::abs(dfx) < 0.0001) { break; } x = x - fx / dfx; } // fx is very close to the pressure at the junction now for(size_t i = 0; i < jsize; i++) { float sign = i > (jsize - 2 - solution_section) ? -1.0f : 1.0f; float constant = pipe_pressure[i].first->surface * sqrt(2.0f) / sqrt_density; pipe_pressure[i].first->flow = sign * constant * sqrt(glm::abs(pipe_pressure[i].second - x)) * FLOW_MULTIPLIER; } } VehiclePlumbing::VehiclePlumbing(Vehicle *in_vehicle) { veh = in_vehicle; pipe_id = 0; junction_id = 0; } std::vector<PlumbingElement> VehiclePlumbing::grid_aabb_check(glm::vec2 start, glm::vec2 end, const std::vector<PlumbingElement>& ignore, bool expand) { std::vector<PlumbingElement> out; for(const Part* p : veh->parts) { for (const auto &pair : p->machines) { bool ignored = false; for(PlumbingElement m : ignore) { if(m == pair.second) { ignored = true; break; } } if(pair.second->plumbing.has_lua_plumbing() && !ignored) { glm::ivec2 min = pair.second->plumbing.editor_position; glm::ivec2 max = min + pair.second->plumbing.get_editor_size(expand); if (min.x < end.x && max.x > start.x && min.y < end.y && max.y > start.y) { out.emplace_back(pair.second); } } } } // It's easier for junctions, note that we return pointers too for(PipeJunction& jnc : junctions) { bool ignored = false; for(PlumbingElement m : ignore) { if(m == &jnc) { ignored = true; break; } } glm::ivec2 min = jnc.pos; glm::ivec2 max = min + jnc.get_size(expand); if (min.x < end.x && max.x > start.x && min.y < end.y && max.y > start.y && !ignored) { out.emplace_back(&jnc); } } return out; } glm::ivec4 VehiclePlumbing::get_plumbing_bounds() { glm::ivec2 amin = glm::ivec2(INT_MAX, INT_MAX); glm::ivec2 amax = glm::ivec2(INT_MIN, INT_MIN); bool any = false; for(const Part* p : veh->parts) { for (const auto &pair : p->machines) { if (pair.second->plumbing.has_lua_plumbing()) { glm::ivec2 min = pair.second->plumbing.editor_position; glm::ivec2 max = min + pair.second->plumbing.get_editor_size(true); amin = glm::min(amin, min); amax = glm::max(amax, max); any = true; } } } if(any) { return glm::ivec4(amin.x, amin.y, amax.x - amin.x, amax.y - amin.y); } else { return glm::ivec4(0, 0, 0, 0); } } glm::ivec2 VehiclePlumbing::find_free_space(glm::ivec2 size) { // We first do a binary search in the currently used space // If that cannot be found, return outside of used space, to the // bottom as rockets are usually vertical glm::ivec4 bounds = get_plumbing_bounds(); return glm::ivec2(bounds.x, bounds.y + bounds.w); } glm::ivec2 VehiclePlumbing::get_plumbing_size_of(Part* p) { // min is always (0, 0) as that's the forced origin of the plumbing start positions glm::ivec2 max = glm::ivec2(INT_MIN, INT_MIN); bool found_any = false; for(const auto& pair : p->machines) { MachinePlumbing& pb = pair.second->plumbing; if(pb.has_lua_plumbing()) { found_any = true; max = glm::max(max, pb.editor_position + pb.get_editor_size()); } } if(found_any) { return max; } else { return glm::ivec2(0, 0); } } std::vector<PlumbingElement> VehiclePlumbing::get_all_elements() { std::vector<PlumbingElement> out; // Machines for(const Part* p : veh->parts) { for (const auto &pair : p->machines) { if (pair.second->plumbing.has_lua_plumbing()) { out.emplace_back(pair.second); } } } // Junctions for(PipeJunction& jnc : junctions) { out.emplace_back(&jnc); } return out; } Pipe* VehiclePlumbing::create_pipe() { size_t id = ++pipe_id; Pipe p = Pipe(); p.id = id; pipes.push_back(p); // Rebuild the junctions as pointers may change in the vector rebuild_pipe_pointers(); return &pipes[pipes.size() - 1]; } PipeJunction* VehiclePlumbing::create_pipe_junction() { size_t id = ++junction_id; PipeJunction j = PipeJunction(); j.id = id; junctions.push_back(j); // Rebuild junctions in pipes as they may have changed pointer rebuild_junction_pointers(); return &junctions[junctions.size() - 1]; } Pipe* VehiclePlumbing::get_pipe(size_t id) { for(Pipe& p : pipes) { if(p.id == id) { return &p; } } logger->fatal("Couldn't find pipe with id = {}", id); return nullptr; } PipeJunction* VehiclePlumbing::get_junction(size_t id) { for(PipeJunction& p : junctions) { if(p.id == id) { return &p; } } logger->fatal("Couldn't find pipe junction with id = {}", id); return nullptr; } void VehiclePlumbing::remove_pipe(size_t id) { bool found = false; for(size_t i = 0; i < pipes.size(); i++) { if(pipes[i].id == id) { pipes.erase(pipes.begin() + i); found = true; break; } } logger->check(found, "Couldn't find pipe with id= {} to remove", id); rebuild_pipe_pointers(); } void VehiclePlumbing::remove_junction(size_t id) { bool found = false; for(size_t i = 0; i < junctions.size(); i++) { if(junctions[i].id == id) { junctions.erase(junctions.begin() + i); found = true; break; } } logger->check(found, "Couldn't find junction with id= {} to remove", id); rebuild_junction_pointers(); } void VehiclePlumbing::rebuild_junction_pointers() { for(Pipe& p : pipes) { if(p.junction_id != 0) { PipeJunction* found = nullptr; for(PipeJunction& fj : junctions) { if(fj.id == p.junction_id) { found = &fj; break; } } logger->check(found != nullptr, "Couldn't find pipe junction with id = {}", p.junction_id); p.junction = found; } } } void VehiclePlumbing::rebuild_pipe_pointers() { for(PipeJunction& jnc : junctions) { if(jnc.pipes.size() == 0) { // This is the case during vehicle loading jnc.pipes.resize(jnc.pipes_id.size()); } for(size_t i = 0; i < jnc.pipes_id.size(); i++) { jnc.pipes[i] = get_pipe(jnc.pipes_id[i]); } } } glm::ivec2 PipeJunction::get_size(bool extend, bool rotate) const { size_t num_subs; if(get_port_number() <= 4) { num_subs = 1; } else { num_subs = ((get_port_number() - 5) / 2) + 2; } glm::ivec2 base = glm::ivec2(num_subs, 1); if(extend) { base += glm::ivec2(1, 1); } if(rotate && (rotation == 1 || rotation == 3)) { std::swap(base.x, base.y); } return base; } void PipeJunction::add_pipe(Pipe* p) { // Try to find a vacant slot for(size_t i = 0; i < pipes.size(); i++) { if(pipes[i] == nullptr && pipes_id[i] == 0xDEADBEEF) { pipes[i] = p; pipes_id[i] = p->id; return; } } // Otherwise add new pipe pipes.push_back(p); pipes_id.push_back(p->id); } glm::vec2 PipeJunction::get_port_position(const Pipe *p) { // Port positions are a.lways in the same order, same as rendering float f = 1.0f; size_t port_count = get_port_number(); int i = -1; for(size_t j = 0; j < pipes.size(); j++) { if(pipes[j] == p) { i = (int)j; } } logger->check(i != -1, "Couldn't find pipe with id = {}", p->id); glm::vec2 offset; if(port_count <= 4 || (i <= 3)) { if(i == 0) { offset = glm::vec2(0.0f, -1.0f); } else if(i == 1) { offset = glm::vec2(-1.0f, 0.0f); } else if(i == 2) { offset = glm::vec2(0.0f, 1.0f); } else if(i == 3) { offset = glm::vec2(1.0f, 0.0f); } } else { // Algorithmic procedure for ports to the right } // Rotation offset += glm::vec2(0.5f); glm::ivec2 size = get_size(false, false); if(rotation == 1) { std::swap(offset.x, offset.y); offset.x = size.x - offset.x; } else if(rotation == 2) { offset.x = (float)size.x - offset.x; offset.y = (float)size.y - offset.y; } else if(rotation == 3) { std::swap(offset.x, offset.y); offset.y = (float)size.y - offset.y; } return offset * f + (glm::vec2)pos; } // This works even for vacant pipes! size_t PipeJunction::get_port_id(const Pipe* p) { int fid = -1; for(size_t i = 0; i < pipes.size(); i++) { if(pipes[i] == p) { fid = (int)i; break; } } logger->check(fid != -1, "Could not find pipe for port id"); return (size_t)fid; } PlumbingElement::PlumbingElement(PipeJunction *junction) { as_junction = junction; type = JUNCTION; } PlumbingElement::PlumbingElement() { as_machine = nullptr; type = EMPTY; } PlumbingElement::PlumbingElement(Machine *machine) { as_machine = machine; type = MACHINE; } // This operator== functions may unnecesarly check type as afterall // there wont' be a machine and a pipe with the same memory index! bool PlumbingElement::operator==(const Machine* m) const { return type == MACHINE && as_machine == m; } bool PlumbingElement::operator==(const PipeJunction* jnc) const { return type == JUNCTION && as_junction == jnc; } // TODO: This one is specially stupid bool PlumbingElement::operator==(const PlumbingElement& j) const { if(type == MACHINE) { return as_machine == j.as_machine && j.type == MACHINE; } else if(type == JUNCTION) { return as_junction == j.as_junction && j.type == JUNCTION; } return false; } glm::ivec2 PlumbingElement::get_size(bool expand, bool rotate) { logger->check(type != EMPTY, "Tried to call get_size on an empty PlumbingElement"); if(type == MACHINE) { return as_machine->plumbing.get_editor_size(expand, rotate); } else if(type == JUNCTION) { return as_junction->get_size(expand, rotate); } return glm::ivec2(0, 0); } glm::ivec2 PlumbingElement::get_pos() { logger->check(type != EMPTY, "Tried to call get_pos on an empty PlumbingElement"); if(type == MACHINE) { return as_machine->plumbing.editor_position; } else if(type == JUNCTION) { return as_junction->pos; } return glm::ivec2(0, 0); } void PlumbingElement::set_pos(glm::ivec2 pos) { logger->check(type != EMPTY, "Tried to call set_pos on an empty PlumbingElement"); if(type == MACHINE) { as_machine->plumbing.editor_position = pos; } else if(type == JUNCTION) { as_junction->pos = pos; } } int PlumbingElement::get_rotation() { logger->check(type != EMPTY, "Tried to call get_rotation on an empty PlumbingElement"); if(type == MACHINE) { return as_machine->plumbing.editor_rotation; } else if(type == JUNCTION) { return as_junction->rotation; } return 0; } void PlumbingElement::set_rotation(int value) { logger->check(type != EMPTY, "Tried to call set_rotation on an empty PlumbingElement"); if(type == MACHINE) { as_machine->plumbing.editor_rotation = value; } else if(type == JUNCTION) { as_junction->rotation = value; } } std::vector<std::pair<FluidPort, glm::vec2>> PlumbingElement::get_ports() { logger->check(type != EMPTY, "Tried to call get_ports on an empty PlumbingElement"); std::vector<std::pair<FluidPort, glm::vec2>> out; if(type == MACHINE) { for(const FluidPort& p : as_machine->plumbing.fluid_ports) { glm::vec2 pos = as_machine->plumbing.get_port_position(p.id); out.emplace_back(p, pos); } } else if(type == JUNCTION) { for(const Pipe* p : as_junction->pipes) { glm::vec2 pos = as_junction->get_port_position(p); FluidPort port = FluidPort(); port.id = "__junction"; port.numer_id = as_junction->get_port_id(p); port.gui_name = "Junction Port"; port.marker = ""; out.emplace_back(port, pos); } } return out; } void Pipe::invert() { logger->check(junction == nullptr, "Cannot invert a pipe that goes to a junction as it must always be the end"); std::swap(ma, mb); std::swap(port_a, port_b); std::reverse(waypoints.begin(), waypoints.end()); } void Pipe::connect_junction(PipeJunction *jnc) { junction = jnc; junction_id = jnc->id; ma = nullptr; port_a = ""; jnc->add_pipe(this); } Pipe::Pipe() { id = 0; ma = nullptr; mb = nullptr; junction = nullptr; junction_id = 0; port_a = ""; port_b = ""; surface = 1.0f; flow = 0.0f; }
21.339307
125
0.649516
TheOpenSpaceProgram
fe3125c25dd4ac57df2898f8d0bf16aefc42bcfb
502
hpp
C++
owl/scene/light.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
owl/scene/light.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
owl/scene/light.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
// // .___. // {o,o} // ./)_) // owl --"-"--- // // Copyright © 2018 Sören König. All rights reserved. // #pragma once #include <chrono> namespace owl { namespace scene { enum class light_type { ambient, directional, spot, point }; template<typename Scalar, typename Color> class light { public: light_type type; Scalar intensity; Scalar temperature; Color color; }; } }
12.55
54
0.5
soerenkoenig
fe33d099e9167369f55f319dc61a9bd1e9d9adf7
1,498
hpp
C++
SDK/ARKSurvivalEvolved_Buff_Radiation_Sickness_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Buff_Radiation_Sickness_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Buff_Radiation_Sickness_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_Radiation_Sickness_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Buff_Radiation_Sickness.Buff_Radiation_Sickness_C // 0x000C (0x096C - 0x0960) class ABuff_Radiation_Sickness_C : public ABuff_Base_OnlyRelevantToOwner_C { public: float BuffTimeDecreaseRate; // 0x0960(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float InitialMaxStamina; // 0x0964(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float InitialMaxWeight; // 0x0968(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Buff_Radiation_Sickness.Buff_Radiation_Sickness_C"); return ptr; } void BuffTickClient(float* DeltaTime); void UserConstructionScript(); void ExecuteUbergraph_Buff_Radiation_Sickness(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
34.045455
208
0.59012
2bite
fe36c35e7c70f16f9c5d5a2f19e5d6ea07142047
2,487
cpp
C++
SWExpertAcademy/SWEA1218.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
1
2020-07-08T23:16:19.000Z
2020-07-08T23:16:19.000Z
SWExpertAcademy/SWEA1218.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
1
2020-05-16T03:12:24.000Z
2020-05-16T03:14:42.000Z
SWExpertAcademy/SWEA1218.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
2
2020-05-16T03:25:16.000Z
2021-02-10T16:51:25.000Z
#include <iostream> #include <stack> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); for (int test_case = 1; test_case <= 10; test_case++) { int test; cin >> test; vector<char> vc(test); stack<char> stk; int chk = 1; for (int i = 0; i < test; i++) { cin >> vc[i]; switch (vc[i]) { case '[': case '{': case '(': case '<': stk.push(vc[i]); break; case ']': if (stk.top() == '[') { stk.pop(); }else { chk = 0; } break; case '}': if (stk.top() == '{'){ stk.pop(); }else { chk = 0; } break; case ')': if (stk.top() == '('){ stk.pop(); }else { chk = 0; } break; case '>': if (stk.top() == '<'){ stk.pop(); }else { chk = 0; } break; } } if (!stk.empty() || chk == 0) cout << "#" << test_case << " " << 0 << endl; else cout << "#" << test_case << " " << 1 << endl; } return 0; }
38.261538
69
0.178126
sungmen
fe3abe9f69d4ccbbdf68b5b27e766cafa3958e47
1,937
cpp
C++
tests/LpmSphereVoronoiMeshUnitTests.cpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
tests/LpmSphereVoronoiMeshUnitTests.cpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
18
2021-06-27T17:59:03.000Z
2022-02-22T03:41:27.000Z
tests/LpmSphereVoronoiMeshUnitTests.cpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
#include "LpmConfig.h" #include "LpmDefs.hpp" #include "Kokkos_Core.hpp" #include "LpmMeshSeed.hpp" #include "LpmSphereVoronoiPrimitives.hpp" #include "LpmSphereVoronoiMesh.hpp" #include "LpmVtkIO.hpp" #include <iostream> #include <iomanip> #include <string> #include <exception> using namespace Lpm; using namespace Voronoi; int main(int argc, char* argv[]) { ko::initialize(argc, argv); { std::ostringstream ss; ss << "Sphere Voronoi Mesh Unit tests:\n"; Int nerr=0; MeshSeed<IcosTriDualSeed> seed; VoronoiMesh<IcosTriDualSeed> vmesh0(seed, 0); std::vector<Index> vinds; std::vector<Index> einds0; std::vector<Index> einds1; std::vector<Index> finds; // std::cout << vmesh0.infoString(true); Voronoi::VtkInterface<IcosTriDualSeed> vtk; auto pd = vtk.toVtkPolyData(vmesh0); vtk.writePolyData("vmesh0.vtk", pd); for (Short i=0; i<vmesh0.nverts(); ++i) { vmesh0.getEdgesAndCellsAtVertex(einds0, finds, i); } for (Short i=0; i<vmesh0.ncells(); ++i) { vmesh0.getEdgesAndVerticesInCell(einds1, vinds, i); } for (Short i=0; i<vmesh0.ncells(); ++i) { const Real qpt[3] = {vmesh0.cells[i].xyz[0], vmesh0.cells[i].xyz[1], vmesh0.cells[i].xyz[2]}; const auto loc = vmesh0.cellContainingPoint(qpt, 0); if (loc != i) { ++nerr; } } for (Int i=5; i<7; ++i) { ss.str(std::string()); VoronoiMesh<IcosTriDualSeed> vmesh(seed,i); std::cout << vmesh.infoString(false); pd = vtk.toVtkPolyData(vmesh); ss << "vmesh" << i << ".vtk"; vtk.writePolyData(ss.str(),pd); } if (nerr>0) { throw std::runtime_error("point location identity test failed."); } if (nerr == 0) { ss << "\tall tests pass.\n"; std::cout << ss.str(); } else { throw std::runtime_error(ss.str()); } } ko::finalize(); return 0; }
24.2125
101
0.603511
pbosler
fe3f3a182ade1097886de34a2afef91e94945431
4,877
cpp
C++
sources/Base/spVertexFormatUniversal.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/Base/spVertexFormatUniversal.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/Base/spVertexFormatUniversal.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2016-10-31T06:08:44.000Z
2019-08-02T16:12:33.000Z
/* * Universal vertex format file * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #include "Base/spVertexFormatUniversal.hpp" #include "RenderSystem/spRenderSystem.hpp" namespace sp { extern video::RenderSystem* GlbRenderSys; namespace video { VertexFormatUniversal::VertexFormatUniversal() : VertexFormat( ), FormatSize_ (0 ) { } VertexFormatUniversal::~VertexFormatUniversal() { } u32 VertexFormatUniversal::getFormatSize() const { return FormatSize_; } void VertexFormatUniversal::addCoord(const ERendererDataTypes Type, s32 Size) { addAttribute(VERTEXFORMAT_COORD, Coord_, Size, Type, "POSITION", (Type == DATATYPE_FLOAT && Size == 3)); } void VertexFormatUniversal::addColor(const ERendererDataTypes Type, s32 Size) { addAttribute(VERTEXFORMAT_COLOR, Color_, Size, Type, "COLOR", (Type == DATATYPE_UNSIGNED_BYTE && Size == 4)); } void VertexFormatUniversal::addNormal(const ERendererDataTypes Type) { addAttribute(VERTEXFORMAT_NORMAL, Normal_, 3, Type, "NORMAL", (Type == DATATYPE_FLOAT)); } void VertexFormatUniversal::addBinormal(const ERendererDataTypes Type) { addAttribute(VERTEXFORMAT_BINORMAL, Binormal_, 3, Type, "BINORMAL", (Type == DATATYPE_FLOAT)); } void VertexFormatUniversal::addTangent(const ERendererDataTypes Type) { addAttribute(VERTEXFORMAT_TANGENT, Tangent_, 3, Type, "TANGENT", (Type == DATATYPE_FLOAT)); } void VertexFormatUniversal::addTexCoord(const ERendererDataTypes Type, s32 Size) { TexCoords_.resize(TexCoords_.size() + 1); addAttribute(VERTEXFORMAT_TEXCOORDS, TexCoords_[TexCoords_.size() - 1], Size, Type, "TEXCOORD" + io::stringc(TexCoords_.size() - 1)); } void VertexFormatUniversal::addFogCoord(const ERendererDataTypes Type) { addAttribute(VERTEXFORMAT_FOGCOORD, FogCoord_, 1, Type, "", (Type == DATATYPE_FLOAT)); } void VertexFormatUniversal::addUniversal( const ERendererDataTypes Type, s32 Size, const io::stringc &Name, bool Normalize, const EVertexFormatFlags Attribute) { Universals_.resize(Universals_.size() + 1); addAttribute(VERTEXFORMAT_UNIVERSAL, Universals_.back(), Size, Type, Name, false, Normalize); /* Link with special attribute */ switch (Attribute) { case VERTEXFORMAT_COORD: addVirtualAttribute(Attribute, Coord_); break; case VERTEXFORMAT_COLOR: addVirtualAttribute(Attribute, Color_); break; case VERTEXFORMAT_NORMAL: addVirtualAttribute(Attribute, Normal_); break; case VERTEXFORMAT_BINORMAL: addVirtualAttribute(Attribute, Binormal_); break; case VERTEXFORMAT_TANGENT: addVirtualAttribute(Attribute, Tangent_); break; case VERTEXFORMAT_FOGCOORD: addVirtualAttribute(Attribute, FogCoord_); break; case VERTEXFORMAT_TEXCOORDS: TexCoords_.resize(TexCoords_.size() + 1); addVirtualAttribute(Attribute, TexCoords_[TexCoords_.size() - 1]); break; default: break; } updateConstruction(); } void VertexFormatUniversal::remove(const EVertexFormatFlags Type) { switch (Type) { case VERTEXFORMAT_TEXCOORDS: TexCoords_.pop_back(); if (TexCoords_.empty()) removeFlag(Type); break; case VERTEXFORMAT_UNIVERSAL: Universals_.pop_back(); if (Universals_.empty()) removeFlag(Type); break; default: removeFlag(Type); break; } updateConstruction(); } void VertexFormatUniversal::clear() { if (FormatSize_) { /* Clear vertex attributes */ TexCoords_.clear(); Universals_.clear(); /* Reset format size */ FormatSize_ = 0; /* Delete vertex-input-layout (for D3D11 only) */ GlbRenderSys->updateVertexInputLayout(this, false); } } /* * ======= Private: ======= */ void VertexFormatUniversal::updateConstruction() { constructFormat(); VertexFormat::getFormatSize(FormatSize_); } void VertexFormatUniversal::addAttribute( const EVertexFormatFlags Flag, SVertexAttribute &Attrib, s32 Size, const ERendererDataTypes Type, const io::stringc &Name, bool hasDefaultSetting, bool Normalize) { addFlag(Flag); Attrib = SVertexAttribute(Size, Name, Type, hasDefaultSetting, Normalize); updateConstruction(); } void VertexFormatUniversal::addVirtualAttribute(const EVertexFormatFlags Attribute, SVertexAttribute &DestAttrib) { DestAttrib = Universals_.back(); DestAttrib.isReference = true; addFlag(Attribute); } } // /namespace video } // /namespace sp // ================================================================================
28.688235
137
0.67316
rontrek
fe402dad1b6dea7988a303d6a94d010af8a89733
3,327
cpp
C++
src/C/Security-57031.40.6/Security/libsecurity_apple_csp/tests/t.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C/Security-57031.40.6/Security/libsecurity_apple_csp/tests/t.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/Security-57031.40.6/Security/libsecurity_apple_csp/tests/t.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. * * The contents of this file constitute Original Code as defined in and are * subject to the Apple Public Source License Version 1.2 (the 'License'). * You may not use this file except in compliance with the License. Please obtain * a copy of the License at http://www.apple.com/publicsource and read it before * using this file. * * This Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the * specific language governing rights and limitations under the License. */ #include <bsafe.h> #include <aglobal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> B_ALGORITHM_METHOD *chooser[] = { &AM_SHA, &AM_SHA_RANDOM, NULL }; void dumpItem(ITEM &item, const char *name); unsigned char seed[] = { 17, 205, 99, 13, 6, 199 }; char data[] = "These are the times that try men's souls."; #define check(expr) \ if (status = (expr)) { printf("error %d at %d\n", status, __LINE__); abort(); } else /* ok */ int main(int argc, char *argv[]) { int status; ITEM key; key.data = (unsigned char *)"Walla Walla Washington! Yeah, yeah, yeah!"; key.len = strlen((const char *)key.data); B_KEY_OBJ bsKey = NULL; check(B_CreateKeyObject(&bsKey)); check(B_SetKeyInfo(bsKey, KI_Item, POINTER(&key))); B_ALGORITHM_OBJ macAlg = NULL; check(B_CreateAlgorithmObject(&macAlg)); B_DIGEST_SPECIFIER macSpec; macSpec.digestInfoType = AI_SHA1; macSpec.digestInfoParams = NULL_PTR; check(B_SetAlgorithmInfo(macAlg, AI_HMAC, POINTER(&macSpec))); check(B_DigestInit(macAlg, bsKey, chooser, NULL)); check(B_DigestUpdate(macAlg, POINTER(data), sizeof(data), NULL)); char mac[128]; unsigned int length; check(B_DigestFinal(macAlg, POINTER(mac), &length, sizeof(mac), NULL)); ITEM macItem; macItem.data = POINTER(mac); macItem.len = length; dumpItem(macItem, "MAC"); check(B_DigestUpdate(macAlg, POINTER(data), 10, NULL)); check(B_DigestUpdate(macAlg, POINTER(data+10), sizeof(data)-10, NULL)); check(B_DigestFinal(macAlg, POINTER(mac), &length, sizeof(mac), NULL)); macItem.data = POINTER(mac); macItem.len = length; dumpItem(macItem, "MAC"); printf("Done.\n"); exit(0); } void dumpItem(ITEM &item, const char *name) { printf("%s [%d] ", name, item.len); for (unsigned char *p = item.data; p < item.data + item.len; p++) printf("%2.2x", *p); printf("\n"); } void T_free(POINTER p) { free(p); } POINTER T_malloc(unsigned int size) { return (POINTER)malloc(size); } POINTER T_realloc(POINTER p, unsigned int size) { return (POINTER)realloc(p, size); } int T_memcmp(POINTER p1, POINTER p2, unsigned int size) { return memcmp(p1, p2, size); } void T_memcpy(POINTER p1, POINTER p2, unsigned int size) { memcpy(p1, p2, size); } void T_memmove(POINTER p1, POINTER p2, unsigned int size) { memmove(p1, p2, size); } void T_memset(POINTER p1, int size, unsigned int val) { memset(p1, size, val); } extern "C" int T_GetDynamicList() { printf("GetDynamicList!\n"); abort(); }
29.184211
95
0.706943
GaloisInc
fe4050b4f5bb5e2d2d9ec3ff5635768a635e43f4
4,419
cc
C++
third_party/blink/renderer/bindings/core/v8/referrer_script_info_test.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
third_party/blink/renderer/bindings/core/v8/referrer_script_info_test.cc
blueboxd/chromium-legacy
07223bc94bd97499909c9ed3c3f5769d718fe2e0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
third_party/blink/renderer/bindings/core/v8/referrer_script_info_test.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/bindings/core/v8/referrer_script_info.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "v8/include/v8.h" namespace blink { TEST(ReferrerScriptInfo, IsDefaultValue) { const KURL script_origin_resource_name("http://example.org/script.js"); // TODO(https://crbug.com/1114993): There three cases should be distinguished. EXPECT_TRUE(ReferrerScriptInfo().IsDefaultValue(script_origin_resource_name)); EXPECT_TRUE( ReferrerScriptInfo(script_origin_resource_name, ScriptFetchOptions()) .IsDefaultValue(script_origin_resource_name)); EXPECT_TRUE(ReferrerScriptInfo(KURL(), ScriptFetchOptions()) .IsDefaultValue(script_origin_resource_name)); EXPECT_FALSE( ReferrerScriptInfo(KURL("http://example.com"), ScriptFetchOptions()) .IsDefaultValue(script_origin_resource_name)); EXPECT_FALSE(ReferrerScriptInfo(KURL("http://example.com"), network::mojom::CredentialsMode::kInclude, "", kNotParserInserted, network::mojom::ReferrerPolicy::kDefault) .IsDefaultValue(script_origin_resource_name)); } TEST(ReferrerScriptInfo, ToFromV8NoReferencingScript) { V8TestingScope scope; const KURL script_origin_resource_name("http://example.org/script.js"); v8::Local<v8::PrimitiveArray> v8_info = ReferrerScriptInfo().ToV8HostDefinedOptions(scope.GetIsolate(), script_origin_resource_name); EXPECT_TRUE(v8_info.IsEmpty()); ReferrerScriptInfo decoded = ReferrerScriptInfo::FromV8HostDefinedOptions( scope.GetContext(), v8_info, script_origin_resource_name); // TODO(https://crbug.com/1235202): This should be null URL. EXPECT_EQ(script_origin_resource_name, decoded.BaseURL()); } TEST(ReferrerScriptInfo, ToFromV8ScriptOriginBaseUrl) { V8TestingScope scope; const KURL script_origin_resource_name("http://example.org/script.js"); v8::Local<v8::PrimitiveArray> v8_info = ReferrerScriptInfo(script_origin_resource_name, ScriptFetchOptions()) .ToV8HostDefinedOptions(scope.GetIsolate(), script_origin_resource_name); EXPECT_TRUE(v8_info.IsEmpty()); ReferrerScriptInfo decoded = ReferrerScriptInfo::FromV8HostDefinedOptions( scope.GetContext(), v8_info, script_origin_resource_name); EXPECT_EQ(script_origin_resource_name, decoded.BaseURL()); } TEST(ReferrerScriptInfo, ToFromV8ScriptNullBaseUrl) { V8TestingScope scope; const KURL script_origin_resource_name("http://example.org/script.js"); v8::Local<v8::PrimitiveArray> v8_info = ReferrerScriptInfo(KURL(), ScriptFetchOptions()) .ToV8HostDefinedOptions(scope.GetIsolate(), script_origin_resource_name); EXPECT_TRUE(v8_info.IsEmpty()); ReferrerScriptInfo decoded = ReferrerScriptInfo::FromV8HostDefinedOptions( scope.GetContext(), v8_info, script_origin_resource_name); // TODO(https://crbug.com/1235202): This should be null URL. EXPECT_EQ(script_origin_resource_name, decoded.BaseURL()); } TEST(ReferrerScriptInfo, ToFromV8) { V8TestingScope scope; const KURL script_origin_resource_name("http://example.org/script.js"); const KURL url("http://example.com"); ReferrerScriptInfo info(url, network::mojom::CredentialsMode::kInclude, "foobar", kNotParserInserted, network::mojom::ReferrerPolicy::kOrigin); v8::Local<v8::PrimitiveArray> v8_info = info.ToV8HostDefinedOptions( scope.GetIsolate(), script_origin_resource_name); ReferrerScriptInfo decoded = ReferrerScriptInfo::FromV8HostDefinedOptions( scope.GetContext(), v8_info, script_origin_resource_name); EXPECT_EQ(url, decoded.BaseURL()); EXPECT_EQ(network::mojom::CredentialsMode::kInclude, decoded.CredentialsMode()); EXPECT_EQ("foobar", decoded.Nonce()); EXPECT_EQ(kNotParserInserted, decoded.ParserState()); EXPECT_EQ(network::mojom::ReferrerPolicy::kOrigin, decoded.GetReferrerPolicy()); } } // namespace blink
40.541284
80
0.721656
Yannic
fe414fd5ca9e82c15c166379487841e8f3ede12f
1,841
hpp
C++
GenericSimulator/GenericSimulatorTemplates/core/EntityFreeFunc.hpp
ducis/pile-of-cpp
af5a123ec67cff589f27bf20d435b2db29a0a7c8
[ "MIT" ]
null
null
null
GenericSimulator/GenericSimulatorTemplates/core/EntityFreeFunc.hpp
ducis/pile-of-cpp
af5a123ec67cff589f27bf20d435b2db29a0a7c8
[ "MIT" ]
null
null
null
GenericSimulator/GenericSimulatorTemplates/core/EntityFreeFunc.hpp
ducis/pile-of-cpp
af5a123ec67cff589f27bf20d435b2db29a0a7c8
[ "MIT" ]
null
null
null
//#pragma once // //#include <Meta/entity.hpp> //#include <entity_as_boost_fusion_sequence.hpp> // //namespace GenericSim{ // namespace Entities{ // template < // typename GenericSim::Meta::GetEntityLabels<_Entity>::Type N0, // typename _Entity // > // typename GenericSim::Meta::GetEntityAtResultType_E1<_Entity,N0>::Type // At_E(_Entity &e){// overload this function for different types // return e.at_e<N0>(); // } // // template < // typename GenericSim::Meta::GetEntityLabels<_Entity>::Type N0, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0>::Type >::Type N1, // typename _Entity // > // typename GenericSim::Meta::GetEntityAtResultType_E2<_Entity,N0,N1>::Type // At_E(_Entity &e){ // return At_E1<N1>(At_E1<N0>(e)); // } // // template < // typename GenericSim::Meta::GetEntityLabels<_Entity>::Type N0, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0>::Type >::Type N1, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0,N1>::Type >::Type N2, // typename _Entity // > // typename GenericSim::Meta::GetEntityAtResultType_E3<_Entity,N0,N1,N2>::Type // At_E(_Entity &e){ // return At_E1<N2>(At_E2<N0,N1>(e)); // } // // template < // typename GenericSim::Meta::GetEntityLabels<_Entity>::Type N0, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0>::Type >::Type N1, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0,N1>::Type >::Type N2, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0,N1,N2>::Type >::Type N3, // typename _Entity // > // typename GenericSim::Meta::GetEntityAtResultType_E4<_Entity,N0,N1,N2,N3>::Type // At_E(_Entity &e){ // return At_E1<N3>(At_E3<N0,N1,N2>(e)); // } // } //}
36.82
97
0.674633
ducis
fe43ebf51be651d1da0fd64829ecf6a0b1efb7e8
670
cpp
C++
src/MeteringSDK/MCORE/MTypeCasting.cpp
beroset/C12Adapter
593b201db169481245b0673813e19d174560a41e
[ "MIT" ]
9
2016-09-02T17:24:58.000Z
2021-12-14T19:43:48.000Z
src/MeteringSDK/MCORE/MTypeCasting.cpp
beroset/C12Adapter
593b201db169481245b0673813e19d174560a41e
[ "MIT" ]
1
2018-09-06T21:48:42.000Z
2018-09-06T21:48:42.000Z
src/MeteringSDK/MCORE/MTypeCasting.cpp
beroset/C12Adapter
593b201db169481245b0673813e19d174560a41e
[ "MIT" ]
4
2016-09-06T16:54:36.000Z
2021-12-16T16:15:24.000Z
// File MCORE/MTypeCasting.cpp #include "MCOREExtern.h" #include "MObject.h" // included instead of MTypeCasting.h #include "MException.h" M_FUNC M_NORETURN_FUNC void MDoThrowBadConversionUint64(const char* typeName) { MException::Throw(MException::ErrorSoftware, M_CODE_STR_P1(MErrorEnum::BadConversion, M_I("Could not convert 64-bit unsigned integer to '%s'"), typeName)); M_ENSURED_ASSERT(0); } M_FUNC M_NORETURN_FUNC void MDoThrowBadConversionInt64(const char* typeName) { MException::Throw(MException::ErrorSoftware, M_CODE_STR_P1(MErrorEnum::BadConversion, M_I("Could not convert 64-bit signed integer to '%s'"), typeName)); M_ENSURED_ASSERT(0); }
35.263158
158
0.777612
beroset
1cfa8e7e33e56d8e5c4cf632073d685c6b267107
66,919
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/CWifiConfiguration.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/CWifiConfiguration.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/CWifiConfiguration.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/text/TextUtils.h" #include "elastos/droid/wifi/CWifiConfigurationKeyMgmt.h" #include "elastos/droid/wifi/CWifiConfigurationProtocol.h" #include "elastos/droid/wifi/CWifiConfigurationPairwiseCipher.h" #include "elastos/droid/wifi/CWifiConfigurationAuthAlgorithm.h" #include "elastos/droid/wifi/CWifiConfigurationGroupCipher.h" #include "elastos/droid/wifi/CWifiConfiguration.h" #include "elastos/droid/wifi/CWifiConfigurationVisibility.h" #include "elastos/droid/wifi/CWifiEnterpriseConfig.h" #include "elastos/droid/wifi/CWifiSsid.h" #include "elastos/droid/net/CLinkProperties.h" #include "elastos/droid/net/CIpConfiguration.h" #include <elastos/core/StringBuilder.h> #include <elastos/core/StringUtils.h> using Elastos::Droid::Text::TextUtils; using Elastos::Droid::Net::CLinkProperties; using Elastos::Droid::Net::CIpConfiguration; using Elastos::Core::CString; using Elastos::Core::CSystem; using Elastos::Core::EIID_IComparator; using Elastos::Core::ICharSequence; using Elastos::Core::ICloneable; using Elastos::Core::IInteger32; using Elastos::Core::IString; using Elastos::Core::ISystem; using Elastos::Core::StringBuilder; using Elastos::Core::StringUtils; using Elastos::Utility::CArrayList; using Elastos::Utility::CBitSet; using Elastos::Utility::CCollections; using Elastos::Utility::CHashMap; using Elastos::Utility::ICollections; using Elastos::Utility::IMap; using Elastos::Utility::IIterable; using Elastos::Utility::IIterator; namespace Elastos { namespace Droid { namespace Wifi { //================================================================ // CWifiConfiguration::InnerComparator //================================================================ CAR_INTERFACE_IMPL(CWifiConfiguration::InnerComparator, Object, IComparator) CWifiConfiguration::InnerComparator::InnerComparator( /* [in] */ CWifiConfiguration* owner) : mOnwer(owner) { } ECode CWifiConfiguration::InnerComparator::Compare( /* [in] */ IInterface* lhs, /* [in] */ IInterface* rhs, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); AutoPtr<IScanResult> a = IScanResult::Probe(lhs); AutoPtr<IScanResult> b = IScanResult::Probe(rhs); Int32 aNumIpConfigFailures, bNumIpConfigFailures; a->GetNumIpConfigFailures(&aNumIpConfigFailures); b->GetNumIpConfigFailures(&bNumIpConfigFailures); if (aNumIpConfigFailures > bNumIpConfigFailures) { *result = 1; return NOERROR; } if (aNumIpConfigFailures < bNumIpConfigFailures) { *result = -1; return NOERROR; } Int64 aSeen, bSeen; a->GetSeen(&aSeen); b->GetSeen(&bSeen); if (aSeen > bSeen) { *result = -1; return NOERROR; } if (aSeen < bSeen) { *result = 1; return NOERROR; } Int32 aLevel, bLevel; a->GetLevel(&aLevel); b->GetLevel(&bLevel); if (aLevel > bLevel) { *result = -1; return NOERROR; } if (aLevel < bLevel) { *result = 1; return NOERROR; } String aBSSID, bBSSID; a->GetBSSID(&aBSSID); b->GetBSSID(&bBSSID); *result = aBSSID.Compare(bBSSID); return NOERROR; } //================================================================ // CWifiConfiguration //================================================================ CAR_INTERFACE_IMPL_2(CWifiConfiguration, Object, IWifiConfiguration, IParcelable) CAR_OBJECT_IMPL(CWifiConfiguration) ECode CWifiConfiguration::constructor() { mNetworkId = IWifiConfiguration::INVALID_NETWORK_ID; mPriority = 0; mHiddenSSID = FALSE; mIsIBSS = FALSE; mFrequency = 0; mDisableReason = IWifiConfiguration::DISABLED_UNKNOWN_REASON; CBitSet::New((IBitSet**)&mAllowedKeyManagement); CBitSet::New((IBitSet**)&mAllowedProtocols); CBitSet::New((IBitSet**)&mAllowedAuthAlgorithms); CBitSet::New((IBitSet**)&mAllowedPairwiseCiphers); CBitSet::New((IBitSet**)&mAllowedGroupCiphers); mWepKeys = ArrayOf<String>::Alloc(4); for (Int32 i = 0; i < mWepKeys->GetLength(); i++) { (*mWepKeys)[i] = NULL; } CWifiEnterpriseConfig::New((IWifiEnterpriseConfig**)&mEnterpriseConfig); mAutoJoinStatus = AUTO_JOIN_ENABLED; mSelfAdded = FALSE; mDidSelfAdd = FALSE; mEphemeral = FALSE; mNoInternetAccess = FALSE; mStatus = 0; mDirty = FALSE; mWepTxKeyIndex = 0; mRequirePMF = FALSE; mCreatorUid = 0; mLastConnectUid = 0; mLastUpdateUid = 0; mNumConnectionFailures = 0; mNumIpConfigFailures = 0; mNumAuthFailures = 0; mBlackListTimestamp = 0; mLastConnected = 0; mLastConnectionFailure = 0; mLastDisconnected = 0; mAutoJoinBailedDueToLowRssi = FALSE; mAutoJoinUseAggressiveJoinAttemptThreshold = 0; mNumScorerOverride = 0; mNumScorerOverrideAndSwitchedNetwork = 0; mNumAssociation = 0; mNumUserTriggeredWifiDisableLowRSSI = 0; mNumUserTriggeredWifiDisableBadRSSI = 0; mNumUserTriggeredWifiDisableNotHighRSSI = 0; mNumTicksAtLowRSSI = 0; mNumTicksAtBadRSSI = 0; mNumTicksAtNotHighRSSI = 0; mNumUserTriggeredJoinAttempts = 0; mDuplicateNetwork = FALSE; return CIpConfiguration::New((IIpConfiguration**)&mIpConfiguration); } ECode CWifiConfiguration::constructor( /* [in] */ IWifiConfiguration* source) { if (source != NULL) { source->GetNetworkId(&mNetworkId); source->GetStatus(&mStatus); source->GetDisableReason(&mDisableReason); source->GetSSID(&mSSID); source->GetBSSID(&mBSSID); source->GetFQDN(&mFQDN); source->GetNaiRealm(&mNaiRealm); source->GetPreSharedKey(&mPreSharedKey); mWepKeys = ArrayOf<String>::Alloc(4); AutoPtr< ArrayOf<String> > wepKeys; source->GetWepKeys((ArrayOf<String>**)&wepKeys); for (Int32 i = 0; i < wepKeys->GetLength(); i++) { (*mWepKeys)[i] = (*wepKeys)[i]; } source->GetWepTxKeyIndex(&mWepTxKeyIndex); source->GetPriority(&mPriority); source->GetHiddenSSID(&mHiddenSSID); source->GetIsIBSS(&mIsIBSS); source->GetFrequency(&mFrequency); AutoPtr<IBitSet> allowedKeyManagement; AutoPtr<IBitSet> allowedProtocols; AutoPtr<IBitSet> allowedAuthAlgorithms; AutoPtr<IBitSet> allowedPairwiseCiphers; AutoPtr<IBitSet> allowedGroupCiphers; source->GetAllowedKeyManagement((IBitSet**)&allowedKeyManagement); AutoPtr<IInterface> obj; ICloneable::Probe(allowedKeyManagement)->Clone((IInterface**)&obj); mAllowedKeyManagement = IBitSet::Probe(obj); obj = NULL; source->GetAllowedProtocols((IBitSet**)&allowedProtocols); ICloneable::Probe(allowedProtocols)->Clone((IInterface**)&obj); mAllowedProtocols = IBitSet::Probe(obj); obj = NULL; source->GetAllowedAuthAlgorithms((IBitSet**)&allowedAuthAlgorithms); ICloneable::Probe(allowedAuthAlgorithms)->Clone((IInterface**)&obj); mAllowedAuthAlgorithms = IBitSet::Probe(obj); obj = NULL; source->GetAllowedPairwiseCiphers((IBitSet**)&allowedPairwiseCiphers); ICloneable::Probe(allowedPairwiseCiphers)->Clone((IInterface**)&obj); mAllowedPairwiseCiphers = IBitSet::Probe(obj); obj = NULL; source->GetAllowedGroupCiphers((IBitSet**)&allowedGroupCiphers); ICloneable::Probe(allowedGroupCiphers)->Clone((IInterface**)&obj); mAllowedGroupCiphers = IBitSet::Probe(obj); AutoPtr<IWifiEnterpriseConfig> enterpriseConfig; source->GetEnterpriseConfig((IWifiEnterpriseConfig**)&enterpriseConfig); CWifiEnterpriseConfig::New(enterpriseConfig, (IWifiEnterpriseConfig**)&mEnterpriseConfig); source->GetDefaultGwMacAddress(&mDefaultGwMacAddress); AutoPtr<IIpConfiguration> ipConfiguration; source->GetIpConfiguration((IIpConfiguration**)&ipConfiguration); CIpConfiguration::New(ipConfiguration, (IIpConfiguration**)&mIpConfiguration); AutoPtr<IHashMap> scanResultCache; source->GetScanResultCache((IHashMap**)&scanResultCache); Int32 size; if ((scanResultCache != NULL) && (scanResultCache->GetSize(&size), size > 0)) { CHashMap::New((IHashMap**)&mScanResultCache); mScanResultCache->PutAll(IMap::Probe(scanResultCache)); } AutoPtr<IHashMap> connectChoices; source->GetConnectChoices((IHashMap**)&connectChoices); if (connectChoices != NULL && (connectChoices->GetSize(&size), size > 0)) { CHashMap::New((IHashMap**)&mConnectChoices); mConnectChoices->PutAll(IMap::Probe(connectChoices)); } AutoPtr<IHashMap> linkedConfigurations; source->GetLinkedConfigurations((IHashMap**)&linkedConfigurations); if ((linkedConfigurations != NULL) && (linkedConfigurations->GetSize(&size), size > 0)) { CHashMap::New((IHashMap**)&mLinkedConfigurations); mLinkedConfigurations->PutAll(IMap::Probe(linkedConfigurations)); } mCachedConfigKey = NULL; //force null configKey source->GetAutoJoinStatus(&mAutoJoinStatus); source->GetSelfAdded(&mSelfAdded); source->GetNoInternetAccess(&mNoInternetAccess); AutoPtr<IWifiConfigurationVisibility> visibility; source->GetVisibility((IWifiConfigurationVisibility**)&visibility); if (visibility != NULL) { CWifiConfigurationVisibility::New(visibility, (IWifiConfigurationVisibility**)&mVisibility); } source->GetLastFailure(&mLastFailure); source->GetDidSelfAdd(&mDidSelfAdd); source->GetLastConnectUid(&mLastConnectUid); source->GetLastUpdateUid(&mLastUpdateUid); source->GetCreatorUid(&mCreatorUid); source->GetPeerWifiConfiguration(&mPeerWifiConfiguration); source->GetBlackListTimestamp(&mBlackListTimestamp); source->GetLastConnected(&mLastConnected); source->GetLastDisconnected(&mLastDisconnected); source->GetLastConnectionFailure(&mLastConnectionFailure); source->GetNumConnectionFailures(&mNumConnectionFailures); source->GetNumIpConfigFailures(&mNumIpConfigFailures); source->GetNumAuthFailures(&mNumAuthFailures); source->GetNumScorerOverride(&mNumScorerOverride); source->GetNumScorerOverrideAndSwitchedNetwork(&mNumScorerOverrideAndSwitchedNetwork); source->GetNumAssociation(&mNumAssociation); source->GetNumUserTriggeredWifiDisableLowRSSI(&mNumUserTriggeredWifiDisableLowRSSI); source->GetNumUserTriggeredWifiDisableBadRSSI(&mNumUserTriggeredWifiDisableBadRSSI); source->GetNumUserTriggeredWifiDisableNotHighRSSI(&mNumUserTriggeredWifiDisableNotHighRSSI); source->GetNumTicksAtLowRSSI(&mNumTicksAtLowRSSI); source->GetNumTicksAtBadRSSI(&mNumTicksAtBadRSSI); source->GetNumTicksAtNotHighRSSI(&mNumTicksAtNotHighRSSI); source->GetNumUserTriggeredJoinAttempts(&mNumUserTriggeredJoinAttempts); source->GetAutoJoinBSSID(&mAutoJoinBSSID); source->GetAutoJoinUseAggressiveJoinAttemptThreshold(&mAutoJoinUseAggressiveJoinAttemptThreshold); source->GetAutoJoinBailedDueToLowRssi(&mAutoJoinBailedDueToLowRssi); source->GetDirty(&mDirty); source->GetDuplicateNetwork(&mDuplicateNetwork); } return NOERROR; } ECode CWifiConfiguration::ToString( /* [out] */ String* value) { VALIDATE_NOT_NULL(value); StringBuilder sbuf; if (mStatus == IWifiConfigurationStatus::CURRENT) { sbuf.Append("* "); } else if (mStatus == IWifiConfigurationStatus::DISABLED) { sbuf.Append("- DSBLE "); } sbuf.Append("ID: "); sbuf.Append(mNetworkId); sbuf.Append(" SSID: "); sbuf.Append(mSSID); sbuf.Append(" BSSID: "); sbuf.Append(mBSSID); sbuf.Append(" FQDN: "); sbuf.Append(mFQDN); sbuf.Append(" REALM: "); sbuf.Append(mNaiRealm); sbuf.Append(" PRIO: "); sbuf.Append(mPriority); sbuf.AppendChar('\n'); if (mNumConnectionFailures > 0) { sbuf.Append(" numConnectFailures "); sbuf.Append(mNumConnectionFailures); sbuf.Append("\n"); } if (mNumIpConfigFailures > 0) { sbuf.Append(" numIpConfigFailures "); sbuf.Append(mNumIpConfigFailures); sbuf.Append("\n"); } if (mNumAuthFailures > 0) { sbuf.Append(" numAuthFailures "); sbuf.Append(mNumAuthFailures); sbuf.Append("\n"); } if (mAutoJoinStatus > 0) { sbuf.Append(" autoJoinStatus "); sbuf.Append(mAutoJoinStatus); sbuf.Append("\n"); } if (mDisableReason > 0) { sbuf.Append(" disableReason "); sbuf.Append(mDisableReason); sbuf.Append("\n"); } if (mNumAssociation > 0) { sbuf.Append(" numAssociation "); sbuf.Append(mNumAssociation); sbuf.Append("\n"); } if (mDidSelfAdd) sbuf.Append(" didSelfAdd"); if (mSelfAdded) sbuf.Append(" selfAdded"); if (mNoInternetAccess) sbuf.Append(" noInternetAccess"); if (mDidSelfAdd || mSelfAdded || mNoInternetAccess) { sbuf.Append("\n"); } AutoPtr<IWifiConfigurationKeyMgmt> keyMgmt; CWifiConfigurationKeyMgmt::AcquireSingleton((IWifiConfigurationKeyMgmt**)&keyMgmt); AutoPtr< ArrayOf<String> > strings; keyMgmt->GetStrings((ArrayOf<String>**)&strings); sbuf.Append(" KeyMgmt:"); Int32 size; mAllowedKeyManagement->GetSize(&size); for (Int32 k = 0; k < size; k++) { Boolean bFlag; mAllowedKeyManagement->Get(k, &bFlag); if (bFlag) { sbuf.Append(" "); if (k < strings->GetLength()) { sbuf.Append((*strings)[k]); } else { sbuf.Append("??"); } } } sbuf.Append("\n Protocols:"); mAllowedProtocols->GetSize(&size); for (Int32 p = 0; p < size; p++) { Boolean bFlag; mAllowedProtocols->Get(p, &bFlag); if (bFlag) { sbuf.Append(" "); AutoPtr<IWifiConfigurationProtocol> protocol; CWifiConfigurationProtocol::AcquireSingleton((IWifiConfigurationProtocol**)&protocol); AutoPtr< ArrayOf<String> > strings; protocol->GetStrings((ArrayOf<String>**)&strings); if (p < strings->GetLength()) { sbuf.Append((*strings)[p]); } else { sbuf.Append("??"); } } } sbuf.AppendChar('\n'); sbuf.Append(" AuthAlgorithms:"); mAllowedAuthAlgorithms->GetSize(&size); for (Int32 a = 0; a < size; a++) { Boolean bFlag; mAllowedAuthAlgorithms->Get(a, &bFlag); if (bFlag) { sbuf.Append(" "); AutoPtr<IWifiConfigurationAuthAlgorithm> algorithm; CWifiConfigurationAuthAlgorithm::AcquireSingleton((IWifiConfigurationAuthAlgorithm**)&algorithm); AutoPtr< ArrayOf<String> > strings; algorithm->GetStrings((ArrayOf<String>**)&strings); if (a < strings->GetLength()) { sbuf.Append((*strings)[a]); } else { sbuf.Append("??"); } } } sbuf.AppendChar('\n'); sbuf.Append(" PairwiseCiphers:"); mAllowedPairwiseCiphers->GetSize(&size); for (Int32 pc = 0; pc < size; pc++) { Boolean bFlag; mAllowedPairwiseCiphers->Get(pc, &bFlag); if (bFlag) { sbuf.Append(" "); AutoPtr<IWifiConfigurationPairwiseCipher> clipher; CWifiConfigurationPairwiseCipher::AcquireSingleton((IWifiConfigurationPairwiseCipher**)&clipher); AutoPtr< ArrayOf<String> > strings; clipher->GetStrings((ArrayOf<String>**)&strings); if (pc < strings->GetLength()) { sbuf.Append((*strings)[pc]); } else { sbuf.Append("??"); } } } sbuf.AppendChar('\n'); sbuf.Append(" GroupCiphers:"); mAllowedGroupCiphers->GetSize(&size); for (Int32 gc = 0; gc < size; gc++) { Boolean bFlag; mAllowedGroupCiphers->Get(gc, &bFlag); if (bFlag) { sbuf.Append(" "); AutoPtr<IWifiConfigurationGroupCipher> cipher; CWifiConfigurationGroupCipher::AcquireSingleton((IWifiConfigurationGroupCipher**)&cipher); AutoPtr< ArrayOf<String> > strings; cipher->GetStrings((ArrayOf<String>**)&strings); if (gc < strings->GetLength()) { sbuf.Append((*strings)[gc]); } else { sbuf.Append("??"); } } } sbuf.AppendChar('\n'); sbuf.Append(" PSK: "); if (mPreSharedKey != NULL) { sbuf.AppendChar('*'); } sbuf.Append("\nEnterprise config:\n"); String enterpriseConfigStr; IObject::Probe(mEnterpriseConfig)->ToString(&enterpriseConfigStr); sbuf.Append(enterpriseConfigStr); sbuf.Append("IP config:\n"); String ipConfigurationStr; IObject::Probe(mIpConfiguration)->ToString(&ipConfigurationStr); sbuf.Append(ipConfigurationStr); if (mCreatorUid != 0) { sbuf.Append(" uid="); sbuf.Append(mCreatorUid); } if (mAutoJoinBSSID != NULL) { sbuf.Append(" autoJoinBSSID="); sbuf.Append(mAutoJoinBSSID); } AutoPtr<ISystem> system; CSystem::AcquireSingleton((ISystem**)&system); Int64 now_ms; system->GetCurrentTimeMillis(&now_ms); if (mBlackListTimestamp != 0) { sbuf.AppendChar('\n'); Int64 diff = now_ms - mBlackListTimestamp; if (diff <= 0) { sbuf.Append(" blackListed since <incorrect>"); } else { sbuf.Append(" blackListed: "); sbuf.Append(diff/1000); sbuf.Append( "sec"); } } if (mLastConnected != 0) { sbuf.AppendChar('\n'); Int64 diff = now_ms - mLastConnected; if (diff <= 0) { sbuf.Append("lastConnected since <incorrect>"); } else { sbuf.Append("lastConnected: "); sbuf.Append(diff/1000); sbuf.Append( "sec"); } } if (mLastConnectionFailure != 0) { sbuf.AppendChar('\n'); Int64 diff = now_ms - mLastConnectionFailure; if (diff <= 0) { sbuf.Append("lastConnectionFailure since <incorrect>"); } else { sbuf.Append("lastConnectionFailure: "); sbuf.Append(diff/1000); sbuf.Append( "sec"); } } sbuf.AppendChar('\n'); if (mLinkedConfigurations != NULL) { AutoPtr<ISet> keySet; mLinkedConfigurations->GetKeySet((ISet**)&keySet); AutoPtr<IIterator> iter; keySet->GetIterator((IIterator**)&iter); Boolean bNext; iter->HasNext(&bNext); for (; bNext; iter->HasNext(&bNext)) { AutoPtr<IInterface> iKey; iter->GetNext((IInterface**)&iKey); String key; ICharSequence::Probe(iKey)->ToString(&key); sbuf.Append(" linked: "); sbuf.Append(key); sbuf.AppendChar('\n'); } } if (mConnectChoices != NULL) { AutoPtr<ISet> keySet; mConnectChoices->GetKeySet((ISet**)&keySet); AutoPtr<IIterator> iter; keySet->GetIterator((IIterator**)&iter); Boolean bNext; iter->HasNext(&bNext); for (; bNext; iter->HasNext(&bNext)) { AutoPtr<IInterface> iKey; iter->GetNext((IInterface**)&iKey); AutoPtr<IInterface> choice; mConnectChoices->Get(iKey, (IInterface**)&choice); if (choice != NULL) { sbuf.Append(" choice: "); String key; ICharSequence::Probe(iKey)->ToString(&key); sbuf.Append(key); sbuf.Append(" = "); Int32 value; IInteger32::Probe(choice)->GetValue(&value); sbuf.Append(value); sbuf.AppendChar('\n'); } } } if (mScanResultCache != NULL) { sbuf.Append("Scan Cache: "); sbuf.AppendChar('\n'); AutoPtr<IArrayList> list = SortScanResults(); Int32 listSize; list->GetSize(&listSize); if (listSize > 0) { AutoPtr<IIterable> iterable = IIterable::Probe(list); AutoPtr<IIterator> iter; iterable->GetIterator((IIterator**)&iter); Boolean bNext; iter->HasNext(&bNext); for (; bNext; iter->HasNext(&bNext)) { AutoPtr<IInterface> obj; iter->GetNext((IInterface**)&obj); IScanResult* result = IScanResult::Probe(obj); Int64 seen; result->GetSeen(&seen); Int64 milli = now_ms - seen; Int64 ageSec = 0; Int64 ageMin = 0; Int64 ageHour = 0; Int64 ageMilli = 0; Int64 ageDay = 0; if (now_ms > seen && seen > 0) { ageMilli = milli % 1000; ageSec = (milli / 1000) % 60; ageMin = (milli / (60*1000)) % 60; ageHour = (milli / (60*60*1000)) % 24; ageDay = (milli / (24*60*60*1000)); } sbuf.Append("{"); String BSSID; result->GetBSSID(&BSSID); sbuf.Append(BSSID); sbuf.Append(","); Int32 frequency; result->GetFrequency(&frequency); sbuf.Append(frequency); sbuf.Append(","); Int32 level; result->GetLevel(&level); sbuf.Append(String().AppendFormat("%3d", level)); Int32 autoJoinStatus; result->GetAutoJoinStatus(&autoJoinStatus); if (autoJoinStatus > 0) { sbuf.Append(",st="); sbuf.Append(autoJoinStatus); } if (ageSec > 0 || ageMilli > 0) { sbuf.Append(String().AppendFormat(",%4d.%02d.%02d.%02d.%03dms", ageDay, ageHour, ageMin, ageSec, ageMilli)); } Int32 numIpConfigFailures; result->GetNumIpConfigFailures(&numIpConfigFailures); if (numIpConfigFailures > 0) { sbuf.Append(",ipfail="); sbuf.Append(numIpConfigFailures); } sbuf.Append("} "); } sbuf.AppendChar('\n'); } } sbuf.Append("triggeredLow: "); sbuf.Append(mNumUserTriggeredWifiDisableLowRSSI); sbuf.Append(" triggeredBad: "); sbuf.Append(mNumUserTriggeredWifiDisableBadRSSI); sbuf.Append(" triggeredNotHigh: "); sbuf.Append(mNumUserTriggeredWifiDisableNotHighRSSI); sbuf.AppendChar('\n'); sbuf.Append("ticksLow: "); sbuf.Append(mNumTicksAtLowRSSI); sbuf.Append(" ticksBad: "); sbuf.Append(mNumTicksAtBadRSSI); sbuf.Append(" ticksNotHigh: "); sbuf.Append(mNumTicksAtNotHighRSSI); sbuf.AppendChar('\n'); sbuf.Append("triggeredJoin: "); sbuf.Append(mNumUserTriggeredJoinAttempts); sbuf.AppendChar('\n'); sbuf.Append("autoJoinBailedDueToLowRssi: "); sbuf.Append(mAutoJoinBailedDueToLowRssi); sbuf.AppendChar('\n'); sbuf.Append("autoJoinUseAggressiveJoinAttemptThreshold: "); sbuf.Append(mAutoJoinUseAggressiveJoinAttemptThreshold); sbuf.AppendChar('\n'); return sbuf.ToString(value); } ECode CWifiConfiguration::GetPrintableSsid( /* [out] */ String* ssid) { VALIDATE_NOT_NULL(ssid); if (mSSID.IsNull()) { *ssid = ""; return NOERROR; } AutoPtr<ArrayOf<Char32> > charArray = mSSID.GetChars(); Int32 length = charArray->GetLength(); if (length > 2 && ((*charArray)[0] == '"') && (*charArray)[length - 1] == '"') { *ssid = mSSID.Substring(1, length - 1); return NOERROR; } /** The ascii-encoded string format is P"<ascii-encoded-string>" * The decoding is implemented in the supplicant for a newly configured * network. */ if (length > 3 && ((*charArray)[0] == 'P') && ((*charArray)[1] == '"') && ((*charArray)[length - 1] == '"')) { AutoPtr<IWifiSsid> wifiSsid; CWifiSsid::CreateFromAsciiEncoded(mSSID.Substring(2, length - 1), (IWifiSsid**)&wifiSsid); return IObject::Probe(wifiSsid)->ToString(ssid); } *ssid = mSSID; return NOERROR; } AutoPtr<IBitSet> CWifiConfiguration::ReadBitSet( /* [in] */ IParcel* src) { Int32 cardinality; src->ReadInt32(&cardinality); AutoPtr<IBitSet> set; CBitSet::New((IBitSet**)&set); for (Int32 i = 0; i < cardinality; i++) { Int32 index; src->ReadInt32(&index); set->Set(index); } return set; } void CWifiConfiguration::WriteBitSet( /* [in] */ IParcel* dest, /* [in] */ IBitSet* set) { Int32 nextSetBit = -1; Int32 number = 0; set->Cardinality(&number); dest->WriteInt32(number); while (set->NextSetBit(nextSetBit + 1, &nextSetBit), nextSetBit != -1) { dest->WriteInt32(nextSetBit); } } AutoPtr<IArrayList> CWifiConfiguration::SortScanResults() { AutoPtr<ICollection> values; mScanResultCache->GetValues((ICollection**)&values); AutoPtr<IArrayList> list; CArrayList::New(values, (IArrayList**)&list); Int32 size; list->GetSize(&size); if (size != 0) { AutoPtr<ICollections> collections; CCollections::AcquireSingleton((ICollections**)&collections); AutoPtr<IComparator> compare = new InnerComparator(this); collections->Sort(IList::Probe(list), compare); } return list; } String CWifiConfiguration::TrimStringForKeyId( /* [in] */ const String& string) { // Remove quotes and spaces String temp; StringUtils::Replace(string, "\"", "", &temp); String temp2; StringUtils::Replace(temp, " ", "", &temp2); //return string.Replace("\"", "").Replace(" ", ""); return temp2; } ECode CWifiConfiguration::GetAuthType( /* [out] */ Int32* authType) { VALIDATE_NOT_NULL(authType); *authType = IWifiConfigurationKeyMgmt::NONE; Boolean bIsValid; IsValid(&bIsValid); if (bIsValid == FALSE) { //throw new IllegalStateException("Invalid configuration"); return E_ILLEGAL_STATE_EXCEPTION; } Boolean temp; if (mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::WPA_PSK, &temp), temp) { *authType = IWifiConfigurationKeyMgmt::WPA_PSK; } else if (mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::WPA2_PSK, &temp), temp) { *authType = IWifiConfigurationKeyMgmt::WPA2_PSK; } else if (mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::WPA_EAP, &temp), temp) { *authType = IWifiConfigurationKeyMgmt::WPA_EAP; } else if (mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::IEEE8021X, &temp), temp) { *authType = IWifiConfigurationKeyMgmt::IEEE8021X; } return NOERROR; } ECode CWifiConfiguration::ReadFromParcel( /* [in] */ IParcel* source) { source->ReadInt32(&mNetworkId); source->ReadInt32(&mStatus); source->ReadInt32(&mDisableReason); source->ReadString(&mSSID); source->ReadString(&mBSSID); source->ReadString(&mAutoJoinBSSID); source->ReadString(&mFQDN); source->ReadString(&mNaiRealm); source->ReadString(&mPreSharedKey); for (Int32 i = 0; i < mWepKeys->GetLength(); ++i) { String key; source->ReadString(&key); (*mWepKeys)[i] = key; } source->ReadInt32(&mWepTxKeyIndex); source->ReadInt32(&mPriority); source->ReadBoolean(&mHiddenSSID); source->ReadBoolean(&mIsIBSS); source->ReadInt32(&mFrequency); source->ReadBoolean(&mRequirePMF); source->ReadString(&mUpdateIdentifier); mAllowedKeyManagement = ReadBitSet(source); mAllowedProtocols = ReadBitSet(source); mAllowedAuthAlgorithms = ReadBitSet(source); mAllowedPairwiseCiphers = ReadBitSet(source); mAllowedGroupCiphers = ReadBitSet(source); AutoPtr<IInterface> ecObj; source->ReadInterfacePtr((Handle32*)&ecObj); mEnterpriseConfig = IWifiEnterpriseConfig::Probe(ecObj); AutoPtr<IInterface> icObj; source->ReadInterfacePtr((Handle32*)&icObj); mIpConfiguration = IIpConfiguration::Probe(icObj); source->ReadString(&mDhcpServer); source->ReadString(&mDefaultGwMacAddress); source->ReadInt32(&mAutoJoinStatus); source->ReadBoolean(&mSelfAdded); source->ReadBoolean(&mDidSelfAdd); source->ReadBoolean(&mNoInternetAccess); source->ReadInt32(&mCreatorUid); source->ReadInt32(&mLastConnectUid); source->ReadInt32(&mLastUpdateUid); source->ReadInt64(&mBlackListTimestamp); source->ReadInt64(&mLastConnectionFailure); source->ReadInt32(&mNumConnectionFailures); source->ReadInt32(&mNumIpConfigFailures); source->ReadInt32(&mNumAuthFailures); source->ReadInt32(&mNumScorerOverride); source->ReadInt32(&mNumScorerOverrideAndSwitchedNetwork); source->ReadInt32(&mNumAssociation); source->ReadInt32(&mNumUserTriggeredWifiDisableLowRSSI); source->ReadInt32(&mNumUserTriggeredWifiDisableBadRSSI); source->ReadInt32(&mNumUserTriggeredWifiDisableNotHighRSSI); source->ReadInt32(&mNumTicksAtLowRSSI); source->ReadInt32(&mNumTicksAtBadRSSI); source->ReadInt32(&mNumTicksAtNotHighRSSI); source->ReadInt32(&mNumUserTriggeredJoinAttempts); source->ReadInt32(&mAutoJoinUseAggressiveJoinAttemptThreshold); source->ReadBoolean(&mAutoJoinBailedDueToLowRssi); return NOERROR; } ECode CWifiConfiguration::WriteToParcel( /* [in] */ IParcel* dest) { dest->WriteInt32(mNetworkId); dest->WriteInt32(mStatus); dest->WriteInt32(mDisableReason); dest->WriteString(mSSID); dest->WriteString(mBSSID); dest->WriteString(mAutoJoinBSSID); dest->WriteString(mFQDN); dest->WriteString(mNaiRealm); dest->WriteString(mPreSharedKey); for (Int32 i = 0; i < mWepKeys->GetLength(); ++i) { dest->WriteString((*mWepKeys)[i]); } dest->WriteInt32(mWepTxKeyIndex); dest->WriteInt32(mPriority); dest->WriteBoolean(mHiddenSSID ? 1 : 0); dest->WriteBoolean(mIsIBSS ? 1 : 0); dest->WriteInt32(mFrequency); dest->WriteBoolean(mRequirePMF ? 1 : 0); dest->WriteString(mUpdateIdentifier); WriteBitSet(dest, mAllowedKeyManagement); WriteBitSet(dest, mAllowedProtocols); WriteBitSet(dest, mAllowedAuthAlgorithms); WriteBitSet(dest, mAllowedPairwiseCiphers); WriteBitSet(dest, mAllowedGroupCiphers); dest->WriteInterfacePtr(mEnterpriseConfig); dest->WriteInterfacePtr(mIpConfiguration); dest->WriteString(mDhcpServer); dest->WriteString(mDefaultGwMacAddress); dest->WriteInt32(mAutoJoinStatus); dest->WriteBoolean(mSelfAdded ? 1 : 0); dest->WriteBoolean(mDidSelfAdd ? 1 : 0); dest->WriteBoolean(mNoInternetAccess ? 1 : 0); dest->WriteInt32(mCreatorUid); dest->WriteInt32(mLastConnectUid); dest->WriteInt32(mLastUpdateUid); dest->WriteInt64(mBlackListTimestamp); dest->WriteInt64(mLastConnectionFailure); dest->WriteInt32(mNumConnectionFailures); dest->WriteInt32(mNumIpConfigFailures); dest->WriteInt32(mNumAuthFailures); dest->WriteInt32(mNumScorerOverride); dest->WriteInt32(mNumScorerOverrideAndSwitchedNetwork); dest->WriteInt32(mNumAssociation); dest->WriteInt32(mNumUserTriggeredWifiDisableLowRSSI); dest->WriteInt32(mNumUserTriggeredWifiDisableBadRSSI); dest->WriteInt32(mNumUserTriggeredWifiDisableNotHighRSSI); dest->WriteInt32(mNumTicksAtLowRSSI); dest->WriteInt32(mNumTicksAtBadRSSI); dest->WriteInt32(mNumTicksAtNotHighRSSI); dest->WriteInt32(mNumUserTriggeredJoinAttempts); dest->WriteInt32(mAutoJoinUseAggressiveJoinAttemptThreshold); dest->WriteBoolean(mAutoJoinBailedDueToLowRssi ? 1 : 0); return NOERROR; } String CWifiConfiguration::ConfigKey( /* [in] */ IScanResult* result) { String key("\""); String SSID; result->GetSSID(&SSID); key += SSID; key += "\""; String capabilities; result->GetCapabilities(&capabilities); if (capabilities.Contains("WEP")) { key += "-WEP"; } if (capabilities.Contains("PSK")) { key += "-"; AutoPtr<IWifiConfigurationKeyMgmt> keyMgmt; CWifiConfigurationKeyMgmt::AcquireSingleton((IWifiConfigurationKeyMgmt**)&keyMgmt); AutoPtr< ArrayOf<String> > strings; keyMgmt->GetStrings((ArrayOf<String>**)&strings); key += (*strings)[IWifiConfigurationKeyMgmt::WPA_PSK]; } if (capabilities.Contains("EAP")) { key += "-"; AutoPtr<IWifiConfigurationKeyMgmt> keyMgmt; CWifiConfigurationKeyMgmt::AcquireSingleton((IWifiConfigurationKeyMgmt**)&keyMgmt); AutoPtr< ArrayOf<String> > strings; keyMgmt->GetStrings((ArrayOf<String>**)&strings); key += (*strings)[IWifiConfigurationKeyMgmt::WPA_EAP]; } return key; } ECode CWifiConfiguration::GetWepKeyVarName( /* [in] */ Int32 index, /* [out] */ String* wepKeyVarName) { VALIDATE_NOT_NULL(wepKeyVarName); if (index < 0 || index > 3) return E_ILLEGAL_ARGUMENT_EXCEPTION; if (index == 0) *wepKeyVarName = "wep_key0"; else if (index == 1) *wepKeyVarName = "wep_key1"; else if (index == 2) *wepKeyVarName = "wep_key2"; else if (index == 3) *wepKeyVarName = "wep_key3"; return NOERROR; } ECode CWifiConfiguration::GetNetworkId( /* [out] */ Int32* networkId) { VALIDATE_NOT_NULL(networkId); *networkId = mNetworkId; return NOERROR; } ECode CWifiConfiguration::SetNetworkId( /* [in] */ Int32 networkId) { mNetworkId = networkId; return NOERROR; } ECode CWifiConfiguration::GetStatus( /* [out] */ Int32* status) { VALIDATE_NOT_NULL(status); *status = mStatus; return NOERROR; } ECode CWifiConfiguration::SetStatus( /* [in] */ Int32 status) { mStatus = status; return NOERROR; } ECode CWifiConfiguration::GetDirty( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mDirty; return NOERROR; } ECode CWifiConfiguration::SetDirty( /* [in] */ Boolean dirty) { mDirty = dirty; return NOERROR; } ECode CWifiConfiguration::GetDisableReason( /* [out] */ Int32* disableReason) { VALIDATE_NOT_NULL(disableReason); *disableReason = mDisableReason; return NOERROR; } ECode CWifiConfiguration::SetDisableReason( /* [in] */ Int32 disableReason) { mDisableReason = disableReason; return NOERROR; } ECode CWifiConfiguration::GetSSID( /* [out] */ String* SSID) { VALIDATE_NOT_NULL(SSID); *SSID = mSSID; return NOERROR; } ECode CWifiConfiguration::SetSSID( /* [in] */ const String& SSID) { mSSID = SSID; return NOERROR; } ECode CWifiConfiguration::GetBSSID( /* [out] */ String* BSSID) { VALIDATE_NOT_NULL(BSSID); *BSSID = mBSSID; return NOERROR; } ECode CWifiConfiguration::SetBSSID( /* [in] */ const String& BSSID) { mBSSID = BSSID; return NOERROR; } ECode CWifiConfiguration::GetFQDN( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mFQDN; return NOERROR; } ECode CWifiConfiguration::SetFQDN( /* [in] */ const String& FQDN) { mFQDN = FQDN; return NOERROR; } ECode CWifiConfiguration::GetNaiRealm( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mNaiRealm; return NOERROR; } ECode CWifiConfiguration::SetNaiRealm( /* [in] */ const String& naiRealm) { mNaiRealm = naiRealm; return NOERROR; } ECode CWifiConfiguration::GetPreSharedKey( /* [out] */ String* preSharedKey) { VALIDATE_NOT_NULL(preSharedKey); *preSharedKey = mPreSharedKey; return NOERROR; } ECode CWifiConfiguration::SetPreSharedKey( /* [in] */ const String& preSharedKey) { mPreSharedKey = preSharedKey; return NOERROR; } ECode CWifiConfiguration::GetWepKeys( /* [out, callee] */ ArrayOf<String>** wepKeys) { VALIDATE_NOT_NULL(wepKeys); *wepKeys = mWepKeys; REFCOUNT_ADD(*wepKeys); return NOERROR; } ECode CWifiConfiguration::SetWepKeys( /* [in] */ ArrayOf<String>* wepKeys) { mWepKeys = wepKeys; return NOERROR; } ECode CWifiConfiguration::GetWepTxKeyIndex( /* [out] */ Int32* wepTxKeyIndex) { VALIDATE_NOT_NULL(wepTxKeyIndex); *wepTxKeyIndex = mWepTxKeyIndex; return NOERROR; } ECode CWifiConfiguration::SetWepTxKeyIndex( /* [in] */ Int32 wepTxKeyIndex) { mWepTxKeyIndex = wepTxKeyIndex; return NOERROR; } ECode CWifiConfiguration::GetPriority( /* [out] */ Int32* priority) { VALIDATE_NOT_NULL(priority); *priority = mPriority; return NOERROR; } ECode CWifiConfiguration::SetPriority( /* [in] */ Int32 priority) { mPriority = priority; return NOERROR; } ECode CWifiConfiguration::GetHiddenSSID( /* [out] */ Boolean* hiddenSSID) { VALIDATE_NOT_NULL(hiddenSSID); *hiddenSSID = mHiddenSSID; return NOERROR; } ECode CWifiConfiguration::SetHiddenSSID( /* [in] */ Boolean hiddenSSID) { mHiddenSSID = hiddenSSID; return NOERROR; } ECode CWifiConfiguration::GetRequirePMF( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mRequirePMF; return NOERROR; } ECode CWifiConfiguration::SetRequirePMF( /* [in] */ Boolean requirePMF) { mRequirePMF = requirePMF; return NOERROR; } ECode CWifiConfiguration::GetUpdateIdentifier( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mUpdateIdentifier; return NOERROR; } ECode CWifiConfiguration::SetUpdateIdentifier( /* [in] */ const String& updateIdentifier) { mUpdateIdentifier = updateIdentifier; return NOERROR; } ECode CWifiConfiguration::GetIsIBSS( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mIsIBSS; return NOERROR; } ECode CWifiConfiguration::SetIsIBSS( /* [in] */ Boolean isIBSS) { mIsIBSS = isIBSS; return NOERROR; } ECode CWifiConfiguration::GetFrequency( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mFrequency; return NOERROR; } ECode CWifiConfiguration::SetFrequency( /* [in] */ Int32 frequency) { mFrequency = frequency; return NOERROR; } ECode CWifiConfiguration::GetAllowedKeyManagement( /* [out] */ IBitSet** allowedKeyManagement) { VALIDATE_NOT_NULL(allowedKeyManagement); *allowedKeyManagement = mAllowedKeyManagement; REFCOUNT_ADD(*allowedKeyManagement); return NOERROR; } ECode CWifiConfiguration::SetAllowedKeyManagement( /* [in] */ IBitSet* allowedKeyManagement) { mAllowedKeyManagement = allowedKeyManagement; return NOERROR; } ECode CWifiConfiguration::GetAllowedProtocols( /* [out] */ IBitSet** allowedProtocols) { VALIDATE_NOT_NULL(allowedProtocols); *allowedProtocols = mAllowedProtocols; REFCOUNT_ADD(*allowedProtocols); return NOERROR; } ECode CWifiConfiguration::SetAllowedProtocols( /* [in] */ IBitSet* allowedProtocols) { mAllowedProtocols = allowedProtocols; return NOERROR; } ECode CWifiConfiguration::GetAllowedAuthAlgorithms( /* [out] */ IBitSet** allowedAuthAlgorithms) { VALIDATE_NOT_NULL(allowedAuthAlgorithms); *allowedAuthAlgorithms = mAllowedAuthAlgorithms; REFCOUNT_ADD(*allowedAuthAlgorithms); return NOERROR; } ECode CWifiConfiguration::SetAllowedAuthAlgorithms( /* [in] */ IBitSet* allowedAuthAlgorithms) { mAllowedAuthAlgorithms = allowedAuthAlgorithms; return NOERROR; } ECode CWifiConfiguration::GetAllowedPairwiseCiphers( /* [out] */ IBitSet** allowedPairwiseCiphers) { VALIDATE_NOT_NULL(allowedPairwiseCiphers); *allowedPairwiseCiphers = mAllowedPairwiseCiphers; REFCOUNT_ADD(*allowedPairwiseCiphers); return NOERROR; } ECode CWifiConfiguration::SetAllowedPairwiseCiphers( /* [in] */ IBitSet* allowedPairwiseCiphers) { mAllowedPairwiseCiphers = allowedPairwiseCiphers; return NOERROR; } ECode CWifiConfiguration::GetAllowedGroupCiphers( /* [out] */ IBitSet** allowedGroupCiphers) { VALIDATE_NOT_NULL(allowedGroupCiphers); *allowedGroupCiphers = mAllowedGroupCiphers; REFCOUNT_ADD(*allowedGroupCiphers); return NOERROR; } ECode CWifiConfiguration::SetAllowedGroupCiphers( /* [in] */ IBitSet* allowedGroupCiphers) { mAllowedGroupCiphers = allowedGroupCiphers; return NOERROR; } ECode CWifiConfiguration::GetEnterpriseConfig( /* [out] */ IWifiEnterpriseConfig** result) { VALIDATE_NOT_NULL(result); *result = mEnterpriseConfig; REFCOUNT_ADD(*result); return NOERROR; } ECode CWifiConfiguration::SetEnterpriseConfig( /* [in] */ IWifiEnterpriseConfig* enterpriseConfig) { mEnterpriseConfig = enterpriseConfig; return NOERROR; } ECode CWifiConfiguration::GetDhcpServer( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mDhcpServer; return NOERROR; } ECode CWifiConfiguration::SetDhcpServer( /* [in] */ const String& dhcpServer) { mDhcpServer = dhcpServer; return NOERROR; } ECode CWifiConfiguration::GetDefaultGwMacAddress( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mDefaultGwMacAddress; return NOERROR; } ECode CWifiConfiguration::SetDefaultGwMacAddress( /* [in] */ const String& defaultGwMacAddress) { mDefaultGwMacAddress = defaultGwMacAddress; return NOERROR; } ECode CWifiConfiguration::GetLastFailure( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mLastFailure; return NOERROR; } ECode CWifiConfiguration::SetLastFailure( /* [in] */ const String& lastFailure) { mLastFailure = lastFailure; return NOERROR; } ECode CWifiConfiguration::GetNoInternetAccess( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mNoInternetAccess; return NOERROR; } ECode CWifiConfiguration::SetNoInternetAccess( /* [in] */ Boolean noInternetAccess) { mNoInternetAccess = noInternetAccess; return NOERROR; } ECode CWifiConfiguration::GetCreatorUid( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mCreatorUid; return NOERROR; } ECode CWifiConfiguration::SetCreatorUid( /* [in] */ Int32 creatorUid) { mCreatorUid = creatorUid; return NOERROR; } ECode CWifiConfiguration::GetLastConnectUid( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mLastConnectUid; return NOERROR; } ECode CWifiConfiguration::SetLastConnectUid( /* [in] */ Int32 lastConnectUid) { mLastConnectUid = lastConnectUid; return NOERROR; } ECode CWifiConfiguration::GetLastUpdateUid( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mLastUpdateUid; return NOERROR; } ECode CWifiConfiguration::SetLastUpdateUid( /* [in] */ Int32 lastUpdateUid) { mLastUpdateUid = lastUpdateUid; return NOERROR; } ECode CWifiConfiguration::GetAutoJoinBSSID( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mAutoJoinBSSID; return NOERROR; } ECode CWifiConfiguration::SetAutoJoinBSSID( /* [in] */ const String& autoJoinBSSID) { mAutoJoinBSSID = autoJoinBSSID; return NOERROR; } ECode CWifiConfiguration::GetScanResultCache( /* [out] */ IHashMap** result) { VALIDATE_NOT_NULL(result); *result = mScanResultCache; REFCOUNT_ADD(*result); return NOERROR; } ECode CWifiConfiguration::SetScanResultCache( /* [in] */ IHashMap* scanResultCache) { mScanResultCache = scanResultCache; return NOERROR; } ECode CWifiConfiguration::GetVisibility( /* [out] */ IWifiConfigurationVisibility** result) { VALIDATE_NOT_NULL(result); *result = mVisibility; REFCOUNT_ADD(*result); return NOERROR; } ECode CWifiConfiguration::SetVisibility( /* [in] */ IWifiConfigurationVisibility* visibility) { mVisibility = visibility; return NOERROR; } ECode CWifiConfiguration::GetAutoJoinStatus( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mAutoJoinStatus; return NOERROR; } ECode CWifiConfiguration::GetNumConnectionFailures( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumConnectionFailures; return NOERROR; } ECode CWifiConfiguration::SetNumConnectionFailures( /* [in] */ Int32 numConnectionFailures) { mNumConnectionFailures = numConnectionFailures; return NOERROR; } ECode CWifiConfiguration::GetNumIpConfigFailures( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumIpConfigFailures; return NOERROR; } ECode CWifiConfiguration::SetNumIpConfigFailures( /* [in] */ Int32 numIpConfigFailures) { mNumIpConfigFailures = numIpConfigFailures; return NOERROR; } ECode CWifiConfiguration::GetNumAuthFailures( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumAuthFailures; return NOERROR; } ECode CWifiConfiguration::SetNumAuthFailures( /* [in] */ Int32 numAuthFailures) { mNumAuthFailures = numAuthFailures; return NOERROR; } ECode CWifiConfiguration::GetBlackListTimestamp( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result); *result = mBlackListTimestamp; return NOERROR; } ECode CWifiConfiguration::SetBlackListTimestamp( /* [in] */ Int64 blackListTimestamp) { mBlackListTimestamp = blackListTimestamp; return NOERROR; } ECode CWifiConfiguration::GetLastConnected( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result); *result = mLastConnected; return NOERROR; } ECode CWifiConfiguration::SetLastConnected( /* [in] */ Int64 lastConnected) { mLastConnected = lastConnected; return NOERROR; } ECode CWifiConfiguration::GetLastConnectionFailure( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result); *result = mLastConnectionFailure; return NOERROR; } ECode CWifiConfiguration::SetLastConnectionFailure( /* [in] */ Int64 lastConnectionFailure) { mLastConnectionFailure = lastConnectionFailure; return NOERROR; } ECode CWifiConfiguration::GetLastDisconnected( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result); *result = mLastDisconnected; return NOERROR; } ECode CWifiConfiguration::SetLastDisconnected( /* [in] */ Int64 lastDisconnected) { mLastDisconnected = lastDisconnected; return NOERROR; } ECode CWifiConfiguration::GetSelfAdded( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mSelfAdded; return NOERROR; } ECode CWifiConfiguration::SetSelfAdded( /* [in] */ Boolean selfAdded) { mSelfAdded = selfAdded; return NOERROR; } ECode CWifiConfiguration::GetDidSelfAdd( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mDidSelfAdd; return NOERROR; } ECode CWifiConfiguration::SetDidSelfAdd( /* [in] */ Boolean didSelfAdd) { mDidSelfAdd = didSelfAdd; return NOERROR; } ECode CWifiConfiguration::GetPeerWifiConfiguration( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); *result = mPeerWifiConfiguration; return NOERROR; } ECode CWifiConfiguration::SetPeerWifiConfiguration( /* [in] */ const String& peerWifiConfiguration) { mPeerWifiConfiguration = peerWifiConfiguration; return NOERROR; } ECode CWifiConfiguration::GetEphemeral( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mEphemeral; return NOERROR; } ECode CWifiConfiguration::SetEphemeral( /* [in] */ Boolean ephemeral) { mEphemeral = ephemeral; return NOERROR; } ECode CWifiConfiguration::GetAutoJoinBailedDueToLowRssi( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mAutoJoinBailedDueToLowRssi; return NOERROR; } ECode CWifiConfiguration::SetAutoJoinBailedDueToLowRssi( /* [in] */ Boolean autoJoinBailedDueToLowRssi) { mAutoJoinBailedDueToLowRssi = autoJoinBailedDueToLowRssi; return NOERROR; } ECode CWifiConfiguration::GetAutoJoinUseAggressiveJoinAttemptThreshold( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mAutoJoinUseAggressiveJoinAttemptThreshold; return NOERROR; } ECode CWifiConfiguration::SetAutoJoinUseAggressiveJoinAttemptThreshold( /* [in] */ Int32 autoJoinUseAggressiveJoinAttemptThreshold) { mAutoJoinUseAggressiveJoinAttemptThreshold = autoJoinUseAggressiveJoinAttemptThreshold; return NOERROR; } ECode CWifiConfiguration::GetNumScorerOverride( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumScorerOverride; return NOERROR; } ECode CWifiConfiguration::SetNumScorerOverride( /* [in] */ Int32 numScorerOverride) { mNumScorerOverride = numScorerOverride; return NOERROR; } ECode CWifiConfiguration::GetNumScorerOverrideAndSwitchedNetwork( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumScorerOverrideAndSwitchedNetwork; return NOERROR; } ECode CWifiConfiguration::SetNumScorerOverrideAndSwitchedNetwork( /* [in] */ Int32 numScorerOverrideAndSwitchedNetwork) { mNumScorerOverrideAndSwitchedNetwork = numScorerOverrideAndSwitchedNetwork; return NOERROR; } ECode CWifiConfiguration::GetNumAssociation( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumAssociation; return NOERROR; } ECode CWifiConfiguration::SetNumAssociation( /* [in] */ Int32 numAssociation) { mNumAssociation = numAssociation; return NOERROR; } ECode CWifiConfiguration::GetNumUserTriggeredWifiDisableLowRSSI( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumUserTriggeredWifiDisableLowRSSI; return NOERROR; } ECode CWifiConfiguration::SetNumUserTriggeredWifiDisableLowRSSI( /* [in] */ Int32 numUserTriggeredWifiDisableLowRSSI) { mNumUserTriggeredWifiDisableLowRSSI = numUserTriggeredWifiDisableLowRSSI; return NOERROR; } ECode CWifiConfiguration::GetNumUserTriggeredWifiDisableBadRSSI( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumUserTriggeredWifiDisableBadRSSI; return NOERROR; } ECode CWifiConfiguration::SetNumUserTriggeredWifiDisableBadRSSI( /* [in] */ Int32 numUserTriggeredWifiDisableBadRSSI) { mNumUserTriggeredWifiDisableBadRSSI = numUserTriggeredWifiDisableBadRSSI; return NOERROR; } ECode CWifiConfiguration::GetNumUserTriggeredWifiDisableNotHighRSSI( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumUserTriggeredWifiDisableNotHighRSSI; return NOERROR; } ECode CWifiConfiguration::SetNumUserTriggeredWifiDisableNotHighRSSI( /* [in] */ Int32 numUserTriggeredWifiDisableNotHighRSSI) { mNumUserTriggeredWifiDisableNotHighRSSI = numUserTriggeredWifiDisableNotHighRSSI; return NOERROR; } ECode CWifiConfiguration::GetNumTicksAtLowRSSI( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumTicksAtLowRSSI; return NOERROR; } ECode CWifiConfiguration::SetNumTicksAtLowRSSI( /* [in] */ Int32 numTicksAtLowRSSI) { mNumTicksAtLowRSSI = numTicksAtLowRSSI; return NOERROR; } ECode CWifiConfiguration::GetNumTicksAtBadRSSI( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumTicksAtBadRSSI; return NOERROR; } ECode CWifiConfiguration::SetNumTicksAtBadRSSI( /* [in] */ Int32 numTicksAtBadRSSI) { mNumTicksAtBadRSSI = numTicksAtBadRSSI; return NOERROR; } ECode CWifiConfiguration::GetNumTicksAtNotHighRSSI( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumTicksAtNotHighRSSI; return NOERROR; } ECode CWifiConfiguration::SetNumTicksAtNotHighRSSI( /* [in] */ Int32 numTicksAtNotHighRSSI) { mNumTicksAtNotHighRSSI = numTicksAtNotHighRSSI; return NOERROR; } ECode CWifiConfiguration::GetNumUserTriggeredJoinAttempts( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = mNumUserTriggeredJoinAttempts; return NOERROR; } ECode CWifiConfiguration::SetNumUserTriggeredJoinAttempts( /* [in] */ Int32 numUserTriggeredJoinAttempts) { mNumUserTriggeredJoinAttempts = numUserTriggeredJoinAttempts; return NOERROR; } ECode CWifiConfiguration::GetConnectChoices( /* [out] */ IHashMap** result) { VALIDATE_NOT_NULL(result); *result = mConnectChoices; REFCOUNT_ADD(*result); return NOERROR; } ECode CWifiConfiguration::SetConnectChoices( /* [in] */ IHashMap* connectChoices) { mConnectChoices = connectChoices; return NOERROR; } ECode CWifiConfiguration::GetLinkedConfigurations( /* [out] */ IHashMap** result) { VALIDATE_NOT_NULL(result); *result = mLinkedConfigurations; REFCOUNT_ADD(*result); return NOERROR; } ECode CWifiConfiguration::SetLinkedConfigurations( /* [in] */ IHashMap* linkedConfigurations) { mLinkedConfigurations = linkedConfigurations; return NOERROR; } ECode CWifiConfiguration::GetDuplicateNetwork( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = mDuplicateNetwork; return NOERROR; } ECode CWifiConfiguration::SetDuplicateNetwork( /* [in] */ Boolean duplicateNetwork) { mDuplicateNetwork = duplicateNetwork; return NOERROR; } ECode CWifiConfiguration::GetWepKeyVarNames( /* [out, callee] */ ArrayOf<String>** result) { VALIDATE_NOT_NULL(result); AutoPtr<ArrayOf<String> > array = ArrayOf<String>::Alloc(4); //"wep_key0", "wep_key1", "wep_key2", "wep_key3" array->Set(0, String("wep_key0")); array->Set(1, String("wep_key1")); array->Set(2, String("wep_key2")); array->Set(3, String("wep_key3")); *result = array; REFCOUNT_ADD(*result); return NOERROR; } ECode CWifiConfiguration::SetVisibility( /* [in] */ Int64 age, /* [out] */ IWifiConfigurationVisibility** resultOut) { VALIDATE_NOT_NULL(resultOut); if (mScanResultCache == NULL) { mVisibility = NULL; *resultOut = NULL; return NOERROR; } AutoPtr<IWifiConfigurationVisibility> status; CWifiConfigurationVisibility::New((IWifiConfigurationVisibility**)&status); AutoPtr<ISystem> system; CSystem::AcquireSingleton((ISystem**)&system); Int64 now_ms; system->GetCurrentTimeMillis(&now_ms); AutoPtr<ICollection> values; mScanResultCache->GetValues((ICollection**)&values); AutoPtr<IIterator> iter; values->GetIterator((IIterator**)&iter); Boolean bNext; iter->HasNext(&bNext); for (; bNext; iter->HasNext(&bNext)) { AutoPtr<IInterface> obj; iter->GetNext((IInterface**)&obj); IScanResult* result = IScanResult::Probe(obj); Int64 seen; result->GetSeen(&seen); if (seen == 0) continue; Boolean bIs5GHz, bIs24GHz; result->Is5GHz(&bIs5GHz); if (bIs5GHz) { //strictly speaking: [4915, 5825] //number of known BSSID on 5GHz band Int32 num5; status->GetNum5(&num5); status->SetNum5(num5 + 1); } else if (result->Is24GHz(&bIs24GHz), bIs24GHz) { //strictly speaking: [2412, 2482] //number of known BSSID on 2.4Ghz band Int32 num24; status->GetNum24(&num24); status->SetNum24(num24 + 1); } if ((now_ms - seen) > age) continue; if (bIs5GHz) { Int32 level, rssi5; result->GetLevel(&level); status->GetRssi5(&rssi5); if (level > rssi5) { status->SetRssi5(level); status->SetAge5(seen); String BSSID; result->GetBSSID(&BSSID); status->SetBSSID5(BSSID); } } else if (result->Is24GHz(&bIs24GHz), bIs24GHz) { Int32 level, rssi24; result->GetLevel(&level); status->GetRssi24(&rssi24); if (level > rssi24) { status->SetRssi24(level); status->SetAge24(seen); String BSSID; result->GetBSSID(&BSSID); status->SetBSSID24(BSSID); } } } mVisibility = status; *resultOut = status; REFCOUNT_ADD(*resultOut) return NOERROR; } ECode CWifiConfiguration::IsValid( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); if (mAllowedKeyManagement == NULL) { *result = FALSE; } Int32 cardinality; mAllowedKeyManagement->Cardinality(&cardinality); if (cardinality > 1) { if (cardinality != 2) { *result = FALSE; return NOERROR; } Boolean bFlag1; mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::WPA_EAP, &bFlag1); if (bFlag1 == FALSE) { return false; } Boolean bFlag2, bFlag3; mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::IEEE8021X, &bFlag2); if (bFlag1 == FALSE && (mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::WPA_PSK, &bFlag3), bFlag3 == FALSE)) { *result = FALSE; } } // TODO: Add more checks *result = TRUE; return NOERROR; } ECode CWifiConfiguration::IsLinked( /* [in] */ IWifiConfiguration* config, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; AutoPtr<IHashMap> linkedConfigurations; config->GetLinkedConfigurations((IHashMap**)&linkedConfigurations); if (linkedConfigurations != NULL && mLinkedConfigurations != NULL) { String key; ConfigKey(&key); AutoPtr<ICharSequence> keyObj; CString::New(key, (ICharSequence**)&keyObj); AutoPtr<IInterface> value; linkedConfigurations->Get(keyObj, (IInterface**)&value); if (value != NULL) { config->ConfigKey(&key); keyObj = NULL; value = NULL; CString::New(key, (ICharSequence**)&keyObj); mLinkedConfigurations->Get(keyObj, (IInterface**)&value); if (value != NULL) { *result = TRUE; } } } return NOERROR; } ECode CWifiConfiguration::LastSeen( /* [out] */ IScanResult** resultOut) { VALIDATE_NOT_NULL(resultOut); AutoPtr<IScanResult> mostRecent; if (mScanResultCache == NULL) { *resultOut = NULL; return NOERROR; } AutoPtr<ICollection> values; mScanResultCache->GetValues((ICollection**)&values); AutoPtr<IIterator> iter; values->GetIterator((IIterator**)&iter); Boolean bNext; iter->HasNext(&bNext); for (; bNext; iter->HasNext(&bNext)) { AutoPtr<IInterface> obj; iter->GetNext((IInterface**)&obj); IScanResult* result = IScanResult::Probe(obj); if (mostRecent == NULL) { Int64 seen; result->GetSeen(&seen); if (seen != 0) mostRecent = result; } else { Int64 resultSeen, mostRecentSeen; result->GetSeen(&resultSeen); mostRecent->GetSeen(&mostRecentSeen); if (resultSeen > mostRecentSeen) { mostRecent = result; } } } *resultOut = mostRecent; REFCOUNT_ADD(*resultOut) return NOERROR; } ECode CWifiConfiguration::SetAutoJoinStatus( /* [in] */ Int32 status) { if (status < 0) status = 0; if (status == 0) { mBlackListTimestamp = 0; } else if (status > mAutoJoinStatus) { AutoPtr<ISystem> system; CSystem::AcquireSingleton((ISystem**)&system); system->GetCurrentTimeMillis(&mBlackListTimestamp); } if (status != mAutoJoinStatus) { mAutoJoinStatus = status; mDirty = TRUE; } return NOERROR; } ECode CWifiConfiguration::GetKeyIdForCredentials( /* [in] */ IWifiConfiguration* current, /* [out] */ String* result) { String keyMgmt; // try { // Get current config details for fields that are not initialized if (TextUtils::IsEmpty(mSSID)) { current->GetSSID(&mSSID); } Int32 cardinality; mAllowedKeyManagement->Cardinality(&cardinality); if (cardinality == 0) { current->GetAllowedKeyManagement((IBitSet**)&mAllowedKeyManagement); } Boolean bFlag; mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::WPA_EAP, &bFlag); if (bFlag) { AutoPtr<IWifiConfigurationKeyMgmt> iKeyMgmt; CWifiConfigurationKeyMgmt::AcquireSingleton((IWifiConfigurationKeyMgmt**)&keyMgmt); AutoPtr< ArrayOf<String> > strings; iKeyMgmt->GetStrings((ArrayOf<String>**)&strings); keyMgmt = (*strings)[IWifiConfigurationKeyMgmt::WPA_EAP]; } mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::IEEE8021X, &bFlag); if (bFlag) { AutoPtr<IWifiConfigurationKeyMgmt> iKeyMgmt; CWifiConfigurationKeyMgmt::AcquireSingleton((IWifiConfigurationKeyMgmt**)&keyMgmt); AutoPtr< ArrayOf<String> > strings; iKeyMgmt->GetStrings((ArrayOf<String>**)&strings); keyMgmt += (*strings)[IWifiConfigurationKeyMgmt::IEEE8021X]; } if (TextUtils::IsEmpty(keyMgmt)) { //throw new IllegalStateException("Not an EAP network"); return E_ILLEGAL_STATE_EXCEPTION; } AutoPtr<IWifiEnterpriseConfig> enterpriseConfig; if (current != NULL) { current->GetEnterpriseConfig((IWifiEnterpriseConfig**)&enterpriseConfig); } String keyId; ((CWifiEnterpriseConfig*)mEnterpriseConfig.Get())->GetKeyId(enterpriseConfig, &keyId); *result = TrimStringForKeyId(mSSID); *result += "_"; *result += keyMgmt; *result += "_"; *result += TrimStringForKeyId(keyId); return NOERROR; // } catch (NullPointerException e) { // throw new IllegalStateException("Invalid config details"); // } } ECode CWifiConfiguration::ConfigKey( /* [in] */ Boolean allowCached, /* [out] */ String* result) { VALIDATE_NOT_NULL(result); String key; if (allowCached && mCachedConfigKey != NULL) { key = mCachedConfigKey; } else { AutoPtr<IWifiConfigurationKeyMgmt> keyMgmt; CWifiConfigurationKeyMgmt::AcquireSingleton((IWifiConfigurationKeyMgmt**)&keyMgmt); AutoPtr< ArrayOf<String> > strings; keyMgmt->GetStrings((ArrayOf<String>**)&strings); Boolean bFlag1, bFlag2, bFlag3; mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::WPA_PSK, &bFlag1); if (bFlag1) { key = mSSID; key += (*strings)[IWifiConfigurationKeyMgmt::WPA_PSK]; } else if ((mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::WPA_EAP, &bFlag2), bFlag2) || (mAllowedKeyManagement->Get(IWifiConfigurationKeyMgmt::IEEE8021X, &bFlag3), bFlag3)) { key = mSSID; key += (*strings)[IWifiConfigurationKeyMgmt::WPA_EAP]; } else if ((*mWepKeys)[0] != NULL) { key = mSSID; key += "WEP"; } else { key = mSSID; key += (*strings)[IWifiConfigurationKeyMgmt::NONE]; } mCachedConfigKey = key; } *result = key; return NOERROR; } ECode CWifiConfiguration::ConfigKey( /* [out] */ String* result) { return ConfigKey(FALSE, result); } ECode CWifiConfiguration::GetIpConfiguration( /* [out] */ IIpConfiguration** result) { VALIDATE_NOT_NULL(result); *result = mIpConfiguration; REFCOUNT_ADD(*result); return NOERROR; } ECode CWifiConfiguration::SetIpConfiguration( /* [in] */ IIpConfiguration* ipConfiguration) { mIpConfiguration = ipConfiguration; return NOERROR; } ECode CWifiConfiguration::GetStaticIpConfiguration( /* [out] */ IStaticIpConfiguration** result) { return mIpConfiguration->GetStaticIpConfiguration(result); } ECode CWifiConfiguration::SetStaticIpConfiguration( /* [in] */ IStaticIpConfiguration* staticIpConfiguration) { return mIpConfiguration->SetStaticIpConfiguration(staticIpConfiguration); } ECode CWifiConfiguration::GetHttpProxy( /* [out] */ IProxyInfo** result) { return mIpConfiguration->GetHttpProxy(result); } ECode CWifiConfiguration::SetHttpProxy( /* [in] */ IProxyInfo* httpProxy) { mIpConfiguration->SetHttpProxy(httpProxy); return NOERROR; } ECode CWifiConfiguration::SetProxy( /* [in] */ IpConfigurationProxySettings settings, /* [in] */ IProxyInfo* proxy) { mIpConfiguration->SetProxySettings(settings); mIpConfiguration->SetHttpProxy(proxy); return NOERROR; } ECode CWifiConfiguration::GetIpAssignment( /* [out] */ IpConfigurationIpAssignment* ipAssignment) { return mIpConfiguration->GetIpAssignment(ipAssignment); } ECode CWifiConfiguration::SetIpAssignment( /* [in] */ IpConfigurationIpAssignment ipAssignment) { return mIpConfiguration->SetIpAssignment(ipAssignment); } ECode CWifiConfiguration::GetProxySettings( /* [out] */ IpConfigurationProxySettings* proxySettings) { return mIpConfiguration->GetProxySettings(proxySettings); } ECode CWifiConfiguration::SetProxySettings( /* [in] */ IpConfigurationProxySettings proxySettings) { return mIpConfiguration->SetProxySettings(proxySettings); } } // namespace Wifi } // namespace Droid } // namespace Elastos
28.683669
112
0.649263
jingcao80
1cfb31356e49096d53dc216d70e33f3b0575fd5f
3,168
cpp
C++
test/test_harmonic1d.cpp
grasingerm/port-authority
51db6b09d6a1545eafeaf6be037a23d47313c490
[ "MIT" ]
null
null
null
test/test_harmonic1d.cpp
grasingerm/port-authority
51db6b09d6a1545eafeaf6be037a23d47313c490
[ "MIT" ]
null
null
null
test/test_harmonic1d.cpp
grasingerm/port-authority
51db6b09d6a1545eafeaf6be037a23d47313c490
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <cstdlib> #include <ctime> #include <random> #include "port_authority.hpp" #include "mpi.h" using namespace std; using namespace pauth; int main() { int taskid, numtasks; MPI_Init(nullptr, nullptr); MPI_Comm_size(MPI_COMM_WORLD, &numtasks); MPI_Comm_rank(MPI_COMM_WORLD, &taskid); srand(time(NULL)); const auto delta_max = static_cast<double>( (rand() % 200 + 50) / 100.0 ); const auto spring_const = static_cast<double>( (rand() % 1990 + 10) / 500.0 ); const auto T = static_cast<double>( (rand() % 200000 + 10) / 1000.0 ); const auto x0 = static_cast<double>( (rand() % 100 - 200) / 50.0 ); const unsigned nsteps = 20000000; if (taskid == 0) { cout << "1D Harmonic test started.\n"; cout << '\n'; cout << "delta_max = " << delta_max << '\n'; cout << "k = " << spring_const << '\n'; cout << "T = " << T << '\n'; cout << "x0 = " << x0 << '\n'; cout << '\n'; } const double dx = 0.1; const double kB = 1.0; const molecular_id id = molecular_id::Test1; const size_t N = 1; const size_t D = 1; const double L = 1.0; const metric m = euclidean; const bc boundary = no_bc; const_k_spring_potential pot(spring_const); metropolis sim(id, N, D, L, continuous_trial_move(delta_max), &pot, T, kB, m, boundary, metropolis_acc, hardware_entropy_seed_gen, true); sim.set_positions({x0}, 0); const double u0 = accessors::U(sim); metropolis_suite msuite(sim, 0, 1, info_lvl_flag::QUIET); msuite.add_variable_to_average("x", [](const metropolis &sim) { return sim.positions()(0, 0); }); msuite.add_variable_to_average("x^2", [](const metropolis &sim) { return sim.positions()(0, 0) * sim.positions()(0, 0); }); msuite.add_variable_to_average("U", accessors::U); msuite.add_variable_to_average("delta(x - x0)", [=](const metropolis &sim) { const double x = sim.positions()(0, 0); return (x < x0 + dx && x > x0 - dx) ? 1 : 0; }); msuite.simulate(nsteps); if(taskid == 0) { auto averages = msuite.averages(); const double exp_x = averages["x"]; const double exp_xsq = averages["x^2"]; const double exp_E = averages["U"]; const auto exp_xsq_an = (kB * T / spring_const); const auto exp_E_an = kB * T / 2.0; const auto Z_an = sqrt(2.0 * M_PI * kB * T / spring_const); cout << "exp_x = " << exp_x << '\n'; assert(abs(exp_x) < 5e-2); cout << "exp_xsq = " << exp_xsq << " ?= " << exp_xsq_an << '\n'; assert(abs((exp_xsq - exp_xsq_an) / exp_xsq_an) < 1e-2); cout << "exp_E = " << exp_E << " ?= " << exp_E_an << '\n'; assert(abs((exp_E - exp_E_an) / exp_E_an) < 1e-2); cout << "Z = " << (2.0 * dx * exp(-u0 / (kB * T)) / averages["delta(x - x0)"]) << " ?= " << Z_an << '\n'; assert(abs( ((2.0 * dx * exp(-u0 / (kB * T)) / averages["delta(x - x0)"]) - Z_an) / Z_an ) < 1e-2); cout << "---------------------------------------------\n"; } if(taskid == 0) cout << "1D Harmonic test passed.\n"; MPI_Finalize(); return 0; }
31.68
80
0.561553
grasingerm
e800177f3cac938807b707a1d0acbeec633aebe8
724
cpp
C++
code_snippets/chapter03/chapter03_02-001_fixed_size_integer.cpp
nandasanchit17/real-time-cpp
fae1aece8b4fe2aaae18c8bd81a99661b0609a23
[ "BSL-1.0" ]
1
2020-03-19T08:10:23.000Z
2020-03-19T08:10:23.000Z
code_snippets/chapter03/chapter03_02-001_fixed_size_integer.cpp
nandasanchit17/real-time-cpp
fae1aece8b4fe2aaae18c8bd81a99661b0609a23
[ "BSL-1.0" ]
null
null
null
code_snippets/chapter03/chapter03_02-001_fixed_size_integer.cpp
nandasanchit17/real-time-cpp
fae1aece8b4fe2aaae18c8bd81a99661b0609a23
[ "BSL-1.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Copyright Christopher Kormanyos 2017 - 2018. // 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) // // chapter03_02-001_fixed_size_integer.cpp #include <cstdint> #include <iomanip> #include <iostream> // This has *exactly* 16-bits signed. constexpr std::int16_t value16 = INT16_C(0x7FFF); // This has *at least* 32-bits unsigned. constexpr std::uint_least32_t value32 = UINT32_C(4'294'967'295); int main() { std::cout << std::hex << std::showbase << value16 << std::endl; std::cout << std::dec << value32 << std::endl; }
26.814815
79
0.622928
nandasanchit17
e80028ad367f2469b3c6449533f19dc84eb2b828
1,591
cpp
C++
test_package/example.cpp
memsharded/conan-eastl
1c0de6b7f650036224fe4f51e5001f59aa609de0
[ "MIT" ]
null
null
null
test_package/example.cpp
memsharded/conan-eastl
1c0de6b7f650036224fe4f51e5001f59aa609de0
[ "MIT" ]
null
null
null
test_package/example.cpp
memsharded/conan-eastl
1c0de6b7f650036224fe4f51e5001f59aa609de0
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include <EASTL/hash_map.h> #include <EASTL/string.h> // EASTL expects us to define these, see allocator.h line 194 void* operator new[](size_t size, const char* /* pName */, int /* flags */, unsigned /* debugFlags */, const char* /* file */, int /* line */) { return malloc(size); } void* operator new[](size_t size, size_t alignment, size_t /* alignmentOffset */, const char* /* pName */, int /* flags */, unsigned /* debugFlags */, const char* /* file */, int /* line */) { // this allocator doesn't support alignment EASTL_ASSERT(alignment <= 8); return malloc(size); } // EASTL also wants us to define this (see string.h line 197) int Vsnprintf8(char8_t* pDestination, size_t n, const char8_t* pFormat, va_list arguments) { #ifdef _MSC_VER return _vsnprintf(pDestination, n, pFormat, arguments); #else return vsnprintf(pDestination, n, pFormat, arguments); #endif } void test_hash_map() { eastl::hash_map<eastl::string, eastl::string> map; map["key1"] = "value1"; map["key2"] = "value2"; EASTL_ASSERT(map.find("key1")->second == "value1"); } void test_string() { eastl::string str; str += "testing "; str += "simple "; str += "string "; str += "concat"; EASTL_ASSERT(str == "testing simple string concat"); str.sprintf("%d", 20); EASTL_ASSERT(str == "20"); } int main() { test_hash_map(); test_string(); return EXIT_SUCCESS; }
27.912281
75
0.59208
memsharded
e802fbd2c9ca1e00f17cf66c860bdb14a403a0e8
1,878
cpp
C++
Camera.cpp
CJT-Jackton/The-Color-of-Tea
d7c79279613bdc04237e8692bcc2cb6918172900
[ "BSD-2-Clause" ]
1
2020-09-15T06:32:08.000Z
2020-09-15T06:32:08.000Z
Camera.cpp
CJT-Jackton/The-Color-of-Tea
d7c79279613bdc04237e8692bcc2cb6918172900
[ "BSD-2-Clause" ]
null
null
null
Camera.cpp
CJT-Jackton/The-Color-of-Tea
d7c79279613bdc04237e8692bcc2cb6918172900
[ "BSD-2-Clause" ]
null
null
null
// // Camera.cpp // // Camera class implementations. // // Author: Jietong Chen // Date: 5/2/2018 // #include <glm/gtc/matrix_transform.hpp> #include "Camera.h" /// // Constructor // // @param position - camera location // @param lookat - lookat point location // @param fov - field of view // @param aspect - aspect ratio // @param near - near clipping plate // @param far - far clipping plate /// Camera::Camera( vec3 position, vec3 lookat, float fov, float aspect, float near, float far ) : position( position ), lookat( lookat ), fov( fov ), aspect( aspect ), znear( near ), zfar( far ) { // default up vector up = vec3( 0.0f, 1.0f, 0.0f ); } /// // Get the viewing transformation matrix of the camera. // // @return the viewing transformation matrix /// mat4 Camera::getViewMat() { // n-axis of camera coordinate vec3 n = normalize( position - lookat ); // u-axis of camera coordinate vec3 u = normalize( cross( up, n ) ); // v-axis of camera coordinate vec3 v = normalize( cross( n, u ) ); return mat4( u.x, v.x, n.x, 0.0f, u.y, v.y, n.y, 0.0f, u.z, v.z, n.z, 0.0f, -dot( u, position ), -dot( v, position ), -dot( n, position ), 1.0f ); } /// // Get the projection matrix of the camera. // // @return the projection matrix /// mat4 Camera::getProjectionMat() { mat4 Projection = mat4( 0.0f ); float tanHalfFov = tan( fov * float( M_PI ) / 360.0f ); Projection[ 0 ][ 0 ] = 1.0f / ( aspect * tanHalfFov ); Projection[ 1 ][ 1 ] = 1.0f / ( tanHalfFov ); Projection[ 2 ][ 3 ] = -1.0f; Projection[ 2 ][ 2 ] = -( zfar + znear ) / ( zfar - znear ); Projection[ 3 ][ 2 ] = -( 2.0f * zfar * znear ) / ( zfar - znear ); return Projection; }
27.217391
80
0.551118
CJT-Jackton
e8046a51eb12bfe61e487c86917358894bf37cc1
31,943
cpp
C++
src/Filesystem/Filesystem.cpp
NerdThings/Ngine
e5c4754d07ec38e727d8baaf7250dbb996cad49e
[ "Apache-2.0" ]
2
2019-05-24T15:20:14.000Z
2019-06-12T11:55:27.000Z
src/Filesystem/Filesystem.cpp
NerdThings/Ngine
e5c4754d07ec38e727d8baaf7250dbb996cad49e
[ "Apache-2.0" ]
23
2019-06-05T12:52:33.000Z
2020-03-11T15:23:00.000Z
src/Filesystem/Filesystem.cpp
NerdThings/Ngine
e5c4754d07ec38e727d8baaf7250dbb996cad49e
[ "Apache-2.0" ]
1
2019-10-02T20:31:12.000Z
2019-10-02T20:31:12.000Z
/********************************************************************************************** * * Ngine - The 2D game engine. * * Copyright (C) 2019 NerdThings * * LICENSE: Apache License 2.0 * View: https://github.com/NerdThings/Ngine/blob/master/LICENSE * **********************************************************************************************/ #include "Filesystem.h" #if defined(_WIN32) #include <Windows.h> #include <shlobj.h> #elif defined(__linux__) #define _GNU_SOURCE #define __USE_GNU #include <unistd.h> #include <limits.h> #include <pwd.h> #include <linux/limits.h> #include <dlfcn.h> #elif defined(__APPLE__) #include <mach-o/dyld.h> #include <dlfcn.h> #include <sys/syslimits.h> #include <unistd.h> #include <pwd.h> #endif #if defined(__linux__) || defined(__APPLE__) #include <unistd.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #endif #include <sstream> namespace NerdThings::Ngine::Filesystem { //////// // Path //////// // Public Constructors Path::Path() { // Mark as improper _HasProperValue = false; } Path::Path(const std::string &pathString_) { // Set internal path _InternalPath = pathString_; // Check path __CorrectPath(); } Path::Path(const std::string &path_, const std::string &pathB_) { // Set internal path _InternalPath = path_ + __GetJoinChar() + pathB_; // Check path __CorrectPath(); } Path::Path(const Path& path_, const Path& pathB_) { // Set internal path _InternalPath = path_._InternalPath + __GetJoinChar() + pathB_._InternalPath; // Check path __CorrectPath(); } Path::Path(const Path &path_, const std::string &pathB_) { // Set internal path _InternalPath = path_._InternalPath + __GetJoinChar() + pathB_; // Check path __CorrectPath(); } Path::Path(const std::string &path_, const Path &pathB_) { // Set internal path _InternalPath = path_ + __GetJoinChar() + pathB_._InternalPath; // Check path __CorrectPath(); } // Public Methods Path Path::GetAbsolute() const { // If we are already absolute, ignore if (IsAbsolute()) return *this; // Get relative to executable dir return GetExecutableDirectory() / *this; } Path Path::GetAppDataDirectory() { #if defined(PLATFORM_DESKTOP) #if defined(_WIN32) // %APPDATA% return std::string(getenv("APPDATA")); #elif defined(__linux__) // Home local share return __GetHome() + ".local/share"; #elif defined(__APPLE__) // Application Support return __GetHome() + "/Library/Application Support" #endif #elif defined(PLATFORM_UWP) // Windows specific path auto roamingAppData = Windows::Storage::ApplicationData::Current->RoamingFolder->Path->ToString(); std::wstring tmp(roamingAppData->Begin()); std::string path(tmp.begin(), tmp.end()); return path; #endif } Path Path::GetExecutableDirectory() { #if defined(PLATFORM_UWP) auto installed = Windows::ApplicationModel::Package::Current->InstalledLocation->Path; std::wstring tmp(installed->Begin()); std::string installedPath(tmp.begin(), tmp.end()); return installedPath; #else return GetExecutablePath().GetParent(); #endif } Path Path::GetExecutablePath() { // https://github.com/cginternals/cpplocate/blob/master/source/liblocate/source/liblocate.c#L39 // I trust this works as there are no issues about it... #if defined(_WIN32) && defined(PLATFORM_DESKTOP) char exePath[MAX_PATH]; unsigned int len = GetModuleFileNameA(GetModuleHandleA(nullptr), exePath, MAX_PATH); if (len == 0) return Path(""); return Path(std::string(exePath)); #elif defined(_WIN32) && defined(PLATFORM_UWP) throw std::runtime_error("Cannot get executable path of UWP app, get executable directory instead."); #elif defined(__linux__) char exePath[PATH_MAX]; int len = readlink("/proc/self/exe", exePath, PATH_MAX); if (len <= 0 || len == PATH_MAX) return Path(""); return Path(std::string(exePath)); #elif defined(__APPLE__) char exePath[PATH_MAX]; unsigned int len = (unsigned int)PATH_MAX; if (_NSGetExecutablePath(exePath, &len) == 0) { char * realPath = realpath(exePath, 0x0); if (realPath == 0x0) { return Path(""); } auto pathStr = std::string(realPath); free(realPath); return Path(pathStr); } else { char * intermediatePath = (char *)malloc(sizeof(char) * len); if (_NSGetExecutablePath(intermediatePath, &len) != 0) { free(intermediatePath); return Path(""); } char * realPath = realpath(intermediatePath, 0x0); free(intermediatePath); if (realPath == 0x0) { return Path(""); } auto pathStr = std::string(realPath); free(realPath); return Path(pathStr); } #else // Returns blank, this cannot be used return Path(""); #endif } std::string Path::GetFileExtension() const { // Get path string auto path = GetString(); // Get file extension auto dot = path.find_last_of('.'); auto lastSlash = path.find_last_of(__GetJoinChar()); if (std::string::npos != dot) { if (dot > lastSlash) { return path.substr(dot + 1); } } return ""; } std::string Path::GetObjectName() const { // Get path string auto nameTemp = GetString(); // Search for the last directory slash auto fSlash = nameTemp.find_last_of(__GetJoinChar()); if (std::string::npos != fSlash) { nameTemp.erase(0, fSlash + 1); } // Remove the file extension auto dot = nameTemp.find_last_of('.'); if (std::string::npos != dot) { nameTemp.erase(dot); } return nameTemp; } Path Path::GetParent() const { auto lastSlash = _InternalPath.find_last_of(__GetJoinChar()); if (std::string::npos != lastSlash) return Path(_InternalPath.substr(0, lastSlash)); else return Path(); } Path Path::GetRelativeTo(const Path &base_) const { // The base must be absolute auto basePath = base_; if (!basePath.IsAbsolute()) basePath = basePath.GetAbsolute(); // Base must be a directory if (basePath.GetResourceType() != TYPE_DIRECTORY) throw std::runtime_error("Base must be a directory."); // I must be absolute if (!IsAbsolute()) throw std::runtime_error("Path must be absolute."); // Find common path auto commonPathPos = 0; auto baseStr = basePath.GetString(); auto str = GetString(); for (auto i = 0; i < baseStr.size() && i < str.size(); i++) { if (baseStr[i] != str[i]) { break; } commonPathPos++; } // Catches things like different drives if (commonPathPos == 0) { throw std::runtime_error("Cannot get relative path to files on different drives."); } // Remove from both strings baseStr.erase(0, commonPathPos); str.erase(0, commonPathPos); // Remove initial slash if left if (str.size() > 0) { if (str[0] == __GetJoinChar()) { str.erase(0, 1); } } // Prepend ../ for all extra parts int subdirs = (int)std::count(baseStr.begin(), baseStr.end(), __GetJoinChar()); // Add one more if it doesn't end in a slash if (baseStr.size() > 0) { if (baseStr[baseStr.size() - 1] != __GetJoinChar()) { subdirs += 1; } } for (auto i = 0; i < subdirs; i++) { str = std::string("..") + __GetJoinChar() + str; } // Return, we're done return str; } ResourceType Path::GetResourceType() const { #if defined(_WIN32) DWORD dwAttrib = GetFileAttributesA(GetString().c_str()); if (dwAttrib != INVALID_FILE_ATTRIBUTES) { return dwAttrib & FILE_ATTRIBUTE_DIRECTORY ? TYPE_DIRECTORY : TYPE_FILE; } #elif defined(__linux__) || defined(__APPLE__) // Get path info struct stat path_stat; stat(GetString().c_str(), &path_stat); if (S_ISREG(path_stat.st_mode)) return TYPE_FILE; else if (S_ISDIR(path_stat.st_mode)) return TYPE_DIRECTORY; #endif return TYPE_INVALID; } std::string Path::GetString() const { return _InternalPath; } std::string Path::GetStringNoExtension() const { auto lastDot = _InternalPath.find_last_of('.'); auto lastSlash = _InternalPath.find_last_of(__GetJoinChar()); if (std::string::npos != lastDot) { if (std::string::npos != lastSlash) { if (lastDot > lastSlash) { return _InternalPath.substr(0, lastDot); } } else { return _InternalPath.substr(0, lastDot); } } return _InternalPath; } Path Path::GetWorkingDirectory() { #if defined(_WIN32) // Create buffer DWORD bufferLen = MAX_PATH; auto buffer = new char[MAX_PATH + 1]; // Get current dir GetCurrentDirectoryA(MAX_PATH + 1, buffer); // Null terminate buffer[MAX_PATH] = 0; // Convert to string std::string string(buffer); // Delete buffer delete[] buffer; // Return return Path(string); #elif defined(__linux) || defined(__APPLE__) // Create buffer auto buffer = new char[PATH_MAX]; // Get working dir if (getcwd(buffer, PATH_MAX) == nullptr) throw std::runtime_error("Unable to determine working directory."); // Convert to string std::string string(buffer); // Delete buffer delete[] buffer; // Return return Path(string); #endif } bool Path::IsAbsolute() const { #if defined(_WIN32) // Test if we have (*):\ at the start if (_InternalPath.size() > 3) return _InternalPath[1] == ':' && _InternalPath[2] == '\\'; #elif defined(__linux__) || defined(__APPLE__) // Test we have an initial slash if (_InternalPath.size() > 0) return _InternalPath[0] == '/'; #endif return false; } Path Path::Join(const std::string &pathA_, const std::string &pathB_) { return Path(pathA_, pathB_); } Path Path::Join(const Path &pathA_, const Path &pathB_) { return Path(pathA_, pathB_); } bool Path::Valid() const { return _HasProperValue; } // Operators Path operator/(const std::string &path_, const std::string &pathB_) { return Path(path_, pathB_); } Path operator/(const Path &path_, const Path &pathB_) { return Path(path_, pathB_); } Path operator/(const std::string &path_, const Path &pathB_) { return Path(path_, pathB_); } Path operator/(const Path &path_, const std::string &pathB_) { return Path(path_, pathB_); } void Path::operator/=(const Path &pathB_) { // Set internal path _InternalPath = _InternalPath + __GetJoinChar() + pathB_._InternalPath; // Check path __CorrectPath(); } void Path::operator/=(const std::string &pathB_) { // Set internal path _InternalPath = _InternalPath + __GetJoinChar() + pathB_; // Check path __CorrectPath(); } Path::operator std::string() const { return _InternalPath; } // Private Methods std::string Path::__CleanPathString(const std::string &str_) { #if defined(_WIN32) && defined(PLATFORM_DESKTOP) // TODO: Another way to fix Unicode path names. // TODO: Basically Ngine needs better Unicode support in general return str_; // // Get path length // auto len = GetShortPathNameA(str_.c_str(), nullptr, 0); // // // Check length // if (len == 0) { // auto e = GetLastError(); // if (e == 0x2 || e == 0x3) // File not found/Path not found, cannot clean it // return str_; // else throw std::runtime_error("GetShortPathNameA error."); // } // // // Allocate buffer // auto buffer = new char[len]; // // // Get path // len = GetShortPathNameA(str_.c_str(), buffer, len); // // // Check length // if (len == 0) { // auto e = GetLastError(); // if (e == 0x2 || e == 0x3) // File not found/Path not found, cannot clean it // return str_; // else throw std::runtime_error("GetShortPathNameA error."); // } // // // Convert to string // auto string = std::string(buffer); // // // Delete buffer // delete[] buffer; // // return string; #endif return str_; } void Path::__CorrectPath() { // Clean path _InternalPath = __CleanPathString(_InternalPath); // Search for empty string if (_InternalPath.empty()) { // Not a correct value _HasProperValue = false; return; } // Look for any non-whitespace chars bool hasNonWhitespace = false; for (auto c : _InternalPath) { if (c != ' ') { hasNonWhitespace = true; break; } } if (!hasNonWhitespace) { // Not a correct value _HasProperValue = false; return; } // Look for notation foreign to this OS if (__GetJoinChar() != '\\') { std::replace(_InternalPath.begin(), _InternalPath.end(), '\\', __GetJoinChar()); } if (__GetJoinChar() != '/') { std::replace(_InternalPath.begin(), _InternalPath.end(), '/', __GetJoinChar()); } // Is valid _HasProperValue = true; } std::string Path::__GetHome() { #if defined(__linux__) || defined(__APPLE__) int uid = getuid(); // Use HOME environment variable if not run as root const char *homeVar = std::getenv("HOME"); if (uid != 0 && homeVar) return std::string(homeVar); // Use psswd home struct passwd *pw = getpwuid(uid); return std::string(pw->pw_dir); #endif return ""; } char Path::__GetJoinChar() { // TODO: See if there are any more variations #if defined(_WIN32) return '\\'; #else return '/'; #endif } //////// // FilesystemObject //////// // Public Methods void FilesystemObject::Move(const Path &newPath_) { // Move file rename(ObjectPath.GetString().c_str(), newPath_.GetString().c_str()); } void FilesystemObject::Rename(const std::string &newName_) { // Rename Move(ObjectPath / newName_); } std::string FilesystemObject::GetObjectName() const { return ObjectPath.GetObjectName(); } Path FilesystemObject::GetObjectPath() const { return ObjectPath; } // Protected Constructors FilesystemObject::FilesystemObject(const Path &path_) : ObjectPath(path_) {} //////// // File //////// // InternalFileHandler Destructor File::InternalFileHandler::~InternalFileHandler() { if (InternalHandle != nullptr) fclose(InternalHandle); InternalHandle = nullptr; } // Public Constructor(s) File::File() : FilesystemObject(Path()) { // Create an empty handler _InternalHandle = std::make_shared<InternalFileHandler>(); } File::File(const Path &path_) : FilesystemObject(path_) { // Check path is valid if (!path_.Valid()) throw std::runtime_error("File must be given a valid path."); // Create an empty handler _InternalHandle = std::make_shared<InternalFileHandler>(); } // Destructor File::~File() { // Close file in case it isnt gone already Close(); } // Public Methods void File::Close() { // Close file if (_InternalHandle->InternalHandle != nullptr) { fclose(_InternalHandle->InternalHandle); _InternalHandle->InternalHandle = nullptr; } // Set mode _InternalOpenMode = MODE_NONE; } File File::CreateNewFile(const Path &path_, bool leaveOpen_, bool binary_) { File f(path_); f.Open(MODE_WRITE, binary_); if (!leaveOpen_) f.Close(); return f; } bool File::Delete() { // Ensure that we are closed Close(); // Remove from filesystem return remove(ObjectPath.GetString().c_str()) == 0; } bool File::Exists() const { // If we are open, we know we exist if (IsOpen()) return true; // Using C apis so that it is cross platform FILE *file = fopen(ObjectPath.GetString().c_str(), "r"); if (file != nullptr) { fclose(file); return true; } return false; } FileOpenMode File::GetCurrentMode() const { return _InternalOpenMode; } File File::GetFile(const Path &path_) { return File(path_); } std::string File::GetFileExtension() const { return ObjectPath.GetFileExtension(); } FILE *File::GetFileHandle() const { if (!IsOpen()) { ConsoleMessage("Cannot get handle of file that is not open.", "WARN", "File"); return nullptr; } return _InternalHandle->InternalHandle; } int File::GetSize() const { if (!IsOpen()) { ConsoleMessage("Cannot determine size of file that is not open.", "WARN", "File"); return 0; } fseek(_InternalHandle->InternalHandle, 0, SEEK_END); auto s = ftell(_InternalHandle->InternalHandle); fseek(_InternalHandle->InternalHandle, 0, SEEK_SET); return s; } bool File::IsOpen() const { if (_InternalHandle == nullptr) return false; return _InternalHandle->InternalHandle != nullptr; } bool File::Open(FileOpenMode mode_, bool binary_) { // Check validity of path if (!ObjectPath.Valid()) throw std::runtime_error("This file's path is invalid"); // Open with selected mode switch(mode_) { case MODE_READ: // Check this is actually a file if (ObjectPath.GetResourceType() != TYPE_FILE) throw std::runtime_error("This path does not point to a file."); // Open binary file for read _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "rb" : "r"); // Set mode _InternalOpenMode = mode_; break; case MODE_WRITE: // Open binary file for write _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "wb" : "w"); // Set mode _InternalOpenMode = mode_; break; case MODE_APPEND: // Open binary file for append _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "ab" : "a"); // Set mode _InternalOpenMode = mode_; break; case MODE_READ_WRITE: // Open binary file for read and write _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "w+b" : "w+"); // Set mode _InternalOpenMode = mode_; break; case MODE_READ_APPEND: // Open binary file for read and append _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "a+b" : "a+"); // Set mode _InternalOpenMode = mode_; break; default: ConsoleMessage("File mode not supported.", "WARN", "File"); // Set mode _InternalOpenMode = MODE_NONE; break; } // Return success return IsOpen(); } unsigned char *File::ReadBytes(int size_, int offset_) { if (!IsOpen()) throw std::runtime_error("Cannot read from closed file."); // Check for our mode if (_InternalOpenMode != MODE_READ && _InternalOpenMode != MODE_READ_WRITE && _InternalOpenMode != MODE_READ_APPEND) throw std::runtime_error("File not opened for reading."); // Determine file size if size is -1 auto filesize_ = GetSize(); if (size_ == -1) { size_ = filesize_; } if (size_ <= 0) { throw std::runtime_error("Invalid read size."); } if (offset_ >= filesize_ || offset_ < 0) { throw std::runtime_error("Invalid offset."); } if (size_ + offset_ > filesize_) { throw std::runtime_error("Data out of bounds."); } // Seek to the offset fseek(_InternalHandle->InternalHandle, offset_, SEEK_SET); // Read bytes to array auto *buffer = new unsigned char[size_]; fread(buffer, size_, 1, _InternalHandle->InternalHandle); // Return data return buffer; } std::string File::ReadString(int size_, int offset_) { // Check we're open if (!IsOpen()) throw std::runtime_error("Cannot read from closed file."); // Check for our mode if (_InternalOpenMode != MODE_READ && _InternalOpenMode != MODE_READ_WRITE && _InternalOpenMode != MODE_READ_APPEND) throw std::runtime_error("File not opened for reading."); // Determine file size if size is -1 auto filesize_ = GetSize(); if (size_ == -1) { size_ = filesize_; } if (size_ <= 0) { throw std::runtime_error("Invalid read size."); } if (offset_ >= filesize_ || offset_ < 0) { throw std::runtime_error("Invalid offset."); } if (size_ + offset_ > filesize_) { throw std::runtime_error("Data out of bounds."); } // Seek to the offset fseek(_InternalHandle->InternalHandle, offset_, SEEK_SET); // Read to c string auto buffer = new char[size_ + 1]; int r = fread(buffer, 1, size_, _InternalHandle->InternalHandle); // Null-terminate buffer buffer[r] = '\0'; // Convert to string auto str = std::string(buffer); // Delete buffer delete[] buffer; return str; } bool File::WriteBytes(unsigned char *data_, int size_) { // Check we're open if (!IsOpen()) throw std::runtime_error("Cannot write to a closed file."); // Check for our mode if (_InternalOpenMode != MODE_WRITE && _InternalOpenMode != MODE_APPEND && _InternalOpenMode != MODE_READ_WRITE && _InternalOpenMode != MODE_READ_APPEND) throw std::runtime_error("File not opened for writing."); // Write return fwrite(data_, 1, size_, _InternalHandle->InternalHandle) == 1; } bool File::WriteString(const std::string &string_) { // Check we're open if (!IsOpen()) throw std::runtime_error("Cannot write to closed file."); // Check for our mode if (_InternalOpenMode != MODE_WRITE && _InternalOpenMode != MODE_APPEND && _InternalOpenMode != MODE_READ_WRITE && _InternalOpenMode != MODE_READ_APPEND) throw std::runtime_error("File not opened for writing."); // Write string return fputs(string_.c_str(), _InternalHandle->InternalHandle) != EOF; } //////// // Directory //////// Directory::Directory() : FilesystemObject(Path()) {} Directory::Directory(const Path &path_) : FilesystemObject(path_) { // Check for valid path if (!path_.Valid()) throw std::runtime_error("Directory must be given a valid path."); } bool Directory::Create() { auto success = false; #if defined(_WIN32) // Create directory success = CreateDirectoryA(GetObjectPath().GetString().c_str(), nullptr) != 0; #elif defined(__linux__) || defined(__APPLE__) // Create directory success = mkdir(GetObjectPath().GetString().c_str(), 0777) == 0; #endif return success; } std::pair<bool, Directory> Directory::Create(const Path &path_) { auto dir = Directory(path_); return {dir.Create(), dir}; } bool Directory::Delete() { // Check __ThrowAccessErrors(); #if defined(_WIN32) // Try to delete (not recursive) auto del = RemoveDirectoryA(ObjectPath.GetString().c_str()); return del != 0; #elif defined(__linux__) || defined(__APPLE__) return remove(ObjectPath.GetString().c_str()) == 0; #endif return false; } bool Directory::DeleteRecursive() { // Check __ThrowAccessErrors(); // Success tracker auto success = true; // Delete my own files for (auto file : GetFiles()) { if (!file.Delete()) { success = false; break; } } // Stop if we find an issue if (!success) return false; // Get directories auto dirs = GetDirectories(); // Delete child directories for (auto dir : dirs) { if (!dir.DeleteRecursive()) { success = false; break; } } // Stop if we find an issue if (!success) return false; // Delete self success = Delete(); // Return return success; } bool Directory::Exists() const { #if defined(_WIN32) // https://stackoverflow.com/a/6218445 // Get attributes for directory DWORD dwAttrib = GetFileAttributesA(ObjectPath.GetString().c_str()); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); #elif defined(__linux__) || defined(__APPLE__) // Test opening of file DIR *dir = opendir(ObjectPath.GetString().c_str()); if (dir) { closedir(dir); return true; } return false; #endif return false; } Directory Directory::GetAppDataDirectory() { return Directory(Path::GetAppDataDirectory()); } std::vector<Directory> Directory::GetDirectories() const { // Check __ThrowAccessErrors(); // Directories vector auto dirs = std::vector<Directory>(); #if defined(_WIN32) // Find first directory WIN32_FIND_DATAA FindFileData; HANDLE hFind = FindFirstFileA((ObjectPath.GetString() + "\\*").c_str(), &FindFileData); // Check exists if (hFind == INVALID_HANDLE_VALUE) { throw std::runtime_error("Invalid directory."); } // Search for directories do { if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { auto dirName = FindFileData.cFileName; // Avoids . and .. directories if (strcmp(dirName, ".") != 0 && strcmp(dirName, "..") != 0) dirs.push_back(Directory(Path(ObjectPath, dirName))); } } while (FindNextFileA(hFind, &FindFileData) != 0); // Close search FindClose(hFind); #elif defined(__linux__) || defined(__APPLE__) // Variables DIR *dir; dirent *entry; // Open dir dir = opendir(ObjectPath.GetString().c_str()); // Test open if (!dir) throw std::runtime_error("Cannot open directory."); // Read all directories while ((entry = readdir(dir)) != nullptr) { if (entry->d_type == DT_DIR) { if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) dirs.push_back(Directory(Path(ObjectPath, entry->d_name))); } } // Close directory closedir(dir); #endif return dirs; } std::vector<File> Directory::GetFiles() const { // Check __ThrowAccessErrors(); // Files vector auto files = std::vector<File>(); #if defined(_WIN32) // Find the first file in the directory WIN32_FIND_DATAA FindFileData; HANDLE hFind = FindFirstFileA((ObjectPath.GetString() + "\\*").c_str(), &FindFileData); // Check it exists if (hFind == INVALID_HANDLE_VALUE) { auto err = GetLastError(); throw std::runtime_error("Invalid directory."); } // Get all files do { if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { auto filename = FindFileData.cFileName; files.push_back(File(Path(ObjectPath, filename))); } } while (FindNextFileA(hFind, &FindFileData) != 0); // Close search FindClose(hFind); #elif defined(__linux__) || defined(__APPLE__) // Variables DIR *dir; dirent *entry; // Open dir dir = opendir(ObjectPath.GetString().c_str()); // Test open if (!dir) throw std::runtime_error("Cannot open directory."); // Read all directories while ((entry = readdir(dir)) != nullptr) { if (entry->d_type != DT_DIR) { files.push_back(File(Path(ObjectPath, entry->d_name))); } } // Close directory closedir(dir); #endif return files; } std::vector<File> Directory::GetFilesRecursive() const { // Check __ThrowAccessErrors(); // Keep track of all files auto files = std::vector<File>(); // Grab my files auto myFiles = GetFiles(); files.insert(files.end(), myFiles.begin(), myFiles.end()); // Get all descendant directories auto dirs = GetDirectories(); for (auto dir : dirs) { auto dirFiles = dir.GetFilesRecursive(); files.insert(files.end(), dirFiles.begin(), dirFiles.end()); } return files; } Directory Directory::GetDirectory(const Path &path_) { return Directory(path_); } Directory Directory::GetExecutableDirectory() { return Directory(Path::GetExecutableDirectory()); } Directory Directory::GetWorkingDirectory() { return Directory(Path::GetWorkingDirectory()); } // Private Fields void Directory::__ThrowAccessErrors() const { // Check exists if (!Exists()) throw std::runtime_error("This directory does not exist."); // Check this is actually a directory if (GetObjectPath().GetResourceType() != TYPE_DIRECTORY) throw std::runtime_error("This path does not point to a directory."); } }
28.243148
134
0.556648
NerdThings
e80537687f2043bd8070d48f5b59437539a52a0c
187
hpp
C++
src/modules/osgWidget/generated_code/Frame.pypp.hpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osgWidget/generated_code/Frame.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osgWidget/generated_code/Frame.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #ifndef Frame_hpp__pyplusplus_wrapper #define Frame_hpp__pyplusplus_wrapper void register_Frame_class(); #endif//Frame_hpp__pyplusplus_wrapper
20.777778
40
0.834225
JaneliaSciComp
e8099e57d34b5af79ab4097f580737e83357e643
3,353
cc
C++
api/cpp/sona_api.cc
LeechanX/Sona
68bdf18d1011ec465ec9de50d4ad189b1f117ede
[ "MIT" ]
39
2018-08-08T14:08:04.000Z
2021-12-07T06:12:19.000Z
api/cpp/sona_api.cc
LeechanX/Sona
68bdf18d1011ec465ec9de50d4ad189b1f117ede
[ "MIT" ]
1
2018-08-09T02:33:16.000Z
2018-08-10T14:18:42.000Z
api/cpp/sona_api.cc
LeechanX/Sona
68bdf18d1011ec465ec9de50d4ad189b1f117ede
[ "MIT" ]
9
2018-08-30T05:57:58.000Z
2021-01-11T03:21:59.000Z
#include "sona_api.h" #include "conf_memory.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <pthread.h> #include <sstream> #include <algorithm> #include "network.h" static std::string trim(const std::string& str) { std::string::size_type pos = str.find_first_not_of(' '); if (pos == std::string::npos) { return ""; } std::string::size_type pos2 = str.find_last_not_of(' '); if (pos2 != std::string::npos) { return str.substr(pos, pos2 - pos + 1); } return str.substr(pos); } static std::vector<std::string> split_by_comma(const std::string& str) { std::stringstream ss(str); std::vector<std::string> result; while(ss.good()) { std::string substr; std::getline(ss, substr, ','); substr = trim(substr); if (substr != "") { result.push_back(substr); } } return result; } //keep using void* keep_using(void* args) { sona_api* api = (sona_api*)args; //keep using while (1) { sleep(10); //keep using send_keep_using(api->sockfd, api->service_key); } } sona_api::~sona_api() { if (ffd != -1) { close(ffd); } if (memory == NULL) { detach_mmap((void*)memory); } if (sockfd != -1) { close(sockfd); } } //get value const std::string sona_api::get(std::string section, std::string key) { std::string conf_key = trim(section) + "." + trim(key); if (conf_key.size() > ConfKeyCap) { fprintf(stderr, "format error: configure key %s is too long\n", conf_key.c_str()); return ""; } char c_value[ConfValueCap + 1]; c_value[0] = '\0'; //lock read lock struct flock lock; lock.l_type = F_RDLCK; lock.l_start = 0; lock.l_whence = SEEK_SET; lock.l_len = 0; fcntl(ffd, F_SETLKW, &lock); get_conf(memory, index, service_key.c_str(), conf_key.c_str(), c_value); //unlock lock.l_type = F_UNLCK; fcntl(ffd, F_SETLK, &lock); const std::string value(c_value); return value; } //get list std::vector<std::string> sona_api::get_list(std::string section, std::string key) { return split_by_comma(get(section, key)); } //must invoke init function before use api sona_api* init_api(const char* service_key) { if (strlen(service_key) > ServiceKeyCap) { fprintf(stderr, "format error: service key %s is too long\n", service_key); return NULL; } sona_api* api = new sona_api(); if (api == NULL) { return NULL; } api->sockfd = create_socket(); if (api->sockfd == -1) { delete api; return NULL; } api->memory = (char*)attach_mmap(); if (api->memory == NULL) { delete api; return NULL; } //subscribe int ret = subscribe(api->sockfd, service_key); if (ret == -1) { delete api; return NULL; } api->index = ret; //create flock char path[1024]; sprintf(path, "/tmp/sona/cfg_%u.lock", api->index); api->ffd = open(path, O_RDONLY, 0400); if (api->ffd == -1) { delete api; return NULL; } api->service_key = service_key; pthread_t tid; pthread_create(&tid, NULL, keep_using, api); pthread_detach(tid); return api; }
24.122302
90
0.579779
LeechanX
e809d18d381bc7627564d835d0abda51c14e182e
1,578
cpp
C++
Store/XamlWin2D/App.cpp
moutend/cppwinrt
737cbbb11fe56e4d94ff9d84a44aa72e0689016b
[ "MIT" ]
83
2017-11-15T22:51:43.000Z
2022-03-01T09:54:00.000Z
Store/XamlWin2D/App.cpp
moutend/cppwinrt
737cbbb11fe56e4d94ff9d84a44aa72e0689016b
[ "MIT" ]
1
2017-11-13T03:14:01.000Z
2017-11-14T18:01:06.000Z
Store/XamlWin2D/App.cpp
moutend/cppwinrt
737cbbb11fe56e4d94ff9d84a44aa72e0689016b
[ "MIT" ]
24
2017-11-16T22:01:41.000Z
2021-08-04T09:27:46.000Z
#include "pch.h" using namespace winrt; using namespace Windows::ApplicationModel::Activation; using namespace Windows::Foundation; using namespace Windows::Foundation::Numerics; using namespace Windows::UI; using namespace Windows::UI::Xaml; using namespace Microsoft::Graphics::Canvas; using namespace Microsoft::Graphics::Canvas::Text; using namespace Microsoft::Graphics::Canvas::UI::Xaml; struct App : ApplicationT<App> { void OnLaunched(LaunchActivatedEventArgs const &) { CanvasTextFormat format; format.HorizontalAlignment(CanvasHorizontalAlignment::Center); format.VerticalAlignment(CanvasVerticalAlignment::Center); format.FontSize(72.0f); format.FontFamily(L"Segoe UI Semibold"); CanvasControl control; control.Draw([=](CanvasControl const& sender, CanvasDrawEventArgs const& args) { float2 size = sender.Size(); float2 center{ size.x / 2.0f, size.y / 2.0f }; Rect bounds{ 0.0f, 0.0f, size.x, size.y }; CanvasDrawingSession session = args.DrawingSession(); session.FillEllipse(center, center.x - 50.0f, center.y - 50.0f, Colors::DarkSlateGray()); session.DrawText(L"Win2D with\nC++/WinRT!", bounds, Colors::Orange(), format); }); Window window = Window::Current(); window.Content(control); window.Activate(); } }; int __stdcall wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) { Application::Start([](auto &&) { make<App>(); }); }
32.204082
102
0.646388
moutend