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
b57bea2cccfddfe6b9113b1c05e6a18698e54fba
5a8fcff9e4ece56a677f5edce16f55b338e5df1f
/HelperTool/libtins/include/network_interface.h
c9ee55fceb55ded8a07ff3ba56863e51f8bb2004
[]
no_license
martinhering/radiohijack
6ca61a790ddac3b1b4dc4ee72eaf2abd0991df18
233a55b98399755e623771b0ca7d238236709776
refs/heads/master
2021-01-19T15:27:39.530689
2014-05-01T08:47:10
2014-05-01T08:47:10
19,338,883
3
1
null
null
null
null
UTF-8
C++
false
false
4,441
h
/* * Copyright (c) 2012, Matias Fontanini * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR 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. * */ #ifndef TINS_NETWORK_INTERFACE_H #define TINS_NETWORK_INTERFACE_H #include <string> #include <stdint.h> #include "hw_address.h" #include "ip_address.h" namespace Tins { /** * \class NetworkInterface * \brief Abstraction of a network interface */ class NetworkInterface { public: /** * \brief The type used to store the interface's identifier. */ typedef uint32_t id_type; /** * \brief The type of this interface's address. */ typedef HWAddress<6> address_type; /** * \brief Struct that holds an interface's addresses. */ struct Info { IPv4Address ip_addr, netmask, bcast_addr; address_type hw_addr; }; /** * Returns a NetworkInterface object associated with the default * interface. */ static NetworkInterface default_interface(); /** * Default constructor. */ NetworkInterface(); /** * \brief Constructor from std::string. * * \param name The name of the interface this object will abstract. */ NetworkInterface(const std::string &name); /** * \brief Constructor from const char*. * * \param name The name of the interface this object will abstract. */ NetworkInterface(const char *name); /** * \brief Constructs a NetworkInterface from an ip address. * * This abstracted interface will be the one that would be the gateway * when sending a packet to the given ip. * * \param ip The ip address being looked up. */ NetworkInterface(IPv4Address ip); /** * \brief Getter for this interface's identifier. * * \return id_type containing the identifier. */ id_type id() const { return iface_id; } /** * \brief Retrieves this interface's name. * * \return std::string containing this interface's name. */ std::string name() const; /** * \brief Retrieve this interface's addresses. * * This method iterates through all the interface's until the * correct one is found. Therefore it's O(N), being N the amount * of interfaces in the system. */ Info addresses() const; /** * \brief Tests whether this is a valid interface; * * An interface will not be valid iff it was created using the * default constructor. */ operator bool() const { return iface_id != 0; } /** * \brief Compares this interface for equality. * * \param rhs The interface being compared. */ bool operator==(const NetworkInterface &rhs) const { return iface_id == rhs.iface_id; } /** * \brief Compares this interface for inequality. * * \param rhs The interface being compared. */ bool operator!=(const NetworkInterface &rhs) const { return !(*this == rhs); } private: id_type resolve_index(const char *name); id_type iface_id; }; } #endif // TINS_NETWORK_INTERFACE_H
[ "hering@vemedio.com" ]
hering@vemedio.com
206daa69c42205c1a4f9e321b8c28dfa31048b31
e77bb7afc612666f1b8d65a0039a32f737b4f209
/components/viz/service/display_embedder/skia_output_device.h
c8bcc7b26acb2167b12367d9086d8e0905fab60b
[ "BSD-3-Clause" ]
permissive
lvyeshufang/chromium
76f6b227ac100f0c75305252a9ffc45820da70de
49f84636734485b99303ed44a18bc09a39efabe2
refs/heads/master
2022-08-22T02:35:00.231811
2019-07-09T11:24:00
2019-07-09T11:24:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,244
h
// 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. #ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_H_ #include "base/callback.h" #include "base/macros.h" #include "base/optional.h" #include "components/viz/service/display/output_surface.h" #include "gpu/command_buffer/common/swap_buffers_complete_params.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/src/gpu/GrSemaphore.h" #include "ui/gfx/swap_result.h" class SkSurface; namespace gfx { class ColorSpace; class Rect; class Size; struct PresentationFeedback; } // namespace gfx namespace viz { class SkiaOutputDevice { public: // A helper class for defining a BeginPaint() and EndPaint() scope. class ScopedPaint { public: explicit ScopedPaint(SkiaOutputDevice* device) : device_(device), sk_surface_(device->BeginPaint()) { DCHECK(sk_surface_); } ~ScopedPaint() { device_->EndPaint(semaphore_); } SkSurface* sk_surface() const { return sk_surface_; } void set_semaphore(const GrBackendSemaphore& semaphore) { DCHECK(!semaphore_.isInitialized()); semaphore_ = semaphore; } private: SkiaOutputDevice* const device_; SkSurface* const sk_surface_; GrBackendSemaphore semaphore_; DISALLOW_COPY_AND_ASSIGN(ScopedPaint); }; using BufferPresentedCallback = base::OnceCallback<void(const gfx::PresentationFeedback& feedback)>; using DidSwapBufferCompleteCallback = base::RepeatingCallback<void(gpu::SwapBuffersCompleteParams, const gfx::Size& pixel_size)>; SkiaOutputDevice( bool need_swap_semaphore, DidSwapBufferCompleteCallback did_swap_buffer_complete_callback); virtual ~SkiaOutputDevice(); // Changes the size of draw surface and invalidates it's contents. virtual void Reshape(const gfx::Size& size, float device_scale_factor, const gfx::ColorSpace& color_space, bool has_alpha, gfx::OverlayTransform transform) = 0; // Presents the back buffer. virtual gfx::SwapResponse SwapBuffers(BufferPresentedCallback feedback) = 0; virtual gfx::SwapResponse PostSubBuffer(const gfx::Rect& rect, BufferPresentedCallback feedback); // Set the rectangle that will be drawn into on the surface. virtual void SetDrawRectangle(const gfx::Rect& draw_rectangle); const OutputSurface::Capabilities& capabilities() const { return capabilities_; } // EnsureBackbuffer called when output surface is visible and may be drawn to. // DiscardBackbuffer called when output surface is hidden and will not be // drawn to. Default no-op. virtual void EnsureBackbuffer(); virtual void DiscardBackbuffer(); bool need_swap_semaphore() const { return need_swap_semaphore_; } protected: // Begin paint the back buffer. virtual SkSurface* BeginPaint() = 0; // End paint the back buffer. virtual void EndPaint(const GrBackendSemaphore& semaphore) = 0; // Helper method for SwapBuffers() and PostSubBuffer(). It should be called // at the beginning of SwapBuffers() and PostSubBuffer() implementations void StartSwapBuffers(base::Optional<BufferPresentedCallback> feedback); // Helper method for SwapBuffers() and PostSubBuffer(). It should be called // at the end of SwapBuffers() and PostSubBuffer() implementations gfx::SwapResponse FinishSwapBuffers(gfx::SwapResult result, const gfx::Size& size); OutputSurface::Capabilities capabilities_; const bool need_swap_semaphore_; uint64_t swap_id_ = 0; DidSwapBufferCompleteCallback did_swap_buffer_complete_callback_; // Only valid between StartSwapBuffers and FinishSwapBuffers. base::Optional<BufferPresentedCallback> feedback_; base::Optional<gpu::SwapBuffersCompleteParams> params_; DISALLOW_COPY_AND_ASSIGN(SkiaOutputDevice); }; } // namespace viz #endif // COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_DEVICE_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
47c5300782c1c559545522bc2bf8cb3aa37c88d9
f5524a0e68536f703871fc1d9bd2b3acfefc8090
/JumpTrading/Order.h
5c4c29f722653fc24b891a21d0a5ba7320e431d7
[]
no_license
mganesh/code
ee014845b38e946fe7aa21853aca100a1d25f4a8
5a74b51c2763f3a7d8796bcdcceab1cdd637ca95
refs/heads/master
2021-01-17T17:00:06.590324
2014-01-23T15:22:11
2014-01-23T15:22:11
1,059,351
0
0
null
null
null
null
UTF-8
C++
false
false
1,324
h
// // Order.h // ExchangeFeed // // #ifndef ExchangeFeed_Order_h #define ExchangeFeed_Order_h #include <stdint.h> #include <string> namespace feed { class Order { public: enum Side { BUY = 1, SELL = 2 }; Order(uint64_t orderId, Side side, uint64_t quantity, double price); ~Order(); uint64_t getOrderId() { return m_orderId;} Side getSide() const { return m_side; } double getPrice() const { return m_price; } uint64_t getQuantity() const { return m_quantity; } bool isOpen() { return m_openQuantity > 0; } void setPrice(double price) { m_price = price; } void setQuantity(uint64_t quantity); void setOpenQuantity(uint64_t openQuantity) { m_openQuantity = openQuantity; } void fill(double price, uint64_t quantity); double lastExecutedPrice() { return m_lastExecutedPrice; } uint64_t lastExecutedQuantity() { return m_lastExecutedQuantity; } uint64_t getOpenQuantity() { return m_openQuantity; } uint64_t getExecutedQty() { return m_executedQuantity; } private: uint64_t m_orderId; Side m_side; uint64_t m_quantity; double m_price; double m_lastExecutedPrice; uint64_t m_openQuantity; uint64_t m_lastExecutedQuantity; uint64_t m_executedQuantity; }; } #endif
[ "ganesh.muniyandi@gmail.com" ]
ganesh.muniyandi@gmail.com
7160ff685a62260b9bf78f0139f37f7f8e814383
084b38da37754392fae375c43d593be1c8b22bb7
/bailian/4107.cpp
a70c14d31b630f53c3d0d8c0b05a6903fb524256
[]
no_license
heliy/oj
1b0c65f02f94ffb5c1ce44a95bc07144505fc141
4c5f97f30997f285e321b0ece53e85595bc641ff
refs/heads/master
2021-01-25T06:36:37.454934
2016-01-14T13:42:21
2016-01-14T13:42:21
28,627,519
2
1
null
null
null
null
UTF-8
C++
false
false
374
cpp
#include<iostream> using namespace std; bool isinclude(int p){ while(p > 10){ if(p%100 == 19){ return true; } p /= 10; } return false; } int main(){ int n, ni, p; cin >> n; for(ni = 0; ni < n; ni++){ cin >> p; if(p%19 == 0 || isinclude(p)){ cout << "Yes" << endl; }else{ cout << "No" << endl; } } return 0; }
[ "ohhlyhly@gmail.com" ]
ohhlyhly@gmail.com
3111c81f82b06d42ab86f07b34c1be1c980bd8f7
1aaeaeaf042529cb0e5b551cde992c91e501e46c
/lab1/src/presenter.cpp
04c12a4e39469c3072eec53e9a1fe40cd1a8787d
[]
no_license
Kazeshirou/ppo
17c3371de5a2f9d06a1a6cedd738b98fa52d0576
b857fb8ba6b6cf712e4b365911ace4d7f814a1dc
refs/heads/master
2020-03-09T06:03:02.540815
2018-05-31T13:51:57
2018-05-31T13:51:57
128,628,825
0
0
null
null
null
null
UTF-8
C++
false
false
4,385
cpp
#include "presenter.h" #include "model.h" #include "mainwindow.h" Presenter::Presenter(Model *model, MainWindow *view, QObject *parent) : QObject(parent), m_model(model), m_view(view) { if (!model) m_model = new Model(this); if (!view) m_view = new MainWindow(); m_view->show(); connect(m_view, SIGNAL(s_fromFile(QStringList)), this, SLOT(addRoutesFromFile(QStringList))); connect(m_view, SIGNAL(s_fromPolyline(QString)), this, SLOT(addRouteFromPolyline(QString))); connect(m_view, SIGNAL(s_insertRoute(int)), this, SLOT(createRoute(int))); connect(m_view, SIGNAL(s_deleteRoute(int)), this, SLOT(removeRoute(int))); connect(m_view, SIGNAL(s_insertCoordinate(int, int)), this, SLOT(createCoordinate(int, int))); connect(m_view, SIGNAL(s_deleteCoordinate(int, int)), this, SLOT(removeCoordinate(int, int))); connect(m_view, SIGNAL(s_changeCurrentRoute(int)), this, SLOT(routeChanged(int))); connect(m_view, SIGNAL(s_changeRoute(int, QString)), this, SLOT(editRouteName(int, QString))); connect(m_view, SIGNAL(s_changeCoordinate(int, int, int, double)), this, SLOT(editCoordinate(int, int, int, double))); connect(m_view, SIGNAL(s_redo()), this, SLOT(redo())); connect(m_view, SIGNAL(s_undo()), this, SLOT(undo())); connect(m_model, SIGNAL(s_routeCreated(GeoRoute, int)), this, SLOT(insertRoute(GeoRoute, int))); connect(m_model, SIGNAL(s_routeRemoved(int)), this, SLOT(deleteRoute(int))); connect(m_model, SIGNAL(s_coordinateCreated(QGeoCoordinate, int, int)), this, SLOT(insertCoordinate(QGeoCoordinate, int, int))); connect(m_model, SIGNAL(s_coordinateRemoved(int, int)), this, SLOT(deleteCoordinate(int, int))); connect(m_model, SIGNAL(s_polylineChanged(QString)), this, SLOT(changePolyline(QString))); connect(m_model, SIGNAL(s_chartChanged(QLineSeries*)), this, SLOT(changeChart(QLineSeries*))); connect(m_model, SIGNAL(s_nameChanged(QString, int)), this, SLOT(changeRouteName(QString, int))); connect(m_model, SIGNAL(s_coordinateChanged(double, int, int, int)), this, SLOT(changeCoordinate(double, int, int, int))); connect(m_model, SIGNAL(s_lengthChanged(int, double)), this, SLOT(changeRouteLength(int, double))); m_model->loadFromSave(); } void Presenter::addRoutesFromFile(const QStringList files) { if (files.length()) m_model->addRoutesFromFiles(files); } void Presenter::addRouteFromPolyline(const QString polyline) { if (polyline.length()) m_model->addRouteFromPolyline(polyline); } void Presenter::createRoute(int index) { m_model->createRoute(index, GeoRoute()); } void Presenter::createCoordinate(int route, int index) { m_model->createCoordinate(route, index); } void Presenter::removeCoordinate(int route, int index) { m_model->removeCoordinate(route, index); } void Presenter::removeRoute(int index) { m_model->removeRoute(index); } void Presenter::editRouteName(int index, QString name) { m_model->editRouteName(index, name); } void Presenter::editCoordinate(int route, int index, int column, double newvalue) { m_model->editCoordinate(route, index, column, newvalue); } void Presenter::insertRoute(const GeoRoute route, int index) { m_view->insertRoute(route, index); } void Presenter::deleteRoute(int index) { m_view->deleteRoute(index); } void Presenter::insertCoordinate(const QGeoCoordinate coordinate, int route, int index) { m_view->insertCoordinate(coordinate, route, index); } void Presenter::deleteCoordinate(int route, int index) { m_view->deleteCoordinate(route, index); } void Presenter::changePolyline(QString s) { m_view->changePolyline(s); } void Presenter::changeChart(QLineSeries *s) { m_view->changeChart(s); } void Presenter::changeRouteLength(int index, double l) { m_view->changeRouteLength(index, l); } void Presenter::routeChanged(int route) { changePolyline(m_model->getPolyline(route)); QLineSeries *s = m_model->createSeries(route); changeChart(s); } void Presenter::changeRouteName(QString newname, int index) { m_view->changeRoute(index, newname); } void Presenter::changeCoordinate(double newvalue, int route, int index, int column) { m_view->changeCoordinate(route, index, column, newvalue); } void Presenter::redo() { m_model->redo(); } void Presenter::undo() { m_model->undo(); }
[ "zhar97@yandex.ru" ]
zhar97@yandex.ru
bf270dbf81b8d364192d9c5fda36d617255ffe4e
8bc4f1bc2144c0e5711baf47783541c9a4ac1e5e
/goldIngot_codevita_9.cpp
fa4e8df12ddc79fa006f80a379546d070a300717
[]
no_license
1337w0rm/BVEC-Hacktoberfest-2020
09df549175471e7c92d7eebc837402822d51af6e
5759759edf0b86bba2612b5c29594d6f27031645
refs/heads/master
2023-01-07T02:23:15.681254
2020-10-22T11:34:07
2020-10-22T11:34:07
300,498,799
2
20
null
2020-10-22T11:34:08
2020-10-02T04:20:06
HTML
UTF-8
C++
false
false
901
cpp
#include <bits/stdc++.h> #include <math.h> using namespace std; int main(){ int i,g,b,h; cin>>g; int l[g]; cin>>b>>h; for(i=0;i<g;i++){ cin>>l[i]; } int totVol=0; for(i=0;i<g;i++){ totVol+=l[i]*b*h; } int cal, maxl; cal=maxl=0; stack<int> s; for (int i=0;i<g;i++) { while(!s.empty() && l[i]<=l[s.top()]) { int n = s.top(); s.pop(); if(s.empty()){ cal = l[n] * i; } else{ cal = l[n] * (i-s.top()-1); } if(cal>maxl){ maxl=cal; } } s.push(i); } while (!s.empty()){ int n = s.top(); s.pop(); if(s.empty()){ cal = l[n]*g; } else{ cal = l[n]*(g-s.top()-1); } if(cal>maxl){ maxl=cal; } } int ingotVol; ingotVol=maxl*b*h; int mod = pow(10,9) + 7; cout << (totVol-ingotVol) % mod ; return 0; }
[ "49098410+rishavjyoti@users.noreply.github.com" ]
49098410+rishavjyoti@users.noreply.github.com
4eeab07582975edb8042b0572d917390954228af
521cd380cc7d29c7f023966aef757dd9f3353692
/problems/3sum/app.cpp
386c2c03cf7c35cb2b7b008b4765339e6149260b
[]
no_license
anhdeev/algorithms
2159eab5b1b40c7aa276789b78dab45c71e15694
0fa25423ea3cf161f9a767da7cb03366d61195ad
refs/heads/master
2023-08-24T12:09:31.932349
2021-10-26T07:01:18
2021-10-26T07:01:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,606
cpp
#include "../common/base.h" class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { map<int, int> cache; vector< vector<int> > result; sort(nums.begin(), nums.end()); for(auto &num: nums) { if(cache.count(num)==0) cache[num] = 0; cache[num] += 1; cout << num << "=" << cache[num] << endl; } int lastj = 100001, lasti=100001; for(int i=0;i<nums.size();++i) { if(nums[i]==lasti) continue; else lasti=nums[i]; for(int j=i+1;j<nums.size();++j) { int sum2 = -(nums[i] +nums[j]); vector<int> v = {nums[i], nums[j], sum2}; if(nums[j]==lastj) continue; else lastj=nums[j]; if(sum2 == nums[j]) { if(cache[sum2] < 1) continue; else if(nums[i]!=nums[j] && cache[sum2] > 1) result.push_back(v); else if(nums[i]==nums[j] && cache[sum2]>2) result.push_back(v); else continue; } else if (sum2 < nums[j]) { continue; } else if(cache[sum2] > 0) { result.push_back(v); } } } return result; } }; int main() { Solution solution; vector<int> nums = {0,0}; vector< vector <int> > result = solution.threeSum(nums); for(auto v:result) { for(auto item: v) { cout << item << ","; } cout << endl; } return 0; }
[ "anhdv@merchize.com" ]
anhdv@merchize.com
af872a4462d3068500a39a5af14279c8ccc3f518
4f2174ffe63cbd3b4e8daca465e6c62c6a8fd9b8
/Problem-22/Problem-22.cpp
4f1dadb8ad736374e8dba85a07985dbb5c6da1c1
[]
no_license
DHRUV-EDDI/DailyCodingProblem
5e680bcd4c00698e91d55955ecf087302214e3dc
82410cb245f4d4d5a50bc02a939f1286ca6ceb6e
refs/heads/master
2022-12-10T12:33:52.706714
2020-08-23T07:33:38
2020-08-23T07:33:38
260,503,585
0
0
null
null
null
null
UTF-8
C++
false
false
2,751
cpp
#include<bits/stdc++.h> using namespace std; using ll = long long; typedef struct Node { struct Node *leftChild,*Parent,*rightChild; bool isLocked; ll val,lockedDescendants; }Node; Node *root=NULL; map<ll,Node*> mp; Node* insert(ll val) { Node *n = new Node; n -> leftChild = n -> Parent = n -> rightChild = NULL; n -> isLocked = false; n -> val = val; if(root == NULL) { n -> lockedDescendants = 0; root = n; mp[val] = root; return root; } queue<Node*> q; q.push(root); while(!q.empty()) { Node *temp = q.front(); q.pop(); if(temp -> leftChild == NULL) { n -> Parent = temp; temp -> leftChild = n; n -> lockedDescendants = 0; mp[val] = n; break; } else q.push(temp -> leftChild); if(temp -> rightChild == NULL) { n -> Parent = temp; temp -> rightChild = n; n -> lockedDescendants = 0; mp[val] = n; break; } else q.push(temp -> rightChild); } return root; } bool isLocked(Node *t) { return t -> isLocked; } void inorder(Node *t) { if(t && !isLocked(t)) { inorder(t -> leftChild); cout<<t -> val<<" "; inorder(t -> rightChild); } } bool canUnlockorLock(Node *n) { if(n -> lockedDescendants > 0) return false; Node *temp = n -> Parent; while(temp) { if(temp -> isLocked) return false; temp = temp -> Parent; } return true; } bool Lock(Node *n) { if(!isLocked(n) && canUnlockorLock(n)) { Node *cur = n -> Parent; while(cur) { cur -> lockedDescendants ++; cur = cur -> Parent; } n -> isLocked = true; return true; } return false; } bool Unlock(Node *n) { if(n && isLocked(n) && canUnlockorLock(n)) { Node *cur = n -> Parent; while(cur) { cur -> lockedDescendants--; cur = cur -> Parent; } n -> isLocked = false; return true; } return false; } int main() { ll n; cin>>n; for(int i=0;i<n;i++) { ll val; cin >> val; root = insert(val); } ll lockQueries,unlockQueries; cin >> lockQueries >> unlockQueries; while(lockQueries--) { ll lockVal; cin>> lockVal; Lock((Node*)mp[lockVal]); } inorder(root); cout<<"\n"; while(unlockQueries--) { ll unlockVal; cin >> unlockVal; Unlock((Node*)mp[unlockVal]); } inorder(root); return 0; }
[ "dhruv2018570@gmail.com" ]
dhruv2018570@gmail.com
a2ccba07802617d15b76857a5826a5c6f3648cdb
c2ad7cb821e98babe6aebf1103ad5b71e6e3940c
/Framework/Common/BaseApplication.hpp
7c7244b672e525be6694e05259efe3148fe40220
[]
no_license
wunianqing/GameEngineLearn
2ae4bcc474a1d242dd25c195011bd7f1cbbccaf5
feb8f1508da417aacd95d909753ccc24c4c55868
refs/heads/master
2022-11-07T11:43:02.811467
2020-06-19T07:08:03
2020-06-19T07:08:03
273,429,554
0
0
null
null
null
null
UTF-8
C++
false
false
311
hpp
#pragma once #include "IApplication.hpp" namespace E { class BaseApplication: implements IApplication { public: virtual int Initialize(); virtual void Finalize(); virtual void Tick(); virtual bool IsQuit(); private: bool m_bQuit; }; } // namespace E
[ "wunianqing@outlook.com" ]
wunianqing@outlook.com
793924f54678062210743cb951bde173227436b6
7e8a447adcf729b84027790eb40aff46aa5002f4
/hlogicprop.cpp
a7460756ccf806e2f92b04fca47bfc74f9b5a90e
[]
no_license
rcswhuang/rule
de6abad08268a140ec1714092ed3d77f9a818459
27b98cdb05d4b7536dc49be5e5e0921cb1eac132
refs/heads/master
2021-06-05T13:43:43.672386
2018-10-14T13:33:11
2018-10-14T13:33:11
95,844,043
0
0
null
null
null
null
UTF-8
C++
false
false
1,029
cpp
#include "hlogicprop.h" #include "ui_logicprop.h" #include "hdrawobj.h" HLogicProp::HLogicProp(HDrawObj* drawObj,QWidget *parent) : m_pDrawObj(drawObj),QDialog(parent), ui(new Ui::HLogicProp) { ui->setupUi(this); connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(ok_clicked())); initLogicProp(); } HLogicProp::~HLogicProp() { delete ui; } void HLogicProp::initLogicProp() { for(int i = 2; i <=30;i++) { QString strInput = QString("输入%1").arg(i); ui->comboBox->addItem(strInput,i); } int nInputSum = m_pDrawObj->m_nInPointSum; ui->comboBox->setCurrentIndex(ui->comboBox->findData(nInputSum)); } void HLogicProp::ok_clicked() { int nSum = ui->comboBox->currentData().toInt(); if(nSum == m_pDrawObj->m_nInPointSum) return; int oneh = m_pDrawObj->m_pointIn[1].y() - m_pDrawObj->m_pointIn[0].y(); m_pDrawObj->m_rectCurPos.setBottom(m_pDrawObj->m_rectCurPos.top() + oneh*(nSum+4)); m_pDrawObj->m_nInPointSum = nSum; QDialog::accept(); }
[ "rcswhuang@163.com" ]
rcswhuang@163.com
5db154d54c27d2abf6e3d3062a4fdbec1a1f79dc
60a2ce8ae0f155dedea181a76da169947508078b
/dprojectmanager/dmakestep.cpp
ddadfa846661827fbe744fdefaaf349ac3e53d7b
[]
no_license
RomulT/QtCreatorD
cc37724f386c8dff4dcfee1eb52843c2afea6a9f
eb2c8dfa4b31af731fdf848f550d5c3f824b3b41
refs/heads/master
2021-01-21T01:11:13.391350
2013-11-29T00:44:29
2013-11-29T00:44:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,481
cpp
#include "dmakestep.h" #include "dprojectmanagerconstants.h" #include "dproject.h" #include "ui_dmakestep.h" #include "dbuildconfiguration.h" #include "drunconfiguration.h" #include <extensionsystem/pluginmanager.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/gnumakeparser.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/toolchain.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtparser.h> #include <coreplugin/variablemanager.h> #include <utils/stringutils.h> #include <utils/qtcassert.h> #include <utils/qtcprocess.h> #include <QSettings> using namespace Core; using namespace ProjectExplorer; using namespace DProjectManager; namespace DProjectManager { namespace Internal { DMakeStep::DMakeStep(BuildStepList *parent) : AbstractProcessStep(parent, Id(Constants::D_MS_ID)), m_targetType(Executable), m_buildPreset(Debug) { ctor(); } DMakeStep::DMakeStep(BuildStepList *parent, const Id id) : AbstractProcessStep(parent, id), m_targetType(Executable), m_buildPreset(Debug) { ctor(); } DMakeStep::DMakeStep(BuildStepList *parent, DMakeStep *bs) : AbstractProcessStep(parent, bs), m_targetType(bs->m_targetType), m_buildPreset(bs->m_buildPreset), m_makeArguments(bs->m_makeArguments), m_targetName(bs->m_targetName), m_targetDirName(bs->m_targetDirName), m_objDirName(bs->m_objDirName) { ctor(); } void DMakeStep::ctor() { setDefaultDisplayName(QCoreApplication::translate("DProjectManager::Internal::DMakeStep", Constants::D_MS_DISPLAY_NAME)); if(m_targetName.length() == 0) m_targetName = project()->displayName(); QString bname = this->buildConfiguration()->displayName().toLower(); QString sep(QDir::separator()); if(m_targetDirName.length() == 0) m_targetDirName = QLatin1String("bin") + sep + bname; if(m_objDirName.length() == 0) m_objDirName = QLatin1String("obj") + sep + bname; if(m_makeArguments.length() == 0) { ProjectExplorer::Abi abi = ProjectExplorer::Abi::hostAbi(); if(abi.wordWidth() == 64) m_makeArguments = QLatin1String("-m64"); } } DMakeStep::~DMakeStep() { } bool DMakeStep::init() { BuildConfiguration *bc = buildConfiguration(); if (!bc) bc = target()->activeBuildConfiguration(); m_tasks.clear(); ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit()); if (!tc) { m_tasks.append(Task(Task::Error, tr("Qt Creator needs a compiler set up to build. Configure a compiler in the kit options."), Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM))); return true; // otherwise the tasks will not get reported } ProcessParameters *pp = processParameters(); pp->setMacroExpander(bc->macroExpander()); pp->setWorkingDirectory(bc->buildDirectory().toString()); Utils::Environment env = bc->environment(); // Force output to english for the parsers. Do this here and not in the toolchain's // addToEnvironment() to not screw up the users run environment. env.set(QLatin1String("LC_ALL"), QLatin1String("C")); pp->setEnvironment(env); pp->setCommand(makeCommand(bc->environment())); pp->setArguments(allArguments()); pp->resolveAll(); setOutputParser(new GnuMakeParser()); IOutputParser *parser = target()->kit()->createOutputParser(); if (parser) appendOutputParser(parser); outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory()); return AbstractProcessStep::init(); } QVariantMap DMakeStep::toMap() const { QVariantMap map = AbstractProcessStep::toMap(); map.insert(QLatin1String(Constants::INI_TARGET_TYPE_KEY), m_targetType); map.insert(QLatin1String(Constants::INI_BUILD_PRESET_KEY), m_buildPreset); map.insert(QLatin1String(Constants::INI_TARGET_NAME_KEY), m_targetName); map.insert(QLatin1String(Constants::INI_TARGET_DIRNAME_KEY), m_targetDirName); map.insert(QLatin1String(Constants::INI_OBJ_DIRNAME_KEY), m_objDirName); map.insert(QLatin1String(Constants::INI_MAKE_ARGUMENTS_KEY), m_makeArguments); return map; } bool DMakeStep::fromMap(const QVariantMap &map) { m_targetType = (TargetType)map.value(QLatin1String(Constants::INI_TARGET_TYPE_KEY)).toInt(); m_buildPreset = (BuildPreset)map.value(QLatin1String(Constants::INI_BUILD_PRESET_KEY)).toInt(); m_targetName = map.value(QLatin1String(Constants::INI_TARGET_NAME_KEY)).toString(); m_targetDirName = map.value(QLatin1String(Constants::INI_TARGET_DIRNAME_KEY)).toString(); m_objDirName = map.value(QLatin1String(Constants::INI_OBJ_DIRNAME_KEY)).toString(); m_makeArguments = map.value(QLatin1String(Constants::INI_MAKE_ARGUMENTS_KEY)).toString(); return BuildStep::fromMap(map); } QString DMakeStep::makeCommand(const Utils::Environment &environment) const { ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit()); if (tc) return tc->makeCommand(environment); else return QLatin1String("dmd"); } QString DMakeStep::allArguments() const { QString bname = this->buildConfiguration()->displayName().toLower(); QString args; if(m_buildPreset == Debug) args += QLatin1String("-debug -gc"); else if(m_buildPreset == Unittest) args += QLatin1String("-debug -gc -unittest"); else if(m_buildPreset == Release) args += QLatin1String(" -release -O -inline"); if(m_targetType == StaticLibrary) args += QLatin1String(" -lib"); else if(m_targetType == SharedLibrary) args += QLatin1String(" -shared -fPIC"); QDir buildDir(this->buildConfiguration()->buildDirectory().toString()); QString projDir = project()->projectDirectory(); QString relTargetDir = m_targetDirName; if(QDir(m_targetDirName).isRelative()) relTargetDir = buildDir.relativeFilePath(projDir + QDir::separator() + m_targetDirName); if(relTargetDir.length() == 0) relTargetDir = QLatin1String("."); QString outFile = outFileName(); QString makargs = m_makeArguments; makargs.replace(QLatin1String("%{TargetDir}"),relTargetDir); Utils::QtcProcess::addArgs(&args, makargs); Utils::QtcProcess::addArgs(&args, QLatin1String("-of") + relTargetDir + QDir::separator() + outFile); if(QDir(m_objDirName).isRelative()) { QString relDir = buildDir.relativeFilePath(projDir + QDir::separator() + m_objDirName); if(relDir.length() > 0) Utils::QtcProcess::addArgs(&args, QLatin1String("-od") + relDir); } DProject* proj = static_cast<DProject*>(project()); // Libs QStringList libs = proj->libraries().split(QLatin1Char(' '), QString::SkipEmptyParts); foreach(QString s, libs) { s = s.replace(QLatin1String("%{TargetDir}"),relTargetDir); if(s.startsWith(QLatin1String("-L"))) Utils::QtcProcess::addArgs(&args, s); else Utils::QtcProcess::addArgs(&args, QLatin1String("-L-l") + s); } // Includes QStringList incs = proj->includes().split(QLatin1Char(' '), QString::SkipEmptyParts); foreach(QString s, incs) { s = s.replace(QLatin1String("%{TargetDir}"),relTargetDir); if(s.startsWith(QLatin1String("-I"))) Utils::QtcProcess::addArgs(&args, s); else Utils::QtcProcess::addArgs(&args, QLatin1String("-I") + s); } // Extra Args makargs = proj->extraArgs(); Utils::QtcProcess::addArgs(&args, makargs.replace(QLatin1String("%{TargetDir}"),relTargetDir)); // Files static QLatin1String dotd(".d"); static QLatin1String dotdi(".di"); static QLatin1String space(" "); QString srcs = QLatin1String(" "); const QHash<QString,QString>& files = static_cast<DProject*>(project())->files(); foreach(QString file, files.values()) if(file.endsWith(dotd) || file.endsWith(dotdi)) srcs.append(file).append(space); Utils::QtcProcess::addArgs(&args, srcs); return args; } QString DMakeStep::outFileName() const { QString outName = m_targetName; if(m_targetType > 0) { QString fix = QLatin1String("lib"); if(outName.startsWith(fix) == false) outName = fix + outName; if(m_targetType == StaticLibrary) fix = QLatin1String(".a"); else if(m_targetType == SharedLibrary) fix = QLatin1String(".so"); if(outName.endsWith(fix) == false) outName.append(fix); } return outName; } void DMakeStep::run(QFutureInterface<bool> &fi) { bool canContinue = true; foreach (const Task &t, m_tasks) { addTask(t); canContinue = false; } if (!canContinue) { emit addOutput(tr("Configuration is faulty. Check the Issues view for details."), BuildStep::MessageOutput); fi.reportResult(false); emit finished(); return; } //processParameters()->setWorkingDirectory(project()->projectDirectory()); AbstractProcessStep::run(fi); } void DMakeStep::stdError(const QString &line) { QString res = line; try { QProcess proc; proc.setProcessChannelMode(QProcess::MergedChannels); proc.start(QLatin1String("ddemangle")); if (!proc.waitForStarted(10000)) return; proc.write(line.toUtf8()); proc.closeWriteChannel(); if(!proc.waitForFinished(2000)) { proc.close(); return; } else if(proc.exitCode() != 0) { proc.close(); return; } else { res = QString::fromUtf8(proc.readAllStandardOutput()); proc.close(); } } catch(...){} AbstractProcessStep::stdError(res); } BuildStepConfigWidget *DMakeStep::createConfigWidget() { return new DMakeStepConfigWidget(this); } bool DMakeStep::immutable() const { return false; } //------------------------------------------------------------------------- //-- DMakeStepConfigWidget //------------------------------------------------------------------------- DMakeStepConfigWidget::DMakeStepConfigWidget(DMakeStep *makeStep) : m_makeStep(makeStep) { Project *pro = m_makeStep->target()->project(); m_ui = new Ui::DMakeStep; m_ui->setupUi(this); m_ui->targetTypeComboBox->addItem(QLatin1String("Executable")); m_ui->targetTypeComboBox->addItem(QLatin1String("Static Library")); m_ui->targetTypeComboBox->addItem(QLatin1String("Shared Library")); m_ui->buildPresetComboBox->addItem(QLatin1String("Debug")); m_ui->buildPresetComboBox->addItem(QLatin1String("Release")); m_ui->buildPresetComboBox->addItem(QLatin1String("Unittest")); m_ui->buildPresetComboBox->addItem(QLatin1String("None")); m_ui->targetTypeComboBox->setCurrentIndex((int)m_makeStep->m_targetType); m_ui->buildPresetComboBox->setCurrentIndex((int)m_makeStep->m_buildPreset); m_ui->makeArgumentsLineEdit->setPlainText(m_makeStep->m_makeArguments); m_ui->targetNameLineEdit->setText(m_makeStep->m_targetName); m_ui->targetDirLineEdit->setText(m_makeStep->m_targetDirName); m_ui->objDirLineEdit->setText(m_makeStep->m_objDirName); updateDetails(); connect(m_ui->targetTypeComboBox, SIGNAL(currentIndexChanged (int)), this, SLOT(targetTypeComboBoxSelectItem(int))); connect(m_ui->buildPresetComboBox, SIGNAL(currentIndexChanged (int)), this, SLOT(buildPresetComboBoxSelectItem(int))); connect(m_ui->targetNameLineEdit, SIGNAL(textEdited(QString)), this, SLOT(targetNameLineEditTextEdited())); connect(m_ui->targetDirLineEdit, SIGNAL(textEdited(QString)), this, SLOT(targetDirNameLineEditTextEdited())); connect(m_ui->objDirLineEdit, SIGNAL(textEdited(QString)), this, SLOT(objDirLineEditTextEdited())); connect(m_ui->makeArgumentsLineEdit, SIGNAL(textChanged()), this, SLOT(makeArgumentsLineEditTextEdited())); connect(ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()), this, SLOT(updateDetails())); connect(pro, SIGNAL(environmentChanged()), this, SLOT(updateDetails())); connect(m_makeStep->buildConfiguration(), SIGNAL(buildDirectoryChanged()), this, SLOT(updateDetails())); connect(m_makeStep->buildConfiguration(), SIGNAL(configurationChanged()), this, SLOT(updateDetails())); } DMakeStepConfigWidget::~DMakeStepConfigWidget() { delete m_ui; } QString DMakeStepConfigWidget::displayName() const { return tr("Make", "D Makestep"); } void DMakeStepConfigWidget::updateDetails() { BuildConfiguration *bc = m_makeStep->buildConfiguration(); if (!bc) bc = m_makeStep->target()->activeBuildConfiguration(); ProcessParameters param; param.setMacroExpander(bc->macroExpander()); param.setWorkingDirectory(bc->buildDirectory().toString()); param.setEnvironment(bc->environment()); param.setCommand(m_makeStep->makeCommand(bc->environment())); param.setArguments(m_makeStep->allArguments()); m_summaryText = param.summary(displayName()); emit updateSummary(); foreach(RunConfiguration* rc, m_makeStep->target()->runConfigurations()) { DRunConfiguration * brc = dynamic_cast<DRunConfiguration *>(rc); if(brc) brc->updateConfig(m_makeStep); } } QString DMakeStepConfigWidget::summaryText() const { return m_summaryText; } void DMakeStepConfigWidget::targetTypeComboBoxSelectItem(int index) { m_makeStep->m_targetType = (DMakeStep::TargetType)index; updateDetails(); } void DMakeStepConfigWidget::buildPresetComboBoxSelectItem(int index) { m_makeStep->m_buildPreset = (DMakeStep::BuildPreset)index; updateDetails(); } void DMakeStepConfigWidget::makeArgumentsLineEditTextEdited() { m_makeStep->m_makeArguments = m_ui->makeArgumentsLineEdit->toPlainText(); updateDetails(); } void DMakeStepConfigWidget::targetNameLineEditTextEdited() { m_makeStep->m_targetName = m_ui->targetNameLineEdit->text(); updateDetails(); } void DMakeStepConfigWidget::targetDirNameLineEditTextEdited() { m_makeStep->m_targetDirName = m_ui->targetDirLineEdit->text(); updateDetails(); } void DMakeStepConfigWidget::objDirLineEditTextEdited() { m_makeStep->m_objDirName = m_ui->objDirLineEdit->text(); updateDetails(); } //-------------------------------------------------------------------------- //-- DMakeStepFactory //-------------------------------------------------------------------------- DMakeStepFactory::DMakeStepFactory(QObject *parent) : IBuildStepFactory(parent) { } bool DMakeStepFactory::canCreate(BuildStepList *parent, const Id id) const { if (parent->target()->project()->id() == Constants::DPROJECT_ID) return id == Constants::D_MS_ID; return false; } BuildStep *DMakeStepFactory::create(BuildStepList *parent, const Id id) { if (!canCreate(parent, id)) return 0; DMakeStep *step = new DMakeStep(parent); return step; } bool DMakeStepFactory::canClone(BuildStepList *parent, BuildStep *source) const { return canCreate(parent, source->id()); } BuildStep *DMakeStepFactory::clone(BuildStepList *parent, BuildStep *source) { if (!canClone(parent, source)) return 0; DMakeStep *old(qobject_cast<DMakeStep *>(source)); Q_ASSERT(old); return new DMakeStep(parent, old); } bool DMakeStepFactory::canRestore(BuildStepList *parent, const QVariantMap &map) const { return canCreate(parent, idFromMap(map)); } BuildStep *DMakeStepFactory::restore(BuildStepList *parent, const QVariantMap &map) { if (!canRestore(parent, map)) return 0; DMakeStep *bs(new DMakeStep(parent)); if (bs->fromMap(map)) return bs; delete bs; return 0; } QList<Id> DMakeStepFactory::availableCreationIds(BuildStepList *parent) const { if (parent->target()->project()->id() == Constants::DPROJECT_ID) return QList<Id>() << Id(Constants::D_MS_ID); return QList<Id>(); } QString DMakeStepFactory::displayNameForId(const Id id) const { if (id == Constants::D_MS_ID) return QCoreApplication::translate("DProjectManager::Internal::DMakeStep", Constants::D_MS_DISPLAY_NAME); return QString(); } } // namespace Internal } // namespace DProjectManager
[ "goldmax3000@gmail.com" ]
goldmax3000@gmail.com
10f40e7099913bd4dc177cdcfaaf176c00886072
0c02367803ca9b3eea6a3f226eb9124c4d6ea26d
/Chapter_09/dynamic_saerch.cpp
03bfabc95759117cb2c7456f46310dcdd7137397
[]
no_license
jerrychaolee/dsac
370344e5459572f95f2ab7ecd4690a644969ee9e
40420318b2ad28c67149bc150e0ceb62a44a8857
refs/heads/master
2020-04-04T13:22:24.834878
2018-12-14T15:43:47
2018-12-14T15:43:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,216
cpp
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "dynamic_search.h" //在根指针T所指二叉树中递归地查找某关键字等于key的数组元素, //若查找成功, 则返回指向该数据元素结点的的指针,否则返回空指针 BiTree SearchBST(BiTree T, KeyType key) { if (!T || EQ(key, T->data.key)) return (T); //查找结束 else if (LT(key, T->data.key)) return (SearchBST(T->lchild, key)); //在右子树中继续查找 else return (SearchBST(T->rchild, key)); } //在根指针T所指二叉排序树中递归地查找其中关键字等于key的数据元素,若查找成功 //则指针p指向该数据元素结点,并返回TRUE,否则p指向查找路径上访问的 //最后一个结点并返回FALSE,指针f指向T的双亲,其初始值调用为NULL Status SearchBST(BiTree T, KeyType key, BiTree f, BiTree &p) { if (!T) { p = f; return FALSE; //查找不成功 } else if (EQ(key, T->data.key)) { p = T; return TRUE; //查找成功 } else if (LT(key, T->data.key)) return SearchBST(T->lchild, key, T, p); //在左子树中继续查找 else return SearchBST(T->rchild, key, T, p); //在右子树中继续查找 } //当二叉排序树T中不存在关键字等于e.key的元素时,插入e并返回TRUE, //否则返回FALSE Status InsertBST(BiTree &T, ElemType e) { BiTree p; BiTNode *s; if (!SearchBST(T, e.key, NULL, p)) { //查找文件 s = (BiTNode *)malloc(sizeof(BiTNode)); //新建一个要插入的结点 s->data = e; s->lchild = NULL; s->rchild = NULL; if (p == NULL) //新插入的结点为根结点 T = s; else if (LT(e.key, p->data.key)) //插入到左子树 p->lchild = s; else //插入到右子树 p->rchild = s; return OK; } else return ERROR; } //若二叉排序树T中存在关键字等于key的数据元素时,则删除该数据元素的结点 //并返回TRUE,否则返回FALSE Status DeleteBST(BiTree &T, KeyType key) { if (!T) return FALSE; //不存在关键字等于key的数据元素 else { if (EQ(key, T->data.key)) //找到关键字等于key的数据元素 return Delete(T); else if(LT(key, T->data.key)) return DeleteBST(T->lchild, key); else return DeleteBST(T->rchild, key); } } //从二叉排序树中删除结点p,并重新接他的左右子树 Status Delete(BiTree &p) { BiTree q, s; if (!p->rchild) { //右子树空则只需要重接它的左子树 q = p; p = p->lchild; free(q); } else if (!p->lchild) { //左子树为空则只需要重接它的右子树 q = p; p = p->rchild; free(q); } else { //左右子树均不空 q = p; s = p->lchild; while (s->rchild) { q = s; s = s->lchild; //左转,然后向右走到尽头 } p->data = s->data; //s指向被删结点的“前驱” if (q != p) q->rchild = s->lchild; //重接*q的右子树 else q->lchild = s->lchild; //重接*q的左子树 delete s; } return TRUE; } //对以*p为根的二叉排序树作右旋处理,处理之后p指向新的树的根结点 //即旋转处理之前的左子树的根结点 void R_Rotate(BSTree &p) { BSTree lc; lc = p->lchild; //lc指向的*p的左子树根结点 p->lchild = lc->rchild; //lc的右子树挂在p的左子树下 lc->rchild = p; //p挂在lc的左子树下 p = lc; //p指向新的根结点 } //对以*p为根的二叉排序树作左旋处理,处理之后p指向新的树的根结点 //即旋转处理之前的右子树的根结点 void L_Rotate(BSTree &p) { BSTree rc; rc = p->rchild; p->rchild = rc->lchild; rc->lchild = p; p = rc; } //算法9.11,若平衡的二叉排序树T中不存在和e有相同关键字的结点,则插入一个数据元素为e //的结点,并返回1,否则返回0,若因此插入而使二叉排序树失去平衡,则作平衡旋转处理, //taller指示树的深度是否增加。用递归的方法寻找要插入的位置,并检测平衡度以做出相应的 //旋转的变化,但因为旋转之后树的深度其实和插入前是没有变化的, //所以整个递归过程中其实只有最小非平衡子树需要作旋转平衡操作,其余结点都无需作旋转操作。 Status InsertAVL(BSTree &T, ElemType e, Boolean &taller) { if(T == NULL){ //空树,插入结点e,树深度增加,置taller为true T->data = e; T->lchild = NULL; T->rchild = NULL; T->bf = EH; taller = true; } else{ if(EQ(e.key, T->data.key)) { //树中存在该元素,则不再插入 taller = false; return 0; } else if (LT(e.key, T->data.key)) { //元素小于根结点,则应在根结点左子树中继续寻找 if (InsertAVL(T->lchild, e, taller)) return 0; //左子树中有该元素,则未插入 else { //该元素插入到左子树中 if (taller) { //已插入以左子树且左子树深度增加,子树不增高的情况不需要考虑 switch (T->bf) { //检查T的平衡度 case LH: //原本左子树比右子树高,需要作左平衡处理 LeftBalance(T); taller = false; break; case EH: //原本左右子树等高,现因左子树增高使树增高 T->bf = LH; taller = true; break; case RH: //原本右子树高,现左右子树等高,树高不增加 T->bf = EH; taller = false; break; default: break; } } } } else { //应在T的右子树中进行搜索 if(InsertAVL(T->rchild, e, taller)) return 0; //未插入 else { if (taller) { //已插入到右子树且右子树长高 switch(T->bf) { //检查T的平衡度 case LH: T->bf = EH; taller = false; break; case EH: T->bf = RH; taller = true; break; case RH: //需要作右平衡处理 RightBalance(T); taller = false; break; } } } } } return 1; } //对以指针T所指结点为根的二叉树作左平衡处理,本算法结束时,指针T指向 //新的根结点; //左平衡操作是指当T的左子树的深度与右子树深度之差大于2时所需要作出的操作。 void LeftBalance(BSTree &T) { BSTree lc, rd; lc = T->rchild; //lc指向T的左子树根结点 switch (lc->bf) { //检查T的左子树的平衡度 case LH: //新节点插入在T的左孩子的左子树上,要做单右旋处理 T->bf = lc->bf = EH; R_Rotate(T); break; case RH: //新结点插入在T的左孩子的右子树上,要作双旋处理 rd = lc->rchild; //rd指向T的左孩子的右子树的根 switch (rd->bf) { //修改T以及其左孩子的平衡因子 case LH: T->bf = RH; lc->bf = EH; break; case EH: T->bf = EH; lc->bf = EH; break; case RH: T->bf = EH; lc->bf = LH; break; } rd->bf = EH; L_Rotate(T->lchild); R_Rotate(T); } } //对以指针T所指结点为根的二叉树作右平衡处理,本算法结束时,指针T指向新的根结点 void RightBalance(BSTree &T) { BSTree rc, ld; rc = T->rchild; //rc指向T的右子树根结点 switch (rc->bf) { //检查T的右子树的平衡度 case RH: //新结点插入在T的右孩子的右子树上,要作单左旋处理 T->bf = rc->bf = EH; L_Rotate(T); break; case LH: //新结点插入在T的右孩子的左子树上,要作双旋处理 ld = rc->lchild; //ld指向T的右孩子的左子树根结点 switch (ld->bf) { case LH: T->bf = EH; rc->bf = RH; break; case EH: T->bf = EH; rc->bf = EH; break; case RH: T->bf = LH; rc->bf = EH; break; } ld->bf = EH; R_Rotate(T->rchild); L_Rotate(T); } } //在m阶B-树T上查找关键字K,返回结果(pt, i, tag),若查找成功, //则特征值tag = 1,指针pt所指结点中第i个关键字等于K,否则特征值tag = 0, //等于K的关键字应插入在指针pt所指结点中第i和第i+1个关键字之间。 Result SearchBTree(BTree T, KeyType K) { int i = 0; Result r; BTree p = T, q = NULL; //初始化,p指向待查结点,q指向p的双亲结点 bool found = false; while (p != NULL && !found) { i = Search(p, K); //在p->key[1...keynum]中查找 //i使得: p->key[i] <= K < key[i + 1] if (i > 0 && K == p->Key[i]) { //找到待查结点 found = true; } else { q = p; p = p->ptr[i]; } } if (found) { //查找成功 r.pt = p; r.i = i; r.tag = 1; } else { //查找失败,返回K的插入位置信息 r.pt = q; r.i = i; r.tag = 0; } return r; } //在p->Key[1...keynum]中查找i,使p->Key[i] <= K < p->Key[i+1],当K < p->Key[1]时, //i = 0, 返回找到的i. int Search(BTree p, KeyType K) { int i, j; if (K < p->Key[1]) i = 0; else if (K >= p->Key[p->keynum]) i = p->keynum; else { for (j = 1; j <= ((p->keynum) - 1); ++j) { if(K >= p->Key[j] && K < p->Key[j + 1]) { i = j; break; } } } return i; } //首先查找m阶B树上是否有关键字K,有则不插入,返回0,否则在m阶B-树插入关键字K //并返回1,若引起结点过大,则沿双亲链进行必要的结点分裂调整,使T仍是m阶B-树。 Status InsertBTree(BTree &T, KeyType K) { int s; //要插入父结点中关键字的位置 KeyType x = K; BTree ap = NULL; //分裂出的结点 bool finished = false; //分裂是否完成标志 Result res; res = SearchBTree(T, K); int i = res.i; BTree q = res.pt; //插入位置 if (res.tag == 1) return 0; //结点已存,无需插入 else { while (q != NULL && !finished) {//要插入的结点不为空且分裂还没有完成 Insert(q, i, x, ap); //插入关键字x及指针ap到q->Key[i+1], q->ptr[i+1] if(q->keynum < m) //结点大小合适,结束分裂 finished = true; else { //分裂结点*q s = (int)ceil(m / 2.0); //中间结点的位置,以s为界限分裂 split(q, s, ap); //将s前的关键字保留在q中,s后面的关键字分裂出去到新的结点ap中 x = q->Key[s]; q = q->parent; if (q != NULL) i = Search(q, x); //在双亲结点中查找插入x的位置 } } if (!finished) //T是空树,或者根结点已分裂 NewRoot(T, q, x, ap); //生成含信息(T, x, ap)的新的根结点*T,原T和ap为子树指针 return 1; } } //将关键字x和指针ap分别插入到p->Key[i+1]和p->ptr[i+1]中,注意结点关键字大小 //p->keynum要加1. Status Insert(BTree p, int i, KeyType x, BTree ap) { for (size_t j = p->keynum; j < i + 1; j--) { p->Key[j + 1] = p->Key[j]; p->ptr[i + 1] = p->ptr[j]; } p->Key[i + 1] = x; p->ptr[i + 1] = ap; p->keynum++; if (ap != NULL) ap->parent = p; return OK; } //分裂结点*p,以s位置为分界分裂,ap->Key[] = p->Key[s+1...m], //ap->ptr[] = p->ptr[s...m], p->Key[] = p->Key[1...s-1], //p->ptr[] = p->ptr[0...s-1],注意修改新建结点ap的父结点。 Status split(BTree p, int s, BTree &ap) { int i, j; p->keynum = s - 1; ap = (BTree)malloc(sizeof(BTNode)); //分配一个新结点 for (i = s + 1, j = 1; i <= m; ++i, ++j) ap->Key[j] = p->Key[i]; for (i = s, j = 0; i <= m; ++i, ++j) { ap->ptr[j] = p->ptr[i]; if (ap->ptr[j] != NULL) //更新结点的父结点,这一个问题debug了好久,mark一个 ap->ptr[j]->parent = ap; } ap->keynum = m - s; ap->parent = p->parent; return OK; } //生成新的根结点, 根结点信息为Key[1] = x, ptr[0, 1] = (q, ap) Status NewRoot(BTree &T, BTree q, KeyType x, BTree ap) { BTree root; root = (BTree)malloc(sizeof(BTNode)); root->Key[1] = x; root->ptr[0] = T; root->ptr[1] = ap; root->keynum = 1; root->parent = NULL; if (T != NULL) T->parent = root; if (ap != NULL) ap->parent = root; T = root; return OK; } //用文件filename中的信息创建B-树,假设B-树中只有关键字信息。 Status CreateBTree(BTree &T, char *filename) { FILE *pf; KeyType e; pf = fopen(filename, "r"); if (pf == NULL) { printf_s("打开文件%s失败!", filename); return ERROR; } while (fscanf(pf, "%d", &e) != EOF) InsertBTree(T, e); fclose(pf); return OK; } //打印B-树,按先序顺序 Status DisplayBTree(BTree T) { if (T != NULL) { for (size_t i = 0; i < T->keynum; i++) { if (i < T->keynum) { DisplayBTree(T->ptr[i]); printf_s("%d", T->Key[i + 1]); } else { DisplayBTree(T->ptr[i]); } } } return OK; } //在非空双链树T中查找关键字等于K的记录, 若存在,则返回指向该关键字的指针 //否则返回空指针 Record *SearchDLTree(DLTree T, KeysType K) { DLTree p; p = T->first; int i = 0; while (p && i < K.num) { while (p && p->symbol != K.ch[i]) p = p->next; //查找关键字的第i位 if (p && i < K.num - 1) p = p->first; //准备查找下一位 ++i; } //查找结束 if (!p) //查找不成功 return NULL; else //查找成功 return p->infoptr; } //在键树T中查找关键字等于K的记录 Record *SearchTrie(TrieTree T, KeysType K) { TrieTree p = T; for (int i = 0; p && p->kind == BRANCH && i < K.num; p = p->bh.ptr[ord(K.ch[i])], ++i); //ord求字符在字母表中的序号 if (p && p->kind == LEAF && p->lf.K.num == K.num && p->lf.K.ch == K.ch) //查找成功 return p->lf.infoptr; else return NULL; } int ord(char ch) { /* a-z:97-122 A-Z:65-90 0-9:48-57*/ int ord; if (ch == '$') ord = 0; else if (ch >= 'a' && ch <= 'z') ord = (int)ch - (int)'a' + 1; else if (ch >= 'A' && ch <= 'Z') ord = (int)ch - (int)'A' + 1; else ord = -1; return ord; }
[ "41637553+Sepheranix@users.noreply.github.com" ]
41637553+Sepheranix@users.noreply.github.com
146d3f5cbec65edb712a21c212dca4ad58274a27
3064e4eae69e25e43ef860a1887c277b9ff9c8aa
/Program.cpp
606cf7868cecf22a1f5e86531e7064baeee60947
[]
no_license
ScottDavey/SFML_GameState
60ceea859742e0eb13e86cd5e2a7019783c7d1a9
ae9e658c10f4c899aced1e10bac77c3215e94ee1
refs/heads/master
2016-09-10T18:56:43.819555
2013-06-09T17:01:39
2013-06-09T17:01:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,710
cpp
#include "Program.h" State BaseClass::gameState = sm_MAIN; Program::Program(void) : window(sf::VideoMode(1280, 720), "Finite State Machine"), activeState(sm_MAIN) { window.setFramerateLimit(60); font_FPS.loadFromFile("Content/Font/GOTHIC.TTF"); // FPS Text text_FPS.setFont(font_FPS); text_FPS.setCharacterSize(12); text_FPS.setColor(sf::Color(85, 85, 85)); text_FPS.setPosition(605, 700); fps = 0.0f; theClass = new StartMenu(window); theClass->setState(sm_MAIN); } Program::~Program(void) { delete theClass; } bool Program::Run () { sf::Clock GameTime; while (window.isOpen()) { elapsedTime = GameTime.restart(); if (activeState != theClass->getState()) { activeState = theClass->getState(); if (theClass) delete theClass; switch (activeState) { case sm_MAIN: theClass = new StartMenu(window); break; case sm_OPTIONS: theClass = new StartMenu_Options(window); break; case GAME: theClass = new Level(window); break; case gm_MAIN: theClass = new StateThree(window); break; default: theClass = new StartMenu(window); break; } } // Poll Events while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } // FPS int FPS = static_cast<int> (1.0f / elapsedTime.asSeconds()); fps += elapsedTime.asSeconds(); if (fps >= 0.2f) { std::ostringstream Converter; Converter << "FPS " << FPS; text_FPS.setString(Converter.str()); fps = 0.0f; } window.clear(sf::Color(34, 34, 34, 100)); theClass->Update(elapsedTime); theClass->Draw(elapsedTime); window.draw(text_FPS); window.display(); } return true; }
[ "scottmichaeldavey@gmail.com" ]
scottmichaeldavey@gmail.com
4553c3790c9a1ef79771875195fe6be1f1c30dbb
4541d0c5153d826781ad60594549d7cf0f830c42
/game/include/Character.h
504ac08096958b9f9c616efc8bae861479e93117
[]
no_license
spidamoo/rlsa
8c2ecf9afead0ea47885da47f69cf8bd9ed5f66e
0edf612fb10fe64ec8c20937ca7ccbebcd04a4b9
refs/heads/master
2021-06-21T01:53:35.911619
2017-08-14T18:28:31
2017-08-14T18:28:31
100,297,600
0
0
null
null
null
null
UTF-8
C++
false
false
1,145
h
#ifndef CHARACTER_H #define CHARACTER_H #include <Lib.h> const char CHARACTER_MOVE_DIRECTION_IDLE = 0; const char CHARACTER_MOVE_DIRECTION_RIGHT = 1; const char CHARACTER_MOVE_DIRECTION_RIGHTDOWN = 2; const char CHARACTER_MOVE_DIRECTION_DOWN = 3; const char CHARACTER_MOVE_DIRECTION_LEFTDOWN = 4; const char CHARACTER_MOVE_DIRECTION_LEFT = 5; const char CHARACTER_MOVE_DIRECTION_LEFTUP = 6; const char CHARACTER_MOVE_DIRECTION_UP = 7; const char CHARACTER_MOVE_DIRECTION_RIGHTUP = 8; const float CHARACTER_DIRECTION_SPEED_C[9][2] = { { 0.000f, 0.000f}, { 1.000f, 0.000f}, { 0.707f, 0.707f}, { 0.000f, 1.000f}, {-0.707f, 0.707f}, {-1.000f, 0.000f}, {-0.707f, -0.707f}, { 0.000f, -1.000f}, { 0.707f, -0.707f} }; class Character { public: Character(Game* game); virtual ~Character(); void Update(float dt); void Control(float dt); void Draw(); float GetX(); float GetY(); protected: Game* game; float x, y; IMeshSceneNode* node; private: }; #endif // CHARACTER_H
[ "spidamoo@spidamoo.ru" ]
spidamoo@spidamoo.ru
070853ffa495926ca07c4322211085e10469e4df
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE36_Absolute_Path_Traversal/s02/CWE36_Absolute_Path_Traversal__char_file_open_52b.cpp
b69099172f61eee74378064044ca74c0e0b7b144
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
1,443
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__char_file_open_52b.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-52b.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: file Read input from a file * GoodSource: Full path and file name * Sink: open * BadSink : Open the file named in data using open() * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #ifdef _WIN32 #define OPEN _open #define CLOSE _close #else #include <unistd.h> #define OPEN open #define CLOSE close #endif namespace CWE36_Absolute_Path_Traversal__char_file_open_52 { /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD /* bad function declaration */ void badSink_c(char * data); void badSink_b(char * data) { badSink_c(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(char * data); void goodG2BSink_b(char * data) { goodG2BSink_c(data); } #endif /* OMITGOOD */ } /* close namespace */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
e90b6af8f452a76f16f061043467cf3e37ec3cdd
1aeb50f6fbbc59c94576c3c40f8b64ca890b2474
/plugins/MultiContactStabilizerPlugin/ModelPredictiveController.cpp
75146a33f144b0ecfba3b2a15019440faecb67ea
[]
no_license
kindsenior/jsk_choreonoid
b6a8f39b45a8350404c42f1e029d777cb349615e
82e3faa0e03595637c30654dba28f90ae3bc9e72
refs/heads/master
2021-01-24T09:46:38.756888
2020-07-07T06:23:12
2020-07-07T06:23:12
37,442,336
1
3
null
2020-06-04T08:42:16
2015-06-15T03:56:32
C++
UTF-8
C++
false
false
10,448
cpp
/** @author Kunio Kojima */ #include "ModelPredictiveController.h" using namespace hrp; using namespace std; // template <class ControllerClass, class ParamClass> // ModelPredictiveController<ControllerClass,ParamClass>::ModelPredictiveController() // { // isInitial = true; // parent = NULL; // } // template <class ControllerClass, class ParamClass> // ParamClass* ModelPredictiveController<ControllerClass,ParamClass>::copyMpcParam(ControllerClass* controller, ParamClass* fromMpcParam) // { // ParamClass* toMpcParam = new ControllerClass(controller, fromMpcParam); // return toMpcParam; // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcPhiMatrix() // { // phiMat = dmatrix(stateDim*numWindows_,stateDim); // dmatrix lastMat = dmatrix::Identity(stateDim,stateDim); // for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter){ // int idx = std::distance(mpcParamDeque.begin(), iter); // lastMat = (*iter)->systemMat * lastMat; // phiMat.block(stateDim*idx,0, stateDim,stateDim) = lastMat; // } // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcPsiMatrix() // { // psiMat = dmatrix::Zero(stateDim*numWindows_,psiCols); // int colIdx = 0; // for(typename std::deque<ParamClass*>::iterator Biter = mpcParamDeque.begin(); Biter != mpcParamDeque.end(); ){// Biterは内側のforループでインクリメント // dmatrix lastMat = (*Biter)->inputMat; // int cols = lastMat.cols(); // int Bidx = std::distance(mpcParamDeque.begin(), Biter);// column index // psiMat.block(stateDim*Bidx,colIdx, stateDim,cols) = lastMat; // for(typename std::deque<ParamClass*>::iterator Aiter = ++Biter; Aiter != mpcParamDeque.end(); ++Aiter){ // int Aidx = std::distance(mpcParamDeque.begin(), Aiter);// row index // lastMat = (*Aiter)->systemMat * lastMat; // psiMat.block(stateDim*Aidx,colIdx, stateDim,cols) = lastMat; // } // colIdx += cols; // } // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcEqualConstraints() // { // equalMat = dmatrix::Zero(equalMatRows,URows); // equalVec = dvector(equalMatRows); // int rowIdx = 0; // int colIdx = 0; // hrp::dumpMatrix(equalMat, &ParamClass::equalMat, mpcParamDeque, rowIdx, colIdx, blockFlagVec); // hrp::dumpVector(equalVec, &ParamClass::equalVec, mpcParamDeque, rowIdx, blockFlagVec); // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcInequalConstraints() // { // inequalMat = dmatrix::Zero(inequalMatRows,URows); // inequalMinVec = dvector(inequalMatRows); // inequalMaxVec = dvector(inequalMatRows); // int rowIdx = 0; // int colIdx = 0; // hrp::dumpMatrix(inequalMat, &ParamClass::inequalMat, mpcParamDeque, rowIdx, colIdx, blockFlagVec); // hrp::dumpVector(inequalMinVec, &ParamClass::inequalMinVec, mpcParamDeque, rowIdx, blockFlagVec); // hrp::dumpVector(inequalMaxVec, &ParamClass::inequalMaxVec, mpcParamDeque, rowIdx, blockFlagVec); // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcBoundVectors() // { // minVec = dvector(URows); // maxVec = dvector(URows); // int rowIdx = 0; // hrp::dumpVector(minVec, &ParamClass::minVec, mpcParamDeque, rowIdx, blockFlagVec); // hrp::dumpVector(maxVec, &ParamClass::maxVec, mpcParamDeque, rowIdx, blockFlagVec); // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcRefXVector() // { // refXVec = dvector(stateDim*numWindows_); // for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter){ // int idx = std::distance(mpcParamDeque.begin(), iter); // refXVec.block(stateDim*idx,0, stateDim,1) = (*iter)->refStateVec; // } // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcErrorWeightMatrix() // { // errorWeightMat = dmatrix::Zero(stateDim*numWindows_,stateDim*numWindows_); // for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter){ // int idx = std::distance(mpcParamDeque.begin(), iter); // errorWeightMat.block(stateDim*idx,stateDim*idx, stateDim,stateDim) = (*iter)->errorWeightVec.asDiagonal(); // } // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcInputWeightMatrix() // { // inputWeightMat = dmatrix::Zero(psiCols,psiCols); // int rowIdx = 0; // for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter){ // int rows = (*iter)->inputWeightVec.rows(); // inputWeightMat.block(rowIdx,rowIdx, rows,rows) = (*iter)->inputWeightVec.asDiagonal(); // rowIdx += rows; // } // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcBlockMatrix() // { // blockMat = dmatrix::Zero(psiCols,URows); // blockMatInv = dmatrix::Zero(URows,psiCols); // std::vector<bool>::iterator blockFlagIter = blockFlagVec.begin(); // typename std::deque<ParamClass*>::iterator colIter = mpcParamDeque.begin(); // int count = 1, rowIdx = 0, colIdx = 0; // for(typename std::deque<ParamClass*>::iterator rowIter = mpcParamDeque.begin(); rowIter != mpcParamDeque.end(); ++rowIter, ++colIter){ // int rows,cols; // rows = (*rowIter)->inputDim; // if(*blockFlagIter){ // cols = (*colIter)->inputDim; // blockMatInv.block(colIdx,rowIdx, cols,rows) = dmatrix::Identity(cols,rows);// blockMatInv // } // blockMat.block(rowIdx,colIdx, rows,cols) = dmatrix::Identity(rows,cols);// blockMat // if(*(++blockFlagIter)){ // colIdx += cols; // } // rowIdx += rows; // } // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::updateX0Vector() // { // ParamClass* mpcParam = mpcParamDeque[0]; // // U->u0 // // x0 = A0*x0 + B'0*u0 // dmatrix x1 = mpcParam->systemMat*x0 + mpcParam->inputMat*U.block(0,0, mpcParam->inputMat.cols(),1); // if(parent != NULL){ // ControllerClass* root = rootController(); // int stepNum = parent->dt/root->dt;// root->dtで割り切れる? // // int nextPushIndex; // // if(!parent->preMpcParamDeque.empty()) nextPushIndex = parent->preMpcParamDeque.back()->index() + stepNum; // // else if(!parent->mpcParamDeque.empty()) nextPushIndex = parent->mpcParamDeque.back()->index() + stepNum; // // else nextPushIndex = 0; // int x0Index = mpcParamDeque[0]->index(); // int x1Index = mpcParamDeque[1]->index();// 0除算の可能性 最後以降は補間しないから大丈夫? // cout << x0Index << ": " << x0.transpose() << endl; // cout << x1Index << ": " << x1.transpose() << endl; // cout << "root: " << root->dt << " parent:" << parent->dt << endl; // typename std::deque<ParamClass*>::iterator rootPreDequeIter = root->preMpcParamDeque.begin(); // ParamClass* targetMpcParam; // while((*rootPreDequeIter)->index() < x0Index) rootPreDequeIter += stepNum; // while((*rootPreDequeIter)->index() < x1Index){ // if(root == parent){ // targetMpcParam = *rootPreDequeIter; // }else{ // parent->preMpcParamDeque.push_back(copyMpcParam(parent, *rootPreDequeIter));// pickup mpcParam from root mpc dtが変わるので行列は生成し直す // targetMpcParam = parent->preMpcParamDeque.back(); // } // targetMpcParam->setRefStateVector(x0 + (x1-x0)*((*rootPreDequeIter)->index() - x0Index)/(double)(x1Index - x0Index)); // interpolate refX,U // rootPreDequeIter += stepNum; // } // } // x0 = x1; // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::calcAugmentedMatrix() // { // psiCols = 0; // equalMatRows = 0; // inequalMatRows = 0; // URows = 0; // std::vector<bool>::iterator blockFlagIter = blockFlagVec.begin(); // for(typename std::deque<ParamClass*>::iterator iter = mpcParamDeque.begin(); iter != mpcParamDeque.end(); ++iter, ++blockFlagIter){ // psiCols += (*iter)->inputMat.cols(); // if(*blockFlagIter){ // URows += (*iter)->inputDim; // equalMatRows += (*iter)->equalMat.rows(); // inequalMatRows += (*iter)->inequalMat.rows(); // } // } // if(isInitial){ // x0 = dvector(stateDim); // x0 = mpcParamDeque[0]->refStateVec; // isInitial = false; // } // calcPhiMatrix(); // calcPsiMatrix(); // calcEqualConstraints(); // calcInequalConstraints(); // calcBoundVectors(); // calcRefXVector(); // calcErrorWeightMatrix(); // calcInputWeightMatrix(); // calcBlockMatrix(); // U = dvector::Zero(URows); // } // template <class ControllerClass, class ParamClass> // ControllerClass* ModelPredictiveController<ControllerClass,ParamClass>::rootController() // { // if(parent != NULL) return parent->rootController(); // return this; // } // template <class ControllerClass, class ParamClass> // void ModelPredictiveController<ControllerClass,ParamClass>::pushAllPreMPCParamFromRoot() // { // ControllerClass* root = rootController(); // int stepNum = dt/root->dt;// root->dtで割り切れる? // typename std::deque<ParamClass*>::iterator iter = root->preMpcParamDeque.begin(); // while(iter != root->preMpcParamDeque.end()){ // preMpcParamDeque.push_back(copyMpcParam(this ,*iter)); // for(int i=0; i<stepNum && iter !=root->preMpcParamDeque.end(); ++i, ++iter); // } // }
[ "kunio.einstein@gmail.com" ]
kunio.einstein@gmail.com
6c59c1a9ab78544db9b3a5d2fd44000122f6c3ce
1d6abe27a802d53f7fbd6eb5e59949044cbb3b98
/tensorflow/core/profiler/rpc/profiler_server.cc
b65621450d1292798c856ad3de21231b2bde983c
[ "Apache-2.0" ]
permissive
STSjeerasak/tensorflow
6bc8bf27fb74fd51a71150f25dc1127129f70222
b57499d4ec0c24adc3a840a8e7e82bd4ce0d09ed
refs/heads/master
2022-12-20T20:32:15.855563
2020-09-29T21:22:35
2020-09-29T21:29:31
299,743,927
5
1
Apache-2.0
2020-09-29T21:38:19
2020-09-29T21:38:18
null
UTF-8
C++
false
false
1,979
cc
/* Copyright 2018 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. ==============================================================================*/ #include "tensorflow/core/profiler/rpc/profiler_server.h" #include <memory> #include <string> #include "grpcpp/grpcpp.h" #include "absl/strings/str_cat.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/profiler/profiler_service.grpc.pb.h" #include "tensorflow/core/profiler/rpc/profiler_service_impl.h" namespace tensorflow { namespace profiler { void ProfilerServer::StartProfilerServer(int32 port) { VLOG(1) << "Starting profiler server."; std::string server_address = absl::StrCat("[::]:", port); service_ = CreateProfilerService(); ::grpc::ServerBuilder builder; int selected_port = 0; builder.AddListeningPort(server_address, ::grpc::InsecureServerCredentials(), &selected_port); builder.RegisterService(service_.get()); server_ = builder.BuildAndStart(); if (!selected_port) { LOG(ERROR) << "Unable to bind to " << server_address << " selected port:" << selected_port; } else { LOG(INFO) << "Profiler server listening on " << server_address << " selected port:" << selected_port; } } ProfilerServer::~ProfilerServer() { if (server_) { server_->Shutdown(); server_->Wait(); } } } // namespace profiler } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
98b9037df35958d25ce713a74b954bae8f8cf0b7
b4f42eed62aa7ef0e28f04c1f455f030115ec58e
/messagingfw/msgtest/targetautomation/TechviewStart/ThreadWatch.cpp
42bcab4ae6b5059e6197872c88b39eeac7d3fd6d
[]
no_license
SymbianSource/oss.FCL.sf.mw.messagingmw
6addffd79d854f7a670cbb5d89341b0aa6e8c849
7af85768c2d2bc370cbb3b95e01103f7b7577455
refs/heads/master
2021-01-17T16:45:41.697969
2010-11-03T17:11:46
2010-11-03T17:11:46
71,851,820
1
0
null
null
null
null
UTF-8
C++
false
false
1,996
cpp
// Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // #include "ThreadWatch.h" #include "Starter.h" /** * class CThreadWatcher **/ CThreadWatcher::~CThreadWatcher() { Cancel(); } CThreadWatcher::CThreadWatcher(TInt appType, TFullName aFullName, CStarter* aOwner, TUint32 aAppUid, TBool aViewless) : CActive(EPriorityStandard), iAppType(appType), iFullName(aFullName), iOwner(aOwner), iAppUid(aAppUid), iViewless(aViewless) {} void CThreadWatcher::ConstructL(const TThreadId aThreadId) { iMonitoringThread = ETrue; User::LeaveIfError(iThread.Open(aThreadId)); // Queue logon request iThread.Logon(iStatus); CActiveScheduler::Add(this); SetActive(); // Tell scheduler we're active } CThreadWatcher* CThreadWatcher::NewL(TInt appType, const TThreadId aThreadId, TFullName aFullName, CStarter* aOwner, TUint32 aAppUid, TBool aViewless) { CThreadWatcher* self = new (ELeave) CThreadWatcher(appType, aFullName, aOwner, aAppUid, aViewless); CleanupStack::PushL(self); self->ConstructL(aThreadId); CleanupStack::Pop(); // self; return self; } void CThreadWatcher::DoCancel() { iThread.LogonCancel(iStatus); iThread.Close(); } void CThreadWatcher::RunL() { iThread.Close(); if(iMonitoringThread) { TRAPD(err, RestartThreadL()); //ignore error } } void CThreadWatcher::RestartThreadL() { TThreadId threadId; iOwner->RestartMonitoredThreadL(iAppType, threadId, iFullName, iAppUid, iViewless); User::LeaveIfError(iThread.Open(threadId)); // Queue logon request iThread.Logon(iStatus); iStatus = KRequestPending; SetActive(); // Tell scheduler we're active }
[ "none@none" ]
none@none
3f07c1f499054b73ccc7bf702526f945767abf15
3b424a008356da060bb0f228bdbd5566fcafa9a5
/maincontent/controlwidget/openglcontrol/objectmodel/objectparent.cpp
6adb57ea9c4613e3cb1a7e07b4849993ee86ef62
[]
no_license
ylx167167/pi_ti_radar_32
058b0e9a1eb3a3cc17e76b69c32082844771eff2
fbf3332289639b970bd2abe1d0816a4216b2f960
refs/heads/main
2023-03-08T17:06:23.139653
2021-02-23T17:26:12
2021-02-23T17:26:12
337,342,813
1
0
null
null
null
null
UTF-8
C++
false
false
4,251
cpp
/***************************************** * 作者: YYC * 日期: 2020-04-26 * 功能:3D模型父类,封装了模型的公共方法 * 包括模型位移,旋转 * VAO,VBO,EBO的创建,绑定,释放,销毁等 * 模型矩阵,观察矩阵,投影矩阵的设置和获取 * ***************************************/ #include "objectparent.h" ObjectParent::ObjectParent() : m_vbo(QOpenGLBuffer::VertexBuffer), m_ebo(QOpenGLBuffer::IndexBuffer) { } ObjectParent::~ObjectParent() { } void ObjectParent::bind() { m_shaderLibrary.bind(); m_textureLibrary.bindAll(); m_vao.bind(); } void ObjectParent::release() { m_textureLibrary.releaseAll(); m_shaderLibrary.release(); if (m_vao.isCreated()) { m_vao.release(); } } void ObjectParent::destory() { if (m_vbo.isCreated()) { m_vbo.destroy(); } if (m_ebo.isCreated()) { m_ebo.destroy(); } if (m_vao.isCreated()) { m_vao.destroy(); } m_textureLibrary.destoryAll(); } void ObjectParent::setupShader(const QString &vertexPath, const QString &fragmentPath) { bool successFlage = m_shaderLibrary.compileAndBindShaderFile(vertexPath, fragmentPath); if(!successFlage) { qDebug() << "Compile shader error!"; } } void ObjectParent::setupTexture(const QImage &image) { if (nullptr != m_openGLWidget) { m_openGLWidget->makeCurrent(); } m_textureLibrary.clearTexture(); m_textureLibrary.appendGlTexture(image); if (nullptr != m_openGLWidget) { m_openGLWidget->doneCurrent(); } } void ObjectParent::setupTexture(const QString &imagePath) { m_textureLibrary.clearTexture(); m_textureLibrary.appendGlTexture(imagePath); } void ObjectParent::setupTexture(const QList<QString> &imagePathList) { m_textureLibrary.generateTexture(imagePathList); } void ObjectParent::setWindowWidth(const int &windowWidth) { m_windowWidth = windowWidth; } void ObjectParent::setWindowHeight(const int &windowHeight) { m_windowHeight = windowHeight; } void ObjectParent::setWindowSize(const int &windowWidth, const int &windowHeight) { m_windowWidth = windowWidth; m_windowHeight = windowHeight; } void ObjectParent::translateByX(const GLfloat &valueData) { m_modelMat.translate(valueData, 0.0f, 0.0f); } void ObjectParent::translateByY(const GLfloat &valueData) { m_modelMat.translate(0.0f, valueData, 0.0f); } void ObjectParent::translateByZ(const GLfloat &valueData) { m_modelMat.translate(0.0f, 0.0f, valueData); } void ObjectParent::rotateByX(const GLfloat &angleData) { m_modelMat.rotate(angleData, 1.0f, 0.0f, 0.0f); } void ObjectParent::rotateByY(const GLfloat &angleData) { m_modelMat.rotate(angleData, 0.0f, 1.0f, 0.0f); } void ObjectParent::rotateByZ(const GLfloat &angleData) { m_modelMat.rotate(angleData, 0.0f, 0.0f, 1.0f); } void ObjectParent::setupPerspective(const GLfloat &angleData) { if (m_windowWidth != 0 && m_windowHeight != 0) { m_projMat.perspective(angleData, 1.0 * m_windowWidth / m_windowHeight, 0.1f, 100.0f); } } int ObjectParent::getVertexCount() { return m_ebo.size() / sizeof(GLfloat); } void ObjectParent::setCameraLibrary(CameraLibrary *cameraLibrary) { m_cameraLibrary = cameraLibrary; } void ObjectParent::setOpenGLFunctions(QOpenGLFunctions *openGLFunctions) { m_openGLFunctions = openGLFunctions; } void ObjectParent::setOpenGLWidget(QOpenGLWidget *openGLWidget) { m_openGLWidget = openGLWidget; m_textureLibrary.setOpenGLWidget(m_openGLWidget); } void ObjectParent::setupObjectShaderMat() { if (nullptr != m_cameraLibrary) { m_viewMat = m_cameraLibrary->getViewMat4x4(); } m_shaderLibrary.setUniformValue("modelMat", m_modelMat); m_shaderLibrary.setUniformValue("viewMat", m_viewMat); m_shaderLibrary.setUniformValue("projMat", m_projMat); } void ObjectParent::makeObject() { } void ObjectParent::drawObject() { if (nullptr != m_openGLFunctions) { this->bind(); this->setupObjectShaderMat(); m_openGLFunctions->glDrawElements(GL_TRIANGLES, this->getVertexCount(), GL_UNSIGNED_INT, nullptr); this->release(); } }
[ "417838124@qq.com" ]
417838124@qq.com
c70fc1851041e2fab2acc40ad0c935df18389625
4903ae99e416302e5feade9f34be348297528f29
/ImprovedLegoEditor/ComposeImageVertexShaderToon06.cpp
ae23a422b72ac828c2853a7d93af929cdb7b483c
[]
no_license
BlurEffect/LegoEditor
d334fb009490f45b43eb1d87eadc0655d4f7d257
ff1a17ec828d01d492229e08341700b956e7a69c
refs/heads/master
2021-01-15T23:07:39.439740
2015-01-11T19:11:49
2015-01-11T19:11:49
29,102,458
3
0
null
null
null
null
UTF-8
C++
false
false
3,535
cpp
/* * Kevin Meergans, Improved Lego Editor, 2014 * ComposeImageVertexShaderToon06.cpp * Contains the function definitions for the ComposeImageVertexShaderToon06 class. */ #include "ComposeImageVertexShaderToon06.h" // The vertex input layout expected by this vertex shader const D3D11_INPUT_ELEMENT_DESC ComposeImageVertexShaderToon06::m_sInputLayoutDescription[] = { // Vertex data { "POSITION" , 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; ComposeImageVertexShaderToon06::ComposeImageVertexShaderToon06( void ) : VertexShader() { } //-------------------------------------------------------------------------------------- // Initialise the shader's member variables. //-------------------------------------------------------------------------------------- HRESULT ComposeImageVertexShaderToon06::Initialise( ID3D11Device* pDevice ) { HRESULT hr; // Create the shader hr = pDevice -> CreateVertexShader( g_composeImageVertexShader06, sizeof( g_composeImageVertexShader06 ), nullptr, &m_pVertexShader ); if( FAILED ( hr ) ) { return hr; } // Create the vertex input layout UINT numElements = ARRAYSIZE( m_sInputLayoutDescription ); hr = pDevice -> CreateInputLayout( m_sInputLayoutDescription, numElements, g_composeImageVertexShader06, sizeof( g_composeImageVertexShader06 ), &m_pInputLayout ); if( FAILED ( hr ) ) { return hr; } return S_OK; } //-------------------------------------------------------------------------------------- // Free all allocated resources. //-------------------------------------------------------------------------------------- HRESULT ComposeImageVertexShaderToon06::Cleanup( void ) { return VertexShader::Cleanup(); } //-------------------------------------------------------------------------------------- // Update the per-scene constant buffer of the shader. //-------------------------------------------------------------------------------------- HRESULT ComposeImageVertexShaderToon06::UpdatePerSceneData( ID3D11DeviceContext* pContext, const PerSceneData& perSceneData) { // Buffer not used in this shader return E_FAIL; } //-------------------------------------------------------------------------------------- // Update the per-frame constant buffer of the shader. //-------------------------------------------------------------------------------------- HRESULT ComposeImageVertexShaderToon06::UpdatePerFrameData( ID3D11DeviceContext* pContext, const PerFrameData& perFrameData) { // Not used in this shader return E_FAIL; } //-------------------------------------------------------------------------------------- // Update the per-object constant buffer of the shader. //-------------------------------------------------------------------------------------- HRESULT ComposeImageVertexShaderToon06::UpdatePerObjectData( ID3D11DeviceContext* pContext, const PerObjectData& perObjectData) { // Not used in this shader return E_FAIL; } //-------------------------------------------------------------------------------------- // Update the texture and corresponding sample state being used by the shader. //-------------------------------------------------------------------------------------- HRESULT ComposeImageVertexShaderToon06::UpdateTextureResource( int index, ID3D11DeviceContext* pContext, ID3D11ShaderResourceView* pTexture, ID3D11SamplerState* pSamplerState ) { // Not used in this shader return E_FAIL; }
[ "kevin.meergans@gmx.de" ]
kevin.meergans@gmx.de
2eb6b0349d9b54051c7d28e758b2f3a23bb61567
c44575cb90dfc9125c3a1c37dd333a7ebc4f022f
/raspberrypi/raspicam/src/private/private_types.h
c64333a53755a212ed65fd6ac52c73af5febb238
[ "BSD-3-Clause" ]
permissive
abobco/Robot-Rover
52a433126085d4b5f9e74e3053cf9802dac60f59
dca21b3e6eeec83586f92d9dab1354cd67bd86e7
refs/heads/main
2023-06-29T07:07:47.507313
2021-07-30T06:18:55
2021-07-30T06:18:55
384,322,119
1
0
null
null
null
null
UTF-8
C++
false
false
4,904
h
/********************************************************** Software developed by AVA ( Ava Group of the University of Cordoba, ava at uco dot es) Main author Rafael Munoz Salinas (rmsalinas at uco dot es) This software is released under BSD license as expressed below ------------------------------------------------------------------- Copyright (c) 2013, AVA ( Ava Group University of Cordoba, ava at uco dot es) 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Ava group of the University of Cordoba. 4. Neither the name of the University 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 AVA ''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 AVA 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. ****************************************************************/ #ifndef _RaspiCam_private_types_H #define _RaspiCam_private_types_H namespace raspicam { namespace _private{ /// struct contain camera settings struct MMAL_PARAM_COLOURFX_T { int enable,u,v; /// Turn colourFX on or off, U and V to use } ; struct PARAM_FLOAT_RECT_T { double x,y,w,h; } ; /** Structure containing all state information for the current run */ struct RASPIVID_STATE { int sensor_mode; /// Requested width of image int width; /// Requested width of image int height; /// requested height of image int framerate; /// Requested frame rate (fps) /// the camera output or the encoder output (with compression artifacts) MMAL_COMPONENT_T *camera_component; /// Pointer to the camera component MMAL_POOL_T *video_pool; /// Pointer to the pool of buffers used by encoder output port //camera params int sharpness; /// -100 to 100 int contrast; /// -100 to 100 int brightness; /// 0 to 100 int saturation; /// -100 to 100 int ISO; /// TODO : what range? bool videoStabilisation; /// 0 or 1 (false or true) int exposureCompensation; /// -10 to +10 ? int shutterSpeed; RASPICAM_FORMAT captureFtm; RASPICAM_EXPOSURE rpc_exposureMode; RASPICAM_METERING rpc_exposureMeterMode; RASPICAM_AWB rpc_awbMode; RASPICAM_IMAGE_EFFECT rpc_imageEffect; MMAL_PARAMETER_IMAGEFX_PARAMETERS_T imageEffectsParameters; MMAL_PARAM_COLOURFX_T colourEffects; int rotation; /// 0-359 int hflip; /// 0 or 1 int vflip; /// 0 or 1 PARAM_FLOAT_RECT_T roi; /// region of interest to use on the sensor. Normalised [0,1] values in the rect float awbg_red;//white balance red and blue float awbg_blue; } ; //clean buffer template<typename T> class membuf{ public: membuf() { data=0; size=0; } ~membuf() { if ( data!=0 ) delete []data; } void resize ( size_t s ) { if ( s!=size ) { delete data; size=s; data=new T[size]; } } T *data; size_t size; }; } } #endif
[ "abobco@gmail.com" ]
abobco@gmail.com
13d47c8d33280c1040610f2194c5327579645cfd
c23865a5359e1eac2165a19ae4f7bf1c6da9128c
/schooldb/sesion.cpp
8996e57ff212fdd5ad98fb33846d9a7280a19e7d
[]
no_license
airkobeju/schoolui
87ec424b30bc934c25c1a7a6b9f03d58bc3d2dd8
87d2f8365f68e92e626eec9e80727cbde8e94b3c
refs/heads/master
2020-04-13T21:56:58.596428
2018-12-28T23:38:50
2018-12-28T23:38:50
163,468,190
0
0
null
null
null
null
UTF-8
C++
false
false
831
cpp
#include "sesion.h" Sesion::Sesion() { } QString Sesion::getId() const { return id; } void Sesion::setId(const QString &value) { id = value; } QString Sesion::getTitulo() const { return titulo; } void Sesion::setTitulo(const QString &value) { titulo = value; } QString Sesion::getRecursoMet() const { return recursoMet; } void Sesion::setRecursoMet(const QString &value) { recursoMet = value; } QString Sesion::getSecuenciaDid() const { return secuenciaDid; } void Sesion::setSecuenciaDid(const QString &value) { secuenciaDid = value; } QString Sesion::getCursoId() const { return cursoId; } void Sesion::setCursoId(const QString &value) { cursoId = value; } Fecha Sesion::getFecha() const { return fecha; } void Sesion::setFecha(const Fecha &value) { fecha = value; }
[ "airkobeju@gmail.com" ]
airkobeju@gmail.com
7e03f3844f0d9637ed8f5473dd6a293613769ea7
f4cdfd17cb593d58b4816f2d28153cdc24b27e30
/MFC_DEMO/MFC_DEMO/bwlabel.cpp
81e22b0a151842cb2c51565c8f09a9556f075f7d
[]
no_license
tuouren/experience
71fa8d78eef8565b03a29154ed79a767426c2f33
bdc759821aac1fd8a10324daf42d24862366e759
refs/heads/master
2021-01-10T20:22:18.083009
2014-08-19T01:25:42
2014-08-19T01:25:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,114
cpp
#include "StdAfx.h" #include "cv.h" #include "highgui.h" #include "bwlabel.h" #define NO_OBJECT 0 #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #define ELEM(img, r, c) (CV_IMAGE_ELEM(img, unsigned char, r, c)) #define ONETWO(L, r, c, col) (L[(r) * (col) + c]) int find( int set[], int x ) { int r = x; while ( set[r] != r ) r = set[r]; return r; } /* labeling scheme +-+-+-+ |D|C|E| +-+-+-+ |B|A| | +-+-+-+ | | | | +-+-+-+ A is the center pixel of a neighborhood. In the 3 versions of connectedness: 4: A connects to B and C 6: A connects to B, C, and D 8: A connects to B, C, D, and E */ ///////////////////////////// //by yysdsyl // //input:img -- gray image // n -- n connectedness // labels -- label of each pixel, labels[row * col] //output: number of connected regions // // //email:yysdsyl@qq.com int bwlabel(IplImage* img, int n, int* labels) { if(n != 4 && n != 8) n = 4; int nr = img->height; int nc = img->width; int total = nr * nc; // results memset(labels, 0, total * sizeof(int)); int nobj = 0; // number of objects found in image // other variables int* lset = new int[total]; // label table memset(lset, 0, total * sizeof(int)); int ntable = 0; for( int r = 0; r < nr; r++ ) { for( int c = 0; c < nc; c++ ) { if ( ELEM(img, r, c) ) // if A is an object { // get the neighboring pixels B, C, D, and E int B, C, D, E; if ( c == 0 ) B = 0; else B = find( lset, ONETWO(labels, r, c - 1, nc) ); if ( r == 0 ) C = 0; else C = find( lset, ONETWO(labels, r - 1, c, nc) ); if ( r == 0 || c == 0 ) D = 0; else D = find( lset, ONETWO(labels, r - 1, c - 1, nc) ); if ( r == 0 || c == nc - 1 ) E = 0; else E = find( lset, ONETWO(labels, r - 1, c + 1, nc) ); if ( n == 4 ) { // apply 4 connectedness if ( B && C ) { // B and C are labeled if ( B == C ) ONETWO(labels, r, c, nc) = B; else { lset[C] = B; ONETWO(labels, r, c, nc) = B; } } else if ( B ) // B is object but C is not ONETWO(labels, r, c, nc) = B; else if ( C ) // C is object but B is not ONETWO(labels, r, c, nc) = C; else { // B, C, D not object - new object // label and put into table ntable++; ONETWO(labels, r, c, nc) = lset[ ntable ] = ntable; } } else if ( n == 6 ) { // apply 6 connected ness if ( D ) // D object, copy label and move on ONETWO(labels, r, c, nc) = D; else if ( B && C ) { // B and C are labeled if ( B == C ) ONETWO(labels, r, c, nc) = B; else { int tlabel = MIN(B,C); lset[B] = tlabel; lset[C] = tlabel; ONETWO(labels, r, c, nc) = tlabel; } } else if ( B ) // B is object but C is not ONETWO(labels, r, c, nc) = B; else if ( C ) // C is object but B is not ONETWO(labels, r, c, nc) = C; else { // B, C, D not object - new object // label and put into table ntable++; ONETWO(labels, r, c, nc) = lset[ ntable ] = ntable; } } else if ( n == 8 ) { // apply 8 connectedness if ( B || C || D || E ) { int tlabel = B; if ( B ) tlabel = B; else if ( C ) tlabel = C; else if ( D ) tlabel = D; else if ( E ) tlabel = E; ONETWO(labels, r, c, nc) = tlabel; if ( B && B != tlabel ) lset[B] = tlabel; if ( C && C != tlabel ) lset[C] = tlabel; if ( D && D != tlabel ) lset[D] = tlabel; if ( E && E != tlabel ) lset[E] = tlabel; } else { // label and put into table ntable++; ONETWO(labels, r, c, nc) = lset[ ntable ] = ntable; } } } else { ONETWO(labels, r, c, nc) = NO_OBJECT; // A is not an object so leave it } } } // consolidate component table for( int i = 0; i <= ntable; i++ ) lset[i] = find( lset, i ); // run image through the look-up table for( int r = 0; r < nr; r++ ) for( int c = 0; c < nc; c++ ) ONETWO(labels, r, c, nc) = lset[ ONETWO(labels, r, c, nc) ]; // count up the objects in the image for( int i = 0; i <= ntable; i++ ) lset[i] = 0; for( int r = 0; r < nr; r++ ) for( int c = 0; c < nc; c++ ) lset[ ONETWO(labels, r, c, nc) ]++; // number the objects from 1 through n objects nobj = 0; lset[0] = 0; for( int i = 1; i <= ntable; i++ ) if ( lset[i] > 0 ) lset[i] = ++nobj; // run through the look-up table again for( int r = 0; r < nr; r++ ) for( int c = 0; c < nc; c++ ) ONETWO(labels, r, c, nc) = lset[ ONETWO(labels, r, c, nc) ]; // delete[] lset; return nobj; }
[ "875494817@qq.com" ]
875494817@qq.com
29014fa61778648d0da958919210f1c1e92c8489
609795ac6f379bffa752dc8c1c8e6a89dd201657
/include/splitspace/Texture.hpp
ca85c858c8d8509be99f12617428850bdf98bc18
[]
no_license
RostakaGmfun/splitspace
11aa686863e6ca7ca08a1b1188453b0c10d5c85b
27bf1af2b94e99b9ca0393394d386a06e8fd5c82
refs/heads/master
2021-01-10T15:32:50.621252
2016-05-05T09:52:54
2016-05-05T09:52:54
51,162,219
1
0
null
null
null
null
UTF-8
C++
false
false
638
hpp
#ifndef TEXTURE_HPP #define TEXTURE_HPP #include <splitspace/Resource.hpp> #include <splitspace/RenderManager.hpp> namespace splitspace { class LogManager; struct TextureManifest: public ResourceManifest { TextureManifest(): ResourceManifest(RES_TEXTURE) {} }; class Texture: public Resource { public: Texture(Engine *e, TextureManifest *manifest); virtual bool load(); virtual void unload(); GLuint getGLName() const { return m_glName; } private: int m_width; int m_height; int m_numChannels; unsigned char *m_data; GLuint m_glName; }; } // namespace splitspace #endif // TEXTURE_HPP
[ "rostawesomegd@gmail.com" ]
rostawesomegd@gmail.com
a8fa9324151f659ce28fbd2afe958a6fd327e895
8cd51b4885680c073566f16236cd68d3f4296399
/src/controls/QskObjectTree.h
9ad0457087f26109a061c04141fb50e47d21c96e
[ "BSD-3-Clause" ]
permissive
uwerat/qskinny
0e0c6552afa020382bfa08453a5636b19ae8ff49
bf2c2b981e3a6ea1187826645da4fab75723222c
refs/heads/master
2023-08-21T16:27:56.371179
2023-08-10T17:54:06
2023-08-10T17:54:06
97,966,439
1,074
226
BSD-3-Clause
2023-08-10T17:12:01
2017-07-21T16:16:18
C++
UTF-8
C++
false
false
3,487
h
/****************************************************************************** * QSkinny - Copyright (C) 2016 Uwe Rathmann * SPDX-License-Identifier: BSD-3-Clause *****************************************************************************/ #ifndef QSK_OBJECT_TREE_H #define QSK_OBJECT_TREE_H #include "QskControl.h" #include "QskWindow.h" #include <qvariant.h> namespace QskObjectTree { class Visitor { public: Visitor() = default; virtual ~Visitor() = default; virtual bool visitDown( QObject* object ) = 0; virtual bool visitUp( const QObject* object ) = 0; private: Q_DISABLE_COPY( Visitor ) }; QSK_EXPORT QObjectList childNodes( const QObject* ); QSK_EXPORT QObject* parentNode( const QObject* ); QSK_EXPORT bool isRoot( const QObject* ); void traverseDown( QObject* object, Visitor& visitor ); void traverseUp( QObject* object, Visitor& visitor ); template< class T > class ResolveVisitor : public Visitor { public: ResolveVisitor( const char* propertyName ) : m_propertyName( propertyName ) { } inline const T& resolveValue() const { return m_value; } void setResolveValue( const T& value ) { m_value = value; } bool visitDown( QObject* object ) override final { if ( auto control = qobject_cast< QskControl* >( object ) ) return setImplicitValue( control, m_value ); if ( auto window = qobject_cast< QskWindow* >( object ) ) return setImplicitValue( window, m_value ); return !setProperty( object, m_propertyName.constData(), m_value ); } bool visitUp( const QObject* object ) override final { if ( isRoot( object ) ) return true; if ( auto control = qobject_cast< const QskControl* >( object ) ) { m_value = value( control ); return true; } if ( auto window = qobject_cast< const QskWindow* >( object ) ) { m_value = value( window ); return true; } return getProperty( object, m_propertyName, m_value ); } private: inline bool getProperty( const QObject* object, const char* name, T& value ) const { if ( !m_propertyName.isEmpty() ) { const QVariant v = object->property( name ); if ( v.canConvert< T >() ) { value = qvariant_cast< T >( v ); return true; } } return false; } inline bool setProperty( QObject* object, const char* name, const T& value ) const { T oldValue; if ( !getProperty( object, name, oldValue ) || oldValue == value ) return false; object->setProperty( name, value ); return true; } virtual bool setImplicitValue( QskControl*, const T& ) = 0; virtual bool setImplicitValue( QskWindow*, const T& ) = 0; virtual T value( const QskControl* ) const = 0; virtual T value( const QskWindow* ) const = 0; private: const QByteArray m_propertyName; T m_value; }; } #endif
[ "Uwe.Rathmann@tigertal.de" ]
Uwe.Rathmann@tigertal.de
4cf80ee9495418a54a96c7f7e98d73f9ef713898
60393750e9c3f3b8ab42d6326fe9eca4ee349b47
/SNAPLib/IntersectingPairedEndAligner.h
4cd3b68157bae80a8021c1797da5f56035a466aa
[ "Apache-2.0" ]
permissive
andrewmagis/snap-rnaseq
5ee9f33ef63539d1f225899971247ac5170e1bdc
458e648f570466e2c702a4c349d11f16e1ee4eac
refs/heads/master
2021-01-10T19:43:26.311446
2013-12-06T03:14:18
2013-12-06T03:14:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,841
h
/*++ Module Name: IntersectingPairedEndAligner.h Abstract: A paired-end aligner based on set intersections to narrow down possible candidate locations. Authors: Bill Bolosky, February, 2013 Environment: User mode service. Revision History: --*/ #pragma once #include "PairedEndAligner.h" #include "BaseAligner.h" #include "BigAlloc.h" #include "directions.h" #include "LandauVishkin.h" #include "FixedSizeMap.h" const unsigned DEFAULT_INTERSECTING_ALIGNER_MAX_HITS = 16000; const unsigned DEFAULT_MAX_CANDIDATE_POOL_SIZE = 1000000; class IntersectingPairedEndAligner : public PairedEndAligner { public: IntersectingPairedEndAligner( GenomeIndex *index_, unsigned maxReadSize_, unsigned maxHits_, unsigned maxK_, unsigned maxSeedsFromCommandLine_, double seedCoverage_, unsigned minSpacing_, // Minimum distance to allow between the two ends. unsigned maxSpacing_, // Maximum distance to allow between the two ends. unsigned maxBigHits_, unsigned extraSearchDepth_, unsigned maxCandidatePoolSize, BigAllocator *allocator); void setLandauVishkin( LandauVishkin<1> *landauVishkin_, LandauVishkin<-1> *reverseLandauVishkin_) { landauVishkin = landauVishkin_; reverseLandauVishkin = reverseLandauVishkin_; } virtual ~IntersectingPairedEndAligner(); virtual void align( Read *read0, Read *read1, PairedAlignmentResult *result); static size_t getBigAllocatorReservation(GenomeIndex * index, unsigned maxBigHitsToConsider, unsigned maxReadSize, unsigned seedLen, unsigned maxSeedsFromCommandLine, double seedCoverage, unsigned maxEditDistanceToConsider, unsigned maxExtraSearchDepth, unsigned maxCandidatePoolSize); virtual _int64 getLocationsScored() const { return nLocationsScored; } private: IntersectingPairedEndAligner() {} // This is for the counting allocator, it doesn't build a useful object static const int NUM_SET_PAIRS = 2; // A "set pair" is read0 FORWARD + read1 RC, or read0 RC + read1 FORWARD. Again, it doesn't make sense to change this. void allocateDynamicMemory(BigAllocator *allocator, unsigned maxReadSize, unsigned maxBigHitsToConsider, unsigned maxSeedsToUse, unsigned maxEditDistanceToConsider, unsigned maxExtraSearchDepth, unsigned maxCandidatePoolSize); GenomeIndex * index; const Genome * genome; unsigned genomeSize; unsigned maxReadSize; unsigned maxHits; unsigned maxBigHits; unsigned extraSearchDepth; unsigned maxK; unsigned numSeedsFromCommandLine; double seedCoverage; static const unsigned MAX_MAX_SEEDS = 30; unsigned minSpacing; unsigned maxSpacing; unsigned seedLen; unsigned maxMergeDistance; _int64 nLocationsScored; struct HashTableLookup { unsigned seedOffset; unsigned nHits; const unsigned *hits; unsigned whichDisjointHitSet; // // We keep the hash table lookups that haven't been exhaused in a circular list. // HashTableLookup *nextLookupWithRemainingMembers; HashTableLookup *prevLookupWithRemainingMembers; // // State for handling the binary search of a location in this lookup. // This would ordinarily be stack local state in the binary search // routine, but because a) we want to interleave the steps of the binary // search in order to allow cache prefetches to have time to execute; // and b) we don't want to do dynamic memory allocation (really at all), // it gets stuck here. // int limit[2]; // The upper and lower limits of the current binary search in hits unsigned maxGenomeOffsetToFindThisSeed; // // A linked list of lookups that haven't yet completed this binary search. This is a linked // list with no header element, so testing for emptiness needs to happen at removal time. // It's done that way to avoid a comparison for list head that would result in a hard-to-predict // branch. // HashTableLookup *nextLookupForCurrentBinarySearch; HashTableLookup *prevLookupForCurrentBinarySearch; unsigned currentHitForIntersection; }; // // A set of seed hits, represented by the lookups that came out of the big hash table. // class HashTableHitSet { public: HashTableHitSet() {} void firstInit(unsigned maxSeeds_, unsigned maxMergeDistance_); // // Reset to empty state. // void init(); // // Record a hash table lookup. All recording must be done before any // calls to getNextHitLessThanOrEqualTo. A disjoint hit set is a set of hits // that don't share any bases in the read. This is interesting because the edit // distance of a read must be at least the number of seeds that didn't hit for // any disjoint hit set (because there must be a difference in the read within a // seed for it not to hit, and since the reads are disjoint there can't be a case // where the same difference caused two seeds to miss). // void recordLookup(unsigned seedOffset, unsigned nHits, const unsigned *hits, bool beginsDisjointHitSet); // // This efficiently works through the set looking for the next hit at or below this address. // A HashTableHitSet only allows a single iteration through its address space per call to // init(). // bool getNextHitLessThanOrEqualTo(unsigned maxGenomeOffsetToFind, unsigned *actualGenomeOffsetFound, unsigned *seedOffsetFound); // // Walk down just one step, don't binary search. // bool getNextLowerHit(unsigned *genomeLocation, unsigned *seedOffsetFound); // // Find the highest genome address. // bool getFirstHit(unsigned *genomeLocation, unsigned *seedOffsetFound); unsigned computeBestPossibleScoreForCurrentHit(); private: struct DisjointHitSet { unsigned countOfExhaustedHits; unsigned missCount; }; int currentDisjointHitSet; DisjointHitSet *disjointHitSets; HashTableLookup *lookups; HashTableLookup lookupListHead[1]; unsigned maxSeeds; unsigned nLookupsUsed; unsigned mostRecentLocationReturned; unsigned maxMergeDistance; }; HashTableHitSet *hashTableHitSets[NUM_READS_PER_PAIR][NUM_DIRECTIONS]; unsigned countOfHashTableLookups[NUM_READS_PER_PAIR]; unsigned totalHashTableHits[NUM_READS_PER_PAIR][NUM_DIRECTIONS]; unsigned largestHashTableHit[NUM_READS_PER_PAIR][NUM_DIRECTIONS]; unsigned readWithMoreHits; unsigned readWithFewerHits; // // A location that's been scored (or waiting to be scored). This is needed in order to do merging // of close-together hits and to track potential mate pairs. // struct HitLocation { unsigned genomeLocation; int genomeLocationOffset; // This is needed because we might get an offset back from scoring (because it's really scoring a range). unsigned seedOffset; bool isScored; // Mate pairs are sometimes not scored when they're inserted, because they unsigned score; unsigned maxK; // The maxK that this was scored with (we may need to rescore if we need a higher maxK and score is -1) double matchProbability; unsigned bestPossibleScore; // // We have to be careful in the case where lots of offsets in a row match well against the read (think // about repetitive short sequences, i.e., ATTATTATTATT...). We want to merge the close ones together, // but if the repetitive sequence extends longer than maxMerge, we don't want to just slide the window // over the whole range and declare it all to be one. There is really no good definition for the right // thing to do here, so instead all we do is that when we declare two candidates to be matched we // pick one of them to be the match primary and then coalesce all matches that are within maxMatchDistance // of the match primary. No one can match with any of the locations in the set that's beyond maxMatchDistance // from the set primary. This means that in the case of repetitve sequences that we'll declare locations // right next to one another not to be matches. There's really no way around this while avoiding // matching things that are possibly much more than maxMatchDistance apart. // unsigned genomeLocationOfNearestMatchedCandidate; }; class HitLocationRingBuffer { public: HitLocationRingBuffer(unsigned bufferSize_) : bufferSize(bufferSize_), head(0), tail(0) { buffer = new HitLocation[bufferSize]; } ~HitLocationRingBuffer() { delete [] buffer; } bool isEmpty() {return head == tail;} void insertHead(unsigned genomeLocation, unsigned seedOffset, unsigned bestPossibleScore) { _ASSERT((head + 1 ) % bufferSize != tail); // Not overflowing _ASSERT(head == tail || genomeLocation < buffer[(head + bufferSize - 1)%bufferSize].genomeLocation); // Inserting in strictly descending order buffer[head].genomeLocation = genomeLocation; buffer[head].seedOffset = seedOffset; buffer[head].isScored = false; buffer[head].genomeLocationOfNearestMatchedCandidate = 0xffffffff; buffer[head].bestPossibleScore = bestPossibleScore; head = (head + 1) % bufferSize; } void insertHead(unsigned genomeLocation, unsigned seedOffset, unsigned score, double matchProbability) { insertHead(genomeLocation, seedOffset, score); HitLocation *insertedLocation = &buffer[(head + bufferSize - 1)%bufferSize]; insertedLocation->isScored = true; insertedLocation->score = score; insertedLocation->matchProbability = matchProbability; } void clear() { head = tail = 0; } void trimAboveLocation(unsigned highestGenomeLocatonToKeep) { for (; tail != head && buffer[tail].genomeLocation > highestGenomeLocatonToKeep; tail = (tail + 1) % bufferSize) { // This loop body intentionally left blank. } } HitLocation *getTail(unsigned *index) { if (head == tail) return NULL; *index = tail; return &buffer[tail]; } HitLocation *getTail() { if (head == tail) return NULL; return &buffer[tail]; } HitLocation *getHead() { if (head == tail) return NULL; // // Recall that head is the next place to write, so it's not filled in yet. // Use the previous element. // return &buffer[(head + bufferSize - 1)% bufferSize]; } HitLocation *getNext(unsigned *index) // Working from tail to head { if ((*index + 1) % bufferSize == head) return NULL; *index = (*index + 1) % bufferSize; return &buffer[*index]; } private: unsigned bufferSize; unsigned head; unsigned tail; HitLocation *buffer; }; char *rcReadData[NUM_READS_PER_PAIR]; // the reverse complement of the data for each read char *rcReadQuality[NUM_READS_PER_PAIR]; // the reversed quality strings for each read unsigned readLen[NUM_READS_PER_PAIR]; Read *reads[NUM_READS_PER_PAIR][NUM_DIRECTIONS]; // These are the reads that are provided in the align call, together with their reverse complements, which are computed. Read rcReads[NUM_READS_PER_PAIR][NUM_DIRECTIONS]; char *reversedRead[NUM_READS_PER_PAIR][NUM_DIRECTIONS]; // The reversed data for each read for forward and RC. This is used in the backwards LV LandauVishkin<> *landauVishkin; LandauVishkin<-1> *reverseLandauVishkin; char rcTranslationTable[256]; unsigned nTable[256]; BYTE *seedUsed; inline bool IsSeedUsed(unsigned indexInRead) const { return (seedUsed[indexInRead / 8] & (1 << (indexInRead % 8))) != 0; } inline void SetSeedUsed(unsigned indexInRead) { seedUsed[indexInRead / 8] |= (1 << (indexInRead % 8)); } // // "Local probability" means the probability that each end is correct given that the pair itself is correct. // Consider the example where there's exactly one decent match for one read, but the other one has several // that are all within the correct range for the first one. Then the local probability for the second read // is lower than the first. The overall probability of an alignment then is // pairProbability * localProbability/ allPairProbability. // double localBestPairProbability[NUM_READS_PER_PAIR]; void scoreLocation( unsigned whichRead, Direction direction, unsigned genomeLocation, unsigned seedOffset, unsigned scoreLimit, unsigned *score, double *matchProbability, int *genomeLocationOffset // The computed offset for genomeLocation (which is needed because we scan several different possible starting locations) ); // // These are used to keep track of places where we should merge together candidate locations for MAPQ purposes, because they're sufficiently // close in the genome. // struct MergeAnchor { double matchProbability; unsigned locationForReadWithMoreHits; unsigned locationForReadWithFewerHits; int pairScore; void init(unsigned locationForReadWithMoreHits_, unsigned locationForReadWithFewerHits_, double matchProbability_, int pairScore_) { locationForReadWithMoreHits = locationForReadWithMoreHits_; locationForReadWithFewerHits = locationForReadWithFewerHits_; matchProbability = matchProbability_; pairScore = pairScore_; } // // Returns whether this candidate is a match for this merge anchor. // bool doesRangeMatch(unsigned newMoreHitLocation, unsigned newFewerHitLocation) { unsigned deltaMore = DistanceBetweenGenomeLocations(locationForReadWithMoreHits, newMoreHitLocation); unsigned deltaFewer = DistanceBetweenGenomeLocations(locationForReadWithFewerHits, newFewerHitLocation); return deltaMore < 50 && deltaFewer < 50; } // // Returns true and sets oldMatchProbability if this should be eliminated due to a match. // bool checkMerge(unsigned newMoreHitLocation, unsigned newFewerHitLocation, double newMatchProbability, int newPairScore, double *oldMatchProbability); }; // // We keep track of pairs of locations to score using two structs, one for each end. The ends for the read with fewer hits points into // a list of structs for the end with more hits, so that we don't need one stuct for each pair, just one for each end, and also so that // we don't need to score the mates more than once if they could be paired with more than one location from the end with fewer hits. // struct ScoringMateCandidate { // // These are kept in arrays in decreasing genome order, one for each set pair, so you can find the next largest location by just looking one // index lower, and vice versa. // double matchProbability; unsigned readWithMoreHitsGenomeLocation; unsigned bestPossibleScore; unsigned score; unsigned scoreLimit; // The scoreLimit with which score was computed unsigned seedOffset; int genomeOffset; void init(unsigned readWithMoreHitsGenomeLocation_, unsigned bestPossibleScore_, unsigned seedOffset_) { readWithMoreHitsGenomeLocation = readWithMoreHitsGenomeLocation_; bestPossibleScore = bestPossibleScore_; seedOffset = seedOffset_; score = -2; scoreLimit = -1; matchProbability = 0; genomeOffset = 0; } }; struct ScoringCandidate { ScoringCandidate * scoreListNext; // This is a singly-linked list MergeAnchor * mergeAnchor; unsigned scoringMateCandidateIndex; // Index into the array of scoring mate candidates where we should look unsigned readWithFewerHitsGenomeLocation; unsigned whichSetPair; unsigned seedOffset; unsigned bestPossibleScore; void init(unsigned readWithFewerHitsGenomeLocation_, unsigned whichSetPair_, unsigned scoringMateCandidateIndex_, unsigned seedOffset_, unsigned bestPossibleScore_, ScoringCandidate *scoreListNext_) { readWithFewerHitsGenomeLocation = readWithFewerHitsGenomeLocation_; whichSetPair = whichSetPair_; _ASSERT(whichSetPair < NUM_SET_PAIRS); // You wouldn't think this would be necessary, but... scoringMateCandidateIndex = scoringMateCandidateIndex_; seedOffset = seedOffset_; bestPossibleScore = bestPossibleScore_; scoreListNext = scoreListNext_; mergeAnchor = NULL; } }; // // A pool of scoring candidates. For each alignment call, we free them all by resetting lowestFreeScoringCandidatePoolEntry to 0, // and then fill in the content when they're initialized. This means that for alignments with few candidates we'll be using the same // entries over and over, so they're likely to be in the cache. We have maxK * maxSeeds * 2 of these in the pool, so we can't possibly run // out. We rely on their being allocated in descending genome order within a set pair. // ScoringCandidate *scoringCandidatePool; unsigned scoringCandidatePoolSize; unsigned lowestFreeScoringCandidatePoolEntry; // // maxK + 1 lists of Scoring Candidates. The lists correspond to bestPossibleScore for the candidate and its best mate. // ScoringCandidate **scoringCandidates; // // The scoring mates. The each set scoringCandidatePoolSize / 2. // ScoringMateCandidate * scoringMateCandidates[NUM_SET_PAIRS]; unsigned lowestFreeScoringMateCandidate[NUM_SET_PAIRS]; // // Merge anchors. Again, we allocate an upper bound number of them, which is the same as the number of scoring candidates. // MergeAnchor *mergeAnchorPool; unsigned firstFreeMergeAnchor; unsigned mergeAnchorPoolSize; };
[ "andrewmagis@gmail.com" ]
andrewmagis@gmail.com
b68ffa9dc5e63aca319ea88f7ce0d91b23250c26
aade1e73011f72554e3bd7f13b6934386daf5313
/Contest/Opencup/XIX/Korea/H.cpp
2ae3479cedb7e9629eb07c4af479d8dc40f64738
[]
no_license
edisonhello/waynedisonitau123
3a57bc595cb6a17fc37154ed0ec246b145ab8b32
48658467ae94e60ef36cab51a36d784c4144b565
refs/heads/master
2022-09-21T04:24:11.154204
2022-09-18T15:23:47
2022-09-18T15:23:47
101,478,520
34
6
null
null
null
null
UTF-8
C++
false
false
1,061
cpp
#include <bits/stdc++.h> using namespace std; int main() { long long a, b, c, d; scanf("%lld%lld%lld%lld", &a, &b, &c, &d); long long ans = 0; for (int i = 1; i < 1000; ++i) { for (int j = 1; j < 1000; ++j) { if (i + j >= 1000) continue; if (__gcd(i, j) != 1) continue; // printf("i = %d j = %d\n", i, j); long long fi = a / i; if (i * fi < a) ++fi; if (i * fi > b) continue; long long fj = c / j; if (j * fj < c) ++fj; if (j * fj > d) continue; // printf("fi = %lld fj = %lld\n", fi, fj); long long si = (b + i - 1) / i; if (i * si > b) --si; assert(i * si <= b && i * si >= a); long long sj = (d + j - 1) / j; if (j * sj > d) --sj; assert(j * sj <= d && j * sj >= c); long long l = max(fi, fj), r = min(si, sj); if (l > r) continue; ans += r - l + 1; } } printf("%lld\n", ans); return 0; }
[ "tu.da.wei@gmail.com" ]
tu.da.wei@gmail.com
cf078d92b91b8155ff6d405d2220ffe37943b00f
084341e3b0d6925d7bdac906d9f9bb309d9d34f2
/trees/lib/binary_search_tree.h
2d02db78e111303124a63cbbd567e47ded04b2ee
[]
no_license
onufriievkyrylo/diploma
f9110d834c0f01d7f630a8baf26e083ad6c28f21
ef535d54968f51cbfcc6d8122021d24b60b8290b
refs/heads/master
2020-03-29T21:29:56.698942
2019-03-10T10:37:56
2019-03-10T10:37:56
150,370,105
0
0
null
null
null
null
UTF-8
C++
false
false
2,739
h
#ifndef BINARY_SEARCH_TREE_LIB_H_ #define BINARY_SEARCH_TREE_LIB_H_ #include <string> #include <iostream> typedef double data_t; struct BinaryTreeNode { BinaryTreeNode* left = nullptr; BinaryTreeNode* right = nullptr; data_t data; BinaryTreeNode(const data_t& data) : data(data), left(nullptr), right(nullptr) { } }; BinaryTreeNode* bst_get_min_node(BinaryTreeNode* root) { return root->left ? bst_get_min_node(root->left) : root; } BinaryTreeNode* bst_internal_add(BinaryTreeNode* root, const data_t& data) { if (root == nullptr) { return new BinaryTreeNode(data); } else if (root->data > data) { root->right = bst_internal_add(root->right, data); } else if (root->data < data) { root->left = bst_internal_add(root->left, data); } return root; } void bst_add(BinaryTreeNode* &root, const data_t& data) { root = bst_internal_add(root, data); } BinaryTreeNode* bst_internal_remove(BinaryTreeNode* root, const data_t& data) { if (root == nullptr) { return root; } else if (root->data > data) { root->right = bst_internal_remove(root, data); } else if (root->data < data) { root->left = bst_internal_remove(root->left, data); } else { if (root->left == nullptr) { BinaryTreeNode* temp = root->right; delete root; return temp; } else if (root->right == nullptr) { BinaryTreeNode* temp = root->left; delete root; return temp; } BinaryTreeNode* temp = bst_get_min_node(root->right); root->data = temp->data; root->right = bst_internal_remove(root->right, temp->data); } } void bst_remove(BinaryTreeNode* &root, const data_t& data) { root = bst_internal_remove(root, data); } void bst_breadth_search(BinaryTreeNode* root) { const int max_queue_size = 500; int queue_front = 0; int queue_back = 0; int* levels = new int[max_queue_size]; BinaryTreeNode** queue = new BinaryTreeNode*[max_queue_size]; levels[queue_back] = 1; queue[queue_back++] = root; while (queue_front != queue_back) { int level = levels[queue_front]; BinaryTreeNode* temp = queue[queue_front++]; std::cout << std::string(level, '=') << " " << temp->data << std::endl; if (temp->left) { levels[queue_back] = level + 1; queue[queue_back++] = temp->left; } if (temp->right) { levels[queue_back] = level + 1; queue[queue_back++] = temp->right; } } delete[] queue; } void bst_depth_search(BinaryTreeNode* root, int level = 1) { if (root->left) { bst_depth_search(root->left, level + 1); } std::cout << std::string(level, '=') << " " << root->data << std::endl; if (root->right) { bst_depth_search(root->right, level + 1); } } #endif //BINARY_SEARCH_TREE_LIB_H_
[ "kyrylo.onufriiev@gmail.com" ]
kyrylo.onufriiev@gmail.com
bf431f4e0c60d0d2a97442d5cfe2bc89663dda0c
ac9b294ed1b27504f1468ff0ac7a82eb982cf8d0
/eGENIEPaperCode/treeProducer_simulation_save.cpp
638442a244dd4abf88853f20094ec03df47b8760
[]
no_license
afropapp13/e4nu
d8f1073d630745e61842587891ca5fd04bc6a5e8
8cb00a1ee852648ac8a7ac79cde461cb2217eca5
refs/heads/master
2023-06-24T23:37:21.926850
2022-03-02T17:09:12
2022-03-02T17:09:12
198,716,604
0
0
null
2019-07-24T22:15:24
2019-07-24T22:15:24
null
UTF-8
C++
false
false
15,778
cpp
#define treeProducer_simulation_cxx #include "treeProducer_simulation.h" #include <TH2.h> #include <TStyle.h> #include <TCanvas.h> #include <TH1D.h> #include <TFile.h> #include <iomanip> #include <TString.h> #include <TMath.h> #include <TVector3.h> #include <TLorentzVector.h> #include <sstream> #include <iostream> #include <vector> #include <iterator> using namespace std; void treeProducer_simulation::Loop() { if (fChain == 0) return; Long64_t nentries = fChain->GetEntriesFast(); TH1D::SetDefaultSumw2(); TH2D::SetDefaultSumw2(); // ------------------------------------------------------------------------------- // Binding Energy double BE = 0.02; // GeV // ------------------------------------------------------------------------------- TString FileName = "myFiles/"+fNucleus+"_"+fEnergy+"_"+fTune+"_"+fInteraction+".root"; TFile* file = new TFile(FileName,"recreate"); std::cout << std::endl << "File " << FileName << " will be created" << std::endl << std::endl; const double ProtonMass = .9383, MuonMass = .106, NeutronMass = 0.9396, ElectronMass = 0.000511; // [GeV] int MissMomentumBin = 99; // ------------------------------------------------------------------------------- // Ranges & Binning int NBinsQ2 = 56; double MinQ2 = 0.1, MaxQ2 = 1.5; TString TitleQ2 = ";Q^{2} [GeV^{2}/c^{2}];"; int NBinsxB = 25; double MinxB = 0.7, MaxxB = 1.3; TString TitlexB = ";x_{B};"; int NBinsnu = 50; double Minnu = 0., Maxnu = 1.2; TString Titlenu = ";Energy Transfer [GeV];"; int NBinsW = 20; double MinW = 0.7, MaxW = 1.2; TString TitleW = ";W (GeV/c^{2});"; int NBinsPmiss = 40; double MinPmiss = 0., MaxPmiss = 1.; TString TitlePmiss = ";P_{T} [GeV/c];"; int NBinsPionMulti = 4; double MinPionMulti = -0.5, MaxPionMulti = 3.5; TString TitlePionMulti = ";Pion Multiplicity;"; int NBinsReso = 30; double MinReso = -50., MaxReso = 10.; TString TitleReso = ";#frac{E^{cal} - E^{beam}}{E^{beam}} (%);"; int NBinsDeltaPhiT = 18; double MinDeltaPhiT = 0., MaxDeltaPhiT = 80.; TString TitleDeltaPhiT = ";#delta#phi_{T} (degrees);"; int NBinsDeltaAlphaT = 18; double MinDeltaAlphaT = 0., MaxDeltaAlphaT = 180.; TString TitleDeltaAlphaT = ";#delta#alpha_{T} (degrees);"; TString TitleQ2Vsnu = ";Energy Transfer [GeV];Q^{2} [GeV^{2}/c^{2}];"; TString TitleQ2VsW = ";W [GeV/c^{2}];Q^{2} [GeV^{2}/c^{2}];"; // ------------------------------------------------------------------------------- // Electron int NBinsElectronEnergy = 40; double MinElectronEnergy = 0., MaxElectronEnergy = 1.2; TString TitleElectronEnergy = ";E_{e'} (GeV);"; int NBinsElectronPhi = 45; double MinElectronPhi = 0., MaxElectronPhi = 360.; TString TitleElectronPhi = ";#phi_{e'} (degrees);"; int NBinsElectronTheta = 15; double MinElectronTheta = 15., MaxElectronTheta = 53.; TString TitleElectronTheta = ";#theta_{e'} (degrees);"; int NBinsElectronCosTheta = 40; double MinElectronCosTheta = -1, MaxElectronCosTheta = 1.; TString TitleElectronCosTheta = ";cos(#theta_{e'});"; int NBinsElectronMom = 40; double MinElectronMom = 1.7, MaxElectronMom = 4.; TString TitleElectronMom = ";P_{e'} (GeV/c);"; TString TitleElectronPhiVsTheta = ";#phi_{e'} (degrees);#theta_{e'} (degrees);"; // ------------------------------------------------------------------------------- // Proton int NBinsEp = 40; double MinEp = 0.9, MaxEp = 2.2; TString TitleEp = ";E_{p} (GeV);"; int NBinsProtonPhi = 45; double MinProtonPhi = 0., MaxProtonPhi = 360.; TString TitleProtonPhi = ";#phi_{p} (degrees);"; int NBinsProtonTheta = 30; double MinProtonTheta = 10., MaxProtonTheta = 120.; TString TitleProtonTheta = ";#theta_{p} (degrees);"; int NBinsProtonCosTheta = 40; double MinProtonCosTheta = -0.2, MaxProtonCosTheta = 1.; TString TitleProtonCosTheta = ";cos(#theta_{p});"; TString TitleProtonEnergyVsMissMomentum = ";P_{T} (GeV/c);E_{p} (GeV);"; TString TitleQ2VsMissMomentum = ";P_{T} (GeV/c);Q^{2} (GeV^{2}/c^{2});"; // ------------------------------------------------------------------------------- TH1D* Q2Plot = new TH1D("Q2Plot",TitleQ2,NBinsQ2,MinQ2,MaxQ2); TH1D* xBPlot = new TH1D("xBPlot",TitlexB,NBinsxB,MinxB,MaxxB); TH1D* nuPlot = new TH1D("nuPlot",Titlenu,NBinsnu,Minnu,Maxnu); TH1D* WPlot = new TH1D("WPlot",TitleW,NBinsW,MinW,MaxW); TH1D* MissMomentumPlot = new TH1D("MissMomentumPlot",TitlePmiss,NBinsPmiss,MinPmiss,MaxPmiss); TH1D* PionMultiPlot = new TH1D("PionMultiPlot",TitlePionMulti,NBinsPionMulti,MinPionMulti,MaxPionMulti); TH1D* PionMultiQEPlot = new TH1D("PionMultiQEPlot",TitlePionMulti,NBinsPionMulti,MinPionMulti,MaxPionMulti); TH2D* Q2VsnuPlot = new TH2D("Q2VsnuPlot",TitleQ2Vsnu,NBinsnu,Minnu,Maxnu,NBinsQ2,MinQ2,MaxQ2); TH2D* Q2VsWPlot = new TH2D("Q2VsWPlot",TitleQ2VsW,NBinsW,MinW,MaxW,NBinsQ2,MinQ2,MaxQ2); // Electron TH1D* ElectronEnergyPlot = new TH1D("ElectronEnergyPlot",TitleElectronEnergy,NBinsElectronEnergy,MinElectronEnergy,MaxElectronEnergy); TH1D* ElectronPhiPlot = new TH1D("ElectronPhiPlot",TitleElectronPhi,NBinsElectronPhi,MinElectronPhi,MaxElectronPhi); TH1D* ElectronThetaPlot = new TH1D("ElectronThetaPlot",TitleElectronTheta,NBinsElectronTheta,MinElectronTheta,MaxElectronTheta); TH1D* ElectronCosThetaPlot = new TH1D("ElectronCosThetaPlot",TitleElectronCosTheta,NBinsElectronCosTheta,MinElectronCosTheta,MaxElectronCosTheta); TH2D* ElectronPhiThetaPlot = new TH2D("ElectronPhiThetaPlot",TitleElectronPhiVsTheta,NBinsElectronPhi,MinElectronPhi,MaxElectronPhi,NBinsElectronTheta,MinElectronTheta,MaxElectronTheta); // Proton TH1D* ProtonEnergyPlot = new TH1D("ProtonEnergyPlot",TitleEp,NBinsEp,MinEp,MaxEp); TH1D* ProtonPhiPlot = new TH1D("ProtonPhiPlot",TitleProtonPhi,NBinsProtonPhi,MinProtonPhi,MaxProtonPhi); TH1D* ProtonThetaPlot = new TH1D("ProtonThetaPlot",TitleProtonTheta,NBinsProtonTheta,MinProtonTheta,MaxProtonTheta); TH1D* ProtonCosThetaPlot = new TH1D("ProtonCosThetaPlot",TitleProtonCosTheta,NBinsProtonCosTheta,MinProtonCosTheta,MaxProtonCosTheta); TH1D* EcalResoPlot = new TH1D("EcalResoPlot",TitleReso,NBinsReso,MinReso,MaxReso); TH2D* EpVsMissMomentumPlot = new TH2D("EpVsMissMomentumPlot",TitleProtonEnergyVsMissMomentum,NBinsPmiss,MinPmiss,MaxPmiss,NBinsEp,MinEp,MaxEp); TH2D* Q2VsMissMomentumPlot = new TH2D("Q2VsMissMomentumPlot",TitleQ2VsMissMomentum,NBinsPmiss,MinPmiss,MaxPmiss,NBinsQ2,MinQ2,MaxQ2); TH1D* DeltaPhiTPlot = new TH1D("DeltaPhiTPlot",TitleDeltaPhiT,NBinsDeltaPhiT,MinDeltaPhiT,MaxDeltaPhiT); TH1D* DeltaAlphaTPlot = new TH1D("DeltaAlphaTPlot",TitleDeltaAlphaT,NBinsDeltaAlphaT,MinDeltaAlphaT,MaxDeltaAlphaT); // ------------------------------------------------------------------------------------- int NBinsCalorimetricEnergy = 400; double MinCalorimetricEnergy = 0.,MaxCalorimetricEnergy = 6.; TString TitleCalorimetricEnergy = ";E^{cal} (GeV);"; TH1D* epRecoEnergy_slice_0Plot = new TH1D("epRecoEnergy_slice_0Plot",TitleCalorimetricEnergy,NBinsCalorimetricEnergy,MinCalorimetricEnergy,MaxCalorimetricEnergy); TH1D* epRecoEnergy_slice_1Plot = new TH1D("epRecoEnergy_slice_1Plot",TitleCalorimetricEnergy,NBinsCalorimetricEnergy,MinCalorimetricEnergy,MaxCalorimetricEnergy); TH1D* epRecoEnergy_slice_2Plot = new TH1D("epRecoEnergy_slice_2Plot",TitleCalorimetricEnergy,NBinsCalorimetricEnergy,MinCalorimetricEnergy,MaxCalorimetricEnergy); TH1D* epRecoEnergy_slice_3Plot = new TH1D("epRecoEnergy_slice_3Plot",TitleCalorimetricEnergy,NBinsCalorimetricEnergy,MinCalorimetricEnergy,MaxCalorimetricEnergy); int NBinsLeptonicEnergy = 200; double MinLeptonicEnergy = 0.,MaxLeptonicEnergy = 6.; TString TitleLeptonicEnergy = ";E^{QE} (GeV);"; TH1D* eRecoEnergy_slice_0Plot = new TH1D("eRecoEnergy_slice_0Plot",TitleLeptonicEnergy,NBinsLeptonicEnergy,MinLeptonicEnergy,MaxLeptonicEnergy); TH1D* eRecoEnergy_slice_1Plot = new TH1D("eRecoEnergy_slice_1Plot",TitleLeptonicEnergy,NBinsLeptonicEnergy,MinLeptonicEnergy,MaxLeptonicEnergy); TH1D* eRecoEnergy_slice_2Plot = new TH1D("eRecoEnergy_slice_2Plot",TitleLeptonicEnergy,NBinsLeptonicEnergy,MinLeptonicEnergy,MaxLeptonicEnergy); TH1D* eRecoEnergy_slice_3Plot = new TH1D("eRecoEnergy_slice_3Plot",TitleLeptonicEnergy,NBinsLeptonicEnergy,MinLeptonicEnergy,MaxLeptonicEnergy); // ------------------------------------------------------------------------------------------------------------- // 2D Inclusive Plots TH2D* QE_Q0_Q3_Plot = new TH2D("QE_Q0_Q3_Plot",";q_{3} [GeV/c];q_{0} [GeV]",200,0,2.,200,0.,2.); TH2D* MEC_Q0_Q3_Plot = new TH2D("MEC_Q0_Q3_Plot",";q_{3} [GeV/c];q_{0} [GeV]",200,0,2.,200,0.,2.); // ------------------------------------------------------------------------------------------------------------- int countEvents = 0; Long64_t nbytes = 0, nb = 0; // ------------------------------------------------------------------------------------------------------------- for (Long64_t jentry=0; jentry<nentries;jentry++) { Long64_t ientry = LoadTree(jentry); if (ientry < 0) break; nb = fChain->GetEntry(jentry); nbytes += nb; if (jentry%1000 == 0) std::cout << jentry/1000 << " k " << std::setprecision(3) << double(jentry)/nentries*100. << " %"<< std::endl; // ------------------------------------------------------------------------------------------ double Ebeam = 1.161; /* if (W > 2) { continue; } if (fEnergy == "1161") { if (Q2 < 0.1) { continue; } if (El < 0.4) { continue; } } if (fEnergy == "2261") { if (Q2 < 0.4) { continue; } if (El < 0.55) { continue; } Ebeam = 2.261; } if (fEnergy == "4461") { if (Q2 < 0.8) { continue; } if (El < 1.1) { continue; } Ebeam = 4.461; } */ // ------------------------------------------------------------------------------------------ int ProtonTagging = 0, ChargedPionPlusTagging = 0, ChargedPionMinusTagging = 0, GammaTagging = 0, NeutralPionTagging = 0; vector <int> ProtonID; ProtonID.clear(); for (int i = 0; i < nf; i++) { if (pdgf[i] == 2212 && pf[i] > 0.3) { ProtonTagging ++; ProtonID.push_back(i); } if (pdgf[i] == 211 && pf[i] > 0.15) { ChargedPionPlusTagging ++; } if (pdgf[i] == -211 && pf[i] > 0.15) { ChargedPionMinusTagging ++; } if (pdgf[i] == 22 && pf[i] > 0.3) { GammaTagging ++; } if (pdgf[i] == 111 && pf[i] > 0.5) { NeutralPionTagging ++; } } // ------------------------------------------------------------------------------------- /* if (ProtonTagging != 1) { continue; } if (ChargedPionPlusTagging != 0) { continue; } if (ChargedPionMinusTagging != 0) { continue; } if (GammaTagging != 0) { continue; } if (NeutralPionTagging != 0) { continue; } */ // ------------------------------------------------------------------------------------- TLorentzVector ProbeV4(pxv,pyv,pzv,Ev); TLorentzVector ElectronV4(pxl,pyl,pzl,El); double ElectronMom = ElectronV4.Rho(); double ElectronTheta = ElectronV4.Theta()*180./TMath::Pi(); if (ElectronTheta < 0) { ElectronTheta += 180.;} if (ElectronTheta > 180) { ElectronTheta -= 180.;} double ElectronCosTheta = ElectronV4.CosTheta(); double ElectronPhi = ElectronV4.Phi()*180./TMath::Pi(); if (ElectronPhi < 0) { ElectronPhi += 360.;} if (ElectronPhi > 360) { ElectronPhi -= 360.;} TLorentzVector qV4 = ProbeV4 - ElectronV4; double nu = qV4.E(); double q3 = qV4.Rho(); // QE Energy Reconstruction double EQE = (2*ProtonMass*BE + 2*ProtonMass*El - pow(ElectronMass,2)) / 2 / (ProtonMass - El + ElectronMom * ElectronCosTheta); // ----------------------------------------------------------------------------------------------------- /* // Proton TLorentzVector ProtonV4(pxf[ProtonID[0]],pyf[ProtonID[0]],pzf[ProtonID[0]],Ef[ProtonID[0]]); double ProtonE = ProtonV4.E(); double ProtonMom = ProtonV4.Rho(); double ProtonTheta = ProtonV4.Theta()*180./TMath::Pi(); if (ProtonTheta < 0) { ProtonTheta += 180.; } if (ProtonTheta > 180) { ProtonTheta -= 180.; } double ProtonCosTheta = ProtonV4.CosTheta(); double ProtonPhi = ProtonV4.Phi()*180./TMath::Pi(); if (ProtonPhi < 0) { ProtonPhi += 360; } if (ProtonPhi > 360) { ProtonPhi -= 360; } // Calorimetric Energy Reconstruction double Ecal = El + ProtonE - ProtonMass + BE; // Transverse variables TVector3 ProtonT(ProtonV4.X(),ProtonV4.Y(),0); double ProtonTMag = ProtonT.Mag(); TVector3 ElectronT(ElectronV4.X(),ElectronV4.Y(),0); double ElectronTMag = ElectronT.Mag(); TVector3 MissMomentumT = ProtonT + ElectronT; double MissMomentumTMag = MissMomentumT.Mag(); double DeltaPhiT = TMath::ACos(-ProtonT*ElectronT/ProtonTMag/ElectronTMag)*180/TMath::Pi(); double DeltaAlphaT = TMath::ACos(-MissMomentumT*ElectronT/MissMomentumTMag/ElectronTMag)*180/TMath::Pi(); */ // ------------------------------------------------------------------------------------------------------- double Weight = 1.; if (fInteraction == "EM+MEC") { Weight = Q2*Q2; } if (fabs(Weight) != Weight) continue; // ----------------------------------------------------------------------------------------------- countEvents ++; // Increase the number of the events that pass the cuts by one // ---------------------------------------------------------------------------------------------- // Define the missing momentum bin /* if (MissMomentumTMag < 0.2) MissMomentumBin = 1; if (MissMomentumTMag > 0.2 && MissMomentumTMag < 0.4) MissMomentumBin = 2; if (MissMomentumTMag > 0.4) MissMomentumBin = 3; */ // ------------------------------------------------------------------------------------------------ Q2Plot->Fill(Q2,Weight); nuPlot->Fill(nu,Weight); WPlot->Fill(W,Weight); xBPlot->Fill(x,Weight); //MissMomentumPlot->Fill(MissMomentumTMag,Weight); // 1D Electron Plots ElectronThetaPlot->Fill(ElectronTheta,Weight); ElectronCosThetaPlot->Fill(ElectronCosTheta,Weight); ElectronPhiPlot->Fill(ElectronPhi,Weight); ElectronEnergyPlot->Fill(El,Weight); ElectronPhiThetaPlot->Fill(ElectronPhi,ElectronTheta,Weight); // 1D Proton Plots /* ProtonCosThetaPlot->Fill(ProtonCosTheta,Weight); ProtonThetaPlot->Fill(ProtonTheta,Weight); ProtonPhiPlot->Fill(ProtonPhi,Weight); ProtonEnergyPlot->Fill(ProtonE,Weight); EcalResoPlot->Fill((Ecal - Ebeam) / Ebeam * 100.,Weight); */ // 2D Plots Q2VsWPlot->Fill(W,Q2,Weight); Q2VsnuPlot->Fill(nu,Q2,Weight); if (qel == 1) { QE_Q0_Q3_Plot->Fill(q3,nu,Weight); } if (mec == 1) { MEC_Q0_Q3_Plot->Fill(q3,nu,Weight); } /*EpVsMissMomentumPlot->Fill(MissMomentumTMag,ProtonE,Weight); Q2VsMissMomentumPlot->Fill(MissMomentumTMag,Q2,Weight); DeltaPhiTPlot->Fill(DeltaPhiT,Weight); DeltaAlphaTPlot->Fill(DeltaAlphaT,Weight); // Reconstructed Energy Plots epRecoEnergy_slice_0Plot->Fill(Ecal,Weight); eRecoEnergy_slice_0Plot->Fill(EQE,Weight); if (MissMomentumBin == 1) { epRecoEnergy_slice_1Plot->Fill(Ecal,Weight); eRecoEnergy_slice_1Plot->Fill(EQE,Weight);} if (MissMomentumBin == 2) { epRecoEnergy_slice_2Plot->Fill(Ecal,Weight); eRecoEnergy_slice_2Plot->Fill(EQE,Weight);} if (MissMomentumBin == 3) { epRecoEnergy_slice_3Plot->Fill(Ecal,Weight); eRecoEnergy_slice_3Plot->Fill(EQE,Weight);} */ } // end of the loop over events // ---------------------------------------------------------------------------------------------------------------- // Print this message after the loop over the events std::cout << std::endl; std::cout << "File " << FileName << " created " << std::endl; std::cout << std::endl; std::cout << "Efficiency = " << double(countEvents)/ double(nentries)*100. << " %" << std::endl; std::cout << std::endl; file->Write(); file->Close(); } // End of the program // ----------------------------------------------------------------------------------------------------------------
[ "afropapp@yahoo.gr" ]
afropapp@yahoo.gr
9905bd018c94bbeb8e37272ccb89940427b514a0
dfadd879ccc98bb99c45651a33c80c18181589d9
/ZeroLibraries/Math/EulerOrder.hpp
a19dc4c5e0946d60d695c7448c4be8d6c6866ee7
[ "MIT" ]
permissive
zeroengineteam/ZeroCore
f690bcea76e1040fe99268bd83a2b76e3e65fb54
14dc0df801b4351a2e9dfa3ce2dc27f68f8c3e28
refs/heads/1.4.2
2022-02-26T04:05:51.952560
2021-04-09T23:27:57
2021-04-09T23:27:57
148,349,710
54
27
MIT
2022-02-08T18:28:30
2018-09-11T16:51:46
C++
UTF-8
C++
false
false
4,553
hpp
/////////////////////////////////////////////////////////////////////////////// /// /// \file EulerOrder.hpp /// Declaration of the Euler angles order as described in Graphic Gems IV, /// EulerOrder design referenced from Insomniac Games. /// /// Authors: Benjamin Strukus /// Copyright 2010-2012, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Math { /* Ken Shoemake, 1993 Order type constants, constructors, extractors There are 24 possible conventions, designated by: - EulAxI = axis used initially - EulPar = parity of axis permutation - EulRep = repetition of initial axis as last - EulFrm = frame from which axes are taken Axes I, J, K will be a permutation of X, Y, Z. Axis H will be either I or K, depending on EulRep. Frame S takes axes from initial static frame. If ord = (AxI = X, Par = Even, Rep = No, Frm = S), then {a, b, c, ord} means Rz(c)Ry(b)Rx(a), where Rz(c)v rotates v around Z by c radians */ namespace EulerOrders { const uint Safe[4] = { 0, 1, 2, 0 }; const uint Next[4] = { 1, 2, 0, 1 }; ///The two different types of reference frames const uint Static = 0; const uint Rotated = 1; ///The two different states of "is there a repeated axis?" const uint No = 0; const uint Yes = 1; ///Two different states of parity const uint Even = 0; const uint Odd = 1; ///CreateOrder creates an order value between 0 and 23 from 4-tuple choices. #define CreateOrder(axis, parity, repeated, frame) (((((((axis) << 1) + \ (parity)) << 1) + \ (repeated)) << 1) + \ (frame)) ///Bit fields to describe the different permutations of rotations, reference ///frames, repeated axes, and parity enum Enum { X = 0, Y, Z, //Static axes XYZs = CreateOrder(X, Even, No, Static), XYXs = CreateOrder(X, Even, Yes, Static), XZYs = CreateOrder(X, Odd, No, Static), XZXs = CreateOrder(X, Odd, Yes, Static), YZXs = CreateOrder(Y, Even, No, Static), YZYs = CreateOrder(Y, Even, Yes, Static), YXZs = CreateOrder(Y, Odd, No, Static), YXYs = CreateOrder(Y, Odd, Yes, Static), ZXYs = CreateOrder(Z, Even, No, Static), ZXZs = CreateOrder(Z, Even, Yes, Static), ZYXs = CreateOrder(Z, Odd, No, Static), ZYZs = CreateOrder(Z, Odd, Yes, Static), //Rotating axes ZYXr = CreateOrder(X, Even, No, Rotated), XYXr = CreateOrder(X, Even, Yes, Rotated), YZXr = CreateOrder(X, Odd, No, Rotated), XZXr = CreateOrder(X, Odd, Yes, Rotated), XZYr = CreateOrder(Y, Even, No, Rotated), YZYr = CreateOrder(Y, Even, Yes, Rotated), ZXYr = CreateOrder(Y, Odd, No, Rotated), YXYr = CreateOrder(Y, Odd, Yes, Rotated), YXZr = CreateOrder(Z, Even, No, Rotated), ZXZr = CreateOrder(Z, Even, Yes, Rotated), XYZr = CreateOrder(Z, Odd, No, Rotated), ZYZr = CreateOrder(Z, Odd, Yes, Rotated) }; #undef CreateOrder }// namespace EulerOrders struct EulerOrder; typedef EulerOrder& EulerOrderRef; typedef const EulerOrder& EulerOrderParam; ///Structure to hold the order of rotations when dealing with Euler angles, ///whether or not there are any repeating angles, and if the rotations are being ///described in a fixed or rotated frame of reference. struct ZeroShared EulerOrder { EulerOrder(EulerOrders::Enum eulerOrder); EulerOrder& operator = (EulerOrderParam rhs); bool operator == (EulerOrderParam rhs); bool operator != (EulerOrderParam rhs); ///Get the index of the first angle in the Euler angle rotation sequence. uint I(void) const; ///Get the index of the second angle in the Euler angle rotation sequence. uint J(void) const; ///Get the index of the third angle in the Euler angle rotation sequence. uint K(void) const; ///Will be I if there are repeating angles, will be K otherwise. uint H(void) const; bool RepeatingAngles(void) const; bool RotatingFrame(void) const; bool OddParity(void) const; ///Unpacks all useful information about order simultaneously. static void GetOrder(EulerOrder order, uint& i, uint& j, uint& k, uint& h, uint& parity, uint& repeated, uint& frame); EulerOrders::Enum Order; }; }// namespace Math
[ "arend.danielek@zeroengine.io" ]
arend.danielek@zeroengine.io
ff417bb380e6e51de4c269a5f2966d496a6b1f44
536226f6b5c7cf30122e1b17e1e495d42ff0e3e1
/Calculator/Calculator.cpp
72db1e2f56457159641ea533cb2cbb343a1a6b02
[]
no_license
MoawazAyub/Postfix-Calculator
64adfe9f382e27e588e5b22c803d538d548f24d2
d8975862debea1e624213ddd13478948a1d82390
refs/heads/master
2020-03-21T08:07:06.345852
2018-06-22T15:54:51
2018-06-22T15:54:51
138,321,534
0
0
null
null
null
null
UTF-8
C++
false
false
5,051
cpp
# include <iostream> # include <string> # include "Stack.h" using namespace std; template <class T> class Calculator { Stack<T> s; public: void push(const T & obj) { s.push(obj); } void pop() { s.pop(); } void print() { s.print(); } const T & top() { return s.top(); } int size() { return s.size(); } string input(string st) { Operator a, b,c; b.setdiscription("("); string temp; int count = 0; for (int j = 0 ; j < st.size() ; j++) { if(st[j] >= 48 && st[j] <= 57) { temp = temp + st[j]; count++; } else if(st[j] == ' ') { if (count != 0) { count = 0; temp = temp + " "; } } else if (st[j] == '(') { a.setdiscription("("); s.push(a); } else if (st[j] == ')') { Operator a1; a1 = s.top(); while((s.empty()) == false && a1 != b) { c = s.top(); temp = temp + " "; temp = temp + c.getdiscription(); s.pop(); } s.pop(); } else if(st[j] == '+' || st[j] == '-' || st[j] == '*' || st[j] == '/' ) { if (st[j] == '+' && st[j + 1] == '+') { a.setdiscription("++"); j++; s.push(a); } else if (st[j] == '-' && st[j + 1] == '-') { a.setdiscription("--"); j++; s.push(a); } else { Operator d,e,f; a.setdiscription(st[j]); s.push(a); d = s.top(); e = s.top(); s.pop(); if(!(s.empty())) { f = s.top(); } while (!(s.empty()) && d.getpresedence() <= f.getpresedence() && f != b) { temp = temp + f.getdiscription(); temp = temp + " "; s.pop(); if(!(s.empty())) { f = s.top(); } } s.push(d); } }//------------ } if ( !(s.empty()) ) { Operator g = s.top(); while (!(s.empty())) { g = s.top(); temp = temp + " "; if (g.getdiscription() != "(") { temp = temp + g.getdiscription(); } s.pop(); } } // cout << temp; string temp2; int count2 = 0; for(int z = 0 ; z < temp.size();z++ ) { if(temp[z] == ' ' || temp[z] == '(') { count2++; } else { count2 = 0; } if(temp[z] !='(' && count2 < 2) { temp2 = temp2 + temp[z]; } } return temp2; } int evaluate(string & st) { int x=0,y=0; Stack<string> a1; string temp,temp2,temp3; int i = 0; int count = 0; for(int j = 0 ; j < st.size() ; j++) { if(st[j] >= 48 && st[j] <= 57) { temp = temp + st[j]; count++; } else if(st[j] == ' ') { if (count != 0) { count = 0; a1.push(temp); temp = ""; } } else if(st[j] == '+' || st[j] == '-' || st[j] == '*' || st[j] == '/' ) { if (st[j] == '+' && st[j + 1] == '+') { temp2 = a1.top(); x = stoi(temp2); x = x + 1; a1.pop(); a1.push(to_string(x)); j++; } else if (st[j] == '-' && st[j + 1] == '-') { temp2 = a1.top(); x = stoi(temp2); x = x - 1; a1.pop(); a1.push(to_string(x)); j++; } else if(st[j] == '+') { int z = 0; temp2 = a1.top(); y = stoi(temp2); a1.pop(); temp2 = a1.top(); x = stoi(temp2); a1.pop(); z = x + y; a1.push(to_string(z)); } else if(st[j] == '-') { int z = 0; temp2 = a1.top(); y = stoi(temp2); a1.pop(); temp2 = a1.top(); x = stoi(temp2); a1.pop(); z = x - y; a1.push(to_string(z)); } else if(st[j] == '*') { int z = 0; temp2 = a1.top(); y = stoi(temp2); a1.pop(); temp2 = a1.top(); x = stoi(temp2); a1.pop(); z = x * y; a1.push(to_string(z)); } else if(st[j] == '/') { int z = 0; temp2 = a1.top(); y = stoi(temp2); a1.pop(); temp2 = a1.top(); x = stoi(temp2); a1.pop(); z = x / y; a1.push(to_string(z)); } }//------------ } int v = stoi(a1.top()); return v; } }; void main() { Calculator<Operator> c; string s; string t; while(s != "quit") { cout << "enter command Remember to add spaces between digits (result is in integer)" <<endl; getline(cin, s); if (s == "quit") { break; } t = c.input(s); cout <<t; cout << endl; cout << "answer = "; cout << c.evaluate(t); cout << endl; } //Calculator<Operator> c; //string s = "2 + 3"; //string t; //t = c.input(s); ////t = "18 2 * 6 /"; //cout<<c.input(s); // //cout << endl; //cout<<c.evaluate(t); //cout <<endl; ///*Operator o,t; //o.setdiscription("/"); /*c.push(o); o.setdiscription("+"); c.push(o); o.setdiscription("*"); c.push(o); c.pop(); o.setdiscription("-"); c.push(o); c.print(); t = c.top(); int d = t.getpresedence() ; cout << d; */ }
[ "moawazayubmmm@gmail.com" ]
moawazayubmmm@gmail.com
7f812a82447d6239c96c880e53c3b5b85d14b833
d4c431faeff66402c8a8ef04ede205ab232b5c8f
/Cthulhu/src/RawDynamic.cpp
d30dafd61b868f6f60668bd41b6fcb07d44d13f5
[ "MIT" ]
permissive
yahiaali/labgraph
6a5bd10626b62adf1055250ac70de63d65a3d575
306d7e55a06219155303f287f91e9b6ea5dca50a
refs/heads/main
2023-07-15T15:35:36.011835
2021-08-27T13:22:23
2021-08-27T13:22:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
616
cpp
// Copyright 2004-present Facebook. All Rights Reserved. #include <cthulhu/RawDynamic.h> #include <memory> #include <cthulhu/Framework.h> namespace cthulhu { template <> CpuBuffer RawDynamic<>::getBuffer() const { return Framework::instance().memoryPool()->getBufferFromPool("", size()); } template <> RawDynamic<>::RawDynamic(CpuBuffer& buf, size_t count) : elementCount(count), elementSize(sizeof(uint8_t)) { if (Framework::instance().memoryPool()->isBufferFromPool(buf)) { raw = buf; } else { raw = getBuffer(); std::memcpy(raw.get(), buf.get(), size()); } } } // namespace cthulhu
[ "jinyu.fjy@gmail.com" ]
jinyu.fjy@gmail.com
e506d5d255a9a28616e7402716a5802486640e37
ba9485e8ea33acee24dc7bd61049ecfe9f8b8930
/yk/784.cpp
dbefc0e6b3cc482201f85d869108bb084125ef94
[]
no_license
diohabara/competitive_programming
a0b90a74b0b923a636b9c82c75b690fef11fe8a4
1fb493eb44ce03e289d1245bf7d3dc450f513135
refs/heads/master
2021-12-11T22:43:40.925262
2021-11-06T12:56:49
2021-11-06T12:56:49
166,757,685
1
0
null
null
null
null
UTF-8
C++
false
false
284
cpp
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < n; i++) #define ll long long #define endl '\n' using namespace std; int main() { cin.tie(0); ios::sync_with_stdio(false); string s; cin >> s; for (int i = 0; i < s.size(); i++) { } return 0; }
[ "kadoitakemaru0902@g.ecc.u-tokyo.ac.jp" ]
kadoitakemaru0902@g.ecc.u-tokyo.ac.jp
33f904509374f9523fed361484b839453f86ef85
c3007f04d2e5cdb0c4d08a6b9c23805c1e6f0fc1
/week10/examples/example4/main.cpp
6fcb617862811e623cc6c690e6d1d37a9cbf4290
[]
no_license
haidao17/CPP
17b217a468639c7e9dd1d0f9229deabc9716c9d6
2ceb5a24dbcd58d0539d80607b932e3066cce3a5
refs/heads/main
2023-09-02T21:45:48.118473
2021-11-21T13:22:48
2021-11-21T13:22:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
456
cpp
#include <iostream> #include "time.hpp" using namespace std; int main() { MyTime t1(1, 20); int minutes = t1; //implicit conversion float f = float(t1); //explicit conversion. std::cout << "minutes = " << minutes << std::endl; std::cout << "minutes = " << f << std::endl; MyTime t2 = 70; std::cout << "t2 is " << t2 << std::endl; MyTime t3; t3 = 80; std::cout << "t3 is " << t3 << std::endl; return 0; }
[ "shiqi.yu@gmail.com" ]
shiqi.yu@gmail.com
c7a68ddd2f18629d61dc7748d24bee4a8ddd89d3
1b51fec6521c8a95b1937b3d3de489efbe2d2029
/cubeCode/cubeCode.ino
8cd01688d3691dd3fedfc1e70c5c78b626f26b84
[ "MIT" ]
permissive
blinky-lite-archive/blinky-DS18B20-cube
1a3914ccdbde4847faa6ad34c447035f3cca8077
ab6d1f67db70fb87de33aad05897bc71e970ab56
refs/heads/master
2023-04-15T14:59:43.539172
2021-05-03T06:00:27
2021-05-03T06:00:27
357,963,746
0
0
null
null
null
null
UTF-8
C++
false
false
4,867
ino
#include <OneWire.h> #define BAUD_RATE 57600 #define CHECKSUM 64 struct TransmitData { float tempA = 0.0; float tempB = 0.0; byte extraInfo[44]; }; struct ReceiveData { int loopDelay = 100; byte extraInfo[52]; }; struct DS18B20 { int signalPin; int powerPin; byte chipType; byte address[8]; OneWire oneWire; float temp = 0.0; }; DS18B20 dS18B20_A; DS18B20 dS18B20_B; byte initDS18B20(byte* addr, OneWire* ow) { byte type_s = 0; if ( !ow->search(addr)) { ow->reset_search(); delay(250); return 0; } // the first ROM byte indicates which chip switch (addr[0]) { case 0x10: type_s = 1; break; case 0x28: type_s = 0; break; case 0x22: type_s = 0; break; default: return 0; } return type_s; } float getDS18B20Temperature(OneWire* ow, byte* addr, byte chipType) { byte i; byte data[12]; float celsius; ow->reset(); ow->select(addr); ow->write(0x44, 1); // start conversion, with parasite power on at the end delay(750); // maybe 750ms is enough, maybe not ow->reset(); ow->select(addr); ow->write(0xBE); // Read Scratchpad for ( i = 0; i < 9; i++) data[i] = ow->read(); int16_t raw = (data[1] << 8) | data[0]; if (chipType) { raw = raw << 3; // 9 bit resolution default if (data[7] == 0x10) raw = (raw & 0xFFF0) + 12 - data[6]; } else { byte cfg = (data[4] & 0x60); if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms } celsius = (float)raw / 16.0; return celsius; } void setupPins(TransmitData* tData, ReceiveData* rData) { dS18B20_A.signalPin = 5; dS18B20_A.powerPin = 3; dS18B20_B.signalPin = 9; dS18B20_B.powerPin = 7; pinMode(dS18B20_A.powerPin, OUTPUT); digitalWrite(dS18B20_A.powerPin, HIGH); pinMode(dS18B20_B.powerPin, OUTPUT); digitalWrite(dS18B20_B.powerPin, HIGH); dS18B20_A.oneWire = OneWire(dS18B20_A.signalPin); dS18B20_A.chipType = initDS18B20(dS18B20_A.address, &dS18B20_A.oneWire); dS18B20_B.oneWire = OneWire(dS18B20_B.signalPin); dS18B20_B.chipType = initDS18B20(dS18B20_B.address, &dS18B20_B.oneWire); // Serial.begin(9600); } void processNewSetting(TransmitData* tData, ReceiveData* rData, ReceiveData* newData) { rData->loopDelay = newData->loopDelay; } boolean processData(TransmitData* tData, ReceiveData* rData) { digitalWrite(dS18B20_A.powerPin, LOW); digitalWrite(dS18B20_B.powerPin, LOW); delay(500); digitalWrite(dS18B20_A.powerPin, HIGH); digitalWrite(dS18B20_B.powerPin, HIGH); delay(500); dS18B20_A.temp = getDS18B20Temperature(&dS18B20_A.oneWire, dS18B20_A.address, dS18B20_A.chipType); dS18B20_B.temp = getDS18B20Temperature(&dS18B20_B.oneWire, dS18B20_B.address, dS18B20_B.chipType); // Serial.print(dS18B20_A.temp); // Serial.print(","); // Serial.println(dS18B20_B.temp); tData->tempA = dS18B20_A.temp; tData->tempB = dS18B20_B.temp; delay(rData->loopDelay); return true; } const int commLEDPin = 13; boolean commLED = true; struct TXinfo { int cubeInit = 1; int newSettingDone = 0; int checkSum = CHECKSUM; }; struct RXinfo { int newSetting = 0; int checkSum = CHECKSUM; }; struct TX { TXinfo txInfo; TransmitData txData; }; struct RX { RXinfo rxInfo; ReceiveData rxData; }; TX tx; RX rx; ReceiveData settingsStorage; int sizeOfTx = 0; int sizeOfRx = 0; void setup() { setupPins(&(tx.txData), &settingsStorage); pinMode(commLEDPin, OUTPUT); digitalWrite(commLEDPin, commLED); sizeOfTx = sizeof(tx); sizeOfRx = sizeof(rx); Serial1.begin(BAUD_RATE); delay(1000); int sizeOfextraInfo = sizeof(tx.txData.extraInfo); for (int ii = 0; ii < sizeOfextraInfo; ++ii) tx.txData.extraInfo[ii] = 0; } void loop() { boolean goodData = false; goodData = processData(&(tx.txData), &settingsStorage); if (goodData) { tx.txInfo.newSettingDone = 0; if(Serial1.available() > 0) { commLED = !commLED; digitalWrite(commLEDPin, commLED); Serial1.readBytes((uint8_t*)&rx, sizeOfRx); if (rx.rxInfo.checkSum == CHECKSUM) { if (rx.rxInfo.newSetting > 0) { processNewSetting(&(tx.txData), &settingsStorage, &(rx.rxData)); tx.txInfo.newSettingDone = 1; tx.txInfo.cubeInit = 0; } } else { Serial1.end(); for (int ii = 0; ii < 50; ++ii) { commLED = !commLED; digitalWrite(commLEDPin, commLED); delay(100); } Serial1.begin(BAUD_RATE); tx.txInfo.newSettingDone = 0; tx.txInfo.cubeInit = -1; } } Serial1.write((uint8_t*)&tx, sizeOfTx); Serial1.flush(); } }
[ "dmcginnis427@gmail.com" ]
dmcginnis427@gmail.com
1edc8860c55f53612a98b3e0ed5f53ce261d0a1c
30deab0afc113791f86ec71f75f0ff4113ed7f8e
/Ludo/picture demmo/PictureDemo.cpp
ec146f46d045f65fcd5a44e3ad30ae588893609a
[]
no_license
FaiyazMohammadSaif/Ludo_Game
347643123fa2bb1d645cb11a8f69bba530342e01
f90290a8f4e55cbbc18f1f1d00ac43c9077f74cd
refs/heads/master
2020-08-03T23:28:30.018965
2019-10-07T18:15:54
2019-10-07T18:15:54
211,920,694
0
0
null
null
null
null
UTF-8
C++
false
false
2,119
cpp
/* author: S. M. Shahriar Nirjon last modified: August 8, 2008 */ # include "iGraphics.h" int pic_x, pic_y; /* function iDraw() is called again and again by the system. */ void iDraw() { //place your drawing codes here iClear(); iShowBMP(pic_x, pic_y, "smurf.bmp"); iText(10, 10, "Use cursors to move the picture."); } /* function iMouseMove() is called when the user presses and drags the mouse. (mx, my) is the position where the mouse pointer is. */ void iMouseMove(int mx, int my) { //place your codes here } /* function iMouse() is called when the user presses/releases the mouse. (mx, my) is the position where the mouse pointer is. */ void iMouse(int button, int state, int mx, int my) { if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { //place your codes here } if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { //place your codes here } } /* function iKeyboard() is called whenever the user hits a key in keyboard. key- holds the ASCII value of the key pressed. */ void iKeyboard(unsigned char key) { if(key == 'x') { //do something with 'x' exit(0); } //place your codes for other keys here } /* function iSpecialKeyboard() is called whenver user hits special keys like- function keys, home, end, pg up, pg down, arraows etc. you have to use appropriate constants to detect them. A list is: GLUT_KEY_F1, GLUT_KEY_F2, GLUT_KEY_F3, GLUT_KEY_F4, GLUT_KEY_F5, GLUT_KEY_F6, GLUT_KEY_F7, GLUT_KEY_F8, GLUT_KEY_F9, GLUT_KEY_F10, GLUT_KEY_F11, GLUT_KEY_F12, GLUT_KEY_LEFT, GLUT_KEY_UP, GLUT_KEY_RIGHT, GLUT_KEY_DOWN, GLUT_KEY_PAGE UP, GLUT_KEY_PAGE DOWN, GLUT_KEY_HOME, GLUT_KEY_END, GLUT_KEY_INSERT */ void iSpecialKeyboard(unsigned char key) { if(key == GLUT_KEY_END) { exit(0); } if(key == GLUT_KEY_LEFT) { pic_x-=5; } if(key == GLUT_KEY_RIGHT) { pic_x+=5; } if(key == GLUT_KEY_UP) { pic_y+=5; } if(key == GLUT_KEY_DOWN) { pic_y-=5; } //place your codes for other keys here } int main() { //place your own initialization codes here. pic_x = 30; pic_y = 30; iInitialize(400, 400, "PictureDemo"); return 0; }
[ "faiyazsaif17@gmail.com" ]
faiyazsaif17@gmail.com
5b72a5dcd4afae544d4564dfdd3ba79d899219ca
d89ad3f7be72e8645db979aff6d5908764f84b53
/অ্যালগরিদম/Bfs And Dfs/shotcut---bfs(TL)/Longest path in a tree----bfs - Copy.cpp
2fb2cfcf11069f88a13741ff640de21d58308b21
[]
no_license
alhelal1/Contest_File
c8dbcaa18bddeeca0791564b7d3b00ccf4eedfde
31bd164e3128de500b5c4c5beb188c86379ab40b
refs/heads/master
2021-04-03T08:38:15.085441
2018-03-14T06:10:08
2018-03-14T06:10:08
125,163,850
0
0
null
null
null
null
UTF-8
C++
false
false
4,875
cpp
using namespace std; #include<bits/stdc++.h> typedef long long ll; typedef pair<ll,ll> pii; typedef vector< pii > vpii; typedef vector<long long> vi; typedef map<string,ll> msi; typedef map<ll,ll> mii; ///Print #define out(a) printf("%lld\n",a) #define out2(a,b) printf("%lld %lld\n",a,b) #define out3(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define nl printf("\n") ///Case #define case(no) printf("Case %lld: ",++no) #define casenl(no) printf("Case %lld:\n",++no) #define caseh(no) printf("Case #%lld: ",++no) #define casehnl(no) printf("Case #%lld:\n",++no) ///Scanf #define in(n) scanf("%lld", &n) #define in2(a,b) scanf("%lld %lld", &a, &b) #define in3(a,b,c) scanf("%lld %lld %lld", &a, &b, &c) ///LOOP #define rep(x,n) for(__typeof(n) x=0;x<(n);x++) #define reps(i,x) for(int i=0;i<(x.size());i++) #define repp(x,n) for(__typeof(n) x=1;x<=(n);x++) #define foreach(x,n) for(__typeof(n.begin()) x=n.begin();x!=n.end();x++) ///Shortcut #define mem(ar,value) memset(ar,value,sizeof(ar)) #define all(x) x.begin(),x.end() #define Unique(store) store.resize(unique(store.begin(),store.end())-store.begin()) #define len(s) s.size() #define mp make_pair #define pb push_back #define ff first #define ss second ///Min AND Max #define min4(a,b,c,d) min(min(a,b),min(c,d)) #define max4(a,b,c,d) max(max(a,b),max(c,d)) #define min3(a,b,c) min(a,min(b,c)) #define max3(a,b,c) max(a,max(b,c)) #define maxall(v) *max_element(all(v)) #define minall(v) *min_element(all(v)) #define eps (1e-9) #define PI acos(-1.0) #define mod 1e9+7 #define isEq(a,b) (fabs((a)-(b))<eps) #define Dist(x1,y1,x2,y2) (sqrt(sqr((x1)-(x2))+sqr((y1)-(y2)))) ///File #define READ freopen("input.txt","r",stdin) #define WRITE freopen("output.txt","w",stdout) /**Define Bitwise operation**/ #define check(n, pos) (n & (1<<(pos))) #define biton(n, pos) (n | (1<<(pos))) #define bitoff(n, pos) (n & ~(1<<(pos))) #define ledzero(n) (__builtin_clz(n)) #define trailzero(n) (__builtin_ctz(n)) #define onbit(n) (__builtin_popcount(n)) ///DEBUG #define d1(x) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<endl; #define d2(x,y) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<" | "#y" = "<<y<<endl; #define d3(x,y,z) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<" | "#y" = "<<y<<" | "#z" = "<<z<<endl; ///Gcd and Lcm template<class T>T gcd(T a,T b){return b == 0 ? a : gcd(b, a % b);} template<typename T>T lcm(T a, T b) {return a / gcd(a,b) * b;} ///Bigmod && Pow template<class T>T my_pow(T n,T p){if(p==0)return 1;T x=my_pow(n,p/2);x=(x*x);if(p&1)x=(x*n);return x;} ///n to the power p template<class T>T big_mod(T n,T p,T m){if(p==0)return (T)1;T x=big_mod(n,p/2,m);x=(x*x)%m;if(p&1)x=(x*n)%m;return x;} template<class T> inline T Mod(T n,T m) {return (n%m+m)%m;} ///For Positive Negative No. ///string to int template <class T> T extract(string s, T ret) {stringstream ss(s); ss >> ret; return ret;}/// extract words or numbers from a line template<class T> string itos(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}///NOTES:toString( ll stoi(string s){ll r=0;istringstream sin(s);sin>>r;return r;}///NOTES:toInt( double toDouble(string s){double r=0;istringstream sin(s);sin>>r;return r;} //int col[8] = {0, 1, 1, 1, 0, -1, -1, -1};int row[8] = {1, 1, 0, -1, -1, -1, 0, 1};///8 Direction //int col[4] = {1, 0, -1, 0};int row[4] = {0, 1, 0, -1};///4 Directionint //int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};///Knight Direction //int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2};///Hexagonal Direction ll ar[2000005],ar1[2000005]; ll a=0,b=0,c=0,r=0,rr=0,res=0,n,m; string s,s1; ll vis[1000006]; vector<ll>v[100005]; ll depth=0; ll dfs(ll i) { queue<ll>q; q.push(i); q.push(0); vis[i]=1; r=0; depth=0; while(len(q)) { ll aa=q.front();q.pop(); ll bb=q.front();q.pop(); //r=max(bb,r); if(r<bb) { depth=aa; r=bb; } rep(j,len(v[aa])) { ll cc=v[aa][j]; if(vis[cc]==0) { q.push(cc); q.push(bb+1); vis[cc]=1; } } } } int main() { //ios_base::sync_with_stdio(false); //cin.tie(false); cin>>n; rep(i,n-1) { cin>>a>>b; v[a].pb(b); v[b].pb(a); } ll dd=0; repp(i,n) { if(len(v[i])>0 and vis[i]==0) { dfs(i); if(rr<r) { rr=r; dd=depth; r=0; } } } mem(vis,false); r=0; dfs(dd); rr=max(r,rr); out(rr); mem(vis,false); return 0; }
[ "a.helal@bjitgroup.com" ]
a.helal@bjitgroup.com
1d9772bc154893331ebbdea8d094fb20cd786fea
6c10d344a25f3194506a414fc7830888b9d78b53
/source/apps/mast/gui/dialogs/FeatureVolumesDialog.h
f610f61debef29d1a943c8d31aed47c393fd5671
[]
no_license
vyeghiazaryan/msc
64fb493660b06031caae126c6572a4dc33177952
dced6bae89461578285cc24b99feab034eafc48e
refs/heads/master
2020-12-24T13:36:11.747054
2013-11-05T12:28:06
2013-11-05T12:28:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,558
h
/*** * millipede: FeatureVolumesDialog.h * Copyright Stuart Golodetz, 2010. All rights reserved. ***/ #ifndef H_MILLIPEDE_FEATUREVOLUMESDIALOG #define H_MILLIPEDE_FEATUREVOLUMESDIALOG #include <sstream> #include <wx/button.h> #include <wx/dialog.h> #include <wx/listctrl.h> #include <wx/sizer.h> #include <common/math/NumericUtil.h> #include <mast/models/PartitionModel.h> #include <mast/util/StringConversion.h> namespace mp { class FeatureVolumesDialog : public wxDialog { //#################### PRIVATE VARIABLES #################### private: int m_index; wxListCtrl *m_list; //#################### CONSTRUCTORS #################### public: template <typename LeafLayer, typename BranchLayer, typename Feature> FeatureVolumesDialog(wxWindow *parent, const boost::shared_ptr<const PartitionModel<LeafLayer,BranchLayer,Feature> >& model) : wxDialog(parent, wxID_ANY, wxT("Feature Volumes"), wxDefaultPosition, wxDefaultSize), m_index(0) { wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL); SetSizer(sizer); // Add a list control to show the volumes. m_list = new wxListCtrl(this, wxID_ANY, wxDefaultPosition, wxSize(300,200), wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_HRULES|wxLC_VRULES); m_list->InsertColumn(0, wxT("Feature Name")); m_list->InsertColumn(1, wxT("Volume (cubic cm, 3 d.p.)")); for(Feature feature=enum_begin<Feature>(), end=enum_end<Feature>(); feature!=end; ++feature) { double volumeMM3 = model->active_multi_feature_selection()->voxel_count(feature) * model->dicom_volume()->voxel_size_mm3(); add_feature_volume(feature, volumeMM3); } m_list->SetColumnWidth(0, wxLIST_AUTOSIZE_USEHEADER); m_list->SetColumnWidth(1, wxLIST_AUTOSIZE_USEHEADER); sizer->Add(m_list, 0, wxALIGN_CENTRE_HORIZONTAL); // Add an OK button. wxButton *okButton = new wxButton(this, wxID_OK, wxT("OK")); sizer->Add(okButton, 0, wxALIGN_CENTRE_HORIZONTAL); okButton->SetFocus(); sizer->Fit(this); CentreOnParent(); } //#################### PRIVATE METHODS #################### private: template <typename Feature> void add_feature_volume(const Feature& feature, double volumeMM3) { std::ostringstream oss; oss.setf(std::ios::fixed, std::ios::floatfield); oss.precision(3); oss << (volumeMM3 / 1000.0); // the / 1000.0 converts cubic mm to cubic cm m_list->InsertItem(m_index, string_to_wxString(feature_to_name(feature))); m_list->SetItem(m_index, 1, string_to_wxString(oss.str())); ++m_index; } }; } #endif
[ "varduhi.yeghiazaryan@cs.ox.ac.uk" ]
varduhi.yeghiazaryan@cs.ox.ac.uk
c091f010bc589eb9c25e39726e4281ded41586d1
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/inetsrv/iis/admin/common/ipa.h
174bac34e4062a244ad32ae52f11c93f1194ee4d
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
7,989
h
/*++ Copyright (c) 1994-1998 Microsoft Corporation Module Name : ipa.h Abstract: IP Address value Author: Ronald Meijer (ronaldm) Project: Internet Services Manager Revision History: --*/ #ifndef _IPA_H #define _IPA_H // // IP Address Conversion Macros // #ifdef MAKEIPADDRESS #undef MAKEIPADDRESS #endif // MAKEIPADDRESS #define MAKEIPADDRESS(b1,b2,b3,b4) (((DWORD)(b1)<<24) +\ ((DWORD)(b2)<<16) +\ ((DWORD)(b3)<< 8) +\ ((DWORD)(b4))) #ifndef GETIP_FIRST #define GETIP_FIRST(x) ((x>>24) & 0xff) #define GETIP_SECOND(x) ((x>>16) & 0xff) #define GETIP_THIRD(x) ((x>> 8) & 0xff) #define GETIP_FOURTH(x) ((x) & 0xff) #endif // GETIP_FIRST // // Some predefined IP values // #define NULL_IP_ADDRESS (DWORD)(0x00000000) #define NULL_IP_MASK (DWORD)(0xFFFFFFFF) #define BAD_IP_ADDRESS (DWORD)(0xFFFFFFFF) class COMDLL CIPAddress : public CObjectPlus /*++ Class Description: IP Address classes. Winsock is required to be initialized for this to work. Public Interface: CIPAddress : Various constructors operator = : Assignment operator operator == : Comparison operators operator const DWORD : Cast operator operator LPCTSTR : Cast operator operator CString : Cast operator CompareItem : Comparison function QueryIPAddress : Get the ip address value QueryNetworkOrderIPAddress : Get the ip address value (network order) QueryHostOrderIPAddress : Get the ip address value (host order) StringToLong : Convert ip address string to 32 bit number LongToString : Convert 32 bit value to ip address string --*/ { // // Helper Functions // public: static DWORD StringToLong( IN LPCTSTR lpstr, IN int nLength ); static DWORD StringToLong( IN const CString & str ); static DWORD StringToLong( IN const CComBSTR & bstr ); static LPCTSTR LongToString( IN const DWORD dwIPAddress, OUT CString & str ); static LPCTSTR LongToString( IN const DWORD dwIPAddress, OUT CComBSTR & bstr ); static LPTSTR LongToString( IN const DWORD dwIPAddress, OUT LPTSTR lpStr, IN int cbSize ); static LPBYTE DWORDtoLPBYTE( IN DWORD dw, OUT LPBYTE lpBytes ); public: // // Constructors // CIPAddress(); // // Construct from DWORD // CIPAddress( IN DWORD dwIPValue, IN BOOL fNetworkByteOrder = FALSE ); // // Construct from byte stream // CIPAddress( IN LPBYTE lpBytes, IN BOOL fNetworkByteOrder = FALSE ); // // Construct from octets // CIPAddress( IN BYTE b1, IN BYTE b2, IN BYTE b3, IN BYTE b4 ); // // Copy constructor // CIPAddress( IN const CIPAddress & ia ); // // Construct from string // CIPAddress( IN LPCTSTR lpstr, IN int nLength ); // // Construct from CString // CIPAddress( IN const CString & str ); // // Access Functions // public: int CompareItem( IN const CIPAddress & ia ) const; // // Query IP address value as a dword // DWORD QueryIPAddress( IN BOOL fNetworkByteOrder = FALSE ) const; // // Get the ip address value as a byte stream // LPBYTE QueryIPAddress( OUT LPBYTE lpBytes, IN BOOL fNetworkByteOrder = FALSE ) const; // // Get the ip address as a CString // LPCTSTR QueryIPAddress( OUT CString & strAddress ) const; // // Get the ip address as a CComBSTR // LPCTSTR QueryIPAddress( OUT CComBSTR & bstrAddress ) const; // // Get ip address in network byte order DWORD // DWORD QueryNetworkOrderIPAddress() const; // // Get the ip address in host byte order DWORD // DWORD QueryHostOrderIPAddress() const; // // Assignment operators // const CIPAddress & operator =( IN const DWORD dwIPAddress ); const CIPAddress & operator =( IN LPCTSTR lpstr ); const CIPAddress & operator =( IN const CString & str ); const CIPAddress & operator =( IN const CIPAddress & ia ); // // Comparison operators // BOOL operator ==( IN const CIPAddress & ia ) const; BOOL operator ==( IN DWORD dwIPAddress ) const; BOOL operator !=( IN const CIPAddress & ia ) const; BOOL operator !=( IN DWORD dwIPAddress ) const; // // Conversion operators // operator const DWORD() const { return m_dwIPAddress; } operator LPCTSTR() const; operator CString() const; // // Value Verification Helpers // void SetZeroValue(); BOOL IsZeroValue() const; BOOL IsBadValue() const; private: DWORD m_dwIPAddress; }; // // Inline Expansion // // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< inline /* static */ DWORD CIPAddress::StringToLong( IN const CString & str ) { return CIPAddress::StringToLong(str, str.GetLength()); } inline /* static */ DWORD CIPAddress::StringToLong( IN const CComBSTR & bstr ) { return CIPAddress::StringToLong(bstr, bstr.Length()); } inline LPCTSTR CIPAddress::QueryIPAddress( OUT CString & strAddress ) const { return LongToString(m_dwIPAddress, strAddress); } inline LPCTSTR CIPAddress::QueryIPAddress( OUT CComBSTR & bstrAddress ) const { return LongToString(m_dwIPAddress, bstrAddress); } inline DWORD CIPAddress::QueryNetworkOrderIPAddress() const { return QueryIPAddress(TRUE); } inline DWORD CIPAddress::QueryHostOrderIPAddress() const { return QueryIPAddress(FALSE); } inline BOOL CIPAddress::operator ==( IN const CIPAddress & ia ) const { return CompareItem(ia) == 0; } inline BOOL CIPAddress::operator ==( IN DWORD dwIPAddress ) const { return m_dwIPAddress == dwIPAddress; } inline BOOL CIPAddress::operator !=( IN const CIPAddress & ia ) const { return CompareItem(ia) != 0; } inline BOOL CIPAddress::operator !=( IN DWORD dwIPAddress ) const { return m_dwIPAddress != dwIPAddress; } inline void CIPAddress::SetZeroValue() { m_dwIPAddress = NULL_IP_ADDRESS; } inline BOOL CIPAddress::IsZeroValue() const { return m_dwIPAddress == NULL_IP_ADDRESS; } inline BOOL CIPAddress::IsBadValue() const { return m_dwIPAddress == BAD_IP_ADDRESS; } // // Helper function to build a list of known IP addresses, // and add them to a combo box // DWORD COMDLL PopulateComboWithKnownIpAddresses( IN LPCTSTR lpszServer, IN CComboBox & combo, IN CIPAddress & iaIpAddress, OUT CObListPlus & oblIpAddresses, OUT int & nIpAddressSel ); // // Helper function to get an ip address from a combo/edit/list // control // BOOL COMDLL FetchIpAddressFromCombo( IN CComboBox & combo, IN CObListPlus & oblIpAddresses, OUT CIPAddress & ia ); #endif // _IPA_H
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
8f85ff85c18495511605a75c88d90e490a8f6f5e
047600ca8efa01dd308f4549793db97e6ddcec20
/Src/HLSDK/dlls/weapon_shotgun.cpp
0e24fb0465bb6a31df57aa6b7d8f871dc4b43bc2
[]
no_license
crskycode/Mind-Team
cbb9e98322701a5d437fc9823dd4c296a132330f
ceab21c20b0b51a2652c02c04eb7ae353b82ffd0
refs/heads/main
2023-03-16T10:34:31.812155
2021-03-02T02:23:40
2021-03-02T02:23:40
343,616,799
6
1
null
null
null
null
UTF-8
C++
false
false
4,833
cpp
/*** * * Copyright (c) 1996-2002, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ***/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "player.h" #include "weapons.h" LINK_ENTITY_TO_CLASS(weapon_shotgun, CShotgun); void CShotgun::Spawn(void) { pev->classname = MAKE_STRING("weapon_shotgun"); Precache(); CBasePlayerWeapon::Spawn(); m_iWeaponClass = WeaponClass_Shotgun; m_iClip = m_Info.iAmmoPerMagazine; m_iAmmo = m_Info.iMaxAmmo; } void CShotgun::Precache(void) { m_iShotgunFire = PRECACHE_EVENT(1, "events/shotgunfire.sc"); } void CShotgun::Deploy(void) { m_fInSpecialReload = FALSE; DefaultDeploy(m_Info.iszPViewModelFileName, m_Info.iszGViewModelFileName, m_Info.m_AnimSelect.iSequence, m_Info.szGViewAnimName, m_Info.m_AnimSelect.flTime); } void CShotgun::Reload(void) { if (m_iClip >= m_Info.iAmmoPerMagazine || m_iAmmo <= 0) return; if (m_flNextPrimaryAttack > UTIL_WeaponTimeBase()) return; if (!m_fInSpecialReload) { m_pPlayer->SetAnimation(PLAYER_RELOAD); SendWeaponAnim(m_Info.m_AnimStartReload.iSequence); m_fInSpecialReload = 1; m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + m_Info.m_AnimStartReload.flTime; m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + m_Info.m_AnimStartReload.flTime; m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + m_Info.m_AnimStartReload.flTime; m_flNextSecondaryAttack = UTIL_WeaponTimeBase() + m_Info.m_AnimStartReload.flTime; } else if (m_fInSpecialReload == 1) { if (m_flTimeWeaponIdle > UTIL_WeaponTimeBase()) return; m_fInSpecialReload = 2; SendWeaponAnim(m_Info.m_AnimReload.iSequence); m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + m_Info.m_AnimReload.flTime; } else { m_iClip++; m_iAmmo--; m_fInSpecialReload = 1; } } void CShotgun::PrimaryAttack(void) { if (m_pPlayer->pev->velocity.Length2D() > 0) ShotgunFire(m_Info.m_AccuracyRunning.flSpreadBase, m_Info.flShotIntervalTime); else if (!FBitSet(m_pPlayer->pev->flags, FL_ONGROUND)) ShotgunFire(m_Info.m_AccuracyJumping.flSpreadBase, m_Info.flShotIntervalTime); else if (FBitSet(m_pPlayer->pev->flags, FL_DUCKING)) ShotgunFire(m_Info.m_AccuracyDucking.flSpreadBase, m_Info.flShotIntervalTime); else ShotgunFire(m_Info.m_AccuracyDefault.flSpreadBase, m_Info.flShotIntervalTime); } void CShotgun::ShotgunFire(float flSpread, float flCycleTime) { if (m_iClip <= 0) { EMIT_SOUND_DYN(m_pPlayer->edict(), CHAN_WEAPON, "weapon/others/g_nobullet_shotgun.wav", VOL_NORM, ATTN_NORM, 0, PITCH_NORM); m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + 0.2; return; } m_iClip--; m_pPlayer->SetAnimation(PLAYER_ATTACK1); SendWeaponAnim(m_Info.m_AnimFire.iSequence); m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + m_Info.m_AnimFire.flTime + 0.1; UTIL_MakeVectors(m_pPlayer->pev->v_angle + m_pPlayer->pev->punchangle * 2); m_pPlayer->FireShotgun(m_Info.m_FireBullets.iShots, m_pPlayer->GetGunPosition(), gpGlobals->v_forward, flSpread, m_Info.m_FireBullets.flDistance, m_Info.m_FireBullets.iDamage, m_Info.m_FireBullets.flRangeModifier, m_pPlayer->pev, m_pPlayer->random_seed); PLAYBACK_EVENT_FULL(FEV_NOTHOST, m_pPlayer->edict(), m_iShotgunFire, 0, g_vecZero, g_vecZero, flSpread, 0, (int)(m_pPlayer->pev->punchangle.x * 100), (int)(m_pPlayer->pev->punchangle.y * 100), m_pPlayer->random_seed, m_Info.iWeaponIndex); m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + flCycleTime; m_fInSpecialReload = FALSE; if (m_pPlayer->pev->velocity.Length2D() > 0) m_pPlayer->pev->punchangle.x -= m_Info.m_KickBackRunning.flUpBase; else if (!FBitSet(m_pPlayer->pev->flags, FL_ONGROUND)) m_pPlayer->pev->punchangle.x -= m_Info.m_KickBackJumping.flUpBase; else if (FBitSet(m_pPlayer->pev->flags, FL_DUCKING)) m_pPlayer->pev->punchangle.x -= m_Info.m_KickBackDucking.flUpBase; else m_pPlayer->pev->punchangle.x -= m_Info.m_KickBackDefault.flUpBase; } void CShotgun::WeaponIdle(void) { if (m_flTimeWeaponIdle <= UTIL_WeaponTimeBase()) { if (m_iClip <= 0 && !m_fInSpecialReload && m_iAmmo > 0) { Reload(); } else if (m_fInSpecialReload) { if (m_iClip < m_Info.iAmmoPerMagazine && m_iAmmo > 0) { Reload(); } else { SendWeaponAnim(m_Info.m_AnimEndReload.iSequence); m_fInSpecialReload = FALSE; m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + m_Info.m_AnimEndReload.flTime; } } } } float CShotgun::GetMaxSpeed(void) { return m_Info.flMaxMoveSpeed; }
[ "crskycode@hotmail.com" ]
crskycode@hotmail.com
91b514c30e0fc1a01a11e704e215ea5cfd17d361
7579d827cb7b50b438dfd9ef6fa80ba2797848c9
/sources/plug_osg/src/luna/bind_osg_TriangleMesh.cpp
35597597b0e28e7f125097f8f2bde95a1e381c78
[]
no_license
roche-emmanuel/sgt
809d00b056e36b7799bbb438b8099e3036377377
ee3a550f6172c7d14179d9d171e0124306495e45
refs/heads/master
2021-05-01T12:51:39.983104
2014-09-08T03:35:15
2014-09-08T03:35:15
79,538,908
3
0
null
null
null
null
UTF-8
C++
false
false
44,369
cpp
#include <plug_common.h> #include <luna/wrappers/wrapper_osg_TriangleMesh.h> class luna_wrapper_osg_TriangleMesh { public: typedef Luna< osg::TriangleMesh > luna_t; inline static bool _lg_typecheck_getTable(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } static int _bind_getTable(lua_State *L) { if (!_lg_typecheck_getTable(L)) { luaL_error(L, "luna typecheck failed in getTable function, expected prototype:\ngetTable(). Got arguments:\n%s",luna_dumpStack(L).c_str()); } osg::Referenced* self=(Luna< osg::Referenced >::check(L,1)); if(!self) { luaL_error(L, "Invalid object in function call getTable()"); } luna_wrapper_base* wrapper = luna_caster<osg::Referenced,luna_wrapper_base>::cast(self); //dynamic_cast<luna_wrapper_base*>(self); if(wrapper) { CHECK_RET(wrapper->pushTable(),0,"Cannot push table from value wrapper."); return 1; } return 0; } inline static bool _lg_typecheck_fromVoid(lua_State *L) { if( lua_gettop(L)!=1 ) return false; if( !Luna<void>::has_uniqueid(L,1,3625364) ) return false; return true; } static int _bind_fromVoid(lua_State *L) { if (!_lg_typecheck_fromVoid(L)) { luaL_error(L, "luna typecheck failed in fromVoid function, expected prototype:\nfromVoid(void*). Got arguments:\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self= (osg::TriangleMesh*)(Luna< void >::check(L,1)); if(!self) { luaL_error(L, "Invalid object in function call fromVoid(...)"); } Luna< osg::TriangleMesh >::push(L,self,false); return 1; } inline static bool _lg_typecheck_asVoid(lua_State *L) { if( lua_gettop(L)!=1 ) return false; if( !Luna<void>::has_uniqueid(L,1,50169651) ) return false; return true; } static int _bind_asVoid(lua_State *L) { if (!_lg_typecheck_asVoid(L)) { luaL_error(L, "luna typecheck failed in fromVoid function, expected prototype:\nasVoid(). Got arguments:\n%s",luna_dumpStack(L).c_str()); } void* self= (void*)(Luna< osg::Referenced >::check(L,1)); if(!self) { luaL_error(L, "Invalid object in function call asVoid(...)"); } Luna< void >::push(L,self,false); return 1; } // Derived class converters: static int _cast_from_Referenced(lua_State *L) { // all checked are already performed before reaching this point. //osg::TriangleMesh* ptr= dynamic_cast< osg::TriangleMesh* >(Luna< osg::Referenced >::check(L,1)); osg::TriangleMesh* ptr= luna_caster< osg::Referenced, osg::TriangleMesh >::cast(Luna< osg::Referenced >::check(L,1)); if(!ptr) return 0; // Otherwise push the pointer: Luna< osg::TriangleMesh >::push(L,ptr,false); return 1; }; // Constructor checkers: inline static bool _lg_typecheck_ctor_overload_1(lua_State *L) { if( lua_gettop(L)!=0 ) return false; return true; } inline static bool _lg_typecheck_ctor_overload_2(lua_State *L) { int luatop = lua_gettop(L); if( luatop<1 || luatop>2 ) return false; if( !Luna<void>::has_uniqueid(L,1,50169651) ) return false; if( (!(Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1))) ) return false; if( luatop>1 && !Luna<void>::has_uniqueid(L,2,27134364) ) return false; if( luatop>1 && (!(Luna< osg::CopyOp >::check(L,2))) ) return false; return true; } inline static bool _lg_typecheck_ctor_overload_3(lua_State *L) { if( lua_gettop(L)!=1 ) return false; if( lua_istable(L,1)==0 ) return false; return true; } inline static bool _lg_typecheck_ctor_overload_4(lua_State *L) { int luatop = lua_gettop(L); if( luatop<2 || luatop>3 ) return false; if( lua_istable(L,1)==0 ) return false; if( !Luna<void>::has_uniqueid(L,2,50169651) ) return false; if( (!(Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,2))) ) return false; if( luatop>2 && !Luna<void>::has_uniqueid(L,3,27134364) ) return false; if( luatop>2 && (!(Luna< osg::CopyOp >::check(L,3))) ) return false; return true; } // Function checkers: inline static bool _lg_typecheck_cloneType(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_clone(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( !Luna<void>::has_uniqueid(L,2,27134364) ) return false; return true; } inline static bool _lg_typecheck_isSameKindAs(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false; return true; } inline static bool _lg_typecheck_libraryName(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_className(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_accept_overload_1(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( !Luna<void>::has_uniqueid(L,2,36301858) ) return false; if( (!(Luna< osg::ShapeVisitor >::check(L,2))) ) return false; return true; } inline static bool _lg_typecheck_accept_overload_2(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( !Luna<void>::has_uniqueid(L,2,45826538) ) return false; if( (!(Luna< osg::ConstShapeVisitor >::check(L,2))) ) return false; return true; } inline static bool _lg_typecheck_setVertices(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false; return true; } inline static bool _lg_typecheck_getVertices_overload_1(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_getVertices_overload_2(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_setIndices(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false; return true; } inline static bool _lg_typecheck_getIndices_overload_1(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_getIndices_overload_2(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_base_setThreadSafeRefUnref(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( lua_isboolean(L,2)==0 ) return false; return true; } inline static bool _lg_typecheck_base_setName(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( lua_type(L,2)!=LUA_TSTRING ) return false; return true; } inline static bool _lg_typecheck_base_computeDataVariance(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_base_setUserData(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false; return true; } inline static bool _lg_typecheck_base_getUserData_overload_1(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_base_getUserData_overload_2(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_base_releaseGLObjects(lua_State *L) { int luatop = lua_gettop(L); if( luatop<1 || luatop>2 ) return false; if( luatop>1 && (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false; return true; } inline static bool _lg_typecheck_base_cloneType(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_base_clone(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( !Luna<void>::has_uniqueid(L,2,27134364) ) return false; return true; } inline static bool _lg_typecheck_base_isSameKindAs(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false; return true; } inline static bool _lg_typecheck_base_libraryName(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_base_className(lua_State *L) { if( lua_gettop(L)!=1 ) return false; return true; } inline static bool _lg_typecheck_base_accept_overload_1(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( !Luna<void>::has_uniqueid(L,2,36301858) ) return false; if( (!(Luna< osg::ShapeVisitor >::check(L,2))) ) return false; return true; } inline static bool _lg_typecheck_base_accept_overload_2(lua_State *L) { if( lua_gettop(L)!=2 ) return false; if( !Luna<void>::has_uniqueid(L,2,45826538) ) return false; if( (!(Luna< osg::ConstShapeVisitor >::check(L,2))) ) return false; return true; } // Operator checkers: // (found 0 valid operators) // Constructor binds: // osg::TriangleMesh::TriangleMesh() static osg::TriangleMesh* _bind_ctor_overload_1(lua_State *L) { if (!_lg_typecheck_ctor_overload_1(L)) { luaL_error(L, "luna typecheck failed in osg::TriangleMesh::TriangleMesh() function, expected prototype:\nosg::TriangleMesh::TriangleMesh()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } return new osg::TriangleMesh(); } // osg::TriangleMesh::TriangleMesh(const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY) static osg::TriangleMesh* _bind_ctor_overload_2(lua_State *L) { if (!_lg_typecheck_ctor_overload_2(L)) { luaL_error(L, "luna typecheck failed in osg::TriangleMesh::TriangleMesh(const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY) function, expected prototype:\nosg::TriangleMesh::TriangleMesh(const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY)\nClass arguments details:\narg 1 ID = 50169651\narg 2 ID = 27134364\n\n%s",luna_dumpStack(L).c_str()); } int luatop = lua_gettop(L); const osg::TriangleMesh* mesh_ptr=(Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1)); if( !mesh_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg mesh in osg::TriangleMesh::TriangleMesh function"); } const osg::TriangleMesh & mesh=*mesh_ptr; const osg::CopyOp* copyop_ptr=luatop>1 ? (Luna< osg::CopyOp >::check(L,2)) : NULL; if( luatop>1 && !copyop_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg copyop in osg::TriangleMesh::TriangleMesh function"); } const osg::CopyOp & copyop=luatop>1 ? *copyop_ptr : (const osg::CopyOp&)osg::CopyOp::SHALLOW_COPY; return new osg::TriangleMesh(mesh, copyop); } // osg::TriangleMesh::TriangleMesh(lua_Table * data) static osg::TriangleMesh* _bind_ctor_overload_3(lua_State *L) { if (!_lg_typecheck_ctor_overload_3(L)) { luaL_error(L, "luna typecheck failed in osg::TriangleMesh::TriangleMesh(lua_Table * data) function, expected prototype:\nosg::TriangleMesh::TriangleMesh(lua_Table * data)\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } return new wrapper_osg_TriangleMesh(L,NULL); } // osg::TriangleMesh::TriangleMesh(lua_Table * data, const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY) static osg::TriangleMesh* _bind_ctor_overload_4(lua_State *L) { if (!_lg_typecheck_ctor_overload_4(L)) { luaL_error(L, "luna typecheck failed in osg::TriangleMesh::TriangleMesh(lua_Table * data, const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY) function, expected prototype:\nosg::TriangleMesh::TriangleMesh(lua_Table * data, const osg::TriangleMesh & mesh, const osg::CopyOp & copyop = osg::CopyOp::SHALLOW_COPY)\nClass arguments details:\narg 2 ID = 50169651\narg 3 ID = 27134364\n\n%s",luna_dumpStack(L).c_str()); } int luatop = lua_gettop(L); const osg::TriangleMesh* mesh_ptr=(Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,2)); if( !mesh_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg mesh in osg::TriangleMesh::TriangleMesh function"); } const osg::TriangleMesh & mesh=*mesh_ptr; const osg::CopyOp* copyop_ptr=luatop>2 ? (Luna< osg::CopyOp >::check(L,3)) : NULL; if( luatop>2 && !copyop_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg copyop in osg::TriangleMesh::TriangleMesh function"); } const osg::CopyOp & copyop=luatop>2 ? *copyop_ptr : (const osg::CopyOp&)osg::CopyOp::SHALLOW_COPY; return new wrapper_osg_TriangleMesh(L,NULL, mesh, copyop); } // Overload binder for osg::TriangleMesh::TriangleMesh static osg::TriangleMesh* _bind_ctor(lua_State *L) { if (_lg_typecheck_ctor_overload_1(L)) return _bind_ctor_overload_1(L); if (_lg_typecheck_ctor_overload_2(L)) return _bind_ctor_overload_2(L); if (_lg_typecheck_ctor_overload_3(L)) return _bind_ctor_overload_3(L); if (_lg_typecheck_ctor_overload_4(L)) return _bind_ctor_overload_4(L); luaL_error(L, "error in function TriangleMesh, cannot match any of the overloads for function TriangleMesh:\n TriangleMesh()\n TriangleMesh(const osg::TriangleMesh &, const osg::CopyOp &)\n TriangleMesh(lua_Table *)\n TriangleMesh(lua_Table *, const osg::TriangleMesh &, const osg::CopyOp &)\n"); return NULL; } // Function binds: // osg::Object * osg::TriangleMesh::cloneType() const static int _bind_cloneType(lua_State *L) { if (!_lg_typecheck_cloneType(L)) { luaL_error(L, "luna typecheck failed in osg::Object * osg::TriangleMesh::cloneType() const function, expected prototype:\nosg::Object * osg::TriangleMesh::cloneType() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call osg::Object * osg::TriangleMesh::cloneType() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } osg::Object * lret = self->cloneType(); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::Object >::push(L,lret,false); return 1; } // osg::Object * osg::TriangleMesh::clone(const osg::CopyOp & arg1) const static int _bind_clone(lua_State *L) { if (!_lg_typecheck_clone(L)) { luaL_error(L, "luna typecheck failed in osg::Object * osg::TriangleMesh::clone(const osg::CopyOp & arg1) const function, expected prototype:\nosg::Object * osg::TriangleMesh::clone(const osg::CopyOp & arg1) const\nClass arguments details:\narg 1 ID = 27134364\n\n%s",luna_dumpStack(L).c_str()); } const osg::CopyOp* _arg1_ptr=(Luna< osg::CopyOp >::check(L,2)); if( !_arg1_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::clone function"); } const osg::CopyOp & _arg1=*_arg1_ptr; osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call osg::Object * osg::TriangleMesh::clone(const osg::CopyOp &) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } osg::Object * lret = self->clone(_arg1); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::Object >::push(L,lret,false); return 1; } // bool osg::TriangleMesh::isSameKindAs(const osg::Object * obj) const static int _bind_isSameKindAs(lua_State *L) { if (!_lg_typecheck_isSameKindAs(L)) { luaL_error(L, "luna typecheck failed in bool osg::TriangleMesh::isSameKindAs(const osg::Object * obj) const function, expected prototype:\nbool osg::TriangleMesh::isSameKindAs(const osg::Object * obj) const\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str()); } const osg::Object* obj=(Luna< osg::Referenced >::checkSubType< osg::Object >(L,2)); osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call bool osg::TriangleMesh::isSameKindAs(const osg::Object *) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } bool lret = self->isSameKindAs(obj); lua_pushboolean(L,lret?1:0); return 1; } // const char * osg::TriangleMesh::libraryName() const static int _bind_libraryName(lua_State *L) { if (!_lg_typecheck_libraryName(L)) { luaL_error(L, "luna typecheck failed in const char * osg::TriangleMesh::libraryName() const function, expected prototype:\nconst char * osg::TriangleMesh::libraryName() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call const char * osg::TriangleMesh::libraryName() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } const char * lret = self->libraryName(); lua_pushstring(L,lret); return 1; } // const char * osg::TriangleMesh::className() const static int _bind_className(lua_State *L) { if (!_lg_typecheck_className(L)) { luaL_error(L, "luna typecheck failed in const char * osg::TriangleMesh::className() const function, expected prototype:\nconst char * osg::TriangleMesh::className() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call const char * osg::TriangleMesh::className() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } const char * lret = self->className(); lua_pushstring(L,lret); return 1; } // void osg::TriangleMesh::accept(osg::ShapeVisitor & arg1) static int _bind_accept_overload_1(lua_State *L) { if (!_lg_typecheck_accept_overload_1(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::accept(osg::ShapeVisitor & arg1) function, expected prototype:\nvoid osg::TriangleMesh::accept(osg::ShapeVisitor & arg1)\nClass arguments details:\narg 1 ID = 36301858\n\n%s",luna_dumpStack(L).c_str()); } osg::ShapeVisitor* _arg1_ptr=(Luna< osg::ShapeVisitor >::check(L,2)); if( !_arg1_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::accept function"); } osg::ShapeVisitor & _arg1=*_arg1_ptr; osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::accept(osg::ShapeVisitor &). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->accept(_arg1); return 0; } // void osg::TriangleMesh::accept(osg::ConstShapeVisitor & arg1) const static int _bind_accept_overload_2(lua_State *L) { if (!_lg_typecheck_accept_overload_2(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::accept(osg::ConstShapeVisitor & arg1) const function, expected prototype:\nvoid osg::TriangleMesh::accept(osg::ConstShapeVisitor & arg1) const\nClass arguments details:\narg 1 ID = 45826538\n\n%s",luna_dumpStack(L).c_str()); } osg::ConstShapeVisitor* _arg1_ptr=(Luna< osg::ConstShapeVisitor >::check(L,2)); if( !_arg1_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::accept function"); } osg::ConstShapeVisitor & _arg1=*_arg1_ptr; osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::accept(osg::ConstShapeVisitor &) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->accept(_arg1); return 0; } // Overload binder for osg::TriangleMesh::accept static int _bind_accept(lua_State *L) { if (_lg_typecheck_accept_overload_1(L)) return _bind_accept_overload_1(L); if (_lg_typecheck_accept_overload_2(L)) return _bind_accept_overload_2(L); luaL_error(L, "error in function accept, cannot match any of the overloads for function accept:\n accept(osg::ShapeVisitor &)\n accept(osg::ConstShapeVisitor &)\n"); return 0; } // void osg::TriangleMesh::setVertices(osg::Vec3Array * vertices) static int _bind_setVertices(lua_State *L) { if (!_lg_typecheck_setVertices(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::setVertices(osg::Vec3Array * vertices) function, expected prototype:\nvoid osg::TriangleMesh::setVertices(osg::Vec3Array * vertices)\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str()); } osg::Vec3Array* vertices=(Luna< osg::Referenced >::checkSubType< osg::Vec3Array >(L,2)); osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::setVertices(osg::Vec3Array *). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->setVertices(vertices); return 0; } // osg::Vec3Array * osg::TriangleMesh::getVertices() static int _bind_getVertices_overload_1(lua_State *L) { if (!_lg_typecheck_getVertices_overload_1(L)) { luaL_error(L, "luna typecheck failed in osg::Vec3Array * osg::TriangleMesh::getVertices() function, expected prototype:\nosg::Vec3Array * osg::TriangleMesh::getVertices()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call osg::Vec3Array * osg::TriangleMesh::getVertices(). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } osg::Vec3Array * lret = self->getVertices(); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::Vec3Array >::push(L,lret,false); return 1; } // const osg::Vec3Array * osg::TriangleMesh::getVertices() const static int _bind_getVertices_overload_2(lua_State *L) { if (!_lg_typecheck_getVertices_overload_2(L)) { luaL_error(L, "luna typecheck failed in const osg::Vec3Array * osg::TriangleMesh::getVertices() const function, expected prototype:\nconst osg::Vec3Array * osg::TriangleMesh::getVertices() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call const osg::Vec3Array * osg::TriangleMesh::getVertices() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } const osg::Vec3Array * lret = self->getVertices(); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::Vec3Array >::push(L,lret,false); return 1; } // Overload binder for osg::TriangleMesh::getVertices static int _bind_getVertices(lua_State *L) { if (_lg_typecheck_getVertices_overload_1(L)) return _bind_getVertices_overload_1(L); if (_lg_typecheck_getVertices_overload_2(L)) return _bind_getVertices_overload_2(L); luaL_error(L, "error in function getVertices, cannot match any of the overloads for function getVertices:\n getVertices()\n getVertices()\n"); return 0; } // void osg::TriangleMesh::setIndices(osg::IndexArray * indices) static int _bind_setIndices(lua_State *L) { if (!_lg_typecheck_setIndices(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::setIndices(osg::IndexArray * indices) function, expected prototype:\nvoid osg::TriangleMesh::setIndices(osg::IndexArray * indices)\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str()); } osg::IndexArray* indices=(Luna< osg::Referenced >::checkSubType< osg::IndexArray >(L,2)); osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::setIndices(osg::IndexArray *). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->setIndices(indices); return 0; } // osg::IndexArray * osg::TriangleMesh::getIndices() static int _bind_getIndices_overload_1(lua_State *L) { if (!_lg_typecheck_getIndices_overload_1(L)) { luaL_error(L, "luna typecheck failed in osg::IndexArray * osg::TriangleMesh::getIndices() function, expected prototype:\nosg::IndexArray * osg::TriangleMesh::getIndices()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call osg::IndexArray * osg::TriangleMesh::getIndices(). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } osg::IndexArray * lret = self->getIndices(); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::IndexArray >::push(L,lret,false); return 1; } // const osg::IndexArray * osg::TriangleMesh::getIndices() const static int _bind_getIndices_overload_2(lua_State *L) { if (!_lg_typecheck_getIndices_overload_2(L)) { luaL_error(L, "luna typecheck failed in const osg::IndexArray * osg::TriangleMesh::getIndices() const function, expected prototype:\nconst osg::IndexArray * osg::TriangleMesh::getIndices() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call const osg::IndexArray * osg::TriangleMesh::getIndices() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } const osg::IndexArray * lret = self->getIndices(); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::IndexArray >::push(L,lret,false); return 1; } // Overload binder for osg::TriangleMesh::getIndices static int _bind_getIndices(lua_State *L) { if (_lg_typecheck_getIndices_overload_1(L)) return _bind_getIndices_overload_1(L); if (_lg_typecheck_getIndices_overload_2(L)) return _bind_getIndices_overload_2(L); luaL_error(L, "error in function getIndices, cannot match any of the overloads for function getIndices:\n getIndices()\n getIndices()\n"); return 0; } // void osg::TriangleMesh::base_setThreadSafeRefUnref(bool threadSafe) static int _bind_base_setThreadSafeRefUnref(lua_State *L) { if (!_lg_typecheck_base_setThreadSafeRefUnref(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_setThreadSafeRefUnref(bool threadSafe) function, expected prototype:\nvoid osg::TriangleMesh::base_setThreadSafeRefUnref(bool threadSafe)\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } bool threadSafe=(bool)(lua_toboolean(L,2)==1); osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_setThreadSafeRefUnref(bool). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->TriangleMesh::setThreadSafeRefUnref(threadSafe); return 0; } // void osg::TriangleMesh::base_setName(const std::string & name) static int _bind_base_setName(lua_State *L) { if (!_lg_typecheck_base_setName(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_setName(const std::string & name) function, expected prototype:\nvoid osg::TriangleMesh::base_setName(const std::string & name)\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } std::string name(lua_tostring(L,2),lua_objlen(L,2)); osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_setName(const std::string &). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->TriangleMesh::setName(name); return 0; } // void osg::TriangleMesh::base_computeDataVariance() static int _bind_base_computeDataVariance(lua_State *L) { if (!_lg_typecheck_base_computeDataVariance(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_computeDataVariance() function, expected prototype:\nvoid osg::TriangleMesh::base_computeDataVariance()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_computeDataVariance(). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->TriangleMesh::computeDataVariance(); return 0; } // void osg::TriangleMesh::base_setUserData(osg::Referenced * obj) static int _bind_base_setUserData(lua_State *L) { if (!_lg_typecheck_base_setUserData(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_setUserData(osg::Referenced * obj) function, expected prototype:\nvoid osg::TriangleMesh::base_setUserData(osg::Referenced * obj)\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str()); } osg::Referenced* obj=(Luna< osg::Referenced >::check(L,2)); osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_setUserData(osg::Referenced *). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->TriangleMesh::setUserData(obj); return 0; } // osg::Referenced * osg::TriangleMesh::base_getUserData() static int _bind_base_getUserData_overload_1(lua_State *L) { if (!_lg_typecheck_base_getUserData_overload_1(L)) { luaL_error(L, "luna typecheck failed in osg::Referenced * osg::TriangleMesh::base_getUserData() function, expected prototype:\nosg::Referenced * osg::TriangleMesh::base_getUserData()\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call osg::Referenced * osg::TriangleMesh::base_getUserData(). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } osg::Referenced * lret = self->TriangleMesh::getUserData(); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::Referenced >::push(L,lret,false); return 1; } // const osg::Referenced * osg::TriangleMesh::base_getUserData() const static int _bind_base_getUserData_overload_2(lua_State *L) { if (!_lg_typecheck_base_getUserData_overload_2(L)) { luaL_error(L, "luna typecheck failed in const osg::Referenced * osg::TriangleMesh::base_getUserData() const function, expected prototype:\nconst osg::Referenced * osg::TriangleMesh::base_getUserData() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call const osg::Referenced * osg::TriangleMesh::base_getUserData() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } const osg::Referenced * lret = self->TriangleMesh::getUserData(); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::Referenced >::push(L,lret,false); return 1; } // Overload binder for osg::TriangleMesh::base_getUserData static int _bind_base_getUserData(lua_State *L) { if (_lg_typecheck_base_getUserData_overload_1(L)) return _bind_base_getUserData_overload_1(L); if (_lg_typecheck_base_getUserData_overload_2(L)) return _bind_base_getUserData_overload_2(L); luaL_error(L, "error in function base_getUserData, cannot match any of the overloads for function base_getUserData:\n base_getUserData()\n base_getUserData()\n"); return 0; } // void osg::TriangleMesh::base_releaseGLObjects(osg::State * arg1 = 0) const static int _bind_base_releaseGLObjects(lua_State *L) { if (!_lg_typecheck_base_releaseGLObjects(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_releaseGLObjects(osg::State * arg1 = 0) const function, expected prototype:\nvoid osg::TriangleMesh::base_releaseGLObjects(osg::State * arg1 = 0) const\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str()); } int luatop = lua_gettop(L); osg::State* _arg1=luatop>1 ? (Luna< osg::Referenced >::checkSubType< osg::State >(L,2)) : (osg::State*)0; osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_releaseGLObjects(osg::State *) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->TriangleMesh::releaseGLObjects(_arg1); return 0; } // osg::Object * osg::TriangleMesh::base_cloneType() const static int _bind_base_cloneType(lua_State *L) { if (!_lg_typecheck_base_cloneType(L)) { luaL_error(L, "luna typecheck failed in osg::Object * osg::TriangleMesh::base_cloneType() const function, expected prototype:\nosg::Object * osg::TriangleMesh::base_cloneType() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call osg::Object * osg::TriangleMesh::base_cloneType() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } osg::Object * lret = self->TriangleMesh::cloneType(); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::Object >::push(L,lret,false); return 1; } // osg::Object * osg::TriangleMesh::base_clone(const osg::CopyOp & arg1) const static int _bind_base_clone(lua_State *L) { if (!_lg_typecheck_base_clone(L)) { luaL_error(L, "luna typecheck failed in osg::Object * osg::TriangleMesh::base_clone(const osg::CopyOp & arg1) const function, expected prototype:\nosg::Object * osg::TriangleMesh::base_clone(const osg::CopyOp & arg1) const\nClass arguments details:\narg 1 ID = 27134364\n\n%s",luna_dumpStack(L).c_str()); } const osg::CopyOp* _arg1_ptr=(Luna< osg::CopyOp >::check(L,2)); if( !_arg1_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::base_clone function"); } const osg::CopyOp & _arg1=*_arg1_ptr; osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call osg::Object * osg::TriangleMesh::base_clone(const osg::CopyOp &) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } osg::Object * lret = self->TriangleMesh::clone(_arg1); if(!lret) return 0; // Do not write NULL pointers. Luna< osg::Object >::push(L,lret,false); return 1; } // bool osg::TriangleMesh::base_isSameKindAs(const osg::Object * obj) const static int _bind_base_isSameKindAs(lua_State *L) { if (!_lg_typecheck_base_isSameKindAs(L)) { luaL_error(L, "luna typecheck failed in bool osg::TriangleMesh::base_isSameKindAs(const osg::Object * obj) const function, expected prototype:\nbool osg::TriangleMesh::base_isSameKindAs(const osg::Object * obj) const\nClass arguments details:\narg 1 ID = 50169651\n\n%s",luna_dumpStack(L).c_str()); } const osg::Object* obj=(Luna< osg::Referenced >::checkSubType< osg::Object >(L,2)); osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call bool osg::TriangleMesh::base_isSameKindAs(const osg::Object *) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } bool lret = self->TriangleMesh::isSameKindAs(obj); lua_pushboolean(L,lret?1:0); return 1; } // const char * osg::TriangleMesh::base_libraryName() const static int _bind_base_libraryName(lua_State *L) { if (!_lg_typecheck_base_libraryName(L)) { luaL_error(L, "luna typecheck failed in const char * osg::TriangleMesh::base_libraryName() const function, expected prototype:\nconst char * osg::TriangleMesh::base_libraryName() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call const char * osg::TriangleMesh::base_libraryName() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } const char * lret = self->TriangleMesh::libraryName(); lua_pushstring(L,lret); return 1; } // const char * osg::TriangleMesh::base_className() const static int _bind_base_className(lua_State *L) { if (!_lg_typecheck_base_className(L)) { luaL_error(L, "luna typecheck failed in const char * osg::TriangleMesh::base_className() const function, expected prototype:\nconst char * osg::TriangleMesh::base_className() const\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str()); } osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call const char * osg::TriangleMesh::base_className() const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } const char * lret = self->TriangleMesh::className(); lua_pushstring(L,lret); return 1; } // void osg::TriangleMesh::base_accept(osg::ShapeVisitor & arg1) static int _bind_base_accept_overload_1(lua_State *L) { if (!_lg_typecheck_base_accept_overload_1(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_accept(osg::ShapeVisitor & arg1) function, expected prototype:\nvoid osg::TriangleMesh::base_accept(osg::ShapeVisitor & arg1)\nClass arguments details:\narg 1 ID = 36301858\n\n%s",luna_dumpStack(L).c_str()); } osg::ShapeVisitor* _arg1_ptr=(Luna< osg::ShapeVisitor >::check(L,2)); if( !_arg1_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::base_accept function"); } osg::ShapeVisitor & _arg1=*_arg1_ptr; osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_accept(osg::ShapeVisitor &). Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->TriangleMesh::accept(_arg1); return 0; } // void osg::TriangleMesh::base_accept(osg::ConstShapeVisitor & arg1) const static int _bind_base_accept_overload_2(lua_State *L) { if (!_lg_typecheck_base_accept_overload_2(L)) { luaL_error(L, "luna typecheck failed in void osg::TriangleMesh::base_accept(osg::ConstShapeVisitor & arg1) const function, expected prototype:\nvoid osg::TriangleMesh::base_accept(osg::ConstShapeVisitor & arg1) const\nClass arguments details:\narg 1 ID = 45826538\n\n%s",luna_dumpStack(L).c_str()); } osg::ConstShapeVisitor* _arg1_ptr=(Luna< osg::ConstShapeVisitor >::check(L,2)); if( !_arg1_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg _arg1 in osg::TriangleMesh::base_accept function"); } osg::ConstShapeVisitor & _arg1=*_arg1_ptr; osg::TriangleMesh* self=Luna< osg::Referenced >::checkSubType< osg::TriangleMesh >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void osg::TriangleMesh::base_accept(osg::ConstShapeVisitor &) const. Got : '%s'\n%s",typeid(Luna< osg::Referenced >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->TriangleMesh::accept(_arg1); return 0; } // Overload binder for osg::TriangleMesh::base_accept static int _bind_base_accept(lua_State *L) { if (_lg_typecheck_base_accept_overload_1(L)) return _bind_base_accept_overload_1(L); if (_lg_typecheck_base_accept_overload_2(L)) return _bind_base_accept_overload_2(L); luaL_error(L, "error in function base_accept, cannot match any of the overloads for function base_accept:\n base_accept(osg::ShapeVisitor &)\n base_accept(osg::ConstShapeVisitor &)\n"); return 0; } // Operator binds: }; osg::TriangleMesh* LunaTraits< osg::TriangleMesh >::_bind_ctor(lua_State *L) { return luna_wrapper_osg_TriangleMesh::_bind_ctor(L); } void LunaTraits< osg::TriangleMesh >::_bind_dtor(osg::TriangleMesh* obj) { osg::ref_ptr<osg::Referenced> refptr = obj; } const char LunaTraits< osg::TriangleMesh >::className[] = "TriangleMesh"; const char LunaTraits< osg::TriangleMesh >::fullName[] = "osg::TriangleMesh"; const char LunaTraits< osg::TriangleMesh >::moduleName[] = "osg"; const char* LunaTraits< osg::TriangleMesh >::parents[] = {"osg.Shape", 0}; const int LunaTraits< osg::TriangleMesh >::hash = 23977023; const int LunaTraits< osg::TriangleMesh >::uniqueIDs[] = {50169651,0}; luna_RegType LunaTraits< osg::TriangleMesh >::methods[] = { {"cloneType", &luna_wrapper_osg_TriangleMesh::_bind_cloneType}, {"clone", &luna_wrapper_osg_TriangleMesh::_bind_clone}, {"isSameKindAs", &luna_wrapper_osg_TriangleMesh::_bind_isSameKindAs}, {"libraryName", &luna_wrapper_osg_TriangleMesh::_bind_libraryName}, {"className", &luna_wrapper_osg_TriangleMesh::_bind_className}, {"accept", &luna_wrapper_osg_TriangleMesh::_bind_accept}, {"setVertices", &luna_wrapper_osg_TriangleMesh::_bind_setVertices}, {"getVertices", &luna_wrapper_osg_TriangleMesh::_bind_getVertices}, {"setIndices", &luna_wrapper_osg_TriangleMesh::_bind_setIndices}, {"getIndices", &luna_wrapper_osg_TriangleMesh::_bind_getIndices}, {"base_setThreadSafeRefUnref", &luna_wrapper_osg_TriangleMesh::_bind_base_setThreadSafeRefUnref}, {"base_setName", &luna_wrapper_osg_TriangleMesh::_bind_base_setName}, {"base_computeDataVariance", &luna_wrapper_osg_TriangleMesh::_bind_base_computeDataVariance}, {"base_setUserData", &luna_wrapper_osg_TriangleMesh::_bind_base_setUserData}, {"base_getUserData", &luna_wrapper_osg_TriangleMesh::_bind_base_getUserData}, {"base_releaseGLObjects", &luna_wrapper_osg_TriangleMesh::_bind_base_releaseGLObjects}, {"base_cloneType", &luna_wrapper_osg_TriangleMesh::_bind_base_cloneType}, {"base_clone", &luna_wrapper_osg_TriangleMesh::_bind_base_clone}, {"base_isSameKindAs", &luna_wrapper_osg_TriangleMesh::_bind_base_isSameKindAs}, {"base_libraryName", &luna_wrapper_osg_TriangleMesh::_bind_base_libraryName}, {"base_className", &luna_wrapper_osg_TriangleMesh::_bind_base_className}, {"base_accept", &luna_wrapper_osg_TriangleMesh::_bind_base_accept}, {"fromVoid", &luna_wrapper_osg_TriangleMesh::_bind_fromVoid}, {"asVoid", &luna_wrapper_osg_TriangleMesh::_bind_asVoid}, {"getTable", &luna_wrapper_osg_TriangleMesh::_bind_getTable}, {0,0} }; luna_ConverterType LunaTraits< osg::TriangleMesh >::converters[] = { {"osg::Referenced", &luna_wrapper_osg_TriangleMesh::_cast_from_Referenced}, {0,0} }; luna_RegEnumType LunaTraits< osg::TriangleMesh >::enumValues[] = { {0,0} };
[ "roche.emmanuel@gmail.com" ]
roche.emmanuel@gmail.com
d5b6ab248e0aeda7aa3dda4c2d2c877402381f11
6bec8cb6f04389c9d2c51b160dc454629f1db66d
/src/decision/subroutines/qualification/include/LineUpWithGate.h
986293cb7765ae31976072389118c7087e1ad6a2
[]
no_license
SoleSun/SubBots-Legacy
9592e62836a4a75201abc2fffec05c20a4a02112
f416e2f244ac4be4d6c95b5ea749fc38ad9ce61e
refs/heads/master
2020-04-02T12:40:24.483562
2018-10-24T05:52:30
2018-10-24T05:52:30
154,445,436
0
0
null
null
null
null
UTF-8
C++
false
false
873
h
/* * Created By: Reid Oliveira * Created On: March 24, 2018 * Description: Subroutine that tries to position the sub in front and * orthogonal with the gate, ready to go through. */ #ifndef DECISION_LINEUPWITHGATE_H #define DECISION_LINEUPWITHGATE_H #include "Subroutine.h" #include <gate_detect/gateDetectMsg.h> #include <std_msgs/String.h> /* * Subroutine: LineUpWithGate * * Function: attempts to get into an orthogonal position with the gate * */ class LineUpWithGate : public Subroutine { public: LineUpWithGate(int argc, char** argv, std::string node_name) : Subroutine(argc, argv, node_name) {} void setupSubscriptions(ros::NodeHandle nh) override; private: void decisionCallback(const gate_detect::gateDetectMsg::ConstPtr& msg); void balance(const geometry_msgs::Twist::ConstPtr& msg); }; #endif // DECISION_LINEUPWITHGATE_H
[ "joel.ahn@alumni.ubc.ca" ]
joel.ahn@alumni.ubc.ca
add06df63d4a028d94ac0231ce3f0d306c8c414f
70eb368ea25ad8767e6713ea88936642154f43ae
/workUndone/Suite15/OpenFlight_API/samples/plugins/skyscraper/buildskyscraper.cpp
6933115b6ae6c6229d83ebe18d96b5b07706f88d
[]
no_license
CatalinaPrisacaru/Di-Java
816cb3428d5026fb63934e14d09c422aa1537b08
1c35b28e0b8c8f3c25afbc7b2c0a7fe8cac96c6b
refs/heads/develop
2021-01-18T02:23:47.759177
2016-04-11T19:55:35
2016-04-11T19:55:35
54,333,823
0
0
null
2016-03-20T18:36:51
2016-03-20T18:36:51
null
UTF-8
C++
false
false
3,793
cpp
#include "buildskyscraper.h" #include "helpers.h" static void buildSide(const Box &i_dimensions, mgrec *i_parent, unsigned int i_xLightCount, unsigned int i_yLightCount, const LightBuilder &i_lightBuilder) { i_yLightCount++; for(unsigned int y = 1 ; y < i_yLightCount ; y++) { double at = (double)y / (double)i_yLightCount; mgcoord3d end1 = interpolate3d(i_dimensions.getCloseBottomLeft(), i_dimensions.getCloseTopLeft(), at); mgcoord3d end2 = interpolate3d(i_dimensions.getFarBottomRight(), i_dimensions.getFarTopRight(), at); i_lightBuilder.buildLightStringExcludingEnds(end1, end2, i_xLightCount, NULL); } buildTriangle(i_parent, i_dimensions.getCloseBottomLeft(), i_dimensions.getFarBottomRight(), i_dimensions.getFarTopRight()); buildTriangle(i_parent, i_dimensions.getCloseBottomLeft(), i_dimensions.getFarTopRight(), i_dimensions.getCloseTopLeft()); } void buildSkyscraper(const Box &i_dimensions, double i_antennaHeight, mgrec *i_parent, unsigned int i_xLightCount, unsigned int i_yLightCount, unsigned int i_zLightCount, unsigned int i_antennaLightCount, const LightBuilder &i_sides, const LightBuilder &i_verticals, const LightBuilder &i_top, const LightBuilder &i_corners, const LightBuilder &i_antenna) { Box dimensions = i_dimensions; dimensions.assureCorrectness(); mgcoord3d downNormal = mgCoord3dNegativeZAxis(); // front buildSide(Box(dimensions.getCloseBottomLeft(), dimensions.getCloseTopRight()), i_parent, i_xLightCount, i_zLightCount, i_sides); i_top.buildLightStringExcludingEnds(dimensions.getCloseTopLeft(), dimensions.getCloseTopRight(), i_xLightCount, &downNormal); // right buildSide(Box(dimensions.getCloseBottomRight(), dimensions.getFarTopRight()), i_parent, i_yLightCount, i_zLightCount, i_sides); i_top.buildLightStringExcludingEnds(dimensions.getCloseTopRight(), dimensions.getFarTopRight(), i_yLightCount, &downNormal); // back buildSide(Box(dimensions.getFarBottomRight(), dimensions.getFarTopLeft()), i_parent, i_xLightCount, i_zLightCount, i_sides); i_top.buildLightStringExcludingEnds(dimensions.getFarTopRight(), dimensions.getFarTopLeft(), i_xLightCount, &downNormal); // left buildSide(Box(dimensions.getFarBottomLeft(), dimensions.getCloseTopLeft()), i_parent, i_yLightCount, i_zLightCount, i_sides); i_top.buildLightStringExcludingEnds(dimensions.getFarTopLeft(), dimensions.getCloseTopLeft(), i_yLightCount, &downNormal); // close left i_verticals.buildLightStringExcludingEnds(dimensions.getCloseBottomLeft(), dimensions.getCloseTopLeft(), i_zLightCount, NULL); i_corners.buildLight(dimensions.getCloseTopLeft(), NULL); // close right i_verticals.buildLightStringExcludingEnds(dimensions.getCloseBottomRight(), dimensions.getCloseTopRight(), i_zLightCount, NULL); i_corners.buildLight(dimensions.getCloseTopRight(), NULL); // far right i_verticals.buildLightStringExcludingEnds(dimensions.getFarBottomRight(), dimensions.getFarTopRight(), i_zLightCount, NULL); i_corners.buildLight(dimensions.getFarTopRight(), NULL); // far left i_verticals.buildLightStringExcludingEnds(dimensions.getFarBottomLeft(), dimensions.getFarTopLeft(), i_zLightCount, NULL); i_corners.buildLight(dimensions.getFarTopLeft(), NULL); // top buildTriangle(i_parent, dimensions.getCloseTopLeft(), dimensions.getCloseTopRight(), dimensions.getFarTopRight()); buildTriangle(i_parent, dimensions.getCloseTopLeft(), dimensions.getFarTopRight(), dimensions.getFarTopLeft()); // antenna mgcoord3d antennaBottom = dimensions.getTopCenter(); mgcoord3d antennaTop = antennaBottom; antennaTop.z += i_antennaHeight; i_antenna.buildLightStringIncludingEnds(antennaBottom, antennaTop, i_antennaLightCount, &downNormal); }
[ "albisteanu.sebastian@yahoo.com" ]
albisteanu.sebastian@yahoo.com
3a3a63551084692ada56744e6dd3f03e10758124
5fc0e828a935fefcc22fc5161e1640a8ad21d67f
/osapi/inc/osapi/Exceptions.hpp
af8af332bae8b6e95af30853d34a0732a522ad2f
[]
no_license
Berthelmaster/Projekt3
e7374d24a42da51dc34474a5c1eebc9111f87566
dbd6db5103f739d390ba56fdc26086ef5a57be9e
refs/heads/master
2020-04-04T01:55:41.356297
2018-12-17T12:43:16
2018-12-17T12:43:16
155,682,182
5
1
null
null
null
null
UTF-8
C++
false
false
264
hpp
#ifndef OSAPI_EXCEPTIONS_HPP #define OSAPI_EXCEPTIONS_HPP #include <stdexcept> namespace osapi { class SystemError : public std::runtime_error { public: SystemError(const std::string& what_arg) : std::runtime_error(what_arg) {} private: }; } #endif
[ "apollotoby@gmail.com" ]
apollotoby@gmail.com
4c3cfe78bf472a4b53828f8b9a8acfe2c1399ce0
aa2c9edcdd4be2c3f0aaa641378cee8dabd75842
/chp17d/part2.cpp
a0bd81b8214f5c7d3c91d810d1f59b16d59c9f73
[]
no_license
asztalosattila007/bevprog
46cbf73767c0407d06b33ca57596eae5423c75a0
8b13194926972a8d5b58d490be1c8dd18e7ea6e4
refs/heads/master
2023-01-23T19:30:34.421406
2020-12-01T21:50:51
2020-12-01T21:50:51
296,564,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,465
cpp
#include "std_lib_facilities.h" void print_array(ostream& os, int* a, int n) { for (int i= 0 ; i< n ; i++) os << a[i] << "\n"; } int main() { int init = 7; // 1 .fel inicializált változó int* p1 = &init; cout<<"content of p1= " << *p1 << endl; //2. cout<<"p1= " << p1 << endl; int* p2 = new int[7]{1,2,4,8,16,32,64}; //3. cout<<"p2= " << p2 << endl; //4.fel cout<<"content of p2= " << endl; print_array(cout,p2,7); int* p3 = p2; //5. p2 = p1; //6. p2 = p3; //7. cout<<" p1= " << p1 << endl; //8. cout<<"content of p1= " << *p1 << endl; //print_array(cout,p1,7); cout<<"p2= " << p2 << endl; cout<<"content of p2= " << endl; print_array(cout,p2,7); //9. p2= p1 és p2=p3 delete[] p3; // p2 = p3 miatt lehet delete[] p2; is int tomb2[10] = {1,2,4,8,16,32,64,128,256,512}; //10. p1 = tomb2; //cout << p1 << endl; //címet írja ki //cout << *p1 << endl; // 0. elemét írja ki a tömbnek int tomb3[10] ; //11. p2 = tomb3; cout << "content of p2[10]= " << endl; for (int i = 0; i < 10; ++i) //12 { p2[i]=p1[i]; } print_array(cout,p2,10); cout << " content of p2 vector=" << endl; vector<int> v1 = {1,2,4,8,16,32,64,128,256,512}; vector<int> v2 ; v2 = v1; for (int i= 0 ; i< v2.size(); i++) { cout << v2[i] << "\n"; } return 0; }
[ "asztalosattila007@gmail.com" ]
asztalosattila007@gmail.com
cc2d6edceb1c6e528ac1b42960314ae5b70d7348
88a81a1685d2f02a529e1ba8bc477a8cbdc27af4
/src/Shin/ShinAI.cpp
87b0af1f0cc061d547ec3f84c5a394380b4f6830
[]
no_license
MarcBrout/HiShinUnit
4901ae768803aab10ce66135fc60b5e28e07b9ef
acd62cb8808f1369c5abf56b1652c02068a3dc31
refs/heads/master
2021-08-28T07:49:24.717023
2017-12-11T15:17:24
2017-12-11T15:17:24
113,872,711
2
0
null
null
null
null
UTF-8
C++
false
false
4,424
cpp
// // Created by 53818 on 04/12/2017. // #include <Shin/ShinHalbard.hpp> #include <iostream> #include "Shin/ShinCase.hpp" #include "Shin/ShinAI.hpp" namespace ai { void ShinAI::initializeCases(Board const &board, std::deque<std::unique_ptr<ai::AICase>> &outCases, size_t round) { for (uint32_t y = 0; y < board.getSize(); ++y) { for (uint32_t x = 0; x < board.getSize(); ++x) { if (board[y][x] == CellState::Empty) { threadPool.addCase(std::make_unique<ai::ShinCase>(board, x, y, round, CellState::Player1)); threadPool.addCase(std::make_unique<ai::ShinCase>(board, x, y, round, CellState::Player2)); } } } } void ShinAI::resolve(std::deque<std::unique_ptr<ai::AICase>> &casesDone, Position &posOut) { myPlays.clear(); enemyPlays.clear(); // Splitting the processed cases in their respective container while (!casesDone.empty()) { if ((*casesDone.front()).getPlayer() == CellState::Player1) { const Position& pos = (*casesDone.front()).getPos(); myPlays.addCase(casesDone.front()); } else { Position const &pos = (*casesDone.front()).getPos(); enemyPlays.addCase(casesDone.front()); } casesDone.pop_front(); } // Can I win ? if (myPlays.getCount(Line::FINAL_WIN) > 0) { simplePlay(posOut, Line::FINAL_WIN, myPlays); return ; } // Can I Lose ? if (enemyPlays.getCount(Line::FINAL_WIN) > 0) { simplePlay(posOut, Line::FINAL_WIN, enemyPlays); return ; } uint32_t myWins = myPlays.getCount(Line::WIN); uint32_t enemyWins = enemyPlays.getCount(Line::WIN); if (myWins >= enemyWins && myWins > 0) { fusionPlays(posOut, Line::WIN, CellState::Player1); } else if (enemyWins > myWins) { fusionPlays(posOut, Line::WIN, CellState::Player2); } else { fusionPlays(posOut, Line::HIGH, Empty); } } bool findCommonValuePosition(std::vector<Position> const &myFusion, std::vector<Position> const &enemyFusion, Position &outPos) { for (Position const &myPos : myFusion) { for (Position const &enemyPos : enemyFusion) { if (myPos == enemyPos) { outPos = myPos; return true; } } } return false; } void ShinAI::fusionPlays(Position &outPos, Line::Values value, CellState priority) { Line::Values myBestPlay; Line::Values enemyBestPlay; std::vector<Position> myFusion = myPlays.getMaxPositions(value, myBestPlay); std::vector<Position> enemyFusion = enemyPlays.getMaxPositions(value, enemyBestPlay); if (priority != CellState::Empty) { if (!myFusion.empty() && !enemyFusion.empty() && findCommonValuePosition(myFusion, enemyFusion, outPos)) { return; } if (priority == CellState::Player1) { outPos = myFusion.front(); } else { outPos = enemyFusion.front(); } } else { if (myBestPlay > enemyBestPlay) { if (!myFusion.empty() && !enemyFusion.empty() && findCommonValuePosition(myFusion, enemyFusion, outPos)) { return; } outPos = myFusion.front(); } else if (enemyBestPlay > myBestPlay) { if (!myFusion.empty() && !enemyFusion.empty() && findCommonValuePosition(enemyFusion, myFusion, outPos)) { return; } outPos = enemyFusion.front(); } else { if (enemyFusion.size() > myFusion.size()) { outPos = enemyFusion.front(); } else { outPos = myFusion.front(); } } } } void ShinAI::simplePlay(Position &outPos, Line::Values value, ShinHalbard &halbard) { Line::Values best; std::vector<Position> plays = halbard.getMaxPositions(value, best); outPos = plays.front(); } ShinAI::ShinAI(unsigned int threadCount, unsigned int timeLimit) : AAI(threadCount, timeLimit) { } }
[ "brout.marc@epitech.eu" ]
brout.marc@epitech.eu
b3ca5eba0e98870bca8d49a902dcf4d84fe26e16
13e11e1019914694d202b4acc20ea1ff14345159
/Back-end/src/Workflow/Node.cpp
cc10923dca04e36792e3c60b374f4967193a38ed
[ "Apache-2.0", "BSL-1.0" ]
permissive
lee-novobi/Frameworks
e5ef6afdf866bb119e41f5a627e695a89c561703
016efe98a42e0b6a8ee09feea08aa52343bb90e4
refs/heads/master
2021-05-28T19:03:02.806782
2014-07-19T09:14:48
2014-07-19T09:14:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,227
cpp
// #include "PrototypeConfig.h" // #ifndef LINUX // #include "StdAfx.h" // #endif #include "Node.h" #include "../Action/Action.h" #include "../Processor/FunctionInterface.h" class CPingAction; class CTelnetAction; class CLoginWebAction; class CLoginAppAction; class CCheckCCUAction; CNode::CNode(void) { m_nCurrentIndex = 0; m_pAction = NULL; m_pParentNode = NULL; } CNode::CNode (int iActId, MA_RESULT eResult, int iChildArraySize, METHOD_ID eMethodID, CONDITION_ID eConditionID) { m_nCurrentIndex = 0; m_pAction = NULL; m_pParentNode = NULL; m_iActId = iActId; m_eResult = eResult; m_iChildArraySize = iChildArraySize; m_eConditionID = eConditionID; m_eMethodID = eMethodID; } CNode::~CNode(void) { cout<<"delete CNode"<<endl; Destroy(); } MA_RESULT CNode::Execute() { MA_RESULT eResult = MA_RESULT_UNKNOWN; cout<<"CNode::Execute()"<<endl; cout<<m_iActId<<endl; if(m_eConditionID != -1) eResult = CFunctionInterface::GetInstance()->CheckCondition(m_eConditionID); else if(m_eMethodID != -1) eResult = CFunctionInterface::GetInstance()->ExecuteFunction(m_eMethodID); return eResult; } void CNode::AddChild(CNode* Child) { m_arrChildNode.push_back(Child); } void CNode::SetParent(CNode* Parent) { m_pParentNode = Parent; } CNode* CNode::GetActivatedNode() { CNode* pNode = NULL; if (m_nCurrentIndex < m_iChildArraySize) { pNode = m_arrChildNode[m_nCurrentIndex]; cout<<"Currindex node: "<<m_nCurrentIndex<<endl; m_nCurrentIndex++; } else cout<<"RETURN NULL NODE"<<endl; return pNode; } CNode* CNode::GetActivatedNode(MA_RESULT eResult) { CNode* pNode = NULL; for(int i = 0; i < m_iChildArraySize; i++) if(m_nCurrentIndex < m_iChildArraySize && eResult == m_arrChildNode[i]->GetResult()) { cout<<"RETURN NODE"<<endl; m_nCurrentIndex++; return m_arrChildNode[i]; } cout<<"RETURN NULL NODE"<<endl; return pNode; } void CNode::ReTravel() { m_nCurrentIndex = 0; } void CNode::Destroy() { // Destroy action if (m_pAction != NULL) { delete m_pAction; } cout<<"delete CNode"<<endl; // Destroy child nodes NodeArray::iterator it = m_arrChildNode.begin(); while (it != m_arrChildNode.end()) { delete *it; it++; } m_arrChildNode.clear(); }
[ "leesvr90@gmail.com" ]
leesvr90@gmail.com
086af70aef1493face3e3665f900ef28f0a1cace
d1aa3b1380d88a1f19620367b71982d014445d7c
/004-用户裁切平面/UserClippingIOS-Proj/UserClippingIOS/UserClipping/source/TorusModel.cpp
07d991bf278172da0fc0d7bbff7b517ad8e1369c
[ "MIT" ]
permissive
jjzhang166/LearnThreeJSRenderingExamples
201d7bb8aa5a290524daa45600a785f4632e62d2
97ecf0235ff893c576236e39bff873ed082e388e
refs/heads/master
2022-04-27T18:19:07.280199
2020-04-24T05:55:31
2020-04-24T05:55:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,809
cpp
//-------------------------------------------------------------------------------- // TorusModel.cpp // Render a plane //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Include files //-------------------------------------------------------------------------------- #include "TorusModel.h" #include "matrix4.h" #include "Geometry.h" #include "TorusKnotGeometry.h" #include <OpenGLES/ES3/gl.h> #include <OpenGLES/ES3/glext.h> extern float UserClipDistance; float TorusModel::timer=0.f; TorusModel::TorusModel() { vao_ = 0; vbo_ = 0; ibo_ = 0; // Load shader lavaShaderState_.reset(new LavaShaderState()); TorusKnotGeometry tkg = TorusKnotGeometry(); TorusKnotGeometry::TKGVertexData tkgVdata = makeTKGVertexData(tkg); // Create VBO num_vertices_ = (int)tkgVdata.vData.size(); num_indices_ = (int)tkgVdata.iData.size(); vector<VertexPNX> vertices = tkgVdata.vData; vector<unsigned short> indices = tkgVdata.iData; geometry_.reset(new Geometry(&vertices[0],&indices[0],num_vertices_,num_indices_)); if(!vao_) glGenVertexArrays(1, &vao_); glBindVertexArray(vao_); // Bind the VBO glBindBuffer(GL_ARRAY_BUFFER, geometry_->vbo); int32_t iStride = sizeof(VertexPNX); // Pass the vertex data glVertexAttribPointer(TEXTURE_ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, iStride, BUFFER_OFFSET(0)); glEnableVertexAttribArray(TEXTURE_ATTRIB_VERTEX); glVertexAttribPointer(TEXTURE_ATTRIB_NORMAL, 3, GL_FLOAT, GL_FALSE, iStride, BUFFER_OFFSET(3 * sizeof(GLfloat))); glEnableVertexAttribArray(TEXTURE_ATTRIB_NORMAL); glVertexAttribPointer(TEXTURE_ATTRIB_UV, 2, GL_FLOAT, GL_FALSE, iStride, BUFFER_OFFSET(2* 3 * sizeof(GLfloat))); glEnableVertexAttribArray(TEXTURE_ATTRIB_UV); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, geometry_->ibo); glBindVertexArray(0); std::vector<std::string> textures = {std::string(GetBundleFileName("cloud.png"))}; texObj_ = Texture::Create(GL_TEXTURE_2D, textures); assert(texObj_); // texObj_->Activate(GL_TEXTURE2); // glUniform1i(lavaShaderState_->tex1_, 2); std::vector<std::string> textures1 = {std::string(GetBundleFileName("lavatile.jpg"))}; texObj1_ = Texture::Create(GL_TEXTURE_2D, textures1); assert(texObj1_); } TorusModel::~TorusModel(){ Unload(); } void TorusModel::Init() { mat_model_ = Matrix4::makeTranslation(Cvec3(0.f, 0.f, 0.f)); //mat_model_ = mat_model_ * Matrix4::makeXRotation(45); mat_view_ = Matrix4::makeTranslation(Cvec3(0,0,4.0f)); mat_view_ = inv(mat_view_); } void TorusModel::Unload() { if (vbo_) { glDeleteBuffers(1, &vbo_); vbo_ = 0; } if (ibo_) { glDeleteBuffers(1, &ibo_); ibo_ = 0; } } void TorusModel::Update(double time) { mat_projection_ = perspectiveCamera_->projMat; } void TorusModel::setPerspectiveCamera(std::shared_ptr<PerspectiveCamera> camera){ this->perspectiveCamera_ = camera; Update(0); } void TorusModel::Render(){ glDisable(GL_CULL_FACE); glUseProgram(lavaShaderState_->program); glUniform1f(lavaShaderState_->utime_, 1.0f); glUniform3f(lavaShaderState_->fogColor_,0,0,0); glUniform1f(lavaShaderState_->fogDensity_, 0.45); glUniform2f(lavaShaderState_->uvScale_, 6.0, 2.0); glUniform4f(lavaShaderState_->userClipPlane_, 0, -1, 0, UserClipDistance); texObj_->Activate(GL_TEXTURE0); glUniform1i(lavaShaderState_->tex1_, 0); texObj1_->Activate(GL_TEXTURE1); glUniform1i(lavaShaderState_->tex2_, 1); timer+=0.025f; if(timer>100.f) timer=1.0f; glUniform1f(lavaShaderState_->utime_, timer); mat_model_ = mat_model_ * Matrix4::makeYRotation(0.0625); mat_model_ = mat_model_ * Matrix4::makeXRotation(0.25); // Feed Projection and Model View matrices to the shaders Matrix4 mat_vp = mat_projection_ * mat_view_ * mat_model_; Matrix4 mat_mv = mat_view_ * mat_model_; GLfloat glmatrix[16]; mat_mv.writeToColumnMajorMatrix(glmatrix); glUniformMatrix4fv(lavaShaderState_->matrix_mv_, 1, GL_FALSE, glmatrix); GLfloat glmatrix2[16]; mat_projection_.writeToColumnMajorMatrix(glmatrix2); glUniformMatrix4fv(lavaShaderState_->matrix_p_, 1, GL_FALSE, glmatrix2); glBindVertexArray(vao_); glDrawElements(GL_TRIANGLES, num_indices_,GL_UNSIGNED_SHORT,NULL); glBindVertexArray(0); }
[ "nintymiles@icloud.com" ]
nintymiles@icloud.com
810883c134c479393c37b3e2aca4156d91b4fe62
cccfb7be281ca89f8682c144eac0d5d5559b2deb
/services/network/public/cpp/corb/orb_impl.cc
9c888b6f9e36077814ab6c6ef172497948222a1b
[ "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
9,089
cc
// Copyright 2021 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 "services/network/public/cpp/corb/orb_impl.h" #include "base/metrics/histogram_functions.h" #include "base/strings/string_piece.h" #include "net/url_request/url_request.h" #include "services/network/public/cpp/corb/corb_impl.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/mojom/url_response_head.mojom.h" namespace network { namespace corb { namespace { // This corresponds to "opaque-blocklisted-never-sniffed MIME type" in ORB spec. bool IsOpaqueBlocklistedNeverSniffedMimeType(base::StringPiece mime_type) { return CrossOriginReadBlocking::GetCanonicalMimeType(mime_type) == CrossOriginReadBlocking::MimeType::kNeverSniffed; } // ORB spec says that "An opaque-safelisted MIME type" is a JavaScript MIME type // or a MIME type whose essence is "text/css" or "image/svg+xml". bool IsOpaqueSafelistedMimeType(base::StringPiece mime_type) { // Based on the spec: Is it a MIME type whose essence is "text/css" or // "image/svg+xml"? if (base::LowerCaseEqualsASCII(mime_type, "image/svg+xml") || base::LowerCaseEqualsASCII(mime_type, "text/css")) { return true; } // Based on the spec: Is it a JavaScript MIME type? if (CrossOriginReadBlocking::IsJavascriptMimeType(mime_type)) return true; // https://github.com/annevk/orb/issues/20 tracks explicitly covering DASH // mime type in the ORB algorithm. if (base::LowerCaseEqualsASCII(mime_type, "application/dash+xml")) return true; return false; } // Return true for multimedia MIME types that // 1) are not explicitly covered by ORB (e.g. that do not begin with "audio/", // "image/", "video/" and that are not covered by // IsOpaqueSafelistedMimeType). // 2) would be recognized by sniffing from steps 6 or 7 of ORB: // step 6. If the image type pattern matching algorithm ... // step 7. If the audio or video type pattern matching algorithm ... bool IsSniffableMultimediaType(base::StringPiece mime_type) { if (base::LowerCaseEqualsASCII(mime_type, "application/ogg")) return true; return false; } // This corresponds to https://fetch.spec.whatwg.org/#ok-status bool IsOkayHttpStatus(const mojom::URLResponseHead& response) { if (!response.headers) return false; int code = response.headers->response_code(); return (200 <= code) && (code <= 299); } bool IsHttpStatus(const mojom::URLResponseHead& response, int expected_status_code) { if (!response.headers) return false; int code = response.headers->response_code(); return code == expected_status_code; } bool IsOpaqueResponse(const absl::optional<url::Origin>& request_initiator, mojom::RequestMode request_mode, const mojom::URLResponseHead& response) { // ORB only applies to "no-cors" requests. if (request_mode != mojom::RequestMode::kNoCors) return false; // Browser-initiated requests are never opaque. if (!request_initiator.has_value()) return false; // Requests from foo.example.com will consult foo.example.com's service worker // first (if one has been registered). The service worker can handle requests // initiated by foo.example.com even if they are cross-origin (e.g. requests // for bar.example.com). This is okay, because there is no security boundary // between foo.example.com and the service worker of foo.example.com + because // the response data is "conjured" within the service worker of // foo.example.com (rather than being fetched from bar.example.com). // Therefore such responses should not be blocked by CORB, unless the // initiator opted out of CORS / opted into receiving an opaque response. See // also https://crbug.com/803672. if (response.was_fetched_via_service_worker) { switch (response.response_type) { case network::mojom::FetchResponseType::kBasic: case network::mojom::FetchResponseType::kCors: case network::mojom::FetchResponseType::kDefault: case network::mojom::FetchResponseType::kError: // Non-opaque responses shouldn't be blocked. return false; case network::mojom::FetchResponseType::kOpaque: case network::mojom::FetchResponseType::kOpaqueRedirect: // Opaque responses are eligible for blocking. Continue on... break; } } return true; } ResponseHeadersHeuristicForUma CalculateResponseHeadersHeuristicForUma( const GURL& request_url, const absl::optional<url::Origin>& request_initiator, mojom::RequestMode request_mode, const mojom::URLResponseHead& response) { // Exclude responses that ORB doesn't apply to. if (!IsOpaqueResponse(request_initiator, request_mode, response)) return ResponseHeadersHeuristicForUma::kNonOpaqueResponse; DCHECK(request_initiator.has_value()); // Same-origin requests are allowed (the spec doesn't explicitly deal with // this). url::Origin target_origin = url::Origin::Create(request_url); if (request_initiator->IsSameOriginWith(target_origin)) return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders; // Presence of an "X-Content-Type-Options: nosniff" header means that ORB will // reach a final decision in step 8, before reaching Javascript parsing in // step 12: // step 8. If nosniff is true, then return false. // ... // step 12. If response's body parses as JavaScript ... if (CrossOriginReadBlocking::CorbResponseAnalyzer::HasNoSniff(response)) return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders; // If a mime type is missing then ORB will reach a final decision in step 10, // before reaching Javascript parsing in step 12: // step 10. If mimeType is failure, then return true. // ... // step 12. If response's body parses as JavaScript ... std::string mime_type; if (!response.headers || !response.headers->GetMimeType(&mime_type)) return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders; // Specific MIME types might make ORB reach a final decision before reaching // Javascript parsing step: // step 3.i. If mimeType is an opaque-safelisted MIME type, then return // true. // step 3.ii. If mimeType is an opaque-blocklisted-never-sniffed MIME // type, then return false. // ... // step 11. If mimeType's essence starts with "audio/", "image/", or // "video/", then return false. // ... // step 12. If response's body parses as JavaScript ... if (IsOpaqueBlocklistedNeverSniffedMimeType(mime_type) || IsOpaqueSafelistedMimeType(mime_type) || IsSniffableMultimediaType(mime_type)) { return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders; } constexpr auto kCaseInsensitive = base::CompareCase::INSENSITIVE_ASCII; if (base::StartsWith(mime_type, "audio/", kCaseInsensitive) || base::StartsWith(mime_type, "image/", kCaseInsensitive) || base::StartsWith(mime_type, "video/", kCaseInsensitive)) { return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders; } // If the http response indicates an error, or a 206 response, then ORB will // reach a final decision before reaching Javascript parsing in step 12: // step 9. If response's status is not an ok status, then return false. // ... // step 12. If response's body parses as JavaScript ... if (!IsOkayHttpStatus(response) || IsHttpStatus(response, 206)) return ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders; // Otherwise we need to parse the response body as Javascript. return ResponseHeadersHeuristicForUma::kRequiresJavascriptParsing; } } // namespace void LogUmaForOpaqueResponseBlocking( const GURL& request_url, const absl::optional<url::Origin>& request_initiator, mojom::RequestMode request_mode, mojom::RequestDestination request_destination, const mojom::URLResponseHead& response) { ResponseHeadersHeuristicForUma response_headers_decision = CalculateResponseHeadersHeuristicForUma(request_url, request_initiator, request_mode, response); base::UmaHistogramEnumeration( "SiteIsolation.ORB.ResponseHeadersHeuristic.Decision", response_headers_decision); switch (response_headers_decision) { case ResponseHeadersHeuristicForUma::kNonOpaqueResponse: break; case ResponseHeadersHeuristicForUma::kProcessedBasedOnHeaders: base::UmaHistogramEnumeration( "SiteIsolation.ORB.ResponseHeadersHeuristic.ProcessedBasedOnHeaders", request_destination); break; case ResponseHeadersHeuristicForUma::kRequiresJavascriptParsing: base::UmaHistogramEnumeration( "SiteIsolation.ORB.ResponseHeadersHeuristic." "RequiresJavascriptParsing", request_destination); break; } } } // namespace corb } // namespace network
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
199ba82c8591c9bcf131ed508eeb1abd4e5b47aa
61d70c727de05e8b07e81a4cd46b22fc03b8861c
/interview_cake/reverse_linked_list.cc
f8cabb69906a06231d41f5fbb4e7815072d29a2f
[]
no_license
cmallalieu/Interview_prep
917942ed2fc0bf1a870e049deb8d263e00287be8
6be7787819104e7e984d4119ca60bda38055f4db
refs/heads/master
2020-08-24T21:25:23.753086
2019-10-30T18:26:07
2019-10-30T18:26:07
216,908,640
0
0
null
null
null
null
UTF-8
C++
false
false
833
cc
#include <iostream> #include <vector> // C++11 lest unit testing framework #include "lest.hpp" using namespace std; class LinkedListNode { public: int intValue_; LinkedListNode* next_; LinkedListNode(int value) : intValue_(value), next_(nullptr) { } }; LinkedListNode* reverse(LinkedListNode* headOfList) { // reverse the linked list in place if (!headOfList) { cout << "List is empty" << endl; } LinkedListNode* currentNode = headOfList; LinkedListNode* previousNode = nullptr; LinkedListNode* nextNode = nullptr; while(currentNode) { nextNode = currentNode->next_; currentNode->next_ = previousNode; previousNode = currentNode; currentNode = nextNode; } return previousNode; }
[ "christophermallalieu@Christophers-MacBook-Pro.local" ]
christophermallalieu@Christophers-MacBook-Pro.local
334a31ee8ba2910ed080cb1699c48e0f31cabb5f
7bd8b4933f2e78d4936d1a4455c84a86b86242fb
/Demo/DEMO.HPP
d7a939376517af06d784f58cdea33b58195d99fe
[]
no_license
dhawt/Immerse
bdbf4470fa6a79da850536efc91272abd01684db
0f562746f9db33c41a6e047fecb0f49acb513b48
refs/heads/master
2016-09-15T23:57:05.086389
2012-05-03T19:52:14
2012-05-03T19:52:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
626
hpp
#ifndef _DEMO_HPP #define _DEMO_HPP // Includes: #include <stdlib.h> #include <conio.h> #include <stdarg.h> #include <stdio.h> #include <windows.h> #include <windowsx.h> #include <time.h> // Libraries: //#include "H:\Lib\Immerse\Code\Core\IMR_Interface.hpp" #include "C:\Code\Engines\Lib\Immerse\Code\GeomMngr\IMR_GM_Interface.hpp" #include "C:\Code\Engines\Lib\WinLayer\WinLayer.hpp" #include "C:\Code\Engines\Lib\GfxLib\GfxLib.hpp" // Prototypes: void Cleanup(void); void InitWindowApp(void); LRESULT CALLBACK WndProc(HWND hWnd, unsigned int iMessage, unsigned int wParam, LONG lParam); #endif
[ "daniel@eduschedu.com" ]
daniel@eduschedu.com
cc11697e7ad01b051f1be7b5cd80e054313c6038
5ea0705061ed9620ff420e66d0faff4f4b3563a2
/src/pofPath.h
7d6c20301f453b7da2f262476f4c57e7a949dc07
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
Ant1r/ofxPof
69cc87686c0f6839e616f7cde601bacc0aaeaeb3
b80210527454484f64003b7a09c8e7f9f8a09ac3
refs/heads/master
2023-08-02T21:30:28.542262
2021-06-28T11:05:03
2021-06-28T11:05:03
32,018,528
68
8
null
null
null
null
UTF-8
C++
false
false
525
h
/* * Copyright (c) 2014 Antoine Rousseau <antoine@metalu.net> * BSD Simplified License, see the file "LICENSE.txt" in this distribution. * See https://github.com/Ant1r/ofxPof for documentation and updates. */ #pragma once #include "pofBase.h" class pofPath; class pofPath: public pofBase { public: pofPath(t_class *Class): pofBase(Class), doMesh(false) { } ofPath path; ofPoint scale; bool doMesh; virtual void draw(); virtual void message(int arc, t_atom *argv); static void setup(void); };
[ "_antoine_@metalu.net" ]
_antoine_@metalu.net
f1a331958ea522bf8559d378a5e52a14381e474e
e9698b61fdad8b64530f75981864768a98d6bf88
/tp6/sia_td6/include/sphere.h
837fb3b005e38f3f89489a1a40d8fc1561992196
[]
no_license
Johan-David/SIA
c6abdb638a63c7d7d6d9284877ec0ff488bec88c
660a2ba600c3e455f1bd7cfb5e27c3e933aa938b
refs/heads/master
2021-09-03T03:55:12.894559
2018-01-05T10:33:56
2018-01-05T10:33:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
770
h
#ifndef _SPHERE_H #define _SPHERE_H #include "shape.h" #include <vector> class Sphere : public Shape { public: Sphere(float radius=1.f, int nU=40, int nV=40); virtual ~Sphere(); void init(); void display(Shader *shader); float radius() const { return _radius; } private: GLuint _vao; GLuint _vbo[6]; std::vector<int> _indices; /** vertex indices */ std::vector<Eigen::Vector3f> _vertices; /** 3D positions */ std::vector<Eigen::Vector3f> _colors; /** colors */ std::vector<Eigen::Vector3f> _normals; /** 3D normals */ std::vector<Eigen::Vector3f> _tangents; /** 3D tangent to surface */ std::vector<Eigen::Vector2f> _texCoords; /** 2D texture coordinates */ float _radius; }; #endif
[ "axelwolski92@gmail.com" ]
axelwolski92@gmail.com
84da9d25f3e5edb38aa95c7bb8eaa9ce0e37cd8e
c5f67ad3724d62c712d58144b5abea10c06a2314
/Lab1/ece250.h
138df16e0fa84cdc7727f4cd43ac939f7f824d87
[]
no_license
hyc20908/ECE250
fdd74688998475a292978574836b57488d3514d9
8d6d5e91b244eea8c8a684c9d8bb48a6337cbc64
refs/heads/master
2021-01-13T12:07:44.763902
2018-09-10T15:05:40
2018-09-10T15:05:40
78,052,948
1
0
null
null
null
null
UTF-8
C++
false
false
13,884
h
#ifndef ECE250 #define ECE250 #include <cstdlib> #include <iostream> #include <iomanip> #include <string> #include <cmath> #include "Exception.h" /************************************************************************** * ************************************************************************ * * You don't have to use the Tester classes to use this to manage your * * memory. All you must do is include this file and then, if you ever * * want to test if you have memory which is currently unallocated, * * you may use ece250::allocation_table.summary(); * * * * You must simply indicate that you want to start recording by * * using ece250::alocation_table.summary(); * * * ************************************************************************ **************************************************************************/ /**************************************************************************** * ece250 * Author: Douglas Wilhelm Harder * Copyright (c) 2006-9 by Douglas Wilhelm Harder. All rights reserved. * * DO NOT EDIT THIS FILE * * This file is broken into two parts: * * 1. The first namespace ece250 is associated with tools used by the * second part. * 2. The second has globally overloaded new, delete, new[], and delete[]. * * This tracks everything that deals with memory allocation (new and new[]) * and memory deallocation (delete and delete[]). * * Each time 'new' or 'new[]' is called, an appropriate entry is * set in a hash table 'allocation_table'. The hash function of any address * is the last log[2](array_size) bits. * * Each time that 'delete' or 'delete[]' is called, it is checked whether: * 1. the memory was actually allocated, * 2. the appropriate form of delete versus delete[] is being called, and * 3. delete/delete[] has been called multiple times. * * The class also stores how much memory was allocated and how much was * deallocated. The summary() function prints a summary indicating the * difference. When this is called at the end of a test, the result must * be zero (0). * * If there is a problem with either allocation or deallocation, two events * occur: a warning is printed and an exception is thrown. * * Each throw is associated with a warning sent to the student through cout. ****************************************************************************/ namespace ece250 { int memory_alloc_store; const size_t PAD = 16; class overflow {}; class invalid_deletion {}; // Each time a student calls either new or new[], the // information about the memory allocation is stored in // an instance of this class class Allocation { public: void *address; size_t size; bool is_array; bool deleted; Allocation(): address( 0 ), size( 0 ), is_array( false ), deleted( false ) { // Empty constructor } Allocation( void *a, size_t s, bool i ): address( a ), size( s ), is_array( i ), deleted( false ) { // Empty constructor } }; int to_int( int *ptr ) { int result = *ptr; if ( result < 0 ) { result = result + (1 << (sizeof( int ) - 1)); } return result >> 3; } // All instances of an allocation are stored in this chained hash table class HashTable { private: int array_size; Allocation *allocated; int total_memory_alloc; int total_memory_deleted; bool record; public: // Initialize all of the addresses to 0 HashTable( int as ): array_size( as ), total_memory_alloc( 0 ), total_memory_deleted( 0 ), record( false ) { allocated = new Allocation[array_size]; } int reserve( int N ) { // N must be a power of 2 if ( (N & ((~N) + 1)) != N ) { throw illegal_argument(); } delete [] allocated; array_size = N; allocated = new Allocation[array_size]; return 0; } int memory_alloc() const { return total_memory_alloc - total_memory_deleted; } void memory_store() const { memory_alloc_store = total_memory_alloc - total_memory_deleted; } void memory_change( int n ) const { int memory_alloc_diff = total_memory_alloc - total_memory_deleted - memory_alloc_store; if ( memory_alloc_diff != n ) { std::cout << "WARNING: expecting a change in memory allocation of " << n << " bytes, but the change was " << memory_alloc_diff << std::endl; } } // Insert uses the last log[2]( array_size ) bits of the address as the hash function // It finds an unallocated entry in the array and stores the information // about the memory allocation in that entry, including: // The amount of memory allocated, // Whether new or new[] was used for the allocation, and // The address of the allocated memory. void insert( void *ptr, size_t size, bool is_array ) { if ( !record ) { return; } // the hash function is the last log[2]( array_size ) bits int hash = to_int( reinterpret_cast<int *>( &ptr ) ) & (array_size - 1); for ( int i = 0; i < array_size; ++i ) { // It may be possible that we are allocated the same memory // location twice (if there are numerous allocations and // deallocations of memory. Thus, the second check is necessary, // otherwise it may introduce session dependant errors. if ( allocated[hash].address == 0 || allocated[hash].address == ptr ) { // Store the address, the amount of memory allocated, // whether or not new[] was used, and set 'deleted' to false. allocated[hash] = Allocation( ptr, size, is_array ); // Add the memory allocated to the total memory allocated. total_memory_alloc += size; return; } hash = (hash + 1) & (array_size - 1); } std::cout << "WARNING: allocating more memory than is allowed for this project" << std::endl; throw overflow(); } // Remove checks: // If the given memory location was allocated in the first place, and // If the appropriate form of delete was used, i.e., delete versus delete[], and // If delete has already been called on this object size_t remove( void *ptr, bool is_array ) { if ( !record || ptr == 0 ) { return 0; } // the hash function is the last log[2]( array_size ) bits int hash = to_int( reinterpret_cast<int *>( &ptr ) ) & ( array_size - 1 ); // Continue searching until we've checked all bins // or we find an empty bin. for ( int i = 0; i < array_size && allocated[hash].address != 0; ++i ) { if ( allocated[hash].address == ptr ) { // First check if: // 1. If the wrong delete was called (e.g., delete[] when new was // used or delete when new[] was used). // 2. If the memory has already been deallocated previously. // // If the deletion is successful, then: // 1. Set the 'deleted' flag to 'true', and // 2. Add the memory deallocated ot the total memory deallocated. if ( allocated[hash].is_array != is_array ) { if ( allocated[hash].is_array ) { std::cout << "WARNING: use 'delete [] ptr;' to use memory allocated with 'ptr = new Class[array_size];'" << std::endl; } else { std::cout << "WARNING: use 'delete ptr;' to use memory allocated with 'ptr = new Class(...);'" << std::endl; } throw invalid_deletion(); } else if ( allocated[hash].deleted ) { std::cout << "WARNING: calling delete twice on the same memory location: " << ptr << std::endl; throw invalid_deletion(); } allocated[hash].deleted = true; total_memory_deleted += allocated[hash].size; // zero the memory before it is deallocated char *cptr = static_cast<char *>( ptr ); for ( size_t j = 0; j < allocated[hash].size; ++j ) { cptr[j] = 0; } return allocated[hash].size; } hash = (hash + 1) & (array_size - 1); } // If we've gotten this far, this means that the address was // never allocated, and therefore we are calling delete on // something which should be deleted. std::cout << "WARNING: deleting a pointer to which memory was never allocated: " << ptr << std::endl; throw invalid_deletion(); } // Print a difference between the memory allocated and the memory deallocated void summary() { std::cout << "Memory allocated minus memory deallocated: " << total_memory_alloc - total_memory_deleted << std::endl; } // Print the difference between total memory allocated and total memory deallocated. void details() { std::cout << "SUMMARY OF MEMORY ALLOCATION:" << std::endl; std::cout << " Memory allocated: " << total_memory_alloc << std::endl; std::cout << " Memory deallocated: " << total_memory_deleted << std::endl << std::endl; std::cout << "INDIVIDUAL REPORT OF MEMORY ALLOCATION:" << std::endl; std::cout << " Address Using Deleted Bytes " << std::endl; for ( int i = 0; i < array_size; ++i ) { if ( allocated[i].address != 0 ) { std::cout << " " << allocated[i].address << ( allocated[i].is_array ? " new[] " : " new " ) << ( allocated[i].deleted ? "Y " : "N " ) << std::setw( 6 ) << allocated[i].size << std::endl; } } } // Start recording memory allocations void start_recording() { record = true; } // Stop recording memory allocations void stop_recording() { record = false; } bool is_recording() { return record; } }; bool asymptotic_tester( double *array, int N, int k, bool ln ) { double *ratios = new double[N]; double *differences = new double[N- 1]; int M = 2; for ( int i = 0; i < N; ++i ) { ratios[i] = array[i] / (M*(ln ? std::log( static_cast<double>( M ) ) : 1.0)); M = M*(1 << k); } for ( int i = 0; i < N - 1; ++i ) { differences[i] = ratios[i + 1] - ratios[i]; // std::cout << differences[i] << std::endl; } for ( int i = 1; i < N - 1; ++i ) { if ( !( differences[i] < 0 ) ) { if ( differences[i] > differences[i - 1] ) { return false; } } } delete [] ratios; delete [] differences; return true; } HashTable allocation_table( 8192 ); std::string history[101]; int count = 0; void initialize_array_bounds( char *ptr, size_t size ) { for ( int i = 0; i < PAD; ++i ) { ptr[i] = 63 + i; ptr[size - i - 1] = 89 + i; } } void check_array_bounds( char *ptr, size_t size ) { for ( int i = 0; i < PAD; ++i ) { if ( ptr[i] != 63 + i ) { std::cout << "Memory before the array located at adderss " << static_cast<void *>( ptr + PAD ) << " was overwritten" << std::endl; throw out_of_bounds(); } if ( ptr[size - i - 1] != 89 + i ) { std::cout << "Memory after the array located at adderss " << static_cast<void *>( ptr + PAD ) << " was overwritten" << std::endl; throw out_of_bounds(); } } } } /**************************************************************************** * new * Author: Douglas Wilhelm Harder * Overloads the global operator new * * Use malloc to perform the allocation. * Insert the pointer returned by malloc into the hash table. * * The argument 'false' indicates that this is a call * to new (versus a call to new[]). * * Return the pointer to the user. ****************************************************************************/ void *operator new( size_t size ) { void *ptr = malloc( size ); ece250::allocation_table.insert( ptr, size, false ); return static_cast<void *>( ptr ); } /**************************************************************************** * delete * Author: Douglas Wilhelm Harder * Overloads the global operator delete * * Remove the pointer from the hash table (the entry is not truly removed, * simply marked as removed). * * The argument 'false' indicates that this is a call * to delete (versus a call to delete[]). * * Use free to perform the deallocation. ****************************************************************************/ void operator delete( void *ptr ) { ece250::allocation_table.remove( ptr, false ); free( ptr ); } /**************************************************************************** * new[] * Author: Douglas Wilhelm Harder * Overloads the global operator new[] * * Use malloc to perform the allocation. * Insert the pointer returned by malloc into the hash table. * * The argument 'true' indicates that this is a call * to new[] (versus a call to new). * * Return the pointer to the user. ****************************************************************************/ void *operator new[]( size_t size ) { char *ptr = static_cast<char *>( malloc( size + 2*ece250::PAD ) ); ece250::allocation_table.insert( static_cast<void *>( ptr + ece250::PAD ), size, true ); ece250::initialize_array_bounds( ptr, size + 2*ece250::PAD ); return static_cast<void *>( ptr + ece250::PAD ); } /**************************************************************************** * delete[] * Author: Douglas Wilhelm Harder * Overloads the global operator delete[] * * Remove the pointer from the hash table (the entry is not truly removed, * simply marked as removed). * * The argument 'true' indicates that this is a call * to delete[] (versus a call to delete). * * Use free to perform the deallocation. ****************************************************************************/ void operator delete[]( void *ptr ) { size_t size = ece250::allocation_table.remove( ptr, true ); if ( ece250::allocation_table.is_recording() ) { ece250::check_array_bounds( static_cast<char *>( ptr ) - ece250::PAD, size + 2*ece250::PAD ); } free( static_cast<char *>( ptr ) - ece250::PAD ); } #endif
[ "kevin.han@coengadvisors.com" ]
kevin.han@coengadvisors.com
e4585f3eb373ba923b3d7fde51804a093ed6d755
b6fb8cc7e66ab98a793007317717b98d72e18e11
/io/ByteArrayInputStream.h
d3801576cf23bfcee4bc59fc462ae5864821a877
[ "MIT" ]
permissive
gizmomogwai/cpplib
70aee27dd04e464868e8ff72822150731cfb63cd
a09bf4d3f2a312774d3d85a5c65468099a1797b0
refs/heads/master
2021-10-31T10:17:51.939965
2021-10-08T21:57:19
2021-10-08T21:59:12
66,270,218
0
1
null
null
null
null
UTF-8
C++
false
false
2,049
h
#pragma once #include <io/InputStream.h> /** Klasse um auf einem Seicherbereich mit einem InputStream abzugehen. * * Es wird nur eine Referenz auf den Speicher gespeichert, * nicht der Speicher des Buffers kopiert. Der Speicher wird auch nicht vom * Stream verwaltet. Wenn man den Speicher nicht mehr braucht muss dieser * also von der Applikation geloescht werden. Wird der Speicher geloescht, * und weiterhin auf dem Stream abgegangen droht gefahr (der stream kann * den speicher nicht wirklich freigeben, da er nicht weiss, was es fuer * ein speicher ist) * * <p> * Curriculum Vitae: * <ul> * <li> 2000-11-19, cK, Created. * </ul> * * @todo Bessere Rangechecks. * * @version $Revision: 1.3 $, $Date: 2001/09/13 13:11:10 $ * * @author cK, $Author: koestlin $ */ class ByteArrayInputStream : public InputStream { public: /** Erzeugt einen neuen ByteArrayInputStream auf dem angegebenen * Speicherbereich. * * @param _buffer Source-speicher. * @param _offset Offset ab dem die Daten als InputStreasmangeboten * werden sollen. * @param _available Anzahl der Bte, die im Strom angeboten werden * sollen. */ ByteArrayInputStream(DataBuffer* _buffer, int _offset, int _available); /** Raeumt auf. */ virtual ~ByteArrayInputStream(); /** Liesst ein byte aus dem strom. * * @return int byte oder -1. */ virtual int read() throw (IOException); /** Liesst eine Menge von byte aus dem strom. * * @param target Datenpuffer in den die Werte geschrieben werden sollen. * @param offset Offset ab dem in die Daten geschrieben werden soll. * @param length Maximale Anzahl zu schreibender Daten. * * @return int Anzahl geschriebener byte. */ virtual int read(DataBuffer& target, int offset, int length) throw (IOException); private: /** Adresse des source-speichers. */ unsigned char* buffer; /** Anzahl von verfuegbaren bytes. */ int available; };
[ "christian.koestlin@esrlabs.com" ]
christian.koestlin@esrlabs.com
deca9e61ac21205d28f536660ca7f87fb05e00a7
8f6fc9656e62881533b8d85e803452116cc0305f
/Source/Quint/Assemblies/Weapons/Mallet.h
324ed2fd609631a1ae5384292819c6023e111dd2
[]
no_license
minogb/Quintessence
47056597790565f454412b8c051c4b08422b4a21
d83ea5130a199baa21407c90225023556fa31173
refs/heads/master
2020-03-28T10:17:10.403482
2019-11-06T05:08:50
2019-11-06T05:08:50
148,097,322
3
3
null
2018-10-14T20:09:09
2018-09-10T04:04:51
C++
UTF-8
C++
false
false
1,200
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Assemblies/AssembledEquipment.h" #include "Interfaces/WeaponInterface.h" #include "Mallet.generated.h" /** * */ UCLASS() class QUINT_API UMallet : public UAssembledEquipment, public IWeaponInterface { GENERATED_BODY() UPROPERTY() UItem* HammerHead; UPROPERTY() UItem* Binding; UPROPERTY() UItem* ShortHandle; public: UMallet(); virtual FString GetSaveJSON() override; virtual UItem** GetComponent(EAssemblyComponentType Type); virtual void InitWithJson(TSharedPtr<FJsonObject> JsonData) override; virtual int GetSkillLevel_Implementation(ESkillType Skill) { return 0; } virtual bool SetWeaponMode_Implementation(int Mode = 0); virtual float GetWeaponRange_Implementation(); virtual float GetWeaponAttackDuration_Implementation(); virtual float GetWeaponAttackCooldown_Implementation(); virtual bool GetDamageStruct_Implementation(UPARAM(ref)FDamageStruct& Damage); virtual bool CanUseWeapon_Implementation(AAvatar* Avatar); virtual bool UseWeapon_Implementation(AAvatar* DamageCauser, UPARAM(ref)FDamageStruct& Damage, AActor* DamageTarget); };
[ "minoguebrad@rocketamil.com" ]
minoguebrad@rocketamil.com
d114eb6ec4564b0834e8d83668564c9d42505676
bffb5982a832677386a198732bb486b874bda302
/ATCCSOrm/src/at60gimbalstatus-odb.hxx
7a1d256f5c61d7ca27d9272b6cedf7672d22446f
[]
no_license
iamgeniuswei/ATCCS
4e28b6f0063c1f4089b447fa3d00299350c1e416
5261b26fbf99cebd0909f06a7bb1bcf9e47cb5e2
refs/heads/master
2021-01-24T07:42:10.596733
2017-06-05T01:34:40
2017-06-05T01:34:40
93,351,146
0
0
null
null
null
null
UTF-8
C++
false
false
5,955
hxx
// This file was generated by ODB, object-relational mapping (ORM) // compiler for C++. // #ifndef AT60GIMBALSTATUS_ODB_HXX #define AT60GIMBALSTATUS_ODB_HXX #include <odb/version.hxx> #if (ODB_VERSION != 20400UL) #error ODB runtime version mismatch #endif #include <odb/pre.hxx> #include "at60gimbalstatus.h" #include "atccsgimbalstatus-odb.hxx" #include "atccspublicstatus-odb.hxx" #include <memory> #include <cstddef> #include <utility> #include <odb/core.hxx> #include <odb/traits.hxx> #include <odb/callback.hxx> #include <odb/wrapper-traits.hxx> #include <odb/pointer-traits.hxx> #include <odb/container-traits.hxx> #include <odb/session.hxx> #include <odb/cache-traits.hxx> #include <odb/result.hxx> #include <odb/simple-object-result.hxx> #include <odb/details/unused.hxx> #include <odb/details/shared-ptr.hxx> namespace odb { // at60gimbalstatus // template <> struct class_traits< ::at60gimbalstatus > { static const class_kind kind = class_object; }; template <> class access::object_traits< ::at60gimbalstatus > { public: typedef ::at60gimbalstatus object_type; typedef ::at60gimbalstatus* pointer_type; typedef odb::pointer_traits<pointer_type> pointer_traits; static const bool polymorphic = false; typedef object_traits< ::atccspublicstatus >::id_type id_type; static const bool auto_id = object_traits< ::atccspublicstatus >::auto_id; static const bool abstract = false; static id_type id (const object_type&); typedef odb::pointer_cache_traits< pointer_type, odb::session > pointer_cache_traits; typedef odb::reference_cache_traits< object_type, odb::session > reference_cache_traits; static void callback (database&, object_type&, callback_event); static void callback (database&, const object_type&, callback_event); }; } #include <odb/details/buffer.hxx> #include <odb/pgsql/version.hxx> #include <odb/pgsql/forward.hxx> #include <odb/pgsql/binding.hxx> #include <odb/pgsql/pgsql-types.hxx> #include <odb/pgsql/query.hxx> namespace odb { // at60gimbalstatus // template <typename A> struct query_columns< ::at60gimbalstatus, id_pgsql, A >: query_columns< ::atccsgimbalstatus, id_pgsql, A > { // atccsgimbalstatus // typedef query_columns< ::atccsgimbalstatus, id_pgsql, A > atccsgimbalstatus; }; template <typename A> struct pointer_query_columns< ::at60gimbalstatus, id_pgsql, A >: query_columns< ::at60gimbalstatus, id_pgsql, A > { }; template <> class access::object_traits_impl< ::at60gimbalstatus, id_pgsql >: public access::object_traits< ::at60gimbalstatus > { public: typedef object_traits_impl< ::atccspublicstatus, id_pgsql >::id_image_type id_image_type; struct image_type: object_traits_impl< ::atccsgimbalstatus, id_pgsql >::image_type { std::size_t version; }; struct extra_statement_cache_type; using object_traits<object_type>::id; static id_type id (const id_image_type&); static id_type id (const image_type&); static bool grow (image_type&, bool*); static void bind (pgsql::bind*, image_type&, pgsql::statement_kind); static void bind (pgsql::bind*, id_image_type&); static bool init (image_type&, const object_type&, pgsql::statement_kind); static void init (object_type&, const image_type&, database*); static void init (id_image_type&, const id_type&); typedef pgsql::object_statements<object_type> statements_type; typedef pgsql::query_base query_base_type; static const std::size_t column_count = 79UL; static const std::size_t id_column_count = 1UL; static const std::size_t inverse_column_count = 0UL; static const std::size_t readonly_column_count = 0UL; static const std::size_t managed_optimistic_column_count = 0UL; static const std::size_t separate_load_column_count = 0UL; static const std::size_t separate_update_column_count = 0UL; static const bool versioned = false; static const char persist_statement[]; static const char find_statement[]; static const char update_statement[]; static const char erase_statement[]; static const char query_statement[]; static const char erase_query_statement[]; static const char table_name[]; static void persist (database&, object_type&); static pointer_type find (database&, const id_type&); static bool find (database&, const id_type&, object_type&); static bool reload (database&, object_type&); static void update (database&, const object_type&); static void erase (database&, const id_type&); static void erase (database&, const object_type&); static result<object_type> query (database&, const query_base_type&); static unsigned long long erase_query (database&, const query_base_type&); static const char persist_statement_name[]; static const char find_statement_name[]; static const char update_statement_name[]; static const char erase_statement_name[]; static const char query_statement_name[]; static const char erase_query_statement_name[]; static const unsigned int persist_statement_types[]; static const unsigned int find_statement_types[]; static const unsigned int update_statement_types[]; public: static bool find_ (statements_type&, const id_type*); static void load_ (statements_type&, object_type&, bool reload); }; template <> class access::object_traits_impl< ::at60gimbalstatus, id_common >: public access::object_traits_impl< ::at60gimbalstatus, id_pgsql > { }; // at60gimbalstatus // } #include "at60gimbalstatus-odb.ixx" #include <odb/post.hxx> #endif // AT60GIMBALSTATUS_ODB_HXX
[ "iamgeniuswei@sina.com" ]
iamgeniuswei@sina.com
ebb22c97b0b2329ae1524e3c64050b28265675b0
3a4bafe20521cf34d723f3524f79c72a586288ec
/src/qt/networkstyle.h
c05ccb3af074653a0d8972f1b84ae592242d6f71
[ "MIT" ]
permissive
kiragame-team/strengthcore
6152914b049638ce566b56184baf78ca9efd07e0
63c130758b115f71f69fe8d93c7aa776cb1ebe13
refs/heads/master
2020-04-24T15:43:53.592225
2019-03-13T07:57:45
2019-03-13T07:57:45
172,080,017
0
0
MIT
2019-03-08T07:47:40
2019-02-22T14:28:31
C++
UTF-8
C++
false
false
1,341
h
// Copyright (c) 2014 The Bitcoin Core developers // Copyright (c) 2014-2017 The STRENGTH Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_NETWORKSTYLE_H #define BITCOIN_QT_NETWORKSTYLE_H #include <QIcon> #include <QPixmap> #include <QString> /* Coin network-specific GUI style information */ class NetworkStyle { public: /** Get style associated with provided BIP70 network id, or 0 if not known */ static const NetworkStyle *instantiate(const QString &networkId); const QString &getAppName() const { return appName; } const QIcon &getAppIcon() const { return appIcon; } const QPixmap &getSplashImage() const { return splashImage; } const QIcon &getTrayAndWindowIcon() const { return trayAndWindowIcon; } const QString &getTitleAddText() const { return titleAddText; } private: NetworkStyle(const QString &appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *titleAddText); QString appName; QIcon appIcon; QPixmap splashImage; QIcon trayAndWindowIcon; QString titleAddText; void rotateColors(QImage& img, const int iconColorHueShift, const int iconColorSaturationReduction); }; #endif // BITCOIN_QT_NETWORKSTYLE_H
[ "kiragame.team@gmail.com" ]
kiragame.team@gmail.com
bddfc6273cc0307ef466fffb318ce1fe985ff6f2
33b567f6828bbb06c22a6fdf903448bbe3b78a4f
/opencascade/VrmlData_Texture.hxx
4ea0f61f9c6e963c4d4b8a5d9c5f23124fbc9d51
[ "Apache-2.0" ]
permissive
CadQuery/OCP
fbee9663df7ae2c948af66a650808079575112b5
b5cb181491c9900a40de86368006c73f169c0340
refs/heads/master
2023-07-10T18:35:44.225848
2023-06-12T18:09:07
2023-06-12T18:09:07
228,692,262
64
28
Apache-2.0
2023-09-11T12:40:09
2019-12-17T20:02:11
C++
UTF-8
C++
false
false
2,465
hxx
// Created on: 2006-05-25 // Created by: Alexander GRIGORIEV // Copyright (c) 2006-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef VrmlData_Texture_HeaderFile #define VrmlData_Texture_HeaderFile #include <VrmlData_Node.hxx> /** * Implementation of the Texture node */ class VrmlData_Texture : public VrmlData_Node { public: // ---------- PUBLIC METHODS ---------- /** * Empty constructor */ inline VrmlData_Texture () : myRepeatS (Standard_False), myRepeatT (Standard_False) {} /** * Constructor */ inline VrmlData_Texture (const VrmlData_Scene& theScene, const char * theName, const Standard_Boolean theRepeatS = Standard_False, const Standard_Boolean theRepeatT = Standard_False) : VrmlData_Node (theScene, theName), myRepeatS (theRepeatS), myRepeatT (theRepeatT) {} /** * Query the RepeatS value */ inline Standard_Boolean RepeatS () const { return myRepeatS; } /** * Query the RepeatT value */ inline Standard_Boolean RepeatT () const { return myRepeatT; } /** * Set the RepeatS flag */ inline void SetRepeatS (const Standard_Boolean theFlag) { myRepeatS = theFlag; } /** * Set the RepeatT flag */ inline void SetRepeatT (const Standard_Boolean theFlag) { myRepeatT = theFlag; } protected: // ---------- PROTECTED METHODS ---------- private: // ---------- PRIVATE FIELDS ---------- Standard_Boolean myRepeatS; Standard_Boolean myRepeatT; public: // Declaration of CASCADE RTTI DEFINE_STANDARD_RTTI_INLINE(VrmlData_Texture,VrmlData_Node) }; // Definition of HANDLE object using Standard_DefineHandle.hxx DEFINE_STANDARD_HANDLE (VrmlData_Texture, VrmlData_Node) #endif
[ "adam.jan.urbanczyk@gmail.com" ]
adam.jan.urbanczyk@gmail.com
29cf6b67bf9190a74dcda410d6e41667e3076912
525dcc2e1e43c381f965cc12059c28e0142d50d0
/src/AssetManager.hpp
cff728b3b929c31fdf2e96c6e637135c6195be87
[]
no_license
sagarPakhrin/sfml-starter-template
ee1925bda2f46448578799f6d1e78a1c311ecc9f
080fdfa4ac9353e4eb5a31433a12caf29853a974
refs/heads/master
2020-06-28T11:27:17.136739
2019-08-11T12:26:05
2019-08-11T12:26:05
200,221,916
1
1
null
null
null
null
UTF-8
C++
false
false
499
hpp
#pragma once #include <SFML/Graphics.hpp> #include <map> namespace Sagar { class AssetManager { public: AssetManager(){}; ~AssetManager(){}; void LoadTexture(std::string name,std::string fileName); sf::Texture &GetTexture(std::string name); void LoadFont(std::string name,std::string fileName); sf::Font &GetFont(std::string name); private: std::map<std::string, sf::Texture> _textures; std::map<std::string, sf::Font> _fonts; }; }
[ "sagarlama826@gmail.com" ]
sagarlama826@gmail.com
276d377bc639bd527c47c17429f3c83d771d7f41
93a939e249c8c2f5c3c3957e1c3057ce2eda2331
/lib/interface.cpp
27469623cdb2d99280800d2b8ea5cc048893040a
[]
no_license
mediabuff/cpp_modules_sample
64bdf32e70025cb82b83d58e13bb89078b04474f
7dadf4c9b1ed080648de4df97dab1b7965c00635
refs/heads/master
2021-06-19T12:06:10.915820
2017-07-09T15:40:57
2017-07-09T15:40:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
63
cpp
module pets; export module pets.pet; export module pets.dog;
[ "marius.elvert@googlemail.com" ]
marius.elvert@googlemail.com
0ccd60e9ca4761a4c5c094647ce55d8d8c969c8a
379b5265e055d4b0fc5c005974b09c2c12ede3b3
/getting-started/hello-triangle/main.cpp
a204582e29b26b2938fa204f13c7bbd007a52333
[]
no_license
jshuam/learn-opengl
fe69aa82ede22c86ea6061235022b7a63a4d8777
d92c699b7db52f068dc8eaedd55bb23515a429d4
refs/heads/master
2022-11-16T23:41:09.786452
2020-07-08T11:11:07
2020-07-08T11:11:07
257,940,214
0
0
null
null
null
null
UTF-8
C++
false
false
6,624
cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> const char* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" "}\0"; const char* fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "\n" "void main()\n" "{\n" " FragColor = vec4(0.416f, 0.353f, 0.804f, 1.0f);\n" "}"; const char* fragmentShaderSource2 = "#version 330 core\n" "out vec4 FragColor;\n" "\n" "void main()\n" "{\n" " FragColor = vec4(0.000f, 0.980f, 0.604f, 1.0f);\n" "}"; float vertices[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f }; float rectVertices[] = { 0.5f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f }; unsigned int indices[] = { 0, 1, 3, 1, 2, 3 }; unsigned int VAO[2]; bool drawTriangle = true; bool wireframeMode = false; void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS) { drawTriangle = true; } if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS) { drawTriangle = false; } if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { wireframeMode = !wireframeMode; if (wireframeMode) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } } unsigned int createShaderProgram(const char* vertexSource, const char* fragmentSource); int main(void) { if (!glfwInit()) { std::cerr << "Failed to initialize GLFW" << std::endl; return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif GLFWwindow* window = glfwCreateWindow(800, 600, "Hello Window", NULL, NULL); if (window == NULL) { std::cerr << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; return -1; } glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback); glClearColor(0.529f, 0.808f, 0.980f, 1.0f); unsigned int buffers[3]; glGenVertexArrays(2, VAO); glGenBuffers(3, buffers); glBindVertexArray(VAO[0]); glBindBuffer(GL_ARRAY_BUFFER, buffers[2]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glBindVertexArray(VAO[1]); glBindBuffer(GL_ARRAY_BUFFER, buffers[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(rectVertices), rectVertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); unsigned int shaderPrograms[2]; shaderPrograms[0] = createShaderProgram(vertexShaderSource, fragmentShaderSource); shaderPrograms[1] = createShaderProgram(vertexShaderSource, fragmentShaderSource2); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); if (drawTriangle) { glUseProgram(shaderPrograms[0]); glBindVertexArray(VAO[0]); glDrawArrays(GL_TRIANGLES, 0, 3); } else { glUseProgram(shaderPrograms[1]); glBindVertexArray(VAO[1]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); } glfwSwapBuffers(window); glfwPollEvents(); } for (auto shaderProgram : shaderPrograms) { glDeleteProgram(shaderProgram); } glDeleteVertexArrays(2, VAO); glDeleteBuffers(3, buffers); glfwTerminate(); return 0; } unsigned int createShaderProgram(const char* vertexSource, const char* fragmentSource) { unsigned int vertexShader; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexSource, NULL); glCompileShader(vertexShader); int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cerr << "Failed to compile vertex shader\n" << infoLog << std::endl; return -1; } unsigned int fragmentShader; fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentSource, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::cerr << "Failed to compile fragment shader\n" << infoLog << std::endl; return -1; } unsigned int shaderProgram; shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cerr << "Failed to link program\n" << infoLog << std::endl; return -1; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); return shaderProgram; }
[ "jshuam0@gmail.com" ]
jshuam0@gmail.com
0d6bd08d0828e60c67e5349be6a153b98dfc67f6
8000180e9d07edd70d069a2ec7c42a2b2ffeecd2
/entity/body.cpp
af08acba3e5dff811a9ad5bda0dbab21289d2dea
[]
no_license
oyvindskog/lunarLander
3beedc476046093333944603715d1e797b884d86
4b828685ba5b8b0f898fa73df1409a3b1e9ac4af
refs/heads/master
2021-06-01T21:13:25.994866
2020-04-09T07:57:50
2020-04-09T07:57:50
254,314,029
0
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
#include "body.h" body::body(entity *e, vector2d &&position, std::vector<part> &parts) : component(e), _position(position), _parts(parts) {} void body::add_part(part &&p) { _parts.emplace_back(p); } void body::render(SDL_Renderer *renderer) const { for (auto p : _parts) { p.v += _position; SDL_Rect rect = {static_cast<int>(p.v.get_x()), static_cast<int>(p.v.get_y()), 2, 2}; SDL_SetRenderDrawColor(renderer, p.red, p.green, p.blue, 255); SDL_RenderFillRect(renderer, &rect); } } void body::rotate(float angle) { for (auto &p : _parts) p.v.rotate(angle); }
[ "oyvindskogstrand@gmail.com" ]
oyvindskogstrand@gmail.com
7dd760614fb5018c7673f22bfa97ca57f3bde1ba
0de27940c1e817befa533106cf7df0357614cea9
/src/qt/clientmodel.h
40a9f915a16e286be7764e863fd1753dfe13a392
[ "MIT" ]
permissive
RocketFund/RocketFundCoin
deda5a0bd01b4feb32686bc209e4515d85699061
8acb4bdbc113c2aa5df46da6af576822bc48857e
refs/heads/master
2020-09-12T19:25:12.205148
2019-11-26T00:51:37
2019-11-26T00:51:37
222,525,768
4
1
null
null
null
null
UTF-8
C++
false
false
3,408
h
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The ROCKETFUNDCOIN developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_CLIENTMODEL_H #define BITCOIN_QT_CLIENTMODEL_H #include "uint256.h" #include <QObject> #include <QDateTime> class AddressTableModel; class BanTableModel; class OptionsModel; class PeerTableModel; class TransactionTableModel; class CWallet; QT_BEGIN_NAMESPACE class QDateTime; class QTimer; QT_END_NAMESPACE enum BlockSource { BLOCK_SOURCE_NONE, BLOCK_SOURCE_REINDEX, BLOCK_SOURCE_DISK, BLOCK_SOURCE_NETWORK }; enum NumConnections { CONNECTIONS_NONE = 0, CONNECTIONS_IN = (1U << 0), CONNECTIONS_OUT = (1U << 1), CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT), }; /** Model for ROCKETFUNDCOIN network client. */ class ClientModel : public QObject { Q_OBJECT public: explicit ClientModel(OptionsModel* optionsModel, QObject* parent = 0); ~ClientModel(); OptionsModel* getOptionsModel(); PeerTableModel* getPeerTableModel(); BanTableModel *getBanTableModel(); //! Return number of connections, default is in- and outbound (total) int getNumConnections(unsigned int flags = CONNECTIONS_ALL) const; QString getMasternodeCountString() const; int getNumBlocks() const; int getNumBlocksAtStartup(); quint64 getTotalBytesRecv() const; quint64 getTotalBytesSent() const; double getVerificationProgress() const; QDateTime getLastBlockDate() const; QString getLastBlockHash() const; //! Return true if core is doing initial block download bool inInitialBlockDownload() const; //! Return true if core is importing blocks enum BlockSource getBlockSource() const; //! Return warnings to be displayed in status bar QString getStatusBarWarnings() const; QString formatFullVersion() const; QString formatBuildDate() const; bool isReleaseVersion() const; QString clientName() const; QString formatClientStartupTime() const; QString dataDir() const; bool getTorInfo(std::string& ip_port) const; private: OptionsModel* optionsModel; PeerTableModel* peerTableModel; BanTableModel *banTableModel; int cachedNumBlocks; QString cachedMasternodeCountString; bool cachedReindexing; bool cachedImporting; int numBlocksAtStartup; QTimer* pollTimer; QTimer* pollMnTimer; void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); signals: void numConnectionsChanged(int count); void numBlocksChanged(int count); void strMasternodesChanged(const QString& strMasternodes); void alertsChanged(const QString& warnings); void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut); //! Fired when a message should be reported to the user void message(const QString& title, const QString& message, unsigned int style); // Show progress dialog e.g. for verifychain void showProgress(const QString& title, int nProgress); public slots: void updateTimer(); void updateMnTimer(); void updateNumConnections(int numConnections); void updateAlert(const QString& hash, int status); void updateBanlist(); }; #endif // BITCOIN_QT_CLIENTMODEL_H
[ "57466496+RocketFund@users.noreply.github.com" ]
57466496+RocketFund@users.noreply.github.com
dae3ff1e458ddc90932c84adb485325ee7fa4ec7
bc7af3a168a49bc0f603782f8322005c17ef066c
/HookDll/Global.h
a11eb27b16f3bad5a8a23a43f7e647ae93546a18
[]
no_license
chen3/HookWindowActivity
9598dd50c2f81ea4176c5488a8f2e87a0d670c60
cac9946968e3f0e8662bc7c26d9859c4a4eae3bb
refs/heads/master
2021-01-23T22:14:52.475773
2017-02-25T09:19:57
2017-02-25T09:19:57
83,120,793
0
0
null
null
null
null
UTF-8
C++
false
false
231
h
#pragma once #include "stdafx.h" class Global { public: static bool isInstall(); static void log(std::string s); static void install(); static void installIfNotInstall(); static bool uninstall(); private: Global() { } };
[ "chen3@qiditu.cn" ]
chen3@qiditu.cn
a4c23c1be6219dc16ae9bd8c73cd1aca0ac424be
30602b4dd984837beb7b9c23bf3f20e22e11b53d
/Day 3 - Medium (Level 2)/Mailbox/Mailbox.cpp
662838ea7fa7e20b76a49179012eaacabc51175c
[]
no_license
sidgujrathi/topcoder
fae7188965f71c880805af838664c082b89f0965
d157ef0b02876b528fa3c4a451afccc2442ee165
refs/heads/master
2021-01-10T03:17:11.702146
2015-10-01T05:57:59
2015-10-01T05:57:59
43,119,043
0
0
null
null
null
null
UTF-8
C++
false
false
3,828
cpp
// BEGIN CUT HERE // END CUT HERE #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <vector> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> using namespace std; vector<string> split( const string& s, const string& delim =" " ) { vector<string> res; string t; for ( int i = 0 ; i != s.size() ; i++ ) { if ( delim.find( s[i] ) != string::npos ) { if ( !t.empty() ) { res.push_back( t ); t = ""; } } else { t += s[i]; } } if ( !t.empty() ) { res.push_back(t); } return res; } vector<int> splitInt( const string& s, const string& delim =" " ) { vector<string> tok = split( s, delim ); vector<int> res; for ( int i = 0 ; i != tok.size(); i++ ) res.push_back( atoi( tok[i].c_str() ) ); return res; } // BEGIN CUT HERE #define ARRSIZE(x) (sizeof(x)/sizeof(x[0])) template<typename T> void print( T a ) { cerr << a; } static void print( long long a ) { cerr << a << "L"; } static void print( string a ) { cerr << '"' << a << '"'; } template<typename T> void print( vector<T> a ) { cerr << "{"; for ( int i = 0 ; i != a.size() ; i++ ) { if ( i != 0 ) cerr << ", "; print( a[i] ); } cerr << "}" << endl; } template<typename T> void eq( int n, T have, T need ) { if ( have == need ) { cerr << "Case " << n << " passed." << endl; } else { cerr << "Case " << n << " failed: expected "; print( need ); cerr << " received "; print( have ); cerr << "." << endl; } } template<typename T> void eq( int n, vector<T> have, vector<T> need ) { if( have.size() != need.size() ) { cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements."; print( have ); print( need ); return; } for( int i= 0; i < have.size(); i++ ) { if( have[i] != need[i] ) { cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << "."; print( have ); print( need ); return; } } cerr << "Case " << n << " passed." << endl; } static void eq( int n, string have, string need ) { if ( have == need ) { cerr << "Case " << n << " passed." << endl; } else { cerr << "Case " << n << " failed: expected "; print( need ); cerr << " received "; print( have ); cerr << "." << endl; } } // END CUT HERE class Mailbox { public: int impossible(string collection, vector <string> address) { int res; return res; } }; // BEGIN CUT HERE void main( int argc, char* argv[] ) { { string addressARRAY[] = {"123C","123A","123 ADA"}; vector <string> address( addressARRAY, addressARRAY+ARRSIZE(addressARRAY) ); Mailbox theObject; eq(0, theObject.impossible("AAAAAAABBCCCCCDDDEEE123456789", address),0); } { string addressARRAY[] = {"2 FIRST ST"," 31 QUINCE ST", "606 BAKER"}; vector <string> address( addressARRAY, addressARRAY+ARRSIZE(addressARRAY) ); Mailbox theObject; eq(1, theObject.impossible("ABCDEFGHIJKLMNOPRSTUVWXYZ1234567890", address),3); } { string addressARRAY[] = {"111 A ST", "A BAD ST", "B BAD ST"}; vector <string> address( addressARRAY, addressARRAY+ARRSIZE(addressARRAY) ); Mailbox theObject; eq(2, theObject.impossible("ABCDAAST", address),2); } } // END CUT HERE
[ "sidh.gujrathi@gmail.com" ]
sidh.gujrathi@gmail.com
b4650a4f5c3338793ab0aa0f41512b5a99893308
9bdcd5ce87a5bdb6dea11084db933a24d5b4891b
/RayTracing/RayTracingRunner/RayTracingRunner.cpp
6615c65048d6de51c853118f8d73dfab44dc89d4
[]
no_license
yichaozhao/Workplace
3bcc35b4162d2ca115e3d243b42d634f271fe632
0302f63a01ec72a9d7098ac1a34a4d82862ab8e5
refs/heads/master
2020-05-20T01:48:27.264860
2015-09-04T03:09:29
2015-09-04T03:09:29
40,741,903
0
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
#include "RayTracer.h" #include <iostream> #include "Dot.h" int main() { std::cout << "It Works!\n"; Geom::Dot a(0, 0, 0); Geom::Object& b = a; std::cout << a.toString() + "\n"; std::cout << b.toString() + "\n"; return 0; }
[ "zhaoyichao@gmail.com" ]
zhaoyichao@gmail.com
acb30d2e08d40ec98d1f540abdd1e4552dd75313
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_PrimalItemConsumable_UnlockHair_Facial_Goatee_parameters.hpp
859c127ae757b79e7c28250fa8e07577a9acf954
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
872
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemConsumable_UnlockHair_Facial_Goatee_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function PrimalItemConsumable_UnlockHair_Facial_Goatee.PrimalItemConsumable_UnlockHair_Facial_Goatee_C.ExecuteUbergraph_PrimalItemConsumable_UnlockHair_Facial_Goatee struct UPrimalItemConsumable_UnlockHair_Facial_Goatee_C_ExecuteUbergraph_PrimalItemConsumable_UnlockHair_Facial_Goatee_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
47492ec37e37effc05be499c0336f175ec8d26d7
8899a8c81e8c8657e5dfe8e94ad5e94eddf59d9e
/Source/WebMediaPlayer/Private/WebMediaPlayer.cpp
7f92d4ecb1f6f805f6544335eae482b711c8eaa5
[]
no_license
bb2002/UE4-WebMediaPlayer
40c7cedb46eaeeebaa8a095bc209c93525e37422
bab03d5e965bc2039934ef2417f0a9e10976e205
refs/heads/master
2022-06-15T21:08:05.836943
2020-05-06T13:04:03
2020-05-06T13:04:03
261,760,256
11
1
null
null
null
null
UTF-8
C++
false
false
626
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "WebMediaPlayer.h" #define LOCTEXT_NAMESPACE "FWebMediaPlayerModule" void FWebMediaPlayerModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module } void FWebMediaPlayerModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FWebMediaPlayerModule, WebMediaPlayer)
[ "5252bb@daum.net" ]
5252bb@daum.net
6e53a038f9bde82a6e2d5285b837276b485b87bd
bbb12cf605c71c67be438ec7548b44c9d08911be
/Day15/main.cpp
0f00a0a88289049189af3dfdf465d750f5851c93
[]
no_license
dloibl/AOC2020
69bd8538a298307186e026fed54068f1b885c221
f60f8b61311f106c95197fe8707dbdf44d9559cd
refs/heads/main
2023-02-07T16:12:06.149859
2020-12-22T11:59:25
2020-12-22T11:59:25
317,606,072
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
#include "../utils.cpp" #include <map> using namespace std; int main() { vector<string> startingNumbers = split(readData("./input.txt")[0], ','); map<int, pair<int, int>> spoken; int part1Word; int turn = 1; int nextWord; int lastWord; for (auto start : startingNumbers) { auto w = stoi(start); spoken[w] = pair(turn, 0); cout << "t:" << turn << " = " << w << endl; lastWord = w; turn++; } pair<int, int> last; pair<int, int> next; while (turn < 30000001) { if (turn == 2021) { part1Word = lastWord; } last = spoken[lastWord]; nextWord = !last.second ? 0 : last.second - last.first; next = spoken[nextWord]; if (!next.first) { spoken[nextWord] = pair(turn, 0); } else { if (next.second) spoken[nextWord].first = next.second; spoken[nextWord].second = turn; } lastWord = nextWord; turn++; } cout << "the answer to part 1 is: " << part1Word << endl; cout << "the answer to part 2 is: " << nextWord << endl; }
[ "daniel.loibl@gmail.com" ]
daniel.loibl@gmail.com
eb464655d7137797638f71f594534c9041797934
5556191506949b4ae226223988e74001e3c3955c
/9/Array.h
b3252375ee97a670baa375895ee49bb7b5f2da15
[]
no_license
josephvitt/cpp_design
7af74d011cb19c7818c49e9ad30b478dded793eb
8ee06707358128828a1fdc2ca5a6fe8acaca0b3b
refs/heads/master
2020-12-09T05:07:49.296660
2020-02-05T07:58:15
2020-02-05T07:58:15
233,201,142
0
0
null
null
null
null
UTF-8
C++
false
false
3,401
h
/* 动态数组类模板 */ #ifndef ARRAY_H #define ARRAY_H #include <cassert> template <class T> //数组类模板定义 class Array { private: T* list;//用于存放动态分配的数组内存首地址 int size;//数组大小,元素个数 public: Array(int sz = 50);//构造函数 Array(const Array<T> &a);//复制构造函数 ~Array();//析构函数 Array<T> & operator = (const Array<T> &rhs);//重载= T & operator[](int n); const T& operator [] (int i) const;//重载[]常函数 operator T*();//重载T*类型的转换 operator const T* () const; int getSize() const;//取数组的大小 void resize(int sz);//修改数组的大小 }; template <class T> Array<T>::Array(int sz){ //构造函数 assert(sz >0);//sz为数组的大小(元素个数),应当非负 size = sz;//将元素个数赋值给变量size list = new T [size];//动态分配size个T类型的元素空间 } template <class T> Array<T>::~Array(){ //析构函数 delete [] list; } //复制构造函数 template <class T> Array<T>::Array(const Array<T> &a){ size = a.size;//从对象x取得数组大小,并且赋值给当前对象的成员 list = new T[size];//动态分配n个T类型的元素空间 //从对象x复制数组元素到本对象 for (int i = 0; i < size; i++) { list[i] = a.list[i]; } } //重载=运算符,将对象rhs赋值给本对象。实现对象之间的整体赋值 template<class T> Array<T> &Array<T>::operator = (const Array<T> & rhs){ if(&rhs != this){ //如果本对象中数组大小与rhs不同,则删除数组原有内存,然后重新分配 if(size != rhs.size){ delete [] list;//删除数组原有的内存 size = rhs.size;//设置本对象的数组大小 list = new T[size];//重新分配size个元素的内容 } //从对象X中复制数组元素到本对象 for(int i=0;i<size;i++){ list[i] = rhs.list[i]; } return *this;//返回当前对象的引用 } } template <class T> T &Array<T>::operator[](int n){ assert(n >= 0 && n <size);//检查下标是否越界 return list[n];//返回下标为n的数组元素 } template <class T> const T &Array<T>::operator[](int n)const{ assert(n >= 0 && n <size);//检查下标是否越界 return list[n];//返回下标为n的数组元素 } //重载指针转换运算符,将Array类的对象名转换为T类型的指针 template <class T> Array<T>::operator T *(){ return list;//返回当前对象中私有数组的首地址 } //取当前数组的大小 template <class T> int Array<T>::getSize() const { return size; } //修改数组的大小为sz template <class T> void Array<T>::resize(int sz){ assert(sz >= 0);//检查是否非负 if(sz == size)//如果指定的大小与原有大小一样,什么也不做 return ; T* newList = new T[size];//申请新的数组内存 int n = (sz <size) ? sz:size;//将sz于siaze中国较小的一个赋值给n //将原有数组中前n个元素复制到新数组中 for (int i = 0; i < n; i++) { newList[i] = list[i]; } //删除原数组 delete[] list; list = newList;//使list指向新数组 size = sz;//更新size } #endif//ARRAY_H
[ "419514268@qq.com" ]
419514268@qq.com
1745a47a9dee9925d9112823c465cfefda9a6816
b372a212000ed977a2a4977eb3aba8467b49315b
/ARduino_workshop__case_/ARduino_workshop__case_.ino
df4b5c52231287829d8a5baa78c62edd66d1703a
[]
no_license
gugus13400/arduino
62852a51d06bd914e31d8590aac2e406a2439f74
baf65ad97ab87b7cc8fde5d943526c95bdd73a23
refs/heads/master
2021-04-06T12:18:11.838080
2018-03-14T14:59:05
2018-03-14T14:59:05
125,226,276
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
ino
int potPin = A0; int led_1 = 8; int led_2 = 9; int led_3 = 10; int led_4 = 11; int led_5 = 12; void setup() { pinMode(potPin, INPUT); Serial.begin(9600); pinMode(led_1, OUTPUT); pinMode(led_2, OUTPUT); pinMode(led_3, OUTPUT); pinMode(led_4, OUTPUT); pinMode(led_5, OUTPUT); } void loop() { int potentiometre = (analogRead(potPin) / 255)+1; Serial.println(potentiometre); switch (potentiometre) { case 1: Serial.println("rouge"); digitalWrite(led_1, HIGH); delay (60); digitalWrite(led_1,LOW); break; case 2: Serial.println("vert"); digitalWrite(led_2, HIGH); delay (60); digitalWrite(led_2,LOW); break; case 3: Serial.println("bleu"); digitalWrite(led_3, HIGH); delay (60); digitalWrite(led_3,LOW); break; case 4: Serial.println("rouge"); digitalWrite(led_4, HIGH); delay (60); digitalWrite(led_4,LOW); break; case 5: Serial.println("jaune"); digitalWrite(led_5, HIGH); delay (60); digitalWrite(led_5,LOW); break; } }
[ "augustepugnet1@gmail.com" ]
augustepugnet1@gmail.com
65b5286ba30fe7edff8ab7b36e6343853f35272d
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_old_hunk_3272.cpp
428a7441439144fcaf169904b1fad18da3895e4b
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,419
cpp
|| r->status != HTTP_OK || c->aborted) { return OK; } else { /* no way to know what type of error occurred */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r, "default_handler: ap_pass_brigade returned %i", status); return HTTP_INTERNAL_SERVER_ERROR; } } else { /* unusual method (not GET or POST) */ if (r->method_number == M_INVALID) { /* See if this looks like an undecrypted SSL handshake attempt. * It's safe to look a couple bytes into the_request if it exists, as it's * always allocated at least MIN_LINE_ALLOC (80) bytes. */ if (r->the_request && r->the_request[0] == 0x16 && (r->the_request[1] == 0x2 || r->the_request[1] == 0x3)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid method in request %s - possible attempt to establish SSL connection on non-SSL port", r->the_request); } else { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid method in request %s", r->the_request); } return HTTP_NOT_IMPLEMENTED; } if (r->method_number == M_OPTIONS) {
[ "993273596@qq.com" ]
993273596@qq.com
9dd7ff082ed9fd81d747a4f1c3809b1464c82932
9f40d2ca59e083d21093a44a269a59330e940c2c
/gameAndMirror.ino
a6233b6fe0cbe7dd3e9c0a1a2461e673c7604833
[]
no_license
danielreyes9756/PI-CalculatorAndOther
a676ba393b66d77378900bd156766475b01a2939
90baf29d56d702e78fe6683a0e09b9eec1a50329
refs/heads/master
2021-01-01T09:34:01.769960
2020-02-09T00:08:56
2020-02-09T00:08:56
239,220,220
0
0
null
null
null
null
UTF-8
C++
false
false
15,415
ino
//Variables int iCount=0,displayCount=0,s=0,s2=0,m=0,m2=0,timbre=0,pulse=0,p=0,iCount2=0,turno=0,modo=0; byte vector[]={0x3F, 0x6, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x7, 0x7F, 0x6F}; byte vectorIn[]={0x3F, 0x30, 0x6D, 0x79, 0x72, 0x5B, 0x5F, 0x31, 0x7F, 0x7B}; long ini; String cadena="",cadena2=""; char aux='\0'; boolean permite=false,startGame=false,win=false,sePulso=false; char tablero[3][3]= { {'z','z','z'}, {'z','z','z'}, {'z','z','z'}}; void setup() { cli(); // modo normal de funcionamiento TCCR1A = 0; TCCR1B = 0; // cuenta inicial a cero TCNT1 = 0; // mode CTC TCCR1B |= (1 << WGM12); // prescaler N = 1024 TCCR1B |= (1 << CS12) | (1 << CS10); // fintr = fclk/(N*(OCR1A+1)) --> OCR1A = [fclk/(N*fintr)] - 1 // para fintr = 100Hz --> OCR1A = [16*10^6/(1024*100)] -1 = 155,25 --> 155 OCR1A = 77; // para 200 Hz programar OCR1A = 77 // enable timer1 compare interrupt (OCR1A) TIMSK1 |= (1 << OCIE1A); // habilitar interrupciones sei(); //Serial3 Serial.begin(9600); Serial3.begin(9600); //Display On Serial3.write(0xFE); Serial3.write(0x41); //Clear Screen Serial3.write(0xFE); Serial3.write(0x51); //Cursor Home Serial3.write(0xFE); Serial3.write(0x46); //Underline Cursor On Serial3.write(0xFE); Serial3.write(0x47); //7Segmentos DDRA = B11111111; //Botones DDRC = B00000001; PORTC = B11111000; //Lineas de teclado DDRL = B00001111; PORTL = B11110000; ini = millis(); Serial3.print("Modo Calculadora"); delay(2000); clearAll(); } void loop() { if(modo==1){ modo_game(); }else if(modo==2){ modo_espejo(); }else if(modo==0){ modo_calculadora(); } } ISR(TIMER1_COMPA_vect) { if(modo==1){ isr_Game(); }else if(modo==2){ isr_Espejo(); }else if(modo==0){ isr_Calculadora(); } } void isr_Calculadora() { if (iCount == 200) { Clock(); iCount = 0; } if (displayCount == 4) { displayCount = 0; } if (displayCount == 0) { PORTA = vector[s]; PORTL = 0b11111110; checkKB(0); } if (displayCount == 1) { PORTA = vector[s2]; PORTL = 0b11111101; checkKB(1); } if (displayCount == 2) { PORTA = vector[m]; PORTL = 0b11111011; checkKB(2); } if (displayCount == 3) { PORTA = vector[m2]; PORTL = 0b11110111; } displayCount++; iCount++; if (pulse == 1) { if ((millis() - ini) >= 200) { ini = millis(); permite=true; tone(37,timbre,100); Serial3.write(aux); cadena += aux; } pulse = 0; } } void isr_Game() { if(iCount2 == 200 && startGame){ Clock(); iCount2=0; } if(iCount2%20==0) { if(iCount2==200){iCount2=0;} if(p==0){ p=1; } else if(p==1) { p=0b11; } else if(p==0b11){ p=0b111; } else if(p==0b111){ p=0b1111; } else if(p==0b1111){ p=0b11111; } else if(p==0b11111){ p=0b111111; } else if(p==0b111111){ p=0b111110; } else if(p==0b111110){ p=0b111100; } else if(p==0b111100){ p=0b111000; } else if(p==0b111000){ p=0b110000; } else if(p==0b110000){ p=0b100000; } else if(p==0b100000){ p=0; } } if (displayCount == 4) { displayCount = 0; } if (displayCount == 0) { if(startGame)PORTA = vector[s]; else PORTA = p; PORTL = 0b11111110; checkKB(0); } if (displayCount == 1) { if(startGame)PORTA = vector[s2]; else PORTA = p; PORTL = 0b11111101; checkKB(1); } if (displayCount == 2) { if(startGame)PORTA = vector[m]; else PORTA = p; PORTL = 0b11111011; checkKB(2); } if (displayCount == 3) { if(startGame)PORTA = vector[m2]; else PORTA = p; PORTL = 0b11110111; } displayCount++; iCount2++; if (pulse == 1) { if ((millis() - ini) >= 200) { ini = millis(); } pulse = 0; } } //----------------------------------------GAME---------------------------------------// void modo_game(){ if(permite){ if(digitalRead(34)==0){ clearAll(); startGame=true; permite=false; } } if(digitalRead(34)==0 && digitalRead(31)==0){ clearAll(); startGame=false; permite=true; turno=0; Serial3.print("Modo juego 3 en raya"); delay(1000); s=0;s2=0;m=0;m2=0; clearAll(); for(int i = 0; i<3;i++){ for(int j=0; j<3;j++){ tablero[i][j]='z'; } } } if(startGame){ pulsacionTurno(); aux='0'; int x = comprobarGanador(); if(x==1){Serial3.write(0xFE);Serial3.write(0x45);Serial3.write(0x54); Serial3.print("Gano player1"); startGame=false;} if(x==2){Serial3.write(0xFE);Serial3.write(0x45);Serial3.write(0x54);Serial3.print("Gano player2"); startGame=false;} if(x==9){Serial3.write(0xFE);Serial3.write(0x45);Serial3.write(0x54);Serial3.print("Empate"); startGame=false;} } } void pulsacionTurno() { switch(aux){ case '1': if(tablero[0][0]=='z' && turno==0){ tablero[0][0]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[0][0]=='z' && turno==1){ tablero[0][0]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '2': if(tablero[0][1]=='z' && turno==0){ tablero[0][1]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[0][1]=='z' && turno==1){ tablero[0][1]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '3': if(tablero[0][2]=='z' && turno==0){ tablero[0][2]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[0][2]=='z' && turno==1){ tablero[0][2]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '4': if(tablero[1][0]=='z' && turno==0){ tablero[1][0]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[1][0]=='z' && turno==1){ tablero[1][0]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '5': if(tablero[1][1]=='z' && turno==0){ tablero[1][1]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[1][1]=='z' && turno==1){ tablero[1][1]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '6': if(tablero[1][2]=='z' && turno==0){ tablero[1][2]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[1][2]=='z' && turno==1){ tablero[1][2]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '7': if(tablero[2][0]=='z' && turno==0){ tablero[2][0]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[2][0]=='z' && turno==1){ tablero[2][0]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '8': if(tablero[2][1]=='z' && turno==0){ tablero[2][1]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[2][1]=='z' && turno==1){ tablero[2][1]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '9': if(tablero[2][2]=='z' && turno==0){ tablero[2][2]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[2][2]=='z' && turno==1){ tablero[2][2]='X'; escribir(aux,turno); delay(200); turno=0;} break; } } void escribir(char aux,int turno) { int i=0; if(aux=='1'||aux=='2'||aux=='3'){ i=0; } if(aux=='4'||aux=='5'||aux=='6'){ i=40; } if(aux=='7'||aux=='8'||aux=='9'){ i=20; } if(aux=='1' || aux=='4' || aux=='7'){ i+=8; } if(aux=='2' || aux=='5' || aux=='8'){ i+=9; } if(aux=='3' || aux=='6' || aux=='9'){ i+=10; } Serial3.write(0xFE); Serial3.write(0x45); Serial3.write(i); if(turno==0){Serial3.print('O');} if(turno==1){Serial3.print('X');} } int comprobarGanador() { //VICTORIA TODAS LAS FILAS if(tablero[0][0]==tablero[0][1] && tablero[0][1]==tablero[0][2]){ if(tablero[0][0]=='O'){ return 1;} if(tablero[0][0]=='X'){ return 2;} } if(tablero[1][0]==tablero[1][1] && tablero[1][1]==tablero[1][2]){ if(tablero[1][0]=='O'){ return 1;} if(tablero[1][0]=='X'){ return 2;} } if(tablero[2][0]==tablero[2][1] && tablero[2][1]==tablero[2][2]){ if(tablero[2][2]=='O'){ return 1;} if(tablero[2][2]=='X'){ return 2;} } //VICTORIA DIAGONALES if(tablero[0][0]==tablero[1][1] && tablero[1][1]==tablero[2][2]){ if(tablero[1][1]=='O'){ return 1;} if(tablero[1][1]=='X'){ return 2;} } if(tablero[0][2]==tablero[1][1] && tablero[1][1]==tablero[2][0]){ if(tablero[1][1]=='O'){ return 1;} if(tablero[1][1]=='X'){ return 2;} } //VICTORIA COLUMNAS if(tablero[0][0]==tablero[1][0] && tablero[1][0]==tablero[2][0]){ if(tablero[0][0]=='O'){ return 1;} if(tablero[0][0]=='X'){ return 2;} } if(tablero[0][1]==tablero[1][1] && tablero[1][1]==tablero[2][1]){ if(tablero[0][1]=='O'){ return 1;} if(tablero[0][1]=='X'){ return 2;} } if(tablero[0][2]==tablero[1][2] && tablero[1][2]==tablero[2][2]){ if(tablero[0][2]=='O'){ return 1;} if(tablero[0][2]=='X'){ return 2;} } int complete=0; for(int i = 0; i<3;i++){ for(int j=0; j<3;j++){ if(tablero[i][j]!='z'){ complete++; } } } if(complete==9){return 9;} return 3; } //-----------------------------------------RELOJ---------------------------------------// //Comprobar el reloj void Clock() { s++; if (s > 9) {s = 0;s2++;} if (s2 > 5) {s2 = 0;m++;} if (m > 9) {m = 0;m2++;} if (m2 > 9) {m2 = 0;} } void checkKB(int a) { if (digitalRead(42) == 0 && digitalRead(45)==0) { while(digitalRead(42) == 0 && digitalRead(45)==0){} if(a==0 && modo==1){ modo=0; s=0;s2=0;m=0;m2=0; startGame=false; permite=false; clearAll(); Serial3.write("Modo Calculadora"); clearAll(); } } if (digitalRead(44) == 0 && digitalRead(45)==0) { while(digitalRead(44) == 0 && digitalRead(45)==0){} if(a==0 && modo==0){ modo=1; permite=true; s=0;s2=0;m=0;m2=0; clearAll(); Serial3.write("Modo Juego"); } } if (digitalRead(42) == 0) { if (cadena.length() < 20) { if (a == 0) {aux = '1'; if(modo==2){timbre=3000;}} if (a == 1) {aux = '2'; if(modo==2){timbre=3100;}} if (a == 2) {aux = '3'; if(modo==2){timbre=3200;}} pulse = 1; } } if (digitalRead(43) == 0) { if (cadena.length() < 20) { if (a == 0) {aux = '4'; if(modo==2){timbre=3300;}} if (a == 1) {aux = '5'; if(modo==2){timbre=3400;}} if (a == 2) {aux = '6'; if(modo==2){timbre=3500;}} pulse = 1; } } if (digitalRead(44) == 0) { if (cadena.length() < 20) { if (a == 0 && modo==0 || a == 0 && startGame || modo == 2){aux = '7'; if(modo==2){timbre=3600;}} if (a == 1) {aux = '8'; if(modo==2){timbre=3700;}} if (a == 2) {aux = '9'; if(modo==2){timbre=3800;}} pulse = 1; } } if (digitalRead(45) == 0) { if(a==0 && aux=='#' && modo!=2){ Serial.println("hola"); modo=2; s=0;s2=0;m=0;m2=0; startGame=false; permite=true; clearAll(); Serial3.write("Modo Piano"); clearAll(); } if (a == 0 && modo==0) {aux = '*';} if (a == 2) {aux = '#';} if (cadena.length() < 20) { if (a == 1) { aux = '0'; pulse = 1; if(modo==2){ timbre=3900; } } } } } void clearAll() { Serial3.write(0xFE); Serial3.write(0x51); if(!modo){ Serial3.write(0xFE); Serial3.write(0x45); Serial3.write(0x53); Serial3.write('0'); permite=false; } Serial3.write(0xFE); Serial3.write(0x46); aux = '\0'; cadena = ""; } void cleanOne() { int z = cadena.length()-1; if (z >= 0) { char a = cadena.charAt(z); if(a=='-' || a=='/' || a=='*' || a=='+'){permite=true;}else{permite=false;} Serial3.write(0xFE); Serial3.write(0x4E); String cadena2 = cadena.substring(0,cadena.length()-1); cadena = cadena2; } aux = '\0'; } long calcRes(String sAux[],char charAux[]){ int punteroS = 0; int punteroChar = 0; for (int i = 0; i < cadena.length(); i++) { if (cadena.charAt(i) != '+' && cadena.charAt(i) != '-' && cadena.charAt(i) != '*' && cadena.charAt(i) != '/' && cadena.charAt('\0')) { sAux[punteroS] += cadena.charAt(i); } else { charAux[punteroS] = cadena.charAt(i); punteroChar++; punteroS++; } } long res = sAux[0].toInt(); if (punteroChar > 0) { for (int i = 0; i < punteroChar; i++) { if(charAux[i]=='+'){res+=sAux[i+1].toInt();} if(charAux[i]=='-'){res-=sAux[i+1].toInt();} if(charAux[i]=='*'){res*=sAux[i+1].toInt();} if(charAux[i]=='/'){res/=sAux[i+1].toInt();} } } return res; } void enterClean(long res){ String res2 = String(res); Serial3.write(0xFE); Serial3.write(0x45); Serial3.write(0x53); for(int i=0; i<20;i++){ Serial3.write(0xFE); Serial3.write(0x4E); } Serial3.write(0xFE); Serial3.write(0x45); Serial3.write(0x53-res2.length()+1); Serial3.print(res); res=0; Serial3.write(0xFE); Serial3.write(0x46); permite=false; delay(250); } void modo_calculadora() { if (aux == '*') {clearAll();} if (aux == '#') { if ((millis() - ini) >= 300) { ini = millis(); cleanOne(); } aux = '\0'; } //Center = resolver if (digitalRead(33) == LOW) { String sAux[10]; char charAux[10]; long res = calcRes(sAux,charAux); while (cadena.length()>0) { cleanOne(); } cleanOne(); //limpia el resultado anterior si hay e imprime el nuevo enterClean(res); } if(permite==true){ //Up = suma if (digitalRead(34) == LOW) { permite=false; Serial3.write("+"); cadena += "+"; delay(250); } //Down = resta if (digitalRead(31) == LOW) { permite=false; Serial3.write("-"); cadena += "-"; delay(250); } //Right = multiplicacion if (digitalRead(30) == LOW) { permite=false; Serial3.write("*"); cadena += "*"; delay(250); } //Left = division if (digitalRead(32) == LOW) { permite=false; Serial3.write("/"); cadena += "/"; delay(250); } } } //----------------------------------------------MODO Espejo--------------------------------------------// void isr_Espejo() { if (displayCount == 4) { displayCount = 0; } if (displayCount == 0) { PORTA = vector[s]; PORTL = 0b11111110; } if (displayCount == 1) { PORTA = vector[s2]; PORTL = 0b11111101; } if (displayCount == 2) { if(!sePulso) { PORTA = 0; } else { PORTA = vectorIn[s2]; } PORTL = 0b11111011; } if (displayCount == 3) { if(!sePulso) { PORTA = 0; } else { PORTA = vectorIn[s]; } PORTL = 0b11110111; } displayCount++; } void modo_espejo(){ if(digitalRead(34)==0){ s++; if(s>9){s2++; s=0;} if(s2>9){s2=0;} sePulso=false; delay(200); } if(digitalRead(31)==0){ s--; if(s<0){s2--; s=9;} if(s2<0){s2=9;} sePulso=false; delay(200); } if(digitalRead(33)==0){ sePulso=true; delay(200); } }
[ "danielreyes9756.com" ]
danielreyes9756.com
9d4af6ba7b8450eb6e11fc525b01c964c7c80093
d320d6fed418f4339a953f3963e7bd4b6b4b3cd0
/platformlibs/libwin32/basalt/win32/shared/win32_gfx_factory.cpp
e34a0857a7fd1827f4d38491c206887dbbdeec23
[]
no_license
juli27/basaltcpp
6ef93bb3c322f328262bb18c572968eb0ff8fc2b
1c6bb55f80e8c1fa4aa3b52a7111e78741424955
refs/heads/master
2023-08-31T04:30:57.379453
2023-08-30T18:57:54
2023-08-30T18:57:54
189,708,858
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
#include <basalt/win32/shared/win32_gfx_factory.h> #if BASALT_DEV_BUILD #include <basalt/gfx/backend/validating_swap_chain.h> #endif namespace basalt::gfx { auto Win32GfxFactory::create_device_and_swap_chain( const HWND window, const DeviceAndSwapChainDesc& desc) const -> DeviceAndSwapChain { DeviceAndSwapChain res {do_create_device_and_swap_chain(window, desc)}; #if BASALT_DEV_BUILD res.swapChain = ValidatingSwapChain::wrap(res.swapChain); #endif return res; } } // namespace basalt::gfx
[ "juli27@users.noreply.github.com" ]
juli27@users.noreply.github.com
89a1eb048968f8d6688e5c6cce86a5809463b3ea
d9184d5f98830195afcdba7bf79b8bde6f90db51
/src/qt/sendcoinsdialog.cpp
b081e0a71722be30b033e9c9bb0f41eba691809f
[ "MIT" ]
permissive
hexioncoin/hexion
2aeb5ebbbc13ff105d9b72d4bda49aabf8246d37
61ddcd8eef5528817b022cb5ed39b433f3762477
refs/heads/master
2016-09-06T05:56:16.185217
2014-11-13T13:27:40
2014-11-13T13:27:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,893
cpp
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Hexion address (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:Test;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid Hexion address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
[ "hexioncoin@hotmail.com" ]
hexioncoin@hotmail.com
e1ee114c8ca3cdc6e0449b63ca1ab9185c1e5783
a71582e89e84a4fae2595f034d06af6d8ad2d43a
/tensorflow/core/grappler/optimizers/graph_optimizer.h
44dfe0de7890f09feb0b2cbfc450ddb9e37fc3cd
[ "Apache-2.0" ]
permissive
tfboyd/tensorflow
5328b1cabb3e24cb9534480fe6a8d18c4beeffb8
865004e8aa9ba630864ecab18381354827efe217
refs/heads/master
2021-07-06T09:41:36.700837
2019-04-01T20:21:03
2019-04-01T20:26:09
91,494,603
3
0
Apache-2.0
2018-07-17T22:45:10
2017-05-16T19:06:01
C++
UTF-8
C++
false
false
2,944
h
/* Copyright 2017 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_CORE_GRAPPLER_OPTIMIZERS_GRAPH_OPTIMIZER_H_ #define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_GRAPH_OPTIMIZER_H_ #include <string> #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/env.h" namespace tensorflow { namespace grappler { class Cluster; struct GrapplerItem; // An abstract interface for an algorithm for generating a candidate // optimization of a GrapplerItem for running on a cluster. class GraphOptimizer { public: GraphOptimizer() : deadline_usec_(0) {} virtual ~GraphOptimizer() {} virtual string name() const = 0; // Routine called to allow an algorithm to propose a rewritten graph // for the graph, feeds and fetches in "item" to run more efficiently // on "cluster". // Returns an error status if it failed to generate a solution. virtual Status Optimize(Cluster* cluster, const GrapplerItem& item, GraphDef* optimized_graph) = 0; // Method invoked by the framework so that it can provide feedback // on how well the "optimized_graph" (produced as *optimized_graph from a // call to Optimize) performed. Lower "result" scores are better. virtual void Feedback(Cluster* cluster, const GrapplerItem& item, const GraphDef& optimized_graph, double result) = 0; // Set deadline in microseconds since epoch. A value of zero means no // deadline. void set_deadline_usec(uint64 deadline_usec) { deadline_usec_ = deadline_usec; } uint64 deadline_usec() const { return deadline_usec_; } bool DeadlineExceeded() const { return deadline_usec_ > 0 && Env::Default()->NowMicros() > deadline_usec_; } private: uint64 deadline_usec_; }; #define GRAPPLER_RETURN_IF_DEADLINE_EXCEEDED() \ do { \ if (this->DeadlineExceeded()) { \ return errors::DeadlineExceeded(this->name(), " exceeded deadline."); \ } \ } while (0) } // end namespace grappler } // end namespace tensorflow #endif // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_GRAPH_OPTIMIZER_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
a75df37088739fa342da2c3a42de4d5a3572dd85
b0368adc2331e1d0b770aeae1773b15ad81072d7
/include/GnssErrorModel.h
26e675f4a8d676decdf6b0a6421ce0d6f4e87cbe
[]
no_license
neophack/PPPLib_v2.0
c3774c285ef8195137f22357604eb2aba789f45f
344f973ea3de74d1db1823988662a5162f6d0080
refs/heads/master
2022-12-05T12:08:38.409433
2020-08-17T02:45:50
2020-08-17T02:45:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,520
h
// // Created by cc on 7/19/20. // #ifndef PPPLIB_GNSSERRORMODEL_H #define PPPLIB_GNSSERRORMODEL_H #include "GnssFunc.h" using namespace PPPLib; namespace PPPLib{ class cGnssModel{ public: cGnssModel(); virtual ~cGnssModel(); public: virtual void InitErrModel(tPPPLibConf C); void InitSatInfo(tSatInfoUnit* sat_info,Vector3d* blh); virtual void UpdateSatInfo(); public: // tNav nav_; tSatInfoUnit* sat_info_; Vector3d blh_; tPPPLibConf PPPLibC_; }; class cTrpDelayModel: public cGnssModel { public: cTrpDelayModel(); cTrpDelayModel(Vector3d blh,tSatInfoUnit& sat_info); ~cTrpDelayModel(); public: Vector2d GetTrpError(double humi,double *x,int it); Vector2d GetSaasTrp(double humi,Vector2d* sat_trp_dry, Vector4d* sat_trp_wet); void UpdateSatInfo() override; void InitTrpModel(Vector3d& blh); private: bool SaasModel(double humi); Vector4d EstTrpWet(double humi,double *x,int it); void TrpMapNeil(cTime t,double el); private: Vector2d zenith_trp_={0,0}; //dry, wet Vector2d slant_trp_dry_={0,0}; //dry, map_dry Vector4d slant_trp_wet_={0,0,0,0}; //wet, map_wet,grand_e,grand_n }; class cIonDelayModel: public cGnssModel { public: cIonDelayModel(); cIonDelayModel(Vector3d blh,tSatInfoUnit& sat_info,tNav nav); ~cIonDelayModel(); public: Vector2d GetIonError(); Vector2d GetKlobIon(); void UpdateSatInfo() override; void InitIondelayModel(double ion_para[NSYS][8]); private: bool KlobModel(); bool GimModel(); bool IonFreeModel(); bool IonEstModel(); private: double ion_para_[NSYS][8]={{0}}; Vector2d ion_delay_; // L1_ion/ion_map }; class cCbiasModel:public cGnssModel { public: cCbiasModel(); cCbiasModel(tNav nav,tSatInfoUnit& sat_info); ~cCbiasModel(); public: void GetCodeBias(); void InitCbiasModel(double cbias[MAX_SAT_NUM][MAX_GNSS_CODE_BIAS_PAIRS],vector<tBrdEphUnit>& brd_eph); void UpdateSatInfo() override; private: void TgdModel(); void BsxModel(); private: double code_bias_[MAX_SAT_NUM][MAX_GNSS_CODE_BIAS_PAIRS]={{0}}; vector<tBrdEphUnit> brd_eph_; private: double cbias_[NSYS+1][MAX_GNSS_FRQ_NUM]={{0}}; }; class cAntModel:public cGnssModel { public: cAntModel(); ~cAntModel(); private: double InterpPcv(double ang,const double *var); double InterpAziPcv(const tAntUnit& ant,double az,double ze,int f); void SatPcvModel(tSatInfoUnit* sat_info,double nadir,double* dant); public: void InitAntModel(tPPPLibConf C,tAntUnit sat_ant[MAX_SAT_NUM],tAntUnit rec_ant[2]); void SatPcvCorr(tSatInfoUnit* sat_info,Vector3d rec_pos,double* pcv_dants); void RecAntCorr(tSatInfoUnit* sat_info,double* dantr,RECEIVER_INDEX rec_idx); private: tAntUnit *sat_ant_; tAntUnit *rec_ant_; }; class cEphModel:public cGnssModel { public: cEphModel(); ~cEphModel(); private: // broadcast int SelectBrdEph(tSatInfoUnit* sat_info,int iode); int SelectGloBrdEph(tSatInfoUnit* sat_info,int iode); void BrdSatClkErr(tSatInfoUnit* sat_info,tBrdEphUnit eph); void BrdGloSatClkErr(tSatInfoUnit* sat_info,tBrdGloEphUnit glo_eph); bool BrdClkError(tSatInfoUnit* sat_info); double EphUra(int ura); double ClkRelErr(double mu,double sinE,tBrdEphUnit eph); void BrdSatPos(tSatInfoUnit& sat_info,tBrdEphUnit eph); void GloDefEq(const VectorXd x,VectorXd& x_dot,const Vector3d acc); void GloOrbit(double t,VectorXd& x,const Vector3d acc); void BrdGloSatPos(tSatInfoUnit& sat_info,tBrdGloEphUnit glo_eph); bool BrdEphModel(tSatInfoUnit* sat_info); // precise void SatPcoCorr(tSatInfoUnit* sat_info,Vector3d sat_pos,Vector3d& dant); bool PreSatClkCorr(tSatInfoUnit* sat_info); bool PreSatPos(tSatInfoUnit* sat_info); bool PreEphModel(tSatInfoUnit* sat_info); public: bool EphCorr(vector<tSatInfoUnit>& epoch_sat_info); void InitEphModel(vector<tBrdEphUnit>& brd_eph,vector<tBrdGloEphUnit>& brd_glo_eph,vector<tPreOrbUnit>& pre_orb, vector<tPreClkUnit>& pre_clk,tAntUnit* sat_ant); private: vector<tPreClkUnit> pre_clk_; vector<tPreOrbUnit> pre_orb_; vector<tBrdEphUnit> brd_eph_; vector<tBrdGloEphUnit> brd_glo_eph_; tAntUnit *sat_ant_; }; class cTidModel:public cGnssModel { public: cTidModel(); ~cTidModel(); private: int GetErpVal(cTime t); void TideSl(const double* eu,const double* rp,double GMp,Vector3d blh,double* dr); void IersMeanPole(double *xp,double *yp); void TidSolid(); void TidOcean(); void TidPole(); public: void InitTidModel(tPPPLibConf C,vector<tErpUnit> erp,double ocean_par[2][66]); void TidCorr(cTime t,Vector3d rec_pos,Vector3d& dr); private: cTime tut_; double re_; Vector3d blh_; Matrix3d E_; Vector3d tid_dr_[3]; Vector3d denu_[2]; Vector3d sun_pos_; Vector3d moon_pos_; double gmst_; double erp_val_[5]; private: vector<tErpUnit> erp_; double ocean_par_[2][6*11]; RECEIVER_INDEX rec_idx_; }; class cGnssErrCorr { public: cGnssErrCorr(); ~cGnssErrCorr(); private: bool SatYaw(tSatInfoUnit& sat_info,Vector3d& exs,Vector3d& eys); public: void InitGnssErrCorr(tPPPLibConf C, tNav* nav); void BD2MultipathModel(tSatInfoUnit* sat_info); double SagnacCorr(Vector3d sat_xyz,Vector3d rec_xyz); double ShapiroCorr(int sys,Vector3d sat_xyz,Vector3d rec_xyz); void PhaseWindUp(tSatInfoUnit& sat_info,Vector3d rec_xyz); public: cEphModel eph_model_; cCbiasModel cbia_model_; cTrpDelayModel trp_model_; cIonDelayModel ion_model_; cAntModel ant_model_; cTidModel tid_model_; private: double bd2_mp_[3]; }; } #endif //PPPLIB_GNSSERRORMODEL_H
[ "cchen@cumt.edu.cn" ]
cchen@cumt.edu.cn
1ebafccf35d7801953d4d12dec6589d8c3f51bab
401982f39507e281d90c1af3f2d81c15a30e3602
/engine/shader/abstract_shader_variant.cpp
34b9890fd8cc4baeba5cb4edd36e0950ae3b543e
[]
no_license
NukeBird/rendy
60a3ea2b6b324eb2b36ffd5625ff97687f059d83
72c7d7db34f374b8245b41f0e27b220dc9738fa8
refs/heads/master
2023-04-08T20:03:26.187857
2020-01-13T13:13:46
2020-01-13T13:13:46
211,322,159
0
0
null
null
null
null
UTF-8
C++
false
false
6,435
cpp
#include "abstract_shader_variant.h" #include "../util/log.h" #include <optick.h> Rendy::AbstractShaderVariant::AbstractShaderVariant(OGL version, const std::string& vtx, const std::string& frg): version(version) { OPTICK_EVENT(); this->vertex_source = vtx; this->fragment_source = frg; compile_shader(); OPTICK_TAG("id", program_id); } Rendy::AbstractShaderVariant::~AbstractShaderVariant() { OPTICK_EVENT(); reset(); } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const glm::vec3& vec) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform3fv(location, 1, &vec[0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const glm::mat4& mat) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniformMatrix4fv(location, 1, false, &mat[0][0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const glm::mat3& mat) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniformMatrix3fv(location, 1, false, &mat[0][0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const float number) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform1fv(location, 1, &number); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const int number) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform1iv(location, 1, &number); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<glm::vec3>& vec_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform3fv(location, static_cast<GLsizei>(vec_array.size()), &vec_array[0][0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<glm::mat4>& mat_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniformMatrix4fv(location, static_cast<GLsizei>(mat_array.size()), false, glm::value_ptr(mat_array[0])); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<glm::mat3>& mat_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniformMatrix3fv(location, static_cast<GLsizei>(mat_array.size()), false, &mat_array[0][0][0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<float>& float_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform1fv(location, static_cast<GLsizei>(float_array.size()), &float_array[0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<int>& int_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform1iv(location, static_cast<GLsizei>(int_array.size()), &int_array[0]); } } int Rendy::AbstractShaderVariant::get_attribute_location(const std::string& name) const { OPTICK_EVENT(); int location = -1; auto it = attribute_cache.find(name); if (it != attribute_cache.end()) { location = (*it).second; } OPTICK_TAG("name", name.c_str()); OPTICK_TAG("location", location); return location; } int Rendy::AbstractShaderVariant::get_buffer_binding_point(const std::string & name) const { OPTICK_EVENT(); int location = -1; auto it = buffer_cache.find(name); if (it != buffer_cache.end()) { location = (*it).second; } OPTICK_TAG("name", name.c_str()); OPTICK_TAG("location", location); return location; } void Rendy::AbstractShaderVariant::bind() { OPTICK_EVENT(); OPTICK_TAG("id", program_id); glUseProgram(program_id); } void Rendy::AbstractShaderVariant::unbind() { OPTICK_EVENT(); OPTICK_TAG("id", program_id); glUseProgram(0); } void Rendy::AbstractShaderVariant::cache_stuff() { cache_uniform_locations(); cache_attribute_locations(); cache_buffer_binding_points(); if (!attribute_cache.empty()) { Log::info("CACHED ATTRIBUTES"); for (auto& i : attribute_cache) { Log::info("{0}: {1}", i.first, i.second); } } if (!uniform_cache.empty()) { Log::info("CACHED UNIFORMS"); for (auto& i : uniform_cache) { Log::info("{0}: {1}", i.first, i.second); } } if (!buffer_cache.empty()) { Log::info("BUFFER BINDING POINTS"); for (auto& i : buffer_cache) { Log::info("{0}: {1}", i.first, i.second); } } } void Rendy::AbstractShaderVariant::reload() { OPTICK_EVENT(); if (!validate()) { compile_shader(); } } bool Rendy::AbstractShaderVariant::validate() const { OPTICK_EVENT(); if (glIsProgram(program_id)) { int link_status; glGetProgramiv(program_id, GL_LINK_STATUS, &link_status); return link_status != GL_FALSE; } return false; } int Rendy::AbstractShaderVariant::get_uniform_location(const std::string& name) const { OPTICK_EVENT(); int location = -1; auto it = uniform_cache.find(name); if (it != uniform_cache.end()) { location = (*it).second; } OPTICK_TAG("name", name.c_str()); OPTICK_TAG("location", location); return location; } void Rendy::AbstractShaderVariant::compile_shader() { OPTICK_EVENT(); reset(); uint32_t vtx_id = glCreateShader(GL_VERTEX_SHADER); const char* vtx_str = vertex_source.c_str(); glShaderSource(vtx_id, 1, &vtx_str, NULL); glCompileShader(vtx_id); uint32_t frg_id = glCreateShader(GL_FRAGMENT_SHADER); const char* frg_str = fragment_source.c_str(); glShaderSource(frg_id, 1, &frg_str, NULL); glCompileShader(frg_id); program_id = glCreateProgram(); glAttachShader(program_id, vtx_id); glAttachShader(program_id, frg_id); glLinkProgram(program_id); glDeleteShader(vtx_id); glDeleteShader(frg_id); OPTICK_TAG("id", program_id); } void Rendy::AbstractShaderVariant::reset() { OPTICK_EVENT(); OPTICK_TAG("id", program_id); glDeleteProgram(program_id); program_id = 0; }
[ "nukebird.dev@gmail.com" ]
nukebird.dev@gmail.com
148c3dd4baca8282366df8e5089e487d0df25538
2927dcbbb0723e8e76710040407c5561fb6b0121
/16384/other/lavos/src/delay.cpp
72ed4fd59741147bfda834f2aed6f2f84b5699a3
[ "BSD-3-Clause" ]
permissive
cafferta10/hardcode
9583599825010c16d46e199aaff9b15834730c65
2033e906d3a7850f88dda431f15a70f0981729b9
refs/heads/master
2021-05-22T01:06:19.072005
2019-10-26T03:28:44
2019-10-26T03:28:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,120
cpp
#include "delay.hpp" /** Maximum number of delay buffers. */ #define MAX_DELAY_BUFFERS 20 /** \brief Delay buffers. * * The delay buffers are too large for stack. Thus, we read them from this global buffer and always take the * 'next' one for each delay. * * I feel bad about this, but what can you do. */ static float g_delay_buffers[MAX_DELAY_BUFFERS][g_delay_buffer_size]; /** Next delay buffer to give. */ static uint8_t current_delay_buffer = 0; /** \brief Acquire delay buffer. * * Will also clear the buffer. */ static float* get_delay_buffer() { float *ret = g_delay_buffers[current_delay_buffer]; { for(unsigned ii = 0; (ii < g_delay_buffer_size); ++ii) { ret[ii] = 0.0f; } } ++current_delay_buffer; return ret; } Delay::Delay(void) { m_mode=k_delay_mode_off; m_level=0.0f; m_delay_index=m_input_index=0; m_delay_time=1; m_feedback=0.0f; m_delay_buffer_l = get_delay_buffer(); m_delay_buffer_r = get_delay_buffer(); m_lowpass_filter_l.setMode(k_filter_lowpass); m_lowpass_filter_l.setCutoff(1.0f); m_highpass_filter_l.setMode(k_filter_highpass); m_highpass_filter_l.setCutoff(0.0f); m_lowpass_filter_r.setMode(k_filter_lowpass); m_lowpass_filter_r.setCutoff(1.0f); m_highpass_filter_r.setMode(k_filter_highpass); m_highpass_filter_r.setCutoff(0.0f); } void Delay::setMode(float value) { value *= k_num_delay_modes; m_mode = common::clrintf(value); } void Delay::process(float input, float &output_l, float& output_r) { process(input,input,output_l,output_r); } void Delay::process(float inputl, float inputr, float &output_l, float& output_r) { float inl = m_level*inputl; float inr = m_level*inputr; // output_l=m_delay_buffer_l[m_delay_index]; // output_r=m_delay_buffer_r[m_delay_index]; output_l=m_highpass_filter_l.process(m_lowpass_filter_l.process(m_delay_buffer_l[m_delay_index])); output_r=m_highpass_filter_r.process(m_lowpass_filter_r.process(m_delay_buffer_r[m_delay_index])); switch(m_mode) { case k_delay_mode_mono: m_delay_buffer_l[m_delay_index] = 0.707f*(inl+inr) + output_l * m_feedback; m_delay_buffer_r[m_delay_index] = 0.707f*(inl+inr) + output_r * m_feedback; break; //stereo delay not used // case k_delay_mode_stereo: // m_delay_buffer_l[m_delay_index] = inl + output_l * m_feedback; // m_delay_buffer_r[m_delay_index] = inr + output_r * m_feedback; // break; case k_delay_mode_pingpong: m_delay_buffer_l[m_delay_index] = 0.707f*(inl+inr) + output_r * m_feedback; m_delay_buffer_r[m_delay_index] = output_l * m_feedback; break; case k_delay_mode_cross: m_delay_buffer_l[m_delay_index] = inl + output_r * m_feedback; m_delay_buffer_r[m_delay_index] = inr + output_l * m_feedback; break; default: m_delay_buffer_l[m_delay_index] = 0.0f; m_delay_buffer_r[m_delay_index] = 0.0f; break; } m_delay_index++; if (m_delay_index > m_delay_time) m_delay_index = 0; }
[ "youngthug@youngthug.com" ]
youngthug@youngthug.com
9ef4e9c1688aadd17dbda6bda69efd7c51f2b9a0
266310ea0b8063e56918727a0a0f65bb22597fea
/src/backend/catalog/mataData.cpp
4cfa7e9f720ac6f4a8231b65454db1d68f7175c5
[]
no_license
RingsC/StorageEngine
88ec03d019d6378b93d8abd3a57a9447cf31b932
4e8447751867329e1d7b7dd9b4d00e2020be9306
refs/heads/master
2021-04-27T00:07:08.962455
2018-03-04T03:13:22
2018-03-04T03:13:22
123,751,907
2
1
null
null
null
null
UTF-8
C++
false
false
1,159
cpp
#include <iostream> #include <exception> #include "postgres.h" #include "postgres_ext.h" #include "catalog/metaData.h" #include "storage/spin.h" using namespace std; hash_map<Oid, Colinfo> g_col_info_cache; slock_t g_spinlock = SpinLockInit(&g_spinlock); void setColInfo(Oid colid, Colinfo pcol_info) { if(pcol_info == NULL) { return; } try { SpinLockAcquire(&g_spinlock); g_col_info_cache.insert(std::pair<Oid, Colinfo>(colid, pcol_info)); SpinLockRelease(&g_spinlock); } #ifdef _DEBUG catch(exception &r) { ereport(WARNING, (errmsg("Set ColInfo:%s %s",__FUNCTION__,r.what()))); } #else catch(exception &/*r*/) { } #endif } Colinfo getColInfo(Oid colid) { hash_map<Oid, Colinfo>::iterator iter; try { SpinLockAcquire(&g_spinlock); iter = g_col_info_cache.find(colid); if (iter != g_col_info_cache.end()) { SpinLockRelease(&g_spinlock); return iter->second; } SpinLockRelease(&g_spinlock); } #ifdef _DEBUG catch(exception &r) { ereport(WARNING, (errmsg("Get ColInfo:%s %s",__FUNCTION__,r.what()))); } #else catch(exception &/*r*/) { } #endif return NULL; }
[ "hom.lee@hotmail.com" ]
hom.lee@hotmail.com
8c6fc42bc80e3941ee5dfd82588954d92a383c0c
90db83e7fb4d95400e62fa2ce48bd371754987e0
/src/components/password_manager/core/browser/form_saver_impl.h
a01ca3e4bac5c5d3cbd67795c54c1c8926cc5c0f
[ "BSD-3-Clause" ]
permissive
FinalProjectNEG/NEG-Browser
5bf10eb1fb8b414313d5d4be6b5af863c4175223
66c824bc649affa8f09e7b1dc9d3db38a3f0dfeb
refs/heads/main
2023-05-09T05:40:37.994363
2021-06-06T14:07:21
2021-06-06T14:07:21
335,742,507
2
4
null
null
null
null
UTF-8
C++
false
false
2,014
h
// Copyright 2016 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 COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FORM_SAVER_IMPL_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FORM_SAVER_IMPL_H_ #include <memory> #include "base/macros.h" #include "components/password_manager/core/browser/form_saver.h" namespace password_manager { class PasswordStore; // The production code implementation of FormSaver. class FormSaverImpl : public FormSaver { public: // |store| needs to outlive |this| and will be used for all PasswordStore // operations. explicit FormSaverImpl(PasswordStore* store); ~FormSaverImpl() override; // FormSaver: PasswordForm PermanentlyBlacklist(PasswordStore::FormDigest digest) override; void Unblacklist(const PasswordStore::FormDigest& digest) override; void Save(PasswordForm pending, const std::vector<const PasswordForm*>& matches, const base::string16& old_password) override; void Update(PasswordForm pending, const std::vector<const PasswordForm*>& matches, const base::string16& old_password) override; void UpdateReplace(PasswordForm pending, const std::vector<const PasswordForm*>& matches, const base::string16& old_password, const PasswordForm& old_unique_key) override; void Remove(const PasswordForm& form) override; std::unique_ptr<FormSaver> Clone() override; private: // The class is stateless. Don't introduce it. The methods are utilities for // common tasks on the password store. The state should belong to either a // form handler or origin handler which could embed FormSaver. // Cached pointer to the PasswordStore. PasswordStore* const store_; DISALLOW_COPY_AND_ASSIGN(FormSaverImpl); }; } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FORM_SAVER_IMPL_H_
[ "sapirsa3@ac.sce.ac.il" ]
sapirsa3@ac.sce.ac.il
455419ccddd7e92d35da5891cd4ade8db8337cb1
0dae134774f7887eb3ffb4b7611b26e8041a0692
/Competitive Programming/Contests/CodeForces/Contests/Good Bye/Good Bye 2015/New Year and Ancient Prophecy/prophesy.cpp
aaae163cea6272d92d0c346098665162aec4f47c
[]
no_license
andyyang200/CP
b6ce11eb58fd535815aa0f7f5a22e9ed009bf470
46efbcdaf441ee485dbf9eb82e9f00e488d2d362
refs/heads/master
2020-08-27T14:49:36.723263
2019-10-25T04:09:11
2019-10-25T04:09:11
217,407,673
0
0
null
null
null
null
UTF-8
C++
false
false
1,877
cpp
//Andrew Yang #include <iostream> #include <stdio.h> #include <sstream> #include <fstream> #include <string> #include <string.h> #include <vector> #include <deque> #include <queue> #include <stack> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <algorithm> #include <functional> #include <utility> #include <bitset> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> #include <climits> using namespace std; #define FOR(index, start, end) for(int index = start; index < end; index++) #define RFOR(index, start, end) for(int index = start; index > end; index--) #define FOREACH(itr, b) for(auto itr = b.begin(); itr != b.end(); itr++) #define RFOREACH(itr, b) for(auto itr = b.rbegin(); itr != b.rend(); itr++) #define INF 1000000000 #define M 1000000007 typedef long long ll; typedef pair<int, int> pii; ll dp[5001][5001]; ll p[5001][5001]; int first[5001][5001]; int main() { int n; scanf("%d", &n); string s; cin >> s; RFOR(a, n - 1, -1) { RFOR(b, n - 1, a) { if (s[a] != s[b] || b == n - 1) { first[a][b] = 0; } else { first[a][b] = 1 + first[a + 1][b + 1]; } if (a + first[a][b] >= b) { first[a][b] = 0; } } } FOR(c, 0, n) { RFOR(b, c, -1) { if (s[b] == '0') { dp[b][c] = 0; } else if (b == 0) { dp[b][c] = 1; } else { int a = (b - 1) - (c - b); int l = max(a + 1, 0); dp[b][c] += p[l][b - 1]; int length = c - b + 1; if (a >= 0 && s[a + first[a][b]] < s[b + first[a][b]]) { dp[b][c] += dp[a][b - 1]; } } dp[b][c] %= M; p[b][c] = dp[b][c] + (b == c ? 0 : p[b + 1][c]); p[b][c] %= M; } } int ans = 0; FOR(i, 0, n) { ans += dp[i][n - 1]; ans %= M; } cout << ans << endl; }
[ "andy@zensors.com" ]
andy@zensors.com
9afd51135471e981f046ff7635bc6386666a2188
20b9fcfc1a657efaf6487bb4c2cb0ce326c79919
/Sources/Past/ABC094/ABC094C.cpp
f1a615bbe6340a94edf587032bb243e3de64348c
[]
no_license
kurose-th/CompetetiveProgramming
e729da45db40d7d382348bca703fbc2f4e81d06a
8b0fd918490941942aed4b9cf7cb733352ff4088
refs/heads/master
2020-03-21T22:53:11.154527
2020-02-16T11:25:43
2020-02-16T11:25:43
139,153,162
0
0
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include <cstdio> #include <string> #include <cmath> #include <string> #include <algorithm> #include <iostream> #include <map> #include <vector> #include <iomanip> #include <tuple> #include <queue> using namespace std; typedef long long ll; #define rep(i, a, n) for (int i=a;i<n;++i) #define repeq(i, a, n) for(int i=a;i<=n;++i) #define per(i, a, n) for (int i=n-1; i>=a;--i) #define pb push_back #define mp make_pair #define all(x) (x).begin(), (x).end() // C - Many Medians int N; vector<ll> x; vector<ll> A; vector<ll> ans; int main(){ cin >> N; rep(i, 0, N){ ll tmp; cin >> tmp; x.push_back(tmp); A.push_back(tmp); } sort(all(A)); rep(i, 0, N){ if(x[i] >= A[(N/2)]){ cout << A[N/2-1] << endl; }else{ cout << A[N/2] << endl; } } return 0; }
[ "krs1218@gmail.com" ]
krs1218@gmail.com
61411aa26972ff36e1eb17f67f1d7717a5081bba
72f1e6b2c742751c23ba16f824a0a91ae4cfcf99
/HackerEarth/HackerEarth_StringWeight.cpp
f16730b0932c897e77a9936e80b49966b0e46e20
[]
no_license
ms-darshan/Competitive-Coding
9d6f7e45a996cb30d54e54eb2c847eeeeccb5dab
76d2e229dd281d063cca6e3374c8d25ed5fff911
refs/heads/master
2020-04-14T00:37:16.076282
2018-05-26T20:00:40
2018-05-26T20:00:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
880
cpp
//http://www.hackerearth.com/epiphany-4-1/algorithm/string-weight/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define sp system("pause") #define FOR(i,a,b) for(int i=a;i<=b;++i) #define FORD(i,a,b) for(int i=a;i>=b;--i) #define REP(i,n) FOR(i,0,(int)n-1) #define MS0(x) memset(x,0,sizeof(x)) #define MS1(x) memset(x,1,sizeof(x)) #define ll long long #define MOD 1000000007 int main(){ int t, n, l; char c[10005], x, y; char skip[26]; int f[26]; ll int ans; scanf("%d", &t); REP(i, t){ MS0(f); ans = 0; scanf("%s", c); l = strlen(c); REP(j, l){ f[c[j] - 97]++; ans += (c[j] - 96); } scanf("%d", &n); REP(j, n){ scanf("%c%c", &x, &y); ans = ans - (f[y - 97] * (y - 96)); } printf("%lld\n", ans); } return 0; } //Solved
[ "akshay95aradhya@gmail.com" ]
akshay95aradhya@gmail.com
9ab01c959f70d1ac40c649afb8aeeb4f2b8259c7
e2ad74f7396a095244676ba5d881574080047862
/JuceLibraryCode/modules/juce_audio_formats/codecs/juce_WavAudioFormat.cpp
58c3d98ae8069a9eac357046a047b285e5a6192f
[]
no_license
kasbah/juci
fd4fae5b45c8a7f97f5143fc4aaf8d341d535d32
5bdc96dfa72b14290e067cb6f2578a57e060a37d
refs/heads/master
2016-09-05T22:48:35.775128
2013-11-08T02:34:23
2013-11-08T02:34:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
58,185
cpp
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ static const char* const wavFormatName = "WAV file"; static const char* const wavExtensions[] = { ".wav", ".bwf", 0 }; //============================================================================== const char* const WavAudioFormat::bwavDescription = "bwav description"; const char* const WavAudioFormat::bwavOriginator = "bwav originator"; const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref"; const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date"; const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time"; const char* const WavAudioFormat::bwavTimeReference = "bwav time reference"; const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history"; StringPairArray WavAudioFormat::createBWAVMetadata (const String& description, const String& originator, const String& originatorRef, const Time date, const int64 timeReferenceSamples, const String& codingHistory) { StringPairArray m; m.set (bwavDescription, description); m.set (bwavOriginator, originator); m.set (bwavOriginatorRef, originatorRef); m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d")); m.set (bwavOriginationTime, date.formatted ("%H:%M:%S")); m.set (bwavTimeReference, String (timeReferenceSamples)); m.set (bwavCodingHistory, codingHistory); return m; } const char* const WavAudioFormat::acidOneShot = "acid one shot"; const char* const WavAudioFormat::acidRootSet = "acid root set"; const char* const WavAudioFormat::acidStretch = "acid stretch"; const char* const WavAudioFormat::acidDiskBased = "acid disk based"; const char* const WavAudioFormat::acidizerFlag = "acidizer flag"; const char* const WavAudioFormat::acidRootNote = "acid root note"; const char* const WavAudioFormat::acidBeats = "acid beats"; const char* const WavAudioFormat::acidDenominator = "acid denominator"; const char* const WavAudioFormat::acidNumerator = "acid numerator"; const char* const WavAudioFormat::acidTempo = "acid tempo"; const char* const WavAudioFormat::ISRC = "ISRC"; //============================================================================== namespace WavFileHelpers { inline int chunkName (const char* const name) noexcept { return (int) ByteOrder::littleEndianInt (name); } inline size_t roundUpSize (size_t sz) noexcept { return (sz + 3) & ~3u; } #if JUCE_MSVC #pragma pack (push, 1) #endif struct BWAVChunk { char description [256]; char originator [32]; char originatorRef [32]; char originationDate [10]; char originationTime [8]; uint32 timeRefLow; uint32 timeRefHigh; uint16 version; uint8 umid[64]; uint8 reserved[190]; char codingHistory[1]; void copyTo (StringPairArray& values, const int totalSize) const { values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, sizeof (description))); values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, sizeof (originator))); values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, sizeof (originatorRef))); values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, sizeof (originationDate))); values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, sizeof (originationTime))); const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow); const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh); const int64 time = (((int64)timeHigh) << 32) + timeLow; values.set (WavAudioFormat::bwavTimeReference, String (time)); values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory, totalSize - (int) offsetof (BWAVChunk, codingHistory))); } static MemoryBlock createFrom (const StringPairArray& values) { MemoryBlock data (roundUpSize (sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8())); data.fillWith (0); BWAVChunk* b = (BWAVChunk*) data.getData(); // Allow these calls to overwrite an extra byte at the end, which is fine as long // as they get called in the right order.. values [WavAudioFormat::bwavDescription] .copyToUTF8 (b->description, 257); values [WavAudioFormat::bwavOriginator] .copyToUTF8 (b->originator, 33); values [WavAudioFormat::bwavOriginatorRef] .copyToUTF8 (b->originatorRef, 33); values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11); values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9); const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue(); b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff)); b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32)); values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff); if (b->description[0] != 0 || b->originator[0] != 0 || b->originationDate[0] != 0 || b->originationTime[0] != 0 || b->codingHistory[0] != 0 || time != 0) { return data; } return MemoryBlock(); } } JUCE_PACKED; //============================================================================== struct SMPLChunk { struct SampleLoop { uint32 identifier; uint32 type; // these are different in AIFF and WAV uint32 start; uint32 end; uint32 fraction; uint32 playCount; } JUCE_PACKED; uint32 manufacturer; uint32 product; uint32 samplePeriod; uint32 midiUnityNote; uint32 midiPitchFraction; uint32 smpteFormat; uint32 smpteOffset; uint32 numSampleLoops; uint32 samplerData; SampleLoop loops[1]; template <typename NameType> static void setValue (StringPairArray& values, NameType name, uint32 val) { values.set (name, String (ByteOrder::swapIfBigEndian (val))); } static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val) { setValue (values, "Loop" + String (prefix) + name, val); } void copyTo (StringPairArray& values, const int totalSize) const { setValue (values, "Manufacturer", manufacturer); setValue (values, "Product", product); setValue (values, "SamplePeriod", samplePeriod); setValue (values, "MidiUnityNote", midiUnityNote); setValue (values, "MidiPitchFraction", midiPitchFraction); setValue (values, "SmpteFormat", smpteFormat); setValue (values, "SmpteOffset", smpteOffset); setValue (values, "NumSampleLoops", numSampleLoops); setValue (values, "SamplerData", samplerData); for (int i = 0; i < (int) numSampleLoops; ++i) { if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize) break; setValue (values, i, "Identifier", loops[i].identifier); setValue (values, i, "Type", loops[i].type); setValue (values, i, "Start", loops[i].start); setValue (values, i, "End", loops[i].end); setValue (values, i, "Fraction", loops[i].fraction); setValue (values, i, "PlayCount", loops[i].playCount); } } template <typename NameType> static uint32 getValue (const StringPairArray& values, NameType name, const char* def) { return ByteOrder::swapIfBigEndian ((uint32) values.getValue (name, def).getIntValue()); } static uint32 getValue (const StringPairArray& values, int prefix, const char* name, const char* def) { return getValue (values, "Loop" + String (prefix) + name, def); } static MemoryBlock createFrom (const StringPairArray& values) { MemoryBlock data; const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue()); if (numLoops > 0) { data.setSize (roundUpSize (sizeof (SMPLChunk) + (size_t) (numLoops - 1) * sizeof (SampleLoop)), true); SMPLChunk* const s = static_cast <SMPLChunk*> (data.getData()); s->manufacturer = getValue (values, "Manufacturer", "0"); s->product = getValue (values, "Product", "0"); s->samplePeriod = getValue (values, "SamplePeriod", "0"); s->midiUnityNote = getValue (values, "MidiUnityNote", "60"); s->midiPitchFraction = getValue (values, "MidiPitchFraction", "0"); s->smpteFormat = getValue (values, "SmpteFormat", "0"); s->smpteOffset = getValue (values, "SmpteOffset", "0"); s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops); s->samplerData = getValue (values, "SamplerData", "0"); for (int i = 0; i < numLoops; ++i) { SampleLoop& loop = s->loops[i]; loop.identifier = getValue (values, i, "Identifier", "0"); loop.type = getValue (values, i, "Type", "0"); loop.start = getValue (values, i, "Start", "0"); loop.end = getValue (values, i, "End", "0"); loop.fraction = getValue (values, i, "Fraction", "0"); loop.playCount = getValue (values, i, "PlayCount", "0"); } } return data; } } JUCE_PACKED; //============================================================================== struct InstChunk { int8 baseNote; int8 detune; int8 gain; int8 lowNote; int8 highNote; int8 lowVelocity; int8 highVelocity; static void setValue (StringPairArray& values, const char* name, int val) { values.set (name, String (val)); } void copyTo (StringPairArray& values) const { setValue (values, "MidiUnityNote", baseNote); setValue (values, "Detune", detune); setValue (values, "Gain", gain); setValue (values, "LowNote", lowNote); setValue (values, "HighNote", highNote); setValue (values, "LowVelocity", lowVelocity); setValue (values, "HighVelocity", highVelocity); } static int8 getValue (const StringPairArray& values, const char* name, const char* def) { return (int8) values.getValue (name, def).getIntValue(); } static MemoryBlock createFrom (const StringPairArray& values) { MemoryBlock data; const StringArray& keys = values.getAllKeys(); if (keys.contains ("LowNote", true) && keys.contains ("HighNote", true)) { data.setSize (8, true); InstChunk* const inst = static_cast <InstChunk*> (data.getData()); inst->baseNote = getValue (values, "MidiUnityNote", "60"); inst->detune = getValue (values, "Detune", "0"); inst->gain = getValue (values, "Gain", "0"); inst->lowNote = getValue (values, "LowNote", "0"); inst->highNote = getValue (values, "HighNote", "127"); inst->lowVelocity = getValue (values, "LowVelocity", "1"); inst->highVelocity = getValue (values, "HighVelocity", "127"); } return data; } } JUCE_PACKED; //============================================================================== struct CueChunk { struct Cue { uint32 identifier; uint32 order; uint32 chunkID; uint32 chunkStart; uint32 blockStart; uint32 offset; } JUCE_PACKED; uint32 numCues; Cue cues[1]; static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val) { values.set ("Cue" + String (prefix) + name, String (ByteOrder::swapIfBigEndian (val))); } void copyTo (StringPairArray& values, const int totalSize) const { values.set ("NumCuePoints", String (ByteOrder::swapIfBigEndian (numCues))); for (int i = 0; i < (int) numCues; ++i) { if ((uint8*) (cues + (i + 1)) > ((uint8*) this) + totalSize) break; setValue (values, i, "Identifier", cues[i].identifier); setValue (values, i, "Order", cues[i].order); setValue (values, i, "ChunkID", cues[i].chunkID); setValue (values, i, "ChunkStart", cues[i].chunkStart); setValue (values, i, "BlockStart", cues[i].blockStart); setValue (values, i, "Offset", cues[i].offset); } } static MemoryBlock createFrom (const StringPairArray& values) { MemoryBlock data; const int numCues = values.getValue ("NumCuePoints", "0").getIntValue(); if (numCues > 0) { data.setSize (roundUpSize (sizeof (CueChunk) + (size_t) (numCues - 1) * sizeof (Cue)), true); CueChunk* const c = static_cast <CueChunk*> (data.getData()); c->numCues = ByteOrder::swapIfBigEndian ((uint32) numCues); const String dataChunkID (chunkName ("data")); int nextOrder = 0; #if JUCE_DEBUG Array<uint32> identifiers; #endif for (int i = 0; i < numCues; ++i) { const String prefix ("Cue" + String (i)); const uint32 identifier = (uint32) values.getValue (prefix + "Identifier", "0").getIntValue(); #if JUCE_DEBUG jassert (! identifiers.contains (identifier)); identifiers.add (identifier); #endif const int order = values.getValue (prefix + "Order", String (nextOrder)).getIntValue(); nextOrder = jmax (nextOrder, order) + 1; Cue& cue = c->cues[i]; cue.identifier = ByteOrder::swapIfBigEndian ((uint32) identifier); cue.order = ByteOrder::swapIfBigEndian ((uint32) order); cue.chunkID = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkID", dataChunkID).getIntValue()); cue.chunkStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkStart", "0").getIntValue()); cue.blockStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "BlockStart", "0").getIntValue()); cue.offset = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Offset", "0").getIntValue()); } } return data; } } JUCE_PACKED; //============================================================================== namespace ListChunk { static int getValue (const StringPairArray& values, const String& name) { return values.getValue (name, "0").getIntValue(); } static int getValue (const StringPairArray& values, const String& prefix, const char* name) { return getValue (values, prefix + name); } static void appendLabelOrNoteChunk (const StringPairArray& values, const String& prefix, const int chunkType, MemoryOutputStream& out) { const String label (values.getValue (prefix + "Text", prefix)); const int labelLength = (int) label.getNumBytesAsUTF8() + 1; const int chunkLength = 4 + labelLength + (labelLength & 1); out.writeInt (chunkType); out.writeInt (chunkLength); out.writeInt (getValue (values, prefix, "Identifier")); out.write (label.toUTF8(), (size_t) labelLength); if ((out.getDataSize() & 1) != 0) out.writeByte (0); } static void appendExtraChunk (const StringPairArray& values, const String& prefix, MemoryOutputStream& out) { const String text (values.getValue (prefix + "Text", prefix)); const int textLength = (int) text.getNumBytesAsUTF8() + 1; // include null terminator int chunkLength = textLength + 20 + (textLength & 1); out.writeInt (chunkName ("ltxt")); out.writeInt (chunkLength); out.writeInt (getValue (values, prefix, "Identifier")); out.writeInt (getValue (values, prefix, "SampleLength")); out.writeInt (getValue (values, prefix, "Purpose")); out.writeShort ((short) getValue (values, prefix, "Country")); out.writeShort ((short) getValue (values, prefix, "Language")); out.writeShort ((short) getValue (values, prefix, "Dialect")); out.writeShort ((short) getValue (values, prefix, "CodePage")); out.write (text.toUTF8(), (size_t) textLength); if ((out.getDataSize() & 1) != 0) out.writeByte (0); } static MemoryBlock createFrom (const StringPairArray& values) { const int numCueLabels = getValue (values, "NumCueLabels"); const int numCueNotes = getValue (values, "NumCueNotes"); const int numCueRegions = getValue (values, "NumCueRegions"); MemoryOutputStream out; if (numCueLabels + numCueNotes + numCueRegions > 0) { out.writeInt (chunkName ("adtl")); for (int i = 0; i < numCueLabels; ++i) appendLabelOrNoteChunk (values, "CueLabel" + String (i), chunkName ("labl"), out); for (int i = 0; i < numCueNotes; ++i) appendLabelOrNoteChunk (values, "CueNote" + String (i), chunkName ("note"), out); for (int i = 0; i < numCueRegions; ++i) appendExtraChunk (values, "CueRegion" + String (i), out); } return out.getMemoryBlock(); } } //============================================================================== struct AcidChunk { /** Reads an acid RIFF chunk from a stream positioned just after the size byte. */ AcidChunk (InputStream& input, size_t length) { zerostruct (*this); input.read (this, (int) jmin (sizeof (*this), length)); } void addToMetadata (StringPairArray& values) const { setBoolFlag (values, WavAudioFormat::acidOneShot, 0x01); setBoolFlag (values, WavAudioFormat::acidRootSet, 0x02); setBoolFlag (values, WavAudioFormat::acidStretch, 0x04); setBoolFlag (values, WavAudioFormat::acidDiskBased, 0x08); setBoolFlag (values, WavAudioFormat::acidizerFlag, 0x10); if (flags & 0x02) // root note set values.set (WavAudioFormat::acidRootNote, String (rootNote)); values.set (WavAudioFormat::acidBeats, String (numBeats)); values.set (WavAudioFormat::acidDenominator, String (meterDenominator)); values.set (WavAudioFormat::acidNumerator, String (meterNumerator)); values.set (WavAudioFormat::acidTempo, String (tempo)); } void setBoolFlag (StringPairArray& values, const char* name, int32 mask) const { values.set (name, (flags & mask) ? "1" : "0"); } int32 flags; int16 rootNote; int16 reserved1; float reserved2; int32 numBeats; int16 meterDenominator; int16 meterNumerator; float tempo; } JUCE_PACKED; //============================================================================== namespace AXMLChunk { static void addToMetadata (StringPairArray& destValues, const String& source) { ScopedPointer<XmlElement> xml (XmlDocument::parse (source)); if (xml != nullptr && xml->hasTagName ("ebucore:ebuCoreMain")) { if (XmlElement* xml2 = xml->getChildByName ("ebucore:coreMetadata")) { if (XmlElement* xml3 = xml2->getChildByName ("ebucore:identifier")) { if (XmlElement* xml4 = xml3->getChildByName ("dc:identifier")) { const String ISRCCode (xml4->getAllSubText().fromFirstOccurrenceOf ("ISRC:", false, true)); if (ISRCCode.isNotEmpty()) destValues.set (WavAudioFormat::ISRC, ISRCCode); } } } } } static MemoryBlock createFrom (const StringPairArray& values) { const String ISRC (values.getValue (WavAudioFormat::ISRC, String::empty)); MemoryOutputStream xml; if (ISRC.isNotEmpty()) { xml << "<ebucore:ebuCoreMain xmlns:dc=\" http://purl.org/dc/elements/1.1/\" " "xmlns:ebucore=\"urn:ebu:metadata-schema:ebuCore_2012\">" "<ebucore:coreMetadata>" "<ebucore:identifier typeLabel=\"GUID\" " "typeDefinition=\"Globally Unique Identifier\" " "formatLabel=\"ISRC\" " "formatDefinition=\"International Standard Recording Code\" " "formatLink=\"http://www.ebu.ch/metadata/cs/ebu_IdentifierTypeCodeCS.xml#3.7\">" "<dc:identifier>ISRC:" << ISRC << "</dc:identifier>" "</ebucore:identifier>" "</ebucore:coreMetadata>" "</ebucore:ebuCoreMain>"; xml.writeRepeatedByte (0, xml.getDataSize()); // ensures even size, null termination and room for future growing } return xml.getMemoryBlock(); } }; //============================================================================== struct ExtensibleWavSubFormat { uint32 data1; uint16 data2; uint16 data3; uint8 data4[8]; bool operator== (const ExtensibleWavSubFormat& other) const noexcept { return memcmp (this, &other, sizeof (*this)) == 0; } bool operator!= (const ExtensibleWavSubFormat& other) const noexcept { return ! operator== (other); } } JUCE_PACKED; static const ExtensibleWavSubFormat pcmFormat = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const ExtensibleWavSubFormat IEEEFloatFormat = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const ExtensibleWavSubFormat ambisonicFormat = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } }; struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise { uint32 riffSizeLow; // low 4 byte size of RF64 block uint32 riffSizeHigh; // high 4 byte size of RF64 block uint32 dataSizeLow; // low 4 byte size of data chunk uint32 dataSizeHigh; // high 4 byte size of data chunk uint32 sampleCountLow; // low 4 byte sample count of fact chunk uint32 sampleCountHigh; // high 4 byte sample count of fact chunk uint32 tableLength; // number of valid entries in array 'table' } JUCE_PACKED; #if JUCE_MSVC #pragma pack (pop) #endif } //============================================================================== class WavAudioFormatReader : public AudioFormatReader { public: WavAudioFormatReader (InputStream* const in) : AudioFormatReader (in, TRANS (wavFormatName)), bwavChunkStart (0), bwavSize (0), dataLength (0), isRF64 (false) { using namespace WavFileHelpers; uint64 len = 0; uint64 end = 0; int cueNoteIndex = 0; int cueLabelIndex = 0; int cueRegionIndex = 0; const int firstChunkType = input->readInt(); if (firstChunkType == chunkName ("RF64")) { input->skipNextBytes (4); // size is -1 for RF64 isRF64 = true; } else if (firstChunkType == chunkName ("RIFF")) { len = (uint64) (uint32) input->readInt(); end = len + (uint64) input->getPosition(); } else { return; } const int64 startOfRIFFChunk = input->getPosition(); if (input->readInt() == chunkName ("WAVE")) { if (isRF64 && input->readInt() == chunkName ("ds64")) { const uint32 length = (uint32) input->readInt(); if (length < 28) return; const int64 chunkEnd = input->getPosition() + length + (length & 1); len = (uint64) input->readInt64(); end = len + (uint64) startOfRIFFChunk; dataLength = input->readInt64(); input->setPosition (chunkEnd); } while ((uint64) input->getPosition() < end && ! input->isExhausted()) { const int chunkType = input->readInt(); uint32 length = (uint32) input->readInt(); const int64 chunkEnd = input->getPosition() + length + (length & 1); if (chunkType == chunkName ("fmt ")) { // read the format chunk const unsigned short format = (unsigned short) input->readShort(); numChannels = (unsigned int) input->readShort(); sampleRate = input->readInt(); const int bytesPerSec = input->readInt(); input->skipNextBytes (2); bitsPerSample = (unsigned int) (int) input->readShort(); if (bitsPerSample > 64) { bytesPerFrame = bytesPerSec / (int) sampleRate; bitsPerSample = 8 * (unsigned int) bytesPerFrame / numChannels; } else { bytesPerFrame = numChannels * bitsPerSample / 8; } if (format == 3) { usesFloatingPointData = true; } else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/) { if (length < 40) // too short { bytesPerFrame = 0; } else { input->skipNextBytes (4); // skip over size and bitsPerSample metadataValues.set ("ChannelMask", String (input->readInt())); ExtensibleWavSubFormat subFormat; subFormat.data1 = (uint32) input->readInt(); subFormat.data2 = (uint16) input->readShort(); subFormat.data3 = (uint16) input->readShort(); input->read (subFormat.data4, sizeof (subFormat.data4)); if (subFormat == IEEEFloatFormat) usesFloatingPointData = true; else if (subFormat != pcmFormat && subFormat != ambisonicFormat) bytesPerFrame = 0; } } else if (format != 1) { bytesPerFrame = 0; } } else if (chunkType == chunkName ("data")) { if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk dataLength = length; dataChunkStart = input->getPosition(); lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0; } else if (chunkType == chunkName ("bext")) { bwavChunkStart = input->getPosition(); bwavSize = length; HeapBlock <BWAVChunk> bwav; bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1); input->read (bwav, (int) length); bwav->copyTo (metadataValues, (int) length); } else if (chunkType == chunkName ("smpl")) { HeapBlock <SMPLChunk> smpl; smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1); input->read (smpl, (int) length); smpl->copyTo (metadataValues, (int) length); } else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which... { HeapBlock <InstChunk> inst; inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1); input->read (inst, (int) length); inst->copyTo (metadataValues); } else if (chunkType == chunkName ("cue ")) { HeapBlock <CueChunk> cue; cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1); input->read (cue, (int) length); cue->copyTo (metadataValues, (int) length); } else if (chunkType == chunkName ("axml")) { MemoryBlock axml; input->readIntoMemoryBlock (axml, (size_t) length); AXMLChunk::addToMetadata (metadataValues, axml.toString()); } else if (chunkType == chunkName ("LIST")) { if (input->readInt() == chunkName ("adtl")) { while (input->getPosition() < chunkEnd) { const int adtlChunkType = input->readInt(); const uint32 adtlLength = (uint32) input->readInt(); const int64 adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1)); if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note")) { String prefix; if (adtlChunkType == chunkName ("labl")) prefix << "CueLabel" << cueLabelIndex++; else if (adtlChunkType == chunkName ("note")) prefix << "CueNote" << cueNoteIndex++; const uint32 identifier = (uint32) input->readInt(); const int stringLength = (int) adtlLength - 4; MemoryBlock textBlock; input->readIntoMemoryBlock (textBlock, stringLength); metadataValues.set (prefix + "Identifier", String (identifier)); metadataValues.set (prefix + "Text", textBlock.toString()); } else if (adtlChunkType == chunkName ("ltxt")) { const String prefix ("CueRegion" + String (cueRegionIndex++)); const uint32 identifier = (uint32) input->readInt(); const uint32 sampleLength = (uint32) input->readInt(); const uint32 purpose = (uint32) input->readInt(); const uint16 country = (uint16) input->readInt(); const uint16 language = (uint16) input->readInt(); const uint16 dialect = (uint16) input->readInt(); const uint16 codePage = (uint16) input->readInt(); const uint32 stringLength = adtlLength - 20; MemoryBlock textBlock; input->readIntoMemoryBlock (textBlock, (int) stringLength); metadataValues.set (prefix + "Identifier", String (identifier)); metadataValues.set (prefix + "SampleLength", String (sampleLength)); metadataValues.set (prefix + "Purpose", String (purpose)); metadataValues.set (prefix + "Country", String (country)); metadataValues.set (prefix + "Language", String (language)); metadataValues.set (prefix + "Dialect", String (dialect)); metadataValues.set (prefix + "CodePage", String (codePage)); metadataValues.set (prefix + "Text", textBlock.toString()); } input->setPosition (adtlChunkEnd); } } } else if (chunkType == chunkName ("acid")) { AcidChunk (*input, length).addToMetadata (metadataValues); } else if (chunkEnd <= input->getPosition()) { break; } input->setPosition (chunkEnd); } } if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex)); if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex)); if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex)); if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV"); } //============================================================================== bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer, int64 startSampleInFile, int numSamples) override { clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer, startSampleInFile, numSamples, lengthInSamples); if (numSamples <= 0) return true; input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame); while (numSamples > 0) { const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3) char tempBuffer [tempBufSize]; const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples); const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame); if (bytesRead < numThisTime * bytesPerFrame) { jassert (bytesRead >= 0); zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead)); } copySampleData (bitsPerSample, usesFloatingPointData, destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); startOffsetInDestBuffer += numThisTime; numSamples -= numThisTime; } return true; } static void copySampleData (unsigned int bitsPerSample, const bool usesFloatingPointData, int* const* destSamples, int startOffsetInDestBuffer, int numDestChannels, const void* sourceData, int numChannels, int numSamples) noexcept { switch (bitsPerSample) { case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break; case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break; case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break; case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break; default: jassertfalse; break; } } int64 bwavChunkStart, bwavSize; int64 dataChunkStart, dataLength; int bytesPerFrame; bool isRF64; private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader) }; //============================================================================== class WavAudioFormatWriter : public AudioFormatWriter { public: WavAudioFormatWriter (OutputStream* const out, const double rate, const unsigned int numChans, const unsigned int bits, const StringPairArray& metadataValues) : AudioFormatWriter (out, TRANS (wavFormatName), rate, numChans, bits), lengthInSamples (0), bytesWritten (0), writeFailed (false) { using namespace WavFileHelpers; if (metadataValues.size() > 0) { // The meta data should have been santised for the WAV format. // If it was originally sourced from an AIFF file the MetaDataSource // key should be removed (or set to "WAV") once this has been done jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF"); bwavChunk = BWAVChunk::createFrom (metadataValues); axmlChunk = AXMLChunk::createFrom (metadataValues); smplChunk = SMPLChunk::createFrom (metadataValues); instChunk = InstChunk::createFrom (metadataValues); cueChunk = CueChunk ::createFrom (metadataValues); listChunk = ListChunk::createFrom (metadataValues); } headerPosition = out->getPosition(); writeHeader(); } ~WavAudioFormatWriter() { if ((bytesWritten & 1) != 0) // pad to an even length { ++bytesWritten; output->writeByte (0); } writeHeader(); } //============================================================================== bool write (const int** data, int numSamples) override { jassert (numSamples >= 0); jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel! if (writeFailed) return false; const size_t bytes = numChannels * (unsigned int) numSamples * bitsPerSample / 8; tempBlock.ensureSize (bytes, false); switch (bitsPerSample) { case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break; case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break; case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break; case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break; default: jassertfalse; break; } if (! output->write (tempBlock.getData(), bytes)) { // failed to write to disk, so let's try writing the header. // If it's just run out of disk space, then if it does manage // to write the header, we'll still have a useable file.. writeHeader(); writeFailed = true; return false; } else { bytesWritten += bytes; lengthInSamples += (uint64) numSamples; return true; } } private: MemoryBlock tempBlock, bwavChunk, axmlChunk, smplChunk, instChunk, cueChunk, listChunk; uint64 lengthInSamples, bytesWritten; int64 headerPosition; bool writeFailed; static int getChannelMask (const int numChannels) noexcept { switch (numChannels) { case 1: return 0; case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT case 6: return 1 + 2 + 4 + 8 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT case 7: return 1 + 2 + 4 + 16 + 32 + 512 + 1024; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT case 8: return 1 + 2 + 4 + 8 + 16 + 32 + 512 + 1024; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT default: break; } return 0; } void writeHeader() { using namespace WavFileHelpers; const bool seekedOk = output->setPosition (headerPosition); (void) seekedOk; // if this fails, you've given it an output stream that can't seek! It needs // to be able to seek back to write the header jassert (seekedOk); const size_t bytesPerFrame = numChannels * bitsPerSample / 8; uint64 audioDataSize = bytesPerFrame * lengthInSamples; const bool isRF64 = (bytesWritten >= 0x100000000LL); const bool isWaveFmtEx = isRF64 || (numChannels > 2); int64 riffChunkSize = (int64) (4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */ + 8 + audioDataSize + (audioDataSize & 1) + chunkSize (bwavChunk) + chunkSize (axmlChunk) + chunkSize (smplChunk) + chunkSize (instChunk) + chunkSize (cueChunk) + chunkSize (listChunk) + (8 + 28)); // (ds64 chunk) riffChunkSize += (riffChunkSize & 1); if (isRF64) writeChunkHeader (chunkName ("RF64"), -1); else writeChunkHeader (chunkName ("RIFF"), (int) riffChunkSize); output->writeInt (chunkName ("WAVE")); if (! isRF64) { #if ! JUCE_WAV_DO_NOT_PAD_HEADER_SIZE /* NB: This junk chunk is added for padding, so that the header is a fixed size regardless of whether it's RF64 or not. That way, we can begin recording a file, and when it's finished, can go back and write either a RIFF or RF64 header, depending on whether more than 2^32 samples were written. The JUCE_WAV_DO_NOT_PAD_HEADER_SIZE macro allows you to disable this feature in case you need to create files for crappy WAV players with bugs that stop them skipping chunks which they don't recognise. But DO NOT USE THIS option unless you really have no choice, because it means that if you write more than 2^32 samples to the file, you'll corrupt it. */ writeChunkHeader (chunkName ("JUNK"), 28 + (isWaveFmtEx? 0 : 24)); output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24)); #endif } else { #if JUCE_WAV_DO_NOT_PAD_HEADER_SIZE // If you disable padding, then you MUST NOT write more than 2^32 samples to a file. jassertfalse; #endif writeChunkHeader (chunkName ("ds64"), 28); // chunk size for uncompressed data (no table) output->writeInt64 (riffChunkSize); output->writeInt64 ((int64) audioDataSize); output->writeRepeatedByte (0, 12); } if (isWaveFmtEx) { writeChunkHeader (chunkName ("fmt "), 40); output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE } else { writeChunkHeader (chunkName ("fmt "), 16); output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/ : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/); } output->writeShort ((short) numChannels); output->writeInt ((int) sampleRate); output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec output->writeShort ((short) bytesPerFrame); // nBlockAlign output->writeShort ((short) bitsPerSample); // wBitsPerSample if (isWaveFmtEx) { output->writeShort (22); // cbSize (size of the extension) output->writeShort ((short) bitsPerSample); // wValidBitsPerSample output->writeInt (getChannelMask ((int) numChannels)); const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat; output->writeInt ((int) subFormat.data1); output->writeShort ((short) subFormat.data2); output->writeShort ((short) subFormat.data3); output->write (subFormat.data4, sizeof (subFormat.data4)); } writeChunk (bwavChunk, chunkName ("bext")); writeChunk (axmlChunk, chunkName ("axml")); writeChunk (smplChunk, chunkName ("smpl")); writeChunk (instChunk, chunkName ("inst"), 7); writeChunk (cueChunk, chunkName ("cue ")); writeChunk (listChunk, chunkName ("LIST")); writeChunkHeader (chunkName ("data"), isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame)); usesFloatingPointData = (bitsPerSample == 32); } static int chunkSize (const MemoryBlock& data) noexcept { return data.getSize() > 0 ? (8 + data.getSize()) : 0; } void writeChunkHeader (int chunkType, int size) const { output->writeInt (chunkType); output->writeInt (size); } void writeChunk (const MemoryBlock& data, int chunkType, int size = 0) const { if (data.getSize() > 0) { writeChunkHeader (chunkType, size != 0 ? size : (int) data.getSize()); *output << data; } } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter) }; //============================================================================== class MemoryMappedWavReader : public MemoryMappedAudioFormatReader { public: MemoryMappedWavReader (const File& file, const WavAudioFormatReader& reader) : MemoryMappedAudioFormatReader (file, reader, reader.dataChunkStart, reader.dataLength, reader.bytesPerFrame) { } bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer, int64 startSampleInFile, int numSamples) override { clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer, startSampleInFile, numSamples, lengthInSamples); if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples))) { jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read. return false; } WavAudioFormatReader::copySampleData (bitsPerSample, usesFloatingPointData, destSamples, startOffsetInDestBuffer, numDestChannels, sampleToPointer (startSampleInFile), (int) numChannels, numSamples); return true; } void readMaxLevels (int64 startSampleInFile, int64 numSamples, float& min0, float& max0, float& min1, float& max1) override { if (numSamples <= 0) { min0 = max0 = min1 = max1 = 0; return; } if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples))) { jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read. min0 = max0 = min1 = max1 = 0; return; } switch (bitsPerSample) { case 8: scanMinAndMax<AudioData::UInt8> (startSampleInFile, numSamples, min0, max0, min1, max1); break; case 16: scanMinAndMax<AudioData::Int16> (startSampleInFile, numSamples, min0, max0, min1, max1); break; case 24: scanMinAndMax<AudioData::Int24> (startSampleInFile, numSamples, min0, max0, min1, max1); break; case 32: if (usesFloatingPointData) scanMinAndMax<AudioData::Float32> (startSampleInFile, numSamples, min0, max0, min1, max1); else scanMinAndMax<AudioData::Int32> (startSampleInFile, numSamples, min0, max0, min1, max1); break; default: jassertfalse; break; } } private: template <typename SampleType> void scanMinAndMax (int64 startSampleInFile, int64 numSamples, float& min0, float& max0, float& min1, float& max1) const noexcept { scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (0, startSampleInFile, numSamples, min0, max0); if (numChannels > 1) scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (1, startSampleInFile, numSamples, min1, max1); else min1 = max1 = 0; } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedWavReader) }; //============================================================================== WavAudioFormat::WavAudioFormat() : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions)) { } WavAudioFormat::~WavAudioFormat() { } Array<int> WavAudioFormat::getPossibleSampleRates() { const int rates[] = { 8000, 11025, 12000, 16000, 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 352800, 384000 }; return Array<int> (rates, numElementsInArray (rates)); } Array<int> WavAudioFormat::getPossibleBitDepths() { const int depths[] = { 8, 16, 24, 32 }; return Array<int> (depths, numElementsInArray (depths)); } bool WavAudioFormat::canDoStereo() { return true; } bool WavAudioFormat::canDoMono() { return true; } AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails) { ScopedPointer<WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream)); if (r->sampleRate > 0 && r->numChannels > 0) return r.release(); if (! deleteStreamIfOpeningFails) r->input = nullptr; return nullptr; } MemoryMappedAudioFormatReader* WavAudioFormat::createMemoryMappedReader (const File& file) { if (FileInputStream* fin = file.createInputStream()) { WavAudioFormatReader reader (fin); if (reader.lengthInSamples > 0) return new MemoryMappedWavReader (file, reader); } return nullptr; } AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate, unsigned int numChannels, int bitsPerSample, const StringPairArray& metadataValues, int /*qualityOptionIndex*/) { if (getPossibleBitDepths().contains (bitsPerSample)) return new WavAudioFormatWriter (out, sampleRate, (unsigned int) numChannels, (unsigned int) bitsPerSample, metadataValues); return nullptr; } namespace WavFileHelpers { static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata) { TemporaryFile tempFile (file); WavAudioFormat wav; ScopedPointer<AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true)); if (reader != nullptr) { ScopedPointer<OutputStream> outStream (tempFile.getFile().createOutputStream()); if (outStream != nullptr) { ScopedPointer<AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate, reader->numChannels, (int) reader->bitsPerSample, metadata, 0)); if (writer != nullptr) { outStream.release(); bool ok = writer->writeFromAudioReader (*reader, 0, -1); writer = nullptr; reader = nullptr; return ok && tempFile.overwriteTargetFileWithTemporary(); } } } return false; } } bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata) { using namespace WavFileHelpers; ScopedPointer<WavAudioFormatReader> reader (static_cast<WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true))); if (reader != nullptr) { const int64 bwavPos = reader->bwavChunkStart; const int64 bwavSize = reader->bwavSize; reader = nullptr; if (bwavSize > 0) { MemoryBlock chunk (BWAVChunk::createFrom (newMetadata)); if (chunk.getSize() <= (size_t) bwavSize) { // the new one will fit in the space available, so write it directly.. const int64 oldSize = wavFile.getSize(); { FileOutputStream out (wavFile); if (! out.failedToOpen()) { out.setPosition (bwavPos); out << chunk; out.setPosition (oldSize); } } jassert (wavFile.getSize() == oldSize); return true; } } } return slowCopyWavFileWithNewMetadata (wavFile, newMetadata); }
[ "kaspar.emanuel@gmail.com" ]
kaspar.emanuel@gmail.com
72c13ecf97ca803411f7e06c2775ba982b159f28
c8ec5672fb971f146ad9819aa171d366394051c9
/AGPLightDemonstration-master/ASSIMPProject/ASSIMPProject/Mesh.h
6a62f2213d5ff75b905653054b4f8eceaba1dc14
[]
no_license
NickJ25/TempGroup
68b16c0d51688807041ca9ddd32fd07b71bd7188
e9872efd1da35c872d84beb9a34eb93be49497cf
refs/heads/master
2020-04-08T09:04:48.432234
2018-12-02T15:33:23
2018-12-02T15:33:23
159,206,909
2
0
null
null
null
null
UTF-8
C++
false
false
10,076
h
#pragma once #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "Shader.h" using namespace std; struct Vertex { // Position glm::vec3 Position; // Normal glm::vec3 Normal; // TexCoords glm::vec2 TexCoords; //normal mapping variables glm::vec3 Tangent; glm::vec3 BiTangent; }; struct Texture { GLuint id; string type; aiString path; }; class Mesh { public: /* Mesh Data */ vector<Vertex> vertices; vector<GLuint> indices; vector<Texture> textures; /* Functions */ // Constructor Mesh( vector<Vertex> vertices, vector<GLuint> indices, vector<Texture> textures ) { this->vertices = vertices; this->indices = indices; this->textures = textures; // Now that we have all the required data, set the vertex buffers and its attribute pointers. this->setupMesh(); this->setupVMesh(); this->setupDMesh(); } // Render the mesh void Draw( Shader shader ) { // Bind appropriate textures GLuint diffuseNr = 1; GLuint specularNr = 1; GLuint normalNr = 1; GLuint occlusionNr = 1; for( GLuint i = 0; i < this->textures.size( ); i++ ) { glActiveTexture( GL_TEXTURE0 + i ); // Active proper texture unit before binding // Retrieve texture number (the N in diffuse_textureN) stringstream ss; string number; string name = this->textures[i].type; if( name == "texture_diffuse" ) { ss << diffuseNr++; // Transfer GLuint to stream } else if( name == "texture_specular" ) { ss << specularNr++; // Transfer GLuint to stream } else if (name == "texture_normal") { cout << "called normal map" << endl; ss << normalNr++; // Transfer GLuint to stream } number = ss.str( ); // Now set the sampler to the correct texture unit glUniform1i( glGetUniformLocation( shader.Program, ( name + number ).c_str( ) ), i ); // And finally bind the texture glBindTexture( GL_TEXTURE_2D, this->textures[i].id ); } // Also set each mesh's shininess property to a default value (if you want you could extend this to another mesh property and possibly change this value) glUniform1f( glGetUniformLocation( shader.Program, "material.shininess" ), 16.0f ); // Draw mesh glBindVertexArray( this->VAO ); glDrawElements( GL_TRIANGLES, this->indices.size( ), GL_UNSIGNED_INT, 0 ); glBindVertexArray( 0 ); // Always good practice to set everything back to defaults once configured. for ( GLuint i = 0; i < this->textures.size( ); i++ ) { glActiveTexture( GL_TEXTURE0 + i ); glBindTexture( GL_TEXTURE_2D, 0 ); } } void DrawVMesh(Shader shader) { // Draw mesh glBindVertexArray(this->VVAO); glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Always good practice to set everything back to defaults once configured. for (GLuint i = 0; i < this->textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } } void DrawTextured(Shader shader, GLuint tex1, GLuint tex2) { glActiveTexture(GL_TEXTURE0); // Active proper texture unit before binding glUniform1i(glGetUniformLocation(shader.Program, "textureUnit0"), 0); glBindTexture(GL_TEXTURE_2D, tex2); glActiveTexture(GL_TEXTURE1); // Active proper texture unit before binding glUniform1i(glGetUniformLocation(shader.Program, "textureUnit1"), 1); glBindTexture(GL_TEXTURE_2D, tex1); // Draw mesh glBindVertexArray(this->VAO); glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Always good practice to set everything back to defaults once configured. for (GLuint i = 0; i < this->textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } } void DrawDMesh(Shader shader) { // Bind appropriate textures GLuint diffuseNr = 1; GLuint specularNr = 1; GLuint normalNr = 1; for (GLuint i = 0; i < this->textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); // Active proper texture unit before binding // Retrieve texture number (the N in diffuse_textureN) stringstream ss; string number; string name = this->textures[i].type; if (name == "texture_diffuse") { cout << "called diffuse map" << endl; ss << diffuseNr++; // Transfer GLuint to stream } else if (name == "texture_specular") { cout << "called specular map" << endl; ss << specularNr++; // Transfer GLuint to stream } else if (name == "texture_normal") { cout << "called normal map" << endl; ss << normalNr++; // Transfer GLuint to stream } number = ss.str(); // Now set the sampler to the correct texture unit glUniform1i(glGetUniformLocation(shader.Program, (name + number).c_str()), i); // And finally bind the texture glBindTexture(GL_TEXTURE_2D, this->textures[i].id); } // Draw mesh glBindVertexArray(this->DVAO); glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Always good practice to set everything back to defaults once configured. for (GLuint i = 0; i < this->textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } } private: /* Render data */ GLuint VAO, VBO, EBO; GLuint VVAO, VVBO, VEBO; GLuint DVAO, DVBO, DEBO; void setupVMesh() { // Create buffers/arrays glGenVertexArrays(1, &this->VVAO); glGenBuffers(1, &this->VVBO); glGenBuffers(1, &this->VEBO); glBindVertexArray(this->VVAO); // Load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, this->VVBO); glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(Vertex), &this->vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->VEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0], GL_STATIC_DRAW); // Set the vertex attribute pointers // Vertex Positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)0); glBindVertexArray(0); } /* Functions */ // Initializes all the buffer objects/arrays void setupMesh( ) { // Create buffers/arrays glGenVertexArrays( 1, &this->VAO ); glGenBuffers( 1, &this->VBO ); glGenBuffers( 1, &this->EBO ); glBindVertexArray( this->VAO ); // Load data into vertex buffers glBindBuffer( GL_ARRAY_BUFFER, this->VBO ); // A great thing about structs is that their memory layout is sequential for all its items. // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which // again translates to 3/2 floats which translates to a byte array. glBufferData( GL_ARRAY_BUFFER, this->vertices.size( ) * sizeof( Vertex ), &this->vertices[0], GL_STATIC_DRAW ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, this->EBO ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, this->indices.size( ) * sizeof( GLuint ), &this->indices[0], GL_STATIC_DRAW ); // Set the vertex attribute pointers // Vertex Positions glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), ( GLvoid * )0 ); // Vertex Normals glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), ( GLvoid * )offsetof( Vertex, Normal ) ); // Vertex Texture Coords glEnableVertexAttribArray(2); glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, sizeof( Vertex ), ( GLvoid * )offsetof( Vertex, TexCoords ) ); // vertex tangents glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, Tangent))); // vertex bitangents glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, BiTangent))); glBindVertexArray( 0 ); } void setupDMesh() { // Create buffers/arrays glGenVertexArrays(1, &this->DVAO); glGenBuffers(1, &this->DVBO); glGenBuffers(1, &this->DEBO); glBindVertexArray(this->DVAO); // Load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, this->DVBO); glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(Vertex), &this->vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->DEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0], GL_STATIC_DRAW); // Set the vertex attribute pointers // Vertex Positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)0); // Vertex Texture Coords glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)offsetof(Vertex, Normal)); // Vertex Normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)offsetof(Vertex, TexCoords)); // vertex tangents glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, Tangent))); // vertex bitangents glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, BiTangent))); glBindVertexArray(0); } };
[ "chrislochhead123@outlook.com" ]
chrislochhead123@outlook.com
135e01ea34d4dfc6897e6d689e5ff78f4ff5f1ad
001bff3a9254779345f2fc22a02786decafe4678
/11/debian-10/postgresql-repmgr-11.11.0-15-linux-amd64-debian-10/files/postgresql/include/geos/geom/FixedSizeCoordinateSequence.h
20e661d1d68f635829235326cc2be141e3c6c5d7
[ "GPL-2.0-only", "MIT", "Zlib", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
radondb-pg/radondb-postgresql-kubernetes
33fe153b2b2148486e9ae3020c6b9664bc603e39
e7a308cb4fd4c31e76b80d4aaabc9463a912c8fd
refs/heads/main
2023-07-11T16:10:30.562439
2021-08-19T11:42:11
2021-08-19T11:42:11
370,936,467
0
0
Apache-2.0
2021-05-26T06:56:52
2021-05-26T06:56:51
null
UTF-8
C++
false
false
3,881
h
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2019 Daniel Baston * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #ifndef GEOS_GEOM_FIXEDSIZECOORDINATESEQUENCE_H #define GEOS_GEOM_FIXEDSIZECOORDINATESEQUENCE_H #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateFilter.h> #include <geos/geom/CoordinateSequence.h> #include <geos/util.h> #include <algorithm> #include <array> #include <memory> #include <sstream> #include <vector> namespace geos { namespace geom { template<size_t N> class FixedSizeCoordinateSequence : public CoordinateSequence { public: explicit FixedSizeCoordinateSequence(size_t dimension_in = 0) : dimension(dimension_in) {} std::unique_ptr<CoordinateSequence> clone() const final override { auto seq = detail::make_unique<FixedSizeCoordinateSequence<N>>(dimension); seq->m_data = m_data; return std::move(seq); // move needed for gcc 4.8 } const Coordinate& getAt(size_t i) const final override { return m_data[i]; } void getAt(size_t i, Coordinate& c) const final override { c = m_data[i]; } size_t getSize() const final override { return N; } bool isEmpty() const final override { return N == 0; } void setAt(const Coordinate & c, size_t pos) final override { m_data[pos] = c; } void setOrdinate(size_t index, size_t ordinateIndex, double value) final override { switch(ordinateIndex) { case CoordinateSequence::X: m_data[index].x = value; break; case CoordinateSequence::Y: m_data[index].y = value; break; case CoordinateSequence::Z: m_data[index].z = value; break; default: { std::stringstream ss; ss << "Unknown ordinate index " << index; throw geos::util::IllegalArgumentException(ss.str()); break; } } } size_t getDimension() const final override { if(dimension != 0) { return dimension; } if(isEmpty()) { return 3; } if(std::isnan(m_data[0].z)) { dimension = 2; } else { dimension = 3; } return dimension; } void toVector(std::vector<Coordinate> & out) const final override { out.insert(out.end(), m_data.begin(), m_data.end()); } void setPoints(const std::vector<Coordinate> & v) final override { std::copy(v.begin(), v.end(), m_data.begin()); } void apply_ro(CoordinateFilter* filter) const final override { std::for_each(m_data.begin(), m_data.end(), [&filter](const Coordinate & c) { filter->filter_ro(&c); }); } void apply_rw(const CoordinateFilter* filter) final override { std::for_each(m_data.begin(), m_data.end(), [&filter](Coordinate &c) { filter->filter_rw(&c); }); dimension = 0; // re-check (see http://trac.osgeo.org/geos/ticket/435) } private: std::array<Coordinate, N> m_data; mutable std::size_t dimension; }; } } #endif
[ "hualongzhong@yunify.com" ]
hualongzhong@yunify.com
21d51963cc4b4f3707e4d4168f1b2aeedae67f13
d3a866847e7feeb4d1893bd7b3794af6bcbf68ed
/Completed/195 - Anagram/195 - Anagram.cpp
803629860b071311db90583334158de0afb3406e
[]
no_license
sodrulamin/UVA
b1c7e88ea34e723a6ab9ec7170959e866c5ec729
d2a6e09ba4d6aabbb06b1080ec41466e26dce4dd
refs/heads/master
2020-07-18T08:47:59.317865
2019-10-16T08:22:40
2019-10-16T08:22:40
206,215,956
0
0
null
null
null
null
UTF-8
C++
false
false
1,991
cpp
#include <iostream> #include <string> #include <algorithm> #include <set> #include <vector> #include <stack> using namespace std; vector<string> resultSet; char charList[] = { 'A','a', 'B','b', 'C','c', 'D','d', 'E','e', 'F','f', 'G','g', 'H','h', 'I','i', 'J','j', 'K','k', 'L','l', 'M','m', 'N','n', 'O','o', 'P','p', 'Q','q', 'R','r', 'S','s', 'T','t', 'U','u', 'V','v', 'W','w', 'X','x', 'Y','y', 'Z','z' }; void produceAnanagrams(string str) { vector<int> characters; for(int i=0;i<str.length();i++) { int n; if(isupper(str[i])) { n = (str[i] - 'A') * 2; } else { n = (str[i] - 'a') * 2 + 1; } characters.push_back(n); } //cout << "Size: " << characters.size() << endl; sort(characters.begin(), characters.begin() + characters.size()); set<string> permutedList; do { string s = ""; for(int i=0;i<characters.size();i++) //cout << characters[i]; { s += charList[characters[i]]; } if(permutedList.find(s) == permutedList.end()){ permutedList.insert(s); cout << s << endl; } } while ( std::next_permutation(characters.begin(),characters.begin() + characters.size()) ); //stack<string> reverseSet; // for(const string& x: permutedList) // { // cout << x << endl; // //reverseSet.push(x); // } // while(!reverseSet.empty()) // { // //cout << reverseSet.top() << endl; // resultSet.push_back(reverseSet.top()); // reverseSet.pop(); // } } int main() { int t; cin >> t; while(t > 0) { string str; cin >> str; produceAnanagrams(str); t--; } // for(int i=0;i<resultSet.size();i++) // { // cout << resultSet[i] << endl; // } return 0; }
[ "shaon@revesoft.com" ]
shaon@revesoft.com
1b09e455f5723caaff3986d4fd670af5caacd4bb
4e8e56d7d7fdc3bc7eedb03d8a466b5e07ed92d8
/src/qt/optionsdialog.cpp
7cf4a04662487cd0fdada04a82d059610fa9472b
[ "MIT" ]
permissive
fairycoin/fairycoin
4f4a8e7bb51a0f95ce9109ee0dc3aa38db93db22
0dcd0b89431b55bb973c24acdc1b7a2c172a0758
refs/heads/master
2016-08-05T00:19:05.040781
2014-05-20T06:16:43
2014-05-20T06:16:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,670
cpp
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinamountfield.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include "qvalidatedlineedit.h" #include "qvaluecombobox.h" #include <QCheckBox> #include <QDir> #include <QIntValidator> #include <QLabel> #include <QLineEdit> #include <QLocale> #include <QMessageBox> #include <QPushButton> #include <QRegExp> #include <QRegExpValidator> #include <QTabWidget> #include <QWidget> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(0, 65535, this)); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_WS_MAC ui->tabWindow->setVisible(false); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); connect(ui->lang, SIGNAL(activated(int)), this, SLOT(showRestartWarning_Lang())); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable save buttons when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableSaveButtons())); /* disable save buttons when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableSaveButtons())); /* disable/enable save buttons when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(bool)), this, SLOT(setSaveButtonState(bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); /* Window */ #ifndef Q_WS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); } void OptionsDialog::enableSaveButtons() { // prevent enabling of the save buttons when data modified, if there is an invalid proxy address present if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); ui->applyButton->setEnabled(false); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Fairycoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Fairycoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { // Update transactionFee with the current unit ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(object == ui->proxyIp && event->type() == QEvent::FocusOut) { // Check proxyIP for a valid IPv4/IPv6 address CService addr; if(!LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)) { ui->proxyIp->setValid(false); fProxyIpValid = false; ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); emit proxyIpValid(false); } else { fProxyIpValid = true; ui->statusLabel->clear(); emit proxyIpValid(true); } } return QDialog::eventFilter(object, event); }
[ "osiris2099@drivehq.com" ]
osiris2099@drivehq.com
d5427077439ce97fea3a246705dcf17086076eed
9de29021638032dfc11056cecb250c34e92b2353
/Type 2/String Processing/Decode the tap Uva 10878.cpp
62ed6ce3c4ccabafa3a582e46a81e478918d9460
[]
no_license
mhRumi/Project-150-2017831023
18c5096c8125eb7eea9bfeacac690c19ebba0762
9f5b5cadcc1c02bf1d38515eb18de40fe0a5513d
refs/heads/master
2020-04-17T14:42:08.326923
2019-01-20T13:55:06
2019-01-20T13:55:06
166,667,718
6
0
null
null
null
null
UTF-8
C++
false
false
359
cpp
#include<bits/stdc++.h> using namespace std; int main() { char s[12]; gets(s); int box[]={0,0,64,32,16,8,0,4,2,1,0}; while(gets(s)){ if(s[0]=='_') break; int sum=0; for(int i=0;i<11;i++){ if(s[i]=='o') sum=sum+box[i]; } cout<<char(sum); } return 0; }
[ "mh913350@gmail.com" ]
mh913350@gmail.com
5ecb820729ee402ae3344a751ead381327a16f07
0b279426020e3e4500b2391a730e24528a902283
/00-string/inc/string.hpp
fd79e015faf66f8e3b911aa91eb80cb1c4cc56c4
[ "MIT" ]
permissive
YuehChuan/Cpp-Weekly
76b5f6ac17ead513082e4efe70856715e69a032d
a396f6508857ca1077ab7513a162724b6489dee2
refs/heads/master
2022-04-21T00:08:13.951977
2020-02-27T15:16:36
2020-02-27T15:16:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,398
hpp
/** @file string.hpp * * @mainpage string.hpp * * @brief build your own string like std::string from scratch * * @author Gapry * * @date 2020 * * @copyright MIT License */ #ifndef __STRING_HPP__ #define __STRING_HPP__ #include <cstddef> class beta::string : public beta::noncopyable { using size_type = std::size_t; public: /** * @brief constructs a string */ string(const char* = ""); /** * @brief copy constructor */ string(const string&); /** * @brief assigns values to the string */ string& operator=(const string&); /** * @brief assigns values to the string */ string& operator=(const char*); /** * @brief destroys the string, deallocating internal storage if used */ ~string(); /** * @brief returns a non-modifiable standard C character array version of the string */ operator const char*() const; /** * @brief concatenates two strings */ string& operator+=(const string&); /** * @brief concatenates a string and a char */ string& operator+=(const char*); /** * @brief returns the number of characters */ size_type length() const; /** * @brief returns the number of characters that can be held in currently allocated storage */ size_type capacity() const; /** * @brief checks whether the string is empty */ bool empty(); }; #endif
[ "gapry@protonmail.com" ]
gapry@protonmail.com
688ac72ffa654a556db6864ee847887ae98946bf
102459cdb53edaa01c10f5bb7d3878efa4b0885a
/cipher_tools.hpp
550a40cdde81d6204f9c2673ef4d51a5ed6ac74c
[]
no_license
amaabalo/Cipher-Tools
7138cca36afd749a0920be57e0ba0543ec14c799
dcfafe3cdbb2da2e3738071c10692346bffd85e5
refs/heads/master
2021-06-25T05:37:07.689845
2017-09-10T01:54:48
2017-09-10T01:54:48
102,996,032
0
0
null
null
null
null
UTF-8
C++
false
false
822
hpp
/* cipher_tools.hpp */ #include <unordered_map> #include <vector> #include <utility> const float englishCharacterFrequencies[26] ={0.080, 0.015, 0.030, 0.040, 0.130, 0.020, 0.015, 0.060, 0.065, 0.005, 0.005, 0.035, 0.030, 0.070, 0.080,// 0.020, 0.002, 0.065, 0.060, 0.090, 0.030, 0.010, 0.015, 0.005, 0.020, 0.002}; int frequencyAnalysis(float *frequency_map, char *file_name); void computeCorrelations(float *frequency_map, std::vector<std::pair<char, float>> &correlation_map); bool getOption(std::string &option); void displayPartialDecryption(char *file_name, int num_letters, int shift); void tryShift(std::vector<std::pair<char, float>> &correlation_map, char *file_name, int num_letters); bool isALetter(char c); void replaceLetters(int argc, char *argv[]); void shift(char *file_name, int shift);
[ "amiabalo@Mawutors-MacBook-Pro.local" ]
amiabalo@Mawutors-MacBook-Pro.local
ae0e7a1cad975c31088c37c4fcd80b04d4a469be
370881312084d8d2ce0f9c8dce147b81a3a9a923
/Game_Code/Code/CryEngine/CryAction/FlowSystem/Nodes/PlaySequenceNode.cpp
6640b255f9ee1ac779fa097841d0a5b05f4bfc79
[]
no_license
ShadowShell/QuestDrake
3030c396cd691be96819eec0f0f376eb8c64ac89
9be472a977882df97612efb9c18404a5d43e76f5
refs/heads/master
2016-09-05T20:23:14.165400
2015-03-06T14:17:22
2015-03-06T14:17:22
31,463,818
3
2
null
2015-02-28T18:26:22
2015-02-28T13:45:52
C++
UTF-8
C++
false
false
14,669
cpp
#include "StdAfx.h" #include <ISystem.h> #include <ICryAnimation.h> #include <IMovieSystem.h> #include <IViewSystem.h> #include "CryActionCVars.h" #include "FlowBaseNode.h" class CPlaySequence_Node : public CFlowBaseNode<eNCT_Instanced>, public IMovieListener { enum INPUTS { EIP_Sequence, EIP_Start, EIP_Pause, EIP_Stop, EIP_Precache, EIP_BreakOnStop, EIP_BlendPosSpeed, EIP_BlendRotSpeed, EIP_PerformBlendOut, EIP_StartTime, EIP_PlaySpeed, EIP_JumpToTime, EIP_TriggerJumpToTime, EIP_SequenceId, // deprecated EIP_TriggerJumpToEnd, }; enum OUTPUTS { EOP_Started = 0, EOP_Done, EOP_Finished, EOP_Aborted, EOP_SequenceTime, EOP_CurrentSpeed, }; typedef enum { PS_Stopped, PS_Playing, PS_Last } EPlayingState; _smart_ptr<IAnimSequence> m_pSequence; SActivationInfo m_actInfo; EPlayingState m_playingState; float m_currentTime; float m_currentSpeed; public: CPlaySequence_Node( SActivationInfo * pActInfo ) { m_pSequence = 0; m_actInfo = *pActInfo; m_playingState = PS_Stopped; m_currentSpeed = 0.0f; m_currentTime = 0.0f; }; virtual void GetMemoryUsage(ICrySizer * s) const { s->Add(*this); } ~CPlaySequence_Node() { if (m_pSequence) { IMovieSystem *pMovieSystem = gEnv->pMovieSystem; if (pMovieSystem) { pMovieSystem->RemoveMovieListener(m_pSequence, this); } } }; IFlowNodePtr Clone( SActivationInfo * pActInfo ) { return new CPlaySequence_Node(pActInfo); } virtual void Serialize(SActivationInfo *pActInfo, TSerialize ser) { ser.BeginGroup("Local"); if (ser.IsWriting()) { ser.EnumValue("m_playingState", m_playingState, PS_Stopped, PS_Last); ser.Value("curTime", m_currentTime); ser.Value("m_playSpeed", m_currentSpeed); bool bPaused = m_pSequence ? m_pSequence->IsPaused() : false; ser.Value("m_paused", bPaused); } else { EPlayingState playingState; { // for backward compatibility - TODO: remove bool playing = false; ser.Value("m_bPlaying", playing); playingState = playing ? PS_Playing : PS_Stopped; /// end remove } ser.EnumValue("m_playingState", playingState, PS_Stopped, PS_Last); ser.Value("curTime", m_currentTime); ser.Value("m_playSpeed", m_currentSpeed); bool bPaused; ser.Value("m_paused", bPaused); if (playingState == PS_Playing) { // restart sequence, possibly at the last frame StartSequence(pActInfo, m_currentTime, false); if (m_pSequence && bPaused) { m_pSequence->Pause(); } } else { // this unregisters only! because all sequences have been stopped already // by MovieSystem's Reset in GameSerialize.cpp StopSequence(pActInfo, true); } } ser.EndGroup(); } virtual void GetConfiguration( SFlowNodeConfig &config ) { static const SInputPortConfig in_config[] = { InputPortConfig<string>( "seq_Sequence_File",_HELP("Name of the Sequence"), _HELP("Sequence") ), InputPortConfig_Void( "Trigger",_HELP("Starts the sequence"), _HELP("StartTrigger") ), InputPortConfig_Void( "Pause", _HELP("Pauses the sequence"), _HELP("PauseTrigger") ), InputPortConfig_Void( "Stop", _HELP("Stops the sequence"), _HELP("StopTrigger") ), InputPortConfig_Void( "Precache",_HELP("Precache keys that start in the first seconds of the animation. (Solves streaming issues)"), _HELP("PrecacheTrigger") ), InputPortConfig<bool>( "BreakOnStop", false, _HELP("If set to 'true', stopping the sequence doesn't jump to end.") ), InputPortConfig<float>("BlendPosSpeed", 0.0f, _HELP("Speed at which position gets blended into animation.") ), InputPortConfig<float>("BlendRotSpeed", 0.0f, _HELP("Speed at which rotation gets blended into animation.") ), InputPortConfig<bool>( "PerformBlendOut", false, _HELP("If set to 'true' the cutscene will blend out after it has finished to the new view (please reposition player when 'Started' happens).") ), InputPortConfig<float>("StartTime", 0.0f, _HELP("Start time from which the sequence'll begin playing.") ), InputPortConfig<float>("PlaySpeed", 1.0f, _HELP("Speed that this sequence plays at. 1.0 = normal speed, 0.5 = half speed, 2.0 = double speed.") ), InputPortConfig<float>("JumpToTime", 0.0f, _HELP("Jump to a specific time in the sequence.") ), InputPortConfig_Void("TriggerJumpToTime", _HELP("Trigger the animation to jump to 'JumpToTime' seconds.") ), InputPortConfig<int>("seqid_SequenceId", 0, _HELP("ID of the Sequence"), _HELP("SequenceId (DEPRECATED)") ), InputPortConfig_Void("TriggerJumpToEnd", _HELP("Trigger the animation to jump to the end of the sequence.") ), {0} }; static const SOutputPortConfig out_config[] = { OutputPortConfig_Void("Started", _HELP("Triggered when sequence is started") ), OutputPortConfig_Void("Done", _HELP("Triggered when sequence is stopped [either via StopTrigger or aborted via Code]"), _HELP("Done") ), OutputPortConfig_Void("Finished", _HELP("Triggered when sequence finished normally") ), OutputPortConfig_Void("Aborted", _HELP("Triggered when sequence is aborted (Stopped and BreakOnStop true or via Code)") ), OutputPortConfig_Void("SequenceTime", _HELP("Current time of the sequence") ), OutputPortConfig_Void("CurrentSpeed", _HELP("Speed at which the sequence is being played") ), {0} }; config.sDescription = _HELP( "Plays a Trackview Sequence" ); config.pInputPorts = in_config; config.pOutputPorts = out_config; config.SetCategory(EFLN_APPROVED); } virtual void ProcessEvent( EFlowEvent event,SActivationInfo *pActInfo ) { switch (event) { case eFE_Update: { UpdatePermanentOutputs(); if (!gEnv->pMovieSystem || !m_pSequence) pActInfo->pGraph->SetRegularlyUpdated(pActInfo->myID, false); } break; case eFE_Activate: { if (IsPortActive(pActInfo, EIP_Stop)) { bool bWasPlaying = m_playingState == PS_Playing; const bool bLeaveTime = GetPortBool(pActInfo, EIP_BreakOnStop); StopSequence(pActInfo, false, true, bLeaveTime); // we trigger manually, as we unregister before the callback happens if (bWasPlaying) { ActivateOutput(pActInfo, EOP_Done, true); // signal we're done ActivateOutput(pActInfo, EOP_Aborted, true); // signal it's been aborted NotifyEntities(); } } if (IsPortActive(pActInfo, EIP_Start)) { StartSequence(pActInfo, GetPortFloat(pActInfo, EIP_StartTime)); } if (IsPortActive(pActInfo, EIP_Pause)) { PauseSequence(pActInfo); } if (IsPortActive(pActInfo, EIP_Precache)) { PrecacheSequence(pActInfo, GetPortFloat(pActInfo, EIP_StartTime)); } if(IsPortActive(pActInfo, EIP_TriggerJumpToTime)) { if(gEnv->pMovieSystem && m_pSequence) { float time = GetPortFloat(pActInfo, EIP_JumpToTime); time = clamp_tpl(time, m_pSequence->GetTimeRange().start, m_pSequence->GetTimeRange().end); gEnv->pMovieSystem->SetPlayingTime(m_pSequence, time); } } else if(IsPortActive(pActInfo, EIP_TriggerJumpToEnd)) { if(gEnv->pMovieSystem && m_pSequence) { float endTime = m_pSequence->GetTimeRange().end; gEnv->pMovieSystem->SetPlayingTime(m_pSequence, endTime); } } if(IsPortActive(pActInfo, EIP_PlaySpeed)) { const float playSpeed = GetPortFloat(pActInfo, EIP_PlaySpeed); if(gEnv->pMovieSystem) { gEnv->pMovieSystem->SetPlayingSpeed(m_pSequence, playSpeed); } } break; } case eFE_Initialize: { StopSequence(pActInfo); } break; }; }; virtual void OnMovieEvent(IMovieListener::EMovieEvent event, IAnimSequence* pSequence) { if (pSequence && pSequence == m_pSequence) { if (event == IMovieListener::eMovieEvent_Started) { m_playingState = PS_Playing; } else if (event == IMovieListener::eMovieEvent_Stopped) { ActivateOutput(&m_actInfo, EOP_Done, true); ActivateOutput(&m_actInfo, EOP_Finished, true); m_playingState = PS_Stopped; NotifyEntities(); SequenceStopped(); } else if (event == IMovieListener::eMovieEvent_Aborted) { SequenceAborted(); } else if (event == IMovieListener::eMovieEvent_Updated) { m_currentTime = gEnv->pMovieSystem->GetPlayingTime(pSequence); m_currentSpeed = gEnv->pMovieSystem->GetPlayingSpeed(pSequence); } } } protected: void SequenceAborted() { ActivateOutput(&m_actInfo, EOP_Done, true); ActivateOutput(&m_actInfo, EOP_Aborted, true); m_playingState = PS_Stopped; NotifyEntities(); SequenceStopped(); } void SequenceStopped() { UpdatePermanentOutputs(); if (gEnv->pMovieSystem && m_pSequence) { gEnv->pMovieSystem->RemoveMovieListener(m_pSequence, this); } m_pSequence = 0; m_actInfo.pGraph->SetRegularlyUpdated(m_actInfo.myID, false); } void PrecacheSequence(SActivationInfo* pActInfo, float startTime = 0.0f) { IMovieSystem* movieSys = gEnv->pMovieSystem; if (movieSys) { IAnimSequence* pSequence = movieSys->FindSequence(GetPortString(pActInfo, EIP_Sequence)); if (pSequence == NULL) pSequence = movieSys->FindSequenceById((uint32)GetPortInt(pActInfo, EIP_SequenceId)); if (pSequence) { pSequence->PrecacheData(startTime); } } } void StopSequence(SActivationInfo* pActInfo, bool bUnRegisterOnly=false, bool bAbort=false, bool bLeaveTime=false) { IMovieSystem *const pMovieSystem = gEnv->pMovieSystem; if (pMovieSystem && m_pSequence) { // we remove first to NOT get notified! pMovieSystem->RemoveMovieListener(m_pSequence, this); if (!bUnRegisterOnly && pMovieSystem->IsPlaying(m_pSequence)) { if (bAbort) // stops sequence and leaves it at current position { pMovieSystem->AbortSequence(m_pSequence, bLeaveTime); } else { pMovieSystem->StopSequence(m_pSequence); } } SequenceStopped(); } } void UpdatePermanentOutputs() { if(gEnv->pMovieSystem && m_pSequence) { const float currentTime = gEnv->pMovieSystem->GetPlayingTime(m_pSequence); const float currentSpeed = gEnv->pMovieSystem->GetPlayingSpeed(m_pSequence); ActivateOutput(&m_actInfo, EOP_SequenceTime, currentTime); ActivateOutput(&m_actInfo, EOP_CurrentSpeed, currentSpeed); } } void StartSequence(SActivationInfo* pActInfo, float curTime = 0.0f, bool bNotifyStarted = true) { IMovieSystem *pMovieSystem = gEnv->pMovieSystem; if (!pMovieSystem) { return; } IAnimSequence *pSequence = pMovieSystem->FindSequence(GetPortString(pActInfo, EIP_Sequence)); if (pSequence == NULL) { pSequence = pMovieSystem->FindSequenceById((uint32)GetPortInt(pActInfo, EIP_SequenceId)); } // If sequence was changed in the meantime, stop old sequence first if (m_pSequence && pSequence != m_pSequence) { pMovieSystem->RemoveMovieListener(m_pSequence, this); pMovieSystem->StopSequence(m_pSequence); } m_pSequence = pSequence; if (m_pSequence) { if (m_pSequence->IsPaused()) { m_pSequence->Resume(); return; } m_pSequence->Resume(); pMovieSystem->AddMovieListener(m_pSequence, this); pMovieSystem->PlaySequence(m_pSequence, NULL, true, false); pMovieSystem->SetPlayingTime(m_pSequence, curTime); // set blend parameters only for tracks with Director Node, having camera track inside IViewSystem* pViewSystem = CCryAction::GetCryAction()->GetIViewSystem(); if (pViewSystem && m_pSequence->GetActiveDirector()) { bool bDirectorNodeHasCameraTrack=false; IAnimNode *pDirectorNode = m_pSequence->GetActiveDirector(); if (pDirectorNode) { for (int trackId=0;trackId<pDirectorNode->GetTrackCount();++trackId) { IAnimTrack *pTrack = pDirectorNode->GetTrackByIndex(trackId); if (pTrack && pTrack->GetParameterType() == eAnimParamType_Camera && pTrack->GetNumKeys() > 0) { bDirectorNodeHasCameraTrack=true; break; } } } if (bDirectorNodeHasCameraTrack) { float blendPosSpeed = GetPortFloat(pActInfo, EIP_BlendPosSpeed); float blendRotSpeed = GetPortFloat(pActInfo, EIP_BlendRotSpeed); bool performBlendOut = GetPortBool(pActInfo, EIP_PerformBlendOut); pViewSystem->SetBlendParams(blendPosSpeed, blendRotSpeed, performBlendOut); } } if (bNotifyStarted) { ActivateOutput(pActInfo, EOP_Started, true); } pActInfo->pGraph->SetRegularlyUpdated(pActInfo->myID, true); } else { // sequence was not found -> hint GameWarning("[flow] Animations:PlaySequence: Sequence \"%s\" not found", GetPortString(pActInfo, 0).c_str()); // maybe we should trigger the output, but if sequence is not found this should be an error } NotifyEntities(); // this can happens when a timedemo is being recorded and the sequence is flagged as CUTSCENE if (m_pSequence && m_playingState==PS_Playing && !pMovieSystem->IsPlaying( m_pSequence)) { SequenceAborted(); } if(CCryActionCVars::Get().g_disableSequencePlayback) { if(gEnv->pMovieSystem && m_pSequence) { float endTime = m_pSequence->GetTimeRange().end; gEnv->pMovieSystem->SetPlayingTime(m_pSequence, endTime); } } } void PauseSequence(SActivationInfo* pActInfo) { if (m_playingState != PS_Playing) { return; } IMovieSystem *pMovieSys = gEnv->pMovieSystem; if (!pMovieSys) { return; } if (m_pSequence) { m_pSequence->Pause(); } } void NotifyEntityScript(IEntity* pEntity) { IScriptTable *pEntityScript = pEntity->GetScriptTable(); if(pEntityScript) { if(m_playingState == PS_Playing && pEntityScript->HaveValue("OnSequenceStart")) { Script::CallMethod(pEntityScript, "OnSequenceStart"); } else if(m_playingState == PS_Stopped && pEntityScript->HaveValue("OnSequenceStop")) { Script::CallMethod(pEntityScript, "OnSequenceStop"); } } } void NotifyEntities() { IMovieSystem *pMovieSystem = gEnv->pMovieSystem; if (!pMovieSystem || !m_pSequence) { return; } int nodeCount = m_pSequence->GetNodeCount(); for(int i=0; i<nodeCount; ++i) { IAnimNode* pNode = m_pSequence->GetNode(i); if(pNode) { IEntity* pEntity = pNode->GetEntity(); if(pEntity) { NotifyEntityScript(pEntity); } if(EntityGUID* guid = pNode->GetEntityGuid()) { EntityId id = gEnv->pEntitySystem->FindEntityByGuid(*guid); if(id != 0) { IEntity* pEntity2 = gEnv->pEntitySystem->GetEntity(id); if(pEntity2) { NotifyEntityScript(pEntity2); } } } } } } }; REGISTER_FLOW_NODE( "Animations:PlaySequence", CPlaySequence_Node );
[ "cloudcodexmain@gmail.com" ]
cloudcodexmain@gmail.com
7c367d5be4407f2206a9b02ad338eb37df830524
c3959671a067b0d3ea77d7b82f60ba7637b3d73e
/obsoleto/alfatesters_placav2.2/GARABULLO18_prueba_lecturas.ino/tiempo.ino
1061f5d8a6dae639169983b5dbe571c6912f70c8
[]
no_license
DiegoLale/garabullo2018
ad00378642ad71dff8677a21a669e7cf322079bd
018b9c194da9e3329a60b7b8d07836c8449b5497
refs/heads/master
2021-04-26T22:35:52.848104
2020-11-06T16:31:08
2020-11-06T16:31:08
124,115,659
0
1
null
2018-03-06T17:43:30
2018-03-06T17:43:30
null
UTF-8
C++
false
false
451
ino
boolean test_tiempo_suficiente() { tiempo_actual = millis(); medida_tiempo = (tiempo_actual - tiempo_inicio) / 1000; //esta variable se usa para la longitud de la barra de tiempo if (tiempo_actual - tiempo_inicio > 120000) { return 0; } else return 1; } void muestra_barra_crono() { pantalla.fillRect(4, 72, 120 - medida_tiempo, 10, ST7735_GREEN); pantalla.fillRect(124 - medida_tiempo, 72, medida_tiempo , 10, ST7735_BLACK); }
[ "diegolale@gmail.com" ]
diegolale@gmail.com
aa0d411d0010a213c4a57c7582d2451865638d44
86dae49990a297d199ea2c8e47cb61336b1ca81e
/c/2020 tasks/3.7 NOI OnLine/bubble/bubble.cpp
3b8e0ea7b1d7d7ed02591444f9bd32ac775ceecf
[]
no_license
yingziyu-llt/OI
7cc88f6537df0675b60718da73b8407bdaeb5f90
c8030807fe46b27e431687d5ff050f2f74616bc0
refs/heads/main
2023-04-04T03:59:22.255818
2021-04-11T10:15:03
2021-04-11T10:15:03
354,771,118
0
0
null
null
null
null
UTF-8
C++
false
false
694
cpp
#include<stdio.h> #include<algorithm> #include<string.h> using namespace std; int a[2000]; int b[2000]; int main() { int n,m; freopen("bubble.in","r",stdin); freopen("bubble.out","w",stdout); scanf("%d%d",&n,&m); for(int i = 1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1 ;i <= m;i++) { int t,c; scanf("%d%d",&t,&c); if(t == 1) swap(a[c],a[c + 1]); else { memcpy(b,a,sizeof(a)); for(int i = 1;i <= c;i++) for(int j = 1;j < n;j++) if(b[j] > b[j + 1]) swap(b[j],b[j + 1]); int ans = 0; for(int i = 1;i <= n;i++) for(int j = i + 1;j <= n;j++) if(b[j] < b[i]) ans++; printf("%d\n",ans); } } return 0; }
[ "linletian1@sina.com" ]
linletian1@sina.com
74d8436d5960c5a5af7b5d5d015cade9ed4a977a
a06a9ae73af6690fabb1f7ec99298018dd549bb7
/_Library/_Include/boost/numeric/odeint/util/same_instance.hpp
d2a21e3f944788ff80c5164d1f560e0715a54dd6
[]
no_license
longstl/mus12
f76de65cca55e675392eac162dcc961531980f9f
9e1be111f505ac23695f7675fb9cefbd6fa876e9
refs/heads/master
2021-05-18T08:20:40.821655
2020-03-29T17:38:13
2020-03-29T17:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,356
hpp
/* [auto_generated] boost/numeric/odeint/util/same_instance.hpp [begin_description] Basic check if two variables are the same instance [end_description] Copyright 2012 Karsten Ahnert Copyright 2012 Mario Mulansky 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 BOOST_NUMERIC_ODEINT_UTIL_SAME_INSTANCE_HPP_INCLUDED #define BOOST_NUMERIC_ODEINT_UTIL_SAME_INSTANCE_HPP_INCLUDED namespace boost { namespace numeric { namespace odeint { template< class T1 , class T2 , class Enabler=void > struct same_instance_impl { static bool same_instance( const T1& /* x1 */ , const T2& /* x2 */ ) { return false; } }; template< class T > struct same_instance_impl< T , T > { static bool same_instance( const T &x1 , const T &x2 ) { // check pointers return (&x1 == &x2); } }; template< class T1 , class T2 > bool same_instance( const T1 &x1 , const T2 &x2 ) { return same_instance_impl< T1 , T2 >::same_instance( x1 , x2 ); } } // namespace odeint } // namespace numeric } // namespace boost #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "adm.fael.hs@gmail.com" ]
adm.fael.hs@gmail.com
94d48ed1c035125452d0b86e91594c1dd5faaec2
b9c62e76aa57e5482ac1bfb96852b74046acea55
/leetcode/59spiral-matrix-ii.cpp
7bce6d215db1942fd58869fd94346780f37d2295
[]
no_license
demeiyan/algorithm
e7c9401a3d3486582865cd1d04a4d34a130bbe56
75c02ae3375e34a6209fdc91ba2a30979f091901
refs/heads/master
2022-11-13T03:59:09.175400
2019-09-17T05:01:06
2019-09-17T05:01:06
59,123,515
0
0
null
null
null
null
UTF-8
C++
false
false
2,262
cpp
/** * @Date 2019/2/18 21:43 * @Created by dmyan */ #include<bits/stdc++.h> using namespace std; class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res; if(n==0)return res; res.resize(n); if(n==1){ vector<int> tmp(n,0); cout<<"1"; res[0] = tmp; res[0][0] = 1; return res; } int m = n; vector<vector<bool>> f; f.resize(n); for(int i=0;i<f.size();i++){ vector<bool> tmp(n, false); f[i] = tmp; vector<int> tmp1(n,0); res[i] = tmp1; } int row = 0, col = 0; bool colr = true, rowu = false, coll = false, rowd = false; int cnt = 1; while(true){ if(!f[row][col]){ res[row][col] = cnt; f[row][col] = true; } if(colr){ if(col < n-1 && !f[row][col+1]){ col++; cnt++; continue; }else{ rowd = true; colr = false; } } if(rowd){ if(row < m-1&&!f[row+1][col]){ row++; cnt++; continue; }else{ coll = true; rowd = false; } } if(coll){ if(col > 0&&!f[row][col-1]){ col --; cnt++; continue; }else{ rowu = true; coll = false; } } if(rowu){ if(row>0&&!f[row-1][col]){ row--; cnt++; continue; }else{ colr = true; rowu = false; } } if(col==0&&f[row][col+1]&&f[row-1][col])break; if(row>0&&col>0&&row<m-1&&col<n-1){ if(f[row-1][col]&&f[row+1][col]&&f[row][col+1]&&f[row][col-1])break; } } return res; } };
[ "1312480794@qq.com" ]
1312480794@qq.com
797cb8d5c59f79639d4387b24586bebffd5a9bdd
c588186250b1af54a276dbba2efc8bb78ca14125
/GYM/101522_J.cpp
d5aa27e39bd18fb4b2801bc16467144d8477d4f7
[]
no_license
Meng-Lan/Lan
380fdedd8ed7b0c1e5ffdabdc0c2ce48344927df
fc12199919028335d6ddb12c8a0aa0537a07b851
refs/heads/master
2021-06-28T11:59:50.201500
2020-07-11T09:05:53
2020-07-11T09:05:53
93,761,541
0
0
null
null
null
null
UTF-8
C++
false
false
2,987
cpp
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<sstream> #include<fstream> #include<vector> #include<list> #include<deque> #include<stack> #include<queue> #include<map> #include<set> #include<cmath> #include<utility> #include<numeric> #include<iterator> #include<algorithm> #include<functional> #include<ctime> #include<cassert> using std::cin; using std::cout; using std::endl; typedef long long ll; typedef unsigned long long ull; typedef std::pair<int,int> P; #define FOR(i,init,len) for(int i=(init);i<(len);++i) #define For(i,init,len) for(int i=(init);i<=(len);++i) #define fi first #define se second #define pb push_back #define is insert namespace IO { inline char getchar() { static const int BUFSIZE=5201314; static char buf[BUFSIZE],*begin,*end; if(begin==end) { begin=buf; end=buf+fread(buf,1,BUFSIZE,stdin); if(begin==end) return -1; } return *begin++; } } inline void read(int &in) { int c,symbol=1; while(isspace(c=IO::getchar())); if(c=='-') { in=0;symbol=-1; } else in=c-'0'; while(isdigit(c=IO::getchar())) { in*=10;in+=c-'0'; } in*=symbol; } inline int read() { static int x;read(x);return x; } ll gcd(ll a,ll b) { return b?gcd(b,a%b):a; } ll lcm(ll a,ll b) { return a/gcd(a,b)*b; } #define PA(name,init,len) cout<<#name"["<<(len-init)<<"]=";FOR(_,init,len) cout<<name[_]<<" \n"[_==(len-1)]; #define Pa(name,init,len) cout<<#name"["<<(len-init+1)<<"]=";For(_,init,len) cout<<name[_]<<" \n"[_==(len)]; #define PV(name) cout<<#name"="<<name<<'\n'; const int maxn=205; const ll INF=1e18; ll d[maxn][maxn][maxn][3]; int b,r,s; ll k; ll dp(int b,int r,int s,int fr) { if(b<0||r<0||s<0) return 0; //printf("b:%d r:%d s:%d fr:%d ans:%lld\n",b,r,s,fr,d[b][r][s]); if(d[b][r][s][fr]>=0) return d[b][r][s][fr]; ll &ans=d[b][r][s][fr];ans=0; if(fr==0&&!r&&!s) return ans; if(fr==1&&!b&&!s) return ans; if(fr==2&&!b&&!r) return ans; if(b+r+s==1) return ans=1; if(fr!=0&&b) ans+=dp(b-1,r,s,0); if(fr!=1&&r) ans+=dp(b,r-1,s,1); if(fr!=2&&s) ans+=dp(b,r,s-1,2); if(ans>=INF) ans=INF; //printf("b:%d r:%d s:%d fr:%d ans:%lld\n",b,r,s,fr,ans); return ans; } void print(int b,int r,int s,int fr,ll k) { if(b<0||r<0||s<0) return; if(b+r+s==1) { if(b) printf("B"); if(r) printf("R"); if(s) printf("S"); return; } if(fr!=0&&b) { if(k>dp(b-1,r,s,0)) k-=dp(b-1,r,s,0); else { printf("B");print(b-1,r,s,0,k);return; } } if(fr!=1&&r) { if(k>dp(b,r-1,s,1)) k-=dp(b,r-1,s,1); else { printf("R");print(b,r-1,s,1,k);return; } } if(fr!=2&&s) { printf("S");print(b,r,s-1,2,k); } } int main() { #ifdef MengLan int Beginning=clock(); //freopen("in","r",stdin); //freopen("out","w",stdout); #endif // MengLan memset(d,-1,sizeof(d)); cin>>b>>r>>s>>k; ll sum=0; sum+=dp(b-1,r,s,0); sum+=dp(b,r-1,s,1); sum+=dp(b,r,s-1,2); if(sum<k) puts("None"); else print(b,r,s,3,k),printf("\n"); #ifdef MengLan printf("Time: %d\n",clock()-Beginning); #endif // MengLan return 0; }
[ "779379402@qq.com" ]
779379402@qq.com
beba5c80af02a979a90a1b609cd9991a5a1cf7cd
bf1e7cb6a0405bd4ab8986a1fdd108525fb576e6
/src/GA/Genome.cpp
32e92bb01fe009e2d85c38333f8888cf3800ccb8
[]
no_license
reckter/TravelingSaleseman
f0062096a07972908f804c7be9d6119016dde7f6
ce4cdca88b3a72b5c669718ac5c4b74dfb59e302
refs/heads/master
2020-04-25T05:10:07.287231
2014-12-15T14:40:09
2014-12-15T14:40:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,353
cpp
/* * Genome.cpp * * Created on: Nov 17, 2014 * Author: ahueck */ #include "Genome.h" #include "Util.h" namespace practical { namespace ga { Genome::Genome() : genes() { } Genome::Genome(const std::vector<IntGene>& genes) : genes(genes) { } Genome::Genome(const Genome& other) : genes(other.genes) { } const Genome& Genome::operator=(const Genome& rhs) { if (this != &rhs) { genes = rhs.genes; } return *this; } Genome* Genome::deepCopy() const { Genome* copy = shallowCopy(); copy->genes = this->genes; return copy; } bool Genome::operator<(const Genome& rhs) const { return fitness() < rhs.fitness(); } int Genome::duel(const Genome& opponent) const { const double fitness = this->fitness(); const double opo_fitness = opponent.fitness(); if (fitness > opo_fitness) { return 1; } else if (fitness < opo_fitness) { return -1; } return 0; } const std::vector<IntGene>& Genome::getGenes() const { return genes; } std::vector<IntGene>& Genome::getGenes() { return genes; } Genome::~Genome() { } std::ostream& operator<<(std::ostream& os, const Genome& genome) { os << "["; std::vector<practical::ga::IntGene>::const_iterator iter = genome.getGenes().begin(); for (; iter < genome.getGenes().end() - 1; ++iter) { os << *iter << " "; } return os << *iter << "] " << 1.0 / genome.fitness(); } } }
[ "hannes@guedelhoefer.de" ]
hannes@guedelhoefer.de