text
stringlengths
8
6.88M
#pragma GCC optimize("Ofast") #include <algorithm> #include <bitset> #include <deque> #include <iostream> #include <iterator> #include <string> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; void abhisheknaiidu() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } // T.C - O(N) // S.C - min(length of string, unique elements of strings) i.e the size of hashmap int main(int argc, char* argv[]) { abhisheknaiidu(); string s = "abhisheknaiidu"; unordered_map <char, int> m; vector<int> longest{0,1}; int startIndex = 0; for(int i=0; i<s.size(); i++) { if(m.find(s[i]) != m.end()) { startIndex = max(startIndex, m[s[i]] + 1); } if(longest[1] - longest[0] < i + 1 - startIndex) { longest = {startIndex, i+1}; } m[s[i]] = i; } string ans = s.substr(longest[0], longest[1]-longest[0]); cout << ans; return 0; }
#include<bits/stdc++.h> using namespace std; int main(){ int a[]={1,2,3,4,5}; int b[]={6,7,8,9,10,11,12}; int n=sizeof(a)/sizeof(a[0]); int m=sizeof(b)/sizeof(b[0]); int p; int c[100],count=0; for(int i=0; i<m; i++) { c[count++]=a[i]; p++; c[count+4]=b[i]; } // for(int i=0;i<m;i++) // { // c[count++]=b[i]; // } for(int i=0;i<p;i++) { cout<<c[i]<<" "; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * 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. */ #include "core/pch.h" #ifdef M2_SUPPORT #include "m2glue.h" #include "adjunct/m2/src/engine/accountmgr.h" #include "adjunct/m2/src/engine/engine.h" #include "adjunct/m2/src/engine/progressinfo.h" #include "adjunct/m2/src/glue/connection.h" #include "adjunct/m2/src/glue/mh.h" #include "adjunct/m2/src/glue/mime.h" #include "adjunct/m2/src/glue/util.h" #include "adjunct/m2/src/util/buffer.h" #include "adjunct/m2/src/util/misc.h" #include "adjunct/quick/Application.h" #include "adjunct/m2_ui/dialogs/AccountSubscriptionDialog.h" #include "adjunct/m2_ui/dialogs/AccountQuestionDialogs.h" #include "adjunct/m2_ui/dialogs/ChangeNickDialog.h" #include "adjunct/quick/dialogs/SimpleDialog.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "adjunct/quick_toolkit/widgets/OpBrowserView.h" #include "adjunct/quick/windows/BrowserDesktopWindow.h" #include "adjunct/m2_ui/windows/ChatDesktopWindow.h" #include "adjunct/m2_ui/windows/ComposeDesktopWindow.h" #include "adjunct/m2_ui/windows/MailDesktopWindow.h" #include "adjunct/desktop_util/sound/SoundUtils.h" #include "adjunct/desktop_util/string/stringutils.h" #include "adjunct/desktop_util/mail/mailformatting.h" #include "adjunct/desktop_util/filelogger/desktopfilelogger.h" #include "modules/doc/doc.h" #include "modules/doc/frm_doc.h" #include "modules/dochand/fdelm.h" #include "modules/encodings/charconverter.h" #include "modules/encodings/decoders/utf8-decoder.h" #include "modules/encodings/decoders/utf7-decoder.h" #include "modules/encodings/encoders/utf8-encoder.h" #include "modules/encodings/encoders/utf7-encoder.h" #include "modules/hardcore/mh/messages.h" #include "modules/idna/idna.h" #include "modules/layout/box/box.h" #include "modules/libssl/sslv3.h" #include "modules/libssl/sslopt.h" #include "modules/locale/oplanguagemanager.h" #include "modules/logdoc/htm_ldoc.h" #include "modules/pi/OpDLL.h" #include "modules/prefs/prefsmanager/collections/pc_m2.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/regexp/include/regexp_api.h" #include "modules/url/uamanager/ua.h" #ifdef FORMATS_CAP_MODULE # include "modules/formats/encoder.h" #else # include "modules/url/mime/encoder.h" #endif #ifdef MIME_CAP_MODULE # include "modules/mime/mimedec2.h" # include "modules/mime/mime_module.h" #else # include "modules/url/mime/mimedec2.h" #endif #ifdef UPLOAD_CAP_MODULE # include "modules/upload/upload.h" #else # include "modules/url/mime/upload2.h" #endif #include "modules/url/protocols/pcomm.h" #include "modules/url/protocols/comm.h" #include "modules/url/url_socket_wrapper.h" #include "modules/url/url2.h" #include "modules/util/filefun.h" #include "modules/util/OpTypedObject.h" #include "modules/util/path.h" #include "modules/widgets/WidgetContainer.h" #include "modules/windowcommander/src/TransferManager.h" #include "modules/util/opfile/unistream.h" #if defined(MSWIN) || defined(UNIX) # include "modules/util/gen_str.h" #endif #if defined (MSWIN) #include "platforms/windows/windows_ui/registry.h" # include "platforms/windows/network/WindowsSocket2.h" //For Win32 dynamic run-time linked gethostbyaddr, gethostbyname and gethostname #elif defined(_UNIX_DESKTOP_) || defined(_MACINTOSH_) #include <netdb.h> // gethostbyname #endif #ifdef WAND_SUPPORT # include "modules/wand/wandmanager.h" #endif #if defined(_SSL_SUPPORT_) && !defined(_EXTERNAL_SSL_SUPPORT_) #include "modules/libssl/ssl_api.h" #include "modules/url/url_sn.h" // ServerName #endif #include "modules/dochand/win.h" #ifdef __SUPPORT_OPENPGP__ #ifdef UPLOAD_CAP_MODULE #include "modules/upload/upload_build.h" #else #include "modules/url/mime/upload_build.h" #endif #endif #if !defined(URL_CAP_GLOBAL_OBJECTS_IN_GOPERA) extern MpSocketFactory* g_socket_factory; extern MpSocketAddressFactory* g_sockaddr_factory; extern MpHostResolverFactory* g_resolver_factory; #endif class ProtocolComm; class ServerName; // ---------------------------------------------------- #ifdef _DEBUG OpVector<DebugReferences> g_debug_references; #endif #ifdef _DEBUG void AddToReferencesList(DebugReferences::DebugReferencesTypes type, const OpStringC8& source_file, int source_line, const void* object_ptr) { OP_ASSERT(object_ptr); DebugReferences* dbg_ref = OP_NEW(DebugReferences, ()); OP_ASSERT(dbg_ref); if (dbg_ref!=NULL) { dbg_ref->type = type; OpStatus::Ignore(dbg_ref->source_file.Set(source_file)); dbg_ref->source_line = source_line; dbg_ref->object_ptr = object_ptr; g_debug_references.Add(dbg_ref); } } #endif //_Debug #ifdef _DEBUG void RemoveFromReferencesList(DebugReferences::DebugReferencesTypes type, const void* object_ptr) { if (!object_ptr) return; UINT32 count = g_debug_references.GetCount(); DebugReferences* dbg_ref = NULL; UINT32 i; for (i=0; i<count; i++) { dbg_ref = g_debug_references.Get(i); if (dbg_ref && dbg_ref->type==type && dbg_ref->object_ptr==object_ptr) break; } OP_ASSERT(dbg_ref && i<count); //If dbg_ref==NULL, the given object has not been allocated using Create-functions! if (dbg_ref && i<count) { g_debug_references.Delete(i); } } #endif //_Debug // ---------------------------------------------------- MailerGlue::MailerGlue() : m_engine_glue(NULL), m_factory(NULL) { #ifdef _DEBUG g_debug_references.Clear(); #endif } MailerGlue::~MailerGlue() { OP_ASSERT(m_factory == NULL); //Should be deleted by calling MailerGlue::Stop() OP_ASSERT(m_engine_glue == NULL); //Should be deleted by calling MailerGlue::Stop() if (m_engine_glue || m_factory) Stop(); #if (1) && defined (_DEBUG) UINT32 i; DebugReferences* dbg_ref; for (i=0; i<g_debug_references.GetCount(); i++) { dbg_ref = g_debug_references.Get(i); // OP_ASSERT(0); //If you get an assert here, please take a note of dbg_ref->type, dbg_ref->source_file and //dbg_ref->source_line, and notify someone on the M2 team. } g_debug_references.Clear(); #endif } OP_STATUS MailerGlue::Start(OpString8& status) { status.Empty(); if (!(m_factory = OP_NEW(MailerUtilFactory, ()))) { status.Append("Out of memory\n"); return OpStatus::ERR_NO_MEMORY; } MessageEngine::CreateInstance(); if (!g_m2_engine) return OpStatus::ERR_NO_MEMORY; m_engine_glue = g_m2_engine; // set us as listener #ifdef IRC_SUPPORT m_engine_glue->AddChatListener(this); #endif // IRC_SUPPORT m_engine_glue->AddInteractionListener(this); // export the factories m_engine_glue->SetFactories(m_factory); // let's go { OP_PROFILE_METHOD("MailEngineGlue::Init completed"); OP_STATUS result = m_engine_glue->Init(status); if (OpStatus::IsError(result)) { if (status.IsEmpty()) status.Set("Engine Init() failed\n"); return result; } } return OpStatus::OK; } OP_STATUS MailerGlue::Stop() { // remove us as listener if (m_engine_glue) { #ifdef IRC_SUPPORT m_engine_glue->RemoveChatListener(this); #endif // IRC_SUPPORT m_engine_glue->RemoveInteractionListener(this); } MessageEngine::DestroyInstance(); m_engine_glue = NULL; //Has been deleted when calling delete_ui OP_DELETE(m_factory); //Because of OpString and HeapProblems, m_factory should be the deleted last! m_factory = NULL; return OpStatus::OK; } // Debug function, should be removed when M2 gets a real UI OP_STATUS MailerGlue::MailCommand(URL& url) { return m_engine_glue->MailCommand(url); } // Implementing the MessageEngine listener interfaces #ifdef IRC_SUPPORT void MailerGlue::OnChatRoomJoined(UINT16 account_id, const ChatInfo& room) { g_application->GoToChat(account_id, room, TRUE, TRUE); } void MailerGlue::OnChatMessageReceived(UINT16 account_id, EngineTypes::ChatMessageType type, const OpStringC& message, const ChatInfo& chat_info, const OpStringC& chatter, BOOL is_private_chat) { ChatDesktopWindow* window = ChatDesktopWindow::FindChatRoom(account_id, chat_info.ChatName(), !is_private_chat); if (window == NULL) { if (is_private_chat) { if (type == EngineTypes::PRIVATE_MESSAGE || type == EngineTypes::PRIVATE_ACTION_MESSAGE) { BOOL open_in_background = FALSE; AccountManager* account_manager = g_m2_engine ? g_m2_engine->GetAccountManager() : 0; if (account_manager != 0) { Account* account = 0; account_manager->GetAccountById(account_id, account); OP_ASSERT(account != 0); open_in_background = account->GetOpenPrivateChatsInBackground(); } g_application->GoToChat(account_id, chat_info, FALSE, FALSE, open_in_background); } else if (type == EngineTypes::PRIVATE_SELF_MESSAGE) { // Perhaps open a window in the background if we sent a message // ourself, without an existing a chat window for it? g_application->GoToChat(account_id, chat_info, FALSE, FALSE, TRUE); } } } } void MailerGlue::OnInvite(UINT16 account_id, const OpStringC& nick, const ChatInfo& room) { // Ensure a window exists for this nickname. ChatInfo Nicholas(nick); OnChatMessageReceived(account_id, EngineTypes::PRIVATE_ACTION_MESSAGE, UNI_L(""), Nicholas, nick, TRUE); } void MailerGlue::OnFileReceiveRequest(UINT16 account_id, const OpStringC& sender, const OpStringC& filename, UINT32 file_size, UINT port_number, UINT id) { // Ensure a window exists for the sender of the file. ChatInfo chat_info(sender); OnChatMessageReceived(account_id, EngineTypes::PRIVATE_ACTION_MESSAGE, UNI_L(""), chat_info, sender, TRUE); } #endif // IRC_SUPPORT void MailerGlue::OnChangeNickRequired(UINT16 account_id, const OpStringC& old_nick) { #ifdef IRC_SUPPORT ChangeNickDialog* dialog = OP_NEW(ChangeNickDialog, (ChangeNickDialog::CHANGE_NICK_IN_USE, account_id, old_nick)); if (!dialog) return; dialog->Init(g_application->GetActiveDesktopWindow()); #endif // IRC_SUPPORT } void MailerGlue::OnRoomPasswordRequired(UINT16 account_id, const OpStringC& room) { #ifdef IRC_SUPPORT RoomPasswordDialog* dialog = OP_NEW(RoomPasswordDialog, (account_id, room)); if (!dialog) return; DesktopWindow * window = NULL; if (room.HasContent()) window = ChatDesktopWindow::FindChatRoom(account_id, room, TRUE); if (!window) window = g_application->GetActiveDesktopWindow(); dialog->Init(window); #endif // IRC_SUPPORT } void MailerGlue::OnYesNoInputRequired(UINT16 account_id, EngineTypes::YesNoQuestionType type, OpString* sender, OpString* param) { switch(type) { case EngineTypes::DELETE_DOWNLOADED_MESSAGES_ON_SERVER: { AskServerCleanupController* controller = OP_NEW(AskServerCleanupController, (account_id)); OpStatus::Ignore(ShowDialog(controller,g_global_ui_context, g_application ? g_application->GetActiveDesktopWindow() : NULL)); break; } default: OP_ASSERT(0); //this is wrong break; } } void MailerGlue::OnError(UINT16 account_id, const OpStringC& errormessage, const OpStringC& context, EngineTypes::ErrorSeverity severity) { OpConsoleEngine::Severity console_severity; switch(severity) { case EngineTypes::VERBOSE: console_severity = OpConsoleEngine::Verbose; break; case EngineTypes::INFORMATION: console_severity = OpConsoleEngine::Information; break; case EngineTypes::GENERIC_ERROR: console_severity = OpConsoleEngine::Error; break; case EngineTypes::CRITICAL: console_severity = OpConsoleEngine::Critical; break; case EngineTypes::DONOTSHOW: default: console_severity = OpConsoleEngine::DoNotShow; break; } if (g_console) { OpConsoleEngine::Message msg(OpConsoleEngine::M2, console_severity); msg.context.Set(context); msg.message.Set(errormessage); msg.url.Empty(); TRAPD(rc, g_console->PostMessageL(&msg)); } } // ---------------------------------------------------- class CommGlue : public ProtocolComm, // from Opera public ProtocolConnection, // from m2 public Autodeletable, public OpTimerListener { public: CommGlue(); ~CommGlue(); // ProtocolConnection (from m2) OP_STATUS SetClient(Client* client); OP_STATUS Connect(const char* hostname, const char* service, port_t port, BOOL ssl, BOOL V3_handshake = FALSE); unsigned int Read(char* buf, size_t buflen); OP_STATUS Send(char *buf, size_t buflen); OP_STATUS SetTimeout(time_t seconds, BOOL timeout_on_idle); void RestartTimeoutTimer(); void OnTimeOut(OpTimer* timer); OP_STATUS StartTLS(); virtual void StopConnectionTimer(); char* AllocBuffer(size_t size); void FreeBuffer(char* buf); void Release(); private: // ProtocolComm (from Opera) void RequestMoreData(); void ProcessReceivedData(); void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); virtual void SetProgressInformation(ProgressState progress_level, unsigned long progress_info1=0, const uni_char *progress_info2 = NULL); UINT TimeoutCheckInterval() const { return m_timeout_secs > 0 ? MAX((m_timeout_secs * 1000) / 5, 1000) : 0; } Client* m_client; ServerName* m_hostname; port_t m_port; time_t m_timeout_secs; BOOL m_timeout_on_idle; OpTimer m_timeout_timer; BOOL m_ssl; }; // ---------------------------------------------------- CommGlue::CommGlue() : ProtocolComm(g_main_message_handler, NULL, NULL), m_client(NULL), m_hostname(NULL), m_port(0), m_timeout_secs(0), m_ssl(FALSE) { } CommGlue::~CommGlue() { #ifdef _DEBUG OP_ASSERT(m_ok_to_delete==TRUE); #endif } void CommGlue::Release() { OP_DELETE(this); } OP_STATUS CommGlue::SetClient(Client* client) { m_client = client; return OpStatus::OK; } unsigned int CommGlue::Read(char* buf, size_t buflen) { return ProtocolComm::ReadData(buf, buflen); } OP_STATUS CommGlue::Send(char *buf, size_t buflen) { ProtocolComm::SendData(buf, buflen); if (ProtocolComm::Closed()) { if (GetSink() != 0) mh->PostMessage(MSG_COMM_LOADING_FAILED, Id(), ERR_COMM_CONNECTION_CLOSED); mh->PostMessage(MSG_COMM_LOADING_FINISHED, Id(), 0); } else { // We have sent something, start timeout timer if (buflen) RestartTimeoutTimer(); } return OpStatus::OK; } OP_STATUS CommGlue::SetTimeout(time_t seconds, BOOL timeout_on_idle) { m_timeout_secs = seconds; m_timeout_on_idle = timeout_on_idle; // Make sure we get timeout events m_timeout_timer.SetTimerListener(this); return OpStatus::OK; } void CommGlue::RestartTimeoutTimer() { m_timeout_timer.Stop(); // Start timer if necessary if (m_timeout_secs) m_timeout_timer.Start(m_timeout_secs * 1000); } void CommGlue::OnTimeOut(OpTimer* timer) { OP_ASSERT(timer == &m_timeout_timer); // Signal client that connection will close if (m_client) m_client->OnClose(OpStatus::OK); // Close connection Stop(); } char* CommGlue::AllocBuffer(size_t size) { return OP_NEWA(char, size); } void CommGlue::FreeBuffer(char* buf) { OP_DELETEA(buf); } OP_STATUS CommGlue::Connect(const char* hostname, const char* service, port_t port, BOOL ssl, BOOL V3_handshake) { m_hostname = urlManager->GetServerName(hostname, TRUE); m_port = port; m_ssl = ssl; SComm* comm = Comm::Create(g_main_message_handler, m_hostname, m_port, FALSE); if (comm) { // M2 must handle the number of open connections independently from // normal browser Comm objects. This means that when Comm runs out // of connections, mail connections will not be taken down, and that // can have negative performance impact on browsing unless M2 makes // sure to keep the number of open connections to a minimum. ((Comm*)comm)->SetManagedConnection(); } if (ssl) { ProtocolComm *ssl_comm = g_ssl_api->Generate_SSL(g_main_message_handler, m_hostname, m_port, V3_handshake); if (ssl_comm == NULL) { OP_DELETE(comm); return OpStatus::ERR; } ssl_comm->SetNewSink(comm); comm = ssl_comm; } SetNewSink(comm); SetCallbacks(NULL,NULL); if (ProtocolComm::Load() != COMM_LOADING) { return OpStatus::ERR; } // Restart timer RestartTimeoutTimer(); return OpStatus::OK; } void CommGlue::StopConnectionTimer() { m_timeout_timer.Stop(); } OP_STATUS CommGlue::StartTLS() { #ifdef _SSL_SUPPORT_ return ProtocolComm::InsertTLSConnection(m_hostname, m_port) ? OpStatus::OK : OpStatus::ERR; #else return OpStatus::ERR_NOT_SUPPORTED; #endif // _SSL_SUPPORT_ } void CommGlue::RequestMoreData() { SetDoNotReconnect(TRUE); if (m_client) m_client->RequestMoreData(); } void CommGlue::ProcessReceivedData() { OP_STATUS ret = OpStatus::OK; // Data received, stop timer RestartTimeoutTimer(); // Let client process data if (m_client) ret = m_client->ProcessReceivedData(); // See if we were disconnected if (ret != OpStatus::ERR_NO_SUCH_RESOURCE && ProtocolComm::Closed()) { if (GetSink() != 0) mh->PostMessage(MSG_COMM_LOADING_FAILED, Id(), ERR_COMM_CONNECTION_CLOSED); mh->PostMessage(MSG_COMM_LOADING_FINISHED, Id(), 0); } } void CommGlue::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { switch (msg) { case MSG_COMM_LOADING_FINISHED: g_main_message_handler->RemoveCallBacks(this, par1); // prevents ssl connections to send double MSG_COMM_LOADING_FINISHED if (m_client) m_client->OnClose(OpStatus::OK); break; case MSG_COMM_LOADING_FAILED: if (m_client) { // ERR_COMM_HOST_NOT_FOUND is offline for windows, we don't need to report an error then if (par2 == Str::S_MSG_SSL_NonFatalError_Retry) m_client->OnRestartRequested(); else m_client->OnClose((par2==ERR_COMM_CONNECTION_CLOSED || par2==ERR_SSL_ERROR_HANDLED || par2==ERR_COMM_HOST_NOT_FOUND) ? OpStatus::OK : OpStatus::ERR_NO_ACCESS); // no server contact? } break; #ifdef LIBSSL_CAP_HAS_RESTART_MESSAGE case MSG_SSL_RESTART_CONNECTION: if (m_client) m_client->OnRestartRequested(); break; #endif // LIBSSL_CAP_HAS_RESTART_MESSAGE default: OP_ASSERT((int)msg != ERR_COMM_CONNECTION_CLOSED); //If this is reached, contact julienp@opera.com or arjanl@opera.com return; } } void CommGlue::SetProgressInformation(ProgressState progress_level, unsigned long progress_info1, const uni_char *progress_info2) { if(progress_level == RESTART_LOADING) { if(progress_info2) *((BOOL *) progress_info2) = m_ssl && (is_connected ? FALSE : TRUE); return; } ProtocolComm::SetProgressInformation(progress_level, progress_info1, progress_info2); } // ---------------------------------------------------- class MessageLoopGlue : public MessageLoop, public MessageObject { public: MessageLoopGlue(); ~MessageLoopGlue(); void Release(); OP_STATUS SetTarget(Target* target); OP_STATUS Post(OpMessage message, time_t delay = 0); OP_STATUS Send(OpMessage message); void HandleCallback(OpMessage msg, MH_PARAM_1 wParam, MH_PARAM_2 lParam); private: Target *m_target; }; MessageLoopGlue::MessageLoopGlue() { m_target = NULL; } MessageLoopGlue::~MessageLoopGlue() { g_main_message_handler->UnsetCallBacks(this); } void MessageLoopGlue::Release() { OP_DELETE(this); } OP_STATUS MessageLoopGlue::SetTarget(Target* target) { m_target = target; return OpStatus::OK; } OP_STATUS MessageLoopGlue::Post(OpMessage message, time_t delay) { if (!g_main_message_handler->HasCallBack(this, message, 0)) { g_main_message_handler->SetCallBack(this, message, 0); } // g_main_message_handler->SendMessage(message,(int)this,(int)m_target); g_main_message_handler->PostDelayedMessage(message, (MH_PARAM_1)this, (MH_PARAM_2)m_target, delay); return OpStatus::OK; } OP_STATUS MessageLoopGlue::Send(OpMessage message) { if (!g_main_message_handler->HasCallBack(this, message, 0)) { g_main_message_handler->SetCallBack(this, message, 0); } g_main_message_handler->PostMessage(message, (MH_PARAM_1)this, (MH_PARAM_2)m_target); // used to be SendMessage in Core-1 return OpStatus::OK; } void MessageLoopGlue::HandleCallback(OpMessage msg, MH_PARAM_1 wParam, MH_PARAM_2 lParam) { if ((wParam == (MH_PARAM_1)this) && (lParam == (MH_PARAM_2)m_target)) { m_target->Receive(msg); } } // *************************************************************************** // // BrowserUtilsURLStream // // *************************************************************************** BrowserUtilsURLStream::BrowserUtilsURLStream() : m_source_len(0), m_has_more(FALSE) { } BrowserUtilsURLStream::~BrowserUtilsURLStream() { } OP_STATUS BrowserUtilsURLStream::Init(URL& url) { OP_ASSERT(m_data_descriptor.get() == 0); RETURN_IF_ERROR(MarkURLAsGenerated(url)); // Fetch the data descriptor that we will read data from. m_data_descriptor = url.GetDescriptor(NULL, TRUE); if (m_data_descriptor.get() == 0) return URL_UNKNOWN_CONTENT; m_has_more = TRUE; return OpStatus::OK; } OP_STATUS BrowserUtilsURLStream::NextChunk(OpString& chunk) { OP_ASSERT(HasMoreChunks()); m_has_more = FALSE; TRAPD(err, m_source_len = m_data_descriptor->RetrieveDataL(m_has_more)); if (OpStatus::IsError(err)) { m_has_more = FALSE; return URL_UNKNOWN_CONTENT; } if (m_source_len == 0) { m_has_more = FALSE; return URL_UNKNOWN_CONTENT; } const uni_char *src = (const uni_char *)(m_data_descriptor->GetBuffer()); if (src == 0) { m_has_more = FALSE; return URL_UNKNOWN_CONTENT; } chunk.Empty(); RETURN_IF_ERROR(chunk.Append(src, UNICODE_DOWNSIZE(m_source_len))); m_data_descriptor->ConsumeData(m_source_len); return OpStatus::OK; } OP_STATUS BrowserUtilsURLStream::NextChunk(OpByteBuffer& chunk) { OP_ASSERT(HasMoreChunks()); m_has_more = FALSE; TRAPD(err, m_source_len = m_data_descriptor->RetrieveDataL(m_has_more)); if (OpStatus::IsError(err)) return URL_UNKNOWN_CONTENT; unsigned char *src = (unsigned char *)m_data_descriptor->GetBuffer(); if (src == NULL || m_source_len == 0) return URL_UNKNOWN_CONTENT; chunk.Empty(); RETURN_IF_ERROR(chunk.Append(src, m_source_len)); m_data_descriptor->ConsumeData(m_source_len); return OpStatus::OK; } OP_STATUS BrowserUtilsURLStream::MarkURLAsGenerated(URL& url) const { // Hack to mark the url as generated; avoiding that Opera will use the // default encoding selected for web pages. Should be replaced by // something better eventually. RETURN_IF_ERROR(url.SetAttribute(URL::KIsGenerated, 1)); return OpStatus::OK; } // ---------------------------------------------------- BrowserUtilsGlue::BrowserUtilsGlue() { } BrowserUtilsGlue::~BrowserUtilsGlue() { } const char* BrowserUtilsGlue::GetLocalHost() { return Comm::GetLocalHostName(); } const char* BrowserUtilsGlue::GetLocalFQDN() { // TODO find out what this does and why //This function should be part of PortingInterface MpHostResolver const char* hostname = GetLocalHost(); if (hostname && *hostname) { struct hostent* host = gethostbyname(hostname); if (host && host->h_addr_list && host->h_addr_list[0]) { host = gethostbyaddr(host->h_addr_list[0],host->h_length, host->h_addrtype); if (host && host->h_name) { return host->h_name; } } } return NULL; } OP_STATUS BrowserUtilsGlue::ResolveUrlName(const OpStringC& szNameIn, OpString& szResolved) { TRAPD(ret, ResolveUrlNameL(szNameIn, szResolved)); return ret; } OP_STATUS BrowserUtilsGlue::GetURL(URL*& url, const uni_char* url_string) { if (!url) return OpStatus::ERR_NULL_POINTER; *url = g_url_api->GetURL(url_string); return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::WriteStartOfMailUrl(URL* url, const Message* message) { if (!url) return OpStatus::ERR_NULL_POINTER; url->Unload(); RETURN_IF_ERROR(url->SetAttribute(URL::KMIME_ForceContentType, "text/html")); OpString body_comment; if (OpStatus::IsSuccess(g_languageManager->GetString(Str::S_MESSAGE_BODY_NOT_DOWNLOADED, body_comment))) { OpStatus::Ignore(SetUrlComment(url, body_comment)); } //Decide TextpartSetting Message::TextpartSetting body_mode = (Message::TextpartSetting)g_pcm2->GetIntegerPref(PrefsCollectionM2::MailBodyMode); if (message->IsFlagSet(Message::PARTIALLY_FETCHED)) { body_mode = Message::PREFER_TEXT_PLAIN; } else if (body_mode==Message::DECIDED_BY_ACCOUNT && message) { body_mode = message->GetTextPartSetting(); } RETURN_IF_ERROR(url->SetAttribute(URL::KIgnoreWarnings, TRUE)); RETURN_IF_ERROR(url->SetAttribute(URL::KPreferPlaintext, body_mode==Message::PREFER_TEXT_PLAIN || body_mode==Message::FORCE_TEXT_PLAIN)); return url->SetAttribute(URL::KBigAttachmentIcons, FALSE); } OP_STATUS BrowserUtilsGlue::WriteEndOfMailUrl(URL* url, const Message* message) { if (!url) return OpStatus::ERR_NULL_POINTER; url->WriteDocumentDataFinished(); url->ForceStatus(URL_LOADED); return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::WriteToUrl(URL* url, const char* data, int length) const { if (!url) return OpStatus::ERR_NULL_POINTER; while (length) { // making smaller portions to try to optimize speed of MIME decoding (johan 20050825) int chunk = length; const char* chunk_start = data; const int chunk_size = 100*1024; if (length > chunk_size) { chunk = chunk_size; length -= chunk_size; data += chunk_size; } else { length = 0; // break out after write } url->WriteDocumentData(URL::KNormal, chunk_start, chunk); } return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::SetUrlComment(URL* url, const OpStringC& comment) { if (!url) return OpStatus::ERR_NULL_POINTER; return url->SetAttribute(URL::KBodyCommentString, comment); } OP_STATUS BrowserUtilsGlue::CreateTimer(OpTimer** timer, OpTimerListener* listener) { OP_ASSERT(!(*timer)); // don't overwrite existing timers if (!(*timer = OP_NEW(OpTimer, ()))) return OpStatus::ERR_NO_MEMORY; if(listener) (*timer)->SetTimerListener(listener); return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::GetUserAgent(OpString8& useragent, UA_BaseStringId override_useragent) { OpString ua; ua.AppendFormat(UNI_L("Opera Mail/%s (%s)"), VER_NUM_STR_UNI, g_op_system_info->GetPlatformStr()); return useragent.Set(ua.CStr()); } time_t BrowserUtilsGlue::CurrentTime() { return g_timecache->CurrentTime(); } long BrowserUtilsGlue::CurrentTimezone() { /* IMPORTANT: This function returns the local timezone without adjustments for daylight savings time */ return g_op_time_info->GetTimezone() + (long)(g_op_time_info->DaylightSavingsTimeAdjustmentMS(g_op_time_info->GetTimeUTC())/1000); } double BrowserUtilsGlue::GetWallClockMS() { return g_op_time_info->GetWallClockMS(); } BOOL BrowserUtilsGlue::OfflineMode() { return g_pcnet->GetIntegerPref(PrefsCollectionNetwork::OfflineMode); } BOOL BrowserUtilsGlue::TLSAvailable() { BOOL tls = g_pcnet->GetIntegerPref(PrefsCollectionNetwork::EnableSSL3_1); //TLS1.0 //tls |= g_pcnet->GetIntegerPref(PrefsCollectionNetwork::EnableTLS1_1); //TLS1.1 return tls; } OP_STATUS BrowserUtilsGlue::ConvertFromIMAAAddress(const OpStringC8& imaa_address, OpString16& address, BOOL& is_mailaddress) const { address.Empty(); if (!address.Reserve(24+imaa_address.Length()*4)) //This size should defintly be calculated more accurate return OpStatus::ERR_NO_MEMORY; TRAPD(err, IDNA::ConvertFromIDNA_L(imaa_address.CStr(), const_cast<uni_char*>(address.CStr()), address.Capacity()-1, is_mailaddress)); if(OpStatus::IsError(err)) return err; return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::PathDirFileCombine(OUT OpString& dest, IN const OpStringC& directory, IN const OpStringC& file) const { return OpPathDirFileCombine(dest, directory, file); } OP_STATUS BrowserUtilsGlue::PathAddSubdir (OUT OpString& dest, IN const OpStringC& subdir) { return OpPathDirFileCombine(dest, dest, subdir); } OP_STATUS BrowserUtilsGlue::GetSelectedText(OUT OpString16& text) const { text.Empty(); MailDesktopWindow* mail_window = g_application->GetActiveMailDesktopWindow(); Window* window = (mail_window && mail_window->GetMailView()) ? mail_window->GetMailView()->GetWindow() : NULL; DocumentManager* doc_manager = window ? window->DocManager() : NULL; FramesDocument* document = doc_manager ? doc_manager->GetCurrentDoc() : NULL; if (!document) return OpStatus::OK; return document->GetSelectedText(text); } OP_STATUS BrowserUtilsGlue::FilenamePartFromFullFilename(const OpStringC& full_filename, OpString &filename_part) const { OP_STATUS status = OpStatus::OK; OpString name_part; OpString extension_part; OpString candidate; candidate.Set(full_filename); TRAP(status, SplitFilenameIntoComponentsL(candidate, 0, &name_part, &extension_part)); RETURN_IF_ERROR(status); filename_part.TakeOver(name_part); RETURN_IF_ERROR(filename_part.Append(UNI_L("."))); return filename_part.Append(extension_part); } OP_STATUS BrowserUtilsGlue::GetContactName(const OpStringC &mail_address, OpString &full_name) { OpString formatted_address; MailFormatting::FormatListIdToEmail(mail_address, formatted_address); HotlistManager::ItemData item_data; if( g_hotlist_manager ) g_hotlist_manager->GetItemValue_ByEmail( formatted_address, item_data ); if( !item_data.name.IsEmpty() ) { return full_name.Set( item_data.name ); } else { return full_name.Set(mail_address); } } OP_STATUS BrowserUtilsGlue::GetContactImage(const OpStringC &mail_address, const char*& image) { OpString formatted_address; MailFormatting::FormatListIdToEmail(mail_address, formatted_address); HotlistManager::ItemData item_data; if( g_hotlist_manager ) g_hotlist_manager->GetItemValue_ByEmail( formatted_address, item_data ); if (item_data.direct_image_pointer) { image = item_data.direct_image_pointer; } return OpStatus::OK; } INT32 BrowserUtilsGlue::GetContactCount() { #if 0 return g_hotlist_manager->GetContactsModel()->GetItemCount(); #else INT32 contact_count = 0; HotlistModel* contacts_model = g_hotlist_manager->GetContactsModel(); if (contacts_model != 0) { HotlistModelItem* trash_item = contacts_model->GetTrashFolder(); OP_ASSERT(trash_item != 0); for (INT32 index = 0, item_count = contacts_model->GetItemCount(); index < item_count; ++index) { HotlistModelItem* item = contacts_model->GetItemByIndex(index); OP_ASSERT(item != 0); if ((!item->GetIsTrashFolder()) && (!item->IsChildOf(trash_item))) ++contact_count; } } return contact_count; #endif } OP_STATUS BrowserUtilsGlue::GetContactByIndex(INT32 index, INT32& id, OpString& nick) { #if 0 HotlistModelItem* item = g_hotlist_manager->GetContactsModel()->GetItemByIndex(index); if (!item) { nick.Empty(); return OpStatus::ERR; } nick.Set(item->GetShortName().CStr()); #else HotlistModel* contacts_model = g_hotlist_manager->GetContactsModel(); if (contacts_model == 0) return OpStatus::ERR; HotlistModelItem* trash_item = contacts_model->GetTrashFolder(); OP_ASSERT(trash_item != 0); INT32 real_index = 0; for (INT32 count = 0, item_count = contacts_model->GetItemCount(); count < item_count; ++count) { HotlistModelItem* item = contacts_model->GetItemByIndex(count); OP_ASSERT(item != 0); if ((!item->GetIsTrashFolder()) && (!item->IsChildOf(trash_item))) { if (index == real_index) { id = item->GetID(); RETURN_IF_ERROR(nick.Set(item->GetShortName())); break; } ++real_index; } } #endif return OpStatus::OK; } BOOL BrowserUtilsGlue::IsContact(const OpStringC &mail_address) { OpString formatted_address; MailFormatting::FormatListIdToEmail(mail_address, formatted_address); return g_hotlist_manager && g_hotlist_manager->IsContact(formatted_address); } OP_STATUS BrowserUtilsGlue::AddContact(const OpStringC& mail_address, const OpStringC& full_name, BOOL is_mailing_list, int parent_folder_id) { OpString notes; return AddContact(mail_address, full_name, notes, is_mailing_list, parent_folder_id); } OP_STATUS BrowserUtilsGlue::AddContact(const OpStringC& mail_address, const OpStringC& full_name, const OpStringC& notes, BOOL is_mailing_list, int parent_folder_id) { //IMAA-addresses should not be present here, they should have been decoded to the unicode-version //(unless the user explicitly wants to add an IMAA-address, for some strange reason) OP_ASSERT(mail_address.Find("@xn--")==KNotFound); if (IsContact(mail_address)) { return OpStatus::OK; } OpString formatted_address; MailFormatting::FormatListIdToEmail(mail_address, formatted_address); HotlistManager::ItemData item_data; item_data.name.Set( full_name ); item_data.mail.Set( formatted_address ); item_data.description.Set( notes ); item_data.image.Set( is_mailing_list ? UNI_L("Contact37") : UNI_L("Contact0") ); if( !is_mailing_list) g_hotlist_manager->SetupPictureUrl(item_data); g_hotlist_manager->NewContact( item_data, parent_folder_id, 0, FALSE ); return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::PlaySound(OpString& path) { return SoundUtils::SoundIt(path, TRUE); } int BrowserUtilsGlue::NumberOfCachedHeaders() { UINT32 megabytes = g_op_system_info->GetPhysicalMemorySizeMB(); int prefered = megabytes * 10; return max(min(prefered, 40000), 100); } OP_STATUS BrowserUtilsGlue::ShowIndex(index_gid_t id, BOOL force_download) { if (!g_application) return OpStatus::ERR_NULL_POINTER; g_application->GoToMailView(id, NULL, NULL, TRUE, FALSE, force_download); return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::SetFromUTF8(OpString* string, const char* aUTF8str, int aLength) { return string->SetFromUTF8(aUTF8str, aLength); } extern int ReplaceEscapes(uni_char* txt, BOOL require_termination, BOOL remove_tabs, BOOL treat_nbsp_as_space); OP_STATUS BrowserUtilsGlue::ReplaceEscapes(OpString& string) { if (string.IsEmpty()) { // ReplaceEscapes returns 0 and nothing to do. return OpStatus::OK; } int num = ::ReplaceEscapes(string.CStr(), TRUE, FALSE, TRUE); if (num == 0) { // OP_ASSERT(0); return OpStatus::ERR; } return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::GetTransferItem(OpTransferItem** item, const OpStringC& url_string, BOOL* already_created) { return ((TransferManager*)g_transferManager)->GetTransferItem(item, url_string.CStr(), already_created); } OP_STATUS BrowserUtilsGlue::StartLoading(URL* url) { if (!url) return OpStatus::ERR_NULL_POINTER; MessageHandler *oldHandler = url->GetFirstMessageHandler(); url->ChangeMessageHandler(oldHandler ? oldHandler : g_main_message_handler, g_main_message_handler); // if(url->Status(0) == URL_UNLOADED) //hack to work around failed second download. { URL tmp; url->Reload(g_main_message_handler, tmp, FALSE, FALSE); } return OpStatus::OK; } OP_STATUS BrowserUtilsGlue::ReadDocumentData(URL& url, BrowserUtilsURLStream& url_stream) { RETURN_IF_ERROR(url_stream.Init(url)); return OpStatus::OK; } void BrowserUtilsGlue::DebugStatusText(const uni_char* message) { if (g_application) { DesktopWindow* dw = g_application->GetActiveDesktopWindow(); if (dw) { dw->SetStatusText(message); } } } #ifdef MSWIN OP_STATUS BrowserUtilsGlue::OpRegReadStrValue(IN HKEY hKeyRoot, IN LPCTSTR szKeyName, IN LPCTSTR szValueName, OUT LPCTSTR szValue, IO DWORD *pdwSize) { return (::OpRegReadStrValue(hKeyRoot, szKeyName, szValueName, szValue, pdwSize) == ERROR_SUCCESS ? OpStatus::OK : OpStatus::ERR); } LONG BrowserUtilsGlue::_RegEnumKeyEx(HKEY hKey, DWORD dwIndex, LPWSTR lpName, LPDWORD lpcbName, LPDWORD lpReserved, LPWSTR lpClass, LPDWORD lpcbClass, PFILETIME lpftLastWriteTime) { return ::RegEnumKeyEx(hKey, dwIndex, lpName, lpcbName, lpReserved, lpClass, lpcbClass, lpftLastWriteTime); } LONG BrowserUtilsGlue::_RegOpenKeyEx(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult) { return ::RegOpenKeyEx(hKey, lpSubKey, ulOptions, samDesired, phkResult); } LONG BrowserUtilsGlue::_RegQueryValueEx(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) { return ::RegQueryValueEx(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData); } LONG BrowserUtilsGlue::_RegCloseKey(HKEY hKey) { return ::RegCloseKey(hKey); } DWORD BrowserUtilsGlue::_ExpandEnvironmentStrings(LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize) { return ::ExpandEnvironmentStrings(lpSrc, lpDst, nSize); } #endif //MSWIN void BrowserUtilsGlue::SubscribeDialog(UINT16 account_id) { AccountSubscriptionDialog* dialog = OP_NEW(AccountSubscriptionDialog, ()); if (dialog) dialog->Init(account_id, NULL); } BOOL BrowserUtilsGlue::MatchRegExp(const OpStringC& regexp, const OpStringC& string) { #if defined(_ECMASCRIPT_SUPPORT_) && !defined(ECMASCRIPT_NO_EXPORT_REGEXP) { if (regexp.IsEmpty() || string.IsEmpty()) { return FALSE; } // Special case: accept a single * as match anything if (regexp.Compare("*") == 0) { return TRUE; } int nmatches = 0; OpREMatchLoc *locs = NULL; OpREFlags flags; flags.multi_line = FALSE; flags.case_insensitive = TRUE; flags.ignore_whitespace = FALSE; OpRegExp *re; RETURN_VALUE_IF_ERROR(OpRegExp::CreateRegExp(&re, regexp.CStr(), &flags), FALSE); OpAutoPtr<OpRegExp> re_holder(re); RETURN_VALUE_IF_ERROR(re->Match(string.CStr(),&nmatches,&locs), FALSE); // According to documentation for Match(), the client must delete the // returned matches. Thus this should help to avoid a memory leak. if (nmatches > 0) OP_DELETEA(locs); return (nmatches > 0); /* example code OpRegExp *re; OpREMatchLoc loc; int nmatches; OpREMatchLoc *locs = NULL; OpREFlags flags; flags.multi_line = FALSE; flags.case_insensitive = TRUE; flags.ignore_whitespace = FALSE; OP_STATUS res = OpRegExp::CreateRegExp(&re, UNI_L("a*(b*)c"), &flags); assert( res == OpStatus::OK ); res = re->Match(UNI_L("xaaBBBBBBCCCCC"),&loc); assert( res == OpStatus::OK ); assert( loc.matchloc == 1 ); assert( loc.matchlen == 9 ); res = re->Match(UNI_L("xaaBBBBBBCCCCC"),&nmatches, &locs); assert( res == OpStatus::OK ); assert( nmatches == 2 ); assert( locs != NULL ); assert( locs[0].matchloc == 1 ); assert( locs[0].matchlen == 9 ); assert( locs[1].matchloc == 3 ); assert( locs[1].matchlen == 6 ); delete re; */ } #else return (regexp.FindI(string) != KNotFound); #endif // ECMASCRIPT_NO_EXPORT_REGEXP } // ---------------------------------------------------- void Decoder::DecodingStopped() { //#pragma PRAGMAMSG("FG: Signal all listeners that decoding is stopped") } void Decoder::SignalReDecodeMessage() { // TODO: we might have to delete it better than this, for instance with a destroyURL if (m_decoder_url) { m_decoder_url->Unload(); OP_DELETE(m_decoder_url); } m_decoder_url = NULL; //#pragma PRAGMAMSG("FG: Signal all listeners that decoding will restart") } OP_STATUS Decoder::DecodeMessage(const char* headers, const char* body, UINT32 message_size, BOOL ignore_content, BOOL body_only, BOOL prefer_plaintext, BOOL ignore_warnings, UINT32 id, MessageListener* listener) { UINT32 header_length = strlen(headers); UINT32 body_length = message_size - (header_length + 2); BrowserUtils* browser_glue = g_m2_engine->GetGlueFactory()->GetBrowserUtils(); OP_STATUS ret = OpStatus::OK; BOOL found_body = FALSE; OP_ASSERT(browser_glue); OP_ASSERT(listener); if (!listener) return OpStatus::ERR_NULL_POINTER; // Create mime decoder if (!m_decoder_url) { OpString8 urlstring; RETURN_IF_ERROR(urlstring.AppendFormat("operaemail:/reply_%d/%.0f.html", id, g_op_time_info->GetRuntimeMS())); m_decoder_url = OP_NEW(URL,(urlManager->GetURL(urlstring.CStr()))); } if (!m_decoder_url) { listener->OnFinishedDecodingMultiparts(OpStatus::ERR_NO_MEMORY); return OpStatus::ERR_NO_MEMORY; } // Set decoder properties RETURN_IF_ERROR(m_decoder_url->SetAttribute(URL::KCachePolicy_NoStore, TRUE)); RETURN_IF_ERROR(m_decoder_url->SetAttribute(URL::KPreferPlaintext, prefer_plaintext)); RETURN_IF_ERROR(m_decoder_url->SetAttribute(URL::KIgnoreWarnings, ignore_warnings)); RETURN_IF_ERROR(m_decoder_url->SetAttribute(URL::KBigAttachmentIcons, FALSE)); if (OpStatus::IsSuccess(ret)) { //Write message to decoder if (headers && *headers) browser_glue->WriteToUrl(m_decoder_url, headers, header_length); browser_glue->WriteToUrl(m_decoder_url, "\r\n", 2); if (body && *body) browser_glue->WriteToUrl(m_decoder_url, body, body_length); m_decoder_url->WriteDocumentDataFinished(); // Fetch parts URL suburl = URL(); BOOL is_inlined_and_visible_element; for (int mimepart_index = 0; OpStatus::IsSuccess(ret) && ((is_inlined_and_visible_element = m_decoder_url->GetAttachment(mimepart_index, suburl)) != 0 || !suburl.IsEmpty()); suburl = URL(), mimepart_index++) { // for the attachment to be inlined and visible, it has to be a URL_CONTENT_ID element and GetAttachment must return TRUE is_inlined_and_visible_element &= suburl.GetAttribute(URL::KType) == URL_CONTENT_ID || g_mime_module.HasContentID(suburl); ret = DecodeSuburl(suburl, found_body, ignore_content, body_only, listener, is_inlined_and_visible_element); } } listener->OnFinishedDecodingMultiparts(ret); //Signal that we are done, possibly with errors return ret; } OP_STATUS Decoder::DecodeSuburl(URL& suburl, BOOL& found_body, BOOL ignore_content, BOOL body_only, MessageListener* listener, BOOL is_visible) { URL* mimepart_url = NULL; URL_DataDescriptor* desc; URLContentType content_type; BOOL is_mailbody, takeover = FALSE; BYTE* mimepart_data = NULL; int mimepart_length = 0; OP_STATUS ret = OpStatus::OK; desc = suburl.GetDescriptor(NULL, TRUE, TRUE); mimepart_url = g_m2_engine->GetGlueFactory()->CreateURL(); if (!mimepart_url) { OP_DELETE(desc); return OpStatus::ERR_NO_MEMORY; } if (desc) *mimepart_url = desc->GetURL(); content_type = mimepart_url->ContentType(); mimepart_url->GetAttribute(URL::KType); is_mailbody = (!found_body && (content_type==URL_TEXT_CONTENT || content_type==URL_HTML_CONTENT)); if (desc && (!ignore_content || (body_only && is_mailbody))) { OpFileLength part_length = 0; suburl.GetAttribute(URL::KContentLoaded, &part_length, TRUE); mimepart_data = OP_NEWA(BYTE, (int)part_length + sizeof(uni_char)); // length of the attachment plus room for a terminator BOOL more = TRUE; const char *tmp_buffer; while (more) { int tmp_buffer_len = desc->RetrieveData(more); tmp_buffer = desc->GetBuffer(); if (tmp_buffer_len>0) { UINT32 new_length = mimepart_length + tmp_buffer_len; if (new_length > part_length) { // Doesn't fit, grow buffer BYTE* new_mimepart_data = OP_NEWA(BYTE, new_length + sizeof(uni_char)); if (!new_mimepart_data) { OP_DELETE(desc); OP_DELETEA(mimepart_data); g_m2_engine->GetGlueFactory()->DeleteURL(mimepart_url); return OpStatus::ERR_NO_MEMORY; } memcpy(new_mimepart_data, mimepart_data, mimepart_length); OP_DELETEA(mimepart_data); mimepart_data = new_mimepart_data; part_length = new_length; } // Copy fetched buffer memcpy(mimepart_data + mimepart_length, tmp_buffer, tmp_buffer_len); mimepart_length += tmp_buffer_len; } else if (desc->NeedRefresh()) { OP_DELETE(desc); OP_DELETEA(mimepart_data); g_m2_engine->GetGlueFactory()->DeleteURL(mimepart_url); return DecodeSuburl(suburl, found_body, ignore_content, body_only, listener, is_visible); } desc->ConsumeData(tmp_buffer_len); } // terminate for (size_t i = 0; i < sizeof(uni_char); i++) mimepart_data[mimepart_length + i] = 0; } if (mimepart_length > 0 || ignore_content) { OpString suggested_filename; TRAP(ret, mimepart_url->GetAttributeL(URL::KSuggestedFileName_L, suggested_filename, TRUE)); takeover = (OpStatus::IsSuccess(ret) && OpStatus::IsSuccess(ret = listener->OnDecodedMultipart(mimepart_url, suburl.GetAttribute(URL::KMIME_CharSet), suggested_filename, mimepart_length, mimepart_data, is_mailbody, is_visible))); } if (!takeover) { g_m2_engine->GetGlueFactory()->DeleteURL(mimepart_url); OP_DELETEA(mimepart_data); } OP_DELETE(desc); found_body |= is_mailbody; return ret; } // ---------------------------------------------------- class MimeUtilsGlue : public MimeUtils { public: // UTF8toUTF16Converter #ifdef _DEBUG UTF8toUTF16Converter* CreateUTF8toUTF16ConverterDbg(const OpStringC8& source_file, int source_line); #else UTF8toUTF16Converter* CreateUTF8toUTF16Converter(); #endif void DeleteUTF8toUTF16Converter(UTF8toUTF16Converter*); // UTF16toUTF8Converter #ifdef _DEBUG UTF16toUTF8Converter* CreateUTF16toUTF8ConverterDbg(const OpStringC8& source_file, int source_line); #else UTF16toUTF8Converter* CreateUTF16toUTF8Converter(); #endif void DeleteUTF16toUTF8Converter(UTF16toUTF8Converter*); // UTF7toUTF16Converter #ifdef _DEBUG UTF7toUTF16Converter* CreateUTF7toUTF16ConverterDbg(UTF7toUTF16Converter::utf7_variant variant, const OpStringC8& source_file, int source_line); #else UTF7toUTF16Converter* CreateUTF7toUTF16Converter(UTF7toUTF16Converter::utf7_variant variant); #endif void DeleteUTF7toUTF16Converter(UTF7toUTF16Converter*); // UTF16toUTF7Converter #ifdef _DEBUG UTF16toUTF7Converter* CreateUTF16toUTF7ConverterDbg(UTF16toUTF7Converter::utf7_variant variant, const OpStringC8& source_file, int source_line); #else UTF16toUTF7Converter* CreateUTF16toUTF7Converter(UTF16toUTF7Converter::utf7_variant variant); #endif void DeleteUTF16toUTF7Converter(UTF16toUTF7Converter*); OP_STATUS RemoveHeaderEscapes(const char* charset, const char *&src, OpString16& dst); #ifndef __SUPPORT_OPENPGP__ Upload_Base* CreateUploadElement(Upload_Element_Type typ); #else Upload_Builder_Base* CreateUploadBuilder(); void DeleteUploadBuilder(Upload_Builder_Base* builder) {OP_DELETE(builder);} #endif void DeleteUploadElement(Upload_Base* element) {OP_DELETE(element);} Decoder* CreateDecoder() { return OP_NEW(Decoder, ()); } void DeleteDecoder(Decoder* decoder) { OP_DELETE(decoder); } }; // ---------------------------------------------------- #ifdef _DEBUG UTF8toUTF16Converter* MimeUtilsGlue::CreateUTF8toUTF16ConverterDbg(const OpStringC8& source_file, int source_line) #else UTF8toUTF16Converter* MimeUtilsGlue::CreateUTF8toUTF16Converter() #endif { UTF8toUTF16Converter* converter = OP_NEW(UTF8toUTF16Converter, ()); #ifdef _DEBUG if (converter) AddToReferencesList(DebugReferences::M2REF_UTF8TOUTF16CONVERTER, source_file, source_line, converter); #endif return converter; } void MimeUtilsGlue::DeleteUTF8toUTF16Converter(UTF8toUTF16Converter* converter) { #ifdef _DEBUG if (converter) RemoveFromReferencesList(DebugReferences::M2REF_UTF8TOUTF16CONVERTER, converter); #endif OP_DELETE(converter); } #ifdef _DEBUG UTF16toUTF8Converter* MimeUtilsGlue::CreateUTF16toUTF8ConverterDbg(const OpStringC8& source_file, int source_line) #else UTF16toUTF8Converter* MimeUtilsGlue::CreateUTF16toUTF8Converter() #endif { UTF16toUTF8Converter* converter = OP_NEW(UTF16toUTF8Converter, ()); #ifdef _DEBUG if (converter) AddToReferencesList(DebugReferences::M2REF_UTF16TOUTF8CONVERTER, source_file, source_line, converter); #endif return converter; } void MimeUtilsGlue::DeleteUTF16toUTF8Converter(UTF16toUTF8Converter* converter) { #ifdef _DEBUG if (converter) RemoveFromReferencesList(DebugReferences::M2REF_UTF16TOUTF8CONVERTER, converter); #endif OP_DELETE(converter); } #ifdef _DEBUG UTF7toUTF16Converter* MimeUtilsGlue::CreateUTF7toUTF16ConverterDbg(UTF7toUTF16Converter::utf7_variant variant, const OpStringC8& source_file, int source_line) #else UTF7toUTF16Converter* MimeUtilsGlue::CreateUTF7toUTF16Converter(UTF7toUTF16Converter::utf7_variant variant) #endif { UTF7toUTF16Converter* converter = OP_NEW(UTF7toUTF16Converter, (variant)); #ifdef _DEBUG if (converter) AddToReferencesList(DebugReferences::M2REF_UTF7TOUTF16CONVERTER, source_file, source_line, converter); #endif return converter; } void MimeUtilsGlue::DeleteUTF7toUTF16Converter(UTF7toUTF16Converter* converter) { #ifdef _DEBUG if (converter) RemoveFromReferencesList(DebugReferences::M2REF_UTF7TOUTF16CONVERTER, converter); #endif OP_DELETE(converter); } #ifdef _DEBUG UTF16toUTF7Converter* MimeUtilsGlue::CreateUTF16toUTF7ConverterDbg(UTF16toUTF7Converter::utf7_variant variant, const OpStringC8& source_file, int source_line) #else UTF16toUTF7Converter* MimeUtilsGlue::CreateUTF16toUTF7Converter(UTF16toUTF7Converter::utf7_variant variant) #endif { UTF16toUTF7Converter* converter = OP_NEW(UTF16toUTF7Converter, (variant)); #ifdef _DEBUG if (converter) AddToReferencesList(DebugReferences::M2REF_UTF16TOUTF7CONVERTER, source_file, source_line, converter); #endif return converter; } void MimeUtilsGlue::DeleteUTF16toUTF7Converter(UTF16toUTF7Converter* converter) { #ifdef _DEBUG if (converter) RemoveFromReferencesList(DebugReferences::M2REF_UTF16TOUTF7CONVERTER, converter); #endif OP_DELETE(converter); } OP_STATUS MimeUtilsGlue::RemoveHeaderEscapes(const char* charset, const char *&source, OpString16& dest) { ::RemoveHeaderEscapes(dest, source, strlen(source), FALSE, TRUE, charset); return OpStatus::OK; } #ifndef __SUPPORT_OPENPGP__ Upload_Base* MimeUtilsGlue::CreateUploadElement(Upload_Element_Type typ) { switch(typ) { case UPLOAD_BINARY_BUFFER: return OP_NEW(Upload_BinaryBuffer, ()); case UPLOAD_STRING8: return OP_NEW(Upload_OpString8, ()); case UPLOAD_MULTIPART: return OP_NEW(Upload_Multipart, ()); case UPLOAD_URL: return OP_NEW(Upload_URL, ()); case UPLOAD_TEMPORARY_URL: return OP_NEW(Upload_TemporaryURL, ()); #ifdef UPLOAD2_OPSTRING16_SUPPORT case UPLOAD_STRING16: return OP_NEW(Upload_OpString16, ()); #endif #ifdef UPLOAD2_EXTERNAL_BUFFER_SUPPORT case UPLOAD_EXTERNAL_BUFFER: return OP_NEW(Upload_ExternalBuffer, ()); #endif #ifdef UPLOAD2_ENCAPSULATED_SUPPORT case UPLOAD_ENCAPSULATED: return OP_NEW(Upload_EncapsulatedElement, ()); case UPLOAD_EXTERNAL_BODY: return OP_NEW(Upload_External_Body, ()); #endif default: return NULL; } } #else // __SUPPORT_OPENPGP__ Upload_Builder_Base* MimeUtilsGlue::CreateUploadBuilder() { Upload_Builder_Base* builder=NULL; TRAPD(op_err, builder = CreateUploadBuilderL()); OpStatus::Ignore(op_err); return builder; } #endif // ---------------------------------------------------- MailerUtilFactory::MailerUtilFactory() : m_browser_utils_glue(NULL), m_mime_utils_glue(NULL) { } MailerUtilFactory::~MailerUtilFactory() { if (m_browser_utils_glue) OP_DELETE(m_browser_utils_glue); if (m_mime_utils_glue) OP_DELETE(m_mime_utils_glue); } // ---------------------------------------------------- #ifdef _DEBUG ProtocolConnection* MailerUtilFactory::CreateCommGlueDbg(const OpStringC8& source_file, int source_line) #else ProtocolConnection* MailerUtilFactory::CreateCommGlue() #endif { ProtocolConnection* connection = OP_NEW(CommGlue, ()); #ifdef _DEBUG AddToReferencesList(DebugReferences::M2REF_COMMGLUE, source_file, source_line, connection); #endif return connection; } // ---------------------------------------------------- void MailerUtilFactory::DeleteCommGlue(ProtocolConnection* p) { if (p) p->SetClient(NULL); #ifdef _DEBUG RemoveFromReferencesList(DebugReferences::M2REF_COMMGLUE, p); #endif CommGlue* tmp_p = static_cast<CommGlue*>(p); autodelete(tmp_p); } // ---------------------------------------------------- #ifdef _DEBUG MessageLoop* MailerUtilFactory::CreateMessageLoopDbg(const OpStringC8& source_file, int source_line) #else MessageLoop* MailerUtilFactory::CreateMessageLoop() #endif { MessageLoop* mess_loop = OP_NEW(MessageLoopGlue, ()); #ifdef _DEBUG AddToReferencesList(DebugReferences::M2REF_MESSAGELOOP, source_file, source_line, mess_loop); #endif return mess_loop; } // ---------------------------------------------------- void MailerUtilFactory::DeleteMessageLoop(MessageLoop* loop) { #ifdef _DEBUG RemoveFromReferencesList(DebugReferences::M2REF_MESSAGELOOP, loop); #endif delete (MessageLoopGlue*) loop; } // ---------------------------------------------------- #ifdef _DEBUG PrefsFile* MailerUtilFactory::CreatePrefsFileDbg(const OpStringC& path, const OpStringC8& source_file, int source_line) #else PrefsFile* MailerUtilFactory::CreatePrefsFile(const OpStringC& path) #endif { OpFile file; RETURN_VALUE_IF_ERROR(file.Construct(path.CStr()), NULL); PrefsFile* OP_MEMORY_VAR prefs = OP_NEW(PrefsFile, (PREFS_STD)); if (!prefs) return NULL; TRAPD(err, prefs->ConstructL(); prefs->SetFileL(&file)); if (OpStatus::IsError(err)) { OP_DELETE(prefs); return NULL; } #ifdef _DEBUG AddToReferencesList(DebugReferences::M2REF_PREFSFILE, source_file, source_line, prefs); #endif return prefs; } // ---------------------------------------------------- void MailerUtilFactory::DeletePrefsFile(PrefsFile* file) { if (!file) return; #ifdef _DEBUG RemoveFromReferencesList(DebugReferences::M2REF_PREFSFILE, file); #endif OP_DELETE(file); } // ---------------------------------------------------- #ifdef _DEBUG PrefsSection* MailerUtilFactory::CreatePrefsSectionDbg(PrefsFile* prefsfile, const OpStringC& section, const OpStringC8& source_file, int source_line) #else PrefsSection* MailerUtilFactory::CreatePrefsSection(PrefsFile* prefsfile, const OpStringC& section) #endif { if (!prefsfile) return NULL; PrefsSection* prefs_section = NULL; TRAPD(err, prefs_section = prefsfile->ReadSectionL(section)); if (OpStatus::IsError(err)) { OP_DELETE(prefs_section); return NULL; } #ifdef _DEBUG AddToReferencesList(DebugReferences::M2REF_PREFSSECTION, source_file, source_line, prefs_section); #endif return prefs_section; } // ---------------------------------------------------- void MailerUtilFactory::DeletePrefsSection(PrefsSection* section) { #ifdef _DEBUG RemoveFromReferencesList(DebugReferences::M2REF_PREFSSECTION, section); #endif OP_DELETE(section); } // ---------------------------------------------------- #ifdef _DEBUG OpFile* MailerUtilFactory::CreateOpFileDbg(const OpStringC& path, const OpStringC8& source_file, int source_line) #else OpFile* MailerUtilFactory::CreateOpFile(const OpStringC& path) #endif { OpFile* file = OP_NEW(OpFile, ()); if (!file) return NULL; if (OpStatus::IsError(file->Construct(path.CStr(), OPFILE_SERIALIZED_FOLDER))) { OP_DELETE(file); return NULL; } #ifdef _DEBUG AddToReferencesList(DebugReferences::M2REF_OPFILE, source_file, source_line, file); #endif return file; } // ---------------------------------------------------- void MailerUtilFactory::DeleteOpFile(OpFile* file) { if (!file) return; #ifdef _DEBUG RemoveFromReferencesList(DebugReferences::M2REF_OPFILE, file); #endif OP_DELETE(file); } // ---------------------------------------------------- #ifdef _DEBUG URL* MailerUtilFactory::CreateURLDbg(const OpStringC8& source_file, int source_line) #else URL* MailerUtilFactory::CreateURL() #endif { URL* url = OP_NEW(URL, ()); #ifdef _DEBUG AddToReferencesList(DebugReferences::M2REF_URL, source_file, source_line, url); #endif return url; } // ---------------------------------------------------- void MailerUtilFactory::DeleteURL(URL* url) { #ifdef _DEBUG RemoveFromReferencesList(DebugReferences::M2REF_URL, url); #endif OP_DELETE(url); } // ---------------------------------------------------- #ifdef _DEBUG UnicodeFileInputStream* MailerUtilFactory::CreateUnicodeFileInputStreamDbg(OpFile *inFile, UnicodeFileInputStream::LocalContentType content, const OpStringC8& source_file, int source_line) #else UnicodeFileInputStream* MailerUtilFactory::CreateUnicodeFileInputStream(OpFile *inFile, UnicodeFileInputStream::LocalContentType content) #endif { OP_ASSERT(inFile); if (!inFile) return NULL; UnicodeFileInputStream* file = OP_NEW(UnicodeFileInputStream, ()); if (!file) return NULL; if (OpStatus::IsError(file->Construct(inFile, content))) { OP_DELETE(file); return NULL; } #ifdef _DEBUG AddToReferencesList(DebugReferences::M2REF_INPUTSTREAM, source_file, source_line, file); #endif return file; } // ---------------------------------------------------- void MailerUtilFactory::DeleteUnicodeFileInputStream(UnicodeFileInputStream* stream) { #ifdef _DEBUG RemoveFromReferencesList(DebugReferences::M2REF_INPUTSTREAM, stream); #endif OP_DELETE(stream); } // ---------------------------------------------------- #ifdef _DEBUG UnicodeFileOutputStream* MailerUtilFactory::CreateUnicodeFileOutputStreamDbg(const uni_char* filename, const char* encoding, const OpStringC8& source_file, int source_line) #else UnicodeFileOutputStream* MailerUtilFactory::CreateUnicodeFileOutputStream(const uni_char* filename, const char* encoding) #endif { OP_ASSERT(filename && *filename); if (!filename || !*filename) return NULL; UnicodeFileOutputStream* file = OP_NEW(UnicodeFileOutputStream, ()); if (!file) return NULL; if (OpStatus::IsError(file->Construct(filename, encoding))) { OP_DELETE(file); return NULL; } #ifdef _DEBUG AddToReferencesList(DebugReferences::M2REF_OUTPUTSTREAM, source_file, source_line, file); #endif return file; } // ---------------------------------------------------- void MailerUtilFactory::DeleteUnicodeFileOutputStream(UnicodeFileOutputStream* stream) { #ifdef _DEBUG RemoveFromReferencesList(DebugReferences::M2REF_OUTPUTSTREAM, stream); #endif OP_DELETE(stream); } // ---------------------------------------------------- OpSocket* MailerUtilFactory::CreateSocket(OpSocketListener &listener) { OpSocket* socket; OP_STATUS status = SocketWrapper::CreateTCPSocket(&socket, &listener, 0); if (OpStatus::IsSuccess(status)) { return socket; } else { return NULL; } } void MailerUtilFactory::DestroySocket(OpSocket *socket) { OP_DELETE(socket); } OpSocketAddress* MailerUtilFactory::CreateSocketAddress() { OpSocketAddress* socket_address; OP_STATUS status = OpSocketAddress::Create(&socket_address); if (OpStatus::IsSuccess(status)) { return socket_address; } else { return NULL; } } void MailerUtilFactory::DestroySocketAddress(OpSocketAddress* socket_address) { OP_DELETE(socket_address); } OpHostResolver* MailerUtilFactory::CreateHostResolver(OpHostResolverListener &resolver_listener) { OpHostResolver* host_resolver; OP_STATUS status = SocketWrapper::CreateHostResolver(&host_resolver, &resolver_listener); if (OpStatus::IsSuccess(status)) { return host_resolver; } else { return NULL; } } void MailerUtilFactory::DestroyHostResolver(OpHostResolver* host_resolver) { OP_DELETE(host_resolver); } // ---------------------------------------------------- BrowserUtils* MailerUtilFactory::GetBrowserUtils() { if (!m_browser_utils_glue) { m_browser_utils_glue = OP_NEW(BrowserUtilsGlue, ()); } return m_browser_utils_glue; } MimeUtils* MailerUtilFactory::GetMimeUtils() { if (!m_mime_utils_glue) { m_mime_utils_glue = OP_NEW(MimeUtilsGlue, ()); } return m_mime_utils_glue; } char* MailerUtilFactory::OpNewChar(int size) {return OP_NEWA(char, size);} uni_char* MailerUtilFactory::OpNewUnichar(int size) {return OP_NEWA(uni_char, size);} void MailerUtilFactory::OpDeleteArray(void* p) {delete [] static_cast<char *>(p);} //If this does not compile in gcc 3.3, please contact frodegill@opera.com // ---------------------------------------------------- #endif // M2_SUPPORT // ----------------------------------------------------
int outpin = 8; float kiloh; float freq = 10; long period; bool ones = false; long lastTime = 0; long now; // Timer output const byte CLOCKOUT = 9; // Only for Arduino Uno #define NOP __asm__ __volatile__ ("nop\n\t") void setup() { // put your setup code here, to run once: Serial.begin(115200); pinMode(outpin,OUTPUT); lastTime = micros(); kiloh = 1000000/freq; kiloh = 1.0; period = 20000; // Timer setup // set up 8 MHz timer on CLOCKOUT (OC1A) // pinMode (CLOCKOUT, OUTPUT); // // set up Timer 1 // TCCR1A = bit (COM1A0); // toggle OC1A on Compare Match // TCCR1B = bit (WGM12) | bit (CS10); // CTC, no prescaling // OCR1A = 7; } void loop() { if (ones){ while (micros()-lastTime < period){ PORTB = B00000001; NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; PORTB = B00000000; NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; PORTB = B00000001; NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; PORTB = B00000000; NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; PORTB = B00000001; NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; PORTB = B00000000; NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; } } else { while (micros()-lastTime < period){ PORTB = B00000000; } } lastTime = micros(); ones = !ones; } //void loop() { // if (ones){ // while (micros()-lastTime < period){ // PORTB = B00000001; // NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; // PORTB = B00000000; // NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; // PORTB = B00000001; // NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; // PORTB = B00000000; // NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; // PORTB = B00000001; // NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; // PORTB = B00000000; // NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP; // } // } else { // while (micros()-lastTime < period){NOP;} // } // lastTime = micros(); // ones = !ones; //}
// Created on: 1998-05-07 // Created by: Andre LIEUTIER // Copyright (c) 1998-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 _Plate_LineConstraint_HeaderFile #define _Plate_LineConstraint_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Plate_LinearScalarConstraint.hxx> #include <Standard_Integer.hxx> class gp_XY; class gp_Lin; //! constraint a point to belong to a straight line class Plate_LineConstraint { public: DEFINE_STANDARD_ALLOC Standard_EXPORT Plate_LineConstraint(const gp_XY& point2d, const gp_Lin& lin, const Standard_Integer iu = 0, const Standard_Integer iv = 0); const Plate_LinearScalarConstraint& LSC() const; protected: private: Plate_LinearScalarConstraint myLSC; }; #include <Plate_LineConstraint.lxx> #endif // _Plate_LineConstraint_HeaderFile
#include "login.h" #include "ui_login.h" #define Path_to_DB "C:/Users/Admin/Documents/TermPaperTEST/build-automated_workplace_of_confectioner-Desktop_Qt_5_15_0_MSVC2019_64bit-Debug/awoc.db" Login::Login(QDialog *parent) : QMainWindow(parent) , ui(new Ui::Login) { ui->setupUi(this); //Підключаємо базу даних QFileInfo checkFile(Path_to_DB); if(checkFile.isFile()){ if(connectToDB()){ qDebug("Connected to Database File :)"); }else{ qDebug("Failed to open the database"); } } //Тінь фрейму QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this); shadow_effect->setOffset(0, 0); shadow_effect->setColor(QColor(38, 78, 119, 127)); shadow_effect->setBlurRadius(22); ui->frame->setGraphicsEffect(shadow_effect); } Login::~Login() { delete ui; } void Login::on_pushButton_SignIn_clicked() { connectToDB(); QString Username, Password; Username=ui->lineEdit_Username->text(); Password=ui->lineEdit_Password->text(); if(!db.isOpen()){ qDebug("No connection to db :("); return; } QSqlQuery qry; if(qry.exec("SELECT Username, Password FROM employees_info WHERE Username=\'"+Username+"\' AND Password=\'"+Password+"\'")){ if(qry.next()){ closeDB(); GeneralWindow gw; this->close(); gw.setModal(true); gw.exec(); }else{ QMessageBox::warning(this, "Login", "Ім'я користувача або пароль неправильний"); } } } bool Login::connectToDB(){ db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(Path_to_DB); return db.open(); } void Login::closeDB(){ QString connection; connection = db.connectionName(); db.close(); db = QSqlDatabase(); db.removeDatabase(connection); }
/***************************************************************************************** * * * owl * * * * Copyright (c) 2014 Jonas Strandstedt * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #ifndef __ANY_H__ #define __ANY_H__ #include <owl/data/typeinfo.h> #include <owl/data/serializer.h> #include <type_traits> #include <typeinfo> #include <string> #include <functional> #include <iostream> template <class T> using StorageType = typename std::decay<T>::type; namespace owl { class Any { public: // Construct Any from any Any Any() : ptr(nullptr) {} Any(Any& that); Any(Any&& that); Any(const Any& that); Any(const Any&& that); Any(const char* value); Any& operator=(const Any& a); Any& operator=(Any&& a); ~Any(); bool is_null() const; bool not_null() const; // Template functions // Construct Any from any type template<typename U> Any(U&& value); template<typename U> bool is() const; template<typename U> StorageType<U>& as() const; template<typename U> operator U() const; template<typename U> bool get(U& v) const; std::string typeName() const; static void serialize(const Any& v, std::ostream& out); static void deserialize(Any& v, std::istream& src); private: template<typename U> static void serialize(const Any& v, std::ostream& out); template<typename U> static void deserialize(Any& v, std::istream& src); enum AnyTypeId { Any_unsupported = 0, Any_char = 1, Any_char16_t = 2, Any_char32_t = 3, Any_wchar_t = 4, Any_short = 5, Any_int = 6, Any_long_int = 7, Any_long_long_int = 8, Any_unsigned_short = 9, Any_unsigned_int = 10, Any_unsigned_long_int = 11, Any_unsigned_long_long_int = 12, Any_float = 13, Any_double = 14, Any_long_double = 15, Any_bool = 16, Any_std_string = 17, Any_Dictionary = 18, Any_vector_char = 19, Any_vector_char16_t = 20, Any_vector_char32_t = 21, Any_vector_wchar_t = 22, Any_vector_short = 23, Any_vector_int = 24, Any_vector_long_int = 25, Any_vector_long_long_int = 26, Any_vector_unsigned_short = 27, Any_vector_unsigned_int = 28, Any_vector_unsigned_long_int = 29, Any_vector_unsigned_long_long_int = 30, Any_vector_float = 31, Any_vector_double = 32, Any_vector_long_double = 33, Any_vector_std_string = 34, Any_vector_Dictionary = 35 }; size_t type() const; struct Base { virtual ~Base() {} virtual Base* clone() const = 0; virtual std::string name() const = 0; }; // Base template<typename T> struct Derived : Base { T value; template<typename U> Derived(U&& value); Base* clone() const; std::string name() const; }; // Derived Base* clone() const; Base* ptr; }; // Any #include <owl/data/any.inl> } // namespace owl #endif
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: double myPow(double x, int n) { //基本思想:快速幂算法,将n看成二进制数,比如n为11,3^11=3^1011=3^1000*3^10*3^1,也就是从低位往高位不断循环右移一位且当前x值为x*=x,最低位遇到1也就是当前为奇数res乘当前x即res*=x double res = 1.0; if (n == 0 || x==1.0) return 1.0; long long N = n; //因为int范围是[-2^31,2^31-1]负数的表示范围比正数大,所以不能简单取绝对值,用long long代替 if (n < 0) N = -N; else N = N; //将n看成二进制数,从低位往高位不断循环右移一位且当前x值为x*=x,最低位遇到1也就是当前为奇数res乘当前x即res*=x for (long long i = N; i != 0; i = i >> 1) { if (i % 2 == 1) res *= x; x *= x; } if (n > 0) return res; else return 1.0 / res; } }; int main() { Solution solute; double x = 2.00000; int n = 10; cout << solute.myPow(x, n) << endl; return 0; }
#include "Arduino.h" #include "PIC.h" //Constructor PIC::PIC(float Kp, float Ti, float dt){ _Kp = Kp; _Ti = Ti; _dt = dt; _u_max = 5.0; _u_min = 0.0; _u_k1 = 0.0; _e_k1 = 0.0; } float PIC::ControlSignal(float setPoint, float temperature){ float e = setPoint-temperature; float u_k = _Kp*(e-_e_k1); float u_i = _Kp*_dt/_Ti*e; float u = _u_k1+u_k+u_i; if(u > _u_max) { u = _u_max; } if(u < _u_min) { u = _u_min; } _u_k1 = u; _e_k1 = e; return u; } void PIC::SetParams(float Kp, float Ti){ _Kp = Kp; _Ti = Ti; }
#include "deferred.h" #include "util.h" #include <functional> namespace { class PassThroughHandler : public CefV8Handler { public: typedef std::function<bool (const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception)> Function; PassThroughHandler(const Function& fn) :_fn(fn) {} virtual bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { return _fn(name, object, arguments, retval, exception); } // Provide the reference counting implementation for this class. IMPLEMENT_REFCOUNTING(PassThroughHandler); private: Function _fn; }; CefRefPtr<CefV8Value> args_to_value(const CefV8ValueList& args) { CefRefPtr<CefV8Value> value = CefV8Value::CreateArray(args.size()); for (size_t i = 0; i < args.size(); ++i) { value->SetValue(i, args[i]); } return value; } CefV8ValueList value_to_args(CefRefPtr<CefV8Value> value) { if (!value->IsArray()) { throw std::runtime_error("Can only convert an array to arguments."); } CefV8ValueList args; args.reserve(value->GetArrayLength()); for (size_t i = 0; i < args.capacity(); ++i) { args.push_back(value->GetValue(i)); } return args; } CefString get_resolved_arguments_key() { static CefString key("resolvedArguments"); return key; } CefString get_rejected_arguments_key() { static CefString key("rejectedArguments"); return key; } CefString get_finish_function_key() { static CefString key("finish"); return key; } CefString get_success_function_key() { static CefString key("success"); return key; } CefString get_failure_function_key() { static CefString key("failure"); return key; } CefString get_finally_function_key() { static CefString key("finally"); return key; } void finish(CefRefPtr<CefV8Value> privateObject) { privateObject->GetValue(get_finish_function_key())->ExecuteFunction(privateObject, CefV8ValueList()); } } Browser::Deferred::Deferred() {} Browser::Deferred::Deferred(CefRefPtr<CefV8Context> context) :_context(context), _privateObject(CefV8Value::CreateObject(nullptr)) { _privateObject->SetValue(get_finish_function_key(), make_finish(), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE); } CefRefPtr<CefV8Value> Browser::Deferred::get_promise() const { return make_promise(_privateObject); } void Browser::Deferred::resolve(const CefV8ValueList& args) { Util::ContextOpener opener(_context); _privateObject->SetValue(get_resolved_arguments_key(), args_to_value(args), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE); ::finish(_privateObject); } void Browser::Deferred::reject(const CefV8ValueList& args) { Util::ContextOpener opener(_context); _privateObject->SetValue(get_rejected_arguments_key(), args_to_value(args), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE); ::finish(_privateObject); } void Browser::Deferred::finish() { Util::ContextOpener opener(_context); ::finish(_privateObject); } CefRefPtr<CefV8Value> Browser::Deferred::make_finish() const { return CefV8Value::CreateFunction(get_finish_function_key(), new PassThroughHandler([](const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception){ auto resolvedArgs = object->GetValue(get_resolved_arguments_key()); auto rejectedArgs = object->GetValue(get_rejected_arguments_key()); auto successFn = object->GetValue(get_success_function_key()); auto failureFn = object->GetValue(get_failure_function_key()); auto finallyFn = object->GetValue(get_finally_function_key()); if (resolvedArgs->IsArray() && successFn->IsFunction()) { successFn->ExecuteFunction(nullptr, value_to_args(resolvedArgs)); } else if (rejectedArgs->IsArray() && failureFn->IsFunction()) { failureFn->ExecuteFunction(nullptr, value_to_args(rejectedArgs)); } if ((resolvedArgs->IsArray() || rejectedArgs->IsArray()) && finallyFn->IsFunction()) { finallyFn->ExecuteFunction(nullptr, CefV8ValueList()); } return true; })); } CefRefPtr<CefV8Value> Browser::Deferred::make_promise(CefRefPtr<CefV8Value> privateObject) const { CefRefPtr<CefV8Value> promise = CefV8Value::CreateObject(nullptr); promise->SetValue("then", make_then(privateObject), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_DONTDELETE); promise->SetValue("finally", make_finally(privateObject), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_DONTDELETE); return promise; } CefRefPtr<CefV8Value> Browser::Deferred::make_then(CefRefPtr<CefV8Value> privateObject) const { return CefV8Value::CreateFunction("then", new PassThroughHandler([privateObject](const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception){ if ((arguments.size() < 1) || !arguments[0]->IsFunction()) { exception = "The first argument must be the success callback."; return true; } if ((arguments.size() > 1) && !arguments[1]->IsFunction()) { exception = "The first argument must be a failure callback if used."; return true; } if ((arguments.size() > 2) && !arguments[2]->IsFunction()) { exception = "The first argument must be a failure callback if used."; return true; } privateObject->SetValue(get_success_function_key(), arguments[0], CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE); if (arguments.size() > 1) { privateObject->SetValue(get_failure_function_key(), arguments[1], CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE); } if (arguments.size() > 2) { privateObject->SetValue(get_finally_function_key(), arguments[2], CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE); } ::finish(privateObject); return true; })); } CefRefPtr<CefV8Value> Browser::Deferred::make_finally(CefRefPtr<CefV8Value> privateObject) const { return CefV8Value::CreateFunction("finally", new PassThroughHandler([privateObject](const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception){ if ((arguments.size() != 1) || !arguments[0]->IsFunction()) { exception = "The first argument must be the finally callback."; return true; } privateObject->SetValue("finally", arguments[0], CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE); return true; })); }
#ifndef QSERIAL_H #define QSERIAL_H #include <QtSerialPort/QSerialPort> #include <QTimer> #include <QQueue> #include <QTextStream> class QSerial : public QObject { public: explicit QSerial(QString, int = 9600, bool = true, bool = false); ~QSerial(); bool open(); void close(); /* * envia por puerto serie el mensaje del array pasado por parametro * Se espera una respuesta por defaul 200ms */ bool serialSend(quint8 *, int, int = 200); /* * serialAvailable * retorna 0 si no se han recibido datos * retorna -1 si no se han recibido datos pero aún no se ha cumplido el timeout * retorna la cantidad de bytes disponibles */ int serialAvailable(); /* * copia los datos recibidos en el array. El tamaño se puede obtener con serialAvailable() */ void serialReceive(quint8 *); private slots: void OnQSerialPort1Rx(); void onQTimer10ms(); private: QSerialPort *QSerialPort1; QTimer *QTimer10ms; // fingerprint del header, como constante ("UNER00:") const quint8 header[7] = {0x55, 0x4E, 0x45, 0x52, 0x00, 0x00, 0x3A}; // Queue con los datos en raw recibidos en el puerto serie QQueue<quint8> rx; quint8 rxStage; quint8 payloadSize; quint8 payloadCount; // Comando recibido QVector<quint8> rcv; // tiempo para completar la respuesta a un comando enviado a arduino int responseTimeout; // tiempo para terminar de recibir un comando que se ha empezado a recibir int cmdTimeout; // true si se ha recibido un comando bool onCMD; // debug bool debug; // opciones del puerto bool serialReadWrite; int serialBaudRate; QString serialPortName; //////////////////////////////////////////////////////// // Funciones privadas /* * calcula chechsum xor */ quint8 checksum(quint8 *, int); /* Procesa los datos en el buffer de entrada y guarda los datos si están OK * No sigue procesando hasta que no se han leído los datos existentes con serialReceive */ void checkHeader(); }; #endif // QSERIAL_H
// Created on: 1992-06-22 // Created by: Gilles DEBARBOUILLE // Copyright (c) 1992-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 _Units_Token_HeaderFile #define _Units_Token_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TCollection_AsciiString.hxx> #include <Standard_Transient.hxx> #include <Standard_Integer.hxx> class Units_Dimensions; class Units_Token; DEFINE_STANDARD_HANDLE(Units_Token, Standard_Transient) //! This class defines an elementary word contained in //! a Sentence object. class Units_Token : public Standard_Transient { public: //! Creates and returns a empty token. Standard_EXPORT Units_Token(); //! Creates and returns a token. <aword> is a string //! containing the available word. Standard_EXPORT Units_Token(const Standard_CString aword); //! Creates and returns a token. <atoken> is copied in //! the returned token. Standard_EXPORT Units_Token(const Handle(Units_Token)& atoken); //! Creates and returns a token. <aword> is a string //! containing the available word and <amean> gives the //! signification of the token. Standard_EXPORT Units_Token(const Standard_CString aword, const Standard_CString amean); //! Creates and returns a token. <aword> is a string //! containing the available word, <amean> gives the //! signification of the token and <avalue> is the numeric //! value of the dimension. Standard_EXPORT Units_Token(const Standard_CString aword, const Standard_CString amean, const Standard_Real avalue); //! Creates and returns a token. <aword> is a string //! containing the available word, <amean> gives the //! signification of the token, <avalue> is the numeric //! value of the dimension, and <adimensions> is the //! dimension of the given word <aword>. Standard_EXPORT Units_Token(const Standard_CString aword, const Standard_CString amean, const Standard_Real avalue, const Handle(Units_Dimensions)& adimension); //! Creates and returns a token, which is a ShiftedToken. Standard_EXPORT virtual Handle(Units_Token) Creates() const; //! Returns the length of the word. Standard_EXPORT Standard_Integer Length() const; //! Returns the string <theword> TCollection_AsciiString Word() const; //! Sets the field <theword> to <aword>. void Word (const Standard_CString aword); //! Returns the significance of the word <theword>, which //! is in the field <themean>. TCollection_AsciiString Mean() const; //! Sets the field <themean> to <amean>. void Mean (const Standard_CString amean); //! Returns the value stored in the field <thevalue>. Standard_Real Value() const; //! Sets the field <thevalue> to <avalue>. void Value (const Standard_Real avalue); //! Returns the dimensions of the token <thedimensions>. Handle(Units_Dimensions) Dimensions() const; //! Sets the field <thedimensions> to <adimensions>. Standard_EXPORT void Dimensions (const Handle(Units_Dimensions)& adimensions); //! Updates the token <me> with the additional //! signification <amean> by concatenation of the two //! strings <themean> and <amean>. If the two //! significations are the same , an information message //! is written in the output device. Standard_EXPORT void Update (const Standard_CString amean); Standard_EXPORT Handle(Units_Token) Add (const Standard_Integer aninteger) const; //! Returns a token which is the addition of <me> and //! another token <atoken>. The addition is possible if //! and only if the dimensions are the same. Standard_EXPORT Handle(Units_Token) Add (const Handle(Units_Token)& atoken) const; //! Returns a token which is the subtraction of <me> and //! another token <atoken>. The subtraction is possible if //! and only if the dimensions are the same. Standard_EXPORT Handle(Units_Token) Subtract (const Handle(Units_Token)& atoken) const; //! Returns a token which is the product of <me> and //! another token <atoken>. Standard_EXPORT Handle(Units_Token) Multiply (const Handle(Units_Token)& atoken) const; //! This virtual method is called by the Measurement //! methods, to compute the measurement during a //! conversion. Standard_NODISCARD Standard_EXPORT virtual Standard_Real Multiplied (const Standard_Real avalue) const; //! Returns a token which is the division of <me> by another //! token <atoken>. Standard_EXPORT Handle(Units_Token) Divide (const Handle(Units_Token)& atoken) const; //! This virtual method is called by the Measurement //! methods, to compute the measurement during a //! conversion. Standard_NODISCARD Standard_EXPORT virtual Standard_Real Divided (const Standard_Real avalue) const; //! Returns a token which is <me> to the power of another //! token <atoken>. The computation is possible only if //! <atoken> is a dimensionless constant. Standard_EXPORT Handle(Units_Token) Power (const Handle(Units_Token)& atoken) const; //! Returns a token which is <me> to the power of <anexponent>. Standard_EXPORT Handle(Units_Token) Power (const Standard_Real anexponent) const; //! Returns true if the field <theword> and the string //! <astring> are the same, false otherwise. Standard_EXPORT Standard_Boolean IsEqual (const Standard_CString astring) const; //! Returns true if the field <theword> and the string //! <theword> contained in the token <atoken> are the //! same, false otherwise. Standard_EXPORT Standard_Boolean IsEqual (const Handle(Units_Token)& atoken) const; //! Returns false if the field <theword> and the string //! <astring> are the same, true otherwise. Standard_Boolean IsNotEqual (const Standard_CString astring) const; //! Returns false if the field <theword> and the string //! <theword> contained in the token <atoken> are the //! same, true otherwise. Standard_Boolean IsNotEqual (const Handle(Units_Token)& atoken) const; //! Returns true if the field <theword> is strictly //! contained at the beginning of the string <astring>, //! false otherwise. Standard_Boolean IsLessOrEqual (const Standard_CString astring) const; //! Returns false if the field <theword> is strictly //! contained at the beginning of the string <astring>, //! true otherwise. Standard_Boolean IsGreater (const Standard_CString astring) const; //! Returns false if the field <theword> is strictly //! contained at the beginning of the string <astring>, //! true otherwise. Standard_Boolean IsGreater (const Handle(Units_Token)& atoken) const; //! Returns true if the string <astring> is strictly //! contained at the beginning of the field <theword> //! false otherwise. Standard_Boolean IsGreaterOrEqual (const Handle(Units_Token)& atoken) const; //! Useful for debugging Standard_EXPORT virtual void Dump (const Standard_Integer ashift, const Standard_Integer alevel) const; DEFINE_STANDARD_RTTIEXT(Units_Token,Standard_Transient) protected: private: TCollection_AsciiString theword; TCollection_AsciiString themean; Standard_Real thevalue; Handle(Units_Dimensions) thedimensions; }; #include <Units_Token.lxx> #endif // _Units_Token_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 2001-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef _WIN_HANDY_H_INCLUDED__849607 #define _WIN_HANDY_H_INCLUDED__849607 uni_char* StrGetTime ( CONST SYSTEMTIME *pSystemTime, uni_char* szResult, int sizeOfResult, bool fSec, bool fForce24); uni_char* StrGetDateTime ( CONST SYSTEMTIME *pSystemTime, uni_char* szResult, int maxlen, BOOL fSec); inline int StrGetMaxLen ( int size) { const int sizeOfChar = sizeof(uni_char); return MAX( ((size - sizeOfChar) / sizeOfChar), 0); } #if defined(ARRAY_SIZE) # undef ARRAY_SIZE #endif #define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(arr[0])) BOOL IsOperaWindow( HWND hWnd); BOOL WinGetVersion ( OUT OSVERSIONINFO *pVersion); #ifndef ISWINDOW #define ISWINDOW(h) ((h)?IsWindow(h):FALSE) #endif #define ISMENU(h) ((h)?IsMenu(h):FALSE) #define SWP_BASIC (SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER) #define WS_MDICHILDDEF ( WS_OVERLAPPEDWINDOW | WS_CHILDWINDOW | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPED) // *** DG-080799 - default used by windows when MDIS_ALLCHILDSTYLES is used for parent inline BOOL IsOfWndClass( HWND hWnd, ATOM atom) { return ISWINDOW(hWnd) && atom && (atom == (ATOM)GetClassLong( hWnd, GCW_ATOM)); }; DWORD GetSystemErrorText( DWORD err, uni_char* pszBuf, int nMaxStrLen); /** * Converts a LogFont-structure to a FontAtt-structure. * @lf LogFont. Contains font info. * @font FontAtt. Will contain result. */ class FontAtt; void LogFontToFontAtt (const LOGFONT &lf, FontAtt &font); /** * Converts a FontAtt-structure to a LogFont-structure. * @font FontAtt. Contains font info. * @lf LogFont. Will contain result. */ void FontAttToLogFont (const FontAtt &font, LOGFONT &lf); BOOL EnsureWindowVisible ( HWND hWndChild, // Child to move BOOL fEntire // if TRUE - try to make the entire window visble inside parent ); HBITMAP CreateScreenCompatibleBitmap(int cx, int cy, HBRUSH brush = NULL); HANDLE CreateDIBFromDDB( HBITMAP hBitmap, DWORD dwCompression, HPALETTE hPal ); BOOL IsNetworkDrive( const char *szDir); BOOL IsNetworkDrive( const uni_char *szDir); BOOL FileExist( const char * szPath); BOOL FileExist( const uni_char * szPath); inline BOOL DirExist( const uni_char * szPath) { return GetFileAttributes(szPath) != 0xFFFFFFFF; } uni_char * GetFavoritesFolder( uni_char *buf, DWORD bufSize); // ClientToScreen for a RECT inline void ClientToScreenRect( HWND hwnd, RECT *rc) { ClientToScreen( hwnd, (POINT*)&rc->left); ClientToScreen( hwnd, (POINT*)&rc->right); } // ScreenToClient for a RECT inline void ScreenToClientRect( HWND hwnd, RECT *rc) { ScreenToClient( hwnd, (POINT*)&rc->left); ScreenToClient( hwnd, (POINT*)&rc->right); } #define RECTSIZE(rc) rc.left,rc.top,rc.right-rc.left,rc.bottom-rc.top inline int RectCX(const RECT &rc) { return rc.right-rc.left;}; inline int RectCY(const RECT &rc) { return rc.bottom-rc.top;}; void *MallocResourceData ( HINSTANCE hInst, // App. instance LPCTSTR lpName, // Resouce name LPCTSTR lpType, // Resource Type DWORD *dwResSize = NULL // Ret.result size (opt) ); LPSTR GetWinVersionStr( LPSTR szVersion, BOOL productname=FALSE); // szVersion: pointer to storage for string, at least 15 characters long. // productname: if TRUE, generate a human-comprehensible name ("Windows XP") // rather than one for scripts ("Windows NT 5.1") class Window; const char* GetSystemCharsetName(); // returns TRUE if a conversion of the wide string can be done using the system's codepage BOOL CharsetSupportedBySystem(const uni_char* str); DWORD UpdateCrc32 ( const void* pBuffer, DWORD size, DWORD seed); uni_char * GetLastErrorMessageAlloc(); // *** DG[29] added int OpPathGetDriveType (IN const uni_char* pszPath); uni_char* StringFileName( const uni_char* fName); char* StringFileName(const char* fName); char *StrAppendSubDir( char *szParentDir, int nMaxLen, const char *szSubDir); OP_STATUS StrAppendSubDir(const OpStringC &parentDir, const OpStringC &subDir, OpString &result); OP_STATUS MakeOperaIniFileCheckSum(const uni_char* iniFile, OpString8* signature); BOOL IsSystemWin2000orXP(); BOOL IsSystemWinXP(); BOOL IsSystemWinVista(); BOOL IsSystemWin7(); BOOL IsSystemWin8(); OP_STATUS GetOSVersionStr(OpString& version); enum WinType { FAILED = 0, OLDER_THAN_WIN2K, WIN2K, WINXP, WINVISTA, WIN7, WIN8 }; WinType GetWinType(); // Get major number of service pack version, 2 for sp2.1 for instance unsigned int GetServicePackMajor(); /* Will tell you if more than one normal user is logged on. * It does not count logged on services like ANANYMOUS LOGON, * LOCAL SERVICE, and other users with session id == 0. * * NB: This function will only work for elevated admins on XP and above. * * @param others_logged_on Number of other users logged on. * * @return Will return OpStatus::OK if we actually manage to * enumerate all the values. The others_logged_on value * will not make sense if this value is an error. * * This function will only work on XP and higher. So * will return ERR_NOT_SUPPORTED if you are not. * * This function will only work if you are an admin. So * will return ERR_NO_ACCESS if you are not. */ OP_STATUS IsOtherUsersLoggedOn(UINT& others_logged_on); #endif // _WIN_HANDY_H_INCLUDED__849607 undefined
#pragma once class CMainFrame; class CSKMobileView; class Controller { public : virtual void Init(CMainFrame * mainFrame) = 0; virtual void Init(CSKMobileView * view) = 0; virtual void Fini() = 0; virtual BOOL OnCopyData(CWindow wnd, PCOPYDATASTRUCT pCopyDataStruct) = 0; virtual LRESULT OnBackLastApplication(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) = 0; virtual LRESULT OnSaveContentHtml(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) = 0; virtual LRESULT OnSaveContentXml(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) = 0; // virtual LRESULT OnActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) = 0; virtual LRESULT OnInputChanged(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) = 0; virtual void OnTimer(UINT_PTR nIDEvent) = 0; virtual LRESULT OnInputSetFocus(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) = 0; virtual LRESULT OnInputKillFocus(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) = 0; virtual LRESULT OnContentTabChanged(int idCtrl, LPNMHDR pnmh, BOOL& bHandled) = 0; virtual LRESULT OnDocumentComplete(int idCtrl, LPNMHDR pnmh, BOOL& bHandled) = 0; virtual LRESULT OnHotspot(int idCtrl, LPNMHDR pnmh, BOOL& bHandled) = 0; virtual LRESULT OnAction(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) = 0; virtual LRESULT OnCloseTab(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) = 0; virtual LRESULT OnQueryMode(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) = 0; virtual BOOL OnReturnKey(UINT nRepCnt, UINT nFlags) = 0; virtual BOOL OnUpKey(UINT nRepCnt, UINT nFlags) = 0; virtual BOOL OnDownKey(UINT nRepCnt, UINT nFlags) = 0; virtual BOOL OnLeftKey(UINT nRepCnt, UINT nFlags) = 0; virtual BOOL OnRightKey(UINT nRepCnt, UINT nFlags) = 0; virtual BOOL OnChar(UINT nChar, UINT nRepCnt,UINT nFlags) = 0; virtual LRESULT OnSimulateKey(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) = 0; }; class ControllerFactory { public : void listAvailableControllerNames(char const* names[], unsigned * count); Controller * create(char const* name); };
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} int main() { int n; cin >> n; string s; cin >> s; int q; cin >> q; set<int> abet[26]; rep(i, s.size()){ int num = s[i] - 'a'; abet[num].insert(i); } rep(i, q){ int query; cin >> query; if (query == 1){ int p1; char p2; cin >> p1 >> p2; p1--; int num_replace = (int)p2 - 'a'; int num_old = s[p1] - 'a'; abet[num_old].erase(p1); s[p1] = p2; abet[num_replace].insert(p1); } else { int p1, p2; cin >> p1 >> p2; p1--; p2--; int ans = 0; rep(j, 26){ if(abet[j].lower_bound(p1) != abet[j].upper_bound(p2)){ //char c = j + 'a'; //cout << "["<< c << "]"; ans++; } } // rep(j, 26){ // cout << (char)(j + 'a') << ":"; // for(auto x:abet[j]){ // cout << x << " "; // } // cout << endl; // } cout << ans << endl; } } }
#pragma once #ifndef FACETRACKING_H #define FACETRACKING_H #if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(WIN64) #include <windows.h> #endif // OpenCV #include "opencv2/objdetect.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/videoio.hpp" #include "opencv2/calib3d.hpp" // AlgLib - LevMarq #include "ap.h" #include "optimization.h" #include <iostream> #include "opencv2/face.hpp" #include "opencv2/video/tracking.hpp" #include "facialmesh.h" #define FACE_MODEL "candide3_rodri.wfm" #define RESIZE_F 1 #define LANDMARKS_POSE 1 #define LANDMARKS_ANIMATION 2 #define LANDMARKS_ALL 3 class facetracking { public: facetracking(); // ================================ DETECCION de CARA ================================ \\ // Obtencion de ROI donde se ubica la cara del sujeto utilizando HaarCascades cv::Rect detectFace(cv::Mat img, bool &face_detected); // ========================== UBICACION de PUNTOS de INTERES ========================= \\ // Actualiza la posicion de los puntos del atributo landmarks utilizando Facemark de OpenCV 4.3.0 void facelandmarks(cv::Mat img, cv::Rect face, bool& detect, int type); // Dibuja los landmarks de interes void drawlandmarks(cv::Mat img); // ============================= TRACKING FLUJO OPTICO =============================== \\ // Obtiene el flujo optico de los puntos de interes entre dos imagenes y devuelve la estimacion // de los puntos de interes en la imagen actual void optflow(cv::Mat prev_img, cv::Mat img, std::vector < cv::Point2f> prev_points, std::vector < cv::Point2f> *points, std::vector<uchar>* status, std::vector<float>* error); // ESTIMACION DE PARAMETROS \\ //Pose // Estimo la rotacion y translacion del modelo de la mascara utilizando los landmarks trackeados con Facemark void estimar_pose_landmarks(cv::Mat img); void estimar_pose_lk_kf(cv::Mat prev_img, cv::Mat img); void ajustar_pose_levmar(puntos3d* opoints, puntos2d* ipoints, cv::Mat *Rvector, cv::Mat *Tvector); // Estimo la pose usando algoritmo de Lucas Terissi void estimar_pose_lk(cv::Mat prev_img, cv::Mat img, puntos2d &puntos); void buscar_puntos(cv::Mat &prev_img, cv::Mat &curr_img, puntos2d &prev_points, int level, puntos2d &puntos_nuevos, vector<int> &indx_OK, cv::Size winsize = cv::Size(20,20)); //Animacion void estimar_animacion_landmarks(cv::Mat img, puntos2d &puntos); void estimar_animacion_lk(cv::Mat prev_img, cv::Mat img, puntos2d*puntos_prev, puntos2d &puntos); void ajustar_animacion_levmar(puntos2d *puntos2D_target, std::vector<int>* point_indxs, facialmesh *modelo); // <><><><><><><><><><><><><><><> ATRIBUTOS DE LA CLASE <><><><><><><><><><><><><><><> \\ // Objeto de la mascara facialmesh* candide; // Creo una instancia de Facemark para la deteccion de los landmarks cv::Ptr<cv::face::Facemark> facemark; // Landmarks obtenidos con Facemark puntos2d landmarks; // Parametros para el Optical Flow LK cv::TermCriteria termcrit; cv::Size winSize; // Creo los objetos clasificadores de cascada cv::CascadeClassifier HC_face; // Para la estimacion de pose con los landmarks puntos3d posevertex, animationvertex; }; #endif // FACETRACKING
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int a[4444]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int n, cnt = 0, s = 0; cin >> n; for (int i = 0; i < n + n; ++i) { int p1; scanf("%d.%d", &p1, &a[i]); s += a[i]; if (a[i] == 0) ++cnt; } int ans = 2e9; for (int i = max(0, cnt - n); i <= n && i <= cnt; ++i) if (abs(s - 1000 * (n - i)) < ans) ans = abs(s - 1000 * (n - i)); printf("%d.%03d\n", abs(ans) / 1000, abs(ans) % 1000); return 0; }
#include "f3lib/assets/model/Motion.h" #include <cassert> using namespace f3; using namespace f3::types; Motion::Motion() { } Motion::~Motion() { } void Motion::initBones(const Skeleton& skeleton, std::vector<Matrix>& boneMatrices) const { for (unsigned int i = 0; i < skeleton._bones.size(); ++i) { boneMatrices[i] = skeleton._bones[i]._localTransMat; if (skeleton._bones[i]._parent != nullptr) { assert(skeleton._bones[i]._parent == &skeleton._bones[skeleton._bones[i]._parentId]); } } } void Motion::updateBones(Skeleton& skeleton, int framePrev, int frameNext, float interp, std::vector<Matrix>& boneMatrices) const { // animate over all the bones for the current frame for (unsigned int boneInfoId = 0; boneInfoId < _boneInfos.size(); ++boneInfoId) { Matrix resultMatrix; const BoneFrame& boneFrame = _boneFrames[boneInfoId]; // check if the bone has frames if (boneFrame._frameList.size() > 0) { // find the two adjacent frames const TMAnimation& animPrev = boneFrame._frameList[framePrev]; const TMAnimation& animNext = boneFrame._frameList[frameNext]; // extract position and rotations Vector3 posPrev = animPrev._position; Vector3 posNext = animNext._position; Quaternion rotPrev = animPrev._rotation; Quaternion rotNext = animNext._rotation; // interpolate them Vector3 pos = posPrev * (1 - interp) + posNext * interp; Quaternion rot = Quaternion::slerp(rotPrev, rotNext, interp); Matrix matTrans = Matrix::makeTranslate(pos); Matrix matRot = Matrix::makeRotate(rot); resultMatrix = matRot * matTrans; } else { // no frames for this bone resultMatrix = boneFrame._localTM; } const Bone& boneInfoBone = _boneInfos[boneInfoId]; if (boneInfoBone._parent) { Matrix& f2Mat = skeleton._bones[boneInfoId]._parent->_localTransMat; Matrix& f3Mat = boneMatrices[skeleton._bones[boneInfoId]._parentId]; resultMatrix = resultMatrix * f2Mat; } Bone& skeletonBone = skeleton._bones[boneInfoId]; skeletonBone._localTransMat = resultMatrix; skeletonBone._transMat = skeletonBone._invTransMat * skeletonBone._localTransMat; boneMatrices[boneInfoId] = skeletonBone._transMat; } }
#ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include <iostream> #include <sstream> #include <iomanip> #include <cstdlib> #include <cstring> #include "glExtension.h" #include "Timer.h" void displayCB(); void reshapeCB(int w, int h); void timerCB(int millisec); void idleCB(); void keyboardCB(unsigned char key, int x, int y); void mouseCB(int button, int stat, int x, int y); void mouseMotionCB(int x, int y); void exitCB(); void initGL(); int initGLUT(int argc, char **argv); bool initSharedMem(); void clearSharedMem(); void initLights(); void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ); void updatePixels(GLubyte* dst, int size); void drawString(const char *str, int x, int y, float color[4], void *font); void drawString3D(const char *str, float pos[3], float color[4], void *font); void showInfo(); void showTransferRate(); void printTransferRate(); const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 600; const float CAMERA_DISTANCE = 2.0f; const int TEXT_WIDTH = 8; const int TEXT_HEIGHT = 13; const int IMAGE_WIDTH = 2048; const int IMAGE_HEIGHT = 2048; const int CHANNEL_COUNT = 4; const int DATA_SIZE = IMAGE_WIDTH * IMAGE_HEIGHT * CHANNEL_COUNT; const GLenum PIXEL_FORMAT = GL_BGRA; void *font = GLUT_BITMAP_8_BY_13; GLuint pboIds[2]; GLuint textureId; GLubyte* imageData = 0; int screenWidth; int screenHeight; bool mouseLeftDown; bool mouseRightDown; float mouseX, mouseY; float cameraAngleX; float cameraAngleY; float cameraDistance; bool pboSupported; int pboMode; int drawMode = 0; Timer timer, t1, t2; float copyTime, updateTime; int main(int argc, char **argv) { initSharedMem(); atexit(exitCB); initGLUT(argc, argv); initGL(); glExtension& ext = glExtension::getInstance(); pboSupported = ext.isSupported("GL_ARB_pixel_buffer_object"); if(pboSupported) { std::cout << "Video card supports GL_ARB_pixel_buffer_object." << std::endl; } else { std::cout << "[ERROR] Video card does not supports GL_ARB_pixel_buffer_object." << std::endl; } glGenTextures(1, &textureId); glBindTexture(GL_TEXTURE_2D, textureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, IMAGE_WIDTH, IMAGE_HEIGHT, 0, PIXEL_FORMAT, GL_UNSIGNED_BYTE, (GLvoid*)imageData); glBindTexture(GL_TEXTURE_2D, 0); #ifdef _WIN32 if(ext.isSupported("WGL_EXT_swap_control")) { wglSwapIntervalEXT(0); std::cout << "Video card supports WGL_EXT_swap_control." << std::endl; } #endif if(pboSupported) { glGenBuffers(2, pboIds); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIds[0]); glBufferData(GL_PIXEL_UNPACK_BUFFER, DATA_SIZE, 0, GL_STREAM_DRAW); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIds[1]); glBufferData(GL_PIXEL_UNPACK_BUFFER, DATA_SIZE, 0, GL_STREAM_DRAW); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } timer.start(); glutMainLoop(); return 0; } int initGLUT(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_ALPHA); glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT); glutInitWindowPosition(100, 100); int handle = glutCreateWindow(argv[0]); glutDisplayFunc(displayCB); //glutTimerFunc(33, timerCB, 33); glutIdleFunc(idleCB); glutReshapeFunc(reshapeCB); glutKeyboardFunc(keyboardCB); glutMouseFunc(mouseCB); glutMotionFunc(mouseMotionCB); return handle; } void initGL() { //@glShadeModel(GL_SMOOTH); glShadeModel(GL_FLAT); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); //@glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); //glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glEnable(GL_DEPTH_TEST); //@glEnable(GL_LIGHTING); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glClearColor(0, 0, 0, 0); glClearStencil(0); glClearDepth(1.0f); glDepthFunc(GL_LEQUAL); //@initLights(); } void drawString(const char *str, int x, int y, float color[4], void *font) { glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); glColor4fv(color); glRasterPos2i(x, y); while(*str) { glutBitmapCharacter(font, *str); ++str; } glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glPopAttrib(); } void drawString3D(const char *str, float pos[3], float color[4], void *font) { glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); glColor4fv(color); glRasterPos3fv(pos); while(*str) { glutBitmapCharacter(font, *str); ++str; } glDisable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glPopAttrib(); } bool initSharedMem() { screenWidth = SCREEN_WIDTH; screenHeight = SCREEN_HEIGHT; mouseLeftDown = mouseRightDown = false; mouseX = mouseY = 0; cameraAngleX = cameraAngleY = 0; cameraDistance = CAMERA_DISTANCE; drawMode = 0; // 0:fill, 1: wireframe, 2:points imageData = new GLubyte[DATA_SIZE]; memset(imageData, 0, DATA_SIZE); return true; } void clearSharedMem() { delete [] imageData; imageData = 0; glDeleteTextures(1, &textureId); if(pboSupported) { glDeleteBuffers(2, pboIds); } } void initLights() { GLfloat lightKa[] = {.2f, .2f, .2f, 1.0f}; // ambient light GLfloat lightKd[] = {.7f, .7f, .7f, 1.0f}; // diffuse light GLfloat lightKs[] = {1, 1, 1, 1}; // specular light glLightfv(GL_LIGHT0, GL_AMBIENT, lightKa); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightKd); glLightfv(GL_LIGHT0, GL_SPECULAR, lightKs); float lightPos[4] = {0, 0, 20, 1}; glLightfv(GL_LIGHT0, GL_POSITION, lightPos); glEnable(GL_LIGHT0); } void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(posX, posY, posZ, targetX, targetY, targetZ, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z) } void updatePixels(GLubyte* dst, int size) { static int color = 0; if(!dst) return; int* ptr = (int*)dst; for(int i = 0; i < IMAGE_HEIGHT; ++i) { for(int j = 0; j < IMAGE_WIDTH; ++j) { *ptr = color; ++ptr; } color += 257; } ++color; } void showInfo() { glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, screenWidth, 0, screenHeight); float color[4] = {1, 1, 1, 1}; std::stringstream ss; ss << "PBO: "; if(pboMode == 0) ss << "off" << std::ends; else if(pboMode == 1) ss << "1 PBO" << std::ends; else if(pboMode == 2) ss << "2 PBOs" << std::ends; drawString(ss.str().c_str(), 1, screenHeight-TEXT_HEIGHT, color, font); ss.str(""); // clear buffer ss << std::fixed << std::setprecision(3); ss << "Updating Time: " << updateTime << " ms" << std::ends; drawString(ss.str().c_str(), 1, screenHeight-(2*TEXT_HEIGHT), color, font); ss.str(""); ss << "Copying Time: " << copyTime << " ms" << std::ends; drawString(ss.str().c_str(), 1, screenHeight-(3*TEXT_HEIGHT), color, font); ss.str(""); ss << "Press SPACE key to toggle PBO on/off." << std::ends; drawString(ss.str().c_str(), 1, 1, color, font); ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } void showTransferRate() { static Timer timer; static int count = 0; static std::stringstream ss; ++count; double elapsedTime = timer.getElapsedTime(); if(elapsedTime > 1.0) { ss.str(""); ss << std::fixed << std::setprecision(1); ss << "Transfer Rate: " << (count / elapsedTime) * DATA_SIZE / (1024 * 1024) << " MB" << std::ends; // update fps string ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); count = 0; timer.start(); } glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); //gluOrtho2D(0, IMAGE_WIDTH, 0, IMAGE_HEIGHT); gluOrtho2D(0, screenWidth, 0, screenHeight); float color[4] = {1, 1, 0, 1}; drawString(ss.str().c_str(), 200, 286, color, font); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } void printTransferRate() { const double INV_MEGA = 1.0 / (1024 * 1024); static Timer timer; static int count = 0; static std::stringstream ss; double elapsedTime; ++count; elapsedTime = timer.getElapsedTime(); if(elapsedTime > 1.0) { std::cout << std::fixed << std::setprecision(1); std::cout << "Transfer Rate: " << (count / elapsedTime) * DATA_SIZE * INV_MEGA << " MB/s. (" << count / elapsedTime << " FPS)\n"; std::cout << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); count = 0; timer.start(); } } void toOrtho() { glViewport(0, 0, (GLsizei)screenWidth, (GLsizei)screenHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, screenWidth, 0, screenHeight, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void toPerspective() { glViewport(0, 0, (GLsizei)screenWidth, (GLsizei)screenHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)(screenWidth)/screenHeight, 1.0f, 1000.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void displayCB() { static int index = 0; int nextIndex = 0; if(pboMode > 0) { if(pboMode == 1) { index = nextIndex = 0; } else if(pboMode == 2) { index = (index + 1) % 2; nextIndex = (index + 1) % 2; } t1.start(); glBindTexture(GL_TEXTURE_2D, textureId); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIds[index]); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0); t1.stop(); copyTime = t1.getElapsedTimeInMilliSec(); t1.start(); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIds[nextIndex]); glBufferData(GL_PIXEL_UNPACK_BUFFER, DATA_SIZE, 0, GL_STREAM_DRAW); GLubyte* ptr = (GLubyte*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY); if(ptr) { updatePixels(ptr, DATA_SIZE); glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); } t1.stop(); updateTime = t1.getElapsedTimeInMilliSec(); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } else { t1.start(); glBindTexture(GL_TEXTURE_2D, textureId); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, (GLvoid*)imageData); t1.stop(); copyTime = t1.getElapsedTimeInMilliSec(); t1.start(); updatePixels(imageData, DATA_SIZE); t1.stop(); updateTime = t1.getElapsedTimeInMilliSec(); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glPushMatrix(); glTranslatef(0, 0, -cameraDistance); glRotatef(cameraAngleX, 1, 0, 0); glRotatef(cameraAngleY, 0, 1, 0); glBindTexture(GL_TEXTURE_2D, textureId); glColor4f(1, 1, 1, 1); glBegin(GL_QUADS); glNormal3f(0, 0, 1); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 0.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 0.0f); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); showInfo(); printTransferRate(); glPopMatrix(); glutSwapBuffers(); } void reshapeCB(int width, int height) { screenWidth = width; screenHeight = height; toPerspective(); } void timerCB(int millisec) { glutTimerFunc(millisec, timerCB, millisec); glutPostRedisplay(); } void idleCB() { glutPostRedisplay(); } void keyboardCB(unsigned char key, int x, int y) { switch(key) { case 27: exit(0); break; case ' ': if(pboSupported) { ++pboMode; pboMode %= 3; } std::cout << "PBO mode: " << pboMode << std::endl; break; case 'd': case 'D': ++drawMode; drawMode %= 3; if(drawMode == 0) // fill mode { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); } else if(drawMode == 1) // wireframe mode { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } else // point mode { glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } break; default: ; } } void mouseCB(int button, int state, int x, int y) { mouseX = x; mouseY = y; if(button == GLUT_LEFT_BUTTON) { if(state == GLUT_DOWN) { mouseLeftDown = true; } else if(state == GLUT_UP) mouseLeftDown = false; } else if(button == GLUT_RIGHT_BUTTON) { if(state == GLUT_DOWN) { mouseRightDown = true; } else if(state == GLUT_UP) mouseRightDown = false; } } void mouseMotionCB(int x, int y) { if(mouseLeftDown) { cameraAngleY += (x - mouseX); cameraAngleX += (y - mouseY); mouseX = x; mouseY = y; } if(mouseRightDown) { cameraDistance -= (y - mouseY) * 0.2f; if(cameraDistance < 2.0f) cameraDistance = 2.0f; mouseY = y; } } void exitCB() { clearSharedMem(); }
#include <iostream> #include <sstream> #include <string> #include <fstream> using namespace std; #include "VoterDB.h" #include "VoterMenu.h" int main(int argc, char *argv[]) { int voters = 0; string file; if (argc == 1) { cout << "\nYou must supply a max voters parameter.\n"; return 0; } if (argc > 1) { istringstream buf(argv[1]); buf >> voters; if (voters < 1 || voters > 1000) { cout << "You must supply a max voters parameter between 1 and 1000.\n"; return 0; } } if (argc > 2) { istringstream buf(argv[2]); buf >> file; } VoterDB voter_database = VoterDB(voters); ifstream infile(file); if (infile) { voter_database.populate(infile); } string choice; do { cout << "\n\nVoter Information Main Menu: Please select from the following\n" << "Login\n" << "New\n" << "Report\n" << "Save\n" << "Load\n" << "Quit\n"; choice = user_input(); if (choice == "Quit") break; else if (choice == "Login") { login_menu(voter_database); } else if (choice == "New") { create_new(voter_database); } else if (choice == "Report") { cout << voter_database; } else if (choice == "Save") { save_database(voter_database); } else if (choice == "Load") { load_database(voter_database); } else { cout << "\nInvalid input, please try again."; continue; } } while (true); }
#include <SPI.h> #include <MFRC522.h> #define SS_PIN 5 #define RST_PIN 9 #define RELAY 3 //connect the relay to number 3 pin #define BUZZER 2 // connect the buzzer to 2 pin #define ACCESS_DELAY 2000 #define DENIED_DELAY 1000 //LED Light const int pwm = 10 ; //LCD #include <LiquidCrystal.h> // initialize the library by associating any needed LCD interface pin // with the arduino pin number it is connected to const int rs = 8, en = 7, d4 = 6, d5 = 4, d6 = 1, d7 = 0; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance. void setup() { lcd.begin(17, 2); //Serial.begin(9600); // Initiate a serial communication SPI.begin(); // Initiate SPI bus mfrc522.PCD_Init(); // Initiate MFRC522 pinMode(RELAY, OUTPUT); pinMode(BUZZER, OUTPUT); noTone(BUZZER); digitalWrite(RELAY, HIGH); //Serial.println("Put your card to the reader for scanning ..."); //Serial.println(); //LCD // set up the LCD's number of columns and rows: // Print a message to the LCD. //LED light pinMode(pwm,OUTPUT) ; //Set pin 2 as output } void loop() { // Look for new cards if ( ! mfrc522.PICC_IsNewCardPresent()) { return; } // Select one of the cards if ( ! mfrc522.PICC_ReadCardSerial()) { return; } //Show UID on serial monitor //Serial.print("UID tag :"); String content= ""; byte letter; for (byte i = 0; i < mfrc522.uid.size; i++) { //Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); //Serial.print(mfrc522.uid.uidByte[i], HEX); content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ")); content.concat(String(mfrc522.uid.uidByte[i], HEX)); } // Serial.println(); //Serial.print("Message : "); content.toUpperCase(); if (content.substring(1) == "1A 66 FD 84") // enter your own card number after copying it from serial monitor { //Serial.println("Authorized access"); lcd.print("Access Success:)"); //Serial.println(); delay(500); digitalWrite(RELAY, LOW); delay(ACCESS_DELAY); digitalWrite(RELAY, HIGH); analogWrite(pwm,2500) ; //setting pwm to 25 delay(50) ; //delay of 50 ms lcd.clear(); } else { //Serial.println(" Access denied"); lcd.print("Access Denied :("); tone(BUZZER, 300); delay(DENIED_DELAY); noTone(BUZZER); lcd.clear(); } //LCD // Turn off the blinking cursor: //lcd.noBlink(); //delay(100); // Turn on the blinking cursor: //lcd.blink(); //delay(3000); }
#include "mainwindow.h" #include "ui_mainwindow.h" #include "mqtt.h" #include <QDebug> #include <string> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(&configDialog, SIGNAL(configChanged()), this, SLOT(on_configChanged())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::SetMqtt(mqtt *p_mqtt_arg){ p_mqtt = p_mqtt_arg; } void MainWindow::on_actionExit_triggered() { QApplication::quit(); } //light switch button pressed void MainWindow::on_pushButton_clicked() { QString number; QMessageBox msgBox; if(connect_state) { //just send switch touched message //and update level p_mqtt->mqtt_pubSwitch(); p_mqtt->mqtt_pubLevel(this->ui->verticalSlider->value()); } else { msgBox.setText("Warning"); msgBox.setInformativeText("Not connected"); msgBox.exec(); } } void MainWindow::on_verticalSlider_valueChanged(int value) { if(no_level_update ){ no_level_update = 0; } else { if(connect_state && lswitchState){ qDebug() << "Slider_valueChanged " << value; p_mqtt->mqtt_pubLevel(value); } } } //Connect button void MainWindow::on_pushButton_2_clicked() { if(connect_state){ p_mqtt->mqtt_disconnect(); } else { //update config QString name = QString(configDialog.getRoomName()); QString light = QString(configDialog.getSwitchName()); p_mqtt->mqtt_set_room(QString(configDialog.getRoomName())); p_mqtt->mqtt_set_light(QString(configDialog.getSwitchName())) ; p_mqtt->mqtt_connect(); } } void MainWindow::on_actionConfigure_triggered() { configDialog.show(); } void MainWindow::on_configChanged(){ //if(configDialog.getConfigSet()){ QString text = QString("%1/%2").arg(configDialog.getRoomName(), configDialog.getSwitchName()); ui->labelTopic->setText(text ); //} } void MainWindow::on_connectEvent(int state){ qDebug() << "on_connectEvent" << state; if(state){ ui->pushButton_2->setText("Disconnect"); connect_state = 1; lswitchState = 0; ui->pushButton->setText("OFF"); } else { ui->pushButton_2->setText("Connect"); connect_state = 0; lswitchState = 0; } } void MainWindow::on_lightEvent(int lightState){ if(lightState != lswitchState){ lswitchState = lightState; if(lightState){ ui->pushButton->setText("ON"); } else{ ui->pushButton->setText("OFF"); } } } void MainWindow::on_switchLevelEvent(int level){ //if(lswitchState){ qDebug() << "on_switchLevelEven " << level; if(ui->verticalSlider->value() != level){ no_level_update = 1; ui->verticalSlider->setValue(level); } //} }
// // Created by silvman on 3/2/19. // #ifndef EESKORKA_HTTPUTILITY_H #define EESKORKA_HTTPUTILITY_H #include <string> #include <filesystem> #include <regex> #include <fstream> #include "../server/ServerConfig.h" #include "../logger/ServerLogger.h" namespace eeskorka { namespace fs = std::filesystem; namespace utility { std::string URLDecode(const std::string &uri); std::string URLEncode(const std::string &uri); std::string RFC1123Time(time_t time); std::string getContentType(const fs::path &path); serverConfig readConfig(const fs::path &path); } } #endif //EESKORKA_HTTPUTILITY_H
// Created on: 1994-10-13 // Created by: Jean Yves LEBEY // Copyright (c) 1994-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 _TopOpeBRep_EdgesIntersector_HeaderFile #define _TopOpeBRep_EdgesIntersector_HeaderFile #include <BRepAdaptor_Surface.hxx> #include <GeomAbs_SurfaceType.hxx> #include <Geom2dAdaptor_Curve.hxx> #include <Geom2dInt_GInter.hxx> #include <IntRes2d_Domain.hxx> #include <IntRes2d_SequenceOfIntersectionPoint.hxx> #include <IntRes2d_SequenceOfIntersectionSegment.hxx> #include <TopAbs_Orientation.hxx> #include <TopoDS_Face.hxx> #include <TopOpeBRep_SequenceOfPoint2d.hxx> #include <TopOpeBRep_P2Dstatus.hxx> #include <TopOpeBRepDS_Config.hxx> class Bnd_Box; class BRepAdaptor_Surface; class TCollection_AsciiString; class TopOpeBRep_Point2d; class IntRes2d_IntersectionSegment; class IntRes2d_IntersectionPoint; class TopOpeBRepDS_Transition; class gp_Pnt; //! Describes the intersection of two edges on the same surface class TopOpeBRep_EdgesIntersector { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TopOpeBRep_EdgesIntersector(); Standard_EXPORT virtual ~TopOpeBRep_EdgesIntersector(); Standard_EXPORT void SetFaces (const TopoDS_Shape& F1, const TopoDS_Shape& F2); Standard_EXPORT void SetFaces (const TopoDS_Shape& F1, const TopoDS_Shape& F2, const Bnd_Box& B1, const Bnd_Box& B2); Standard_EXPORT void ForceTolerances (const Standard_Real Tol1, const Standard_Real Tol2); Standard_EXPORT void Dimension (const Standard_Integer D); //! set working space dimension D = 1 for E &|| W, 2 for E in F Standard_EXPORT Standard_Integer Dimension() const; Standard_EXPORT void Perform (const TopoDS_Shape& E1, const TopoDS_Shape& E2, const Standard_Boolean ReduceSegments = Standard_True); Standard_EXPORT Standard_Boolean IsEmpty(); //! true if at least one intersection segment. Standard_EXPORT Standard_Boolean HasSegment() const; //! = mySameDomain. Standard_EXPORT Standard_Boolean SameDomain() const; Standard_EXPORT const TopoDS_Shape& Edge (const Standard_Integer Index) const; Standard_EXPORT const Geom2dAdaptor_Curve& Curve (const Standard_Integer Index) const; Standard_EXPORT const TopoDS_Shape& Face (const Standard_Integer Index) const; Standard_EXPORT const BRepAdaptor_Surface& Surface (const Standard_Integer Index) const; Standard_EXPORT Standard_Boolean SurfacesSameOriented() const; Standard_EXPORT Standard_Boolean FacesSameOriented() const; Standard_EXPORT Standard_Real ToleranceMax() const; Standard_EXPORT void Tolerances (Standard_Real& tol1, Standard_Real& tol2) const; Standard_EXPORT Standard_Integer NbPoints() const; Standard_EXPORT Standard_Integer NbSegments() const; Standard_EXPORT void Dump (const TCollection_AsciiString& str, const Standard_Integer ie1 = 0, const Standard_Integer ie2 = 0); Standard_EXPORT void InitPoint (const Standard_Boolean selectkeep = Standard_True); Standard_EXPORT Standard_Boolean MorePoint() const; Standard_EXPORT void NextPoint(); Standard_EXPORT const TopOpeBRep_SequenceOfPoint2d& Points() const; Standard_EXPORT const TopOpeBRep_Point2d& Point() const; Standard_EXPORT const TopOpeBRep_Point2d& Point (const Standard_Integer I) const; Standard_EXPORT virtual Standard_Boolean ReduceSegment (TopOpeBRep_Point2d& P1, TopOpeBRep_Point2d& P2, TopOpeBRep_Point2d& Pn) const; Standard_EXPORT TopOpeBRep_P2Dstatus Status1() const; protected: private: Standard_EXPORT void Find(); //! process if current edges can be considered as SameDomain Standard_EXPORT Standard_Boolean ComputeSameDomain(); //! set field mySameDomain to B and return B value Standard_EXPORT Standard_Boolean SetSameDomain (const Standard_Boolean B); Standard_EXPORT void MakePoints2d(); Standard_EXPORT void ReduceSegments(); Standard_EXPORT const IntRes2d_IntersectionSegment& Segment1() const; Standard_EXPORT Standard_Boolean IsOpposite1() const; Standard_EXPORT void InitPoint1(); Standard_EXPORT Standard_Boolean MorePoint1() const; Standard_EXPORT void NextPoint1(); Standard_EXPORT const IntRes2d_IntersectionPoint& Point1() const; Standard_EXPORT TopOpeBRepDS_Transition Transition1 (const Standard_Integer Index, const TopAbs_Orientation EO) const; Standard_EXPORT Standard_Real Parameter1 (const Standard_Integer Index) const; Standard_EXPORT Standard_Boolean IsVertex1 (const Standard_Integer Index); Standard_EXPORT const TopoDS_Shape& Vertex1 (const Standard_Integer Index); Standard_EXPORT gp_Pnt Value1() const; Standard_EXPORT Standard_Boolean IsPointOfSegment1() const; Standard_EXPORT Standard_Integer Index1() const; //! geometric configuration of E1,E2 at current intersection point : //! UNSHGEOMETRY if the edges do not share geometry. //! SAMEORIENTED if the edges share geometry and are same oriented. //! DIFFORIENTED if the edges share geometry and are not same oriented. Standard_EXPORT TopOpeBRepDS_Config EdgesConfig1() const; TopoDS_Face myFace1; TopoDS_Face myFace2; Handle(BRepAdaptor_Surface) mySurface1; Handle(BRepAdaptor_Surface) mySurface2; GeomAbs_SurfaceType mySurfaceType1; GeomAbs_SurfaceType mySurfaceType2; Standard_Boolean mySurfacesSameOriented; Standard_Boolean myFacesSameOriented; IntRes2d_Domain myDomain1; IntRes2d_Domain myDomain2; TopoDS_Edge myEdge1; TopoDS_Edge myEdge2; Geom2dAdaptor_Curve myCurve1; Geom2dAdaptor_Curve myCurve2; Standard_Real myTol1; Standard_Real myTol2; Standard_Boolean myTolForced; Geom2dInt_GInter myIntersector; IntRes2d_SequenceOfIntersectionPoint mylpnt; IntRes2d_SequenceOfIntersectionSegment mylseg; Standard_Integer myNbPoints; Standard_Integer myNbSegments; Standard_Integer myTrueNbPoints; Standard_Integer myPointIndex; Standard_Integer myIsVertexPointIndex; Standard_Integer myIsVertexIndex; Standard_Boolean myIsVertexValue; TopoDS_Vertex myIsVertexVertex; Standard_Integer myDimension; Standard_Boolean myHasSegment; Standard_Boolean mySameDomain; Standard_Boolean myf1surf1F_sameoriented; Standard_Boolean myf2surf1F_sameoriented; TopOpeBRep_SequenceOfPoint2d mysp2d; Standard_Integer myip2d; Standard_Integer mynp2d; Standard_Boolean myselectkeep; }; #endif // _TopOpeBRep_EdgesIntersector_HeaderFile
#pragma once #include "BufferManager.h" #include "RWLockable.h" #include "Block.h" #include <bitstream.h> #include <unordered_map> namespace credb { namespace trusted { class Shard : public RWLockable { public: explicit Shard(BufferManager &buffer); Shard(const Shard &other) = delete; shard_id_t identifier() const { return m_identifier; } page_no_t pending_block_id() const { return m_pending_block_id; } PageHandle<Block> get_block(block_id_t block); PageHandle<Block> generate_block(); /// For downstream void set_pending_block(page_no_t id, Block::int_type num_events) { m_pending_block_id = id; m_num_pending_events = num_events; } void discard_pending_block(); // for downstream void discard_cached_block(page_no_t page_no); // for downstream void unload_everything(); // for debug purpose void dump_metadata(bitstream &output); // for debug purpose void load_metadata(bitstream &input); // for debug purpose private: BufferManager &m_buffer; shard_id_t m_identifier; //Needed for downstream page_no_t m_pending_block_id; Block::int_type m_num_pending_events; PageHandle<Block> m_pending_block; }; } // namespace trusted } // namespace credb
class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { vector<bool> DP(s.size() + 1, 0); DP[0] = 1; set<string> setDict; for (auto i : wordDict) { setDict.insert(i); } for (int i=1; i<=s.size(); i++) { for (int j=0; j<i; j++) { if (setDict.count(s.substr(j, i - j)) && DP[j]) { DP[i] = 1; break; } } } return DP[s.size()]; } };
// BEGIN CUT HERE // PROBLEM STATEMENT // A big box contains marbles of one or more colors. You're // given a vector <int> colors, each element of which denotes // the number of marbles there are of a particular color. You // draw n marbles randomly from the box, leaving each marble // outside the box after taking it. Return the probability // that all marbles drawn will be the same color. // // DEFINITION // Class:DrawingMarbles // Method:sameColor // Parameters:vector <int>, int // Returns:double // Method signature:double sameColor(vector <int> colors, int // n) // // // NOTES // -Every time we draw a marble, all marbles in the box are // equally likely to be chosen. // -A return value with either an absolute or relative error // of less than 1.0E-9 is considered correct. // // // CONSTRAINTS // -colors will contain between 1 and 50 elements, inclusive. // -Each element of colors will be between 1 and 50, inclusive. // -n will be between 1 and the sum of all elements of // colors, inclusive. // // // EXAMPLES // // 0) // { 13 } // 8 // // Returns: 1.0 // // All the marbles are the same color, so obviously all drawn // marbles will be the same color too. // // 1) // { 5, 7 } // 1 // // Returns: 1.0 // // // // 2) // { 5, 6, 7 } // 2 // // Returns: 0.3006535947712418 // // The probability that the first drawn marble will be of the // color 0 is 5 / 18 (there are 5 marbles of color 0 out of // 18). If the first drawn marble is of the color 0, then the // probability that the second drawn marble will be of the // color 0 is 4 / 17 (there are 4 marbles of color 0 left out // of 17). So the probability that both drawn marbles will be // of the color 0 is (5 / 18) * (4 / 17) = 0.0653594771... . // Similarly, the probability that both drawn marbles will be // of the color 1 is (6 / 18) * (5 / 17) = 0.0980392156..., // and that both drawn marbles will be of the color 2 is (7 / // 18) * (6 / 17) = 0.1372549019... . The answer is the sum // of these 3 probabilities. // // 3) // { 12, 2, 34, 13, 17 } // 4 // // Returns: 0.035028830818304504 // // // // END CUT HERE #line 81 "DrawingMarbles.cpp" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; double memo[2505][2505]; bool done[2505][2505]; double ncr(int n, int r) { if (done[n][r]) { return memo[n][r]; } if (r == 0) { return memo[n][r] = 1; } if (n < r) { return memo[n][r] = 0; } return memo[n][r] = ncr(n-1,r-1) + ncr(n-1,r); } class DrawingMarbles { public: double sameColor(vector <int> colors, int n) { int t = 0; fi(colors.size()) t += colors[i]; memset(done, 0, sizeof(done)); long double ret = 0.0; fi(colors.size()) { if (colors[i] < n) { continue; } ret += ncr(colors[i], n) / ncr(t, n); } return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = { 13 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 8; double Arg2 = 1.0; verify_case(0, Arg2, sameColor(Arg0, Arg1)); } void test_case_1() { int Arr0[] = { 5, 7 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; double Arg2 = 1.0; verify_case(1, Arg2, sameColor(Arg0, Arg1)); } void test_case_2() { int Arr0[] = { 5, 6, 7 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; double Arg2 = 0.3006535947712418; verify_case(2, Arg2, sameColor(Arg0, Arg1)); } void test_case_3() { int Arr0[] = { 12, 2, 34, 13, 17 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 4; double Arg2 = 0.035028830818304504; verify_case(3, Arg2, sameColor(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { DrawingMarbles ___test; ___test.run_test(-1); } // END CUT HERE
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib // This simple sketch will adjust the RTC time to the desired time as defined // in DATE and TIME defines. The adjustment will be made upon pressing the // SET_BUTTON. The adjustment can be skipped by pressing the SKIP_BUTTON. When // done, the time is shown every 10 seconds. Button is HIGH when NOT pressed. #include <Wire.h> #include <RTClib.h> // buttons #define SET_BUTTON 2 #define SKIP_BUTTON 3 // desired time for RTC #define DATE "Sep 17 2015" #define TIME "00:55:00" RTC_DS1307 RTC; void setup () { Serial.begin(115200); Wire.begin(); RTC.begin(); // this button will trigger time setting when changed to LOW pinMode(SET_BUTTON, INPUT); digitalWrite(SET_BUTTON, HIGH); // enable pull up R // this button will skip the time setting when changed to LOW pinMode(SKIP_BUTTON, INPUT); digitalWrite(SKIP_BUTTON, HIGH); // enable pull up R // allow some time to connect the terminal delay (3000); Serial.print(F("RTC will be adjusted to the following time: ")); Serial.print(F(DATE)); Serial.print(F(" / ")); Serial.println(F(TIME)); Serial.print(F("YES: connect GND to PIN")); Serial.println(SET_BUTTON); Serial.print(F("NO: connect GND to PIN")); Serial.println(SKIP_BUTTON); while(1) { // keep waiting until pin is HIGH if (digitalRead(SET_BUTTON) == LOW) { DateTime now = DateTime(F(DATE), F(TIME)); RTC.adjust(now); Serial.println("The RTC has been ADJUSTED"); break; } if (digitalRead(SKIP_BUTTON) == LOW) { Serial.println("The RTC has been left UNCHANGED"); break; } } } void loop () { DateTime now = RTC.now(); Serial.print(now.year(), DEC); Serial.print('/'); Serial.print(now.month(), DEC); Serial.print('/'); Serial.print(now.day(), DEC); Serial.print(' '); Serial.print(now.hour(), DEC); Serial.print(':'); Serial.print(now.minute(), DEC); Serial.print(':'); Serial.print(now.second(), DEC); Serial.println(); Serial.print("unix: "); Serial.println(now.unixtime()); delay(1000 * 10); }
#include <my_filters/common_include.h> //--------------- KF ---------------// class KF { // ros ros::NodeHandle nh_; ros::Publisher pub_kf, pub_pf; ros::Subscriber sub_arucoResult; ros::Subscriber sub_arucoPixel; ros::Subscriber sub_pcl; geometry_msgs::PointStamped msg_kf, msg_pf; // time ros::Time ti,tf; double dt; // config bool test_mode; int filter_type; // random std::random_device rd; // others int AR_seq=-1, AR_seq_old=-1, imgSizeRow, imgSizeCol, imgNum; Eigen::Vector4d noise4d, measurement, stateTrue; cv::Mat testImg; cv_bridge::CvImagePtr realImgArr[3]; std::string cvWindowName[3]={"PREDICTION","UPDATE","RESAMPLE"}; cv::Scalar colorTrue=cv::Scalar(255,0,0), colorPre=cv::Scalar(0,255,0), colorPost=cv::Scalar(0,0,255), colorMeas=cv::Scalar(255,255,255); //pcl pcl::PointCloud<pcl::PointXYZRGB> cloud_; pcl::PointXYZRGB cloud_p; //tf tf::TransformBroadcaster br; tf::TransformListener listener; tf::Transform transform; tf::Quaternion qtf; tf::StampedTransform transform2; // kalman filter double processNoiseFactor,measurementNoiseFactor; Eigen::Vector4d statePre, statePost; Eigen::Matrix4d errorCovPre, errorCovPost, A_KF, C_KF, R_KF, Q_KF, K_KF; Eigen::Matrix2d ellipse_value,ellipse_vector; // particle filter int M; bool doInit = true; Eigen::MatrixXd particlePost, particlePre, weight, weightAccumulation; Eigen::Matrix4d A_PF, C_PF; Eigen::Vector4d statePrePf,statePostPf; double processNoiseVar, resampleNoiseVar, weightSum, measurementVar; // function menber void transport_arucoResult(const sensor_msgs::ImageConstPtr &img); void transport_arucoPixel(const geometry_msgs::PointStamped &pixel); void transport_pcl(const sensor_msgs::PointCloud2ConstPtr &pc); void initialization(); void prediction(); void update(); void draw_ellipse(const Eigen::Vector4d &center, const Eigen::Matrix4d &cov, cv::Scalar color, int n); void draw_particle(const Eigen::Vector4d &center, int radius, cv::Scalar color, int n); // public function menber public: KF(ros::NodeHandle nh); ~KF(){} }; KF::KF(ros::NodeHandle nh) : nh_(nh) { // initialize publisher and subscriber pub_kf = nh_.advertise<geometry_msgs::PointStamped>("/kf_result",100); pub_pf = nh_.advertise<geometry_msgs::PointStamped>("/pf_result",100); sub_arucoResult = nh_.subscribe("/aruco_single/result", 100, &KF::transport_arucoResult, this); sub_arucoPixel = nh_.subscribe("/aruco_single/pixel", 100, &KF::transport_arucoPixel, this); sub_pcl = nh_.subscribe("/xtion/depth_registered/points", 100, &KF::transport_pcl, this); // initialize parameter ros::param::get("test_mode",test_mode); ros::param::get("filter_type",filter_type); ros::param::get("imgSizeRow",imgSizeRow); ros::param::get("imgSizeCol",imgSizeCol); testImg = cv::Mat::zeros(imgSizeRow*4, imgSizeCol, CV_32FC3); ti = ros::Time::now(); switch (filter_type) { case 1: // kf initialization ros::param::get("processNoiseFactor",processNoiseFactor); ros::param::get("measurementNoiseFactor",measurementNoiseFactor); imgNum = 1; statePost << 1,1,1,1; statePost += Eigen::Vector4d::Random(); errorCovPost = A_KF = C_KF = Eigen::Matrix4d::Identity(); R_KF = processNoiseFactor * Eigen::Matrix4d::Identity(); Q_KF = measurementNoiseFactor * Eigen::Matrix4d::Identity(); break; case 2: break; case 3: // pf initialization ros::param::get("particleNum",M); ros::param::get("processNoiseVar",processNoiseVar); ros::param::get("measurementVar",measurementVar); ros::param::get("resampleNoiseVar",resampleNoiseVar); imgNum = 3; particlePost.setZero(4,M); particlePre.setZero(4,M); weight.setZero(1,M); weightAccumulation.setZero(1,M); A_PF = C_PF = Eigen::Matrix4d::Identity(); if (test_mode) { initialization(); cv::imshow("TESTIMAGE",testImg); cv::waitKey(3); } break; } ROS_WARN_STREAM("INITIALIZATION: test_mode=" << test_mode << " filter_type=" << filter_type); } //--------------- transport arucoPixel and arucoresult ---------------// void KF::transport_arucoPixel(const geometry_msgs::PointStamped &pixel) { // ROS_WARN_STREAM(__LINE__); measurement << pixel.point.x , pixel.point.y, (pixel.point.x-statePost(0))/dt, (pixel.point.y-statePost(1))/dt; AR_seq = pixel.header.seq; return; } void KF::transport_arucoResult(const sensor_msgs::ImageConstPtr &img) { // ROS_WARN_STREAM(__LINE__); if (filter_type ==1) A_KF(0,2) = A_KF(1,3) = dt; tf = ros::Time::now(); dt = tf.toSec()-ti.toSec(); measurement(2) = (measurement(0)-statePost(0))/dt; measurement(3) = (measurement(1)-statePost(1))/dt; for (int n=0;n<imgNum;n++) realImgArr[n] = cv_bridge::toCvCopy(img, sensor_msgs::image_encodings::BGR8); if (filter_type == 3 && doInit) { ROS_WARN_STREAM("INITIALIZE THE IMGSIZE"); imgSizeRow = img->width; imgSizeCol = img->height; initialization(); doInit = false; return; } prediction(); if (AR_seq != AR_seq_old) { update(); ti = tf; AR_seq_old = AR_seq; } else { particlePost = particlePre; statePost = statePre; } for (int n=0;n<imgNum;n++) cv::imshow(cvWindowName[n], realImgArr[n]->image); cv::waitKey(3); return; } void KF::transport_pcl(const sensor_msgs::PointCloud2ConstPtr &pc) { pcl::fromROSMsg(*pc, cloud_); cloud_p = cloud_.at(statePost(0),statePost(1)); listener.lookupTransform("/xtion_rgb_optical_frame", "/arm_6_link", ros::Time(0), transform2); // qtf.setRPY(0,0,0); transform.setOrigin(tf::Vector3(cloud_p.x, cloud_p.y, cloud_p.z)); transform.setRotation(transform2.getRotation()); br.sendTransform(tf::StampedTransform(transform,ros::Time::now(),"/xtion_rgb_optical_frame","/pose_estimation")); ROS_INFO_STREAM(cloud_p.x << cloud_p.y << cloud_p.z); ROS_INFO("Process pcl"); return; } //--------------- predict and update---------------// void KF::initialization() { std::mt19937 gen(rd()); std::uniform_int_distribution<> rng_initialRow(1, imgSizeRow); std::uniform_int_distribution<> rng_initialCol(1, imgSizeCol); std::uniform_int_distribution<> rng_initialVel(-50, 50); for (int n=0; n<M; ++n) { particlePost.col(n) << rng_initialRow(gen),rng_initialCol(gen),rng_initialVel(gen),rng_initialVel(gen); draw_particle(particlePost.col(n), 1, colorPost, 3); } } void KF::prediction() { ROS_WARN_STREAM("PREDICTION"); switch (filter_type) { case 1: statePre = A_KF * statePost; errorCovPre = A_KF * errorCovPost * A_KF.transpose() + R_KF; statePost = statePre; draw_ellipse(statePre,errorCovPre,colorPre,1); draw_particle(stateTrue, 1, colorTrue, 3); draw_particle(statePre, 1, colorPre, 3); draw_particle(measurement, 1, colorMeas, 3); break; case 2: break; case 3: particlePre = A_PF * particlePost; std::mt19937 gen(rd()); std::normal_distribution<> rng_processNoise{0,processNoiseVar}; std::uniform_int_distribution<> rng_sampleDynamicModel(0, M-1); for (int n=0; n<M; ++n) { noise4d << rng_processNoise(gen),rng_processNoise(gen),rng_processNoise(gen),rng_processNoise(gen); particlePre.col(n)=particlePre.col(rng_sampleDynamicModel(gen))+noise4d; draw_particle(particlePre.col(n), 1, colorPre, 1); } statePrePf << particlePre.row(0).mean(), particlePre.row(1).mean(), particlePre.row(2).mean(), particlePre.row(3).mean(); draw_particle(statePrePf, 3, colorPre, 1); break; } return; } void KF::update() { ROS_WARN_STREAM("UPDATE"); switch (filter_type) { case 1: K_KF = errorCovPre * (errorCovPre+Q_KF).inverse(); statePost = statePre + K_KF * (measurement-statePre); errorCovPost = (Eigen::Matrix4d::Identity()-K_KF) * errorCovPre; draw_ellipse(statePost, errorCovPost, colorPost, 2); draw_particle(statePost, 1, colorPost, 3); break; case 2: break; case 3: measurement = C_PF * measurement; weightSum = 0; for (int n=0; n<M; ++n) { double d = (particlePre.block(0,n,2,1)-measurement.topRows(2)).norm(); weight(n) = 1 / sqrt(2 * M_PI * measurementVar) * exp( -d*d/(2*measurementVar) ); weightAccumulation(n) = weightSum + weight(n); weightSum = weightAccumulation(n); draw_particle(particlePre.col(n), weight(n)*100, colorPost, 2); } weight = weight / weightSum; weightAccumulation = weightAccumulation / weightSum; statePostPf = particlePre * weight.transpose(); std::mt19937 gen(rd()); std::uniform_real_distribution<> rng_resample(0, 1); std::normal_distribution<> rng_resampleNoise{0,10}; for (int n=0; n<M; ++n) { double rn_resample = rng_resample(gen); noise4d << rng_resampleNoise(gen),rng_resampleNoise(gen),rng_resampleNoise(gen),rng_resampleNoise(gen); double begin=0,end=M,i=std::round((end-begin)/2+begin),target; for (; end-begin>1; i=std::round((end-begin)/2+begin)) { if (weightAccumulation(i)<rn_resample) { begin=i; target = end; } else if (weightAccumulation(i)>rn_resample) { end=i; target = end; } else { target = i; break; } } particlePost.col(n) = particlePre.col(target);//+noise4d; draw_particle(particlePost.col(n), 1, colorPost,3); } draw_particle(measurement, 3, colorMeas, 2); draw_particle(measurement, 3, colorMeas, 3); draw_particle(statePostPf, 3, colorPost, 2); draw_particle(statePostPf, 3, colorPost, 3); break; } return; } //--------------- draw ---------------// void KF::draw_ellipse(const Eigen::Vector4d &center, const Eigen::Matrix4d &cov, cv::Scalar color, int n) { double major_axis,minor_axis,angle; Eigen::EigenSolver<Eigen::Matrix2d> es(cov.block(0,0,2,2)); ellipse_value = es.pseudoEigenvalueMatrix(); ellipse_vector = es.pseudoEigenvectors(); major_axis = sqrt(5.991*ellipse_value(0)); minor_axis = sqrt(5.991*ellipse_value(3)); angle = 180/3.14*atan(ellipse_vector(1)/ellipse_vector(0)); try { if (test_mode) { cv::circle(testImg, cv::Point(center(0), center(1)+n*imgSizeRow), 1, color, CV_FILLED); cv::ellipse(testImg, cv::Point(center(0), center(1)+n*imgSizeRow), cv::Size(major_axis,minor_axis),angle, 0, 360, color); } else { cv::circle(realImgArr[0]->image, cv::Point(center(0),center(1)), 1, color, CV_FILLED); cv::ellipse(realImgArr[0]->image, cv::Point(center(0),center(1)), cv::Size(major_axis,minor_axis),angle, 0, 360, color); } } catch (...) { ROS_ERROR_STREAM("error!"); doInit = 0; } } void KF::draw_particle(const Eigen::Vector4d &center, int radius, cv::Scalar color, int n) { // red: particle, green: measurement, blue: statepost if (test_mode) cv::circle(testImg, cv::Point(center(0), center(1)+n*imgSizeRow), radius, color, CV_FILLED); else if (filter_type==1) return; else cv::circle(realImgArr[n-1]->image, cv::Point(center(0), center(1)), radius, color, CV_FILLED); } //--------------- main ---------------// int main(int argc, char** argv) { ros::init(argc,argv,"KF"); ros::NodeHandle nh; KF node(nh); ros::spin(); return 0; }
// // Main Components // ------------------- // - Ball // - Paddel // - Playing Field // - Scores #if defined (__EMSCRIPTEN__) #include <emscripten/emscripten.h> #include <emscripten/html5.h> #endif #include <functional> #include "GameScene.h" // variable to hold GameScene's frame function for emscripten std::function<void()> frame_function; // c style callback function for emscripten_set_main_loop() // emscripten_set_main_loop() requires a c style function, // since c has no sense of objects, we need a create a // wrapper function to hold the member function extern "C" void frame_wrapper() { frame_function(); } int main(int argc, char* args[]) { auto scene = new GameScene(); // attach the frame function from the scene object to frame_function frame_function = std::bind(&GameScene::frame, scene); #if defined (__EMSCRIPTEN__) emscripten_set_main_loop(frame_wrapper, 0, 0); #else scene->event_loop(); #endif return 0; }
#include "GnMainPCH.h" #include "GnTimeController.h" GnImplementRootRTTI(GnTimeController); void GnTimeController::SetCycleType(GnTimeController::eCycleType eType, GnObjectForm *pObject) { GnTimeController* ctrl = pObject->GetTimeControllers(); GnAssert( ctrl ); while ( ctrl ) { ctrl->SetCycleType( eType ); ctrl = ctrl->GetNext(); } } void GnTimeController::StartTimeControllers(GnObjectForm* pObject) { GnTimeController* ctrl = pObject->GetTimeControllers(); GnAssert( ctrl ); while ( ctrl ) { ctrl->Start(); ctrl = ctrl->GetNext(); } } void GnTimeController::StopTimeControllers(GnObjectForm* pObject) { GnTimeController* ctrl = pObject->GetTimeControllers(); GnAssert( ctrl ); while ( ctrl ) { ctrl->Stop(); ctrl = ctrl->GetNext(); } } bool GnTimeController::IsAllStopControllers(GnObjectForm* pObject) { GnTimeController* ctrl = pObject->GetTimeControllers(); GnAssert( ctrl ); while ( ctrl ) { if( ctrl->GetPlayFlags() == PLAY ) return false; ctrl = ctrl->GetNext(); } return true; } GnTimeController::GnTimeController() : mpTarget( NULL ), mIsMeshSteram( true ) { mCycleType = LOOP; mPlayFlags = PLAY; } GnTimeController::~GnTimeController() { } void GnTimeController::Start() { mPlayFlags = PLAY; } void GnTimeController::Stop() { mPlayFlags = STOP; } bool GnTimeController::SetTargetObject(GnObjectForm* pObject) { if( pObject == NULL ) { mpTarget = NULL; return true; } mpTarget = pObject; mpTarget->SetTimeController( this ); return true; } void GnTimeController::Playing(float fTime) { mPlayFlags = PLAYING; mStartTime = fTime; mAccumulateDeltaTime = 0.0f; } void GnTimeController::LoadStream(GnObjectStream* pStream) { GnObject::LoadStream( pStream ); pStream->LoadEnumStream( mCycleType ); pStream->LoadLinkID(); // mpsNext; pStream->LoadLinkID(); // mpTarget; } void GnTimeController::LinkObject(GnObjectStream* pStream) { GnObject::LinkObject( pStream ); mpsNext = (GnTimeController*)pStream->GetObjectFromLinkID(); mpTarget = (GnObjectForm*)pStream->GetObjectFromLinkID(); } void GnTimeController::SaveStream(GnObjectStream* pStream) { GnObject::SaveStream( pStream ); pStream->SaveEnumStream( mCycleType ); GnTimeController* control = mpsNext; if( control && control->IsStreamable() == false ) control = control->GetNext(); pStream->SaveLinkID( control ); pStream->SaveLinkID( mpTarget ); } void GnTimeController::RegisterSaveObject(GnObjectStream* pStream) { GnObject::RegisterSaveObject( pStream ); if( mpsNext ) mpsNext->RegisterSaveObject( pStream ); }
#include "../include/drift_diffusion.h" #include "../include/unscaling.h" void Drift_diffusion::unscaling_results(void) { int N = grid_scaled.N_points_scaled; // Plus two sided boundaries scaled_result result_scaled = result_it1_scaled; // Only the last is used result_it.V.resize(N); result_it.E.resize(N); result_it.n.resize(N); result_it.p.resize(N); result_it.n_t.resize(N); result_it.p_t.resize(N); result_it.a.resize(N); //result_it.c.resize(N); result_it.E_c.resize(N); result_it.E_v.resize(N); result_it.E_fn.resize(N); result_it.E_fp.resize(N); result_it.J_n.resize(N); result_it.J_p.resize(N); result_it.J_a.resize(N); //result_it.J_c.resize(N); result_it.J_disp.resize(N); result_it.t = time_unscaling(result_scaled.t_scaled, &params_c); result_it.t_steps = result_scaled.t_steps; result_it.epsilon_calc = result_scaled.epsilon_calc; for (int i = 0; i < N; i++) { result_it.V[i] = potential_unscaling(result_scaled.V_scaled[i], &params_c); result_it.E[i] = electric_field_unscaling(result_scaled.E_scaled[i], &params_c); result_it.n[i] = concentrations_unscaling(result_scaled.n_scaled[i], &params_c); result_it.p[i] = concentrations_unscaling(result_scaled.p_scaled[i], &params_c); result_it.n_t[i] = concentrations_unscaling(result_scaled.n_t_scaled[i], &params_c); result_it.p_t[i] = concentrations_unscaling(result_scaled.p_t_scaled[i], &params_c); result_it.a[i] = concentrations_unscaling(result_scaled.a_scaled[i], &params_c); //result_it.c[i] = concentrations_unscaling(result_scaled.c_scaled[i], &params_c); result_it.E_c[i] = energy_unscaling(result_scaled.E_c_scaled[i], &params_c); result_it.E_v[i] = energy_unscaling(result_scaled.E_v_scaled[i], &params_c); result_it.E_fn[i] = energy_unscaling(result_scaled.E_fn_scaled[i], &params_c); result_it.E_fp[i] = energy_unscaling(result_scaled.E_fp_scaled[i], &params_c); result_it.J_n[i] = current_density_unscaling(result_scaled.J_n_scaled[i], &params_c); result_it.J_p[i] = current_density_unscaling(result_scaled.J_p_scaled[i], &params_c); result_it.J_a[i] = current_density_unscaling(result_scaled.J_a_scaled[i], &params_c); //result_it.J_c[i] = current_density_unscaling(result_scaled.J_c_scaled[i], &params_c); result_it.J_disp[i] = current_density_unscaling(result_scaled.J_disp_scaled[i], &params_c); } result_it.J_total = current_density_unscaling(result_scaled.J_total_scaled, &params_c); // Grid unscaling vector<double> tmp_li, tmp_xi, tmp_hi, tmp_Gi; grid.N_points = grid_scaled.N_points_scaled; grid.N_points_boundaries = grid_scaled.N_points_boundaries_scaled; for (size_t i = 0; i < grid_scaled.N_points_scaled; i++) { tmp_li.push_back(grid_scaled.li_scaled[i]); tmp_xi.push_back(space_unscaling(grid_scaled.xi_scaled[i], &params_c)); tmp_Gi.push_back(generation_unscaling(grid_scaled.Gi_scaled[i], &params_c)); } for (size_t i = 0; i <= grid_scaled.N_points_boundaries_scaled; i++) tmp_hi.push_back(space_unscaling(grid_scaled.hi_scaled[i], &params_c)); grid.li = tmp_li; grid.xi = tmp_xi; grid.hi = tmp_hi; grid.Gi = tmp_Gi; } // PARAMETERS double space_unscaling(double x_scaled, scaling_params * params) { double tmp_space_unscaled; double x_c = params->x_c; // Unscaling space tmp_space_unscaled = x_scaled * x_c; return tmp_space_unscaled; } double time_unscaling(double t_scaled, scaling_params * params) { double tmp_time_unscaled; double t_c = params->t_c; // Unscaling time tmp_time_unscaled = t_scaled * t_c; return tmp_time_unscaled; } double permittivity_unscaling(double Er_scaled, scaling_params * params) { double tmp_Er_unscaled; double Er_max = params->Er_max; // Uncaling permittivity tmp_Er_unscaled = Er_scaled * Er_max; return tmp_Er_unscaled; } double concentrations_unscaling(double concentration_scaled, scaling_params * params) { double tmp_concentration_unscaled; double N = params->N; // Uncaling concentration tmp_concentration_unscaled = concentration_scaled * N; return tmp_concentration_unscaled; } double mobility_unscaling(double u_scaled, scaling_params * params) { double tmp_mobility_unscaled; double u_max = params->u_max; // Unscaling mobility tmp_mobility_unscaled = u_scaled * u_max; return tmp_mobility_unscaled; } double potential_unscaling(double V_scaled, scaling_params * params) { double tmp_V_unscaled; double V_c = params->V_c; // Unscaling potential tmp_V_unscaled = V_scaled * V_c; return tmp_V_unscaled; } double electric_field_unscaling(double E_scaled, scaling_params * params) { double tmp_E_unscaled; double F_c = params->F_c; // Unscaling electric field tmp_E_unscaled = E_scaled * F_c; return tmp_E_unscaled; } double current_density_unscaling(double J_scaled, scaling_params * params) { double tmp_J_unscaled; double J_c = params->J_c; // Unscaling current tmp_J_unscaled = J_scaled * J_c; return tmp_J_unscaled; } double generation_unscaling(double G_scaled, scaling_params * params) { double tmp_G_unscaled; double G_c = params->G_c; // Unscaling generation rate tmp_G_unscaled = G_scaled * G_c; return tmp_G_unscaled; } double bimolecular_unscaling(double B_scaled, scaling_params * params) { double tmp_B_unscaled; double B_c = params->T_c; // Unscaling trimolecular recombination rate tmp_B_unscaled = B_scaled * B_c; return tmp_B_unscaled; } double trimolecular_unscaling(double T_scaled, scaling_params * params) { double tmp_T_unscaled; double T_c = params->T_c; // Unscaling trimolecular recombination rate tmp_T_unscaled = T_scaled * T_c; return tmp_T_unscaled; } double energy_unscaling(double E_scaled, scaling_params * params) { double tmp_E_unscaled; double E_c = params->E_c; // Unscaling energy tmp_E_unscaled = E_scaled * E_c; return tmp_E_unscaled; }
//Напишите функцию, которая //называется PalindromFilter, //возвращает vector<string>, //принимает vector<string> words и int min_length, //возвращает из вектора words все строки - палиндромы длиной не меньше min_length. // //Примеры //WORDS/min_length РЕЗУЛЬТАТ //abacaba, aba //5 abacaba //abacaba, aba //2 abacaba, aba //weew, bro, code //4 weew #include <iostream> #include <string> #include <vector> using namespace std; bool IsPalindrom(string s) { // является ли строка s палиндромом bool rez = false; string s_rev = ""; for (int i = s.size() - 1; i >= 0; i--) { s_rev = s_rev + s[i]; } if (s == s_rev) { rez = true; } else rez = false; return rez; } vector<string> SplitIntoWords(string text) { vector<string> words; string word; for (int i = 0; i < text.size(); ++i) { if (text[i] == ',') { words.push_back(word); word = ""s; } else if (text[i] == ' ') { continue; } else { word += text[i]; } } words.push_back(word); return words; } vector<string> PalindromFilter(vector<string> words, int min_length) { // формируем и возвращаем вектор подходящих палиндромов vector<string> rez; for (auto now : words) { if (IsPalindrom(now) && size(now) >= min_length) { rez.push_back(now); } } return rez; } int main() { string query; int min_length; getline(cin, query); cin >> min_length; vector<string> v_words = SplitIntoWords(query); vector<string> v_palindrom = PalindromFilter(v_words, min_length); for (string word : v_palindrom) { cout << word << endl; } return 0; }
// // EPITECH PROJECT, 2018 // nanotekspice // File description: // simulate chipsets // #include "../include/AComponent.hpp" std::map<std::string,std::function<std::unique_ptr<nts::IComponent> *(const std::string &value)> > nts::AComponent::_funcs; nts::AComponent::AComponent() { _funcs.insert(std::make_pair("input", std::bind(&nts::AComponent::createInput, this, std::placeholders::_1))); _funcs.insert(std::make_pair("output", std::bind(&nts::AComponent::createOutput, this, std::placeholders::_1))); _funcs.insert(std::make_pair("4081", std::bind(&nts::AComponent::create4081, this, std::placeholders::_1))); _funcs.insert(std::make_pair("4001", std::bind(&nts::AComponent::create4001, this, std::placeholders::_1))); _funcs.insert(std::make_pair("4011", std::bind(&nts::AComponent::create4011, this, std::placeholders::_1))); _funcs.insert(std::make_pair("4030", std::bind(&nts::AComponent::create4030, this, std::placeholders::_1))); _funcs.insert(std::make_pair("4069", std::bind(&nts::AComponent::create4069, this, std::placeholders::_1))); _funcs.insert(std::make_pair("4071", std::bind(&nts::AComponent::create4071, this, std::placeholders::_1))); } nts::AComponent::~AComponent() {} std::unique_ptr<nts::IComponent> *nts::AComponent::createInput(const std::string &value) const { return new std::unique_ptr<nts::IComponent>(new nts::Input(value)); } std::unique_ptr<nts::IComponent> *nts::AComponent::createOutput(const std::string &value) const { return new std::unique_ptr<nts::IComponent>(new nts::Input(value)); } std::unique_ptr<nts::IComponent> *nts::AComponent::create4081(const std::string &value) const { return new std::unique_ptr<nts::IComponent>(new nts::C4081(value)); } std::unique_ptr<nts::IComponent> *nts::AComponent::create4001(const std::string &value) const { return new std::unique_ptr<nts::IComponent>(new nts::C4001(value)); } std::unique_ptr<nts::IComponent> *nts::AComponent::create4011(const std::string &value) const { return new std::unique_ptr<nts::IComponent>(new nts::C4011(value)); } std::unique_ptr<nts::IComponent> *nts::AComponent::create4030(const std::string &value) const { return new std::unique_ptr<nts::IComponent>(new nts::C4030(value)); } std::unique_ptr<nts::IComponent> *nts::AComponent::create4069(const std::string &value) const { return new std::unique_ptr<nts::IComponent>(new nts::C4069(value)); } std::unique_ptr<nts::IComponent> *nts::AComponent::create4071(const std::string &value) const { return new std::unique_ptr<nts::IComponent>(new nts::C4071(value)); } std::unique_ptr<nts::IComponent> *nts::AComponent::createComponent(const std::string &type, const std::string &value) { _funcs[type](value); }
#ifndef CONTROLWIDGET_H #define CONTROLWIDGET_H #include <QWidget> #include <QPushButton> #include <QHBoxLayout> #include <QVBoxLayout> #include <QGridLayout> #include <QLabel> #include <QLineEdit> class ControlWidget : public QWidget { Q_OBJECT public: explicit ControlWidget(int width, QWidget *parent = 0); void setProperties(double x, double y, int iter, double zoom, double zoomFactor); QPushButton *buttonUpdate; QPushButton *buttonZoomIn; QPushButton *buttonZoomOut; QPushButton *buttonHelp; private: QLabel *labelX; QLabel *labelY; QLabel *labelIter; QLabel *labelZoom; QLabel *labelZoomFactor; QLineEdit *editX; QLineEdit *editY; QLineEdit *editIter; QLineEdit *editZoom; QLineEdit *editZoomFactor; QGridLayout *mainLayout; signals: void updateClicked(double x, double y, double range, int maxIter, double zoom); public slots: void onPositionChange(QPointF pos, double range); }; #endif // CONTROLWIDGET_H
#include <bits/stdc++.h> using namespace std; int main(){ int h, w; cin >> h >> w; vector<string> m(h); for(int i=0; i<h; i++) cin >> m[i]; for(int i=0; i<h; i++){ for(int j=0; j<w; j++){ if(m[i][j] == '.'){ int cnt = 0; for(int x=-1; x<=1; x++){ for(int y=-1; y<=1; y++){ if(0<=y+i && y+i<h && 0<=x+j && x+j<w && m[i+y][j+x] == '#') cnt++; } } cout << cnt; } else{ cout << "#"; } } cout << endl; } return 0; }
#include <iostream> #include "entity.h" Entity::Entity(QVector<Mesh *> meshes, const QVector3D &position, btRigidBody* rigidBody) : meshes(std::move(meshes)), position(position), rigidBody(rigidBody) { } QVector<Mesh *> Entity::getMeshes() const { return meshes; } QVector3D Entity::getPosition() const { return position; } QMatrix4x4 Entity::getModelMatrix() { QMatrix4x4 modelMatrix = QMatrix4x4(); btVector3 rbPosition = rigidBody->getWorldTransform().getOrigin(); btQuaternion rbRotation = rigidBody->getWorldTransform().getRotation(); QVector3D position(rbPosition.x(), rbPosition.y(), rbPosition.z()); QQuaternion rotation(rbRotation.w(), rbRotation.x(), rbRotation.y(), rbRotation.z()); modelMatrix.translate(position); modelMatrix.rotate(rotation); modelMatrix.scale(scale); return modelMatrix; } QQuaternion Entity::getRotation() const { return rotation; } void Entity::setRotation(const QQuaternion &rotation) { this->rotation = rotation; } void Entity::setPosition(const QVector3D &position) { this->position = position; } void Entity::setScale(const float &scale) { this->scale = scale; } float Entity::getScale() const { return scale; } btRigidBody *Entity::getRigidBody() const { return rigidBody; } void Entity::setRigidBody(btRigidBody *rigidBody) { Entity::rigidBody = rigidBody; } btVector3 Entity::getBtPosition() { return btVector3({position.x()}, {position.y()}, {position.z()}); } btQuaternion Entity::getBtRotation() { return {rotation.x(), rotation.y(), rotation.z(), rotation.scalar()}; }
#include "GameObject.h" #include <DxLib.h> #include "Reference.h" #include "misc\Func.h" int GameObject::resolution; void GameObject::setResolution(int r) { resolution = r; } GameObject::GameObject(Vector2 position) : Object(position), hitRange(0.0F), count(0), minCount(-1), dispRange(10.0F) { } void GameObject::Init() { flag = true; count = 0; } void GameObject::Fin() { flag = false; } void GameObject::Update() { Object::Update(); if (!flag) { return; } if (minCount != -1 && count > minCount) { if (position.x < -dispRange || position.y < -dispRange || position.x > Ref::FLD_W + dispRange || position.y > Ref::FLD_H + dispRange) { Fin(); } } count++; } void GameObject::Draw() const { Object::Draw(); } void GameObject::Draw(Vector2 position, string tag) const { Func::DrawRotaGraphFWithRate(position.x + 16 + 8 * resolution, position.y + 16 + 8 * resolution, 1.0, 0.0, Image::Instance()->getImage(tag), TRUE); } void GameObject::CheckCollision(vector<GameObject*> objs) { if (hitRange <= 0.0F) { return; } for (unsigned i = 0; i < objs.size(); i++) { Vector2 pos = objs[i]->position; if ((pos.y - position.y) * (pos.y - position.y) + (pos.x - position.x) * (pos.x - position.x) < (objs[i]->hitRange - this->hitRange) * (objs[i]->hitRange - this->hitRange)) { this->OnCollide(objs[i]); } } } Vector2 GameObject::GetPosition() const { return position; }
#include<bits/stdc++.h> using namespace std; vector<int> e[100]; string s[100],val[100]; int siz[100],f[100],t,n,minf,ans; inline void ins(int u,int v){ e[u].push_back(v); e[v].push_back(u); } void readit(){ scanf("%d",&n); for (int i=1;i<=n;i++) e[i].clear(); for (int i=1;i<=n;i++){ int x; scanf("%d",&x); if (x) ins(i,x); } } void writeit(){ printf("%d\n",ans); } void findroot(int u,int fa){ siz[u]=1; f[u]=0; for (int i=0;i<e[u].size();i++){ int v=e[u][i]; if (v!=fa){ findroot(v,u); siz[u]+=siz[v]; f[u]=max(f[u],siz[v]); } } f[u]=max(f[u],n-siz[u]); minf=min(minf,f[u]); } void dfs(int u,int fa){ string son[100]; int tot=0; s[u]="("; for (int i=0;i<e[u].size();i++){ int v=e[u][i]; if (v!=fa){ dfs(v,u); son[tot++]=s[v]; } } sort(son,son+tot); for (int i=0;i<tot;i++) s[u]+=son[i]; s[u]+=")"; } void work(int t){ minf=n; findroot(1,0); for (int i=1;i<=n;i++) if (f[i]==minf){ dfs(i,0); val[t]=max(val[t],s[i]); } for (int i=1;i<=t;i++) if (val[t]==val[i]){ ans=i; break; } } int main(){ scanf("%d",&t); for (int i=1;i<=t;i++){ readit(); work(i); writeit(); } return 0; }
#ifndef VNAFILESYSTEM_H #define VNAFILESYSTEM_H #include "Definitions.h" #include <QObject> #include <QScopedPointer> namespace RsaToolbox { class Vna; class VnaFileSystem : public QObject { Q_OBJECT public: enum Directory { DEFAULT_DIRECTORY, EMBED_DIRECTORY, DEEMBED_DIRECTORY, CAL_GROUP_DIRECTORY, CAL_KIT_DIRECTORY, EXTERNAL_TOOLS_DIRECTORY, RECALL_SETS_DIRECTORY, TRACES_DIRECTORY }; explicit VnaFileSystem(QObject *parent = 0); VnaFileSystem(VnaFileSystem &other); VnaFileSystem(Vna *_vna, QObject *parent = 0); ~VnaFileSystem(); bool isFile(QString pathName); bool isNotFile(QString pathName); bool isDirectory(QString pathName); bool isNotDirectory(QString pathName); bool isFreeSpace(quint64 bytes); bool isFreeSpace(QString path, quint64 bytes); QStringList files(); QStringList files(QString path); QStringList directories(); QStringList directories(QString path); quint64 freeSpace_Bytes(); quint64 freeSpace_Bytes(QString path); uint fileSize_Bytes(QString pathName); QString directory(); QString directory(Directory directory); void changeDirectory(QString path); void changeDirectory(Directory directory); void createDirectory(QString pathName); void moveFile(QString sourcePathName, QString destinationPathName); void copyFile(QString sourcePathName, QString destinationPathName); void deleteFile(QString pathName); void deleteFiles(QStringList pathNames); void deleteFiles(QString path); void deleteFiles(); void deleteDirectory(QString pathName); void uploadFile(QString sourcePathName, QString destinationPathName); void uploadFile(QString sourcePathName, QString destinationFilename, Directory destinationDirectory); void downloadFile(QString sourcePathName, QString destinationPathName); void downloadFile(QString sourcePathName, QString destinationPathName, uint bufferSize_B); void downloadFile(QString sourceFilename, Directory sourceDirectory, QString destinationPathName); void downloadFile(QString sourceFilename, Directory sourceDirectory, QString destinationPathName, uint bufferSize_B); void operator=(VnaFileSystem const &other); private: Vna *_vna; QScopedPointer<Vna> placeholder; QString dir(); void dir(quint64 &totalFileSize_B, quint64 &freeSpace_B, QStringList &files, QVector<uint> &fileSizes_B, QStringList &directories); }; } Q_DECLARE_METATYPE(RsaToolbox::VnaFileSystem::Directory) #endif // VNAFILESYSTEM_H
#include "precompiled.h" #include "interface/pos.h" #include "interface/interface.h" #include "render/render.h" #include "render/dx.h" #include "render/font.h" #include "game/game.h" #include "game/player.h" using namespace ui; Pos::Pos() { d3dfont = NULL; draw = 0; } Pos::~Pos() { delete d3dfont; } void Pos::reset() { delete d3dfont; d3dfont = NULL; } void Pos::render() { if (!draw) return; char buf[256]; if (d3dfont == NULL) { d3dfont = new CD3DFont("Terminal", 8); d3dfont->InitDeviceObjects(render::device); d3dfont->RestoreDeviceObjects(); } sprintf(buf, "pos x: %.2f y: %.2f z: %.2f", game::player->pos.x, game::player->pos.y, game::player->pos.z); d3dfont->DrawText((float)xpos, (float)ypos, D3DCOLOR_XRGB(255, 255, 255), buf); sprintf(buf, "rot x: %.2f y: %.2f z: %.2f", game::player->rot.x, game::player->rot.y, game::player->rot.z); d3dfont->DrawText((float)xpos, (float)ypos + 10, D3DCOLOR_XRGB(255, 255, 255), buf); sprintf(buf, "vel x: %.2f y: %.2f z: %.2f", game::player->vel.x, game::player->vel.y, game::player->vel.z); d3dfont->DrawText((float)xpos, (float)ypos + 20, D3DCOLOR_XRGB(255, 255, 255), buf); sprintf(buf, "clusters: %i faces: %i", render::frame_clusters, render::frame_faces); d3dfont->DrawText((float)xpos, (float)ypos + 30, D3DCOLOR_XRGB(255, 255, 255), buf); sprintf(buf, "polys: %i texswaps: %i bufswaps: %i", render::frame_polys, render::frame_texswaps, render::frame_bufswaps); d3dfont->DrawText((float)xpos, (float)ypos + 40, D3DCOLOR_XRGB(255, 255, 255), buf); sprintf(buf, "DIP calls: %i", render::frame_drawcalls); d3dfont->DrawText((float)xpos, (float)ypos + 50, D3DCOLOR_XRGB(255, 255, 255), buf); }
#include "DwriteCairo.h" #include <dwrite.h> #include "DebugUtility.h" HRESULT __stdcall DwriteCairoCreateTextRender( _In_ REFIID iid, _COM_Outptr_ IUnknown **textRender ) { if (textRender == nullptr) return E_POINTER; DebugAssert(iid == IDirectWriteCairoTextRenderer::IID_IDirectWriteCairoTextRenderer, "IID must be GUID of IDirectWriteCairoTextRenderer"); *textRender = new IDirectWriteCairoTextRenderer(); return S_OK; }
#include "QueueTp.h" #include "Worker.h" #include <iostream> #include <cstring> const int SIZE = 5; int main() { using std::cin; using std::cout; using std::endl; using std::strchr; Queue<Worker*> workerQueue(SIZE); for (int i = 0; i < SIZE; ++i) { cout << "Enter the employee category:\nw:waiter\ts:singer\tt:singing waiter\tq:quit\n"; char choice; cin >> choice; while (strchr("wstq", choice) == NULL) { cout << "Please enter w, s, t, q: "; cin >> choice; } if (choice == 'q') break; Worker* temp=nullptr; switch (choice) { case 'w': temp = new Waiter; break; case 's': temp = new Singer; break; case 't': temp = new SingingWaiter; break; } cin.get(); temp->Set(); workerQueue.enqueue(temp); } Worker* temp; cout << endl << "Here is your staff:\n"; while (workerQueue.dequeue(temp)) { temp->Show(); cout << endl; delete temp; } cout << "Bye.\n"; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * 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. * * @author Arjan van Leeuwen (arjanl) */ #include "core/pch.h" #include "adjunct/quick_toolkit/contexts/UiContext.h" UiContext::~UiContext() { ReleaseFocus(); g_main_message_handler->UnsetCallBacks(this); } void UiContext::AddChildContext(UiContext* child) { child->SetParentInputContext(this); child->Into(&m_children); // Listen to messages from children g_main_message_handler->SetCallBack(this, MSG_QUICKTK_CLOSE_CONTEXT, reinterpret_cast<MH_PARAM_1>(child)); } BOOL UiContext::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { case OpInputAction::ACTION_LOWLEVEL_PREFILTER_ACTION: return CancelsAction(action->GetChildAction()); case OpInputAction::ACTION_GET_ACTION_STATE: return OnActionGetState(action->GetChildAction()); } BOOL handled = FALSE; if (CanHandleAction(action) && !DisablesAction(action)) handled = OpStatus::IsSuccess(HandleAction(action)); return handled; } void UiContext::OnUiClosing() { // Send message to close context to parent g_main_message_handler->PostMessage(MSG_QUICKTK_CLOSE_CONTEXT, reinterpret_cast<MH_PARAM_1>(this), 0); } BOOL UiContext::OnActionGetState(OpInputAction* action) { if (CanHandleAction(action)) { action->SetEnabled(!DisablesAction(action)); action->SetSelected(SelectsAction(action)); return TRUE; } return FALSE; } void UiContext::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { // Handle close message from children if (msg != MSG_QUICKTK_CLOSE_CONTEXT) return; g_main_message_handler->RemoveCallBacks(this, par1); UiContext* to_close = reinterpret_cast<UiContext*>(par1); OP_ASSERT(m_children.HasLink(to_close) || !"Deleting a context that's not owned by us"); to_close->Out(); OP_DELETE(to_close); }
#ifndef __DF40940SDVCV__DFNIDS_HPP__ #define __DF40940SDVCV__DFNIDS_HPP__ #include <string> #include <iostream> namespace g9898fvc909gg_e { namespace fgbcxh4g43xvc { std::string df40940sdvcv__dfnids(const std::string& flxfbdfb4364b_e4vx); } } namespace g9898fvc909gg_e { namespace fgbcxn4g43xvc { std::string df40940sdvcv__dfnids(const std::string& flxfbdfb4364b_e4vx); } } #endif
#ifndef DRAWMAP #define DRAWMAP #include "glut.h" class DrawMap { public: static DrawMap* Instance(); void drawMap(); private: DrawMap() { } virtual ~DrawMap() { } }; #endif
#include <Arduino.h> /* This code will fetch the latest data from your antares project device. Your Antares project device must have a structure like this: (Note that nesting the JSON object can only be done up to 2 levels using this library) { "temperature": some-integer, "humidity": some-integer, "wind_speed": some-float, "rain_level": some-float, "location" : { "latitude": "static-string", "longitude": "static-string" } } For more information please visit https://antares.id/id/docs.html */ #define LED D5 #define fan D4 #define Pump D6 int ledState; int pumpState; int fanState; float limitTemp; float limitMoist; #include "AntaresESP8266HTTP.h" #define ACCESSKEY "017c7e810b75e05b:0932f32db0c81348" #define WIFISSID "TP-LINK 2" #define PASSWORD "asdf1234" #define projectName "antaresChallenge" #define deviceName "actuatorState" AntaresESP8266HTTP antares(ACCESSKEY); void setup() { Serial.begin(9600); antares.setDebug(true); antares.wifiConnection(WIFISSID,PASSWORD); pinMode(LED,OUTPUT); pinMode(Pump,OUTPUT); pinMode(fan,OUTPUT); } void loop() { antares.get(projectName, deviceName); // Store latest value in buffer /* Uncomment the line below to use HTTP instead of HTTPS. Will be faster, but less secure */ // antares.getNonSecure(projectName, deviceName); // Check if we're actually getting data if(antares.getSuccess()) { // Get each values ledState = antares.getInt("LED"); fanState = antares.getInt("Fan"); pumpState = antares.getInt("Pump"); limitTemp = antares.getFloat("limitTemp"); limitMoist = antares.getFloat("limitMoisture"); // Print each values } Serial.println("LED State: " + String(ledState)); Serial.println("Fan State: " + String(fanState)); Serial.println("Pump State: " + String(pumpState)); Serial.println("Limit Temp: " + String(limitTemp)); Serial.println("Limit Moist: " + String(limitMoist)); if(ledState==1){ digitalWrite(LED,HIGH); } else{ digitalWrite(LED,LOW); } if(fanState==1){ if(limitTemp>60){ digitalWrite(fan,HIGH); yield(); } } else{ digitalWrite(fan,LOW); } if(pumpState==1){ if(limitMoist<90) { digitalWrite(Pump,HIGH); } } else{ digitalWrite(Pump,LOW); } delay(5000); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; #define max(a,b) ((a>b)?a:b) const int inf = 1e9 + 7; const int maxn = 1e6 + 10; int f[maxn][2],g[maxn][2]; int a[maxn]; int main() { int n,m; int now,la; while (scanf("%d%d",&m,&n) != EOF) { memset(f,0,sizeof(f)); memset(g,0,sizeof(g)); for (int i = 1;i <= n; i++) scanf("%d",&a[i]); for (int j = 1;j <= m; j++) { now = j&1,la = 1 - now; f[j-1][now] = g[j-1][now] = -inf; for (int i = j;i <= n; i++) { f[i][now] = max(f[i-1][now],max(f[i-1][la],g[i-1][la]))+a[i]; g[i][now] = max(f[i-1][now],g[i-1][now]); //cout << f[i][now] << ":" << g[i][now] << endl; } } printf("%d\n",max(f[n][m&1],g[n][m&1])); } return 0; }
#include<iostream> #include<bits/stdc++.h> using namespace std; //count distinct elements in union of two arrays //IDEA: copy both arrays in hashset and return hashset's size int count(int a[],int n,int b[],int m){ unordered_set<int> u; u.insert(a,a+n); u.insert(b,b+m); return u.size(); } int main(int argc, char const *argv[]) { int a[]={15,20,5,15}; int b[]={15,15,15,10,20,15}; int n=sizeof(a)/sizeof(a[0]); int m=sizeof(b)/sizeof(b[0]); cout<<": "<<count(a,n,b,m); return 0; }
#include "gtest/gtest.h" #include "opennwa/Nwa.hpp" #include "opennwa/query/language.hpp" #include "opennwa/construct/union.hpp" #include "opennwa/query/automaton.hpp" #include "opennwa/query/language.hpp" #include "Tests/unit-tests/Source/opennwa/fixtures.hpp" #include "Tests/unit-tests/Source/opennwa/int-client-info.hpp" #include "Tests/unit-tests/Source/opennwa/class-NWA/supporting.hpp" using namespace opennwa; #define NUM_ELEMENTS(array) (sizeof(array)/sizeof((array)[0])) static const Nwa empty, balanced = AcceptsBalancedOnly().nwa, strict_left = AcceptsStrictlyUnbalancedLeft().nwa, maybe_left = AcceptsPossiblyUnbalancedLeft().nwa, strict_right = AcceptsStrictlyUnbalancedRight().nwa, maybe_right = AcceptsPossiblyUnbalancedRight().nwa, maybe_full = AcceptsPositionallyConsistentString().nwa; // WARNING: the order of these words must be consistent with the row & column // order in the table 'expected_answers' below. static Nwa const nwas[] = { empty, balanced, strict_left, maybe_left, strict_right, maybe_right, maybe_full }; static const unsigned num_nwas = NUM_ELEMENTS(nwas); // WARNING: the order of the rows and columns in this table must be // consistent with the order of 'nwas' above. // // "What is the union of the row and column?" static const Nwa * const expected_answers[][num_nwas] = { /* empty balanced strict left maybe left strict right maybe right maybe full */ /* empty */ { &empty, &balanced, &strict_left, &maybe_left, &strict_right, &maybe_right, &maybe_full }, /* balanced */ { &balanced, &balanced, &maybe_left, &maybe_left, &maybe_right, &maybe_right, &maybe_full }, /* strict left */ { &strict_left, &maybe_left, &strict_left, &maybe_left, NULL, &maybe_full, &maybe_full }, /* maybe left */ { &maybe_left, &maybe_left, &maybe_left, &maybe_left, &maybe_full, &maybe_full, &maybe_full }, /* strict right */ { &strict_right, &maybe_right, NULL, &maybe_full, &strict_right, &maybe_right, &maybe_full }, /* maybe right */ { &maybe_right, &maybe_right, &maybe_full, &maybe_full, &maybe_right, &maybe_right, &maybe_full }, /* maybe full */ { &maybe_full, &maybe_full, &maybe_full, &maybe_full, &maybe_full, &maybe_full, &maybe_full } }; namespace opennwa { namespace construct { TEST(opennwa$construct$$union, testBatteryOfVariouslyBalancedNwas) { for (unsigned left = 0 ; left < num_nwas ; ++left) { for (unsigned right = 0 ; right < num_nwas ; ++right) { std::stringstream ss; ss << "Testing NWA " << left << " union " << right; SCOPED_TRACE(ss.str()); Nwa const * expected_answer = expected_answers[left][right]; // First, make sure that we expect an answer // (i.e. it's not no_answer). if (expected_answer && left != right) { NwaRefPtr u = unionNwa(nwas[left], nwas[right]); EXPECT_TRUE(query::languageEquals(*expected_answer, *u)); } } // for right } // for left } TEST(opennwa$construct$$union, resultingAutomatonIsNondeterministic) { Nwa left, right; left.addInitialState(getKey("s")); right.addInitialState(getKey("t")); NwaRefPtr u = unionNwa(left, right); EXPECT_FALSE(query::isDeterministic(*u)); } TEST(opennwa$construct$$union, unionWithEmptyIsNoop) { OddNumEvenGroupsNwa fixture; Nwa empty; NwaRefPtr u = unionNwa(fixture.nwa, empty); EXPECT_EQ(fixture.nwa, *u); u = unionNwa(empty, empty); EXPECT_EQ(empty, empty); } TEST(opennwa$construct$$union$$DeathTest, overlappingStatesTriggerAssertionViolation) { Nwa nwa; nwa.addState(getKey("s")); EXPECT_DEATH({ NwaRefPtr u = unionNwa(nwa, nwa); }, "statesOverlap"); } TEST(opennwa$construct$$union, unionCopiesClientInfo) { AcceptsBalancedOnly bal; Nwa nwa; SomeElements e; e.add_to_nwa(&nwa); ClientInfoRefPtr ci1 = new IntClientInfo(1); ClientInfoRefPtr ci2 = new IntClientInfo(2); bal.nwa.setClientInfo(bal.q0, ci1); nwa.setClientInfo(e.state, ci2); NwaRefPtr u = unionNwa(bal.nwa, nwa); #define EXPECT_CLIENT_INFO_IS(expect, nwa, state) \ do { \ ClientInfo * ci = (nwa).getClientInfo(state).get_ptr(); \ IntClientInfo * ici = dynamic_cast<IntClientInfo *>(ci); \ ASSERT_TRUE(ici != NULL); \ EXPECT_EQ(expect, ici->n); \ } while (0) EXPECT_CLIENT_INFO_IS(1, *u, bal.q0); EXPECT_CLIENT_INFO_IS(2, *u, e.state); #undef EXPECT_CLIENT_INFO_IS EXPECT_NE(ci1, u->getClientInfo(bal.q0)); EXPECT_NE(ci2, u->getClientInfo(e.state)); } } }
//#include "stdafx.h" #include <iostream> #include <fstream> #include <string> //#include <dos.h> #include "Lexer.h" using namespace std; ifstream inFile("input.go"); string Lexer::readString() { string app; if (inFile.fail()) { cerr << "Unable to open file for reading." << endl; exit(1); } if (inFile.is_open()) { char c; inFile.get(c); if ((c == '\r') || (c == '\n')) { inFile.get(c); } while ((c != ' ')&&(c != '\n')){ app.append(1, c); inFile.get(c); } //used if you want to print out the .go file /*if (c == ' ') { cout << c; }*/ if (inFile.eof()) { return("EOF"); } //used if you want to print out the .go file //cout << app; return(app); } }
#define SPLITTERS 8 // nombre de délimiteurs MAX pris en compte String Subs[SPLITTERS]; int SplitIndex[SPLITTERS]; void String_Split(char Splitter, String _string) { int i; int Index=0; int Nsubs; for(i=0; i<SPLITTERS; i++) { SplitIndex[i]=_string.indexOf(Splitter,Index); Index=SplitIndex[i]+1; if(!Index) break; } Nsubs=i+1; Index=-1; for(i=0; i<Nsubs; i++) { Subs[i]= _string.substring(Index+1,SplitIndex[i]); /* Serial.print("Sub "); Serial.print(i); Serial.print(": "); Serial.println(Subs[i]);*/ Index=SplitIndex[i]; } for(i=0; i<SPLITTERS; i++) { SplitIndex[i]=-1; } }
#ifndef UTILS_HH_ # define UTILS_HH_ // #include <gtk/gtk.h> // // #include <string> #include <vector> #include <iostream> #include <deque> #include <list> #include "WoZ.hh" using namespace std; void add_toolTips (GtkWidget *w, const char* s); void display_infoTab (); string d2s(double n); string i2s(int n); void clear_widget (GtkWidget *w); std::vector<string> tokenize (string s); void clear_widget_on_switch_page (GtkNotebook *notebook, GtkNotebookPage *page, guint page_num, gpointer user_data); GtkWidget* display_history_record (const history_record h); const std::string currentDateTime(); const std::string DoubleTofFormatedDate(double date); #endif //UTILS_HH_
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2015 Steven Lovegrove * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <pangolin/gl/gltext.h> #include <cstdio> #include <cstdarg> namespace pangolin { class PANGOLIN_EXPORT GlFont { public: // Singleton instance if requested. static GlFont& I(); // Load GL Font data. Delay uploading as texture until first use. GlFont(const unsigned char* ttf_buffer, float pixel_height, int tex_w=512, int tex_h=512); GlFont(const std::string& filename, float pixel_height, int tex_w=512, int tex_h=512); virtual ~GlFont(); // Generate renderable GlText object from this font. GlText Text( const char* fmt, ... ); GlText Text( const std::string& str ); inline float Height() const { return font_height_px; } protected: void InitialiseFont(const unsigned char* ttf_buffer, float pixel_height, int tex_w, int tex_h); // This can only be called once GL context is initialised void InitialiseGlTexture(); const static int FIRST_CHAR = 32; const static int NUM_CHARS = 96; float font_height_px; int tex_w; int tex_h; unsigned char* font_bitmap; GlTexture mTex; GlChar chardata[NUM_CHARS]; GLfloat kern_table[NUM_CHARS*NUM_CHARS]; }; }
#include <ros/ros.h> int main(int argc, char **argv) { ros::init(argc, argv, "log"); ros::NodeHandle nh; ros::Rate loopRate(10.0); for (auto i = 1; ros::ok(); ++i, loopRate.sleep()) { ROS_DEBUG_STREAM("Counted to " << i); auto mod = 3; if (i % mod == 0) { ROS_INFO_STREAM(i << " is divisible by " << mod); } mod = 5; if (i % mod == 0) { ROS_WARN_STREAM(i << " is divisible by " << mod); } mod = 10; if (i % mod == 0) { ROS_ERROR_STREAM(i << " is divisible by " << mod); } mod = 20; if (i % mod == 0) { ROS_FATAL_STREAM(i << " is divisible by " << mod); } } }
#include<bits/stdc++.h> using namespace std; #define PI 3.1415926535897932 int main(){ char message[256]; printf("%d\n",strlen(message)); //先頭をヌル文字に message[0] = '\0'; printf("message[] = %s\n",message); printf("message len = %d\n",strlen(message)); //copy strcpy(x, y); -> x = y; strcpy(message, "Hello"); printf("message[] = %s\n",message); printf("message len = %d\n",strlen(message)); //+=y strcat(x, y); -> x += y; strcat(message, ", "); printf("message[] = %s\n",message); printf("message len = %d\n",strlen(message)); //らしいけどうまく動かないので使うのは避けるか、かなり慎重に動確してから //copy y[:i] strncpy x = y[:i];?? //文字列 y の先頭 n 文字分を、文字列 x に保存する //char dummy[] = "Hello, World!!!!"; //strncpy(message, dummy, 4); //printf("message[] = %s\n",message); //printf("message len = %d\n",strlen(message)); // //+= y[:i] strncat x+= y[:i]; //文字列 x の内容に文字列 y の先頭 n 文字分を追加したものを、文字列 x に保存する //humei; return 0; }
/* BEGIN LICENSE */ /***************************************************************************** * SKCore : the SK core library * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: integerlist.h,v 1.5.4.3 2005/02/17 15:29:20 krys Exp $ * * Authors: Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #ifndef __SKC_INTEGERLIST_H_ #define __SKC_INTEGERLIST_H_ class SKAPI SKIntegerList : public SKFile { public: SK_REFCOUNT_INTF_DEFAULT(SKIntegerList) SKIntegerList(); ~SKIntegerList(); SKERR SetFileName(const char *pszFileName, const char *pszDefaultFileName = NULL); SKERR SetListFromArray(const PRUint32 *piArray, PRUint32 iSize, PRBool bDuplicate); SKERR SetListFromUTF8String(const char *pszString); SKERR IsPresent(PRUint32 iValue, PRBool *pbResult); SKERR FormatToAsciiString(char** ppcResult); SKERR SetListFromAsciiString(const char* pcString); private: PRUint32 m_iSize; const PRUint32 *m_pIntegerList; PRBool m_bOwner; PRUint32 *m_piUCS4Data; PRBool m_bInitialized; }; #else // __SKC_INTEGERLIST_H_ #error "Multiple inclusions of integerlist.h" #endif // __SKC_INTEGERLIST_H_
/* * 判断两个有环单链表是否相交,并且可求出相交节点 */ #include <bits/stdc++.h> struct ListNode{ int data; ListNode *next; ListNode(int x):data(x),next(NULL){} }; class Solution{ public: bool list_judge_two_joined_hasCircle(ListNode *head1,ListNode *head2){ if(head1 == NULL || head2 == NULL){ return false; } ListNode *loopStartNode1 = getLoopNode(head1); ListNode *loopStartNode2 = getLoopNode(head2); if(loopStartNode1 == NULL || loopStartNode2 == NULL){ return false; } if(loopStartNode1 == loopStartNode2){ return true; }else{ //由第一个循环节点的下一个节点开始遍历,若遍历到第二个循环节点则返回true ListNode *temp = loopStartNode1->next; while(temp != loopStartNode1){ if(temp == loopStartNode2){ return true; } temp = temp->next; } } return false; } ListNode* getLoopNode(ListNode *head){ ListNode *fast = head->next->next; ListNode *slow = head->next; while(fast != NULL && fast ->next != NULL && fast != slow){ fast = fast->next->next; slow = slow->next; } if(fast == slow){ fast = head; while(fast != slow){ fast = fast->next; slow = slow->next; } return fast; } return NULL; } }; int main(){ return 0; }
// // Created by jakub on 31.10.18. // #ifndef ESP32ACTUATOR_NVS_H #define ESP32ACTUATOR_NVS_H #include <nvs_flash.h> #include <nvs.h> #include <esp_system.h> #include "TempSensor/TempSensor.h" #include "Actuator/Actuator.h" namespace Nvs{ static nvs_handle my_handle; static esp_err_t err; static int32_t speed; static int32_t temp; static void begin() { err = nvs_flash_init(); if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_INVALID_VERSION) { // NVS partition was truncated and needs to be erased // Retry nvs_flash_init ESP_ERROR_CHECK(nvs_flash_erase()); err = nvs_flash_init(); } ESP_ERROR_CHECK(err); // Open printf("\n"); printf("Opening Non-Volatile Storage (NVS) handle... "); err = nvs_open("storage", NVS_READWRITE, &my_handle); if (err != ESP_OK) { printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err)); } else { printf("Done\n"); // Read printf("Reading vals from NVS ... "); err = nvs_get_i32(my_handle, "temp", &temp); switch (err) { case ESP_OK: printf("Done\n"); printf("temp = %d\n", temp); TempSensor::targetTemp = ((double)temp)/100; break; case ESP_ERR_NVS_NOT_FOUND: printf("The value is not initialized yet!\n"); break; default : printf("Error (%s) reading!\n", esp_err_to_name(err)); } err = nvs_get_i32(my_handle, "speed", &speed); switch (err) { case ESP_OK: printf("Done\n"); printf("speed = %d\n", speed); Actuator::setSpeed(speed); break; case ESP_ERR_NVS_NOT_FOUND: printf("The value is not initialized yet!\n"); break; default : printf("Error (%s) reading!\n", esp_err_to_name(err)); } } } static void save(uint32_t a){ printf("Updating speed in NVS ... "); err = nvs_set_i32(my_handle, "speed", a); printf((err != ESP_OK) ? "Failed!\n" : "Done\n"); // Commit written value. // After setting any values, nvs_commit() must be called to ensure changes are written // to flash storage. Implementations may write to storage at other times, // but this is not guaranteed. printf("Committing updates in NVS ... "); err = nvs_commit(my_handle); printf((err != ESP_OK) ? "Failed!\n" : "Done\n"); } static void save(double a) { printf("Updating speed in NVS ... "); err = nvs_set_i32(my_handle, "temp", ((int32_t )(a*100))); printf((err != ESP_OK) ? "Failed!\n" : "Done\n"); // Commit written value. // After setting any values, nvs_commit() must be called to ensure changes are written // to flash storage. Implementations may write to storage at other times, // but this is not guaranteed. printf("Committing updates in NVS ... "); err = nvs_commit(my_handle); printf((err != ESP_OK) ? "Failed!\n" : "Done\n"); } } #endif //ESP32ACTUATOR_NVS_H
// Created on: 1992-05-06 // Created by: Jacques GOUSSARD // Copyright (c) 1992-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 _IntPatch_TheSOnBounds_HeaderFile #define _IntPatch_TheSOnBounds_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <IntPatch_SequenceOfSegmentOfTheSOnBounds.hxx> #include <IntPatch_SequenceOfPathPointOfTheSOnBounds.hxx> #include <Standard_Integer.hxx> class StdFail_NotDone; class Standard_OutOfRange; class Standard_ConstructionError; class Adaptor3d_HVertex; class IntPatch_HCurve2dTool; class IntPatch_HInterTool; class Adaptor3d_TopolTool; class IntPatch_ArcFunction; class IntPatch_ThePathPointOfTheSOnBounds; class IntPatch_TheSegmentOfTheSOnBounds; class IntPatch_TheSOnBounds { public: DEFINE_STANDARD_ALLOC //! Empty constructor. Standard_EXPORT IntPatch_TheSOnBounds(); //! Algorithm to find the points and parts of curves of Domain //! (domain of of restriction of a surface) which verify //! F = 0. //! TolBoundary defines if a curve is on Q. //! TolTangency defines if a point is on Q. Standard_EXPORT void Perform (IntPatch_ArcFunction& F, const Handle(Adaptor3d_TopolTool)& Domain, const Standard_Real TolBoundary, const Standard_Real TolTangency, const Standard_Boolean RecheckOnRegularity = Standard_False); //! Returns True if the calculus was successful. Standard_Boolean IsDone() const; //! Returns true if all arc of the Arcs are solution (inside //! the surface). //! An exception is raised if IsDone returns False. Standard_Boolean AllArcSolution() const; //! Returns the number of resulting points. //! An exception is raised if IsDone returns False (NotDone). Standard_Integer NbPoints() const; //! Returns the resulting point of range Index. //! The exception NotDone is raised if IsDone() returns //! False. //! The exception OutOfRange is raised if //! Index <= 0 or Index > NbPoints. const IntPatch_ThePathPointOfTheSOnBounds& Point (const Standard_Integer Index) const; //! Returns the number of the resulting segments. //! An exception is raised if IsDone returns False (NotDone). Standard_Integer NbSegments() const; //! Returns the resulting segment of range Index. //! The exception NotDone is raised if IsDone() returns //! False. //! The exception OutOfRange is raised if //! Index <= 0 or Index > NbPoints. const IntPatch_TheSegmentOfTheSOnBounds& Segment (const Standard_Integer Index) const; protected: private: Standard_Boolean done; Standard_Boolean all; IntPatch_SequenceOfSegmentOfTheSOnBounds sseg; IntPatch_SequenceOfPathPointOfTheSOnBounds spnt; }; #define TheVertex Handle(Adaptor3d_HVertex) #define TheVertex_hxx <Adaptor3d_HVertex.hxx> #define TheArc Handle(Adaptor2d_Curve2d) #define TheArc_hxx <Adaptor2d_Curve2d.hxx> #define TheArcTool IntPatch_HCurve2dTool #define TheArcTool_hxx <IntPatch_HCurve2dTool.hxx> #define TheSOBTool IntPatch_HInterTool #define TheSOBTool_hxx <IntPatch_HInterTool.hxx> #define Handle_TheTopolTool Handle(Adaptor3d_TopolTool) #define TheTopolTool Adaptor3d_TopolTool #define TheTopolTool_hxx <Adaptor3d_TopolTool.hxx> #define TheFunction IntPatch_ArcFunction #define TheFunction_hxx <IntPatch_ArcFunction.hxx> #define IntStart_ThePathPoint IntPatch_ThePathPointOfTheSOnBounds #define IntStart_ThePathPoint_hxx <IntPatch_ThePathPointOfTheSOnBounds.hxx> #define IntStart_SequenceOfPathPoint IntPatch_SequenceOfPathPointOfTheSOnBounds #define IntStart_SequenceOfPathPoint_hxx <IntPatch_SequenceOfPathPointOfTheSOnBounds.hxx> #define IntStart_TheSegment IntPatch_TheSegmentOfTheSOnBounds #define IntStart_TheSegment_hxx <IntPatch_TheSegmentOfTheSOnBounds.hxx> #define IntStart_SequenceOfSegment IntPatch_SequenceOfSegmentOfTheSOnBounds #define IntStart_SequenceOfSegment_hxx <IntPatch_SequenceOfSegmentOfTheSOnBounds.hxx> #define IntStart_SearchOnBoundaries IntPatch_TheSOnBounds #define IntStart_SearchOnBoundaries_hxx <IntPatch_TheSOnBounds.hxx> #include <IntStart_SearchOnBoundaries.lxx> #undef TheVertex #undef TheVertex_hxx #undef TheArc #undef TheArc_hxx #undef TheArcTool #undef TheArcTool_hxx #undef TheSOBTool #undef TheSOBTool_hxx #undef Handle_TheTopolTool #undef TheTopolTool #undef TheTopolTool_hxx #undef TheFunction #undef TheFunction_hxx #undef IntStart_ThePathPoint #undef IntStart_ThePathPoint_hxx #undef IntStart_SequenceOfPathPoint #undef IntStart_SequenceOfPathPoint_hxx #undef IntStart_TheSegment #undef IntStart_TheSegment_hxx #undef IntStart_SequenceOfSegment #undef IntStart_SequenceOfSegment_hxx #undef IntStart_SearchOnBoundaries #undef IntStart_SearchOnBoundaries_hxx #endif // _IntPatch_TheSOnBounds_HeaderFile
#include <iostream> #include <cmath> using namespace std; int main() { int num = 0; cout << "Enter a number: "; cin >> num; int cube = num*num*num; if ( cube % num == 0 ) { cout << "The cube of " << num << " is " << cube << "." << endl; } else { cout << "Error! The cube of " << num << " is not " << cube << endl; } }
#include "terminallistdialog.h" #include "ui_terminallistdialog.h" TerminalListDialog::TerminalListDialog(QSqlQueryModel *modTerm, QWidget *parent) : QDialog(parent), ui(new Ui::TerminalListDialog) { ui->setupUi(this); modelTerminals = modTerm; createUI(); } TerminalListDialog::~TerminalListDialog() { delete ui; } void TerminalListDialog::createUI() { modelTerminals->setHeaderData(0,Qt::Horizontal,tr("АЗС")); modelTerminals->setHeaderData(1,Qt::Horizontal,tr("Расположение")); ui->tableView->setModel(modelTerminals); ui->tableView->verticalHeader()->hide(); for(int i = 2;i<=4; ++i) ui->tableView->hideColumn(i); ui->tableView->resizeColumnsToContents(); ui->tableView->verticalHeader()->setDefaultSectionSize(ui->tableView->verticalHeader()->minimumSectionSize()); } void TerminalListDialog::on_pushButtonCancel_clicked() { this->reject(); } void TerminalListDialog::on_tableView_doubleClicked(const QModelIndex &idx) { terminalID = modelTerminals->data(modelTerminals->index(idx.row(),0)).toInt(); emit sendTerminalID(terminalID); this->accept(); } void TerminalListDialog::on_pushButtonChoise_clicked() { QModelIndex idx; idx = ui->tableView->currentIndex(); terminalID = modelTerminals->data(modelTerminals->index(idx.row(),0)).toInt(); emit sendTerminalID(terminalID); this->accept(); }
// Copyright 2017 Pok On Cheng // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mpi.h" #include <algorithm> #include <cstdlib> #include <cctype> #include <cmath> #include <sstream> #include <fstream> #include <iostream> #include <vector> #define send_data_tag 2001 #define return_data_tag 2002 ***************** Add/Change the functions(including processImage) here ********************* // NOTE: Some arrays are linearized in the skeleton below to ease the MPI Data Communication // i.e. A[x][y] become A[x*total_number_of_columns + y] int* processImage(int* inputImage, int processId, int num_processes, int image_height, int image_width){ int x, y, sum, sumx, sumy; int GX[3][3], GY[3][3]; /* 3x3 Sobel masks. */ GX[0][0] = -1; GX[0][1] = 0; GX[0][2] = 1; GX[1][0] = -2; GX[1][1] = 0; GX[1][2] = 2; GX[2][0] = -1; GX[2][1] = 0; GX[2][2] = 1; GY[0][0] = 1; GY[0][1] = 2; GY[0][2] = 1; GY[1][0] = 0; GY[1][1] = 0; GY[1][2] = 0; GY[2][0] = -1; GY[2][1] = -2; GY[2][2] = -1; //chunkSize is the number of rows to be computed by this process int chunkSize; int* partialOutputImage; for( x = start_of_chunk; x < end_of_chunk; x++ ){ for( y = 0; y < image_width; y++ ){ sumx = 0; sumy = 0; //Change boundary cases as required if(x==0 || x==(image_height-1) || y==0 || y==(image_width-1)) sum = 0; else{ for(int i=-1; i<=1; i++) { for(int j=-1; j<=1; j++){ sumx += (inputImage[(x+i)*image_width+ (y+j)] * GX[i+1][j+1]); } } for(int i=-1; i<=1; i++) { for(int j=-1; j<=1; j++){ sumy += (inputImage[(x+i)*image_width+ (y+j)] * GY[i+1][j+1]); } } sum = (abs(sumx) + abs(sumy)); } partialOutputImage[x*image_width + y] = (0 <= sum <= 255); } } return partialOutputImage; } int main(int argc, char* argv[]) { int processId, num_processes, image_height, image_width, image_maxShades, root_process, child_id; int *inputImage, *outputImage; int *partialImage, *tempImage; int count_recv, count_return; root_process = 0; // Setup MPI MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &processId); MPI_Comm_size( MPI_COMM_WORLD, &num_processes); chunk_size = image_height / num_processes; if(argc != 3) { if(processId == 0) std::cout << "ERROR: Incorrect number of arguments. Format is: <Input image filename> <Output image filename>" << std::endl; MPI_Finalize(); return 0; } if(processId == 0) { std::ifstream file(argv[1]); if(!file.is_open()) { std::cout << "ERROR: Could not open file " << argv[1] << std::endl; MPI_Finalize(); return 0; } std::cout << "Detect edges in " << argv[1] << " using " << num_processes << " processes\n" << std::endl; std::string workString; /* Remove comments '#' and check image format */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ if( workString.at(1) != '2' ){ std::cout << "Input image is not a valid PGM image" << std::endl; return 0; } else { break; } } else { continue; } } /* Check image size */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ std::stringstream stream(workString); int n; stream >> n; image_width = n; stream >> n; image_height = n; break; } else { continue; } } inputImage = new int[image_height*image_width]; outputImage = new int[image_height*image_width]; tempImage = new int[image_height*image_width]; partialImage = new int[image_height*image_width]; /* Check image max shades */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ std::stringstream stream(workString); stream >> image_maxShades; break; } else { continue; } } /* Fill input image matrix */ int pixel_val; for( int i = 0; i < image_height; i++ ) { if( std::getline(file,workString) && workString.at(0) != '#' ){ std::stringstream stream(workString); for( int j = 0; j < image_width; j++ ){ if( !stream ) break; stream >> pixel_val; inputImage[(i*image_width)+j] = pixel_val; } } else { continue; } } } // Done with reading image using process 0 if(processId == 0){ // distribute a portion to each child process for(child_id = 1; child_id < num_processes; child_id++) { start_of_chunk = child_id*chunk_size; end_of_chunk = (child_id + 1)*chunk_size - 1; int count = chunk_size * image_width; int start_index = child_id * count; // check last chuck's end point if((image_height- end_of_chunk) < chunk_size) { end_of_chunk = image_height - 1; int rows = end_of_chunk - start_of_chunk + 1; // overwrite count value count = rows * image_width; } // sending segments MPI_Send(&count, 1, MPI_INT, child_id, send_data_tag, MPI_COMM_WORLD); MPI_Send(&inputImage[start_index], count, MPI_INT, child_id, send_data_tag, MPI_COMM_WORLD); } // process image in the segment assigned to the root process for(int i = 0; i < (chunk_size * image_width); i++){ tempImage[i] = inputImage[i]; } outputImage = processImage(tempImage, processId, num_processes, image_height, image_width); // receive partial image and add them to outputImage for(child_id = 1; child_id < num_processes; child_id++) { MPI_Recv (&count_return, 1, MPI_INT, MPI_ANY_SOURCE, return_data_tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv (&partialImage, count_return, MPI_INT, MPI_ANY_SOURCE, return_data_tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); for(int i = 0; i < ;i++){ outputImage[child_id*image_width + 1] = partialImage[i]; } } } else{ // receive segments from root process MPI_Recv(&count_recv, 1, MPI_INT, root_process, send_data_tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&tempImage, count_recv, MPI_INT, root_process, send_data_tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // process image in the segment assigned to each child process partialImage = processImage(tempImage, processId, num_processes, image_height, image_width); // send partial image to the root process MPI_Send(&count_recv, 1, MPI_INT, root_process, return_data_tag, MPI_COMM_WORLD); MPI_Send(&partialImage, count_recv, MPI_INT, root_process, return_data_tag, MPI_COMM_WORLD); } ***************** Add code as per your requirement below ********************* if(processId == 0) { /* Start writing output to your file */ std::ofstream ofile(argv[2]); if( ofile.is_open() ) { ofile << "P2" << "\n" << image_width << " " << image_height << "\n" << image_maxShades << "\n"; for( int i = 0; i < image_height; i++ ) { for( int j = 0; j < image_width; j++ ){ ofile << outputImage[(i*image_width)+j] << " "; } ofile << "\n"; } } else { std::cout << "ERROR: Could not open output file " << argv[2] << std::endl; return 0; } } MPI_Finalize(); return 0; }
#ifndef OBJECT_UPPER_EXT_H #define OBJECT_UPPER_EXT_H #include <QObject> class Object_Upper_Ext_H : public QObject { Q_OBJECT Q_SLOT void go(){}; }; #endif
#include "Options.h" Options::Options(QWidget* parent) : QDialog(parent) { this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); this->setAttribute(Qt::WA_DeleteOnClose); this->setMinimumSize(300, 300); storedSettings = Utils::loadSettingsFromFile(); oldSettingsToCompare = storedSettings; QGridLayout* layoutOption = new QGridLayout(this); ini(layoutOption); this->exec(); } void Options::ini(QGridLayout* layout) { QLabel* langueIcon = new QLabel(this); QLabel* langue = new QLabel(tr("Languages"), this); QComboBox* langList = new QComboBox(this); QLabel* themeIcon = new QLabel(this); QLabel* theme = new QLabel(tr("Theme"), this); QComboBox* themeList = new QComboBox(this); QLabel* fontIcon = new QLabel(this); QLabel* font = new QLabel(tr("Font"), this); QPushButton* fontChoser = new QPushButton(tr("Selector"), this); QPushButton* closeButton = new QPushButton(tr("Close"), this); layout->addWidget(langueIcon, 0, 0); layout->addWidget(langue, 0, 1); layout->addWidget(langList, 1, 0, 1, 3); layout->addWidget(themeIcon, 2, 0); layout->addWidget(theme, 2, 1); layout->addWidget(themeList, 3, 0, 1, 3); layout->addWidget(fontIcon, 4, 0); layout->addWidget(font, 4, 1); layout->addWidget(fontChoser, 4, 2); layout->addWidget(closeButton, 5, 0, 1, 3); langList->addItem("Francais"); langList->addItem("English"); themeList->addItem(tr("Light")); themeList->addItem(tr("Dark")); connect(fontChoser, SIGNAL(clicked()), this, SLOT(newFont())); connect(langList, SIGNAL(activated(int)), this, SLOT(setTraduction(int))); connect(themeList, SIGNAL(activated(int)), this, SLOT(setTheme(int))); connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); themeList->setCurrentIndex(storedSettings.theme); langList->setCurrentIndex(storedSettings.langue); langList->setItemDelegate(new QStyledItemDelegate()); themeList->setItemDelegate(new QStyledItemDelegate()); layout->setAlignment(Qt::AlignLeft); langList->setObjectName("comboLangue"); themeList->setObjectName("comboTheme"); fontChoser->setObjectName("fontButton"); langList->setCursor(Qt::PointingHandCursor); themeList->setCursor(Qt::PointingHandCursor); fontChoser->setCursor(Qt::PointingHandCursor); closeButton->setCursor(Qt::PointingHandCursor); SingleData* getData = SingleData::getInstance(); getData->addLabelToAdaptOnTheme("translations", langueIcon); getData->addLabelToAdaptOnTheme("theme", themeIcon); getData->addLabelToAdaptOnTheme("letter", fontIcon); langueIcon->setPixmap(getData->getPixMapOnActualTheme("translations")); themeIcon->setPixmap(getData->getPixMapOnActualTheme("theme")); fontIcon->setPixmap(getData->getPixMapOnActualTheme("letter")); } void Options::newFont() { bool validButton = true; QFont font = QFontDialog::getFont(&validButton, qApp->font(), this); if (!validButton) { return; } storedSettings.font_family = font.family(); storedSettings.font_style = font.styleName(); storedSettings.font_size = font.pointSize(); storedSettings.font_weight = font.weight(); storedSettings.font_italic = font.italic(); storedSettings.font_underline = font.underline(); storedSettings.font_strike_out = font.strikeOut(); Utils::applyNewFont(storedSettings); } void Options::setTheme(int index) { storedSettings.theme = index; Utils::applyNewTheme(index); Utils::applyNewFont(storedSettings); } void Options::setTraduction(int index) { storedSettings.langue = index; Utils::applyNewLanguage(index); } void Options::closeEvent(QCloseEvent* e) { if (storedSettings != oldSettingsToCompare) { QMessageBox lMessageBox(QMessageBox::Icon::Information, tr("Info"), tr("The application needs to be restarted."), QMessageBox::StandardButton::Ok); lMessageBox.exec(); } SingleData::getInstance()->setIndexActualTheme(storedSettings.theme); Utils::saveSettingsToJsonFile(storedSettings); } Options::~Options() { }
#include <stdio.h> using namespace std; int main() { freopen("student.txt", "w", stdout); int i; for(i=1; i<=31000; i++) printf("0 0\n"); return 0; }
#include <iostream> #ifndef TOKEN_H #define TOKEN_H class Token { private: public: std::string Type; std::string Value; friend std::ostream& operator<<(std::ostream& os, const Token& token); Token(std::string Token_Type = "None", std::string Token_value = "None"); }; #endif
#pragma once #include <QStyledItemDelegate> namespace envire { namespace viz { /**A double spin box item delegate with high precision */ class DoubleSpinboxItemDelegate : public QStyledItemDelegate { Q_OBJECT /**NOTE: This whole class only exists because the default precision of * QDoubleSpinBox is 2 and there is no way to change it inside a * TreeView or TableView without providing a custom delegate. * * This class is mostly copied from * http://doc.qt.io/qt-5/qtwidgets-itemviews-spinboxdelegate-example.html */ public: DoubleSpinboxItemDelegate(QObject *parent = 0); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setDecimals(const unsigned int value); private: unsigned int decimals; }; }}
#include <Arduino.h> #include<Wire.h> // SHT25 I2C address is 0x40(64)ds #define Addr 0x40 void setup() { Wire.begin(); Serial.begin(9600); } void loop() { unsigned int data[2]; Wire.beginTransmission(Addr); Wire.write(0xF5); // Send humidity measurement command, NO HOLD master Wire.endTransmission(); delay(500); Wire.requestFrom(Addr, 2); if(Wire.available() == 2) // humidity msb, humidity lsb { data[0] = Wire.read(); data[1] = Wire.read(); float humidity = (((data[0] * 256.0 + data[1]) * 125.0) / 65536.0) - 6; byte* humidityBytes = (byte*) &humidity; Serial.write("#"); Serial.write(humidityBytes, 4); } Wire.beginTransmission(Addr); Wire.write(0xF3); Wire.endTransmission(); delay(500); Wire.requestFrom(Addr, 2); if(Wire.available() == 2) { data[0] = Wire.read(); data[1] = Wire.read(); float cTemp = (((data[0] * 256.0 + data[1]) * 175.72) / 65536.0) - 46.85; byte* tempBytes = (byte*) &cTemp; Serial.write("*"); Serial.write(tempBytes, 4); } Serial.write("@"); delay(300); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; int a[100]; int main() { int t;long long n; scanf("%d",&t); while (t--) { scanf("%lld",&n); int k = 0; while (n) { a[k++] = n%2; n /= 2; } int ans = 0,sum = 0; for (int i = 0;i < k; i++) { if (a[i] == 1) sum = 1; else { ans += sum; sum = 0; } } ans += sum; printf("%d\n",ans); } return 0; }
#include "PCH.hpp" #include "Tree.hpp" #include "Game.hpp" Tree::Tree(Game* game) { m_game = game; m_ID = "tree"; } void Tree::Update() { GameObject::Update(); } void Tree::Render() { GameObject::Render(); } void Tree::Clean() { GameObject::Clean(); }
//Class to define a stock object #ifndef H_STOCK #define H_STOCK #include "stdafx.h" class Stock { //**************************************************** //Overloaded Stream Operators //**************************************************** friend istream& operator>> (istream &in, Stock &astock); friend ostream& operator<< (ostream &out, Stock &astock); public: //**************************************************** //Constructors //**************************************************** Stock(string insymbol = "", double inopenValue = 0, double incloseValue = 0, double inhigh = 0, double inlow = 0, double inpreviousClose = 0, unsigned long involume = 0); //Postcondition: symbol = insymbol // openValue = inopenValue // closeValue = incloseValue // high = inhigh // low = inlow // previousClose = inpreviousClose // volume = inVolume // change is calculated through the calculateChange method //**************************************************** //Accessors //**************************************************** string getSymbol(); double getOpenValue(); double getCloseValue(); double getHigh(); double getLow(); double getPreviousClose(); double getChange(); unsigned long getVolume(); //**************************************************** //Mutators //**************************************************** void setSymbol(string insymbol); //Postcondition: symbol = insymbol void setOpenValue(double inValue); //Postcondition: openValue = inValue void setCloseValue(double inValue); //Postcondition: closeValue = inValue void setHigh(double inValue); //Postcondition: high = inValue void setLow(double inValue); //Postcondition: low = inValue void setPreviousClose(double inValue); //Postcondition: previousClose = inValue void setVolume(unsigned long inValue); //Postcondition: volume = inValue //**************************************************** //Overloaded Relational Operators //**************************************************** bool operator> (Stock &astock) const; bool operator< (Stock &astock) const; bool operator>= (Stock &astock) const; bool operator<= (Stock &astock) const; bool operator== (Stock &astock) const; bool operator!= (Stock &astock) const; //**************************************************** //Sort Functions //**************************************************** static void sortBySymbol(Stock stocks[], int maxElement); static void sortByChange(Stock stocks[], int maxElement); private: //Ticker symbol string symbol; //Open and close prices double openValue; double closeValue; //Highest achieved price double high; //Lowest price of the day double low; //Closing price for the previous day double previousClose; //Percent change from yesterday to today double change; //Number of shares traded today unsigned long volume; //Calculates Change Percentage void calculateChange(); }; #endif
/* TouchKeys: multi-touch musical keyboard control software Copyright (c) 2013 Andrew McPherson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ===================================================================== OscMidiConverter.cpp: converts incoming OSC messages to outgoing MIDI messages with adjustable ranges and parameters. */ #include "OscMidiConverter.h" #include "MidiKeyboardSegment.h" #undef DEBUG_OSC_MIDI_CONVERTER // Main constructor: set up OSC reception from the keyboard OscMidiConverter::OscMidiConverter(PianoKeyboard& keyboard, MidiKeyboardSegment& segment, int controllerId) : keyboard_(keyboard), keyboardSegment_(segment), midiOutputController_(0), controller_(controllerId), lastUniqueId_(0), incomingController_(MidiKeyboardSegment::kControlDisabled) { setOscController(&keyboard_); for(int i = 0; i < 16; i++) { currentValue_[i] = 0; lastOutputValue_[i] = -1; } } // Set the type of MIDI message (CC, Pitch Wheel, Aftertouch) // that this particular object is in charge of controlling. // Optionally specify the default, range, and whether to use a // 14 bit controller. void OscMidiConverter::setMidiMessageType(int defaultValue, int minValue, int maxValue, int centerValue, bool use14BitControl) { /*if(controller < 0 || controller >= MidiKeyboardSegment::kControlMax) { controller_ = MidiKeyboardSegment::kControlDisabled; return; } keyboardSegment_ = segment;*/ // Otherwise, send defaults on the current controller to all channels and update to the new values //for(int i = 0; i < 16; i++) // sendDefaultValue(i); // Clear any existing active inputs, but not the mappings themselves lastValues_.clear(); //controller_ = controller; if(defaultValue >= 0) controlDefaultValue_ = defaultValue; else { // Default value for MIDI CCs and aftertouch is 0 // Default value for MIDI pitch wheel is 8192 if(controller_ == MidiKeyboardSegment::kControlPitchWheel) controlDefaultValue_ = 8192; else controlDefaultValue_ = 0; } if(centerValue >= 0) controlCenterValue_ = centerValue; else { // Set center value with same procedure as default value if(controller_ == MidiKeyboardSegment::kControlPitchWheel) controlCenterValue_ = 8192; else controlCenterValue_ = 0; } // Pitch wheel is always 14 bit. Aftertouch is always 7 bit. // Other CCs are selectable (though according to MIDI spec not every // controller has an LSB defined). And above 96 using "control+32" // for fine adjust no longer makes sense if(controller_ < 96) controllerIs14Bit_ = use14BitControl; else if(controller_ == MidiKeyboardSegment::kControlPitchWheel) controllerIs14Bit_ = true; else controllerIs14Bit_ = false; // Handle the outer ranges of the control, providing defaults if unspecified if(controllerIs14Bit_) { if(maxValue < 0 || maxValue > 16383) controlMaxValue_ = 16383; else controlMaxValue_ = maxValue; if(minValue < 0 || minValue > 16383) controlMinValue_ = 0; else controlMinValue_ = minValue; } else { if(maxValue < 0 || maxValue > 127) controlMaxValue_ = 127; else controlMaxValue_ = maxValue; if(minValue < 0 || minValue > 127) controlMinValue_ = 0; else controlMinValue_ = minValue; } } void OscMidiConverter::listenToIncomingControl(int controller, int centerValue, bool use14BitControl) { if(controller < 0 || controller >= MidiKeyboardSegment::kControlMax) { incomingController_ = MidiKeyboardSegment::kControlDisabled; return; } incomingController_ = controller; // Assign the center value that will be subtacted from the incoming controller if(centerValue >= 0) incomingControllerCenterValue_ = centerValue; else if(controller == MidiKeyboardSegment::kControlPitchWheel) incomingControllerCenterValue_ = 8192; // Pitch wheel is centered at 8192 else incomingControllerCenterValue_ = 0; // Pitch wheel is always 14 bit. Aftertouch is always 7 bit. // Other CCs are selectable (though according to MIDI spec not every // controller has an LSB defined). And above 96 using "control+32" // for fine adjust no longer makes sense if(controller < 96) incomingControllerIs14Bit_ = use14BitControl; else if(controller == MidiKeyboardSegment::kControlPitchWheel) incomingControllerIs14Bit_ = true; else incomingControllerIs14Bit_ = false; } // Resend the most recent value void OscMidiConverter::resend(int channel) { sendCurrentValue(keyboardSegment_.outputPort(), channel, -1, true); } // Send the default value on the specified channel. void OscMidiConverter::sendDefaultValue(int channel) { if(midiOutputController_ == 0 || controller_ == MidiKeyboardSegment::kControlDisabled) return; // Modulate the default value by the value of the incoming controller, // if one is enabled. int defaultValue = controlDefaultValue_; // if(incomingController_ != MidiKeyboardSegment::kControlDisabled) // defaultValue += keyboardSegment_.controllerValue(incomingController_) - incomingControllerCenterValue_; // // if(controller_ == MidiKeyboardSegment::kControlPitchWheel) { // //sendPitchWheelRange(keyboardSegment_.outputPort(), channel); // midiOutputController_->sendPitchWheel(keyboardSegment_.outputPort(), channel, defaultValue); // } // else if(controller_ == MidiKeyboardSegment::kControlChannelAftertouch) { // midiOutputController_->sendAftertouchChannel(keyboardSegment_.outputPort(), channel, defaultValue); // } // else if(controller_ == MidiKeyboardSegment::kControlPolyphonicAftertouch) { // // TODO // } // else if(controllerIs14Bit_) { // midiOutputController_->sendControlChange(keyboardSegment_.outputPort(), channel, controller_, defaultValue >> 7); // midiOutputController_->sendControlChange(keyboardSegment_.outputPort(), channel, controller_ + 32, defaultValue & 0x7F); // } // else // midiOutputController_->sendControlChange(keyboardSegment_.outputPort(), channel, controller_, defaultValue); } int OscMidiConverter::currentControllerValue(int channel) { float controlValue = (float)controlCenterValue_ + (float)controlMinValue_ + currentValue_[channel]*(float)(controlMaxValue_ - controlMinValue_); if(incomingController_ != MidiKeyboardSegment::kControlDisabled) { controlValue += keyboardSegment_.controllerValue(incomingController_) - incomingControllerCenterValue_; #ifdef DEBUG_OSC_MIDI_CONVERTER std::cout << "current value " << currentValue_[channel] << " corresponds to " << controlValue; std::cout << " including incoming value " << (keyboardSegment_.controllerValue(incomingController_) - incomingControllerCenterValue_) << std::endl; #endif } else { #ifdef DEBUG_OSC_MIDI_CONVERTER std::cout << "current value " << currentValue_[channel] << " corresponds to " << controlValue << std::endl; #endif } // For 14-bit CC messages, multiply by 128 first to keep the same apparent range as // the 7-bit version but adding extra resolution on the second CC number. This should // not be done for pitch wheel where the values are already normalised to 14 bits. if(controllerIs14Bit_ && controller_ != MidiKeyboardSegment::kControlPitchWheel) controlValue *= 128.0; int roundedControlValue = (int)floorf(controlValue + 0.5f); int maxValue = controllerIs14Bit_ ? 16383 : 127; if(roundedControlValue > maxValue) roundedControlValue = maxValue; if(roundedControlValue < 0) roundedControlValue = 0; return roundedControlValue; } // Add a new OSC input to this MIDI control void OscMidiConverter::addControl(const string& oscPath, int oscParamNumber, float oscMinValue, float oscMaxValue, float oscCenterValue, int outOfRangeBehavior) { // First remove any existing mapping with these exact parameters removeControl(oscPath); #ifdef DEBUG_OSC_MIDI_CONVERTER std::cout << "OscMidiConverter: adding path " << oscPath << std::endl; #endif // Insert the mapping OscInput input; input.oscParamNumber = oscParamNumber; input.oscMinValue = oscMinValue; input.oscMaxValue = oscMaxValue; // Calculate the normalized center value which will be subtracted // from the scaled input. Do this once now to save computation. if(oscMinValue == oscMaxValue) input.oscScaledCenterValue = 0.5; else { input.oscScaledCenterValue = (oscCenterValue - oscMinValue) / (oscMaxValue - oscMinValue); if(input.oscScaledCenterValue < 0) input.oscScaledCenterValue = 0; if(input.oscScaledCenterValue > 1.0) input.oscScaledCenterValue = 1.0; } input.outOfRangeBehavior = outOfRangeBehavior; input.uniqueId = lastUniqueId_++; inputs_[oscPath] = input; // Register for the relevant OSC message addOscListener(oscPath); } // Remove an existing OSC input void OscMidiConverter::removeControl(const string& oscPath) { // Find the affected control and its ID if(inputs_.count(oscPath) == 0) return; int controlId = inputs_[oscPath].uniqueId; #ifdef DEBUG_OSC_MIDI_CONVERTER std::cout << "OscMidiConverter: removing path " << oscPath << std::endl; #endif // Look for any active inputs on this channel for(int i = 0; i < 16; i++) { int channelModulatedId = idWithChannel(i, controlId); if(lastValues_.count(channelModulatedId) == 0) continue; // Found a last value. Subtract it off and get new value float lastValueThisChannel = lastValues_[channelModulatedId]; currentValue_[i] -= lastValueThisChannel; // Remove this value from the set of active inputs lastValues_.erase(channelModulatedId); // Send the new value after removing this one sendCurrentValue(keyboardSegment_.outputPort(), i, -1, true); } // Having removed any active inputs, now remove the control itself // TODO: mutex protection inputs_.erase(oscPath); removeOscListener(oscPath); } void OscMidiConverter::removeAllControls() { // Clear all active inputs and send default values to all channels for(int i = 0; i < 16; i++) sendDefaultValue(i); lastValues_.clear(); inputs_.clear(); lastUniqueId_ = 0; removeAllOscListeners(); } // Update the minimum input value of an existing path void OscMidiConverter::setControlMinValue(const string& oscPath, float newValue) { if(inputs_.count(oscPath) == 0) return; inputs_[oscPath].oscMinValue = newValue; } // Update the maximum input value of an existing path void OscMidiConverter::setControlMaxValue(const string& oscPath, float newValue) { if(inputs_.count(oscPath) == 0) return; inputs_[oscPath].oscMaxValue = newValue; } // Update the center input value of an existing path void OscMidiConverter::setControlCenterValue(const string& oscPath, float newValue) { if(inputs_.count(oscPath) == 0) return; float minValue, maxValue, scaledCenterValue; minValue = inputs_[oscPath].oscMinValue; maxValue = inputs_[oscPath].oscMaxValue; if(minValue == maxValue) scaledCenterValue = 0.0; else scaledCenterValue = (newValue - minValue) / (maxValue - minValue); if(scaledCenterValue < 0) scaledCenterValue = 0; if(scaledCenterValue > 1.0) scaledCenterValue = 1.0; inputs_[oscPath].oscScaledCenterValue = scaledCenterValue; } // Update the out of range behavior for an existing path void OscMidiConverter::setControlOutOfRangeBehavior(const string& oscPath, int newBehavior) { if(inputs_.count(oscPath) == 0) return; inputs_[oscPath].outOfRangeBehavior = newBehavior; } // Reset any active previous values on the given channel // 'send' indicated whether to send the value when finished // even if it hasn't changed void OscMidiConverter::clearLastValues(int channel, bool send) { std::map<int, float>::iterator it = lastValues_.begin(); bool erased = false; while(it != lastValues_.end()) { // Look for any last values matching this channel if((it->first & 0x0F) == channel) { lastValues_.erase(it++); erased = true; } else it++; } currentValue_[channel] = 0; lastOutputValue_[channel] = -1; // If any last values were erased and send is enabled, // resend the current values if(erased || send) sendDefaultValue(channel); } // OSC Handler, called by the data source (PianoKeyboard in this case). Check path against stored // inputs and map to MIDI accordingly bool OscMidiConverter::oscHandlerMethod(const char *path, const char *types, int numValues, lo_arg **values, void *data) { #ifdef DEBUG_OSC_MIDI_CONVERTER std::cout << "OscMidiConverter: received path " << path << std::endl; #endif if(midiOutputController_ == 0 || controller_ == MidiKeyboardSegment::kControlDisabled) return false; //double before = Time::getMillisecondCounterHiRes(); // DEBUG // First value should always be MIDI note number (integer type) so we can retrieve // information from the PianoKeyboard class if(numValues < 1) return false; if(types[0] != 'i') return false; int midiNoteNumber = values[0]->i; // Get the MIDI retransmission channel from the note number if(keyboard_.key(midiNoteNumber) == 0) return false; int midiChannel = keyboard_.key(midiNoteNumber)->midiChannel(); if(midiChannel < 0 || midiChannel > 15) { #ifdef DEBUG_OSC_MIDI_CONVERTER std::cout << "OscMidiConverter: no retransmission channel on note " << midiNoteNumber << std::endl; #endif return false; } // Find the relevant input and make sure this OSC message has enough parameters if(inputs_.count(path) == 0) return false; OscInput const& input = inputs_[path]; if(input.oscParamNumber >= numValues) return false; // Find the relevant input value from this OSC message float oscParamValue; if(types[input.oscParamNumber] == 'f') oscParamValue = values[input.oscParamNumber]->f; else if(types[input.oscParamNumber] == 'i') oscParamValue = (float)values[input.oscParamNumber]->i; else return false; // Scale input to a 0-1 range, then to the output range. There's a special case for MIDI pitch wheel, // where if the range is set to 0, it means to use the segment-wide pitch wheel range. This is done so // we don't have to cache multiple copies of the pitch wheel range in every OSC-MIDI converter. float scaledValue; if(controller_ == MidiKeyboardSegment::kControlPitchWheel && input.oscMaxValue == 0 && input.oscMinValue == 0) { float pitchWheelRange = keyboardSegment_.midiPitchWheelRange(); scaledValue = (oscParamValue + pitchWheelRange) / (2.0 * pitchWheelRange); } else scaledValue = (oscParamValue - input.oscMinValue) / (input.oscMaxValue - input.oscMinValue); #ifdef DEBUG_OSC_MIDI_CONVERTER std::cout << "port " << keyboardSegment_.outputPort() << " received input " << oscParamValue << " which scales to " << scaledValue << std::endl; #endif // Figure out what to do with an out of range value... if(scaledValue < 0.0 || scaledValue > 1.0) { if(input.outOfRangeBehavior == kOutOfRangeClip) { if(scaledValue < 0.0) scaledValue = 0.0; if(scaledValue > 1.0) scaledValue = 1.0; } else if(input.outOfRangeBehavior == kOutOfRangeExtrapolate) { // Do nothing } else // Ignore or unknown behavior return false; } //double midpoint = Time::getMillisecondCounterHiRes(); // DEBUG // Now subtract the normalized center value, which may put the range outside 0-1 // but this is expected. For example, in a pitch wheel situation, we might move // to a range of -0.5 to 0.5. scaledValue -= input.oscScaledCenterValue; // Look for previous input with this path and channel and remove it int channelModulatedId = idWithChannel(midiChannel, input.uniqueId); if(lastValues_.count(channelModulatedId) > 0) { // Found a last value. Subtract it off and replace with our current value float lastValueThisChannel = lastValues_[channelModulatedId]; currentValue_[midiChannel] -= lastValueThisChannel; #ifdef DEBUG_OSC_MIDI_CONVERTER std::cout << "found and removed " << lastValueThisChannel << ", now have " << currentValue_[midiChannel] << std::endl; #endif } lastValues_[channelModulatedId] = scaledValue; currentValue_[midiChannel] += scaledValue; // Send the total current value as a MIDI controller sendCurrentValue(keyboardSegment_.outputPort(), midiChannel, midiNoteNumber, false); //double after = Time::getMillisecondCounterHiRes(); // DEBUG //std::cout << "OscMidiConverter: total " << after - before << "ms, of which " << after - midpoint << " in 2nd half\n"; return true; } // Send the current sum value of all OSC inputs as a MIDI message void OscMidiConverter::sendCurrentValue(int port, int channel, int note, bool force) { if(midiOutputController_ == 0 || channel < 0 || channel > 15) return; // TODO: what about values that are centered by default e.g. pitch? /*float controlValue = (float)controlCenterValue_ + (float)controlMinValue_ + currentValue_[channel]*(float)(controlMaxValue_ - controlMinValue_); if(incomingController_ != MidiKeyboardSegment::kControlDisabled) controlValue += keyboardSegment_.controllerValue(incomingController_) - incomingControllerCenterValue_; std::cout << "sending value " << currentValue_[channel] << " as " << controlValue << std::endl; int roundedControlValue = (int)roundf(controlValue); if(roundedControlValue > controlMaxValue_) roundedControlValue = controlMaxValue_; if(roundedControlValue < controlMinValue_) roundedControlValue = controlMinValue_;*/ int roundedControlValue = currentControllerValue(channel); // If this is the same ultimate CC value as before, don't resend unless forced if(roundedControlValue == lastOutputValue_[channel] && !force) return; lastOutputValue_[channel] = roundedControlValue; // Four cases: Pitch Wheel messages, aftertouch, 14-bit controls (major and minor controllers), ordinary 7-bit controls // if(controller_ == MidiKeyboardSegment::kControlPitchWheel) { // midiOutputController_->sendPitchWheel(port, channel, roundedControlValue); // } // else if(controller_ == MidiKeyboardSegment::kControlChannelAftertouch) { // midiOutputController_->sendAftertouchChannel(port, channel, roundedControlValue); // } // else if(controller_ == MidiKeyboardSegment::kControlPolyphonicAftertouch && note >= 0) { // midiOutputController_->sendAftertouchPoly(port, channel, note + keyboardSegment_.outputTransposition(), // roundedControlValue); // } // else if(controllerIs14Bit_) { // // LSB for controllers 0-31 are found on controllers 32-63 // int lsb = roundedControlValue & 0x007F; // int msb = (roundedControlValue >> 7) & 0x007F; // // midiOutputController_->sendControlChange(port, channel, controller_, msb); // midiOutputController_->sendControlChange(port, channel, controller_ + 32, lsb); // } // else { // 7 bit // midiOutputController_->sendControlChange(port, channel, controller_, roundedControlValue); // } }
#include "log.hpp" #include "admin_mgr_class.hpp" #include "admin.hpp" #include "route/route_mgr.hpp" #include "utils/client_process_mgr.hpp" #include "config/options_ptts.hpp" #include "proto/config_options.pb.h" #include "proto/ss_gm.pb.h" #include <condition_variable> #include <mutex> namespace nora { namespace gm { using admin_service = client_process_mgr<admin, net::WS_SERVER_CONN>; admin_mgr_class::admin_mgr_class() { name_ = "gmd-adminmgr"; st_ = make_shared<service_thread>("adminmgr"); st_->start(); const auto& ptt = PTTS_GET(options, 1); gmdb_ = make_shared<db::connector>(ptt.gm_info().db().ipport(), ptt.gm_info().db().user(), ptt.gm_info().db().password(), ptt.gm_info().db().database()); gmdb_->start(); } void admin_mgr_class::start(const string& ip, unsigned short port) { mutex m; condition_variable cv; auto waiting_count = 1; auto db_msg = make_shared<db::message>("load_gmd_administrators", db::message::req_type::rt_select, [this, &waiting_count, &cv, &m] (const shared_ptr<db::message>& msg) { lock_guard<mutex> lock(lock_); auto& results = msg->results(); for (const auto& i : results) { ASSERT(i.size() == 2); auto username = boost::any_cast<string>(i[0]); auto password = boost::any_cast<string>(i[1]); admin2passwords_[username] = password; ADMIN_TLOG << "add username: " << username << " password: " << password; } { lock_guard<mutex> lk(m); waiting_count -= 1; } cv.notify_one(); }); gmdb_->push_message(db_msg, st_); { unique_lock<mutex> lk(m); cv.wait(lk, [&waiting_count] { return waiting_count == 0; }); } const auto& ptt = PTTS_GET(options, 1); admin_service::instance().init(ptt.gm_info().id()); admin_service::instance().static_init(); admin_service::instance().start(ip, port); } void admin_mgr_class::player_online(uint32_t server_id, uint64_t gid) { lock_guard<mutex> lock(lock_); server2onlines_[server_id].insert(gid); } void admin_mgr_class::player_offline(uint32_t server_id, uint64_t gid) { lock_guard<mutex> lock(lock_); if (server2onlines_.count(server_id) > 0) { if (server2onlines_.at(server_id).count(gid) > 0) { server2onlines_[server_id].erase(gid); } } } void admin_mgr_class::player_register_count_update(uint32_t server_id, uint32_t register_count) { lock_guard<mutex> lock(lock_); server2register_count_[server_id] = register_count; } void admin_mgr_class::login_done(uint32_t conn_id, const string& username, const string& password) { st_->async_call( [this, conn_id, username, password] { ASSERT(st_->check_in_thread()); auto result = pd::OK; if (admin2passwords_.count(username) < 0 || admin2passwords_.at(username) != password) { result = pd::NOT_FOUND; } if (result != pd::OK) { if (aids_.count(conn_id) > 0) { aids_.erase(conn_id); } admin_service::instance().disconnect(conn_id); } else { ASSERT(aids_.count(conn_id) == 0); aids_.insert(conn_id); proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_sync_serverlist::gss); auto route_table = route::route_mgr::instance().route_table(); for (const auto& i : route_table.clients()) { auto *server = sync->add_servers(); server->set_server_type(i.type()); server->set_server_id(i.id()); if (i.type() == pd::RCT_SCENED) { server->set_online_count(server2onlines_[i.id()].size()); server->set_register_count(server2register_count_[i.id()]); } } admin_service::instance().send_msg(conn_id, sync_msg); } }); } void admin_mgr_class::get_role_info_done(uint32_t conn_id, uint32_t server_id, const pd::role& role_data, pd::result result) { st_->async_call( [this, conn_id, server_id, role_data, result] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_get_role_info_by_gid_rsp::ggribgr); sync->set_result(result); sync->set_server_id(server_id); if (result == pd::OK) { *sync->add_role_info() = role_data; } admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::operates_activity_done(uint32_t conn_id, pd::result result) { st_->async_call( [this, conn_id, result] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_admin_start_activity_rsp::gasar); sync->set_result(result); admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::admin_edit_role_by_gid_done(uint32_t conn_id, pd::result result, pd::admin_edit_role_type edit_type) { st_->async_call( [this, conn_id, result, edit_type] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_admin_edit_role_by_gid_rsp::gaerbgr); sync->set_edit_type(edit_type); sync->set_result(result); admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::admin_edit_role_rollback_by_gid_done(uint32_t conn_id, pd::result result, pd::admin_edit_role_type edit_type) { st_->async_call( [this, conn_id, result, edit_type] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_admin_edit_role_rollback_by_gid_rsp::gaerrbgr); sync->set_edit_type(edit_type); sync->set_result(result); admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::admin_send_mail_done(uint32_t conn_id, pd::result result) { st_->async_call( [this, conn_id, result] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_admin_send_mail_rsp::gasmr); sync->set_result(result); admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::admin_fetch_gonggao_list_done(uint32_t conn_id, const pd::gonggao_array& gonggao_list) { st_->async_call( [this, conn_id, gonggao_list] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_admin_fetch_gonggao_list_rsp::gafglr); *sync->mutable_gonggao_list() = gonggao_list; admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::admin_edit_gonggao_done(uint32_t conn_id, pd::result result) { st_->async_call( [this, conn_id, result] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_admin_edit_gonggao_rsp::gaegr); sync->set_result(result); admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::admin_fetch_white_list_done(uint32_t conn_id, pd::result result, const pd::white_list_array& white_list) { st_->async_call( [this, conn_id, result, white_list] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_admin_fetch_white_list_rsp::gafwlr); sync->set_result(result); *sync->mutable_white_list() = white_list; admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::admin_edit_white_list_done(uint32_t conn_id, bool publish, pd::result result) { st_->async_call( [this, conn_id, result, publish] { ASSERT(st_->check_in_thread()); if (aids_.count(conn_id) <= 0) { return; } proto::ss::base sync_msg; auto *sync = sync_msg.MutableExtension(ps::g2c_admin_edit_white_list_rsp::gaewlr); sync->set_publish(publish); sync->set_result(result); admin_service::instance().send_msg(conn_id, sync_msg); }); } void admin_mgr_class::stop() { if (st_) { st_->stop(); } ADMIN_DLOG << *this << " stop"; } } }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}} #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; typedef pair<ll, ll> llP; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} template<class T> inline bool chmax(T& a, T b) {if (a < b) {a = b; return true;} return false;} template<class T> inline bool chmin(T& a, T b) {if (a > b) {a = b; return true;} return false;} int main() { int n; cin >> n; vector<int> a(n+1); rep(i, n+1){ cin >> a[i]; } vector<int> a_rev; a_rev = a; reverse(a_rev.begin(), a_rev.end()); vector<ll> a_limit(n+1, 0); a_limit[n] = a[n]; for (int i = n-1; i >= 0; i--) { a_limit[i] = a_limit[i+1] + a[i]; } //show(a_limit); ll node = 1; ll ans = 0; rep(i, n+1){ chmin(node, a_limit[i]); //限界値で丸める ans += node; node -= a[i];// 葉っぱを引く if (node < 0) { cout << -1 << endl; return 0; } node *= 2;// 二分木化する } cout << ans << endl; }
/* Given is the code to print numbers from 1 to n in increasing order recursively. But it contains few bugs that you need to rectify such that all the test cases pass. Input Format : Integer n Output Format : Numbers from 1 to n (separated by space) Constraints : 1 <= n <= 10000 Sample Input 1 : 6 Sample Output 1 : 1 2 3 4 5 6 Sample Input 2 : 4 Sample Output 2 : 1 2 3 4 */ #include<iostream> using namespace std; void print(int n){ if(n==0){ return; } print(n-1); cout<<n<<" "; } int main(){ int n; cin>>n; print(n); return 0; }
#include "Screen.h" #include "Exception.h" Screen::Screen(glm::vec2 _size) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { throw std::exception(); } size = _size; window = SDL_CreateWindow("GEP Engine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, size.x, size.y, SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL); if (!SDL_GL_CreateContext(window)) { throw Exception("Failed to Create Window"); } if (glewInit() != GLEW_OK) { throw Exception("Failed to Init Glew"); } SDL_GLContext glContext = SDL_GL_CreateContext(window); if (!glContext) { throw Exception("Failed to create OpenGL context"); } } Screen::~Screen() { SDL_DestroyWindow(window); SDL_Quit(); } void Screen::Clear() { glClearColor(0.f, 0.f, 0.f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Screen::SetScreenName(std::string _name) { SDL_SetWindowTitle(window, _name.c_str()); } void Screen::Display() { SDL_GL_SwapWindow(window); }
#include <bits/stdc++.h> using namespace std; #define MAX 10010 vector<int> graph[MAX]; bool used [MAX]; void dfs(int u){ if(used[u]) return; used[u] = true; for(int i = 0; i < graph[u].size();++i){ int v = graph[u][i]; if(!used[v]) dfs(v); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; for(int test = 0; test < T; ++test){ int n,m; cin >> n >> m; for(int i = 0; i < m; ++i){ int a,b; cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); } memset(used, false, sizeof used); int ans = 0; for(int i = 1; i <= n; ++i){ if(!used[i]){ dfs(i); ans++; } } cout << (ans*(ans-1)/2)<<'\n'; for(int i = 1; i <= n; ++i) graph[i].clear(); } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2004 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ /** * @author Daniel Bratell */ #include "core/pch.h" #include "modules/forms/datetime.h" #include "modules/util/str.h" #include "modules/util/datefun.h" #include "modules/stdlib/util/opdate.h" // Local help funtion inline static int digit(uni_char a_char) { return a_char - '0'; } // Local help function static BOOL IsLeapYear(int year) { return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)); } // 4-digit years, prefixed with 0s if needed. static void ToISO8601YearString(unsigned year, uni_char *buf) { unsigned i = 0; if (year < 1000) { buf[i++] = '0'; if (year < 100) { buf[i++] = '0'; if (year < 10) buf[i++] = '0'; } } uni_itoa(year, &buf[i], 10); } void WeekSpec::ToISO8601String(uni_char* buf) const { OP_ASSERT(m_year <= 9999); ToISO8601YearString(m_year, buf); buf[4] = '-'; buf[5] = 'W'; buf[6] = m_week/10 + '0'; buf[7] = m_week%10 + '0'; buf[8] = '\0'; } unsigned int WeekSpec::GetISO8601StringLength() const { return 8; } BOOL WeekSpec::SetFromISO8601String(const uni_char* week_string) { m_year = 0; for (int i = 0; i < 4; i++) { if (!uni_isdigit(week_string[i])) { return FALSE; } m_year = m_year*10 + digit(week_string[i]); } if (week_string[4] != '-') { return FALSE; } if (week_string[5] != 'W') { return FALSE; } if (!uni_isdigit(week_string[6]) || !uni_isdigit(week_string[7]) || week_string[8]) { return FALSE; } m_week = digit(week_string[6])*10 + digit(week_string[7]); if (m_year < 1000 || m_week < 1 || m_week > 53) { return FALSE; } // XXX Doesn't check if week 53 is legal for the given year. return TRUE; } void WeekSpec::SetFromTime(double ms) { DaySpec day; day.m_year = OpDate::YearFromTime(ms); day.m_month = OpDate::MonthFromTime(ms); day.m_day = OpDate::DateFromTime(ms); WeekSpec week = day.GetWeek(); m_year = week.m_year; m_week = week.m_week; } double WeekSpec::AsDouble() { #if 0 // XXXX This is buggy for weeks before 1970-W01. // 1970-01-01 was a thursday. Found the date of the // thursday in the specified week // Find date of thursday week 1 of the year DaySpec d = { m_year, 0, 1 }; int day_of_week = d.DayOfWeek(); int date_of_first_week_thursday; // thursday is 3, if we get > 3 then this is the last week last year if (day_of_week > 3) { date_of_first_week_thursday = 11 - day_of_week; } else { date_of_first_week_thursday = 4 - day_of_week; } DaySpec first_week_thursday = { m_year, 0, date_of_first_week_thursday }; double days_since_epoch = first_week_thursday.AsDouble(); BOOL negative = days_since_epoch < 0; if (negative) { days_since_epoch = -days_since_epoch; } int weeks_since_epoch = (int)((days_since_epoch+3.5) / 7); if (negative) { days_since_epoch = -days_since_epoch; } return double(weeks_since_epoch + m_week - 1); #else WeekSpec base_week = { 1970, 01 }; double diff_days = GetLastDay().AsDouble() - base_week.GetLastDay().AsDouble(); OP_ASSERT(diff_days == static_cast<int>(diff_days)); OP_ASSERT(diff_days/7.0 == static_cast<int>(diff_days/7.0)); return static_cast<int>(diff_days)/7; #endif // 0 } DaySpec WeekSpec::GetFirstDay() const { DaySpec as_day = GetLastDay(); // Move from sunday to monday if (as_day.m_day > 6) { as_day.m_day -= 6; } else { MonthSpec month = { as_day.m_year, as_day.m_month }; month = month.PrevMonth(); as_day.m_day = as_day.m_day -6 + month.DaysInMonth(); as_day.m_year = month.m_year; as_day.m_month = month.m_month; } return as_day; } DaySpec WeekSpec::GetLastDay() const { DaySpec day_for_last_in_week_1 = { m_year, 0, 4 }; day_for_last_in_week_1.m_day += 6 - day_for_last_in_week_1.DayOfWeek(); // To sunday if (day_for_last_in_week_1.m_day > 31) { day_for_last_in_week_1.m_day -= 31; day_for_last_in_week_1.m_month = 0; day_for_last_in_week_1.m_year++; } OP_ASSERT(day_for_last_in_week_1.DayOfWeek() == 6); if (day_for_last_in_week_1.GetWeek().m_week != 1) { day_for_last_in_week_1.m_day += 7; // 7 days a week (unless you're a Beatles fan) if (day_for_last_in_week_1.m_day > 31) // 31 days in dec { day_for_last_in_week_1.m_month = 0; day_for_last_in_week_1.m_day -= 31; day_for_last_in_week_1.m_year++; } } OP_ASSERT (day_for_last_in_week_1.GetWeek().m_week == 1); OP_ASSERT (day_for_last_in_week_1.m_year == m_year); // I have no good algorithm for this. Use a "brute force" method that is limited // to 11 iterations. int day_number = day_for_last_in_week_1.m_day; MonthSpec month = { m_year, 0 }; day_number += 7 * (m_week - 1); while (day_number > month.DaysInMonth()) { day_number -= month.DaysInMonth(); if (month.m_month == 11) { OP_ASSERT(day_number < 4); // Bad week number. Should have been caught earlier month.m_month = 0; month.m_year++; } else { month.m_month++; } } OP_ASSERT(day_number >= 1 && day_number <= 31); DaySpec res = {month.m_year, month.m_month, static_cast<unsigned char>(day_number)}; return res; } WeekSpec WeekSpec::NextWeek() const { DaySpec d = GetLastDay().NextDay(); OP_ASSERT(d.GetWeek().m_week != m_week); return d.GetWeek(); } WeekSpec WeekSpec::PrevWeek() const { DaySpec d = GetFirstDay().PrevDay(); OP_ASSERT(d.GetWeek().m_week != m_week); return d.GetWeek(); } // MonthSpec MonthSpec MonthSpec::PrevMonth() const { MonthSpec prev = { static_cast<unsigned short>(m_year - (m_month == 0 ? 1:0)), static_cast<unsigned char>((m_month + 11) % 12) }; return prev; } MonthSpec MonthSpec::NextMonth() const { MonthSpec next = { static_cast<unsigned short>(m_year + (m_month == 11 ? 1:0)), static_cast<unsigned char>((m_month + 1) % 12) }; return next; } DaySpec MonthSpec::FirstDay() const { DaySpec first = { m_year, m_month, 1 }; return first; } DaySpec MonthSpec::LastDay() const { DaySpec last = { m_year, m_month, DaysInMonth() }; return last; } void MonthSpec::ToISO8601String(uni_char* buf) const { OP_ASSERT(m_year <= 9999); ToISO8601YearString(m_year, buf); buf[4] = '-'; buf[5] = (m_month+1)/10 + '0'; buf[6] = (m_month+1)%10 + '0'; buf[7] = '\0'; } unsigned int MonthSpec::GetISO8601StringLength() const { return 7; } BOOL MonthSpec::SetFromISO8601String(const uni_char* month_string) { m_year = 0; for (int i = 0; i < 4; i++) { if (!uni_isdigit(month_string[i])) { return FALSE; } m_year = m_year*10 + digit(month_string[i]); } if (month_string[4] != '-') { return FALSE; } if (!uni_isdigit(month_string[5]) || !uni_isdigit(month_string[6]) || month_string[7]) { return FALSE; } m_month = digit(month_string[5])*10 + digit(month_string[6]); if (m_year < 1000 || m_month < 1 || m_month > 12) { return FALSE; } m_month--; // our months are 0-11, not 1-12 return TRUE; } void MonthSpec::SetFromTime(double ms) { m_year = OpDate::YearFromTime(ms); m_month = OpDate::MonthFromTime(ms); } double MonthSpec::AsDouble() { return 12.0 * (m_year - 1970) + m_month; // 1970-01 is the base == 0.0 } #ifdef _DEBUG static int OldDayOfWeek(int m_year, int m_month, int m_day) { static const unsigned char mkeys[12] = { 1, 4, 4, 0, 2, 5, 0, 3, 6, 1, 4, 6 }; int day; day = (m_year-1900) + (m_year-1900)/4 + mkeys[static_cast<int>(m_month)] + m_day - 1; /* The above counts the leap day even if it occurs later in the year */ if(m_year > 1900 && m_year % 4 == 0 && m_month < 2) { day--; } day--; // Change to make monday the first day of the week day %= 7; return day; } #endif // _DEBUG // This one isn't as limited. /** * * From http://www.faqs.org/faqs/sci-math-faq/dayWeek/ * * The following formula, which is for the Gregorian calendar only, may * be more convenient for computer programming. Note that in some * programming languages the remainder operation can yield a negative * result if given a negative operand, so mod 7 may not translate to a * simple remainder. W = (k + floor(2.6m - 0.2) - 2C + Y + floor(Y/4) + * floor(C/4)) mod 7 where floor() denotes the integer floor function, * k is day (1 to 31) * m is month (1 = March, ..., 10 = December, 11 = Jan, 12 = Feb) Treat * Jan &Feb as months of the preceding year * C is century (1987 has C = 19) * Y is year (1987 has Y = 87 except Y = 86 for Jan &Feb) * W is week day (0 = Sunday, ..., 6 = Saturday) * Here the century and 400 year corrections are built into the formula. * The floor(2.6m - 0.2) term relates to the repetitive pattern that the * 30-day months show when March is taken as the first month. */ int DaySpec::DayOfWeek() const { int year = m_year; // We have a cycle of 400 years so we can just move the year to the range 1700-2099 if (year < 1700) { year += 400*((2099-year)/400); } else if (year > 2099) { year -= 400*((year-1700)/400); } OP_ASSERT(year > 1699 && year < 2100); // "Treat Jan &Feb as months of the preceding year" int month; if (m_month < 2) { year--; month = m_month + 11; } else { month = m_month - 1; } int century = year / 100; int year_in_century = year % 100; int day = (m_day + static_cast<int>(2.6*month - 0.2) - 2*century + year_in_century + (year_in_century/4) + century/4 + 70 - 1) % 7; // adding 70 to get a positive number, removing 1 since we have monday = 0, not sunday as the formula expects. // min = 1+2.6-0.2-2*40 #ifdef _DEBUG if (m_year > 1900 && m_year < 2100) { OP_ASSERT(day == OldDayOfWeek(m_year, m_month, m_day)); } #endif // _DEBUG return day; } void DaySpec::ToISO8601String(uni_char* buf) const { OP_ASSERT(m_year <= 9999); ToISO8601YearString(m_year, buf); buf[4] = '-'; OP_ASSERT(m_month <= 11); if (m_month < 9) { buf[5] = '0'; buf[6] = m_month + 1 + '0'; } else { buf[5] = '1'; buf[6] = m_month + 1 - 10 + '0'; } buf[7] = '-'; OP_ASSERT(m_day >= 1 && m_day <= 31); buf[8] = m_day/10 + '0'; buf[9] = m_day%10 + '0'; buf[10] = '\0'; } unsigned int DaySpec::GetISO8601StringLength() const { return 4+1+2+1+2; // Not including null byte } BOOL DaySpec::SetFromISO8601String(const uni_char* value, BOOL partial /* = FALSE */) { // A date (year, month, day) encoded according to [ISO8601], e.g.: // 1995-12-31. // Does this duplicate some existing tested code? if (uni_isdigit(value[0]) && uni_isdigit(value[1]) && uni_isdigit(value[2]) && uni_isdigit(value[3]) && value[4] == '-' && uni_isdigit(value[5]) && uni_isdigit(value[6]) && value[7] == '-' && uni_isdigit(value[8]) && uni_isdigit(value[9]) && (partial || value[10] == '\0')) { m_year = digit(value[0])*1000+digit(value[1])*100+digit(value[2])*10+digit(value[3]); m_month = digit(value[5])*10 + digit(value[6]); m_day = digit(value[8])*10 + digit(value[9]); if (m_year == 0) { return FALSE; } if (m_month < 1 || m_month > 12) { return FALSE; } MonthSpec month = {m_year, static_cast<unsigned char>(m_month - 1)}; if (m_day < 1 || m_day > month.DaysInMonth()) { return FALSE; } m_month--; // We use months between 0 and 11 return TRUE; } return FALSE; } void DaySpec::SetFromTime(double ms) { m_year = OpDate::YearFromTime(ms); m_month = OpDate::MonthFromTime(ms); m_day = OpDate::DateFromTime(ms); } double DaySpec::AsDouble() { // FIXME: Code duplication? Very similar code in OpDate double double_val = 0.0; // Let 1970-01-01 be our "zero" (it is in the specification) unsigned short year = 1970; int direction = year < m_year ? 1 : -1; while (year != m_year) { int year_to_skip = direction > 0 ? year : year - 1; if (IsLeapYear(year_to_skip)) { double_val += direction*366.0; } else { double_val += direction*365.0; } year += direction; } // Correct year. We're a January 1st unsigned char month = 0; while (month < m_month) { MonthSpec m = {year, month}; double_val += m.DaysInMonth(); month++; } // Correct month. We're at The first day in the month double_val += m_day - 1; return double_val; } WeekSpec DaySpec::GetWeek() const { // Algorithm taken from http://www.tondering.dk/claus/cal/node7.html#SECTION00780000000000000000 // First calculate JD: http://www.tondering.dk/claus/cal/node3.html#sec-calcjd int a = (14 - (m_month+1)) / 12; int y = m_year+4800-a; int m = (m_month + 1)+12*a-3; // Julian day, gregorian calendar long JD = m_day + (153*m+2)/5 + 365*y + y / 4 - y / 100 + y / 400 - 32045; long d4 = (((JD + 31741 - (JD%7)) % 146097) % 36524) % 1461; int L = d4/1460; int d1 = (d4-L) % 365 + L; int week_number = d1/7+1; // To this we add the year and make a WeekSpec unsigned short year = m_year; if (m_month == 0 && week_number > 50) { // wrong year. This is week 52/53 of last year year--; } else if (m_month == 11 && week_number == 1) { // wrong year. This is week 1 of next year year++; } OP_ASSERT(week_number >= 1 && week_number <= 53); WeekSpec week = {year, static_cast<unsigned char>(week_number)}; return week; } DaySpec DaySpec::NextDay() const { DaySpec ret = *this; MonthSpec m = { m_year, m_month }; if (ret.m_day == m.DaysInMonth()) { ret.m_day = 1; if (ret.m_month == 11) { ret.m_month = 0; ret.m_year++; } else ret.m_month++; } else { ret.m_day += 1; } return ret; } DaySpec DaySpec::PrevDay() const { DaySpec ret = *this; if (ret.m_day == 1) { MonthSpec m = { m_year, m_month }; m = m.PrevMonth(); ret.m_year = m.m_year; ret.m_month = m.m_month; ret.m_day = m.DaysInMonth(); } else { ret.m_day -= 1; } return ret; } int TimeSpec::GetFraction() const { // The world isn't ready for full fractions yet. Statically sized buffers for instance if (IsSecondUndefined() || m_fraction_digit_count < 1) { return 0; } int fraction_digits = m_fraction_digit_count; int fraction = m_fraction; while (fraction_digits < 2) { fraction *= 10; fraction_digits++; } while (fraction_digits > 2) { fraction /= 10; fraction_digits--; } return fraction; } int TimeSpec::GetFractionDigitCount() const { if (IsSecondUndefined() || m_fraction_digit_count < 1) { return 0; } // The world isn't ready for full fractions yet. Statically sized buffers for instance return 2; } void TimeSpec::ToISO8601String(uni_char* buf) const { OP_ASSERT(m_hour <= 23); buf[0] = m_hour/10 + '0'; buf[1] = m_hour%10 + '0'; buf[2] = ':'; OP_ASSERT(m_minute >= 0 && m_minute <= 59); buf[3] = m_minute/10 + '0'; buf[4] = m_minute%10 + '0'; OP_ASSERT(m_second == -1 || (m_second >= 0 && m_second <= 59)); if (m_second == -1) { // XXX The real format? Read the spec! buf[5] = '\0'; } else { buf[5] = ':'; buf[6] = m_second/10 + '0'; buf[7] = m_second%10 + '0'; int fraction_digits = GetFractionDigitCount(); if (fraction_digits == 0) { buf[8] = '\0'; } else { int factor = 1; for (int i = fraction_digits; i > 1; i--) { factor *= 10; } int buf_pos = 8; buf[buf_pos++] = '.'; int fraction = GetFraction(); while (factor) { buf[buf_pos++] = '0' + fraction/factor; fraction = fraction % factor; factor /= 10; } OP_ASSERT(buf_pos == (int)GetISO8601StringLength()); buf[buf_pos++] = '\0'; } } } unsigned int TimeSpec::GetISO8601StringLength() const { // Not including null byte if (m_second == -1) { return 5; // "HH:MM" } int fraction_digit_count = GetFractionDigitCount(); if (fraction_digit_count == 0) { return 8; // "HH:MM:SS" } return 9 + fraction_digit_count; // "HH:MM:SS.xxxxx" } unsigned int TimeSpec::SetFromISO8601String(const uni_char* time_string, BOOL partial /* = FALSE */) { // A time (hour, minute) encoded according to [ISO8601] with no // time zone, e.g.: 23:59. User agents are expected to show an // appropriate widget, such as a clock. UAs should make it clear // to the user that the time does not carry any time zone information. if (!(uni_isdigit(time_string[0]) && uni_isdigit(time_string[1]) && time_string[2] == ':' && uni_isdigit(time_string[3]) && uni_isdigit(time_string[4]))) { // Doesn't even start correctly return 0; } m_hour = 10 * digit(time_string[0]) + digit(time_string[1]); m_minute = 10 * (digit(time_string[3])) + digit(time_string[4]); if (m_hour > 23 || m_minute > 59) { return 0; } OP_ASSERT(m_hour <= 23); OP_ASSERT(m_minute <= 59); m_second = -1; m_fraction_digit_count = 0; m_fraction = 0; int len = 5; // Length of valid string. if (time_string[5] != '\0') { if (!(time_string[5] == ':' && uni_isdigit(time_string[6]) && uni_isdigit(time_string[7]))) { // Had something after the minute that wasn't a second. return partial ? len : 0; } m_second = 10 * digit(time_string[6]) + digit(time_string[7]); if (m_second > 59) { return 0; } OP_ASSERT(m_second >= 0 && m_second <= 59); len = 8; if (time_string[8] != '\0') { if (!(time_string[8] == '.')) { // The seperator must be a period. return partial ? len : 0; } // Consume n digits, but only use 9 (~30 bits) for fraction. for (len = 9; uni_isdigit(time_string[len]); len++) { if (m_fraction_digit_count < 9) { m_fraction_digit_count++; m_fraction = m_fraction * 10 + digit(time_string[len]); } } OP_ASSERT(m_fraction_digit_count < 10); if (m_fraction_digit_count == 0) { // Must have at least one digit return partial ? 8 : 0; } OP_ASSERT(m_fraction_digit_count > 0); if (!partial && time_string[len] != '\0') { // Must be null-terminated if so requested return 0; } } } return len; } /** * Simple helper method to do powers of ten. op_pow(10, x) * seems to be broken with some compilers (MSVC7.1) in * optimizing mode. It returns ERROR for op_pow(10,-3) for instance. */ static double TenPower(int power) { OP_ASSERT(power < 10 && power > -10); // made for small powers double val = 1.0; while (power > 0) { val *= 10; power--; } while (power < 0) { val /= 10; power++; } return val; } void TimeSpec::SetFromTime(double ms) { m_hour = OpDate::HourFromTime(ms); m_minute = OpDate::MinFromTime(ms); m_second = OpDate::SecFromTime(ms); SetFractionUndefined(); } double TimeSpec::AsDouble() const { double val = 0.0; if (m_second != -1) { if (m_fraction_digit_count > 0) val += m_fraction/TenPower(m_fraction_digit_count); val += m_second; } val += 60.0 * (m_minute + 60.0 * m_hour); return val; } void TimeSpec::SetFromNumber(int value, int multiplied_factor) { OP_ASSERT(value >= 0); OP_ASSERT(value <= 86400*multiplied_factor-1); m_hour = value / (3600 * multiplied_factor); value -= m_hour * 3600 * multiplied_factor; m_minute = value / (60 * multiplied_factor); value -= m_minute * 60 * multiplied_factor; if (m_second != -1 || value > 0) { m_second = value / multiplied_factor; value -= m_second * multiplied_factor; value = (value * 1000) / multiplied_factor; // Now in ms if (value > 0 || GetFractionDigitCount() > 0) { if (value == 0) { SetFraction(0, 0); } else if ((value/100) * 100 == value) { SetFraction(value/100, 1); } else if ((value/10) * 10 == value) { SetFraction(value/10, 2); } else { SetFraction(value, 3); } } } else { SetFractionUndefined(); } } void TimeSpec::SetFraction(int fraction, int fraction_digit_count) { OP_ASSERT(fraction_digit_count <= 9); m_fraction = fraction; m_fraction_digit_count = fraction_digit_count; } unsigned int TimeZoneSpec::SetFromISO8601String(const uni_char* tz_string, BOOL partial /* = FALSE */) { // A time zone (hour, minute) encoded according to [ISO8601], // e.g.: 'Z', '+02:00' or '-07:45'. Time zones which don't exist // are OK as long as they are in the range -23:59 to +23:59. unsigned int len = 0; if (tz_string[0] == 'Z') { m_sign = '+'; m_hour = 0; m_minute = 0; len = 1; } else if ((tz_string[0] == '+' || tz_string[0] == '-') && uni_isdigit(tz_string[1]) && uni_isdigit(tz_string[2]) && tz_string[3] == ':' && uni_isdigit(tz_string[4]) && uni_isdigit(tz_string[5])) { m_sign = static_cast<char>(tz_string[0]); m_hour = 10 * digit(tz_string[1]) + digit(tz_string[2]); m_minute = 10 * (digit(tz_string[4])) + digit(tz_string[5]); if (m_hour > 23 || m_minute > 59) { return 0; } len = 6; } else { // Neither Z nor +/-HH:MM format return 0; } OP_ASSERT(m_sign == '+' || m_sign == '-'); OP_ASSERT(m_hour <= 23); OP_ASSERT(m_minute <= 59); if (!partial && tz_string[len] != '\0') { return 0; } return len; } double TimeZoneSpec::AsDouble() const { OP_ASSERT(m_sign == '+' || m_sign == '-'); OP_ASSERT(m_hour <= 23); OP_ASSERT(m_minute <= 59); double val = 60.0 * (m_minute + 60.0 * m_hour); return (m_sign == '+') ? val : -val; } void DateTimeSpec::ToISO8601String(uni_char* buf, BOOL include_timezone) const { if (include_timezone && !m_timezone.IsZ()) { DateTimeSpec norm = *this; norm.ConvertToUTC(); norm.ToISO8601String(buf, include_timezone); } else { m_date.ToISO8601String(buf); buf += m_date.GetISO8601StringLength(); *buf = 'T'; buf++; m_time.ToISO8601String(buf); buf += m_time.GetISO8601StringLength(); if (include_timezone) { *buf = 'Z'; // Timezone buf++; } *buf = '\0'; } } unsigned int DateTimeSpec::GetISO8601StringLength(BOOL include_timezone) const { // NOTE: the code below may miscalulate if we allow for years with > 4 digits return m_date.GetISO8601StringLength()+ // 10 1 + // The 'T' char m_time.GetISO8601StringLength() + // 5 - ~ 12 !!include_timezone; // The 'Z' char (and not including the null byte) } unsigned int DateTimeSpec::SetFromISO8601String(const uni_char* date_time_string, BOOL include_timezone, BOOL partial /* = FALSE */) { if (!date_time_string) { return 0; } unsigned int len = 0; if (!m_date.SetFromISO8601String(date_time_string, TRUE)) { return 0; } len = m_date.GetISO8601StringLength(); if (date_time_string[len++] != 'T') { return 0; } unsigned int time_len = m_time.SetFromISO8601String(date_time_string+len, TRUE); if (time_len == 0) { return 0; } len += time_len; if (include_timezone) { // A fully fledged time zone offset spec is allowed/required here // (see http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#date-and-time-state) // unsigned int timezone_length = m_timezone.SetFromISO8601String(date_time_string+len, TRUE); if (timezone_length == 0) { return 0; } len += timezone_length; } else { m_timezone.Clear(); } if (!partial && date_time_string[len] != '\0') { return 0; } return len; } void DateTimeSpec::SetFromTime(double ms) { m_date.SetFromTime(ms); m_time.SetFromTime(ms); m_timezone.Clear(); } double DateTimeSpec::AsDouble() { double ms = m_time.m_fraction/TenPower(m_time.m_fraction_digit_count-3); OP_ASSERT(TenPower(m_time.m_fraction_digit_count-3) != 0); OP_ASSERT(!op_isnan(ms) && !op_isinf(ms)); double val = OpDate::MakeDate(OpDate::MakeDay(m_date.m_year, m_date.m_month, m_date.m_day), OpDate::MakeTime(m_time.m_hour, m_time.m_minute, m_time.GetSecond(), ms)) - m_timezone.AsDouble()*1000; OP_ASSERT(!op_isnan(val) && !op_isinf(val)); return val; } unsigned char MonthSpec::DaysInMonth() const { static const unsigned char MONTH_DAYS[] = {31,28,31,30,31,30,31,31,30,31,30,31}; unsigned char days = MONTH_DAYS[m_month]; if (m_month == 1) // february { if (IsLeapYear(m_year)) { days++; } } return days; } void DateTimeSpec::ConvertToUTC() { OP_ASSERT(m_time.m_minute >= 0 && m_time.m_minute < 60); OP_ASSERT(m_time.m_hour < 24); OP_ASSERT(m_timezone.m_minute < 60); OP_ASSERT(m_timezone.m_hour < 24); int sign = (m_timezone.m_sign == '+' ? 1 : -1); int minute = m_time.m_minute - sign * m_timezone.m_minute; int hour = m_time.m_hour - sign * m_timezone.m_hour; if (minute < 0) { minute += 60; --hour; } else if (minute >= 60) { minute -= 60; ++hour; } if (hour < 0) { hour += 24; m_date = m_date.PrevDay(); } else if (hour >= 24) { hour -= 24; m_date = m_date.NextDay(); } OP_ASSERT(minute >= 0 && minute < 60); OP_ASSERT(hour >= 0 && hour < 24); m_time.m_minute = minute; m_time.m_hour = hour; m_timezone.m_minute = 0; m_timezone.m_hour = 0; OP_ASSERT(m_timezone.IsZ()); }
// Copyright (c) 2012-2017 The Cryptonote developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "gtest/gtest.h" #include <thread> #include "Transfers/BlockchainSynchronizer.h" #include "Transfers/TransfersConsumer.h" #include "crypto/hash.h" #include "CryptoNoteCore/TransactionApi.h" #include "CryptoNoteCore/CryptoNoteFormatUtils.h" #include "CryptoNoteCore/CryptoNoteTools.h" #include "Logging/ConsoleLogger.h" #include "INodeStubs.h" #include "TestBlockchainGenerator.h" #include "EventWaiter.h" using namespace crypto; using namespace cn; namespace { Transaction createTx(ITransactionReader& tx) { Transaction outTx; fromBinaryArray(outTx, tx.getTransactionData()); return outTx; } } class INodeNonTrivialRefreshStub : public INodeTrivialRefreshStub { public: INodeNonTrivialRefreshStub(TestBlockchainGenerator& generator) : INodeTrivialRefreshStub(generator), blocksWasQueried(false), poolWasQueried(false) {} virtual void queryBlocks(std::vector<Hash>&& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const Callback& callback) override { blocksWasQueried = true; INodeTrivialRefreshStub::queryBlocks(std::move(knownBlockIds), timestamp, newBlocks, startHeight, callback); } virtual void getPoolSymmetricDifference(std::vector<Hash>&& known_pool_tx_ids, Hash known_block_id, bool& is_bc_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted_tx_ids, const Callback& callback) override { poolWasQueried = true; INodeTrivialRefreshStub::getPoolSymmetricDifference(std::move(known_pool_tx_ids), known_block_id, is_bc_actual, new_txs, deleted_tx_ids, callback); } void notifyAboutPool() { observerManager.notify(&INodeObserver::poolChanged); } bool blocksWasQueried; bool poolWasQueried; }; class INodeFunctorialStub : public INodeNonTrivialRefreshStub { public: INodeFunctorialStub(TestBlockchainGenerator& generator) : INodeNonTrivialRefreshStub(generator) , queryBlocksFunctor([](const std::vector<Hash>&, uint64_t, std::vector<BlockShortEntry>&, uint32_t&, const Callback&) -> bool { return true; }) , getPoolSymmetricDifferenceFunctor([](const std::vector<Hash>&, Hash, bool&, std::vector<std::unique_ptr<ITransactionReader>>&, std::vector<Hash>&, const Callback&)->bool {return true; }) { } virtual void queryBlocks(std::vector<Hash>&& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const Callback& callback) override { if (queryBlocksFunctor(knownBlockIds, timestamp, newBlocks, startHeight, callback)) { INodeNonTrivialRefreshStub::queryBlocks(std::move(knownBlockIds), timestamp, newBlocks, startHeight, callback); } } virtual void getPoolSymmetricDifference(std::vector<Hash>&& known_pool_tx_ids, Hash known_block_id, bool& is_bc_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted_tx_ids, const Callback& callback) override { if (getPoolSymmetricDifferenceFunctor(known_pool_tx_ids, known_block_id, is_bc_actual, new_txs, deleted_tx_ids, callback)) { INodeNonTrivialRefreshStub::getPoolSymmetricDifference(std::move(known_pool_tx_ids), known_block_id, is_bc_actual, new_txs, deleted_tx_ids, callback); } } std::function<bool(const std::vector<Hash>&, uint64_t, std::vector<BlockShortEntry>&, uint32_t&, const Callback&)> queryBlocksFunctor; std::function<bool(const std::vector<Hash>&, Hash, bool&, std::vector<std::unique_ptr<ITransactionReader>>&, std::vector<Hash>&, const Callback&)> getPoolSymmetricDifferenceFunctor; }; class IBlockchainSynchronizerTrivialObserver : public IBlockchainSynchronizerObserver { public: virtual void synchronizationProgressUpdated(uint32_t current, uint32_t total) override { m_current = current; m_total = total; } virtual void synchronizationCompleted(std::error_code result) override { completionResult = result; } std::error_code completionResult; uint32_t m_current; uint32_t m_total; }; class IBlockchainSynchronizerFunctorialObserver : public IBlockchainSynchronizerObserver { public: IBlockchainSynchronizerFunctorialObserver() : updFunc([](uint32_t, uint32_t) {}), syncFunc([](std::error_code) {}) { } virtual void synchronizationProgressUpdated(uint32_t current, uint32_t total) override { updFunc(current, total); } virtual void synchronizationCompleted(std::error_code result) override { syncFunc(result); } std::function<void(uint32_t, uint32_t)> updFunc; std::function<void(std::error_code)> syncFunc; }; class ConsumerStub : public IBlockchainConsumer { public: ConsumerStub(const Hash& genesisBlockHash) { m_blockchain.push_back(genesisBlockHash); } void addPoolTransaction(const crypto::Hash& hash) { m_pool.emplace(hash); } virtual SynchronizationStart getSyncStart() override { SynchronizationStart start = { 0, 0 }; return start; } virtual void addObserver(IBlockchainConsumerObserver* observer) override { } virtual void removeObserver(IBlockchainConsumerObserver* observer) override { } virtual void onBlockchainDetach(uint32_t height) override { assert(height < m_blockchain.size()); m_blockchain.resize(height); } virtual bool onNewBlocks(const CompleteBlock* blocks, uint32_t startHeight, uint32_t count) override { //assert(m_blockchain.size() == startHeight); while (count--) { m_blockchain.push_back(blocks->blockHash); ++blocks; } return true; } const std::vector<Hash>& getBlockchain() const { return m_blockchain; } virtual const std::unordered_set<crypto::Hash>& getKnownPoolTxIds() const override { return m_pool; } virtual std::error_code onPoolUpdated(const std::vector<std::unique_ptr<ITransactionReader>>& addedTransactions, const std::vector<Hash>& deletedTransactions) override { for (const auto& tx: addedTransactions) { m_pool.emplace(tx->getTransactionHash()); } for (auto& hash : deletedTransactions) { m_pool.erase(hash); } return std::error_code(); } std::error_code addUnconfirmedTransaction(const ITransactionReader& /*transaction*/) override { throw std::runtime_error("Not implemented"); } void removeUnconfirmedTransaction(const crypto::Hash& /*transactionHash*/) override { throw std::runtime_error("Not implemented"); } private: std::unordered_set<crypto::Hash> m_pool; std::vector<Hash> m_blockchain; }; class BcSTest : public ::testing::Test, public IBlockchainSynchronizerObserver { public: BcSTest() : m_currency(CurrencyBuilder(m_logger).currency()), generator(m_currency), m_node(generator), m_sync(m_node, m_currency.genesisBlockHash()) { m_node.setGetNewBlocksLimit(5); // sync max 5 blocks per request } void addConsumers(size_t count = 1) { while (count--) { std::shared_ptr<ConsumerStub> stub(new ConsumerStub(m_currency.genesisBlockHash())); m_sync.addConsumer(stub.get()); m_consumers.push_back(stub); } } void checkSyncedBlockchains() { std::vector<Hash> generatorBlockchain; std::transform( generator.getBlockchain().begin(), generator.getBlockchain().end(), std::back_inserter(generatorBlockchain), [](const Block& b) { return get_block_hash(b); }); for (const auto& consumer : m_consumers) { ASSERT_EQ(consumer->getBlockchain(), generatorBlockchain); } } void startSync() { syncCompleted = std::promise<std::error_code>(); syncCompletedFuture = syncCompleted.get_future(); m_sync.addObserver(this); m_sync.start(); syncCompletedFuture.get(); m_sync.removeObserver(this); } void refreshSync() { syncCompleted = std::promise<std::error_code>(); syncCompletedFuture = syncCompleted.get_future(); m_sync.addObserver(this); m_node.updateObservers(); syncCompletedFuture.get(); m_sync.removeObserver(this); } void synchronizationCompleted(std::error_code result) override { decltype(syncCompleted) detachedPromise = std::move(syncCompleted); detachedPromise.set_value(result); } protected: logging::ConsoleLogger m_logger; Currency m_currency; TestBlockchainGenerator generator; INodeFunctorialStub m_node; BlockchainSynchronizer m_sync; std::vector<std::shared_ptr<ConsumerStub>> m_consumers; std::promise<std::error_code> syncCompleted; std::future<std::error_code> syncCompletedFuture; }; TEST_F(BcSTest, addConsumerStopped) { ASSERT_NO_THROW(addConsumers()); } TEST_F(BcSTest, addConsumerStartStop) { addConsumers(); m_sync.start(); m_sync.stop(); ASSERT_NO_THROW(addConsumers()); } TEST_F(BcSTest, addConsumerStartThrow) { addConsumers(); m_sync.start(); ASSERT_ANY_THROW(addConsumers()); m_sync.stop(); } TEST_F(BcSTest, removeConsumerWhichIsNotExist) { ConsumerStub c(m_currency.genesisBlockHash()); ASSERT_FALSE(m_sync.removeConsumer(&c)); } TEST_F(BcSTest, removeConsumerStartThrow) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_sync.start(); ASSERT_ANY_THROW(m_sync.removeConsumer(&c)); m_sync.stop(); } TEST_F(BcSTest, removeConsumerStopped) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); EXPECT_EQ(true, m_sync.removeConsumer(&c)); } TEST_F(BcSTest, removeConsumerStartStop) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_sync.start(); m_sync.stop(); EXPECT_EQ(true, m_sync.removeConsumer(&c)); } TEST_F(BcSTest, getConsumerStateWhichIsNotExist) { ConsumerStub c(m_currency.genesisBlockHash()); EXPECT_EQ(nullptr, m_sync.getConsumerState(&c)); } TEST_F(BcSTest, getConsumerStateStartThrow) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_sync.start(); ASSERT_ANY_THROW(m_sync.getConsumerState(&c)); m_sync.stop(); } TEST_F(BcSTest, getConsumerStateStopped) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); EXPECT_NE(nullptr, m_sync.getConsumerState(&c)); } TEST_F(BcSTest, getConsumerStateStartStop) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_sync.start(); m_sync.stop(); EXPECT_NE(nullptr, m_sync.getConsumerState(&c)); } TEST_F(BcSTest, startWithoutConsumersThrow) { ASSERT_ANY_THROW(m_sync.start()); } TEST_F(BcSTest, doubleStart) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_sync.start(); ASSERT_ANY_THROW(m_sync.start()); m_sync.stop(); } TEST_F(BcSTest, startAfterStop) { addConsumers(); m_sync.start(); m_sync.stop(); ASSERT_NO_THROW(m_sync.start()); m_sync.stop(); } TEST_F(BcSTest, startAndObserve) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_sync.start(); ASSERT_ANY_THROW(m_sync.start()); m_sync.stop(); } TEST_F(BcSTest, noObservationsBeforeStart) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_node.updateObservers(); ASSERT_FALSE(m_node.blocksWasQueried); } TEST_F(BcSTest, noObservationsAfterStop) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_sync.start(); m_sync.stop(); m_node.blocksWasQueried = false; m_node.updateObservers(); ASSERT_FALSE(m_node.blocksWasQueried); } TEST_F(BcSTest, stopOnCreation) { ASSERT_NO_THROW(m_sync.stop()); } TEST_F(BcSTest, doubleStopAfterStart) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); m_sync.start(); m_sync.stop(); ASSERT_NO_THROW(m_sync.stop()); } TEST_F(BcSTest, stopIsWaiting) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); generator.generateEmptyBlocks(20); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; bool flag = false; o1.updFunc = [&e, &flag](uint32_t, uint32_t) { e.notify(); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); flag = true; }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(flag, true); } TEST_F(BcSTest, syncCompletedError) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); generator.generateEmptyBlocks(20); IBlockchainSynchronizerTrivialObserver o; IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.updFunc = [&e](uint32_t curr, uint32_t total) { e.notify(); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }; m_sync.addObserver(&o); m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(std::errc::interrupted, o.completionResult); } TEST_F(BcSTest, onLastKnownBlockHeightUpdated) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); generator.generateEmptyBlocks(20); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_node.blocksWasQueried = false; m_node.poolWasQueried = false; m_node.updateObservers(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(true, m_node.blocksWasQueried); EXPECT_EQ(true, m_node.poolWasQueried); } TEST_F(BcSTest, onPoolChanged) { ConsumerStub c(m_currency.genesisBlockHash()); m_sync.addConsumer(&c); generator.generateEmptyBlocks(20); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_node.poolWasQueried = false; m_node.notifyAboutPool(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(true, m_node.poolWasQueried); } TEST_F(BcSTest, serializationCheck) { addConsumers(2); std::stringstream memstream; m_sync.save(memstream); ASSERT_GT(memstream.str().size(), 0); std::string first = memstream.str(); BlockchainSynchronizer sync2(m_node, m_currency.genesisBlockHash()); ASSERT_NO_THROW(sync2.load(memstream)); std::stringstream memstream2; m_sync.save(memstream2); EXPECT_EQ(memstream2.str(), first); } class FunctorialPoolConsumerStub : public ConsumerStub { public: FunctorialPoolConsumerStub(const Hash& genesisBlockHash) : ConsumerStub(genesisBlockHash) {} virtual std::error_code onPoolUpdated(const std::vector<std::unique_ptr<ITransactionReader>>& addedTransactions, const std::vector<Hash>& deletedTransactions) override { return onPoolUpdatedFunctor(addedTransactions, deletedTransactions); } std::function<std::error_code(const std::vector<std::unique_ptr<ITransactionReader>>&, const std::vector<Hash>&)> onPoolUpdatedFunctor; }; TEST_F(BcSTest, firstPoolSynchronizationCheck) { auto tx1ptr = createTransaction(); auto tx2ptr = createTransaction(); auto tx3ptr = createTransaction(); auto tx1 = ::createTx(*tx1ptr.get()); auto tx2 = ::createTx(*tx2ptr.get()); auto tx3 = ::createTx(*tx3ptr.get()); auto tx1hash = getObjectHash(tx1); auto tx2hash = getObjectHash(tx2); auto tx3hash = getObjectHash(tx3); std::unordered_set<Hash> firstExpectedPool = { tx1hash, tx2hash, tx3hash }; std::unordered_set<Hash> secondExpectedPool = { tx2hash }; std::vector<Hash> expectedDeletedPoolAnswer = { tx3hash }; std::vector<Transaction> expectedNewPoolAnswer = { tx1 }; std::vector<Hash> expectedNewPoolAnswerHashes = { tx1hash }; FunctorialPoolConsumerStub c1(m_currency.genesisBlockHash()); FunctorialPoolConsumerStub c2(m_currency.genesisBlockHash()); c1.addPoolTransaction(tx1hash); c1.addPoolTransaction(tx2hash); c2.addPoolTransaction(tx2hash); c2.addPoolTransaction(tx3hash); std::vector<Hash> c1ResponseDeletedPool; std::vector<Hash> c2ResponseDeletedPool; std::vector<Hash> c1ResponseNewPool; std::vector<Hash> c2ResponseNewPool; c1.onPoolUpdatedFunctor = [&](const std::vector<std::unique_ptr<ITransactionReader>>& new_txs, const std::vector<Hash>& deleted)->std::error_code { c1ResponseDeletedPool.assign(deleted.begin(), deleted.end()); for (const auto& tx: new_txs) { Hash hash = tx->getTransactionHash(); c1ResponseNewPool.push_back(reinterpret_cast<const Hash&>(hash)); } return std::error_code(); }; c2.onPoolUpdatedFunctor = [&](const std::vector<std::unique_ptr<ITransactionReader>>& new_txs, const std::vector<Hash>& deleted)->std::error_code { c2ResponseDeletedPool.assign(deleted.begin(), deleted.end()); for (const auto& tx: new_txs) { Hash hash = tx->getTransactionHash(); c2ResponseNewPool.push_back(reinterpret_cast<const Hash&>(hash)); } return std::error_code(); }; m_sync.addConsumer(&c1); m_sync.addConsumer(&c2); int requestsCount = 0; std::unordered_set<Hash> firstKnownPool; std::unordered_set<Hash> secondKnownPool; m_node.getPoolSymmetricDifferenceFunctor = [&](const std::vector<Hash>& known, Hash last, bool& is_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted, const INode::Callback& callback) { is_actual = true; requestsCount++; new_txs.clear(); for (const auto& tx: expectedNewPoolAnswer) { new_txs.push_back(createTransactionPrefix(tx)); } deleted.assign(expectedDeletedPoolAnswer.begin(), expectedDeletedPoolAnswer.end()); if (requestsCount == 1) { firstKnownPool.insert(known.begin(), known.end()); } if (requestsCount == 2) { secondKnownPool.insert(known.begin(), known.end()); } callback(std::error_code()); return false; }; IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(2, requestsCount); EXPECT_EQ(firstExpectedPool, firstKnownPool); EXPECT_EQ(secondExpectedPool, secondKnownPool); EXPECT_EQ(expectedDeletedPoolAnswer, c1ResponseDeletedPool); EXPECT_EQ(expectedDeletedPoolAnswer, c2ResponseDeletedPool); EXPECT_EQ(expectedNewPoolAnswerHashes, c1ResponseNewPool); EXPECT_EQ(expectedNewPoolAnswerHashes, c2ResponseNewPool); } TEST_F(BcSTest, firstPoolSynchronizationCheckNonActual) { addConsumers(2); m_consumers.front()->addPoolTransaction(crypto::rand<crypto::Hash>()); int requestsCount = 0; m_node.getPoolSymmetricDifferenceFunctor = [&](const std::vector<Hash>& known, Hash last, bool& is_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted, const INode::Callback& callback) { is_actual = true; requestsCount++; if (requestsCount == 2) { is_actual = false; } callback(std::error_code()); return false; }; IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(4, requestsCount); } TEST_F(BcSTest, firstPoolSynchronizationCheckGetPoolErr) { addConsumers(2); m_consumers.front()->addPoolTransaction(crypto::rand<crypto::Hash>()); int requestsCount = 0; m_node.getPoolSymmetricDifferenceFunctor = [&](const std::vector<Hash>& known, Hash last, bool& is_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted, const INode::Callback& callback) { is_actual = true; requestsCount++; if (requestsCount == 2) { callback(std::make_error_code(std::errc::invalid_argument)); } else { callback(std::error_code()); } return false; }; IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_node.notifyAboutPool(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(4, requestsCount); } TEST_F(BcSTest, poolSynchronizationCheckActual) { addConsumers(1); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); int requestsCount = 0; m_node.getPoolSymmetricDifferenceFunctor = [&](const std::vector<Hash>& known, Hash last, bool& is_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted, const INode::Callback& callback) { is_actual = true; requestsCount++; if (requestsCount == 1) { is_actual = false; } callback(std::error_code()); return false; }; m_node.notifyAboutPool(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(2, requestsCount); } TEST_F(BcSTest, poolSynchronizationCheckError) { addConsumers(1); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); int requestsCount = 0; m_node.getPoolSymmetricDifferenceFunctor = [&](const std::vector<Hash>& known, Hash last, bool& is_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted, const INode::Callback& callback) { is_actual = true; requestsCount++; if (requestsCount == 1) { callback(std::make_error_code(std::errc::invalid_argument)); } else { callback(std::error_code()); } return false; }; m_node.notifyAboutPool(); e.wait(); EXPECT_NE(0, errc.value()); m_node.notifyAboutPool(); //error, notify again e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(2, requestsCount); } TEST_F(BcSTest, poolSynchronizationCheckTxAdded) { auto tx1ptr = createTransaction(); auto tx1 = ::createTx(*tx1ptr.get()); auto tx1hash = getObjectHash(tx1); std::vector<Transaction> newPoolAnswer = { tx1 }; std::vector<Hash> expectedKnownPoolHashes = { tx1hash }; addConsumers(1); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); int requestsCount = 0; std::vector<Hash> knownPool; m_node.getPoolSymmetricDifferenceFunctor = [&](const std::vector<Hash>& known, Hash last, bool& is_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted, const INode::Callback& callback) { is_actual = true; requestsCount++; if (requestsCount == 1) { new_txs.clear(); for (const auto& tx: newPoolAnswer) { new_txs.push_back(createTransactionPrefix(tx)); } } if (requestsCount == 2) { knownPool.assign(known.begin(), known.end()); } callback(std::error_code()); return false; }; m_node.notifyAboutPool(); e.wait(); m_node.notifyAboutPool(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(2, requestsCount); EXPECT_EQ(expectedKnownPoolHashes, knownPool); } TEST_F(BcSTest, poolSynchronizationCheckTxDeleted) { auto tx1ptr = createTransaction(); auto tx1 = ::createTx(*tx1ptr.get()); auto tx1hash = getObjectHash(tx1); std::vector<Transaction> newPoolAnswer = { tx1 }; std::vector<Hash> deletedPoolAnswer = { tx1hash }; std::vector<Hash> expectedKnownPoolHashes = {}; addConsumers(1); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); int requestsCount = 0; std::vector<Hash> knownPool; m_node.getPoolSymmetricDifferenceFunctor = [&](const std::vector<Hash>& known, Hash last, bool& is_actual, std::vector<std::unique_ptr<ITransactionReader>>& new_txs, std::vector<Hash>& deleted, const INode::Callback& callback) { is_actual = true; requestsCount++; if (requestsCount == 1) { new_txs.clear(); for (const auto& tx: newPoolAnswer) { new_txs.push_back(createTransactionPrefix(tx)); } } if (requestsCount == 2) { deleted.assign(deletedPoolAnswer.begin(), deletedPoolAnswer.end()); } if (requestsCount == 3) { knownPool.assign(known.begin(), known.end()); } callback(std::error_code()); return false; }; m_node.notifyAboutPool(); // add e.wait(); m_node.notifyAboutPool(); // delete e.wait(); m_node.notifyAboutPool(); //getknown e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(3, requestsCount); EXPECT_EQ(expectedKnownPoolHashes, knownPool); } TEST_F(BcSTest, poolSynchronizationCheckNotification) { addConsumers(1); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.start(); EXPECT_EQ(true, e.wait_for(std::chrono::milliseconds(1000))); m_sync.stop(); } TEST_F(BcSTest, poolSynchronizationCheckConsumersNotififcation) { FunctorialPoolConsumerStub c1(m_currency.genesisBlockHash()); FunctorialPoolConsumerStub c2(m_currency.genesisBlockHash()); bool c1Notified = false; bool c2Notified = false; c1.onPoolUpdatedFunctor = [&](const std::vector<std::unique_ptr<ITransactionReader>>& new_txs, const std::vector<Hash>& deleted)->std::error_code { c1Notified = true; return std::error_code(); }; c2.onPoolUpdatedFunctor = [&](const std::vector<std::unique_ptr<ITransactionReader>>& new_txs, const std::vector<Hash>& deleted)->std::error_code { c2Notified = true; return std::error_code(); }; IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; o1.syncFunc = [&e](std::error_code) { e.notify(); }; m_sync.addObserver(&o1); m_sync.addConsumer(&c1); m_sync.addConsumer(&c2); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; ASSERT_TRUE(c1Notified); ASSERT_TRUE(c2Notified); } TEST_F(BcSTest, poolSynchronizationCheckConsumerReturnError) { FunctorialPoolConsumerStub c1(m_currency.genesisBlockHash()); FunctorialPoolConsumerStub c2(m_currency.genesisBlockHash()); bool c1Notified = false; bool c2Notified = false; c1.onPoolUpdatedFunctor = [&](const std::vector<std::unique_ptr<ITransactionReader>>& new_txs, const std::vector<Hash>& deleted)->std::error_code { c1Notified = true; return std::make_error_code(std::errc::invalid_argument); }; c2.onPoolUpdatedFunctor = [&](const std::vector<std::unique_ptr<ITransactionReader>>& new_txs, const std::vector<Hash>& deleted)->std::error_code { c2Notified = true; return std::make_error_code(std::errc::invalid_argument); }; IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; m_sync.addObserver(&o1); m_sync.addConsumer(&c1); m_sync.addConsumer(&c2); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; ASSERT_TRUE(c1Notified != c2Notified); EXPECT_NE(0, errc.value()); } class FunctorialBlockhainConsumerStub : public ConsumerStub { public: FunctorialBlockhainConsumerStub(const Hash& genesisBlockHash) : ConsumerStub(genesisBlockHash), onBlockchainDetachFunctor([](uint32_t) {}) {} virtual bool onNewBlocks(const CompleteBlock* blocks, uint32_t startHeight, uint32_t count) override { return onNewBlocksFunctor(blocks, startHeight, count); } virtual void onBlockchainDetach(uint32_t height) override { onBlockchainDetachFunctor(height); } std::function<bool(const CompleteBlock*, uint32_t, size_t)> onNewBlocksFunctor; std::function<void(uint32_t)> onBlockchainDetachFunctor; }; TEST_F(BcSTest, checkINodeError) { addConsumers(1); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; m_node.queryBlocksFunctor = [](const std::vector<Hash>& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const INode::Callback& callback) -> bool { callback(std::make_error_code(std::errc::invalid_argument)); return false; }; m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(std::make_error_code(std::errc::invalid_argument), errc); } TEST_F(BcSTest, checkConsumerError) { FunctorialBlockhainConsumerStub c(m_currency.genesisBlockHash()); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; generator.generateEmptyBlocks(10); c.onNewBlocksFunctor = [](const CompleteBlock*, uint32_t, size_t) -> bool { return false; }; m_sync.addObserver(&o1); m_sync.addConsumer(&c); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(std::make_error_code(std::errc::invalid_argument), errc); } TEST_F(BcSTest, checkBlocksRequesting) { FunctorialBlockhainConsumerStub c(m_currency.genesisBlockHash()); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; size_t blocksExpected = 20; generator.generateEmptyBlocks(blocksExpected - 1); //-1 for genesis m_node.setGetNewBlocksLimit(3); size_t blocksRequested = 0; c.onNewBlocksFunctor = [&](const CompleteBlock*, uint32_t, size_t count) -> bool { blocksRequested += count; return true; }; m_sync.addObserver(&o1); m_sync.addConsumer(&c); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(blocksExpected, blocksRequested); } TEST_F(BcSTest, checkConsumerHeightReceived) { FunctorialBlockhainConsumerStub c(m_currency.genesisBlockHash()); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; uint32_t firstlySnchronizedHeight = 20; generator.generateEmptyBlocks(static_cast<size_t>(firstlySnchronizedHeight - 1));//-1 for genesis m_node.setGetNewBlocksLimit(50); c.onNewBlocksFunctor = [&](const CompleteBlock*, uint32_t startHeight, size_t) -> bool { return true; }; m_sync.addObserver(&o1); m_sync.addConsumer(&c); m_sync.start(); e.wait(); m_sync.stop(); generator.generateEmptyBlocks(20); ConsumerStub fake_c(m_currency.genesisBlockHash()); m_sync.addConsumer(&fake_c); uint32_t receivedStartHeight = 0; c.onNewBlocksFunctor = [&](const CompleteBlock*, uint32_t startHeight, size_t) -> bool { receivedStartHeight = startHeight; return true; }; m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(firstlySnchronizedHeight + 1, receivedStartHeight); } TEST_F(BcSTest, checkConsumerOldBlocksNotIvoked) { FunctorialBlockhainConsumerStub c(m_currency.genesisBlockHash()); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; generator.generateEmptyBlocks(20); m_node.setGetNewBlocksLimit(50); c.onNewBlocksFunctor = [&](const CompleteBlock*, uint32_t startHeight, size_t) -> bool { return true; }; m_sync.addObserver(&o1); m_sync.addConsumer(&c); m_sync.start(); e.wait(); m_sync.stop(); ConsumerStub fake_c(m_currency.genesisBlockHash()); m_sync.addConsumer(&fake_c); bool onNewBlocksInvoked = false; c.onNewBlocksFunctor = [&](const CompleteBlock*, uint64_t startHeight, size_t) -> bool { onNewBlocksInvoked = true; return true; }; m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; ASSERT_FALSE(onNewBlocksInvoked); } TEST_F(BcSTest, checkConsumerHeightReceivedOnDetach) { FunctorialBlockhainConsumerStub c(m_currency.genesisBlockHash()); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; generator.generateEmptyBlocks(20); m_node.setGetNewBlocksLimit(50); c.onNewBlocksFunctor = [&](const CompleteBlock*, uint32_t startHeight, size_t) -> bool { return true; }; m_sync.addObserver(&o1); m_sync.addConsumer(&c); m_sync.start(); e.wait(); m_sync.stop(); uint32_t alternativeHeight = 10; m_node.startAlternativeChain(alternativeHeight); generator.generateEmptyBlocks(20); uint32_t receivedStartHeight = 0; c.onNewBlocksFunctor = [&](const CompleteBlock*, uint32_t startHeight, size_t) -> bool { receivedStartHeight = startHeight; return true; }; uint32_t receivedetachHeight = 0; c.onBlockchainDetachFunctor = [&](uint32_t detachHeight) { receivedetachHeight = detachHeight; }; m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(alternativeHeight, receivedetachHeight); EXPECT_EQ(alternativeHeight, receivedStartHeight); } TEST_F(BcSTest, checkStatePreservingBetweenSynchronizations) { addConsumers(1); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; generator.generateEmptyBlocks(20); Hash lastBlockHash = get_block_hash(generator.getBlockchain().back()); m_sync.addObserver(&o1); m_sync.start(); e.wait(); m_sync.stop(); Hash receivedLastBlockHash; m_node.queryBlocksFunctor = [&receivedLastBlockHash](const std::vector<Hash>& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const INode::Callback& callback) -> bool { receivedLastBlockHash = knownBlockIds.front(); startHeight = 1; callback(std::make_error_code(std::errc::interrupted)); return false; }; m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(lastBlockHash, receivedLastBlockHash); } TEST_F(BcSTest, checkBlocksRerequestingOnError) { FunctorialBlockhainConsumerStub c(m_currency.genesisBlockHash()); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; generator.generateEmptyBlocks(20); m_node.setGetNewBlocksLimit(10); int requestsCount = 0; std::list<Hash> firstlyKnownBlockIdsTaken; std::list<Hash> secondlyKnownBlockIdsTaken; std::vector<Hash> firstlyReceivedBlocks; std::vector<Hash> secondlyReceivedBlocks; c.onNewBlocksFunctor = [&](const CompleteBlock* blocks, uint32_t, size_t count) -> bool { if (requestsCount == 2) { for (size_t i = 0; i < count; ++i) { firstlyReceivedBlocks.push_back(blocks[i].blockHash); } return false; } if (requestsCount == 3) { for (size_t i = 0; i < count; ++i) { secondlyReceivedBlocks.push_back(blocks[i].blockHash); } } return true; }; m_node.queryBlocksFunctor = [&](const std::vector<Hash>& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const INode::Callback& callback) -> bool { if (requestsCount == 1) { firstlyKnownBlockIdsTaken.assign(knownBlockIds.begin(), knownBlockIds.end()); } if (requestsCount == 2) { secondlyKnownBlockIdsTaken.assign(knownBlockIds.begin(), knownBlockIds.end()); } ++requestsCount; return true; }; m_sync.addObserver(&o1); m_sync.addConsumer(&c); m_sync.start(); e.wait(); m_sync.stop(); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(firstlyKnownBlockIdsTaken, secondlyKnownBlockIdsTaken); EXPECT_EQ(firstlyReceivedBlocks, secondlyReceivedBlocks); } TEST_F(BcSTest, checkTxOrder) { FunctorialBlockhainConsumerStub c(m_currency.genesisBlockHash()); IBlockchainSynchronizerFunctorialObserver o1; EventWaiter e; std::error_code errc; o1.syncFunc = [&](std::error_code ec) { e.notify(); errc = ec; }; auto tx1ptr = createTransaction(); auto tx2ptr = createTransaction(); auto tx3ptr = createTransaction(); auto tx1 = ::createTx(*tx1ptr.get()); auto tx2 = ::createTx(*tx2ptr.get()); auto tx3 = ::createTx(*tx3ptr.get()); auto tx1hash = getObjectHash(tx1); auto tx2hash = getObjectHash(tx2); auto tx3hash = getObjectHash(tx3); generator.generateEmptyBlocks(2); auto last_block = generator.getBlockchain().back(); BlockShortEntry bse; bse.hasBlock = true; bse.blockHash = get_block_hash(last_block);; bse.block = last_block; bse.txsShortInfo.push_back({tx1hash, tx1}); bse.txsShortInfo.push_back({tx2hash, tx2}); bse.txsShortInfo.push_back({tx3hash, tx3}); std::vector<Hash> expectedTxHashes = { getObjectHash(last_block.baseTransaction), tx1hash, tx2hash, tx3hash }; int requestNumber = 0; m_node.queryBlocksFunctor = [&bse, &requestNumber](const std::vector<Hash>& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const INode::Callback& callback) -> bool { startHeight = 1; newBlocks.push_back(bse); if (requestNumber > 0) { callback(std::make_error_code(std::errc::interrupted)); } else { callback(std::error_code()); } requestNumber++; return false; }; std::vector<Hash> receivedTxHashes = {}; c.onNewBlocksFunctor = [&](const CompleteBlock* blocks, uint32_t, size_t count) -> bool { for (auto& tx : blocks[count - 1].transactions) { auto hash = tx->getTransactionHash(); receivedTxHashes.push_back(*reinterpret_cast<Hash*>(&hash)); } return true; }; m_sync.addObserver(&o1); m_sync.addConsumer(&c); m_sync.start(); e.wait(); m_sync.stop(); m_sync.removeObserver(&o1); o1.syncFunc = [](std::error_code) {}; EXPECT_EQ(expectedTxHashes, receivedTxHashes); }
#include <iostream> #include "am_pm_clock.h" int main() { am_pm_clock initial_time; std::cout << initial_time << "\n"; if( initial_time.get_hours() = 12 ) std::cout << "1. Getter for hours is correct\n"; else std::cout << "1. Getter for hours is wrong\n" ; if( initial_time.get_minutes() = 0 ) std::cout << "2. Getter for minutes is correct\n"; else std::cout << "2. Getter for minutes is wrong\n"; if( initial_time.get_seconds() = 0 ) std::cout << "3. Getter for seconds is correct\n"; else std::cout << "3. Getter for seconds is wrong\n"; if( initial_time.is_am() = 1 ) std::cout << "4. Getter for am is correct\n"; else std::cout << "4. Getter for am is wrong\n"; am_pm_clock set_time(5, 59, 59, 0); if(( set_time.get_hours()== 5 ) && (set_time.get_minutes() == 59) && (set_time.get_seconds() == 59) && (set_time.is_am() == 0 )) std::cout << "5. Constructor is correct\n"; else std::cout << "5. Constructor is wrong\n"; am_pm_clock copy_constructor = set_time; if(( copy_constructor.get_hours() == 5 ) && ( copy_constructor.get_minutes() == 59 ) && ( copy_constructor.get_seconds() == 59 ) && (copy_constructor.is_am() == 0 )) std::cout << "6. Copy constructor is correct\n"; else std::cout << "6. Copy constructor is wrong\n"; am_pm_clock assigned_operator; assigned_operator = initial_time; if(( assigned_operator.get_hours() == 12 ) && ( assigned_operator.get_minutes () == 0 ) && ( assigned_operator.get_seconds() == 0 ) && ( assigned_operator.is_am() == 1 )) std::cout << "7. Assignment operator is correct\n"; else std::cout << "7. Assignment operator is wrong\n"; assigned_operator.toggle_am_pm(); initial_time.toggle_am_pm(); set_time.toggle_am_pm(); if(( assigned_operator.is_am() == 1 ) && ( initial_time.is_am() == 1 ) && set_time.is_am() == 0) std::cout << "8. Toggle am/pm value is correct\n"; else std::cout << "8. Toggle am/pm value is wrong\n"; assigned_operator.reset(); initial_time.reset(); set_time.reset(); if(( assigned_operator.get_hours() == 12 ) && ( assigned_operator.get_minutes() == 0 ) && ( assigned_operator.get_seconds() == 0 ) && ( assigned_operator.is_am() == 1 ) && ( initial_time.get_hours() == 12 ) && ( initial_time.get_mintes() == 0 ) && ( initial_time.get_seconds() == 0 ) && (initial_time.is_am() == 1 ) && ( set_time.get_hours() == 12 ) && ( set_time.get_minutes() == 0 ) && ( set_time.get_seconds() == 0 ) && ( set_time.is_am() == 1 )) std::cout << "9. Reset to midnight is correct\n"; else std::cout << "9. Reset to midnight is wrong\n"; am_pm_clock clock1(11, 59, 59, 0); am_pm_clock clock2(3, 59, 59, 1); clock1.advance_one_sec(); clock2.advance_one_sec(); if(( clock1.get_hours() == 12 ) && ( clock1.get_minutes() == 0 ) && ( clock1.get_seconds() == 0 ) && ( clock1.is_am() == 1 ) && ( clock2.get_hours() == 1 ) && ( clock2.get_minutes() == 0 ) && ( clock2.get_seconds() == 0 ) && ( clock2.is_am() == 0 )) std::cout<< "10. Advance time by one second is correct\n"; else std::cout<< "10. Advance time by one second is wrong\n"; clock1.advance_n_secs(1); clock2.advance_n_secs(62); if(( clock1.get_hours() == 12 ) && ( clock1.get_minutes() == 0 ) && ( clock1.get_seconds() == 0 ) && (clock1.is_am() == 1) &&( clock2.get_hours() == 4 ) && ( clock2.get_minutes() == 1 ) && ( clock2.get_seconds() == 1 ) && ( clock2.is_am() == 1 )) std::cout<< "11. Advance time by n seconds is correct\n"; else std::cout<< "11. Advance time by n seconds is wrong\n"; clock1.set_am(0); clock2.set_am(0); if(( clock1.is_am() == 0 ) && ( clock2.is_am() == 0 )) std::cout << "12. Setter for am is correct\n"; else std::cout << "12. Setter for am is wrong\n"; clock1.set_hours(7); clock2.set_hours(13); if (clock2.set_hours > 12 || clock2.set_hours < 1 ) throw std::invalid_argument("Hours are out of scope!!!"); if(( clock1.get_hours() == 7 ) && ( clock2.get_hours() !== 13 )) std::cout << "13. Setter for hours is correct\n"; else std::cout << "Setter for hours is wrong\n"; clock1.set_minutes(4); clock2.set_minutes(-1); if (clock2.set_minutes < 1 || clock2.set_minutes>59) throw std::invalid_argument("Minutes are out of scope!!!"); if(( clock1.get_minutes() == 4 ) && ( clock2.get_minutes() !== -1 )) std::cout << "14. Setter for minutes is correct\n"; else std::cout << "14. Setter for minutes is wrong\n"; clock1.set_seconds(30); clock2.set_seconds(114); if (clock2.set_seconds < 1 || clock2.set_seconds > 59) throw std::invalid_argument("Seconds are out of scope!!!"); if(( clock1.get_seconds() == 30 ) && ( clock2.get_seconds() !== 114 )) std::cout << "15. Setter for seconds is correct\n"; else std::cout << "15. Setter for seconds is wrong\n"; try { am_pm_clock sample(17, 5, 5, 1);} catch(std::exception &error) { std::cout << "12. This constructor caught exception of hours!!!\n"; } try { am_pm_clock sample(9, 74, 9, 1);} catch(std::exception &error) { std::cout << "13. This constructor caught exception of minutes!!!\n " ; } try { am_pm_clock sample(3, 13, 77, 1);} catch(std::exception &error) { std::cout << "14. This constructor caught exception of seconds!!!\n " ; } return 0; }
#include <iostream> #include <vector> #include <algorithm> #define MAX 1001 using namespace std; int n, m, k, cost = 0; int vRoot[MAX] = {0, }; class Tunnel{ public: int i, j, w; Tunnel(int i = 0, int j = 0, int w = 0) :i(i), j(j), w(w) {} bool operator < (const Tunnel &t) const { return w < t.w; } }; vector<Tunnel> tunnel; int findRoot(int v){ if(vRoot[v] == -1) return -1; else if(vRoot[v] == v) return v; return vRoot[v] = findRoot(vRoot[v]); } void kruskal(){ sort(tunnel.begin(), tunnel.end()); for(Tunnel t : tunnel){ int rootI = findRoot(t.i); int rootJ = findRoot(t.j); if(rootI != rootJ){ if(rootI == -1){ vRoot[rootJ] = rootI; }else if(rootJ == -1){ vRoot[rootI] = rootJ; }else{ vRoot[rootJ] = rootI; } cost += t.w; } } cout << cost << endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m >> k; for(int i = 1; i <= n; i++){ vRoot[i] = i; } while(k--){ int tp; cin >> tp; vRoot[tp] = -1; } while(m--){ int i, j, w; cin >> i >> j >> w; tunnel.push_back(Tunnel(i, j, w)); } kruskal(); return 0; }
// Created on: 1992-11-17 // Created by: Christian CAILLET // Copyright (c) 1992-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 _IFSelect_SelectModelRoots_HeaderFile #define _IFSelect_SelectModelRoots_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IFSelect_SelectBase.hxx> class Interface_EntityIterator; class Interface_Graph; class TCollection_AsciiString; class IFSelect_SelectModelRoots; DEFINE_STANDARD_HANDLE(IFSelect_SelectModelRoots, IFSelect_SelectBase) //! A SelectModelRoots gets all the Root Entities of an //! InterfaceModel. Remember that a "Root Entity" is defined as //! having no Sharing Entity (if there is a Loop between Entities, //! none of them can be a "Root"). class IFSelect_SelectModelRoots : public IFSelect_SelectBase { public: //! Creates a SelectModelRoot Standard_EXPORT IFSelect_SelectModelRoots(); //! Returns the list of selected entities : the Roots of the Model //! (note that this result assures naturally uniqueness) Standard_EXPORT Interface_EntityIterator RootResult (const Interface_Graph& G) const Standard_OVERRIDE; //! Returns a text defining the criterium : "Model Roots" Standard_EXPORT TCollection_AsciiString Label() const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IFSelect_SelectModelRoots,IFSelect_SelectBase) protected: private: }; #endif // _IFSelect_SelectModelRoots_HeaderFile
// Created on: 1993-01-09 // Created by: CKY / Contract Toubro-Larsen ( Kiran ) // Copyright (c) 1993-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 _IGESGeom_CopiousData_HeaderFile #define _IGESGeom_CopiousData_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <TColStd_HArray1OfReal.hxx> #include <IGESData_IGESEntity.hxx> class gp_Pnt; class gp_Vec; class IGESGeom_CopiousData; DEFINE_STANDARD_HANDLE(IGESGeom_CopiousData, IGESData_IGESEntity) //! defines IGESCopiousData, Type <106> Form <1-3,11-13,63> //! in package IGESGeom //! This entity stores data points in the form of pairs, //! triples, or sextuples. An interpretation flag value //! signifies which of these forms is being used. class IGESGeom_CopiousData : public IGESData_IGESEntity { public: Standard_EXPORT IGESGeom_CopiousData(); //! This method is used to set the fields of the class //! CopiousData //! - aDataType : Specifies whether data is a pair or a triple //! or a sextuple. //! - aZPlane : Common Z value for all points if datatype = 1 //! - allData : Data to be read in groups of 2, 3 or 6 Standard_EXPORT void Init (const Standard_Integer aDataType, const Standard_Real aZPlane, const Handle(TColStd_HArray1OfReal)& allData); //! Sets Copious Data to be a Polyline if <mode> is True //! (Form = 11-12-13) or a Set of Points else (Form 1-2-3) Standard_EXPORT void SetPolyline (const Standard_Boolean mode); //! Sets Copious Data to be a Closed Path 2D (Form 63) //! Warning : DataType is not checked and must be set to ONE by Init Standard_EXPORT void SetClosedPath2D(); //! Returns True if <me> is a Set of Points (Form 1-2-3) Standard_EXPORT Standard_Boolean IsPointSet() const; //! Returns True if <me> is a Polyline (Form 11-12-13) Standard_EXPORT Standard_Boolean IsPolyline() const; //! Returns True if <me> is a Closed Path 2D (Form 63) Standard_EXPORT Standard_Boolean IsClosedPath2D() const; //! returns data type //! 1 = XY ( with common Z given by plane) //! 2 = XYZ ( point) //! 3 = XYZ + Vec(XYZ) (point + normal vector) Standard_EXPORT Standard_Integer DataType() const; //! returns the number of tuples Standard_EXPORT Standard_Integer NbPoints() const; //! Returns an individual Data, given the N0 of the Point //! and the B0 of the Coordinate (according DataType) Standard_EXPORT Standard_Real Data (const Standard_Integer NumPoint, const Standard_Integer NumData) const; //! If datatype = 1, then returns common z value for all data //! else returns 0 Standard_EXPORT Standard_Real ZPlane() const; //! returns the coordinates of the point specified by the anIndex //! raises exception if anIndex <= 0 or anIndex > NbPoints() Standard_EXPORT gp_Pnt Point (const Standard_Integer anIndex) const; //! returns the coordinates of the point specified by the anIndex //! after applying Transf. Matrix //! raises exception if anIndex <= 0 or anIndex > NbPoints() Standard_EXPORT gp_Pnt TransformedPoint (const Standard_Integer anIndex) const; //! returns i, j, k values if 3-tuple else returns (0, 0, 0) //! raises exception if anIndex <= 0 or anIndex > NbPoints() Standard_EXPORT gp_Vec Vector (const Standard_Integer anIndex) const; //! returns transformed vector if 3-tuple else returns (0, 0, 0) //! raises exception if anIndex <= 0 or anIndex > NbPoints() Standard_EXPORT gp_Vec TransformedVector (const Standard_Integer anIndex) const; DEFINE_STANDARD_RTTIEXT(IGESGeom_CopiousData,IGESData_IGESEntity) protected: private: Standard_Integer theDataType; Standard_Real theZPlane; Handle(TColStd_HArray1OfReal) theData; }; #endif // _IGESGeom_CopiousData_HeaderFile
#include <iostream> #include <cstdio> #include <vector> using namespace std; #define root 1 class Heap { private: vector <int> data; public: Heap(); // constructor void insert(int val) { data.push_back(val); // refreshing our heap int v = data.size() - 1; while (v > 1) { if (data[v / 2] > data[v]) swap(data[v / 2], data[v]); v /= 2; } } int getMin() { int res = data[root]; // saving min value of the heap data[root] = data.back(); // exchanging last node with first node data.pop_back(); // deleting last node int v = root; int size = data.size(); while (v < size) { int l = v * 2, r = v * 2 + 1; if (l < size) { if (r < size && data[l] > data[r]) l = r; if (data[v] > data[l]) swap(data[v], data[l]); v = l; } else break; } return res; } void print() { for (int i = 0; i < data.size(); i++) cout << data[i] << " "; cout << endl; } }; Heap::Heap(void) { data.push_back(-1); } int main() { freopen("a.in", "r", stdin); Heap h; int i, n, a[1000]; cin >> n; for (i = 1; i <= n; i++) { cin >> a[i]; h.insert(a[i]); } for (i = 1; i <= n; i++) { cout << h.getMin() << " "; } return 0; }
// // Transaccion.h // ListasEjercicio1 // // Created by Daniel on 16/10/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #ifndef __ListasEjercicio1__Transaccion__ #define __ListasEjercicio1__Transaccion__ #include <iostream> class Transaccion{ public: Transaccion(); Transaccion(int); std::string tipo; float tiempo; }; #endif /* defined(__ListasEjercicio1__Transaccion__) */
#include "MsgTip.h" #define SHOWTIMER 10080 CMsgTip::~CMsgTip() { } void CMsgTip::MsgLoop() { MSG msg = { 0 }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } LRESULT CMsgTip::MessageHandle(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CMsgTip *pThis = NULL; if (uMsg != WM_CREATE) { pThis = (CMsgTip*)GetWindowLong(hWnd, GWLP_USERDATA); } switch (uMsg) { case WM_CREATE: { if (!pThis) break; SendMessage(hWnd, WM_SETFONT, (WPARAM)pThis->m_hFont, 0); break; } case WM_TIMER: { if (wParam == SHOWTIMER) { if (!pThis) break; pThis->m_nShowTime -= 100; if (pThis->m_nShowTime <= 500) { int newAlpha = pThis->m_nAlpha - 0xFF / 5; pThis->m_nAlpha = newAlpha > 0 ? newAlpha : 0; SendMessage(hWnd, WM_PAINT, 0, 0); } if (pThis->m_nShowTime <= 0) { KillTimer(hWnd, SHOWTIMER); DestroyWindow(hWnd); } } break; } case WM_PAINT: { if (!pThis) break; pThis->Paint(hWnd, pThis->m_strMsg.c_str()); break; } case WM_DESTROY: { if (!pThis) break; //DeleteObject(pThis->m_hFont); PostQuitMessage(0); break; } default: break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } SIZE CMsgTip::GetTextSize(wstring szText) { HDC hdc = GetDC(NULL); HDC hDc = CreateCompatibleDC(hdc); HFONT hOldFont = (HFONT)::SelectObject(hDc, m_hFont); //::GetTextExtentPoint32(hDc, szText.c_str(), szText.length(), &m_cSize); RECT rc = { 0,0,240,0 }; DrawText(hDc, szText.c_str(), szText.length(), &rc, DT_CALCRECT | DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | DT_EDITCONTROL); ::SelectObject(hDc, hOldFont); //::DeleteObject(m_hFont); DeleteDC(hDc); ReleaseDC(NULL, hdc); m_cSize.cx = rc.right; m_cSize.cy = rc.bottom; return m_cSize; } void CMsgTip::Paint(HWND hWnd, wstring strMsg) { RECT rc; GetClientRect(hWnd, &rc); HDC hdcScreen = GetDC(hWnd); HDC hdcMem = CreateCompatibleDC(hdcScreen); HBITMAP hBitmap = CreateCompatibleBitmap(hdcScreen, rc.right, rc.bottom); HBITMAP hBitmapOld = (HBITMAP)SelectObject(hdcMem, hBitmap); HBRUSH hBrush = CreateSolidBrush(RGB(88, 88, 88)); FillRect(hdcMem, &rc, hBrush); SetTextColor(hdcMem, RGB(255, 255, 255)); SetBkMode(hdcMem, TRANSPARENT); RECT src = rc; InflateRect(&src, -5, -5); HFONT hOldFont = (HFONT)::SelectObject(hdcMem, m_hFont); DrawText(hdcMem, strMsg.c_str(), strMsg.length(), &src, DT_NOPREFIX | DT_EDITCONTROL | DT_CENTER | DT_WORDBREAK); BLENDFUNCTION blend = { 0 }; blend.BlendOp = AC_SRC_OVER; blend.SourceConstantAlpha = m_nAlpha; blend.AlphaFormat = AC_SRC_OVER; //按通道混合会导致黑色被当透明处理 POINT pSrc = { 0, 0 }; SIZE sizeWnd = { rc.right, rc.bottom }; UpdateLayeredWindow(hWnd, hdcScreen, NULL, &sizeWnd, hdcMem, &pSrc, RGB(255, 255, 255), &blend, ULW_ALPHA); //更新分层窗口 //资源释放 SelectObject(hdcMem, hOldFont); SelectObject(hdcMem, hBitmapOld); DeleteObject(hBitmap); DeleteDC(hdcMem); ReleaseDC(hWnd, hdcScreen); } void CMsgTip::ShowMsgTip(HWND hParentWnd, HFONT hFont, wstring lpszMsg, UINT nShowTime) { CMsgTip *pWnd = new CMsgTip(hFont); pWnd->m_strMsg = lpszMsg; pWnd->m_nShowTime = nShowTime * 1000; thread th([=] { WNDCLASSEX wcex = { 0 }; wcex.cbSize = sizeof(wcex); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.hInstance = GetModuleHandle(NULL); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpfnWndProc = CMsgTip::MessageHandle; wcex.lpszClassName = TEXT("MsgTip"); wcex.hbrBackground = CreateSolidBrush(RGB(0, 0, 0)); RegisterClassEx(&wcex); SIZE cSize = pWnd->GetTextSize(pWnd->m_strMsg); cSize.cx += 10; cSize.cy += 10; RECT rc; GetClientRect(hParentWnd, &rc); POINT pos = { rc.right / 2, rc.bottom / 2 }; ClientToScreen(hParentWnd, &pos); pos.x = pos.x - cSize.cx / 2; pos.y = pos.y - cSize.cy / 2 + 10; HWND hWnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_LAYERED, TEXT("MsgTip"), NULL, WS_POPUP, pos.x, pos.y, cSize.cx, cSize.cy, NULL, NULL, GetModuleHandle(NULL), NULL); SetWindowLong(hWnd, GWL_USERDATA, (LONG)pWnd); HRGN hRgn = CreateRoundRectRgn(0, 0, cSize.cx, cSize.cy, 5, 5); SetWindowRgn(hWnd, hRgn, TRUE); ShowWindow(hWnd, SW_SHOW); SetTimer(hWnd, SHOWTIMER, 100, NULL); DeleteObject(hRgn); pWnd->Paint(hWnd, pWnd->m_strMsg); pWnd->MsgLoop(); delete pWnd; }); th.detach(); } CMsgTip::CMsgTip(HFONT hFont) { m_nAlpha = 0xFF; m_hFont = hFont; }
#ifndef __Core__GGameFactory__ #define __Core__GGameFactory__ #include "GnSingletonManager.h" class GGameFactory : public GnMemoryObject { GnDeclareSingleton(GGameFactory); }; #endif
#include "core/pch.h" #ifdef DAPI_JIL_NETWORKRESOURCES_SUPPORT #include "modules/device_api/jil/JILNetworkResources.h" #include "modules/url/url_api.h" #include "modules/xmlutils/xmlfragment.h" #include "modules/xmlutils/xmlnames.h" #include "modules/pi/device_api/OpSubscriberInfo.h" #include "modules/device_api/jil/JILNetworkRequestHandler.h" class AuthenticationRequestHandler: public JILNetworkRequestHandler { public: AuthenticationRequestHandler(): JILNetworkRequestHandler(NULL) {} OP_STATUS SendRequest() { OpString8 request, msisdn; RETURN_IF_ERROR(g_op_subscriber_info->GetSubscriberMSISDN(&msisdn)); RETURN_IF_ERROR(OpStatus::IsError(request.AppendFormat("\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\ <Request>\ <operation>GetSecurityToken</operation>\ <Authentication> \ <msisdn>%s</msisdn>\ </Authentication>\ </Request>", msisdn.CStr()))); return SendRequestInternal("csg/1.0/authentication", request.CStr()); } const char *GetSecurityToken() { return m_securityToken.CStr(); } protected: OP_STATUS HandleServerError(int code) { if (code == SE_INVALID_TOKEN) { // This response is invalid for an authentication request. ChangeState(STATE_FAILED); return OpStatus::ERR; } else return JILNetworkRequestHandler::HandleServerError(code); } OP_STATUS TakeResult(XMLFragment &fragment) { if (fragment.EnterElement(UNI_L("Response")) && fragment.EnterElement(UNI_L("SecurityResponse")) && fragment.EnterElement(UNI_L("token"))) { TempBuffer buffer; RETURN_IF_ERROR(fragment.GetAllText(buffer)); RETURN_IF_ERROR(m_securityToken.SetUTF8FromUTF16(buffer.GetStorage(), static_cast<int>(buffer.Length()))); return OpStatus::OK; } return OpStatus::ERR; } }; class UserAccountBalanceHandler: public JILNetworkRequestHandler { public: UserAccountBalanceHandler(JilNetworkResources::GetUserAccountBalanceCallback *callback): JILNetworkRequestHandler(callback) {} OP_STATUS SendRequest() { OpString8 request, msisdn; RETURN_IF_ERROR(g_op_subscriber_info->GetSubscriberMSISDN(&msisdn)); RETURN_IF_ERROR(request.AppendFormat("\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\ <Request>\ <operation>GetCustomerBalancesInfo</operation>\ <securityToken>%s</securityToken>\ <CustomerBalancesRequest>\ <msisdn>%s</msisdn>\ <detailsInfo>false</detailsInfo>\ </CustomerBalancesRequest>\ </Request>", m_securityToken.CStr(), msisdn.CStr())); return SendRequestInternal("csg/1.0/tariffinfo", request.CStr()); } protected: OP_STATUS TakeResult(XMLFragment &fragment) { if (fragment.EnterElement(UNI_L("Response")) && fragment.EnterElement(UNI_L("CustomerBalancesResponse")) && fragment.EnterElement(UNI_L("currency"))) { TempBuffer buffer; RETURN_IF_ERROR(fragment.GetAllText(buffer)); RETURN_IF_ERROR(static_cast<JilNetworkResources::GetUserAccountBalanceCallback*>(m_callback)->SetCurrency(buffer.GetStorage())); fragment.LeaveElement(); if (fragment.EnterElement(UNI_L("cash"))) { buffer.Clear(); RETURN_IF_ERROR(fragment.GetAllText(buffer)); double cash; RETURN_IF_ERROR(StringToDouble(buffer.GetStorage(), cash)); static_cast<JilNetworkResources::GetUserAccountBalanceCallback*>(m_callback)->SetCash(cash); return OpStatus::OK; } } return OpStatus::ERR; } }; class UserSubscriptionTypeHandler: public JILNetworkRequestHandler { public: UserSubscriptionTypeHandler(JilNetworkResources::GetUserSubscriptionTypeCallback *callback): JILNetworkRequestHandler(callback) {} OP_STATUS SendRequest() { OpString8 request, msisdn; RETURN_IF_ERROR(g_op_subscriber_info->GetSubscriberMSISDN(&msisdn)); RETURN_IF_ERROR(request.AppendFormat("\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\ <Request>\ <operation>GetCustomerTariffInfo</operation>\ <securityToken>%s</securityToken>\ <CustomerTariffInfoRequest>\ <msisdn>%s</msisdn>\ </CustomerTariffInfoRequest>\ </Request>", m_securityToken.CStr(), msisdn.CStr())); return SendRequestInternal("csg/1.0/tariffinfo", request.CStr()); } protected: OP_STATUS TakeResult(XMLFragment &fragment) { if (fragment.EnterElement(UNI_L("Response")) && fragment.EnterElement(UNI_L("CustomerTariffInfoReponse")) && fragment.EnterElement(UNI_L("Tariff")) && fragment.EnterElement(UNI_L("prepay"))) { TempBuffer buffer; RETURN_IF_ERROR(fragment.GetAllText(buffer)); RETURN_IF_ERROR(static_cast<JilNetworkResources::GetUserSubscriptionTypeCallback*>(m_callback)->SetType( uni_stricmp(buffer.GetStorage(),"true") == 0 ? UNI_L("prepaid") : UNI_L("postpaid"))); return OpStatus::OK; } return OpStatus::ERR; } }; class SelfLocationHandler: public JILNetworkRequestHandler { public: SelfLocationHandler(JilNetworkResources::GetSelfLocationCallback *callback): JILNetworkRequestHandler(callback) {} OP_STATUS SendRequest() { OpString8 request, msisdn; RETURN_IF_ERROR(g_op_subscriber_info->GetSubscriberMSISDN(&msisdn)); RETURN_IF_ERROR(request.AppendFormat("\ <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\ <Request>\ <operation>GetSelfLocation</operation>\ <securityToken>%s</securityToken>\ <Location>\ <msisdn>%s</msisdn>\ </Location>\ </Request>", m_securityToken.CStr(), msisdn.CStr())); return SendRequestInternal("csg/1.0/location", request.CStr()); } protected: OP_STATUS TakeResult(XMLFragment &fragment) { int cellId; double latitude, longitude, accuracy; if (!fragment.EnterElement(UNI_L("Response")) || !fragment.EnterElement(UNI_L("LocationResponse")) || !fragment.EnterElement(UNI_L("cellId"))) return OpStatus::ERR; TempBuffer buffer; RETURN_IF_ERROR(fragment.GetAllText(buffer)); RETURN_IF_ERROR(StringToInt(buffer.GetStorage(), cellId)); static_cast<JilNetworkResources::GetSelfLocationCallback*>(m_callback)->SetCellId(cellId); fragment.LeaveElement(); if (!fragment.EnterElement(UNI_L("latitude"))) return OpStatus::ERR; buffer.Clear(); RETURN_IF_ERROR(fragment.GetAllText(buffer)); RETURN_IF_ERROR(StringToDouble(buffer.GetStorage(), latitude)); static_cast<JilNetworkResources::GetSelfLocationCallback*>(m_callback)->SetLatitude(latitude); fragment.LeaveElement(); if (!fragment.EnterElement(UNI_L("longitude"))) return OpStatus::ERR; buffer.Clear(); RETURN_IF_ERROR(fragment.GetAllText(buffer)); RETURN_IF_ERROR(StringToDouble(buffer.GetStorage(), longitude)); static_cast<JilNetworkResources::GetSelfLocationCallback*>(m_callback)->SetLongitude(longitude); fragment.LeaveElement(); if (!fragment.EnterElement(UNI_L("accuracy"))) return OpStatus::ERR; buffer.Clear(); RETURN_IF_ERROR(fragment.GetAllText(buffer)); RETURN_IF_ERROR(StringToDouble(buffer.GetStorage(), accuracy)); static_cast<JilNetworkResources::GetSelfLocationCallback*>(m_callback)->SetAccuracy(accuracy); return OpStatus::OK; } }; JilNetworkResources::JilNetworkResources(): m_authRequest(NULL) { } OP_STATUS JilNetworkResources::Construct() { g_main_message_handler->SetCallBack(this, MSG_DAPI_JIL_HANDLER_STATUS_CHANGED, 0); return OpStatus::OK; } JilNetworkResources::~JilNetworkResources() { g_main_message_handler->UnsetCallBacks(this); m_requests.Clear(); } OP_STATUS JilNetworkResources::GetSecurityToken() { m_authRequest = OP_NEW(AuthenticationRequestHandler,()); RETURN_OOM_IF_NULL(m_authRequest); m_authRequest->Into(&m_requests); OP_STATUS res; if (OpStatus::IsError(res = m_authRequest->SendRequest())) { OP_DELETE(m_authRequest); return res; } return OpStatus::OK; } void JilNetworkResources::PrepareTokenRequiringRequest(JILNetworkRequestHandlerCallback *callback, JILNetworkRequestHandler *handler) { OP_STATUS res = OpStatus::ERR_NO_MEMORY; if (!handler || m_securityToken.IsEmpty() && OpStatus::IsError(res = GetSecurityToken())) { OP_DELETE(handler); callback->Finished(res); return; } handler->Into(&m_requests); if ( !m_securityToken.IsEmpty() && (OpStatus::IsError(res = handler->SetSecurityToken(m_securityToken.CStr())) || OpStatus::IsError(res = handler->SendRequest()))) { OP_DELETE(handler); callback->Finished(res); } } void JilNetworkResources::GetUserAccountBalance(GetUserAccountBalanceCallback *callback) { PrepareTokenRequiringRequest(callback, OP_NEW(UserAccountBalanceHandler,(callback))); } void JilNetworkResources::GetUserSubscriptionType(GetUserSubscriptionTypeCallback *callback) { PrepareTokenRequiringRequest(callback, OP_NEW(UserSubscriptionTypeHandler,(callback))); } void JilNetworkResources::GetSelfLocation(GetSelfLocationCallback *callback) { PrepareTokenRequiringRequest(callback, OP_NEW(SelfLocationHandler,(callback))); } void JilNetworkResources::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { if (msg==MSG_DAPI_JIL_HANDLER_STATUS_CHANGED) { JILNetworkRequestHandler *handler = reinterpret_cast<JILNetworkRequestHandler*>(par1); switch(handler->GetState()) { case JILNetworkRequestHandler::STATE_FINISHED: if (handler==m_authRequest) { m_securityToken.Set(m_authRequest->GetSecurityToken()); for (JILNetworkRequestHandler *it = static_cast<JILNetworkRequestHandler*>(m_requests.First()); it!=NULL; it = static_cast<JILNetworkRequestHandler*>(it->Suc())) { if (it->GetState() == JILNetworkRequestHandler::STATE_NEW || it->GetState() == JILNetworkRequestHandler::STATE_NEW_TOKEN_NEEDED) { it->SetSecurityToken(m_securityToken.CStr()); it->SendRequest(); } } m_authRequest = NULL; } OP_DELETE(handler); break; case JILNetworkRequestHandler::STATE_FAILED: if (handler==m_authRequest) for (JILNetworkRequestHandler *it = static_cast<JILNetworkRequestHandler*>(m_requests.First()); it!=NULL; it = static_cast<JILNetworkRequestHandler*>(it->Suc())) if (it != handler) it->FinishCallBackAndChangeState(OpStatus::ERR); OP_DELETE(handler); break; case JILNetworkRequestHandler::STATE_NEW_TOKEN_NEEDED: { OP_STATUS res; if (OpStatus::IsError(res = GetSecurityToken())) handler->FinishCallBackAndChangeState(res); } break; } } } #endif // DOM_JIL_API_SUPPORT
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 Opera Software ASA. 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/encodings/encoders/iso-8859-1-encoder.h" #include "modules/encodings/encoders/encoder-utility.h" const char *UTF16toISOLatin1Converter::GetDestinationCharacterSet() { if (m_high == 128) return "us-ascii"; if (m_is_x_user_defined) return "x-user-defined"; return "iso-8859-1"; } char UTF16toISOLatin1Converter::lookup(uni_char) { return 0; } int UTF16toISOLatin1Converter::Convert(const void *src, int len, void* dest, int maxlen, int *read_p) { const uni_char *input = reinterpret_cast<const uni_char *>(src); int utf16len = len / 2; int written = 0; char *output = reinterpret_cast<char *>(dest); int read = 0; char target_character; while (read < utf16len && written < maxlen) { if (*input < m_high) { *(output ++) = static_cast<char>(*(input ++)); ++ written; } else if (*input >= 0xFF00 && *input <= 0xFF5E) { // Full-width ASCII *(output ++) = static_cast<char>((*(input ++) & 0xFF) + 0x20); ++ written; } else if (0 != (target_character = lookup(*input))) { *(output ++) = target_character; ++ written; ++ input; } else { // Note: need some more logic here to fold look-alike characters // to their best local representations #ifdef ENCODINGS_HAVE_ENTITY_ENCODING if (!CannotRepresent(*(input ++), read, &output, &written, maxlen)) break; #else *(output ++) = NOT_A_CHARACTER_ASCII; CannotRepresent(*(input ++), read); ++ written; #endif } ++ read; } *read_p = read * 2; m_num_converted += read; return written; }
// // GItemInfo.cpp // Core // // Created by Max Yoon on 11. 8. 12.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #include "GnGamePCH.h" #include "GItemInfo.h" GnImplementSingleton(GItemInfo) const gchar* GItemInfo::GetIconFileName(gtuint uiIndex) { uiIndex -= INDEX_ITEM; if( mscNumMaxItem <= uiIndex ) return NULL; static const char fileName[mscNumMaxItem][256] = { {"Upgrade/items/400_74 a.png"}, {"Upgrade/items/400_174.png"}, {"Upgrade/items/400_124.png"}, {"Upgrade/items/400_74 .png"}, {"Upgrade/items/400_174 a.png"}, {"Upgrade/items/N1_a.png"} }; return fileName[uiIndex]; } const gchar* GItemInfo::GetGameIconFileName(gtuint uiIndex) { uiIndex -= INDEX_ITEM; if( mscNumMaxItem <= uiIndex ) return NULL; static const char fileName[mscNumMaxItem][256] = { {"Controll/N5_g.png"}, {"Controll/N4_g.png"}, {"Controll/N3_g.png"}, {"Controll/N2_g.png"}, {"Controll/N6_g.png"}, {"Controll/N1_g.png"} }; return fileName[uiIndex]; } const gchar* GItemInfo::GetPriceIconFileName(gtuint uiIndex) { uiIndex -= INDEX_ITEM; if( mscNumMaxItem <= uiIndex ) return NULL; static const char fileName[mscNumMaxItem][256] = { {"Upgrade/items/30_140.png"}, {"Upgrade/items/134_74.png"}, {"Upgrade/items/82_74.png"}, {"Upgrade/items/30_74.png"}, {"Upgrade/items/82_140.png"}, {"Upgrade/items/N1.png"} }; return fileName[uiIndex]; } const gchar* GItemInfo::GetExplainFileName(gtuint uiIndex) { uiIndex -= INDEX_ITEM; if( mscNumMaxItem <= uiIndex ) return NULL; static const char fileName[mscNumMaxItem][256] = { {"Upgrade/items/a 28_222.png"}, {"Upgrade/items/c 28_222.png"}, {"Upgrade/items/b 28_222.png"}, {"Upgrade/items/d 28_222.png"}, {"Upgrade/items/e 28_222.png"}, {"Upgrade/items/e 28_222.png"} }; return fileName[uiIndex]; } guint32 GItemInfo::GetBuyPrice(gtuint uiIndex, guint32 uiLevel) { GnSQLite sqlite( GetFullPath( "ItemInfo.sqlite" ) ); GnSQLiteQuery query = sqlite.ExecuteSingleQuery( "SELECT * FROM GameItem WHERE idx=%d" , uiIndex ); if( query.QueryReturn() == false ) return false; guint32 price = query.GetIntField( 3 ) *( uiLevel + 1 ); return price; } guint32 GItemInfo::GetSellPrice(gtuint uiIndex, guint32 uiLevel) { GnSQLite sqlite( GetFullPath( "ItemInfo.sqlite" ) ); GnSQLiteQuery query = sqlite.ExecuteSingleQuery( "SELECT * FROM GameItem WHERE idx=%d" , uiIndex ); if( query.QueryReturn() == false ) return false; guint32 price = query.GetIntField( 4 ) *( uiLevel + 1 ); return price; }
#include "stdafx.h" #include "MultipleResponseQuestion.h" #include "MultipleResponseQuestionView.h" #include "MultipleResponseQuestionState.h" using namespace qp; using namespace std; BOOST_AUTO_TEST_SUITE(MultipleResponseQuestionViewTests) BOOST_AUTO_TEST_CASE(MultipleResponseQuestionViewShowsDescriptionAndDetails) { CGradedChoices choices; choices.AddChoice("0 Incorrect", false); choices.AddChoice("1 Correct", true); choices.AddChoice("2 Incorrect", false); choices.AddChoice("3 Correct", true); string description = "Description"; auto question = make_shared<CMultipleResponseQuestion>(description, 10, choices); auto state = make_shared<CMultipleResponseQuestionState>(question); state->SelectResponse(1); state->SelectResponse(3); ostringstream ostrm; istringstream istrm; CMultipleResponseQuestionView view(state, ostrm, istrm); view.Show(); BOOST_CHECK_EQUAL(ostrm.str(), description + "\n" "[ ] A. 0 Incorrect\n" "[V] B. 1 Correct\n" "[ ] C. 2 Incorrect\n" "[V] D. 3 Correct\n" ); state->UnselectResponse(3); state->Submit(); view.Show(); cout << ostrm.str(); /* BOOST_CHECK_EQUAL(ostrm.str(), description + "\n" "[ ] A. 0 Incorrect\n" "[V] B. 1 Correct\n" "[ ] C. 2 Incorrect\n" "[V] D. 3 Correct\n" ); */ /* Description 1. [ ] Choice 1 2. [ ] Choice 2 3. [ ] Choice 3 */ //BOOST_MESSAGE("TODO: verify that choices are shown"); } BOOST_AUTO_TEST_SUITE_END()
#include "../command.hpp" void iterate(const unsigned int count) { response::vacuous(); }
#include<graphics.h> #include<conio.h> #include<string.h> #include<process.h> #include<stdio.h> #include<dos.h> #include<stdlib.h> #include<fstream.h> #include<time.h> #include"H:\PROJECTS\MOUSE.CPP" clock_t start=clock(), end=clock(); int x,y,button; int qno=0; int fif=1,exp=1,e20=1; int dip=1,dipactive=0; int expq=0; void Dip() { outtext("Double Dip Activated"); dipactive=1; dip=0; } double moneywon; double permawon=0; int exprtans(int rans); void Startplay(); void Mainpage(); void Walloffame(); void About(); void Drawhexa(int x, int y,int a, int b,int w, int col) { int hexa[14]; hexa[0]=x; hexa[1]=y; hexa[2]=x+a; hexa[3]=y-b; hexa[4]=x+a+w; hexa[5]=y-b; hexa[6]=x+2*a+w; hexa[7]=y; hexa[8]=x+a+w; hexa[9]=y+b; hexa[10]=x+a; hexa[11]=y+b; hexa[12]=x; hexa[13]=y; drawpoly(7,hexa); setfillstyle(SOLID_FILL,col); fillpoly(7,hexa); } struct Question { char quest[500]; struct option { int opno; char op[125]; }o1,o2,o3,o4;//options int Rans ; double money; int Status ; }; void display(Question Que) { cleardevice(); setbkcolor(0); if(!expq) { if(dip) { bar(getmaxx()-430,10,getmaxx()-330,30); settextstyle(5,0,1); outtextxy(getmaxx()-425,5,"Double Dip"); } if(fif) {bar(getmaxx()-320,10,getmaxx()-220,30); outtextxy(getmaxx()-315,5,"50-50"); } if(exp) { bar(getmaxx()-210,10,getmaxx()-110,30); settextstyle(5, 0, 1); outtextxy(getmaxx()-210,5,"Expert Advice"); } if(e20) { bar(getmaxx()-100,10,getmaxx(),30); outtextxy(getmaxx()-95,5,"Extra 20"); } } Drawhexa(20,getmaxy()/3,30,40,getmaxx()-100,3);//quest Drawhexa(20,2*getmaxy()/3,30,30,(getmaxx()-170)/2,3);//op1 Drawhexa(90+(getmaxx()-170)/2,2*getmaxy()/3,30,30,(getmaxx()-170)/2,3);//op2 Drawhexa(20,2*getmaxy()/3+80,30,30,(getmaxx()-170)/2,3);//op3 Drawhexa(90+(getmaxx()-170)/2,2*getmaxy()/3+80,30,30,(getmaxx()-170)/2,3);//op4 setcolor(RED); settextstyle(2 , 0, 4); //style,direction, size outtextxy(40,getmaxy()/3,Que.quest); setcolor(BLACK); settextstyle(2, 0, 4); outtextxy(35,2*getmaxy()/3-10, "A."); outtextxy(45,2*getmaxy()/3-10,Que.o1.op); outtextxy(90+(getmaxx()-170)/2+15,2*getmaxy()/3-10, "B."); outtextxy(90+(getmaxx()-170)/2+25,2*getmaxy()/3-10,Que.o2.op); outtextxy(35,2*getmaxy()/3+70, "C."); outtextxy(45,2*getmaxy()/3+70,Que.o3.op); outtextxy(90+(getmaxx()-170)/2+15,2*getmaxy()/3+70, "D."); outtextxy(90+(getmaxx()-170)/2+25,2*getmaxy()/3+70,Que.o4.op); setcolor(RED); }//DISPLAY void display(int r1,int r2,Question Que)//for 50-50 { cleardevice(); setbkcolor(0); if(dip) { bar(getmaxx()-430,10,getmaxx()-330,30); settextstyle(5, 0, 1); outtextxy(getmaxx()-425,5,"Double Dip"); } if(fif) {bar(getmaxx()-320,10,getmaxx()-220,30); outtextxy(getmaxx()-315,5,"50-50"); } if(exp) { bar(getmaxx()-210,10,getmaxx()-110,30); settextstyle(5, 0, 1); outtextxy(getmaxx()-210,5,"Expert Advice"); } if(e20) { bar(getmaxx()-100,10,getmaxx(),30); outtextxy(getmaxx()-95,5,"Extra 20"); } Drawhexa(20,getmaxy()/3,30,40,getmaxx()-100,3);//quest Drawhexa(20,2*getmaxy()/3,30,30,(getmaxx()-170)/2,3);//op1 Drawhexa(90+(getmaxx()-170)/2,2*getmaxy()/3,30,30,(getmaxx()-170)/2,3);//op2 Drawhexa(20,2*getmaxy()/3+80,30,30,(getmaxx()-170)/2,3);//op3 Drawhexa(90+(getmaxx()-170)/2,2*getmaxy()/3+80,30,30,(getmaxx()-170)/2,3);//op4 setcolor(RED); settextstyle(5, 0, 2); //style,direction, size outtextxy(40,getmaxy()/3-40,Que.quest); settextstyle(2, 0, 4); if(Que.o1.opno==r1||Que.o1.opno==r2) {outtextxy(35,2*getmaxy()/3-10, "A."); outtextxy(45,2*getmaxy()/3-10,Que.o1.op);} if(Que.o2.opno==r1||Que.o2.opno==r2) { outtextxy(90+(getmaxx()-170)/2+15,2*getmaxy()/3-10, "B."); outtextxy(90+(getmaxx()-170)/2+25,2*getmaxy()/3-10,Que.o2.op); } if(Que.o3.opno==r1||Que.o3.opno==r2) {outtextxy(35,2*getmaxy()/3+70, "C."); outtextxy(45,2*getmaxy()/3+70,Que.o3.op);} if(Que.o4.opno==r1||Que.o4.opno==r2) {outtextxy(90+(getmaxx()-170)/2+15,2*getmaxy()/3+70, "D."); outtextxy(90+(getmaxx()-170)/2+25,2*getmaxy()/3+70,Que.o4.op); } }//DISPLAY int E20(int x) {e20=0; x+=20; } int exprtans(int rans) { while(1) { cout<<"00:"; end = clock() ; int TimeSec = 60-(int)(end - start) / CLK_TCK; gotoxy(35, 4); cout<<TimeSec ; delay( 100 ); getmousepos( &button, &x, &y ); if( button & 1 == 1) //Left mouse button { if(x>=50&&x<=50+(getmaxx()-170)/2&&y>=2*getmaxy()/3-30&&y<=2*getmaxy()/3+30) if(1==rans) return 1; else return 0; if(x>=120+(getmaxx()-170)/2&&x<=120+getmaxx()-170&&y>=2*getmaxy()/3-30&&y<=2*getmaxy()/3+30) if(2==rans) return 1; else return 0; if(x>=50&&x<=50+(getmaxx()-170)/2&&y>=2*getmaxy()/3+500&&y<=2*getmaxy()/3+110) if(3==rans) return 1; else return 0; if(x>=120+(getmaxx()-170)/2&&x<=120+getmaxx()-170&&y>=2*getmaxy()/3+50&&y<=2*getmaxy()/3+110) if(4==rans) return 1; else return 0; } } } void fifty(Question Que) { fif=0; int r1=Que.Rans,r2=Que.Rans; while(r2==Que.Rans) { r2=rand()%4+1; } display(r1,r2,Que); }//fifty void expadv(Question dup) { exp=0; Question Q; fstream KBfile; KBfile.open("H:EXPADV.som",ios::in|ios::binary); int num; KBfile.seekg(0,ios::end); int size=KBfile.tellg(); int nofq=(size-1)/sizeof(Q); num=rand()%nofq+1; KBfile.seekg(0); KBfile.read((char*)&Q,sizeof(Q)); int i=1; int flag=0; Question temp;int flagf=0; while(!KBfile.eof())//selecting a random q { if(flag==0&&Q.Status==0) {temp=Q;flag=1;} if(i==num) { if(Q.Status==0) {flagf=1; KBfile.seekp(KBfile.tellg()-sizeof(Q)); Q.Status=1; settextstyle(4,0,2) ; KBfile.write((char*)&Q,sizeof(Q)); break; } else//if(status==1) num++; } else//(i!=num) {KBfile.read((char*)&Q,sizeof(Q)); i++; } } if(flagf==0) { if(flag==1) {temp=Q; KBfile.seekg(0); KBfile.seekp(0); KBfile.read((char*)&Q,sizeof(Q)); while(!KBfile.eof()) { if(!strcmpi(Q.quest,temp.quest)) { KBfile.seekp(KBfile.tellg()-sizeof(Q)); Q.Status=1; settextstyle(4,0,2); KBfile.write((char*)&Q,sizeof(Q)); break; } }//EOF }//FLAG==1 else//all are used....set status=0;..read first one { KBfile.seekg(0); KBfile.seekp(0); KBfile.read((char*)&Q,sizeof(Q)); while(!KBfile.eof()) { Q.Status=0; KBfile.write((char*)&Q,sizeof(Q)); KBfile.read((char*)&Q,sizeof(Q)); } KBfile.seekg(0); KBfile.seekp(0); KBfile.read((char*)&Q,sizeof(Q)); Q.Status=1; KBfile.write((char*)&Q,sizeof(Q)); } } cleardevice(); expq=1; outtextxy(10,10," To get the most probable answer for the question answer this question : "); display(Q); if(exprtans(Q.Rans)) { delay(1000); expq=0; display(dup); outtextxy(10,20," The most probable answer for this question is : "); int r=rand()%1000+1; int m=dup.Rans; if(r%200==0)//to get wrong ans. while(m==dup.Rans) m=rand()%4+1; if(dup.o1.opno==m) {outtext("A. ");outtext(dup.o1.op);} if(dup.o2.opno==m) {outtext("B. ");outtext(dup.o2.op);} if(dup.o3.opno==m) {outtext("C. ");outtext(dup.o3.op);} if(dup.o4.opno==m) {outtext("D. ");outtext(dup.o4.op);} }//if correct ans. else { outtextxy(10,20," Sorry, you answered it wrong..."); delay(1000); display(dup); } }//expadv struct Score { char name[30]; double monwon; }; void Mainpage() { cleardevice(); setbkcolor(0); settextstyle(3, 0, 1 ); outtextxy(620,10,"X"); settextstyle(5, 0, 5 ); outtextxy(50,20,"Are you the next billionaire ?"); setcolor( RED) ; outtextxy(51,20,"Are you the next billionaire ?"); setcolor(WHITE); setfillstyle(SOLID_FILL,BLUE); Drawhexa(getmaxx()/2-100-20,getmaxy()/3,30,30,220,3);//play Drawhexa(getmaxx()/2-100-20,getmaxy()/3+90,30,30,220,3);//WALL OF FAME Drawhexa(getmaxx()/2-100-20,getmaxy()/3+180,30,30,220,3);//ABOUT setcolor( RED) ; settextstyle(7, 0, 5 ); outtextxy(285,getmaxy()/3-30+5,"PLAY"); settextstyle(7, 0, 4 ); outtextxy(213,getmaxy()/3-30+110-10,"WALL OF FAME"); settextstyle(7, 0, 5 ); outtextxy(265,getmaxy()/3-30+185,"ABOUT"); //int left, int top, int right, int bottom //rectangle(620,15,630,30); while(1) { getmousepos( &button, &x, &y ); if( button & 1 == 1) //Left mouse button { if(x>=getmaxx()/2-70-20&&x<=getmaxx()/2+70+80&&y>=getmaxy()/3-30&&y<=getmaxy()/3+30) Startplay(); if(x>=getmaxx()/2-70-20&&x<=getmaxx()/2+70+80&&y>=getmaxy()/3-30+90&&y<=getmaxy()/3+30+90) Walloffame(); if(x>=getmaxx()/2-70-20&&x<=getmaxx()/2+70+80&&y>=getmaxy()/3-30+180&&y<=getmaxy()/3+30+180) About(); if(x>=620&&x<=630&&y<=30&&y>=15) { delay(1000); exit(0); } }//button &1 } } void About() { cleardevice(); setbkcolor(0); setcolor(RED); settextstyle(5,0,5);//style,direction,size outtextxy(170,25,"HOW TO PLAY\? "); setcolor(WHITE); outtextxy(171,25,"HOW TO PLAY\? "); char c=4; char ch[3]; gcvt(c,5,ch); settextstyle(1,0,5); fstream KBfile; KBfile.open("H:RULE.som",ios::binary|ios::in); if(!KBfile) outtextxy(10,30,"File not found!!"); else { char temp; outtextxy(5,35,ch); KBfile.get(temp); while(!KBfile.eof()) { if(temp=='\n') { outtext("\n\n"); outtext(ch); }//if \n else { char cha[5]; gcvt(temp,5,cha); outtext(cha); } KBfile.get(temp); }//while }//else KBfile.close(); bar(10,getmaxy()-20,50,getmaxy()); settextstyle(2,0,4); outtextxy(20,getmaxy()-10,"BACK"); while(1) { getmousepos( &button, &x, &y ); if( button & 1 == 1) //Left mouse button { if(x>=20&&x<=50&&y>=getmaxy()-20&&y<=getmaxy()) Mainpage(); }} }//about void Displaytree(int i)//i- question to be ans { int yadd=0; cleardevice(); for(int j=1;j<=11;j++) { if(j==11-(i-1)||(j==7&&i==7)) Drawhexa(getmaxx()/2+100,30+yadd,10,15,200,1); else if(j==7) Drawhexa(getmaxx()/2+100,30+yadd,10,15,200,2); else Drawhexa(getmaxx()/2+100,30+yadd,10,15,200,3); yadd+=40; } settextstyle(5,0,2); outtextxy(getmaxx()/2+120,15,"$1,000,000,000"); outtextxy(getmaxx()/2+153,55,"$10,000,000"); outtextxy(getmaxx()/2+154,95,"$1,000,000"); outtextxy(getmaxx()/2+155,135,"$500,000"); outtextxy(getmaxx()/2+155,175,"$250,000"); outtextxy(getmaxx()/2+155,215,"$100,000"); outtextxy(getmaxx()/2+157,255,"$50,000"); outtextxy(getmaxx()/2+157,295,"$25,000"); outtextxy(getmaxx()/2+157,335,"$10,000"); outtextxy(getmaxx()/2+160,375,"$5000"); outtextxy(getmaxx()/2+160,415,"$1000"); if(dip) {bar(20,200,130,230); outtextxy(20,205,"Double Dip"); } if(fif) {bar(20,getmaxy()/2,120,getmaxy()/2+30); outtextxy(25,getmaxy()/2,"50-50"); } if(exp) { bar(20,getmaxy()/2+40,120,getmaxy()/2+70) ; settextstyle(5,0,1); outtextxy(20,getmaxy()/2+40,"Expert advice"); } if(e20) { bar(20,getmaxy()/2+80,120,getmaxy()/2+110); settextstyle(5,0,1); outtextxy(23,getmaxy()/2+80,"Extra 20"); } } void Walloffame() { cleardevice(); setbkcolor(0); Drawhexa(20,40,30,30,getmaxx()-100,3);//for heading settextstyle(5,0,5);//style,direction,size outtextxy(getmaxx()/2-100,10,"Wall of Fame"); settextstyle(5,0,3); outtextxy(70,60,"Player Name"); outtextxy(390,60,"Money Won"); bar(20,getmaxy()-60,100,getmaxy()-30);//left, top, right,bottom settextstyle(6,0,3); outtextxy(30,getmaxy()-60,"BACK"); fstream KBfile; KBfile.open("H:FAME.QUE",ios::binary|ios::in|ios::out); if(!KBfile) outtextxy(10,20,"File not found!!"); else { Score dum; int a=0,b=0,cou=0;//cou-how many r displayed already KBfile.read((char*)&dum,sizeof(dum)); while(!KBfile.eof()&&cou==5) { char cha[5]; gcvt(cou+1,5,cha); outtextxy(22+a,145+b,cha); outtextxy(25+a,145+b,". "); outtextxy(40+a,145+b,dum.name); a+=320; outtextxy(22+a,145+b,"$ "); gcvt(dum.monwon,5,cha); outtextxy(40+a,145+b,cha); a-=320; b+=30; cou++; KBfile.read((char*)&dum,sizeof(dum)); } } KBfile.close(); while(1) { getmousepos( &button, &x, &y ); if( button & 1 == 1) //Left mouse button { if(x>=20&&x<=100&&y>=getmaxy()-60&&y<=getmaxy()-30) { Mainpage(); } } }//while } int Askq(int qno)//increments money {//pikc a random question from the set of questions //display the question and know whether the users ans is ocrretc or not Question dup; fstream KBfile; if(!KBfile) outtextxy(10,20,"FILE NOT FOUND!!") ; else { switch(qno) {case 1:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 2:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 3:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 4:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 5:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 6:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 7:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 8:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 9:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 10:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; case 11:KBfile.open("h:q001.som",ios::in|ios::out|ios::binary);break; } int num; KBfile.seekg(0,ios::end); int size=KBfile.tellg(); int nofq=(size-1)/sizeof(dup); num=rand()%nofq+1; KBfile.seekg(0); KBfile.read((char*)&dup,sizeof(dup)); char dfg[30]="no"; int i=1; int flag=0; Question temp;int flagf=0; while(!KBfile.eof())//selecting a random q { if(flag==0&&dup.Status==0) {temp=dup;flag=1;} if(i==num)//status later { if(dup.Status==0) {flagf=1; strcpy(dfg,"yes"); KBfile.seekp(KBfile.tellg()-sizeof(dup)); dup.Status=1; for(int e=0;e<sizeof(dup); e++) KBfile.write((char*)&dup,1); break; } else//if(status==1) num++; }//if i==num KBfile.read((char*)&dup,sizeof(dup)); i++; } if(flagf==0) { if(flag==1) { KBfile.seekg(0); KBfile.seekp(0); KBfile.read((char*)&dup,sizeof(dup)); while(!KBfile.eof()) { if(!strcmpi(dup.quest,temp.quest)) { KBfile.seekp(KBfile.tellg()-sizeof(dup)); dup.Status=1; for(i=0;i<sizeof(dup);i++) { KBfile.write((char*)&dup,1); } break; } } dup=temp; } else//all are used....set status=0;..read first one { KBfile.seekg(0); KBfile.seekp(0); KBfile.read((char*)&dup,sizeof(dup)); while(!KBfile.eof()) { dup.Status=0; KBfile.write((char*)&dup,sizeof(dup)); KBfile.read((char*)&dup,sizeof(dup)); } KBfile.seekg(0); KBfile.seekp(0); KBfile.read((char*)&dup,sizeof(dup)); dup.Status=1; KBfile.write((char*)&dup,sizeof(dup)); } } display(dup); outtext(dfg); }//else KBfile.close(); //display part is done start=clock(), end=clock(); int flag=0; while(1) { int TimeSec; cout<<"00:"; end = clock() ; if(flag==1) {TimeSec = 60-(int)(end - start) / CLK_TCK+20;flag=0;} else TimeSec = 60-(int)(end - start) / CLK_TCK; gotoxy(35, 4); cout<<TimeSec ; delay( 100 ); if(!TimeSec) {cout<<"\n\n Time up!!"; cleardevice(); outtextxy(50,50," Thank you for playing!!!"); outtextxy(50,80," Enter your name : "); gotoxy(0,100); getch(); exit(0); } getmousepos( &button,&x, &y ); if( button & 1 == 1) //Left mouse button {if(x>=50&&x<=(getmaxx()-170)/2+50&&y>=2*getmaxy()/3-30&&y<=2*getmaxy()/3+30)//op1 //hv a problem with hexagon if(dipactive&&dup.Rans!=1) { dipactive=0; Drawhexa(20,2*getmaxy()/3,30,30,(getmaxx()-170)/2,4); outtextxy(35,2*getmaxy()/3-10, "A."); outtextxy(45,2*getmaxy()/3-10,dup.o1.op); delay(1000); continue; } else if(dup.Rans==1) {moneywon=dup.money; if(moneywon==50000) permawon=50000; return 1;} else return 0; if(x>=120+(getmaxx()-170)/2&&x<=120+getmaxx()-170&&y<=2*getmaxy()/3+30&&y>=2*getmaxy()/3-30)//op2 if(dipactive&&dup.Rans!=2) { dipactive=0; Drawhexa(90+(getmaxx()-170)/2,2*getmaxy()/3,30,30,(getmaxx()-170)/2,4); outtextxy(90+(getmaxx()-170)/2+15,2*getmaxy()/3-10, "B."); outtextxy(90+(getmaxx()-170)/2+25,2*getmaxy()/3-10,dup.o2.op); delay(1000); continue; } else if(dup.Rans==2) {moneywon=dup.money; if(moneywon==50000) permawon=50000; return 1; } else return 0; if(x>=50&&x<=(getmaxx()-170)/2+50&&y>=2*getmaxy()/3+50&&y<=2*getmaxy()/3+110)//op3 if(dipactive&&dup.Rans!=3) { dipactive=0; Drawhexa(20,2*getmaxy()/3+80,30,30,(getmaxx()-170)/2,4); outtextxy(35,2*getmaxy()/3+70, "C."); outtextxy(45,2*getmaxy()/3+70,dup.o3.op); delay(1000); continue; } else if(dup.Rans==3) { moneywon=dup.money; if(moneywon==50000) permawon=50000; return 1;} else return 0; if(x>=120+(getmaxx()-170)/2&&x<=120+getmaxx()-170&&y>=2*getmaxy()/3+50&&y<=2*getmaxy()/3+110)//op4 if(dipactive&&dup.Rans!=4) { dipactive=0; Drawhexa(90+(getmaxx()-170)/2,2*getmaxy()/3+80,30,30,(getmaxx()-170)/2,4); outtextxy(90+(getmaxx()-170)/2+15,2*getmaxy()/3+70, "D."); outtextxy(90+(getmaxx()-170)/2+25,2*getmaxy()/3+70,dup .o4.op); delay(1000); continue; } else if(dup.Rans==4) {moneywon=dup.money; if(moneywon==50000) permawon=50000; return 1; } else return 0; if(x>=getmaxx()-320&&y>=10&&x<=getmaxx()-220&&y<=30) if(!expq)if(fif) fifty(dup); if(x>=getmaxx()-210&&y>=10&&x<=getmaxx()-110&&y<=30) if(!expq)if(exp) expadv(dup); //extra 20 if(x>=getmaxx()-100&&y>=10&&x<=getmaxx()&&y<=30) if(!expq)if(e20) {flag=1;e20=0;display(dup);} if(!expq)if(dip) if(x>=getmaxx()-430&&y>=10&&x<=getmaxx()-330&&y<=30) //for dip Dip(); } }//while for selecting } void SaveinFame(Score player) { fstream KBfile,Kfile;Score dup; KBfile.open("H:FAME.QUE",ios::binary|ios::out|ios::in); if(!KBfile) outtextxy(10,20,"File not found!!!"); else { Kfile.open("H:FAMEdup.QUE",ios::binary|ios::out|ios::in); if(!Kfile) outtextxy(10,20,"File not found!!!"); else { KBfile.read((char*)&dup,sizeof(dup)); while(!KBfile.eof()) { if(player.monwon>=dup.monwon) { Kfile.write((char*)&player,sizeof(player)); Kfile.write((char*)&dup,sizeof(dup)); } else { Kfile.write((char*)&dup,sizeof(dup)); } KBfile.read((char*)&dup,sizeof(dup)); }//while Kfile.close(); } KBfile.close(); } remove("H:FAME.QUE"); rename("H:FAMEdup.QUE","H:FAME.QUE"); } void Repeat(int retval,int i) { Score player; while(i!=11) { retval=Askq(i); if(retval==1&&i!=11) { cleardevice(); Displaytree(i); outtextxy(10,15,"That's the right answer!!!You won $"); char cha[20]; gcvt(moneywon,20,cha); outtextxy(325,15,cha); outtextxy(10,35,"Do you want to continue ?"); bar(10,70,70,110);//left, top, right,bottom //yes outtextxy(14,75," YES "); bar(150,70,210,110);//NO outtextxy(154,70," NO "); while(1) { getmousepos( &button, &x, &y ); if( button & 1 == 1) //Left mouse button { if(x>=150&&y>=70&&x<=210&&y<=110)//no { cleardevice(); outtextxy(50,50," Thank you for playing!!!"); outtextxy(50,80," Enter your name : "); gotoxy(0,100); gets(player.name); char cha[20]; gcvt(moneywon,20,cha); outtextxy(325,15,cha); player.monwon=moneywon; SaveinFame(player); getch(); exit(0); } if(x>=10&y>=70&&x<=80&&y<=110)//yes { delay(500); clrscr(); Displaytree(i+1); //left, top, right,bottom outtextxy(20,getmaxy()-20,"Click 'PLAY' to continue..."); bar(getmaxx()/2-50,getmaxy()-50,getmaxx()/2+50,getmaxy()-20);//left, top, right,bottom outtextxy(getmaxx()/2-25,getmaxy()-35,"PLAY"); while(1) { getmousepos( &button, &x, &y ); if( button & 1 == 1) //Left mouse button { if(x>=getmaxx()/2-50&&y>=getmaxy()-50&&x<=getmaxx()/2+50&&y<=getmaxy()-20)//play Repeat(retval,++i); } }//while inside }//if yes } }//while outside }//if right else if(retval==1&&i==11) { //try inluding some animations clrscr (); outtextxy(10,30,"That was right!!!Congratulations!!!!...You won $1000,000,000!!!!"); outtextxy(20,70,"Thank you for playing the game!!..."); outtextxy(30,100,"Please enter your name : "); gotoxy(100,70);gets(player.name); player.monwon=1000000000; SaveinFame(player); }//11 orret else {cleardevice(); settextstyle(11,0,3); outtextxy(30,50,"OOPS...You got that wrong!!!Better luck next time!!You win $"); char cha[20]; gcvt(permawon,20,cha); outtext(cha); outtextxy(50,70,"Please enter your name : "); gets(player.name); //save in the drive player.monwon=permawon; if(!permawon) SaveinFame(player); delay(1000); exit(0); } i++; }//while outside } void Realgame() {int retval;int i=1; Repeat(retval,i); } void Startplay() { setbkcolor(0); cleardevice(); Displaytree(1); setcolor(RED); bar(5,getmaxy()-40,105,getmaxy()-10);//left, top, right,bottom settextstyle(1,0,3); outtextxy(11,getmaxy()-49,"BACK"); bar(getmaxx()/2-100,getmaxy()-50,getmaxx()/2-10,getmaxy()-20);//left, top, right,bottom settextstyle(1,0,3); outtextxy(getmaxx()/2-85,getmaxy()-55,"PLAY"); while(1) { getmousepos( &button, &x, &y ); if( button & 1 == 1) //Left mouse button { if(x>=5&&x<=105&&y>=getmaxy()-40&&y<=getmaxy()-10)//back { Mainpage(); } if(x>=getmaxx()/2-100&&x<=getmaxx()/2-10&&y>=getmaxy()-50&&y<=getmaxy()-20)//start { Realgame(); } } }//WHILE }//startplay void main() { int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, ""); randomize(); initmouse(); showmouseptr(); //mouse initialise Mainpage(); closegraph(); }//main
class BTR90; class BTR90_DZ: BTR90 { scope = 2; displayName = "$STR_VEH_NAME_BTR90"; vehicleClass = "DayZ Epoch Vehicles"; commanderCanSee = 2+16+32; gunnerCanSee = 2+16+32; driverCanSee = 2+16+32; crew = ""; typicalCargo[] = {}; class TransportMagazines {}; class TransportWeapons {}; transportMaxMagazines = 100; transportMaxWeapons = 20; transportmaxbackpacks = 6; supplyRadius = 1.8; crewVulnerable = 1; class Turrets; // External class reference class MainTurret; // External class reference }; class BTR90_DZE: BTR90_DZ { displayName = "$STR_VEH_NAME_BTR90"; class Turrets: Turrets { class MainTurret: MainTurret { magazines[] = {}; }; }; class Upgrades { ItemTankORP[] = {"BTR90_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}}; }; }; class BTR90_DZE1: BTR90_DZE { displayName = "$STR_VEH_NAME_BTR90+"; original = "BTR90_DZE"; maxspeed = 120; // base 100 terrainCoef = 0.5; // base 1.5 turnCoef = 2; // base 4 class Upgrades { ItemTankAVE[] = {"BTR90_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}}; }; }; class BTR90_DZE2: BTR90_DZE1 { displayName = "$STR_VEH_NAME_BTR90++"; armor = 220; // base 150 damageResistance = 0.048; // base 0.02432 class Upgrades { ItemTankLRK[] = {"BTR90_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}}; }; }; class BTR90_DZE3: BTR90_DZE2 { displayName = "$STR_VEH_NAME_BTR90+++"; transportMaxWeapons = 40; transportMaxMagazines = 200; transportmaxbackpacks = 12; class Upgrades { ItemTankTNK[] = {"BTR90_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}}; }; }; class BTR90_DZE4: BTR90_DZE3 { displayName = "$STR_VEH_NAME_BTR90++++"; fuelCapacity = 550; // base 300 }; class BTR90_HQ; class BTR90_HQ_DZ: BTR90_HQ { scope = 2; displayName = "$STR_VEH_NAME_BTR90_HQ"; vehicleClass = "DayZ Epoch Vehicles"; commanderCanSee = 2+16+32; gunnerCanSee = 2+16+32; driverCanSee = 2+16+32; crew = ""; typicalCargo[] = {}; class TransportMagazines {}; class TransportWeapons {}; transportSoldier = 6; enableGPS = 0; transportMaxMagazines = 100; transportMaxWeapons = 20; transportmaxbackpacks = 6; supplyRadius = 1.8; crewVulnerable = 1; class Turrets; // External class reference class MainTurret; // External class reference }; class BTR90_HQ_DZE: BTR90_HQ_DZ { displayName = "$STR_VEH_NAME_BTR90_HQ"; class Turrets: Turrets { class MainTurret: MainTurret { magazines[] = {}; }; }; class Upgrades { ItemTankORP[] = {"BTR90_HQ_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}}; }; }; class BTR90_HQ_DZE1: BTR90_HQ_DZE { displayName = "$STR_VEH_NAME_BTR90_HQ+"; original = "BTR90_HQ_DZE"; maxspeed = 120; // base 100 terrainCoef = 0.5; // base 1.5 turnCoef = 2; // base 4 class Upgrades { ItemTankAVE[] = {"BTR90_HQ_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}}; }; }; class BTR90_HQ_DZE2: BTR90_HQ_DZE1 { displayName = "$STR_VEH_NAME_BTR90_HQ++"; armor = 220; // base 150 damageResistance = 0.048; // base 0.02432 class Upgrades { ItemTankLRK[] = {"BTR90_HQ_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}}; }; }; class BTR90_HQ_DZE3: BTR90_HQ_DZE2 { displayName = "$STR_VEH_NAME_BTR90_HQ+++"; transportMaxWeapons = 40; transportMaxMagazines = 200; transportmaxbackpacks = 12; class Upgrades { ItemTankTNK[] = {"BTR90_HQ_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}}; }; }; class BTR90_HQ_DZE4: BTR90_HQ_DZE3 { displayName = "$STR_VEH_NAME_BTR90_HQ++++"; fuelCapacity = 550; // base 300 };
#include "struct.hpp" #include "parse.hpp" using namespace std; using namespace Eigen; // Vertex Helper Function Vertex convert_v(string x, string y, string z) { Vertex v; // convert the strings to float to store in Vertex struct v.x = stof(x); v.y = stof(y); v.z = stof(z); return v; } //Face Helper Function Face convert_f(string x, string y, string z) { Face f; size_t div1 = x.find("/"); size_t div2 = y.find("/"); size_t div3 = z.find("/"); string v1 = x.substr(0, div1); string v2 = y.substr(0, div2); string v3 = z.substr(0, div3); string v1n = x.substr(div1 + 2); string v2n = y.substr(div2 + 2); string v3n = z.substr(div3 + 2); // extract vertex and vertex normal from strings f.v1 = stoi(v1); f.v2 = stoi(v2); f.v3 = stoi(v3); f.v1n = stoi(v1n); f.v2n = stoi(v2n); f.v3n = stoi(v3n); return f; } // Transformation Helper Function Matrix4f convert_t(string x, string y, string z) { // convert the strings float t1 = stof(x); float t2 = stof(y); float t3 = stof(z); // create the matrix Matrix4f m; m << 1, 0, 0, t1, 0, 1, 0, t2, 0, 0, 1, t3, 0, 0, 0, 1; return m; } // Rotation Helper Function Matrix4f convert_r(string x, string y, string z, string d) { // convert the strings float t1 = stof(x); float t2 = stof(y); float t3 = stof(z); float t4 = stof(d); // calculate the values for the rotation matrix float m11 = t1*t1 + (1-t1*t1)*cos(t4); float m12 = t1*t2*(1-cos(t4))-t3*sin(t4); float m13 = t1*t3*(1-cos(t4))+t2*sin(t4); float m21 = t1*t2*(1-cos(t4))+t3*sin(t4); float m22 = t2*t2 + (1-t2*t2)*cos(t4); float m23 = t2*t3*(1-cos(t4))-t1*sin(t4); float m31 = t1*t3*(1-cos(t4))-t2*sin(t4); float m32 = t2*t3*(1-cos(t4))+t1*sin(t4); float m33 = t3*t3 + (1-t3*t3)*cos(t4); // create the matrix Matrix4f m; m << m11, m12, m13, 0, m21, m22, m23, 0, m31, m32, m33, 0, 0, 0, 0, 1; return m; } // Scaling Helper Function Matrix4f convert_s(string x, string y, string z) { // convert the strings float t1 = stof(x); float t2 = stof(y); float t3 = stof(z); // create the matrix Matrix4f m; m << t1, 0, 0, 0, 0, t2, 0, 0, 0, 0, t3, 0, 0, 0, 0, 1; return m; } // Normals Helper Function Vector4f convert_n(string x, string y, string z) { float t1 = stof(x); float t2 = stof(y); float t3 = stof(z); Vector4f n; n << t1, t2, t3, 1; return n; } // Color Helper Function Vector3f convert_c(string x, string y, string z) { float t1 = stof(x); float t2 = stof(y); float t3 = stof(z); Vector3f c; c << t1, t2, t3; return c; } // Light Helper Function Light convert_l(ifstream &file) { Light l; // extract the point light out of the file string x, y, z, j; file >> x >> y >> z >> j; float t1 = stof(x); float t2 = stof(y); float t3 = stof(z); Vector4f p; p << t1, t2, t3, 1; l.point = p; // extract the light color out of the file string r, g, b; file >> r >> g >> b >> j; float c1 = stof(r); float c2 = stof(g); float c3 = stof(b); Vector3f c; c << c1, c2, c3; l.color = c; // extract the attenuation out of the file string a; file >> a; float att = stof(a); l.attenuation = att; return l; } // Open File Helper Function void parse(char* file_name, vector<Object> &copies, vector<Light> &lights, Camera &cam, Perspective &per) { string f_name = "data/"; f_name += file_name; // Open the text file of objects and transformations ifstream file; file.open(f_name); if (!file) { cout << "no file to read original" << endl; file.close(); } else { env(file, lights, cam, per); map<string, Object> objects; string name = obj_parse(file, objects); obj_matrix(file, copies, name, objects); file.close(); } } // Environment Helper Function void env(ifstream &file, vector<Light> &lights, Camera &cam, Perspective &per) { string s; file >> s; if (s == "camera:") { while (file >> s) { // Input the position and orientation into the camera if (s == "position") { string x, y, z; file >> x >> y >> z; cam.position = convert_t(x, y, z); } else if (s == "orientation") { string x, y, z, d; file >> x >> y >> z >> d; cam.orientation = convert_r(x, y, z, d); } else // Input the perspective information into its data structure if (s == "left") { file >> s; float val = stof(s); per.l = val; } else if (s == "right") { file >> s; float val = stof(s); per.r = val; } else if (s == "top") { file >> s; float val = stof(s); per.t = val; } else if (s == "bottom") { file >> s; float val = stof(s); per.b = val; } else if (s == "near") { file >> s; float val = stof(s); per.n = val; } else if (s == "far") { file >> s; float val = stof(s); per.f = val; } else if (s == "light") { lights.push_back(convert_l(file)); } else { // When all of this information has been exhausted, the // next part to parse is the object data break; } } } return; } // Object File Parsing Helper Function string obj_parse(ifstream &file, map<string, Object> &objects) { // create a map of object names and objects string n; while (file >> n) { if (objects.count(n) < 1) { // create a new object for the map Object obj; string f = "data/"; string n00b; file >> n00b; f += n00b; // try to open the file to read ifstream infile; infile.open(f); if (!infile) { cerr << "no file to read" << endl; } else { // create vectors of the object faces and vertices vector<Face> faces; vector<Vertex> vertices; vector<Vector4f> normals; // read the file while there are still lines to read string l, x, y, z; while(infile >> l >> x >> y >> z) { // convert the file line to the correct struct and // add to vector if (l == "v") { Vertex v; v = convert_v(x, y, z); vertices.push_back(v); } else if (l == "f") { Face f; f = convert_f(x, y, z); faces.push_back(f); } else if (l == "vn") { Vector4f n = convert_n(x, y, z); normals.push_back(n); } } // create the object with its vertices and faces obj.vertices = vertices; obj.faces = faces; obj.normals = normals; objects[n] = obj; } infile.close(); } else { break; } } return n; } // Matrix Transformation Helper Function void obj_matrix(ifstream &file, vector<Object> &copies, string name, map<string, Object> objects) { // create the vector of matrices to be multiplied vector<Matrix4f> matrices; vector<Matrix4f> n_matrices; Vector3f ambient; Vector3f diffuse; Vector3f specular; float shine; string o, n; int num = 1; while (file >> n) { if (n == "ambient") { string x, y, z; file >> x >> y >> z; ambient = convert_c(x, y, z); } else if (n == "diffuse") { string x, y, z; file >> x >> y >> z; diffuse = convert_c(x, y, z); } else if (n == "specular") { string x, y, z; file >> x >> y >> z; specular = convert_c(x, y, z); } else if (n == "shininess") { string s; file >> s; shine = stof(s); } else if (n == "t") { string x, y, z; file >> x >> y >> z; Matrix4f m = convert_t(x, y, z); matrices.push_back(m); } else if (n == "r") { string x, y, z, d; file >> x >> y >> z >> d; Matrix4f m = convert_r(x, y, z, d); matrices.push_back(m); n_matrices.push_back(m); } else if (n == "s") { string x, y, z; file >> x >> y >> z; Matrix4f m = convert_s(x, y, z); matrices.push_back(m); n_matrices.push_back(m); } else { // add the object and transformation to be printed copies.push_back(copy_obj(matrices, n_matrices, objects, name, o, n, num, shine, ambient, diffuse, specular)); // set what the last object to be transformed was name = n; o = name; // check which number the copy of the object is if (o == n) { num++; } else { num = 1; } } } // add the object and transformation to be printed copies.push_back(copy_obj(matrices, n_matrices, objects, name, o, n, num, shine, ambient, diffuse, specular)); return; } // Scene Object Helper Function Object copy_obj (vector<Matrix4f> &matrices, vector<Matrix4f> &n_matrices, map<string, Object> objects, string name, string o, string n, int &num, float shine, Vector3f ambient, Vector3f diffuse, Vector3f specular) { // multiply all of the matrices in the vector together to make // the final transformation while (matrices.size() > 1) { Matrix4f m; Matrix4f m1 = matrices.back(); matrices.pop_back(); Matrix4f m2 = matrices.back(); matrices.pop_back(); m = m1 * m2; matrices.push_back(m); } while (n_matrices.size() > 1) { Matrix4f m; Matrix4f m1 = n_matrices.back(); n_matrices.pop_back(); Matrix4f m2 = n_matrices.back(); n_matrices.pop_back(); m = m1 * m2; n_matrices.push_back(m); } // create an object copy to be transformed Object copy = objects[name]; copy.ambient = ambient; copy.diffuse = diffuse; copy.specular = specular; copy.shine = shine; copy.v_transformation = matrices[0]; copy.n_transformation = n_matrices[0]; copy.name = name + "_copy" + to_string(num); matrices.clear(); n_matrices.clear(); return copy; }
#include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <math.h> #include <limits.h> #include <iostream> #include <string> #include <exception> #include <stdexcept> #include <vector> #include "RingBuffer.hpp" #include "GuitarString.hpp" #define CONCERT_A 220.0 #define SAMPLES_PER_SEC 44100 using namespace std; vector<int16_t> makeSamplesFromString(GuitarString guitarString) { vector<int16_t> samples; guitarString.pluck(); int duration = 8; int i; for (i= 0; i < SAMPLES_PER_SEC * duration; i++) { guitarString.tic(); samples.push_back(guitarString.sample()); } return samples; } int main() { sf::RenderWindow window(sf::VideoMode(500, 500), "SFML Guitar Hero Lite"); sf::Event event; double freq; string keyboard = "q2we4r5ty7u8i9op-[=zxdcfvgbnjmk,.;/' "; vector<vector<int16_t> > samples(37); vector<sf::Sound> sounds(37); vector<sf::SoundBuffer> soundBuffers(37); for(int i = 0; i < 37; i++) { freq = 440 * pow(2, (i - 24) / 12.0); GuitarString guitarString(freq); samples[i] = makeSamplesFromString(guitarString); if (!soundBuffers[i].loadFromSamples(&samples[i][0], samples[i].size(), 2, SAMPLES_PER_SEC)) throw std::runtime_error("Cant load the samples"); sounds[i].setBuffer(soundBuffers[i]); } while (window.isOpen()) { while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::TextEntered: if (event.text.unicode < 128) { string temp; temp += static_cast<char>(event.text.unicode); cout << "Playing sound using the key: " << temp << endl; int index = keyboard.find(temp); sounds[index].play(); } break; default: break; } window.clear(); window.display(); } } return 0; }
#include "Blending.h" Blender::Blender(CImg<float> src1, CImg<float> src2){ this->srcImg1 = src1; this->srcImg2 = src2; } CImg<float> Blender::blendImages(){ // Construct center og overlapping points double sum_x = 0; double sum_y = 0; int n = 0; double sum_x_overlap = 0; double sum_y_overlap = 0; int overlap_n = 0; if (srcImg1.width() > srcImg1.height()) { for (int x = 0; x < srcImg1.width(); x++) { if (!empty(srcImg1, x, srcImg1.height() / 2)) { sum_x += x; srcImg1_n++; } if (!empty(srcImg1, x, srcImg1.height() / 2) && !empty(srcImg2, x, srcImg1.height() / 2)) { sum_x_overlap += x; overlap_n++; } } } else { for (int y = 0; y < srcImg1.height(); y++) { if (!empty(srcImg1, srcImg1.width() / 2, y)) { sum_y += y; n++; } if (!empty(srcImg1, srcImg1.width() / 2, y) && !empty(srcImg2, srcImg2.width() / 2, y)) { sum_y_overlap += y; overlap_n++; } } } int min_len = (srcImg1.width() < srcImg1.height()) ? srcImg1.width() : srcImg1.height(); int n_level = floor(log2(min_len)); vector<CImg<float> > a_pyramid(n_level); vector<CImg<float> > b_pyramid(n_level); vector<CImg<float> > mask(n_level); // Initialize the base. a_pyramid[0] = srcImg1; b_pyramid[0] = srcImg2; mask[0] = CImg<float>(srcImg1.width(), srcImg1.height(), 1, 1, 0); if (srcImg1.width() > srcImg1.height()) { if (sum_x / n < sum_x_overlap / overlap_n) { for (int x = 0; x < sum_x_overlap / overlap_n; x++) { for (int y = 0; y < srcImg1.height(); y++) { mask[0](x, y) = 1; } } } else { for (int x = sum_x_overlap / overlap_n + 1; x < srcImg1.width(); x++) { for (int y = 0; y < srcImg1.height(); y++) { mask[0](x, y) = 1; } } } } else { if (sum_y / n < sum_y_overlap / overlap_n) { for (int x = 0; x < srcImg1.width(); x++) { for (int y = 0; y < sum_y_overlap / overlap_n; y++) { mask[0](x, y) = 1; } } } else { for (int x = 0; x < srcImg1.width(); x++) { for (int y = sum_y_overlap / overlap_n; y < srcImg1.height(); y++) { mask[0](x, y) = 1; } } } } // Down sampling a and b, building Gaussian pyramids. for (int i = 1; i < n_level; i++) { a_pyramid[i] = a_pyramid[i - 1].get_blur(2).get_resize(a_pyramid[i - 1].width() / 2, a_pyramid[i - 1].height() / 2, 1, a_pyramid[i - 1].spectrum(), 3); b_pyramid[i] = b_pyramid[i - 1].get_blur(2).get_resize(b_pyramid[i - 1].width() / 2, b_pyramid[i - 1].height() / 2, 1, b_pyramid[i - 1].spectrum(), 3); mask[i] = mask[i - 1].get_blur(2).get_resize(mask[i - 1].width() / 2, mask[i - 1].height() / 2, 1, mask[i - 1].spectrum(), 3); } // Building Laplacian pyramids. for (int i = 0; i < n_level - 1; i++) { a_pyramid[i] = a_pyramid[i] - a_pyramid[i + 1].get_resize(a_pyramid[i].width(), a_pyramid[i].height(), 1, a_pyramid[i].spectrum(), 3); b_pyramid[i] = b_pyramid[i] - b_pyramid[i + 1].get_resize(b_pyramid[i].width(), b_pyramid[i].height(), 1, b_pyramid[i].spectrum(), 3); } vector<CImg<float> > blend_pyramid(n_level); // Blending for (int i = 0; i < n_level; i++) { blend_pyramid[i] = CImg<float>(a_pyramid[i].width(), a_pyramid[i].height(), 1, a_pyramid[i].spectrum(), 0); for (int x = 0; x < blend_pyramid[i].width(); x++) { for (int y = 0; y < blend_pyramid[i].height(); y++) { for (int k = 0; k < blend_pyramid[i].spectrum(); k++) { blend_pyramid[i](x, y, k) = a_pyramid[i](x, y, k) * mask[i](x, y) + b_pyramid[i](x, y, k) * (1.0 - mask[i](x, y)); } } } } // Resizing and filling empty spaces with black CImg<float> res = blend_pyramid[n_level - 1]; for (int i = n_level - 2; i >= 0; i--) { res.resize(blend_pyramid[i].width(), blend_pyramid[i].height(), 1, blend_pyramid[i].spectrum(), 3); for (int x = 0; x < blend_pyramid[i].width(); x++) { for (int y = 0; y < blend_pyramid[i].height(); y++) { for (int k = 0; k < blend_pyramid[i].spectrum(); k++) { float t = res(x, y, k) + blend_pyramid[i](x, y, k); if (t > 255) { t = 255; } else if (t < 0) { t = 0; } res(x, y, k) = t; } } } } return res; }
#pragma once #include "utils/assert.hpp" #include "utils/instance_counter.hpp" #include "proto/data_item.pb.h" namespace pd = proto::data; namespace nora { namespace scene { class item : private instance_countee { public: item(); item(uint32_t pttid, int count); void serialize(proto::data::item *item) const; void parse(const proto::data::item *item); uint32_t pttid() const; int count() const; int change_count(int value); bool confirmed() const; void set_confirmed(bool confirmed); private: uint32_t pttid_ = 0; int count_ = 0; bool confirmed_ = false; }; inline uint32_t item::pttid() const { return pttid_; } inline int item::count() const { return count_; } inline int item::change_count(int value) { count_ = max(0, count_ + value); return count_; } inline bool item::confirmed() const { return confirmed_; } inline void item::set_confirmed(bool confirmed) { confirmed_ = confirmed; } } }
#pragma once #include "../scene/Patch.h" #include "../math/Complex.h" class Utils { public: static void saveHeightmap(const std::vector<Patch::Vertex>& vertices, int N, const std::string& path); static void saveComplexMatrix(const std::vector<std::vector<Complex>>& data, const std::string& path, double Are, double Aim); static void saveDisplacementMap(const std::vector<std::vector<glm::vec2>>& data, const std::string& pathDx, const std::string& pathDy); static GLuint loadCubemap(); }; void _check_gl_error(const char* file, int line); #define check_gl_error() _check_gl_error(__FILE__,__LINE__)