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
ff0f8063d62f2d694996cb6596cc8f677db676c0
6dc2cd09d43e37d83840e422efb164e5d3d60077
/Ape/Rendering/Effect/src/PlainQuad.cpp
15aa3097a1eaaf233328fdec813b599f3a2928b9
[]
no_license
andyprowl/ape
c98badeec3ed275a96860fae6dc294ff71164927
2b7d25957ac7856cd45b5b484c33664f2cc5af54
refs/heads/master
2020-09-14T23:24:17.447725
2020-02-29T00:36:57
2020-02-29T00:36:57
223,287,544
5
0
null
null
null
null
UTF-8
C++
false
false
1,986
cpp
#include <Ape/Rendering/Effect/PlainQuad.hpp> #include <Ape/Rendering/Effect/PlainQuadVertex.hpp> #include <Glow/BufferObject/VertexArrayObject.hpp> #include <Glow/BufferObject/VertexLayout.hpp> #include <Glow/GpuResource/ScopedBinder.hpp> #include <glad/glad.h> namespace ape { namespace { auto makeVertexBufferObject(std::vector<PlainQuadVertex> const & vertices) -> glow::VertexBufferObject { auto vbo = glow::VertexBufferObject{}; auto const binder = glow::bind(vbo); auto const vertexBufferSize = vertices.size() * sizeof(PlainQuadVertex); glBufferStorage(GL_ARRAY_BUFFER, vertexBufferSize, vertices.data(), 0); glow::sendVertexLayoutToGpu<PlainQuadVertex>(); return vbo; } auto makeArrayObject(glow::VertexBufferObject const & vertexBuffer) -> glow::VertexArrayObject { auto arrayObject = glow::VertexArrayObject{}; auto const binder = glow::bind(arrayObject); vertexBuffer.bind(); glow::sendVertexLayoutToGpu<PlainQuadVertex>(); return arrayObject; } } // unnamed namespace PlainQuad::PlainQuad() : vertexBuffer{makeVertices()} , arrayObject{makeArrayObject(vertexBuffer)} { } auto PlainQuad::getVertexBuffer() const -> const glow::VertexBufferObject & { return vertexBuffer; } auto PlainQuad::getArrayObject() const -> const glow::VertexArrayObject & { return arrayObject; } auto PlainQuad::getNumOfVertices() const -> int { return 6; } auto PlainQuad::makeVertices() const -> glow::VertexBufferObject { auto vao = glow::VertexArrayObject{}; auto const binder = glow::bind(vao); auto const vertices = std::vector<PlainQuadVertex>{ {{-1.0f, +1.0f}, {+0.0f, +1.0f}}, {{-1.0f, -1.0f}, {+0.0f, +0.0f}}, {{+1.0f, -1.0f}, {+1.0f, +0.0f}}, {{-1.0f, +1.0f}, {+0.0f, +1.0f}}, {{+1.0f, -1.0f}, {+1.0f, +0.0f}}, {{+1.0f, +1.0f}, {+1.0f, +1.0f}}}; return makeVertexBufferObject(vertices); } } // namespace ape
[ "andy.prowl@gmail.com" ]
andy.prowl@gmail.com
8fd9ebd5df445b3d7cea72120959757b1cd43c96
f773348c59228adb3000ff0b5f731b40c247fe84
/src/vnninputconnectorfile.h
01da4ced51dc91a5aa6c62008afaf20389b4187b
[ "Apache-2.0" ]
permissive
jolibrain/libvnn
c28fea95aa4dc8f7dfb3b1f8635d5237a4c3f5e8
0b7869c95dd0037db716157827659cfca6148443
refs/heads/master
2020-05-16T11:26:45.869612
2019-04-26T03:47:03
2019-04-26T03:47:03
183,016,620
3
0
null
null
null
null
UTF-8
C++
false
false
1,595
h
/** * libvnn * Copyright (c) 2018 JoliBrain * Author: Nicolas Bertrand <nicolas@davionbertrand.net> * * This file is part of libvnn. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License */ #ifndef VNNINPUTCONNECTORFILE_H #define VNNINPUTCONNECTORFILE_H #include "vnninputconnectorstrategy.h" #include <string> namespace vnn { class VnnInputConnectorFile: public VnnInputConnectorStrategy { public: VnnInputConnectorFile() {} VnnInputConnectorFile(const std::string & file_path, const int & duration_s) : _file_path(file_path), _duration_s(duration_s) {} ~VnnInputConnectorFile() {} void init() {}; void set_filepath(std::string &filepath) { _file_path = filepath; } std::string get_input_stream(); std::string _file_path; int _duration_s; }; } #endif
[ "nicolas@indecp.org" ]
nicolas@indecp.org
095463b6139f8775bf5dd161ad8af25bb543c1dd
105cea794f718d34d0c903f1b4b111fe44018d0e
/chrome/browser/policy/messaging_layer/util/manual_test_heartbeat_event_factory.h
50f325c7859cf2f6f481ca05ad31cdc1daf74698
[ "BSD-3-Clause" ]
permissive
blueboxd/chromium-legacy
27230c802e6568827236366afe5e55c48bb3f248
e6d16139aaafff3cd82808a4660415e762eedf12
refs/heads/master.lion
2023-08-12T17:55:48.463306
2023-07-21T22:25:12
2023-07-21T22:25:12
242,839,312
164
12
BSD-3-Clause
2022-03-31T17:44:06
2020-02-24T20:44:13
null
UTF-8
C++
false
false
1,238
h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_MANUAL_TEST_HEARTBEAT_EVENT_FACTORY_H_ #define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_MANUAL_TEST_HEARTBEAT_EVENT_FACTORY_H_ #include "base/no_destructor.h" #include "chrome/browser/profiles/profile_keyed_service_factory.h" namespace reporting { // This class is only used for manual testing purpose. Do not depend on it in // other parts of the production code. class ManualTestHeartbeatEventFactory : public ProfileKeyedServiceFactory { public: static ManualTestHeartbeatEventFactory* GetInstance(); private: friend base::NoDestructor<ManualTestHeartbeatEventFactory>; ManualTestHeartbeatEventFactory(); ~ManualTestHeartbeatEventFactory() override; // BrowserContextKeyedServiceFactyory KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; bool ServiceIsCreatedWithBrowserContext() const override; bool ServiceIsNULLWhileTesting() const override; }; } // namespace reporting #endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UTIL_MANUAL_TEST_HEARTBEAT_EVENT_FACTORY_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
bd164e461f1f241c92b9f5efa69ea74e823d1ae7
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/com/ole32/stg/exp/docfile.cxx
72e6177c50754a709139f58755543bd69f47e8ad
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
39,132
cxx
//+-------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1991 - 1992. // // File: docfile.c // // Contents: DocFile root functions (Stg* functions) // // History: 10-Dec-91 DrewB Created // //--------------------------------------------------------------- #include <exphead.cxx> #pragma hdrstop #include <rpubdf.hxx> #include <expdf.hxx> #include <expst.hxx> #include <dfentry.hxx> #include <logfile.hxx> #include <dirfunc.hxx> #include <wdocfile.hxx> #include <ole2sp.h> #ifdef COORD #include <resource.hxx> #endif #ifdef _MAC #include <ole2sp.h> #endif HRESULT IsNffAppropriate(const LPCWSTR pwcsName); //+-------------------------------------------------------------- // // Function: DfFromLB, private // // Synopsis: Starts a root Docfile on an ILockBytes // // Arguments: [plst] - LStream to start on // [df] - Permissions // [dwStartFlags] - Startup flags // [snbExclude] - Partial instantiation list // [ppdfExp] - DocFile return // [pcid] - Class ID return for opens // // Returns: Appropriate status code // // Modifies: [ppdfExp] // [pcid] // // History: 19-Mar-92 DrewB Created // 18-May-93 AlexT Added pMalloc // // Algorithm: Create and initialize a root transaction level // Create and initialize a public docfile // Create and initialize an exposed docfile // //--------------------------------------------------------------- #ifdef COORD SCODE DfFromLB(CPerContext *ppc, ILockBytes *plst, DFLAGS df, DWORD dwStartFlags, SNBW snbExclude, ITransaction *pTransaction, CExposedDocFile **ppdfExp, CLSID *pcid) #else SCODE DfFromLB(CPerContext *ppc, ILockBytes *plst, DFLAGS df, DWORD dwStartFlags, SNBW snbExclude, CExposedDocFile **ppdfExp, CLSID *pcid) #endif //COORD { SCODE sc, scConv; CRootPubDocFile *prpdf; #ifdef COORD CPubDocFile *ppubdf; CPubDocFile *ppubReturn; CWrappedDocFile *pwdf; CDocfileResource *pdfr = NULL; #endif CDFBasis *pdfb; ULONG ulOpenLock; IMalloc *pMalloc = ppc->GetMalloc(); ppc->AddRef(); olDebugOut((DEB_ITRACE, "In DfFromLB(%p, %p, %X, %lX, %p, %p, %p)\n", pMalloc, plst, df, dwStartFlags, snbExclude, ppdfExp, pcid)); //Take the mutex in the CPerContext, in case there is an IFillLockBytes // trying to write data while we're trying to open. CSafeSem _ss(ppc); olChk(_ss.Take()); #ifdef CHECKCID ULONG cbRead; olChk(plst->ReadAt(CBCLSIDOFFSET, pcid, sizeof(CLSID), &cbRead)); if (cbRead != sizeof(CLSID)) olErr(EH_Err, STG_E_INVALIDHEADER); if (!REFCLSIDEQ(*pcid, DOCFILE_CLASSID)) olErr(EH_Err, STG_E_INVALIDHEADER); #endif #ifdef COORD if (pTransaction != NULL) { //If we've passed in an ITransaction pointer, it indicates that we // want to open or create this docfile as part of a coordinated // transaction. First, we need to find out if there's a docfile // resource manager for that transaction currently existing in // this process. //First, check if we're opening transacted. If we aren't, then we're // not going to allow this docfile to participate in the // transaction. if (!P_TRANSACTED(df)) { //Is this the right error? olErr(EH_Err, STG_E_INVALIDFUNCTION); } XACTTRANSINFO xti; olChk(pTransaction->GetTransactionInfo(&xti)); EnterCriticalSection(&g_csResourceList); CDocfileResource *pdfrTemp = g_dfrHead.GetNext(); while (pdfrTemp != NULL) { if (IsEqualBOID(pdfrTemp->GetUOW(), xti.uow)) { //Direct hit. pdfr = pdfrTemp; break; } pdfrTemp = pdfrTemp->GetNext(); } if (pdfr == NULL) { ITransactionCoordinator *ptc; //If there isn't, we need to create one. olChkTo(EH_cs, pTransaction->QueryInterface( IID_ITransactionCoordinator, (void **)&ptc)); pdfr = new CDocfileResource; if (pdfr == NULL) { ptc->Release(); olErr(EH_cs, STG_E_INSUFFICIENTMEMORY); } sc = pdfr->Enlist(ptc); ptc->Release(); if (FAILED(sc)) { pdfr->Release();; olErr(EH_cs, sc); } //Add to list. pdfr->SetNext(g_dfrHead.GetNext()); if (g_dfrHead.GetNext() != NULL) g_dfrHead.GetNext()->SetPrev(pdfr); g_dfrHead.SetNext(pdfr); pdfr->SetPrev(&g_dfrHead); } else { //We'll release this reference below. pdfr->AddRef(); } LeaveCriticalSection(&g_csResourceList); } #endif // Make root olMem(prpdf = new (pMalloc) CRootPubDocFile(pMalloc)); olChkTo(EH_prpdf, scConv = prpdf->InitRoot(plst, dwStartFlags, df, snbExclude, &pdfb, &ulOpenLock, ppc->GetGlobal())); #ifdef COORD if (pTransaction != NULL) { //Set up a fake transaction level at the root. A pointer to // this will be held by the resource manager. The storage pointer // that is passed back to the caller will be a pointer to the // transaction level (non-root) below it. This will allow the // client to write and commit as many times as desired without // the changes ever actually hitting the file. CDfName dfnNull; // auto-initialized to 0 WCHAR wcZero = 0; dfnNull.Set(2, (BYTE *)&wcZero); olMemTo(EH_prpdfInit, pwdf = new (pMalloc) CWrappedDocFile( &dfnNull, ROOT_LUID, (df & ~DF_INDEPENDENT), pdfb, NULL)); olChkTo(EH_pwdf, pwdf->Init(prpdf->GetDF())); prpdf->GetDF()->AddRef(); olMemTo(EH_pwdfInit, ppubdf = new (pMalloc) CPubDocFile( prpdf, pwdf, (df | DF_COORD) & ~DF_INDEPENDENT, ROOT_LUID, pdfb, &dfnNull, 2, pdfb->GetBaseMultiStream())); olChkTo(EH_ppubdf, pwdf->InitPub(ppubdf)); ppubdf->AddXSMember(NULL, pwdf, ROOT_LUID); ppubReturn = ppubdf; } else { ppubReturn = prpdf; } #endif //COORD ppc->SetILBInfo(pdfb->GetBase(), pdfb->GetDirty(), pdfb->GetOriginal(), ulOpenLock); ppc->SetLockInfo(ulOpenLock != 0, df); // Make exposed #ifdef COORD //We don't need to AddRef ppc since it starts with a refcount of 1. olMemTo(EH_ppcInit, *ppdfExp = new (pMalloc) CExposedDocFile( ppubReturn, pdfb, ppc)); if (pTransaction != NULL) { CExposedDocFile *pexpdf; olMemTo(EH_ppcInit, pexpdf = new (pMalloc) CExposedDocFile( prpdf, pdfb, ppc)); ppc->AddRef(); sc = pdfr->Join(pexpdf); if (FAILED(sc)) { pexpdf->Release(); olErr(EH_ppcInit, sc); } pdfr->Release(); } #else olMemTo(EH_ppcInit, *ppdfExp = new (pMalloc) CExposedDocFile( prpdf, pdfb, ppc)); #endif //COORD olDebugOut((DEB_ITRACE, "Out DfFromLB => %p\n", *ppdfExp)); return scConv; EH_ppcInit: // The context will release this but we want to keep it around // so take a reference pdfb->GetOriginal()->AddRef(); pdfb->GetBase()->AddRef(); pdfb->GetDirty()->AddRef(); if (ulOpenLock > 0 && ppc->GetGlobal() == NULL) { // The global context doesn't exist, so we need to release // the open lock explicitly. ReleaseOpen(pdfb->GetOriginal(), df, ulOpenLock); } // The open lock has now been released (either explicitly or by ppc) ulOpenLock = 0; #ifdef COORD EH_ppubdf: if (pTransaction != NULL) { ppubdf->vRelease(); } EH_pwdfInit: if (pTransaction != NULL) { prpdf->GetDF()->Release(); } EH_pwdf: if (pTransaction != NULL) { pwdf->Release(); } EH_prpdfInit: #endif //COORD pdfb->GetDirty()->Release(); pdfb->GetBase()->Release(); if (ulOpenLock > 0) ReleaseOpen(pdfb->GetOriginal(), df, ulOpenLock); pdfb->SetDirty(NULL); pdfb->SetBase(NULL); EH_prpdf: prpdf->ReleaseLocks(plst); prpdf->vRelease(); #ifdef COORD if ((pTransaction != NULL) && (pdfr != NULL)) { pdfr->Release(); } goto EH_Err; EH_cs: LeaveCriticalSection(&g_csResourceList); #endif EH_Err: ppc->Release(); return sc; } //+-------------------------------------------------------------- // // Function: DfFromName, private // // Synopsis: Starts a root DocFile from a base name // // Arguments: [pwcsName] - Name // [df] - Permissions // [dwStartFlags] - Startup flags // [snbExclude] - Partial instantiation list // [ppdfExp] - Docfile return // [pcid] - Class ID return for opens // // Returns: Appropriate status code // // Modifies: [ppdfExp] // [pcid] // // History: 19-Mar-92 DrewB Created // 18-May-93 AlexT Add per file allocator // // Notes: [pwcsName] is treated as unsafe memory // //--------------------------------------------------------------- // This set of root startup flags is handled by the multistream // and doesn't need to be set for filestreams #define RSF_MSF (RSF_CONVERT | RSF_TRUNCATE | RSF_ENCRYPTED) #ifdef COORD SCODE DfFromName(WCHAR const *pwcsName, DFLAGS df, DWORD dwStartFlags, SNBW snbExclude, ITransaction *pTransaction, CExposedDocFile **ppdfExp, ULONG *pulSectorSize, CLSID *pcid) #else SCODE DfFromName(WCHAR const *pwcsName, DFLAGS df, DWORD dwStartFlags, SNBW snbExclude, CExposedDocFile **ppdfExp, ULONG *pulSectorSize, CLSID *pcid) #endif { IMalloc *pMalloc; CFileStream *plst; CPerContext *ppc; CFileStream *plst2 = NULL; SCODE sc; CMSFHeader *phdr = NULL; BOOL fCreated; olDebugOut((DEB_ITRACE, "In DfFromName(%ws, %lX, %lX, %p, %p, %p)\n", pwcsName, df, dwStartFlags, snbExclude, ppdfExp, pcid)); olHChk(DfCreateSharedAllocator(&pMalloc, df & DF_LARGE)); // Start an ILockBytes from the named file olMemTo(EH_Malloc, plst = new (pMalloc) CFileStream(pMalloc)); olChkTo(EH_plst, plst->InitGlobal(dwStartFlags & ~RSF_MSF, df)); sc = plst->InitFile(pwcsName); fCreated = SUCCEEDED(sc) && ((dwStartFlags & RSF_CREATE) || pwcsName == NULL); if (sc == STG_E_FILEALREADYEXISTS && (dwStartFlags & RSF_MSF)) { plst->SetStartFlags(dwStartFlags & ~(RSF_MSF | RSF_CREATE)); sc = plst->InitFile(pwcsName); } olChkTo(EH_plst, sc); if (!(dwStartFlags & RSF_CREATE)) { ULONG cbDiskSector = (dwStartFlags & RSF_NO_BUFFERING) ? plst->GetSectorSize() : HEADERSIZE; olMemTo (EH_plstInit, phdr = (CMSFHeader*) TaskMemAlloc (cbDiskSector)); ULARGE_INTEGER ulOffset = {0,0}; ULONG ulRead; olChkTo (EH_plstInit, plst->ReadAt(ulOffset,phdr,cbDiskSector,&ulRead)); if (ulRead < sizeof(CMSFHeaderData)) olErr (EH_plstInit, STG_E_FILEALREADYEXISTS); sc = phdr->Validate(); if (sc == STG_E_INVALIDHEADER) sc = STG_E_FILEALREADYEXISTS; olChkTo (EH_plstInit, sc); if (phdr->GetSectorShift() > SECTORSHIFT512) { IMalloc *pMalloc2 = NULL; CGlobalFileStream *pgfst = plst->GetGlobal(); #ifdef MULTIHEAP CSharedMemoryBlock *psmb; BYTE *pbBase; ULONG ulHeapName; #endif df |= DF_LARGE; // reallocate objects from task memory dwStartFlags |= (phdr->GetSectorShift() <<12) & RSF_SECTORSIZE_MASK; // create and initialize the task allocator #ifdef MULTIHEAP g_smAllocator.GetState (&psmb, &pbBase, &ulHeapName); #endif olChkTo(EH_taskmem, DfCreateSharedAllocator(&pMalloc2, TRUE)); pMalloc->Release(); pMalloc = pMalloc2; olMemTo(EH_taskmem, plst2 = new (pMalloc2) CFileStream(pMalloc2)); olChkTo(EH_taskmem, plst2->InitGlobal(dwStartFlags & ~RSF_MSF, df)); plst2->InitFromFileStream (plst); plst2->GetGlobal()->InitFromGlobalFileStream (pgfst); #ifdef MULTIHEAP g_smAllocator.SetState (psmb, pbBase, ulHeapName, NULL, NULL); g_smAllocator.Uninit(); // unmap newly created heap g_smAllocator.SetState (NULL, NULL, 0, NULL, NULL); #endif plst = plst2; // CFileStream was destroyed by Uninit } TaskMemFree ((BYTE*)phdr); phdr = NULL; } //Create the per context olMemTo(EH_plstInit, ppc = new (pMalloc) CPerContext(pMalloc)); olChkTo(EH_ppc, ppc->InitNewContext()); { #ifdef MULTIHEAP CSafeMultiHeap smh(ppc); #endif // Start up the docfile #ifdef COORD sc = DfFromLB(ppc, plst, df, dwStartFlags, snbExclude, pTransaction, ppdfExp, pcid); #else sc = DfFromLB(ppc, plst, df, dwStartFlags, snbExclude, ppdfExp, pcid); #endif //COORD //Either DfFromLB has AddRef'ed the per context or it has failed. //Either way we want to release our reference here. LONG lRet; lRet = ppc->Release(); #ifdef MULTIHEAP olAssert((FAILED(sc)) || (lRet != 0)); #endif if (FAILED(sc)) { if (fCreated || ((dwStartFlags & RSF_CREATE) && !P_TRANSACTED(df))) plst->Delete(); plst->Release(); #ifdef MULTIHEAP if (lRet == 0) { g_smAllocator.Uninit(); } #endif } else if (pulSectorSize != NULL) { *pulSectorSize = (*ppdfExp)->GetPub()->GetBaseMS()->GetSectorSize(); } } pMalloc->Release(); olDebugOut((DEB_ITRACE, "Out DfFromName => %p\n", *ppdfExp)); return sc; EH_ppc: delete ppc; EH_taskmem: if (plst2) plst2->Release(); EH_plstInit: if (fCreated || ((dwStartFlags & RSF_CREATE) && !P_TRANSACTED(df))) plst->Delete(); EH_plst: plst->Release(); EH_Malloc: #ifdef MULTIHEAP g_smAllocator.Uninit(); // unmap newly created heap #endif pMalloc->Release(); EH_Err: if (phdr != NULL) TaskMemFree ((BYTE*)phdr); return sc; } //+-------------------------------------------------------------- // // Function: DfCreateDocfile, public // // Synopsis: Creates a root Docfile on a file // // Arguments: [pwcsName] - Filename // [grfMode] - Permissions // [reserved] - security attributes // [grfAttrs] - Win32 CreateFile attributes // [ppstgOpen] - Docfile return // // Returns: Appropriate status code // // Modifies: [ppstgOpen] // // History: 14-Jan-92 DrewB Created // //--------------------------------------------------------------- STDAPI DfCreateDocfile (WCHAR const *pwcsName, #ifdef COORD ITransaction *pTransaction, #else void *pTransaction, #endif DWORD grfMode, #if WIN32 == 300 LPSECURITY_ATTRIBUTES reserved, #else LPSTGSECURITY reserved, #endif ULONG ulSectorSize, DWORD grfAttrs, IStorage **ppstgOpen) { SafeCExposedDocFile pdfExp; SCODE sc; DFLAGS df; DWORD dwSectorFlag = 0; olLog(("--------::In StgCreateDocFile(%ws, %lX, %lu, %p)\n", pwcsName, grfMode, reserved, ppstgOpen)); olDebugOut((DEB_TRACE, "In StgCreateDocfile(%ws, %lX, %lu, %p)\n", pwcsName, grfMode, reserved, ppstgOpen)); olAssert(sizeof(LPSTGSECURITY) == sizeof(DWORD)); olChkTo(EH_BadPtr, ValidatePtrBuffer(ppstgOpen)); *ppstgOpen = NULL; if (pwcsName) olChk(ValidateNameW(pwcsName, _MAX_PATH)); if (reserved != 0) olErr(EH_Err, STG_E_INVALIDPARAMETER); if (grfMode & STGM_SIMPLE) { if (pTransaction != NULL) { olErr(EH_Err, STG_E_INVALIDFLAG); } if (ulSectorSize > 512) olErr (EH_Err, STG_E_INVALIDPARAMETER); sc = DfCreateSimpDocfile(pwcsName, grfMode, 0, ppstgOpen); goto EH_Err; } olChk(VerifyPerms(grfMode, TRUE)); if ((grfMode & STGM_RDWR) == STGM_READ || (grfMode & (STGM_DELETEONRELEASE | STGM_CONVERT)) == (STGM_DELETEONRELEASE | STGM_CONVERT)) olErr(EH_Err, STG_E_INVALIDFLAG); df = ModeToDFlags(grfMode); if ((grfMode & (STGM_TRANSACTED | STGM_CONVERT)) == (STGM_TRANSACTED | STGM_CONVERT)) df |= DF_INDEPENDENT; if (ulSectorSize > 512) { df |= DF_LARGE; switch (ulSectorSize) { case 4096 : dwSectorFlag = RSF_SECTORSIZE4K; break; case 8192 : dwSectorFlag = RSF_SECTORSIZE8K; break; case 16384 : dwSectorFlag = RSF_SECTORSIZE16K; break; case 32768 : dwSectorFlag = RSF_SECTORSIZE32K; break; default : olErr (EH_Err, STG_E_INVALIDPARAMETER); } } else if (ulSectorSize != 0 && ulSectorSize != 512) olErr (EH_Err, STG_E_INVALIDPARAMETER); #if WIN32 != 200 // // When we create over NFF files, delete them first. // except when we want to preserve encryption information // if( (STGM_CREATE & grfMode) && !(FILE_ATTRIBUTE_ENCRYPTED & grfAttrs)) { if( SUCCEEDED( IsNffAppropriate( pwcsName ) ) ) { if(FALSE == DeleteFileW( pwcsName ) ) { DWORD dwErr = GetLastError(); if( dwErr != ERROR_FILE_NOT_FOUND && dwErr != ERROR_PATH_NOT_FOUND ) { olErr( EH_Err, Win32ErrorToScode( dwErr ) ); } } } } #endif // _CHICAGO_ DfInitSharedMemBase(); #ifdef COORD olChk(sc = DfFromName(pwcsName, df, RSF_CREATE | ((grfMode & STGM_CREATE) ? RSF_TRUNCATE : 0) | ((grfMode & STGM_CONVERT) ? RSF_CONVERT : 0) | ((grfMode & STGM_DELETEONRELEASE) ? RSF_DELETEONRELEASE : 0) | (dwSectorFlag) | ((grfAttrs & FILE_FLAG_NO_BUFFERING) ? RSF_NO_BUFFERING : 0) | ((grfAttrs & FILE_ATTRIBUTE_ENCRYPTED) ? RSF_ENCRYPTED : 0), NULL, pTransaction, &pdfExp, NULL, NULL)); #else olChk(sc = DfFromName(pwcsName, df, RSF_CREATE | ((grfMode & STGM_CREATE) ? RSF_TRUNCATE : 0) | ((grfMode & STGM_CONVERT) ? RSF_CONVERT : 0) | ((grfMode & STGM_DELETEONRELEASE) ? RSF_DELETEONRELEASE : 0) | (dwSectorFlag) | ((grfAttrs & FILE_FLAG_NO_BUFFERING) ? RSF_NO_BUFFERING : 0) | ((grfAttrs & FILE_ATTRIBUTE_ENCRYPTED) ? RSF_ENCRYPTED : 0), NULL, &pdfExp, NULL, NULL)); #endif //COORD TRANSFER_INTERFACE(pdfExp, IStorage, ppstgOpen); EH_Err: olDebugOut((DEB_TRACE, "Out StgCreateDocfile => %p, ret == %lx\n", *ppstgOpen, sc)); olLog(("--------::Out StgCreateDocFile(). *ppstgOpen == %p, ret == %lx\n", *ppstgOpen, sc)); EH_BadPtr: FreeLogFile(); return _OLERETURN(sc); } //+-------------------------------------------------------------- // // Function: StgCreateDocfile, public // // Synopsis: Creates a root Docfile on a file // // Arguments: [pwcsName] - Filename // [grfMode] - Permissions // [reserved] - security attributes // [ppstgOpen] - Docfile return // // Returns: Appropriate status code // // Modifies: [ppstgOpen] // // History: 14-Jan-92 DrewB Created // //--------------------------------------------------------------- STDAPI StgCreateDocfile(WCHAR const *pwcsName, DWORD grfMode, LPSTGSECURITY reserved, IStorage **ppstgOpen) { return DfCreateDocfile(pwcsName, NULL, grfMode, reserved, 0, 0, ppstgOpen); } //+-------------------------------------------------------------- // // Function: StgCreateDocfileOnILockBytes, public // // Synopsis: Creates a root Docfile on an lstream // // Arguments: [plkbyt] - LStream // [grfMode] - Permissions // [reserved] - Unused // [ppstgOpen] - Docfile return // // Returns: Appropriate status code // // Modifies: [ppstgOpen] // // History: 14-Jan-92 DrewB Created // //--------------------------------------------------------------- STDAPI StgCreateDocfileOnILockBytes(ILockBytes *plkbyt, DWORD grfMode, DWORD reserved, IStorage **ppstgOpen) { IMalloc *pMalloc; CPerContext *ppc; SafeCExposedDocFile pdfExp; SCODE sc; DFLAGS df; #ifdef MULTIHEAP CPerContext pcSharedMemory (NULL); #endif olLog(("--------::In StgCreateDocFileOnILockBytes(%p, %lX, %lu, %p)\n", plkbyt, grfMode, reserved, ppstgOpen)); olDebugOut((DEB_TRACE, "In StgCreateDocfileOnILockBytes(" "%p, %lX, %lu, %p)\n", plkbyt, grfMode, reserved, ppstgOpen)); olChk(ValidatePtrBuffer(ppstgOpen)); *ppstgOpen = NULL; olChk(ValidateInterface(plkbyt, IID_ILockBytes)); if (reserved != 0) olErr(EH_Err, STG_E_INVALIDPARAMETER); if ((grfMode & (STGM_CREATE | STGM_CONVERT)) == 0) olErr(EH_Err, STG_E_FILEALREADYEXISTS); olChk(VerifyPerms(grfMode, TRUE)); if (grfMode & STGM_DELETEONRELEASE) olErr(EH_Err, STG_E_INVALIDFUNCTION); df = ModeToDFlags(grfMode); if ((grfMode & (STGM_TRANSACTED | STGM_CONVERT)) == (STGM_TRANSACTED | STGM_CONVERT)) df |= DF_INDEPENDENT; DfInitSharedMemBase(); olHChk(DfCreateSharedAllocator(&pMalloc, TRUE)); #ifdef MULTIHEAP // Because a custom ILockbytes can call back into storage code, // possibly using another shared heap, we need a temporary // owner until the real CPerContext is allocated // new stack frame for CSafeMultiHeap constructor/destructor { pcSharedMemory.GetThreadAllocatorState(); CSafeMultiHeap smh(&pcSharedMemory); #endif //Create the per context olMem(ppc = new (pMalloc) CPerContext(pMalloc)); olChkTo(EH_ppc, ppc->InitNewContext()); #ifdef COORD sc = DfFromLB(ppc, plkbyt, df, RSF_CREATE | ((grfMode & STGM_CREATE) ? RSF_TRUNCATE : 0) | ((grfMode & STGM_CONVERT) ? RSF_CONVERT : 0), NULL, NULL, &pdfExp, NULL); #else sc = DfFromLB(ppc, plkbyt, df, RSF_CREATE | ((grfMode & STGM_CREATE) ? RSF_TRUNCATE : 0) | ((grfMode & STGM_CONVERT) ? RSF_CONVERT : 0), NULL, &pdfExp, NULL); #endif //COORD pMalloc->Release(); //Either DfFromLB has AddRef'ed the per context or it has failed. //Either way we want to release our reference here. ppc->Release(); olChkTo(EH_Truncate, sc); TRANSFER_INTERFACE(pdfExp, IStorage, ppstgOpen); // Success; since we hold on to the ILockBytes interface, // we must take a reference to it. plkbyt->AddRef(); olDebugOut((DEB_TRACE, "Out StgCreateDocfileOnILockBytes => %p\n", *ppstgOpen)); #ifdef MULTIHEAP } #endif EH_Err: olLog(("--------::Out StgCreateDocFileOnILockBytes(). " "*ppstgOpen == %p, ret == %lx\n", *ppstgOpen, sc)); FreeLogFile(); return ResultFromScode(sc); EH_ppc: delete ppc; goto EH_Err; EH_Truncate: if ((grfMode & STGM_CREATE) && (grfMode & STGM_TRANSACTED) == 0) { ULARGE_INTEGER ulSize; ULISet32(ulSize, 0); olHVerSucc(plkbyt->SetSize(ulSize)); } goto EH_Err; } //+-------------------------------------------------------------- // // Function: DfOpenDocfile, public // // Synopsis: Instantiates a root Docfile from a file, // converting if necessary // // Arguments: [pwcsName] - Name // [pstgPriority] - Priority mode reopen IStorage // [grfMode] - Permissions // [snbExclude] - Exclusions for priority reopen // [reserved] - security attributes // [grfAttrs] - Win32 CreateFile attributes // [ppstgOpen] - Docfile return // // Returns: Appropriate status code // // Modifies: [ppstgOpen] // // History: 14-Jan-92 DrewB Created // //--------------------------------------------------------------- STDAPI DfOpenDocfile(OLECHAR const *pwcsName, #ifdef COORD ITransaction *pTransaction, #else void *pTransaction, #endif IStorage *pstgPriority, DWORD grfMode, SNB snbExclude, LPSTGSECURITY reserved, ULONG *pulSectorSize, DWORD grfAttrs, IStorage **ppstgOpen) { SafeCExposedDocFile pdfExp; SCODE sc; WCHAR awcName[_MAX_PATH]; CLSID cid; olLog(("--------::In StgOpenStorage(%ws, %p, %lX, %p, %lu, %p)\n", pwcsName, pstgPriority, grfMode, snbExclude, reserved, ppstgOpen)); olDebugOut((DEB_TRACE, "In StgOpenStorage(" "%ws, %p, %lX, %p, %lu, %p)\n", pwcsName, pstgPriority, grfMode, snbExclude, reserved, ppstgOpen)); olAssert(sizeof(LPSTGSECURITY) == sizeof(DWORD)); olChk(ValidatePtrBuffer(ppstgOpen)); *ppstgOpen = NULL; if (pstgPriority == NULL) { olChk(ValidateNameW(pwcsName, _MAX_PATH)); StringCbCopyW(awcName, sizeof(awcName), pwcsName); } if (pstgPriority) { STATSTG stat; olChk(ValidateInterface(pstgPriority, IID_IStorage)); olHChk(pstgPriority->Stat(&stat, 0)); if (lstrlenW (stat.pwcsName) > _MAX_PATH) olErr (EH_Err, STG_E_INVALIDNAME); StringCbCopyW(awcName, sizeof(awcName), stat.pwcsName); TaskMemFree(stat.pwcsName); } #if WIN32 != 200 if (grfMode & STGM_SIMPLE) { sc = DfOpenSimpDocfile(pwcsName, grfMode, 0, ppstgOpen); goto EH_Err; } #endif olChk(VerifyPerms(grfMode, TRUE)); if (grfMode & (STGM_CREATE | STGM_CONVERT)) olErr(EH_Err, STG_E_INVALIDFLAG); if (snbExclude) { if ((grfMode & STGM_RDWR) != STGM_READWRITE) olErr(EH_Err, STG_E_ACCESSDENIED); olChk(ValidateSNB(snbExclude)); } if (reserved != 0) olErr(EH_Err, STG_E_INVALIDPARAMETER); if (grfMode & STGM_DELETEONRELEASE) olErr(EH_Err, STG_E_INVALIDFUNCTION); //Otherwise, try it as a docfile if (pstgPriority) olChk(pstgPriority->Release()); DfInitSharedMemBase(); #ifdef COORD olChk(DfFromName(awcName, ModeToDFlags(grfMode), RSF_OPEN | ((grfMode & STGM_DELETEONRELEASE) ? RSF_DELETEONRELEASE : 0) | ((grfAttrs & FILE_FLAG_NO_BUFFERING) ? RSF_NO_BUFFERING : 0), snbExclude, pTransaction, &pdfExp, pulSectorSize, &cid)); #else olChk(DfFromName(awcName, ModeToDFlags(grfMode), RSF_OPEN | ((grfMode & STGM_DELETEONRELEASE) ? RSF_DELETEONRELEASE : 0) | ((grfAttrs & FILE_FLAG_NO_BUFFERING) ? RSF_NO_BUFFERING : 0), snbExclude, &pdfExp, pulSectorSize, &cid)); #endif //COORD TRANSFER_INTERFACE(pdfExp, IStorage, ppstgOpen); olDebugOut((DEB_TRACE, "Out StgOpenStorage => %p\n", *ppstgOpen)); EH_Err: olLog(("--------::Out StgOpenStorage(). *ppstgOpen == %p, ret == %lx\n", *ppstgOpen, sc)); FreeLogFile(); return sc; } //+-------------------------------------------------------------- // // Function: StgOpenStorageOnILockBytes, public // // Synopsis: Instantiates a root Docfile from an LStream, // converting if necessary // // Arguments: [plkbyt] - Source LStream // [pstgPriority] - For priority reopens // [grfMode] - Permissions // [snbExclude] - For priority reopens // [reserved] // [ppstgOpen] - Docfile return // // Returns: Appropriate status code // // Modifies: [ppstgOpen] // // History: 14-Jan-92 DrewB Created // //--------------------------------------------------------------- STDAPI StgOpenStorageOnILockBytes(ILockBytes *plkbyt, IStorage *pstgPriority, DWORD grfMode, SNB snbExclude, DWORD reserved, IStorage **ppstgOpen) { IMalloc *pMalloc; CPerContext *ppc; SCODE sc; SafeCExposedDocFile pdfExp; #ifdef MULTIHEAP CPerContext pcSharedMemory(NULL); #endif CLSID cid; olLog(("--------::In StgOpenStorageOnILockBytes(" "%p, %p, %lX, %p, %lu, %p)\n", plkbyt, pstgPriority, grfMode, snbExclude, reserved, ppstgOpen)); olDebugOut((DEB_TRACE, "In StgOpenStorageOnILockBytes(" "%p, %p, %lX, %p, %lu, %p)\n", plkbyt, pstgPriority, grfMode, snbExclude, reserved, ppstgOpen)); olChk(ValidatePtrBuffer(ppstgOpen)); *ppstgOpen = NULL; olChk(ValidateInterface(plkbyt, IID_ILockBytes)); if (pstgPriority) olChk(ValidateInterface(pstgPriority, IID_IStorage)); olChk(VerifyPerms(grfMode, TRUE)); if (grfMode & (STGM_CREATE | STGM_CONVERT)) olErr(EH_Err, STG_E_INVALIDFLAG); if (grfMode & STGM_DELETEONRELEASE) olErr(EH_Err, STG_E_INVALIDFUNCTION); if (snbExclude) { if ((grfMode & STGM_RDWR) != STGM_READWRITE) olErr(EH_Err, STG_E_ACCESSDENIED); olChk(ValidateSNB(snbExclude)); } if (reserved != 0) olErr(EH_Err, STG_E_INVALIDPARAMETER); if (pstgPriority) olChk(pstgPriority->Release()); IFileLockBytes *pfl; if (SUCCEEDED(plkbyt->QueryInterface(IID_IFileLockBytes, (void **)&pfl)) && ((CFileStream *)plkbyt)->GetContextPointer() != NULL) { //Someone passed us the ILockBytes we gave them from //StgGetIFillLockBytesOnFile. It already contains a //context pointer, so reuse that rather than creating //a whole new shared heap. pfl->Release(); CFileStream *pfst = (CFileStream *)plkbyt; CPerContext *ppc2 = pfst->GetContextPointer(); #ifdef MULTIHEAP CSafeMultiHeap smh(ppc2); #endif #ifdef COORD olChk(DfFromLB(ppc2, pfst, ModeToDFlags(grfMode), pfst->GetStartFlags(), NULL, NULL, &pdfExp, NULL)); #else olChk(DfFromLB(ppc2, pfst, ModeToDFlags(grfMode), pfst->GetStartFlags(), NULL, &pdfExp, NULL)); #endif } else { DfInitSharedMemBase(); olHChk(DfCreateSharedAllocator(&pMalloc, TRUE)); #ifdef MULTIHEAP // Because a custom ILockbytes can call back into storage code, // possibly using another shared heap, we need a temporary // owner until the real CPerContext is allocated // new stack frame for CSafeMultiHeap constructor/destructor { pcSharedMemory.GetThreadAllocatorState(); CSafeMultiHeap smh(&pcSharedMemory); #endif //Create the per context olMem(ppc = new (pMalloc) CPerContext(pMalloc)); sc = ppc->InitNewContext(); if (FAILED(sc)) { delete ppc; olErr(EH_Err, sc); } #ifdef COORD sc = DfFromLB(ppc, plkbyt, ModeToDFlags(grfMode), RSF_OPEN, snbExclude, NULL, &pdfExp, &cid); #else sc = DfFromLB(ppc, plkbyt, ModeToDFlags(grfMode), RSF_OPEN, snbExclude, &pdfExp, &cid); #endif //COORD pMalloc->Release(); //Either DfFromLB has AddRef'ed the per context or it has failed. //Either way we want to release our reference here. ppc->Release(); olChk(sc); #ifdef MULTIHEAP } #endif } TRANSFER_INTERFACE(pdfExp, IStorage, ppstgOpen); // Success; since we hold on to the ILockBytes interface, // we must take a reference to it. plkbyt->AddRef(); olDebugOut((DEB_TRACE, "Out StgOpenStorageOnILockBytes => %p\n", *ppstgOpen)); EH_Err: olLog(("--------::Out StgOpenStorageOnILockBytes(). " "*ppstgOpen == %p, ret == %lx\n", *ppstgOpen, sc)); FreeLogFile(); return sc; } //+--------------------------------------------------------------------------- // // Function: DfGetClass, public // // Synopsis: Retrieves the class ID of the root entry of a docfile // // Arguments: [hFile] - Docfile file handle // [pclsid] - Class ID return // // Returns: Appropriate status code // // Modifies: [pclsid] // // History: 09-Feb-94 DrewB Created // //---------------------------------------------------------------------------- STDAPI DfGetClass(HANDLE hFile, CLSID *pclsid) { SCODE sc; DWORD dwCb; IMalloc *pMalloc; CFileStream *pfst; ULARGE_INTEGER uliOffset; ULONG ulOpenLock, ulAccessLock; BYTE bBuffer[sizeof(CMSFHeader)]; CMSFHeader *pmsh; CDirEntry *pde; olDebugOut((DEB_ITRACE, "In DfGetClass(%p, %p)\n", hFile, pclsid)); olAssert(sizeof(bBuffer) >= sizeof(CMSFHeader)); pmsh = (CMSFHeader *)bBuffer; olAssert(sizeof(bBuffer) >= sizeof(CDirEntry)); pde = (CDirEntry *)bBuffer; if (SetFilePointer(hFile, 0, NULL, FILE_BEGIN) != 0) { olErr(EH_Err, LAST_STG_SCODE); } if (!ReadFile(hFile, pmsh->GetData(), sizeof(CMSFHeaderData), &dwCb, NULL)) { olErr(EH_Err, LAST_STG_SCODE); } if (dwCb != sizeof(CMSFHeaderData)) { olErr(EH_Err, STG_E_INVALIDHEADER); } sc = pmsh->Validate(); olChk(sc); // Now we know it's a docfile DfInitSharedMemBase(); olHChk(DfCreateSharedAllocator(&pMalloc, TRUE)); olMemTo(EH_pMalloc, pfst = new (pMalloc) CFileStream(pMalloc)); olChkTo(EH_pfst, pfst->InitGlobal(0, 0)); olChkTo(EH_pfst, pfst->InitFromHandle(hFile)); // Take open and access locks to ensure that we're cooperating // with real opens olChkTo(EH_pfst, GetOpen(pfst, DF_READ, TRUE, &ulOpenLock)); olChkTo(EH_open, GetAccess(pfst, DF_READ, &ulAccessLock)); #ifdef LARGE_DOCFILE uliOffset.QuadPart = (ULONGLONG)(pmsh->GetDirStart() + 1) << pmsh->GetSectorShift(); #else uliOffset.HighPart = 0; uliOffset.LowPart = (pmsh->GetDirStart()+1) << pmsh->GetSectorShift(); #endif // The root directory entry is always the first directory entry // in the first directory sector // Ideally, we could read just the class ID directly into // pclsid. In practice, all the important things are declared // private or protected so it's easier to read the whole entry olChkTo(EH_access, GetScode(pfst->ReadAt(uliOffset, pde, sizeof(CDirEntry), &dwCb))); if (dwCb != sizeof(CDirEntry)) { sc = STG_E_READFAULT; } else { if (pde->GetFlags() != STGTY_ROOT) olErr (EH_access, STG_E_DOCFILECORRUPT); *pclsid = pde->GetClassId(); sc = S_OK; } olDebugOut((DEB_ITRACE, "Out DfGetClass\n")); EH_access: ReleaseAccess(pfst, DF_READ, ulAccessLock); EH_open: ReleaseOpen(pfst, DF_READ, ulOpenLock); EH_pfst: pfst->Release(); EH_pMalloc: pMalloc->Release(); EH_Err: return ResultFromScode(sc); }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
56c86ab0450194c14d5949239640ea832136a54a
0f840db8cbd4d1d0a1d267634748185a10dd12c5
/calculator/QCalculatorDec.cpp
90008fcff3b190a2f118e9769ba9ecacafcbc290
[]
no_license
piJam/calculator
5f1f6285af7bf9c9c8c222440431cfe702ca701a
d1b81cd2317506806e4aff39d00479f66a368acb
refs/heads/master
2022-04-08T02:47:50.693607
2020-03-04T11:39:31
2020-03-04T11:39:31
239,695,900
0
0
null
null
null
null
UTF-8
C++
false
false
5,542
cpp
#include "QCalculatorDec.h" #include <QDebug> QCalculatorDec::QCalculatorDec() { m_exp = ""; m_result = ""; } QCalculatorDec::~QCalculatorDec() { } bool QCalculatorDec::isDigitOrDot(QChar c) { return ( '0' <= c ) && ( c <= '9' ) || (c =='.'); } bool QCalculatorDec::isSymbol(QChar c) { return isOperator(c) || (c == '(') || (c == ')'); } bool QCalculatorDec::isSign(QChar c) { return (c == '+') || (c == '-'); } bool QCalculatorDec::isNumber(QString s) { bool ret = false; s.toDouble(&ret); return ret; } bool QCalculatorDec::isOperator(QString s) { return (s == "+") || (s == "-") || (s == "*") || (s == "/"); } bool QCalculatorDec::isLeft(QString s) { return (s == "("); } bool QCalculatorDec::isRight(QString s) { return (s == ")"); } int QCalculatorDec::priority(QString s) { int ret = 0; if( (s == "+") || (s == "-") ) { ret = 1; } if( (s == "*") || (s == "/") ) { ret = 2; } return ret; } bool QCalculatorDec::expression(const QString& exp) { bool ret = false; QQueue<QString> exps = split(exp); QQueue<QString> result; m_exp = exp; if( transform(exps, result) ) { m_result = calculate(result); ret = ( m_result != "Error" ); } else { m_result = "Error"; } return ret; } QString QCalculatorDec::result() { return m_result; } QQueue<QString> QCalculatorDec::split(const QString& exp) { QQueue<QString> ret; QString num = ""; QString pre = ""; for( int i=0; i<exp.length(); i++) { if( isDigitOrDot(exp[i]) ) { num += exp[i]; pre = exp[i]; } else if( isSymbol(exp[i]) ) { if( !num.isEmpty() ) { ret.enqueue(num); num.clear(); } if( isSign(exp[i]) && ((pre == "") || (pre == "(") || isOperator(pre)) ) { num += exp[i]; } else { ret.enqueue(exp[i]); } pre = exp[i]; } } if( !num.isEmpty() ) { ret.enqueue(num); } return ret; } bool QCalculatorDec::match(QQueue<QString>& exp) { bool ret = true; QStack<QString> stack; for(int i=0; i<exp.length(); i++) { if( isLeft(exp[i]) ) { stack.push(exp[i]); } else if( isRight(exp[i]) ) { if( isLeft(stack.top()) ) { stack.pop(); } else { ret = false; break; } } } return ret && stack.isEmpty(); } QString QCalculatorDec::calculate(QQueue<QString>& exp) { QStack<QString> stack; QString ret = "Error"; while( !exp.isEmpty() ) { QString e = exp.dequeue(); if( isNumber(e) ) { stack.push(e); } else if ( isOperator(e) ) { QString ro = !stack.isEmpty() ? stack.pop() : ""; QString lo = !stack.isEmpty() ? stack.pop() : ""; QString result = calculate(lo, e, ro); if( result != "Error") { stack.push(result); } else { break; } } else { break; } } if( exp.isEmpty() && stack.size() == 1 && isNumber(stack.top()) ) { ret = stack.pop(); } return ret; } QString QCalculatorDec::calculate(QString l, QString op, QString r) { QString ret = "Error"; if( isNumber(l) && isNumber(r) ) { double ld = l.toDouble(); double rd = r.toDouble(); if( op == "+" ) { ret.sprintf("%f", ld + rd); } else if ( op == "-" ) { ret.sprintf("%f", ld - rd); } else if ( op == "*" ) { ret.sprintf("%f", ld * rd); } else if ( op == "/" ) { const double p = 0.000000000000001; if( (-p < rd) && (rd < p) ) { ret = "Error"; } else { ret.sprintf("%f", ld / rd); } } else { ret = "Error"; } } return ret; } bool QCalculatorDec::transform(QQueue<QString>& exp, QQueue<QString>& output) { bool ret = match(exp); QStack<QString> stack; output.clear(); while( ret && !exp.isEmpty()) { QString e = exp.dequeue(); if( isNumber(e)) { output.enqueue(e); } else if( isOperator(e) ) { while ( !stack.isEmpty() && (priority(e) <= priority(stack.top())) ) { output.enqueue(stack.pop()); } stack.push(e); } else if( isLeft(e) ) { stack.push(e); } else if( isRight(e) ) { while(!stack.isEmpty() && !isLeft(stack.top()) ) { output.enqueue(stack.pop()); } if( !stack.isEmpty() ) { stack.pop(); } } else { ret = false; } } while ( !stack.isEmpty()) { output.enqueue(stack.pop()); } if( !ret ) { output.clear(); } return ret; }
[ "piJam@gmail.com" ]
piJam@gmail.com
1d9e631a1a38f313a06b0ddeb20e3b291de459c7
1e451405a6a642085b007ce6d16923ebff2b1fd0
/lib/RadioHead-148/RHNRFSPIDriver.cpp
a97467dbf569911805b2e4d7fa971625a8fd9453
[]
no_license
jpowen898/RFM69_Test
0d565e9111e5f6c62d08b8d851d299e5970c7e0f
b5d30b91fa69c0abc72c41380c2f05ea54fddf19
refs/heads/master
2020-03-16T21:20:06.735962
2019-03-29T15:05:49
2019-03-29T15:05:49
132,994,829
0
1
null
null
null
null
UTF-8
C++
false
false
2,444
cpp
// RHNRFSPIDriver.cpp // // Copyright (C) 2014 Mike McCauley // $Id: RHNRFSPIDriver.cpp,v 1.2 2014/05/03 00:20:36 mikem Exp $ #include <RHNRFSPIDriver.h> RHNRFSPIDriver::RHNRFSPIDriver(PINS slaveSelectPin, RHGenericSPI& spi) : _spi(spi), _slaveSelectPin(slaveSelectPin) { } bool RHNRFSPIDriver::init() { // start the SPI library with the default speeds etc: // On Arduino Due this defaults to SPI1 on the central group of 6 SPI pins _spi.begin(); // Initialise the slave select pin // On Maple, this must be _after_ spi.begin #if (RH_PLATFORM != RH_PLATFORM_MBED) pinMode(_slaveSelectPin, OUTPUT); #endif digitalWrite(_slaveSelectPin, HIGH); delay(100); return true; } // Low level commands for interfacing with the device uint8_t RHNRFSPIDriver::spiCommand(uint8_t command) { uint8_t status; ATOMIC_BLOCK_START; digitalWrite(_slaveSelectPin, LOW); status = _spi.transfer(command); digitalWrite(_slaveSelectPin, HIGH); ATOMIC_BLOCK_END; return status; } uint8_t RHNRFSPIDriver::spiRead(uint8_t reg) { uint8_t val; ATOMIC_BLOCK_START; digitalWrite(_slaveSelectPin, LOW); _spi.transfer(reg); // Send the address, discard the status val = _spi.transfer(0); // The written value is ignored, reg value is read digitalWrite(_slaveSelectPin, HIGH); ATOMIC_BLOCK_END; return val; } uint8_t RHNRFSPIDriver::spiWrite(uint8_t reg, uint8_t val) { uint8_t status = 0; ATOMIC_BLOCK_START; digitalWrite(_slaveSelectPin, LOW); status = _spi.transfer(reg); // Send the address _spi.transfer(val); // New value follows digitalWrite(_slaveSelectPin, HIGH); ATOMIC_BLOCK_END; return status; } uint8_t RHNRFSPIDriver::spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len) { uint8_t status = 0; ATOMIC_BLOCK_START; digitalWrite(_slaveSelectPin, LOW); status = _spi.transfer(reg); // Send the start address while (len--) *dest++ = _spi.transfer(0); digitalWrite(_slaveSelectPin, HIGH); ATOMIC_BLOCK_END; return status; } uint8_t RHNRFSPIDriver::spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len) { uint8_t status = 0; ATOMIC_BLOCK_START; digitalWrite(_slaveSelectPin, LOW); status = _spi.transfer(reg); // Send the start address while (len--) _spi.transfer(*src++); digitalWrite(_slaveSelectPin, HIGH); ATOMIC_BLOCK_END; return status; }
[ "plowen12@gmail.com" ]
plowen12@gmail.com
7b54906be40b6084c9e7b5c7e4056db476d58543
a3254b9ee437a6fb55dde9037e29fe083b15fedd
/EVGEN/AliGenPromptPhotons.h
bfa7919e9f7fd84a5dad865eb9f0a7b657362d28
[]
permissive
ALICEHLT/AliRoot
d768c99669c9794cf1b73f23076caa336dadb15b
2c786600dd440722389cbb32f6397038fab71bbd
refs/heads/dev
2021-01-23T02:10:15.531036
2018-05-14T15:16:37
2018-05-14T15:16:37
85,963,435
1
5
BSD-3-Clause
2018-04-17T19:04:17
2017-03-23T15:05:30
C++
UTF-8
C++
false
false
4,384
h
#ifndef ALIGENPROMPTPHOTONS_H #define ALIGENPROMPTPHOTONS_H /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ //------------------------------------------------------------------------- // author: Sergey Kiselev, ITEP, Moscow // e-mail: Sergey.Kiselev@cern.ch // tel.: 007 495 129 95 45 //------------------------------------------------------------------------- // Generator of prompt photons for the reaction A+B, sqrt(S) // // main assumptions: // 1. flat rapidity distribution // 2. all existing p+p(pbar) data at y_{c.m.} can be described by the function // F(x_T) = (sqrt(s))^5 Ed^3sigma/d^3p, x_T = 2p_t/sqrt(s) // all data points cover the region x_T: 0.01 - 0.6 // see Nucl.Phys.A783:577-582,2007, hep-ex/0609037 // 3. binary scaling: for A+B at the impact parameter b // Ed^3N^{AB}(b)/d^3p = Ed^3sigma^{pp}/d^3p A B T_{AB}(b), // T_{AB}(b) - nuclear overlapping fuction, calculated in the Glauber approach, // nuclear density is parametrized by a Woods-Saxon with nuclear radius // R_A = 1.19 A^{1/3} - 1.61 A^{-1/3} fm and surface thickness a=0.54 fm // 4. nuclear effects (Cronin, shadowing, ...) are ignored // // input parameters: // fAProjectile, fATarget - number of nucleons in a nucleus A and B // fMinImpactParam - minimal impct parameter, fm // fMaxImpactParam - maximal impct parameter, fm // fEnergyCMS - sqrt(S) per nucleon pair, AGeV // // fYMin - minimal rapidity of photons // fYMax - maximal rapidity of photons // fPtMin - minimal p_t value of gamma, GeV/c // fPtMax - maximal p_t value of gamma, GeV/c //------------------------------------------------------------------------- // comparison with SPS and RHIC data, prediction for LHC can be found in // arXiv:0811.2634 [nucl-th] //------------------------------------------------------------------------- class TF1; #include "AliGenerator.h" class AliGenPromptPhotons : public AliGenerator { public: AliGenPromptPhotons(); AliGenPromptPhotons(Int_t npart); virtual ~AliGenPromptPhotons(); virtual void Generate(); virtual void Init(); virtual void SetPtRange(Float_t ptmin = 0.1, Float_t ptmax=10.); virtual void SetYRange(Float_t ymin = -1., Float_t ymax=1.); // Setters virtual void SetAProjectile(Float_t a = 208) {fAProjectile = a;} virtual void SetATarget(Float_t a = 208) {fATarget = a;} virtual void SetEnergyCMS(Float_t energy = 5500.) {fEnergyCMS = energy;} virtual void SetImpactParameterRange(Float_t bmin = 0., Float_t bmax = 0.) {fMinImpactParam=bmin; fMaxImpactParam=bmax;} protected: Float_t fAProjectile; // Projectile nucleus mass number Float_t fATarget; // Target nucleus mass number Float_t fEnergyCMS; // Center of mass energy Float_t fMinImpactParam; // minimum impact parameter Float_t fMaxImpactParam; // maximum impact parameter static Double_t FitData (const Double_t *xx, const Double_t *par); static Double_t WSforNorm (const Double_t *xx, const Double_t *par); static Double_t WSz (const Double_t *xx, const Double_t *par); static Double_t TA (const Double_t *xx, const Double_t *par); static Double_t TB (const Double_t *xx, const Double_t *par); static Double_t TAxTB (const Double_t *xx, const Double_t *par); static Double_t TAB (const Double_t *xx, const Double_t *par); static TF1 *fgDataPt; // d^{2}#sigma^{pp}/(dp_t dy) from data fit static TF1 *fgWSzA; // Wood Saxon parameterisation for nucleus A static TF1 *fgWSzB; // Wood Saxon parameterisation for nucleus B static TF1 *fgTA; // nuclear thickness function T_A(b) (1/fm**2) static TF1 *fgTB; // nuclear thickness function T_B(phi)=T_B(sqtr(s**2+b**2-2*s*b*cos(phi))) static TF1 *fgTAxTB; // s * TA(s) * 2 * Integral(0,phiMax) TB(phi(s,b)) static TF1 *fgTAB; // overlap function T_AB(b) (1/fm**2) private: AliGenPromptPhotons(const AliGenPromptPhotons & PromptPhotons); AliGenPromptPhotons& operator = (const AliGenPromptPhotons & PromptPhotons) ; ClassDef(AliGenPromptPhotons, 1) // prompt photon generator }; #endif
[ "morsch@f7af4fe6-9843-0410-8265-dc069ae4e863" ]
morsch@f7af4fe6-9843-0410-8265-dc069ae4e863
1a94ec6fd0608cca773a1ea1caa00c72b32b7c80
c2255a97156a963110399a7d7cac768986d7b22b
/Sudoku/my570list.hpp
ebb477375ac4604c295fa4e8c6d079c45ce30b72
[]
no_license
pavangm/Algorithms
cb3dc419e8a2d98b1f62e992ccbf12ce42473212
5350cf26809ed8e262764264132baae2d1156c5a
refs/heads/master
2020-05-25T11:41:06.658141
2012-11-10T06:28:37
2012-11-10T06:28:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,242
hpp
/* * Author: William Chia-Wei Cheng (bill.cheng@acm.org) * * @(#)$Id: my570list.hpp,v 1.1 2011/08/11 04:56:07 william Exp $ */ #ifndef _MY570LIST_H_ #define _MY570LIST_H_ #include "cs570.h" class My570ListElem; class My570List { public: My570List(); virtual ~My570List(); int Length() { return num_members; } int Empty() { return num_members<=0; } int Append(void *obj); int Prepend(void *obj); void Unlink(My570ListElem*); void UnlinkAll(); int InsertBefore(void *obj, My570ListElem *elem); int InsertAfter(void *obj, My570ListElem *elem); My570ListElem *First(); My570ListElem *Last(); My570ListElem *Next(My570ListElem *cur); My570ListElem *Prev(My570ListElem *cur); My570ListElem *Find(void *obj); private: friend class My570ListElem; int num_members; My570ListElem *anchor; }; class My570ListElem { public: My570ListElem(void *object=NULL); virtual ~My570ListElem(); void *Obj() { return obj; } void Set(void *object) { obj = object; } private: friend class My570List; void *obj; My570ListElem *next; My570ListElem *prev; }; #endif /*_MY570LIST_H_*/
[ "pavangm@gmail.com" ]
pavangm@gmail.com
ec6dc8ffd3ce9602a7cbb9e745853d2171a86e0b
c6824080d5db1af9b1c2129eb124dac7ba35c347
/dataview.h
ea4eeb10fc5e7c13c6c797a2aca96d762c3b86d8
[]
no_license
TarasMeln/CPPQT-2019-1-FileServer
d84b295465f22f58340664c16446208efd77ead4
bc3196340c537a8159bb6f1a258e7802f50ef54b
refs/heads/master
2020-05-17T02:43:53.802317
2019-04-18T18:15:35
2019-04-18T18:15:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
82
h
#ifndef DATAVIEW_H #define DATAVIEW_H class DataView { }; #endif // DATAVIEW_H
[ "alex.chmykhalo@gmail.com" ]
alex.chmykhalo@gmail.com
0b1ee0203cfb677a6c7e9e3b1b112178fd8ca228
cd95b5f100f14e66965a331b6386c8dda552f503
/tests/qmlshellunittests/main.cpp
fd187ff18e92a72c8429795fee82e6e203e87b01
[ "Apache-2.0" ]
permissive
e-fever/qmlshell
597e525db201649191f8f1142707a1ece25e4941
093ebdde784ef0d3465a847693030b87fcbe5fa8
refs/heads/master
2021-05-15T14:07:42.091062
2019-03-13T12:31:05
2019-03-13T12:31:05
107,163,171
4
0
null
null
null
null
UTF-8
C++
false
false
1,082
cpp
#include <QString> #include <QtTest> #include <TestRunner> #include <QtQuickTest/quicktest.h> #if defined(Q_OS_MAC) || defined(Q_OS_LINUX) #include <execinfo.h> #include <unistd.h> #include <signal.h> void handleBacktrace(int sig) { void *array[100]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 100); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } #endif namespace AutoTestRegister { QUICK_TEST_MAIN(QuickTests) } int main(int argc, char *argv[]) { #if defined(Q_OS_MAC) || defined(Q_OS_LINUX) signal(SIGSEGV, handleBacktrace); #endif QGuiApplication app(argc, argv); QVariantMap config; config["srcdir"] = SRCDIR; TestRunner runner; runner.addImportPath("qrc:///"); runner.add(QString(SRCDIR) + "qmltests"); runner.setConfig(config); bool error = runner.exec(app.arguments()); if (!error) { qDebug() << "All test cases passed!"; } return error; }
[ "xbenlau@gmail.com" ]
xbenlau@gmail.com
4e8a4bf2d83a0983a746f148768c8b5c6d95860f
0d65d55ae64c2606332d61fa0c60b619f0659f20
/src/RectTransform.cpp
172e4232cb1275b6d4d905015536f8624c39c406
[]
no_license
MarcoPPino/ledWallMapper
3fee5bcde6a1d908991d0607a8471eb6063da3d2
d2085d46ec24dee32fc6ba8afcec43ade8758624
refs/heads/master
2022-04-25T01:39:43.770666
2020-04-22T16:28:52
2020-04-22T16:28:52
256,207,432
1
0
null
null
null
null
UTF-8
C++
false
false
7,188
cpp
#include "RectTransform.hpp" #include "ofApp.h" #include <GLUT/GLUT.h> //-------------------------------------------------------------- void RectTransform::setup(int initX, int initY, int initWidth, int initHeight ){ rec.set(initX, initY, initWidth, initHeight); cornerSize = 10; sideSize = 8; startWidth=0; startHeight=0; } //-------------------------------------------------------------- void RectTransform::update(){ corner1.set(rec.getMinX() - cornerSize / 2, rec.getMinY() - cornerSize / 2, cornerSize, cornerSize); corner2.set(rec.getMaxX() - cornerSize / 2, rec.getMinY() - cornerSize / 2, cornerSize, cornerSize); corner3.set(rec.getMaxX() - cornerSize / 2, rec.getMaxY() - cornerSize / 2, cornerSize, cornerSize); corner4.set(rec.getMinX() - cornerSize / 2, rec.getMaxY() - cornerSize / 2, cornerSize, cornerSize); side1.set(rec.getHorzAnchor(OF_ALIGN_HORZ_CENTER) - sideSize / 2, rec.getMinY() - sideSize / 2, sideSize, sideSize); side2.set(rec.getMaxX() - sideSize / 2, rec.getVertAnchor(OF_ALIGN_VERT_CENTER) - sideSize / 2, sideSize, sideSize); side3.set(rec.getHorzAnchor(OF_ALIGN_HORZ_CENTER) - sideSize / 2, rec.getMaxY() - sideSize / 2, sideSize, sideSize); side4.set(rec.getMinX() - sideSize / 2, rec.getVertAnchor(OF_ALIGN_VERT_CENTER) - sideSize / 2, sideSize, sideSize); x = rec.getX(); y = rec.getY(); width = rec.getWidth(); height = rec.getHeight(); } //-------------------------------------------------------------- void RectTransform::draw(){ ofSetColor(255,255,255); ofNoFill(); ofDrawRectangle(rec); ofDrawRectangle(corner1); ofDrawRectangle(corner2); ofDrawRectangle(corner3); ofDrawRectangle(corner4); ofDrawRectangle(side1); ofDrawRectangle(side2); ofDrawRectangle(side3); ofDrawRectangle(side4); if(insideGlobal == true || insideHandle == true){ string x = ofToString(rec.getX()); string y = ofToString(rec.getY()); string w = ofToString(abs(rec.getWidth())); string h = ofToString(abs(rec.getHeight())); string str; if(insideGlobal == true){ str ="X: " + x + "px" + "\n" + "Y: " + y + "px"; } if(insideHandle == true){ str = "Width: " + w + "px" + "\n" + "Height: " + h + "px"; } if(insideSide1 == true || insideSide3 == true){ str = "Height: " + h + "px"; } if(insideSide2 == true || insideSide4 == true){ str = "Width: " + w + "px"; } ofDrawBitmapStringHighlight(str, ofGetMouseX() - ofGetWidth()/3 + 10, ofGetMouseY() - 10); } } //-------------------------------------------------------------- void RectTransform::keyPressed(int key){ if (OF_KEY_SHIFT) { shiftPressed = true; } } //-------------------------------------------------------------- void RectTransform::keyReleased(int key){ if (OF_KEY_SHIFT) { shiftPressed = false; } } //-------------------------------------------------------------- void RectTransform::mouseDragged(int x, int y, int button){ if(insideGlobal == true && insideHandle == false){ rec.setPosition(x - ofsetX, y - ofsetY); } if(insideCorner1 == true){ if(x < rec.getX() || x > rec.getX()){ rec.set(x, rec.getY(), rec.getMaxX() - x, rec.getHeight()); } if(y < rec.getY() || y > rec.getY()){ rec.set(rec.getX(), y, rec.getWidth(), rec.getMaxY() - y); } } if(insideCorner2 == true){ if(x < rec.getMaxX() || x > rec.getMaxX()){ rec.set(rec.getX(), rec.getY(), x - rec.getX() , rec.getHeight()); } if(y < rec.getMinY() || y > rec.getMinY()){ rec.set(rec.getX(), y, rec.getWidth() , rec.getMaxY() - y); } } if(insideCorner3 == true){ rec.setSize(x - rec.getX(), y - rec.getY()); float factor; if(shiftPressed == true){ if(abs(startWidth - rec.getWidth()) > abs(startHeight - rec.getHeight())){ factor = abs(startWidth - rec.getWidth()); }else{ factor = abs(startHeight - rec.getHeight()); } if(startWidth < rec.getWidth() || startHeight < rec.getHeight() ){ rec.setWidth(startWidth + factor); rec.setHeight(startHeight + factor); }else{ rec.setWidth(startWidth - factor); rec.setHeight(startHeight - factor); } } } if(insideCorner4 == true){ if(x < rec.getMaxX() || x > rec.getMaxX()){ rec.set(x, rec.getY(), rec.getMaxX() - x , rec.getHeight()); } if(y < rec.getMaxY() || y > rec.getMaxY()){ rec.set(rec.getX(), y, rec.getWidth(), rec.getMinY() - y); } } if(insideSide1 == true){ rec.set(rec.getX(), y, rec.getWidth() , rec.getMaxY() - y); } if(insideSide2 == true){ rec.set(rec.getX(), rec.getY(), x - rec.getX() , rec.getHeight()); } if(insideSide3 == true){ rec.set(rec.getX(), rec.getY(), rec.getWidth() , y - rec.getY()); } if(insideSide4 == true){ rec.set(x, rec.getY(), rec.getMaxX() - x , rec.getHeight()); } } //-------------------------------------------------------------- void RectTransform::mousePressed(int x, int y, int button){ if(rec.inside(x,y) && insideGlobal == false){ ofsetX = x - rec.getX(); ofsetY = y - rec.getY(); insideGlobal = true; } if(corner1.inside(x,y) && insideCorner1 == false){ insideCorner1 = true; insideHandle = true; } if(corner2.inside(x,y) && insideCorner2 == false){ insideCorner2 = true; insideHandle = true; } if(corner3.inside(x,y) && insideCorner3 == false){ insideCorner3 = true; insideHandle = true; startWidth = rec.getWidth(); startHeight = rec.getHeight(); } if(corner4.inside(x,y) && insideCorner4 == false){ insideCorner4 = true; insideHandle = true; } if(side1.inside(x,y) && insideSide1 == false){ insideSide1 = true; insideHandle = true; } if(side2.inside(x,y) && insideSide2 == false){ insideSide2 = true; insideHandle = true; } if(side3.inside(x,y) && insideSide3 == false){ insideSide3 = true; insideHandle = true; } if(side4.inside(x,y) && insideSide4 == false){ insideSide4 = true; insideHandle = true; } } //-------------------------------------------------------------- void RectTransform::mouseReleased(int x, int y, int button){ insideGlobal = false; insideHandle = false; insideCorner1 = false; insideCorner2 = false; insideCorner3 = false; insideCorner4 = false; insideSide1 = false; insideSide2 = false; insideSide3 = false; insideSide4 = false; if(!rec.isStandardized()){ rec = rec.getStandardized(); } }
[ "hello@marcopisano.de" ]
hello@marcopisano.de
f83f1c45c7edd7cc5668077010fd6ce7bf1a5a3f
2f10b5f0e22a3cd9f58b894730b82b001fc71fad
/Matrix.h
3ae832652c68f78e537b34b92a45a793c380e6aa
[]
no_license
sxeraverx/CS348A-HW4
63c2987e3262ef00e4ed88bff3c71f9725a93ee3
a1a1272174763669789a1ed92c2139419a59f8e6
refs/heads/master
2016-09-06T21:47:49.862306
2012-03-14T17:57:59
2012-03-14T17:57:59
3,675,564
0
0
null
null
null
null
UTF-8
C++
false
false
1,794
h
#pragma once /* template <typename T, int M, int N> class Matrix { public: class ColumnLookup { private: T *data; ColumnLookup() {} friend class Matrix<T,M,N>; int row; public: T &operator[](int column) {return data[N*row+column];} const T &operator[](int column) const {return data[N*row+column];} }; class ConstColumnLookup { private: const T *data; ConstColumnLookup() {} friend class Matrix<T,M,N>; int row; public: const T &operator[](int column) const {return data[N*row+column];} }; public: static const int width=M; static const int height=N; private: T *data; public: Matrix() //Default constructor is zero matrix { data = new T[M*N]; for(int row = 0; row<M; row++) for(int col = 0; col<N; col++) data[row*N+col] = 0; } ~Matrix() { delete[] data; } Matrix &operator=(const Matrix<T,M,N> &other) { for(int i = 0; i < M; i++) for(int j = 0; j < N; j++) (*this)[i][j] = other[i][j]; } ColumnLookup operator[](int row) {ColumnLookup cl; cl.data=data; cl.row=row; return cl;} ConstColumnLookup operator[](int row) const {ConstColumnLookup ccl; ccl.data=data; ccl.row=row; return ccl;} template <typename T1, int N1> Matrix<typeof(T*T1),M,N1> operator*(const Matrix<T1,N,N1> &other) const { Matrix<typeof(T*T1),M,N1> ret; for(int i = 0; i < M; i++) for(int j = 0; j < N; j++) for(int k = 0; k < N1; k++) ret[i][k]+=(*this)[i][j]*other[j][k]; } }; */
[ "tomek@Charmander.(none)" ]
tomek@Charmander.(none)
0121436a1e962403ba2efdae52ba845dd6e7af0e
37625ec34630e209b8844d5fde6e0538ab8ac16a
/inc/Audio.h
a6e8e8bc49bcefb58aa5b9cb5c15144c5fa0b7c0
[ "Apache-2.0" ]
permissive
hagleitn/GuerrillaRadio
b13869c12e80a92df2b5c3382a0b10515125f88e
2ea6f23753eb66eed47a4fc19c2bdab0c673026b
refs/heads/master
2020-12-24T07:55:45.371633
2017-03-16T05:09:40
2017-03-16T05:09:40
73,353,648
4
0
null
null
null
null
UTF-8
C++
false
false
639
h
/* * Audio.h * * Created on: Nov 12, 2016 * Author: ghagleitner */ #ifndef AUDIO_H_ #define AUDIO_H_ #include <stdint.h> #include "stm32f1xx.h" class Audio { private: TIM_TypeDef *timer; TIM_HandleTypeDef htim; TIM_OC_InitTypeDef hOc; uint32_t channel; GPIO_TypeDef *port; uint32_t pin; unsigned long startTime; uint16_t duration; public: void begin(); void play(uint16_t *samples); void tone(uint16_t freq, uint16_t duration); void update(unsigned long currentTime); Audio(TIM_TypeDef *timer, uint32_t channel, GPIO_TypeDef *port, uint32_t pin); virtual ~Audio(); }; #endif /* AUDIO_H_ */
[ "gunther@apache.org" ]
gunther@apache.org
c721396d6a71e88826f2adc893ca38dd178829c3
eea8becbec0ecd7b10ad9e13c0335d1024499494
/dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.cpp
94bf0d61b64926cb6892d5dc3e4b27c5cee26a9e
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
templeblock/dali-toolkit
30d7643db2e09dd60f5315b844216ce620ee47f6
2b051f9220d4e28225a57d5dabc98e093357cad6
refs/heads/master
2022-10-30T08:19:52.154997
2020-06-19T11:03:58
2020-06-19T11:03:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,368
cpp
/* * Copyright (c) 2017 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.h> // EXTERNAL INCLUDES #include <algorithm> #include <dali/public-api/animation/animation.h> #include <dali/public-api/animation/constraint.h> // INTERNAL INCLUDES #include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h> #include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h> using namespace Dali; using namespace Dali::Toolkit; namespace // unnamed namespace { const float DEFAULT_ITEMS_PER_SPIRAL_TURN = 9.5f; const float DEFAULT_ITEM_SPACING_RADIANS = Math::PI*2.0f/DEFAULT_ITEMS_PER_SPIRAL_TURN; const float DEFAULT_REVOLUTION_DISTANCE = 190.0f; const float DEFAULT_ITEM_DESCENT = DEFAULT_REVOLUTION_DISTANCE / DEFAULT_ITEMS_PER_SPIRAL_TURN; const float DEFAULT_TOP_ITEM_ALIGNMENT = -0.125f; const float DEFAULT_SCROLL_SPEED_FACTOR = 0.01f; const float DEFAULT_MAXIMUM_SWIPE_SPEED = 30.0f; const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.1f; float GetDefaultSpiralRadiusFunction(const Vector3& layoutSize) { return layoutSize.width*0.4f; } struct SpiralPositionConstraint { SpiralPositionConstraint( unsigned int itemId, float spiralRadius, float itemSpacingRadians, float itemDescent, float topItemAlignment ) : mItemId( itemId ), mSpiralRadius( spiralRadius ), mItemSpacingRadians( itemSpacingRadians ), mItemDescent( itemDescent ), mTopItemAlignment( topItemAlignment ) { } inline void OrientationUp( Vector3& current, float layoutPosition, const Vector3& layoutSize ) { float angle = -Math::PI * 0.5f + mItemSpacingRadians * layoutPosition; current.x = -mSpiralRadius * cosf( angle ); current.y = ( mItemDescent * layoutPosition ) + layoutSize.height * mTopItemAlignment; current.z = -mSpiralRadius * sinf( angle ); } inline void OrientationLeft( Vector3& current, float layoutPosition, const Vector3& layoutSize ) { float angle = Math::PI * 0.5f + mItemSpacingRadians * layoutPosition; current.x = ( mItemDescent * layoutPosition ) + layoutSize.width * mTopItemAlignment; current.y = -mSpiralRadius * cosf( angle ); current.z = mSpiralRadius * sinf( angle ); } inline void OrientationDown( Vector3& current, float layoutPosition, const Vector3& layoutSize ) { float angle = Math::PI * 0.5f + mItemSpacingRadians * layoutPosition; current.x = -mSpiralRadius * cosf( angle ); current.y = ( -mItemDescent * layoutPosition ) - layoutSize.height * mTopItemAlignment; current.z = mSpiralRadius * sinf(angle); } inline void OrientationRight( Vector3& current, float layoutPosition, const Vector3& layoutSize ) { float angle = -Math::PI*0.5f + mItemSpacingRadians * layoutPosition; current.x = (-mItemDescent * layoutPosition) - layoutSize.width * mTopItemAlignment; current.y = -mSpiralRadius * cosf( angle ); current.z = -mSpiralRadius * sinf( angle ); } void OrientationUp( Vector3& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); const Vector3& layoutSize = inputs[1]->GetVector3(); OrientationUp( current, layoutPosition, layoutSize ); } void OrientationLeft( Vector3& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); const Vector3& layoutSize = inputs[1]->GetVector3(); OrientationLeft( current, layoutPosition, layoutSize ); } void OrientationDown( Vector3& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); const Vector3& layoutSize = inputs[1]->GetVector3(); OrientationDown( current, layoutPosition, layoutSize ); } void OrientationRight( Vector3& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); const Vector3& layoutSize = inputs[1]->GetVector3(); OrientationRight( current, layoutPosition, layoutSize ); } unsigned int mItemId; float mSpiralRadius; float mItemSpacingRadians; float mItemDescent; float mTopItemAlignment; }; struct SpiralRotationConstraint { SpiralRotationConstraint( unsigned int itemId, float itemSpacingRadians ) : mItemId( itemId ), mItemSpacingRadians( itemSpacingRadians ) { } void OrientationUp( Quaternion& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); float angle = -mItemSpacingRadians * layoutPosition; current = Quaternion( Radian( angle ), Vector3::YAXIS); } void OrientationLeft( Quaternion& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); float angle = -mItemSpacingRadians * layoutPosition; current = Quaternion( Radian( -Math::PI * 0.5f ), Vector3::ZAXIS ) * Quaternion( Radian( angle ), Vector3::YAXIS ); } void OrientationDown( Quaternion& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); float angle = -mItemSpacingRadians * layoutPosition; current = Quaternion( Radian( -Math::PI ), Vector3::ZAXIS) * Quaternion( Radian( angle ), Vector3::YAXIS ); } void OrientationRight( Quaternion& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); float angle = -mItemSpacingRadians * layoutPosition; current = Quaternion( Radian( -Math::PI * 1.5f ), Vector3::ZAXIS) * Quaternion( Radian( angle ), Vector3::YAXIS ); } unsigned int mItemId; float mItemSpacingRadians; }; struct SpiralColorConstraint { SpiralColorConstraint( unsigned int itemId, float itemSpacingRadians ) : mItemId( itemId ), mItemSpacingRadians( itemSpacingRadians ) { } void operator()( Vector4& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); Radian angle( mItemSpacingRadians * fabsf( layoutPosition ) / Dali::ANGLE_360 ); float progress = angle - floorf( angle ); // take fractional bit only to get between 0.0 - 1.0 progress = (progress > 0.5f) ? 2.0f*(1.0f - progress) : progress*2.0f; float darkness(1.0f); { const float startMarker = 0.10f; // The progress at which darkening starts const float endMarker = 0.35f; // The progress at which darkening ends const float minDarkness = 0.15f; // The darkness at end marker if (progress > endMarker) { darkness = minDarkness; } else if (progress > startMarker) { darkness = 1.0f - ( (1.0f - minDarkness) * ((progress-startMarker) / (endMarker-startMarker)) ); } } current.r = current.g = current.b = darkness; } unsigned int mItemId; float mItemSpacingRadians; }; struct SpiralVisibilityConstraint { SpiralVisibilityConstraint( unsigned int itemId, float itemSpacingRadians, float itemDescent, float topItemAlignment ) : mItemId( itemId ), mItemSpacingRadians( itemSpacingRadians ), mItemDescent( itemDescent ), mTopItemAlignment( topItemAlignment ) { } void Portrait( bool& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); const Vector3& layoutSize = inputs[1]->GetVector3(); float itemsCachedBeforeTopItem = layoutSize.height*(mTopItemAlignment+0.5f) / mItemDescent; current = ( layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= ( layoutSize.height / mItemDescent ) + 1.0f ); } void Landscape( bool& current, const PropertyInputContainer& inputs ) { float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); const Vector3& layoutSize = inputs[1]->GetVector3(); float itemsCachedBeforeTopItem = layoutSize.width*(mTopItemAlignment+0.5f) / mItemDescent; current = ( layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= ( layoutSize.width / mItemDescent ) + 1.0f ); } unsigned int mItemId; float mItemSpacingRadians; float mItemDescent; float mTopItemAlignment; }; } // unnamed namespace namespace Dali { namespace Toolkit { namespace Internal { struct SpiralLayout::Impl { Impl() : mItemSpacingRadians(DEFAULT_ITEM_SPACING_RADIANS), mRevolutionDistance(DEFAULT_REVOLUTION_DISTANCE), mItemDescent(DEFAULT_ITEM_DESCENT), mTopItemAlignment(DEFAULT_TOP_ITEM_ALIGNMENT), mScrollSpeedFactor(DEFAULT_SCROLL_SPEED_FACTOR), mMaximumSwipeSpeed(DEFAULT_MAXIMUM_SWIPE_SPEED), mItemFlickAnimationDuration(DEFAULT_ITEM_FLICK_ANIMATION_DURATION) { } float mItemSpacingRadians; float mRevolutionDistance; float mItemDescent; float mTopItemAlignment; float mScrollSpeedFactor; float mMaximumSwipeSpeed; float mItemFlickAnimationDuration; }; SpiralLayoutPtr SpiralLayout::New() { return SpiralLayoutPtr(new SpiralLayout()); } SpiralLayout::~SpiralLayout() { delete mImpl; } void SpiralLayout::SetItemSpacing(Radian itemSpacing) { mImpl->mItemSpacingRadians = itemSpacing; float itemsPerSpiral = std::max(1.0f, (2.0f*(float)Math::PI) / mImpl->mItemSpacingRadians); mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral; } Radian SpiralLayout::GetItemSpacing() const { return Radian( mImpl->mItemSpacingRadians ); } void SpiralLayout::SetRevolutionDistance(float distance) { mImpl->mRevolutionDistance = distance; float itemsPerSpiral = std::max(1.0f, (2.0f*(float)Math::PI) / mImpl->mItemSpacingRadians); mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral; } float SpiralLayout::GetRevolutionDistance() const { return mImpl->mRevolutionDistance; } void SpiralLayout::SetTopItemAlignment(float alignment) { mImpl->mTopItemAlignment = alignment; } float SpiralLayout::GetTopItemAlignment() const { return mImpl->mTopItemAlignment; } void SpiralLayout::SetScrollSpeedFactor(float scrollSpeed) { mImpl->mScrollSpeedFactor = scrollSpeed; } void SpiralLayout::SetMaximumSwipeSpeed(float speed) { mImpl->mMaximumSwipeSpeed = speed; } void SpiralLayout::SetItemFlickAnimationDuration(float durationSeconds) { mImpl->mItemFlickAnimationDuration = durationSeconds; } float SpiralLayout::GetScrollSpeedFactor() const { return mImpl->mScrollSpeedFactor; } float SpiralLayout::GetMaximumSwipeSpeed() const { return mImpl->mMaximumSwipeSpeed; } float SpiralLayout::GetItemFlickAnimationDuration() const { return mImpl->mItemFlickAnimationDuration; } float SpiralLayout::GetMinimumLayoutPosition(unsigned int numberOfItems, Vector3 layoutSize) const { return 1.0f - static_cast<float>(numberOfItems); } float SpiralLayout::GetClosestAnchorPosition(float layoutPosition) const { return round(layoutPosition); } float SpiralLayout::GetItemScrollToPosition(unsigned int itemId) const { return -(static_cast<float>(itemId)); } ItemRange SpiralLayout::GetItemsWithinArea(float firstItemPosition, Vector3 layoutSize) const { float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height; float itemsPerSpiral = layoutHeight / mImpl->mItemDescent; float itemsCachedBeforeTopItem = layoutHeight * (mImpl->mTopItemAlignment + 0.5f) / mImpl->mItemDescent; float itemsViewable = std::min(itemsPerSpiral, itemsPerSpiral - itemsCachedBeforeTopItem - firstItemPosition + 1.0f); unsigned int firstItem = static_cast<unsigned int>(std::max(0.0f, -firstItemPosition - itemsCachedBeforeTopItem - 1.0f)); unsigned int lastItem = static_cast<unsigned int>(std::max(0.0f, firstItem + itemsViewable)); return ItemRange(firstItem, lastItem+1); } unsigned int SpiralLayout::GetReserveItemCount(Vector3 layoutSize) const { float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height; return static_cast<unsigned int>(layoutHeight / mImpl->mItemDescent); } void SpiralLayout::GetDefaultItemSize( unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize ) const { itemSize.width = layoutSize.width * 0.25f; // 4x3 aspect ratio itemSize.height = itemSize.depth = ( itemSize.width / 4.0f ) * 3.0f; } Degree SpiralLayout::GetScrollDirection() const { Degree scrollDirection(0); const ControlOrientation::Type orientation = GetOrientation(); if ( orientation == ControlOrientation::Up ) { scrollDirection = Degree( -45.0f ); // Allow swiping horizontally & vertically } else if ( orientation == ControlOrientation::Left ) { scrollDirection = Degree( 45.0f ); } else if ( orientation == ControlOrientation::Down ) { scrollDirection = Degree( 180.0f - 45.0f ); } else // orientation == ControlOrientation::Right { scrollDirection = Degree( 270.0f - 45.0f ); } return scrollDirection; } void SpiralLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor ) { // This just implements the default behaviour of constraint application. // Custom layouts can override this function to apply their custom constraints. Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast( itemViewActor ); if( itemView ) { const ControlOrientation::Type orientation = GetOrientation(); // Position constraint SpiralPositionConstraint positionConstraint( itemId, GetDefaultSpiralRadiusFunction( layoutSize ), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment ); Constraint constraint; if ( orientation == ControlOrientation::Up ) { constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationUp ); } else if ( orientation == ControlOrientation::Left ) { constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationLeft ); } else if ( orientation == ControlOrientation::Down ) { constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationDown ); } else // orientation == ControlOrientation::Right { constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationRight ); } constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); constraint.AddSource( ParentSource( Actor::Property::SIZE ) ); constraint.Apply(); // Rotation constraint SpiralRotationConstraint rotationConstraint( itemId, mImpl->mItemSpacingRadians ); if ( orientation == ControlOrientation::Up ) { constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationUp ); } else if ( orientation == ControlOrientation::Left ) { constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationLeft ); } else if ( orientation == ControlOrientation::Down ) { constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationDown ); } else // orientation == ControlOrientation::Right { constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationRight ); } constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); constraint.Apply(); // Color constraint constraint = Constraint::New< Vector4 >( actor, Actor::Property::COLOR, SpiralColorConstraint( itemId, mImpl->mItemSpacingRadians ) ); constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); constraint.SetRemoveAction(Dali::Constraint::Discard); constraint.Apply(); // Visibility constraint SpiralVisibilityConstraint visibilityConstraint( itemId, mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment ); if (IsVertical( orientation ) ) { constraint = Constraint::New< bool >( actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Portrait ); } else // horizontal { constraint = Constraint::New< bool >( actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Landscape ); } constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); constraint.AddSource( ParentSource( Actor::Property::SIZE ) ); constraint.SetRemoveAction(Dali::Constraint::Discard); constraint.Apply(); } } void SpiralLayout::SetSpiralLayoutProperties(const Property::Map& properties) { // Set any properties specified for SpiralLayout. for( unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx ) { KeyValuePair propertyPair = properties.GetKeyValue( idx ); switch(DefaultItemLayoutProperty::Property(propertyPair.first.indexKey)) { case DefaultItemLayoutProperty::SPIRAL_ITEM_SPACING: { SetItemSpacing(Radian(propertyPair.second.Get<float>())); break; } case DefaultItemLayoutProperty::SPIRAL_MAXIMUM_SWIPE_SPEED: { SetMaximumSwipeSpeed(propertyPair.second.Get<float>()); break; } case DefaultItemLayoutProperty::SPIRAL_TOP_ITEM_ALIGNMENT: { SetTopItemAlignment(propertyPair.second.Get<float>()); break; } case DefaultItemLayoutProperty::SPIRAL_SCROLL_SPEED_FACTOR: { SetScrollSpeedFactor(propertyPair.second.Get<float>()); break; } case DefaultItemLayoutProperty::SPIRAL_REVOLUTION_DISTANCE: { SetRevolutionDistance(propertyPair.second.Get<float>()); break; } case DefaultItemLayoutProperty::SPIRAL_ITEM_FLICK_ANIMATION_DURATION: { SetItemFlickAnimationDuration(propertyPair.second.Get<float>()); break; } default: { break; } } } } Vector3 SpiralLayout::GetItemPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) const { Vector3 itemPosition = Vector3::ZERO; const ControlOrientation::Type orientation = GetOrientation(); SpiralPositionConstraint positionConstraint( itemID, GetDefaultSpiralRadiusFunction( layoutSize ), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment ); if ( orientation == ControlOrientation::Up ) { positionConstraint.OrientationUp( itemPosition, currentLayoutPosition + itemID, layoutSize ); } else if ( orientation == ControlOrientation::Left ) { positionConstraint.OrientationLeft( itemPosition, currentLayoutPosition + itemID, layoutSize ); } else if ( orientation == ControlOrientation::Down ) { positionConstraint.OrientationDown( itemPosition, currentLayoutPosition + itemID, layoutSize ); } else //orientation == ControlOrientation::Right { positionConstraint.OrientationRight( itemPosition, currentLayoutPosition + itemID, layoutSize ); } return itemPosition; } SpiralLayout::SpiralLayout() : mImpl(NULL) { mImpl = new Impl(); } float SpiralLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) { return GetItemScrollToPosition(itemID); } } // namespace Internal } // namespace Toolkit } // namespace Dali
[ "adeel.kazmi@samsung.com" ]
adeel.kazmi@samsung.com
540e9180b9abd6c919cd95ee3bf8a8e794166aa4
ddb74dba641341468cb47b68adff73282755b07a
/9.2/ex2.cpp
d3cc0988d22759d628a974c489be29388456c822
[]
no_license
physicshinzui/CppFundation
32f6afc944862ad787111f173049cff9fb3af4b1
69ce6726addd3b7bbc015422fff83c41e9485204
refs/heads/master
2023-04-16T17:37:50.888415
2021-04-25T12:29:21
2021-04-25T12:29:21
330,292,676
0
0
null
null
null
null
UTF-8
C++
false
false
743
cpp
#include <iostream> using namespace std; //0,1,... are assigned to each name automatically. namespace StudentNames { enum StudentNames { jack, // 0 nami, // 1 bob, // 2 max_students // 3 }; } //note : unlike enum, enum class does not convert names into integers implicitly. enum class StudentSomething { shin, masu, tom, max_student }; int main() { int testScores[StudentNames::max_students]{}; testScores[StudentNames::nami] = 100; cout << testScores[StudentNames::nami] << endl; cout << testScores[1] << endl; cout << testScores[StudentNames::bob] << endl; cout << StudentNames::bob << endl; //bob = 10; Error. can'be assigned. return 0; }
[ "physicshinzui@gmail.com" ]
physicshinzui@gmail.com
45f1cacea176d2e4be7a743318ad4d61a5dc7373
6be8f0b25fe420c89310f446fb173a7c26e6fb02
/np_hw2_type2.cpp
f956989b04dd2b5bac353d25869a9b698afa65dc
[]
no_license
itsPG/NP_hw2
ea49276eb8c9ac095d8c20edd7df9fbe20a10ff6
9b851dab6655a6028bc29d068d36e4d670bb0214
refs/heads/master
2020-04-28T02:05:48.532086
2011-11-24T12:13:44
2011-11-24T12:13:44
2,721,300
0
0
null
null
null
null
UTF-8
C++
false
false
12,308
cpp
#include <iostream> #include <sstream> #include <fstream> #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <errno.h> #include <wait.h> #include <fcntl.h> #include <sys/stat.h> #include <ctype.h> #include <sys/socket.h> #include <arpa/inet.h> #include <map> #include <signal.h> #include <sys/ipc.h> #include <sys/shm.h> #include <signal.h> #define ROOT_DIC "/home/PG/PG/" #define DEBUG 0 #define PIPEMAX 100000 #define PIPEADD 10000000 #define PROG_TYPE 2 using namespace std; void welcome_msg() { cout << "****************************************" << endl; cout << "** Welcome to the information server. **" << endl; cout << "****************************************" << endl; } string i2s(int q) { ostringstream sout; sout << q; return sout.str(); } int s2i(string q) { int r; istringstream ssin(q); ssin >> r; return r; } #include "np_hw2_shell.cpp" class PG_MSGBOX { }; class PG_FIFO { public: int BUFMAX; int fd; char *buf; string str; PG_FIFO() { BUFMAX = 100000; buf = new char[BUFMAX+1]; } void fifo_open(string q) { q = "/tmp/" + q; mkfifo(q.c_str(),0666); fd = open(q.data(),O_RDWR|O_NONBLOCK); if(fd<0)perror("open"); //else cout << "created " << q << " fd is " << fd << endl; } string get() { string r = ""; int t; t = read(fd,buf,BUFMAX); buf[t] = '\0'; r = buf; return r; } void put(string q) { if(write(fd,q.c_str(),q.size())<0)perror("write"); } ~PG_FIFO() { delete buf; } }; class PG_share_memory { public: int shm_id, user_id; struct PG_extra_data { char msg[31][11][2001]; char name[31][31]; int user_max; int user_flag[31], pipe_used_flag[31]; int m[31]; int port[31]; char ip[31][20]; int pid[31]; }; PG_extra_data *buf; PG_share_memory() { } void logout(int uid) { buf->m[uid] = 0; buf->user_flag[uid] = 0; buf->pipe_used_flag[uid] = 0; strcpy(buf->name[uid], "(no name)"); } int create() { int r = shmget(IPC_PRIVATE, 700000, 0666); if (r < 0){perror("create");} if ( (buf = (PG_extra_data*)shmat(r, 0, 0)) < (PG_extra_data*)0 )perror("link of create"); /****************** init start ************************/ buf->user_max = 0; for (int i = 1; i <=30; i++) { logout(i); } /****************** init end ************************/ shmdt((void*)r); return r; } void link(int q) { shm_id = q; if ( (buf = (PG_extra_data*)shmat(q, 0, 0)) < (PG_extra_data*)0 )perror("link"); } void unlink(int q) { shmdt((void*)shm_id); } void login(string ip, int port) { for (int i = 1; i <= 30; i++) { if (buf->user_flag[i] == 0) { user_id = i; buf->user_max = i; buf->user_flag[i] = 1; strcpy(buf->ip[i], ip.c_str()); buf->port[i] = port; buf->pid[i] = getpid(); if (DEBUG)cout << "ip : " << buf->ip[i] << endl; if (DEBUG)cout << "port : " << buf->port[i] << endl; return; } } } void send_msg(int to,string q) { if (!buf->user_flag[to])return; if (buf->m[to] >= 10)return; strcpy(buf->msg[to][ ++buf->m[to] ], q.c_str()); for (int i = 1; i <= 30; i++) { if (buf->user_flag[i]) { kill(buf->pid[i], SIGUSR1); //if (kill(buf->pid[i], SIGUSR1) == -1)perror("fail to send signal"); } } } string recv_msg(int id) { string r = "", t; for (int i = 1; i <= buf->m[id]; i++) { t = buf->msg[id][i]; r += t + "\n"; } buf->m[id] = 0; return r; } void recv_msg() { cout << recv_msg(user_id); } void test() { int t; cin >> t; if(t==-1) shm_id = create(); else shm_id = t; cout << "shm_id " << shm_id << endl; link(shm_id); if (t != -1) { cout << recv_msg(7) << endl; return; } string tmp; cin >> tmp; send_msg(7,"****************"); send_msg(7,tmp); send_msg(7,"!!!!!!!!!!!!!!!!"); //strcpy(buf->msg[1][2], tmp.c_str()); //buf->m[13] = 3510; unlink(shm_id); } }; PG_share_memory share_memory; class PG_global_pipe { public: PG_FIFO FIFO[31]; void init() { string fn; for (int i = 1; i <= 30; i++) { fn = "test_"+i2s(i); FIFO[i].fifo_open(fn); } } }; class PG_ChatRoom { public: PG_global_pipe global_pipe; PG_FIFO FIFO; int uid; string ID; void init_firsttime() { int t = share_memory.create(); if (DEBUG)cout << "id is " << t << endl; ofstream fout("/tmp/PG_autoid"); fout << t << endl; fout.close(); } //void broadcast(string q, int f); //void broadcast(string q); void init(string ip, int port) { int t; ifstream fin("/tmp/PG_autoid"); fin >> t; fin.close(); if (DEBUG)cout << "shmid is" << t << endl; if (DEBUG)cout << "ChatRoom will init with " << ip << " / " << port << endl; ostringstream sout; sout << ip << "/" << port; ID = sout.str(); share_memory.link(t); share_memory.login(ip,port); uid = share_memory.user_id; global_pipe.init(); //cout << "the ID of this user is " << ID << endl; broadcast("*** User \'(no name)\' entered from " + ID + ". ***"); } string recv_msg() { return share_memory.recv_msg(uid); } void broadcast(string q) { //cout.flush(); //cout << "broadcast ==== " << q << endl; for (int i = 1; i <= 30; i++) { share_memory.send_msg(i, q); } } void broadcast(string q, int f) { for (int i = 1; i <= 30; i++) { if (i!=f) share_memory.send_msg(i, q); } } void cmd_who() { cout << "<ID>\t<nickname>\t<IP/port>\t<indicate me>" << endl; for (int i = 1; i <= 30; i++) { if (share_memory.buf->user_flag[i]) { cout << i << "\t" << share_memory.buf->name[i] << "\t" ; cout << share_memory.buf->ip[i] << "/" << share_memory.buf->port[i] << "\t"; if (i == uid) cout << "<- me"; cout << endl; } } } void cmd_tell(int to, string &msg) { ostringstream sout; if(!share_memory.buf->user_flag[to]) { sout << "*** Error: user #" << to << " does not exist yet. ***" << endl; share_memory.send_msg(uid, sout.str()); } else { sout << "*** " << share_memory.buf->name[uid] << " told you ***:" << msg; share_memory.send_msg(to, sout.str()); } } void cmd_yell(string &msg) { for (int i = 1; i <= 30; i++) { ostringstream sout; sout << "*** " << share_memory.buf->name[uid] << " yelled " << msg; share_memory.send_msg(i, sout.str()); } } void cmd_name(string q) { strcpy(share_memory.buf->name[uid], q.c_str()); //) ostringstream sout; //<< //cout << q.size() << endl; sout << "*** User from " << ID << " is named \'" << q << "\'. ***"; broadcast(sout.str()); } void test() { int id = share_memory.user_id; uid = id; cout << "this is client id " << share_memory.user_id << endl; while (1) { string str; str = share_memory.recv_msg(id); cout << "-------------msg list --------" << endl; cout << str; cout << "------------ end --------" << endl; cout << "select id to talk "; int t; cin >> t; cout << "type some words : "; cin.ignore(); getline(cin, str); share_memory.send_msg(t, str); } } void logout() { ostringstream sout; sout << "*** User \'" << share_memory.buf->name[uid] << "\' left. ***"; broadcast(sout.str(), uid); share_memory.logout(uid); } ~PG_ChatRoom() { share_memory.buf->user_max--; } }; void handler(int signo) { //cout << "handler start" << endl; share_memory.recv_msg(); //cout << "handler end" << endl; } void shell_main(PG_ChatRoom &ChatRoom) { PG_pipe Elie; PG_cmd Tio; PG_process Rixia; int seq_no = 0,pid; PG_TCP Noel; chdir(ROOT_DIC); Noel.go(); //cout << "before SIGUSER" << endl; if (signal(SIGUSR1,handler) == SIG_ERR) { perror("cant regist SIGUSR1"); } welcome_msg(); //cout << "1" << endl; ChatRoom.init(Noel.my_ip, getpid()); //cout << "2" << endl; while (1) { //cout << "-----msg_start-----" << endl; //////cout << ChatRoom.recv_msg(); //cout << "-----msg_end-----" << endl; //cout << " / pid : " << getpid(); cout << "% "; Tio.seq_no = ++seq_no; Tio.read(); //////cout << ChatRoom.recv_msg(); Tio.parse(); //Tio.show(); if (Tio.exit_flag) { ChatRoom.logout(); exit(0); } int pipe_to = 0; if(Tio.delay) { pipe_to = seq_no + Tio.delay; Elie.connect(seq_no, pipe_to); } //cout << "before fork" << endl; string tmp = Tio.chk_all_cmd(); if (tmp != "") { cout << tmp; continue; } if (pid = Rixia.harmonics()) { Elie.fix_main(seq_no); Rixia.Wait(); if (Tio.setenv())continue; if (Tio.send_to_user_flag) { int uid = ChatRoom.uid; string name = share_memory.buf->name[uid], Tio_cmd = Tio.cmd; Tio_cmd.erase(Tio_cmd.size()-1,1); if (share_memory.buf->pipe_used_flag[uid]) { } else { ostringstream sout; sout << "*** " << name << " (#" << i2s(uid) << ") just piped \'" << Tio_cmd; sout << "\' into his/her pipe. ***"; share_memory.buf->pipe_used_flag[uid] = 1; ChatRoom.broadcast(sout.str()); } } if (Tio.recv_from_user) { int uid = ChatRoom.uid; string name = share_memory.buf->name[uid], Tio_cmd = Tio.cmd; Tio_cmd.erase(Tio_cmd.size()-1,1); //cout << "recv from user" << endl; if (share_memory.buf->pipe_used_flag[Tio.recv_from_user] == 0) { } else { ostringstream sout; sout << "*** " << name << " (#" << i2s(uid) << ") just received from the pipe #" << Tio.recv_from_user; sout << " by \'" << Tio_cmd << "\' ***"; share_memory.buf->pipe_used_flag[Tio.recv_from_user] = 0; ChatRoom.broadcast(sout.str()); } } } else { Elie.fix_stdin(seq_no); if (Tio.pipe_err_flag) Elie.fix_stdout(seq_no,1); else Elie.fix_stdout(seq_no,0); Elie.clean_pipe(); if (Tio.redirect_to != "") Elie.redirect_to_file(Tio.redirect_to); int uid = ChatRoom.uid; string name = share_memory.buf->name[uid], Tio_cmd = Tio.cmd; Tio_cmd.erase(Tio_cmd.size()-1,1); if (Tio.recv_from_user) { //cout << "recv from user" << endl; if (share_memory.buf->pipe_used_flag[Tio.recv_from_user] == 0) { cout << "*** Error: the pipe from #" << Tio.recv_from_user << " does not exist yet. ***" << endl; exit(0); } else { ostringstream sout; sout << "*** " << name << " (#" << i2s(uid) << ") just received from the pipe #" << Tio.recv_from_user; sout << " by \'" << Tio_cmd << "\' ***"; //ChatRoom.broadcast(sout.str()); //share_memory.buf->pipe_used_flag[Tio.recv_from_user] = 0; Elie.recv_from_user(ChatRoom.global_pipe.FIFO[Tio.recv_from_user].fd); } } if (Tio.send_to_user_flag) { if (share_memory.buf->pipe_used_flag[uid]) { cout << "*** Error: your pipe already exists. ***" << endl; exit(0); } else { //cout << "name ~" << name << "~" << endl; ostringstream sout; sout << "*** " << name << " (#" << i2s(uid) << ") just piped \'" << Tio_cmd; sout << "\' into his/her pipe. ***"; //ChatRoom.broadcast(sout.str()); //share_memory.buf->pipe_used_flag[uid] = 1; Elie.send_to_user(ChatRoom.global_pipe.FIFO[ChatRoom.uid].fd, Tio.send_to_user_flag); } } if (Tio.ext_cmd != "") { if (Tio.ext_cmd == "who") { ChatRoom.cmd_who(); exit(0); } if (Tio.ext_cmd == "tell") { ChatRoom.cmd_tell(Tio.ext_cmd_clientID, Tio.chat_msg); exit(0); } if (Tio.ext_cmd == "yell") { ChatRoom.cmd_yell(Tio.chat_msg); exit(0); } if (Tio.ext_cmd == "name") { ChatRoom.cmd_name(Tio.chat_msg); exit(0); } } if(Tio.pipe_seg.size() > 2) { pipe_exec(Elie, Tio, 0, Tio.pipe_seg.size()-2); exit(0); cerr << "failed to exit" << endl; } else { Tio.exec(); } } } } int main(int argc, char* argv[]) { PG_ChatRoom ChatRoom; if (argc == 2 && strcmp(argv[1],"init") == 0) { ChatRoom.init_firsttime(); } shell_main(ChatRoom); if (argc == 2 && strcmp(argv[1],"init") == 0) { ChatRoom.init_firsttime(); } else { //ChatRoom.init(); cout << "$$$$$$" << endl; ChatRoom.test(); } return 0; /* PG_share_memory PGB; PGB.test(); return 0; PG_global_pipe PG; PG.test(); return 0; */ shell_main(ChatRoom); }
[ "smartPG@gmail.com" ]
smartPG@gmail.com
3e9f6672344f5f7eb3fcfe6c7ab3243d23d62a11
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
/Windows多线程编程技术与实例/第3章/第3节/namedPipe/NamedPipe1.h
63b1de65a9b502246757866338ab5a97262a61b5
[]
no_license
IgorYunusov/Mega-collection-cpp-1
c7c09e3c76395bcbf95a304db6462a315db921ba
42d07f16a379a8093b6ddc15675bf777eb10d480
refs/heads/master
2020-03-24T10:20:15.783034
2018-06-12T13:19:05
2018-06-12T13:19:05
142,653,486
3
1
null
2018-07-28T06:36:35
2018-07-28T06:36:35
null
UTF-8
C++
false
false
1,500
h
// NamedPipe1.h: interface for the CNamedPipe class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_NAMEDPIPE1_H__D497FC47_C9B5_4780_9254_D769A1766E72__INCLUDED_) #define AFX_NAMEDPIPE1_H__D497FC47_C9B5_4780_9254_D769A1766E72__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <string> using namespace std; #define PIPE_BUF_SIZE 1024 #define PIPE_TIMEOUT (120*1000) /*120 seconds*/ class CNamedPipe { public: CNamedPipe(); virtual ~CNamedPipe(); bool Initialize(bool bAsServer, string szStopListnenCmd, void (WINAPI *fCallBack)(string buf)); static DWORD WINAPI ListnerProc(LPVOID lpParameter); struct ListnerParam { HANDLE hPipe; // Handle to pipe to listne to... string szStopCmd; // Stop listen when this is read. void (WINAPI *funcCallBack)(string buf); // Call this function for every successful read operation. }; protected: string m_szPipeName; string m_szPipeHost; string m_szFullPipeName; HANDLE m_hPipe; // HANDLE m_hInPipe; HANDLE m_hListner; DWORD m_dwListnerThreadId; public: void SetPipeName(string szName, string szHost = "."); string GetPipeName() { return m_szFullPipeName; } // string GetRealPipeName(bool bIsServerInPipe); bool Send(string szMsg); }; #endif // !defined(AFX_NAMEDPIPE1_H__D497FC47_C9B5_4780_9254_D769A1766E72__INCLUDED_)
[ "wyrover@gmail.com" ]
wyrover@gmail.com
40494b8e51770af5e150e59f3506f2219f8042f6
c3fbfd6d249a63304b6080ce13c68fa6d5271326
/TheClaw/src/main/include/Commands/PuncherControl.h
b23c903bb7eecc990a5dae56a578efe7a88facb9
[]
no_license
SteelRidgeRobotics/2019Build
0318b736ff4e24d80d5ea2c26df4e94795364679
c221192ea47d19388ffd6c5f485e4d9c742ffd16
refs/heads/master
2020-04-16T16:56:00.909280
2019-11-08T01:21:06
2019-11-08T01:21:06
165,755,983
0
1
null
null
null
null
UTF-8
C++
false
false
1,126
h
// 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. #ifndef PUNCHERCONTROL_H #define PUNCHERCONTROL_H #include "frc/commands/Subsystem.h" #include "Robot.h" /** * * * @author ExampleAuthor */ class PuncherControl: public frc::Command { public: // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR PuncherControl(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR void Initialize() override; void Execute() override; bool IsFinished() override; void End() override; void Interrupted() override; private: // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLES // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLES }; #endif
[ "Nerf12402@users.noreply.github.com" ]
Nerf12402@users.noreply.github.com
b376a63747e438a336fe4a83d54278285d7f0d72
ec68c973b7cd3821dd70ed6787497a0f808e18e1
/Cpp/SDK/Quest_OverworldPOI_ElfQueen_functions.cpp
a71faa417532a0a28a45a4d3df387973ed6f6189
[]
no_license
Hengle/zRemnant-SDK
05be5801567a8cf67e8b03c50010f590d4e2599d
be2d99fb54f44a09ca52abc5f898e665964a24cb
refs/heads/main
2023-07-16T04:44:43.113226
2021-08-27T14:26:40
2021-08-27T14:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,874
cpp
// Name: Remnant, Version: 1.0 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function Quest_OverworldPOI_ElfQueen.Quest_OverworldPOI_ElfQueen_C.TurnDownBugVolume // () void AQuest_OverworldPOI_ElfQueen_C::TurnDownBugVolume() { static auto fn = UObject::FindObject<UFunction>("Function Quest_OverworldPOI_ElfQueen.Quest_OverworldPOI_ElfQueen_C.TurnDownBugVolume"); AQuest_OverworldPOI_ElfQueen_C_TurnDownBugVolume_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Quest_OverworldPOI_ElfQueen.Quest_OverworldPOI_ElfQueen_C.ResetBugVolume // () void AQuest_OverworldPOI_ElfQueen_C::ResetBugVolume() { static auto fn = UObject::FindObject<UFunction>("Function Quest_OverworldPOI_ElfQueen.Quest_OverworldPOI_ElfQueen_C.ResetBugVolume"); AQuest_OverworldPOI_ElfQueen_C_ResetBugVolume_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Quest_OverworldPOI_ElfQueen.Quest_OverworldPOI_ElfQueen_C.ExecuteUbergraph_Quest_OverworldPOI_ElfQueen // () void AQuest_OverworldPOI_ElfQueen_C::ExecuteUbergraph_Quest_OverworldPOI_ElfQueen() { static auto fn = UObject::FindObject<UFunction>("Function Quest_OverworldPOI_ElfQueen.Quest_OverworldPOI_ElfQueen_C.ExecuteUbergraph_Quest_OverworldPOI_ElfQueen"); AQuest_OverworldPOI_ElfQueen_C_ExecuteUbergraph_Quest_OverworldPOI_ElfQueen_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
01cf8f6bb9c5f0e54bb6489dd00e2f5fe6b8c4e9
8192807f1af938f9cd0668dbd0f54431560ff2e7
/test/main.cpp
de4ff8e96afeb158ba3a4688a4b8e6f2f7dd3f21
[ "BSD-3-Clause" ]
permissive
PlumpMath/Jcoroutine
e741d130f7e6d1df28ec155465ecf3151945b958
3cd0f91daf75fcc5b4c9a07e550ae8bee9a8a8bb
refs/heads/master
2021-01-20T09:54:17.130835
2016-11-24T13:48:16
2016-11-24T13:48:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,013
cpp
#include <iostream> #include"../src/schedule.h" #include"../src/coroutine.h" #include<memory> using namespace JC; struct args{ int n; }; void func(std::shared_ptr<Schedule> s,void *ud){ struct args* arg = (args*)ud; int start = arg->n; for(int i=0;i<50;i++){ std::cout<<"coroutine "<<s->getCurCoroutineId()<<" "<<start+i<<std::endl; s->yield(); } } void test(){ args arg1{1}; args arg2{101}; int co_num = 2; std::shared_ptr<Schedule> s(new Schedule(co_num)); int id1=0,id2=1; std::shared_ptr<Coroutine> co1(new Coroutine(s,std::bind(&func,s,&arg1),id1)); std::shared_ptr<Coroutine> co2(new Coroutine(s,std::bind(&func,s,&arg2),id2)); s->add(co1); s->add(co2); int count = 0; while(co1->getStatus()||co2->getStatus()){ if(count==5) s->remove(id1); if(count==40) s->remove(id2); s->resume(id1); s->resume(id2); count++; } } int main(int argc, char *argv[]) { test(); return 0; }
[ "643274003@qq.com" ]
643274003@qq.com
9d7eafb77d6a518cfa9cea001b31a2cb2ec9db64
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/components/history_clusters/core/history_clusters_types.h
cb12e25ad2938d405455343eef05e0924c88df2c
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
6,602
h
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_HISTORY_CLUSTERS_CORE_HISTORY_CLUSTERS_TYPES_H_ #define COMPONENTS_HISTORY_CLUSTERS_CORE_HISTORY_CLUSTERS_TYPES_H_ #include <string> #include <vector> #include "base/containers/flat_set.h" #include "base/functional/callback.h" #include "components/history/core/browser/history_types.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace history_clusters { // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class ClusteringRequestSource { kAllKeywordCacheRefresh = 0, kShortKeywordCacheRefresh = 1, kJourneysPage = 2, kNewTabPage = 3, // New values go above here. kMaxValue = kNewTabPage, }; struct QueryClustersFilterParams { QueryClustersFilterParams(); QueryClustersFilterParams(const QueryClustersFilterParams&); ~QueryClustersFilterParams(); // Parameters related to the minimum requirements for returned clusters. // The minimum number of non-hidden visits that are required for returned // clusters. Note that this also implicitly works as a visit filter such that // if fewer than `min_total_visits` are in a cluster, it will be filtered out. int min_visits = 0; // The minimum number of visits within a cluster that have associated images. // Note that this also implicitly works as a visit filter such that if fewer // than `min_visits_with_images` are in a cluster, it will be filtered out. int min_visits_with_images = 0; // The category IDs that a cluster must be a part of for it to be included. // If both `categories_allowlist` and `categories_blocklist` are empty, the // returned clusters will not be filtered. base::flat_set<std::string> categories_allowlist; // The category IDs that a cluster must not contain for it to be included. // If both `categories_allowlist` and `categories_blocklist` are empty, the // returned clusters will not be filtered. base::flat_set<std::string> categories_blocklist; // Whether all clusters returned are search-initiated. bool is_search_initiated = false; // Whether all clusters returned must have associated related searches. bool has_related_searches = false; // Whether the returned clusters will be shown on prominent UI surfaces. bool is_shown_on_prominent_ui_surfaces = false; // Whether to exclude clusters that have interaction state equal to done. bool filter_done_clusters = false; // Whether to exclude visits that have interaction state equal to hidden. bool filter_hidden_visits = false; // Whether to include synced visits. bool include_synced_visits = false; // Whether to return merged clusters that are similar based on content. bool group_clusters_by_content = false; }; struct QueryClustersContinuationParams { QueryClustersContinuationParams() = default; QueryClustersContinuationParams(base::Time continuation_time, bool is_continuation, bool is_partial_day, bool exhausted_unclustered_visits, bool exhausted_all_visits) : continuation_time(continuation_time), is_continuation(is_continuation), is_partial_day(is_partial_day), exhausted_unclustered_visits(exhausted_unclustered_visits), exhausted_all_visits(exhausted_all_visits) {} // Returns a `QueryClustersContinuationParams` representing the done state. // Most of the values don't matter, but `exhausted_unclustered_visits` and // `exhausted_all_visits` should be true. static const QueryClustersContinuationParams DoneParams() { static QueryClustersContinuationParams kDoneParams = {base::Time(), true, false, true, true}; return kDoneParams; } // The time already fetched visits up to and where the next request will // continue. base::Time continuation_time = base::Time(); // False for the first request, true otherwise. bool is_continuation = false; // True if left off midday; i.e. not a day boundary. This occurs when the max // visit threshold was reached. bool is_partial_day = false; // True if unclustered visits were exhausted. If we're searching oldest to // newest, this is true iff `exhausted_all_visits` is true. Otherwise, this // may be true before `exhausted_all_visits` is true but not the reverse. bool exhausted_unclustered_visits = false; // True if both unclustered and clustered were exhausted. bool exhausted_all_visits = false; }; using QueryClustersCallback = base::OnceCallback<void(std::vector<history::Cluster>, QueryClustersContinuationParams)>; // Tracks which fields have been or are pending recording. This helps 1) avoid // re-recording fields and 2) determine whether a visit is complete (i.e. has // all expected fields recorded). struct RecordingStatus { // Whether `url_row` and `visit_row` have been set. bool history_rows = false; // Whether a navigation has ended; i.e. another navigation has begun in the // same tab or the navigation's tab has been closed. bool navigation_ended = false; // Whether the `context_annotations` associated with navigation end have been // set. Should only be true if both `history_rows` and `navigation_ended` are // true. bool navigation_end_signals = false; // Whether the UKM `page_end_reason` `context_annotations` is expected to be // set. bool expect_ukm_page_end_signals = false; // Whether the UKM `page_end_reason` `context_annotations` has been set. // Should only be true if `expect_ukm_page_end_signals` is true. bool ukm_page_end_signals = false; }; // A partially built VisitContextAnnotations with its state of completeness and // associated `URLRow` and `VisitRow` which are necessary to build it. struct IncompleteVisitContextAnnotations { IncompleteVisitContextAnnotations(); IncompleteVisitContextAnnotations(const IncompleteVisitContextAnnotations&); ~IncompleteVisitContextAnnotations(); RecordingStatus status; history::URLRow url_row; history::VisitRow visit_row; history::VisitContextAnnotations context_annotations; }; // Used to track incomplete, unpersisted visits. using IncompleteVisitMap = std::map<int64_t, IncompleteVisitContextAnnotations>; } // namespace history_clusters #endif // COMPONENTS_HISTORY_CLUSTERS_CORE_HISTORY_CLUSTERS_TYPES_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
91c72180bed4d1ff9fdd0895dc5b0bc770801bc2
9d9c27c5fe52838bed8c6ea9d7c2ad7ae997a54a
/Library/Cegui/cegui/src/RendererModules/OpenGL3/Texture.cpp
cc20d3badfef02c131efc71bcf05144df0fc0789
[]
no_license
respu/xsilium-engine
f19fe3ea41fb8d8b2010c225bf3cadc2b31ce5e8
36a282616c055b24c44882c8f219ba72eec269c7
refs/heads/master
2021-01-15T17:36:51.212274
2013-06-07T07:20:54
2013-06-07T07:20:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,584
cpp
/*********************************************************************** filename: CEGUIOpenGLTexture.cpp created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include <GL/glew.h> #include "CEGUI/RendererModules/OpenGL3/Texture.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/ImageCodec.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// OpenGL3Texture::OpenGL3Texture(OpenGL3Renderer& owner, const String& name) : d_size(0, 0), d_grabBuffer(0), d_dataSize(0, 0), d_texelScaling(0, 0), d_owner(owner), d_name(name) { initInternalPixelFormatFields(PF_RGBA); generateOpenGLTexture(); } //----------------------------------------------------------------------------// OpenGL3Texture::OpenGL3Texture(OpenGL3Renderer& owner, const String& name, const String& filename, const String& resourceGroup) : d_size(0, 0), d_grabBuffer(0), d_dataSize(0, 0), d_owner(owner), d_name(name) { initInternalPixelFormatFields(PF_RGBA); generateOpenGLTexture(); loadFromFile(filename, resourceGroup); } //----------------------------------------------------------------------------// OpenGL3Texture::OpenGL3Texture(OpenGL3Renderer& owner, const String& name, const Sizef& size) : d_size(0, 0), d_grabBuffer(0), d_dataSize(0, 0), d_owner(owner), d_name(name) { initInternalPixelFormatFields(PF_RGBA); generateOpenGLTexture(); setTextureSize(size); } //----------------------------------------------------------------------------// OpenGL3Texture::OpenGL3Texture(OpenGL3Renderer& owner, const String& name, GLuint tex, const Sizef& size) : d_ogltexture(tex), d_size(size), d_grabBuffer(0), d_dataSize(size), d_owner(owner), d_name(name) { initInternalPixelFormatFields(PF_RGBA); updateCachedScaleValues(); } //----------------------------------------------------------------------------// void OpenGL3Texture::initInternalPixelFormatFields(const PixelFormat fmt) { d_isCompressed = false; switch (fmt) { case PF_RGBA: d_format = GL_RGBA; d_subpixelFormat = GL_UNSIGNED_BYTE; break; case PF_RGB: d_format = GL_RGB; d_subpixelFormat = GL_UNSIGNED_BYTE; break; case PF_RGB_565: d_format = GL_RGB; d_subpixelFormat = GL_UNSIGNED_SHORT_5_6_5; break; case PF_RGBA_4444: d_format = GL_RGBA; d_subpixelFormat = GL_UNSIGNED_SHORT_4_4_4_4; break; case PF_RGB_DXT1: d_format = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. d_isCompressed = true; break; case PF_RGBA_DXT1: d_format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. d_isCompressed = true; break; case PF_RGBA_DXT3: d_format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. d_isCompressed = true; break; case PF_RGBA_DXT5: d_format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. d_isCompressed = true; break; default: CEGUI_THROW(RendererException( "invalid or unsupported CEGUI::PixelFormat.")); } } //----------------------------------------------------------------------------// OpenGL3Texture::~OpenGL3Texture() { cleanupOpenGLTexture(); } //----------------------------------------------------------------------------// const String& OpenGL3Texture::getName() const { return d_name; } //----------------------------------------------------------------------------// const Sizef& OpenGL3Texture::getSize() const { return d_size; } //----------------------------------------------------------------------------// const Sizef& OpenGL3Texture::getOriginalDataSize() const { return d_dataSize; } //----------------------------------------------------------------------------// const Vector2f& OpenGL3Texture::getTexelScaling() const { return d_texelScaling; } //----------------------------------------------------------------------------// void OpenGL3Texture::loadFromFile(const String& filename, const String& resourceGroup) { // Note from PDT: // There is somewhat tight coupling here between OpenGL3Texture and the // ImageCodec classes - we have intimate knowledge of how they are // implemented and that knowledge is relied upon in an unhealthy way; this // should be addressed at some stage. // load file to memory via resource provider RawDataContainer texFile; System::getSingleton().getResourceProvider()-> loadRawDataContainer(filename, texFile, resourceGroup); // get and check existence of CEGUI::System (needed to access ImageCodec) System* sys = System::getSingletonPtr(); if (!sys) CEGUI_THROW(RendererException( "CEGUI::System object has not been created: " "unable to access ImageCodec.")); Texture* res = sys->getImageCodec().load(texFile, this); // unload file data buffer System::getSingleton().getResourceProvider()-> unloadRawDataContainer(texFile); if (!res) // It's an error CEGUI_THROW(RendererException( sys->getImageCodec().getIdentifierString() + " failed to load image '" + filename + "'.")); } //----------------------------------------------------------------------------// void OpenGL3Texture::loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format) { if (!isPixelFormatSupported(pixel_format)) CEGUI_THROW(InvalidRequestException( "Data was supplied in an unsupported pixel format.")); initInternalPixelFormatFields(pixel_format); setTextureSize_impl(buffer_size); // store size of original data we are loading d_dataSize = buffer_size; updateCachedScaleValues(); // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // do the real work of getting the data into the texture glBindTexture(GL_TEXTURE_2D, d_ogltexture); if (d_isCompressed) loadCompressedTextureBuffer(buffer_size, buffer); else loadUncompressedTextureBuffer(buffer_size, buffer); // restore previous texture binding. glBindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void OpenGL3Texture::loadUncompressedTextureBuffer(const Sizef& buffer_size, const GLvoid* buffer) const { GLint old_pack; glGetIntegerv(GL_UNPACK_ALIGNMENT, &old_pack); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei>(buffer_size.d_width), static_cast<GLsizei>(buffer_size.d_height), d_format, d_subpixelFormat, buffer); glPixelStorei(GL_UNPACK_ALIGNMENT, old_pack); } //----------------------------------------------------------------------------// void OpenGL3Texture::loadCompressedTextureBuffer(const Sizef& buffer_size, const GLvoid* buffer) const { GLsizei blocksize = 16; if (d_format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT || d_format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) { blocksize = 8; } const GLsizei image_size = ((static_cast<GLsizei>(buffer_size.d_width) + 3) / 4) * ((static_cast<GLsizei>(buffer_size.d_height) + 3) / 4) * blocksize; glCompressedTexImage2D(GL_TEXTURE_2D, 0, d_format, static_cast<GLsizei>(buffer_size.d_width), static_cast<GLsizei>(buffer_size.d_height), 0, image_size, buffer); } //----------------------------------------------------------------------------// void OpenGL3Texture::setTextureSize(const Sizef& sz) { initInternalPixelFormatFields(PF_RGBA); setTextureSize_impl(sz); d_dataSize = d_size; updateCachedScaleValues(); } //----------------------------------------------------------------------------// void OpenGL3Texture::setTextureSize_impl(const Sizef& sz) { const Sizef size(d_owner.getAdjustedTextureSize(sz)); d_size = size; if (d_isCompressed) return; // make sure size is within boundaries GLfloat maxSize; glGetFloatv(GL_MAX_TEXTURE_SIZE, &maxSize); if ((size.d_width > maxSize) || (size.d_height > maxSize)) CEGUI_THROW(RendererException("size too big")); // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // set texture to required size glBindTexture(GL_TEXTURE_2D, d_ogltexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast<GLsizei>(size.d_width), static_cast<GLsizei>(size.d_height), 0, GL_RGBA , GL_UNSIGNED_BYTE, 0); // restore previous texture binding. glBindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void OpenGL3Texture::grabTexture() { // if texture has already been grabbed, do nothing. if (d_grabBuffer) return; // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // bind the texture we want to grab glBindTexture(GL_TEXTURE_2D, d_ogltexture); // allocate the buffer for storing the image data d_grabBuffer = new uint8[static_cast<int>(4*d_size.d_width*d_size.d_height)]; glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, d_grabBuffer); // delete the texture glDeleteTextures(1, &d_ogltexture); // restore previous texture binding. glBindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void OpenGL3Texture::blitFromMemory(void* sourceData, const Rectf& area) { // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // set texture to required size glBindTexture(GL_TEXTURE_2D, d_ogltexture); glTexSubImage2D(GL_TEXTURE_2D, 0, GLint(area.left()), GLint(area.top()), GLsizei(area.getWidth()), GLsizei(area.getHeight()), GL_RGBA8, GL_UNSIGNED_BYTE, sourceData ); // restore previous texture binding. glBindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void OpenGL3Texture::blitToMemory(void* targetData) { // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // set texture to required size glBindTexture(GL_TEXTURE_2D, d_ogltexture); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, targetData); // restore previous texture binding. glBindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void OpenGL3Texture::restoreTexture() { if (d_grabBuffer) { generateOpenGLTexture(); // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); // bind the texture to restore to glBindTexture(GL_TEXTURE_2D, d_ogltexture); // reload the saved image data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<GLsizei>(d_size.d_width), static_cast<GLsizei>(d_size.d_height), 0, GL_RGBA, GL_UNSIGNED_BYTE, d_grabBuffer); // restore previous texture binding. glBindTexture(GL_TEXTURE_2D, old_tex); // free the grabbuffer delete [] d_grabBuffer; d_grabBuffer = 0; } } //----------------------------------------------------------------------------// void OpenGL3Texture::updateCachedScaleValues() { // // calculate what to use for x scale // const float orgW = d_dataSize.d_width; const float texW = d_size.d_width; // if texture and original data width are the same, scale is based // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale // const float orgH = d_dataSize.d_height; const float texH = d_size.d_height; // if texture and original data height are the same, scale is based // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// void OpenGL3Texture::generateOpenGLTexture() { // save old texture binding GLuint old_tex; glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex)); glGenTextures(1, &d_ogltexture); // set some parameters for this texture. glBindTexture(GL_TEXTURE_2D, d_ogltexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // restore previous texture binding. glBindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// void OpenGL3Texture::cleanupOpenGLTexture() { // if the grabbuffer is not empty then free it if (d_grabBuffer) { delete[] d_grabBuffer; d_grabBuffer = 0; } // otherwise delete any OpenGL texture associated with this object. else { glDeleteTextures(1, &d_ogltexture); d_ogltexture = 0; } } //----------------------------------------------------------------------------// GLuint OpenGL3Texture::getOpenGLTexture() const { return d_ogltexture; } //----------------------------------------------------------------------------// void OpenGL3Texture::setOpenGLTexture(GLuint tex, const Sizef& size) { if (d_ogltexture != tex) { // cleanup the current state first. cleanupOpenGLTexture(); d_ogltexture = tex; } d_dataSize = d_size = size; updateCachedScaleValues(); } //----------------------------------------------------------------------------// bool OpenGL3Texture::isPixelFormatSupported(const PixelFormat fmt) const { switch (fmt) { case PF_RGBA: case PF_RGB: case PF_RGBA_4444: case PF_RGB_565: return true; case PF_RGB_DXT1: case PF_RGBA_DXT1: case PF_RGBA_DXT3: case PF_RGBA_DXT5: return d_owner.isS3TCSupported(); default: return false; } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
[ "xelfes@gmail.com" ]
xelfes@gmail.com
109e534d8eba4df7982531c3e3eb25bbe2e25117
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/mojo/edk/system/broker_host.h
a7995d2b0fcdd42677e0b9e47e08ba6a0188886b
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,872
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 MOJO_EDK_SYSTEM_BROKER_HOST_H_ #define MOJO_EDK_SYSTEM_BROKER_HOST_H_ #include <stdint.h> #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/process/process_handle.h" #include "base/strings/string_piece.h" #include "mojo/edk/embedder/platform_handle_vector.h" #include "mojo/edk/embedder/scoped_platform_handle.h" #include "mojo/edk/system/channel.h" namespace mojo { namespace edk { // The BrokerHost is a channel to the child process, which services synchronous // IPCs. class BrokerHost : public Channel::Delegate, public base::MessageLoop::DestructionObserver { public: BrokerHost(base::ProcessHandle client_process, ScopedPlatformHandle handle); // Send |handle| to the child, to be used to establish a NodeChannel to us. bool SendChannel(ScopedPlatformHandle handle); #if defined(OS_WIN) // Sends a named channel to the child. Like above, but for named pipes. void SendNamedChannel(const base::StringPiece16& pipe_name); #endif private: ~BrokerHost() override; bool PrepareHandlesForClient(PlatformHandleVector* handles); // Channel::Delegate: void OnChannelMessage(const void* payload, size_t payload_size, ScopedPlatformHandleVectorPtr handles) override; void OnChannelError() override; // base::MessageLoop::DestructionObserver: void WillDestroyCurrentMessageLoop() override; void OnBufferRequest(uint32_t num_bytes); #if defined(OS_WIN) base::ProcessHandle client_process_; #endif scoped_refptr<Channel> channel_; DISALLOW_COPY_AND_ASSIGN(BrokerHost); }; } // namespace edk } // namespace mojo #endif // MOJO_EDK_SYSTEM_BROKER_HOST_H_
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
7b617d92a1ff9bdcea9cad4d6f049c95f38e18ce
8bb36e35302388cb508e3ed7f821b0d40ec49b41
/comp371-graphics/Group371/Room.cpp
55afa0f5bde22a9b22469a35b73f9791a88a49c5
[]
no_license
tucci/ProceduralArtGallery
4c8cc469dfa3878baffd5c74dff1a028eb8b7069
1df1495cf3b3d65241e7e60bbfa27cf72166970b
refs/heads/master
2020-03-22T06:17:40.455359
2018-07-03T18:33:12
2018-07-03T18:33:12
139,623,414
2
0
null
null
null
null
UTF-8
C++
false
false
21,092
cpp
#include "Room.h" #include <iostream> Room::Room(float length, float width, float height, float x, float y) : width(width), length(length), height(height), position(x, y) { center.setSides(false, false, true, true, false, false); setColors(center); center.localScaleMesh(glm::vec3(1.0f - sides_size, 1.0f, 1.0f - sides_size)); manager.addMesh(&center); Cube* leftc = new Cube(true, false, true, true, false, false); setColors(*leftc); left = leftc; manager.addMesh(left); Cube* rightc = new Cube(false, true, true, true, false, false); setColors(*rightc); right = rightc; manager.addMesh(right); Cube* frontc = new Cube(false, false, true, true, true, false); setColors(*frontc); front = frontc; manager.addMesh(front); Cube* backc = new Cube(false, false, true, true, false, true); setColors(*backc); back = backc; manager.addMesh(back); onChangeLeft(); onChangeRight(); onChangeFront(); onChangeBack(); onChange(); } Room::~Room() { //delete left, right, front, back; } void Room::onChange() { //recompute mesh on changes MeshManager m; manager.computeMergedMesh(); Mesh roomMesh = manager.finalMesh; roomMesh.localScaleMesh(glm::vec3(width, height, length)); roomMesh.translateMesh(glm::vec3(position.y, 0.0f, position.x)); for (Mesh* art : objects) { art->translateMesh(glm::vec3(position.y, 0.0f, position.x)); } objectManager.computeMergedMesh(); Mesh objectsMesh = objectManager.finalMesh; m.addMesh(roomMesh); m.addMesh(objectsMesh); m.computeMergedMeshCopies(); Mesh final = m.finalMesh; vertices = final.getVertices(); indices = final.getIndices(); maxXYZ = roomMesh.maxXYZ; minXYZ = roomMesh.minXYZ; } void Room::onChangeLeft() { left->localScaleMesh(glm::vec3(sides_size, 1.0f, 1.0f)); left->translateMesh(glm::vec3(0.5f - (sides_size / 2.0f), 0.0f, 0.0f)); } void Room::onChangeRight() { right->localScaleMesh(glm::vec3(sides_size, 1.0f, 1.0f)); right->translateMesh(glm::vec3(-0.5f + (sides_size / 2.0f), 0.0f, 0.0f)); } void Room::onChangeFront() { front->localScaleMesh(glm::vec3(1.0f, 1.0f, sides_size)); front->translateMesh(glm::vec3(0.0f, 0.0f, 0.5f - (sides_size / 2.0f))); } void Room::onChangeBack() { back->localScaleMesh(glm::vec3(1.0f, 1.0f, sides_size)); back->translateMesh(glm::vec3(0.0f, 0.0f, -0.5f + (sides_size / 2.0f))); } bool Room::intersects(Room room) { float aLeft = position.x - (length / 2.0f); float aRight = position.x + (length / 2.0f); float aTop = position.y + (width / 2.0f); float aBottom = position.y - (width / 2.0f); float bLeft = room.position.x - (room.length / 2.0f); float bRight = room.position.x + (room.length / 2.0f); float bTop = room.position.y + (room.width / 2.0f); float bBottom = room.position.y - (room.width / 2.0f); return (aLeft <= bRight && aRight >= bLeft && aTop >= bBottom && aBottom <= bTop); } Mesh Room::getXOpening(float from, float to, bool isLeft) { //limit from/to to object length from = from > length ? length : from; to = to > length ? length : to; //normalize to 0-1 from = from / length; to = to / length; Cube hole(false, false, true, true, false, false); Cube c1(isLeft, !isLeft, true, true, false, false); Cube c2(isLeft, !isLeft, true, true, false, false); setColors(hole); setColors(c1); setColors(c2); float holeSize = to - from; float c1size = from; float c2size = 1.0f - to; hole.localScaleMesh(glm::vec3(1.0f, 1.0f, holeSize)); c1.localScaleMesh(glm::vec3(1.0f, 1.0f, c1size)); c2.localScaleMesh(glm::vec3(1.0f, 1.0f, c2size)); hole.translateMesh(glm::vec3(0.0f, 0.0f, -0.5 + from + holeSize / 2.0f)); c1.translateMesh(glm::vec3(0.0f, 0.0f, -0.5 + c1size / 2.0f)); c2.translateMesh(glm::vec3(0.0f, 0.0f, -0.5 + to + c2size / 2.0f)); MeshManager manager; manager.addMesh(hole); manager.addMesh(c1); manager.addMesh(c2); manager.computeMergedMeshCopies(); return manager.finalMesh; } Mesh Room::getYOpening(float from, float to, bool isFront) { //limit from/to to object width from = from > width ? width : from; to = to > width ? width : to; //normalize to 0-1 from = from / width; to = to / width; Cube hole(false, false, true, true, false, false); Cube c1(false, false, true, true, isFront, !isFront); Cube c2(false, false, true, true, isFront, !isFront); setColors(hole); setColors(c1); setColors(c2); float holeSize = to - from; float c1size = from; float c2size = 1.0f - to; hole.localScaleMesh(glm::vec3(holeSize, 1.0f, 1.0f)); c1.localScaleMesh(glm::vec3(c1size, 1.0f, 1.0f)); c2.localScaleMesh(glm::vec3(c2size, 1.0f, 1.0f)); hole.translateMesh(glm::vec3(-0.5 + from + holeSize / 2.0f, 0.0f, 0.0f)); c1.translateMesh(glm::vec3(-0.5 + c1size / 2.0f, 0.0f, 0.0f)); c2.translateMesh(glm::vec3(-0.5 + to + c2size / 2.0f, 0.0f, 0.0f)); MeshManager manager; manager.addMesh(hole); manager.addMesh(c1); manager.addMesh(c2); manager.computeMergedMeshCopies(); return manager.finalMesh; } void Room::setLeftOpening(float from, float to) { //if from and to are the same, we have nothing to do if (from == to) return; Mesh mesh = getXOpening(from, to, true); hasLeftOpen = true; leftOpening = glm::vec2(from, to); left->reset(); left->addVertices(mesh.getVertices()); left->addIndices(mesh.getIndices()); onChangeLeft(); onChange(); } void Room::setRightOpening(float from, float to) { //if from and to are the same, we have nothing to do if (from == to) return; Mesh mesh = getXOpening(from, to, false); hasRightOpen = true; rightOpening = glm::vec2(from, to); right->reset(); right->addVertices(mesh.getVertices()); right->addIndices(mesh.getIndices()); onChangeRight(); onChange(); } void Room::setFrontOpening(float from, float to) { //if from and to are the same, we have nothing to do if (from == to) return; Mesh mesh = getYOpening(from, to, true); hasFrontOpen = true; frontOpening = glm::vec2(from, to); front->reset(); front->addVertices(mesh.getVertices()); front->addIndices(mesh.getIndices()); onChangeFront(); onChange(); } void Room::setBackOpening(float from, float to) { //if from and to are the same, we have nothing to do if (from == to) return; Mesh mesh = getYOpening(from, to, false); hasBackOpen = true; backOpening = glm::vec2(from, to); back->reset(); back->addVertices(mesh.getVertices()); back->addIndices(mesh.getIndices()); onChangeBack(); onChange(); } void Room::setColors(Cube& cube) { int mix = 50; float repeat = 2; if (rand() % 2 == 0) { Material m = randomMaterial(); cube.setFaceMix(CubeFace::front, m, Texture::getTexture("wall"), repeat, repeat, mix); } else { cube.setFaceTexture(CubeFace::front, Texture::getTexture("wall"), repeat, repeat); } if (rand() % 2 == 0) { Material m = randomMaterial(); cube.setFaceMix(CubeFace::back, m, Texture::getTexture("wall"), repeat, repeat, mix); } else { cube.setFaceTexture(CubeFace::back, Texture::getTexture("wall"), repeat, repeat); } if (rand() % 2 == 0) { Material m = randomMaterial(); cube.setFaceMix(CubeFace::left, m, Texture::getTexture("wall"), repeat, repeat, mix); } else { cube.setFaceTexture(CubeFace::left, Texture::getTexture("wall"), repeat, repeat); } if (rand() % 2 == 0) { Material m = randomMaterial(); cube.setFaceMix(CubeFace::right, m, Texture::getTexture("wall"), repeat, repeat, mix); } else { cube.setFaceTexture(CubeFace::right, Texture::getTexture("wall"), repeat, repeat); } cube.setFaceTexture(CubeFace::bottom, Texture::getTexture("floor"), 8, 16); cube.setFaceTexture(CubeFace::top, Texture::getTexture("wall")); } const glm::vec2 Room::getPosition() { return position; } const float Room::getLength() { return length; } const float Room::getWidth() { return width; } const float Room::getHeight() { return height; } glm::vec2 Room::getTopLeft() { return glm::vec2(getPosition().x - getLength() / 2.0f, getPosition().y + getWidth() / 2.0f); } glm::vec2 Room::getBottomRight() { return glm::vec2(getPosition().x + getLength() / 2.0f, getPosition().y - getWidth() / 2.0f); } std::vector<Light> Room::getLights() { std::vector<Light> lights; float lightheight = 0; glm::vec3 topLeft(position.y + width / 4.0f, lightheight, position.x - length / 4.0f); glm::vec3 topRight(position.y + width / 4.0f, lightheight, position.x + length / 4.0f); glm::vec3 bottomLeft(position.y - width / 4.0f, lightheight, position.x - length / 4.0f); glm::vec3 bottomRight(position.y - width / 4.0f, lightheight, position.x + length / 4.0f); glm::vec3 middleLeft(position.y, lightheight, position.x - length / 4.0f); glm::vec3 middleRight(position.y, lightheight, position.x + length / 4.0f); glm::vec3 middleTop(position.y + width / 4.0f, lightheight, position.x); glm::vec3 middleBottom(position.y - width / 4.0f, lightheight, position.x); Light low = LIGHT_DISTANCE_20; Light high = LIGHT_DISTANCE_32; Light light1 = width > 10.0f && length > 10.0f ? high : low; light1.position = middleTop; lights.push_back(light1); if (width > 10.0f || length > 10.0f) { Light light2 = high; light2.position = middleBottom; lights.push_back(light2); } return lights; } void Room::addArtPieces() { //min-max sizes float minPaintingHeight = height / 6.0f; float maxPaintingHeight = height / 3.0f; float minPaintingLength = 1.0f; float maxPaintingLength = 4.25f; float pedestalHeight = 1.25f; float pedestalWidth = 0.25f; float pedestalLength = 0.25f; std::vector<float> addAtHeights = {height*2/3 - 0.25f*2 - maxPaintingHeight/2.0f, height - 0.25f - maxPaintingHeight/2.0f}; //go through for each height (so that paintings can be at different places throughout a wall) for (float atHeight : addAtHeights) { //fill each wall for (int i = 0; i < 4; i++) { WallSide side = (WallSide)i; //get the empty wall parts on this wall std::vector<glm::vec2> openings = getOpenings(side); for (glm::vec2 openarea : openings) { //as long as we can add another painting while (openarea.y - openarea.x >= minPaintingLength) { float openingLength = openarea.y - openarea.x; float maxLength = openingLength >= maxPaintingLength ? maxPaintingLength : openingLength; Painting* painting = getRandomPainting(minPaintingLength, maxLength, minPaintingHeight, maxPaintingHeight); addToWall(side, painting, openarea.x + painting->getLength() / 2.0f, painting->getWidth(), atHeight); openarea.x += painting->getLength() + 0.5f; } } } } //fill each wall once for (int i = 0; i < 4; i++) { WallSide side = (WallSide)i; //get the empty wall parts on this wall std::vector<glm::vec2> openings = getOpenings(side); for (glm::vec2 openarea : openings) { openarea.x += 0.75f; //as long as we can add another painting while (openarea.y - openarea.x >= pedestalLength + 0.75) { //if we can add another pedestal and have some space Pedestal* pedestal = getRandomPedestal(pedestalLength, pedestalWidth, pedestalHeight); addToWall(side, pedestal, (openarea.x + pedestalLength / 2.0f), pedestalWidth, pedestalHeight / 2.0f); float minHeight = pedestalHeight / 10.0f; float maxHeight = pedestalHeight / 2.0f; float shapeHeight = minHeight + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxHeight - minHeight))); RandomShape* shape = getRandomShape(pedestalLength, pedestalWidth, shapeHeight); addToWall(side, shape, (openarea.x + pedestalLength / 2.0f), pedestalWidth, pedestalHeight + shapeHeight / 2.0f); openarea.x += pedestalLength + 1.75f; } } } //center Pedestal* ped = new Pedestal(); float center_pedestal_width = width / 4.0f; float center_pedestal_height = height / 6.0f; float center_pedestal_length = length / 4.0f; ped->localScaleMesh(glm::vec3(center_pedestal_width, center_pedestal_height, center_pedestal_length)); float center_pedestal_heightPosition = -height / 2.0f + height / 6.0f / 2.0f + 0.0001f; ped->translateMesh(glm::vec3(0.0f, center_pedestal_heightPosition, 0.0f)); objectManager.addMesh(ped); objects.push_back(ped); //Bench float benchSpacing = 0.2f; Bench* bench1 = new Bench(center_pedestal_width - 0.5f, 0.3f, 0.3f); bench1->translateMesh(glm::vec3(0.0f, -height / 2.0f + bench1->getHeight(), (center_pedestal_length / 2) + benchSpacing)); objectManager.addMesh(bench1); objects.push_back(bench1); Bench* bench2 = new Bench(center_pedestal_width - 0.5f, 0.3f, 0.3f); bench2->translateMesh(glm::vec3(0.0f, -height / 2.0f + bench2->getHeight(), -(center_pedestal_length / 2) - benchSpacing)); objectManager.addMesh(bench2); objects.push_back(bench2); Bench* bench3 = new Bench(center_pedestal_length - 0.5f, 0.3f, 0.3f); bench3->rotateMesh(glm::radians(90.0f), glm::vec3(0, 1, 0)); bench3->translateMesh(glm::vec3((center_pedestal_width / 2) + benchSpacing, -height / 2.0f + bench3->getHeight(), 0.0f)); objectManager.addMesh(bench3); objects.push_back(bench3); Bench* bench4 = new Bench(center_pedestal_length - 0.5f, 0.3f, 0.3f); bench4->rotateMesh(glm::radians(90.0f), glm::vec3(0, 1, 0)); bench4->translateMesh(glm::vec3(-(center_pedestal_width / 2) - benchSpacing, -height/2.0f + bench4->getHeight(), 0.0f)); objectManager.addMesh(bench4); objects.push_back(bench4); float minHeight = height / 8.0f; float maxHeight = this->height - center_pedestal_height - 0.25f; float shapeHeight = minHeight + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxHeight - minHeight))); RandomShape* shape = getRandomShape(center_pedestal_length, center_pedestal_width, shapeHeight); shape->translateMesh(glm::vec3(0.0f, center_pedestal_heightPosition + center_pedestal_height/2.0f + shapeHeight/2.0f, 0.0f)); objectManager.addMesh(shape); objects.push_back(shape); onChange(); } std::vector<BoundingBox> Room::getBoundingBox() { float extraSpace = 0.135f; std::vector<BoundingBox> boxes; if (hasLeftOpening()) { BoundingBox l1; l1.max = glm::vec3(this->maxXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->minXYZ.z + leftOpening.x + extraSpace); l1.min = glm::vec3(this->maxXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(l1); BoundingBox l2; l2.max = glm::vec3(this->maxXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); l2.min = glm::vec3(this->maxXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z + leftOpening.y - extraSpace); boxes.push_back(l2); } else { BoundingBox l; l.max = glm::vec3(this->maxXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); l.min = glm::vec3(this->maxXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(l); } if (hasRightOpening()) { BoundingBox l1; l1.max = glm::vec3(this->minXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->minXYZ.z + rightOpening.x + extraSpace); l1.min = glm::vec3(this->minXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(l1); BoundingBox l2; l2.max = glm::vec3(this->minXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); l2.min = glm::vec3(this->minXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z + rightOpening.y - extraSpace); boxes.push_back(l2); } else { BoundingBox r; r.max = glm::vec3(this->minXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); r.min = glm::vec3(this->minXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(r); } if (hasFrontOpening()) { BoundingBox f1; f1.max = glm::vec3(this->minXYZ.x + frontOpening.x + extraSpace, this->maxXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); f1.min = glm::vec3(this->minXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->maxXYZ.z - extraSpace); boxes.push_back(f1); BoundingBox f2; f2.max = glm::vec3(this->maxXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); f2.min = glm::vec3(this->minXYZ.x + frontOpening.y - extraSpace, this->minXYZ.y - extraSpace, this->maxXYZ.z - extraSpace); boxes.push_back(f2); } else { BoundingBox f; f.max = glm::vec3(this->maxXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); f.min = glm::vec3(this->minXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->maxXYZ.z - extraSpace); boxes.push_back(f); } if (hasBackOpening()) { BoundingBox b1; b1.max = glm::vec3(this->minXYZ.x + backOpening.x + extraSpace, this->maxXYZ.y + extraSpace, this->minXYZ.z + extraSpace); b1.min = glm::vec3(this->minXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(b1); BoundingBox b2; b2.max = glm::vec3(this->maxXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->minXYZ.z + extraSpace); b2.min = glm::vec3(this->minXYZ.x + backOpening.y - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(b2); } else { BoundingBox b; b.max = glm::vec3(this->maxXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->minXYZ.z + extraSpace); b.min = glm::vec3(this->minXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(b); } BoundingBox t; t.max = glm::vec3(this->maxXYZ.x + extraSpace, this->maxXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); t.min = glm::vec3(this->minXYZ.x - extraSpace, this->maxXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(t); BoundingBox bot; bot.max = glm::vec3(this->maxXYZ.x + extraSpace, this->minXYZ.y + extraSpace, this->maxXYZ.z + extraSpace); bot.min = glm::vec3(this->minXYZ.x - extraSpace, this->minXYZ.y - extraSpace, this->minXYZ.z - extraSpace); boxes.push_back(bot); for (Mesh* art : objects) { for (BoundingBox box : art->getBoundingBox()) { boxes.push_back(box); } } return boxes; } Painting* Room::getRandomPainting(float minLength, float maxLength, float minheight, float maxHeight) { float paintingWidth = Painting::FRAME_LENGTH / 2.0f; float paintingLength = minLength + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxLength - minLength))); float paintingHeight = minheight + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxHeight - minheight))); return new Painting(paintingLength, paintingHeight, paintingWidth); } Pedestal* Room::getRandomPedestal(float length, float width, float height) { Pedestal* ped = new Pedestal(); ped->localScaleMesh(glm::vec3(width, height, length)); return ped; } RandomShape* Room::getRandomShape(float length, float width, float height) { RandomShape* shape = new RandomShape(); shape->localScaleMesh(glm::vec3(width, height, length)); return shape; } void Room::addToWall(WallSide side, Mesh* mesh, float at, float width, float atHeight) { switch (side) { case LEFT: mesh->localRotateMesh(glm::radians(-90.0f), glm::vec3(0, 1, 0)); mesh->translateMesh(glm::vec3( this->width / 2.0f - width / 2.0f - 0.001f, -this->height / 2.0f + atHeight + 0.001f, -this->length / 2.0f + at)); break; case RIGHT: mesh->localRotateMesh(glm::radians(90.0f), glm::vec3(0, 1, 0)); mesh->translateMesh(glm::vec3( -this->width / 2.0f + width / 2.0f + 0.001f, -this->height / 2.0f + atHeight + 0.001f, -this->length / 2.0f + at)); break; case FRONT: mesh->localRotateMesh(glm::radians(180.0f), glm::vec3(0, 1, 0)); mesh->translateMesh(glm::vec3( -this->width / 2.0f + at, -this->height / 2.0f + atHeight + 0.001f, this->length / 2.0f - width / 2.0f - 0.001f)); break; case BACK: mesh->translateMesh(glm::vec3( -this->width / 2.0f + at, -this->height / 2.0f + atHeight + 0.001f, -this->length / 2.0f + width / 2.0f + 0.001f)); break; } objects.push_back(mesh); objectManager.addMesh(mesh); } std::vector<glm::vec2> Room::getOpenings(WallSide side, float padding) { std::vector<glm::vec2> openings; //empty space on wall switch (side) { case LEFT: if (hasLeftOpening()) { openings.push_back(glm::vec2(padding, leftOpening.x - padding)); openings.push_back(glm::vec2(leftOpening.y + padding, length - padding)); } else { openings.push_back(glm::vec2(padding, length - padding)); } break; case RIGHT: if (hasRightOpening()) { openings.push_back(glm::vec2(padding, rightOpening.x - padding)); openings.push_back(glm::vec2(rightOpening.y + padding, length - padding)); } else { openings.push_back(glm::vec2(padding, length - padding)); } break; case FRONT: if (hasFrontOpening()) { openings.push_back(glm::vec2(padding, frontOpening.x - padding)); openings.push_back(glm::vec2(frontOpening.y + padding, width - padding)); } else { openings.push_back(glm::vec2(padding, width - padding)); } break; case BACK: if (hasBackOpening()) { openings.push_back(glm::vec2(padding, backOpening.x - padding)); openings.push_back(glm::vec2(backOpening.y + padding, width - padding)); } else { openings.push_back(glm::vec2(padding, width - padding)); } break; } return openings; }
[ "tuccisteven@gmail.com" ]
tuccisteven@gmail.com
b6119dd7ff97d889452fbcb0318758ca41538e20
b705322f4ab5ce92180e820d8c59990a9ac1d60b
/lib/k2hsubkeys.h
d740c881c541275694ea436b59ff48e3b3fa15c8
[ "MIT" ]
permissive
hiwakaba/k2hash
effcdb33a076ad915b056ea4f0ce4be6a84dac08
154257ccc3e0aaa5cefdb0361a354ec19b53616d
refs/heads/master
2023-02-22T08:02:01.841699
2021-01-27T00:04:50
2021-01-27T00:04:50
162,055,341
0
0
MIT
2018-12-17T00:49:23
2018-12-17T00:49:23
null
UTF-8
C++
false
false
4,008
h
/* * K2HASH * * Copyright 2013 Yahoo Japan Corporation. * * K2HASH is key-valuew store base libraries. * K2HASH is made for the purpose of the construction of * original KVS system and the offer of the library. * The characteristic is this KVS library which Key can * layer. And can support multi-processing and multi-thread, * and is provided safely as available KVS. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: Takeshi Nakatani * CREATE: Fri Dec 2 2013 * REVISION: * */ #ifndef K2HSUBKEYS_H #define K2HSUBKEYS_H #include <string.h> #include <vector> #include "k2hutil.h" class K2HShm; class K2HSubKeys; class K2HSKIterator; //--------------------------------------------------------- // Structure //--------------------------------------------------------- typedef struct subkey{ unsigned char* pSubKey; size_t length; subkey() : pSubKey(NULL), length(0UL) {} // example: memcmp(this, other) // this < other ---> -1 // this == other --> 0 // this > other ---> 1 int compare(const unsigned char* bySubkey, size_t SKLength) const { int result; if(!pSubKey && !bySubkey){ result = 0; }else if(!pSubKey){ result = -1; }else if(!bySubkey){ result = 1; }else{ size_t cmplength = std::min(length, SKLength); if(0 == (result = memcmp(pSubKey, bySubkey, cmplength))){ if(length < SKLength){ result = -1; }else if(length > SKLength){ result = 1; } } } return result; } bool operator==(const struct subkey& other) const { return (0 == compare(other.pSubKey, other.length)); } bool operator!=(const struct subkey& other) const { return (0 != compare(other.pSubKey, other.length)); } }SUBKEY, *PSUBKEY; typedef std::vector<SUBKEY> skeyarr_t; //--------------------------------------------------------- // Class K2HSubKeys //--------------------------------------------------------- class K2HSubKeys { friend class K2HSKIterator; protected: skeyarr_t SubKeys; public: typedef K2HSKIterator iterator; K2HSubKeys(); K2HSubKeys(const K2HSubKeys& other); explicit K2HSubKeys(const char* pSubkeys); K2HSubKeys(const unsigned char* pSubkeys, size_t length); virtual ~K2HSubKeys(); bool Serialize(unsigned char** ppSubkeys, size_t& length) const; bool Serialize(const unsigned char* pSubkeys, size_t length); strarr_t::size_type StringArray(strarr_t& strarr) const; K2HSubKeys& operator=(const K2HSubKeys& other); void clear(void); bool empty(void) const; size_t size(void) const; K2HSubKeys::iterator insert(const char* pSubkey); K2HSubKeys::iterator insert(const unsigned char* bySubkey, size_t length); K2HSubKeys::iterator begin(void); K2HSubKeys::iterator end(void); K2HSubKeys::iterator find(const unsigned char* bySubkey, size_t length); K2HSubKeys::iterator erase(K2HSubKeys::iterator iter); bool erase(const char* pSubkey); bool erase(const unsigned char* bySubkey, size_t length); }; //--------------------------------------------------------- // Class K2HSKIterator //--------------------------------------------------------- // cppcheck-suppress copyCtorAndEqOperator class K2HSKIterator : public std::iterator<std::forward_iterator_tag, SUBKEY> { friend class K2HSubKeys; friend class K2HShm; friend class K2HIterator; protected: const K2HSubKeys* pK2HSubKeys; skeyarr_t::iterator iter_pos; SUBKEY dummy; public: K2HSKIterator(const K2HSKIterator& iterator); virtual ~K2HSKIterator(); private: K2HSKIterator(); K2HSKIterator(const K2HSubKeys* pK2HSKeys, skeyarr_t::iterator pos); bool Next(void); public: K2HSKIterator& operator++(void); K2HSKIterator operator++(int); SUBKEY& operator*(void); PSUBKEY operator->(void) const; bool operator==(const K2HSKIterator& iterator); bool operator!=(const K2HSKIterator& iterator); }; #endif // K2HSUBKEYS_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
[ "nakatani@yahoo-corp.jp" ]
nakatani@yahoo-corp.jp
67cb75b46b49636d0396fbf20ba1a151948bc65a
060c9bdf3f22e86f5d8655616932784f07bc7e47
/Contests/Code_Mate_2/polite.cpp
6ab3f58db05ebf24cb91c8d40e3498543d0fc883
[]
no_license
agabhi017/Codechef
582e211d053e69f1ecc6fe50d06e0311b1a45dc9
4f3e5f1e5b5c67f46d334d16060d9f5a2d814aa5
refs/heads/main
2023-03-05T11:08:28.182769
2021-02-11T14:22:52
2021-02-11T14:22:52
325,817,227
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int t; unsigned long long n; cin >> t; while (t--){ cin >> n; cout << floor(log2(n)) + 1 << endl; } return 0; }
[ "agabhi001@gmail.com" ]
agabhi001@gmail.com
4c2621490357bcbd5ee13f1f90b27e5051505af5
b40d2f76c9cb01ed11e317ace30587dff22e42db
/OVERRIDD.CPP
35ea8aaa081bc1e98a4305b300424978ef75926f
[]
no_license
Rajwinders13/Basic-Programs
b4a42dbb1c35eaa2f64dd4a117f3e303f8ed48d5
8dc06ace0c2d89da45982941fddcfe59899db949
refs/heads/master
2020-03-31T13:19:01.247273
2018-10-09T13:42:27
2018-10-09T13:42:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
#include<iostream.h> #include<conio.h> class A { int a; public: void get_a() { cout<<"Enter the value of a:"; cin>>a; } void display() { cout<<a; } }; class B:public A { int b; public: void get_b() { cout<<"Enter the value of b:"; cin>>b; } void display() { cout<<b; } }; void main() { clrscr(); B b; b.get_a(); b.get_b(); b.display(); getch(); }
[ "noreply@github.com" ]
Rajwinders13.noreply@github.com
fb8bd9785a66a40d96991f31e4694d4c89c82910
262b8cfc6a48853efe7e37bc223343fa94a4518a
/Classes/UserInterface/ButtonHolder/ButtonHolder.cpp
55637a0ac7b47c42aa9b6fb4ac13f26c9c939913
[]
no_license
yeadong/THE_DEAD_FOREST
94b7de304331de145f419f29fc1d56625edb83f3
b42ace192ac3dfa13c7b80ddf014f05fcf1b1a33
refs/heads/master
2020-03-16T21:32:17.928651
2016-03-07T12:03:44
2016-03-07T12:03:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,947
cpp
// // ButtonHolder.cpp // TheDeadForest // // Created by mac on 2016. 2. 19.. // // #include "ButtonHolder.hpp" #include "GameManager.hpp" namespace realtrick { namespace userinterface { using namespace cocos2d; ButtonHolder::ButtonHolder(GameManager* mgr) : _gameMgr(mgr), _status(nullptr), _inventory(nullptr), _setting(nullptr) {} ButtonHolder::~ButtonHolder() { } ButtonHolder* ButtonHolder::create(GameManager* mgr) { ButtonHolder* ret = new (std::nothrow) ButtonHolder(mgr); if ( ret && ret->init() ) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } bool ButtonHolder::init() { if ( !Node::init() ) { return false; } _status = ui::CheckBox::create("status.png", "status_s.png"); _status->setPosition(Vec2(-100, -50)); _status->addEventListener([this](Ref* ref, const ui::CheckBox::EventType& type){ for( const auto& callback : _statusButtonCallbacks ) { callback.second(ref, type); } }); addChild(_status); _inventory = ui::CheckBox::create("inventory.png", "inventory_s.png"); _inventory->setPosition(Vec2(0, 0)); _inventory->addEventListener([this](Ref* ref, const ui::CheckBox::EventType& type){ for( const auto& callback : _inventoryButtonCallbacks ) { callback.second(ref, type); } }); addChild(_inventory); _setting = ui::CheckBox::create("setting.png", "setting_s.png"); _setting->setPosition(Vec2(100, -50)); _setting->addEventListener([this](Ref* ref, const ui::CheckBox::EventType& type){ for( const auto& callback : _settingButtonCallbacks ) { callback.second(ref, type); } }); addChild(_setting); return true; } void ButtonHolder::setButtonSize(cocos2d::Size size) { _status->setScale(size.width / _status->getContentSize().width, size.height / _status->getContentSize().height); _inventory->setScale(size.width / _inventory->getContentSize().width, size.height / _inventory->getContentSize().height); _setting->setScale(size.width / _setting->getContentSize().width, size.height / _setting->getContentSize().height); } void ButtonHolder::_disableButtons() { _status->setSelected(false); _inventory->setSelected(false); _setting->setSelected(false); } void ButtonHolder::addStausButtonEvent(int key, const cocos2d::ui::CheckBox::ccCheckBoxCallback& callback) { _statusButtonCallbacks.insert(std::make_pair(key, callback)); } void ButtonHolder::addInventoryButtonEvent(int key, const cocos2d::ui::CheckBox::ccCheckBoxCallback& callback) { _inventoryButtonCallbacks.insert(std::make_pair(key, callback)); } void ButtonHolder::addSettingButtonEvent(int key, const cocos2d::ui::CheckBox::ccCheckBoxCallback& callback) { _settingButtonCallbacks.insert(std::make_pair(key, callback)); } } }
[ "njh0602@naver.com" ]
njh0602@naver.com
e92525509213692cc48b5d6c9001b59045c29441
825dbfde537faf753581a2ab86d8f536c1125737
/src/gfx/Skeleton.cpp
b912fe2e5048e8974fc60a2f3d8de52ec021575c
[ "Zlib" ]
permissive
oceancx/mud
e59a739f69fbb48fc9c7e53f4412ee2c9aabc913
a7ca88d062bf2679e2977b03dc63d6e315912e14
refs/heads/master
2020-03-30T05:42:00.403384
2018-09-23T23:06:31
2018-09-23T23:06:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,596
cpp
// Copyright (c) 2018 Hugo Amiard hugo.amiard@laposte.net // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #include <gfx/Cpp20.h> #ifdef MUD_MODULES module mud.gfx; #else #include <gfx/Skeleton.h> #include <gfx/Renderer.h> #endif #include <bx/math.h> #define SKELETON_TEXTURE_SIZE 256 namespace mud { Skeleton::Skeleton() {} Skeleton::Skeleton(cstring name, int num_bones) : m_name(name) { m_bones.reserve(num_bones); } void Skeleton::update_bones() { for(Bone& bone : m_bones) { if(bone.m_parent > -1) bone.m_pose = m_bones[bone.m_parent].m_pose * bone.m_pose_local; else bone.m_pose = bone.m_pose_local; } } Bone& Skeleton::add_bone(cstring name, int parent) { m_bones.emplace_back(name, m_bones.size(), parent); return m_bones.back(); } Bone* Skeleton::find_bone(cstring name) { for(size_t i = 0; i < m_bones.size(); i++) if(m_bones[i].m_name == name) return &m_bones[i]; return nullptr; } Skin::Skin(Skeleton& skeleton, int num_joints) : m_skeleton(&skeleton) { int height = num_joints / SKELETON_TEXTURE_SIZE; if(num_joints % SKELETON_TEXTURE_SIZE) height++; m_texture = bgfx::createTexture2D(SKELETON_TEXTURE_SIZE, uint16_t(height * 4), false, 1, bgfx::TextureFormat::RGBA32F, GFX_TEXTURE_POINT | GFX_TEXTURE_CLAMP); //m_texture_data.resize(SKELETON_TEXTURE_SIZE * height * 4 * 4); } Skin::Skin(const Skin& copy, Skeleton& skeleton) : Skin(skeleton, copy.m_joints.size()) { m_joints = copy.m_joints; m_skeleton = &skeleton; } Skin::~Skin() { if(bgfx::isValid(m_texture)) bgfx::destroy(m_texture); } void Skin::add_joint(cstring bone, const mat4& inverse_bind) { Joint joint = { size_t(m_skeleton->find_bone(bone)->m_index), inverse_bind, mat4{} }; m_joints.push_back(joint); } Joint* Skin::find_bone_joint(cstring name) { for(Joint& joint : m_joints) if(m_skeleton->m_bones[joint.m_bone].m_name == name) return &joint; return nullptr; } void Skin::update_joints() { int height = m_joints.size() / SKELETON_TEXTURE_SIZE; if(m_joints.size() % SKELETON_TEXTURE_SIZE) height++; m_memory = bgfx::alloc(SKELETON_TEXTURE_SIZE * height * 4 * 4 * sizeof(float)); int index = 0; for(Joint& joint : m_joints) { joint.m_joint = m_skeleton->m_bones[joint.m_bone].m_pose * joint.m_inverse_bind; float* texture = (float*)m_memory->data; //float* texture = m_texture_data.data(); int offset = ((index / SKELETON_TEXTURE_SIZE) * SKELETON_TEXTURE_SIZE) * 4 * 4 + (index % SKELETON_TEXTURE_SIZE) * 4; index++; //debug_print_mat(joint.m_joint); for(int i = 0; i < 4; ++i) { for(int j = 0; j < 4; ++j) texture[offset + j] = joint.m_joint[j][i]; offset += SKELETON_TEXTURE_SIZE * 4; } } //const bgfx::Memory* mem = bgfx::makeRef(m_texture_data.data(), sizeof(float) * m_texture_data.size()); bgfx::updateTexture2D(m_texture, 0, 0, 0, 0, SKELETON_TEXTURE_SIZE, uint16_t(height * 4), m_memory); } Rig::Rig() {} Rig::Rig(const Rig& rig) : m_skeleton(rig.m_skeleton) { for(const Skin& skin : rig.m_skins) m_skins.emplace_back(skin, m_skeleton); } Rig& Rig::operator=(const Rig& rig) { m_skeleton = rig.m_skeleton; m_skins.reserve(rig.m_skins.size()); for(const Skin& skin : rig.m_skins) m_skins.emplace_back(skin, m_skeleton); return *this; } void Rig::update_rig() { m_skeleton.update_bones(); for(Skin& skin : m_skins) skin.update_joints(); } }
[ "hugo.amiard@laposte.net" ]
hugo.amiard@laposte.net
638d6854a1d419fd05899aa4324e92ae158a7709
d0a279edfcb1d5aff935720bee71af796ebff1a5
/Reality/Source/ConsoleThread.h
3c22857718824751939de2515c2b9b04b0b06607
[]
no_license
TasteeWheat/mxoemu1
a0cb32ed2868d3f65cd7a54113b9672437a28709
9e583b5101f7914d9e27f6dc0e071c3cc0808254
refs/heads/master
2020-06-08T22:52:38.948378
2010-06-01T22:05:48
2010-06-01T22:05:48
698,058
2
0
null
null
null
null
UTF-8
C++
false
false
1,219
h
// ************************************************************************************************* // -------------------------------------- // Copyright (C) 2006-2010 Rajko Stojadinovic // // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // ************************************************************************************************* #ifndef MXOSIM_CONSOLETHREAD_H #define MXOSIM_CONSOLETHREAD_H #include "Threading/ThreadStarter.h" class ConsoleThread : public ThreadContext { public: bool run(); }; #endif
[ "John@.(none)" ]
John@.(none)
8a59793113a3521fc53ccba583aa9ff7fda92483
dc10d039f593790a1fe9e0723769bfba07d5ccd9
/VKTS/include/vkts/layer0/debug/fn_debug.hpp
9b1dc84fe2256f706d7144e63996625466780a52
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-happy-bunny", "LicenseRef-scancode-khronos", "BSD-3-Clause", "Apache-2.0" ]
permissive
YoutaVen/Vulkan
5a38ebc694355631f50ebbeee092c959ecf99817
b19dca5388491257c74f18f3b271355be5ff55fa
refs/heads/master
2020-04-05T18:29:35.317945
2016-04-10T15:04:08
2016-04-10T15:04:08
55,913,171
9
0
null
2016-04-10T17:35:04
2016-04-10T17:35:03
null
UTF-8
C++
false
false
1,709
hpp
/** * VKTS - VulKan ToolS. * * The MIT License (MIT) * * Copyright (c) since 2014 Norbert Nopper * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef VKTS_FN_DEBUG_HPP_ #define VKTS_FN_DEBUG_HPP_ #include <vkts/vkts.hpp> namespace vkts { VKTS_APICALL VkBool32 VKTS_APIENTRY debugGatherNeededInstanceExtensions(); VKTS_APICALL VkBool32 VKTS_APIENTRY debugInitInstanceExtensions(const VkInstance instance); VKTS_APICALL VkBool32 VKTS_APIENTRY debugCreateDebugReportCallback(const VkInstance instance, const VkDebugReportFlagsEXT flags); VKTS_APICALL void VKTS_APIENTRY debugDestroyDebugReportCallback(const VkInstance instance); } #endif /* VKTS_FN_DEBUG_HPP_ */
[ "norbert@nopper.tv" ]
norbert@nopper.tv
cdaf839e5025651ec38c694a4903ee47b4d13f99
79a634d9357a750cbd0efea04d932938e1b7f632
/Contest/ACM/2010_bak/Monthly_2010/2010-05-PKU-MONTHLY/3768.cpp
46e9f9b14540db8dcb877048d0d3ef82d5f9d594
[]
no_license
hphp/Algorithm
5f42fe188422427a7762dbbe7af539b89fa796ed
ccbb368a37eed1b0cb37356026b299380f9c008b
refs/heads/master
2016-09-06T02:24:43.141927
2014-05-27T00:49:44
2014-05-27T00:49:44
14,009,913
1
0
null
null
null
null
UTF-8
C++
false
false
2,466
cpp
#include <stdio.h> #include <math.h> #define N 3010 #define K 6 #define P 9 int n; char grid[N][N]; char ori[K][K]; int power[6][P]; void booling() { for(int i=3;i<7;i++) { power[i][0] = 1; for(int j=1;j<P;j++) power[i][j] = power[i][j-1]*i; } } void build(int sx,int sy,int size) { int xx = sx;int yy = sy; if(size == 1) { for(int i=0;i<n;i++,xx++) { yy = sy; for(int j=0;j<n;j++,yy++) { grid[xx][yy] = ori[i][j]; } } return; } int add = power[n][size-1]; for(int i=0;i<n;i++,xx += add) { yy = sy; for(int j=0;j<n;j++,yy += add) { if(ori[i][j] != ' ') { build(xx,yy,size-1); } } } } int main() { booling(); /* freopen("3768.in","r",stdin); freopen("3768.out","w",stdout);*/ // printf("%lf\n",log(3000.0)/log(3)); while(scanf("%d",&n)!=EOF) { if(!n)break; getchar(); for(int i=0;i<n;i++) gets(ori[i]); int size; scanf("%d",&size); for(int i=0;i<N;i++) { for(int j=0;j<N;j++) grid[i][j] = ' '; grid[i][power[n][size]] = '\0'; } build(0,0,size); /* for(int i=0;i<power[n][size];i++) for(int j = N-2;j>=0;j--) if(grid[][])*/ for(int i=0;i<power[n][size];i++) printf("%s\n",grid[i]); } return 0; } /* 3 # # # # # 1 3 # # # # # 3 4 OO O O O O OO 2 0 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # OO OO O OO O O OO O OO OO OO OO O O O O O O O O OO OO OO OO O O O O O O O O OO OO OO OO O OO O O OO O OO OO */
[ "hphpcarrot@gmail.com" ]
hphpcarrot@gmail.com
123528fc8958b17942e047192b6333b73663dd4d
ee19e56bb8806906917ddfef150b752b971b310b
/includes/dhyara/packets/echo_reply.h
7ab90ecb012eb0114c93b24d447fa7355dd733cf
[ "BSD-2-Clause" ]
permissive
RustyShackleforth/dhyara
19ec93a3279b88d2292b5032866f960491eaeaa2
9f7dc956011f5aca542eca46cee4a27c463835a1
refs/heads/main
2023-04-12T16:50:56.522005
2021-05-11T21:25:00
2021-05-11T21:25:00
382,931,781
1
0
BSD-2-Clause
2021-07-04T19:21:44
2021-07-04T19:21:44
null
UTF-8
C++
false
false
2,577
h
/* * Copyright (c) 2020, Sunanda Bose (a.k.a. Neel Basu) * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #ifndef DHYARA_PACKETS_ECHO_REPLY_H #define DHYARA_PACKETS_ECHO_REPLY_H #include <array> #include <cstdint> #include "dhyara/peer.h" #include "esp_timer.h" namespace dhyara{ namespace packets{ /** * An echo reply * \ingroup packets */ struct echo_reply{ typedef std::array<std::uint8_t, 6> raw_address_type; /** * Construct an echo reply to null destination originating from null destination on current time */ inline echo_reply(): _target{0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, _source{0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, _seq(0), _time(esp_timer_get_time()), _ttl(255){} /** * Construct an echo reply to the target originating from the source with the provided sequence number and time. * \param target the target mac address * \param source the originating mac address * \param seq the sequence number of this Echo request * \param time the time in the Echo request (defaults to current time) * \param ttl Time to Live (number of hops to live) */ inline echo_reply(const dhyara::address& target, const dhyara::address& source, std::uint32_t seq = 0, std::uint64_t time = esp_timer_get_time(), std::uint8_t ttl = 255) : _target{target.b1(), target.b2(), target.b3(), target.b4(), target.b5(), target.b6()}, _source{source.b1(), source.b2(), source.b3(), source.b4(), source.b5(), source.b6()}, _seq(seq), _time(time), _ttl(ttl){} /** * Size of the packet */ inline std::size_t size() const {return sizeof(echo_reply); } /** * Time in the packet */ inline std::uint64_t time() const {return _time;} /** * Sequence number in teh packet */ inline std::uint32_t seq() const {return _seq;} /** * TTL value */ inline std::uint8_t ttl() const {return _ttl;} /** * target address */ inline dhyara::address target() const { return dhyara::address(_target); } /** * source address */ inline dhyara::address source() const { return dhyara::address(_source); } private: raw_address_type _target; raw_address_type _source; std::uint32_t _seq; std::uint64_t _time; std::uint8_t _ttl; } __attribute__((packed)); } } #endif // DHYARA_PACKETS_ECHO_REPLY_H
[ "neel.basu.z@gmail.com" ]
neel.basu.z@gmail.com
430a375c9f6a0473b3cf6dc9ed4c26ca3fd32ddf
28690c8767e907ad83304a6b58fec76c6ba1f46c
/ThirdPartyLibs/include/CGAL/Polygon_mesh_processing/repair.h
0beb2704097bcfcc8d5f9415570c9425e0c2df19
[]
no_license
haisenzhao/SmartCFS
c9d7e2f73cde25a5957d1c3268cc5ddbbe7f5af2
2c066792dab2ca99b02bc035e77d09b4b5619aa2
refs/heads/master
2023-08-20T17:51:37.254851
2021-09-27T20:55:36
2021-09-27T20:55:36
271,935,428
7
0
null
null
null
null
UTF-8
C++
false
false
33,826
h
// Copyright (c) 2015 GeometryFactory (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // You can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Sebastien Loriot #ifndef CGAL_POLYGON_MESH_PROCESSING_REPAIR_H #define CGAL_POLYGON_MESH_PROCESSING_REPAIR_H #include <set> #include <vector> #include <boost/algorithm/minmax_element.hpp> #include <CGAL/boost/graph/Euler_operations.h> #include <CGAL/Union_find.h> #include <CGAL/Polygon_mesh_processing/internal/named_function_params.h> #include <CGAL/Polygon_mesh_processing/internal/named_params_helper.h> namespace CGAL{ namespace Polygon_mesh_processing { namespace debug{ template <class TriangleMesh, class VertexPointMap> std::ostream& dump_edge_neighborhood( typename boost::graph_traits<TriangleMesh>::edge_descriptor ed, TriangleMesh& tmesh, const VertexPointMap& vpmap, std::ostream& out) { typedef boost::graph_traits<TriangleMesh> GT; typedef typename GT::halfedge_descriptor halfedge_descriptor; typedef typename GT::vertex_descriptor vertex_descriptor; typedef typename GT::face_descriptor face_descriptor; halfedge_descriptor h = halfedge(ed, tmesh); std::map<vertex_descriptor, int> vertices; std::set<face_descriptor> faces; int vindex=0; BOOST_FOREACH(halfedge_descriptor hd, halfedges_around_target(h, tmesh)) { if ( vertices.insert(std::make_pair(source(hd, tmesh), vindex)).second ) ++vindex; if (!is_border(hd, tmesh)) faces.insert( face(hd, tmesh) ); } h=opposite(h, tmesh); BOOST_FOREACH(halfedge_descriptor hd, halfedges_around_target(h, tmesh)) { if ( vertices.insert(std::make_pair(source(hd, tmesh), vindex)).second ) ++vindex; if (!is_border(hd, tmesh)) faces.insert( face(hd, tmesh) ); } std::vector<vertex_descriptor> ordered_vertices(vertices.size()); typedef std::pair<const vertex_descriptor, int> Pair_type; BOOST_FOREACH(const Pair_type& p, vertices) ordered_vertices[p.second]=p.first; out << "OFF\n" << ordered_vertices.size() << " " << faces.size() << " 0\n"; BOOST_FOREACH(vertex_descriptor vd, ordered_vertices) out << get(vpmap, vd) << "\n"; BOOST_FOREACH(face_descriptor fd, faces) { out << "3"; h=halfedge(fd,tmesh); BOOST_FOREACH(halfedge_descriptor hd, halfedges_around_face(h, tmesh)) out << " " << vertices[target(hd, tmesh)]; out << "\n"; } return out; } } //end of namespace debug template <class HalfedgeGraph, class VertexPointMap, class Traits> struct Less_vertex_point{ typedef typename boost::graph_traits<HalfedgeGraph>::vertex_descriptor vertex_descriptor; const Traits& m_traits; const VertexPointMap& m_vpmap; Less_vertex_point(const Traits& traits, const VertexPointMap& vpmap) : m_traits(traits) , m_vpmap(vpmap) {} bool operator()(vertex_descriptor v1, vertex_descriptor v2) const{ return m_traits.less_xyz_3_object()(get(m_vpmap, v1), get(m_vpmap, v2)); } }; template <class Traits> struct Less_along_ray{ const Traits& m_traits; typename Traits::Point_3 m_source; Less_along_ray(const Traits& traits, const typename Traits::Point_3& s) : m_traits(traits) , m_source(s) {}; bool operator()( const typename Traits::Point_3& p1, const typename Traits::Point_3& p2) const { return m_traits.collinear_are_ordered_along_line_3_object()(m_source, p1, p2); } }; template <class Traits, class TriangleMesh, class VertexPointMap> bool is_degenerated( typename boost::graph_traits<TriangleMesh>::halfedge_descriptor hd, TriangleMesh& tmesh, const VertexPointMap& vpmap, const Traits& traits) { const typename Traits::Point_3& p1 = get(vpmap, target( hd, tmesh) ); const typename Traits::Point_3& p2 = get(vpmap, target(next(hd, tmesh), tmesh) ); const typename Traits::Point_3& p3 = get(vpmap, source( hd, tmesh) ); return traits.collinear_3_object()(p1, p2, p3); } template <class Traits, class TriangleMesh, class VertexPointMap> bool is_degenerated( typename boost::graph_traits<TriangleMesh>::face_descriptor fd, TriangleMesh& tmesh, const VertexPointMap& vpmap, const Traits& traits) { return is_degenerated(halfedge(fd,tmesh), tmesh, vpmap, traits); } ///\cond SKIP_IN_MANUAL template <class EdgeRange, class TriangleMesh, class NamedParameters> std::size_t remove_null_edges( const EdgeRange& edge_range, TriangleMesh& tmesh, const NamedParameters& np) { CGAL_assertion(CGAL::is_triangle_mesh(tmesh)); using boost::choose_const_pmap; using boost::get_param; using boost::choose_param; typedef TriangleMesh TM; typedef typename boost::graph_traits<TriangleMesh> GT; typedef typename GT::edge_descriptor edge_descriptor; typedef typename GT::halfedge_descriptor halfedge_descriptor; typedef typename GT::face_descriptor face_descriptor; typedef typename GT::vertex_descriptor vertex_descriptor; typedef typename GetVertexPointMap<TM, NamedParameters>::type VertexPointMap; VertexPointMap vpmap = choose_pmap(get_param(np, boost::vertex_point), tmesh, boost::vertex_point); typedef typename GetGeomTraits<TM, NamedParameters>::type Traits; Traits traits = choose_param(get_param(np, geom_traits), Traits()); std::size_t nb_deg_faces = 0; // collect edges of length 0 std::set<edge_descriptor> null_edges_to_remove; BOOST_FOREACH(edge_descriptor ed, edge_range) { if ( traits.equal_3_object()(get(vpmap, target(ed, tmesh)), get(vpmap, source(ed, tmesh))) ) null_edges_to_remove.insert(ed); } while (!null_edges_to_remove.empty()) { edge_descriptor ed = *null_edges_to_remove.begin(); null_edges_to_remove.erase(null_edges_to_remove.begin()); halfedge_descriptor h = halfedge(ed, tmesh); if (CGAL::Euler::does_satisfy_link_condition(ed,tmesh)) { // remove edges that could also be set for removal if ( face(h, tmesh)!=GT::null_face() ) { ++nb_deg_faces; null_edges_to_remove.erase(edge(prev(h, tmesh), tmesh)); } if (face(opposite(h, tmesh), tmesh)!=GT::null_face()) { ++nb_deg_faces; null_edges_to_remove.erase(edge(prev(opposite(h, tmesh), tmesh), tmesh)); } //now remove the edge CGAL::Euler::collapse_edge(ed, tmesh); } else{ //handle the case when the edge is incident to a triangle hole //we first fill the hole and try again if ( is_border(ed, tmesh) ) { halfedge_descriptor hd = halfedge(ed,tmesh); if (!is_border(hd,tmesh)) hd=opposite(hd,tmesh); if (is_triangle(hd, tmesh)) { Euler::fill_hole(hd, tmesh); null_edges_to_remove.insert(ed); continue; } } // When the edge does not satisfy the link condition, it means that it cannot be // collapsed as is. In the following we assume that there is no topological issue // with contracting the edge (no volume will disappear). // We start by marking the faces that are incident to an edge endpoint. // If the set of marked faces is a topologically disk, then we simply remove all the simplicies // inside the disk and star the hole with the edge vertex kept. // If the set of marked faces is not a topological disk, it has some non-manifold vertices // on its boundary. We need to mark additional faces to make it a topological disk. // We can then apply the star hole procedure. // Right now we additionally mark the smallest connected components of non-marked faces // (using the numnber of faces) //backup central point typename Traits::Point_3 pt = get(vpmap, source(ed, tmesh)); // mark faces of the link of each endpoints of the edge which collapse is not topologically valid std::set<face_descriptor> marked_faces; // first endpoint BOOST_FOREACH( halfedge_descriptor hd, CGAL::halfedges_around_target(halfedge(ed,tmesh), tmesh) ) if (!is_border(hd,tmesh)) marked_faces.insert( face(hd, tmesh) ); // second endpoint BOOST_FOREACH( halfedge_descriptor hd, CGAL::halfedges_around_target(opposite(halfedge(ed, tmesh), tmesh), tmesh) ) if (!is_border(hd,tmesh)) marked_faces.insert( face(hd, tmesh) ); // extract the halfedges on the boundary of the marked region std::vector<halfedge_descriptor> border; BOOST_FOREACH(face_descriptor fd, marked_faces) BOOST_FOREACH(halfedge_descriptor hd, CGAL::halfedges_around_face(halfedge(fd,tmesh), tmesh)) { halfedge_descriptor hd_opp = opposite(hd, tmesh); if ( is_border(hd_opp, tmesh) || marked_faces.count( face(hd, tmesh) )!= marked_faces.count( face(hd_opp, tmesh) ) ) { border.push_back( hd ); } } // define cc of border halfedges: two halfedges are in the same cc // if they are on the border of the cc of non-marked faces. typedef CGAL::Union_find<halfedge_descriptor> UF_ds; UF_ds uf; std::map<halfedge_descriptor, typename UF_ds::handle> handles; // one cc per border halfedge BOOST_FOREACH(halfedge_descriptor hd, border) handles.insert( std::make_pair(hd, uf.make_set(hd)) ); // join cc's BOOST_FOREACH(halfedge_descriptor hd, border) { CGAL_assertion( marked_faces.count( face( hd, tmesh) ) > 0); CGAL_assertion( marked_faces.count( face( opposite(hd, tmesh), tmesh) ) == 0 ); halfedge_descriptor candidate = hd; do{ candidate = prev( opposite(candidate, tmesh), tmesh ); } while( !marked_faces.count( face( opposite(candidate, tmesh), tmesh) ) ); uf.unify_sets( handles[hd], handles[opposite(candidate, tmesh)] ); } std::size_t nb_cc = uf.number_of_sets(); if ( nb_cc != 1 ) { // if more than one connected component is found then the patch // made of marked faces contains "non-manifold" vertices. // The smallest components need to be marked so that the patch // made of marked faces is a topological disk // we will explore in parallel the connected components and will stop // when all but one connected component have been entirely explored. // We add one face at a time for each cc in order to not explore a // potentially very large cc. std::vector< std::vector<halfedge_descriptor> > stacks_per_cc(nb_cc); std::vector< std::set<face_descriptor> > faces_per_cc(nb_cc); std::vector< bool > exploration_finished(nb_cc, false); // init the stacks of halfedges using the cc of the boundary std::size_t index=0; std::map< halfedge_descriptor, std::size_t > ccs; typedef std::pair<const halfedge_descriptor, typename UF_ds::handle> Pair_type; BOOST_FOREACH(Pair_type p, handles) { halfedge_descriptor opp_hedge = opposite(p.first, tmesh); if (is_border(opp_hedge, tmesh)) continue; // nothing to do on the boundary typedef typename std::map< halfedge_descriptor, std::size_t >::iterator Map_it; std::pair<Map_it, bool> insert_res= ccs.insert( std::make_pair(*uf.find( p.second ), index) ); if (insert_res.second) ++index; stacks_per_cc[ insert_res.first->second ].push_back( prev(opp_hedge, tmesh) ); stacks_per_cc[ insert_res.first->second ].push_back( next(opp_hedge, tmesh) ); faces_per_cc[ insert_res.first->second ].insert( face(opp_hedge, tmesh) ); } std::size_t nb_ccs_to_be_explored = nb_cc; index=0; //explore the cc's do{ // try to extract one more face for a given cc do{ CGAL_assertion( !exploration_finished[index] ); halfedge_descriptor hd = stacks_per_cc[index].back(); stacks_per_cc[index].pop_back(); hd = opposite(hd, tmesh); if ( !is_border(hd,tmesh) && !marked_faces.count(face(hd, tmesh) ) ) { if ( faces_per_cc[index].insert( face(hd, tmesh) ).second ) { stacks_per_cc[index].push_back( next(hd, tmesh) ); stacks_per_cc[index].push_back( prev(hd, tmesh) ); break; } } if (stacks_per_cc[index].empty()) break; } while(true); // the exploration of a cc is finished when its stack is empty exploration_finished[index]=stacks_per_cc[index].empty(); if ( exploration_finished[index] ) --nb_ccs_to_be_explored; if ( nb_ccs_to_be_explored==1 ) break; while ( exploration_finished[(++index)%nb_cc] ); index=index%nb_cc; }while(true); /// \todo use the area criteria? this means maybe continue exploration of larger cc // mark faces of completetly explored cc for (index=0; index< nb_cc; ++index) if( exploration_finished[index] ) { BOOST_FOREACH(face_descriptor fd, faces_per_cc[index]) marked_faces.insert(fd); } } // collect simplices to be removed std::set<vertex_descriptor> vertices_to_keep; std::set<halfedge_descriptor> halfedges_to_keep; BOOST_FOREACH(halfedge_descriptor hd, border) if ( !marked_faces.count(face(opposite(hd, tmesh), tmesh)) ) { halfedges_to_keep.insert( hd ); vertices_to_keep.insert( target(hd, tmesh) ); } // backup next,prev relationships to set after patch removal std::vector< std::pair<halfedge_descriptor, halfedge_descriptor> > next_prev_halfedge_pairs; halfedge_descriptor first_border_hd=*( halfedges_to_keep.begin() ); halfedge_descriptor current_border_hd=first_border_hd; do{ halfedge_descriptor prev_border_hd=current_border_hd; current_border_hd=next(current_border_hd, tmesh); while( marked_faces.count( face( opposite(current_border_hd, tmesh), tmesh) ) ) current_border_hd=next(opposite(current_border_hd, tmesh), tmesh); next_prev_halfedge_pairs.push_back( std::make_pair(prev_border_hd, current_border_hd) ); }while(current_border_hd!=first_border_hd); // collect vertices and edges to remove and do remove faces std::set<edge_descriptor> edges_to_remove; std::set<vertex_descriptor> vertices_to_remove; BOOST_FOREACH(face_descriptor fd, marked_faces) { halfedge_descriptor hd=halfedge(fd, tmesh); for(int i=0; i<3; ++i) { if ( !halfedges_to_keep.count(hd) ) edges_to_remove.insert( edge(hd, tmesh) ); if ( !vertices_to_keep.count(target(hd,tmesh)) ) vertices_to_remove.insert( target(hd,tmesh) ); hd=next(hd, tmesh); } remove_face(fd, tmesh); } // remove vertices BOOST_FOREACH(vertex_descriptor vd, vertices_to_remove) remove_vertex(vd, tmesh); // remove edges BOOST_FOREACH(edge_descriptor ed, edges_to_remove) { null_edges_to_remove.erase(ed); remove_edge(ed, tmesh); } // add a new face, set all border edges pointing to it // and update halfedge vertex of patch boundary vertices face_descriptor new_face = add_face(tmesh); typedef std::pair<halfedge_descriptor, halfedge_descriptor> Pair_type; BOOST_FOREACH(const Pair_type& p, next_prev_halfedge_pairs) { set_face(p.first, new_face, tmesh); set_next(p.first, p.second, tmesh); set_halfedge(target(p.first, tmesh), p.first, tmesh); } set_halfedge(new_face, first_border_hd, tmesh); // triangulate the new face and update the coordinate of the central vertex halfedge_descriptor new_hd=Euler::add_center_vertex(first_border_hd, tmesh); put(vpmap, target(new_hd, tmesh), pt); BOOST_FOREACH(halfedge_descriptor hd, halfedges_around_target(new_hd, tmesh)) if ( traits.equal_3_object()(get(vpmap, target(hd, tmesh)), get(vpmap, source(hd, tmesh))) ) null_edges_to_remove.insert(edge(hd, tmesh)); CGAL_assertion( is_valid(tmesh) ); } } return nb_deg_faces; } template <class EdgeRange, class TriangleMesh> std::size_t remove_null_edges( const EdgeRange& edge_range, TriangleMesh& tmesh) { return remove_null_edges(edge_range, tmesh, parameters::all_default()); } /// \ingroup PkgPolygonMeshProcessing /// removes the degenerate faces from a triangulated surface mesh. /// A face is considered degenerate if two of its vertices share the same location, /// or more generally if all its vertices are collinear. /// /// @pre `CGAL::is_triangle_mesh(tmesh)` /// /// @tparam TriangleMesh a model of `FaceListGraph` and `MutableFaceGraph` /// that has an internal property map for `boost::vertex_point_t` /// @tparam NamedParameters a sequence of \ref namedparameters /// /// @param tmesh the triangulated surface mesh to be repaired /// @param np optional \ref namedparameters described below /// /// \cgalNamedParamsBegin /// \cgalParamBegin{vertex_point_map} the property map with the points associated to the vertices of `pmesh`. The type of this map is model of `ReadWritePropertyMap` \cgalParamEnd /// \cgalParamBegin{geom_traits} a geometric traits class instance. /// The traits class must provide the nested type `Point_3`, /// and the nested functors : /// - `Compare_distance_3` to compute the distance between 2 points /// - `Collinear_are_ordered_along_line_3` to check whether 3 collinear points are ordered /// - `Collinear_3` to check whether 3 points are collinear /// - `Less_xyz_3` to compare lexicographically two points /// - `Equal_3` to check whether 2 points are identical /// - for each functor Foo, a function `Foo foo_object()` /// \cgalParamEnd /// \cgalNamedParamsEnd /// /// \return number of removed degenerate faces /// \endcond template <class TriangleMesh, class NamedParameters> std::size_t remove_degenerate_faces(TriangleMesh& tmesh, const NamedParameters& np) { CGAL_assertion(CGAL::is_triangle_mesh(tmesh)); using boost::choose_const_pmap; using boost::get_param; using boost::choose_param; typedef TriangleMesh TM; typedef typename boost::graph_traits<TriangleMesh> GT; typedef typename GT::edge_descriptor edge_descriptor; typedef typename GT::halfedge_descriptor halfedge_descriptor; typedef typename GT::face_descriptor face_descriptor; typedef typename GT::vertex_descriptor vertex_descriptor; typedef typename GetVertexPointMap<TM, NamedParameters>::type VertexPointMap; VertexPointMap vpmap = choose_pmap(get_param(np, boost::vertex_point), tmesh, boost::vertex_point); typedef typename GetGeomTraits<TM, NamedParameters>::type Traits; Traits traits = choose_param(get_param(np, geom_traits), Traits()); // First remove edges of length 0 std::size_t nb_deg_faces = remove_null_edges(edges(tmesh), tmesh, np); // Then, remove triangles made of 3 collinear points std::set<face_descriptor> degenerate_face_set; BOOST_FOREACH(face_descriptor fd, faces(tmesh)) if ( is_degenerated(fd, tmesh, vpmap, traits) ) degenerate_face_set.insert(fd); nb_deg_faces+=degenerate_face_set.size(); while (!degenerate_face_set.empty()) { face_descriptor fd = *degenerate_face_set.begin(); // look whether an incident triangle is also degenerated bool detect_cc_of_degenerate_triangles = false; BOOST_FOREACH(halfedge_descriptor hd, halfedges_around_face(halfedge(fd, tmesh), tmesh) ) { face_descriptor adjacent_face = face( opposite(hd, tmesh), tmesh ); if ( adjacent_face!=GT::null_face() && degenerate_face_set.count(adjacent_face) ) { detect_cc_of_degenerate_triangles = true; break; } } if (!detect_cc_of_degenerate_triangles) { degenerate_face_set.erase(degenerate_face_set.begin()); // flip the longest edge of the triangle const typename Traits::Point_3& p1 = get(vpmap, target( halfedge(fd, tmesh), tmesh) ); const typename Traits::Point_3& p2 = get(vpmap, target(next(halfedge(fd, tmesh), tmesh), tmesh) ); const typename Traits::Point_3& p3 = get(vpmap, source( halfedge(fd, tmesh), tmesh) ); CGAL_assertion(p1!=p2 && p1!=p3 && p2!=p3); typename Traits::Compare_distance_3 compare_distance = traits.compare_distance_3_object(); halfedge_descriptor edge_to_flip; if (compare_distance(p1,p2, p1,p3) != CGAL::SMALLER) // p1p2 > p1p3 { if (compare_distance(p1,p2, p2,p3) != CGAL::SMALLER) // p1p2 > p2p3 // flip p1p2 edge_to_flip = next( halfedge(fd, tmesh), tmesh ); else // flip p2p3 edge_to_flip = prev( halfedge(fd, tmesh), tmesh ); } else if (compare_distance(p1,p3, p2,p3) != CGAL::SMALLER) // p1p3>p2p3 //flip p3p1 edge_to_flip = halfedge(fd, tmesh); else //flip p2p3 edge_to_flip = prev( halfedge(fd, tmesh), tmesh ); face_descriptor opposite_face=face( opposite(edge_to_flip, tmesh), tmesh); if ( opposite_face == GT::null_face() ) // simply remove the face Euler::remove_face(edge_to_flip, tmesh); else Euler::flip_edge(edge_to_flip, tmesh); } else { // Process a connected component of degenerate faces // get all the faces from the connected component // and the boundary edges std::set<face_descriptor> cc_faces; std::vector<face_descriptor> queue; std::vector<halfedge_descriptor> boundary_hedges; std::vector<halfedge_descriptor> inside_hedges; queue.push_back(fd); cc_faces.insert(fd); while(!queue.empty()) { face_descriptor top=queue.back(); queue.pop_back(); BOOST_FOREACH(halfedge_descriptor hd, halfedges_around_face(halfedge(top, tmesh), tmesh) ) { face_descriptor adjacent_face = face( opposite(hd, tmesh), tmesh ); if ( adjacent_face==GT::null_face() || !degenerate_face_set.count(adjacent_face) ) boundary_hedges.push_back(hd); else if (cc_faces.insert(adjacent_face).second) { inside_hedges.push_back(hd); queue.push_back(adjacent_face); } } } #if 0 /// dump cc_faces { int id=0; std::map<vertex_descriptor, int> vids; BOOST_FOREACH(face_descriptor f, cc_faces) { if ( vids.insert( std::make_pair( target(halfedge(f, tmesh), tmesh), id) ).second ) ++id; if ( vids.insert( std::make_pair( target(next(halfedge(f, tmesh), tmesh), tmesh), id) ).second ) ++id; if ( vids.insert( std::make_pair( target(next(next(halfedge(f, tmesh), tmesh), tmesh), tmesh), id) ).second ) ++id; } std::ofstream output("/tmp/cc_faces.off"); output << std::setprecision(44); output << "OFF\n" << vids.size() << " " << cc_faces.size() << " 0\n"; std::vector<typename Traits::Point_3> points(vids.size()); typedef std::pair<const vertex_descriptor, int> Pair_type; BOOST_FOREACH(Pair_type p, vids) points[p.second]=get(vpmap, p.first); BOOST_FOREACH(typename Traits::Point_3 p, points) output << p << "\n"; BOOST_FOREACH(face_descriptor f, cc_faces) { output << "3 " << vids[ target(halfedge(f, tmesh), tmesh) ] << " " << vids[ target(next(halfedge(f, tmesh), tmesh), tmesh) ] << " " << vids[ target(next(next(halfedge(f, tmesh), tmesh), tmesh), tmesh) ] << "\n"; } for (std::size_t pid=2; pid!=points.size(); ++pid) { CGAL_assertion(collinear(points[0], points[1], points[pid])); } } #endif // find vertices strictly inside the cc std::set<vertex_descriptor> boundary_vertices; BOOST_FOREACH(halfedge_descriptor hd, boundary_hedges) boundary_vertices.insert( target(hd, tmesh) ); std::set<vertex_descriptor> inside_vertices; BOOST_FOREACH(halfedge_descriptor hd, inside_hedges) { if (!boundary_vertices.count( target(hd, tmesh) )) inside_vertices.insert( target(hd, tmesh) ); if (!boundary_vertices.count( source(hd, tmesh) )) inside_vertices.insert( source(hd, tmesh) ); } // update the face and halfedge vertex pointers on the boundary BOOST_FOREACH(halfedge_descriptor h, boundary_hedges) { set_face(h, GT::null_face(), tmesh); set_halfedge(target(h,tmesh), h, tmesh); } // update next/prev pointers of boundary_hedges BOOST_FOREACH(halfedge_descriptor h, boundary_hedges) { halfedge_descriptor next_candidate = next( h, tmesh); while (face(next_candidate, tmesh)!=GT::null_face()) next_candidate = next( opposite( next_candidate, tmesh), tmesh); set_next(h, next_candidate, tmesh); } // remove degenerate faces BOOST_FOREACH(face_descriptor f, cc_faces) degenerate_face_set.erase(f); BOOST_FOREACH(face_descriptor f, cc_faces) remove_face(f, tmesh); // remove interior edges BOOST_FOREACH(halfedge_descriptor h, inside_hedges) remove_edge(edge(h, tmesh), tmesh); // remove interior vertices BOOST_FOREACH(vertex_descriptor v, inside_vertices) remove_vertex(v, tmesh); // sort the boundary points along the common supporting line // we first need a reference point typedef Less_vertex_point<TriangleMesh, VertexPointMap, Traits> Less_vertex; std::pair< typename std::set<vertex_descriptor>::iterator, typename std::set<vertex_descriptor>::iterator > ref_vertices = boost::minmax_element( boundary_vertices.begin(), boundary_vertices.end(), Less_vertex(traits, vpmap) ); // and then we sort the vertices using this reference point typedef Less_along_ray<Traits> Less_point; typedef std::set<typename Traits::Point_3, Less_point> Sorted_point_set; Sorted_point_set sorted_points( Less_point( traits, get(vpmap, *ref_vertices.first) ) ); BOOST_FOREACH(vertex_descriptor v, boundary_vertices) sorted_points.insert( get(vpmap,v) ); CGAL_assertion( get( vpmap, *ref_vertices.first)==*sorted_points.begin() ); CGAL_assertion( get( vpmap, *ref_vertices.second)==*cpp11::prev(sorted_points.end()) ); // recover halfedges on the hole, bounded by the reference vertices std::vector<halfedge_descriptor> side_one, side_two; side_one.push_back( next( halfedge(*ref_vertices.first, tmesh), tmesh) ); while( target(side_one.back(), tmesh)!=*ref_vertices.second) side_one.push_back( next(side_one.back(), tmesh) ); side_two.push_back( next(side_one.back(), tmesh) ); while( target(side_two.back(), tmesh)!=*ref_vertices.first ) side_two.push_back( next(side_two.back(), tmesh) ); // reverse the order of the second side so as to follow // the same order than side one std::reverse(side_two.begin(), side_two.end()); BOOST_FOREACH(halfedge_descriptor& h, side_two) h=opposite(h, tmesh); CGAL_assertion( source(side_one.front(), tmesh) == *ref_vertices.first ); CGAL_assertion( source(side_two.front(), tmesh) == *ref_vertices.first ); CGAL_assertion( target(side_one.back(), tmesh) == *ref_vertices.second ); CGAL_assertion( target(side_two.back(), tmesh) == *ref_vertices.second ); // now split each side to contains the same sequence of points // first side int hi=0; for (typename Sorted_point_set::iterator it=cpp11::next(sorted_points.begin()), it_end=sorted_points.end(); it!=it_end; ++it) { CGAL_assertion( *cpp11::prev(it) == get(vpmap, source(side_one[hi], tmesh) ) ); if( *it != get(vpmap, target(side_one[hi], tmesh) ) ){ // split the edge and update the point halfedge_descriptor h1 = next(opposite(side_one[hi], tmesh), tmesh); put(vpmap, target(Euler::split_edge(side_one[hi], tmesh), tmesh), *it); // split_edge updates the halfedge of the source vertex of h, // since we reuse later the halfedge of the first refernce vertex // we must set it as we need. if ( source(h1,tmesh) == *ref_vertices.first) set_halfedge(*ref_vertices.first, prev( prev(side_one[hi], tmesh), tmesh), tmesh ); // retriangulate the opposite face if ( face(h1, tmesh) != GT::null_face()) Euler::split_face(h1, opposite(side_one[hi], tmesh), tmesh); } else ++hi; } // second side hi=0; for (typename Sorted_point_set::iterator it=cpp11::next(sorted_points.begin()), it_end=sorted_points.end(); it!=it_end; ++it) { CGAL_assertion( *cpp11::prev(it) == get(vpmap, source(side_two[hi], tmesh) ) ); if( *it != get(vpmap, target(side_two[hi], tmesh) ) ){ // split the edge and update the point halfedge_descriptor h2 = Euler::split_edge(side_two[hi], tmesh); put(vpmap, target(h2, tmesh), *it); // split_edge updates the halfedge of the source vertex of h, // since we reuse later the halfedge of the first refernce vertex // we must set it as we need. if ( source(h2,tmesh) == *ref_vertices.first) set_halfedge(*ref_vertices.first, opposite( prev(side_two[hi], tmesh), tmesh), tmesh ); // retriangulate the face if ( face(h2, tmesh) != GT::null_face()) Euler::split_face(h2, next(side_two[hi], tmesh), tmesh); } else ++hi; } CGAL_assertion( target(halfedge(*ref_vertices.first, tmesh), tmesh) == *ref_vertices.first ); CGAL_assertion( face(halfedge(*ref_vertices.first, tmesh), tmesh) == GT::null_face() ); // remove side1 and replace its opposite hedges by those of side2 halfedge_descriptor h_side2 = halfedge(*ref_vertices.first, tmesh); halfedge_descriptor h_side1 = next(h_side2, tmesh); while(true) { CGAL_assertion( get(vpmap, source(h_side1, tmesh)) == get(vpmap, target(h_side2, tmesh)) ); CGAL_assertion( get(vpmap, target(h_side1, tmesh)) == get(vpmap, source(h_side2, tmesh)) ); // backup target vertex vertex_descriptor vertex_to_remove = target(h_side1, tmesh); if (vertex_to_remove!=*ref_vertices.second){ vertex_descriptor replacement_vertex = source(h_side2, tmesh); // replace the incident vertex BOOST_FOREACH(halfedge_descriptor hd, halfedges_around_target(h_side1, tmesh)) set_target(hd, replacement_vertex, tmesh); } // prev side2 hedge for next loop halfedge_descriptor h_side2_for_next_turn = prev(h_side2, tmesh); // replace the opposite of h_side1 by h_side2 halfedge_descriptor opposite_h_side1 = opposite( h_side1, tmesh); face_descriptor the_face = face(opposite_h_side1, tmesh); set_face(h_side2, the_face, tmesh); if (the_face!=GT::null_face()) set_halfedge(the_face, h_side2, tmesh); set_next(h_side2, next(opposite_h_side1, tmesh), tmesh); set_next(prev(opposite_h_side1, tmesh), h_side2, tmesh); // take the next hedges edge_descriptor edge_to_remove = edge(h_side1, tmesh); h_side1 = next(h_side1, tmesh); // now remove the extra edge remove_edge(edge_to_remove, tmesh); // ... and the extra vertex if it's not the second reference if (vertex_to_remove==*ref_vertices.second) { // update the halfedge pointer of the last vertex (others were already from side 2) CGAL_assertion( target(opposite(h_side2, tmesh), tmesh) == vertex_to_remove ); set_halfedge(vertex_to_remove, opposite(h_side2, tmesh), tmesh); break; } else remove_vertex(vertex_to_remove , tmesh); h_side2 = h_side2_for_next_turn; } } } return nb_deg_faces; } /// \cond SKIP_IN_MANUAL template<class TriangleMesh> std::size_t remove_degenerate_faces(TriangleMesh& tmesh) { return remove_degenerate_faces(tmesh, CGAL::Polygon_mesh_processing::parameters::all_default()); } /// \endcond } } // end of CGAL::Polygon_mesh_processing #endif // CGAL_POLYGON_MESH_PROCESSING_REPAIR_H
[ "haisenzhao@gmail.com" ]
haisenzhao@gmail.com
6f94ad322404d66c66ffc47094b1b77e0c61e91b
04f25ac243e50ec14d1e87a9bd92e073d62c4a77
/451_Sort_Characters_By_Frequency.cpp
2b5a7333478532dd978b1c778e7c6d401e936bdb
[]
no_license
indrajeet95/LeetCode-Problems
e0ea837da888e5e42fd3bfd28c4afe8726e20943
6cd5383b10172fec645909115cf37b135c93a60c
refs/heads/master
2020-03-19T23:33:57.658437
2019-04-12T16:38:42
2019-04-12T16:38:42
137,010,414
1
0
null
null
null
null
UTF-8
C++
false
false
1,273
cpp
class Solution { public: string frequencySort(string s) { unordered_map<char, int> m1; priority_queue<pair<int, char>> q1; for (int i = 0;i<s.length();i++) m1[s[i]]++; for (auto it = m1.begin();it != m1.end();it++) q1.push(make_pair(it->second, it->first)); string res = ""; while (q1.size()) { pair<int , char> y1 = q1.top(); for(int i=0;i<q1.top().first;i++) res += q1.top().second; q1.pop(); } return res; } }; class Solution { public: string frequencySort(string s) { unordered_map<char,int> basics; string res; for(auto ch : s) basics[ch]++; multimap<int,char,greater<int>> advanced; for(auto it = basics.begin(); it!= basics.end(); it++) advanced.insert(make_pair(it->second, it->first)); //for(auto it = advanced.begin(); it!=advanced.end(); it++) // res.push_back(it->first); for(auto it = advanced.begin(); it!=advanced.end(); it++) cout << it->first << " " << it->second << endl; for(auto it = advanced.begin(); it!=advanced.end(); it++) { for(int i=0; i<it->first; i++) res.push_back(it->second); } return res; } };
[ "indrajeet95@gmail.com" ]
indrajeet95@gmail.com
956451157c8dc2f2127ff7d3aa9b100c09ec67c8
644c18c29c42db2bd3c4d7024c72192da4c887c4
/mainwindow.cpp
11728bea5285ccb065543eed7041b712b9084fae
[]
no_license
LetsOffBrains/ImagePyramid
981fe089855ef1d3f94f74455d47ed8f99653bcb
93fe3ae6e2391ae6598f4fb17a3f12df7f34d6d2
refs/heads/master
2020-08-03T17:15:49.070890
2019-09-30T09:29:00
2019-09-30T09:29:00
211,824,370
0
0
null
null
null
null
UTF-8
C++
false
false
2,969
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); lImage = new QLabel(); lImage->setBackgroundRole(QPalette::Base); lImage->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); lImage->setScaledContents(true); ui->scrollArea->setWidget(lImage); ui->scrollArea->setWidgetResizable(false); currentIndex = -1; currentScale = 2.0; } MainWindow::~MainWindow() { delete ui; } bool compareDiagonal(QString& s1, QString& s2) { QImage i1(s1), i2(s2); if(i1.isNull()) return true; if(i2.isNull()) return false; return (i1.width() * i1.height() < i2.width() * i2.height()); } void MainWindow::on_actionOpen_triggered() { QStringList files = QFileDialog::getOpenFileNames( this, tr("Select Images"), QStandardPaths::writableLocation(QStandardPaths::PicturesLocation), "*.jpg *.png"); if(!files.isEmpty()){ images.clear(); fileNames.clear(); } else{ return; } std::sort(files.begin(), files.end(), compareDiagonal); for(auto file : files){ QImage img(file); if(!img.isNull()){ images << img; fileNames << file.mid(file.lastIndexOf('/') + 1); } else{ QMessageBox::warning( this, "Not an image", file + " is not an image or being corrupted." " It will be ignored."); } } currentIndex = 0; ui->cbFile->addItems(fileNames); on_dsbScale_valueChanged(ui->dsbScale->value()); } void MainWindow::on_cbFile_currentIndexChanged(int index) { currentIndex = index; lImage->setPixmap(QPixmap::fromImage(images.at(index))); lImage->adjustSize(); ui->lSize->setText("Size: " + QString::number(images.at(index).width()) + ";" + QString::number(images.at(index).height())); on_dsbScale_valueChanged(ui->dsbScale->value()); } void MainWindow::on_dsbScale_valueChanged(double arg) { if(currentIndex >= 0){ QStringList list; currentScale = arg; int w = images.at(currentIndex).width(); int h = images.at(currentIndex).height(); int lowest = (w <= h) ? w : h; int max = log(lowest) / log(currentScale) + 1; for(int i = 0; i < max; ++i){ list << QString::number(i); } ui->cbLayer->clear(); ui->cbLayer->addItems(list); } } void MainWindow::on_cbLayer_currentIndexChanged(int index) { if(currentIndex >= 0){ if(index > 0){ currentLayerScale = pow(currentScale, index); int width = images.at(currentIndex).width() / currentLayerScale; int height = images.at(currentIndex).height() / currentLayerScale; QImage newImage = images.at(currentIndex).scaled(width, height); lImage->setPixmap(QPixmap::fromImage(newImage)); ui->lSize->setText("Size: " + QString::number(width) + ";" + QString::number(height)); } else{ lImage->setPixmap(QPixmap::fromImage(images.at(currentIndex))); ui->lSize->setText("Size: " + QString::number(images.at(currentIndex).width()) + ";" + QString::number(images.at(currentIndex).height())); } } }
[ "darkhorseaka@ya.ru" ]
darkhorseaka@ya.ru
477e3604ca42c03da209b4b614d7a61ba546fe35
dc92fcb7e6f9dea015596f06abe3f4f31bc19419
/JMFEL/src/native code/signal processing/SignalProcessor/VecMat/include/vm/vm_fftw3.h
0cefca609f1a4860523dafa4bfe96a971013bcd2
[]
no_license
Blinky0815/Java-Media-Framework-Extension-Layer
5f6fc3b9a476f82287b69a86703921252a9a33f8
93c98e08d3baa8b459dbd3937db0a4edd79b183a
refs/heads/master
2020-03-22T11:43:03.401320
2017-11-28T18:00:54
2017-11-28T18:00:54
139,991,130
0
1
null
2018-07-06T13:51:02
2018-07-06T13:51:01
null
UTF-8
C++
false
false
23,588
h
#ifndef VM_FFTW3_H #define VM_FFTW3_H /****************************************************************************** * * VecMat Software, version 1.5 * Copyright (C) 2003 Kevin Dolan * kdolan@mailaps.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ****************************************************************************** * * vm_fftw3.h - Wrapper and support functions for the FFTW 3.x software. * * This header file should be included if you want to use the FFTW 3.x * software in combination with the VecMat software. * *****************************************************************************/ #include <vm/vec_mat.h> #include <vm/vm_filter.h> #include <fftw3.h> namespace VM { enum Plan_Type {NULL_PLAN, C2C_PLAN, R2C_PLAN, R2R_PLAN}; enum Plan_Dir {FORWARD, BACKWARD, BIDIR}; /****************************************************************************** * * Wrapper class for the fftw_plan structure. * *****************************************************************************/ class FFTPlan { private: double *indp_, *outdp_; fftw_complex *incdp_, *outcdp_; size_t size_; ptrdiff_t str_in_, str_out_; Plan_Type type_; Plan_Dir direction_; fftw_plan forward_; fftw_plan backward_; public: FFTPlan() : indp_(0), outdp_(0), incdp_(0), outcdp_(0), size_(0), str_in_(0), str_out_(0), type_(NULL_PLAN), direction_(BIDIR), forward_(0), backward_(0) {;} FFTPlan(const FFTPlan& plan) : forward_(0), backward_(0) {(*this) = plan;} FFTPlan(Vec_CPLX_DP& in, Vec_CPLX_DP& out, Plan_Dir dir = BIDIR) : forward_(0), backward_(0) {new_plan(in, out, dir);} FFTPlan(Vec_CPLX_DP& dat, Plan_Dir dir = BIDIR) : forward_(0), backward_(0) {new_plan(dat, dir);} FFTPlan(Vec_DP& in, Vec_CPLX_DP& out, Plan_Dir dir = BIDIR) : forward_(0), backward_(0) {new_plan(in, out, dir);} FFTPlan(Vec_DP& in, Vec_DP& out, Plan_Dir dir = BIDIR) : forward_(0), backward_(0) {new_plan(in, out, dir);} FFTPlan(Vec_DP& dat, Plan_Dir dir = BIDIR) : forward_(0), backward_(0) {new_plan(dat, dir);} ~FFTPlan() { if (forward_) fftw_destroy_plan(forward_); if (backward_) fftw_destroy_plan(backward_); } FFTPlan& operator=(const FFTPlan& plan) { if (&plan == this) return *this; free(); Vec_DP indp, outdp; Vec_CPLX_DP incdp, outcdp; if (plan.indp_) indp.view(plan.indp_, plan.size_, plan.str_in_); if (plan.outdp_) outdp.view(plan.outdp_, plan.size_, plan.str_out_); if (plan.incdp_) incdp.view(reinterpret_cast<CPLX_DP*>(plan.incdp_), plan.size_, plan.str_in_); if (plan.outcdp_) outcdp.view(reinterpret_cast<CPLX_DP*>(plan.outcdp_), plan.size_, plan.str_out_); switch (plan.type_) { case C2C_PLAN: new_plan(incdp, outcdp, plan.direction_); break; case R2C_PLAN: new_plan(indp, outcdp, plan.direction_); break; case R2R_PLAN: new_plan(indp, outdp, plan.direction_); break; case NULL_PLAN: break; } return *this; } Plan_Type type() const {return type_;} void new_plan(Vec_CPLX_DP& in, Vec_CPLX_DP& out, Plan_Dir dir = BIDIR) { if (in.size() != out.size() || !in.size()) vmerror("Size mismatch error in FFTPlan::new_plan()"); if (forward_) fftw_destroy_plan(forward_); if (backward_) fftw_destroy_plan(backward_); type_ = C2C_PLAN; direction_ = dir; indp_ = 0; outdp_ = 0; incdp_ = reinterpret_cast<fftw_complex*>(in.data()); outcdp_ = reinterpret_cast<fftw_complex*>(out.data()); size_ = in.size(); str_in_ = in.stride(); str_out_ = out.stride(); forward_ = 0; backward_ = 0; int s = int(size_); if (dir != BACKWARD) forward_ = fftw_plan_many_dft(1, &s, 1, incdp_, 0, int(str_in_), 0, outcdp_, 0, int(str_out_), 0, FFTW_FORWARD, FFTW_ESTIMATE); if (dir != FORWARD) backward_ = fftw_plan_many_dft(1, &s, 1, outcdp_, 0, int(str_out_), 0, incdp_, 0, int(str_in_), 0, FFTW_BACKWARD, FFTW_ESTIMATE); } void new_plan(Vec_CPLX_DP& dat, Plan_Dir dir = BIDIR) { new_plan(dat, dat, dir); } void new_plan(Vec_DP& in, Vec_CPLX_DP& out, Plan_Dir dir = BIDIR) { if (in.size() / 2 + 1 != out.size() || !in.size()) vmerror("Size mismatch error in FFTPlan::new_plan()"); if (forward_) fftw_destroy_plan(forward_); if (backward_) fftw_destroy_plan(backward_); type_ = R2C_PLAN; direction_ = dir; indp_ = in.data(); outdp_ = 0; incdp_ = 0; outcdp_ = reinterpret_cast<fftw_complex*>(out.data()); size_ = in.size(); str_in_ = in.stride(); str_out_ = out.stride(); forward_ = 0; backward_ = 0; int s = int(size_); if (dir != BACKWARD) forward_ = fftw_plan_many_dft_r2c(1, &s, 1, indp_, 0, int(str_in_), 0, outcdp_, 0, int(str_out_), 0, FFTW_ESTIMATE); if (dir != FORWARD) backward_ = fftw_plan_many_dft_c2r(1, &s, 1, outcdp_, 0, int(str_out_), 0, indp_, 0, int(str_in_), 0, FFTW_ESTIMATE); } void new_plan(Vec_DP& in, Vec_DP& out, Plan_Dir dir = BIDIR) { if (in.size() != out.size() || !in.size()) vmerror("Size mismatch error in FFTPlan::new_plan()"); if (forward_) fftw_destroy_plan(forward_); if (backward_) fftw_destroy_plan(backward_); type_ = R2R_PLAN; direction_ = dir; indp_ = in.data(); outdp_ = out.data(); incdp_ = 0; outcdp_ = 0; size_ = in.size(); str_in_ = in.stride(); str_out_ = out.stride(); forward_ = 0; backward_ = 0; int s = int(size_); fftw_r2r_kind r2hc = FFTW_R2HC, hc2r = FFTW_HC2R; if (dir != BACKWARD) forward_ = fftw_plan_many_r2r(1, &s, 1, indp_, 0, int(str_in_), 0, outdp_, 0, int(str_out_), 0, &r2hc, FFTW_ESTIMATE); if (dir != FORWARD) backward_ = fftw_plan_many_r2r(1, &s, 1, outdp_, 0, int(str_out_), 0, indp_, 0, int(str_in_), 0, &hc2r, FFTW_ESTIMATE | FFTW_PRESERVE_INPUT); } void new_plan(Vec_DP& dat, Plan_Dir dir = BIDIR) { new_plan(dat, dat, dir); } void free() { if (forward_) fftw_destroy_plan(forward_); if (backward_) fftw_destroy_plan(backward_); type_ = NULL_PLAN; direction_ = BIDIR; indp_ = 0; outdp_ = 0; incdp_ = 0; outcdp_ = 0; size_ = 0; str_in_ = 0; str_out_ = 0; forward_ = 0; backward_ = 0; } Plan_Dir direction() const { return direction_; } void direction(Plan_Dir dir) { if (dir == direction_ || type_ == NULL_PLAN) return; int s = int(size_); fftw_r2r_kind hc2r = FFTW_HC2R, r2hc = FFTW_R2HC; switch (direction_) { case BIDIR: if (dir == FORWARD) fftw_destroy_plan(backward_); if (dir == BACKWARD) fftw_destroy_plan(forward_); break; case FORWARD: if (dir == BACKWARD) fftw_destroy_plan(forward_); switch (type_) { case R2R_PLAN: backward_ = fftw_plan_many_r2r(1, &s, 1, outdp_, 0, int(str_out_), 0, indp_, 0, int(str_in_), 0, &hc2r, FFTW_ESTIMATE | FFTW_PRESERVE_INPUT); break; case R2C_PLAN: backward_ = fftw_plan_many_dft_c2r(1, &s, 1, outcdp_, 0, int(str_out_), 0, indp_, 0, int(str_in_), 0, FFTW_ESTIMATE); break; case C2C_PLAN: backward_ = fftw_plan_many_dft(1, &s, 1, outcdp_, 0, int(str_out_), 0, incdp_, 0, int(str_in_), 0, FFTW_BACKWARD, FFTW_ESTIMATE); break; case NULL_PLAN: break; } break; case BACKWARD: if (dir == FORWARD) fftw_destroy_plan(backward_); switch (type_) { case R2R_PLAN: forward_ = fftw_plan_many_r2r(1, &s, 1, indp_, 0, int(str_out_), 0, outdp_, 0, int(str_in_), 0, &r2hc, FFTW_ESTIMATE); break; case R2C_PLAN: forward_ = fftw_plan_many_dft_r2c(1, &s, 1, indp_, 0, int(str_out_), 0, outcdp_, 0, int(str_in_), 0, FFTW_ESTIMATE); break; case C2C_PLAN: forward_ = fftw_plan_many_dft(1, &s, 1, incdp_, 0, int(str_out_), 0, outcdp_, 0, int(str_in_), 0, FFTW_FORWARD, FFTW_ESTIMATE); break; case NULL_PLAN: break; } break; } direction_ = dir; } void fourier() const { if (type_ == NULL_PLAN) vmerror("Cannot transform a NULL plan."); if (direction_ == BACKWARD) vmerror("Cannot forward transform a backward plan."); fftw_execute(forward_); } void ifourier() const { if (type_ == NULL_PLAN) vmerror("Cannot transform a NULL plan."); if (direction_ == FORWARD) vmerror("Cannot backward transform a forward plan."); fftw_execute(backward_); } void power(const Vec_DP& signal, Vec_DP& pwr) const { size_t i, k, len = signal.size(), winsize = pwr.size(); if (!len) vmerror("Power of zero size vector not allowed."); if (!winsize) vmerror("Zero sample size error in FFTPlan::power()."); if (winsize != size_) vmerror("Size mismatch error in FFTPlan::power()."); if (type_ != R2R_PLAN) vmerror("Wrong plan-type in FFTPlan::power()."); if (winsize > len) vmerror("Size mismatch error in FFTPlan::power()."); if (direction_ == BACKWARD) vmerror("Cannot calculate power with a backward plan."); Vec_DP welch(winsize); double temp; Vec_DP::iterator p1, p2, a, b; p1 = welch.begin(); for (i = 0; i < winsize; ++i, ++p1) { temp = (2.0 * i - winsize + 1.0) / (winsize + 1.0); (*p1) = 1.0 - square(temp); } double data_mean = mean(signal); Vec_DP x, y; x.view(indp_, size_, str_in_); y.view(outdp_, size_, str_out_); a = y.begin(); b = y.end(); size_t nyq = winsize / 2; i = 0; k = 0; pwr = 0.0; while (i < len - winsize) { x = signal.slice(i, winsize); x -= data_mean; x *= welch; fourier(); p2 = pwr.begin(); for (p1 = a; p1 < b; ++p1, ++p2) (*p2) += square(*p1); i += nyq; ++k; } pwr /= double(k * winsize); } void cross_spectrum(const Vec_DP& signal1, const Vec_DP& signal2, Vec_CPLX_DP& cross) const { size_t i, k, len = signal1.size(), winsize = cross.size(); if (!len) vmerror("Cross-Spectrum of zero size vector not allowed."); if (len != signal2.size()) vmerror("Size mismatch error in FFTPlan::cross_spectrum()."); if (!winsize) vmerror("Zero sample size error in FFTPlan::cross_spectrum()."); if (winsize != size_) vmerror("Size mismatch error in FFTPlan::cross_spectrum()."); if (type_ != C2C_PLAN) vmerror("Wrong plan-type in FFTPlan::cross_spectrum()."); if (winsize > len) vmerror("Size mismatch error in FFTPlan::cross_spectrum()."); if (direction_ == BACKWARD) vmerror("Cannot calculate cross-spectrum with a backward plan."); Vec_DP welch(winsize); Vec_DP::iterator p = welch.begin(); double temp; for (i = 0; i < winsize; ++i, ++p) { temp = (2.0 * i - winsize + 1.0) / (winsize + 1.0); (*p) = 1.0 - square(temp); } double data1_mean = mean(signal1); double data2_mean = mean(signal2); Vec_CPLX_DP sft(winsize); Vec_CPLX_DP x, y; Vec_CPLX_DP::iterator p1, p2, p3, a = cross.begin(), b = cross.end(); x.view(reinterpret_cast<CPLX_DP*>(incdp_), size_, str_in_); y.view(reinterpret_cast<CPLX_DP*>(outcdp_), size_, str_out_); Vec_DP xr = x.real(), xi = x.imag(); xi = 0.0; size_t nyq = winsize / 2; i = 0; k = 0; cross = CPLX_DP(0.0, 0.0); while (i < len - winsize) { xr = signal1.slice(i, winsize); xr -= data1_mean; xr *= welch; fourier(); sft = y; xr = signal2.slice(i, winsize); xr -= data2_mean; xr *= welch; fourier(); p2 = sft.begin(); p3 = y.begin(); for (p1 = a; p1 < b; ++p1, ++p2, ++p3) (*p1) += (*p2) * std::conj(*p3); i += nyq; ++k; } cross /= CPLX_DP(k * winsize); } void spectra(const Vec_DP& signal1, const Vec_DP& signal2, Vec_DP& pow1, Vec_DP& pow2, Vec_CPLX_DP& cross) const { size_t i, k, len = signal1.size(), winsize = pow1.size(); if (!len) vmerror("Spectra of zero size vector not allowed."); if (len != signal2.size()) vmerror("Size mismatch error in FFTPlan::spectra()."); if (!winsize) vmerror("Zero sample size error in FFTPlan::spectra()."); if (winsize != size_ || winsize != pow2.size() || winsize != cross.size()) vmerror("Size mismatch error in FFTPlan::spectra()."); if (type_ != C2C_PLAN) vmerror("Wrong plan-type in FFTPlan::spectra()."); if (winsize > len) vmerror("Size mismatch error in FFTPlan::spectra()."); if (direction_ == BACKWARD) vmerror("Cannot calculate spectra with a backward plan."); Vec_DP welch(winsize); Vec_DP::iterator p = welch.begin(); double temp; for (i = 0; i < winsize; ++i,++p) { temp = (2.0 * i - winsize + 1.0) / (winsize + 1.0); (*p) = 1.0 - square(temp); } double data1_mean = mean(signal1); double data2_mean = mean(signal2); Vec_CPLX_DP sft(winsize); Vec_CPLX_DP x, y; x.view(reinterpret_cast<CPLX_DP*>(incdp_), size_, str_in_); y.view(reinterpret_cast<CPLX_DP*>(outcdp_), size_, str_out_); Vec_DP xr = x.real(), xi = x.imag(); xi = 0.0; Vec_CPLX_DP::iterator p1, p2, p3, a, b; Vec_DP::iterator p4, p5; size_t nyq = winsize / 2; i = 0; k = 0; a = cross.begin(); b = cross.end(); pow1 = 0.0; pow2 = 0.0; cross = CPLX_DP(0.0); while (i < len - winsize + 1) { xr = signal1.slice(i, winsize); xr -= data1_mean; xr *= welch; fourier(); sft = y; xr = signal2.slice(i, winsize); xr -= data2_mean; xr *= welch; fourier(); p2 = sft.begin(); p3 = y.begin(); p4 = pow1.begin(); p5 = pow2.begin(); for (p1 = a; p1 < b; ++p1, ++p2, ++p3, ++p4, ++p5) { (*p1) += (*p2) * std::conj(*p3); (*p4) += std::norm(*p2); (*p5) += std::norm(*p3); } i += nyq; ++k; } pow1 /= double(k * winsize); pow2 /= double(k * winsize); cross /= CPLX_DP(k * winsize); } void coherence(const Vec_DP& signal1, const Vec_DP& signal2, Vec_DP& coh) const { size_t len = signal1.size(), winsize = coh.size(); if (!len) vmerror("Coherence of zero size vector not allowed."); if (len != signal2.size()) vmerror("Size mismatch error in FFTPlan::coherence()."); if (!winsize) vmerror("Zero sample size error in FFTPlan::coherence()."); if (winsize != size_) vmerror("Size mismatch error in FFTPlan::coherence()."); if (type_ != C2C_PLAN) vmerror("Wrong plan-type in FFTPlan::coherence()."); if (winsize > len) vmerror("Size mismatch error in FFTPlan::coherence()."); if (direction_ == BACKWARD) vmerror("Cannot calculate coherence with a backward plan."); Vec_DP pow1(winsize), pow2(winsize); Vec_CPLX_DP cross(winsize); spectra(signal1, signal2, pow1, pow2, cross); Vec_DP::iterator p1, p3, p4, e = coh.end(); Vec_CPLX_DP::iterator p2 = cross.begin(); p3 = pow1.begin(); p4 = pow2.begin(); for (p1 = coh.begin(); p1 < e; ++p1, ++p2, ++p3, ++p4) (*p1) = std::abs(*p2) / std::sqrt((*p3) * (*p4)); } void filter(const Vec_DP& signal, Vec_DP& sigflt, const Filter& filt) const { size_t len = signal.size(); if (!len) vmerror("Cannot filter a zero length vector."); if (sigflt.size() != len) vmerror("Size mismatch error in FFTPlan::filter()."); if (size_ < len) vmerror("Plan too small error in FFTPlan::filter()."); if (type_ != R2R_PLAN) vmerror("Wrong plan type in FFTPlan::filter()."); if (direction_ != BIDIR) vmerror("Plan for filterring must be bidirectional."); Vec_DP x, y; x.view(indp_, size_, str_in_); y.view(outdp_, size_, str_out_); Vec_DP::iterator p1, e = x.end(); Vec_DP::const_iterator p2, a = signal.begin(), b = signal.end(); double sig_mean = mean(signal); p1 = x.begin(); for (p2 = a; p2 < b; ++p1, ++p2) (*p1) = (*p2) - sig_mean; for (; p1 < e; ++p1) (*p1) = 0.0; Vec_DP pwr(size_); filt.make_filter(pwr); pwr.apply(std::sqrt); fourier(); y *= pwr; ifourier(); x /= size_; sig_mean *= pwr[0]; sigflt = x.slice(0, len) + sig_mean; } void hilbert(const Vec_DP& signal, Vec_CPLX_DP& hil) const { size_t len = signal.size(), nyq = (size_ + 1) / 2; if (!len) vmerror("Cannot make Hilbert transform of a zero length vector."); if (hil.size() != len) vmerror("Size mismatch error in FFTPlan::hilbert()."); if (size_ < len) vmerror("Size mismatch error in FFTPlan::hilbert()."); if (type_ != C2C_PLAN) vmerror("Wrong plan type in FFTPlan::hilbert()."); if (direction_ != BIDIR) vmerror("Plan for Hilbert transform must be bidirectional."); Vec_CPLX_DP x, y; x.view(reinterpret_cast<CPLX_DP*>(incdp_), size_, str_in_); y.view(reinterpret_cast<CPLX_DP*>(outcdp_), size_, str_out_); Vec_DP xr = x.real(), xi = x.imag(); double sig_mean = mean(signal); xr = 0.0; Vec(xr.slice(0, len)) = signal; Vec(xr.slice(0, len)) -= sig_mean; xi = 0.0; fourier(); Vec_CPLX_DP::iterator p, a, b; a = y.begin(); b = a + nyq; for (p = a + 1; p < b; ++p) (*p) *= 2.0; b = y.end(); if (len % 2 == 0) ++p; for (; p < b; ++p) (*p) = 0.0; ifourier(); hil = x.slice(0, len); hil /= size_; } }; /****************************************************************************** * * Global Functions. * *****************************************************************************/ inline void power(const Vec_DP& signal, Vec_DP& pwr) { size_t winsize = pwr.size(); Vec_DP in(winsize), out(winsize); FFTPlan fft(in, out, FORWARD); fft.power(signal, pwr); } inline void cross_spectrum(const Vec_DP& signal1, const Vec_DP& signal2, Vec_CPLX_DP& cross) { size_t winsize = cross.size(); Vec_CPLX_DP in(winsize), out(winsize); FFTPlan fft(in, out, FORWARD); fft.cross_spectrum(signal1, signal2, cross); } inline void spectra(const Vec_DP& signal1, const Vec_DP& signal2, Vec_DP& pow1, Vec_DP& pow2, Vec_CPLX_DP& cross) { size_t winsize = pow1.size(); Vec_CPLX_DP in(winsize), out(winsize); FFTPlan fft(in, out, FORWARD); fft.spectra(signal1, signal2, pow1, pow2, cross); } inline void coherence(const Vec_DP& signal1, const Vec_DP& signal2, Vec_DP& coh) { size_t winsize = coh.size(); Vec_CPLX_DP in(winsize), out(winsize); FFTPlan fft(in, out, FORWARD); fft.coherence(signal1, signal2, coh); } inline void filter(const Vec_DP& signal, Vec_DP& sigflt, const Filter& filt, size_t pad = 0) { size_t len = signal.size(); Vec_DP in(len + pad), out(len + pad); FFTPlan fft(in, out, BIDIR); fft.filter(signal, sigflt, filt); } inline void hilbert(const Vec_DP& signal, Vec_CPLX_DP& hil, size_t pad = 0) { size_t len = signal.size(); Vec_CPLX_DP in(len + pad), out(len + pad); FFTPlan fft(in, out, BIDIR); fft.hilbert(signal, hil); } inline size_t good_size(size_t len, size_t factor = 1) { if (!factor) return 0; if (len < 128 * factor) return len + factor - (len % factor); size_t n, i, x; static size_t num[9] = {9, 75, 5, 45, 25, 27, 15, 1}; static size_t denom[9] = {4, 7, 3, 6, 5, 5, 4, 0}; n = factor; while (n < len) n <<= 1; x = n >> 1; i = 0; while (x < len) { x = (n >> denom[i]) * num[i]; ++i; } return x; } } /* namespace VM */ #endif /* VM_FFTW3_H */
[ "you@example.com" ]
you@example.com
4b357ea6fca548c0ff8d71d7b7cfc2cebc48ad0d
13c5777f79d7ff4fdfabda09c648e95818fd6d7f
/lamilputa27/src/common/cola/Cola.cc
2b1fd56273f1e2ddf4447e50d1b5760a6c205803
[]
no_license
jjputamierda/jueputahijueputa
884cb2c702d88e57203ee76ebccfa5025cc7ee23
e443e0175138440fdd205922c0ad0c5a4d8217f8
refs/heads/master
2023-02-13T21:16:19.226024
2021-01-08T18:33:25
2021-01-08T18:33:25
299,783,801
0
0
null
null
null
null
UTF-8
C++
false
false
4,076
cc
//Modificado de: https://gist.github.com/ictlyh/f8473ad0cb1008c6b32c41f3dea98ef5#file-producer-consumer-L25 //Autor Original: Yuanhao Luo "ictlyh" //Fecha de última modificación: 10/11/20 #include "Cola.h" /** @brief Método encargado de sacar un elemento de la cola y retornarlo. @details Se aplica un lock para que solo un hilo pueda entrar en la cola y evitar condiciones de carrera. Si la cola está vacía, se esperará de forma pasiva (wait) a que un elemento llegue a esta. Cuando la cola posea al menos un elemento, este se guardará en una variable auto y seguidamente se elimina de la cola (pop). La cola entonces se desbloquea y se retorna la variable que creada. @param[in] N/A @param[out] N/A @pre No hay ningún prerrequisito, aparte de que la cola exista @remark Ninguna observación destacable. @return El método retorna una variable de tipo auto, la cual se pretente que pueda ser cualquier tipo de variable (int, string, struct, ..) para así darle versatilidad a la cola. @exception Este método no puede lanzar ninguna clase de excepción. @author Isaac Herrera B43332 (Pandemic Plan Remastered) @date 9/9/20 */ template <typename T> T Cola<T>::pop(){ std::unique_lock<std::mutex> mlock(*m); if(this->cola.empty()){ this->condicion->wait(mlock); } auto mensaje = this->cola.front(); this->cola.pop(); mlock.unlock(); return mensaje; } /** @brief Método encargado de ingresar un elemento a la cola. @details Se recibe una variable "mensaje" que puede contener cualquier tipo de dato. Se ejecuta un mutex antes de que el dato sea almacenado en la cola, para evitar así condiciones de carrera. Se realiza un push a la cola y esta es desbloqueada inmediatamente después. @param[in] N/A @param[out] Se recibe la dirección de memoria donde se encuentra la variable mensaje que se desea almacenar en la cola. La cola no modifica dicha dirección. @pre Se espera que es parámetro "mensaje" exista y posea un dato, para que este se almacene en la cola. @remark Ninguna observación destacable. @return Este método no retorna ningún valor (void). @exception @author Isaac Herrera B43332 (Pandemic Plan Remastered) @date 9/9/20 */ template <typename T> void Cola<T>::push(const T& mensaje){ std::unique_lock<std::mutex> mlock(*m); this->cola.push(mensaje); mlock.unlock(); this->condicion->notify_one(); } /*Estas son plantillas que se deben definir para que la cola, a nivel de compilación, pueda "prepararse" para almacenar estos tipos de datos, ya que esta es emplantillada. Si se define con anticipación una estructura, esta también puede ser usada como plantilla para la cola, como es el caso de las estructuras "datosNodo" y de las capas. */ template class Cola<int>; template class Cola<std::string>; template class Cola<const char*>; template class Cola<struct datosNodo>; template class Cola<struct capaSuperior>; template class Cola<struct capaRed>; template class Cola<struct capaEnlace>; template class Cola<struct capaAplicacion>; template class Cola<struct estructuraAplicacion>; template class Cola<struct estructuraRed>; template class Cola<struct estructuraEnlace>; template class Cola<struct CapaAplicacion>; template class Cola<struct Mensaje>; template class Cola<struct Alcanzabilidad>; template class Cola<struct Forwarding>; template class Cola<struct BroadcastA>; template class Cola<struct BroadcastB>; template class Cola<struct CapaRedA>; template class Cola<struct CapaEnlaceB>; template class Cola<struct DatosMensaje>; template class Cola<struct CapaRed>; template class Cola<struct DatosForwarding>; template class Cola<struct Broadcast>; template class Cola<struct CapaEnlace>; template class Cola<struct ArbolGenerador>; template class Cola<struct DatosArbolGenerador>; template class Cola<struct Latido>; template class Cola<struct DatosForwardingAplicacion>; template class Cola<struct ForwardingAplicacion>;
[ "JUAN.HERRERARODRIGUEZ@ucr.ac.cr" ]
JUAN.HERRERARODRIGUEZ@ucr.ac.cr
094850b57fa5931d14e04dde8c500171e6b76d45
dad150b0426d9faf23de82a7879d1e4ed0ce57ef
/polygon.cpp
27545560d8b2d04be215bd438e190ced2bcaef44
[ "MIT" ]
permissive
niekbouman/convex_dynamics
39da10c1883204cd7ba6e44bf1ea41ad21771c15
387037dbcfb0c52110b78bca24b43e6c5c65942a
refs/heads/master
2020-04-12T09:05:50.170472
2018-11-06T13:02:43
2018-11-06T13:02:43
64,872,652
1
0
null
null
null
null
UTF-8
C++
false
false
5,557
cpp
#include "polygon.hpp" //#include <CGAL/Direction_2.h> #include <CGAL/Polygon_nop_decomposition_2.h> #include <CGAL/Small_side_angle_bisector_decomposition_2.h> #include <CGAL/Minkowski_sum_2.h> // typedef for the result type of the point location //using Site_2 = AT::Site_2; //using Locate_result = VD::Locate_result; //using Vertex_handle = VD::Vertex_handle; //using Halfedge_handle = VD::Halfedge_handle; void print_polygon(const Polygon_2 &P) { using std::cout; cout << " " << P.size() << " vertices: {"; for (auto vit = P.vertices_begin(); vit != P.vertices_end(); ++vit) { if (vit != P.vertices_begin()) cout << ","; cout << "{" << (*vit).x() << ',' << (*vit).y() << "}"; } cout << "}\n" ; } Polygon_2 convert_face_to_polygon(Face_handle f, int bound) { // Convert a voronoi region to a polygon of type Polygon_2 // (We need this because the CGAL::intersection function can, to the best of // our knowledge, not handle unbounded regions) // // If the region is unbounded, we clip it by adding an extra vertex on each // ray. The 'bound' parameter controls 'how far' the vertex will be placed Polygon_2 p; using Ccb_halfedge_circulator = VD::Ccb_halfedge_circulator; Ccb_halfedge_circulator ec_start = f->ccb(); Ccb_halfedge_circulator ec = ec_start; do { if (ec->is_ray()) { CGAL::Vector_2<K> v(ec->opposite()->face()->dual()->point(), ec->face()->dual()->point()); auto vp = v.perpendicular(CGAL::CLOCKWISE); auto t = bound; if (vp.squared_length() < 1) { t *= int(1.0 / std::sqrt(CGAL::to_double(vp.squared_length()))); // make sure that the extension will be not too short } if (ec->has_target()) { p.push_back(ec->target()->point() - t * vp); p.push_back(ec->target()->point()); } else p.push_back(ec->source()->point() + t * vp); } else p.push_back(ec->target()->point()); } while (++ec != ec_start); return p; } /* void print_polygon_with_holes(const Polygon_with_holes_2& pwh) { if (! pwh.is_unbounded()) { std::cout << "{ Outer boundary = "; print_polygon (pwh.outer_boundary()); } else std::cout << "{ Unbounded polygon." << std::endl; unsigned int k = 1; std::cout << " " << pwh.number_of_holes() << " holes:" << std::endl; for (auto hit = pwh.holes_begin(); hit != pwh.holes_end(); ++hit, ++k) { std::cout << " Hole #" << k << " = "; print_polygon (*hit); } std::cout << " }" << std::endl; } */ Polygon_2 extract_poly(const Polygon_with_holes_2 &poly) { // Extract a polygon from a more general object type // (CGAL::Polygon_with_holes_2), which is returned by several functions, like // minkowski sum. However, we never encounter polygons with holes. if (poly.is_unbounded()) throw std::runtime_error("polygon is unbounded"); if (poly.has_holes()) throw std::runtime_error("polygon has holes"); return poly.outer_boundary(); } Polygon_2 intersection(const Polygon_2 &PA, const Polygon_2 &PB) { // intersection of two overlapping polygons std::list<Polygon_with_holes_2> intR; CGAL::intersection(PA, PB, std::back_inserter(intR)); if (intR.size() != 1) throw std::runtime_error("intersection is disconnected"); const auto &shape = *(intR.begin()); return extract_poly(shape); } Polygon_2 union_of_overlapping_polygons(const std::vector<Polygon_2> &input) { // union of a list of overlapping polygons std::list<Polygon_with_holes_2> _union_result; CGAL::join(input.cbegin(), input.cend(), std::back_inserter(_union_result)); if (_union_result.size() != 1) throw std::runtime_error("union is disconnected"); const auto &shape = *(_union_result.begin()); return remove_collinear_vertices(extract_poly(shape)); } Polygon_2 remove_collinear_vertices(const Polygon_2 &P) { Polygon_2 reduced; auto i = P.vertices_circulator(); auto start = i; do { if (!CGAL::collinear(*(i - 1), *i, *(i + 1))) reduced.push_back(*i); } while (++i != start); return reduced; } Polygon_2 remove_repeated_vertices(const Polygon_2 &P) { Polygon_2 reduced; auto i = P.vertices_circulator(); auto start = i; do { if (*i != *(i + 1)) reduced.push_back(*i); } while (++i != start); return reduced; } Polygon_2 remove_redundant_vertices(Polygon_2 P) { Polygon_2 Pp; do { Pp = P; P = remove_collinear_vertices(P); P = remove_repeated_vertices(P); } while (Pp != P); return P; } Polygon_2 minkowski_sum_between_nonconv_and_conv(const Polygon_2 &P, const Polygon_2 &Q) { CGAL::Small_side_angle_bisector_decomposition_2<K> ssab_decomp; CGAL::Polygon_nop_decomposition_2<K> nop; return extract_poly(CGAL::minkowski_sum_2(P, Q, ssab_decomp, nop)); } Polygon_2 minkowski_sum_between_convex_sets(const Polygon_2 &P, const Polygon_2 &Q) { CGAL::Polygon_nop_decomposition_2<K> nop; return extract_poly(CGAL::minkowski_sum_2(P, Q, nop)); } double find_bounding_radius(const Polygon_2 &P) { auto max_abs_coord = [](const auto &point) { return CGAL::max(CGAL::abs(point.x()), CGAL::abs(point.y())); }; auto it = std::max_element(P.vertices_begin(), P.vertices_end(), [&max_abs_coord](const auto &a, const auto &b) { return (max_abs_coord(a) < max_abs_coord(b)); }); return CGAL::to_double(max_abs_coord(*it)); }
[ "niekbouman@gmail.com" ]
niekbouman@gmail.com
3c03c658806c7b624a1ae938a686d9e76539e38e
8e56ba44a699f3f5feb44d12ab6356a09bc5a86d
/LearningOpenGL/Project1/Vector2D.cpp
0dfd4dee1ba3ac77f7cfbd6d5ce629b9bd87bb61
[]
no_license
rbtres/GamePhysics
37d85253c8401450145a303c38e7fc0403fe2ca1
7f8ed55597ab036584508878da4eed940981e1b9
refs/heads/master
2016-09-06T14:34:13.459734
2015-04-29T23:30:23
2015-04-29T23:30:23
29,218,084
0
0
null
null
null
null
UTF-8
C++
false
false
3,712
cpp
#include "Vector2D.h" #include <cmath> //-------------------------------------------------------------------------------------------- Vector2D::Vector2D() { X = 0; Y = 0; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- Vector2D::Vector2D(float x, float y) { X = x; Y = y; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- Vector2D::~Vector2D() { } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- Vector2D Vector2D::operator*(const float& rhs) { return Vector2D(X * rhs, Y * rhs); } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- Vector2D Vector2D::operator/(const float& rhs) { return Vector2D(X / rhs, Y / rhs); } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- Vector2D Vector2D::operator+(const Vector2D& rhs) { return Vector2D(X + rhs.X, Y + rhs.Y); } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- Vector2D Vector2D::operator-(const Vector2D& rhs) { return Vector2D(X - rhs.X, Y - rhs.Y); } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- bool Vector2D::operator==(const Vector2D& rhs) { return X == rhs.X && Y == rhs.Y; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- bool Vector2D::operator!=(const Vector2D& rhs) { return X != rhs.X || Y != rhs.Y; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- float Vector2D::Dot(const Vector2D& rhs) { return X * rhs.X + Y * rhs.Y; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- float Vector2D::Magnitude() { return sqrt(Dot(*this)); } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- float Vector2D::MagnitudeSqr() { return Dot(*this); } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- void Vector2D::Normalize() { Vector2D norm = Normalized(); X = norm.X; Y = norm.Y; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- Vector2D Vector2D::Normalized() { return (*this / Magnitude()); } //--------------------------------------------------------------------------------------------
[ "robert.bethune@Foster200-11.champlain.edu" ]
robert.bethune@Foster200-11.champlain.edu
184b658b6054a0f6793a54d392335fca2d6cd762
b46135c541b0296861932669cf187481397eed54
/TP5/tp3cpp/Rectangle.cpp
5390f0a762d84606250814887b114fa831d5d851
[]
no_license
Yvpouedogo/tpc-
a41f678ec7cef1177ca4346e95acab90d6565a3f
7e1fe0d550d004a7fd4a941966c3f113d78688be
refs/heads/master
2020-04-05T12:03:44.012284
2018-11-28T08:23:24
2018-11-28T08:23:24
156,856,808
0
0
null
null
null
null
UTF-8
C++
false
false
190
cpp
#include "Rectangle.hpp" Rectangle::Rectangle(int x, int y, int w, int h) { x=x; y=y; w=w; h=h; } Rectangle::Rectangle(int x1, int y1, int x2, int y2) { x=x1; y=y1; w=x2; h=y2; }
[ "Yves.POUEDOGO_NJIMEFO@etu.uca.fr" ]
Yves.POUEDOGO_NJIMEFO@etu.uca.fr
7d27b4d92a60f3d12b7feadc04c47e03eb2cbac7
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE23_Relative_Path_Traversal/s03/CWE23_Relative_Path_Traversal__wchar_t_connect_socket_ifstream_53b.cpp
adc3bbfe13718b077dd599e9dc250ecf5262b212
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
1,927
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__wchar_t_connect_socket_ifstream_53b.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-53b.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Use a fixed file name * Sink: ifstream * BadSink : Open the file named in data using ifstream::open() * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH L"c:\\temp\\" #else #include <wchar.h> #define BASEPATH L"/tmp/" #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #include <fstream> using namespace std; namespace CWE23_Relative_Path_Traversal__wchar_t_connect_socket_ifstream_53 { /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD /* bad function declaration */ void badSink_c(wchar_t * data); void badSink_b(wchar_t * data) { badSink_c(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(wchar_t * data); void goodG2BSink_b(wchar_t * data) { goodG2BSink_c(data); } #endif /* OMITGOOD */ } /* close namespace */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
c339696743e2e65157cdaa620bd0f781b44a4f04
25604990380f8ca32ed0b5a18e09ef3a2284c522
/Elcano_C5_Sonar/Elcano_C5_Sonar.ino
24bdc7966239ec01a34ee59901edc8443930ef5f
[ "MIT" ]
permissive
ract93/Elcano
e6ac4caf61352ec4f837e134ba05ce58cca50b18
656cfd197f349add5dbdc57689d7c0e693e206d7
refs/heads/master
2020-12-02T22:43:51.304093
2017-06-30T23:16:43
2017-06-30T23:16:43
96,172,764
0
0
null
null
null
null
UTF-8
C++
false
false
12,758
ino
/* SONAR BOARD The board uses an Arduino Micro, with interrupts on digital pins 0, 1, 2, 3 and 7. The interrupt numbers are 2, 3, 1, 0 and 4 respectively. Two boards can hold 12 sonars on the points of a clock. The front board holds Sonar 12 (straight ahead) and 1, 2, and 3F to the right. It also holds 9F, 10, and 11 to the left. The rear facing board holds 3R through 9R, with 6R pointing back. The front sonar board uses the SPI interface to appear as a slave to a host computer. When the host asks for sonar readings, the front board sends all data. Two board operation is not yet implemented. The front board controls the rear board over an I2C interface. It will intruct the rear board to take readings when the front board is taking readings. The hardware is identical for the front and rear boards. There may be no rear board present. In this case, the front board may use the 6F socket. Sonars are grouped into three rounds so that multiple sonars can fire simultaneously and do not intefere with each other. Rounds are selected by the (S_DEC1, S_DEC2) signal, which is used as a Gray code (only one bit changes at a time). The 74139 2-to-4 line decoder chip selects outputs Y0,Y1,Y2 and Y3 based on inputs a and b Y1, Y2 and Y3 are active low, so they are passed through the SN74LVC3G14DCTR inverter to be active high. These signals go to the SN74LVCH8T245PWR transceiver, which enables the appropriate sonars. Round(AB) Output Sonars 00 Y0 none 01 Y1 9, 12, 3 11 Y2 6, 11, 2 10 Y3 1, 10 A round may fire up to 3 sonars. The sonar range may be reported as either an analog value or as a pulse width. A pulse width will cause an interrupt. There are three interrupt handlers, one for each sonar fired in the round. */ #define BAUD_RATE 115200 //Serial Baud Rate for debugging #define DEBUG_MODE true //When DEBUG_MODE is true, send data over Serial, false send data over SPI #define VERBOSE_DEBUG true //false //When sedning over Serial, true gives verbose output #define SONAR_POWER_5V true //TRUE for 5v sonar power, FALSE for 3.4v, // ------------------------------------------------------------------------------------------------- //Pin configuration for the Arduino Micro (atmega32u4) //If using I2C to communicate with rear board, its SDA will need to share pin 2 with PW_OR2 #define PW_OR1 3 //Pulse on the center and back of the board 6 or 12 #define PW_OR2 2 //Pulse on the left side of the board 9, 10, or 11 #define PW_OR3 7 //Pulse on the right side of the board 1, 2, or 3 #define S_DEC1 5 //Low order bit for selecting the round //S-DECx pins good - Tai B. #define S_DEC2 6 //Hi bit of round select #define V_ENABLE 13 //Apply power to sonars //POWER good - Tai B. #define V_TOGGLE 4 //(V_TOGGLE) HIGH for 3.4v, LOW for 5v sonar power #define F_BSY 11 //pin signals to rear sonar board IMPORTANT - FBSY should be pin 11 was 9 #define R_BSY 8 //pin signals from rear sonar bord IMPORTANT - RBSY should be pin 8 was 10 // ------------------------------------------------------------------------------------------------- #define DEBUG_PIN A0 //Light-emitting diode indicator for DEBUG_status = TRUE // ------------------------------------------------------------------------------------------------- #define TIMEOUT_PERIOD 100 //ms: 20.5ms for calc + up to 62ms for the reading + a little buffer #define ROUND_DELAY 100 //ms between rounds, seems to help stability //Modify EXPECTED_SIGNALS to match which sonars are on the board. #define EXPECTED_SIGNALS1 3 #define EXPECTED_SIGNALS2 3 #define EXPECTED_SIGNALS3 2 #define RANGE_DATA_SIZE 13 #define SAMPLE_DATA_SIZE 7 // ------------------------------------------------------------------------------------------------- //Bit Manipulation Functions #define cbi(port, bit) (port &= ~(1 << bit)) //Clear a bit #define sbi(port, bit) (port |= (1 << bit)) //Set a bit #define tbi(port, bit) (port ^= (1 << bit)) //toggle a bit #define ibh(port, bit) ((port & (1 << bit)) > 0) //Is a bit high #define ibl(port, bit) ((port & (1 << bit)) == 0) //Is a bit low #define valueToClockPosition(val) ((val >= 1 && val <= 3) ? (val - 1) : (val >= 9 && val <= 12) \ ? (val - 5) : (val == 6) ? 3 : -1 ) // ------------------------------------------------------------------------------------------------- #include <avr/wdt.h> // Watch Dog Timer (Allows me to reboot the Arduino) const int SCALE_FACTOR = 58; //to calculate the distance, use the scale factor of 58us per cm // SPI Slave Communications enum SPI_COMMAND : byte { INITIAL = 14, INDEX, LSB, MSB, INCREMENT, END }; //SPI Command list char receive_buffer[100]; // buffer to store input commands volatile byte position, data_index; // position : keeps track of buffer index; data_index: which finalRange index is send to the MASTER volatile boolean process_command; // tells me if there is a command that needs to be processed //For Sonar Interrupts volatile unsigned long timeLeft, timeRight, timeCenter; volatile unsigned long timeStart; volatile bool timeStartSet; volatile int isr1Count, isr2Count, isr3Count; volatile byte SignalsReceived; //For Sonar Data and Sample Storage enum SONAR : byte { S01, S02, S03, S06, S09, S10, S11, S12 }; //Sonar list int sampleRange[RANGE_DATA_SIZE][SAMPLE_DATA_SIZE]{}; //Stores sample readings from each sonar int range[RANGE_DATA_SIZE] = { INITIAL }; //Stores the final results of each sonar radar int roundCount, timeoutStart, timeSinceLastRound; byte sampleIndex; //Keeps track of which sample is being stored for the sampleRange array int controlSwitch; //Keeps track of each radar in binary form if enabled/disabled to store data // ------------------------------------------------------------------------------------------------- void setup() { //Baud rate configured for 115200 //It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB Serial.begin(BAUD_RATE); if (DEBUG_MODE) { //DEBUG LED test pinMode(DEBUG_PIN, OUTPUT); digitalWrite(DEBUG_PIN, HIGH); } else { //Serial Peripheral Interface (SPI) Setup pinMode(MISO, OUTPUT); // have to send on master in, *slave out* //SPI Control Register (SPCR) SPCR |= _BV(SPE); //Turn on SPI in slave mode (SPI Enable) SPCR |= _BV(SPIE); //Turn on interrupts for SPI (SPI Interrupt Enable) // get ready for an interrupt position = 0; // buffer empty process_command = false; //False until we have a request to process data_index = 1; //start the array index at 1 } pinMode(S_DEC1, OUTPUT); //Pin 5 (PWM) --> SD1 pinMode(S_DEC2, OUTPUT); //Pin 6 (PWM/A7) --> SD2 timeLeft = timeRight = timeCenter = timeStart = 0; roundCount = timeoutStart = timeSinceLastRound = 0; isr1Count = isr2Count = isr3Count = 0; timeStartSet = false; SignalsReceived = 0; controlSwitch = 0xFF; //Enable all the sonars ready to store data clearRangeData(); //initialize range array setRound(LOW, LOW); digitalWrite(F_BSY, HIGH); //Signal rear board that we are here; See if there is a rear board digitalWrite(V_TOGGLE, (SONAR_POWER_5V ? LOW:HIGH)); //Select 5V power(LOW), or 3.8V power(HIGH) //Turn on sonars digitalWrite(V_ENABLE, HIGH); //Required delay above 175ms after power-up with the board for all XL-MaxSonars to be ready delay(200); //Per sonar datasheet, needs 175ms for boot attachInterrupt( digitalPinToInterrupt(PW_OR2), ISRLeft, CHANGE ); attachInterrupt( digitalPinToInterrupt(PW_OR1), ISRCenter, CHANGE ); attachInterrupt( digitalPinToInterrupt(PW_OR3), ISRRight, CHANGE ); digitalWrite(F_BSY, LOW); //Open for business } // ------------------------------------------------------------------------------------------------- void loop() { if (process_command) { processCommand(); process_command = false; } setRound(LOW, LOW); //Send a pulse on sonars, superfluous interrupts(); // Not sure if we need this here at all //Gets the current sample index to be used for the range array sampleIndex = (roundCount % SAMPLE_DATA_SIZE); //***** ROUND 1 ************************************************************** SignalsReceived = 0; setRound(LOW, HIGH); //Send a pulse on sonars delayPeriod(EXPECTED_SIGNALS1); // if (bitRead(controlSwitch, S12)) // { sampleRange[12][sampleIndex] = (timeCenter - timeStart) / SCALE_FACTOR; // } // if (bitRead(controlSwitch, S03)) // { sampleRange[3][sampleIndex] = (timeRight - timeStart) / SCALE_FACTOR; // } // if (bitRead(controlSwitch, S09)) // { sampleRange[9][sampleIndex] = (timeLeft - timeStart) / SCALE_FACTOR; // } //***** ROUND 3 ************************************************************** SignalsReceived = 0; setRound(HIGH, HIGH); //Send a pulse on sonars delayPeriod(EXPECTED_SIGNALS3); // if (bitRead(controlSwitch, S10)) // { sampleRange[10][sampleIndex] = (timeLeft - timeStart) / SCALE_FACTOR; // } // if (bitRead(controlSwitch, S01)) // { sampleRange[1][sampleIndex] = (timeRight - timeStart) / SCALE_FACTOR; // } //****** ROUND 2 *************************************************************** SignalsReceived = 0; setRound(HIGH, LOW); //Send a pulse on sonars delayPeriod(EXPECTED_SIGNALS2); // if (bitRead(controlSwitch, S11)) // { sampleRange[11][sampleIndex] = (timeLeft - timeStart) / SCALE_FACTOR; // } // if (bitRead(controlSwitch, S02)) // { sampleRange[2][sampleIndex] = (timeRight - timeStart) / SCALE_FACTOR; // } // if (bitRead(controlSwitch, S06)) // { sampleRange[6][sampleIndex] = (timeCenter - timeStart) / SCALE_FACTOR; // } //****************************************************************************** //TO DO: Receive data from rear board if (sampleIndex == (SAMPLE_DATA_SIZE - 1)) { writeOutput(); } roundCount++; } // ------------------------------------------------------------------------------------------------- //we should rewrite this method to manipulate the digital pin registers rather that using //digitalWrite to toggle RND pins. This way the pins will change simultaneously, which //will create more reliable functionality -- tb //If Pin 4 is left open or held high (20uS or greater), the sensor will take a range reading //Bring high 20uS or more for range reading. void setRound(int highOrderBit, int lowOrderBit) { //Turn off all sonars if (highOrderBit == LOW && lowOrderBit == LOW) { cbi(PORTC, PC6); // digitalWrite(S_DEC1, LOW); cbi(PORTD, PD7); // digitalWrite(S_DEC2, LOW); } //SD1 = HIGH, SD2 = LOW. Clock positions 9, 12, and 3 else if (highOrderBit == LOW && lowOrderBit == HIGH) { cbi(PORTD, PD7); // digitalWrite(S_DEC2, LOW); sbi(PORTC, PC6); // digitalWrite(S_DEC1, HIGH); delayMicroseconds(50); cbi(PORTC, PC6); // digitalWrite(S_DEC1, LOW); } //SD1 = LOW, SD2 = HIGH. Clock positions 6, 11, and 2 else if (highOrderBit == HIGH && lowOrderBit == LOW) { cbi(PORTC, PC6); // digitalWrite(S_DEC1, LOW); sbi(PORTD, PD7); // digitalWrite(S_DEC2, HIGH); delayMicroseconds(50); cbi(PORTD, PD7); // digitalWrite(S_DEC2, LOW); } //SD1 = HIGH, SD2 = HIGH. Clock positions 10, and 1 else if (highOrderBit == HIGH && lowOrderBit == HIGH) { sbi(PORTC, PC6); // digitalWrite(S_DEC1, HIGH); sbi(PORTD, PD7); // digitalWrite(S_DEC2, HIGH); delayMicroseconds(50); cbi(PORTC, PC6); // digitalWrite(S_DEC1, LOW); cbi(PORTD, PD7); // digitalWrite(S_DEC2, LOW); } } // ------------------------------------------------------------------------------------------------- void delayPeriod(byte expectedSingal) { timeoutStart = millis(); while (SignalsReceived < expectedSingal) { if ((millis() - timeoutStart) > TIMEOUT_PERIOD) { break; } } delay(ROUND_DELAY); timeStartSet = false; }
[ "evramos@uw.edu" ]
evramos@uw.edu
e29bad1e35f04706793347d2bca42fa893f2b104
215750938b1dd4354eab9b8581eec76881502afb
/src/mfx/uitk/pg/EditText.h
16318c0e1617e35807eb9671cd74d976a5ce050e
[ "WTFPL" ]
permissive
EleonoreMizo/pedalevite
c28fd19578506bce127b4f451c709914ff374189
3e324801e3a1c5f19a4f764176cc89e724055a2b
refs/heads/master
2023-05-30T12:13:26.159826
2023-05-01T06:53:31
2023-05-01T06:53:31
77,694,808
103
8
null
null
null
null
UTF-8
C++
false
false
4,273
h
/***************************************************************************** EditText.h Author: Laurent de Soras, 2016 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #pragma once #if ! defined (mfx_uitk_pg_EditText_HEADER_INCLUDED) #define mfx_uitk_pg_EditText_HEADER_INCLUDED #if defined (_MSC_VER) #pragma warning (4 : 4250) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "mfx/uitk/PageInterface.h" #include "mfx/uitk/PageMgrInterface.h" #include "mfx/uitk/NBitmap.h" #include "mfx/uitk/NText.h" #include "mfx/uitk/NWindow.h" #include <map> namespace mfx { namespace uitk { class PageSwitcher; namespace pg { class EditText final : public PageInterface { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ public: class Param { public: std::string _title; // Input std::string _text; // Input/output bool _ok_flag = false; // Output }; explicit EditText (PageSwitcher &page_switcher); /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ protected: // mfx::uitk::PageInterface void do_connect (Model &model, const View &view, PageMgrInterface &page, Vec2d page_size, void *usr_ptr, const FontSet &fnt) final; void do_disconnect () final; // mfx::uitk::MsgHandlerInterface via mfx::uitk::PageInterface EvtProp do_handle_evt (const NodeEvt &evt) final; /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ private: enum Entry { Entry_WINDOW = 0, Entry_TITLE, Entry_TEXT, Entry_CURS, Entry_NAV_BEG, Entry_OK = Entry_NAV_BEG, Entry_CANCEL, Entry_SPACE, Entry_DEL, Entry_LEFT, Entry_RIGHT, Entry_CHAR_BEG }; enum Span : char32_t { Span_R = 2, Span_L }; typedef std::shared_ptr <NBitmap> BitmapSPtr; typedef std::shared_ptr <NText> TxtSPtr; typedef std::shared_ptr <NWindow> WinSPtr; typedef std::vector <TxtSPtr> TxtArray; typedef std::vector <int> NodeIdRow; typedef std::vector <NodeIdRow> NodeIdTable; typedef std::map <int, char32_t> CharMap; void update_display (); void update_curs (); void fill_nav (PageMgrInterface::NavLocList &nav_list, const NodeIdTable &nit, int x, int y) const; PageSwitcher & _page_switcher; PageMgrInterface * // 0 = not connected _page_ptr; Vec2d _page_size; const ui::Font * // 0 = not connected _fnt_ptr; Param * _param_ptr; WinSPtr _menu_sptr; BitmapSPtr _curs_sptr; TxtSPtr _title_sptr; TxtSPtr _text_sptr; TxtSPtr _ok_sptr; TxtSPtr _cancel_sptr; TxtSPtr _space_sptr; TxtSPtr _del_sptr; TxtSPtr _left_sptr; TxtSPtr _right_sptr; TxtArray _char_list; int _curs_pos; bool _curs_blink_flag; std::u32string _txt; CharMap _char_map; static const std::array <std::u32string, 1+7> _char_table; /*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ private: EditText () = delete; EditText (const EditText &other) = delete; EditText (EditText &&other) = delete; EditText & operator = (const EditText &other) = delete; EditText & operator = (EditText &&other) = delete; bool operator == (const EditText &other) const = delete; bool operator != (const EditText &other) const = delete; }; // class EditText } // namespace pg } // namespace uitk } // namespace mfx //#include "mfx/uitk/pg/EditText.hpp" #endif // mfx_uitk_pg_EditText_HEADER_INCLUDED /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
[ "fuck@fuck.fuck" ]
fuck@fuck.fuck
8e13b80f4e4f02af307cdaaa04575991a49fecfc
91ac3071b9e5de4ad796c884ab1d945234d79dc7
/Algorithm/Stringarray/spiralmatrix.cpp
63b6ae2af3420e4cfe4733ef5805cddfd937c845
[]
no_license
anshumanvarshney/CODE
aa22950acf1aed4a694774454716dd5acff38143
a93bb1f20a246948d178a1a59d1ce99945c063f6
refs/heads/master
2021-05-04T12:15:56.879649
2018-02-05T10:48:21
2018-02-05T10:48:21
120,291,672
0
0
null
null
null
null
UTF-8
C++
false
false
663
cpp
#include<bits/stdc++.h> using namespace std; const int MAX=100; void printspiral(int a[][MAX],int n) { int s=n/2,i,j,k,l,m; for(i=0;i<s;i++) { for(j=i;j<n-1-i;j++) cout<<a[i][j]<<" "; for(k=i;k<n-1-i;k++) cout<<a[k][n-1-i]<<" "; for(l=n-1-i;l>=i+1;l--) cout<<a[n-1-i][l]<<" "; for(m=n-1-i;m>=i+1;m--) cout<<a[m][i]<<" "; } if(n%2!=0) { cout<<a[s][s]; } cout<<"\n"; } int main() { int p,i,j; cin>>p; int a[MAX][MAX]; while(p--) { for(i=0;i<4;i++) { for(j=0;j<4;j++) { cin>>a[i][j]; } } printspiral(a,4); } return 0; }
[ "coviam@Anshumans-MacBook-Pro.local" ]
coviam@Anshumans-MacBook-Pro.local
13f65db72e4f59ebf5ab57364bdb1048f595b28e
e7e459165851a0cdefd0c8cad730b748cd98e2b1
/map_builder.cpp
5292d9c1ceacb08e91ac861802bbbdf0503d0e34
[ "MIT" ]
permissive
michael-novikov/TransportGuide
4f896b85536781f0ecc879705f489cf2860b68c7
77a4c77fc317dcb5dfb52effbb19cb82dc7cdfa8
refs/heads/master
2023-06-23T18:49:51.173277
2021-04-24T15:59:44
2021-04-24T15:59:44
298,062,688
0
0
MIT
2021-04-24T15:59:44
2020-09-23T18:41:22
C++
UTF-8
C++
false
false
13,125
cpp
#include "map_builder.h" #include "stop.h" #include "svg.h" #include "transport_manager_command.h" #include "projector_interface.h" #include "scanline_compressed_projection.h" #include "scanline_projection.h" #include <algorithm> #include <cstddef> #include <cstdlib> #include <iterator> #include <set> #include <utility> using namespace std; using namespace Svg; static vector<Coordinates> RecomputeBasedOnReferencePoint( std::vector<Stop> stops, const std::map<BusRoute::RouteNumber, BusRoute> &buses) { std::map<std::string, Coordinates *> stop_ptr; for (auto &stop : stops) { stop_ptr[stop.Name()] = &stop.StopCoordinates(); } set<Coordinates> reference_points; // 1. endpoints for (const auto &[bus_name, bus] : buses) { { auto endpoints = bus.Endpoints(); reference_points.insert(*stop_ptr.at(endpoints.first)); if (endpoints.second) { reference_points.insert(*stop_ptr.at(endpoints.second.value())); } } } // 2. stops crossed more than twice by any bus for (const auto &stop : stops) { for (const auto &[bus_name, bus] : buses) { int count_stop = count_if( begin(bus.Stops()), end(bus.Stops()), [&stop](const auto &bus_stop) { return bus_stop == stop.Name(); }); if (count_stop > 2) { reference_points.insert(stop.StopCoordinates()); } } } // 3. stops crossed by more than one bus for (const auto &stop : stops) { int count_stop = count_if(begin(buses), end(buses), [&stop](const auto &p) { return p.second.ContainsStop(stop.Name()); }); if (count_stop > 1) { reference_points.insert(stop.StopCoordinates()); } } for (const auto &[bus_name, bus] : buses) { size_t i{0}; auto stop_count = bus.Stops().size(); while (i < stop_count) { size_t j{i + 1}; for (; j < stop_count; ++j) { if (reference_points.count(*stop_ptr.at(bus.Stop(j)))) { break; } } if (j == stop_count) { break; } const auto &stop_i = *stop_ptr.at(bus.Stop(i)); const auto &stop_j = *stop_ptr.at(bus.Stop(j)); double lon_step = (stop_j.longitude - stop_i.longitude) / (j - i); double lat_step = (stop_j.latitude - stop_i.latitude) / (j - i); for (size_t k = i + 1; k < j; ++k) { auto &stop_k = *stop_ptr.at(bus.Stop(k)); stop_k.longitude = stop_i.longitude + lon_step * (k - i); stop_k.latitude = stop_i.latitude + lat_step * (k - i); } i = j; } } vector<Coordinates> points; transform(begin(stops), end(stops), back_inserter(points), [](const Stop &stop) { return stop.StopCoordinates(); }); return points; } static map<string, Svg::Point> ComputeStopsCoords(RenderSettings render_settings, const std::vector<Stop> &stops, const std::map<std::string, size_t> &stop_idx, const std::map<BusRoute::RouteNumber, BusRoute> &buses) { const auto points = RecomputeBasedOnReferencePoint(stops, buses); const double max_width = render_settings.width; const double max_height = render_settings.height; const double padding = render_settings.padding; const unique_ptr<Projector> projector = make_unique<ScanlineCompressedProjector>(points, stop_idx, buses, max_width, max_height, padding); map<string, Svg::Point> stops_coords; for (size_t i = 0; i < stops.size(); ++i) { stops_coords[stops[i].Name()] = projector->project(points[i]); } return stops_coords; } MapBuilder::MapBuilder(RenderSettings render_settings, const std::vector<Stop> &stops, const std::map<std::string, size_t> &stop_idx, const std::map<BusRoute::RouteNumber, BusRoute> &buses) : render_settings_(move(render_settings)) , stop_idx_(stop_idx) , buses_(buses) , stop_coordinates_(ComputeStopsCoords(render_settings_, stops, stop_idx_, buses)) { int color_idx{0}; for (const auto &[bus_no, bus] : buses_) { route_color[bus_no] = render_settings_.color_palette[color_idx]; color_idx = (color_idx + 1) % render_settings_.color_palette.size(); } doc_ = BuildMap(); } Svg::Document MapBuilder::BuildMap() const { Svg::Document doc; for (const auto &layer : render_settings_.layers) { (this->*build.at(layer))(doc); } return doc; } void MapBuilder::BuildTranslucentRoute(Svg::Document &doc) const { doc.Add( Rectangle{} .SetBasePoint({-render_settings_.outer_margin, -render_settings_.outer_margin}) .SetWidth(render_settings_.width + 2 * render_settings_.outer_margin) .SetHeight(render_settings_.height + 2 * render_settings_.outer_margin) .SetFillColor(render_settings_.underlayer_color) ); } Svg::Document MapBuilder::BuildRoute(const RouteInfo::Route &route) const { auto res = BuildMap(); BuildTranslucentRoute(res); for (const auto &layer : render_settings_.layers) { (this->*build_route.at(layer))(res, route); } return res; } Svg::Point MapBuilder::MapStop(const std::string &stop_name) const { return stop_coordinates_.at(stop_name); } void MapBuilder::BuildBusLines(Svg::Document &doc, const std::vector<std::pair<std::string, std::vector<std::string>>> &lines) const { for (const auto &line : lines) { auto route_line = Polyline{} .SetStrokeColor(route_color.at(line.first)) .SetStrokeWidth(render_settings_.line_width) .SetStrokeLineCap("round") .SetStrokeLineJoin("round"); for (const auto &stop_name : line.second) { route_line.AddPoint(MapStop(stop_name)); } doc.Add(route_line); } } void MapBuilder::BuildBusLines(Svg::Document &doc) const { vector<pair<string, vector<string>>> full_routes; for (const auto &[bus_no, bus] : buses_) { full_routes.emplace_back(bus_no, bus.Stops()); } BuildBusLines(doc, full_routes); } void MapBuilder::BuildBusLinesOnRoute(Svg::Document &doc, const RouteInfo::Route &route) const { vector<pair<string, vector<string>>> routes; for (const auto& activity : route) { if (holds_alternative<BusActivity>(activity)) { auto bus_activity = get<BusActivity>(activity); const auto& bus = buses_.at(bus_activity.bus); vector<string> bus_stops; copy_n( next(begin(bus.Stops()), bus_activity.start_stop_idx), bus_activity.span_count + 1, back_inserter(bus_stops) ); routes.emplace_back(bus.Number(), bus_stops); } } BuildBusLines(doc, routes); } void MapBuilder::BuildBusLabels(Svg::Document &doc, const std::vector<std::pair<std::string, std::vector<Svg::Point>>> &labels) const { auto create_bus_no_text = [&](string bus_no, const Svg::Point &point) -> Text { return Text{} .SetPoint(point) .SetOffset(render_settings_.bus_label_offset) .SetFontSize(render_settings_.bus_label_font_size) .SetFontFamily("Verdana") .SetFontWeight("bold") .SetData(bus_no); }; auto add_bus_label = [&](const string &label, const Svg::Point &point, const Color &stroke_color) { doc.Add(create_bus_no_text(label, point) .SetFillColor(render_settings_.underlayer_color) .SetStrokeColor(render_settings_.underlayer_color) .SetStrokeWidth(render_settings_.underlayer_width) .SetStrokeLineCap("round") .SetStrokeLineJoin("round")); doc.Add(create_bus_no_text(label, point).SetFillColor(stroke_color)); }; for (const auto &label : labels) { for (const auto &point : label.second) { add_bus_label(label.first, point, route_color.at(label.first)); } } } void MapBuilder::BuildBusLabels(Svg::Document &doc) const { vector<pair<string, vector<Svg::Point>>> labels; for (const auto &[bus_no, bus] : buses_) { vector<Svg::Point> points; const auto &first_stop = bus.Stops().front(); points.push_back(MapStop(first_stop)); const auto last_stop = bus.Stop(bus.Stops().size() / 2); if (!bus.IsRoundTrip() && first_stop != last_stop) { points.push_back(MapStop(last_stop)); } labels.emplace_back(bus_no, points); } BuildBusLabels(doc, labels); } void MapBuilder::BuildBusLabelsOnRoute(Svg::Document& doc, const RouteInfo::Route &route) const { vector<pair<string, vector<Svg::Point>>> labels; for (const auto& activity : route) { if (holds_alternative<BusActivity>(activity)) { auto bus_activity = get<BusActivity>(activity); const auto& bus = buses_.at(bus_activity.bus); vector<Svg::Point> points; auto endpoints = bus.Endpoints(); const auto &first_stop = bus.Stop(bus_activity.start_stop_idx); if ((first_stop == endpoints.first) || (endpoints.second && first_stop == endpoints.second)) { points.push_back(MapStop(first_stop)); } const auto &last_stop = bus.Stop(bus_activity.start_stop_idx + bus_activity.span_count); if ((endpoints.second && last_stop == endpoints.second) || (last_stop == endpoints.first)) { points.push_back(MapStop(last_stop)); } labels.emplace_back(bus.Number(), points); } } BuildBusLabels(doc, labels); } void MapBuilder::BuildStopPoints(Svg::Document &doc, const std::vector<std::string> &stop_names) const { for (const auto &stop_name : stop_names) { doc.Add(Circle{} .SetCenter(MapStop(stop_name)) .SetRadius(render_settings_.stop_radius) .SetFillColor("white") ); } } void MapBuilder::BuildStopPoints(Svg::Document &doc) const { vector<string> stop_names; for (const auto &[stop_name, stop_id] : stop_idx_) { stop_names.push_back(stop_name); } BuildStopPoints(doc, stop_names); } void MapBuilder::BuildStopPointsOnRoute(Svg::Document& doc, const RouteInfo::Route &route) const { vector<string> stop_names; for (const auto& activity : route) { if (holds_alternative<BusActivity>(activity)) { auto bus_activity = get<BusActivity>(activity); const auto& bus = buses_.at(bus_activity.bus); if (bus_activity.span_count > 0) { copy_n( begin(bus.Stops()) + bus_activity.start_stop_idx, bus_activity.span_count + 1, back_inserter(stop_names) ); } } } BuildStopPoints(doc, stop_names); } void MapBuilder::BuildStopLabels(Svg::Document &doc, const std::vector<std::string> &stop_names) const { for (const auto &stop_name : stop_names) { const auto common = Text{} .SetPoint(MapStop(stop_name)) .SetOffset(render_settings_.stop_label_offset) .SetFontSize(render_settings_.stop_label_font_size) .SetFontFamily("Verdana") .SetData(stop_name); doc.Add(Text{common} .SetFillColor(render_settings_.underlayer_color) .SetStrokeColor(render_settings_.underlayer_color) .SetStrokeWidth(render_settings_.underlayer_width) .SetStrokeLineCap("round") .SetStrokeLineJoin("round")); doc.Add(Text{common}.SetFillColor("black")); } } void MapBuilder::BuildStopLabels(Svg::Document &doc) const { vector<string> stop_names; for (const auto &[stop_name, stop_id] : stop_idx_) { stop_names.push_back(stop_name); } BuildStopLabels(doc, stop_names); } void MapBuilder::BuildStopLabelsOnRoute(Svg::Document& doc, const RouteInfo::Route &route) const { vector<string> stop_names; for (const auto& activity : route) { if (holds_alternative<WaitActivity>(activity)) { auto wait_activity = get<WaitActivity>(activity); stop_names.push_back(wait_activity.stop_name); } } if (route.size() > 1) { auto bus_activity = get<BusActivity>(route.back()); auto last_stop = buses_.at(bus_activity.bus).Stop(bus_activity.start_stop_idx + bus_activity.span_count); stop_names.push_back(last_stop); } BuildStopLabels(doc, stop_names); } const std::unordered_map<MapLayer, void (MapBuilder::*)(Svg::Document &) const> MapBuilder::build = { {MapLayer::BUS_LINES, &MapBuilder::BuildBusLines}, {MapLayer::BUS_LABELS, &MapBuilder::BuildBusLabels}, {MapLayer::STOP_POINTS, &MapBuilder::BuildStopPoints}, {MapLayer::STOP_LABELS, &MapBuilder::BuildStopLabels}, }; const std::unordered_map<MapLayer, void (MapBuilder::*)(Svg::Document &, const RouteInfo::Route &route) const> MapBuilder::build_route = { {MapLayer::BUS_LINES, &MapBuilder::BuildBusLinesOnRoute}, {MapLayer::BUS_LABELS, &MapBuilder::BuildBusLabelsOnRoute}, {MapLayer::STOP_POINTS, &MapBuilder::BuildStopPointsOnRoute}, {MapLayer::STOP_LABELS, &MapBuilder::BuildStopLabelsOnRoute}, };
[ "michael.alex.novikov@gmail.com" ]
michael.alex.novikov@gmail.com
0a53c315f3107d63ebe95de1f57173e03d453950
40712dc426dfb114dfabe5913b0bfa08ab618961
/Extras/COLLADA_DOM/src/1.4/dom/domSource.cpp
b56fd7657028c959166a665e8327b9b1823f30c7
[]
no_license
erwincoumans/dynamica
7dc8e06966ca1ced3fc56bd3b655a40c38dae8fa
8b5eb35467de0495f43ed929d82617c21d2abecb
refs/heads/master
2021-01-17T05:53:34.958159
2015-02-10T18:34:11
2015-02-10T18:34:11
31,622,543
7
3
null
null
null
null
UTF-8
C++
false
false
5,453
cpp
/* * Copyright 2006 Sony Computer Entertainment Inc. * * Licensed under the SCEA Shared Source License, Version 1.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://research.scea.com/scea_shared_source_license.html * * 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 <dae/daeDom.h> #include <dom/domSource.h> #include <dae/daeMetaCMPolicy.h> #include <dae/daeMetaSequence.h> #include <dae/daeMetaChoice.h> #include <dae/daeMetaGroup.h> #include <dae/daeMetaAny.h> #include <dae/daeMetaElementAttribute.h> daeElementRef domSource::create(daeInt bytes) { domSourceRef ref = new(bytes) domSource; return ref; } daeMetaElement * domSource::registerElement() { if ( _Meta != NULL ) return _Meta; _Meta = new daeMetaElement; _Meta->setName( "source" ); _Meta->registerClass(domSource::create, &_Meta); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( _Meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( _Meta, cm, 0, 0, 1 ); mea->setName( "asset" ); mea->setOffset( daeOffsetOf(domSource,elemAsset) ); mea->setElementType( domAsset::registerElement() ); cm->appendChild( mea ); cm = new daeMetaChoice( _Meta, cm, 1, 0, 1 ); mea = new daeMetaElementAttribute( _Meta, cm, 0, 1, 1 ); mea->setName( "IDREF_array" ); mea->setOffset( daeOffsetOf(domSource,elemIDREF_array) ); mea->setElementType( domIDREF_array::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( _Meta, cm, 0, 1, 1 ); mea->setName( "Name_array" ); mea->setOffset( daeOffsetOf(domSource,elemName_array) ); mea->setElementType( domName_array::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( _Meta, cm, 0, 1, 1 ); mea->setName( "bool_array" ); mea->setOffset( daeOffsetOf(domSource,elemBool_array) ); mea->setElementType( domBool_array::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( _Meta, cm, 0, 1, 1 ); mea->setName( "float_array" ); mea->setOffset( daeOffsetOf(domSource,elemFloat_array) ); mea->setElementType( domFloat_array::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( _Meta, cm, 0, 1, 1 ); mea->setName( "int_array" ); mea->setOffset( daeOffsetOf(domSource,elemInt_array) ); mea->setElementType( domInt_array::registerElement() ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); mea = new daeMetaElementAttribute( _Meta, cm, 2, 0, 1 ); mea->setName( "technique_common" ); mea->setOffset( daeOffsetOf(domSource,elemTechnique_common) ); mea->setElementType( domSource::domTechnique_common::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( _Meta, cm, 3, 0, -1 ); mea->setName( "technique" ); mea->setOffset( daeOffsetOf(domSource,elemTechnique_array) ); mea->setElementType( domTechnique::registerElement() ); cm->appendChild( mea ); cm->setMaxOrdinal( 3 ); _Meta->setCMRoot( cm ); // Ordered list of sub-elements _Meta->addContents(daeOffsetOf(domSource,_contents)); _Meta->addContentsOrder(daeOffsetOf(domSource,_contentsOrder)); // Add attribute: id { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "id" ); ma->setType( daeAtomicType::get("xsID")); ma->setOffset( daeOffsetOf( domSource , attrId )); ma->setContainer( _Meta ); ma->setIsRequired( true ); _Meta->appendAttribute(ma); } // Add attribute: name { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "name" ); ma->setType( daeAtomicType::get("xsNCName")); ma->setOffset( daeOffsetOf( domSource , attrName )); ma->setContainer( _Meta ); _Meta->appendAttribute(ma); } _Meta->setElementSize(sizeof(domSource)); _Meta->validate(); return _Meta; } daeElementRef domSource::domTechnique_common::create(daeInt bytes) { domSource::domTechnique_commonRef ref = new(bytes) domSource::domTechnique_common; return ref; } daeMetaElement * domSource::domTechnique_common::registerElement() { if ( _Meta != NULL ) return _Meta; _Meta = new daeMetaElement; _Meta->setName( "technique_common" ); _Meta->registerClass(domSource::domTechnique_common::create, &_Meta); _Meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( _Meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( _Meta, cm, 0, 1, 1 ); mea->setName( "accessor" ); mea->setOffset( daeOffsetOf(domSource::domTechnique_common,elemAccessor) ); mea->setElementType( domAccessor::registerElement() ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); _Meta->setCMRoot( cm ); _Meta->setElementSize(sizeof(domSource::domTechnique_common)); _Meta->validate(); return _Meta; } daeMetaElement * domSource::_Meta = NULL; daeMetaElement * domSource::domTechnique_common::_Meta = NULL;
[ "erwin.coumans@e05b9ecc-110c-11df-b47a-af0d17c1a499" ]
erwin.coumans@e05b9ecc-110c-11df-b47a-af0d17c1a499
e6ddc6eee0ec080f003bfb1cdd8b5e2dcff99c11
516babd52e0c5c5034af323d88045bff500732d2
/TBusyTruCFG.hxx
440938400632a97bff7107c36fb7846dd9903e75
[]
no_license
policheh/phos_fee_dim
9aa65ab55ece302c5fbd79902f4202d8f0779746
ff996717eeead5f1d266edf2c9381f58857d7e0b
refs/heads/master
2021-07-31T21:10:02.514067
2021-07-20T08:39:20
2021-07-20T08:39:20
121,374,697
0
0
null
null
null
null
UTF-8
C++
false
false
389
hxx
#ifndef TBUSYTRUCFG_HH #define TBUSYTRUCFG_HH #include <iostream> #include <vector> #include <stdint.h> #include "TBusyFeeCFG.hxx" #include "TSequencerCommand.hxx" #include "dim/dis.hxx" using namespace std; // TRU card BUSY monitoring class TBusyTruCFG : public TBusyFeeCFG { public: TBusyTruCFG(char* name, int truNum, vector<TSequencerCommand*> *sequence); }; #endif
[ "Boris.Polishchuk@cern.ch" ]
Boris.Polishchuk@cern.ch
3ebc879a1f7f35312c8c6e5bb901e71f54f7544d
acb84fb8d54724fac008a75711f926126e9a7dcd
/poj/poj3714.cpp
6aa4ae98fbae6d56ae5097ea35d56a44ba3e71b9
[]
no_license
zrt/algorithm
ceb48825094642d9704c98a7817aa60c2f3ccdeb
dd56a1ba86270060791deb91532ab12f5028c7c2
refs/heads/master
2020-05-04T23:44:25.347482
2019-04-04T19:48:58
2019-04-04T19:48:58
179,553,878
1
0
null
null
null
null
UTF-8
C++
false
false
1,247
cpp
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int tt; struct point{ int x,y,z; }p[200005],tmp[200005]; int n; bool cmp(const point&a,const point&b){ if(a.x!=b.x) return a.x<b.x; return a.y<b.y; } bool cmp2(const point&a,const point&b){ return a.y<b.y; } double solve(int l,int r){ if(l==r) return 1e100; int mid=(l+r)/2; double ans=1e100; ans=min(solve(l,mid),solve(mid+1,r)); int tot=0; for(int i=mid;i>=l;i--){ if(p[mid].x-p[i].x<=ans) tmp[tot++]=p[i]; else break; } for(int i=mid+1;i<=r;i++){ if(p[i].x-p[mid+1].x<=ans) tmp[tot++]=p[i]; else break; } sort(tmp,tmp+tot,cmp2); for(int i=0;i<tot;i++){ for(int j=i+1;j<tot&&tmp[j].y-tmp[i].y<=ans;j++){ if(tmp[i].z^tmp[j].z){ ans=min(ans,sqrt((tmp[i].x-tmp[j].x)*1LL*(tmp[i].x-tmp[j].x)+(tmp[i].y-tmp[j].y)*1LL*(tmp[i].y-tmp[j].y))); } } } return ans; } int main(){ scanf("%d",&tt); while(tt--){ scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d%d",&p[i].x,&p[i].y); p[i].z=0; } for(int i=1;i<=n;i++){ scanf("%d%d",&p[i+n].x,&p[i+n].y); p[i+n].z=1; } sort(p+1,p+2*n+1,cmp); printf("%.3f\n",solve(1,2*n)); } return 0; }
[ "zhangruotian@foxmail.com" ]
zhangruotian@foxmail.com
a8e5bdf57384a21bf4b3350bf08e185d28162ca5
cb93bcc328d66756cd22b58c8040489c1cfdfc04
/Project_Alice/Project/Alice_Engine/07.Component/RadioButton.h
48c1e1f7acdb83ec548f0479e25782611aef6a3c
[]
no_license
haeunjung/Team_Project
ba9661729ed25be4a3fb22dc288dee05281b2613
ecd2b67c504af116a2e4f30114fe943f3a472e19
refs/heads/master
2018-10-30T11:20:50.980879
2018-10-05T11:18:09
2018-10-05T11:18:09
103,035,103
4
0
null
null
null
null
UTF-8
C++
false
false
827
h
#pragma once #include "UIButton.h" WOOJUN_BEGIN class DLL CRadioButton : public CUIButton { private: friend class CGameObject; private: bool m_bClick; public: void RadioButtonOff(); bool GetClick(); public: bool Init() override; void Input(float _fTime) override; void Update(float _fTime) override; void LateUpdate(float _fTime) override; void Collision(float _fTime) override; void Render(float _fTime) override; CRadioButton* Clone() override; public: void OnCollisionEnter(CCollider* _pSrc, CCollider* _pDest, float _fTime) override; void OnCollisionStay(CCollider* _pSrc, CCollider* _pDest, float _fTime) override; void OnCollisionLeave(CCollider* _pSrc, CCollider* _pDest, float _fTime) override; private: CRadioButton(); CRadioButton(const CRadioButton& _RadioButton); ~CRadioButton(); }; WOOJUN_END
[ "woojun2010@naver.com" ]
woojun2010@naver.com
3fc18e0010dd5f7e8968ed4ab593ae1efc3f73a6
de78b74157de4cd70d70b3747756c99554bcd6bc
/LeetCode/Top/Easy/inOrder.cpp
aee2edb433727ccfd0f82ed4f1afb61f516cb2ce
[]
no_license
vidalmatheus/codes
ae1d5c31abf4f215c677109ef091221214c82758
de9dfeb721df7a4a3036c32c1c83c02c7b53b8ac
refs/heads/master
2023-02-09T15:32:04.713987
2020-12-21T15:04:00
2020-12-21T15:04:00
219,653,651
0
0
null
null
null
null
UTF-8
C++
false
false
1,712
cpp
#include <bits/stdc++.h> using namespace std; static int speedup=[](){ std::ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }(); struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<int> inorderTraversal(TreeNode* root) { if (root==nullptr) return {}; vector<int> ans; stack<TreeNode*> s; // in levelOrder we use a queue TreeNode* curr = root; while(!s.empty() || curr!=nullptr){ // we are finished when we don't have any nodes to go down (left and right sides) while(curr!=nullptr){ s.push(curr); curr=curr->left; // go down on leftside } // now we have a filled stack to goes through all its nodes, just popping them from the stack // we can use curr again curr = s.top(); s.pop(); ans.push_back(curr->val); // now we go rightside and after that repite all over again curr = curr->right; } return ans; } }; int main(){ /* 3 / \ 9 20 / \ / \ 2 1 15 7 */ TreeNode *root = new TreeNode(3); root->left = new TreeNode(9); root->right = new TreeNode(20); root->left->left = new TreeNode(2); root->left->right = new TreeNode(1); root->right->left = new TreeNode(15); root->right->right = new TreeNode(7); vector<int> v; Solution sol; v=sol.inorderTraversal(root); cout << "[ "; for (auto i:v){ cout << i << " "; } cout << "]" << endl; return 0; }
[ "matheusvidaldemenezes@gmail.com" ]
matheusvidaldemenezes@gmail.com
c70862241d6dcb7878b1b06111dfa6d007429674
4122acc5bd9ee517fdfd1307bf8a04cc7c95599c
/mindspore/ccsrc/backend/optimizer/gpu/add_relu_grad_v2_fusion.cc
c7e05c6b9ca87c65fa64917b23af4b91b3ddf2a6
[ "Apache-2.0", "MIT", "Libpng", "LicenseRef-scancode-proprietary-license", "LGPL-2.1-only", "AGPL-3.0-only", "MPL-2.0-no-copyleft-exception", "IJG", "Zlib", "MPL-1.1", "BSD-3-Clause", "BSD-3-Clause-Open-MPI", "MPL-1.0", "GPL-2.0-only", "MPL-2.0", "BSL-1.0", "LicenseRef-scancode-unknow...
permissive
limberc/mindspore
655bb4fc582a85711e70c31e12f611cf1a0f422e
e294acdffc9246cb6d77ea18ea00d08244d30c59
refs/heads/master
2023-02-18T20:10:22.588348
2021-01-23T15:33:01
2021-01-23T15:33:01
322,821,027
0
0
Apache-2.0
2021-01-18T14:07:45
2020-12-19T10:27:43
null
UTF-8
C++
false
false
3,421
cc
/** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 "backend/optimizer/gpu/add_relu_grad_v2_fusion.h" #include <memory> #include <vector> #include <string> #include "backend/session/anf_runtime_algorithm.h" #include "ir/primitive.h" #include "utils/utils.h" #include "backend/optimizer/common/helper.h" namespace mindspore { namespace opt { namespace { kernel::KernelBuildInfoPtr GenerateKernelBuildInfo(CNodePtr node) { std::vector<std::string> inputs_format; std::vector<std::string> outputs_format; std::vector<TypeId> inputs_type; std::vector<TypeId> outputs_type; kernel::KernelBuildInfo::KernelBuildInfoBuilder builder; for (size_t input_index = 0; input_index < AnfAlgo::GetInputTensorNum(node); ++input_index) { inputs_type.push_back(AnfAlgo::GetPrevNodeOutputInferDataType(node, input_index)); inputs_format.push_back(kOpFormat_DEFAULT); } for (size_t output_index = 0; output_index < AnfAlgo::GetOutputTensorNum(node); ++output_index) { outputs_type.push_back(AnfAlgo::GetOutputInferDataType(node, output_index)); outputs_format.push_back(kOpFormat_DEFAULT); } builder.SetInputsDeviceType(inputs_type); builder.SetInputsFormat(inputs_format); builder.SetOutputsDeviceType(outputs_type); builder.SetOutputsFormat(outputs_format); return builder.Build(); } } // namespace const BaseRef AddReluGradV2Fusion::DefinePattern() const { VectorRef relu_grad = VectorRef({prim::kPrimReluGradV2, VectorRef({prim::kPrimTensorAdd, x1_, x2_}), mask_}); return relu_grad; } const AnfNodePtr AddReluGradV2Fusion::Process(const FuncGraphPtr &graph, const AnfNodePtr &node, const EquivPtr &equiv) const { MS_EXCEPTION_IF_NULL(graph); MS_EXCEPTION_IF_NULL(node); MS_EXCEPTION_IF_NULL(equiv); auto x1 = utils::cast<AnfNodePtr>((*equiv)[x1_]); auto x2 = utils::cast<AnfNodePtr>((*equiv)[x2_]); auto mask = utils::cast<AnfNodePtr>((*equiv)[mask_]); auto tensor_add = AnfAlgo::GetInputNode(utils::cast<CNodePtr>(node), 0); MS_EXCEPTION_IF_NULL(tensor_add); auto users = GetRealNodeUsedList(graph, tensor_add); if (users->size() > 1) { return nullptr; } auto prim = std::make_shared<Primitive>(kFusedAddReluGradV2Name); MS_EXCEPTION_IF_NULL(prim); std::vector<AnfNodePtr> inputs = {NewValueNode(prim), x1, x2, mask}; auto add_relugrad = graph->NewCNode(inputs); MS_EXCEPTION_IF_NULL(add_relugrad); auto types = {AnfAlgo::GetOutputInferDataType(node, 0)}; auto shapes = {AnfAlgo::GetOutputInferShape(node, 0)}; AnfAlgo::SetOutputInferTypeAndShape(types, shapes, add_relugrad.get()); add_relugrad->set_scope(node->scope()); auto build_info = GenerateKernelBuildInfo(add_relugrad); AnfAlgo::SetSelectKernelBuildInfo(build_info, add_relugrad.get()); return add_relugrad; } } // namespace opt } // namespace mindspore
[ "chenweifeng720@huawei.com" ]
chenweifeng720@huawei.com
932fdd626f74f57d20f715b4dd3b1f13959a62b8
de182bef4000bfa3c8569079696b62042e1046d3
/iTestManager/ui_mainwindow.h
0a74307a646caeca1137f87ca9211f06bd91238d
[]
no_license
ashishpandya1984/QtExamples
41c5c274017b8aefd06ced4c9395b7b3613fd66b
2b0d41d201cc24864d8c975b048b6f8d1a568e47
refs/heads/master
2021-09-11T00:13:23.111896
2018-04-04T19:41:10
2018-04-04T19:41:10
108,021,369
1
0
null
null
null
null
UTF-8
C++
false
false
24,236
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.0.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QComboBox> #include <QtWidgets/QCommandLinkButton> #include <QtWidgets/QFrame> #include <QtWidgets/QGridLayout> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QStatusBar> #include <QtWidgets/QTabWidget> #include <QtWidgets/QTableView> #include <QtWidgets/QToolBar> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QVBoxLayout *verticalLayout_9; QFrame *frm_main; QGridLayout *gridLayout; QFrame *frm_mainOption; QVBoxLayout *verticalLayout; QCommandLinkButton *cmdBtn_usrMgmt; QCommandLinkButton *cmdBtn_termMgmt; QCommandLinkButton *cmdBtn_testMgmt; QFrame *frame_4; QFrame *ln_devider; QFrame *frm_mainContent; QVBoxLayout *verticalLayout_2; QTabWidget *tb_main_content; QWidget *tab_user_management; QVBoxLayout *verticalLayout_16; QFrame *frame_8; QVBoxLayout *verticalLayout_13; QGroupBox *groupBox_3; QVBoxLayout *verticalLayout_3; QTableView *tv_user_management; QFrame *frame_9; QVBoxLayout *verticalLayout_15; QPushButton *btn_register_usr; QWidget *tab_terminal_management; QVBoxLayout *verticalLayout_20; QFrame *frame_10; QVBoxLayout *verticalLayout_17; QGroupBox *groupBox_7; QVBoxLayout *verticalLayout_4; QTableView *tv_terminal_management; QFrame *frame_11; QVBoxLayout *verticalLayout_19; QPushButton *btn_register_terminal; QWidget *tab_test_case_management; QVBoxLayout *verticalLayout_24; QFrame *frame_12; QVBoxLayout *verticalLayout_21; QGroupBox *groupBox_8; QHBoxLayout *horizontalLayout_5; QLabel *label_11; QComboBox *comboBox_6; QLabel *label_12; QComboBox *comboBox_7; QLabel *label_13; QComboBox *comboBox_8; QPushButton *btn_search_tests; QGroupBox *groupBox_9; QVBoxLayout *verticalLayout_5; QTableView *tv_test_cases; QFrame *frame_13; QVBoxLayout *verticalLayout_23; QPushButton *btn_execute_selected_tests; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(1084, 726); QIcon icon; icon.addFile(QStringLiteral(":/images/images/iTestManager.png"), QSize(), QIcon::Normal, QIcon::Off); MainWindow->setWindowIcon(icon); MainWindow->setToolButtonStyle(Qt::ToolButtonIconOnly); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); verticalLayout_9 = new QVBoxLayout(centralWidget); verticalLayout_9->setSpacing(0); verticalLayout_9->setContentsMargins(11, 11, 11, 11); verticalLayout_9->setObjectName(QStringLiteral("verticalLayout_9")); verticalLayout_9->setContentsMargins(0, 0, 0, 0); frm_main = new QFrame(centralWidget); frm_main->setObjectName(QStringLiteral("frm_main")); frm_main->setFrameShape(QFrame::StyledPanel); frm_main->setFrameShadow(QFrame::Raised); gridLayout = new QGridLayout(frm_main); gridLayout->setSpacing(0); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); gridLayout->setContentsMargins(0, 0, 0, 0); frm_mainOption = new QFrame(frm_main); frm_mainOption->setObjectName(QStringLiteral("frm_mainOption")); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(10); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(frm_mainOption->sizePolicy().hasHeightForWidth()); frm_mainOption->setSizePolicy(sizePolicy); frm_mainOption->setFrameShape(QFrame::StyledPanel); frm_mainOption->setFrameShadow(QFrame::Raised); verticalLayout = new QVBoxLayout(frm_mainOption); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); cmdBtn_usrMgmt = new QCommandLinkButton(frm_mainOption); cmdBtn_usrMgmt->setObjectName(QStringLiteral("cmdBtn_usrMgmt")); cmdBtn_usrMgmt->setCheckable(false); cmdBtn_usrMgmt->setChecked(false); verticalLayout->addWidget(cmdBtn_usrMgmt); cmdBtn_termMgmt = new QCommandLinkButton(frm_mainOption); cmdBtn_termMgmt->setObjectName(QStringLiteral("cmdBtn_termMgmt")); cmdBtn_termMgmt->setCheckable(false); verticalLayout->addWidget(cmdBtn_termMgmt); cmdBtn_testMgmt = new QCommandLinkButton(frm_mainOption); cmdBtn_testMgmt->setObjectName(QStringLiteral("cmdBtn_testMgmt")); cmdBtn_testMgmt->setCheckable(false); verticalLayout->addWidget(cmdBtn_testMgmt); frame_4 = new QFrame(frm_mainOption); frame_4->setObjectName(QStringLiteral("frame_4")); QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Expanding); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(frame_4->sizePolicy().hasHeightForWidth()); frame_4->setSizePolicy(sizePolicy1); frame_4->setFrameShape(QFrame::StyledPanel); frame_4->setFrameShadow(QFrame::Raised); verticalLayout->addWidget(frame_4); gridLayout->addWidget(frm_mainOption, 0, 0, 1, 1); ln_devider = new QFrame(frm_main); ln_devider->setObjectName(QStringLiteral("ln_devider")); ln_devider->setFrameShape(QFrame::VLine); ln_devider->setFrameShadow(QFrame::Sunken); gridLayout->addWidget(ln_devider, 0, 1, 1, 1); frm_mainContent = new QFrame(frm_main); frm_mainContent->setObjectName(QStringLiteral("frm_mainContent")); QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy2.setHorizontalStretch(90); sizePolicy2.setVerticalStretch(0); sizePolicy2.setHeightForWidth(frm_mainContent->sizePolicy().hasHeightForWidth()); frm_mainContent->setSizePolicy(sizePolicy2); frm_mainContent->setFrameShape(QFrame::StyledPanel); frm_mainContent->setFrameShadow(QFrame::Raised); verticalLayout_2 = new QVBoxLayout(frm_mainContent); verticalLayout_2->setSpacing(0); verticalLayout_2->setContentsMargins(11, 11, 11, 11); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); verticalLayout_2->setContentsMargins(0, 0, 0, 0); tb_main_content = new QTabWidget(frm_mainContent); tb_main_content->setObjectName(QStringLiteral("tb_main_content")); tab_user_management = new QWidget(); tab_user_management->setObjectName(QStringLiteral("tab_user_management")); verticalLayout_16 = new QVBoxLayout(tab_user_management); verticalLayout_16->setSpacing(0); verticalLayout_16->setContentsMargins(11, 11, 11, 11); verticalLayout_16->setObjectName(QStringLiteral("verticalLayout_16")); verticalLayout_16->setContentsMargins(5, 5, 5, 0); frame_8 = new QFrame(tab_user_management); frame_8->setObjectName(QStringLiteral("frame_8")); frame_8->setFrameShape(QFrame::StyledPanel); frame_8->setFrameShadow(QFrame::Raised); verticalLayout_13 = new QVBoxLayout(frame_8); verticalLayout_13->setSpacing(6); verticalLayout_13->setContentsMargins(11, 11, 11, 11); verticalLayout_13->setObjectName(QStringLiteral("verticalLayout_13")); verticalLayout_13->setContentsMargins(0, 0, 0, 0); groupBox_3 = new QGroupBox(frame_8); groupBox_3->setObjectName(QStringLiteral("groupBox_3")); QSizePolicy sizePolicy3(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy3.setHorizontalStretch(0); sizePolicy3.setVerticalStretch(95); sizePolicy3.setHeightForWidth(groupBox_3->sizePolicy().hasHeightForWidth()); groupBox_3->setSizePolicy(sizePolicy3); verticalLayout_3 = new QVBoxLayout(groupBox_3); verticalLayout_3->setSpacing(3); verticalLayout_3->setContentsMargins(11, 11, 11, 11); verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3")); verticalLayout_3->setContentsMargins(5, 5, 5, 5); tv_user_management = new QTableView(groupBox_3); tv_user_management->setObjectName(QStringLiteral("tv_user_management")); tv_user_management->setFocusPolicy(Qt::WheelFocus); tv_user_management->setAlternatingRowColors(true); tv_user_management->setSelectionMode(QAbstractItemView::SingleSelection); tv_user_management->setSelectionBehavior(QAbstractItemView::SelectRows); tv_user_management->setShowGrid(false); tv_user_management->horizontalHeader()->setDefaultSectionSize(200); tv_user_management->horizontalHeader()->setMinimumSectionSize(200); tv_user_management->horizontalHeader()->setStretchLastSection(true); tv_user_management->verticalHeader()->setVisible(false); verticalLayout_3->addWidget(tv_user_management); frame_9 = new QFrame(groupBox_3); frame_9->setObjectName(QStringLiteral("frame_9")); QSizePolicy sizePolicy4(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy4.setHorizontalStretch(0); sizePolicy4.setVerticalStretch(0); sizePolicy4.setHeightForWidth(frame_9->sizePolicy().hasHeightForWidth()); frame_9->setSizePolicy(sizePolicy4); frame_9->setLayoutDirection(Qt::RightToLeft); frame_9->setFrameShape(QFrame::StyledPanel); frame_9->setFrameShadow(QFrame::Raised); verticalLayout_15 = new QVBoxLayout(frame_9); verticalLayout_15->setSpacing(0); verticalLayout_15->setContentsMargins(11, 11, 11, 11); verticalLayout_15->setObjectName(QStringLiteral("verticalLayout_15")); verticalLayout_15->setContentsMargins(0, 5, 0, 0); btn_register_usr = new QPushButton(frame_9); btn_register_usr->setObjectName(QStringLiteral("btn_register_usr")); QSizePolicy sizePolicy5(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy5.setHorizontalStretch(0); sizePolicy5.setVerticalStretch(0); sizePolicy5.setHeightForWidth(btn_register_usr->sizePolicy().hasHeightForWidth()); btn_register_usr->setSizePolicy(sizePolicy5); btn_register_usr->setMinimumSize(QSize(120, 30)); verticalLayout_15->addWidget(btn_register_usr); verticalLayout_3->addWidget(frame_9); verticalLayout_13->addWidget(groupBox_3); verticalLayout_16->addWidget(frame_8); tb_main_content->addTab(tab_user_management, QString()); tab_terminal_management = new QWidget(); tab_terminal_management->setObjectName(QStringLiteral("tab_terminal_management")); verticalLayout_20 = new QVBoxLayout(tab_terminal_management); verticalLayout_20->setSpacing(0); verticalLayout_20->setContentsMargins(11, 11, 11, 11); verticalLayout_20->setObjectName(QStringLiteral("verticalLayout_20")); verticalLayout_20->setContentsMargins(5, 5, 5, 0); frame_10 = new QFrame(tab_terminal_management); frame_10->setObjectName(QStringLiteral("frame_10")); frame_10->setFrameShape(QFrame::StyledPanel); frame_10->setFrameShadow(QFrame::Raised); verticalLayout_17 = new QVBoxLayout(frame_10); verticalLayout_17->setSpacing(6); verticalLayout_17->setContentsMargins(11, 11, 11, 11); verticalLayout_17->setObjectName(QStringLiteral("verticalLayout_17")); verticalLayout_17->setContentsMargins(0, 0, 0, 0); groupBox_7 = new QGroupBox(frame_10); groupBox_7->setObjectName(QStringLiteral("groupBox_7")); sizePolicy3.setHeightForWidth(groupBox_7->sizePolicy().hasHeightForWidth()); groupBox_7->setSizePolicy(sizePolicy3); verticalLayout_4 = new QVBoxLayout(groupBox_7); verticalLayout_4->setSpacing(3); verticalLayout_4->setContentsMargins(11, 11, 11, 11); verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4")); verticalLayout_4->setContentsMargins(5, 5, 5, 5); tv_terminal_management = new QTableView(groupBox_7); tv_terminal_management->setObjectName(QStringLiteral("tv_terminal_management")); tv_terminal_management->setAlternatingRowColors(true); tv_terminal_management->setSelectionMode(QAbstractItemView::SingleSelection); tv_terminal_management->setSelectionBehavior(QAbstractItemView::SelectRows); tv_terminal_management->setShowGrid(false); tv_terminal_management->horizontalHeader()->setDefaultSectionSize(200); tv_terminal_management->horizontalHeader()->setMinimumSectionSize(200); tv_terminal_management->horizontalHeader()->setStretchLastSection(true); tv_terminal_management->verticalHeader()->setVisible(false); verticalLayout_4->addWidget(tv_terminal_management); frame_11 = new QFrame(groupBox_7); frame_11->setObjectName(QStringLiteral("frame_11")); frame_11->setLayoutDirection(Qt::RightToLeft); frame_11->setFrameShape(QFrame::StyledPanel); frame_11->setFrameShadow(QFrame::Raised); verticalLayout_19 = new QVBoxLayout(frame_11); verticalLayout_19->setSpacing(0); verticalLayout_19->setContentsMargins(11, 11, 11, 11); verticalLayout_19->setObjectName(QStringLiteral("verticalLayout_19")); verticalLayout_19->setContentsMargins(0, 5, 0, 0); btn_register_terminal = new QPushButton(frame_11); btn_register_terminal->setObjectName(QStringLiteral("btn_register_terminal")); sizePolicy5.setHeightForWidth(btn_register_terminal->sizePolicy().hasHeightForWidth()); btn_register_terminal->setSizePolicy(sizePolicy5); btn_register_terminal->setMinimumSize(QSize(120, 30)); verticalLayout_19->addWidget(btn_register_terminal); verticalLayout_4->addWidget(frame_11); verticalLayout_17->addWidget(groupBox_7); verticalLayout_20->addWidget(frame_10); tb_main_content->addTab(tab_terminal_management, QString()); tab_test_case_management = new QWidget(); tab_test_case_management->setObjectName(QStringLiteral("tab_test_case_management")); verticalLayout_24 = new QVBoxLayout(tab_test_case_management); verticalLayout_24->setSpacing(0); verticalLayout_24->setContentsMargins(11, 11, 11, 11); verticalLayout_24->setObjectName(QStringLiteral("verticalLayout_24")); verticalLayout_24->setContentsMargins(5, 5, 5, 0); frame_12 = new QFrame(tab_test_case_management); frame_12->setObjectName(QStringLiteral("frame_12")); frame_12->setFrameShape(QFrame::StyledPanel); frame_12->setFrameShadow(QFrame::Raised); verticalLayout_21 = new QVBoxLayout(frame_12); verticalLayout_21->setSpacing(6); verticalLayout_21->setContentsMargins(11, 11, 11, 11); verticalLayout_21->setObjectName(QStringLiteral("verticalLayout_21")); verticalLayout_21->setContentsMargins(0, 0, 0, 0); groupBox_8 = new QGroupBox(frame_12); groupBox_8->setObjectName(QStringLiteral("groupBox_8")); QSizePolicy sizePolicy6(QSizePolicy::Preferred, QSizePolicy::Expanding); sizePolicy6.setHorizontalStretch(0); sizePolicy6.setVerticalStretch(5); sizePolicy6.setHeightForWidth(groupBox_8->sizePolicy().hasHeightForWidth()); groupBox_8->setSizePolicy(sizePolicy6); horizontalLayout_5 = new QHBoxLayout(groupBox_8); horizontalLayout_5->setSpacing(6); horizontalLayout_5->setContentsMargins(11, 11, 11, 11); horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5")); label_11 = new QLabel(groupBox_8); label_11->setObjectName(QStringLiteral("label_11")); QSizePolicy sizePolicy7(QSizePolicy::Fixed, QSizePolicy::Preferred); sizePolicy7.setHorizontalStretch(0); sizePolicy7.setVerticalStretch(0); sizePolicy7.setHeightForWidth(label_11->sizePolicy().hasHeightForWidth()); label_11->setSizePolicy(sizePolicy7); horizontalLayout_5->addWidget(label_11); comboBox_6 = new QComboBox(groupBox_8); comboBox_6->setObjectName(QStringLiteral("comboBox_6")); horizontalLayout_5->addWidget(comboBox_6); label_12 = new QLabel(groupBox_8); label_12->setObjectName(QStringLiteral("label_12")); sizePolicy7.setHeightForWidth(label_12->sizePolicy().hasHeightForWidth()); label_12->setSizePolicy(sizePolicy7); horizontalLayout_5->addWidget(label_12); comboBox_7 = new QComboBox(groupBox_8); comboBox_7->setObjectName(QStringLiteral("comboBox_7")); horizontalLayout_5->addWidget(comboBox_7); label_13 = new QLabel(groupBox_8); label_13->setObjectName(QStringLiteral("label_13")); sizePolicy7.setHeightForWidth(label_13->sizePolicy().hasHeightForWidth()); label_13->setSizePolicy(sizePolicy7); horizontalLayout_5->addWidget(label_13); comboBox_8 = new QComboBox(groupBox_8); comboBox_8->setObjectName(QStringLiteral("comboBox_8")); horizontalLayout_5->addWidget(comboBox_8); btn_search_tests = new QPushButton(groupBox_8); btn_search_tests->setObjectName(QStringLiteral("btn_search_tests")); sizePolicy5.setHeightForWidth(btn_search_tests->sizePolicy().hasHeightForWidth()); btn_search_tests->setSizePolicy(sizePolicy5); horizontalLayout_5->addWidget(btn_search_tests); verticalLayout_21->addWidget(groupBox_8); groupBox_9 = new QGroupBox(frame_12); groupBox_9->setObjectName(QStringLiteral("groupBox_9")); sizePolicy3.setHeightForWidth(groupBox_9->sizePolicy().hasHeightForWidth()); groupBox_9->setSizePolicy(sizePolicy3); verticalLayout_5 = new QVBoxLayout(groupBox_9); verticalLayout_5->setSpacing(3); verticalLayout_5->setContentsMargins(11, 11, 11, 11); verticalLayout_5->setObjectName(QStringLiteral("verticalLayout_5")); verticalLayout_5->setContentsMargins(5, 5, 5, 5); tv_test_cases = new QTableView(groupBox_9); tv_test_cases->setObjectName(QStringLiteral("tv_test_cases")); tv_test_cases->setAlternatingRowColors(true); tv_test_cases->setSelectionMode(QAbstractItemView::MultiSelection); tv_test_cases->setSelectionBehavior(QAbstractItemView::SelectRows); tv_test_cases->setShowGrid(false); tv_test_cases->horizontalHeader()->setDefaultSectionSize(200); tv_test_cases->horizontalHeader()->setMinimumSectionSize(200); tv_test_cases->horizontalHeader()->setStretchLastSection(true); tv_test_cases->verticalHeader()->setVisible(false); verticalLayout_5->addWidget(tv_test_cases); frame_13 = new QFrame(groupBox_9); frame_13->setObjectName(QStringLiteral("frame_13")); frame_13->setLayoutDirection(Qt::RightToLeft); frame_13->setFrameShape(QFrame::StyledPanel); frame_13->setFrameShadow(QFrame::Raised); verticalLayout_23 = new QVBoxLayout(frame_13); verticalLayout_23->setSpacing(0); verticalLayout_23->setContentsMargins(11, 11, 11, 11); verticalLayout_23->setObjectName(QStringLiteral("verticalLayout_23")); verticalLayout_23->setContentsMargins(0, 5, 0, 0); btn_execute_selected_tests = new QPushButton(frame_13); btn_execute_selected_tests->setObjectName(QStringLiteral("btn_execute_selected_tests")); sizePolicy5.setHeightForWidth(btn_execute_selected_tests->sizePolicy().hasHeightForWidth()); btn_execute_selected_tests->setSizePolicy(sizePolicy5); btn_execute_selected_tests->setMinimumSize(QSize(120, 30)); verticalLayout_23->addWidget(btn_execute_selected_tests); verticalLayout_5->addWidget(frame_13); verticalLayout_21->addWidget(groupBox_9); verticalLayout_24->addWidget(frame_12); tb_main_content->addTab(tab_test_case_management, QString()); verticalLayout_2->addWidget(tb_main_content); gridLayout->addWidget(frm_mainContent, 0, 2, 1, 1); verticalLayout_9->addWidget(frm_main); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 1084, 21)); MainWindow->setMenuBar(menuBar); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QStringLiteral("statusBar")); MainWindow->setStatusBar(statusBar); retranslateUi(MainWindow); tb_main_content->setCurrentIndex(0); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "iTestManager", 0)); cmdBtn_usrMgmt->setText(QApplication::translate("MainWindow", "User Management", 0)); cmdBtn_termMgmt->setText(QApplication::translate("MainWindow", "Terminal Management", 0)); cmdBtn_testMgmt->setText(QApplication::translate("MainWindow", "Test Management", 0)); groupBox_3->setTitle(QApplication::translate("MainWindow", "Registered Users", 0)); btn_register_usr->setText(QApplication::translate("MainWindow", "Register New User", 0)); tb_main_content->setTabText(tb_main_content->indexOf(tab_user_management), QApplication::translate("MainWindow", "User Management", 0)); groupBox_7->setTitle(QApplication::translate("MainWindow", "Manage Terminals", 0)); btn_register_terminal->setText(QApplication::translate("MainWindow", "Register New Terminal", 0)); tb_main_content->setTabText(tb_main_content->indexOf(tab_terminal_management), QApplication::translate("MainWindow", "Terminal Management", 0)); groupBox_8->setTitle(QApplication::translate("MainWindow", "Test Case Filter", 0)); label_11->setText(QApplication::translate("MainWindow", "Host", 0)); label_12->setText(QApplication::translate("MainWindow", "SDK", 0)); label_13->setText(QApplication::translate("MainWindow", "Search Criteria", 0)); btn_search_tests->setText(QApplication::translate("MainWindow", "Search", 0)); groupBox_9->setTitle(QApplication::translate("MainWindow", "Test Cases", 0)); btn_execute_selected_tests->setText(QApplication::translate("MainWindow", "Excute Selected Tests", 0)); tb_main_content->setTabText(tb_main_content->indexOf(tab_test_case_management), QApplication::translate("MainWindow", "Test Management", 0)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
[ "ashish.engineer84@gmail.com" ]
ashish.engineer84@gmail.com
8369894f2da9adedea4397dfeb2be026851989cd
8d5159a0d39f10f3a6a1bf1766e275095cd87379
/ash/home_screen/home_screen_controller.cc
0147545de83f3d7e75f99914d08bbe5d7158e660
[ "BSD-3-Clause" ]
permissive
cptjacky/chromium
8598b05d8baa46bd78ef40060e4ae9c527bc2bd2
df6f983ca489cd3b16e177348cbc282035a8faca
refs/heads/master
2023-03-16T03:59:43.459198
2019-11-07T17:48:42
2019-11-07T17:48:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,971
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/home_screen/home_screen_controller.h" #include <vector> #include "ash/home_screen/home_launcher_gesture_handler.h" #include "ash/home_screen/home_screen_delegate.h" #include "ash/home_screen/window_transform_to_home_screen_animation.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/window_properties.h" #include "ash/session/session_controller_impl.h" #include "ash/shelf/shelf.h" #include "ash/shell.h" #include "ash/wallpaper/wallpaper_controller_impl.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/overview/overview_controller.h" #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/window_state.h" #include "ash/wm/window_transient_descendant_iterator.h" #include "base/barrier_closure.h" #include "base/logging.h" #include "base/stl_util.h" #include "ui/aura/window.h" #include "ui/display/manager/display_manager.h" namespace ash { namespace { // Minimizes all windows in |windows| that aren't in the home screen container, // and are not in |windows_to_ignore|. Done in reverse order to preserve the mru // ordering. // Returns true if any windows are minimized. bool MinimizeAllWindows(const aura::Window::Windows& windows, const aura::Window::Windows& windows_to_ignore) { bool handled = false; aura::Window* container = Shell::Get()->GetPrimaryRootWindow()->GetChildById( kShellWindowId_HomeScreenContainer); for (auto it = windows.rbegin(); it != windows.rend(); it++) { if (!container->Contains(*it) && !base::Contains(windows_to_ignore, *it) && !WindowState::Get(*it)->IsMinimized()) { WindowState::Get(*it)->Minimize(); handled = true; } } return handled; } } // namespace HomeScreenController::HomeScreenController() : home_launcher_gesture_handler_( std::make_unique<HomeLauncherGestureHandler>()) { Shell::Get()->overview_controller()->AddObserver(this); Shell::Get()->wallpaper_controller()->AddObserver(this); } HomeScreenController::~HomeScreenController() { Shell::Get()->wallpaper_controller()->RemoveObserver(this); Shell::Get()->overview_controller()->RemoveObserver(this); } void HomeScreenController::Show() { DCHECK(Shell::Get()->tablet_mode_controller()->InTabletMode()); if (!Shell::Get()->session_controller()->IsActiveUserSessionStarted()) return; delegate_->ShowHomeScreenView(); UpdateVisibility(); aura::Window* window = delegate_->GetHomeScreenWindow(); if (window) Shelf::ForWindow(window)->MaybeUpdateShelfBackground(); } bool HomeScreenController::GoHome(int64_t display_id) { DCHECK(Shell::Get()->tablet_mode_controller()->InTabletMode()); OverviewController* overview_controller = Shell::Get()->overview_controller(); SplitViewController* split_view_controller = SplitViewController::Get(Shell::GetPrimaryRootWindow()); const bool split_view_active = split_view_controller->InSplitViewMode(); if (!features::IsDragFromShelfToHomeOrOverviewEnabled()) { if (home_launcher_gesture_handler_->ShowHomeLauncher( Shell::Get()->display_manager()->GetDisplayForId(display_id))) { return true; } if (overview_controller->InOverviewSession()) { // End overview mode. overview_controller->EndOverview( OverviewSession::EnterExitOverviewType::kSlideOutExit); return true; } if (split_view_active) { // End split view mode. split_view_controller->EndSplitView( SplitViewController::EndReason::kHomeLauncherPressed); return true; } // The home screen opens for the current active desk, there's no need to // minimize windows in the inactive desks. if (MinimizeAllWindows( Shell::Get()->mru_window_tracker()->BuildWindowForCycleList( kActiveDesk), {} /*windows_to_ignore*/)) { return true; } return false; } // The home screen opens for the current active desk, there's no need to // minimize windows in the inactive desks. aura::Window::Windows windows = Shell::Get()->mru_window_tracker()->BuildWindowForCycleList(kActiveDesk); // The foreground window or windows (for split mode) - the windows that will // not be minimized without animations (instead they wil bee animated into the // home screen). std::vector<aura::Window*> active_windows; if (split_view_active) { active_windows = {split_view_controller->left_window(), split_view_controller->right_window()}; base::EraseIf(active_windows, [](aura::Window* window) { return !window; }); } else if (!windows.empty() && !WindowState::Get(windows[0])->IsMinimized()) { active_windows.push_back(windows[0]); } if (split_view_active) { // End split view mode. split_view_controller->EndSplitView( SplitViewController::EndReason::kHomeLauncherPressed); // If overview session is active (e.g. on one side of the split view), end // it immediately, to prevent overview UI being visible while transitioning // to home screen. if (overview_controller->InOverviewSession()) { overview_controller->EndOverview( OverviewSession::EnterExitOverviewType::kImmediateExit); } } // If overview is active (if overview was active in split view, it exited by // this point), just fade it out to home screen. if (overview_controller->InOverviewSession()) { overview_controller->EndOverview( OverviewSession::EnterExitOverviewType::kFadeOutExit); return true; } delegate_->OnHomeLauncherTargetPositionChanged(true /* showing */, display_id); // First minimize all inactive windows. const bool window_minimized = MinimizeAllWindows(windows, active_windows /*windows_to_ignore*/); // Animate currently active windows into the home screen - they will be // minimized by WindowTransformToHomeScreenAnimation when the transition // finishes. if (!active_windows.empty()) { base::RepeatingClosure window_transforms_callback = base::BarrierClosure( active_windows.size(), base::BindOnce(&HomeScreenController::NotifyHomeLauncherTransitionEnded, weak_ptr_factory_.GetWeakPtr(), true /*shown*/, display_id)); for (auto* active_window : active_windows) { BackdropWindowMode original_backdrop_mode = active_window->GetProperty(kBackdropWindowMode); active_window->SetProperty(kBackdropWindowMode, BackdropWindowMode::kDisabled); // Do the scale-down transform for the entire transient tree. for (auto* window : GetTransientTreeIterator(active_window)) { // Self-destructed when window transform animation is done. new WindowTransformToHomeScreenAnimation( window, window == active_window ? base::make_optional(original_backdrop_mode) : base::nullopt, window == active_window ? window_transforms_callback : base::NullCallback()); } } } else { delegate_->OnHomeLauncherAnimationComplete(true /*shown*/, display_id); } return window_minimized || !active_windows.empty(); } void HomeScreenController::NotifyHomeLauncherTransitionEnded( bool shown, int64_t display_id) { if (delegate_) delegate_->OnHomeLauncherAnimationComplete(shown, display_id); } void HomeScreenController::SetDelegate(HomeScreenDelegate* delegate) { delegate_ = delegate; } void HomeScreenController::OnWindowDragStarted() { in_window_dragging_ = true; UpdateVisibility(); } void HomeScreenController::OnWindowDragEnded() { in_window_dragging_ = false; UpdateVisibility(); } bool HomeScreenController::IsHomeScreenVisible() const { return delegate_->IsHomeScreenVisible(); } void HomeScreenController::OnOverviewModeStarting() { const OverviewSession::EnterExitOverviewType overview_enter_type = Shell::Get() ->overview_controller() ->overview_session() ->enter_exit_overview_type(); const bool animate = overview_enter_type == OverviewSession::EnterExitOverviewType::kSlideInEnter || overview_enter_type == OverviewSession::EnterExitOverviewType::kFadeInEnter; const HomeScreenPresenter::TransitionType transition = overview_enter_type == OverviewSession::EnterExitOverviewType::kFadeInEnter ? HomeScreenPresenter::TransitionType::kScaleHomeOut : HomeScreenPresenter::TransitionType::kSlideHomeOut; home_screen_presenter_.ScheduleOverviewModeAnimation(transition, animate); } void HomeScreenController::OnOverviewModeEnding( OverviewSession* overview_session) { // The launcher should be shown after overview mode finishes animating, in // OnOverviewModeEndingAnimationComplete(). Overview however is nullptr by the // time the animations are finished, so cache the exit type here. overview_exit_type_ = base::make_optional(overview_session->enter_exit_overview_type()); } void HomeScreenController::OnOverviewModeEndingAnimationComplete( bool canceled) { if (canceled) return; DCHECK(overview_exit_type_.has_value()); const bool animate = *overview_exit_type_ == OverviewSession::EnterExitOverviewType::kSlideOutExit || *overview_exit_type_ == OverviewSession::EnterExitOverviewType::kFadeOutExit; const HomeScreenPresenter::TransitionType transition = *overview_exit_type_ == OverviewSession::EnterExitOverviewType::kFadeOutExit ? HomeScreenPresenter::TransitionType::kScaleHomeIn : HomeScreenPresenter::TransitionType::kSlideHomeIn; overview_exit_type_ = base::nullopt; home_screen_presenter_.ScheduleOverviewModeAnimation(transition, animate); // Make sure the window visibility is updated, in case it was previously // hidden due to overview being shown. UpdateVisibility(); } void HomeScreenController::OnWallpaperPreviewStarted() { in_wallpaper_preview_ = true; UpdateVisibility(); } void HomeScreenController::OnWallpaperPreviewEnded() { in_wallpaper_preview_ = false; UpdateVisibility(); } void HomeScreenController::UpdateVisibility() { if (!Shell::Get()->tablet_mode_controller()->InTabletMode()) return; aura::Window* window = delegate_->GetHomeScreenWindow(); if (!window) return; const bool in_overview = Shell::Get()->overview_controller()->InOverviewSession(); if (in_overview || in_wallpaper_preview_ || in_window_dragging_) window->Hide(); else window->Show(); } } // namespace ash
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
225f4d5e1b0d85d9e6a1c11da6fcd8c503e667df
904441a3953ee970325bdb4ead916a01fcc2bacd
/src/sys/misc/os/os_init.cpp
682847dac3d65bf65852ac5be253fb6dcd23d0e0
[ "MIT" ]
permissive
itm/shawn
5a75053bc490f338e35ea05310cdbde50401fb50
49cb715d0044a20a01a19bc4d7b62f9f209df83c
refs/heads/master
2020-05-30T02:56:44.820211
2013-05-29T13:34:51
2013-05-29T13:34:51
5,994,638
16
4
null
2014-06-29T05:29:00
2012-09-28T08:33:42
C++
UTF-8
C++
false
false
1,378
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "sys/misc/os/os_init.h" #include "sys/misc/os/log_sys_resources.h" #include "sys/misc/os/load_plugin_task.h" #include "sys/simulation/simulation_task_keeper.h" #include "sys/simulation/simulation_controller.h" namespace shawn { void init_misc_os( SimulationController& sc ) throw() { sc.simulation_task_keeper_w().add( new LogSysResourcesTask ); sc.simulation_task_keeper_w().add( new LoadPluginTask ); } } /*----------------------------------------------------------------------- * Source $Source: /cvs/shawn/shawn/sys/misc/os/os_init.cpp,v $ * Version $Revision: 38 $ * Date $Date: 2007-06-08 14:30:12 +0200 (Fri, 08 Jun 2007) $ *----------------------------------------------------------------------- * $Log: os_init.cpp,v $ *-----------------------------------------------------------------------*/
[ "github@farberg.de" ]
github@farberg.de
5eb50ddb7c571cf5d5a46a7865f3e0a5c8a93cca
c057e033602e465adfa3d84d80331a3a21cef609
/C/testcases/CWE127_Buffer_Underread/s03/CWE127_Buffer_Underread__new_char_loop_73b.cpp
f669b1f2e14fbcccdb496e358d7730cfead9fc8e
[]
no_license
Anzsley/My_Juliet_Test_Suite_v1.3_for_C_Cpp
12c2796ae7e580d89e4e7b8274dddf920361c41c
f278f1464588ffb763b7d06e2650fda01702148f
refs/heads/main
2023-04-11T08:29:22.597042
2021-04-09T11:53:16
2021-04-09T11:53:16
356,251,613
1
0
null
null
null
null
UTF-8
C++
false
false
2,210
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE127_Buffer_Underread__new_char_loop_73b.cpp Label Definition File: CWE127_Buffer_Underread__new.label.xml Template File: sources-sink-73b.tmpl.cpp */ /* * @description * CWE: 127 Buffer Under-read * BadSource: Set data pointer to before the allocated memory buffer * GoodSource: Set data pointer to the allocated memory buffer * Sinks: loop * BadSink : Copy data to string using a loop * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files * * */ #include "std_testcase.h" #include <list> #include <wchar.h> using namespace std; namespace CWE127_Buffer_Underread__new_char_loop_73 { #ifndef OMITBAD void badSink(list<char *> dataList) { /* copy data out of dataList */ char * data = dataList.back(); { size_t i; char dest[100]; memset(dest, 'C', 100-1); /* fill with 'C's */ dest[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ for (i = 0; i < 100; i++) { dest[i] = data[i]; } /* Ensure null termination */ dest[100-1] = '\0'; printLine(dest); /* INCIDENTAL CWE-401: Memory Leak - data may not point to location * returned by new [] so can't safely call delete [] on it */ } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(list<char *> dataList) { char * data = dataList.back(); { size_t i; char dest[100]; memset(dest, 'C', 100-1); /* fill with 'C's */ dest[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ for (i = 0; i < 100; i++) { dest[i] = data[i]; } /* Ensure null termination */ dest[100-1] = '\0'; printLine(dest); /* INCIDENTAL CWE-401: Memory Leak - data may not point to location * returned by new [] so can't safely call delete [] on it */ } } #endif /* OMITGOOD */ } /* close namespace */
[ "65642214+Anzsley@users.noreply.github.com" ]
65642214+Anzsley@users.noreply.github.com
6e0eb3381c71d224fb62be46c3fc48bc828f6cd8
6bfc2ba7ee5f32685c4ec385631a71731b76dde6
/BST/Construct BST from preorder traversal 2.cpp
c96694de14d516637c32062bdb6685a7c547c52d
[]
no_license
rishabh-shukla/code
881871ff573751c806e6012d47e45f6196626416
951a17541cbf9fac33fb34c96aa2a6e7890003ad
refs/heads/master
2021-01-10T23:16:07.058076
2017-07-31T10:59:18
2017-07-31T10:59:18
70,623,468
0
0
null
null
null
null
UTF-8
C++
false
false
1,634
cpp
#include <stdio.h> #include <stdlib.h> #include <limits.h> struct node { int data; struct node *left; struct node *right; }; struct node* newNode (int data) { struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; return temp; } struct node* constructTreeUtil( int pre[], int* preIndex, int key, int min, int max, int size ) { if( *preIndex >= size ) return NULL; struct node* root = NULL; if( key > min && key < max ) { root = newNode ( key ); *preIndex = *preIndex + 1; if (*preIndex < size) { root->left = constructTreeUtil( pre, preIndex, pre[*preIndex], min, key, size ); root->right = constructTreeUtil( pre, preIndex, pre[*preIndex], key, max, size ); } } return root; } struct node *constructTree (int pre[], int size) { int preIndex = 0; return constructTreeUtil ( pre, &preIndex, pre[0], INT_MIN, INT_MAX, size ); } void printInorder (struct node* node) { if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right); } int main () { int pre[] = {10, 5, 1, 7, 40, 50}; int size = sizeof( pre ) / sizeof( pre[0] ); struct node *root = constructTree(pre, size); printf("Inorder traversal of the constructed tree: \n"); printInorder(root); return 0; }
[ "noreply@github.com" ]
rishabh-shukla.noreply@github.com
5cf166099f6931b1075300d4227896a68e65c7b2
f016a655deac2058570a7b70c0f2b08a44071c93
/src/main/cpp/commands/intakeRollersIn.cpp
04912eff1dddbc8a2030c000cd3851c6425ca149
[]
no_license
FRC6474/DeepSpace
9158f9457c5c293dea6037e7020cee10a6451493
9677a24bed58b0929b50973f16a3c82712fbca65
refs/heads/master
2020-05-30T10:06:07.153723
2019-12-23T15:13:40
2019-12-23T15:13:40
189,664,980
0
0
null
null
null
null
UTF-8
C++
false
false
777
cpp
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "commands/intakeRollersIn.h" intakeRollersIn::intakeRollersIn() { // Use Requires() here to declare subsystem dependencies // eg. Requires(Robot::chassis.get()); } // Called once when the command executes void intakeRollersIn::Initialize() { Robot::m_intake.RollersIn(); }
[ "51249178+FRC6474@users.noreply.github.com" ]
51249178+FRC6474@users.noreply.github.com
ce470b7832122a7efaac77c906376252ddbf9639
73ca9575897d66bc564f521cc3034608af9c7c3a
/Bai 5.cpp
2f8eaaf379bb8c15799483b857e02ffc08e02829
[]
no_license
anh5/Tran_Ky_Anh-Bai-thi-giua-ky
5fcbb1c0287c85cd9a8dfc367b04233fe33a1632
d98c064cbb395e2bebfb9af2d1172d7e5a47f505
refs/heads/master
2021-06-13T20:00:33.544725
2021-02-28T00:43:35
2021-02-28T00:43:35
131,608,137
1
0
null
null
null
null
UTF-8
C++
false
false
591
cpp
#include<iostream> using namespace std; class date{ private: int day,month,year; public: void get(int a,int b,int c) { day=a; month=b; year=c; } void getdate() { int a,b,c; char ch1,ch2; cout<<"\nEnter a date(mm/dd/yy): "; cin>>a>>ch1>>b>>ch2>>c; get(b,a,c); } int getday() { return day; } int getmonth() { return month; } int getyear() { return year; } void showdate() { cout<<"\nDate is: "<<getmonth()<<"/"<<getday()<<"/"<<getyear(); } }; int main() { date d1; d1.getdate(); d1.showdate(); return 0; }
[ "anhtrankyd15@gmail.com" ]
anhtrankyd15@gmail.com
c0e78007f250f70492382e788dfc696ef4b81e56
68602134d4a9d0ed0f85f7898633272518567468
/src/fista.cpp
87f4f99c75afb2ee875574c6786935bd7eadb0af
[]
no_license
sohelmsc/FISTA_FDCT3D
8bcc240334a3f1519d0d897bbe441b7e7f92d00f
8f6e57c9764300b2a7628ec4d73597fd31e2ff5a
refs/heads/master
2016-09-01T17:27:25.525957
2015-05-14T01:18:05
2015-05-14T01:18:05
35,582,055
0
0
null
null
null
null
UTF-8
C++
false
false
3,642
cpp
/* ================================================================================= * Name : Fista.cpp * Author : Mafijul Bhuiyan * Version : 1.0 * Purpose : To reconstruct 3D/2D seismic data * Date : September 12, 2014 * Affiliation : University of Alberta, Physics department, (SAIG) * Email : mbhuiyan@ualberta.ca * =================================================================================== */ #include "fistaParams.hpp" #include "fistaCore.hpp" #include "PARAMS.hpp" #include "fdct3d.hpp" #include "fdct3dinline.hpp" #include <cmath> int optionsCreate(const char* optfile, map<string,string>& options) { options.clear(); ifstream fin(optfile); fin.open("/home/entropy/workspace/fdct3d/src/params.txt"); assert(fin.good()); string name; fin>>name; while(fin.good()) { char cont[100]; fin.getline(cont, 99); options[name] = string(cont); fin>>name; } fin.close(); return 0; } int main(int argc, char** argv) { clock_t start, finish; /** Creating the objects of the dependence classes ************************************/ fistaParams fsp; fistaCore fsc; PARAMS params; /* Data initialisation */ fsp.maxItr = 140; fsp.eigenItr = 10; /*fsp.lambda.push_back(0.009); fsp.lambda.push_back(0.03); fsp.lambda.push_back(0.05);*/ // fsp.lambda.push_back(0.004); fsp.lambda.push_back(0.003); // fsp.lambda.push_back(0.0035); // You need data to run the code successfully *************************************/ fsp.inDataFileName = "/home/entropy/workspace/fdct3d/src/Data/oversampled_data.bin"; fsp.sampleMatFileName = "/home/entropy/workspace/fdct3d/src/Data/sobol_sample_80.bin"; fsp.outDataFileName = "/home/entropy/workspace/fdct3d/src/Data/reconData_80.bin"; /* Data initialisation for 3D FFT ****************************************************/ params.ac = 1; assert(argc==2); map<string, string> opts; optionsCreate(argv[2], opts); map<string,string>::iterator mi; mi = opts.find("-m"); assert(mi!=opts.end()); {istringstream ss((*mi).second); ss>>fsp.n1;} mi = opts.find("-n"); assert(mi!=opts.end()); {istringstream ss((*mi).second); ss>>fsp.n2;} mi = opts.find("-p"); assert(mi!=opts.end()); {istringstream ss((*mi).second); ss>>fsp.n3;} mi = opts.find("-nbscales"); assert(mi!=opts.end()); {istringstream ss((*mi).second); ss>>params.nbscales;} mi = opts.find("-nbdstz_coarse"); assert(mi!=opts.end()); {istringstream ss((*mi).second); ss>>params.nbdstz_coarse;} CpxNumTns init(fsp.n3,fsp.n2,fsp.n1); for(int i=0; i<fsp.n3; i++) for(int j=0; j<fsp.n2; j++) for(int k=0; k<fsp.n1; k++) init(i,j,k) = cpx(1.0, 0.0); //* Initialise the parameters for 3D curvelet transformation *************************** fdct3d_param(fsp.n3,fsp.n2,fsp.n1,params.nbscales,params.nbdstz_coarse,params.ac,params.fxs,params.fys,params.fzs, params.nxs,params.nys,params.nzs); fsc.readSampleMat(fsp.sampleMatFileName, fsp.n1, fsp.n2, fsp.n3, params.samplMat); fsp.alpha = 1.1; //*fsc.powerEigen(init, &fsp, &params); params.cellStruct.clear(); //* Executing FISTA optimisation code to reconstruct seismic data *********************/ start = clock(); fsc.Reconstruct(&fsp, &params, &fsc); finish = clock(); std::cout << "Time: " << (finish-start)/double(CLOCKS_PER_SEC) << " Seconds " <<std::endl; //* Clearing the memory space **********************************************************/ std::cout << "Cleared the memory space." <<std::endl; fsp.reset(); params.reset(); return 0; }
[ "sohelmsc@gmail.com" ]
sohelmsc@gmail.com
0a34092171b132b73de4858039d76cc9ce3201f1
c93ac2f725f4ea1e09ec3178dee52de56a41783a
/SPOJ/TRIGALGE.cpp
82e1f43c65d71de752b96418348e38aea5a07c80
[]
no_license
TheStranger512/Competitive-Programming-Stuff
4b51f140907c044616c28b14db28e881ee9d2f41
66824e816b1f3ee113e29444dab3506a668c437d
refs/heads/master
2021-01-21T01:26:36.676309
2014-01-22T08:18:01
2014-01-22T08:18:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
cpp
/* Solved * 10712. Easy Calculation * File: TRIGALGE.cpp * Author: Andy Y.F. Huang * Created on January 2, 2013, 1:15 PM */ #include <cstdio> #include <iostream> #include <cmath> #include <algorithm> #include <stack> #include <vector> #include <queue> #include <string> #include <cstring> #include <set> #include <map> #include <sstream> #include <deque> #include <iomanip> #include <cassert> #include <ctime> #include <functional> #include <complex> #include <numeric> #include <cctype> #include <cstddef> #include <utility> #include <valarray> #include <cstdlib> #ifdef AZN #include "Azn.cpp" #endif using namespace std; /** * Solved * @author Andy Y.F. Huang */ namespace TRIGALGE { void solve(int test_num) { int a, b, c; scanf("%d %d %d", &a, &b, &c); double low = -1e10, high = 1e10; while (abs(high - low) > 1e-6) { double mid = (low + high) / 2.0; if (a * mid + b * sin(mid) - c < 0) low = mid; else high = mid; } printf("%.6lf\n", low); } void solve() { #ifdef AZN freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int tests; scanf("%d", &tests); for (int i = 1; i <= tests; i++) solve(i); } } int main() { TRIGALGE::solve(); return 0; }
[ "huang.yf.andy@live.ca" ]
huang.yf.andy@live.ca
a13a24e78dff7b9249afcd4c970ad3027ec7cb37
53b9ed8fe5d3da380ef23a5aedf7557f1c2e82fe
/Square Root Decomposition MO's Algorithm/SPOJ D-Query.cpp
55d30c998beecfb44e492d11d173d178f1af7f5e
[]
no_license
BhuwaneshNainwal/DSA
37cada454c4c139e6f3a345b33ea18683a498eff
f75b91aa70701c3bef9dd38f75a2970ef2d9985e
refs/heads/master
2023-07-09T05:57:42.459007
2021-08-16T16:27:51
2021-08-16T16:27:51
355,267,090
3
0
null
null
null
null
UTF-8
C++
false
false
3,792
cpp
/* ॐ JAI SHREE RAM Hare Krishna Hare Krishna Krishna Krishna Hare Hare Hare Rama Hare Rama Rama Rama Hare Hare ॐ */ //Written by Bhuwanesh Nainwal #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; #define fast ios_base::sync_with_stdio(false) , cin.tie(NULL) , cout.tie(NULL) #define int long long int #define vci vector<int> #define vcvci vector<vector<int>> #define vcpi vector<pair<int,int>> #define vcs vector<string> #define pb push_back #define mpii map<int , int> #define mpsi map<string , int> #define mpci map<char , int> #define umpii unordered_map<int , int> #define umpsi unordered_map<string , int> #define umpci unordered_map<char , int> #define all(x) auto it = x.begin() ; it != x.end() ; it++ #define vcc vector<char> #define vcs vector<string> #define sti set<int> #define stc set<char> #define sts set<string> #define pqmx priority_queue<int> #define pqmn priority_queue<int , vi , greater<int>> #define null NULL #define ff first #define ss second #define stb(x) __builtin_popcount(x) #define lzr(x) __builtin_clz(x) #define tzr(x) __builtin_ctz(x) #define prc(x , y) fixed << setprecision(y) << x #define max3(a, b, c) max(a, max(b, c)) #define min3(a, b, c) min(a, min(b, c)) using namespace std; const int mod = 1e9 + 7; const int INF = 1e9; const int LINF = 1e18; const int N = 1e4; const int chkprc = 1e-9; // Check for precision error in double int fre[10000]; int distinct; struct query { int L; int R; int q_no; int block_no; bool operator < (query &q2) { if(block_no < q2.block_no) return 1; else if (block_no > q2.block_no) return 0; else return R < q2.R; } }; void Add(int elem) { if(fre[elem] == 0) distinct++; fre[elem]++; } void Remove(int elem) { fre[elem]--; if(fre[elem] == 0) distinct--; } void Adjust(int &curr_l , int &curr_r , query &q , vector<int> &ar) { while(curr_l < q.L) { Remove(ar[curr_l]); curr_l++; } while(curr_l > q.L) { curr_l--; Add(ar[curr_l]); } while(curr_r < q.R) { curr_r++; Add(ar[curr_r]); } while(curr_r > q.R) { Remove(ar[curr_r]); curr_r--; } } void solve(vector<query> &queries , vector<int> &ar , int q) { vector<int> answer(q1); sort(queries.begin(), queries.end()); memset(fre , 0 , sizeof(fre)); distinct = 0; int curr_l = queries[0].L; int curr_r = queries[0].R; for(int i = queries[0].L ; i <= queries[0].R ; i++) { Add(ar[i]); } answer[queries[0].q_no] = distinct; for(int i = 1 ; i < queries.size() ; i++) { Adjust(curr_l , curr_r , queries[i] , ar); answer[queries[i].q_no] = distinct; } for(int i = 0 ; i < answer.size(); i++) cout << answer[i] << " "; } void solve() { int n , q; vector<query> queries(n); cin >> n; vci ar(n); for(int i = 0 ; i < n ; i++) cin >> ar[i]; int rn = sqrt(n); cin >> q; for(int i = 0 ; i < q ; i++) { int u , v; cin >> u >> v; queries[i].L = u - 1; queries[i].R = v - 1; queries[i].q_no = i; queries[i].block_no = u / rn; } solve(queries , ar , q); } void local() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // ONLINE_JUDGE } int32_t main() { fast; local(); int T = 1; // cin>>T; while(T--) { solve(); } return 0; }
[ "harshitnainwal38@gmail.com" ]
harshitnainwal38@gmail.com
2b0087818a6a6e55859e292eddc55992ea642bcd
6de059a8cf18d4b4640e91390aac28fc90d84785
/src/qt/rpcconsole.cpp
437ab61d04ea47f3c8a9136857846962bcbb3838
[ "MIT" ]
permissive
irobotnik8/LobbyCoin
63f031ed4c8f65cea762e0e18e7324b46899bdd1
c9f677a6fd077c29f1ad8bab786a7117eec7e76d
refs/heads/master
2016-09-10T12:01:55.225028
2014-06-12T19:52:54
2014-06-12T19:52:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,287
cpp
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QTimer> #include <QThread> #include <QTextEdit> #include <QKeyEvent> #include <QUrl> #include <QScrollBar> #include <boost/tokenizer.hpp> #include <openssl/crypto.h> // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_SCROLLBACK = 50; const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor: public QObject { Q_OBJECT public slots: void start(); void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" void RPCExecutor::start() { // Nothing to do } void RPCExecutor::request(const QString &command) { // Parse shell-like command line into separate arguments std::string strMethod; std::vector<std::string> strParams; try { boost::escaped_list_separator<char> els('\\',' ','\"'); std::string strCommand = command.toStdString(); boost::tokenizer<boost::escaped_list_separator<char> > tok(strCommand, els); int n = 0; for(boost::tokenizer<boost::escaped_list_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg,++n) { if(n == 0) // First parameter is the command strMethod = *beg; else strParams.push_back(*beg); } } catch(boost::escaped_list_error &e) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error")); return; } try { std::string strPrint; json_spirit::Value result = tableRPC.execute(strMethod, RPCConvertValues(strMethod, strParams)); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), historyPtr(0) { ui->setupUi(this); #ifndef Q_WS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(obj == ui->lineEdit) { if(event->type() == QEvent::KeyPress) { QKeyEvent *key = static_cast<QKeyEvent*>(event); switch(key->key()) { case Qt::Key_Up: browseHistory(-1); return true; case Qt::Key_Down: browseHistory(1); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } " ); message(CMD_REPLY, (tr("Welcome to the lobbycoin RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); ui->totalBlocks->setText(QString::number(countOfPeers)); if(clientModel) { // If there is no current number available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers())); ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Truncate history from current position history.erase(history.begin() + historyPtr, history.end()); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Notify executor when thread started (in executor thread) connect(thread, SIGNAL(started()), executor, SLOT(start())); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); }
[ "irobotnik8@gmail.com" ]
irobotnik8@gmail.com
374c7174aa1a26335661fdec83fb6b898cc379b7
06c3e05f96352f91958cb40e3421d5396e4cdf22
/include/reconstructionEvaluator/camParser/EpflParser.h
46a3e00040e13b9aa227488cb59c3391fed3b6dc
[]
no_license
andresax/reconstructionEvaluator
96996cc4c3529353a618bca20a18991dab9f2492
38eaaa193b0cb1619c69457ab1b6f46f538378f1
refs/heads/master
2021-05-01T19:30:49.262668
2020-04-30T06:31:19
2020-04-30T06:31:19
76,339,561
1
1
null
null
null
null
UTF-8
C++
false
false
696
h
/* * EpflParser.h * * Created on: Dec 13, 2016 * Author: andrea */ #ifndef SRC_CAMPARSER_EPFLPARSER_H_ #define SRC_CAMPARSER_EPFLPARSER_H_ #include <boost/filesystem.hpp> #include <ParserInterface.hpp> #include <types.hpp> namespace reconstructorEvaluator { class EpflParser : ParserInterface { public: EpflParser(); virtual ~EpflParser(); void parse(const boost::filesystem::path &path); const std::vector<CameraType>& getCameras() const { return cameras_; } private: void orderPaths(const boost::filesystem::path &path); std::vector<boost::filesystem::path> cameraPaths_; }; } /* namespace reconstructorEvaluator */ #endif /* SRC_CAMPARSER_EPFLPARSER_H_ */
[ "andrearomanoni@gmail.com" ]
andrearomanoni@gmail.com
46f859e6fc5eaefdf223135acf6c63dd2fdee200
cd765e691961c0d9692e6233025809a69aa83c66
/DynamicAllocate/DynamicAllocate.cpp
25e94b3e811e02fe87692bc4e2fcd16f0642ee7f
[]
no_license
chanaAkerman/Ex3Parrallel
e764ff66ff92faab7fb9fe9cb0127f549dda22bf
2ef5fd00f319b0bde3701aeeb24d2896bf18eb12
refs/heads/master
2020-05-01T17:19:56.314292
2019-03-24T09:59:59
2019-03-24T09:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,481
cpp
#include "DynamicAllocate.h" #include <mpi.h> #include <stdio.h> #include <math.h> #define HEAVY 100000 #define N 20 #define MasterP 0 #define DATA_TAG 1 #define EXIT_TAG 0 // This function performs heavy computations, // its run time depends on x and y values double heavy(int x, int y) { int i, loop = 1; double sum = 0; // Super heavy tasks if (x < 5 || y < 5) loop = 10; // Heavy calculations for (i = 0; i < loop*HEAVY; i++) sum += sin(exp(sin((double)i / HEAVY))); return sum; } double DoWork(int input) { double temp = 0; for (int y = 0; y < N; y++) { temp += heavy(input, y); } return temp; } bool moreJob(int * numofTasks) { if (*numofTasks >= 0) { return true; } else { return false; } } int main(int argc, char *argv[]) { int namelen, numprocs, myid; double answer = 0, temp; int num_of_process_that_exit = 0; int jobTasks = N-1; char processor_name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Get_processor_name(processor_name, &namelen); MPI_Status status; // my code // master if (myid == MasterP) { // sending to worker init work for (int i = 1; i < numprocs; i++) { // send to process i a init task - one number with DATA TAG MPI_Send(&jobTasks, 1, MPI_INT, i, DATA_TAG, MPI_COMM_WORLD); jobTasks--; } while (num_of_process_that_exit != numprocs - 1) { // receive from any slave answer MPI_Recv(&temp, 1, MPI_DOUBLE, MPI_ANY_SOURCE, DATA_TAG, MPI_COMM_WORLD, &status); answer += temp; if (moreJob(&jobTasks)) { MPI_Send(&jobTasks, 1, MPI_INT, status.MPI_SOURCE, DATA_TAG, MPI_COMM_WORLD); jobTasks--; } else { // send null of something else MPI_Send(&jobTasks, 1, MPI_INT, status.MPI_SOURCE, EXIT_TAG, MPI_COMM_WORLD); num_of_process_that_exit++; } } printf("Answer is %e \n", answer); } else // slave code { int Exited = 0; int input; while (!Exited) { MPI_Recv(&input, 1, MPI_INT, MasterP, MPI_ANY_TAG, MPI_COMM_WORLD, &status); switch (status.MPI_TAG) { case EXIT_TAG: // exiting //printf("Exiting with input %d \n ", input); Exited = 1; break; case DATA_TAG: //printf("Do Work id %d with input : %d \n", myid, input); temp = DoWork(input); MPI_Send(&temp, 1, MPI_DOUBLE, MasterP, DATA_TAG, MPI_COMM_WORLD); break; } } } MPI_Finalize(); return 0; }
[ "lirannh@gmail.com" ]
lirannh@gmail.com
5d0764705784c61b47d5398fd28a7a29a7ee66c6
5a109e2a688139d290f89328beb4145481806f8c
/CppAdvanced/cpla_ws05/value_holder/src/Test.cpp
216cb6f91584bc267ca7d642eea863f40f824c2f
[]
no_license
tcorbat/CPlusPlusLecture
78609f766d1699c58fbae4734369b7c4c90370ef
07eaccdb38fca54b3723e33ad9b0f8f7cf6383b3
refs/heads/master
2020-12-24T06:25:04.869046
2016-11-15T13:31:28
2016-11-15T13:31:28
73,487,864
1
0
null
2016-11-11T15:16:04
2016-11-11T15:16:03
null
UTF-8
C++
false
false
7,266
cpp
#include "cute.h" #include "ide_listener.h" #include "xml_listener.h" #include "cute_runner.h" template <typename T> struct bad_get:std::logic_error{ bad_get(): logic_error{ typeid(T).name() }{} }; namespace detail{ auto const no_op_del=[](char *)noexcept{}; } struct value_holder{ value_holder()=default; template <typename T,typename =std::enable_if_t<!std::is_array<std::remove_reference_t<T>>::value>> value_holder(T &&value) :pv{allocate(std::forward<T>(value))} ,del{make_deleter<std::decay_t<T>>()} {} value_holder(value_holder const &)=delete; value_holder(value_holder &)=delete; value_holder(value_holder &&rhs) noexcept:value_holder{}{ std::swap(pv,rhs.pv); std::swap(del,rhs.del); } ~value_holder(){ del(pv); delete[] pv; } explicit operator bool() const { return pv != nullptr;} void clear() { del(pv); delete pv; pv=nullptr;} template <typename T> T const & get() const { if (pv) return *reinterpret_cast<T const *>(pv); throw bad_get<T>{}; } template <typename T> value_holder& operator=(T && val){ del(pv); del=detail::no_op_del; // ensure an exception won't break this delete[] pv; pv=nullptr; pv=allocate(std::forward<T>(val)); del=make_deleter<std::decay_t<T>>(); return *this; } value_holder& operator=(value_holder const &rhs)=delete; value_holder& operator=(value_holder &rhs)=delete; value_holder& operator=(value_holder &&rhs){ del(pv); del=detail::no_op_del; delete[] pv; pv=nullptr; std::swap(pv,rhs.pv); std::swap(del,rhs.del); return *this; } private: char * pv{}; using DELTYPE=void(*)(char *); DELTYPE del{detail::no_op_del}; // no op template <typename T> static char *allocate(T && value){ auto p=new char[sizeof(std::decay_t<T>)]; new (p) std::remove_reference_t<T>{std::forward<T>(value)}; return p; } template <typename T> static DELTYPE make_deleter(){ return [](char *p)noexcept{if(p)reinterpret_cast<std::decay_t<T>*>(p)->~T();}; } }; struct simple_holder{ simple_holder()=default; template <typename T> simple_holder(T const &value) :pv{new char[sizeof(T)]} ,del{make_deleter<T>()} { new(pv)T{value}; // placement new } ~simple_holder(){ del(pv); // destroy a T delete[]pv; } explicit operator bool() const { return pv != nullptr;} simple_holder(simple_holder const &)=delete; simple_holder(simple_holder &&rhs) noexcept:simple_holder{}{ std::swap(pv,rhs.pv); std::swap(del,rhs.del); } void clear() { del(pv); delete pv; pv=nullptr;} template <typename T> T const & get() const { if (pv) return *reinterpret_cast<T const *>(pv); throw bad_get<T>{}; } template <typename T> simple_holder& operator=(T const & val){ del(pv); delete[] pv; pv=new char[sizeof(T)]; new(pv)T{val}; del=make_deleter<T>(); return *this; } simple_holder& operator=(simple_holder const &rhs)=delete; // would need to memorize size as well simple_holder& operator=(simple_holder &&rhs){ del(pv); del=[](char *){}; delete[] pv; pv=nullptr; std::swap(pv,rhs.pv); std::swap(del,rhs.del); return *this; } private: char *pv{}; using DELTYPE=void(*)(char *); DELTYPE del{[](char *){}}; // no op template <typename T> static DELTYPE make_deleter(){ return [](char *p){if(p)reinterpret_cast<T*>(p)->~T();}; } }; void thisIsATest() { value_holder i{}; // empty ASSERTM("value is undefined", !i); } void testWithValue(){ value_holder v{42}; ASSERTM("value is defined", bool(v)); ASSERT_EQUAL(42,v.get<int>()); v.clear(); ASSERT_THROWS(v.get<int>(),bad_get<int>); } void testWithReassign(){ using namespace std::string_literals; value_holder i{}; ASSERTM("undefined value", !i); i = 42; ASSERTM("defined value", bool(i)); ASSERT_EQUAL(42,i.get<int>()); i = "hallo"s; ASSERT_EQUAL("hallo"s,i.get<std::string>()); i.clear(); ASSERT_THROWS(i.get<int>(),bad_get<int>); } void testSimpleEmpty() { simple_holder i{}; // empty ASSERTM("value is undefined", !i); } void testSimpleWithValue(){ simple_holder v{42}; ASSERTM("value is defined", bool(v)); ASSERT_EQUAL(42,v.get<int>()); v.clear(); ASSERT_THROWS(v.get<int>(),bad_get<int>); } void testSimpleWithReassign(){ using namespace std::string_literals; simple_holder i{}; ASSERTM("undefined value", !i); i = 42; ASSERTM("defined value", bool(i)); ASSERT_EQUAL(42,i.get<int>()); i = "hallo"s; ASSERT_EQUAL("hallo"s,i.get<std::string>()); i.clear(); ASSERT_THROWS(i.get<int>(),bad_get<int>); } struct tracer{ tracer(std::ostream &os):out{os}{out.get() << "tracer ctor"<<std::endl;} ~tracer(){out.get()<<"~tracer"<< std::endl;} tracer(tracer &&rhs):out{rhs.out}{out.get() << "tracer move ctor"<<std::endl;} tracer &operator=(tracer &&rhs){out = rhs.out;out.get()<<"tracer move assign"<<std::endl; return *this;} tracer(tracer const &rhs):out{rhs.out}{out.get() << "tracer copy ctor"<<std::endl;} tracer &operator=(tracer const&rhs){ out=rhs.out;out.get()<<"tracer copy assign"<<std::endl; return *this;} std::reference_wrapper<std::ostream> out; }; void testDtor(){ std::ostringstream os{}; { value_holder sh{tracer{os}}; } ASSERT_EQUAL("tracer ctor\ntracer move ctor\n~tracer\n~tracer\n",os.str()); } void testSimpleDtor(){ std::ostringstream os{}; { simple_holder sh{tracer{os}}; } ASSERT_EQUAL("tracer ctor\ntracer copy ctor\n~tracer\n~tracer\n",os.str()); } void testSimpleMoveCtor(){ std::ostringstream os{}; simple_holder sh{tracer{os}}; ASSERT_EQUAL("tracer ctor\ntracer copy ctor\n~tracer\n",os.str()); ASSERTM("defined value",bool(sh)); sh=simple_holder{}; ASSERTM("no defined value",!sh); ASSERT_EQUAL("tracer ctor\ntracer copy ctor\n~tracer\n~tracer\n",os.str()); } void testMoveCtor(){ std::ostringstream os{}; value_holder sh{tracer{os}}; ASSERTM("defined value",bool(sh)); sh=value_holder{}; ASSERTM("no defined value",!sh); ASSERT_EQUAL("tracer ctor\ntracer move ctor\n~tracer\n~tracer\n",os.str()); } void testLvalueArgumentForCtor(){ std::ostringstream os { }; tracer tr{ os }; value_holder sh { tr }; ASSERTM("defined value", bool(sh)); sh = value_holder { }; ASSERTM("no defined value", !sh); ASSERT_EQUAL("tracer ctor\ntracer copy ctor\n~tracer\n", os.str()); } void testLvalueArgumentForAssignment(){ std::ostringstream os { }; tracer tr{ os }; value_holder sh { }; sh = tr; ASSERTM("defined value", bool(sh)); sh = value_holder { }; ASSERTM("no defined value", !sh); ASSERT_EQUAL("tracer ctor\ntracer copy ctor\n~tracer\n", os.str()); } void runAllTests(int argc, char const *argv[]){ cute::suite s; //TODO add your test here s.push_back(CUTE(thisIsATest)); s.push_back(CUTE(testWithValue)); s.push_back(CUTE(testWithReassign)); s.push_back(CUTE(testSimpleEmpty)); s.push_back(CUTE(testSimpleWithValue)); s.push_back(CUTE(testSimpleWithReassign)); s.push_back(CUTE(testSimpleMoveCtor)); s.push_back(CUTE(testMoveCtor)); s.push_back(CUTE(testDtor)); s.push_back(CUTE(testSimpleDtor)); s.push_back(CUTE(testLvalueArgumentForAssignment)); s.push_back(CUTE(testLvalueArgumentForCtor)); cute::xml_file_opener xmlfile(argc,argv); cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out); cute::makeRunner(lis,argc,argv)(s, "AllTests"); } int main(int argc, char const *argv[]){ runAllTests(argc,argv); return 0; }
[ "peter.sommerlad@hsr.ch" ]
peter.sommerlad@hsr.ch
996c303f5eeb3c774c318636134f17781c11e253
ae3df5c20bfe7eab0a3a9148258f82afb0668578
/android_webview/native/permission/permission_request_handler.h
d4d91b64bfc6738f2aa4c095b343831fbcd03946
[ "BSD-3-Clause" ]
permissive
dianalow/chromium
d026a4cbc9d2f845cce6848bf0ac41719f982b3f
b683a1177deb781cac01b860c2bedcf91ae9aaaf
refs/heads/master
2021-01-11T06:06:53.539954
2014-05-08T18:20:13
2014-05-08T18:20:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,916
h
// 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. #ifndef ANDROID_WEBVIEW_NATIVE_PERMISSION_PERMISSION_REQUEST_HANDLER_H #define ANDROID_WEBVIEW_NATIVE_PERMISSION_PERMISSION_REQUEST_HANDLER_H #include <vector> #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "url/gurl.h" namespace android_webview { class AwPermissionRequest; class AwPermissionRequestDelegate; class PermissionRequestHandlerClient; // This class is used to send the permission requests, or cancel ongoing // requests. // It is owned by AwContents and has 1x1 mapping to AwContents. All methods // are running on UI thread. class PermissionRequestHandler { public: PermissionRequestHandler(PermissionRequestHandlerClient* aw_contents); virtual ~PermissionRequestHandler(); // Send the given |request| to PermissionRequestHandlerClient. void SendRequest(scoped_ptr<AwPermissionRequestDelegate> request); // Cancel the ongoing request initiated by |origin| for accessing |resources|. void CancelRequest(const GURL& origin, int64 resources); private: friend class TestPermissionRequestHandler; typedef std::vector<base::WeakPtr<AwPermissionRequest> >::iterator RequestIterator; // Return the request initiated by |origin| for accessing |resources|. RequestIterator FindRequest(const GURL& origin, int64 resources); // Cancel the given request. void CancelRequest(RequestIterator i); // Remove the invalid requests from requests_. void PruneRequests(); PermissionRequestHandlerClient* client_; // A list of ongoing requests. std::vector<base::WeakPtr<AwPermissionRequest> > requests_; DISALLOW_COPY_AND_ASSIGN(PermissionRequestHandler); }; } // namespace android_webivew #endif // ANDROID_WEBVIEW_NATIVE_PERMISSION_PERMISSION_REQUEST_HANDLER_H
[ "michaelbai@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98" ]
michaelbai@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98
f78cca990674214d5a755606d978450ccaa0f50c
1e421f87dd7fb22434a883719906f64c01113609
/interview/Optiver/askAndBid.cpp
4b8bf5083f1e71cde2d5a5a2ee53d6cf4f972ea3
[]
no_license
FJJLeon/LeetCode
e98936dbffd500e2da2242ff2e4fc9cbe6cb4366
8cd6bfcb9819b8ddff9c8d8119d7d6592b002f0f
refs/heads/master
2022-09-17T09:43:13.086248
2022-08-29T15:47:27
2022-08-29T15:47:27
173,561,588
0
0
null
null
null
null
UTF-8
C++
false
false
118
cpp
#include <bits/stdc++.h> using namespace std; // using big top heap and small top heap int main() { return 0; }
[ "695048014@qq.com" ]
695048014@qq.com
3d9c11a660b1a172d7d39f7e3fcd59b0b33a0258
2743ed11026e2fba43799799b04d0df55af30365
/abdata/abdata/DBIpBan.h
d990a32519a461319c33ec8be05464c03900f8c9
[]
no_license
lineCode/ABx
bb792946429bf60fee38da609b0c36c89ec34990
b726a2ada8815e8d4c8a838f823ffd3ab2e2b81b
refs/heads/master
2022-01-22T06:13:49.170390
2019-07-19T20:03:31
2019-07-19T20:03:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
406
h
#pragma once #include <AB/Entities/IpBan.h> namespace DB { class DBIpBan { public: DBIpBan() = delete; ~DBIpBan() = delete; static bool Create(AB::Entities::IpBan& ban); static bool Load(AB::Entities::IpBan& ban); static bool Save(const AB::Entities::IpBan& ban); static bool Delete(const AB::Entities::IpBan& ban); static bool Exists(const AB::Entities::IpBan& ban); }; }
[ "stievie2006@gmail.com" ]
stievie2006@gmail.com
34ffadf5b74bcd123e5308e62264a1c3a48a915e
34fc36da5d684f908bb988cc76bf542fabca88db
/ARC/ARC113/r113a.cpp
b4362ff66f77a2708f462b93e6d48ff8045c5eee
[]
no_license
take1010/MyAtCoder
6f2dc830d75ae4c99edfb3638734854e905bc557
d85aecee85f7ebf5232fd82599b21ff5658c4e1c
refs/heads/main
2023-05-31T12:44:32.336673
2021-06-19T14:01:24
2021-06-19T14:01:24
308,521,140
0
0
null
null
null
null
UTF-8
C++
false
false
594
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define MOD 1000000007 template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; } int main(){ ll k; cin >> k; ll a, b, ans=0; for(a=1; a*a*a<=k; a++){ for(b=a; a*b*b<=k; b++){ ll c=k/(a*b); if(a==b) ans += (c-b)*3+1; else ans += (c-b)*6+3; } } cout << ans << endl; return 0; }
[ "tk10314@gmail.com" ]
tk10314@gmail.com
325d6f88b106e855d0cfa26c803ddf4806e71443
e12466a26cfef4f1e79373890286d248caee8b68
/B. Trace.cpp
9eaa85158ed3f0af24a9fd540ccb7118adb518d2
[]
no_license
azhanali/Codeforces
6362fdb031afb1881eaf4dcf44a1ec8444a94bee
6119512dc55f239c88d72ced37e4dc7f430af105
refs/heads/master
2021-09-22T21:30:49.807190
2018-09-17T06:41:55
2018-09-17T06:41:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,491
cpp
/* -------------------------------- */ /* Name: MD. Khairul Basar */ /* Institute: HSTU */ /* Dept: CSE */ /* Email: khairul.basar93@gmail.com */ /* -------------------------------- */ #include <bits/stdc++.h> /* all header files included */ #define mod 1000000007 #define pi acos(-1.0) #define eps 1e-9 #define fs first #define sc second #define pb(a) push_back(a) #define mp(a,b) make_pair(a,b) #define sp printf(" ") #define nl printf("\n") #define set0(a) memset(a,0,sizeof(a)) #define setneg(a) memset(a,-1,sizeof(a)) #define setinf(a) memset(a,126,sizeof(a)) #define tc1(x) printf("Case %d: ",x) #define tc2(x) printf("Case #%d: ",x) #define tc3(x) printf("Case %d:\n",x) #define tc4(x) printf("Case #%d:\n",x) #define pr1(x) cout<<x<<"\n" #define pr2(x,y) cout<<x<<" "<<y<<"\n" #define pr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<"\n" /* defining macros */ using namespace std; template <class T> inline T bigmod(T b, T p, T m) { T ret; if(p==0) return 1; if(p&1) { ret=(bigmod(b,p/2,m)%m); return ((b%m)*ret*ret)%m; } else { ret=(bigmod(b,p/2,m)%m); return (ret*ret)%m; } } template <class T> inline T _sqrt(T a) { return (T)sqrt((double)a); } template <class T, class X> inline T _pow(T a, X b) { T res=1; for(int i=1; i<=b; i++) res*=a; return res; } /* template functions */ typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int>pii; typedef pair<LL, LL>pll; typedef pair<double, double>pdd; typedef vector<int>vi; typedef vector<LL>vll; typedef vector<double>vd; /* type definition */ int dx4[]= {1,-1,0,0}; int dy4[]= {0,0,1,-1}; int dx6[]= {0,0,1,-1,0,0}; int dy6[]= {1,-1,0,0,0,0}; int dz6[]= {0,0,0,0,1,-1}; int dx8[]= {1,-1,0,0,-1,1,-1,1}; int dy8[]= {0,0,1,-1,1,1,-1,-1}; int dkx8[]= {-1,1,-1,1,-2,-2,2,2}; int dky8[]= {2,2,-2,-2,1,-1,1,-1}; /* direction array */ int tc=1; const long long int mx=100; /* global declaration */ int main() { int i,n,a[mx+5],cnt; double ans; while(cin>>n) { for(i=0;i<n;i++) cin>>a[i]; sort(a,a+n); cnt=0; for(i=n-1;i>=0;i-=2) { if(i==0) cnt+=a[i]*a[i]; else cnt+=(a[i]*a[i])-(a[i-1]*a[i-1]); } ans=acos(-1)*(double)cnt; printf("%.10lf\n",ans); } return 0; }
[ "khairul.basar93@gmail.com" ]
khairul.basar93@gmail.com
a8979a6a882408ee4a80be229ba7ce6c1c01ecbb
2744d7236215e153c345cb992c5d9c9524bd6576
/EventLoopThreadPool.cpp
ccab4dd909b522bb24b8697cae56f21520ce78c4
[]
no_license
shilinlun/mymuduo
3c2cdbe00f5c4542f7bf2db8fc5cec1fa740dec3
6fd60f0868c393cb436e8cd5bcf9e598b6dc75e7
refs/heads/main
2023-04-15T10:46:18.781205
2021-04-28T12:00:17
2021-04-28T12:00:17
362,447,235
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
cpp
#include "EventLoopThreadPool.h" #include "EventLoopThread.h" EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseloop, const std::string &nameArg) : baseLoop_(baseloop), name_(nameArg), started_(false), numThreads_(0), next_(0) { } EventLoopThreadPool::~EventLoopThreadPool() { } void EventLoopThreadPool::start(const ThreadInitCallback &cb) { started_ = true; for (int i = 0; i < numThreads_; ++i) { char buf[name_.size() + 32] = {0}; snprintf(buf, sizeof(buf), "%s%d", name_.c_str(), i); EventLoopThread *t = new EventLoopThread(cb, buf); threads_.push_back(std::unique_ptr<EventLoopThread>(t)); loops_.push_back(t->startloop()); // 会返回一个新的loop } // 表明只有一个线程执行 if (numThreads_ == 0 && cb) { cb(baseLoop_); } } // 若工作在多线程中,则默认以轮询的方式分配channel给subreactor EventLoop *EventLoopThreadPool::getNextLoop() { EventLoop *loop = baseLoop_; if (!loops_.empty()) { loop = loops_[next_]; ++next_; if (next_ >= loops_.size()) { next_ = 0; } } return loop; } std::vector<EventLoop *> EventLoopThreadPool::getAlLoops() { if (loops_.empty()) { return std::vector<EventLoop *>(1, baseLoop_); } else { return loops_; } }
[ "noreply@github.com" ]
shilinlun.noreply@github.com
8930f5031a503f9a1b4e519e4314c4237677c1b0
62671b516e94df1102e734142aeb10808f7504c3
/libframelesswindow/borderimage.cpp
6770d0319e2881eadab7dfa5311c85611f00da2c
[]
no_license
ooab/QtFramelessWindow
bcd29f47ebed49b00f15630027a243dcbcdcf73f
bdf1a0e49bb7ddf15da62f09a61b6da14cb5c383
refs/heads/master
2022-01-20T11:30:44.975311
2019-03-29T14:45:22
2019-03-29T14:45:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,258
cpp
#include "borderimage.h" #include <QTextStream> void BorderImage::setPixmap(const QString& url) { m_pixmapUrl = url; m_pixmap.load(url); } void BorderImage::setPixmap(const QPixmap& pixmap) { m_pixmap = pixmap; } void BorderImage::setBorder(const QString& border) { QTextStream qs((QString*)&border); int left, top, right, bottom; qs >> left >> top >> right >> bottom; setBorder(left, top, right, bottom); } void BorderImage::setBorder(const QMargins& border) { m_border = border; } void BorderImage::setBorder(int left, int top, int right, int bottom) { QMargins m(left, top, right, bottom); m_border = m; } void BorderImage::setMargin(const QString& border) { QTextStream qs((QString*)&border); int left, top, right, bottom; qs >> left >> top >> right >> bottom; setMargin(left, top, right, bottom); } void BorderImage::setMargin(const QMargins& border) { m_margin = border; } void BorderImage::setMargin(int left, int top, int right, int bottom) { QMargins m(left, top, right, bottom); m_margin = m; } void BorderImage::load(const QString& pixmap_url, const QString& border, const QString& margin) { setPixmap(pixmap_url); setBorder(border); setMargin(margin); }
[ "cnfreebsd@163.com" ]
cnfreebsd@163.com
788dc0e291c3a4f5af41953aed49765b370750d5
66c212ef68eb394f5a1e8e6fc5ebcffb13064dba
/src/main.cpp
2fc2c8e746f44d8c99d9457210c5c3b48cfe5c7f
[]
no_license
Luigi30/polygon
ca3f8af7b25d4fd4862a0c18c48a8beaf662ec11
b5603abc25021bd46d71e1588e5a8499e27aeab7
refs/heads/master
2021-01-20T21:16:02.543772
2017-03-17T22:32:43
2017-03-17T22:32:43
62,531,209
1
0
null
null
null
null
UTF-8
C++
false
false
5,844
cpp
#include "main.hpp" void wait_for_vsync(){ //Wait for the end of a retrace do {} while(inp(0x3DA) & 0x08); //Wait for the new retrace do {} while (!(inp(0x3DA) & 0x08)); } void abort(char *msg){ printf("\r\nCritical error: %s\r\n", msg); exit(255); } void load_shapes(){ //Read SHAPES.DAT FILE *hShapesFile; hShapesFile = fopen("SHAPES.DAT", "r"); char rawShapes[64][4]; int numShapes = 0; if(hShapesFile != NULL){ while(fgets(rawShapes[numShapes], 255, hShapesFile) != NULL){ numShapes++; } } else { abort("SHAPES.DAT not found."); } for(int i=0;i<numShapes;i++){ shapesList.push_back(Shape("NEWSHAPE", rawShapes[i])); //TODO: shape names } } void load_lookup_tables(){ //VGA_Y_OFFSETS - offset of the start of a new row of pixels for(int i=0;i<VGA_HEIGHT;i++){ VGA_Y_OFFSETS[i] = i * VGA_WIDTH; } //Trigonometry tables for(int i=0;i<360;i++){ SIN_TABLE[i] = std::sin(i * (M_PI/180.0f)); COS_TABLE[i] = std::cos(i * (M_PI/180.0f)); } } void updatePlayerPosition(Vector3f _eye, Vector3f _cameraRotation){ //Player's position and rotation = camera, effectively PTR_SCENEOBJECT("player")->transformation.translation = _eye; PTR_SCENEOBJECT("player")->transformation.rotation = _cameraRotation; } int main(){ load_lookup_tables(); //needed for any draw routine Install_KBHook(); //needed for input processing //Debug_Init(); //init_timer(11930); //100 ticks per second serialPort = Serial(0x3F8, SER_9600_BAUD); printf("main(): serialPort setup\n"); serialPort.sendString("\n\n\r\n*** CONNECTED ***\r\n"); serialPort.sendString("main(): Serial connected\r\n"); VGA_PTR = (char*)VGA_LINEAR_ADDRESS; _setvideomode(_MRES256COLOR); //Change to mode 13h //MainMenu(); BeginSimulation(); //exit cleanup routines Restore_KBHook(); _setvideomode(_DEFAULTMODE); printf("exiting!\n"); return 0; } void MainMenu(){ Mouse::cursorEnable(); controlsState.escapePressed = false; g_screen.layer_background.draw_rectangle_filled(Point(80, 50), Size2D(160, 100), COLOR_LTGRAY); g_screen.layer_background.shade_rectangle(Point(80, 50), Size2D(160, 100), COLOR_WHITE, COLOR_DKGRAY); g_screen.layer_text.putString("Main Menu", strlen("Main Menu"), Point(85, 55), COLOR_GRAYS, FONT_6x8); g_screen.widgetsList.push_back(new W_Button("btn_Launch", Point(85, 70), BUTTON_SHAPE_RECT, Size2D(30, 50), "", true)); while(controlsState.escapePressed == false){ wait_for_vsync(); controlsState.DecayAxes(); //Process inputs read_keyboard(); Mouse::cursorDisable(); g_screen.redraw(); Mouse::cursorEnable(); } //BeginSimulation(); } void BeginSimulation(){ _setvideomode(_DEFAULTMODE); std::printf("Polysim Engine\n"); std::printf("Now loading...\n"); std::printf("Connect 9600,8,N,1 terminal to COM1\n"); printf("Loading models\n"); WavefrontObject cube = WavefrontObject("cube.3d"); ptr_DumbShip dumbShip(new DumbShip("ship", Vector3f(0,0,0), Vector3f(-45,45,-90))); g_SceneManager.addSceneObject(dumbShip); g_SceneManager.addSceneObject("player", cube, Vector3f(0,0,-5), Vector3f(0,0,0), Vector3f(.5,.5,.5)); g_SceneManager.addSceneObject("waypoint", cube, Vector3f(10,10,0), Vector3f(0,0,0), Vector3f(.5,.5,.5)); PTR_SCENEOBJECT("waypoint")->target = NULL; PTR_SCENEOBJECT("ship")->target = &*PTR_SCENEOBJECT("waypoint"); PTR_SCENEOBJECT("ship")->current_behavior = BEHAVIOR_WAYPOINTS; //g_SceneManager.addSceneObject("waypt2", cube, Vector3f(-20,10,-5), Vector3f(0,0,0), Vector3f(.5,.5,.5)); //PTR_SCENEOBJECT("waypoint")->target = &*PTR_SCENEOBJECT("waypt2"); _setvideomode(_MRES256COLOR); //Change to mode 13h g_screen.draw_polygon_debug_data(); g_screen.draw_object_debug_data(*PTR_SCENEOBJECT("ship")); g_screen.redraw(); bool stop = false; controlsState.escapePressed = false; serialPort.sendString("main(): Beginning simulation\r\n"); //Scene loop while(!stop){ stop = DoSceneLoop(); } } bool DoSceneLoop(){ //we need a player object assert(PTR_SCENEOBJECT("player") != NULL); //Limit to 35Hz refresh wait_for_vsync(); //SceneObjects now think. g_SceneManager.objectsThink(); //update object location and orientation g_SceneManager.applyObjectVelocities(); g_SceneManager.applyObjectRotations(); //draw some debug data g_screen.draw_polygon_debug_data(); g_screen.draw_object_debug_data(*PTR_SCENEOBJECT("ship")); g_screen.redraw(); //Process inputs, update controlsState read_keyboard(); //Update player's forward speed PTR_SCENEOBJECT("player")->movement.forward_speed = controlsState.forward_throttle * PTR_SCENEOBJECT("player")->movement.maximum_throttle_speed; //Apply this speed to the direction vector Vector3f direction = controlsState.direction + Vector3f(0, 0, PTR_SCENEOBJECT("player")->movement.forward_speed); //Rotate direction to align with the camera cameraRotation.z = controlsState.rotation.z; cameraRotation.x = controlsState.rotation.x; cameraRotation.y = controlsState.rotation.y; //Update global transformation matrix with the player's location and rotation eye = PTR_SCENEOBJECT("player")->transformation.translation; direction = direction.rotateAroundZAxis(-cameraRotation.z); direction = direction.rotateAroundXAxis(-cameraRotation.x); direction = direction.rotateAroundYAxis(-cameraRotation.y); eye = eye + direction; updatePlayerPosition(eye, cameraRotation); return controlsState.escapePressed; }
[ "luigi30@gmail.com" ]
luigi30@gmail.com
ed5df2cffb0964bb7125330701ca07d4836dde95
85a783b1e7f7868aaf744ac39b72f737ec3ec0dd
/biomedical_display/src/oscilloscope.cpp
99b585cd545774737ca7181dcc9781a5ebb8a616
[ "MIT" ]
permissive
avilleret/FourFor
de5ae30da77e3991b1372bf6fe2f7d3ce30b8921
1a82ed69cab439c385e62108ba6e65e98eaf12ca
refs/heads/master
2021-11-29T01:07:39.149181
2021-11-25T13:47:09
2021-11-25T13:47:21
167,441,329
0
0
null
null
null
null
UTF-8
C++
false
false
3,681
cpp
#include "oscilloscope.h" #include "ofxFatLine.h" Oscilloscope::Oscilloscope(const opp::node& root) : m_root(root) { { auto n = m_root.create_argb("color"); opp::value::vec4f c{1.,1.,0.,0.}; n.set_value(c); n.set_value_callback( [](void* context, const opp::value& v){ Oscilloscope* osc = static_cast<Oscilloscope*>(context); auto vec = v.to_vec4f(); osc->set_color(ofFloatColor(vec[1],vec[2],vec[3],vec[0])); }, this); } { auto n = m_root.create_bool("enable"); n.set_value(true); n.set_value_callback( [](void* context, const opp::value& v){ Oscilloscope* osc = (Oscilloscope*) context; auto b = v.to_bool(); osc->set_enabled(b); }, this); } { auto n = m_root.create_float("input"); n.set_value(0.); n.set_value_callback( [](void* context, const opp::value& v){ Oscilloscope* osc = (Oscilloscope*) context; auto f = 1. - v.to_float(); osc->set_value(f); }, this); } { auto n = m_root.create_float("line_width"); n.set_value(1.); n.set_value_callback( [](void* context, const opp::value& v){ Oscilloscope* osc = (Oscilloscope*) context; float f = v.to_float(); osc->m_line_width = f; osc->m_line_width_changed=true; }, this); } { auto n = m_root.create_int("vbar_width"); n.set_min(0); n.set_max(int(m_size)); n.set_value(20); n.set_value_callback( [](void* context, const opp::value& v){ Oscilloscope* osc = (Oscilloscope*) context; float f = v.to_float(); osc->m_vbar_width = f; osc->m_line_width_changed=true; }, this); } { auto n = m_root.create_int("buffer_length"); n.set_min(32); n.set_max(1024); n.set_bounding(opp::bounding_mode::Low); n.set_value(static_cast<int>(m_size)); n.set_value_callback( [](void* context, const opp::value& v){ Oscilloscope* osc = (Oscilloscope*) context; int size = v.to_int(); osc->m_size = v.to_int(); osc->m_size_changed=true; }, this); } } void Oscilloscope::update() { } void Oscilloscope::draw(float x, float y, float w, float h) { ofPushStyle(); ofPushMatrix(); ofTranslate(x,y); ofVec2f scale(w-h*1.5,h); //ofScale(float(w-h)/float(m_buffer.size()),h); m_mutex.lock(); if(m_size_changed) { m_buffer.resize(m_size); m_colors.resize(m_size); m_weights.resize(m_size); for(size_t i = 0; i < m_buffer.size(); i++) { m_buffer[i] = ofDefaultVertexType(float(i)/m_buffer.size(), 0.5, 0.); m_colors[i] = m_color; m_weights[i] = m_line_width; } m_size_changed = false; } if(m_line_width_changed) { for(auto& w : m_weights) { w = static_cast<double>(m_line_width); } m_line_width_changed = false; } if(m_color_changed) { for(size_t i = 0; i < m_buffer.size(); i++) m_colors[i] = m_color; } m_buffer[m_index] = ofDefaultVertexType(static_cast<float>(m_index)/m_buffer.size(), static_cast<double>(m_value)/2.+0.5, 0); m_index = (m_index + 1) % m_buffer.size(); std::vector<ofDefaultVec3> scaled_buffer; scaled_buffer.reserve(m_buffer.size()); for(auto d : m_buffer) { ofDefaultVec3 pt; pt.x = d.x * scale.x; pt.y = d.y * scale.y; scaled_buffer.push_back(pt); } ofxFatLine line(scaled_buffer, m_colors, m_weights); ofSetColor(m_color); m_mutex.unlock(); line.setClosed(false); line.draw(); ofSetColor(ofColor::black); ofDrawRectangle(scaled_buffer[m_index].x, 0., m_vbar_width, h); ofPopMatrix(); ofPushMatrix(); ofPopMatrix(); ofPopStyle(); }
[ "antoine.villeret@gmail.com" ]
antoine.villeret@gmail.com
ebce497097446503e4b06f5f3150c62c1f03f34b
c0a8145e469131e8b54e2edbb2ed19ce9bef0d98
/Assignment2/Assignment2_4/Hare.h
4b46d22a4bdb918b0aafec87b6cb349c247a782c
[]
no_license
dring1/COMP2404
a6a3c76fcd865a7cb7d24626d712ddebf985d358
5a005f6a9c123f79e258e597a41635a572e33300
refs/heads/master
2020-12-24T17:07:55.006703
2013-04-14T22:28:44
2013-04-14T22:28:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
486
h
#ifndef HARE_H #define HARE_H class Hare//class definition { public://function prototypes Hare(); Hare(int,int,int,int);//x,y,health,strength,armor void swordPlay(bool); void setHealth(int); void setStrength(int); void setArmor(int); void setX(int); void update(); bool getSword(); int getX(); int getHealth(); int getStrength(); int getArmor(); void damage(int); private://private data members bool sword; int x; int health; int strength; int armor; }; #endif
[ "derptacos@derptacos-virtual-machine.(none)" ]
derptacos@derptacos-virtual-machine.(none)
dc177d5da16798a2292a76951857752434fa5cf7
ec4aba270988123fb86cea49772d3a58018f6627
/ros_lib/mavros_msgs/CommandHome.h
7e3b2cc0e76b8e23c5159835cc6d94cd0c3eacf1
[]
no_license
hdh7485/flying_car
e81f69f3e42f2f551b27df0fbca17af5acc17efe
e80d72447a31c4648c7d78708a67ee5708f1a6e0
refs/heads/master
2023-04-14T17:14:02.799851
2021-04-27T12:51:07
2021-04-27T12:51:07
287,976,804
2
2
null
null
null
null
UTF-8
C++
false
false
6,720
h
#ifndef _ROS_SERVICE_CommandHome_h #define _ROS_SERVICE_CommandHome_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace mavros_msgs { static const char COMMANDHOME[] = "mavros_msgs/CommandHome"; class CommandHomeRequest : public ros::Msg { public: typedef bool _current_gps_type; _current_gps_type current_gps; typedef float _yaw_type; _yaw_type yaw; typedef float _latitude_type; _latitude_type latitude; typedef float _longitude_type; _longitude_type longitude; typedef float _altitude_type; _altitude_type altitude; CommandHomeRequest(): current_gps(0), yaw(0), latitude(0), longitude(0), altitude(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { bool real; uint8_t base; } u_current_gps; u_current_gps.real = this->current_gps; *(outbuffer + offset + 0) = (u_current_gps.base >> (8 * 0)) & 0xFF; offset += sizeof(this->current_gps); union { float real; uint32_t base; } u_yaw; u_yaw.real = this->yaw; *(outbuffer + offset + 0) = (u_yaw.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_yaw.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_yaw.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_yaw.base >> (8 * 3)) & 0xFF; offset += sizeof(this->yaw); union { float real; uint32_t base; } u_latitude; u_latitude.real = this->latitude; *(outbuffer + offset + 0) = (u_latitude.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_latitude.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_latitude.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_latitude.base >> (8 * 3)) & 0xFF; offset += sizeof(this->latitude); union { float real; uint32_t base; } u_longitude; u_longitude.real = this->longitude; *(outbuffer + offset + 0) = (u_longitude.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_longitude.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_longitude.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_longitude.base >> (8 * 3)) & 0xFF; offset += sizeof(this->longitude); union { float real; uint32_t base; } u_altitude; u_altitude.real = this->altitude; *(outbuffer + offset + 0) = (u_altitude.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_altitude.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_altitude.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_altitude.base >> (8 * 3)) & 0xFF; offset += sizeof(this->altitude); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { bool real; uint8_t base; } u_current_gps; u_current_gps.base = 0; u_current_gps.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->current_gps = u_current_gps.real; offset += sizeof(this->current_gps); union { float real; uint32_t base; } u_yaw; u_yaw.base = 0; u_yaw.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_yaw.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_yaw.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_yaw.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->yaw = u_yaw.real; offset += sizeof(this->yaw); union { float real; uint32_t base; } u_latitude; u_latitude.base = 0; u_latitude.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_latitude.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_latitude.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_latitude.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->latitude = u_latitude.real; offset += sizeof(this->latitude); union { float real; uint32_t base; } u_longitude; u_longitude.base = 0; u_longitude.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_longitude.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_longitude.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_longitude.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->longitude = u_longitude.real; offset += sizeof(this->longitude); union { float real; uint32_t base; } u_altitude; u_altitude.base = 0; u_altitude.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_altitude.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_altitude.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_altitude.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->altitude = u_altitude.real; offset += sizeof(this->altitude); return offset; } const char * getType(){ return COMMANDHOME; }; const char * getMD5(){ return "af3ed5fc0724380793eba353ee384c9a"; }; }; class CommandHomeResponse : public ros::Msg { public: typedef bool _success_type; _success_type success; typedef uint8_t _result_type; _result_type result; CommandHomeResponse(): success(0), result(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { bool real; uint8_t base; } u_success; u_success.real = this->success; *(outbuffer + offset + 0) = (u_success.base >> (8 * 0)) & 0xFF; offset += sizeof(this->success); *(outbuffer + offset + 0) = (this->result >> (8 * 0)) & 0xFF; offset += sizeof(this->result); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { bool real; uint8_t base; } u_success; u_success.base = 0; u_success.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->success = u_success.real; offset += sizeof(this->success); this->result = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->result); return offset; } const char * getType(){ return COMMANDHOME; }; const char * getMD5(){ return "1cd894375e4e3d2861d2222772894fdb"; }; }; class CommandHome { public: typedef CommandHomeRequest Request; typedef CommandHomeResponse Response; }; } #endif
[ "hdh7485@gmail.com" ]
hdh7485@gmail.com
f61d3d10809a57abc94a3d71fb88941c8e61c5f2
d52d5fdbcd848334c6b7799cad7b3dfd2f1f33e4
/third_party/folly/folly/logging/LogWriter.h
cbbfdd3c6c3830e5dab4e9d312c2a48ac3089c77
[ "Apache-2.0" ]
permissive
zhiliaoniu/toolhub
4109c2a488b3679e291ae83cdac92b52c72bc592
39a3810ac67604e8fa621c69f7ca6df1b35576de
refs/heads/master
2022-12-10T23:17:26.541731
2020-07-18T03:33:48
2020-07-18T03:33:48
125,298,974
1
0
null
null
null
null
UTF-8
C++
false
false
2,424
h
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <folly/Range.h> namespace folly { /** * LogWriter defines the interface for processing a serialized log message. */ class LogWriter { public: /** * Bit flag values for use with writeMessage() */ enum Flags : uint32_t { NO_FLAGS = 0x00, /** * Ensure that this log message never gets discarded. * * Some LogWriter implementations may discard messages when messages are * being received faster than they can be written. This flag ensures that * this message will never be discarded. * * This flag is used to ensure that LOG(FATAL) messages never get * discarded, so we always report the reason for a crash. */ NEVER_DISCARD = 0x01, }; virtual ~LogWriter() {} /** * Write a serialized log message. * * The flags parameter is a bitwise-ORed set of Flag values defined above. */ virtual void writeMessage(folly::StringPiece buffer, uint32_t flags = 0) = 0; /** * Write a serialized message. * * This version of writeMessage() accepts a std::string&&. * The default implementation calls the StringPiece version of * writeMessage(), but subclasses may override this implementation if * desired. */ virtual void writeMessage(std::string&& buffer, uint32_t flags = 0) { writeMessage(folly::StringPiece{buffer}, flags); } /** * Block until all messages that have already been sent to this LogWriter * have been written. * * Other threads may still call writeMessage() while flush() is running. * writeMessage() calls that did not complete before the flush() call started * will not necessarily be processed by the flush call. */ virtual void flush() = 0; }; } // namespace folly
[ "yangshengzhi1@bigo.sg" ]
yangshengzhi1@bigo.sg
8a0880f6cb19199dd693b2e12bf2ce7448d68af9
cc429e9f74292b5a2069142cae43bafcd9374ca7
/GuessWho- v1/hairwindow.h
3af4ca30e9899852b77f13ec07c4e96d78ce8de1
[]
no_license
ttendohv/GuessWho17B
83d8e0fc3491fbfdabde2c338e47d59c7c72b86f
607c9d3408fdcd5e38fcaee580ddda05b00fd67d
refs/heads/master
2020-06-04T03:52:10.320296
2014-12-13T07:01:17
2014-12-13T07:01:17
24,170,396
0
1
null
null
null
null
UTF-8
C++
false
false
498
h
#ifndef HAIRWINDOW_H #define HAIRWINDOW_H #include <QDialog> class QDialogButtonBox; class QLabel; class QRadioButton; class HairWindow : public QDialog { Q_OBJECT public: explicit HairWindow(QWidget *parent = 0); ~HairWindow(); private slots: void isAccepted(); private: QLabel *hairColorLabel; QDialogButtonBox *buttonBox; QRadioButton *question1; QRadioButton *question2; QRadioButton *question3; QRadioButton *question4; }; #endif // HAIRWINDOW_H
[ "eckods@hotmail.com" ]
eckods@hotmail.com
4301a354ff9d32303eba03bad65ec96afd1c37f1
c464b71b7936f4e0ddf9246992134a864dd02d64
/workWithClint/TestCase/processor2/2.3/U
c6099431f7f1dea680cb5d4cef298929774ef58e
[]
no_license
simuBT/foamyLatte
c11e69cb2e890e32e43e506934ccc31b40c4dc20
8f5263edb1b2ae92656ffb38437cc032eb8e4a53
refs/heads/master
2021-01-18T05:28:49.236551
2013-10-11T04:38:23
2013-10-11T04:38:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,490
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM Extend Project: Open source CFD | | \\ / O peration | Version: 1.6-ext | | \\ / A nd | Web: www.extend-project.de | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "2.3"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 70 ( (0.200543 0.012056 0) (0.205607 0.0366889 0) (0.216002 0.0661032 0) (0.23079 0.102695 0) (0.248478 0.146788 0) (0.271367 0.198321 0) (0.297554 0.263109 0) (0.354816 0.343095 0) (0.397179 0.424271 0) (0.200832 0.00884287 0) (0.207979 0.0274422 0) (0.221959 0.0515297 0) (0.241965 0.083309 0) (0.267222 0.122297 0) (0.301604 0.166053 0) (0.342605 0.216123 0) (0.408868 0.25473 0) (0.489304 0.329781 0) (0.201379 0.00425137 0) (0.211446 0.0151382 0) (0.228782 0.0329768 0) (0.251832 0.058766 0) (0.280207 0.0907558 0) (0.316592 0.124527 0) (0.361028 0.160995 0) (0.417444 0.174323 0) (0.496137 0.221311 0) (0.202434 -0.0030256 0) (0.216644 -0.000815686 0) (0.236403 0.011595 0) (0.259611 0.0322835 0) (0.287142 0.0580718 0) (0.320773 0.0837935 0) (0.363034 0.110327 0) (0.410751 0.116919 0) (0.473378 0.137758 0) (0.2042 -0.0142322 0) (0.222321 -0.0192154 0) (0.239673 -0.00921478 0) (0.257483 0.0084263 0) (0.279375 0.0290373 0) (0.307132 0.0481639 0) (0.343622 0.0660219 0) (0.384383 0.0707072 0) (0.432542 0.0769821 0) (0.201743 -0.0354597 0) (0.214662 -0.0375133 0) (0.217231 -0.023546 0) (0.220938 -0.00725326 0) (0.231809 0.00775301 0) (0.250838 0.0196292 0) (0.278899 0.0289061 0) (0.311455 0.0310292 0) (0.347664 0.031371 0) (0.164642 -0.0249548 0) (0.150901 -0.0224874 0) (0.123147 -0.0128197 0) (0.109562 -0.00494533 0) (0.108904 0.000607722 0) (0.116925 0.0041334 0) (0.131534 0.00625526 0) (0.149131 0.00625229 0) (0.167604 0.00544267 0) (0.358212 0.162401 0) (0.543435 0.166491 0) (0.572243 0.153479 0) (0.540109 0.106194 0) (0.483335 0.0594635 0) (0.382998 0.0219105 0) (0.183513 0.00220582 0) ) ; boundaryField { inlet { type fixedValue; value uniform (0.2 0 0); } outlet { type zeroGradient; } fixedWalls { type fixedValue; value uniform (0 0 0); } frontAndBack { type empty; } procBoundary2to3 { type processor; value nonuniform List<vector> 9((0.200346 0.0142423 0) (0.2038 0.0431826 0) (0.210737 0.0760161 0) (0.219305 0.114447 0) (0.226442 0.158416 0) (0.229028 0.208438 0) (0.220329 0.270769 0) (0.194217 0.338384 0) (0.0599171 0.285649 0)); } procBoundary2to1 { type processor; value nonuniform List<vector> 7((0.197785 0.0387181 0) (0.505432 0.0657267 0) (0.593497 0.0782618 0) (0.578015 0.054821 0) (0.519078 0.02751 0) (0.407022 0.00563787 0) (0.191139 -0.00221223 0)); } } // ************************************************************************* //
[ "clint@clint-Parallels-Virtual-Platform.(none)" ]
clint@clint-Parallels-Virtual-Platform.(none)
9dfa727904bdd198f72fe7e1808d36a890f8c254
1d60a0aeb4107f0fd0602f9c708057389166dfb9
/include/CEnumGen.h
aeddb591ec2c650e320fa50c3d0ed27c98199b65
[ "MIT" ]
permissive
colinw7/CUtil
230ff7bbd8806608d6c185e007cdbcb4618ddbb8
219f844a731b85c6c5cf9dc66c756da2bc5613e3
refs/heads/master
2023-09-01T14:00:00.849065
2023-08-20T23:22:32
2023-08-20T23:22:32
10,445,250
2
2
null
null
null
null
UTF-8
C++
false
false
279
h
#undef CENUM_START #undef CENUM_END #undef CENUM_ITEM #undef CENUM_VALUE #define CENUM_START(E) \ CEnum<E> enum_map; \ \ template<typename T> \ void CEnum<T>::init() { #define CENUM_END(E) \ } #define CENUM_ITEM(E,S,N) add(E,S); #define CENUM_VALUE(E,S,N,V) CENUM_ITEM(E,S,N)
[ "colinw@nc.rr.com" ]
colinw@nc.rr.com
4b3392521006d9a059997a65eb4b6478bc867c0b
2ef59fac2a6c8a7cbb56ce8ab673d4dd8e28f270
/Winsock_Project/Winsock_Project/stdafx.h
407bff2e6ac3c70dcca92bd2416d278d7af94055
[]
no_license
OverFace/Winsock_Project
6878f57e6e46dac91968e42459fe2a7df919e3b8
492da333c50d1a29970e7a48e4198fd2c03b074b
refs/heads/master
2021-08-23T18:04:48.486141
2017-12-06T00:35:37
2017-12-06T00:35:37
112,901,027
0
1
null
2017-12-04T01:59:20
2017-12-03T04:53:02
C++
UTF-8
C++
false
false
745
h
// stdafx.h : 자주 사용하지만 자주 변경되지는 않는 // 표준 시스템 포함 파일 또는 프로젝트 관련 포함 파일이 // 들어 있는 포함 파일입니다. // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> // TODO: 프로그램에 필요한 추가 헤더는 여기에서 참조합니다. #pragma comment(lib, "ws2_32") #include <winsock2.h> #include <WS2tcpip.h> #include <stdlib.h> #include <stdio.h> #include <Windows.h> #include <process.h> #include "../Headers/Constant.h" #include "../Headers/Define.h" #include "../Headers/Enum.h" #include "../Headers/Struct.h" #include <string> #include <list> #include <vector> #include <algorithm> #include <iostream> using namespace std;
[ "ygchoi2001@naver.com" ]
ygchoi2001@naver.com
18f7e2c727c53bfee61a6ab49fdd1a3f6d6ae237
3b31392756ff5824966a9a58d97106307dc12d8c
/ch11/test.cpp
3a1d545569015d02ff4e50f921e0a83d749394d9
[]
no_license
heturing/Cpp_primer_solution
e7a3735823ab806d210d57bc8f200d0f31778e91
df34b80bb5f9f62be567a51af6e4711404f60a16
refs/heads/master
2020-07-30T06:32:48.295897
2019-10-18T08:36:50
2019-10-18T08:36:50
210,118,290
0
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
#include <iostream> #include <map> int main () { std::map<char,int> mymap; mymap['b'] = 100; mymap['a'] = 200; mymap['c'] = 300; // print content: std::cout << "mymap contains:"; for (std::map<char, int>::const_iterator it = mymap.cbegin(); it != mymap.cend(); ++it) std::cout << " [" << (*it).first << ':' << (*it).second << ']'; std::cout << '\n'; return 0; }
[ "heturing@gmail.com" ]
heturing@gmail.com
675788d28d29b1971bcae0c05a37dca48a2c7f08
b857ba4267d8bafda5312272f050e966e4e32a25
/Source/Cross/Common/MoCore/FNetMessageConnection.cpp
06868ce45d7df55e4b6dab5d1725e550f122e774
[]
no_license
favedit/MoCross3d
8ce6fc7f92e4716dde95b19020347b24f7c2e469
b5b87bef0baa744625b348d7519509ba6f4e6f1e
refs/heads/master
2021-01-10T12:12:19.301253
2016-04-04T15:06:03
2016-04-04T15:06:03
54,264,397
0
1
null
null
null
null
GB18030
C++
false
false
13,613
cpp
#ifdef _MO_LINUX #include <unistd.h> #endif #include <MoCmStream.h> #include <MoCmNet.h> #include "MoCrNetConnection.h" #define MO_MD_MESSAGE_WAIT_INTERVAL 1 MO_NAMESPACE_BEGIN //============================================================ FNetMessageConnection::FNetMessageConnection(){ _isConnected = EFalse; _isUdpConnected = EFalse; _pSocket = MO_CREATE(FNetClientSocket); _pUdpSocket = MO_CREATE(FNetUdpClientSocket); _pipeLength = 1024*32; _queueLength = 1024*64; MO_CLEAR(_pInputPipe); MO_CLEAR(_pInputQueue); MO_CLEAR(_pInputUdpQueue); MO_CLEAR(_pOutputPipe); MO_CLEAR(_pOuputQueue); } //============================================================ FNetMessageConnection::~FNetMessageConnection(){ MO_DELETE(_pSocket); MO_DELETE(_pUdpSocket); MO_DELETE(_pInputPipe); MO_DELETE(_pInputQueue); MO_DELETE(_pInputUdpQueue); MO_DELETE(_pOutputPipe); MO_DELETE(_pOuputQueue); }; //============================================================ TBool FNetMessageConnection::Create(){ _pInputPipe = MO_CREATE(FPipe, _pipeLength); _pInputQueue = MO_CREATE(FQueue, _queueLength); _pInputUdpQueue = MO_CREATE(FQueue, _queueLength); _pOutputPipe = MO_CREATE(FPipe, _pipeLength); _pOuputQueue = MO_CREATE(FQueue, _queueLength); return ETrue; } //============================================================ TBool FNetMessageConnection::Connect(TCharC* pHost, TUint16 port){ // 链接服务器 _isConnected = _pSocket->Connect(pHost, port); return _isConnected; } //============================================================ TBool FNetMessageConnection::UdpConnect(TCharC* pHost, TUint16 port){ // 链接服务器 _isUdpConnected = _pUdpSocket->Connect(pHost, port); return _isUdpConnected; } //============================================================ TBool FNetMessageConnection::SetNonBlock(){ MO_ASSERT(_isConnected); _pSocket->SetNonBlock(); return ETrue; } //============================================================ TBool FNetMessageConnection::SetUdpNonBlock(){ MO_ASSERT(_isUdpConnected); _pUdpSocket->SetNonBlock(); return ETrue; } //============================================================ TBool FNetMessageConnection::Disconnect(){ // 断开TCP链接 _pSocket->Disconnect(); _isConnected = EFalse; // 断开UDP链接 _pUdpSocket->Disconnect(); _isUdpConnected = EFalse; return ETrue; } //============================================================ TBool FNetMessageConnection::OnStartup(){ return ETrue; } //============================================================ TBool FNetMessageConnection::AbandonReceiveMessages(){ while(ETrue){ // 判断是否存在长度数据 TUint32 length = (TUint32)_pInputPipe->Length(); if(length <= sizeof(SNetHead)){ break; } // 测试是否含有完整消息 TUint32 size = 0;; if(!_pInputPipe->TryPeek(&size, sizeof(TUint32))){ break; } // 消息不够一个完整的 if(length < size){ break; } // 舍弃一个消息 TByte readBuffer[MO_NETMESSAGE_MAXLENGTH]; _pInputPipe->Read(readBuffer, size); } return ETrue; } //============================================================ // <T>读取网络数据,写入接收缓冲。如果缓冲中有完整消息,则读出写入消息管道。</T> // // @return 处理结果 //============================================================ TBool FNetMessageConnection::ProcessTcpReceive(){ // 测试是否已经链接 if(!_isConnected){ return EFalse; } // 接收数据 TByte buffer[MO_NETMESSAGE_MAXLENGTH]; TInt received = _pSocket->Receive(buffer, MO_NETMESSAGE_MAXLENGTH); if(-1 == received){ _pSocket->Disconnect(); return EFalse; } if(received > 0){ MO_DEBUG(TC("Receive socket tcp data. (length=%d)"), received); TBool result = _pInputPipe->TryWrite(buffer, received); if(!result){ // 舍弃已经接收的消息 AbandonReceiveMessages(); // 重新写入数据 result = _pInputPipe->TryWrite(buffer, received); if(!result){ MO_FATAL(TC("Input pipe buffer is full.")); } } } // 判断是否存在长度数据 TUint32 length = (TUint32)_pInputPipe->Length(); if(length <= sizeof(SNetHead)){ return EFalse; } // 测试是否含有完整消息 TNetLength size = 0;; if(!_pInputPipe->TryPeek(&size, sizeof(TNetLength))){ return EFalse; } // 消息不够一个完整的 if(length < size){ return EFalse; } // 测试消息管道是否能放下该消息 TUint32 remain = (TUint32)_pInputQueue->Reamin(); if(remain < size){ return EFalse; } // 获得消息数据,写入消息管道 TByte readBuffer[MO_NETMESSAGE_MAXLENGTH]; TInt readed = _pInputPipe->Read(readBuffer, size); if(readed <= 0){ MO_ERROR(TC("Read pipe failure. (size=%d)"), size); return EFalse; } // 获得网络头信息 SNetHead* pHead = (SNetHead*)readBuffer; if(ENetProtocol_Message != pHead->protocol){ MO_FATAL(TC("Unknown net head protocol. (protocol=%d)"), pHead->protocol); return EFalse; } // 存储消息 return _pInputQueue->Push(readBuffer, readed); } //============================================================ // <T>读取网络数据,写入接收缓冲。如果缓冲中有完整消息,则读出写入消息管道。</T> // // @return 处理结果 //============================================================ TBool FNetMessageConnection::ProcessUdpReceive(){ // 测试是否已经链接 if(!_isUdpConnected){ return EFalse; } // 接收数据 TByte buffer[MO_NETMESSAGE_MAXLENGTH]; TInt received = _pUdpSocket->Receive(buffer, MO_NETMESSAGE_MAXLENGTH); // 错误处理 if(-1 == received){ _pSocket->Disconnect(); return EFalse; } // 未接收到消息 if(0 == received){ return EFalse; } MO_DEBUG(TC("Receive socket udp data. (length=%d)"), received); // 测试消息管道是否能放下该消息 TInt remain = _pInputUdpQueue->Reamin(); if(remain < received){ // 放弃前面的消息 _pInputUdpQueue->Reset(); } // 获得网络头信息 SNetHead* pHead = (SNetHead*)buffer; if(ENetProtocol_Message != pHead->protocol){ MO_FATAL(TC("Unknown net head protocol. (protocol=%d)"), pHead->protocol); return EFalse; } // 存储消息 return _pInputUdpQueue->Push(buffer, received); } //============================================================ // <T>读取网络数据,写入接收缓冲。如果缓冲中有完整消息,则读出写入消息管道。</T> // // @return 处理结果 //============================================================ TBool FNetMessageConnection::ProcessReceive(){ TBool result = ProcessTcpReceive(); result |= ProcessUdpReceive(); return result; } //============================================================ // <T>发送一个网络消息。</T> // // @param pMessage 消息对象 // @return 处理结果 //============================================================ TBool FNetMessageConnection::PushMessage(TNetMessage* pMessage){ MO_ASSERT(pMessage); // 检查是否已经链接 if(!_isConnected){ return EFalse; } // 序列化消息 TInt length; TByte buffer[MO_NETMESSAGE_MAXLENGTH]; if(pMessage->Serialize(buffer, MO_NETMESSAGE_MAXLENGTH, &length)){ #ifdef _MO_DEBUG TChar dump[MO_FS_DUMP_LENGTH]; TChar format[MO_FS_DUMP_LENGTH]; MO_STATIC_DEBUG(TC("Send tcp net message.\n%s%s"), pMessage->Dump(dump, MO_FS_DUMP_LENGTH), pMessage->DumpMemory(format, MO_FS_DUMP_LENGTH)); #endif // 发送消息 TInt result = _pSocket->Send(buffer, length); if(EError == result){ _pSocket->Disconnect(); return EFalse; } return ETrue; } return EFalse; } //============================================================ // <T>发送一个网络消息。</T> // // @param pMessage 消息对象 // @return 处理结果 //============================================================ TBool FNetMessageConnection::PushUdpMessage(TNetMessage* pMessage){ MO_ASSERT(pMessage); // 检查是否已经链接 if(!_isUdpConnected){ return EFalse; } // 序列化消息 TInt length; TByte buffer[MO_NETMESSAGE_MAXLENGTH]; if(pMessage->Serialize(buffer, MO_NETMESSAGE_MAXLENGTH, &length)){ #ifdef _MO_DEBUG TChar dump[MO_FS_DUMP_LENGTH]; TChar format[MO_FS_DUMP_LENGTH]; MO_STATIC_DEBUG(TC("Send udp net message.\n%s%s"), pMessage->Dump(dump, MO_FS_DUMP_LENGTH), pMessage->DumpMemory(format, MO_FS_DUMP_LENGTH)); #endif // 发送消息 TInt result = _pUdpSocket->Send(buffer, length); if(EError == result){ _pUdpSocket->Disconnect(); return EFalse; } return ETrue; } return EFalse; } //============================================================ // <T>弹出一个TCP消息。</T> //============================================================ TBool FNetMessageConnection::PopupMessage(TNetMessage* pMessage){ // 检查是否已经链接 if(!_isConnected){ return EFalse; } // 弹出消息 TByte buffer[MO_NETMESSAGE_MAXLENGTH]; TInt length = _pInputQueue->Pop(buffer, MO_NETMESSAGE_MAXLENGTH); if(length > 0){ // 反序列化消息 TInt msgLength; if(pMessage->Unserialize(buffer, length, &msgLength)){ #ifdef _MO_DEBUG // 输出消息信息 TChar dump[MO_FS_DUMP_LENGTH]; TChar format[MO_FS_DUMP_LENGTH]; MO_DEBUG(TC("Receive net message.\n%s%s"), pMessage->Dump(dump, MO_FS_DUMP_LENGTH), pMessage->DumpMemory(format, MO_FS_DUMP_LENGTH)); #endif } return ETrue; } return EFalse; } //============================================================ // <T>弹出一个UDP消息。</T> //============================================================ TBool FNetMessageConnection::PopupUdpMessage(TNetMessage* pMessage){ // 检查是否已经链接 if(!_isConnected){ return EFalse; } // 弹出消息 TByte buffer[MO_NETMESSAGE_MAXLENGTH]; TInt length = _pInputUdpQueue->Pop(buffer, MO_NETMESSAGE_MAXLENGTH); if(length > 0){ // 反序列化消息 TInt msgLength; if(pMessage->Unserialize(buffer, length, &msgLength)){ #ifdef _MO_DEBUG // 输出消息信息 TChar dump[MO_FS_DUMP_LENGTH]; TChar format[MO_FS_DUMP_LENGTH]; MO_DEBUG(TC("Receive net message.\n%s%s"), pMessage->Dump(dump, MO_FS_DUMP_LENGTH), pMessage->DumpMemory(format, MO_FS_DUMP_LENGTH)); #endif } return ETrue; } return EFalse; } //============================================================ // <T>一直等到读取到消息返回。</T> //============================================================ TBool FNetMessageConnection::WaitMessage(TNetMessage* pMessage){ // 检查是否已经链接 if(!_isConnected){ return EFalse; } // 接收到第一个消息 TByte buffer[MO_NETMESSAGE_MAXLENGTH]; while(ETrue){ // 弹出消息 TInt length = _pInputQueue->Pop(buffer, MO_NETMESSAGE_MAXLENGTH); if(length > 0){ // 反序列化消息 TInt msgLength; if(pMessage->Unserialize(buffer, length, &msgLength)){ #ifdef _MO_DEBUG // 输出消息信息 TChar dump[MO_FS_DUMP_LENGTH]; TChar format[MO_FS_DUMP_LENGTH]; MO_DEBUG(TC("Receive net message.\n%s%s"), pMessage->Dump(dump, MO_FS_DUMP_LENGTH), pMessage->DumpMemory(format, MO_FS_DUMP_LENGTH)); #endif break; } } MO_LIB_SLEEP(MO_MD_MESSAGE_WAIT_INTERVAL); } return ETrue; } //============================================================ // <T>一直等到读取到消息返回。</T> //============================================================ TBool FNetMessageConnection::ProcessWaitMessage(TNetMessage* pMessage){ // 接收到第一个消息 TByte buffer[MO_NETMESSAGE_MAXLENGTH]; while(ETrue){ // 检查是否已经链接 if(!_isConnected){ return EFalse; } // 接收消息 ProcessReceive(); // 弹出消息 TInt length = _pInputQueue->Pop(buffer, MO_NETMESSAGE_MAXLENGTH); if(length > 0){ // 反序列化消息 TInt msgLength; if(pMessage->Unserialize(buffer, length, &msgLength)){ #ifdef _MO_DEBUG // 输出消息信息 TChar dump[MO_FS_DUMP_LENGTH]; TChar format[MO_FS_DUMP_LENGTH]; MO_DEBUG(TC("Receive net message.\n%s%s"), pMessage->Dump(dump, MO_FS_DUMP_LENGTH), pMessage->DumpMemory(format, MO_FS_DUMP_LENGTH)); #endif break; } } MO_LIB_SLEEP(1); } return ETrue; } //============================================================ TBool FNetMessageConnection::DoConnect(){ //TNmCrConnectRequest request; //return PushMessage(&request); return ETrue; } //============================================================ TBool FNetMessageConnection::DoUdpConnect(){ //TNmCrUdpConnectRequest request; //request.SetClientId(_clientId); //return PushUdpMessage(&request); return ETrue; } MO_NAMESPACE_END
[ "favedit@hotmail.com" ]
favedit@hotmail.com
e0990005a483d7d0a08efb43daba74c2e0dd5ff1
ecc6cc9834d9e98e20c69226aebe5daf861e8097
/src/qt/signverifymessagedialog.cpp
53d80af3e5f45a73d24499dc8357ec3ed70e7256
[ "MIT" ]
permissive
lxccoin/lxccoin
daa3f082c579122e956eef6aa8a5ca6774d3d15d
fc0fb195531db7395cc197e3d78beefa8c27774e
refs/heads/master
2021-01-17T13:32:41.693636
2017-12-06T19:35:22
2017-12-06T19:35:22
24,432,339
0
2
null
null
null
null
UTF-8
C++
false
false
8,707
cpp
#include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <string> #include <vector> #include <QClipboard> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a valid LxcCoin address")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a valid LxcCoin address")); ui->signatureIn_VM->setPlaceholderText(tr("Enter LxcCoin signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(QString address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(QString address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(key.GetPubKey().GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
[ "root@usdwallet.localdomain" ]
root@usdwallet.localdomain
a7f579a1e13b9f3731926118bbd7c2f04a0ec8c1
6d6498aeee1c7205b023d4dfe154a01074ab5e63
/VIS.Test/test.cpp
d072cd6a97e2ef62c43b69b1605bdfeeb9fc3ea6
[]
no_license
nodbrag/VIS
36f42f6df41bd407675c0179dc8bbf41694e48b6
7e31758de1eb8b3b904eb0b54863bf98e32ea32e
refs/heads/master
2020-07-31T21:05:32.278581
2019-09-25T04:12:44
2019-09-25T04:12:44
210,752,972
1
0
null
null
null
null
GB18030
C++
false
false
3,435
cpp
/*---------------------------------------------- * Usage: * endoscope_test <ir_video_name> <rgb_video_name> *--------------------------------------------------*/ #include <opencv2/core/utility.hpp> #include <opencv2/videoio.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include <cstring> #include "ViTask.h" #define OUTPUT_DATA //#define OUTPUT_VIDEO using namespace std; using namespace cv; int main(int argc, char** argv) { Mat frame; //图像帧 Mat frameRgb; //RGB图像帧 TickMeter tm; //计时器 CViTask vt; //图像处理任务 vector<int> vtFlags; //图像处理任务标识 vtFlags.push_back(0); map<int, vector<vector<string>>> objs; //返回识别结果信息 string errorMsg; //返回错误信息 // 调试用参数 int showWait = 1; int startFrame = 0; float weight = .01f; vt.tp.tagAreaMax = 9000; //设置编码更新权重 vt.traces.SetMinWeight(weight); //设置解码阈值 vector<float> decodeThres; decodeThres.push_back(0.78); decodeThres.push_back(0.46); decodeThres.push_back(0.14); vt.traces.SetDecodeThres(decodeThres); // set input video string video = argv[1]; string videoRgb = argv[2]; VideoCapture cap(video); VideoCapture capRgb(videoRgb); cap.set(CV_CAP_PROP_POS_FRAMES, startFrame); capRgb.set(CV_CAP_PROP_POS_FRAMES, startFrame + 30); #ifdef OUTPUT_VIDEO // 打开录像输出文件 VideoWriter wr("output.mp4", CV_FOURCC('M', 'J', 'P', 'G'), 25, frame.size()); #endif map<int, vector<Rect>> roiRects; roiRects[0].push_back(Rect(0, 0, 1200, 1400)); roiRects[0].push_back(Rect(1220, 0, 1200, 1400)); Mat frameShow(720, 1280, CV_8UC3); // do the tracking printf("Start the tracking process, press ESC to quit.\n"); int cnt = 0; for (;; ) { cap >> frame; capRgb >> frameRgb; // 读不到图像则退出 if (frame.rows == 0 || frame.cols == 0) break; tm.reset(); tm.start(); vt.ViCall("RGB", frameRgb, "IR", frame, vtFlags, roiRects, frameShow, objs, errorMsg); tm.stop(); cout << "frame " << cnt << " time cost:" << tm.getTimeMilli() << "ms" << endl; //显示跟踪识别结果 imshow("endoscope", frameShow); if (waitKey(showWait) == 27) break; #ifdef OUTPUT_DATA //记录数据 for (int i = 0; i <MAX_TRACE; ++i) { if (vt.traces.trace[i].length != 0) { if (!vt.traces.trace[i].ofs.is_open()) { string fn = format("./trace%02d.csv", i); vt.traces.trace[i].ofs.open(fn); vt.traces.trace[i].ofs << "帧号,平均灰度,编码,加权编码,"; for (size_t j = 0, sz = vt.traces.trace[i].tagInfo.codeLevel.size(); j<sz; ++j) { vt.traces.trace[i].ofs << "占空比" << j << ","; } vt.traces.trace[i].ofs << endl; } vt.traces.trace[i].ofs << cnt << "," << vt.traces.trace[i].tagInfo.grayLevel << "," << vt.traces.trace[i].code << "," << vt.traces.trace[i].weightedCode << ","; for (size_t j = 0, sz = vt.traces.trace[i].tagInfo.codeLevel.size(); j<sz; ++j) { vt.traces.trace[i].ofs << vt.traces.trace[i].tagInfo.codeLevel[j] << ","; } vt.traces.trace[i].ofs << endl; } } #endif #ifdef OUTPUT_VIDEO // 写入录像输出文件 wr << frame; #endif ++cnt; } #ifdef OUTPUT_DATA for (int i = 0; i <MAX_TRACE; ++i) { if (vt.traces.trace[i].ofs.is_open()) { vt.traces.trace[i].ofs.close(); } } #endif #ifdef OUTPUT_VIDEO // 关闭录像输出文件 wr.release(); #endif }
[ "nodbrag@sina.com" ]
nodbrag@sina.com
15ab4aa7a6708c20eb835a8207b248d00806f4c4
1afb32961518b97958191b7b0aff19637ed231a5
/apps/rgbd_calibration/picture_taker/src/PictureTakerViewfinder.h
c078e2969080e089b805645aa68f96fa27beda62
[ "MIT" ]
permissive
rmbrualla/libcgt
57c790a259abc1256624ebc57e002023c636ef93
dedf0273b6e614a25b10cbc80a4dbaf59e02d06f
refs/heads/master
2021-01-12T07:26:04.046162
2016-12-22T08:39:54
2016-12-22T08:39:54
76,960,198
0
0
null
2016-12-20T13:47:05
2016-12-20T13:47:05
null
UTF-8
C++
false
false
1,875
h
#include <memory> #include <gflags/gflags.h> #include <QBrush> #include <QPen> #include <QWidget> #include <camera_wrappers/kinect1x/KinectCamera.h> #include <camera_wrappers/OpenNI2/OpenNI2Camera.h> #include <core/common/BasicTypes.h> #include <core/common/Array2DView.h> #include <core/io/NumberedFilenameBuilder.h> #include <core/vecmath/Vector2i.h> class PictureTakerViewfinder : public QWidget { Q_OBJECT public: using KinectCamera = libcgt::camera_wrappers::kinect1x::KinectCamera; using OpenNI2Camera = libcgt::camera_wrappers::openni2::OpenNI2Camera; // dir should be something like "/tmp". The trailing slash is optional. PictureTakerViewfinder( const std::string& dir = "", QWidget* parent = nullptr ); void updateRGB( Array2DReadView< uint8x3 > frame ); void updateBGRA( Array2DReadView< uint8x4 > frame ); void updateInfrared( Array2DReadView< uint16_t > frame ); protected: virtual void paintEvent( QPaintEvent* e ) override; virtual void keyPressEvent( QKeyEvent* e ) override; private: NumberedFilenameBuilder m_colorNFB; NumberedFilenameBuilder m_infraredNFB; const bool m_isDryRun; bool m_saving = false; bool m_isColor = true; std::unique_ptr< KinectCamera > m_kinect1xCamera; std::unique_ptr< OpenNI2Camera > m_oniCamera; Array2D< uint8x3 > m_rgb; Array2D< uint8x4 > m_bgra; Array2D< uint16_t > m_infrared; int m_nSecondsUntilNextShot; const int kDefaultDrawFlashFrames = 5; int m_nDrawFlashFrames = 0; QImage m_image; const QPen m_yellowPen = QPen{ Qt::yellow }; const QBrush m_whiteBrush = QBrush{ Qt::white }; int m_nextColorImageIndex = 0; int m_nextInfraredImageIndex = 0; void maybeSaveShot(); void maybeToggleStreams(); private slots: void onViewfinderTimeout(); void onShotTimeout(); };
[ "jiawen@csail.mit.edu" ]
jiawen@csail.mit.edu
babc71b808ded0320afd04eb9c473586ecea5265
25c16aebca642ecf23e597c239c76629480bba2c
/src/base_client.cpp
a3bf4a1a803345f4387e02829796eff9cc2db079
[]
no_license
officert/simple_http
edbe678f716559a93af22e2a534bf6a535b1a349
e9ca695b82ef1245e7c772bd099f02579e5b22c1
refs/heads/master
2021-01-10T05:56:00.051801
2016-03-01T01:04:19
2016-03-01T01:04:19
52,635,406
0
0
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
#include <iostream> #include <arpa/inet.h> #include "base_client.h" using namespace std; std::string BaseClient::send_message(const std::string address, const std::string message, const int port) { int socket_desc; struct sockaddr_in server; char *server_reply = new char[2000]; socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (socket_desc == -1) { throw "Error creating ocket"; } server.sin_addr.s_addr = inet_addr(address.c_str()); server.sin_family = AF_INET; server.sin_port = htons(port); int connected = connect(socket_desc, (struct sockaddr *)&server, sizeof(server)); if (connected < 0) { throw "Error connecting to socket"; } int message_sent = write(socket_desc, message.c_str(), strlen(message.c_str())); if (message_sent < 0) { throw "Error sending to socket message"; } else { int message_received = recv(socket_desc, server_reply, 2000, 0); if (message_received < 0) { throw "Error receiving socket message"; } close(socket_desc); } return server_reply; }
[ "timothyofficer@gmail.com" ]
timothyofficer@gmail.com
ae5cc948e5f121d8992645fc268b4b3c096cc30e
cb11dfc4e4aea17ccb6b5ce6884aab832d8c96a9
/proto_server/core/protocol/c4soap/c4soap_director.cpp
8ae274b36d46bd03bae3058967911df363850027
[ "MIT" ]
permissive
donnchadh/proto-server
fa45be030b800131b0845583ce58eb6a3b1e228f
e3a45dc64e8081deaad5a8a59560878c2b0bfdc1
refs/heads/master
2023-05-02T14:05:28.789360
2017-04-13T16:06:40
2017-04-13T16:06:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,628
cpp
// // Copyright (c) 2016 Terry Seyler // // Distributed under the MIT License // See accompanying file LICENSE.md // #include <core/protocol/c4soap/c4soap_message.hpp> #include <core/protocol/c4soap/c4soap_director.hpp> namespace proto_net { namespace protocol { namespace c4soap { bool is_async_c4soap(const std::string& soap) { c4soap_message msg(soap); return msg.is_async(); } std::string authenticate_password(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "AuthenticatePassword", seq); c4soap_message::param(ss, "password", "string", "root"); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_version_info(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetVersionInfo", seq); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_director_info(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDirectorInfo", seq); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_devices_by_interface(unsigned long& seq, const params_array& params) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDevicesByInterface", seq); c4soap_message::param(ss, "GUID", "string", params[0]); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_devices_by_c4i(unsigned long& seq, const params_array& params) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDevicesByC4i", seq); c4soap_message::param(ss, "c4i_name", "string", params[0]); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string send_to_device(unsigned long& seq, const params_array& params) { std::stringstream ss; if (params.size() > 1) { std::string id = params[0]; std::string cmd = params[1]; c4soap_message::begin_c4soap_message(ss, "SendToDevice", seq); c4soap_message::param(ss, "iddevice", "number", id); cmd = "<command>" + cmd + "</command>"; if (params.size() > 2) { std::string param = ""; for (size_t i = 2; i < params.size(); i++) { size_t j = i + 1; if (j < params.size()) { param += c4soap_message::get_param_value(params[i], params[j]); } else break; } std::string params = "<params>" + param + "</params>"; cmd += params; } std::string device_command = "<devicecommand>" + cmd + "</devicecommand>"; c4soap_message::param(ss, "data", "string", device_command); c4soap_message::end_c4soap_message(ss); } return ss.str(); } std::string send_async_to_device(unsigned long& seq, const params_array& params) { std::stringstream ss; if (params.size() > 1) { std::string id = params[0]; std::string cmd = params[1]; c4soap_message::begin_c4soap_async_message(ss, "SendToDevice", seq); c4soap_message::param(ss, "iddevice", "number", id); cmd = "<command>" + cmd + "</command>"; if (params.size() > 2) { std::string param = ""; for (size_t i = 2; i < params.size(); i++) { size_t j = i + 1; if (j < params.size()) { param += c4soap_message::get_param_value(params[i], params[j]); } else break; } std::string params = "<params>" + param + "</params>"; cmd += params; } std::string device_command = "<devicecommand>" + cmd + "</devicecommand>"; c4soap_message::param(ss, "data", "string", device_command); c4soap_message::end_c4soap_message(ss); } return ss.str(); } // register an event listener std::string register_event_listener(unsigned long& seq, const params_array& params) { std::stringstream ss; c4soap_message::begin_c4soap_async_message(ss, "RegisterEventListener", seq); c4soap_message::param(ss, "idevent", "ulong", params[0]); c4soap_message::param(ss, "iditem", "ulong", params[1]); c4soap_message::end_c4soap_message(ss); return ss.str(); } // unregister an event listener std::string unregister_event_listener(unsigned long& seq, const params_array& params) { std::stringstream ss; c4soap_message::begin_c4soap_async_message(ss, "UnregisterEventListener", seq); c4soap_message::param(ss, "idevent", "ulong", params[0]); c4soap_message::param(ss, "iditem", "ulong", params[1]); c4soap_message::end_c4soap_message(ss); return ss.str(); } } } }
[ "tseyler@control4.com" ]
tseyler@control4.com
2f588ac4df24f64fb0bc938f8e52a107639ae07a
c2f63c55934f0eb586159740f823d6ad0e00c9c0
/sources/ClassList/list.h
f6cdd09c8ef46876291a111348a45e412c3f391b
[]
no_license
Olieaw/ProgrammingCourse
70f86f07ff238c6148e352558b66a72fcf14e0b2
267c7ea4adf536ffb9fa017afe09bb4c70352840
refs/heads/master
2020-12-31T00:03:49.796761
2015-12-25T11:26:04
2015-12-25T11:26:04
46,551,571
0
0
null
2015-11-20T09:12:29
2015-11-20T09:12:29
null
UTF-8
C++
false
false
663
h
#ifndef LIST_H #define LIST_H #include <exception> class NoItemException { int number; public: NoItemException(int number) : number(number){} int getError() { return number; } }; class BeyondTheLimitException { int i; public: BeyondTheLimitException(int i) : i(i){} int getError() { return i; } }; class List { int* list; int size; int i; const int sizeIncrement = 6; void allocateMoreMemory(); public: List(int size = 2); ~List(); void put(int number); void erase(int position); int find(int number) const; int rfind(int number) const; }; #endif // LIST_H
[ "olieaw1998@yandex.ru" ]
olieaw1998@yandex.ru
04b1deaafac3602068baf843abde2a689d017901
bf5be9e5b6033c9634d46955df088771145f6da7
/Source/SmallWorld/Private/Buildings/BuildingActors/ArmyCenterActor.cpp
4f55d44a8c4061f01c1b3f076903ee9e5a9445e5
[]
no_license
devilmhzx/SmallWorld
eaff8c1abb460397d7844a083eac24ce77954b92
eff5eddb408fc337e70be716a250ed98f17dd097
refs/heads/master
2020-07-19T00:04:27.629460
2019-09-03T13:34:58
2019-09-03T13:34:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
781
cpp
#include "ArmyCenterActor.h" #include "ArmyCenterData.h" AArmyCenterActor::AArmyCenterActor() { RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent")); BaseMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent")); BaseMeshComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform); mMaxLevel = 3; MeshPathLevel_1 = TEXT("/Game/CastlePack/Meshes/SM_Wacamp_Lvl1"); MeshPathLevel_2 = TEXT("/Game/CastlePack/Meshes/SM_Wacamp_Lvl2"); MeshPathLevel_3 = TEXT("/Game/CastlePack/Meshes/SM_Wacamp_Lvl3"); } void AArmyCenterActor::On_Init() { mData->mLevel = 1; UStaticMesh * mesh = LoadObject<UStaticMesh>(this, *GetMeshPath()); if (mesh) { BaseMeshComponent->SetStaticMesh(mesh); } }
[ "1097195326@qq.com" ]
1097195326@qq.com
e56846cf89ea0691b0628fda4303ca7291eee9fe
2d91e4376e651c97a003dd6bc351afe3f344b78b
/software/libraries/SimpleCAN/sailingSpecifics.cpp
938ff7966266ff4952dc397ef8f73b5a6fb6dcfd
[]
no_license
splashelec/splashelec
9b4465c283fc0d5eca0151f8e27122c44b0ae1bb
ef6973af0d4aa225fcf3dcd5e7d1b9fb21663c60
refs/heads/master
2016-09-10T20:52:02.215108
2015-05-27T23:12:44
2015-05-27T23:12:44
2,659,035
2
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
#include "sailingSpecifics.h" //Mapping functions void mapSend(uint8_t data[8], uint64_t value, uint32_t id) { //Conversion switch(id) { case 50: //headSailWinchSpeed { } case 51: //mainSailWinchSpeed { } case 52: // { } case 53: //Seat { } case 54: //rudderAngle { } default: { } } //Partitioning for(int i = 0 ; i<8 ; i++) { data[i]=(uint8_t)(value>>(8*i)); } } void mapReceive(uint64_t* data, uint8_t tmp[8], uint8_t length) { *data=0; //Recombination for(int i = 0 ; i<length ; i++) { *data=*data | ((uint64_t)(tmp[i])<<(8*i)); } }
[ "bernt.weber@splashelec.com" ]
bernt.weber@splashelec.com
29cd330c10df2cf7f7065182f8fa0b2d52855cec
7c9214dfe43101829e65efd26140fab8d5945777
/Game/Game.h
8dd747570e08073e89cec523001284c4abb9f79a
[]
no_license
chadha02/Game-Engine
f7fbecc51843ce76a74ac0eae5612097ccbce51b
910cc792811d978288d0801e71f075eb8c8f1b17
refs/heads/master
2021-01-23T02:16:12.962771
2017-03-23T18:16:30
2017-03-23T18:16:30
85,980,118
0
0
null
null
null
null
UTF-8
C++
false
false
146
h
#ifndef _GAME_H #define _GAME_H #include "../GLib/_Console/ConsolePrint.h" namespace Game { bool Init(); //void TestStringPool(); } #endif
[ "u1011565@utah.edu" ]
u1011565@utah.edu
e88c017b289a12b4a0adcc93beee0647e2e4e388
a2fb2d662d53f88fcb21ebd3c13f4f577420827e
/Algorithms/Sorting/ClosestNumbers.cpp
5844f42b4544b7d631547ab7e5aff35a25304250
[]
no_license
sandboxorg/HackerRank
8560606d7bde4c851d49c2c8ce9ac904d9dd16bf
1aa9d83111f64c345145f9b89c0cbb30f20114e1
refs/heads/master
2021-01-17T08:56:07.427306
2016-05-17T11:48:43
2016-05-17T11:48:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
637
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <climits> using namespace std; int main() { int n; cin >> n; vector<int> v; for (int i = 0; i < n; i++) { v.push_back(i); cin >> v[i]; } sort(v.begin(), v.end()); int smallest_diff = INT_MAX; for (int i = 1; i < n; i++) { if (abs(v[i-1] - v[i]) < smallest_diff) smallest_diff = abs(v[i-1] - v[i]); } for (int i = 1; i < n; i++) { if (abs(v[i-1] - v[i]) == smallest_diff) cout << v[i-1] << " " << v[i] << " "; } return 0; }
[ "douglasbellonrocha@gmail.com" ]
douglasbellonrocha@gmail.com
a4f0d33a4b52db3b205b3e39746da4b46199e8dc
e38284c7578f084dd726e5522b3eab29b305385b
/Wml/Include/WmlConvexRegion.inl
0b93a8a77356bee3f49c00fe8dbefb8a6150db7b
[ "MIT" ]
permissive
changjiayi6322/deform2d
99d73136b493833fa4d6788120f6bfb71035bc4d
1a350dd20f153e72de1ea9cffb873eb67bf3d668
refs/heads/master
2020-06-02T19:38:45.240018
2018-07-04T20:26:35
2018-07-04T20:26:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
826
inl
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2004. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. //---------------------------------------------------------------------------- inline int ConvexRegion::GetPortalQuantity () const { return m_iPortalQuantity; } //---------------------------------------------------------------------------- inline Portal* ConvexRegion::GetPortal (int i) const { assert( i < m_iPortalQuantity ); return m_apkPortal[i]; } //----------------------------------------------------------------------------
[ "git@liyiwei.org" ]
git@liyiwei.org
6ebeb382d71f454ae92c1d70d1475cc9cb7137ea
ca2125d3a3a4aa7167326a09ff3adae4a03c90fe
/Platforms/Emscripten/interface/EmscriptenPlatformMisc.hpp
d4abb83c46bc6414a0a6a0f9b840c7deefbf026d
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-nvidia-2002", "BSD-2-Clause" ]
permissive
DiligentGraphics/DiligentCore
9e124fee53bda1b280b3aa8c11ef1d3dc577d630
2ebd6cd1b3221a50d7f11f77ac51023a2b33697f
refs/heads/master
2023-08-28T14:13:18.861391
2023-08-24T00:52:40
2023-08-24T00:52:40
44,292,712
545
180
Apache-2.0
2023-09-11T14:44:45
2015-10-15T03:56:34
C++
UTF-8
C++
false
false
1,566
hpp
/* * Copyright 2019-2022 Diligent Graphics LLC * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once #include "../../Linux/interface/LinuxPlatformMisc.hpp" #include "../../../Platforms/Basic/interface/DebugUtilities.hpp" namespace Diligent { struct EmscriptenMisc : public LinuxMisc {}; } // namespace Diligent
[ "assiduous@diligentgraphics.com" ]
assiduous@diligentgraphics.com
d6cf3a3dd4daa4e90c9d3f3cf248ce69dd14b90a
95ebb92e21b6ba70cb7b326691ceb2e8049f25c9
/proto-studio/app_ide.h
57e6d5f03c60274af0828c8511b7d84b1cf9731a
[]
no_license
enburk/ae
1940e440aa9026e7a5e8dbfa5cecd94d3e2ca95e
188b58e8e3d7c415733479b33f3bd0f5aa21b422
refs/heads/master
2022-11-09T06:42:04.843889
2022-11-06T10:09:59
2022-11-06T10:09:59
184,372,579
0
0
null
null
null
null
UTF-8
C++
false
false
9,121
h
#pragma once #include "abc.h" #include "app_ide_compiler.h" #include "app_ide_console.h" #include "app_ide_editor.h" #include "app_ide_flist.h" #include "../../auxs/test.h" using namespace std::literals::chrono_literals; struct IDE : gui::widget<IDE> { gui::canvas canvas; gui::canvas toolbar; gui::button button_run; gui::button button_build; gui::button button_rebuild; gui::button button_test; gui::area<Flist> flist_area; gui::area<Editor> editor_area; gui::area<Console> console_area; gui::splitter splitter_editor_l; gui::splitter splitter_editor_r; Flist& flist = flist_area.object; Editor& editor = editor_area.object; Console& console = console_area.object; gui::area<Test> test_area; // very last sys::thread thread; gui::property<gui::time> timer; sys::directory_watcher watcher; std::atomic<bool> reload = false; gui::time edittime; bool syntax_run = false; bool syntax_ok = false; IDE() { skin = "gray"; canvas.color = rgba::red; toolbar.color = gui::skins[skin].light.first; button_run .text.text = "run"; button_build.text.text = "build"; button_rebuild.text.text = "rebuild"; button_test.text.text = "test"; console.activate(&console.editor); console_area.show_focus = true; editor_area.show_focus = true; flist_area.show_focus = true; test_area.hide(); watcher.dir = std::filesystem::current_path(); watcher.action = [this](std::filesystem::path path, str what) { str e = path.extension().string(); if (std::filesystem::is_directory(path)) return; if (e != ".ae" and e != ".ae!" and e != ".ae!!" and e != ".c++" and e != ".cpp" and e != ".hpp") return; console.events << light(path.string() + " " + what); reload = true; }; watcher.error = [this](aux::error error){ console.events << red("watcher error: " + error); }; watcher.watch(); } ~IDE() { watcher.cancel(); doc::text::repo::save(); } void on_change (void* what) override { if (timer.now == gui::time()) timer.go(gui::time::infinity, gui::time::infinity); if (what == &timer) { if (reload) { reload = false; console.events << "Reload..."; flist.reload(); editor.flist.reload(); // before repo delete something doc::text::repo::reload(); // triggers recompiling editor.editor.update_text = true; syntax_run = true; syntax_ok = false; } if ((gui::time::now - edittime) > 30s) { edittime = gui::time::infinity; doc::text::repo::save(); } if ((gui::time::now - edittime) > 0s) { auto& report = doc::text::repo::report; if (not report.errors.empty()) edittime = gui::time::now; if (not report.messages.empty()) { console.activate(&console.events); console.events << report(); report.clear(); } } if ((gui::time::now - edittime) > 10s) { auto& report = doc::ae::syntax::analysis::events; if (report.messages.size() > 0) { console.events << report(); report.clear(); } } doc::text::repo::tick(); if ((gui::time::now - edittime) > 500ms) if (syntax_run and editor.syntax_ready()) { syntax_run = false; syntax_ok = editor. log.errors.empty(); console.editor.clear(); if (not editor.log.errors.empty()) console.activate(&console.editor); if (not editor.log.messages.empty()) { console.editor << editor.log(); editor.log.clear(); } } button_run.enabled = ( editor.path.now.extension() == ".ae!" or editor.path.now.extension() == ".ae!!") and syntax_ok; button_build.enabled = ( editor.path.now.extension() == ".ae!" or editor.path.now.extension() == ".ae!!") and syntax_ok; button_rebuild.enabled = editor.path.now.extension() == ".ae" or editor.path.now.extension() == ".ae!" or editor.path.now.extension() == ".ae!!"; } if (what == &coord) { int W = coord.now.w; if (W <= 0) return; int H = coord.now.h; if (H <= 0) return; int w = gui::metrics::text::height*10; int h = gui::metrics::text::height*12/10; int d = gui::metrics::line::width*6; int l = sys::settings::load("splitter.editor.l.permyriad", 18'00) * W / 100'00; int r = sys::settings::load("splitter.editor.r.permyriad", 70'00) * W / 100'00; splitter_editor_l.coord = xyxy(l-d, h, l+d, H); splitter_editor_r.coord = xyxy(r-d, h, r+d, H); splitter_editor_l.lower = 10'00 * W / 100'00; splitter_editor_l.upper = 35'00 * W / 100'00; splitter_editor_r.lower = 55'00 * W / 100'00; splitter_editor_r.upper = 85'00 * W / 100'00; canvas.coord = coord.now.local(); toolbar.coord = xywh(0, 0, W, h); button_run.coord = xywh(0*w, 0, w, h); button_build.coord = xywh(1*w, 0, w, h); button_rebuild.coord = xywh(2*w, 0, w, h); button_test.coord = xywh(W-w, 0, w, h); test_area.coord = xyxy(0, h, W, H); flist_area.coord = xywh(0, h, l-0, H-h); editor_area.coord = xywh(l, h, r-l, H-h); console_area.coord = xywh(r, h, W-r, H-h); } if (test_area.object.aux.done) button_test.text.color = test_area.object.aux.ok ? rgba::green : rgba::error; if (what == &flist) { editor.flist.selected = flist.selected.now; focus = &editor_area; syntax_run = true; syntax_ok = false; } if (what == &editor.flist) { flist.selected = editor.flist.selected.now; focus = &editor_area; syntax_run = true; syntax_ok = false; } if (what == &editor) { edittime = gui::time::now; syntax_run = true; syntax_ok = false; } if (what == &console) { if (syntax_run) return; std::string source = console.pressed_file; if (source != "" and std::filesystem::exists(source)) flist.selected = source; focus = &editor_area; editor.editor.go(doc::place{ std::stoi(console.pressed_line)-1, std::stoi(console.pressed_char)-1}); } if (what == &button_test) { bool on = test_area.alpha.to != 0; bool turn_on = not on; test_area.show(turn_on); flist_area.hide(turn_on); editor_area.hide(turn_on); console_area.hide(turn_on); test_area.coord = turn_on ? xyxy(0, toolbar.coord.now.h, coord.now.w, coord.now.h): xyxy{}; if (turn_on) focus = &test_area; else focus = &editor_area; } if (what == &button_rebuild) { doc::text::repo::map[editor.path.now].model->tokenize(); } if (what == &button_run or what == &button_build) try { bool run = what == &button_run; console.activate(&console.output); if (not ide::compiler::translate( editor.path.now, console.output)) return; thread = [this,run](auto& cancel) { ide::compiler::run( editor.path.now, console.output, cancel, run); }; } catch (std::exception const& e) { console.output << red(doc::html:: encoded(e.what())); } if (what == &splitter_editor_l) { sys::settings::save( "splitter.editor.l.permyriad", splitter_editor_l.middle *100'00 / coord.now.w); on_change(&coord); } if (what == &splitter_editor_r) { sys::settings::save( "splitter.editor.r.permyriad", splitter_editor_r.middle *100'00 / coord.now.w); on_change(&coord); } } }; sys::app<IDE> app("ae proto-studio");//, {0,0}, {100, 100});
[ "enburk@gmail.com" ]
enburk@gmail.com
f18d735a56b94a37e752385337d7f68f2e2f8119
1e1adecddbe2ccbb07207bac4eeda10ad84f16df
/fakul.cpp
30be7aa646e36f703a0e610e623b2a7cab415ef0
[]
no_license
chigganutta/C--
c9bb77f5aff3c7a0ea904bdc536fc2d1fec8c94a
07a895e7a322f30ce64548d5fa62b5783722d4c0
refs/heads/master
2021-01-01T16:13:05.755526
2014-02-12T00:21:54
2014-02-12T00:21:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
// fakul.cpp #include <iostream> using namespace std; long fakul(long n); int main(void) { long n; long val; cout << "Ihre Zahl bitte: "; if (!(cin >> n)) { cerr << "Bitte keine 0 eingeben!\n"; exit(1); } val = fakul(n); cout << "Die Fakultät beträgt: " << val << '\n'; } long fakul(long n) { if ( n ) { return n * fakul(n-1); } return 1; }
[ "felix12000@live.de" ]
felix12000@live.de
40bbeadfb54d7723c61ece890c18d0d894e46739
d7ef1300dc1b4d6174788605bf2f19ece12a1708
/other/old_scripts/scripts/MC_true_zarah/K0s_analysis_part1+true_31.cxx
a389d262d8a96a785b9145031753b2543fcddb8c
[]
no_license
libov/zeus
388a2d49eb83f098c06008cb23b6ab42ae42e0e5
a0ca857ede59c74cace29924503d78670e10fe7b
refs/heads/master
2021-01-01T05:51:48.516178
2014-12-03T09:14:02
2014-12-03T09:14:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,422
cxx
////////////////////////////////////////////////// ////////////// K0s analysis ///////////////// ////////////// with V0lite ///////////////// ////////////// (part1) ///////////////// ////////////////////////////////////////////////// // // // // // Libov Vladyslav // // T.S. National University of Kiev // // April 2008 // // // // // ////////////////////////////////////////////////// ////////// /////////// ////////// Part1: peparing small trees /////////// ////////// /////////// ////////////////////////////////////////////////// // // // 1. Event selection // // 2. K0s selection (loose) // // 3. Writing data to small tree // // easy to analyze // // // ////////////////////////////////////////////////// // Modified 05 September: add true info #ifndef __CINT__ #include <TChain.h> #include <TH1F.h> #include <TFile.h> #include <TTree.h> #include <TClonesArray.h> #include <TROOT.h> #include <TSystem.h> #include <iostream> using namespace std; #include<Daughter.h> #include<Mother.h> #endif void analysis() { Int_t goa=0, nevents=0, Nv0lite=0, Sincand=0, Tt1_id[80], Tt2_id[80], Tq1[80], Tq2[80], Trk_ntracks=0, Trk_id[300], Tt1_layout[80], Tt2_layout[80], Tt1_layinn[80], Tt2_layinn[80]; Float_t Tinvmass_k0[80], Tinvmass_lambda[80], Tinvmass_alambda[80], Tinvmass_ee[80], Tsecvtx_collin3[80], Tsecvtx_collin2[80], Tsecvtx[80][3], reso_mass=0, Tp1[80][3], Tp2[80][3], Tpk[80][3], corr=0, Siq2el[10], Siyel[10], Siyjb[10], Sizuhmom[4][10], Sicalpos[3][10], Sisrtpos[2][10], Sisrtene[10], Siecorr[3][10], Sith[10], Siprob[10]; Int_t Trk_prim_vtx[300], Trk_sec_vtx[300], Trk_vtx[300], Runnr=0, year=0, k0_cand=0; const Int_t low_2004=47010, up_2004=51245, low_2005=52244, up_2005=57123, low_2006=58181, up_2006=59947, low_2006p=60005, up_2006p=61746, low_2007=61747, up_2007=62638; const Float_t corr_2004=1.005, corr_2005=1.009, corr_2006=1.0077, corr_2007=1.0065; Float_t Xvtx=0, Yvtx=0, Zvtx=0; Int_t Tltw[14]; Float_t Cal_et=0; Int_t Kt_njet_a=0; Float_t Kt_etjet_a[20], Kt_etajet_a[20], Kt_phijet_a[20]; Int_t Fmck_nstor=0, // Number of stored (e.g. those survived pT cut) // FMCKIN particles Fmck_prt[500], // particle code FMCPRT Fmck_daug[500]; // Daughter of Float_t Fmck_m[500]; // particle mass Int_t Fmck_id[500]; // particle FMCKIN ID Float_t Fmck_px[500], // particle px Fmck_py[500], // particle py Fmck_pz[500]; // particle pz //TChain *myChain=new TChain("resonance"); TChain *myChain=new TChain("orange"); // PATH to NTUPLES gSystem->Load("libzio.so"); gSystem->Load("libdcap.so"); //------------------------------------------------------------------------------------------// myChain->Add("zeus://acs/mc/ntup/05/v01/dijetPHP/root/dwwe25.f13548.lfres.e0506.uncut_0043.root"); myChain->Add("zeus://acs/mc/ntup/05/v01/dijetPHP/root/dwwe25.f13548.lfres.e0506.uncut_0044.root"); myChain->Add("zeus://acs/mc/ntup/05/v01/dijetPHP/root/dwwe25.f13548.lfres.e0506.uncut_0045.root"); //input //------------------------------------------------------------------------------------------// // V0lite myChain->SetBranchAddress("Nv0lite",&Nv0lite); //myChain->SetBranchAddress("Tinvmass_k0",Tinvmass_k0); //myChain->SetBranchAddress("Tinvmass_lambda",Tinvmass_lambda); //myChain->SetBranchAddress("Tinvmass_alambda",Tinvmass_alambda); myChain->SetBranchAddress("Tinvmass_ee",Tinvmass_ee); myChain->SetBranchAddress("Tsecvtx_collin3",Tsecvtx_collin3); myChain->SetBranchAddress("Tsecvtx_collin2",Tsecvtx_collin2); myChain->SetBranchAddress("Tpk",Tpk); myChain->SetBranchAddress("Tp1",Tp1); myChain->SetBranchAddress("Tp2",Tp2); //myChain->SetBranchAddress("Tq1",Tq1); //myChain->SetBranchAddress("Tq2",Tq2); myChain->SetBranchAddress("Tt1_id",Tt1_id); myChain->SetBranchAddress("Tt2_id",Tt2_id); myChain->SetBranchAddress("Tt1_layout",Tt1_layout); myChain->SetBranchAddress("Tt2_layout",Tt2_layout); myChain->SetBranchAddress("Tt1_layinn",Tt1_layinn); myChain->SetBranchAddress("Tt2_layinn",Tt2_layinn); // Tracking, Trk_vtx myChain->SetBranchAddress("Trk_ntracks",&Trk_ntracks); myChain->SetBranchAddress("Trk_id",Trk_id); myChain->SetBranchAddress("Trk_prim_vtx",Trk_prim_vtx); myChain->SetBranchAddress("Trk_sec_vtx",Trk_sec_vtx); myChain->SetBranchAddress("Trk_vtx",Trk_vtx); //Vertex myChain->SetBranchAddress("Xvtx",&Xvtx); myChain->SetBranchAddress("Yvtx",&Yvtx); myChain->SetBranchAddress("Zvtx",&Zvtx); //Sira, Si_kin myChain->SetBranchAddress("Sincand",&Sincand); myChain->SetBranchAddress("Siq2el",Siq2el); myChain->SetBranchAddress("Siyel",Siyel); myChain->SetBranchAddress("Siyjb",Siyjb); myChain->SetBranchAddress("Sizuhmom",Sizuhmom); //myChain->SetBranchAddress("Siecorr",Siecorr); //myChain->SetBranchAddress("Sith",Sith); myChain->SetBranchAddress("Sicalpos",Sicalpos); myChain->SetBranchAddress("Sisrtpos",Sisrtpos); myChain->SetBranchAddress("Sisrtene",Sisrtene); myChain->SetBranchAddress("Siprob",Siprob); // Event myChain->SetBranchAddress("Runnr",&Runnr); // CAL block - calorimeter info myChain->SetBranchAddress("Cal_et",&Cal_et); // ktJETSA_A myChain->SetBranchAddress("Kt_njet_a",&Kt_njet_a); myChain->SetBranchAddress("Kt_etjet_a",Kt_etjet_a); myChain->SetBranchAddress("Kt_etajet_a",Kt_etajet_a); myChain->SetBranchAddress("Kt_phijet_a",Kt_phijet_a); // FMCKIN (common ntuple additional block) myChain->SetBranchAddress("Fmck_nstor",&Fmck_nstor); myChain->SetBranchAddress("Fmck_prt",Fmck_prt); myChain->SetBranchAddress("Fmck_m",Fmck_m); myChain->SetBranchAddress("Fmck_daug",Fmck_daug); myChain->SetBranchAddress("Fmck_id",Fmck_id); myChain->SetBranchAddress("Fmck_px",Fmck_px); myChain->SetBranchAddress("Fmck_py",Fmck_py); myChain->SetBranchAddress("Fmck_pz",Fmck_pz); // Trigger stuff //myChain->SetBranchAddress("Tltw", Tltw); cout<<"Calculating number of events..."<<endl; nevents=myChain->GetEntries(); cout<<nevents<<" events in this chain..."<<endl; // TREE VARIABLES DEFINITION // these variables are written to tree for further analysis Int_t nv0=0, // number K0s candidates that passed soft selection id1[80], // id of the first track id2[80], // id of the second track runnr=0, // number of run is1_sec[80], // =1 if 1st track flagged as secondary is2_sec[80], // =1 if 2nd track flagged as secondary is1_prim[80], // =1 if 1st track flagged as primary is2_prim[80], // =1 if 2nd track flagged as primary sincand, // Number of Sinistra electron candidates layout1[80], //outer superlayer of 1st pion layout2[80], //outer superlayer of 2nd pion layinn1[80], //inner superlayer of 1st pion layinn2[80]; //inner superlayer of 2nd pion Float_t p1[80][3], // momenta of 1st track p2[80][3], // momenta of 2nd track coll2[80], // angle 2D coll3[80], // collinearity angle 3D q2el, // Q^2 from electron method (1st Sinistra candidate) yel, // y from electron method (1st Sinistra candidate) yjb, // y from Jaquet-Blondel method (1st Sinistra candidate) box_x, // x position of scattered electron box_y, // y position of electron e_pz, // E-pz calculated both from hadronic system and electron siprob, // probability of 1st Sinistra candidate mass_lambda[80],// invariant mass assuming proton(larger momenuma) and pion mass_ee[80]; // invariant mass assuming electron and positron Int_t tlt[6][16]; // 3rd-level trigger: tlt[m][k] // m=3 SPP, m=4 DIS ... k=1 bit 1 (e.g. HPP01) k=2 bit 2 .. Float_t xvtx=0, // coordinates of primary vertex; 0 if none yvtx=0, // zvtx=0; // Float_t cal_et=0; // Transverse Energy =SUM(CALTRU_E*sin(thetai)) Int_t njet=0; // Number of jets (kT jet finder A) Float_t etjet[20], // Transverse energy of jets etajet[20], // eta of jets phijet[20]; // phi of jets Int_t ntrue=0, // Number of stored (e.g. those survived pT cut) // FMCKIN particles fmcprt[50], // FMCPRT daug_of[50]; // Daughter of Float_t mass[50]; // mass Int_t fmckin_id[50]; // FMCKIN ID of the particle Float_t px[50], // px of the particle py[50], // py of the particle pz[50]; // pz of the particle //-------------------------------------------------------------------------------------------// Int_t err=0; Int_t with_V0=0, ev_pass_DIS=0; TH1F *hdebug=new TH1F("hdebug","",10,0,10); cout<<"Start add branches"<<endl; TTree *tree=new TTree("resonance","K0sK0s"); tree->Branch("nv0",&nv0,"nv0/I"); tree->Branch("p1",p1,"p1[nv0][3]/F"); tree->Branch("p2",p2,"p2[nv0][3]/F"); tree->Branch("coll2",coll2,"coll2[nv0]/F"); tree->Branch("coll3",coll3,"coll3[nv0]/F"); tree->Branch("id1",id1,"id1[nv0]/I"); tree->Branch("id2",id2,"id2[nv0]/I"); tree->Branch("is1_sec",is1_sec,"is1_sec[nv0]/I"); tree->Branch("is2_sec",is2_sec,"is2_sec[nv0]/I"); tree->Branch("is1_prim",is1_prim,"is1_prim[nv0]/I"); tree->Branch("is2_prim",is2_prim,"is2_prim[nv0]/I"); tree->Branch("runnr",&runnr,"runnr/I"); tree->Branch("q2el",&q2el,"q2el/F"); tree->Branch("yel",&yel,"yel/F"); tree->Branch("yjb",&yel,"yjb/F"); tree->Branch("siprob",&siprob,"siprob/F"); tree->Branch("sincand",&sincand,"sincand/I"); tree->Branch("box_x",&box_x,"box_x/F"); tree->Branch("box_y",&box_y,"box_y/F"); tree->Branch("e_pz",&e_pz,"e_pz/F"); tree->Branch("mass_lambda",mass_lambda,"mass_lambda[nv0]/F"); tree->Branch("mass_ee",mass_ee,"mass_ee[nv0]/F"); tree->Branch("layout1",layout1,"layout1[nv0]/I"); tree->Branch("layout2",layout2,"layout2[nv0]/I"); tree->Branch("layinn1",layinn1,"layinn1[nv0]/I"); tree->Branch("layinn2",layinn2,"layinn2[nv0]/I"); //tree->Branch("tlt",tlt,"tlt[6][16]/I"); tree->Branch("xvtx",&xvtx,"xvtx/F"); tree->Branch("yvtx",&yvtx,"yvtx/F"); tree->Branch("zvtx",&zvtx,"zvtx/F"); tree->Branch("cal_et",&cal_et,"cal_et/F"); tree->Branch("njet",&njet,"njet/I"); tree->Branch("etjet",&etjet,"etjet[njet]/F"); tree->Branch("etajet",&etajet,"etajet[njet]/F"); tree->Branch("phijet",&phijet,"phijet[njet]/F"); tree->Branch("ntrue",&ntrue,"ntrue/I"); tree->Branch("fmcprt",&fmcprt,"fmcprt[ntrue]/I"); tree->Branch("mass",&mass,"mass[ntrue]/F"); tree->Branch("daug_of",&daug_of,"daug_of[ntrue]/I"); tree->Branch("fmckin_id",&fmckin_id,"fmckin_id[ntrue]/I"); tree->Branch("px",&px,"px[ntrue]/F"); tree->Branch("py",&py,"py[ntrue]/F"); tree->Branch("pz",&pz,"pz[ntrue]/F"); //------ Loop over events -------// char name[256]; Int_t file_num=0; bool fire; cout<<"Start looping..."<<endl; for(Int_t i=0;i<nevents;i++) { if (goa==10000) { cout<<i<<" events processed"<<" Runnr:"<<Runnr<<endl; goa=0; } goa++; //cout<<"Getting entry "<<i<<" ..."<<endl; myChain->GetEntry(i); //cout<<"event "<<i<<endl; //------DIS event selection------// hdebug->Fill(1); //if (Siq2el[0]<1) continue; // Q^2>1 GeV^2 hdebug->Fill(2); // E-pz calculation float Empz_had = Sizuhmom[0][3] - Sizuhmom[0][2]; float Empz_e = Siecorr[0][2]*(1-TMath::Cos( Sith[0] )); float EminPz_Evt = Empz_e + Empz_had; //if ((EminPz_Evt<38)||(EminPz_Evt>60)) continue; // 38 < E-pz < 60 GeV hdebug->Fill(3); // electron position calculation (box cut) float x_srtd=Sicalpos[0][0]; // position of electron in calorimeter float y_srtd=Sicalpos[0][1]; if (Sisrtene[0]>0) { x_srtd=Sisrtpos[0][0]; // position of electron in SRDT y_srtd=Sisrtpos[0][1]; } //if (TMath::Abs(x_srtd)<12) // box cut: electron required to be outside 12x6 cm^2 box { //if (TMath::Abs(y_srtd)<6) continue; } hdebug->Fill(4); //if (Siyel[0]>0.95) continue; // y from electron method < 0.95 hdebug->Fill(5); //if (Siyjb[0]<0.01) continue; // y from Jacquet-Blondel method > 0.01 hdebug->Fill(6); ev_pass_DIS++; //------ (soft) K0s selection------// Int_t cand_k0=0, list_k0[180]; if (Nv0lite<1) continue; with_V0++; if (Nv0lite>75) cout<<Nv0lite<<endl; //this loop is now sensless but it will become necessary if we restrict to at least 2K0s for(Int_t j=0;j<Nv0lite;j++) { Daughter t1(Tp1[j][0],Tp1[j][1],Tp1[j][2]); Daughter t2(Tp2[j][0],Tp2[j][1],Tp2[j][2]); if ((t1.GetPt()<0.1)||(t2.GetPt()<0.1)) continue; if ((Tt1_layout[j]<3)||(Tt2_layout[j]<3)) continue; Mother K0s_cand(t1,t2); Float_t p1=t1.GetP(); Float_t p2=t2.GetP(); Float_t mass_pi_p=0; if (p1>=p2) //first track proton(antiproton); second track pion_minus(pion_plus) { mass_pi_p=K0s_cand.GetMass_m(6,4); //if(Tq1[j]>0) cout<<"Lambda"<<endl; //if(Tq1[j]<0) cout<<"ALambda"<<endl; } if (p1<p2) //first track pion_minus(pion_plus); first track proton(antiproton); { mass_pi_p=K0s_cand.GetMass_m(4,6); //if(Tq1[j]>0) cout<<"ALambda"<<endl; //if(Tq1[j]<0) cout<<"Lambda"<<endl; } //cout<<mass_pi_p<<" "<<Tinvmass_lambda[j]<<" "<<Tinvmass_alambda[j]<<endl; //if (mass_pi_p<1.116) continue; //mass_lambda=mass_pi_p; //mass_ee=Tinvmass_ee[j]; //if (Tinvmass_ee[j]<0.05) continue; Int_t take1=1, take2=1; for (Int_t n=0; n<Trk_ntracks; n++) { unsigned int idx=Trk_id[n]; if (idx == Tt1_id[j]) { take1=Trk_prim_vtx[n]; continue; } if (idx == Tt2_id[j]) { take2=Trk_prim_vtx[n]; continue; } } //if ((take1==1)||(take2==1)) continue; list_k0[cand_k0]=j; cand_k0++; } //end k0 selection if (Trk_ntracks>295) cout<<Trk_ntracks<<endl; if (cand_k0<1) continue; nv0=cand_k0; if (nv0>75) cout<<nv0<<endl; Int_t id=0; //---- Tree filling -----// for(Int_t k=0;k<nv0;k++) { id=list_k0[k]; p1[k][0]=Tp1[id][0]; p1[k][1]=Tp1[id][1]; p1[k][2]=Tp1[id][2]; p2[k][0]=Tp2[id][0]; p2[k][1]=Tp2[id][1]; p2[k][2]=Tp2[id][2]; coll2[k]=Tsecvtx_collin2[id]; coll3[k]=Tsecvtx_collin3[id]; id1[k]=Tt1_id[id]; id2[k]=Tt2_id[id]; Int_t t1_prim=1, t2_prim=1, t1_sec=0, t2_sec=0, t1_vertex_id=-1, t2_vertex_id=-1; for (Int_t n=0; n<Trk_ntracks; n++) { unsigned int idx=Trk_id[n]; if (idx == Tt1_id[id]) { t1_prim=Trk_prim_vtx[n]; t1_sec=Trk_sec_vtx[n]; t1_vertex_id=Trk_vtx[n]; continue; } if (idx == Tt2_id[id]) { t2_prim=Trk_prim_vtx[n]; t2_sec=Trk_sec_vtx[n]; t2_vertex_id=Trk_vtx[n]; continue; } } is1_sec[k]=t1_sec; is2_sec[k]=t2_sec; is1_prim[k]=t1_prim; is2_prim[k]=t2_prim; Daughter temp1(Tp1[id][0],Tp1[id][1],Tp1[id][2]); Daughter temp2(Tp2[id][0],Tp2[id][1],Tp2[id][2]); Mother K0s_candtemp(temp1,temp2); Float_t ptemp1=temp1.GetP(); Float_t ptemp2=temp2.GetP(); Float_t mass_pi_ptemp=0; if (ptemp1>ptemp2) //first track proton(antiproton); second track pion_minus(pion_plus) { mass_pi_ptemp=K0s_candtemp.GetMass_m(6,4); } if (ptemp1<ptemp2) //first track pion_minus(pion_plus); first track proton(antiproton); { mass_pi_ptemp=K0s_candtemp.GetMass_m(4,6); } mass_lambda[k]=mass_pi_ptemp; mass_ee[k]=Tinvmass_ee[id]; layout1[k]=Tt1_layout[id]; layout2[k]=Tt2_layout[id]; layinn1[k]=Tt1_layinn[id]; layinn2[k]=Tt2_layinn[id]; } runnr=Runnr; if (Sincand>0) { q2el=Siq2el[0]; siprob=Siprob[0]; } if (Sincand==0) { q2el=0; siprob=0; } sincand=Sincand; //cout<<Sincand<<" "<<Siyel[0]<<" "<<Siyjb[0]<<endl; yel=Siyel[0]; yjb=Siyjb[0]; box_x=x_srtd; box_y=y_srtd; e_pz=EminPz_Evt; cal_et=Cal_et; /* // trigger defining for (int m=0;m<6;m++) { for (int k=0;k<16;k++) { fire = (Bool_t)(Tltw[m+6-1] & (1 << k) ); //tlt[m][k]=2; tlt[m][k]=0; if (fire) { tlt[m][k]=1; //cout<<m<<", bit"<<k+1<<" fired"<<endl; } } } */ xvtx=Xvtx; yvtx=Yvtx; zvtx=Zvtx; njet=Kt_njet_a; for (int jet=0;jet<njet;jet++) { etjet[jet]=Kt_etjet_a[jet]; etajet[jet]=Kt_etajet_a[jet]; phijet[jet]=Kt_phijet_a[jet]; } bool kshort=false, pi_plus=false, pi_minus=false, pi=false, f0980=false, daug_of_kshort=false; ntrue=0; for (int k=0;k<Fmck_nstor;k++) { // particle k identification kshort=false; pi_plus=false; pi_minus=false; f0980=false; daug_of_kshort=false; kshort=(Fmck_prt[k]==62); pi_plus=(Fmck_prt[k]==54); pi_minus=(Fmck_prt[k]==55); pi=(pi_plus||pi_minus); f0980=(Fmck_prt[k]==81); if (pi) { Int_t parent_fmckin=0; parent_fmckin=Fmck_daug[k]; // Fmckin id of mother of k //cout<<"Parent of pi+/pi-: "<<parent_fmckin<<endl; for (int jj=0;jj<Fmck_nstor;jj++) { //cout<<Fmck_id[jj]<<endl; if (Fmck_id[jj]!=parent_fmckin) continue; // skip if not of mother of k //cout<<Fmck_prt[jj]<<endl; // now jj is index of mother of particle k daug_of_kshort=(Fmck_prt[jj]==62); //cout<<"Parent of pi+/pi-: "<<parent_fmckin<<endl; break; } } if (f0980||kshort||((pi_plus||pi_minus)&&daug_of_kshort)) { fmcprt[ntrue]=Fmck_prt[k]; mass[ntrue]=Fmck_m[k]; daug_of[ntrue]=Fmck_daug[k]; fmckin_id[ntrue]=Fmck_id[k]; px[ntrue]=Fmck_px[k]; py[ntrue]=Fmck_py[k]; pz[ntrue]=Fmck_pz[k]; ntrue++; } } tree->Fill(); } //------- End of events loop ---------// tree->Print(); Int_t temp=sprintf(name,"batch31.root");//output TFile *f2 =new TFile(name,"recreate"); cout<<"File created"<<endl; tree->Write(); cout<<"Tree wrote"<<endl; f2->Close(); cout<<"File Closed"<<endl; delete tree; cout<<"Tree deleted, O.K.!"<<endl; cout<<ev_pass_DIS<<" events passed DIS selection"<<endl; cout<<with_V0<<" events with at least 1 V0"<<endl; cout<<"Done!!!"<<endl; } #ifndef __CINT__ int main(int argc, char **argv) { analysis(); return 0; } #endif
[ "libov@mail.desy.de" ]
libov@mail.desy.de
8e54a10cb095de2cef00e85b5e6f06f0394c7ac6
fb98e790b90cc475b53780f1e5fedd5eccfe8b56
/Hekateros/include/Hekateros/hekSysBoard.h
bb8ce9aacff3bcd4fe71ad6521635095cdd9117e
[ "MIT" ]
permissive
roadnarrows-robotics/rnr-sdk
e348dacd80907717bee4ad9c0a3c58b20fa380ae
be7b3e0806364cdb4602202aba2b4cdd9ba676f4
refs/heads/master
2023-08-16T06:52:31.580475
2023-08-03T19:45:33
2023-08-03T19:45:33
56,259,572
0
0
null
null
null
null
UTF-8
C++
false
false
5,750
h
//////////////////////////////////////////////////////////////////////////////// // // Package: Hekateros // // Library: libhekateros // // File: hekSysBoard.h // /*! \file * * $LastChangedDate: 2014-09-18 16:53:49 -0600 (Thu, 18 Sep 2014) $ * $Rev: 3748 $ * * \brief \h_hek original system board. * * \note The original system board is deprecated. However a newer version may * be resurected at a future time, so keep the code. * * \author Robin Knight (robin.knight@roadnarrows.com) * \author Daniel Packard (daniel@roadnarrows.com) * * \copyright * \h_copy 2013-2017. RoadNarrows LLC.\n * http://www.roadnarrows.com\n * All Rights Reserved */ /* * @EulaBegin@ * * Unless otherwise stated explicitly, all materials contained are copyrighted * and may not be used without RoadNarrows LLC's written consent, * except as provided in these terms and conditions or in the copyright * notice (documents and software) or other proprietary notice provided with * the relevant materials. * * IN NO EVENT SHALL THE AUTHOR, ROADNARROWS LLC, OR ANY * MEMBERS/EMPLOYEES/CONTRACTORS OF ROADNARROWS OR DISTRIBUTORS OF THIS SOFTWARE * BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS * DOCUMENTATION, EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE AUTHORS AND ROADNARROWS LLC SPECIFICALLY DISCLAIM ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN * "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * @EulaEnd@ */ //////////////////////////////////////////////////////////////////////////////// #ifndef _HEK_SYS_BOARD_H #define _HEK_SYS_BOARD_H #include <string> #include "rnr/rnrconfig.h" #include "rnr/log.h" #include "rnr/i2c.h" #include "Hekateros/hekateros.h" #include "Hekateros/hekOptical.h" namespace hekateros { class HekSysBoard { public: /*! * \brief Default constructor. */ HekSysBoard() { m_i2c.fd = -1; m_i2c.addr = 0; } /*! * \brief Destructor. */ virtual ~HekSysBoard() { close(); } /*! * \brief Open all interfaces monitoring hardware. * * \param dev \h_i2c device. * * \copydoc doc_return_std */ virtual int open(const std::string& dev=HekI2CDevice); /*! * \brief Close all interfaces to monitoring hardware. * * \copydoc doc_return_std */ virtual int close(); /*! * \brief Scan and initialize hardware. * * \copydoc doc_return_std */ virtual int scan(); /*! * \brief Command to read firmware version. * * param [out] ver Version number. * * \copydoc doc_return_std */ virtual int cmdReadFwVersion(int &ver); /*! * \brief Command to read limit bit state. * * \return Returns limit switches state as a bit packed byte. */ virtual byte_t cmdReadLimits(); /*! * \brief Command to read auxilliary bit state. * * Auxillary bits are usually End Effector GPIO, but allows room for * additional bits. * * \return Returns auxilliary switches state as a bit packed byte. */ virtual byte_t cmdReadAux(); /*! * \brief Command to read one I/O pin. * * \param id Pin identifier. * * \return Return pin state 0 or 1. */ virtual int cmdReadPin(int id); /*! * \brief Command to write value to an I/O pin. * * \param id Pin identifier. * \param val Pin state 0 or 1. * * \copydoc doc_return_std */ virtual int cmdWritePin(int id, int val); /*! * \brief Command to configure direction of an I/O pin. * * \param id Pin identifier. * \param dir Pin direction 'i' or 'o'. * * \copydoc doc_return_std */ virtual int cmdConfigPin(int id, char dir); /*! * \brief Command to set Alarm LED. * * \param val LED 0==off or 1==on value. * * \copydoc doc_return_std */ virtual int cmdSetAlarmLED(int val); /*! * \brief Command to set Status LED. * * \param val LED 0==off or 1==on value. * * \copydoc doc_return_std */ virtual int cmdSetStatusLED(int val); /*! * \brief Command to set monitoring state to halting. * * \copydoc doc_return_std */ virtual int cmdSetHaltingState(); protected: i2c_struct m_i2c; ///< i2c bus /*! * \brief Read I/O expander byte. * * \param byCmd I/O expander command. * * \return Byte value. */ byte_t readIOExp(byte_t byCmd); /*! * \brief Read I/O expander port 0. * * All optical limit switches are tied to port 0. * * \return Port 0 byte value. */ byte_t readIOExpPort0() { return readIOExp(HekIOExpCmdInput0); } /*! * \brief Read I/O expander port 1. * * All end effector i/o are tied to port 1. * * \return Port 1 byte value. */ byte_t readIOExpPort1() { return readIOExp(HekIOExpCmdInput1); } /*! * \brief Write byte to I/O expander. * * \param byCmd I/O expander command. * \param Byte value. * * \copydoc doc_return_std */ int writeIOExp(byte_t byCmd, byte_t byVal); }; } // namespace hekateros #endif // _HEK_SYS_BOARD_H
[ "robin.knight@roadnarrows.com" ]
robin.knight@roadnarrows.com