blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
96244a68f4749c960a9399d04b65656885b25d31
e9774bd2d0cd9aaad49eacd092ba97e95dbf9a5f
/problems/A - Average Height.cpp
77de0c8198c7ff98353c2695883ce3928e610415
[]
no_license
My-Competitive-Programming-Legacy/CodeForces
fb589c187706060d8a33eccf75597dad4dab904d
f9df0ffe76b1d37215f063e87920c0044fe226a4
refs/heads/master
2023-06-23T06:04:30.369027
2021-07-19T12:20:19
2021-07-19T12:20:19
387,414,460
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> e, o; for (int i = 0; i < n; i++) { int t; cin >> t; if (t % 2) e.push_back(t); else o.push_back(t); } for (auto v : e) cout << v << " "; for (auto v : o) cout << v << " "; cout << endl; } int main() { int t; cin >> t; while (t--) { solve(); } return 0; }
[ "hamzahasssan835@gmail.com" ]
hamzahasssan835@gmail.com
68e838b14f1d6c203d5a22a29d3782280f13b6c9
d1de10aead5ccf25b3eb94feefa60f90fc7454ee
/UPXGuy/UPXGuyDlg.cpp
b214876264dc2b378e8eb9214e2ea1f5afa6b0ed
[ "Unlicense" ]
permissive
mjohne/Cpp-Apps
3f9d838a120843dc0ac87cc81b1c3ae29282c51c
0d386f4a76a3aa4676a11d0e1e3cc87e91e9b96f
refs/heads/master
2020-09-09T03:51:54.553623
2019-11-25T23:45:37
2019-11-25T23:45:37
221,339,592
0
0
Unlicense
2019-11-25T23:45:38
2019-11-13T00:35:36
C++
UTF-8
C++
false
false
5,273
cpp
// UPXGuyDlg.cpp : implementation file // #include "stdafx.h" #include "UPXGuy.h" #include "UPXGuyDlg.h" #include "DlgProxy.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CUPXGuyDlg dialog IMPLEMENT_DYNAMIC(CUPXGuyDlg, CDialog); CUPXGuyDlg::CUPXGuyDlg(CWnd* pParent /*=NULL*/) : CDialog(CUPXGuyDlg::IDD, pParent) { //{{AFX_DATA_INIT(CUPXGuyDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); m_pAutoProxy = NULL; } CUPXGuyDlg::~CUPXGuyDlg() { // If there is an automation proxy for this dialog, set // its back pointer to this dialog to NULL, so it knows // the dialog has been deleted. if (m_pAutoProxy != NULL) m_pAutoProxy->m_pDialog = NULL; } void CUPXGuyDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CUPXGuyDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CUPXGuyDlg, CDialog) //{{AFX_MSG_MAP(CUPXGuyDlg) ON_WM_SYSCOMMAND() ON_WM_CLOSE() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CUPXGuyDlg message handlers BOOL CUPXGuyDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } void CUPXGuyDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CUPXGuyDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CUPXGuyDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } // Automation servers should not exit when a user closes the UI // if a controller still holds on to one of its objects. These // message handlers make sure that if the proxy is still in use, // then the UI is hidden but the dialog remains around if it // is dismissed. void CUPXGuyDlg::OnClose() { if (CanExit()) CDialog::OnClose(); } void CUPXGuyDlg::OnOK() { if (CanExit()) CDialog::OnOK(); } void CUPXGuyDlg::OnCancel() { if (CanExit()) CDialog::OnCancel(); } BOOL CUPXGuyDlg::CanExit() { // If the proxy object is still around, then the automation // controller is still holding on to this application. Leave // the dialog around, but hide its UI. if (m_pAutoProxy != NULL) { ShowWindow(SW_HIDE); return FALSE; } return TRUE; }
[ "noreply@github.com" ]
mjohne.noreply@github.com
de9eb9dd125bc1464592f2ac90125446b7ae25c2
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Core/ComponentBaseClasses/elxOptimizerBase.h
f5617047dcd070e9ab57a8abe062058b756ed5f5
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
4,880
h
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxOptimizerBase_h #define __elxOptimizerBase_h /** Needed for the macros */ #include "elxMacro.h" #include "elxBaseComponentSE.h" #include "itkOptimizer.h" namespace elastix { using namespace itk; /** * \class OptimizerBase * \brief This class is the elastix base class for all Optimizers. * * This class contains all the common functionality for Optimizers. * * The parameters used in this class are: * \parameter NewSamplesEveryIteration: if this flag is set to "true" some * optimizers ask the metric to select a new set of spatial samples in * every iteration. This, if used in combination with the correct optimizer (such as the * StandardGradientDescent), and ImageSampler (Random, RandomCoordinate, or RandomSparseMask), * allows for a very low number of spatial samples (around 2000), even with large images * and transforms with a large number of parameters.\n * Choose one from {"true", "false"} for every resolution.\n * example: <tt>(NewSamplesEveryIteration "true" "true" "true")</tt> \n * Default is "false" for every resolution.\n * * \ingroup Optimizers * \ingroup ComponentBaseClasses */ template <class TElastix> class OptimizerBase : public BaseComponentSE<TElastix> { public: /** Standard ITK-stuff. */ typedef OptimizerBase Self; typedef BaseComponentSE<TElastix> Superclass; /** Run-time type information (and related methods). */ itkTypeMacro( OptimizerBase, BaseComponentSE ); /** Typedefs inherited from Elastix. */ typedef typename Superclass::ElastixType ElastixType; typedef typename Superclass::ElastixPointer ElastixPointer; typedef typename Superclass::ConfigurationType ConfigurationType; typedef typename Superclass::ConfigurationPointer ConfigurationPointer; typedef typename Superclass::RegistrationType RegistrationType; typedef typename Superclass::RegistrationPointer RegistrationPointer; /** ITKBaseType. */ typedef itk::Optimizer ITKBaseType; /** Typedef needed for the SetCurrentPositionPublic function. */ typedef typename ITKBaseType::ParametersType ParametersType; /** Cast to ITKBaseType. */ virtual ITKBaseType * GetAsITKBaseType(void) { return dynamic_cast<ITKBaseType *>(this); } /** Cast to ITKBaseType, to use in const functions. */ virtual const ITKBaseType * GetAsITKBaseType(void) const { return dynamic_cast<const ITKBaseType *>(this); } /** Add empty SetCurrentPositionPublic, so this function is known in every inherited class. */ virtual void SetCurrentPositionPublic( const ParametersType &param ); /** Execute stuff before each new pyramid resolution: * \li Find out if new samples are used every new iteration in this resolution. */ virtual void BeforeEachResolutionBase(); /** Method that sets the scales defined by a sinus * scale[i] = amplitude^( sin(i/nrofparam*2pi*frequency) ) */ virtual void SetSinusScales(double amplitude, double frequency, unsigned long numberOfParameters); protected: /** The constructor. */ OptimizerBase(); /** The destructor. */ virtual ~OptimizerBase() {} /** Force the metric to base its computation on a new subset of image samples. * Not every metric may have implemented this. */ virtual void SelectNewSamples(void); /** Check whether the user asked to select new samples every iteration. */ virtual const bool GetNewSamplesEveryIteration(void) const; private: /** The private constructor. */ OptimizerBase( const Self& ); // purposely not implemented /** The private copy constructor. */ void operator=( const Self& ); // purposely not implemented /** Member variable to store the user preference for using new * samples each iteration. */ bool m_NewSamplesEveryIteration; }; // end class OptimizerBase } // end namespace elastix #ifndef ITK_MANUAL_INSTANTIATION #include "elxOptimizerBase.hxx" #endif #endif // end #ifndef __elxOptimizerBase_h
[ "maik.stille@gmail.com" ]
maik.stille@gmail.com
3b62d8374db04507b2309222c3ce4fc8f28a5f11
16e2f9d88b7163edf13fac603157bec32a58e54d
/include/aka/rtl/object_base.h
47e6b219c3720a0c23cc7838423c7d6e3021dfde
[ "MIT" ]
permissive
vadim-platonov/aka
3823a60bb5c5aac21b6f814752627a330bd1dd0c
2d9fef3cd0490d07dad790d6f2d6db238ee26eb3
refs/heads/master
2021-01-22T21:21:53.740786
2017-03-19T14:44:38
2017-03-19T14:44:38
85,416,046
0
0
null
null
null
null
UTF-8
C++
false
false
599
h
#ifndef AKA_OBJECT_BASE_H #define AKA_OBJECT_BASE_H #include <atomic> namespace aka { template <typename I> class ObjectBase : public I { public: ObjectBase() : m_ref(1) { } std::uint32_t AddRef() override { return ++m_ref; } std::uint32_t Release() override { if } result_t QueryInteface(iid_t iid, ptr_t* object) override { if (iid == I::m_iid) { *object = this; *object->AddRef(); } } private: std::atomic<std::uint32_t> m_ref; }; } #endif //AKA_OBJECT_BASE_H
[ "Vadim Platonov" ]
Vadim Platonov
2ba54f2dc45228690e20a666fb2e1ce8267b94e7
37cca16f12e7b1d4d01d6f234da6d568c318abee
/src/org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint.cpp
911a12644e992155485c5e308a251e46e3da5421
[]
no_license
subhash1-0/thirstyCrow
e48155ce68fc886f2ee8e7802567c1149bc54206
78b7e4e3d2b9a9530ad7d66b44eacfe73ceea582
refs/heads/master
2016-09-06T21:25:54.075724
2015-09-21T17:21:15
2015-09-21T17:21:15
42,881,521
0
0
null
null
null
null
UTF-8
C++
false
false
13,509
cpp
// Generated from /pastry-2.1/src/org/mpisws/p2p/transport/direct/DirectAppSocket.java #include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint.hpp> #include <java/io/IOException.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/Math.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuilder.hpp> #include <java/nio/ByteBuffer.hpp> #include <java/util/Iterator.hpp> #include <java/util/LinkedList.hpp> #include <java/util/Map.hpp> #include <org/mpisws/p2p/transport/P2PSocketReceiver.hpp> #include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_register_3.hpp> #include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_register_4.hpp> #include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_shutdownOutput_5.hpp> #include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_read_1.hpp> #include <org/mpisws/p2p/transport/direct/DirectAppSocket_DirectAppSocketEndpoint_write_2.hpp> #include <org/mpisws/p2p/transport/direct/DirectAppSocket.hpp> #include <org/mpisws/p2p/transport/direct/GenericNetworkSimulator.hpp> #include <rice/environment/logging/Logger.hpp> #include <Array.hpp> template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } extern void lock(::java::lang::Object *); extern void unlock(::java::lang::Object *); namespace { struct synchronized { synchronized(::java::lang::Object *o) : o(o) { ::lock(o); } ~synchronized() { ::unlock(o); } private: synchronized(const synchronized&); synchronized& operator=(const synchronized&); ::java::lang::Object *o; }; } org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::DirectAppSocket_DirectAppSocketEndpoint(DirectAppSocket *DirectAppSocket_this, const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) , DirectAppSocket_this(DirectAppSocket_this) { clinit(); } org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::DirectAppSocket_DirectAppSocketEndpoint(DirectAppSocket *DirectAppSocket_this, ::java::lang::Object* localNodeHandle, ::rice::environment::logging::Logger* logger) : DirectAppSocket_DirectAppSocketEndpoint(DirectAppSocket_this, *static_cast< ::default_init_tag* >(0)) { ctor(localNodeHandle,logger); } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::init() { seq = int32_t(0); bytesInFlight = int32_t(0); byteDeliveries = new ::java::util::LinkedList(); firstOffset = int32_t(0); } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::ctor(::java::lang::Object* localNodeHandle, ::rice::environment::logging::Logger* logger) { super::ctor(); init(); this->localNodeHandle = localNodeHandle; this->logger = logger; } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::setCounterpart(DirectAppSocket_DirectAppSocketEndpoint* counterpart) { this->counterpart = counterpart; } java::lang::Object* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::getRemoteNodeHandle() { return java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle); } int64_t org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::read(::java::nio::ByteBuffer* dsts) /* throws(IOException) */ { auto lengthRead = int32_t(0); { synchronized synchronized_0(this); { if(npc(byteDeliveries)->isEmpty()) { return 0; } if(java_cast< ::int8_tArray* >(npc(byteDeliveries)->getFirst()) == DirectAppSocket::EOF_()) { return -int32_t(1); } auto i = npc(byteDeliveries)->iterator(); while (npc(i)->hasNext()) { auto msg = java_cast< ::int8_tArray* >(java_cast< ::int8_tArray* >(npc(i)->next())); auto curBuffer = dsts; auto lengthToPut = npc(curBuffer)->remaining(); if(lengthToPut > (npc(msg)->length - firstOffset)) { lengthToPut = npc(msg)->length - firstOffset; } npc(curBuffer)->put(msg, firstOffset, lengthToPut); firstOffset += lengthToPut; lengthRead += lengthToPut; if(firstOffset == npc(msg)->length) { npc(i)->remove(); firstOffset = 0; } else { break; } } } } bytesInFlight -= lengthRead; if(npc(logger)->level <= ::rice::environment::logging::Logger::FINER) npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".write("_j) ->append(static_cast< ::java::lang::Object* >(dsts)) ->append(u") len:"_j) ->append(lengthRead) ->append(u" inFlight:"_j) ->append(bytesInFlight)->toString()); npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_read_1(this), 0); return lengthRead; } int64_t org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::write(::java::nio::ByteBuffer* srcs) /* throws(IOException) */ { if(outputClosed) return -int32_t(1); if(!npc(DirectAppSocket_this->simulator)->isAlive(java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle))) { return -int32_t(1); } auto availableToWrite = npc(srcs)->remaining(); int32_t lengthToWrite; { synchronized synchronized_1(counterpart); { lengthToWrite = DirectAppSocket::MAX_BYTES_IN_FLIGHT - npc(counterpart)->bytesInFlight; if(lengthToWrite > availableToWrite) lengthToWrite = availableToWrite; npc(counterpart)->bytesInFlight += lengthToWrite; } } auto const msg = new ::int8_tArray(lengthToWrite); auto remaining = lengthToWrite; while (remaining > 0) { auto lengthToReadFromBuffer = npc(srcs)->remaining(); if(remaining < lengthToReadFromBuffer) lengthToReadFromBuffer = remaining; npc(srcs)->get(msg, lengthToWrite - remaining, lengthToReadFromBuffer); remaining -= lengthToReadFromBuffer; } if(npc(logger)->level <= ::rice::environment::logging::Logger::FINER) npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".write("_j) ->append(static_cast< ::java::lang::Object* >(srcs)) ->append(u") len:"_j) ->append(lengthToWrite) ->append(u" inFlight:"_j) ->append(npc(counterpart)->bytesInFlight)->toString()); npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_write_2(this, msg), static_cast< int32_t >(::java::lang::Math::round(npc(DirectAppSocket_this->simulator)->networkDelay(java_cast< ::java::lang::Object* >(localNodeHandle), java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle))))); return lengthToWrite; } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::addToReadQueue(::int8_tArray* msg) { { synchronized synchronized_2(this); { if(npc(logger)->level <= ::rice::environment::logging::Logger::FINE) { if(msg == DirectAppSocket::EOF_()) { npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u": addToReadQueue(EOF)"_j)->toString()); } else { npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u": addToReadQueue("_j) ->append(npc(msg)->length) ->append(u")"_j)->toString()); } } npc(byteDeliveries)->addLast(static_cast< ::java::lang::Object* >(msg)); } } notifyCanRead(); } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::notifyCanWrite() { if(writer == nullptr) return; if(npc(counterpart)->bytesInFlight < DirectAppSocket::MAX_BYTES_IN_FLIGHT) { auto temp = writer; writer = nullptr; try { if(npc(logger)->level <= ::rice::environment::logging::Logger::FINEST) npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".notifyCanWrite()"_j)->toString()); npc(temp)->receiveSelectResult(this, false, true); } catch (::java::io::IOException* ioe) { npc(logger)->logException(::java::lang::StringBuilder().append(u"Error in "_j)->append(static_cast< ::java::lang::Object* >(temp))->toString(), ioe); } } } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::notifyCanRead() { if(npc(byteDeliveries)->isEmpty()) return; if(reader != nullptr) { auto temp = reader; reader = nullptr; try { if(npc(logger)->level <= ::rice::environment::logging::Logger::FINEST) npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".notifyCanRead()"_j)->toString()); npc(temp)->receiveSelectResult(this, true, false); } catch (::java::io::IOException* ioe) { npc(logger)->logException(::java::lang::StringBuilder().append(u"Error in "_j)->append(static_cast< ::java::lang::Object* >(temp))->toString(), ioe); } } } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::register_(bool wantToRead, bool wantToWrite, ::org::mpisws::p2p::transport::P2PSocketReceiver* receiver) { if(wantToWrite) { writer = receiver; npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_register_3(this), 0); } if(wantToRead) { reader = receiver; npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_register_4(this), 0); } } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::shutdownOutput() { if(npc(logger)->level <= ::rice::environment::logging::Logger::FINER) npc(logger)->log(::java::lang::StringBuilder().append(static_cast< ::java::lang::Object* >(this))->append(u".shutdownOutput()"_j)->toString()); outputClosed = true; if(!npc(DirectAppSocket_this->simulator)->isAlive(java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle))) return; npc(DirectAppSocket_this->simulator)->enqueueDelivery(new DirectAppSocket_DirectAppSocketEndpoint_shutdownOutput_5(this), static_cast< int32_t >(::java::lang::Math::round(npc(DirectAppSocket_this->simulator)->networkDelay(java_cast< ::java::lang::Object* >(localNodeHandle), java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle))))); } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::shutdownInput() { } void org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::close() { shutdownOutput(); shutdownInput(); } java::lang::String* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::toString() { return ::java::lang::StringBuilder().append(u"DAS{"_j)->append(static_cast< ::java::lang::Object* >(java_cast< ::java::lang::Object* >(localNodeHandle))) ->append(u":"_j) ->append(npc(DirectAppSocket_this->simulator)->isAlive(java_cast< ::java::lang::Object* >(localNodeHandle))) ->append(u"->"_j) ->append(static_cast< ::java::lang::Object* >(java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle))) ->append(u":"_j) ->append(npc(DirectAppSocket_this->simulator)->isAlive(java_cast< ::java::lang::Object* >(npc(counterpart)->localNodeHandle))) ->append(u" w:"_j) ->append(static_cast< ::java::lang::Object* >(writer)) ->append(u" r:"_j) ->append(static_cast< ::java::lang::Object* >(reader)) ->append(u"}"_j)->toString(); } java::lang::Object* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::getIdentifier() { return java_cast< ::java::lang::Object* >(getRemoteNodeHandle()); } java::util::Map* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::getOptions() { return DirectAppSocket_this->options; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::class_() { static ::java::lang::Class* c = ::class_(u"org.mpisws.p2p.transport.direct.DirectAppSocket.DirectAppSocketEndpoint", 71); return c; } java::lang::Class* org::mpisws::p2p::transport::direct::DirectAppSocket_DirectAppSocketEndpoint::getClass0() { return class_(); }
[ "sgurjar@adobe.com" ]
sgurjar@adobe.com
9f9cd6d9be8e3b3380665991bf842df694715b55
903855cbeb65affd6620ded59191c8a8b8d1df45
/Pestov/sem_1/tictactoe/main.cpp
ccb14c1a03d71071813e36c965f55efb8c008b61
[ "MIT" ]
permissive
soomrack/MR2020
260b2ff093ab39c48d3cfa18e0c1c0b3859bd1e0
2de7289665dcdac4a436eb512f283780aa78cb76
refs/heads/master
2023-04-26T15:11:08.607185
2021-05-24T11:02:34
2021-05-24T11:02:34
293,246,956
4
0
MIT
2021-02-21T10:29:12
2020-09-06T09:50:17
C++
UTF-8
C++
false
false
5,654
cpp
/* The 4th assignment of programming in a high level language Console application - game tic tac toe. Principle of operation: // The game board is created. // The user chooses who he wants to play for (X or 0) // Human move // Program move (random) // The end Debag Smart proram move */ #include <iostream> #include <cstdlib> #include <ctime> struct board_t { char A[3][3]; }; board_t create_board(){ board_t board; for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ board.A[i][j] = '-'; } } return board; } void print_board(board_t board){ for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ std::cout << board.A[i][j] << " "; } std::cout << std::endl; } } bool user_choice(){ // return is_user_X; bool x; std::cout << "Choose your sym (X or 0):" << std::endl; char sym; std::cin >> sym; if (sym == 'X'){ return true; } else if (sym == '0') { return false; } else { std::cout << "Invalid sym, re-enter:" << std::endl; return user_choice(); } } board_t human_move(board_t board, bool is_gamemode_X){ int row, col; std::cout << "Your move(enter col and row):" << std::endl; std::cin >> row >> col; row--; col--; char temp = board.A[col][row]; if (temp == '-'){ if (is_gamemode_X){ board.A[col][row] = 'X'; } else { board.A[col][row] = '0'; } } else { std::cout << "Place already occupied, enter another value." << std::endl; board = human_move(board, is_gamemode_X); } return board; } board_t prog_move(board_t board, bool is_gamemode_X){ // srand(static_cast<unsigned int>(time(0))); int row = (rand() % 3); int col = (rand() % 3); // std::cout << row << " " << col << std::endl; char temp = board.A[col][row]; if (temp == '-'){ std::cout << "My move:" << std::endl; std::cout << row << " " << col << std::endl; if (!is_gamemode_X){ board.A[col][row] = 'X'; } else { board.A[col][row] = '0'; } } else { board = prog_move(board, is_gamemode_X); } return board; } int find_winner(board_t board){ // return 1 - X win // return 0 - 0 win // return 2 - draw // return -1 - no end int count = 0; // find X win for (int i = 0; i < 3; i++){ // horizontal for (int j = 0; j < 3; j++){ if (board.A[i][j] == 'X'){ count++; } } if (count == 3){ return 1; } count = 0; // vertical for (int j = 0; j < 3; j++){ if (board.A[j][i] == 'X'){ count++; } } if (count == 3){ return 1; } count = 0; } // main diagonal for (int j = 0; j < 3; j++){ if (board.A[j][j] == 'X'){ count++; } } if (count == 3){ return 1; } count = 0; // second diagonal for (int j = 0; j < 3; j++){ if (board.A[j][2 - j] == 'X'){ count++; } } if (count == 3){ return 1; } count = 0; // find 0 win for (int i = 0; i < 3; i++){ // horizontal for (int j = 0; j < 3; j++){ if (board.A[i][j] == '0'){ count++; } } if (count == 3){ return 0; } count = 0; // vertical for (int j = 0; j < 3; j++){ if (board.A[j][i] == '0'){ count++; } } if (count == 3){ return 0; } count = 0; } // main diagonal for (int j = 0; j < 3; j++){ if (board.A[j][j] == '0'){ count++; } } if (count == 3){ return 0; } count = 0; // second diagonal for (int j = 0; j < 3; j++){ if (board.A[j][2 - j] == '0'){ count++; } } if (count == 3){ return 0; } count = 0; // find end game for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ if (board.A[i][j] == '-'){ count++; } } } if (count == 0){ return 2; } return -1; } int main(int argc, char const *argv[]) { bool end = false; bool pr_move = false; bool hum_move = false; board_t board = create_board(); print_board(board); bool choice = user_choice(); if (choice){ hum_move = true; } else { pr_move = true; } int win = find_winner(board); int win_help = win; while (!end){ if (hum_move){ board = human_move(board, choice); hum_move = false; pr_move = true; } else if (pr_move){ board = prog_move(board, choice); pr_move = false; hum_move = true; } print_board(board); int win = find_winner(board); win_help = win; if (win != -1){ end = true; } } if (win_help == 2){ std::cout << "Draw!" << std::endl; } else if ((win_help == 1) and choice){ std::cout << "You win!!!" << std::endl; } else { std::cout << "You lose!!!" << std::endl; } return 0; }
[ "noreply@github.com" ]
soomrack.noreply@github.com
5e05c4e08ce61cec3fb1d73aeef8b39f492099bb
cd470ad61c4dbbd37ff004785fd6d75980987fe9
/Luogu/3857 [TJOI2008]彩灯/线性基/std.cpp
6417a6aa4496bf72070a7eeec537e9f16efd9447
[]
no_license
AutumnKite/Codes
d67c3770687f3d68f17a06775c79285edc59a96d
31b7fc457bf8858424172bc3580389badab62269
refs/heads/master
2023-02-17T21:33:04.604104
2023-02-17T05:38:57
2023-02-17T05:38:57
202,944,952
3
1
null
null
null
null
UTF-8
C++
false
false
789
cpp
#include <cstdio> #include <cctype> #include <algorithm> #include <cstring> int read(){ register int x = 0; register char f = 1, ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = !f; for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ '0'); return f ? x : -x; } int n, m; char s[60]; long long a[60]; void insert(long long x){ for (register int i = m - 1; ~i; --i) if (x >> i & 1) if (a[i]) x ^= a[i]; else return a[i] = x, void(0); } int main(){ m = read(), n = read(); for (register int i = 1; i <= n; ++i){ scanf("%s", s + 1); long long x = 0; for (register int j = 1; j <= m; ++j) x = x << 1 | (s[j] == 'O'); insert(x); } int s = 0; for (register int i = 0; i < m; ++i) if (a[i]) ++s; printf("%lld\n", (1ll << s) % 2008); }
[ "1790397194@qq.com" ]
1790397194@qq.com
1974822aa8296803ec88670928d68208817a580e
b60776fe3c35b48485b3e9fd85c38e2954e0186b
/Recursion/histogramOfOutcomesOFNDiceRolls.cpp
90d3c6ef08c0e8ac0d7ee1653f9bd7745d443903
[]
no_license
aniket-gore/practice-codes
88994ef1719f21f1b1ae4c21b6fd7ad80d581e6b
4b3fbfb73da8cd1f2786717e4e8927bac69eefb2
refs/heads/master
2021-01-17T21:24:00.879741
2017-08-17T01:37:32
2017-08-17T01:37:32
36,997,219
0
0
null
null
null
null
UTF-8
C++
false
false
1,340
cpp
#include<iostream> #include<map> using namespace std; /* Given N dice with m sides, print histogram of all outcomes of dice throws. e.g. N=2, m = 3 (1, 1) -> 2 (1, 2) -> 3 (1, 3) -> 4 (2, 1) -> 3 (2, 2) -> 4 (2, 3) -> 5 (3, 1) -> 4 (3, 2) -> 5 (3, 3) -> 6 And the function should return: 2: 1 3: 2 4: 3 5: 2 6: 1 */ void histogramOfOutComesOfNDiceRolls(int N, int sides, int outcomes[], int index, map<int,int> &histogram){ if(index == -1){ int sum=0; for(int i=0; i<N; i++){ sum += outcomes[i]; } if(histogram.find(sum) != histogram.end()){ histogram[sum]++; } else{ histogram.insert(make_pair(sum,1)); } return; } for(int i=1; i<=sides; i++){ outcomes[index] = i; histogramOfOutComesOfNDiceRolls(N,sides,outcomes,index-1,histogram); } } /* int main(){ int outcomes[2] = {0}; //size = no. of dice map<int,int> histogram; // 4th parameter : index = index in the array denoting which dice // we start with last dice, and decrement till 0th by filling values from 1 to m histogramOfOutComesOfNDiceRolls(2,3,outcomes,1,histogram); cout<<"histogram = "; map<int,int>::iterator iter; for(iter = histogram.begin(); iter != histogram.end(); iter++){ cout<<endl<<iter->first<<" : "<<iter->second; } cout<<endl; return 1; }*/
[ "aniketgore05@gmail.com" ]
aniketgore05@gmail.com
2c52d7c79d9d97014b996947b28f546eafd49f32
da89726ee5d4b307c56027ce6546e5f6fc693209
/control.cpp
686533352d29a533144d99b3f6f4e9ff998f620b
[]
no_license
ImaginationZ/physics-simulation-engine
0ab9dc216ca80e1168819101dad55d0cc704316c
9cabf49081d7a1c7d9fa8701f10d781455b8c090
refs/heads/master
2020-06-12T21:24:30.633789
2013-06-27T10:19:05
2013-06-27T10:19:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,228
cpp
#include "control.h" coordinate control::get_position(point* p){ return p->ask_position(); } coordinate control::get_velosity(point* p){ return p->ask_velosity(); } coordinate control::get_accelerate(point* p){ return p->ask_acceleration(); } void control::moveto(point* p, const coordinate& c) { p->moveto(c); } void control::set_accelarate(point* p, const coordinate& c) { p->set_acceleration(c); } void control::set_velosity(point* p, const coordinate& c) { p->set_velosity(c); } coordinate control::get_direction(point* a, point* b) { coordinate dis = b->ask_position() - a->ask_position(); return dis.unit(); } double control::get_distance( point* a, point* b ){ coordinate dis = b->ask_position() - a->ask_position(); return dis.length(); } double control::get_mass(mass_point* p){ return p->get_mass(); } void control::set_gravity(mass_point* p, const coordinate& g){ p->set_force(g * p->get_mass()); } double control::get_radius(ball* b) { return b->get_radius(); } bool control::if_touched(ball* a, ball* b) { if (get_distance(a,b) > a->get_radius() + b->get_radius()) return false; return true; } void control::set_elastic_force( elastic_ball* a, elastic_ball* b, double delta_time){ coordinate direction = get_direction(a,b); double proportional = a->get_radius() + b->get_radius() - get_distance(a,b); if( proportional < 0 ) return; double v = dot(a->ask_velosity() - b->ask_velosity(),direction.unit( )); if(v>0 &&( 2*v*delta_time > direction.length() ||a->get_radius()+b->get_radius()> 10*direction.length()) ){ coordinate hforce = 2/(a->get_mass()+b->get_mass())*v * direction / delta_time; a->set_force( -hforce *b->get_mass() ); b->set_force( hforce*a->get_mass() ); } coordinate force =( ( a->get_stiffness() + b->get_stiffness() ) / 2 * proportional ) * direction; a->set_force(-force); a->set_force(-delta_time* a->ask_velosity()); b->set_force(force); b->set_force(-delta_time* b->ask_velosity()); } void control::arrange(elastic_ball* a,elastic_ball* b,double delta_time){ coordinate direction = get_direction(a,b); double proportional = a->get_radius() + b->get_radius() - get_distance(a,b); if( proportional < 0 ) return; double v = dot(a->ask_velosity() - b->ask_velosity(),direction.unit( )); if(v>0) { coordinate hforce = v * direction / delta_time; a->set_force( -hforce ); b->set_force( hforce ); } } void control::arrange(elastic_ball* a,cylinder* c,double delta_time){ coordinate p = c->get_nearest(a); coordinate direction = a->ask_position() - p; double proportional = a->get_radius() - direction.length(); if(proportional<0) return; double v = dot(a->ask_velosity() - c->get_velosity( p ),-direction.unit()); coordinate hforce = v*direction.unit() / delta_time; a->set_force(hforce); coordinate force = proportional * a->get_stiffness() * direction.unit(); a->set_force(force); } void control::set_elastic_force(elastic_ball* a,cylinder* c,double delta_time){ coordinate p = c->get_nearest(a); coordinate direction = a->ask_position() - p; double proportional = a->get_radius() - direction.length(); if(proportional<0) return; double v = dot(a->ask_velosity() - c->get_velosity( p ),-direction.unit()); if(v>0 && (4 * v *delta_time> direction.length() || direction.length()<0.9*a->get_radius())){ coordinate hforce = 2/(a->get_mass()+c->get_mass())*v*direction.unit() / delta_time; a->set_force(c->get_mass()*hforce); c->set_force(-a->get_mass()*hforce * cos_angle(c->get_axis(),c->ask_position() -p)); c->set_moment( cross( p - c->ask_position( ), -hforce ) ); } coordinate force = proportional * a->get_stiffness() * direction.unit(); coordinate moment = cross(p - c->ask_position(),-force); a->set_force(force); c->set_force(-force * cos_angle(c->get_axis(),c->ask_position() -p)); a->set_force(-a->ask_velosity()*delta_time); c->set_force(-c->get_velosity(p)*delta_time); c->set_moment(-c->get_speed() *delta_time); c->set_moment(moment); }
[ "frequencyhzs@gmail.com" ]
frequencyhzs@gmail.com
4d6e30e0405a021843ec8250c70d80bdf92d5e72
b2f31a8dd5675da82fc74ce613a6b78e59addc95
/MotLB/src/graphics/VertexArray.cpp
79b67c401ad0a311692f6d25d7c9e9c5aa39851d
[]
no_license
samuelxyz/motlb
d2d0d99680b57840a7a4b8c343f0cd753ea8e235
f7b919d17bc01c86602651ddc9a16cbcbdc16ef7
refs/heads/master
2020-03-23T18:59:14.772758
2018-09-07T14:52:37
2018-09-07T14:52:37
141,946,608
0
0
null
2018-08-07T20:07:23
2018-07-23T01:35:36
C
UTF-8
C++
false
false
1,925
cpp
/* * VertexArray.cpp * * Created on: Jul 30, 2018 * Author: Samuel Tan */ #include "../graphics/VertexArray.h" #include <cassert> namespace graphics { GLuint VertexArray::currentlyBound = 0; VertexArray::VertexArray() : stride(0) { glGenVertexArrays(1, &ID); } VertexArray::~VertexArray() { if (currentlyBound == ID) currentlyBound = 0; glDeleteVertexArrays(1, &ID); } void VertexArray::addAttribute(const std::string& varName, GLenum dataType, GLuint numComponents) { attributes.push_back({ varName, dataType, numComponents }); stride += (numComponents * getSizeOfType(dataType)); } void VertexArray::applyAttributesWithBuffer(const VertexBuffer& vb, const ShaderProgram& sp) { vb.bind(); bind(); unsigned int offset = 0; for (auto& attribute : attributes) { GLuint varPos = glGetAttribLocation(sp.getID(), attribute.varName.c_str()); glEnableVertexAttribArray(varPos); glVertexAttribPointer(varPos, attribute.numComponents, attribute.dataType, GL_FALSE, stride, (const void*)offset); offset += attribute.numComponents * getSizeOfType(attribute.dataType); } } void VertexArray::bind() const { if (currentlyBound != ID) forceBind(); } void VertexArray::forceBind() const { glBindVertexArray(ID); currentlyBound = ID; } void VertexArray::unbind() const { glBindVertexArray(0); currentlyBound = 0; } GLsizei VertexArray::getSizeOfType(GLenum dataType) { switch (dataType) { case GL_FLOAT: return sizeof(GLfloat); case GL_UNSIGNED_INT: return sizeof(GLuint); case GL_UNSIGNED_BYTE: return sizeof(GLbyte); } // should be done before here assert(false); return 0; } } /* namespace render */
[ "xinyizhentan@gmail.com" ]
xinyizhentan@gmail.com
6944cf306f31252cc131e163a17f80284c2555da
2d5f2e5ff7a384cdd8402e9a55e4f3c639ad1a25
/arduino/robot/robot.ino
5ba3c2596954cc63357508834599bb0dff480715
[]
no_license
vs223/hci
e2a714be9bc00fc261c8d43523bfa7965a490c75
a1e764bd9c1150ac8821523e82c73bbd082078ed
refs/heads/master
2021-01-19T09:46:14.770996
2017-05-17T11:29:17
2017-05-17T11:29:17
87,780,995
0
0
null
2017-05-17T11:29:18
2017-04-10T07:37:59
HTML
UTF-8
C++
false
false
972
ino
#include <Servo.h> Servo arm; int pos = 40; int armFlag = 0; int goalPos = 40; int fsrValue =0; int ledPin = 11; int potValue; int ledValue; int photoValue; int oldPhotoValue = 0; void setup() { // put your setup code here, to run once: arm.attach(4); pinMode(ledPin, OUTPUT); } void loop() { fsrValue = analogRead(A4); if(fsrValue > 128){ armFlag = 1; } potValue = analogRead(A0); ledValue = map(potValue, 0, 1023, 0, 255); analogWrite(ledPin, ledValue); photoValue = analogRead(A1); if(photoValue < 350 && oldPhotoValue >= 350){ for(int i =0; i <6; i++){ analogWrite(ledPin, 255); delay(100); analogWrite(ledPin, 0); delay(100); } } oldPhotoValue = photoValue; if(pos == 130){ goalPos=40; armFlag = 0; } if(pos==40 && armFlag ==1){ goalPos = 130; armFlag = 0; } if(pos != goalPos){ pos += (goalPos - pos > 0)? 1:-1; } arm.write(pos); delay(15); }
[ "vs223@naver.com" ]
vs223@naver.com
cc58e256ac98e05821724ba494280b210d7f6288
57b3e9e577d464e7b78919bfe247db86490dc82e
/test3-8.cpp
e9516d49bfbb2b4513ee4d6a24de74f0f230ca6b
[]
no_license
xjx00/FkprogramClass
7eed075d1ffad571fa73a0bbda2a8e5a2591d5d0
ecf3b5b3f43c47aeaf3617dbfedeff42b98cc372
refs/heads/master
2020-03-15T23:28:36.323275
2018-06-22T12:12:58
2018-06-22T12:12:58
132,394,581
0
0
null
2018-05-07T02:08:17
2018-05-07T02:08:17
null
UTF-8
C++
false
false
386
cpp
#include <stdio.h> #include <stdlib.h> int cow(int n) { int i,j, sum = 0; int one_new = 1; int a[4] = {1,0,0,0}; for(i=1; i<n; i++) { sum = 0; one_new = a[3] + a[2]; a[3] += a[2]; a[2] = a[1]; a[1] = a[0]; a[0] = one_new; for(j=0; j<4; j++) sum += a[j]; printf("n=%d,cow=%d\n",i + 1,sum); } return sum; } int main(void) { cow(10); getchar(); getchar(); }
[ "noreply@github.com" ]
xjx00.noreply@github.com
5cc0ab00156a47b1c0540d424a096fb3afd6afb4
0e8d57f10639b0bdcab2c89b307029697c909863
/aoj/ITP2/ITP2-10C/main.cpp
075c0c05b15373ab253ade81ea19b11d9cf92fa7
[ "Apache-2.0" ]
permissive
xirc/cp-algorithm
07a6faf5228e07037920f5011326c16091a9157d
e83ea891e9f8994fdd6f704819c0c69f5edd699a
refs/heads/main
2021-12-25T16:19:57.617683
2021-12-22T12:06:49
2021-12-22T12:06:49
226,591,291
15
1
Apache-2.0
2021-12-22T12:06:50
2019-12-07T23:53:18
C++
UTF-8
C++
false
false
1,340
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); bitset<64> bits; int Q; cin >> Q; int t, i; while (Q--, Q >= 0) { cin >> t; if (t == 0) { // test i cin >> i; auto ans = (bits[i] ? 1 : 0); cout << ans << endl; } else if (t == 1) { // set i cin >> i; bits[i] = true; } else if (t == 2) { // clear i cin >> i; bits[i] = false; } else if (t == 3) { // flip i cin >> i; bits[i].flip(); } else if (t == 4) { // all auto ans = bits.all() ? 1 : 0; cout << ans << endl; } else if (t == 5) { // any auto ans = bits.any() ? 1 : 0; cout << ans << endl; } else if (t == 6) { // none auto ans = bits.none() ? 1 : 0; cout << ans << endl; } else if (t == 7) { // count auto ans = bits.count(); cout << ans << endl; } else if (t == 8) { // val auto ans = bits.to_ullong(); cout << ans << endl; } else throw; } return 0; }
[ "xirckey@gmail.com" ]
xirckey@gmail.com
bc04cff8fe6254d1b29a203269ce3c54c6ef6a6f
6a35dfbc1721342b6202327394ac74e053ed655d
/0050.Pow_x_n/pow_x_n.cpp
fc6edafa531d91b5aaf5574604c127cf8c0b3ea4
[]
no_license
Villarealfan/Leetcode
0c09190b896824d820ae1d712f17b39a3621df79
11006480c58f8af031773f4dcdcf3711a134ff39
refs/heads/master
2022-12-03T06:39:14.503309
2020-08-18T23:52:04
2020-08-18T23:52:04
270,938,148
3
1
null
null
null
null
UTF-8
C++
false
false
679
cpp
#include "../include/tools.h" class Solution { public: double myPow(double x, int n) { if (n >= 0){ return power(x, n); } else{ return 1.0/power(x,n); } } private: double power(double x, int n){ if (n == 0) return 1.0; double y = power(x, n/2); if (n %2 == 0){ return y*y; } else{ return y*y*x; } } }; int main(){ Solution so; double x; int n; cout << "输入 x:" << endl; cin >> x; cout << "输入 n:" << endl; cin >> n; double output = so.myPow(x, n); cout << output << endl; return 0; }
[ "noreply@github.com" ]
Villarealfan.noreply@github.com
615f9861eba483a35585d9f1ce67d92c549576a0
a5095c14cf28ffd97ccb478dd1781a476bef0413
/Client/Game/States/PreGameState.cpp
9d6a7c91251d1fb1a063c7368685d87a03b097f9
[ "CC-BY-3.0", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
Katipo007/diorama_roguelite
4bf1bfc96a4a00192f58e599594cd44b27b2c994
81b2bd282507cbffb8c90a3793a7b97f395e8584
refs/heads/master
2023-06-04T02:59:26.469544
2021-06-28T11:04:19
2021-06-28T11:04:19
347,273,548
2
0
null
2021-06-06T03:44:41
2021-03-13T04:39:12
C++
UTF-8
C++
false
false
269
cpp
#include "PreGameState.hpp" namespace Game::States { fsm::Might<fsm::TransitionTo<MainMenuState>> PreGameState::HandleEvent( const Events::FrameEvent& ) { // TODO: only transition after we've loaded starting stuff return fsm::TransitionTo<MainMenuState>(); } }
[ "ben@steadfast.co.nz" ]
ben@steadfast.co.nz
134c7a99d461dc1c252a5247d4247e4fefde1ba3
b2dbadcfecc50c7328196fe3632b4cc87042c635
/ext/avif/ext/aom/test/error_block_test.cc
3664ccf29f95f653fb6860c6d51b06e8da43cc0e
[ "BSL-1.0", "LicenseRef-scancode-alliance-open-media-patent-1.0", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
EwoutH/colorist
ce6af59a9ad6ee17a5d112da637e1626c6488b21
8e8b586aceac9f54fecb648e94f6e4ad19593c76
refs/heads/master
2023-04-15T15:37:50.943391
2019-04-23T23:39:44
2019-04-23T23:39:44
185,622,495
0
0
BSL-1.0
2019-05-08T14:31:15
2019-05-08T14:29:00
C
UTF-8
C++
false
false
8,137
cc
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <cmath> #include <cstdlib> #include <string> #include "third_party/googletest/src/googletest/include/gtest/gtest.h" #include "config/aom_config.h" #include "config/av1_rtcd.h" #include "test/acm_random.h" #include "test/clear_system_state.h" #include "test/register_state_check.h" #include "test/util.h" #include "av1/common/entropy.h" #include "aom/aom_codec.h" #include "aom/aom_integer.h" using libaom_test::ACMRandom; namespace { const int kNumIterations = 1000; typedef int64_t (*ErrorBlockFunc)(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz, int bps); typedef ::testing::tuple<ErrorBlockFunc, ErrorBlockFunc, aom_bit_depth_t> ErrorBlockParam; class ErrorBlockTest : public ::testing::TestWithParam<ErrorBlockParam> { public: virtual ~ErrorBlockTest() {} virtual void SetUp() { error_block_op_ = GET_PARAM(0); ref_error_block_op_ = GET_PARAM(1); bit_depth_ = GET_PARAM(2); } virtual void TearDown() { libaom_test::ClearSystemState(); } protected: aom_bit_depth_t bit_depth_; ErrorBlockFunc error_block_op_; ErrorBlockFunc ref_error_block_op_; }; TEST_P(ErrorBlockTest, OperationCheck) { ACMRandom rnd(ACMRandom::DeterministicSeed()); DECLARE_ALIGNED(16, tran_low_t, coeff[4096]); DECLARE_ALIGNED(16, tran_low_t, dqcoeff[4096]); int err_count_total = 0; int first_failure = -1; intptr_t block_size; int64_t ssz; int64_t ret; int64_t ref_ssz; int64_t ref_ret; const int msb = bit_depth_ + 8 - 1; for (int i = 0; i < kNumIterations; ++i) { int err_count = 0; block_size = 16 << (i % 9); // All block sizes from 4x4, 8x4 ..64x64 for (int j = 0; j < block_size; j++) { // coeff and dqcoeff will always have at least the same sign, and this // can be used for optimization, so generate test input precisely. if (rnd(2)) { // Positive number coeff[j] = rnd(1 << msb); dqcoeff[j] = rnd(1 << msb); } else { // Negative number coeff[j] = -rnd(1 << msb); dqcoeff[j] = -rnd(1 << msb); } } ref_ret = ref_error_block_op_(coeff, dqcoeff, block_size, &ref_ssz, bit_depth_); ASM_REGISTER_STATE_CHECK( ret = error_block_op_(coeff, dqcoeff, block_size, &ssz, bit_depth_)); err_count += (ref_ret != ret) | (ref_ssz != ssz); if (err_count && !err_count_total) { first_failure = i; } err_count_total += err_count; } EXPECT_EQ(0, err_count_total) << "Error: Error Block Test, C output doesn't match optimized output. " << "First failed at test case " << first_failure; } TEST_P(ErrorBlockTest, ExtremeValues) { ACMRandom rnd(ACMRandom::DeterministicSeed()); DECLARE_ALIGNED(16, tran_low_t, coeff[4096]); DECLARE_ALIGNED(16, tran_low_t, dqcoeff[4096]); int err_count_total = 0; int first_failure = -1; intptr_t block_size; int64_t ssz; int64_t ret; int64_t ref_ssz; int64_t ref_ret; const int msb = bit_depth_ + 8 - 1; int max_val = ((1 << msb) - 1); for (int i = 0; i < kNumIterations; ++i) { int err_count = 0; int k = (i / 9) % 9; // Change the maximum coeff value, to test different bit boundaries if (k == 8 && (i % 9) == 0) { max_val >>= 1; } block_size = 16 << (i % 9); // All block sizes from 4x4, 8x4 ..64x64 for (int j = 0; j < block_size; j++) { if (k < 4) { // Test at positive maximum values coeff[j] = k % 2 ? max_val : 0; dqcoeff[j] = (k >> 1) % 2 ? max_val : 0; } else if (k < 8) { // Test at negative maximum values coeff[j] = k % 2 ? -max_val : 0; dqcoeff[j] = (k >> 1) % 2 ? -max_val : 0; } else { if (rnd(2)) { // Positive number coeff[j] = rnd(1 << 14); dqcoeff[j] = rnd(1 << 14); } else { // Negative number coeff[j] = -rnd(1 << 14); dqcoeff[j] = -rnd(1 << 14); } } } ref_ret = ref_error_block_op_(coeff, dqcoeff, block_size, &ref_ssz, bit_depth_); ASM_REGISTER_STATE_CHECK( ret = error_block_op_(coeff, dqcoeff, block_size, &ssz, bit_depth_)); err_count += (ref_ret != ret) | (ref_ssz != ssz); if (err_count && !err_count_total) { first_failure = i; } err_count_total += err_count; } EXPECT_EQ(0, err_count_total) << "Error: Error Block Test, C output doesn't match optimized output. " << "First failed at test case " << first_failure; } TEST_P(ErrorBlockTest, DISABLED_Speed) { ACMRandom rnd(ACMRandom::DeterministicSeed()); DECLARE_ALIGNED(16, tran_low_t, coeff[4096]); DECLARE_ALIGNED(16, tran_low_t, dqcoeff[4096]); intptr_t block_size; int64_t ssz; int num_iters = 100000; int64_t ref_ssz; int k; const int msb = bit_depth_ + 8 - 1; for (int i = 0; i < 9; ++i) { block_size = 16 << (i % 9); // All block sizes from 4x4, 8x4 ..64x64 for (k = 0; k < 9; k++) { for (int j = 0; j < block_size; j++) { if (k < 5) { if (rnd(2)) { // Positive number coeff[j] = rnd(1 << msb); dqcoeff[j] = rnd(1 << msb); } else { // Negative number coeff[j] = -rnd(1 << msb); dqcoeff[j] = -rnd(1 << msb); } } else { if (rnd(2)) { // Positive number coeff[j] = rnd(1 << 14); dqcoeff[j] = rnd(1 << 14); } else { // Negative number coeff[j] = -rnd(1 << 14); dqcoeff[j] = -rnd(1 << 14); } } } aom_usec_timer ref_timer, test_timer; aom_usec_timer_start(&ref_timer); for (int i = 0; i < num_iters; ++i) { ref_error_block_op_(coeff, dqcoeff, block_size, &ref_ssz, bit_depth_); } aom_usec_timer_mark(&ref_timer); const int elapsed_time_c = static_cast<int>(aom_usec_timer_elapsed(&ref_timer)); aom_usec_timer_start(&test_timer); for (int i = 0; i < num_iters; ++i) { error_block_op_(coeff, dqcoeff, block_size, &ssz, bit_depth_); } aom_usec_timer_mark(&test_timer); const int elapsed_time_simd = static_cast<int>(aom_usec_timer_elapsed(&test_timer)); printf( " c_time=%d \t simd_time=%d \t " "gain=%d \n", elapsed_time_c, elapsed_time_simd, (elapsed_time_c / elapsed_time_simd)); } } } #if (HAVE_SSE2 || HAVE_AVX) using ::testing::make_tuple; INSTANTIATE_TEST_CASE_P( SSE2, ErrorBlockTest, ::testing::Values(make_tuple(&av1_highbd_block_error_sse2, &av1_highbd_block_error_c, AOM_BITS_10), make_tuple(&av1_highbd_block_error_sse2, &av1_highbd_block_error_c, AOM_BITS_12), make_tuple(&av1_highbd_block_error_sse2, &av1_highbd_block_error_c, AOM_BITS_8))); #endif // HAVE_SSE2 #if (HAVE_AVX2) using ::testing::make_tuple; INSTANTIATE_TEST_CASE_P( AVX2, ErrorBlockTest, ::testing::Values(make_tuple(&av1_highbd_block_error_avx2, &av1_highbd_block_error_c, AOM_BITS_10), make_tuple(&av1_highbd_block_error_avx2, &av1_highbd_block_error_c, AOM_BITS_12), make_tuple(&av1_highbd_block_error_avx2, &av1_highbd_block_error_c, AOM_BITS_8))); #endif // HAVE_AVX2 } // namespace
[ "jdrago@netflix.com" ]
jdrago@netflix.com
3428b906afed20ebdd0434d5f688a5a7b44a12f8
88eb1d1e85698ec3c3d3c3198b3caff1a036e88e
/src/MBC.cpp
c4790100be61e0587a535f87471066911b9b8f82
[]
no_license
Lordelbert/GBpp
153aafc4c26869493c00fea398a8996ec94e7bee
0defa1c8b0599f3944faac4c0f2ba6f95f8dbc2f
refs/heads/master
2022-12-04T20:29:44.618409
2020-08-21T14:40:38
2020-08-21T14:40:38
275,627,327
0
0
null
null
null
null
UTF-8
C++
false
false
2,499
cpp
#include "MBC.hpp" // TODO change nbr with enum to make code more explicit auto MBC1::swap_bank_rom_high() { for(size_t i = 0; i < 2; ++i) { MBC1_Partition::section mem_part{&m_memory[reg1_2() * 16_kB + i * 8_kB], &m_memory[reg1_2() * 16_kB + i * 8_kB + 8_kB]}; m_memory_partition.swap(i + 2, std::move(mem_part)); } return; } auto MBC1::swap_bank_rom_low() { const size_t addr = (mode()) ? (reg2() << 5) * 16_kB : 0b0; for(size_t i = 0; i < 2; ++i) { MBC1_Partition::section mem_part{&m_memory[addr + i * 8_kB], &m_memory[addr + i * 8_kB + 8_kB]}; m_memory_partition.swap(i, std::move(mem_part)); } return; } auto MBC1::swap_bank_ram() { const size_t addr = (mode()) ? reg2() * 8_kB : 0b0; MBC1_Partition::section mem_part{&m_memory[addr], &m_memory[addr + 8_kB]}; m_memory_partition.swap(5, std::move(mem_part)); return; } auto MBC1::ramg_enable(std::uint8_t value) noexcept -> void { m_ramg_enable = ((value & 0x0F) == 0x0A) ? true : false; } auto MBC1::bank_reg1(std::uint8_t value) noexcept -> void { const std::uint8_t _val = (value & 0b0001'1111); m_bank_selector = (m_bank_selector & 0b1110'0000) | ((_val == 0) ? 0b1 : _val); swap_bank_rom_high(); } // note can also be used for bank in ram : auto MBC1::bank_reg2(std::uint8_t value) noexcept -> void { m_bank_selector = (m_bank_selector & 0b1001'1111) | ((value & 0b11) << 5); swap_bank_rom_high(); swap_bank_rom_low(); if(m_ram > 8_kB) swap_bank_ram(); } auto MBC1::bank_mode(std::uint8_t value) noexcept -> void { m_bank_selector = set_bit(m_bank_selector, 7, static_cast<std::uint8_t>(value & 0b1)); swap_bank_rom_high(); swap_bank_rom_low(); if(m_ram > 8_kB) swap_bank_ram(); } [[nodiscard]] auto MBC1::read(std::uint16_t addr) const noexcept -> std::uint8_t { if(addr >= SWI_RAM_base and addr < SWI_RAM_ul) { return (m_ramg_enable) ? m_memory_partition[addr] : m_distrib(m_gen); } return m_memory_partition[addr]; } auto MBC1::write(std::uint16_t addr, std::uint8_t value) noexcept -> void { if(addr < IROM1_ul) { if(addr < 0x2000) { ramg_enable(value); return; } if(addr < 0x4000) { bank_reg1(value); return; } if(addr < 0x6000) { bank_reg2(value); return; } if(addr < 0x8000) { bank_mode(value); return; } } if(addr >= SWI_RAM_base and addr < SWI_RAM_ul) { if(m_ramg_enable) { m_memory_partition[addr] = value; } } m_memory_partition[addr] = value; return; }
[ "lordelbert@gmail.com" ]
lordelbert@gmail.com
3cc2f633ea81f21713c64577301cc281c0761b96
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1484496_0/C++/jasy/gcj2012R1BC.cpp
1e942dd42a1586ea0127aa4fd46b8be4fbd0eb1a
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,932
cpp
#include <iostream> #include <vector> #include <algorithm> typedef unsigned long long vtype; static void solve () { int N; std::cin >> N; std::vector<vtype> S(N); vtype s = 0; for (int i=0; i<N; ++i) { std::cin >> S[i]; s+=S[i]; } s/=2; std::sort(S.begin(), S.end()); const vtype mx = 1<<N; for (vtype x = 1; x<mx; ++x) { std::vector<vtype> a; vtype A = 0; std::vector<vtype> b; { vtype d = 1; for (int i=0; d<=x; d<<=1,++i) { const vtype s = S[i]; if (x&d) { a.push_back(s); A += s; } else { b.push_back(s); } } } if (A>s) { continue; } const vtype mxb = 1<<b.size(); for (vtype xb = 1; xb<mxb; ++xb) { vtype B = 0; vtype d = 1; std::vector<vtype> b2; for (int i=0; d<=xb; d<<=1,++i) { if (xb&d) { B += b[i]; b2.push_back(b[i]); } } if (A==B) { for (int i=0; i<a.size(); ++i) { if (i!=0) { std::cout << " "; } std::cout << a[i]; } std::cout << "\n"; for (int i=0; i<b2.size(); ++i) { if (i!=0) { std::cout << " "; } std::cout << b2[i]; } std::cout << "\n"; return; } } } std::cout << "Impossible\n"; } int main () { int T; std::cin >> T; for (int i=1; i<=T; ++i) { std::cout << "Case #" << i << ":\n"; solve(); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
d3ea9cc3ecf50506ab0e454eab5b3b0a297d560a
beede1d5be2e49f4656251d8020c1ff7452b9c92
/store/lexer_main.cc
d139daa090f8e3fb15834dc3c37f7f4d4ea475b3
[]
no_license
kryzthov/gooz
62e47026346e690086076a148bce1eec86ebb663
318cf7a8c3b878233a58777c16115627d2956b63
refs/heads/master
2020-05-17T17:51:23.069850
2017-12-06T07:23:39
2017-12-06T07:23:39
37,021,627
0
1
null
null
null
null
UTF-8
C++
false
false
585
cc
#include <iostream> #include <string> #include <glog/logging.h> #include <boost/spirit/include/lex_lexertl.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include "base/file-util.h" #include "store/oz_lexer.h" namespace lex = boost::spirit::lex; int main(int argc, char* argv[]) { ::google::ParseCommandLineFlags(&argc, &argv, true); ::google::InitGoogleLogging(argv[0]); CHECK_GE(argc, 2) << "No input file provided"; const string file_path = argv[1]; const string str = util::ReadFileToString(file_path); oz::RunLexerTest(str, file_path); return 0; }
[ "taton@wibidata.com" ]
taton@wibidata.com
fed5f5e7ecd746027411948d6c64d730253a4c9a
0f3cd546c1f60b1a47d045c9cbc6ab005d039aa9
/Intro/Langplay.cpp
148db6da5e8c8d2933d69c9815341ea0d31e2f30
[]
no_license
isliulin/legacy-vc6
62ea49025c519227af6cf73e5a4d1cc451568eb0
5d16f6e0bd71e3dff474cc2394263482c014ae56
refs/heads/master
2023-07-07T20:55:51.067797
2015-12-17T21:30:53
2015-12-17T21:30:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,050
cpp
#define INC_OLE2 #include <windows.h> #include <windowsx.h> #include <mmsystem.h> #include <commdlg.h> #include <string.h> #include <stdlib.h> #include <direct.h> #include <digitalv.h> #include <vfw.h> #include "langplay.h" #include <profiles.h> #include <int2str.h> HWND hwndMovie; /* window handle of the movie */ char szAppName [] = "IntroPlay"; /* function declarations */ long FAR PASCAL WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); void exitintro(); HWND initApp(HINSTANCE hInstance, HINSTANCE hPrevInstance, int nCmdShow) { HWND hWnd; /* window handle to return */ int iWinHeight; WORD wVer; char tmpstr[64]; /* first let's make sure we are running on 1.1 */ wVer = HIWORD(VideoForWindowsVersion()); if (wVer < 0x010a){ /* oops, we are too old, blow out of here */ MessageBeep(MB_ICONHAND); MessageBox(NULL, "Video for Windows version is too old", "LangPlay Error", MB_OK|MB_ICONSTOP); return FALSE; } if (!hPrevInstance){ WNDCLASS wndclass; wndclass.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon (hInstance, "AppIcon"); wndclass.hCursor = LoadCursor (NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); wndclass.lpszMenuName = szAppName; wndclass.lpszClassName = szAppName; if (!RegisterClass(&wndclass)){ MessageBox(NULL, "RegisterClass failure", szAppName, MB_OK); return NULL; } } iWinHeight = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYMENU) + (GetSystemMetrics(SM_CYFRAME) * 2); /* create the main window for the app */ hWnd = CreateWindow(szAppName, szAppName, //WS_SYSMENU | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 320, 240, NULL, NULL, hInstance, NULL); if (hWnd == NULL){ MessageBox(NULL, "CreateWindow failure", szAppName, MB_OK); return NULL; } /* Show the main window */ ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); /* create the movie window using MCIWnd that has no file open initially */ hwndMovie = MCIWndCreate(hWnd, hInstance, MCIWNDF_NOPLAYBAR |WS_CHILD |WS_VISIBLE | MCIWNDF_NOOPEN | MCIWNDF_NOERRORDLG | MCIWNDF_NOTIFYSIZE|MCIWNDF_NOTIFYMODE , NULL); if (!hwndMovie){ /* we didn't get the movie window, destroy the app's window and bail out */ DestroyWindow(hWnd); exitintro(); return NULL; } GetPrivateProfileStringCurrentDir("config.ini","intro","avifile",tmpstr,64); if (MCIWndOpen(hwndMovie, tmpstr, 0) == 0){ /* we opened the file o.k., now set up to */ /* play it. */ ShowWindow(hwndMovie, SW_SHOW); } else { /* generic error for open */ MessageBox(hWnd, "Unable to open Movie", NULL, MB_ICONEXCLAMATION|MB_OK); exitintro(); } MCIWndPlay(hwndMovie); return hWnd; } /*--------------------------------------------------------------+ | WinMain - main routine. | | | +--------------------------------------------------------------*/ int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdShow) { HWND hWnd; MSG msg; if ((hWnd = initApp(hInstance, hPrevInstance,nCmdShow)) == NULL) return 0; /* died initializing, bail out */ while (GetMessage(&msg, NULL, 0, 0)){ TranslateMessage(&msg); DispatchMessage(&msg); //MCIWndPlay(hwndMovie); } return msg.wParam; } /*--------------------------------------------------------------+ | WndProc - window proc for the app | | | +--------------------------------------------------------------*/ long FAR PASCAL WndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; RECT rect; POINT size; switch (message){ case WM_KEYDOWN: switch(wParam) { case VK_ESCAPE: exitintro(); break; } case WM_CREATE: return 0; case WM_INITMENUPOPUP: break; case WM_COMMAND: return 0; case WM_PAINT: BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); return 0; case WM_SIZE: break; case WM_DESTROY: exitintro(); return 0; case MCIWNDM_NOTIFYSIZE: GetWindowRect(hwndMovie,&rect); AdjustWindowRect(&rect,WS_OVERLAPPEDWINDOW |WS_CLIPCHILDREN,FALSE); size.x=rect.right-rect.left; size.y=rect.bottom-rect.top; rect.left=GetSystemMetrics(SM_CXSCREEN)/2-size.x/2; rect.right=rect.left+size.x; rect.top=GetSystemMetrics(SM_CYSCREEN)/2-size.y/2; rect.bottom=rect.top+size.y; SetWindowPos(hWnd,HWND_TOP,rect.left,rect.top,rect.right-rect.left,rect.bottom-rect.top,SWP_DRAWFRAME); break; case MCIWNDM_NOTIFYMODE: if((LONG)lParam==525) exitintro(); break; case WM_ACTIVATE: case WM_QUERYNEWPALETTE: case WM_PALETTECHANGED: // // Forward palette-related messages through to the MCIWnd, // so it can do the right thing. // if (hwndMovie) return SendMessage(hwndMovie, message, wParam, lParam); break; } /* switch */ return DefWindowProc(hWnd, message, wParam, lParam); } void exitintro() { char tmpstr[64]; MCIWndClose(hwndMovie); // close an open movie MCIWndDestroy(hwndMovie); // now destroy the MCIWnd window PostQuitMessage(0); GetPrivateProfileStringCurrentDir("config.ini","intro","startfile",tmpstr,64); WinExec(tmpstr,SW_SHOW); }
[ "sebastian.kotulla@gmx.de" ]
sebastian.kotulla@gmx.de
f53b646fbeacade31041f6c4e0f8ab54da35462d
81c0c928289110b4e0efda08e4372cf4e19a31ee
/core/src/db/insert/MemCollection.cpp
9231e5e101ded498b6ebdfc51b1ce32905420ba0
[ "Apache-2.0", "BSD-3-Clause", "MIT", "JSON", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference", "Zlib", "LicenseRef-scancode-public-domain" ]
permissive
AmyYH/milvus
f8f2de0ed103f0d8da1a6694c4094addec841442
d993bcc9894f30fd1bbf3a3b998bcaa7226260da
refs/heads/master
2022-12-12T15:58:18.188195
2020-08-18T08:50:51
2020-08-18T08:50:51
281,320,040
0
0
Apache-2.0
2020-07-21T06:55:25
2020-07-21T06:55:24
null
UTF-8
C++
false
false
12,245
cpp
// Copyright (C) 2019-2020 Zilliz. 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 "db/insert/MemCollection.h" #include <unistd.h> #include <algorithm> #include <chrono> #include <cstdlib> #include <ctime> #include <memory> #include <string> #include <fiu/fiu-local.h> #include "config/ServerConfig.h" #include "db/Utils.h" #include "db/snapshot/CompoundOperations.h" #include "db/snapshot/IterateHandler.h" #include "db/snapshot/Snapshots.h" #include "utils/CommonUtil.h" #include "utils/Log.h" #include "utils/TimeRecorder.h" namespace milvus { namespace engine { MemCollection::MemCollection(int64_t collection_id, const DBOptions& options) : collection_id_(collection_id), options_(options) { } Status MemCollection::Add(int64_t partition_id, const milvus::engine::VectorSourcePtr& source) { while (!source->AllAdded()) { std::lock_guard<std::mutex> lock(mutex_); MemSegmentPtr current_mem_segment; auto pair = mem_segments_.find(partition_id); if (pair != mem_segments_.end()) { MemSegmentList& segments = pair->second; if (!segments.empty()) { current_mem_segment = segments.back(); } } Status status; if (current_mem_segment == nullptr || current_mem_segment->IsFull()) { MemSegmentPtr new_mem_segment = std::make_shared<MemSegment>(collection_id_, partition_id, options_); STATUS_CHECK(new_mem_segment->CreateSegment()); status = new_mem_segment->Add(source); if (status.ok()) { mem_segments_[partition_id].emplace_back(new_mem_segment); } else { return status; } } else { status = current_mem_segment->Add(source); } if (!status.ok()) { std::string err_msg = "Insert failed: " + status.ToString(); LOG_ENGINE_ERROR_ << LogOut("[%s][%ld] ", "insert", 0) << err_msg; return Status(DB_ERROR, err_msg); } } return Status::OK(); } Status MemCollection::Delete(const std::vector<id_t>& ids) { // Locate which collection file the doc id lands in { std::lock_guard<std::mutex> lock(mutex_); for (auto& partition_segments : mem_segments_) { MemSegmentList& segments = partition_segments.second; for (auto& segment : segments) { segment->Delete(ids); } } } // Add the id to delete list so it can be applied to other segments on disk during the next flush for (auto& id : ids) { doc_ids_to_delete_.insert(id); } return Status::OK(); } Status MemCollection::EraseMem(int64_t partition_id) { std::lock_guard<std::mutex> lock(mutex_); auto pair = mem_segments_.find(partition_id); if (pair != mem_segments_.end()) { mem_segments_.erase(pair); } return Status::OK(); } Status MemCollection::Serialize(uint64_t wal_lsn) { TimeRecorder recorder("MemCollection::Serialize collection " + std::to_string(collection_id_)); if (!doc_ids_to_delete_.empty()) { while (true) { auto status = ApplyDeletes(); if (status.ok()) { break; } else if (status.code() == SS_STALE_ERROR) { std::string err = "ApplyDeletes is stale, try again"; LOG_ENGINE_WARNING_ << err; continue; } else { std::string err = "ApplyDeletes failed: " + status.ToString(); LOG_ENGINE_ERROR_ << err; return status; } } } doc_ids_to_delete_.clear(); std::lock_guard<std::mutex> lock(mutex_); for (auto& partition_segments : mem_segments_) { MemSegmentList& segments = partition_segments.second; for (auto& segment : segments) { auto status = segment->Serialize(wal_lsn); if (!status.ok()) { return status; } LOG_ENGINE_DEBUG_ << "Flushed segment " << segment->GetSegmentId() << " of collection " << collection_id_; } } mem_segments_.clear(); recorder.RecordSection("Finished flushing"); return Status::OK(); } int64_t MemCollection::GetCollectionId() const { return collection_id_; } size_t MemCollection::GetCurrentMem() { std::lock_guard<std::mutex> lock(mutex_); size_t total_mem = 0; for (auto& partition_segments : mem_segments_) { MemSegmentList& segments = partition_segments.second; for (auto& segment : segments) { total_mem += segment->GetCurrentMem(); } } return total_mem; } Status MemCollection::ApplyDeletes() { snapshot::ScopedSnapshotT ss; STATUS_CHECK(snapshot::Snapshots::GetInstance().GetSnapshot(ss, collection_id_)); snapshot::OperationContext context; context.lsn = lsn_; auto segments_op = std::make_shared<snapshot::CompoundSegmentsOperation>(context, ss); int64_t segment_iterated = 0; auto segment_executor = [&](const snapshot::SegmentPtr& segment, snapshot::SegmentIterator* iterator) -> Status { segment_iterated++; auto seg_visitor = engine::SegmentVisitor::Build(ss, segment->GetID()); segment::SegmentReaderPtr segment_reader = std::make_shared<segment::SegmentReader>(options_.meta_.path_, seg_visitor); // Step 1: Check delete_id in mem std::vector<id_t> delete_ids; { segment::IdBloomFilterPtr pre_bloom_filter; STATUS_CHECK(segment_reader->LoadBloomFilter(pre_bloom_filter)); for (auto& id : doc_ids_to_delete_) { if (pre_bloom_filter->Check(id)) { delete_ids.push_back(id); } } if (delete_ids.empty()) { return Status::OK(); } } std::vector<engine::id_t> uids; STATUS_CHECK(segment_reader->LoadUids(uids)); std::sort(delete_ids.begin(), delete_ids.end()); std::set<id_t> ids_to_check(delete_ids.begin(), delete_ids.end()); // Step 2: Mark previous deleted docs file and bloom filter file stale auto& field_visitors_map = seg_visitor->GetFieldVisitors(); auto uid_field_visitor = seg_visitor->GetFieldVisitor(engine::FIELD_UID); auto del_doc_visitor = uid_field_visitor->GetElementVisitor(FieldElementType::FET_DELETED_DOCS); auto del_docs_element = del_doc_visitor->GetElement(); auto blm_filter_visitor = uid_field_visitor->GetElementVisitor(FieldElementType::FET_BLOOM_FILTER); auto blm_filter_element = blm_filter_visitor->GetElement(); auto segment_file_executor = [&](const snapshot::SegmentFilePtr& segment_file, snapshot::SegmentFileIterator* iterator) -> Status { if (segment_file->GetSegmentId() == segment->GetID() && (segment_file->GetFieldElementId() == del_docs_element->GetID() || segment_file->GetFieldElementId() == blm_filter_element->GetID())) { segments_op->AddStaleSegmentFile(segment_file); } return Status::OK(); }; auto segment_file_iterator = std::make_shared<snapshot::SegmentFileIterator>(ss, segment_file_executor); segment_file_iterator->Iterate(); STATUS_CHECK(segment_file_iterator->GetStatus()); // Step 3: Create new deleted docs file and bloom filter file snapshot::SegmentFileContext del_file_context; del_file_context.field_name = uid_field_visitor->GetField()->GetName(); del_file_context.field_element_name = del_docs_element->GetName(); del_file_context.collection_id = segment->GetCollectionId(); del_file_context.partition_id = segment->GetPartitionId(); del_file_context.segment_id = segment->GetID(); snapshot::SegmentFilePtr delete_file; STATUS_CHECK(segments_op->CommitNewSegmentFile(del_file_context, delete_file)); std::string collection_root_path = options_.meta_.path_ + COLLECTIONS_FOLDER; auto segment_writer = std::make_shared<segment::SegmentWriter>(options_.meta_.path_, seg_visitor); std::string del_docs_path = snapshot::GetResPath<snapshot::SegmentFile>(collection_root_path, delete_file); snapshot::SegmentFileContext bloom_file_context; bloom_file_context.field_name = uid_field_visitor->GetField()->GetName(); bloom_file_context.field_element_name = blm_filter_element->GetName(); bloom_file_context.collection_id = segment->GetCollectionId(); bloom_file_context.partition_id = segment->GetPartitionId(); bloom_file_context.segment_id = segment->GetID(); engine::snapshot::SegmentFile::Ptr bloom_filter_file; STATUS_CHECK(segments_op->CommitNewSegmentFile(bloom_file_context, bloom_filter_file)); std::string bloom_filter_file_path = snapshot::GetResPath<snapshot::SegmentFile>(collection_root_path, bloom_filter_file); // Step 4: update delete docs and bloom filter { segment::IdBloomFilterPtr bloom_filter; STATUS_CHECK(segment_writer->CreateBloomFilter(bloom_filter_file_path, bloom_filter)); std::vector<engine::offset_t> delete_docs_offset; for (size_t i = 0; i < uids.size(); i++) { if (std::binary_search(ids_to_check.begin(), ids_to_check.end(), uids[i])) { delete_docs_offset.emplace_back(i); } else { bloom_filter->Add(uids[i]); } } STATUS_CHECK(segments_op->CommitRowCountDelta(segment->GetID(), delete_docs_offset.size(), true)); // Load previous delete_id and merge into 'delete_ids' segment::DeletedDocsPtr prev_del_docs; STATUS_CHECK(segment_reader->LoadDeletedDocs(prev_del_docs)); if (prev_del_docs) { auto& pre_del_offsets = prev_del_docs->GetDeletedDocs(); size_t delete_docs_size = delete_docs_offset.size(); for (auto& offset : pre_del_offsets) { if (!std::binary_search(delete_docs_offset.begin(), delete_docs_offset.begin() + delete_docs_size, offset)) { delete_docs_offset.emplace_back(offset); } } } std::sort(delete_docs_offset.begin(), delete_docs_offset.end()); auto delete_docs = std::make_shared<segment::DeletedDocs>(delete_docs_offset); STATUS_CHECK(segment_writer->WriteDeletedDocs(del_docs_path, delete_docs)); STATUS_CHECK(segment_writer->WriteBloomFilter(bloom_filter_file_path, bloom_filter)); } delete_file->SetSize(CommonUtil::GetFileSize(del_docs_path + codec::DeletedDocsFormat::FilePostfix())); bloom_filter_file->SetSize( CommonUtil::GetFileSize(bloom_filter_file_path + codec::IdBloomFilterFormat::FilePostfix())); return Status::OK(); }; auto segment_iterator = std::make_shared<snapshot::SegmentIterator>(ss, segment_executor); segment_iterator->Iterate(); STATUS_CHECK(segment_iterator->GetStatus()); if (segment_iterated == 0) { return Status::OK(); // no segment, nothing to do } fiu_do_on("MemCollection.ApplyDeletes.RandomSleep", sleep(1)); return segments_op->Push(); } uint64_t MemCollection::GetLSN() { return lsn_; } void MemCollection::SetLSN(uint64_t lsn) { lsn_ = lsn; } } // namespace engine } // namespace milvus
[ "noreply@github.com" ]
AmyYH.noreply@github.com
128ed46c64486585829cce0b0c2d3eb8e850b7a4
2e86b8c70e2d3b1b98b7acab5ffe86137e8fb363
/vga_train/snd/step.cpp
1ef7d06f80f154a9dfe01454d5f31ad87c856011
[]
no_license
pavel-krivanek/PicoVGA
c5ecfe768395f48485a4626453a655fd97ead04a
c09c387abff827c0d59cc70db7fe5e9fde3c6e76
refs/heads/main
2023-05-29T09:22:21.481369
2021-06-10T17:07:49
2021-06-10T17:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,832
cpp
#include "include.h" // sound format: PCM mono 8-bit 22050Hz const u8 StepSnd[2243] = { 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7C, 0x7E, 0x7C, 0x7E, 0x7C, 0x7D, 0x88, 0xFF, 0x68, 0x55, 0xFF, 0x79, 0x4E, 0xFF, 0x8B, 0x44, 0xFF, 0x97, 0x41, 0xFF, 0xAB, 0x41, 0xFF, 0xBF, 0x3D, 0xF6, 0xCB, 0x3A, 0xE9, 0xD8, 0x37, 0xE2, 0xF1, 0xF9, 0x88, 0x5A, 0xB9, 0xF2, 0xF7, 0x56, 0x7F, 0xC5, 0xFF, 0xC1, 0x45, 0x9B, 0xDC, 0xFF, 0x85, 0x53, 0xAE, 0xF2, 0xF1, 0x5C, 0x68, 0xC2, 0xF9, 0xDE, 0xD7, 0xE4, 0xB6, 0x35, 0x9A, 0x7B, 0xF6, 0xDD, 0xE5, 0x7E, 0x41, 0x90, 0x83, 0xFF, 0xC2, 0xDF, 0x46, 0x5B, 0x74, 0xA2, 0xF8, 0xB7, 0xC2, 0x20, 0x91, 0xF8, 0xB0, 0xCE, 0x60, 0x34, 0x78, 0x5B, 0xE4, 0xC1, 0xB4, 0x94, 0x17, 0x66, 0x4C, 0xA0, 0xDE, 0x95, 0xB5, 0x2B, 0x3D, 0x51, 0x65, 0xE0, 0x9F, 0x9B, 0x9A, 0x99, 0x9F, 0x96, 0xA9, 0x64, 0x16, 0x58, 0x43, 0x52, 0x3F, 0xD1, 0xA1, 0x8F, 0x8A, 0x99, 0x63, 0x0A, 0x49, 0x37, 0x47, 0x2F, 0xBB, 0xA1, 0x7E, 0x88, 0x82, 0x8A, 0x85, 0x8D, 0x86, 0x94, 0x70, 0x0A, 0x3F, 0x39, 0x40, 0x34, 0x3B, 0x2D, 0xBD, 0x94, 0x7B, 0x7E, 0x82, 0x7C, 0x8E, 0x4F, 0x0B, 0x3D, 0x31, 0x38, 0x2F, 0x32, 0x2C, 0x2D, 0x29, 0x29, 0x26, 0x25, 0x23, 0x22, 0x20, 0x1F, 0x1E, 0x1D, 0x1C, 0x1C, 0x1B, 0x1A, 0x1A, 0x19, 0x19, 0x19, 0x18, 0x18, 0x19, 0x18, 0x19, 0x19, 0x19, 0x1A, 0x1A, 0x1B, 0x1B, 0x1C, 0x1D, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x26, 0x27, 0x28, 0x29, 0x2B, 0x2C, 0x2E, 0x2F, 0x31, 0x32, 0x34, 0x36, 0x37, 0x39, 0x3B, 0x3C, 0x3E, 0x40, 0x41, 0x43, 0x45, 0x47, 0x48, 0x4A, 0x4C, 0x4E, 0x50, 0x51, 0x53, 0x55, 0x57, 0x58, 0x5A, 0x5C, 0x5E, 0x5F, 0x61, 0x63, 0x65, 0x66, 0x68, 0x69, 0x6B, 0x6D, 0x6E, 0x70, 0x71, 0x73, 0x74, 0x76, 0x77, 0x79, 0x7A, 0x7B, 0x7D, 0x7E, 0x7F, 0x80, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x8F, 0x90, 0x91, 0x91, 0x92, 0x93, 0x93, 0x94, 0x94, 0x95, 0x95, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, 0x97, 0x97, 0x97, 0x97, 0x96, 0x96, 0x96, 0x95, 0x95, 0x95, 0x94, 0x94, 0x93, 0x93, 0x93, 0x92, 0x92, 0x91, 0x91, 0x90, 0x90, 0x8F, 0x8F, 0x8E, 0x8E, 0x8E, 0x8D, 0x8D, 0x8C, 0x8B, 0x8B, 0x8B, 0x8A, 0x8A, 0x89, 0x89, 0x88, 0x88, 0x87, 0x86, 0x86, 0x85, 0x85, 0x85, 0x84, 0x84, 0x83, 0x83, 0x82, 0x82, 0x81, 0x81, 0x81, 0x80, 0x80, 0x7F, 0x7F, 0x7E, 0x7E, 0x7E, 0x7D, 0x7D, 0x7D, 0x7C, 0x7C, 0x7C, 0x7B, 0x7B, 0x7B, 0x7A, 0x7A, 0x7A, 0x7A, 0x79, 0x79, 0x79, 0x79, 0x78, 0x78, 0x78, 0x78, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x79, 0x79, 0x79, 0x79, 0x79, 0x79, 0x7A, 0x7A, 0x7A, 0x7A, 0x7A, 0x7A, 0x7B, 0x7B, 0x7B, 0x7B, 0x7B, 0x7B, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x82, 0x81, 0x81, 0x82, 0x81, 0x82, 0x82, 0x81, 0x82, 0x81, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x81, 0x81, 0x82, 0x81, 0x82, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x80, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7E, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7F, 0x7F, 0x7F, 0x7F, 0x7E, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7E, 0x7E, 0x7F, 0x7F, 0x7E, 0x7F, 0x7E, 0x7F, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7F, 0x7E, 0x7F, 0x7F, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7F, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, 0x7D, };
[ "Panda38@seznam.cz" ]
Panda38@seznam.cz
8b9fa02c363dd4f82ddd8cb1b2c25dd19d53b15e
5880f1fa2a1d572050c2ccd63a3761dd1f75caa1
/07.Strings/02.AnagramsUsingCountCharacters.cpp
2a8f8732a159d5210fe91020481e9f454b626179
[]
no_license
mayank8200/Data-Structure-and-Algo-for-Interview-Preparation
3bd7856530da92182a4afde0a15cfc6a932fc7f6
9e830ec03c8dec5f4069168b290fcaff8d1167ea
refs/heads/master
2022-10-11T23:20:22.105296
2020-06-09T09:20:02
2020-06-09T09:20:02
263,544,924
3
0
null
null
null
null
UTF-8
C++
false
false
730
cpp
#include <bits/stdc++.h> using namespace std; bool anagrams(string s1,string s2) { int a = s1.length(); int b = s2.length(); if(a!=b) { return false; } int c1[256] = {0}; int c2[256] = {0}; for(int i=0;i<a;i++) { c1[s1[i]]++; c2[s2[i]]++; } for(int i=0;i<256;i++) { if(c1[i]!=c2[i]) return false; } return true; } int main() { string s1,s2; cout << "Enter two strings to check:"; cin >> s1 >> s2; if (anagrams(s1, s2)) cout << "The two strings are anagram of each other"; else cout << "The two strings are not anagram of each other"; return 0; }
[ "41484766+mayank8200@users.noreply.github.com" ]
41484766+mayank8200@users.noreply.github.com
64a23bce7022e9d1e6f16cd00723d3412807879e
62d2961f1e1af919eaa0b83b559a8a4fec342287
/LT228/LT228.cpp
196bbe8cb88b6a324eb75cad7f77de3f30100141
[]
no_license
z7059652/LT228
9b9109fcf7433e590257ee66905e40f3c720992e
0c9fdd0df68fbd1597626577aff9fa2c84748e8c
refs/heads/master
2021-01-21T14:08:51.845878
2016-03-31T02:02:35
2016-03-31T02:02:35
41,524,791
0
0
null
null
null
null
UTF-8
C++
false
false
1,385
cpp
// LT228.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <vector> #include <string> using namespace std; void stringformat(string& str,int a,int b) { char buf[10]; memset(buf, 0, 10); if (a==b) { sprintf(buf, "%d", a); } else sprintf(buf, "%d->%d", a, b); str = buf; } vector<string> summaryRanges(vector<int>& nums) { vector<string> res; if (nums.size() == 0) { return res; } int startpos = 0, endpos = 0; int ifirst, ilast; for (int i = 0; i < nums.size() - 1; i++) { // ifirst = ilast = nums[i]; startpos = endpos = i; while (i < nums.size() - 1) { if (nums[i + 1] - nums[i] == 1) { i++; endpos = i; } else { string temp; stringformat(temp, nums[startpos], nums[endpos]); res.push_back(temp); break; } } } string temp; if (endpos == nums.size() - 1) stringformat(temp, nums[startpos], nums[endpos]); else stringformat(temp, nums[endpos + 1], nums[endpos + 1]); res.push_back(temp); return res; } int _tmain(int argc, _TCHAR* argv[]) { vector<int> nums; nums.push_back(0); nums.push_back(1); nums.push_back(2); nums.push_back(3); nums.push_back(5); nums.push_back(6); nums.push_back(7); nums.push_back(8); nums.push_back(11); nums.push_back(12); nums.push_back(13); nums.push_back(18); vector<string> res = summaryRanges(nums); return 0; }
[ "7059652@163.com" ]
7059652@163.com
413539e5136e5d91176f0d572b159e5466723e56
845d3e85651ad3bf8c730b0a3add807894631119
/Satisfiability/Solvers/OKsolver/SAT2002/plans/milestones.hpp
22e3ff6ef041bc0ce53b95c968f26a003eabe808
[]
no_license
PJames/oklibrary
6516e1150fd1d040a91a2ba7e48d9b3eba976edf
38983feadd7e54ab19a2c2a94b6b39887265de17
refs/heads/master
2020-12-24T13:20:36.195708
2008-10-29T21:09:01
2008-10-29T21:09:01
69,392
1
0
null
null
null
null
UTF-8
C++
false
false
5,018
hpp
// Oliver Kullmann, 18.8.2007 (Swansea) /* Copyright 2007, 2008 Oliver Kullmann This file is part of the OKlibrary. OKlibrary is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation and included in this library; either version 3 of the License, or any later version. */ /*! \file Solvers/OKsolver/SAT2002/plans/milestones.hpp \module_version OKsolver/SAT2002 0.9.4 (16.9.2008) \par Version 0.9.5 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - OUTPUTTREEDATAXML \par Version 0.9.6 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Documentation problems - Language standards \par Version 0.9.7 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Buildsystem \par Version 0.9.8 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Complete the help facilities of the OKsolver \par Version 0.9.9 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Write docus-pages \par Version 1.0 \par Create a tag, stating that the basically unaltered original OKsolver has now been made fully available. \par Version 1.0.1 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Add doxygen-documentation - Eliminate old history in code \par Version 1.0.2 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Create systematic application tests \par Version 1.0.3 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Add asserts throughout \par Version 1.0.4 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Investigate unit-testing \par Version 1.0.5 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Correct computation of basic statistics \par Version 1.0.6 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Incorrect output of monitoring-data to files \par Version 1.1 \par The fully tested and specified original OKsolver (parallel in C and in Maxima). \par Version 1.2.1 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Improve statistics \par Version 1.2.2 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Declare variable as close to their first usage as possible \par Version 1.2.3 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Use const-qualification \par Version 1.2.4 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Use restrict-qualification \par Version 1.2.5 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Elimination of compile-time options \par Version 1.3 \par The fully cleaned-up and documented original OKsolver. \par Version 1.4 \par Make nearly everything also available at the Maxima-level, and make sure that both levels fully coincide. \par Version 1.5 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Enable finding all solutions \par Version 1.5.1 \par In Solvers/OKsolver/SAT2002/plans/general.hpp the following topics are handled: - Apply time-measurements \par Version 1.6 \par We have timing-date available. \par Version 1.7 \par Document the extensive database-data. \par Version 2.0 \par Now the original OKsolver is also fully reflected and fully specified. ------------------------------------------------------------------------------------------------------------------------------------- \par Version history - 0.9 : 18.8.2007; initial version number (the old OKsolver mainly unchanged since SAT2002; a bug found by Marijn Heule showed up with newer versions of gcc) - 0.9.1 : 20.8.2007; two bugs corrected, linking behaviour corrected, basic code maintenance performed, and basic application tests written and executed. The OKsolver in the standard version appears now to be bug-free. - 0.9.2 : 14.9.2007; basic tests for main variants established. Now also the main variants appear to be bug-free. - 0.9.3 : 22.9.2007; completed planning for counting all satisfying assignments (implementation postponed), and on the way also code and documentation maintenance. - 0.9.4 : 16.9.2008; various "spontaneous" workings: improved the build, extended plans, created application tests, basic code overhauls, using SIGINT instead of SIGUSR2, better documentation, corrected output of statistics. */
[ "O.Kullmann@Swansea.ac.uk" ]
O.Kullmann@Swansea.ac.uk
43cefc03da549c578619f90e9a87150ce85fc211
893f7883bc472570e1c407ccdee6da9f3df78580
/src/assert/test/testAssertWithNDEBUG.h
9d769f6f327d25421365deee04076c2ed300c03d
[ "MIT" ]
permissive
dpicken/utils
a7bde29d760daff4947a599a20db7d0a640b5c08
53d214cd81d45c29578e3165c1b188057e6ac9e1
refs/heads/master
2021-07-17T07:46:05.881675
2020-04-23T22:58:58
2020-04-30T04:52:58
133,750,175
0
0
null
null
null
null
UTF-8
C++
false
false
237
h
#ifndef assert_test_testAssertWithNDEBUG_h #define assert_test_testAssertWithNDEBUG_h namespace assert { namespace test { void testAssertWithNDEBUG(); } } // namespace assert::test #endif // ifndef assert_test_testAssertWithNDEBUG_h
[ "dpicken@users.noreply.github.com" ]
dpicken@users.noreply.github.com
8e7f62fb16b3cf57f23d3eaaf66833a9fdd10fb9
70de48a6e65e468e2b30a0c0fd74e591b242a16c
/Basic Searching and Sorting Algorithms/Selection Sort/selection_sort(iterative).cpp
318cddf2fbf3a01dc79a786924db71a5d3af201f
[]
no_license
ihjohny/Algorithms-Implementation
130be91380f96af05fdaada813d57321b859d24b
c30aefdee716c4a45780299b10f24b5351c01ea2
refs/heads/master
2020-03-22T10:18:03.439914
2019-10-22T06:29:59
2019-10-22T06:29:59
139,894,399
0
0
null
null
null
null
UTF-8
C++
false
false
721
cpp
//selection_sort(iterative) /* * Unstable * In place * Worst case complexity O(n^2) * Space complexityO (1) * */ #include<iostream> #include<cstdio> #define SZ 10 using namespace std; int main() { int Arra[SZ]={777,55,45,2,14,878,4,145,14,99}; int i,j,k,temp; int count=0; //for counting time complixty (how many time the loop iterate) for(i=0;i<SZ-1;i++) { for(j=i+1;j<SZ;j++) { count++; //for counting loop intertion if(Arra[j]<Arra[k]) { k=j; } } if(k!=i) { //swaping temp=Arra[i]; Arra[i]=Arra[k]; Arra[k]=temp; } } //print for(i=0;i<SZ;i++) { cout<<Arra[i]<<" "; } cout<<endl; cout<<"time compxity (loop iteration) "<<count<<endl; return 0; }
[ "ihjony23@gmail.com" ]
ihjony23@gmail.com
d03a49d30c5c9323359bc7b5c8cf5d200d488d8b
c3ffa07567d3d29a7439e33a6885a5544e896644
/CodeForce/100482-C.cpp
4d060a3635c286f969057e4f8b9bef66a9ae6650
[]
no_license
a00012025/Online_Judge_Code
398c90c046f402218bd14867a06ae301c0c67687
7084865a7050fc09ffb0e734f77996172a93d3ce
refs/heads/master
2018-01-08T11:33:26.352408
2015-10-10T23:20:35
2015-10-10T23:20:35
44,031,127
0
0
null
null
null
null
UTF-8
C++
false
false
828
cpp
#include<stdio.h> #include<algorithm> #include<string.h> using namespace std; char s[200010] ; main() { int T,cnt=0,a[30]; scanf("%d",&T) ; while(++cnt && cnt<=T) { gets(s) ; int q ; while(s[0]=='\0' || s[0]==49 || s[0]=='\n') gets(s) ; printf("Case #%d:\n",cnt) ; scanf("%d",&q) ; while(q--) { char c; int l,r ; scanf("%c",&c) ; while(c!='g' && c!='s') scanf("%c",&c) ; scanf("%d %d",&l,&r) ; if(c=='s') sort(s+l,s+r+1) ; else { memset(a,0,sizeof(a)) ; for(int i=l;i<=r;i++) a[s[i]-'A'+1]++ ; for(int i=1;i<=26;i++) printf("%d ",a[i]); printf("\n") ; } } } }
[ "a00012025@gmail.com" ]
a00012025@gmail.com
2032a759845d3a2b24b6361ef5b463f0727a655f
9ded4c4fc135c2154ea85bc6a8fb4dcf2ce84863
/wikioi/1701.cpp
ec4b5147c274d28b18cf32eea483d81965b8083e
[]
no_license
yanhuanwang/codekata
5389a1e958c7c2d79582098b89a26648dcc188ba
9369f7461ddcc731b318bc701b2f17ad2990f285
refs/heads/master
2016-09-06T01:17:37.255599
2014-06-19T12:31:06
2014-06-19T12:31:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,623
cpp
///* // * A.cpp // * // * Created on: Apr 26, 2014 // * Author: ecaiyan // */ // //#include <cstdio> //#include <cstdlib> //#include <memory.h> //#include <algorithm> //#include <string> //#include <map> ////#include <unordered_map> ////#include <unordered_set> //#include <set> //#include <vector> //#include <cmath> //#include <climits> //#include <queue> //#include <cassert> //#include <iostream> //#include <sstream> //#include <utility> //#include <bitset> //using namespace std; //#define PI 3.14159265358979323846264338327950288 //vector<string> Tokenize(string s, string ch) { // vector<string> ret; // for (int p = 0, p2; p < s.size(); p = p2 + 1) { // p2 = s.find_first_of(ch, p); // if (p2 == -1) // p2 = s.size(); // if (p2 - p > 0) // ret.push_back(s.substr(p, p2 - p)); // } // return ret; //} //int my_abs(int a) { // int i = a >> 31; // return ((a ^ i) - i); //} // //vector<int> TokenizeInt(string s, string ch) { // vector<int> ret; // vector<string> p = Tokenize(s, ch); // for (int i = 0; i < p.size(); i++) // ret.push_back(atoi(p[i].c_str())); // return ret; //} //int process(int A, int B, int K) { // int res = 0; // return res; //} //unsigned long f[50005] = { 0, 1 }; //void set1() { // unsigned long i = 2, j, k = 2, p = 2; // while (1) { // for (j = 1; j <= p; j++) { // f[i] = (f[i - 1] + k) % 10000; // i++; // if (i > 50000) // return; // } // k = k * 2; // k = k % 10000; // p++; // } //} //int main() { // set1(); // long n; // cin>>n; // cout<<f[n]; //// while (scanf("%ld", &n) != EOF) { //// printf("%ld\n", f[n]); //// } //// return 0; // return 0; //} //
[ "martin.yan.seu@gmail.com" ]
martin.yan.seu@gmail.com
67233f2d9b8c826b442bf1d8c6cae68cb4f18e05
88001ef8e6023558ea35870b431ee207b5c48f3e
/Source/ToonTanks/Actors/ProjectileBase.h
bbca002033ffa9ce3ced40784955244ef47e4222
[]
no_license
ZhiyuanGu/ToonTanks
ca153cdceb2fac29feccfac0222673764cd86544
aa68629ce200c01c42c8f7d27269547fccb7c75b
refs/heads/main
2023-06-17T21:53:49.008085
2021-06-27T22:18:35
2021-06-27T22:18:35
380,847,372
0
0
null
null
null
null
UTF-8
C++
false
false
1,901
h
// Zhiyuan Gu 2020 All Rights Reserved #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "ProjectileBase.generated.h" class UProjectileMovementComponent; class UParticleSystemComponent; UCLASS() class TOONTANKS_API AProjectileBase : public AActor { GENERATED_BODY() private: // COMPONENTS UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true")) UProjectileMovementComponent* ProjectileMovement; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true")) UStaticMeshComponent* ProjectileMesh; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true")) UParticleSystemComponent* ParticleTrail; // use component for trail so it can be attached and follow the projectile movement // VARIABLES UPROPERTY(EditAnywhere, Category = "Effects") UParticleSystem* HitParticle; UPROPERTY(EditDefaultsOnly, Category = "Damage") TSubclassOf<UDamageType> DamageType; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Move", meta = (AllowPrivateAccess = "true")) float MovementSpeed = 1300.0f; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Damage", meta = (AllowPrivateAccess = "true")) float Damage = 50.0f; UPROPERTY(EditAnywhere, Category = "Effects") USoundBase* LaunchSound; UPROPERTY(EditAnywhere, Category = "Effects") USoundBase* HitSound; UPROPERTY(EditAnywhere, Category = "Effects") TSubclassOf<UCameraShake> HitShake; // FUNCTIONS UFUNCTION() void OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit); public: // Sets default values for this actor's properties AProjectileBase(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; };
[ "42496605+ZhiyuanGu@users.noreply.github.com" ]
42496605+ZhiyuanGu@users.noreply.github.com
494a99e22d762554335b6f084408077c6a5f00c1
dff1748a78a317af81cc4e2a721bcda9915a538b
/Regelungscontroller-neu2/IO.ino
a0f5e59cfe16dd7ed8a00a1dcfc0e08cb69735e8
[]
no_license
lumascet/supercharger
1985cdd53e2ba4fd0fa4194c4efbab1d7b134018
2f936554cb3002a4903d4be40527fe933a493038
refs/heads/master
2020-07-30T01:10:25.450349
2020-05-15T14:58:50
2020-05-15T14:58:50
210,030,994
0
0
null
null
null
null
UTF-8
C++
false
false
1,766
ino
//---Input & Output operations--- void initPins(){ //PIN Setup pinMode(PIN_PWOK, INPUT); pinMode(PIN_PSON, OUTPUT); digitalWrite(PIN_PSON, HIGH); pinMode(PIN_RX, INPUT_PULLUP); pinMode(PIN_TX, INPUT_PULLUP); pinMode(PIN_VSENSE, INPUT); pinMode(PIN_LEDCURR, OUTPUT); digitalWrite(PIN_LEDCURR, LOW); pinMode(PIN_LEDVOLT, OUTPUT); digitalWrite(PIN_LEDVOLT, LOW); pinMode(PIN_DACSS, OUTPUT); digitalWrite(PIN_DACSS, HIGH); pinMode(PIN_ADCSS, OUTPUT); digitalWrite(PIN_ADCSS, HIGH); pinMode(PIN_CNV, OUTPUT); adcConversion(); pinMode(PIN_BUSY, INPUT); } void setOutput(bool state){//set output State if(state) digitalWrite(PIN_PSON, LOW); else digitalWrite(PIN_PSON, HIGH); } void changeMode(uint8_t mode){//change ADC inputs according to mode if(output_state == 0){ adc_voltage_port = 0; return; } switch(mode){ case 0: adc_voltage_port = 0; adc_current_port = 3; Serial.println("Mode 0"); break; case 1: if(external_measure)adc_voltage_port = 1; else adc_voltage_port = 2; adc_current_port = 3; Serial.println("Mode 1"); break; case 2: if(external_measure)adc_voltage_port = 5; else adc_current_port = 4; adc_current_port = 3; Serial.println("Mode 2"); break; case 3: //not implemented break; } } void fanState(bool state){//normal or high fan state if (state) { controlStatusRegister |= (1 << FAN_HI_BIT); setControlStatusRegister(controlStatusRegister); // SET FAN HIGH delay(I2C_MESSAGE_DELAY); } else { controlStatusRegister &= ~(1 << FAN_HI_BIT); setControlStatusRegister(controlStatusRegister); // SET FAN LOW delay(I2C_MESSAGE_DELAY); } }
[ "lukas.schroeer@gmx.at" ]
lukas.schroeer@gmx.at
9e7aa2a14024f4050fae1cb37fa93bb6736fe185
79eb737b20cfd332c84d5a6926365868f94ebdad
/src/PortWriter.cpp
81f43bf841943ea35b896da45e75ec6d74ee8f5a
[]
no_license
johnty/libYARP_OS_iOS
70d6555d8e0bc05b7feaa8711fca6efe9277e16c
65bc7bf382e3de1004acff408b110808da3ff9c0
refs/heads/master
2020-08-26T20:08:47.955399
2014-02-12T01:02:00
2014-02-12T01:02:00
16,746,103
1
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* * Copyright (C) 2006 RobotCub Consortium * Authors: Paul Fitzpatrick * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT */ #include <yarp/os/PortWriter.h> yarp::os::PortWriter::~PortWriter() { } void yarp::os::PortWriter::onCompletion() { } void yarp::os::PortWriter::onCommencement() { }
[ "johntywang@gmail.com" ]
johntywang@gmail.com
9ebdad0ecb0eb9aabdb8894534caf73b2b33f6d2
b8c4c902e8ac17a59719efedb87efb79c56394db
/oop/VirtualFunctions/CoutOperator.cpp
06e2235f5a6803b66230af9c04fdf0ed0da06360
[]
no_license
dibolsoni/LearningCpp
ab61a87d9c45b190f65e7aff8616ca9bee6565b9
d485a7d06183f0df9d188c4326105ff76c89ce76
refs/heads/master
2023-08-20T08:34:11.917654
2021-10-13T18:45:38
2021-10-13T18:45:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
969
cpp
#include <iostream> class Base { public: Base() {} // Here's our overloaded operator<< friend std::ostream& operator<<(std::ostream &out, const Base &b) { // Delegate printing responsibility for printing to member function print() return b.print(out); } // We'll rely on member function print() to do the actual printing // Because print is a normal member function, it can be virtualized virtual std::ostream& print(std::ostream& out) const { out << "Base"; return out; } }; class Derived : public Base { public: Derived() {} // Here's our override print function to handle the Derived case virtual std::ostream& print(std::ostream& out) const override { out << "Derived"; return out; } }; int main() { Base b; std::cout << b << '\n'; Derived d; std::cout << d << '\n'; // note that this works even with no operator<< that explicitly handles Derived objects Base &bref = d; std::cout << bref << '\n'; return 0; }
[ "dibolsoni@gmail.com" ]
dibolsoni@gmail.com
e6b9db3b3e728d14803a2acfc24e0cb2b5aee303
b227d23f889f5dc04b7eef4bc3eb514732ccef55
/PTA/PAT_A/Cpp11/A1015_AC.cc
f75a5d2e720596508a2f1b8d46198c2cdde3a241
[ "MIT" ]
permissive
StrayDragon/OJ-Solutions
e5dd953781237197b98fa83711a818cd705c3fdc
b31b11c01507544aded2302923da080b39cf2ba8
refs/heads/master
2020-04-26T17:17:04.605568
2019-12-24T08:03:18
2019-12-24T08:03:18
173,708,012
1
0
null
null
null
null
UTF-8
C++
false
false
915
cc
// --- // id : 1015 // title : Reversible Primes // difficulty : Easy // score : 20 // tag : TODO // keyword : TODO // status : AC // from : PAT (Advanced Level) Practice // --- #include <cmath> #include <iostream> bool is_prime(int n) { if (n <= 1) return false; int bound = (int)std::sqrt(1.0 * n); for (int i = 2; i <= bound; ++i) if (n % i == 0) return false; return true; } int digits[110]; int reverse_redix_convert(int n, int d) { int len = 0; do { digits[len++] = n % d; n /= d; } while (n != 0); for (int i = 0; i < len; i++) { n = n * d + digits[i]; } return n; } using namespace std; int main() { int n, d; while (true) { cin >> n; if (n < 0) break; cin >> d; if (is_prime(n) && is_prime(reverse_redix_convert(n, d))) cout << "Yes\n"; else cout << "No\n"; } return 0; }
[ "straydragonl@foxmail.com" ]
straydragonl@foxmail.com
2cb5aab6457963a2bb65d0b02f65951196504d48
97d1bfba6adafc0fbdd68bdfbeb314d33aa364be
/astar/2012-2013/121211/b/b.cpp
f63f0ca4e44f72cbb340499d73623a084df04f9b
[]
no_license
github188/MyCode-1
26069f08222b154c08308a72a61f8e9f879a447e
2227b9dd9a13114a1b2b294c3e70253b16f88538
refs/heads/master
2020-12-24T11:24:54.215740
2014-04-21T04:15:54
2014-04-21T04:15:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,736
cpp
#include<stdio.h> #define p 2012 int a[251],c[2001][2001],f[251][2001][2],h[2012][2012],ans[251]; int main() { a[1]=1; for (int i=2;i<=250;i++) a[i]=a[i-1]+2; for (int i=0;i<p;i++) for (int j=0;j<p;j++) h[i][j]=i*j%p; c[0][0]=1; for (int i=1;i<=2000;i++) for (int j=0;j<=2000;j++) { c[i][j]=c[i-1][j]; if (j>0) c[i][j]+=c[i-1][j-1]; if (c[i][j]>=p) c[i][j]-=p; } f[1][0][0]=f[1][1][1]=1; for (int i=2;i<=250;i++) for (int j=0;j<=a[i];j++) for (int k=0;(k<=a[i]-j)&&(k<=a[i-1]);k++) { if (a[i]-k-1>=j) { f[i][j][0]+=h[f[i-1][k][0]][c[a[i]-k-1][j]]; if (f[i][j][0]>=p) f[i][j][0]-=p; if (a[i]-k-2>=j) { f[i][j][0]+=h[f[i-1][k][1]][c[a[i]-k-2][j]]; if (f[i][j][0]>=p) f[i][j][0]-=p; } } if (j>0) { f[i][j][1]+=h[f[i-1][k][0]][c[a[i]-k-1][j-1]]; if (f[i][j][1]>=p) f[i][j][1]-=p; if (a[i]-k-1>=j) { f[i][j][1]+=h[f[i-1][k][1]][c[a[i]-k-2][j-1]]; if (f[i][j][1]>=p) f[i][j][1]-=p; } } } for (int i=1;i<=250;i++) { for (int j=0;j<=a[i];j++) { ans[i]+=f[i][j][0]; if (ans[i]>=p) ans[i]-=p; ans[i]+=f[i][j][1]; if (ans[i]>=p) ans[i]-=p; } int tmp=1; for (int k=0;k<4;k++) tmp=tmp*ans[i]%p; ans[i]=tmp; } int n; while (scanf("%d",&n)!=EOF) { printf("%d\n",ans[n/2]); } return 0; }
[ "wcwswswws@gmail.com" ]
wcwswswws@gmail.com
06a865379f6476139a32622c57b134feb32a8877
8854f8f28b44f16b136a8d728c397b22ccbd3599
/chapter_3/3.11.cpp
339bbcd64edea0494d638477d0cc781de42cc6d8
[]
no_license
Hannahhiendo/C-programming
33bc1a13b05421a0daca727c1931134ea1c89b79
a106792dc68dd19ffd10674d29631c7b82538d4b
refs/heads/master
2021-07-09T10:48:57.538146
2019-02-14T03:42:04
2019-02-14T03:42:04
144,395,449
1
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
#include <iostream> #include <cstdlib> using namespace std; int main () { int income = 10500; double tax; if ( income <= 10000) tax = income * 0.1; else if (income > 10000 && income <= 20000) tax = 1000 + (income - 10000) * 0.15; cout << tax << '\n'; return 0; }
[ "marinahiendo@gmail.com" ]
marinahiendo@gmail.com
cf9a69466e94f8f5753d83b7db8e5ac25b40b19b
044f85c8f00da4ad6001ed53363d829e034849a8
/32.cpp
0919c8095f48afeda42a655770cd0eac914f7ebd
[]
no_license
anand9git/DSA-code
877c30d779d9de492d29f58ab37650105b070395
e90a64ee8469754eda8d734e203ea16d4c53f174
refs/heads/master
2023-02-27T17:08:40.928070
2021-02-03T18:12:46
2021-02-03T18:12:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
541
cpp
#include <bits/stdc++.h> #include <iostream> using namespace std; int main(){ //program to find first row with max no of 1s if all rows are sorted and contain only 0 and 1 in O(m+n) time. int m, n; cin>>m>>n; int arr[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++)cin>>arr[i][j]; } int ans = 0; int j = n-1; for(int i=0;i<m;i++){ while(j>=0 && arr[i][j]==1){ j--; ans = i; } } if(arr[ans][j+1]==0) cout<<-1; cout<<ans<<endl; return 0; }
[ "aggarwalanand9@gmail.com" ]
aggarwalanand9@gmail.com
e366f7f42b16bd07146cda27c3a280f0d70d704a
d508027427b9a11a6bab0722479ee8d7b7eda72b
/src/dbghlp/chart.cpp
9d1a5ac99f58dabbba39b0dd2a31be2f3b40ccbc
[]
no_license
gaoyakun/atom3d
421bc029ee005f501e0adb6daed778662eb73bac
129adf3ceca175faa8acf715c05e3c8f099399fe
refs/heads/master
2021-01-10T18:28:50.562540
2019-12-06T13:17:00
2019-12-06T13:17:00
56,327,530
5
0
null
null
null
null
UTF-8
C++
false
false
11,764
cpp
#include "StdAfx.h" #include <ATOM_thread.h> #include "stl.h" #include "chart.h" #if defined(_MSC_VER) # pragma warning(disable:4786) #endif #define WMU_CS_CREATE (WM_APP + 1) #define WMU_CS_DESTROY (WM_APP + 2) #define WMU_CS_SHOW (WM_APP + 3) #define WMU_CS_UPDATE (WM_APP + 4) struct ChartThreadParams { DWORD request; ATOM_Chart *chart; bool isshown; char name[256]; unsigned w; unsigned h; unsigned vw; unsigned vh; unsigned ww; unsigned wh; HANDLE hRequestEvent; HANDLE hFinishEvent; ATOM_FastMutex lock; }; static HANDLE chartserviceEndEvent = 0; static ATOM_VECTOR<ChartThreadParams> chartserviceParamsIn; static ATOM_VECTOR<ChartThreadParams> chartserviceParamsProc; static ATOM_VECTOR<ChartThreadParams> *ParamIn = &chartserviceParamsIn; static ATOM_VECTOR<ChartThreadParams> *ParamProc = &chartserviceParamsProc; static ATOM_FastMutex paramMutex; unsigned __stdcall ChartService (void*) { for (;;) { for (unsigned i = 0; i < ParamProc->size(); ++i) { const ChartThreadParams &params = (*ParamProc)[i]; switch (params.request) { case WMU_CS_CREATE: params.chart->_create ( params.name, params.w, params.h, params.vw, params.vh, params.ww, params.wh ); break; case WMU_CS_DESTROY: params.chart->_destroy (); break; case WMU_CS_SHOW: params.chart->_show (params.isshown); break; case WMU_CS_UPDATE: params.chart->_update (); break; default: break; } } ParamProc->resize(0); { ATOM_FastMutex::ScopeMutex l(paramMutex); ATOM_VECTOR<ChartThreadParams> *tmp = ParamIn; ParamIn = ParamProc; ParamProc = tmp; } { MSG msg; while (::PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) { ::TranslateMessage (&msg); ::DispatchMessage (&msg); } } if (::WaitForSingleObject (chartserviceEndEvent, 0) == WAIT_OBJECT_0) { break; } ::Sleep (50); } return 0; }; static HANDLE chartserviceThread = 0; static unsigned chartserviceThreadId = 0; void ATOM_Chart::startChartService (void) { chartserviceEndEvent = ::CreateEvent (0, FALSE, FALSE, 0); chartserviceThread = (HANDLE)::_beginthreadex (0, 0, &ChartService, 0, 0, &chartserviceThreadId); } void ATOM_Chart::stopChartService (void) { if (chartserviceThread) { ::SetEvent (chartserviceEndEvent); ::WaitForSingleObject (chartserviceThread, INFINITE); ::CloseHandle (chartserviceThread); chartserviceThread = 0; } } bool ATOM_Chart::ChartServiceRunning (void) { return chartserviceThread != NULL; } ATOM_Chart::ATOM_Chart (void) { if (!ChartServiceRunning()) { startChartService (); } m_isshown = false; m_hWnd = 0; m_memDC = 0; m_memBitmap = 0; m_width = 0; m_height = 0; m_virtual_width = 0; m_virtual_height = 0; m_pos_x = 0; m_pos_y = 0; m_bkcallback = 0; m_bkcallback_param = 0; m_window_w = 0; m_window_h = 0; } ATOM_Chart::~ATOM_Chart (void) { destroy (); } static const char *CHART_WNDCLASS = "ATOM_CHART_WCLASS"; LRESULT CALLBACK ATOM_ChartWindowProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); static void _ChartRegisterClass (void) { WNDCLASS wc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = (HBRUSH)::GetStockObject(DKGRAY_BRUSH); wc.hCursor = (HCURSOR)::LoadCursor(NULL, IDC_ARROW); wc.hIcon = (HICON)::LoadIcon(NULL, IDI_WINLOGO); wc.hInstance = (HINSTANCE)::GetModuleHandle (NULL); wc.lpfnWndProc = &ATOM_ChartWindowProc; wc.lpszClassName = CHART_WNDCLASS; wc.lpszMenuName = 0; wc.style = CS_VREDRAW|CS_HREDRAW; ::RegisterClass (&wc); } static ATOM_MAP<HWND, ATOM_Chart*> chartWindows; static ATOM_FastMutex chartWindowLock; LRESULT CALLBACK ATOM_ChartWindowProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { ATOM_Chart *chart = 0; if (msg == WM_CREATE) { CREATESTRUCT *cs = (CREATESTRUCT*)lParam; chart = (ATOM_Chart*)cs->lpCreateParams; { ATOM_FastMutex::ScopeMutex l(chartWindowLock); chartWindows[hWnd] = chart; } } else if (msg == WM_DESTROY) { ATOM_FastMutex::ScopeMutex l(chartWindowLock); ATOM_MAP<HWND, ATOM_Chart*>::iterator it = chartWindows.find (hWnd); if (it != chartWindows.end()) { chartWindows.erase (it); } } else { ATOM_FastMutex::ScopeMutex l(chartWindowLock); ATOM_MAP<HWND, ATOM_Chart*>::iterator it = chartWindows.find (hWnd); chart = (it != chartWindows.end()) ? it->second : 0; } LRESULT lresult = 0; if (!chart || !chart->processMessage (msg, wParam, lParam, &lresult)) { lresult = ::DefWindowProc (hWnd, msg, wParam, lParam); } return lresult; } bool ATOM_Chart::create (const char *name, unsigned w, unsigned h, unsigned vw, unsigned vh, unsigned win_w, unsigned win_h) { if (!ChartServiceRunning ()) { return false; } ChartThreadParams params; params.request = WMU_CS_CREATE; params.chart = this; strcpy (params.name, name); params.w = w; params.h = h; params.vw = vw; params.vh = vh; params.ww = win_w; params.wh = win_h; { ATOM_FastMutex::ScopeMutex l(paramMutex); ParamIn->push_back (params); } return true; } bool ATOM_Chart::_create (const char *name, unsigned w, unsigned h, unsigned vw, unsigned vh, unsigned win_w, unsigned win_h) { _destroy (); _ChartRegisterClass (); DWORD style = WS_CAPTION|WS_SYSMENU|WS_MINIMIZE; RECT rc; rc.left = 0; rc.top = 0; rc.right = win_w; rc.bottom = win_h; ::AdjustWindowRect (&rc, style, FALSE); win_w = rc.right - rc.left; win_h = rc.bottom - rc.top; m_hWnd = ::CreateWindowA (CHART_WNDCLASS, name, style, CW_USEDEFAULT, CW_USEDEFAULT, win_w, win_h, NULL, NULL, ::GetModuleHandle(NULL), this); if (!m_hWnd) { return false; } m_window_w = win_w; m_window_h = win_h; HDC hDC = ::GetDC (m_hWnd); m_memDC = ::CreateCompatibleDC (hDC); m_memBitmap = ::CreateCompatibleBitmap (hDC, win_w, win_h); ::SelectObject (m_memDC, m_memBitmap); ::ReleaseDC (m_hWnd, hDC); m_width = w; m_height = h; m_virtual_width = vw ? vw : w; m_virtual_height = vh ? vh : h; m_pos_x = 0; m_pos_y = 0; return true; } void ATOM_Chart::destroy (void) { if (!ChartServiceRunning ()) { return; } if (m_hWnd ) { ChartThreadParams params; params.request = WMU_CS_DESTROY; params.chart = this; { ATOM_FastMutex::ScopeMutex l(paramMutex); ParamIn->push_back (params); } } } void ATOM_Chart::_destroy (void) { if (m_hWnd) { ::DestroyWindow (m_hWnd); m_hWnd = 0; ::DeleteDC (m_memDC); m_memDC = 0; ::DeleteObject (m_memBitmap); m_memBitmap = 0; } } void ATOM_Chart::update (void) { if (!ChartServiceRunning ()) { return; } if (m_hWnd ) { ChartThreadParams params; params.request = WMU_CS_UPDATE; params.chart = this; { ATOM_FastMutex::ScopeMutex l(paramMutex); ParamIn->push_back (params); } } } void ATOM_Chart::_update (void) { if (m_hWnd) { InvalidateRect (m_hWnd, NULL, FALSE); } } void ATOM_Chart::show (bool show) { if (!ChartServiceRunning ()) { return; } if (m_hWnd ) { ChartThreadParams params; params.request = WMU_CS_SHOW; params.chart = this; params.isshown = show; { ATOM_FastMutex::ScopeMutex l(paramMutex); ParamIn->push_back (params); } m_isshown = show; } } void ATOM_Chart::_show (bool show) { if (m_hWnd) { ::ShowWindow (m_hWnd, show ? SW_SHOW : SW_HIDE); ::UpdateWindow (m_hWnd); } } bool ATOM_Chart::isShown (void) const { return m_isshown; } bool ATOM_Chart::_isShown (void) const { return m_hWnd && ::IsWindowVisible (m_hWnd); } void ATOM_Chart::setPosition (unsigned x, unsigned y) { if (m_pos_x != x || m_pos_y != y) { m_pos_x = x; m_pos_y = y; update (); } } void ATOM_Chart::drawBackground (HDC hdc) { if (m_bkcallback) { for (unsigned i = 0; i < m_window_w; ++i) for (unsigned j = 0; j < m_window_h; ++j) { m_bkcallback (hdc, i, j, m_bkcallback_param); } } else { drawDefaultBackground (hdc); } } void ATOM_Chart::drawDefaultBackground (HDC hdc) { HBRUSH hbr = (HBRUSH)::GetStockObject(GRAY_BRUSH); RECT rc; rc.left = 0; rc.top = 0; rc.right = m_window_w; rc.bottom = m_window_h; ::FillRect (hdc, &rc, hbr); } bool ATOM_Chart::processMessage (UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *result) { switch (msg) { case WM_ERASEBKGND: *result = 1; return true; case WM_PAINT: { PAINTSTRUCT ps; paint (m_memDC); ::BeginPaint (m_hWnd, &ps); ::BitBlt (ps.hdc, 0, 0, m_window_w, m_window_h, m_memDC, 0, 0, SRCCOPY); ::EndPaint (m_hWnd, &ps); *result = 0; return true; } case WM_CLOSE: _show (false); *result = 0; return true; default: break; } return false; } /////////////////////////////////////////ATOM_ChartLines/////////////////////////////////////////// ATOM_ChartLines::ATOM_ChartLines (void) { m_clearback = true; } bool ATOM_ChartLines::newPath (const char *path, int linestyle, int width, COLORREF color) { ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.find (path); if (it != m_pathes.end ()) { return false; } PathInfo &pi = m_pathes[path]; pi.pen = ::CreatePen (linestyle, width, color); return true; } void ATOM_ChartLines::insertPoint (const char *path, unsigned x, unsigned y, bool linknext) { if (!isShown()) { return; } ATOM_FastMutex::ScopeMutex l(m_lock); ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.find (path); if (it == m_pathes.end ()) { return; } Point pt; pt.pt.x = x; pt.pt.y = y; pt.linknext = linknext; it->second.points.push_back (pt); } void ATOM_ChartLines::clearPoints (void) { ATOM_FastMutex::ScopeMutex l(m_lock); for (ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.begin(); it != m_pathes.end(); ++it) { it->second.points.resize(0); } m_clearback = true; } void ATOM_ChartLines::clear (void) { ATOM_FastMutex::ScopeMutex l(m_lock); for (ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.begin(); it != m_pathes.end(); ++it) { ::DeleteObject (it->second.pen); } m_pathes.clear (); m_clearback = true; } void ATOM_ChartLines::paint (HDC hdc) { // fill background if (m_clearback) { m_clearback = false; drawBackground (hdc); } // draw mark HBRUSH hbrMark[2] = { (HBRUSH)::GetStockObject(WHITE_BRUSH), (HBRUSH)::GetStockObject(DKGRAY_BRUSH) }; static int mark = 0; RECT rc; rc.left = 0; rc.top = 0; rc.right = 10; rc.bottom = 10; ::FillRect (hdc, &rc, hbrMark[mark++%2]); // draw lines { ATOM_FastMutex::ScopeMutex l(m_lock); for (ATOM_HASHMAP<ATOM_STRING, PathInfo>::iterator it = m_pathes.begin(); it != m_pathes.end(); ++it) { PathInfo &pi = it->second; if (pi.points.size() > 1) { HGDIOBJ oldPen = ::SelectObject (hdc, (HGDIOBJ)pi.pen); for (unsigned i = 0; i < pi.points.size()-1; ++i) { if (pi.points[i].linknext) { ::MoveToEx (hdc, pi.points[i].pt.x, pi.points[i].pt.y, 0); ::LineTo (hdc, pi.points[i+1].pt.x, pi.points[i+1].pt.y); } else { continue; } } ::SelectObject (hdc, oldPen); Point pt = pi.points.back(); pi.points.resize(0); pi.points.push_back (pt); } } } }
[ "80844871@qq.com" ]
80844871@qq.com
46d49d79978ab4fdfa2308c874fb5934dd3f4ade
153b3230aa3235a5003642d07e114fb6bdf36caa
/Assignment2/Program/build-HFractal-Desktop_Qt_5_11_3_MinGW_32bit-Debug/debug/moc_gtextarea.cpp
cd2bbc116e57a4637596f2d525f47c0a1ffd496b
[]
no_license
MeloYang05/CUHK-CSC3002-Assignment
dc6e4c4e73194a0de324ece850880d22c6f84373
a5156f4edf13b59291647e566b7766ec42faccd3
refs/heads/master
2020-07-12T13:05:42.498424
2019-08-28T01:54:34
2019-08-28T01:54:34
204,825,810
1
0
null
null
null
null
UTF-8
C++
false
false
3,935
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'gtextarea.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../H-Fractal/lib/StanfordCPPLib/graphics/gtextarea.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'gtextarea.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.11.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata__Internal_QTextEdit_t { QByteArrayData data[5]; char stringdata0[57]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata__Internal_QTextEdit_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata__Internal_QTextEdit_t qt_meta_stringdata__Internal_QTextEdit = { { QT_MOC_LITERAL(0, 0, 19), // "_Internal_QTextEdit" QT_MOC_LITERAL(1, 20, 12), // "handleScroll" QT_MOC_LITERAL(2, 33, 0), // "" QT_MOC_LITERAL(3, 34, 5), // "value" QT_MOC_LITERAL(4, 40, 16) // "handleTextChange" }, "_Internal_QTextEdit\0handleScroll\0\0" "value\0handleTextChange" }; #undef QT_MOC_LITERAL static const uint qt_meta_data__Internal_QTextEdit[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x0a /* Public */, 4, 0, 27, 2, 0x0a /* Public */, // slots: parameters QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, 0 // eod }; void _Internal_QTextEdit::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { _Internal_QTextEdit *_t = static_cast<_Internal_QTextEdit *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->handleScroll((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->handleTextChange(); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject _Internal_QTextEdit::staticMetaObject = { { &QTextEdit::staticMetaObject, qt_meta_stringdata__Internal_QTextEdit.data, qt_meta_data__Internal_QTextEdit, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *_Internal_QTextEdit::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *_Internal_QTextEdit::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata__Internal_QTextEdit.stringdata0)) return static_cast<void*>(this); if (!strcmp(_clname, "_Internal_QWidget")) return static_cast< _Internal_QWidget*>(this); return QTextEdit::qt_metacast(_clname); } int _Internal_QTextEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QTextEdit::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "lianyixiaofan@foxmail.com" ]
lianyixiaofan@foxmail.com
8634c08b685081d89aaf09b80e9f1a5a1402cfb5
07eb399da1ce4374deedb339117299d321305b55
/freespace2/include/multi_pause.h
ee3b46dd5e2df826afc04791ac1d1916e729e4b6
[]
no_license
lubomyr/freespace2
222474acb364f4f2e5ad36ecad0450244196220d
a959fcf403400f5c5d933fba66a41d8e96b02811
refs/heads/master
2021-01-15T08:58:58.113252
2016-11-06T14:53:59
2016-11-06T14:53:59
52,396,527
11
4
null
null
null
null
UTF-8
C++
false
false
2,556
h
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ /* * $Logfile: /Freespace2/code/Network/multi_pause.h $ * $Revision: 110 $ * $Date: 2002-06-09 07:41:30 +0300 (нд, 09 чер 2002) $ * $Author: relnev $ * * $Log$ * Revision 1.2 2002/06/09 04:41:14 relnev * added copyright header * * Revision 1.1.1.1 2002/05/03 03:28:12 root * Initial import. * * * 3 10/13/98 9:29a Dave * Started neatening up freespace.h. Many variables renamed and * reorganized. Added AlphaColors.[h,cpp] * * 2 10/07/98 10:53a Dave * Initial checkin. * * 1 10/07/98 10:50a Dave * * 2 5/07/98 6:26p Dave * Fix strange boundary conditions which arise when players die/respawn * while the game is being ended. Spiff up the chatbox doskey thing a bit. * * 1 4/14/98 12:18p Dave * * * $NoKeywords: $ */ #ifndef _MULTI_PAUSE_HEADER_FILE #define _MULTI_PAUSE_HEADER_FILE // ---------------------------------------------------------------------------------- // PAUSE DEFINES/VARS // class UI_WINDOW; struct net_player; // state of the game (paused or not) on _my_ machine. Obviously this is important for the server // call multi_pause_reset() to reinitialize extern int Multi_pause_status; // who paused the game extern net_player *Multi_pause_pauser; // ---------------------------------------------------------------------------------- // PAUSE FUNCTIONS // // re-initializes the pause system. call before entering the mission to reset void multi_pause_reset(); // send a request to pause or unpause a game (all players should use this function) void multi_pause_request(int pause); // (client) call when receiving a packet indicating we should pause void multi_pause_pause(); // (client) call when receiving a packet indicating we should unpause void multi_pause_unpause(); // (server) evaluate a pause request from the given player (should call for himself as well) void multi_pause_server_eval_request(net_player *pl, int pause); // if we still want to eat keys int multi_pause_eat_keys(); // ---------------------------------------------------------------------------------- // PAUSE UI FUNCTIONS // // initialize multi pause screen void multi_pause_init(UI_WINDOW *Ui_window); // do frame for the multi pause screen void multi_pause_do(); // close the multi pause screen void multi_pause_close(); #endif
[ "lubomyr31@gmail.com" ]
lubomyr31@gmail.com
5addeb853ffd246d1a5811a7cc41bc6fdb3a3722
ab9b1af430728a52a8fd91279f9a9093a2701604
/sword_to_offer_010_ex/sword_to_offer_010_ex/sword_to_offer_010_ex.cpp
707e31ab6b829606b69176c96f770ba4d908cda6
[]
no_license
wuyong66/sword_to_offer
3a59677b9965a08db8aa516c0ccc48070347c264
db436d2772cc4873ab696162b495113f1d1cec48
refs/heads/master
2020-03-19T10:47:30.232106
2018-07-25T14:47:56
2018-07-25T14:47:56
136,401,309
1
0
null
null
null
null
GB18030
C++
false
false
764
cpp
#include <iostream> #include <string> #include <vector> using namespace std; bool IsPowOf2(int num); int MChangeToN(int m, int n); int main() { cout << IsPowOf2(8) << endl; cout << MChangeToN(8, 4) << endl; system("pause"); return 0; } //判定某个数是否是2的指数得到的 bool IsPowOf2(int num) { unsigned int flag = 1; unsigned int count = 0; while (flag) { if (num & flag) ++count; flag = flag << 1; } if (count == 1) return true; else return false; } //得出用以表示M的二进制通过变换多少位可以变换为表示N二进制数 int MChangeToN(int m, int n) { int num = m ^ n; unsigned int flag = 1; unsigned int count = 0; while (flag) { if (num & flag) ++count; flag = flag << 1; } return count; }
[ "1062073083@qq.com" ]
1062073083@qq.com
5c08bf721268856c2037578406d82a5c85bb4708
bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7
/gta5/0xAA0A52D24FB98293.cpp
a5cb865f044fc64cb0cbee54deebd2d665db09e8
[]
no_license
DeepWolf413/additional-native-data
aded47e042f0feb30057e753910e0884c44121a0
e015b2500b52065252ffbe3c53865fe3cdd3e06c
refs/heads/main
2023-07-10T00:19:54.416083
2021-08-12T16:00:12
2021-08-12T16:00:12
395,340,507
1
0
null
null
null
null
UTF-8
C++
false
false
821
cpp
// am_imp_exp.ysc @ L8276 void func_189(int iParam0, int iParam1, int iParam2) { int iVar0; int iVar1; int iVar2; var uVar3; HUD::GET_HUD_COLOUR(iParam2, &iVar0, &iVar1, &iVar2, &uVar3); if (iParam1 == 0) { } VEHICLE::TRACK_VEHICLE_VISIBILITY(iParam0); if (func_14(PLAYER::PLAYER_ID(), 1, 1)) { if (VEHICLE::IS_VEHICLE_DRIVEABLE(iParam0, false)) { if (func_190(iParam0) == 0) { if (!PED::IS_PED_IN_VEHICLE(PLAYER::PLAYER_PED_ID(), iParam0, false)) { if (VEHICLE::IS_VEHICLE_VISIBLE(iParam0)) { GRAPHICS::ADD_ENTITY_ICON(iParam0, "MP_Arrow"); GRAPHICS::SET_ENTITY_ICON_COLOR(iParam0, iVar0, iVar1, iVar2, 190); GRAPHICS::SET_ENTITY_ICON_VISIBILITY(iParam0, true); } } } } } }
[ "jesper15fuji@live.dk" ]
jesper15fuji@live.dk
f946afd96f40ff7139a3862761ad0d6dc557c013
438cd59a4138cd87d79dcd62d699d563ed976eb9
/mame/src/mame/includes/atarig42.h
d1aa27dbc638d6ec70b6f2d0c4e5bf6be06db9c5
[]
no_license
clobber/UME
031c677d49634b40b5db27fbc6e15d51c97de1c5
9d4231358d519eae294007133ab3eb45ae7e4f41
refs/heads/master
2021-01-20T05:31:28.376152
2013-05-01T18:42:59
2013-05-01T18:42:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,299
h
/************************************************************************* Atari G42 hardware *************************************************************************/ #include "machine/atarigen.h" class atarig42_state : public atarigen_state { public: atarig42_state(const machine_config &mconfig, device_type type, const char *tag) : atarigen_state(mconfig, type, tag), m_mo_command(*this, "mo_command") { } UINT16 m_playfield_base; UINT16 m_current_control; UINT8 m_playfield_tile_bank; UINT8 m_playfield_color_bank; UINT16 m_playfield_xscroll; UINT16 m_playfield_yscroll; UINT8 m_analog_data; required_shared_ptr<UINT16> m_mo_command; int m_sloop_bank; int m_sloop_next_bank; int m_sloop_offset; int m_sloop_state; UINT16 * m_sloop_base; device_t * m_rle; UINT32 m_last_accesses[8]; virtual void update_interrupts(); virtual void scanline_update(screen_device &screen, int scanline); DECLARE_READ16_MEMBER(special_port2_r); DECLARE_WRITE16_MEMBER(a2d_select_w); DECLARE_READ16_MEMBER(a2d_data_r); DECLARE_WRITE16_MEMBER(io_latch_w); DECLARE_WRITE16_MEMBER(mo_command_w); DECLARE_READ16_MEMBER(roadriot_sloop_data_r); DECLARE_WRITE16_MEMBER(roadriot_sloop_data_w); DECLARE_READ16_MEMBER(guardians_sloop_data_r); DECLARE_WRITE16_MEMBER(guardians_sloop_data_w); void roadriot_sloop_tweak(int offset); void guardians_sloop_tweak(int offset); DECLARE_DIRECT_UPDATE_MEMBER(atarig42_sloop_direct_handler); DECLARE_DRIVER_INIT(roadriot); DECLARE_DRIVER_INIT(guardian); TILE_GET_INFO_MEMBER(get_alpha_tile_info); TILE_GET_INFO_MEMBER(get_playfield_tile_info); TILEMAP_MAPPER_MEMBER(atarig42_playfield_scan); DECLARE_MACHINE_START(atarig42); DECLARE_MACHINE_RESET(atarig42); DECLARE_VIDEO_START(atarig42); UINT32 screen_update_atarig42(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); void screen_eof_atarig42(screen_device &screen, bool state); }; /*----------- defined in video/atarig42.c -----------*/ DECLARE_WRITE16_HANDLER( atarig42_mo_control_w ); void atarig42_scanline_update(screen_device &screen, int scanline);
[ "brymaster@gmail.com" ]
brymaster@gmail.com
d6053c911037b737af040af6165b9a9817b98856
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/chrome/browser/sync/test/integration/themes_helper.h
587f790635b6ce04c5478c43385507e55d28b89c
[ "BSD-3-Clause" ]
permissive
denix123/a32_ul
4ffe304b13c1266b6c7409d790979eb8e3b0379c
b2fd25640704f37d5248da9cc147ed267d4771c2
refs/heads/master
2021-01-17T20:21:17.196296
2016-08-16T04:30:53
2016-08-16T04:30:53
65,786,970
0
2
null
2020-03-06T22:00:52
2016-08-16T04:15:54
null
UTF-8
C++
false
false
1,201
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SYNC_TEST_INTEGRATION_THEMES_HELPER_H_ #define CHROME_BROWSER_SYNC_TEST_INTEGRATION_THEMES_HELPER_H_ #include <string> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "chrome/browser/sync/test/integration/sync_test.h" class Profile; namespace themes_helper { std::string GetCustomTheme(int index) WARN_UNUSED_RESULT; std::string GetThemeID(Profile* profile) WARN_UNUSED_RESULT; bool UsingCustomTheme(Profile* profile) WARN_UNUSED_RESULT; bool UsingDefaultTheme(Profile* profile) WARN_UNUSED_RESULT; bool UsingSystemTheme(Profile* profile) WARN_UNUSED_RESULT; bool ThemeIsPendingInstall( Profile* profile, const std::string& id) WARN_UNUSED_RESULT; void UseCustomTheme(Profile* profile, int index); void UseDefaultTheme(Profile* profile); void UseSystemTheme(Profile* profile); bool AwaitThemeIsPendingInstall(Profile* profile, const std::string& theme); bool AwaitUsingSystemTheme(Profile* profile); bool AwaitUsingDefaultTheme(Profile* profile); } #endif
[ "allegrant@mail.ru" ]
allegrant@mail.ru
be26cb5e563ca8a301dec40afb3bff14e0714909
d7b2eef3c363d735afc14abefe88a0d6426cd133
/dynamic_programming/C.cpp
8254f1fe9965c13919972f735b18c79111a1234b
[]
no_license
AndreyBocharnikov/Algorithms-and-Data-structures
ab5d6a4552f59bcae567ca76c14370230d75b0b5
0eb404fa8521c0550d4a23d563649c49d2cc56bc
refs/heads/master
2023-06-04T16:51:01.401711
2021-06-15T09:57:28
2021-06-15T09:57:28
250,284,061
0
0
null
null
null
null
UTF-8
C++
false
false
1,845
cpp
#include <fstream> #include <vector> #include <algorithm> #define ll long long #define f first #define s second using namespace std; ll dp[2001][2001], w[2001]; int R[2001][2001]; vector <string> ans; void find_ans(int l, int r) { if (l == r) return; int mid = R[l][r]; // cout << l << " " << mid << " " << r << '\n'; for (int i = l; i <= mid; i++) ans[i] += '0'; for (int i = mid + 1; i <= r; i++) ans[i] += '1'; find_ans(l, mid); find_ans(mid + 1, r); } int main() { ifstream cin("optimalcode.in"); ofstream cout("optimalcode.out"); int n; ll inf = 1e18; cin >> n; ans.resize(n); vector <ll> f(n); for (int i = 0; i < 2001; i++) for (int j = 0; j < 2001; j++) dp[i][j] = inf; for (int i = 0; i < n; i++) cin >> f[i], dp[i][i] = 0; for (int i = 0; i < n; i++) w[i] = f[i]; for (int i = 1; i < n; i++) w[i] += w[i - 1]; for (int i = 0; i < n; i++) R[i][i] = i; for (int len = 2; len <= n; len++) { for (int i = 0; i <= n - len; i++) { int j = i + len - 1; int l = R[i][j - 1], r = R[i + 1][j]; ll val = i == 0 ? w[j] : w[j] - w[i - 1]; // cout << i << " " << j << " " << l << " " << r << '\n'; for (int k = l; k <= r; k++) { if (k + 1 <= j && dp[i][k] + dp[k + 1][j] < dp[i][j]) dp[i][j] = dp[i][k] + dp[k + 1][j], R[i][j] = k; } dp[i][j] += val; // cout << i << " " << j << " " << dp[i][j] << '\n'; } } cout << dp[0][n - 1] << '\n'; find_ans(0, n - 1); for (int i = 0; i < n; i++) { cout << ans[i] << '\n'; } }
[ "a-bocharnikov@bk.ru" ]
a-bocharnikov@bk.ru
0dcebbc472ea2ff9bee964db7b2760231d91ff56
ed0fb471daca59daa6255d75d4c68508e58e3454
/recognition/include/pcl/recognition/distance_map.h
ac68e5b4ed81036bfd823775d271c9227326713a
[ "BSD-3-Clause" ]
permissive
mujin/pcl
ec9de205e1ee5940fd0a55a012733984a0bb1ff2
9a13da19c792ce1f9dfcb752bc92300f40270bec
refs/heads/master
2023-06-09T13:49:51.928549
2022-04-18T01:03:29
2022-04-18T01:03:29
32,294,758
4
2
NOASSERTION
2023-05-09T03:41:42
2015-03-16T01:43:16
C++
UTF-8
C++
false
false
3,929
h
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT 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 PCL_RECOGNITION_DISTANCE_MAP #define PCL_RECOGNITION_DISTANCE_MAP namespace pcl { /** \brief Represents a distance map obtained from a distance transformation. * \author Stefan Holzer */ class DistanceMap { public: /** \brief Constructor. */ DistanceMap () : data_ (0), width_ (0), height_ (0) {} /** \brief Destructor. */ virtual ~DistanceMap () {} /** \brief Returns the width of the map. */ inline size_t getWidth () const { return (width_); } /** \brief Returns the height of the map. */ inline size_t getHeight () const { return (height_); } /** \brief Returns a pointer to the beginning of map. */ inline float * getData () { return (&data_[0]); } /** \brief Resizes the map to the specified size. * \param[in] width the new width of the map. * \param[in] height the new height of the map. */ void resize (const size_t width, const size_t height) { data_.resize (width*height); width_ = width; height_ = height; } /** \brief Operator to access an element of the map. * \param[in] col_index the column index of the element to access. * \param[in] row_index the row index of the element to access. */ inline float & operator() (const size_t col_index, const size_t row_index) { return (data_[row_index*width_ + col_index]); } /** \brief Operator to access an element of the map. * \param[in] col_index the column index of the element to access. * \param[in] row_index the row index of the element to access. */ inline const float & operator() (const size_t col_index, const size_t row_index) const { return (data_[row_index*width_ + col_index]); } protected: /** \brief The storage for the distance map data. */ std::vector<float> data_; /** \brief The width of the map. */ size_t width_; /** \brief The height of the map. */ size_t height_; }; } #endif
[ "holzers@in.tum.de" ]
holzers@in.tum.de
186465f9cd35fcf9ff7b50a436459d05d19d50ec
bc15567a31a80adf9027710cfc1c04e6c2735b3c
/src/test/checkblock_tests.cpp
57a2fc2fd6a9ab72e7f6059dae4bf4b42d666844
[ "MIT" ]
permissive
shadowOz/stargate-guru-test
a012770acf941111cce415af9e02406d879421a3
41716cd5142df5d598775139c4a3313bc3c917ac
refs/heads/master
2020-03-15T13:57:18.983505
2018-05-06T13:32:11
2018-05-06T13:32:11
132,179,190
0
0
null
null
null
null
UTF-8
C++
false
false
1,901
cpp
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "consensus/validation.h" #include "validation.h" // For CheckBlock #include "primitives/block.h" #include "test/test_stargate.h" #include "utiltime.h" #include <cstdio> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(CheckBlock_tests, BasicTestingSetup) bool read_block(const std::string& filename, CBlock& block) { namespace fs = boost::filesystem; fs::path testFile = fs::current_path() / "data" / filename; #ifdef TEST_DATA_DIR if (!fs::exists(testFile)) { testFile = fs::path(BOOST_PP_STRINGIZE(TEST_DATA_DIR)) / filename; } #endif FILE* fp = fopen(testFile.string().c_str(), "rb"); if (!fp) return false; fseek(fp, 8, SEEK_SET); // skip msgheader/size CAutoFile filein(fp, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return false; filein >> block; return true; } BOOST_AUTO_TEST_CASE(May15) { // Putting a 1MB binary file in the git repository is not a great // idea, so this test is only run if you manually download // test/data/Mar12Fork.dat from // http://sourceforge.net/projects/bitcoin/files/Bitcoin/blockchain/Mar12Fork.dat/download unsigned int tMay15 = 1368576000; SetMockTime(tMay15); // Test as if it was right at May 15 CBlock forkingBlock; if (read_block("Mar12Fork.dat", forkingBlock)) { CValidationState state; // After May 15'th, big blocks are OK: forkingBlock.nTime = tMay15; // Invalidates PoW BOOST_CHECK(CheckBlock(forkingBlock, state, false, false)); } SetMockTime(0); } BOOST_AUTO_TEST_SUITE_END()
[ "38054148+shadowOz@users.noreply.github.com" ]
38054148+shadowOz@users.noreply.github.com
74415afe8b1b79b79598229727852d99f28d52db
c50d61136efbd74c97d939468542e40e0fbb79e1
/core/vendor/pytorch-release/include/nvfuser_resources/grid_reduction.h
4e7a1260996db3ff758c6bcc358336c3240333d4
[]
no_license
Ajblast/GameEngine
e95836d631fa2e2057ab9a5219ceb57fcbf5b23f
db2473add049125f7e2c21965a3957e4f3d74ffc
refs/heads/main
2023-09-01T17:31:20.655818
2021-10-17T13:03:45
2021-10-17T13:03:45
327,814,676
0
0
null
null
null
null
UTF-8
C++
false
false
14,226
h
// Generated from "C:/w/b/windows/pytorch/torch/csrc/jit/codegen/cuda/runtime/grid_reduction.cu" // 2021-09-14 15:01:05 namespace nvfuser_resources { constexpr const char* grid_reduction_cu = R"( // Inter-block reduction. // // Function gridReduce performs point-wise reductions of scalars across thread // blocks. Thread blocks are disjointly partitioned into groups of thread // blocks, "reduction segments," that are collectively defined by boolean // template parameters, X_BLOCK, Y_BLOCK and Z_BLOCK. Each of X/Y/Z_BLOCK // determines whether thread blocks along the dimension should be grouped into // the same reduction segment. Cross-block reducitons are independently done // within each segment and generates distinctive results per segment. For // instance, if all of X/Y/Z_BLOCK are true, reductions will be done across all // thread blocks since there will be just a single segment consisting of all // thread blocks. If none of them are true, each thread block will become a // segment by itself, so no reduction will be performed. // // The input scalars to reduce within each segment are a certain subset of // thread-private scalars provided as part of the gridReduce function // parameters. Boolean template parameters, X_THREAD, Y_THREAD and Z_THREAD, // determine which subset of the scalars should be used for inter-block // reductions. Specifically, all the input scalars of threads along each // dimension will be used when X/Y/Z_THREAD are true. Otherwise, only the value // held at offset 0 of each dimension will be used. Thus, for example, if all of // X/Y/Z_THREAD are true, the scalars of all threads in each block will // participate in inter-block reductions. If all of them are false, only one // scalar of the thread at threadIdx.x == threadIdx.y == threadIdx.z == 0 will // be used. In the code below, we call the subset of threads a "reduction // block." // // Inter-block reductions perform point-wise reductions of scalars of reduction // blocks within each reduction segment. More specifically, let rb be a // reduction block and rs be a reduction segment. Let IN(thread_idx, block_idx) // denote the input scalar of thread at thread_idx and block_idx. The result of // each reduction segment, OUT(thread_idx, block_idx_out), is defined only for // each thread_idx in thread block block_idx_out in the segment as follows: // // OUT(thread_idx, block_idx_out) = // Reduction of IN(thread_idx, block_idx) for // all block_idx in a reduction segment // // OUT is not given for all threads that are not in block_idx_out and the // reduction block. // // See also the function comment of gridReduce. namespace reduction { // Utility functions template <typename _dim3> __device__ __forceinline__ size_t size(const _dim3& d) { return (size_t)d.x * (size_t)d.y * (size_t)d.z; } #define isize(d) d.x* d.y* d.z template <typename _dim3pos, typename _dim3dim> __device__ __forceinline__ size_t offset(const _dim3pos& pos, const _dim3dim& dim) { return (size_t)pos.x + (size_t)pos.y * (size_t)dim.x + (size_t)pos.z * (size_t)dim.x * (size_t)dim.y; } #define ioffset(pos, dim) pos.x + pos.y* dim.x + pos.z* dim.x* dim.y // Returns dim3 of each reduction segment. template <bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, typename _dim3> __device__ dim3 dimension_of_reduction_segment(const _dim3& grid_dim) { return dim3{ X_BLOCK ? (unsigned)grid_dim.x : 1U, Y_BLOCK ? (unsigned)grid_dim.y : 1U, Z_BLOCK ? (unsigned)grid_dim.z : 1U}; } // Returns the number of blocks in each reduction segment. template <bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, typename _dim3> __device__ size_t size_of_reduction_segment(const _dim3& grid_dim) { return size( dimension_of_reduction_segment<X_BLOCK, Y_BLOCK, Z_BLOCK>(grid_dim)); } // Returns the total number of reduction segments. template <bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, typename _dim3> __device__ size_t number_of_reduction_segments(const _dim3& grid_dim) { return (X_BLOCK ? 1 : grid_dim.x) * (Y_BLOCK ? 1 : grid_dim.y) * (Z_BLOCK ? 1 : grid_dim.z); } // Returns the 1-D index of the segment of thread block of block_idx. template < bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, typename _dim3bi, typename _dim3gd> __device__ size_t index_of_reduction_segment(const _dim3bi& block_idx, const _dim3gd& grid_dim) { size_t seg_idx = 0; if (!Z_BLOCK) seg_idx += block_idx.z; if (!Y_BLOCK) seg_idx = seg_idx * grid_dim.y + block_idx.y; if (!X_BLOCK) seg_idx = seg_idx * grid_dim.x + block_idx.x; return seg_idx; } // Returns the offset of thread block in its reduction segment. template < bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, typename _dim3bi, typename _dim3gd> __device__ size_t offset_in_reduction_segment(const _dim3bi& block_idx, const _dim3gd& grid_dim) { size_t offset = 0; if (Z_BLOCK) offset = offset * grid_dim.z + block_idx.z; if (Y_BLOCK) offset = offset * grid_dim.y + block_idx.y; if (X_BLOCK) offset = offset * grid_dim.x + block_idx.x; return offset; } // Returns dim3 of each reduction block. template <bool X_THREAD, bool Y_THREAD, bool Z_THREAD, typename _dim3> __device__ dim3 dimension_of_reduction_block(const _dim3& block_dim) { return dim3{ X_THREAD ? (unsigned)block_dim.x : 1U, Y_THREAD ? (unsigned)block_dim.y : 1U, Z_THREAD ? (unsigned)block_dim.z : 1U}; } // Returns the number of threads of each reduction block. template <bool X_THREAD, bool Y_THREAD, bool Z_THREAD, typename _dim3> __device__ int size_of_reduction_block(const _dim3& block_dim) { auto tmp_dim = dimension_of_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>(block_dim); return isize(tmp_dim); } // Returns the linear offset of a thread in a reduction block. template < bool X_THREAD, bool Y_THREAD, bool Z_THREAD, typename _dim3ti, typename _dim3bd> __device__ int offset_in_reduction_block( const _dim3ti& thread_idx, const _dim3bd& block_dim) { int offset = 0; if (Z_THREAD) offset += thread_idx.z; if (Y_THREAD) offset = offset * block_dim.y + thread_idx.y; if (X_THREAD) offset = offset * block_dim.x + thread_idx.x; return offset; } // Reduces all the reduction blocks in each reduction segment. // // This is only used by one thread block per reduction segment. The input // reduction blocks of the segment are stored in an intermediate buffer pointed // by parameter in. Template parameters X/Y/Z_THREAD denote how the reduction // block is formed. // // The size of a reduction block is by definition smaller or equal to the size // of a thread block. We use the remaining threads to parallelize reductions // across reduction blocks. For example, when X/Y/Z_THREAD = {true, false, // false}, we use blockDim.y*blockDim.z threads for each output value. This is // done first by loading the input values in parallel and then by reducing // across threads of dimensions whose XYZ_THREAD are false. // // Note that what is done here after the loading from global memory is similar // to what the existing blockReduce function does. The main difference is that // the logical block to reduce is a 2D domain where the leading dimension is the // size of a reduction block and the second dimension is the remaining factor in // each thread block. For example, when X/Y/Z_THREAD = {false, true, false}, the // threads are arranged as (blockDim.y, blockDim.x*blockDim.z). We do not reduce // along the first dimension but only the second dimension. So, it is possible // to reuse the existing blockReduce with dim3{blockDim.y, // blockDim.x*blockDim.z} instead of blockDim and with X_THREAD and Y_THREAD // being false and true, respectively. Also, it still need to shuffle the final // output values to their actual corresponding threads. In the case of when // X/Y/Z_THREAD = {false, true, false}, after the intra-block reduction, the // final results will still be held by the first blockDim.y threads, which need // to be transferred to threads at threadIdx.x == 0 and threadIdx.z == 0. template < bool X_THREAD, bool Y_THREAD, bool Z_THREAD, typename T, typename Func> __device__ void gridReduceLastBlock( T& out, const T* in, const size_t in_size, Func reduction_op, T* shared_buf, bool read_write_pred, T init_val) { const int tid = ioffset(threadIdx, blockDim); const int block_size = isize(blockDim); const int rblock_size = size_of_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>(blockDim); T inp = init_val; if (tid < in_size) { inp = in[tid]; } for (size_t i = tid + block_size; i < in_size; i += block_size) { reduction_op(inp, in[i]); } const auto should_write = (X_THREAD || threadIdx.x == 0) && (Y_THREAD || threadIdx.y == 0) && (Z_THREAD || threadIdx.z == 0); auto rem_size = block_size / rblock_size; if (rem_size > 1) { const int rblock_offset = tid % rblock_size; const int rblock_idx = tid / rblock_size; blockReduce<false, true, false>( inp, inp, reduction_op, dim3{(unsigned)rblock_offset, (unsigned)rblock_idx, 0}, dim3{(unsigned)rblock_size, (unsigned)rem_size}, shared_buf, true, init_val); __syncthreads(); if (tid < rblock_size) { shared_buf[tid] = inp; } __syncthreads(); if (should_write) { inp = shared_buf[offset_in_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>( threadIdx, blockDim)]; } } if (should_write && read_write_pred) { out = inp; } } // Reduces per-thread values across thread blocks. // // Function parameters: // - out: Per-thread output location // - inp_val: Per-thread input value // - reduction_op: Scalar reduction function // - work_buf: Temporary buffer for cross-block reductions // - sync_flags: A vector of integers for synchronizations // - shared_buf: Shared memory buffer for intra-block reduction // // Return true when the thread block has the valid result. // // Template parameters: // - X/Y/Z_BLOCK: When true, reduces across thread blocks along the X/Y/Z // dimensions // - X/Y/Z_THREAD: When true, all threads along the X/Y/Z dimensions participate // in the cross-block reduction. Otherwise, only threads at offset 0 do. // - T: Scalar data type of input/output data // - Func: Type of scalara reduction function // // Template parameters X/Y/Z_BLOCK define a group of thread blocks that are // reduced together. We call it a reduction segment. Some examples are: // // Case 1: X/Y/Z_BLOCK == true/true/true -> There is only one segment, which // includes all thread blocks. It is effecively the same as the grid. // // Case 2: X/Y/Z_BLOCK == false/false/false -> Each thread block comprises an // individual segment by itself. // // Case 3: X/Y/Z_BLOCK == true/false/false -> Each segment contains thread // blocks that have the same blockDim.x. There will be blockDim.y*blockDim.z // such segments. // // X/Y/Z_THREAD defines a sub region of a thread block that should be reduced // with the sub regions of other thread blocks. We call it a reduction block. // E.g., // // Case 1: X/Y/Z_THREAD == false/false/false -> Only thread 0 participates in // the cross-block reductions. The reduction block is 1x1x1 with thread 0. // // Case 2: X/Y/Z_THREAD == true/true/true-> All threads in a thread block // participate in the cross-block reductions. The reduction block in this case // is equivalent to the thread block. // // After the function completes, only one thread block per reduction segment // gets valid reduction results. There is no guarantee which particular block // gets the final results. // template < bool X_BLOCK, bool Y_BLOCK, bool Z_BLOCK, bool X_THREAD, bool Y_THREAD, bool Z_THREAD, typename T, typename Func> __device__ bool gridReduce( T& out, T inp_val, Func reduction_op, volatile T* work_buf, Tensor<int64_t, 1> sync_flags, T* shared_buf, bool read_write_pred, T init_val) { // Number of values to reduce in the grid dimensions const auto seg_size = size_of_reduction_segment<X_BLOCK, Y_BLOCK, Z_BLOCK>(gridDim); // Index of the reduction we're performing out of the seg_size const auto seg_idx = index_of_reduction_segment<X_BLOCK, Y_BLOCK, Z_BLOCK>(blockIdx, gridDim); // Number of threads we can use in final reduction, Seems to assume all // threads in the block participate const auto rblock_size = size_of_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>(blockDim); // advance to the offset for this segment // index of reduction * size of the reduction * size of threads work_buf += seg_idx * seg_size * rblock_size; if ((X_THREAD || threadIdx.x == 0) && (Y_THREAD || threadIdx.y == 0) && (Z_THREAD || threadIdx.z == 0)) { auto rblock_offset = offset_in_reduction_segment<X_BLOCK, Y_BLOCK, Z_BLOCK>( blockIdx, gridDim); auto thread_offset = offset_in_reduction_block<X_THREAD, Y_THREAD, Z_THREAD>( threadIdx, blockDim); auto work_buf_offset = rblock_size * rblock_offset + thread_offset; if (read_write_pred) { work_buf[work_buf_offset] = inp_val; } else { work_buf[work_buf_offset] = init_val; } } __syncthreads(); __shared__ bool last_block; if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) { __threadfence(); // printf("%ld\n", sync_flags[seg_idx]); auto old = (int64_t)atomicAdd((unsigned long long*)&sync_flags[seg_idx], 1); last_block = old + 1 == seg_size; // printf("Last_block = %d + 1 == %d\n", (int)old, (int)seg_size); } __syncthreads(); if (last_block) { // printf("Last block %d %d %d %d\n", blockIdx.x, blockIdx.y, blockIdx.z); // final reduction gridReduceLastBlock<X_THREAD, Y_THREAD, Z_THREAD>( out, (T*)work_buf, seg_size * rblock_size, reduction_op, shared_buf, read_write_pred, init_val); return true; } else { // printf("Not last block %d %d %d\n", blockIdx.x, blockIdx.y, blockIdx.z); return false; } } } // namespace reduction )"; } // namespace nvfuser_resources
[ "46971018+Ajblast@users.noreply.github.com" ]
46971018+Ajblast@users.noreply.github.com
9a453052e9369e618a723a5a3baad7de3cdedb42
385cb76729b67994db6ce40b70e6f6806c5f4303
/RomiRobot_MovementAndMapping_v1.5/button.h
4331c6538c701bd0b2455217e40084fba326cbb3
[ "MIT" ]
permissive
meisben/RomiRobot_MovementAndMapping
f638f8d26fd846558bbfa66ed4edadc4de60e690
993d3c5c2fc067f343343662a3a0dc31a8e133ce
refs/heads/master
2020-05-17T14:10:02.422730
2019-05-08T19:46:51
2019-05-08T19:46:51
183,757,226
2
1
null
null
null
null
UTF-8
C++
false
false
6,348
h
// Arduino Button Library // https://github.com/JChristensen/JC_Button // Copyright (C) 2018 by Jack Christensen and licensed under // GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html #ifndef JC_BUTTON_H_INCLUDED #define JC_BUTTON_H_INCLUDED //#include <Arduino.h> class Button { public: // Button(pin, dbTime, puEnable, invert) instantiates a button object. // // Required parameter: // pin The Arduino pin the button is connected to // // Optional parameters: // dbTime Debounce time in milliseconds (default 25ms) // puEnable true to enable the AVR internal pullup resistor (default true) // invert true to interpret a low logic level as pressed (default true) Button(uint8_t pin, uint32_t dbTime=25, uint8_t puEnable=true, uint8_t invert=true) : m_pin(pin), m_dbTime(dbTime), m_puEnable(puEnable), m_invert(invert) {} // Initialize a Button object and the pin it's connected to void begin(); // Returns the current debounced button state, true for pressed, // false for released. Call this function frequently to ensure // the sketch is responsive to user input. bool read(); // Returns true if the button state was pressed at the last call to read(). // Does not cause the button to be read. bool isPressed(); // Returns true if the button state was released at the last call to read(). // Does not cause the button to be read. bool isReleased(); // Returns true if the button state at the last call to read() was pressed, // and this was a change since the previous read. bool wasPressed(); // Returns true if the button state at the last call to read() was released, // and this was a change since the previous read. bool wasReleased(); // Returns true if the button state at the last call to read() was pressed, // and has been in that state for at least the given number of milliseconds. bool pressedFor(uint32_t ms); // Returns true if the button state at the last call to read() was released, // and has been in that state for at least the given number of milliseconds. bool releasedFor(uint32_t ms); // Returns the time in milliseconds (from millis) that the button last // changed state. uint32_t lastChange(); private: uint8_t m_pin; // arduino pin number connected to button uint32_t m_dbTime; // debounce time (ms) bool m_puEnable; // internal pullup resistor enabled bool m_invert; // if true, interpret logic low as pressed, else interpret logic high as pressed bool m_state; // current button state, true=pressed bool m_lastState; // previous button state bool m_changed; // state changed since last read uint32_t m_time; // time of current state (ms from millis) uint32_t m_lastChange; // time of last state change (ms) }; /*----------------------------------------------------------------------* / initialize a Button object and the pin it's connected to. * /-----------------------------------------------------------------------*/ void Button::begin() { pinMode(m_pin, m_puEnable ? INPUT_PULLUP : INPUT); m_state = digitalRead(m_pin); if (m_invert) m_state = !m_state; m_time = millis(); m_lastState = m_state; m_changed = false; m_lastChange = m_time; } /*----------------------------------------------------------------------* / returns the state of the button, true if pressed, false if released. * / does debouncing, captures and maintains times, previous state, etc. * /-----------------------------------------------------------------------*/ bool Button::read() { uint32_t ms = millis(); bool pinVal = digitalRead(m_pin); if (m_invert) pinVal = !pinVal; if (ms - m_lastChange < m_dbTime) { m_changed = false; } else { m_lastState = m_state; m_state = pinVal; m_changed = (m_state != m_lastState); if (m_changed) m_lastChange = ms; } m_time = ms; return m_state; } /*----------------------------------------------------------------------* * isPressed() and isReleased() check the button state when it was last * * read, and return false (0) or true (!=0) accordingly. * * These functions do not cause the button to be read. * *----------------------------------------------------------------------*/ bool Button::isPressed() { return m_state; } bool Button::isReleased() { return !m_state; } /*----------------------------------------------------------------------* * wasPressed() and wasReleased() check the button state to see if it * * changed between the last two reads and return false (0) or * * true (!=0) accordingly. * * These functions do not cause the button to be read. * *----------------------------------------------------------------------*/ bool Button::wasPressed() { return m_state && m_changed; } bool Button::wasReleased() { return !m_state && m_changed; } /*----------------------------------------------------------------------* * pressedFor(ms) and releasedFor(ms) check to see if the button is * * pressed (or released), and has been in that state for the specified * * time in milliseconds. Returns false (0) or true (!=0) accordingly. * * These functions do not cause the button to be read. * *----------------------------------------------------------------------*/ bool Button::pressedFor(uint32_t ms) { return m_state && m_time - m_lastChange >= ms; } bool Button::releasedFor(uint32_t ms) { return !m_state && m_time - m_lastChange >= ms; } /*----------------------------------------------------------------------* * lastChange() returns the time the button last changed state, * * in milliseconds. * *----------------------------------------------------------------------*/ uint32_t Button::lastChange() { return m_lastChange; } #endif
[ "afunnyllama@gmail.com" ]
afunnyllama@gmail.com
6d15cafe514d886b84547382bd95847972d37c7f
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_10710.cpp
542a39d6f5a2e9db385a2fbd0a1ab113cbf60190
[]
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
103
cpp
{ ci->folders[i].digest_defined = digest.defineds[i]; ci->folders[i].digest = digest.digests[i]; }
[ "993273596@qq.com" ]
993273596@qq.com
5e02ee8bee47050190672a5ec52f15926e9d067b
0f171cb8ebcae3acf824fae38608df156cd512a2
/src/rpc/core_rpc_server.cpp
80bc210f6e8dfb70600b0dcb52c62392e1db8713
[ "BSD-3-Clause" ]
permissive
projekgallus/galluscoin
55c136574a3a0aec6b0c2a9599ed602644fd8bef
84c33ab8cf2d187d514957110060114bc66cb944
refs/heads/master
2020-03-07T05:06:22.648000
2018-07-09T22:10:40
2018-07-09T22:10:40
127,286,033
5
4
null
null
null
null
UTF-8
C++
false
false
57,438
cpp
// Copyright (c) 2014-2017, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <boost/foreach.hpp> #include "include_base_utils.h" using namespace epee; #include "core_rpc_server.h" #include "common/command_line.h" #include "cryptonote_core/cryptonote_format_utils.h" #include "cryptonote_core/account.h" #include "cryptonote_core/cryptonote_basic_impl.h" #include "misc_language.h" #include "crypto/hash.h" #include "core_rpc_server_error_codes.h" #define MAX_RESTRICTED_FAKE_OUTS_COUNT 40 #define MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT 500 namespace cryptonote { //----------------------------------------------------------------------------------- void core_rpc_server::init_options(boost::program_options::options_description& desc) { command_line::add_arg(desc, arg_rpc_bind_ip); command_line::add_arg(desc, arg_rpc_bind_port); command_line::add_arg(desc, arg_testnet_rpc_bind_port); command_line::add_arg(desc, arg_restricted_rpc); command_line::add_arg(desc, arg_user_agent); } //------------------------------------------------------------------------------------------------------------------------------ core_rpc_server::core_rpc_server( core& cr , nodetool::node_server<cryptonote::t_cryptonote_protocol_handler<cryptonote::core> >& p2p ) : m_core(cr) , m_p2p(p2p) {} //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::handle_command_line( const boost::program_options::variables_map& vm ) { auto p2p_bind_arg = m_testnet ? arg_testnet_rpc_bind_port : arg_rpc_bind_port; m_bind_ip = command_line::get_arg(vm, arg_rpc_bind_ip); m_port = command_line::get_arg(vm, p2p_bind_arg); m_restricted = command_line::get_arg(vm, arg_restricted_rpc); return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::init( const boost::program_options::variables_map& vm ) { m_testnet = command_line::get_arg(vm, command_line::arg_testnet_on); std::string m_user_agent = command_line::get_arg(vm, command_line::arg_user_agent); m_net_server.set_threads_prefix("RPC"); bool r = handle_command_line(vm); CHECK_AND_ASSERT_MES(r, false, "Failed to process command line in core_rpc_server"); return epee::http_server_impl_base<core_rpc_server, connection_context>::init(m_port, m_bind_ip, m_user_agent); } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::check_core_busy() { if(m_p2p.get_payload_object().get_core().get_blockchain_storage().is_storing_blockchain()) { return false; } return true; } #define CHECK_CORE_BUSY() do { if(!check_core_busy()){res.status = CORE_RPC_STATUS_BUSY;return true;} } while(0) //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::check_core_ready() { if(!m_p2p.get_payload_object().is_synchronized()) { return false; } return check_core_busy(); } #define CHECK_CORE_READY() do { if(!check_core_ready()){res.status = CORE_RPC_STATUS_BUSY;return true;} } while(0) //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_height(const COMMAND_RPC_GET_HEIGHT::request& req, COMMAND_RPC_GET_HEIGHT::response& res) { CHECK_CORE_BUSY(); res.height = m_core.get_current_blockchain_height(); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_info(const COMMAND_RPC_GET_INFO::request& req, COMMAND_RPC_GET_INFO::response& res) { CHECK_CORE_BUSY(); crypto::hash top_hash; if (!m_core.get_blockchain_top(res.height, top_hash)) { res.status = "Failed"; return false; } ++res.height; // turn top block height into blockchain height res.top_block_hash = string_tools::pod_to_hex(top_hash); res.target_height = m_core.get_target_blockchain_height(); res.difficulty = m_core.get_blockchain_storage().get_difficulty_for_next_block(); res.target = DIFFICULTY_TARGET; res.tx_count = m_core.get_blockchain_storage().get_total_transactions() - res.height; //without coinbase res.tx_pool_size = m_core.get_pool_transactions_count(); res.alt_blocks_count = m_core.get_blockchain_storage().get_alternative_blocks_count(); uint64_t total_conn = m_p2p.get_connections_count(); res.outgoing_connections_count = m_p2p.get_outgoing_connections_count(); res.incoming_connections_count = total_conn - res.outgoing_connections_count; res.white_peerlist_size = m_p2p.get_peerlist_manager().get_white_peers_count(); res.grey_peerlist_size = m_p2p.get_peerlist_manager().get_gray_peers_count(); res.testnet = m_testnet; res.cumulative_difficulty = m_core.get_blockchain_storage().get_db().get_block_cumulative_difficulty(res.height - 1); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_blocks(const COMMAND_RPC_GET_BLOCKS_FAST::request& req, COMMAND_RPC_GET_BLOCKS_FAST::response& res) { CHECK_CORE_BUSY(); std::list<std::pair<block, std::list<transaction> > > bs; if(!m_core.find_blockchain_supplement(req.start_height, req.block_ids, bs, res.current_height, res.start_height, COMMAND_RPC_GET_BLOCKS_FAST_MAX_COUNT)) { res.status = "Failed"; return false; } BOOST_FOREACH(auto& b, bs) { res.blocks.resize(res.blocks.size()+1); res.blocks.back().block = block_to_blob(b.first); res.output_indices.push_back(COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices()); res.output_indices.back().indices.push_back(COMMAND_RPC_GET_BLOCKS_FAST::tx_output_indices()); bool r = m_core.get_tx_outputs_gindexs(get_transaction_hash(b.first.miner_tx), res.output_indices.back().indices.back().indices); if (!r) { res.status = "Failed"; return false; } size_t txidx = 0; BOOST_FOREACH(auto& t, b.second) { res.blocks.back().txs.push_back(tx_to_blob(t)); res.output_indices.back().indices.push_back(COMMAND_RPC_GET_BLOCKS_FAST::tx_output_indices()); bool r = m_core.get_tx_outputs_gindexs(b.first.tx_hashes[txidx++], res.output_indices.back().indices.back().indices); if (!r) { res.status = "Failed"; return false; } } } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_hashes(const COMMAND_RPC_GET_HASHES_FAST::request& req, COMMAND_RPC_GET_HASHES_FAST::response& res) { CHECK_CORE_BUSY(); NOTIFY_RESPONSE_CHAIN_ENTRY::request resp; resp.start_height = req.start_height; if(!m_core.find_blockchain_supplement(req.block_ids, resp)) { res.status = "Failed"; return false; } res.current_height = resp.total_height; res.start_height = resp.start_height; res.m_block_ids = std::move(resp.m_block_ids); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_random_outs(const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request& req, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response& res) { CHECK_CORE_BUSY(); res.status = "Failed"; if (m_restricted) { if (req.amounts.size() > 100 || req.outs_count > MAX_RESTRICTED_FAKE_OUTS_COUNT) { res.status = "Too many outs requested"; return true; } } if(!m_core.get_random_outs_for_amounts(req, res)) { return true; } res.status = CORE_RPC_STATUS_OK; std::stringstream ss; typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount outs_for_amount; typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry out_entry; std::for_each(res.outs.begin(), res.outs.end(), [&](outs_for_amount& ofa) { ss << "[" << ofa.amount << "]:"; CHECK_AND_ASSERT_MES(ofa.outs.size(), ;, "internal error: ofa.outs.size() is empty for amount " << ofa.amount); std::for_each(ofa.outs.begin(), ofa.outs.end(), [&](out_entry& oe) { ss << oe.global_amount_index << " "; }); ss << ENDL; }); std::string s = ss.str(); LOG_PRINT_L2("COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS: " << ENDL << s); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_outs_bin(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res) { CHECK_CORE_BUSY(); res.status = "Failed"; if (m_restricted) { if (req.outputs.size() > MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT) { res.status = "Too many outs requested"; return true; } } if(!m_core.get_outs(req, res)) { return true; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_outs(const COMMAND_RPC_GET_OUTPUTS::request& req, COMMAND_RPC_GET_OUTPUTS::response& res) { CHECK_CORE_BUSY(); res.status = "Failed"; if (m_restricted) { if (req.outputs.size() > MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT) { res.status = "Too many outs requested"; return true; } } cryptonote::COMMAND_RPC_GET_OUTPUTS_BIN::request req_bin; req_bin.outputs = req.outputs; cryptonote::COMMAND_RPC_GET_OUTPUTS_BIN::response res_bin; if(!m_core.get_outs(req_bin, res_bin)) { return true; } // convert to text for (const auto &i: res_bin.outs) { res.outs.push_back(cryptonote::COMMAND_RPC_GET_OUTPUTS::outkey()); cryptonote::COMMAND_RPC_GET_OUTPUTS::outkey &outkey = res.outs.back(); outkey.key = epee::string_tools::pod_to_hex(i.key); outkey.mask = epee::string_tools::pod_to_hex(i.mask); outkey.unlocked = i.unlocked; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_random_rct_outs(const COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::request& req, COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::response& res) { CHECK_CORE_BUSY(); res.status = "Failed"; if(!m_core.get_random_rct_outs(req, res)) { return true; } res.status = CORE_RPC_STATUS_OK; std::stringstream ss; typedef COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::out_entry out_entry; CHECK_AND_ASSERT_MES(res.outs.size(), true, "internal error: res.outs.size() is empty"); std::for_each(res.outs.begin(), res.outs.end(), [&](out_entry& oe) { ss << oe.global_amount_index << " "; }); ss << ENDL; std::string s = ss.str(); LOG_PRINT_L2("COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS: " << ENDL << s); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_indexes(const COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::request& req, COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::response& res) { CHECK_CORE_BUSY(); bool r = m_core.get_tx_outputs_gindexs(req.txid, res.o_indexes); if(!r) { res.status = "Failed"; return true; } res.status = CORE_RPC_STATUS_OK; LOG_PRINT_L2("COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES: [" << res.o_indexes.size() << "]"); return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_transactions(const COMMAND_RPC_GET_TRANSACTIONS::request& req, COMMAND_RPC_GET_TRANSACTIONS::response& res) { CHECK_CORE_BUSY(); std::vector<crypto::hash> vh; BOOST_FOREACH(const auto& tx_hex_str, req.txs_hashes) { blobdata b; if(!string_tools::parse_hexstr_to_binbuff(tx_hex_str, b)) { res.status = "Failed to parse hex representation of transaction hash"; return true; } if(b.size() != sizeof(crypto::hash)) { res.status = "Failed, size of data mismatch"; return true; } vh.push_back(*reinterpret_cast<const crypto::hash*>(b.data())); } std::list<crypto::hash> missed_txs; std::list<transaction> txs; bool r = m_core.get_transactions(vh, txs, missed_txs); if(!r) { res.status = "Failed"; return true; } LOG_PRINT_L2("Found " << txs.size() << "/" << vh.size() << " transactions on the blockchain"); // try the pool for any missing txes size_t found_in_pool = 0; std::unordered_set<crypto::hash> pool_tx_hashes; if (!missed_txs.empty()) { std::list<transaction> pool_txs; bool r = m_core.get_pool_transactions(pool_txs); if(r) { for (std::list<transaction>::const_iterator i = pool_txs.begin(); i != pool_txs.end(); ++i) { crypto::hash tx_hash = get_transaction_hash(*i); std::list<crypto::hash>::iterator mi = std::find(missed_txs.begin(), missed_txs.end(), tx_hash); if (mi != missed_txs.end()) { pool_tx_hashes.insert(tx_hash); missed_txs.erase(mi); txs.push_back(*i); ++found_in_pool; } } } LOG_PRINT_L2("Found " << found_in_pool << "/" << vh.size() << " transactions in the pool"); } std::list<std::string>::const_iterator txhi = req.txs_hashes.begin(); std::vector<crypto::hash>::const_iterator vhi = vh.begin(); BOOST_FOREACH(auto& tx, txs) { res.txs.push_back(COMMAND_RPC_GET_TRANSACTIONS::entry()); COMMAND_RPC_GET_TRANSACTIONS::entry &e = res.txs.back(); crypto::hash tx_hash = *vhi++; e.tx_hash = *txhi++; blobdata blob = t_serializable_object_to_blob(tx); e.as_hex = string_tools::buff_to_hex_nodelimer(blob); if (req.decode_as_json) e.as_json = obj_to_json_str(tx); e.in_pool = pool_tx_hashes.find(tx_hash) != pool_tx_hashes.end(); if (e.in_pool) { e.block_height = std::numeric_limits<uint64_t>::max(); } else { e.block_height = m_core.get_blockchain_storage().get_db().get_tx_block_height(tx_hash); } // fill up old style responses too, in case an old wallet asks res.txs_as_hex.push_back(e.as_hex); if (req.decode_as_json) res.txs_as_json.push_back(e.as_json); // output indices too if not in pool if (pool_tx_hashes.find(tx_hash) == pool_tx_hashes.end()) { bool r = m_core.get_tx_outputs_gindexs(tx_hash, e.output_indices); if (!r) { res.status = "Failed"; return false; } } } BOOST_FOREACH(const auto& miss_tx, missed_txs) { res.missed_tx.push_back(string_tools::pod_to_hex(miss_tx)); } LOG_PRINT_L2(res.txs.size() << " transactions found, " << res.missed_tx.size() << " not found"); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_is_key_image_spent(const COMMAND_RPC_IS_KEY_IMAGE_SPENT::request& req, COMMAND_RPC_IS_KEY_IMAGE_SPENT::response& res) { CHECK_CORE_BUSY(); std::vector<crypto::key_image> key_images; BOOST_FOREACH(const auto& ki_hex_str, req.key_images) { blobdata b; if(!string_tools::parse_hexstr_to_binbuff(ki_hex_str, b)) { res.status = "Failed to parse hex representation of key image"; return true; } if(b.size() != sizeof(crypto::key_image)) { res.status = "Failed, size of data mismatch"; } key_images.push_back(*reinterpret_cast<const crypto::key_image*>(b.data())); } std::vector<bool> spent_status; bool r = m_core.are_key_images_spent(key_images, spent_status); if(!r) { res.status = "Failed"; return true; } res.spent_status.clear(); for (size_t n = 0; n < spent_status.size(); ++n) res.spent_status.push_back(spent_status[n] ? COMMAND_RPC_IS_KEY_IMAGE_SPENT::SPENT_IN_BLOCKCHAIN : COMMAND_RPC_IS_KEY_IMAGE_SPENT::UNSPENT); // check the pool too std::vector<cryptonote::tx_info> txs; std::vector<cryptonote::spent_key_image_info> ki; r = m_core.get_pool_transactions_and_spent_keys_info(txs, ki); if(!r) { res.status = "Failed"; return true; } for (std::vector<cryptonote::spent_key_image_info>::const_iterator i = ki.begin(); i != ki.end(); ++i) { crypto::hash hash; crypto::key_image spent_key_image; if (parse_hash256(i->id_hash, hash)) { memcpy(&spent_key_image, &hash, sizeof(hash)); // a bit dodgy, should be other parse functions somewhere for (size_t n = 0; n < res.spent_status.size(); ++n) { if (res.spent_status[n] == COMMAND_RPC_IS_KEY_IMAGE_SPENT::UNSPENT) { if (key_images[n] == spent_key_image) { res.spent_status[n] = COMMAND_RPC_IS_KEY_IMAGE_SPENT::SPENT_IN_POOL; break; } } } } } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_send_raw_tx(const COMMAND_RPC_SEND_RAW_TX::request& req, COMMAND_RPC_SEND_RAW_TX::response& res) { CHECK_CORE_READY(); std::string tx_blob; if(!string_tools::parse_hexstr_to_binbuff(req.tx_as_hex, tx_blob)) { LOG_PRINT_L0("[on_send_raw_tx]: Failed to parse tx from hexbuff: " << req.tx_as_hex); res.status = "Failed"; return true; } cryptonote_connection_context fake_context = AUTO_VAL_INIT(fake_context); tx_verification_context tvc = AUTO_VAL_INIT(tvc); if(!m_core.handle_incoming_tx(tx_blob, tvc, false, false) || tvc.m_verifivation_failed) { if (tvc.m_verifivation_failed) { LOG_PRINT_L0("[on_send_raw_tx]: tx verification failed"); } else { LOG_PRINT_L0("[on_send_raw_tx]: Failed to process tx"); } res.status = "Failed"; if ((res.low_mixin = tvc.m_low_mixin)) res.reason = "mixin too low"; if ((res.high_mixin = tvc.m_high_mixin)) res.reason = "mixin too high"; if ((res.double_spend = tvc.m_double_spend)) res.reason = "double spend"; if ((res.invalid_input = tvc.m_invalid_input)) res.reason = "invalid input"; if ((res.invalid_output = tvc.m_invalid_output)) res.reason = "invalid output"; if ((res.too_big = tvc.m_too_big)) res.reason = "too big"; if ((res.overspend = tvc.m_overspend)) res.reason = "overspend"; if ((res.fee_too_low = tvc.m_fee_too_low)) res.reason = "fee too low"; if ((res.not_rct = tvc.m_not_rct)) res.reason = "tx is not ringct"; if ((res.invalid_tx_version = tvc.m_invalid_tx_version)) res.reason = "invalid tx version"; return true; } if(!tvc.m_should_be_relayed || req.do_not_relay) { LOG_PRINT_L0("[on_send_raw_tx]: tx accepted, but not relayed"); res.reason = "Not relayed"; res.not_relayed = true; res.status = CORE_RPC_STATUS_OK; return true; } NOTIFY_NEW_TRANSACTIONS::request r; r.txs.push_back(tx_blob); m_core.get_protocol()->relay_transactions(r, fake_context); //TODO: make sure that tx has reached other nodes here, probably wait to receive reflections from other nodes res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_start_mining(const COMMAND_RPC_START_MINING::request& req, COMMAND_RPC_START_MINING::response& res) { CHECK_CORE_READY(); cryptonote::address_parse_info info; if (!get_account_address_from_str(info, m_testnet, req.miner_address)) { res.status = "Failed, wrong address"; LOG_PRINT_L0(res.status); return true; } if (info.is_subaddress) { res.status = "Mining to subaddress isn't supported yet"; LOG_PRINT_L0(res.status); return true; } boost::thread::attributes attrs; attrs.set_stack_size(THREAD_STACK_SIZE); if (!m_core.get_miner().start(info.address, static_cast<size_t>(req.threads_count), attrs)) { res.status = "Failed, mining not started"; LOG_PRINT_L0(res.status); return true; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_stop_mining(const COMMAND_RPC_STOP_MINING::request& req, COMMAND_RPC_STOP_MINING::response& res) { if(!m_core.get_miner().stop()) { res.status = "Failed, mining not stopped"; LOG_PRINT_L0(res.status); return true; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_mining_status(const COMMAND_RPC_MINING_STATUS::request& req, COMMAND_RPC_MINING_STATUS::response& res) { CHECK_CORE_READY(); const miner& lMiner = m_core.get_miner(); res.active = lMiner.is_mining(); if ( lMiner.is_mining() ) { res.speed = lMiner.get_speed(); res.threads_count = lMiner.get_threads_count(); const account_public_address& lMiningAdr = lMiner.get_mining_address(); res.address = get_account_address_as_str(m_testnet, false, lMiningAdr); } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_save_bc(const COMMAND_RPC_SAVE_BC::request& req, COMMAND_RPC_SAVE_BC::response& res) { CHECK_CORE_BUSY(); if( !m_core.get_blockchain_storage().store_blockchain() ) { res.status = "Error while storing blockhain"; return true; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_peer_list(const COMMAND_RPC_GET_PEER_LIST::request& req, COMMAND_RPC_GET_PEER_LIST::response& res) { std::list<nodetool::peerlist_entry> white_list; std::list<nodetool::peerlist_entry> gray_list; m_p2p.get_peerlist_manager().get_peerlist_full(gray_list, white_list); for (auto & entry : white_list) { res.white_list.emplace_back(entry.id, entry.adr.ip, entry.adr.port, entry.last_seen); } for (auto & entry : gray_list) { res.gray_list.emplace_back(entry.id, entry.adr.ip, entry.adr.port, entry.last_seen); } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_set_log_hash_rate(const COMMAND_RPC_SET_LOG_HASH_RATE::request& req, COMMAND_RPC_SET_LOG_HASH_RATE::response& res) { if(m_core.get_miner().is_mining()) { m_core.get_miner().do_print_hashrate(req.visible); res.status = CORE_RPC_STATUS_OK; } else { res.status = CORE_RPC_STATUS_NOT_MINING; } return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_set_log_level(const COMMAND_RPC_SET_LOG_LEVEL::request& req, COMMAND_RPC_SET_LOG_LEVEL::response& res) { if (req.level < LOG_LEVEL_MIN || req.level > LOG_LEVEL_MAX) { res.status = "Error: log level not valid"; } else { epee::log_space::log_singletone::get_set_log_detalisation_level(true, req.level); int otshell_utils_log_level = 100 - (req.level * 20); gCurrentLogger.setDebugLevel(otshell_utils_log_level); res.status = CORE_RPC_STATUS_OK; } return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_transaction_pool(const COMMAND_RPC_GET_TRANSACTION_POOL::request& req, COMMAND_RPC_GET_TRANSACTION_POOL::response& res) { CHECK_CORE_BUSY(); m_core.get_pool_transactions_and_spent_keys_info(res.transactions, res.spent_key_images); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_stop_daemon(const COMMAND_RPC_STOP_DAEMON::request& req, COMMAND_RPC_STOP_DAEMON::response& res) { // FIXME: replace back to original m_p2p.send_stop_signal() after // investigating why that isn't working quite right. m_p2p.send_stop_signal(); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_getblockcount(const COMMAND_RPC_GETBLOCKCOUNT::request& req, COMMAND_RPC_GETBLOCKCOUNT::response& res) { CHECK_CORE_BUSY(); res.count = m_core.get_current_blockchain_height(); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_getblockhash(const COMMAND_RPC_GETBLOCKHASH::request& req, COMMAND_RPC_GETBLOCKHASH::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy"; return false; } if(req.size() != 1) { error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM; error_resp.message = "Wrong parameters, expected height"; return false; } uint64_t h = req[0]; if(m_core.get_current_blockchain_height() <= h) { error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT; error_resp.message = std::string("Too big height: ") + std::to_string(h) + ", current blockchain height = " + std::to_string(m_core.get_current_blockchain_height()); } res = string_tools::pod_to_hex(m_core.get_block_id_by_height(h)); return true; } //------------------------------------------------------------------------------------------------------------------------------ // equivalent of strstr, but with arbitrary bytes (ie, NULs) // This does not differentiate between "not found" and "found at offset 0" uint64_t slow_memmem(const void* start_buff, size_t buflen,const void* pat,size_t patlen) { const void* buf = start_buff; const void* end=(const char*)buf+buflen; if (patlen > buflen || patlen == 0) return 0; while(buflen>0 && (buf=memchr(buf,((const char*)pat)[0],buflen-patlen+1))) { if(memcmp(buf,pat,patlen)==0) return (const char*)buf - (const char*)start_buff; buf=(const char*)buf+1; buflen = (const char*)end - (const char*)buf; } return 0; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_getblocktemplate(const COMMAND_RPC_GETBLOCKTEMPLATE::request& req, COMMAND_RPC_GETBLOCKTEMPLATE::response& res, epee::json_rpc::error& error_resp) { if(!check_core_ready()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy"; return false; } if(req.reserve_size > 255) { error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_RESERVE_SIZE; error_resp.message = "To big reserved size, maximum 255"; return false; } cryptonote::address_parse_info info; if (!req.wallet_address.size() || !cryptonote::get_account_address_from_str(info, m_testnet, req.wallet_address)) { error_resp.code = CORE_RPC_ERROR_CODE_WRONG_WALLET_ADDRESS; error_resp.message = "Failed to parse wallet address"; return false; } if (info.is_subaddress) { error_resp.code = CORE_RPC_ERROR_CODE_MINING_TO_SUBADDRESS; error_resp.message = "Mining to subaddress is not supported yet"; return false; } block b = AUTO_VAL_INIT(b); cryptonote::blobdata blob_reserve; blob_reserve.resize(req.reserve_size, 0); if(!m_core.get_block_template(b, info.address, res.difficulty, res.height, blob_reserve)) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: failed to create block template"; LOG_ERROR("Failed to create block template"); return false; } blobdata block_blob = t_serializable_object_to_blob(b); crypto::public_key tx_pub_key = cryptonote::get_tx_pub_key_from_extra(b.miner_tx); if(tx_pub_key == null_pkey) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: failed to create block template"; LOG_ERROR("Failed to tx pub key in coinbase extra"); return false; } res.reserved_offset = slow_memmem((void*)block_blob.data(), block_blob.size(), &tx_pub_key, sizeof(tx_pub_key)); if(!res.reserved_offset) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: failed to create block template"; LOG_ERROR("Failed to find tx pub key in blockblob"); return false; } res.reserved_offset += sizeof(tx_pub_key) + 3; //3 bytes: tag for TX_EXTRA_TAG_PUBKEY(1 byte), tag for TX_EXTRA_NONCE(1 byte), counter in TX_EXTRA_NONCE(1 byte) if(res.reserved_offset + req.reserve_size > block_blob.size()) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: failed to create block template"; LOG_ERROR("Failed to calculate offset for "); return false; } blobdata hashing_blob = get_block_hashing_blob(b); res.prev_hash = string_tools::pod_to_hex(b.prev_id); res.blocktemplate_blob = string_tools::buff_to_hex_nodelimer(block_blob); res.blockhashing_blob = string_tools::buff_to_hex_nodelimer(hashing_blob); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_submitblock(const COMMAND_RPC_SUBMITBLOCK::request& req, COMMAND_RPC_SUBMITBLOCK::response& res, epee::json_rpc::error& error_resp) { CHECK_CORE_READY(); if(req.size()!=1) { error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM; error_resp.message = "Wrong param"; return false; } blobdata blockblob; if(!string_tools::parse_hexstr_to_binbuff(req[0], blockblob)) { error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB; error_resp.message = "Wrong block blob"; return false; } // Fixing of high orphan issue for most pools // Thanks Boolberry! block b = AUTO_VAL_INIT(b); if(!parse_and_validate_block_from_blob(blockblob, b)) { error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB; error_resp.message = "Wrong block blob"; return false; } // Fix from Boolberry neglects to check block // size, do that with the function below if(!m_core.check_incoming_block_size(blockblob)) { error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB_SIZE; error_resp.message = "Block bloc size is too big, rejecting block"; return false; } if(!m_core.handle_block_found(b)) { error_resp.code = CORE_RPC_ERROR_CODE_BLOCK_NOT_ACCEPTED; error_resp.message = "Block not accepted"; return false; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ uint64_t core_rpc_server::get_block_reward(const block& blk) { uint64_t reward = 0; BOOST_FOREACH(const tx_out& out, blk.miner_tx.vout) { reward += out.amount; } return reward; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::fill_block_header_response(const block& blk, bool orphan_status, uint64_t height, const crypto::hash& hash, block_header_response& response) { response.major_version = blk.major_version; response.minor_version = blk.minor_version; response.timestamp = blk.timestamp; response.prev_hash = string_tools::pod_to_hex(blk.prev_id); response.nonce = blk.nonce; response.orphan_status = orphan_status; response.height = height; response.depth = m_core.get_current_blockchain_height() - height - 1; response.hash = string_tools::pod_to_hex(hash); response.difficulty = m_core.get_blockchain_storage().block_difficulty(height); response.reward = get_block_reward(blk); return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_last_block_header(const COMMAND_RPC_GET_LAST_BLOCK_HEADER::request& req, COMMAND_RPC_GET_LAST_BLOCK_HEADER::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } uint64_t last_block_height; crypto::hash last_block_hash; bool have_last_block_hash = m_core.get_blockchain_top(last_block_height, last_block_hash); if (!have_last_block_hash) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't get last block hash."; return false; } block last_block; bool have_last_block = m_core.get_block_by_hash(last_block_hash, last_block); if (!have_last_block) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't get last block."; return false; } bool response_filled = fill_block_header_response(last_block, false, last_block_height, last_block_hash, res.block_header); if (!response_filled) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't produce valid response."; return false; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_block_header_by_hash(const COMMAND_RPC_GET_BLOCK_HEADER_BY_HASH::request& req, COMMAND_RPC_GET_BLOCK_HEADER_BY_HASH::response& res, epee::json_rpc::error& error_resp){ if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } crypto::hash block_hash; bool hash_parsed = parse_hash256(req.hash, block_hash); if(!hash_parsed) { error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM; error_resp.message = "Failed to parse hex representation of block hash. Hex = " + req.hash + '.'; return false; } block blk; bool have_block = m_core.get_block_by_hash(block_hash, blk); if (!have_block) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't get block by hash. Hash = " + req.hash + '.'; return false; } if (blk.miner_tx.vin.front().type() != typeid(txin_gen)) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: coinbase transaction in the block has the wrong type"; return false; } uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height; bool response_filled = fill_block_header_response(blk, false, block_height, block_hash, res.block_header); if (!response_filled) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't produce valid response."; return false; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_block_headers_range(const COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::request& req, COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::response& res, epee::json_rpc::error& error_resp){ if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } const uint64_t bc_height = m_core.get_current_blockchain_height(); if (req.start_height >= bc_height || req.end_height >= bc_height || req.start_height > req.end_height) { error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT; error_resp.message = "Invalid start/end heights."; return false; } for (uint64_t h = req.start_height; h <= req.end_height; ++h) { crypto::hash block_hash = m_core.get_block_id_by_height(h); block blk; bool have_block = m_core.get_block_by_hash(block_hash, blk); if (!have_block) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't get block by height. Height = " + boost::lexical_cast<std::string>(h) + ". Hash = " + epee::string_tools::pod_to_hex(block_hash) + '.'; return false; } if (blk.miner_tx.vin.front().type() != typeid(txin_gen)) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: coinbase transaction in the block has the wrong type"; return false; } uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height; if (block_height != h) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: coinbase transaction in the block has the wrong height"; return false; } res.headers.push_back(block_header_response()); bool responce_filled = fill_block_header_response(blk, false, block_height, block_hash, res.headers.back()); if (!responce_filled) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't produce valid response."; return false; } } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_block_header_by_height(const COMMAND_RPC_GET_BLOCK_HEADER_BY_HEIGHT::request& req, COMMAND_RPC_GET_BLOCK_HEADER_BY_HEIGHT::response& res, epee::json_rpc::error& error_resp){ if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } if(m_core.get_current_blockchain_height() <= req.height) { error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT; error_resp.message = std::string("Too big height: ") + std::to_string(req.height) + ", current blockchain height = " + std::to_string(m_core.get_current_blockchain_height()); return false; } crypto::hash block_hash = m_core.get_block_id_by_height(req.height); block blk; bool have_block = m_core.get_block_by_hash(block_hash, blk); if (!have_block) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't get block by height. Height = " + std::to_string(req.height) + '.'; return false; } bool response_filled = fill_block_header_response(blk, false, req.height, block_hash, res.block_header); if (!response_filled) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't produce valid response."; return false; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_block(const COMMAND_RPC_GET_BLOCK::request& req, COMMAND_RPC_GET_BLOCK::response& res, epee::json_rpc::error& error_resp){ if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } crypto::hash block_hash; if (!req.hash.empty()) { bool hash_parsed = parse_hash256(req.hash, block_hash); if(!hash_parsed) { error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM; error_resp.message = "Failed to parse hex representation of block hash. Hex = " + req.hash + '.'; return false; } } else { if(m_core.get_current_blockchain_height() <= req.height) { error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT; error_resp.message = std::string("Too big height: ") + std::to_string(req.height) + ", current blockchain height = " + std::to_string(m_core.get_current_blockchain_height()); return false; } block_hash = m_core.get_block_id_by_height(req.height); } block blk; bool have_block = m_core.get_block_by_hash(block_hash, blk); if (!have_block) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't get block by hash. Hash = " + req.hash + '.'; return false; } if (blk.miner_tx.vin.front().type() != typeid(txin_gen)) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: coinbase transaction in the block has the wrong type"; return false; } uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height; bool response_filled = fill_block_header_response(blk, false, block_height, block_hash, res.block_header); if (!response_filled) { error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR; error_resp.message = "Internal error: can't produce valid response."; return false; } for (size_t n = 0; n < blk.tx_hashes.size(); ++n) { res.tx_hashes.push_back(epee::string_tools::pod_to_hex(blk.tx_hashes[n])); } res.blob = string_tools::buff_to_hex_nodelimer(t_serializable_object_to_blob(blk)); res.json = obj_to_json_str(blk); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_connections(const COMMAND_RPC_GET_CONNECTIONS::request& req, COMMAND_RPC_GET_CONNECTIONS::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } res.connections = m_p2p.get_payload_object().get_connections(); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_info_json(const COMMAND_RPC_GET_INFO::request& req, COMMAND_RPC_GET_INFO::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } crypto::hash top_hash; if (!m_core.get_blockchain_top(res.height, top_hash)) { res.status = "Failed"; return false; } ++res.height; // turn top block height into blockchain height res.top_block_hash = string_tools::pod_to_hex(top_hash); res.target_height = m_core.get_target_blockchain_height(); res.difficulty = m_core.get_blockchain_storage().get_difficulty_for_next_block(); res.target = DIFFICULTY_TARGET; res.tx_count = m_core.get_blockchain_storage().get_total_transactions() - res.height; //without coinbase res.tx_pool_size = m_core.get_pool_transactions_count(); res.alt_blocks_count = m_core.get_blockchain_storage().get_alternative_blocks_count(); uint64_t total_conn = m_p2p.get_connections_count(); res.outgoing_connections_count = m_p2p.get_outgoing_connections_count(); res.incoming_connections_count = total_conn - res.outgoing_connections_count; res.white_peerlist_size = m_p2p.get_peerlist_manager().get_white_peers_count(); res.grey_peerlist_size = m_p2p.get_peerlist_manager().get_gray_peers_count(); res.testnet = m_testnet; res.cumulative_difficulty = m_core.get_blockchain_storage().get_db().get_block_cumulative_difficulty(res.height - 1); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_hard_fork_info(const COMMAND_RPC_HARD_FORK_INFO::request& req, COMMAND_RPC_HARD_FORK_INFO::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } const Blockchain &blockchain = m_core.get_blockchain_storage(); uint8_t version = req.version > 0 ? req.version : blockchain.get_next_hard_fork_version(); res.version = blockchain.get_current_hard_fork_version(); res.enabled = blockchain.get_hard_fork_voting_info(version, res.window, res.votes, res.threshold, res.earliest_height, res.voting); res.state = blockchain.get_hard_fork_state(); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_bans(const COMMAND_RPC_GETBANS::request& req, COMMAND_RPC_GETBANS::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } auto now = time(nullptr); std::map<uint32_t, time_t> blocked_ips = m_p2p.get_blocked_ips(); for (std::map<uint32_t, time_t>::const_iterator i = blocked_ips.begin(); i != blocked_ips.end(); ++i) { if (i->second > now) { COMMAND_RPC_GETBANS::ban b; b.ip = i->first; b.seconds = i->second - now; res.bans.push_back(b); } } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_set_bans(const COMMAND_RPC_SETBANS::request& req, COMMAND_RPC_SETBANS::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } for (auto i = req.bans.begin(); i != req.bans.end(); ++i) { if (i->ban) m_p2p.block_ip(i->ip, i->seconds); else m_p2p.unblock_ip(i->ip); } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_flush_txpool(const COMMAND_RPC_FLUSH_TRANSACTION_POOL::request& req, COMMAND_RPC_FLUSH_TRANSACTION_POOL::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } bool failed = false; std::list<crypto::hash> txids; if (req.txids.empty()) { std::list<transaction> pool_txs; bool r = m_core.get_pool_transactions(pool_txs); if (!r) { res.status = "Failed to get txpool contents"; return true; } for (const auto &tx: pool_txs) { txids.push_back(cryptonote::get_transaction_hash(tx)); } } else { for (const auto &str: req.txids) { cryptonote::blobdata txid_data; if(!epee::string_tools::parse_hexstr_to_binbuff(str, txid_data)) { failed = true; } crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data()); txids.push_back(txid); } } if (!m_core.get_blockchain_storage().flush_txes_from_pool(txids)) { res.status = "Failed to remove one more tx"; return false; } if (failed) { res.status = "Failed to parse txid"; return false; } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_output_histogram(const COMMAND_RPC_GET_OUTPUT_HISTOGRAM::request& req, COMMAND_RPC_GET_OUTPUT_HISTOGRAM::response& res, epee::json_rpc::error& error_resp) { if(!check_core_busy()) { error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY; error_resp.message = "Core is busy."; return false; } std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> histogram; try { histogram = m_core.get_blockchain_storage().get_output_histogram(req.amounts, req.unlocked, req.recent_cutoff); } catch (const std::exception &e) { res.status = "Failed to get output histogram"; return true; } res.histogram.clear(); res.histogram.reserve(histogram.size()); for (const auto &i: histogram) { if (std::get<0>(i.second) >= req.min_count && (std::get<0>(i.second) <= req.max_count || req.max_count == 0)) res.histogram.push_back(COMMAND_RPC_GET_OUTPUT_HISTOGRAM::entry(i.first, std::get<0>(i.second), std::get<1>(i.second), std::get<2>(i.second))); } res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_version(const COMMAND_RPC_GET_VERSION::request& req, COMMAND_RPC_GET_VERSION::response& res, epee::json_rpc::error& error_resp) { res.version = CORE_RPC_VERSION; res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_coinbase_tx_sum(const COMMAND_RPC_GET_COINBASE_TX_SUM::request& req, COMMAND_RPC_GET_COINBASE_TX_SUM::response& res, epee::json_rpc::error& error_resp) { std::pair<uint64_t, uint64_t> amounts = m_core.get_coinbase_tx_sum(req.height, req.count); res.emission_amount = amounts.first; res.fee_amount = amounts.second; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_get_per_kb_fee_estimate(const COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::request& req, COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::response& res, epee::json_rpc::error& error_resp) { res.fee = m_core.get_blockchain_storage().get_dynamic_per_kb_fee_estimate(req.grace_blocks); res.status = CORE_RPC_STATUS_OK; return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_out_peers(const COMMAND_RPC_OUT_PEERS::request& req, COMMAND_RPC_OUT_PEERS::response& res) { // TODO /*if (m_p2p.get_outgoing_connections_count() > req.out_peers) { m_p2p.m_config.m_net_config.connections_count = req.out_peers; if (m_p2p.get_outgoing_connections_count() > req.out_peers) { int count = m_p2p.get_outgoing_connections_count() - req.out_peers; m_p2p.delete_connections(count); } } else m_p2p.m_config.m_net_config.connections_count = req.out_peers; */ return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_start_save_graph(const COMMAND_RPC_START_SAVE_GRAPH::request& req, COMMAND_RPC_START_SAVE_GRAPH::response& res) { m_p2p.set_save_graph(true); return true; } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::on_stop_save_graph(const COMMAND_RPC_STOP_SAVE_GRAPH::request& req, COMMAND_RPC_STOP_SAVE_GRAPH::response& res) { m_p2p.set_save_graph(false); return true; } //------------------------------------------------------------------------------------------------------------------------------ const command_line::arg_descriptor<std::string> core_rpc_server::arg_rpc_bind_ip = { "rpc-bind-ip" , "IP for RPC server" , "127.0.0.1" }; const command_line::arg_descriptor<std::string> core_rpc_server::arg_rpc_bind_port = { "rpc-bind-port" , "Port for RPC server" , std::to_string(config::RPC_DEFAULT_PORT) }; const command_line::arg_descriptor<std::string> core_rpc_server::arg_testnet_rpc_bind_port = { "testnet-rpc-bind-port" , "Port for testnet RPC server" , std::to_string(config::testnet::RPC_DEFAULT_PORT) }; const command_line::arg_descriptor<bool> core_rpc_server::arg_restricted_rpc = { "restricted-rpc" , "Restrict RPC to view only commands" , false }; const command_line::arg_descriptor<std::string> core_rpc_server::arg_user_agent = { "user-agent" , "Restrict RPC to clients using this user agent" , "" }; } // namespace cryptonote
[ "" ]
b07a35e1e7d1737a41dbd736258e12b374575f9e
338a9f8e5f6d8b5b79b9c32b6319af16b02ff7b7
/tests/src/utility/LambdaFunctionWithCapturesBadCase.hpp
9cb71d085766876d48cf907c3eed16e97f63b78c
[ "MIT" ]
permissive
ddovod/jet-live
26b60783cbd5ab76015c4386318731e49cbcdc00
59c38997f7c16f54ddf9e68a189384bd11878568
refs/heads/master
2022-08-26T18:52:46.584817
2022-01-28T09:00:25
2022-01-28T09:00:25
163,978,787
394
33
MIT
2020-01-18T10:28:27
2019-01-03T13:47:39
C++
UTF-8
C++
false
false
110
hpp
#pragma once #include <functional> std::function<int(int, int)> createLambdaFunctionWithCapturesBadCase();
[ "ddovod@gmail.com" ]
ddovod@gmail.com
50ce1362bf441a420469de87853c389deb4baa06
b0f2c26360815e94da1aad9b931174be6019f2f2
/pasha/lect_17/reg_expression/main.cpp
34c8724445ea02458e8d6d422b39fce96813a6b9
[]
no_license
tarstars/prog_course_2013
aa2c1f21a06db40cd6fa84622a9f5fb29578dda5
60caba18ef418fe97e8d69e831864732a24fdd71
refs/heads/master
2020-05-17T12:44:06.451902
2013-12-17T10:52:03
2013-12-17T10:52:03
8,088,769
1
1
null
null
null
null
UTF-8
C++
false
false
958
cpp
#include <iostream> #include <QRegExp> #include <QImage> using namespace std; int main(int, char **) { QRegExp reCircle("circle\\((\\-?[0-9]+),(\\-?[0-9]+)\\),([0-9]+)"); QRegExp reLine("line\\(([0-9]+),([0-9]+)\\)\\-\\(([0-9]+),([0-9]+)\\)"); QRegExp reCls("cls"); int n = 800; QImage img(n, n, QImage::Format_ARGB32_Premultiplied); string command; while(getline(cin, command)) { if (reCircle.exactMatch(QString::fromStdString(command))) { int cx = reCircle.cap(1).toInt(); int cy = reCircle.cap(2).toInt(); int cr = reCircle.cap(3).toInt(); cout << "circle with x = " << cx << " y = " << cy << " r = " << cr << endl; for(int p = 0; p < n; ++p) { for(int q = 0; q < n; ++q) { int dx = cx - q; int dy = cy - p; if (dx * dx + dy * dy < cr * cr) { img.setPixel(q, p, qRgb(0,255,0)); } } } } else { cout << "no match" << endl; } } img.save("a.png"); return 0; }
[ "nikitin.pavel.a@gmail.com" ]
nikitin.pavel.a@gmail.com
6b63c1b942bdd8d08bff2164a561662b52cf58eb
6a3890b734797641a0e45dc2d882da370de63e49
/include/rdgill_subs.h
3315f6ec6d842528ac4f33980c5fa97f0b28fefa
[]
no_license
SysSynBio/StoichiometricBalance
f85222fd4bf650dbe0872dd29db10fd4b6ff30f6
2a9d3aac66bf5fc9ea1e29cb782afa4ae034983b
refs/heads/master
2023-03-16T13:22:54.631650
2020-10-29T21:49:13
2020-10-29T21:49:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
803
h
#include <fstream> #include <iostream> #include <ctime> #include <cmath> #include <string> #include "write_conc_vs_time.h" using namespace std; void check_reactions(Parms plist, int *numpartners, int **Speclist, int *Nmyrxn, int **Rlist, int **myrxn, int Nspecies); void read_reactions_complex(ifstream &rxnfile, int Nrxn, int **Rlist, int *Nmyrxn, int **myrxn, int *rxntype, double *k, int Nspecies, int **Del, int *Npart, int *Ncoup, int **mycoupled, int *rxn2D, int Nifaces, int *mem_prod, int *sol_prod, ProductName *complexnames); /*below is with also RD states*/ void read_protlist_twostate(int nwhole, gillProtein *wholep, int Niface, int *p_home, ifstream &protfile, int *ihome, string *pronames); void read_network_comment(Parms &plist, int *numpartner, int **Speclist, ifstream &infile);
[ "noreply@github.com" ]
SysSynBio.noreply@github.com
4576b56b3a9ff0da8fa0ba63f368ca8998155b62
cde72953df2205c2322aac3debf058bb31d4f5b9
/win10.19042/System32/msvproc.dll.cpp
fafb10df5a7b0312e3c195ae9b4d3eaa2fdb3841
[]
no_license
v4nyl/dll-exports
928355082725fbb6fcff47cd3ad83b7390c60c5a
4ec04e0c8f713f6e9a61059d5d87abc5c7db16cf
refs/heads/main
2023-03-30T13:49:47.617341
2021-04-10T20:01:34
2021-04-10T20:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
280
cpp
#print comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\System32\\msvproc.dll\"") #print comment(linker, "/export:DllGetActivationFactory=\"C:\\Windows\\System32\\msvproc.dll\"") #print comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\System32\\msvproc.dll\"")
[ "magnus@stubman.eu" ]
magnus@stubman.eu
0b2a06215420ec4fd729c1b1a6cb876c5d5ff1f4
79665d879469ce04ea365bdddd7754ce53744ac8
/BulletController.h
ee5515f89d00563d3a86bbf3812bb21d321d1764
[]
no_license
GrantAviex/Draconomy
851a592e9b47ba0f9bb945e185bd9e3783038016
531a2cab48feb52bfdf4156a72b0aeecf7cd403e
refs/heads/master
2021-01-10T16:42:07.843572
2016-11-26T23:57:24
2016-11-26T23:57:24
43,165,841
0
0
null
null
null
null
UTF-8
C++
false
false
3,190
h
//BulletController.h //Created May 2015 #ifndef BULLETCONTROLLER_H #define BULLETCONTROLLER_H #include <string> #include "Component.h" #include "EventSystem.h" using namespace std; #include <DirectXMath.h> using namespace DirectX; class CBulletController : public CComponent { private: float fLiveTimer; CGameObject* myShooter; bool m_bHoming = false; CGameObject* myTarget = nullptr; int m_nDamage; XMFLOAT3 dir; bool setDir = true; float m_fSpin; float m_fDisplacement; float m_fFrequency; int m_nMaxBounces = 0; int m_nBouncesLeft = 0; string m_sHitEffect; float m_fSlow = 0.0f; int m_nExploding = 0; bool m_bBouncing = false; bool m_bBurning = false; float dmgMod = 1.0f; float amrMod = 1.0f; float m_fDamageMult = 1.0f; float gLife = 0.0f; XMFLOAT3 vel; bool gravity; bool m_bVortex = false; bool m_bBlazing = false; bool m_bDecay = false; bool m_bPiercing = false; int m_InitialDamage; public: void SetPiercing(bool _pierce){ m_bPiercing = _pierce; } bool GetPiercing(){ return m_bPiercing; } void SetDamageMult(float _mult){ m_fDamageMult = _mult; } float GetDamageMult(){return m_fDamageMult; } void SetExploding(int _explode){ m_nExploding = _explode; } int GetExploding(){ return m_nExploding; } void SetBouncing(bool _bounce){ m_bBouncing = _bounce; } bool GetBouncing(){ return m_bBouncing; } void SetBurning(bool _burn){ m_bBurning = _burn; } bool GetBurning(){ return m_bBurning; } void SetBlazing(bool _blaze){ m_bBlazing = _blaze; } bool GetBlazing(){ return m_bBlazing; } void SetSlow(float _slow){ m_fSlow = _slow; } float GetSlow(){ return m_fSlow;} void SetWknDmg(float _curse){ dmgMod = _curse; } void SetWknAMR(float _curse){ amrMod = _curse; } void SetGravity(bool _gravity, float _gLife) { gravity = _gravity; gLife = _gLife; } float GetWknDmg(){ return dmgMod; } float GetWknAmr(){ return amrMod; } bool GetDecay(){ return m_bDecay; } void SetDecay(bool _bool){ m_bDecay = _bool; } void SetVortexBool(bool _bool){ m_bVortex = _bool; } bool GetVortexBool(){ return m_bVortex; } vector<CGameObject*> vcEnemiesHit; int GetDamage(){ return m_nDamage; } int GetInitialDamage() { return m_InitialDamage; } void SetDamage(int _dmg){ m_nDamage = _dmg; } void SetLifeTime(float _life){ fLiveTimer = _life; } bool GetHomingBool(){ return m_bHoming; } void SetHomingBool(bool _homing){ m_bHoming = _homing; } CBulletController(CGameObject* owner); ~CBulletController(); virtual CBulletController* clone() const; void Update(float _dt) override; CGameObject* GetWhoShotMe(){ return myShooter; } void SetWhoShotMe(CGameObject* _shooter){ myShooter = _shooter; } void SetTarget(CGameObject* _targ) { myTarget = _targ; } void SetBounce(){ m_nBouncesLeft = m_nMaxBounces; } void SetMaxBounce(int _bounce){ m_nMaxBounces = _bounce; } void OnEnable() override; void Bounce(); void CreateHitEffect(); bool CanHit(CGameObject* _col); void OnDisable() override; void KilledEnemy(); float m_MoveSpeed; void SetHitEffect(string hitEffect) { m_sHitEffect = hitEffect; } }; #endif
[ "noreply@github.com" ]
GrantAviex.noreply@github.com
4e0704eaeea9a7843426775a42f1b0ef399e2a4a
97eb00d7b35076b1efce57b21ad51636ac2a920c
/ABC/162/d.cpp
8f73a46f29c2d9ab5830ac7000a7cf39dc005205
[]
no_license
jimjin73/compro
43199716dc857f52c10d3237908e70c1801e7fb4
b194b4414752fff3debc838f4ee70af8e2e43f34
refs/heads/master
2021-05-18T01:02:39.338377
2020-08-06T12:25:20
2020-08-06T12:25:20
251,037,702
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll N; string s; vector<ll> v[3]; int main(){ cin >> N; cin >> s; for(int i=0;i<N;i++){ if(s[i] == 'R') v[0].push_back(i); if(s[i] == 'G') v[1].push_back(i); if(s[i] == 'B') v[2].push_back(i); } ll sum = 0; for(int i=0;i<N;i++){ for(int j=i+1;j<N;j++){ if(s[i] == s[j]) continue; ll diff = j - i; ll index = -1; if((s[i] == 'R' || s[i] == 'G') && (s[j] == 'R' || s[j] == 'G')){ index = 2; } if((s[i] == 'R' || s[i] == 'B') && (s[j] == 'R' || s[j] == 'B')){ index = 1; } if((s[i] == 'B' || s[i] == 'G') && (s[j] == 'B' || s[j] == 'G')){ index = 0; } auto itr = upper_bound(v[index].begin(),v[index].end(),j); sum += v[index].end() - itr; if(binary_search(v[index].begin(),v[index].end(),j + diff)) sum--; } } cout << sum << endl; return 0; }
[ "j.kam.j.kan.w.jmj@gmail.com" ]
j.kam.j.kan.w.jmj@gmail.com
cae933c60c16dae64e96cc7a48e6b330ee534d91
069ea34f9980dd0d0445202dcaa16d1a553a3e23
/HDACMer/Buildings/main.cpp
d17145f540bb395b31a5932654b4e1cb4121fdcd
[]
no_license
theJinFei/C-Test
fe9c3b1236f3c40b8f0d1c7b1f90b517723d1b14
e2e26578e7df245f1c1f35a74fd8c02966690f94
refs/heads/master
2021-09-01T17:11:07.727227
2017-12-28T02:14:05
2017-12-28T02:14:05
114,580,401
0
0
null
null
null
null
UTF-8
C++
false
false
578
cpp
#include <iostream> #include <vector> #include <stdio.h> #include <algorithm> #include <iomanip> #include <string> #include <cstdio> #include <string.h> #include <set> #include <cmath> using namespace std; int main() { int N; cin>>N; while(N-->0){ int a,b; cin>>a>>b; int array[a][b],sum=0; for(int i=0;i<a;i++){ for(int j=0;j<b;j++){ cin>>array[i][j]; if(array[i][j]==1){ sum++; } } } cout<<sum<<endl; } return 0; }
[ "luojinfei_study@163.com" ]
luojinfei_study@163.com
1317f73678771bc2df6a5a0e04b762c5a5f56f3a
4dbfab72ec685805d94c95fb2fefc3525011caa2
/compiler_optimizations/copy_elision__initialization_with_temporary_variable.cpp
de4d0a2b78fb0c433417afafa495dbeacce80e20
[]
no_license
init931/yandex.praktikum
53dc83d3e2a442c43e1e9f8f88abadc06c37aa55
454616cbc490990034157c65dfd585b9c62ef7bb
refs/heads/main
2023-08-05T03:31:06.759141
2021-09-15T10:02:48
2021-09-15T10:02:48
357,801,199
0
0
null
null
null
null
UTF-8
C++
false
false
1,666
cpp
#include <iostream> #include <string> using namespace std; // класс кота Шрёдингера class SchrodingerCat { private: string color_; public: SchrodingerCat() : color_("black"s) { cout << "Default Ctor cat"s << endl; } SchrodingerCat(const SchrodingerCat& other) : color_(other.color_) { cout << "Copy Ctor cat"s << endl; } ~SchrodingerCat() { cout << "Dtor cat"s << endl; } }; // класс Коробки class Box { private: bool is_empty_; SchrodingerCat cat_; public: Box() : cat_({}), is_empty_(false) { cout << "Default Ctor box"s << endl; } ~Box() { cout << "Dtor box"s << endl; } // кота из коробки можно вытащить SchrodingerCat GetCat() { is_empty_ = true; cout << "GetCat box"s << endl; return cat_; } bool HasCat() { cout << "HasCat box"s << endl; return !is_empty_; } }; int main() { Box black_box = {}; if (black_box.HasCat()) { SchrodingerCat fluffy = black_box.GetCat(); cout << "end if"s << endl; } cout << "end main"s << endl; return 0; } /* (pytorch4) test$ ./a.out Default Ctor cat Default Ctor box HasCat box GetCat box Copy Ctor cat end if Dtor cat end main Dtor box Dtor cat (pytorch4) test$ g++ -fno-elide-constructors test_cat.cpp (pytorch4) villedepommes@devfair044:/scratch/villedepommes/github/pytorch4/test$ ./a.out Default Ctor cat Copy Ctor cat Dtor cat Default Ctor box HasCat box GetCat box Copy Ctor cat Copy Ctor cat Dtor cat end if Dtor cat end main Dtor box Dtor cat */
[ "friendskenny72@gmail.com" ]
friendskenny72@gmail.com
21b1a6a06a9745bf40c4feb2a30da1148d55f4e3
8903cb76cedac12995249e2e613af65365be7cf2
/ares/n64/controller/gamepad/gamepad.cpp
4b33563b8620b4c637287bb886f442f65437a0fe
[ "ISC" ]
permissive
kirwinia/ares-emu-v121
0c1e21e073f291741406cd1ed01acca43acd56d7
722aa227caf943a4a64f1678c1bdd07b38b15caa
refs/heads/main
2023-06-09T15:28:23.665934
2021-06-28T06:10:46
2021-06-28T06:10:46
380,923,321
0
0
ISC
2021-06-28T06:05:04
2021-06-28T06:05:04
null
UTF-8
C++
false
false
6,300
cpp
Gamepad::Gamepad(Node::Port parent) { node = parent->append<Node::Peripheral>("Gamepad"); port = node->append<Node::Port>("Pak"); port->setFamily("Nintendo 64"); port->setType("Pak"); port->setHotSwappable(true); port->setAllocate([&](auto name) { return allocate(name); }); port->setConnect([&] { return connect(); }); port->setDisconnect([&] { return disconnect(); }); port->setSupported({"Controller Pak", "Rumble Pak"}); x = node->append<Node::Input::Axis> ("X-Axis"); y = node->append<Node::Input::Axis> ("Y-Axis"); up = node->append<Node::Input::Button>("Up"); down = node->append<Node::Input::Button>("Down"); left = node->append<Node::Input::Button>("Left"); right = node->append<Node::Input::Button>("Right"); b = node->append<Node::Input::Button>("B"); a = node->append<Node::Input::Button>("A"); cameraUp = node->append<Node::Input::Button>("C-Up"); cameraDown = node->append<Node::Input::Button>("C-Down"); cameraLeft = node->append<Node::Input::Button>("C-Left"); cameraRight = node->append<Node::Input::Button>("C-Right"); l = node->append<Node::Input::Button>("L"); r = node->append<Node::Input::Button>("R"); z = node->append<Node::Input::Button>("Z"); start = node->append<Node::Input::Button>("Start"); } Gamepad::~Gamepad() { disconnect(); } auto Gamepad::save() -> void { if(!slot) return; if(slot->name() == "Controller Pak") { ram.save(pak->write("save.pak")); } } auto Gamepad::allocate(string name) -> Node::Peripheral { if(name == "Controller Pak") return slot = port->append<Node::Peripheral>("Controller Pak"); if(name == "Rumble Pak" ) return slot = port->append<Node::Peripheral>("Rumble Pak"); return {}; } auto Gamepad::connect() -> void { if(!slot) return; if(slot->name() == "Controller Pak") { node->setPak(pak = platform->pak(node)); ram.allocate(32_KiB); formatControllerPak(); if(auto fp = pak->read("save.pak")) { if(fp->attribute("loaded").boolean()) { ram.load(pak->read("save.pak")); } } } if(slot->name() == "Rumble Pak") { motor = node->append<Node::Input::Rumble>("Rumble"); } } auto Gamepad::disconnect() -> void { if(!slot) return; if(slot->name() == "Controller Pak") { save(); ram.reset(); } if(slot->name() == "Rumble Pak") { rumble(false); node->remove(motor); motor.reset(); } port->remove(slot); slot.reset(); } auto Gamepad::rumble(bool enable) -> void { if(!motor) return; motor->setEnable(enable); platform->input(motor); } auto Gamepad::read() -> n32 { platform->input(x); platform->input(y); platform->input(up); platform->input(down); platform->input(left); platform->input(right); platform->input(b); platform->input(a); platform->input(cameraUp); platform->input(cameraDown); platform->input(cameraLeft); platform->input(cameraRight); platform->input(l); platform->input(r); platform->input(z); platform->input(start); //scale {-32768 ... +32767} to {-84 ... +84} auto ax = x->value() * 85.0 / 32767.0; auto ay = y->value() * 85.0 / 32767.0; //create scaled circular dead-zone in range {-15 ... +15} auto length = sqrt(ax * ax + ay * ay); if(length < 16.0) { length = 0.0; } else if(length > 85.0) { length = 85.0 / length; } else { length = (length - 16.0) * 85.0 / 69.0 / length; } ax *= length; ay *= length; //bound diagonals to an octagonal range {-68 ... +68} if(ax != 0.0 && ay != 0.0) { auto slope = ay / ax; auto edgex = copysign(85.0 / (abs(slope) + 16.0 / 69.0), ax); auto edgey = copysign(min(abs(edgex * slope), 85.0 / (1.0 / abs(slope) + 16.0 / 69.0)), ay); edgex = edgey / slope; auto scale = sqrt(edgex * edgex + edgey * edgey) / 85.0; ax *= scale; ay *= scale; } n32 data; data.byte(0) = -ay; data.byte(1) = +ax; data.bit(16) = cameraRight->value(); data.bit(17) = cameraLeft->value(); data.bit(18) = cameraDown->value(); data.bit(19) = cameraUp->value(); data.bit(20) = r->value(); data.bit(21) = l->value(); data.bit(22) = 0; //GND data.bit(23) = 0; //RST data.bit(24) = right->value() & !left->value(); data.bit(25) = left->value() & !right->value(); data.bit(26) = down->value() & !up->value(); data.bit(27) = up->value() & !down->value(); data.bit(28) = start->value(); data.bit(29) = z->value(); data.bit(30) = b->value(); data.bit(31) = a->value(); //when L+R+Start are pressed: the X/Y axes are zeroed, RST is set, and Start is cleared if(l->value() && r->value() && start->value()) { data.byte(0) = 0; //Y-Axis data.byte(1) = 0; //X-Axis data.bit(23) = 1; //RST data.bit(28) = 0; //Start } return data; } //controller paks contain 32KB of SRAM split into 128 pages of 256 bytes each. //the first 5 pages are for storing system data, and the remaining 123 for game data. auto Gamepad::formatControllerPak() -> void { ram.fill(0x00); //page 0 (system area) n6 fieldA = random(); n19 fieldB = random(); n27 fieldC = random(); for(u32 area : array<u8[4]>{1,3,4,6}) { ram.write<Byte>(area * 0x20 + 0x01, fieldA); //unknown ram.write<Word>(area * 0x20 + 0x04, fieldB); //serial# hi ram.write<Word>(area * 0x20 + 0x08, fieldC); //serial# lo ram.write<Half>(area * 0x20 + 0x18, 0x0001); //device ID ram.write<Byte>(area * 0x20 + 0x1a, 0x01); //banks (0x01 = 32KB) ram.write<Byte>(area * 0x20 + 0x1b, 0x00); //version# u16 checksum = 0; u16 inverted = 0; for(u32 half : range(14)) { u16 data = ram.read<Half>(area * 0x20 + half * 2); checksum += data; inverted += ~data; } ram.write<Half>(area * 0x20 + 0x1c, checksum); ram.write<Half>(area * 0x20 + 0x1e, inverted); } //pages 1+2 (inode table) for(u32 page : array<u8[2]>{1,2}) { ram.write<Byte>(0x100 * page + 0x01, 0x71); //unknown for(u32 slot : range(5,128)) { ram.write<Byte>(0x100 * page + slot * 2 + 0x01, 0x03); //0x01 = stop, 0x03 = empty } } //pages 3+4 (note table) //pages 5-127 (game saves) } auto Gamepad::serialize(serializer& s) -> void { s(ram); rumble(false); }
[ "ecallaghan@protonmail.com" ]
ecallaghan@protonmail.com
10c2c399ba3cac69feeb154d609d98e5f171e55b
e1383b70afaacf030012f04480f5e0b2608ebb42
/ESP-Now/espnow-gateway/espnow-gateway.ino
93c3cb62fd89177f8529458583c1e2c97a002098
[ "CC0-1.0" ]
permissive
px4ugs/IoT
025dfa291f5c6efbbe8854235d7d8882c96303c9
8b078b4a5663dd31603e70df603ae2457d442018
refs/heads/master
2020-06-20T13:03:10.874306
2017-05-06T12:03:22
2017-05-06T12:03:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,107
ino
/* Testing ESP-Now See https://espressif.com/en/products/software/esp-now/overview ESP-Now enables fast lightwieght connectionless communication between ESP8266's. So for example a remote sensor node could send a reading using ESP-Now in just a few hundred milliseconds and deepSleep the rest of the time and so get increased battery life compared to the node using a regular WiFi connection which could take 10 times as long to connect to WiFi and send a sensor reading. ESP-Now has the concept of controllers and slaves. AFAICT the controller is the remote sensor node and the slave is the always on "gateway" node that listens for sensor node readings. *** Note: to compile ESP-Now (with arduino/esp8266 release 2.3.0) need to edit * ~/Library/Arduino15/packages/esp8266/hardware/esp8266/2.1.0/platform.txt * Search "compiler.c.elf.libs", and append "-lespnow" at the end of the line. * See: http://www.esp8266.com/viewtopic.php?p=44161#p44161 *** **** This skecth is the slave/gateway node **** Ant Elder License: Apache License v2 */ #include <ESP8266WiFi.h> extern "C" { #include <espnow.h> } const char* ssid = "BTHub5-72W5"; const char* password = "xxxxxxxxxx"; #define WIFI_CHANNEL 1 // keep in sync with sensor struct struct SENSOR_DATA { float temp; float hum; float t; float pressure; }; void setup() { Serial.begin(115200); Serial.println(); initWifi(); if (esp_now_init()!=0) { Serial.println("*** ESP_Now init failed"); ESP.restart(); } Serial.print("This node AP mac: "); Serial.print(WiFi.softAPmacAddress()); Serial.print(", STA mac: "); Serial.println(WiFi.macAddress()); // Note: When ESP8266 is in soft-AP+station mode, this will communicate through station interface // if it is in slave role, and communicate through soft-AP interface if it is in controller role, // so you need to make sure the remote nodes use the correct MAC address being used by this gateway. esp_now_set_self_role(ESP_NOW_ROLE_SLAVE); esp_now_register_recv_cb([](uint8_t *mac, uint8_t *data, uint8_t len) { Serial.print("recv_cb, from mac: "); char macString[50] = {0}; sprintf(macString, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); Serial.print(macString); getReading(data, len); }); } void loop() { } void getReading(uint8_t *data, uint8_t len) { SENSOR_DATA tmp; memcpy(&tmp, data, sizeof(tmp)); Serial.print(", parsed data, t="); Serial.println(tmp.t); } void initWifi() { WiFi.mode(WIFI_AP_STA); WiFi.softAP("MyGateway", "12345678", WIFI_CHANNEL, 1); Serial.print("Connecting to "); Serial.print(ssid); if (strcmp (WiFi.SSID().c_str(), ssid) != 0) { WiFi.begin(ssid, password); } int retries = 20; // 10 seconds while ((WiFi.status() != WL_CONNECTED) && (retries-- > 0)) { delay(500); Serial.print("."); } Serial.println(""); if (retries < 1) { Serial.print("*** WiFi connection failed"); ESP.restart(); } Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP()); }
[ "ant.elder@uk.ibm.com" ]
ant.elder@uk.ibm.com
a1acf14ea89349a7685ab8ea39532fd9a0dc372e
5b1b25a0c1fbb384064cbb0500e7b74926111fe0
/ZeroNetServer/zeroserver.h
6bfb24f945835d33692ba7b00f661a5201aa9a5a
[]
no_license
Yuanyiis/ZeroNet
9f0c1e92b09dfe07e545dc4203014602e15e3c64
763c5f2774628e0bb74c5d74d4e08549c788731a
refs/heads/master
2021-04-30T10:03:08.319246
2018-01-21T03:50:32
2018-01-21T03:50:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,220
h
/* * Author: 752049643@qq.com * Date: 2017-12-24 * Brief: Zero远控主要服务端 * */ #ifndef ZEROSERVER_H #define ZEROSERVER_H #include <QObject> #include "TcpServer.h" #include "ZeroClient.h" #include <QHash> class ZeroServer : public QObject { Q_OBJECT public: explicit ZeroServer(QObject *parent = 0); // 启动或停止服务端 void start(int port); void stop(); // 用id来获取ZeroClient ZeroClient *client(int id) { return mClients[id]; } TcpServer *server() { return mServer; } private: TcpServer *mServer; // Tcp服务端 QHash<int, ZeroClient*> mClients; // 用ID来索引相应的客户 // 生成新的id int generateId(); signals: // 客户登入或登出,主要是告诉窗口控件 void clientLogin(int id, QString userName, QString ip,int port, QString system); void clientLogout(int id); public slots: // 新客户连接 void newConnection(QTcpSocket *sock); // 客户登入 void login(ZeroClient*, QString userName, QString ip, int port, QString system); // 客户登出 void logout(int id); }; #endif // ZEROSERVER_H
[ "zhjf1996@163.com" ]
zhjf1996@163.com
68fd5121b0bec95d4c52f4c809fb5587905e0b82
fca68c5fec6df6f999408571315c2b8e7c4b8ce9
/service/supersialign_home/src/Suez/SuezMain.cc
b1a3b9837e382bdeb4293afdc5bd6bc40812a018
[]
no_license
jpivarski-talks/1999-2006_gradschool-3
8b2ea0b6babef104b0281c069994fc9894a05b14
57e80d601c0519f9e01a07ecb53d367846e8306e
refs/heads/master
2022-11-19T12:01:42.959599
2020-07-25T01:19:59
2020-07-25T01:19:59
282,235,559
0
0
null
null
null
null
UTF-8
C++
false
false
15,471
cc
// -*- C++ -*- // // Package: Suez // Module: SuezMain // // Description: The main "Main" in the Suez World // // Implimentation: // <Notes on implimentation> // // Author: Martin Lohner // Created: Thu Mar 20 15:13:11 EST 1997 // $Id: SuezMain.cc,v 1.67 2002/01/03 21:07:26 cdj Exp $ // // Revision history (at end of file) // #include "Experiment/Experiment.h" // system include files #include <assert.h> #include <fstream.h> #include <stdlib.h> #include <unistd.h> #include <stdexcept> #if defined(XALLOC_NON_STANDARD_EXCEPTION_BUG) #include <exception.h> #endif #if defined(STL_TEMPLATE_DEFAULT_PARAMS_FIRST_BUG) #include <deque> #include <map> #endif // user include files #include "Suez/testBoolean.h" #include "Suez/forceLinkStorageManagement.h" #include "Experiment/report.h" #include "DataHandler/FrameLogger.h" #include "JobControl/JobControl.h" #include "Suez/UserApplication.h" #include "JobControl/ReportModule.h" #include "Interpreter/TclInterpreter.h" #include "Utility/StringTokenizer.h" // signal handling #include "Signal/SignalHandler.h" #include "Signal/SIGINT_Handler.h" // exceptions #include "DAException/DAException.h" // STL includes #include <deque> int TheMain( int argc, char** argv ); DABoolean SuezInit( Interpreter& interpreter, const string& runFile = "", DABoolean runSetupFile = false ); // typedefs, enums, constants #include "Suez/externConst.h" //static const char* const kFacilityString = "Suez.SuezMain"; static const char* const IdString = "$Id: SuezMain.cc,v 1.67 2002/01/03 21:07:26 cdj Exp $"; static const char* const TagString = "$Name: $"; static const char* const VersionString = "$Version$"; static string welcomeMsg = string( "// -----------------------------------------------------------\n" )+ string( "// Welcome to Suez, the CLEO III data access program \n" )+ string( "// -----------------------------------------------------------\n" ); //----------------- // Main //----------------- int main( int argc, char** argv ) { // install SignalHandlers DABoolean callExit; SIGINT_Handler sigint_handler( callExit=true ); SignalHandler::instance()->registerHandler( SignalHandler::kSigInt, &sigint_handler ); #ifndef CLEO_DEBUG // catch all (uncaught) exceptions and print message // catch first specific ones, then less specific try { #endif TheMain( argc, argv ); #ifndef CLEO_DEBUG } // all specific logic_error exceptions catch( length_error& thisException ) { cerr << "ERROR: Suez caught \"length_error\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } catch( domain_error& thisException ) { cerr << "ERROR: Suez caught \"domain_error\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } catch( out_of_range& thisException ) { cerr << "ERROR: Suez caught \"out_of_range\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } catch( invalid_argument& thisException ) { cerr << "ERROR: Suez caught \"invalid_argument\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } // now catch all other logic_error exceptions catch( logic_error& thisException ) { cerr << "ERROR: Suez caught \"logic_error\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } // now all non-logic_error, non-runtime_error exceptions #if !defined(UNDEF_BAD_ALLOC_EXCEPT_BUG) catch( bad_alloc& thisException ) { cerr << "ERROR: Suez caught \"bad_alloc\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } #else #if defined(XALLOC_NON_STANDARD_EXCEPTION_BUG) catch( xalloc& thisException ) { cerr << "ERROR: Suez caught \"xalloc\" exception:\n\"" << thisException.why() << "\"\n ... exiting program" << endl; } #endif #endif #if !defined(UNDEF_BAD_EXCEPTION_EXCEPT_BUG) catch( bad_exception& thisException ) { cerr << "ERROR: Suez caught \"bad_exception\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } #endif #if !defined(UNDEF_IOS_BASE_FAILURE_EXCEPT_BUG) catch( ios_base::failure& thisException ) { cerr << "ERROR: Suez caught \"ios_base::failure\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } #endif #if !defined(UNDEF_BAD_TYPEID_EXCEPT_BUG) catch( bad_typeid& thisException ) { cerr << "ERROR: Suez caught \"bad_typeid\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } #endif #if !defined(UNDEF_BAD_CAST_EXCEPT_BUG) catch( bad_cast& thisException ) { cerr << "ERROR: Suez caught \"bad_cast\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } #endif // all specific runtime_error exceptions #if !defined(UNDEF_UNDERFLOW_ERROR_EXCEPT_BUG) catch( underflow_error& thisException ) { cerr << "ERROR: Suez caught \"underflow_error\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } #endif #if !defined(UNDEF_OVERFLOW_ERROR_EXCEPT_BUG) catch( overflow_error& thisException ) { cerr << "ERROR: Suez caught \"overflow_error\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } #endif #if !defined(UNDEFINED_RANGE_ERROR_EXCEPT_BUG) catch( range_error& thisException ) { cerr << "ERROR: Suez caught \"range_error\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } #endif // now catch all other runtime_error exceptions catch( runtime_error& thisException ) { cerr << "ERROR: Suez caught \"runtime_error\" exception:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } // now catch DAExceptions catch( DAExceptionBase& thisException ) { cerr << "ERROR: Suez caught a DAException:\n\"" << thisException.what() << "\"\n ... exiting program" << endl; } // catch non-standard exceptions #if defined(XALLOC_NON_STANDARD_EXCEPTION_BUG) catch( xmsg& thisException ) { cerr << "ERROR: Suez caught \"xmsg\" exception:\n\"" << thisException.why() << "\"\n ... exiting program" << endl; } #endif // now just catch anything catch( ... ) { cerr << "ERROR: Suez caught an (unknown/user-defined?) exception:\n" << " ... exiting program" << endl; } #endif /* in debug mode don't catch exceptions */ return 0; } int TheMain( int argc, char** argv ) { // setup message logger //FrameLogger logger( reportLevel, cout ); //MessageLog::Tie( "." , logger ); // try new logging via ReportModule ReportModule* reportModule = new ReportModule( INFO ); // test proper Boolean behavior; if no good, will exit testBoolean(); // force-link StorageManagement, so that nobody has else to forceLinkStorageManagement(); // handle options DABoolean runGUI = false, runSetupFile = true; string runFile( "" ); // handle options using the getopt standard function; if int option; optarg = 0; const char* const ARGS = "f:xq"; while( true ) { option = getopt( argc, argv, ARGS ); if( option == -1 ) break; switch( option ) { case 'f': { runFile = optarg; break; } case 'x': { runGUI = true; break; } case 'q': { runSetupFile = false; break; } case '?': { // ignore break; } default: { report( WARNING, kFacilityString ) << "don't understand option: " << option << endl; } } } // print out any other non-option arguments (since we won't process them!) if( optind < argc ) { ostream& os = report( ERROR, kFacilityString ); os <<"ignoring non-option ARGV-elements: \n"; while( optind < argc ) { os << argv[optind++] << "\n"; } os << "continuing..." << endl; } // --------- welcome user ------------- report( INFO, kFacilityString ) << "\n" << welcomeMsg << endl; report( INFO, kFacilityString ) << IdString << "\n" //<< TagString << "\n" //<< VersionString << "\n" << endl; // create Interpreter Interpreter::setInterpreter( new TclInterpreter() ); Interpreter* interpreter = Interpreter::interpreter(); assert( 0 != interpreter ); // --------- Initialize Suez Application ----------------- JobControl* jobControl = JobControl::instance(); assert( 0 != jobControl ); jobControl->setName( "Suez" ); jobControl->addModule( reportModule, false ); // not owned by JobControl jobControl->initLogger( reportModule->logger() ); // ------------------ create user application ---------------- // create on the stack, no need to control deletion UserApplication userApplication( jobControl ); if( true == runGUI ) { report( INFO, kFacilityString ) << "starting suez in gui mode..." << endl; report( ERROR, kFacilityString ) << "not supported at the moment!" << endl; //// Need to enable commands before running initialization scripts ////interpreter->initialize( false, argc, argv ); ////jobControl->enableCommands(); //SuezInit( *interpreter, runFile, runSetupFile ); //interpreter->initialize( runGUI, argc, argv ); } else // default is pure cli mode { // Need to enable commands before running initialization scripts interpreter->initialize( false, argc, argv ); interpreter->pushActiveModule(jobControl); SuezInit( *interpreter, runFile, runSetupFile ); // ------------ Main Interaction Loop with User ----------- userApplication.runEmbeddedCommands( *interpreter ); if( true == userApplication.interactiveMode() ) { interpreter->loop(); } } // -------------- Clean Up -------------------------------- jobControl->finalizeLogger( reportModule->logger() ); jobControl->destroy(); delete interpreter; delete reportModule; // finally delete ReportModule (to be last!) return 0; } DABoolean SuezInit( Interpreter& interpreter, const string& runFile, DABoolean runSetupFile ) { DABoolean status = true; if( true == runSetupFile ) { // turn setup file off if requested // if file was specified from command line, run that. if( runFile != "" ) { interpreter.runCommandFile( runFile.c_str() ); } else { // Run any initialization scripts (official, home directory etc.) // only run official startup script if personal doesn't exist const char* const HOME = getenv( "HOME" ); if( 0 != HOME ) { string personalStartupScript = string( HOME ) + string( "/.suezrc" ); ifstream ifs( personalStartupScript.c_str() ); if( ifs ) { // personal file exists ifs.close(); interpreter.runCommandFile( personalStartupScript.c_str() ); } else { // no personal file exists; run official const char* const C3_SUEZRC = getenv( "C3_SUEZRC" ); if( 0 == C3_SUEZRC ) { report( WARNING, kFacilityString ) << "cannot find C3_SUEZRC environment variable!\n " << "May not be able to initialize properly!" << endl; } else { // need to find first entry in C3_SUEZRC string StringTokenizer c3_suezrc_tokens( C3_SUEZRC ); if( c3_suezrc_tokens.hasMoreElements() ) { // now assemble file name string officialStartupScript = c3_suezrc_tokens.nextElement() + string( "/suezrc" ); interpreter.runCommandFile( officialStartupScript.c_str() ); } } } } else { report( WARNING, kFacilityString ) << "cannot find HOME environment variable!\n " << "May not be able to initialize properly!" << endl; } } // specified script on command-line or not } // run setup file or not return status; } // ---------------------------------------------------------------------- // Revision history // // $Log: SuezMain.cc,v $ // Revision 1.67 2002/01/03 21:07:26 cdj // updated to work with new Interpreter handling // // Revision 1.66 2000/12/01 20:33:59 cdj // updated to work with DynamicLoader package // // Revision 1.65 2000/07/29 17:02:28 mkl // catch non-standard Solaris exceptions (base class and out-of-memory) // // Revision 1.64 2000/03/31 16:52:37 mkl // for online benefit: print warning, but ignore any illegal options // // Revision 1.63 2000/03/14 22:52:06 mkl // UserApplication header now comes from Suez // // Revision 1.62 2000/03/14 20:55:21 mkl // new UserApplication functionality: new embeddedCommand and interactiveMode methods for running Suez in standalone mode in online // // Revision 1.61 2000/03/02 16:59:59 mkl // new StringTokenizer parse handling // // Revision 1.60 2000/01/27 03:46:18 mkl // create UserApplication on the stack, no need to control deletion // // Revision 1.59 2000/01/17 19:03:58 mkl // run_file was not working correctly together with -f flag // // Revision 1.58 2000/01/03 19:00:07 mkl // print 'ERROR' as part of exception-handling message // // Revision 1.57 1999/12/06 16:17:18 mkl // name change: CleoException-->DAException // // Revision 1.56 1999/12/03 19:10:43 mkl // reflect move of CleoException to its own package // // Revision 1.55 1999/12/02 23:36:43 mkl // have to catch CleoExceptions now (as last resort) // // Revision 1.54 1999/11/05 17:43:52 mkl // move force-link to StorageManagement into its own file (for better maintainance) // // Revision 1.53 1999/11/04 20:42:11 mkl // force link to StorageManagement, so that nobody else has to // // Revision 1.52 1999/09/08 19:50:19 mkl // ReportModule has to be deleted last so that all messages get put out // // Revision 1.51 1999/09/07 14:47:50 mkl // move to new Histogram Interface // // Revision 1.50 1999/08/31 23:10:04 mkl // removed deprecated report level option; fixed up handling of explicitly specified executable // // Revision 1.49 1999/08/26 03:02:03 mkl // better than rethrow: dont catch in debug mode // // Revision 1.48 1999/08/26 02:29:29 mkl // rethrow caught exceptions so that gdb can properly work // // Revision 1.47 1999/08/25 21:27:46 mkl // ReportModule allows setting of report level and logging to files // // Revision 1.46 1999/05/12 20:34:21 mkl // change default report level to INFO // // Revision 1.45 1999/05/02 02:45:46 mkl // use new Signal library // // Revision 1.44 1999/04/30 18:09:25 mkl // catch all exceptions // // Revision 1.43 1999/04/29 19:54:42 mkl // take out MAILTO line from test scripts // // Revision 1.42 1999/04/19 18:01:50 mkl // added info on tcl via web pages // // Revision 1.41 1999/02/12 15:53:10 mkl // simplify nooption error // // Revision 1.40 1999/02/12 00:12:59 mkl // allow run-time control over report level // // Revision 1.39 1999/01/27 23:02:54 mkl // trivial change to get rid of insure++ complaint about null parameter // // Revision 1.38 1998/12/16 03:17:59 mkl // print 'Welcome to Suez' instead of 'SUEZ' as a test for release system // // Revision 1.37 1998/12/09 22:46:43 mkl // Logger now logs everything above DEBUG severity level. // // Revision 1.36 1998/11/30 20:38:18 mkl // test TagString // // Revision 1.35 1998/11/30 19:51:11 mkl // properly format SuezMain //
[ "jpivarski@gmail.com" ]
jpivarski@gmail.com
ab73ff22eecbfa21f8634bcaae44b447d8868912
c51febc209233a9160f41913d895415704d2391f
/library/ATF/_trunk_pw_hint_index_request_clzo.hpp
7d3675575cb35a175fa55dd52a612b19cc4dcbe7
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
270
hpp
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct _trunk_pw_hint_index_request_clzo { char byDummy; }; END_ATF_NAMESPACE
[ "b1ll.cipher@yandex.ru" ]
b1ll.cipher@yandex.ru
58f49af56745f7fadd6dea66251948f3e08633f3
8e2e2996ca91988e4c2e65e1ded8ff08952ab4ad
/src/MoviePriceType.h
bf34138b3937bb84dfa5be96c6c4990153376b2d
[]
no_license
GEN-BGroupeD/Labo5
77604e2d71d096afd411fd739e3778b4dba502d5
c45cf1befa83621568b4c8c0d97b6898b1ba9222
refs/heads/master
2022-11-08T10:50:15.171530
2020-06-21T10:00:01
2020-06-21T10:00:01
272,814,521
0
0
null
null
null
null
UTF-8
C++
false
false
357
h
#ifndef MOVIEPRICETYPE_H #define MOVIEPRICETYPE_H class MoviePriceType { public: explicit MoviePriceType(double price) : price(price) {} virtual double getPrice(double daysRented) = 0; virtual int getBonus(){ return 0; } virtual ~MoviePriceType() = default; protected: const double price; }; #endif //MOVIEPRICETYPE_H
[ "helene.dubuis@heig-vd.ch" ]
helene.dubuis@heig-vd.ch
e83f433c55b5407e67c655d0178c4be9d49500f9
bd8dff663c463faa69e2bfa9ee177b50c617f701
/B1026.cpp
188dde3997113610d65191376e9b87ff441e3a5d
[]
no_license
Gabriel-18/PAT
94b8b0b02955458f736f781246d91b9c6ee25794
f66e5f6c6db22e1be28b738523cb589e9ce12b11
refs/heads/master
2022-12-07T08:15:11.181501
2020-09-05T01:27:38
2020-09-05T01:28:18
198,178,163
0
0
null
null
null
null
GB18030
C++
false
false
432
cpp
#include<cstdio> // 模拟 // 四舍五入 int main() { int c1, c2; scanf("%d%d",&c1, &c2); int ans = c2 - c1; //四舍五入 if(ans % 100 >= 50) { // 傻逼写法 ans /= 100 + 1 ans = ans / 100 + 1; } else { ans /= 100; } //ans / 3600 直接得到小时数 //ans % 3600 除去小时数剩下的部分 //ans % 60 剩下的秒数 printf("%02d:%02d:%02d", ans / 3600, ans % 3600 / 60 ,ans % 60); return 0; }
[ "644050173@qq.com" ]
644050173@qq.com
a7fd1c7d655189dd8e7b8892ea08b5853da16664
7844379f018944f9be77cc213a8985372eff0848
/src/saiga/core/image/png_wrapper.cpp
7d7acaeb1e2d3341c3e316dea327af241618ca90
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
muetimueti/saiga
344306e2340f4668b9fece1e3d0d934cd189feb2
32b54a8fc7b1251368e07e7d31c15ac90cee3b32
refs/heads/master
2020-07-31T12:42:29.096235
2019-09-25T16:50:09
2019-09-25T16:50:09
210,607,609
0
0
MIT
2019-09-24T13:17:44
2019-09-24T13:17:38
null
UTF-8
C++
false
false
14,662
cpp
/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "png_wrapper.h" #include "saiga/core/util/assert.h" #include <cstring> // for memcpy #include <iostream> #ifdef SAIGA_USE_PNG # include "internal/noGraphicsAPI.h" # include <png.h> namespace Saiga { namespace PNG { struct PNGLoadStore { // temp variables for libpng. Don't modify them!!! uchar** row_pointers; void* png_ptr; void* info_ptr; FILE* infile; FILE* outfile; jmp_buf jmpbuf; }; static void writepng_error_handler(png_structp png_ptr, png_const_charp msg) { PNGLoadStore* image; /* This function, aside from the extra step of retrieving the "error * pointer" (below) and the fact that it exists within the application * rather than within libpng, is essentially identical to libpng's * default error handler. The second point is critical: since both * setjmp() and longjmp() are called from the same code, they are * guaranteed to have compatible notions of how big a jmp_buf is, * regardless of whether _BSD_SOURCE or anything else has (or has not) * been defined. */ fprintf(stderr, "writepng libpng error: %s\n", msg); fflush(stderr); image = static_cast<PNGLoadStore*>(png_get_error_ptr(png_ptr)); if (image == NULL) { /* we are completely hosed now */ fprintf(stderr, "writepng severe error: jmpbuf not recoverable; terminating.\n"); fflush(stderr); SAIGA_ASSERT(0); } longjmp(image->jmpbuf, 1); } bool readPNG(PngImage* img, const std::string& path, bool invertY) { PNGLoadStore pngls; png_structp png_ptr; png_infop info_ptr; unsigned int sig_read = 0; int interlace_type; if ((pngls.infile = fopen(path.c_str(), "rb")) == NULL) return false; /* Create and initialize the png_struct * with the desired error handler * functions. If you want to use the * default stderr and longjump method, * you can supply NULL for the last * three parameters. We also supply the * the compiler header file version, so * that we know if the application * was compiled with a compatible version * of the library. REQUIRED */ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { fclose(pngls.infile); return false; } /* Allocate/initialize the memory * for image information. REQUIRED. */ info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { fclose(pngls.infile); png_destroy_read_struct(&png_ptr, NULL, NULL); return false; } /* Set error handling if you are * using the setjmp/longjmp method * (this is the normal method of * doing things with libpng). * REQUIRED unless you set up * your own error handlers in * the png_create_read_struct() * earlier. */ if (setjmp(png_jmpbuf(png_ptr))) { /* Free all of the memory associated * with the png_ptr and info_ptr */ png_destroy_read_struct(&png_ptr, &info_ptr, NULL); fclose(pngls.infile); /* If we get here, we had a * problem reading the file */ return false; } /* Set up the output control if * you are using standard C streams */ png_init_io(png_ptr, pngls.infile); /* If we have already * read some of the signature */ png_set_sig_bytes(png_ptr, sig_read); /* * If you have enough memory to read * in the entire image at once, and * you need to specify only * transforms that can be controlled * with one of the PNG_TRANSFORM_* * bits (this presently excludes * dithering, filling, setting * background, and doing gamma * adjustment), then you can read the * entire image (including pixels) * into the info structure with this * call * * PNG_TRANSFORM_STRIP_16 | * PNG_TRANSFORM_PACKING forces 8 bit * PNG_TRANSFORM_EXPAND forces to * expand a palette into RGB */ png_read_png(png_ptr, info_ptr, // PNG_TRANSFORM_STRIP_16 | //Strip 16-bit samples to 8 bits PNG_TRANSFORM_SWAP_ENDIAN | // png byte order is big endian! PNG_TRANSFORM_PACKING | // Expand 1, 2 and 4-bit samples to bytes PNG_TRANSFORM_EXPAND // Perform set_expand() , NULL); png_uint_32 pw, ph; png_get_IHDR(png_ptr, info_ptr, &pw, &ph, &img->bit_depth, &img->color_type, &interlace_type, NULL, NULL); SAIGA_ASSERT(interlace_type == PNG_INTERLACE_NONE); img->width = pw; img->height = ph; unsigned int row_bytes = png_get_rowbytes(png_ptr, info_ptr); // we want to row-align the image in our output data int rowPadding = (img->rowAlignment - (row_bytes % img->rowAlignment)) % img->rowAlignment; img->bytesPerRow = row_bytes + rowPadding; img->data.resize(img->bytesPerRow * img->height); png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr); if (invertY) { for (unsigned int i = 0; i < img->height; i++) { memcpy(img->data.data() + (img->bytesPerRow * (img->height - 1 - i)), row_pointers[i], row_bytes); } } else { for (unsigned int i = 0; i < img->height; i++) { memcpy(img->data.data() + (img->bytesPerRow * i), row_pointers[i], row_bytes); } } /* Clean up after the read, * and free any memory allocated */ png_destroy_read_struct(&png_ptr, &info_ptr, NULL); /* Close the file */ fclose(pngls.infile); /* That's it */ return true; } /* returns 0 for success, 2 for libpng problem, 4 for out of memory, 11 for * unexpected pnmtype; note that outfile might be stdout */ static int writepng_init(const Image& img, PNGLoadStore* pngls) { png_structp png_ptr; /* note: temporary variables! */ png_infop info_ptr; int interlace_type; /* could also replace libpng warning-handler (final NULL), but no need: */ png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, writepng_error_handler, NULL); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, NULL); return 4; /* out of memory */ } /* setjmp() must be called in every function that calls a PNG-writing * libpng function, unless an alternate error handler was installed-- * but compatible error handlers must either use longjmp() themselves * (as in this program) or exit immediately, so here we go: */ if (setjmp(pngls->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); return 2; } /* make sure outfile is (re)opened in BINARY mode */ png_init_io(png_ptr, pngls->outfile); /* set the compression levels--in general, always want to leave filtering * turned on (except for palette images) and allow all of the filters, * which is the default; want 32K zlib window, unless entire image buffer * is 16K or smaller (unknown here)--also the default; usually want max * compression (NOT the default); and remaining compression flags should * be left alone */ // png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); /* >> this is default for no filtering; Z_FILTERED is default otherwise: png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY); >> these are all defaults: png_set_compression_mem_level(png_ptr, 8); png_set_compression_window_bits(png_ptr, 15); png_set_compression_method(png_ptr, 8); */ /* set the image parameters appropriately */ interlace_type = PNG_INTERLACE_NONE; // PNG_INTERLACE_ADAM7 int bit_depth = bitsPerChannel(img.type); int color_type = 0; switch (channels(img.type)) { case 1: color_type = PNG_COLOR_TYPE_GRAY; break; case 2: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3: color_type = PNG_COLOR_TYPE_RGB; break; case 4: color_type = PNG_COLOR_TYPE_RGB_ALPHA; break; default: SAIGA_ASSERT(0); } png_set_IHDR(png_ptr, info_ptr, img.width, img.height, bit_depth, color_type, interlace_type, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); // Higher is more compression // PNG_TEXT_Z_DEFAULT_STRATEGY png_set_compression_level(png_ptr, 1); // One of the following // PNG_FAST_FILTERS, PNG_FILTER_NONE, PNG_ALL_FILTERS png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_NONE); /* write all chunks up to (but not including) first IDAT */ png_write_info(png_ptr, info_ptr); /* if we wanted to write any more text info *after* the image data, we * would set up text struct(s) here and call png_set_text() again, with * just the new data; png_set_tIME() could also go here, but it would * have no effect since we already called it above (only one tIME chunk * allowed) */ /* set up the transformations: for now, just pack low-bit-depth pixels * into bytes (one, two or four pixels per byte) */ png_set_packing(png_ptr); /* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */ if (bit_depth == 16 || bit_depth == 32) png_set_swap(png_ptr); // std::cout << "bit depth " << bit_depth << std::endl; /* make sure we save our pointers for use in writepng_encode_image() */ pngls->png_ptr = png_ptr; pngls->info_ptr = info_ptr; SAIGA_ASSERT(pngls->png_ptr); SAIGA_ASSERT(pngls->info_ptr); return 0; } static void writepng_encode_image(const Image& img, PNGLoadStore* pngls, bool invertY) { png_structp png_ptr = (png_structp)pngls->png_ptr; png_infop info_ptr = (png_infop)pngls->info_ptr; for (int i = 0; i < img.height; i++) { auto j = invertY ? img.height - i - 1 : i; auto offset = j * img.pitchBytes; auto rowPtr = img.data8() + offset; # if 0 std::vector<unsigned char> dataTest(img.pitchBytes); for (auto c : img.colRange()) { png_save_uint_16(dataTest.data() + c * sizeof(short), ((unsigned short*)rowPtr)[c]); } # endif png_write_row(png_ptr, rowPtr); // png_write_row(png_ptr, dataTest.data()); } png_write_end(png_ptr, NULL); png_destroy_write_struct(&png_ptr, &info_ptr); } # if 0 bool writePNG(PngImage *img, const std::string &path, bool invertY) { PNGLoadStore pngls; FILE *fp = fopen(path.c_str(), "wb"); if (!fp) { std::cout << "could not open file: " << path.c_str() << std::endl; return false; } pngls.outfile = fp; if(writepng_init(img,&pngls)!=0) { std::cout<<"error write png init"<<std::endl; } writepng_encode_image(img,&pngls,invertY); fclose(fp); return true; } # endif ImageType PngImage::saigaType() const { int channels = -1; switch (color_type) { case PNG_COLOR_TYPE_GRAY: channels = 1; break; case PNG_COLOR_TYPE_GRAY_ALPHA: channels = 2; break; case PNG_COLOR_TYPE_RGB: channels = 3; break; case PNG_COLOR_TYPE_RGB_ALPHA: channels = 4; break; } SAIGA_ASSERT(channels != -1); ImageElementType elementType = IET_ELEMENT_UNKNOWN; switch (bit_depth) { case 8: elementType = IET_UCHAR; break; case 16: elementType = IET_USHORT; break; case 32: elementType = IET_UINT; break; } SAIGA_ASSERT(elementType != IET_ELEMENT_UNKNOWN); return getType(channels, elementType); } void PngImage::fromSaigaType(ImageType t) { switch (channels(t)) { case 1: color_type = PNG_COLOR_TYPE_GRAY; break; case 2: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3: color_type = PNG_COLOR_TYPE_RGB; break; case 4: color_type = PNG_COLOR_TYPE_RGB_ALPHA; break; default: color_type = PNG_COLOR_TYPE_RGB; SAIGA_ASSERT(0); } switch (elementType(t)) { case IET_UCHAR: bit_depth = 8; break; case IET_USHORT: bit_depth = 16; break; case IET_UINT: bit_depth = 32; break; default: bit_depth = 0; SAIGA_ASSERT(0); } } void convert(PNG::PngImage& src, Image& dest) { dest.width = src.width; dest.height = src.height; dest.type = src.saigaType(); dest.create(); for (int i = 0; i < dest.rows; ++i) { memcpy(dest.rowPtr(i), src.rowPtr(i), std::min(dest.pitchBytes, src.bytesPerRow)); } } void convert(Image& src, PNG::PngImage& dest) { dest.width = src.width; dest.height = src.height; dest.fromSaigaType(src.type); // The rows must be 4-aligned SAIGA_ASSERT(src.pitchBytes % 4 == 0); dest.bytesPerRow = iAlignUp(elementSize(src.type) * src.width, 4); // dest.data.resize(dest.bytesPerRow * src.height); dest.data2 = src.data8(); for (int i = 0; i < src.rows; ++i) { // memcpy(dest.rowPtr(i),src.rowPtr(i), std::min(src.pitchBytes,dest.bytesPerRow)); } } bool save(const Image& img, const std::string& path, bool invertY) { // PNG::PngImage pngimg; // PNG::convert(img,pngimg); // return PNG::writePNG(&pngimg,path,invertY); PNGLoadStore pngls; FILE* fp = fopen(path.c_str(), "wb"); if (!fp) { std::cout << "could not open file: " << path.c_str() << std::endl; return false; } pngls.outfile = fp; if (writepng_init(img, &pngls) != 0) { std::cout << "error write png init" << std::endl; } writepng_encode_image(img, &pngls, invertY); fclose(fp); return true; } bool load(Image& img, const std::string& path, bool invertY) { PNG::PngImage pngimg; bool erg = PNG::readPNG(&pngimg, path, invertY); if (erg) PNG::convert(pngimg, img); return erg; } } // namespace PNG } // namespace Saiga #endif
[ "darius.rueckert@fau.de" ]
darius.rueckert@fau.de
917a1cfeb76a9146b509b34f3daa9298b195ceeb
f1103e383f37e9e2f3695cbe6475d8a4cc8416ea
/sketch_mar13a/build/sketch_mar13a.cpp
668c214d6bdc51cfc45684cf01ec9e4093c4597a
[]
no_license
ajparedes10/arquisoft
140cfaec7d6b7b22097fb73c11be1c6a8c118cae
19a3a53163a41315c9103981960ace2b89e6b717
refs/heads/master
2021-01-22T10:07:22.657248
2017-05-01T20:16:19
2017-05-01T20:16:19
81,987,093
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
/* Obtiene un numero aleatorio y lo muestra en monitor serie */ //Variable donde almacenaremos el numero aleatorio #include "WProgram.h" void setup(); void loop(); long randomNumber; long randomNumber2; long randomNumber3; long randomNumber4; //Funci\u00f3n de inicializaci\u00f3n void setup() { //Inicializamos la comunicaci\u00f3n serial Serial.begin(9600); //Escribimos por el puerto serie mensaje de inicio Serial.println("Inicio de sketch - secuencia de numeros aleatorios"); } //Bucle principal void loop() { //Genera un numero aleatorio entre 1 y 100 randomNumber = random(50,150); randomNumber2 = random(50,150); randomNumber4 = random(50,150); randomNumber3 = random(1,10); //Escribimos el numero aleatorio por el puerto serie Serial.print(randomNumber); Serial.print("@"); Serial.print(randomNumber2); Serial.print("@"); Serial.print(randomNumber4); Serial.print("@"); Serial.print(randomNumber3); Serial.println(" "); delay(2000); }
[ "cc.novoa11@sis.virtual.uniandes.edu.co" ]
cc.novoa11@sis.virtual.uniandes.edu.co
f733850e64d7344c9534c56b41f99252c311693b
bdd9f3cdabe0c768641cf61855a6f24174735410
/src/engine/client/library/clientAudio/src/win32/Audio.h
6b717613b0ff7ef5a57b53e74a527b03993e363a
[]
no_license
SWG-Source/client-tools
4452209136b376ab369b979e5c4a3464be28257b
30ec3031184243154c3ba99cedffb2603d005343
refs/heads/master
2023-08-31T07:44:22.692402
2023-08-28T04:34:07
2023-08-28T04:34:07
159,086,319
15
47
null
2022-04-15T16:20:34
2018-11-25T23:57:31
C++
UTF-8
C++
false
false
13,614
h
// ============================================================================ // // Audio.h // Copyright Sony Online Entertainment // // ============================================================================ #ifndef INCLUDED_Audio_H #define INCLUDED_Audio_H #include "clientAudio/SoundId.h" class AudioSampleInformation; class CellProperty; class CrcString; class Iff; class Object; class SampleId; class Vector; class Plane; namespace AudioCapture { class ICallback; } // ============================================================================ // // Audio // // ============================================================================ //----------------------------------------------------------------------------- class Audio { // These classes are friends to access the protected functions of this class friend class Sound2; friend class Sound2d; friend class Sound3d; friend class ConfigClientAudio; friend class SoundTemplate; friend class Sound2dTemplate; friend class SoundTemplateWidget; friend class Sample2d; friend class Sample3d; friend class SampleStream; public: enum AttenuationMethod { AM_none, AM_2d, AM_3d }; enum PlayBackStatus { PS_doesNotExist = 0, PS_notStarted, PS_playing, PS_done }; enum SoundCategory { SC_ambient = 0, SC_explosion, SC_item, SC_movement, SC_userInterface, SC_vehicle, SC_vocalization, SC_weapon, SC_backGroundMusic, SC_playerMusic, SC_machine, SC_installation, SC_combatMusic, SC_voiceover, SC_bufferedSound, SC_bufferedMusic, SC_count }; enum RoomType { RT_alley = 0, RT_arena, RT_auditorium, RT_bathRoom, RT_carpetedHallway, RT_cave, RT_city, RT_concertHall, RT_dizzy, RT_drugged, RT_forest, RT_generic, RT_hallway, RT_hangar, RT_livingRoom, RT_mountains, RT_paddedCell, RT_parkingLot, RT_plain, RT_psychotic, RT_quarry, RT_room, RT_sewerPipe, RT_stoneCorridor, RT_stoneRoom, RT_underWater, RT_notSupported }; public: // Setup //---------------------------------- static bool install(); static void remove(); static void lock(); static void unLock(); static void setLargePreMixBuffer(); static void setNormalPreMixBuffer(); static void silenceAllNonBackgroundMusic(); static void unSilenceAllNonBackgroundMusic(); static void fadeAllNonVoiceover(); static void unFadeAllNonVoiceover(); static void fadeAll(); static void unfadeAll(); static void setSoundFallOffPower(int const power); // Enabled/Disable the entire audio system static bool isEnabled(); static void setEnabled(bool enabled); static bool isMilesEnabled(); static void * getMilesDigitalDriver(); static void setRequestedMaxNumberOfSamples(int const max); static int getRequestedMaxNumberOfSamples(); static void setMaxCached2dSampleSize(int bytes); static int getMaxCached2dSampleSize(); //static void setMaxCacheSize(int bytes); //static int getMaxCacheSize(); // Update //---------------------------------- static void alter(float const deltaTime, Object const *listener); static void serve(); // Volumes //---------------------------------- static void setSoundVolume(SoundId const &soundId, float volume); static void setSoundPitchDelta(SoundId const &soundId, float pitchDelta); static void setMasterVolume(float volume); static float getMasterVolume(); static float getDefaultMasterVolume(); static void setSoundEffectVolume(float volume); static float getSoundEffectVolume(); static float getDefaultSoundEffectVolume(); static void setBackGroundMusicVolume(float volume); static float getBackGroundMusicVolume(); static float getDefaultBackGroundMusicVolume(); static void setPlayerMusicVolume(float volume); static float getPlayerMusicVolume(); static float getDefaultPlayerMusicVolume(); static void setUserInterfaceVolume(float volume); static float getUserInterfaceVolume(); static float getDefaultUserInterfaceVolume(); static void setFadeAllFactor(float factor); static float getFadeAllFactor(); static float getDefaultFadeAllFactor(); static void setBufferedSoundVolume(float volume); static void setBufferedMusicVolume(float volume); static void setAmbientEffectVolume(float volume); static float getAmbientEffectVolume(); static float getDefaultAmbientEffectVolume(); // Sounds //---------------------------------- static SoundId playSound(char const * const path); // Only use for stereo sounds static SoundId playSound(char const *path, CellProperty const * const parentCell); static SoundId playSound(char const *path, Vector const &position, CellProperty const * const parentCell); static SoundId attachSound(char const *path, Object const *object, char const *hardPointName = NULL); static SoundId createSoundId(char const *path); static void playSound(SoundId &soundId, Vector const *position, CellProperty const * const parentCell); static void playBufferedSound(char const * const buffer, uint32 bufferLength, char const * const extension); static void playBufferedMusic(char const * const buffer, uint32 bufferLength, char const * const extension); static void stopBufferedSound(); static void stopBufferedMusic(); static void silenceNonBufferedMusic(bool silence); static SoundId restartSound(char const *path, Vector const *position = NULL, float const fadeOutTime = 0.0f); static void restartSound(SoundId &soundId, Vector const *position = NULL, float const fadeOutTime = 0.0f); static void detachSound(SoundId const &soundId, float const fadeOutTime = 0.0f); static void detachSound(Object const &object, float const fadeOutTime = 0.0f); static void stopSound(SoundId const &soundId, float const fadeOutTime = 0.0f); static void stopAllSounds(float const fadeOutTime = 0.0f); static bool isSoundPlaying(SoundId const &soundId); static void setAutoDelete(SoundId const &soundId, bool const autoDelete); static void setCurrentSoundTime(SoundId const &soundId, int const milliSecond); static bool getCurrentSoundTime(SoundId const &soundId, int &totalMilliSeconds, int &currentMilliSeconds); static bool getCurrentSoundTime(SoundId const &soundId, int &milliSecond); static bool getTotalSoundTime(SoundId const &soundId, int &milliSecond); static void setSoundPosition_w(SoundId const &soundId, Vector const &position_w); static Vector getSoundPosition_w(SoundId const &soundId); typedef void (*EndOfSampleCallBack)(); static void setEndOfSampleCallBack(SoundId const &soundId, EndOfSampleCallBack callBack); typedef stdvector<Sound2*>::fwd SoundVector; static void getSoundsAttachedToObject (const Object & obj, SoundVector & sv); static Sound2 * getSoundById (const SoundId & soundId); static void transferOwnershipOfSounds(Object const & previousOwner, Object const & newOwner, Plane const * partition); // Sound Status //---------------------------------- static PlayBackStatus getSoundPlayBackStatus(SoundId const &soundId); // Environmental effects //---------------------------------- static void setRoomType(RoomType const roomType); static RoomType getRoomType(); static char const * const getRoomTypeString(); static bool isRoomTypeSupported(); static void setSampleOcclusion(SampleId const &sampleId, float const occlusion); static void setSampleObstruction(SampleId const &sampleId, float const obstruction); // Providers of 3d //---------------------------------- static std::string const & getCurrent3dProvider(); static bool set3dProvider(std::string const &provider); static bool setDefault3dProvider(); static stdvector<std::string>::fwd get3dProviders(); // Utilities //---------------------------------- static Object const * const getListener(); static Vector const & getListenerPosition(); static int getCacheHitCount(); static int getCacheMissCount(); static int getCachedSampleCount(); static int getCurrentCacheSize(); static void getCurrentSample(SoundId const &soundId, TemporaryCrcString &path); static void getCurrentSampleTime(SoundId const &soundId, float &timeTotal, float &timeCurrent); static int getDigitalCpuPercent(); static int getDigitalLatency(); static int getMaxDigitalMixerChannels(); static std::string getMilesVersion(); static int getSample2dCount(); static int getSample3dCount(); static AudioSampleInformation getSampleInformation(std::string const &path); static int getSampleSize(char const *path); static int getSampleStreamCount(); static int getSampleCount(); static std::string getSampleType(void *fileImage, int fileSize); static int getSoundCount(); static float getSoundTemplateVolume(SoundId const &soundId); static float getSoundAttenuation(SoundId const &soundId); static float getSoundVolume(SoundId const &soundId); static float getSoundPitchDelta(SoundId const &soundId); // Adjustment in half steps static bool getLoopOffsets(CrcString const &path, int &loopStartOffset, int &loopEndOffset); static bool isSampleAtEnd(SoundId const &soundId); static float getDistanceAtVolumeCutOff(SoundId const &soundId); static bool isToolApplication(); static void setToolApplication(bool const toolApplication); // SoundEditor access //---------------------------------- static SoundId playSound(Iff &iff); static SoundId playSound(Iff &iff, Vector const &position); static float getFallOffDistance(float const minDistance); static bool isSampleValid(SampleId const &sampleId); static bool isSoundValid(SoundId const &soundId); static bool isSampleForSoundIdPlaying(SoundId const &soundId); static void releaseSampleId(Sound2 const &sound); static bool queueSample(Sound2 &sound, bool const soundIsAlreadyPlaying); static void setDebugEnabled(bool const enabled); static bool isDebugEnabled(); // AudioCapture //---------------------------------- #if PRODUCTION == 0 static bool getAudioCaptureConfig(int& samplesPerSec, int& bitsPerSample, int& channels); static bool startAudioCapture(AudioCapture::ICallback* pCallback); static void stopAudioCapture(); #endif // PRODUCTION protected: // Helper functions that friend classes access, these are the only functions // that friend classes should access static SoundId attachSound(Iff &iff, Object const *object, char const *hardPointName=0); static PlayBackStatus getSamplePlayBackStatus(SampleId const &sampleId); static float getSampleVolume(SampleId const &sampleId); static int getSamplePlayBackRate(SampleId const &sampleId); static void getSampleTime(SampleId const &sampleId, float &timeTotal, float &timeCurrent); static int getSampleCurrentTime(SampleId const &sampleId); static void setSampleCurrentTime(SampleId const &sampleId, int const milliSeconds); static int getSampleTotalTime(SampleId const &sampleId); static void setSamplePlayBackRate(SampleId const &sampleId, int const playBackRate, float const playBackRateDelta = 0.0f); static void setSampleVolume(SampleId const &sampleId, float const volume); static float getSampleEffectsLevel(SampleId const &sampleId); static void setSampleEffectsLevel(SampleId const &sampleId, float const effectLevel); static void setSamplePosition_w(SampleId const &sampleId, Vector const &position_w); static bool getSoundWorldPosition(SoundId const &soundId, Vector &position); static CrcString const *increaseReferenceCount(const char *path, bool const cacheSample); static void decreaseReferenceCount(CrcString const &path); static float getObstruction(); static float getOcclusion(); #ifdef _DEBUG // Runtime statistics static void showAudioDebug(); static void debugDumpAudioText(); #endif // _DEBUG private: static SoundId playSound(Iff &iff, Vector const * const position, CellProperty const * const parentCell); static SoundId playSound(char const *path, Vector const * const position, CellProperty const * const parentCell); static void startSample(Sound2 & sound); // Disabled Audio(); Audio(Audio const &); Audio &operator=(Audio const &); ~Audio(); }; // ============================================================================ #endif // INCLUDED_Audio_H
[ "swgmaster@india.com" ]
swgmaster@india.com
a5d74b594e8978189faec88dcf8749c9e933b045
5df7293b4a7d7f3cf4e4d25921e252ac92c21b5f
/onnxruntime/core/providers/xnnpack/nn/average_pool.cc
d933ff30748081cd97b98bd87918a493a509bc04
[ "MIT" ]
permissive
Nifury/onnxruntime
ccd7fed07ad917fb3b63ae333c388895073f9263
198994d01d4e226fd3a8816e8b2fad00c84a691c
refs/heads/main
2023-04-08T21:40:39.383881
2023-04-05T00:34:13
2023-04-05T00:34:13
312,125,003
7
2
MIT
2020-11-12T00:28:40
2020-11-12T00:28:39
null
UTF-8
C++
false
false
11,715
cc
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/providers/xnnpack/nn/average_pool.h" #include "core/common/status.h" #include "core/graph/graph.h" #include "core/providers/utils.h" #include "core/framework/tensorprotoutils.h" #include "core/providers/xnnpack/detail/utils.h" namespace onnxruntime { namespace xnnpack { namespace { Status CreateXnnpackKernel(const PoolAttributes& pool_attrs, int64_t C, const std::optional<std::pair<float, float>>& clip_min_max, struct xnn_operator*& p, const OpQuantParam& quant_param, OpComputeType avgpool_type) { uint32_t input_padding_top = gsl::narrow<uint32_t>(pool_attrs.pads[0]); uint32_t input_padding_left = gsl::narrow<uint32_t>(pool_attrs.pads[1]); uint32_t input_padding_bottom = gsl::narrow<uint32_t>(pool_attrs.pads[2]); uint32_t input_padding_right = gsl::narrow<uint32_t>(pool_attrs.pads[3]); uint32_t pooling_height = gsl::narrow<uint32_t>(pool_attrs.kernel_shape[0]); uint32_t pooling_width = gsl::narrow<uint32_t>(pool_attrs.kernel_shape[1]); uint32_t stride_height = gsl::narrow<uint32_t>(pool_attrs.strides[0]); uint32_t stride_width = gsl::narrow<uint32_t>(pool_attrs.strides[1]); uint32_t flags = 0; if (pool_attrs.auto_pad == AutoPadType::SAME_UPPER) { flags |= XNN_FLAG_TENSORFLOW_SAME_PADDING; } float foutput_min = clip_min_max ? clip_min_max->first : -INFINITY; float foutput_max = clip_min_max ? clip_min_max->second : INFINITY; xnn_status status = xnn_status_unsupported_parameter; if (avgpool_type == OpComputeType::op_compute_type_fp32) { status = xnn_create_average_pooling2d_nhwc_f32(input_padding_top, input_padding_right, input_padding_bottom, input_padding_left, pooling_height, pooling_width, stride_height, stride_width, C, C, C, // channels, input_pixel_stride, output_pixel_stride foutput_min, foutput_max, flags, &p); } else if (avgpool_type == OpComputeType::op_compute_type_qu8) { const float output_scale = quant_param[1].first[0]; const uint8_t output_zero_point = quant_param[1].second; const uint8_t output_min = xnn_u8s8_quantize<uint8_t>(foutput_min, output_scale, output_zero_point); const uint8_t output_max = xnn_u8s8_quantize<uint8_t>(foutput_max, output_scale, output_zero_point); status = xnn_create_average_pooling2d_nhwc_qu8(input_padding_top, input_padding_right, input_padding_bottom, input_padding_left, pooling_height, pooling_width, stride_height, stride_width, C, C, C, // channels, input_pixel_stride, output_pixel_stride quant_param[0].second, quant_param[0].first[0], quant_param[1].second, quant_param[1].first[0], output_min, output_max, flags, &p); } if (status != xnn_status_success) { return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "xnn_create_average_pooling2d_nhwc_", OpTypeToString(avgpool_type), " failed. Status:", status); } return Status::OK(); } bool IsQuantAvgPoolSupported(const NodeUnit& node_unit, const GraphViewer& graph) { TensorQuantType x_input_type = GetTensorQuantType(node_unit, 0, false, graph); TensorQuantType output_type = GetTensorQuantType(node_unit, 0, true, graph); return (x_input_type == TensorTypeUint8 && output_type == TensorTypeUint8); } bool IsQuantizedAvgPool(QuantizedOpType quant_op_type) { return (quant_op_type == QuantizedOpType::QlinearAvgPool) || (quant_op_type == QuantizedOpType::QDQAvgPool); } } // namespace bool AveragePool::IsOnnxNodeSupported(const NodeUnit& node_unit, const GraphViewer& graph) { bool supported = false; auto qtype = GetQuantizedOpType(node_unit); // we check quant-conditions first, if this quant-node is not supported, return directly. if (IsQuantizedAvgPool(qtype) && IsQuantAvgPoolSupported(node_unit, graph) == false) { return false; } // share the common checks here for fp32 and quant-op const auto& inputs = node_unit.Inputs(); // use do {} while(false) so it's easier to set a breakpoint on the return do { // AveragePool has 1 input. const auto& x_arg = inputs[0].node_arg; // we only support 2D (4 dims with batch and channel) const auto* x_shape = x_arg.Shape(); if (!x_shape || x_shape->dim_size() != 4) { break; } // we only support float and u8 currently const auto* x_type = x_arg.TypeAsProto(); if (x_type == nullptr || (x_type->tensor_type().elem_type() != ONNX_NAMESPACE::TensorProto_DataType_FLOAT && x_type->tensor_type().elem_type() != ONNX_NAMESPACE::TensorProto_DataType_UINT8)) { break; } // require C, H, W to be known so we can construct the xnnpack kernel prior to Compute if (!x_shape->dim(1).has_dim_value() || !x_shape->dim(2).has_dim_value() || !x_shape->dim(3).has_dim_value()) { break; } ProtoHelperNodeContext nc(node_unit.GetNode()); OpNodeProtoHelper info(&nc); PoolAttributes pool_attrs(info, "AveragePool", node_unit.SinceVersion()); // xnnpack doesn't appear to support using 'ceil' to calculate the output shape // https://github.com/google/XNNPACK/blob/3caa8b9de973839afa1e2a1462ff356e6927a66b/src/operators/average-pooling-nhwc.c#L643 // calls compute_output_dimension but there's no ability to specify rounding that value up. if (pool_attrs.ceil_mode != 0) { break; } if (!IsPaddingTypeSupported(pool_attrs.auto_pad)) { break; } if ((pool_attrs.kernel_shape.size() != 2) || (pool_attrs.kernel_shape[0] == 1 && pool_attrs.kernel_shape[1] == 1)) { // XNNPack doesn't support 1x1 average pool. break; } // a weird design in xnnpack, fp32 should have count_include_pad false, // while quant should have count_include_pad true bool cp_in_op = pool_attrs.count_include_pad ^ IsQuantizedAvgPool(qtype); if (cp_in_op) { break; } supported = true; } while (false); return supported; } AveragePool::AveragePool(const OpKernelInfo& info) : XnnpackKernel(info), pool_attrs_{info, "AveragePool", info.node().SinceVersion()} { // get values from any fusion with an activation if (std::string activation; info.GetAttr<std::string>("activation", &activation).IsOK()) { if (activation == "Clip" || activation == "Relu") { std::vector<float> activation_params; // min/max could be from Clip or Relu if (info.GetAttrs<float>("activation_params", activation_params).IsOK()) { if (activation_params.size() == 2) { clip_min_max_ = {activation_params[0], activation_params[1]}; } } } } // input is NHWC and we only support input with 4 dims. we checked C, H, W were all known in the op support checker const auto& X_arg = *Node().InputDefs()[0]; const auto& X_shape = *X_arg.Shape(); int64_t H = X_shape.dim(1).dim_value(); int64_t W = X_shape.dim(2).dim_value(); int64_t C = X_shape.dim(3).dim_value(); // create NCHW shape to calculate most of the output shape. 'N' is set in Compute. TensorShapeVector input_shape{1, C, H, W}; auto pads = pool_attrs_.pads; auto nchw_output_dims = pool_attrs_.SetOutputSize(input_shape, C, &pads); output_dims_ = {-1, nchw_output_dims[2], nchw_output_dims[3], nchw_output_dims[1]}; OpQuantParam quant_param; // TEMPORARY sanity check. If C, H and W are known, the output shape should have been able to be inferred, with the // exception of the batch size. Can be removed once we've run more models using xnnpack AveragePool. auto inferred_output_shape = utils::GetTensorShapeFromTensorShapeProto(*Node().OutputDefs()[0]->Shape()); ORT_ENFORCE(inferred_output_shape[1] == output_dims_[1] && inferred_output_shape[2] == output_dims_[2] && inferred_output_shape[3] == output_dims_[3], "Shape mismatch between inferred value and calculated value."); const auto& input_dtype = X_arg.TypeAsProto()->tensor_type().elem_type(); if (input_dtype == ONNX_NAMESPACE::TensorProto_DataType_FLOAT) { avgpool_type_ = OpComputeType::op_compute_type_fp32; } else if (input_dtype == ONNX_NAMESPACE::TensorProto_DataType_UINT8) { // the order of input tensor, x,x_scale, x_zp, y_scale, y_zp quant_param = ParseQuantParamForOp(info, input_dtype, 1); avgpool_type_ = OpComputeType::op_compute_type_qu8; } else { auto stype = DataTypeImpl::ToString(DataTypeImpl::TypeFromProto(*X_arg.TypeAsProto())); ORT_THROW("unsupported AveragePool in XnnpackEP, we have FLOAT|UINT8, but got ", stype); } struct xnn_operator* p; auto ret = CreateXnnpackKernel(pool_attrs_, C, clip_min_max_, p, quant_param, avgpool_type_); ORT_ENFORCE(ret.IsOK(), ret.ErrorMessage()); op0_.reset(p); } Status AveragePool::Compute(OpKernelContext* context) const { const auto& X = *context->Input<Tensor>(0); const auto& X_shape = X.Shape(); int64_t N = X_shape[0]; int64_t H = X_shape[1]; int64_t W = X_shape[2]; // set the N dim to the correct value TensorShapeVector output_dims{output_dims_}; output_dims[0] = N; Tensor& Y = *context->Output(0, output_dims); // empty input if (Y.Shape().Size() == 0) { return Status::OK(); } pthreadpool_t t_pool = GetThreadPool(); xnn_status status = xnn_status_invalid_state; if (avgpool_type_ == OpComputeType::op_compute_type_fp32) { status = xnn_setup_average_pooling2d_nhwc_f32(op0_.get(), N, H, W, X.Data<float>(), Y.MutableData<float>(), t_pool /*threadpool */); } else if (avgpool_type_ == OpComputeType::op_compute_type_qu8) { status = xnn_setup_average_pooling2d_nhwc_qu8(op0_.get(), N, H, W, X.Data<uint8_t>(), Y.MutableData<uint8_t>(), t_pool /*threadpool */); } if (status != xnn_status_success) { return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "xnn_setup_average_pooling2d_nhwc_", OpTypeToString(avgpool_type_), " returned ", status); } status = xnn_run_operator(op0_.get(), t_pool); if (status != xnn_status_success) { return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "xnn_run_operator returned ", status); } return Status::OK(); } ONNX_OPERATOR_KERNEL_EX( AveragePool, kMSInternalNHWCDomain, 11, kXnnpackExecutionProvider, KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()), AveragePool); ONNX_OPERATOR_KERNEL_EX( QLinearAveragePool, kMSInternalNHWCDomain, 1, kXnnpackExecutionProvider, KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<uint8_t>()), AveragePool); } // namespace xnnpack } // namespace onnxruntime
[ "noreply@github.com" ]
Nifury.noreply@github.com
f723322f6962769feb404d5d81ac24ec1216abdc
e572189d60a70df27b95fc84b63cc24048b90d09
/bjoj/3143.cpp
9eba49e8eee23c9e4979c1b79aad4a8db683c0eb
[]
no_license
namhong2001/Algo
00f70a0f6132ddf7a024aa3fc98ec999fef6d825
a58f0cb482b43c6221f0a2dd926dde36858ab37e
refs/heads/master
2020-05-22T12:29:30.010321
2020-05-17T06:16:14
2020-05-17T06:16:14
186,338,640
0
0
null
null
null
null
UTF-8
C++
false
false
500
cpp
#include <iostream> #include <vector> #include <algorithm> #include <queue> int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> aset(n); vector<pair<int,int>> bset(n); for (int i=0; i<n; ++i) { cin >> aset[i]; } for (int i=0; i<n; ++i) { int a, b; cin >> a >> b; bset[i] = {a,b}; } sort(aset.begin(), aset.end()); sort(bset.begin(), bset.end()); priority_queue<pair<int,int>> pq; int ans = 0; int bidx = 0; for (int a : aset) {
[ "namhong2001@gmail.com" ]
namhong2001@gmail.com
cc8f7e42234cd1e9a3997375ffef055952e239cf
c5a98c662bf46ca465d621810275a81c2372e9e9
/Arduino/WifiModule/WifiModule.ino
f48e510e3087393bffcf899c084836ca42dac7e2
[]
no_license
AllanFontaine/Pot-App
241a01a44858e4af509d08546488aa58503eb02e
f28e64ff24c25076a0f71eb4a0c60bc4c4e875b2
refs/heads/master
2023-01-31T14:21:09.979306
2020-12-17T13:23:21
2020-12-17T13:23:21
296,675,344
2
0
null
2020-12-17T13:23:22
2020-09-18T16:33:54
CSS
UTF-8
C++
false
false
5,253
ino
#include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> const char* ssid = "PDC"; const char* password = "Scott44572Glenn"; //Your Domain name with URL path or IP address with path String serverDonneesParcelle = "https://api.pot-app.be/api/donnees-parcelle/"; String serverDonneesUser = "https://api.pot-app.be/api/donnees-user/"; String serverName = ""; String userCode = "codeCelia"; // the following variables are unsigned longs because the time, measured in // milliseconds, will quickly become a bigger number than can be stored in an int. unsigned long lastTime = 0; // Timer set to 10 minutes (600000) //unsigned long timerDelay = 600000; // Set timer to 5 seconds (5000) unsigned long timerDelay = 5000; float temp_exterieure; float hum_exterieure; float id_parcelle_1; float hum_sol_parcelle_1; float quantite_eau_parcelle_1; float id_parcelle_2; float hum_sol_parcelle_2; float quantite_eau_parcelle_2; float id_parcelle_3; float hum_sol_parcelle_3; float quantite_eau_parcelle_3; boolean newData = false; void postToParcel(String parcelleId, String humidite_sol, String quantite_eau){ if(WiFi.status()== WL_CONNECTED){ HTTPClient http; WiFiClientSecure client; client.setInsecure(); //the magic line, use with caution client.connect(serverDonneesUser, 443); // Your Domain name with URL path or IP address with path http.begin(client, serverDonneesParcelle); // Specify content-type header http.addHeader("Content-Type", "application/x-www-form-urlencoded"); // Data to send with HTTP POST // If you need an HTTP request with a content type: application/json, use the following: http.addHeader("Content-Type", "application/json"); String jsonObject = "{\"parcelleId\":" + parcelleId + ",\"humidite_sol\":" + humidite_sol + ",\"quantite_eau_litre\": \"" + quantite_eau + "\",\"code\": \"" + userCode + "\"}"; int httpResponseCode = http.POST(jsonObject); Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); // Free resources http.end(); } else { Serial.println("WiFi Disconnected"); } } void postToUser(String temperature_exterieur, String humidite_exterieur){ if(WiFi.status()== WL_CONNECTED){ HTTPClient http; WiFiClientSecure client; client.setInsecure(); //the magic line, use with caution client.connect(serverDonneesUser, 443); // Your Domain name with URL path or IP address with path http.begin(client, serverDonneesUser); // Specify content-type header http.addHeader("Content-Type", "application/x-www-form-urlencoded"); // Data to send with HTTP POST // If you need an HTTP request with a content type: application/json, use the following: http.addHeader("Content-Type", "application/json"); String jsonObject = "{\"userId\":\" 1 \",\"temperature_exterieur\":" + temperature_exterieur + ",\"humidite_exterieur\": \"" + humidite_exterieur + "\",\"code\": \"" + userCode + "\"}"; int httpResponseCode = http.POST(jsonObject); Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); String payload = http.getString(); Serial.println(payload); // Free resources http.end(); } else { Serial.println("WiFi Disconnected"); } } void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.println("Connecting"); while(WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to WiFi network with IP Address: "); Serial.println(WiFi.localIP()); Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading."); } void loop() { //Send an HTTP POST request every 10 minutes newData = true; Serial.println("NewData true"); delay(5000); if (newData) { postToParcel("5", "80", "2.5"); delay(2000); postToParcel("5", "80", "2.5"); delay(2000); postToUser("22.5","25"); newData = false; Serial.println("NewData false"); } //GET REQUEST NOT USED if (false) { //Check WiFi connection status if(WiFi.status()== WL_CONNECTED){ HTTPClient http; String serverPath = serverName + "?code=codeCelia"; WiFiClientSecure client; client.setInsecure(); //the magic line, use with caution client.connect(serverPath, 443); Serial.println(serverPath); // Your Domain name with URL path or IP address with path http.begin(client, serverPath.c_str()); // Send HTTP GET request int httpResponseCode = http.GET(); if (httpResponseCode>0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); String payload = http.getString(); Serial.println(payload); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); } // Free resources http.end(); } else { Serial.println("WiFi Disconnected"); } lastTime = millis(); } }
[ "mr.glennichou@gmail.com" ]
mr.glennichou@gmail.com
f1d1e139fcdd08bdafdf0cb4170f83db117f7a6f
0254f2ee4fde7362762a32cf8e59612271c63c87
/src/plugins/server/cache.h
ddda11011834bd9b466d4692415e4747611baddd
[]
no_license
alexey-zayats/athletic
9a97f7f221bd3671df43ac65642df2916ba42a0b
0c65552d32a7bf581b03f0311e6764aaa60e1690
refs/heads/master
2020-05-22T01:31:14.186306
2017-07-10T12:06:58
2017-07-10T12:06:58
64,463,265
0
0
null
null
null
null
UTF-8
C++
false
false
3,466
h
#ifndef SERVER_CACHE #define SERVER_CACHE #include "cacheentry.h" #include "server_global.h" class QReadWriteLock; namespace Server { /** @brief A read-write-locked cache structure. * * Depending on the Server configuration, this will use one of * several backends; for example, QCache-based, or memcached-based. * * If QCache is used, the cache will be shared between all threads in * the current process. If memcached is used, the cache will: * - Perform better (honestly, even though it's out of process) * - Be shared with any other instances of the same application using * the same memcached pool. * * All backends should lock as neccessary, but you may want to lock at * an outer scope for performance. * * Keep in mind that even with a recursive lock, the locks must be of * the same type; for example, all the writing calls will deadlock * if called while a read lock is open. * * @section settings Settings * * @todo A configuration interface for these needs to be added (probably --configure-cache?) * * In the settings file (.ApplicationName), there are several settings for this: @verbatim [cache] backend={RamCache|MemcachedCache} @endverbatim * * RamCache is always available, and gives a cache shared between all requests in the current process. * Memcached performs better, and depending on the configuration, can be used by multiple processes, * or even multiple machines. * * @subsection ramcache RamCache * * RamCache is a simple QCache-backed cache, with just one setting: * @verbatim [RamCache] maxSize=numberOfBytes @endverbatim * * This allows you to configure the maximum size of the cache * * @subsection memcached MemcachedCache * * This backend performs better, can be shared amongst a cluster, but is only available if * Server was built with -DWITH_MEMCACHED_SUPPORT=ON * @verbatim [MemcachedServers] size=numberOfServers 0/host=foo 0/port=11211 1/host=bar 1/port=11211 ... @endverbatim * * If a port is not set, Server uses libmemcached's default - normally 11211. * * If the size is zero, or this section is omitted, Server will try to connect to * a memcached server on localhost, on the default port. If this does not work, the * application will exit. * * @ingroup plugins */ class SERVER_EXPORT Cache { public: /// Construct a Cache with the given name. Cache(const QString& cacheName); /// Destroy a cache. ~Cache(); /// Remove a key from the cache. void remove(const QString& key); /** Retrieve a value from the cache. * * If the entry isnt' in the cache, an invalid * CacheEntry will be returned. */ CacheEntry value(const QString& key) const; /** Set a value in the cache. * * If a value already exists with the given key, it is * overwritten. */ void setValue(const QString& key, const CacheEntry& object); protected: /// Return a pointer to the QReadWriteLock. QReadWriteLock* readWriteLock() const; private: class Private; Private* d; }; } #endif // SERVER_CACHE
[ "alexey.zayats@gmail.com" ]
alexey.zayats@gmail.com
d1f96d1d675e3c893ed054560e07e89f707367d8
9de18ef120a8ae68483b866c1d4c7b9c2fbef46e
/third_party/libutils/Singleton_test1.cpp
4a91ec08a742ae9e4f19501d98acf5c4955bca57
[ "BSD-2-Clause", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
google/orbit
02a5b4556cd2f979f377b87c24dd2b0a90dff1e2
68c4ae85a6fe7b91047d020259234f7e4961361c
refs/heads/main
2023-09-03T13:14:49.830576
2023-08-25T06:28:36
2023-08-25T06:28:36
104,358,587
2,680
325
BSD-2-Clause
2023-08-25T06:28:37
2017-09-21T14:28:35
C++
UTF-8
C++
false
false
1,199
cpp
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <utils/Singleton.h> #include "Singleton_test.h" namespace android { // Singleton<SingletonTestStruct> is referenced in Singleton_test1.cpp and // Singleton_test2.cpp, but only defined in Singleton_test1.cpp. ANDROID_SINGLETON_STATIC_INSTANCE(SingletonTestData); void singletonSetInstanceContents(unsigned int contents) { SingletonTestData::getInstance().contents = contents; } unsigned int singletonGetInstanceContents() { return SingletonTestData::getInstance().contents; } bool singletonHasInstance() { return SingletonTestData::hasInstance(); } }
[ "noreply@github.com" ]
google.noreply@github.com
72c8b6139f2f383cad00448c0b5beb49ddd8d5c4
f4bc78d304fcebd766a7a7d161e6b72d61e10d9a
/code/compiler/include/allscale/compiler/frontend/allscale_frontend.h
1f5f32405524045b25d1fd071791b8d99a30b13e
[]
no_license
allscale/allscale_compiler
6a02d655e1a101a9a6afa0c79df7e772fc8abcd6
12e5dada431e574b025c572ae5f8819047be12aa
refs/heads/master
2021-01-12T06:53:34.553070
2019-03-19T12:43:15
2019-03-19T12:43:15
76,847,596
5
1
null
2017-12-01T11:39:58
2016-12-19T09:26:03
C++
UTF-8
C++
false
false
195
h
#pragma once #include "insieme/frontend/frontend.h" namespace allscale { namespace compiler { namespace frontend { void configureConversionJob(insieme::frontend::ConversionJob& job); } } }
[ "peterz@dps.uibk.ac.at" ]
peterz@dps.uibk.ac.at
de4521109d8b683aa1a801f7c4468e31355f5e92
3fee60dca52d83e0e96824abb53d380f518f4f68
/Valid Triangle Number.cpp
ee9f064fbbfa5875ea0e9a8b90fdc9ee92eca35b
[]
no_license
ShreyashiBansal/LEETCODE-JULY-2021
a9d11532cc533f66681a5f21cc80ef7b89e29add
7e99ec9c9fe2f44d60c0b37d2ddac5c94b5bd22b
refs/heads/main
2023-06-25T03:41:58.312946
2021-07-30T12:21:44
2021-07-30T12:21:44
382,679,281
0
0
null
null
null
null
UTF-8
C++
false
false
532
cpp
class Solution { public: int triangleNumber(vector<int>& nums) { sort(nums.begin(),nums.end()); int c=0; for(int i=2;i<nums.size();i++){ int left = 0, right = i-1; while(left<right) { if(nums[left] + nums[right] > nums[i]){ c += (right - left); right--; } else{ left++; } } } return c; } };
[ "noreply@github.com" ]
ShreyashiBansal.noreply@github.com
57a36d4fe0d245a5190e0ca3e8a498921939056b
fa4c26316e29e18e8b34f8ee22011d748985dae0
/Native/animcontrol.h
3531eb11cfec8c94f1288f3adaa4c70f74091520
[]
no_license
shoff/ShadowbaneCacheViewer
6024a412a57d5790bd89f893e03562027f00165e
cc42629430adff108015fca9d04a7b8b237f5aed
refs/heads/main
2023-05-25T19:03:31.569467
2022-08-27T19:33:43
2022-08-27T19:33:43
37,615,646
7
2
null
null
null
null
UTF-8
C++
false
false
401
h
#pragma once #include "stdafx.h" #include "skeleton.h" #include "enums.h" class AnimControl: public wxWindow { DECLARE_CLASS(AnimControl) DECLARE_EVENT_TABLE() wxComboBox *animList; unsigned int selectedAnim; Skeleton *skeleton; public: AnimControl(wxWindow* parent, wxWindowID id); ~AnimControl(); void OnAnim(wxCommandEvent &event); void UpdateSkeleton(Skeleton *s); }; // --
[ "smhoff256@gmail.com" ]
smhoff256@gmail.com
7c2c588f30b18f3454647da23347af5f93b2b4c7
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/media/formats/mp4/mp4_stream_parser_unittest.cc
d7b23181681d90ae1a5df19abf1384aaa90865a3
[ "BSD-3-Clause" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
22,185
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/formats/mp4/mp4_stream_parser.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <memory> #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "media/base/audio_decoder_config.h" #include "media/base/decoder_buffer.h" #include "media/base/media_track.h" #include "media/base/media_tracks.h" #include "media/base/mock_media_log.h" #include "media/base/stream_parser.h" #include "media/base/stream_parser_buffer.h" #include "media/base/test_data_util.h" #include "media/base/text_track_config.h" #include "media/base/video_decoder_config.h" #include "media/formats/mp4/es_descriptor.h" #include "media/formats/mp4/fourccs.h" #include "media/media_features.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::InSequence; using ::testing::StrictMock; using base::TimeDelta; namespace media { namespace mp4 { // Matchers for verifying common media log entry strings. MATCHER_P(VideoCodecLog, codec_string, "") { return CONTAINS_STRING(arg, "Video codec: " + std::string(codec_string)); } MATCHER_P(AudioCodecLog, codec_string, "") { return CONTAINS_STRING(arg, "Audio codec: " + std::string(codec_string)); } MATCHER(SampleEncryptionInfoUnavailableLog, "") { return CONTAINS_STRING(arg, "Sample encryption info is not available."); } MATCHER_P(ErrorLog, error_string, "") { return CONTAINS_STRING(arg, error_string); } class MP4StreamParserTest : public testing::Test { public: MP4StreamParserTest() : media_log_(new StrictMock<MockMediaLog>()), configs_received_(false), lower_bound_( DecodeTimestamp::FromPresentationTime(base::TimeDelta::Max())) { std::set<int> audio_object_types; audio_object_types.insert(kISO_14496_3); parser_.reset(new MP4StreamParser(audio_object_types, false)); } protected: scoped_refptr<StrictMock<MockMediaLog>> media_log_; std::unique_ptr<MP4StreamParser> parser_; bool configs_received_; std::unique_ptr<MediaTracks> media_tracks_; AudioDecoderConfig audio_decoder_config_; VideoDecoderConfig video_decoder_config_; DecodeTimestamp lower_bound_; StreamParser::TrackId audio_track_id_; StreamParser::TrackId video_track_id_; bool AppendData(const uint8_t* data, size_t length) { return parser_->Parse(data, length); } bool AppendDataInPieces(const uint8_t* data, size_t length, size_t piece_size) { const uint8_t* start = data; const uint8_t* end = data + length; while (start < end) { size_t append_size = std::min(piece_size, static_cast<size_t>(end - start)); if (!AppendData(start, append_size)) return false; start += append_size; } return true; } void InitF(const StreamParser::InitParameters& expected_params, const StreamParser::InitParameters& params) { DVLOG(1) << "InitF: dur=" << params.duration.InMicroseconds() << ", autoTimestampOffset=" << params.auto_update_timestamp_offset; EXPECT_EQ(expected_params.duration, params.duration); EXPECT_EQ(expected_params.timeline_offset, params.timeline_offset); EXPECT_EQ(expected_params.auto_update_timestamp_offset, params.auto_update_timestamp_offset); EXPECT_EQ(expected_params.liveness, params.liveness); EXPECT_EQ(expected_params.detected_audio_track_count, params.detected_audio_track_count); EXPECT_EQ(expected_params.detected_video_track_count, params.detected_video_track_count); EXPECT_EQ(expected_params.detected_text_track_count, params.detected_text_track_count); } bool NewConfigF(std::unique_ptr<MediaTracks> tracks, const StreamParser::TextTrackConfigMap& tc) { configs_received_ = true; CHECK(tracks.get()); DVLOG(1) << "NewConfigF: got " << tracks->tracks().size() << " tracks"; for (const auto& track : tracks->tracks()) { const auto& track_id = track->bytestream_track_id(); if (track->type() == MediaTrack::Audio) { audio_track_id_ = track_id; audio_decoder_config_ = tracks->getAudioConfig(track_id); DVLOG(1) << "track_id=" << track_id << " audio config=" << (audio_decoder_config_.IsValidConfig() ? audio_decoder_config_.AsHumanReadableString() : "INVALID"); } else if (track->type() == MediaTrack::Video) { video_track_id_ = track_id; video_decoder_config_ = tracks->getVideoConfig(track_id); DVLOG(1) << "track_id=" << track_id << " video config=" << (video_decoder_config_.IsValidConfig() ? video_decoder_config_.AsHumanReadableString() : "INVALID"); } } media_tracks_ = std::move(tracks); return true; } bool NewBuffersF(const StreamParser::BufferQueueMap& buffer_queue_map) { DecodeTimestamp lowest_end_dts = kNoDecodeTimestamp(); for (const auto& it : buffer_queue_map) { DVLOG(3) << "Buffers for track_id=" << it.first; DCHECK(!it.second.empty()); if (lowest_end_dts == kNoDecodeTimestamp() || lowest_end_dts > it.second.back()->GetDecodeTimestamp()) lowest_end_dts = it.second.back()->GetDecodeTimestamp(); for (const auto& buf : it.second) { DVLOG(3) << " track_id=" << buf->track_id() << ", size=" << buf->data_size() << ", pts=" << buf->timestamp().InSecondsF() << ", dts=" << buf->GetDecodeTimestamp().InSecondsF() << ", dur=" << buf->duration().InSecondsF(); // Ensure that track ids are properly assigned on all emitted buffers. EXPECT_EQ(it.first, buf->track_id()); } } EXPECT_NE(lowest_end_dts, kNoDecodeTimestamp()); if (lower_bound_ != kNoDecodeTimestamp() && lowest_end_dts < lower_bound_) { return false; } lower_bound_ = lowest_end_dts; return true; } void KeyNeededF(EmeInitDataType type, const std::vector<uint8_t>& init_data) { DVLOG(1) << "KeyNeededF: " << init_data.size(); EXPECT_EQ(EmeInitDataType::CENC, type); EXPECT_FALSE(init_data.empty()); } void NewSegmentF() { DVLOG(1) << "NewSegmentF"; lower_bound_ = kNoDecodeTimestamp(); } void EndOfSegmentF() { DVLOG(1) << "EndOfSegmentF()"; lower_bound_ = DecodeTimestamp::FromPresentationTime(base::TimeDelta::Max()); } void InitializeParserWithInitParametersExpectations( StreamParser::InitParameters params) { parser_->Init( base::Bind(&MP4StreamParserTest::InitF, base::Unretained(this), params), base::Bind(&MP4StreamParserTest::NewConfigF, base::Unretained(this)), base::Bind(&MP4StreamParserTest::NewBuffersF, base::Unretained(this)), true, base::Bind(&MP4StreamParserTest::KeyNeededF, base::Unretained(this)), base::Bind(&MP4StreamParserTest::NewSegmentF, base::Unretained(this)), base::Bind(&MP4StreamParserTest::EndOfSegmentF, base::Unretained(this)), media_log_); } StreamParser::InitParameters GetDefaultInitParametersExpectations() { // Most unencrypted test mp4 files have zero duration and are treated as // live streams. StreamParser::InitParameters params(kInfiniteDuration); params.liveness = DemuxerStream::LIVENESS_LIVE; params.detected_audio_track_count = 1; params.detected_video_track_count = 1; params.detected_text_track_count = 0; return params; } void InitializeParserAndExpectLiveness(DemuxerStream::Liveness liveness) { auto params = GetDefaultInitParametersExpectations(); params.liveness = liveness; InitializeParserWithInitParametersExpectations(params); } void InitializeParser() { InitializeParserWithInitParametersExpectations( GetDefaultInitParametersExpectations()); } bool ParseMP4File(const std::string& filename, int append_bytes) { scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile(filename); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), append_bytes)); return true; } }; TEST_F(MP4StreamParserTest, UnalignedAppend) { // Test small, non-segment-aligned appends (small enough to exercise // incremental append system) EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")); InitializeParser(); ParseMP4File("bear-1280x720-av_frag.mp4", 512); } TEST_F(MP4StreamParserTest, BytewiseAppend) { // Ensure no incremental errors occur when parsing EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")); InitializeParser(); ParseMP4File("bear-1280x720-av_frag.mp4", 1); } TEST_F(MP4StreamParserTest, MultiFragmentAppend) { // Large size ensures multiple fragments are appended in one call (size is // larger than this particular test file) EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")); InitializeParser(); ParseMP4File("bear-1280x720-av_frag.mp4", 768432); } TEST_F(MP4StreamParserTest, Flush) { // Flush while reading sample data, then start a new stream. EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")).Times(2); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")).Times(2); InitializeParser(); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-1280x720-av_frag.mp4"); EXPECT_TRUE(AppendDataInPieces(buffer->data(), 65536, 512)); parser_->Flush(); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } TEST_F(MP4StreamParserTest, Reinitialization) { EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")).Times(2); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")).Times(2); InitializeParser(); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-1280x720-av_frag.mp4"); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } TEST_F(MP4StreamParserTest, MPEG2_AAC_LC) { InSequence s; std::set<int> audio_object_types; audio_object_types.insert(kISO_13818_7_AAC_LC); parser_.reset(new MP4StreamParser(audio_object_types, false)); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.67")); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")); auto params = GetDefaultInitParametersExpectations(); params.detected_video_track_count = 0; InitializeParserWithInitParametersExpectations(params); ParseMP4File("bear-mpeg2-aac-only_frag.mp4", 512); } // Test that a moov box is not always required after Flush() is called. TEST_F(MP4StreamParserTest, NoMoovAfterFlush) { EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")); InitializeParser(); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-1280x720-av_frag.mp4"); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); parser_->Flush(); const int kFirstMoofOffset = 1307; EXPECT_TRUE(AppendDataInPieces(buffer->data() + kFirstMoofOffset, buffer->data_size() - kFirstMoofOffset, 512)); } // Test an invalid file where there are encrypted samples, but // SampleEncryptionBox (senc) and SampleAuxiliaryInformation{Sizes|Offsets}Box // (saiz|saio) are missing. // The parser should fail instead of crash. See http://crbug.com/361347 TEST_F(MP4StreamParserTest, MissingSampleEncryptionInfo) { InSequence s; // Encrypted test mp4 files have non-zero duration and are treated as // recorded streams. auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMicroseconds(23219); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_video_track_count = 0; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-1280x720-a_frag-cenc_missing-saiz-saio.mp4"); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")).Times(2); EXPECT_MEDIA_LOG(SampleEncryptionInfoUnavailableLog()); EXPECT_FALSE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } // Test a file where all video samples start with an Access Unit // Delimiter (AUD) NALU. TEST_F(MP4StreamParserTest, VideoSamplesStartWithAUDs) { EXPECT_MEDIA_LOG(VideoCodecLog("avc1.4D4028")); auto params = GetDefaultInitParametersExpectations(); params.detected_audio_track_count = 0; InitializeParserWithInitParametersExpectations(params); ParseMP4File("bear-1280x720-av_with-aud-nalus_frag.mp4", 512); } TEST_F(MP4StreamParserTest, HEVC_in_MP4_container) { #if BUILDFLAG(ENABLE_HEVC_DEMUXING) bool expect_success = true; EXPECT_MEDIA_LOG(VideoCodecLog("hevc")); #else bool expect_success = false; EXPECT_MEDIA_LOG(ErrorLog("Parse unsupported video format hev1")); #endif auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMicroseconds(1002000); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_audio_track_count = 0; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-hevc-frag.mp4"); EXPECT_EQ(expect_success, AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } // Sample encryption information is stored as CencSampleAuxiliaryDataFormat // (ISO/IEC 23001-7:2015 8) inside 'mdat' box. No SampleEncryption ('senc') box. TEST_F(MP4StreamParserTest, CencWithEncryptionInfoStoredAsAuxDataInMdat) { // Encrypted test mp4 files have non-zero duration and are treated as // recorded streams. auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMicroseconds(2736066); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_audio_track_count = 0; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-1280x720-v_frag-cenc.mp4"); EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } TEST_F(MP4StreamParserTest, CencWithSampleEncryptionBox) { // Encrypted test mp4 files have non-zero duration and are treated as // recorded streams. auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMicroseconds(2736066); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_audio_track_count = 0; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-640x360-v_frag-cenc-senc.mp4"); EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001E")); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } TEST_F(MP4StreamParserTest, NaturalSizeWithoutPASP) { auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMicroseconds(1000966); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_audio_track_count = 0; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-640x360-non_square_pixel-without_pasp.mp4"); EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001E")); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); EXPECT_EQ(gfx::Size(639, 360), video_decoder_config_.natural_size()); } TEST_F(MP4StreamParserTest, NaturalSizeWithPASP) { auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMicroseconds(1000966); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_audio_track_count = 0; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-640x360-non_square_pixel-with_pasp.mp4"); EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001E")); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); EXPECT_EQ(gfx::Size(639, 360), video_decoder_config_.natural_size()); } TEST_F(MP4StreamParserTest, DemuxingAC3) { std::set<int> audio_object_types; audio_object_types.insert(kAC3); parser_.reset(new MP4StreamParser(audio_object_types, false)); #if BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING) bool expect_success = true; #else bool expect_success = false; EXPECT_MEDIA_LOG(ErrorLog("Unsupported audio format 0x61632d33 in stsd box")); #endif auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMicroseconds(1045000); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_video_track_count = 0; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-ac3-only-frag.mp4"); EXPECT_EQ(expect_success, AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } TEST_F(MP4StreamParserTest, DemuxingEAC3) { std::set<int> audio_object_types; audio_object_types.insert(kEAC3); parser_.reset(new MP4StreamParser(audio_object_types, false)); #if BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING) bool expect_success = true; #else bool expect_success = false; EXPECT_MEDIA_LOG(ErrorLog("Unsupported audio format 0x65632d33 in stsd box")); #endif auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMicroseconds(1045000); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_video_track_count = 0; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-eac3-only-frag.mp4"); EXPECT_EQ(expect_success, AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } TEST_F(MP4StreamParserTest, FourCCToString) { // A real FOURCC should print. EXPECT_EQ("mvex", FourCCToString(FOURCC_MVEX)); // Invalid FOURCC should also print whenever ASCII values are printable. EXPECT_EQ("fake", FourCCToString(static_cast<FourCC>(0x66616b65))); // Invalid FORCC with non-printable values should not give error message. EXPECT_EQ("0x66616b00", FourCCToString(static_cast<FourCC>(0x66616b00))); } TEST_F(MP4StreamParserTest, MediaTrackInfoSourcing) { EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")); InitializeParser(); ParseMP4File("bear-1280x720-av_frag.mp4", 4096); EXPECT_EQ(media_tracks_->tracks().size(), 2u); const MediaTrack& video_track = *(media_tracks_->tracks()[0]); EXPECT_EQ(video_track.type(), MediaTrack::Video); EXPECT_EQ(video_track.bytestream_track_id(), 1); EXPECT_EQ(video_track.kind(), "main"); EXPECT_EQ(video_track.label(), "VideoHandler"); EXPECT_EQ(video_track.language(), "und"); const MediaTrack& audio_track = *(media_tracks_->tracks()[1]); EXPECT_EQ(audio_track.type(), MediaTrack::Audio); EXPECT_EQ(audio_track.bytestream_track_id(), 2); EXPECT_EQ(audio_track.kind(), "main"); EXPECT_EQ(audio_track.label(), "SoundHandler"); EXPECT_EQ(audio_track.language(), "und"); } TEST_F(MP4StreamParserTest, TextTrackDetection) { auto params = GetDefaultInitParametersExpectations(); params.detected_text_track_count = 1; InitializeParserWithInitParametersExpectations(params); scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile("bear-1280x720-avt_subt_frag.mp4"); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")); EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64001F")); EXPECT_TRUE(AppendDataInPieces(buffer->data(), buffer->data_size(), 512)); } TEST_F(MP4StreamParserTest, MultiTrackFile) { auto params = GetDefaultInitParametersExpectations(); params.duration = base::TimeDelta::FromMilliseconds(4248); params.liveness = DemuxerStream::LIVENESS_RECORDED; params.detected_audio_track_count = 2; params.detected_video_track_count = 2; InitializeParserWithInitParametersExpectations(params); EXPECT_MEDIA_LOG(VideoCodecLog("avc1.64000D")).Times(2); EXPECT_MEDIA_LOG(AudioCodecLog("mp4a.40.2")).Times(2); ParseMP4File("bbb-320x240-2video-2audio.mp4", 4096); EXPECT_EQ(media_tracks_->tracks().size(), 4u); const MediaTrack& video_track1 = *(media_tracks_->tracks()[0]); EXPECT_EQ(video_track1.type(), MediaTrack::Video); EXPECT_EQ(video_track1.bytestream_track_id(), 1); EXPECT_EQ(video_track1.kind(), "main"); EXPECT_EQ(video_track1.label(), "VideoHandler"); EXPECT_EQ(video_track1.language(), "und"); const MediaTrack& audio_track1 = *(media_tracks_->tracks()[1]); EXPECT_EQ(audio_track1.type(), MediaTrack::Audio); EXPECT_EQ(audio_track1.bytestream_track_id(), 2); EXPECT_EQ(audio_track1.kind(), "main"); EXPECT_EQ(audio_track1.label(), "SoundHandler"); EXPECT_EQ(audio_track1.language(), "und"); const MediaTrack& video_track2 = *(media_tracks_->tracks()[2]); EXPECT_EQ(video_track2.type(), MediaTrack::Video); EXPECT_EQ(video_track2.bytestream_track_id(), 3); EXPECT_EQ(video_track2.kind(), ""); EXPECT_EQ(video_track2.label(), "VideoHandler"); EXPECT_EQ(video_track2.language(), "und"); const MediaTrack& audio_track2 = *(media_tracks_->tracks()[3]); EXPECT_EQ(audio_track2.type(), MediaTrack::Audio); EXPECT_EQ(audio_track2.bytestream_track_id(), 4); EXPECT_EQ(audio_track2.kind(), ""); EXPECT_EQ(audio_track2.label(), "SoundHandler"); EXPECT_EQ(audio_track2.language(), "und"); } } // namespace mp4 } // namespace media
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
94598c38fdbf5bc9e8eabec4987a841b45b0a945
b7f22e51856f4989b970961f794f1c435f9b8f78
/src/library/kernel_serializer.cpp
1f9880ac3fb5f38022fe8e4af51d400fd9066b73
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
2021-01-21T00:01:24.081719
2015-12-22T06:45:37
2016-10-10T18:02:27
11,513,992
2
0
null
2014-06-03T02:38:22
2013-07-18T21:17:15
C++
UTF-8
C++
false
false
15,292
cpp
/* Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <string> #include "util/object_serializer.h" #include "kernel/expr.h" #include "kernel/declaration.h" #include "library/annotation.h" #include "library/max_sharing.h" #include "library/kernel_serializer.h" // Procedures for serializing and deserializing kernel objects (levels, exprs, declarations) namespace lean { // Universe level serialization class level_serializer : public object_serializer<level, level::ptr_hash, level::ptr_eq> { typedef object_serializer<level, level::ptr_hash, level::ptr_eq> super; public: void write(level const & l) { super::write(l, [&]() { serializer & s = get_owner(); auto k = kind(l); s << static_cast<char>(k); switch (k) { case level_kind::Zero: break; case level_kind::Param: s << param_id(l); break; case level_kind::Global: s << global_id(l); break; case level_kind::Meta: s << meta_id(l); break; case level_kind::Max: write(max_lhs(l)); write(max_rhs(l)); break; case level_kind::IMax: write(imax_lhs(l)); write(imax_rhs(l)); break; case level_kind::Succ: write(succ_of(l)); break; } }); } }; class level_deserializer : public object_deserializer<level> { typedef object_deserializer<level> super; public: level read() { return super::read([&]() -> level { deserializer & d = get_owner(); auto k = static_cast<level_kind>(d.read_char()); switch (k) { case level_kind::Zero: return mk_level_zero(); case level_kind::Param: return mk_param_univ(read_name(d)); case level_kind::Global: return mk_global_univ(read_name(d)); case level_kind::Meta: return mk_meta_univ(read_name(d)); case level_kind::Max: { level lhs = read(); return mk_max(lhs, read()); } case level_kind::IMax: { level lhs = read(); return mk_imax(lhs, read()); } case level_kind::Succ: return mk_succ(read()); } throw corrupted_stream_exception(); }); } }; struct level_sd { unsigned m_s_extid; unsigned m_d_extid; level_sd() { m_s_extid = serializer::register_extension([](){ return std::unique_ptr<serializer::extension>(new level_serializer()); }); m_d_extid = deserializer::register_extension([](){ return std::unique_ptr<deserializer::extension>(new level_deserializer()); }); } }; static level_sd * g_level_sd = nullptr; serializer & operator<<(serializer & s, level const & n) { s.get_extension<level_serializer>(g_level_sd->m_s_extid).write(n); return s; } level read_level(deserializer & d) { return d.get_extension<level_deserializer>(g_level_sd->m_d_extid).read(); } serializer & operator<<(serializer & s, levels const & ls) { return write_list<level>(s, ls); } levels read_levels(deserializer & d) { return read_list<level>(d, read_level); } // Expression serialization typedef std::unordered_map<std::string, macro_definition_cell::reader> macro_readers; static macro_readers * g_macro_readers = nullptr; macro_readers & get_macro_readers() { return *g_macro_readers; } void register_macro_deserializer(std::string const & k, macro_definition_cell::reader rd) { macro_readers & readers = get_macro_readers(); lean_assert(readers.find(k) == readers.end()); readers[k] = rd; } static expr read_macro_definition(deserializer & d, unsigned num, expr const * args) { auto k = d.read_string(); macro_readers & readers = get_macro_readers(); auto it = readers.find(k); lean_assert(it != readers.end()); return it->second(d, num, args); } serializer & operator<<(serializer & s, binder_info const & i) { unsigned w = (i.is_rec() ? 8 : 0) + (i.is_implicit() ? 4 : 0) + (i.is_strict_implicit() ? 2 : 0) + (i.is_inst_implicit() ? 1 : 0); s.write_char(w); return s; } static binder_info read_binder_info(deserializer & d) { unsigned w = d.read_char(); bool rec = (w & 8) != 0; bool imp = (w & 4) != 0; bool s_imp = (w & 2) != 0; bool i_imp = (w & 1) != 0; return binder_info(imp, s_imp, i_imp, rec); } static name * g_binder_name = nullptr; class expr_serializer : public object_serializer<expr, expr_hash_alloc, expr_eqp> { typedef object_serializer<expr, expr_hash_alloc, expr_eqp> super; max_sharing_fn m_max_sharing_fn; unsigned m_next_id; void write_binder_name(serializer & s, name const & a) { // make sure binding names are atomic string if (!a.is_atomic() || a.is_numeral()) { s << g_binder_name->append_after(m_next_id); m_next_id++; } else { s << a; } } void write_core(expr const & a) { auto k = a.kind(); super::write_core(a, static_cast<char>(k), [&]() { serializer & s = get_owner(); switch (k) { case expr_kind::Var: s << var_idx(a); break; case expr_kind::Constant: lean_assert(!const_name(a).is_anonymous()); s << const_name(a) << const_levels(a); break; case expr_kind::Sort: s << sort_level(a); break; case expr_kind::Macro: s << macro_num_args(a); for (unsigned i = 0; i < macro_num_args(a); i++) { write_core(macro_arg(a, i)); } macro_def(a).write(s); break; case expr_kind::App: write_core(app_fn(a)); write_core(app_arg(a)); break; case expr_kind::Lambda: case expr_kind::Pi: lean_assert(!binding_name(a).is_anonymous()); write_binder_name(s, binding_name(a)); s << binding_info(a); write_core(binding_domain(a)); write_core(binding_body(a)); break; case expr_kind::Let: s << let_name(a); write_core(let_type(a)); write_core(let_value(a)); write_core(let_body(a)); break; case expr_kind::Meta: lean_assert(!mlocal_name(a).is_anonymous()); s << mlocal_name(a); write_core(mlocal_type(a)); break; case expr_kind::Local: lean_assert(!mlocal_name(a).is_anonymous()); lean_assert(!local_pp_name(a).is_anonymous()); s << mlocal_name(a) << local_pp_name(a) << local_info(a); write_core(mlocal_type(a)); break; } }); } public: expr_serializer() { m_next_id = 0; } void write(expr const & a) { write_core(m_max_sharing_fn(a)); } }; class expr_deserializer : public object_deserializer<expr> { typedef object_deserializer<expr> super; public: expr read_binding(expr_kind k) { deserializer & d = get_owner(); name n = read_name(d); binder_info i = read_binder_info(d); expr t = read(); return mk_binding(k, n, t, read(), i); } expr read() { return super::read_core([&](char c) { deserializer & d = get_owner(); auto k = static_cast<expr_kind>(c); switch (k) { case expr_kind::Var: return mk_var(d.read_unsigned()); case expr_kind::Constant: { auto n = read_name(d); return mk_constant(n, read_levels(d)); } case expr_kind::Sort: return mk_sort(read_level(d)); case expr_kind::Macro: { unsigned n = d.read_unsigned(); buffer<expr> args; for (unsigned i = 0; i < n; i++) { args.push_back(read()); } return read_macro_definition(d, args.size(), args.data()); } case expr_kind::App: { expr f = read(); return mk_app(f, read()); } case expr_kind::Lambda: case expr_kind::Pi: return read_binding(k); case expr_kind::Let: { name n = read_name(d); expr t = read(); expr v = read(); return mk_let(n, t, v, read()); } case expr_kind::Meta: { name n = read_name(d); return mk_metavar(n, read()); } case expr_kind::Local: { name n = read_name(d); name pp_n = read_name(d); binder_info bi = read_binder_info(d); return mk_local(n, pp_n, read(), bi); }} throw corrupted_stream_exception(); // LCOV_EXCL_LINE }); } }; struct expr_sd { unsigned m_s_extid; unsigned m_d_extid; expr_sd() { m_s_extid = serializer::register_extension([](){ return std::unique_ptr<serializer::extension>(new expr_serializer()); }); m_d_extid = deserializer::register_extension([](){ return std::unique_ptr<deserializer::extension>(new expr_deserializer()); }); } }; static expr_sd * g_expr_sd = nullptr; serializer & operator<<(serializer & s, expr const & n) { s.get_extension<expr_serializer>(g_expr_sd->m_s_extid).write(n); return s; } expr read_expr(deserializer & d) { return d.get_extension<expr_deserializer>(g_expr_sd->m_d_extid).read(); } // Declaration serialization serializer & operator<<(serializer & s, level_param_names const & ps) { return write_list<name>(s, ps); } level_param_names read_level_params(deserializer & d) { return read_list<name>(d); } serializer & operator<<(serializer & s, declaration const & d) { char k = 0; if (d.is_definition()) { k |= 1; if (d.use_conv_opt()) k |= 2; } if (d.is_theorem() || d.is_axiom()) k |= 4; s << k << d.get_name() << d.get_univ_params() << d.get_type(); if (d.is_definition()) { s << d.get_value(); s << d.get_height(); } return s; } declaration read_declaration(deserializer & d) { char k = d.read_char(); bool has_value = (k & 1) != 0; bool is_th_ax = (k & 4) != 0; name n = read_name(d); level_param_names ps = read_level_params(d); expr t = read_expr(d); if (has_value) { expr v = read_expr(d); unsigned w = d.read_unsigned(); if (is_th_ax) { return mk_theorem(n, ps, t, v, w); } else { bool use_conv_opt = (k & 2) != 0; return mk_definition(n, ps, t, v, w, use_conv_opt); } } else { if (is_th_ax) return mk_axiom(n, ps, t); else return mk_constant_assumption(n, ps, t); } } using inductive::certified_inductive_decl; using inductive::inductive_decl; using inductive::intro_rule; using inductive::inductive_decl_name; using inductive::inductive_decl_type; using inductive::inductive_decl_intros; using inductive::intro_rule_name; using inductive::intro_rule_type; serializer & operator<<(serializer & s, certified_inductive_decl::comp_rule const & r) { s << r.m_num_bu << r.m_comp_rhs; return s; } certified_inductive_decl::comp_rule read_comp_rule(deserializer & d) { unsigned n; expr e; d >> n >> e; return certified_inductive_decl::comp_rule(n, e); } serializer & operator<<(serializer & s, inductive_decl const & d) { s << inductive_decl_name(d) << inductive_decl_type(d) << length(inductive_decl_intros(d)); for (intro_rule const & r : inductive_decl_intros(d)) s << intro_rule_name(r) << intro_rule_type(r); return s; } inductive_decl read_inductive_decl(deserializer & d) { name d_name = read_name(d); expr d_type = read_expr(d); unsigned num_intros = d.read_unsigned(); buffer<intro_rule> rules; for (unsigned j = 0; j < num_intros; j++) { name r_name = read_name(d); expr r_type = read_expr(d); rules.push_back(inductive::mk_intro_rule(r_name, r_type)); } return inductive_decl(d_name, d_type, to_list(rules.begin(), rules.end())); } serializer & operator<<(serializer & s, certified_inductive_decl::data const & d) { s << d.m_decl << d.m_K_target << d.m_num_indices; write_list<certified_inductive_decl::comp_rule>(s, d.m_comp_rules); return s; } certified_inductive_decl::data read_certified_inductive_decl_data(deserializer & d) { inductive_decl decl = read_inductive_decl(d); bool K = d.read_bool(); unsigned nind = d.read_unsigned(); auto rs = read_list<certified_inductive_decl::comp_rule>(d, read_comp_rule); return certified_inductive_decl::data(decl, K, nind, rs); } serializer & operator<<(serializer & s, certified_inductive_decl const & d) { s << d.get_univ_params() << d.get_num_params() << d.get_num_ACe() << d.elim_prop_only() << d.has_dep_elim(); write_list<expr>(s, d.get_elim_types()); write_list<certified_inductive_decl::data>(s, d.get_decl_data()); return s; } class read_certified_inductive_decl_fn { public: certified_inductive_decl operator()(deserializer & d) { level_param_names ls = read_list<name>(d, read_name); unsigned nparams = d.read_unsigned(); unsigned nACe = d.read_unsigned(); bool elim_prop = d.read_bool(); bool dep_elim = d.read_bool(); list<expr> ets = read_list<expr>(d, read_expr); auto ds = read_list<certified_inductive_decl::data>(d, read_certified_inductive_decl_data); return certified_inductive_decl(ls, nparams, nACe, elim_prop, dep_elim, ets, ds); } }; certified_inductive_decl read_certified_inductive_decl(deserializer & d) { return read_certified_inductive_decl_fn()(d); } void initialize_kernel_serializer() { g_level_sd = new level_sd(); g_macro_readers = new macro_readers(); g_binder_name = new name("a"); g_expr_sd = new expr_sd(); } void finalize_kernel_serializer() { delete g_expr_sd; delete g_binder_name; delete g_macro_readers; delete g_level_sd; } }
[ "leonardo@microsoft.com" ]
leonardo@microsoft.com
94056f408497ba1fc66ed12ccdb3cd06aac5e9cf
f0d560c9bb443e24a707347ac498d386d9b274e3
/scene.h
aabe6ba59bc393a7d54312ddbf903e7749f6774c
[]
no_license
seamanj/ARAP
e5d7d4166b517fde92965e3a972f12908cbe3e6a
3a5b1b19a912ff9260ef1d88972bedf860566e0f
refs/heads/master
2020-05-02T22:12:34.374982
2019-06-08T13:37:10
2019-06-08T13:37:10
178,244,972
5
1
null
null
null
null
UTF-8
C++
false
false
810
h
#ifndef SCENE_H #define SCENE_H #include "scenenode.h" #include "scenenodeiterator.h" #include <QObject> class Scene : public QObject { Q_OBJECT public: Scene(); virtual ~Scene(); virtual void render(); SceneNode* root() { return m_root; } SceneNodeIterator begin() const; void loadMesh(const QString &filename, glm::mat4 CTM=glm::mat4()); void reset(); void deleteSelectedNodes(); void deleteSelectedMeshes(); void roiSelectedParticles(); void deroiSelectedParticles(); void controlSelectedParticles(); void decontrolSelectedParticles(); void selectPriorGroup(); void selectNextGroup(); void clearSelection(); signals: void updateTool(); private: SceneNode* m_root; void setupLights(); }; #endif // SCENE_H
[ "tjiang.work@gmail.com" ]
tjiang.work@gmail.com
bde8c42c31a8d046b7e260cb2d0f507fb1880669
239f22dcc4b79d7afb86796bee42128025ec5aae
/trainingthread.cpp
e8339823d2f772b7142548a8685eb4d545b27119
[ "LicenseRef-scancode-public-domain" ]
permissive
2php/ConvolutionalNeuralNetworkDemo
aef1dd4f616f3287fc3e0cad713b9b67fbabfe04
13331cfa8888dc28d5f5b55322eb1c21ee45c571
refs/heads/master
2021-01-21T03:38:37.649203
2016-07-19T14:40:06
2016-07-19T14:40:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,703
cpp
#include "trainingthread.h" TrainingThread::TrainingThread(MainWindow *_window, double _learningRate, double _momentum, double _weightDecay) { stopRequested=false; window=_window; mutex=new QMutex(); learningRate=_learningRate; momentum=_momentum; weightDecay=_weightDecay; } TrainingThread::~TrainingThread() { mutex->unlock(); delete mutex; } void TrainingThread::run() { srand(time(0)); for(/*;;*/uint64_t cycle=0;cycle<100000000;cycle++) { if(stopRequested) break; uint32_t imageId=((double)rand())/((double)RAND_MAX)*IMAGES_PER_BATCH*BATCH_COUNT; uint8_t imageLabel=window->imageLabels[imageId]; //forwardPass(imageId); // Input for first layer: Image data double ***previousLayerOutput=window->imageInputData[imageId]; // Forward pass // MODIFY IN MAINWINDOW.CPP, TOO! for(uint32_t layerIndex=0;layerIndex<LAYER_COUNT;layerIndex++) { CNNLayer *thisLayer=window->layers[layerIndex]; double ***output=thisLayer->forwardPass(previousLayerOutput); if(layerIndex>0) CNNLayer::freeArray(previousLayerOutput,thisLayer->previousLayerFeatureMapCount,thisLayer->previousLayerSingleFeatureMapHeight); previousLayerOutput=output; } // previousLayerOutput now contains the output of the last layer // Backward pass double ***higherLayerInputDiffs=0; for(uint32_t _layerIndex=LAYER_COUNT;_layerIndex>0;_layerIndex--) // _layerIndex is of type uint32_t and cannot be <0, therefore we have to artificially increment it by 1 { uint32_t layerIndex=_layerIndex-1; // The actual index of this layer CNNLayer *thisLayer=window->layers[layerIndex]; CNNLayer *higherLayer=layerIndex<LAYER_COUNT-1?window->layers[layerIndex+1]:0; double ***inputDiffs=0; double ****weightDiffs=0; double *biasDiffs=0; // Error in calculateDiffs (tested) thisLayer->calculateDiffs(weightDiffs,biasDiffs,higherLayerInputDiffs,inputDiffs,imageLabel); thisLayer->applyDiffs(weightDiffs,biasDiffs,learningRate,momentum,weightDecay); if(weightDiffs!=0) { if(thisLayer->type==CNN_LAYER_TYPE_CONV) CNNLayer::freeWeightTypeArray(weightDiffs,thisLayer->previousLayerFeatureMapCount,thisLayer->featureMapCount,thisLayer->receptiveFieldHeight,thisLayer->receptiveFieldWidth); else if(thisLayer->type==CNN_LAYER_TYPE_FC) CNNLayer::freeWeightTypeArray(weightDiffs,thisLayer->previousLayerFeatureMapCount,thisLayer->previousLayerSingleFeatureMapHeight,thisLayer->previousLayerSingleFeatureMapWidth,thisLayer->featureMapCount); } if(biasDiffs!=0) CNNLayer::freeBiasTypeArray(biasDiffs); if(layerIndex<LAYER_COUNT-1) CNNLayer::freeArray(higherLayerInputDiffs,higherLayer->previousLayerFeatureMapCount,higherLayer->previousLayerSingleFeatureMapHeight); higherLayerInputDiffs=inputDiffs; // Will be freed when processing the next layer } if(higherLayerInputDiffs!=window->desiredOutputValueCache[imageLabel]&&higherLayerInputDiffs!=0) CNNLayer::freeArray(higherLayerInputDiffs,window->layers[0]->previousLayerFeatureMapCount,window->layers[0]->previousLayerSingleFeatureMapHeight); // previousLayerOutput now contains the output of the last layer iterationFinished(imageId,previousLayerOutput); } stopRequested=false; window->training=false; }
[ "a.niedental@outlook.com" ]
a.niedental@outlook.com
ba12f11349c9275c670c072561987c8dbc469656
e53074d668e8eea241e2afa5aa42890bedb78cd9
/Project1/Project1/Source/Engine/GraphicsSystem/Description/CommandQueueDesc.h
5581c2dab347b8348fbe1bbcd4b1c8b53fe8b249
[]
no_license
ReU1107/Project1
9f1e2ab128744c321f56219679cdb2a33072dd9f
dfae75c51981c29a5a578b1e754524476d1a6809
refs/heads/master
2020-12-26T19:13:20.864694
2020-10-29T11:51:13
2020-10-29T11:51:13
237,610,628
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
293
h
#pragma once #include <cstdint> namespace Engine { namespace GraphicsSystem { enum class CommandQueuePriority : uint8_t; enum class CommandListType : uint8_t; struct CommandQueueDesc { CommandListType type; // タイプ CommandQueuePriority priority; // 優先度 }; } }
[ "reu1107@yahoo.co.jp" ]
reu1107@yahoo.co.jp
d204cabbbdb0d57be2b53ac4a1251e24f1b58838
b4c2ea1c4edc0b635ecde4f353a0ab390050f6fc
/src/trading-bot/server/if.h
a946ba9f14e0d4bf5e8db422e5d636d7eba6a6dd
[ "ISC", "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
KenYuan1987/Krypto-trading-bot
ab5adf0a103d8ad669d90d45d27414defbd564cc
e88cd71a978f2c5db32cb6cabe49aa6af3736b93
refs/heads/master
2020-03-29T01:50:31.027125
2018-09-18T23:28:11
2018-09-18T23:28:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,808
h
#ifndef K_IF_H_ #define K_IF_H_ namespace K { class Screen { public: virtual void pressme(const mHotkey&, function<void()>) = 0; virtual void printme(mToScreen *const) = 0; virtual void waitForUser() = 0; virtual const int error(const string&, const string&, const bool& = false) = 0; virtual const string stamp() = 0; virtual void logWar(string, string, string = " Warrrrning: ") = 0; virtual void logUI(const string&) = 0; virtual void logUIsess(int, string) = 0; virtual void log(const string&, const string&, const string& = "") = 0; virtual void switchOff() = 0; } *screen = nullptr; class Events { public: virtual void deferred(const function<void()>&) = 0; } *events = nullptr; class Sqlite { public: virtual void backup(mFromDb *const) = 0; } *sqlite = nullptr; class Client { public: uWS::Hub* socket = nullptr; virtual void timer_Xs() = 0; virtual void welcome(mToClient&) = 0; virtual void clickme(mFromClient&, function<void(const json&)>) = 0; } *client = nullptr; class Engine { #define SQLITE_BACKUP \ SQLITE_BACKUP_LIST \ ( SQLITE_BACKUP_CODE ) #define SQLITE_BACKUP_CODE(data) sqlite->backup(&data); #define SQLITE_BACKUP_LIST(code) \ code( qp ) \ code( wallet.target ) \ code( wallet.safety.trades ) \ code( wallet.profits ) \ code( levels.stats.ewma.fairValue96h ) \ code( levels.stats.ewma ) \ code( levels.stats.stdev ) #define SCREEN_PRINTME \ SCREEN_PRINTME_LIST \ ( SCREEN_PRINTME_CODE ) #define SCREEN_PRINTME_CODE(data) screen->printme(&data); #define SCREEN_PRINTME_LIST(code) \ code( *gw ) \ code( orders ) \ code( wallet.target ) \ code( wallet.safety.trades ) \ code( levels.stats.fairPrice ) \ code( levels.stats.ewma ) \ code( broker.semaphore ) \ code( broker.calculon.quotes ) \ code( broker.calculon.dummyMM ) #define SCREEN_PRESSME \ SCREEN_PRESSME_LIST \ ( SCREEN_PRESSME_CODE ) #define SCREEN_PRESSME_CODE(key, fn) screen->pressme(mHotkey::key, [&]() { fn(); }); #define SCREEN_PRESSME_LIST(code) \ code( Q , gw->quit ) \ code( q , gw->quit ) \ code( ESC , broker.semaphore.toggle ) #define CLIENT_WELCOME \ CLIENT_WELCOME_LIST \ ( CLIENT_WELCOME_CODE ) #define CLIENT_WELCOME_CODE(data) client->welcome(data); #define CLIENT_WELCOME_LIST(code) \ code( qp ) \ code( monitor ) \ code( monitor.product ) \ code( orders ) \ code( wallet.target ) \ code( wallet.safety ) \ code( wallet.safety.trades ) \ code( wallet ) \ code( levels.diff ) \ code( levels.stats.takerTrades ) \ code( levels.stats.fairPrice ) \ code( levels.stats ) \ code( broker.semaphore ) \ code( broker.calculon ) \ code( btn.notepad ) #define CLIENT_CLICKME \ CLIENT_CLICKME_LIST \ ( CLIENT_CLICKME_CODE ) #define CLIENT_CLICKME_CODE(btn, fn, val) \ client->clickme(btn, [&](const json &butterfly) { fn(val); }); #define CLIENT_CLICKME_LIST(code) \ code( qp , savedQuotingParameters , ) \ code( broker.semaphore , void , ) \ code( btn.notepad , void , ) \ code( btn.submit , manualSendOrder , butterfly ) \ code( btn.cancel , manualCancelOrder , butterfly ) \ code( btn.cancelAll , cancelOrders , ) \ code( btn.cleanTrade , wallet.safety.trades.clearOne , butterfly ) \ code( btn.cleanTradesClosed , wallet.safety.trades.clearClosed , ) \ code( btn.cleanTrades , wallet.safety.trades.clearAll , ) public: mButtons btn; mMonitor monitor; mOrders orders; mMarketLevels levels; mWalletPosition wallet; mBroker broker; Engine() : levels(orders, monitor.product) , wallet(orders, levels.stats.ewma.targetPositionAutoPercentage, levels.fairValue) , broker(orders, monitor.product, levels, wallet) {}; void savedQuotingParameters() { broker.calculon.dummyMM.mode("saved"); levels.stats.ewma.calcFromHistory(); }; void timer_1s(const unsigned int &tick) { if (levels.warn_empty()) return; levels.timer_1s(); if (!(tick % 60)) { levels.timer_60s(); monitor.timer_60s(); } wallet.safety.timer_1s(); calcQuotes(); }; void calcQuotes() { if (broker.ready() and levels.ready() and wallet.ready()) { if (broker.calcQuotes()) { quote2orders(broker.calculon.quotes.ask); quote2orders(broker.calculon.quotes.bid); } else cancelOrders(); } broker.clear(); }; void quote2orders(mQuote &quote) { const vector<mOrder*> abandoned = broker.abandon(quote); const bool replace = gw->askForReplace and !(quote.empty() or abandoned.empty()); for_each( abandoned.begin(), abandoned.end() - (replace ? 1 : 0), [&](mOrder *const it) { cancelOrder(it); } ); if (quote.empty()) return; if (replace) replaceOrder(quote.price, quote.isPong, abandoned.back()); else placeOrder(mOrder( gw->randId(), quote.side, quote.price, quote.size, quote.isPong )); monitor.tick_orders(); }; void cancelOrders() { for (mOrder *const it : orders.working()) cancelOrder(it); }; void manualSendOrder(mOrder raw) { raw.orderId = gw->randId(); placeOrder(raw); }; void manualCancelOrder(const mRandId &orderId) { cancelOrder(orders.find(orderId)); }; private: void placeOrder(const mOrder &raw) { gw->place(orders.upsert(raw)); }; void replaceOrder(const mPrice &price, const bool &isPong, mOrder *const order) { if (orders.replace(price, isPong, order)) gw->replace(order); }; void cancelOrder(mOrder *const order) { if (orders.cancel(order)) gw->cancel(order); }; } *engine = nullptr; } #endif
[ "ctubio@users.noreply.github.com" ]
ctubio@users.noreply.github.com
1ed3c7a4038fd2644b65bbfe9c83598e55c993af
677ee07ddf148ccb7de362ca6e4f55e56ba77171
/FrogPlay/RealWndDlg_URL.h
2f5324fdd67b8279d2c6cfbd79cef3daa32b2e10
[ "MIT" ]
permissive
zhuyanbing/SouiDemo
126d0c00af4ec13fb0d4e8ebc7c5399997ad7be2
09b0151a81e5d1552b05938b7aede0f7a9617cc4
refs/heads/master
2020-03-30T05:38:09.272310
2018-06-30T11:44:17
2018-06-30T11:44:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
915
h
#pragma once #include "MainDlg.h" class CRealWndDlg_URL : public SHostWnd { public: CRealWndDlg_URL():SHostWnd(_T("LAYOUT:XML_Readwnd_url")) {} ~CRealWndDlg_URL(void){} void On_Open_URLBtn() { SEdit *m_URL_text = FindChildByID2<SEdit>(8001); if (m_URL_text) { if (m_URL_text->GetWindowTextW().IsEmpty()) { CRect rc = m_URL_text->GetWindowRect(); ClientToScreen(&rc); CTipWnd::ShowTip(rc.right, rc.top, CTipWnd::AT_LEFT_BOTTOM, _T("地址错误!\\n地址为空,无法解析")); return; } ::SendMessageW(SApplication::getSingleton().GetMainWnd(), MS_REALWND_URLPLAY, 0, (LPARAM)(LPCTSTR)m_URL_text->GetWindowTextW()); } } protected: //soui消息 EVENT_MAP_BEGIN() EVENT_ID_COMMAND(8000, On_Open_URLBtn) EVENT_MAP_END() //消息映射表 BEGIN_MSG_MAP_EX(CRealWndDlg_URL) CHAIN_MSG_MAP(SHostWnd) REFLECT_NOTIFICATIONS_EX() END_MSG_MAP() private: };
[ "kklvzl@gmail.com" ]
kklvzl@gmail.com
ab729b4774b1911158b0aa98e06ab772de0a6519
a6d934968dca366bde7e3d41c05acfcb3606afad
/misc/seaVote.cpp
1aac7fc77ef39edd1132403a5cfe76ebaae1912a
[]
no_license
nishant-nimbare/cp
ec392e643973f57946601aca5b9bcb6ffe5e8c8e
55107bede1d6f9bb958c7c0c7da6b9319c8f2dc3
refs/heads/master
2022-04-30T15:46:04.549480
2022-03-12T15:51:03
2022-03-12T15:51:03
229,908,243
1
0
null
null
null
null
UTF-8
C++
false
false
869
cpp
// https://www.codechef.com/problems/SEAVOTE #include <iostream> #include <bits/stdc++.h> #include <vector> #include <fstream> using namespace std; // inputs // 3 // 3 // 30 30 30 // 4 // 25 25 25 25 // 2 // 50 51 int main(int argc, char const *argv[]) { int t; std::fstream myfile("./input.txt", std::ios_base::in); myfile>> t; while(t--){ int n,total=0; myfile >> n; int num = n; while(n--){ int a; myfile >>a; total += a; if(a == 0) num--; } cout<<"total "<<total<<endl; if(total < 100){ cout<<"NO"<<endl; continue; } if(total == 100){ cout<<"YES"<<endl; continue; } if(total > 100){ // cout<<"total >100 "<<total<<" n "<<num<<endl; if(total<num+100){ // cout<<"total >100 "<<total-100<<endl; cout<<"YES"<<endl; }else{ cout<<"NO"<<endl; } } } return 0; }
[ "nishantnimbare@gmail.com" ]
nishantnimbare@gmail.com
776ab2430ecd1f3fae9dd34cc260b032c47ecae1
e4cbfd0f27e1ceda8a87d68d9c2e33c27438bb47
/Hello World!.cpp
702f1e09d01e87a872efa16c0bb91233fcd45357
[]
no_license
comajor/comajor
8e680533b9e8e12644987636e19dc89534a88f05
8b2245d46b9b05ade174ac98e89b33e4fa652353
refs/heads/master
2021-09-06T04:56:05.693334
2018-02-02T14:14:52
2018-02-02T14:14:52
113,677,114
0
0
null
null
null
null
UTF-8
C++
false
false
75
cpp
#include <stdio.h> int main(){ printf("Hello world!"); return 0; }
[ "noreply@github.com" ]
comajor.noreply@github.com
1c306778e44d9a6cfa9a9d27954a5b91a57ca770
8d0b9126c6a6002ef3d228e024f7b5bd4742aaad
/hammerblade/torch/kernel/kernel_conv.cpp
59ed857fe518cfaa6ee0fb5d50c0d0c7b076fdf1
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
mchao409/hb-pytorch
f667b3857b3d7ed7c40ac7c985fd9700a61da3c1
3c28bb5b3d79e51a719e523fbe108fdd1915d3cd
refs/heads/master
2021-05-23T11:07:24.432230
2020-05-26T01:45:20
2020-05-26T01:45:22
253,257,752
0
0
NOASSERTION
2020-04-05T14:45:09
2020-04-05T14:45:09
null
UTF-8
C++
false
false
8,884
cpp
//==================================================================== // Convolution kernel // 03/08/2020 Bandhav Veluri //==================================================================== #include <kernel_common.hpp> // We wrap all external-facing C++ kernels with `extern "C"` to // prevent name mangling extern "C" { __attribute__ ((noinline)) int tensorlib_convolution_forward( hb_tensor_t* output, hb_tensor_t* input, hb_tensor_t* weight, hb_vector_t* padding, hb_vector_t* strides) { auto y = HBTensor<float>(output); auto x = HBTensor<float>(input); auto w = HBTensor<float>(weight); auto p = HBVector<uint32_t>(padding); auto s = HBVector<uint32_t>(strides); // Conv2d parameters auto N = y.dim(0); // number of minibatches auto Cout = y.dim(1); // number of output channels auto Hout = y.dim(2); auto Wout = y.dim(3); auto Cin = x.dim(1); // number of input channels auto Hin = x.dim(2); auto Win = x.dim(3); auto Kh = w.dim(2); auto Kw = w.dim(3); auto Sh = s[0]; auto Sw = s[1]; auto Ph = p[0]; auto Pw = p[1]; // Start profiling bsg_cuda_print_stat_kernel_start(); // Preliminary single tile implementation // // Grows O(^5) with image size: // N x Cout x Cin x H x W // Kernel loops are constant-time if(__bsg_id == 0) { for(uint32_t n = 0; n < N; ++n) for(uint32_t co = 0; co < Cout; ++co) for(uint32_t yh = 0; yh < Hout; ++yh) for(uint32_t yw = 0; yw < Wout; ++yw) for(uint32_t ci = 0; ci < Cin; ++ci) for(uint32_t kh = 0; kh < Kh; ++kh) for(uint32_t kw = 0; kw < Kw; ++kw) { if((ci + kh + kw) == 0) { y(n, co, yh, yw) = 0.0; } int32_t xh = Sh * yh - Ph + kh; int32_t xw = Sw * yw - Pw + kw; if(xh >= 0 && xh < Hin && xw >= 0 && xw < Win) { y(n, co, yh, yw) += x(n, ci, xh, xw) * w(co, ci, kh, kw); } // else 0 } } // End profiling bsg_cuda_print_stat_kernel_end(); return 0; } __attribute__ ((noinline)) int tensorlib_convolution_add_bias( hb_tensor_t* output, hb_tensor_t* bias) { auto y = (float*) ((intptr_t) output->data); auto y_strides = (uint32_t*) ((intptr_t) output->strides); auto b = (float*) ((intptr_t) bias->data); auto N = output->N; // total number of elements in the output auto out_ch_stride = y_strides[1]; // output channel stride auto nb = bias->N; // number of elements in the bias // Calculate elements per tile uint32_t len_per_tile = N / (bsg_tiles_X * bsg_tiles_Y) + 1; uint32_t start = len_per_tile * __bsg_id; uint32_t end = start + len_per_tile; end = (end > N) ? N : end; // Start profiling bsg_cuda_print_stat_kernel_start(); for(int i = start; i < end; ++i) { float bias = b[(i / out_ch_stride) % nb]; y[i] += bias; } // End profiling bsg_cuda_print_stat_kernel_end(); return 0; } __attribute__ ((noinline)) int tensorlib_convolution_backward_input( hb_tensor_t* grad_input, hb_tensor_t* grad_output, hb_tensor_t* weight, hb_vector_t* padding, hb_vector_t* strides) { auto x = HBTensor<float>(grad_input); auto y = HBTensor<float>(grad_output); auto w = HBTensor<float>(weight); auto p = HBVector<uint32_t>(padding); auto s = HBVector<uint32_t>(strides); // Conv2d parameters auto N = y.dim(0); // number of minibatches auto Cout = y.dim(1); // number of output channels auto Hout = y.dim(2); auto Wout = y.dim(3); auto Cin = x.dim(1); // number of input channels auto Hin = x.dim(2); auto Win = x.dim(3); auto Kh = w.dim(2); auto Kw = w.dim(3); auto Sh = s[0]; auto Sw = s[1]; auto Ph = p[0]; auto Pw = p[1]; // Start profiling bsg_cuda_print_stat_kernel_start(); // Preliminary single tile implementation // // Grows O(^5) with image size: // N x Cout x Cin x H x W // Kernel loops are constant-time if(__bsg_id == 0) { // init input grads for(uint32_t n = 0; n < N; ++n) for(uint32_t ci = 0; ci < Cin; ++ci) for(uint32_t xh = 0; xh < Hin; ++xh) for(uint32_t xw = 0; xw < Win; ++xw) x(n, ci, xh, xw) = 0.0; for(uint32_t n = 0; n < N; ++n) for(uint32_t co = 0; co < Cout; ++co) for(uint32_t yh = 0; yh < Hout; ++yh) for(uint32_t yw = 0; yw < Wout; ++yw) for(uint32_t ci = 0; ci < Cin; ++ci) for(uint32_t kh = 0; kh < Kh; ++kh) for(uint32_t kw = 0; kw < Kw; ++kw) { int32_t xh = Sh * yh - Ph + kh; int32_t xw = Sw * yw - Pw + kw; if(xh >= 0 && xh < Hin && xw >= 0 && xw < Win) { x(n, ci, xh, xw) += y(n, co, yh, yw) * w(co, ci, kh, kw); } // else 0 } } // End profiling bsg_cuda_print_stat_kernel_end(); return 0; } __attribute__ ((noinline)) int tensorlib_convolution_backward_weight( hb_tensor_t* grad_weight, hb_tensor_t* grad_output, hb_tensor_t* input, hb_vector_t* padding, hb_vector_t* strides) { auto x = HBTensor<float>(input); auto y = HBTensor<float>(grad_output); auto w = HBTensor<float>(grad_weight); auto p = HBVector<uint32_t>(padding); auto s = HBVector<uint32_t>(strides); // Conv2d parameters auto N = y.dim(0); // number of minibatches auto Cout = y.dim(1); // number of output channels auto Hout = y.dim(2); auto Wout = y.dim(3); auto Cin = x.dim(1); // number of input channels auto Hin = x.dim(2); auto Win = x.dim(3); auto Kh = w.dim(2); auto Kw = w.dim(3); auto Sh = s[0]; auto Sw = s[1]; auto Ph = p[0]; auto Pw = p[1]; // Start profiling bsg_cuda_print_stat_kernel_start(); // Preliminary single tile implementation // // Grows O(^5) with image size: // N x Cout x Cin x H x W // Kernel loops are constant-time if(__bsg_id == 0) { // init weight grad for(uint32_t ci = 0; ci < Cin; ++ci) for(uint32_t co = 0; co < Cout; ++co) for(uint32_t kh = 0; kh < Kh; ++kh) for(uint32_t kw = 0; kw < Kw; ++kw) w(co, ci, kh, kw) = 0.0f; for(uint32_t n = 0; n < N; ++n) for(uint32_t co = 0; co < Cout; ++co) for(uint32_t yh = 0; yh < Hout; ++yh) for(uint32_t yw = 0; yw < Wout; ++yw) for(uint32_t ci = 0; ci < Cin; ++ci) for(uint32_t kh = 0; kh < Kh; ++kh) for(uint32_t kw = 0; kw < Kw; ++kw) { int32_t xh = Sh * yh - Ph + kh; int32_t xw = Sw * yw - Pw + kw; if(xh >= 0 && xh < Hin && xw >= 0 && xw < Win) { w(co, ci, kh, kw) += y(n, co, yh, yw) * x(n, ci, xh, xw); } // else 0 } } // End profiling bsg_cuda_print_stat_kernel_end(); return 0; } __attribute__ ((noinline)) int tensorlib_convolution_backward_bias( hb_tensor_t* grad_bias, hb_tensor_t* grad_output) { auto gb = HBTensor<float>(grad_bias); auto y = HBTensor<float>(grad_output); auto N = y.dim(0); // number of minibatches auto Cout = y.dim(1); // number of output channels auto Hout = y.dim(2); auto Wout = y.dim(3); // Start profiling bsg_cuda_print_stat_kernel_start(); if(__bsg_id == 0) { for(uint32_t n = 0; n < N; ++n) for(uint32_t co = 0; co < Cout; ++co) for(uint32_t yh = 0; yh < Hout; ++yh) for(uint32_t yw = 0; yw < Wout; ++yw) { if((n + yh + yw) == 0) gb(co) = 0.0f; gb(co) += y(n, co, yh, yw); } } // End profiling bsg_cuda_print_stat_kernel_end(); return 0; } HB_EMUL_REG_KERNEL(tensorlib_convolution_forward, hb_tensor_t*, hb_tensor_t*, hb_tensor_t*, hb_vector_t*, hb_vector_t*); HB_EMUL_REG_KERNEL(tensorlib_convolution_add_bias, hb_tensor_t*, hb_tensor_t*); HB_EMUL_REG_KERNEL(tensorlib_convolution_backward_input, hb_tensor_t*, hb_tensor_t*, hb_tensor_t*, hb_vector_t*, hb_vector_t*); HB_EMUL_REG_KERNEL(tensorlib_convolution_backward_weight, hb_tensor_t*, hb_tensor_t*, hb_tensor_t*, hb_vector_t*, hb_vector_t*); HB_EMUL_REG_KERNEL(tensorlib_convolution_backward_bias, hb_tensor_t*, hb_tensor_t*); }
[ "bandhav.veluri00@gmail.com" ]
bandhav.veluri00@gmail.com
b5cc33a1a4978fab006e31d404737d57aa3df27b
f7c673d103a0a7261246dbdde75490f8eed918ab
/source/Client/old/source/editor/subscene/GroupedTilePreview.cpp
19e92d3295b86e9cde70642a62ed2b38b65a17ca
[]
no_license
phisn/PixelJumper2
2c69faf83c09136b81befd7a930c19ea0ab521f6
842878cb3e44113cc2753abe889de62921242266
refs/heads/master
2022-11-14T04:44:00.690120
2020-07-06T09:38:38
2020-07-06T09:38:38
277,490,158
0
0
null
2020-07-06T09:38:42
2020-07-06T08:48:52
C++
UTF-8
C++
false
false
32
cpp
#include "GroupedTilePreview.h"
[ "phisn@outlook.de" ]
phisn@outlook.de
b2a0eca102dc1f4f33334c695f9c37401a4c3fe2
f001a867881a910f09b30b924d88897a4ba51799
/STFT/stft_src/invSTFT.hpp
8f9b86e3f3ff49f93b60eeb7e454c2c6a3eb3e31
[]
no_license
tachi-hi/timefreq
9cce9e1e7bf572900f33a3cab7e8d76e266ee8c2
98d6d3f1b9d3e1f9ce787a17cc4e31f6ce071fa0
refs/heads/master
2016-09-15T14:47:58.760843
2016-05-15T17:36:43
2016-05-15T17:36:43
4,710,764
5
0
null
2016-05-15T17:36:43
2012-06-19T07:35:57
C++
UTF-8
C++
false
false
368
hpp
#pragma once #include<vector> #include<complex> #include"twoDimArray.h" //inv stft void invSTFT( const twoDimArray<double>& abs, const twoDimArray<std::complex<double> >& phase, std::vector<double>* output, int frame, int shift, double(*win)(int, int) ); // Normalize signal void normalization(std::vector<double>* signal1, std::vector<double>* signal2);
[ "tachi-hi@users.noreply.github.com" ]
tachi-hi@users.noreply.github.com
9eeac77a900e9bac8838f010d6d4fb70a015e4cb
bd3bcdce42c9e28364bfcc0615c4955a41fc7c1a
/vfd_demo/vfd_demo.ino
782e8254a5f6d9417d60a33e8a5bfdfc3cdfbf1f
[]
no_license
DevSeq/hp-VFD
8a91f34ded77dc3d56cf11b47ab0f12adbb55840
238c058adb41148dacef9c56b1bff8214108f65b
refs/heads/master
2021-05-26T18:51:44.576644
2013-06-27T11:45:14
2013-06-27T11:45:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,010
ino
/* M66004Vfd and HpLaserJetControl libraries - Demo Demonstrates the use a control/display panel from a HP LaserJet 4 printer. This sketch: * Sets all pixels and flashes the LEDs for approximately 1 second. * Prints "Hello, world!" to the display and flahses a heart beat. * Sets LEDs on/off based on button presses. Not all models of printer have the same pinout. For the model tested, the 10 pin dual row connector was connected as follows: * Pins 1, 2 and/or 3 connected to Arduino ground. * Pins 4 and/or 5 connected to Arduino +5V. * Pins 6 through 10 connected to Arduino pins 6 through 10 respectively. Originally created 21 March 2011 This example code is in the public domain. http://arduino.cc/playground/Main/M66004Vfd */ #include <M66004Vfd.h> // VFD library. #include <HpLaserJetControl.h> // Button and LED library. M66004Vfd vfd(8, 6, 7); HpLaserJetControl control(9, 6, 7, 10); //control.wasButtonPressed(#) is a toggle //control.isButtonPressed(#) is a continuous function //control.wasButtonReleased(#) is a toggle // Out custom characters. byte openHeart[8] = { 0b00000, 0b01010, 0b10101, 0b10001, 0b01010, 0b00100, 0b00000, 0b00000 }; byte filledHeart[8] = { 0b00000, 0b01010, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000, 0b00000 }; // Does a flashing sequence with the LEDs. void StartupLedSequence() { static const uint8_t LED_ON_TIME_IN_MS = 75; for (uint8_t i=0; i < 5; i++) { control.setLedState(1, HIGH); delay(LED_ON_TIME_IN_MS); control.setLedState(1, LOW); control.setLedState(2, HIGH); delay(LED_ON_TIME_IN_MS); control.setLedState(2, LOW); control.setLedState(0, HIGH); delay(LED_ON_TIME_IN_MS); control.setLedState(0, LOW); } delay(LED_ON_TIME_IN_MS); for (uint8_t i=0; i < 2; i++) { delay(LED_ON_TIME_IN_MS); control.setLedState(0, HIGH); control.setLedState(1, HIGH); control.setLedState(2, HIGH); delay(LED_ON_TIME_IN_MS * (i*2+1)); control.setLedState(0, LOW); control.setLedState(1, LOW); control.setLedState(2, LOW); } } // We call this each frame to process button presses and update LED's accordingly. void UpdateButtonsAndLeds() { // Top row of buttons being pressed toggles. if (control.wasButtonPressed(0)) { Serial.println("button 0 pressed"); } if (control.wasButtonPressed(1) && !control.isButtonPressed(7)) { Serial.println("button 1 pressed"); } if (control.wasButtonPressed(2)) { Serial.println("button 2 pressed"); } if (control.wasButtonPressed(3)) { Serial.println("button 3 pressed"); } if (control.wasButtonPressed(4)) { Serial.println("button 4 pressed"); } if (control.wasButtonPressed(5)) { Serial.println("button 5 pressed"); } if (control.wasButtonPressed(6)) { Serial.println("button 6 pressed"); } if (control.wasButtonPressed(7) && !control.isButtonPressed(1)) { Serial.println("button 7 pressed"); } if ((control.wasButtonPressed(7) && control.isButtonPressed(7)) || (control.wasButtonPressed(1) && control.isButtonPressed(7))) { Serial.println("button 8 pressed"); } } void setup() { Serial.begin(9600); // Prepare the VFD library for use. vfd.begin(16, 1); // Create open as custom character 0. Note that this display supports 16 custom characters. vfd.createChar(0, openHeart); // Create filled heart as custom character 1. vfd.createChar(1, filledHeart); if (control.isDeviceAttached()) // Test that isDeviceAttached() works correctly { // Sets all pixels on the display. vfd.allDisplay(); // LED flashing sequence. StartupLedSequence(); // Enables normal character display. vfd.display(); } // Print some text to the display. vfd.print("Hello, world!"); } void loop() { UpdateButtonsAndLeds(); // Draw heart beat. vfd.setCursor(14, 0); vfd.write(((millis() % 1000) < 250) ? 1 : 0); }
[ "abzman2000@gmail.com" ]
abzman2000@gmail.com
ec71fe441e7d08320ce7af0dc763a52006dec537
12ac0673d43abcc55c9b7d7a81d0f47848386a6f
/src/Commands/moveServos.cpp
6bf6dcb0adc1f9610f0aaa0138f8afbdd2cd245d
[]
no_license
plahera/RobotTestNew
c7e425584626a18aaf8240c429fef2fef06109d9
d2ed375aca7ed8f57c08f9fce88137e9e17bfebb
refs/heads/master
2021-01-10T06:21:28.745492
2016-03-04T01:48:27
2016-03-04T01:48:27
52,684,882
0
1
null
2016-03-04T01:48:28
2016-02-27T19:32:55
C++
UTF-8
C++
false
false
2,662
cpp
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #define hi #include "moveServos.h" // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR moveServos::moveServos(): Command() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES Requires(Robot::intakeSubsystem.get()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // Called just before this Command runs the first time void moveServos::Initialize() { } // Called repeatedly when this Command is scheduled to run void moveServos::Execute() { #ifdef hi if (Robot::oi->getDriveJoy()->GetPOV()==270||Robot::oi->getDriveJoy()->GetPOV()==90) // goes middle { //Robot::intakeSubsystem->MoveServoLeft(140); //Robot::intakeSubsystem->MoveServoRight(50); Robot::intakeSubsystem->MoveServoLeft(90); Robot::intakeSubsystem->MoveServoRight(90); Wait(.05); //should open it } else if (Robot::oi->getDriveJoy()->GetPOV()==0) // goes out. { //Robot::intakeSubsystem->MoveServoLeft(180); //Robot::intakeSubsystem->MoveServoRight(0); Robot::intakeSubsystem->MoveServoLeft(0); Robot::intakeSubsystem->MoveServoRight(180); Wait(.05); //should close it, first action } else if (Robot::oi->getDriveJoy()->GetPOV()==180) //currently goes up { //Robot::intakeSubsystem->MoveServoLeft(00); //Robot::intakeSubsystem->MoveServoRight(180); Robot::intakeSubsystem->MoveServoLeft(180); Robot::intakeSubsystem->MoveServoRight(0); //should go to middle Wait(.05); } SmartDashboard::PutNumber("POV thing", Robot::oi->getDriveJoy()->GetPOV()); #endif //225-315 left //315-45 top //right: 45 -135 //bottom: 135-225 } // Make this return true when this Command no longer needs to run execute() bool moveServos::IsFinished() { return false; } // Called once after isFinished returns true void moveServos::End() { //Robot::intakeSubsystem->ChangeServoSpeed(0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run void moveServos::Interrupted() { //Robot::intakeSubsystem->ChangeServoSpeed(0); }
[ "plahera1@hwemail.com" ]
plahera1@hwemail.com
e791f74651ee1ab7bb2912f310514e66e9526c04
942aea90ecc3cd50ec8e34de08a9b77876ae80ce
/Dynamic Programming/FloydWarshall.cpp
07930625bc0128e1cba96a5972f336dcb7871bf1
[]
no_license
somenathmaji/github-upload
0f6546997325cab049e299c7b16987d2dafe364d
ab213a8a4118a7b716621253ff23e85fcb0682e6
refs/heads/master
2020-05-01T09:12:28.216905
2019-03-24T14:50:15
2019-03-24T14:50:15
177,394,570
0
0
null
null
null
null
UTF-8
C++
false
false
2,830
cpp
#include<iostream> using namespace std; #define MAX 9999 // graph implementation using adj matrix class Graph { private: int V; int E; bool isDirected; int **adjMat; public: Graph(int v, int e=0, bool d=false) { V = v; E = e; isDirected = d; *adjMat = new int[V]; for(int i=0; i<V; i++) adjMat[i] = new int[V]; for(int i=0; i<V; i++) { for(int j=0; j<V; j++) adjMat[i][j] = MAX; } } bool addEdge(int src, int dst, int w=1) { E++; adjMat[src][dst] = w; if(!isDirected) adjMat[dst][src] = w; } void printAdjMat() { cout<<"The graph represented as adj matrix : "<<endl; for(int i=0; i<V; i++) { for(int j=0; j<V; j++) { if(adjMat[i][j]==MAX) cout<<"x"<<" "; else cout<<adjMat[i][j]<<" "; } cout<<endl; } } void floydWarshall() { int table[V][V]; // initialize same as adj matrix for(int i=0; i<V; i++) { for(int j=0; j<V; j++) { table[i][j] = adjMat[i][j]; } } // pick an intermediate vertex for(int k=0; k<V; k++) { // pick a source vertex for(int i=0; i<V; i++) { // pick a destination vertex for(int j=0; j<V; j++) { // if we can get to destination using intermediate vertex and that is shortest if(table[i][k] + table[k][j] < table[i][j]) table[i][j] = table[i][k] + table[k][j]; } } } // print the solution matrix cout<<"the solution matrix is : "<<endl; for(int i=0; i<V; i++) { for(int j=0; j<V; j++) { if(table[i][j]==MAX) cout<<"x"<<" "; else cout<<table[i][j]<<" "; } cout<<endl; } } }; int main() { Graph g(5, 0, true); g.addEdge(0, 1, 1); g.addEdge(0, 2, 4); g.addEdge(1, 2, 3); g.addEdge(1, 3, 2); g.addEdge(1, 4, 2); g.addEdge(3, 2, 5); g.addEdge(3, 1, 1); g.addEdge(4, 3, 3); g.printAdjMat(); g.floydWarshall(); return 0; }
[ "live.somenath@gmail.com" ]
live.somenath@gmail.com
f51fbcf85eca2b4e787cb0112626e09730e08e8a
ba8b8f21c24009749dbf1145d0dd6169929e3173
/src/libraries/xvnode/src/xvnode_manager.cpp
11f335e814f51736f5f7b603e8417ba2d67cc35f
[]
no_license
Alipipe/TOP-chain
8acbc370738af887ebf4a3d1ccee52b2813d3511
d88c18893bfa88ead5752b74874693819cdf406f
refs/heads/main
2023-07-02T22:37:07.787601
2021-02-11T06:50:46
2021-02-11T06:50:46
357,528,232
0
0
null
2021-04-13T11:29:16
2021-04-13T11:29:15
null
UTF-8
C++
false
false
11,146
cpp
// Copyright (c) 2017-2018 Telos Foundation & contributors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "xvnode/xvnode_manager.h" #include "xcodec/xmsgpack_codec.hpp" #include "xcrypto/xckey.h" #include "xdata/xcodec/xmsgpack/xelection_result_store_codec.hpp" #include "xdata/xdata_common.h" #include "xstore/xaccount_context.h" #include "xstore/xstore_error.h" #include "xvnode/xvnode_factory.h" #include "xvnode/xvnode.h" #include <algorithm> #include <cinttypes> NS_BEG2(top, vnode) xtop_vnode_manager::xtop_vnode_manager(observer_ptr<elect::ElectMain> const & elect_main, observer_ptr<mbus::xmessage_bus_face_t> const & mbus, observer_ptr<store::xstore_face_t> const & store, observer_ptr<base::xvblockstore_t> const & block_store, observer_ptr<time::xchain_time_face_t> const & logic_timer, observer_ptr<router::xrouter_face_t> const & router, observer_ptr<vnetwork::xvhost_face_t> const & vhost, observer_ptr<sync::xsync_object_t> const & sync_object, observer_ptr<grpcmgr::xgrpc_mgr_t> const & grpc_mgr, observer_ptr<xunit_service::xcons_service_mgr_face> const & cons_mgr, observer_ptr<xtxpool_service::xtxpool_service_mgr_face> const & txpool_service_mgr, observer_ptr<xtxpool::xtxpool_face_t> const & txpool, observer_ptr<election::cache::xdata_accessor_face_t> const & election_cache_data_accessor) : m_logic_timer{logic_timer} , m_vhost{vhost} , m_vnode_factory{top::make_unique<xvnode_factory_t>(elect_main, mbus, store, block_store, logic_timer, router, vhost, sync_object, grpc_mgr, cons_mgr, txpool_service_mgr, txpool, election_cache_data_accessor)} { } xtop_vnode_manager::xtop_vnode_manager(observer_ptr<time::xchain_time_face_t> logic_timer, observer_ptr<vnetwork::xvhost_face_t> vhost, std::unique_ptr<xvnode_factory_face_t> vnode_factory) : m_logic_timer{std::move(logic_timer)}, m_vhost{std::move(vhost)}, m_vnode_factory{std::move(vnode_factory)} { assert(m_vnode_factory != nullptr); } void xtop_vnode_manager::start() { assert(m_logic_timer != nullptr); m_logic_timer->watch(chain_timer_watch_name, 1, std::bind(&xtop_vnode_manager::on_timer, this, std::placeholders::_1)); assert(!running()); running(true); } void xtop_vnode_manager::stop() { assert(running()); running(false); assert(m_logic_timer != nullptr); m_logic_timer->unwatch(chain_timer_watch_name); } std::vector<common::xip2_t> xtop_vnode_manager::handle_election_data(std::unordered_map<common::xcluster_address_t, election::cache::xgroup_update_result_t> const & election_data) { // if (!running()) { // xwarn("[vnode mgr] is not running"); // return {}; // } assert(!election_data.empty()); auto const & host_node_id = m_vhost->host_node_id(); xdbg("[vnode mgr] host %s sees election data size %zu", host_node_id.value().c_str(), election_data.size()); std::vector<common::xip2_t> outdated_xips; XLOCK(m_nodes_mutex); for (auto const & group_info : election_data) { auto const & cluster_address = top::get<common::xcluster_address_t const>(group_info); auto const & group_update_result = top::get<election::cache::xgroup_update_result_t>(group_info); auto const & outdated_group = group_update_result.outdated; auto const & faded_group = group_update_result.faded; auto const & added_group = group_update_result.added; assert(added_group != nullptr); bool vnode_outdated{false}; if (outdated_group != nullptr && outdated_group->contains(host_node_id)) { auto const & address = outdated_group->node_element(host_node_id)->address(); assert(address.slot_id().has_value()); auto const it = m_all_nodes.find(address); if (it != std::end(m_all_nodes)) { vnode_outdated = true; auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it); vnode->rotation_status(common::xrotation_status_t::outdated, outdated_group->outdate_time()); xwarn("[vnode mgr] vnode (%p) at address %s will outdate at logic time %" PRIu64, vnode.get(), vnode->address().to_string().c_str(), vnode->outdate_time()); } } if (faded_group != nullptr && faded_group->contains(host_node_id)) { auto const & address = faded_group->node_element(host_node_id)->address(); assert(address.slot_id().has_value()); auto const & it = m_all_nodes.find(address); if (it != std::end(m_all_nodes)) { vnode_outdated = false; auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it); vnode->rotation_status(common::xrotation_status_t::faded, faded_group->fade_time()); xwarn("[vnode mgr] vnode (%p) at address %s will fade at logic time %" PRIu64, vnode.get(), vnode->address().to_string().c_str(), vnode->fade_time()); } } if (added_group->contains(host_node_id)) { vnode_outdated = false; auto const & address = added_group->node_element(host_node_id)->address(); assert(address.slot_id().has_value()); auto const it = m_all_nodes.find(address); if (it != std::end(m_all_nodes)) { continue; } assert(m_vnode_factory); auto vnode = m_vnode_factory->create_vnode_at(added_group); assert(vnode->address() == address); vnode->rotation_status(common::xrotation_status_t::started, added_group->start_time()); xwarn("[vnode mgr] vnode (%p) at address %s will start at logic time %" PRIu64 " associated election blk height %" PRIu64, vnode.get(), vnode->address().to_string().c_str(), vnode->start_time(), vnode->address().associated_blk_height()); vnode->synchronize(); xwarn("[vnode mgr] vnode (%p) at address %s starts synchronizing", vnode.get(), vnode->address().to_string().c_str()); XATTRIBUTE_MAYBE_UNUSED auto ret = m_all_nodes.insert({address, vnode}); assert(top::get<bool>(ret)); (void)ret; } if (vnode_outdated) { xwarn("[vnode mgr] vnode at address %s is outdated", cluster_address.to_string().c_str()); common::xip2_t xip{cluster_address.network_id(), cluster_address.zone_id(), cluster_address.cluster_id(), cluster_address.group_id()}; outdated_xips.push_back(std::move(xip)); } } return outdated_xips; } void xtop_vnode_manager::on_timer(time::xchain_time_st const & timer_data) { if (!running()) { xwarn("[vnode mgr] is not running"); return; } assert(m_election_notify_thread_id != std::this_thread::get_id()); XLOCK_GUARD(m_nodes_mutex) { // make sure: // 1. outdate first // 2. fade second // 3. start third for (auto it = std::begin(m_all_nodes); it != std::end(m_all_nodes);) { auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it); assert(vnode != nullptr); switch (vnode->rotation_status(timer_data.xtime_round)) { case common::xrotation_status_t::outdated: { vnode->stop(); xwarn("[vnode mgr] vnode (%p) at address %s outdates at logic time %" PRIu64 " current logic time %" PRIu64, vnode.get(), vnode->address().to_string().c_str(), vnode->outdate_time(), timer_data.xtime_round); it = m_all_nodes.erase(it); break; } default: { ++it; break; } } } for (auto it = std::begin(m_all_nodes); it != std::end(m_all_nodes); ++it) { auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it); assert(vnode != nullptr); switch (vnode->rotation_status(timer_data.xtime_round)) { case common::xrotation_status_t::outdated: { assert(false); break; } case common::xrotation_status_t::faded: { if (!vnode->faded() && vnode->running()) { vnode->fade(); xwarn("[vnode mgr] vnode (%p) at address %s fades at logic time %" PRIu64 " current logic time %" PRIu64, vnode.get(), vnode->address().to_string().c_str(), vnode->fade_time(), timer_data.xtime_round); } break; } default: { break; } } } for (auto it = std::begin(m_all_nodes); it != std::end(m_all_nodes); ++it) { auto & vnode = top::get<std::shared_ptr<xvnode_face_t>>(*it); assert(vnode != nullptr); switch (vnode->rotation_status(timer_data.xtime_round)) { case common::xrotation_status_t::outdated: { assert(false); break; } case common::xrotation_status_t::started: { if (!vnode->running()) { vnode->start(); xwarn("[vnode mgr] vnode (%p) at address %s starts at logic time %" PRIu64 " current logic time %" PRIu64, vnode.get(), vnode->address().to_string().c_str(), vnode->start_time(), timer_data.xtime_round); } break; } default: { break; } } } } } NS_END2
[ "zql0114@gmail.com" ]
zql0114@gmail.com
2a973c3dee806fdeb7bbb4481e16a4ee86fd4e40
896d897a135f7ae7175ceed28ce4f439d7a74cc8
/tstring.hpp
bbb9c3018add1d37c68321a207b94717cc4446f9
[]
no_license
zby123/bookstore
b1489ad36172c0c0a2b895405503982e01cd0815
4b7210f12a386a6f2cc604fdf6f35ba574b3e0de
refs/heads/master
2021-08-31T18:47:09.744446
2017-12-22T12:16:23
2017-12-22T12:16:23
115,112,653
0
0
null
null
null
null
UTF-8
C++
false
false
1,617
hpp
#ifndef tstring_hpp #define tstring_hpp #include <string> #include <cstring> #include <algorithm> #include <iostream> using namespace std; template <int size> class tstring { private: char m[size]; int len = 0; public: tstring() { len = 0; } tstring(int t) { if (t == 0) { len = 0; } else{ len = size; for(int i = 0; i < size; i++) m[i] = 127; } } tstring (const char *b) { len = min(size, (int)strlen(b)); for(int i = 0; i < len; i++) m[i] = b[i]; } tstring (char *b) { len = min(size, (int)strlen(b)); for(int i = 0; i < len; i++) m[i] = b[i]; } tstring(string &b) { len = min(size, (int)b.length()); for(int i = 0; i < len; i++) m[i] = b[i]; } int getLen() { return len; } void print() { for(int i = 0; i < len; i++) cout << m[i]; } template <int s2> tstring(tstring<s2> &b) { len = min(b.getLen(), size); for(int i = 0; i < len; i++) m[i] = b[i]; } operator bool () const { return len != 0; } operator string () const { string ret = ""; for(int i = 0; i < len; i++) ret += m[i]; return ret; } char operator [] (int pos) { if (pos > len) return '\0'; return m[pos]; } template <int s2> bool operator == (tstring<s2> &b) { if (b.getLen() != len) return false; for(int i = 0; i < len; i++) { if (m[i] != b[i]) return false; } return true; } template <int s2> bool operator < (tstring<s2> &b) { int tlen = min(len, b.getLen()); for(int i = 0; i < tlen; i++) { if (m[i] < b[i]) return true; if (m[i] > b[i]) return false; } if (len < b.getLen()) return true; return false; } }; #endif
[ "ZengBiyang@sjtu.edu.cn" ]
ZengBiyang@sjtu.edu.cn
50832aad5d2a4ee9254f1091652e2e939497efd0
f267b24a6bcab15be3ff54e733e2e38acaf22576
/C/12. login.cpp
083a96384aafe354f8e5f3b9f32df1cfca442462
[]
no_license
BusBang/Practice-PythonAndR
b5fb5f29fe2c6fa8afc6154c7da30689d9bdf518
b79cbd31ab009c63562746f595f30ef103511255
refs/heads/master
2022-12-31T03:36:35.916456
2020-10-21T14:55:25
2020-10-21T14:55:25
284,936,368
0
0
null
null
null
null
UHC
C++
false
false
279
cpp
#include <stdio.h> int main(void) { int x = 50, y = 30; printf("x가 y보다 크고, y는 40 미만입니까? %d\n", (x>y) && (y<40)); printf("x가 y보다 작거나, y는 30입니까? %d\n", (x<y) || (y<30)); printf("x가 50이 아닙니까? %d", x!= 50); return 0; }
[ "58544672+BusBang@users.noreply.github.com" ]
58544672+BusBang@users.noreply.github.com
bc62e1fbc3ba4150fb90873e05ec09939f274ccc
a81c07a5663d967c432a61d0b4a09de5187be87b
/ash/system/message_center/arc/arc_notification_content_view.h
caaa5712feb4c122b76686610c758592491f984e
[ "BSD-3-Clause" ]
permissive
junxuezheng/chromium
c401dec07f19878501801c9e9205a703e8643031
381ce9d478b684e0df5d149f59350e3bc634dad3
refs/heads/master
2023-02-28T17:07:31.342118
2019-09-03T01:42:42
2019-09-03T01:42:42
205,967,014
2
0
BSD-3-Clause
2019-09-03T01:48:23
2019-09-03T01:48:23
null
UTF-8
C++
false
false
7,921
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 ASH_SYSTEM_MESSAGE_CENTER_ARC_ARC_NOTIFICATION_CONTENT_VIEW_H_ #define ASH_SYSTEM_MESSAGE_CENTER_ARC_ARC_NOTIFICATION_CONTENT_VIEW_H_ #include <memory> #include <string> #include "ash/system/message_center/arc/arc_notification_item.h" #include "ash/system/message_center/arc/arc_notification_surface_manager.h" #include "base/macros.h" #include "ui/aura/window_observer.h" #include "ui/message_center/views/notification_background_painter.h" #include "ui/message_center/views/notification_control_buttons_view.h" #include "ui/views/controls/native/native_view_host.h" #include "ui/views/widget/widget_observer.h" namespace message_center { class Notification; class NotificationControlButtonsView; } // namespace message_center namespace ui { class LayerTreeOwner; } namespace views { class FocusTraversable; class Widget; } // namespace views namespace ash { class ArcNotificationSurface; // ArcNotificationContentView is a view to host NotificationSurface and show the // content in itself. This is implemented as a child of ArcNotificationView. class ArcNotificationContentView : public views::NativeViewHost, public aura::WindowObserver, public ArcNotificationItem::Observer, public ArcNotificationSurfaceManager::Observer, public views::WidgetObserver { public: static const char kViewClassName[]; ArcNotificationContentView(ArcNotificationItem* item, const message_center::Notification& notification, message_center::MessageView* message_view); ~ArcNotificationContentView() override; // views::View overrides: const char* GetClassName() const override; void Update(const message_center::Notification& notification); message_center::NotificationControlButtonsView* GetControlButtonsView(); void UpdateControlButtonsVisibility(); void UpdateCornerRadius(int top_radius, int bottom_radius); void OnSlideChanged(bool in_progress); void OnContainerAnimationStarted(); void OnContainerAnimationEnded(); void ActivateWidget(bool activate); private: friend class ArcNotificationViewTest; friend class ArcNotificationContentViewTest; FRIEND_TEST_ALL_PREFIXES(ArcNotificationContentViewTest, ActivateWhenRemoteInputOpens); class EventForwarder; class MouseEnterExitHandler; class SettingsButton; class SlideHelper; void CreateCloseButton(); void CreateSettingsButton(); void MaybeCreateFloatingControlButtons(); void SetSurface(ArcNotificationSurface* surface); void UpdatePreferredSize(); void UpdateSnapshot(); void AttachSurface(); void SetExpanded(bool expanded); bool IsExpanded() const; void SetManuallyExpandedOrCollapsed(bool value); bool IsManuallyExpandedOrCollapsed() const; void ShowCopiedSurface(); void HideCopiedSurface(); // Generates a mask using |top_radius_| and |bottom_radius_| and installs it. void UpdateMask(bool force_update); // views::NativeViewHost void ViewHierarchyChanged( const views::ViewHierarchyChangedDetails& details) override; void Layout() override; void OnPaint(gfx::Canvas* canvas) override; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; void OnFocus() override; void OnBlur() override; views::FocusTraversable* GetFocusTraversable() override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; void OnAccessibilityEvent(ax::mojom::Event event) override; void AddedToWidget() override; void RemovedFromWidget() override; // aura::WindowObserver void OnWindowBoundsChanged(aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) override; void OnWindowDestroying(aura::Window* window) override; // views::WidgetObserver: void OnWidgetClosing(views::Widget* widget) override; // ArcNotificationItem::Observer void OnItemDestroying() override; void OnItemContentChanged( arc::mojom::ArcNotificationShownContents content) override; void OnRemoteInputActivationChanged(bool activated) override; // ArcNotificationSurfaceManager::Observer: void OnNotificationSurfaceAdded(ArcNotificationSurface* surface) override; void OnNotificationSurfaceRemoved(ArcNotificationSurface* surface) override; // If |item_| is null, we may be about to be destroyed. In this case, // we have to be careful about what we do. ArcNotificationItem* item_; ArcNotificationSurface* surface_ = nullptr; arc::mojom::ArcNotificationShownContents shown_content_ = arc::mojom::ArcNotificationShownContents::CONTENTS_SHOWN; // The flag to prevent an infinite loop of changing the visibility. bool updating_control_buttons_visibility_ = false; const std::string notification_key_; // A pre-target event handler to forward events on the surface to this view. // Using a pre-target event handler instead of a target handler on the surface // window because it has descendant aura::Window and the events on them need // to be handled as well. // TODO(xiyuan): Revisit after exo::Surface no longer has an aura::Window. std::unique_ptr<EventForwarder> event_forwarder_; // A handler which observes mouse entered and exited events for the floating // control buttons widget. std::unique_ptr<ui::EventHandler> mouse_enter_exit_handler_; // A helper to observe slide transform/animation and use surface layer copy // when a slide is in progress and restore the surface when it finishes. std::unique_ptr<SlideHelper> slide_helper_; // Whether the notification is being slid or is at the origin. This stores the // latest value of the |in_progress| from OnSlideChanged callback, which is // called during both manual swipe and automatic slide on dismissing or // resetting back to the origin. // This value is synced with the visibility of the copied surface. If the // value is true, the copied surface is visible instead of the original // surface itself. Copied surgace doesn't have control buttons so they must be // hidden if it's true. // This value is stored in case of the change of surface. When a new surface // sets, if this value is true, the copy of the new surface gets visible // instead of the copied surface itself. bool slide_in_progress_ = false; // A control buttons on top of NotificationSurface. Needed because the // aura::Window of NotificationSurface is added after hosting widget's // RootView thus standard notification control buttons are always below // it. std::unique_ptr<views::Widget> floating_control_buttons_widget_; // The message view which wrapps thie view. This must be the parent of this // view. message_center::MessageView* const message_view_; // This view is owned by client (this). message_center::NotificationControlButtonsView control_buttons_view_; // Protects from call loops between Layout and OnWindowBoundsChanged. bool in_layout_ = false; // Widget which this view tree is currently attached to. views::Widget* attached_widget_ = nullptr; base::string16 accessible_name_; // If it's true, the surface gets active when attached to this view. bool activate_on_attach_ = false; // Radiuses of rounded corners. These values are used in UpdateMask(). int top_radius_ = 0; int bottom_radius_ = 0; // Current insets of mask layer. base::Optional<gfx::Insets> mask_insets_; std::unique_ptr<ui::LayerTreeOwner> surface_copy_; DISALLOW_COPY_AND_ASSIGN(ArcNotificationContentView); }; } // namespace ash #endif // ASH_SYSTEM_MESSAGE_CENTER_ARC_ARC_NOTIFICATION_CONTENT_VIEW_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2d4b9e8a79b204aec4d1de65544a128d936073e5
0b61d90afd0c72155a9b28951995ed23eae70e16
/Source/SmartSPS/SmartSPS/node_blfrs.h
7f97b63d167ecfb6cfcdec4b7a0b12ab9887a469
[ "MIT" ]
permissive
RBEGamer/HomePLC
76aaf1b9386bf1faee63c2d5172f61d5e1a03eb5
65dbf7224563878d0550dea9a8df731437d4f83c
refs/heads/master
2023-02-23T17:30:02.378516
2023-02-06T16:07:01
2023-02-06T16:07:01
47,475,515
4
1
null
null
null
null
UTF-8
C++
false
false
999
h
#pragma once #include "single_node_include.h" class node_blfrs : public base_node { public: node_blfrs(int id, bool us, const int con_count, std::string params, bool is_static, bool ut); ~node_blfrs(); void update(float timestep = 0.0f); void init(); void load_node_parameters(std::string params); connector* p_connections; int connection_count; void set_connection(int pos, base_node* ptr, int dest_pos); virtual void serial_income(std::string message); //PARAMS //VALUES bool p0_a_input; //pos 0 bool p1_b_input; bool last_set_a; bool p2_c_output; bool outuput_updated; bool last_state_a; bool last_state_b; bool update_v; bool last_set_b; void set_value(int position, float value); void set_value(int position, int value); void set_value(int position, bool value); void set_value(int position, std::string value); float get_value_f(int position); int get_value_i(int position); bool get_value_b(int position); std::string get_value_s(int position); private: };
[ "marcel.ochsendorf@gmail.com" ]
marcel.ochsendorf@gmail.com
782a87564857298b1016cf990ca9eaa60b487f43
8425574e87365bba72bc45ab9eab9f29b9f3568d
/src/basicMath/Math.h
078ca914af6a1c403c455616df905677c7344905
[]
no_license
melisaadin/modedock
92dd3714928f18f70c621de4760facb43f05b376
28fc1398ea8022b85883979a2da6d6451a0a7472
refs/heads/master
2023-03-15T15:28:47.042591
2019-02-19T07:06:18
2019-02-19T07:06:18
522,142,100
1
0
null
2022-08-07T07:10:36
2022-08-07T07:10:36
null
UTF-8
C++
false
false
14,575
h
#ifndef MATH_H_ #define MATH_H_ #include <cmath> #include <cstdio> #include <cstdlib> #include <vector> #include <iostream> #include <GL/gl.h> using std::vector; using std::string; #ifndef MAXFLOAT #define MAXFLOAT 1.0E+20 #endif static const double smallEPS = 1.01E-10, mediumEPS = 1.01E-5, largeEPS = 1.01E-3, Pi = 3.14159265358979, PiSquared = Pi * Pi, TwoPi = 2.0 * Pi, twoPiSqrt = sqrt(2.0*Pi), FourPi = 4.0 * Pi, PiOverTwo = Pi / 2.0, PiOverThree = Pi / 3.0, TwoPiOverThree= Pi / 1.5, // 120.0 PiOverFour = Pi / 4.0, OverPi = 1.0 / Pi, OverTwoPi = 1.0 / TwoPi, OverFourPi = 1.0 / FourPi, Infinity = MAXFLOAT, Tiny = 1.0 / MAXFLOAT, DegreesToRad = Pi / 180.0, deg2Rad = DegreesToRad, RadToDegrees = 180.0 / Pi, rad2Deg = RadToDegrees, X = 0.525731112119133606, Z = 0.850650808352039932 ; static const unsigned short dim2 = 2, dim3= 3, dim4= 4, dim5 = 5, dim6 = 6, dim7 = 7, dim8 = 8, dim9 = 9, dim10 = 10, dim12 = 12, dim13 = 13, dim15 = 15, dim20 = 20, dim30 = 30; static const double sqrt2 = sqrt(2.0); static const double sqrt2OverTwo = 0.50 * sqrt2; static const double sqrt3 = sqrt(3.0); static const double PiOverSix = 0.50 *PiOverThree; const static double vdata[12][3] = { {-X, 0.0, Z}, {X, 0.0, Z}, {-X, 0.0, -Z}, {X, 0.0, -Z}, {0.0, Z, X}, {0.0, Z, -X}, {0.0, -Z, X}, {0.0, -Z, -X}, {Z, X, 0.0}, {-Z, X, 0.0}, {Z, -X, 0.0}, {-Z, -X, 0.0} }; const static unsigned short tindices[20][3] = { {0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1}, {8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3}, {7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6}, {6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11} }; const static unsigned short icosahedronEdge[30][2] = { {0, 1}, {0, 4}, {0, 6}, {0, 9}, {0, 11}, {1, 4}, {1, 6}, {1, 8}, {1, 10}, {2, 3}, {2, 5}, {2, 7}, {2, 9}, {2, 11}, {3, 5}, {3, 7}, {3, 8}, {3, 10}, {4, 5}, {4, 8}, {4, 9}, {5, 8}, {5, 9}, {6, 7}, {6, 10}, {6, 11}, {7, 10}, {7, 11}, {8, 10}, {9, 11} }; inline int Odd ( int k ) { return k & 1; } inline int Even ( int k ) { return !(k & 1); } inline float Abs ( int x ) { return x > 0 ? x : -x; } inline float Abs ( float x ) { return x > 0. ? x : -x; } inline float Abs ( double x ) { return x > 0. ? x : -x; } inline int iMin ( int x, int y ) { return x < y ? x : y; } inline int iMax ( int x, int y ) { return x > y ? x : y; } inline float fMin ( float x, float y ) { return x < y ? x : y; } inline float fMax ( float x, float y ) { return x > y ? x : y; } inline double dMin ( double x, double y ) { return x < y ? x : y; } inline double dMax ( double x, double y ) { return x > y ? x : y; } inline float Sqr ( int x ) { return x * x; } inline float Sqr ( float x ) { return x * x; } inline float Sqr ( double x ) { return x * x; } inline float Sqrt ( double x ) { return x > 0. ? sqrt(x) : 0.; } inline float Cubed ( float x ) { return x * x * x; } inline int Sign ( float x ) { return x > 0. ? 1 : (x < 0. ? -1 : 0); } inline void Swap ( float &a, float &b ) { float c = a; a = b; b = c; } inline void Swap ( int &a, int &b ) { int c = a; a = b; b = c; } inline double Sin ( double x, int n ) { return pow( sin(x), n ); } inline double Cos ( double x, int n ) { return pow( cos(x), n ); } inline float ToSin ( double x ) { return Sqrt( 1.0 - Sqr(x) ); } inline float ToCos ( double x ) { return Sqrt( 1.0 - Sqr(x) ); } inline float Pythag( double x, double y ) { return Sqrt( x*x + y*y ); } inline double ArcCos( double x ){ double y; if( -1.0 <= x && x <= 1.0 ) y = acos( x ); else if( x > 1.0 ) y = 0.0; else if( x < -1.0 ) y = Pi; return y; } inline double ArcSin( double x ){ if( x < -1.0 ) x = -1.0; if( x > 1.0 ) x = 1.0; return asin( x ); } inline float Clamp( float min, float &x, float max ){ if( x < min ) x = min; else if( x > max ) x = max; return x; } inline double Clamp( float min, double &x, float max ){ if( x < min ) x = min; else if( x > max ) x = max; return x; } inline int iMax( int x, int y, int z ){ int t; if( x >= y && x >= z ) t = x; else if( y >= z ) t = y; else t = z; return t; } inline int iMin( int x, int y, int z ){ int t; if( x <= y && x <= z ) t = x; else if( y <= z ) t = y; else t = z; return t; } inline float fMax( float x, float y, float z ){ float t; if( x >= y && x >= z ) t = x; else if( y >= z ) t = y; else t = z; return t; } inline float fMin( float x, float y, float z ){ float t; if( x <= y && x <= z ) t = x; else if( y <= z ) t = y; else t = z; return t; } inline double dMax( double x, double y, double z ){ double t; if( x >= y && x >= z ) t = x; else if( y >= z ) t = y; else t = z; return t; } inline double dMin( double x, double y, double z ){ double t; if( x <= y && x <= z ) t = x; else if( y <= z ) t = y; else t = z; return t; } inline float Pythag( float x, float y, float z ){ return sqrt( x * x + y * y + z * z ); } /** calculate the angles between two vectors v1 and v2 * The returned angle is in the [0,Pi] range or the cosine value (not the value of angle). */ inline double interAngle(double * const v1, double * const v2, const int dim){ double v1Len = 0.0, v2Len = 0.0; for (int i = 0; i < dim; i++) v1Len += v1[i]*v1[i]; // v1Len = sqrt(v1Len); for (int i = 0; i < dim; i++) v2Len += v2[i]*v2[i]; // v2Len = sqrt(v2Len); if ( v1Len < Tiny || v2Len < Tiny){ std::cout<<"divide by ZERO in interAngle \n"; exit(1); } return ( (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]) / ( sqrt(v1Len * v2Len) ) ); // return Math.acos(c); //acos [0, PI] so should be OK } /** calculate the angles between two vectors v1 and v2 * The returned angle is in the [0,Pi] range or the cosine value (not the value of angle). */ inline bool interAngle(double *v1, double *v2, const int dim, double &angle){ double v1Len = 0.0, v2Len = 0.0; for (int i = 0; i < dim; i++) v1Len += v1[i]*v1[i]; // v1Len = sqrt(v1Len); for (int i = 0; i < dim; i++) v2Len += v2[i]*v2[i]; // v2Len = sqrt(v2Len); if ( v1Len < Tiny || v2Len < Tiny){ std::cout<<"divide by ZERO in interAngle \n"; return false; } angle = (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]) / ( sqrt(v1Len * v2Len) ) ; return true; // return Math.acos(c); //acos [0, PI] so should be OK } inline double interAngleF(float *v1, float *v2, const int dim){ float v1Len = 0.0, v2Len = 0.0; for (int i = 0; i < dim; i++) v1Len += v1[i]*v1[i]; v1Len = sqrt(v1Len); for (int i = 0; i < dim; i++) v2Len += v2[i]*v2[i]; v2Len = sqrt(v2Len); if ( v1Len < Tiny || v2Len < Tiny){ std::cout<<"divide by ZERO in interAngle \n"; exit(1); } return ( (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]) / (v1Len * v2Len) ); // return Math.acos(c); //acos [0, PI] so should be OK } // //inline bool interAngleD( double *const v1, double *const v2, // const size_t dim, double& angle){ // double v1Len = 0.0, v2Len = 0.0; // for (unsigned int i = 0; i < dim; i++) // v1Len += v1[i] * v1[i]; // v1Len = sqrt(v1Len); // for (unsigned int i = 0; i < dim; i++) // v2Len += v2[i] * v2[i]; // v2Len = sqrt(v2Len); // if ( v1Len < Tiny || v2Len < Tiny){ // cout<<"divide by ZERO in interAngle \n"; // return false; // } // double cosValue = 0.0; // for (unsigned int i = 0; i < dim; i++) // cosValue += v1[i] * v2[i]; // angle = cosValue / (v1Len * v2Len) ; // return true; // // return Math.acos(c); //acos [0, PI] so should be OK //} /** cal the directioal cosines of the vector vec */ inline double* dirCos(double *vec, int dim) { double len = 0.0; double *dirs = new double[dim]; for (int i = 0; i < dim; i++) len += vec[i] * vec[i]; len = sqrt(len); if ( len < Tiny ){ std::cout<<"divide by ZERO in interAngle \n"; exit(1); } for (int j=0; j<dim; j++) dirs[j] = vec[j] / len; return dirs; } /** cal the polar coordinate of the vector vec */ inline double* polarCoord(double *vec, int dim) { double len = 0.0; double *dirs = new double[dim]; for (int i = 0; i < dim; i++) len += vec[i] * vec[i]; len = sqrt(len); if ( len < Tiny ){ std::cout<<"divide by ZERO in interAngle \n"; exit(1); } if ( dim != 3 ){ std::cout<<"This polar function only for 3D \n"; exit(1); } for (int j=0; j<dim; j++) dirs[j] = vec[j] / len; dirs[0] = acos( sqrt (dirs[0] * dirs[0] + dirs[1] * dirs[1] ) / len); if ( dirs[2] < 0) dirs[0] = Pi - dirs[0]; if ( fabs(dirs[0] ) < Tiny){ dirs[1] = 0.0; return dirs; } double sinF = vec[1] / ( len * dirs[0] ); double cosF = vec[0] / ( len * dirs[0] ); if( sinF >= 0.0) dirs[1] = acos(cosF); else dirs[1] = TwoPi - acos(cosF); return dirs; } /** cal the polar coordinate of the vector vec */ inline float* polarCoordF(float *vec, int dim) { float len = 0.0; float *dirs = new float[dim]; for (int i = 0; i < dim; i++) len += vec[i] * vec[i]; len = sqrt(len); if ( len < Tiny ){ std::cout<<"divide by ZERO in interAngle \n"; exit(1); } if ( dim != 3 ){ std::cout<<"This polar function only for 3D \n"; exit(1); } for (int j=0; j<dim; j++) dirs[j] = vec[j] / len; dirs[0]= acos( dirs[2]); float sinT = sqrt( 1.0 - dirs[2] * dirs[2]); // 1 - cos^2_{theta} if ( fabs(sinT ) < Tiny){ dirs[1] = 0.0; dirs[2] = len; return dirs; } float sinF = vec[1] / ( len * sinT ); float cosF = vec[0] / ( len * sinT); // cout<<sinF<<" "<<cosF<<endl; if( sinF >= 0.0) dirs[1] = acos(cosF); else dirs[1] = TwoPi - acos(cosF); dirs[2] = len; return dirs; } /** * A method for generating the internuclear vector between two atoms @param n1 the coordinate for the nucleus of the atom 1 @param n2 the coordinate for the nucleus of the atom 2 @return a vector from n1->n2 */ inline double Distance(double *n1, double *n2, const size_t dim = 3){ double sum =0.0; for (unsigned int i = 0; i < dim; i++) sum += ( n2[i] - n1[i] ) * ( n2[i] - n1[i] ) ; return sqrt(sum); } inline float DistanceF(float *n1, float *n2, const size_t dim = 3){ float sum =0.0; for (unsigned int i = 0; i < dim; i++) sum += ( n2[i] - n1[i] ) * ( n2[i] - n1[i] ) ; return sqrt(sum); } inline double Distsq(double *n1, double *n2, const size_t dim = 3){ double sum =0.0; for (unsigned int i = 0; i < dim; i++) sum += ( n2[i] - n1[i] ) * ( n2[i] - n1[i] ) ; return sum; } inline void Norm(double *x, double *xnorm) { /* RETURNS INPUT VECTOR X NORMALIZED TO UNIT LENGTH. XNORM IS THE ORIGINAL LENGTH OF X. */ double TEMP, TEMP1, TEMP2; TEMP = x[0]; TEMP1 = x[1]; TEMP2 = x[2]; *xnorm = TEMP * TEMP + TEMP1 * TEMP1 + TEMP2 * TEMP2; if (*xnorm <= 0.0) return; *xnorm = sqrt(*xnorm); x[0] /= *xnorm; x[1] /= *xnorm; x[2] /= *xnorm; } inline void Diff( const double *const x, const double *const y, double *z, const size_t dim = 3){ for ( unsigned int i = 0; i < dim; i++ ) z[i]= x[i] - y[i]; } inline double Dot(const double *const x, const double *const y) { return x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; } inline void Cross(const double *const x, const double *const y, double *z){ z[0] = x[1] * y[2] - y[1] * x[2]; z[1] = x[2] * y[0] - y[2] * x[0]; z[2] = x[0] * y[1] - y[0] * x[1]; } inline float *addCoords( float*n1, float*n2, int dim){ float *sum = new float[dim]; for (int i = 0; i < dim; i++) sum[i] = n2[i] + n1[i]; return sum; } inline float *aveCoords(float *n1, float *n2, int dim){ float *ave = new float[dim]; for (int i = 0; i < dim; i++) ave[i] = 0.50 * ( n2[i] + n1[i] ); return ave; } inline float *internuclearVec( float*n1, float*n2, int dim){ float *sum = new float[dim]; for (int i = 0; i < dim; i++) sum[i] = n2[i] - n1[i]; return sum; } inline void internuclearVec( double *const n1, double *const n2, double sum[], int dim ){ for (int i = 0; i < dim; i++) sum[i] = n2[i] - n1[i]; } inline vector<double> n1ToN2VecD( double *n1, double *n2, int dim){ vector<double> sum(dim, 0.0); for (int i = 0; i < dim; i++) sum[i] = n2[i] - n1[i]; return sum; } // inline float *internuclearVec( float*n1, const vector<float>&n1, int dim){ // float *sum = new float[dim]; // for (int i = 0; i < dim; i++) // sum[i] = n2[i] - n1[i]; // return sum; // } inline float norm( float *vec, int dim){ float len = 0.0; for (int i=0; i< dim; i++) len += vec[i] * vec[i]; return sqrt(len); } inline double norm( vector<float>& vec, const size_t dim){ double len = 0.0; for (unsigned int i=0; i< dim; i++) len += vec[i] * vec[i]; len = sqrt(len); for (unsigned int i=0; i< dim; i++) vec[i] /= len; return len; } inline double norm( vector<double>& vec, const size_t dim){ double len = 0.0; for (unsigned int i=0; i< dim; i++) len += vec[i] * vec[i]; len = sqrt(len); for (unsigned int i=0; i< dim; i++) vec[i] /= len; return len; } inline float normSquare( float*vec, int dim){ float len = 0.0; for (int i=0; i< dim; i++) len += vec[i] * vec[i]; return len; } inline void printArray(string name, double *const n1, int d){ printf("%5s", name.c_str() ); for (int i=0; i<d; i++) printf("%10.5f", n1[i]); printf("\n"); } inline void printArray(string name, const vector<double> &n1 ){ printf("%5s", name.c_str() ); for (int i=0; i< n1.size(); i++) printf("%10.5f", n1[i]); printf("\n"); } inline void printArray(double *const n1, int d){ for (int i=0; i<d; i++) printf("%16.8f", n1[i]); printf("\n"); } inline void printArray(const vector<double> &n1 ){ for (int i=0; i< n1.size(); i++) printf("%16.8f", n1[i]); printf("\n"); } inline float InvSqrt (float x){ float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f - xhalf*x*x); return x; } #ifndef ABS #define ABS( x ) ((x) > 0 ? (x) : -(x)) #endif #ifndef MAX #define MAX( x, y ) ((x) > (y) ? (x) : (y)) #endif #ifndef MIN #define MIN( x, y ) ((x) < (y) ? (x) : (y)) #endif #endif /*MATH_H_*/
[ "xushutan@gmail.com" ]
xushutan@gmail.com
f108a73935c7a1a8fcdbe75035e97d96b7f6f200
31738a884a8d66abef58459247cbbd8d8e4355ed
/src/pair.h
a369e027e5c8f5d1d1f00a8c2e64eee673b0b97f
[]
no_license
kyho4515/FinalProject
9a563dd548a9679179cc1e9dee064045d73fa126
473473d10883846cd28b5829871ab10595e7a9b2
refs/heads/master
2020-06-08T16:33:49.160471
2015-09-06T07:38:44
2015-09-06T07:38:44
39,369,753
0
0
null
null
null
null
UTF-8
C++
false
false
1,429
h
#ifndef POTENTIALPAIR #define POTENTIALPAIR #include "Gate.h" #include "util.h" #include <fstream> #include <algorithm> #include <math.h> #include <stack> class PotentialPair{ public: PotentialPair(vector<vector<Wire*>*>);//input為_FECpair ~PotentialPair(){ for(int i=0;i<pair.size();i++){ delete pair[i]; delete commonIn[i]; } delete number; } void Out(); private: vector<vector<Wire*>*> pair; vector<vector<Gate*>*> commonIn;//每一組pair的common input vector<Gate*>differentIn; vector<Gate*>store; vector<int> overflowpair; vector<vector<Gate*> > temDFSlist; int start; int *number; fstream output; bool RepeatInPair(int starting,Wire* unfind);//從pair中找到wire可能的位置 void FindCommonInput(Wire*,Wire*,int);//找相同的input void FindCommonInput(Wire*,int);// bool ProveDontCare(Wire*,Wire*,int);//證明不同的input為dont care term bool ProveFunction(Wire*,Wire*,int);//證明function相同或相反 void DFS(Gate*);//做DFS bool ProveEqual(Wire*,Wire*,int); bool InSameLine(Wire*,Wire*);//證明wire沒有上下關係 bool DFSFind(Gate*,Gate*);//DFS尋找後面的wire void cleanstore(); static bool sortcompare(const Wire* l,const Wire* r){ //sort的判斷式 return l->gateLevel < r->gateLevel; } void GiveNumber(vector<Gate*>*,int,bool);//10個input以內用確定的證明,超過10個用隨機證明 }; #endif
[ "willywsm1013@gmail.com" ]
willywsm1013@gmail.com
1a54b5d0b772d04f9fd62b35082caacafd4d8f83
f043e988d058b3fc5c40fd52e62d7269d24163f4
/Switch_case.cpp
ab5e456ab182b97c4540ecfac9e0a444c43fe37c
[]
no_license
prakhar199/C-plus-plus-Programing-
ee892436272b79f6bdb62fe099398b4c56122d8b
e3073ec96ac8c7db6b0ecfbdb74ccc8858ea0559
refs/heads/main
2023-01-10T02:05:46.039732
2020-11-15T11:05:45
2020-11-15T11:05:45
311,301,849
0
0
null
null
null
null
UTF-8
C++
false
false
768
cpp
//program to build a simple calculator using switch statement #include <iostream> using namespace std; main() { char oper; float num1,num2; cout<<"Enter an operator (+,-,*,/): "; cin>>oper; cout<< "Enter the two numbers: " <<endl; cin>>num1 >> num2; switch(oper) { case '+': cout<<num1<<"+"<<num2<<"="<<num1+num2; break; case '-': cout<<num1<<"-"<<num2<<"="<<num1-num2; break; case '*': cout<<num1<<"*"<<num2<<"="<<num1*num2; break; case '/': cout<<num1<<"/"<<num2<<"="<<num1/num2; break; //if operator is invalid default: cout<<"Error! the operator does not match"; break; } }
[ "noreply@github.com" ]
prakhar199.noreply@github.com