text
stringlengths
8
6.88M
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int main() { int n,k,ans = 0; scanf("%d",&n); for (int i = 0;i < n; i++) { scanf("%d",&k); ans ^= k; } if (!ans) printf("Bob\n"); else printf("Alice\n"); return 0; }
#include <stdio.h> #include <stdlib.h> #include <vector> #include <iostream> #include <math.h> using namespace std; int h1(int c, int m){ return c%m; } int h2(int c, int m){ int f = floor(c/m); if(c < m || f%m == 0){ return 1; } return f%m; } int doubleHashingInsertion(FILE *arquivo, string nomeDoArquivo){ int number,quantidade, index, deslocamento; cout << "Quantos numeros deseja adicionar?" << endl; cin >> quantidade; int v[quantidade]; for(int i = 0;i < quantidade; i++){ v[i] = 0; } //a+ goes to the end of file arquivo = fopen(nomeDoArquivo.c_str(),"a+"); for(int i = 0;i < quantidade; i++){ cout << "Digite um numero inteiro maior que 0:" << endl; cin >> number; if(v[h1(number,quantidade)] == 0) v[h1(number,quantidade)] = number; else{ index = h1(number,quantidade); deslocamento = h2(number,quantidade); if(index + deslocamento >= quantidade) index+=deslocamento - quantidade; else index+=deslocamento; while(v[index] != 0){ if(index + deslocamento >= quantidade){ index += deslocamento - quantidade; continue; } index+=deslocamento; } v[index] = number; } } for(int i = 0;i < quantidade; i++){ cout << v[i] << " "; } cout << endl; fwrite(v,sizeof(int),quantidade,arquivo); fclose(arquivo); return quantidade; } int countQuantity(FILE *arquivo, string nomeDoArquivo){ int quantidade = 0,v; //convert nomeDoArquivo to const char* with the function c_str() arquivo = fopen(nomeDoArquivo.c_str(),"r+"); if(arquivo == NULL) return -1; while(fread(&v,sizeof(int),1,arquivo) != 0){ quantidade++; } fclose(arquivo); return quantidade; } bool doubleHashingQuery(FILE *arquivo, string nomeDoArquivo){ int searchNumber,index,read,element,quantidade,deslocamento; quantidade = countQuantity(arquivo,nomeDoArquivo); cout << "Digite o elemento que deseja consultar" << endl; cin >> element; arquivo = fopen(nomeDoArquivo.c_str(),"r+"); if(arquivo == NULL){ cout << "erro na leitura do arquivo" << endl; return false; } index = h1(element,quantidade); deslocamento = h2(element,quantidade); fseek(arquivo,h1(element,quantidade)*sizeof(int),SEEK_SET); fread(&searchNumber,sizeof(int),1,arquivo); if(searchNumber == element){ cout << "O elemento " << element << " esta contido no vetor, no indice " << index << endl; return true; } if(index + deslocamento >= quantidade) index+=deslocamento - quantidade; else index+=deslocamento; fseek(arquivo,index*sizeof(int),SEEK_SET); fread(&searchNumber,sizeof(int),1,arquivo); while( index != h1(element,quantidade)){ if(searchNumber != element){ if(index + deslocamento >= quantidade){ index+=deslocamento - quantidade; fseek(arquivo,index*sizeof(int),SEEK_SET); fread(&searchNumber,sizeof(int),1,arquivo); continue; } index+=deslocamento; fseek(arquivo,index*sizeof(int),SEEK_SET); fread(&searchNumber,sizeof(int),1,arquivo); continue; } cout << "O elemento " << element << " esta contido no vetor, no indice " << index << endl; return true; } cout << "O elemento " << element << " nao esta contido no vetor" << endl; fclose(arquivo); return false; } int main(){ FILE *arquivo; int comando,quantidade, element,result; string nomeDoArquivo, enter; cout << "Digite o nome do arquivo a ser manipulado" << endl; getline(cin,nomeDoArquivo); cout << "comandos: " << endl; cout << "1 - Insercao" << endl; cout << "2 - Consulta" << endl; cout << "4 - Fechar programa" << endl; while(cin >> comando, comando != 4){ switch(comando){ case 1: quantidade = doubleHashingInsertion(arquivo,nomeDoArquivo); break; case 2: doubleHashingQuery(arquivo,nomeDoArquivo); break; } cout << "comandos: " << endl; cout << "1 - Insercao" << endl; cout << "2 - Consulta" << endl; cout << "4 - Fechar programa" << endl; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2009 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. ** It may not be distributed under any circumstances. ** ** Espen Sand */ #ifndef _UNIX_OPVIEW_H_ #define _UNIX_OPVIEW_H_ #include "modules/pi/OpView.h" class UnixOpView : public OpView { public: UnixOpView( bool is_x11 ) : m_is_x11(is_x11) { } bool isX11() const { return m_is_x11; } private: bool m_is_x11; }; #endif
// // Mail.cpp // // $Id: //poco/1.4/NetSSL_OpenSSL/samples/Mail/src/Mail.cpp#1 $ // // This sample demonstrates the MailMessage and SecureSMTPClientSession classes. // // Copyright (c) 2005-2011, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "_Net/MailMessage.h" #include "_Net/MailRecipient.h" #include "_Net/SecureSMTPClientSession.h" #include "_Net/StringPartSource.h" #include "_Net/SSLManager.h" #include "_Net/KeyConsoleHandler.h" #include "_Net/ConsoleCertificateHandler.h" #include "_/SharedPtr.h" #include "_/Path.h" #include "_/Exception.h" #include <iostream> using _Net::MailMessage; using _Net::MailRecipient; using _Net::SMTPClientSession; using _Net::SecureSMTPClientSession; using _Net::StringPartSource; using _Net::SSLManager; using _Net::Context; using _Net::KeyConsoleHandler; using _Net::PrivateKeyPassphraseHandler; using _Net::InvalidCertificateHandler; using _Net::ConsoleCertificateHandler; using _::SharedPtr; using _::Path; using _::Exception; class SSLInitializer { public: SSLInitializer() { _Net::initializeSSL(); } ~SSLInitializer() { _Net::uninitializeSSL(); } }; const unsigned char PocoLogo[] = { #include "_Logo.hpp" }; int main(int argc, char** argv) { SSLInitializer sslInitializer; if (argc < 4) { Path p(argv[0]); std::cerr << "usage: " << p.getBaseName() << " <mailhost> <sender> <recipient> [<username> <password>]" << std::endl; std::cerr << " Send an email greeting from <sender> to <recipient>," << std::endl; std::cerr << " using a secure connection to the SMTP server at <mailhost>." << std::endl; return 1; } std::string mailhost(argv[1]); std::string sender(argv[2]); std::string recipient(argv[3]); std::string username(argc >= 5 ? argv[4] : ""); std::string password(argc >= 6 ? argv[5] : ""); try { // Note: we must create the passphrase handler prior Context SharedPtr<InvalidCertificateHandler> pCert = new ConsoleCertificateHandler(false); // ask the user via console Context::Ptr pContext = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_RELAXED, 9, true, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); SSLManager::instance().initializeClient(0, pCert, pContext); MailMessage message; message.setSender(sender); message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, recipient)); message.setSubject("Hello from the POCO C++ Libraries"); std::string content; content += "Hello "; content += recipient; content += ",\r\n\r\n"; content += "This is a greeting from the POCO C++ Libraries.\r\n\r\n"; std::string logo(reinterpret_cast<const char*>(PocoLogo), sizeof(PocoLogo)); message.addContent(new StringPartSource(content)); message.addAttachment("logo", new StringPartSource(logo, "image/gif")); SecureSMTPClientSession session(mailhost); session.login(); session.startTLS(pContext); if (!username.empty()) { session.login(SMTPClientSession::AUTH_LOGIN, username, password); } session.sendMessage(message); session.close(); } catch (Exception& exc) { std::cerr << exc.displayText() << std::endl; return 1; } return 0; }
#include <iostream> #include <bs/ewma.hpp> #include <bs/frame_range.hpp> #include <bs/zivkovic_gmm.hpp> #include <bs/utils.hpp> #include <boost/make_shared.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <range/v3/front.hpp> #include <range/v3/action/take.hpp> #include <range/v3/view/take.hpp> #include <opencv2/highgui.hpp> using namespace cv; #include <options.hpp> #include <run.hpp> // // options_t::options_t is specific to each example: // options_t::options_t (int argc, char** argv) { { auto tmp = std::make_pair ( "program", po::variable_value (std::string (argv [0]), false)); map_.insert (tmp); } po::options_description generic ("Generic options"); po::options_description config ("Configuration options"); generic.add_options () ("version", "version") ("help", "this"); config.add_options () ("display,d", "display frames.") ("input,i", po::value< std::string > ()->default_value ("0"), "input (file or stream index).") ("size,s", po::value< size_t > ()->default_value (4UL), "maximum number of distributions.") ("alpha,a", po::value< double > ()->default_value (.005), "learning alpha.") ("threshold,t", po::value< double > ()->default_value (15.), "variance threshold for matching a distribution.") ("variance,v", po::value< double > ()->default_value (16.), "default variance for new distributions.") ("weight-threshold,w", po::value< double > ()->default_value (.7), "maximum weight (probability) for likely background distributions.") ("bias,b", po::value< double > ()->default_value (.01), "bias from the conjugate prior, see example in paper for picking one."); desc_ = boost::make_shared< po::options_description > (); desc_->add (generic); desc_->add (config); store (po::command_line_parser (argc, argv).options (*desc_).run (), map_); notify (map_); } //////////////////////////////////////////////////////////////////////// static void program_options_from (int& argc, char** argv) { bool complete_invocation = false; options_t program_options (argc, argv); if (program_options.have ("version")) { std::cout << "OpenCV v3.1\n"; complete_invocation = true; } if (program_options.have ("help")) { std::cout << program_options.description () << std::endl; complete_invocation = true; } if (complete_invocation) exit (0); global_options (program_options); } //////////////////////////////////////////////////////////////////////// static void process_zivkovic_gmm (cv::VideoCapture& cap, const options_t& opts) { const bool display = opts.have ("display"); bs::zivkovic_gmm_t zivkovic_gmm ( opts ["size"].as< size_t > (), opts ["alpha"].as< double > (), opts ["threshold"].as< double > (), opts ["variance"].as< double > (), opts ["weight-threshold"].as< double > (), opts ["bias"].as< double > ()); namedWindow ("Zivkovic GMM"); namedWindow ("Zivkovic GMM background"); moveWindow ("Zivkovic GMM", 0, 0); moveWindow ("Zivkovic GMM background", 512, 0); for (auto& frame : bs::getframes_from (cap)) { bs::frame_delay temp { 0 }; auto src = bs::resize_frame (frame, 512. / frame.cols); if (display) { imshow ("Zivkovic GMM", zivkovic_gmm (src)); imshow ("Zivkovic GMM background", zivkovic_gmm.background ()); } if (temp.wait_for_key (27)) break; } } //////////////////////////////////////////////////////////////////////// int main (int argc, char** argv) { program_options_from (argc, argv); return run_with (process_zivkovic_gmm, global_options ()), 0; }
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmFileTimeCache.h" #include <string> #include <unordered_map> #include <utility> cmFileTimeCache::cmFileTimeCache() = default; cmFileTimeCache::~cmFileTimeCache() = default; bool cmFileTimeCache::Load(std::string const& fileName, cmFileTime& fileTime) { // Use the stored time if available. { auto fit = this->Cache.find(fileName); if (fit != this->Cache.end()) { fileTime = fit->second; return true; } } // Read file time from OS if (!fileTime.Load(fileName)) { return false; } // Store file time in cache this->Cache[fileName] = fileTime; return true; } bool cmFileTimeCache::Remove(std::string const& fileName) { return (this->Cache.erase(fileName) != 0); } bool cmFileTimeCache::Compare(std::string const& f1, std::string const& f2, int* result) { // Get the modification time for each file. cmFileTime ft1; cmFileTime ft2; if (this->Load(f1, ft1) && this->Load(f2, ft2)) { // Compare the two modification times. *result = ft1.Compare(ft2); return true; } // No comparison available. Default to the same time. *result = 0; return false; } bool cmFileTimeCache::DifferS(std::string const& f1, std::string const& f2) { // Get the modification time for each file. cmFileTime ft1; cmFileTime ft2; if (this->Load(f1, ft1) && this->Load(f2, ft2)) { // Compare the two modification times. return ft1.DifferS(ft2); } // No comparison available. Default to different times. return true; }
#pragma once #include <Tanker/AttachResult.hpp> #include <Tanker/Network/SdkInfo.hpp> #include <Tanker/Opener.hpp> #include <Tanker/Session.hpp> #include <Tanker/Status.hpp> #include <Tanker/Streams/DecryptionStreamAdapter.hpp> #include <Tanker/Streams/EncryptionStream.hpp> #include <Tanker/Streams/InputSource.hpp> #include <Tanker/Trustchain/DeviceId.hpp> #include <Tanker/Types/Passphrase.hpp> #include <Tanker/Types/SGroupId.hpp> #include <Tanker/Types/SPublicIdentity.hpp> #include <Tanker/Types/SResourceId.hpp> #include <Tanker/Types/SSecretProvisionalIdentity.hpp> #include <Tanker/Types/SUserId.hpp> #include <Tanker/Types/VerificationCode.hpp> #include <Tanker/Types/VerificationKey.hpp> #include <Tanker/Unlock/Verification.hpp> #include <boost/variant2/variant.hpp> #include <gsl-lite.hpp> #include <tconcurrent/coroutine.hpp> #include <tconcurrent/task_auto_canceler.hpp> #include <cstdint> #include <memory> #include <string> #include <vector> namespace Tanker { class Core { public: using SessionClosedHandler = std::function<void()>; Core(std::string url, Network::SdkInfo infos, std::string writablePath); Tanker::Status status() const; tc::cotask<Status> start(std::string const& identity); tc::cotask<void> registerIdentity(Unlock::Verification const& verification); tc::cotask<void> verifyIdentity(Unlock::Verification const& verification); void stop(); tc::cotask<void> encrypt( uint8_t* encryptedData, gsl::span<uint8_t const> clearData, std::vector<SPublicIdentity> const& publicIdentities = {}, std::vector<SGroupId> const& groupIds = {}); tc::cotask<std::vector<uint8_t>> encrypt( gsl::span<uint8_t const> clearData, std::vector<SPublicIdentity> const& publicIdentities = {}, std::vector<SGroupId> const& groupIds = {}); tc::cotask<void> decrypt(uint8_t* decryptedData, gsl::span<uint8_t const> encryptedData); tc::cotask<std::vector<uint8_t>> decrypt( gsl::span<uint8_t const> encryptedData); tc::cotask<void> share(std::vector<SResourceId> const& resourceId, std::vector<SPublicIdentity> const& publicIdentities, std::vector<SGroupId> const& groupIds); tc::cotask<SGroupId> createGroup(std::vector<SPublicIdentity> const& members); tc::cotask<void> updateGroupMembers( SGroupId const& groupId, std::vector<SPublicIdentity> const& usersToAdd); tc::cotask<VerificationKey> generateVerificationKey(); tc::cotask<void> setVerificationMethod(Unlock::Verification const& method); tc::cotask<std::vector<Unlock::VerificationMethod>> getVerificationMethods(); tc::cotask<AttachResult> attachProvisionalIdentity( SSecretProvisionalIdentity const& sidentity); tc::cotask<void> verifyProvisionalIdentity( Unlock::Verification const& verification); Trustchain::DeviceId const& deviceId() const; tc::cotask<std::vector<Device>> getDeviceList() const; tc::cotask<void> syncTrustchain(); tc::cotask<void> revokeDevice(Trustchain::DeviceId const& deviceId); tc::cotask<Streams::EncryptionStream> makeEncryptionStream( Streams::InputSource, std::vector<SPublicIdentity> const& suserIds = {}, std::vector<SGroupId> const& sgroupIds = {}); tc::cotask<Streams::DecryptionStreamAdapter> makeDecryptionStream( Streams::InputSource); void setDeviceRevokedHandler(Session::DeviceRevokedHandler); void setSessionClosedHandler(SessionClosedHandler); static Trustchain::ResourceId getResourceId( gsl::span<uint8_t const> encryptedData); private: // We store the session as a unique_ptr so that open() does not // emplace<Session>. The Session constructor is asynchronous, so the user // could try to observe the variant state while it is emplacing. variant is // not reentrant so the observation would trigger undefined behavior. using SessionType = std::unique_ptr<Session>; std::string _url; Network::SdkInfo _info; std::string _writablePath; boost::variant2::variant<Opener, SessionType> _state; Session::DeviceRevokedHandler _deviceRevoked; SessionClosedHandler _sessionClosed; void reset(); void initSession(Session::Config openResult); template <typename F> decltype(std::declval<F>()()) resetOnFailure(F&& f); tc::cotask<Status> startImpl(std::string const& identity); }; }
#include <math.h> #include <chrono> #include <stdio.h> #include <tsc_x86.h> using namespace std; using namespace std::chrono; // timer cribbed from // https://gist.github.com/gongzhitaao/7062087 class Timer { public: Timer() : beg_(clock_::now()) {} void reset() { beg_ = clock_::now(); } double elapsed() const { return duration_cast<second_> (clock_::now() - beg_).count(); } private: typedef high_resolution_clock clock_; typedef duration<double, ratio<1>> second_; time_point<clock_> beg_; }; int main(char* argv) { double total; Timer tmr; init_tsc(); double cycles; myInt64 start, end; #define randf() ((double) 3.0* rand()) / ((double) (RAND_MAX)) #define OP_TEST(name, expr) \ total = 0.0; \ srand(42); \ cycles = 0.0; \ start = start_tsc() ; \ for (int i = 0; i < 100000000; i++) { \ double r1 = randf(); \ double r2 = randf(); \ total += expr; \ } \ end = stop_tsc(start); \ double name = (double) end ; \ \ printf(#name); \ printf(" %.7f\n", (name - baseline)/322519040.0000000); // time the baseline code: // for loop with no extra math op OP_TEST(baseline, 1.0) // time various floating point operations. // subtracts off the baseline time to give // a better approximation of the cost // for just the specified operation OP_TEST(plus, r1 + r2) OP_TEST(mult, r1 * r2) OP_TEST(div, r1 / r2) OP_TEST(sqrt, sqrt(r1)) OP_TEST(sin, sin(r1)) OP_TEST(cos, cos(r1)) OP_TEST(tan, tan(r1)) OP_TEST(atan2, atan2(r1,r2)) OP_TEST(exp, exp(r1)) OP_TEST(greater, r1 > r2) OP_TEST(greaterequal, r1 >= r2) OP_TEST(random, rand()) OP_TEST(abs, abs(r1)) OP_TEST(floor, floor(r2)) return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int a,b,c=0,t,i,j,co; char str[1005][100]; scanf("%d",&t); while(t--){ scanf("%d",&a); for(i=0;i<=a;i++){ scanf("%s",str[i]); } b=strlen(str[0]); printf("Case %d:\n",++c); for(j=0;j<a;j++){ co=0; for(i=0;i<b;i++){ if(str[j][i]!=str[a][i]){ co++; } } if(co<=1) printf("%s\n",str[j]); } } return 0; }
#pragma once #include <list> #include "Logs.h" #include "InitPath.h" #include "GetFileInfo.h" using namespace std; class CKievPost { public: CKievPost(void); virtual ~CKievPost(void); // Перемещение файлов в папку отправки на Киев list<CString> SendPostToKiev(); private: CInitPath *pPath; CLogs *pLog; CGetFileInfo *pFileInfo; //Файл был перемещён в папку Ошибки bool bErrorDirMove; // Владелец файла char szFileOwner[1024]; char szDomainName[1024]; //Пути к папкам //откуда забрать CString strSrcFile; //куда положить CString strDstFile; // Список файлов в папке на отправку list<CString> vFileName; list<CString>::iterator itFileName; // Проверка на правильность имени файла для отправки bool VerifyFileName(char* strFileName); // Получаем список файлов подготовленных на отправку в Киев из ГНС в Запорожской области void GetNameFileMailFromFolder(char* pFolderPath); // Полный путь к файлу отправки исходное положение CString m_strSrcFolder; // Полный путь к файлу отправки конечное положение CString m_strDstFolder; // Создание директории для конкретного управления, с текущим месяцем и днём bool CreateArcDir(char* szFileName, char *szDestination); // Копирование файла в архив ОГНС и на отправку bool CopyFileToDirectory(char* szFileName, char* szDstFullPath, char* szDirPah); // Перемещение файла в папку Ошибки для района, без отправки на Киев bool MoveFileToErrorDirectoty(char *szFileName); };
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int a; std::cin >> a; switch (a) { case a>10:std::cout << "greater" << '\n'; break; case a<10:std::cout << "less" << '\n'; break; default: std::cout << "equal" << '\n'; } return 0; }
#ifndef _SIMULATOR_H_ #define _SIMULATOR_H_ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <assert.h> #include <random> #include <map> #include <vector> #include "NanoTimer.h" #include "Model.h" #include "ModelWF.h" #include "Event.h" #include "EventList.h" #include "Population.h" #include "Profile.h" #include "Pool.h" using namespace std; class Simulator{ private: unsigned int sim_id; Model *model; EventList *events; Profile *profile; Pool *pool; map<string, Population*> populations; mt19937 generator; public: Simulator(); Simulator(const Simulator &original); Simulator& operator=(const Simulator& original); virtual Simulator *clone(); virtual ~Simulator(); Model *getModel() const; EventList *getEvents() const; Profile *getProfile() const; Pool *getPool() const; // Notar que la lista de nombres de poblacion la retorno POR COPIA vector<string> getPopulationNames() const; Population *getPopulation(const string &name) const; void setModel(Model *_model); void setEvents(EventList *_events); void setProfile(Profile *_profile); void setId(unsigned int _sim_id){ sim_id = _sim_id; } unsigned int getId() const{ return sim_id; } void run(); void executeEvent(Event *event); // Metodo de debug void print(){ cout << "-----\n"; cout << "Simulator::print - Inicio\n"; if(model == NULL){ cout << "Simulator::print - Model NULL\n"; } else{ model->print(); } if(events == NULL){ cout << "Simulator::print - EventList NULL\n"; } else{ events->print(); } if(profile == NULL){ cout << "Simulator::print - Profile NULL\n"; } else{ profile->print(); } if(pool == NULL){ cout << "Simulator::print - Pool NULL\n"; } else{ pool->print(); } cout << "Simulator::print - Populations: " << populations.size() << "\n"; for(auto it : populations){ cout << "Simulator::print - (" << it.first << ", " << it.second->size() << " individuos)\n"; } cout << "Simulator::print - Fin\n"; cout << "-----\n"; } char *serialize(){ // return NULL; // int para el mismo n_bytes, y otro para el id unsigned int n_bytes = sizeof(int) * 2; n_bytes += model->serializedSize(); n_bytes += events->serializedSize(); n_bytes += profile->serializedSize(); // cout<<"Simulator::serialize - Preparando buffer de " << n_bytes << " bytes\n"; char *buff = new char[n_bytes]; unsigned int pos = 0; memcpy(buff + pos, (char*)&n_bytes, sizeof(int)); pos += sizeof(int); memcpy(buff + pos, (char*)&sim_id, sizeof(int)); pos += sizeof(int); // Notar que model es polimorfico // Quizas esto deberia hacerlo un factory model->serialize(buff + pos); pos += model->serializedSize(); events->serialize(buff + pos); pos += events->serializedSize(); profile->serialize(buff + pos); pos += profile->serializedSize(); return buff; } unsigned int loadSerialized(char *buff){ // cout<<"Simulator::loadSerialized - Inicio\n"; if( buff == NULL ){ return 0; } char *buff_original = buff; // Esto de hecho no es necesario, pero podria usarse para verificacion unsigned int n_bytes = 0; memcpy((char*)&n_bytes, buff, sizeof(int)); buff += sizeof(int); // cout<<"Simulator::loadSerialized - n_bytes: " << n_bytes << "\n"; sim_id = 0; memcpy((char*)&sim_id, buff, sizeof(int)); buff += sizeof(int); // Notar este constructor medio fuera de lugar // Esto deberia hacerlo un factory, quizas todo este metodo deberia estar en SimulatorFactory Model *model = new ModelWF(); buff += model->loadSerialized(buff); setModel(model); EventList *events = new EventList(); buff += events->loadSerialized(buff); setEvents(events); Profile *profile = new Profile(); buff += profile->loadSerialized(buff); setProfile(profile); // cout<<"Simulator::loadSerialized - Fin (bytes usados: " << (buff - buff_original) << ")\n"; return (buff - buff_original); } }; #endif
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 2004-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Morten Stenshorne */ #include "core/pch.h" #include "uastring.h" #include <sys/utsname.h> OP_STATUS GetUnixUaWindowingSystem(OpString8 &winsys) { #if defined(_X11_) RETURN_IF_ERROR(winsys.Append("X11")); #endif return OpStatus::OK; } OP_STATUS GetUnixUaScreenSize(OpString8 &uastring) { return OpStatus::OK; } OP_STATUS GetUnixUaSystemString(OpString8 &uastring) { uastring.Empty(); struct utsname buf; if (uname(&buf) == 0) { #ifdef UA_INCLUDE_WINDOWSYS RETURN_IF_ERROR(GetUnixUaWindowingSystem(uastring)); RETURN_IF_ERROR(uastring.Append("; ")); #endif // UA_INCLUDE_WINDOWSYS RETURN_IF_ERROR(uastring.Append(buf.sysname)); #ifdef UA_INCLUDE_ARCHITECTURE RETURN_IF_ERROR(uastring.Append(" ")); RETURN_IF_ERROR(uastring.Append(buf.machine)); #endif // UA_INCLUDE_ARCHITECTURE #ifdef UA_INCLUDE_DEVICENAME RETURN_IF_ERROR(uastring.Append("; ")); RETURN_IF_ERROR(GetUnixUaPrettyDeviceName(uastring)); #endif // OPERA_DEVICENAME #ifdef UA_INCLUDE_BUILDNUMBER RETURN_IF_ERROR(uastring.Append("; ")); RETURN_IF_ERROR(uastring.Append(BROWSER_BUILD_NUMBER)); #endif // UA_INCLUDE_BUILDNUMBER #ifdef UA_INCLUDE_SCREENSIZE RETURN_IF_ERROR(uastring.Append("; ")); RETURN_IF_ERROR(GetUnixUaScreenSize(uastring)); #endif // UA_INCLUDE_SCREENSIZE } if (uastring.IsEmpty()) { perror("uname"); RETURN_IF_ERROR(uastring.Set("UNIX")); } return OpStatus::OK; } OP_STATUS GetUnixUaDeviceInfo(OpString8 &uastring) { return OpStatus::OK; } #ifdef CUSTOM_UASTRING_SUPPORT OP_STATUS GetUnixUaPrettyDeviceName(OpString8 &uastring) { return OpStatus::OK; } #endif // CUSTOM_UASTRING_SUPPORT #ifdef CUSTOM_UASTRING_SUPPORT OP_STATUS GetUnixUaOSName(OpString8 &uastring) { struct utsname buf; if (uname(&buf) != 0) return OpStatus::ERR; return uastring.Append(buf.sysname); } OP_STATUS GetUnixUaOSVersion(OpString8 &uastring) { struct utsname buf; if (uname(&buf) != 0) return OpStatus::ERR; return uastring.Append(buf.release); } OP_STATUS GetUnixUaMachineArchitecture(OpString8 &uastring) { struct utsname buf; if (uname(&buf) != 0) return OpStatus::ERR; return uastring.Append(buf.machine); } OP_STATUS GetUnixUaDeviceIdentifier(OpString8 &uastring) { return OpStatus::OK; } OP_STATUS GetUnixUaDeviceSoftwareVersion(OpString8 &uastring) { return OpStatus::OK; } #endif // CUSTOM_UASTRING_SUPPORT
#ifndef __IREPORTEDITORVIEW_H #define __IREPORTEDITORVIEW_H //----------------------------------------------------------------------------- #include "_pch.h" #include "ReportData.h" namespace wh{ //----------------------------------------------------------------------------- class IReportEditorView { public: virtual void SetReportItem(const rec::ReportItem&) = 0; sig::signal<void(const rec::ReportItem&)> sigChItem; virtual void Show()=0; virtual void Close() = 0; }; //----------------------------------------------------------------------------- }//namespace wh{ #endif // __****_H
#define BOOST_TEST_LOG_LEVEL test_suite #define BOOST_TEST_MODULE test_main #include <boost/test/unit_test.hpp> #include <boost/mpl/assert.hpp> #include "Handler.h" #include "Writers.h" using Commands = std::vector<std::string>; BOOST_AUTO_TEST_SUITE(test_bulk) BOOST_AUTO_TEST_CASE(example) { std::stringbuf out_buffer; std::ostream out_stream(&out_buffer); auto handler = std::make_shared<Handler>(3); auto consoleWriter = std::shared_ptr<ConsoleWriter>(new ConsoleWriter(out_stream)); auto fileWriter = std::shared_ptr<FileWriter>(new FileWriter()); consoleWriter->subscribe(handler); fileWriter->subscribe(handler); handler->addCommand("cmd1"); handler->addCommand("cmd2"); handler->addCommand("cmd3"); std::ifstream file{fileWriter->getName()}; std::stringstream string_stream; string_stream << file.rdbuf(); file.close(); std::remove(fileWriter->getName().c_str()); BOOST_CHECK_EQUAL(out_buffer.str(),"bulk: cmd1, cmd2, cmd3\n"); BOOST_CHECK_EQUAL(string_stream.str(),"bulk: cmd1, cmd2, cmd3"); out_buffer.str(""); string_stream.str(""); handler->addCommand("cmd4"); handler->addCommand("cmd5"); handler->stop(); file.open(fileWriter->getName()); string_stream << file.rdbuf(); file.close(); std::remove(fileWriter->getName().c_str()); BOOST_CHECK_EQUAL(out_buffer.str(),"bulk: cmd4, cmd5\n"); BOOST_CHECK_EQUAL(string_stream.str(),"bulk: cmd4, cmd5"); } BOOST_AUTO_TEST_SUITE_END()
// Created on: 1995-12-01 // Created by: EXPRESS->CDL V0.2 Translator // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepAP214_AutoDesignDateAndPersonAssignment_HeaderFile #define _StepAP214_AutoDesignDateAndPersonAssignment_HeaderFile #include <Standard.hxx> #include <StepAP214_HArray1OfAutoDesignDateAndPersonItem.hxx> #include <StepBasic_PersonAndOrganizationAssignment.hxx> #include <Standard_Integer.hxx> class StepBasic_PersonAndOrganization; class StepBasic_PersonAndOrganizationRole; class StepAP214_AutoDesignDateAndPersonItem; class StepAP214_AutoDesignDateAndPersonAssignment; DEFINE_STANDARD_HANDLE(StepAP214_AutoDesignDateAndPersonAssignment, StepBasic_PersonAndOrganizationAssignment) class StepAP214_AutoDesignDateAndPersonAssignment : public StepBasic_PersonAndOrganizationAssignment { public: //! Returns a AutoDesignDateAndPersonAssignment Standard_EXPORT StepAP214_AutoDesignDateAndPersonAssignment(); Standard_EXPORT void Init (const Handle(StepBasic_PersonAndOrganization)& aAssignedPersonAndOrganization, const Handle(StepBasic_PersonAndOrganizationRole)& aRole, const Handle(StepAP214_HArray1OfAutoDesignDateAndPersonItem)& aItems); Standard_EXPORT void SetItems (const Handle(StepAP214_HArray1OfAutoDesignDateAndPersonItem)& aItems); Standard_EXPORT Handle(StepAP214_HArray1OfAutoDesignDateAndPersonItem) Items() const; Standard_EXPORT StepAP214_AutoDesignDateAndPersonItem ItemsValue (const Standard_Integer num) const; Standard_EXPORT Standard_Integer NbItems() const; DEFINE_STANDARD_RTTIEXT(StepAP214_AutoDesignDateAndPersonAssignment,StepBasic_PersonAndOrganizationAssignment) protected: private: Handle(StepAP214_HArray1OfAutoDesignDateAndPersonItem) items; }; #endif // _StepAP214_AutoDesignDateAndPersonAssignment_HeaderFile
#include "StdAfx.h" #include "Boon.h" #include "../Bullet/BulletManager.h" const float MOVE_SPEED = 500.0f; Boon::Boon() { } Boon::~Boon() { delete anime; delete bulletAnime; } void Boon::Init() { anime = new Anime("data/boon/boon.xml"); bulletAnime = new Anime("data/boon/bullet.xml"); } void Boon::Move() { } void Boon::Draw() { if (life <= 0) { return; } // ’e˜AŽË if (DirectXLib::GetInstance()->IsKeyDown(DIK_X)) { static DWORD time = timeGetTime(); // 100ms˜A‘Å if ((timeGetTime() - time) > 100) { // ’e”­ŽË BulletManager::GetInstance()->ShootBullet(OBJECT_BULLET_STANDARD, static_cast<float>(posX + 130), static_cast<float>(posY), 0); PlaySound("data/se/tm2_shoot001.wav", NULL, SND_FILENAME | SND_ASYNC); time = timeGetTime(); } } // ’e˜AŽË if (DirectXLib::GetInstance()->IsKeyDown(DIK_Z)) { static DWORD time = timeGetTime(); // 100ms˜A‘Å if ((timeGetTime() - time) > 100) { // ’e”­ŽË BulletManager::GetInstance()->ShootBullet(OBJECT_BULLET_MISSILE, static_cast<float>(posX + 130), static_cast<float>(posY), 0); PlaySound("data/se/tm2_sonic002.wav", NULL, SND_FILENAME | SND_ASYNC); time = timeGetTime(); } } // Ž©“®‰EƒXƒNƒ[ƒ‹(•bŠÔ100dot) posX += DirectXLib::GetInstance()->GetMove(100); // ¶‰EˆÚ“® if (DirectXLib::GetInstance()->IsKeyDown(DIK_LEFT)) { posX -= DirectXLib::GetInstance()->GetMove(MOVE_SPEED); } else if (DirectXLib::GetInstance()->IsKeyDown(DIK_RIGHT)) { posX += DirectXLib::GetInstance()->GetMove(MOVE_SPEED); } // ã‰ºˆÚ“® if (DirectXLib::GetInstance()->IsKeyDown(DIK_UP)) { posY -= DirectXLib::GetInstance()->GetMove(MOVE_SPEED); } else if (DirectXLib::GetInstance()->IsKeyDown(DIK_DOWN)) { posY += DirectXLib::GetInstance()->GetMove(MOVE_SPEED); } // Ž©‹@•`‰æ D3DXVECTOR2 pos = GetClientPos(); anime->Draw(pos.x, pos.y); }
#include "Composite.h" Composite::Composite() { } Composite::~Composite() { } void Composite::Operation() { std::vector<CompositeComponent*>::iterator comIter = comVec.begin(); for (; comIter != comVec.end(); ++comIter) { (*comIter)->Operation(); } } void Composite::Add(CompositeComponent *com) { comVec.push_back(com); } void Composite::Remove(CompositeComponent *com) { //comVec.erase(com); } CompositeComponent * Composite::GetChild(int index) { return comVec[index]; }
#include <avr/pgmspace.h> PROGMEM const char pumianFlash[] = "111100111100," "111100111222," "111100111100," "111100221221," "111100111100," "111100111222," "111100111100," "111100221212," "211121212121," "212212212121," "000000000000," "2010201020110020," "2020201020201120," "2010201020110020," "2020102020101120," "2010201020101020," "2010102010121222," "1020102010222020," "1020112121201122," "1020102010221120," "1020102010221220," "1020102011221122," "1020102010222222," "1020102010221120," "1020102010221220," "1020102011221122," "1020102010222222," "1020102010201022," "1111222211112222," "1122112212222222," "1000100000101222," "1010100020202000," "1010100020102012," "1010100020202000," "1010100012221222," "1010100020202000," "1010100021212122," "1010100020202000," "1010100012221122," "2020101020201010," "2222111122221111," "2211221122221111," "1000000020000000," "1000202020002000," "1000100020001000," "1000202020002000," "1000000020000000," "1000202020002000," "1000100020001000," "2020102020002000," "1000100020001000," "1000202020002000," "2010101020202020," "2010101020201010," "2020202020202020," "1010202010102020," "1010202010202020," "1010202010102020," "1212121210202020," "1010202010102020," "1010202010202020," "1020201020101020," "1020102021022122," "1010202010102020," "1010202010202020," "1010202010102020," "1212121210202020," "1010202010102020," "1010202010202020," "1020201020101020," "1020102021022122," "1022222222222222," "1111111111111111," "2222222211111111," "2222222211111111," "2222111122221111," "2121212121212121," "2010201020201020," "2010201020102020," "2010201020201020," "2010211101112120," "2010201020201020," "2010201010201020," "2020102010201020," "2020112201211120," "2020102010201020," "1010202020102010," "2020102010201020," "1010211101112120," "2010201020201020," "1020102010202010," "2010202010201020," "111122112020202022102210," "1120221022102212," "2122121210001000," "1000100010002020," "1000102010001020," "1121212110001211," "2112100021112111," "2112112112112112," "1212121212121212," "1000100000300000," "2000200000400000," "1000100000300000," "2000200000400000," "1000100000300000," "2000200000400000," "1000100000300000," "2020102020102222," "2020101020201010," "2020101020101020," "2020101020201010," "2020101012222222," "2020101020201010," "2020101020102010," "2020101020201010," "2020101022221122," "2020101020010102," "1022201020201022," "1111111122222222," "1010202010201010," "1020101020101010," "2020102010201010," "2010102010102010," "2010102010102010," "1020102010201020," "1020100020101020," "1000201010002010," "1000211110201020," "1020102010201021," "1110201010201020," "1010201010222222," "1010300000101030," "0010101021212121," "1010300000100030," "2020202010222222," "1010300000101030," "0010101021212121," "1010300000100030," "1111112121212121," "5," "000000000000000000000000000000000000000000000008,"; int Left_blue = 2; int Left_red = 3; int Right_red = 8; int Right_blue = 9; int button = 0; void setup(){ Serial.begin(9600); pinMode(button, INPUT); pinMode(Left_red, OUTPUT); pinMode(Right_red, OUTPUT); pinMode(Left_blue, OUTPUT); pinMode(Right_blue, OUTPUT); } void loop(){ if(digitalRead(button) == LOW){ int total = 2580; //总note数+乐段数 int bpm = 160; //初始BPM int shaky = 5; //按键从按下到抬起的时间 int pai = 60000/bpm; //计算延迟时间 float measure = 3; //初始拍子 int bar_place[] = {11,92,93}; //改变节奏bar的位置 int CM_data[] = {4,4,4}; //改变的节拍 int CBPM_data[] = {300,300,300}; //改变的BPM int change = -1; float T_measure = 1/measure; float bpm_speed = pai*T_measure; bpm_speed = bpm_speed - shaky; int i = 0; //初始化i的值 int state = 0; //左右交替状态 int yellow = 0; int p = 0; //变速位置 int bar = 0; while (i<=total-1){ char pumian = pgm_read_byte(&pumianFlash[i]);//flash读取谱面信息 if(bar==bar_place[p]){ bpm = CBPM_data[p]; //改变BPM pai = 60000/bpm; //计算延迟时间 measure = CM_data[p]; T_measure = 1/measure; bpm_speed = pai*T_measure; bpm_speed = bpm_speed - shaky; p++; Serial.println(bpm_speed); Serial.println(pumian); } if(pumian=='0'&&yellow==0){ i++; delay (bpm_speed+shaky+change); } else if(pumian=='1'){ //咚 if(state==0){ i++; digitalWrite(Left_red,HIGH); delay(shaky); digitalWrite(Left_red,LOW); delay (bpm_speed); state = 1; } else{ i++; digitalWrite(Right_red,HIGH); delay(shaky); digitalWrite(Right_red,LOW); delay (bpm_speed); state = 0; } } else if(pumian=='2'){ //咔 if(state==0){ i++; digitalWrite(Left_blue,HIGH); delay(shaky); digitalWrite(Left_blue,LOW); delay (bpm_speed); state = 1; } else{ i++; digitalWrite(Right_blue,HIGH); delay(shaky); digitalWrite(Right_blue,LOW); delay (bpm_speed); state = 0; } } else if(pumian=='3'){ //大咚 i++; digitalWrite(Left_red,HIGH); digitalWrite(Right_red,HIGH); delay(shaky); digitalWrite(Left_red,LOW); digitalWrite(Right_red,LOW); delay (bpm_speed); } else if(pumian=='4'){ //大咔 i++; digitalWrite(Left_blue,HIGH); digitalWrite(Right_blue,HIGH); delay(shaky); digitalWrite(Left_blue,LOW); digitalWrite(Right_blue,LOW); delay (bpm_speed); } else if(pumian=='8'){ yellow = 0; delay (yellow); } else if(pumian=='5'||pumian=='6'||pumian=='7'||yellow==1){ //连打 i++; digitalWrite(Left_blue,HIGH); digitalWrite(Right_blue,HIGH); digitalWrite(Left_red,HIGH); digitalWrite(Right_red,HIGH); delay(shaky); digitalWrite(Left_blue,LOW); digitalWrite(Right_blue,LOW); digitalWrite(Left_red,LOW); digitalWrite(Right_red,LOW); delay (bpm_speed); yellow = 1; delay (yellow); } else if(pumian==','){ i++; bar++; } else { i++; delay (bpm_speed + shaky + change); } } } }
#include <uWS/uWS.h> using namespace uWS; int main() { Hub h; std::string response = "Hello!"; h.onMessage([](WebSocket<SERVER> *ws, char *message, size_t length, OpCode opCode) { ws->send(message, length, opCode); }); h.onHttpRequest([&](HttpResponse *res, HttpRequest req, char *data, size_t length, size_t remainingBytes) { res->end(response.data(), response.length()); }); if (h.listen(3000)) { h.run(); } }
/*! @file LogVol_PCBs.hh @brief Defines mandatory user class LogVol_PCBs_Box. @date August, 2015 @author Flechas (D. C. Flechas dcflechasg@unal.edu.co) @version 2.0 In this header file, the 'physical' setup is defined: materials, geometries and positions. This class defines the experimental hall used in the toolkit. */ /* no-geant4 classes*/ #include "LogVol_PCBs_Box.hh" /* units and constants */ #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" /* geometric objects */ #include "G4Box.hh" #include "G4Tubs.hh" #include "G4Polycone.hh" #include "G4UnionSolid.hh" /* logic and physical volume */ #include "G4LogicalVolume.hh" /* geant4 materials */ #include "G4NistManager.hh" #include "G4Material.hh" /* visualization */ #include "G4VisAttributes.hh" LogVol_PCBs_Box:: LogVol_PCBs_Box(G4String fname, G4double fwidth, G4double flen, G4double fthick): G4LogicalVolume(new G4Box("PCBs_Box_solid",10*mm, 10*mm, 10*mm),(G4NistManager::Instance())->FindOrBuildMaterial("G4_BAKELITE"),fname,0,0,0) { /* set variables */ SetName(fname); SetWidth(fwidth); SetLength(flen); SetThickness(fthick); Material=(G4NistManager::Instance())->FindOrBuildMaterial("G4_BAKELITE"); /* Construct solid volume */ ConstructSolidVol_PCBs_Box(); /* Visualization */ G4VisAttributes* back_vis = new G4VisAttributes(true,G4Colour(0.1,0.9,0.1)); back_vis->SetForceWireframe(false); back_vis->SetForceSolid(false); this->SetVisAttributes(back_vis); } LogVol_PCBs_Box::~LogVol_PCBs_Box() {} void LogVol_PCBs_Box::ConstructSolidVol_PCBs_Box(void) { //!*** PCB from the electronics ***!// G4Box* solid_pcb_box; solid_pcb_box = new G4Box(Name+"pcb_box_Sol",Width/2.0,Width/2.0,Thickness/2.0); G4UnionSolid* solid_sec1; solid_sec1 = new G4UnionSolid(Name+"_pcb_sec1_Sol",solid_pcb_box,solid_pcb_box,0,G4ThreeVector(0.,0.,(Length-3*Thickness)/2.0+Thickness)); PCBs_Box_solid = new G4UnionSolid(Name+"_pcb_Sol",solid_sec1,solid_pcb_box,0,G4ThreeVector(0.,0.,Length-Thickness)); /*** Main trick here: Set the new solid volume ***/ SetSolidVol_PCBs_Box(); } void LogVol_PCBs_Box::SetSolidVol_PCBs_Box(void) { /*** Main trick here: Set the new solid volume ***/ if(PCBs_Box_solid) this->SetSolid(PCBs_Box_solid); }
#include "robot.h" namespace sge { namespace entity{ Robot::Robot(graphics::Sprite *sprite): GameObject(sprite){ init(); } void Robot::init(){ //GameObject::init(); //WALKING_LEFT m_Animation.push_back(graphics::Animation(0, false)); //WALKING_up m_Animation.push_back(graphics::Animation(1, false)); //walking_RIGHT m_Animation.push_back(graphics::Animation(2, false)); //WALKING_DOWN m_Animation.push_back(graphics::Animation(3, false)); m_State = State::IDLE; m_Sprite->setUV(m_Animation[2].getNextFrameUV()); } void Robot::onUpdate(){ GameObject::onUpdate(); if(active){ if(App::getApplication().window->getInputManager()->isKeyPressed(GLFW_KEY_RIGHT)){ m_Speed.x = 5.0f; m_Sprite->setUV(m_Animation[2].getNextFrameUV()); }else if(App::getApplication().window->getInputManager()->isKeyPressed(GLFW_KEY_LEFT)){ m_Speed.x = -5.0f; m_Sprite->setUV(m_Animation[0].getNextFrameUV()); }else{ m_Speed.x = 0.0f; } if(App::getApplication().window->getInputManager()->isKeyPressed(GLFW_KEY_UP)){ m_Speed.y = 5.0f; m_Sprite->setUV(m_Animation[1].getNextFrameUV()); }else if(App::getApplication().window->getInputManager()->isKeyPressed(GLFW_KEY_DOWN)){ m_Speed.y = -5.0f; m_Sprite->setUV(m_Animation[3].getNextFrameUV()); }else{ m_Speed.y = 0.0f; } } } void Robot::onEvent(events::Event& event) { events::EventDispatcher dispatcher(event); dispatcher.dispatch<events::KeyPressedEvent>([this](events::KeyPressedEvent& e) { return onKeyPressed(e); }); dispatcher.dispatch<events::KeyReleasedEvent>([this](events::KeyReleasedEvent& e) { return onKeyReleased(e); }); } bool Robot::onKeyPressed(events::KeyPressedEvent& e) { int key = (int)e.getKeyCode(); bool handled = false; if(active){ switch(key){ case GLFW_KEY_UP:{ m_State = State::WALKING_UP; handled = true; break; }case GLFW_KEY_DOWN:{ m_State = State::WALKING_DOWN; handled = true; break; }case GLFW_KEY_LEFT:{ m_State = State::WALKING_LEFT; handled = true; break; }case GLFW_KEY_RIGHT:{ m_State = State::WALKING_RIGHT; handled = true; break; } } } return handled; } bool Robot::onKeyReleased(events::KeyReleasedEvent& e) { int key = e.getKeyCode(); m_State = State::IDLE; return true; } } }
// Login.cpp : 实现文件 // #include "stdafx.h" #include "Talk2Me.h" #include "Login.h" #include "afxdialogex.h" // CLogin 对话框 IMPLEMENT_DYNAMIC(CLogin, CDialogEx) CLogin::CLogin(CWnd* pParent /*=NULL*/) : CDialogEx(CLogin::IDD, pParent) , m_pwd(_T("")) , m_userid(0) { } CLogin::~CLogin() { } void CLogin::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_PWD_EDIT, m_pwd); DDX_Text(pDX, IDC_USERNAME_EDIT, m_userid); } BEGIN_MESSAGE_MAP(CLogin, CDialogEx) ON_BN_CLICKED(IDOK, &CLogin::OnBnClickedOk) END_MESSAGE_MAP() // CLogin 消息处理程序 void CLogin::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 UpdateData(true); CDialogEx::OnOK(); }
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/BottomBar.g.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.Controls.Grid.h> #include <Fuse.Drawing.ISurfaceDrawable.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.ITemplateSource.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.ICollapse.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Fuse.Visual.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.UX.IPropertyListener.h> namespace g{namespace Fuse{namespace Reactive{struct EventBinding;}}} namespace g{struct BottomBar;} namespace g{ // public partial sealed class BottomBar :2 // { ::g::Fuse::Controls::Panel_type* BottomBar_typeof(); void BottomBar__ctor_8_fn(BottomBar* __this); void BottomBar__InitializeUX_fn(BottomBar* __this); void BottomBar__New5_fn(BottomBar** __retval); struct BottomBar : ::g::Fuse::Controls::Grid { uStrong< ::g::Fuse::Reactive::EventBinding*> temp_eb2; uStrong< ::g::Fuse::Reactive::EventBinding*> temp_eb3; uStrong< ::g::Fuse::Reactive::EventBinding*> temp_eb4; uStrong< ::g::Fuse::Reactive::EventBinding*> temp_eb5; void ctor_8(); void InitializeUX(); static BottomBar* New5(); }; // } } // ::g
#include "stdafx.h" #include "OutputListener.h" #include "Console.h" #include "NetworkLogic.h" Console::Console() { } Console::~Console() { } void Console::update() { } void Console::write(const ExitGames::Common::JString& str) { mpImp->write(str); } void Console::writeLine(const ExitGames::Common::JString& str) { mpImp->writeLine(str); } Console& Console::get(void) { static Console console; return console; }
/* UpdateThread.h Header file for class UpdateThread @author Martin Terneborg */ #ifndef UPDATE_THREAD_H #define UPDATE_THREAD_H #include "Thread.h" #include <Windows.h> #include <vector> #include <memory> #include "Settings.h" #include "MonitorThread.h" /* Class represnting a thread used by the main window to handle updates. */ class UpdateThread : public Thread { private: CONST HWND m_hWnd; CONST Settings &m_rSettings; std::vector<MonitorThread> m_monitorThreads; std::unique_ptr<RGBQUAD[]> m_outputValues; CONST HANDLE m_hMutexSettings; BOOL m_stopped; VOID Run(); public: UpdateThread(CONST HWND hWndMain, CONST Settings &pSettings, CONST HANDLE hMutexSettings); VOID Stop(); }; #endif
class M110_NVG_EP1; class M110_NV_DZ: M110_NVG_EP1 { displayName = $STR_DZ_WPN_M110_NV_NAME; descriptionShort = $STR_DZ_WPN_M110_NV_DESC; class OpticsModes { class HTWS { opticsID = 1; useModelOptics = "true"; opticsZoomMin = 0.0293; distanceZoomMin = 300; opticsZoomMax = 0.0293; distanceZoomMax = 300; opticsZoomInit = 0.0293; memoryPointCamera = "eye"; opticsFlare = "true"; opticsDisablePeripherialVision = "true"; cameraDir = ""; opticsPPEffects[] = {}; visionMode[] = {"Normal","NVG"}; thermalMode[] = {}; discretefov[] = {0.0755,0.0249}; discreteInitIndex = 0; discreteDistance[] = {100,200,300,400,500,600,700,800}; discreteDistanceInitIndex = 2; }; }; };
#include "Input.h" #include "Game.h" bool Input::keys[256]; void Input::input(ALLEGRO_EVENT *ev){ if(ev->type == ALLEGRO_EVENT_KEY_DOWN){ switch(ev->keyboard.keycode){ case ALLEGRO_KEY_Q: Game::gameState = 0; break; case ALLEGRO_KEY_W: Input::keys[0] = true; break; case ALLEGRO_KEY_S: Input::keys[1] = true; break; case ALLEGRO_KEY_A: Input::keys[2] = true; break; case ALLEGRO_KEY_D: Input::keys[3] = true; break; case ALLEGRO_KEY_UP: Input::keys[0] = true; break; case ALLEGRO_KEY_DOWN: Input::keys[1] = true; break; case ALLEGRO_KEY_LEFT: Input::keys[2] = true; break; case ALLEGRO_KEY_RIGHT: Input::keys[3] = true; break; } } else if(ev->type == ALLEGRO_EVENT_KEY_UP){ switch(ev->keyboard.keycode){ case ALLEGRO_KEY_Q: Game::gameState = 0; break; case ALLEGRO_KEY_W: Input::keys[0] = false; break; case ALLEGRO_KEY_S: Input::keys[1] = false; break; case ALLEGRO_KEY_A: Input::keys[2] = false; break; case ALLEGRO_KEY_D: Input::keys[3] = false; break; case ALLEGRO_KEY_UP: Input::keys[0] = false; break; case ALLEGRO_KEY_DOWN: Input::keys[1] = false; break; case ALLEGRO_KEY_LEFT: Input::keys[2] = false; break; case ALLEGRO_KEY_RIGHT: Input::keys[3] = false; break; } } };
#include <stdlib.h> #include <math.h> #include "attractor.h" static double eval(double x, double y, const std::vector<double>& v) { double ret = 0.0; for (unsigned x_deg = 0; x_deg <= MAP_DEGREE; x_deg++) { for (unsigned y_deg = 0; y_deg <= x_deg; y_deg++) { ret += v[x_deg * MAP_DEGREE + y_deg] * pow(x, x_deg - y_deg) * pow(y, y_deg); } } return ret; } #define maxmin(z) \ do { \ if (z##_new > z##_max) \ z##_max = z##_new; \ else if (z##_new < z##_min) \ z##_min = z##_new; \ } while(0) Attractor::Attractor() { find_vecs(); } bool Attractor::try_vecs_usage(unsigned iters) const { HitMap hm(search_xfm, SEARCH_DIM_X, SEARCH_DIM_Y); apply(hm, SEARCH_ITERS); if (hm.get_fill_count() < MIN_FILL * SEARCH_DIM_X * SEARCH_DIM_Y) return false; return true; } bool Attractor::try_vecs(unsigned iters) { if (!try_vec_bounds(iters)) return false; return try_vecs_usage(iters); } bool Attractor::try_vec_bounds(unsigned iters) { double x_min, y_min, x_max, y_max, x, y; int i; x = 0; y = 0; x_min = x_max = x; y_min = y_max = y; for (i = 0; i < iters; i++) { double x_new = eval(x, y, a), y_new = eval(x, y, b); maxmin(x); maxmin(y); x = x_new; y = y_new; // test for NaN's if (x != x || y != y) return false; } if ((x_max - x_max) == x_max || (y_max - y_max) == y_max || x_max != x_max || y_max != y_max) return false; if ((x_min - x_min) == x_min || (y_min - y_min) == y_min || x_min != x_min || y_min != y_min) return false; if (x_max - x_min == x_max || x_max - x_min == -x_min || y_max - y_min == y_max || y_max - y_min == -y_min) return false; search_xfm.xlateX = -x_min; search_xfm.xlateY = -y_min; search_xfm.scaleX = ((double)SEARCH_DIM_X - 1) / (x_max - x_min); search_xfm.scaleY = ((double)SEARCH_DIM_Y - 1) / (y_max - y_min); return true; } static void gen_vec(std::vector<double>& v, double min, double max) { v.resize((MAP_DEGREE * (MAP_DEGREE + 1)) / 2); for (unsigned i = 0; i < v.size(); i++) { double rval = (double)rand() / (double)RAND_MAX; v[i] = (rval * (max - min)) + min; } } /* return number of attempts */ unsigned Attractor::find_vecs(void) { unsigned attempts = 0; do { attempts++; gen_vec(a, SEARCH_VMIN, SEARCH_VMAX); gen_vec(b, SEARCH_VMIN, SEARCH_VMAX); } while (!try_vecs(SEARCH_ITERS)); return attempts; } void Attractor::apply(HitMap& hm, unsigned iters) const { double x = 0.0, y = 0.0; for (unsigned i = 0; i < iters; i++) { double x_new = eval(x, y, a), y_new = eval(x, y, b); hm.inc(x_new, y_new); x = x_new; y = y_new; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; coding: iso-8859-1 -*- ** ** Copyright (C) 1995-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #include "modules/util/opstringset.h" OpStringSet::OpStringSet() : strings(NULL) , numStrings(0) { } OpStringSet::~OpStringSet() { if (strings) OP_DELETEA(strings); } BOOL OpStringSet::IsDupeWord(const uni_char *start, const uni_char *elem) const { const uni_char *elemEnd = elem; while (*elemEnd && !uni_isspace(*elemEnd)) ++elemEnd; BOOL isDupe = FALSE; // Check for a dupe earlier in the string. while (start != elem) { while (start != elem && uni_isspace(*start)) ++start; if (start != elem && uni_strncmp(elem, start, elemEnd - elem) == 0) { isDupe = TRUE; break; } while (start != elem && !uni_isspace(*start)) ++start; } return isDupe; } // Initialize the set with a string of white space delimited words. void OpStringSet::InitL(const OpStringC &str) { int num = 0; if (str.IsEmpty()) return; const uni_char *wPtr = str.CStr(); // Figure out how many whitespace separated strings there are. while (*wPtr != 0) { while (*wPtr != 0 && uni_isspace(*wPtr)) ++wPtr; if (*wPtr != 0) { // Only count words that aren't dupes. if (!IsDupeWord(str.CStr(), wPtr)) ++num; } while (*wPtr != 0 && !uni_isspace(*wPtr)) ++wPtr; } // Delete old storage. if (strings && numStrings < num) { OP_DELETEA(strings); strings = NULL; } // Set this just in case we leave, then at least this will be an empty set. numStrings = 0; if (!strings && num > 0) strings = OP_NEWA_L(OpString, num); if (strings || num == 0) { if (num > 0) { // Iterate and extract delimited strings. int c = 0; wPtr = str.CStr(); while (*wPtr != 0) { // Skip past whitespace. while (*wPtr != 0 && uni_isspace(*wPtr)) ++wPtr; // Find the end of the string, or the first whitespace. const uni_char *wEndPtr = wPtr; while (*wEndPtr != 0 && !uni_isspace(*wEndPtr)) ++wEndPtr; // If we found a string that's not a dupe, copy it and increase the count. if (wPtr != wEndPtr && !IsDupeWord(str.CStr(), wPtr)) strings[c++].SetL(wPtr, wEndPtr - wPtr); wPtr = wEndPtr; } } } numStrings = num; } // Do the relative complement a - b and return the result in the passed in set. OpStringSet &OpStringSet::RelativeComplementL(const OpStringSet &a, const OpStringSet &b) { // Calculate the number of elements in the resulting set. int num = a.Size(); for (int ai = 0; ai < a.Size(); ++ai) for (int bi = 0; bi < b.Size(); ++bi) if (a.GetString(ai) == b.GetString(bi)) { --num; break; } // Don't reallocate if we have the correct amount of elements in array. if (strings && numStrings != num) { OP_DELETEA(strings); strings = NULL; } // Set this just in case we leave, then at least this will be an empty set. numStrings = 0; if (!strings && num > 0) strings = OP_NEWA_L(OpString, num); if (strings && num > 0) { // We're not doing anything fancy here. O(n2). int c = 0; for (int ai = 0; ai < a.Size(); ++ai) { BOOL found = FALSE; for (int bi = 0; bi < b.Size(); ++bi) if (a.GetString(ai) == b.GetString(bi)) { found = TRUE; break; } if (!found) strings[c++].SetL(a.GetString(ai)); } } numStrings = num; return *this; }
// // Created by Lee on 2019-04-23. // #ifndef UBP_CLIENT_CPP_VER_UPLOADVIEW_H #define UBP_CLIENT_CPP_VER_UPLOADVIEW_H #include "PhotoThumbnailForUpload.h" #include <QWidget> #include "PhotoManager.h" class UploadView : public QWidget { Q_OBJECT public: explicit UploadView(QWidget * parent = nullptr, PhotoManager * photoManager = nullptr); void updateThumbnails(); private slots: void handleHomeButton(); void handleCreateGroupButton(); void handleDeleteGroupButton(); private: std::vector<PhotoGroup> photoGroups; std::vector<PhotoThumbnailForUpload *> photoThumbnails; PhotoManager * photoManager; QPushButton * homeButton; QPushButton * createGroupButton; QPushButton * deleteGroupButton; void updateContents(PhotoGroup &group); void replaceTheContents(); }; #endif //UBP_CLIENT_CPP_VER_UPLOADVIEW_H
#pragma once #include "Keng/WindowSystem/IWindowListener.h" #include "Keng/WindowSystem/IWindow.h" #include "WinWrappers\WinWrappers.h" #include "EverydayTools\UnusedVar.h" #include "EverydayTools\Observable.h" #include <algorithm> #include <vector> namespace keng::window_system { template<typename TChar> class MainWindow : public IWindow, public Window<TChar, ::keng::window_system::MainWindow>, public Observable<MainWindow<TChar>, IWindowListener> { public: MainWindow(HWND handle = nullptr) : Window<TChar, keng::window_system::MainWindow>(handle) { } void Initialize(HINSTANCE hInstance) { UnusedVar(hInstance); } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_SIZE: ForEachListener([&](IWindowListener* p) { p->OnWindowResize(LOWORD(lParam), HIWORD(lParam)); return false; }); break; } return WA::DefWindowProc_(hWnd, msg, wParam, lParam); } //IWindow virtual void Subscribe(IWindowListener* listener) override final { Observable<window_system::MainWindow<TChar>, IWindowListener>::Subscribe(listener); } virtual void Unsubscribe(IWindowListener* listener) override final { Observable<window_system::MainWindow<TChar>, IWindowListener>::Unsubscribe(listener); } virtual void GetClientSize(size_t* w, size_t* h) override final { GetWindowClientSize(w, h); } virtual int64_t* GetNativeHandle() override final { return (int64_t*)GetHandle(); } }; template<typename TChar> class MainWindowClass : public WindowClass<TChar, keng::window_system::MainWindowClass> { public: using Window = MainWindow<TChar>; static inline const TChar* GetName(); MainWindowClass(HINSTANCE module_) : WindowClass<TChar, keng::window_system::MainWindowClass>(module_, 0) { } }; const char* MainWindowClass<char>::GetName() { return "MainWindow"; } const wchar_t* MainWindowClass<wchar_t>::GetName() { return L"MainWindow"; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Per Hedbor */ #if !defined TABLE_DECOMPRESSOR_H && defined TABLEMANAGER_COMPRESSED_TABLES #define TABLE_DECOMPRESSOR_H #include "modules/zlib/zlib.h" /** * Decompress deflate and delta-encoded tables. * Only used from the internal tablemanager functions, never used by users. * * The tables are stored as deflate-compressed delta-encoded 24-bit * signed network-byte-order integers. The decompression will generate * an equal number of 16bit unsigned host-byte-order integers. */ class TableDecompressor { public: TableDecompressor(); ~TableDecompressor(); /** * Initialize decompressor object. Object MUST be initialized before * the decompress session, and the object should be used only once. * * @return Status of the operation */ OP_STATUS Init(); /** * Read bytes from src and write them to dest, but read no more than * src_len bytes and write no more than dest_len bytes. Return the number * of bytes written into dest, and set read to the number of bytes * read. The src and dest pointers must point to different buffers. * * @param src The buffer to convert from. * @param src_len The amount of data in the src buffer (in bytes). * @param dest The buffer to convert to. * @param dest_len The size of the dest buffer (in bytes). * @param read Output parameter returning the number of bytes * read from src. * @return The number of bytes written to dest; -1 on error * (failed to allocate memory). */ int Decompress(const UINT8 *src, int src_len, UINT8 *dest, int dest_len, int *read); private: inline int Undelta(UINT8 *dest, const UINT8 *src, int len, int cur); public: z_stream m_stream; UINT8 *m_work_area; int m_work_area_len; int m_delta; //Preious Undelta value int m_left; //Number of bytes in m_work_area from last (incomplete) Decompress call }; #endif
//--------------------------------------------------------------------------- /*可适合非同步连接的sock5代理服务器连接封装类 作者: Bluely 日期:2003.09.27 说明: 遵循 RFC 1982 标准,目前只实现sock5协议代码,UDP模式下没有测试过. /* 步骤: smNEGOTIATION 协商版本和方法 客户端连到服务器后,然后就发送请求来协商版本和认证方法: VER 版本: 0x5 (sock5) NMETHODS NMETHODS字段包含了在METHODS字段中出现的方法标示的数目(以字节为单位)。 METHODS 方法: 0x00 不需要认证 0x01 GSSAPI 0x02 用户名/密码 0x03 -- 0x7F 由IANA分配 0x80 -- 0xFE 为私人方法所保留的 0xFF 没有可以接受的方法 服务器返回: 服务器从这些给定的方法中选择一个并发送一个方法选中的消息回客户端: VER 版本: 0x5 (sock5) METHOD 应等于SEND 的METHODS,如果为0xFF表示没有可以接受的方法 步骤: emAUTHENTICATION 校验用户 VER version of subnegotiation USERNAME LEN 用户名长度 USERNAME 用户名 PassWord Len 密码长度 PASSWORD 密码 服务器返回: 0x0表示验证成功,否则为失败 步骤:smCONNECTION 发送代理连接信息 SockVER // socks version ConnectMethod // connect method Reserved // reserved AddrType //address type: IP V4 address: X'01', DOMAINNAME: X'03' IP V6 address: X'04' HOSTNAME_LEN //目标主机名长度 HOSTNAME //目标主机名 PORT //目标主机端口 */ #ifndef sock5H #define sock5H #include <Classes.hpp> enum TSockStepMode {smNEGOTIATION=0,smAUTHENTICATION,smCONNECTION,smFINISH}; enum TAuthenticationMode {amNoAuthentication,amUsernamePassword}; class TSockProxyClient { private: String mUserName; String mPassWord; DWORD mHostIP; WORD mPort; TSockStepMode mCurrentStep; int mLastError; private: String DoNegotiation(); //处理协商步骤 String DoAuthentication(); //处理验证步骤 String DoConnection(); //处理连接步骤 bool RecvNegotiation(LPBYTE buf,int Len); //处理协商步骤返回封包 bool RecvAuthentication(LPBYTE buf,int Len); //处理验证步骤返回封包 bool RecvConnection(LPBYTE buf,int Len); //处理连接步骤返回封包 public: TAuthenticationMode AuthenticationMode; public: __fastcall TSockProxyClient(); __fastcall ~TSockProxyClient(); void SetHostInfo(const String &Host,WORD Port); //设置目标服务器信息(不是代理服务器地址) void SetUserInfo(const String &UserName,const String &PassWord); //设置用户名和密码 String ProcessNext(); //处理下一步 bool ProcessRecvData(LPBYTE buf,int Len); //处理服务器返回信息 int GetCurrentStep(); //获取当前和代理服务器的通信完成步骤 String GetCurrentStepInfo(); //获取当前和代理服务器的通信完成步骤描述 bool IsFinish(); //是否已经全部验证完毕 int GetLastError(); String GetLastErrorStr(); void Reset(); }; //--------------------------------------------------------------------------- #endif
#include "Engine.hpp" #undef main int main(int argc, const char* argv[]) { Engine l_eng; l_eng.RunConfigAndInitilize("config.lua"); return 0; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <quic/state/StateData.h> namespace quic { /** * Check whether the peer supports ACK_FREQUENCY and IMMEDIATE_ACK frames */ bool canSendAckControlFrames(const QuicConnectionStateBase& conn); /** * Send an ACK_FREQUENCY frame to request the peer to change its ACKing * behavior */ void requestPeerAckFrequencyChange( QuicConnectionStateBase& conn, uint64_t ackElicitingThreshold, std::chrono::microseconds maxAckDelay, uint64_t reorderThreshold); std::chrono::microseconds clampMaxAckDelay( const QuicConnectionStateBase& conn, std::chrono::microseconds maxAckDelay); /** * Send an IMMEDIATE_ACK frame to request the peer to send an ACK immediately */ void requestPeerImmediateAck(QuicConnectionStateBase& conn); } // namespace quic
#include <iostream> using namespace std; int main() { if (cout<<"hello") { } }
/** * Copyright (c) 2013, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file nextwork-extension-functions.cc */ #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <string.h> #include <sys/socket.h> #include "base/auto_mem.hh" #include "config.h" #include "sqlite-extension-func.hh" #include "sqlite3.h" #include "vtab_module.hh" static std::string sql_gethostbyname(const char* name_in) { char buffer[INET6_ADDRSTRLEN]; auto_mem<struct addrinfo> ai(freeaddrinfo); void* addr_ptr = nullptr; struct addrinfo hints; int rc; memset(&hints, 0, sizeof(hints)); for (auto family : {AF_INET, AF_INET6}) { hints.ai_family = family; while ((rc = getaddrinfo(name_in, nullptr, &hints, ai.out())) == EAI_AGAIN) { sqlite3_sleep(10); } if (rc != 0) { return name_in; } switch (ai.in()->ai_family) { case AF_INET: addr_ptr = &((struct sockaddr_in*) ai.in()->ai_addr)->sin_addr; break; case AF_INET6: addr_ptr = &((struct sockaddr_in6*) ai.in()->ai_addr)->sin6_addr; break; default: return name_in; } inet_ntop(ai.in()->ai_family, addr_ptr, buffer, sizeof(buffer)); break; } return buffer; } static std::string sql_gethostbyaddr(const char* addr_str) { union { struct sockaddr_in sin; struct sockaddr_in6 sin6; } sa; char buffer[NI_MAXHOST]; int family, socklen; char* addr_raw; int rc; memset(&sa, 0, sizeof(sa)); if (strchr(addr_str, ':')) { family = AF_INET6; socklen = sizeof(struct sockaddr_in6); sa.sin6.sin6_family = family; addr_raw = (char*) &sa.sin6.sin6_addr; } else { family = AF_INET; socklen = sizeof(struct sockaddr_in); sa.sin.sin_family = family; addr_raw = (char*) &sa.sin.sin_addr; } if (inet_pton(family, addr_str, addr_raw) != 1) { return addr_str; } while ((rc = getnameinfo((struct sockaddr*) &sa, socklen, buffer, sizeof(buffer), NULL, 0, 0)) == EAI_AGAIN) { sqlite3_sleep(10); } if (rc != 0) { return addr_str; } return buffer; } int network_extension_functions(struct FuncDef** basic_funcs, struct FuncDefAgg** agg_funcs) { static struct FuncDef network_funcs[] = { sqlite_func_adapter<decltype(&sql_gethostbyname), sql_gethostbyname>:: builder( help_text("gethostbyname", "Get the IP address for the given hostname") .sql_function() .with_parameter({"hostname", "The DNS hostname to lookup."}) .with_tags({"net"}) .with_example({ "To get the IP address for 'localhost'", "SELECT gethostbyname('localhost')", })), sqlite_func_adapter<decltype(&sql_gethostbyaddr), sql_gethostbyaddr>:: builder( help_text("gethostbyaddr", "Get the hostname for the given IP address") .sql_function() .with_parameter({"hostname", "The IP address to lookup."}) .with_tags({"net"}) .with_example({ "To get the hostname for the IP '127.0.0.1'", "SELECT gethostbyaddr('127.0.0.1')", })), {nullptr}, }; *basic_funcs = network_funcs; return SQLITE_OK; }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10037" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int CASE,num; scanf("%d",&CASE); int people[1005]; int path[1005][3]; while( CASE-- ){ memset(people,0,sizeof(people)); memset(path,-1,sizeof(path)); scanf("%d",&num); for(int i = 0 ; i < num ; i++ ) scanf("%d",&people[i+1]); sort(&people[1],&people[num+1]); int trip = 0; int ans = 0; while( num > 0 ){ if( num == 1 ){ ans = people[1]; printf("%d\n", people[1]); break; } else if( num == 2 ){ path[trip][0] = people[1]; path[trip][1] = people[2]; trip++; ans = ans + people[2]; num = 0; } else if( num == 3 ){ path[trip][0] = people[1]; path[trip][1] = people[2]; path[trip][2] = people[1]; trip++; path[trip][0] = people[1]; path[trip][1] = people[3]; trip++; num = 0; ans = ans + people[1] + people[2] + people[3]; } else{ int A,B; A = people[1] + people[2]*2 + people[num]; B = people[1]*2 + people[num-1] + people[num]; if( A < B ){ path[trip][0] = people[1]; path[trip][1] = people[2]; path[trip][2] = people[1]; trip++; path[trip][0] = people[num-1]; path[trip][1] = people[num]; path[trip][2] = people[2]; trip++; ans = ans + A; } else{ path[trip][0] = people[1]; path[trip][1] = people[num-1]; path[trip][2] = people[1]; trip++; path[trip][0] = people[1]; path[trip][1] = people[num]; path[trip][2] = people[1]; trip++; ans = ans + B; } num = num - 2; } } printf("%d\n",ans ); for(int i = 0 ; i < trip ; i++ ){ printf("%d %d\n",path[i][0],path[i][1] ); if( path[i][2] != -1 ) printf("%d\n",path[i][2] ); } if( CASE > 0 ) printf("\n"); } return 0; }
// Given a 2D board and a word, find if the word exists in the grid. // The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. // For example, // Given board = // [ // ["ABCE"], // ["SFCS"], // ["ADEE"] // ] // word = "ABCCED", -> returns true, // word = "SEE", -> returns true, // word = "ABCB", -> returns false. bool exist(vector<vector<char> > &board, string word, int idx, int row, int col, vector< vector<bool> > &mask) { int i = row; int j = col; if (board[i][j] == word[idx] && mask[i][j]==0 ) { mask[i][j]=1; //mark the current char is matched if (idx+1 == word.size()) return true; //checking the next char in `word` through the right, left, up, down four directions in the `board`. idx++; if (( i+1<board.size() && exist(board, word, idx, i+1, j, mask) ) || ( i>0 && exist(board, word, idx, i-1, j, mask) ) || ( j+1<board[i].size() && exist(board, word, idx, i, j+1, mask) ) || ( j>0 && exist(board, word, idx, i, j-1, mask) ) ) { return true; } mask[i][j]=0; //cannot find any successful solution, clear the mark. (backtracking) } return false; } bool exist(vector<vector<char> > &board, string word) { if (board.size()<=0 || word.size()<=0) return false; int row = board.size(); int col = board[0].size(); //using a mask to mark which char has been selected. //do not use vector<bool>, it has big performance issue, could cause Time Limit Error vector< vector<bool> > mask(row, vector<bool>(col, false)); for(int i=0; i<board.size(); i++) { for(int j=0; j<board[i].size(); j++){ if ( board[i][j]==word[0] ){ vector< vector<bool> > m = mask; if( exist(board, word, 0, i, j, m) ){ return true; } } } } return false; } class Solution { private: vector<vector<char> >* board; string* word; bool **used; bool isInboard(int i, int j){ if(i < 0)return false; if(i >= board->size())return false; if(j < 0)return false; if(j >= (*board)[i].size())return false; return true; } bool DFS(int si, int sj, int n){ if(n == word.size()) return true; if(isInboard(si, sj)){ if(!used[si][sj] && (*board)[si][sj] == (*word)[n]){ used[si][sj] = true; bool ret = false; if(DFS(si+1, sj, n+1)){ ret = true; }else if(DFS(si-1, sj, n+1)) ret = true; else if(DFS(si, sj+1, n+1)) ret = true; else if(DFS(si, sj-1, n+1)) ret = true; used[si][sj] = false; return ret; } } return false; } public: bool exist(vector<vector<char> > &board, string word) { if(board.size() == 0 ) return false; this->board = &board; this->word = &word; used = new bool*[board.size()]; for(int i = 0; i < board.size(); i ++) { used[i] = new bool[board[i].size()]; for(int j = 0; j < board[i].size(); j ++) used[i][j] = false; } // for(int i = 0; i < board.size(); i ++) for(int j = 0; j < board[i].size(); j ++) if(DFS(i, j, 0))return true; return false; } };
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; int f[110][110][4],a[110][110]; int main() { int n,m; scanf("%d%d",&n,&m); for (int i = 1;i <= n; i++) for (int j = 1;j <= m; j++) { scanf("%d",&a[i][j]); } int ans = n+1,x = -1,y = -1; for (int i = 1;i <= m; i++) for (int j = i+1;j <= m; j++) { for (int k = 1;k <= n; k++) f[i][j][a[k][i]*2+a[k][j]]++; int mi = max(max(f[i][j][0],f[i][j][1]),max(f[i][j][2],f[i][j][3])); //cout<< i << " " << j << mi << endl; if (mi < ans) { ans = mi; x = i;y = j; } } printf("%d\n%d %d\n",ans,x,y); return 0; }
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #include <unordered_map> #include <stack> #include <cstdio> #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) #define INF (1e300) using namespace std; ifstream fin("1062_input.txt"); #define cin fin struct ele { ele(int step, int letter) { this->step = step; this->letter = letter; } int step; int letter; }; int main() { string s; cin >> s; int case_count = 0; while (s != "end") { int slen = s.length(); vector<ele> buffer; vector<bool> visited(slen, false); int step = 0; int prev_max = -1; int v_count = 0; while (v_count < slen) { prev_max = -1; step++; for (int i = 0; i < slen; i++) if (!visited[i] && s[i] - 'A'>prev_max) { prev_max = s[i] - 'A'; v_count++; visited[i] = true; buffer.push_back(ele(step, prev_max)); } } buffer.push_back(ele(-1, -1)); int result = 0; int last = -1; int count = 0; for (auto it : buffer) { if (it.step != last) { result = max(result, count); last = it.step; count = 1; } else count++; } case_count++; cout << "Case " << case_count << ": " << result << endl; cin >> s; } }
#include <iostream> #include <string> #include <vector> using namespace std; class Person { public: int m_a, m_b, m_c; // 先定义的m_a, m_b, m_c,然后再分别赋值 // Person(int a, int b, int c) // { // m_a = a; // m_b = b; // m_c = c; // } // 使用初始化列表 // 先声明了m_a, m_b, m_c,再根据声明的顺序进行定义初始化 Person(int a, int b, int c) : m_a(a), m_b(b), m_c(c) { } void show() { cout << m_a << " " << m_b << " " << m_c << endl; } // ~Person(); }; void test01() { Person p1(2, 3, 5); p1.show(); } int main(int argc, char **argv) { test01(); return 0; }
/** * @author shaoDong * @email scut_sd@163.com * @create date 2018-09-20 19:40:04 * @modify date 2018-09-20 19:40:04 * @desc n 个非负整数的柱状图,能接多少水 * 输入:[0,1,0,2,1,0,1,3,2,1,2,1] * 输出:6 */ #include <iostream> #include <vector> using namespace std; int main(int argc, char const *argv[]) { int arr[] = {0,1,0,2,1,0,1,3,2,1,2,1}; int res = 0; char temp; string str; // vector<int> inputVec(arr, arr + 12); vector<int> inputVec; // input while(true) { temp = getchar(); if(temp == '\n') { break; } else { int num = int(temp) - 48; if(num >= 0 && num <= 9) { inputVec.push_back(num); } } } cout<<inputVec.size(); // cin>>str; // for(int i = 0, len = str.size(); i < len; i += 2) // { // inputVec.push_back(int(str[i]) - 48); // } // cout<<int(str[0])<<endl; for(int i = 0, len = inputVec.size() - 1; i < len; i++) { // cout<<inputVec[i]<<" "; for(int j = i + 1; j < len; j++) { // 从每个位置向后找到第一个大于等于自己高度的位置,然后计算中间的面积 if(arr[i] <= arr[j]) { if(j - i > 1) { int min = arr[i] > arr[j] ? arr[j] : arr[i]; for(; i < j; i++) { res += min - arr[i]; } i--; } break; } else { continue; } } } // cout<<endl; cout<<res<<endl; return 0; }
#ifndef TOKEN_H #define TOKEN_H #include <iostream> using namespace std; class Token { public: Token(int num):type(num) { //cout << "Token constructor called"; } ~Token() { //cout << "Token destructor called"; } void virtual print(ostream& outs = cout) const {} double virtual getNum() { return 0; } char virtual getSymbol() { return ' '; } int virtual getPrecedence() { return 0; } /* friend ostream& operator << (ostream& outs, const Token* p) { //p->print(); return outs; } */ int getType() { return type; } void setType(int i) { type = i; } private: int type; }; #endif
#include<string> #include<vector> #include<stdlib.h> #include<iostream> using namespace std; typedef struct BiNode { char data; struct BiNode * lchild; struct BiNode * rchild; }BiNode, * BiTree; void CreateBiTree(BiTree &t,string pre,string mid) { if(pre.length()==0) { t=NULL; return ; } char rootNode=pre[0]; int index=mid.find(rootNode); string lchild_mid=mid.substr(0,index); string rchild_mid=mid.substr(index+1); int lchild_length=lchild_mid.length(); int rchild_length=rchild_mid.length(); string lchild_pre=pre.substr(1,lchild_length); string rchild_pre=pre.substr(1+lchild_length); t=(BiTree)malloc(sizeof(BiNode)); if(t!=NULL) { t->data=rootNode; CreateBiTree(t->lchild,lchild_pre,lchild_mid); CreateBiTree(t->rchild,rchild_pre,rchild_mid); } } void printNodeByLevel(BiTree root) { if(root == NULL) return; vector<BiNode *> vec; vec.push_back(root); int cur = 0; int last = 1; while(cur < vec.size()) { last = vec.size(); while(cur < last) { cout<<vec[cur]->data << " "; if(vec[cur]->lchild != NULL) vec.push_back(vec[cur]->lchild); if(vec[cur]->rchild != NULL) vec.push_back(vec[cur]->rchild); ++cur; } } } int main() { BiTree t; int n; string pre, mid; while (cin >> n) { cin >> pre; cin >> mid; CreateBiTree(t,pre,mid); printNodeByLevel(t); } return 0; }
// // Ray.cpp // RayTracingPro // // Created by Ying Zhan on 10/24/15. // Copyright (c) 2015 Ying Zhan. All rights reserved. // #include "Ray.h" Ray::Ray() { } Ray::~Ray() { } void Ray::setSign(int sign) { ray_sign = sign; } int Ray::getSign() { return ray_sign; } void Ray::setEnergy(float energy) { ray_energy = energy; } float Ray::getEnergy() { return ray_energy; } void Ray::setRayDirection(Eigen::VectorXd direction_vector) { ray_direction = direction_vector; } Eigen::VectorXd Ray::getRayDirection() { return ray_direction; } void Ray::setStartTracingPoint(Eigen::VectorXd point) { start_tracing_point = point; } Eigen::VectorXd Ray::getStartTracingPoint() { return start_tracing_point; } void Ray::setRayDistance(float distance) { ray_distance = distance; } float Ray::getRayDistance() { return ray_distance; }
#include "DrawTriangle.h" void DrawTriangle::initBuffer() { glGenBuffers(1, &vbo); // 生成一个顶点缓冲对象 vbo 缓冲对象类型有很多 下一步设置为array类型 glGenVertexArrays(1, &vao); // 生成一个vao 用来保存顶点属性解释 我们一个程序可以有很多vao 代表不同的顶点属性解释方法 只需要绑定到相应的顶点上就可以对buffer做正确的解释 glBindVertexArray(vao); // 表示我们的程序的顶点属性应该按照它来解释 就是上面的glVertexAttribPointer这行。 glBindBuffer(GL_ARRAY_BUFFER, vbo); // 设置这个缓冲对象的类型是array glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // 为缓冲区写入数据 复制数据到缓冲区内 //GL_STATIC_DRAW 表示数据不会改变 GL_DYNAMIC_DRAW数据会改变很多 GL_STREAM_DRAW 数据每次绘制的时候都会改变 // 设置顶点属性指针 第一个参数0对应顶点shader着色器的layout(location=0) 表示我们希望把数据传递到这个这一个顶点属性中 // 第二个参数是顶点属性大小,我们的in是vec3,所以是3 // 第三个参数是数据类型,我们的是float // 第4个参数是是否希望被标准化,标准化后所有数据是-1到1之间的,而我们的不是,我们希望在vertex着色器去标准化。所以是false // 第5个参数是步长,因为我们是vec3,所以是3个float。 // 第6个参数是数据在缓冲中的起始偏移量。由于位置数据在数组的开头,所以我们这里设置为0 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); // 定义opengl如何解释顶点数据 glEnableVertexAttribArray(0); // 这两步是定义opengl如何解释顶点数据 glBindVertexArray(0); // 还原回系统默认值 因为数据已经在上面绑定到了唯一id vao上了 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // 还原回系统默认值 因为数据已经绑定到唯一id vbo上了 } void DrawTriangle::drawGraph() // 绘制三角形 { // 使用该程序 glUseProgram(sharedProgram); glBindVertexArray(vao); // 使用该vao配置 glDrawArrays(GL_TRIANGLES, 0, 3); // 画三角形 起始索引是0, 使用3个顶点 }
#include <cstdio> #include <fstream> #include <iostream> #include <sstream> #include <conio.h> #include "graphviewer.h" #include "edgetype.h" #include "SistemaDeEvacuacao.h" #include "utils.h" using namespace std; #define NODES_FN "Nodes.txt" #define ROADS_FN "Roads.txt" #define NODES_TO_ROADS_FN "NodesToRoads.txt" #define KEY_UP 72 #define KEY_DOWN 80 #define KEY_LEFT 75 #define KEY_RIGHT 77 #define ESC 27 #define FILE_LOADING_REPORTING false //---------------------------------------Reading From Files Functions--------------------------------------- //------------------------------------------------------------------------------ //Recieves a file stream that was not openned yet and reads the file name from user //Returns the file name that it read from the user //Does not return anything while it is not able to successfully read the file name introduced //If it can read the filename but can't open it, exits with an error message string ReadFile(ifstream &f_stream) { string f_name; string error_msg = "Ocorreu um erro ao ler o nome de ficheiro que introduziu. Por favor, tente novamente, introduzindo um nome de ficheiro valido: "; f_name = ReadString(error_msg); f_stream.open(f_name); if (!(f_stream.is_open())) //Check if the file was openned successfully { cerr << endl << "Ocorreu um erro ao tentar abrir o ficheiro. O programa ira terminar." << endl; system("pause"); exit(1); } return f_name; } //------------------------------------------------------------------------------ void OpenFile(const string &f_name, ifstream &f_stream) { f_stream.open(f_name); if (!(f_stream.is_open())) //Check if the file was openned successfully { cerr << endl << "Ocorreu um erro ao tentar abrir um dos ficheiros que contem a informacao sobre o mapa. Por favor, garanta que todos os ficheiros necessarios estao disponiveis. O programa ira terminar." << endl; system("pause"); exit(1); } } //------------------------------------------------------------------------------ //Reads all the filenames from user and opens the file streams (checking if the files exist) void ReadFiles(ifstream &cars_fs, string &cars_fn) { cout << endl << "Introduza o nome do ficheiro que contem as informacoes dos carros para desviar: "; cars_fn = ReadFile(cars_fs); cout << endl; } //------------------------------------------------------------------------------ //Parses the contents of all the files to the vectors in the class VendeMaisMais void ParseFileContents(SistemaDeEvacuacao &EvacSystem, ifstream &cars_fs) { //Load information from map files const string nodes_fn = NODES_FN; const string rods_fn = ROADS_FN; const string nodes_to_roads_fn = NODES_TO_ROADS_FN; ifstream nodes_fs; ifstream rods_fs; ifstream nodes_to_roads_fs; OpenFile(nodes_fn, nodes_fs); OpenFile(rods_fn, rods_fs); OpenFile(nodes_to_roads_fn, nodes_to_roads_fs); #if FILE_LOADING_REPORTING cout << "Started parsing files." << endl << endl; unsigned int start_time = GetTickCount64(); unsigned int elapsed_time; #endif try { EvacSystem.ParseNodesFile(nodes_fs); nodes_fs.close(); #if FILE_LOADING_REPORTING elapsed_time = GetTickCount64() - start_time; cout << "Nodes file parsed in " << elapsed_time << " ms" << endl; start_time = GetTickCount64(); #endif EvacSystem.ParseRoadsFile(rods_fs); rods_fs.close(); #if FILE_LOADING_REPORTING elapsed_time = GetTickCount64() - start_time; cout << "Roads file parsed in " << elapsed_time << " ms" << endl; start_time = GetTickCount64(); #endif EvacSystem.ParseNodesToRoadsFile(nodes_to_roads_fs); nodes_to_roads_fs.close(); #if FILE_LOADING_REPORTING elapsed_time = GetTickCount64() - start_time; cout << "Nodes to Roads file parsed in " << elapsed_time << " ms" << endl; start_time = GetTickCount64(); #endif } catch (SistemaDeEvacuacao::ErrorParsingFile &error) { cout << "Ocorreu um erro ao ler a informacao de um dos ficheiros que contem a informacao do mapa. O programa ira terminar." << endl << endl; system("pause"); exit(1); } catch (SistemaDeEvacuacao::InvalidInfoParsedFromFile &error) { cout << "A informacao lida de um dos ficheiros que contem a informacao do mapa e invalida. Por favor verifique a validade dos ficheiros. O programa ira terminar." << endl << endl; system("pause"); exit(1); } //Load information from cars file string cars_fn; ReadFiles(cars_fs, cars_fn); #if FILE_LOADING_REPORTING start_time = GetTickCount64(); #endif try { EvacSystem.ParseCars(cars_fs); cars_fs.close(); #if FILE_LOADING_REPORTING elapsed_time = GetTickCount64() - start_time; cout << "Cars file parsed in " << elapsed_time << " ms" << endl << endl; start_time = GetTickCount64(); #endif } catch (SistemaDeEvacuacao::ErrorParsingFile &error) { cout << "Ocorreu um erro ao ler a informacao do ficheiro de carros na linha " << error.GetLine() << ". Por favor verifique a validade do ficheiro. O programa ira terminar" << endl << endl; system("pause"); exit(1); } catch (SistemaDeEvacuacao::InvalidInfoParsedFromFile &error) { cout << "A informacao lida do ficheiro do ficheiro de carros na linha " << error.GetLine() << " e invalida. Por favor verifique a validade do ficheiro. O programa ira terminar." << endl << endl; system("pause"); exit(1); } cout << "A informacao contida em todos os ficheiros foi lida com sucesso" << endl << endl; system("pause"); } int main() { SistemaDeEvacuacao EvacSystem; ifstream cars_fs; ParseFileContents(EvacSystem, cars_fs); ClearScreen(); EvacSystem.ReadIssueVertexesIds(); ClearScreen(); EvacSystem.HandleCarsList(); ClearScreen(); //alterate between cars unsigned int cars_size = EvacSystem.GetCarsSize(); if (cars_size == 0) { cout << "Nao existem rotas de carros para mostrar" << endl; goto END; } unsigned char cin_1, cin_2; int curr_car = 0; cout << "Por favor aguarde..." << endl; EvacSystem.CreateGraphViewer(1900, 1000, BLUE, DARK_GRAY); EvacSystem.DisplayMap(); ClearScreen(); EvacSystem.ShowCarRoute(curr_car); cout << endl << endl; cout << "Pressione as setas para alternar entre os carros." << endl; cout << "Setas esquerda e cima mostram o carro anterior <-" << endl; cout << "Setas direita e baixo mostram o carro seguinte ->" << endl << endl; cout << "Pressione ESC para sair." << endl; while (true) { cin_1 = _getch(); if (cin_1 == ESC) break; cin_2 = _getch(); if (cin_2 == KEY_DOWN || cin_2 == KEY_RIGHT) curr_car++; if (cin_2 == KEY_UP || cin_2 == KEY_LEFT) curr_car--; if (curr_car < 0) curr_car = cars_size - 1; else if (curr_car == cars_size) curr_car = 0; EvacSystem.DisplayMap(); ClearScreen(); EvacSystem.ShowCarRoute(curr_car); cout << endl << endl; cout << "Pressione as setas para alternar entre os carros." << endl; cout << "Setas esquerda e cima mostram o carro anterior <-" << endl; cout << "Setas direita e baixo mostram o carro seguinte ->" << endl << endl; cout << "Pressione ESC para sair." << endl; } END: system("pause"); return 0; }
#pragma once extern "C" { #include <gvc.h> } #include <vector> #include <memory> #include <set> #include "recording_api.h" class Situation; class Transition; /** * This class represents a graph of Situations and Transitions and can create a visual representation of it. */ class SituationGraph { public: /** * Builds a graph from the given Situations. */ RECORDING_API SituationGraph(std::vector<std::shared_ptr<Transition>> transitions); /** * Cleans up memory of the graph representation. */ RECORDING_API ~SituationGraph(); /** * Exports the image of the graph as PDF with the given filename in the subfolder 'Graphs' * @param filename Name of the file to be created. */ RECORDING_API void saveAsPDF(const std::string &filename) const; /** * Computes the longest simple path from an initial situation to a final situation. * @Returns longest simple path in the graph */ RECORDING_API int getLongestSequence() const; private: Agraph_t *graph; GVC_t *gvc; std::vector<std::shared_ptr<Transition>> transitions; std::set<std::shared_ptr<Situation>> initialSituations; std::set<std::shared_ptr<Situation>> finalSituations; int longestDFS(std::shared_ptr<Situation> root) const; /** * Adds nodes for all Situations and edges for all Transitions. */ void createGraph(); };
// Created on : Sat May 02 12:41:15 2020 // Created by: Irina KRYLOVA // Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V3.0 // Copyright (c) Open CASCADE 2020 // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepKinematics_PointOnPlanarCurvePair_HeaderFile_ #define _StepKinematics_PointOnPlanarCurvePair_HeaderFile_ #include <Standard.hxx> #include <StepKinematics_HighOrderKinematicPair.hxx> #include <TCollection_HAsciiString.hxx> #include <StepRepr_RepresentationItem.hxx> #include <StepKinematics_KinematicJoint.hxx> #include <StepGeom_Curve.hxx> DEFINE_STANDARD_HANDLE(StepKinematics_PointOnPlanarCurvePair, StepKinematics_HighOrderKinematicPair) //! Representation of STEP entity PointOnPlanarCurvePair class StepKinematics_PointOnPlanarCurvePair : public StepKinematics_HighOrderKinematicPair { public : //! default constructor Standard_EXPORT StepKinematics_PointOnPlanarCurvePair(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theRepresentationItem_Name, const Handle(TCollection_HAsciiString)& theItemDefinedTransformation_Name, const Standard_Boolean hasItemDefinedTransformation_Description, const Handle(TCollection_HAsciiString)& theItemDefinedTransformation_Description, const Handle(StepRepr_RepresentationItem)& theItemDefinedTransformation_TransformItem1, const Handle(StepRepr_RepresentationItem)& theItemDefinedTransformation_TransformItem2, const Handle(StepKinematics_KinematicJoint)& theKinematicPair_Joint, const Handle(StepGeom_Curve)& thePairCurve, const Standard_Boolean theOrientation); //! Returns field PairCurve Standard_EXPORT Handle(StepGeom_Curve) PairCurve() const; //! Sets field PairCurve Standard_EXPORT void SetPairCurve (const Handle(StepGeom_Curve)& thePairCurve); //! Returns field Orientation Standard_EXPORT Standard_Boolean Orientation() const; //! Sets field Orientation Standard_EXPORT void SetOrientation (const Standard_Boolean theOrientation); DEFINE_STANDARD_RTTIEXT(StepKinematics_PointOnPlanarCurvePair, StepKinematics_HighOrderKinematicPair) private: Handle(StepGeom_Curve) myPairCurve; Standard_Boolean myOrientation; }; #endif // _StepKinematics_PointOnPlanarCurvePair_HeaderFile_
#include<iostream> #include<algorithm> #include<vector> #include<unordered_set> using namespace std; class Solution { public: bool containsDuplicate(vector<int>& nums) { //基本思想:哈希表,时间复杂度O(n)空间复杂度O(n) unordered_set<int> dict; for (auto num : nums) { if (dict.find(num) != dict.end()) return true; dict.insert(num); } return false; } }; int main() { Solution solute; vector<int> nums = { 1,2,3,1 }; cout << solute.containsDuplicate(nums) << endl; return 0; }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #pragma once #include <QWidget> #include <QApplication> #include <QPushButton> #include <QLabel> class charStack { private: int top=-1; char Stack[300]; public: void push(char elem); char pop(); char showLast(); }; class intStack { private: int top = -1; double Stack[300]; public: void push(double ); double pop(); }; class infixToPostfix { private: charStack charObject; intStack intObject; public: int pres(char ope); char * infix_postfix(char str[]); double solve_postfix(char str[]); double getResult( char str[]); }; class MainWindow : public QWidget{ Q_OBJECT public: MainWindow(QWidget *parent = nullptr); private slots: void On_0(); void On_1(); void On_2(); void On_3(); void On_4(); void On_5(); void On_6(); void On_7(); void On_8(); void On_9(); void On_add(); void On_minus(); void On_divide(); void On_multi(); void On_clear(); void On_allclear(); void On_ans(); private: QLabel *disp; }; #endif // MAINWINDOW_H
#include <iostream> #include <cstdio> #include <math.h> using namespace std; int main(){ double A,B,C; cin >> A >> B >> C; double res1 = sqrt((B*B) - (xi4 * A * C)); if(res1 || A == 0){ cout << "Impossivel calcular"<<"\n"; }else{ double res2 = (-B + res1)/(2 * A); double res3 = (-B - res1)/(2 * A); cout << "R1 = "<<res2<<"\n"; cout << "R2 = "<<res3<<"\n"; } return 0; }
#include <cstdlib> #include <cstring> #include <cstdio> #include <cmath> #include "dct.h" dct_trig_table dct_table_init(size_t size) { dct_trig_table table = (dct_trig_table)malloc(2*size*sizeof(double)); register double alpha = (PI/(double)size)*(PI/(double)size); for(size_t k1 = 0; k1 < size; ++k1) { for(size_t k2 = 0; k2 < size; ++k2) { for(size_t n = 0; n < size; ++n) { table[(k1*size)+k2] = cos(alpha * pow((n+0.5),2) * k1 * k2); } } } return table; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Patricia Aas (psmaas) */ #include "core/pch.h" #ifdef FEATURE_UI_TEST #include "adjunct/ui_test_framework/OpExtensionContainer.h" #include "adjunct/desktop_pi/DesktopAccessibilityExtension.h" /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpAccessibilityExtension::Create(OpAccessibilityExtension** extension, OpAccessibilityExtension* parent, OpAccessibilityExtensionListener* listener, ElementKind kind) { OpExtensionContainer* parent_container = static_cast<OpExtensionContainer*>(parent); *extension = NULL; OpExtensionContainer* container = new OpExtensionContainer(); if (container == NULL) return OpStatus::ERR_NO_MEMORY; OP_STATUS error = container->Init(parent_container, listener, kind); if (OpStatus::IsError(error)) { delete container; return error; } *extension = container; return OpStatus::OK; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::Init(OpExtensionContainer* parent, OpAccessibilityExtensionListener* listener, ElementKind kind) { m_extension_listener = listener; if (!m_extension_listener) return OpStatus::ERR; OpAccessibilityExtension* platform_extension = 0; RETURN_IF_ERROR(DesktopAccessibilityExtension::Create(&platform_extension, parent ? parent->GetExtension() : NULL, this, kind)); m_extension = platform_extension; return OpStatus::OK; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpExtensionContainer::~OpExtensionContainer() { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { OpExtensionContainer::Listener* listener = m_listeners.GetNext(iterator); listener->OnExtensionContainerDeleted(); } delete m_extension; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AddChild(OpExtensionContainer* child) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { OpExtensionContainer::Listener* listener = m_listeners.GetNext(iterator); RETURN_IF_ERROR(listener->OnChildAdded(child)); } return OpStatus::OK; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::BlockEvents(BOOL block) { m_extension->BlockEvents(block); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::SetWindow(OpWindow* window) { m_extension->SetWindow(window); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::SetState(AccessibilityState state) { m_extension->SetState(state); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::Moved() { m_extension->Moved(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::Resized() { m_extension->Resized(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::TextChanged() { m_extension->TextChanged(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::TextChangedByKeyboard() { m_extension->TextChangedByKeyboard(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::DescriptionChanged() { m_extension->DescriptionChanged(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::URLChanged() { m_extension->URLChanged(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::KeyboardShortcutChanged() { m_extension->KeyboardShortcutChanged(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::SelectedTextRangeChanged() { m_extension->SelectedTextRangeChanged(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::SelectionChanged() { m_extension->SelectionChanged(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::SetLive() { m_extension->SetLive(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::StartDragAndDrop() { m_extension->StartDragAndDrop(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::EndDragAndDrop() { m_extension->EndDragAndDrop(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::StartScrolling() { m_extension->StartScrolling(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::EndScrolling() { m_extension->EndScrolling(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void OpExtensionContainer::Reorder() { m_extension->Reorder(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtensionListener* OpExtensionContainer::GetListener() { return m_extension->GetListener(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityClicked() { return m_extension_listener->AccessibilityClicked(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilitySetValue(int value) { return m_extension_listener->AccessibilitySetValue(value); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilitySetText(const uni_char* text) { return m_extension_listener->AccessibilitySetText(text); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilitySetSelectedTextRange(int start, int end) { return m_extension_listener->AccessibilitySetSelectedTextRange(start, end); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ BOOL OpExtensionContainer::AccessibilityChangeSelection(SelectionSet flags, OpAccessibilityExtension* child) { return m_extension_listener->AccessibilityChangeSelection(flags, child); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ BOOL OpExtensionContainer::AccessibilitySetFocus() { return m_extension_listener->AccessibilitySetFocus(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ BOOL OpExtensionContainer::AccessibilitySetExpanded(BOOL expanded) { return m_extension_listener->AccessibilitySetExpanded(expanded); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetAbsolutePosition(OpRect &rect) { return m_extension_listener->AccessibilityGetAbsolutePosition(rect); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetValue(int &value) { return m_extension_listener->AccessibilityGetValue(value); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetMinValue(int &value) { return m_extension_listener->AccessibilityGetMinValue(value); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetMaxValue(int &value) { return m_extension_listener->AccessibilityGetMaxValue(value); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetText(OpString& str) { return m_extension_listener->AccessibilityGetText(str); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetSelectedTextRange(int &start, int &end) { return m_extension_listener->AccessibilityGetSelectedTextRange(start, end); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetDescription(OpString& str) { return m_extension_listener->AccessibilityGetDescription(str); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetURL(OpString& str) { return m_extension_listener->AccessibilityGetURL(str); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpExtensionContainer::AccessibilityGetKeyboardShortcut(ShiftKeyState* shifts, uni_char* kbdShortcut) { return m_extension_listener->AccessibilityGetKeyboardShortcut(shifts, kbdShortcut); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension::AccessibilityState OpExtensionContainer::AccessibilityGetState() { return m_extension_listener->AccessibilityGetState(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension::ElementKind OpExtensionContainer::AccessibilityGetRole() { return m_extension_listener->AccessibilityGetRole(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetAccessibleControlForLabel() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetAccessibleControlForLabel(); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetAccessibleLabelForControl() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetAccessibleLabelForControl(); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ int OpExtensionContainer::GetAccessibleChildrenCount() { return m_extension_listener->GetAccessibleChildrenCount(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetAccessibleChild(int n) { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetAccessibleChild(n); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetAccessibleChildOrSelfAt(int x, int y) { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetAccessibleChildOrSelfAt(x, y); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetNextAccessibleSibling() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetNextAccessibleSibling(); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetPreviousAccessibleSibling() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetPreviousAccessibleSibling(); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetLeftAccessibleObject() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetLeftAccessibleObject(); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetRightAccessibleObject() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetRightAccessibleObject(); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetDownAccessibleObject() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetDownAccessibleObject(); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetUpAccessibleObject() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetUpAccessibleObject(); return container ? container->GetExtension() : NULL; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpAccessibilityExtension* OpExtensionContainer::GetAccessibleFocusedChildOrSelf() { OpExtensionContainer* container = (OpExtensionContainer*)m_extension_listener->GetAccessibleFocusedChildOrSelf(); return container ? container->GetExtension() : NULL; } #endif // FEATURE_UI_TEST
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- * * Copyright (C) 2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OP_TIME_INFO_H #define OP_TIME_INFO_H class OpTimeInfo { public: double GetTimeUTC(); double GetRuntimeMS(); unsigned int GetRuntimeTickMS(); #if defined _MACINTOSH_ || defined UNIX OpTimeInfo(); int DaylightSavingsTimeAdjustmentMS(double t) { return IsDST(t) ? 36e5 : 0; } int GetTimezone() { return m_timezone; } private: double m_last_dst; ///< Last change to DST double m_next_dst; ///< Next change to DST bool m_is_dst; ///< Does DST apply between last and next ? long m_timezone; ///< GetTimezone() cache: seconds west of UTC, DST-adjusted. long ComputeTimezone(); ///< Update m_*_isdst, return value for m_timezone. bool IsDST(double t); ///< Determines whether DST applies to time t. #else int DaylightSavingsTimeAdjustmentMS(double t); int GetTimezone(); #endif }; #endif // OP_TIME_INFO_H
#include "LeagueEvent.h" #include "cjson/cJSON.h" /* * Update the league event. Probably do some supporting champions voting here? TODO. */ void LeagueEvent::Update(PtrLeagueEvent newEvent, int timestamp) { } cJSON* LeagueEvent::CreateJSON() { cJSON* newJson = cJSON_CreateObject(); cJSON_AddNumberToObject(newJson, GetTeamJsonId().c_str(), RelevantTeam); cJSON_AddNumberToObject(newJson, GetEventJsonId().c_str(), EventId); cJSON_AddItemToObject(newJson, GetAdditionalInfoJsonId().c_str(), cJSON_CreateString(AdditionalInfo.c_str())); cJSON_AddItemToObject(newJson, GetPlayerInstigatorJsonId().c_str(), cJSON_CreateString(PlayerInstigator.c_str())); cJSON* supporting = cJSON_CreateArray(); for (std::string name : SupportingPlayers) { cJSON_AddItemToArray(supporting, cJSON_CreateString(name.c_str())); } cJSON_AddItemToObject(newJson, GetSupportingPlayerJsonId().c_str(), supporting); cJSON_AddNumberToObject(newJson, GetTimestampJsonId().c_str(), Timestamp); cJSON_AddNumberToObject(newJson, GetKillTypeJsonId().c_str(), KillType); return newJson; }
#include <iostream> #include <vector> #include <algorithm> int n, list[1000000], dp[1000000]; int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); std::vector<int> buf; std::cin >> n; for(int i = 0; i < n; i++) { std::cin >> list[i]; } buf.push_back(list[0]); dp[0] = 1; for(int i = 1; i < n; i++) { if(buf.back() < list[i]) { buf.push_back(list[i]); dp[i] = buf.size(); } else { auto it = std::lower_bound(buf.begin(), buf.end(), list[i]); *it = list[i]; dp[i] = it - buf.begin() + 1; } } int sz = (int)buf.size(), keep = 1000000001; std::cout << sz << '\n'; std::vector<int> ans; for(int i = n - 1; i >= 0; i--) { if(sz == 0) { break; } if(sz == dp[i] && list[i] < keep) { ans.push_back(list[i]); sz--; keep = list[i]; } } for(auto x = ans.rbegin(); x != ans.rend(); x++) { std::cout << *x << ' '; } return 0; }
#include <map> #include <assert.h> #include "JFA.h" using namespace std; /*================================================================================================= DEFINES =================================================================================================*/ // Initial window dimensions #define MINLength 10 //有用 是论文中的Li /*================================================================================================= FUNCTIONS =================================================================================================*/ // If the buffers exist, delete them void ClearBuffers(Pixel* BufferA, Pixel* BufferB) { if (BufferA != NULL) { free(BufferA); BufferA = NULL; } if (BufferB != NULL) { free(BufferB); BufferB = NULL; } } // Jump Flooding Algorithm void ExecuteJumpFloodingDis(float* flowDisMap, Seeds Seeds, unsigned int xsize, unsigned int ysize) { int* disMap = (int*)malloc(sizeof(Pixel) * xsize * ysize); // Buffers Pixel* BufferA = NULL; Pixel* BufferB = NULL; // Buffer dimensions int BufferWidth = xsize; int BufferHeight = ysize; // Which buffer are we reading from? bool ReadingBufferA = true; // No seeds will just give us a black screen :P if (Seeds.size() < 1) { printf("Please create at least 1 seed.\n"); } printf("Executing the Jump Flooding algorithm...\n"); // Clear the buffers before we start //ClearBuffers(); // Allocate memory for the two buffers int* distmap = NULL; distmap = (int*)malloc(sizeof(int) *BufferWidth * BufferHeight); BufferA = (Pixel*)malloc(sizeof(Pixel) * BufferWidth * BufferHeight); BufferB = (Pixel*)malloc(sizeof(Pixel) * BufferWidth * BufferHeight); assert(BufferA != NULL && BufferB != NULL); // Initialize BufferA with (-1,-1), indicating an invalid closest seed. // We don't need to initialize BufferB because it will be written to in the first round. for (int y = 0; y < BufferHeight; ++y) { for (int x = 0; x < BufferWidth; ++x) { int idx = (y * BufferWidth) + x; BufferA[idx].x = -1; BufferA[idx].y = -1; } } // Put the seeds into the first buffer for (int i = 0; i < Seeds.size(); ++i) { Pixel& p = Seeds[i]; BufferA[(p.y * BufferWidth) + p.x] = p; } // Initial step length is half the image's size. If the image isn't square, // we use the largest dimension. int step = BufferWidth > BufferHeight ? BufferWidth / 2 : BufferHeight / 2; // We use this boolean to know which buffer we are reading from ReadingBufferA = true; // We read from the RBuffer and write into the WBuffer Pixel* RBuffer; Pixel* WBuffer; // Carry out the rounds of Jump Flooding while (step >= 1) { // Set which buffers we'll be using if (ReadingBufferA == true) { RBuffer = BufferA; WBuffer = BufferB; } else { RBuffer = BufferB; WBuffer = BufferA; } // Iterate over each Pixel to find its closest seed for (int y = 0; y < BufferHeight; ++y) { //循环每一个点 for (int x = 0; x < BufferWidth; ++x) { // The Pixel's absolute index in the buffer int idx = (y * BufferWidth) + x; // The Pixel's current closest seed (if any) Pixel& p = RBuffer[idx]; // Go ahead and write our current closest seed, if any. If we don't do this // we might lose this information if we don't update our seed this round. WBuffer[idx] = p; // This is a seed, so skip this Pixel if (p.x == x && p.y == y) continue; // This variable will be used to judge which seed is closest int dist; if (p.x == -1 || p.y == -1) dist = -1; // No closest seed has been found yet else dist = (p.x - x)*(p.x - x) + (p.y - y)*(p.y - y); // Current closest seed's distance //当前点到当前点已标记的暂时最邻近点的距离 // To find each Pixel's closest seed, we look at its 8 neighbors thusly: // (x-step,y-step) (x,y-step) (x+step,y-step) // (x-step,y ) (x,y ) (x+step,y ) // (x-step,y+step) (x,y+step) (x+step,y+step) for (int ky = -1; ky <= 1; ++ky) { for (int kx = -1; kx <= 1; ++kx) { //当前点(已被标记)的上下左右 // Calculate neighbor's row and column int ny = y + ky * step; int nx = x + kx * step; // If the neighbor is outside the bounds of the buffer, skip it if (nx < 0 || nx >= BufferWidth || ny < 0 || ny >= BufferHeight) continue; // Calculate neighbor's absolute index int nidx = (ny * BufferWidth) + nx; // Retrieve the neighbor Pixel& pk = RBuffer[nidx]; // If the neighbor doesn't have a closest seed yet, skip it if (pk.x == -1 || pk.y == -1) continue; //发现当前点的上(下左右)的点已经有了标记 // Calculate the distance from us to the neighbor's closest seed int newDist = (pk.x - x)*(pk.x - x) + (pk.y - y)*(pk.y - y); //新的距离是 当前点(x,y) 和 临近点pk // If dist is -1, it means we have no closest seed, so we might as well take this one //如果 当前点没有标记 就将 已有标记点的上(下左右)作为该点的最临近点 //如果 当前点已有标记 且当前点到已有标记(最临近)点上(下左右)的距离 < 当前点到已有标记点的距离 更新 // Otherwise, only adopt this new seed if it's closer than our current closest seed if (dist == -1 || newDist < dist) { WBuffer[idx] = pk; dist = newDist; } } } distmap[idx] = dist; } } // Halve the step. step /= 2; // Swap the buffers for the next round ReadingBufferA = !ReadingBufferA; } int minlen = 5; // for (unsigned int i = 0; i < xsize*ysize; i++) { distmap[i] = int(sqrt(distmap[i])); int tparm = int(distmap[i] / (minlen)); if ((tparm % 2)) { flowDisMap[i] = float((distmap[i] % minlen) * 255) / minlen; } else { flowDisMap[i] = float(1 - (distmap[i] % minlen)) * 255 / minlen; } } ClearBuffers(BufferA, BufferB); free(disMap); } // Jump Flooding Algorithm void ExecuteJumpFloodingVoi(int* VoiMap, const Seeds Seeds, unsigned int xsize, unsigned int ysize) { // Buffer dimensions int BufferWidth = xsize; int BufferHeight = ysize; // Buffers Pixel* BufferA = NULL; Pixel* BufferB = NULL; // Which buffer are we reading from? bool ReadingBufferA = true; // No seeds will just give us a black screen :P if (Seeds.size() < 1) { printf("Please create at least 1 seed.\n"); } printf("Executing the Jump Flooding algorithm for Voi...\n"); // Clear the buffers before we start ClearBuffers(BufferA, BufferB); // Allocate memory for the two buffers BufferA = (Pixel*)malloc(sizeof(Pixel) * BufferWidth * BufferHeight); BufferB = (Pixel*)malloc(sizeof(Pixel) * BufferWidth * BufferHeight); //assert(BufferA != NULL && BufferB != NULL); // Initialize BufferA with (-1,-1), indicating an invalid closest seed. // We don't need to initialize BufferB because it will be written to in the first round. for (int y = 0; y < BufferHeight; ++y) { for (int x = 0; x < BufferWidth; ++x) { int idx = (y * BufferWidth) + x; BufferA[idx].x = -1; BufferA[idx].y = -1; } } // Put the seeds into the first buffer for (int i = 0; i < Seeds.size(); ++i) { Pixel p = Seeds[i]; BufferA[(p.y * BufferWidth) + p.x] = p; } // Initial step length is half the image's size. If the image isn't square, // we use the largest dimension. int step = BufferWidth > BufferHeight ? BufferWidth / 2 : BufferHeight / 2; // We use this boolean to know which buffer we are reading from ReadingBufferA = true; // We read from the RBuffer and write into the WBuffer Pixel* RBuffer; Pixel* WBuffer; // Carry out the rounds of Jump Flooding while (step >= 1) { // Set which buffers we'll be using if (ReadingBufferA == true) { RBuffer = BufferA; WBuffer = BufferB; } else { RBuffer = BufferB; WBuffer = BufferA; } // Iterate over each Pixel to find its closest seed for (int y = 0; y < BufferHeight; ++y) { //循环每一个点 for (int x = 0; x < BufferWidth; ++x) { // The Pixel's absolute index in the buffer int idx = (y * BufferWidth) + x; // The Pixel's current closest seed (if any) Pixel& p = RBuffer[idx]; // Go ahead and write our current closest seed, if any. If we don't do this // we might lose this information if we don't update our seed this round. WBuffer[idx] = p; // This is a seed, so skip this Pixel if (p.x == x && p.y == y) continue; // This variable will be used to judge which seed is closest float dist; if (p.x == -1 || p.y == -1) dist = -1; // No closest seed has been found yet else dist = (p.x - x)*(p.x - x) + (p.y - y)*(p.y - y); // Current closest seed's distance //当前点到当前点已标记的暂时最邻近点的距离 // To find each Pixel's closest seed, we look at its 8 neighbors thusly: // (x-step,y-step) (x,y-step) (x+step,y-step) // (x-step,y ) (x,y ) (x+step,y ) // (x-step,y+step) (x,y+step) (x+step,y+step) for (int ky = -1; ky <= 1; ++ky) { for (int kx = -1; kx <= 1; ++kx) { //当前点(已被标记)的上下左右 // Calculate neighbor's row and column int ny = y + ky * step; int nx = x + kx * step; // If the neighbor is outside the bounds of the buffer, skip it if (nx < 0 || nx >= BufferWidth || ny < 0 || ny >= BufferHeight) continue; // Calculate neighbor's absolute index int nidx = (ny * BufferWidth) + nx; // Retrieve the neighbor Pixel& pk = RBuffer[nidx]; // If the neighbor doesn't have a closest seed yet, skip it if (pk.x == -1 || pk.y == -1) continue; //发现当前点的上(下左右)的点已经有了标记 // Calculate the distance from us to the neighbor's closest seed float newDist = (pk.x - x)*(pk.x - x) + (pk.y - y)*(pk.y - y); //新的距离是 当前点(x,y) 和 临近点pk // If dist is -1, it means we have no closest seed, so we might as well take this one //如果 当前点没有标记 就将 已有标记点的上(下左右)作为该点的最临近点 //如果 当前点已有标记 且当前点到已有标记(最临近)点上(下左右)的距离 < 当前点到已有标记点的距离 更新 // Otherwise, only adopt this new seed if it's closer than our current closest seed if (dist == -1 || newDist < dist) { WBuffer[idx] = pk; dist = newDist; } } } } } // Halve the step. step /= 2; // Swap the buffers for the next round ReadingBufferA = !ReadingBufferA; } Pixel* Buffer = (ReadingBufferA == true) ? BufferA : BufferB; for (int y = 0; y < BufferHeight; ++y) { for (int x = 0; x < BufferWidth; ++x) { int idx = (y * BufferWidth) + x; int seedIdx = Buffer[idx].y * BufferWidth + Buffer[idx].x; VoiMap[idx] = seedIdx; } } ClearBuffers(BufferA, BufferB); }
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { // Create Head Node that will be returned in the end ListNode* head = new ListNode(); // Create Node that always will be current ListNode* current = head; int addition = 0; int val; // Create new Nodes and calculate value until both input Nodes are not empty while( l1 != nullptr || l2 != nullptr ) { // Count value only from existing Nodes if ( l1 == nullptr ) { val = l2->val + addition; } else if ( l2 == nullptr ) { val = l1->val + addition; } else { val = l1->val + l2->val + addition; } // Find addition that should be added in the next step or to last Node. Value should be less than 10 addition = val / 10; if (val > 9) { val -= 10; } // Create new Node to next of the current and make new created Node as current current->next = new ListNode(val); current = current->next; // Switch to next Node if it's possible if ( l1 != nullptr) { l1 = l1->next; } if ( l2 != nullptr) { l2 = l2->next; } } // In case addition still exist - create new Node with addition value if(addition > 0) { current->next = new ListNode(addition); } // Return next Node of Head because first Node always will be empty return head->next; } };
#pragma once #ifndef BALL_H #define BALL_H #include <SFML/Graphics.hpp> #include "Collidable.h" #define PI 3.14159265 class Ball { private: float x, y; int radius; int speed; float direction; int lastCollision; sf::CircleShape image; public: Ball(int, int, float); int getX(); int getY(); void setX(float); void setY(float); int getLastCollision(); void setLastCollision(int); float getDirection(); int getSpeed(); sf::CircleShape getImage(); void setPosition(float, float); void setDirection(float); bool isOutOfLeftBound(); bool isOutOfRightBound(int); bool hasCollided(Collidable*); sf::Vector2f getLeftEdgeCoordinates(); sf::Vector2f getRightEdgeCoordinates(); sf::Vector2f getTopEdgeCoordinates(); sf::Vector2f getBottomEdgeCoordinates(); void move(); }; #endif
#include "MatMath.h" // constructors MatMath::MatMath(void) { } MatMath::~MatMath(void) { } /* vec3::vec3() {} vec3::vec3(float a, float b, float c) { v[0] = a; v[1] = b; v[2] = c; } void vec3::normalize() { float magnitude = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); v[0] /= magnitude; v[1] /= magnitude; v[2] /= magnitude; } vec2::vec2() {} vec2::vec2(float x, float y) { vec2::x = x; vec2::y = y; } vec2::vec2(vec2& copyFrom) { vec2::x = copyFrom.x; vec2::y = copyFrom.y; } bool vec2::operator==(vec2& isEqual) { return vec2::x == isEqual.x && vec2::y == isEqual.y; } void vec2::normalize() { float magnitude = sqrt(x * x + y * y); x /= magnitude; y /= magnitude; } float vec2::dot(vec2 vec) { return x * vec.x + y * vec.y; } float vec2::dot(float x2, float y2) { return x * x2 + y * y2; } */ mat4::mat4() {} // note: entered in rows, but stored in columns mat4::mat4 (float a, float b, float c, float d, float e, float f, float g, float h, float i, float j, float k, float l, float mm, float n, float o, float p) { m[0] = a; m[1] = e; m[2] = i; m[3] = mm; m[4] = b; m[5] = f; m[6] = j; m[7] = n; m[8] = c; m[9] = g; m[10] = k; m[11] = o; m[12] = d; m[13] = h; m[14] = l; m[15] = p; } // matrices mat4 MatMath::identity_mat4() { return mat4 ( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); } mat4 MatMath::zero_mat4() { return mat4 ( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f ); } mat4 mat4::operator* (const mat4& rhs) { mat4 r = MatMath::zero_mat4 (); int r_index = 0; for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { float sum = 0.0f; for (int i = 0; i < 4; i++) { sum += rhs.m[i + col * 4] * m[row + i * 4]; } r.m[r_index] = sum; r_index++; } } return r; } // matrix transformations mat4 MatMath::translate (const mat4& m, const vec3& v) { mat4 m_t = MatMath::identity_mat4 (); m_t.m[12] = v.x; m_t.m[13] = v.y; m_t.m[14] = v.z; return m_t * m; } // dot product float MatMath::dot(float x1, float y1, float z1, float x2, float y2, float z2) { return x1 * x2 + y1 * y2 + z1 * z2; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CamProjectile.h" #include "NewProjectile.generated.h" /** * */ UCLASS() class CAM_API ANewProjectile : public ACamProjectile { GENERATED_BODY() public: ANewProjectile(const FObjectInitializer& ObjectInitializer); void Tick(float DeltaTime) override; };
#include "gtest/gtest.h" #include "print.h" TEST(print, PrintConsole) { std::stringstream is{}; PrintConsole print{is}; std::vector<std::string> cmd_pool{"first", "second", "third"}; print.print_cmd_pool(cmd_pool); EXPECT_EQ(is.str(), "Bulk: first, second, third\n"); } TEST(print, PrintFile) { PrintFile print{}; std::time_t time = std::time(nullptr); print.set_first_cmd_time(time); std::vector<std::string> cmd_pool{"first", "second", "third"}; print.print_cmd_pool(cmd_pool); std::fstream fs{}; std::string file_name = "bulk" + std::to_string(time) + ".log"; fs.open(file_name, std::ios::in); EXPECT_TRUE(fs.is_open()); std::string str{}; std::getline(fs, str); EXPECT_EQ(str, "Bulk: first, second, third"); }
#include <iostream> #include <thread> #include <mutex> using namespace std; mutex semaforo; void imprimeCaractere(int n, char c){ semaforo.lock(); for(int i = 1; i<= n; i++){ cout << c; } cout << endl; semaforo.unlock(); } int main() { thread t1(imprimeCaractere, 50, '*'); thread t2(imprimeCaractere, 50, '$'); thread t3(imprimeCaractere, 50, '#'); thread t4(imprimeCaractere, 50, '@'); t1.join(); t2.join(); t3.join(); t4.join(); return 0; }
#include "../Objects.h" Shape::Shape(gfx::Canvas* canvasToSet, std::initializer_list<Point> pointsToSet, int thicknessToSet, Color borderColorToSet) : Primitive (canvasToSet, thicknessToSet, borderColorToSet) { _points.insert(_points.end(), pointsToSet.begin(), pointsToSet.end()); assert(_points.size() > 2); for (int i = 0; i < _points.size() - 1; ++i) { _lines.push_back(new Line(_canvas, _points[i], _points[i+1], thicknessToSet, borderColorToSet)); _lines[i]->parent(this); } } void Shape::draw() { fill(Color(255,0,0)); //TODO: fixme for (int i = 0; i < _lines.size(); ++i) { _lines[i]->draw(); } } void Shape::fill(Color color) { // FIXME: fatal crash after changing to floating point number //_fillScanLine(color); } Shape::~Shape() { for (int i = 0; i < _lines.size(); ++i) { delete _lines[i];} } void Shape::_fillScanLine(Color fillColor) { std::vector<Edge> edges; std::vector<Edge> edgeBuffer; int x,y; for(int i = 0; i < _lines.size(); ++i) { if (_lines[i]->location().y() < _lines[i]->endPoint().y()) edges.push_back(Edge(_lines[i]->location() * transformationMatrix(), _lines[i]->endPoint())); else edges.push_back(Edge(_lines[i]->endPoint(), _lines[i]->location() * transformationMatrix())); } if (edges.size() > 0) { y = edges[0].p1().y(); x = edges[0].p1().x(); } while (!edges.empty() || !edgeBuffer.empty()) { for(int i = 0; i < edges.size(); i++) { // move from edges edge to edgeBuffer if edgePoint1.y == y if (edges[i].p1().y() == y) { edgeBuffer.push_back(edges[i]); edges.erase(edges.begin() + i); i--; } } sort(edgeBuffer.begin(), edgeBuffer.end(), [](Edge e1, Edge e2) { if (e1.p1().x() != e2.p1().x()) return e1.p1().x() < e2.p1().x(); else return e1.p2().x() < e2.p2().x(); }); // loop through edgeBuffers std::vector<int> pointsInLine; for (int j = 0; j < edgeBuffer.size(); j++) { // calculate x in respect to y if (edgeBuffer[j].bVertical()) { pointsInLine.push_back(edgeBuffer[j].p1().x()); } else if (edgeBuffer[j].a() != 0) { x = round(double(y - edgeBuffer[j].b()) / edgeBuffer[j].a()); pointsInLine.push_back(x); } else { pointsInLine.push_back(edgeBuffer[j].p1().x()); } } for (int j = 0; j < pointsInLine.size() - 1; j += 2) { if (pointsInLine[j] == pointsInLine[j+1]) { j--; continue; } for (int x = pointsInLine[j] + _thickness; x < pointsInLine[j+1]; ++x) { _canvas->px(x, y, fillColor, motionBlur()); } } // remove edges from edgeBuffer if y == edgePoint2.y for (int j = 0; j < edgeBuffer.size(); j++) { if (edgeBuffer[j].p2().y() == y) { edgeBuffer.erase(edgeBuffer.begin() + j); j--; } } y++; } }
#include <iostream> int binarySearch(int* array, int left, int rigth, int number) { if (rigth >= left) { int mid = left + (rigth - left) / 2; if (array[mid] == number) { return mid; } if (array[mid] > number) { return binarySearch(array, left, mid -1, number); } return binarySearch(array, mid + 1, rigth, number); } return -1; } void sortingArray(int* array, int size) { for (int i = 0; i < size; ++i) { for (int j = 0; j < size - i - 1; ++j) { if (array[j] > array[j+1]) { int tmp = array[j]; array[j] = array[j+1]; array[j+1] = tmp; } } } } void validNumber(int& number) { while (std::cin.fail() || 1 > number) { std::cout << "Invalid Value: Try again!" << std::endl; std::cin.clear(); std::cin.ignore(256,'\n'); std::cout << "Please enter the intager number: "; std::cin>> number; } } int main() { int size = 0; std::cout << "Enter size of array: "; std::cin >> size; validNumber(size); std::cout << "Enter elemets: "; int* array = new int[size]; for (int i = 0; i < size; ++i) { std::cin >> array[i]; validNumber(array[i]); } sortingArray(array, size); std::cout << "======Array=====" << std::endl; for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; } std::cout << std::endl; int searchedNumber = 0; std::cout << "Enter searched number: "; std::cin >> searchedNumber; validNumber(searchedNumber); int position = binarySearch(array, 0, size -1, searchedNumber); std::cout << std::endl; if (-1 == position) { std::cout << searchedNumber << " is not in the array!" << std::endl; } else { std::cout << searchedNumber << " found at index " << position << std::endl; } delete[] array; return 0; }
/* kamalsam */ #include<stdio.h> #include<algorithm> #include<iostream> using namespace std; int main() { int i,j,n,t; scanf("%d",&t); for(i=0;i<t;i++) { scanf("%d",&n); int count,k,best; long ent[n],exi[n]; for(j=0;j<n;j++) scanf("%ld%ld",&ent[j],&exi[j]); sort(exi,exi+n); sort(ent,ent+n); best=count=0; for(j=0,k=0;j<n&&k<n;) { if(ent[j]<exi[k]) count++, j++; else count--, k++; best=max(count,best); } printf("%d\n",best); } return 0; }
// PileShuffleOptimization.cpp : Defines the entry point for the console application. // Find optimal number of piles for pile shuffling to maximize probability of // Two lands per pile // Uses Hypergeometric distribution h(x; p, n, k) = [kCx][p-kCn-x]/[pCn] // p: number of items in population // k: Number of items in population that are successes // n: Number of items in sample(size of piles) // x: Number of items in sample(pile) that are success #include "RandomUtilities.h" #include <iostream> using namespace std; const int P = 100; const int K = 40; const int N = 3; const int X = 2; const int TRIALS = 10000; float aCb(int, int); float hyper(int, int, int, int); int main() { //for RandomUtilities randomizeSeed(); float avgTrials = 0; for (int i = 0; i < TRIALS; ++i) { int n = N; int k = K; //Set population equal to non sucesses for management of population int p = P - k; int piles = 0; float dist = 0; float avgH = 0; int sub = 0; while (p > -1) { dist = hyper(X, p + k, n, k); //cout << dist << endl; avgH += dist; if (k < n) { sub = randInt(0, k); } else { sub = randInt(0, n); } k -= sub; p -= (sub + n - sub); ++piles; } avgH /= piles; avgTrials += avgH; } avgTrials /= TRIALS; cout << "Average Hypergeometric Distribution over " << TRIALS << " trials: " << avgTrials << endl; } float aCb(int n, int k) { if (k > n) return 0; if (k * 2 > n) k = n - k; if (k == 0) return 1; float result = n; for (int i = 2; i <= k; ++i) { result *= (n - i + 1); result /= i; } return result; } float hyper(int x, int p, int n, int k) { if (n > p) return 0; if (n < x) return 0; if (k == p) return 1; else { return ((aCb(k, x) * aCb((p - k), (n - x))) / aCb(P, n)); } }
//Global variables const int ledPinR1 = 13; const int ledPinG1 = 12; const int ledPinR2 = 10; const int ledPinY2 = 9; const int ledPinG2 = 8; const int buttonPin = 2; int buttonState = 0; int prevButtonState = HIGH; void setup(){ //Setting all pins to input/output pinMode(ledPinR1, OUTPUT); pinMode(ledPinG1, OUTPUT); pinMode(ledPinR2, OUTPUT); pinMode(ledPinY2, OUTPUT); pinMode(ledPinG2, OUTPUT); pinMode(buttonPin, INPUT); } void loop(){ //Setting initials: green light for cars, read for walkers digitalWrite(ledPinG2, HIGH); digitalWrite(ledPinR1, HIGH); digitalWrite(ledPinG1, LOW); digitalWrite(ledPinR2, LOW); digitalWrite(ledPinY2, LOW); //Checking if button is pushed buttonState = digitalRead(buttonPin); //Check if button is pressed == LOW if ((buttonState == LOW) && (prevButtonState == HIGH)) { delay(1000); digitalWrite(ledPinR2, LOW); //STATE 4 digitalWrite(ledPinY2, HIGH); //yellow light for cars delay(1000); digitalWrite(ledPinG2, LOW); //STATE 1 digitalWrite(ledPinR2, HIGH); //red light for cars delay(2000); digitalWrite(ledPinR1, LOW); digitalWrite(ledPinG1, HIGH); //green light for walkers delay(5000); digitalWrite(ledPinG1, LOW); digitalWrite(ledPinR1, HIGH); //red light for walkers delay(2000); digitalWrite(ledPinR2, HIGH); //STATE 2 digitalWrite(ledPinY2, HIGH); //yellow and red for cars delay(1000); digitalWrite(ledPinR2, LOW); //STATE 3 digitalWrite(ledPinY2, LOW); digitalWrite(ledPinG2, HIGH); //green light for cars } else { digitalWrite(ledPinG1, LOW); // turns green LED off } prevButtonState = buttonState; //sets previous button state }
#include<stdio.h> #include<conio.h> int main(){ int x=0,y=1,z=1; printf("Enter a number :"); scanf("%d",&x); while(y<=x){ z=z*y; z<x; y=y+1; } if(z==0){ printf("\nError"); }else printf("\nThe factorial of %d = %d",x,z); return 0; getch(); }
#ifndef EXPENSE_CATEGORY_H #define EXPENSE_CATEGORY_H #include "base_entity.h" #include "models/instance.h" class ExpenseCategory : public BaseEntity { Q_OBJECT Q_PROPERTY(Instance* instance READ getInstance WRITE setInstance NOTIFY propChanged) Q_PROPERTY(QString name READ getName WRITE setName NOTIFY propChanged) Q_PROPERTY(QString description READ getDescription WRITE setDescription NOTIFY propChanged) protected: Instance * _instance; QString _name; QString _description; public: ExpenseCategory(QObject * parent = 0); public slots: Instance* getInstance(); QString getName(); QString getDescription(); void setInstance(Instance * instance); void setName(QString name); void setDescription(QString description); static void createFromList(Instance * instance, QStringList names); static QList<ExpenseCategory*> getByInstanceId(uuid instanceId); signals: void propChanged(); }; #endif // EXPENSE_CATEGORY_H
#include<iostream> #include<list> #include<queue> #include<map> using namespace std; //Adj List Implementation for generic Nodes template<typename T> class Graph{ //Array of Linked Lists of size V, V LL's are there map<T,list<T> > adjList; public: Graph(){ } void addEdge(T u,T v,bool bidir=true){ adjList[u].push_back(v); if(bidir){ adjList[v].push_back(u); } } void printAdjList(){ for(auto row : adjList){ T key = row.first; cout<<key<<"->"; for(auto element:row.second){ cout<<element<<","; } cout<<endl; } } void dfsHelper(T node,map<T,bool> &visited){ visited[node]=true; cout<<node<<" "; for(T neighbour: adjList[node]){ if(!visited[neighbour]){ dfsHelper(neighbour,visited); } } } void dfs(T src){ map<T,bool> visited; dfsHelper(src,visited); } }; int main(){ Graph<int> g; g.addEdge(0,1); g.addEdge(1,2); g.addEdge(0,4); g.addEdge(2,4); g.addEdge(3,2); g.addEdge(2,3); g.addEdge(3,5); g.addEdge(3,4); g.dfs(0); return 0; }
#include <cstdio> #include <vector> #include <algorithm> using namespace std; const int INF = 0xfffffff; int graph[1010][1010]; bool visited[1010]; int n, m, k, con; int deleteed; void dfs(int node){ if(node == con) return; visited[node] = true; for(int i = 1; i <= n; i++){ if(!visited[i] && graph[node][i] == 1){ dfs(i); } } } int main(){ for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ graph[i][j] = graph[j][i] = INF; } } scanf("%d%d%d", &n, &m, &k); for(int i = 0; i < m; i++){ int a, b; scanf("%d%d", &a, &b); graph[a][b] = graph[b][a] = 1; } for(int i = 0; i < k; i++){ scanf("%d", &con); fill(visited, visited + 1010, false); int block = 0; for(int i = 1; i <= n; i++){ if(i != con && !visited[i]){ dfs(i); block++; } } printf("%d\n", block - 1); } return 0; }
#include "stdafx.h" #include "RenderStates.h" // Staitc Values ID3D11RasterizerState* Jaraffe::RenderStates::m_WireframeRS = 0; // 와이어프레임 랜더링. ID3D11RasterizerState* Jaraffe::RenderStates::m_SolidRS = 0; // 일단 고형체 랜더링. void Jaraffe::RenderStates::InitAll(ID3D11Device * device) { // // WireframeRS // D3D11_RASTERIZER_DESC wireframeDesc; ZeroMemory(&wireframeDesc, sizeof(D3D11_RASTERIZER_DESC)); wireframeDesc.FillMode = D3D11_FILL_WIREFRAME; wireframeDesc.CullMode = D3D11_CULL_BACK; wireframeDesc.FrontCounterClockwise = false; wireframeDesc.DepthClipEnable = true; HR(device->CreateRasterizerState(&wireframeDesc, &m_WireframeRS)); // // NoCullRS // D3D11_RASTERIZER_DESC noCullDesc; ZeroMemory(&noCullDesc, sizeof(D3D11_RASTERIZER_DESC)); noCullDesc.FillMode = D3D11_FILL_SOLID; noCullDesc.CullMode = D3D11_CULL_NONE; noCullDesc.FrontCounterClockwise = false; noCullDesc.DepthClipEnable = true; HR(device->CreateRasterizerState(&noCullDesc, &m_SolidRS)); } void Jaraffe::RenderStates::DestroyAll() { }
#pragma once #include "bricks/config.h" #if BRICKS_CONFIG_AUDIO_FFMPEG #include "bricks/core/copypointer.h" #include "bricks/collections/array.h" namespace Bricks { namespace IO { class Stream; } } extern "C" { struct AVFormatContext; struct AVStream; struct AVCodec; struct AVPacket; struct AVFrame; } namespace Bricks { namespace Audio { class FFmpegDecoder : public Object, NoCopy { protected: size_t streamIndex; AVFormatContext* format; AutoPointer<IO::Stream> ioStream; void* ffmpegBuffer; static const int ffmpegBufferSize = 0x1000; bool currentTimeKnown; s64 currentTime; Bricks::Collections::Array<AVPacket> packetQueue; Bricks::Collections::Array<int> openStreams; public: FFmpegDecoder(IO::Stream* stream); ~FFmpegDecoder(); AVFormatContext* GetFormatContext() const { return format; } IO::Stream* GetStream() const { return ioStream; } AVCodec* OpenStream(int streamIndex); void CloseStream(int streamIndex); bool IsStreamOpen(int streamIndex); bool ReadPacket(AVPacket* packet, int streamIndex = -1); void FreePacket(AVPacket* packet); void QueuePacket(AVPacket* packet); bool DequeuePacket(AVPacket* packet, int streamIndex = -1); void FlushQueue(); void SeekFrame(s64 time); s64 GetFrameTime(); void ResetFrameTime(); }; } } #endif
/*************************************************************************************************** vector3.h Simple Vector3 class mainly destined to hide the ugliness of D3DXVECTOR3 while still being interchangeable with it by David Ramos ***************************************************************************************************/ #pragma once #include <D3dx9math.h> class cVector3 : public D3DXVECTOR3 { public: // Inherit constructors (not working in VS2012) // using D3DXVECTOR3::D3DXVECTOR3; cVector3() {} cVector3(float val) : D3DXVECTOR3(val, val, val) {} cVector3(const D3DXVECTOR3& other) : D3DXVECTOR3(other) {} cVector3(float x, float y, float z) : D3DXVECTOR3(x, y, z) {} cVector3& RotateAroundY(float angle); cVector3& RotateAroundX(float angle); void SetNormalized(); bool IsNormalized() const; float Length() const; float LengthSqr() const; cVector2 GetXZ() const; bool IsZero() const; enum class eAxis { X, Y, Z }; template <eAxis axis> float Get() const; // In newer compiler versions these could be constexpr, here we rely on RVO static cVector3 XAXIS() { return cVector3(1.0f, 0.0f, 0.0f); } static cVector3 YAXIS() { return cVector3(0.0f, 1.0f, 0.0f); } static cVector3 ZAXIS() { return cVector3(0.0f, 0.0f, 1.0f); } static cVector3 ZERO() { return cVector3(0.0f, 0.0f, 0.0f); } static cVector3 ONE() { return cVector3(1.0f, 1.0f, 1.0f); } }; inline cVector3 Normalize(const cVector3& v); inline float Dot(const cVector3& lhs, const cVector3& rhs); inline cVector3 Cross(const cVector3& lhs, const cVector3& rhs); inline cVector3 ProjectVectorOntoPlane(const cVector3& vector, const cVector3& plane_normal); inline cVector3 Multiply(const cVector3& lhs, const cVector3& rhs); //---------------------------------------------------------------------------- inline bool IsSimilar(const cVector3& lhs, const cVector3& rhs, float epsilon = EPSILON) { return IsSimilar(lhs.x, rhs.x, epsilon) && IsSimilar(lhs.y, rhs.y, epsilon) && IsSimilar(lhs.z, rhs.z, epsilon); } //---------------------------------------------------------------------------- inline cVector3& cVector3::RotateAroundY(float angle) { // Negate angle to be more left-handedness-correct const float cosine = cos(-angle); const float sine = sin(-angle); *this = cVector3( (x * cosine) - (z * sine) , y , (x * sine) + (z * cosine)); return *this; } //---------------------------------------------------------------------------- inline cVector3& cVector3::RotateAroundX(float angle) { // Negate angle to be more left-handedness-correct const float cosine = cos(angle); const float sine = sin(angle); *this = cVector3( x , (y * cosine) - (z * sine) , (y * sine) + (z * cosine)); return *this; } //---------------------------------------------------------------------------- inline void cVector3::SetNormalized() { D3DXVec3Normalize(this, this); } //---------------------------------------------------------------------------- inline float cVector3::Length() const { return D3DXVec3Length(this); } //---------------------------------------------------------------------------- inline float cVector3::LengthSqr() const { return D3DXVec3LengthSq(this); } //---------------------------------------------------------------------------- inline cVector2 cVector3::GetXZ() const { return cVector2(x, z); } //---------------------------------------------------------------------------- inline bool cVector3::IsZero() const { return !!(*this == cVector3::ZERO()); } //---------------------------------------------------------------------------- template <> inline float cVector3::Get<cVector3::eAxis::X>() const { return x; } //---------------------------------------------------------------------------- template <> inline float cVector3::Get<cVector3::eAxis::Y>() const { return y; } //---------------------------------------------------------------------------- template <> inline float cVector3::Get<cVector3::eAxis::Z>() const { return z; } //---------------------------------------------------------------------------- inline cVector3 Normalize(const cVector3& v) { cVector3 result; return *D3DXVec3Normalize(&result, &v); } //---------------------------------------------------------------------------- inline bool cVector3::IsNormalized() const { return IsSimilar(Length(), 1.0f); }; //---------------------------------------------------------------------------- inline float Dot(const cVector3& lhs, const cVector3& rhs) { return D3DXVec3Dot(&lhs, &rhs); } //---------------------------------------------------------------------------- inline cVector3 Cross(const cVector3& lhs, const cVector3& rhs) { cVector3 result; return *D3DXVec3Cross(&result, &lhs, &rhs); } //---------------------------------------------------------------------------- inline cVector3 ProjectVectorOntoPlane(const cVector3& vector, const cVector3& plane_normal) { CPR_assert(plane_normal.IsNormalized(), "The plane normal must be normalized!"); // V||N = N x (V x N) return Cross(plane_normal, Cross(vector, plane_normal)); } //---------------------------------------------------------------------------- inline cVector3 ReflectVectorOntoPlane(const cVector3& vector, const cVector3& plane_normal) { CPR_assert(plane_normal.IsNormalized(), "The plane normal must be normalized!"); return (vector - (plane_normal * Dot(plane_normal, vector) * 2.0f)); } //---------------------------------------------------------------------------- inline cVector3 Multiply(const cVector3& lhs, const cVector3& rhs) { return cVector3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z); }
#pragma once #include "wrapper_glfw.h" #include <glm/glm.hpp> #include "terrain_object.h" class terrain_loader { public: terrain_object *heightfield; int octaves; GLfloat perlin_scale, perlin_freq, land_size, sealevel; terrain_loader(); };
#pragma once #include "GlobalHeader.h" #include <stdexcept> // std::logic_error #include <span.h> // gsl::span #include "Amount.h" // fa::Amount namespace fa { //! Enum for the different kinds of nutrients enum class NutrientType { // TODO: have this contain all the different kinds of nutrients VitaminA, // WARNING: keep amountOfNutrientTypes synchronized with this enum VitaminC, VitaminK, VitaminE, VitaminD, VitaminB1, VitaminB2, VitaminB3, VitaminB6, VitaminB9, VitaminB12, Calcium, Iron, Selen, Phosphorus, Potassium, Zinc, Magnesium, Water, Protein, Fat, Carbohydrates, Kcal }; static auto constexpr amountOfNutrientTypes{ static_cast<size_type>(23U) }; // make sure this corresponds with the enum //! returns a textual representation of a NutrientType enumerator String toString(NutrientType nutrientType); //! returns the corresponding NutrientType enumerator for the given string NutrientType toNutrientType(String const &string); //! prints a NutrientType to an OStream OStream &operator<<(OStream &os, NutrientType nutrientType); enum class NutrientKind { Micro, Macro, Kcal }; OStream &operator<<(OStream &os, NutrientKind nutrientKind); class NoSuchNutrientException : public std::logic_error { public: using this_type = NoSuchNutrientException; explicit NoSuchNutrientException(std::string const &message) noexcept; virtual ~NoSuchNutrientException() override; virtual char const *what() const noexcept override; }; // END of class NoSuchNutrientException class NutrientImpl final { public: using this_type = NutrientImpl; using NutrientAmount = Amount; using ConstStringSpan = gsl::span<const Char>; NutrientImpl(NutrientType nutrientType, String description, String overdoseDescription, NutrientAmount minimumDose, NutrientAmount maximumDose, NutrientAmount optimumDose, NutrientAmount storage); // I have kicked the NutrientKind out of the parameters, because otherwise the client // would be able to declare VitaminA as a macro nutrient. this_type &operator=(this_type const &) = delete; this_type &operator=(this_type &&) = delete; NutrientImpl(this_type const &) = default; NutrientImpl(this_type &&) = default; NutrientType getNutrientType() const noexcept; ConstStringSpan getName() const noexcept; ConstStringSpan getDescription() const noexcept; ConstStringSpan getOverDoseDescription() const noexcept; NutrientAmount getMinimumDose() const noexcept; NutrientAmount getMaximumDose() const noexcept; NutrientAmount getOptimumDose() const noexcept; NutrientAmount getStorage() const noexcept; bool isMicro() const noexcept; bool isMacro() const noexcept; bool isKcal() const noexcept; friend OStream &operator<<(OStream &os, this_type const &obj); private: NutrientType nutrientType_; String const name_; // initialized by calling toString on nutrientType_ String const description_; String const overdoseDescription_; NutrientAmount const minimumDose_; NutrientAmount const maximumDose_; NutrientAmount const optimumDose_; NutrientAmount const storage_; NutrientKind nutrientKind_; }; // END of class NutrientImpl NutrientKind toNutrientKind(const NutrientType &type); } // END of namespace fa
#include "file_utils.h" const char* getFileSystemContents() { // Get the Current Working Directory char *cwdBuffer = new char[512]; sprintf(cwdBuffer, "%s/%s", getcwd(cwdBuffer, 1024), "UDPClient/share/"); DIR *open = opendir(cwdBuffer); struct stat filestat; if (open == NULL) { printf("%s%s\n", "ERROR: Directory structure is incorrect. The client should ", "be run using the makefile with a share folder inside the UDPClient folder"); exit(1); } std::string listings_str = ""; struct dirent *dirp; while ((dirp = readdir(open)) != NULL) { std::string filename = cwdBuffer; filename += dirp->d_name; if (stat(filename.c_str(), &filestat)) continue; // Populates filestat if (S_ISDIR(filestat.st_mode)) continue; // Breaks loop if not file int f_size = getFileSize(filename.c_str()); // This is a very ugly implementation but it means I don't have to // allocate another C String just to use sprintf for formatting listings_str += dirp->d_name; listings_str += "|"; listings_str += std::to_string(f_size); listings_str += "\n"; } return listings_str.c_str(); } int getFileSize(const char *fileName) { std::ifstream file(fileName, std::ifstream::in | std::ifstream::binary); if (!file.good()) { printf("%s\n", "File is not in good state. The given file size will be incorrect."); } file.seekg(0, std::ios::end); int fileSize = file.tellg(); file.close(); return fileSize; }
// $Id: bigint.cpp,v 1.76 2016-06-14 16:34:24-07 - - $ #include <cstdlib> #include <exception> #include <stack> #include <stdexcept> using namespace std; #include "bigint.h" #include "debug.h" #include "relops.h" bigint::bigint(long that) : uvalue(that), is_negative(that < 0) { DEBUGF('~', this << " -> " << uvalue) } bigint::bigint(const ubigint& uvalue, bool is_negative) : uvalue(uvalue), is_negative(is_negative) { } bigint::bigint(const string& that) { is_negative = that.size() > 0 and that[0] == '_'; //cout << "uvalue = ubigint" << endl; uvalue = ubigint(that.substr(is_negative ? 1 : 0)); } bigint bigint::operator+() const { return *this; } bigint bigint::operator-() const { return { uvalue, not is_negative }; } bigint bigint::operator+(const bigint& that) const { bool sign; ubigint result; bigint answer; if (is_negative == that.is_negative) { sign = that.is_negative; if (*this < that) { result = that.uvalue + uvalue; } else { result = uvalue + that.uvalue; } } else { if (*this < that) { //cout << "reached big op + <" << endl; sign = that.is_negative; result = that.uvalue - uvalue; } else { //cout << "reached big op + else" << endl; sign = is_negative; result = uvalue - that.uvalue; } } answer = bigint(result, sign); //cout << "answer: " << answer << endl; return answer; } bigint bigint::operator-(const bigint& that) const { bool sign; ubigint result; if (is_negative == that.is_negative) { //cout << "in bigint - op" << endl; if (*this < that) { //cout << "in uvalue < that" << endl; sign = !(that.is_negative); result = that.uvalue - uvalue; } else { sign = is_negative; result = uvalue - that.uvalue; } } else { if (*this < that) { //cout << "in uvalue < that" << endl; sign = that.is_negative; result = that.uvalue + uvalue; } else { sign = false; result = uvalue - that.uvalue; } } return { result, sign }; } bigint bigint::operator*(const bigint& that) const { bigint result = uvalue * that.uvalue; return result; } bigint bigint::operator/(const bigint& that) const { bigint result = uvalue / that.uvalue; return result; } bigint bigint::operator%(const bigint& that) const { bigint result = uvalue % that.uvalue; return result; } bool bigint::operator==(const bigint& that) const { return is_negative == that.is_negative and uvalue == that.uvalue; } bool bigint::operator<(const bigint& that) const { //cout << "bigint op < reached" << endl; if (is_negative != that.is_negative) return is_negative; return is_negative ? uvalue > that.uvalue : uvalue < that.uvalue; } ostream& operator<<(ostream& out, const bigint& that) { if (that.is_negative) { return out << "-" << that.uvalue; } else { return out << that.uvalue; } }
#include "bvh.h" #include <stdio.h> //#ifndef PBRT_L1_CACHE_LINE_SIZE //#define PBRT_L1_CACHE_LINE_SIZE 64 //#endif // Feel free to ignore these structs entirely! // They are here if you want to implement any of PBRT's // methods for BVH construction. //STAT_MEMORY_COUNTER("Memory/BVH tree", treeBytes); //#define CHECK_EQ(x, y) CHECK((x) == (y)) //#define CHECK_NE(x, y) CHECK((x) != (y)) //#define CHECK_LE(x, y) CHECK((x) <= (y)) //#define CHECK_LT(x, y) CHECK((x) < (y)) //#define CHECK_GE(x, y) CHECK((x) >= (y)) //#define CHECK_GT(x, y) CHECK((x) > (y)) struct BVHPrimitiveInfo { BVHPrimitiveInfo() {} BVHPrimitiveInfo(size_t primitiveNumber, const Bounds3f &bounds) : primitiveNumber(primitiveNumber), bounds(bounds), centroid(.5f * bounds.min + .5f * bounds.max) {} int primitiveNumber; Bounds3f bounds; Point3f centroid; }; struct BVHBuildNode { // BVHBuildNode Public Methods void InitLeaf(int first, int n, const Bounds3f &b) { firstPrimOffset = first; nPrimitives = n; bounds = b; children[0] = children[1] = nullptr; } void InitInterior(int axis, BVHBuildNode *c0, BVHBuildNode *c1) { children[0] = c0; children[1] = c1; bounds = Union(c0->bounds, c1->bounds); splitAxis = axis; nPrimitives = 0; } Bounds3f bounds; BVHBuildNode *children[2]; int splitAxis, firstPrimOffset, nPrimitives; }; struct MortonPrimitive { int primitiveIndex; unsigned int mortonCode; }; struct LBVHTreelet { int startIndex, nPrimitives; BVHBuildNode *buildNodes; }; struct LinearBVHNode { Bounds3f bounds; union { int primitivesOffset; // leaf int secondChildOffset; // interior }; unsigned short nPrimitives; // 0 -> interior node, 16 bytes unsigned char axis; // interior node: xyz, 8 bytes unsigned char pad[1]; // ensure 32 byte total size }; BVHAccel::~BVHAccel() { delete [] nodes; } // Constructs an array of BVHPrimitiveInfos, recursively builds a node-based BVH // from the information, then optimizes the memory of the BVH BVHAccel::BVHAccel(const std::vector<std::shared_ptr<Primitive> > &p, int maxPrimsInNode) : maxPrimsInNode(std::min(255, maxPrimsInNode)), primitives(p) { //TODO if (primitives.empty()) return; // Build BVH from _primitives_ // Initialize _primitiveInfo_ array for primitives std::vector<BVHPrimitiveInfo> primitiveInfo(primitives.size()); for (size_t i = 0; i < primitives.size(); ++i) primitiveInfo[i] = {i, primitives[i]->shape->WorldBound()}; // Build BVH tree for primitives using _primitiveInfo_ //MemoryArena arena(1024 * 1024); int totalNodes = 0; std::vector<std::shared_ptr<Primitive>> orderedPrims; orderedPrims.reserve(primitives.size()); BVHBuildNode *root; root = recursiveBuild(primitiveInfo, 0, primitives.size(), &totalNodes, orderedPrims); primitives.swap(orderedPrims); // LOG(INFO) << StringPrintf("BVH created with %d nodes for %d " // "primitives (%.2f MB)", totalNodes, // (int)primitives.size(), // float(totalNodes * sizeof(LinearBVHNode)) / // (1024.f * 1024.f)); // Compute representation of depth-first traversal of BVH tree // treeBytes += totalNodes * sizeof(LinearBVHNode) + sizeof(*this) + // primitives.size() * sizeof(primitives[0]); //nodes = AllocAligned<LinearBVHNode>(totalNodes); //nodes=(LinearBVHNode*)_aligned_malloc(totalNodes*sizeof(LinearBVHNode),PBRT_L1_CACHE_LINE_SIZE); nodes= new LinearBVHNode[totalNodes]; int offset = 0; flattenBVHTree(root, &offset); //CHECK_EQ(totalNodes, offset); if(totalNodes!=offset) return; } bool BVHAccel::Intersect(const Ray &ray, Intersection *isect) const { //TODO //return false; if (!nodes) return false; //ProfilePhase p(Prof::AccelIntersect); bool hit = false; Vector3f invDir(1 / ray.direction.x, 1 / ray.direction.y, 1 / ray.direction.z); int dirIsNeg[3] = {invDir.x < 0, invDir.y < 0, invDir.z < 0}; // Follow ray through BVH nodes to find primitive intersections int toVisitOffset = 0, currentNodeIndex = 0; int nodesToVisit[64]; float minT=INFINITE; Intersection minIsect; while (true) { const LinearBVHNode *node = &nodes[currentNodeIndex]; // Check ray against BVH node if (node->bounds.IntersectP(ray, invDir, dirIsNeg)) { if (node->nPrimitives > 0) { // Intersect ray with primitives in leaf BVH node for (int i = 0; i < node->nPrimitives; ++i) if (primitives[node->primitivesOffset + i]->Intersect( ray, isect)) { if(minT>isect->t) { minT=isect->t; minIsect=*isect; } hit=true; } if (toVisitOffset == 0) break; currentNodeIndex = nodesToVisit[--toVisitOffset]; } else { // Put far BVH node on _nodesToVisit_ stack, advance to near // node if (dirIsNeg[node->axis]) { nodesToVisit[toVisitOffset++] = currentNodeIndex + 1; currentNodeIndex = node->secondChildOffset; } else { nodesToVisit[toVisitOffset++] = node->secondChildOffset; currentNodeIndex = currentNodeIndex + 1; } } } else { if (toVisitOffset == 0) break; currentNodeIndex = nodesToVisit[--toVisitOffset]; } } *isect=minIsect; return hit; } //bool BVHAccel::IntersectP(const Ray &ray) const //{ // //TODO // //return false; // if (!nodes) return false; // //ProfilePhase p(Prof::AccelIntersect); // bool hit = false; // Vector3f invDir(1 / ray.direction.x, 1 / ray.direction.y, 1 / ray.direction.z); // int dirIsNeg[3] = {invDir.x < 0, invDir.y < 0, invDir.z < 0}; // // Follow ray through BVH nodes to find primitive intersections // int toVisitOffset = 0, currentNodeIndex = 0; // int nodesToVisit[64]; // float minT=INFINITE; // Intersection minIsect; // Intersection isect; // while (true) { // const LinearBVHNode *node = &nodes[currentNodeIndex]; // // Check ray against BVH node // if (node->bounds.IntersectP(ray, invDir, dirIsNeg)) { // if (node->nPrimitives > 0) { // // Intersect ray with primitives in leaf BVH node // for (int i = 0; i < node->nPrimitives; ++i) // if (primitives[node->primitivesOffset + i]->Intersect( // ray, &isect)) // { // if(minT>isect.t) // { // minT=isect.t; // minIsect=isect; // } // hit=true; // } // if (toVisitOffset == 0) break; // currentNodeIndex = nodesToVisit[--toVisitOffset]; // } else { // // Put far BVH node on _nodesToVisit_ stack, advance to near // // node // if (dirIsNeg[node->axis]) { // nodesToVisit[toVisitOffset++] = currentNodeIndex + 1; // currentNodeIndex = node->secondChildOffset; // } else { // nodesToVisit[toVisitOffset++] = node->secondChildOffset; // currentNodeIndex = currentNodeIndex + 1; // } // } // } else { // if (toVisitOffset == 0) break; // currentNodeIndex = nodesToVisit[--toVisitOffset]; // } // } // return hit; //} BVHBuildNode* BVHAccel::recursiveBuild( std::vector<BVHPrimitiveInfo> &primitiveInfo, int start, int end, int *totalNodes, std::vector<std::shared_ptr<Primitive>> &orderedPrims) { //CHECK_NE(start, end); if(start==end) return nullptr; //BVHBuildNode *node = arena.Alloc<BVHBuildNode>(); BVHBuildNode *node = new BVHBuildNode(); (*totalNodes)++; // Compute bounds of all primitives in BVH node Bounds3f bounds; for (int i = start; i < end; ++i) bounds = Union(bounds, primitiveInfo[i].bounds); int nPrimitives = end - start; if (nPrimitives == 1) { // Create leaf _BVHBuildNode_ int firstPrimOffset = orderedPrims.size(); for (int i = start; i < end; ++i) { int primNum = primitiveInfo[i].primitiveNumber; orderedPrims.push_back(primitives[primNum]); } node->InitLeaf(firstPrimOffset, nPrimitives, bounds); return node; } else { // Compute bound of primitive centroids, choose split dimension _dim_ //Bounds3f centroidBounds; Bounds3f centroidBounds=Bounds3f(primitiveInfo[start].centroid); for (int i = start; i < end; ++i) centroidBounds = Union(centroidBounds, primitiveInfo[i].centroid); int dim = centroidBounds.MaximumExtent(); // Partition primitives into two sets and build children int mid = (start + end) / 2; if (centroidBounds.max[dim] == centroidBounds.min[dim]) { // Create leaf _BVHBuildNode_ int firstPrimOffset = orderedPrims.size(); for (int i = start; i < end; ++i) { int primNum = primitiveInfo[i].primitiveNumber; orderedPrims.push_back(primitives[primNum]); } node->InitLeaf(firstPrimOffset, nPrimitives, bounds); return node; } else { // Partition primitives based on _splitMethod_ // Partition primitives using approximate SAH if (nPrimitives <= 2) { // Partition primitives into equally-sized subsets mid = (start + end) / 2; std::nth_element(&primitiveInfo[start], &primitiveInfo[mid], &primitiveInfo[end - 1] + 1, [dim](const BVHPrimitiveInfo &a, const BVHPrimitiveInfo &b) { return a.centroid[dim] < b.centroid[dim]; }); } else { // Allocate _BucketInfo_ for SAH partition buckets //PBRT_CONSTEXPR int nBuckets = 12; //BucketInfo buckets[nBuckets]; constexpr int nBuckets = 12; struct BucketInfo { int count = 0; Bounds3f bounds; }; BucketInfo buckets[nBuckets]; // Initialize _BucketInfo_ for SAH partition buckets for (int i = start; i < end; ++i) { int b = nBuckets * centroidBounds.Offset( primitiveInfo[i].centroid)[dim]; if (b == nBuckets) b = nBuckets - 1; //CHECK_GE(b, 0); //CHECK_LT(b, nBuckets); if(b>=0){ if(b<nBuckets){ buckets[b].count++; buckets[b].bounds = Union(buckets[b].bounds, primitiveInfo[i].bounds);}} } // Compute costs for splitting after each bucket Float cost[nBuckets - 1]; for (int i = 0; i < nBuckets - 1; ++i) { Bounds3f b0, b1; int count0 = 0, count1 = 0; for (int j = 0; j <= i; ++j) { b0 = Union(b0, buckets[j].bounds); count0 += buckets[j].count; } for (int j = i + 1; j < nBuckets; ++j) { b1 = Union(b1, buckets[j].bounds); count1 += buckets[j].count; } cost[i] = 1 + (count0 * b0.SurfaceArea() + count1 * b1.SurfaceArea()) / bounds.SurfaceArea(); } // Find bucket to split at that minimizes SAH metric Float minCost = cost[0]; int minCostSplitBucket = 0; for (int i = 1; i < nBuckets - 1; ++i) { if (cost[i] < minCost) { minCost = cost[i]; minCostSplitBucket = i; } } // Either create leaf or split primitives at selected SAH // bucket Float leafCost = nPrimitives; if (nPrimitives > maxPrimsInNode || minCost < leafCost) { BVHPrimitiveInfo *pmid = std::partition( &primitiveInfo[start], &primitiveInfo[end - 1] + 1, [=](const BVHPrimitiveInfo &pi) { int b = nBuckets * centroidBounds.Offset(pi.centroid)[dim]; if (b == nBuckets) b = nBuckets - 1; //CHECK_GE(b, 0); //CHECK_LT(b, nBuckets); if(b>=0){ if(b<nBuckets) return b <= minCostSplitBucket;} }); mid = pmid - &primitiveInfo[0]; } else { // Create leaf _BVHBuildNode_ int firstPrimOffset = orderedPrims.size(); for (int i = start; i < end; ++i) { int primNum = primitiveInfo[i].primitiveNumber; orderedPrims.push_back(primitives[primNum]); } node->InitLeaf(firstPrimOffset, nPrimitives, bounds); return node; } } //break; if(mid==start) mid++; if(mid==end) mid--; node->InitInterior(dim, recursiveBuild(primitiveInfo, start, mid, totalNodes, orderedPrims), recursiveBuild(primitiveInfo, mid, end, totalNodes, orderedPrims)); } } return node; } int BVHAccel::flattenBVHTree(BVHBuildNode *node, int *offset) { LinearBVHNode *linearNode = &nodes[*offset]; linearNode->bounds = node->bounds; int myOffset = (*offset)++; if (node->nPrimitives > 0) { //CHECK(!node->children[0] && !node->children[1]); //CHECK_LT(node->nPrimitives, 65536); if(!node->children[0] && !node->children[1]){ if(node->nPrimitives< 65536){ linearNode->primitivesOffset = node->firstPrimOffset; linearNode->nPrimitives = node->nPrimitives;}} } else { // Create interior flattened BVH node linearNode->axis = node->splitAxis; linearNode->nPrimitives = 0; flattenBVHTree(node->children[0], offset); linearNode->secondChildOffset = flattenBVHTree(node->children[1], offset); } return myOffset; }
#include<iostream> #define max 10000 using namespace std; int main(){ int a[max];int temp; for(int i=0;i<max;i++) a[i]=0; int n; cin>>n; for(int i=0;i<n;i++) cin>>a[i]; for(int i=1;i<n;i++){ for(int j=0;j<i;j++){ if(a[i]<a[j]){ temp=a[j]; a[j]=a[i]; a[i]=temp; } } for(int k=0;k<n;k++) cout<<a[k]<<" "; cout<<"\n"; } return 0; }
// // File: CLedBuf.cpp // Author: Andy Shepherd // email: seg7led@bytecode.co.uk // License: Public Domain // #ifndef LEDBUF_H #define LEDBUF_H #include <arduino.h> class CLEDBuf { #define CLEDBUF_NUMDIGITS 4 //#define CLEDBUF_BUFSIZE ((CLEDBUF_NUMDIGITS * 2) + 1) public: CLEDBuf(); void clear(); uint8_t addDP(); uint8_t addInt( int i ); uint8_t addULong( unsigned long l ); uint8_t addChar( char c ); bool setCharAt( uint8_t pos, char ch, bool dp ); bool setDpAt( uint8_t pos, bool dp ); void shiftLeft( char ch, bool dp); void shiftRight( char ch, bool dp); uint8_t getNumDigits(); uint8_t getCurrentDigitPos(); char * getBuf(); private: // char m_buf[ CLEDBUF_BUFSIZE ]; char m_buf[ CLEDBUF_NUMDIGITS ]; bool m_buf_dp[ CLEDBUF_NUMDIGITS ]; char m_bufCombined[((CLEDBUF_NUMDIGITS * 2) + 1)]; uint8_t m_bufPos; }; #endif // LEDBUF_H
#ifndef __TEST_OPTIMAL_PARTITION_HPP__ #define __TEST_OPTIMAL_PARTITION_HPP__ #include <cmath> #include <vector> #include <algorithm> #include <utility> #include <numeric> #include <iterator> #include <atomic> #include "threadpool.hpp" #include "threadsafequeue.hpp" #define UNUSED(expr) do { (void)(expr); } while (0) class Score { public: static double power_(double a, double b, double gamma) { return std::pow(a, gamma)/b; } static double power_plus_c(double a, double b, double gamma) { return std::pow(a, gamma)/b + 1.0; } static double neg_log_(double a, double b) { return -std::log(a)/b; } static double expq_(double a, double b) { return std::exp(-a)/b; } static double log_(double a, double b) { UNUSED(b); return -1.*std::log(1+a); } static double log_prod_(double a, double b) { return -1.*std::log((1+a)*(1+b)); } static double double_log_(double a, double b) { return std::log(std::log((1+a)*(1+b))); } static double exp_(double a, double b) { return std::exp((1-a)*(1+b)); } static double power_sum_(double a, double b, double gamma) { return std::pow(a,gamma) + std::pow(b,gamma); } static double power_prod_(double a, double b, double gamma) { return std::pow(a,gamma)*std::pow(b,gamma); } // placeholder for testing static double score_summand_(double a, double b, double gamma) { UNUSED(gamma); return (std::pow(a,6.0))*(std::pow(b,-5.0)); return a; } }; using resultPair = std::pair<double, std::vector<std::vector<int>>>; class PartitionTest { public: PartitionTest(std::vector<double>& a, std::vector<double>& b, int T, double gamma, double delta=1.0) : a_(a), b_(b), T_(T), gamma_(gamma), delta_(delta), numElements_(a.size()) { init_(true); } PartitionTest(std::vector<double>& a, std::vector<double>& b, int T, double gamma, std::vector<std::vector<std::vector<int>>> fList, double delta=1.0) : a_(a), b_(b), T_(T), gamma_(gamma), delta_(delta), fList_(fList) { init_(false); } void runTest(); resultPair get_results() const; void print_pair(const resultPair&) const; void print_partitions() const; bool assertOrdered(const resultPair&) const; int numPartitions() const; std::vector<std::vector<std::vector<int>>> get_partitions() const; void set_a(std::vector<double>&&); void set_b(std::vector<double>&&); void set_T(int); std::vector<double> get_a() const; std::vector<double> get_b() const; private: std::vector<double> a_; std::vector<double> b_; int T_; double gamma_; double delta_; int numElements_; std::vector<int> elements_; std::vector<resultPair> results_; resultPair optimalResult_; std::vector<std::vector<std::vector<int>>> fList_; ThreadsafeQueue<resultPair> results_queue_; std::vector<ThreadPool::TaskFuture<void>> v_; mutable std::atomic<bool> optimization_done_{false}; void init_(bool); void cleanup_(); resultPair optimize_(int, int); void formPartitions_(); void sort_by_priority_(std::vector<double>&, std::vector<double>&, double); }; #endif
#include <stdio.h> #include <math.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <R.h> #include <Rinternals.h> #include <Rdefines.h> #include "mat.h" #include "nutil.h" using namespace std; bool Conslink(long nsam, double **DPtr, double **dend); bool ConISS(long nsam, double **DPtr, double **dend); bool CalcDissimilarity(dMat &Data, double ***DissimPtr, int coef); extern "C" { /* __declspec(dllexport) */ SEXP chclust_c(SEXP sexpData, SEXP sexMethod) { SEXP dims, eMessage = R_NilValue; dims = Rf_getAttrib(sexpData, R_DimSymbol); int method = INTEGER(sexMethod)[0]; long nr = INTEGER(dims)[0]; PROTECT(sexpData); double **DPtr = new double*[nr]; double *diss; long i =0; for (i=1;i<nr;i++) { if ((DPtr[i]= new double[i])==NULL) return eMessage; diss=DPtr[i]; for(long j=0;j<i;j++) { diss[j] = REAL(sexpData)[i + nr*j]; } } UNPROTECT(1); double *dend = NULL; bool errorFlag = false; if (method==1) { if (!Conslink(nr, DPtr, &dend)) { PROTECT(eMessage = allocVector(STRSXP, 1)); SET_STRING_ELT(eMessage, 0, mkChar("Error in Conslink C++ code")); errorFlag = true; } } else if (method==2) { if (!ConISS(nr, DPtr, &dend)) { PROTECT(eMessage = allocVector(STRSXP, 1)); SET_STRING_ELT(eMessage, 0, mkChar("Error in ConISS C++ code")); errorFlag = true; } } else { PROTECT(eMessage = allocVector(STRSXP, 1)); SET_STRING_ELT(eMessage, 0, mkChar("Unknown clustering method")); errorFlag = true; } SEXP sDend; PROTECT(sDend = allocVector(REALSXP, nr-1)); for (i=1;i<nr;i++) { REAL(sDend)[i-1] = dend[i]; } if (dend) delete [] dend; for (i=1;i<nr;i++) delete [] DPtr[i]; delete [] DPtr; UNPROTECT(1); if (errorFlag) { UNPROTECT(1); return eMessage; } return sDend; } } // I apologise for the fairly horrible code below. Translated from the orginal FORTRAN ZONATION written program by John Birks & John Line when I was learning C/C++. #define dc(a,b) (((a) > (b)) ? (DPtr[(a)-1][(b)-1]) : (DPtr[(b)-1][(a)-1])) double Update(double **DPtr, long j, long p, long q, long *nclus, long *name, double dshort, long np, long nq); void Minim(double *diag, double *tiny, long *least, long *ncount, long nsam); void Group(double **DPtr, double *diag, double tiny, double *prev, double *dend, long *least, long ncount, long *nclust, double large, long *nbit, long nsam, long *nlev, char *nsplur, FILE *fout); double Update(double **DPtr, long j, long p, long q, long *nclus, long *name, double dshort, long np, long nq) { long nr; nr = nclus[name[j-1]-1]; return( ( ((double)(nr+np)) *dc(j,p)+((double)(nr+nq))*dc(j,q)-((double)nr)*dshort) / ((double)(nr+np+nq))); } bool ConISS(long nsam, double **DPtr, double **es) { double *ess, dshort,e,de; long i=0 ,n=0, j=0, iter=0, p, q, np, nq, *name, *nclus, msiz,namp,namq; ess = new double[nsam]; *es = new double[nsam]; nclus = new long[nsam]; name = new long[nsam]; if ((ess==NULL)||(es==NULL)||(nclus==NULL)||(name==NULL)) return(false); for (i=0;i<nsam;i++) { nclus[i]=1; ess[i] =0.0; name[i] = i+1; } msiz = nsam-1; e = 0.0; // FULL // fprintf(fout,"\n\n%65sMean\n%50sWithin- within","",""); // fprintf(fout,"\n Clusters Increase in Total cluster cluster"); // fprintf(fout,"\n Iter merged dispersion dispersion dispersion dispersion\n"); for (iter=1;iter<=nsam-1;iter++) { dshort = dc(2,1); p = 1; for (n=2;n<=msiz;n++) { if (dc(n+1,n) < dshort) { dshort = dc(n+1,n); p = n; } } q = p + 1; namp = name[p-1]; namq = name[q-1]; np = nclus[namp-1]; nq = nclus[namq-1]; de = 0.5 * dshort; e += de; ess[namp-1] += ess[namq-1] + de; (*es)[namq-1] = e; //FULL // fprintf(fout,"\n%4d %4d %4d %14.7f %14.7f %14.7f %14.7f", iter, namp, namq, de, e, ess[namp-1], (ess[namp-1]/ (double) (np+nq))); for (j=1;j<p;j++) { DPtr[p-1][j-1] = Update(DPtr,j,p,q,nclus,name,dshort,np,nq); for(i=q;i<=msiz;i++) { DPtr[i-1][j-1] = dc(i+1,j); } } for (i=q;i<=msiz;i++) { DPtr[i-1][p-1] = Update(DPtr,i+1,p,q,nclus,name,dshort,np,nq); } for (j=q;j<msiz;j++) { for (i=j+1;i<=msiz;i++) { DPtr[i-1][j-1] = dc(i+1,j+1); } } for (i=q;i<=msiz;i++) name[i-1] = name[i]; nclus[namp-1] = np+nq; msiz--; } // fprintf(fout,"\n\nSample Level Total\nNumber Dispersion\n"); // DendrogramPlot(Data, es, fout); // delete ess; // delete nclus; // delete name; delete [] ess; delete [] nclus; delete [] name; return true; } void Minim(double *diag, double *tiny, long *least, long *ncount, long nsam) { long i=0; double diff; *ncount=1; least[0]=1; *tiny = diag[1]; for (i=2;i<nsam;i++) { diff = *tiny-diag[i]; if (diff<0.0) { continue; } else if (diff>1.0E-30) { *ncount = 1; *tiny = diag[i]; least[*ncount-1] = i; } else if (diff<=1.0E-30) { (*ncount)++; least[*ncount-1] = i; } } } void Group(double **DPtr, double *diag, double tiny, double *prev, double *dend, long *least, long ncount, long *nclust, double large, long *nbit, long nsam, long *nlev, char *nsplur) { long i=0,j=0,k=0,l=0,up=0, down=0, up1=0, up2=0, down1=0, down2=0; double diss; for (i=0;i<ncount;i++) { j = least[i]; nsplur[j] = '*'; diag[j] = large; nbit[j] = 1; // for(k=1;k<nsam;k++) down=j; up = j; /* find limits of new group, put in up & down */ while ((down<nsam-1) && (nbit[down+1]==1)) { down++; } while ((up>1)&&(nbit[up-1]==1)) { up--; } /* find limits of neighbouring groups */ if (up>1) { down1=up-1; if (up>2) { up1=down1; while (up1>1) { if ((nbit[up1-1])==1) { up1--; } else { break; } } } else down1=up1=1; } if (down<nsam-1) { up2=down+1; if (down<nsam-2) { down2=up2; while ((down2)<(nsam-1)) { if ((nbit[down2+1])==1) { down2++; } else { break; } } } else down2=up2=nsam-1; } /* calc new dcs and update diag */ diss = large; if (up>1) { for (k=up;k<=down+1;k++) { for (l=up1;l<=down1;l++) { if (dc(k,l) < diss) { diss = dc(k,l); } } } diag[down1]=diss; } diss = large; if (down<nsam-1) { for (k=up;k<=down+1;k++) { for (l=up2+1;l<=down2+1;l++) { if (dc(k,l) < diss) { diss = dc(k,l); } } } diag[up2]=diss; } if ((tiny-*prev)<0.0) { dend[j]=*prev; } else { dend[j]=tiny; *prev=tiny; } (*nlev)++; (*nclust)--; nsplur[j]=' '; } } bool Conslink(long nsam, double **DPtr, double **dend) { double *diag, large, tiny; long nclust, *nbit, *least, nlev, ncount; char *nsplur; long i=0, nsam2; double prev; diag = new double[nsam+1]; *dend = new double[nsam+1]; nsplur = new char[nsam+1]; nbit = new long[nsam+1]; least = new long[nsam+1]; if ((diag==NULL)||(*dend==NULL)||(nsplur==NULL)||(nbit==NULL)||(least==NULL)) return false; /* Setup parameters */ large=0.0; nsam2 = unsigned(nsam); for (i=1;i<nsam2;i++) { diag[i] = dc(i,i+1); nsplur[i]='\\'; nbit[i]=0; large += diag[i]; nbit[i] = 0; } prev = 0.0; nclust = nsam; nlev=0; while (nclust>1) { Minim(diag, &tiny, least, &ncount, nsam); Group(DPtr, diag, tiny, &prev, *dend, least, ncount, &nclust, large, nbit, nsam, &nlev, nsplur); } delete [] diag; delete [] nsplur; delete [] nbit; delete [] least; return true; }
#include <stdio.h> #include<string.h> using namespace std; int n; int a[500010],tmp[500010]; long long ans; void mergsort(int l,int r) { if(l<r) { mergsort(l,(l+r)/2); mergsort((l+r)/2+1,r); int *a1=a+l-1; int *a2=a+(l+r)/2; int *a3=tmp+l-1; int l1=1,l2=1,l3=0,c1=(l+r)/2-l+1,c2=r-(l+r)/2; while(l3<r-l+1) { if((l1>c1||a1[l1]>a2[l2])&&(l2<=c2)) { a3[++l3]=a2[l2++]; ans+=c1-l1+1; } else if((l2>c2||a1[l1]<a2[l2])&&(l1<=c1)) { a3[++l3]=a1[l1++]; }else{ if (l1>c1) a3[++l3]=a2[l2++]; else a3[++l3]=a1[l1++]; } } for(int i=l;i<=r;++i) a[i]=tmp[i]; } } int main() { freopen("test.in","r",stdin); scanf("%d",&n); int x; while(n!=0) { for(int i=1;i<=n;++i) scanf("%d",&a[i]); ans=0; mergsort(1,n); printf("%lld\n",ans); scanf("%d",&n); } return 0; }
#include "Label.h" Label::Label(QString text, int x, int y, int textSize, int textWidth) { setFlags(QGraphicsItem::ItemIsMovable |QGraphicsItem::ItemIsSelectable); this->setPos(x, y); setSize(textSize); setBold(true); setDefaultTextColor(QColor(0, 0, 0)); setAlignment(Qt::AlignCenter); //implicit functions this->setPlainText(text); this->setTextWidth(textWidth); } void Label::setSize(int size) { font.setPixelSize(size); updateFontData(); } void Label::setBold(bool bold) { font.setBold(bold); updateFontData(); } int Label::getFontSize() { return this->font.pixelSize(); } void Label::updateFontData() { this->setFont(font); } void Label::setAlignment(Qt::Alignment align) { QTextOption option = this->document()->defaultTextOption(); option.setAlignment(align); this->document()->setDefaultTextOption(option); } void Label::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { if (event->button() != Qt::LeftButton) { event->ignore(); return; } event->accept(); if (GlobalStats::GetTogglePropertyStatus()) { GlobalStats::ToggleOffPropertyMenu(); } else { GlobalStats::ToggleOnPropertyMenu(new LabelProperty(this)); } }
// Copyright (c) 2020 The Orbit 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 "OrbitClientData/FunctionUtils.h" #include <map> #include "OrbitBase/Logging.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/match.h" #include "xxhash.h" namespace { uint64_t StringHash(const std::string& string) { return XXH64(string.data(), string.size(), 0xBADDCAFEDEAD10CC); } } // namespace namespace FunctionUtils { using orbit_client_protos::FunctionInfo; using orbit_grpc_protos::SymbolInfo; std::string GetLoadedModuleName(const FunctionInfo& func) { return std::filesystem::path(func.loaded_module_path()).filename().string(); } uint64_t GetHash(const FunctionInfo& func) { return StringHash(func.pretty_name()); } uint64_t Offset(const FunctionInfo& func) { return func.address() - func.load_bias(); } bool IsOrbitFunc(const FunctionInfo& func) { return func.orbit_type() != FunctionInfo::kNone; } std::unique_ptr<FunctionInfo> CreateFunctionInfo(const SymbolInfo& symbol_info, uint64_t load_bias, const std::string& module_path, uint64_t module_base_address) { auto function_info = std::make_unique<FunctionInfo>(); function_info->set_name(symbol_info.name()); function_info->set_pretty_name(symbol_info.demangled_name()); function_info->set_address(symbol_info.address()); function_info->set_load_bias(load_bias); function_info->set_size(symbol_info.size()); function_info->set_file(""); function_info->set_line(0); function_info->set_loaded_module_path(module_path); function_info->set_module_base_address(module_base_address); SetOrbitTypeFromName(function_info.get()); return function_info; } const absl::flat_hash_map<const char*, FunctionInfo::OrbitType>& GetFunctionNameToOrbitTypeMap() { static absl::flat_hash_map<const char*, FunctionInfo::OrbitType> function_name_to_type_map{ {"Start(", FunctionInfo::kOrbitTimerStart}, {"Stop(", FunctionInfo::kOrbitTimerStop}, {"StartAsync(", FunctionInfo::kOrbitTimerStartAsync}, {"StopAsync(", FunctionInfo::kOrbitTimerStopAsync}, {"TrackValue(", FunctionInfo::kOrbitTrackValue}}; return function_name_to_type_map; } // Detect Orbit API functions by looking for special function names part of the // orbit_api namespace. On a match, set the corresponding function type. bool SetOrbitTypeFromName(FunctionInfo* func) { const std::string& name = GetDisplayName(*func); if (absl::StartsWith(name, "orbit_api::")) { for (auto& pair : GetFunctionNameToOrbitTypeMap()) { if (absl::StrContains(name, pair.first)) { func->set_orbit_type(pair.second); return true; } } } return false; } } // namespace FunctionUtils
#include <iostream> #include <fstream> #include "vw.h" #include "core/session/onnxruntime_cxx_api.h" #include "core/graph/constants.h" struct Input { const char* name; std::vector<int64_t> dims; std::vector<uint32_t> values_int; std::vector<float> values_float; }; struct OrtTensorDimensions : std::vector<int64_t> { OrtTensorDimensions(Ort::CustomOpApi ort, const OrtValue* value) { OrtTensorTypeAndShapeInfo* info = ort.GetTensorTypeAndShape(value); std::vector<int64_t>::operator=(ort.GetTensorShape(info)); ort.ReleaseTensorTypeAndShapeInfo(info); } }; typedef const char* PATH_TYPE; #define TSTR(X) (X) static constexpr PATH_TYPE MODEL_URI = TSTR("../model.onnx"); // CHANGE TO POINT TO ONNX MODEL int main(int argc, char** argv) { //ORT Ort::Env env_= Ort::Env(ORT_LOGGING_LEVEL_INFO, "Default"); // Inference Ort::SessionOptions session_options; Ort::Session session(env_, MODEL_URI, session_options); Ort::AllocatorWithDefaultOptions allocator; std::string classCount = session.GetModelMetadata().LookupCustomMetadataMap("class_count", allocator); std::string line = std::string(argv[1]); std::string initializer = std::string(" -b 32") + std::string(" --csoaa ") + classCount + std::string(" --quiet"); auto vw = VW::initialize(initializer); example* ex = VW::read_example(*vw, line); std::vector<Input> inputs(2); auto input = inputs.begin(); input->name = "Features"; input->values_int = {}; for (features& fs : *ex) { for (features::iterator& f : fs) { input->values_int.push_back(f.index()); } } VW::finish_example(*vw, *ex); input->dims = {static_cast<int>(input->values_int.size())}; input = std::next(input, 1); input->name = "Valid_Classes"; input->dims = {3}; input->values_float = {0.0f,1.0f,0.0f}; const char* output_name = "Outputs"; auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU); std::vector<Ort::Value> input_tensors; std::vector<const char*> input_names; for (size_t i = 0; i < inputs.size(); i++) { input_names.emplace_back(inputs[i].name); if(i == 0){ input_tensors.emplace_back(Ort::Value::CreateTensor<uint32_t>(memory_info, const_cast<uint32_t*>(inputs[i].values_int.data()), inputs[i].values_int.size(), inputs[i].dims.data(), inputs[i].dims.size())); } else{ input_tensors.emplace_back(Ort::Value::CreateTensor<float>(memory_info, const_cast<float*>(inputs[i].values_float.data()), inputs[i].values_float.size(), inputs[i].dims.data(), inputs[i].dims.size())); } } std::vector<Ort::Value> ort_outputs; ort_outputs = session.Run(Ort::RunOptions{nullptr}, input_names.data(), input_tensors.data(), input_tensors.size(), &output_name, 1); int64_t* f = ort_outputs[0].GetTensorMutableData<int64_t>(); std::cout << "Model Output: " << *f << "\n"; return 0; /* std::fstream data_file(argv[1]); std::string line; while (std::getline(data_file, line)) { // assumes single-line examples; multi-line (e.g. for CB) is more complex example* ex = VW::read_example(*vw, line); vw->learn(*ex); VW::finish_example(*vw, *ex); // note that this is a manual driver. If you want to use vw in the same mode as the executable // use this code instead (and add appropriate -i, -f, -d, etc. options to the args passed to VW::initialize) VW::start_parser(*vw); LEARNER::generic_driver(*vw); VW::end_parser(*vw); VW::sync_stats(*vw); } VW::save_predictor(*vw, argv[2]); */ VW::finish(*vw); return 0; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef DEBUGCONTROLLER_H_ #define DEBUGCONTROLLER_H_ #include "../controller/IController.h" #include "ReflectionMacros.h" namespace Controller { struct DebugController : public IController { C__ (void) virtual ~DebugController () {} void onPreUpdate (Event::UpdateEvent *e, Model::IModel *m, View::IView *v) {} void onUpdate (Event::UpdateEvent *e, Model::IModel *m, View::IView *v) {} void onPostUpdate (Event::UpdateEvent *e, Model::IModel *m, View::IView *v) {} /*--------------------------------------------------------------------------*/ HandlingType onButtonPress (Event::ButtonPressEvent *e, Model::IModel *m, View::IView *v); HandlingType onButtonRelease (Event::ButtonReleaseEvent *e, Model::IModel *m, View::IView *v); HandlingType onMouseMotion (Event::MouseMotionEvent *e, Model::IModel *m, View::IView *v); HandlingType onMouseOver (Event::MouseMotionEvent *e, Model::IModel *m, View::IView *v); HandlingType onMouseOut (Event::MouseMotionEvent *e, Model::IModel *m, View::IView *v); HandlingType onKeyDown (Event::KeyDownEvent *e, Model::IModel *m, View::IView *v); HandlingType onKeyUp (Event::KeyUpEvent *e, Model::IModel *m, View::IView *v); HandlingType onTimer (Event::TimerEvent *e, Model::IModel *m, View::IView *v); HandlingType onQuit (Event::QuitEvent *e, Model::IModel *m, View::IView *v); HandlingType onActive (Event::ActiveEvent *e, Model::IModel *m, View::IView *v); HandlingType onExpose (Event::ExposeEvent *e, Model::IModel *m, View::IView *v); HandlingType onResize (Event::ResizeEvent *e, Model::IModel *m, View::IView *v); HandlingType onManagerLoad (Event::ManagerEvent *e, Model::IModel *m, View::IView *v); HandlingType onManagerUnload (Event::ManagerEvent *e, Model::IModel *m, View::IView *v); // linia do dołu m_ (setEventMask) E_ (DebugController) }; } /* namespace Controller */ # endif /* DEBUGCONTROLLER_H_ */
#ifndef _FMT_MEM_VIEW_HPP_ #define _FMT_MEM_VIEW_HPP_ #include <cassert> #include <cstdint> #include <cstdlib> namespace fmt { template<typename T> class mem_view { public: mem_view() : data_(nullptr), size_(0) {} mem_view(T* data, uint32_t size) : data_(data), size_(size) { assert(size == 0 || (size > 0 && data != nullptr)); } mem_view sub_view(uint32_t a, uint32_t b) { assert(b <= size_); assert(a < b); assert(0 <= a); return mem_view(&data_[from], b - a); } uint32_t size() const { return size_; } bool empty() const { return size_ == 0; } T *begin() const { return data_; } T *end() const { return &data_[length]; } T &operator[](uint32_t i) const { assert(0 <= i && i < size_); return data_[i]; } T &first() { return data_[0]; } T &last() { return data_[length_ - 1]; } private: T* data_; size_t size_; }; } #endif
#include "GameStart.h" GameStart::GameStart() { graphic = LoadGraph("graphic/particle.jpg"); alive = true; flag = true; size = 0; pos_x = 0; pos_y = 0; } void GameStart::start(int i) { pos_x = rand() % WIN_WIDTH; pos_y = rand() % WIN_HEIGHT; size = 0.1 + 0.01 * i; } void GameStart::update() { if (alive == true) { if (flag == true) { size += 0.01; } else if (flag == false) { size -= 0.01; } if (size > 1.5) { flag = false; } else if (size < 0.1) { flag = true; } } } void GameStart::draw(int i) { SetDrawBlendMode(DX_BLENDMODE_ADD, 140); if (i % 2 == 0) { SetDrawBright(0, 100, 100); DrawRotaGraph(pos_x, pos_y, size, 0, graphic, true); } else if (i % 2 == 1) { //SetDrawBright(200, 0, 200); DrawRotaGraph(pos_x, pos_y, size, 0, graphic, true); } SetDrawBright(255, 255, 255); SetDrawBlendMode(DX_BLENDMODE_NOBLEND, NULL); }
../../lib/PageXML.cc
#include "task.hh" #include "buffer.hh" #include "http/http_message.hh" #include "uri/uri.hh" #include "net.hh" #include <iostream> using namespace ten; const size_t default_stacksize=4096*2; static void do_get(uri u) { netsock s(AF_INET, SOCK_STREAM); u.normalize(); if (u.scheme != "http") return; if (u.port == 0) u.port = 80; s.dial(u.host.c_str(), u.port); http_request r("GET", u.compose(true)); // HTTP/1.1 requires host header r.append("Host", u.host); std::string data = r.data(); std::cout << "Request:\n" << "--------------\n"; std::cout << data; ssize_t nw = s.send(data.c_str(), data.size()); buffer buf(4*1024); buffer::slice rb = buf(0); http_parser parser; http_response resp; resp.parser_init(&parser); for (;;) { ssize_t nr = s.recv(rb.data(), rb.size()); if (nr <= 0) { std::cerr << "Error: " << strerror(errno) << "\n"; break; } if (resp.parse(&parser, rb.data(), nr)) break; } std::cout << "Response:\n" << "--------------\n"; std::cout << resp.data(); std::cout << "Body size: " << resp.body.size() << "\n"; } int main(int argc, char *argv[]) { if (argc < 2) return -1; procmain p; uri u(argv[1]); taskspawn(std::bind(do_get, u)); return p.main(argc, argv); }
/* * File: Enemey.h * Author: mohammedheader * * Created on November 24, 2014, 4:32 PM */ #ifndef ENEMEY_H #define ENEMEY_H #include "cocos2d.h" #include "Waypoint.h" class HelloWorld; class Enemy : public cocos2d::Node { public: static Enemy* create(HelloWorld* game); virtual void update(float dt); void doActivate(float dt); cocos2d::Vec2 getSpritePosition(){return mySprite->getPosition();}; private: Enemy* init(HelloWorld* game); virtual void remove(); cocos2d::Vec2 myPosition; int maxHp; int currentHp; float walkingSpeed; Waypoint *destinationWaypoint; bool active; HelloWorld *theGame; cocos2d::Sprite *mySprite; }; #endif /* ENEMEY_H */
//--------------------------------------------------------- // // Project: dada // Module: geometry // File: Matrix3f.h // Author: Viacheslav Pryshchepa // // Description: Nine-element square column aligned matrix // //--------------------------------------------------------- #ifndef DADA_GEOMETRY_MATRIX3F_H #define DADA_GEOMETRY_MATRIX3F_H namespace dada { class Matrix3f { public: enum { NUM_ROWS = 3 }; enum { NUM_COLS = 3 }; enum { NUM_ELEMENTS = 9 }; typedef float element_t; typedef unsigned int index_t; Matrix3f(); explicit Matrix3f(float val); Matrix3f(float val00, float val11, float val22); const float* buffer() const; float* buffer(); void set(float val); void set(float val00, float val11, float val22); float operator [] (index_t index) const; float& operator [] (index_t index); float at(index_t row, index_t col) const; float& at(index_t row, index_t col); private: float m_buffer[9]; }; inline Matrix3f::Matrix3f() { } inline Matrix3f::Matrix3f(float val) { set(val); } inline Matrix3f::Matrix3f(float val00, float val11, float val22) { set(val00, val11, val22); } inline const float* Matrix3f::buffer() const { return m_buffer; } inline float* Matrix3f::buffer() { return m_buffer; } inline void Matrix3f::set(float val) { m_buffer[0] = val; m_buffer[1] = 0.0f; m_buffer[2] = 0.0f; m_buffer[3] = 0.0f; m_buffer[4] = val; m_buffer[5] = 0.0f; m_buffer[6] = 0.0f; m_buffer[7] = 0.0f; m_buffer[8] = val; } inline void Matrix3f::set(float val00, float val11, float val22) { m_buffer[0] = val00; m_buffer[1] = 0.0f; m_buffer[2] = 0.0f; m_buffer[3] = 0.0f; m_buffer[4] = val11; m_buffer[5] = 0.0f; m_buffer[6] = 0.0f; m_buffer[7] = 0.0f; m_buffer[8] = val22; } inline float Matrix3f::operator [] (index_t index) const { return m_buffer[index]; } inline float& Matrix3f::operator [] (index_t index) { return m_buffer[index]; } inline float Matrix3f::at(index_t row, index_t col) const { return m_buffer[row + NUM_ROWS * col]; } inline float& Matrix3f::at(index_t row, index_t col) { return m_buffer[row + NUM_ROWS * col]; } } // dada #endif // DADA_GEOMETRY_MATRIX3F_H
#pragma once #include <string> #include <vector> #include "l10n/Locale.h" namespace BeeeOn { class LocaleManager { public: typedef Poco::SharedPtr<LocaleManager> Ptr; virtual ~LocaleManager(); virtual Locale parse(const std::string &input) = 0; virtual Locale chooseBest(const std::vector<std::string> &input) = 0; }; }
/******************************************************************************** ** Form generated from reading UI file 'viewer.ui' ** ** Created: Thu 6. Jun 09:09:27 2013 ** by: Qt User Interface Compiler version 4.8.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_VIEWER_H #define UI_VIEWER_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDockWidget> #include <QtGui/QFormLayout> #include <QtGui/QGridLayout> #include <QtGui/QGroupBox> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QMainWindow> #include <QtGui/QMenu> #include <QtGui/QMenuBar> #include <QtGui/QPushButton> #include <QtGui/QRadioButton> #include <QtGui/QSlider> #include <QtGui/QSpacerItem> #include <QtGui/QSpinBox> #include <QtGui/QStatusBar> #include <QtGui/QToolBar> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> #include "Histo.h" QT_BEGIN_NAMESPACE class Ui_ViewerClass { public: QAction *actionOuvrir; QAction *actionFermer; QAction *actionSauver; QAction *actionSauver_sous; QAction *actionQuitter; QAction *actionAnnuler; QAction *actionRefaire; QAction *actionDetruire_Pile_Avant_et_Arri_re; QAction *actionAide; QAction *actionA_propos; QAction *actionModification_de_la_Taille; QAction *actionSeuillage; QAction *actionImage_Noir_et_Blanc; QAction *actionInverser_Image; QAction *actionModifications_des_couleurs; QAction *actionMiroir_horizontal_de_l_image; QAction *actionMiroir_vertical_de_l_image; QAction *actionFaire_un_quart_de_tour; QAction *actionSpectre_de_l_image; QAction *actionAddition; QAction *actionSoustraction; QAction *actionFaire_un_demi_tour; QWidget *centralWidget; QLabel *imageLabel; QMenuBar *menuBar; QMenu *menuFichier; QMenu *menuEdition; QMenu *menuCaract_riqtique_Images; QMenu *menuModif; QMenu *menu; QMenu *menuOperations_de_base; QToolBar *mainToolBar; QStatusBar *statusBar; QDockWidget *DWSeuillage; QWidget *dockWidgetContents_3; QFormLayout *formLayout_2; QPushButton *pButtonValiderSeuillage; QPushButton *pButtonAnnulerSeuillage; QLabel *labelMinSeuillage; QLabel *labelMaxSeuillage; QSpinBox *spinBoxMinSeuillage; QSpinBox *spinBoxMaxSeuillage; QDockWidget *DWReglage; QWidget *dockWidgetContents_2; QGridLayout *gridLayout; QLabel *labelRouge; QSlider *hSliderRouge; QSlider *hSliderBleu; QSlider *hSliderVert; QLabel *labelNbRouge; QLabel *labelVert; QLabel *labelNbLumosite; QLabel *labelNbVert; QLabel *labelBleu; QLabel *labelNbBleu; QPushButton *pButtonValiderCouleur; QPushButton *pButtonAnnulerCouleur; QLabel *labelLuminosite; QSlider *hSliderLumosite; QSpacerItem *verticalSpacer; QDockWidget *DWSpectreImage; QWidget *dockWidgetContents; QVBoxLayout *verticalLayout; QGroupBox *groupBox; QGridLayout *gridLayout_2; QRadioButton *radioButtonSpectreBleu; QRadioButton *radioButtonSpectreVert; QRadioButton *radioButtonSpectreRouge; QRadioButton *radioButtonSpectreTout; CHisto *MonHisto; QSpacerItem *verticalSpacer_2; void setupUi(QMainWindow *ViewerClass) { if (ViewerClass->objectName().isEmpty()) ViewerClass->setObjectName(QString::fromUtf8("ViewerClass")); ViewerClass->resize(830, 886); actionOuvrir = new QAction(ViewerClass); actionOuvrir->setObjectName(QString::fromUtf8("actionOuvrir")); actionFermer = new QAction(ViewerClass); actionFermer->setObjectName(QString::fromUtf8("actionFermer")); actionFermer->setEnabled(false); actionSauver = new QAction(ViewerClass); actionSauver->setObjectName(QString::fromUtf8("actionSauver")); actionSauver->setEnabled(false); actionSauver_sous = new QAction(ViewerClass); actionSauver_sous->setObjectName(QString::fromUtf8("actionSauver_sous")); actionSauver_sous->setEnabled(false); actionQuitter = new QAction(ViewerClass); actionQuitter->setObjectName(QString::fromUtf8("actionQuitter")); actionAnnuler = new QAction(ViewerClass); actionAnnuler->setObjectName(QString::fromUtf8("actionAnnuler")); actionAnnuler->setEnabled(true); actionRefaire = new QAction(ViewerClass); actionRefaire->setObjectName(QString::fromUtf8("actionRefaire")); actionRefaire->setEnabled(true); actionDetruire_Pile_Avant_et_Arri_re = new QAction(ViewerClass); actionDetruire_Pile_Avant_et_Arri_re->setObjectName(QString::fromUtf8("actionDetruire_Pile_Avant_et_Arri_re")); actionAide = new QAction(ViewerClass); actionAide->setObjectName(QString::fromUtf8("actionAide")); actionA_propos = new QAction(ViewerClass); actionA_propos->setObjectName(QString::fromUtf8("actionA_propos")); actionModification_de_la_Taille = new QAction(ViewerClass); actionModification_de_la_Taille->setObjectName(QString::fromUtf8("actionModification_de_la_Taille")); actionModification_de_la_Taille->setEnabled(false); actionSeuillage = new QAction(ViewerClass); actionSeuillage->setObjectName(QString::fromUtf8("actionSeuillage")); actionSeuillage->setCheckable(true); actionSeuillage->setEnabled(false); actionImage_Noir_et_Blanc = new QAction(ViewerClass); actionImage_Noir_et_Blanc->setObjectName(QString::fromUtf8("actionImage_Noir_et_Blanc")); actionImage_Noir_et_Blanc->setCheckable(false); actionImage_Noir_et_Blanc->setEnabled(false); actionInverser_Image = new QAction(ViewerClass); actionInverser_Image->setObjectName(QString::fromUtf8("actionInverser_Image")); actionInverser_Image->setCheckable(false); actionInverser_Image->setEnabled(false); actionModifications_des_couleurs = new QAction(ViewerClass); actionModifications_des_couleurs->setObjectName(QString::fromUtf8("actionModifications_des_couleurs")); actionModifications_des_couleurs->setCheckable(true); actionModifications_des_couleurs->setEnabled(false); actionMiroir_horizontal_de_l_image = new QAction(ViewerClass); actionMiroir_horizontal_de_l_image->setObjectName(QString::fromUtf8("actionMiroir_horizontal_de_l_image")); actionMiroir_horizontal_de_l_image->setEnabled(false); actionMiroir_vertical_de_l_image = new QAction(ViewerClass); actionMiroir_vertical_de_l_image->setObjectName(QString::fromUtf8("actionMiroir_vertical_de_l_image")); actionMiroir_vertical_de_l_image->setEnabled(false); actionFaire_un_quart_de_tour = new QAction(ViewerClass); actionFaire_un_quart_de_tour->setObjectName(QString::fromUtf8("actionFaire_un_quart_de_tour")); actionFaire_un_quart_de_tour->setEnabled(false); actionSpectre_de_l_image = new QAction(ViewerClass); actionSpectre_de_l_image->setObjectName(QString::fromUtf8("actionSpectre_de_l_image")); actionSpectre_de_l_image->setCheckable(true); actionSpectre_de_l_image->setEnabled(false); actionAddition = new QAction(ViewerClass); actionAddition->setObjectName(QString::fromUtf8("actionAddition")); actionAddition->setEnabled(false); actionSoustraction = new QAction(ViewerClass); actionSoustraction->setObjectName(QString::fromUtf8("actionSoustraction")); actionSoustraction->setEnabled(false); actionFaire_un_demi_tour = new QAction(ViewerClass); actionFaire_un_demi_tour->setObjectName(QString::fromUtf8("actionFaire_un_demi_tour")); actionFaire_un_demi_tour->setEnabled(false); centralWidget = new QWidget(ViewerClass); centralWidget->setObjectName(QString::fromUtf8("centralWidget")); imageLabel = new QLabel(centralWidget); imageLabel->setObjectName(QString::fromUtf8("imageLabel")); imageLabel->setGeometry(QRect(280, 110, 51, 21)); ViewerClass->setCentralWidget(centralWidget); menuBar = new QMenuBar(ViewerClass); menuBar->setObjectName(QString::fromUtf8("menuBar")); menuBar->setGeometry(QRect(0, 0, 830, 21)); menuFichier = new QMenu(menuBar); menuFichier->setObjectName(QString::fromUtf8("menuFichier")); menuEdition = new QMenu(menuBar); menuEdition->setObjectName(QString::fromUtf8("menuEdition")); menuCaract_riqtique_Images = new QMenu(menuBar); menuCaract_riqtique_Images->setObjectName(QString::fromUtf8("menuCaract_riqtique_Images")); menuModif = new QMenu(menuBar); menuModif->setObjectName(QString::fromUtf8("menuModif")); menu = new QMenu(menuBar); menu->setObjectName(QString::fromUtf8("menu")); menuOperations_de_base = new QMenu(menuBar); menuOperations_de_base->setObjectName(QString::fromUtf8("menuOperations_de_base")); ViewerClass->setMenuBar(menuBar); mainToolBar = new QToolBar(ViewerClass); mainToolBar->setObjectName(QString::fromUtf8("mainToolBar")); ViewerClass->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(ViewerClass); statusBar->setObjectName(QString::fromUtf8("statusBar")); ViewerClass->setStatusBar(statusBar); DWSeuillage = new QDockWidget(ViewerClass); DWSeuillage->setObjectName(QString::fromUtf8("DWSeuillage")); DWSeuillage->setFeatures(QDockWidget::DockWidgetMovable); dockWidgetContents_3 = new QWidget(); dockWidgetContents_3->setObjectName(QString::fromUtf8("dockWidgetContents_3")); formLayout_2 = new QFormLayout(dockWidgetContents_3); formLayout_2->setSpacing(6); formLayout_2->setContentsMargins(11, 11, 11, 11); formLayout_2->setObjectName(QString::fromUtf8("formLayout_2")); pButtonValiderSeuillage = new QPushButton(dockWidgetContents_3); pButtonValiderSeuillage->setObjectName(QString::fromUtf8("pButtonValiderSeuillage")); formLayout_2->setWidget(2, QFormLayout::LabelRole, pButtonValiderSeuillage); pButtonAnnulerSeuillage = new QPushButton(dockWidgetContents_3); pButtonAnnulerSeuillage->setObjectName(QString::fromUtf8("pButtonAnnulerSeuillage")); formLayout_2->setWidget(2, QFormLayout::FieldRole, pButtonAnnulerSeuillage); labelMinSeuillage = new QLabel(dockWidgetContents_3); labelMinSeuillage->setObjectName(QString::fromUtf8("labelMinSeuillage")); labelMinSeuillage->setFrameShape(QFrame::NoFrame); formLayout_2->setWidget(0, QFormLayout::LabelRole, labelMinSeuillage); labelMaxSeuillage = new QLabel(dockWidgetContents_3); labelMaxSeuillage->setObjectName(QString::fromUtf8("labelMaxSeuillage")); formLayout_2->setWidget(1, QFormLayout::LabelRole, labelMaxSeuillage); spinBoxMinSeuillage = new QSpinBox(dockWidgetContents_3); spinBoxMinSeuillage->setObjectName(QString::fromUtf8("spinBoxMinSeuillage")); formLayout_2->setWidget(0, QFormLayout::FieldRole, spinBoxMinSeuillage); spinBoxMaxSeuillage = new QSpinBox(dockWidgetContents_3); spinBoxMaxSeuillage->setObjectName(QString::fromUtf8("spinBoxMaxSeuillage")); formLayout_2->setWidget(1, QFormLayout::FieldRole, spinBoxMaxSeuillage); DWSeuillage->setWidget(dockWidgetContents_3); ViewerClass->addDockWidget(static_cast<Qt::DockWidgetArea>(1), DWSeuillage); DWReglage = new QDockWidget(ViewerClass); DWReglage->setObjectName(QString::fromUtf8("DWReglage")); DWReglage->setFeatures(QDockWidget::DockWidgetMovable); dockWidgetContents_2 = new QWidget(); dockWidgetContents_2->setObjectName(QString::fromUtf8("dockWidgetContents_2")); gridLayout = new QGridLayout(dockWidgetContents_2); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); labelRouge = new QLabel(dockWidgetContents_2); labelRouge->setObjectName(QString::fromUtf8("labelRouge")); gridLayout->addWidget(labelRouge, 4, 1, 1, 1); hSliderRouge = new QSlider(dockWidgetContents_2); hSliderRouge->setObjectName(QString::fromUtf8("hSliderRouge")); hSliderRouge->setMinimum(-100); hSliderRouge->setMaximum(100); hSliderRouge->setOrientation(Qt::Horizontal); gridLayout->addWidget(hSliderRouge, 4, 0, 1, 1); hSliderBleu = new QSlider(dockWidgetContents_2); hSliderBleu->setObjectName(QString::fromUtf8("hSliderBleu")); hSliderBleu->setMinimum(-100); hSliderBleu->setMaximum(100); hSliderBleu->setOrientation(Qt::Horizontal); gridLayout->addWidget(hSliderBleu, 6, 0, 1, 1); hSliderVert = new QSlider(dockWidgetContents_2); hSliderVert->setObjectName(QString::fromUtf8("hSliderVert")); hSliderVert->setMinimum(-100); hSliderVert->setMaximum(100); hSliderVert->setOrientation(Qt::Horizontal); gridLayout->addWidget(hSliderVert, 5, 0, 1, 1); labelNbRouge = new QLabel(dockWidgetContents_2); labelNbRouge->setObjectName(QString::fromUtf8("labelNbRouge")); gridLayout->addWidget(labelNbRouge, 4, 2, 1, 1); labelVert = new QLabel(dockWidgetContents_2); labelVert->setObjectName(QString::fromUtf8("labelVert")); gridLayout->addWidget(labelVert, 5, 1, 1, 1); labelNbLumosite = new QLabel(dockWidgetContents_2); labelNbLumosite->setObjectName(QString::fromUtf8("labelNbLumosite")); gridLayout->addWidget(labelNbLumosite, 2, 2, 1, 1); labelNbVert = new QLabel(dockWidgetContents_2); labelNbVert->setObjectName(QString::fromUtf8("labelNbVert")); gridLayout->addWidget(labelNbVert, 5, 2, 1, 1); labelBleu = new QLabel(dockWidgetContents_2); labelBleu->setObjectName(QString::fromUtf8("labelBleu")); gridLayout->addWidget(labelBleu, 6, 1, 1, 1); labelNbBleu = new QLabel(dockWidgetContents_2); labelNbBleu->setObjectName(QString::fromUtf8("labelNbBleu")); gridLayout->addWidget(labelNbBleu, 6, 2, 1, 1); pButtonValiderCouleur = new QPushButton(dockWidgetContents_2); pButtonValiderCouleur->setObjectName(QString::fromUtf8("pButtonValiderCouleur")); gridLayout->addWidget(pButtonValiderCouleur, 8, 0, 1, 1); pButtonAnnulerCouleur = new QPushButton(dockWidgetContents_2); pButtonAnnulerCouleur->setObjectName(QString::fromUtf8("pButtonAnnulerCouleur")); gridLayout->addWidget(pButtonAnnulerCouleur, 8, 1, 1, 2); labelLuminosite = new QLabel(dockWidgetContents_2); labelLuminosite->setObjectName(QString::fromUtf8("labelLuminosite")); labelLuminosite->setLineWidth(1); gridLayout->addWidget(labelLuminosite, 1, 0, 1, 1); hSliderLumosite = new QSlider(dockWidgetContents_2); hSliderLumosite->setObjectName(QString::fromUtf8("hSliderLumosite")); hSliderLumosite->setMinimum(-100); hSliderLumosite->setMaximum(100); hSliderLumosite->setOrientation(Qt::Horizontal); gridLayout->addWidget(hSliderLumosite, 2, 0, 1, 1); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer, 9, 0, 1, 1); DWReglage->setWidget(dockWidgetContents_2); ViewerClass->addDockWidget(static_cast<Qt::DockWidgetArea>(1), DWReglage); DWSpectreImage = new QDockWidget(ViewerClass); DWSpectreImage->setObjectName(QString::fromUtf8("DWSpectreImage")); DWSpectreImage->setMinimumSize(QSize(174, 454)); DWSpectreImage->setFeatures(QDockWidget::DockWidgetMovable); dockWidgetContents = new QWidget(); dockWidgetContents->setObjectName(QString::fromUtf8("dockWidgetContents")); verticalLayout = new QVBoxLayout(dockWidgetContents); verticalLayout->setSpacing(6); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); groupBox = new QGroupBox(dockWidgetContents); groupBox->setObjectName(QString::fromUtf8("groupBox")); groupBox->setMaximumSize(QSize(200, 100)); gridLayout_2 = new QGridLayout(groupBox); gridLayout_2->setSpacing(6); gridLayout_2->setContentsMargins(11, 11, 11, 11); gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2")); radioButtonSpectreBleu = new QRadioButton(groupBox); radioButtonSpectreBleu->setObjectName(QString::fromUtf8("radioButtonSpectreBleu")); gridLayout_2->addWidget(radioButtonSpectreBleu, 4, 0, 1, 1); radioButtonSpectreVert = new QRadioButton(groupBox); radioButtonSpectreVert->setObjectName(QString::fromUtf8("radioButtonSpectreVert")); gridLayout_2->addWidget(radioButtonSpectreVert, 3, 0, 1, 1); radioButtonSpectreRouge = new QRadioButton(groupBox); radioButtonSpectreRouge->setObjectName(QString::fromUtf8("radioButtonSpectreRouge")); gridLayout_2->addWidget(radioButtonSpectreRouge, 0, 0, 1, 1); radioButtonSpectreTout = new QRadioButton(groupBox); radioButtonSpectreTout->setObjectName(QString::fromUtf8("radioButtonSpectreTout")); gridLayout_2->addWidget(radioButtonSpectreTout, 3, 1, 1, 1); verticalLayout->addWidget(groupBox); MonHisto = new CHisto(dockWidgetContents); MonHisto->setObjectName(QString::fromUtf8("MonHisto")); MonHisto->setMinimumSize(QSize(0, 300)); MonHisto->setMaximumSize(QSize(16777215, 400)); verticalLayout->addWidget(MonHisto); verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer_2); DWSpectreImage->setWidget(dockWidgetContents); ViewerClass->addDockWidget(static_cast<Qt::DockWidgetArea>(1), DWSpectreImage); DWReglage->raise(); menuBar->addAction(menuFichier->menuAction()); menuBar->addAction(menuEdition->menuAction()); menuBar->addAction(menuCaract_riqtique_Images->menuAction()); menuBar->addAction(menuModif->menuAction()); menuBar->addAction(menuOperations_de_base->menuAction()); menuBar->addAction(menu->menuAction()); menuFichier->addAction(actionOuvrir); menuFichier->addAction(actionFermer); menuFichier->addAction(actionSauver); menuFichier->addAction(actionSauver_sous); menuFichier->addSeparator(); menuFichier->addAction(actionQuitter); menuEdition->addAction(actionAnnuler); menuEdition->addAction(actionRefaire); menuEdition->addAction(actionDetruire_Pile_Avant_et_Arri_re); menuCaract_riqtique_Images->addAction(actionModification_de_la_Taille); menuCaract_riqtique_Images->addAction(actionMiroir_horizontal_de_l_image); menuCaract_riqtique_Images->addAction(actionMiroir_vertical_de_l_image); menuCaract_riqtique_Images->addAction(actionFaire_un_quart_de_tour); menuCaract_riqtique_Images->addAction(actionFaire_un_demi_tour); menuCaract_riqtique_Images->addSeparator(); menuCaract_riqtique_Images->addAction(actionSpectre_de_l_image); menuModif->addAction(actionImage_Noir_et_Blanc); menuModif->addAction(actionInverser_Image); menuModif->addAction(actionSeuillage); menuModif->addAction(actionModifications_des_couleurs); menu->addAction(actionAide); menu->addAction(actionA_propos); menuOperations_de_base->addAction(actionAddition); menuOperations_de_base->addAction(actionSoustraction); retranslateUi(ViewerClass); QMetaObject::connectSlotsByName(ViewerClass); } // setupUi void retranslateUi(QMainWindow *ViewerClass) { ViewerClass->setWindowTitle(QApplication::translate("ViewerClass", "Visualisation d'images", 0, QApplication::UnicodeUTF8)); actionOuvrir->setText(QApplication::translate("ViewerClass", "Ouvrir", 0, QApplication::UnicodeUTF8)); actionOuvrir->setShortcut(QApplication::translate("ViewerClass", "Ctrl+O", 0, QApplication::UnicodeUTF8)); actionFermer->setText(QApplication::translate("ViewerClass", "Fermer", 0, QApplication::UnicodeUTF8)); actionSauver->setText(QApplication::translate("ViewerClass", "Sauver", 0, QApplication::UnicodeUTF8)); actionSauver->setShortcut(QApplication::translate("ViewerClass", "Ctrl+S", 0, QApplication::UnicodeUTF8)); actionSauver_sous->setText(QApplication::translate("ViewerClass", "Sauver sous", 0, QApplication::UnicodeUTF8)); actionSauver_sous->setShortcut(QApplication::translate("ViewerClass", "Ctrl+Shift+S", 0, QApplication::UnicodeUTF8)); actionQuitter->setText(QApplication::translate("ViewerClass", "Quitter", 0, QApplication::UnicodeUTF8)); actionQuitter->setShortcut(QApplication::translate("ViewerClass", "Ctrl+Q", 0, QApplication::UnicodeUTF8)); actionAnnuler->setText(QApplication::translate("ViewerClass", "Annuler", 0, QApplication::UnicodeUTF8)); actionAnnuler->setShortcut(QApplication::translate("ViewerClass", "Ctrl+Z", 0, QApplication::UnicodeUTF8)); actionRefaire->setText(QApplication::translate("ViewerClass", "Refaire", 0, QApplication::UnicodeUTF8)); actionRefaire->setShortcut(QApplication::translate("ViewerClass", "Ctrl+Y", 0, QApplication::UnicodeUTF8)); actionDetruire_Pile_Avant_et_Arri_re->setText(QApplication::translate("ViewerClass", "Detruire Pile Avant et Arri\303\250re", 0, QApplication::UnicodeUTF8)); actionAide->setText(QApplication::translate("ViewerClass", "Aide", 0, QApplication::UnicodeUTF8)); actionAide->setShortcut(QApplication::translate("ViewerClass", "F1", 0, QApplication::UnicodeUTF8)); actionA_propos->setText(QApplication::translate("ViewerClass", "A propos", 0, QApplication::UnicodeUTF8)); actionModification_de_la_Taille->setText(QApplication::translate("ViewerClass", "Modification de la Taille", 0, QApplication::UnicodeUTF8)); actionSeuillage->setText(QApplication::translate("ViewerClass", "Seuillage", 0, QApplication::UnicodeUTF8)); actionImage_Noir_et_Blanc->setText(QApplication::translate("ViewerClass", "Image Noir et Blanc", 0, QApplication::UnicodeUTF8)); actionInverser_Image->setText(QApplication::translate("ViewerClass", "Inverser une Image", 0, QApplication::UnicodeUTF8)); actionModifications_des_couleurs->setText(QApplication::translate("ViewerClass", "R\303\251glages des couleurs", 0, QApplication::UnicodeUTF8)); actionMiroir_horizontal_de_l_image->setText(QApplication::translate("ViewerClass", "Miroir horizontal de l'image", 0, QApplication::UnicodeUTF8)); actionMiroir_vertical_de_l_image->setText(QApplication::translate("ViewerClass", "Miroir vertical de l'image", 0, QApplication::UnicodeUTF8)); actionFaire_un_quart_de_tour->setText(QApplication::translate("ViewerClass", "Faire un quart de tour", 0, QApplication::UnicodeUTF8)); actionSpectre_de_l_image->setText(QApplication::translate("ViewerClass", "Spectre de l'image", 0, QApplication::UnicodeUTF8)); actionAddition->setText(QApplication::translate("ViewerClass", "Addition", 0, QApplication::UnicodeUTF8)); actionSoustraction->setText(QApplication::translate("ViewerClass", "Soustraction", 0, QApplication::UnicodeUTF8)); actionFaire_un_demi_tour->setText(QApplication::translate("ViewerClass", "Faire un demi-tour", 0, QApplication::UnicodeUTF8)); imageLabel->setText(QString()); menuFichier->setTitle(QApplication::translate("ViewerClass", "Fichier", 0, QApplication::UnicodeUTF8)); menuEdition->setTitle(QApplication::translate("ViewerClass", "Edition", 0, QApplication::UnicodeUTF8)); menuCaract_riqtique_Images->setTitle(QApplication::translate("ViewerClass", "Caract\303\251riqtique Images", 0, QApplication::UnicodeUTF8)); menuModif->setTitle(QApplication::translate("ViewerClass", "Modif", 0, QApplication::UnicodeUTF8)); menu->setTitle(QApplication::translate("ViewerClass", "?", 0, QApplication::UnicodeUTF8)); menuOperations_de_base->setTitle(QApplication::translate("ViewerClass", "Operations de base", 0, QApplication::UnicodeUTF8)); DWSeuillage->setWindowTitle(QApplication::translate("ViewerClass", "Seuillage", 0, QApplication::UnicodeUTF8)); pButtonValiderSeuillage->setText(QApplication::translate("ViewerClass", "Valider", 0, QApplication::UnicodeUTF8)); pButtonAnnulerSeuillage->setText(QApplication::translate("ViewerClass", "Annuler", 0, QApplication::UnicodeUTF8)); labelMinSeuillage->setText(QApplication::translate("ViewerClass", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600;\">Minimum</span></p></body></html>", 0, QApplication::UnicodeUTF8)); labelMaxSeuillage->setText(QApplication::translate("ViewerClass", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600;\">Maximum</span></p></body></html>", 0, QApplication::UnicodeUTF8)); DWReglage->setWindowTitle(QApplication::translate("ViewerClass", "R\303\251glage des couleurs", 0, QApplication::UnicodeUTF8)); labelRouge->setText(QApplication::translate("ViewerClass", "<html><head/><body><p><span style=\" font-size:10pt; color:#ff0000;\">R</span></p></body></html>", 0, QApplication::UnicodeUTF8)); labelNbRouge->setText(QApplication::translate("ViewerClass", "00", 0, QApplication::UnicodeUTF8)); labelVert->setText(QApplication::translate("ViewerClass", "<html><head/><body><p><span style=\" font-size:10pt; color:#00ff00;\">V</span></p></body></html>", 0, QApplication::UnicodeUTF8)); labelNbLumosite->setText(QApplication::translate("ViewerClass", "00", 0, QApplication::UnicodeUTF8)); labelNbVert->setText(QApplication::translate("ViewerClass", "00", 0, QApplication::UnicodeUTF8)); labelBleu->setText(QApplication::translate("ViewerClass", "<html><head/><body><p><span style=\" font-size:10pt; color:#0000ff;\">B</span></p></body></html>", 0, QApplication::UnicodeUTF8)); labelNbBleu->setText(QApplication::translate("ViewerClass", "00", 0, QApplication::UnicodeUTF8)); pButtonValiderCouleur->setText(QApplication::translate("ViewerClass", "Valider", 0, QApplication::UnicodeUTF8)); pButtonAnnulerCouleur->setText(QApplication::translate("ViewerClass", "Annuler", 0, QApplication::UnicodeUTF8)); labelLuminosite->setText(QApplication::translate("ViewerClass", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600;\">Luminosit\303\251</span></p></body></html>", 0, QApplication::UnicodeUTF8)); DWSpectreImage->setWindowTitle(QApplication::translate("ViewerClass", "Spectre de l'image", 0, QApplication::UnicodeUTF8)); groupBox->setTitle(QApplication::translate("ViewerClass", "Choisir une couleur", 0, QApplication::UnicodeUTF8)); radioButtonSpectreBleu->setText(QApplication::translate("ViewerClass", "B", 0, QApplication::UnicodeUTF8)); radioButtonSpectreVert->setText(QApplication::translate("ViewerClass", "G", 0, QApplication::UnicodeUTF8)); radioButtonSpectreRouge->setText(QApplication::translate("ViewerClass", "R", 0, QApplication::UnicodeUTF8)); radioButtonSpectreTout->setText(QApplication::translate("ViewerClass", "Tout", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class ViewerClass: public Ui_ViewerClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_VIEWER_H