blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
af06acc3e3ee35936dda296c03225e1baca80c0c
6208713c56549bcb4895203cb033c31eb2e06a17
/xmlparser.h
ad52d1db4a75badfac14d1ce402b4748cc1e3cfe
[]
no_license
thehilmisu/LogParser
f99bb82e452b7583935d2b97bdc8b0c44fb540c1
5f19558b983ede405bcacf05c7bd55e03470df32
refs/heads/master
2022-10-01T06:18:17.008971
2022-09-21T13:15:41
2022-09-21T13:15:41
269,301,787
0
0
null
null
null
null
UTF-8
C++
false
false
577
h
#ifndef XMLPARSER_H #define XMLPARSER_H #include <QObject> #include <QStringList> #include <QXmlStreamReader> #include <QDebug> #include <QColor> #include <QFile> struct Arguments { QColor color; QString argument; }; class xmlparser { public: xmlparser(QString path); ~xmlparser(); QStringList extractSearchTerms( QString path, QVector< QPair<int, int> > &argumentListType ); QStringList getOccuranceCount(); private: QString xmlPath; QList<Arguments> args; QStringList counts; }; #endif // XMLPARSER_H
[ "ozcanhakanzi@gmail.com" ]
ozcanhakanzi@gmail.com
5e53c15bb66d38784d58a4fb48e61146e26ec42f
bf007dec921b84d205bffd2527e376bb60424f4c
/Codeforces_Submissions/991D.cpp
e25e15417fbf30701d8b7f9878166fbd4f0ef9e6
[]
no_license
Suvrojyoti/APS-2020
257e4a94f52f5fe8adcac1ba4038cc66e81d9d26
d4de0ef098e7ce9bb40036ef55616fa1f159f7a5
refs/heads/master
2020-12-21T19:27:59.955338
2020-04-22T13:27:49
2020-04-22T13:27:49
236,534,218
0
0
null
null
null
null
UTF-8
C++
false
false
1,424
cpp
#include <bits/stdc++.h> using namespace std; int main() { char l[105],arr[2][105]; int i,c=0,k=0; cin>>l; arr[0][0]='X'; arr[1][0]='X'; for(i=0;l[i]!='\0';i++) { arr[0][i+1]=l[i]; k++; } arr[0][k+1]='X'; arr[1][k+1]='X'; cin>>l; for(i=1;i<=k;i++) { arr[1][i]=l[i-1]; } for(i=1;i<=k;i++) { if(arr[0][i]=='0'&&arr[1][i]=='0'&&arr[1][i+1]=='0') { arr[0][i]='X'; arr[1][i]='X'; arr[1][i+1]='X'; c++; //cout<<i; } else if(arr[0][i]=='0'&&arr[1][i]=='0'&&arr[1][i-1]=='0') { arr[0][i]='X'; arr[1][i]='X'; arr[1][i-1]='X'; c++; //cout<<i; } else if(arr[0][i]=='0'&&arr[0][i+1]=='0'&&arr[1][i]=='0') { c++; arr[0][i]='X'; arr[1][i+1]='X'; arr[1][i]='X'; //cout<<i; } else if(arr[0][i]=='0'&&arr[0][i+1]=='0'&&arr[1][i+1]=='0') { arr[0][i]='X'; c++; arr[1][i+1]='X'; arr[0][i+1]='X'; //cout<<i; } // cout<<" "; } /*for(i=1;i<=k;i++) { cout<<arr[0][i]; } cout<<"\n"; for(i=1;i<=k;i++) { cout<<arr[1][i]; }*/ cout<<c; return 0; }
[ "suvrojyoti.mandal@theatom.app" ]
suvrojyoti.mandal@theatom.app
b88e849b512c25e3c4b8992d3374babe3d82564f
8d9b36b08c510841d469f9d78ffc13e74967bdfc
/Rocket/Engine/Render/DrawSubPass/GeometrySubPass.cpp
76a108c75a90ff306388e0b2695d7eafaecf255f
[]
no_license
rocketman123456/RocketArticle
8b0e621eb2a05a274a9f6bd87355ae41d667384f
f7b354badb35266190b0011d146856b78f784c74
refs/heads/main
2023-05-06T16:30:20.842480
2021-02-27T15:26:56
2021-02-27T15:26:56
319,081,322
0
0
null
2021-02-27T15:24:13
2020-12-06T16:42:36
C++
UTF-8
C++
false
false
543
cpp
#include "Render/DrawSubPass/GeometrySubPass.h" #include "Module/PipelineStateManager.h" #include "Module/GraphicsManager.h" using namespace Rocket; void GeometrySubPass::Draw(Frame& frame) { auto& pPipelineState = g_PipelineStateManager->GetPipelineState("PBR"); // Set the color shader as the current shader program and set the matrices // that it will use for rendering. g_GraphicsManager->SetPipelineState(pPipelineState, frame); //g_GraphicsManager->SetShadowMaps(frame); g_GraphicsManager->DrawBatch(frame); }
[ "759094438@qq.com" ]
759094438@qq.com
4abd42ef9d16ec2161e7d2d0637d8e0faaf1dc54
5e1afd243b9972138591b43149dc9dbb3a017879
/Content/C++/graph/bipartite/DynamicBipartiteDivAndConq.h
66ff6f15d1005e3fc08ffe174c62db57bea689cf
[]
no_license
pidddgy/Resources
47bfd6fe019a3c59ac8468bb04c114b4e4679e07
624b2fcde28abe035cf7b54087c839bdabc623f8
refs/heads/master
2022-12-28T15:31:41.243316
2020-09-30T05:38:07
2020-09-30T05:38:07
300,311,262
0
0
null
2020-10-01T14:35:43
2020-10-01T14:35:42
null
UTF-8
C++
false
false
4,823
h
#pragma once #include <bits/stdc++.h> #include "SemiDynamicBipartiteUndo.h" using namespace std; // Support queries on connected components and bipartiteness, after edges // have been added or removed, using divide and conquer // Constructor Arguments: // V: the number of vertices in the graph // Fields: // ans: a vector of integers with the answer for // each query (1 is true, 0 is false for boolean queries) // Functions: // addEdge(v, w): adds an edge between vertices v and w // removeEdge(v, w): removes an edge between vertices v and w, assuming // an edge exists // addConnectedQuery(v, w): adds a query asking whether v and w are in the // same connected component // addSizeQuery(v): adds a query asking for the number of vertices in the // same connected component as vertex v // addCntQuery(): adds a query asking for the number of connected components // addComponentBipartiteQuery(v): adds a query asking for whether the // connected component containing vertex v is bipartite // addBipartiteGraphQuery(): adds a query asking if the graph is bipartite // addColorQuery(v): adds a query asking for the color of vertex v for one // possible coloring of the graph, assuming the component is bipartite // addPathParity(v, w): adds a query asking for the parity of the path from // v to w (false if even number of edges, true if odd), assuming the // component is bipartite and v and w are connected // solveQueries(): solves all queries asked so far // In practice, has a small constant // Time Complexity: // constructor: O(V) // addEdge, removeEdge, addConnectedQuery, addSizeQuery, addCntQuery: O(1) // addComponentBipartiteQuery, addBipartiteGraphQuery: O(1) // addColorQuery, addPathParity: O(1) // solveQueries: O(V + Q log Q log V) // Memory Complexity: O(V + Q) for Q edge additions/removals and queries // Tested: // https://codeforces.com/contest/813/problem/F struct DynamicBipartiteDivAndConq { int V; vector<tuple<int, int, int, int>> queries; vector<int> ans; DynamicBipartiteDivAndConq(int V) : V(V) {} void addEdge(int v, int w) { if (v > w) swap(v, w); queries.emplace_back(0, v, w, -1); } void removeEdge(int v, int w) { if (v > w) swap(v, w); queries.emplace_back(1, v, w, -1); } void addConnectedQuery(int v, int w) { queries.emplace_back(2, v, w, queries.size()); } void addSizeQuery(int v) { queries.emplace_back(3, v, v, queries.size()); } void addCntQuery() { queries.emplace_back(4, -1, -1, queries.size()); } void addComponentBipartiteQuery(int v) { queries.emplace_back(5, v, v, queries.size()); } void addBipartiteGraphQuery() { queries.emplace_back(6, -1, -1, queries.size()); } void addColorQuery(int v) { queries.emplace_back(7, v, v, queries.size()); } void addPathParityQuery(int v, int w) { queries.emplace_back(8, v, w, queries.size()); } void solveQueries() { vector<pair<int, int>> edges; int Q = queries.size(); edges.reserve(Q); for (auto &&q : queries) if (get<0>(q) == 0) edges.emplace_back(get<1>(q), get<2>(q)); sort(edges.begin(), edges.end()); vector<int> last(edges.size(), INT_MAX); for (int i = 0; i < Q; i++) { int t, v, w, _; tie(t, v, w, _) = queries[i]; if (t == 0) { int j = lower_bound(edges.begin(), edges.end(), make_pair(v, w)) - edges.begin(); get<3>(queries[i]) = last[j]; last[j] = i; } else if (t == 1) { int j = lower_bound(edges.begin(), edges.end(), make_pair(v, w)) - edges.begin(); int temp = get<3>(queries[get<3>(queries[i]) = last[j]]); get<3>(queries[last[j]]) = i; last[j] = temp; } } SemiDynamicBipartiteUndo uf(V); ans.clear(); ans.reserve(Q); function<void(int, int)> dc = [&] (int l, int r) { if (l == r) { int t, v, w, _; tie(t, v, w, _) = queries[l]; if (t == 2) ans.push_back(uf.connected(v, w)); else if (t == 3) ans.push_back(uf.getSize(v)); else if (t == 4) ans.push_back(uf.cnt); else if (t == 5) ans.push_back(uf.componentBipartite(v)); else if (t == 6) ans.push_back(uf.bipartiteGraph); else if (t == 7) ans.push_back(uf.color(v)); else if (t == 8) ans.push_back(uf.pathParity(v, w)); return; } int m = l + (r - l) / 2, curSize = uf.history.size(); for (int i = m + 1; i <= r; i++) if (get<3>(queries[i]) < l) uf.addEdge(get<1>(queries[i]), get<2>(queries[i])); dc(l, m); while (int(uf.history.size()) > curSize) uf.undo(); for (int i = l; i <= m; i++) if (get<3>(queries[i]) > r) uf.addEdge(get<1>(queries[i]), get<2>(queries[i])); dc(m + 1, r); while (int(uf.history.size()) > curSize) uf.undo(); }; if (Q > 0) dc(0, Q - 1); } };
[ "wesley.a.leung@gmail.com" ]
wesley.a.leung@gmail.com
f208fd13fa6516ce12658a7f1932979a82d84d4d
cccfb7be281ca89f8682c144eac0d5d5559b2deb
/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer.cc
3ce9b13688f63c31794d0f73590b2b3fde8c1d0f
[ "BSD-3-Clause" ]
permissive
SREERAGI18/chromium
172b23d07568a4e3873983bf49b37adc92453dd0
fd8a8914ca0183f0add65ae55f04e287543c7d4a
refs/heads/master
2023-08-27T17:45:48.928019
2021-11-11T22:24:28
2021-11-11T22:24:28
428,659,250
1
0
BSD-3-Clause
2021-11-16T13:08:14
2021-11-16T13:08:14
null
UTF-8
C++
false
false
5,703
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_context_menu/accessibility_labels_menu_observer.h" #include <utility> #include "base/bind.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/accessibility/accessibility_labels_service.h" #include "chrome/browser/accessibility/accessibility_labels_service_factory.h" #include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_context_menu/accessibility_labels_bubble_model.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" #include "chrome/browser/ui/confirm_bubble.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/rect.h" using content::BrowserThread; AccessibilityLabelsMenuObserver::AccessibilityLabelsMenuObserver( RenderViewContextMenuProxy* proxy) : proxy_(proxy) {} AccessibilityLabelsMenuObserver::~AccessibilityLabelsMenuObserver() {} void AccessibilityLabelsMenuObserver::InitMenu( const content::ContextMenuParams& params) { Profile* profile = Profile::FromBrowserContext(proxy_->GetBrowserContext()); if (ShouldShowLabelsItem()) { proxy_->AddAccessibilityLabelsServiceItem(profile->GetPrefs()->GetBoolean( prefs::kAccessibilityImageLabelsEnabled)); } } bool AccessibilityLabelsMenuObserver::IsCommandIdSupported(int command_id) { return command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_TOGGLE || command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS || command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_TOGGLE_ONCE; } bool AccessibilityLabelsMenuObserver::IsCommandIdChecked(int command_id) { DCHECK(IsCommandIdSupported(command_id)); Profile* profile = Profile::FromBrowserContext(proxy_->GetBrowserContext()); if (command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_TOGGLE || command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS || command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_TOGGLE_ONCE) { return profile->GetPrefs()->GetBoolean( prefs::kAccessibilityImageLabelsEnabled); } return false; } bool AccessibilityLabelsMenuObserver::IsCommandIdEnabled(int command_id) { DCHECK(IsCommandIdSupported(command_id)); if (command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_TOGGLE || command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS || command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_TOGGLE_ONCE) { return ShouldShowLabelsItem(); } return false; } void AccessibilityLabelsMenuObserver::ExecuteCommand(int command_id) { DCHECK(IsCommandIdSupported(command_id)); Profile* profile = Profile::FromBrowserContext(proxy_->GetBrowserContext()); if (command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_TOGGLE) { // When a user enables the accessibility labeling item, we // show a bubble to confirm it. On the other hand, when a user disables this // item, we directly update/ the profile and stop integrating the labels // service immediately. if (!profile->GetPrefs()->GetBoolean( prefs::kAccessibilityImageLabelsEnabled)) { // Always show the confirm bubble when enabling the full feature, // regardless of whether it's been shown before. ShowConfirmBubble(profile, true /* enable always */); } else { profile->GetPrefs()->SetBoolean(prefs::kAccessibilityImageLabelsEnabled, false); } } else if (command_id == IDC_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_TOGGLE_ONCE) { // Only show the confirm bubble if it's never been shown before. if (!profile->GetPrefs()->GetBoolean( prefs::kAccessibilityImageLabelsOptInAccepted)) { ShowConfirmBubble(profile, false /* enable once only */); } else { AccessibilityLabelsServiceFactory::GetForProfile(profile) ->EnableLabelsServiceOnce(); } } } bool AccessibilityLabelsMenuObserver::ShouldShowLabelsItem() { // Disabled by policy. Profile* profile = Profile::FromBrowserContext(proxy_->GetBrowserContext()); if (!profile->GetPrefs()->GetBoolean( prefs::kAccessibilityImageLabelsEnabled) && profile->GetPrefs()->IsManagedPreference( prefs::kAccessibilityImageLabelsEnabled)) { return false; } return accessibility_state_utils::IsScreenReaderEnabled(); } void AccessibilityLabelsMenuObserver::ShowConfirmBubble(Profile* profile, bool enable_always) { content::WebContents* web_contents = proxy_->GetWebContents(); content::RenderWidgetHostView* view = proxy_->GetRenderViewHost()->GetWidget()->GetView(); gfx::Rect rect = view->GetViewBounds(); auto model = std::make_unique<AccessibilityLabelsBubbleModel>( profile, web_contents, enable_always); chrome::ShowConfirmBubble( web_contents->GetTopLevelNativeWindow(), view->GetNativeView(), gfx::Point(rect.CenterPoint().x(), rect.y()), std::move(model)); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2a8f8a9d6037ca6d1b55c1e7dfb2d50684e6b0df
267d544589f973693eb3c47b5aa4e28158f65217
/Love Meter/p03_LoveOMeter/p03_LoveOMeter.ino
b1d0d671c02ecb4eb1154fa1eac551ff3132a4c6
[]
no_license
BrandonKirklen/EE-322
095cc54707aab5b90ce4afc21ca6fceccd19cf8a
18f2c4f3e28d250d259850fdfac41451aadafe92
refs/heads/master
2021-01-13T01:00:06.951730
2016-01-20T13:08:57
2016-01-20T13:08:57
43,038,282
0
0
null
null
null
null
UTF-8
C++
false
false
2,227
ino
// named constant for the pin the sensor is connected to const int sensorPin = A0; // room temperature in Celcius const float baselineTemp = 28.0; bool print = false; void setup() { // open a serial connection to display values Serial.begin(9600); pinMode(1, INPUT); // set the LED pins as outputs // the for() loop saves some extra coding // for (int pinNumber = 8; pinNumber <= 10; pinNumber++) { // pinMode(pinNumber, OUTPUT); // digitalWrite(pinNumber, LOW); // } } void loop() { // read the value on AnalogIn pin 0 // and store it in a variable int sensorVal = analogRead(sensorPin); int ledRed = 10; int ledYellow = 9; int ledGreen = 8; int switchState = 0; switchState = digitalRead(1); float voltage = (sensorVal / 1024.0) * 5.0; if( switchState == HIGH ){ print = !print; } if( print ){ Serial.print("Sensor Value: "); Serial.print(sensorVal); Serial.print(", Volts: "); Serial.print(voltage); } // convert the voltage to temperature in degrees C // the sensor changes 10 mV per degree // the datasheet says there's a 500 mV offset // ((volatge - 500mV) times 100) // Serial.print(", degrees C: "); // float temperature = (voltage - .5) * 100; // Serial.println(temperature); // if the current temperature is lower than the baseline // turn off all LEDs // if (temperature < baselineTemp + 2) { // digitalWrite(ledRed, LOW); // digitalWrite(ledYellow, LOW); // digitalWrite(ledGreen, LOW); // } // if the temperature rises 2-4 degrees, turn an LED on // else if (temperature >= baselineTemp + 2 && temperature < baselineTemp + 4) { // digitalWrite(ledRed, HIGH); // digitalWrite(ledYellow, LOW); // digitalWrite(ledGreen, LOW); // } // if the temperature rises 4-6 degrees, turn a second LED on // else if (temperature >= baselineTemp + 4 && temperature < baselineTemp + 6) { // digitalWrite(ledRed, HIGH); // digitalWrite(ledYellow, HIGH); // digitalWrite(ledGreen, LOW); // } // if the temperature rises more than 6 degrees, turn all LEDs on // else if (temperature >= baselineTemp + 6) { // digitalWrite(ledRed, HIGH); // digitalWrite(ledYellow, HIGH); // digitalWrite(ledGreen, HIGH); // } delay(1); }
[ "brandonkirklen@gmail.com" ]
brandonkirklen@gmail.com
4a3468141a2f0feb2baefe6ccb7623adb9897ae2
b109be1f005e7ae523bb979dbaac265d7c96a072
/src/CyclicSubsetSeed.hh
bd5aecf7a04420af2252745213cae71a87b5fab4
[]
no_license
hallamlab/LAST-Plus
5a00036f1e842178347f1f2a15c86c742c705aa7
cb9306ead29074efd9b8bac11c8ec85884a63a94
refs/heads/master
2021-01-24T14:18:31.337340
2016-11-27T04:11:23
2016-11-27T04:11:23
38,019,621
23
6
null
2015-06-25T01:01:15
2015-06-25T01:01:15
null
UTF-8
C++
false
false
3,845
hh
// Copyright 2009, 2010, 2013, 2014 Martin C. Frith // A "subset seed" covers a range of sequence. The size of this range // is called its span. At each position, it maps letters (encoded as // numbers) to subsets of the letters (encoded as numbers). The // mapping may or may not be different at different positions. // Subset seeds are described in: // G Kucherov et al. J Bioinform Comput Biol. 2006 4(2):553-69. // "Cyclic" means that the seed can cover arbitrary-size ranges, by // cyclically repeating. // The INPUT/OUTPUT FORMAT looks like this: // A C G T // AG CT // ACGT // Each line represents one position, and each letter-group (separated // by whitespace) is one subset. In each position, any letters not // specified will get mapped to the special DELIMITER subset. Blank // lines and comment lines starting with # are ignored. // The input format is always case-insensitive. If the // isMaskLowercase argument of the reading routines is true, then all // lowercase letters will get mapped to the DELIMITER subset, // otherwise they will be treated like their uppercase equivalents. #ifndef CYCLIC_SUBSET_SEED_HH #define CYCLIC_SUBSET_SEED_HH #include <string> #include <vector> #include <iosfwd> namespace cbrc{ typedef unsigned char uchar; class CyclicSubsetSeed{ public: enum { MAX_LETTERS = 64 }; enum { DELIMITER = 255 }; // This converts a seed name to a set of strings in the I/O format. // If the name isn't known, it assumes it's a file and tries to read it. static std::vector<std::string> fromName( const std::string& name ); // This converts a mask to a set of strings in the I/O format. // The mask is something like: "1110TT,1001T1". The "1"s are // must-match positions, the "0"s are don't care positions, and "T" // or "t" allows transitions but not transversions. For consistency // with YASS/Iedera, you can also use "#" for match, "@" for // transition, and "_" or "-" for don't care. You can have multiple // seed patterns separated by commas, which get returned as separate // strings. The alph indicates the letters that can occur in "1" // and "0" positions. static std::vector<std::string> fromMask( const std::string& alph, const std::string& mask ); // This is a more general version, where seedAlph maps mask // characters to lines in the I/O format. static std::vector<std::string> fromMask( const char* seedAlph[], const std::string& mask ); void clear() { subsetLists.clear(); subsetMaps.clear(); } void fromString( const std::string& s, bool isMaskLowercase, const uchar letterCode[] ); void fromStream( std::istream& stream, bool isMaskLowercase, const uchar letterCode[] ); void appendPosition( std::istream& inputLine, bool isMaskLowercase, const uchar letterCode[] ); void writePosition( std::ostream& out, unsigned position ) const; unsigned span() const{ return subsetLists.size(); } const uchar* subsetMap( unsigned depth ) const{ return &subsetMaps[0] + (depth % span()) * MAX_LETTERS; } unsigned subsetCount( unsigned depth ) const{ return subsetLists[ depth % span() ].size(); } const uchar* firstMap() const{ return &subsetMaps[0]; } /* const uchar* nextMap( const uchar* x ) const{ const uchar* y = x + MAX_LETTERS; if( y == &subsetMaps[0] + subsetMaps.size() ) y = &subsetMaps[0]; return y; } */ const uchar* nextMap( const uchar* x ) const{ if( x == &subsetMaps[0] + subsetMaps.size() ) { return &subsetMaps[0]; } else { return x; } } private: std::vector< std::vector<std::string> > subsetLists; std::vector<uchar> subsetMaps; static void addLetter( std::vector<uchar>& numbersToSubsets, uchar letter, uchar subsetNum, const uchar letterCode[] ); }; } // end namespace #endif
[ "david.kim9325@gmail.com" ]
david.kim9325@gmail.com
b614eb5bdeac6dc26e9100cfcd598d21c4d2627a
165bd4c2d8e94f9b230c5321f1d5854214e63824
/TAP/AllPrimeSums/main.cpp
43e9b5d55beef3dae333c342425f035e0d2e5450
[]
no_license
alexandru-balan/Facultate
d09c57ce2c07b50c4a4ce281de62d9c7de30ebf4
506cc6ce2e31e9f1967fd81ea233d1333e60d6c6
refs/heads/master
2023-03-11T07:56:51.716573
2020-01-15T09:01:42
2020-01-15T09:01:42
163,764,490
1
0
null
2023-03-03T08:13:36
2019-01-01T20:30:29
JavaScript
UTF-8
C++
false
false
1,806
cpp
#include <iostream> #include <vector> #include <numeric> using namespace std; bool isPrimeNumber (int x) { bool prime = true; if (x == 2) { return true; } for (int i = 2; i <= x/2; ++i) { if (x % i == 0) { prime = false; break; } } return prime; } int findBiggerPrime (int x) { // equal is a flag value if (x == 2) { return 3; } for (int i = x+1; i < INT_MAX; ++i) { if (isPrimeNumber(i)) { return i; } } } void bktSumPrimes (int &sum, int x, vector<int> primes) { if (sum > x) { sum -= primes.back(); primes.pop_back(); // no more elements => Terminate if (primes.empty()) { return; } // incrementing the last element sum -= primes.back(); int num = primes.back(); primes.pop_back(); primes.push_back(findBiggerPrime(num)); sum += primes.back(); bktSumPrimes(sum, x, primes); } else if (sum < x) { sum += primes.back(); primes.push_back(primes.back()); bktSumPrimes(sum, x, primes); } else { for (auto i : primes) { cout << i << " "; } cout << endl; sum -= primes.back(); primes.pop_back(); if (primes.empty()) { return; } // incrementing the last element sum -= primes.back(); int num = primes.back(); primes.pop_back(); primes.push_back(findBiggerPrime(num)); sum += primes.back(); bktSumPrimes(sum, x, primes); } } int main() { bool found = false; int sum = 2; vector<int> primes; primes.push_back(2); bktSumPrimes(sum, 10, primes); return 0; }
[ "balan.alexandru1997@tutanota.com" ]
balan.alexandru1997@tutanota.com
32f626299c77fa2deb5d31ff952707ebf4a3dfad
7e5be101928eb7ea43bc1a335d3475536f8a5bb2
/2016 Training/8.7/G.cpp
1cf46307e7de27bfa11f0406df151306bf3b2a78
[]
no_license
TaoSama/ICPC-Code-Library
f94d4df0786a8a1c175da02de0a3033f9bd103ec
ec80ec66a94a5ea1d560c54fe08be0ecfcfc025e
refs/heads/master
2020-04-04T06:19:21.023777
2018-11-05T18:22:32
2018-11-05T18:22:32
54,618,194
0
2
null
null
null
null
UTF-8
C++
false
false
1,531
cpp
// // Created by TaoSama on 2016-08-07 // Copyright (c) 2016 TaoSama. All rights reserved. // #pragma comment(linker, "/STACK:102400000,102400000") #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <string> #include <set> #include <vector> using namespace std; #define pr(x) cout << #x << " = " << x << " " #define prln(x) cout << #x << " = " << x << endl const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7; typedef long long LL; map<LL, LL> f; LL s, k; LL get(int k, int n) { if(n < k) return 0; if(n == k) return 1; if(f.count(n)) return f[n]; LL& ret = f[n]; ret = 0; for(int i = n - 1; i >= max(k, n - k); --i) ret += get(k, i); return ret; } int main() { #ifdef LOCAL freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin); // freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout); #endif ios_base::sync_with_stdio(0); cin >> s >> k; vector<int> v; for(int i = k - 1; ; ++i) { LL cur = get(k, i); v.push_back(cur); if(cur > 1e9) break; } vector<int> ans; int sum = 0; for(int i = v.size() - 1; ~i; --i) { if(sum + v[i] > s) continue; sum += v[i]; ans.push_back(v[i]); } printf("%d\n", ans.size()); for(int i = 0; i < ans.size(); ++i) printf("%d%c", ans[i], " \n"[i == ans.size() - 1]); return 0; }
[ "lwt1367@gmail.com" ]
lwt1367@gmail.com
3a05f257389daceacf6e77fbb604053f57cfe8fe
8078ebbb3a2270e6c32c881392e2c4b915021944
/src/Game-Engine-Design/Label.h
6499d167f126d3feb3a145068146eec12933b85d
[ "Apache-2.0" ]
permissive
bsc-william-taylor/game-engine-design
4c456fafa5b2a649ce29ebb074c9ea3177dab0e6
80550dd0e5bdf1daf9825f66b619c07c5d0d9abc
refs/heads/master
2021-06-21T00:46:19.375355
2017-05-02T03:37:55
2017-05-02T03:37:55
79,837,538
1
0
null
null
null
null
UTF-8
C++
false
false
356
h
#pragma once #include "Main.h" #include "Object.h" class Label : public Object { private: TTF_Font * font; string textFile; GLuint textureID; bool dontDelete; public: Label(); ~Label(); void textToTexture(string); void setText(string, int); void setFont(TTF_Font *); TTF_Font * getFont(); GLuint getID(); };
[ "wi11berto@yahoo.co.uk" ]
wi11berto@yahoo.co.uk
6d9f83a9aa6e9f6d5f2db40ee85b541de6a56c09
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtdeclarative/src/qml/debugger/qqmldebugstatesdelegate_p.h
16bf4824cad030d6ed4ff62ea22af925ea2f8329
[ "LGPL-2.0-or-later", "LGPL-2.1-only", "LGPL-3.0-only", "GPL-1.0-or-later", "GPL-3.0-only", "Qt-LGPL-exception-1.1", "LGPL-2.1-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GFDL-1.3-only", "LicenseRef-scancode-digia-qt-preview", "LicenseRef-scancode-warranty-discl...
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
3,220
h
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QQMLDEBUGSTATESDELEGATE_P_H #define QQMLDEBUGSTATESDELEGATE_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtQml/qtqmlglobal.h> #include <QtCore/QList> #include <QtCore/QPointer> QT_BEGIN_NAMESPACE class QQmlContext; class QQmlProperty; class QObject; class QString; class QVariant; class QQmlDebugStatesDelegate { protected: QQmlDebugStatesDelegate() {} public: virtual ~QQmlDebugStatesDelegate() {} virtual void buildStatesList(bool cleanList, const QList<QPointer<QObject> > &instances) = 0; virtual void updateBinding(QQmlContext *context, const QQmlProperty &property, const QVariant &expression, bool isLiteralValue, const QString &fileName, int line, int column, bool *inBaseState) = 0; virtual bool setBindingForInvalidProperty(QObject *object, const QString &propertyName, const QVariant &expression, bool isLiteralValue) = 0; virtual void resetBindingForInvalidProperty(QObject *object, const QString &propertyName) = 0; private: Q_DISABLE_COPY(QQmlDebugStatesDelegate) }; QT_END_NAMESPACE #endif // QQMLDEBUGSTATESDELEGATE_P_H
[ "p_pavlov@wargaming.net" ]
p_pavlov@wargaming.net
ef00d35c8676cc64fb66cd12bbbeb48fd8e2e3f4
290952d106627de07fc2c9581665e7c560ab18bd
/Geeks For Geeks/Greedy/Untitled9.cpp
c723a6ec2e46cb5093cd2c5294683f99ee13b99d
[]
no_license
MdAbuNafeeIbnaZahid/Competitive-Programming
8669db792d3d604ee09429378da52d238b0e5b13
5b8f4f0c08c62ac410fdf153b3c4bd19775411b1
refs/heads/master
2021-01-20T07:57:04.742595
2018-09-25T15:29:32
2018-09-25T15:29:32
83,894,136
4
0
null
null
null
null
UTF-8
C++
false
false
252
cpp
#include <bits/stdc++.h> using namespace std; char str[100]; int i; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); gets(str); cin >> i; cout << str << endl; cout << i << endl; return 0; }
[ "1305023.maniz@ugrad.cse.buet.ac.bd" ]
1305023.maniz@ugrad.cse.buet.ac.bd
2b46bff05bab1c37a26dad19c5748bbea138b64c
8bb26f9ebd122829a84f3d288108b2e181a0a4ca
/Branch/ShellMode/Alpha001/Source/GameServer/Classes/MyServerDlg.cpp
3a4ed9858e609c73a031f98771c07f5e24675148
[]
no_license
continuedc/BaseServer
ef4cc645817056da050f473047ae5cf66e92918a
47225ae9818d3863e2c48e047651c5af9204b14c
refs/heads/master
2021-08-23T14:13:40.828956
2015-09-11T10:19:10
2015-09-11T10:19:10
null
0
0
null
null
null
null
GB18030
C++
false
false
19,711
cpp
// MyServerDlg.cpp : 实现文件 // #include "stdafx.h" #include "MyServer.h" #include "MyServerDlg.h" #include "afxdialogex.h" #include "version.h" #include "../share/define.h" #include "../share/protocol.h" #include "../Common/IniFile.h" #include "../Common/logfile.h" #include "../../../Include/CrashRpt.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 全局变量保存服务器名和线路 char g_szServerName[64] = ""; int g_nServerGroup = 0; int g_nServerLine = 0; //////////////////////////////////////////////////////////////////////// // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg() : CDialog(CAboutDlg::IDD) {} enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 protected: DECLARE_MESSAGE_MAP() }; void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() //////////////////////////////////////////////////////////////////////// BOOL WINAPI MyCrashProc(PEXCEPTION_POINTERS Exception) { COleDateTime dt=COleDateTime::GetCurrentTime(); CString strCrashFileName; CString temp=dt.Format("GameServer_%Y年%m月%d日%H时%M分%S秒"); strCrashFileName.Format("./dump/%s_%lu", temp, ::GetTickCount()); CString strDumpFile = strCrashFileName + ".dmp"; CString strReportFile = strCrashFileName + ".xml"; // 生成错误时系统快照 // GenerateCrashRpt(Exception, strReportFile, CRASHRPT_ERROR|CRASHRPT_SYSTEM|CRASHRPT_PROCESS); GenerateCrashRpt(Exception, strReportFile, CRASHRPT_ALL); // 生成minidump.dmp,这个可以用vc或者windbg打开分析 GenerateMiniDump(Exception, strDumpFile); return EXCEPTION_EXECUTE_HANDLER; } // CMyServerDlg 对话框 CMyServerDlg::CMyServerDlg(CWnd* pParent /*=NULL*/) : CDialog(CMyServerDlg::IDD, pParent) , m_pMsgPort(NULL) , m_eState(SHELL_STATUS_FAILD) , m_nTextLines(0) , m_sShellState(_T("")) , m_sText(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMyServerDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_STC_STATUS, m_sShellState); DDX_Text(pDX, IDC_STC_TIPS, m_sText); } HBRUSH CMyServerDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if (IDC_STC_MANAGER == pWnd->GetDlgCtrlID()) { pDC->SetTextColor(RGB(0, 0, 255)); } return hbr; } BEGIN_MESSAGE_MAP(CMyServerDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_TIMER() ON_WM_QUERYDRAGICON() ON_WM_CTLCOLOR() ON_BN_CLICKED(IDC_BTN_NOTIFY, &CMyServerDlg::OnBnClickedBtnnotify) ON_BN_CLICKED(IDC_BTN_RESTART, &CMyServerDlg::OnBnClickedBtnRestart) ON_BN_CLICKED(IDC_BTN_CLOSE, &CMyServerDlg::OnBnClickedBtnClose) ON_BN_CLICKED(IDC_CHK_LUA, &CMyServerDlg::OnBnClickedChkLua) ON_BN_CLICKED(IDC_CHK_GM, &CMyServerDlg::OnBnClickedChkGm) ON_BN_CLICKED(IDC_CHK_GMTOOL, &CMyServerDlg::OnBnClickedChkGmtool) ON_BN_CLICKED(IDC_BTN_UPDATE_LUA, &CMyServerDlg::OnBnClickedBtnUpdateLua) ON_BN_CLICKED(IDC_BTN_UPDATE_TABLE, &CMyServerDlg::OnBnClickedBtnUpdateTable) END_MESSAGE_MAP() // CMyServerDlg 消息处理程序 BOOL CMyServerDlg::OnInitDialog() { CDialog::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); // 初始化系统菜单相关 CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } // 关闭系统菜单“关闭”按钮功能 pSysMenu->EnableMenuItem(SC_CLOSE, MF_BYCOMMAND | MF_GRAYED); } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 // 设置进程优先级类(高于标准) SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); #ifdef _DEBUG // 调试模式检测内存块泄露 //_CrtSetBreakAlloc(3753); #endif // 初始化服务器名和线路号 CIniFile ini(GAMESERVER_FILENAME, "System" ); ini.GetString(g_szServerName, "ServerName", sizeof(g_szServerName)); g_nServerGroup = ini.GetInt("ServerGroup"); g_nServerLine = ini.GetInt("ServerLine"); // 设置服务器程序标题 CString strTitle; strTitle.Format(GAMESERVER_TITLE, g_szServerName, g_nServerGroup, g_nServerLine, ::GetCurrentProcessId(), VER_SERVER_SVN_VISION); SetWindowText(strTitle); // 初始化日志系统 CreateDirectory(LOGFILE_DIR, NULL); //CreateDirectory(DBLOGFILE_DIR, NULL); //CreateDirectory(GMLOG_DIR, NULL); InitLog(strTitle, time(NULL)); wchar_t szUnicodeTitle[1024]; char szUtf8Title[1024] = ""; CHECKB(::MyANSIToUnicode(strTitle.GetBuffer(0), szUnicodeTitle, sizeof(szUnicodeTitle) / sizeof(szUnicodeTitle[0]))); CHECKB(::MyUnicodeToUTF8(szUnicodeTitle, szUtf8Title, sizeof(szUtf8Title) / sizeof(szUtf8Title[0]))); ::LogSave( "\n\n===================================================================================================\n" "=== %s \n" "===================================================================================================\t\t\t" , szUtf8Title); // 初始化打印堆栈系统 ::InitSymEngine(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. // -------------------------------------------------------------------- // ::SetUnhandledExceptionFilter(MyUnhandledExceptionFilter); // 初始化CrashRpt.dll异常捕获库 InitializeCrashRptEx(MyCrashProc); // 设置服务器权限和SVN版本信息 SetDlgItemText(IDC_STC_SVN, VER_SERVER_SVN_URL); ini.SetSection("Service" ); char szManagerName[32] = ""; ini.GetString(szManagerName, "Manager", sizeof(szManagerName)); char szManagerCall[16] = ""; ini.GetString(szManagerCall, "Call", sizeof(szManagerCall)); CString stManager; stManager.Format("Mr:%s - Call:%s", szManagerName, szManagerCall); SetDlgItemText(IDC_STC_MANAGER, stManager); // 初始化对话框线程管道 if(!CMessagePort::InitPortSet(MSGPORT_SIZE)) { MessageBox("Init Message Port Failed!"); } else { m_pMsgPort = CMessagePort::GetInterface(MSGPORT_SHELL); m_pMsgPort->Open(); m_eState = SHELL_STATUS_INIT; } // 初始化数据 // srand( (unsigned)time( NULL ) ); // RandGet(100, true); DateTime(m_szStartServerTime, time(NULL)); // 设置定时器。句柄为1,刷新间隔为500MS SetTimer(1, 500, NULL); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CMyServerDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CMyServerDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CMyServerDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMyServerDlg::OnTimer(UINT nIDEvent) { DEBUG_TRY; //!!! Can't use 'return' in this block // TODO: Add your message handler code here and/or call default static bool bOnTimer = true; if(1 == nIDEvent && bOnTimer) { bOnTimer = false; // 处理线程管道消息 if(m_pMsgPort) { this->ProcessMsg(); } // 检测服务器状态 switch (m_eState) { case SHELL_STATUS_FAILD: { m_eState = SHELL_STATUS_END; } break; case SHELL_STATUS_INIT: { // 若初始化失败直接退出 m_eState = SHELL_STATUS_CLOSING; // 1.启动日志线程 this->PrintText("1. Start Log thread..."); CLogThread::GetInstance()->StartLogServe(); // 2.启动堆栈引擎 this->PrintText("2. Start SymEngine"); STACK_TRACE_START; // 3.启动网络线程 this->PrintText("3. Start Socket Thread..."); // 4.初始化数据库 this->PrintText("4. Init DataBase..."); // 5.启动登陆线程 this->PrintText("5. Start Login Thread..."); // 6.启动游戏线程 this->PrintText("6. Start Game Thread..."); // 7.启动关系线程 this->PrintText("7. Start Relation Thread..."); // 8.启动守护进程 this->PrintText("8. Start Seiya..."); m_dwSeiyaPID = StartSeiya(); PrintText("All thread start OK !"); m_eState = SHELL_STATUS_RUNNING; } break; case SHELL_STATUS_RUNNING: { // 服务器性能监视 if (m_tState.ToNextTime(PERFORMANCE_STATISTICS_ONTIMER_SECOND)) { UpdateData(TRUE); int nAllPlayers = CPerformanceStatistics::GetInstance()->GetData(PERFORMANCE_STATISTICS_TYPE_NOW_TOTAL_USER_AMOUNT); int nMaxPlayers = CPerformanceStatistics::GetInstance()->GetData(PERFORMANCE_STATISTICS_TYPE_MAX_TOTAL_USER_AMOUNT); char szCurrentDateTime[20] = ""; ::DateTime(szCurrentDateTime, time(NULL)); //char szPlayersBuff[64] = ""; //sprintf(szPlayersBuff, "NowPlayer[%04d], MaxPlayer[%04d]", nAllPlayers, nMaxPlayers); //CMemMonitor::GetInstance()->OnTimerMonitor(szPlayersBuff); CPerformanceStatistics::GetInstance()->OnTimer(); //m_sShellState.Format("Start Time: %s Current Time: %s\n%s", m_szStartServerTime, szCurrentDateTime, CPerformanceStatistics::GetInstance()->GetLogBuffer()); m_sShellState.Format("Start Time: %s Current Time: %s\n", m_szStartServerTime, szCurrentDateTime); UpdateData(FALSE); } // dead loop extern long g_nMessagePortErrorCount; if (g_nMessagePortErrorCount > 0 && g_nMessagePortErrorCount % 50000 == 0) { InterlockedExchange(&g_nMessagePortErrorCount, 0); this->PrintText("Message pipe block, Server may be slowly!!!"); } } break; case SHELL_STATUS_CLOSING_KICK: { static int nCount = 0; nCount++; // 3次心跳后退出 if (nCount > 3) { m_eState = SHELL_STATUS_CLOSING; } } break; case SHELL_STATUS_CLOSING: { // 服务器开始关闭 this->PrintText("Server closing..."); // 关闭日志线程 if (CLogThread::GetInstance()->CloseLogServe()) { this->PrintText("Close Log Thread OK!"); } else { this->PrintText("Close Log Thread failed!"); } // 关闭守护进程 this->PrintText("Close Seiya..."); this->CloseSeiya(m_dwSeiyaPID); // 关闭网络线程 this->PrintText("Close Socket Thread OK!"); // 关闭关系线程 this->PrintText("Close Relation Thread OK!"); // 关闭游戏线程 this->PrintText("Close Game Thread OK!"); // 关闭登陆线程 this->PrintText("Close Login Thread OK!"); this->PrintText("Server is over, close all after 3 second!"); this->ProcessMsg(); m_pMsgPort->Close(); CMessagePort::ClearPortSet(); m_pMsgPort = NULL; m_eState = SHELL_STATUS_END; } break; case SHELL_STATUS_END: { // 关闭ONTIMER KillTimer(1); // 关闭数据库 //CloseDatabaseServer(); // 延迟3秒 Sleep(3000); // 析构打印堆栈系统 ::ReleaseSymEngine(); // 退出程序 CDialog::OnOK(); } break; default: ASSERT(!"switch(m_eState)"); } bOnTimer = true; } CDialog::OnTimer(nIDEvent); DEBUG_CATCH("CMyServerDlg::OnTimer"); } void CMyServerDlg::ProcessMsg() { char buf[MAX_MESSAGESIZE]; CMessageStatus cStatus; DEBUG_TRY; while(m_pMsgPort->Recv(PORT_ANY, PACKET_ANY, STRUCT_TYPE(buf), buf, &cStatus)) { switch (cStatus.m_nPacket) { case SHELL_PRINTTEXT: { this->PrintText((char*)buf); } break; case SHELL_REMOTE_CLOSE: { this->PrintText("Remote Close"); this->CloseServer(); } break; default: tolog2("CMsgServerDlg::ProcessMsg unkonw idPacket[%u]", cStatus.m_nPacket); this->PrintText("ERROR: CMsgServerDlg::Process() ProcessMsg()"); break; } } DEBUG_CATCH("CMsgServerDlg::Process()") } void CMyServerDlg::PrintText(const char* pszText) { DEBUG_TRY; CHECK(pszText); if(m_nTextLines >= WINDOW_TEXT_SIZE) { int nPos = m_sText.Find("\n", 0); if(nPos != -1) m_sText = m_sText.Mid(nPos + 1); } // 字符串截断, 不至于换行 char szMsgBuff[96] = ""; ::SafeCopy(szMsgBuff, pszText, sizeof(szMsgBuff)); char szBuf[20] = ""; DateTime(szBuf); m_sText += szBuf+11; m_sText += "["; m_sText += szMsgBuff; m_sText += "]"; m_sText += "\r\n"; m_nTextLines++; UpdateData(FALSE); // debug版本不用记录日志 #ifndef _DEBUG ::LogSave("SHELL: %s", pszText); #endif DEBUG_CATCH("CMsgServerDlg::PrintText"); } DWORD CMyServerDlg::StartSeiya() { #ifndef SEIYA_RUN return 0; #endif const DWORD MAX_FILE_PATH_LEN = 1024; const DWORD MAX_FILE_NAME_LEN = 256; const char SEIYA_NAME[] = "Seiya.exe"; char CreateOrder[MAX_FILE_PATH_LEN] = {0}; char CurFloder[MAX_FILE_PATH_LEN] = {0}; char exePath[MAX_FILE_PATH_LEN] = {0}; char szFile[MAX_FILE_NAME_LEN] = {0}; // 获取本程序的文件名 ::GetModuleFileName(NULL, exePath, MAX_FILE_PATH_LEN); for(int nIndex = strlen(exePath) - 1; nIndex >= 0; nIndex--) { if (exePath[nIndex] == '\\' || exePath[nIndex] == '/') { if ((strlen(exePath) - nIndex - 1) > MAX_FILE_NAME_LEN) // 如果文件名超过了最大文件名长度 { LOGWARNING("StartupSeiya::the FileName is too Long [%d]", strlen(exePath) - nIndex - 1); return 0; } strcpy(szFile, exePath + nIndex + 1); break; } } // 获取进程启动指令 ::GetCurrentDirectory(MAX_FILE_PATH_LEN,CurFloder); int nFloderLen = strlen(CurFloder); if (nFloderLen <= 0) // 获取当前路径异常 { LOGWARNING("StartupSeiya::Get Work Path is Failed"); return 0; } if (CurFloder[nFloderLen - 1] == '/' || CurFloder[nFloderLen - 1] == '\\') { sprintf(CreateOrder,"%s%s %s %d",CurFloder, SEIYA_NAME, szFile, ::GetCurrentProcessId()); // 盘符根目录 } else { sprintf(CreateOrder,"%s\\%s %s %d",CurFloder, SEIYA_NAME, szFile, ::GetCurrentProcessId()); } // 进程信息 STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); // 创建守护进程 if(CreateProcess(NULL, CreateOrder, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { // 脱离父进程成为独立进程 DWORD dwPID = pi.dwProcessId; CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CString szOldTitle; CString szNewTitle; GetWindowText(szOldTitle); szNewTitle.Format("%s Seiya[%d]", szOldTitle.GetBuffer(), dwPID); SetWindowText(szNewTitle); return dwPID; } LOGWARNING("StartupSeiya::Create Seiya Process Failed"); return 0; } void CMyServerDlg::CloseSeiya(DWORD dwPID) { #ifndef SEIYA_RUN return; #endif if (0 == dwPID) { LOGWARNING("ShutdownSeiya::the Seiya is not Exist"); return; } HANDLE hProcess; hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwPID); if (hProcess == NULL) { DWORD dwErrNum = ::GetLastError(); LOGWARNING("ShutdownSeiya::the Seiya[%d] OpenProcess is Failed[%d]",dwPID, dwErrNum); return; } // 关闭进程 ::TerminateProcess(hProcess,0); } void CMyServerDlg::CloseServer() { this->PrintText("Kick All User..."); //SOCKET_ID idSocket = SOCKET_NONE; //m_pMsgPort->Send(MSGPORT_LOGIN, LOGINTHREAD_CLOSE_ENTRANCE, VARTYPE_INT, &idSocket); //m_pMsgPort->Send(MSGPORT_GAME, GAMETHREAD_KICK_ALLUSER, VARTYPE_INT, &idSocket); //m_pMsgPort->Send(MSGPORT_SOCKET, SOCKETTHREAD_BREAKALLCONNECT, VARTYPE_INT, &idSocket); // 实质性处理 m_eState = SHELL_STATUS_CLOSING_KICK; } void CMyServerDlg::InitCtrlLuaView() { auto plistBoxLua = (CListBox*)GetDlgItem(IDC_LIST_UPDATE_LUA); plistBoxLua->AddString(_T("Lua: login")); plistBoxLua->AddString(_T("Lua: liveness")); plistBoxLua->AddString(_T("Lua: box")); } void CMyServerDlg::InitCtrlTableView() { auto plistBoxTable = (CListBox*)GetDlgItem(IDC_LIST_UPDATE_TABLE); plistBoxTable->AddString(_T("Table: config")); plistBoxTable->AddString(_T("Table: server_list")); plistBoxTable->AddString(_T("Table: config_txt")); } void CMyServerDlg::OnBnClickedBtnnotify() { // TODO: 在此添加控件通知处理程序代码 int i = 1; i = 3; } void CMyServerDlg::OnBnClickedBtnRestart() { // TODO: 在此添加控件通知处理程序代码 int i = 1; i = 3; } void CMyServerDlg::OnBnClickedBtnClose() { // TODO: 在此添加控件通知处理程序代码 // 提示对话框 this->PrintText("Close Button pressed!"); if (IDCANCEL == this->MessageBox("确认要关闭服务器吗?\n正确无误请点[确定]", "关闭服务器" , MB_ICONEXCLAMATION | MB_OKCANCEL)) { return; } this->PrintText("Server closing..."); this->CloseServer(); } void CMyServerDlg::OnBnClickedChkLua() { // TODO: 在此添加控件通知处理程序代码 if (BST_UNCHECKED != this->IsDlgButtonChecked(IDC_CHK_LUA)) { int i = 1; i = 3; } else { } } void CMyServerDlg::OnBnClickedChkGm() { // TODO: 在此添加控件通知处理程序代码 if (BST_UNCHECKED != ((CButton *)GetDlgItem(IDC_CHK_GM))->GetCheck()) { int i = 1; i = 3; } else { } } void CMyServerDlg::OnBnClickedChkGmtool() { // TODO: 在此添加控件通知处理程序代码 } void CMyServerDlg::OnBnClickedBtnUpdateLua() { // TODO: 在此添加控件通知处理程序代码 auto pListBoxLua = (CListBox*)GetDlgItem(IDC_LIST_UPDATE_LUA); if (pListBoxLua->GetSelCount() > 0) { // 通知更新 } else { // 全部选中 for (int i = 0; i < pListBoxLua->GetCount(); i++) { pListBoxLua->SetSel(i); } } } void CMyServerDlg::OnBnClickedBtnUpdateTable() { // TODO: 在此添加控件通知处理程序代码 auto pListBoxTable = (CListBox*)GetDlgItem(IDC_LIST_UPDATE_TABLE); if (pListBoxTable->GetSelCount() > 0) { // 通知更新 } else { // 全部选中 for (int i = 0; i < pListBoxTable->GetCount(); i++) { pListBoxTable->SetSel(i); } } }
[ "c913421043@b7d7a4be-286e-455e-978f-175bf5e4c3c4" ]
c913421043@b7d7a4be-286e-455e-978f-175bf5e4c3c4
f0ed50cfcb090bb2dca11c12a0a19dfca21882f5
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-connect/source/model/UpdateContactFlowModuleContentRequest.cpp
5f6d57111f4716b08a99b457c108347bc02821ef
[ "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
785
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/connect/model/UpdateContactFlowModuleContentRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Connect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateContactFlowModuleContentRequest::UpdateContactFlowModuleContentRequest() : m_instanceIdHasBeenSet(false), m_contactFlowModuleIdHasBeenSet(false), m_contentHasBeenSet(false) { } Aws::String UpdateContactFlowModuleContentRequest::SerializePayload() const { JsonValue payload; if(m_contentHasBeenSet) { payload.WithString("Content", m_content); } return payload.View().WriteReadable(); }
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
edd4d6db335ea7abe27e75af91d20d8a25c499e9
07cda1295da0370c630697701df0fc5e3e45ca28
/chrome/browser/ui/toolbar/component_toolbar_actions_factory.cc
c96b7653f08003673fc5a42a0a7f8e43568ccc16
[ "BSD-3-Clause" ]
permissive
anawhj/chromium-crosswalk
8221f9510bfb9df29dab12e6cdc57030380eb3f5
97959a5c98a1e18513f3ea21697323634d2fd696
refs/heads/master
2021-01-24T17:23:55.447032
2015-08-11T23:14:52
2015-08-11T23:14:52
40,750,463
0
1
null
2015-08-15T07:18:53
2015-08-15T07:18:52
null
UTF-8
C++
false
false
2,263
cc
// Copyright 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. #include "chrome/browser/ui/toolbar/component_toolbar_actions_factory.h" #include "base/lazy_instance.h" #include "chrome/browser/ui/toolbar/media_router_action.h" #include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h" #include "extensions/common/feature_switch.h" namespace { ComponentToolbarActionsFactory* testing_factory_ = nullptr; base::LazyInstance<ComponentToolbarActionsFactory> lazy_factory = LAZY_INSTANCE_INITIALIZER; } // namespace ComponentToolbarActionsFactory::ComponentToolbarActionsFactory() : num_component_actions_(-1), media_router_ui_enabled_(false) {} ComponentToolbarActionsFactory::~ComponentToolbarActionsFactory() {} // static ComponentToolbarActionsFactory* ComponentToolbarActionsFactory::GetInstance() { return testing_factory_ ? testing_factory_ : &lazy_factory.Get(); } ScopedVector<ToolbarActionViewController> ComponentToolbarActionsFactory::GetComponentToolbarActions() { ScopedVector<ToolbarActionViewController> component_actions; // This is currently behind the extension-action-redesign flag, as it is // designed for the new toolbar. if (!extensions::FeatureSwitch::extension_action_redesign()->IsEnabled()) return component_actions.Pass(); // Add component toolbar actions here. // This current design means that the ComponentToolbarActionsFactory is aware // of all actions. Since we should *not* have an excessive amount of these // (since each will have an action in the toolbar or overflow menu), this // should be okay. If this changes, we should rethink this design to have, // e.g., RegisterChromeAction(). if (media_router_ui_enabled_) component_actions.push_back(new MediaRouterAction()); return component_actions.Pass(); } int ComponentToolbarActionsFactory::GetNumComponentActions() { if (num_component_actions_ == -1) num_component_actions_ = GetComponentToolbarActions().size(); return num_component_actions_; } // static void ComponentToolbarActionsFactory::SetTestingFactory( ComponentToolbarActionsFactory* factory) { testing_factory_ = factory; }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
582b32f14f9506ba551bffccd373b4b6bfc2878d
4f1d319133a467466a99c5197b519f73fd73e1f1
/src/mame/includes/gijoe.h
7011134a1d0d5b1b788e7a43e786bdd7d8d10938
[]
no_license
AltimorTASDK/shmupmametgm
5da401800c7c435b1c3a5a927ba5bc15a6e056cd
2911e3cf43d04a3d1587a48a63352c42647cc9e6
refs/heads/master
2021-01-13T00:50:22.251435
2015-12-13T18:16:27
2015-12-13T18:16:27
47,025,375
3
3
null
2017-02-05T01:09:53
2015-11-28T13:55:58
C
UTF-8
C++
false
false
1,199
h
/************************************************************************* GI Joe *************************************************************************/ class gijoe_state { public: static void *alloc(running_machine &machine) { return auto_alloc_clear(&machine, gijoe_state(machine)); } gijoe_state(running_machine &machine) { } /* memory pointers */ UINT16 * workram; UINT16 * spriteram; // UINT16 * paletteram; // currently this uses generic palette handling /* video-related */ int avac_bits[4], avac_occupancy[4]; int layer_colorbase[4], layer_pri[4]; int avac_vrc, sprite_colorbase; /* misc */ UINT16 cur_control2; emu_timer *dmadelay_timer; /* devices */ running_device *maincpu; running_device *audiocpu; running_device *k054539; running_device *k056832; running_device *k053246; running_device *k053251; }; /*----------- defined in video/gijoe.c -----------*/ extern void gijoe_sprite_callback(running_machine *machine, int *code, int *color, int *priority_mask); extern void gijoe_tile_callback(running_machine *machine, int layer, int *code, int *color, int *flags); VIDEO_START( gijoe ); VIDEO_UPDATE( gijoe );
[ "altimormc@gmail.com" ]
altimormc@gmail.com
015498721bc4a2f802d9397aa9f3b7055bee2cac
0df764149f0612bdd9b120079eca184ff0d74213
/1055 打印图案.cpp
af5121f30155534cc5f7c2e2529b303a45e6cf80
[]
no_license
Carterwwt/Mycode
b92bee26748fdef6e152cede7dca5c01c356eb00
a7f3aabc1b5de61aefc9f79a9c84076a8e96b012
refs/heads/master
2020-03-19T23:43:18.394268
2013-02-08T03:53:31
2013-02-08T03:53:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
#include"stdio.h" #include"stdlib.h" #include"math.h" #include"string.h" #include"malloc.h" int main() { int i,j,k,n,N,m; scanf("%d",&m); N=m/2+1; for(n=1;n<=N*2-1;n++) printf("*"); printf("\n"); for(i=0;i<=N-2;i++){ for(j=0;j<=N-3-i;j++) printf("*"); printf("*"); for(k=0;k<=2*i;k++) printf(" "); printf("*"); for(j=0;j<=N-3-i;j++) printf("*"); printf("\n"); } for(i=0;i<=N-3;i++){ for(j=0;j<=i;j++) printf("*"); printf("*"); for(k=0;k<=2*N-6-2*i;k++) printf(" "); printf("*"); for(j=0;j<=i;j++) printf("*"); printf("\n"); } for(n=1;n<=N*2-1;n++) printf("*"); return 0; }
[ "liaohaojie@126.com" ]
liaohaojie@126.com
8b89c6a2df0be12be293b8238040d14597f1c833
819b717ffcc34b3df2e6538ec3f952722e6be320
/stx/thread/posix/thread.hpp
38a4da064a55a91a1bf0cb644bee10dda19b838e
[]
no_license
kadavros/stx
7033c7a22a28dc6a5c2b9482e962f9fc9a3e04ce
a3700e0e639761e6a494f84d6f064fc5787d0a7c
refs/heads/master
2016-09-05T18:51:52.922853
2013-07-31T09:31:58
2013-07-31T09:31:58
6,503,368
1
0
null
2012-12-04T10:47:28
2012-11-02T08:26:08
C++
UTF-8
C++
false
false
2,699
hpp
#ifndef STX_THREAD_POSIX_THREAD_HPP #define STX_THREAD_POSIX_THREAD_HPP #include <stx/thread/posix/common.hpp> #include <stdexcept> namespace stx { namespace posix { template<class Func> inline void* thread_routine(void* arg) { (*((Func*) arg))(); delete (Func*) arg; return NULL; } // Create thread object for main thread: // thread t(this_thread::handle()); class thread { public: typedef thread this_type; typedef pthread_t handle_type; handle_type handle() { return handle_; } const handle_type handle() const { return handle_; } thread() { } thread(const pthread_t handle): handle_(handle) { } thread(const thread& t) { handle_ = t.handle(); } ~thread() { } template<class Func> void create(void *(*start_routine)(void*), void* arg) { int ret = pthread_create(&handle_, NULL, start_routine, arg); if (ret) { //STX_THROW_SYSTEM_ERROR_VAL(ret, "pthread_create"); // todo delete (Func*) arg; throw std::runtime_error("pthread_create"); } } template<class Func> void create(Func func) { Func* pf = new Func(func); create<Func>(thread_routine<Func>, (void*) pf); } void join() { void* val; join(val); } void join(void*& val) { int ret = pthread_join(handle_, &val); if (ret) { //STX_THROW_SYSTEM_ERROR_VAL(ret, "pthread_join"); // todo throw std::runtime_error("pthread_join"); } } bool joinable() const { return !equal(pthread_self()); } bool equal(const thread& t) const { return pthread_equal(handle_, t.handle()); } bool equal(const handle_type& h) const { return pthread_equal(handle_, h); } static unsigned hardware_concurrency() { return 0; } void detach() { int ret = pthread_detach(handle_); if (ret) { //STX_THROW_SYSTEM_ERROR_VAL(ret, "pthread_detach"); // todo throw std::runtime_error("pthread_detach"); } } void swap(thread& t) { handle_type h = handle_; handle_ = t.handle_; t.handle_ = h; } private: handle_type handle_; }; } // namespace posix } // namespace stx #endif // STX_THREAD_POSIX_THREAD_HPP
[ "kadavros@gmail.com" ]
kadavros@gmail.com
01ae41551243c7114f3c93b1a04ecc2a1dc4e9de
80a4b3ad41726e2c0bcb9d7aa8a754ba978567aa
/AdventOfCode2015/Day01/day01-part2.cpp
73f371d704e1445bf931921e7597a8a5ad87aa57
[]
no_license
brunk23/code-challenges
fb8feda4b397cccd8e1270945430e9d053a2a0d8
4726ecdb6765220a04622e4588bfcddade1b8aef
refs/heads/master
2021-01-10T12:54:48.092463
2020-12-07T01:53:35
2020-12-07T01:53:35
47,441,658
1
0
null
null
null
null
UTF-8
C++
false
false
562
cpp
// let's do day 1, just so we have a complete set of code for the // whole challenge #include <iostream> #include <string> using std::cout; using std::cin; using std::endl; using std::getline; using std::string; int main() { int floors = 0; int x = 0; string input; while( getline(cin, input) ) { for(; x < input.size(); ++x) { if(input[x] == '(') { floors++; } if(input[x] == ')' ) { floors--; } if( floors < 0 ) { break; } } } cout << "We went below the ground floor at character: " << (1+x) << endl; return 0; }
[ "brunellek@gmail.com" ]
brunellek@gmail.com
fd059421cf81025707d6e1ddd7376bc1005b6f8a
6e1bbe76ca284280555cef49a1e16f2c8a911e65
/deps/lcb/src/cntl.cc
2d2c966f1c561e850acd835e4efa8ba82b789463
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
camelspeed/couchnode
e0cdfb33d5595f42b10b1e2f135038d20b657b8e
2eb6be47ba95e1a4e792e092954c20937120f530
refs/heads/master
2022-04-27T00:08:04.723308
2020-04-17T17:46:14
2020-04-30T07:19:03
260,312,126
0
0
Apache-2.0
2020-04-30T20:30:25
2020-04-30T20:30:24
null
UTF-8
C++
false
false
42,641
cc
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010-2020 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "internal.h" #include "bucketconfig/clconfig.h" #include "contrib/lcb-jsoncpp/lcb-jsoncpp.h" #include <lcbio/iotable.h> #include <mcserver/negotiate.h> #include <lcbio/ssl.h> #define LOGARGS(instance, lvl) instance->settings, "cntl", LCB_LOG_##lvl, __FILE__, __LINE__ #define CNTL__MODE_SETSTRING 0x1000 /* Basic definition/declaration for handlers */ #define HANDLER(name) static lcb_STATUS name(int mode, lcb_INSTANCE *instance, int cmd, void *arg) /* For handlers which only retrieve values */ #define RETURN_GET_ONLY(T, acc) \ if (mode != LCB_CNTL_GET) { \ return LCB_ERR_CONTROL_UNSUPPORTED_MODE; \ } \ *reinterpret_cast< T * >(arg) = (T)acc; \ return LCB_SUCCESS; \ (void)cmd; #define RETURN_SET_ONLY(T, acc) \ if (mode != LCB_CNTL_SET) { \ return LCB_ERR_CONTROL_UNSUPPORTED_MODE; \ } \ acc = *reinterpret_cast< T * >(arg); \ return LCB_SUCCESS; #define RETURN_GET_SET(T, acc) \ if (mode == LCB_CNTL_GET) { \ RETURN_GET_ONLY(T, acc); \ } else if (mode == LCB_CNTL_SET) { \ RETURN_SET_ONLY(T, acc); \ } else { \ return LCB_ERR_CONTROL_UNSUPPORTED_MODE; \ } typedef lcb_STATUS (*ctl_handler)(int, lcb_INSTANCE *, int, void *); typedef struct { const char *s; lcb_U32 u32; } STR_u32MAP; static const STR_u32MAP* u32_from_map(const char *s, const STR_u32MAP *lookup) { const STR_u32MAP *ret; for (ret = lookup; ret->s; ret++) { lcb_SIZE maxlen = strlen(ret->s); if (!strncmp(ret->s, s, maxlen)) { return ret; } } return NULL; } #define DO_CONVERT_STR2NUM(s, lookup, v) \ { \ const STR_u32MAP *str__rv = u32_from_map(s, lookup); \ if (str__rv) { \ v = str__rv->u32; \ } else { \ return LCB_ERR_CONTROL_INVALID_ARGUMENT; \ } \ } static lcb_uint32_t *get_timeout_field(lcb_INSTANCE *instance, int cmd) { lcb_settings *settings = instance->settings; switch (cmd) { case LCB_CNTL_OP_TIMEOUT: return &settings->operation_timeout; case LCB_CNTL_VIEW_TIMEOUT: return &settings->views_timeout; case LCB_CNTL_QUERY_TIMEOUT: return &settings->n1ql_timeout; case LCB_CNTL_DURABILITY_INTERVAL: return &settings->durability_interval; case LCB_CNTL_DURABILITY_TIMEOUT: return &settings->durability_timeout; case LCB_CNTL_HTTP_TIMEOUT: return &settings->http_timeout; case LCB_CNTL_CONFIGURATION_TIMEOUT: return &settings->config_timeout; case LCB_CNTL_CONFDELAY_THRESH: return &settings->weird_things_delay; case LCB_CNTL_CONFIG_NODE_TIMEOUT: return &settings->config_node_timeout; case LCB_CNTL_HTCONFIG_IDLE_TIMEOUT: return &settings->bc_http_stream_time; case LCB_CNTL_RETRY_INTERVAL: return &settings->retry_interval; case LCB_CNTL_RETRY_NMV_INTERVAL: return &settings->retry_nmv_interval; case LCB_CNTL_CONFIG_POLL_INTERVAL: return &settings->config_poll_interval; case LCB_CNTL_TRACING_ORPHANED_QUEUE_FLUSH_INTERVAL: return &settings->tracer_orphaned_queue_flush_interval; case LCB_CNTL_TRACING_THRESHOLD_QUEUE_FLUSH_INTERVAL: return &settings->tracer_threshold_queue_flush_interval; case LCB_CNTL_TRACING_THRESHOLD_KV: return &settings->tracer_threshold[LCBTRACE_THRESHOLD_KV]; case LCB_CNTL_TRACING_THRESHOLD_QUERY: return &settings->tracer_threshold[LCBTRACE_THRESHOLD_QUERY]; case LCB_CNTL_TRACING_THRESHOLD_VIEW: return &settings->tracer_threshold[LCBTRACE_THRESHOLD_VIEW]; case LCB_CNTL_TRACING_THRESHOLD_SEARCH: return &settings->tracer_threshold[LCBTRACE_THRESHOLD_SEARCH]; case LCB_CNTL_TRACING_THRESHOLD_ANALYTICS: return &settings->tracer_threshold[LCBTRACE_THRESHOLD_ANALYTICS]; case LCB_CNTL_PERSISTENCE_TIMEOUT_FLOOR: return &settings->persistence_timeout_floor; default: return NULL; } } HANDLER(timeout_common) { lcb_U32 *ptr; lcb_U32 *user = reinterpret_cast<lcb_U32*>(arg); ptr = get_timeout_field(instance, cmd); if (!ptr) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } if (mode == LCB_CNTL_GET) { *user = *ptr; } else { if (cmd == LCB_CNTL_PERSISTENCE_TIMEOUT_FLOOR && *user < LCB_DEFAULT_PERSISTENCE_TIMEOUT_FLOOR) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } *ptr = *user; } return LCB_SUCCESS; } HANDLER(noop_handler) { (void)mode;(void)instance;(void)cmd;(void)arg; return LCB_SUCCESS; } HANDLER(get_vbconfig) { RETURN_GET_ONLY(lcbvb_CONFIG*, LCBT_VBCONFIG(instance)) } HANDLER(get_htype) { RETURN_GET_ONLY(lcb_INSTANCE_TYPE, static_cast< lcb_INSTANCE_TYPE >(instance->settings->conntype)) } HANDLER(get_iops) { RETURN_GET_ONLY(lcb_io_opt_t, instance->iotable->p) } HANDLER(ippolicy) { RETURN_GET_SET(lcb_ipv6_t, instance->settings->ipv6) } HANDLER(confthresh) { RETURN_GET_SET(lcb_SIZE, instance->settings->weird_things_threshold) } HANDLER(randomize_bootstrap_hosts_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, randomize_bootstrap_nodes)) } HANDLER(get_changeset) { (void)instance; RETURN_GET_ONLY(char*, LCB_VERSION_CHANGESET) } HANDLER(ssl_mode_handler) { RETURN_GET_ONLY(int, LCBT_SETTING(instance, sslopts)) } HANDLER(ssl_truststorepath_handler) { RETURN_GET_ONLY(char*, LCBT_SETTING(instance, truststorepath)) } HANDLER(ssl_certpath_handler) { RETURN_GET_ONLY(char*, LCBT_SETTING(instance, certpath)) } HANDLER(ssl_keypath_handler) { RETURN_GET_ONLY(char*, LCBT_SETTING(instance, keypath)) } HANDLER(htconfig_urltype_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, bc_http_urltype)); } HANDLER(syncdtor_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, syncdtor)); } HANDLER(detailed_errcode_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, detailed_neterr)) } HANDLER(http_poolsz_handler) { RETURN_GET_SET(lcb_SIZE, instance->http_sockpool->get_options().maxidle) } HANDLER(http_pooltmo_handler) { RETURN_GET_SET(uint32_t, instance->http_sockpool->get_options().tmoidle) } HANDLER(http_refresh_config_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, refresh_on_hterr)) } HANDLER(compmode_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, compressopts)) } HANDLER(bucketname_handler) { RETURN_GET_ONLY(const char*, LCBT_SETTING(instance, bucket)) } HANDLER(buckettype_handler) { RETURN_GET_ONLY(lcb_BTYPE, static_cast<lcb_BTYPE>(instance->btype)) } HANDLER(schedflush_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, sched_implicit_flush)) } HANDLER(vbguess_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, keep_guess_vbs)) } HANDLER(vb_noremap_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, vb_noremap)) } HANDLER(wait_for_config_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, wait_for_config)) } HANDLER(fetch_mutation_tokens_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, fetch_mutation_tokens)) } HANDLER(nmv_imm_retry_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, nmv_retry_imm)); } HANDLER(tcp_nodelay_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, tcp_nodelay)); } HANDLER(tcp_keepalive_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, tcp_keepalive)); } HANDLER(readj_ts_wait_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, readj_ts_wait)); } HANDLER(kv_hg_handler) { RETURN_GET_ONLY(lcb_HISTOGRAM*, instance->kv_timings); } HANDLER(read_chunk_size_handler) { RETURN_GET_SET(lcb_U32, LCBT_SETTING(instance, read_chunk_size)); } HANDLER(enable_errmap_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, use_errmap)); } HANDLER(select_bucket_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, select_bucket)); } HANDLER(send_hello_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, send_hello)); } HANDLER(log_redaction_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, log_redaction)); } HANDLER(enable_tracing_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, use_tracing)); } HANDLER(tracing_orphaned_queue_size_handler) { RETURN_GET_SET(lcb_U32, LCBT_SETTING(instance, tracer_orphaned_queue_size)); } HANDLER(tracing_threshold_queue_size_handler) { RETURN_GET_SET(lcb_U32, LCBT_SETTING(instance, tracer_threshold_queue_size)); } HANDLER(config_poll_interval_handler) { lcb_U32 *user = reinterpret_cast<lcb_U32*>(arg); if (mode == LCB_CNTL_SET && *user > 0 && *user < LCB_CONFIG_POLL_INTERVAL_FLOOR) { lcb_log(LOGARGS(instance, ERROR), "Interval for background poll is too low: %dus (min: %dus)", *user, LCB_CONFIG_POLL_INTERVAL_FLOOR); return LCB_ERR_CONTROL_INVALID_ARGUMENT; } lcb_STATUS rv = timeout_common(mode, instance, cmd, arg); if (rv == LCB_SUCCESS && (mode == LCB_CNTL_SET || mode == CNTL__MODE_SETSTRING) && // Note: This might be NULL during creation! instance->bs_state) { instance->bs_state->check_bgpoll(); } return rv; } HANDLER(get_kvb) { lcb_cntl_vbinfo_st *vbi = reinterpret_cast<lcb_cntl_vbinfo_st*>(arg); if (mode != LCB_CNTL_GET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } if (!LCBT_VBCONFIG(instance)) { return LCB_ERR_NO_CONFIGURATION; } if (vbi->version != 0) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } lcbvb_map_key(LCBT_VBCONFIG(instance), vbi->v.v0.key, vbi->v.v0.nkey, &vbi->v.v0.vbucket, &vbi->v.v0.server_index); (void)cmd; return LCB_SUCCESS; } HANDLER(conninfo) { const lcbio_SOCKET *sock; lcb_cntl_server_st *si = reinterpret_cast<lcb_cntl_server_st*>(arg); const lcb_host_t *host; if (mode != LCB_CNTL_GET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } if (si->version < 0 || si->version > 1) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } if (cmd == LCB_CNTL_MEMDNODE_INFO) { lcb::Server *server; int ix = si->v.v0.index; if (ix < 0 || ix > (int)LCBT_NSERVERS(instance)) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } server = instance->get_server(ix); if (!server) { return LCB_ERR_NETWORK; } sock = server->connctx->sock; if (si->version == 1 && sock) { lcb::SessionInfo *info = lcb::SessionInfo::get(server->connctx->sock); if (info) { si->v.v1.sasl_mech = info->get_mech().c_str(); } } } else if (cmd == LCB_CNTL_CONFIGNODE_INFO) { sock = lcb::clconfig::http_get_conn(instance->confmon); } else { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } if (!sock) { return LCB_SUCCESS; } host = lcbio_get_host(sock); si->v.v0.connected = 1; si->v.v0.host = host->host; si->v.v0.port = host->port; if (instance->iotable->model == LCB_IOMODEL_EVENT) { si->v.v0.sock.sockfd = sock->u.fd; } else { si->v.v0.sock.sockptr = sock->u.sd; } return LCB_SUCCESS; } HANDLER(config_cache_loaded_handler) { if (mode != LCB_CNTL_GET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } *(int *)arg = instance->cur_configinfo && instance->cur_configinfo->get_origin() == lcb::clconfig::CLCONFIG_FILE; (void)cmd; return LCB_SUCCESS; } HANDLER(force_sasl_mech_handler) { if (mode == LCB_CNTL_SET) { free(instance->settings->sasl_mech_force); if (arg) { const char *s = reinterpret_cast<const char*>(arg); instance->settings->sasl_mech_force = strdup(s); } } else { *(char**)arg = instance->settings->sasl_mech_force; } (void)cmd; return LCB_SUCCESS; } HANDLER(max_redirects) { if (mode == LCB_CNTL_SET && *(int *)arg < -1) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } RETURN_GET_SET(int, LCBT_SETTING(instance, max_redir)) } HANDLER(logprocs_handler) { if (mode == LCB_CNTL_GET) { *(const lcb_LOGGER **)arg = LCBT_SETTING(instance, logger); } else if (mode == LCB_CNTL_SET) { LCBT_SETTING(instance, logger) = (const lcb_LOGGER *)arg; } (void)cmd; return LCB_SUCCESS; } HANDLER(config_transport) { lcb_BOOTSTRAP_TRANSPORT *val = reinterpret_cast< lcb_BOOTSTRAP_TRANSPORT * >(arg); if (mode == LCB_CNTL_SET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } if (!instance->cur_configinfo) { return LCB_ERR_NO_CONFIGURATION; } switch (instance->cur_configinfo->get_origin()) { case lcb::clconfig::CLCONFIG_HTTP: *val = LCB_CONFIG_TRANSPORT_HTTP; break; case lcb::clconfig::CLCONFIG_CCCP: *val = LCB_CONFIG_TRANSPORT_CCCP; break; default: return LCB_ERR_NO_CONFIGURATION; } (void)cmd; return LCB_SUCCESS; } HANDLER(config_nodes) { const char *node_strs = reinterpret_cast<const char*>(arg); lcb::clconfig::Provider *target; lcb::Hostlist hostlist; lcb_STATUS err; if (mode != LCB_CNTL_SET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } err = hostlist.add(node_strs, -1, cmd == LCB_CNTL_CONFIG_HTTP_NODES ? LCB_CONFIG_HTTP_PORT : LCB_CONFIG_MCD_PORT); if (err != LCB_SUCCESS) { return err; } if (cmd == LCB_CNTL_CONFIG_HTTP_NODES) { target = instance->confmon->get_provider(lcb::clconfig::CLCONFIG_HTTP); } else { target = instance->confmon->get_provider(lcb::clconfig::CLCONFIG_CCCP); } target->configure_nodes(hostlist); return LCB_SUCCESS; } HANDLER(config_cache_handler) { using namespace lcb::clconfig; Provider *provider; provider = instance->confmon->get_provider(lcb::clconfig::CLCONFIG_FILE); if (mode == LCB_CNTL_SET) { bool rv = file_set_filename(provider, reinterpret_cast<const char*>(arg), cmd == LCB_CNTL_CONFIGCACHE_RO); if (rv) { instance->settings->bc_http_stream_time = LCB_MS2US(10000); return LCB_SUCCESS; } return LCB_ERR_INVALID_ARGUMENT; } else { *(const char **)arg = file_get_filename(provider); return LCB_SUCCESS; } } HANDLER(retrymode_handler) { lcb_U32 *val = reinterpret_cast<lcb_U32*>(arg); lcb_U32 rmode = LCB_RETRYOPT_GETMODE(*val); uint8_t *p = NULL; if (rmode >= LCB_RETRY_ON_MAX) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } p = &(LCBT_SETTING(instance, retry)[rmode]); if (mode == LCB_CNTL_SET) { *p = LCB_RETRYOPT_GETPOLICY(*val); } else { *val = LCB_RETRYOPT_CREATE(rmode, *p); } (void)cmd; return LCB_SUCCESS; } HANDLER(allocfactory_handler) { lcb_cntl_rdballocfactory *cbw = reinterpret_cast<lcb_cntl_rdballocfactory*>(arg); if (mode == LCB_CNTL_SET) { LCBT_SETTING(instance, allocator_factory) = cbw->factory; } else { cbw->factory = LCBT_SETTING(instance, allocator_factory); } (void)cmd; return LCB_SUCCESS; } HANDLER(console_log_handler) { lcb_U32 level; struct lcb_CONSOLELOGGER *logger; const lcb_LOGGER *procs; level = *(lcb_U32*)arg; if (mode != LCB_CNTL_SET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } procs = LCBT_SETTING(instance, logger); if (!procs) { procs = lcb_init_console_logger(); } if (procs) { /* don't override previous config */ return LCB_SUCCESS; } logger = (struct lcb_CONSOLELOGGER *)lcb_console_logger; level = LCB_LOG_ERROR - level; logger->minlevel = (lcb_LOG_SEVERITY)level; LCBT_SETTING(instance, logger) = &logger->base; (void)cmd; return LCB_SUCCESS; } HANDLER(console_fp_handler) { struct lcb_CONSOLELOGGER *logger = (struct lcb_CONSOLELOGGER *)lcb_console_logger; if (mode == LCB_CNTL_GET) { *(FILE **)arg = logger->fp; } else if (mode == LCB_CNTL_SET) { logger->fp = *(FILE**)arg; } else if (mode == CNTL__MODE_SETSTRING) { FILE *fp = fopen(reinterpret_cast<const char*>(arg), "w"); if (!fp) { return LCB_ERR_INVALID_ARGUMENT; } else { logger->fp = fp; } } (void)cmd; (void)instance; return LCB_SUCCESS; } HANDLER(reinit_spec_handler) { if (mode == LCB_CNTL_GET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } (void)cmd; return lcb_reinit(instance, reinterpret_cast< const char * >(arg)); } HANDLER(client_string_handler) { if (mode == LCB_CNTL_SET) { const char *val = reinterpret_cast<const char*>(arg); free(LCBT_SETTING(instance, client_string)); LCBT_SETTING(instance, client_string) = NULL; if (val) { char *p, *buf = strdup(val); for (p = buf; *p != '\0'; p++) { switch (*p) { case '\n': case '\r': *p = ' '; break; default: break; } } LCBT_SETTING(instance, client_string) = buf; } } else { *(const char **)arg = LCBT_SETTING(instance, client_string); } (void)cmd; return LCB_SUCCESS; } HANDLER(unsafe_optimize) { lcb_STATUS rc; int val = *(int *)arg; if (mode != LCB_CNTL_SET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } if (!val) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } /* Simpler to just input strings here. */ #define APPLY_UNSAFE(k, v) \ if ((rc = lcb_cntl_string(instance, k, v)) != LCB_SUCCESS) { return rc; } APPLY_UNSAFE("vbguess_persist", "1"); APPLY_UNSAFE("retry_policy", "topochange:none") APPLY_UNSAFE("retry_policy", "sockerr:none"); APPLY_UNSAFE("retry_policy", "maperr:none"); APPLY_UNSAFE("retry_policy", "missingnode:none"); (void)cmd; return LCB_SUCCESS; } HANDLER(mutation_tokens_supported_handler) { size_t ii; if (mode != LCB_CNTL_GET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } *(int *)arg = 0; for (ii = 0; ii < LCBT_NSERVERS(instance); ii++) { if (instance->get_server(ii)->supports_mutation_tokens()) { *(int *)arg = 1; break; } } (void)cmd; return LCB_SUCCESS; } HANDLER(n1ql_cache_clear_handler) { if (mode != LCB_CNTL_SET) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } lcb_n1qlcache_clear(instance->n1ql_cache); (void)cmd; (void)arg; return LCB_SUCCESS; } HANDLER(bucket_auth_handler) { const lcb_BUCKETCRED *cred; if (mode == LCB_CNTL_SET) { if (LCBT_SETTING(instance, keypath)) { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } /* Parse the bucket string... */ cred = (const lcb_BUCKETCRED *)arg; return lcbauth_add_pass(instance->settings->auth, (*cred)[0], (*cred)[1], LCBAUTH_F_BUCKET); (void)cmd; (void)arg; } else if (mode == CNTL__MODE_SETSTRING) { const char *ss = reinterpret_cast<const char *>(arg); size_t sslen = strlen(ss); Json::Value root; if (!Json::Reader().parse(ss, ss + sslen, root)) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } if (!root.isArray() || root.size() != 2) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } return lcbauth_add_pass(instance->settings->auth, root[0].asString().c_str(), root[1].asString().c_str(), LCBAUTH_F_BUCKET); } else { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } return LCB_SUCCESS; } HANDLER(metrics_handler) { if (mode == LCB_CNTL_SET) { int val = *(int *)arg; if (!val) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } if (!instance->settings->metrics) { instance->settings->metrics = lcb_metrics_new(); } return LCB_SUCCESS; } else if (mode == LCB_CNTL_GET) { *(lcb_METRICS**)arg = instance->settings->metrics; return LCB_SUCCESS; } else { return LCB_ERR_CONTROL_UNSUPPORTED_MODE; } (void)cmd; } HANDLER(collections_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, use_collections)); } HANDLER(allow_static_config_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, allow_static_config)); } HANDLER(comp_min_size_handler) { if (mode == LCB_CNTL_SET && *reinterpret_cast<lcb_U32*>(arg) < LCB_DEFAULT_COMPRESS_MIN_SIZE) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } RETURN_GET_SET(lcb_U32, LCBT_SETTING(instance, compress_min_size)) } HANDLER(comp_min_ratio_handler) { if (mode == LCB_CNTL_SET) { float val = *reinterpret_cast<float*>(arg); if (val > 1 || val < 0) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } } RETURN_GET_SET(float, LCBT_SETTING(instance, compress_min_ratio)) } HANDLER(network_handler) { if (mode == LCB_CNTL_SET) { const char *val = reinterpret_cast<const char*>(arg); free(LCBT_SETTING(instance, network)); LCBT_SETTING(instance, network) = NULL; if (val) { LCBT_SETTING(instance, network) = strdup(val); } } else { *(const char **)arg = LCBT_SETTING(instance, network); } (void)cmd; return LCB_SUCCESS; } HANDLER(durable_write_handler) { RETURN_GET_SET(int, LCBT_SETTING(instance, enable_durable_write)); } /* clang-format off */ static ctl_handler handlers[] = { timeout_common, /* LCB_CNTL_OP_TIMEOUT */ timeout_common, /* LCB_CNTL_VIEW_TIMEOUT */ noop_handler, /* LCB_CNTL_RBUFSIZE */ noop_handler, /* LCB_CNTL_WBUFSIZE */ get_htype, /* LCB_CNTL_HANDLETYPE */ get_vbconfig, /* LCB_CNTL_VBCONFIG */ get_iops, /* LCB_CNTL_IOPS */ get_kvb, /* LCB_CNTL_VBMAP */ conninfo, /* LCB_CNTL_MEMDNODE_INFO */ conninfo, /* LCB_CNTL_CONFIGNODE_INFO */ NULL, /* deprecated LCB_CNTL_SYNCMODE (0x0a) */ ippolicy, /* LCB_CNTL_IP6POLICY */ confthresh, /* LCB_CNTL_CONFERRTHRESH */ timeout_common, /* LCB_CNTL_DURABILITY_INTERVAL */ timeout_common, /* LCB_CNTL_DURABILITY_TIMEOUT */ timeout_common, /* LCB_CNTL_HTTP_TIMEOUT */ lcb_iops_cntl_handler, /* LCB_CNTL_IOPS_DEFAULT_TYPES */ lcb_iops_cntl_handler, /* LCB_CNTL_IOPS_DLOPEN_DEBUG */ timeout_common, /* LCB_CNTL_CONFIGURATION_TIMEOUT */ noop_handler, /* LCB_CNTL_SKIP_CONFIGURATION_ERRORS_ON_CONNECT */ randomize_bootstrap_hosts_handler, /* LCB_CNTL_RANDOMIZE_BOOTSTRAP_HOSTS */ config_cache_loaded_handler, /* LCB_CNTL_CONFIG_CACHE_LOADED */ force_sasl_mech_handler, /* LCB_CNTL_FORCE_SASL_MECH */ max_redirects, /* LCB_CNTL_MAX_REDIRECTS */ logprocs_handler, /* LCB_CNTL_LOGGER */ timeout_common, /* LCB_CNTL_CONFDELAY_THRESH */ config_transport, /* LCB_CNTL_CONFIG_TRANSPORT */ timeout_common, /* LCB_CNTL_CONFIG_NODE_TIMEOUT */ timeout_common, /* LCB_CNTL_HTCONFIG_IDLE_TIMEOUT */ config_nodes, /* LCB_CNTL_CONFIG_HTTP_NODES */ config_nodes, /* LCB_CNTL_CONFIG_CCCP_NODES */ get_changeset, /* LCB_CNTL_CHANGESET */ NULL, /* LCB_CNTL_CONFIG_ALL_NODES */ config_cache_handler, /* LCB_CNTL_CONFIGCACHE */ ssl_mode_handler, /* LCB_CNTL_SSL_MODE */ ssl_certpath_handler, /* LCB_CNTL_SSL_CERT */ retrymode_handler, /* LCB_CNTL_RETRYMODE */ htconfig_urltype_handler, /* LCB_CNTL_HTCONFIG_URLTYPE */ compmode_handler, /* LCB_CNTL_COMPRESSION_OPTS */ allocfactory_handler, /* LCB_CNTL_RDBALLOCFACTORY */ syncdtor_handler, /* LCB_CNTL_SYNCDESTROY */ console_log_handler, /* LCB_CNTL_CONLOGGER_LEVEL */ detailed_errcode_handler, /* LCB_CNTL_DETAILED_ERRCODES */ reinit_spec_handler, /* LCB_CNTL_REINIT_CONNSTR */ timeout_common, /* LCB_CNTL_RETRY_INTERVAL */ NULL, /* deprecated LCB_CNTL_RETRY_BACKOFF (0x2D) */ http_poolsz_handler, /* LCB_CNTL_HTTP_POOLSIZE */ http_refresh_config_handler, /* LCB_CNTL_HTTP_REFRESH_CONFIG_ON_ERROR */ bucketname_handler, /* LCB_CNTL_BUCKETNAME */ schedflush_handler, /* LCB_CNTL_SCHED_IMPLICIT_FLUSH */ vbguess_handler, /* LCB_CNTL_VBGUESS_PERSIST */ unsafe_optimize, /* LCB_CNTL_UNSAFE_OPTIMIZE */ fetch_mutation_tokens_handler, /* LCB_CNTL_ENABLE_MUTATION_TOKENS */ NULL, /* LCB_CNTL_DURABILITY_MUTATION_TOKENS */ config_cache_handler, /* LCB_CNTL_CONFIGCACHE_READONLY */ nmv_imm_retry_handler, /* LCB_CNTL_RETRY_NMV_IMM */ mutation_tokens_supported_handler, /* LCB_CNTL_MUTATION_TOKENS_SUPPORTED */ tcp_nodelay_handler, /* LCB_CNTL_TCP_NODELAY */ readj_ts_wait_handler, /* LCB_CNTL_RESET_TIMEOUT_ON_WAIT */ console_fp_handler, /* LCB_CNTL_CONLOGGER_FP */ kv_hg_handler, /* LCB_CNTL_KVTIMINGS */ timeout_common, /* LCB_CNTL_QUERY_TIMEOUT */ n1ql_cache_clear_handler, /* LCB_CNTL_N1QL_CLEARCACHE */ client_string_handler, /* LCB_CNTL_CLIENT_STRING */ bucket_auth_handler, /* LCB_CNTL_BUCKET_CRED */ timeout_common, /* LCB_CNTL_RETRY_NMV_DELAY */ read_chunk_size_handler, /* LCB_CNTL_READ_CHUNKSIZE */ enable_errmap_handler, /* LCB_CNTL_ENABLE_ERRMAP */ select_bucket_handler, /* LCB_CNTL_SELECT_BUCKET */ tcp_keepalive_handler, /* LCB_CNTL_TCP_KEEPALIVE */ config_poll_interval_handler, /* LCB_CNTL_CONFIG_POLL_INTERVAL */ send_hello_handler, /* LCB_CNTL_SEND_HELLO */ buckettype_handler, /* LCB_CNTL_BUCKETTYPE */ metrics_handler, /* LCB_CNTL_METRICS */ collections_handler, /* LCB_CNTL_ENABLE_COLLECTIONS */ ssl_keypath_handler, /* LCB_CNTL_SSL_KEY */ log_redaction_handler, /* LCB_CNTL_LOG_REDACTION */ ssl_truststorepath_handler, /* LCB_CNTL_SSL_TRUSTSTORE */ enable_tracing_handler, /* LCB_CNTL_ENABLE_TRACING */ timeout_common, /* LCB_CNTL_TRACING_ORPHANED_QUEUE_FLUSH_INTERVAL */ tracing_orphaned_queue_size_handler, /* LCB_CNTL_TRACING_ORPHANED_QUEUE_SIZE */ timeout_common, /* LCB_CNTL_TRACING_THRESHOLD_QUEUE_FLUSH_INTERVAL */ tracing_threshold_queue_size_handler, /* LCB_CNTL_TRACING_THRESHOLD_QUEUE_SIZE */ timeout_common, /* LCB_CNTL_TRACING_THRESHOLD_KV */ timeout_common, /* LCB_CNTL_TRACING_THRESHOLD_QUERY */ timeout_common, /* LCB_CNTL_TRACING_THRESHOLD_VIEW */ timeout_common, /* LCB_CNTL_TRACING_THRESHOLD_SEARCH */ timeout_common, /* LCB_CNTL_TRACING_THRESHOLD_ANALYTICS */ comp_min_size_handler, /* LCB_CNTL_COMPRESSION_MIN_SIZE */ comp_min_ratio_handler, /* LCB_CNTL_COMPRESSION_MIN_RATIO */ vb_noremap_handler, /* LCB_CNTL_VB_NOREMAP */ network_handler, /* LCB_CNTL_NETWORK */ wait_for_config_handler, /* LCB_CNTL_WAIT_FOR_CONFIG */ http_pooltmo_handler, /* LCB_CNTL_HTTP_POOL_TIMEOUT */ durable_write_handler, /* LCB_CNTL_ENABLE_DURABLE_WRITE */ timeout_common, /* LCB_CNTL_PERSISTENCE_TIMEOUT_FLOOR */ allow_static_config_handler, /* LCB_CNTL_ALLOW_STATIC_CONFIG */ NULL }; /* clang-format on */ /* Union used for conversion to/from string functions */ typedef union { lcb_U32 u32; lcb_SIZE sz; int i; float f; void *p; } u_STRCONVERT; /* This handler should convert the string argument to the appropriate * type needed for the actual control handler. It should return an error if the * argument is invalid. */ typedef lcb_STATUS (*ctl_str_cb)(const char *value, u_STRCONVERT *u); typedef struct { const char *key; int opcode; ctl_str_cb converter; } cntl_OPCODESTRS; static lcb_STATUS convert_timevalue(const char *arg, u_STRCONVERT *u) { int rv; unsigned long tmp; /* Parse as a float */ double dtmp; rv = sscanf(arg, "%lf", &dtmp); if (rv != 1) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } tmp = dtmp * (double) 1000000; u->u32 = tmp; return LCB_SUCCESS; } static lcb_STATUS convert_intbool(const char *arg, u_STRCONVERT *u) { if (!strcmp(arg, "true") || !strcmp(arg, "on")) { u->i = 1; } else if (!strcmp(arg, "false") || !strcmp(arg, "off")) { u->i = 0; } else { u->i = atoi(arg); } return LCB_SUCCESS; } static lcb_STATUS convert_passthru(const char *arg, u_STRCONVERT *u) { u->p = (void*)arg; return LCB_SUCCESS; } static lcb_STATUS convert_int(const char *arg, u_STRCONVERT *u) { int rv = sscanf(arg, "%d", &u->i); return rv == 1 ? LCB_SUCCESS : LCB_ERR_CONTROL_INVALID_ARGUMENT; } static lcb_STATUS convert_u32(const char *arg, u_STRCONVERT *u) { unsigned int tmp; int rv = sscanf(arg, "%u", &tmp); u->u32 = tmp; return rv == 1 ? LCB_SUCCESS : LCB_ERR_CONTROL_INVALID_ARGUMENT; } static lcb_STATUS convert_float(const char *arg, u_STRCONVERT *u) { double d; int rv = sscanf(arg, "%lf", &d); if (rv != 1) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } u->f = d; return LCB_SUCCESS; } static lcb_STATUS convert_SIZE(const char *arg, u_STRCONVERT *u) { unsigned long lu; int rv; rv = sscanf(arg, "%lu", &lu); if (rv != 1) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } u->sz = lu; return LCB_SUCCESS; } static lcb_STATUS convert_compression(const char *arg, u_STRCONVERT *u) { static const STR_u32MAP optmap[] = { { "on", LCB_COMPRESS_INOUT }, { "off", LCB_COMPRESS_NONE }, { "inflate_only", LCB_COMPRESS_IN }, { "deflate_only", LCB_COMPRESS_OUT }, { "force", LCB_COMPRESS_INOUT|LCB_COMPRESS_FORCE }, { NULL } }; DO_CONVERT_STR2NUM(arg, optmap, u->i); return LCB_SUCCESS; } static lcb_STATUS convert_retrymode(const char *arg, u_STRCONVERT *u) { static const STR_u32MAP modemap[] = { { "topochange", LCB_RETRY_ON_TOPOCHANGE }, { "sockerr", LCB_RETRY_ON_SOCKERR }, { "maperr", LCB_RETRY_ON_VBMAPERR }, { "missingnode", LCB_RETRY_ON_MISSINGNODE }, { NULL } }; static const STR_u32MAP polmap[] = { { "all", LCB_RETRY_CMDS_ALL }, { "get", LCB_RETRY_CMDS_GET }, { "safe", LCB_RETRY_CMDS_SAFE }, { "none", LCB_RETRY_CMDS_NONE }, { NULL } }; lcb_U32 polval, modeval; const char *polstr = strchr(arg, ':'); if (!polstr) { return LCB_ERR_CONTROL_INVALID_ARGUMENT; } polstr++; DO_CONVERT_STR2NUM(arg, modemap, modeval); DO_CONVERT_STR2NUM(polstr, polmap, polval); u->u32 = LCB_RETRYOPT_CREATE(modeval, polval); return LCB_SUCCESS; } static lcb_STATUS convert_ipv6(const char *arg, u_STRCONVERT *u) { static const STR_u32MAP optmap[] = { {"disabled", LCB_IPV6_DISABLED}, {"only", LCB_IPV6_ONLY}, {"allow", LCB_IPV6_ALLOW}, {NULL} }; DO_CONVERT_STR2NUM(arg, optmap, u->i); return LCB_SUCCESS; } static cntl_OPCODESTRS stropcode_map[] = { {"operation_timeout", LCB_CNTL_OP_TIMEOUT, convert_timevalue}, {"timeout", LCB_CNTL_OP_TIMEOUT, convert_timevalue}, {"views_timeout", LCB_CNTL_VIEW_TIMEOUT, convert_timevalue}, {"query_timeout", LCB_CNTL_QUERY_TIMEOUT, convert_timevalue}, {"durability_timeout", LCB_CNTL_DURABILITY_TIMEOUT, convert_timevalue}, {"durability_interval", LCB_CNTL_DURABILITY_INTERVAL, convert_timevalue}, {"http_timeout", LCB_CNTL_HTTP_TIMEOUT, convert_timevalue}, {"randomize_nodes", LCB_CNTL_RANDOMIZE_BOOTSTRAP_HOSTS, convert_intbool}, {"sasl_mech_force", LCB_CNTL_FORCE_SASL_MECH, convert_passthru}, {"error_thresh_count", LCB_CNTL_CONFERRTHRESH, convert_SIZE}, {"error_thresh_delay", LCB_CNTL_CONFDELAY_THRESH, convert_timevalue}, {"config_total_timeout", LCB_CNTL_CONFIGURATION_TIMEOUT, convert_timevalue}, {"config_node_timeout", LCB_CNTL_CONFIG_NODE_TIMEOUT, convert_timevalue}, {"compression", LCB_CNTL_COMPRESSION_OPTS, convert_compression}, {"console_log_level", LCB_CNTL_CONLOGGER_LEVEL, convert_u32}, {"config_cache", LCB_CNTL_CONFIGCACHE, convert_passthru}, {"config_cache_ro", LCB_CNTL_CONFIGCACHE_RO, convert_passthru}, {"detailed_errcodes", LCB_CNTL_DETAILED_ERRCODES, convert_intbool}, {"retry_policy", LCB_CNTL_RETRYMODE, convert_retrymode}, {"http_urlmode", LCB_CNTL_HTCONFIG_URLTYPE, convert_int}, {"sync_dtor", LCB_CNTL_SYNCDESTROY, convert_intbool}, {"_reinit_connstr", LCB_CNTL_REINIT_CONNSTR}, {"", -1}, /* deprecated "retry_backoff" */ {"retry_interval", LCB_CNTL_RETRY_INTERVAL, convert_timevalue}, {"http_poolsize", LCB_CNTL_HTTP_POOLSIZE, convert_SIZE}, {"vbguess_persist", LCB_CNTL_VBGUESS_PERSIST, convert_intbool}, {"unsafe_optimize", LCB_CNTL_UNSAFE_OPTIMIZE, convert_intbool}, {"enable_mutation_tokens", LCB_CNTL_ENABLE_MUTATION_TOKENS, convert_intbool}, {"", -1, NULL}, /* removed dur_mutation_tokens */ {"retry_nmv_imm", LCB_CNTL_RETRY_NMV_IMM, convert_intbool}, {"tcp_nodelay", LCB_CNTL_TCP_NODELAY, convert_intbool}, {"readj_ts_wait", LCB_CNTL_RESET_TIMEOUT_ON_WAIT, convert_intbool}, {"console_log_file", LCB_CNTL_CONLOGGER_FP, NULL}, {"client_string", LCB_CNTL_CLIENT_STRING, convert_passthru}, {"retry_nmv_delay", LCB_CNTL_RETRY_NMV_INTERVAL, convert_timevalue}, {"bucket_cred", LCB_CNTL_BUCKET_CRED, NULL}, {"read_chunk_size", LCB_CNTL_READ_CHUNKSIZE, convert_u32}, {"enable_errmap", LCB_CNTL_ENABLE_ERRMAP, convert_intbool}, {"select_bucket", LCB_CNTL_SELECT_BUCKET, convert_intbool}, {"tcp_keepalive", LCB_CNTL_TCP_KEEPALIVE, convert_intbool}, {"config_poll_interval", LCB_CNTL_CONFIG_POLL_INTERVAL, convert_timevalue}, {"send_hello", LCB_CNTL_SEND_HELLO, convert_intbool}, {"ipv6", LCB_CNTL_IP6POLICY, convert_ipv6}, {"metrics", LCB_CNTL_METRICS, convert_intbool}, {"log_redaction", LCB_CNTL_LOG_REDACTION, convert_intbool}, {"enable_tracing", LCB_CNTL_ENABLE_TRACING, convert_intbool}, {"tracing_orphaned_queue_flush_interval", LCB_CNTL_TRACING_ORPHANED_QUEUE_FLUSH_INTERVAL, convert_timevalue}, {"tracing_orphaned_queue_size", LCB_CNTL_TRACING_ORPHANED_QUEUE_SIZE, convert_u32}, {"tracing_threshold_queue_flush_interval", LCB_CNTL_TRACING_THRESHOLD_QUEUE_FLUSH_INTERVAL, convert_timevalue}, {"tracing_threshold_queue_size", LCB_CNTL_TRACING_THRESHOLD_QUEUE_SIZE, convert_u32}, {"tracing_threshold_kv", LCB_CNTL_TRACING_THRESHOLD_KV, convert_timevalue}, {"tracing_threshold_search", LCB_CNTL_TRACING_THRESHOLD_QUERY, convert_timevalue}, {"tracing_threshold_view", LCB_CNTL_TRACING_THRESHOLD_VIEW, convert_timevalue}, {"tracing_threshold_search", LCB_CNTL_TRACING_THRESHOLD_SEARCH, convert_timevalue}, {"tracing_threshold_analytics", LCB_CNTL_TRACING_THRESHOLD_ANALYTICS, convert_timevalue}, {"compression_min_size", LCB_CNTL_COMPRESSION_MIN_SIZE, convert_u32}, {"compression_min_ratio", LCB_CNTL_COMPRESSION_MIN_RATIO, convert_float}, {"vb_noremap", LCB_CNTL_VB_NOREMAP, convert_intbool}, {"network", LCB_CNTL_NETWORK, convert_passthru}, {"wait_for_config", LCB_CNTL_WAIT_FOR_CONFIG, convert_intbool}, {"http_pool_timeout", LCB_CNTL_HTTP_POOL_TIMEOUT, convert_timevalue}, {"enable_collections", LCB_CNTL_ENABLE_COLLECTIONS, convert_intbool}, {"enable_durable_write", LCB_CNTL_ENABLE_DURABLE_WRITE, convert_intbool}, {"persistence_timeout_floor", LCB_CNTL_PERSISTENCE_TIMEOUT_FLOOR, convert_timevalue}, {"allow_static_config", LCB_CNTL_ALLOW_STATIC_CONFIG, convert_intbool}, {NULL, -1}}; #define CNTL_NUM_HANDLERS (sizeof(handlers) / sizeof(handlers[0])) static lcb_STATUS wrap_return(lcb_INSTANCE *instance, lcb_STATUS retval) { if (retval == LCB_SUCCESS) { return retval; } if (instance && LCBT_SETTING(instance, detailed_neterr) == 0) { switch (retval) { case LCB_ERR_CONTROL_UNKNOWN_CODE: return LCB_ERR_UNSUPPORTED_OPERATION; case LCB_ERR_CONTROL_UNSUPPORTED_MODE: return LCB_ERR_UNSUPPORTED_OPERATION; case LCB_ERR_CONTROL_INVALID_ARGUMENT: return LCB_ERR_INVALID_ARGUMENT; default: return retval; } } else { return retval; } } LIBCOUCHBASE_API lcb_STATUS lcb_cntl(lcb_INSTANCE *instance, int mode, int cmd, void *arg) { ctl_handler handler; if (cmd >= (int)CNTL_NUM_HANDLERS || cmd < 0) { return wrap_return(instance, LCB_ERR_CONTROL_UNKNOWN_CODE); } handler = handlers[cmd]; if (!handler) { return wrap_return(instance, LCB_ERR_CONTROL_UNKNOWN_CODE); } return wrap_return(instance, handler(mode, instance, cmd, arg)); } LIBCOUCHBASE_API lcb_STATUS lcb_cntl_string(lcb_INSTANCE *instance, const char *key, const char *value) { cntl_OPCODESTRS *cur; u_STRCONVERT u; lcb_STATUS err; for (cur = stropcode_map; cur->key; cur++) { if (!strcmp(cur->key, key)) { if (cur->opcode < 0) { return LCB_ERR_CONTROL_UNKNOWN_CODE; } if (cur->converter) { err = cur->converter(value, &u); if (err != LCB_SUCCESS) { return err; } if (cur->converter == convert_passthru) { return lcb_cntl(instance, LCB_CNTL_SET, cur->opcode, u.p); } else { return lcb_cntl(instance, LCB_CNTL_SET, cur->opcode, &u); } } return lcb_cntl(instance, CNTL__MODE_SETSTRING, cur->opcode, (void *)value); } } return wrap_return(instance, LCB_ERR_UNSUPPORTED_OPERATION); } LIBCOUCHBASE_API int lcb_cntl_exists(int ctl) { if (ctl >= (int)CNTL_NUM_HANDLERS || ctl < 0) { return 0; } return handlers[ctl] != NULL; } LIBCOUCHBASE_API lcb_STATUS lcb_cntl_setu32(lcb_INSTANCE *instance, int cmd, lcb_uint32_t arg) { return lcb_cntl(instance, LCB_CNTL_SET, cmd, &arg); } LIBCOUCHBASE_API lcb_uint32_t lcb_cntl_getu32(lcb_INSTANCE *instance, int cmd) { lcb_uint32_t ret = 0; lcb_cntl(instance, LCB_CNTL_GET, cmd, &ret); return ret; }
[ "brett19@gmail.com" ]
brett19@gmail.com
edda90b90b0eebd028412a06bf4ab005ee8c73b4
3e093521306ac955f65ad7648dfe2dbc649c7e4d
/tests/Mocks/Servers.cpp
902fd864b279e88e4c20961011cf3440cd9a37fc
[ "Apache-2.0", "LGPL-2.1-or-later", "BSD-3-Clause", "Bison-exception-2.2", "JSON", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "GPL-1.0-or-later", "ISC", "ICU", "GPL-2.0-only", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "Licen...
permissive
Simran-B/arangodb_test
8836e89af5bfcf156aaf643ab1ab1f48c38c0eb6
e643ddbaa8327249ae5f10add89ab9e6d9f6fecd
refs/heads/devel
2021-10-24T18:45:11.844512
2019-03-11T13:28:44
2019-03-11T13:28:44
174,999,262
0
1
Apache-2.0
2019-03-11T13:27:59
2019-03-11T12:51:28
C++
UTF-8
C++
false
false
6,886
cpp
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2018 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include "Servers.h" #include "ApplicationFeatures/ApplicationFeature.h" #include "Aql/AqlFunctionFeature.h" #include "Aql/OptimizerRulesFeature.h" #include "Aql/Query.h" #include "GeneralServer/AuthenticationFeature.h" #include "Logger/Logger.h" #include "Logger/LogTopic.h" #include "IResearch/IResearchCommon.h" #include "IResearch/IResearchAnalyzerFeature.h" #include "IResearch/IResearchFeature.h" #include "RestServer/AqlFeature.h" #include "RestServer/DatabaseFeature.h" #include "RestServer/DatabasePathFeature.h" #include "RestServer/QueryRegistryFeature.h" #include "RestServer/SystemDatabaseFeature.h" #include "RestServer/TraverserEngineRegistryFeature.h" #include "RestServer/ViewTypesFeature.h" #include "StorageEngine/EngineSelectorFeature.h" #include "Sharding/ShardingFeature.h" #include "Transaction/Methods.h" #include "Transaction/StandaloneContext.h" #include "VocBase/vocbase.h" #include "utils/log.hpp" #if USE_ENTERPRISE #include "Enterprise/Ldap/LdapFeature.h" #endif using namespace arangodb; using namespace arangodb::tests; using namespace arangodb::tests::mocks; MockServer::MockServer() : _server(nullptr, nullptr), _engine(_server) { arangodb::EngineSelectorFeature::ENGINE = &_engine; init(); } MockServer::~MockServer() { _system.reset(); // destroy before reseting the 'ENGINE' arangodb::application_features::ApplicationServer::server = nullptr; arangodb::EngineSelectorFeature::ENGINE = nullptr; stopFeatures(); } void MockServer::init() { arangodb::transaction::Methods::clearDataSourceRegistrationCallbacks(); } void MockServer::startFeatures() { for (auto& f : _features) { arangodb::application_features::ApplicationServer::server->addFeature(f.first); } for (auto& f : _features) { f.first->prepare(); } for (auto& f : _features) { if (f.second) { f.first->start(); } } } void MockServer::stopFeatures() { // destroy application features for (auto& f : _features) { if (f.second) { f.first->stop(); } } for (auto& f : _features) { f.first->unprepare(); } } TRI_vocbase_t& MockServer::getSystemDatabase() const { TRI_ASSERT(_system != nullptr); return *(_system.get()); } MockAqlServer::MockAqlServer() : MockServer() { // suppress INFO {authentication} Authentication is turned on (system only), authentication for unix sockets is turned on arangodb::LogTopic::setLogLevel(arangodb::Logger::AUTHENTICATION.name(), arangodb::LogLevel::WARN); // suppress log messages since tests check error conditions arangodb::LogTopic::setLogLevel(arangodb::Logger::FIXME.name(), arangodb::LogLevel::ERR); // suppress WARNING DefaultCustomTypeHandler called arangodb::LogTopic::setLogLevel(arangodb::iresearch::TOPIC.name(), arangodb::LogLevel::FATAL); irs::logger::output_le(::iresearch::logger::IRL_FATAL, stderr); // setup required application features _features.emplace_back(new arangodb::ViewTypesFeature(_server), true); _features.emplace_back(new arangodb::AuthenticationFeature(_server), true); _features.emplace_back(new arangodb::DatabasePathFeature(_server), false); _features.emplace_back(new arangodb::DatabaseFeature(_server), false); _features.emplace_back(new arangodb::ShardingFeature(_server), true); _features.emplace_back(new arangodb::QueryRegistryFeature(_server), false); // must be first arangodb::application_features::ApplicationServer::server->addFeature(_features.back().first); // need QueryRegistryFeature feature to be added now in order to create the system database _system = std::make_unique<TRI_vocbase_t>(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL, 0, TRI_VOC_SYSTEM_DATABASE); _features.emplace_back(new arangodb::SystemDatabaseFeature(_server, _system.get()), false); // required for IResearchAnalyzerFeature _features.emplace_back(new arangodb::TraverserEngineRegistryFeature(_server), false); // must be before AqlFeature _features.emplace_back(new arangodb::AqlFeature(_server), true); _features.emplace_back(new arangodb::aql::OptimizerRulesFeature(_server), true); _features.emplace_back(new arangodb::aql::AqlFunctionFeature(_server), true); // required for IResearchAnalyzerFeature _features.emplace_back(new arangodb::iresearch::IResearchAnalyzerFeature(_server), true); _features.emplace_back(new arangodb::iresearch::IResearchFeature(_server), true); #if USE_ENTERPRISE _features.emplace_back(new arangodb::LdapFeature(_server), false); // required for AuthenticationFeature with USE_ENTERPRISE #endif startFeatures(); } MockAqlServer::~MockAqlServer() { arangodb::AqlFeature(_server).stop(); // unset singleton instance arangodb::LogTopic::setLogLevel(arangodb::iresearch::TOPIC.name(), arangodb::LogLevel::DEFAULT); arangodb::LogTopic::setLogLevel(arangodb::Logger::FIXME.name(), arangodb::LogLevel::DEFAULT); arangodb::LogTopic::setLogLevel(arangodb::Logger::AUTHENTICATION.name(), arangodb::LogLevel::DEFAULT); } arangodb::transaction::Methods* MockAqlServer::createFakeTransaction() const { std::vector<std::string> noCollections{}; transaction::Options opts; return new arangodb::transaction::Methods(transaction::StandaloneContext::Create( getSystemDatabase()), noCollections, noCollections, noCollections, opts); } std::unique_ptr<arangodb::aql::Query> MockAqlServer::createFakeQuery() const { auto bindParams = std::make_shared<VPackBuilder>(); bindParams->openObject(); bindParams->close(); auto queryOptions = std::make_shared<VPackBuilder>(); queryOptions->openObject(); queryOptions->close(); aql::QueryString fakeQueryString(""); auto query = std::make_unique<arangodb::aql::Query>( false, getSystemDatabase(), fakeQueryString, bindParams, queryOptions, arangodb::aql::QueryPart::PART_DEPENDENT); query->injectTransaction(createFakeTransaction()); return query; }
[ "michael@arangodb.com" ]
michael@arangodb.com
d717ed0e0a5f19c209ad28d224fde83326a317f0
2e1fe5afefd534848e3a3c1f8d65cc58463cb753
/drawView.h
51ce5877a438232a1f882db8690f330c035dfbd1
[]
no_license
tianskylan/Painting-Application
05ccd4a95f074bfcfd9e5bc43bcbdee2a301101f
00032490c448d067d801e0925d8f5d8660c2b017
refs/heads/master
2021-01-22T11:12:06.552118
2016-02-28T18:20:11
2016-02-28T18:20:11
19,564,178
0
1
null
2016-02-28T18:20:11
2014-05-08T07:13:27
C++
UTF-8
C++
false
false
1,683
h
// drawView.h : interface of the CDrawView class // ///////////////////////////////////////////////////////////////////////////// #pragma once #include <memory> #include "Shape.h" #include <list> #include "ShapeMaker.h" #include "PenWeight.h" class CDrawView : public CScrollWindowImpl<CDrawView> { public: DECLARE_WND_CLASS(NULL) BOOL PreTranslateMessage(MSG* pMsg); BEGIN_MSG_MAP(CDrawView) MESSAGE_HANDLER(WM_PAINT, OnPaint) MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp) MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove) CHAIN_MSG_MAP(CScrollWindowImpl<CDrawView>) END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnLButtonUp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnMouseMove(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); CDrawView(); Gdiplus::Bitmap m_BitmapImage; Gdiplus::Graphics m_GraphicsImage; Gdiplus::Point m_start; Gdiplus::Point m_end; Gdiplus::Pen m_Pen; std::shared_ptr<Shape> shape; // current shape being drawn std::list<std::shared_ptr<Shape>> undo_list; std::list<std::shared_ptr<Shape>> redo_list; int current_shape; bool saved_or_loaded; std::string filename; };
[ "4dreams.sky@gmail.com" ]
4dreams.sky@gmail.com
fd8f15272acbcd933b7084947135a7026cf970e8
ec89e41ca41970c0704a80544f5f579f3fc42cb3
/internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Display.2.h
304ee4d1cecc7917c1bc994cd5b8fbeb4cafb2db
[ "Apache-2.0" ]
permissive
google/nearby
0feeea41a96dd73d9d1b8c06e101622411e770c5
55194622a7b7e9066f80f90675b06eb639612161
refs/heads/main
2023-08-17T01:36:13.900851
2023-08-17T01:11:43
2023-08-17T01:13:11
258,325,401
425
94
Apache-2.0
2023-09-14T16:40:13
2020-04-23T20:41:37
C++
UTF-8
C++
false
false
901
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.220531.1 #pragma once #ifndef WINRT_Windows_Devices_Display_2_H #define WINRT_Windows_Devices_Display_2_H #include "winrt/impl/Windows.Devices.Display.1.h" WINRT_EXPORT namespace winrt::Windows::Devices::Display { struct __declspec(empty_bases) DisplayMonitor : winrt::Windows::Devices::Display::IDisplayMonitor, impl::require<DisplayMonitor, winrt::Windows::Devices::Display::IDisplayMonitor2> { DisplayMonitor(std::nullptr_t) noexcept {} DisplayMonitor(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Devices::Display::IDisplayMonitor(ptr, take_ownership_from_abi) {} static auto GetDeviceSelector(); static auto FromIdAsync(param::hstring const& deviceId); static auto FromInterfaceIdAsync(param::hstring const& deviceInterfaceId); }; } #endif
[ "copybara-worker@google.com" ]
copybara-worker@google.com
6c6041e24cd6fa49abcdc562cc83c2be06a03258
68c2c9f85e79fb2ce4fd3bb90d857b8be5bf9520
/mathclass/include/point3.h
44d04b3b9c12b23634d1c9f3f5ff787dd2c192ae
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
mori-inj/Graphics
556e6b7f7f722ec71f5ec5ede462e2e2b132f6a9
4923736e43f782e242f835074e8f67cb7653afd9
refs/heads/master
2021-01-01T16:47:37.426078
2019-06-13T20:25:47
2019-06-13T20:25:47
97,922,371
0
1
null
null
null
null
UTF-8
C++
false
false
1,988
h
// +------------------------------------------------------------------------- // | point3.h // | // | Author: Jehee Lee // +------------------------------------------------------------------------- // | COPYRIGHT: // | Copyright Jehee Lee 2013 // | See the included COPYRIGHT.txt file for further details. // | // | This file is part of the MATHCLASS. // | MATHCLASS is free software: you can redistribute it and/or modify // | it under the terms of the MIT License. // | // | You should have received a copy of the MIT License // | along with MATHCLASS. If not, see <mit-license.org>. // +------------------------------------------------------------------------- #ifndef POINT3_H #define POINT3_H namespace jhm { class point3 { private: int p[3]; // negation friend point3 operator-( point3 const& ); // addtion friend point3& operator+=( point3&, point3 const& ); friend point3 operator+( point3 const&, point3 const& ); // subtraction friend point3 operator-( point3 const&, point3 const& ); friend point3& operator-=( point3&, point3 const& ); public: // constructors point3() {} point3( int x, int y, int z ) { p[0]=x; p[1]=y; p[2]=z; } point3( int a[3] ) { p[0]=a[0]; p[1]=a[1]; p[2]=a[2]; } // inquiry functions int& operator[](int i) { return p[i]; } int x() const { return p[0]; }; int y() const { return p[1]; }; int z() const { return p[2]; }; void getValue( int d[2] ) { d[0]=p[0]; d[1]=p[1]; d[2]=p[2]; } void setValue( int d[2] ) { p[0]=d[0]; p[1]=d[1]; p[2]=d[2]; } int getValue( int n ) const { return p[n]; } point3 setValue( int x, int y, int z ) { p[0]=x, p[1]=y; p[2]=z; return *this; } int setValue( int n, int x ) { return p[n]=x; } m_real length() const; // change functions void set_x( int x ) { p[0]=x; }; void set_y( int y ) { p[1]=y; }; void set_z( int z ) { p[2]=z; }; }; } #endif
[ "leokim1022@snu.ac.kr" ]
leokim1022@snu.ac.kr
6bc03fad20bf2d8320f309594eae75d9b9763d28
c6bddd88916e6c8697a9e02485bd22c58d76bcec
/GeneratedPlaceholders/Engine/BlueprintAsyncActionBase.h
e94929eeab0c3d28004c7e553d5f8de0f5f92bc7
[]
no_license
GIRU-GIRU/Mordhau-Unofficial-SDK
18d13d62d746a838820e387907d13b0a37aed654
f831d7355cf553b81fb6e82468b3abf68f7955aa
refs/heads/master
2020-07-06T03:36:48.908227
2020-04-22T13:54:00
2020-04-22T13:54:00
202,872,898
7
4
null
null
null
null
UTF-8
C++
false
false
265
h
#pragma once #include "CoreMinimal.h" #include "BlueprintAsyncActionBase.generated.h" UCLASS() class UBlueprintAsyncActionBase : public UObject { GENERATED_BODY() public: UFUNCTION(BlueprintCallable, Category = "BlueprintAsyncActionBase") void Activate(); };
[ "45307738+crypdos@users.noreply.github.com" ]
45307738+crypdos@users.noreply.github.com
2741d651b8aceaf7bc5be58975c358ab15764a6c
bc2347b87e3b000282ab32e37c154e7bc3647539
/source/basic_path_tracer/main.cpp
c089bf942136bac5ba2bc218d35633f9910727ba
[ "Apache-2.0" ]
permissive
Nuos/rapt
67c5cc6acb1cb2a2b0f6753fd33370be8e5dc277
9469012a0a339241b972c146e60f33e8d12730f2
refs/heads/master
2021-01-11T02:59:53.932122
2015-04-10T01:36:51
2015-04-10T01:36:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
984
cpp
/* rapt - RichieSam's Adventures in Path Tracing * * rapt is the legal property of Adrian Astley * Copyright Adrian Astley 2015 */ #include "basic_path_tracer/basic_path_tracer.h" #include "graphics/d3d_util.h" int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { DBG_UNREFERENCED_PARAMETER(hPrevInstance); DBG_UNREFERENCED_PARAMETER(lpCmdLine); DBG_UNREFERENCED_PARAMETER(nCmdShow); #ifdef _DEBUG ID3D11Debug *debugInterface = nullptr; #endif // Force scope so we can guarantee the destructor is called before we try to use ReportLiveDeviceObjects { BasicPathTracer::BasicPathTracer app(hInstance); app.Initialize(L"Basic Path Tracer", 1280, 720, false); #ifdef _DEBUG app.CreateDebugInterface(&debugInterface); #endif app.Run(); app.Shutdown(); } #ifdef _DEBUG debugInterface->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL); ReleaseCOM(debugInterface); #endif return 0; }
[ "adastley@gmail.com" ]
adastley@gmail.com
c8e2a747917f630143f7a73282aa15e4a034bc3f
5390eac0ac54d2c3c1c664ae525881fa988e2cf9
/include/Pothos/serialization/impl/mpl/apply.hpp
c92459bf8eded3f6e8d99c54cace48bb4876c174
[ "BSL-1.0" ]
permissive
pothosware/pothos-serialization
2935b8ab1fe51299a6beba2a3e11611928186849
c59130f916a3e5b833a32ba415063f9cb306a8dd
refs/heads/master
2021-08-16T15:22:12.642058
2015-12-10T03:32:04
2015-12-10T03:32:04
19,961,886
1
0
null
null
null
null
UTF-8
C++
false
false
6,715
hpp
#if !defined(POTHOS_PP_IS_ITERATING) ///// header body #ifndef POTHOS_MPL_APPLY_HPP_INCLUDED #define POTHOS_MPL_APPLY_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: apply.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $ // $Revision: 49267 $ #if !defined(POTHOS_MPL_PREPROCESSING_MODE) # include <Pothos/serialization/impl/mpl/apply_fwd.hpp> # include <Pothos/serialization/impl/mpl/apply_wrap.hpp> # include <Pothos/serialization/impl/mpl/placeholders.hpp> # include <Pothos/serialization/impl/mpl/lambda.hpp> # include <Pothos/serialization/impl/mpl/aux_/na.hpp> # include <Pothos/serialization/impl/mpl/aux_/lambda_support.hpp> #endif #include <Pothos/serialization/impl/mpl/aux_/config/use_preprocessed.hpp> #if !defined(POTHOS_MPL_CFG_NO_PREPROCESSED_HEADERS) \ && !defined(POTHOS_MPL_PREPROCESSING_MODE) # define POTHOS_MPL_PREPROCESSED_HEADER apply.hpp # include <Pothos/serialization/impl/mpl/aux_/include_preprocessed.hpp> #else # include <Pothos/serialization/impl/mpl/limits/arity.hpp> # include <Pothos/serialization/impl/mpl/aux_/preprocessor/params.hpp> # include <Pothos/serialization/impl/mpl/aux_/preprocessor/default_params.hpp> # include <Pothos/serialization/impl/mpl/aux_/preprocessor/partial_spec_params.hpp> # include <Pothos/serialization/impl/mpl/aux_/preprocessor/enum.hpp> # include <Pothos/serialization/impl/mpl/aux_/config/lambda.hpp> # include <Pothos/serialization/impl/mpl/aux_/config/dtp.hpp> # include <Pothos/serialization/impl/mpl/aux_/nttp_decl.hpp> # include <Pothos/serialization/impl/mpl/aux_/config/eti.hpp> # include <Pothos/serialization/impl/mpl/aux_/config/msvc.hpp> # include <Pothos/serialization/impl/mpl/aux_/config/workaround.hpp> # include <Pothos/serialization/impl/preprocessor/comma_if.hpp> # include <Pothos/serialization/impl/preprocessor/inc.hpp> # include <Pothos/serialization/impl/preprocessor/iterate.hpp> # include <Pothos/serialization/impl/preprocessor/cat.hpp> namespace Pothos { namespace mpl { // local macros, #undef-ined at the end of the header # define AUX778076_APPLY_PARAMS(param) \ POTHOS_MPL_PP_PARAMS( \ POTHOS_MPL_LIMIT_METAFUNCTION_ARITY \ , param \ ) \ /**/ # define AUX778076_APPLY_DEF_PARAMS(param, value) \ POTHOS_MPL_PP_DEFAULT_PARAMS( \ POTHOS_MPL_LIMIT_METAFUNCTION_ARITY \ , param \ , value \ ) \ /**/ # define AUX778076_APPLY_N_PARAMS(n, param) \ POTHOS_MPL_PP_PARAMS(n, param) \ /**/ # define AUX778076_APPLY_N_COMMA_PARAMS(n, param) \ POTHOS_PP_COMMA_IF(n) \ POTHOS_MPL_PP_PARAMS(n, param) \ /**/ # define AUX778076_APPLY_N_PARTIAL_SPEC_PARAMS(n, param, def) \ POTHOS_PP_COMMA_IF(n) \ POTHOS_MPL_PP_PARTIAL_SPEC_PARAMS(n, param, def) \ /**/ # define AUX778076_APPLY_N_SPEC_PARAMS(n, param) \ POTHOS_MPL_PP_ENUM(POTHOS_PP_INC(n), param) \ /**/ #define POTHOS_PP_ITERATION_PARAMS_1 \ (3,(0, POTHOS_MPL_LIMIT_METAFUNCTION_ARITY, <boost/mpl/apply.hpp>)) #include POTHOS_PP_ITERATE() # if !defined(POTHOS_MPL_CFG_NO_APPLY_TEMPLATE) // real C++ version is already taken care of # if defined(POTHOS_NO_TEMPLATE_PARTIAL_SPECIALIZATION) namespace aux { // apply_count_args #define AUX778076_COUNT_ARGS_PREFIX apply #define AUX778076_COUNT_ARGS_DEFAULT na #define AUX778076_COUNT_ARGS_ARITY POTHOS_MPL_LIMIT_METAFUNCTION_ARITY #include <Pothos/serialization/impl/mpl/aux_/count_args.hpp> } template< typename F, AUX778076_APPLY_DEF_PARAMS(typename T, na) > struct apply : aux::apply_chooser< aux::apply_count_args< AUX778076_APPLY_PARAMS(T) >::value >::template result_< F, AUX778076_APPLY_PARAMS(T) >::type { }; # endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION # endif // BOOST_MPL_CFG_NO_APPLY_TEMPLATE # undef AUX778076_APPLY_N_SPEC_PARAMS # undef AUX778076_APPLY_N_PARTIAL_SPEC_PARAMS # undef AUX778076_APPLY_N_COMMA_PARAMS # undef AUX778076_APPLY_N_PARAMS # undef AUX778076_APPLY_DEF_PARAMS # undef AUX778076_APPLY_PARAMS }} #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #endif // BOOST_MPL_APPLY_HPP_INCLUDED ///// iteration, depth == 1 // For gcc 4.4 compatability, we must include the // BOOST_PP_ITERATION_DEPTH test inside an #else clause. #else // BOOST_PP_IS_ITERATING #if POTHOS_PP_ITERATION_DEPTH() == 1 # define i_ POTHOS_PP_FRAME_ITERATION(1) template< typename F AUX778076_APPLY_N_COMMA_PARAMS(i_, typename T) > struct POTHOS_PP_CAT(apply,i_) #if !POTHOS_WORKAROUND(POTHOS_MSVC, < 1300) : POTHOS_PP_CAT(apply_wrap,i_)< typename lambda<F>::type AUX778076_APPLY_N_COMMA_PARAMS(i_, T) > { #else { typedef typename POTHOS_PP_CAT(apply_wrap,i_)< typename lambda<F>::type AUX778076_APPLY_N_COMMA_PARAMS(i_, T) >::type type; #endif POTHOS_MPL_AUX_LAMBDA_SUPPORT( POTHOS_PP_INC(i_) , POTHOS_PP_CAT(apply,i_) , (F AUX778076_APPLY_N_COMMA_PARAMS(i_,T)) ) }; #if defined(POTHOS_MPL_CFG_MSVC_ETI_BUG) /// workaround for ETI bug template<> struct POTHOS_PP_CAT(apply,i_)<AUX778076_APPLY_N_SPEC_PARAMS(i_, int)> { typedef int type; }; #endif # if !defined(POTHOS_MPL_CFG_NO_APPLY_TEMPLATE) # if !defined(POTHOS_NO_TEMPLATE_PARTIAL_SPECIALIZATION) #if i_ == POTHOS_MPL_LIMIT_METAFUNCTION_ARITY /// primary template (not a specialization!) template< typename F AUX778076_APPLY_N_COMMA_PARAMS(i_, typename T) > struct apply : POTHOS_PP_CAT(apply,i_)< F AUX778076_APPLY_N_COMMA_PARAMS(i_, T) > { }; #else template< typename F AUX778076_APPLY_N_COMMA_PARAMS(i_, typename T) > struct apply< F AUX778076_APPLY_N_PARTIAL_SPEC_PARAMS(i_, T, na) > : POTHOS_PP_CAT(apply,i_)< F AUX778076_APPLY_N_COMMA_PARAMS(i_, T) > { }; #endif # else // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION #if !defined(POTHOS_MPL_CFG_NO_APPLY_TEMPLATE) namespace aux { template<> struct apply_chooser<i_> { template< typename F, AUX778076_APPLY_PARAMS(typename T) > struct result_ { typedef POTHOS_PP_CAT(apply,i_)< F AUX778076_APPLY_N_COMMA_PARAMS(i_, T) > type; }; }; } // namespace aux #endif # endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION # endif // BOOST_MPL_CFG_NO_APPLY_TEMPLATE # undef i_ #endif // BOOST_PP_ITERATION_DEPTH() #endif // BOOST_PP_IS_ITERATING
[ "josh@joshknows.com" ]
josh@joshknows.com
3e943e0ab9ce33bf0aceb69cc1881c893c257515
2f0032ea310a5d455f54c3f9c646abe3750153d1
/Elapsedtime/Elapsedtime.ino
259460d15b6adbce7d4cf98a548886466a94dc15
[]
no_license
Adamsmith6300/arduino-stuff
203f5c819213e103d830483d847e6fe6a3106f67
e2ef5d82a7a10bab1c0108cc3b16104131c6bfa0
refs/heads/master
2020-03-19T03:51:54.901584
2020-01-06T20:30:53
2020-01-06T20:30:53
135,769,959
0
0
null
null
null
null
UTF-8
C++
false
false
340
ino
int seconds; int minutes; void setup() { // put your setup code here, to run once: seconds = 0; minutes = 0; Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: Serial.print(minutes); Serial.print(":"); Serial.println(seconds); delay(1000); seconds++; if(seconds == 60) { minutes++; seconds = 0; } }
[ "Adamsmith6300@gmail.com" ]
Adamsmith6300@gmail.com
d3f11f2a470516a659ac2b1328eb02a4894aff2b
157fd7fe5e541c8ef7559b212078eb7a6dbf51c6
/TRiAS/TRiASDB/TRiASMI/mitab-1.0.1/ogr/ogrsf_frmts.h
f7dd59417a2e1e1546ee9f020c4e7cab7b01667c
[ "MIT" ]
permissive
15831944/TRiAS
d2bab6fd129a86fc2f06f2103d8bcd08237c49af
840946b85dcefb34efc219446240e21f51d2c60d
refs/heads/master
2020-09-05T05:56:39.624150
2012-11-11T02:24:49
2012-11-11T02:24:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,753
h
/****************************************************************************** * $Id: ogrsf_frmts.h,v 1.4 1999/11/04 21:38:50 warmerda Exp $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Classes related to format registration, and file opening. * Author: Frank Warmerdam, warmerda@home.com * ****************************************************************************** * Copyright (c) 1999, Les Technologies SoftMap Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * * $Log: ogrsf_frmts.h,v $ * Revision 1.4 1999/11/04 21:38:50 warmerda * reimported * * Revision 1.11 1999/11/04 21:09:40 warmerda * Made a bunch of changes related to supporting creation of new * layers and data sources. * * Revision 1.10 1999/10/06 19:02:43 warmerda * Added tiger registration. * * Revision 1.9 1999/09/22 03:05:08 warmerda * added SDTS * * Revision 1.8 1999/09/09 21:04:55 warmerda * added fme support * * Revision 1.7 1999/08/28 03:12:43 warmerda * Added NTF. * * Revision 1.6 1999/07/27 00:50:39 warmerda * added a number of OGRLayer methods * * Revision 1.5 1999/07/26 13:59:05 warmerda * added feature writing api * * Revision 1.4 1999/07/21 13:23:27 warmerda * Fixed multiple inclusion protection. * * Revision 1.3 1999/07/08 20:04:58 warmerda * added GetFeatureCount * * Revision 1.2 1999/07/06 20:25:09 warmerda * added some documentation * * Revision 1.1 1999/07/05 18:59:00 warmerda * new * */ #ifndef _OGRSF_FRMTS_H_INCLUDED #define _OGRSF_FRMTS_H_INCLUDED #include "ogr_feature.h" /** * \file ogrsf_frmts.h * * Classes related to registration of format support, and opening datasets. */ #define OLCRandomRead "RandomRead" #define OLCSequentialWrite "SequentialWrite" #define OLCRandomWrite "RandomWrite" #define OLCFastSpatialFilter "FastSpatialFilter" #define OLCFastFeatureCount "FastFeatureCount" #define OLCCreateField "CreateField" #define ODsCCreateLayer "CreateLayer" #define ODrCCreateDataSource "CreateDataSource" /************************************************************************/ /* OGRLayer */ /************************************************************************/ /** * This class represents a layer of simple features, with access methods. * */ class OGRLayer { public: virtual ~OGRLayer() {} virtual OGRGeometry *GetSpatialFilter() = 0; virtual void SetSpatialFilter( OGRGeometry * ) = 0; virtual void ResetReading() = 0; virtual OGRFeature *GetNextFeature() = 0; virtual OGRFeature *GetFeature( long nFID ); virtual OGRErr SetFeature( OGRFeature *poFeature ); virtual OGRErr CreateFeature( OGRFeature *poFeature ); virtual OGRFeatureDefn *GetLayerDefn() = 0; virtual OGRSpatialReference *GetSpatialRef() { return NULL; } virtual int GetFeatureCount( int bForce = TRUE ); virtual int TestCapability( const char * ) = 0; virtual const char *GetInfo( const char * ); virtual OGRErr CreateField( OGRFieldDefn *poField, int bApproxOK = TRUE ); }; /************************************************************************/ /* OGRDataSource */ /************************************************************************/ /** * This class represents a data source. A data source potentially * consists of many layers (OGRLayer). A data source normally consists * of one, or a related set of files, though the name doesn't have to be * a real item in the file system. * * When an OGRDataSource is destroyed, all it's associated OGRLayers objects * are also destroyed. */ class OGRDataSource { public: virtual ~OGRDataSource(); virtual const char *GetName() = 0; virtual int GetLayerCount() = 0; virtual OGRLayer *GetLayer(int) = 0; virtual int TestCapability( const char * ) = 0; virtual OGRLayer *CreateLayer( const char *, OGRSpatialReference * = NULL, OGRwkbGeometryType = wkbUnknown, char ** = NULL ); }; /************************************************************************/ /* OGRSFDriver */ /************************************************************************/ /** * Represents an operational format driver. * * One OGRSFDriver derived class will normally exist for each file format * registered for use, regardless of whether a file has or will be opened. * The list of available drivers is normally managed by the * OGRSFDriverRegistrar. */ class OGRSFDriver { public: virtual ~OGRSFDriver(); virtual const char *GetName() = 0; virtual OGRDataSource *Open( const char *pszName, int bUpdate=FALSE ) = 0; virtual int TestCapability( const char * ) = 0; virtual OGRDataSource *CreateDataSource( const char *pszName, char ** = NULL ); }; /************************************************************************/ /* OGRSFDriverRegistrar */ /************************************************************************/ /** * Singleton manager for drivers. * */ class OGRSFDriverRegistrar { int nDrivers; OGRSFDriver **papoDrivers; OGRSFDriverRegistrar(); public: ~OGRSFDriverRegistrar(); static OGRSFDriverRegistrar *GetRegistrar(); static OGRDataSource *Open( const char *pszName, int bUpdate=FALSE, OGRSFDriver ** ppoDriver = NULL ); void RegisterDriver( OGRSFDriver * ); int GetDriverCount( void ); OGRSFDriver *GetDriver( int ); }; /* -------------------------------------------------------------------- */ /* Various available registration methods. */ /* -------------------------------------------------------------------- */ CPL_C_START void OGRRegisterAll(); void RegisterOGRShape(); void RegisterOGRNTF(); void RegisterOGRSDTS(); void RegisterOGRTiger(); void RegisterOGRS57(); CPL_C_END #endif /* ndef _OGRSF_FRMTS_H_INCLUDED */
[ "Windows Live ID\\hkaiser@cct.lsu.edu" ]
Windows Live ID\hkaiser@cct.lsu.edu
41c258a2bf52d5e0bb34b1c7ed5fa25f7eafdb45
ae4d9cf742b9f6e5024bcd5bdf4b4473558da9e3
/_PSmine/PS모음/boj/11399.cpp
53cb114af4a7967b507c5dc43fc7861f52fd44dc
[]
no_license
son0179/ttt
b6d171141e0b7894258cfb367023de62cdc9dd19
a5153b0170c0df156c96d9be85b21d73f1f2e21e
refs/heads/master
2023-02-09T22:01:57.658467
2021-01-05T09:14:52
2021-01-05T09:14:52
200,059,589
1
0
null
null
null
null
UTF-8
C++
false
false
379
cpp
#include<stdio.h> int main() { int n,p[1000]={0},s[1000]={0},hap=0; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d",&p[i]); } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(p[i]>p[j]){ int tmp=p[i]; p[i]=p[j]; p[j]=tmp; } } } s[0]=p[0]; for(int i=1;i<n;i++){ s[i]=s[i-1]+p[i]; } for(int i=0;i<n;i++){ hap+=s[i]; } printf("%d",hap); }
[ "starson2648@gmail.com" ]
starson2648@gmail.com
d960463889dc2a6e5708814a49de7dce2c64976f
ba6ef4e867d6b611b0058fc8d33a72ca6074e02a
/tools/textfuns.cpp
6d41336ab02683e3920885dbe680ff9b1ffefb95
[]
no_license
Proxmiff/XaraVG-lib
3d3f8c9d8176678a887672ab251b593e3913988c
8fd443b42c94c9fce26e4e4337dec4647756c530
refs/heads/master
2021-01-11T13:33:51.866796
2016-05-14T14:48:36
2016-05-14T14:48:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,534
cpp
// Implementation of the TEXT tool #include "camtypes.h" #include "textfuns.h" #include "camelot.h" #include "fontman.h" #ifndef EXCLUDE_FROM_XARALX #include "atmfonts.h" #endif #include "unicdman.h" DECLARE_SOURCE( "$Revision$" ); CC_IMPLEMENT_MEMDUMP( CharMetrics, CC_CLASS_MEMDUMP ); #define new CAM_DEBUG_NEW ///////////////////////////////////////////////////////////////////////////////////////////// // CharMetrics /*************************************************************************************** > CharMetrics::CharMetrics() Author: Ed_Cornes (Xara Group Ltd) <camelotdev@xara.com> Created: 15/1/96 Purpose: default constructorGet the path associated with a given char ********************************************************************************************/ CharMetrics::CharMetrics() { CharWidth = 0; FontAscent = 0; FontDescent = 0; FontEmWidth = 0; } /*************************************************************************************** > BOOL CharMetrics::Scale(double ScaleX, double ScaleY) Author: Ed_Cornes (Xara Group Ltd) <camelotdev@xara.com> Created: 17/1/96 Inputs: ScaleX - ScaleY - Purpose: Scale the metrics by the x/y scale factors ********************************************************************************************/ void CharMetrics::Scale(double ScaleX, double ScaleY) { CharWidth = (MILLIPOINT)(CharWidth * ScaleX + 0.5); FontEmWidth = (MILLIPOINT)(FontEmWidth * ScaleX + 0.5); FontAscent = (MILLIPOINT)(FontAscent * ScaleY + 0.5); FontDescent = (MILLIPOINT)(FontDescent * ScaleY + 0.5); } ///////////////////////////////////////////////////////////////////////////////////////////// // TextManager /*************************************************************************************** > static BOOL TextManager::GetTTCharPath(CharDescription& ChDesc, DocCoord** ppCoords, PathVerb** ppVerbs, UINT32* pNumCoords, wxDC* pDC=NULL) Author: Mark_Goodall (Xara Group Ltd) <camelotdev@xara.com> Created: 21/3/95 Inputs: ChDesc= description of char pDC= (possible) pointer to a DC (for optimisation) defaults to NULL Outputs: ppCoords=>pointer to path coords buffer ppVerbs=>pointer to path verbs buffer pNumCoords=number of elements in path Returns: FALSE if fails Purpose: Get the path associated with a given char Global: Assumes MM_TextMode ********************************************************************************************/ BOOL TextManager::GetTTCharPath(CharDescription& ChDesc, DocCoord** ppCoords, PathVerb** ppVerbs, UINT32* pNumCoords, wxDC* pDC) { PORTNOTE("text", "no TrueType font manager in wxOil") #ifndef EXCLUDE_FROM_XARALX ERROR2IF(ppCoords==NULL,FALSE,"TextManager::GetTTCharPath pCoords==NULL"); ERROR2IF(ppVerbs==NULL,FALSE,"TextManager::GetTTCharPath ppVerbs==NULL"); ERROR2IF(pNumCoords==NULL,FALSE,"TextManager::GetTTCharPath pNumCoords==NULL"); const CharPathBufferSize=2048; static DocCoord CharPathCoordArray[CharPathBufferSize]; static PathVerb CharPathVerbArray[CharPathBufferSize]; // ensure we have a DC BOOL LocalDC=(pDC==NULL); if (LocalDC) { pDC=new CDC; if (pDC==NULL) { ERROR3("TextManager::GetCharPath() - failed to create DC"); return FALSE; } if (pDC->CreateCompatibleDC(NULL)==FALSE) { delete pDC; ERROR3("TextManager::GetCharPath() - CreateCompatibleDC() failed"); return FALSE; } } // get a log font from the char description, then the path data from the logfont LOGFONT CharLogFont; BOOL ok=GetLogFontFromCharDescriptor(pDC, ChDesc, &CharLogFont); UINT32 Coords=CharPathBufferSize; if (ok) { ok=GetBezierFromChar(pDC, ChDesc.GetCharCode(), &CharLogFont, &Coords, (POINT*)CharPathCoordArray, CharPathVerbArray); // If that failed try again with the default character if (!ok) { // Get the default character to use if a charater is not present in the font. WCHAR DefChar = (unsigned char)'?'; TEXTMETRIC FontTextData; #ifdef _UNCCODE if (pDC->GetTextMetrics(&FontTextData)) DefChar = FontTextData.tmDefaultChar; #else if (pDC->GetTextMetrics(&FontTextData)) DefChar = (unsigned char)FontTextData.tmDefaultChar; #endif ok = GetBezierFromChar(pDC, DefChar, &CharLogFont, &Coords, (POINT*)CharPathCoordArray, CharPathVerbArray); } ERROR3IF(!ok, "TextManager::GetCharPath error from GetBezierFromChar"); } // if ok, set outputs, tidy up and return if (ok) { *ppCoords = CharPathCoordArray; *ppVerbs = CharPathVerbArray; *pNumCoords = Coords; } if (LocalDC) delete pDC; return ok; #else return FALSE; #endif } /*************************************************************************************** > static BOOL TextManager::GetBezierFromChar(wxDC* pDC,const WCHAR CharNumber, LPLOGFONT pLogFont, DWORD* NoPolyElements, POINT* pPolyCordBuffer, BYTE* pPolyVerbBuffer) Author: Mark_Goodall (Xara Group Ltd) <camelotdev@xara.com> Created: 25/1/95 Purpose: To generate the bezier paths which represent a character from a TrueType and, eventually, an ATM, font character Inputs: pDC=>device context CharNumber=character number of char this is a wide Unicode value pLogFontStruct=>LOGFONT struct defining char, the size field is in logcords (=device cords in MM_TextMode) NoPolyElements=Number of elements in PolyDraw arrays, If NoPolyElements=0 then NoPolyElements is set to no. of elements required If NoPolyElements<>0 then generate paths in PolyDraw arrays pPolyCordBuffer=>Cord array in PolyDraw system pPolyVerbBuffer=>Verb array in PolyDraw system Global: Assumes MM_TextMode Outputs: NoPolyElements=No. required if entry value=0 PolyDrawArrays (Verb,Cord) filled if NoPolyElements<>0, CordArrays hold cords in 1/72000's Returns: If FALSE returned then error has occured ********************************************************************************************/ #define FIXEDTOINT32(FIXED) (*((INT32 *)&FIXED)) #define SCALEX(jobby) (MulDiv(MulDiv(jobby,72000,DivConstX),pLogFont->lfHeight,-4096)) #define SCALEY(jobby) (MulDiv(MulDiv(jobby,72000,DivConstY),pLogFont->lfHeight,-4096)) BOOL TextManager::GetBezierFromChar(wxDC* pDC,WCHAR CharNumber, LPLOGFONT pLogFont, DWORD* NoPolyElements, POINT* pPolyCordBuffer, BYTE* pPolyVerbBuffer) { PORTNOTE("text", "no TrueType font manager in wxOil") #ifndef EXCLUDE_FROM_XARALX if (*NoPolyElements==0) { *NoPolyElements=2000; // Assume that 500 element array is big enough, although we still check on this later!! return TRUE; } INT32 DivConstX=pDC->GetDeviceCaps(LOGPIXELSX)<<16; INT32 DivConstY=pDC->GetDeviceCaps(LOGPIXELSY)<<16; LOGFONT TempLogFont=*pLogFont; TempLogFont.lfHeight=-4096;//This ought to be -2048 but this doesn't return correct outlines on Times Italic on o's etc TempLogFont.lfWidth=0; CFont UnHintedCFont; UnHintedCFont.CreateFontIndirect(&TempLogFont); CFont* pOldCFont=pDC->SelectObject(&UnHintedCFont); MAT2 DefaultMatrix={ {0,1} ,{0,0}, {0,0}, {0,1} }; TEXTMETRIC ATextMetricStruct; pDC->GetTextMetrics(&ATextMetricStruct); GLYPHMETRICS GlyphMetricsBuffer; // Get the size of the glyph data DWORD SizeOfGlyphData = (DWORD)-1; UINT32 MBChar = 0; if (UnicodeManager::IsUnicodeCompleteOS()) SizeOfGlyphData = GetGlyphOutlineW(pDC->GetSafeHdc(), CharNumber, GGO_NATIVE, &GlyphMetricsBuffer, 0, NULL, &DefaultMatrix); else { MBChar = UnicodeManager::UnicodeToMultiByte(CharNumber); SizeOfGlyphData = GetGlyphOutlineA(pDC->GetSafeHdc(), MBChar, GGO_NATIVE, &GlyphMetricsBuffer, 0, NULL, &DefaultMatrix); } if (SizeOfGlyphData==-1) return FALSE; // claim memory for glyph data BYTE* pGlyphBuffer= new BYTE[SizeOfGlyphData]; if (pGlyphBuffer == NULL) return FALSE; // Get the glyph outline data DWORD Error = (DWORD)-1; if (UnicodeManager::IsUnicodeCompleteOS()) Error = GetGlyphOutlineW(pDC->GetSafeHdc(), CharNumber, GGO_NATIVE, &GlyphMetricsBuffer, SizeOfGlyphData, pGlyphBuffer, &DefaultMatrix); else Error = GetGlyphOutlineA(pDC->GetSafeHdc(), MBChar, GGO_NATIVE, &GlyphMetricsBuffer, SizeOfGlyphData, pGlyphBuffer, &DefaultMatrix); if (Error == -1) { delete[] pGlyphBuffer; ERROR2(FALSE, "GetGlyphOutline failed"); } //Lets restore the DC font status pDC->SelectObject(pOldCFont); // We now have the GlyphOutline structure in the GlyphBuffer, this consists of TTPolygon etc headers // and records BYTE* pPosInGlyphBuffer=(BYTE*)pGlyphBuffer;// pointer to our current position in GlyphBuffer DWORD ContourSize; // size of data controlled by a PolyHeader structure TTPOLYGONHEADER* pPolyHeader; // needed to allow access to structure data TTPOLYCURVE* pPolyCurve; // ditto DWORD CurrentPolyIndex=0; // Current index in the output PolyBuffer holding beziers etc WORD NoOfArrayElements; // No of elements in a Qspline or prim_line record INT32 CurrentX; // Last point of current path (line or quad b-spline) or previous one INT32 CurrentY; DWORD FirstContourIndex; // The index in PolyCordBuffer of the first member of the current contour while (pPosInGlyphBuffer<(BYTE*)pGlyphBuffer+SizeOfGlyphData) { // Right lets process a TTPOLYGONHEADER and its associated spline and line records pPolyHeader=(TTPOLYGONHEADER*)pPosInGlyphBuffer; ContourSize=pPolyHeader->cb; CurrentX=FIXEDTOINT32(pPolyHeader->pfxStart.x); CurrentY=FIXEDTOINT32(pPolyHeader->pfxStart.y); pPolyCordBuffer[CurrentPolyIndex].x=SCALEX(CurrentX); // First entry is always MoveTo to set 1st point of bezier etc pPolyCordBuffer[CurrentPolyIndex].y=SCALEY(CurrentY); pPolyVerbBuffer[CurrentPolyIndex] =PT_MOVETO; FirstContourIndex=CurrentPolyIndex; CurrentPolyIndex++; pPosInGlyphBuffer=pPosInGlyphBuffer+sizeof(TTPOLYGONHEADER); // pPosInGlyphBuffer=>1st TTPOLYCURVE // Lets process all the TTPOLYGONCURVE structs that exist within the current TTPOLYGONHEADER domain (contour) do { if (CurrentPolyIndex+4>=*NoPolyElements) // are we overflowing poly draw buffer { delete[] pGlyphBuffer; TRACE( _T("overflowing polydraw buffer")); return FALSE; } pPolyCurve=(TTPOLYCURVE*)pPosInGlyphBuffer; NoOfArrayElements=pPolyCurve->cpfx; DWORD i; switch (pPolyCurve->wType) { case TT_PRIM_LINE: for (i=0;i<NoOfArrayElements;i++) { CurrentX=FIXEDTOINT32(pPolyCurve->apfx[i].x); pPolyCordBuffer[CurrentPolyIndex].x=SCALEX(CurrentX); // First entry is always MoveTo to set 1st point of bezier etc CurrentY=FIXEDTOINT32(pPolyCurve->apfx[i].y); pPolyCordBuffer[CurrentPolyIndex].y=SCALEY(CurrentY); pPolyVerbBuffer[CurrentPolyIndex]=PT_LINETO; CurrentPolyIndex++; } break; case TT_PRIM_QSPLINE: for ( i=0;i+1<NoOfArrayElements;i++) { pPolyVerbBuffer[CurrentPolyIndex]=PT_BEZIERTO; pPolyVerbBuffer[CurrentPolyIndex+1]=PT_BEZIERTO; pPolyVerbBuffer[CurrentPolyIndex+2]=PT_BEZIERTO; //TRACE( _T("i=%d\n"),i); // Lets set CurrentPolyIndex [+0] & [+1] pPolyCordBuffer[CurrentPolyIndex].x= // This can overflow - best to scale the components separately // SCALEX((CurrentX+((FIXEDTOINT32(pPolyCurve->apfx[i].x))<<1))/3); SCALEX(CurrentX/3) + SCALEX(((FIXEDTOINT32(pPolyCurve->apfx[i].x))<<1)/3); pPolyCordBuffer[CurrentPolyIndex].y= // This can overflow - best to scale the components separately // SCALEY((CurrentY+((FIXEDTOINT32(pPolyCurve->apfx[i].y))<<1))/3); SCALEY(CurrentY/3) + SCALEY(((FIXEDTOINT32(pPolyCurve->apfx[i].y))<<1)/3); if (i+2==NoOfArrayElements) // are we on last processable point in record? { // yes we are, so just get last point CurrentX=FIXEDTOINT32(pPolyCurve->apfx[i+1].x); pPolyCordBuffer[CurrentPolyIndex+2].x=SCALEX(CurrentX); CurrentY=FIXEDTOINT32(pPolyCurve->apfx[i+1].y); pPolyCordBuffer[CurrentPolyIndex+2].y=SCALEY(CurrentY); } else { // no we're not, so we have to calculate midpoint between the two following points CurrentX=(FIXEDTOINT32(pPolyCurve->apfx[i].x)+FIXEDTOINT32(pPolyCurve->apfx[i+1].x))>>1; pPolyCordBuffer[CurrentPolyIndex+2].x=SCALEX(CurrentX); CurrentY=(FIXEDTOINT32(pPolyCurve->apfx[i].y)+FIXEDTOINT32(pPolyCurve->apfx[i+1].y))>>1; pPolyCordBuffer[CurrentPolyIndex+2].y=SCALEY(CurrentY); } pPolyCordBuffer[CurrentPolyIndex+1].x= // This can overflow - best to scale the components separately // SCALEX((CurrentX+((FIXEDTOINT32(pPolyCurve->apfx[i].x))<<1))/3); SCALEX(CurrentX/3) + SCALEX(((FIXEDTOINT32(pPolyCurve->apfx[i].x))<<1)/3); pPolyCordBuffer[CurrentPolyIndex+1].y= // This can overflow - best to scale the components separately // SCALEY((CurrentY+((FIXEDTOINT32(pPolyCurve->apfx[i].y))<<1))/3); SCALEY(CurrentY/3) + SCALEY(((FIXEDTOINT32(pPolyCurve->apfx[i].y))<<1)/3); CurrentPolyIndex=CurrentPolyIndex+3; } break; default: delete[] pGlyphBuffer; TRACE( _T("oh my god\n")); AfxThrowMemoryException(); } pPosInGlyphBuffer=pPosInGlyphBuffer+sizeof(TTPOLYCURVE)+(NoOfArrayElements-1)*sizeof(POINTFX); } while (pPosInGlyphBuffer<(BYTE*)pPolyHeader+ContourSize); if ( (pPolyCordBuffer[FirstContourIndex].x != pPolyCordBuffer[CurrentPolyIndex-1].x) || (pPolyCordBuffer[FirstContourIndex].y != pPolyCordBuffer[CurrentPolyIndex-1].y)) { pPolyVerbBuffer[CurrentPolyIndex]=PT_LINETO | PT_CLOSEFIGURE; pPolyCordBuffer[CurrentPolyIndex]=pPolyCordBuffer[FirstContourIndex]; CurrentPolyIndex++; } else { pPolyVerbBuffer[CurrentPolyIndex-1]=pPolyVerbBuffer[CurrentPolyIndex-1] | PT_CLOSEFIGURE; } } delete[] pGlyphBuffer; *NoPolyElements=CurrentPolyIndex; return TRUE; #else return FALSE; #endif } /********************************************************************************************* > static INT32 TextManager::GetDesignSize(wxDC* pDC) Author: Ed_Cornes (Xara Group Ltd) <camelotdev@xara.com> Created: 12/1/96 Inputs: pDC - ptr to DC with font selected, for which design size required Returns: design size of font in logical units (or -1 if fails) Note: >>>> just returns a constant for the moment, but gives reasonable accuracy <<<< ********************************************************************************************/ INT32 TextManager::GetDesignSize(wxDC* pDC) { // ERROR2IF(pDC==NULL,FALSE,"TextManager::GetDesignSize() - pDC==NULL"); return 2048; } /********************************************************************************************** > static BOOL TextManager::GetLogFontFromCharDescriptor(wxDC* pDC, CharDescription& ChDesc, LPLOGFONT pLogFont, INT32 LogicalHeight=-1) Author: Ed_Cornes (Xara Group Ltd) <camelotdev@xara.com> Created: 12/1/96 Inputs: pDC - ptr to DC ChDesc - CharDescription containing font handle, bold, italic LogicalHeight - desired height in DC pixels (or -1 for dpi - ie 1" high) Outputs: pLogFont - Logfont corresponding to given ChDesc at specified height Returns: FALSE if fails Purpose: Given a char descriptor, get its corresponding Logfont, and Font metrics if required Note: Assumes MM_TextMode *********************************************************************************************/ BOOL TextManager::GetLogFontFromCharDescriptor(wxDC* pDC, CharDescription& ChDesc, LOGFONT* pLogFont, INT32 LogicalHeight) { ERROR2IF(pLogFont==NULL,FALSE,"TextManager::GetLogFontFromCharDescriptor() pLogFont==NULL"); ERROR2IF( pDC==NULL,FALSE,"TextManager::GetLogFontFromCharDescriptor() pDC==NULL"); // get LogFont from face handle in char descriptor WORD FaceHandle = ChDesc.GetTypefaceHandle(); CachedFontItem* pFontDataItem = FONTMANAGER->GetFont(FaceHandle); if (pFontDataItem == NULL) return FALSE; ENUMLOGFONT* pEnumLogFont = pFontDataItem->GetEnumLogFont(); if (pEnumLogFont == NULL) return FALSE; *pLogFont = pEnumLogFont->elfLogFont; #ifndef EXCLUDE_FROM_XARALX // if not specified, set LogicalHeight to dpi (ie 1") if (LogicalHeight==-1) LogicalHeight = pDC->GetDeviceCaps(LOGPIXELSY); // set font height, aspect (100%), bold, italic pLogFont->lfHeight = -LogicalHeight; pLogFont->lfWidth = 0; pLogFont->lfWeight = ChDesc.GetBold() ? 700 : 0; pLogFont->lfItalic = ChDesc.GetItalic(); #else ERROR2IF(LogicalHeight==-1, FALSE, "NYI - get device DPI"); #endif return TRUE; } /******************************************************************************************** > static BOOL TextManager::GetInfoFromLogFont(FontInfo* pFontInfo, LOGFONT* pLogFont, FontClass Class = FC_UNDEFINED); Author: Ed_Cornes (Xara Group Ltd) <camelotdev@xara.com> Created: 8/4/95 Inputs: pLogFont - Log font to obtain info from Class - describes the type of class (see typedef for details) FC_UNDEFINED then ignore the class match and match the first item with the same name whatever font class it is Outputs: pFontInfo - Fontinfo structure built from given log font Returns: FALSE if fails Purpose: extract as many text attributes as possible from a LOGFONT structure Note: assumes the font is cached ********************************************************************************************/ BOOL TextManager::GetInfoFromLogFont(FontInfo* pFontInfo, LOGFONT* pLogFont, FontClass Class) { #ifndef EXCLUDE_FROM_XARALX // BODGE TEXT - no error trapping of creating new MFC objects - TRY/THROW required // ensure the font is cached String_64 Desc(pLogFont->lfFaceName); if (FONTMANAGER->CacheNamedFont(&Desc, Class)==ILLEGALFHANDLE) return FALSE; // create DC and get it's pixels per inch CDC ADC; if (ADC.CreateCompatibleDC(NULL)==0) ERROR2(FALSE,"TextManager::GetInfoFromLogFont() - CreateCompatibleDC() failed"); INT32 PixelsPerInch=ADC.GetDeviceCaps(LOGPIXELSX); if (PixelsPerInch==0) ERROR2(FALSE,"TextManager::GetInfoFromLogFont() - GetDeviceCaps() failed"); // create a font from the LOGFONT but of default width INT32 DefaultAveCharWidth=0; if (pLogFont->lfWidth!=0) { LOGFONT DefaultWidthLogFont=*pLogFont; DefaultWidthLogFont.lfWidth=0; CFont DefaultWidthFont; if (DefaultWidthFont.CreateFontIndirect(&DefaultWidthLogFont)==0) ERROR2(FALSE,"TextManager::GetInfoFromLogFont() - CreateFontIndirect() failed"); CFont* pOldFont=ADC.SelectObject(&DefaultWidthFont); ERROR2IF(pOldFont==NULL,FALSE,"TextManager::GetInfoFromLogFont() - SelectObject() failed"); TEXTMETRIC TM; if (ADC.GetTextMetrics(&TM)==0) ERROR2(FALSE,"TextManager::GetInfoFromLogFont() - GetTextMetrics() failed"); DefaultAveCharWidth=TM.tmAveCharWidth; if (ADC.SelectObject(pOldFont)==NULL) ERROR2(FALSE,"TextManager::GetInfoFromLogFont() - SelectObject() failed"); } // create font from LOGFONT, select it into DC, and get metrics CFont font; if (font.CreateFontIndirect(pLogFont)==0) ERROR2(FALSE,"TextManager::GetInfoFromLogFont() - CreateFontIndirect() failed"); CFont* pOldFont=ADC.SelectObject(&font); ERROR2IF(pOldFont==NULL,FALSE,"TextManager::GetInfoFromLogFont() - SelectObject() failed"); TEXTMETRIC TM; if (ADC.GetTextMetrics(&TM)==0) ERROR2(FALSE,"TextManager::GetInfoFromLogFont() - GetTextMetrics() failed"); if (ADC.SelectObject(pOldFont)==NULL) ERROR2(FALSE,"TextManager::GetInfoFromLogFont() - SelectObject() failed"); MILLIPOINT FontSize = MulDiv(TM.tmHeight-TM.tmInternalLeading,72000,PixelsPerInch); ERROR2IF(FontSize==-1,FALSE,"TextManager::GetInfoFromLogFont() - MulDiv() failed"); FIXED16 FontAspect = DefaultAveCharWidth!=0 ? Div32By32(TM.tmAveCharWidth,DefaultAveCharWidth) : 1; ERROR2IF(FontAspect==-1,FALSE,"TextManager::GetInfoFromLogFont() - MulDiv() failed"); pFontInfo->Handle = FONTMANAGER->GetFontHandle(&Desc, Class); pFontInfo->Size = FontSize; pFontInfo->Aspect = FontAspect; pFontInfo->Bold = pLogFont->lfWeight > FW_MEDIUM; pFontInfo->Italic = pLogFont->lfItalic != FALSE; pFontInfo->Rotation = pLogFont->lfEscapement / 10.0; return TRUE; #else return FALSE; #endif } /******************************************************************************************** > static CharCase TextManager::ProcessCharCase(WCHAR* pChar, CharCase NewState) Author: Ed_Cornes (Xara Group Ltd) <camelotdev@xara.com> Created: 6/4/95 Inputs: pChar - pointer to char to process NewState - Upper/Lower/Swap/Read Ouptuts: pChar - modified char (if required) Returns: previous state of char (Upper/Lower/Unknown) or Failed Purpose: process the case of a char (accounting for Unicode and non-unicode builds!) ********************************************************************************************/ CharCase TextManager::ProcessCharCase(WCHAR* pChar, CharCase NewState) { ERROR2IF(pChar==NULL,Failed,"TextManager::ProcessCharCase() - pChar==NULL"); ERROR2IF(NewState==Failed || NewState==UnknownType,Failed,"TextManager::ProcessCharCase() - invalid NewState"); ERROR2IF(sizeof(TCHAR) != sizeof(WCHAR), Failed,"TextManager::ProcessCharCase - Unicode only"); CharCase OldCase=UnknownType; // get a lower case version of the char (if it changes it must have been upper) WCHAR OldCharW = *pChar; WCHAR LowerCharW = OldCharW; if ((WCHAR)camTolower(OldCharW) != OldCharW) { OldCase = Upper; LowerCharW = camTolower(OldCharW); } // get an upper case version of the char (if it changes it must have been lower) WCHAR UpperCharW = OldCharW; if ((WCHAR)camToupper(OldCharW) != OldCharW) { OldCase = Lower; UpperCharW = camToupper(OldCharW); } // if its case can be changed and we want to change it do it! if (OldCase!=UnknownType && NewState!=Read) { if (NewState==Swap) NewState = OldCase==Lower ? Upper : Lower; WCHAR NewChar = NewState==Lower ? LowerCharW : UpperCharW; *pChar = NewChar; } return OldCase; } /******************************************************************************************** > BOOL TextManager::GetCharWidth(wxDC* pDC, WCHAR FirstChar, WCHAR, LastChar, INT32* pCharWidthsBuf) Author: Ed_Cornes (Xara Group Ltd) <camelotdev@xara.com> Created: 12/1/96 Inputs: pDC - pointer to DC with correct font selected FirstChar, LastChar - range of chars for which char widths required Outputs: pCharWidthsBuf - buffer filled with char widths Returns: FALSE if fails Purpose: Interface to API call, dynamically accounting for Unicode ability of OS Note: pCharWidthsBuf size must be LastChar-FirstChar+1 ********************************************************************************************/ BOOL TextManager::GetCharWidth(wxDC* pDC, WCHAR FirstChar, WCHAR LastChar, INT32* pCharWidthsBuf) { #ifndef EXCLUDE_FROM_XARALX ERROR2IF( pDC==NULL,FALSE,"TextManager::GetCharWidth() - pDC==NULL"); ERROR2IF(pCharWidthsBuf==NULL,FALSE,"TextManager::GetCharWidth() - pCharWidthsBuf==NULL"); BOOL ok=TRUE; if (UnicodeManager::IsUnicodeCompleteOS()) ok = ::GetCharWidthW(pDC->GetSafeHdc(), FirstChar, LastChar, pCharWidthsBuf); else { UINT32 FirstMBChar = UnicodeManager::UnicodeToMultiByte(FirstChar); UINT32 LastMBChar = UnicodeManager::UnicodeToMultiByte(LastChar); ok = ::GetCharWidthA(pDC->GetSafeHdc(), FirstMBChar, LastMBChar, pCharWidthsBuf); } ERROR2IF(!ok,FALSE,"TextManager::GetCharWidth() - ::GetCharWidth() failed"); return TRUE; #else return FALSE; #endif } /******************************************************************************************** > BOOL TextManager::GetCharABCWidths(wxDC* pDC, WCHAR FirstChar, WCHAR, LastChar, INT32* pCharABCsBuf) Author: Ed_Cornes (Xara Group Ltd) <camelotdev@xara.com> Created: 12/1/96 Inputs: pDC - pointer to DC with correct font selected FirstChar, LastChar - range of chars for which char ABC widths required Outputs: pCharABCsBuf - buffer filled with char ABC widths Returns: FALSE if fails Purpose: Interface to API call, dynamically accounting for Unicode ability of OS Note: pABCWidthsBuf size must be LastChar-FirstChar+1 ********************************************************************************************/ BOOL TextManager::GetCharABCWidths(wxDC* pDC, WCHAR FirstChar, WCHAR LastChar, ABC* pCharABCsBuf) { #ifndef EXCLUDE_FROM_XARALX ERROR2IF( pDC==NULL,FALSE,"TextManager::GetABCWidths() - pDC==NULL"); ERROR2IF(pCharABCsBuf==NULL,FALSE,"TextManager::GetABCWidths() - pCharABCsBuf==NULL"); BOOL ok=TRUE; if (UnicodeManager::IsUnicodeCompleteOS()) ok = ::GetCharABCWidthsW(pDC->GetSafeHdc(), FirstChar, LastChar, pCharABCsBuf); else { UINT32 FirstMBChar = UnicodeManager::UnicodeToMultiByte(FirstChar); UINT32 LastMBChar = UnicodeManager::UnicodeToMultiByte(LastChar); ok = ::GetCharABCWidthsA(pDC->GetSafeHdc(), FirstMBChar, LastMBChar, pCharABCsBuf); } ERROR2IF(!ok,FALSE,"TextManager::GetABCWidths() - ::GetCharABCWidths() failed"); return TRUE; #else return FALSE; #endif } /******************************************************************************************** > INT32 TextManager::GetKernCount(wxDC* pDC) Author: Jonathan_Payne (Xara Group Ltd) <camelotdev@xara.com> Created: 16/10/2000 Inputs: pDC - DC with currently selected font Returns: Number of kerns (0 if there are no kerns or there is an error) Purpose: Find the number of kerns for the currently selected font See also: TextManager::FillKernArray() ********************************************************************************************/ INT32 TextManager::GetKernCount(wxDC* pDC) { ERROR2IF(pDC==0,0,"TextManager::GetKernCount() passed null DC"); #ifndef EXCLUDE_FROM_XARALX return pDC->GetKerningPairs(0, 0); #else return 0; #endif } /******************************************************************************************** > bool TextManager::FillKernArray(wxDC* pDC, KERNINGPAIR *pKerningPairs, INT32 count) Author: Jonathan_Payne (Xara Group Ltd) <camelotdev@xara.com> Created: 16/10/2000 Inputs: pDC - DC with currently selected font count - Size of the array (must be >= GetKernCount() ) Outputs pKerningPairs - Pointer to an array to fill with the kerning pairs Returns: true if all is OK or false if things go real bad Purpose: Fills an array with kerning data for the currently selected font See also: TextManager::GetKernCount() ********************************************************************************************/ bool TextManager::FillKernArray(wxDC* pDC, MillipointKerningPair* pKerningPairs, INT32 count) { ERROR2IF(pDC==0, 0, "TextManager::FillKernArray() passed null DC"); ERROR3IF(count<GetKernCount(pDC), "TextManager::FillKernArray() not passed enough memory - " "kern table will be incomplete"); #ifndef EXCLUDE_FROM_XARALX // Allocate some tmp memory to store windows kerning data KERNINGPAIR* pKPtmp = new KERNINGPAIR[count]; if (!pKPtmp) return false; // Get windows kerning data INT32 number = pDC->GetKerningPairs(count, pKPtmp); // Convert windows data into our own format for (INT32 c = 0; c < number; ++c) { pKerningPairs[c].wFirst = pKPtmp[c].wFirst; pKerningPairs[c].wSecond = pKPtmp[c].wSecond; pKerningPairs[c].iKernAmount = pKPtmp[c].iKernAmount; } // Delete tmp memory delete pKPtmp; // Check for error condition if (number == 0 && GetKernCount(pDC) != 0) { ERROR3("Error reading kerning data"); return false; } else { return true; } #else return FALSE; #endif }
[ "neon.king.fr@gmail.com" ]
neon.king.fr@gmail.com
548bada7eee6a09e4fe7b7931e0158d5167c5d72
d3abf62239ef4189e4c27d30210548dc441dd604
/source/app/task_list.cpp
39fe96640a7536f88e27c7b15581fb02e01080e9
[]
no_license
antranbkdn/Getway_raspberry
88203b9a18990a12ade73c0121be6fd520f5b2fa
8da47d79dba3a4c55c9494ef3deb8408432de258
refs/heads/master
2021-01-19T23:53:37.139619
2017-04-22T06:52:18
2017-04-22T06:52:18
89,050,429
0
0
null
null
null
null
UTF-8
C++
false
false
1,284
cpp
#include "../ak/timer.h" #include "task_list.h" ak_task_t task_list[] = { { GW_TASK_TIMER_ID, TASK_PRI_LEVEL_1, timer_entry , &timer_mailbox , "timer service" }, { GW_TASK_IF_CONSOLE_ID, TASK_PRI_LEVEL_1, gw_task_if_console_entry , &gw_task_if_console_mailbox , "terminal gate" }, { GW_TASK_CONSOLE_ID, TASK_PRI_LEVEL_1, gw_task_console_entry , &gw_task_console_mailbox , "handle commands" }, { GW_TASK_IF_RF24_ID, TASK_PRI_LEVEL_1, gw_task_if_rf24_entry , &gw_task_if_rf24_mailbox , "if rf24" }, { GW_TASK_SNMP_ID, TASK_PRI_LEVEL_1, gw_task_snmp_entry , &gw_task_snmp_mailbox , "task snmp" }, { GW_TASK_IF_RF433_ID, TASK_PRI_LEVEL_1, gw_task_if_rf433_entry , &gw_task_if_rf433_mailbox , "rf433 gate" }, { GW_TASK_RF433_ID, TASK_PRI_LEVEL_1, gw_task_rf433_entry , &gw_task_rf433_mailbox , "task rf433" }, { GW_TASK_MQTT_ID, TASK_PRI_LEVEL_1, gw_task_mqtt_entry , &gw_task_mqtt_mailbox , "task mqtt" }, { GW_TASK_FIRMWARE_ID, TASK_PRI_LEVEL_1, gw_task_firmware_entry , &gw_task_firmware_mailbox , "task firmware" }, { GW_TASK_IF_ID, TASK_PRI_LEVEL_1, gw_task_if_entry , &gw_task_if_mailbox , "task if" }, { GW_TASK_SENSOR_ID, TASK_PRI_LEVEL_1, gw_task_sensor_entry , &gw_task_sensor_mailbox , "task sensor" } };
[ "antrandx@gmail.com" ]
antrandx@gmail.com
5cb71fe1546279603b06f7dd1175bb75db3e38e3
a2111a80faf35749d74a533e123d9da9da108214
/raw/pmsb13/pmsb13-data-20130530/sources/qhuulr654q26tohr/2013-05-21T21-02-44.118+0200/sandbox/PMSB_group6/include/seqan/GCluster/GCluster_base.h
69ae91b443e5c726ddb365c6cb4ffeaf2e478365
[ "MIT" ]
permissive
bkahlert/seqan-research
f2c550d539f511825842a60f6b994c1f0a3934c2
21945be863855077eec7cbdb51c3450afcf560a3
refs/heads/master
2022-12-24T13:05:48.828734
2015-07-01T01:56:22
2015-07-01T01:56:22
21,610,669
1
0
null
null
null
null
UTF-8
C++
false
false
4,051
h
//Autor:Jakob #ifndef GINGER_CLUSTER_CLUSTER_BASE_H_ #define GINGER_CLUSTER_CLUSTER_BASE_H_ #include <iostream> #include <seqan/sequence.h> #include <seqan/seq_io.h> #include <seqan/GStructs/GFastaRecord.h> #include <seqan/GStructs/PerformanceSample.h> #include <seqan/GStructs/MemorySample.h> #include <seqan/GSearch/GScore.h> #include <seqan/GSearch/GScorePeptideQGram.h> #include <seqan/GCluster/GAssignCluster.h> #include <seqan/GCluster/GCheckClusterAssign.h> using namespace seqan; using namespace std; int checkStreams(SequenceStream &inStream, SequenceStream &outStream, SequenceStream &outMasterStream) { if (!isGood(inStream)) { std::cerr << "ERROR: Could not open the input file.\n"; return 1; } if (!isGood(outStream)) { std::cerr << "ERROR: Could not open the output file.\n"; return 1; } if (!isGood(outMasterStream)) { std::cerr << "ERROR: Could not open the output file.\n"; return 1; } return 0; } template<typename TSequence, typename TScore> int GCluster(String<PerformanceSample> & performance, const char * inPath, const char * outPath, const char * outMasterPath, TSequence & sequenceFormatExample, TScore threshold, double lengthThreshold, string & scoreMode) { PerformanceSample perfCluster("GCluster Total"); typedef Score<int> TScoringScheme; typedef GFastaRecord<TSequence> TRecord; typedef typename Iterator<String<TRecord> , Rooted>::Type TMasterIt; SequenceStream inStream(inPath); SequenceStream outStream(outPath, SequenceStream::WRITE); SequenceStream outMasterStream(outMasterPath, SequenceStream::WRITE); if (checkStreams(inStream, outStream, outMasterStream)) return 1; String<TRecord> masterSequences; unsigned recordCounter=0; TScoringScheme scoringScheme(1, -2, -1); TMasterIt masterIt; TRecord record; String<PerformanceSample> perfEntryAvgContainer; String<PerformanceSample> perfGScoreAvgContainer; while (!readRecord(record.id, record.seq, inStream)) { PerformanceSample perfEntryAvg(""); bool createNewCluster = true; masterIt = begin(masterSequences); for (; !atEnd(masterIt); goNext(masterIt)) { TScore score; PerformanceSample perfGScoreAvg(""); if (IsSameType<TSequence, Peptide>::VALUE){ GScorePeptideQGram(score, record, *masterIt, scoringScheme, scoreMode);} else GScore(score, record, *masterIt, scoringScheme, scoreMode); perfGScoreAvg.end(); appendValue(perfGScoreAvgContainer, perfGScoreAvg); if (GCheckClusterAssign(score, threshold, record, *masterIt, lengthThreshold)){ createNewCluster = false; GAssignCluster(outStream, record, *masterIt); break; } } if (createNewCluster) { appendValue(masterSequences, TRecord(record.id, record.seq)); GAssignCluster(outStream, record, record); } ++recordCounter; perfEntryAvg.end(); appendValue(perfEntryAvgContainer, perfEntryAvg); } for (masterIt=begin(masterSequences); !atEnd(masterIt); goNext(masterIt)) { writeRecord(outMasterStream, (*masterIt).id, (*masterIt).seq); } if (length(masterSequences)>0) cout << "\tCreated "<< length(masterSequences) << " cluster with an average of " << (recordCounter/length(masterSequences)) << " sequences each."<< endl; else cout << "\tCreated 0 cluster." << endl; //MemorySample ms("End of cluster function"); //ms.printToStdout(); PerformanceSample perfEntryAvg("Handle one database entry in Cluster average"); //perfEntryAvg.takeAverageValues(perfEntryAvgContainer); //appendValue(performance, perfEntryAvg); PerformanceSample perfGScoreAvg("Call GScore in Cluster average"); //perfGScoreAvg.takeAverageValues(perfGScoreAvgContainer); //appendValue(performance, perfGScoreAvg); perfCluster.end(); appendValue(performance, perfCluster); return 0; } #endif // GINGER_CLUSTER_CLUSTER_BASE_H_
[ "mail@bkahlert.com" ]
mail@bkahlert.com
2d5bb2972f255e74c5886c4a870dc0f971584601
483f8b397e225b060f736871dca6a7f8bfc4ff07
/src/particle_filter/filter.h
037834e29eeb0cd91710dcdf9997a5618541435a
[ "MIT" ]
permissive
emmanueldumont/face_track_visp
95911da31756ce33527cdfe8d64899707dc74b64
56ebd77a2b689f01ef16f62ba7cada88f8422cc6
refs/heads/master
2020-12-04T08:47:16.814104
2016-08-31T13:19:41
2016-08-31T13:19:41
66,259,337
0
0
null
null
null
null
UTF-8
C++
false
false
1,733
h
#ifndef PARTICLEFILTER_H #define PARTICLEFILTER_H /** * @copyright * * Copyright 2012 Kevin Schluff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <opencv2/opencv.hpp> #include "condens.h" class ParticleFilter : private ConDensation { public: enum FilterStates { STATE_X, STATE_Y, STATE_X_VEL, STATE_Y_VEL, STATE_SCALE, NUM_STATES }; ParticleFilter(int num_particles); virtual ~ParticleFilter(); void init(const cv::Rect& selection); cv::Mat& update(cv::Mat& image, cv::Mat& lbp_image, const cv::Size& target_size, cv::Mat& target_hist, bool use_lbp); cv::Rect draw_estimated_state(cv::Mat& image, const cv::Size& target_size, const cv::Scalar& color); void draw_particles(cv::Mat& image, const cv::Size& target_size, const cv::Scalar& color); void redistribute(const float lower_bound[], const float upper_bound[]); const cv::Mat& state() const { return m_state; } float confidence() const { return m_mean_confidence; }; private: float calc_likelyhood(cv::Mat& image_roi, cv::Mat& lbp_roi, cv::Mat& target_hist, bool use_lbp ); float m_mean_confidence; }; #endif
[ "emmanueldumont91@gmail.com" ]
emmanueldumont91@gmail.com
e6e5211682eb7a5ba40e89a9469f79983789384a
87016ad27385090a69abe3a0418d17f5f415f682
/libraries/memorymanager/include/interface/IMemoryContainer.hpp
7e0dfc4ce46a435b96d0f9ff24a23fa18ee4eabc
[]
no_license
BetterCallBene/cudamemorymanager
f468a420aafb0e674b895462bb725fe851aa1ac7
35f163314988358a9c7d8328a3bd4573a8bffa06
refs/heads/master
2023-03-18T00:19:38.467653
2020-06-15T13:18:14
2020-06-15T13:18:14
345,456,083
0
0
null
null
null
null
UTF-8
C++
false
false
557
hpp
#ifndef MEMORYMANAGER_IMEMORY_CONTAINER_HPP_ #define MEMORYMANAGER_IMEMORY_CONTAINER_HPP_ #include <Rte_Type.h> #include "cuda/common.hpp" #include "interface/IPointer.hpp" namespace TraPla { namespace future { class IMemoryContainer : public IPointer { public: IMemoryContainer(/* args */) = default; virtual ~IMemoryContainer() = default; virtual void setQuantity(uint64 quantity) = 0; CUDA_HOSTDEV virtual uint64 getQuantity() const = 0; }; } // namespace future } // namespace TraPla #endif // MEMORYMANAGER_IMEMORY_CONTAINER_HPP_
[ "extern.benedikt.koenig@efs-auto.de" ]
extern.benedikt.koenig@efs-auto.de
43cb1ac75312b92a67d5ca2bbb6af790f79aff4e
19219e745a4fa359fd577d02f2a9619200933018
/togsonguyenchan.cpp
a124307072befd925489d2f1e97a296ff689f287
[]
no_license
duyvippro1156/CTDL_GT
4188418ed86e2837587df47515e686ec0e337fc1
6c3b508831629a545615ba2fc9d00d5994c7df52
refs/heads/main
2023-03-27T14:30:57.565732
2021-03-28T17:58:51
2021-03-28T17:58:51
352,400,124
0
0
null
null
null
null
UTF-8
C++
false
false
257
cpp
#include <stdio.h> #include <conio.h> int main() { int so,dv,tg; printf("Nhap so: "); scanf("%d",&so); tg=0; while (so!=0) { dv=so%10; if (dv%2==0) tg=tg+dv; so=so/10; } printf("tong cac chu so chan trong so nguyen la %d",tg); getch(); }
[ "maiduybigbang@gmail.com" ]
maiduybigbang@gmail.com
08f0800a5c39a979bfaca5299f396258a08e4b2b
3850ae5c29c40b703a62287f8fc13ae34d62b912
/include/mars/listener/util/TestStack.h
69251ee33b73bb1a9052015d4a25d7ed1d8ea015
[]
no_license
horance-liu/mars
1c244191cb9a9e31d1869df7e3c72f8deb9cf91b
d6721631e27b3fdc88512b0234541ca76563d5fe
refs/heads/master
2020-03-21T07:23:49.853189
2018-07-02T01:10:00
2018-07-02T01:10:00
138,277,793
0
0
null
null
null
null
UTF-8
C++
false
false
409
h
#ifndef INCLUDE_MARS_LISTENER_UTIL_TESTSTACK_H_ #define INCLUDE_MARS_LISTENER_UTIL_TESTSTACK_H_ #include <stack> template <typename TestInfo> struct TestStack { void push(TestInfo* test) { tests.push(test); } void pop() { auto top = tests.top(); tests.pop(); delete top; } TestInfo& top() const { return *tests.top(); } private: std::stack<TestInfo*> tests; }; #endif
[ "horance@aliyun.com" ]
horance@aliyun.com
8f578430a9eea43ef622940074b69d24cab729fe
4d42d26fd71bf977d422fbb06ba40e8dba494b0f
/dynamic/wrappers/mesh/CylindricalHoneycombVertexMeshGenerator.pypp.cpp
15cae49c72e8c489ac55615350dcdc6a623e22d6
[]
no_license
myousefi2016/PyChaste
dc1649b9992aeecabdbe2a1977541757b7e9fd6c
af5b30d5135ed0a0664d695ca62b0e88af05ca1b
refs/heads/master
2020-12-30T12:34:48.266420
2017-04-13T10:04:09
2017-04-13T10:04:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,417
cpp
// This file has been generated by Py++. /* Copyright (c) 2005-2016, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "boost/python.hpp" #include "mesh_headers.hpp" #include "CylindricalHoneycombVertexMeshGenerator.pypp.hpp" namespace bp = boost::python; struct SharedCylindricalHoneycombVertexMeshGenerator_wrapper : SharedCylindricalHoneycombVertexMeshGenerator, bp::wrapper< SharedCylindricalHoneycombVertexMeshGenerator > { SharedCylindricalHoneycombVertexMeshGenerator_wrapper(SharedCylindricalHoneycombVertexMeshGenerator const & arg ) : SharedCylindricalHoneycombVertexMeshGenerator( arg ) , bp::wrapper< SharedCylindricalHoneycombVertexMeshGenerator >(){ // copy constructor } SharedCylindricalHoneycombVertexMeshGenerator_wrapper(unsigned int numElementsAcross, unsigned int numElementsUp, bool isFlatBottom=false, double cellRearrangementThreshold=0.01, double t2Threshold=0.001 ) : SharedCylindricalHoneycombVertexMeshGenerator( numElementsAcross, numElementsUp, isFlatBottom, cellRearrangementThreshold, t2Threshold ) , bp::wrapper< SharedCylindricalHoneycombVertexMeshGenerator >(){ // constructor } virtual ::boost::shared_ptr< MutableVertexMesh< 2, 2 > > GetMesh( ) { if( bp::override func_GetMesh = this->get_override( "GetMesh" ) ) return func_GetMesh( ); else{ return this->SharedCylindricalHoneycombVertexMeshGenerator::GetMesh( ); } } ::boost::shared_ptr< MutableVertexMesh< 2, 2 > > default_GetMesh( ) { return SharedCylindricalHoneycombVertexMeshGenerator::GetMesh( ); } }; void register_CylindricalHoneycombVertexMeshGenerator_class(){ bp::class_< SharedCylindricalHoneycombVertexMeshGenerator_wrapper >( "CylindricalHoneycombVertexMeshGenerator", bp::init< unsigned int, unsigned int, bp::optional< bool, double, double > >(( bp::arg("numElementsAcross"), bp::arg("numElementsUp"), bp::arg("isFlatBottom")=(bool)(false), bp::arg("cellRearrangementThreshold")=0.01, bp::arg("t2Threshold")=0.001 )) ) .def( "GetCylindricalMesh" , (::boost::shared_ptr< Cylindrical2dVertexMesh > ( ::SharedCylindricalHoneycombVertexMeshGenerator::* )( ))( &::SharedCylindricalHoneycombVertexMeshGenerator::GetCylindricalMesh ) ) .def( "GetMesh" , (::boost::shared_ptr< MutableVertexMesh< 2, 2 > > ( ::SharedCylindricalHoneycombVertexMeshGenerator::* )( ))(&::SharedCylindricalHoneycombVertexMeshGenerator::GetMesh) , (::boost::shared_ptr< MutableVertexMesh< 2, 2 > > ( SharedCylindricalHoneycombVertexMeshGenerator_wrapper::* )( ))(&SharedCylindricalHoneycombVertexMeshGenerator_wrapper::default_GetMesh) ); }
[ "grogan@maths.ox.ac.uk" ]
grogan@maths.ox.ac.uk
55bf0ae5f06d534e57d062a3bc8643e60e6edd27
3686ee91b33cf71d6dfbc38cfe797a2a9b6653b0
/archive4/164.cpp
d86f851116d05b45498436246008e8032332763a
[]
no_license
danleechina/Leetcode
e27e6c4ccb947bf87e200a47c4b3defb4643107a
95a25af7767e30bacc2ebfb7faffbba6d7bdc157
refs/heads/master
2020-03-26T21:56:15.199890
2019-05-22T02:42:30
2019-05-22T02:42:30
145,419,407
0
0
null
null
null
null
UTF-8
C++
false
false
1,260
cpp
#include <iostream> #include <vector> #include <map> #include <set> #include <stack> #include <string> #include <map> #include <algorithm> #include <queue> using namespace std; bool myfunction(int i, int j) { return (i < j); } class Solution { public: int maximumGap(vector<int> &nums) { int cnt = nums.size(); if (cnt < 2) return 0; auto mm = minmax_element(nums.begin(), nums.end()); int mi = *mm.first, ma = *mm.second; int gap = max((ma - mi) / (cnt - 1), 1); int m = (ma - mi) / gap + 1; vector<int> bucketMax(m, INT_MIN); vector<int> bucketMin(m, INT_MAX); for (int num : nums) { int bucket = (num - mi) / gap; if (num > bucketMax[bucket]) bucketMax[bucket] = num; if (num < bucketMin[bucket]) bucketMin[bucket] = num; } gap = bucketMax[0] - bucketMin[0]; int i = 0, j; while (i < m) { j = i + 1; while (j < m && bucketMax[j] == INT_MIN && bucketMin[j] == INT_MAX) j++; if (j == m) break; gap = max(gap, bucketMin[j] - bucketMax[i]); i = j; } return gap; } }; int main(int argc, char const *argv[]) { Solution s; vector<int> n = {1, 3, 4, 5, 6}; cout << s.maximumGap(n); return 0; }
[ "349604757@qq.com" ]
349604757@qq.com
f757a3b38bd35e50e877fef2dae9fefacd3584bd
44f6b07a14ae51c52bcb2e531a8eff27197bfb5b
/Bb/file_manager/FileParametr.cpp
f113a9158196c3623363f64b30d7faa6254cd319
[]
no_license
Underya/RecognizeFaceFramework
3ca30d27b0d261cdf2d2ab9c64baa343ae3b6bf3
ea8957e190610c70d3a51a732c0ef7b3bbd23106
refs/heads/master
2022-11-15T02:43:30.381568
2020-07-07T07:28:39
2020-07-07T07:28:39
277,747,549
0
0
null
null
null
null
UTF-8
C++
false
false
44
cpp
#include "pch.h" #include "file_parametr.h"
[ "nik.nikita.matveev.1997@gmail.com" ]
nik.nikita.matveev.1997@gmail.com
ab78063a3b7d7fb116e9d9203698b43e5f902a34
ab2ba92c7e6708a5b07be833dd3f479375faba7b
/imgui/imconfig.h
8a1d6880ecdf251ce6dce7f8b64deaafbcbb55d8
[ "MIT" ]
permissive
Keiwaamung/Font-Atlas-Generator
d2d8d835882875ee208acbdb67f672966b5a3a91
44aa09048378742c790a354da3a9eacf94d475e2
refs/heads/main
2023-05-09T16:53:20.054133
2021-06-16T06:47:02
2021-06-16T06:47:02
373,380,081
1
0
null
null
null
null
UTF-8
C++
false
false
9,336
h
//----------------------------------------------------------------------------- // COMPILE-TIME OPTIONS FOR DEAR IMGUI // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. //----------------------------------------------------------------------------- // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) // B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. //----------------------------------------------------------------------------- // You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp // files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. // Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. //----------------------------------------------------------------------------- #pragma once //---- Define assertion handler. Defaults to calling assert(). // If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows // Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. // DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. //#define IMGUI_API __declspec( dllexport ) //#define IMGUI_API __declspec( dllimport ) //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names. //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //---- Disable all of Dear ImGui or don't implement standard windows. // It is very strongly recommended to NOT disable the demo windows during development. Please read comments in imgui_demo.cpp. //#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. //#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. //#define IMGUI_DISABLE_METRICS_WINDOW // Disable metrics/debugger window: ShowMetricsWindow() will be empty. //---- Don't implement some functions to reduce linkage requirements. //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow. (imm32.lib/.a) //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). //---- Include imgui_user.h at the end of imgui.h as a convenience //#define IMGUI_INCLUDE_IMGUI_USER_H //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) //#define IMGUI_USE_BGRA_PACKED_COLOR //---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) //#define IMGUI_USE_WCHAR32 //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION //---- Use stb_printf's faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) // Requires 'stb_sprintf.h' to be available in the include path. Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by STB sprintf. // #define IMGUI_USE_STB_SPRINTF //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) // Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). // On Windows you may use vcpkg with 'vcpkg install freetype' + 'vcpkg integrate install'. //#define IMGUI_ENABLE_FREETYPE //---- Use stb_truetype to build and rasterize the font atlas (default) // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. //#define IMGUI_ENABLE_STB_TRUETYPE //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. // This will be inlined as part of ImVec2 and ImVec4 class declarations. /* #define IM_VEC2_CLASS_EXTRA \ ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ operator MyVec2() const { return MyVec2(x,y); } #define IM_VEC4_CLASS_EXTRA \ ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ operator MyVec4() const { return MyVec4(x,y,z,w); } */ //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. // Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). // Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. //#define ImDrawIdx unsigned int //---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) //struct ImDrawList; //struct ImDrawCmd; //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); //#define ImDrawCallback MyImDrawCallback //---- Debug Tools: Macro to break in Debugger // (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) //#define IM_DEBUG_BREAK IM_ASSERT(0) //#define IM_DEBUG_BREAK __debugbreak() //---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead of ItemHoverable(), // (which comes earlier in the code, will catch a few extra items, allow picking items other than Hovered one.) // This adds a small runtime cost which is why it is not enabled by default. //#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX //---- Debug Tools: Enable slower asserts //#define IMGUI_DEBUG_PARANOID //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* namespace ImGui { void MyFunction(const char* name, const MyMatrix44& v); } */
[ "Kuanlan@outlook.com" ]
Kuanlan@outlook.com
625361e80bf04e4116b8f937f65207d7c0665c10
a25ba11cf682fcaed212e8af979127f6cc5651ff
/src/server/game/Instances/InstanceScript.cpp
8dc969ec9caf4abfb23770be2d02d6877ff7c8d5
[]
no_license
bahajan95/flame-core
79c678be7f340a56f48f3326856ccc7f8223e0ab
ca9fa2715b8c3f3113e3a181dc869a789d088b00
refs/heads/master
2021-01-17T06:23:01.085091
2012-03-28T22:12:40
2012-03-28T22:12:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,050
cpp
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "InstanceScript.h" #include "DatabaseEnv.h" #include "Map.h" #include "Player.h" #include "GameObject.h" #include "Creature.h" #include "CreatureAI.h" #include "Log.h" #include "LFGMgr.h" void InstanceScript::SaveToDB() { std::string data = GetSaveData(); if (data.empty()) return; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_DATA); stmt->setUInt32(0, GetCompletedEncounterMask()); stmt->setString(1, data); stmt->setUInt32(2, instance->GetInstanceId()); CharacterDatabase.Execute(stmt); } void InstanceScript::HandleGameObject(uint64 GUID, bool open, GameObject* go) { if (!go) go = instance->GetGameObject(GUID); if (go) go->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY); else sLog->outDebug(LOG_FILTER_TSCR, "TSCR: InstanceScript: HandleGameObject failed"); } bool InstanceScript::IsEncounterInProgress() const { for (std::vector<BossInfo>::const_iterator itr = bosses.begin(); itr != bosses.end(); ++itr) if (itr->state == IN_PROGRESS) return true; return false; } void InstanceScript::LoadMinionData(const MinionData* data) { while (data->entry) { if (data->bossId < bosses.size()) minions.insert(std::make_pair(data->entry, MinionInfo(&bosses[data->bossId]))); ++data; } sLog->outDebug(LOG_FILTER_TSCR, "InstanceScript::LoadMinionData: " UI64FMTD " minions loaded.", uint64(minions.size())); } void InstanceScript::LoadDoorData(const DoorData* data) { while (data->entry) { if (data->bossId < bosses.size()) doors.insert(std::make_pair(data->entry, DoorInfo(&bosses[data->bossId], data->type, BoundaryType(data->boundary)))); ++data; } sLog->outDebug(LOG_FILTER_TSCR, "InstanceScript::LoadDoorData: " UI64FMTD " doors loaded.", uint64(doors.size())); } void InstanceScript::UpdateMinionState(Creature* minion, EncounterState state) { switch (state) { case NOT_STARTED: if (!minion->isAlive()) minion->Respawn(); else if (minion->isInCombat()) minion->AI()->EnterEvadeMode(); break; case IN_PROGRESS: if (!minion->isAlive()) minion->Respawn(); else if (!minion->getVictim()) minion->AI()->DoZoneInCombat(); break; default: break; } } void InstanceScript::UpdateDoorState(GameObject* door) { DoorInfoMap::iterator lower = doors.lower_bound(door->GetEntry()); DoorInfoMap::iterator upper = doors.upper_bound(door->GetEntry()); if (lower == upper) return; bool open = true; for (DoorInfoMap::iterator itr = lower; itr != upper && open; ++itr) { switch (itr->second.type) { case DOOR_TYPE_ROOM: open = (itr->second.bossInfo->state != IN_PROGRESS); break; case DOOR_TYPE_PASSAGE: open = (itr->second.bossInfo->state == DONE); break; case DOOR_TYPE_SPAWN_HOLE: open = (itr->second.bossInfo->state == IN_PROGRESS); break; default: break; } } door->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY); } void InstanceScript::AddDoor(GameObject* door, bool add) { DoorInfoMap::iterator lower = doors.lower_bound(door->GetEntry()); DoorInfoMap::iterator upper = doors.upper_bound(door->GetEntry()); if (lower == upper) return; for (DoorInfoMap::iterator itr = lower; itr != upper; ++itr) { DoorInfo const& data = itr->second; if (add) { data.bossInfo->door[data.type].insert(door); switch (data.boundary) { default: case BOUNDARY_NONE: break; case BOUNDARY_N: case BOUNDARY_S: data.bossInfo->boundary[data.boundary] = door->GetPositionX(); break; case BOUNDARY_E: case BOUNDARY_W: data.bossInfo->boundary[data.boundary] = door->GetPositionY(); break; case BOUNDARY_NW: case BOUNDARY_SE: data.bossInfo->boundary[data.boundary] = door->GetPositionX() + door->GetPositionY(); break; case BOUNDARY_NE: case BOUNDARY_SW: data.bossInfo->boundary[data.boundary] = door->GetPositionX() - door->GetPositionY(); break; } } else data.bossInfo->door[data.type].erase(door); } if (add) UpdateDoorState(door); } void InstanceScript::AddMinion(Creature* minion, bool add) { MinionInfoMap::iterator itr = minions.find(minion->GetEntry()); if (itr == minions.end()) return; if (add) itr->second.bossInfo->minion.insert(minion); else itr->second.bossInfo->minion.erase(minion); } bool InstanceScript::SetBossState(uint32 id, EncounterState state) { if (id < bosses.size()) { BossInfo* bossInfo = &bosses[id]; if (bossInfo->state == TO_BE_DECIDED) // loading { bossInfo->state = state; //sLog->outError("Inialize boss %u state as %u.", id, (uint32)state); return false; } else { if (bossInfo->state == state) return false; if (state == DONE) for (MinionSet::iterator i = bossInfo->minion.begin(); i != bossInfo->minion.end(); ++i) if ((*i)->isWorldBoss() && (*i)->isAlive()) return false; bossInfo->state = state; SaveToDB(); } for (uint32 type = 0; type < MAX_DOOR_TYPES; ++type) for (DoorSet::iterator i = bossInfo->door[type].begin(); i != bossInfo->door[type].end(); ++i) UpdateDoorState(*i); for (MinionSet::iterator i = bossInfo->minion.begin(); i != bossInfo->minion.end(); ++i) UpdateMinionState(*i, state); return true; } return false; } std::string InstanceScript::LoadBossState(const char * data) { if (!data) return NULL; std::istringstream loadStream(data); uint32 buff; uint32 bossId = 0; for (std::vector<BossInfo>::iterator i = bosses.begin(); i != bosses.end(); ++i, ++bossId) { loadStream >> buff; if (buff < TO_BE_DECIDED) SetBossState(bossId, (EncounterState)buff); } return loadStream.str(); } std::string InstanceScript::GetBossSaveData() { std::ostringstream saveStream; for (std::vector<BossInfo>::iterator i = bosses.begin(); i != bosses.end(); ++i) saveStream << (uint32)i->state << ' '; return saveStream.str(); } void InstanceScript::DoUseDoorOrButton(uint64 uiGuid, uint32 uiWithRestoreTime, bool bUseAlternativeState) { if (!uiGuid) return; GameObject* go = instance->GetGameObject(uiGuid); if (go) { if (go->GetGoType() == GAMEOBJECT_TYPE_DOOR || go->GetGoType() == GAMEOBJECT_TYPE_BUTTON) { if (go->getLootState() == GO_READY) go->UseDoorOrButton(uiWithRestoreTime, bUseAlternativeState); else if (go->getLootState() == GO_ACTIVATED) go->ResetDoorOrButton(); } else sLog->outError("SD2: Script call DoUseDoorOrButton, but gameobject entry %u is type %u.", go->GetEntry(), go->GetGoType()); } } void InstanceScript::DoRespawnGameObject(uint64 uiGuid, uint32 uiTimeToDespawn) { if (GameObject* go = instance->GetGameObject(uiGuid)) { //not expect any of these should ever be handled if (go->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE || go->GetGoType() == GAMEOBJECT_TYPE_DOOR || go->GetGoType() == GAMEOBJECT_TYPE_BUTTON || go->GetGoType() == GAMEOBJECT_TYPE_TRAP) return; if (go->isSpawned()) return; go->SetRespawnTime(uiTimeToDespawn); } } void InstanceScript::DoUpdateWorldState(uint32 uiStateId, uint32 uiStateData) { Map::PlayerList const& lPlayers = instance->GetPlayers(); if (!lPlayers.isEmpty()) { for (Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr) if (Player* player = itr->getSource()) player->SendUpdateWorldState(uiStateId, uiStateData); } else sLog->outDebug(LOG_FILTER_TSCR, "TSCR: DoUpdateWorldState attempt send data but no players in map."); } // Send Notify to all players in instance void InstanceScript::DoSendNotifyToInstance(char const* format, ...) { InstanceMap::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) { va_list ap; va_start(ap, format); char buff[1024]; vsnprintf(buff, 1024, format, ap); va_end(ap); for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) if (Player* player = i->getSource()) if (WorldSession* session = player->GetSession()) session->SendNotification("%s", buff); } } // Complete Achievement for all players in instance void InstanceScript::DoCompleteAchievement(uint32 achievement) { AchievementEntry const* pAE = sAchievementStore.LookupEntry(achievement); Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!pAE) { sLog->outError("TSCR: DoCompleteAchievement called for not existing achievement %u", achievement); return; } if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player *pPlayer = i->getSource()) pPlayer->CompletedAchievement(pAE); } // Update Achievement Criteria for all players in instance void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* player = i->getSource()) player->UpdateAchievementCriteria(type, miscValue1, miscValue2, unit); } // Start timed achievement for all players in instance void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* player = i->getSource()) player->GetAchievementMgr().StartTimedAchievement(type, entry); } // Stop timed achievement for all players in instance void InstanceScript::DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* player = i->getSource()) player->GetAchievementMgr().RemoveTimedAchievement(type, entry); } // Remove Auras due to Spell on all players in instance void InstanceScript::DoRemoveAurasDueToSpellOnPlayers(uint32 spell) { Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) { if (Player* player = itr->getSource()) { player->RemoveAurasDueToSpell(spell); if (Pet* pet = player->GetPet()) pet->RemoveAurasDueToSpell(spell); } } } } // Cast spell on all players in instance void InstanceScript::DoCastSpellOnPlayers(uint32 spell) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* player = i->getSource()) player->CastSpell(player, spell, true); } bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= NULL*/, uint32 /*miscvalue1*/ /*= 0*/) { sLog->outError("Achievement system call InstanceScript::CheckAchievementCriteriaMeet but instance script for map %u not have implementation for achievement criteria %u", instance->GetId(), criteria_id); return false; } void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= NULL*/, uint8 param1 /*= 0*/, uint8 param2 /*= 0*/) { // size of this packet is at most 15 (usually less) WorldPacket data(SMSG_UPDATE_INSTANCE_ENCOUNTER_UNIT, 15); data << uint32(type); switch (type) { case ENCOUNTER_FRAME_ENGAGE: case ENCOUNTER_FRAME_DISENGAGE: case ENCOUNTER_FRAME_UPDATE_PRIORITY: data.append(unit->GetPackGUID()); data << uint8(param1); break; case ENCOUNTER_FRAME_ADD_TIMER: case ENCOUNTER_FRAME_ENABLE_OBJECTIVE: case ENCOUNTER_FRAME_DISABLE_OBJECTIVE: data << uint8(param1); break; case ENCOUNTER_FRAME_UPDATE_OBJECTIVE: data << uint8(param1); data << uint8(param2); break; case ENCOUNTER_FRAME_UNK7: default: break; } instance->SendToPlayers(&data); } void InstanceScript::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source) { DungeonEncounterList const* encounters = sObjectMgr->GetDungeonEncounterList(instance->GetId(), instance->GetDifficulty()); if (!encounters) return; for (DungeonEncounterList::const_iterator itr = encounters->begin(); itr != encounters->end(); ++itr) { if ((*itr)->creditType == type && (*itr)->creditEntry == creditEntry) { completedEncounters |= 1 << (*itr)->dbcEntry->encounterIndex; sLog->outDebug(LOG_FILTER_TSCR, "Instance %s (instanceId %u) completed encounter %s", instance->GetMapName(), instance->GetInstanceId(), (*itr)->dbcEntry->encounterName[0]); if (uint32 dungeonId = (*itr)->lastEncounterDungeon) { Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) if (Player* player = i->getSource()) if (!source || player->IsAtGroupRewardDistance(source)) sLFGMgr->RewardDungeonDoneFor(dungeonId, player); } return; } } }
[ "rial9111@rambler.ru" ]
rial9111@rambler.ru
7664a78ed929e09180650b316f62e0bd2d06d6e0
118ef177541ab022ac14f6a683bc3a0e709ea19b
/catkin_ws/devel/include/hannrs_costmap_layers/InteractionLayerConfig.h
2b11c113463b205bd449ac1e1e80d2ab803e9521
[]
no_license
mateus03/HANNRS
a636284e113876676a6dbd3fefe4df9b3bde895c
664e09512f5cda06434a0b9ff269d1953d27aa58
refs/heads/master
2016-08-09T20:43:06.240285
2015-11-09T17:31:00
2015-11-09T17:31:00
45,854,149
1
2
null
null
null
null
UTF-8
C++
false
false
20,704
h
//#line 2 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template" // ********************************************************* // // File autogenerated for the hannrs_costmap_layers package // by the dynamic_reconfigure package. // Please do not edit. // // ********************************************************/ #ifndef __hannrs_costmap_layers__INTERACTIONLAYERCONFIG_H__ #define __hannrs_costmap_layers__INTERACTIONLAYERCONFIG_H__ #include <dynamic_reconfigure/config_tools.h> #include <limits> #include <ros/node_handle.h> #include <dynamic_reconfigure/ConfigDescription.h> #include <dynamic_reconfigure/ParamDescription.h> #include <dynamic_reconfigure/Group.h> #include <dynamic_reconfigure/config_init_mutex.h> #include <boost/any.hpp> namespace hannrs_costmap_layers { class InteractionLayerConfigStatics; class InteractionLayerConfig { public: class AbstractParamDescription : public dynamic_reconfigure::ParamDescription { public: AbstractParamDescription(std::string n, std::string t, uint32_t l, std::string d, std::string e) { name = n; type = t; level = l; description = d; edit_method = e; } virtual void clamp(InteractionLayerConfig &config, const InteractionLayerConfig &max, const InteractionLayerConfig &min) const = 0; virtual void calcLevel(uint32_t &level, const InteractionLayerConfig &config1, const InteractionLayerConfig &config2) const = 0; virtual void fromServer(const ros::NodeHandle &nh, InteractionLayerConfig &config) const = 0; virtual void toServer(const ros::NodeHandle &nh, const InteractionLayerConfig &config) const = 0; virtual bool fromMessage(const dynamic_reconfigure::Config &msg, InteractionLayerConfig &config) const = 0; virtual void toMessage(dynamic_reconfigure::Config &msg, const InteractionLayerConfig &config) const = 0; virtual void getValue(const InteractionLayerConfig &config, boost::any &val) const = 0; }; typedef boost::shared_ptr<AbstractParamDescription> AbstractParamDescriptionPtr; typedef boost::shared_ptr<const AbstractParamDescription> AbstractParamDescriptionConstPtr; template <class T> class ParamDescription : public AbstractParamDescription { public: ParamDescription(std::string name, std::string type, uint32_t level, std::string description, std::string edit_method, T InteractionLayerConfig::* f) : AbstractParamDescription(name, type, level, description, edit_method), field(f) {} T (InteractionLayerConfig::* field); virtual void clamp(InteractionLayerConfig &config, const InteractionLayerConfig &max, const InteractionLayerConfig &min) const { if (config.*field > max.*field) config.*field = max.*field; if (config.*field < min.*field) config.*field = min.*field; } virtual void calcLevel(uint32_t &comb_level, const InteractionLayerConfig &config1, const InteractionLayerConfig &config2) const { if (config1.*field != config2.*field) comb_level |= level; } virtual void fromServer(const ros::NodeHandle &nh, InteractionLayerConfig &config) const { nh.getParam(name, config.*field); } virtual void toServer(const ros::NodeHandle &nh, const InteractionLayerConfig &config) const { nh.setParam(name, config.*field); } virtual bool fromMessage(const dynamic_reconfigure::Config &msg, InteractionLayerConfig &config) const { return dynamic_reconfigure::ConfigTools::getParameter(msg, name, config.*field); } virtual void toMessage(dynamic_reconfigure::Config &msg, const InteractionLayerConfig &config) const { dynamic_reconfigure::ConfigTools::appendParameter(msg, name, config.*field); } virtual void getValue(const InteractionLayerConfig &config, boost::any &val) const { val = config.*field; } }; class AbstractGroupDescription : public dynamic_reconfigure::Group { public: AbstractGroupDescription(std::string n, std::string t, int p, int i, bool s) { name = n; type = t; parent = p; state = s; id = i; } std::vector<AbstractParamDescriptionConstPtr> abstract_parameters; bool state; virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &config) const = 0; virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &config) const =0; virtual void updateParams(boost::any &cfg, InteractionLayerConfig &top) const= 0; virtual void setInitialState(boost::any &cfg) const = 0; void convertParams() { for(std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = abstract_parameters.begin(); i != abstract_parameters.end(); ++i) { parameters.push_back(dynamic_reconfigure::ParamDescription(**i)); } } }; typedef boost::shared_ptr<AbstractGroupDescription> AbstractGroupDescriptionPtr; typedef boost::shared_ptr<const AbstractGroupDescription> AbstractGroupDescriptionConstPtr; template<class T, class PT> class GroupDescription : public AbstractGroupDescription { public: GroupDescription(std::string name, std::string type, int parent, int id, bool s, T PT::* f) : AbstractGroupDescription(name, type, parent, id, s), field(f) { } GroupDescription(const GroupDescription<T, PT>& g): AbstractGroupDescription(g.name, g.type, g.parent, g.id, g.state), field(g.field), groups(g.groups) { parameters = g.parameters; abstract_parameters = g.abstract_parameters; } virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &cfg) const { PT* config = boost::any_cast<PT*>(cfg); if(!dynamic_reconfigure::ConfigTools::getGroupState(msg, name, (*config).*field)) return false; for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i) { boost::any n = &((*config).*field); if(!(*i)->fromMessage(msg, n)) return false; } return true; } virtual void setInitialState(boost::any &cfg) const { PT* config = boost::any_cast<PT*>(cfg); T* group = &((*config).*field); group->state = state; for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i) { boost::any n = boost::any(&((*config).*field)); (*i)->setInitialState(n); } } virtual void updateParams(boost::any &cfg, InteractionLayerConfig &top) const { PT* config = boost::any_cast<PT*>(cfg); T* f = &((*config).*field); f->setParams(top, abstract_parameters); for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i) { boost::any n = &((*config).*field); (*i)->updateParams(n, top); } } virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &cfg) const { const PT config = boost::any_cast<PT>(cfg); dynamic_reconfigure::ConfigTools::appendGroup<T>(msg, name, id, parent, config.*field); for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i) { (*i)->toMessage(msg, config.*field); } } T (PT::* field); std::vector<InteractionLayerConfig::AbstractGroupDescriptionConstPtr> groups; }; class DEFAULT { public: DEFAULT() { state = true; name = "Default"; } void setParams(InteractionLayerConfig &config, const std::vector<AbstractParamDescriptionConstPtr> params) { for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator _i = params.begin(); _i != params.end(); ++_i) { boost::any val; (*_i)->getValue(config, val); if("enabled"==(*_i)->name){enabled = boost::any_cast<bool>(val);} if("importance"==(*_i)->name){importance = boost::any_cast<double>(val);} } } bool enabled; double importance; bool state; std::string name; }groups; //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" bool enabled; //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" double importance; //#line 218 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template" bool __fromMessage__(dynamic_reconfigure::Config &msg) { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__(); int count = 0; for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) if ((*i)->fromMessage(msg, *this)) count++; for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i ++) { if ((*i)->id == 0) { boost::any n = boost::any(this); (*i)->updateParams(n, *this); (*i)->fromMessage(msg, n); } } if (count != dynamic_reconfigure::ConfigTools::size(msg)) { ROS_ERROR("InteractionLayerConfig::__fromMessage__ called with an unexpected parameter."); ROS_ERROR("Booleans:"); for (unsigned int i = 0; i < msg.bools.size(); i++) ROS_ERROR(" %s", msg.bools[i].name.c_str()); ROS_ERROR("Integers:"); for (unsigned int i = 0; i < msg.ints.size(); i++) ROS_ERROR(" %s", msg.ints[i].name.c_str()); ROS_ERROR("Doubles:"); for (unsigned int i = 0; i < msg.doubles.size(); i++) ROS_ERROR(" %s", msg.doubles[i].name.c_str()); ROS_ERROR("Strings:"); for (unsigned int i = 0; i < msg.strs.size(); i++) ROS_ERROR(" %s", msg.strs[i].name.c_str()); // @todo Check that there are no duplicates. Make this error more // explicit. return false; } return true; } // This version of __toMessage__ is used during initialization of // statics when __getParamDescriptions__ can't be called yet. void __toMessage__(dynamic_reconfigure::Config &msg, const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__, const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__) const { dynamic_reconfigure::ConfigTools::clear(msg); for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->toMessage(msg, *this); for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i) { if((*i)->id == 0) { (*i)->toMessage(msg, *this); } } } void __toMessage__(dynamic_reconfigure::Config &msg) const { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__(); __toMessage__(msg, __param_descriptions__, __group_descriptions__); } void __toServer__(const ros::NodeHandle &nh) const { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->toServer(nh, *this); } void __fromServer__(const ros::NodeHandle &nh) { static bool setup=false; const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->fromServer(nh, *this); const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__(); for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i++){ if (!setup && (*i)->id == 0) { setup = true; boost::any n = boost::any(this); (*i)->setInitialState(n); } } } void __clamp__() { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); const InteractionLayerConfig &__max__ = __getMax__(); const InteractionLayerConfig &__min__ = __getMin__(); for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->clamp(*this, __max__, __min__); } uint32_t __level__(const InteractionLayerConfig &config) const { const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__(); uint32_t level = 0; for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i) (*i)->calcLevel(level, config, *this); return level; } static const dynamic_reconfigure::ConfigDescription &__getDescriptionMessage__(); static const InteractionLayerConfig &__getDefault__(); static const InteractionLayerConfig &__getMax__(); static const InteractionLayerConfig &__getMin__(); static const std::vector<AbstractParamDescriptionConstPtr> &__getParamDescriptions__(); static const std::vector<AbstractGroupDescriptionConstPtr> &__getGroupDescriptions__(); private: static const InteractionLayerConfigStatics *__get_statics__(); }; template <> // Max and min are ignored for strings. inline void InteractionLayerConfig::ParamDescription<std::string>::clamp(InteractionLayerConfig &config, const InteractionLayerConfig &max, const InteractionLayerConfig &min) const { return; } class InteractionLayerConfigStatics { friend class InteractionLayerConfig; InteractionLayerConfigStatics() { InteractionLayerConfig::GroupDescription<InteractionLayerConfig::DEFAULT, InteractionLayerConfig> Default("Default", "", 0, 0, true, &InteractionLayerConfig::groups); //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __min__.enabled = 0; //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __max__.enabled = 1; //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __default__.enabled = 1; //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" Default.abstract_parameters.push_back(InteractionLayerConfig::AbstractParamDescriptionConstPtr(new InteractionLayerConfig::ParamDescription<bool>("enabled", "bool", 0, "Whether to apply this plugin or not ", "", &InteractionLayerConfig::enabled))); //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __param_descriptions__.push_back(InteractionLayerConfig::AbstractParamDescriptionConstPtr(new InteractionLayerConfig::ParamDescription<bool>("enabled", "bool", 0, "Whether to apply this plugin or not ", "", &InteractionLayerConfig::enabled))); //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __min__.importance = 0.0; //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __max__.importance = 1.0; //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __default__.importance = 1.0; //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" Default.abstract_parameters.push_back(InteractionLayerConfig::AbstractParamDescriptionConstPtr(new InteractionLayerConfig::ParamDescription<double>("importance", "double", 0, "Factor to multiply by the costmap_2d::LethalObstacle cost", "", &InteractionLayerConfig::importance))); //#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __param_descriptions__.push_back(InteractionLayerConfig::AbstractParamDescriptionConstPtr(new InteractionLayerConfig::ParamDescription<double>("importance", "double", 0, "Factor to multiply by the costmap_2d::LethalObstacle cost", "", &InteractionLayerConfig::importance))); //#line 233 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" Default.convertParams(); //#line 233 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py" __group_descriptions__.push_back(InteractionLayerConfig::AbstractGroupDescriptionConstPtr(new InteractionLayerConfig::GroupDescription<InteractionLayerConfig::DEFAULT, InteractionLayerConfig>(Default))); //#line 353 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template" for (std::vector<InteractionLayerConfig::AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i) { __description_message__.groups.push_back(**i); } __max__.__toMessage__(__description_message__.max, __param_descriptions__, __group_descriptions__); __min__.__toMessage__(__description_message__.min, __param_descriptions__, __group_descriptions__); __default__.__toMessage__(__description_message__.dflt, __param_descriptions__, __group_descriptions__); } std::vector<InteractionLayerConfig::AbstractParamDescriptionConstPtr> __param_descriptions__; std::vector<InteractionLayerConfig::AbstractGroupDescriptionConstPtr> __group_descriptions__; InteractionLayerConfig __max__; InteractionLayerConfig __min__; InteractionLayerConfig __default__; dynamic_reconfigure::ConfigDescription __description_message__; static const InteractionLayerConfigStatics *get_instance() { // Split this off in a separate function because I know that // instance will get initialized the first time get_instance is // called, and I am guaranteeing that get_instance gets called at // most once. static InteractionLayerConfigStatics instance; return &instance; } }; inline const dynamic_reconfigure::ConfigDescription &InteractionLayerConfig::__getDescriptionMessage__() { return __get_statics__()->__description_message__; } inline const InteractionLayerConfig &InteractionLayerConfig::__getDefault__() { return __get_statics__()->__default__; } inline const InteractionLayerConfig &InteractionLayerConfig::__getMax__() { return __get_statics__()->__max__; } inline const InteractionLayerConfig &InteractionLayerConfig::__getMin__() { return __get_statics__()->__min__; } inline const std::vector<InteractionLayerConfig::AbstractParamDescriptionConstPtr> &InteractionLayerConfig::__getParamDescriptions__() { return __get_statics__()->__param_descriptions__; } inline const std::vector<InteractionLayerConfig::AbstractGroupDescriptionConstPtr> &InteractionLayerConfig::__getGroupDescriptions__() { return __get_statics__()->__group_descriptions__; } inline const InteractionLayerConfigStatics *InteractionLayerConfig::__get_statics__() { const static InteractionLayerConfigStatics *statics; if (statics) // Common case return statics; boost::mutex::scoped_lock lock(dynamic_reconfigure::__init_mutex__); if (statics) // In case we lost a race. return statics; statics = InteractionLayerConfigStatics::get_instance(); return statics; } } #endif // __INTERACTIONLAYERRECONFIGURATOR_H__
[ "andrgmateus@gmail.com" ]
andrgmateus@gmail.com
f0f1556a30ff6c6e2a9d27ce588b407dcf2a25be
5c4326259272ce5bd86bd054303cc2611dc363c7
/ddtt/experiment/StructureAnalysis.cpp
ae129eaea289843100e47a712fa0d5d86c9e45ea
[]
no_license
aaronzou/ddtt-dev
dd96b1be26d8c743f9b8b06a6de3a54c866be88d
6e79fbbb3c566674658ab8e3f9fde31c4a200922
refs/heads/master
2020-12-29T01:23:00.404671
2015-09-01T02:32:50
2015-09-01T02:32:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,199
cpp
#include "StructureAnalysis.h" #include "ShapeGraph.h" #include "GenericGraph.h" #include "helpers/PhysicsHelper.h" #include "disjointset.h" void StructureAnalysis::analyzeGroups(Structure::ShapeGraph * shape, bool isDebug) { shape->relations.clear(); QStringList nodesIDs; Structure::NodeGroups tmpA; for (auto n : shape->nodes) nodesIDs << n->id; for (auto g : shape->groups) for (auto nid : g) nodesIDs.removeAll(nid); for (auto nid : nodesIDs) tmpA.push_back(QVector<QString>() << nid); for (auto g : shape->groups) tmpA.push_back(g); shape->groups = tmpA; for (auto g : shape->groups) { Structure::Relation r; r.parts = QStringList::fromVector(g); if (g.size() == 1) { r.type = Structure::Relation::SELF; // TODO: figure out the plane, or select the most similar to global reflectional } // Since fitted input might not always be perfect, we equalize parts geometry (resample) here { auto firstPart = shape->getNode(r.parts.front()); for (auto partID : r.parts) if (shape->getNode(partID)->numCtrlPnts() > firstPart->numCtrlPnts()) firstPart = shape->getNode(partID); for (auto partID : r.parts) { auto smaller = firstPart; auto larger = shape->getNode(partID); if (smaller->numCtrlPnts() > larger->numCtrlPnts()) std::swap(smaller, larger); smaller->equalizeControlPoints(larger); } } if (g.size() == 2) { r.type = Structure::Relation::REFLECTIONAL; auto partA = shape->getNode(g.front()), partB = shape->getNode(g.back()); auto plane = getReflectionalPlane(partA, partB); r.point = plane.first; r.axis = plane.second; } std::vector<Vector3> centers; Vector3 centroid(0, 0, 0); if (g.size() > 2) { // Compute distances from group centroid to parts for (auto part : r.parts) centers.push_back( shape->getNode(part)->position(Eigen::Vector4d(0.5,0.5,0,0)) ); for (auto c : centers) centroid += c; centroid /= centers.size(); Array1D_Real cdists; for (auto c : centers) cdists.push_back((c - centroid).norm()); // Compute closest pair distance std::vector< QVector<double> > pair_dists(g.size()); Array1D_Real dists(g.size()); for (int i = 0; i < g.size(); i++){ for (int j = 0; j < g.size(); j++){ if (i==j) continue; double d = (centers.at(i) - centers.at(j)).norm(); pair_dists[i] << d; } std::sort(pair_dists[i].begin(), pair_dists[i].end()); dists[i] = (pair_dists[i][0] + pair_dists[i][1]) / 2.0; } double avg_dist_pair = 0; for (auto d : dists) avg_dist_pair += d; avg_dist_pair /= dists.size(); if (*std::min_element(cdists.begin(), cdists.end()) < avg_dist_pair * 0.5) r.type = Structure::Relation::TRANSLATIONAL; else r.type = Structure::Relation::ROTATIONAL; /* // Median absolute deviation (MAD) double avg_dist = std::accumulate(dists.begin(), dists.end(), 0.0) / dists.size(); QVector<double> absolute_deviations; for (auto dist : dists) absolute_deviations << abs(dist - avg_dist); std::sort(absolute_deviations.begin(), absolute_deviations.end()); double mad = 0; if (absolute_deviations.size() % 2 == 1) mad = absolute_deviations[(absolute_deviations.size() - 1) / 2]; else { auto a = absolute_deviations[(absolute_deviations.size() / 2) - 1]; auto b = absolute_deviations[(absolute_deviations.size() / 2)]; mad = (a + b) / 2; } // Rotational relations have consistent distance double threshold = avg_dist * 0.45; if (mad < threshold) r.type = Structure::Relation::ROTATIONAL; else r.type = Structure::Relation::TRANSLATIONAL; */ if (r.type == Structure::Relation::TRANSLATIONAL) { auto line = best_line_from_points(centers); r.point = line.first; r.axis = line.second; // Sort parts in relation { Vector3 point, direction; MatrixXd curveCenters(r.parts.size(), 3); for (int pi = 0; pi < (int)r.parts.size(); pi++) curveCenters.row(pi) = shape->getNode(r.parts[pi])->position(Eigen::Vector4d(0.5, 0.5, 0, 0)); point = Vector3(curveCenters.colwise().mean()); curveCenters = curveCenters.rowwise() - point.transpose(); Eigen::JacobiSVD<Eigen::MatrixXd> svd(curveCenters, Eigen::ComputeThinU | Eigen::ComputeThinV); direction = Vector3(svd.matrixV().col(0)).normalized(); std::vector <size_t> sorted; QMap<size_t, double> dists; for (size_t pi = 0; pi < (int)r.parts.size(); pi++) dists[pi] = curveCenters.row(pi).dot(direction); for (auto p : sortQMapByValue(dists)) sorted.push_back(p.second); QStringList sortedParts; for (auto idx : sorted) sortedParts << r.parts[idx]; r.parts = sortedParts; } } if (r.type == Structure::Relation::ROTATIONAL) { auto plane = best_plane_from_points(centers); r.point = plane.first; r.axis = plane.second; // Sort parts by angle around axis QStringList sorted; QMap<QString, double> angles; for (size_t i = 0; i < r.parts.size(); i++) { double angle = signedAngle(centers[0], centers[i], r.axis); if (angle < 0) angle = (M_PI * 2) + angle; angles[r.parts[i]] = angle; } for (auto pair : sortQMapByValue(angles)) sorted << pair.second; r.parts = sorted; // Vector from part's head to centroid for (size_t i = 0; i < r.parts.size(); i++) r.deltas.push_back(centroid - shape->getNode(r.parts[i])->position(Eigen::Vector4d(0.5, 0.5, 0, 0))); } } // Record volume of relation { double relationVolume = 0.0; for (auto partID : r.parts){ auto mesh = shape->getNode(partID)->property["mesh"].value< QSharedPointer<SurfaceMeshModel> >(); if (mesh.isNull()) continue; relationVolume += PhysicsHelper(mesh.data()).volume(); } if (relationVolume == 0.0) relationVolume = 1.0; r.property["volume"].setValue(relationVolume); } // Add relation to shape: shape->relations.push_back(r); for (auto partID : r.parts) { auto node = shape->getNode(partID); node->property["groupParts"].setValue(r.parts); if (r.type == Structure::Relation::ROTATIONAL) node->property["isRotational"].setValue(true); } // Visualize: if (isDebug) { shape->debug << starlab::PointSoup::drawPoint(r.point, 12, Qt::red); if (r.type != Structure::Relation::TRANSLATIONAL) { auto plane = new starlab::PlaneSoup(0.1, true, r.type == Structure::Relation::REFLECTIONAL ? Qt::red : Qt::green); plane->addPlane(r.point, r.axis); shape->debug << plane; } else { auto line = new starlab::LineSegments(3); line->addLine(r.point, Vector3(r.point + r.axis)); shape->debug << line; } } } // Same height grouping { DisjointSet set(shape->nodes.size()); double range_z = shape->robustBBox().sizes().z(); double threshold = 0.05; QMap < Structure::Node*, int > idx_map; int idx = 0; for (auto n : shape->nodes) idx_map[n] = idx++; for (auto ni : shape->nodes){ for (auto nj : shape->nodes){ double zi = ni->center().z(); double zj = nj->center().z(); double dist = abs(zi - zj); if (dist < range_z * threshold) set.Union(idx_map[ni], idx_map[nj]); } } auto hight_groups = set.Groups(); for (auto hight_group : hight_groups){ for (auto ni : hight_group){ auto node_i = shape->nodes.at(ni); QStringList height_siblings; for (auto nj : hight_group){ if (ni == nj) continue; auto node_j = shape->nodes.at(nj); height_siblings << node_j->id; } node_i->property.insert("height_siblings", height_siblings); } } } } std::pair<Vector3, Vector3> StructureAnalysis::getReflectionalPlane(Structure::Node * n1, Structure::Node * n2) { Vector3 point(0, 0, 0), axis(0, 0, 0); int num_samples = 10; for (int i = 0; i < num_samples; i++) { double t = double(i) / (num_samples - 1); auto p = n1->position(Eigen::Vector4d(t, t, 0, 0)); auto q = n2->position(Eigen::Vector4d(t, t, 0, 0)); point += (p + q) * 0.5; axis += (p - q).normalized(); } point /= num_samples; axis /= num_samples; axis.normalize(); return std::make_pair(point, axis); } SurfaceMesh::Vector3 StructureAnalysis::pointReflection(const Vector3 & p, const Vector3 & planePoint, const Vector3 & planeNormal) { double d = (p - planePoint).dot(planeNormal); Vector3 v = planeNormal * d; return p - (v * 2); } void StructureAnalysis::removeFromGroups(Structure::ShapeGraph * shape, Structure::Node * node) { for (auto & r : shape->relations) r.parts.removeAll(node->id); } void StructureAnalysis::updateRelation(Structure::ShapeGraph * shape, Structure::Relation & r) { std::vector<Vector3> centers; Vector3 centroid(0, 0, 0); for (auto part : r.parts) centers.push_back(shape->getNode(part)->position(Eigen::Vector4d(0.5, 0.5, 0, 0))); if (r.type == Structure::Relation::REFLECTIONAL) { } if (r.type == Structure::Relation::ROTATIONAL) { auto plane = best_plane_from_points(centers); r.point = plane.first; r.axis = plane.second; // Vector from part's head to centroid for (size_t i = 0; i < r.parts.size(); i++) r.deltas[i] = centroid - shape->getNode(r.parts[i])->position(Eigen::Vector4d(0.5, 0.5, 0, 0)); } }
[ "ennetws@gmail.com" ]
ennetws@gmail.com
aa6c95ce6703066b04be98cdab7f507f63c71106
55ca9323779bf243b155564a14f3adfe4acc6b3b
/[COGS_1]a_plus_b/a_plus_b.cpp
2fb562ae3e844b2455315409122156b37ef5eaf1
[]
no_license
xzcxzcyy/algorithm
6c7c2faa6b80e1031c9ff1a3a57eede63a450494
6e42f98f99e5d6a31d43139ad332fa21345475f0
refs/heads/master
2021-06-26T00:53:50.217442
2020-09-14T14:41:18
2020-09-14T14:41:18
93,413,846
2
0
null
null
null
null
UTF-8
C++
false
false
327
cpp
#include <iostream> #include <cstdio> #include <iomanip> #define DEBUG using namespace std; double a, b; int main() { #ifndef DEBUG freopen("aplusb.in", "r", stdin); freopen("aplusb.out", "w", stdout); #endif cin >> a >> b; cout << setiosflags(ios::fixed) << setprecision(0) << a + b << endl; return 0; }
[ "xzcxzcyy@126.com" ]
xzcxzcyy@126.com
ee6fb3f7b5c257e91daaaafaa5eb046b0787c3b3
c4f04d6136a30a704c437dd59c7b190011916017
/src/Scene.cpp
59aae8606ce758671ceb6997f186c65b5aa4b308
[]
no_license
Bluedream-eric/SurfaceReconstruction
2a065da8f9386b993935bdf23b1811e84490b2ac
378daac351db93773a3b2361ab18cf99e30e9821
refs/heads/master
2020-12-27T11:56:05.844748
2017-03-22T07:41:11
2017-03-22T07:41:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,587
cpp
#include "Scene.hpp" #include "PointCloud.hpp" #include "BaseEntity.hpp" #include "MoveableEntity.hpp" #include "DynamicCamera.hpp" Scene* Scene::s_pInstance = NULL; Scene::~Scene() { // Clear and delete sets m_pStaticEntities->clear(); delete m_pStaticEntities; m_pMoveableEntities->clear(); delete m_pMoveableEntities; m_pStaticCameras->clear(); delete m_pStaticCameras; m_pDynamicCameras->clear(); delete m_pDynamicCameras; m_pDestroyedEntities->clear(); delete m_pDestroyedEntities; // Remove anything from queues and delete while (!m_pDynamicCamerasQueue->empty()) { delete m_pDynamicCamerasQueue->front(); m_pDynamicCamerasQueue->pop(); } delete m_pDynamicCamerasQueue; while (!m_pMoveableEntitesQueue->empty()) { delete m_pMoveableEntitesQueue->front(); m_pMoveableEntitesQueue->pop(); } delete m_pMoveableEntitesQueue; // Delete all entities and map for (auto i : *m_pEntities) { delete i.second; } m_pEntities->clear(); delete m_pEntities; // Delete all models for (auto i : *m_pPointClouds) { delete i.second; } m_pPointClouds->clear(); delete m_pPointClouds; } void Scene::AddEntity(BaseEntity* entity) { m_pEntities->insert(std::make_pair(entity->ID(), entity)); } void Scene::AddToMoveableQueue(MoveableEntity* entity) { // Add to queue if not in init otherwise // add directly to set and map if (!m_bInit) { m_pMoveableEntitesQueue->push(entity); } else { m_pMoveableEntities->insert(entity->ID()); m_pEntities->insert(std::make_pair(entity->ID(), entity)); } } void Scene::AddToDynamicQueue(DynamicCamera* entity) { // Add to queue if not in init otherwise // add directly to set and map if (!m_bInit) { m_pDynamicCamerasQueue->push(entity); } else { m_pDynamicCameras->insert(entity->ID()); m_pEntities->insert(std::make_pair(entity->ID(), entity)); } } void Scene::Update() { Preprocess(); // Update moveable entities for (int id : *m_pMoveableEntities) { if (m_pDestroyedEntities->find(id) == m_pDestroyedEntities->end()) { ((MoveableEntity*)m_pEntities->at(id))->Update(); } } // Update dynamic cameras for (int id : *m_pDynamicCameras) { if (m_pDestroyedEntities->find(id) == m_pDestroyedEntities->end()) { ((DynamicCamera*)m_pEntities->at(id))->Update(); } } } void Scene::Preprocess() { // Remove all destroyed entities if (m_pDestroyedEntities->size() > 0) { for (int id : *m_pDestroyedEntities) { m_pStaticEntities->erase(id); m_pMoveableEntities->erase(id); m_pDynamicCameras->erase(id); // Change camera if necessary if (*m_itViewingCamera == id) { NextCamera(); } m_pStaticCameras->erase(id); delete m_pEntities->at(id); m_pEntities->erase(id); } m_pDestroyedEntities->clear(); } // Empty queues into sets and map while (!m_pMoveableEntitesQueue->empty()) { MoveableEntity* entity = m_pMoveableEntitesQueue->front(); m_pMoveableEntities->insert(entity->ID()); m_pEntities->insert(std::make_pair(entity->ID(), entity)); m_pMoveableEntitesQueue->pop(); } while (!m_pDynamicCamerasQueue->empty()) { DynamicCamera* entity = m_pDynamicCamerasQueue->front(); m_pDynamicCameras->insert(entity->ID()); m_pEntities->insert(std::make_pair(entity->ID(), entity)); m_pDynamicCamerasQueue->pop(); } } void Scene::AddPointCloud(PointCloud* pointCloud) { std::string file = pointCloud->File(); size_t f1 = file.find_last_of('/'); size_t f2 = file.find_last_of('.'); file = file.substr(f1 + 1, f2 - f1 - 1); m_pPointClouds->insert(std::make_pair(file, pointCloud)); }
[ "korydondzila@gmail.com" ]
korydondzila@gmail.com
357ec3fd2a9b7564a253de1f3f1a109e6e72e3a5
372dc502da0afae10078f231a2158a2aefc45890
/medialib/src/main/cpp/modules/skottie/include/utils/SkLua.h
ea847bb5452f8bdece81bc87d9918b7b8f230df2
[]
no_license
chongbo2013/LottieRecoder
e8a8c589ad317948c7d4415bd5766a53d30f7ad4
4732aba62222aadc346a28173554051b883590e2
refs/heads/master
2021-07-12T23:52:17.324668
2020-07-31T05:32:09
2020-07-31T05:32:09
185,334,538
4
2
null
null
null
null
UTF-8
C++
false
false
2,362
h
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkLua_DEFINED #define SkLua_DEFINED #include "../core/SkColor.h" #include "../core/SkPathEffect.h" #include "../core/SkScalar.h" #include "../core/SkString.h" struct lua_State; class SkCanvas; class SkMatrix; class SkPaint; class SkPath; struct SkRect; class SkRRect; class SkTextBlob; #define SkScalarToLua(x) SkScalarToDouble(x) #define SkLuaToScalar(x) SkDoubleToScalar(x) class SkLua { public: static void Load(lua_State*); SkLua(const char termCode[] = nullptr); // creates a new L, will close it SkLua(lua_State*); // uses L, will not close it ~SkLua(); lua_State* get() const { return fL; } lua_State* operator*() const { return fL; } lua_State* operator->() const { return fL; } bool runCode(const char code[]); bool runCode(const void* code, size_t size); void pushBool(bool, const char tableKey[] = nullptr); void pushString(const char[], const char tableKey[] = nullptr); void pushString(const char[], size_t len, const char tableKey[] = nullptr); void pushString(const SkString&, const char tableKey[] = nullptr); void pushArrayU16(const uint16_t[], int count, const char tableKey[] = nullptr); void pushArrayPoint(const SkPoint[], int count, const char key[] = nullptr); void pushArrayScalar(const SkScalar[], int count, const char key[] = nullptr); void pushColor(SkColor, const char tableKey[] = nullptr); void pushU32(uint32_t, const char tableKey[] = nullptr); void pushScalar(SkScalar, const char tableKey[] = nullptr); void pushRect(const SkRect&, const char tableKey[] = nullptr); void pushRRect(const SkRRect&, const char tableKey[] = nullptr); void pushDash(const SkPathEffect::DashInfo&, const char tableKey[] = nullptr); void pushMatrix(const SkMatrix&, const char tableKey[] = nullptr); void pushPaint(const SkPaint&, const char tableKey[] = nullptr); void pushPath(const SkPath&, const char tableKey[] = nullptr); void pushCanvas(SkCanvas*, const char tableKey[] = nullptr); void pushTextBlob(const SkTextBlob*, const char tableKey[] = nullptr); private: lua_State* fL; SkString fTermCode; bool fWeOwnL; }; #endif
[ "459821731@qq.com" ]
459821731@qq.com
2f1ec13c8f5419f5ab6515f5fae5773a345e4d1d
d860f6cca75c160ee22f5fec1a14626ce3e3f11d
/qtProject/bspline_blended.h
fb7a74df9562fa52b13e654f678541411233ed26
[]
no_license
mrbrian/589_Project
ccc7efd15b4485be44a2ab3ee8a5cb915e11f807
8175347e0e40413eb1c188a97d7b0bb3cad30ad2
refs/heads/master
2021-01-10T06:14:39.366740
2016-04-10T19:48:45
2016-04-10T19:48:45
53,610,103
0
0
null
2016-04-10T19:49:21
2016-03-10T19:11:38
C++
UTF-8
C++
false
false
1,733
h
#ifndef BSPLINE_BLENDED_H #define BSPLINE_BLENDED_H #include <vector> #include "bspline.h" using namespace std; class BSpline_Blended : public BSpline { public: BSpline_Blended(float bf, int k, vector<BSpline*> *b); QVector2D *evalPoint(float blend_factor, float u); QVector2D *evalPoint(float u) override; void getLinePoints(vector<QVector2D*> *list, vector<float> *u_list, float step_u) override; private: float m_blend_factor; vector<BSpline*> *splines; QVector2D *effSum(int d, float blend_factor, float u); /* BSpline(int k, vector<QVector2D*> *pts); void setOrder(int in_k); // setter void setKnots(float *U); // setter void setControlPoints(vector<QVector2D*> *p); // setter QVector2D *evalPoint(float step_u); virtual void getLinePoints(vector<QVector2D*> *list, vector<float> *u_list, float step_u); // evaluate a list of points on the curve int getIndexOfFocus(float u); // find the index of focus QVector2D *effSum(int d, float u, vector<QVector2D*> *geoPts, vector<QVector2D*> *convexPts); // efficient algorithm to evaluate a point on the curve static float *standardKnotSeq(int m, int k); // generates the standard knot sequence for given m and k static double bSplineBasis(int i, int m, int k, double u, float *knots); // evaluate a specified bspline basis func int getOrder(); // getter float *getKnots(); // getter vector<QVector2D*> *getControlPts(); // getter private: int k; // curve order float *knots; // knot array vector<QVector2D*> *ctrlPts; // a pointer to the control point list in program */ }; #endif // BSPLINE_BLENDED_H
[ "bgyee@ucalgary.ca" ]
bgyee@ucalgary.ca
7c929d1a43a840f858f9f19d58ebb41703bd7298
cd2cd6ffdc5646b442f63b1fa4ef7448333b7ee4
/cpp/506.相对名次.cpp
c5efad010ad82adb2686d054483657e763348527
[]
no_license
mtai000/leetcode
aabd3e016a19a7147622f6ff19e6ac6a7dcd7238
7a7472c432602eaabe77ef92144471b0fa7ecf90
refs/heads/master
2021-08-04T02:09:16.987763
2021-07-16T14:54:25
2021-07-16T14:54:25
219,299,171
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
/* * @lc app=leetcode.cn id=506 lang=cpp * * [506] 相对名次 */ // @lc code=start class Solution { public: vector<string> findRelativeRanks(vector<int>& nums) { } }; // @lc code=end
[ "605836858@qq.com" ]
605836858@qq.com
7dbc4246aaebf3a882634d048e8a97abe36eac27
ea41f3b5a72fae03686173c644529ded1f4cde97
/winsdkvk/winsdkvk.Shared/API/Networking/GZipExtensions.cpp
6100377ef5cbe86fb252ce30aee756c851d9c79d
[]
no_license
i-z/winsdkvk
51702d756de8965deef3f0f5a9b3dc43c611c24b
61531dc69d6640487eff1e83fab234713f7e594f
refs/heads/master
2021-01-10T18:31:41.178659
2016-06-01T11:06:08
2016-06-01T11:06:08
59,741,231
0
0
null
null
null
null
UTF-8
C++
false
false
9,934
cpp
using namespace System; #include "GZipExtensions.h" using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace System::Diagnostics; using namespace System::Diagnostics::CodeAnalysis; using namespace System::IO; using namespace System::Net; using namespace System::Windows; using namespace System::Windows::Resources; namespace winsdkvk { namespace WindowsPhone { namespace SDK { namespace API { namespace Networking { void GzipExtensions::AddAcceptEncodingHeader(HttpWebRequest ^request) { if (nullptr == request) { throw ref new ArgumentNullException("request"); } request->Headers[HttpRequestHeader::AcceptEncoding] = GZIP; } IAsyncResult ^GzipExtensions::BeginGetCompressedResponse(HttpWebRequest ^request, AsyncCallback ^callback, Platform::Object ^state) { AddAcceptEncodingHeader(request); return request->BeginGetResponse(callback, state); } Stream ^GzipExtensions::GetCompressedResponseStream(HttpWebResponse ^response) { // Validate arguments if (nullptr == response) { throw ref new ArgumentNullException("response"); } // Check the response for GZIP auto responseStream = response->GetResponseStream(); if (Platform::String::Equals(response->Headers[HttpRequestHeader::ContentEncoding], GZIP, StringComparison::OrdinalIgnoreCase)) { // Read header if ((0x1f != responseStream->ReadByte()) || (0x8b != responseStream->ReadByte()) || (8 != responseStream->ReadByte())) // CM (8 == deflate) - ID2 - ID1 { throw ref new NotSupportedException("Compressed data not in the expected format."); } // Read flags auto flg = responseStream->ReadByte(); // FLG auto fhcrc = 0 != (0x2 & flg); // CRC16 present before compressed data auto fextra = 0 != (0x4 & flg); // extra fields present auto fname = 0 != (0x8 & flg); // original file name present auto fcomment = 0 != (0x10 & flg); // file comment present // Skip unsupported fields responseStream->ReadByte(); responseStream->ReadByte(); responseStream->ReadByte(); responseStream->ReadByte(); // MTIME responseStream->ReadByte(); // XFL responseStream->ReadByte(); // OS if (fextra) { // Skip XLEN bytes of data auto xlen = responseStream->ReadByte() | (responseStream->ReadByte() << 8); while (0 < xlen) { responseStream->ReadByte(); xlen--; } } if (fname) { // Skip 0-terminated file name while (0 != responseStream->ReadByte()) { } } if (fcomment) { // Skip 0-terminated file comment while (0 != responseStream->ReadByte()) { } } if (fhcrc) { responseStream->ReadByte(); responseStream->ReadByte(); // CRC16 } // Read compressed data const int32 zipHeaderSize = 30 + 1; // 30 bytes + 1 character for file name const int32 zipFooterSize = 68 + 1; // 68 bytes + 1 character for file name // Download unknown amount of compressed data efficiently (note: Content-Length header is not always reliable) auto buffers = ref new List<Platform::Array<uint8>^>(); auto buffer = ref new Platform::Array<uint8>(4096); auto bytesInBuffer = 0; auto totalBytes = 0; auto bytesRead = 0; do { if (buffer->Length == bytesInBuffer) { // Full, allocate another buffers->Add(buffer); buffer = ref new Platform::Array<uint8>(buffer->Length); bytesInBuffer = 0; } Debug::Assert(bytesInBuffer < buffer->Length); bytesRead = responseStream->Read(buffer, bytesInBuffer, buffer->Length - bytesInBuffer); bytesInBuffer += bytesRead; totalBytes += bytesRead; } while (0 < bytesRead); buffers->Add(buffer); // "Trim" crc32 and isize fields off the end auto compressedSize = totalBytes - 4 - 4; if (compressedSize < 0) { throw ref new NotSupportedException("Compressed data not in the expected format."); } // Create contiguous buffer auto compressedBytes = ref new Platform::Array<uint8>(zipHeaderSize + compressedSize + zipFooterSize); auto offset = zipHeaderSize; auto remainingBytes = totalBytes; for (auto b : buffers) { auto length = Math::Min(b->Length, remainingBytes); Array::Copy(b, 0, compressedBytes, offset, length); offset += length; remainingBytes -= length; } Debug::Assert(0 == remainingBytes); // Read footer from end of compressed bytes (note: footer is within zipFooterSize; will be overwritten below) Debug::Assert(totalBytes <= compressedSize + zipFooterSize); offset = zipHeaderSize + compressedSize; auto crc32 = compressedBytes[offset + 0] | (compressedBytes[offset + 1] << 8) | (compressedBytes[offset + 2] << 16) | (compressedBytes[offset + 3] << 24); auto isize = compressedBytes[offset + 4] | (compressedBytes[offset + 5] << 8) | (compressedBytes[offset + 6] << 16) | (compressedBytes[offset + 7] << 24); // Create ZIP file stream Platform::String ^ const fileName = "f"; // MUST be 1 character (offsets below assume this) Debug::Assert(1 == fileName->Length); auto zipFileMemoryStream = ref new MemoryStream(compressedBytes); auto writer = ref new BinaryWriter(zipFileMemoryStream); // Local file header writer->Write(safe_cast<uint32>(0x04034b50)); // local file header signature writer->Write(safe_cast<uint16>(20)); // version needed to extract (2.0 == compressed using deflate) writer->Write(safe_cast<uint16>(0)); // general purpose bit flag writer->Write(safe_cast<uint16>(8)); // compression method (8: deflate) writer->Write(safe_cast<uint16>(0)); // last mod file time writer->Write(safe_cast<uint16>(0)); // last mod file date writer->Write(crc32); // crc-32 writer->Write(compressedSize); // compressed size writer->Write(isize); // uncompressed size writer->Write(safe_cast<uint16>(1)); // file name length writer->Write(safe_cast<uint16>(0)); // extra field length writer->Write(safe_cast<uint8>(fileName[0])); // file name // File data (already present) zipFileMemoryStream->Seek(compressedSize, SeekOrigin::Current); // Central directory structure writer->Write(safe_cast<uint32>(0x02014b50)); // central file header signature writer->Write(safe_cast<uint16>(20)); // version made by writer->Write(safe_cast<uint16>(20)); // version needed to extract (2.0 == compressed using deflate) writer->Write(safe_cast<uint16>(0)); // general purpose bit flag writer->Write(safe_cast<uint16>(8)); // compression method writer->Write(safe_cast<uint16>(0)); // last mod file time writer->Write(safe_cast<uint16>(0)); // last mod file date writer->Write(crc32); // crc-32 writer->Write(compressedSize); // compressed size writer->Write(isize); // uncompressed size writer->Write(safe_cast<uint16>(1)); // file name length writer->Write(safe_cast<uint16>(0)); // extra field length writer->Write(safe_cast<uint16>(0)); // file comment length writer->Write(safe_cast<uint16>(0)); // disk number start writer->Write(safe_cast<uint16>(0)); // internal file attributes writer->Write(safe_cast<uint32>(0)); // external file attributes writer->Write(safe_cast<uint32>(0)); // relative offset of local header writer->Write(safe_cast<uint8>(fileName[0])); // file name // End of central directory record writer->Write(safe_cast<uint32>(0x06054b50)); // end of central dir signature writer->Write(safe_cast<uint16>(0)); // number of this disk writer->Write(safe_cast<uint16>(0)); // number of the disk with the start of the central directory writer->Write(safe_cast<uint16>(1)); // total number of entries in the central directory on this disk writer->Write(safe_cast<uint16>(1)); // total number of entries in the central directory writer->Write(safe_cast<uint32>(46 + 1)); // size of the central directory (46 bytes + 1 character for file name) writer->Write(safe_cast<uint32>(zipHeaderSize + compressedSize)); // offset of start of central directory with respect to the starting disk number writer->Write(safe_cast<uint16>(0)); // .ZIP file comment length // Reset ZIP file stream to beginning zipFileMemoryStream->Seek(0, SeekOrigin::Begin); auto sw = Stopwatch::StartNew(); // Return the decompressed stream auto decompressedStream = Application::GetResourceStream(ref new StreamResourceInfo(zipFileMemoryStream, nullptr), ref new Uri(fileName, UriKind::Relative)).Stream; sw->Stop(); Debug::WriteLine("Decompression took " + sw->ElapsedMilliseconds + "ms."); LogCompression(zipFileMemoryStream->Length, decompressedStream->Length); return decompressedStream; } else { // Not GZIP-compressed; return stream as-is return responseStream; } } void GzipExtensions::LogCompression(int64 compressedStreamLength, int64 decompressedStreamLength) { float64 ratio = -1; if (decompressedStreamLength > 0) { ratio = safe_cast<float64>(compressedStreamLength) / decompressedStreamLength; } Debug::WriteLine(Platform::String::Format("CompressedLength={0}, DecompressedLength={1}, Ratio={2}", compressedStreamLength, decompressedStreamLength, ratio)); } } } } } }
[ "igor.zubkov@nevosoft.ru" ]
igor.zubkov@nevosoft.ru
f7c31acc64ece67fbd243b616614cd8fb06b6fb4
a1091ad42e6a07b6fbb6fe876feb03547a8da1eb
/MITK-superbuild/MITK-build/Modules/RigidRegistration/mitkPyramidalRegistrationMethod-int.cpp
478c05a5c77d6fea7b8a4e7d4bca237d42a75144
[]
no_license
Sotatek-TuyenLuu/DP2
bc61866fe5d388dd11209f4d02744df073ec114f
a48dd0a41c788981009c5ddd034b0e21644c8077
refs/heads/master
2020-03-10T04:59:52.461184
2018-04-12T07:19:27
2018-04-12T07:19:27
129,206,578
1
0
null
null
null
null
UTF-8
C++
false
false
926
cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkPyramidalRegistrationMethodAccessFunctor.txx> #include <mitkInstantiateAccessFunctions.h> #define InstantiateAccessFunction_PyramidalAccessItkImage(pixelType, dim) \ template void mitk::PyramidalRegistrationMethodAccessFunctor::AccessItkImage(const itk::Image<pixelType, dim>* itkImage1, mitk::PyramidalRegistrationMethod* method); InstantiateAccessFunctionForFixedPixelType(PyramidalAccessItkImage, (int))
[ "tuyen.luu@sotatek.com" ]
tuyen.luu@sotatek.com
c0c1707a5cea66e6ff91138abb189b92e715952e
68595eb8a484a2ce24590b144b2697acd9de2369
/Qt/connect/build-server/ui_mainwindow.h
6eac46f54bcec5d884769207655f6c428611d136
[]
no_license
bamshad-shrm/socketProgramming
2a9cf6cab1b2a43d86718c88452eb6690427587c
83b61bb74ab6e00fe6076896baca65966b5e915c
refs/heads/master
2022-12-04T00:10:33.883058
2020-08-24T15:52:17
2020-08-24T15:52:17
289,970,526
0
0
null
null
null
null
UTF-8
C++
false
false
4,332
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.9.5 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QMainWindow> #include <QtWidgets/QPushButton> #include <QtWidgets/QScrollArea> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QGridLayout *gridLayout_2; QLabel *label; QPushButton *stopButton; QLineEdit *portlineEdit; QSpacerItem *horizontalSpacer; QScrollArea *scrollArea; QWidget *scrollAreaWidgetContents; QGridLayout *gridLayout; QLabel *infoLable; QPushButton *startButton; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(726, 490); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); gridLayout_2 = new QGridLayout(centralWidget); gridLayout_2->setSpacing(6); gridLayout_2->setContentsMargins(11, 11, 11, 11); gridLayout_2->setObjectName(QStringLiteral("gridLayout_2")); label = new QLabel(centralWidget); label->setObjectName(QStringLiteral("label")); gridLayout_2->addWidget(label, 0, 1, 1, 1); stopButton = new QPushButton(centralWidget); stopButton->setObjectName(QStringLiteral("stopButton")); gridLayout_2->addWidget(stopButton, 0, 6, 1, 1); portlineEdit = new QLineEdit(centralWidget); portlineEdit->setObjectName(QStringLiteral("portlineEdit")); gridLayout_2->addWidget(portlineEdit, 0, 3, 1, 1); horizontalSpacer = new QSpacerItem(446, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); gridLayout_2->addItem(horizontalSpacer, 0, 5, 1, 1); scrollArea = new QScrollArea(centralWidget); scrollArea->setObjectName(QStringLiteral("scrollArea")); scrollArea->setWidgetResizable(true); scrollAreaWidgetContents = new QWidget(); scrollAreaWidgetContents->setObjectName(QStringLiteral("scrollAreaWidgetContents")); scrollAreaWidgetContents->setGeometry(QRect(0, 0, 706, 439)); gridLayout = new QGridLayout(scrollAreaWidgetContents); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); infoLable = new QLabel(scrollAreaWidgetContents); infoLable->setObjectName(QStringLiteral("infoLable")); infoLable->setFrameShape(QFrame::Box); infoLable->setLineWidth(2); gridLayout->addWidget(infoLable, 0, 0, 1, 1); scrollArea->setWidget(scrollAreaWidgetContents); gridLayout_2->addWidget(scrollArea, 4, 0, 1, 7); startButton = new QPushButton(centralWidget); startButton->setObjectName(QStringLiteral("startButton")); gridLayout_2->addWidget(startButton, 0, 4, 1, 1); MainWindow->setCentralWidget(centralWidget); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "Server", Q_NULLPTR)); label->setText(QApplication::translate("MainWindow", "Port:", Q_NULLPTR)); stopButton->setText(QApplication::translate("MainWindow", "Stop", Q_NULLPTR)); infoLable->setText(QString()); startButton->setText(QApplication::translate("MainWindow", "Start", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
[ "bamshad.shm@gmail.com" ]
bamshad.shm@gmail.com
84dcb27b1cf3d72f97c4f09e0fd1a6848241a50f
c09e3ed57ff3aaa9f7f1632e3f633de994d9b774
/src/vproducer/producer.hpp
49ef30e228fce19be8f8c569ed0c9a6cd999f152
[]
no_license
qbcir/vproducer
5cd41bb7106c3896b18b2b566051eb5098548e38
2bd576c5e057396e22f1de374e1412f2bf11e1f6
refs/heads/master
2020-05-27T21:07:05.644537
2019-07-09T19:30:51
2019-07-09T19:30:51
188,791,493
0
0
null
null
null
null
UTF-8
C++
false
false
585
hpp
#ifndef __NNXCAM_VPROD_PRODUCER_HPP_21897__ #define __NNXCAM_VPROD_PRODUCER_HPP_21897__ #include <mutex> #include <vector> #include <thread> #include "reader.hpp" #include "common/shm_queue.hpp" namespace nnxcam { class Producer { public: static void init(); bool read_config(const std::string& config_path); void run(); private: std::mutex _queue_lock; std::vector<CameraConfig> _cameras; std::vector<std::shared_ptr<Reader>> _readers; std::vector<std::thread> _threads; ShmQueue _shm_queue; }; } #endif /* __NNXCAM_VPROD_PRODUCER_HPP_21897__ */
[ "alex.golenev@gmail.com" ]
alex.golenev@gmail.com
e3970629ae80a0a6cf1e397ae115917a95a5db30
436623ee85c9d9444d700b56f2729b12b9f2c659
/include/eepp/ui/css/propertydefinition.hpp
c79ca36c3d634e04347453defd70d3a1b80981e2
[ "MIT" ]
permissive
SpartanJ/eepp
0bd271b33058ef119f5c34460ed94e44df882a25
9f64a2149f3a0842ced34b8b981ffe3a8efc6d13
refs/heads/develop
2023-09-01T01:17:30.155540
2023-08-27T20:58:19
2023-08-27T20:58:19
125,767,856
341
27
MIT
2023-04-01T20:10:26
2018-03-18T21:11:21
C++
UTF-8
C++
false
false
12,575
hpp
#ifndef EE_UI_CSS_PROPERTYDEFINITION_HPP #define EE_UI_CSS_PROPERTYDEFINITION_HPP #include <eepp/config.hpp> #include <eepp/core/string.hpp> namespace EE { namespace UI { namespace CSS { enum class PropertyId : Uint32 { Id = String::hash( "id" ), Class = String::hash( "class" ), X = String::hash( "x" ), Y = String::hash( "y" ), Width = String::hash( "width" ), Height = String::hash( "height" ), BackgroundColor = String::hash( "background-color" ), BackgroundImage = String::hash( "background-image" ), BackgroundTint = String::hash( "background-tint" ), BackgroundPositionX = String::hash( "background-position-x" ), BackgroundPositionY = String::hash( "background-position-y" ), BackgroundRepeat = String::hash( "background-repeat" ), BackgroundSize = String::hash( "background-size" ), ForegroundColor = String::hash( "foreground-color" ), ForegroundTint = String::hash( "foreground-tint" ), ForegroundImage = String::hash( "foreground-image" ), ForegroundPositionX = String::hash( "foreground-position-x" ), ForegroundPositionY = String::hash( "foreground-position-y" ), ForegroundRepeat = String::hash( "foreground-repeat" ), ForegroundSize = String::hash( "foreground-size" ), ForegroundRadius = String::hash( "foreground-radius" ), Visible = String::hash( "visible" ), Enabled = String::hash( "enabled" ), Theme = String::hash( "theme" ), Skin = String::hash( "skin" ), SkinColor = String::hash( "skin-color" ), Gravity = String::hash( "gravity" ), Flags = String::hash( "flags" ), MarginLeft = String::hash( "margin-left" ), MarginRight = String::hash( "margin-right" ), MarginTop = String::hash( "margin-top" ), MarginBottom = String::hash( "margin-bottom" ), Tooltip = String::hash( "tooltip" ), LayoutWeight = String::hash( "layout-weight" ), LayoutGravity = String::hash( "layout-gravity" ), LayoutWidth = String::hash( "layout-width" ), LayoutHeight = String::hash( "layout-height" ), LayoutToLeftOf = String::hash( "layout-to-left-of" ), LayoutToRightOf = String::hash( "layout-to-right-of" ), LayoutToTopOf = String::hash( "layout-to-top-of" ), LayoutToBottomOf = String::hash( "layout-to-bottom-of" ), Clip = String::hash( "clip" ), Rotation = String::hash( "rotation" ), Scale = String::hash( "scale" ), RotationOriginPointX = String::hash( "rotation-origin-point-x" ), RotationOriginPointY = String::hash( "rotation-origin-point-y" ), ScaleOriginPointX = String::hash( "scale-origin-point-x" ), ScaleOriginPointY = String::hash( "scale-origin-point-y" ), BlendMode = String::hash( "blend-mode" ), PaddingLeft = String::hash( "padding-left" ), PaddingRight = String::hash( "padding-right" ), PaddingTop = String::hash( "padding-top" ), PaddingBottom = String::hash( "padding-bottom" ), Opacity = String::hash( "opacity" ), Cursor = String::hash( "cursor" ), Text = String::hash( "text" ), TextTransform = String::hash( "text-transform" ), Color = String::hash( "color" ), TextShadowColor = String::hash( "text-shadow-color" ), TextShadowOffset = String::hash( "text-shadow-offset" ), SelectionColor = String::hash( "selection-color" ), SelectionBackColor = String::hash( "selection-back-color" ), FontFamily = String::hash( "font-family" ), FontSize = String::hash( "font-size" ), FontStyle = String::hash( "font-style" ), TextDecoration = String::hash( "text-decoration" ), Wordwrap = String::hash( "word-wrap" ), TextStrokeWidth = String::hash( "text-stroke-width" ), TextStrokeColor = String::hash( "text-stroke-color" ), TextSelection = String::hash( "text-selection" ), TextAlign = String::hash( "text-align" ), Icon = String::hash( "icon" ), MinIconSize = String::hash( "min-icon-size" ), MinSize = String::hash( "min-size" ), MaxSize = String::hash( "max-size" ), Src = String::hash( "src" ), ScaleType = String::hash( "scale-type" ), Tint = String::hash( "tint" ), MaxTextLength = String::hash( "max-text-length" ), MinTabWidth = String::hash( "min-tab-width" ), MaxTabWidth = String::hash( "max-tab-width" ), TabClosable = String::hash( "tab-closable" ), TabsEdgesDiffSkin = String::hash( "tabs-edges-diff-skin" ), TabSeparation = String::hash( "tab-separation" ), TabHeight = String::hash( "tab-height" ), Selected = String::hash( "selected" ), Checked = String::hash( "checked" ), PopUpToRoot = String::hash( "popup-to-root" ), MaxVisibleItems = String::hash( "max-visible-items" ), SelectedIndex = String::hash( "selected-index" ), SelectedText = String::hash( "selected-text" ), ScrollBarStyle = String::hash( "scrollbar-style" ), RowHeight = String::hash( "row-height" ), VScrollMode = String::hash( "vscroll-mode" ), HScrollMode = String::hash( "hscroll-mode" ), ColumnMargin = String::hash( "column-margin" ), RowMargin = String::hash( "row-margin" ), ColumnMode = String::hash( "column-mode" ), RowMode = String::hash( "row-mode" ), ColumnWeight = String::hash( "column-weight" ), ColumnHeight = String::hash( "column-height" ), ColumnWidth = String::hash( "column-width" ), RowWeight = String::hash( "row-weight" ), ReverseDraw = String::hash( "reverse-draw" ), Orientation = String::hash( "orientation" ), Indeterminate = String::hash( "indeterminate" ), MaxProgress = String::hash( "max-progress" ), Progress = String::hash( "progress" ), FillColor = String::hash( "fill-color" ), Radius = String::hash( "radius" ), OutlineThickness = String::hash( "outline-thickness" ), AnimationSpeed = String::hash( "animation-speed" ), ArcStartAngle = String::hash( "arc-start-angle" ), MinWidth = String::hash( "min-width" ), MinHeight = String::hash( "min-height" ), MaxWidth = String::hash( "max-width" ), MaxHeight = String::hash( "max-height" ), TotalSteps = String::hash( "total-steps" ), VerticalExpand = String::hash( "vertical-expand" ), DisplayPercent = String::hash( "display-percent" ), MovementSpeed = String::hash( "movement-speed" ), MinValue = String::hash( "min-value" ), MaxValue = String::hash( "max-value" ), Value = String::hash( "value" ), ClickStep = String::hash( "click-step" ), PageStep = String::hash( "page-step" ), BackgroundExpand = String::hash( "background-expand" ), ScrollBarMode = String::hash( "scrollbar-mode" ), HalfSlider = String::hash( "half-slider" ), Owns = String::hash( "owns" ), AllowEditing = String::hash( "allow-editing" ), Locked = String::hash( "locked" ), MaxLength = String::hash( "max-length" ), Numeric = String::hash( "numeric" ), AllowFloat = String::hash( "allow-float" ), TouchDrag = String::hash( "touch-drag" ), TouchDragDeceleration = String::hash( "touch-drag-deceleration" ), WindowTitle = String::hash( "window-title" ), WindowOpacity = String::hash( "window-opacity" ), WindowButtonsOffset = String::hash( "window-buttons-offset" ), WindowFlags = String::hash( "window-flags" ), WindowTitlebarSize = String::hash( "window-titlebar-size" ), WindowBorderSize = String::hash( "window-border-size" ), WindowMinSize = String::hash( "window-min-size" ), WindowButtonsSeparation = String::hash( "window-buttons-separation" ), WindowCornerDistance = String::hash( "window-corner-distance" ), WindowTitlebarAutoSize = String::hash( "window-decoration-auto-size" ), WindowBorderAutoSize = String::hash( "window-border-auto-size" ), Hint = String::hash( "hint" ), HintColor = String::hash( "hint-color" ), HintShadowColor = String::hash( "hint-shadow-color" ), HintShadowOffset = String::hash( "hint-shadow-offset" ), HintFontFamily = String::hash( "hint-font-family" ), HintFontSize = String::hash( "hint-font-size" ), HintFontStyle = String::hash( "hint-font-style" ), HintStrokeWidth = String::hash( "hint-stroke-width" ), HintStrokeColor = String::hash( "hint-stroke-color" ), Transition = String::hash( "transition" ), TransitionDelay = String::hash( "transition-delay" ), TransitionDuration = String::hash( "transition-duration" ), TransitionProperty = String::hash( "transition-property" ), TransitionTimingFunction = String::hash( "transition-timing-function" ), Animation = String::hash( "animation" ), AnimationName = String::hash( "animation-name" ), AnimationDelay = String::hash( "animation-delay" ), AnimationDuration = String::hash( "animation-duration" ), AnimationFillMode = String::hash( "animation-fill-mode" ), AnimationIterationCount = String::hash( "animation-iteration-count" ), AnimationPlayState = String::hash( "animation-play-state" ), AnimationTimingFunction = String::hash( "animation-timing-function" ), DragResistance = String::hash( "drag-resistance" ), ChangePagePercent = String::hash( "change-page-percent" ), MaxEdgeResistance = String::hash( "max-edge-resistance" ), PageTransitionDuration = String::hash( "page-transition-duration" ), TimingFunction = String::hash( "timing-function" ), PageLocked = String::hash( "page-locked" ), BorderType = String::hash( "border-type" ), BorderLeftColor = String::hash( "border-left-color" ), BorderRightColor = String::hash( "border-right-color" ), BorderTopColor = String::hash( "border-top-color" ), BorderBottomColor = String::hash( "border-bottom-color" ), BorderLeftWidth = String::hash( "border-left-width" ), BorderRightWidth = String::hash( "border-right-width" ), BorderTopWidth = String::hash( "border-top-width" ), BorderBottomWidth = String::hash( "border-bottom-width" ), BorderTopLeftRadius = String::hash( "border-top-left-radius" ), BorderTopRightRadius = String::hash( "border-top-right-radius" ), BorderBottomLeftRadius = String::hash( "border-bottom-left-radius" ), BorderBottomRightRadius = String::hash( "border-bottom-right-radius" ), BorderSmooth = String::hash( "border-smooth" ), BackgroundSmooth = String::hash( "background-smooth" ), TabBarHideOnSingleTab = String::hash( "tabbar-hide-on-single-tab" ), TabBarAllowRearrange = String::hash( "tabbar-allow-rearrange" ), TabBarAllowDragAndDrop = String::hash( "tabbar-allow-drag-and-drop-tabs" ), TabAllowSwitchTabsInEmptySpaces = String::hash( "tabbar-allow-switch-tabs-in-empty-spaces" ), SplitterPartition = String::hash( "splitter-partition" ), SplitterAlwaysShow = String::hash( "splitter-always-show" ), DroppableHoveringColor = String::hash( "droppable-hovering-color" ), TextAsFallback = String::hash( "text-as-fallback" ), SelectOnClick = String::hash( "select-on-click" ), LineSpacing = String::hash( "line-spacing" ), GravityOwner = String::hash( "gravity-owner" ), Href = String::hash( "href" ), Focusable = String::hash( "focusable" ), InnerWidgetOrientation = String::hash( "inner-widget-orientation" ), Glyph = String::hash( "glyph" ), Name = String::hash( "name" ), RowValign = String::hash( "row-valign" ), }; enum class PropertyType : Uint32 { Undefined, String, Bool, NumberInt, NumberIntFixed, NumberFloat, NumberFloatFixed, NumberLength, NumberLengthFixed, RadiusLength, Color, Vector2, BackgroundSize, ForegroundSize, Time }; enum class PropertyRelativeTarget : Uint32 { None, ContainingBlockWidth, ContainingBlockHeight, FontSize, ParentFontSize, LineHeight, LocalBlockWidth, LocalBlockHeight, BackgroundWidth, BackgroundHeight, ForegroundWidth, ForegroundHeight, LocalBlockRadiusWidth, LocalBlockRadiusHeight }; class EE_API PropertyDefinition { public: static PropertyDefinition* New( const std::string& name, const std::string& defaultValue, const bool& inherited = false ); PropertyDefinition( const std::string& name, const std::string& defaultValue, const bool& inherited = false ); const std::string& getName() const; const String::HashType& getId() const; PropertyId getPropertyId() const; const std::string& getDefaultValue() const; bool getInherited() const; const PropertyRelativeTarget& getRelativeTarget() const; PropertyDefinition& setRelativeTarget( const PropertyRelativeTarget& relativeTarget ); PropertyDefinition& setType( const PropertyType& propertyType ); const PropertyType& getType() const; PropertyDefinition& addAlias( const std::string& alias ); bool isAlias( const std::string& alias ) const; bool isAlias( const Uint32& id ) const; bool isDefinition( const std::string& name ) const; bool isDefinition( const Uint32& id ) const; PropertyDefinition& setIndexed(); const bool& isIndexed() const; protected: std::string mName; String::HashType mId; std::vector<std::string> mAliases; std::vector<Uint32> mAliasesHash; std::string mDefaultValue; bool mInherited; bool mIndexed; PropertyRelativeTarget mRelativeTarget; PropertyType mPropertyType; }; }}} // namespace EE::UI::CSS #endif
[ "spartanj@gmail.com" ]
spartanj@gmail.com
cf5f8ecae14744cf4acced5dea7965e17c13efb7
2b984e87cc5239bda08a9de7ddd31ad2a18774d5
/baekjoon/1167.cpp
fc4dfbba58e029d96ff5f3802b25d07f32f71b7d
[]
no_license
pce913/Algorithm
f862d0f450471c3b910bcf50e684caf856ec4165
1cb695972ea6804c8d669a9b606f1aaf87360af6
refs/heads/master
2022-02-08T06:51:39.537054
2022-01-31T16:20:03
2022-01-31T16:20:03
110,357,251
0
0
null
null
null
null
UTF-8
C++
false
false
963
cpp
#include<stdio.h> #include<vector> #include<queue> #include<cstring> using namespace std; int dist[100001]; vector< pair<int,int> > A[100001]; void bfs(int x){ dist[x] = -1; queue<int> q; q.push(x); while (!q.empty()){ int node = q.front(); q.pop(); for (int i = 0; i < A[node].size(); i++){ int next = A[node][i].first; if (dist[next]==0){ dist[next] = dist[node] + A[node][i].second; q.push(next); } } } } int main(){ int N; scanf("%d", &N); for (int i = 1; i <= N; i++){ int a, b,c; scanf("%d", &a); while (true){ scanf("%d", &b); if (b == -1) break; scanf("%d", &c); A[a].push_back(make_pair(b, c)); } } bfs(1); int far=1; int max = dist[1]; for (int i = 2; i <= N; i++){ if (max < dist[i]){ max = dist[i]; far = i; } } memset(dist,0,sizeof(dist)); bfs(far); max = dist[1]; for (int i = 2; i <= N; i++){ if (max < dist[i]) max = dist[i]; } printf("%d",max+1); return 0; }
[ "pce0913@naver.com" ]
pce0913@naver.com
fe94e134635cdf5a03ce496f3f551e99fd85a621
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/graphics/libfreehand/files/patch-src_lib_libfreehand__utils.cpp
5cac8509992970b0dc0c9405171ba4613f4598d6
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C++
false
false
1,762
cpp
Regressed by https://github.com/unicode-org/icu/commit/480bec3ea652 libfreehand_utils.cpp:165:30: error: expected ';' after do/while statement U16_NEXT(s, j, length, c) ^ ; libfreehand_utils.cpp:168:23: error: use of undeclared identifier 'outbuf' U8_APPEND_UNSAFE(&outbuf[0], i, c); ^ libfreehand_utils.cpp:168:23: error: use of undeclared identifier 'outbuf' libfreehand_utils.cpp:168:23: error: use of undeclared identifier 'outbuf' libfreehand_utils.cpp:168:23: error: use of undeclared identifier 'outbuf' libfreehand_utils.cpp:168:23: error: use of undeclared identifier 'outbuf' libfreehand_utils.cpp:168:23: error: use of undeclared identifier 'outbuf' libfreehand_utils.cpp:168:23: error: use of undeclared identifier 'outbuf' libfreehand_utils.cpp:169:5: error: use of undeclared identifier 'outbuf'; did you mean 'setbuf'? outbuf[i] = 0; ^~~~~~ setbuf /usr/include/stdio.h:283:7: note: 'setbuf' declared here void setbuf(FILE * __restrict, char * __restrict); ^ libfreehand_utils.cpp:169:5: error: subscript of pointer to function type 'void (FILE *, char *)' (aka 'void (__sFILE *, char *)') outbuf[i] = 0; ^~~~~~ libfreehand_utils.cpp:171:25: error: use of undeclared identifier 'outbuf' text.append((char *)outbuf); ^ --- src/lib/libfreehand_utils.cpp.orig 2017-09-16 10:28:50 UTC +++ src/lib/libfreehand_utils.cpp @@ -162,7 +162,7 @@ void libfreehand::_appendUTF16(librevenge::RVNGString while (j < length) { UChar32 c; - U16_NEXT(s, j, length, c) + U16_NEXT(s, j, length, c); unsigned char outbuf[U8_MAX_LENGTH+1]; int i = 0; U8_APPEND_UNSAFE(&outbuf[0], i, c);
[ "jbeich@FreeBSD.org" ]
jbeich@FreeBSD.org
08a06cd2499b50b3fa3d0204892042891d359097
1f16e283f72586254ac1a70d3cfd2035cbec7b30
/Proto8Projects/Proto8Template/P8Interface.h
93b6b27dbb8e3e09391305e37cd2556310e40a7a
[]
no_license
marshalltaylorSFE/ProtoPedalProjects
359d81d9d9b42405463121643080d446b9708ee0
493fa624750d9af78075f6ae0c219a9e2478ebbf
refs/heads/master
2020-12-04T22:04:04.270888
2016-09-03T03:19:29
2016-09-03T03:19:29
66,912,660
0
1
null
null
null
null
UTF-8
C++
false
false
1,549
h
//**********************************************************************// // // Interface example for the Bendvelope panel, 16 button/led bar w/ knob // and scanned matrix 7 segment display. // // This file defines the human interaction of the panel parts // // Written by: Marshall Taylor // Changelog (YYYY/MM/DD): // 2016/2/24: Created // 2016/2/29: Moved seven segment stuff to voltage monitor // //**********************************************************************// #ifndef P8INTERFACE_H #define P8INTERFACE_H #include "stdint.h" #include "timeKeeper.h" #include "P8PanelComponents.h" #include "P8Panel.h" #include "flagMessaging.h" enum PStates { PInit, PIdle, }; class P8Interface : public P8Panel { public: P8Interface( void ); void reset( void ); //State machine stuff void processMachine( void ); void tickStateMachine( void ); void timersMIncrement( uint8_t ); //Flags coming in from the system //Internal - and going out to the system - Flags // ..and data. //Template Parameters // Set initial values here uint8_t p8Param[15] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //Save 16 for idle // p8ParamSync used for knob resyincc uint8_t p8ParamSync = 0; // Choose how many params for the project uint8_t p8ParamActive[15] = {1,1,1,1,1,0,0,0,0,0,0,0,0,0,0}; uint8_t activeParam = 0; private: //Internal Flags //MessagingFlag quantizeHoldOffFlag; // ..and data P8PanelButton * buttonAccess[16]; P8PanelLed * ledAccess[16]; //State machine stuff PStates state; }; #endif
[ "marshall.taylor@sparkfun.com" ]
marshall.taylor@sparkfun.com
0ec2240e62150427a86a99472641e6a85e9f73a0
2ff43b5f55285bd9f0bc243ed81bfda1d75bdc27
/8.其他/机器人抓取/重构/NCC/squirrel_perception_backup-hydro_dev/v4r/v4r/TomGine/tgRenderModel.cpp
e7cf7bfa74ff68c438305310a2e66151c04b5c4b
[]
no_license
Ivan-VV/3D-ObjectDetection-and-Pose-Estimation
876d343aa5011228e15a43cb999586b09bfa313d
4fbe1c32fcd0618ab237eaa12931626c8d88c4ac
refs/heads/master
2022-02-20T03:27:58.829378
2019-06-17T06:51:48
2019-06-17T06:51:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,059
cpp
/* * Software License Agreement (GNU General Public License) * * Copyright (c) 2011, Thomas Mörwald * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @author thomas.moerwald * */ #include "tgRenderModel.h" #include "tgShapeCreator.h" #include "tgError.h" #include <GL/gl.h> using namespace TomGine; tgRenderModel::tgRenderModel() : m_displaylist_initialized(false), m_bufferobject_initialized(false) { m_material.Random(); } tgRenderModel::tgRenderModel(const tgRenderModel& model) : m_displaylist_initialized(false), m_bufferobject_initialized(false) { tgModel::operator=(model); m_pose = model.m_pose; m_material = model.m_material; } tgRenderModel::tgRenderModel(const tgModel& model) : tgModel(model), m_displaylist_initialized(false), m_bufferobject_initialized(false) { m_material.Random(); } tgRenderModel::~tgRenderModel() { destroy(); } void tgRenderModel::destroy() { if (m_displaylist_initialized) { if(glIsList(m_displaylist)) glDeleteLists(m_displaylist, 1); m_displaylist_initialized = false; } if (m_bufferobject_initialized) { if(glIsBuffer(m_vertexVBO)) glDeleteBuffers(1, &m_vertexVBO); if(glIsBuffer(m_triangleIBO)) glDeleteBuffers(1, &m_triangleIBO); if(glIsBuffer(m_quadIBO)) glDeleteBuffers(1, &m_quadIBO); m_bufferobject_initialized = false; } } void tgRenderModel::operator=(const tgModel& model) { tgModel::operator=(model); destroy(); } void tgRenderModel::GenDisplayList() { if (m_displaylist_initialized) { glDeleteLists(m_displaylist, 1); m_displaylist_initialized = false; } m_displaylist = glGenLists(1); glNewList(m_displaylist, GL_COMPILE_AND_EXECUTE); tgModel::DrawFaces(); glEndList(); m_displaylist_initialized = true; } void tgRenderModel::GenBufferObject(GLenum usage) { if (m_bufferobject_initialized) { if(glIsBuffer(m_vertexVBO)) glDeleteBuffers(1, &m_vertexVBO); if(glIsBuffer(m_triangleIBO)) glDeleteBuffers(1, &m_triangleIBO); if(glIsBuffer(m_quadIBO)) glDeleteBuffers(1, &m_quadIBO); m_bufferobject_initialized = false; } // collect data m_triangleIDX.clear(); m_quadIDX.clear(); for (unsigned i = 0; i < m_faces.size(); i++) { if (m_faces[i].v.size() == 3) { m_triangleIDX.push_back(m_faces[i].v[0]); m_triangleIDX.push_back(m_faces[i].v[1]); m_triangleIDX.push_back(m_faces[i].v[2]); } else if (m_faces[i].v.size() == 4) { m_quadIDX.push_back(m_faces[i].v[0]); m_quadIDX.push_back(m_faces[i].v[1]); m_quadIDX.push_back(m_faces[i].v[2]); m_quadIDX.push_back(m_faces[i].v[3]); } else { printf("[tgRenderModel::GenBufferObject] Warning, no suitable face format\n"); printf("[tgRenderModel::GenBufferObject] Face has %d vertices (supported: 3 or 4)\n", (int) m_faces[i].v.size()); return; } } // generate VBOs glGenBuffers(1, &m_vertexVBO); glBindBuffer(GL_ARRAY_BUFFER, m_vertexVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(tgVertex) * m_vertices.size(), &m_vertices[0].pos.x, usage); #ifdef DEBUG tgCheckError("[tgRenderModel::GenBufferObject] generate vertex buffer"); #endif glGenBuffers(1, &m_triangleIBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_triangleIBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned) * m_triangleIDX.size(), &m_triangleIDX[0], usage); #ifdef DEBUG tgCheckError("[tgRenderModel::GenBufferObject] generate triangle buffer"); #endif glGenBuffers(1, &m_quadIBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_quadIBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned) * m_quadIDX.size(), &m_quadIDX[0], usage); #ifdef DEBUG tgCheckError("[tgRenderModel::GenBufferObject] generate quad buffer"); #endif glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); m_bufferobject_initialized = true; } void tgRenderModel::UpdateBufferObjectVertices(GLenum usage) { glBindBuffer(GL_ARRAY_BUFFER, m_vertexVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(tgVertex) * m_vertices.size(), &m_vertices[0], usage); glBindBuffer(GL_ARRAY_BUFFER, 0); } void tgRenderModel::UpdateBufferObjectVertices(const std::vector<size_t>& vertex_indices) { glBindBuffer(GL_ARRAY_BUFFER, m_vertexVBO); tgCheckError("[tgRenderModel::UpdateBufferObjectVertices] A"); for(size_t i=0; i<vertex_indices.size(); i++) { const size_t& vi = vertex_indices[i]; if(vi<m_vertices.size()) { const tgVertex& v = m_vertices[vi]; glBufferSubData(GL_ARRAY_BUFFER, sizeof(tgVertex)*vi, sizeof(tgVertex), &v); if(tgCheckError("[tgRenderModel::UpdateBufferObjectVertices] B")!=GL_NO_ERROR) { GLint s; glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &s); printf("[tgRenderModel::UpdateBufferObjectVertices] %lu / %d\n", sizeof(tgVertex)*vi, s); return; } }else { printf("[tgRenderModel::UpdateBufferObjectVertices] Warning, vertex does not exists (index out of bounds)\n"); } } glBindBuffer(GL_ARRAY_BUFFER, 0); tgCheckError("[tgRenderModel::UpdateBufferObjectVertices] C"); } #define BUFFER_OFFSET(i) ((char *)NULL + (i)) void tgRenderModel::DrawBufferObject(bool normals, bool texture) { GLsizei vsize = sizeof(tgVertex); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_INDEX_ARRAY); if(normals) glEnableClientState(GL_NORMAL_ARRAY); if(texture) glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, m_vertexVBO); glVertexPointer(3, GL_FLOAT, vsize, BUFFER_OFFSET(0)); if(normals) glNormalPointer(GL_FLOAT, vsize, BUFFER_OFFSET(12)); if(texture) glTexCoordPointer(2, GL_FLOAT, vsize, BUFFER_OFFSET(24)); if(!m_triangleIDX.empty()) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_triangleIBO); glDrawElements(GL_TRIANGLES, m_triangleIDX.size(), GL_UNSIGNED_INT, BUFFER_OFFSET(0)); } if(!m_quadIDX.empty()) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_quadIBO); glDrawElements(GL_QUADS, m_quadIDX.size(), GL_UNSIGNED_INT, BUFFER_OFFSET(0)); } #ifdef DEBUG tgCheckError("[tgRenderModel::DrawBufferObject] drawing quads"); #endif glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_INDEX_ARRAY); if(normals) glDisableClientState(GL_NORMAL_ARRAY); if(texture) glDisableClientState(GL_TEXTURE_COORD_ARRAY); } void tgRenderModel::Draw() { this->DrawFaces(); m_pose.Activate(); this->DrawLines(); this->DrawPoints(); this->DrawColorPoints(); m_pose.Deactivate(); } void tgRenderModel::DrawFaces(bool lighting, RenderMode rmode) { if (lighting) { m_material.Activate(); } else { glDisable(GL_LIGHTING); glColor3f(m_material.color.x, m_material.color.y, m_material.color.z); } m_pose.Activate(); switch (rmode) { case DISPLAYLIST: if (m_displaylist_initialized) glCallList(m_displaylist); else GenDisplayList(); break; case BUFFEROBJECT: if (!m_bufferobject_initialized) GenBufferObject(); DrawBufferObject(); break; case RENDERNORMAL: default: tgModel::DrawFaces(); break; } m_pose.Deactivate(); if (lighting) { m_material.Deactivate(); } } void tgRenderModel::DrawNormals(float normal_length) { m_pose.Activate(); tgModel::DrawNormals(normal_length); m_pose.Deactivate(); }
[ "1253703632@qq.com" ]
1253703632@qq.com
cee7cda410817d2496d537a78f693fb921d2119a
982244b477a02fa3074b683ffc194ae52301e145
/lab1/matmul.cpp
f649555c42f708a018869d481da119b010869776
[]
no_license
crazymidnight/matrix-multiplication
bb99144bac389be610127fa353c58f1ab276307f
f282b8f15dfd4ad222ad6f77be79a6b39430eda0
refs/heads/master
2021-07-15T20:20:22.486542
2017-10-13T03:31:55
2017-10-13T03:31:55
106,764,658
0
0
null
null
null
null
UTF-8
C++
false
false
3,325
cpp
// matmul.cpp: определяет точку входа для консольного приложения. #include "stdafx.h" #include <iostream> #include <vector> #include <string> #include <Windows.h> #include <WinUser.h> // объявления типа матрицы typedef std::vector< std::vector<double> > matX; // функция перемножения матриц matX multiplyMatrix(int m, int n, int p, matX matA, matX matB) { matX matC(m, std::vector<double>(p)); for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { matC[i][j] = 0; for (int k = 0; k < n; k++) { matC[i][j] += matA[i][k] * matB[k][j]; } } } std::cout << "===" << matC[0][0] << std::endl; return matC; } // функция ввода матрицы matX inputMatrix(int m, int n) { double num; std::string in_num; bool successful; matX mat(m, std::vector<double>(n)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { successful = false; while (!successful) { std::cout << "Element " << i << ", " << j << std::endl; std::cin >> in_num; try { if (!isdigit(in_num[0]) && in_num[0] != '-' || !isdigit(in_num[1]) && in_num[0] == '-') { throw 1; } const char * c_str = in_num.c_str(); num = std::atof(c_str); mat[i][j] = num; successful = true; } catch (int i) { std::cout << "It's not a number! Try again!" << std::endl; continue; } } } } std::cout << "Your matrix" << std::endl; std::cout << mat[0][0]; return mat; } // функция ввода размерности матриц int inputDim() { int m; std::string in_num; bool successful; successful = false; while (!successful) { try { std::cin >> in_num; if (!isdigit(in_num[0])) { throw 1; } const char * c_str = in_num.c_str(); m = atoi(c_str); successful = true; } catch (int i) { if (i == 1) std::cout << "Type error! Enter integer number" << std::endl; continue; } } return m; } // функция вывода матрицы void showMat(int m, int n, matX mat) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) std::cout << mat[i][j] << " "; std::cout << std::endl; } } int main() { int m, n, p; matX matA; matX matB; matX matC; std::cout << "Enter dimensions of two matrices (m, n) and (n, p):" << "\n"; std::cout << "m = "; m = inputDim(); std::cout << "n = "; n = inputDim(); std::cout << "p = "; p = inputDim(); std::cout << "Ok!" << std::endl; std::cout << m << ", "<< n << ", " << p << std::endl; std::cout << "Enter first matrix" << std::endl; matA = inputMatrix(m, n); std::cout << "Enter second matrix" << std::endl; matB = inputMatrix(n, p); matC = multiplyMatrix(m, n, p, matA, matB); std::cout << "Matrix A:" << std::endl; showMat(m, n, matA); std::cout << "Matrix B:" << std::endl; showMat(n, p, matB); std::cout << "The result of multiplying:" << std::endl; showMat(m, p, matC); std::cout << "Press Space to exit!"; while (1) { if (GetAsyncKeyState(VK_SPACE)) { break; //User pressed space } } return 0; }
[ "alexvoit70@gmail.com" ]
alexvoit70@gmail.com
90db53d7db270b261826dcac09acf656ccfe94d1
f6fb79c6ae4f9076f0f01647ff69c8e3da05f6c9
/source-code/Classes/Stats/simple_stats.h
12691c3636b2c7608b198a307401cd4351aa2f63
[ "CC-BY-4.0" ]
permissive
gjbex/Scientific-C-plus-plus
421f7170a3ea67c3465fc247df6f01416848f752
438a4422d147b9069fda416cc51a660f5003f496
refs/heads/master
2023-08-21T16:52:03.863968
2023-03-30T12:45:04
2023-03-30T12:45:04
241,086,567
19
11
CC-BY-4.0
2023-08-03T08:17:16
2020-02-17T11:03:12
C++
UTF-8
C++
false
false
521
h
#ifndef SIMPLE_STATS_HDR #define SIMPLE_STATS_HDR #include <iostream> class SimpleStats { private: double sum_; int n_; public: SimpleStats() : sum_ {0.0}, n_ {0} {}; void add(double x) { sum_ += x; n_++; }; double sum() const { return sum_; }; int n() const { return n_; }; double mean() const { return sum()/n(); }; friend std::ostream& operator<<(std::ostream& out, const SimpleStats& stats); }; #endif
[ "geertjan.bex@uhasselt.be" ]
geertjan.bex@uhasselt.be
e0b405d1dea102bcde2d8a415eb1f96cbb185e49
92d997e19d3d85d69f8c432a12367671960c8c6e
/C . C++/Programas/tercer parametro del main.cpp
ba4c2a67b0297b6d5214b013845d1d1180c197a9
[]
no_license
0aps/Legacy-Code
3aebc22d0d513e95ccf1b9149a80675cc02c04df
be8f336d6d0d3c63d2961c25e4584f9d08404b37
refs/heads/master
2021-01-10T21:38:58.395925
2014-09-24T20:36:16
2014-09-24T20:36:16
24,429,977
11
2
null
null
null
null
ISO-8859-3
C++
false
false
568
cpp
#include <stdio.h> #include <string.h> //env puntero a arrey de caracteres que almacena las variables de entorno int main ( int argc, char *argv[], char *env[] ) { char * solicitud = argv [1]; int n; if ( argc == 1 ) { printf ( "Con argumento pls:\n\n\t%s VARIABLE\n\nżOk?\n", argv [0] ); return -1; } for ( n = 0 ; env [n] != NULL; n++ ) { //busco en las variables de entorno cualquier variable que empieze o que contega // lo escrito en solicitud if ( strstr ( env[n], solicitud ) ) printf ( "%s\n", env[n] ); } return 0; }
[ "six.aps@gmail.com" ]
six.aps@gmail.com
2166fa52fa9807a9788afa81b91b207668c13d14
460455e7990de7257aa223a58e73069f3ef7ff43
/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_herod.cpp
81bf21cf4bdd76b34a8c7b58a5228e39346edade
[]
no_license
Shkipper/wmane
2ce69adea1eedf866921c857cbc5bd1bc6d037f0
2da37e1e758f17b61efb6aae8fa7343b234f3dcd
refs/heads/master
2020-04-24T19:51:51.897587
2019-02-25T06:14:18
2019-02-25T06:14:18
172,225,859
0
0
null
2019-02-23T14:49:31
2019-02-23T14:49:31
null
UTF-8
C++
false
false
4,689
cpp
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * 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 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Herod SD%Complete: 95 SDComment: Should in addition spawn Myrmidons in the hallway outside SDCategory: Scarlet Monastery EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedEscortAI.h" enum Says { SAY_AGGRO = -1189000, SAY_WHIRLWIND = -1189001, SAY_ENRAGE = -1189002, SAY_KILL = -1189003 }; enum Emotes { EMOTE_ENRAGE = -1189004 }; enum Spells { SPELL_RUSHINGCHARGE = 8260, SPELL_CLEAVE = 15496, SPELL_WHIRLWIND = 8989, SPELL_FRENZY = 8269 }; enum Entry { ENTRY_SCARLET_TRAINEE = 6575, ENTRY_SCARLET_MYRMIDON = 4295 }; class boss_herod : public CreatureScript { public: boss_herod() : CreatureScript("boss_herod") { } CreatureAI* GetAI(Creature* creature) const { return new boss_herodAI(creature); } struct boss_herodAI : public ScriptedAI { boss_herodAI(Creature* creature) : ScriptedAI(creature) {} bool Enrage; uint32 Cleave_Timer; uint32 Whirlwind_Timer; void Reset() { Enrage = false; Cleave_Timer = 12000; Whirlwind_Timer = 60000; } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); DoCast(me, SPELL_RUSHINGCHARGE); } void KilledUnit(Unit* /*victim*/) { DoScriptText(SAY_KILL, me); } void JustDied(Unit* /*killer*/) { for (uint8 i = 0; i < 20; ++i) me->SummonCreature(ENTRY_SCARLET_TRAINEE, 1939.18f, -431.58f, 17.09f, 6.22f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; //If we are <30% hp goes Enraged if (!Enrage && !HealthAbovePct(30) && !me->IsNonMeleeSpellCasted(false)) { DoScriptText(EMOTE_ENRAGE, me); DoScriptText(SAY_ENRAGE, me); DoCast(me, SPELL_FRENZY); Enrage = true; } //Cleave_Timer if (Cleave_Timer <= diff) { DoCast(me->GetVictim(), SPELL_CLEAVE); Cleave_Timer = 12000; } else Cleave_Timer -= diff; // Whirlwind_Timer if (Whirlwind_Timer <= diff) { DoScriptText(SAY_WHIRLWIND, me); DoCast(me->GetVictim(), SPELL_WHIRLWIND); Whirlwind_Timer = 30000; } else Whirlwind_Timer -= diff; DoMeleeAttackIfReady(); } }; }; class mob_scarlet_trainee : public CreatureScript { public: mob_scarlet_trainee() : CreatureScript("mob_scarlet_trainee") { } CreatureAI* GetAI(Creature* creature) const { return new mob_scarlet_traineeAI(creature); } struct mob_scarlet_traineeAI : public npc_escortAI { mob_scarlet_traineeAI(Creature* creature) : npc_escortAI(creature) { Start_Timer = urand(1000, 6000); } uint32 Start_Timer; void Reset() {} void WaypointReached(uint32 /*waypointId*/) { } void EnterCombat(Unit* /*who*/) {} void UpdateAI(const uint32 diff) { if (Start_Timer) { if (Start_Timer <= diff) { Start(true, true); Start_Timer = 0; } else Start_Timer -= diff; } npc_escortAI::UpdateAI(diff); } }; }; void AddSC_boss_herod() { new boss_herod(); new mob_scarlet_trainee(); }
[ "felianther15@gmail.com" ]
felianther15@gmail.com
d7c64445cab27f4d91db2d35031897fdb7897757
c6f400289a1ea9f58adf0b92f13e8489acd3f5d7
/tensorflow_lite_support/cc/task/audio/audio_classifier.h
f82826b823d048b4414e0c22e609e00299a15d68
[ "Apache-2.0" ]
permissive
milindthakur177/tflite-support
90b2f0ab081e1cc65e3a5baf9232ff45f0d87294
f0a5b449b315730cac8c6550a87bb82e81e455af
refs/heads/master
2023-07-17T16:16:26.157733
2021-09-04T06:14:54
2021-09-04T06:14:54
382,568,129
0
0
Apache-2.0
2021-07-03T08:46:35
2021-07-03T08:46:34
null
UTF-8
C++
false
false
6,648
h
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LITE_SUPPORT_CC_TASK_AUDIO_AUDIO_CLASSIFIER_H_ #define TENSORFLOW_LITE_SUPPORT_CC_TASK_AUDIO_AUDIO_CLASSIFIER_H_ #include <memory> #include "absl/status/status.h" #include "tensorflow/lite/core/api/op_resolver.h" #include "tensorflow/lite/core/shims/cc/kernels/register.h" #include "tensorflow_lite_support/cc/port/statusor.h" #include "tensorflow_lite_support/cc/task/audio/core/audio_buffer.h" #include "tensorflow_lite_support/cc/task/audio/proto/audio_classifier_options.pb.h" #include "tensorflow_lite_support/cc/task/audio/proto/classifications_proto_inc.h" #include "tensorflow_lite_support/cc/task/core/base_task_api.h" #include "tensorflow_lite_support/cc/task/core/classification_head.h" namespace tflite { namespace task { namespace audio { // Performs classification on audio clips. // // The API expects a TFLite model with optional, but strongly recommended, // TFLite Model Metadata. // // Input tensor: // (kTfLiteFloat32) // - input audio buffer of size `[batch * samples]`. // - batch inference is not supported (`batch` is required to be 1). // - for multi-channel models, the channels need be interleaved. // At least one output tensor with: // (kTfLiteFloat32) // - `[1 x N]` array with `N` represents the class number. // - optional (but recommended) label map(s) as AssociatedFile-s with type // TENSOR_AXIS_LABELS, containing one label per line. The first such // AssociatedFile (if any) is used to fill the `class_name` field of the // results. The `display_name` field is filled from the AssociatedFile (if // any) whose locale matches the `display_names_locale` field of the // `ImageClassifierOptions` used at creation time ("en" by default, i.e. // English). If none of these are available, only the `index` field of the // results will be filled. // // TODO(b/182535933): Add a model example and demo comments here. class AudioClassifier : public tflite::task::core::BaseTaskApi<ClassificationResult, const AudioBuffer&> { public: using BaseTaskApi::BaseTaskApi; // Creates an AudioClassifier from the provided options. A non-default // OpResolver can be specified in order to support custom Ops or specify a // subset of built-in Ops. static tflite::support::StatusOr<std::unique_ptr<AudioClassifier>> CreateFromOptions( const AudioClassifierOptions& options, std::unique_ptr<tflite::OpResolver> resolver = absl::make_unique<tflite_shims::ops::builtin::BuiltinOpResolver>()); // Performs classification on the provided audio buffer. // // The input `audio_buffer` are the raw buffer captured by the required format // which can retrieved by GetRequiredAudioFormat(). tflite::support::StatusOr<ClassificationResult> Classify( const AudioBuffer& audio_buffer); // Returns the required input audio format if it is set. Otherwise, returns // kMetadataNotFoundError. // TODO(b/182625132): Add unit test after the format is populated from model // metadata. tflite::support::StatusOr<AudioBuffer::AudioFormat> GetRequiredAudioFormat(); // Returns the required input buffer size in number of float elements. int GetRequiredInputBufferSize() { return input_buffer_size_; } private: // Performs sanity checks on the provided AudioClassifierOptions. static absl::Status SanityCheckOptions(const AudioClassifierOptions& options); // Initializes the AudioClassifier from the provided AudioClassifierOptions, // whose ownership is transferred to this object. absl::Status Init(std::unique_ptr<AudioClassifierOptions> options); // Sets up input audio format from the model metadata; absl::Status SetAudioFormatFromMetadata(); // Performs sanity checks on the model input dimension and sets the input // buffer size accordingly. absl::Status CheckAndSetInputs(); // Performs sanity checks on the model outputs and extracts their metadata. absl::Status CheckAndSetOutputs(); // Passes through the input audio buffer into model's input tensor. absl::Status Preprocess(const std::vector<TfLiteTensor*>& input_tensors, const AudioBuffer& audio_buffer) override; // Post-processing to transform the raw model outputs into classification // results. tflite::support::StatusOr<ClassificationResult> Postprocess( const std::vector<const TfLiteTensor*>& output_tensors, const AudioBuffer& audio_buffer) override; // Given a ClassificationResult object containing class indices, fills the // name and display name from the label map(s). absl::Status FillResultsFromLabelMaps(ClassificationResult* result); // The options used to build this AudioClassifier. std::unique_ptr<AudioClassifierOptions> options_; // The list of classification heads associated with the corresponding output // tensors. Built from TFLite Model Metadata. std::vector<tflite::task::core::ClassificationHead> classification_heads_; // The number of output tensors. This corresponds to the number of // classification heads. int num_outputs_; // Whether the model features quantized inference type (QUANTIZED_UINT8). This // is currently detected by checking if all output tensors data type is uint8. bool has_uint8_outputs_; // Set of allowlisted or denylisted class names. struct ClassNameSet { absl::flat_hash_set<std::string> values; bool is_allowlist; }; // Allowlisted or denylisted class names based on provided options at // construction time. These are used to filter out results during // post-processing. ClassNameSet class_name_set_; // Expected input audio format by the model. AudioBuffer::AudioFormat audio_format_; // Expected input audio buffer size in number of float elements. int input_buffer_size_; }; } // namespace audio } // namespace task } // namespace tflite #endif // TENSORFLOW_LITE_SUPPORT_CC_TASK_AUDIO_AUDIO_CLASSIFIER_H_
[ "tflite-support-github-robot@google.com" ]
tflite-support-github-robot@google.com
6c02a1fec2c282989f174c9a9a61a3cd14c381ba
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14628/function14628_schedule_8/function14628_schedule_8.cpp
ae19de0d70a57bc712643e432ef00be20e20794c
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
685
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14628_schedule_8"); constant c0("c0", 128), c1("c1", 512), c2("c2", 1024); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04"); computation comp0("comp0", {i0, i1, i2}, 7 * 9 + 3); comp0.tile(i0, i1, 64, 64, i01, i02, i03, i04); comp0.parallelize(i01); buffer buf0("buf0", {128, 512, 1024}, p_int32, a_output); comp0.store_in(&buf0); tiramisu::codegen({&buf0}, "../data/programs/function14628/function14628_schedule_8/function14628_schedule_8.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
eb140b454adbc3e8cd92c9bf83d04ea507533ae0
38c29c3c4c97e4831b2882d02f245161ccdd63e7
/VoxelEngine_V2/engine/utilities/Util.cpp
c5eb921076f5985c4952c25fd128b36ba7e51ae3
[]
no_license
incetents/VoxelEngine_V2
fc7f9ac7f0977fa9467b0d0516dd8eddb661bb33
91d5c2e96a297ac8144a8a2c78216943cfed60dc
refs/heads/master
2020-04-06T08:57:28.877501
2020-01-26T05:05:57
2020-01-26T05:05:57
157,323,605
3
0
null
null
null
null
UTF-8
C++
false
false
1,423
cpp
// Copyright (c) 2020 Emmanuel Lajeunesse #include "Precompiled.h" #include "Util.h" #include "../math/Vector.h" #include "../math/Color.h" namespace Vxl { namespace Util { namespace Conversion { void uint_to_uchars(uint32_t input, unsigned char& output1, unsigned char& output2, unsigned char& output3, unsigned char& output4) { output1 = (input) & 0xFF; output2 = (input >> 8) & 0xFF; output3 = (input >> 16) & 0xFF; output4 = (input >> 24) & 0xFF; } uint32_t uchars_to_uint(unsigned char* inputs) { uint32_t output; output = output << 8 | static_cast<unsigned char>(inputs[3]); output = output << 8 | static_cast<unsigned char>(inputs[2]); output = output << 8 | static_cast<unsigned char>(inputs[1]); output = output << 8 | static_cast<unsigned char>(inputs[0]); return output; } Vector4 uint_to_vec4(uint32_t input) { unsigned char cx, cy, cz, cw; uint_to_uchars(input, cx, cy, cz, cw); return Vector4( (float)cx / 255.0f, (float)cy / 255.0f, (float)cz / 255.0f, (float)cw / 255.0f ); } Color4F uint_to_color4(uint32_t input) { unsigned char cx, cy, cz, cw; uint_to_uchars(input, cx, cy, cz, cw); return Color4F( (float)cx / 255.0f, (float)cy / 255.0f, (float)cz / 255.0f, (float)cw / 255.0f ); } } } }
[ "incetents99@gmail.com" ]
incetents99@gmail.com
a34eb0146ba3904f7527a6e64ef2d5a8a78ed871
ebba8dfe112e93bad2be3551629d632ee4681de9
/apps/examples/movieGrabberExample/src/testApp.cpp
2296dc2a90f5473536d5263fb93c2a9230739232
[]
no_license
lucasdupin/28blobs
8499a4c249b5ac4c7731313e0d418dc051610de4
5a6dd8a9b084468a38f5045a2367a1dbf6d21609
refs/heads/master
2016-08-03T12:27:08.348430
2009-06-20T04:39:03
2009-06-20T04:39:03
219,034
2
0
null
null
null
null
UTF-8
C++
false
false
2,199
cpp
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ camWidth = 320; // try to grab at this size. camHeight = 240; vidGrabber.setVerbose(true); vidGrabber.initGrabber(camWidth,camHeight); videoInverted = new unsigned char[camWidth*camHeight*3]; videoTexture.allocate(camWidth,camHeight, GL_RGB); } //-------------------------------------------------------------- void testApp::update(){ ofBackground(100,100,100); vidGrabber.grabFrame(); if (vidGrabber.isFrameNew()){ int totalPixels = camWidth*camHeight*3; unsigned char * pixels = vidGrabber.getPixels(); for (int i = 0; i < totalPixels; i++){ videoInverted[i] = 255 - pixels[i]; } videoTexture.loadData(videoInverted, camWidth,camHeight, GL_RGB); } } //-------------------------------------------------------------- void testApp::draw(){ ofSetColor(0xffffff); vidGrabber.draw(20,20); videoTexture.draw(20+camWidth,20,camWidth,camHeight); } //-------------------------------------------------------------- void testApp::keyPressed (int key){ // in fullscreen mode, on a pc at least, the // first time video settings the come up // they come up *under* the fullscreen window // use alt-tab to navigate to the settings // window. we are working on a fix for this... if (key == 's' || key == 'S'){ vidGrabber.videoSettings(); } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ }
[ "lucas@sala28.it" ]
lucas@sala28.it
2f1177e403095dcde000cafc24cb6d836301c644
6296b56408a52273d4ae437473ea8d3eb9387755
/DesignPatterns/src/Facade.cpp
3d25c90663df33881d0f8e88b6e62ba817b55637
[]
no_license
yngaocn/DesignPatterns
bbd301601d57cc18919e866aef2c267987909a29
e6ffc1e6f7f537d4fdbe8349333669fed7987788
refs/heads/master
2020-12-24T13:28:16.559313
2015-03-07T18:21:23
2015-03-07T18:21:23
29,065,227
0
0
null
null
null
null
UTF-8
C++
false
false
513
cpp
#include "Facade.h" #include <iostream> namespace Facade { void SubSystem::Function1() { std::cout<<"SubSystem::Function1"<<std::endl; } void SubSystem::Function2() { std::cout<<"SubSystem::Function2"<<std::endl; } void Facade::Function() { subsystem.Function1(); subsystem.Function2(); } void TestFacade() { std::cout<<"----------Test Facade----------"<<std::endl; Facade facade; facade.Function(); } }
[ "yngaocn@gmail.com" ]
yngaocn@gmail.com
eddb8d905f5b470be04b6bc8ebf3f7c2b5cbb0fc
8601aa04eedda23a5a42cde56ac4ebea843fac0d
/src/web/mdns-publisher/mdns_publisher.hpp
7128510f2be61dd436bfda0c8172667399252eb5
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
ptone/borderrouter
c79fd90cfe2e02938035f2ae005e58d244a51215
68acf651f4c57f62a861f5ae9288150c41f9a4d2
refs/heads/master
2021-01-25T04:35:58.698763
2017-06-05T05:21:36
2017-06-05T05:21:36
93,453,911
0
0
null
2017-06-05T22:50:01
2017-06-05T22:50:01
null
UTF-8
C++
false
false
3,458
hpp
/* * Copyright (c) 2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements starting mDNS server, and publish border router service. */ #ifndef MDNS_SERVER_HPP #define MDNS_SERVER_HPP #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <syslog.h> #include <time.h> #include <avahi-core/core.h> #include <avahi-core/publish.h> #include <avahi-common/simple-watch.h> #include <avahi-common/malloc.h> #include <avahi-common/alternative.h> #include <avahi-common/error.h> namespace ot { namespace Mdns { class Publisher { public: static int StartServer(void); static void SetServiceName(const char *aServiceName); static void SetNetworkNameTxT(const char *aTxtData); static void SetEPANIDTxT(const char *aTxtData); static void SetType(const char *aType); static void SetPort(uint16_t aPort); static int UpdateService(void); static bool IsServerStart(void) { return isStart; }; private: static int CreateService(AvahiServer *aServer); static void EntryGroupCallback(AvahiServer *aServer, AvahiSEntryGroup *aGroup, AvahiEntryGroupState aState, AVAHI_GCC_UNUSED void *aUserData); static void ServerCallback(AvahiServer *aServer, AvahiServerState aState, AVAHI_GCC_UNUSED void *aUserData); static void PeriodicallyPublish(AVAHI_GCC_UNUSED AvahiTimeout *aTimeout, void *aUserData); static void Free(void); static AvahiSEntryGroup *mGroup; static AvahiSimplePoll *mSimplePoll; static AvahiServer *mServer; static const char *mNetworkNameTxt; static const char *mExtPanIdTxt; static const char *mType; static uint16_t mPort; static char *mServiceName; static bool isStart; }; } //namespace Mdns } //namespace ot #endif //MDNS_SERVER_HPP
[ "jonhui@nestlabs.com" ]
jonhui@nestlabs.com
2979798cd34c46aafd10472478751e056a9072d4
db9eb5465783107dfcdb866c1a8e9f0f646326c0
/src/opcode/Ice/IceUtils.h
ce1762aa63e39423e573b6a95214a02e5c47ef61
[]
no_license
stevesjtu/tricycle
961bd4f440b7aad7529cfd2afbeef39788c548c4
fb06c74cccc2bdf563efa353024b46ca135a33b0
refs/heads/master
2023-07-20T08:41:26.067975
2018-08-23T15:14:07
2018-08-23T15:14:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,546
h
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains misc. useful macros & defines. * \file IceUtils.h * \author Pierre Terdiman (collected from various sources) * \date April, 4, 2000 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Include Guard #ifndef __ICEUTILS_H__ #define __ICEUTILS_H__ // #define START_RUNONCE { static bool __RunOnce__ = false; if(!__RunOnce__){ -- not thread safe // #define END_RUNONCE __RunOnce__ = true;}} -- not thread safe //! Reverse all the bits in a 32 bit word (from Steve Baker's Cute Code Collection) //! (each line can be done in any order. // inline_ void ReverseBits(udword& n) // { // n = ((n >> 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa); // n = ((n >> 2) & 0x33333333) | ((n << 2) & 0xcccccccc); // n = ((n >> 4) & 0x0f0f0f0f) | ((n << 4) & 0xf0f0f0f0); // n = ((n >> 8) & 0x00ff00ff) | ((n << 8) & 0xff00ff00); // n = ((n >> 16) & 0x0000ffff) | ((n << 16) & 0xffff0000); // // Etc for larger intergers (64 bits in Java) // // NOTE: the >> operation must be unsigned! (>>> in java) // } // // //! Count the number of '1' bits in a 32 bit word (from Steve Baker's Cute Code Collection) // inline_ udword CountBits(udword n) // { // // This relies of the fact that the count of n bits can NOT overflow // // an n bit interger. EG: 1 bit count takes a 1 bit interger, 2 bit counts // // 2 bit interger, 3 bit count requires only a 2 bit interger. // // So we add all bit pairs, then each nible, then each byte etc... // n = (n & 0x55555555) + ((n & 0xaaaaaaaa) >> 1); // n = (n & 0x33333333) + ((n & 0xcccccccc) >> 2); // n = (n & 0x0f0f0f0f) + ((n & 0xf0f0f0f0) >> 4); // n = (n & 0x00ff00ff) + ((n & 0xff00ff00) >> 8); // n = (n & 0x0000ffff) + ((n & 0xffff0000) >> 16); // // Etc for larger intergers (64 bits in Java) // // NOTE: the >> operation must be unsigned! (>>> in java) // return n; // } // // //! Even faster? // inline_ udword CountBits2(udword bits) // { // bits = bits - ((bits >> 1) & 0x55555555); // bits = ((bits >> 2) & 0x33333333) + (bits & 0x33333333); // bits = ((bits >> 4) + bits) & 0x0F0F0F0F; // return (bits * 0x01010101) >> 24; // } // // //! Spread out bits. EG 00001111 -> 0101010101 // //! 00001010 -> 0100010000 // //! This is used to interleve to intergers to produce a `Morten Key' // //! used in Space Filling Curves (See DrDobbs Journal, July 1999) // //! Order is important. // inline_ void SpreadBits(udword& n) // { // n = ( n & 0x0000ffff) | (( n & 0xffff0000) << 16); // n = ( n & 0x000000ff) | (( n & 0x0000ff00) << 8); // n = ( n & 0x000f000f) | (( n & 0x00f000f0) << 4); // n = ( n & 0x03030303) | (( n & 0x0c0c0c0c) << 2); // n = ( n & 0x11111111) | (( n & 0x22222222) << 1); // } // // // Next Largest Power of 2 // // Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm // // that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with // // the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next // // largest power of 2. For a 32-bit value: // inline_ udword nlpo2(udword x) // { // x |= (x >> 1); // x |= (x >> 2); // x |= (x >> 4); // x |= (x >> 8); // x |= (x >> 16); // return x+1; // } // // //! Test to see if a number is an exact power of two (from Steve Baker's Cute Code Collection) // inline_ bool IsPowerOfTwo(udword n) { return ((n&(n-1))==0); } // // //! Zero the least significant '1' bit in a word. (from Steve Baker's Cute Code Collection) // inline_ void ZeroLeastSetBit(udword& n) { n&=(n-1); } // // //! Set the least significant N bits in a word. (from Steve Baker's Cute Code Collection) // inline_ void SetLeastNBits(udword& x, udword n) { x|=~(~0<<n); } // // //! Classic XOR swap (from Steve Baker's Cute Code Collection) // //! x ^= y; /* x' = (x^y) */ // //! y ^= x; /* y' = (y^(x^y)) = x */ // //! x ^= y; /* x' = (x^y)^x = y */ inline_ void Swap(udword& x, udword& y) { x ^= y; y ^= x; x ^= y; } inline_ void Swap(uword& x, uword& y) { x ^= y; y ^= x; x ^= y; } // // //! Little/Big endian (from Steve Baker's Cute Code Collection) // //! // //! Extra comments by Kenny Hoff: // //! Determines the byte-ordering of the current machine (little or big endian) // //! by setting an integer value to 1 (so least significant bit is now 1); take // //! the address of the int and cast to a byte pointer (treat integer as an // //! array of four bytes); check the value of the first byte (must be 0 or 1). // //! If the value is 1, then the first byte least significant byte and this // //! implies LITTLE endian. If the value is 0, the first byte is the most // //! significant byte, BIG endian. Examples: // //! integer 1 on BIG endian: 00000000 00000000 00000000 00000001 // //! integer 1 on LITTLE endian: 00000001 00000000 00000000 00000000 // //!--------------------------------------------------------------------------- // //! int IsLittleEndian() { int x=1; return ( ((char*)(&x))[0] ); } // inline_ char LittleEndian() { int i = 1; return *((char*)&i); } // // //!< Alternative abs function // inline_ udword abs_(sdword x) { sdword y= x >> 31; return (x^y)-y; } // // //!< Alternative min function // inline_ sdword min_(sdword a, sdword b) { sdword delta = b-a; return a + (delta&(delta>>31)); } // // // Determine if one of the bytes in a 4 byte word is zero // inline_ BOOL HasNullByte(udword x) { return ((x + 0xfefefeff) & (~x) & 0x80808080); } // // // To find the smallest 1 bit in a word EG: ~~~~~~10---0 => 0----010---0 // inline_ udword LowestOneBit(udword w) { return ((w) & (~(w)+1)); } //// inline_ udword LowestOneBit_(udword w) { return ((w) & (-(w))); } // // // Most Significant 1 Bit // // Given a binary integer value x, the most significant 1 bit (highest numbered element of a bit set) // // can be computed using a SWAR algorithm that recursively "folds" the upper bits into the lower bits. // // This process yields a bit vector with the same most significant 1 as x, but all 1's below it. // // Bitwise AND of the original value with the complement of the "folded" value shifted down by one // // yields the most significant bit. For a 32-bit value: // inline_ udword msb32(udword x) // { // x |= (x >> 1); // x |= (x >> 2); // x |= (x >> 4); // x |= (x >> 8); // x |= (x >> 16); // return (x & ~(x >> 1)); // } // // /* // "Just call it repeatedly with various input values and always with the same variable as "memory". // The sharpness determines the degree of filtering, where 0 completely filters out the input, and 1 // does no filtering at all. // // I seem to recall from college that this is called an IIR (Infinite Impulse Response) filter. As opposed // to the more typical FIR (Finite Impulse Response). // // Also, I'd say that you can make more intelligent and interesting filters than this, for example filters // that remove wrong responses from the mouse because it's being moved too fast. You'd want such a filter // to be applied before this one, of course." // // (JCAB on Flipcode) // */ // inline_ float FeedbackFilter(float val, float& memory, float sharpness) // { // ASSERT(sharpness>=0.0f && sharpness<=1.0f && "Invalid sharpness value in feedback filter"); // if(sharpness<0.0f) sharpness = 0.0f; // else if(sharpness>1.0f) sharpness = 1.0f; // return memory = val * sharpness + memory * (1.0f - sharpness); // } // // //! If you can guarantee that your input domain (i.e. value of x) is slightly // //! limited (abs(x) must be < ((1<<31u)-32767)), then you can use the // //! following code to clamp the resulting value into [-32768,+32767] range: // inline_ int ClampToInt16(int x) // { //// ASSERT(abs(x) < (int)((1<<31u)-32767)); // // int delta = 32767 - x; // x += (delta>>31) & delta; // delta = x + 32768; // x -= (delta>>31) & delta; // return x; // } // // // Generic functions template<class Type> inline_ void TSwap(Type& a, Type& b) { const Type c = a; a = b; b = c; } // template<class Type> inline_ Type TClamp(const Type& x, const Type& lo, const Type& hi) { return ((x<lo) ? lo : (x>hi) ? hi : x); } // // template<class Type> inline_ void TSort(Type& a, Type& b) // { // if(a>b) TSwap(a, b); // } // // template<class Type> inline_ void TSort(Type& a, Type& b, Type& c) // { // if(a>b) TSwap(a, b); // if(b>c) TSwap(b, c); // if(a>b) TSwap(a, b); // if(b>c) TSwap(b, c); // } // // // Prevent nasty user-manipulations (strategy borrowed from Charles Bloom) //// #define PREVENT_COPY(curclass) void operator = (const curclass& object) { ASSERT(!"Bad use of operator ="); } // // ... actually this is better ! // #define PREVENT_COPY(cur_class) private: cur_class(const cur_class& object); cur_class& operator=(const cur_class& object); // // //! TO BE DOCUMENTED // #define OFFSET_OF(Class, Member) (size_t)&(((Class*)0)->Member) // //! TO BE DOCUMENTED //#ifndef ARRAYSIZE // #define ARRAYSIZE(p) (sizeof(p)/sizeof((p)[0])) //#endif // #ifndef ARRAYSIZE // // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // /** // * Returns the alignment of the input address. // * \fn Alignment() // * \param address [in] address to check // * \return the best alignment (e.g. 1 for odd addresses, etc) // */ // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // FUNCTION ICECORE_API udword Alignment(udword address); // // #define IS_ALIGNED_2(x) ((x&1)==0) // #define IS_ALIGNED_4(x) ((x&3)==0) // #define IS_ALIGNED_8(x) ((x&7)==0) // // inline_ void _prefetch(void const* ptr) { (void)*(char const volatile *)ptr; } // // // Compute implicit coords from an index: // // The idea is to get back 2D coords from a 1D index. // // For example: // // // // 0 1 2 ... nbu-1 // // nbu nbu+1 i ... // // // // We have i, we're looking for the equivalent (u=2, v=1) location. // // i = u + v*nbu // // <=> i/nbu = u/nbu + v // // Since 0 <= u < nbu, u/nbu = 0 (integer) // // Hence: v = i/nbu // // Then we simply put it back in the original equation to compute u = i - v*nbu // inline_ void Compute2DCoords(udword& u, udword& v, udword i, udword nbu) // { // v = i / nbu; // u = i - (v * nbu); // } // // // In 3D: i = u + v*nbu + w*nbu*nbv // // <=> i/(nbu*nbv) = u/(nbu*nbv) + v/nbv + w // // u/(nbu*nbv) is null since u/nbu was null already. // // v/nbv is null as well for the same reason. // // Hence w = i/(nbu*nbv) // // Then we're left with a 2D problem: i' = i - w*nbu*nbv = u + v*nbu // inline_ void Compute3DCoords(udword& u, udword& v, udword& w, udword i, udword nbu, udword nbu_nbv) // { // w = i / (nbu_nbv); // Compute2DCoords(u, v, i - (w * nbu_nbv), nbu); // } #endif // __ICEUTILS_H__
[ "jiabeishi@gmail.com" ]
jiabeishi@gmail.com
42f2bda871388de0557ad891ccc559daadd41f12
429e991f5428414cb2683bf7f8a55409a4efaee7
/ToySoldier_IOCPServer/circular_buffer.h
989561e7811ba37c08bc07051b2d994a0e4101ed
[]
no_license
yjpark9201/ToySoldier_Server
6fa9dfdb83cce1adcf7b318b5ee78b423a2cabb2
2110560424e40c09e3859f4836e01502e2660e6c
refs/heads/master
2020-12-04T03:59:01.727966
2020-10-06T13:28:35
2020-10-06T13:28:35
231,599,996
0
0
null
null
null
null
UHC
C++
false
false
3,648
h
#pragma once ; #include <iostream> template <class T> class Circular_buffer { public: explicit Circular_buffer(size_t size) : begin((new T[size])), End(size) { } explicit Circular_buffer(char* buffer, size_t size) : begin(buffer), End(size) { } ~Circular_buffer(); void put(T item); T* GetBegin() { return begin; } T get(); void reset(); bool empty() const; bool full() const; size_t capacity() const; size_t remain() const; T* GetRecordablePoint() const; // Socket이 Recv 가능한 지점 size_t GetRecordableSize() const; // Socket이 한번에 Recv가능한 범위까지의 길이 void update_head(size_t recored); void update_tail(size_t recored); size_t FromTailToEnd() { return End - tail_; } void Copy(T* buf, int len); T* Ref(T* buf, int len); //size_t GetRecordable(int& len) // len만큼의 길이를 private: //std::mutex mutex_; T* begin; size_t head_ = 0; size_t tail_ = 0; const size_t End; //end bool full_ = 0; // unsigned char *m_load_ptr, *m_consume_ptr; // unsigned char *m_buff_end; //unsigned char *m_buff; // int m_max_load, m_max_consume, m_data_in_buffer; }; template <class T> Circular_buffer<T>::~Circular_buffer() { std::cout << "링버퍼 소멸 - 메모리 주소" << begin <<std::endl; delete begin; } template <class T> void Circular_buffer<T>::reset() { // std::lock_guard<std::mutex> lock(mutex_); head_ = tail_; full_ = false; } template <class T> bool Circular_buffer<T>::empty() const { //if head and tail are equal, we are empty return (!full_ && (head_ == tail_)); } template <class T> bool Circular_buffer<T>::full() const { //If tail is ahead the head by 1, we are full return full_; } template <class T> size_t Circular_buffer<T> ::capacity() const { return End; } template <class T> size_t Circular_buffer<T> ::remain() const { size_t size = End; if (!full_) { if (head_ >= tail_) { size = head_ - tail_; } else { size = End + head_ - tail_; } } return size; } template <class T> T* Circular_buffer<T> ::GetRecordablePoint() const { return begin + head_; } template <class T> size_t Circular_buffer<T> ::GetRecordableSize() const { if (head_ >= tail_) return End - head_; else return tail_ - head_; } template <class T> void Circular_buffer<T> ::Copy(T* buf, int len) { if ((head_ >= tail_) || (End - tail_ >= len)) { MoveMemory(buf, begin + tail_, len); tail_ = tail_ + len; } else { MoveMemory(buf, begin + tail_, End - tail_); MoveMemory(buf + End - tail_, begin, len - End + tail_); tail_ = len - End + tail_;// ( tail_ + len )% End; 와 같음. } } template <class T> void Circular_buffer<T> ::update_tail(size_t len) { if ((head_ >= tail_) || (End - tail_ >= len)) {; tail_ = tail_ + len; } else { tail_ = len - End + tail_;// ( tail_ + len )% End; 와 같음. } } template <class T> T* Circular_buffer<T> ::Ref(T* buf, int len) { if ((head_ >= tail_) || (End - tail_ >= len)) { MoveMemory(buf, begin + tail_, len); } else { MoveMemory(buf, begin + tail_, End - tail_); MoveMemory(buf + End - tail_, begin, len - End + tail_); } return buf; } template <class T> void Circular_buffer<T> ::put(T item) { //std::lock_guard<std::mutex> lock(mutex_); begin[head_] = item; if (full_) { tail_ = (tail_ + 1) % End; } head_ = (head_ + 1) % End; full_ = head_ == tail_; } template <class T> void Circular_buffer<T> ::update_head(size_t recored) { //std::lock_guard<std::mutex> lock(mutex_); //if (full_) //{ // tail_ = (tail_ + recored) % End; //} head_ = (head_ + recored) % End; //full_ = head_ == tail_; }
[ "yjpark9201@gmail.com" ]
yjpark9201@gmail.com
06971d1001f4b5e6185e462595e4f537da427b14
56f5af749409d1ead0de98e470e83f2ae140eb64
/src/core/common/locator.cpp
40dc1f1e5a7eafab8bd6a88b95ddc0796e5d4e7c
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
ygtysr/openthread
178101233019735864234f6a53538f87301721fe
afa7f34b265f262138f40a007e304c1c2d3f10f6
refs/heads/master
2021-01-25T14:45:40.552604
2018-03-02T17:16:36
2018-03-02T17:16:36
123,726,211
2
0
null
2018-03-03T19:53:32
2018-03-03T19:53:32
null
UTF-8
C++
false
false
2,255
cpp
/* * Copyright (c) 2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the locator class for OpenThread objects. */ #define WPP_NAME "locator.tmh" #include "locator.hpp" #include "common/instance.hpp" #include "net/ip6.hpp" namespace ot { #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES Instance &InstanceLocator::GetInstance(void) const { return Instance::Get(); } #endif Ip6::Ip6 &InstanceLocator::GetIp6(void) const { return GetInstance().GetIp6(); } ThreadNetif &InstanceLocator::GetNetif(void) const { return GetInstance().GetThreadNetif(); } Notifier &InstanceLocator::GetNotifier(void) const { return GetInstance().GetNotifier(); } } // namespace ot
[ "jonhui@nestlabs.com" ]
jonhui@nestlabs.com
0f90df94e6aeed405db60f5818b59295881e6b29
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/2017-2021/2019/speedrun/002/a.cpp
c9aa4d6741a455cd425a4804803f7fade8165bd3
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
827
cpp
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- int N; ll A,B; void solve() { int i,j,k,l,r,x,y; string s; cin>>N; FOR(i,N) { cin>>A>>B; cout<<A*B<<endl; } } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false), cin.tie(0); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); cout.tie(0); solve(); return 0; }
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
a42d0456b50c6e3e05a75256e2dc5143d86e3a6a
54bba666285f7b97fe101368f25556d9500c3c45
/MCM.cpp
56d50ec1950be06d0c10bb1bfba3a593ae480027
[ "MIT" ]
permissive
dlara10/DanielLara_Ejercicio22
4e8510d90b5bb82ab71bc44f9ffb84fec9d3c257
203c7e1145a2675803ab0fb691039f5f2b85f1d1
refs/heads/master
2020-05-04T21:44:38.743980
2019-04-04T14:51:10
2019-04-04T14:51:10
179,486,965
0
0
null
null
null
null
UTF-8
C++
false
false
923
cpp
#define _USE_MATH_DEFINES #include <iostream> #include <cstdlib> #include <ctime> #include <math.h> #include <algorithm> using std::cout; using std::endl; float apuesta(float x); void MCM(int inicial, int *x); int main(){ int i, N, y; N = 1000; int x[N]; for ( int i = 0; i < N; i++ ) { MCM(N, &y); cout << x[i] << endl; } return 0; } float f(float x){ return exp(-(x*x)/2); } void MCM(int inicial, int *x){ int i; int step, propuesta, alpha, a, r, n; int h[inicial]; srand48(time(0)); i = 0; a = (rand()%3)*M_PI; r = 0; while(i <= inicial){ step = a + rand()%3-1; if(1< f(step)/f(a) ){ r = 1; }else{ r = f(step)/f(a); } alpha = rand(); if(alpha<r){ h[i] = step; }else{ h[i] = a; } a += step; i++; } *x = r; }
[ "d.lara10@uniandes.edu.co" ]
d.lara10@uniandes.edu.co
b2c8fb24412f51f1cb9370098041b3572866a686
d0fb46aecc3b69983e7f6244331a81dff42d9595
/r-kvstore/include/alibabacloud/r-kvstore/model/DescribeAccountsResult.h
2ac4f90d0d68ddc4e03e3bc5d15dc9c438bb0f63
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,819
h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_R_KVSTORE_MODEL_DESCRIBEACCOUNTSRESULT_H_ #define ALIBABACLOUD_R_KVSTORE_MODEL_DESCRIBEACCOUNTSRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/r-kvstore/R_kvstoreExport.h> namespace AlibabaCloud { namespace R_kvstore { namespace Model { class ALIBABACLOUD_R_KVSTORE_EXPORT DescribeAccountsResult : public ServiceResult { public: struct Account { struct DatabasePrivilege { std::string accountPrivilege; std::string accountPrivilegeDetail; }; std::string accountDescription; std::string accountStatus; std::string instanceId; std::string accountType; std::vector<Account::DatabasePrivilege> databasePrivileges; std::string accountName; }; DescribeAccountsResult(); explicit DescribeAccountsResult(const std::string &payload); ~DescribeAccountsResult(); std::vector<Account> getAccounts()const; protected: void parse(const std::string &payload); private: std::vector<Account> accounts_; }; } } } #endif // !ALIBABACLOUD_R_KVSTORE_MODEL_DESCRIBEACCOUNTSRESULT_H_
[ "haowei.yao@alibaba-inc.com" ]
haowei.yao@alibaba-inc.com
051d9ec6f043337a67fcf9f4157629a6ebb22f68
bf0e0ca8d71c453c506176ab40b343297ce77fc8
/memory/boost/memory/pool.hpp
3d4bef5c8ec28c786c394206f5f686ae2478ed6e
[ "MIT" ]
permissive
vihariswamy/cerl
59ad9cebcf5443e0487160c47423cd4a872bf82e
02b75ab9daf19f63294b7c078a73753328e2984b
refs/heads/master
2022-12-26T04:09:22.807492
2020-10-01T10:57:40
2020-10-01T10:57:40
300,246,396
0
0
MIT
2020-10-01T10:57:07
2020-10-01T10:57:06
null
UTF-8
C++
false
false
913
hpp
// // boost/memory/pool.hpp // // Copyright (c) 2004 - 2008 xushiwei (xushiweizh@gmail.com) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/memory/index.htm for documentation. // #ifndef BOOST_MEMORY_POOL_HPP #define BOOST_MEMORY_POOL_HPP #ifndef BOOST_MEMORY_POOL_ALLOC_HPP #include "pool_alloc.hpp" #endif #ifndef BOOST_MEMORY_BLOCKPOOL_HPP #include "block_pool.hpp" #endif NS_BOOST_MEMORY_BEGIN // ------------------------------------------------------------------------- // class pool, scoped_pool typedef pool_alloc<NS_BOOST_MEMORY_POLICY::stdlib> pool; typedef pool_alloc<NS_BOOST_MEMORY_POLICY::scoped> scoped_pool; // ------------------------------------------------------------------------- NS_BOOST_MEMORY_END #endif /* BOOST_MEMORY_POOL_HPP */
[ "xushiweizh@gmail.com" ]
xushiweizh@gmail.com
64d7ead4a16984828d7e65356700faa56b453455
6038e68f49a6f6bf7d8053500da7bd9a302d2800
/Arduino/Lampka.h
1bb55fd83947cce31047a7fa8e28b192cb3ad8fa
[]
no_license
receek/Projekt_PO
adbe16eb1ebcff05572424bef0c6810d27e40347
be4ea1d13a3b1a8893f103222e65dd16865cb91a
refs/heads/master
2022-10-15T13:23:58.522330
2022-10-02T12:27:45
2022-10-02T12:27:45
190,267,021
0
0
null
null
null
null
UTF-8
C++
false
false
605
h
#ifndef Lampka_h #define Lampka_h #include "Arduino.h" #include "Modul.h" class Lampka : public Modul { private: int pin_analog_in; int pin_pwm; int value; int last_value; int range; bool active; public: Lampka() {} Lampka(int, int); virtual void apply_state(bool); virtual bool is_modyfing(); virtual bool is_tasking(); virtual void print_data(LiquidCrystal*, bool); virtual void execute_task(); virtual void write_info(char*, int*); virtual int write_data(char* buffer); virtual int procces_data(char*, char*, int); }; #endif
[ "krzysztof.juszczyk20@gmail.com" ]
krzysztof.juszczyk20@gmail.com
14a5d04e131dc3672a82419b8200363bb34b0895
97b3e122718def0797a0e0963eb2ca37c01dfebf
/include/modules/chanserv/level.h
05582764178e9c35c314909351a914728c74e848
[]
no_license
aszrul/anope
1af8392fe99863df63af3ceeddda95844ab74bc9
0902ee30447d7d063be7d2d8636470fc26d34d0f
refs/heads/master
2023-06-08T11:54:55.914919
2021-12-20T11:58:13
2021-12-20T12:15:31
18,457,844
0
0
null
null
null
null
UTF-8
C++
false
false
1,205
h
/* * Anope IRC Services * * Copyright (C) 2012-2017 Anope Team <team@anope.org> * * This file is part of Anope. Anope 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, version 2. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see see <http://www.gnu.org/licenses/>. */ #pragma once namespace ChanServ { class Level : public Serialize::Object { public: static constexpr const char *const NAME = "level"; using Serialize::Object::Object; virtual Channel *GetChannel() anope_abstract; virtual void SetChannel(Channel *) anope_abstract; virtual Anope::string GetName() anope_abstract; virtual void SetName(const Anope::string &) anope_abstract; virtual int GetLevel() anope_abstract; virtual void SetLevel(const int &) anope_abstract; }; } // namespace ChanServ
[ "Adam@anope.org" ]
Adam@anope.org
e1416af3afffe353326eafb6c701097a56cd8574
a254a6bc7cbd830f955e1b81d6f75a12d808161b
/AutoLoadDemo/AutoLoadDemo/Apps/Duck/src/mainwindow.cpp
760b9a364bad75a7bc7e3d2cd88acfdc41acdceb
[]
no_license
ruoyu2048/QtWorkspace
57c41253ce0c1538387c9711d426fff2b90c48d2
18a575c31e659cdcf6d9cdcb84537ee1530131a6
refs/heads/master
2023-04-03T06:42:22.623088
2021-04-09T07:23:29
2021-04-09T07:23:29
142,648,701
4
6
null
null
null
null
UTF-8
C++
false
false
2,966
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "PluginManager.h" #include "PluginInterface.h" #include <QMessageBox> #include <QMdiSubWindow> #include <QDockWidget> #include <QTextEdit> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); iniForm(); loadPlugin(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::iniForm() { this->showMaximized(); //setMinimumSize(QSize(1024,768)); QObject::connect(ui->mainToolBar, SIGNAL(actionTriggered(QAction*)), SLOT(actionTriggeredSlots(QAction* ))); } void MainWindow::loadPlugin() { PluginManager *manager = new PluginManager(this); QMap<QString, PluginInterface*> map = manager->FindPlugin(); QMap<QString, PluginInterface*>::const_iterator i = map.constBegin(); while (i != map.constEnd()) { i.value()->widget()->setWindowTitle(i.key()); _MapWidget[i.key()] = i.value()->widget(); _MapDockWidgetArea[i.key()] = i.value()->duck_DockWidgetArea(); if(i.value()->duck_Widget() == DUCK_WIDGETTYPE::MDIAREA){ ui->mainToolBar->addAction(QIcon(i.value()->iconPath()),i.value()->name()); ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); } if(i.value()->duck_Widget() == DUCK_WIDGETTYPE::DOCKWIDGET){ addDockWidget(i.value()->duck_DockWidgetArea(), Duck_Widget(i.value()->widget())); ui->menuView->addAction(Duck_Widget(i.value()->widget())->toggleViewAction()); } ++i; } ui->mainToolBar->toolButtonStyleChanged(Qt::ToolButtonTextUnderIcon); delete manager; } void MainWindow::loadPluginWidget() { PluginManager *manager = new PluginManager(this); QMap<QString, PluginInterface*> map = manager->FindPlugin(); QMap<QString, PluginInterface*>::const_iterator i = map.constBegin(); while (i != map.constEnd()) { _MapWidget[i.key()] = i.value()->widget(); _MapDockWidgetArea[i.key()] = i.value()->duck_DockWidgetArea(); ++i; } delete manager; } QDockWidget *MainWindow::Duck_Widget(QWidget *widget) { QDockWidget *dock = new QDockWidget(widget->windowTitle()); dock->setFeatures(QDockWidget::DockWidgetMovable); dock->setAllowedAreas(Qt::AllDockWidgetAreas); dock->setWidget(widget); return dock; } void MainWindow::actionTriggeredSlots(QAction *action) { if(ui->mdiArea->subWindowList().count() != 0){ for(int i =0 ; i < ui->mdiArea->subWindowList().count(); i++){ if(ui->mdiArea->subWindowList().at(i)->windowTitle() == action->text()){ return; } } } ui->mdiArea->addSubWindow(_MapWidget[action->text()],Qt::SubWindow); _MapWidget[action->text()]->setWindowIcon(action->icon()); _MapWidget[action->text()]->setWindowTitle(action->text()); _MapWidget[action->text()]->show(); loadPluginWidget(); }
[ "chenyouzhi06@163.com" ]
chenyouzhi06@163.com
1ace8ea000f9fecaf96b07e09d6ac2044afbcd2e
3b403117947515baa651b428485236abcc3bbbe0
/backchanger/changeback.h
97b6d0681f6baf5aaa850abcfc176642d17eeac8
[]
no_license
expliyh/backchanger
f0e0800489b9907e5cbd289d022cd640a3bbfa8c
1c563718923abe9611dfda739d7716255f26a1a0
refs/heads/master
2020-11-30T02:41:51.683756
2019-12-30T15:20:01
2019-12-30T15:20:01
230,279,027
0
0
null
null
null
null
UTF-8
C++
false
false
149
h
#include <iostream> #include <Windows.h> #include <string> #include <sstream> #include <direct.h> using namespace std; void change(string filename);
[ "expliyh@outlook.com" ]
expliyh@outlook.com
65c5fb9109136d67b49b72362dd5309428d8dd22
cce47742dab002daf68c754b5563eeee48d2aee3
/Actions/Move.h
41ec548771e62311fe68566e72b235267a01a207
[]
no_license
MennaMustafa/Flow-chart-simulator
f5ee13309c7dee002edcb1c64179740e0ae25208
894e6376b75a71797591b71a40cc298fe9a339d5
refs/heads/master
2021-01-21T17:17:40.565404
2017-05-21T09:19:54
2017-05-21T09:19:54
91,944,618
0
0
null
null
null
null
UTF-8
C++
false
false
380
h
#pragma once #include "Action.h" #include"../Statements/Statement.h" class Move : public Action { private: Point Position; Statement *S; int counter; public: Move(ApplicationManager *pAppManager); //Read Assignemt statements position virtual void ReadActionParameters(); //Create and add an assignemnt statement to the list of statements virtual void Execute(); };
[ "mennamustafa.f@gmail.com" ]
mennamustafa.f@gmail.com
867b5ae211a477695077381f67bf1196568a3969
25f9765455ad09c14e9cc54a8f5fa3a590466f37
/job/globus_gram_job_adaptor_stream.hpp
d7582b8085f6bc18e7b181c74f8c4173d09bf2c2
[ "BSL-1.0" ]
permissive
saga-project/saga-cpp-adaptor-globus
8d41af595c6402ba4a3a6462c5edde9933357a4d
33b352cbbc12f9057cab9c59d71a514661032edf
refs/heads/master
2021-01-22T09:50:46.101174
2012-01-26T16:31:26
2012-01-26T16:31:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,237
hpp
// Copyright (c) 2007 Ole Christian Weidner (oweidner@cct.lsu.edu) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef GLOBUS_GRAM_JOB_ADAPTOR_STREAM_HPP #define GLOBUS_GRAM_JOB_ADAPTOR_STREAM_HPP #include <iosfwd> #include <saga/impl/engine/cpi.hpp> /////////////////////////////////////////////////////////////////////////////// namespace impl { template <typename Base> class globus_gram_job_adaptor_stream : public Base { private: typedef Base base_type; public: globus_gram_job_adaptor_stream(saga::impl::v1_0::job_cpi* cpi, int fd) : base_type(fd), cpi_(cpi->shared_from_this()), proxy_(cpi->get_proxy()->shared_from_this()) { } ~globus_gram_job_adaptor_stream() { // } private: // a saga stream has to keep alive the proxy and the cpi instance TR1::shared_ptr<saga::impl::v1_0::cpi> cpi_; TR1::shared_ptr<saga::impl::proxy> proxy_; }; /////////////////////////////////////////////////////////////////////////////// } // namespace impl #endif // GLOBUS_GRAM_JOB_ADAPTOR_STREAM_HPP
[ "oweidner@cct.lsu.edu" ]
oweidner@cct.lsu.edu
b1040228a87b03e396a8f04ea90fa417def2ba60
c0caed81b5b3e1498cbca4c1627513c456908e38
/src/protocols/docking/DockingPrepackProtocol.fwd.hh
dc55e0c71ecb24f041899ddecde6c5d418161597
[]
no_license
malaifa/source
5b34ac0a4e7777265b291fc824da8837ecc3ee84
fc0af245885de0fb82e0a1144422796a6674aeae
refs/heads/master
2021-01-19T22:10:22.942155
2017-04-19T14:13:07
2017-04-19T14:13:07
88,761,668
0
2
null
null
null
null
UTF-8
C++
false
false
1,085
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file docking_min_protocol /// @brief /// @author Robin A Thottungal (raugust1@jhu.edu) #ifndef INCLUDED_protocols_docking_DockingPrepackProtocol_fwd_hh #define INCLUDED_protocols_docking_DockingPrepackProtocol_fwd_hh #include <utility/pointer/owning_ptr.hh> namespace protocols { namespace docking { class DockingPrepackProtocol; typedef utility::pointer::shared_ptr< DockingPrepackProtocol > DockingPrepackProtocolOP; typedef utility::pointer::shared_ptr< DockingPrepackProtocol const > DockingPrepackProtocolCOP; } } #endif
[ "malaifa@yahoo.com" ]
malaifa@yahoo.com
110d35b217a65c7c659de56cacfa1b23b2ac2627
3d402c62aa5fe37858e785becedec0ede33aa951
/Intermediate1/5. 완전 탐색 1/ExhaustiveSearch1/ExhaustiveSearch1/1963.cpp
6832a324699b393a24a9d2509f81db273964745b
[]
no_license
syshim77/BaekjoonOnlineLecture
6786a1ea7f960279c5046def86591b46baa747a8
c5e85c3f98981d9f761e3c61ae75c341514cdd1b
refs/heads/master
2020-04-27T20:29:55.368243
2019-04-10T11:25:32
2019-04-10T11:25:32
174,660,292
0
0
null
null
null
null
UHC
C++
false
false
1,128
cpp
// 코드 이해하고 다시 풀어볼 것 #include <iostream> #include <cstring> #include <queue> #include <string> #include <algorithm> using namespace std; bool prime[10001]; bool c[10001]; int d[10001]; int change(int num, int index, int digit) { if (index == 0 && digit == 0) return -1; string s = to_string(num); s[index] = digit + '0'; return stoi(s); } int main() { for (int i = 2; i <= 10000; i++) { if (prime[i] == false) { for (int j = i*i; j <= 10000; j += i) { prime[j] = true; } } } for (int i = 0; i <= 10000; i++) { prime[i] = !prime[i]; } int t; cin >> t; while (t--) { int n, m; cin >> n >> m; memset(c, false, sizeof(c)); memset(d, 0, sizeof(d)); d[n] = 0; c[n] = true; queue<int> q; q.push(n); while (!q.empty()) { int now = q.front(); q.pop(); for (int i = 0; i<4; i++) { for (int j = 0; j <= 9; j++) { int next = change(now, i, j); if (next != -1) { if (prime[next] && c[next] == false) { q.push(next); d[next] = d[now] + 1; c[next] = true; } } } } } cout << d[m] << '\n'; } return 0; }
[ "syshim77@gmail.com" ]
syshim77@gmail.com
1f0ebbc9e40264b44f9264414d1a6d21a7101982
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/third_party/blink/renderer/core/aom/accessible_node_list.h
a048b24706c62667880c5f9a87919627448f4e03
[ "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", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
1,813
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_AOM_ACCESSIBLE_NODE_LIST_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_AOM_ACCESSIBLE_NODE_LIST_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/bindings/v8_binding.h" namespace blink { class AccessibleNode; enum class AOMRelationListProperty; class ExceptionState; // Accessibility Object Model node list // Explainer: https://github.com/WICG/aom/blob/master/explainer.md // Spec: https://wicg.github.io/aom/spec/ class CORE_EXPORT AccessibleNodeList : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: static AccessibleNodeList* Create(const HeapVector<Member<AccessibleNode>>&); AccessibleNodeList(); ~AccessibleNodeList() override; void AddOwner(AOMRelationListProperty, AccessibleNode*); void RemoveOwner(AOMRelationListProperty, AccessibleNode*); AccessibleNode* item(unsigned offset) const; void add(AccessibleNode*, AccessibleNode* = nullptr); void remove(int index); IndexedPropertySetterResult AnonymousIndexedSetter(unsigned, AccessibleNode*, ExceptionState&); unsigned length() const; void setLength(unsigned); void Trace(Visitor*) const override; private: void NotifyChanged(); HeapVector<std::pair<AOMRelationListProperty, Member<AccessibleNode>>> owners_; HeapVector<Member<AccessibleNode>> nodes_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_AOM_ACCESSIBLE_NODE_LIST_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
151c70a1a8af7756890375915fc2a81844c9e6e4
4b6ba2969250944f8d6921402822077d6d875659
/code/TSQueueMain.cc
795e6c427c485b2272e40cde0d949f0d9d858904
[]
no_license
asegid/os-playground
9323e124c1ca8444d73393fae09089479ffcde46
e124027bcccc01367f9a8bc01d7d530e16b4ee64
refs/heads/master
2021-01-24T04:55:24.359431
2016-05-05T20:30:02
2016-05-05T20:30:02
61,919,284
1
0
null
2016-06-25T00:20:09
2016-06-25T00:20:09
null
UTF-8
C++
false
false
1,150
cc
#include <assert.h> #include <stdio.h> #include "thread.h" #include "TSQueue.h" void *putSome(void *p); void testRemoval(TSQueue *tsqueuePtr); // TSQueueMain.cc // Test code for TSQueue. int main(int argc, char **argv) { TSQueue *queues[3]; sthread_t workers[3]; int i, j; // Start worker threads to insert. for (i = 0; i < 3; i++) { queues[i] = new TSQueue(); thread_create_p(&workers[i], putSome, queues[i]); } // Wait for some items to be put. thread_join(workers[0]); // Remove 20 items from each queue. for (i = 0; i < 3; i++) { printf("Queue %d:\n", i); testRemoval(&queues[i]); } } // Insert 50 items into a queue. void *putSome(void *p) { TSQueue *queue = (TSQueue *)p; int i; for (i = 0; i < 50; i++) { queue->tryInsert(i); } return NULL; } // Remove 20 items from a queue. void testRemoval(TSQueue *queue) { int i, item; for (i = 0; i < 20; j++) { if (queue->tryRemove(&item)) printf("Removed %d\n", item); else printf("Nothing there.\n"); } } }
[ "ivogeorg@gmail.com" ]
ivogeorg@gmail.com
bef500c0c6fe0d37190d9688e020c836cc69aabe
09dc57d26326f2190d7aee1c5562793aed986ba5
/Src/Condition.cc
f8813f915b5af6f7f0f2051d5835775b68a9214e
[]
no_license
colinhp/SpellCorrection-System
8a295e4c6c7a7fce6fabbbfdd1e1df7ac4e7d297
251fbac8c72c87d04d82f0222c9e94b85e1918fc
refs/heads/master
2021-05-20T23:31:31.968607
2015-12-27T05:07:56
2015-12-27T05:07:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
458
cc
#include "../Inc/Condition.h" #include "../Inc/MutexLock.h" namespace tanfy { Condition::Condition(MutexLock &mutex) :mutex_(mutex) { pthread_cond_init(&cond_, NULL); } Condition::~Condition() { pthread_cond_destroy(&cond_); } void Condition::wait() { pthread_cond_wait(&cond_, mutex_.getMutexPtr()); } void Condition::notify() { pthread_cond_signal(&cond_); } void Condition::notifyall() { pthread_cond_broadcast(&cond_); } }//end of namespace
[ "tanfy.0113@gmail.com" ]
tanfy.0113@gmail.com
dfeea03c81e086b5dc5fa1cd1ce4f2da0755fa21
f72cf9f9c4469c8cfc314377947c0d540d45ccaf
/tests/src/RaZ/Script/LuaAnimation.cpp
fa758df635aa4f968c85d6e657d8b0a8a5d14fb7
[ "MIT" ]
permissive
Razakhel/RaZ
1ce718b55deee01ca13ba86b63d02de201a50fb3
c8b365f3f42de145d79c191fac93b3924b9952bf
refs/heads/master
2023-08-16T18:18:20.344104
2023-08-02T19:47:57
2023-08-05T12:40:06
56,182,613
496
33
MIT
2023-09-08T22:25:16
2016-04-13T20:10:49
C++
UTF-8
C++
false
false
1,872
cpp
#include "Catch.hpp" #include "RaZ/Script/LuaWrapper.hpp" TEST_CASE("LuaAnimation Skeleton") { CHECK(Raz::LuaWrapper::execute(R"( local skeleton = Skeleton.new() skeleton = Skeleton.new(0) skeleton = BvhFormat.load(FilePath.new(RAZ_TESTS_ROOT .. "assets/animation/ànîm.bvh")) assert(skeleton:getNodeCount() == 5) local rootJoint = skeleton:getNode(0) assert(rootJoint:isRoot()) rootJoint.rotation = Quaternionf.new(Radiansf.new(Constant.Pi), Axis.Y) rootJoint:rotate(Quaternionf.new(Radiansf.new(Constant.Pi), Axis.Z)) rootJoint.translation = Vec3f.new(1) rootJoint:translate(Vec3f.new(1, 2, 3)) assert(rootJoint.translation == Vec3f.new(2, 3, 4)) assert(rootJoint.rotation == Quaternionf.new(0, 1, 0, 0)) assert(rootJoint:computeTransformMatrix() == Mat4f.new(1, 0, 0, 2, 0, -1, 0, 3, 0, 0, -1, 4, 0, 0, 0, 1)) assert(rootJoint:getChildCount() == 2) assert(rootJoint:getChild(0):getParentCount() == 1) assert(rootJoint:getChild(0):getParent(0) == rootJoint) assert(rootJoint:getChild(0):isLeaf()) rootJoint:removeChildren(rootJoint:getChild(0), rootJoint:getChild(1)) assert(rootJoint:isIsolated()) rootJoint:addChildren(skeleton:getNode(1), skeleton:getNode(2)) assert(rootJoint:getChildCount() == 2) local newJoint = skeleton:addNode() assert(skeleton:getNodeCount() == 6) skeleton:getNode(1):addParents(rootJoint, newJoint) assert(skeleton:getNode(1):getParentCount() == 2) skeleton:getNode(1):removeParents(rootJoint, newJoint) assert(skeleton:getNode(1):isRoot()) skeleton:removeNode(newJoint) assert(skeleton:getNodeCount() == 5) )")); }
[ "romain.milbert@gmail.com" ]
romain.milbert@gmail.com
caf0e368ba2949565f46a10adf30a786ffb7677d
dd90bfc1970227b42497fc9158b232b7fcd4fdc7
/Exercises/factory.cc
ae489d34900430c91eaa06c11b0e38a0aa6b0a67
[]
no_license
RendaZhang/class-repo-public
ae5f5a032185a1748a91bbf53bb78f86df571d5e
b0841bb00ce47ce5570c0d778e122a5e8aaffa7b
refs/heads/master
2022-10-25T21:18:58.643612
2020-06-16T11:45:27
2020-06-16T11:45:27
272,690,315
0
0
null
null
null
null
UTF-8
C++
false
false
813
cc
#define RED 0 #define BLUE 1 class Entity { public: Entity(int x=0, int y=0) : pos_x_(x), pos_y_(y), color_(RED) {} private: int pos_x_; int pos_y_; int color_; }; class Robot : public Entity { public: Robot(int x=0, int y=0) : Entity(x,y), unique_to_robot_(0) {} private: int unique_to_robot_; }; class Player : public Entity { public: Player(int x=0, int y=0) : Entity(x,y), unique_to_player_(0) {} private: int unique_to_player_; }; class EntityFactory { public: //Entity* Create( ... }; class RobotFactory : public EntityFactory { // ... }; class PlayerFactory : public EntityFactory { // ... }; class Arena { //void AddEntities( EntityFactory factory, ... }; int main() { Arena arena; RobotFactory robot_factory; PlayerFactory player_factory; // AddEntities( ... }
[ "952402967@qq.com" ]
952402967@qq.com
de22054033cbc3506970864e9f1296995f3b8cdb
d1a0d697798704d2a989b068574587cf6ca1ece9
/extensions/browser/api/management/management_api.cc
9cc75c1387f424549692110ce4368bb26081f3a9
[ "BSD-3-Clause" ]
permissive
lihui7115/ChromiumGStreamerBackend
983199aa76e052d3e9ea21ff53d0dd4cf4c995dc
6e41f524b780f2ff8d731f9986be743414a49a33
refs/heads/master
2021-01-17T10:26:00.070404
2015-08-05T16:39:35
2015-08-05T17:09:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,737
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/api/management/management_api.h" #include <string> #include <vector> #include "base/basictypes.h" #include "base/bind.h" #include "base/json/json_writer.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/memory/linked_ptr.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_context.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/management/management_api_constants.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/management_policy.h" #include "extensions/browser/requirements_checker.h" #include "extensions/browser/uninstall_reason.h" #include "extensions/common/api/management.h" #include "extensions/common/constants.h" #include "extensions/common/error_utils.h" #include "extensions/common/extension.h" #include "extensions/common/extension_icon_set.h" #include "extensions/common/manifest_handlers/icons_handler.h" #include "extensions/common/manifest_handlers/offline_enabled_info.h" #include "extensions/common/manifest_handlers/options_page_info.h" #include "extensions/common/manifest_url_handlers.h" #include "extensions/common/permissions/permission_set.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/url_pattern.h" using base::IntToString; using content::BrowserThread; namespace keys = extension_management_api_constants; namespace extensions { namespace management = api::management; namespace { typedef std::vector<linked_ptr<management::ExtensionInfo>> ExtensionInfoList; typedef std::vector<linked_ptr<management::IconInfo>> IconInfoList; enum AutoConfirmForTest { DO_NOT_SKIP = 0, PROCEED, ABORT }; AutoConfirmForTest auto_confirm_for_test = DO_NOT_SKIP; std::vector<std::string> CreateWarningsList(const Extension* extension) { std::vector<std::string> warnings_list; for (const extensions::PermissionMessageString& str : extension->permissions_data()->GetPermissionMessageStrings()) { warnings_list.push_back(base::UTF16ToUTF8(str.message)); } return warnings_list; } std::vector<management::LaunchType> GetAvailableLaunchTypes( const Extension& extension, const ManagementAPIDelegate* delegate) { std::vector<management::LaunchType> launch_type_list; if (extension.is_platform_app()) { launch_type_list.push_back(management::LAUNCH_TYPE_OPEN_AS_WINDOW); return launch_type_list; } launch_type_list.push_back(management::LAUNCH_TYPE_OPEN_AS_REGULAR_TAB); launch_type_list.push_back(management::LAUNCH_TYPE_OPEN_AS_WINDOW); if (!delegate->IsNewBookmarkAppsEnabled()) { launch_type_list.push_back(management::LAUNCH_TYPE_OPEN_AS_PINNED_TAB); launch_type_list.push_back(management::LAUNCH_TYPE_OPEN_FULL_SCREEN); } return launch_type_list; } scoped_ptr<management::ExtensionInfo> CreateExtensionInfo( const Extension& extension, content::BrowserContext* context) { ExtensionSystem* system = ExtensionSystem::Get(context); ExtensionRegistry* registry = ExtensionRegistry::Get(context); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance()->Get(context)->GetDelegate(); scoped_ptr<management::ExtensionInfo> info(new management::ExtensionInfo()); info->id = extension.id(); info->name = extension.name(); info->short_name = extension.short_name(); info->enabled = registry->enabled_extensions().Contains(info->id); info->offline_enabled = OfflineEnabledInfo::IsOfflineEnabled(&extension); info->version = extension.VersionString(); info->description = extension.description(); info->options_url = OptionsPageInfo::GetOptionsPage(&extension).spec(); info->homepage_url.reset( new std::string(ManifestURL::GetHomepageURL(&extension).spec())); info->may_disable = system->management_policy()->UserMayModifySettings(&extension, NULL); info->is_app = extension.is_app(); if (info->is_app) { if (extension.is_legacy_packaged_app()) info->type = management::EXTENSION_TYPE_LEGACY_PACKAGED_APP; else if (extension.is_hosted_app()) info->type = management::EXTENSION_TYPE_HOSTED_APP; else info->type = management::EXTENSION_TYPE_PACKAGED_APP; } else if (extension.is_theme()) { info->type = management::EXTENSION_TYPE_THEME; } else { info->type = management::EXTENSION_TYPE_EXTENSION; } if (info->enabled) { info->disabled_reason = management::EXTENSION_DISABLED_REASON_NONE; } else { ExtensionPrefs* prefs = ExtensionPrefs::Get(context); if (prefs->DidExtensionEscalatePermissions(extension.id())) { info->disabled_reason = management::EXTENSION_DISABLED_REASON_PERMISSIONS_INCREASE; } else { info->disabled_reason = management::EXTENSION_DISABLED_REASON_UNKNOWN; } } if (!ManifestURL::GetUpdateURL(&extension).is_empty()) { info->update_url.reset( new std::string(ManifestURL::GetUpdateURL(&extension).spec())); } if (extension.is_app()) { info->app_launch_url.reset( new std::string(delegate->GetFullLaunchURL(&extension).spec())); } const ExtensionIconSet::IconMap& icons = IconsInfo::GetIcons(&extension).map(); if (!icons.empty()) { info->icons.reset(new IconInfoList()); ExtensionIconSet::IconMap::const_iterator icon_iter; for (icon_iter = icons.begin(); icon_iter != icons.end(); ++icon_iter) { management::IconInfo* icon_info = new management::IconInfo(); icon_info->size = icon_iter->first; GURL url = delegate->GetIconURL(&extension, icon_info->size, ExtensionIconSet::MATCH_EXACTLY, false, nullptr); icon_info->url = url.spec(); info->icons->push_back(make_linked_ptr<management::IconInfo>(icon_info)); } } const std::set<std::string> perms = extension.permissions_data()->active_permissions()->GetAPIsAsStrings(); if (!perms.empty()) { std::set<std::string>::const_iterator perms_iter; for (perms_iter = perms.begin(); perms_iter != perms.end(); ++perms_iter) info->permissions.push_back(*perms_iter); } if (!extension.is_hosted_app()) { // Skip host permissions for hosted apps. const URLPatternSet host_perms = extension.permissions_data()->active_permissions()->explicit_hosts(); if (!host_perms.is_empty()) { for (URLPatternSet::const_iterator iter = host_perms.begin(); iter != host_perms.end(); ++iter) { info->host_permissions.push_back(iter->GetAsString()); } } } switch (extension.location()) { case Manifest::INTERNAL: info->install_type = management::EXTENSION_INSTALL_TYPE_NORMAL; break; case Manifest::UNPACKED: case Manifest::COMMAND_LINE: info->install_type = management::EXTENSION_INSTALL_TYPE_DEVELOPMENT; break; case Manifest::EXTERNAL_PREF: case Manifest::EXTERNAL_REGISTRY: case Manifest::EXTERNAL_PREF_DOWNLOAD: info->install_type = management::EXTENSION_INSTALL_TYPE_SIDELOAD; break; case Manifest::EXTERNAL_POLICY: case Manifest::EXTERNAL_POLICY_DOWNLOAD: info->install_type = management::EXTENSION_INSTALL_TYPE_ADMIN; break; case Manifest::NUM_LOCATIONS: NOTREACHED(); case Manifest::INVALID_LOCATION: case Manifest::COMPONENT: case Manifest::EXTERNAL_COMPONENT: info->install_type = management::EXTENSION_INSTALL_TYPE_OTHER; break; } info->launch_type = management::LAUNCH_TYPE_NONE; if (extension.is_app()) { LaunchType launch_type; if (extension.is_platform_app()) { launch_type = LAUNCH_TYPE_WINDOW; } else { launch_type = delegate->GetLaunchType(ExtensionPrefs::Get(context), &extension); } switch (launch_type) { case LAUNCH_TYPE_PINNED: info->launch_type = management::LAUNCH_TYPE_OPEN_AS_PINNED_TAB; break; case LAUNCH_TYPE_REGULAR: info->launch_type = management::LAUNCH_TYPE_OPEN_AS_REGULAR_TAB; break; case LAUNCH_TYPE_FULLSCREEN: info->launch_type = management::LAUNCH_TYPE_OPEN_FULL_SCREEN; break; case LAUNCH_TYPE_WINDOW: info->launch_type = management::LAUNCH_TYPE_OPEN_AS_WINDOW; break; case LAUNCH_TYPE_INVALID: case NUM_LAUNCH_TYPES: NOTREACHED(); } info->available_launch_types.reset(new std::vector<management::LaunchType>( GetAvailableLaunchTypes(extension, delegate))); } return info.Pass(); } bool ShouldNotBeVisible(const Extension* extension, content::BrowserContext* context) { return (extension->ShouldNotBeVisible() || ExtensionPrefs::Get(context)->IsEphemeralApp(extension->id())); } void AddExtensionInfo(const ExtensionSet& extensions, ExtensionInfoList* extension_list, content::BrowserContext* context) { for (ExtensionSet::const_iterator iter = extensions.begin(); iter != extensions.end(); ++iter) { const Extension& extension = *iter->get(); if (ShouldNotBeVisible(&extension, context)) continue; // Skip built-in extensions/apps. extension_list->push_back(make_linked_ptr<management::ExtensionInfo>( CreateExtensionInfo(extension, context).release())); } } } // namespace bool ManagementGetAllFunction::RunSync() { ExtensionInfoList extensions; ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); AddExtensionInfo(registry->enabled_extensions(), &extensions, browser_context()); AddExtensionInfo(registry->disabled_extensions(), &extensions, browser_context()); AddExtensionInfo(registry->terminated_extensions(), &extensions, browser_context()); results_ = management::GetAll::Results::Create(extensions); return true; } bool ManagementGetFunction::RunSync() { scoped_ptr<management::Get::Params> params( management::Get::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); const Extension* extension = registry->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); if (!extension) { error_ = ErrorUtils::FormatErrorMessage(keys::kNoExtensionError, params->id); return false; } scoped_ptr<management::ExtensionInfo> info = CreateExtensionInfo(*extension, browser_context()); results_ = management::Get::Results::Create(*info); return true; } bool ManagementGetSelfFunction::RunSync() { scoped_ptr<management::ExtensionInfo> info = CreateExtensionInfo(*extension_, browser_context()); results_ = management::Get::Results::Create(*info); return true; } bool ManagementGetPermissionWarningsByIdFunction::RunSync() { scoped_ptr<management::GetPermissionWarningsById::Params> params( management::GetPermissionWarningsById::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); if (!extension) { error_ = ErrorUtils::FormatErrorMessage(keys::kNoExtensionError, params->id); return false; } std::vector<std::string> warnings = CreateWarningsList(extension); results_ = management::GetPermissionWarningsById::Results::Create(warnings); return true; } bool ManagementGetPermissionWarningsByManifestFunction::RunAsync() { scoped_ptr<management::GetPermissionWarningsByManifest::Params> params( management::GetPermissionWarningsByManifest::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); if (delegate) { delegate->GetPermissionWarningsByManifestFunctionDelegate( this, params->manifest_str); // Matched with a Release() in OnParseSuccess/Failure(). AddRef(); // Response is sent async in OnParseSuccess/Failure(). return true; } else { // TODO(lfg) add error string OnParseFailure(""); return false; } } void ManagementGetPermissionWarningsByManifestFunction::OnParseSuccess( scoped_ptr<base::Value> value) { if (!value->IsType(base::Value::TYPE_DICTIONARY)) { OnParseFailure(keys::kManifestParseError); return; } const base::DictionaryValue* parsed_manifest = static_cast<const base::DictionaryValue*>(value.get()); scoped_refptr<Extension> extension = Extension::Create(base::FilePath(), Manifest::INVALID_LOCATION, *parsed_manifest, Extension::NO_FLAGS, &error_); if (!extension) { OnParseFailure(keys::kExtensionCreateError); return; } std::vector<std::string> warnings = CreateWarningsList(extension.get()); results_ = management::GetPermissionWarningsByManifest::Results::Create(warnings); SendResponse(true); // Matched with AddRef() in RunAsync(). Release(); } void ManagementGetPermissionWarningsByManifestFunction::OnParseFailure( const std::string& error) { error_ = error; SendResponse(false); // Matched with AddRef() in RunAsync(). Release(); } bool ManagementLaunchAppFunction::RunSync() { scoped_ptr<management::LaunchApp::Params> params( management::LaunchApp::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); if (!extension) { error_ = ErrorUtils::FormatErrorMessage(keys::kNoExtensionError, params->id); return false; } if (!extension->is_app()) { error_ = ErrorUtils::FormatErrorMessage(keys::kNotAnAppError, params->id); return false; } const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); return delegate->LaunchAppFunctionDelegate(extension, browser_context()); } ManagementSetEnabledFunction::ManagementSetEnabledFunction() { } ManagementSetEnabledFunction::~ManagementSetEnabledFunction() { } ExtensionFunction::ResponseAction ManagementSetEnabledFunction::Run() { scoped_ptr<management::SetEnabled::Params> params( management::SetEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); extension_id_ = params->id; const Extension* extension = registry->GetExtensionById(extension_id_, ExtensionRegistry::EVERYTHING); if (!extension || ShouldNotBeVisible(extension, browser_context())) return RespondNow(Error(keys::kNoExtensionError, extension_id_)); bool enabled = params->enabled; const ManagementPolicy* policy = ExtensionSystem::Get(browser_context())->management_policy(); if (!policy->UserMayModifySettings(extension, nullptr) || (!enabled && policy->MustRemainEnabled(extension, nullptr)) || (enabled && policy->MustRemainDisabled(extension, nullptr, nullptr))) { return RespondNow(Error(keys::kUserCantModifyError, extension_id_)); } bool currently_enabled = registry->enabled_extensions().Contains(extension_id_) || registry->terminated_extensions().Contains(extension_id_); if (!currently_enabled && enabled) { ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context()); if (prefs->DidExtensionEscalatePermissions(extension_id_)) { if (!user_gesture()) return RespondNow(Error(keys::kGestureNeededForEscalationError)); AddRef(); // Matched in InstallUIProceed/InstallUIAbort install_prompt_ = delegate->SetEnabledFunctionDelegate(this, extension); return RespondLater(); } if (prefs->GetDisableReasons(extension_id_) & Extension::DISABLE_UNSUPPORTED_REQUIREMENT) { // Recheck the requirements. requirements_checker_ = delegate->CreateRequirementsChecker(); requirements_checker_->Check( extension, base::Bind(&ManagementSetEnabledFunction::OnRequirementsChecked, this)); // This bind creates a reference. return RespondLater(); } delegate->EnableExtension(browser_context(), extension_id_); } else if (currently_enabled && !params->enabled) { delegate->DisableExtension(browser_context(), extension_id_, Extension::DISABLE_USER_ACTION); } return RespondNow(NoArguments()); } void ManagementSetEnabledFunction::InstallUIProceed() { ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate() ->EnableExtension(browser_context(), extension_id_); Respond(OneArgument(new base::FundamentalValue(true))); Release(); } void ManagementSetEnabledFunction::InstallUIAbort(bool user_initiated) { Respond(Error(keys::kUserDidNotReEnableError)); Release(); } void ManagementSetEnabledFunction::OnRequirementsChecked( const std::vector<std::string>& requirements_errors) { if (requirements_errors.empty()) { ManagementAPI::GetFactoryInstance()->Get(browser_context())->GetDelegate()-> EnableExtension(browser_context(), extension_id_); Respond(NoArguments()); } else { // TODO(devlin): Should we really be noisy here all the time? Respond(Error(keys::kMissingRequirementsError, base::JoinString(requirements_errors, " "))); } } ManagementUninstallFunctionBase::ManagementUninstallFunctionBase() { } ManagementUninstallFunctionBase::~ManagementUninstallFunctionBase() { } ExtensionFunction::ResponseAction ManagementUninstallFunctionBase::Uninstall( const std::string& target_extension_id, bool show_confirm_dialog) { const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); target_extension_id_ = target_extension_id; const Extension* target_extension = extensions::ExtensionRegistry::Get(browser_context()) ->GetExtensionById(target_extension_id_, ExtensionRegistry::EVERYTHING); if (!target_extension || ShouldNotBeVisible(target_extension, browser_context())) { return RespondNow(Error(keys::kNoExtensionError, target_extension_id_)); } ManagementPolicy* policy = ExtensionSystem::Get(browser_context())->management_policy(); if (!policy->UserMayModifySettings(target_extension, nullptr) || policy->MustRemainInstalled(target_extension, nullptr)) { return RespondNow(Error(keys::kUserCantModifyError, target_extension_id_)); } // Note: null extension() means it's WebUI. bool self_uninstall = extension() && extension_id() == target_extension_id_; // We need to show a dialog for any extension uninstalling another extension. show_confirm_dialog |= !self_uninstall; if (show_confirm_dialog && !user_gesture()) return RespondNow(Error(keys::kGestureNeededForUninstallError)); if (show_confirm_dialog) { // We show the programmatic uninstall ui for extensions uninstalling // other extensions. bool show_programmatic_uninstall_ui = !self_uninstall && extension(); AddRef(); // Balanced in OnExtensionUninstallDialogClosed. // TODO(devlin): A method called "UninstallFunctionDelegate" does not in // any way imply that this actually creates a dialog and runs it. uninstall_dialog_ = delegate->UninstallFunctionDelegate( this, target_extension, show_programmatic_uninstall_ui); } else { // No confirm dialog. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ManagementUninstallFunctionBase::UninstallExtension, this)); } return RespondLater(); } void ManagementUninstallFunctionBase::Finish(bool did_start_uninstall, const std::string& error) { Respond(did_start_uninstall ? NoArguments() : Error(error)); } void ManagementUninstallFunctionBase::OnExtensionUninstallDialogClosed( bool did_start_uninstall, const base::string16& error) { Finish(did_start_uninstall, ErrorUtils::FormatErrorMessage(keys::kUninstallCanceledError, target_extension_id_)); Release(); // Balanced in Uninstall(). } void ManagementUninstallFunctionBase::UninstallExtension() { // The extension can be uninstalled in another window while the UI was // showing. Do nothing in that case. const Extension* target_extension = extensions::ExtensionRegistry::Get(browser_context()) ->GetExtensionById(target_extension_id_, ExtensionRegistry::EVERYTHING); std::string error; bool success = false; if (target_extension) { const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); base::string16 utf16_error; success = delegate->UninstallExtension( browser_context(), target_extension_id_, extensions::UNINSTALL_REASON_MANAGEMENT_API, base::Bind(&base::DoNothing), &utf16_error); error = base::UTF16ToUTF8(utf16_error); } else { error = ErrorUtils::FormatErrorMessage(keys::kNoExtensionError, target_extension_id_); } Finish(success, error); } ManagementUninstallFunction::ManagementUninstallFunction() { } ManagementUninstallFunction::~ManagementUninstallFunction() { } ExtensionFunction::ResponseAction ManagementUninstallFunction::Run() { scoped_ptr<management::Uninstall::Params> params( management::Uninstall::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); bool show_confirm_dialog = params->options.get() && params->options->show_confirm_dialog.get() && *params->options->show_confirm_dialog; return Uninstall(params->id, show_confirm_dialog); } ManagementUninstallSelfFunction::ManagementUninstallSelfFunction() { } ManagementUninstallSelfFunction::~ManagementUninstallSelfFunction() { } ExtensionFunction::ResponseAction ManagementUninstallSelfFunction::Run() { scoped_ptr<management::UninstallSelf::Params> params( management::UninstallSelf::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); EXTENSION_FUNCTION_VALIDATE(extension_.get()); bool show_confirm_dialog = params->options.get() && params->options->show_confirm_dialog.get() && *params->options->show_confirm_dialog; return Uninstall(extension_->id(), show_confirm_dialog); } ManagementCreateAppShortcutFunction::ManagementCreateAppShortcutFunction() { } ManagementCreateAppShortcutFunction::~ManagementCreateAppShortcutFunction() { } // static void ManagementCreateAppShortcutFunction::SetAutoConfirmForTest( bool should_proceed) { auto_confirm_for_test = should_proceed ? PROCEED : ABORT; } void ManagementCreateAppShortcutFunction::OnCloseShortcutPrompt(bool created) { if (!created) error_ = keys::kCreateShortcutCanceledError; SendResponse(created); Release(); } bool ManagementCreateAppShortcutFunction::RunAsync() { if (!user_gesture()) { error_ = keys::kGestureNeededForCreateAppShortcutError; return false; } scoped_ptr<management::CreateAppShortcut::Params> params( management::CreateAppShortcut::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); if (!extension) { error_ = ErrorUtils::FormatErrorMessage(keys::kNoExtensionError, params->id); return false; } if (!extension->is_app()) { error_ = ErrorUtils::FormatErrorMessage(keys::kNotAnAppError, params->id); return false; } #if defined(OS_MACOSX) if (!extension->is_platform_app()) { error_ = keys::kCreateOnlyPackagedAppShortcutMac; return false; } #endif if (auto_confirm_for_test != DO_NOT_SKIP) { // Matched with a Release() in OnCloseShortcutPrompt(). AddRef(); OnCloseShortcutPrompt(auto_confirm_for_test == PROCEED); return true; } if (ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate() ->CreateAppShortcutFunctionDelegate(this, extension)) { // Matched with a Release() in OnCloseShortcutPrompt(). AddRef(); } // Response is sent async in OnCloseShortcutPrompt(). return true; } bool ManagementSetLaunchTypeFunction::RunSync() { if (!user_gesture()) { error_ = keys::kGestureNeededForSetLaunchTypeError; return false; } scoped_ptr<management::SetLaunchType::Params> params( management::SetLaunchType::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); if (!extension) { error_ = ErrorUtils::FormatErrorMessage(keys::kNoExtensionError, params->id); return false; } if (!extension->is_app()) { error_ = ErrorUtils::FormatErrorMessage(keys::kNotAnAppError, params->id); return false; } std::vector<management::LaunchType> available_launch_types = GetAvailableLaunchTypes(*extension, delegate); management::LaunchType app_launch_type = params->launch_type; if (std::find(available_launch_types.begin(), available_launch_types.end(), app_launch_type) == available_launch_types.end()) { error_ = keys::kLaunchTypeNotAvailableError; return false; } LaunchType launch_type = LAUNCH_TYPE_DEFAULT; switch (app_launch_type) { case management::LAUNCH_TYPE_OPEN_AS_PINNED_TAB: launch_type = LAUNCH_TYPE_PINNED; break; case management::LAUNCH_TYPE_OPEN_AS_REGULAR_TAB: launch_type = LAUNCH_TYPE_REGULAR; break; case management::LAUNCH_TYPE_OPEN_FULL_SCREEN: launch_type = LAUNCH_TYPE_FULLSCREEN; break; case management::LAUNCH_TYPE_OPEN_AS_WINDOW: launch_type = LAUNCH_TYPE_WINDOW; break; case management::LAUNCH_TYPE_NONE: NOTREACHED(); } delegate->SetLaunchType(browser_context(), params->id, launch_type); return true; } ManagementGenerateAppForLinkFunction::ManagementGenerateAppForLinkFunction() { } ManagementGenerateAppForLinkFunction::~ManagementGenerateAppForLinkFunction() { } void ManagementGenerateAppForLinkFunction::FinishCreateBookmarkApp( const Extension* extension, const WebApplicationInfo& web_app_info) { if (extension) { scoped_ptr<management::ExtensionInfo> info = CreateExtensionInfo(*extension, browser_context()); results_ = management::GenerateAppForLink::Results::Create(*info); SendResponse(true); Release(); } else { error_ = keys::kGenerateAppForLinkInstallError; SendResponse(false); Release(); } } bool ManagementGenerateAppForLinkFunction::RunAsync() { if (!user_gesture()) { error_ = keys::kGestureNeededForGenerateAppForLinkError; return false; } scoped_ptr<management::GenerateAppForLink::Params> params( management::GenerateAppForLink::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); GURL launch_url(params->url); if (!launch_url.is_valid() || !launch_url.SchemeIsHTTPOrHTTPS()) { error_ = ErrorUtils::FormatErrorMessage(keys::kInvalidURLError, params->url); return false; } if (params->title.empty()) { error_ = keys::kEmptyTitleError; return false; } app_for_link_delegate_ = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate() ->GenerateAppForLinkFunctionDelegate(this, browser_context(), params->title, launch_url); // Matched with a Release() in FinishCreateBookmarkApp(). AddRef(); // Response is sent async in FinishCreateBookmarkApp(). return true; } ManagementEventRouter::ManagementEventRouter(content::BrowserContext* context) : browser_context_(context), extension_registry_observer_(this) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); } ManagementEventRouter::~ManagementEventRouter() { } void ManagementEventRouter::OnExtensionLoaded( content::BrowserContext* browser_context, const Extension* extension) { BroadcastEvent(extension, events::MANAGEMENT_ON_ENABLED, management::OnEnabled::kEventName); } void ManagementEventRouter::OnExtensionUnloaded( content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionInfo::Reason reason) { BroadcastEvent(extension, events::MANAGEMENT_ON_DISABLED, management::OnDisabled::kEventName); } void ManagementEventRouter::OnExtensionInstalled( content::BrowserContext* browser_context, const Extension* extension, bool is_update) { BroadcastEvent(extension, events::MANAGEMENT_ON_INSTALLED, management::OnInstalled::kEventName); } void ManagementEventRouter::OnExtensionUninstalled( content::BrowserContext* browser_context, const Extension* extension, extensions::UninstallReason reason) { BroadcastEvent(extension, events::MANAGEMENT_ON_UNINSTALLED, management::OnUninstalled::kEventName); } void ManagementEventRouter::BroadcastEvent( const Extension* extension, events::HistogramValue histogram_value, const char* event_name) { if (ShouldNotBeVisible(extension, browser_context_)) return; // Don't dispatch events for built-in extenions. scoped_ptr<base::ListValue> args(new base::ListValue()); if (event_name == management::OnUninstalled::kEventName) { args->Append(new base::StringValue(extension->id())); } else { scoped_ptr<management::ExtensionInfo> info = CreateExtensionInfo(*extension, browser_context_); args->Append(info->ToValue().release()); } EventRouter::Get(browser_context_) ->BroadcastEvent(scoped_ptr<Event>( new Event(histogram_value, event_name, args.Pass()))); } ManagementAPI::ManagementAPI(content::BrowserContext* context) : browser_context_(context), delegate_(ExtensionsAPIClient::Get()->CreateManagementAPIDelegate()) { EventRouter* event_router = EventRouter::Get(browser_context_); event_router->RegisterObserver(this, management::OnInstalled::kEventName); event_router->RegisterObserver(this, management::OnUninstalled::kEventName); event_router->RegisterObserver(this, management::OnEnabled::kEventName); event_router->RegisterObserver(this, management::OnDisabled::kEventName); } ManagementAPI::~ManagementAPI() { } void ManagementAPI::Shutdown() { EventRouter::Get(browser_context_)->UnregisterObserver(this); } static base::LazyInstance<BrowserContextKeyedAPIFactory<ManagementAPI>> g_factory = LAZY_INSTANCE_INITIALIZER; // static BrowserContextKeyedAPIFactory<ManagementAPI>* ManagementAPI::GetFactoryInstance() { return g_factory.Pointer(); } void ManagementAPI::OnListenerAdded(const EventListenerInfo& details) { management_event_router_.reset(new ManagementEventRouter(browser_context_)); EventRouter::Get(browser_context_)->UnregisterObserver(this); } } // namespace extensions
[ "j.isorce@samsung.com" ]
j.isorce@samsung.com
37be079a2a5f8a8071953712a39212c4d60237fc
d990692dd7afdbb2a235ad03ac5209b4f3bb0df9
/ipc/chromium/src/chrome/common/ipc_fuzzing_tests.cc
8148723957b03e8c446ca7a28668142ae248232f
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
walkero-gr/timberwolf
5c33158a19dfeb3781c72c6732d45747d9a3c19e
90ca7da29b6089d1b14f5ff1d08e586aa2ec041f
refs/heads/master
2022-09-15T11:13:14.252767
2022-09-04T12:39:59
2022-09-04T12:39:59
291,531,351
0
0
NOASSERTION
2020-08-30T18:46:51
2020-08-30T18:46:51
null
UTF-8
C++
false
false
13,754
cc
// Copyright (c) 2006-2008 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 <stdio.h> #include <iostream> #include <string> #include <sstream> #include "base/message_loop.h" #include "base/platform_thread.h" #include "base/process_util.h" #include "chrome/common/ipc_channel.h" #include "chrome/common/ipc_channel_proxy.h" #include "chrome/common/ipc_message_utils.h" #include "chrome/common/ipc_tests.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" TEST(IPCMessageIntegrity, ReadBeyondBufferStr) { //This was BUG 984408. uint32 v1 = kuint32max - 1; int v2 = 666; IPC::Message m(0, 1, IPC::Message::PRIORITY_NORMAL); EXPECT_TRUE(m.WriteInt(v1)); EXPECT_TRUE(m.WriteInt(v2)); void* iter = NULL; std::string vs; EXPECT_FALSE(m.ReadString(&iter, &vs)); } TEST(IPCMessageIntegrity, ReadBeyondBufferWStr) { //This was BUG 984408. uint32 v1 = kuint32max - 1; int v2 = 777; IPC::Message m(0, 1, IPC::Message::PRIORITY_NORMAL); EXPECT_TRUE(m.WriteInt(v1)); EXPECT_TRUE(m.WriteInt(v2)); void* iter = NULL; std::wstring vs; EXPECT_FALSE(m.ReadWString(&iter, &vs)); } TEST(IPCMessageIntegrity, ReadBytesBadIterator) { // This was BUG 1035467. IPC::Message m(0, 1, IPC::Message::PRIORITY_NORMAL); EXPECT_TRUE(m.WriteInt(1)); EXPECT_TRUE(m.WriteInt(2)); void* iter = NULL; const char* data = NULL; EXPECT_FALSE(m.ReadBytes(&iter, &data, sizeof(int))); } TEST(IPCMessageIntegrity, ReadVectorNegativeSize) { // A slight variation of BUG 984408. Note that the pickling of vector<char> // has a specialized template which is not vulnerable to this bug. So here // try to hit the non-specialized case vector<P>. IPC::Message m(0, 1, IPC::Message::PRIORITY_NORMAL); EXPECT_TRUE(m.WriteInt(-1)); // This is the count of elements. EXPECT_TRUE(m.WriteInt(1)); EXPECT_TRUE(m.WriteInt(2)); EXPECT_TRUE(m.WriteInt(3)); std::vector<double> vec; void* iter = 0; EXPECT_FALSE(ReadParam(&m, &iter, &vec)); } TEST(IPCMessageIntegrity, ReadVectorTooLarge1) { // This was BUG 1006367. This is the large but positive length case. Again // we try to hit the non-specialized case vector<P>. IPC::Message m(0, 1, IPC::Message::PRIORITY_NORMAL); EXPECT_TRUE(m.WriteInt(0x21000003)); // This is the count of elements. EXPECT_TRUE(m.WriteInt64(1)); EXPECT_TRUE(m.WriteInt64(2)); std::vector<int64> vec; void* iter = 0; EXPECT_FALSE(ReadParam(&m, &iter, &vec)); } TEST(IPCMessageIntegrity, ReadVectorTooLarge2) { // This was BUG 1006367. This is the large but positive with an additional // integer overflow when computing the actual byte size. Again we try to hit // the non-specialized case vector<P>. IPC::Message m(0, 1, IPC::Message::PRIORITY_NORMAL); EXPECT_TRUE(m.WriteInt(0x71000000)); // This is the count of elements. EXPECT_TRUE(m.WriteInt64(1)); EXPECT_TRUE(m.WriteInt64(2)); std::vector<int64> vec; void* iter = 0; EXPECT_FALSE(ReadParam(&m, &iter, &vec)); } // We don't actually use the messages defined in this file, but we do this // to get to the IPC macros. #define MESSAGES_INTERNAL_FILE "chrome/common/ipc_sync_message_unittest.h" #include "chrome/common/ipc_message_macros.h" enum IPCMessageIds { UNUSED_IPC_TYPE, SERVER_FIRST_IPC_TYPE, // 1st Test message tag. SERVER_SECOND_IPC_TYPE, // 2nd Test message tag. SERVER_THIRD_IPC_TYPE, // 3rd Test message tag. CLIENT_MALFORMED_IPC, // Sent to client if server detects bad message. CLIENT_UNHANDLED_IPC // Sent to client if server detects unhanded IPC. }; // Generic message class that is an int followed by a wstring. class MsgClassIS : public IPC::MessageWithTuple< Tuple2<int, std::wstring> > { public: enum { ID = SERVER_FIRST_IPC_TYPE }; MsgClassIS(const int& arg1, const std::wstring& arg2) : IPC::MessageWithTuple< Tuple2<int, std::wstring> >( MSG_ROUTING_CONTROL, ID, MakeTuple(arg1, arg2)) {} }; // Generic message class that is a wstring followed by an int. class MsgClassSI : public IPC::MessageWithTuple< Tuple2<std::wstring, int> > { public: enum { ID = SERVER_SECOND_IPC_TYPE }; MsgClassSI(const std::wstring& arg1, const int& arg2) : IPC::MessageWithTuple< Tuple2<std::wstring, int> >( MSG_ROUTING_CONTROL, ID, MakeTuple(arg1, arg2)) {} }; // Message to create a mutex in the IPC server, using the received name. class MsgDoMutex : public IPC::MessageWithTuple< Tuple2<std::wstring, int> > { public: enum { ID = SERVER_THIRD_IPC_TYPE }; MsgDoMutex(const std::wstring& mutex_name, const int& unused) : IPC::MessageWithTuple< Tuple2<std::wstring, int> >( MSG_ROUTING_CONTROL, ID, MakeTuple(mutex_name, unused)) {} }; class SimpleListener : public IPC::Channel::Listener { public: SimpleListener() : other_(NULL) { } void Init(IPC::Message::Sender* s) { other_ = s; } protected: IPC::Message::Sender* other_; }; enum { FUZZER_ROUTING_ID = 5 }; // The fuzzer server class. It runs in a child process and expects // only two IPC calls; after that it exits the message loop which // terminates the child process. class FuzzerServerListener : public SimpleListener { public: FuzzerServerListener() : message_count_(2), pending_messages_(0) { } virtual void OnMessageReceived(const IPC::Message& msg) { if (msg.routing_id() == MSG_ROUTING_CONTROL) { ++pending_messages_; IPC_BEGIN_MESSAGE_MAP(FuzzerServerListener, msg) IPC_MESSAGE_HANDLER(MsgClassIS, OnMsgClassISMessage) IPC_MESSAGE_HANDLER(MsgClassSI, OnMsgClassSIMessage) IPC_END_MESSAGE_MAP() if (pending_messages_) { // Probably a problem de-serializing the message. ReplyMsgNotHandled(msg.type()); } } } private: void OnMsgClassISMessage(int value, const std::wstring& text) { UseData(MsgClassIS::ID, value, text); RoundtripAckReply(FUZZER_ROUTING_ID, MsgClassIS::ID, value); Cleanup(); } void OnMsgClassSIMessage(const std::wstring& text, int value) { UseData(MsgClassSI::ID, value, text); RoundtripAckReply(FUZZER_ROUTING_ID, MsgClassSI::ID, value); Cleanup(); } bool RoundtripAckReply(int routing, int type_id, int reply) { IPC::Message* message = new IPC::Message(routing, type_id, IPC::Message::PRIORITY_NORMAL); message->WriteInt(reply + 1); message->WriteInt(reply); return other_->Send(message); } void Cleanup() { --message_count_; --pending_messages_; if (0 == message_count_) MessageLoop::current()->Quit(); } void ReplyMsgNotHandled(int type_id) { RoundtripAckReply(FUZZER_ROUTING_ID, CLIENT_UNHANDLED_IPC, type_id); Cleanup(); } void UseData(int caller, int value, const std::wstring& text) { std::wostringstream wos; wos << L"IPC fuzzer:" << caller << " [" << value << L" " << text << L"]\n"; std::wstring output = wos.str(); LOG(WARNING) << output.c_str(); }; int message_count_; int pending_messages_; }; class FuzzerClientListener : public SimpleListener { public: FuzzerClientListener() : last_msg_(NULL) { } virtual void OnMessageReceived(const IPC::Message& msg) { last_msg_ = new IPC::Message(msg); MessageLoop::current()->Quit(); } bool ExpectMessage(int value, int type_id) { if (!MsgHandlerInternal(type_id)) return false; int msg_value1 = 0; int msg_value2 = 0; void* iter = NULL; if (!last_msg_->ReadInt(&iter, &msg_value1)) return false; if (!last_msg_->ReadInt(&iter, &msg_value2)) return false; if ((msg_value2 + 1) != msg_value1) return false; if (msg_value2 != value) return false; delete last_msg_; last_msg_ = NULL; return true; } bool ExpectMsgNotHandled(int type_id) { return ExpectMessage(type_id, CLIENT_UNHANDLED_IPC); } private: bool MsgHandlerInternal(int type_id) { MessageLoop::current()->Run(); if (NULL == last_msg_) return false; if (FUZZER_ROUTING_ID != last_msg_->routing_id()) return false; return (type_id == last_msg_->type()); }; IPC::Message* last_msg_; }; // Runs the fuzzing server child mode. Returns when the preset number // of messages have been received. MULTIPROCESS_TEST_MAIN(RunFuzzServer) { MessageLoopForIO main_message_loop; FuzzerServerListener listener; IPC::Channel chan(kFuzzerChannel, IPC::Channel::MODE_CLIENT, &listener); chan.Connect(); listener.Init(&chan); MessageLoop::current()->Run(); return 0; } class IPCFuzzingTest : public IPCChannelTest { }; // This test makes sure that the FuzzerClientListener and FuzzerServerListener // are working properly by generating two well formed IPC calls. TEST_F(IPCFuzzingTest, SanityTest) { FuzzerClientListener listener; IPC::Channel chan(kFuzzerChannel, IPC::Channel::MODE_SERVER, &listener); base::ProcessHandle server_process = SpawnChild(FUZZER_SERVER, &chan); ASSERT_TRUE(server_process); PlatformThread::Sleep(1000); ASSERT_TRUE(chan.Connect()); listener.Init(&chan); IPC::Message* msg = NULL; int value = 43; msg = new MsgClassIS(value, L"expect 43"); chan.Send(msg); EXPECT_TRUE(listener.ExpectMessage(value, MsgClassIS::ID)); msg = new MsgClassSI(L"expect 44", ++value); chan.Send(msg); EXPECT_TRUE(listener.ExpectMessage(value, MsgClassSI::ID)); EXPECT_TRUE(base::WaitForSingleProcess(server_process, 5000)); base::CloseProcessHandle(server_process); } // This test uses a payload that is smaller than expected. // This generates an error while unpacking the IPC buffer which in // In debug this triggers an assertion and in release it is ignored(!!). Right // after we generate another valid IPC to make sure framing is working // properly. #ifdef NDEBUG TEST_F(IPCFuzzingTest, MsgBadPayloadShort) { FuzzerClientListener listener; IPC::Channel chan(kFuzzerChannel, IPC::Channel::MODE_SERVER, &listener); base::ProcessHandle server_process = SpawnChild(FUZZER_SERVER, &chan); ASSERT_TRUE(server_process); PlatformThread::Sleep(1000); ASSERT_TRUE(chan.Connect()); listener.Init(&chan); IPC::Message* msg = new IPC::Message(MSG_ROUTING_CONTROL, MsgClassIS::ID, IPC::Message::PRIORITY_NORMAL); msg->WriteInt(666); chan.Send(msg); EXPECT_TRUE(listener.ExpectMsgNotHandled(MsgClassIS::ID)); msg = new MsgClassSI(L"expect one", 1); chan.Send(msg); EXPECT_TRUE(listener.ExpectMessage(1, MsgClassSI::ID)); EXPECT_TRUE(base::WaitForSingleProcess(server_process, 5000)); base::CloseProcessHandle(server_process); } #endif // NDEBUG // This test uses a payload that has too many arguments, but so the payload // size is big enough so the unpacking routine does not generate an error as // in the case of MsgBadPayloadShort test. // This test does not pinpoint a flaw (per se) as by design we don't carry // type information on the IPC message. TEST_F(IPCFuzzingTest, MsgBadPayloadArgs) { FuzzerClientListener listener; IPC::Channel chan(kFuzzerChannel, IPC::Channel::MODE_SERVER, &listener); base::ProcessHandle server_process = SpawnChild(FUZZER_SERVER, &chan); ASSERT_TRUE(server_process); PlatformThread::Sleep(1000); ASSERT_TRUE(chan.Connect()); listener.Init(&chan); IPC::Message* msg = new IPC::Message(MSG_ROUTING_CONTROL, MsgClassSI::ID, IPC::Message::PRIORITY_NORMAL); msg->WriteWString(L"d"); msg->WriteInt(0); msg->WriteInt(0x65); // Extra argument. chan.Send(msg); EXPECT_TRUE(listener.ExpectMessage(0, MsgClassSI::ID)); // Now send a well formed message to make sure the receiver wasn't // thrown out of sync by the extra argument. msg = new MsgClassIS(3, L"expect three"); chan.Send(msg); EXPECT_TRUE(listener.ExpectMessage(3, MsgClassIS::ID)); EXPECT_TRUE(base::WaitForSingleProcess(server_process, 5000)); base::CloseProcessHandle(server_process); } // This class is for testing the IPC_BEGIN_MESSAGE_MAP_EX macros. class ServerMacroExTest { public: ServerMacroExTest() : unhandled_msgs_(0) { } virtual bool OnMessageReceived(const IPC::Message& msg) { bool msg_is_ok = false; IPC_BEGIN_MESSAGE_MAP_EX(ServerMacroExTest, msg, msg_is_ok) IPC_MESSAGE_HANDLER(MsgClassIS, OnMsgClassISMessage) IPC_MESSAGE_HANDLER(MsgClassSI, OnMsgClassSIMessage) IPC_MESSAGE_UNHANDLED(++unhandled_msgs_) IPC_END_MESSAGE_MAP_EX() return msg_is_ok; } int unhandled_msgs() const { return unhandled_msgs_; } private: void OnMsgClassISMessage(int value, const std::wstring& text) { } void OnMsgClassSIMessage(const std::wstring& text, int value) { } int unhandled_msgs_; }; TEST_F(IPCFuzzingTest, MsgMapExMacro) { IPC::Message* msg = NULL; ServerMacroExTest server; // Test the regular messages. msg = new MsgClassIS(3, L"text3"); EXPECT_TRUE(server.OnMessageReceived(*msg)); delete msg; msg = new MsgClassSI(L"text2", 2); EXPECT_TRUE(server.OnMessageReceived(*msg)); delete msg; #ifdef NDEBUG // Test a bad message. msg = new IPC::Message(MSG_ROUTING_CONTROL, MsgClassSI::ID, IPC::Message::PRIORITY_NORMAL); msg->WriteInt(2); EXPECT_FALSE(server.OnMessageReceived(*msg)); delete msg; msg = new IPC::Message(MSG_ROUTING_CONTROL, MsgClassIS::ID, IPC::Message::PRIORITY_NORMAL); msg->WriteInt(0x64); msg->WriteInt(0x32); EXPECT_FALSE(server.OnMessageReceived(*msg)); delete msg; EXPECT_EQ(0, server.unhandled_msgs()); #endif }
[ "benjamin@smedbergs.us" ]
benjamin@smedbergs.us
4739b620c6d4c30edccfa28dcb7070792413be34
cfc99437b085afa7304ed5a4eab2a90072c7e50e
/pintools/extras/components/include/debugger-protocol/forward.hpp
cbf879fe7a5073488aa271a3ef37b78716844a4b
[ "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
moraispgsi/pin-bootstrap
95498b63f88c311e4fe446259214266130aece3f
7315b4e1709f63f018781456f9c745fc6f020f22
refs/heads/master
2021-09-07T18:09:11.568374
2018-02-27T05:16:32
2018-02-27T05:16:32
122,972,429
0
1
MIT
2018-02-26T14:31:18
2018-02-26T13:17:08
C++
UTF-8
C++
false
false
1,874
hpp
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL 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. END_LEGAL */ // <COMPONENT>: debugger-protocol // <FILE-TYPE>: component public header #ifndef DEBUGGER_PROTOCOL_FORWARD_HPP #define DEBUGGER_PROTOCOL_FORWARD_HPP namespace DEBUGGER_PROTOCOL { struct TCP_INFO; class IFRONTEND; class IBACKEND; class ICOMMANDS; class INOTIFICATIONS; class ILOG_NOTIFICATIONS; } // namespace #endif // file guard
[ "moraispgsi@gmail.com" ]
moraispgsi@gmail.com
1950e2e1064a78a886d7dc1dbbc255b629ffc530
771d2a1234eecd77b355590569b74a4b4c9a7eba
/nexxT/src/Logger.cpp
9b79c32b86a4019fdb594b60676a4e90aa5715ce
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
ifm/nexxT
776384b8f82b0a4f7a069f82c79f09b9710f87aa
d49f6595908f0ecf90060ec1d7d23075120c8045
refs/heads/master
2023-08-04T18:05:59.904490
2023-07-31T11:24:59
2023-07-31T11:24:59
248,195,896
11
2
Apache-2.0
2023-07-31T11:25:01
2020-03-18T10:05:08
Python
UTF-8
C++
false
false
1,161
cpp
/* * SPDX-License-Identifier: Apache-2.0 * Copyright (C) 2020 ifm electronic gmbh * * THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. */ #include "nexxT/Logger.hpp" using namespace nexxT; namespace nexxT { unsigned int Logging::loglevel; void Logging::setLogLevel(unsigned int level) { loglevel = level; } void Logging::_log(unsigned int level, const QString &message, const QString &file, unsigned int line) { SharedQObjectPtr logger = Services::getService("Logging"); if( !logger.isNull() ) { bool res = QMetaObject::invokeMethod(logger.get(), "log", Qt::DirectConnection, Q_ARG(int, level), Q_ARG(const QString &, message), Q_ARG(const QString &, file), Q_ARG(int, line)); if(!res) { fprintf(stderr, "WARNING: invokeMetod returned false!\n"); } } else { if( level >= NEXXT_LOG_LEVEL_INFO ) { fprintf(stderr, "LOG: level=%d msg=%s file=%s line=%d\n", level, message.toStdString().c_str(), file.toStdString().c_str(), line); } } } };
[ "62332054+cwiede@users.noreply.github.com" ]
62332054+cwiede@users.noreply.github.com
3d71423439a5bc5c75183d4201b6b1655406ed23
da8e7d1a86a03d936eecdc1a1328499a5e1168d7
/libraries/TGRSIFormat/TBadFragment.cxx
57181303ed98d28861f9490c406f6cf587d19bba
[]
no_license
mcgeee/GRSISort
45ce1e89cdb4d07dcfddc27bdcc3b26646aa4573
ac1df1b8e9856faced84cd9f443224d2f1f261b9
refs/heads/master
2021-01-21T21:19:00.380587
2017-06-17T01:46:28
2017-06-17T01:46:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,020
cxx
#include "TBadFragment.h" TBadFragment::TBadFragment() : TFragment() { /// Default constructor #if MAJOR_ROOT_VERSION < 6 Class()->IgnoreTObjectStreamer(kTRUE); #endif Clear(); } TBadFragment::TBadFragment(TFragment& fragment, uint32_t* data, int size, int failedWord, bool multipleErrors) : TFragment(fragment) { /// Construct a bad fragment from a fragment, the data it was created from, the size of that data, and the word the /// parser failed on. /// The data is only copied up to and including the next header word (high nibble 0x8). fData.clear(); // skipping the first word, we search for the next header int numWords; for(numWords = 1; numWords < size; ++numWords) { if((data[numWords] & 0xf0000000) == 0x80000000) break; } // only copy data up to the next header (including that header) fData.insert(fData.begin(), data, data + numWords + 1); fFailedWord = failedWord; fMultipleErrors = multipleErrors; } TBadFragment::TBadFragment(const TBadFragment& rhs) : TFragment(rhs) { /// Copy constructor fData = rhs.fData; fFailedWord = rhs.fFailedWord; } TBadFragment::~TBadFragment() { /// Destructor, does nothing for now. } void TBadFragment::Print(Option_t*) const { /// Print out all fields of the fragment using TFragment::Print() and then print the raw data with the failed words /// highlighted/ TFragment::Print(); std::cout << "Raw data with " << (fMultipleErrors ? "multiple errors" : "single error") << ":" << std::endl; size_t i; for(i = 0; i < fData.size(); ++i) { if(i == static_cast<size_t>(fFailedWord)) std::cout << ALERTTEXT; std::cout << "0x" << std::setw(8) << std::setfill('0') << std::hex << fData[i] << std::dec; if(i == static_cast<size_t>(fFailedWord)) std::cout << RESET_COLOR; if(i % 10 == 9) std::cout << std::endl; else std::cout << " "; } if(i % 10 != 0) std::cout << std::endl; // add newline if the last data word didn't have one }
[ "vbildste@uoguelph.ca" ]
vbildste@uoguelph.ca
9ea7262462b987336fd598474d95d3f42d73a545
1dbf007249acad6038d2aaa1751cbde7e7842c53
/csms/include/huaweicloud/csms/v1/model/ListProjectSecretsTagsRequest.h
4919c70f5c66a639628f07bd2040383258c74bc5
[]
permissive
huaweicloud/huaweicloud-sdk-cpp-v3
24fc8d93c922598376bdb7d009e12378dff5dd20
71674f4afbb0cd5950f880ec516cfabcde71afe4
refs/heads/master
2023-08-04T19:37:47.187698
2023-08-03T08:25:43
2023-08-03T08:25:43
324,328,641
11
10
Apache-2.0
2021-06-24T07:25:26
2020-12-25T09:11:43
C++
UTF-8
C++
false
false
1,306
h
#ifndef HUAWEICLOUD_SDK_CSMS_V1_MODEL_ListProjectSecretsTagsRequest_H_ #define HUAWEICLOUD_SDK_CSMS_V1_MODEL_ListProjectSecretsTagsRequest_H_ #include <huaweicloud/csms/v1/CsmsExport.h> #include <huaweicloud/core/utils/ModelBase.h> #include <huaweicloud/core/http/HttpResponse.h> namespace HuaweiCloud { namespace Sdk { namespace Csms { namespace V1 { namespace Model { using namespace HuaweiCloud::Sdk::Core::Utils; using namespace HuaweiCloud::Sdk::Core::Http; /// <summary> /// Request Object /// </summary> class HUAWEICLOUD_CSMS_V1_EXPORT ListProjectSecretsTagsRequest : public ModelBase { public: ListProjectSecretsTagsRequest(); virtual ~ListProjectSecretsTagsRequest(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; ///////////////////////////////////////////// /// ListProjectSecretsTagsRequest members protected: #ifdef RTTR_FLAG RTTR_ENABLE() public: ListProjectSecretsTagsRequest& dereference_from_shared_ptr(std::shared_ptr<ListProjectSecretsTagsRequest> ptr) { return *ptr; } #endif }; } } } } } #endif // HUAWEICLOUD_SDK_CSMS_V1_MODEL_ListProjectSecretsTagsRequest_H_
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
f273749b139a006506ec6bd5495b319a6c4104b5
0c54a096a1fd1110c0441c8c7fa7f2f441617cc5
/npr-v2/RMITGP.1.5/ProgramGenerator.h
f4c435a316150c6b0f4865cd7283f53abc617010
[]
no_license
s3544134/Non-Photorealistic-Rendering
09a79832eb8c62fb5dc411a7dc434c47cd5ef070
048a9b07d8f2df030cb35c10e5d32ea735086c90
refs/heads/master
2021-04-12T11:03:52.724447
2018-03-22T06:15:24
2018-03-22T06:15:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,492
h
#ifndef _PROGRAMGENERATOR_H_ #define _PROGRAMGENERATOR_H_ /****************************************************************************** Header file Class: ProgramGenerator Date created: 22/04/2002 Written by: Dylan Mawhinney The ProgramGenerator class generates program trees. ******************************************************************************/ #include "NodeVector.h" #include "GeneticProgram.h" #include "Node.h" class ProgramGenerator { private: GPConfig *config; NodeVector<Node> *growTable; NodeVector<Node> *fullTable; protected: public: ProgramGenerator(GPConfig *conf); virtual ~ProgramGenerator(); /********************************************* Generates an inital population. **********************************************/ virtual void generateInitialPopulation(GeneticProgram* pop[], int numIndividuals, int minSize, int maxSize, int expectedSize, int expectedReturnType); virtual Node* createFullProgram(int curDepth, int maxDepth, int expectedReturnType); virtual Node* createGrowProgram(int curDepth, int maxDepth, int expectedReturnType); }; #endif
[ "s3544134@student.rmit.edu.au" ]
s3544134@student.rmit.edu.au
97a887a57f6d4c3eec1b639e28ae65856ffe83de
368da16580bf14e9a284033b0f1a419b4674cee5
/yh_210608_1/src/yh_sub_1.cpp
4df8e46167d3dd714340d2f2aec7365d5ed584f0
[]
no_license
terrificmn/basic-ros
ae7fdf7da709a1a058bf517ff9f1829a47f38e86
63b3b92bb64794b5eb8dcaf3faca6f1b8fa4359c
refs/heads/main
2023-05-29T16:36:39.963956
2021-06-17T00:56:02
2021-06-17T00:56:02
377,665,584
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
#include "ros/ros.h"; #include "yh_210608_1/yh_msg_1.h"; void msgCallback (const yh_210608_1::yh_msg_1::ConstPtr&msg) { ROS_INFO("received msg = %d", msg->stamp.sec); ROS_INFO("received msg = %d", msg->stamp.nsec); ROS_INFO("received msg = %d", msg->data); } int main(int argc, char **argv) { ros::init(argc, argv, "yh_sub_1"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe("yh_topic_1", 100, msgCallback); ros::spin(); return 0; }
[ "mildsm@gmail.com" ]
mildsm@gmail.com
eef4884364baa713a426a172fafc9ce1e5d85c93
293f1095803ea5031e9719d28c0fcefe9008473a
/ichigo/Utils.cpp
642ee08c44e9011501ca3995a427bbaa01b2d2fc
[]
no_license
Avnerus/ichigo
23e24f547dde5d1bd158db7871a07a3f7679d4bb
849c507bfca8989685f9fc64ac06f68bc5ce0576
refs/heads/master
2021-01-13T14:37:06.784739
2015-10-03T17:22:19
2015-10-03T17:22:19
43,607,246
1
1
null
null
null
null
UTF-8
C++
false
false
3,422
cpp
#include "Utils.h" #include "TouchPoint.h" #include "Actor.h" #include "ActorView.h" #include <cmath> #include <time.h> #include <iomanip> #include <sstream> namespace ichigo { // Utility function to calculate the scale and rotation two touch points. The first one is static and the second one moving // If one of the out parameters is NULL, it will be disregarded void Utils::calcMultitouchTransform(ichigo::Point *anchorPos, ichigo::TouchPoint *touchPos, float *outScale, float *outRotation) { Point preMoveTP = touchPos->getPrevPos(); Point postMoveTP = touchPos->getPos(); // Calculate how much the distance has changed for the scale if (outScale) { float distanceBefore = anchorPos->distanceTo(preMoveTP); float distanceAfter = anchorPos->distanceTo(postMoveTP); if (distanceBefore != 0) { *outScale = distanceAfter / distanceBefore; } else { *outScale = 0; } } // Calculate how much the angle between both points has changed to get the rotation if (outRotation) { Point angleBefore = preMoveTP - *anchorPos; Point angleAfter = postMoveTP - *anchorPos; angleBefore.normalize(); angleAfter.normalize(); float angleInRadians = atan2f(angleAfter.y, angleAfter.x) - atan2f(angleBefore.y, angleBefore.x); *outRotation = -rad2deg(angleInRadians); } } // Returns true if the bounding spheres of both actor views are colliding bool Utils::areActorsColliding(ichigo::Actor *actor1, ichigo::Actor *actor2) { bool retVal = false; if (actor1 && actor2) { ActorView *view1 = (ActorView *)actor1->getView(); ActorView *view2 = (ActorView *)actor2->getView(); if (view1 && view2) { float distance = view1->getPositionOnScreen().distanceTo(view2->getPositionOnScreen()); if (distance <= view1->getRadius() * view1->getWorldScale() + view2->getRadius() * view2->getWorldScale()) { retVal = true; } } } return retVal; } // Converts an angle in radians to degrees float Utils::rad2deg(float angleInRadians) { return angleInRadians * 180.0f / PI; } // Converts an angle in degrees to radians float Utils::deg2rad(float angleInDegrees) { return angleInDegrees * PI / 180.0f; } // Seed the random generator void Utils::seedRand() { srand(time(NULL)); } // Returns a random float between 0 and max float Utils::randf(float max) { return ((float)rand() / (float)RAND_MAX) * max; } // Returns a random int between 0 and max int Utils::randi(int max) { return (rand() % max); } // Converts NUM into a string. If num has less digits than DIGITS, it will be zero padded std::string Utils::intToZeroPaddedString(int num, int digits) { std::ostringstream retVal; retVal << std::setw(digits) << std::setfill('0') << num; return retVal.str(); } }
[ "avnerus@gmail.com" ]
avnerus@gmail.com
c32d8d75ca1388bae64a25628934a9fcfe011bd1
5dc16607fc5438136f7a525563e95faf83e6fab4
/sandbox/zengarden_sample/zg_sample_2.cpp
86c5ba891f7bc79729d907ea6a7583cf0c7f5057
[]
no_license
rvega/XookyNabox
a1c8ea8e7df843a4fcc4c5ac5c3a576a634a91a2
a067710a7ee9a4259bbe09a36fb00283426a199e
refs/heads/master
2021-01-10T19:16:25.338171
2011-10-24T20:46:10
2011-10-24T20:46:10
1,781,227
5
1
null
null
null
null
UTF-8
C++
false
false
4,515
cpp
// // zg_sample_2.cpp // // Created by rafaelvega on 2011-01-23. // // An ALSA host to test ZenGarden. #include <iostream> #include <string> #include <alsa/asoundlib.h> #include "ZenGarden.h" // settings #define BLOCK_SIZE 1024 #define NUM_INPUTS 0 #define NUM_OUTPUTS 2 #define SAMPLERATE (44100.0f) using namespace std; // interleaved io buffers float output[BLOCK_SIZE*NUM_OUTPUTS]; float input[BLOCK_SIZE*NUM_INPUTS]; // =============================== // = Zengarden Callback Function = // =============================== extern "C" { void zengardenCallback(ZGCallbackFunction function, void *userData, void *ptr) { switch (function) { case ZG_PRINT_STD: { cout << "STD: " << (char *)ptr << endl; break; } case ZG_PRINT_ERR: { cout << "ERR: " << (char *)ptr << endl; break; } case ZG_PD_DSP: { cout << "DSP: " << (char *)ptr << endl; break; } } } }; // =============== // = Entry Point = // =============== int main(int argc, char * const argv[]) { //Parse command line params string arg_patch_path; int c; while((c = getopt(argc, argv, "p:")) != -1){ switch (c){ case 'p': arg_patch_path = string(optarg); break; } } if(arg_patch_path.empty()){ cout << "Usage:" << endl << argv[0] << " -p /path/to/patch.pd" << endl; exit(1); } //Open PCM device for playback. snd_pcm_t *output_handle; if (snd_pcm_open(&output_handle, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0) { // 0 is the standard mode, can also be SND_PCM_NONBLOCK or SND_PCM_NONBLOCK <http://www.suse.de/~mana/alsa090_howto.html> cout << "Unable to open default pcm device" << endl; exit(1); } //Set parameters to PCM device snd_pcm_hw_params_t *hw_params; // Hardware params struct snd_pcm_hw_params_alloca(&hw_params); //Allocate memory for it snd_pcm_hw_params_any(output_handle, hw_params); //Start with default PCM params snd_pcm_hw_params_set_access(output_handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED); //Set noninterleaved mode snd_pcm_hw_params_set_format(output_handle, hw_params, SND_PCM_FORMAT_S32); //Set 32 bit floating point samples snd_pcm_hw_params_set_channels(output_handle, hw_params, 2); // 2 output channels unsigned int samplerate_actual_value = SAMPLERATE; int dir; snd_pcm_hw_params_set_rate_near(output_handle, hw_params, &samplerate_actual_value, &dir); // Set sample rate snd_pcm_uframes_t block_size_actual_size = BLOCK_SIZE; snd_pcm_hw_params_set_period_size_near(output_handle, hw_params, &block_size_actual_size, &dir); // Set block size if (snd_pcm_hw_params(output_handle, hw_params) < 0) { cout << "Unable to set hardware parameters" << endl; exit(1); } // A sawtooth wave // unsigned char *data; // int pcmreturn, l1, l2; // short s1, s2; // int frames; // // data = (unsigned char *)malloc(block_size_actual_size); // frames = block_size_actual_size >> 2; // for(l1 = 0; l1 < 100; l1++) { // for(l2 = 0; l2 < block_size_actual_size; l2++) { // s1 = (l2 % 128) * 100 - 5000; // s2 = (l2 % 256) * 100 - 5000; // data[4*l2] = (unsigned char)s1; // data[4*l2+1] = s1 >> 8; // data[4*l2+2] = (unsigned char)s2; // data[4*l2+3] = s2 >> 8; // } // while ((pcmreturn = snd_pcm_writei(output_handle, data, frames)) < 0) { // snd_pcm_prepare(output_handle); // fprintf(stderr, "<<<<<<<<<<<<<<< Buffer Underrun >>>>>>>>>>>>>>>\n"); // } // } //Create ZG context PdContext *context = zg_new_context(0, 2, (int)block_size_actual_size, (int)samplerate_actual_value, zengardenCallback, NULL); // 0 inputs, 2 outputs, samplerate, callback, userData // Load pd patch char cp[4096]; getcwd(cp, sizeof(cp)); string current_path = string(cp); string patch_path = current_path + "/" + arg_patch_path; unsigned int i = patch_path.find_last_of("/"); string patch_file = patch_path.substr(i+1); string patch_dir = patch_path.substr(0,i+1); PdGraph *graph = zg_new_graph(context, (char*)patch_dir.c_str(), (char*)patch_file.c_str()); if (graph == NULL) { zg_delete_context(context); cout << "Could not open patch"; exit(1); } // Processing loop while(1){ zg_process(context, input, output); } //This will never run... zg_delete_context(context); free(input); free(output); exit(0); }
[ "rvega@elsoftwarehamuerto.org" ]
rvega@elsoftwarehamuerto.org
5682ffc6008ab6c7e725d6f5ed171d1f17831974
17f2db87b1fddea1691f62fb812236f247e43410
/Brick.cpp
eebb098cd278103505218bcb98ce32307035b8fd
[]
no_license
kenjinote/Breakout
81987495f609d7f8123d48b2e0a00b87e2e97c5e
0cc64f7a657b38c58adfc43cf4355f1764966391
refs/heads/master
2023-03-18T13:48:47.124539
2020-07-31T06:18:48
2020-07-31T06:18:48
524,574,705
2
0
null
2022-08-14T04:43:53
2022-08-14T04:43:53
null
UTF-8
C++
false
false
2,401
cpp
#include "framework.h" #include "Point2D.h" #include "Brick.h" #include "Ball.h" #include "Engine.h" Brick::Brick(float xPos, float yPos) : m_pGreenBrush(NULL) { position.x = xPos; position.y = yPos; health = 1; } Brick::~Brick() { SafeRelease(&m_pGreenBrush); } void Brick::Initialize(ID2D1HwndRenderTarget* m_pRenderTarget) { // Creates a blue brush for drawing m_pRenderTarget->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::Green), &m_pGreenBrush ); } void Brick::BallCollision(Ball* ball) { if (health > 0) { float brickTop = position.y - BRICK_HEIGHT / 2; float brickBottom = position.y + BRICK_HEIGHT / 2; float brickLeft = position.x - BRICK_WIDTH / 2; float brickRight = position.x + BRICK_WIDTH / 2; float ballTop = ball->position.y - 10; float ballBottom = ball->position.y + 10; float ballLeft = ball->position.x - 10; float ballRight = ball->position.x + 10; // If it's a collision if (ballTop < brickBottom && ballBottom > brickTop && ballRight > brickLeft && ballLeft < brickRight) { float distanceX1 = abs(ballRight - brickLeft); float distanceX2 = abs(ballLeft - brickRight); float distanceY1 = abs(ballTop - brickBottom); float distanceY2 = abs(ballBottom - brickTop); // From bottom if (ball->speed.y < 0 && distanceY1 < distanceY2 && distanceY1 < distanceX1 && distanceY1 < distanceX2) { ball->speed.y = abs(ball->speed.y); health = 0; } // From top if (ball->speed.y > 0 && distanceY2 < distanceY1 && distanceY2 < distanceX1 && distanceY2 < distanceX2) { ball->speed.y = -abs(ball->speed.y); health = 0; } // From left if (ball->speed.x > 0 && distanceX1 < distanceX2 && distanceX1 < distanceY1 && distanceX1 < distanceY2) { ball->speed.x = -abs(ball->speed.x); health = 0; } // From right if (ball->speed.x < 0 && distanceX2 < distanceX1 && distanceX2 < distanceY1 && distanceX2 < distanceY2) { ball->speed.x = abs(ball->speed.x); health = 0; } } } } void Brick::Draw(ID2D1HwndRenderTarget* m_pRenderTarget) { if (health > 0) { // Draws a rectangle representing the brick D2D1_RECT_F rectangle1 = D2D1::RectF( position.x - BRICK_WIDTH / 2 + 1, position.y - BRICK_HEIGHT / 2 + 1, position.x + BRICK_WIDTH / 2 - 1, position.y + BRICK_HEIGHT / 2 - 1 ); m_pRenderTarget->FillRectangle(&rectangle1, m_pGreenBrush); } }
[ "lucian.y2k@gmail.com" ]
lucian.y2k@gmail.com
7de1163059e755a9c699f46a45cbd2be7242c230
937df3b9a7db4cbc9aa45460d57b9d5b5d6fd0d9
/understandingcpp11/p2/test2_28_2.cpp
e78339ad9e67ef3c4d9f357e9c780667e1658613
[]
no_license
EucWang/cpp_primer_plus_demo
53d41e6f3b1b57b0069b95216e82b801a0f281d3
827e9ffe803b341d8e21bfb132166d9716933815
refs/heads/master
2020-04-23T06:30:53.938020
2019-06-15T07:31:06
2019-06-15T07:31:06
170,975,775
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
#include <iostream> #include "test2.h" /** * 显示的外部模板声明 */ extern template void fun<int>(int); int testp2_28(){ fun(34); std::cout << "testp2_28()" << std::endl; return 0; }
[ "qqwwdr@gmail.com" ]
qqwwdr@gmail.com