blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
fe4feaa3c091e646b9b4058440b95ea055b26b97
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-sagemaker/include/aws/sagemaker/model/MonitoringSchedule.h
f55fcd159cfd70059f72b6343f7160c640a99542
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
21,447
h
MonitoringSchedule.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/sagemaker/SageMaker_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/sagemaker/model/ScheduleStatus.h> #include <aws/sagemaker/model/MonitoringType.h> #include <aws/core/utils/DateTime.h> #include <aws/sagemaker/model/MonitoringScheduleConfig.h> #include <aws/sagemaker/model/MonitoringExecutionSummary.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/sagemaker/model/Tag.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace SageMaker { namespace Model { /** * <p>A schedule for a model monitoring job. For information about model monitor, * see <a * href="https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor.html">Amazon * SageMaker Model Monitor</a>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/MonitoringSchedule">AWS * API Reference</a></p> */ class MonitoringSchedule { public: AWS_SAGEMAKER_API MonitoringSchedule(); AWS_SAGEMAKER_API MonitoringSchedule(Aws::Utils::Json::JsonView jsonValue); AWS_SAGEMAKER_API MonitoringSchedule& operator=(Aws::Utils::Json::JsonView jsonValue); AWS_SAGEMAKER_API Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The Amazon Resource Name (ARN) of the monitoring schedule.</p> */ inline const Aws::String& GetMonitoringScheduleArn() const{ return m_monitoringScheduleArn; } /** * <p>The Amazon Resource Name (ARN) of the monitoring schedule.</p> */ inline bool MonitoringScheduleArnHasBeenSet() const { return m_monitoringScheduleArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the monitoring schedule.</p> */ inline void SetMonitoringScheduleArn(const Aws::String& value) { m_monitoringScheduleArnHasBeenSet = true; m_monitoringScheduleArn = value; } /** * <p>The Amazon Resource Name (ARN) of the monitoring schedule.</p> */ inline void SetMonitoringScheduleArn(Aws::String&& value) { m_monitoringScheduleArnHasBeenSet = true; m_monitoringScheduleArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the monitoring schedule.</p> */ inline void SetMonitoringScheduleArn(const char* value) { m_monitoringScheduleArnHasBeenSet = true; m_monitoringScheduleArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the monitoring schedule.</p> */ inline MonitoringSchedule& WithMonitoringScheduleArn(const Aws::String& value) { SetMonitoringScheduleArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the monitoring schedule.</p> */ inline MonitoringSchedule& WithMonitoringScheduleArn(Aws::String&& value) { SetMonitoringScheduleArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the monitoring schedule.</p> */ inline MonitoringSchedule& WithMonitoringScheduleArn(const char* value) { SetMonitoringScheduleArn(value); return *this;} /** * <p>The name of the monitoring schedule.</p> */ inline const Aws::String& GetMonitoringScheduleName() const{ return m_monitoringScheduleName; } /** * <p>The name of the monitoring schedule.</p> */ inline bool MonitoringScheduleNameHasBeenSet() const { return m_monitoringScheduleNameHasBeenSet; } /** * <p>The name of the monitoring schedule.</p> */ inline void SetMonitoringScheduleName(const Aws::String& value) { m_monitoringScheduleNameHasBeenSet = true; m_monitoringScheduleName = value; } /** * <p>The name of the monitoring schedule.</p> */ inline void SetMonitoringScheduleName(Aws::String&& value) { m_monitoringScheduleNameHasBeenSet = true; m_monitoringScheduleName = std::move(value); } /** * <p>The name of the monitoring schedule.</p> */ inline void SetMonitoringScheduleName(const char* value) { m_monitoringScheduleNameHasBeenSet = true; m_monitoringScheduleName.assign(value); } /** * <p>The name of the monitoring schedule.</p> */ inline MonitoringSchedule& WithMonitoringScheduleName(const Aws::String& value) { SetMonitoringScheduleName(value); return *this;} /** * <p>The name of the monitoring schedule.</p> */ inline MonitoringSchedule& WithMonitoringScheduleName(Aws::String&& value) { SetMonitoringScheduleName(std::move(value)); return *this;} /** * <p>The name of the monitoring schedule.</p> */ inline MonitoringSchedule& WithMonitoringScheduleName(const char* value) { SetMonitoringScheduleName(value); return *this;} /** * <p>The status of the monitoring schedule. This can be one of the following * values.</p> <ul> <li> <p> <code>PENDING</code> - The schedule is pending being * created.</p> </li> <li> <p> <code>FAILED</code> - The schedule failed.</p> </li> * <li> <p> <code>SCHEDULED</code> - The schedule was successfully created.</p> * </li> <li> <p> <code>STOPPED</code> - The schedule was stopped.</p> </li> </ul> */ inline const ScheduleStatus& GetMonitoringScheduleStatus() const{ return m_monitoringScheduleStatus; } /** * <p>The status of the monitoring schedule. This can be one of the following * values.</p> <ul> <li> <p> <code>PENDING</code> - The schedule is pending being * created.</p> </li> <li> <p> <code>FAILED</code> - The schedule failed.</p> </li> * <li> <p> <code>SCHEDULED</code> - The schedule was successfully created.</p> * </li> <li> <p> <code>STOPPED</code> - The schedule was stopped.</p> </li> </ul> */ inline bool MonitoringScheduleStatusHasBeenSet() const { return m_monitoringScheduleStatusHasBeenSet; } /** * <p>The status of the monitoring schedule. This can be one of the following * values.</p> <ul> <li> <p> <code>PENDING</code> - The schedule is pending being * created.</p> </li> <li> <p> <code>FAILED</code> - The schedule failed.</p> </li> * <li> <p> <code>SCHEDULED</code> - The schedule was successfully created.</p> * </li> <li> <p> <code>STOPPED</code> - The schedule was stopped.</p> </li> </ul> */ inline void SetMonitoringScheduleStatus(const ScheduleStatus& value) { m_monitoringScheduleStatusHasBeenSet = true; m_monitoringScheduleStatus = value; } /** * <p>The status of the monitoring schedule. This can be one of the following * values.</p> <ul> <li> <p> <code>PENDING</code> - The schedule is pending being * created.</p> </li> <li> <p> <code>FAILED</code> - The schedule failed.</p> </li> * <li> <p> <code>SCHEDULED</code> - The schedule was successfully created.</p> * </li> <li> <p> <code>STOPPED</code> - The schedule was stopped.</p> </li> </ul> */ inline void SetMonitoringScheduleStatus(ScheduleStatus&& value) { m_monitoringScheduleStatusHasBeenSet = true; m_monitoringScheduleStatus = std::move(value); } /** * <p>The status of the monitoring schedule. This can be one of the following * values.</p> <ul> <li> <p> <code>PENDING</code> - The schedule is pending being * created.</p> </li> <li> <p> <code>FAILED</code> - The schedule failed.</p> </li> * <li> <p> <code>SCHEDULED</code> - The schedule was successfully created.</p> * </li> <li> <p> <code>STOPPED</code> - The schedule was stopped.</p> </li> </ul> */ inline MonitoringSchedule& WithMonitoringScheduleStatus(const ScheduleStatus& value) { SetMonitoringScheduleStatus(value); return *this;} /** * <p>The status of the monitoring schedule. This can be one of the following * values.</p> <ul> <li> <p> <code>PENDING</code> - The schedule is pending being * created.</p> </li> <li> <p> <code>FAILED</code> - The schedule failed.</p> </li> * <li> <p> <code>SCHEDULED</code> - The schedule was successfully created.</p> * </li> <li> <p> <code>STOPPED</code> - The schedule was stopped.</p> </li> </ul> */ inline MonitoringSchedule& WithMonitoringScheduleStatus(ScheduleStatus&& value) { SetMonitoringScheduleStatus(std::move(value)); return *this;} /** * <p>The type of the monitoring job definition to schedule.</p> */ inline const MonitoringType& GetMonitoringType() const{ return m_monitoringType; } /** * <p>The type of the monitoring job definition to schedule.</p> */ inline bool MonitoringTypeHasBeenSet() const { return m_monitoringTypeHasBeenSet; } /** * <p>The type of the monitoring job definition to schedule.</p> */ inline void SetMonitoringType(const MonitoringType& value) { m_monitoringTypeHasBeenSet = true; m_monitoringType = value; } /** * <p>The type of the monitoring job definition to schedule.</p> */ inline void SetMonitoringType(MonitoringType&& value) { m_monitoringTypeHasBeenSet = true; m_monitoringType = std::move(value); } /** * <p>The type of the monitoring job definition to schedule.</p> */ inline MonitoringSchedule& WithMonitoringType(const MonitoringType& value) { SetMonitoringType(value); return *this;} /** * <p>The type of the monitoring job definition to schedule.</p> */ inline MonitoringSchedule& WithMonitoringType(MonitoringType&& value) { SetMonitoringType(std::move(value)); return *this;} /** * <p>If the monitoring schedule failed, the reason it failed.</p> */ inline const Aws::String& GetFailureReason() const{ return m_failureReason; } /** * <p>If the monitoring schedule failed, the reason it failed.</p> */ inline bool FailureReasonHasBeenSet() const { return m_failureReasonHasBeenSet; } /** * <p>If the monitoring schedule failed, the reason it failed.</p> */ inline void SetFailureReason(const Aws::String& value) { m_failureReasonHasBeenSet = true; m_failureReason = value; } /** * <p>If the monitoring schedule failed, the reason it failed.</p> */ inline void SetFailureReason(Aws::String&& value) { m_failureReasonHasBeenSet = true; m_failureReason = std::move(value); } /** * <p>If the monitoring schedule failed, the reason it failed.</p> */ inline void SetFailureReason(const char* value) { m_failureReasonHasBeenSet = true; m_failureReason.assign(value); } /** * <p>If the monitoring schedule failed, the reason it failed.</p> */ inline MonitoringSchedule& WithFailureReason(const Aws::String& value) { SetFailureReason(value); return *this;} /** * <p>If the monitoring schedule failed, the reason it failed.</p> */ inline MonitoringSchedule& WithFailureReason(Aws::String&& value) { SetFailureReason(std::move(value)); return *this;} /** * <p>If the monitoring schedule failed, the reason it failed.</p> */ inline MonitoringSchedule& WithFailureReason(const char* value) { SetFailureReason(value); return *this;} /** * <p>The time that the monitoring schedule was created.</p> */ inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; } /** * <p>The time that the monitoring schedule was created.</p> */ inline bool CreationTimeHasBeenSet() const { return m_creationTimeHasBeenSet; } /** * <p>The time that the monitoring schedule was created.</p> */ inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTimeHasBeenSet = true; m_creationTime = value; } /** * <p>The time that the monitoring schedule was created.</p> */ inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTimeHasBeenSet = true; m_creationTime = std::move(value); } /** * <p>The time that the monitoring schedule was created.</p> */ inline MonitoringSchedule& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;} /** * <p>The time that the monitoring schedule was created.</p> */ inline MonitoringSchedule& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;} /** * <p>The last time the monitoring schedule was changed.</p> */ inline const Aws::Utils::DateTime& GetLastModifiedTime() const{ return m_lastModifiedTime; } /** * <p>The last time the monitoring schedule was changed.</p> */ inline bool LastModifiedTimeHasBeenSet() const { return m_lastModifiedTimeHasBeenSet; } /** * <p>The last time the monitoring schedule was changed.</p> */ inline void SetLastModifiedTime(const Aws::Utils::DateTime& value) { m_lastModifiedTimeHasBeenSet = true; m_lastModifiedTime = value; } /** * <p>The last time the monitoring schedule was changed.</p> */ inline void SetLastModifiedTime(Aws::Utils::DateTime&& value) { m_lastModifiedTimeHasBeenSet = true; m_lastModifiedTime = std::move(value); } /** * <p>The last time the monitoring schedule was changed.</p> */ inline MonitoringSchedule& WithLastModifiedTime(const Aws::Utils::DateTime& value) { SetLastModifiedTime(value); return *this;} /** * <p>The last time the monitoring schedule was changed.</p> */ inline MonitoringSchedule& WithLastModifiedTime(Aws::Utils::DateTime&& value) { SetLastModifiedTime(std::move(value)); return *this;} inline const MonitoringScheduleConfig& GetMonitoringScheduleConfig() const{ return m_monitoringScheduleConfig; } inline bool MonitoringScheduleConfigHasBeenSet() const { return m_monitoringScheduleConfigHasBeenSet; } inline void SetMonitoringScheduleConfig(const MonitoringScheduleConfig& value) { m_monitoringScheduleConfigHasBeenSet = true; m_monitoringScheduleConfig = value; } inline void SetMonitoringScheduleConfig(MonitoringScheduleConfig&& value) { m_monitoringScheduleConfigHasBeenSet = true; m_monitoringScheduleConfig = std::move(value); } inline MonitoringSchedule& WithMonitoringScheduleConfig(const MonitoringScheduleConfig& value) { SetMonitoringScheduleConfig(value); return *this;} inline MonitoringSchedule& WithMonitoringScheduleConfig(MonitoringScheduleConfig&& value) { SetMonitoringScheduleConfig(std::move(value)); return *this;} /** * <p>The endpoint that hosts the model being monitored.</p> */ inline const Aws::String& GetEndpointName() const{ return m_endpointName; } /** * <p>The endpoint that hosts the model being monitored.</p> */ inline bool EndpointNameHasBeenSet() const { return m_endpointNameHasBeenSet; } /** * <p>The endpoint that hosts the model being monitored.</p> */ inline void SetEndpointName(const Aws::String& value) { m_endpointNameHasBeenSet = true; m_endpointName = value; } /** * <p>The endpoint that hosts the model being monitored.</p> */ inline void SetEndpointName(Aws::String&& value) { m_endpointNameHasBeenSet = true; m_endpointName = std::move(value); } /** * <p>The endpoint that hosts the model being monitored.</p> */ inline void SetEndpointName(const char* value) { m_endpointNameHasBeenSet = true; m_endpointName.assign(value); } /** * <p>The endpoint that hosts the model being monitored.</p> */ inline MonitoringSchedule& WithEndpointName(const Aws::String& value) { SetEndpointName(value); return *this;} /** * <p>The endpoint that hosts the model being monitored.</p> */ inline MonitoringSchedule& WithEndpointName(Aws::String&& value) { SetEndpointName(std::move(value)); return *this;} /** * <p>The endpoint that hosts the model being monitored.</p> */ inline MonitoringSchedule& WithEndpointName(const char* value) { SetEndpointName(value); return *this;} inline const MonitoringExecutionSummary& GetLastMonitoringExecutionSummary() const{ return m_lastMonitoringExecutionSummary; } inline bool LastMonitoringExecutionSummaryHasBeenSet() const { return m_lastMonitoringExecutionSummaryHasBeenSet; } inline void SetLastMonitoringExecutionSummary(const MonitoringExecutionSummary& value) { m_lastMonitoringExecutionSummaryHasBeenSet = true; m_lastMonitoringExecutionSummary = value; } inline void SetLastMonitoringExecutionSummary(MonitoringExecutionSummary&& value) { m_lastMonitoringExecutionSummaryHasBeenSet = true; m_lastMonitoringExecutionSummary = std::move(value); } inline MonitoringSchedule& WithLastMonitoringExecutionSummary(const MonitoringExecutionSummary& value) { SetLastMonitoringExecutionSummary(value); return *this;} inline MonitoringSchedule& WithLastMonitoringExecutionSummary(MonitoringExecutionSummary&& value) { SetLastMonitoringExecutionSummary(std::move(value)); return *this;} /** * <p>A list of the tags associated with the monitoring schedlue. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * Amazon Web Services resources</a> in the <i>Amazon Web Services General * Reference Guide</i>.</p> */ inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; } /** * <p>A list of the tags associated with the monitoring schedlue. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * Amazon Web Services resources</a> in the <i>Amazon Web Services General * Reference Guide</i>.</p> */ inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; } /** * <p>A list of the tags associated with the monitoring schedlue. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * Amazon Web Services resources</a> in the <i>Amazon Web Services General * Reference Guide</i>.</p> */ inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>A list of the tags associated with the monitoring schedlue. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * Amazon Web Services resources</a> in the <i>Amazon Web Services General * Reference Guide</i>.</p> */ inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>A list of the tags associated with the monitoring schedlue. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * Amazon Web Services resources</a> in the <i>Amazon Web Services General * Reference Guide</i>.</p> */ inline MonitoringSchedule& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;} /** * <p>A list of the tags associated with the monitoring schedlue. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * Amazon Web Services resources</a> in the <i>Amazon Web Services General * Reference Guide</i>.</p> */ inline MonitoringSchedule& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;} /** * <p>A list of the tags associated with the monitoring schedlue. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * Amazon Web Services resources</a> in the <i>Amazon Web Services General * Reference Guide</i>.</p> */ inline MonitoringSchedule& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; } /** * <p>A list of the tags associated with the monitoring schedlue. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * Amazon Web Services resources</a> in the <i>Amazon Web Services General * Reference Guide</i>.</p> */ inline MonitoringSchedule& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; } private: Aws::String m_monitoringScheduleArn; bool m_monitoringScheduleArnHasBeenSet = false; Aws::String m_monitoringScheduleName; bool m_monitoringScheduleNameHasBeenSet = false; ScheduleStatus m_monitoringScheduleStatus; bool m_monitoringScheduleStatusHasBeenSet = false; MonitoringType m_monitoringType; bool m_monitoringTypeHasBeenSet = false; Aws::String m_failureReason; bool m_failureReasonHasBeenSet = false; Aws::Utils::DateTime m_creationTime; bool m_creationTimeHasBeenSet = false; Aws::Utils::DateTime m_lastModifiedTime; bool m_lastModifiedTimeHasBeenSet = false; MonitoringScheduleConfig m_monitoringScheduleConfig; bool m_monitoringScheduleConfigHasBeenSet = false; Aws::String m_endpointName; bool m_endpointNameHasBeenSet = false; MonitoringExecutionSummary m_lastMonitoringExecutionSummary; bool m_lastMonitoringExecutionSummaryHasBeenSet = false; Aws::Vector<Tag> m_tags; bool m_tagsHasBeenSet = false; }; } // namespace Model } // namespace SageMaker } // namespace Aws
b8d774d7b5e76331afa979cfd05461a2d63b5006
6bc3f5955699fcdac540823c51354bc21919fb06
/Round-3/INOI 19/F.cpp
d419ce39da7a0ec9444c48204af2c3b74e5f6924
[]
no_license
soroush-tabesh/Competitive-Programming
e1a265e2224359962088c74191b7dc87bbf314bf
a677578c2a0e21c0510258933548a251970d330d
refs/heads/master
2021-09-24T06:36:43.037300
2018-10-04T14:12:00
2018-10-04T14:12:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,295
cpp
F.cpp
//In The Name of God #include <bits/stdc++.h> #define Init ios_base::sync_with_stdio(0),cin.tie(0) #define forar(i,n) for(int i = 0; i < n;i++) #define fori(i,a,b) for(long long int i = a; i < b;i++) #define ford(i,a,b) for(long long int i = a; i > b;i--) #define WFile freopen("in.txt","r",stdin),freopen("out.txt","w",stdout) #define Log(x) cout << "Log: " << x << endl; #define F first #define S second #define pb push_back #define pf push_front using namespace std; typedef long long int ll; typedef long double ld; typedef pair<int,int> pii; typedef pair<ll,ll> pll; const ll delta = 10337; void Solution(); int score[6]; int m; int main() { Init; //WFile; Solution(); return 0; } ll ppow(ll base,ll exp){ if(exp == 0) return 1; if(exp == 1) return base; ll v = ppow(base,exp/2); v *= v; if(exp%2==1) v *= base; return v; } void solve(int depth){ if(depth == 0){ int sum = 0; forar(i,6){ sum += score[i]; } if(sum == 100){ set<int> tot; forar(i,ppow(2,6)){ int temp = 0; forar(w,6){ if(i & (1<<w)){ temp += score[w]; } } tot.insert(temp); } m = max(m,int(tot.size())); } }else{ fori(i,10,26){ score[depth-1]=i; solve(depth-1); } } } void Solution(){ solve(6); cout << (m*m*m)%delta << endl; }
32113b35dfdb68ea5a2a34962de5c38aed8f1629
383278dd8528182724ff60e20ef5ce603b3fd0f7
/AdvancedLevel_C++/1025.cpp
c0190c487203d462ca345c6403f26882f8c913e4
[]
no_license
YiChong-Liu/PAT
37df3405083d48255b2894037ab7d8f02603a36e
2a05c3740344225774d3b2f24cd2b4fd417af5f4
refs/heads/master
2022-03-19T18:00:46.110850
2022-03-13T19:27:22
2022-03-13T19:27:22
202,313,025
3
1
null
null
null
null
UTF-8
C++
false
false
1,343
cpp
1025.cpp
/*author:moonlake23 question1025:PAT Ranking*/ /*甲级第一题 噢耶(#^.^#)*/ #include<iostream> #include<string> #include<cstring> #include<algorithm> using namespace std; typedef struct { int location; char ID[14]; double score; int local_rank; }Student; bool cmp(Student a, Student b) { if (a.score != b.score)return a.score > b.score; else return strcmp(a.ID, b.ID) < 0; //分数相同按准考证号从小到大排序 } Student stu[30010]; int main() { int locations, cases,mark=0,len=0;//mark用来提供考点,len标记数组位置 cin >> locations; while (locations > 0) { locations--; mark++; cin >> cases; for (int i = len; i <len+cases; i++) { stu[i].location = mark; scanf("%s %lf", stu[i].ID, &stu[i].score); } sort(stu + len, stu + len + cases, cmp); for (int i = len; i < len + cases; i++) { //计算本地排名 if (stu[i].score == stu[i - 1].score)stu[i].local_rank = stu[i - 1].local_rank; else { stu[i].local_rank = i - len + 1; } } len += cases; } cout << len << endl; sort(stu, stu + len, cmp); int rank = 1; for (int i = 0; i < len; i++) { //如果分数相同则排名不发生变化 if (i > 0 && stu[i].score != stu[i - 1].score) { rank = i + 1; } printf("%s %d %d %d\n", stu[i].ID, rank, stu[i].location, stu[i].local_rank); } return 0; }
f883da23cd83cb50fcc4ed0a21d6f6158acf017d
621d7a83e3549b0570b2b7dde4ec6a985f1bd22c
/demo2.2_detect_cylinder/detection_rgbd/lib/vision.hpp
041b12b03badd860a182014a823bffa773f4f9da
[]
no_license
dbddqy/machine_perception
93270c3b56092e20cd77197fb2aa6c7c2839119b
6864794806e42923b130052b03f800473f3752d9
refs/heads/master
2021-07-07T09:22:53.152889
2020-11-30T19:09:14
2020-11-30T19:09:14
212,831,797
2
0
null
2019-10-04T20:34:27
2019-10-04T14:18:16
Python
UTF-8
C++
false
false
554
hpp
vision.hpp
// // Created by yue on 31.01.20. // #ifndef VISION_HPP #define VISION_HPP #include <opencv2/opencv.hpp> #include <vector> #include <stack> #include <pose.hpp> using namespace cv; using namespace std; class CameraConfig { public: Mat M; Mat distortion; Mat MInv; double fx, fy, cx, cy; CameraConfig(); }; CameraConfig C; void detectAruco(Mat img, vector<pose> &poses, vector<vector<Point2f> > &markerCorners, vector<int> &markerIds); void grow(cv::Mat& src, cv::Mat& mask, cv::Point seed, int threshold); #endif //VISION_HPP
1228b1ab6af446d1cffce68023484b5a4063f677
4754bb5470fbbd608323f468cddf6658b031e090
/2 семестр/HW5/Задача 1/testingtree.h
8979aae49df0ed231c779cf05f86a137802d2c19
[]
no_license
artbez/origin
af86cba1eacfbf85c10047afd84884355aece671
7fe1dd71cc3b8312cf3d5713714319bc4f629692
refs/heads/master
2016-09-03T06:32:57.485079
2015-05-28T20:54:28
2015-05-28T20:54:28
15,024,516
0
0
null
null
null
null
UTF-8
C++
false
false
1,118
h
testingtree.h
#pragma once #include <QObject> #include <QtTest/QTest> #include "tree.h" class TestingTree: public QObject { Q_OBJECT public: explicit TestingTree(QObject *parent = 0) : QObject(parent){} private slots: void simpleSumTest() { Tree * tree = new Tree("(+ 1 2)"); QVERIFY(tree->countTree() == 3); delete tree; } void simpleMoveTest() { Tree * tree = new Tree("(* 3 2)"); QVERIFY(tree->countTree() == 6); delete tree; } void simpleNegTest() { Tree * tree = new Tree("(- 3 2)"); QVERIFY(tree->countTree() == 1); delete tree; } void simpleDivTest() { Tree * tree = new Tree("(/ 4 2)"); QVERIFY(tree->countTree() == 2); delete tree; } void twoBracketsTest() { Tree * tree = new Tree("(+ (* 3 2) (/ 4 2))"); QVERIFY(tree->countTree() == 8); delete tree; } void hardTest() { Tree * tree = new Tree("(* (+ (* 3 2) (/ 4 2)) (- 7 (/ 4 2)))"); QVERIFY(tree->countTree() == 40); delete tree; } };
e4a0335537f4b5e7ff5fb938a6e1107aa1379f06
7a84597eb5b9281d2b152c6f8061b0bee8660d49
/tests/dump_files_for_tests/test_it_known_function_sqrt_5.cpp
fa9ba30d389ac7d8dc2dc1a13d2f8f4204d5329e
[ "MIT" ]
permissive
JasonSun623/phriky-units
bedbe8fd68519f54db0379e6c897dad2132856c8
16c8cdd91de0899411b139e5a94fcb4ea8104ad2
refs/heads/master
2020-05-04T15:10:46.553842
2019-02-08T22:36:54
2019-02-08T22:36:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
248
cpp
test_it_known_function_sqrt_5.cpp
#include <ros/ros.h> #include <sensor_msgs/Range.h> #include <math.h> int main(int argc, char **argv) { sensor_msgs::Range r; r.range = 0; float f = r.range * r.range; using std::sqrt; float x = sqrt(f); // meters? return 0; }
8d883ea064abba28497ffb5f68696790a4649a46
aba70b61f237998779e34b400fb88bf1b7d1a43a
/adhoc_package/adhoc_tests/src/adhoc_r.cpp
d4ed6d6e1b7b8cc466a6db18afbe410476fe1a0e
[]
no_license
Gdislave/running_setup
46e39931cf5432a083bc84dd07af5453750e90ff
e357a5305d97b23afc6e61d4514fc4d13b962005
refs/heads/master
2021-01-19T17:30:50.143579
2017-10-14T09:53:36
2017-10-14T09:53:36
101,065,215
0
0
null
2017-08-29T19:28:23
2017-08-22T13:20:41
C++
UTF-8
C++
false
false
2,684
cpp
adhoc_r.cpp
#include "ros/ros.h" #include "adhoc_customize/include.h" #include "adhoc_tests/FilenameService.h" #include <adhoc_tests/sendPing.h> #include <iostream> #include <fstream> ros::NodeHandle* nhp; std::ofstream outFile; int recvCounter = 0, linecounter = 0; void answerCallback(const adhoc_customize::RecvTime::ConstPtr& recvTime); void filenameCallback(const std_msgs::String::ConstPtr& msg); bool setFilename(adhoc_tests::FilenameService::Request &req, adhoc_tests::FilenameService::Response &res); int main (int argc, char **argv){ ros::init(argc, argv, "adhoc_timeRecv"); ros::NodeHandle nh; nhp = &nh; ros::Subscriber sub_answer = nh.subscribe("t_answer", 1000, answerCallback); ros::Subscriber sub_filename = nh.subscribe("t_filename", 1000, filenameCallback); ros::ServiceServer fnameService = nh.advertiseService("setFilename", setFilename); //ros::spin(); ros::AsyncSpinner spinner(4); spinner.start(); ros::waitForShutdown(); outFile.close(); return 1; } void answerCallback(const adhoc_customize::RecvTime::ConstPtr& recvTime){ ros::Time afterSend = ros::Time::now(); float sendTimeSec = (afterSend - recvTime->time).toSec(); ROS_INFO("%d.%d: RecvAnswer, Duration: [%f] sec", recvCounter, linecounter, sendTimeSec); //ignore first if(recvCounter){ outFile << sendTimeSec <<";"; linecounter++; } //make lines 25 wide if(linecounter == 25){ linecounter=0; outFile << "\n"; } recvCounter++; // send newPing ros::NodeHandle nh; ros::ServiceClient pingClient = nh.serviceClient<adhoc_tests::sendPing>("sendPing"); adhoc_tests::sendPing sendPing; if (pingClient.call(sendPing)) ROS_INFO("sentPing"); else ROS_ERROR("Error calling Ping service or loop is over"); } void filenameCallback(const std_msgs::String::ConstPtr& msg){ outFile << "\n"; outFile.close(); recvCounter = 0; linecounter = 0; outFile.open (msg->data.c_str(), std::ios_base::app); ROS_INFO("Filepath: [%s]", msg->data.c_str()); } bool setFilename(adhoc_tests::FilenameService::Request &req, adhoc_tests::FilenameService::Response &res){ outFile << "\n"; outFile.close(); recvCounter = 0; linecounter = 0; outFile.open (req.filename.c_str(), std::ios_base::app); ROS_INFO("Filepath from Service: [%s]", req.filename.c_str()); // request first ping ros::NodeHandle nh; ros::ServiceClient pingClient = nh.serviceClient<adhoc_tests::sendPing>("sendPing"); adhoc_tests::sendPing sendPing; ROS_INFO("before first ping req"); if ( ros::service::call("sendPing", sendPing)) //pingClient.call(sendPing)) ROS_INFO("sent first Ping"); else ROS_ERROR("Error calling first Ping service"); ROS_INFO("after first ping req"); return true; }
051008483fbcd57122c89ea4f05537dbb8dbbe52
189a2a674b8f641c10a5ff3efaacec14846e819b
/hls/src/Compiler/Synthesizer.cpp
6519645a460e2469b1b12e6c467d910fee6401fd
[]
no_license
rafaelgasperetti/llvm-fpga
8b9ea965f188291dffce74d9b2d5514751a85ddc
8c5a9963e4c2337f9b47d56dfa336637513455d8
refs/heads/master
2023-02-16T00:02:01.104414
2021-01-12T11:23:10
2021-01-12T11:23:10
328,963,739
0
0
null
null
null
null
UTF-8
C++
false
false
13,947
cpp
Synthesizer.cpp
#include<iostream> #include <fstream> #include<vector> #include<Tools/MessageLibrary.hpp> #include<Tools/StringUtils.hpp> #include<Compiler/Synthesizer.hpp> #include<FileManager/FileReader.hpp> #include<FileManager/FileWriter.hpp> #include<Core/Design.hpp> #include<Core/Component.hpp> #include<Core/IOComponent.hpp> #include<Core/Signal.hpp> #include<Components/cmp_add_op_s.hpp> #include<Components/cmp_counter.hpp> #include<Components/cmp_delay_op.hpp> #include<Components/cmp_mult_op_s.hpp> #include<Compiler/NodeVisitor.hpp> using namespace std; Synthesizer::Synthesizer(){ } string Synthesizer::GetLibrariesDeclaration() { string libl = ""; libl += "library IEEE;\n"; libl += "use IEEE.std_logic_1164.all;\n"; libl += "use IEEE.std_logic_arith.all;\n"; libl += "use IEEE.std_logic_unsigned.all;\n"; return libl; } string Synthesizer::GetEntityDeclaration(string entityName, int width) { string entity = ""; entity += "entity " + entityName +" is\n"; entity += " port(\n"; entity += " \\init\\ : in std_logic;\n"; entity += " \\done\\ : out std_logic;\n"; entity += " \\result\\ : out std_logic_vector(" + to_string(width - 1) + " downto 0);\n"; entity += " \\clk\\ : in std_logic;\n"; entity += " \\reset\\ : in std_logic;\n"; entity += " \\clear\\ : in std_logic\n"; entity += " ); \n"; entity += "end " + entityName + ";\n"; return entity; } string Synthesizer::GetConstantsDeclaration(vector<Component*>* components) { string constsDecl = ""; for(int i = 0; i < components->size(); i++) { if((*components)[i]->GetComponentName().compare("const_op") == 0) { constsDecl += "constant " + (*components)[i]->GetInstanceName() + " : std_logic_vector(" + to_string((*components)[i]->GetDataWidth() - 1) + " downto 0);\n"; } } constsDecl += "\n"; return constsDecl; } string Synthesizer::GetSignalsDeclaration(vector<Signal*>* signals) { string signalsDecl = ""; for (int i = 0; i < signals->size(); i++) { if((*signals)[i]->GetSignalName() == "\\init\\" || (*signals)[i]->GetSignalName() == "\\done\\" || (*signals)[i]->GetSignalName() == "\\result\\" || (*signals)[i]->GetSignalName() == "\\clk\\" || (*signals)[i]->GetSignalName() == "\\reset\\" || (*signals)[i]->GetSignalName() == "\\clear\\" ) continue; signalsDecl += "signal " + (*signals)[i]->GetSignalName() + " : " + (*signals)[i]->GetType(); if ((*signals)[i]->GetType() == "std_logic_vector") { if ((*signals)[i]->GetDataWidth() == 1) signalsDecl += "(0 downto 0);\n"; else signalsDecl += "(" + to_string((*signals)[i]->GetDataWidth() - 1) + " downto 0);\n"; } else { signalsDecl += ";\n"; } } signalsDecl += "\n"; return signalsDecl; } string Synthesizer::GetComponentInstancesDeclaration(vector<Component*>* components) { string componentDecl = ""; for (int i = 0, ramNumber = 0; i < components->size(); i++) { if((*components)[i]->GetVHDLDeclaration((*components)[i]->GetComponentName()).compare("") != 0) { string instanceType = ((*components)[i]->GetComponentName().compare("block_ram") == 0 ? (*components)[i]->GetComponentName() + "_" + to_string(ramNumber) : (*components)[i]->GetComponentName()); componentDecl += "\t" + (*components)[i]->GetInstanceName() + ": " + instanceType + "\n"; if((*components)[i]->GetComponentName().compare("block_ram") == 0) { ramNumber++; } componentDecl += GetComponentMapsDeclaration((*components)[i]->GetMaps()); componentDecl += GetComponentPortsDeclaration((*components)[i]->GetPorts()); componentDecl += "\n"; } } return componentDecl; } string Synthesizer::GetComponentMapsDeclaration(vector<GenericMap*> maps) { string mapsDecl = ""; if(maps.size() > 0) { mapsDecl += "\tgeneric map (\n"; for (int i = 0; i < maps.size(); i++) { mapsDecl += "\t\t" + maps[i]->GetName() + " => " + maps[i]->GetValue(); // If its the last decl it doesnt hava a , in the end if(i == (maps.size() - 1)) mapsDecl += "\n"; else mapsDecl += ",\n"; } mapsDecl += "\t)\n"; } return mapsDecl; } string Synthesizer::GetComponentPortsDeclaration(vector<Port*> ports) { string portsDecl = ""; if(ports.size() > 0) { portsDecl += "\tport map (\n"; for (int i = 0; i < ports.size(); i++) { for(Signal* s : ports[i]->GetPortSignals()) { if(s != NULL) { if(i > 0) { portsDecl = portsDecl + ",\n"; } if(ports[i]->GetWidth() == s->GetDataWidth()) { portsDecl += "\t\t" + ports[i]->GetName() + " => " + s->GetSignalName(); } else if(ports[i]->GetWidth() > 1 && s->GetDataWidth() == 1) { portsDecl += "\t\t" + ports[i]->GetName() + "(" + to_string(s->GetDataWidth() - 1) + " downto " + ports[i]->GetUsedWidthFinal() + ") => " + s->GetSignalName(); } else if(ports[i]->GetWidth() == 1 && s->GetDataWidth() > 1) { portsDecl += "\t\t" + ports[i]->GetName() + " => " + s->GetSignalName() + "(" + to_string(ports[i]->GetWidth() - 1) + ")"; } else if(ports[i]->GetWidth() > s->GetDataWidth()) { portsDecl += "\t\t" + ports[i]->GetName() + "(" + to_string(s->GetDataWidth() - 1) + " downto 0) => " + s->GetSignalName() + "(" + to_string(s->GetDataWidth() - 1) + " downto 0)"; } else { portsDecl += "\t\t" + ports[i]->GetName() + "(" + ports[i]->GetUsedWidthInitial() + " downto " + ports[i]->GetUsedWidthFinal() + ") => " + s->GetSignalName() + "(" + ports[i]->GetUsedWidthInitial() + " downto " + ports[i]->GetUsedWidthFinal() + ")"; } } } if(i == ports.size() - 1) { portsDecl += "\n"; } } portsDecl += "\t);\n"; } return portsDecl; } string Synthesizer::GetExternalComponentsDeclaration(vector<Component*>* components) { string output = ""; vector<string> declaredTypes; for (int i = 0, ramNumber = 0; i < components->size(); i++) { if(StringUtils::IndexOf((*components)[i]->GetComponentName(), declaredTypes) == -1) { if ((*components)[i]->GetComponentName() == "block_ram") { output += (*components)[i]->GetVHDLDeclaration(to_string(ramNumber)); declaredTypes.push_back((*components)[i]->GetComponentName() + "_" + to_string(ramNumber)); ramNumber++; } else if ((*components)[i]->IsDeclared() == false) { output += (*components)[i]->GetVHDLDeclaration(""); declaredTypes.push_back((*components)[i]->GetComponentName()); } } } return output; } string Synthesizer::GetDesignDeclaration(Design* design) { string output = ""; vector<Component*>* components = GetComponents(design); output += GetLibrariesDeclaration() + "\n"; output += GetEntityDeclaration(design->GetName(), design->GetWidth()) + "\n"; output += "architecture behavior of " + design->GetName() + " is \n"; output += GetExternalComponentsDeclaration(components); output += GetConstantsDeclaration(components); output += GetSignalsDeclaration(design->GetSignals()); output += "begin\n"; output += GetComponentInstancesDeclaration(components); output += "end behavior;"; return output; } void Synthesizer::CreateMemoryFile(vector<Cmp_block_ram*> memories, FileWriter* mainWriter) { if(memories.size() > 0) { string memoryPath = mainWriter->GetParentPaths() + mainWriter->GetPathSeparator() + "memory.vhd"; FileWriter* memoryWriter = new FileWriter(memoryPath); if(memoryWriter->Exists()) { cout << "Deleting old generated VHDL memory code file from \"" << memoryWriter->GetPath() << "\"..." << endl; memoryWriter->Delete(); cout << "Deleted old generated VHDL memory code file from \"" << memoryWriter->GetPath() << "\"." << endl << endl; } cout << "Generating design's VHDL memory code and writing into output file \"" << memoryWriter->GetPath() << "\"..." << endl; string memoryCode = ""; memoryCode += GetLibrariesDeclaration() + "\n"; for(int i = 0; i < memories.size(); i++) { if(i == 0) { memoryCode += Cmp_block_ram::GetEntityDeclaration(memories[i], i); } else { memoryCode += "\n\n" + Cmp_block_ram::GetEntityDeclaration(memories[i], i); } } memoryWriter->WriteFile(memoryCode); cout << "Generated design's VHDL memory code and written into output file \"" << memoryWriter->GetPath() << "\"." << endl << endl; } } vector<Component*>* Synthesizer::GetComponents(Design* design) { vector<Component*>* components = new vector<Component*>(); for(ComponentIdentifier c : (*design->GetComponents())) { components->push_back(c.IdentifiedComponent); } return components; } //Executes the HLS using the CLang lib. //Example of how to use the library: https://gist.github.com/raphaelmor/3150866 int Synthesizer::Synthesize(int argc, char** argv) { vector<string> args = StringUtils::GetArgs(1, argv); if(argc == 2 && args.size() >= 2) { int designWidth = 32; if(args.size() >= 3 && stoi(args[2]) > 0) { designWidth = stoi(args[2]); } // Hardware design of the program Design* design = NodeVisitor::VisitAll(StringUtils::StringToChar(args[0]), designWidth); // Putting only the components on the vector vector<Component*>* componentArray = GetComponents(design); cout << endl << "---------Design (" << to_string(designWidth) << " bits) check---------" << endl; for(Component* c : (*componentArray)) { if(c->IsBlockRam()) { string values; for(int i = 0; i < c->AssignedConstants.size(); i++) { values += "\t" + c->AssignedConstants[i]; } if(c->AssignedConstants.size() > 0) { cout << "Declared ram component name: " << c->GetInstanceName() << "(" << c->GetComponentName() << " with values " << endl << values << ", maxSize: " << ((Cmp_block_ram*) c)->GetMaxSize() << ")" << endl; } else { cout << "Declared ram component name: " << c->GetInstanceName() << " (" << c->GetComponentName() << ", maxSize: " << ((Cmp_block_ram*) c)->GetMaxSize() << ")" << endl; } } else if(c->IsIoComponent()) { cout << "Declared component name: " << c->GetInstanceName() << " (" << c->GetComponentName() << " with value \"" << ((IOComponent*) c)->GetValue() << "\")" << endl; } else { cout << "Declared component name: " << c->GetInstanceName() << " (" << c->GetComponentName() << ")" << endl; } if(c->GetComponentName().compare("const_op") != 0) { for(Port* p : c->GetPorts()) { cout << (p->GetPortSignals().size() == 0 ? "\tPort: " + p->GetName() + ", Signal: No signal connected\n" : ""); for(Signal* s : p->GetPortSignals()) { cout << "\tPort: " << p->GetName() << ", Signal: " << s->GetSignalName() << endl; } } } } cout << "-----End of design (" << to_string(designWidth) << " bits) check------" << endl << endl; FileWriter* writer = new FileWriter(args[1]); design->SetName(writer->GetFileName(false)); if(writer->Exists()) { cout << "Deleting old generated VHDL code file from \"" << writer->GetPath() << "\"..." << endl; writer->Delete(); cout << "Deleted old generated VHDL code file from \"" << writer->GetPath() << "\"." << endl << endl; } vector<Cmp_block_ram*> memories; for(Component* c : (*componentArray)) { if(c->IsBlockRam()) { memories.push_back((Cmp_block_ram*) c); } } CreateMemoryFile(memories, writer); cout << "Generating design's VHDL code and writing into output file \"" << writer->GetPath() << "\"..." << endl; writer->WriteFile(GetDesignDeclaration(design)); cout << "Generated design's VHDL code and written into output file \"" << writer->GetPath() << "\"." << endl << endl; //Returns successful HLS result. cout << "Synthesis successfully executed." << endl << endl; return MessageLibrary::COMPILATION_SUCCESSFULL; } else { //Returns error HLS result. cerr << "Synthesis error \"ERROR_NOT_SPECIFIED_SOURCE\" (" << MessageLibrary::ERROR_NOT_SPECIFIED_SOURCE << ")." << endl; return MessageLibrary::ERROR_NOT_SPECIFIED_SOURCE; } }
e52bf819c7b9259a4ccecb9c362b05ab0411c022
7abbbef9590f9c4b9469adcbae5ea8907478bf03
/chromium_git/chromium/src/out/Debug/gen/blink/core/CSSValueKeywords.h
695a917403a4bce7d548dccf2d5de184f7e719b5
[ "BSD-3-Clause" ]
permissive
GiorgiGagnidze/CEF
845bdc2f54833254b3454ba8f6c61449431c7884
fbfc30b5d60f1ea7157da449e34dd9ba9c50f360
refs/heads/master
2021-01-10T17:32:27.640882
2016-03-23T07:43:04
2016-03-23T07:43:04
54,463,340
0
1
null
null
null
null
UTF-8
C++
false
false
24,091
h
CSSValueKeywords.h
// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CSSValueKeywords_h #define CSSValueKeywords_h #include "core/css/parser/CSSParserMode.h" #include <string.h> namespace blink { enum CSSValueID { CSSValueInvalid = 0, CSSValueInherit = 1, CSSValueInitial = 2, CSSValueNone = 3, CSSValueHidden = 4, CSSValueInset = 5, CSSValueGroove = 6, CSSValueOutset = 7, CSSValueRidge = 8, CSSValueDotted = 9, CSSValueDashed = 10, CSSValueSolid = 11, CSSValueDouble = 12, CSSValueCaption = 13, CSSValueIcon = 14, CSSValueMenu = 15, CSSValueMessageBox = 16, CSSValueSmallCaption = 17, CSSValueWebkitMiniControl = 18, CSSValueWebkitSmallControl = 19, CSSValueWebkitControl = 20, CSSValueStatusBar = 21, CSSValueItalic = 22, CSSValueOblique = 23, CSSValueAll = 24, CSSValueSmallCaps = 25, CSSValueCommonLigatures = 26, CSSValueNoCommonLigatures = 27, CSSValueDiscretionaryLigatures = 28, CSSValueNoDiscretionaryLigatures = 29, CSSValueHistoricalLigatures = 30, CSSValueNoHistoricalLigatures = 31, CSSValueContextual = 32, CSSValueNoContextual = 33, CSSValueNormal = 34, CSSValueBold = 35, CSSValueBolder = 36, CSSValueLighter = 37, CSSValue100 = 38, CSSValue200 = 39, CSSValue300 = 40, CSSValue400 = 41, CSSValue500 = 42, CSSValue600 = 43, CSSValue700 = 44, CSSValue800 = 45, CSSValue900 = 46, CSSValueUltraCondensed = 47, CSSValueExtraCondensed = 48, CSSValueCondensed = 49, CSSValueSemiCondensed = 50, CSSValueSemiExpanded = 51, CSSValueExpanded = 52, CSSValueExtraExpanded = 53, CSSValueUltraExpanded = 54, CSSValueXxSmall = 55, CSSValueXSmall = 56, CSSValueSmall = 57, CSSValueMedium = 58, CSSValueLarge = 59, CSSValueXLarge = 60, CSSValueXxLarge = 61, CSSValueWebkitXxxLarge = 62, CSSValueSmaller = 63, CSSValueLarger = 64, CSSValueSerif = 65, CSSValueSansSerif = 66, CSSValueCursive = 67, CSSValueFantasy = 68, CSSValueMonospace = 69, CSSValueWebkitBody = 70, CSSValueWebkitPictograph = 71, CSSValueSwap = 72, CSSValueFallback = 73, CSSValueOptional = 74, CSSValueAqua = 75, CSSValueBlack = 76, CSSValueBlue = 77, CSSValueFuchsia = 78, CSSValueGray = 79, CSSValueGreen = 80, CSSValueLime = 81, CSSValueMaroon = 82, CSSValueNavy = 83, CSSValueOlive = 84, CSSValueOrange = 85, CSSValuePurple = 86, CSSValueRed = 87, CSSValueSilver = 88, CSSValueTeal = 89, CSSValueWhite = 90, CSSValueYellow = 91, CSSValueTransparent = 92, CSSValueWebkitLink = 93, CSSValueWebkitActivelink = 94, CSSValueActiveborder = 95, CSSValueActivecaption = 96, CSSValueAppworkspace = 97, CSSValueBackground = 98, CSSValueButtonface = 99, CSSValueButtonhighlight = 100, CSSValueButtonshadow = 101, CSSValueButtontext = 102, CSSValueCaptiontext = 103, CSSValueGraytext = 104, CSSValueHighlight = 105, CSSValueHighlighttext = 106, CSSValueInactiveborder = 107, CSSValueInactivecaption = 108, CSSValueInactivecaptiontext = 109, CSSValueInfobackground = 110, CSSValueInfotext = 111, CSSValueMenutext = 112, CSSValueScrollbar = 113, CSSValueThreeddarkshadow = 114, CSSValueThreedface = 115, CSSValueThreedhighlight = 116, CSSValueThreedlightshadow = 117, CSSValueThreedshadow = 118, CSSValueWindow = 119, CSSValueWindowframe = 120, CSSValueWindowtext = 121, CSSValueInternalActiveListBoxSelection = 122, CSSValueInternalActiveListBoxSelectionText = 123, CSSValueInternalInactiveListBoxSelection = 124, CSSValueInternalInactiveListBoxSelectionText = 125, CSSValueWebkitFocusRingColor = 126, CSSValueCurrentcolor = 127, CSSValueGrey = 128, CSSValueWebkitText = 129, CSSValueRepeat = 130, CSSValueRepeatX = 131, CSSValueRepeatY = 132, CSSValueNoRepeat = 133, CSSValueClear = 134, CSSValueCopy = 135, CSSValueSourceOver = 136, CSSValueSourceIn = 137, CSSValueSourceOut = 138, CSSValueSourceAtop = 139, CSSValueDestinationOver = 140, CSSValueDestinationIn = 141, CSSValueDestinationOut = 142, CSSValueDestinationAtop = 143, CSSValueXor = 144, CSSValuePlusLighter = 145, CSSValueBaseline = 146, CSSValueMiddle = 147, CSSValueSub = 148, CSSValueSuper = 149, CSSValueTextTop = 150, CSSValueTextBottom = 151, CSSValueTop = 152, CSSValueBottom = 153, CSSValueWebkitBaselineMiddle = 154, CSSValueWebkitAuto = 155, CSSValueLeft = 156, CSSValueRight = 157, CSSValueCenter = 158, CSSValueJustify = 159, CSSValueWebkitLeft = 160, CSSValueWebkitRight = 161, CSSValueWebkitCenter = 162, CSSValueWebkitMatchParent = 163, CSSValueInterWord = 164, CSSValueDistribute = 165, CSSValueOutside = 166, CSSValueInside = 167, CSSValueDisc = 168, CSSValueCircle = 169, CSSValueSquare = 170, CSSValueDecimal = 171, CSSValueDecimalLeadingZero = 172, CSSValueArabicIndic = 173, CSSValueBengali = 174, CSSValueCambodian = 175, CSSValueKhmer = 176, CSSValueDevanagari = 177, CSSValueGujarati = 178, CSSValueGurmukhi = 179, CSSValueKannada = 180, CSSValueLao = 181, CSSValueMalayalam = 182, CSSValueMongolian = 183, CSSValueMyanmar = 184, CSSValueOriya = 185, CSSValuePersian = 186, CSSValueUrdu = 187, CSSValueTelugu = 188, CSSValueTibetan = 189, CSSValueThai = 190, CSSValueLowerRoman = 191, CSSValueUpperRoman = 192, CSSValueLowerGreek = 193, CSSValueLowerAlpha = 194, CSSValueLowerLatin = 195, CSSValueUpperAlpha = 196, CSSValueUpperLatin = 197, CSSValueCjkEarthlyBranch = 198, CSSValueCjkHeavenlyStem = 199, CSSValueEthiopicHalehame = 200, CSSValueEthiopicHalehameAm = 201, CSSValueEthiopicHalehameTiEr = 202, CSSValueEthiopicHalehameTiEt = 203, CSSValueHangul = 204, CSSValueHangulConsonant = 205, CSSValueKoreanHangulFormal = 206, CSSValueKoreanHanjaFormal = 207, CSSValueKoreanHanjaInformal = 208, CSSValueHebrew = 209, CSSValueArmenian = 210, CSSValueLowerArmenian = 211, CSSValueUpperArmenian = 212, CSSValueGeorgian = 213, CSSValueCjkIdeographic = 214, CSSValueSimpChineseFormal = 215, CSSValueSimpChineseInformal = 216, CSSValueTradChineseFormal = 217, CSSValueTradChineseInformal = 218, CSSValueHiragana = 219, CSSValueKatakana = 220, CSSValueHiraganaIroha = 221, CSSValueKatakanaIroha = 222, CSSValueInline = 223, CSSValueBlock = 224, CSSValueListItem = 225, CSSValueInlineBlock = 226, CSSValueTable = 227, CSSValueInlineTable = 228, CSSValueTableRowGroup = 229, CSSValueTableHeaderGroup = 230, CSSValueTableFooterGroup = 231, CSSValueTableRow = 232, CSSValueTableColumnGroup = 233, CSSValueTableColumn = 234, CSSValueTableCell = 235, CSSValueTableCaption = 236, CSSValueWebkitBox = 237, CSSValueWebkitInlineBox = 238, CSSValueFlex = 239, CSSValueInlineFlex = 240, CSSValueGrid = 241, CSSValueInlineGrid = 242, CSSValueWebkitFlex = 243, CSSValueWebkitInlineFlex = 244, CSSValueAuto = 245, CSSValueCrosshair = 246, CSSValueDefault = 247, CSSValuePointer = 248, CSSValueMove = 249, CSSValueVerticalText = 250, CSSValueCell = 251, CSSValueContextMenu = 252, CSSValueAlias = 253, CSSValueProgress = 254, CSSValueNoDrop = 255, CSSValueNotAllowed = 256, CSSValueZoomIn = 257, CSSValueZoomOut = 258, CSSValueEResize = 259, CSSValueNeResize = 260, CSSValueNwResize = 261, CSSValueNResize = 262, CSSValueSeResize = 263, CSSValueSwResize = 264, CSSValueSResize = 265, CSSValueWResize = 266, CSSValueEwResize = 267, CSSValueNsResize = 268, CSSValueNeswResize = 269, CSSValueNwseResize = 270, CSSValueColResize = 271, CSSValueRowResize = 272, CSSValueText = 273, CSSValueWait = 274, CSSValueHelp = 275, CSSValueAllScroll = 276, CSSValueWebkitGrab = 277, CSSValueWebkitGrabbing = 278, CSSValueWebkitZoomIn = 279, CSSValueWebkitZoomOut = 280, CSSValueLtr = 281, CSSValueRtl = 282, CSSValueCapitalize = 283, CSSValueUppercase = 284, CSSValueLowercase = 285, CSSValueVisible = 286, CSSValueCollapse = 287, CSSValueA3 = 288, CSSValueA4 = 289, CSSValueA5 = 290, CSSValueAbove = 291, CSSValueAbsolute = 292, CSSValueAlways = 293, CSSValueAvoid = 294, CSSValueB4 = 295, CSSValueB5 = 296, CSSValueBelow = 297, CSSValueBidiOverride = 298, CSSValueBlink = 299, CSSValueBoth = 300, CSSValueCloseQuote = 301, CSSValueEmbed = 302, CSSValueFixed = 303, CSSValueHand = 304, CSSValueHide = 305, CSSValueIsolate = 306, CSSValueIsolateOverride = 307, CSSValuePlaintext = 308, CSSValueWebkitIsolate = 309, CSSValueWebkitIsolateOverride = 310, CSSValueWebkitPlaintext = 311, CSSValueLandscape = 312, CSSValueLedger = 313, CSSValueLegal = 314, CSSValueLetter = 315, CSSValueLineThrough = 316, CSSValueLocal = 317, CSSValueNoCloseQuote = 318, CSSValueNoOpenQuote = 319, CSSValueNowrap = 320, CSSValueOpenQuote = 321, CSSValueOverlay = 322, CSSValueOverline = 323, CSSValuePortrait = 324, CSSValuePre = 325, CSSValuePreLine = 326, CSSValuePreWrap = 327, CSSValueRelative = 328, CSSValueScroll = 329, CSSValueSeparate = 330, CSSValueShow = 331, CSSValueStatic = 332, CSSValueThick = 333, CSSValueThin = 334, CSSValueUnderline = 335, CSSValueWavy = 336, CSSValueWebkitNowrap = 337, CSSValueStretch = 338, CSSValueStart = 339, CSSValueEnd = 340, CSSValueClone = 341, CSSValueSlice = 342, CSSValueReverse = 343, CSSValueHorizontal = 344, CSSValueVertical = 345, CSSValueInlineAxis = 346, CSSValueBlockAxis = 347, CSSValueSingle = 348, CSSValueMultiple = 349, CSSValueFlexStart = 350, CSSValueFlexEnd = 351, CSSValueSpaceBetween = 352, CSSValueSpaceAround = 353, CSSValueSpaceEvenly = 354, CSSValueUnsafe = 355, CSSValueSafe = 356, CSSValueRow = 357, CSSValueRowReverse = 358, CSSValueColumn = 359, CSSValueColumnReverse = 360, CSSValueWrap = 361, CSSValueWrapReverse = 362, CSSValueDense = 363, CSSValueReadOnly = 364, CSSValueReadWrite = 365, CSSValueReadWritePlaintextOnly = 366, CSSValueElement = 367, CSSValueWebkitMinContent = 368, CSSValueWebkitMaxContent = 369, CSSValueWebkitFillAvailable = 370, CSSValueWebkitFitContent = 371, CSSValueMinContent = 372, CSSValueMaxContent = 373, CSSValueFitContent = 374, CSSValueClip = 375, CSSValueEllipsis = 376, CSSValueDiscard = 377, CSSValueBreakAll = 378, CSSValueKeepAll = 379, CSSValueBreakWord = 380, CSSValueSpace = 381, CSSValueLoose = 382, CSSValueStrict = 383, CSSValueAfterWhiteSpace = 384, CSSValueCheckbox = 385, CSSValueRadio = 386, CSSValuePushButton = 387, CSSValueSquareButton = 388, CSSValueButton = 389, CSSValueButtonBevel = 390, CSSValueInnerSpinButton = 391, CSSValueListbox = 392, CSSValueListitem = 393, CSSValueMediaEnterFullscreenButton = 394, CSSValueMediaExitFullscreenButton = 395, CSSValueMediaFullscreenVolumeSlider = 396, CSSValueMediaFullscreenVolumeSliderThumb = 397, CSSValueMediaMuteButton = 398, CSSValueMediaPlayButton = 399, CSSValueMediaOverlayPlayButton = 400, CSSValueMediaToggleClosedCaptionsButton = 401, CSSValueMediaSlider = 402, CSSValueMediaSliderthumb = 403, CSSValueMediaVolumeSliderContainer = 404, CSSValueMediaVolumeSlider = 405, CSSValueMediaVolumeSliderthumb = 406, CSSValueMediaControlsBackground = 407, CSSValueMediaControlsFullscreenBackground = 408, CSSValueMediaCurrentTimeDisplay = 409, CSSValueMediaTimeRemainingDisplay = 410, CSSValueInternalMediaCastOffButton = 411, CSSValueInternalMediaOverlayCastOffButton = 412, CSSValueMenulist = 413, CSSValueMenulistButton = 414, CSSValueMenulistText = 415, CSSValueMenulistTextfield = 416, CSSValueMeter = 417, CSSValueProgressBar = 418, CSSValueProgressBarValue = 419, CSSValueSliderHorizontal = 420, CSSValueSliderVertical = 421, CSSValueSliderthumbHorizontal = 422, CSSValueSliderthumbVertical = 423, CSSValueCaret = 424, CSSValueSearchfield = 425, CSSValueSearchfieldDecoration = 426, CSSValueSearchfieldResultsDecoration = 427, CSSValueSearchfieldCancelButton = 428, CSSValueTextfield = 429, CSSValueRelevancyLevelIndicator = 430, CSSValueContinuousCapacityLevelIndicator = 431, CSSValueDiscreteCapacityLevelIndicator = 432, CSSValueRatingLevelIndicator = 433, CSSValueTextarea = 434, CSSValueCapsLockIndicator = 435, CSSValueRound = 436, CSSValueBorder = 437, CSSValueBorderBox = 438, CSSValueContent = 439, CSSValueContentBox = 440, CSSValuePadding = 441, CSSValuePaddingBox = 442, CSSValueMarginBox = 443, CSSValueContain = 444, CSSValueCover = 445, CSSValueLogical = 446, CSSValueVisual = 447, CSSValueAlternate = 448, CSSValueAlternateReverse = 449, CSSValueForwards = 450, CSSValueBackwards = 451, CSSValueInfinite = 452, CSSValueRunning = 453, CSSValuePaused = 454, CSSValueFlat = 455, CSSValuePreserve3d = 456, CSSValueEase = 457, CSSValueLinear = 458, CSSValueEaseIn = 459, CSSValueEaseOut = 460, CSSValueEaseInOut = 461, CSSValueStepStart = 462, CSSValueStepMiddle = 463, CSSValueStepEnd = 464, CSSValueSteps = 465, CSSValueCubicBezier = 466, CSSValueDocument = 467, CSSValueReset = 468, CSSValueZoom = 469, CSSValueVisiblePainted = 470, CSSValueVisibleFill = 471, CSSValueVisibleStroke = 472, CSSValuePainted = 473, CSSValueFill = 474, CSSValueStroke = 475, CSSValueBoundingBox = 476, CSSValueSpellOut = 477, CSSValueDigits = 478, CSSValueLiteralPunctuation = 479, CSSValueNoPunctuation = 480, CSSValueAntialiased = 481, CSSValueSubpixelAntialiased = 482, CSSValueOptimizeSpeed = 483, CSSValueOptimizeLegibility = 484, CSSValueGeometricPrecision = 485, CSSValueEconomy = 486, CSSValueExact = 487, CSSValueLr = 488, CSSValueRl = 489, CSSValueTb = 490, CSSValueLrTb = 491, CSSValueRlTb = 492, CSSValueTbRl = 493, CSSValueHorizontalTb = 494, CSSValueVerticalRl = 495, CSSValueVerticalLr = 496, CSSValueAfter = 497, CSSValueBefore = 498, CSSValueOver = 499, CSSValueUnder = 500, CSSValueFilled = 501, CSSValueOpen = 502, CSSValueDot = 503, CSSValueDoubleCircle = 504, CSSValueTriangle = 505, CSSValueSesame = 506, CSSValueEllipse = 507, CSSValueClosestSide = 508, CSSValueClosestCorner = 509, CSSValueFarthestSide = 510, CSSValueFarthestCorner = 511, CSSValueMixed = 512, CSSValueSideways = 513, CSSValueSidewaysRight = 514, CSSValueUpright = 515, CSSValueVerticalRight = 516, CSSValueOn = 517, CSSValueOff = 518, CSSValueOptimizeQuality = 519, CSSValuePixelated = 520, CSSValueWebkitOptimizeContrast = 521, CSSValueNonzero = 522, CSSValueEvenodd = 523, CSSValueAt = 524, CSSValueAlphabetic = 525, CSSValueFullscreen = 526, CSSValueStandalone = 527, CSSValueMinimalUi = 528, CSSValueBrowser = 529, CSSValueSticky = 530, CSSValueCoarse = 531, CSSValueFine = 532, CSSValueOnDemand = 533, CSSValueHover = 534, CSSValueMultiply = 535, CSSValueScreen = 536, CSSValueDarken = 537, CSSValueLighten = 538, CSSValueColorDodge = 539, CSSValueColorBurn = 540, CSSValueHardLight = 541, CSSValueSoftLight = 542, CSSValueDifference = 543, CSSValueExclusion = 544, CSSValueHue = 545, CSSValueSaturation = 546, CSSValueColor = 547, CSSValueLuminosity = 548, CSSValueScaleDown = 549, CSSValueBalance = 550, CSSValueWebkitPagedX = 551, CSSValueWebkitPagedY = 552, CSSValueDrag = 553, CSSValueNoDrag = 554, CSSValueSpan = 555, CSSValueMinmax = 556, CSSValueEachLine = 557, CSSValueProgressive = 558, CSSValueInterlace = 559, CSSValueMarkers = 560, CSSValueInternalExtendToZoom = 561, CSSValuePanX = 562, CSSValuePanY = 563, CSSValuePanLeft = 564, CSSValuePanRight = 565, CSSValuePanUp = 566, CSSValuePanDown = 567, CSSValueManipulation = 568, CSSValueLastBaseline = 569, CSSValueSelfStart = 570, CSSValueSelfEnd = 571, CSSValueLegacy = 572, CSSValueSmooth = 573, CSSValueContents = 574, CSSValueScrollPosition = 575, CSSValueRevert = 576, CSSValueUnset = 577, CSSValueLinearGradient = 578, CSSValueRadialGradient = 579, CSSValueRepeatingLinearGradient = 580, CSSValueRepeatingRadialGradient = 581, CSSValueWebkitCrossFade = 582, CSSValueWebkitGradient = 583, CSSValueWebkitLinearGradient = 584, CSSValueWebkitRadialGradient = 585, CSSValueWebkitRepeatingLinearGradient = 586, CSSValueWebkitRepeatingRadialGradient = 587, CSSValueWebkitImageSet = 588, CSSValueFrom = 589, CSSValueTo = 590, CSSValueColorStop = 591, CSSValueRadial = 592, CSSValueAttr = 593, CSSValueCounter = 594, CSSValueCounters = 595, CSSValueRect = 596, CSSValuePolygon = 597, CSSValueFormat = 598, CSSValueInvert = 599, CSSValueGrayscale = 600, CSSValueSepia = 601, CSSValueSaturate = 602, CSSValueHueRotate = 603, CSSValueOpacity = 604, CSSValueBrightness = 605, CSSValueContrast = 606, CSSValueBlur = 607, CSSValueDropShadow = 608, CSSValueUrl = 609, CSSValueRgb = 610, CSSValueRgba = 611, CSSValueHsl = 612, CSSValueHsla = 613, CSSValueMatrix = 614, CSSValueMatrix3d = 615, CSSValuePerspective = 616, CSSValueRotate = 617, CSSValueRotateX = 618, CSSValueRotateY = 619, CSSValueRotateZ = 620, CSSValueRotate3d = 621, CSSValueScale = 622, CSSValueScaleX = 623, CSSValueScaleY = 624, CSSValueScaleZ = 625, CSSValueScale3d = 626, CSSValueSkew = 627, CSSValueSkewX = 628, CSSValueSkewY = 629, CSSValueTranslate = 630, CSSValueTranslateX = 631, CSSValueTranslateY = 632, CSSValueTranslateZ = 633, CSSValueTranslate3d = 634, CSSValuePath = 635, CSSValueCalc = 636, CSSValueWebkitCalc = 637, CSSValueMandatory = 638, CSSValueProximity = 639, CSSValueFromImage = 640, CSSValuePaint = 641, CSSValueStyle = 642, CSSValueLayout = 643, CSSValueAutoFill = 644, CSSValueAutoFit = 645, CSSValueVar = 646, CSSValueInternalVariableValue = 647, CSSValueAliceblue = 648, CSSValueAntiquewhite = 649, CSSValueAquamarine = 650, CSSValueAzure = 651, CSSValueBeige = 652, CSSValueBisque = 653, CSSValueBlanchedalmond = 654, CSSValueBlueviolet = 655, CSSValueBrown = 656, CSSValueBurlywood = 657, CSSValueCadetblue = 658, CSSValueChartreuse = 659, CSSValueChocolate = 660, CSSValueCoral = 661, CSSValueCornflowerblue = 662, CSSValueCornsilk = 663, CSSValueCrimson = 664, CSSValueCyan = 665, CSSValueDarkblue = 666, CSSValueDarkcyan = 667, CSSValueDarkgoldenrod = 668, CSSValueDarkgray = 669, CSSValueDarkgreen = 670, CSSValueDarkgrey = 671, CSSValueDarkkhaki = 672, CSSValueDarkmagenta = 673, CSSValueDarkolivegreen = 674, CSSValueDarkorange = 675, CSSValueDarkorchid = 676, CSSValueDarkred = 677, CSSValueDarksalmon = 678, CSSValueDarkseagreen = 679, CSSValueDarkslateblue = 680, CSSValueDarkslategray = 681, CSSValueDarkslategrey = 682, CSSValueDarkturquoise = 683, CSSValueDarkviolet = 684, CSSValueDeeppink = 685, CSSValueDeepskyblue = 686, CSSValueDimgray = 687, CSSValueDimgrey = 688, CSSValueDodgerblue = 689, CSSValueFirebrick = 690, CSSValueFloralwhite = 691, CSSValueForestgreen = 692, CSSValueGainsboro = 693, CSSValueGhostwhite = 694, CSSValueGold = 695, CSSValueGoldenrod = 696, CSSValueGreenyellow = 697, CSSValueHoneydew = 698, CSSValueHotpink = 699, CSSValueIndianred = 700, CSSValueIndigo = 701, CSSValueIvory = 702, CSSValueKhaki = 703, CSSValueLavender = 704, CSSValueLavenderblush = 705, CSSValueLawngreen = 706, CSSValueLemonchiffon = 707, CSSValueLightblue = 708, CSSValueLightcoral = 709, CSSValueLightcyan = 710, CSSValueLightgoldenrodyellow = 711, CSSValueLightgray = 712, CSSValueLightgreen = 713, CSSValueLightgrey = 714, CSSValueLightpink = 715, CSSValueLightsalmon = 716, CSSValueLightseagreen = 717, CSSValueLightskyblue = 718, CSSValueLightslategray = 719, CSSValueLightslategrey = 720, CSSValueLightsteelblue = 721, CSSValueLightyellow = 722, CSSValueLimegreen = 723, CSSValueLinen = 724, CSSValueMagenta = 725, CSSValueMediumaquamarine = 726, CSSValueMediumblue = 727, CSSValueMediumorchid = 728, CSSValueMediumpurple = 729, CSSValueMediumseagreen = 730, CSSValueMediumslateblue = 731, CSSValueMediumspringgreen = 732, CSSValueMediumturquoise = 733, CSSValueMediumvioletred = 734, CSSValueMidnightblue = 735, CSSValueMintcream = 736, CSSValueMistyrose = 737, CSSValueMoccasin = 738, CSSValueNavajowhite = 739, CSSValueOldlace = 740, CSSValueOlivedrab = 741, CSSValueOrangered = 742, CSSValueOrchid = 743, CSSValuePalegoldenrod = 744, CSSValuePalegreen = 745, CSSValuePaleturquoise = 746, CSSValuePalevioletred = 747, CSSValuePapayawhip = 748, CSSValuePeachpuff = 749, CSSValuePeru = 750, CSSValuePink = 751, CSSValuePlum = 752, CSSValuePowderblue = 753, CSSValueRebeccapurple = 754, CSSValueRosybrown = 755, CSSValueRoyalblue = 756, CSSValueSaddlebrown = 757, CSSValueSalmon = 758, CSSValueSandybrown = 759, CSSValueSeagreen = 760, CSSValueSeashell = 761, CSSValueSienna = 762, CSSValueSkyblue = 763, CSSValueSlateblue = 764, CSSValueSlategray = 765, CSSValueSlategrey = 766, CSSValueSnow = 767, CSSValueSpringgreen = 768, CSSValueSteelblue = 769, CSSValueTan = 770, CSSValueThistle = 771, CSSValueTomato = 772, CSSValueTurquoise = 773, CSSValueViolet = 774, CSSValueWheat = 775, CSSValueWhitesmoke = 776, CSSValueYellowgreen = 777, CSSValueAlpha = 778, CSSValueLuminance = 779, CSSValueAccumulate = 780, CSSValueNew = 781, CSSValueSRGB = 782, CSSValueLinearRGB = 783, CSSValueCrispEdges = 784, CSSValueButt = 785, CSSValueMiter = 786, CSSValueBevel = 787, CSSValueBeforeEdge = 788, CSSValueAfterEdge = 789, CSSValueCentral = 790, CSSValueTextBeforeEdge = 791, CSSValueTextAfterEdge = 792, CSSValueIdeographic = 793, CSSValueHanging = 794, CSSValueMathematical = 795, CSSValueUseScript = 796, CSSValueNoChange = 797, CSSValueResetSize = 798, CSSValueDynamic = 799, CSSValueNonScalingStroke = 800, }; const int numCSSValueKeywords = 801; const size_t maxCSSValueKeywordLength = 42; const char* getValueName(CSSValueID); bool isValueAllowedInMode(unsigned short id, CSSParserMode mode); } // namespace blink #endif // CSSValueKeywords_h
030e8eccd09a0603dfe20e91ca7518813eb8b654
8693b0db0d593347757e3225a485eeb75e6861af
/lib/list.h
ef6cbb909f102448c93616f4af0dbb4eea2fbbeb
[]
no_license
abharga2/Inventory-Project
3722ab00dc1bf3d6da5dfc01bcdb9945868918dc
56dfaa0d473728afb3b1a57cddd28de047d8be80
refs/heads/master
2021-01-12T08:01:55.033349
2017-01-08T04:22:46
2017-01-08T04:22:46
77,101,866
0
0
null
null
null
null
UTF-8
C++
false
false
2,217
h
list.h
// Created by Abhishek Bhargava on 1/7/17. // Copyright © 2017 Abhishek Bhargava. All rights reserved. #include <iostream> #include <map> #include <cstring> #include <cstdlib> #include <cstddef> #include <cstdint> /*Doubly linked list interface*/ #ifndef _LIST_H #define _LIST_H /******************/ /*Client Interface*/ /******************/ using namespace std; typedef void *elem; typedef void list_elem_free_fn(elem x); typedef void print_elem_fn(elem x); typedef bool elem_equiv_fn(elem x, elem y); //To search for product using product id, generic function typedef template <class product_id> using product_id_equiv_fn = bool(elem x, product_id P); /*******************/ /*Library Interface*/ /*******************/ typedef struct list_node *node_t; typedef struct list_header *list_t; //Add to top of linked list void add_top(list_t L, node_t N); //Add to bottom (end) of linked list void add_bottom(list_t L, node_t N); //Default: add to top of list void add(list_t L, node_t N); //Default: remove from top of list elem remove(list_t L); //Remove from top of list elem remove_top(list_t L); //Remove from bottom of list elem remove_bottom(list_t L); //Get new, empty list list_t new_list(list_elem_free_fn *F, print_elem_fn *P, elem_equiv_fn *E); //Get new list whose first node contains elem E list_t new_list(elem E, list_elem_free_fn *F, print_elem_fn *P, elem_equiv_fn *G); //Get new list whose first node is N list_t new_list(node_t N, list_elem_free_fn *F, print_elem_fn *P, elem_equiv_fn *E); //Get new node whose data field is E node_t new_node(elem E); /*Additional functions*/ //True if the list is empty, false otherwise bool is_empty(list_t L); //Print elements of list from top to bottom void print_list(list_t L); //Free list void free_list(list_t L); //Set free function void set_free_fn(list_t L, list_elem_free_fn *F); //Returns number of nodes in list size_t get_size(list_t L); //Lookup to see if elem is in list bool is_in_list(list_t L, elem x); //Lookup with product id template <typename product_id> elem is_id_in_list(list_t L, product_id P, product_id_equiv_fn<product_id> *func); //Remove element from list elem remove_elem(list_t L, elem x); #endif
f88587db67c5ed2d41ef92b63fe8d09d73e5f7b8
e343256bfdb60efd3237b0556fd20e3905f8be21
/include/reports.hpp
5a11588f1b894dbf265ecde170908dd5c1ede386
[]
no_license
wacus99/network_sim
568843caf265f155cf6dbf4c42f238923241e17b
a1212a65f97faa26c98cf4876b610f17b14f8da2
refs/heads/main
2023-01-30T01:52:27.611400
2020-12-15T19:21:46
2020-12-15T19:21:46
321,762,378
0
0
null
null
null
null
UTF-8
C++
false
false
271
hpp
reports.hpp
#ifndef NETWORK_SIM_REPORTS_HPP #define NETWORK_SIM_REPORTS_HPP #include "types.hpp" /* klasy IReportNotifier, SpecificTurnsReportNotifier, IntervalReportNotifier funkcje generate_structure_report(), generate_simulation_turn_report() */ #endif //NETWORK_SIM_REPORTS_HPP
bbcf03196b31a80c263294d9972658054e564c39
c16963879c47148ec2e6f5a524dc90562075e56d
/monitorBuddyUSB/monitorBuddy.ino
9f9c21ff9a44be9444feddf508196e0decf5b732
[]
no_license
kraftboy/monitorBuddy
5e0837d5f7511bf7ad355e98e3c98a62c0da386e
98b1f227d73b3c2a7e46163282eb13508e342267
refs/heads/main
2023-03-09T01:55:32.008524
2021-02-08T01:15:30
2021-02-08T01:15:30
326,261,816
0
0
null
null
null
null
UTF-8
C++
false
false
312
ino
monitorBuddy.ino
/* Name: monitorBuddy.ino Created: 12/23/2020 7:51:59 PM Author: glocal */ #include <avr/io.h> #include <avr/interrupt.h> #include <avr/wdt.h> #include "MonitorBuddyApp.h" MonitorBuddyApp myMonitorBuddy; void setup() { cli(); myMonitorBuddy.init(); } void loop() { myMonitorBuddy.update(); }
2587680beb7b5cd60b39bf4fd4ddda54e2feaef4
826c2762805e39ac1c080091e7f4f642fb41e19a
/ouniverse_2020_ue4_source_multiplayer_whitebox/App/Game/Include/CompanionRemote.h
5dd4137c6032d0da0cbc56c80046c861de749d4e
[]
no_license
legendofceo/ouniverse_ue_cpp_source_deprecated_pre2022
fe625f69210c9c038202b8305495bdf373657ea8
729f12569f805ce74e602f8b13bab0ac318358a5
refs/heads/main
2023-08-12T19:14:39.216646
2021-10-17T16:19:29
2021-10-17T16:19:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
537
h
CompanionRemote.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Remote.h" #include "CompanionRemote.generated.h" class AAppController; class UPartyMemberHandle; UCLASS(BlueprintType, Blueprintable) class APP_API UCompanionRemote : public URemote { GENERATED_BODY() static const FName SYS; public: // Sets default values for this component's properties UCompanionRemote(); void Init(AAppController* AP); void Engage(UPartyMemberHandle* PartyMemberHandle); };
a015eca869ad9164d3e7aae24bb163ccf30646db
72e101109c8134d553d1404364d4e4d44ee52ed8
/Code/source/main.cpp
c383027e4806ff0081d8a4ad3e88220b16afa2a2
[]
no_license
hippogyz/opengl_project
be6def547c392f0258db4d5fa04f772e10f3e906
14f1acab15294e283c53e4ac3f3b1e1c70bb5690
refs/heads/master
2023-06-03T17:15:17.519736
2021-06-23T06:48:52
2021-06-23T06:48:52
345,647,027
0
0
null
null
null
null
UTF-8
C++
false
false
19,328
cpp
main.cpp
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <memory> #include "stb_image.h" #include "Shader.h" #include "TextureManager.h" #include "Camera.h" #include "Light.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Game.h" #include "GameObject.h" #include "Component.h" #include "Component/TransformComponent.h" #include "RenderManager.h" #include "Model.h" void framebuffer_size_callback(GLFWwindow* window, int width, int height); void cursor_move_callback(GLFWwindow* window, double cursor_x, double cursor_y); void processInput(GLFWwindow* window); void clearBuffer(GLenum config); unsigned int loadTextureFromPath(Shader shader, unsigned int texture_order, const char* texture_path); // has been replaced by class TextureManager // settings const unsigned int SCR_WIDTH = 600; const unsigned int SCR_HEIGHT = 600; // global variable // time float delta_time = 0.0f; float process_time = 0.0f; float real_time = 0.0f; // cursor bool first_cursor = true; double cursor_last_x = 0.0; double cursor_last_y = 0.0; // camera Camera camera(glm::vec3(0.0f, 0.0f, 3.0f)); #define TEST_MODE int main() { #ifdef TEST_MODE Game::access().execute(); #else // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "MyOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, cursor_move_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // fix cursor for First Personal Sight // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } //use Shader class Shader shaderProg; shaderProg.initializeShaderVF("opengl_project/Code/shader/vertex_shader.vs", "opengl_project/Code/shader/frag_shader.fs"); Shader refShaderProg; refShaderProg.initializeShaderVF("opengl_project/Code/shader/vertex_shader.vs", "opengl_project/Code/shader/ref_frag_shader.fs"); // load texture // -------------- //unsigned int texture = loadTextureFromPath(shaderProg, 0, "Resource/test_texture.jpg"); const char* texture_path[] = { "opengl_project/Resource/test_texture.jpg", "opengl_project/Resource/test_texture2.jpg", "opengl_project/Resource/test_texture3.jpg", "opengl_project/Resource/test_specular_texture.jpg" }; float material_ambient = 0.1; float material_shininess = 256.0; TextureManager texture_manager; texture_manager.loadJPGsFromPath(4, texture_path); // fragment uniform (for lighting material) shaderProg.useShader(); shaderProg.setInt("material.default_texture", 0); shaderProg.setInt("material.specular_texture", 1); shaderProg.setFloat("material.ambient", material_ambient); shaderProg.setFloat("material.shininess", material_shininess); //texture_manager.setShaderForTexture(&shaderProg); // lighting const int point_light_num = 4; glm::vec3 light_position[point_light_num] = { glm::vec3(5.0, 2.0, 1.0), glm::vec3(-2.0, 3.0, -10.0), glm::vec3(4.0, -9.0, 2.0), glm::vec3(-10.0, 2.0, -3.0) }; PointLight point_light[point_light_num] = { PointLight(true, glm::vec3(0.7), glm::vec3(1.0), light_position[0]), PointLight(true, glm::vec3(0.7), glm::vec3(1.0), light_position[1]), PointLight(true, glm::vec3(0.7), glm::vec3(1.0), light_position[2]), PointLight(true, glm::vec3(0.7), glm::vec3(1.0), light_position[3]) }; DirLight dir_light = DirLight(true, glm::vec3(0.3), glm::vec3(0.5), glm::vec3(1.0, 1.0, -1.0) ); glm::vec3 spot_light_position = glm::vec3(3.0); glm::vec3 spot_light_direction = glm::vec3(-1.0); SpotLight spot_light = SpotLight(true, glm::vec3(0.7), glm::vec3(1.0), spot_light_position, spot_light_direction); // enable light for (int i = 0; i < point_light_num; ++i) { std::string pl_name = std::string("point_light[") + char(i + int('0')) + "]"; point_light[i].setLight(shaderProg, pl_name.c_str()); } dir_light.setLight(shaderProg, "dir_light"); spot_light.setLight(shaderProg, "spot_light"); // enable depth test // ------------------ glEnable(GL_DEPTH_TEST); // load vertex array // -------------- float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0, 0.0, -1.0, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0, 0.0, -1.0, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0, 0.0, -1.0, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0, 0.0, -1.0, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0, 0.0, 1.0, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0, 0.0, 1.0, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0, 0.0, 1.0, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0, 0.0, 1.0, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0, 0.0, 0.0, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0, 0.0, 0.0, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0, 0.0, 0.0, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0, 0.0, 0.0, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0, 0.0, 0.0, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0, 0.0, 0.0, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0, 0.0, 0.0, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0, 0.0, 0.0, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0, -1.0, 0.0, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0, -1.0, 0.0, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0, -1.0, 0.0, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0, -1.0, 0.0, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0, 1.0, 0.0, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0, 1.0, 0.0, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0, 1.0, 0.0, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0, 1.0, 0.0, 0.0f, 0.0f }; unsigned int indices[] = { 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23 }; glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; unsigned int VAO,VBO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // bind VAO glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); // render loop // ----------- real_time = glfwGetTime(); while (!glfwWindowShouldClose(window)) { // update time float pre_time = real_time; real_time = glfwGetTime(); delta_time = (real_time - pre_time < 0.05f) ? real_time - pre_time : 0.05f; process_time += delta_time; // input processInput(window); double mouse_position[2] = { cursor_last_x, cursor_last_y }; int window_size[2]; glfwGetWindowSize(window, &(window_size[0]), &(window_size[1])); glm::mat4 model = glm::mat4(1.0f); glm::mat4 norm_mat = glm::mat4(1.0f); glm::mat4 view = glm::mat4(1.0f); glm::mat4 projection = glm::mat4(1.0f); model = glm::rotate(model, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(process_time * 50.0f), glm::vec3(0.5f, 1.0f, 0.0f)); norm_mat = glm::transpose(glm::inverse(model)); view = camera.getViewMat(); projection = glm::perspective(glm::radians(45.0f), float(window_size[0]) / float(window_size[1]), 0.1f, 100.0f); glm::vec3 camera_position = camera.getPosition(); // render part clearBuffer(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderProg.useShader(); // vertex uniform shaderProg.setTrans("model", model); shaderProg.setTrans("norm_mat", norm_mat); shaderProg.setTrans("view", view); shaderProg.setTrans("projection", projection); // fragment uniform shaderProg.setFloat("u_time", process_time); shaderProg.setFloat("u_mouse", float(mouse_position[0]), float(window_size[1]) - float(mouse_position[1])); shaderProg.setFloat("u_resolution", float(window_size[0]), float(window_size[1])); shaderProg.setFloat("camera_position", camera_position.x, camera_position.y, camera_position.z); //texture_manager.activeTextures(); //glActiveTexture(GL_TEXTURE0); //glBindTexture(GL_TEXTURE_2D, texture); glBindVertexArray(VAO); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); for (int i = 0; i < 10; ++i) { glm::mat4 model2 = glm::mat4(1.0f); glm::mat4 norm_mat2 = glm::mat4(1.0f); model2 = glm::translate(model2, cubePositions[i]); model2 = glm::rotate(model2, glm::radians(20.0f * i), glm::vec3(1.0f, 0.3f, 0.5f)); model2 = glm::rotate(model2, glm::radians(process_time * 5.0f * i), glm::vec3(0.5f, 1.0f, 0.0f)); norm_mat2 = glm::transpose(glm::inverse(model2)); shaderProg.setTrans("model", model2); shaderProg.setTrans("norm_mat", norm_mat2); texture_manager.activeSingleTexture(1, 3); texture_manager.activeSingleTexture(0, 0); glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, (void*)0); texture_manager.activeSingleTexture(0, 1); glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, (void*)(12 * sizeof(unsigned int))); texture_manager.activeSingleTexture(0, 2); glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, (void*)(24 * sizeof(unsigned int))); } // draw light source refShaderProg.useShader(); refShaderProg.setTrans("view", view); refShaderProg.setTrans("projection", projection); refShaderProg.setFloat("u_time", process_time); refShaderProg.setFloat("u_mouse", float(mouse_position[0]), float(window_size[1]) - float(mouse_position[1])); refShaderProg.setFloat("u_resolution", float(window_size[0]), float(window_size[1])); for (int i = 0; i < point_light_num; ++i) { if (point_light[i].is_active) { glm::mat4 ref_model = glm::mat4(1.0f); glm::mat4 ref_norm_mat = glm::mat4(1.0f); ref_model = glm::translate(ref_model, glm::vec3(light_position[i].x, light_position[i].y, light_position[i].z)); ref_model = glm::scale(ref_model, glm::vec3(0.3)); ref_norm_mat = glm::transpose(glm::inverse(ref_model)); refShaderProg.useShader(); refShaderProg.setTrans("model", ref_model); refShaderProg.setTrans("norm_mat", ref_norm_mat); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, (void*)0); } } if (spot_light.is_active) { glm::mat4 ref_spot_model = glm::mat4(1.0f); glm::mat4 ref_spot_norm_mat = glm::mat4(1.0f); ref_spot_model = glm::translate(ref_spot_model, glm::vec3(spot_light_position.x, spot_light_position.y, spot_light_position.z)); ref_spot_model = glm::scale(ref_spot_model, glm::vec3(0.4)); ref_spot_norm_mat = glm::transpose(glm::inverse(ref_spot_model)); refShaderProg.useShader(); refShaderProg.setTrans("model", ref_spot_model); refShaderProg.setTrans("norm_mat", ref_spot_norm_mat); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, (void*)0); for (int i = 0; i < 5; ++i) { glm::mat4 ref_model = glm::mat4(1.0f); glm::mat4 ref_norm_mat = glm::mat4(1.0f); glm::vec3 spot_dir = spot_light_position + glm::normalize(spot_light_direction) * float(0.1f * i + 0.4f); ref_model = glm::translate(ref_model, glm::vec3(spot_dir.x, spot_dir.y, spot_dir.z)); ref_model = glm::scale(ref_model, glm::vec3(0.2)); ref_norm_mat = glm::transpose(glm::inverse(ref_model)); refShaderProg.useShader(); refShaderProg.setTrans("model", ref_model); refShaderProg.setTrans("norm_mat", ref_norm_mat); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, (void*)0); } } //glDrawArrays(GL_TRIANGLES, 0, 3); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glfwTerminate(); #endif // test mode return 0; } //--------------------------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------------------------- // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.moveCamera(delta_time, MOVE_FORWARD); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.moveCamera(delta_time, MOVE_BACKWARD); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.moveCamera(delta_time, MOVE_RIGHT); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.moveCamera(delta_time, MOVE_LEFT); } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } void cursor_move_callback(GLFWwindow* window, double cursor_x, double cursor_y) { if (first_cursor) { cursor_last_x = cursor_x; cursor_last_y = cursor_y; first_cursor = false; } camera.rotateCamera(delta_time, float(cursor_last_x - cursor_x ), float(cursor_last_y - cursor_y)); cursor_last_x = cursor_x; cursor_last_y = cursor_y; } void clearBuffer(GLenum config) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(config); } unsigned int loadTextureFromPath(Shader shader, unsigned int texture_order, const char* texture_path) { unsigned int texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); int texture_width, texture_height, texture_nrChannels; stbi_set_flip_vertically_on_load(true); unsigned char* texture_data = stbi_load(texture_path, &texture_width, &texture_height, &texture_nrChannels, 0); if (texture_data) { //std::cout << strlen((char*)(texture_data)) << std::endl; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture_width, texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture_data); glGenerateMipmap(GL_TEXTURE_2D); } else { printf(" --- loadTextureFromPath(): failed to load texture at path: %s --- \n", texture_path); } stbi_image_free(texture_data); shader.useShader(); char uni_name[] = "texture0"; uni_name[7] = char(texture_order + 48); // change the index with texture_order shader.setInt(uni_name, texture_order); return texture; }
831ff458f42c33662b67118159166d95e852448d
ebe1c6c28f879a9a85b1254db3a0090a52a7db1f
/printer.cpp
66707daaf925fe9ae5eb57f10217979a36a9ca37
[]
no_license
robinei/old_slang
33d79dbae74abb7802aac9e6438a4ad92cde6f54
250b17f26b190f77f8642bd1ccd57a5378042f56
refs/heads/master
2021-06-10T03:21:34.718459
2016-10-19T00:39:54
2016-10-19T00:39:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,047
cpp
printer.cpp
class Printer { public: Printer(Context *ctx) : ctx(ctx), module(ctx->module) {} void print(Any *form) { last_line = 0; print_form(form); } private: Context *ctx; Module *module; u32 last_line; void print_form(Any *form) { switch (form->type->type) { case TYPE_SYMBOL: { Ptr<Symbol> sym(form); printf("%s", sym->data); break; } case TYPE_STRING: { Ptr<String> str(form); // TODO: escape the output printf("\"%s\"", str->data); break; } case TYPE_CONS: { printf("("); while (form != &NIL) { Ptr<Cons> cons(form); // try to preserve whitespace when printing forms that were read // (for which we remember the locations of the car forms of all conses) SourceLoc loc; if (module->locations.get(cons, loc)) { if (last_line < loc.line) { do { printf("\n"); ++last_line; } while (last_line < loc.line); for (u32 i = 0; i < loc.col; ++i) { printf(" "); } } } print_form(cons->car); form = cons->cdr; if (form != &NIL) { printf(" "); } } printf(")"); break; } case TYPE_BOOL: if (form == &TRUE) { printf("#t"); } else { printf("#f"); } break; case TYPE_I8: { Ptr<i8> num(form); printf("%d", (i32)*num); break; } case TYPE_I16: { Ptr<i16> num(form); printf("%d", (i32)*num); break; } case TYPE_I32: { Ptr<i32> num(form); printf("%d", (i32)*num); break; } case TYPE_I64: { Ptr<i64> num(form); printf("%lld", (long long)*num); break; } case TYPE_U8: { Ptr<u8> num(form); printf("%u", (u32)*num); break; } case TYPE_U16: { Ptr<u16> num(form); printf("%u", (u32)*num); break; } case TYPE_U32: { Ptr<u32> num(form); printf("%u", (u32)*num); break; } case TYPE_U64: { Ptr<u64> num(form); printf("%llu", (unsigned long long)*num); break; } case TYPE_F32: { Ptr<f32> num(form); printf("%f", (f64)*num); break; } case TYPE_F64: { Ptr<f64> num(form); printf("%f", (f64)*num); break; } } } };
2913d5aaf0c759433963d250d3c313d814a14782
c2338617a02efa35d9b5154ac99fa97bbf739ec1
/lib/tt_hander.cc
6257f48da4fb82b5a67afd5defa5b71e849efb1b
[]
no_license
luguocfw/TaskTop
84f001e60d753e72774e122d308122944ca7fd20
89f493cd5529c85a76ba044907cdcdb77e36259c
refs/heads/master
2021-07-06T18:45:31.033570
2020-08-07T08:13:03
2020-08-07T08:13:03
157,182,739
0
0
null
null
null
null
UTF-8
C++
false
false
10,842
cc
tt_hander.cc
/* * * author: ChenFawang * tt_hander.cc * 2018 - 11 - 12 * mail: cfwang_9984@163.com * */ #include "tt_hander.h" #include "tt_log.h" #include "tt_global.h" #include "tt_path.h" #include <fstream> #include <sstream> namespace task_top { TaskTopHandler::TaskTopHandler(const std::list<int>& pids) { pids_ = pids; sys_stat_.idle = -1; apps_stat_.clear(); } TaskTopHandler::TaskTopHandler(const int * pids, int pid_count) { pids_.clear(); int i; for (i = 0; i < pid_count; i++) { pids_.push_back(pids[i]); } sys_stat_.idle = -1; apps_stat_.clear(); } TaskTopHandler::~TaskTopHandler() { } void TaskTopHandler::GetCpuInfo(std::list<AppCpuInfoAll>& infos, SystemCpuInfo & sys_info) { SystemStatData cur_sys_stat; std::list<AppStatAll> cur_app_stat; infos.clear(); memset(&sys_info, 0, sizeof(SystemCpuInfo)); if (pids_.size() <= 0) { return; } cur_app_stat.clear(); GetAllStat(cur_sys_stat, cur_app_stat, pids_); GetAllCpu(infos, sys_info, cur_sys_stat, cur_app_stat); } bool TaskTopHandler::GetAllStat(SystemStatData & sys_stat, std::list<AppStatAll>& apps_stat, std::list<int> &pids) { int ret; memset(&sys_stat, 0, sizeof(SystemStatData)); apps_stat.clear(); std::string sys_stat_str; std::ifstream system_stat_ifs; std::list<AppStatStrAll> apps_stat_str; if (!OpenAllStatFile(pids, system_stat_ifs, apps_stat_str)) { return false; } if (!GetAllStatString(sys_stat_str, system_stat_ifs, apps_stat_str)) { CloseAllStatFile(system_stat_ifs, apps_stat_str); return false; } CloseAllStatFile(system_stat_ifs, apps_stat_str); ret = task_top::SystemStatResolv::Resolv(sys_stat_str, sys_stat); if (ret != 0) { LogError("resolv system stat string failed\n"); return false; } for (auto app = apps_stat_str.begin(); app != apps_stat_str.end(); app++) { AppStatAll app_stat; app_stat.pid = app->pid; ret = task_top::AppAndTaskStatResolv::Resolv(app->stat_str, app_stat.app_stat); if (ret != 0) { LogError("resolv app(pid:%d) stat string failed:%d\n",app->pid, ret); continue; } app_stat.tasks_stat.clear(); for (auto task = app->thrs_stat.begin(); task != app->thrs_stat.end(); task++) { AppAndTaskStatData task_stat_data; ret = task_top::AppAndTaskStatResolv::Resolv(task->stat_str, task_stat_data); if (ret != 0) { LogError("resolv app(pid:%d) thread(tid:%d) stat string failed:%d\n", app->pid, task->tid, ret); continue; } TaskStat task_stat; task_stat.tid = task->tid; memcpy(&task_stat.stat, &task_stat_data, sizeof(AppAndTaskStatData)); app_stat.tasks_stat.push_back(task_stat); } if (app_stat.tasks_stat.size() > 0) { apps_stat.push_back(app_stat); } } if (apps_stat.size() <= 0) { return false; } return true; } void TaskTopHandler::GetAllCpu(std::list<AppCpuInfoAll>& infos_out, SystemCpuInfo & sys_info_out, SystemStatData & sys_stat_in, std::list<AppStatAll>& apps_stat_in) { infos_out.clear(); int total_diff = 1; if (sys_stat_.idle == -1) { memset(&sys_info_out, 0, sizeof(SystemCpuInfo)); memcpy(&sys_stat_, &sys_stat_in, sizeof(SystemStatData)); return; } else { total_diff = sys_stat_in.total - sys_stat_.total; if (total_diff == 0) { memset(&sys_info_out, 0, sizeof(SystemCpuInfo)); memcpy(&sys_stat_, &sys_stat_in, sizeof(SystemStatData)); return; } else { sys_info_out.idle_ = ((sys_stat_in.idle - sys_stat_.idle) * 1.0) / total_diff; sys_info_out.io_ = ((sys_stat_in.io - sys_stat_.io) * 1.0) / total_diff; sys_info_out.irq_ = ((sys_stat_in.irq - sys_stat_.irq) * 1.0) / total_diff; sys_info_out.nic_ = ((sys_stat_in.nice - sys_stat_.nice) * 1.0) / total_diff; sys_info_out.sirq_ = ((sys_stat_in.sirq - sys_stat_.sirq) * 1.0) / total_diff; sys_info_out.sys_ = ((sys_stat_in.sys - sys_stat_.sys) * 1.0) / total_diff; sys_info_out.user_ = ((sys_stat_in.user - sys_stat_.user) * 1.0) / total_diff; } } memcpy(&sys_stat_, &sys_stat_in, sizeof(SystemStatData)); for (auto app = apps_stat_in.begin(); app != apps_stat_in.end(); app++) { AppCpuInfoAll app_cpu_info; app_cpu_info.pid = app->pid; GetAppCpuInfo(app->pid, app->app_stat, total_diff, app_cpu_info.app_cpu); app_cpu_info.name = task_top::AppTaskScan::GetAppName(app->pid); app_cpu_info.task.clear(); for (auto task = app->tasks_stat.begin(); task != app->tasks_stat.end(); task++) { TaskInfo task_cpu_info; task_cpu_info.tid = task->tid; GetTaskCpuInfo(app->pid, task->tid, task->stat, total_diff, task_cpu_info.cpu); task_cpu_info.name = task_top::AppTaskScan::GetThrName(app->pid, task->tid); app_cpu_info.task.push_back(task_cpu_info); } infos_out.push_back(app_cpu_info); } apps_stat_.clear(); apps_stat_ = apps_stat_in; } bool TaskTopHandler::OpenAllStatFile(std::list<int>& pids, std::ifstream & sys_stat_ifs, std::list<AppStatStrAll>& apps_stat_str) { sys_stat_ifs.open(task_top::global::g_system_stat_path_, std::ios::in); if (!sys_stat_ifs.is_open()) { return false; } int ret; apps_stat_str.clear(); for (auto pid = pids.begin(); pid != pids.end();) { AppStatStrAll app_stat_str; app_stat_str.pid = *pid; Path path(task_top::global::g_system_proc_path_); path.AppendFolder(task_top::to_string(app_stat_str.pid)); path.SetFile(task_top::global::g_stat_filename_); app_stat_str.ifs = new std::ifstream(); app_stat_str.ifs->open(path.Pathname(), std::ios::in); if (!app_stat_str.ifs->is_open()) { LogError("open stat file:%s failed\n", path.Pathname().c_str()); delete app_stat_str.ifs; pid = pids.erase(pid); continue; } std::list<int> tids; ret = task_top::AppTaskScan::GetTids(*pid, tids); if (ret != 0) { LogError("get tids for pid:%d failed:%d\n", *pid, ret); pid = pids.erase(pid); continue; } for (auto tid = tids.begin(); tid != tids.end(); tid++) { TaskStatStr task_stat; task_stat.tid = *tid; Path tid_path(task_top::global::g_system_proc_path_); tid_path.AppendFolder(task_top::to_string(app_stat_str.pid)); tid_path.AppendFolder(task_top::global::g_task_folder_); tid_path.AppendFolder(task_top::to_string(task_stat.tid)); tid_path.SetFile(task_top::global::g_stat_filename_); task_stat.ifs = new std::ifstream(); task_stat.ifs->open(tid_path.Pathname(), std::ios::in); if (!task_stat.ifs->is_open()) { LogError("open tid stat file %s failed\n", tid_path.Pathname().c_str()); delete task_stat.ifs; continue; } app_stat_str.thrs_stat.push_back(task_stat); } if (app_stat_str.thrs_stat.size() == 0) { delete app_stat_str.ifs; pid = pids.erase(pid); continue; } apps_stat_str.push_back(app_stat_str); pid++; } if (apps_stat_str.size() == 0) { sys_stat_ifs.close(); return false; } return true; } bool TaskTopHandler::GetAllStatString(std::string & sys_stat_str, std::ifstream & sys_stat_ifs, std::list<AppStatStrAll>& apps_stat_str) { if (!GetSystemStatString(sys_stat_ifs, sys_stat_str)) { return false; } for (auto app = apps_stat_str.begin(); app != apps_stat_str.end();) { if (!GetOneAppOrTaskStatString(*app->ifs, app->stat_str)) { app->ifs->close(); delete app->ifs; app = apps_stat_str.erase(app); continue; } for (auto thread = app->thrs_stat.begin(); thread != app->thrs_stat.end();) { if (!GetOneAppOrTaskStatString(*thread->ifs, thread->stat_str)) { thread->ifs->close(); delete thread->ifs; thread = app->thrs_stat.erase(thread); continue; } thread++; } if (app->thrs_stat.size() == 0) { app->ifs->close(); delete app->ifs; app = apps_stat_str.erase(app); continue; } app++; } if (apps_stat_str.size() == 0) { return false; } return true; } void TaskTopHandler::CloseAllStatFile(std::ifstream & sys_stat_ifs, std::list<AppStatStrAll>& apps_stat_str) { sys_stat_ifs.close(); for (auto app = apps_stat_str.begin(); app != apps_stat_str.end(); app++) { app->ifs->close(); delete app->ifs; for (auto tid = app->thrs_stat.begin(); tid != app->thrs_stat.end(); tid++) { tid->ifs->close(); delete tid->ifs; } } } bool TaskTopHandler::GetSystemStatString(std::ifstream &ifs,std::string & stat_data) { if (!std::getline(ifs, stat_data)) { LogError("get file %s one line string failed\n", task_top::global::g_system_proc_path_.c_str()); return false; } return true; } bool TaskTopHandler::GetOneAppOrTaskStatString(std::ifstream &ifs, std::string & stat_data) { if (!std::getline(ifs, stat_data)) { return false; } return true; } bool TaskTopHandler::GetOldAppStatData(int pid, AppAndTaskStatData & old_stat) { for (auto app = apps_stat_.begin(); app != apps_stat_.end(); app++) { if (app->pid == pid) { memcpy(&old_stat, &app->app_stat, sizeof(AppAndTaskStatData)); return true; } } return false; } bool TaskTopHandler::GetOldTaskStatData(int pid, int tid, AppAndTaskStatData & old_stat) { for (auto app = apps_stat_.begin(); app != apps_stat_.end(); app++) { if (app->pid == pid) { for (auto task = app->tasks_stat.begin(); task != app->tasks_stat.end(); task++) { if (task->tid == tid) { memcpy(&old_stat, &task->stat, sizeof(AppAndTaskStatData)); return true; } } } } return false; } void TaskTopHandler::GetAppCpuInfo(int pid, AppAndTaskStatData & cur_stat_data, int total_diff, AppAndTaskCpuInfo & cpu_info) { AppAndTaskStatData old_stat; if (!GetOldAppStatData(pid, old_stat)) { memset(&cpu_info, 0, sizeof(AppAndTaskCpuInfo)); } else { cpu_info.cstime = ((cur_stat_data.cstime - old_stat.cstime)*1.0) / total_diff; cpu_info.cutime = ((cur_stat_data.cutime - old_stat.cutime)*1.0) / total_diff; cpu_info.stime = ((cur_stat_data.stime - old_stat.stime)*1.0) / total_diff; cpu_info.utime = ((cur_stat_data.utime - old_stat.utime)*1.0) / total_diff; } } void TaskTopHandler::GetTaskCpuInfo(int pid, int tid, AppAndTaskStatData & cur_stat_data, int total_diff, AppAndTaskCpuInfo & cpu_info) { AppAndTaskStatData old_stat; if (!GetOldTaskStatData(pid, tid, old_stat)) { memset(&cpu_info, 0, sizeof(AppAndTaskCpuInfo)); } else { cpu_info.cstime = ((cur_stat_data.cstime - old_stat.cstime)*1.0) / total_diff; cpu_info.cutime = ((cur_stat_data.cutime - old_stat.cutime)*1.0) / total_diff; cpu_info.stime = ((cur_stat_data.stime - old_stat.stime)*1.0) / total_diff; cpu_info.utime = ((cur_stat_data.utime - old_stat.utime)*1.0) / total_diff; } } }
4cbb0a138b522a832bf16322615a3d90adbcabc8
6f874ccb136d411c8ec7f4faf806a108ffc76837
/code/Windows-classic-samples/Samples/Win7Samples/multimedia/mediafoundation/protectedplayback/Player.h
4ed9739ba5ad8dc07a1bf46345a83270d01e8c46
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
JetAr/ZDoc
c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435
e81a3adc354ec33345e9a3303f381dcb1b02c19d
refs/heads/master
2022-07-26T23:06:12.021611
2021-07-11T13:45:57
2021-07-11T13:45:57
33,112,803
8
8
null
null
null
null
UTF-8
C++
false
false
3,549
h
Player.h
////////////////////////////////////////////////////////////////////////// // // player.h : Playback helper class. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // ////////////////////////////////////////////////////////////////////////// #pragma once const UINT WM_APP_PLAYER_EVENT = WM_APP + 1; // wparam = IMFMediaEvent* enum PlayerState { Closed = 0, // No session. Ready, // Session was created, ready to open a file. OpenPending, // Session is opening a file. Started, // Session is playing a file. Paused, // Session is paused. Stopped, // Session is stopped (ready to play). Closing // Application has closed the session, but is waiting for MESessionClosed. }; class CPlayer : public IMFAsyncCallback { public: static HRESULT CreateInstance(HWND hVideo, HWND hEvent, CPlayer **ppPlayer); // IUnknown methods STDMETHODIMP QueryInterface(REFIID iid, void** ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // IMFAsyncCallback methods STDMETHODIMP GetParameters(DWORD*, DWORD*) { // Implementation of this method is optional. return E_NOTIMPL; } STDMETHODIMP Invoke(IMFAsyncResult* pAsyncResult); // Playback HRESULT OpenURL(const WCHAR *sURL); HRESULT Play(); HRESULT Pause(); HRESULT Shutdown(); HRESULT HandleEvent(UINT_PTR pUnkPtr); PlayerState GetState() const { return m_state; } // Video functionality HRESULT Repaint(); HRESULT ResizeVideo(WORD width, WORD height); BOOL HasVideo() const { return (m_pVideoDisplay != NULL); } // Content protection manager HRESULT GetContentProtectionManager(ContentProtectionManager **ppManager); protected: // Constructor is private. Use static CreateInstance method to instantiate. CPlayer(HWND hVideo, HWND hEvent); // Destructor is private. Caller should call Release. virtual ~CPlayer(); HRESULT Initialize(); HRESULT CreateSession(); HRESULT CloseSession(); HRESULT StartPlayback(); HRESULT CreateMediaSource(const WCHAR *sURL); HRESULT CreateTopologyFromSource(IMFTopology **ppTopology); HRESULT AddBranchToPartialTopology( IMFTopology *pTopology, IMFPresentationDescriptor *pSourcePD, DWORD iStream ); // Media event handlers HRESULT OnTopologyReady(IMFMediaEvent *pEvent); HRESULT OnSessionStarted(IMFMediaEvent *pEvent); HRESULT OnSessionPaused(IMFMediaEvent *pEvent); HRESULT OnSessionClosed(IMFMediaEvent *pEvent); HRESULT OnPresentationEnded(IMFMediaEvent *pEvent); long m_nRefCount; // Reference count. IMFMediaSession *m_pSession; IMFMediaSource *m_pSource; IMFVideoDisplayControl *m_pVideoDisplay; HWND m_hwndVideo; // Video window. HWND m_hwndEvent; // App window to receive events. PlayerState m_state; // Current state of the media session. HANDLE m_hCloseEvent; // Event to wait on while closing ContentProtectionManager *m_pContentProtectionManager; };
f6096479c4b08f2953b7f3653aa76e90e11f1e07
b1b3fc3e75508e471e1e1c0077b820fe0d6d431e
/example/src/ofApp.cpp
1eb3b8e88c808185d656eafe99ab6faa7699163a
[]
no_license
javl/ofxStreetView
dc44fd69ad7d17bd2e7d1e4754eea3ce02e63c9f
231400fd183d44eb92fddf0a3caaec6ea7b9f90a
refs/heads/master
2020-03-10T23:05:53.744485
2017-11-16T11:37:16
2017-11-16T11:37:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,198
cpp
ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetVerticalSync(true); ofEnableDepthTest(); streetview.setLatLon(40.75732,-73.985951); // Time Sq //streetview.setLatLon(40.768153,-73.981473); // Columbus Circus // streetview.setLatLon(40.751511,-73.993953); // Penn Station //streetview.setLatLon(22.276499,114.1735439); // wanchai MTR hong kong; // streetview.setLatLon( 51.462088,-2.5901384 ); //stokes croft // streetview.setLatLon( 50.7530769,5.6964121 ); //liege netherlands border post // streetview.setLatLon( 50.7531791,5.6960133 ); //liege netherlands border post 2 streetview.setZoom(3); b_drawPointCloud, b_enableLight = false; fileName = "streetmesh" + ofGetTimestampString() + ".obj"; cout << fileName << endl; obj.open(ofToDataPath(fileName),ofFile::WriteOnly); } //-------------------------------------------------------------- void ofApp::update(){ streetview.update(); //streetview.setUseTexture(false); mesh = streetview.getDethMesh(); } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); if (b_enableLight) worldLight.enable(); cam.begin(); if (b_drawPointCloud) { streetview.draw(); } else { // db hack nov 2017 mesh.setMode(OF_PRIMITIVE_POINTS); glPointSize(4); //glEnable(GL_POINT_SMOOTH); // use circular points instead of square points ofPushMatrix(); // ofScale(1, -1, -1); // the projected points are 'upside down' and 'backwards' // ofTranslate(0, 0, 0); // center the points a bit glEnable(GL_DEPTH_TEST); //gluPerspective(57.0, 1.5, 0.1, 20000.0); // fov, glShadeModel(GL_TRIANGLES); //mesh.drawVertices(); mesh.drawFaces(); ofSetColor( 255, 255, 255); //set render colour for unpainted points, faces and lines mesh.draw(); glDisable(GL_DEPTH_TEST); // mesh.clear(); ofPopMatrix(); } cam.end(); worldLight.disable(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ switch (key) { case 'p': case 'P': b_drawPointCloud =!b_drawPointCloud; break; case 'f': case 'F': ofToggleFullscreen(); break; case 'l': case 'L': b_enableLight = !b_enableLight; break; case 's': case 'S': exportOBJ(mesh); } } //----------------- void ofApp::exportOBJ(ofMesh &mesh){ //obj.open(ofToDataPath(name),ofFile::WriteOnly); obj << "#vertices\n"; for(int i = 0 ; i < mesh.getNumVertices(); i++) { ofVec3f v = mesh.getVertex(i); obj << "v " + ofToString(v.x) + " " + ofToString(v.y) + " " + ofToString(v.z) + "\n"; } obj << "#faces\n"; for(int i = 0 ; i < mesh.getNumIndices(); i += 3) obj << "f " + ofToString(mesh.getIndex(i)) + " " + ofToString(mesh.getIndex(i+1)) + " " + ofToString(mesh.getIndex(i+2)) + "\n"; obj << "\n"; obj.close(); cout << "wrote obj file" << endl; } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
6f3b6dbab3df12a09a9a361aee4670229f4ff3ab
d89cf4037553c61900955c919b190ae229664659
/algorithms/bidirectional_dijkstra.cpp
0123cff62b6ed3c3699ffbd0a3fd7c327f94d13e
[]
no_license
ekaterinapluch/dijkstra
118dcb70a93f63d3178bbb0f5ef8893d4921afc1
44c6ec78dd356d6c47eb11cdf46a06526180eead
refs/heads/master
2023-02-21T00:33:17.254442
2021-01-27T15:45:31
2021-01-27T15:45:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
81
cpp
bidirectional_dijkstra.cpp
// // Created by mkspopov on 13.11.2020. // #include "bidirectional_dijkstra.h"
bdc525b7bbb395ff8a04ef2541655ad536a78169
4a18656e5e113c2a684830c8466d4f4ceccc43eb
/EAWebKitSupportPackages/EAIOEAWebKit/local-01/include/EAIO/EAStreamFixedMemory.h
6afa40a9e26745e7ceefc76d058ace5213eadb41
[]
no_license
ychin/EAWebKit
a0159b005427946e54b3faf4c4295859f8e4e7d5
f8b5c9ba619eb80a2a06a073e2aaa08f039a2954
refs/heads/master
2023-03-08T14:28:53.888399
2023-02-28T23:58:53
2023-02-28T23:59:42
67,105,099
47
16
null
2019-11-04T03:54:24
2016-09-01T06:38:31
Objective-C
UTF-8
C++
false
false
5,659
h
EAStreamFixedMemory.h
/* Copyright (C) 2009-2010 Electronic Arts, Inc. 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 Electronic Arts, Inc. ("EA") 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 ELECTRONIC ARTS AND ITS 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 ELECTRONIC ARTS OR ITS 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. */ ///////////////////////////////////////////////////////////////////////////// // EAStreamFixedMemory.h // // Copyright (c) 2007, Electronic Arts Inc. All rights reserved. // Written by Talin // Based on EAStreamMemory.h by PaulPedriana. // // Implements a IO stream that reads from a fixed-length block of memory. ///////////////////////////////////////////////////////////////////////////// #if !defined(EAIO_EASTREAMFIXEDMEMORY_H) && !defined(FOUNDATION_EASTREAMFIXEDMEMORY_H) #define EAIO_EASTREAMFIXEDMEMORY_H #define FOUNDATION_EASTREAMFIXEDMEMORY_H // For backward compatability. Eventually, we'll want to get rid of this. #include <EAIO/internal/Config.h> #ifndef EAIO_EASTREAM_H #include <EAIO/EAStream.h> #endif namespace EA { namespace IO { /// Implements an memory-based stream that supports the IStream interface. /// /// This class is not inherently thread-safe. As a result, thread-safe usage /// between multiple threads requires higher level coordination, such as a mutex. /// class EAIO_API FixedMemoryStream : public IStream { public: enum { kTypeFixedMemoryStream = 0x02f2f470 }; FixedMemoryStream( void *pBuffer = NULL, size_type nSize = 0 ); FixedMemoryStream( FixedMemoryStream& memoryStream ); virtual ~FixedMemoryStream(); int AddRef(); int Release(); void* GetData() const; bool SetData( void* pData, size_type nSize ); size_type GetCapacity() const; // IStream uint32_t GetType() const; int GetAccessFlags() const; int GetState() const; bool Close(); size_type GetSize() const; bool SetSize(size_type size); off_type GetPosition( PositionType positionType = kPositionTypeBegin ) const; bool SetPosition( off_type position, PositionType positionType = kPositionTypeBegin ); size_type GetAvailable() const; size_type Read(void* pData, size_type nSize); bool Flush(); bool Write(const void* pData, size_type nSize); protected: void * mpData; int mnRefCount; /// Reference count. May or may not be in use. size_type mnSize; /// The size of the stream, in bytes. size_type mnCapacity; /// The size of the memory buffer, in bytes. size_type mnPosition; /// Current position within memory block. }; } // namespace IO } // namespace EA /////////////////////////////////////////////////////////////////////////////// // Inlines /////////////////////////////////////////////////////////////////////////////// inline EA::IO::FixedMemoryStream::~FixedMemoryStream() {} inline int EA::IO::FixedMemoryStream::AddRef() { return ++mnRefCount; } inline int EA::IO::FixedMemoryStream::Release() { if(mnRefCount > 1) return --mnRefCount; delete this; return 0; } inline void* EA::IO::FixedMemoryStream::GetData() const { return mpData; } inline EA::IO::size_type EA::IO::FixedMemoryStream::GetCapacity() const { return mnCapacity; } inline uint32_t EA::IO::FixedMemoryStream::GetType() const { return kTypeFixedMemoryStream; } inline int EA::IO::FixedMemoryStream::GetAccessFlags() const { return kAccessFlagReadWrite; } inline int EA::IO::FixedMemoryStream::GetState() const { return kStateSuccess; } inline bool EA::IO::FixedMemoryStream::Close() { return true; } inline EA::IO::size_type EA::IO::FixedMemoryStream::GetSize() const { return mnSize; } inline EA::IO::size_type EA::IO::FixedMemoryStream::GetAvailable() const { // assert(mnPosition <= mnSize); return (mnSize - mnPosition); } inline bool EA::IO::FixedMemoryStream::Flush() { // Nothing to do. return true; } #endif // Header include guard
2e350894d5323cd896681c13695b8f9a85882608
b80b4845b10bdce598070aa1e98f7037219a67b5
/tests/main.cpp
1d037505ea6de0eba63e58ad42430f0572f25f44
[]
no_license
mettizik/cpp-test-framework
a2293acb40e6923df03b0398495418d210c59e98
75b27b175db4a7e0664161a0e58c072f4d5fc885
refs/heads/master
2020-03-30T07:00:00.319994
2018-09-30T19:21:16
2018-09-30T19:21:16
150,906,957
0
0
null
null
null
null
UTF-8
C++
false
false
1,232
cpp
main.cpp
#include <iostream> #include <iomanip> #include <string> #include <cpptest/cpptest.h> void print_ruller(size_t length, char filler) { if (filler != 0) { std::cout << " " << std::string(length, filler) << std::endl; } } template <class T> void print_row(const std::string &name, T value, char headliner = 0, char bottomliner = 0) { print_ruller(80, headliner); std::cout << " | " << std::left << std::setw(20) << name << " | " << std::left << std::setw(55) << value << std::right << " | " << std::endl; print_ruller(80, bottomliner); } test::test_suite engine_tests(); test::test_suite comparators_tests(); void run_tests(const test::test_suite &suite, const std::string &name) { test::TestExecutionEngine executor; executor.run_testset(suite); print_row("Test suite", name, '='); print_row("Passed tests", executor.passed_tests(), '='); print_row("Failed tests", executor.failed_tests(), '-', '='); if (executor.failed_tests() > 0) { std::cerr << executor.errors() << std::endl; } } int main() { run_tests(engine_tests(), "Execution engine tests"); run_tests(comparators_tests(), "Comparators tests"); return 0; }
ef5d21321a5b185c0ca1b41db443bcc62b103b83
c08b3bd26be7717c11cfb8456e067f089c546f73
/MainWindow.cpp
358ea7cc53ab26704fdd8b968f326ad7616237f7
[]
no_license
Dagal/QSinJack
18ece3951d780f681431010318cca9cf78631fb9
73a301ee6b43554511825ed2033f7fa8fc166d49
refs/heads/master
2021-01-13T02:03:29.233382
2014-06-06T06:20:00
2014-06-06T06:20:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
582
cpp
MainWindow.cpp
#include "MainWindow.h" #include "ui_MainWindow.h" void MainWindow::closeEvent(QCloseEvent* event) { m_sinusOnJack->stop(); exit(0); } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_sinusOnJack = new SinusOnJack(this); m_sinusOnJack->start(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_soundButton_clicked() { // C'est ici qu'on demande au son de bien vouloir sortir s'il vous plait! } void MainWindow::on_gainSlider_valueChanged(int value) { m_sinusOnJack->updateGain(value); }
60f5c064bfd1815465488ed2e3b8cfb948fe0671
73a50069f27146c879e6cd04cf8a744bf9a4b32c
/Matchers/main.cpp
6d4a1c285c40871362d4d08903446559a0bc964e
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hoelzl/CPlusPlus-Tests
98db4a074467ef43713a74f42f12507f67de88cd
4b890fa002ed0c4deb0fccb4c47dc3bdb652acb6
refs/heads/master
2021-04-03T08:11:36.072804
2018-07-10T06:33:17
2018-07-10T06:33:17
125,044,947
0
0
null
null
null
null
UTF-8
C++
false
false
268
cpp
main.cpp
// Copyright 2018 Dr. Matthias Hölzl // Licensed under the MIT License // #include <iostream> #include "lib.h" int main() { std::cout << "Hello, World!" << std::endl; std::cout << "Pi is approximately " << Approximate(3.141592) << std::endl; return 0; }
d61f807400825138de142842a7efffc826f4aca2
75f26c2678a8c16899ae58a07879a7e3c6d2d36a
/Kernel/tConcept.cpp
df95843c173f380279acdce22379cada985af0c3
[]
no_license
tweag/factplusplus
ce94e4c87e52e9f1353e34043319592bed2d7bb9
d7f377351d82ea5243262538e43ddc4f0312ecdf
refs/heads/master
2021-05-01T04:20:52.485504
2016-09-16T07:06:52
2016-09-16T07:06:52
75,384,013
1
0
null
null
null
null
UTF-8
C++
false
false
6,368
cpp
tConcept.cpp
/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2015 Dmitry Tsarkov and The University of Manchester Copyright (C) 2015-2016 Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tConcept.h" #include "tRole.h" void TConcept :: clear ( void ) { // TNamedEntry clean setId(0); // ClassifiableEntry clean taxVertex = nullptr; toldSubsumers.clear(); setCompletelyDefined(false); pSynonym = nullptr; // TConcept clean removeDescription(); setPrimitive(); pName = pBody = bpINVALID; } void TConcept :: addDesc ( DLTree* Desc ) { fpp_assert (!isNonPrimitive()); // safety check // FIXME!! check about reverse order Description = createSNFAnd ( Desc, Description ); } /// calculate value of classification TAG based on told subsumers. WARNING: no TS cycles allowed CTTag TConcept :: determineClassTag ( void ) { // for synonyms -- set tag as a primer's one if ( isSynonym() ) return resolveSynonym(this)->getClassTag(); // check if it is non-primitive if ( isNonPrimitive() ) return cttNonPrimitive; // no told subsumers if ( !hasToldSubsumers() ) return cttOrphan; // now need to check all the told subsumers bool hasLCD = false; bool hasOther = false; bool hasNP = false; for ( auto& p: told() ) switch ( static_cast<TConcept*>(p)->getClassTag() ) { case cttTrueCompletelyDefined: break; case cttOrphan: case cttLikeCompletelyDefined: hasLCD = true; break; case cttRegular: hasOther = true; break; case cttHasNonPrimitiveTS: case cttNonPrimitive: hasNP = true; break; default: fpp_unreachable(); } // there are non-primitive TS if ( hasNP ) return cttHasNonPrimitiveTS; // has something different from CD-like ones (and not CD) if ( hasOther || !isCompletelyDefined() ) return cttRegular; // no more 'other' concepts here, and the CD-like structure if ( hasLCD ) return cttLikeCompletelyDefined; return cttTrueCompletelyDefined; } bool TConcept :: hasSelfInDesc ( const DLTree* t ) const { if ( t == nullptr ) return false; switch ( t->Element().getToken() ) { case NAME: // if ID contains synonym of P { const ClassifiableEntry* name = static_cast<const ClassifiableEntry*>(t->Element().getNE()); return resolveSynonym(name) == this; } case AND: return hasSelfInDesc(t->Left()) || hasSelfInDesc(t->Right()); case NOT: // a [= (not a) -> a [= BOTTOM; a [= (a or b) -> a [= TOP switch ( t->Left()->Element().getToken() ) { case AND: case NAME: return hasSelfInDesc(t->Left()); default: return false; } default: return false; } } DLTree* TConcept :: replaceSelfWithConst ( const DLTree* t ) const { if ( t == nullptr ) return nullptr; switch ( t->Element().getToken() ) { case NAME: // if ID contains synonym of P { const ClassifiableEntry* name = static_cast<const ClassifiableEntry*>(t->Element().getNE()); if ( resolveSynonym(name) == this ) return createTop(); else break; } case AND: // a [= (and a b) -> a [= b return createSNFAnd ( replaceSelfWithConst(t->Left()), replaceSelfWithConst(t->Right()) ); case NOT: // a [= (not a) -> a [= BOTTOM; a [= (a or b) -> a [= TOP switch ( t->Left()->Element().getToken() ) { case AND: case NAME: return createSNFNot(replaceSelfWithConst(t->Left())); default: break; } default: break; } return clone(t); } /// init told subsumers of the concept by given DESCription; @return TRUE iff concept is CD bool TConcept :: initToldSubsumers ( const DLTree* desc, RoleSSet& RolesProcessed ) { // no description => nothing to do (and yes, it is told) if ( desc == nullptr ) return true; switch ( desc->Element().getToken() ) { case TOP: // the 1st node return true; case NAME: // it is a concept ID return addToldSubsumer(static_cast<TConcept*>(desc->Element().getNE())); case AND: // add TS from BOTH parts of AND return initToldSubsumers ( desc->Left(), RolesProcessed ) & initToldSubsumers ( desc->Right(), RolesProcessed ); case NOT: // Domains from \ER.C and (>= n R.C) are told concepts { const TLexeme& cur = desc->Left()->Element(); if ( cur.getToken() == FORALL || cur.getToken() == LE ) SearchTSbyRoleAndSupers ( resolveRole(desc->Left()->Left()), RolesProcessed ); return false; } case SELF: // Domains and Range from participating role { const TRole* R = resolveRole(desc->Left()); SearchTSbyRoleAndSupers ( R, RolesProcessed ); SearchTSbyRoleAndSupers ( R->inverse(), RolesProcessed ); return false; } default: // not told one return false; } } void TConcept :: SearchTSbyRole ( const TRole* R, RoleSSet& RolesProcessed ) { const DLTree* Domain = R->getTDomain(); if ( Domain == nullptr || isConst(Domain) ) return; // don't process the same role twice if ( RolesProcessed.find(R) != RolesProcessed.end() ) return; // mark role as processed; usually it's the only role, so set hint as a begin() RolesProcessed.insert ( RolesProcessed.begin(), R ); // init TS by the domain of role initToldSubsumers ( Domain, RolesProcessed ); // don't bother about result } void TConcept :: SearchTSbyRoleAndSupers ( const TRole* r, RoleSSet& RolesProcessed ) { SearchTSbyRole ( r, RolesProcessed ); // do the same for all super-roles if necessary // FIXME!! need to do the same for DomSupers (like SoR [= R) for ( const auto& sup: r->ancestors() ) SearchTSbyRole ( sup, RolesProcessed ); } unsigned int TConcept :: calculateTSDepth ( void ) { if ( tsDepth > 0 ) return tsDepth; unsigned int max = 0; for ( auto& p: told() ) { unsigned int cur = static_cast<TConcept*>(p)->calculateTSDepth(); if ( max < cur ) max = cur; } return (tsDepth = max+1); }
3c117bce2f292fafe6561dbfc16214d33c046e6b
cb4df4e081f71c1bda5d54d9c7760952b20895c7
/287BaseCode/ExerciseBasicGraphics.cpp
981b062cbb1f70cb39b7319f6598f2fb78793edf
[]
no_license
FranciKZ/287-Code
b82f698e358246c3ea2e434ba7310cdc79bb0e61
aa93dc643e68747fdeb2993b4f752b4222249856
refs/heads/master
2020-03-28T04:17:51.065934
2018-12-05T19:35:07
2018-12-05T19:35:07
147,705,983
0
0
null
null
null
null
UTF-8
C++
false
false
3,164
cpp
ExerciseBasicGraphics.cpp
#include <ctime> #include <vector> #include "defs.h" #include "Utilities.h" #include "FrameBuffer.h" #include "ColorAndMaterials.h" #include "Rasterization.h" FrameBuffer frameBuffer(WINDOW_WIDTH, WINDOW_HEIGHT); void closed5x5Square(int x, int y, color C) { drawLine(frameBuffer, x - 2, y - 2, x + 2, y - 2, C); drawLine(frameBuffer, x - 2, y - 1, x + 2, y - 1, C); drawLine(frameBuffer, x - 2, y, x + 2, y, C); drawLine(frameBuffer, x - 2, y + 1, x + 2, y + 1, C); drawLine(frameBuffer, x - 2, y + 2, x + 2, y + 2, C); } void closed5x5Square(const glm::vec2 &centerPt, color C) { closed5x5Square(centerPt.x, centerPt.y, C); } void open5x5Square(const glm::vec2 &centerPt, color C) { drawLine(frameBuffer, centerPt.x - 2, centerPt.y + 2, centerPt.x + 2, centerPt.y + 2, C); drawLine(frameBuffer, centerPt.x - 2, centerPt.y - 2, centerPt.x + 2, centerPt.y - 2, C); drawLine(frameBuffer, centerPt.x - 2, centerPt.y + 2, centerPt.x - 2, centerPt.y - 2, C); drawLine(frameBuffer, centerPt.x + 2, centerPt.y + 2, centerPt.x + 2, centerPt.y - 2, C); } // length of small arc = perc * 2pi // length of arc arc = 2pi - perc * 2pi // rad is radius void pieChart(const glm::vec2 &centerPt, float rad, float perc, const color &C1, const color &C2) { float smallPerc = perc * M_2PI; float bigPerc = M_2PI - smallPerc; float startPoint = smallPerc / 2; drawArc(frameBuffer, centerPt, rad, startPoint, bigPerc, C1); glm::vec2 bigStartPoint(pointOnCircle(centerPt, rad, startPoint)); glm::vec2 bigEndPoint(pointOnCircle(centerPt, rad, (startPoint + bigPerc))); drawLine(frameBuffer, centerPt.x, centerPt.y, bigStartPoint.x, bigStartPoint.y, C1); drawLine(frameBuffer, centerPt.x, centerPt.y, bigEndPoint.x, bigEndPoint.y, C1); glm::vec2 newCenter(centerPt.x + 20, centerPt.y); glm::vec2 smallStartPoint(pointOnCircle(newCenter, rad, startPoint + bigPerc)); glm::vec2 smallEndPoint(pointOnCircle(newCenter, rad, startPoint)); drawArc(frameBuffer, newCenter, rad, (startPoint + bigPerc), smallPerc, C2); drawLine(frameBuffer, newCenter.x, newCenter.y, smallStartPoint.x, smallStartPoint.y, C2); drawLine(frameBuffer, newCenter.x, newCenter.y, smallEndPoint.x, smallEndPoint.y, C2); } void render() { frameBuffer.clearColorAndDepthBuffers(); closed5x5Square(50, 50, red); closed5x5Square(glm::vec2(100, 50), green); open5x5Square(glm::vec2(150, 50), blue); pieChart(glm::vec2(250, 100), 50, 0.15, red, green); frameBuffer.showColorBuffer(); } void resize(int width, int height) { frameBuffer.setFrameBufferSize(width, height); glutPostRedisplay(); } void keyboard(unsigned char key, int x, int y) { switch (key) { case ESCAPE: glutLeaveMainLoop(); break; } } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); GLuint world_Window = glutCreateWindow(__FILE__); glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); glutDisplayFunc(render); glutReshapeFunc(resize); glutKeyboardFunc(keyboard); glutMouseFunc(mouseUtility); frameBuffer.setClearColor(black); glutMainLoop(); return 0; }
aa1f01143535b56bf34e962cdd1aa5e546c7f915
7918b32f641d758d2ea05a3eb22aa1171cea8cd3
/ui/include/ui/window.hpp
1ac2932379ec86196237c7f44d9da56fd9cb5897
[ "BSL-1.0" ]
permissive
dobson156/irc_client
e43553b43bde33b2f8b4e72b40a677fd2f9004cb
9afc098087a64c88f599e3dae956b7be1407bb96
refs/heads/master
2021-01-01T06:45:01.450302
2014-11-25T23:51:13
2014-11-25T23:51:13
8,236,549
1
0
null
2014-01-18T13:18:26
2013-02-16T14:11:55
C++
UTF-8
C++
false
false
599
hpp
window.hpp
#ifndef CONS_WINDOW_HPP #define CONS_WINDOW_HPP #include <ncurses.h> #include <memory> namespace cons { struct point; using unique_window_ptr=std::unique_ptr<WINDOW, decltype(&::delwin)>; //helper int destroy_parent(WINDOW *win); //Makes a new parent windows unique_window_ptr make_window(); //Makes a sub window from an existing window unique_window_ptr make_window(WINDOW *parent, const point& position, const point& dimension); //Makes a new pad unique_window_ptr make_pad(const point& dimension); } //namespace cons #endif //CONS_WINDOW_HPP
b083fd2fc6b3801a54b1dee8a85536b5e1073974
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5640146288377856_0/C++/ImGonnaWreckIt/1.cpp
28af3690baa36dbb78f5ad05539dade539df7349
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
382
cpp
1.cpp
#include <iostream> #include <iomanip> #include <cmath> #include <algorithm> using namespace std; int main(){ int i,j,k,l; int N,T; int *board; int R, C, W; cin>>T; for(l = 0 ; l < T ; l++){ cin>>R>>C>>W; cout<<"Case #"<<l+1<<": "; N = (C - W)/W; if(C % W == 0) N = N+W; else N = N + W +1; if(R > 1) N += C/W * (R - 1); cout<<N<<"\n"; } return 0; }
875a8e4e47d91af47035baf315403275ff65a64b
d3f7cbcb205928281ef170a95ff399fad5e5d208
/TY_PSUO/Inheritance/abstract_class.cpp
7a184466ac3d010fec0c3e5e435e73140b3f4c87
[]
no_license
SatvikDandale/TY_SEM1
43883fefb31052315f9f00e5dbffbe8a3c28744b
474790a4d360835ab843f4a083244e5ccaba6c0b
refs/heads/master
2021-08-08T21:19:30.967009
2020-08-05T12:15:54
2020-08-05T12:15:54
208,415,563
1
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
abstract_class.cpp
/* CPP program to demostrate how abstract (do nothing) functions are inherited and the rules for the same. */ #include<bits/stdc++.h> using namespace std; class A{ public: // Declaring just one function as virtaul AND do nothing will make the class abstract. virtual void f1() = 0; void f2(){ cout<<"This is f2\n"; } }; class B: public A{ public: void f1(){ cout<<"This is from f1 function of class B.\n"; } }; int main(){ // A a1; // Abstract class cannot be instantiated. A *p; B b; b.f1(); // This will obviously work. No other concept involved. p = &b; p -> f1(); // Here calling entity, according to compiler at the (time of compilation) is A. // But making the abstract function virtual will not let the compiler bind this f1() to A. // This f1() will be bound to B at RUNTIME. }
53c4b8212fbf8e92ed55981cbb26ac6b953b5fc8
5bccf2d2118008c0af6a51a92a042e967e4f2abe
/Support/Modules/UDLib/UDToolBox.hpp
f3b7c200935387823ada7b99f4680ac90fe0f10e
[ "Apache-2.0" ]
permissive
graphisoft-python/DGLib
fa42fadebedcd8daaddde1e6173bd8c33545041d
66d8717eb4422b968444614ff1c0c6c1bf50d080
refs/heads/master
2020-06-13T21:38:18.089834
2020-06-12T07:27:54
2020-06-12T07:27:54
194,795,808
3
0
Apache-2.0
2020-06-12T07:27:55
2019-07-02T05:45:00
C++
UTF-8
C++
false
false
11,059
hpp
UDToolBox.hpp
// ***************************************************************************** // File: UDToolBox.hpp // // Description: Toolbox related classes // // Project: GRAPHISOFT User Dialog Module (UDLib) // // Namespace: UD // // Contact person: MD // // SG compatible // ***************************************************************************** #ifndef UDTOOLBOX_HPP #define UDTOOLBOX_HPP #pragma once // --- Includes ---------------------------------------------------------------- #include <xercesc/util/XercesDefs.hpp> #include "Array.hpp" #include "Event.hpp" #include "EventObserver.hpp" #include "EventSource.hpp" #include "UniString.hpp" #include "UDDefinitions.hpp" #include "DGCommandDescriptor.hpp" #include "DGDialog.hpp" // --- Predeclarations --------------------------------------------------------- XERCES_CPP_NAMESPACE_BEGIN class DOMElement; XERCES_CPP_NAMESPACE_END namespace UD { class ToolBox; class ToolBoxImpl; class ToolBoxGroup; class ToolBoxItem; } namespace DG { class Command; class CommandLayoutSerializer; class CommandLayoutDeserializer; class ListViewPressedEvent; class SingleSelListView; } namespace UD { // --- Class declarations ------------------------------------------------------ // --- ToolBoxObserver --------------------------------------------------------- class UD_DLL_EXPORT ToolBoxObserver: public GS::EventObserver { friend class ToolBox; protected: virtual void ToolBoxOpened (const ToolBox& toolBox); virtual void ToolBoxClosed (const ToolBox& toolBox, bool onRequest); virtual void ToolBoxContextMenuRequested (const ToolBox& toolBox, const DG::PanelContextMenuEvent& ev, bool* needHelp, bool* processed); virtual void ToolBoxItemPressed (const ToolBox& toolBox, const DG::ListViewPressedEvent& ev); public: ToolBoxObserver (); ~ToolBoxObserver (); }; // --- ToolBox ----------------------------------------------------------------- class UD_DLL_EXPORT ToolBox: private GS::EventSource { friend class ToolBoxGroup; friend class ToolBoxItem; friend ToolBoxImpl* ToolBox_GetImpl (ToolBox*); friend class ToolBoxImpl; public: // inner class definitions // ConstIterator typedef GS::Array<ToolBoxGroup*>::ConstIterator ConstIterator; public: // enumerations static const GS::Guid guid; private: // attributes GS::UniString title; // relations GS::Array<ToolBoxGroup*> groups; // implementation ToolBoxImpl* impl; // position mutable DG::NativePoint position; short initialHeight; bool doLayoutInit; mutable UIndex lastSelectedItem; static bool disableAllLayout; bool changedByTheUser; bool isInCustomState; void Init (void); ToolBoxImpl* GetImpl (void); void AdjustLastSelected (void) const; // observer notifications // disable copy ToolBox (const ToolBox& source); bool SetGroupVisibility (const ConstIterator& iterator, bool visibility) const; void RebuildImpl (void); // private interface for the bridge void ProcessImplDestroyed (void); void ProcessOpenEvent (void); void ProcessCloseEvent (void); short ProcessCloseRequestEvent (void); void ProcessItemClickedEvent (void* data); void ProcessItemDoubleClickedEvent (void* data); void ProcessContextMenuRequested (const DG::PanelContextMenuEvent& ev, bool* needHelp, bool* processed); void ProcessItemPressedEvent (const DG::ListViewPressedEvent& ev); GS::UniString GetItemShortcut (void* data); public: // constructors / destructors ToolBox (const GS::UniString& title); virtual ~ToolBox (); void Attach (ToolBoxObserver& observer); void Detach (ToolBoxObserver& observer); // accessors GS::UniString GetId (void) const; GS::UniString GetTitle (void) const; void SetTitle (const GS::UniString& title); void Create (void); void Destroy (void); bool IsCreated (void) const; void Show (DG::NativePoint pPosition = DG::NativePoint ()); void Hide (void); bool IsVisible (void) const; void InitDefaultLayout (const DG::NativePoint& position, short height); void PrevTool (void); void NextTool (void); void PressTool (void); void DisableUpdate (void); void EnableUpdate (void); bool IsUpdateEnabled (void); static void DisableAllUpdate (void); static void EnableAllUpdate (void); bool IsChangedByTheUser (void) const; void SetCustomState (bool isCustomState); bool IsInCustomState (void) const; // group operations void AddToolBoxGroup (const GS::UniString& name) throw (GS::OutOfMemoryException); void InsertToolBoxGroup (const ConstIterator& iterator, const GS::UniString& name) throw (GS::OutOfMemoryException); void MoveToolBoxGroup (const ConstIterator& from, const ConstIterator& to) throw (GS::OutOfMemoryException); void RemoveToolBoxGroup (const ConstIterator& iterator); void ExpandGroup (const ToolBoxGroup* group); ConstIterator Enumerate (const ToolBoxGroup* group = nullptr) const; ConstIterator Begin (void) const; ConstIterator End (void) const; // void DeepCopy (const ToolBox& source); GSErrCode XMLWrite (xercesc::DOMElement* parent, int level) const; GSErrCode XMLRead (const xercesc::DOMElement* parent); //GSErrCode XMLReadVersion1 (const xercesc::DOMElement* parent); //GSErrCode XMLReadVersion2 (const xercesc::DOMElement* parent); GSErrCode Read (GS::IChannel& ic, const GS::ClassVersion& version); //GSErrCode ReadVersion1 (GS::IChannel& ic); //GSErrCode ReadVersion2 (GS::IChannel& ic); GSErrCode Write (GS::OChannel& oc) const; DG::Palette* GetImplPalette (void); void ApplyConstraints (void); virtual bool IsHoverNeeded (const DG::SingleSelListView& listView, short listItemIndex) const; void FreezeHover (void); void UnFreezeHover (void); }; // --- ToolBoxGroup ------------------------------------------------------------ class UD_DLL_EXPORT ToolBoxGroup : public DG::CommandDescriptorObserver { friend class ToolBox; friend class ToolBoxItem; public: // enumerations enum Style { SmallIconWithText, SmallIconOnly }; private: //impl UIndex index; mutable char* implData; mutable USize implDataSize; // attributes const ToolBox* parentToolBox; GS::UniString name; bool visible; Style style; bool openToMax; bool closable; // relations GS::Array<ToolBoxItem*> items; // disable copy ToolBoxGroup (const ToolBoxGroup& source); ToolBoxGroup& operator= (const ToolBoxGroup& source); void DeepCopy (const ToolBoxGroup& source); void RebuildItemImpl (void); // private interface for the bridge protected: // CommandDescriptorObserver methods virtual void CheckChanged (const DG::CommandDescriptorCheckEvent& ev) override; virtual void EnableChanged (const DG::CommandDescriptorEnableEvent& ev) override; virtual void TextChanged (const DG::CommandDescriptorTextEvent& ev) override; virtual void CmdDescDeleting (const DG::CommandDescriptorDeleteEvent& ev) override; public: // inner class definitions // ConstIterator typedef GS::Array<ToolBoxItem*>::ConstIterator ConstIterator; // constructors / destructors ToolBoxGroup (const ToolBox& toolbox, const GS::UniString& name); virtual ~ToolBoxGroup (); // accessors GS::UniString GetId (void) const; GS::UniString GetName (void) const; void SetName (const GS::UniString& name); bool IsVisible (void) const; Style GetStyle (void) const; void SetStyle (Style style); bool IsOpenToMax (void) const; void SetOpenToMax (bool openToMax); bool IsClosable (void) const; void SetClosable (bool closable); // item operations void AddToolBoxItem (const DG::Command& command) throw (GS::OutOfMemoryException); void InsertToolBoxItem (const ConstIterator& iterator, const DG::Command& command) throw (GS::OutOfMemoryException); void RemoveToolBoxItem (const ConstIterator& iterator); ConstIterator Enumerate (const DG::Command& command) const; ConstIterator Begin (void) const; ConstIterator End (void) const; // serialization GSErrCode XMLWrite (xercesc::DOMElement* parent, int level) const; GSErrCode XMLRead (const xercesc::DOMElement* parent); //GSErrCode XMLReadVersion1 (const xercesc::DOMElement* parent); //GSErrCode XMLReadVersion2 (const xercesc::DOMElement* parent); GSErrCode Read (GS::IChannel& ic, const GS::ClassVersion& version); //GSErrCode ReadVersion1 (GS::IChannel& ic); //GSErrCode ReadVersion2 (GS::IChannel& ic); GSErrCode Write (GS::OChannel& oc) const; GSErrCode RetrieveImplData (void) const; GSErrCode ApplyImplData (void); }; // === ToolBoxItem class =============================================================================================== // --- Declaration ----------------------------------------------------------------------------------------------------- class UD_DLL_EXPORT ToolBoxItem { friend class ToolBoxGroup; private: const ToolBoxGroup& parentGroup; UIndex index; DG::Command command; ToolBoxItem (const ToolBoxItem& source); // disable ToolBoxItem& operator= (const ToolBoxItem& source); ToolBoxItem (); // for Array public: ToolBoxItem (const ToolBoxGroup& group, const DG::Command& command); virtual ~ToolBoxItem (); const DG::Command& GetCommand (void) const; }; // === ToolBoxCommandDescriptor class ================================================================================== // --- Declaration ----------------------------------------------------------------------------------------------------- class UD_DLL_EXPORT ToolBoxCommandDescriptor : public DG::CommandDescriptor { private: DG::Icon largeIcon; GS::UniString contextHelpAnchor; ToolBoxCommandDescriptor (const ToolBoxCommandDescriptor& source); // disable public: ToolBoxCommandDescriptor (const DG::Command& command, const GS::UniString& text, const DG::Icon& smallIcon, const DG::Icon& largeIcon, const GS::UniString& category = GS::UniString(), const GS::UniString& contextHelp = GS::UniString(), bool visible = true); ~ToolBoxCommandDescriptor (); inline DG::Icon GetSmallIcon (void) const; inline DG::Icon GetLargeIcon (void) const; inline const GS::UniString& GetContextHelpAnchor (void) const; }; // --- Inline implementations ------------------------------------------------------------------------------------------ inline DG::Icon ToolBoxCommandDescriptor::GetSmallIcon (void) const { return GetIcon (); } inline DG::Icon ToolBoxCommandDescriptor::GetLargeIcon (void) const { return largeIcon; } inline const GS::UniString& ToolBoxCommandDescriptor::GetContextHelpAnchor (void) const { return contextHelpAnchor; } } // namespace UD #endif
72c0fbd8e32bb071f7c37b3ff7622198685f85ac
91e542992f2572e80fdde0cb1d61155e6ee1afcd
/oll/oll_train.cpp
fc9f4d25e0f7fc84a2961f306927778d3a2d701f
[]
no_license
hecomi/HAS-Project
5eca2cc7c52637f3ed71f1b32a9d62c52fe9b63b
0bb1b98f2ce12333f36ce343a303a92e12d18816
refs/heads/master
2021-01-02T23:08:12.379569
2012-05-13T03:06:26
2012-05-13T03:06:26
3,766,009
1
0
null
null
null
null
UTF-8
C++
false
false
2,280
cpp
oll_train.cpp
#include <iostream> #include <string> #include <stdlib.h> #include "oll.hpp" static const char* OLL_PROGNAME = "oll_train"; void usage(){ fprintf(stderr, "%s (P|AP|PA|PA1|PA2|CW) trainfile modelfile [devfile] -C=FLOAT -b=FLOAT -I=INT\n" "P : Perceptron\n" "AP : Averaged Perceptron\n" "PA : Passive Agressive\n" "PA1 : Passive Agressive I\n" "PA2 : Passive Agressive II\n" "PAK : Kernelized Passive Agressive\n" "CW : Confidence Weighted\n" "AL : ALMA HD (heavy)\n" "-C Regularization Paramter (Default 1.0)\n" "-b Bias (Default 0.0)\n" "-I Iteration (Default 10, 0 = one pass without storing)\n" , OLL_PROGNAME); } void parseARGV(const char* s, float& C, float& bias, int& iter, std::string& devFileName){ std::string str(s); if (str.size() >= 3){ if (str.substr(0, 3) == "-C="){ C = atof(str.substr(3).c_str()); return; } else if (str.substr(0, 3) == "-b="){ bias = atof(str.substr(3).c_str()); return; } else if (str.substr(0, 3) == "-I="){ iter = atoi(str.substr(3).c_str()); return; } } devFileName = s; } int main(int argc, char* argv[]){ if (argc < 4){ usage(); return -1; } // argv[2] = trainfile // argv[3] = modelfile float C = 1.0f; // regularization parameter float bias = 0.f; // bias int iter = 0; // iteration std::string devFileName; for (int i = 4; i < argc; i++){ parseARGV(argv[i], C, bias, iter, devFileName); } oll_tool::trainMethod tm = oll_tool::P; std::string argv1(argv[1]); if (argv1 == "P" ) {tm = oll_tool::P;} else if (argv1 == "AP") {tm = oll_tool::AP;} else if (argv1 == "PA") {tm = oll_tool::PA;} else if (argv1 == "PA1") {tm = oll_tool::PA1;} else if (argv1 == "PA2") {tm = oll_tool::PA2;} else if (argv1 == "PAK") {tm = oll_tool::PAK;} else if (argv1 == "CW") {tm = oll_tool::CW;} else if (argv1 == "AL") {tm = oll_tool::AL;} else { usage(); return -1; } if (oll_tool::trainFile(argv[2], argv[3], tm, C, bias, iter, true) == -1){ return -1; } if (devFileName != ""){ std::vector<int> confMat; if (oll_tool::testFile(devFileName.c_str(), argv[3], confMat, true) == -1){ return -1; } } return 0; }
47e76ad2f088753046ef9c0f0f6d18ad5d75e2c4
e9c14ecea6b6f349269997ee9fbf75e704d5ffc5
/include/customUserTracker.h
4021ecac346d5a499622916713957d7a460483f8
[]
no_license
heokyunam/GraduateIntegratedProject
d31c34052d80794e001218dc22c1e604cfbc26a9
2d51765b7772a7cd61d73c1a2deac9360c43f758
refs/heads/master
2020-12-30T10:12:21.780317
2017-10-18T05:30:31
2017-10-18T05:30:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,782
h
customUserTracker.h
#include <openni-nite/NiteCAPI.h> #include <openni-nite/NiTE.h> #include <openni-nite/NiteEnums.h> #include <openni2/OpenNI.h> #include <iostream> using namespace nite; /** This is the main object of the User Tracker algorithm. It provides access to one half of the algorithms provided by NiTE. Scene segmentation, skeleton, floor plane detection, and pose detection are all provided by this class. The first purpose of the User Tracker algorithm is to find all of the active users in a specific scene. It individually tracks each human it finds, and provides the means to seperate their outline from each other and from the background. Once the scene has been segmented, the User Tracker is also used to initiate Skeleton Tracking and Pose Detection algorithms. Each user is provided an ID as they are detected. The user ID remains constant as long as the user remains in the frame. If a user leaves the field of view of the camera, or tracking of that user is otherwise lost, the user may have a different ID when he is detected again. There is currently no mechanism that provides persistant recognition of individuals when they are not being actively tracking. If this functionality is desired, it will need to be implimented at the application level. A listener class is provided to allow event based interaction with this algorithm. @see UserMap for the output format of the User Tracker algorithm @see UserData for additional data output by this format @see Skeleton if you are also interested in tracking a user's skeleton @see NiTE for a couple of static functions that must be run before User Tracker can be used @see @ref HandTracker for Gesture and Hand tracking algorithms. */ class CustomUserTracker : public UserTracker { public: /** This is a listener class that is used to react to events generated by the @ref UserTracker class. To use this class, you must derive a class from it that implements the @ref onNewFrame() function. This is the function that will be called when an event is generated. Create a new instance of your derived class. Then, use the @ref UserTracker::addNewFrameListener() function to add the listener to the @ref UserTracker. When that @ref UserTracker generates an onNewFrame event, \ the specified callback function will be called. The onNewFrame event is currently the only event type that this listener is designed to work with. @see @ref UserTracker for the source of this listener's events. */ class NewFrameListener { public: /** Default Constructor. Creates a new object of this type and configures it to correctly receive events. */ NewFrameListener() : m_pUserTracker(NULL) { m_userTrackerCallbacks.readyForNextFrame = newFrameCallback; } /** This is the callback function for the event. It should be implemented in a class derived from NewFrameListener. This function will automatically be called when the OnNewFrame event is triggered. @param [in] A reference to the UserTracker that triggered the event is provided. */ virtual void onNewFrame(UserTracker&) = 0; private: NiteUserTrackerCallbacks m_userTrackerCallbacks; NiteUserTrackerCallbacks& getCallbacks() {return m_userTrackerCallbacks;} static void ONI_CALLBACK_TYPE newFrameCallback(void* pCookie) { NewFrameListener* pListener = (NewFrameListener*)pCookie; pListener->onNewFrame(*pListener->m_pUserTracker); } friend class UserTracker; void setUserTracker(UserTracker* pUserTracker) { m_pUserTracker = pUserTracker; } UserTracker* m_pUserTracker; }; /** Default constructor. Creates an empty @ref UserTracker with a NULL handle. This object will not be useful until the @ref create() function is called. @see @ref UserTracker::create() for a function to create and activate the algorithm. @see @ref UserTracker::isValid() to determine whether @ref create() has already been called. */ CustomUserTracker() : m_userTrackerHandle(NULL) {} /** Destructor. Automatically calls the provided @ref destroy() function. */ ~CustomUserTracker() { destroy(); } /** Creates and initializes an empty User Tracker. This function should be the first one called when a new UserTracker object is constructed. An OpenNI device with depth capabilities is required for this algorithm to work. See the OpenNI 2.0 documentation for more information about using an OpenNI 2.0 compliant hardware device and creating a Device object. @param [in] pDevice A pointer to an initalized OpenNI 2.0 Device object that provides depth streams. @returns A status code to indicate success/failure. Since this relies on an external hardware device, it is important for applications to check this value. @see Status enumeration for a list of all possible status values generated by this call. */ Status create(openni::Device* pDevice = NULL) { if (isValid()) { // tracker already active return STATUS_OUT_OF_FLOW; } if (pDevice == NULL) { return (Status)niteInitializeUserTracker(&m_userTrackerHandle); } return (Status)niteInitializeUserTrackerByDevice(pDevice, &m_userTrackerHandle); } /** Shuts down the user tracker and releases all resources used by it. This is the opposite of create(). This function is called automatically by the destructor in the current implimentation, but it is good practice to run it manually when the algorithm is no longer required. Running this function more than once is safe -- it simply exits if called on a non-valid UserTracker. */ void destroy() { if (isValid()) { niteShutdownUserTracker(m_userTrackerHandle); m_userTrackerHandle = NULL; } } /** Gets the next snapshot of the algorithm. This causes all data to be generated for the next frame of the algorithm -- algorithm frames correspond to the input depth frames used to generate them.OpenNI.h> @param pFrame [out] A pointer that will be set to point to the next frame of data. @returns Status code indicating whether this operation was successful. */ Status readFrame(UserTrackerFrameRef* pFrame) { NiteUserTrackerFrame *pNiteFrame = NULL; Status rc = (Status)niteReadUserTrackerFrame(m_userTrackerHandle, &pNiteFrame); pFrame->setReference(m_userTrackerHandle, pNiteFrame); std::cout << "CustomUserTracker readFrame called" << std::endl; return rc; } /** Indicates whether the UserTracker is valid. When a new UserTracker is first constructed, this function will indicate that it is invalid (ie return False). Once the create() function has been successfully called, then this function will return True. If the destroy() function is called, this function will again indicate invalid. It is safe to run create() and destroy() without calling this function -- both of those functions already check this value and return without doing anything if no action is required. @returns True if the UserTracker object is correctly initialized, False otherwise. @see create() function -- causes the UserTracker to become initialized. @see destroy() function -- causes the UserTracker to become uninitialized. */ bool isValid() const { return m_userTrackerHandle != NULL; } /** Control the smoothing factor of the skeleton joints. Factor should be between 0 (no smoothing at all) and 1 (no movement at all). Experimenting with this factor should allow you to fine tune the skeleton performance. Higher values will produce smoother operation of the skeleton, but may make the skeleton feel less responsive to the user. @param [in] factor The smoothing factor. @returns Status code indicating success or failure of this operation. */ Status setSkeletonSmoothingFactor(float factor) { return (Status)niteSetSkeletonSmoothing(m_userTrackerHandle, factor); } /** Queries the current skeleton smoothing factor. @returns Current skeleton smoothing factor. @see setSkeletonSmoothingFactor for more information on the smoothing factor, and the means to change it. */ float getSkeletonSmoothingFactor() const { float factor; Status rc = (Status)niteGetSkeletonSmoothing(m_userTrackerHandle, &factor); if (rc != STATUS_OK) { factor = 0; } return factor; } /** Requests that the Skeleton algorithm starts tracking a specific user. Once started, the skeleton will provide information on the joint position and orientation for that user during each new frame of the UserTracker. Note that the computational requirements of calculating a skeleton increase linearly with the number of users tracked. Tracking too many users may result in poor performance and high CPU utilization. If performance slows to the point where the skeleton is not calculated at the full frame rate of the depth data used to generate it, the algorithm tends to perform poorly. @param [in] UserID The ID number of the user to calculate a skeleton for. @returns Status code indicating success or failure of this operation. @see nite::Skeleton for more information on the skeleton algorithm. */ Status startSkeletonTracking(UserId id) { return (Status)niteStartSkeletonTracking(m_userTrackerHandle, id); } /** Stops skeleton tracking for a specific user. If multiple users are being tracked, this will only stop tracking for the user specified -- skeleton calculation will continue for remaining users. @param [in] UserID of the person to stop tracking. @see nite::Skeleton for more information on the skeleton algorithm. */ void stopSkeletonTracking(UserId id) { niteStopSkeletonTracking(m_userTrackerHandle, id); } /** This function commands the @ref UserTracker to start detecting specific poses for a specific user. @param [in] user The @ref UserID of the user that you would like to detect a pose for. @param [in] type The type of pose you would like to detect. @returns @ref Status code indicating success or failure of this operation. @see @ref PoseData For more information on pose detection and the output it generates. @see @ref PoseType enumeration for a list of the available poses that can be detected. */ Status startPoseDetection(UserId user, PoseType type) { return (Status)niteStartPoseDetection(m_userTrackerHandle, (NiteUserId)user, (NitePoseType)type); } /** This function commands the pose detection algorithm to stop detecting a specific pose for a specific user. Since it is possible to detect multiple poses from multiple users, it is possible that detection of a different pose on the same user (or the same pose on a different user) may continue after this function is called. @param [in] user The @ref UserID of the user to stop detecting a specific pose for. @param [in] type The @ref PoseType of the pose to stop detecting. */ void stopPoseDetection(UserId user, PoseType type) { niteStopPoseDetection(m_userTrackerHandle, (NiteUserId)user, (NitePoseType)type); } /** Adds a @ref NewFrameListner object to this @ref UserTracker so that it will respond when a new frame is generated. @param [in] pListener Pointer to a listener to add. @see @ref UserTracker::NewFrameListener for more information on using event based interaction with UserTracker */ void addNewFrameListener(NewFrameListener* pListener) { niteRegisterUserTrackerCallbacks(m_userTrackerHandle, &pListener->getCallbacks(), pListener); pListener->setUserTracker(this); } /** Removes a @ref NewFrameListener object from this UserTracker's list of listeners. The listener will no longer respond when a new frame is generated. @param [in] pListener Pointer to a listener to remove. @see @ref UserTracker::NewFrameListener for more information on using event based interaction with UserTracker. */ void removeNewFrameListener(NewFrameListener* pListener) { niteUnregisterUserTrackerCallbacks(m_userTrackerHandle, &pListener->getCallbacks()); pListener->setUserTracker(NULL); } /** In general, two coordinate systems are used in OpenNI 2.0. These conventions are also followed in NiTE 2.0. Skeleton joint positions are provided in "Real World" coordinates, while the native coordinate system of depth maps is the "projective" system. In short, "Real World" coordinates locate objects using a Cartesian coordinate system with the origin at the sensor. "Projective" coordinates measure straight line distance from the sensor (perpendicular to the sensor face), and indicate x/y coordinates using pixels in the image (which is mathematically equivalent to specifying angles). See the OpenNI 2.0 documentation online for more information. Note that no output is given for the Z coordinate. Z coordinates remain the same when performing the conversion. An input value is still required for Z, since this can affect the x/y output. This function allows you to convert the coordinates of a SkeletonJoint to the native coordinates of a depth map. This is useful if you need to find the joint position on the raw depth map. @param [in] x The input X coordinate using the "real world" coordinate system. @param [in] y The input Y coordinate using the "real world" coordinate system. @param [in] z The input Z coordinate using the "real world" coordinate system. @param [out] pOutX Pointer to a location to store the output X coordinate in the "projective" system. @param [out] pOutY Pointer to a location to store the output Y coordinate in the "projective" system. @returns @ref Status indicating success or failure of this operation. This is needed because the ability to convert between coordinate systems requires a properly initalized Device from OpenNI 2.0. */ Status convertJointCoordinatesToDepth(float x, float y, float z, float* pOutX, float* pOutY) const { return (Status)niteConvertJointCoordinatesToDepth(m_userTrackerHandle, x, y, z, pOutX, pOutY); } /** In general, two coordinate systems are used in OpenNI 2.0. These conventions are also followed in NiTE 2.0. Skeleton joint positions are provided in "Real World" coordinates, while the native coordinate system of depth maps is the "projective" system. In short, "Real World" coordinates locate objects using a Cartesian coordinate system with the origin at the sensor. "Projective" coordinates measure straight line distance from the sensor, and indicate x/y coordinates using pixels in the image (which is mathematically equivalent to specifying angles). See the OpenNI 2.0 documentation online for more information. This function allows you to convert the native depth map coordinates to the system used by the joints. This might be useful for performing certain types of measurements (eg distance between a joint and an object identified only in the depth map). Note that no output is given for the Z coordinate. Z coordinates remain the same when performing the conversion. An input value is still required for Z, since this can affect the x/y output. @param [in] x The input X coordinate using the "projective" coordinate system. @param [in] y The input Y coordinate using the "projective" coordinate system. @param [in] z The input Z coordinate using the "projective" coordinate system. @param [out] pOutX Pointer to a location to store the output X coordinate in the "real world" system. @param [out] pOutY Pointer to a location to store the output Y coordinate in the "real world" system. @returns @ref Status indicating success or failure of this operation. This is needed because the ability to convert between coordinate systems requires a properly initalized Device from OpenNI 2.0. */ Status convertDepthCoordinatesToJoint(int x, int y, int z, float* pOutX, float* pOutY) const { return (Status)niteConvertDepthCoordinatesToJoint(m_userTrackerHandle, x, y, z, pOutX, pOutY); } private: NiteUserTrackerHandle m_userTrackerHandle; };
c15b4e6e271402eb81ad0fc2f0b181afde7bad41
3cfc3f4cb1572806c153cdb550f7fd41e1943f08
/_MODEL_FOLDERS_/_modelNameHere TEXTURE NORMALS/crystalBlockShadow_00/crystalBlockShadow_00_shaderInit.cpp
01427ab901b4e3de91e0c5f607102e9f8135d959
[]
no_license
marcclintdion/a8a_MATRIX_MATH_MAY_10
c8d07b3425f8fb04f05104c1baf1b5934fa5b0c4
d9f9851c20f681929aa0896be4e0b8336c50a4fb
refs/heads/master
2021-01-10T07:11:59.889363
2015-09-30T14:11:41
2015-09-30T14:11:41
43,436,890
1
1
null
null
null
null
UTF-8
C++
false
false
1,756
cpp
crystalBlockShadow_00_shaderInit.cpp
const char *crystalBlockShadow_00_SHADER_VertexStrings[1]; const char *crystalBlockShadow_00_SHADER_FragmentStrings[1]; crystalBlockShadow_00_SHADER_Vertex = glCreateShaderObjectARB( GL_VERTEX_SHADER_ARB ); unsigned char *crystalBlockShadow_00_SHADER_VertexAssembly = readShaderFile( "_MODEL_FOLDERS_/crystalBlockShadow_00/crystalBlockShadow_00.vert" ); crystalBlockShadow_00_SHADER_VertexStrings[0] = (char*)crystalBlockShadow_00_SHADER_VertexAssembly; glShaderSourceARB( crystalBlockShadow_00_SHADER_Vertex, 1, crystalBlockShadow_00_SHADER_VertexStrings, NULL ); glCompileShaderARB( crystalBlockShadow_00_SHADER_Vertex); delete crystalBlockShadow_00_SHADER_VertexAssembly; crystalBlockShadow_00_SHADER_Fragment = glCreateShaderObjectARB( GL_FRAGMENT_SHADER_ARB ); unsigned char *crystalBlockShadow_00_SHADER_FragmentAssembly = readShaderFile( "_MODEL_FOLDERS_/crystalBlockShadow_00/crystalBlockShadow_00.frag" ); crystalBlockShadow_00_SHADER_FragmentStrings[0] = (char*)crystalBlockShadow_00_SHADER_FragmentAssembly; glShaderSourceARB( crystalBlockShadow_00_SHADER_Fragment, 1, crystalBlockShadow_00_SHADER_FragmentStrings, NULL ); glCompileShaderARB( crystalBlockShadow_00_SHADER_Fragment ); delete crystalBlockShadow_00_SHADER_FragmentAssembly; crystalBlockShadow_00_SHADER = glCreateProgramObjectARB(); glAttachObjectARB( crystalBlockShadow_00_SHADER, crystalBlockShadow_00_SHADER_Vertex ); glAttachObjectARB( crystalBlockShadow_00_SHADER, crystalBlockShadow_00_SHADER_Fragment ); glLinkProgramARB(crystalBlockShadow_00_SHADER); UNIFORM_counter_crystalBlockShadow_00 = glGetUniformLocationARB( crystalBlockShadow_00_SHADER, "counter" );
6db266274dd8aea38c3fb543fc01184b74000546
1a8ac76c6f7ba53fa6292f680e664dc084d69cf4
/src/lib/tools/Typenames.hpp
f67192586de9ec111a627fa68d91a1d232b46ffe
[ "MIT" ]
permissive
Lut99/Rasterizer
eb14ac6f873b54966d559458961e89be986351e0
453864506db749a93fb82fb17cc5ee88cc4ada01
refs/heads/master
2023-08-24T23:46:21.258199
2021-10-01T10:21:14
2021-10-01T10:21:14
374,108,823
1
0
null
null
null
null
UTF-8
C++
false
false
2,609
hpp
Typenames.hpp
/* TYPENAMES.hpp * by Lut99 * * Created: * 18/07/2021, 12:56:59 * Last edited: * 18/07/2021, 12:56:59 * Auto updated? * Yes * * Description: * Provides some templated functions to easily return a sort of * human-readable name of types. Others can be provided by defining * template specializations yourself. **/ #ifndef TOOLS_TYPENAMES_HPP #define TOOLS_TYPENAMES_HPP #include <cstdint> #include <string> #include <typeinfo> namespace Tools { /* Returns the typeid(T).name() of the given type. Functions as basecase when no type_name() specialization for the type is available. */ template <class T> inline constexpr const char* type_name() { return typeid(T).name(); } /* Wrapper around type_name that returns a string. */ template <class T> inline std::string type_sname() { return std::string(type_name<T>()); } /* Returns the name of the char* datatype. */ template <> inline constexpr const char* type_name<char*>() { return "char*"; } /* Returns the name of the const char* datatype. */ template <> inline constexpr const char* type_name<const char*>() { return "const char*"; } /* Returns the name of the std::string datatype. */ template <> inline constexpr const char* type_name<std::string>() { return "std::string"; } /* Returns the name of the bool datatype. */ template <> inline constexpr const char* type_name<bool>() { return "bool"; } /* Returns the name of the int8_t datatype. */ template <> inline constexpr const char* type_name<int8_t>() { return "int8_t"; } /* Returns the name of the uint8_t datatype. */ template <> inline constexpr const char* type_name<uint8_t>() { return "uint8_t"; } /* Returns the name of the int16_t datatype. */ template <> inline constexpr const char* type_name<int16_t>() { return "int16_t"; } /* Returns the name of the uint16_t datatype. */ template <> inline constexpr const char* type_name<uint16_t>() { return "uint16_t"; } /* Returns the name of the int32_t datatype. */ template <> inline constexpr const char* type_name<int32_t>() { return "int32_t"; } /* Returns the name of the uint32_t datatype. */ template <> inline constexpr const char* type_name<uint32_t>() { return "uint32_t"; } /* Returns the name of the int64_t datatype. */ template <> inline constexpr const char* type_name<int64_t>() { return "int64_t"; } /* Returns the name of the uint64_t datatype. */ template <> inline constexpr const char* type_name<uint64_t>() { return "uint64_t"; } } #endif
bf1d44d3886f297a53b0ef442dd1224bb8980807
6b2a39df2cd6e626ca042b80d98003f9e47a0b02
/week4/767.ReorganizeString.cpp
9601547f68665901f9aa7c692277efa4e64f613b
[]
no_license
ShuhengLi/LeetCode
0b7db0eaee71b13a8c6324cd837324db31560247
f882fc0fd58857dafdd4b41b1b89c10e56a3f23d
refs/heads/master
2021-06-07T21:15:54.639277
2020-10-20T22:02:46
2020-10-20T22:02:46
28,899,606
0
0
null
null
null
null
UTF-8
C++
false
false
1,191
cpp
767.ReorganizeString.cpp
/*767. Reorganize String * Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. If possible, output any possible result. If not possible, return the empty string. Example 1: Input: S = "aab" Output: "aba" Example 2: Input: S = "aaab" Output: "" */ class Solution { public: typedef pair<int, char> p; string reorganizeString(string S) { int n = S.size(); string res(n, ' '); map<char, int> m; for(auto c:S){ m[c]++; } int half = ceil((double)n / 2); int large = 0; priority_queue<p, vector<p>, greater<p>> q; for(auto it = m.begin(); it != m.end(); it++){ q.push({it->second, it->first}); if(it->second > large){ large = it->second; } } if(large > half) return ""; int t = 1; while(!q.empty()){ auto cur = q.top(); q.pop(); for(int i = 0; i < cur.first; i++){ if(t >= n) t = 0; res[t] = cur.second; t += 2; } } return res; } };
8199a9ea42b29c533fd4a0dde665f4518d57680b
4d827ed761ca8bbd903d77a248db932629c8d6de
/InputManager.cpp
fd08cf42580d54ff032de423e3542dc6f47abeab
[ "Apache-2.0" ]
permissive
ChrSacher/MyEngine
e0e9067678ad4cbffc9d7ca8e500104e28223dfe
8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8
refs/heads/master
2021-10-22T07:09:25.782032
2019-03-09T01:25:28
2019-03-09T01:25:28
38,216,634
0
0
null
null
null
null
UTF-8
C++
false
false
4,375
cpp
InputManager.cpp
#include "InputManager.h" void InputHandler::ScriptCreated(SeScript* SeScript) { ChaiScript &script = SeScript->getState(); script.add(user_type<InputHandler>(), "InputHandler"); script.add_global(var(this), "Input"); script.add(fun(&InputHandler::isKeyDownS), "isKeyDown"); script.add(fun(&InputHandler::isKeyPressedS), "isKeyPressed"); script.add(fun(&InputHandler::isKeyReleasedS), "isKeyReleased"); script.add(fun(&InputHandler::getMouseCoords), "getMouseCoords"); }; void InputHandler::handle(SDL_Event &e) { switch(e.type) { case SDL_MOUSEMOTION: { setMouseCoords(e.motion.x,e.motion.y); }; case SDL_KEYUP: { releaseKey(e.key.keysym.sym); }break; case SDL_KEYDOWN: { pressKey(e.key.keysym.sym); }break; case SDL_MOUSEBUTTONDOWN: { pressKey(e.button.button); };break; case SDL_MOUSEBUTTONUP: { releaseKey(e.button.button); };break; } isChanged = true; } void InputHandler::update() { for (auto& it : _keyMap) { _previousKeyMap[it.first] = it.second; } } void InputHandler::pressKey(unsigned int keyID) { _keyMap[keyID]=true; } void InputHandler::releaseKey(unsigned int keyID) { _keyMap[keyID]=false; } bool InputHandler::isKeyDown(unsigned int keyID) { auto it=_keyMap.find(keyID); if(it != _keyMap.end()) { return it->second; } else { return false; } } void InputHandler::setMouseCoords(float x,float y) { _mousecoords[0] = x; _mousecoords[1] = y; } bool InputHandler::isKeyPressed(unsigned int keyID) { if (isKeyDown(keyID) == true && wasKeyDown(keyID) == false) { return true; } return false; } bool InputHandler::isKeyReleased(unsigned int keyID) { if (isKeyDown(keyID) != true && wasKeyDown(keyID) != false) { return true; } return false; } bool InputHandler::wasKeyDown(unsigned int keyID) { // We dont want to use the associative array approach here // because we don't want to create a key if it doesnt exist. // So we do it manually auto it = _previousKeyMap.find(keyID); if (it != _previousKeyMap.end()) { // Found the key return it->second; } else { // Didn't find the key return false; } } void InputHandler::generate_input(std::vector<Command*> &command_queue) { for (auto& it : _keyMap) { if(it.second) { auto& r = commands.find(it.first); if(r != commands.end()) { switch(r->second->type) { case KEYDOWN: { if(isKeyDown(it.first)) keyListPressed.push_back(it.first); }break; case KEYPRESSED: { if(isKeyPressed(it.first)) keyListPressed.push_back(it.first); }break; case KEYRELEASED: { if(isKeyReleased(it.first)) keyListPressed.push_back(it.first); };break; default: { std::cout<<"Unknown Input Type"<<std::endl; } } } } } static unsigned int maxCommandsRemembered = 50; if(keyListPressed.size() == 0) return; if(lastCommands.size() > maxCommandsRemembered) { int toReduce = lastCommands.size() - maxCommandsRemembered; lastCommands.erase(lastCommands.begin(),lastCommands.begin() + toReduce); } for(unsigned int i = 0; i < keyListPressed.size();i++) { if(commands[keyListPressed[i]] == NULL) continue; command_queue.push_back(commands[keyListPressed[i]]); lastCommands.push_back(commands[keyListPressed[i]]); } keyListPressed.clear(); } void InputHandler::bind(unsigned int key, Command* command) { auto it = commands.find(key); if(it != commands.end()) { delete(it->second);//delete if existing commands.erase(key); } commands.insert(std::make_pair(key,command)); // key points to newly assigned command ) } Command* InputHandler::getCommand(GLuint ID) { auto r = commands.find(ID); if(r == commands.end()) return NULL; return r->second; } bool InputHandler::isKeyDownS(const std::string &string) { auto &r = stringKeyMap.find(string); if (r == stringKeyMap.end()) return false; return isKeyDown(r->second); } bool InputHandler::isKeyPressedS(const std::string &string) { auto &r = stringKeyMap.find(string); if (r == stringKeyMap.end()) return false; return isKeyPressed(r->second); } bool InputHandler::isKeyReleasedS(const std::string &string) { auto &r = stringKeyMap.find(string); if (r == stringKeyMap.end()) return false; return isKeyReleased(r->second); }
d87c33d461498fa465b46c7ef3565284e4ae48d8
c339b53d49d23b788d85d830ba2c50c2a5999509
/GLOW/32/inside-sphere-view/viewdataviewer.h
f9118f9d20d6afb7781239ba4e7b9d20445bb50e
[]
no_license
ghali/gcb
68ba7a2b47db2483c8fa710d14a6c1433e5ee70c
103874c0ca2f88dfac3b069c278470d13f7b9c25
refs/heads/master
2020-06-24T01:53:33.999331
2019-07-25T11:23:29
2019-07-25T11:23:29
198,814,679
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
h
viewdataviewer.h
/* The following code example is described in the book "Introduction * to Geometric Computing" by Sherif Ghali, Springer-Verlag, 2008. * * Copyright (C) 2008 Sherif Ghali. This code may be freely copied, * modified, or republished electronically or in print provided that * this copyright notice appears in all copies. This software is * provided "as is" without express or implied warranty; not even for * merchantability or fitness for a particular purpose. */ #ifndef OFFVIEWDATAVIEWER_H #define OFFVIEWDATAVIEWER_H #include <string> using std::string; #include "glow.h" using namespace glow; class ViewDataViewer : public GlowComponent { public: ViewDataViewer(GlowComponent* parent, int width, int height); void SetSize(int _width, int _height) { width = _width; height = _height; } void setFOVandZnear(double _fov, double _znear) { fov = _fov; znear = _znear; } void setYawAndPitch(double y, double p) { cameraYaw = y; cameraPitch = p; } protected: void drawAxis(); void setCamera(); virtual void OnEndPaint(); private: int width, height; double fov, znear; double cameraYaw, cameraPitch; }; #endif // OFFVIEWDATAVIEWER_H
56af0621c463e57270f4b360777e7d7fa41359d7
5a84cf73fc6771b6a3375824231f3de91f77e1d5
/load_dump.cpp
135bbe467a48fc2086426598d7e16bc323eecc18
[]
no_license
vuniverdevTeam/projectVuniverCgiBin
4e1ff1e9c79c090512f9b47ca81cd4d1281402bc
83aaf6847ead28405f4a8bba18c2369dfa87e91a
refs/heads/master
2021-01-01T05:48:26.159640
2015-02-26T12:33:17
2015-02-26T12:33:17
30,250,759
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,034
cpp
load_dump.cpp
#include <stdlib.h> #include <iostream> #include <string.h> using namespace std; char buff[200]; char* name; char* value; void read() { short i, j = 0; strcpy(buff, getenv("QUERY_STRING")); char* ptr=buff; for(i = 0; ptr[i] != 0; i++) if(ptr[i] == '='){ ptr[i] = 0; name = new char[i+1]; strcpy(name, ptr); ptr += i+1; break; } //write name for(i = 0; true; i++) if(ptr[i] == '&' || ptr[i] == 0){ ptr[i] = 0; value = new char[i+1]; strcpy(value, ptr); ptr += i; break; }//write value } int main() { read(); cout << "Content-type: text/html\r\n\r\n"; char* require = new char[100]; require = "mysql vuniver -uvuniver -h185.25.117.161 -p5S1CQhvO <"; char* NEW = new char[300]; for(int i = 0; i<strlen(require); i++) { NEW[i] = require[i]; } for(int i = strlen(NEW), j = 0; j<strlen(value); i++,j++) { NEW[i] = value[j]; } system(NEW); cout << "База була оновлена"; }
0a3fdd3133af88ae29399a21196243be1c13c991
600dd5e4d37be7014948e54c83f5a31a3fb181ca
/topcoder/srm594/FoxAndGo3.cc
8f075d977627aad862c94cdac919c40a03a94e60
[]
no_license
wolf5x/acmcode
daabffac7435ea7c72ed5336475201f846bf5ddc
6e1ab3678edcab310be6d765c73a2c7339e03c1c
refs/heads/master
2020-06-04T12:45:01.592103
2014-05-17T03:47:59
2014-05-17T03:47:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,283
cc
FoxAndGo3.cc
#include <cstdlib> #include <cctype> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <iostream> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <fstream> #include <numeric> #include <iomanip> #include <bitset> #include <list> #include <stdexcept> #include <functional> #include <utility> #include <ctime> using namespace std; #define PB push_back #define MP(x,y) make_pair((x),(y)) #define FI(x) ((x).first) #define SE(x) ((x).second) #define SZ(x) ((x).size()) #define LEN(x) ((x).length()) #define REP(i,n) for(int i=0;i<(n);++i) #define FOR(i,l,h) for(int i=(l);i<=(h);++i) #define FORD(i,h,l) for(int i=(h);i>=(l);--i) #define FORIT(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i) #define FORRIT(i,c) for(typeof((c).rbegin()) i=(c).rbegin(); i!=(c).rend(); ++i) #define CLR(x) memset((x),0,sizeof(x)) #define SET(x,y) memset((x),(y),sizeof(x)) typedef vector<int> VI; typedef vector<string> VS; typedef vector<double> VD; typedef long long LL; typedef pair<int,int> PII; const int Ni = 2510; const int MAX = 1<<26; struct Edge{ int u,v,c; int next; }edge[20*Ni]; int n,m; int edn;//边数 int p[Ni];//父亲 int d[Ni]; int sp,tp;//原点,汇点 void addedge(int u,int v,int c) { edge[edn].u=u; edge[edn].v=v; edge[edn].c=c; edge[edn].next=p[u]; p[u]=edn++; edge[edn].u=v; edge[edn].v=u; edge[edn].c=0; edge[edn].next=p[v]; p[v]=edn++; } int bfs() { queue <int> q; memset(d,-1,sizeof(d)); d[sp]=0; q.push(sp); while(!q.empty()) { int cur=q.front(); q.pop(); for(int i=p[cur];i!=-1;i=edge[i].next) { int u=edge[i].v; if(d[u]==-1 && edge[i].c>0) { d[u]=d[cur]+1; q.push(u); } } } return d[tp] != -1; } int dfs(int a,int b) { int r=0; if(a==tp)return b; for(int i=p[a];i!=-1 && r<b;i=edge[i].next) { int u=edge[i].v; if(edge[i].c>0 && d[u]==d[a]+1) { int x=min(edge[i].c,b-r); x=dfs(u,x); r+=x; edge[i].c-=x; edge[i^1].c+=x; } } if(!r)d[a]=-2; return r; } int dinic(int sp,int tp) { int total=0,t; while(bfs()) { while(t=dfs(sp,MAX)) total+=t; } return total; } class FoxAndGo3 { int nn, mm; inline int enc(int r, int c) { return r*mm+c; } public: int maxEmptyCells(vector <string> bb) { edn = 0; memset(p, -1, sizeof(p)); nn = bb.size(), mm = bb[0].size(); int tot = nn*mm; sp = tot, tp = tot+1; int dr[] = {-1,0,1,0}; int dc[] = {0,-1,0,1}; int ans = 0; for (int i = 0; i < nn; i++) { for (int j = 0; j < mm; j++) { if (bb[i][j] == 'o') { ans++; addedge(enc(i,j), tp, 1); for (int k = 0; k < 4; k++) { int tr = i+dr[k], tc = j+dc[k]; if (tr >= 0 && tr < nn && tc >= 0 && tc < mm && bb[tr][tc] == '.') { addedge(enc(tr,tc), enc(i,j), MAX); } } } else if (bb[i][j] == '.') { ans++; addedge(sp, enc(i,j), 1); } } } ans -= dinic(sp, tp); return ans; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"o.o", ".o.", "o.o"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 5; verify_case(0, Arg1, maxEmptyCells(Arg0)); } void test_case_1() { string Arr0[] = {"...", ".o.", "..."} ; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 8; verify_case(1, Arg1, maxEmptyCells(Arg0)); } void test_case_2() { string Arr0[] = {"xxxxx", "xxoxx", "xo.ox", "xxoxx", "xxxxx"} ; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 4; verify_case(2, Arg1, maxEmptyCells(Arg0)); } void test_case_3() { string Arr0[] = {".xox.", ".o.ox", "x.o.o", "ox.ox", ".ox.."} ; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 12; verify_case(3, Arg1, maxEmptyCells(Arg0)); } void test_case_4() { string Arr0[] = {"o.o.o", ".ox..", "oxxxo", "..x..", "o.o.o"} ; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 12; verify_case(4, Arg1, maxEmptyCells(Arg0)); } void test_case_5() { string Arr0[] = {"...", "...", "..."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 9; verify_case(5, Arg1, maxEmptyCells(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { FoxAndGo3 ___test; ___test.run_test(-1); return 0; } // END CUT HERE
253a6a462ac381c74dece2c6a7f98a6f9e2550a9
927c2b11739dccab27a44d5c1c76bbbc38add8f1
/Practice/ZUCCACM/Problem : Train Problem II (卡特兰数+高精度)/Problem : Train Problem II (卡特兰数+高精度)/main.cpp
1dbc1afb24bc1c035cf985b77c446001c114142a
[]
no_license
civinx/ACM_Code
23034ca3eecb9758c3c00a519f61434a526e89cc
d194ee4e2554a29720ac455e6c6f86b3219724ee
refs/heads/master
2021-09-15T06:18:09.151529
2018-05-27T18:07:25
2018-05-27T18:07:25
105,544,957
1
0
null
null
null
null
UTF-8
C++
false
false
6,360
cpp
main.cpp
// // main.cpp // Problem : Train Problem II (卡特兰数+高精度) // // Created by czf on 16/3/31. // Copyright © 2016年 czf. All rights reserved. // #include <iostream> #include <algorithm> #include <string> #include <vector> #include <cmath> #include <cstring> using namespace std; struct BigInterger{ vector<long long> s; static const int BASE = 10; //由于除法算法有缺陷,只能使用十进制储存。 static const int WIDTH = 1; BigInterger(long long num = 0) { *this = num; } BigInterger(const string &s) { *this = s; } BigInterger& operator = (long long num); BigInterger& operator = (const string& str); BigInterger operator + (const BigInterger &b) const; BigInterger operator - (const BigInterger &b) const; BigInterger operator * (const BigInterger &b) const; BigInterger operator / (const BigInterger &b) const; BigInterger operator % (const BigInterger &b) const; BigInterger& operator += (const BigInterger &b); BigInterger& operator -= (const BigInterger &b); BigInterger& operator *= (const BigInterger &b); BigInterger& operator /= (const BigInterger &b); BigInterger& operator %= (const BigInterger &b); bool operator < (const BigInterger &b) const; bool operator > (const BigInterger &b) const; bool operator <= (const BigInterger &b) const; bool operator >= (const BigInterger &b) const; bool operator == (const BigInterger &b) const; bool operator != (const BigInterger &b) const; friend ostream& operator << (ostream &out, const BigInterger& x); friend ostream& operator >> (istream &in, const BigInterger& x); }; BigInterger& BigInterger::operator = (long long num){ s.clear(); do{ s.push_back(num % BASE); num /= BASE; }while(num > 0); return *this; } BigInterger& BigInterger::operator = (const string& str){ s.clear(); int x, len = (str.length() - 1) / WIDTH + 1; for(int i = 0; i < len; i ++){ int end = str.length() - i*WIDTH; int start = max(0, end - WIDTH); sscanf(str.substr(start, end-start).c_str(), "%d", &x); //substr(后缀开始处,位数), c_str(),把string转化为c的char数组 s.push_back(x); } return *this; } BigInterger BigInterger::operator + (const BigInterger &b) const{ BigInterger c; c.s.clear(); for(int i = 0, g = 0; ; i ++){ if (g == 0 && i >= s.size() && i >= b.s.size()) break; int x = g; if (i < s.size()) x += s[i]; if (i < b.s.size()) x += b.s[i]; c.s.push_back(x % BASE); g = x / BASE; } return c; } BigInterger BigInterger::operator - (const BigInterger &b) const{ BigInterger c; c.s.clear(); if (*this < b) c = 0; else{ for (int i = 0, g = 0; i < s.size(); i ++) { int x = g; if (i < b.s.size()) x += s[i] - b.s[i]; else x += s[i]; if (x < 0){ x += BASE; g = -1; }else g = 0; // if (!(i == s.size()-1 && x == 0)) c.s.push_back(x); } for (int i = c.s.size()-1; c.s[i] == 0 && i > 0; c.s.pop_back(),i --); } return c; } BigInterger BigInterger::operator * (const BigInterger &b) const{ BigInterger c; c.s.clear(); if (*this == 0 || b == 0) return c = 0; for (int i = 0; i < s.size(); i ++) { long long g = 0; for (int j = 0; j < b.s.size() || g; j ++, g /= BASE) { if (j < b.s.size()) g += s[i] * b.s[j]; if (i + j < c.s.size()) { g += c.s[i+j]; c.s[i+j] = g % BASE; } else c.s.push_back(g % BASE); } } return c; } BigInterger BigInterger::operator / (const BigInterger &b) const{ //有缺陷。 BigInterger c, temp = *this; c.s.clear(); if (*this < b) return c = 0; for (int i = s.size()-b.s.size(); i >= 0; i --) { int x = 0; while (b * (int)pow(10, i) > temp && i) { i --; if (c.s.size()) c.s.push_back(0); } while (temp >= b*(int)pow(10, i)) { temp -= b*(int)pow(10, i); x ++; } c.s.push_back(x); } reverse(c.s.begin(), c.s.end()); return c; } BigInterger BigInterger::operator % (const BigInterger &b) const{ BigInterger c; c = *this - (*this/b)*b; return c; } BigInterger& BigInterger::operator += (const BigInterger &b) { return *this = *this + b; } BigInterger& BigInterger::operator -= (const BigInterger &b){ return *this = *this - b; } BigInterger& BigInterger::operator *= (const BigInterger &b){ return *this = *this * b; } BigInterger& BigInterger::operator /= (const BigInterger &b){ return *this = *this / b; } BigInterger& BigInterger::operator %= (const BigInterger &b){ return *this = *this % b; } bool BigInterger::operator < (const BigInterger &b) const{ if (s.size() != b.s.size()) return s.size() < b.s.size(); for (int i = s.size()-1; i >= 0; i --) { if (s[i] != b.s[i]) return s[i] < b.s[i]; } return false; } bool BigInterger::operator > (const BigInterger &b) const{ return b < *this; } bool BigInterger::operator <= (const BigInterger &b) const{ return !(b < *this); } bool BigInterger::operator >= (const BigInterger &b) const{ return !(*this < b); } bool BigInterger::operator != (const BigInterger &b) const{ return *this < b || b < *this; } bool BigInterger::operator == (const BigInterger &b) const{ return !(*this < b) && !(b < *this); } ostream& operator << (ostream &out, const BigInterger& x){ out << x.s.back(); for(int i = x.s.size()-2; i >= 0; i --){ char buf[20]; sprintf(buf, "%01lld", x.s[i]); for(int j = 0; j < strlen(buf); j ++) out << buf[j]; } return out; } istream& operator >> (istream &in, BigInterger& x){ string s; if (!(in >> s)) return in; x = s; return in; } int main() { BigInterger a[105]; for (int i = 0; i < 105; i ++) { a[i] = 0; } a[0] = a[1] = 1; for (int i = 2; i <= 100; i ++) { for (int j = 1; j <= i; j ++) { a[i] = a[i] + a[j-1] * a[i-j]; } // cout << i << ' ' << a[i] << endl; } int n; while (cin >> n) { cout << a[n] << endl; } return 0; }
6a19a56c6ab7a06e040e4c92a31fde6a026120b9
1e2cba1a4c0890916e7518f37c8533c82424650d
/test.cpp
f9930810c3de2a0f4fded23db540c39e363486e2
[]
no_license
KeyLD/RBTree
6612d018e60f3b7daa6dd580e227ba9b20d9f97e
76aace26c53babc3c908a764c03a6c13b259ba4e
refs/heads/master
2021-09-08T22:30:37.886279
2018-03-12T14:07:16
2018-03-12T14:07:16
124,658,408
0
0
null
null
null
null
UTF-8
C++
false
false
1,121
cpp
test.cpp
/* *********************************************************************** > File Name: test.cpp > Author: Key > Mail: keyld777@gmail.com > Created Time: Tue 06 Mar 2018 05:15:09 PM CST *********************************************************************** */ #include "kmap.h" #include <iostream> using namespace std; int main() { kmap<int,int> test_map; test_map.insert(makePair(123,1)); test_map.insert(makePair(52,2)); test_map.insert(makePair(324,3)); test_map.insert(makePair(436,4)); test_map.insert(makePair(413,5)); test_map.insert(makePair(525,6)); test_map.insert(makePair(235,7)); test_map.insert(makePair(63,8)); test_map.insert(makePair(346,9)); test_map.insert(makePair(521,10)); test_map.insert(makePair(675,11)); test_map.insert(makePair(240,12)); test_map.erase(675); test_map.erase(413); kmap<int,int>::iterator it = test_map.begin(); while(it != test_map.end()) { printf("%d %d\n",it->first,it->second); it++; } //puts("bfsPrint here:"); //test_map.bfsPrint(); return 0; }
3a9c35674309b9ca5790734e258a4e2e2a435984
f5a10483d3cba20abf49d35576afed19af358a52
/sketch_aug12a.ino
f6e663de6ed6450684af7c7c62a7c742efa1359e
[]
no_license
Tyronezzz/Arduino_getinfo
cf637326d72b9d78fce408c5d2dfbff92cb66060
26da678f82180f1d9e761065d997cc144799ebf7
refs/heads/master
2021-01-16T20:21:25.438617
2017-08-13T20:21:25
2017-08-13T20:21:25
100,202,429
0
0
null
null
null
null
UTF-8
C++
false
false
952
ino
sketch_aug12a.ino
unsigned long last_time = 0; String comdata = ""; int port = 13; char isn; void setup() { Serial.begin(115200); while(Serial.read()>=0){} //清空串口缓存 pinMode(port, OUTPUT); } void loop() { while(Serial.available()>0) { //comdata += char( Serial.read()); isn = char( Serial.read()); if(isn=='\n' &&comdata=="666") { Serial.println(comdata); digitalWrite(port, HIGH); delay(10); digitalWrite(port, LOW); comdata=""; // break; } else if(isn=='6') { comdata += isn; delay(2); } else if(comdata.length()>=4 && comdata!="666") { comdata=""; } // else // { // comdata=""; // } } }
82763649728cea4257bdc61e19168c72b83b730e
2304dc468bbe40b2a9f9466df85bfa674e9a123d
/util/test/TestBox.cpp
d936dd401541d233533947de35a5bc9c04b9cd84
[]
no_license
ab-vm/ab
a330a5ea53537a8c00dc90ecee11a4b2b0a8fcc8
173f56d0e1fc93e1cfefe5711c6df91a9552a467
refs/heads/master
2021-01-15T19:03:57.673408
2019-12-14T15:41:17
2019-12-14T15:41:17
99,801,785
7
1
null
2019-12-14T15:41:18
2017-08-09T11:40:44
WebAssembly
UTF-8
C++
false
false
561
cpp
TestBox.cpp
#include <Ab/Box.hpp> #include <gtest/gtest.h> using namespace Ab; class Destructor {}; TEST(TestBox, defaultConstructor) { Box<int> box{IN_PLACE}; box() = 1; EXPECT_EQ(box(), 1); } TEST(TextBox, copyConstructor) { Box<int> b{5}; EXPECT_EQ(b(), 5); } struct MyStruct { int x; }; TEST(TestBox, Constructor) { Box<MyStruct> box{MyStruct{2}}; EXPECT_EQ(box().x, 2); } TEST(TestBox, BoxBox) { Box<int> box1{5}; EXPECT_EQ(box1(), 5); Box<Box<int>> box2{box1}; EXPECT_EQ(box2()(), 5); Box<Box<Box<int>>> box3{box2}; EXPECT_EQ(box3()()(), 5); }
ea806dd31a297d7a0464b5aab2636d540449e176
dbed5e361a7e9ec4c4a20ed0de84b599a1c30f02
/InternalRepresentations/NibbleState/NibbleState.cpp
8c9f223ba0cbe9f0410c4df3f07e30b62abc03e9
[ "MIT" ]
permissive
H3LLB0Y/8PuzzleBenchmark
00eca5ee455c3c577119a589ff7030f6c297aea7
48a2c73963d260022a51da4e56ed43cdc6bc2c7d
refs/heads/master
2023-05-04T17:34:43.697225
2021-05-15T20:38:33
2021-05-15T20:38:33
367,588,364
0
0
null
null
null
null
UTF-8
C++
false
false
3,283
cpp
NibbleState.cpp
#include "NibbleState.h" #include "../InternalRepresentation.h" #include <stdexcept> #include <string> unsigned char characterToNibble(char character) { switch (character) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return character - '0'; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return character - 'A' + 0xA; default: throw std::invalid_argument("Character must be a HEX character!"); } } char nibbleToCharacter(unsigned char nibble) { if (nibble < 0xA) { return '0' + nibble; } else { return 'A' - 0xA + nibble; } } NibbleState nibbleInPlace(NibbleState nibbleState, int x, int y) { return nibbleState & ((NibbleState) 0xF << ((y * 4 + x) * 4)); } template<> std::string internalRepresentationName<NibbleState>() { return "NibbleState"; } template<> NibbleState stringToIR<NibbleState>(const std::string &state) { NibbleState nibbleState = 0ULL; switch (state.length()) { case 9: for (int y = 0; y < 3; ++y) { for (int x = 0; x < 3; ++x) { // TODO: Utility functions! for 2D->1D NibbleState character = characterToNibble(state[y * 3 + x]); nibbleState |= character << ((y * 4 + x) * 4); } } break; case 16: for (int y = 0; y < 4; ++y) { for (int x = 0; x < 4; ++x) { NibbleState character = characterToNibble(state[y * 4 + x]); nibbleState |= character << ((y * 4 + x) * 4); } } break; default: throw std::invalid_argument("State must be either 9 or 16 characters long!"); } return nibbleState; } template<> std::string stringFromIR<NibbleState>(NibbleState state) { std::string string; string.reserve(16); // TODO: Do for 16 for (int y = 0; y < 3; ++y) { for (int x = 0; x < 3; ++x) { int index = (y * 4 + x) * 4; char character = nibbleToCharacter((state >> index) & 0xF); string += character; } } return string; } template<> NibbleState adjust<NibbleState>(NibbleState state, int x, int y, MovementType movementType) { switch (movementType) { case MovementType::UP: --y; break; case MovementType::RIGHT: ++x; break; case MovementType::DOWN: ++y; break; case MovementType::LEFT: --x; break; } NibbleState inPlace = nibbleInPlace(state, x, y); state ^= inPlace; switch (movementType) { case MovementType::UP: inPlace <<= 4 * 4; break; case MovementType::RIGHT: inPlace >>= 1 * 4; break; case MovementType::DOWN: inPlace >>= 4 * 4; break; case MovementType::LEFT: inPlace <<= 1 * 4; break; } state |= inPlace; return state; }
e8e787fd26180d3f5a2349b073e0128c75bc84af
6db54cff6d29bbaa597c5c80e0632dac0eb39a26
/source/VkRenderer/Enum/VkAttachmentLoadOp.cpp
6180ab9b87952d0f12bf77ade245b711439cdfc6
[ "MIT" ]
permissive
Chaanks/Ashes
62fdcb6aaf558b6b80f18c9961c94f05251362df
e3d2b42b7b3e9aced385e203bbe6badddb2166ec
refs/heads/master
2020-05-19T07:10:07.618947
2019-05-04T10:57:11
2019-05-04T10:57:11
184,881,467
0
0
null
2019-05-04T10:33:32
2019-05-04T10:33:32
null
UTF-8
C++
false
false
521
cpp
VkAttachmentLoadOp.cpp
#include "VkRendererPrerequisites.hpp" namespace vk_renderer { VkAttachmentLoadOp convert( ashes::AttachmentLoadOp const & value ) { switch ( value ) { case ashes::AttachmentLoadOp::eLoad: return VK_ATTACHMENT_LOAD_OP_LOAD; case ashes::AttachmentLoadOp::eClear: return VK_ATTACHMENT_LOAD_OP_CLEAR; case ashes::AttachmentLoadOp::eDontCare: return VK_ATTACHMENT_LOAD_OP_DONT_CARE; default: assert( false && "Unsupported AttachmentLoadOp" ); return VK_ATTACHMENT_LOAD_OP_DONT_CARE; } } }
75cef18fe33390822d1732831e019ddeb414b73c
f20e965e19b749e84281cb35baea6787f815f777
/Online/Online/ExampleGaucho/src/GaudiExample.cpp
b21779fea3a5fc973aa6411104e53ab455aa5efb
[]
no_license
marromlam/lhcb-software
f677abc9c6a27aa82a9b68c062eab587e6883906
f3a80ecab090d9ec1b33e12b987d3d743884dc24
refs/heads/master
2020-12-23T15:26:01.606128
2016-04-08T15:48:59
2016-04-08T15:48:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,240
cpp
GaudiExample.cpp
// $Id: GaudiExample.cpp,v 1.17 2010-10-01 13:43:45 frankb Exp $ // Include files #include "GaudiKernel/AlgFactory.h" #include "GaudiKernel/DataObject.h" #include "Gaucho/MonStatEntity.h" #include "Gaucho/MonVectorI.h" #include "Gaucho/MonVectorD.h" #include "GaudiExample.h" #include "AIDA/IHistogram1D.h" #include "AIDA/IHistogram2D.h" #include "AIDA/IHistogram3D.h" #include "AIDA/IProfile1D.h" #include "AIDA/IProfile2D.h" #include "AIDA/IAxis.h" #include <cstring> #include <cmath> #include "GaudiUtils/Aida2ROOT.h" #include "TH1D.h" #ifdef WIN32 namespace win { #include <windows.h> } # define mysleep(x) win::Sleep(x) #else # include <unistd.h> # define mysleep(x) usleep(x*1000000) #endif // Static Factory declaration DECLARE_ALGORITHM_FACTORY(GaudiExample) // Constructor //------------------------------------------------------------------------------ GaudiExample::GaudiExample(const std::string& name, ISvcLocator* ploc) : GaudiHistoAlg(name, ploc) // ,statEntity(msgSvc(), name,0) ,monVectorInt(msgSvc(), name,0) ,monVectorDouble(msgSvc(), name,0) { declareProperty("SleepTime",sleepTime=1); // Sleeping time between events, in seconds } //------------------------------------------------------------------------------ StatusCode GaudiExample::initialize() { //------------------------------------------------------------------------------ StatusCode sc = Algorithm::initialize(); // must be executed first MsgStream msg(msgSvc(), name()); sc = service("HistogramDataSvc", m_histosvc, true ); if( !sc.isSuccess() ){ msg << MSG::FATAL << "Unable to locate HistogramSvc" << endreq; return sc; } counter1=0; // "All events" counter2=0; // "Event of type 1" count_rate_1=0; count_rate_2=0; efficiency1 = 0; // "Ratio counter2/counter1" aboveRef = false; // "true if efficiency > 0.55" efficiency2=0.0; // "3090 < mass < 310" position.first = 0; position.second = 0; index.first = 0; index.second = 0; ix.first = 0.; ix.second = 0; m_eventsCounter = counter("#events"); oldStatus=new char[20]; // For histos debugging nbinEntries=0; sumOfWeights=0; sumOfSquaredWeights=0; // No need to instantiate explicitly the MonitorScv. The GaudKernel/Algorithm has // a method declareInfo that and do this automatically for you msg << MSG::INFO << "Declaring infos to be published" << endreq; declareInfo("counter1",counter1,"All events"); declareInfo("counter2",counter2,"Event of type 1"); declareInfo("COUNTER_TO_RATE[#events]",m_eventsCounter,"Events accepted"); declareInfo("#test",counter("#test"),"test"); // msg << MSG::INFO << "Test: Try to publish info with a name already used. Not possible" << endreq; declareInfo("counter2",counter2,"Event type 1"); declareInfo("efficiency1",efficiency1,"Ratio type 1/all"); declareInfo("aboveRef",aboveRef,"#events is above reference"); // msg << MSG::INFO << "Test: No declareInfo for char* type. By default, will use bool instead!" << endreq; // declareInfo("oldStatus",oldStatus,"Previous Trigger status"); declareInfo("status",status,"Trigger status"); declareInfo("efficiency2",efficiency2,"Time rate 1-2"); // It doesn't work because there are not pairs II nor pairs DI in IMonitorSvc // The IMonitorSvc Interface Misunderstand and declare this two pairs as DD declareInfo("index",index,"ij indices (pair of ints)"); declareInfo("ix",ix,"i -> x map (pair of double-int)"); declareInfo("position",position,"xy position (pair of doubles)"); // IMonitorSvc has no declareInfo methods for MonObjects. // But we publish MonObjects using the obsolete declareInfo for void * // notice that the second and four arguments are obsoletes monVectorInt.setValue(m_vectInt); declareInfo("vectorInts", "", &monVectorInt, 0, "std::vector of ints"); monVectorDouble.setValue(m_vectDouble); declareInfo("vectorDoubles", "", &monVectorDouble, 0, "std::vector of doubles"); // This is only for counters which will be monitorated as rates // Obs: the description should be "COUNTER_TO_RATE" declareInfo("COUNTER_TO_RATE[count_rate_1]", count_rate_1, "Counter number 1"); declareInfo("COUNTER_TO_RATE[count_rate_2]", count_rate_2, "Counter number 2"); // declareInfo("count2", count_rate_2); // For histograms, either declare explicitly here using histosvc, or // use plot methods from class GaudiHistos in GaudiExample::execute(), see my1Dhisto1 below effHisto = m_histosvc->book("effHisto","Efficiency (counter2/counter1)",10,0.,1.); declareInfo("effHisto",effHisto,"Efficiency (counter2/counter1)"); time(&time_old); // use Random Number Service to generate events sc = random1.initialize(randSvc(), Rndm::Flat(0.,1.)); if ( !sc.isSuccess() ) { return sc; } sc = random2.initialize(randSvc(), Rndm::Gauss(3096.,10.)); if ( !sc.isSuccess() ) { return sc; } sc = random3.initialize(randSvc(), Rndm::Gauss(892.,50.3)); if ( !sc.isSuccess() ) { return sc; } sc = random4.initialize(randSvc(), Rndm::Poisson(5)); if ( !sc.isSuccess() ) { return sc; } return StatusCode::SUCCESS; } //------------------------------------------------------------------------------ StatusCode GaudiExample::execute() { //------------------------------------------------------------------------------ MsgStream msg( msgSvc(), name() ); msg << MSG::DEBUG << "******************************************" << endreq; msg << MSG::DEBUG << "execute method...." << endreq; int eventtype; counter1=counter1+3; count_rate_1=count_rate_1+3; count_rate_2=count_rate_2+2; counter("#events")++; counter("#test")=counter("#test")+2; time(&time_new); msg << MSG::DEBUG << "Current event: " << counter1 << " Current time: " << time_new << endreq; // For histograms, use plot methods from class GaudiHistos: // E.g.: AIDA::IHistogram1D* plot1D ( value, title, low, high, bins, weight ); std::string Histo1Da_ID; std::string Histo1Da_Title; std::string Histo1Db_ID; std::string Histo1Db_Title; std::string Histo2D_ID; std::string Histo2D_Title; std::string HistoProf_ID; std::string HistoProf_Title; Histo1Da_Title = "Event type"; Histo1Db_Title = "Mass plot"; Histo2D_Title = "Plot of position in XY plane"; HistoProf_Title = "Profile histo of y(x)"; // rearrange this to make it easy to change the nb of histograms unsigned int nHisto=2; for (unsigned int i=0;i<nHisto;i++) { Histo1Da_ID = "1Da"+boost::lexical_cast<std::string>(i); Histo1Db_ID = "1Db"+boost::lexical_cast<std::string>(i); Histo2D_ID = "2D"+boost::lexical_cast<std::string>(i); HistoProf_ID= "Prof"+boost::lexical_cast<std::string>(i); float dice1 = float(random1()); if(dice1 > 0.9 ) eventtype=0; // To test UNDERFLOW if(dice1 > 0.5 ) eventtype=1; else if(dice1 > 0.4) eventtype=2; else if(dice1 > 0.25) eventtype=3; else if(dice1 > 0.2) eventtype=4; else if(dice1 > 0.1) eventtype=5; else eventtype=15; // Just to test OVERFLOW IHistogram1D * my1Dhisto1 = plot1D(eventtype,Histo1Da_ID,Histo1Da_Title,0.5, 5.5,5); msg << MSG::DEBUG << Histo1Da_ID << ": Bin entries: " << my1Dhisto1->binEntries(AIDA::IAxis::UNDERFLOW_BIN) << " -"; for(int jxBin=0; jxBin<my1Dhisto1->axis().bins();++jxBin) msg << MSG::DEBUG << " " << my1Dhisto1->binEntries(jxBin); msg << MSG::DEBUG << " - " << my1Dhisto1->binEntries(AIDA::IAxis::OVERFLOW_BIN) ; msg << MSG::DEBUG << " errors: " << my1Dhisto1->binError(AIDA::IAxis::UNDERFLOW_BIN) << " -"; for(int jxBin=0; jxBin<my1Dhisto1->axis().bins();++jxBin) msg << MSG::DEBUG << " " << my1Dhisto1->binError(jxBin); msg << MSG::DEBUG << " - " << my1Dhisto1->binError(AIDA::IAxis::OVERFLOW_BIN) << endreq; double mass; if(1 == eventtype) mass = random2(); else if(2 == eventtype) mass = random3(); else mass = 2800+random1()*500; IHistogram1D * my1Dhisto2 = plot1D(mass,Histo1Db_ID,Histo1Db_Title,2900., 3200., 30); TH1D *h = Gaudi::Utils::Aida2ROOT::aida2root( my1Dhisto1 ); if ( 0 != h ) { // get the axis: TAxis* axis = h->GetXaxis() ; if( 0 != axis ) { // loop over bins: // for ( int ibin = 1; ibin < 6 ; ++ibin ) { // char * test = "Test label "+ibin; // msg << MSG::DEBUG << " bin " << ibin << " heeft als naam " << test << endreq; axis-> SetBinLabel ( 1, "bin 1" ); axis-> SetBinLabel ( 2, "bin 2" ); axis-> SetBinLabel ( 3, "bin 3" ); axis-> SetBinLabel ( 4, "bin 4" ); axis-> SetBinLabel ( 5, "bin 5" ); // } } } position.first = random1()*400; position.second = random1()*300; IHistogram2D * my2Dhisto = plot2D(position.first, position.second, Histo2D_ID, Histo2D_Title, 0., 400., 0., 300., 10, 10); IProfile1D * my1Dhprof = profile1D(position.first, position.second, HistoProf_ID, HistoProf_Title, 0., 400., 10); // Debug info: msg << MSG::DEBUG << Histo1Db_ID << " All entries: " << my1Dhisto2->allEntries() << " mean: " << my1Dhisto2->mean() << " rms: " << my1Dhisto2->rms() << endreq; msg << MSG::DEBUG << Histo2D_ID << " All entries: " << my2Dhisto->allEntries() << " meanX: " << my2Dhisto->meanX() << " rmsX: " << my2Dhisto->rmsX() << " meanY: " << my2Dhisto->meanY() << " rmsY: " << my2Dhisto->rmsY() << endreq; msg << MSG::DEBUG << HistoProf_ID << " All entries: " << my1Dhprof->allEntries() << " mean: " << my1Dhprof->mean() << " rms: " << my1Dhprof->rms() << endreq; // Track calculations for bin 3 in last my1Dhprof: int ixBin=3; if (int(position.first/400*10) == ixBin ){ sumOfWeights += position.second; sumOfSquaredWeights += position.second*position.second; /* msg << MSG::DEBUG << HistoProf_ID << ": all entries: " << counter1 << " x: " << position.first << " y: " << position.second << " bin: " << ixBin << " binEntries: " << nbinEntries << " sumOfWeights: " << sumOfWeights << " sumOfSquaredWeights: " << sumOfSquaredWeights << endreq; msg << MSG::DEBUG << HistoProf_ID << ": ixBin " << ixBin << " entries " << my1Dhprof->binEntries(ixBin) << " mean " << my1Dhprof->binHeight(ixBin) << " rms " << my1Dhprof->binRms(ixBin) << " error " << my1Dhprof->binError(ixBin) << endreq;*/ } } // (Track only last loop step above): if(1 == eventtype) counter2++; efficiency1= float(counter2)/counter1; effHisto->fill(efficiency1); /* msg << MSG::DEBUG << "Event: " << counter1 << " counter2: " << counter2 << " efficiency1: " << efficiency1 << " effHisto content: "; for(int i=0; i<= effHisto->axis().bins();++i){ msg << MSG::DEBUG << effHisto->binEntries(i) << " ";} msg << MSG::DEBUG<< endreq;*/ status="Normal"; if(efficiency1 > .55 ) { aboveRef = true; strcpy(oldStatus,status.c_str()); status="High"; } index.first = (int)(random1()*10); index.second = (int)(random1()*20); ix.first = random1()*50; ix.second = (int)(ix.first); if (counter1 % 50 == 0) { efficiency2=float(counter2)/(time_new-time_old); } int nD=(int)random4(); m_vectDouble.clear(); for(int i=0;i<nD;++i)m_vectDouble.push_back(random1()*100); /* msg << MSG::DEBUG << "Filled a vector of doubles with " << m_vectDouble.size() << " elements: "; for(std::vector<double>::iterator iD=m_vectDouble.begin();iD != m_vectDouble.end();++iD) msg << MSG::DEBUG << *iD << " "; msg << MSG::DEBUG << endreq;*/ monVectorDouble.setValue(m_vectDouble); // Print content from monVectorDouble to check if(MSG::DEBUG == msgSvc()->outputLevel(name())) monVectorDouble.print(); int nI=(int)random4(); m_vectInt.clear(); for(int i=0;i<nI;++i)m_vectInt.push_back((int)(random1()*50)); /* msg << MSG::INFO << "Filled a vector of integers with " << m_vectInt.size() << " elements: "; for(std::vector<int>::iterator iI=m_vectInt.begin();iI != m_vectInt.end();++iI) msg << MSG::DEBUG << *iI << " "; msg << MSG::INFO << endreq;*/ monVectorInt.setValue(m_vectInt); // Print content from monVectorInt to check if(MSG::DEBUG == msgSvc()->outputLevel(name())) monVectorInt.print(); // delay mysleep(sleepTime); msg << MSG::DEBUG << "******************************************" << endreq; return StatusCode::SUCCESS; } //------------------------------------------------------------------------------ StatusCode GaudiExample::finalize() { //------------------------------------------------------------------------------ MsgStream msg(msgSvc(), name()); msg << MSG::INFO << "finalizing...." << endreq; // Print the final contents of the Profile1D histogram AIDA::IProfile1D* my1Dhprof = profile1D(std::string("Profile histo of y(x)")); msg << MSG::DEBUG << "GaudiExample: final contents of the Profile1D histogram my1Dhprof:" << endreq; msg << MSG::DEBUG << "ixBin " << "UNDERFLOW" << " entries " << my1Dhprof->binEntries(AIDA::IAxis::UNDERFLOW_BIN) << " mean " << my1Dhprof->binHeight(AIDA::IAxis::UNDERFLOW_BIN) << " rms " << my1Dhprof->binRms(AIDA::IAxis::UNDERFLOW_BIN) << " error " << my1Dhprof->binError(AIDA::IAxis::UNDERFLOW_BIN) << endreq; int nXBins = my1Dhprof->axis().bins(); for (int ixBin=0; ixBin< nXBins; ixBin++){ msg << MSG::DEBUG << "ixBin " << ixBin << " entries " << my1Dhprof->binEntries(ixBin) << " mean " << my1Dhprof->binHeight(ixBin) << " rms " << my1Dhprof->binRms(ixBin) << " error " << my1Dhprof->binError(ixBin) << endreq; } msg << MSG::DEBUG << "ixBin " << "OVERFLOW" << " entries " << my1Dhprof->binEntries(AIDA::IAxis::OVERFLOW_BIN) << " mean " << my1Dhprof->binHeight(AIDA::IAxis::OVERFLOW_BIN) << " rms " << my1Dhprof->binRms(AIDA::IAxis::OVERFLOW_BIN) << " error " << my1Dhprof->binError(AIDA::IAxis::OVERFLOW_BIN) << endreq; return StatusCode::SUCCESS; }
7c61021ac87209ddcdc06f699ed9905f7c5a9514
711504d90b90c717cf7213822f60aac6eb99ab87
/133.cpp
9aea5afbf5ebd1fde8dad0552623d1a04815b5af
[]
no_license
ysc6688/leetcode
b646c2027c41fb677f14186f4d2df612f29e7749
f9028ac42d0d5db1bf8f6c87c7b2a59046a3856c
refs/heads/master
2021-01-24T10:36:04.438381
2016-09-20T15:38:29
2016-09-20T15:38:29
53,134,158
0
0
null
null
null
null
UTF-8
C++
false
false
1,341
cpp
133.cpp
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ struct hash_func { size_t operator()(const UndirectedGraphNode* node) const { return node->label*31; } }; typedef unordered_map<UndirectedGraphNode *,UndirectedGraphNode *,hash_func> HASH; class Solution { public: UndirectedGraphNode *dfs(UndirectedGraphNode* node, HASH &hash) { UndirectedGraphNode *root = new UndirectedGraphNode(node->label); hash.insert(make_pair(node,root)); vector<UndirectedGraphNode *> &nbrs = node->neighbors; for(int i = 0; i < nbrs.size(); ++ i) { if(nbrs[i] == node) root->neighbors.push_back(root); else { HASH::iterator it = hash.find(nbrs[i]); if(it != hash.end()) root->neighbors.push_back(it->second); else root->neighbors.push_back(dfs(nbrs[i],hash)); } } return root; } UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if( !node ) return NULL; HASH hash; return dfs(node,hash); } };
320f16452576dd9a2bd0d095e2f1d18f07688c2a
0d085b4ee7537095ff0d0b1f12cb486329800dce
/Lang/Constructor/main.cpp
8e0105fd3206184bf32e9db4cf2fe6ec45f484ac
[]
no_license
YongHoonJJo/CPP
f3043e5bca1314fa9954e82fb3b481ef25a56c6f
1cfdda3fddb86d7f010401bbc9bfc4330e9cd324
refs/heads/master
2021-01-02T23:04:51.188049
2017-09-03T11:09:31
2017-09-03T11:09:31
99,462,878
0
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
main.cpp
#include <iostream> #include "cat.h" using namespace std; int main(){ cat A; A.print(); // 이름: , 나이: 0 A.set(3, "Pine"); A.print(); // 이름: Pine, 나이: 3 A.set(5); A.print(); // 이름: Pine, 나이: 5 A.set("Odd"); A.print(); // 이름: Odd, 나이: 5 cat B(5); B.print(); // 이름: , 나이: 5 cat C("Hoon"); C.print(); // 이름: Hoon, 나이: 0 cat D(10, "JJo"); D.print(); // 이름: JJo, 나이: 10 /*** explicit constructor call ***/ // return temporary object..!! cat E = cat("Happy"); E.print(); // 이름: Happy, 나이: 0 E = cat(); E.print(); // 이름: , 나이: 0 E = cat(15, "YH"); E.print(); // 이름: YH, 나이: 15 /*** copy constructor ***/ cat F(E); F.print(); // 이름: YH, 나이: 15 return 0; }
0e02016d2d17190fd09f51163d233f685b6ebf2d
b5f0a4540d122b98e7c11196544e44c597decbe7
/Ejercicio Resueltos por mi/Punteros.cpp
d968ec1c940088f2d92d24bf92c0886b7fbd84a4
[]
no_license
joaquinheliop/CPP-Practicas-
964f604c7429842235cacf8a5a8e0013a3167d53
ab1276126b17632e54f7dc95cbb41916b5c9a41c
refs/heads/main
2023-08-14T05:50:55.573323
2021-10-07T18:55:11
2021-10-07T18:55:11
410,961,049
0
0
null
null
null
null
UTF-8
C++
false
false
267
cpp
Punteros.cpp
#include<iostream> #include<conio.h> using namespace std; int main() { int num, *dir_num; num = 20; dir_num = &num; cout<<"Numero: "<<*dir_num<<endl; cout<<"Direccion de memoria de mi variable: "<<dir_num<<endl; getch(); return 0; }
5bf5ef6151722fba113ab3ca7ae5a6ed4992e8ae
d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3
/chromium/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc
0a99ca6a50b28b475334fc5b7b41be533a6d5144
[ "BSD-3-Clause" ]
permissive
Csineneo/Vivaldi
4eaad20fc0ff306ca60b400cd5fad930a9082087
d92465f71fb8e4345e27bd889532339204b26f1e
refs/heads/master
2022-11-23T17:11:50.714160
2019-05-25T11:45:11
2019-05-25T11:45:11
144,489,531
5
4
BSD-3-Clause
2022-11-04T05:55:33
2018-08-12T18:04:37
null
UTF-8
C++
false
false
30,676
cc
shared_memory_data_consumer_handle_unittest.cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/loader/shared_memory_data_consumer_handle.h" #include <stddef.h> #include <string.h> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/callback.h" #include "base/location.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/task_runner.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" #include "content/public/renderer/fixed_received_data.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" namespace content { namespace { using blink::WebDataConsumerHandle; using Result = WebDataConsumerHandle::Result; using Writer = SharedMemoryDataConsumerHandle::Writer; const WebDataConsumerHandle::Flags kNone = WebDataConsumerHandle::kFlagNone; const Result kOk = WebDataConsumerHandle::kOk; const Result kDone = WebDataConsumerHandle::kDone; const Result kShouldWait = WebDataConsumerHandle::kShouldWait; const Result kUnexpectedError = WebDataConsumerHandle::kUnexpectedError; using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::MockFunction; using ::testing::Return; using ::testing::StrictMock; using Checkpoint = StrictMock<MockFunction<void(int)>>; using ReceivedData = RequestPeer::ReceivedData; class Logger final : public base::RefCounted<Logger> { public: Logger() {} void Add(const std::string& entry) { log_ += entry + "\n"; } const std::string& log() const { return log_; } private: friend class base::RefCounted<Logger>; ~Logger() {} std::string log_; DISALLOW_COPY_AND_ASSIGN(Logger); }; class LoggingFixedReceivedData final : public RequestPeer::ReceivedData { public: LoggingFixedReceivedData(const char* name, const char* s, scoped_refptr<Logger> logger) : name_(name), data_(s, s + strlen(s)), logger_(logger) {} ~LoggingFixedReceivedData() override { logger_->Add(name_ + " is destructed."); } const char* payload() override { return data_.empty() ? nullptr : &data_[0]; } int length() override { return static_cast<int>(data_.size()); } private: const std::string name_; const std::vector<char> data_; scoped_refptr<Logger> logger_; DISALLOW_COPY_AND_ASSIGN(LoggingFixedReceivedData); }; class DestructionTrackingFunction : public base::RefCountedThreadSafe<DestructionTrackingFunction> { public: MOCK_METHOD0(Destruct, void(void)); MOCK_METHOD0(Call, void(void)); protected: friend class base::RefCountedThreadSafe<DestructionTrackingFunction>; virtual ~DestructionTrackingFunction() { Destruct(); } }; class MockClient : public WebDataConsumerHandle::Client { public: MOCK_METHOD0(DidGetReadable, void()); }; std::string ToString(const void* p, size_t size) { const char* q = static_cast<const char*>(p); return std::string(q, q + size); } class ThreadedSharedMemoryDataConsumerHandleTest : public ::testing::Test { protected: class ReadDataOperation; class ClientImpl final : public WebDataConsumerHandle::Client { public: explicit ClientImpl(ReadDataOperation* operation) : operation_(operation) {} void DidGetReadable() override { operation_->ReadData(); } private: ReadDataOperation* operation_; }; class ReadDataOperation final { public: typedef WebDataConsumerHandle::Result Result; ReadDataOperation( std::unique_ptr<SharedMemoryDataConsumerHandle> handle, scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner, const base::Closure& on_done) : handle_(std::move(handle)), main_thread_task_runner_(std::move(main_thread_task_runner)), on_done_(on_done) {} const std::string& result() const { return result_; } void ReadData() { if (!client_) { client_.reset(new ClientImpl(this)); reader_ = handle_->ObtainReader( client_.get(), blink::scheduler::GetSingleThreadTaskRunnerForTesting()); } Result rv = kOk; size_t read_size = 0; while (true) { char buffer[16]; rv = reader_->Read(&buffer, sizeof(buffer), kNone, &read_size); if (rv != kOk) break; result_.insert(result_.size(), &buffer[0], read_size); } if (rv == kShouldWait) { // Wait a while... return; } if (rv != kDone) { // Something is wrong. result_ = "error"; } // The operation is done. reader_.reset(); main_thread_task_runner_->PostTask(FROM_HERE, on_done_); } private: std::unique_ptr<SharedMemoryDataConsumerHandle> handle_; std::unique_ptr<WebDataConsumerHandle::Reader> reader_; std::unique_ptr<WebDataConsumerHandle::Client> client_; scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; base::Closure on_done_; std::string result_; }; void SetUp() override { handle_ = std::make_unique<SharedMemoryDataConsumerHandle>(&writer_); } StrictMock<MockClient> client_; std::unique_ptr<SharedMemoryDataConsumerHandle> handle_; std::unique_ptr<Writer> writer_; base::test::ScopedTaskEnvironment task_environment_; }; class SharedMemoryDataConsumerHandleTest : public testing::Test { protected: void SetUp() override { handle_ = std::make_unique<SharedMemoryDataConsumerHandle>(&writer_); } std::unique_ptr<FixedReceivedData> NewFixedData(const char* s) { return std::make_unique<FixedReceivedData>(s, strlen(s)); } StrictMock<MockClient> client_; std::unique_ptr<SharedMemoryDataConsumerHandle> handle_; std::unique_ptr<Writer> writer_; base::test::ScopedTaskEnvironment task_environment_; }; void RunPostedTasks() { base::RunLoop run_loop; blink::scheduler::GetSingleThreadTaskRunnerForTesting()->PostTask( FROM_HERE, run_loop.QuitClosure()); run_loop.Run(); } TEST_F(SharedMemoryDataConsumerHandleTest, ReadFromEmpty) { char buffer[4]; size_t read = 88; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); Result result = reader->Read(buffer, 4, kNone, &read); EXPECT_EQ(kShouldWait, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, AutoClose) { char buffer[4]; size_t read = 88; writer_.reset(); auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); Result result = reader->Read(buffer, 4, kNone, &read); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, ReadSimple) { writer_->AddData(NewFixedData("hello")); char buffer[4] = {}; size_t read = 88; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); Result result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(3u, read); EXPECT_STREQ("hel", buffer); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(2u, read); EXPECT_STREQ("lol", buffer); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kShouldWait, result); EXPECT_EQ(0u, read); writer_->Close(); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, ReadAfterHandleIsGone) { writer_->AddData(NewFixedData("hello")); char buffer[8] = {}; size_t read = 88; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); handle_.reset(); Result result = reader->Read(buffer, sizeof(buffer), kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(5u, read); EXPECT_STREQ("hello", buffer); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kShouldWait, result); EXPECT_EQ(0u, read); writer_->Close(); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, ReObtainReader) { writer_->AddData(NewFixedData("hello")); char buffer[4] = {}; size_t read = 88; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); Result result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(3u, read); EXPECT_STREQ("hel", buffer); reader.reset(); reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(2u, read); EXPECT_STREQ("lol", buffer); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kShouldWait, result); EXPECT_EQ(0u, read); writer_->Close(); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, CloseBeforeReading) { writer_->AddData(NewFixedData("hello")); writer_->Close(); char buffer[20] = {}; size_t read = 88; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); Result result = reader->Read(buffer, sizeof(buffer), kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(5u, read); EXPECT_STREQ("hello", buffer); result = reader->Read(buffer, sizeof(buffer), kNone, &read); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, CloseWithDataBeforeZeroRead) { writer_->AddData(NewFixedData("hello")); writer_->Close(); size_t read = 88; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); Result result = reader->Read(nullptr, 0, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, CloseWithoutDataBeforeZeroRead) { writer_->Close(); size_t read = 88; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); Result result = reader->Read(nullptr, 0, kNone, &read); EXPECT_EQ(kDone, result); } TEST_F(SharedMemoryDataConsumerHandleTest, AddMultipleData) { writer_->AddData(NewFixedData("Once ")); writer_->AddData(NewFixedData("upon ")); writer_->AddData(NewFixedData("a ")); writer_->AddData(NewFixedData("time ")); writer_->AddData(NewFixedData("there ")); writer_->AddData(NewFixedData("was ")); writer_->AddData(NewFixedData("a ")); writer_->Close(); char buffer[20]; size_t read; Result result; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 6, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(6u, read); EXPECT_STREQ("Once u", buffer); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 2, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(2u, read); EXPECT_STREQ("po", buffer); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 9, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(9u, read); EXPECT_STREQ("n a time ", buffer); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 3, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(3u, read); EXPECT_STREQ("the", buffer); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 20, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(9u, read); EXPECT_STREQ("re was a ", buffer); result = reader->Read(buffer, sizeof(buffer), kNone, &read); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, AddMultipleDataInteractively) { writer_->AddData(NewFixedData("Once ")); writer_->AddData(NewFixedData("upon ")); char buffer[20]; size_t read; Result result; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 6, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(6u, read); EXPECT_STREQ("Once u", buffer); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 2, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(2u, read); EXPECT_STREQ("po", buffer); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 9, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(2u, read); EXPECT_STREQ("n ", buffer); writer_->AddData(NewFixedData("a ")); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 1, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(1u, read); EXPECT_STREQ("a", buffer); writer_->AddData(NewFixedData("time ")); writer_->AddData(NewFixedData("there ")); writer_->AddData(NewFixedData("was ")); writer_->AddData(NewFixedData("a ")); writer_->Close(); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 9, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(9u, read); EXPECT_STREQ(" time the", buffer); std::fill(&buffer[0], &buffer[base::size(buffer)], 0); result = reader->Read(buffer, 20, kNone, &read); EXPECT_EQ(kOk, result); EXPECT_EQ(9u, read); EXPECT_STREQ("re was a ", buffer); result = reader->Read(buffer, sizeof(buffer), kNone, &read); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, RegisterClient) { Checkpoint checkpoint; InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(checkpoint, Call(3)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(4)); checkpoint.Call(0); auto reader = handle_->ObtainReader( &client_, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); checkpoint.Call(1); RunPostedTasks(); checkpoint.Call(2); writer_->Close(); checkpoint.Call(3); RunPostedTasks(); checkpoint.Call(4); } TEST_F(SharedMemoryDataConsumerHandleTest, RegisterClientWhenDataExists) { Checkpoint checkpoint; InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(3)); checkpoint.Call(0); writer_->AddData(NewFixedData("Once ")); checkpoint.Call(1); auto reader = handle_->ObtainReader( &client_, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); checkpoint.Call(2); RunPostedTasks(); checkpoint.Call(3); } TEST_F(SharedMemoryDataConsumerHandleTest, AddDataWhenClientIsRegistered) { Checkpoint checkpoint; char buffer[20]; Result result; size_t size; InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(checkpoint, Call(3)); EXPECT_CALL(checkpoint, Call(4)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(5)); checkpoint.Call(0); auto reader = handle_->ObtainReader( &client_, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); checkpoint.Call(1); writer_->AddData(NewFixedData("Once ")); checkpoint.Call(2); writer_->AddData(NewFixedData("upon ")); checkpoint.Call(3); result = reader->Read(buffer, sizeof(buffer), kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(10u, size); checkpoint.Call(4); writer_->AddData(NewFixedData("a ")); checkpoint.Call(5); } TEST_F(SharedMemoryDataConsumerHandleTest, CloseWithClientAndData) { Checkpoint checkpoint; InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(checkpoint, Call(3)); checkpoint.Call(0); auto reader = handle_->ObtainReader( &client_, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); checkpoint.Call(1); writer_->AddData(NewFixedData("Once ")); checkpoint.Call(2); writer_->Close(); checkpoint.Call(3); } TEST_F(SharedMemoryDataConsumerHandleTest, ReleaseReader) { Checkpoint checkpoint; InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(checkpoint, Call(2)); checkpoint.Call(0); auto reader = handle_->ObtainReader( &client_, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); checkpoint.Call(1); reader.reset(); writer_->AddData(NewFixedData("Once ")); checkpoint.Call(2); } TEST_F(SharedMemoryDataConsumerHandleTest, TwoPhaseReadShouldWait) { Result result; const void* buffer = &result; size_t size = 99; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kShouldWait, result); EXPECT_EQ(nullptr, buffer); EXPECT_EQ(0u, size); } TEST_F(SharedMemoryDataConsumerHandleTest, TwoPhaseReadSimple) { writer_->AddData(NewFixedData("Once ")); Result result; const void* buffer = &result; size_t size = 99; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(5u, size); EXPECT_EQ("Once ", ToString(buffer, 5)); reader->EndRead(1); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(4u, size); EXPECT_EQ("nce ", ToString(buffer, 4)); reader->EndRead(4); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kShouldWait, result); EXPECT_EQ(0u, size); EXPECT_EQ(nullptr, buffer); writer_->Close(); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, size); EXPECT_EQ(nullptr, buffer); } TEST_F(SharedMemoryDataConsumerHandleTest, CallOnClearWhenDestructed1) { // Call |on_clear| when the handle is gone and if there is no reader. Checkpoint checkpoint; scoped_refptr<DestructionTrackingFunction> on_clear( new StrictMock<DestructionTrackingFunction>); InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*on_clear, Call()); EXPECT_CALL(*on_clear, Destruct()); EXPECT_CALL(checkpoint, Call(2)); checkpoint.Call(0); handle_ = std::make_unique<SharedMemoryDataConsumerHandle>( base::BindOnce(&DestructionTrackingFunction::Call, on_clear), &writer_); handle_.reset(); on_clear = nullptr; checkpoint.Call(1); RunPostedTasks(); checkpoint.Call(2); } TEST_F(SharedMemoryDataConsumerHandleTest, CallOnClearWhenDestructed2) { // Call |on_clear| when the reader is gone if the handle is alredy gone. Checkpoint checkpoint; scoped_refptr<DestructionTrackingFunction> on_clear( new StrictMock<DestructionTrackingFunction>); InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(checkpoint, Call(3)); EXPECT_CALL(*on_clear, Call()); EXPECT_CALL(*on_clear, Destruct()); EXPECT_CALL(checkpoint, Call(4)); checkpoint.Call(0); handle_ = std::make_unique<SharedMemoryDataConsumerHandle>( base::BindOnce(&DestructionTrackingFunction::Call, on_clear), &writer_); auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); handle_.reset(); on_clear = nullptr; checkpoint.Call(1); RunPostedTasks(); checkpoint.Call(2); reader.reset(); checkpoint.Call(3); RunPostedTasks(); checkpoint.Call(4); } TEST_F(SharedMemoryDataConsumerHandleTest, DoNotCallOnClearWhenDone) { Checkpoint checkpoint; scoped_refptr<DestructionTrackingFunction> on_clear( new StrictMock<DestructionTrackingFunction>); InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*on_clear, Destruct()); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(checkpoint, Call(3)); EXPECT_CALL(checkpoint, Call(4)); checkpoint.Call(0); handle_ = std::make_unique<SharedMemoryDataConsumerHandle>( base::BindOnce(&DestructionTrackingFunction::Call, on_clear), &writer_); on_clear = nullptr; checkpoint.Call(1); writer_->Close(); checkpoint.Call(2); handle_.reset(); checkpoint.Call(3); RunPostedTasks(); checkpoint.Call(4); } TEST_F(SharedMemoryDataConsumerHandleTest, DoNotCallOnClearWhenErrored) { Checkpoint checkpoint; scoped_refptr<DestructionTrackingFunction> on_clear( new StrictMock<DestructionTrackingFunction>); InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*on_clear, Destruct()); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(checkpoint, Call(3)); EXPECT_CALL(checkpoint, Call(4)); checkpoint.Call(0); handle_ = std::make_unique<SharedMemoryDataConsumerHandle>( base::BindOnce(&DestructionTrackingFunction::Call, on_clear), &writer_); on_clear = nullptr; checkpoint.Call(1); writer_->Fail(); checkpoint.Call(2); handle_.reset(); checkpoint.Call(3); RunPostedTasks(); checkpoint.Call(4); } TEST_F(SharedMemoryDataConsumerHandleTest, TwoPhaseReadWithMultipleData) { writer_->AddData(NewFixedData("Once ")); writer_->AddData(NewFixedData("upon ")); Result result; const void* buffer = &result; size_t size = 99; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(5u, size); EXPECT_EQ("Once ", ToString(buffer, 5)); reader->EndRead(1); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(4u, size); EXPECT_EQ("nce ", ToString(buffer, 4)); reader->EndRead(4); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(5u, size); EXPECT_EQ("upon ", ToString(buffer, 5)); reader->EndRead(5); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kShouldWait, result); EXPECT_EQ(0u, size); EXPECT_EQ(nullptr, buffer); writer_->Close(); result = reader->BeginRead(&buffer, kNone, &size); EXPECT_EQ(kDone, result); EXPECT_EQ(0u, size); EXPECT_EQ(nullptr, buffer); } TEST_F(SharedMemoryDataConsumerHandleTest, ErrorRead) { Checkpoint checkpoint; Result result; char buffer[20] = {}; size_t read = 99; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); writer_->Fail(); result = reader->Read(buffer, sizeof(buffer), kNone, &read); EXPECT_EQ(kUnexpectedError, result); EXPECT_EQ(0u, read); } TEST_F(SharedMemoryDataConsumerHandleTest, ErrorTwoPhaseRead) { Result result; const void* pointer = &result; size_t size = 99; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); writer_->Fail(); result = reader->BeginRead(&pointer, kNone, &size); EXPECT_EQ(kUnexpectedError, result); EXPECT_EQ(nullptr, pointer); EXPECT_EQ(0u, size); } TEST_F(SharedMemoryDataConsumerHandleTest, FailWhileTwoPhaseReadIsInProgress) { Result result; const void* pointer = nullptr; size_t size = 0; auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); writer_->AddData(NewFixedData("Once ")); result = reader->BeginRead(&pointer, kNone, &size); auto* buffer = static_cast<const char*>(pointer); ASSERT_EQ(kOk, result); ASSERT_NE(nullptr, pointer); ASSERT_EQ(size, 5u); writer_->Fail(); // We can access the buffer after calling |Fail|. I hope ASAN will detect // an error if the region is already freed. EXPECT_EQ('O', buffer[0]); EXPECT_EQ('n', buffer[1]); EXPECT_EQ('c', buffer[2]); EXPECT_EQ('e', buffer[3]); EXPECT_EQ(' ', buffer[4]); EXPECT_EQ(kOk, reader->EndRead(size)); EXPECT_EQ(kUnexpectedError, reader->BeginRead(&pointer, kNone, &size)); } TEST_F(SharedMemoryDataConsumerHandleTest, FailWithClient) { Checkpoint checkpoint; InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(3)); checkpoint.Call(0); auto reader = handle_->ObtainReader( &client_, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); checkpoint.Call(1); writer_->Fail(); checkpoint.Call(2); RunPostedTasks(); checkpoint.Call(3); } TEST_F(SharedMemoryDataConsumerHandleTest, FailWithClientAndData) { Checkpoint checkpoint; InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(checkpoint, Call(3)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(4)); checkpoint.Call(0); auto reader = handle_->ObtainReader( &client_, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); checkpoint.Call(1); writer_->AddData(NewFixedData("Once ")); checkpoint.Call(2); writer_->Fail(); checkpoint.Call(3); RunPostedTasks(); checkpoint.Call(4); } TEST_F(SharedMemoryDataConsumerHandleTest, RecursiveErrorNotification) { Checkpoint checkpoint; InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(client_, DidGetReadable()) .WillOnce(Invoke(writer_.get(), &Writer::Fail)); EXPECT_CALL(checkpoint, Call(2)); EXPECT_CALL(client_, DidGetReadable()); EXPECT_CALL(checkpoint, Call(3)); checkpoint.Call(0); auto reader = handle_->ObtainReader( &client_, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); checkpoint.Call(1); writer_->AddData(NewFixedData("Once ")); checkpoint.Call(2); RunPostedTasks(); checkpoint.Call(3); } TEST_F(SharedMemoryDataConsumerHandleTest, Read) { char buffer[20]; Result result; size_t size; scoped_refptr<Logger> logger(new Logger); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data1", "Once ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data2", "upon ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data3", "a ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data4", "time ", logger)); auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); logger->Add("1"); result = reader->Read(buffer, 2, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(2u, size); logger->Add("2"); result = reader->Read(buffer, 5, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(5u, size); logger->Add("3"); result = reader->Read(buffer, 6, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(6u, size); logger->Add("4"); EXPECT_EQ( "1\n" "2\n" "data1 is destructed.\n" "3\n" "data2 is destructed.\n" "data3 is destructed.\n" "4\n", logger->log()); } TEST_F(SharedMemoryDataConsumerHandleTest, CloseAndReset) { char buffer[20]; Result result; size_t size; scoped_refptr<Logger> logger(new Logger); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data1", "Once ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data2", "upon ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data3", "a ", logger)); auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); logger->Add("1"); result = reader->Read(buffer, 2, kNone, &size); EXPECT_EQ(kOk, result); EXPECT_EQ(2u, size); logger->Add("2"); writer_->Close(); logger->Add("3"); handle_.reset(); reader.reset(); logger->Add("4"); std::vector<std::string> log = base::SplitString( logger->log(), "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); ASSERT_EQ(8u, log.size()); EXPECT_EQ("1", log[0]); EXPECT_EQ("2", log[1]); EXPECT_EQ("3", log[2]); EXPECT_EQ("4", log[6]); EXPECT_EQ("", log[7]); // The destruction order doesn't matter in this case. std::vector<std::string> destruction_entries = {log[3], log[4], log[5]}; std::sort(destruction_entries.begin(), destruction_entries.end()); EXPECT_EQ(destruction_entries[0], "data1 is destructed."); EXPECT_EQ(destruction_entries[1], "data2 is destructed."); EXPECT_EQ(destruction_entries[2], "data3 is destructed."); } TEST_F(ThreadedSharedMemoryDataConsumerHandleTest, Read) { base::RunLoop run_loop; auto operation = std::make_unique<ReadDataOperation>( std::move(handle_), blink::scheduler::GetSingleThreadTaskRunnerForTesting(), run_loop.QuitClosure()); scoped_refptr<Logger> logger(new Logger); base::Thread t("DataConsumerHandle test thread"); ASSERT_TRUE(t.Start()); t.task_runner()->PostTask(FROM_HERE, base::BindOnce(&ReadDataOperation::ReadData, base::Unretained(operation.get()))); logger->Add("1"); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data1", "Once ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data2", "upon ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data3", "a time ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data4", "there ", logger)); writer_->AddData( std::make_unique<LoggingFixedReceivedData>("data5", "was ", logger)); writer_->Close(); logger->Add("2"); run_loop.Run(); t.Stop(); EXPECT_EQ("Once upon a time there was ", operation->result()); EXPECT_EQ( "1\n" "2\n" "data1 is destructed.\n" "data2 is destructed.\n" "data3 is destructed.\n" "data4 is destructed.\n" "data5 is destructed.\n", logger->log()); } } // namespace } // namespace content
706807115f5c5cf9d9451ccd71591615d5ca1bd6
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/third_party/blink/renderer/modules/webcodecs/audio_encoder.h
100691161f039810fb293cccccdb33d01d39d4fc
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
3,699
h
audio_encoder.h
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_AUDIO_ENCODER_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_AUDIO_ENCODER_H_ #include "media/base/audio_codecs.h" #include "media/base/audio_encoder.h" #include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_codec_state.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_encoded_audio_chunk_output_callback.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_webcodecs_error_callback.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webcodecs/audio_data.h" #include "third_party/blink/renderer/modules/webcodecs/encoder_base.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" namespace blink { class ExceptionState; class AudioEncoderConfig; class AudioEncoderInit; class MODULES_EXPORT AudioEncoderTraits { public: struct ParsedConfig final : public GarbageCollected<ParsedConfig> { media::AudioEncoder::Options options; String codec_string; void Trace(Visitor*) const {} }; struct AudioEncoderEncodeOptions : public GarbageCollected<AudioEncoderEncodeOptions> { void Trace(Visitor*) const {} }; using Init = AudioEncoderInit; using Config = AudioEncoderConfig; using InternalConfig = ParsedConfig; using Input = AudioData; using EncodeOptions = AudioEncoderEncodeOptions; using OutputChunk = EncodedAudioChunk; using OutputCallback = V8EncodedAudioChunkOutputCallback; using MediaEncoder = media::AudioEncoder; // Can't be a virtual method, because it's used from base ctor. static const char* GetName(); }; class MODULES_EXPORT AudioEncoder final : public EncoderBase<AudioEncoderTraits> { DEFINE_WRAPPERTYPEINFO(); public: static AudioEncoder* Create(ScriptState*, const AudioEncoderInit*, ExceptionState&); AudioEncoder(ScriptState*, const AudioEncoderInit*, ExceptionState&); ~AudioEncoder() override; void encode(AudioData* data, ExceptionState& exception_state) { return Base::encode(data, nullptr, exception_state); } // EventTarget interface const AtomicString& InterfaceName() const override; static ScriptPromise isConfigSupported(ScriptState*, const AudioEncoderConfig*, ExceptionState&); private: using Base = EncoderBase<AudioEncoderTraits>; using ParsedConfig = AudioEncoderTraits::ParsedConfig; void ProcessEncode(Request* request) override; void ProcessConfigure(Request* request) override; void ProcessReconfigure(Request* request) override; ParsedConfig* ParseConfig(const AudioEncoderConfig* opts, ExceptionState&) override; bool VerifyCodecSupport(ParsedConfig*, ExceptionState&) override; bool CanReconfigure(ParsedConfig& original_config, ParsedConfig& new_config) override; std::unique_ptr<media::AudioEncoder> CreateMediaAudioEncoder( const ParsedConfig& config); void CallOutputCallback( ParsedConfig* active_config, uint32_t reset_count, media::EncodedAudioBuffer encoded_buffer, absl::optional<media::AudioEncoder::CodecDescription> codec_desc); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_AUDIO_ENCODER_H_
43e84248b4aef1dd008b756035a0a8b4650a752d
9b2d7c2a3df6d6e287a176540d4b587aebb187a1
/Tema2/Object3D.cpp
b4d4b3e7b9d4df13c90233e095b5707a1b92f66a
[]
no_license
RazvanBusuioc/Tema2EGC
a45d6379805c0a83f48e530684a70605951f0f93
2b6feb30d2ee4ab3eb44ecb6d0547830ba0b17de
refs/heads/main
2023-03-06T02:13:29.398979
2021-02-18T12:52:33
2021-02-18T12:52:33
340,048,077
0
0
null
null
null
null
UTF-8
C++
false
false
3,128
cpp
Object3D.cpp
#include "Object3D.h" #include <Core/Engine.h> #include <iostream> Mesh* Object3D::CreateMesh(std::string name, const std::vector<VertexFormat>& vertices, const std::vector<unsigned short>& indices) { unsigned int VAO = 0; //Create the VAO and bind it glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); // Create the VBO and bind it unsigned int VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); // Send vertices data into the VBO buffer glBufferData(GL_ARRAY_BUFFER, sizeof(vertices[0]) * vertices.size(), &vertices[0], GL_STATIC_DRAW); // Crete the IBO and bind it unsigned int IBO; glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); // Send indices data into the IBO buffer glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices[0]) * indices.size(), &indices[0], GL_STATIC_DRAW); // ======================================================================== // This section describes how the GPU Shader Vertex Shader program receives data // set vertex position attribute glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), 0); // set vertex normal attribute glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(sizeof(glm::vec3))); // set texture coordinate attribute glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(2 * sizeof(glm::vec3))); // set vertex color attribute glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(2 * sizeof(glm::vec3) + sizeof(glm::vec2))); // ======================================================================== // Unbind the VAO glBindVertexArray(0); // Check for OpenGL errors CheckOpenGLError(); // Mesh information is saved into a Mesh object Mesh* m = new Mesh(name); m->InitFromBuffer(VAO, static_cast<unsigned short>(indices.size())); m->vertices = vertices; m->indices = indices; return m; } Mesh* Object3D::CreateTile(std::string name, glm::vec3 dimension, glm::vec3 color) { float dim_x = dimension.x/(float)2; float dim_y = dimension.y/(float)2; float dim_z = dimension.z/(float)2; glm::vec3 white_color = glm::vec3(0.8f, 0.8f, 0.8f); std::vector<VertexFormat> vertices { VertexFormat(glm::vec3(-dim_x, -dim_y, dim_z), color), VertexFormat(glm::vec3(dim_x, -dim_y, dim_z), color), VertexFormat(glm::vec3(-dim_x, dim_y, dim_z), color), VertexFormat(glm::vec3(dim_x, dim_y, dim_z), white_color), VertexFormat(glm::vec3(-dim_x, -dim_y, -dim_z), white_color), VertexFormat(glm::vec3(dim_x, -dim_y, -dim_z), color), VertexFormat(glm::vec3(-dim_x, dim_y, -dim_z), color), VertexFormat(glm::vec3(dim_x, dim_y, -dim_z), color) }; std::vector<unsigned short> indices = { 0, 1, 2, 1, 3, 2, 2, 3, 7, 2, 7, 6, 1, 7, 3, 1, 5, 7, 6, 7, 4, 7, 5, 4, 0, 4, 1, 1, 4, 5, 2, 6, 4, 0, 2, 4, }; return CreateMesh(name, vertices, indices); }
41d94c01df01efa1e92537a48d0f119c33a51672
28f6b5c0ee50c4ff00f0388483e7ecd81943613a
/WebComponents/demos/vui-video/C++Builder/uFormMain.h
7a897142da92728df57383ea55dd4881a843ee6d
[ "MIT" ]
permissive
cybelesoft/virtualui
14866c9247d7a0dbd97fcd0073e3bbfcfdbb307b
7d2ed509b7f8c5c72dda3cfbff9b307cc27c1663
refs/heads/master
2023-03-11T09:48:48.763815
2022-09-16T14:25:54
2022-09-16T14:25:54
64,767,401
15
13
null
2023-03-04T09:32:41
2016-08-02T15:11:06
JavaScript
UTF-8
C++
false
false
1,204
h
uFormMain.h
//--------------------------------------------------------------------------- #ifndef uFormMainH #define uFormMainH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ComCtrls.hpp> #include <ExtCtrls.hpp> //--------------------------------------------------------------------------- class TFormMain : public TForm { __published: // IDE-managed Components TLabel *Label1; TComboBox *ComboUrl; TButton *ButGo; TButton *ButPlay; TButton *ButStop; TLabel *Label2; TLabel *LabelStatus; TTrackBar *Slider; TPanel *PanelXVideo; void __fastcall ButGoClick(TObject *Sender); void __fastcall ButPlayClick(TObject *Sender); void __fastcall ButStopClick(TObject *Sender); void __fastcall SliderChange(TObject *Sender); private: // User declarations public: // User declarations __fastcall TFormMain(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TFormMain *FormMain; //--------------------------------------------------------------------------- #endif
82798469dae8eb707e1c25d017176b41117476ae
ba5a2c65b5e2845f910d7bc7bf61df33cdec1ee6
/OOP Practices/OOP Practices/Clock.h
249f35309e4b3ea3a09cd57bd2960fa7058368be
[]
no_license
kruztev/C-plus-plus
2469089dcd57195d3bb52618a970b7e382911bea
61d4671086bf075d9ccc09e486dcc42a31546570
refs/heads/master
2021-07-23T04:56:02.025409
2020-05-02T21:14:45
2020-05-02T21:14:45
159,057,172
1
0
null
null
null
null
UTF-8
C++
false
false
585
h
Clock.h
// // Clock.h // OOP Practices // #ifndef Clock_h #define Clock_h class Clock { public: Clock(); Clock(const unsigned, const unsigned, const unsigned); Clock(const Clock&); Clock& operator=(const Clock&); Clock operator+(const Clock&); ~Clock(); public: void setHours(unsigned); void setMinutes(unsigned); void setSeconds(unsigned); public: void setClock(unsigned, unsigned, unsigned); void print(); void nextTick(); void syncTime(); private: unsigned hours; unsigned minutes; unsigned seconds; }; #endif
acbdc07fd0d363a345dfca1c88a08fa0ff96bf68
c78d7966f5334564660ec1490429dfdce860b3ea
/Questions/Codeforces/Solutions/Binary Protoco/q.cpp
9904da721b0ed1568015d27a51e84c92a18ca785
[]
no_license
felipegetulio/Competitive-Programming-Subjects
2f886204418fab84432588dc63823d65d4572d9f
fdcdda799c018c2d0bca46692e9c9682a3367025
refs/heads/master
2020-03-29T08:19:14.056794
2019-02-26T17:40:58
2019-02-26T17:40:58
149,704,507
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
q.cpp
using namespace std; #include<bits/stdc++.h> #define _ ios_base::sync_with_stdio(0); int main(){_ int n, cont = 0, ans = 0; string s; cin >> n >> s; for(int i=0; i<n; i++){ if(s[i] == '0'){ ans = 10*ans + cont; cont = 0; continue; } cont++; } ans = 10*ans + cont; cout << ans << endl; return 0; }
f09706637afe891ea78b8bd0e304c61c6628013c
fd3f8e4383292c15194a97cfa251a3de0882ac3c
/src/replica/duplication/replica_duplicator_manager.cpp
56ec34a39272dc545c3ed7a9ef7d610433ad2296
[ "Apache-2.0", "Zlib", "MIT", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
apache/incubator-pegasus
417ea26a150c3bfd6c7f6a0a2148de7770dd291b
be9119e75f27b9f0563acaf33f5c96edf0051307
refs/heads/master
2023-08-29T00:35:34.152285
2023-08-28T06:45:00
2023-08-28T06:45:00
41,712,332
663
97
Apache-2.0
2023-09-14T08:03:29
2015-09-01T02:29:37
C++
UTF-8
C++
false
false
6,280
cpp
replica_duplicator_manager.cpp
// 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 <algorithm> #include <cstdint> #include <memory> #include "common//duplication_common.h" #include "common/gpid.h" #include "replica/duplication/replica_duplicator.h" #include "replica_duplicator_manager.h" #include "utils/errors.h" #include "utils/fmt_logging.h" namespace dsn { namespace replication { std::vector<duplication_confirm_entry> replica_duplicator_manager::get_duplication_confirms_to_update() const { zauto_lock l(_lock); std::vector<duplication_confirm_entry> updates; for (const auto &kv : _duplications) { replica_duplicator *duplicator = kv.second.get(); duplication_progress p = duplicator->progress(); if (p.last_decree != p.confirmed_decree || (kv.second->status() == duplication_status::DS_PREPARE && p.checkpoint_has_prepared)) { if (p.last_decree < p.confirmed_decree) { LOG_ERROR_PREFIX("invalid decree state: p.last_decree({}) < p.confirmed_decree({})", p.last_decree, p.confirmed_decree); continue; } duplication_confirm_entry entry; entry.dupid = duplicator->id(); entry.confirmed_decree = p.last_decree; entry.__set_checkpoint_prepared(p.checkpoint_has_prepared); updates.emplace_back(entry); } } return updates; } void replica_duplicator_manager::sync_duplication(const duplication_entry &ent) { // state is inconsistent with meta-server auto it = ent.progress.find(get_gpid().get_partition_index()); if (it == ent.progress.end()) { _duplications.erase(ent.dupid); return; } zauto_lock l(_lock); dupid_t dupid = ent.dupid; duplication_status::type next_status = ent.status; replica_duplicator_u_ptr &dup = _duplications[dupid]; if (dup == nullptr) { if (!is_duplication_status_invalid(next_status)) { dup = std::make_unique<replica_duplicator>(ent, _replica); } else { LOG_ERROR_PREFIX("illegal duplication status: {}", duplication_status_to_string(next_status)); } } else { // update progress duplication_progress newp = dup->progress().set_confirmed_decree(it->second); CHECK_EQ_PREFIX(dup->update_progress(newp), error_s::ok()); dup->update_status_if_needed(next_status); if (ent.__isset.fail_mode) { dup->update_fail_mode(ent.fail_mode); } } } decree replica_duplicator_manager::min_confirmed_decree() const { zauto_lock l(_lock); decree min_decree = invalid_decree; if (_replica->status() == partition_status::PS_PRIMARY) { for (auto &kv : _duplications) { const duplication_progress &p = kv.second->progress(); if (min_decree == invalid_decree) { min_decree = p.confirmed_decree; } else { min_decree = std::min(min_decree, p.confirmed_decree); } } } else if (_primary_confirmed_decree > 0) { // if the replica is not primary, use the latest known (from primary) // confirmed_decree instead. min_decree = _primary_confirmed_decree; } return min_decree; } // Remove the duplications that are not in the `new_dup_map`. // NOTE: this function may be blocked when destroying replica_duplicator. void replica_duplicator_manager::remove_non_existed_duplications( const std::map<dupid_t, duplication_entry> &new_dup_map) { zauto_lock l(_lock); std::vector<dupid_t> removal_set; for (auto &pair : _duplications) { dupid_t cur_dupid = pair.first; if (new_dup_map.find(cur_dupid) == new_dup_map.end()) { removal_set.emplace_back(cur_dupid); } } for (dupid_t dupid : removal_set) { _duplications.erase(dupid); } } void replica_duplicator_manager::update_confirmed_decree_if_secondary(decree confirmed) { // this function always runs in the same single thread with config-sync if (_replica->status() != partition_status::PS_SECONDARY) { return; } zauto_lock l(_lock); remove_all_duplications(); if (confirmed >= 0) { // duplication ongoing // confirmed decree never decreases if (_primary_confirmed_decree < confirmed) { _primary_confirmed_decree = confirmed; } } else { // duplication add with freeze but no start or no duplication(include removed) _primary_confirmed_decree = confirmed; } } int64_t replica_duplicator_manager::get_pending_mutations_count() const { int64_t total = 0; for (const auto &dup : _duplications) { total += dup.second->get_pending_mutations_count(); } return total; } std::vector<replica_duplicator_manager::dup_state> replica_duplicator_manager::get_dup_states() const { zauto_lock l(_lock); std::vector<dup_state> ret; ret.reserve(_duplications.size()); for (const auto &dup : _duplications) { dup_state state; state.dupid = dup.first; state.duplicating = !dup.second->paused(); auto progress = dup.second->progress(); state.last_decree = progress.last_decree; state.confirmed_decree = progress.confirmed_decree; state.fail_mode = dup.second->fail_mode(); ret.emplace_back(state); } return ret; } } // namespace replication } // namespace dsn
9a781040babf267660f1e6d3aa787cb1e5b82507
9aaf6e9a28a521e87285a70ebbfbf2fcf2f202a6
/src/cell_tracking_flow.cpp
06fe47163e831b4abd0075254fada3aa7637b2f8
[]
no_license
pawelswoboda/LP_MP-Cell-tracking
69971bbb467f790d05ae4627784dda9776459f07
cb5e2b2625d77c867facefc218a369dd4ce77740
refs/heads/master
2021-09-19T18:36:10.783790
2018-07-30T14:13:01
2018-07-30T14:13:01
111,903,270
2
1
null
null
null
null
UTF-8
C++
false
false
393
cpp
cell_tracking_flow.cpp
#include "cell_tracking.h" #include "solver.hxx" #include "visitors/standard_visitor.hxx" using namespace LP_MP; int main(int argc, char** argv) { Solver<LP<FMC_CELL_TRACKING_FLOW>,StandardVisitor> solver(argc,argv); auto input = cell_tracking_parser_2d::parse_file(solver.get_input_file()); auto& c = solver.template GetProblemConstructor<0>(); c.construct(input); return solver.Solve(); }
94eda4c91d39ab8160e9cc02eca5d994ddf13a14
d0c7b39c0a724d2bceaac7cbf0e35a136e009c50
/Project6/SDLProject/Entity.cpp
5ce22f0a6b3079b585ff5375839e3bab504a45c3
[ "CC-BY-4.0" ]
permissive
jhochrun99/CS3113projects
041a40793b0a29a5e84d8282b20fcb87d283636b
d7444c91f91a00d76287cce55ffaeac42d8026f6
refs/heads/master
2021-01-04T21:23:31.824946
2020-05-09T03:38:13
2020-05-09T03:38:13
240,764,246
0
0
null
2020-05-06T03:54:44
2020-02-15T18:11:46
C++
UTF-8
C++
false
false
17,456
cpp
Entity.cpp
#include "Entity.h" #include "math.h" #include <stdlib.h> #include <time.h> #include "Util.h" #include "Enemy.h" Entity::Entity() { srand(time(NULL)); position = glm::vec3(0); velocity = glm::vec3(0); acceleration = glm::vec3(0); movement = glm::vec3(0); speed = 1.0f; health = 3; width = 1.0f; height = 1.0f; scale = 1.0f; isActive = true; canMove = true; canUse = true; collidedTop = false; collidedBottom = false; collidedLeft = false; collidedRight = false; collidedWith = NULL; soundEffect = Mix_LoadWAV("dig16-c.wav"); modelMatrix = glm::mat4(1.0f); animRight = NULL; animLeft = NULL; animUp = NULL; animDown = NULL; animIndices = NULL; animFrames = 0; animIndex = 0; animTime = 0; textureCols = 0; textureRows = 0; } bool Entity::CheckCollision(Entity* other) { if (other == NULL) { return false; } if (!isActive || !other->isActive) { return false; } float xDist = fabs(position.x - other->position.x) - ((width + other->width) / 2.0f); float yDist = fabs(position.y - other->position.y) - ((height + other->height) / 2.0f); if (xDist < 0 && yDist < 0) { return true; } return false; } void Entity::CheckCollisionY(Entity* objects, int objectCount) { for (int i = 0; i < objectCount; i++) { Entity* object = &objects[i]; if (CheckCollision(object)) { if (entityType==SANDD) { if (position.y > object->position.y + 0.5) { object->Health(); if (object->health == 1) { object->isActive = false; } } else { return; } return; } //if player falls on top of the sand player.position>sand.position //if sand falls on top of player sand.position> player.position float yOverlap = fabs(fabs(position.y - object->position.y) - (height / 2.0f) - (object->height / 2.0f)); if (object->entityType == ENEMY) { if (position.y > object->position.y + 0.2) { object->isActive = false; } else { std::cout << "this happens!!"<<std::endl; Health(); return; } return; } if (velocity.y > 0) { position.y -= yOverlap; velocity.y = 0; collidedTop = true; collidedWith = object; Health(); } else if (velocity.y < 0) { if(entityType == SANDD) { return; } position.y += yOverlap; velocity.y = 0; collidedBottom = true; collidedWith = object; if (object->health == 1) { object->isActive = false; } else { object->health--; } } } } } void Entity::CheckCollisionX(Entity* objects, int objectCount) { for (int i = 0; i < objectCount; i++) { Entity* object = &objects[i]; if (CheckCollision(object)) { float xOverlap = fabs(fabs(position.x - object->position.x) - (width / 2.0f) - (object->width / 2.0f)); if (velocity.x > 0) { position.x -= xOverlap; velocity.x = 0; collidedRight = true; collidedWith = object; Health(); } else { position.x += xOverlap; velocity.x = 0; collidedLeft = true; collidedWith = object; Health(); } } } } void Entity::CheckCollisionsY(Map* map) { // Probes for tiles glm::vec3 top = glm::vec3(position.x, position.y + (height / 2), position.z); glm::vec3 top_left = glm::vec3(position.x - (width / 2), position.y + (height / 2), position.z); glm::vec3 top_right = glm::vec3(position.x + (width / 2), position.y + (height / 2), position.z); glm::vec3 bottom = glm::vec3(position.x, position.y - (height / 2), position.z); glm::vec3 bottom_left = glm::vec3(position.x - (width / 2), position.y - (height / 2), position.z); glm::vec3 bottom_right = glm::vec3(position.x + (width / 2), position.y - (height / 2), position.z); float penetration_x = 0; float penetration_y = 0; float ticks = (float)SDL_GetTicks() / 1000.0f; if (entityType==SANDD) { if (map->IsSolidSand(top, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } else if (map->IsSolidSand(top_left, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } else if (map->IsSolidSand(top_right, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } if (map->IsSolidSand(bottom, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolidSand(bottom_left, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolidSand(bottom_right, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } if (map->IsSolidSand(bottom, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolidSand(bottom_left, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolidSand(bottom_right, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } return; } if (entityType == ENEMY) { if (map->IsSolidSlime(top, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } else if (map->IsSolidSlime(top_left, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } else if (map->IsSolidSlime(top_right, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } if (map->IsSolidSlime(bottom, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolidSlime(bottom_left, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolidSlime(bottom_right, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } if (map->IsSolidSlime(bottom, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolidSlime(bottom_left, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolidSlime(bottom_right, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } return; } if (map->IsSolid(top, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } else if (map->IsSolid(top_left, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } else if (map->IsSolid(top_right, &penetration_x, &penetration_y) && velocity.y > 0) { position.y -= penetration_y; velocity.y = 0; collidedTop = true; } if (map->IsSolid(bottom, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; glm::vec3 bottom = glm::vec3(position.x, position.y - (height / 2), position.z); if(map->currentTile==GLASS && int(ticks)%2==0){ map->destroy_tile(bottom); } } else if (map->IsSolid(bottom_left, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } else if (map->IsSolid(bottom_right, &penetration_x, &penetration_y) && velocity.y < 0) { position.y += penetration_y; velocity.y = 0; collidedBottom = true; } if (map->lastTile == LAVA || map->lastTile == SPIKE) { map->lastTile = SAFE; } } void Entity::CheckDown(Map *map) { glm::vec3 bottom = glm::vec3(position.x, position.y - (height / 2), position.z); if (map->currentTile==DIRT) { Mix_FadeInChannel(-1, soundEffect, 0, 1000); Mix_PlayChannel(-1, soundEffect, 0); map->destroy_tile(bottom); } } void Entity::CheckRight(Map *map) { glm::vec3 right = glm::vec3(position.x + (width), position.y, position.z); if (map->rightTile==DIRT) { Mix_FadeInChannel(-1, soundEffect, 0, 1000); Mix_PlayChannel(-1, soundEffect, 0); map->destroy_tile(right); } } void Entity::CheckLeft(Map *map) { glm::vec3 left = glm::vec3(position.x - (width), position.y, position.z); if (map->leftTile==DIRT) { Mix_FadeInChannel(-1, soundEffect, 0, 1000); Mix_PlayChannel(-1, soundEffect, 0); map->destroy_tile(left); } } void Entity::CheckCollisionsX(Map* map) { // Probes for tiles glm::vec3 left = glm::vec3(position.x - (width / 2), position.y, position.z); glm::vec3 right = glm::vec3(position.x + (width / 2), position.y, position.z); float penetration_x = 0; float penetration_y = 0; if (entityType == ENEMY) { if (map->IsSolidSand(left, &penetration_x, &penetration_y) && velocity.x < 0) { position.x += penetration_x; velocity.x = 0; collidedLeft = true; } if (map->IsSolidSand(right, &penetration_x, &penetration_y) && velocity.x > 0) { position.x -= penetration_x; velocity.x = 0; collidedRight = true; } } if (map->IsSolid(left, &penetration_x, &penetration_y) && velocity.x < 0) { position.x += penetration_x; velocity.x = 0; collidedLeft = true; } if (map->IsSolid(right, &penetration_x, &penetration_y) && velocity.x > 0) { position.x -= penetration_x; velocity.x = 0; collidedRight = true; } } void Entity::Update(float deltaTime, Map* map, Entity* objects, Entity* obj2, int objectCount) { if (!isActive || !canMove) { return; } //don't do anything if not active collidedTop = false; collidedBottom = false; collidedLeft = false; collidedRight = false; if (animIndices != NULL && objects == NULL) { if (glm::length(movement) != 0 || entityType != PLAYER) { animTime += deltaTime; if (animTime >= 0.25f) { animTime = 0.0f; animIndex++; if (animIndex >= animFrames) { animIndex = 0; } } } else { animIndex = 0; } } if ((entityType == PLAYER && objects == NULL) || entityType != PLAYER) { velocity.x = movement.x * speed; velocity += acceleration * deltaTime; } if (entityType == SANDD) { position.y += velocity.y * deltaTime; CheckCollisionY(objects,objectCount); position.x += velocity.x * deltaTime; CheckCollisionsY(map); modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); return; } if ((entityType == PLAYER && objects == NULL) || entityType != PLAYER) { position.y += velocity.y * deltaTime; // Move on Y } CheckCollisionsY(map); CheckCollisionY(objects, objectCount); if ((entityType == PLAYER && objects == NULL) || entityType != PLAYER) { position.x += velocity.x * deltaTime; } // Move on X CheckCollisionsX(map); CheckCollisionX(objects, objectCount); if (entityType == ENEMY) { Action(); } modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); } void Entity::DrawSpriteFromTextureAtlas(ShaderProgram* program, GLuint textureID, int index) { if (!isActive) { return; } //don't do anything if not active float u = (float)(index % textureCols) / (float)textureCols; float v = (float)(index / textureCols) / (float)textureRows; float width = 1.0f / (float)textureCols; float height = 1.0f / (float)textureRows; float texCoords[] = { u, v + height, u + width, v + height, u + width, v, u, v + height, u + width, v, u, v }; //default size is 0.5 float sizeNeg = -0.5 * scale; float sizePos = 0.5 * scale; float vertices[] = { sizeNeg, sizeNeg, sizePos, sizeNeg, sizePos, sizePos, sizeNeg, sizeNeg, sizePos, sizePos, sizeNeg, sizePos }; glBindTexture(GL_TEXTURE_2D, textureID); glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices); glEnableVertexAttribArray(program->positionAttribute); glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords); glEnableVertexAttribArray(program->texCoordAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program->positionAttribute); glDisableVertexAttribArray(program->texCoordAttribute); } void Entity::Render(ShaderProgram* program) { program->SetModelMatrix(modelMatrix); if (animIndices != NULL) { DrawSpriteFromTextureAtlas(program, textureID, animIndices[animIndex]); return; } //default size is 0.5 float sizeNeg = -0.5 * scale; float sizePos = 0.5 * scale; float vertices[] = { sizeNeg, sizeNeg, sizePos, sizeNeg, sizePos, sizePos, sizeNeg, sizeNeg, sizePos, sizePos, sizeNeg, sizePos }; float texCoords[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 }; glBindTexture(GL_TEXTURE_2D, textureID); glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices); glEnableVertexAttribArray(program->positionAttribute); glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords); glEnableVertexAttribArray(program->texCoordAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program->positionAttribute); glDisableVertexAttribArray(program->texCoordAttribute); } Player::Player() { health = 3; lastCheckpoint = 0; checkPLocations.push_back(std::make_tuple(2, 0)); checkPLocations.push_back(std::make_tuple(2, -19)); checkPLocations.push_back(std::make_tuple(2, -39)); checkPLocations.push_back(std::make_tuple(2, -59)); isActive = true; position = glm::vec3(2.0f, 0, 0); acceleration = glm::vec3(0, -5.8f, 0); speed = 2.0f; textureID = Util::LoadTexture("golemTRP.png"); height = 0.8f; width = 0.75f; animRight = new int[5]{ 1, 4, 7, 10, 13 }; animLeft = new int[5]{ 2, 5, 8, 11, 14 }; animUp = new int[5]{ 0, 3, 6, 9, 6 }; animDown = new int[5]{ 0, 3, 6, 9, 6 }; animIndices = animRight; animFrames = 5; animIndex = 0; animTime = 0; textureCols = 3; textureRows = 6; } void Player::Action() { } void Player::Health() { health -= 1; if (health == 0) { isActive = false; } else { movement = glm::vec3(0); position = glm::vec3(std::get<0>(checkPLocations[lastCheckpoint]), std::get<1>(checkPLocations[lastCheckpoint]), 0); //getting entry in vector according to lastCheckPoint, 0 in tuple = x, 1 = y coordinate } }
e14cc9ab14aede68be5cfbcb4a708382b8e7895d
4382d8e976816ba2be05621b3566df9d5be9c0a6
/OpenHome/Net/Bindings/Cpp/Device/Providers/DvAvOpenhomeOrgProduct2Std.cpp
b42ab25755c772a69593a1ee249542ad7c0dcdec
[ "MIT" ]
permissive
openhome/ohNetGenerated
f9e9fc591d52c1a2ed69c676046af4e931c22f7c
05270d36e77f97a2ffd0f9eb44249a908c333d71
refs/heads/master
2020-12-13T18:39:35.802161
2018-07-12T13:09:23
2018-07-12T13:09:23
22,726,722
1
6
null
2016-10-17T12:43:53
2014-08-07T15:38:18
C++
UTF-8
C++
false
false
33,434
cpp
DvAvOpenhomeOrgProduct2Std.cpp
#include "DvAvOpenhomeOrgProduct2.h" #include <OpenHome/Types.h> #include <OpenHome/Net/Private/DviService.h> #include <OpenHome/Net/Private/Service.h> #include <OpenHome/Net/Private/FunctorDviInvocation.h> #include <OpenHome/Net/Cpp/DvInvocation.h> #include <OpenHome/Net/Private/DviStack.h> using namespace OpenHome; using namespace OpenHome::Net; bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyManufacturerName(const std::string& aValue) { ASSERT(iPropertyManufacturerName != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyManufacturerName, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyManufacturerName(std::string& aValue) { ASSERT(iPropertyManufacturerName != NULL); const Brx& val = iPropertyManufacturerName->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyManufacturerInfo(const std::string& aValue) { ASSERT(iPropertyManufacturerInfo != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyManufacturerInfo, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyManufacturerInfo(std::string& aValue) { ASSERT(iPropertyManufacturerInfo != NULL); const Brx& val = iPropertyManufacturerInfo->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyManufacturerUrl(const std::string& aValue) { ASSERT(iPropertyManufacturerUrl != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyManufacturerUrl, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyManufacturerUrl(std::string& aValue) { ASSERT(iPropertyManufacturerUrl != NULL); const Brx& val = iPropertyManufacturerUrl->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyManufacturerImageUri(const std::string& aValue) { ASSERT(iPropertyManufacturerImageUri != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyManufacturerImageUri, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyManufacturerImageUri(std::string& aValue) { ASSERT(iPropertyManufacturerImageUri != NULL); const Brx& val = iPropertyManufacturerImageUri->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyModelName(const std::string& aValue) { ASSERT(iPropertyModelName != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyModelName, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyModelName(std::string& aValue) { ASSERT(iPropertyModelName != NULL); const Brx& val = iPropertyModelName->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyModelInfo(const std::string& aValue) { ASSERT(iPropertyModelInfo != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyModelInfo, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyModelInfo(std::string& aValue) { ASSERT(iPropertyModelInfo != NULL); const Brx& val = iPropertyModelInfo->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyModelUrl(const std::string& aValue) { ASSERT(iPropertyModelUrl != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyModelUrl, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyModelUrl(std::string& aValue) { ASSERT(iPropertyModelUrl != NULL); const Brx& val = iPropertyModelUrl->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyModelImageUri(const std::string& aValue) { ASSERT(iPropertyModelImageUri != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyModelImageUri, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyModelImageUri(std::string& aValue) { ASSERT(iPropertyModelImageUri != NULL); const Brx& val = iPropertyModelImageUri->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyProductRoom(const std::string& aValue) { ASSERT(iPropertyProductRoom != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyProductRoom, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyProductRoom(std::string& aValue) { ASSERT(iPropertyProductRoom != NULL); const Brx& val = iPropertyProductRoom->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyProductName(const std::string& aValue) { ASSERT(iPropertyProductName != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyProductName, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyProductName(std::string& aValue) { ASSERT(iPropertyProductName != NULL); const Brx& val = iPropertyProductName->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyProductInfo(const std::string& aValue) { ASSERT(iPropertyProductInfo != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyProductInfo, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyProductInfo(std::string& aValue) { ASSERT(iPropertyProductInfo != NULL); const Brx& val = iPropertyProductInfo->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyProductUrl(const std::string& aValue) { ASSERT(iPropertyProductUrl != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyProductUrl, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyProductUrl(std::string& aValue) { ASSERT(iPropertyProductUrl != NULL); const Brx& val = iPropertyProductUrl->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyProductImageUri(const std::string& aValue) { ASSERT(iPropertyProductImageUri != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyProductImageUri, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyProductImageUri(std::string& aValue) { ASSERT(iPropertyProductImageUri != NULL); const Brx& val = iPropertyProductImageUri->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyStandby(bool aValue) { ASSERT(iPropertyStandby != NULL); return SetPropertyBool(*iPropertyStandby, aValue); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyStandby(bool& aValue) { ASSERT(iPropertyStandby != NULL); aValue = iPropertyStandby->Value(); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertySourceIndex(uint32_t aValue) { ASSERT(iPropertySourceIndex != NULL); return SetPropertyUint(*iPropertySourceIndex, aValue); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertySourceIndex(uint32_t& aValue) { ASSERT(iPropertySourceIndex != NULL); aValue = iPropertySourceIndex->Value(); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertySourceCount(uint32_t aValue) { ASSERT(iPropertySourceCount != NULL); return SetPropertyUint(*iPropertySourceCount, aValue); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertySourceCount(uint32_t& aValue) { ASSERT(iPropertySourceCount != NULL); aValue = iPropertySourceCount->Value(); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertySourceXml(const std::string& aValue) { ASSERT(iPropertySourceXml != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertySourceXml, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertySourceXml(std::string& aValue) { ASSERT(iPropertySourceXml != NULL); const Brx& val = iPropertySourceXml->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } bool DvProviderAvOpenhomeOrgProduct2Cpp::SetPropertyAttributes(const std::string& aValue) { ASSERT(iPropertyAttributes != NULL); Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length()); return SetPropertyString(*iPropertyAttributes, buf); } void DvProviderAvOpenhomeOrgProduct2Cpp::GetPropertyAttributes(std::string& aValue) { ASSERT(iPropertyAttributes != NULL); const Brx& val = iPropertyAttributes->Value(); aValue.assign((const char*)val.Ptr(), val.Bytes()); } DvProviderAvOpenhomeOrgProduct2Cpp::DvProviderAvOpenhomeOrgProduct2Cpp(DvDeviceStd& aDevice) : DvProvider(aDevice.Device(), "av.openhome.org", "Product", 2) { iPropertyManufacturerName = NULL; iPropertyManufacturerInfo = NULL; iPropertyManufacturerUrl = NULL; iPropertyManufacturerImageUri = NULL; iPropertyModelName = NULL; iPropertyModelInfo = NULL; iPropertyModelUrl = NULL; iPropertyModelImageUri = NULL; iPropertyProductRoom = NULL; iPropertyProductName = NULL; iPropertyProductInfo = NULL; iPropertyProductUrl = NULL; iPropertyProductImageUri = NULL; iPropertyStandby = NULL; iPropertySourceIndex = NULL; iPropertySourceCount = NULL; iPropertySourceXml = NULL; iPropertyAttributes = NULL; } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyManufacturerName() { iPropertyManufacturerName = new PropertyString(new ParameterString("ManufacturerName")); iService->AddProperty(iPropertyManufacturerName); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyManufacturerInfo() { iPropertyManufacturerInfo = new PropertyString(new ParameterString("ManufacturerInfo")); iService->AddProperty(iPropertyManufacturerInfo); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyManufacturerUrl() { iPropertyManufacturerUrl = new PropertyString(new ParameterString("ManufacturerUrl")); iService->AddProperty(iPropertyManufacturerUrl); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyManufacturerImageUri() { iPropertyManufacturerImageUri = new PropertyString(new ParameterString("ManufacturerImageUri")); iService->AddProperty(iPropertyManufacturerImageUri); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyModelName() { iPropertyModelName = new PropertyString(new ParameterString("ModelName")); iService->AddProperty(iPropertyModelName); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyModelInfo() { iPropertyModelInfo = new PropertyString(new ParameterString("ModelInfo")); iService->AddProperty(iPropertyModelInfo); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyModelUrl() { iPropertyModelUrl = new PropertyString(new ParameterString("ModelUrl")); iService->AddProperty(iPropertyModelUrl); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyModelImageUri() { iPropertyModelImageUri = new PropertyString(new ParameterString("ModelImageUri")); iService->AddProperty(iPropertyModelImageUri); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyProductRoom() { iPropertyProductRoom = new PropertyString(new ParameterString("ProductRoom")); iService->AddProperty(iPropertyProductRoom); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyProductName() { iPropertyProductName = new PropertyString(new ParameterString("ProductName")); iService->AddProperty(iPropertyProductName); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyProductInfo() { iPropertyProductInfo = new PropertyString(new ParameterString("ProductInfo")); iService->AddProperty(iPropertyProductInfo); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyProductUrl() { iPropertyProductUrl = new PropertyString(new ParameterString("ProductUrl")); iService->AddProperty(iPropertyProductUrl); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyProductImageUri() { iPropertyProductImageUri = new PropertyString(new ParameterString("ProductImageUri")); iService->AddProperty(iPropertyProductImageUri); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyStandby() { iPropertyStandby = new PropertyBool(new ParameterBool("Standby")); iService->AddProperty(iPropertyStandby); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertySourceIndex() { iPropertySourceIndex = new PropertyUint(new ParameterUint("SourceIndex")); iService->AddProperty(iPropertySourceIndex); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertySourceCount() { iPropertySourceCount = new PropertyUint(new ParameterUint("SourceCount")); iService->AddProperty(iPropertySourceCount); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertySourceXml() { iPropertySourceXml = new PropertyString(new ParameterString("SourceXml")); iService->AddProperty(iPropertySourceXml); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnablePropertyAttributes() { iPropertyAttributes = new PropertyString(new ParameterString("Attributes")); iService->AddProperty(iPropertyAttributes); // passes ownership } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionManufacturer() { OpenHome::Net::Action* action = new OpenHome::Net::Action("Manufacturer"); action->AddOutputParameter(new ParameterRelated("Name", *iPropertyManufacturerName)); action->AddOutputParameter(new ParameterRelated("Info", *iPropertyManufacturerInfo)); action->AddOutputParameter(new ParameterRelated("Url", *iPropertyManufacturerUrl)); action->AddOutputParameter(new ParameterRelated("ImageUri", *iPropertyManufacturerImageUri)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoManufacturer); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionModel() { OpenHome::Net::Action* action = new OpenHome::Net::Action("Model"); action->AddOutputParameter(new ParameterRelated("Name", *iPropertyModelName)); action->AddOutputParameter(new ParameterRelated("Info", *iPropertyModelInfo)); action->AddOutputParameter(new ParameterRelated("Url", *iPropertyModelUrl)); action->AddOutputParameter(new ParameterRelated("ImageUri", *iPropertyModelImageUri)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoModel); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionProduct() { OpenHome::Net::Action* action = new OpenHome::Net::Action("Product"); action->AddOutputParameter(new ParameterRelated("Room", *iPropertyProductRoom)); action->AddOutputParameter(new ParameterRelated("Name", *iPropertyProductName)); action->AddOutputParameter(new ParameterRelated("Info", *iPropertyProductInfo)); action->AddOutputParameter(new ParameterRelated("Url", *iPropertyProductUrl)); action->AddOutputParameter(new ParameterRelated("ImageUri", *iPropertyProductImageUri)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoProduct); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionStandby() { OpenHome::Net::Action* action = new OpenHome::Net::Action("Standby"); action->AddOutputParameter(new ParameterRelated("Value", *iPropertyStandby)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoStandby); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSetStandby() { OpenHome::Net::Action* action = new OpenHome::Net::Action("SetStandby"); action->AddInputParameter(new ParameterRelated("Value", *iPropertyStandby)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSetStandby); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSourceCount() { OpenHome::Net::Action* action = new OpenHome::Net::Action("SourceCount"); action->AddOutputParameter(new ParameterRelated("Value", *iPropertySourceCount)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSourceCount); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSourceXml() { OpenHome::Net::Action* action = new OpenHome::Net::Action("SourceXml"); action->AddOutputParameter(new ParameterRelated("Value", *iPropertySourceXml)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSourceXml); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSourceIndex() { OpenHome::Net::Action* action = new OpenHome::Net::Action("SourceIndex"); action->AddOutputParameter(new ParameterRelated("Value", *iPropertySourceIndex)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSourceIndex); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSetSourceIndex() { OpenHome::Net::Action* action = new OpenHome::Net::Action("SetSourceIndex"); action->AddInputParameter(new ParameterRelated("Value", *iPropertySourceIndex)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSetSourceIndex); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSetSourceIndexByName() { OpenHome::Net::Action* action = new OpenHome::Net::Action("SetSourceIndexByName"); action->AddInputParameter(new ParameterString("Value")); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSetSourceIndexByName); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSetSourceBySystemName() { OpenHome::Net::Action* action = new OpenHome::Net::Action("SetSourceBySystemName"); action->AddInputParameter(new ParameterString("Value")); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSetSourceBySystemName); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSource() { OpenHome::Net::Action* action = new OpenHome::Net::Action("Source"); action->AddInputParameter(new ParameterRelated("Index", *iPropertySourceIndex)); action->AddOutputParameter(new ParameterString("SystemName")); action->AddOutputParameter(new ParameterString("Type")); action->AddOutputParameter(new ParameterString("Name")); action->AddOutputParameter(new ParameterBool("Visible")); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSource); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionAttributes() { OpenHome::Net::Action* action = new OpenHome::Net::Action("Attributes"); action->AddOutputParameter(new ParameterRelated("Value", *iPropertyAttributes)); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoAttributes); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::EnableActionSourceXmlChangeCount() { OpenHome::Net::Action* action = new OpenHome::Net::Action("SourceXmlChangeCount"); action->AddOutputParameter(new ParameterUint("Value")); FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgProduct2Cpp::DoSourceXmlChangeCount); iService->AddAction(action, functor); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoManufacturer(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); std::string respName; std::string respInfo; std::string respUrl; std::string respImageUri; DvInvocationStd invocation(aInvocation); Manufacturer(invocation, respName, respInfo, respUrl, respImageUri); aInvocation.InvocationWriteStart(); DviInvocationResponseString respWriterName(aInvocation, "Name"); Brn buf_Name((const TByte*)respName.c_str(), (TUint)respName.length()); respWriterName.Write(buf_Name); aInvocation.InvocationWriteStringEnd("Name"); DviInvocationResponseString respWriterInfo(aInvocation, "Info"); Brn buf_Info((const TByte*)respInfo.c_str(), (TUint)respInfo.length()); respWriterInfo.Write(buf_Info); aInvocation.InvocationWriteStringEnd("Info"); DviInvocationResponseString respWriterUrl(aInvocation, "Url"); Brn buf_Url((const TByte*)respUrl.c_str(), (TUint)respUrl.length()); respWriterUrl.Write(buf_Url); aInvocation.InvocationWriteStringEnd("Url"); DviInvocationResponseString respWriterImageUri(aInvocation, "ImageUri"); Brn buf_ImageUri((const TByte*)respImageUri.c_str(), (TUint)respImageUri.length()); respWriterImageUri.Write(buf_ImageUri); aInvocation.InvocationWriteStringEnd("ImageUri"); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoModel(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); std::string respName; std::string respInfo; std::string respUrl; std::string respImageUri; DvInvocationStd invocation(aInvocation); Model(invocation, respName, respInfo, respUrl, respImageUri); aInvocation.InvocationWriteStart(); DviInvocationResponseString respWriterName(aInvocation, "Name"); Brn buf_Name((const TByte*)respName.c_str(), (TUint)respName.length()); respWriterName.Write(buf_Name); aInvocation.InvocationWriteStringEnd("Name"); DviInvocationResponseString respWriterInfo(aInvocation, "Info"); Brn buf_Info((const TByte*)respInfo.c_str(), (TUint)respInfo.length()); respWriterInfo.Write(buf_Info); aInvocation.InvocationWriteStringEnd("Info"); DviInvocationResponseString respWriterUrl(aInvocation, "Url"); Brn buf_Url((const TByte*)respUrl.c_str(), (TUint)respUrl.length()); respWriterUrl.Write(buf_Url); aInvocation.InvocationWriteStringEnd("Url"); DviInvocationResponseString respWriterImageUri(aInvocation, "ImageUri"); Brn buf_ImageUri((const TByte*)respImageUri.c_str(), (TUint)respImageUri.length()); respWriterImageUri.Write(buf_ImageUri); aInvocation.InvocationWriteStringEnd("ImageUri"); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoProduct(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); std::string respRoom; std::string respName; std::string respInfo; std::string respUrl; std::string respImageUri; DvInvocationStd invocation(aInvocation); Product(invocation, respRoom, respName, respInfo, respUrl, respImageUri); aInvocation.InvocationWriteStart(); DviInvocationResponseString respWriterRoom(aInvocation, "Room"); Brn buf_Room((const TByte*)respRoom.c_str(), (TUint)respRoom.length()); respWriterRoom.Write(buf_Room); aInvocation.InvocationWriteStringEnd("Room"); DviInvocationResponseString respWriterName(aInvocation, "Name"); Brn buf_Name((const TByte*)respName.c_str(), (TUint)respName.length()); respWriterName.Write(buf_Name); aInvocation.InvocationWriteStringEnd("Name"); DviInvocationResponseString respWriterInfo(aInvocation, "Info"); Brn buf_Info((const TByte*)respInfo.c_str(), (TUint)respInfo.length()); respWriterInfo.Write(buf_Info); aInvocation.InvocationWriteStringEnd("Info"); DviInvocationResponseString respWriterUrl(aInvocation, "Url"); Brn buf_Url((const TByte*)respUrl.c_str(), (TUint)respUrl.length()); respWriterUrl.Write(buf_Url); aInvocation.InvocationWriteStringEnd("Url"); DviInvocationResponseString respWriterImageUri(aInvocation, "ImageUri"); Brn buf_ImageUri((const TByte*)respImageUri.c_str(), (TUint)respImageUri.length()); respWriterImageUri.Write(buf_ImageUri); aInvocation.InvocationWriteStringEnd("ImageUri"); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoStandby(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); bool respValue; DvInvocationStd invocation(aInvocation); Standby(invocation, respValue); aInvocation.InvocationWriteStart(); DviInvocationResponseBool respWriterValue(aInvocation, "Value"); respWriterValue.Write(respValue); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSetStandby(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); bool Value = aInvocation.InvocationReadBool("Value"); aInvocation.InvocationReadEnd(); DvInvocationStd invocation(aInvocation); SetStandby(invocation, Value); aInvocation.InvocationWriteStart(); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSourceCount(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); uint32_t respValue; DvInvocationStd invocation(aInvocation); SourceCount(invocation, respValue); aInvocation.InvocationWriteStart(); DviInvocationResponseUint respWriterValue(aInvocation, "Value"); respWriterValue.Write(respValue); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSourceXml(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); std::string respValue; DvInvocationStd invocation(aInvocation); SourceXml(invocation, respValue); aInvocation.InvocationWriteStart(); DviInvocationResponseString respWriterValue(aInvocation, "Value"); Brn buf_Value((const TByte*)respValue.c_str(), (TUint)respValue.length()); respWriterValue.Write(buf_Value); aInvocation.InvocationWriteStringEnd("Value"); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSourceIndex(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); uint32_t respValue; DvInvocationStd invocation(aInvocation); SourceIndex(invocation, respValue); aInvocation.InvocationWriteStart(); DviInvocationResponseUint respWriterValue(aInvocation, "Value"); respWriterValue.Write(respValue); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSetSourceIndex(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); uint32_t Value = aInvocation.InvocationReadUint("Value"); aInvocation.InvocationReadEnd(); DvInvocationStd invocation(aInvocation); SetSourceIndex(invocation, Value); aInvocation.InvocationWriteStart(); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSetSourceIndexByName(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); Brhz buf_Value; aInvocation.InvocationReadString("Value", buf_Value); std::string Value((const char*)buf_Value.Ptr(), buf_Value.Bytes()); aInvocation.InvocationReadEnd(); DvInvocationStd invocation(aInvocation); SetSourceIndexByName(invocation, Value); aInvocation.InvocationWriteStart(); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSetSourceBySystemName(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); Brhz buf_Value; aInvocation.InvocationReadString("Value", buf_Value); std::string Value((const char*)buf_Value.Ptr(), buf_Value.Bytes()); aInvocation.InvocationReadEnd(); DvInvocationStd invocation(aInvocation); SetSourceBySystemName(invocation, Value); aInvocation.InvocationWriteStart(); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSource(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); uint32_t Index = aInvocation.InvocationReadUint("Index"); aInvocation.InvocationReadEnd(); std::string respSystemName; std::string respType; std::string respName; bool respVisible; DvInvocationStd invocation(aInvocation); Source(invocation, Index, respSystemName, respType, respName, respVisible); aInvocation.InvocationWriteStart(); DviInvocationResponseString respWriterSystemName(aInvocation, "SystemName"); Brn buf_SystemName((const TByte*)respSystemName.c_str(), (TUint)respSystemName.length()); respWriterSystemName.Write(buf_SystemName); aInvocation.InvocationWriteStringEnd("SystemName"); DviInvocationResponseString respWriterType(aInvocation, "Type"); Brn buf_Type((const TByte*)respType.c_str(), (TUint)respType.length()); respWriterType.Write(buf_Type); aInvocation.InvocationWriteStringEnd("Type"); DviInvocationResponseString respWriterName(aInvocation, "Name"); Brn buf_Name((const TByte*)respName.c_str(), (TUint)respName.length()); respWriterName.Write(buf_Name); aInvocation.InvocationWriteStringEnd("Name"); DviInvocationResponseBool respWriterVisible(aInvocation, "Visible"); respWriterVisible.Write(respVisible); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoAttributes(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); std::string respValue; DvInvocationStd invocation(aInvocation); Attributes(invocation, respValue); aInvocation.InvocationWriteStart(); DviInvocationResponseString respWriterValue(aInvocation, "Value"); Brn buf_Value((const TByte*)respValue.c_str(), (TUint)respValue.length()); respWriterValue.Write(buf_Value); aInvocation.InvocationWriteStringEnd("Value"); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::DoSourceXmlChangeCount(IDviInvocation& aInvocation) { aInvocation.InvocationReadStart(); aInvocation.InvocationReadEnd(); uint32_t respValue; DvInvocationStd invocation(aInvocation); SourceXmlChangeCount(invocation, respValue); aInvocation.InvocationWriteStart(); DviInvocationResponseUint respWriterValue(aInvocation, "Value"); respWriterValue.Write(respValue); aInvocation.InvocationWriteEnd(); } void DvProviderAvOpenhomeOrgProduct2Cpp::Manufacturer(IDvInvocationStd& /*aInvocation*/, std::string& /*aName*/, std::string& /*aInfo*/, std::string& /*aUrl*/, std::string& /*aImageUri*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::Model(IDvInvocationStd& /*aInvocation*/, std::string& /*aName*/, std::string& /*aInfo*/, std::string& /*aUrl*/, std::string& /*aImageUri*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::Product(IDvInvocationStd& /*aInvocation*/, std::string& /*aRoom*/, std::string& /*aName*/, std::string& /*aInfo*/, std::string& /*aUrl*/, std::string& /*aImageUri*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::Standby(IDvInvocationStd& /*aInvocation*/, bool& /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::SetStandby(IDvInvocationStd& /*aInvocation*/, bool /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::SourceCount(IDvInvocationStd& /*aInvocation*/, uint32_t& /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::SourceXml(IDvInvocationStd& /*aInvocation*/, std::string& /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::SourceIndex(IDvInvocationStd& /*aInvocation*/, uint32_t& /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::SetSourceIndex(IDvInvocationStd& /*aInvocation*/, uint32_t /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::SetSourceIndexByName(IDvInvocationStd& /*aInvocation*/, const std::string& /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::SetSourceBySystemName(IDvInvocationStd& /*aInvocation*/, const std::string& /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::Source(IDvInvocationStd& /*aInvocation*/, uint32_t /*aIndex*/, std::string& /*aSystemName*/, std::string& /*aType*/, std::string& /*aName*/, bool& /*aVisible*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::Attributes(IDvInvocationStd& /*aInvocation*/, std::string& /*aValue*/) { ASSERTS(); } void DvProviderAvOpenhomeOrgProduct2Cpp::SourceXmlChangeCount(IDvInvocationStd& /*aInvocation*/, uint32_t& /*aValue*/) { ASSERTS(); }
4f918adc3986c66a49e26a3bcd5985cf8ff5abec
eb48aad8f83ee1a2647b1c0e7297ef2187bcc3cb
/src/Basic2D/Model.h
47117e2b56211c8bc826d5e010a77bf5cae941ca
[]
no_license
Thsuva/ProjectCG
cd5328dd9a4a0087dd01b0e581ce4664b5b74631
def75c5bff19fc1eb554352e97acf2504b34e04c
refs/heads/master
2022-04-10T21:26:17.756493
2020-04-01T08:13:29
2020-04-01T08:13:29
221,173,592
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
9,163
h
Model.h
/////////////////////////////////////////////////////////////////// // A basic skeleton for 2D like game developpers. // // model data /////////////////////////////////////////////////////////////////// // world geometry // eye (0,0,0) // center (0,0,-1) // up (0,1,0) // left -1, right 1 // top & bottom centered on Y to match the window aspect ratio // clipping planes: 1, 5.1 #pragma warning(disable: 4996) #include <vector> #include <time.h> #include <math.h> #include <list> #define PI 3.141592654 // A class for storing vetices // Vertex class Vertex { public: float x, y, z; // 3d coordinate of the vertex float Nx, Ny, Nz; // Normal to the surface (if present) float u, v; // texture coordinates float r, g, b; // Color (0.0 - 1.0) Vertex() {} Vertex(float x, float y, float z) : x(x), y(y), z(z) { } Vertex(float x, float y, float z, float u, float v) : x(x), y(y), z(z), u(u), v(v) { } inline void SetP(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } inline void SetN(float x, float y, float z) { Nx = x; Ny = y; Nz = z; } }; class Bullet { public: std::vector<Vertex> bullet; // floating personaggio bool alive; // per i movimenti float bullet_x; float bullet_y; float bullet_horizontal_transl; float bullet_vertical_transl; float bullet_vel_h; float b_height = 0.01; float b_width = 0.01; public: // methods Bullet(float b_x, float b_y, float trasl_x, float trasl_y, float my_vel) { alive = true; bullet_x = b_x; bullet_y = b_y; bullet_horizontal_transl = trasl_x; bullet_vertical_transl = trasl_y; bullet_vel_h = my_vel; bullet.clear(); bullet.push_back(Vertex(-0.005, 0.045, -1, 0, 0)); bullet.push_back(Vertex(0.005, 0.045, -1, 1, 0)); bullet.push_back(Vertex(0.005, 0.055, -1, 1, 1)); bullet.push_back(Vertex(-0.005, 0.055, -1, 0, 1)); } void Update_position(); void Die(); int round(double value); ~Bullet() { } }; class Character { public: std::vector<Vertex> personaggio; // floating personaggio bool alive; bool god_mode; // per i movimenti int character_direction; float player_x; float player_y; float player_horizontal_transl; float player_vertical_transl; float p_height = 0.1; float p_width = 0.1; float vel_h; float vel_v; float MAX_VEL_H = 0.00025 * 10; float MAX_VEL_V = 0.00025 * 50; //collision tile of feet int left_tile = 19; int middle_feet_tile=19; int right_tile=20; //collision tile of body int bottom_tile = 11; int middle_body_tile = 11; int top_tile = 10; int weapon = 0; bool bump; public: // methods Character() { alive = true; bump = false; god_mode = false; // inizialmente il personaggio è orientato verso destra character_direction = -1; } ~Character() { } // inizio nostre funzioni void MoveOrCollide(double nvel_h); void Move_up_down_personaggio(int dir); bool Jump_personaggio(); void Setup_position(); void Gravity(); bool Is_on_tile(); void Die(); void Convert_coordinate_for_translation(); Bullet shoot(); int round(double value); }; class Personaggio : public Character { public: bool has_moved; bool has_won; bool death_complete; int motion_status; public: Personaggio() : Character(){ has_moved = false; has_won = false; death_complete = false; player_x = 1; player_y = 0.55; vel_h = 0; vel_v = 0; motion_status = 0; personaggio.clear(); personaggio.push_back(Vertex(-0.05, 0, -1, 0, 0)); personaggio.push_back(Vertex(0.05, 0, -1, 1, 0)); personaggio.push_back(Vertex(0.05, 0.1, -1, 1, 1)); personaggio.push_back(Vertex(-0.05, 0.1, -1, 0, 1)); } ~Personaggio(){ } }; class Enemy : public Character { public: int id; int type; Enemy(int x, int y, int my_id, int my_type) : Character() { id = my_id; type = my_type; player_x = .05 * (x+1); player_y = .05 * (y+1); vel_h = 0; vel_v = 0; personaggio.clear(); personaggio.push_back(Vertex(-0.05, 0, -1, 0, 0)); personaggio.push_back(Vertex(0.05, 0, -1, 1, 0)); personaggio.push_back(Vertex(0.05, 0.1, -1, 1, 1)); personaggio.push_back(Vertex(-0.05, 0.1, -1, 0, 1)); } void random_move(float hero_player_x, int level_width); ~Enemy() { } }; class Door { public: std::vector<Vertex> porta; int id; double door_horizontal_transl; double door_vertical_transl; float p_height = 0.15; float p_width = 0.1; Door(int x, int y, int my_id) { id = my_id; door_horizontal_transl = (.05 * 20) - (.05 * (x + 1)); door_vertical_transl = (.05 * (y + 1)) - (.05 * 11); porta.clear(); porta.push_back(Vertex(-0.05, 0, -2, 0, 0)); porta.push_back(Vertex(0.05, 0, -2, 1, 0)); porta.push_back(Vertex(0.05, 0.15, -2, 1, 1)); porta.push_back(Vertex(-0.05, 0.15, -2, 0, 1)); } ~Door() { } }; class MyModel { public: // general data for window and input controls HDC hDC; // Private GDI Device Context HGLRC hRC; // Permanent Rendering Context HWND hWnd; // Holds Our Window Handle HINSTANCE hInstance; // Holds The Instance Of The Application bool keys[256]; // Array Used For The Keyboard Routine bool active; // Window Active Flag Set To TRUE By Default bool fullscreen; // Fullscreen Flag bool game_started; bool enemy_hit_by_bullet; int texture_delay; Personaggio Player; std::list<Enemy> enemy_list; std::list<Bullet> bullet_list; std::list<Door> door_list; private: // projection limits in X and Y: x in [-plx, plx], y in [-ply, ply] double plx, ply; int Wheight, Wwidth; // window dimensions in pixels int frames; // n. of frames double frameTime; // for fps computation double fps; // model data std::vector<Vertex> Background; // background std::vector<Vertex> Background2; // background2 std::vector<Vertex> Background3; // background3 std::vector<Vertex> tile; // blocco base clock_t Tstamp, Tstart; double Full_elapsed; // elapsed time in seconds from the beginning of the program double Shot_elapsed; double Bump_elapsed; double Motion_elapsed; double Jump_elapsed; GLuint texture[28]; // Storage For 28 Textures! GLuint base; // Base Display List For The Font Set std::string level = ""; int num_of_screens = 9; int screen_width = 40; int level_height = 24; public: // methods MyModel() : hDC(NULL), hRC(NULL), hWnd(NULL), active(true), fullscreen(true), frames(0), fps(0){ game_started = false; enemy_hit_by_bullet = false; texture_delay = 0; Shot_elapsed = 1; Jump_elapsed = 1; Background.clear(); Background2.clear(); Background3.clear(); tile.clear(); // i primi 2 valori dei vertex sono stati cambiati per fittare il 16/9 // (prima erano tutti -1 e 1 per generare un quadrato di lato 2 centrato in 0,0) Background.push_back(Vertex(-1, -1.8, -5, 0, 0)); Background.push_back(Vertex(5, -1.8, -5, 1, 0)); Background.push_back(Vertex(5, 1.8, -5, 1, 1)); Background.push_back(Vertex(-1, 1.8, -5, 0, 1)); Background2.push_back(Vertex(4.99, -1.8, -5, 0, 0)); Background2.push_back(Vertex(11, -1.8, -5, 1, 0)); Background2.push_back(Vertex(11, 1.8, -5, 1, 1)); Background2.push_back(Vertex(4.99, 1.8, -5, 0, 1)); Background3.push_back(Vertex(10.99, -1.8, -5, 0, 0)); Background3.push_back(Vertex(17, -1.8, -5, 1, 0)); Background3.push_back(Vertex(17, 1.8, -5, 1, 1)); Background3.push_back(Vertex(10.99, 1.8, -5, 0, 1)); tile.push_back(Vertex(-.025, 0, -4, 0, 0)); tile.push_back(Vertex(.025, 0, -4, 1, 0)); tile.push_back(Vertex(.025, .05, -4, 1, 1)); tile.push_back(Vertex(-.025, .05, -4, 0, 1)); this->Tstart = this->Tstamp = clock(); this->Full_elapsed = 0; this->frameTime = 0; } ~MyModel() { this->KillFont(); } bool DrawGLScene(void); bool InitGL(void); void ReSizeGLScene(int width, int height); void glPrint(const char *fmt, ...); // Custom GL "Print" Routine // inizio nostre funzioni void Set_level(); char Get_tile(int x, int y); void Set_tile(int x, int y, char c); int Get_level_width(); int Get_level_height(); void Check_collisions(); double Get_last_shot_elapsed(); void Set_shot_elapsed(); double Get_last_bump_elapsed(); void Set_bump_elapsed(); double Get_last_motion_elapsed(); void Set_motion_elapsed(); double Get_last_jump_elapsed(); void Set_jump_elapsed(); private: bool LoadGLTextures(void); void BuildFont(void); void KillFont(void); // Conversion from pixel distance to float X and Y distance inline float PixToCoord_X(int pix) { return (2.0f * (float)pix * (float)plx) / (float)Wwidth; } inline float PixToCoord_Y(int pix) { return (2.0f * (float)pix * (float)ply) / (float)Wheight; } }; extern class MyModel Data; bool Distance(double player_x, double player_y, double enemy_x, double enemy_y);
717377d0d2b39d1cdf0692e3f7ba230cced2f854
73110e3a8901a3b597ffcd275e7c5cc900d3d859
/GroupProj/ScanParser.cpp
5182e216d636a315225fcc95aed0d8f7c5bde54b
[ "MIT" ]
permissive
NicholasJW/EyeMoveDetector
5bfa53f757053b8b18d1b1f06fed0a895fd7df1f
56ae7117d2359782c43a19a411506ab40ac72fd1
refs/heads/master
2021-07-20T21:33:23.071384
2017-10-24T02:17:08
2017-10-24T02:17:08
108,065,927
0
0
null
null
null
null
UTF-8
C++
false
false
8,158
cpp
ScanParser.cpp
/* * ScanParser.cpp * * Created on: Nov 8, 2016 * Author: KWChen */ #include "ScanParser.h" ScanParser::ScanParser(string filename) { // TODO Auto-generated constructor stub Scan s; myFormatCorrect = true; ifstream in; in.open(filename.c_str()); if (in.bad()) { myFormatCorrect = false; } else { string line; while (getline(in, line)) { cout << line << endl; try { if (isComment(line) || isText(line) || isBlank(line) ) {continue;} if (!(isComment(line) || isText(line) || isBlank(line) ) ){break;} } catch (out_of_range) { break; } } while (getline(in, line)) { bool inData = false; bool lineIsTarget = false; // cout << line << endl; if (isTargetMsg(line)){ parseTarget(line); continue; } if (!isTargetMsg(line)) { if (isComment(line) || isText(line) || isBlank(line) ) {continue;} // lineIsTarget = true; } string dataEntry[80]; int cell_count = 0; if (line.length() ==0) { continue; } getTokens(line, dataEntry, cell_count, lineIsTarget); bool success = setValues(s, dataEntry, cell_count, lineIsTarget); //TODO: continue if (!success) { //invalid number of cells read myFormatCorrect = false; break; } myScans.push_back(s); } } myScanIndex = 0; } ScanParser::~ScanParser() { // TODO Auto-generated destructor stub } Scan ScanParser::getNextScan() { if (myScanIndex < (int) (myScans.size())) { myScanIndex++; return myScans[myScanIndex - 1]; } Scan s; return s; } Scan ScanParser::getNextTarget() { if (myTargetIndex < (int) (myTargets.size())) { myTargetIndex++; return myTargets[myTargetIndex - 1]; } Scan t; return t; } bool ScanParser::setValues(Scan& s, string* entry, int cell_count, bool isTarget) { if (isTarget) { return true; } else if (cell_count != NUMFIELDS) { // cout << "fail" << cell_count << endl; return false; } /* • timestamp is the time in milliseconds since the monitoring computer was started. • leye x is the x coordinate of the left eye gaze position in pixels. • leye y is the y coordinate of the left eye gaze position in pixels. • l pupil is the diameter of the left pupil in millimeters. • reye x is the x coordinate of the right eye gaze position in pixels. • reye y is the y coordinate of the right eye gaze position in pixels. • r pupil is the diameter of the right pupil in millimeters. 3 • leye xvel is the x component of the left eye’s velocity in degrees per second. • leye yvel is the y component of the left eye’s velocity in degrees per second. • reye xvel is the x component of the right eye’s velocity in degrees per second. • reye yvel is the y component of the right eye’s velocity in degrees per second. • xres is the resolution for the x dimension in pixels per degree. • yres is the resolution for the y dimension in pixels per degree*/ s.setTime(cvtNumString2Number(entry[TIME])); s.setLeftGazePos(GazePos (cvtNumString2Number(entry[L_EYE_X]),cvtNumString2Number(entry[L_EYE_Y])) ); s.setRightGazePos(GazePos (cvtNumString2Number(entry[R_EYE_X]), cvtNumString2Number(entry[R_EYE_Y])) ); s.setLeftPupil(Pupil (cvtNumString2Number( entry[L_PUPIL]))); s.setRightPupil(Pupil (cvtNumString2Number( entry[R_PUPIL]))); s.setResolution(Resolution (cvtNumString2Number( entry[X_RES]), cvtNumString2Number( entry[Y_RES])) ); s.setLeftVelocity(Velocity( cvtNumString2Number( entry[L_EYE_XVEL] ), cvtNumString2Number( entry[L_EYE_YVEL])) ); s.setRightVelocity(Velocity( cvtNumString2Number( entry[R_EYE_XVEL] ), cvtNumString2Number( entry[R_EYE_YVEL])) ); s.setTargetPos(myPreviousTargetPos); // cout << "good" << endl; return true; } void ScanParser::getTokens(string line, string* cell, int& numCells, bool isTarget) { string dataLabel = line.substr(0, 3); while (isAlpha(line[0]) ) {//skip the preamble numCells = 0; return; } if (dataLabel.compare("MSG") == 0) { parseTarget(line); isTarget = true; return; } /*if (dataLabel.compare("MSG") == 0) {//line is a target pos parseTarget(line); isTarget = true;//tells parser that this scan is a target int len = line.length(); int p = 0; //position in line int i = 0; while (p < len) { //target entry looks like this //MSG 2958082.0 -16 !V TARGET_POS TARG1 (960, 600) 1 0 while (p < len && isWhitespace(line.at(p))) p++; if (line.at(p) == '(' || line.at(p) == ')') p++; //data entry starts bool flag = false; while (p < len && !isWhitespace(line.at(p)) && !isSymbol(line.at(p))){ cell[i] = cell[i] + line.at(p); flag = true; p++; } if (flag == true){ numCells ++; } i++; } return; }*/ if (!isAlpha(line[0])){//scan line start isTarget = false; int len = line.length(); if (len == 0) return; int p = 0; // position in line int i = 0; while (p < len) { while (p < len && isWhitespace(line.at(p))) p++; //data entry may start bool flag = false; while (p < len && !isWhitespace(line.at(p))){ cell[i] = cell[i] + line.at(p); flag = true; p++; } if (flag == true){ numCells ++; } i++; } } } void ScanParser::parseTarget(string line) { TargetPos t; int len = line.length(); if (len == 0) return; int p = 0;//position in line // line.at(p) is whitespace or p >= len while (p < len && ( isWhitespace(line.at(p)) || isAlpha(line.at(p)) ) ) p++; //time starts string timeStr = ""; while (p < len && !isWhitespace(line.at(p))){ timeStr += line.at(p); p++; } t.recentTargetTime = cvtNumString2Number(timeStr); //time ends //look for coordinate while (p < len && (line.at(p) != '(' ) ) { p++; } //coordinate starts string coordinateX = ""; while (p < len && line.at(p) != ','){ coordinateX += line.at(p); p++; } t.targetGazePos.xPos = cvtNumString2Number(coordinateX); while (p < len && ( isAlpha(line.at(p)) || isWhitespace(line.at(p))) ) { p++; } string coordinateY = ""; while (p < len && !isAlpha(line.at(p))){ coordinateY += line.at(p); p++; } t.targetGazePos.yPos = cvtNumString2Number(coordinateY); myPreviousTargetPos = t; Scan target; target.setTargetPos(t); target.toggleIsTarget(); myTargets.push_back(target); } bool ScanParser::isScan(string s) { return false; } bool ScanParser::isNumberString(string s) // Returns true if s represents a valid decimal integer { int len = s.length(); if (len == 0) return false; if ((isSign(s.at(0)) && len > 1) || isDigit(s.at(0)) || isDecPoint (s.at(0))) { // check remaining characters for (int i=1; i < len; i++) { if (!isdigit(s.at(i))) return false; } return true; } return false; } double ScanParser::cvtNumString2Number(string s) { // stringstream ss = new stringstream(); // ss << "d"; int k = 1; int val = 0; int decimal = 0; int decK = 0.1; int decPt = 0; for ( ; decPt < s.length() - 1; decPt ++) {//find decimal point index char c = s.at(decPt); if (c == '.') {break;} } for (int i = decPt + 1; i < s.length() - 1; i++) {// char c = s.at(i); decimal += k*((int)(c - '0')); decK /= 10; } for (int i = decPt - 1; i > 0; i--) { char c = s.at(i); val = val + k*((int) (c - '0')); k *= 10; } if (isSign(s.at(0))) { if (s.at(0) == '-') val *= -1; } else { val += k*((int)(s.at(0) - '0')); } return val + decimal; } int ScanParser::cvtNumString2Int(string s) // Converts a string to an integer. Assumes s is something like "-231" and produces -231 { if (!isNumberString(s)) { cerr << "Non-numberic string passed to cvtNumString2Number" << endl; return 0; } int k = 1; int val = 0; for (int i = s.length()-1; i>0; i--) { char c = s.at(i); val = val + k*((int)(c - '0')); k = k*10; } if (isSign(s.at(0))) { if (s.at(0) == '-') val = -1*val; } else { val = val + k*((int)(s.at(0) - '0')); } return val; } bool ScanParser::isTargetMsg(string s) { //MSG 2958082.0 -16 !V TARGET_POS TARG1 (960, 600) 1 0 if (s.find("TARGET_POS") != s.npos) { // if (s.at(0) == 'M'){ return true; } return false; }
fb75db9ceb22d7c421bee28cbba9b545731a536e
ce0d47673cfdaed48c6b415c4d940a694588a868
/FastSimulation/CTPPSFastGeometry/interface/CTPPSTrkDetector.h
5b518449266333bf79a243619e22ae8f5e9b6854
[]
no_license
sfonsecaUERJ/CTPPSFastSimDev
a59fe09af2c16021a4a7a76e8b4cb85b2d3c048f
10940a90cab266851483654ced38969a956f0831
refs/heads/master
2020-06-14T14:03:29.038164
2017-04-18T16:14:08
2017-04-18T16:14:08
83,049,382
0
1
null
null
null
null
UTF-8
C++
false
false
823
h
CTPPSTrkDetector.h
#ifndef CTPPSTrkDetector_h #define CTPPSTrkDetector_h #include <vector> class CTPPSTrkDetector { public: CTPPSTrkDetector(double detw, double deth, double detin); virtual ~CTPPSTrkDetector() {}; public: const double DetectorWidth; const double DetectorHeight; const double DetectorPosition; std::vector<unsigned int> DetId; int NHits; std::vector<double> X; std::vector<double> Y; std::vector<double> Z; void clear() {DetId.clear();NHits=0;X.clear();Y.clear();Z.clear();}; void AddHit(unsigned int detID,double x, double y, double z); }; typedef std::pair<CTPPSTrkDetector,CTPPSTrkDetector> CTPPSTrkStation; #endif
ff5ef440671b4ac827f1ed436417551523ad325c
d341408bd1526239440ef8f057db0a2005232a7c
/취업을위한알고리즘문제풀이/나이차이.cpp
2104140eb6cb5919c5d86eb5d15035f9ac38a8e9
[]
no_license
juneeda-maker/Algorithm
28d7a01e3fe4e6bd3226a43e7ec42b1e40bde8cc
84298bb7118142478c8527dd64642d95d8a31aa4
refs/heads/master
2023-07-21T06:24:52.427155
2021-09-06T07:29:48
2021-09-06T07:29:48
320,888,572
2
0
null
null
null
null
UTF-8
C++
false
false
446
cpp
나이차이.cpp
#include <iostream> using namespace std; int main() { //freopen("input.txt", "rt", stdin); //입력할 데이터가 많을경우 input.txt파일 생성해서 입력 int n; int age; int max = 0; int min = 2100000000; cin >> n; for(int i = 0; i < n; i++) { cin >> age; if(age > max) max = age; if(age < min) min = age; } cout << max - min << '\n'; }
16d22878c0c6694b7d07b7bc88aa055c1a1b337d
5464d8f847aecb3cbab7629485a1fdff707f0a3d
/s32v234_sdk/libs/arm/apexcv_base/arithmetic/include/apexcv_arithmetic_func.h
f6f31e1abf336acc49b90752f3a15c8a7670b2d5
[]
no_license
kernal88/VisionSDK
73e0d1280ac1574a43f129e0ab8940e8be86000e
63dfbbb8800c647ac9d23dae08de946e7c1ab6f3
refs/heads/master
2021-06-02T14:26:44.838058
2016-03-22T00:34:08
2016-03-22T00:34:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,908
h
apexcv_arithmetic_func.h
/***************************************************************************** * * Freescale Confidential Proprietary * * Copyright (c) 2013 Freescale Semiconductor; * All Rights Reserved * ***************************************************************************** * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED 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 FREESCALE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /*!********************************************************************************* * \file apexcv_arithmetic.hpp * \brief Host-ACF interface for arithmetic operations. ***********************************************************************************/ #ifndef _APEXCV_ARITHMETIC_FUNC_H_ #define _APEXCV_ARITHMETIC_FUNC_H_ #ifndef APEX2_EMULATE #include <icp_data.h> using namespace icp; #else #include "acf_data_descriptor.hpp" using namespace APEX2; #endif #include "apexcv_mat.hpp" /*!********************************************************************************* * \brief Host-ACF interface for arithmetic operations. * * This template class is an interface for creating, initializing, processing and releasing * the APU implementation of the arithmetic kernels on the host. ***********************************************************************************/ namespace apexcv { void add(apexcv::Mat& src0, apexcv::Mat& src1, apexcv::Mat& dest, apexcv::Mat mask = Mat(), int dtype = -1); apexcv::Mat abs(apexcv::Mat& src); // NOT YET IMPLEMENTED!! Just mimicks of being there, in order not to cause compile errors when compiling with APEXCV flag //! computes element-wise weighted product of the two arrays (dst = scale*src1*src2) void multiply(apexcv::Mat& src1, apexcv::Mat& src2, apexcv::Mat& dst, double scale = 1, int dtype = -1); /* TO BE IMPLEMENTED subtract(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray(), int dtype = -1); //! computes element-wise weighted quotient of the two arrays (dst = scale*src1/src2) void divide(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1); //! computes element-wise weighted reciprocal of an array (dst = scale/src2) void divide(double scale, InputArray src2, OutputArray dst, int dtype = -1); //! adds scaled array to another one (dst = alpha*src1 + src2) void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); //! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma) void addWeighted(InputArray src1, double alpha, InputArray src2, double beta, double gamma, OutputArray dst, int dtype = -1); //! scales array elements, computes absolute values and converts the results to 8-bit unsigned integers: dst(i)=saturate_cast<uchar>abs(src(i)*alpha+beta) void convertScaleAbs(InputArray src, OutputArray dst, double alpha = 1, double beta = 0); //! transforms array of numbers using a lookup table: dst(i)=lut(src(i)) void LUT(InputArray src, InputArray lut, OutputArray dst, int interpolation = 0); //! computes sum of array elements CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); //! computes the number of nonzero array elements int countNonZero(InputArray src); //! returns the list of locations of non-zero pixels void findNonZero(InputArray src, OutputArray idx); //! computes mean value of selected array elements Scalar mean(InputArray src, InputArray mask = noArray()); //! computes mean value and standard deviation of all or selected array elements void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, InputArray mask = noArray()); //! computes norm of the selected array part double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray()); //! computes norm of selected part of the difference between two arrays double norm(InputArray src1, InputArray src2, int normType = NORM_L2, InputArray mask = noArray()); //! naive nearest neighbor finder void batchDistance(InputArray src1, InputArray src2, OutputArray dist, int dtype, OutputArray nidx, int normType = NORM_L2, int K = 0, InputArray mask = noArray(), int update = 0, bool crosscheck = false); //! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values void normalize(InputArray src, OutputArray dst, double alpha = 1, double beta = 0, int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray()); //! finds global minimum and maximum array elements and returns their values and their locations void minMaxLoc(InputArray src, CV_OUT double* minVal, CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0, CV_OUT Point* maxLoc = 0, InputArray mask = noArray()); void minMaxIdx(InputArray src, double* minVal, double* maxVal, int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray()); //! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1); //! makes multi-channel array out of several single-channel arrays void merge(const Mat* mv, size_t count, OutputArray dst); void merge(const vector<Mat>& mv, OutputArray dst); //! makes multi-channel array out of several single-channel arrays void merge(InputArrayOfArrays mv, OutputArray dst); //! copies each plane of a multi-channel array to a dedicated array void split(const Mat& src, Mat* mvbegin); void split(const Mat& m, vector<Mat>& mv); //! copies each plane of a multi-channel array to a dedicated array void split(InputArray m, OutputArrayOfArrays mv); //! copies selected channels from the input arrays to the selected channels of the output arrays void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, const int* fromTo, size_t npairs); void mixChannels(const vector<Mat>& src, vector<Mat>& dst, const int* fromTo, size_t npairs); void mixChannels(InputArrayOfArrays src, InputArrayOfArrays dst, const vector<int>& fromTo); //! extracts a single channel from src (coi is 0-based index) void extractChannel(InputArray src, OutputArray dst, int coi); //! inserts a single channel to dst (coi is 0-based index) void insertChannel(InputArray src, InputOutputArray dst, int coi); //! reverses the order of the rows, columns or both in a matrix void flip(InputArray src, OutputArray dst, int flipCode); //! replicates the input matrix the specified number of times in the horizontal and/or vertical direction void repeat(InputArray src, int ny, int nx, OutputArray dst); Mat repeat(const Mat& src, int ny, int nx); void hconcat(const Mat* src, size_t nsrc, OutputArray dst); void hconcat(InputArray src1, InputArray src2, OutputArray dst); void hconcat(InputArrayOfArrays src, OutputArray dst); void vconcat(const Mat* src, size_t nsrc, OutputArray dst); void vconcat(InputArray src1, InputArray src2, OutputArray dst); void vconcat(InputArrayOfArrays src, OutputArray dst); //! computes bitwise conjunction of the two arrays (dst = src1 & src2) void bitwise_and(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray()); //! computes bitwise disjunction of the two arrays (dst = src1 | src2) void bitwise_or(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray()); //! computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2) void bitwise_xor(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray()); //! inverts each bit of array (dst = ~src) void bitwise_not(InputArray src, OutputArray dst, InputArray mask = noArray()); //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2)) void absdiff(InputArray src1, InputArray src2, OutputArray dst); //! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) void inRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst); //! compares elements of two arrays (dst = src1 <cmpop> src2) void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); //! computes per-element minimum of two arrays (dst = min(src1, src2)) void min(InputArray src1, InputArray src2, OutputArray dst); //! computes per-element maximum of two arrays (dst = max(src1, src2)) void max(InputArray src1, InputArray src2, OutputArray dst); //! computes per-element minimum of two arrays (dst = min(src1, src2)) void min(const Mat& src1, const Mat& src2, Mat& dst); //! computes per-element minimum of array and scalar (dst = min(src1, src2)) void min(const Mat& src1, double src2, Mat& dst); //! computes per-element maximum of two arrays (dst = max(src1, src2)) void max(const Mat& src1, const Mat& src2, Mat& dst); //! computes per-element maximum of array and scalar (dst = max(src1, src2)) void max(const Mat& src1, double src2, Mat& dst); //! computes square root of each matrix element (dst = src**0.5) void sqrt(InputArray src, OutputArray dst); //! raises the input matrix elements to the specified power (b = a**power) void pow(InputArray src, double power, OutputArray dst); //! computes exponent of each matrix element (dst = e**src) void exp(InputArray src, OutputArray dst); //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src)) void log(InputArray src, OutputArray dst); //! computes cube root of the argument float cubeRoot(float val); //! computes the angle in degrees (0..360) of the vector (x,y) float fastAtan2(float y, float x); void exp(const float* src, float* dst, int n); void log(const float* src, float* dst, int n); void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); void magnitude(const float* x, const float* y, float* dst, int n); //! converts polar coordinates to Cartesian void polarToCart(InputArray magnitude, InputArray angle, OutputArray x, OutputArray y, bool angleInDegrees = false); //! converts Cartesian coordinates to polar void cartToPolar(InputArray x, InputArray y, OutputArray magnitude, OutputArray angle, bool angleInDegrees = false); //! computes angle (angle(i)) of each (x(i), y(i)) vector void phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees = false); //! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector void magnitude(InputArray x, InputArray y, OutputArray magnitude); //! checks that each matrix element is within the specified range. bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0, double minVal = -DBL_MAX, double maxVal = DBL_MAX); //! converts NaN's to the given number void patchNaNs(InputOutputArray a, double val = 0); //! implements generalized matrix product algorithm GEMM from BLAS void gemm(InputArray src1, InputArray src2, double alpha, InputArray src3, double beta, OutputArray dst, int flags = 0); //! multiplies matrix by its transposition from the left or from the right void mulTransposed(InputArray src, OutputArray dst, bool aTa, InputArray delta = noArray(), double scale = 1, int dtype = -1); //! transposes the matrix void transpose(InputArray src, OutputArray dst); //! performs affine transformation of each element of multi-channel input matrix void transform(InputArray src, OutputArray dst, InputArray m); //! performs perspective transformation of each element of multi-channel input matrix void perspectiveTransform(InputArray src, OutputArray dst, InputArray m); //! extends the symmetrical matrix from the lower half or from the upper half void completeSymm(InputOutputArray mtx, bool lowerToUpper = false); //! initializes scaled identity matrix void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1)); //! computes determinant of a square matrix double determinant(InputArray mtx); //! computes trace of a matrix Scalar trace(InputArray mtx); //! computes inverse or pseudo-inverse matrix double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU); //! solves linear system or a least-square problem bool solve(InputArray src1, InputArray src2, OutputArray dst, int flags = DECOMP_LU); */ } // end of namespace #endif /* _APEXCV_ARITHMETIC_HPP_ */
6c38539b40710c23a2b1adef6029686bbe14524d
b16ddbe96352f03c3fa97e4ec224678aa2f87c6e
/Cau truc du lieu giai thuat/7.de quy nhi phan.cpp
c0528ebfdd7b68a08bf2f22ab3b0bffeea735e4c
[]
no_license
DinhTuanAnh2k1/C-plus-plus
63ba28e5d3795a7311b4e92f6e92e3e56558cc7f
47ee1ca4006e72eaf5bbdae5872df2c9cf8bdc94
refs/heads/master
2023-08-26T19:11:18.247502
2021-11-03T09:50:30
2021-11-03T09:50:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
178
cpp
7.de quy nhi phan.cpp
#include<bits/stdc++.h> using namespace std; int fb(int n){ if(n<=2){ return 1; } return fb(n-1)+fb(n-2); } int main(){ int n; cin>>n; cout<<fb(n)<<endl; return 0; }
0bc3a6b9291d45f8d3e3ab302a0c79a2ae42e163
565baf0e91d56a39c43fe6c2711b01dd92c189e8
/Library/DataSys.h
8495ce3c461d43f90c52ceff72f50dad5a605cfe
[]
no_license
cpp-library/library
8461c4782ff8fc656335cf16ae31af33eff95902
ee0f7c830684d0e4b4cf305d7cdd8d9f215286ef
refs/heads/master
2021-04-06T06:07:03.001271
2018-04-20T13:16:33
2018-04-20T13:16:33
125,381,842
0
2
null
null
null
null
GB18030
C++
false
false
1,873
h
DataSys.h
#pragma once #include "Blist.h" class DataSys { public: static void create(string _name, int _num, int _len[], bool _ifsearch[]); ///新建表(表名,表的列数,格式描述,是否课检索) static DataSys* getData(string name);///获得数据表指针 static void Sysclose(string name);///关闭指定名称数据表 void close();///关闭数据管理器,请在程序结束前调用该方法以防止数据损失,与上一个方法效果相同 string getName();///返回当前对象打开的表名 int add(char* data); ///插入传入的信息 bool del(int id); ///根据行id删除行 vector<int> find(int column, char* key);///根据第几关键字,获取所有满足条件的行的id ,(若该列为非加速列则自动调用暴力查找) vector<int> fuzzy_search(int column, char* key);///模糊搜索 bool change(int id, int column, char * attr);///改变指定行指定列的属性 char* get(int id); /// 根据行id获取对应行,此处有待商议,易导致内存损失,不推荐使用 务必delete bool get(char* a, int id); /// 推荐使用的方法 vector< pair<int, char*> > get_by_key(int column, char* key);///根据第几关键字,获取所有满足条件的行属性与id char*需delete void del_by_key(int column, char * key);///直接根据条件key,删除满足该条件的行 int size();///总行数 vector<int> get_column_length();///获取每一列的宽度 vector< pair<int, char*> > get_all();///湖区整张数据表的所有数据 char*需delete protected: DataSys(string _name); ///打开表 int get_len_sum(); vector<int> find_onybyone(int column, char * key);///暴力查找 private: static map<string, DataSys*> Sys; string name; int num; ///列数 vector<int> len; ///每一列的宽度 vector<bool> if_search; ///是否支持索引 FileOp table; Blist blist; };
b2d1d255a71c5dcd26d86a4b118f54b65a4b51b9
8bcd6750765c2dc4a3f545670bedf8db28684e69
/S_Jord_Row/task.cpp
2d1a3a63c5655d8b7bb164f33ae2532bbd33501f
[]
no_license
LyakhovIS/matrix_operations
790f0d30864eb65d886dc2da20d18035e3d64505
62bd049cb6773cecb889a357c374e574edf9c2ac
refs/heads/main
2023-03-06T04:58:12.266549
2021-02-21T18:45:19
2021-02-21T18:45:19
336,499,056
0
0
null
null
null
null
UTF-8
C++
false
false
1,286
cpp
task.cpp
#include <iostream> #include <cmath> #include "func.h" using namespace std; const double EPS = 1e-13; int SolveSystem (int n, int *mass, double *a, double *x, double *answer){ int q, w, j, i, g, temp; double maxi, numb; for (q = 0; q < n; ++q){ maxi = abs(a[q * n + q]); i = q; for(w = q + 1; w < n; ++w) if(abs(a[q * n + w]) > maxi){ i = w; maxi = abs(a[q * n + w]); } if (abs(maxi) < EPS) return -1; if (i != q){ for (j = 0; j < n; ++j){ numb = a[j * n + q]; a[j * n + q] = a[j * n + i]; a[j * n + i] = numb; } temp = mass[i]; mass[i] = mass[q]; mass[q] = temp; } maxi = a[q * n + q]; a[q * n + q] = 1; for (j = q + 1; j < n; ++j) a[q * n + j] /= maxi; x[q] /= maxi; for (i = 0; i < n; ++i){ if (i != q){ x[i] -= x[q] * a[i * n + q]; for (g = n - 1; g >= q; --g) a[i * n + g] -= a[q * n + g] * a[i * n + q]; } } } for (i = 0; i < n; ++i) answer[mass[i]] = x[i]; return 0; }
7555e0d68bcf72f42b81b3518927e3f8190bd3b7
3cbea0497545c00ffc87fe1fa8a74dfe88dc9509
/1947_MaximumCompatibilityScoreSum.cpp
8885b7bf700240ac16232c8d523a9f03ff976a19
[]
no_license
yuhenghuang/Leetcode
40b954676feb3a2ef350188a6d86dadc44e84d71
3c5aafa7969a5a1eb01106676a5b94d404d07d9f
refs/heads/master
2023-08-30T18:17:16.209053
2023-08-25T01:05:49
2023-08-25T01:05:49
249,166,616
0
0
null
null
null
null
UTF-8
C++
false
false
2,969
cpp
1947_MaximumCompatibilityScoreSum.cpp
#include <local_leetcode.hpp> class Solution { private: int m; int res; void dfs(int k, int s, vector<bool>& seen_s, vector<bool>& seen_m, vector<vector<int>>& mat) { if (k == m) { if (s > res) res = s; return; } for (int i = 0; i < m; ++i) if (!seen_s[i]) for (int j = 0; j < m; ++j) if (!seen_m[j]) { seen_s[i] = seen_m[j] = true; dfs(k+1, s+mat[i][j], seen_s, seen_m, mat); seen_s[i] = seen_m[j] = false; } } public: int maxCompatibilitySumTLE(vector<vector<int>>& students, vector<vector<int>>& mentors) { m = students.size(); int n = students[0].size(); vector<vector<int>> mat(m, vector<int>(m)); for (int i = 0; i < m; ++i) for (int j = 0; j < m; ++j) { int score = 0; for (int k = 0; k < n; ++k) score += 1 ^ (students[i][k] ^ mentors[j][k]); mat[i][j] = score; } res = 0; vector<bool> seen_s(m), seen_m(m); dfs(0, 0, seen_s, seen_m, mat); return res; } int maxCompatibilitySum(vector<vector<int>>& students, vector<vector<int>>& mentors) { int m = students.size(); int n = students[0].size(); vector<vector<int>> mat(m, vector<int>(m)); for (int i = 0; i < m; ++i) for (int j = 0; j < m; ++j) { int score = 0; for (int k = 0; k < n; ++k) score += 1 ^ (students[i][k] ^ mentors[j][k]); mat[i][j] = score; } int M = 1 << m; int dp[M][M]; memset(dp, 0, sizeof(dp)); // dp[i][0] = 0 // dp[0][j] = 0 for (int bs = 1; bs < M; ++bs) { for (int bm = 1; bm < M; ++bm) { for (int i = 0; i < m; ++i) if (bs & (1 << i)) for (int j = 0; j < m; ++j) if (bm & (1 << j)) dp[bs][bm] = max(dp[bs][bm], mat[i][j] + dp[bs ^ (1 << i)][bm ^ (1 << j)]); } } return dp[M-1][M-1]; } int maxCompatibilitySumFast(vector<vector<int>>& students, vector<vector<int>>& mentors) { int m = students.size(); int n = students[0].size(); int mat[m][m]; for (int i = 0; i < m; ++i) for (int j = 0; j < m; ++j) { int score = 0; for (int k = 0; k < n; ++k) score += 1 ^ (students[i][k] ^ mentors[j][k]); mat[i][j] = score; } int M = 1 << m; int dp[M]; memset(dp, 0, sizeof(dp)); for (int b = 1; b < M; ++b) { int i = __builtin_popcount(b) - 1; for (int j = 0; j < m; ++j) if (b & (1 << j)) dp[b] = max(dp[b], mat[i][j] + dp[b ^ (1 << j)]); } return dp[M-1]; } }; int main() { EXECS(Solution::maxCompatibilitySumTLE); EXECS(Solution::maxCompatibilitySum); EXECS(Solution::maxCompatibilitySumFast); return 0; }
ff87c3557edb6f182fe59c3e0b9862fcdf4a4745
2d5a42a4718aa112970e91f6b8a46f6deb007798
/src/Model/BranchAccountModel/Include/BranchAccountModel.h
515b27fb2d6383912899201185fbca54fe6c49c2
[ "Apache-2.0" ]
permissive
sidphbot/Bank-Management-System
9fbfb3e20e6165272f467bf1318c53c14eda313f
665db860e46e897ab77c7a30145b09e13228614c
refs/heads/master
2022-07-30T22:04:50.779503
2020-05-23T20:08:59
2020-05-23T20:08:59
260,279,105
2
0
null
null
null
null
UTF-8
C++
false
false
699
h
BranchAccountModel.h
#ifndef _BRANCHACCOUNTMODEL_H_ #define _BRANCHACCOUNTMODEL_H_ #include<iostream> //#include<sqlca.h> #include"../../AppClass/BranchAccount/Include/BranchAccount.h" //#include"../../Controller/BranchAccountController/Include/BranchAccountController.h" #include"../../UI/BranchAccountUI/Include/BranchAccountUI.h" using namespace std; class BranchAccountModel { public: long int addBranchAccount(BranchAccount &); int findBranchAccount(long int); void dbConnect(); void disconnect(); int deleteBranchAccount(long int); BranchAccount viewBranchAccount(long int ); int updateBranchID(BranchAccount &); int updateBranchThreshold(BranchAccount &); int updateCurrentBalance(BranchAccount &); }; #endif
2f017e9128ead2186c53968223078890198f42a0
ef6bc69f4443c2c65b5928403ad6ba20bc723099
/week-04/day-5/restaurant/main.cpp
cdccacc8a5709d7053de14533480d2e45a01d5df
[]
no_license
green-fox-academy/plainte
14a76155f82c6922c4634586153f62f79c86ec05
4150b688ac2a48b56f88c5488d8c6dd3bcfaf72e
refs/heads/master
2020-04-16T18:52:44.457767
2019-03-21T14:23:01
2019-03-21T14:23:01
165,569,057
0
0
null
null
null
null
UTF-8
C++
false
false
1,281
cpp
main.cpp
#include <iostream> #include "Employees.h" #include "Restaurant.h" int main() { Restaurant restaurant; Chef chef; Waiter waiter1; Waiter waiter2; Waiter waiter3; Manager manager; restaurant.hire(&chef); restaurant.hire(&waiter1); restaurant.hire(&waiter2); restaurant.hire(&waiter3); restaurant.hire(&manager); /*for (int i = 0; i < 3; i++) { restaurant.guestsArrived(); } */ for (unsigned int i = 0; i < restaurant.getEmployees().size(); i++) { if (i == restaurant.getEmployees().size() - 1) { std::cout << restaurant.getEmployees()[i]->getExperience() << std::endl; } else { std::cout << restaurant.getEmployees()[i]->getExperience() << " "; } } std::cout << "Testing manager: " << std::endl; manager.work(); std::cout << manager.getMoodLevel() << std::endl; for (unsigned int i = 0; i < restaurant.getEmployees().size(); i++) { if (i == restaurant.getEmployees().size() - 1) { std::cout << restaurant.getEmployees()[i]->getExperience() << std::endl; } else { std::cout << restaurant.getEmployees()[i]->getExperience() << " "; } } std::vector<int> myVector = {0, 5, 3}; return 0; }
94ff56c709d5abd746a0423c46a5d40abf5c980a
c39db905cab19a0a033ac3a461772d7457c0e2b6
/include/lsst/afw/image/ImagePca.h
0b6ffe0d691a855f952de62c78d1deaca642c308
[]
no_license
RayPlante/DMS.afw
be8f62bd6d1c1286a012fd6b4f40bf12fff7f767
30888b34cceb85c3216972d5a26558ac3e76f2f8
refs/heads/master
2020-04-06T05:25:48.899481
2011-10-28T18:18:43
2011-10-28T18:18:43
2,667,156
1
0
null
null
null
null
UTF-8
C++
false
false
2,910
h
ImagePca.h
// -*- lsst-c++ -*- /* * LSST Data Management System * Copyright 2008, 2009, 2010 LSST Corporation. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ /** * \file * \brief Support for PCA analysis of 2-D images */ #ifndef LSST_AFW_IMAGE_IMAGEPCA_H #define LSST_AFW_IMAGE_IMAGEPCA_H #include <vector> #include <string> #include <utility> #include "boost/mpl/bool.hpp" #include "boost/shared_ptr.hpp" #include "lsst/pex/exceptions.h" #include "lsst/afw/image/MaskedImage.h" namespace lsst { namespace afw { namespace image { template <typename ImageT> class ImagePca { public: typedef typename boost::shared_ptr<ImageT> Ptr; typedef typename boost::shared_ptr<const ImageT> ConstPtr; typedef std::vector<typename ImageT::Ptr> ImageList; ImagePca(bool constantWeight=true); void addImage(typename ImageT::Ptr img, double flux=0.0); ImageList getImageList() const; /// Return the dimension of the images being analyzed geom::Extent2I const getDimensions() const { return _dimensions; } typename ImageT::Ptr getMean() const; void analyze(); double updateBadPixels(unsigned long mask, int const ncomp); /// Return Eigen values std::vector<double> const& getEigenValues() const { return _eigenValues; } /// Return Eigen images ImageList const& getEigenImages() const { return _eigenImages; } private: double getFlux(int i) const { return _fluxList[i]; } ImageList _imageList; // image to analyze std::vector<double> _fluxList; // fluxes of images geom::Extent2I _dimensions; // width/height of images on _imageList //int _border; // how many pixels to ignore around regions bool _constantWeight; // should all stars have the same weight? std::vector<double> _eigenValues; // Eigen values ImageList _eigenImages; // Eigen images }; template <typename Image1T, typename Image2T> double innerProduct(Image1T const& lhs, Image2T const& rhs, int const border=0); }}} #endif
e030f6b5561ef77e7e9803c2ff62329ad92a66be
8541b8a4da8d62be416c4205e7e1643b22cbac16
/include/Memory.h
522e6cafa87162bcedb51fbef02355a0bcfde72d
[ "MIT" ]
permissive
anerfo/esp32-dimmer
0585919b7b4edd35607fac1ba166ff78ea12a97d
38364f8ef45fe571f376be57d0825f247f966670
refs/heads/main
2023-03-21T12:24:23.304060
2021-03-14T09:00:44
2021-03-14T09:00:44
332,428,324
0
0
null
null
null
null
UTF-8
C++
false
false
1,326
h
Memory.h
#include <EEPROM.h> class Memory { private: struct Storage { uint32_t Brightness; } _Storage, _LastStorage; bool Equals(const Storage& first, const Storage& second) { return first.Brightness == second.Brightness; } Memory() { EEPROM.begin(sizeof(Storage)); EEPROM.get(0, _Storage); } public: static Memory& Instance() { static Memory _Instance; return _Instance; } void Store() { Serial.printf("Storage %i, LastStorage %i\n", _Storage.Brightness, _LastStorage.Brightness); if(Equals(_Storage, _LastStorage) == false) { Serial.printf("Writing Storage\n"); _LastStorage = _Storage; EEPROM.put(0, _Storage); EEPROM.commit(); } } void SetBrightness(uint8_t brightness) { _Storage.Brightness = brightness; Store(); } uint8_t GetBrightness() { return _Storage.Brightness; } void Print() { Serial.printf("Memory:\n"); Serial.printf(" Brightness: %i\n", _Storage.Brightness); } };
74612361bc39e8a676aad21dac6533095b3b5569
03666e5f961946fc1a0ac67781ac1425562ef0d7
/src/avt/VisWindow/Colleagues/VisWinRenderingWithoutWindowWithInteractions.h
195a052e7525fc93e1a8299284b7fa87e6e53b81
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
visit-dav/visit
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
601ae46e0bef2e18425b482a755d03490ade0493
refs/heads/develop
2023-09-06T08:19:38.397058
2023-09-05T21:29:32
2023-09-05T21:29:32
165,565,988
335
120
BSD-3-Clause
2023-09-14T00:53:37
2019-01-13T23:27:26
C
UTF-8
C++
false
false
1,803
h
VisWinRenderingWithoutWindowWithInteractions.h
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. // ************************************************************************* // // VisWinRenderingWithoutWindow.h // // ************************************************************************* // #ifndef VIS_WIN_RENDERING_WITHOUT_WINDOW_WITH_INTERACTIONS_H #define VIS_WIN_RENDERING_WITHOUT_WINDOW_WITH_INTERACTIONS_H #include <viswindow_exports.h> #include <VisWinRenderingWithoutWindow.h> class VisitHotPointInteractor; class vtkRenderWindowInteractor; // **************************************************************************** // Class: VisWinRenderingWithoutWindowWithInteractions // // Purpose: // A derived type of VisWinRendering that assumes that there will be no // window on the screen but this version adds interactions. // // Programmer: Hari Krishnan // Creation: // // Modifications: // // **************************************************************************** class VISWINDOW_API VisWinRenderingWithoutWindowWithInteractions : public VisWinRenderingWithoutWindow { public: VisWinRenderingWithoutWindowWithInteractions(VisWindowColleagueProxy &); virtual ~VisWinRenderingWithoutWindowWithInteractions(); virtual vtkRenderWindowInteractor* GetRenderWindowInteractor(); void Initialize(VisitHotPointInteractor* i); static void SetInteractorCallback(vtkRenderWindowInteractor* (*cb)()) { createInteractor = cb; } private: static vtkRenderWindowInteractor* (*createInteractor)(); vtkRenderWindowInteractor* iren; bool ownsInteractor; }; #endif
42df2f68a07cd5caadb15722698abec955dcc37d
9fb4a0d3aa064c6042578237fa300ba6c197bad0
/핸드폰 번호 가리기.cpp
ee9f80f0aaaf0b56d3732e28da4636697129f4c8
[]
no_license
19sProgrammersStudy/Gyudong
d66f2bf5213e36b378b31073bf14dcc14e15a70d
338852b2489722e1f10a2ac4c34e1aea2b6cc998
refs/heads/main
2023-06-19T23:22:42.872161
2021-07-20T13:50:27
2021-07-20T13:50:27
383,170,088
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
핸드폰 번호 가리기.cpp
#include <string> #include <vector> #include <iostream> using namespace std; string solution(string phone_number) { string answer = ""; int len = phone_number.length(); for(int i=0;i<len-4;i++){ answer += '*'; } for(int i=len-4;i<len;i++){ answer += phone_number[i]; } return answer; } //https://programmers.co.kr/learn/courses/30/lessons/12948
1646e430bde2717317765f53df2f3103f048a71d
e5e37d09d0d96d515279ac9a484ff48616ea4fd8
/UVa_12086 - Potentiometers.cpp
6002292276b33935d3f68f86800b655b08688f93
[]
no_license
code-Night/UVa-Online-judge
298fe10811ced2350a6cd2f99974926b68186147
ebe1a83dd2d49312f0b918c18009966f165912ec
refs/heads/master
2016-08-11T15:57:32.948678
2015-12-17T09:18:56
2015-12-17T09:18:56
46,227,023
0
0
null
null
null
null
UTF-8
C++
false
false
1,757
cpp
UVa_12086 - Potentiometers.cpp
#include <iostream> #include <cstring> #include <cstdio> using namespace std; typedef long long int lli; int n; lli sumTree [16000000+1] ; lli value [200000] ; void build(int i,int l,int r){ if(l == r){ sumTree[i] = value[l] ; return ; } int mid = (l+r)/2 ; build(i*2+1,l, mid); build(i*2+2,mid+1,r); sumTree[i] = sumTree[2*i+1]+sumTree[2*i+2] ; } lli query (int i,int li,int ri,int a,int b){ if(li > b || ri < a) return 0 ; if(li >= a && ri <= b) return sumTree[i] ; int mid = (li+ri)/2; return query(2*i+1,li,mid,a,b)+query(2*i+2,mid+1,ri,a,b) ; } void update(int i, int li,int ri,int target,int newValue) { if((li == ri)&& (ri == target)){ sumTree[i] = newValue ; return ; }else if(target <= (li+ri)/2){ update(2*i+1,li,(li+ri)/2,target,newValue); }else{ update(2*i+2,(li+ri)/2+1,ri,target,newValue); } sumTree[i] = sumTree[2*i+1]+sumTree[2*i+2]; } int main() { ios_base::sync_with_stdio(0); freopen("input.txt","r",stdin); cin >> n ;int tc = 1 ; while(n!=0){ if(tc > 1) cout << endl ; cout << "Case " << tc++ << ":\n" ; memset(sumTree,-1,sizeof(sumTree)); for(int i=0 ; i<n ; i++){ cin >> value[i]; } build(0,0,n-1); while(true){ string Q = "" ; cin >> Q ; int x, y ; if(Q == "END") break ; else{ cin >> x >> y ; if(Q == "S") update(0,0,n-1,x-1,y); else cout << query(0,0,n-1,x-1,y-1) << endl; } } cin >> n ; } return 0; }
37f92ac6e443909691aa28c85a1bf3c91175347e
1a469959f56cadab86d0ee8dcb4f87af1af64410
/Qt/FleetGUI/fleetGUI.cpp
47a2e842f8a30f747aff88af8cde445177557d0b
[]
no_license
denischmielewski/test
921cf027b2ade01f42c647239859f3f27d451409
9fbde28b7171b04bc9982749a51ecb1b91359d2a
refs/heads/master
2020-05-14T17:33:24.279737
2015-07-14T14:29:12
2015-07-14T14:29:12
32,296,819
0
0
null
null
null
null
UTF-8
C++
false
false
16,647
cpp
fleetGUI.cpp
#include "fleetGUI.h" #include <QtDebug> #include <iostream> #include <string> #include <math.h> MainWindow::MainWindow(QWidget *parent, const config * fleetGUI_configuration, std::unordered_map<std::string, TrainSession> * trainsSessions, FleetGUICommunicationsServer const * t, const FleetGUICommunicationClient *c) : QMainWindow(parent), ui(new Ui::MainWindow) { bool connection; softwareConfig_ = fleetGUI_configuration; trainsSessions_ = trainsSessions; startup_severity_channel_logger_mt& lg = fleetGUI_logger::get(); fleetGUI_logger_ = &lg; QPainterPath linePath, stopsPath; BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "==================== CONSTRUCTOR !!! "; ui->setupUi(this); connection = connect(this, &MainWindow::myclose, t, &FleetGUICommunicationsServer::onCloseFleetGUI); connection = connect(this, &MainWindow::myclose, c, &FleetGUICommunicationClient::onCloseFleetGUI); myScene = new QGraphicsScene(0,0,1600,900,this); ui->graphicsView->setScene(myScene); ui->graphicsView->setRenderHints(QPainter::Antialiasing); QBrush redBrush(Qt::red); QBrush blueBrush(Qt::blue); QPen blackPen(Qt::black); blackPen.setWidth(2); QPen redPen(Qt::red); redPen.setWidth(2); QPen bluePen(Qt::blue); bluePen.setWidth(3); linePath.moveTo(50, 800); linePath.cubicTo(80,600, 200,600, 200,600); linePath.cubicTo(300,600, 300,400, 300,400); linePath.cubicTo(300,300, 200,300, 200,300); linePath.cubicTo(80,300, 40,200, 40,200); linePath.cubicTo(20,100, 80,80, 100,80); linePath.cubicTo(200,80, 300,50, 300,50); linePath.cubicTo(400,20, 500,20, 500,20); linePath.cubicTo(575,15, 630,20, 630,20); linePath.cubicTo(735,25, 835,20, 835,20); linePath.cubicTo(910,15, 1030,20, 1030,20); linePath.cubicTo(1087,22, 1190,15, 1190,15); linePath.cubicTo(1250,11, 1319,1, 1365,45); linePath.cubicTo(1400,75, 1400,125, 1400,125); linePath.cubicTo(1400,195, 1320,205, 1320,205); linePath.cubicTo(1247,218, 1067,334, 1125,435); linePath.cubicTo(1140,465, 1170,480, 1200,485); linePath.cubicTo(1279,493, 1274,580, 1195,565); linePath.cubicTo(1145,559, 1070,542, 1040,595); linePath.cubicTo(872,737, 609,755, 400,790); linePathLength_ = linePath.length(); //Memorized after Line was built and before adding any item (because adding items length is modified) std::string s = std::to_string(linePathLength_); //qDebug("\n\n ==================== TEST111 !!!!! ========================"); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "\n******* length " << " is " << s.c_str(); //add stations QPointF qp1; // #1 float length = 0.0/38500*linePathLength_; float percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #2 length = 100.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #3 length = 400.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #4 length = 500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #5 length = 3500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #6 length = 6500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #7 length = 9500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #8 length = 12500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #9 length = 14500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #10 length = 16000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #11 length = 17000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #12 length = 18500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #13 length = 20000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #14 length = 21500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #15 length = 23000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #16 length = 24000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #17 length = 25500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #18 length = 26500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #19 length = 28000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #20 length = 30000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #21 length = 32000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #22 length = 34500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #23 length = 38000.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); // #24 length = 38500.0/38500.0*linePathLength_; percent = linePath.percentAtLength(length); qp1 = linePath.pointAtPercent(percent); stopsPath.addEllipse(qp1, 5, 5); QGraphicsPathItem * myPath = ui->graphicsView->scene()->addPath(linePath, bluePen); ui->graphicsView->scene()->addPath(stopsPath, blackPen); timerForGUIRefresh_ = new QTimer; connect(timerForGUIRefresh_, &QTimer::timeout, this, &MainWindow::onTimerForGUIRefreshShot); timerForGUIRefresh_->start(1000); linePath_ = linePath; BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "===================== END CONSTRUCTOR MAIN WINDOW ==================="; } MainWindow::~MainWindow() { timerForGUIRefresh_->stop(); delete timerForGUIRefresh_; delete ui; } void MainWindow::closeEvent(QCloseEvent *evt) { emit myclose(); evt->accept(); } void MainWindow::resizeEvent(QResizeEvent * evt) { int hcw = ui->centralWidget->height(); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "central widget height " << hcw; int wcw = ui->centralWidget->width(); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "central widget width " << wcw; ui->graphicsView->resize(wcw, hcw); int hgw = ui->graphicsView->height(); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "graphicView height " << hgw; int wgw = ui->graphicsView->width(); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "graphicView width " << wgw; float newScalex, newScaley; newScalex = (float)wcw/(float)1600; newScaley = (float)hcw/(float)1000; //invert previous scale ui->graphicsView->scale(1/currentScaleW_, 1/currentScaleY_); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "newScalex factor = " << newScalex << "newScaley factor = " << newScaley; //apply new scale ui->graphicsView->scale(newScalex, newScaley); //memorize new scale currentScaleW_ = newScalex; currentScaleY_ = newScaley; QRectF sceneRect = ui->graphicsView->sceneRect(); ui->graphicsView->scene()->setSceneRect(sceneRect); evt->accept(); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "===================== END RESIZE ==================="; } void MainWindow::onTimerForGUIRefreshShot(void) { //display trains BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "Start Displaying trains !"; int i = 0; for ( auto it = trainsSessions_->begin(); it != trainsSessions_->end(); ++it ) { //TrainOperationSession trainOperationSession = (it->second).GetTrainOperationSessionRef(); if((it->second).GetTrainOperationSessionRef().IsThisSessionATrain()) { i++; } } BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "number of Train : " << i; i = 0; for ( auto it = trainsSessions_->begin(); it != trainsSessions_->end(); ++it ) { if((it->second).GetTrainOperationSessionRef().IsThisSessionATrain()) { i++; BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "========================== Train : " << i << " IP address :" << it->first; // 1st step: curve length. It was calculated after Line was built and before adding any item (else length is modified) BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "length : " << linePathLength_; if((it->second).GetTrainOperationSessionRef().TryLockOperationSessionMutexFor(softwareConfig_->commSessionMutexLockTimeoutMilliseconds_)) { static QPointF qp1, qp2, qp3; //retrieve information we need from TrainOPperationSession class then release mutex as fast as possible as it is accessed by message processing std::string path = ((it->second).GetTrainOperationSessionRef().GetPath()); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "path = " << path; float pkPos = (it->second).GetTrainOperationSessionRef().GetKpPosition(); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "pkPos = " << pkPos; int dir = (it->second).GetTrainOperationSessionRef().GetDirection(); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "dir = " << dir; (it->second).GetTrainOperationSessionRef().UnlockOperationSessionMutex(); // position in line coordinates auto iter = softwareConfig_->linesData_.find(path); //note: we can not use map [] operator as it is not const float length = (pkPos - (float)((iter->second).lineFirstKPPosition_))/(float)((iter->second).linePKDistance_) * (float)linePathLength_; std::string s = std::to_string(length); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "position in linePath_ coordinates : " << length << " kpPosition : " << pkPos; // retrieve percent from position in line coordinates //float p = linePath_.percentAtLength(((pkPos - (float)((iter->second).lineFirstKPPosition_)))/(float)((iter->second).linePKDistance_)); float p = linePath_.percentAtLength(length); s = std::to_string(p); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "percent : " << p << " kpPosition : " << pkPos; // get angle at percent float angle = linePath_.angleAtPercent(p); s = std::to_string(angle); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "angle at percent : " << angle; // get point at percent qp1 = linePath_.pointAtPercent(p); s = std::to_string(qp1.rx()); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "x at percent " << " is " << s.c_str(); s = std::to_string(qp1.ry()); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "y at percent " << " is " << s.c_str(); // get slope at percent float slope = linePath_.slopeAtPercent(p); s = std::to_string(slope); BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "slope at percent " << " is " << s.c_str(); QBrush yellowBrush(Qt::yellow); QBrush blackBrush(Qt::black); QBrush greenBrush(Qt::green); //QPen greenPen(Qt::green); QPen greenPen(greenBrush, 10); int16_t trainSizePixel = softwareConfig_->configForFleetGUISw_.trainDisplaySizeInPixel_; int16_t trainDisplayOffsetPixel = softwareConfig_->configForFleetGUISw_.trainDisplayOffsetRelativeToLineInPixels_; bool firstTimeTrainIsReceived = false; auto search = trainsQGraphicsEllipseItems_.find(it->first); if(search == trainsQGraphicsEllipseItems_.end()) firstTimeTrainIsReceived = true; //for unordered map management if(dir == 1) { //center of train position point for direction 1 qp2.setX((qp1.rx()) - (trainDisplayOffsetPixel * sin(angle/360*2*M_PI))); qp2.setY((qp1.ry()) - (trainDisplayOffsetPixel * cos(angle/360*2*M_PI))); if(firstTimeTrainIsReceived) { //first time, create the item BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "first time on graphic scene for " \ << it->first << " x = " << qp2.rx()-trainSizePixel/sqrt(2) << " y = " << qp2.ry()-trainSizePixel/sqrt(2); QGraphicsEllipseItem * ei = \ ui->graphicsView->scene()->addEllipse(qp2.rx()-trainSizePixel/sqrt(2),qp2.ry()-trainSizePixel/sqrt(2),trainSizePixel*sqrt(2),trainSizePixel*sqrt(2),greenPen, blackBrush); trainsQGraphicsEllipseItems_.emplace(it->first, ei); } else { trainsQGraphicsEllipseItems_[it->first]->setRect(qp2.rx()-trainSizePixel/sqrt(2),qp2.ry()-trainSizePixel/sqrt(2),trainSizePixel*sqrt(2),trainSizePixel*sqrt(2)); } } else if(dir == 2) { //center of train position point for direction 2 qp3.setX((qp1.rx()) + (trainDisplayOffsetPixel * sin(angle/360*2*M_PI))); qp3.setY((qp1.ry()) + (trainDisplayOffsetPixel * cos(angle/360*2*M_PI))); if(firstTimeTrainIsReceived) { //first time, create the item BOOST_LOG_SEV(*fleetGUI_logger_, debug) << "first time on graphic scene for " \ << it->first << " x = " << qp3.rx()-trainSizePixel/sqrt(2) << " y = " << qp3.ry()-trainSizePixel/sqrt(2); QGraphicsEllipseItem * ei = \ ui->graphicsView->scene()->addEllipse(qp3.rx()-trainSizePixel/sqrt(2),qp3.ry()-trainSizePixel/sqrt(2),trainSizePixel*sqrt(2),trainSizePixel*sqrt(2),greenPen, blackBrush); trainsQGraphicsEllipseItems_.emplace(it->first, ei); } else { trainsQGraphicsEllipseItems_[it->first]->setRect(qp3.rx()-trainSizePixel/sqrt(2),qp3.ry()-trainSizePixel/sqrt(2),trainSizePixel*sqrt(2),trainSizePixel*sqrt(2)); } } } else { BOOST_LOG_SEV(*fleetGUI_logger_, warning) << "Train Operation Session Lock failed !!!"; } } } }
cf4f123ba273bd004ad49cc8076a8b2bafcdb986
b6a78c62271b9be421eb43722d500d717dfa1db8
/sheet/A/CF486-D2.cpp
8fcdf799ba1c0d3cae3722405d4e8f34a1a1e1d5
[]
no_license
Zehnun/cp
474388f44f7e260140335581326ec5788c9b6f21
91d5e8517684364ef5e472924affa922da2d708e
refs/heads/main
2023-01-24T06:39:17.299891
2020-12-08T22:09:00
2020-12-08T22:09:00
267,667,970
0
0
null
null
null
null
UTF-8
C++
false
false
171
cpp
CF486-D2.cpp
#include<bits/stdc++.h> using namespace std; int main(){ long long n; cin >> n; if(n %2 == 0) cout << n / 2 << endl; else cout << -(n+1)/2 << endl; return 0; }
bd36a7797a909decd0a2cda102b37253dffa6830
8c826d76cb42cc0cf15930424b4817f90db4b964
/Blinding/RandomLib-1.10/include/RandomLib/DiscreteNormalAlt.hpp
b92e4974097f5d8535756360982202f35ec68075
[ "MIT" ]
permissive
glukicov/EDMTracking
79936455e6ab20ac9d8cc7a00df294dd108cfe54
ed17431bd9071b0aa6a773380d5a0d362fa933c8
refs/heads/master
2021-07-15T20:30:37.124456
2020-10-22T19:54:09
2020-10-22T19:54:09
214,927,605
1
1
null
null
null
null
UTF-8
C++
false
false
14,256
hpp
DiscreteNormalAlt.hpp
/** * \file DiscreteNormalAlt.hpp * \brief Header for DiscreteNormalAlt * * Sample exactly from the discrete normal distribution (alternate version). * * Copyright (c) Charles Karney (2013) <charles@karney.com> and licensed * under the MIT/X11 License. For more information, see * http://randomlib.sourceforge.net/ **********************************************************************/ #if !defined(RANDOMLIB_DISCRETENORMALALT_HPP) #define RANDOMLIB_DISCRETENORMALALT_HPP 1 #include <RandomLib/RandomNumber.hpp> #include <RandomLib/UniformInteger.hpp> #include <limits> namespace RandomLib { /** * \brief The discrete normal distribution (alternate version). * * Sample integers \e i with probability proportional to * \f[ * \exp\biggl[-\frac12\biggl(\frac{i-\mu}{\sigma}\biggr)^2\biggr], * \f] * where &sigma; and &mu; are given as rationals (the ratio of two integers). * The sampling is exact (provided that the random generator is ideal). The * results of this class are UniformInteger objects which represent a * contiguous range which is a power of 2<sup>\e bits</sup>. This can be * narrowed down to a specific integer as follows * \code #include <iostream> #include <RandomLib/Random.hpp> #include <RandomLib/UniformInteger.hpp> #include <RandomLib/DiscreteNormalAlt.hpp> int main() { RandomLib::Random r; // Create r r.Reseed(); // and give it a unique seed int sigma_num = 7, sigma_den = 1, mu_num = 1, mu_den = 3; RandomLib::DiscreteNormalAlt<int,1> d(sigma_num, sigma_den, mu_num, mu_den); for (int i = 0; i < 100; ++i) { RandomLib::UniformInteger<int,1> u = d(r); std::cout << u << " = "; std::cout << u(r) << "\n"; } } \endcode * prints out 100 samples with &sigma; = 7 and &mu; = 1/3; the samples are * first given as a range and then <code>u(r)</code> is used to obtain a * specific integer. In some applications, it might be possible to avoid * sampling all the additional digits to get to a specific integer. (An * example would be drawing a sample which satisfies an inequality.) This * version is slower (by a factor of about 4 for \e bits = 1) than * DiscreteNormal on a conventional computer, but may be faster when random * bits are generated by a slow hardware device. * * The basic algorithm is the same as for DiscreteNormal. However randomness * in metered out \e bits random bits at a time. The algorithm uses the * least random bits (and is slowest!) when \e bits = 1. This rationing of * random bits also applies to sampling \e j in the expression * \f[ * x = x_0 + j/\sigma. * \f] * Rather than sampling a definite value for \e j, which then might be * rejected, \e j is sampled using UniformInteger. UniformInteger uses * Lumbroso's method from sampling an integer uniformly in [0, \e m) using at * most 2 + log<sub>2</sub>\e m bits on average (for \e bits = 1). However * when a UniformInteger object is first constructed it samples at most 3 * bits (on average) to obtain a range for \e j which is power of 2. This * allows the algorithm to achieve ideal scaling in the limit of large * &sigma; consuming constant + log<sub>2</sub>&sigma; bits on average. In * addition it can deliver the resuls in the form of a UniformInteger * consuming a constant number of bits on average (and then about * log<sub>2</sub>&sigma; additional bits are required to convert the * UniformInteger into an integer sample). The consumption of random bits * (for \e bits = 1) is summarized here \verbatim min mean max bits for UniformInteger result 30.4 34.3 35.7 bits for integer result - log2(sigma) 28.8 31.2 32.5 toll 26.8 29.1 30.4 \endverbatim * These results are averaged over many samples. The "min" results apply * when &sigma; is a power of 2; the "max" results apply when &sigma; is * slightly more than a power of two; the "mean" results are averaged over * &sigma;. The toll is the excess number of bits over the entropy of the * distribution, which is log<sub>2</sub>(2&pi;\e e)/2 + * log<sub>2</sub>&sigma; (for &sigma; large). * * The data for the first two lines in the table above are taken for the blue * and red lines in the figure below where the abscissa is the fractional * part of log<sub>2</sub>&sigma; * \image html * discrete-bits.png "Random bits to sample from discrete normal distribution" * * This class uses a mutable RandomNumber objects. So a single * DiscreteNormalAlt object cannot safely be used by multiple threads. In a * multi-processing environment, each thread should use a thread-specific * DiscreteNormalAlt object. * * @tparam IntType the integer type to use (default int). **********************************************************************/ template<typename IntType = int, int bits = 1> class DiscreteNormalAlt { public: /** * Constructor. * * @param[in] sigma_num the numerator of &sigma;. * @param[in] sigma_den the denominator of &sigma; (default 1). * @param[in] mu_num the numerator of &mu; (default 0). * @param[in] mu_den the denominator of &mu; (default 1). * * This may throw an exception is the parameters are such that overflow is * possible. **********************************************************************/ DiscreteNormalAlt(IntType sigma_num, IntType sigma_den = 1, IntType mu_num = 0, IntType mu_den = 1); /** * Return a sample. * * @tparam Random the type of the random generator. * @param[in,out] r a random generator. * @return discrete normal sample in the form of a UniformInteger object. **********************************************************************/ template<class Random> UniformInteger<IntType, bits> operator()(Random& r) const; private: /** * sigma = _sig / _d, mu = _imu + _mu / _d, _isig = ceil(sigma) **********************************************************************/ IntType _sig, _mu, _d, _isig, _imu; mutable RandomNumber<bits> _p; mutable RandomNumber<bits> _q; // ceil(n/d) for d > 0 static IntType iceil(IntType n, IntType d); // abs(n) needed because Visual Studio's std::abs has problems static IntType iabs(IntType n); static IntType gcd(IntType u, IntType v); /** * Implement outcomes for choosing with prob (\e x + 2\e k) / (2\e k + 2); * return: * - 1 (succeed unconditionally) with prob (\e m &minus; 2) / \e m, * - 0 (succeed with probability x) with prob 1 / \e m, * - &minus;1 (fail unconditionally) with prob 1 / \e m. **********************************************************************/ template<class Random> static int Choose(Random& r, int m); /** * Return true with probability exp(&minus;1/2). **********************************************************************/ template<class Random> bool ExpProbH(Random& r) const; /** * Return true with probability exp(&minus;<i>n</i>/2). **********************************************************************/ template<class Random> bool ExpProb(Random& r, int n) const; /** * Return \e n with probability exp(&minus;<i>n</i>/2) * (1&minus;exp(&minus;1/2)). **********************************************************************/ template<class Random> int ExpProbN(Random& r) const; /** * Algorithm B: true with prob exp(-x * (2*k + x) / (2*k + 2)) where * x = (xn0 + _d * j) / _sig **********************************************************************/ template<class Random> bool B(Random& r, int k, IntType xn0, UniformInteger<IntType, bits>& j) const; }; template<typename IntType, int bits> DiscreteNormalAlt<IntType, bits>::DiscreteNormalAlt (IntType sigma_num, IntType sigma_den, IntType mu_num, IntType mu_den) { STATIC_ASSERT(std::numeric_limits<IntType>::is_integer, "DiscreteNormalAlt: invalid integer type IntType"); STATIC_ASSERT(std::numeric_limits<IntType>::is_signed, "DiscreteNormalAlt: IntType must be a signed type"); if (!( sigma_num > 0 && sigma_den > 0 && mu_den > 0 )) throw RandomErr("DiscreteNormalAlt: need sigma > 0"); _imu = mu_num / mu_den; if (_imu == (std::numeric_limits<IntType>::min)()) throw RandomErr("DiscreteNormalAlt: abs(mu) too large"); mu_num -= _imu * mu_den; IntType l; l = gcd(sigma_num, sigma_den); sigma_num /= l; sigma_den /= l; l = gcd(mu_num, mu_den); mu_num /= l; mu_den /= l; _isig = iceil(sigma_num, sigma_den); l = gcd(sigma_den, mu_den); _sig = sigma_num * (mu_den / l); _mu = mu_num * (sigma_den / l); _d = sigma_den * (mu_den / l); // The rest of the constructor tests for possible overflow // Check for overflow in computing member variables IntType maxint = (std::numeric_limits<IntType>::max)(); if (!( mu_den / l <= maxint / sigma_num && iabs(mu_num) <= maxint / (sigma_den / l) && mu_den / l <= maxint / sigma_den )) throw RandomErr("DiscreteNormalAlt: sigma or mu overflow"); if (!UniformInteger<IntType, bits>::Check(_isig, _d)) throw RandomErr("DiscreteNormalAlt: overflow in UniformInteger"); // The probability that k = kmax is about 10^-543. int kmax = 50; // Check that max plausible result fits in an IntType, i.e., // _isig * (kmax + 1) + abs(_imu) does not lead to overflow. if (!( kmax + 1 <= maxint / _isig && _isig * (kmax + 1) <= maxint - iabs(_imu) )) throw RandomErr("DiscreteNormalAlt: possible overflow a"); // Check xn0 = _sig * k + s * _mu; if (!( kmax <= maxint / _sig && _sig * kmax <= maxint - iabs(_mu) )) throw RandomErr("DiscreteNormalAlt: possible overflow b"); // Check for overflow in RandomNumber::LessThan(..., UniformInteger& j) // p0 * b, p0 = arg2 = xn0 = _d - 1 // c *= b, c = arg3 = _d // digit(D, k) * q, digit(D, k) = b - 1, q = arg4 = _sig if (!( _d <= maxint >> bits )) throw std::runtime_error("DiscreteNormalAlt: overflow in RandomNumber a"); if (!( (IntType(1) << bits) - 1 <= maxint / _sig )) throw std::runtime_error("DiscreteNormalAlt: overflow in RandomNumber b"); } template<typename IntType, int bits> template<class Random> UniformInteger<IntType, bits> DiscreteNormalAlt<IntType, bits>::operator()(Random& r) const { for (;;) { int k = ExpProbN(r); if (!ExpProb(r, k * (k - 1))) continue; UniformInteger<IntType, bits> j(r, _isig); IntType s = r.Boolean() ? -1 : 1, xn0 = _sig * IntType(k) + s * _mu, i0 = iceil(xn0, _d); // i = i0 + j xn0 = i0 * _d - xn0; // xn = xn0 + _d * j if (!j.LessThan(r, _sig - xn0, _d) || (k == 0 && s < 0 && !j.GreaterThan(r, -xn0, _d))) continue; int h = k + 1; while (h-- && B(r, k, xn0, j)); if (!(h < 0)) continue; j.Add(i0 + s * _imu); if (s < 0) j.Negate(); return j; } } template<typename IntType, int bits> IntType DiscreteNormalAlt<IntType, bits>::iceil(IntType n, IntType d) { IntType k = n / d; return k + (k * d < n ? 1 : 0); } template<typename IntType, int bits> IntType DiscreteNormalAlt<IntType, bits>::iabs(IntType n) { return n < 0 ? -n : n; } template<typename IntType, int bits> IntType DiscreteNormalAlt<IntType, bits>::gcd(IntType u, IntType v) { // Knuth, TAOCP, vol 2, 4.5.2, Algorithm A u = iabs(u); v = iabs(v); while (v > 0) { IntType r = u % v; u = v; v = r; } return u; } template<typename IntType, int bits> template<class Random> int DiscreteNormalAlt<IntType, bits>::Choose(Random& r, int m) { // Limit base to 2^15 to avoid integer overflow const int b = bits > 15 ? 15 : bits; const unsigned mask = (1u << b) - 1; int n1 = m - 2, n2 = m - 1; // Evaluate u < n/m where u is a random real number in [0,1). Write u = // (d + u') / 2^b where d is a random integer in [0,2^b) and u' is in // [0,1). Then u < n/m becomes u' < n'/m where n' = 2^b * n - d * m and // exit if n' <= 0 (false) or n' >= m (true). for (;;) { int d = (mask & RandomNumber<bits>::RandomDigit(r)) * m; n1 = (std::max)((n1 << b) - d, 0); if (n1 >= m) return 1; n2 = (std::min)((n2 << b) - d, m); if (n2 <= 0) return -1; if (n1 == 0 && n2 == m) return 0; } } template<typename IntType, int bits> template<class Random> bool DiscreteNormalAlt<IntType, bits>::ExpProbH(Random& r) const { _p.Init(); if (_p.Digit(r, 0) >> (bits - 1)) return true; for (;;) { _q.Init(); if (!_q.LessThan(r, _p)) return false; _p.Init(); if (!_p.LessThan(r, _q)) return true; } } template<typename IntType, int bits> template<class Random> bool DiscreteNormalAlt<IntType, bits>::ExpProb(Random& r, int n) const { while (n-- > 0) { if (!ExpProbH(r)) return false; } return true; } template<typename IntType, int bits> template<class Random> int DiscreteNormalAlt<IntType, bits>::ExpProbN(Random& r) const { int n = 0; while (ExpProbH(r)) ++n; return n; } template<typename IntType, int bits> template<class Random> bool DiscreteNormalAlt<IntType, bits>::B(Random& r, int k, IntType xn0, UniformInteger<IntType, bits>& j) const { int n = 0, m = 2 * k + 2, f; for (;; ++n) { if ( ((f = k ? 0 : Choose(r, m)) < 0) || (_q.Init(), !(n ? _q.LessThan(r, _p) : _q.LessThan(r, xn0, _d, _sig, j))) || ((f = k ? Choose(r, m) : f) < 0) || (f == 0 && (_p.Init(), !_p.LessThan(r, xn0, _d, _sig, j))) ) break; _p.swap(_q); // an efficient way of doing p = q } return (n % 2) == 0; } } // namespace RandomLib #endif // RANDOMLIB_DISCRETENORMALALT_HPP
52a5704d190666743881675bc7d7c45a9ec5cdd2
5696f7e9bb6cb18e791be3f71e8a72f9a26a0a22
/src/FundInvest/FundInvest/FundInvestDlg.h
6217e2436d654a873b2e48212c117a740fb1b5ab
[ "MIT" ]
permissive
xylsxyls/xueyelingshuang
0fdde992e430bdee38abb7aaf868b320e48dba64
a646d281c4b2ec3c2b27de29a67860fccce22436
refs/heads/master
2023-08-04T01:02:35.112586
2023-07-17T09:30:27
2023-07-17T09:30:27
61,338,042
4
2
null
null
null
null
GB18030
C++
false
false
4,161
h
FundInvestDlg.h
// FundInvestDlg.h : 头文件 // #pragma once #include <string> #include <map> #include <vector> #include "IntDateTime/IntDateTimeAPI.h" #include "DataNeuron.h" #include "CSystem/CSystemAPI.h" #include "afxwin.h" #define FUND_NUM std::string("161725")//161725 class CDrawDlg; // CFundInvestDlg 对话框 class CFundInvestDlg : public CDialogEx { // 构造 public: CFundInvestDlg(CWnd* pParent = NULL); // 标准构造函数 // 对话框数据 enum { IDD = IDD_FundInvest_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedButton1(); afx_msg void OnBnClickedButton2(); private: void LoadFund(const std::string& fundName); DataNeuron* GetFirstNeuron(const std::string& fundName); DataNeuron* GetLastNeuron(const std::string& fundName); DataNeuron* GetNeuron(const std::string& fundName, const std::string& time); DataNeuron* GetNeuron(const std::string& fundName, const IntDateTime& time); private: std::string m_fundPath = CSystem::GetEnvironment("xueyelingshuang") + "data\\Fund\\"; std::string m_fundName = FUND_NUM; bool m_isOpenBuy = true; bool m_isOpenSell = true; std::map<std::string, std::map<IntDateTime, DataNeuron>> m_mapDataNeuron; public: afx_msg void OnBnClickedButton3(); afx_msg void OnBnClickedButton4(); afx_msg void OnBnClickedButton5(); afx_msg void OnBnClickedButton6(); afx_msg void OnBnClickedButton7(); afx_msg void OnBnClickedButton8(); afx_msg void OnBnClickedButton9(); afx_msg void OnBnClickedButton10(); afx_msg void OnBnClickedButton11(); void Draw(const std::map<double,double>& mapData); CDrawDlg * drawDlg = NULL; afx_msg void OnBnClickedButton12(); double DaysBidSell(int32_t lookDays, const IntDateTime& beginTime, const IntDateTime& endTime, double bid, double sell); afx_msg void OnBnClickedButton13(); //always,highest,bid,sell std::vector<double> GetBidSellInfo(int32_t lookDays, const IntDateTime& time, int32_t days); afx_msg void OnBnClickedButton14(); afx_msg void OnBnClickedButton15(); afx_msg void OnBnClickedButton16(); afx_msg void OnBnClickedButton17(); double GetReceive(const std::string& beginTime, const std::string& endTime, double bid, double sell, int32_t days); std::map<double, double> GetReceiveMap(const std::string& beginTime, const std::string& endTime, double bidBegin, double bidEnd, double sell, int32_t days); std::vector<std::string> m_vecFundName; afx_msg void OnBnClickedButton18(); double GetPersent(const IntDateTime& beginTime, const IntDateTime& endTime, double bidUpdown, double sellGetPersent); afx_msg void OnBnClickedButton21(); CButton m_simulationBtn; CButton m_bidSellBtn; CButton m_haveLookBtn; DataNeuron* m_simulationBegin; DataNeuron* m_simulationEnd; DataNeuron* m_simulationNow; double m_present = 1.0; double m_simulationFund = 100000.0; bool m_isHave = false; afx_msg void OnBnClickedButton19(); afx_msg void OnBnClickedButton22(); afx_msg void OnBnClickedButton23(); void Buy(double fundHandlePersent, double& fundHave, double& fund, double buyCharge); void Sell(double fundHandlePersent, double& fundHave, double& frozen, double sellCharge); int32_t Condition(DataNeuron* nowNeuron, double& fundHandlePersent); void HandleFrozen(double& frozen, double& fund); afx_msg void OnBnClickedButton24(); afx_msg void OnBnClickedButton25(); };
20e138073d1f8a34418d9ff596909ff68f30d83d
5c98eff3fa528c1ccf384b76a5713f82e6c96fab
/core/src/Systems/BaseRenderSystem.h
ae051fb34a18befa686e906a5b484a30444934e0
[ "MIT" ]
permissive
kalouantonis/Alpha-To-Beta
a6c3619a56e71262ba9de073da1062d0f0c50531
0cd49eb65a645a136696e6b87553cb9cc4ee927a
refs/heads/master
2021-06-17T03:11:10.934653
2017-03-30T09:43:52
2017-03-30T09:43:52
40,261,726
1
0
null
null
null
null
UTF-8
C++
false
false
1,098
h
BaseRenderSystem.h
#ifndef _BASERENDERSYSTEM_H_ #define _BASERENDERSYSTEM_H_ #include<Artemis/EntitySystem.h> #include <Graphics/SpriteBatch.h> #include <unordered_map> #include <map> class IRenderable; class Transform; template <class T> class BaseRenderSystem: public artemis::EntitySystem { public: // In the deriving class, its best for the user to declare the type of component it // will be processing // e.g. addComponentType<Renderable>() BaseRenderSystem(SpriteBatch& spriteBatch); virtual ~BaseRenderSystem(); protected: virtual void updateRenderable(T* pRenderable) {} float getDelta() const; private: virtual void added(artemis::Entity& e) final; virtual void removed(artemis::Entity& e) final; virtual void begin() final; virtual void end() final; virtual void processEntities(artemis::ImmutableBag<artemis::Entity*> & bag) final; virtual bool checkProcessing() final; SpriteBatch& m_spriteBatch; typedef std::pair<T*, const Transform*> DrawablePair; typedef std::unordered_map<int, DrawablePair> DrawableMap; // Ordered map std::map<int, DrawableMap> m_drawables; }; #endif
bb94bc7308b349e8ec62ae6b771cb03476de7e38
bffc3c917900674f98379e842408a867cf92b558
/test3.cpp
60d9f72ead866d2c24ef8d711e5950c90263661f
[]
no_license
firstmanpower/SPScript
441c7949ebda6340e2b1170b91dc0911a1615e90
d05be44db287fb0b304421311fe63f19d37aec19
refs/heads/master
2021-01-01T11:35:06.626424
2020-02-14T23:50:43
2020-02-14T23:50:43
239,261,116
0
0
null
null
null
null
UTF-8
C++
false
false
4,716
cpp
test3.cpp
#include <stdio.h> #include <stdlib.h> #include <dirent.h> int SizeOfString(const char* str) { int value = 0; for (int i = 0; str[i] != 0; i++) { value = i; } return value + 1; } void Copy(char* str, const char* str2, int strsize){ for(int i = 0; i < strsize; i++){ str[i] = str2[i]; } } void MemSet(char* str, char val, int strsize) { for (int i = 0; i < strsize; i++) { str[i] = val; } } int Getstrpos(const char* str, const char* str2){ int i2 = 0; for(int i = 0; i < SizeOfString(str)+1; i++){ } } void DeleteBlank(char* str){ char* l_str = new char[SizeOfString(str)+1]; int i2 = 0; for(int i = 0; i < SizeOfString(str)+1; i++){ if(str[i] != ' ' && str[i] != ' '){ l_str[i2] = str[i]; i2++; } } Copy(str, l_str, SizeOfString(str)+1); } void _DeleteBlank(char* str, char* result, int resultsize){ char* l_str = new char[SizeOfString(str)+1]; int i2 = 0; for(int i = 0; i < SizeOfString(str)+1; i++){ if(str[i] != ' ' && str[i] != ' '){ l_str[i2] = str[i]; i2++; } } Copy(result, l_str, resultsize); } void Substr(const char* str, int num, char* result, int resultsize) { int i2 = 0; char* CS = new char[resultsize]; MemSet(CS, 0, resultsize); for (int i = 0; i < resultsize; i++) { if (SizeOfString(str)-num != i2) { CS[i] = str[i2]; i2++; } } Copy(result, CS, resultsize); } void AddStr(const char* str, const char* str2, char* result, int resultsize) { int i2 = 0; int i3 = 0; char* CS = new char[resultsize]; MemSet(CS, 0, resultsize); for (int i = 0; i < resultsize; i++) { if (SizeOfString(str) != i2) { CS[i] = str[i2]; i2++; } else if(SizeOfString(str2) != i3){ CS[i] = str2[i3]; i3++; } } Copy(result, CS, resultsize); } bool _strcmp(const char* str, const char* str2){ int i2 = 0; for(int i = 0; i < SizeOfString(str)+1; i++){ if(str[i] == str2[i2]){ i2++; if(i2 >= SizeOfString(str2))return true; } else{ i2 = 0; } } return false; } int ___strcmp(const char* str, const char* str2){ int i2 = 0; for(int i = 0; i < SizeOfString(str)+1; i++){ if(str[i] == str2[i2]){ i2++; if(i2 >= SizeOfString(str2))return i; } else{ i2 = 0; } } return -1; } int ____strcmp(int startpos, const char* str, const char* str2){ int i2 = 0; for(int i = startpos; i < SizeOfString(str)+1; i++){ if(str[i] == str2[i2]){ i2++; if(i2 >= SizeOfString(str2))return i; } else{ i2 = 0; } } return -1; } bool __strcmp(int startpos, const char* str, const char* str2){ int i2 = 0; for(int i = startpos; i < SizeOfString(str)+1; i++){ if(str[i] == str2[i2]){ i2++; if(i2 >= SizeOfString(str2))return true; } else{ i2 = 0; } } return false; } void EditFile(char* str, int startpos, int endpos){ for(int i = startpos; i < endpos; i++){ if(str[i] == '\\'){ str[i] = '/'; } } } void Fmp_Scan(const char* str){ DIR *_dir; struct dirent *dire; int cysize = SizeOfString(str)+1+256+1; FILE* fp; FILE* fp2; long nbytes = 0; char *file_buffer; _dir = opendir(str); if(_dir) { while ((dire = readdir(_dir)) != NULL) { if(dire->d_type != DT_DIR && dire->d_name[0] != '.'){ char * copy = new char[cysize]; AddStr(str, "\\", copy, cysize); AddStr(copy, dire->d_name, copy, cysize); fp = fopen(copy, "r"); char oldfile_name[300]; Copy(oldfile_name, copy, 300); AddStr("output\\", oldfile_name, oldfile_name, 300); fp2 = fopen(oldfile_name, "w"); if (fp == NULL || fp2 == NULL)return; fseek(fp, 0L, SEEK_END); nbytes = ftell(fp); fseek(fp, 0L, SEEK_SET); file_buffer = (char*)calloc(nbytes, sizeof(char)); if(file_buffer == NULL)return; fread(file_buffer, sizeof(char), nbytes, fp); int slot01 = ___strcmp(file_buffer, "\"mod_download\""); int slot01_1 = ____strcmp(slot01, file_buffer, "}"); int slot02 = ___strcmp(file_buffer, "\"download\""); int slot02_1 = ____strcmp(slot02, file_buffer, "}"); int slot03 = ___strcmp(file_buffer, "\"mat_download\""); int slot03_1 = ____strcmp(slot03, file_buffer, "}"); int slot04 = ___strcmp(file_buffer, "\"sound_bgm\""); int slot04_1 = ____strcmp(slot04, file_buffer, "}"); EditFile(file_buffer, slot01, slot01_1); EditFile(file_buffer, slot02, slot02_1); EditFile(file_buffer, slot03, slot03_1); EditFile(file_buffer, slot04, slot04_1); fputs(file_buffer, fp2); fclose(fp2); fclose(fp); } } } } int main(int argc, char **argv) { if(argc != 2)return 0; Fmp_Scan(argv[1]); return 0; }
8e9a4777d0c388bfb562bc80e9648c162f3dea5f
45ffd735bca9b753726972791eca1df8e54313d1
/C-Craft++/Context.cpp
9697d4634d9f4105158f51e364701361fb063f34
[]
no_license
Intekin/C-Craftpp
4302c4ef80b478bd281445aed8fe527a4541bfc9
55a92810fa81843a3324392c5408e1177d72e534
refs/heads/master
2021-09-06T10:49:05.825805
2017-12-04T14:35:09
2017-12-04T14:35:09
111,219,962
0
0
null
null
null
null
UTF-8
C++
false
false
1,245
cpp
Context.cpp
#include "Context.h" #include "GlobalInfo.h" #include <GL\glew.h> #include <iostream> sf::RenderWindow* g_window; Context::Context(const Config& config) { sf::ContextSettings settings; settings.antialiasingLevel = 0; settings.majorVersion = 3; settings.minorVersion = 3; settings.depthBits = 24; settings.stencilBits = 8; settings.attributeFlags = sf::ContextSettings::Debug; std::cout << "OpenGL version:" << settings.majorVersion << "." << settings.minorVersion << std::endl; if (config.isFullscreen) { window.create(sf::VideoMode::getDesktopMode(), "C-Craft++", sf::Style::Fullscreen, settings); g_info.resolutionX = sf::VideoMode::getDesktopMode().width; g_info.resolutionY = sf::VideoMode::getDesktopMode().height; } else { sf::VideoMode winMode(config.windowX, config.windowY); window.create(winMode, "C-Craft++", sf::Style::Close, settings); g_info.resolutionX = config.windowX; g_info.resolutionY = config.windowY; } g_window = &window; glewExperimental = GL_TRUE; GLenum err = glewInit(); if (err != GLEW_OK) { throw std::runtime_error("GLEW init failed"); } glViewport(0, 0, window.getSize().x, window.getSize().y); glCullFace(GL_BACK); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); }
92a42c27000418d4385d09e2815ab944ec308059
05e82fe22459b6befc8304bd7e096e7c7727b3ff
/laba5massives/Header.h
a2a62dba2d1307debb414de3bb31f751ceeba7ec
[]
no_license
FOOZBY/laba5massives
f0e84c3f7977971a3f2d2c2da0ef8f9f465efc12
a54546a25c027e1b0c53d7cbf0b6dcfa2a9aaee1
refs/heads/master
2023-04-08T19:03:59.401208
2021-04-19T17:21:14
2021-04-19T17:21:14
349,257,690
0
0
null
null
null
null
UTF-8
C++
false
false
294
h
Header.h
#include <iostream> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <regex> using namespace std; double getnum(); void show_array(double (&arr)[10][10], int n); void fill_array(double (&arr)[10][10], int n); void change_array(double(&arr)[10][10], int n);
bc206ceda42b0e0a058e48a36f5976ba2082108c
f113b7f7695bf2f5c09e5e8afb28cc99ee06c63a
/trrom/matlab/TRROM_MxReducedObjectiveOperators.hpp
28f5ecf5f8538aa4998e3aa29ba209e8244c278c
[]
no_license
maguilo11/locus
501a074a12e260e2b9f0940a6eb389ad36aefb89
cbf926808493c621893cc11f124f813b9e0fcbde
refs/heads/master
2021-09-24T21:35:27.503003
2018-10-15T02:58:38
2018-10-15T02:58:38
72,475,433
1
0
null
null
null
null
UTF-8
C++
false
false
7,939
hpp
TRROM_MxReducedObjectiveOperators.hpp
/* * TRROM_MxReducedObjectiveOperators.hpp * * Created on: Dec 1, 2016 * Author: maguilo */ #ifndef TRROM_MXREDUCEDOBJECTIVEOPERATORS_HPP_ #define TRROM_MXREDUCEDOBJECTIVEOPERATORS_HPP_ #include <mex.h> #include "TRROM_ReducedObjectiveOperators.hpp" namespace trrom { template<typename ScalarType> class Vector; class MxReducedObjectiveOperators : public trrom::ReducedObjectiveOperators { public: //! @name Constructors/destructors //@{ /*! * Creates a MxReducedObjectiveOperators object * Parameters: * \param In * input_: MEX array pointer * * \return Reference to MxReducedObjectiveOperators. * **/ explicit MxReducedObjectiveOperators(const mxArray* input_); //! MxReducedObjectiveOperators destructor. virtual ~MxReducedObjectiveOperators(); //@} /*! * Evaluates nonlinear programming objective function of type f(\mathbf{u},\mathbf{z})\colon * \mathbb{R}^{n_u}\times\mathbb{R}^{n_z}\rightarrow\mathbb{R}, using the MEX interface. Here * u denotes the state and z denotes the control variables. **/ double value(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_); /*! MEX interface is used to evaluate the objective function inexactness * Parameters: * \param In * state_: state variables * \param In * control_: control variables * * \return Objective function inexactness. If no error certification is available (i.e. user has not * perform the error analysis for the problem of interest), user must return zero. **/ double evaluateObjectiveInexactness(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_); /*! MEX interface is used to evaluate the gradient operator inexactness * Parameters: * \param In * state_: state variables * \param In * control_: control variables * * \return Gradient operator inexactness. If no error certification is available (i.e. user has not * perform the error analysis for the problem of interest), user must return zero. **/ double evaluateGradientInexactness(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_); /*! * Evaluates partial derivative of the objective function with respect to the * state variables, \frac{\partial{f(\mathbf{u},\mathbf{z})}}{\partial\mathbf{u}}, * using the MEX interface. * Parameters: * \param In * state_: state variables * \param In * control_: control variables * \param Out * output_: partial derivative of the objective function with respect to the state variables **/ void partialDerivativeState(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_, trrom::Vector<double> & output_); /*! * Evaluates partial derivative of the objective function with respect to the state variables, * \frac{\partial{f(\mathbf{u},\mathbf{z})}}{\partial\mathbf{z}}, using the MEX interface. * Parameters: * \param In * state_: state variables * \param In * control_: control variables * \param Out * output_: partial derivative of the objective function with respect to the control variables **/ void partialDerivativeControl(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_, trrom::Vector<double> & output_); /*! * Evaluates mixed partial derivative of the objective function with respect to the control and * state variables, \frac{\partial^2{f(\mathbf{u},\mathbf{z})}}{\partial\mathbf{z}\partial\mathbf{u}}, * using the MEX interface. * Parameters: * \param In * state_: state variables * \param In * control_: control variables * \param In * vector_: perturbation vector * \param Out * output_: mixed partial derivative of the objective function with respect to the control and state variables **/ void partialDerivativeControlState(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_, const trrom::Vector<double> & vector_, trrom::Vector<double> & output_); /*! * Evaluates second order partial derivative of the objective function with respect to the * control variables, \frac{\partial^2{f(\mathbf{u},\mathbf{z})}}{\partial\mathbf{z}^2}, * using the MEX interface. * Parameters: * \param In * state_: state variables * \param In * control_: control variables * \param In * vector_: perturbation vector * \param Out * output_: second order partial derivative of the objective function with respect to the control variables **/ void partialDerivativeControlControl(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_, const trrom::Vector<double> & vector_, trrom::Vector<double> & output_); /*! * Evaluates second order partial derivative of the objective function with respect to the * state variables, \frac{\partial^2{f(\mathbf{u},\mathbf{z})}}{\partial\mathbf{u}^2}, * using the MEX interface. * Parameters: * \param In * state_: state variables * \param In * control_: control variables * \param In * vector_: perturbation vector * \param Out * output_: second order partial derivative of the objective function with respect to the state variables **/ void partialDerivativeStateState(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_, const trrom::Vector<double> & vector_, trrom::Vector<double> & output_); /*! * Evaluates mixed partial derivative of the objective function with respect to the control and * state variables, \frac{\partial^2{f(\mathbf{u},\mathbf{z})}}{\partial\mathbf{u}\partial\mathbf{z}}, * using the MEX interface. * Parameters: * \param In * state_: state variables * \param In * control_: control variables * \param In * vector_: perturbation vector * \param Out * output_: mixed partial derivative of the objective function with respect to the state and control variables **/ void partialDerivativeStateControl(const trrom::Vector<double> & state_, const trrom::Vector<double> & control_, const trrom::Vector<double> & vector_, trrom::Vector<double> & output_); private: mxArray* m_Value; mxArray* m_GradientError; mxArray* m_ObjectiveError; mxArray* m_PartialDerivativeState; mxArray* m_PartialDerivativeControl; mxArray* m_PartialDerivativeControlState; mxArray* m_PartialDerivativeControlControl; mxArray* m_PartialDerivativeStateState; mxArray* m_PartialDerivativeStateControl; private: MxReducedObjectiveOperators(const trrom::MxReducedObjectiveOperators &); trrom::MxReducedObjectiveOperators & operator=(const trrom::MxReducedObjectiveOperators & rhs_); }; } #endif /* TRROM_MXREDUCEDOBJECTIVEOPERATORS_HPP_ */
463fa730ec47b16044118a1a3c53baff27d60f1e
10e48d2b31ad0cbf1f321dc7bd59d800873ddcad
/src/multimedia/qqtwavsoundeffect.cpp
5dd2cedaeafaafd5d2cb29238db172b78d1ffd1a
[]
no_license
Qt-Widgets/LibQQt-Widgets-Collection
5393ba76abbf2d152c3c7f0c0ab86d733147d882
9db5b678fefd2efa1eb5f2565aad5e48df2bdf18
refs/heads/master
2020-11-28T02:57:24.183536
2019-11-29T07:30:57
2019-11-29T07:30:57
229,687,198
6
0
null
null
null
null
UTF-8
C++
false
false
3,893
cpp
qqtwavsoundeffect.cpp
#include "qqtwavsoundeffect.h" QQtWavSoundEffect* QQtWavSoundEffect::msInstance = NULL; QQtWavSoundEffect* QQtWavSoundEffect::Instance ( QObject* parent ) { if ( !msInstance ) msInstance = new QQtWavSoundEffect ( parent ); return msInstance; } QQtWavSoundEffect::QQtWavSoundEffect ( QObject* parent ) : QObject ( parent ) { mVolume = 1; mIOInput = NULL; mLooping = 1; mLoops = 1; } void QQtWavSoundEffect::setOutputDevice ( const QAudioDeviceInfo& output ) { if ( output.isNull() ) manager.outputDeviceInfo() = QQtAudioManager::defaultOutputDevice(); else manager.outputDeviceInfo() = output; } void QQtWavSoundEffect::useDefaultOutputDevice() { manager.outputDeviceInfo() = QQtAudioManager::defaultOutputDevice(); } void QQtWavSoundEffect::useCustomOutputDevice ( const QAudioDeviceInfo& output ) { manager.outputDeviceInfo() = output; } #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QDebug& operator << ( QDebug& dbg, const QAudioFormat& fmt ) { return dbg; } #endif void QQtWavSoundEffect::play ( QString localFile ) { #if QT_VERSION > QT_VERSION_CHECK(5,0,0) //判断文件类型是否接受 QMimeDatabase mimedb; QMimeType mimetype = mimedb.mimeTypeForFile ( localFile ); if ( !QSoundEffect::supportedMimeTypes().contains ( mimetype.name(), Qt::CaseInsensitive ) ) { pline() << "filename" << localFile << "mimetype" << mimetype.name() << QSoundEffect::supportedMimeTypes().contains ( mimetype.name(), Qt::CaseInsensitive ) ; pline() << "can't play file"; return; } #endif mSourceFile = localFile; stop(); mIOInput = mWavInput.setSourceFile ( localFile ); connect ( mIOInput, SIGNAL ( readyRead() ), this, SLOT ( readyRead() ) ); QAudioDeviceInfo& usingOutput = manager.outputDeviceInfo(); QAudioFormat fmt = mWavInput.format(); //输出设备是否支持格式是否支持 if ( !usingOutput.isFormatSupported ( fmt ) ) { //当前使用设备是否支持 pline() << "output cant support" << fmt; fmt = usingOutput.nearestFormat ( fmt ); //转换为最接近格式 pline() << "use format" << fmt; } manager.outputAudioFormat() = fmt; manager.startOutput(); #if QT_VERSION > QT_VERSION_CHECK(5,0,0) //默认是静音的。 manager.outputManager()->setVolume ( mVolume ); #endif //不响,音频输出设备接受顺序的间隔的输出,不接受一股脑输出。 //manager.write ( bytes ); //OK, 达到QSound效果。 mWavInput.start(); } void QQtWavSoundEffect::stop() { //如果正在播放,先关闭 if ( mIOInput ) { mWavInput.stop(); manager.stopOutput(); disconnect ( mIOInput, SIGNAL ( readyRead() ), this, SLOT ( readyRead() ) ); mIOInput = NULL; } mLooping = 1; mDataSize = 0; } void QQtWavSoundEffect::setVolume ( qreal volume ) { mVolume = volume; #if QT_VERSION > QT_VERSION_CHECK(5,0,0) manager.outputManager()->setVolume ( mVolume ); #endif } int QQtWavSoundEffect::loops() const { return mLoops; } int QQtWavSoundEffect::loopsRemaining() const { return mLoops - mLooping; } void QQtWavSoundEffect::setLoops ( int loops ) { mLoops = loops; } void QQtWavSoundEffect::readyRead() { QByteArray bytes = mIOInput->readAll(); //pline() << bytes.size(); manager.write ( bytes ); mDataSize += bytes.size(); if ( mDataSize == mWavInput.fileDataSize() ) { int loop = mLooping; if ( loop < loops() ) play ( mSourceFile ); mLooping = loop + 1; } } QQtWavSoundEffect* QQtWavSound ( QString localFile ) { if ( !localFile.isEmpty() ) QQtWavSoundEffect::Instance ( )->play ( localFile ); return QQtWavSoundEffect::Instance(); }
627defa4837d53d5f722da5b8145f59944d13e54
be4952850ad6a8b0abe50de671c495c6add9fae7
/hdu/1267.cpp
5cce26fd17811e70cd6e8a83e9d557e8ca65f6a6
[]
no_license
ss5ssmi/OJ
296cb936ecf7ef292e91f24178c9c08bd2d241b5
267184cef5f1bc1f222950a71fe705bbc5f0bb3e
refs/heads/master
2022-10-29T18:15:14.290028
2022-10-12T04:42:47
2022-10-12T04:42:47
103,818,651
0
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
1267.cpp
#include<stdio.h> #include<string.h> int main(){ __int64 s[21][21]; int i,j,x,y; memset(s,0,sizeof(s)); for(i=0;i<21;i++){ s[i][0]=1; } for(i=1;i<=20;i++){ for(j=i;j<=20;j++){ s[j][i]=s[j-1][i]+s[j][i-1]; } } while(scanf("%d %d",&x,&y)!=EOF){ printf("%I64d\n",s[x][y]); } return 0; }
1f8321cd645d441f9ee3f4469530e2f2e5955d16
fafce52a38479e8391173f58d76896afcba07847
/uppdev/MyDbase/query.cpp
62351f03eb2b6691c07d9edc52921ef89d6f46c2
[]
no_license
Sly14/upp-mirror
253acac2ec86ad3a3f825679a871391810631e61
ed9bc6028a6eed422b7daa21139a5e7cbb5f1fb7
refs/heads/master
2020-05-17T08:25:56.142366
2015-08-24T18:08:09
2015-08-24T18:08:09
41,750,819
2
1
null
null
null
null
WINDOWS-1252
C++
false
false
8,351
cpp
query.cpp
#include "dbase.h" //int dbDatabase::Query(const String &queryString, dbRecordSet &rs1) { Value dbDatabase::Query(const String &queryString) { unsigned int i, j, f, h, p, b, n, a; String tbn, whr; Array<String> ord, groupBy; Array<unsigned int> ordStyle; bool b1, validRecord; //dbRecordSet rs1; dbRecordSet rs1; //rs1.Reset(); Vector<String> tkn = StringToToken(queryString); if(String(tkn[0]) == "SELECT") { ExecuteSelect(tkn, rs1); //StringStream s; //s.SetStoring(); //rs1.Serialize(s); //return String(s); return RawToValue(rs1); } else if(String(tkn[0]) == "DELETE") { return ExecuteDelete(tkn); } else if(String(tkn[0]) == "UPDATE") { return ExecuteUpdate(tkn); } else if(String(tkn[0]) == "INSERT") { return ExecuteInsert(tkn); } return 0; } void dbDatabase::ExecuteSelect(Vector<String> &tkn, dbRecordSet &result) { unsigned int i, j, f, h, p, b, n, a; String tbn, whr; Array<String> ord, groupBy; Array<unsigned int> ordStyle; bool b1, validRecord; n = tkn.GetCount(); // cerco il nome della tabella for(f=1; f<n; f++) { if(strcmp(tkn.At(f), "FROM") == 0) { tbn = tkn.At(f+1); #ifdef _WITH_DEBUG RLOG("ExecuteSelect():From = " + tbn); #endif break; } } if((h = GetTableHandle(tbn)) == MTDB_TB_NOT_FOUND) return; // nome tabella trovato; // cerco la condizione where for(f=1; f<n; f++) { if(strcmp(tkn.At(f), "WHERE") == 0) { whr = tkn.At(f+1); #ifdef _WITH_DEBUG RLOG("ExecuteSelect():Where = " + whr); #endif break; } } // condizione where trovata; // cerco la condizione GROUP BY for(f=1; f<n; f++) { if(strcmp(tkn.At(f), "GROUP") == 0 && strcmp(tkn.At(f+1), "BY") == 0) { p = 2; while((f+p)<n && !IsSQLWord(tkn.At(f+p))) { groupBy.Add(tkn.At(f+p)); p++; #ifdef _WITH_DEBUG RLOG("ExecuteSelect():Group by = " + groupBy.Top()); #endif } break; } } // cerco la condizione Order By for(f=1; f<n; f++) { if(strcmp(tkn.At(f), "ORDER") == 0 && strcmp(tkn.At(f+1), "BY") == 0) { p = 2; for(i=0; i<3; i++) { if((f+p)<n && !IsSQLWord(tkn.At(f+p))) { ord.Add(tkn.At(f+p)); if(strcmp(tkn.At(f+p+1), "DESC") == 0) { ordStyle.At(i) = MTDB_DESC; p += 2; } else if(strcmp(tkn.At(f+p+1), "ASC") == 0) { ordStyle.At(i) = MTDB_ASC; p += 2; } else { ordStyle.At(i) = MTDB_ASC; p += 1; } #ifdef _WITH_DEBUG RLOG("ExecuteSelect():Order by = " + ord.Top() + " - " + AsString(ordStyle[i])); #endif } } } } // condizione Order By trovata; // creazione testa del RecorSet (metto in ordine i nomi di campo secondo l'ordine di query) Array<String> keys; for(f=1; f<n; f++) { if(!IsSQLWord(tkn.At(f))) { if(strcmp(tkn.At(f), "*") != 0) { for(i=0; i<GetNumOfField(h); i++) { if(strcmp(GetFieldName(h, i), tkn.At(f)) == 0) { keys.Add(String(GetFieldName(h, i))); } } } else { for(i=0; i<GetNumOfField(h); i++) { b1 = false; for(j=0; j<keys.GetCount(); j++) { if(strcmp(GetFieldName(h, i), keys[j]) == 0) { b1 = true; } } if(!b1) keys.Add(String(GetFieldName(h, i))); } } } else break; } // testa RecordSet creata tkn.SetCountR(n); dbRecord rec1; for(i=1; i<=GetNumOfRec(h); i++) { validRecord = false; if(GetRecord(h, i, rec1) == MTDB_SUCCESS) { if(EvalWhere(rec1, whr)) { // se il record è valido #ifdef _WITH_DEBUG RLOG("ExecuteSelect():type = " + String(tkn[0])); #endif dbRecord rc2; for(unsigned int y=0; y<keys.GetCount(); y++) { Value v = rec1.GetValue(keys[y]); rc2.Add(keys[y], v); } result.Add((int)i, rc2, ord, ordStyle); } #ifdef _WITH_DEBUG RLOG("ExecuteSelect():recno = " + FormatInt(i)); #endif } } return; } int dbDatabase::ExecuteDelete(Vector<String> &tkn) { unsigned int i, j, f, h, p, b, n, a; String tbn, whr; bool b1, validRecord; n = tkn.GetCount(); // cerco il nome della tabella for(f=1; f<n; f++) { if(strcmp(tkn.At(f), "FROM") == 0) { tbn = tkn.At(f+1); break; } } if((h = GetTableHandle(tbn)) == MTDB_TB_NOT_FOUND) return MTDB_TB_NOT_FOUND; // nome tabella trovato; // cerco la condizione where for(f=1; f<n; f++) { if(strcmp(tkn.At(f), "WHERE") == 0) { whr = tkn.At(f+1); break; } } // condizione where trovata; dbRecord rec1; n = 0; for(i=1; i<=GetNumOfRec(h); i++) { validRecord = false; if(GetRecord(h, i, rec1) == MTDB_SUCCESS) { if(EvalWhere(rec1, whr)) { // se il record è valido DelRec(h, i); n++; } } } return n; } int dbDatabase::ExecuteUpdate(Vector<String> &tkn) { unsigned int i, j, f, h, p, b, n, a; String table, whr; bool b1, validRecord; n = tkn.GetCount(); // cerco il nome della tabella for(f=0; f<n; f++) { if(tkn.At(f) == "UPDATE") { table = tkn.At(f+1); break; } } if((h = GetTableHandle(table)) == MTDB_TB_NOT_FOUND) return MTDB_TB_NOT_FOUND; // cerco la condizione where for(f; f<n; f++) { if(tkn.At(f) == "WHERE") { whr = tkn.At(f+1); break; } } // creo l'array dei valori da aggiornare VectorMap<String, String> values; bool s = false; for(f=1; f<n; f++) { if(!s && tkn.At(f) == "SET") s = true; else if(s) { if(!IsSQLWord(tkn.At(f))) { int u; if((u = StringSearch(tkn.At(f), "=")) > 0) { values.Add(tkn.At(f).Left(u), tkn.At(f).Mid(u+1)); } } else { s = false; break; } } } dbRecord rec1; n = 0; for(i=1; i<=GetNumOfRec(h); i++) { validRecord = false; if(GetRecord(h, i, rec1) == MTDB_SUCCESS) { if(EvalWhere(rec1, whr)) { // se il record è valido // sostituisco i nuovi valori for(int k=0; k<values.GetCount(); k++) { if(rec1(values.GetKey(k)).GetType() == BOOL_V) { rec1(values.GetKey(k)) = (bool)atoi(~CSVDequote(values[k])); } if(rec1(values.GetKey(k)).GetType() == INT_V) { rec1(values.GetKey(k)) = (int)atoi(~CSVDequote(values[k])); } else if(rec1(values.GetKey(k)).GetType() == DOUBLE_V) { rec1(values.GetKey(k)) = (double)atof(~CSVDequote(values[k])); } else if(rec1(values.GetKey(k)).GetType() == STRING_V) { rec1(values.GetKey(k)) = CSVDequote(values[k]); } else if(rec1(values.GetKey(k)).GetType() == MTDB_DATETIME || rec1(values.GetKey(k)).GetType() == MTDB_DATE || rec1(values.GetKey(k)).GetType() == MTDB_TIME ) { ConvertTime cv; rec1(values.GetKey(k)) = (Time)cv.Scan(CSVDequote(values[k])); } } PutRecord(h, i, rec1, true); n++; } } } return n; } int dbDatabase::ExecuteInsert(Vector<String> &tkn) { unsigned int i, j, f, h, p, b, n, a; String table; bool b1, validRecord; n = tkn.GetCount(); // cerco il nome della tabella for(f=1; f<n; f++) { if(tkn.At(f) == "INTO") { table = tkn.At(f+1); f += 2; break; } } if((h = GetTableHandle(table)) == MTDB_TB_NOT_FOUND) return MTDB_TB_NOT_FOUND; // creo l'array delle chiavi da inserire VectorMap<String, String> values; Vector<String> buff = StringToToken(tkn.At(f).Mid(1, tkn.At(f).GetLength()-2)); for(int u=0; u<buff.GetCount(); u++) { values.Add(buff[u]); } for(; f<n; f++) { if(tkn.At(f) == "VALUES") { buff = StringToToken(tkn.At(f+1).Mid(1, tkn.At(f+1).GetLength()-2)); for(int u=0; u<buff.GetCount(); u++) { values[u] = buff[u]; } break; } } n = 0; dbRecord rec1; for(int k=0; k<values.GetCount(); k++) { int t = GetFieldFormat(table, values.GetKey(k)); if(t == MTDB_INT || t == MTDB_BOOL) { rec1(values.GetKey(k)) = (int)atoi(~CSVDequote(values[k])); } else if(t == MTDB_DOUBLE) { rec1(values.GetKey(k)) = (double)atof(~CSVDequote(values[k])); } else if(t == MTDB_DATETIME || t == MTDB_DATE || t == MTDB_TIME ) { ConvertTime cv; rec1(values.GetKey(k)) = (Time)cv.Scan(CSVDequote(values[k])); } else if((t >= 0x0100 && t <= 0x02ff) || t == MTDB_STR) { rec1(values.GetKey(k)) = CSVDequote(values[k]); } } PutRecord(h, MTDB_TB_APP, rec1, true); n++; return n; }
2a9e4c161597f71d3206da4c3d9cf7dff9b51046
a91796ab826878e54d91c32249f45bb919e0c149
/modules/video/perf/perf_bgfg_mog2.cpp
610138f85c60d27e127afdd98368ab6b90a4c75e
[ "Apache-2.0" ]
permissive
opencv/opencv
8f1c8b5a16980f78de7c6e73a4340d302d1211cc
a308dfca9856574d37abe7628b965e29861fb105
refs/heads/4.x
2023-09-01T12:37:49.132527
2023-08-30T06:53:59
2023-08-30T06:53:59
5,108,051
68,495
62,910
Apache-2.0
2023-09-14T17:37:48
2012-07-19T09:40:17
C++
UTF-8
C++
false
false
2,593
cpp
perf_bgfg_mog2.cpp
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "perf_precomp.hpp" #include "perf_bgfg_utils.hpp" namespace opencv_test { namespace { //////////////////////////// Mog2////////////////////////// typedef tuple<std::string, int> VideoMOG2ParamType; typedef TestBaseWithParam<VideoMOG2ParamType> MOG2_Apply; typedef TestBaseWithParam<VideoMOG2ParamType> MOG2_GetBackgroundImage; PERF_TEST_P(MOG2_Apply, Mog2, Combine(Values("cv/video/768x576.avi", "cv/video/1920x1080.avi"), Values(1,3))) { VideoMOG2ParamType params = GetParam(); const string inputFile = getDataPath(get<0>(params)); const int cn = get<1>(params); int nFrame = 5; vector<Mat> frame_buffer(nFrame); cv::VideoCapture cap(inputFile); if (!cap.isOpened()) throw SkipTestException("Video file can not be opened"); prepareData(cap, cn, frame_buffer); Mat foreground; TEST_CYCLE() { Ptr<cv::BackgroundSubtractorMOG2> mog2 = createBackgroundSubtractorMOG2(); mog2->setDetectShadows(false); foreground.release(); for (int i = 0; i < nFrame; i++) { mog2->apply(frame_buffer[i], foreground); } } SANITY_CHECK_NOTHING(); } PERF_TEST_P(MOG2_GetBackgroundImage, Mog2, Values( std::make_pair<string, int>("cv/video/768x576.avi", 5), std::make_pair<string, int>("cv/video/1920x1080.avi", 5))) { VideoMOG2ParamType params = GetParam(); const string inputFile = getDataPath(get<0>(params)); const int cn = 3; const int skipFrames = get<1>(params); int nFrame = 10; vector<Mat> frame_buffer(nFrame); cv::VideoCapture cap(inputFile); if (!cap.isOpened()) throw SkipTestException("Video file can not be opened"); prepareData(cap, cn, frame_buffer, skipFrames); Mat foreground, background; TEST_CYCLE() { Ptr<cv::BackgroundSubtractorMOG2> mog2 = createBackgroundSubtractorMOG2(); mog2->setDetectShadows(false); foreground.release(); background.release(); for (int i = 0; i < nFrame; i++) { mog2->apply(frame_buffer[i], foreground); } mog2->getBackgroundImage(background); } #ifdef DEBUG_BGFG imwrite(format("fg_%d_%d_mog2.png", frame_buffer[0].rows, cn), foreground); imwrite(format("bg_%d_%d_mog2.png", frame_buffer[0].rows, cn), background); #endif SANITY_CHECK_NOTHING(); } }}// namespace
5f27138a0c3394aaf763688264774b7e88886970
1a92eb77a231d6941de0ded7ddd547133ca6fde6
/src/server/protocol/ServerHttp1.h
21001a5fb4d420f939a97c4bc0875dfe63a7d645
[ "MIT" ]
permissive
zminor/Zony_CPP
5b160c65357a443e0241ed970ba0a635823ff4bd
311c75a3d6acebb7f4265b63813b19eeaa9d8926
refs/heads/master
2020-03-19T12:19:17.989166
2018-07-03T07:38:48
2018-07-03T07:38:48
136,510,601
0
0
null
null
null
null
UTF-8
C++
false
false
1,667
h
ServerHttp1.h
#ifndef __SERVERHTTP1_H__ #define __SERVERHTTP1_H__ #include "ServerProtocol.h" #include "../../transfer/HttpStatusCode.h" namespace HttpServer { class ServerHttp1 : public ServerProtocol { private: const ServerApplicationSettings *getApplicationSettings( struct Request &rp, const bool isSecureConnection ) const; Http::StatusCode getRequestData( struct Request &rp, std::string &str_buf, const ServerApplicationSettings &appSets ) const; protected: void useHttp1Protocol( struct Request &rp, std::vector<char> &buf, std::string &str_buf ) const; public: ServerHttp1( Socket::Adapter &sock, const ServerSettings &settings, ServerControls &controls ) noexcept; virtual bool sendHeaders( const Http::StatusCode status, std::vector<std::pair<std::string, std::string> > &headers, const std::chrono::milliseconds &timeout, const bool endStream ) const override; virtual long sendData( const void *src, size_t size, const std::chrono::milliseconds &timeout, DataTransfer *dt ) const override; virtual bool packRequestParameters( std::vector<char> &buf, const struct Request &rp, const std::string &rootDir ) const override; virtual void unpackResponseParameters( struct Request &req, const void *src ) const override; virtual ServerProtocol *process() override; virtual void close() override; }; } #endif
1da61a063fa151accd32fe8db7254e5ec05c1d02
187bd1fada83ae5888b4822d63abda9856453800
/include/YourDetectorConstruction.hh
c7e1374ad0a9d7a866783f9e17c6051a8bf73348
[]
no_license
shiv6510/Geant4
f1d0078a84ce2948128bc6968cf92fc14037ac72
e67394a7ff0ff85b872010bf98c432c8eda19ea8
refs/heads/main
2023-07-14T13:25:17.757948
2021-08-15T21:31:19
2021-08-15T21:31:19
387,872,320
0
0
null
null
null
null
UTF-8
C++
false
false
985
hh
YourDetectorConstruction.hh
#ifndef YOURDETECTORCONTRUCTION_HH #define YOURDETECTORCONTRUCTION_HH #include "G4VUserDetectorConstruction.hh" #include "MySensitiveDetector.hh" // forward declarations // class G4VPhysicalVolume; // This class is mandatory: description of the detector class YourDetectorConstruction : public G4VUserDetectorConstruction { public: // Method declarations YourDetectorConstruction(); // Constructor virtual ~YourDetectorConstruction(); // Destructor // The base class has the (only one) pure virtual method Construct() which // is invoked by the G4RunManager when it's Initialize() method is invoked. // The Construct() method must return the G4VPhysicalVolume pointer which // represents the world volume. // Your detector description must be implemented here in this method. virtual G4VPhysicalVolume* Construct(); private: // Data members G4LogicalVolume *logicDetector; //virtual void ConstructSDandField(); }; #endif
452a9f998f57602fe59c320ea382bdd9f0660111
e3729845ea0ec8f7c01acebfdc2217d13bd3cf5a
/BlockParser.h
9585c6c1be7df6aff411e91afc88006fc51c0c96
[ "BSD-3-Clause" ]
permissive
mugwort-rc/MarkdownCpp
8137d9a30824b29308f51a6d92c67a95849190dd
7b1f4db24ae2b1a0dd4f6e03a9854892ae815508
refs/heads/master
2020-06-07T14:03:12.567866
2014-01-17T12:52:04
2014-01-17T12:52:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,364
h
BlockParser.h
/* * BlockParser.h * * Created on: 2013/10/27 * Author: mugwort_rc */ #ifndef BLOCKPARSER_H_ #define BLOCKPARSER_H_ #include "BlockProcessors.h" namespace markdown{ class Markdown; //!< forward declaration /*! * Track the current and nested state of the parser. * * This utility class is used to track the state of the BlockParser and * support multiple levels if nesting. It's just a simple API wrapped around * a list. Each time a state is set, that state is appended to the end of the * list. Each time a state is reset, that state is removed from the end of * the list. * * Therefore, each time a state is set for a nested block, that state must be * reset when we back out of that level of nesting or the state could be * corrupted. * * While all the methods of a list object are available, only the three * defined below need be used. */ class State { public: State() {} /*! * Set a new state. */ void set(const std::wstring &state) { this->list.push_back(state); } /*! * Step back one step in nested state. */ void reset(void) { this->list.pop_back(); } /*! * Test that top (current) level is of given state. */ bool isstate(const std::wstring &state) { if ( ! this->list.empty() ) { return this->list.back() == state; } return false; } private: std::list<std::wstring> list; }; /*! * Parse Markdown blocks into an ElementTree object. * * A wrapper class that stitches the various BlockProcessors together, * looping through them and creating an ElementTree object. */ class BlockParser { public: BlockParser(Markdown *markdown); /*! * Parse a markdown document into an ElementTree. * * Given a list of lines, an ElementTree object (not just a parent Element) * is created and the root element is passed to the parser as the parent. * The ElementTree object is returned. * * This should only be called on an entire document, not pieces. */ ElementTree parseDocument(const std::list<std::wstring> &lines); /*! * Parse a chunk of markdown text and attach to given etree node. * * While the ``text`` argument is generally assumed to contain multiple * blocks which will be split on blank lines, it could contain only one * block. Generally, this method would be called by extensions when * block parsing is required. * * The ``parent`` etree Element passed in is altered in place. * Nothing is returned. */ void parseChunk(Element &parent, const std::wstring &text); /*! * Process blocks of markdown text and attach to given etree node. * * Given a list of ``blocks``, each blockprocessor is stepped through * until there are no blocks left. While an extension could potentially * call this method directly, it's generally expected to be used internally. * * This is a public method as an extension may need to add/alter additional * BlockProcessors which call this method to recursively parse a nested * block. */ void parseBlocks(Element &parent, std::list<std::wstring> &blocks); public: Markdown* markdown; OrderedDictBlockProcessors blockprocessors; State state; ElementTree root; }; } // end of namespace markdown #endif /* BLOCKPARSER_H_ */
7858c6468c51471cc9d33536a5dc6a461248c846
4bc181c8ae76fc87e5a41ecbcfa5b6af77798b5f
/common/shared_conf.hpp
754e3acdc054eb06ac4b5168718d0e7bfc13ac8e
[]
no_license
computer-network-shenjian/linux-data-link-layer
5367848b8db81aa956c73e5397cd729e4c51e1e8
a739243be0a8b9af72f247cf0cbb6109a24aa7bd
refs/heads/master
2020-04-09T05:08:13.998491
2018-12-09T16:26:14
2018-12-09T16:26:14
160,052,918
0
0
null
2018-12-06T13:41:22
2018-12-02T13:58:25
C++
UTF-8
C++
false
false
1,704
hpp
shared_conf.hpp
// Configurations for shared libraries. #define SIGCKERR SIGRTMIN+1 //cksum_err #define SIGFRARV SIGRTMIN+2 //frame_arrival #define SIGNLREADY SIGRTMIN+3 //network_layer_ready #define SIGENANL SIGRTMIN+4 //enable_network_layer #define SIGDISNL SIGRTMIN+5 //disble_network_layer typedef unsigned int seq_nr; //send seq const unsigned int LEN_PKG_DATA = 1036; const unsigned int LEN_PKG_NODATA = 12; const unsigned int TCP_LISTEN_NUM = 10; const unsigned int RAW_DATA_SIZE = 1024; const char all_zero[LEN_PKG_DATA+1] = {0}; // Datalink layer protocols enum DProtocol{ test, utopia, simple_stop_and_wait, noisy_stop_and_wait, one_bit_sliding, back_n, selective_repeat }; // Pipe read and pipe write. enum Pipe_RW{ p_read = 0, p_write = 1 }; typedef enum { no_event, frame_arrival, cksum_err, timeout, network_layer_ready, ack_timeout }event_type; typedef enum { data, ack, nak }frame_kind; //frame types: data/ack/nak struct packet{ unsigned char data[RAW_DATA_SIZE] = {0}; }; struct frame{ frame_kind kind; seq_nr seq; seq_nr ack; packet info; }; extern int sig_cksum_err; extern int sig_frame_arrival; extern int sig_network_layer_ready; extern int sig_enable_network_layer; extern int sig_timeout; extern int sig_ack_timeout; //#define SEND_FILE "rand_100.myfile" #define SEND_FILE "rand_1.myfile" //#define SEND_FILE "README.md" #define RECV_FILE "recv.myfile" // timeout for select. const int timeout_seconds = 0; const int timeout_microseconds = 50 * 1000; // 50ms // how many ticks a frame lasts const unsigned int tick_s = 2; // s const int error_rate = 3; // %
98746bfb3f8ca67c7393f930ae0af3e3cc855de8
1e73e280d1af2a77a3bece88f46e753aebd30e34
/engine/code/sources/Kernel.cpp
08e8bae3bed6ffac35c4a8078ba38c2ac8a99f59
[]
no_license
ricky395/LilEngine
3ac5a545ae1cf4f7d7038fe3f89f4b0ded553924
8dad9f8be50f68bb8dbc89e6668ce0c5bea39dc1
refs/heads/master
2023-04-25T15:52:25.567358
2021-05-06T16:02:46
2021-05-06T16:02:46
364,956,125
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,351
cpp
Kernel.cpp
/// Author: Ricardo Roldán Fernández /// Date: 26/06/2018 #include "Kernel.hpp" #include "Task.hpp" void Kernel::execute() { exit = false; // Se inicializan primero las tareas init(); // Parámetros iniciales del timer auto previous_t = Time::now(); auto current_t = Time::now(); // Delta time inicial delta_time = m_to_float(current_t - previous_t).count() * 0.001; while (!exit) { current_t = Time::now(); // Se recorren todas las tareas std::list< Task * >::iterator it; for (it = task_list.begin(); it != task_list.end(); ++it) { Task * task = *it; task->run(delta_time); // Si alguna tarea finaliza... if (task->is_finished()) { // Método finalize, que finaliza los componentes asociados task->finalize(); // Se elimina task_list.remove(task); } } // Cálculo de delta time delta_time = m_to_float(current_t - previous_t).count() * 0.001; previous_t = current_t; } } void Kernel::init() { for (auto & task : task_list) { task->initialize(); } } void Kernel::stop() { exit = true; } void Kernel::add(Task & task) { // Se añade la tarea a la lista de tareas task_list.push_back(&task); // Se reordena la lista por prioridad de ejecución task_list.sort(compare); } bool Kernel::compare(const Task * a, const Task * b) { return *a < *b; }
4da3ee4c9bbc16c4e5258c84127a516beb8e40af
3f301b99e121c1eb2880969fd67df1245a6fd62f
/adlik_serving/runtime/tvm/tvm_model.h
1fa56d87df01e7a0441b82770a3c4f99b5cc15e7
[ "Apache-2.0" ]
permissive
ishine/Adlik
93efcea30f136088600773d3714d93832e18e4ca
fb31f6fb2150e551c582ce4279cf53f9e938a214
refs/heads/master
2021-11-23T11:16:34.137970
2021-11-09T09:08:18
2021-11-09T09:08:18
360,808,128
0
2
Apache-2.0
2021-04-23T08:00:36
2021-04-23T08:00:36
null
UTF-8
C++
false
false
1,184
h
tvm_model.h
// Copyright 2019 ZTE corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #ifndef ADLIK_SERVING_RUNTIME_TVM_TVM_MODEL_H #define ADLIK_SERVING_RUNTIME_TVM_TVM_MODEL_H #include <memory> #include "adlik_serving/framework/domain/model_config.h" #include "adlik_serving/framework/domain/model_id.h" #include "adlik_serving/runtime/batching/batching_model.h" #include "adlik_serving/runtime/batching/composite_batch_processor.h" #include "cub/base/status.h" #include "tensorflow/core/lib/core/status.h" namespace tvm_runtime { struct TvmModel : adlik::serving::BatchingModel, adlik::serving::CompositeBatchProcessor { static cub::Status create(const adlik::serving::ModelConfig&, const adlik::serving::ModelId&, std::unique_ptr<TvmModel>*); private: TvmModel(const adlik::serving::ModelConfig& config, const adlik::serving::ModelId& model_id); TvmModel(TvmModel&&) = delete; TvmModel(const TvmModel&) = delete; cub::Status init(); IMPL_ROLE_NS(adlik::serving, BatchProcessor); adlik::serving::ModelConfig config; adlik::serving::ModelId model_id; }; } // namespace tvm_runtime #endif
63e3e4bd6d8bf1c1d1596249983cccaf5c2b9f38
4c66b4e42b00671e3b74ebb3d361283f69d24ed5
/WS08/Account.h
11bdd1afa8ddd4aef4965f632b3020db0a011dff
[]
no_license
hanyd81/OOP-Workshops
eaea7a6436cf126b2d2f21d1605ac6d6aced0e01
c13ae288cb990d714dde9b1143fc02935a2fd54e
refs/heads/master
2021-01-25T10:07:50.557146
2018-06-11T14:46:59
2018-06-11T14:46:59
123,341,740
0
0
null
2018-02-28T20:59:01
2018-02-28T20:59:00
null
UTF-8
C++
false
false
592
h
Account.h
//Name: Yadong Han //ID: 151799160 //Email: yhan61@myseneca.ca #ifndef SICT_ACCOUNT_H__ #define SICT_ACCOUNT_H__ #include "iAccount.h" namespace sict { class Account:public iAccount { double m_balance; protected: double balance() const; public: // TODO: constructor initializes account balance, defaults to 0.0 Account(double balance = 0.0); // TODO: credit adds +ve amount to the balance virtual bool credit(double add); // TODO: debit subtracts a +ve amount from the balance virtual bool debit(double subtract); }; } #endif
e61a6934f595e6433be9d332da46df1ba25e71e8
03e77dd985f601752afd0c159f1b81f2fe24907d
/app/src/main/cpp/tswriter.cpp
ededc23d3d5ffe973cd194e5a124671af1ea5b5a
[]
no_license
msdgwzhy6/M3u8ForTsWrite
65e18ca7af9286bdac3183f553aaeb646ffe5829
d602dbc300737c08f2f5eaab9a978f62069b140e
refs/heads/master
2020-04-11T02:50:00.614733
2017-03-29T09:47:55
2017-03-29T09:47:55
161,457,913
1
0
null
2018-12-12T08:40:46
2018-12-12T08:40:46
null
UTF-8
C++
false
false
19,615
cpp
tswriter.cpp
// // tswriter.cpp // Main // // Created by dy on 2/10/17. // Copyright © 2017 feitian. All rights reserved. // #include <string> #include <assert.h> #include <string> #include "tswriter.h" static uint8_t flv_mpegts_header[] = { #if 0 /* SDT */ 0x47, 0x40, 0x11, 0x10, 0x00, 0x42, 0xF0, 0x25, 0x00, 0x01, 0xC1, 0x00, 0x00, 0xFF, 0x01, 0xFF, 0x00, 0x01, 0xFC, 0x80, 0x14, 0x48, 0x12, 0x01, 0x06, 0x46, 0x46, 0x6D, 0x70, 0x65, 0x67, 0x09, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x30, 0x31, 0x77, 0x7C, 0x43, 0xCA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, #endif /* PAT */ /* TS */ 0x47, 0x40, 0x00, 0x10, 0x00, /* PSI */ 0x00, 0xb0, 0x0d, 0x00, 0x01, 0xc1, 0x00, 0x00, /* PAT */ 0x00, 0x01, 0xf0, 0x01, /* CRC */ 0x2e, 0x70, 0x19, 0x05, /* stuffing 167 bytes */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* PMT PID == 0x1001 */ /* TS */ 0x47, 0x50, 0x01, 0x10, 0x00, /* PSI */ 0x02, 0xb0, 0x1d, 0x00, 0x01, 0xc1, 0x00, 0x00, /* PMT */ 0xe1, 0x00, 0xf0, 0x00, 0x1b, 0xe1, 0x00, 0xf0, 0x00, /* h264 */ 0x0F, 0xE1, 0x01, 0xF0, 0x06, 0x0A, 0x04, 0x75, 0x6E, 0x64, 0x00, /* aac with lang descriptor from ffmpeg */ /* CRC */ 0x08, 0x7D, 0xE8, 0x77, // from ffmpeg for new aac with land descriptor /* stuffing 151 bytes */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; struct flv_mpegts_frame_t { int64_t pts; int64_t dts; uint32_t pid; uint32_t sid; uint32_t cc; unsigned key; }; struct str_buf_t { uint8_t* pos; uint8_t* last; }; /* 700 ms PCR delay */ #define FLV_HLS_DELAY 45000 static void flv_mpegts_write_header(TSFileBuffer &fileBuffer) { memcpy(fileBuffer.data + fileBuffer.ptr, flv_mpegts_header, sizeof(flv_mpegts_header)); fileBuffer.ptr += sizeof(flv_mpegts_header); } static uint8_t* flv_mpegts_write_pcr(uint8_t *p, int64_t pcr) { int64_t pcr_low = pcr % 300, pcr_high = pcr / 300; *p++ = pcr_high >> 25; *p++ = pcr_high >> 17; *p++ = pcr_high >> 9; *p++ = pcr_high >> 1; *p++ = pcr_high << 7 | pcr_low >> 8 | 0x7e; *p++ = pcr_low; return p; } static uint8_t* flv_mpegts_write_pts(uint8_t *p, uint32_t fb, int64_t pts) { uint32_t val; val = fb << 4 | (((pts >> 30) & 0x07) << 1) | 1; *p++ = (uint8_t) val; val = (((pts >> 15) & 0x7fff) << 1) | 1; *p++ = (uint8_t) (val >> 8); *p++ = (uint8_t) val; val = (((pts) & 0x7fff) << 1) | 1; *p++ = (uint8_t) (val >> 8); *p++ = (uint8_t) val; return p; } int flv_mpegts_write_frame(TSFileBuffer &file, flv_mpegts_frame_t *f, str_buf_t *b, int64_t tsbase) { //printf("flv_mpegts_write_frame pid %d payloadsize %d pts %lld tsbase %lld\n", f->pid, (int)(b->last - b->pos), f->pts, tsbase); f->pts = f->pts - tsbase + FLV_HLS_DELAY * 2; f->dts = f->dts - tsbase + FLV_HLS_DELAY * 2; uint32_t pes_size, header_size, body_size, in_size, stuff_size, flags; uint8_t packet[188], *p, *base; int first = 1; while (b->pos < b->last) { // PAT and MPT must be inserted into ts file per 40 ts packets (copy from ffmpeg) // otherwise, Quictime doesn't work if (file.tspacknum == 40) { flv_mpegts_write_header(file); file.tspacknum = 0; } p = packet; f->cc++; *p++ = 0x47; *p++ = (uint8_t) (f->pid >> 8); if (first) { p[-1] |= 0x40; } *p++ = (uint8_t) f->pid; *p++ = 0x10 | (f->cc & 0x0f); /* payload */ if (first) { if (f->key) { packet[3] |= 0x20; /* adaptation */ *p++ = 7; /* size */ *p++ = 0x50; /* random access + PCR */ // fix this, the file pcr start from 0 !! // printf("writing pcr %lld\n", (f->dts - FLV_HLS_DELAY) * 300); p = flv_mpegts_write_pcr(p, (f->dts - FLV_HLS_DELAY) * 300); // in fact, the pcr can be set to 0 in all time, the only problem will be that VLC can't seek //p = flv_mpegts_write_pcr(p, 0);///jyf? } /* PES header */ *p++ = 0x00; *p++ = 0x00; *p++ = 0x01; *p++ = (uint8_t) f->sid; header_size = 5; flags = 0x80; /* PTS */ if (f->dts != f->pts) { header_size += 5; flags |= 0x40; /* DTS */ } pes_size = (b->last - b->pos) + header_size + 3; if (pes_size > 0xffff || f->pid == 0x100) { pes_size = 0; // pes size == 0 for video stream } *p++ = (uint8_t) (pes_size >> 8); *p++ = (uint8_t) pes_size; *p++ = 0x80; /* H222 */ *p++ = (uint8_t) flags; *p++ = (uint8_t) header_size; p = flv_mpegts_write_pts(p, flags >> 6, f->pts); if (f->dts != f->pts) { p = flv_mpegts_write_pts(p, 1, f->dts); } first = 0; } body_size = (u_int32_t) (packet + sizeof(packet) - p); in_size = (u_int32_t) (b->last - b->pos); if (body_size <= in_size) { memcpy(p, b->pos, body_size); b->pos += body_size; } else { stuff_size = (body_size - in_size); if (packet[3] & 0x20) { /* has adaptation */ base = &packet[5] + packet[4]; p = (u_int8_t*)memmove((void*)(base + stuff_size), (void*)base, p - base); memset(base, 0xff, stuff_size); packet[4] += (uint8_t)stuff_size; } else { /* no adaptation */ packet[3] |= 0x20; int movecnt = (int)(p - &packet[4]); memmove((void*)(&packet[4] + stuff_size), (void*)&packet[4], movecnt); p = packet + 4 + stuff_size + movecnt; packet[4] = (uint8_t) (stuff_size - 1); if (stuff_size >= 2) { packet[5] = 0; memset(&packet[6], 0xff, stuff_size - 2); } } memcpy(p, b->pos, in_size); b->pos = b->last; } // append a ts packet to file memcpy(file.data + file.ptr, packet, sizeof(packet)); file.ptr += sizeof(packet); file.tspacknum++; } return 0; } static int g_count = 0; /////////////////////////////// TSWriter::TSWriter() { memset(&_fileBuffer, 0, sizeof(_fileBuffer)); _sps = _pps = NULL; _spsLength = _ppsLength = 0; _tsAudioNum = _tsVideoNum = 0; _audioCC = _videoCC = 0; _firstTS = _lastTS = 0; _baseTS = -1; _aacCacheTS = 0; _aacCachePtr = 0; pthread_mutex_init(&m_mutex, NULL); pthread_mutex_init(&m_mutex_audio, NULL); g_count ++; // m_file = NULL; // m_264file.clear(); } TSWriter::~TSWriter() { pthread_mutex_destroy(&m_mutex); pthread_mutex_destroy(&m_mutex_audio); // if(m_file){ // fclose(m_file); // m_file = NULL; // } } void TSWriter::AddH264Data(const uint8_t *data, int length, H264FrameType ftype, int64_t ts, TSFileBuffer &tsfile) { pthread_mutex_lock(&m_mutex); memset(&tsfile, 0, sizeof(tsfile)); if (ftype == H264FrameType::SPS || ftype == H264FrameType::PPS) { // save them if (ftype == H264FrameType::SPS) { // assert(_sps == NULL); _sps = new uint8_t[length]; _spsLength = length; memcpy(_sps, data, length); } else { // assert(_pps == NULL); _pps = new uint8_t[length]; _ppsLength = length; memcpy(_pps, data, length); } pthread_mutex_unlock(&m_mutex); return; } if (ftype == H264FrameType::I) { // complete the previous ts file, create the new ts file // if there is audio frames left in cache, flush it to ts file // combine the sps and pps with the first I frame if (_aacCachePtr > 0) { flv_mpegts_frame_t framet; framet.cc = _audioCC; framet.key = 0; framet.dts = (int64_t) _aacCacheTS * 90; // in 90KHz framet.pts = framet.dts; framet.pid = 0x101; framet.sid = 0xc0; str_buf_t buf = { 0 }; buf.pos = (uint8_t*)_aacCache; buf.last = (uint8_t*)_aacCache + _aacCachePtr; flv_mpegts_write_frame(_fileBuffer, &framet, &buf, 0); _audioCC = framet.cc; _aacCachePtr = 0; } // returning the completed ts file content ! tsfile = _fileBuffer; if (tsfile.data != NULL) { tsfile.duration = _lastTS - _firstTS; } // reset for new ts file memset(&_fileBuffer, 0, sizeof(_fileBuffer)); _tsAudioNum = 0; _tsVideoNum = 0; _audioCC = 0; _videoCC = 0; _firstTS = ts; _lastTS = ts; if (_baseTS == -1) { // setting the base timestamp of the whole h264 sequence printf("h264 basets = %lld\n", _firstTS); _baseTS = _firstTS; } } else if (_tsVideoNum == 0) { // ignore the P frames before IDR pthread_mutex_unlock(&m_mutex); return; } _tsVideoNum++; if (ts > _lastTS) { _lastTS = ts; } if (_fileBuffer.data == NULL) { _fileBuffer.data = new uint8_t[1024 * 1024 * 10]; // big enough for testing !! _fileBuffer.size = 1024 * 1024 * 10; _fileBuffer.ptr = 0; _fileBuffer.duration = 0; _fileBuffer.tspacknum = 0; // set PAT and PMT at the beginning of new ts file flv_mpegts_write_header(_fileBuffer); } // must added at the beginning of all h264 frames (09 = Access Unit Delimiter, otherwise QuickTime Player can't play a ts file) const uint8_t audslice[] = { 0x00, 0x00, 0x00, 0x01, 0x09, 0xF0 }; if (ftype == H264FrameType::I) { uint8_t *tmp = new uint8_t[_spsLength + _ppsLength + length + sizeof(audslice)]; memcpy(tmp, audslice, sizeof(audslice)); memcpy(tmp + sizeof(audslice), _sps, _spsLength); memcpy(tmp + sizeof(audslice) + _spsLength, _pps, _ppsLength); memcpy(tmp + sizeof(audslice) + _spsLength + _ppsLength, data, length); length = _spsLength + _ppsLength + length + sizeof(audslice); flv_mpegts_frame_t framet; framet.cc = _videoCC; framet.key = 1; framet.dts = (int64_t) ts * 90; // in 90KHz framet.pts = framet.dts; framet.pid = 0x100; framet.sid = 0xe0; str_buf_t buf = { 0 }; buf.pos = tmp; buf.last = tmp + length; flv_mpegts_write_frame(_fileBuffer, &framet, &buf, 0); _videoCC = framet.cc; delete[] tmp; } else { uint8_t *tmp = new uint8_t[sizeof(audslice) + length]; memcpy(tmp, audslice, sizeof(audslice)); memcpy(tmp + sizeof(audslice), data, length); length = length + sizeof(audslice); flv_mpegts_frame_t framet; framet.cc = _videoCC; framet.key = 0; framet.dts = (int64_t) ts * 90; // in 90KHz framet.pts = framet.dts; framet.pid = 0x100; framet.sid = 0xe0; str_buf_t buf = { 0 }; buf.pos = (uint8_t*)tmp; buf.last = (uint8_t*)tmp + length; flv_mpegts_write_frame(_fileBuffer, &framet, &buf, 0); _videoCC = framet.cc; delete[] tmp; } pthread_mutex_unlock(&m_mutex); } // static int SamplingFrequencyIndex[] = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000 , 7350 , 0 , 0 }; int indexSampleRate(int index) { int size = sizeof(SamplingFrequencyIndex)/sizeof(int); if(index < 0 || index >= size){ return -1; } return SamplingFrequencyIndex[index]; } void TSWriter::AddAACData(unsigned int sampleRate, unsigned int channels, const uint8_t *data, int length, int64_t ts) { pthread_mutex_lock(&m_mutex); // printf("AddAACData length %d, ts %lld\n", length, ts); if (_tsVideoNum == 0) { // printf("aacdata ignored by videonum == 0\n"); pthread_mutex_unlock(&m_mutex); return; // ignore } if (ts <_firstTS) { // printf("aacdata ignored by small firstts\n"); pthread_mutex_unlock(&m_mutex); return; } if (ts > _lastTS) { _lastTS = ts; } // { // int adtsLength = 7; // unsigned int fullLength = adtsLength + length; // // fill in ADTS data // char adtsHead[7] = {0}; // adtsHead[0] = (char)0xFF; // 11111111 = syncword // adtsHead[1] = (char)0xF9; // 1111 1 00 1 = syncword MPEG-2 Layer CRC // adtsHead[2] = (char)(((profile-1)<<6) + (indexSampleRate(sampleRate)<<2) +(channels>>2)); // adtsHead[3] = (char)(((channels&3)<<6) + (fullLength>>11)); // adtsHead[4] = (char)((fullLength&0x7FF) >> 3); // adtsHead[5] = (char)(((fullLength&7)<<5) + 0x1F); // adtsHead[6] = (char)0xFC; // } if (_aacCachePtr == 0) { memcpy(_aacCache, data, length); _aacCachePtr = length; _aacCacheTS = ts; } else { memcpy(_aacCache + _aacCachePtr, data, length); _aacCachePtr += length; if ((ts - _aacCacheTS) * 90 > FLV_HLS_DELAY) { // flush cached audio frames as a PES flv_mpegts_frame_t framet; framet.cc = _audioCC; framet.key = 0; framet.dts = (int64_t) _aacCacheTS * 90; // in 90KHz framet.pts = framet.dts; framet.pid = 0x101; framet.sid = 0xc0; str_buf_t buf = { 0 }; buf.pos = (uint8_t*)_aacCache; buf.last = (uint8_t*)_aacCache + _aacCachePtr; flv_mpegts_write_frame(_fileBuffer, &framet, &buf, 0); _audioCC = framet.cc; _aacCachePtr = 0; _tsAudioNum++; } } pthread_mutex_unlock(&m_mutex); } void TSWriter::Close(TSFileBuffer &filebuffer) { pthread_mutex_lock(&m_mutex); // flush the uncompleted ts file if (_aacCachePtr > 0) { flv_mpegts_frame_t framet; framet.cc = _audioCC; framet.key = 0; framet.dts = (int64_t) _aacCacheTS * 90; // in 90KHz framet.pts = framet.dts; framet.pid = 0x101; framet.sid = 0xc0; str_buf_t buf = { 0 }; buf.pos = (uint8_t*)_aacCache; buf.last = (uint8_t*)_aacCache + _aacCachePtr; flv_mpegts_write_frame(_fileBuffer, &framet, &buf, 0); _audioCC = framet.cc; _aacCachePtr = 0; } if(_sps){ delete [] _sps; _sps = NULL; } _spsLength = 0; if(_pps){ delete [] _pps; _pps = NULL; } _ppsLength = 0; if (_fileBuffer.data != NULL && _fileBuffer.ptr > 0) { _fileBuffer.duration = _lastTS - _firstTS; } filebuffer = _fileBuffer; memset(&_fileBuffer, 0, sizeof(_fileBuffer)); pthread_mutex_unlock(&m_mutex); } //void TSWriter::writeH264File(char * path, const uint8_t *data, int length) //{ // if(m_264file.empty()){ // if(path){ // char temp[200]{0}; // sprintf(temp, "%s/264_%d.264", path, g_count); // m_264file = temp; // } // } // // if(! m_264file.empty()){ // if(m_file == NULL){ // m_file = fopen(m_264file.c_str(), "wb"); // } // } // // if(m_file){ // fwrite(data, 1, length, m_file); // fflush(m_file); // } // // printf("AddH264Data 1111111111"); //} //void TSWriter::closeH264File() //{ // if(m_file){ // fflush(m_file); // fclose(m_file); // m_file = NULL; // } // m_264file.clear(); //}
c2e16a5aac2b88f454eb46ebd54dd1bc20cd17fe
a67837eae91dbf86671be1bba85432554c545e0d
/Practica1/Mapa.h
399dcaed55a7dfaa3a9b20c8f008d51c5934d384
[]
no_license
ignacioperezvelasco/P1_G6_XavierOrtigosa_IgnacioPerez_corregido
c5a7464b1c30a921e39e6b42d12989c4887ddc16
2910453ed247c60aa5d89f4c90c8837c48587e84
refs/heads/master
2021-01-20T08:43:40.107526
2017-05-03T19:33:53
2017-05-03T19:33:53
90,186,224
0
2
null
null
null
null
UTF-8
C++
false
false
246
h
Mapa.h
#pragma once class Mapa { public: //atributos int dificultad; int numRows; int numColumns; char **md; // Mapa(int dificultat); void inicializarmapa(); void printmapa(); void cambiarpunto(int x, int y, char nuevoelemento); ~Mapa(); };
e4923b7718dce1653cde74633bf2bb2154be985a
f6ca330b81adb604d0f709169b8f345c2ac2afe0
/src/Miniseq.cpp
937af9904645b32b70572f853d1a48d98f82e839
[]
no_license
ad-synth/AdSynth-VCV
9b24f8d0b6257cfc59c9000764c85638b61e15ae
599cc9ebb6f73d714d05ac3c5e8ac27107344d22
refs/heads/master
2023-02-10T19:49:49.002227
2023-01-25T13:27:28
2023-01-25T13:27:28
224,710,987
1
0
null
2020-03-17T16:40:11
2019-11-28T18:41:48
C++
UTF-8
C++
false
false
10,214
cpp
Miniseq.cpp
#include "plugin.hpp" struct Adsynth_Miniseq : Module { enum ParamIds { ENUMS(SWITCH_PARAM, 8), ENUMS(KNOB_PARAM, 8), CLOCK_PARAM, DIR_PARAM, STEPS_PARAM, RUN_PARAM, LOOP_PARAM, GATE_PARAM, NUM_PARAMS }; enum InputIds { GATEPW_INPUT, CLOCK_INPUT, RESET_INPUT, RUN_INPUT, MODE_INPUT, NUM_INPUTS }; enum OutputIds { CV_OUTPUT, GATE_OUTPUT, CLOCK_OUTPUT, EOC_OUTPUT, NUM_OUTPUTS }; enum LightIds { ENUMS(LED_LIGHT, 8), ENUMS(ON_LIGHT, 8), ENUMS(MODE_LIGHT, 3), NUM_LIGHTS }; //variables======================================================= bool runState = true, eocCache = false; int index = 0, modeSwitch = 1, direction = 1, seqLength = 8; float outCache = 0, clockPhase = 0.5f; dsp::SchmittTrigger gateInput; dsp::SchmittTrigger resetInput; dsp::SchmittTrigger runInput; dsp::PulseGenerator internalClock, externalClock; dsp::PulseGenerator eocGate, outputGate; //functions======================================================= int voltageToSwitch(float voltage) { int switchValue = 0; voltage = 3 * (voltage + 5.f); if (voltage <= 10.f) switchValue = -1; else if (voltage > 10.f && voltage <= 20.f) switchValue = 0; else if (voltage > 20.f) switchValue = 1; return switchValue; } void resetSequence() { switch (modeSwitch) { case 1: index = 0; direction = 1; break; case 2: index = seqLength - 1; break; case 3: index = 0; direction = 1; break; } //(modeSwitch == 2) ? index = seqLength - 1 : index = 0, direction = 1; } void stopSequence() { runState = false; params[RUN_PARAM].setValue(0.f); resetSequence(); } void muteOuts() { outputGate.reset(); outputs[CV_OUTPUT].setVoltage(0.f); } void setModeLight() { for (int i = 0; i < 3; i++) { lights[MODE_LIGHT + i].setBrightness(0.f); } switch (clamp(modeSwitch, 1, 3)) { case 1: lights[MODE_LIGHT + 0].setBrightness(10.f); break; case 2: lights[MODE_LIGHT + 1].setBrightness(10.f); break; case 3: lights[MODE_LIGHT + 2].setBrightness(10.f); break; default: break; } } void killSeqLights() { for (int i = 0; i < 8; i++) { lights[LED_LIGHT + i].setBrightness(0.f); } } void killActiveLights() { for (int i = 0; i < 8; i++) { lights[ON_LIGHT + i].setBrightness(0.f); } } void setActiveLights (){ for (int i = 0; i < seqLength; i++) { lights[ON_LIGHT + i].setBrightness(1.f); } } //======================================================================= Adsynth_Miniseq() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); for (int i = 0; i < 8; i++) { configParam(SWITCH_PARAM + i, 0.f, 1.f, 0.f, ""); configParam(KNOB_PARAM + i, 0.f, 1.f, 0.f, ""); lights[LED_LIGHT + i].setBrightness(0.f); lights[ON_LIGHT + i].setBrightness(1.f); } configParam(DIR_PARAM, 1.f, 3.f, 1, "1: Forward 2: Backward 3: Pendulum"); configParam(STEPS_PARAM, 2.f, 8.f, 8, "Step Count"); configParam(CLOCK_PARAM, 0.f, 10.f, 5, "Clock Rate"); configParam(RUN_PARAM, 0.f, 1.f, 1.f, "Run"); configParam(LOOP_PARAM, 0.f, 1.f, 1, "Loop / OneShot"); configParam(GATE_PARAM, 0, 1, 1, "Gatelength"); } void process(const ProcessArgs& args) override { float input = 10, //output stage gain for all signals out, gain[8], tempoMod = 0.1, //clock tempo linear modifier clockRate, extClock, trigger, eoc, modeParamValue, gateOut, gateLength = 0.1, //in seconds, init value only gatePW = params[GATE_PARAM].getValue(); bool pendulum, switchState, runInValue, runButtonValue, reset, loop, pulse; //fetch parameters; reset = resetInput.process(inputs[RESET_INPUT].getVoltage()); loop = params[LOOP_PARAM].getValue(); seqLength = std::round(params[STEPS_PARAM].getValue()); runButtonValue = params[RUN_PARAM].getValue(); runInValue = runInput.process(inputs[RUN_INPUT].getVoltage()); runState = runButtonValue || runInValue; modeSwitch = std::round(params[DIR_PARAM].getValue()); if (inputs[MODE_INPUT].isConnected()) { modeParamValue = inputs[MODE_INPUT].getVoltage(); modeSwitch += voltageToSwitch(modeParamValue); } else modeParamValue = 0; //lights init setModeLight(); killActiveLights(); setActiveLights(); //generate internal clock signal clockRate = tempoMod * std::pow(2.f, params[CLOCK_PARAM].getValue()); clockPhase += clockRate * args.sampleTime; if (clockPhase >= 0.5f) { internalClock.trigger(1e-6f); externalClock.trigger(1e-3f); clockPhase -= 1.f; } extClock = externalClock.process(args.sampleTime); pulse = internalClock.process(args.sampleTime); if (inputs[GATEPW_INPUT].isConnected()) { gatePW += inputs[GATEPW_INPUT].getVoltage() / input; } gateLength = gatePW / clockRate; //choosing clock source if (inputs[CLOCK_INPUT].isConnected()) { trigger = gateInput.process(inputs[CLOCK_INPUT].getVoltage()); outputs[CLOCK_OUTPUT].setVoltage(inputs[CLOCK_INPUT].getVoltage()); gateLength = 8; // if external clock is connected - max gatetime equals fixed 8 sec // (bypasses gate param, sets permanent legato mode) // todo: gatelength for ext clx } else { trigger = pulse ? 10.f : 0.f; outputs[CLOCK_OUTPUT].setVoltage(extClock); } runState += clampSafe(inputs[RUN_INPUT].getVoltage(), 0.f, 10.f); runState ? params[RUN_PARAM].setValue(10.f) : params[RUN_PARAM].setValue(0.f); //button light on/off if (reset) resetSequence(); //check direction switch (modeSwitch) { case 1: direction = 1; pendulum = false; break; case 2: direction = -1; pendulum = false; break; case 3: pendulum = true; break; default: direction = 1; pendulum = false; break; } if (trigger && eocCache) { muteOuts(); eocCache = 0; } if (trigger && runState) { killSeqLights(); //process row switchState = params[SWITCH_PARAM + index].getValue(); gain[index] = params[KNOB_PARAM + index].getValue(); if (switchState) { outCache = gain[index]; outputGate.trigger(gateLength); } else { outputGate.reset(); } out = input * outCache; outputs[CV_OUTPUT].setVoltage(out); lights[LED_LIGHT + index].setSmoothBrightness(1.f, 5e3); index += direction; } eoc = eocGate.process(args.sampleTime) * 10.f; outputs[EOC_OUTPUT].setVoltage(eoc); gateOut = input * outputGate.process(args.sampleTime); outputs[GATE_OUTPUT].setVoltage(gateOut); //one shot or loop if (!loop && eoc) { stopSequence(); eocCache++; } //check if on edge of sequence if (pendulum) { if (index <= 0 && direction == -1) direction = 1, eocGate.trigger(1e-3f); if (index >= seqLength - 1 && direction == 1) direction = -1; } else { if (index < 0) resetSequence(), eocGate.trigger(5e-3f); if (index > seqLength-1) resetSequence(), eocGate.trigger(5e-3f); } } }; struct Adsynth_MiniseqWidget : ModuleWidget { Adsynth_MiniseqWidget(Adsynth_Miniseq* module) { setModule(module); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Miniseq.svg"))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); const int jackTop = 97, jackBot = 109; for (int i = 0; i < 8; i++) { const float mult = 9.5; addParam(createParamCentered<AdsynthSmallKnob>(mm2px(Vec(17, 18 + i * mult)), module, Adsynth_Miniseq::KNOB_PARAM + i)); addParam(createParamCentered<AdsynthGreenSeqButton>(mm2px(Vec(8, 18 + i * mult)), module, Adsynth_Miniseq::SWITCH_PARAM + i)); addChild(createLightCentered<SmallLight<RedLight>>(mm2px(Vec(23, 16 + i * mult)), module, Adsynth_Miniseq::LED_LIGHT + i)); addChild(createLightCentered<SmallLight<GreenLight>>(mm2px(Vec(23, 20 + i * mult)), module, Adsynth_Miniseq::ON_LIGHT + i)); } addParam(createParamCentered<AdsynthBigKnobRed>(mm2px(Vec(37.8, 22)), module, Adsynth_Miniseq::CLOCK_PARAM)); addParam(createParamCentered<AdsynthSmallSnapKnob>(mm2px(Vec(41.8, 47)), module, Adsynth_Miniseq::STEPS_PARAM)); addParam(createParamCentered<AdsynthKnobSmallTeal>(mm2px(Vec(32.8, 35)), module, Adsynth_Miniseq::GATE_PARAM)); addParam(createParamCentered<AdsynthSmallTriKnob>(mm2px(Vec(37, 70.5)), module, Adsynth_Miniseq::DIR_PARAM)); addChild(createLightCentered<SmallLight<GreenLight>>(mm2px(Vec(32, 62.5)), module, Adsynth_Miniseq::MODE_LIGHT + 0)); addChild(createLightCentered<SmallLight<GreenLight>>(mm2px(Vec(37, 59.5)), module, Adsynth_Miniseq::MODE_LIGHT + 1)); addChild(createLightCentered<SmallLight<GreenLight>>(mm2px(Vec(42, 62.5)), module, Adsynth_Miniseq::MODE_LIGHT + 2)); addParam(createParamCentered<AdsynthGreenSeqButton>(mm2px(Vec(31.8, 82.5)), module, Adsynth_Miniseq::RUN_PARAM)); addParam(createParamCentered<AdsynthGreenSeqButton>(mm2px(Vec(42.8, 82.5)), module, Adsynth_Miniseq::LOOP_PARAM)); addInput(createInputCentered<AdsynthJackTeal>(mm2px(Vec(31.8, 44.5)), module, Adsynth_Miniseq::GATEPW_INPUT)); addInput(createInputCentered<AdsynthJack>(mm2px(Vec(8, jackTop)), module, Adsynth_Miniseq::CLOCK_INPUT)); addInput(createInputCentered<AdsynthJack>(mm2px(Vec(8, jackBot)), module, Adsynth_Miniseq::RUN_INPUT)); addInput(createInputCentered<AdsynthJack>(mm2px(Vec(19, jackTop)), module, Adsynth_Miniseq::RESET_INPUT)); addInput(createInputCentered<AdsynthJack>(mm2px(Vec(19, jackBot)), module, Adsynth_Miniseq::MODE_INPUT)); addOutput(createOutputCentered<AdsynthJack>(mm2px(Vec(31.8, jackTop)), module, Adsynth_Miniseq::CLOCK_OUTPUT)); addOutput(createOutputCentered<AdsynthJack>(mm2px(Vec(31.8, jackBot)), module, Adsynth_Miniseq::EOC_OUTPUT)); addOutput(createOutputCentered<AdsynthJack>(mm2px(Vec(42.8, jackTop)), module, Adsynth_Miniseq::CV_OUTPUT)); addOutput(createOutputCentered<AdsynthJack>(mm2px(Vec(42.8, jackBot)), module, Adsynth_Miniseq::GATE_OUTPUT)); } }; Model* modelAdsynth_Miniseq = createModel<Adsynth_Miniseq, Adsynth_MiniseqWidget>("Adsynth_Miniseq");
e14e8ee08d47a4fb49570889474ef0871a527578
4fcf2967da46f37c831b72b7b97f705d3364306d
/problems/acmicpc_24499.cpp
03d1014956b7dde645bb1ce71063981ee77b3ba8
[ "MIT" ]
permissive
qawbecrdtey/BOJ-sol
e2be11e60c3c19e88439665d586cb69234f2e5db
249b988225a8b4f52d27c5f526d7c8d3f4de557c
refs/heads/master
2023-08-03T15:04:50.837332
2023-07-30T08:25:58
2023-07-30T08:25:58
205,078,469
0
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
acmicpc_24499.cpp
#include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int k, n; cin >> n >> k; auto a = new int[n << 1]; for(int i = 0; i < n; i++) { cin >> a[i]; a[i + n] = a[i]; } int res = 0, sum = 0; for(int i = 0; i < k; i++) { sum += a[i]; } res = sum; for(int i = k; i < n + k; i++) { sum += a[i] - a[i - k]; if(res < sum) res = sum; } cout << res; }
d5cf19459993aaa2bf80b20d6950c363a64d0e42
a9a7d3131e73b79d2e4ecb527f9502303f1023ea
/src/Hermes/DownstreamSerializer.cpp
c359bea8dbb433be0e438709e3a165dbd6e13207
[]
no_license
emilemesselken/ASM_Hermes
8dc811d95c090ee791330d3aa19d129c533d6178
fbd49032aceb69fd42cbfd132c05da63fc5e1424
refs/heads/master
2021-08-24T01:22:42.428278
2017-12-07T12:27:56
2017-12-07T12:27:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,676
cpp
DownstreamSerializer.cpp
#include "stdafx.h" #include "DownstreamSerializer.h" #include "Network.h" #include "IService.h" #include "Serializer.h" #include "StringBuilder.h" namespace Hermes { namespace Downstream { struct Serializer : Downstream::ISerializer, ISocketCallback { unsigned m_sessionId; IAsioService& m_service; IServerSocket& m_socket; ISerializerCallback* m_pCallback = nullptr; std::string m_receiveBuffer; Serializer(unsigned sessionId, IAsioService& service, IServerSocket& socket) : m_sessionId(sessionId), m_service(service), m_socket(socket) {} // ISocketCallback void OnConnected(const ConnectionInfo& connectionInfo) override { m_pCallback->OnSocketConnected(connectionInfo); } void OnReceived(StringView dataView) override { m_receiveBuffer.append(dataView.data(), dataView.size()); m_service.Log(m_sessionId, "m_receiveBuffer[", dataView.size(), "]=", m_receiveBuffer); std::string messageXml; while (TakeMessage(messageXml, m_receiveBuffer)) { m_service.Log(m_sessionId, "messageXml[", messageXml.size(), "]=", messageXml, "\nm_receiveBuffer[", m_receiveBuffer.size(), "]=", m_receiveBuffer); const auto& variant = Deserialize(messageXml); if (const auto* pData = boost::get<Error>(&variant)) { auto error = m_service.Alarm(m_sessionId, EErrorCode::ePEER_ERROR, pData->m_text); Signal(NotificationData(ENotificationCode::ePROTOCOL_ERROR, ESeverity::eFATAL, error.m_text)); m_socket.Close(); m_pCallback->OnDisconnected(error); return; } if (const auto* pData = boost::get<CheckAliveData>(&variant)) { m_service.Log(m_sessionId, "CheckAliveData=", *pData); m_pCallback->On(*pData); continue; } if (const auto* pData = boost::get<ServiceDescription>(&variant)) { m_service.Log(m_sessionId, "ServiceDescription=", *pData); m_pCallback->On(*pData); continue; } if (const auto* pData = boost::get<NotificationData>(&variant)) { m_service.Log(m_sessionId, "NotificationData=", *pData); m_pCallback->On(*pData); continue; } if (const auto* pData = boost::get<MachineReadyData>(&variant)) { m_service.Log(m_sessionId, "MachineReadyData=", *pData); m_pCallback->On(*pData); continue; } if (const auto* pData = boost::get<RevokeMachineReadyData>(&variant)) { m_service.Log(m_sessionId, "RevokeMachineReadyData=", *pData); m_pCallback->On(*pData); continue; } if (const auto* pData = boost::get<StartTransportData>(&variant)) { m_service.Log(m_sessionId, "StartTransportData=", *pData); m_pCallback->On(*pData); continue; } if (const auto* pData = boost::get<StopTransportData>(&variant)) { m_service.Log(m_sessionId, "StopTransportData=", *pData); m_pCallback->On(*pData); continue; } m_service.Warn(m_sessionId, "Unexpected message"); } if (m_receiveBuffer.size() <= cMAX_MESSAGE_SIZE) return; auto error = m_service.Alarm(m_sessionId, EErrorCode::ePEER_ERROR, "Maximum message size exceeded"); Signal(NotificationData(ENotificationCode::ePROTOCOL_ERROR, ESeverity::eFATAL, error.m_text)); m_socket.Close(); m_pCallback->OnDisconnected(error); } void OnDisconnected(const Error& error) override { m_pCallback->OnDisconnected(error); } //============== Downstream::ISerializer ================================ void Connect(std::weak_ptr<void> wpOwner, ISerializerCallback& callback) override { assert(!m_pCallback); m_pCallback = &callback; m_socket.Connect(wpOwner, *this); } void Signal(const ServiceDescription& data) override { const auto& xmlString = Serialize(data); Send_(xmlString); } void Signal(const BoardAvailableData& data) override { const auto& xmlString = Serialize(data); Send_(xmlString); } void Signal(const RevokeBoardAvailableData& data) override { const auto& xmlString = Serialize(data); Send_(xmlString); } void Signal(const TransportFinishedData& data) override { const auto& xmlString = Serialize(data); Send_(xmlString); } void Signal(const NotificationData& data) override { const auto& xmlString = Serialize(data); Send_(xmlString); } void Signal(const CheckAliveData& data) override { const auto& xmlString = Serialize(data); Send_(xmlString); } void Disconnect() override { m_socket.Close(); } void Send_(StringView message) { m_socket.Send(message); } }; } using namespace Downstream; std::unique_ptr<ISerializer> Downstream::CreateSerializer(unsigned sessionId, IAsioService& service, IServerSocket& socket) { return std::make_unique<Serializer>(sessionId, service, socket); } }
b6de5c35fcb37d7148e4ade5ad7b7175befdd9eb
91684991bc6ffbe3e4c117fc5064e72dc2d2dea4
/MainSocket.cpp
5504a21f6ff37c76f322aec9ac6755bd80a72e71
[]
no_license
Soraruholic/ReliableUdp_Client
36a5bedd770350ca9abbdd96a47144e89738ba85
b69ba89d847ffd738aee5e5f355c74375b952c14
refs/heads/master
2023-04-18T21:36:20.492205
2017-02-19T12:17:34
2017-02-19T12:17:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,139
cpp
MainSocket.cpp
// // Created by ahmed on 12/16/16. // #include <cstring> #include "MainSocket.h" #include "client_config.h" #include <ProtocolDef.h> MainSocket::MainSocket(const string &server_addr, const unsigned short server_port) { server_info = unique_ptr<AddressInfo>(new AddressInfo(server_addr, server_port)); this->server_addr = string(server_addr); this->socket = unique_ptr<RawUdpSocket>(new RawUdpSocket(*this->server_info)); this->socket->SetReceiveTimeout(RCV_TIMEO_SEC, RCV_TIMEO_USEC); this->socket->SetSendTimeout(RCV_TIMEO_SEC, RCV_TIMEO_USEC); } int MainSocket::InitFileRequest(string &handshake) { this->socket->SendStringPacket(*this->server_info, handshake, ID_HNDSHK_CLNT); string temp; int seqno = this->socket->ReceiveStringPacket(temp); if (seqno != ID_GO_REDIRECT) { string err("Bad protocol message "); err.append(to_string(seqno)); throw std::runtime_error(err); } temp.replace(0, strlen(GO_REDIRECT_SRV), ""); cout << "Redirect port:" << temp << endl; return (stoi(temp)); } MainSocket::~MainSocket() { this->socket->~RawUdpSocket(); }