text
stringlengths 8
6.88M
|
|---|
//---------------------------------------------------------------------------
#ifndef hookfuncH
#define hookfuncH
#include <windows.h>
#include <winsock.h>
#include <string>
#include "injlib.h"
#ifdef VCVERSION
#include "comm_stl.h"
#else
#include "CommFunc.h"
#endif
#include "alist.h"
using namespace std;
class CHookData
{
public:
string FuncName; //函数名
LPBYTE OrgFuncAddr; //原来的函数指针地址
LPBYTE NewFuncAddr; //替换后的函数指针地址
public:
__fastcall CHookData();
__fastcall ~CHookData();
};
//---------------------------------------------------------------------------
//拦截api函数的管理类
class CHooker
{
private:
HMODULE m_Module; //动态链接库句柄
string m_DllName; //动态链接库名字
AList<CHookData> *HookFuncList; //需要hook的函数列表
protected:
public:
public:
__fastcall CHooker(char * DllName);
__fastcall ~CHooker();
void BeginHookFunc();
void EndHookFunc();
bool RegisterFunc(char * FuncName,LPBYTE ReplaceFuncAddr); //注册替换函数,
bool IsHooked(){return m_Module != NULL;}
LPBYTE GetOrgFuncAddr(char * FuncName);
};
#endif
|
#include<conio.h>
#include<iostream.h>
#include<string.h>
void main () {
int leng, comp;
char *name="SALMAN";
char *name2="shaikh";
char *name3="2K10/CSE/73";
char *n,*up,*lowr, *cat, *dup_str, set;
char *ptr, c = 'r', check;
char *string="This is a String";
char symbol = 'x';
clrscr();
cout<<"\nBefore strset(): \n"<< string<<endl;
strset(string, symbol);
cout<<"\nAfter strset(): \n"<< string<<endl;
cout<<"\nName1 is: "<<name<<endl;
cout<<"Name2 is: "<<name2<<endl;
dup_str=strdup(name);
cout<<"\n\nDuplicate of Name1: "<<dup_str<<endl;
cout<<"\nLength of Name1 is: "<<strlen(name)<<endl;
cout<<"Length of Name2 is: "<<strlen(name2)<<endl;
cat=strcat(name, name2);
cout<<"\nAfter Concatenation: "<<cat<<endl;
comp=strcmp(name,name2);
cout <<endl<<"After Comparision of Name1 and Name2 is: "<<comp;
cout<<"\n\nOriginal case: "<<name<<endl;
up=strupr(name);
cout<<"String in upper case: "<<up<<endl;
cout<<"\nOriginal case: "<<name3<<endl;
lowr=strlwr(name3);
cout<<"String in Lower case: "<<lowr;
ptr = strchr(string, c);
cout<<endl<<"\nThe Character "<<c<<" is at position: "<<ptr-string;
check = strcoll(name, name2);
if (check == 0)
cout<<endl<<"\nThe strings are equal\n";
if (check < 0)
cout<<endl<<"\n"<<name2<<" comes before "<<name;
if (check > 0)
cout<<endl<<"\n"<<name<<" comes before "<<name2<<" \n";
n=strrev(name);
cout<<"\n\nAfter Reverse Name1: "<<n<<endl;
getche();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
#include "adjunct/m2/src/include/defs.h"
#include "adjunct/m2/src/include/mailfiles.h"
#include "engine.h"
#include "adjunct/m2/src/engine/accountmgr.h"
#include "adjunct/m2/src/engine/chatinfo.h"
#include "adjunct/m2/src/engine/indexer.h"
#include "adjunct/m2/src/engine/modules.h"
#include "adjunct/m2/src/engine/progressinfo.h"
#include "adjunct/m2/src/engine/store/storemessage.h"
#include "adjunct/m2/src/MessageDatabase/SEMessageDatabase.h"
#include "adjunct/m2/src/backend/rss/rssmodule.h"
#include "adjunct/m2/src/backend/nntp/nntpmodule.h"
#include "adjunct/m2/src/recovery/recovery.h"
#include "adjunct/m2_ui/models/indexmodel.h"
#include "adjunct/m2_ui/models/chattersmodel.h"
#include "adjunct/m2_ui/models/chatroomsmodel.h"
#include "adjunct/m2_ui/models/accountsmodel.h"
#include "adjunct/m2_ui/models/groupsmodel.h"
#include "modules/encodings/encoders/outputconverter.h"
#include "adjunct/m2/src/util/autodelete.h"
#include "adjunct/m2/src/util/qp.h"
#include "adjunct/m2/src/util/misc.h"
#include "adjunct/m2/src/util/str/strutil.h"
#include "adjunct/m2/src/import/ImportFactory.h"
#include "adjunct/m2/src/import/OperaImporter.h"
#include "adjunct/desktop_pi/DesktopMailClientUtils.h"
#include "adjunct/desktop_util/adt/hashiterator.h"
#include "adjunct/desktop_util/prefs/PrefsCollectionM2.h"
#include "adjunct/m2_ui/dialogs/DefaultMailClientDialog.h"
#include "adjunct/m2_ui/dialogs/NewAccountWizard.h"
#include "adjunct/m2_ui/dialogs/NewsfeedSubscribeDialog.h"
#include "adjunct/m2_ui/windows/MailDesktopWindow.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/dialogs/SimpleDialog.h"
#include "adjunct/quick/managers/CommandLineManager.h"
#include "adjunct/quick/managers/KioskManager.h"
#include "adjunct/quick/managers/NotificationManager.h"
#include "adjunct/quick/hotlist/HotlistManager.h"
#ifdef USE_COMMON_RESOURCES
#include "adjunct/desktop_util/resources/ResourceDefines.h"
#endif // USE_COMMON_RESOURCES
#include "adjunct/m2/src/util/quote.h"
//#include "locale/oplanguagemanager.h"
#ifdef IRC_SUPPORT
#include "adjunct/m2/src/backend/irc/irc-urlparser.h"
#include "adjunct/m2/src/backend/irc/chat-networks.h"
#include "adjunct/m2/src/backend/irc/chat-filetransfer.h"
#endif
#include "adjunct/m2/src/backend/rss/opml.h"
#include "adjunct/m2/src/backend/rss/opml_importer.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/pi/OpLocale.h"
#include "modules/prefs/prefsmanager/collections/pc_m2.h"
#include "modules/util/opstrlst.h"
#ifdef USE_COMMON_RESOURCES
#include "adjunct/desktop_util/resources/ResourceDefines.h"
#endif // USE_COMMON_RESOURCES
#ifdef M2_MERLIN_COMPATIBILITY
# include "adjunct/m2/src/engine/store/storeupdater.h"
#endif // M2_MERLIN_COMPATIBILITY
#ifdef M2_MAPI_SUPPORT
#include "adjunct/m2/src/mapi/MapiMessageListener.h"
#endif //M2_MAPI_SUPPORT
#include "adjunct/desktop_util/filelogger/desktopfilelogger.h"
#ifdef ENABLE_USAGE_REPORT
# include "adjunct/quick/usagereport/UsageReport.h"
#endif
// Delay (in ms) for calling listeners when indexes changed
#define INDEX_CHANGE_DELAY 500
MessageEngine* MessageEngine::s_instance = 0;
MessageEngine::MessageEngine()
: m_glue_factory(NULL),
m_store(NULL),
m_indexer(NULL),
m_message_database(NULL),
m_clipboard_cut(FALSE),
m_chat_networks(NULL),
m_chat_file_transfer_manager(NULL),
m_multiple_message_changes(0),
// m_sending_queued_messages(FALSE), // unused ?
m_deleting_trash(FALSE),
m_posted_index_changed(FALSE),
#ifdef IRC_SUPPORT
m_chatrooms_model(NULL),
#endif
m_account_manager(NULL),
m_accounts_model(NULL),
m_is_busy_asking_for_security_password(FALSE),
m_will_do_recover_check_on_exit(TRUE),
m_has_asked_user_about_recovery(FALSE),
m_autodelete(NULL),
m_loop(NULL),
m_master_progress(NULL),
m_mail_import_in_progress(0)
#ifdef M2_MAPI_SUPPORT
, m_check_default_mailer(TRUE)
, m_mapi_listener(NULL)
#endif //M2_MAPI_SUPPORT
{
}
MessageEngine::~MessageEngine()
{
OP_PROFILE_METHOD("Destructed MessageEngine");
#ifdef M2_MAPI_SUPPORT
OP_DELETE(m_mapi_listener);
#endif //M2_MAPI_SUPPORT
// if we are supposed to run mail db maintenance, we want to run this code to remove ghosts before deleting store and indexer
if (m_will_do_recover_check_on_exit && m_has_asked_user_about_recovery)
{
OP_PROFILE_METHOD("Ghostbuster");
MailRecovery recovery;
recovery.GhostBuster();
}
{
OP_PROFILE_METHOD("Destructed MessageEngine - phase 1");
if (g_application)
g_application->RemoveSettingsListener(this);
if (m_message_database && m_message_database->IsInitialized())
OpStatus::Ignore(m_message_database->Commit());
// m_indexer may not be created if something failed on Init()
if( m_indexer )
m_indexer->PrepareToDie();
// save messages that are waiting in queue first
// m_autodelete may not be created in if something failed on Init()
if( m_autodelete )
m_autodelete->FlushQueue();
m_index_models.DeleteAll();
m_groups_models.DeleteAll();
}
{
OP_PROFILE_METHOD("Destructed Indexer");
if (m_indexer)
m_indexer->RemoveIndexerListener(this);
OP_DELETE(m_indexer);
m_indexer = NULL;
}
{
OP_PROFILE_METHOD("Destructed AccountManager");
OP_DELETE(m_account_manager);
OP_DELETE(m_accounts_model);
}
{
OP_PROFILE_METHOD("Destructed MessageEngine - phase 2");
#ifdef IRC_SUPPORT
OP_DELETE(m_chatrooms_model);
#endif
OP_DELETE(m_message_database);
if (GetGlueFactory())
GetGlueFactory()->DeleteMessageLoop(m_loop);
#ifdef IRC_SUPPORT
if (m_chat_networks)
OP_DELETE(m_chat_networks);
if (m_chat_file_transfer_manager)
OP_DELETE(m_chat_file_transfer_manager);
#endif // IRC_SUPPORT
OP_DELETE(m_autodelete);
OP_DELETE(m_master_progress);
}
{
OP_PROFILE_METHOD("Destructed Store");
OP_DELETE(m_store);
m_store = NULL;
}
SetFactories(NULL); // after killing account manager !
// maybe we want to do maintenance on the databases
if (m_will_do_recover_check_on_exit && m_has_asked_user_about_recovery)
{
OP_PROFILE_METHOD("Mail database maintenance");
MailRecovery recovery;
// check and fix all database files
OpStatus::Ignore(recovery.CheckConsistencyAndFixAllMailDBs());
// lexicon is closed when indexer is deleted, so we can check the lexicon as well
OpStatus::Ignore(recovery.CheckAndFixLexicon());
m_will_do_recover_check_on_exit = FALSE;
}
}
BOOL MessageEngine::NeedToAskAboutDoingMailRecovery ()
{
#ifdef DU_CAP_PREFS
if (CommandLineManager::GetInstance()->GetArgument(CommandLineManager::WatirTest))
return FALSE;
// only check if it's about time to do a check if we haven't asked already
if (!m_has_asked_user_about_recovery)
{
time_t now = g_timecache->CurrentTime();
// we only ask if we should do a mail database consistency if we have never run the consistency check
if (g_pcm2->GetIntegerPref(PrefsCollectionM2::LastDatabaseCheck) == 0)
{
// we are going to ask to do a mail recovery, store the time
TRAPD(err, g_pcm2->WriteIntegerL(PrefsCollectionM2::LastDatabaseCheck, now));
// don't return TRUE if we didn't manage to update the time in the pref
m_will_do_recover_check_on_exit = err == OpStatus::OK;
return m_will_do_recover_check_on_exit;
}
else
{
// we don't need to a consistency check, so don't ask
m_will_do_recover_check_on_exit = FALSE;
return FALSE;
}
}
#endif // DU_CAP_PREFS
// we have asked, don't ask again
return FALSE;
}
OP_STATUS MessageEngine::Init(OpString8& status)
{
OP_STATUS ret = OpStatus::OK;
//Start AutoDelete early, can be used by other objects
m_autodelete = OP_NEW(AutoDelete, ());
if (!m_autodelete)
return OpStatus::ERR_NO_MEMORY;
// Setup master progress
m_master_progress = OP_NEW(ProgressInfo, ());
if (!m_master_progress)
return OpStatus::ERR_NO_MEMORY;
// Init input converters
RETURN_IF_ERROR(m_input_converter_manager.Init());
m_message_database = OP_NEW(SEMessageDatabase, (*g_main_message_handler));
if (!m_message_database)
return OpStatus::ERR_NO_MEMORY;
#ifdef M2_MERLIN_COMPATIBILITY
// need to check if we need to upgrade before creating store
StoreUpdater::NeedsUpdate();
#endif // M2_MERLIN_COMPATIBILITY
// Create Store and Indexer before initializing the MessageDatabase
m_store = OP_NEW(Store, (m_message_database));
if (!m_store)
return OpStatus::ERR_NO_MEMORY;
m_indexer = OP_NEW(Indexer, (m_message_database));
if (!m_indexer)
return OpStatus::ERR_NO_MEMORY;
m_store->SetProgressKeeper(m_master_progress);
OpString error_message;
ret = m_store->Init(error_message);
if (OpStatus::IsError(ret))
{
if (error_message.HasContent())
status.SetUTF8FromUTF16(error_message.CStr());
else
status.Set("\nStore Init() failed\n");
return ret;
}
if(g_application)
g_application->AddSettingsListener(this);
ret = InitEnginePart1(status);
#ifdef M2_MERLIN_COMPATIBILITY
if (!StoreUpdater::NeedsUpdate())
#endif //M2_MERLIN_COMPATIBILITY
{
if (OpStatus::IsSuccess(ret))
{
ret = InitEnginePart2(status);
}
}
if (OpStatus::IsError(ret) && m_account_manager)
m_account_manager->M2InitFailed();
// Setup message loop
m_loop = GetGlueFactory()->CreateMessageLoop();
if (!m_loop)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(m_loop->SetTarget(this));
// Setup notification listener
RETURN_IF_ERROR(m_master_progress->AddNotificationListener(g_notification_manager));
#ifdef M2_MAPI_SUPPORT
m_mapi_listener = OP_NEW(MapiMessageListener,());
RETURN_OOM_IF_NULL(m_mapi_listener);
#endif //M2_MAPI_SUPPORT
return ret;
}
OP_STATUS MessageEngine::InitEnginePart1(OpString8& status)
{
OP_PROFILE_METHOD("Init mail root dir completed");
OP_STATUS ret;
//Initialize accounts.ini
OpString accounts_filename;
RETURN_IF_ERROR(MailFiles::GetAccountsINIFilename(accounts_filename));
if (accounts_filename.IsEmpty())
return OpStatus::ERR_NO_MEMORY;
// create chat rooms model
#ifdef IRC_SUPPORT
m_chatrooms_model = OP_NEW(ChatRoomsModel, ());
if (!m_chatrooms_model)
return OpStatus::ERR_NO_MEMORY;
{
OP_PROFILE_METHOD("Init chat rooms model");
if ((ret=m_chatrooms_model->Init()) != OpStatus::OK)
return ret;
}
#endif
// create accounts model
m_accounts_model = OP_NEW(AccountsModel, ());
if (!m_accounts_model)
return OpStatus::ERR_NO_MEMORY;
{
OP_PROFILE_METHOD("Init accounts model");
if ((ret=m_accounts_model->Init()) != OpStatus::OK)
return ret;
}
//Initialize the one and only account_manager
{
OP_PROFILE_METHOD("Init accounts manager");
m_account_manager = OP_NEW(AccountManager, (*m_message_database));
if (!m_account_manager)
return OpStatus::ERR_NO_MEMORY;
if ((ret=m_account_manager->SetPrefsFile(accounts_filename)) != OpStatus::OK)
return ret;
if ((ret=m_account_manager->Init(status)) != OpStatus::OK)
{
status.Append("AccountManager Init failed\n");
return ret;
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::InitEnginePart2(OpString8& status)
{
OpFile custom_file;
if (m_account_manager->GetAccountCount() != 0 || GetCustomDefaultAccountsFile(custom_file))
{
RETURN_IF_ERROR(InitMessageDatabase(status));
OP_PROFILE_METHOD("AccountManager ToOnlineMode");
RETURN_IF_ERROR(m_account_manager->RemoveTemporaryAccounts());
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::InitMessageDatabaseIfNeeded()
{
if (m_message_database->IsInitialized())
return OpStatus::OK;
OpAutoPtr<OpString8> status(OP_NEW(OpString8, ()));
if (!status.get())
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsError(InitMessageDatabase(*status)))
{
g_main_message_handler->PostMessage(MSG_QUICK_MAIL_PROBLEM_INITIALIZING, (MH_PARAM_1)g_application, (MH_PARAM_2)status.release(), 10);
return OpStatus::ERR;
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::InitMessageDatabase(OpString8& status)
{
OP_PROFILE_METHOD("Indexer Init");
OpString indexer_filename;
RETURN_IF_ERROR(MailFiles::GetIndexIniFileName(indexer_filename));
RETURN_IF_ERROR(m_indexer->Init(indexer_filename, status));
RETURN_IF_ERROR(m_indexer->AddIndexerListener(this));
return m_message_database->Init(m_store, m_indexer, this, m_indexer->GetLexicon());
}
void MessageEngine::FlushAutodeleteQueue()
{
if (m_autodelete)
m_autodelete->FlushQueue();
}
// ----------------------------------------------------
#ifdef USE_COMMON_RESOURCES
#define __ACCOUNTS_DEFAULT DESKTOP_RES_STD_ACCOUNTS
#else
#define __ACCOUNTS_DEFAULT UNI_L("accounts_default.ini")
#endif // USE_COMMON_RESOURCES
BOOL MessageEngine::GetCustomDefaultAccountsFile(OpFile& file)
{
OpString filename;
BOOL exists;
if ((g_application->DetermineFirstRunType() != Application::RUNTYPE_FIRSTCLEAN))
return FALSE;
// Get prefsfile that countains default accounts
OpString icpfolder;
RETURN_VALUE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_INI_CUSTOM_PACKAGE_FOLDER, icpfolder), FALSE);
RETURN_VALUE_IF_ERROR(filename.AppendFormat(UNI_L("%s%c%s"),
icpfolder.CStr(),
PATHSEPCHAR,__ACCOUNTS_DEFAULT), FALSE);
// Check if file exists
RETURN_VALUE_IF_ERROR(file.Construct(filename.CStr()), FALSE);
RETURN_VALUE_IF_ERROR(file.Exists(exists), FALSE);
return exists;
}
OP_STATUS MessageEngine::InitDefaultAccounts()
{
OpFile file;
if (!GetCustomDefaultAccountsFile(file))
return OpStatus::OK;
// Open prefsfile
OP_STATUS status = OpStatus::OK;
TRAP(status,
{
PrefsFile defaults(PREFS_STD);
defaults.ConstructL();
defaults.SetFileL(&file);
defaults.LoadAllL();
/* Read default RSS accounts */
PrefsSection* rss_section = defaults.ReadSectionL(UNI_L("RSS"));
if (!rss_section)
return OpStatus::ERR_NULL_POINTER;
OpAutoPtr<OpString_list> rss_list(rss_section->GetKeyListL());
if (!rss_list.get())
return OpStatus::ERR_NULL_POINTER;
/* Add RSS accounts */
for(UINT32 i = 0; i < rss_list->Count(); i++)
{
URL dummy;
RETURN_IF_ERROR(LoadRSSFeed(rss_list->Item(i), dummy, FALSE, FALSE));
}
} );
return status;
}
// ----------------------------------------------------
BOOL MessageEngine::InitM2OnStartup()
{
// Check if M2 has been disabled somewhere
BOOL init_mail = KioskManager::GetMailEnabled();
init_mail &= !CommandLineManager::GetInstance()->GetArgument(CommandLineManager::NoMail);
init_mail &= g_pcm2->GetIntegerPref(PrefsCollectionM2::ShowEmailClient);
#ifdef EMBROWSER_SUPPORT
//never start M2 if embedded in another application
extern long gVendorDataID;
init_mail &= (gVendorDataID == 'OPRA');
#endif
return init_mail;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::GetGroupsModel(OpTreeModel** accounts_model, UINT16 account_id, BOOL read_only)
{
GroupsModel* model = NULL;
if (read_only)
{
INT32 count = m_groups_models.GetCount();
for (INT32 i = 0; i < count; i++)
{
GroupsModel* cached_model = m_groups_models.Get(i);
if (cached_model->GetAccountId() == account_id)
{
model = cached_model;
break;
}
}
}
if (!model)
{
model = OP_NEW(GroupsModel, ());
RETURN_IF_ERROR(model->Init(account_id, read_only));
if (read_only)
{
m_groups_models.Add(model);
}
}
model->IncRefCount();
*accounts_model = model;
return OpStatus::OK;
}
OP_STATUS MessageEngine::ReleaseGroupsModel(OpTreeModel* tree_model, BOOL commit)
{
GroupsModel* model = (GroupsModel*)tree_model;
if (commit)
{
model->Commit();
}
// if found in cache list, it is read only
INT32 count = m_groups_models.GetCount();
for (INT32 i = 0; i < count; i++)
{
GroupsModel* cached_model = m_groups_models.Get(i);
if (model == cached_model)
{
model->DecRefCount();
return OpStatus::OK;
}
}
// not found.. it was writable.. delete it
OP_DELETE(model);
return OpStatus::OK;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::SubscribeFolder(OpTreeModel* tree_model, UINT32 item_id, BOOL subscribe)
{
GroupsModel* model = (GroupsModel*)tree_model;
return model->SubscribeFolder(item_id, subscribe);
}
OP_STATUS MessageEngine::CreateFolder(OpTreeModel* tree_model, UINT32* item_id)
{
OpString default_folder_name;
OpString default_folder_path;
OpString8 protocol;
RETURN_IF_ERROR(g_languageManager->GetString(Str::S_DEFAULT_IMAP_NEW_FOLDER_NAME, default_folder_name));
default_folder_path.Set(default_folder_name);
GroupsModel* model = (GroupsModel*)tree_model;
Account* account = GetAccountById(model->GetAccountId());
if (account->GetIncomingProtocol() == AccountTypes::RSS)
{
RETURN_IF_ERROR(g_languageManager->GetString(Str::S_RSS_NEWSFOLDER, default_folder_name));
default_folder_path.Set(UNI_L("http://example"));
Index* index = m_indexer->GetSubscribedFolderIndex(account, default_folder_path, 0, default_folder_name, TRUE, FALSE);
if (index != 0)
index->SetUpdateFrequency(-1); // So that a newly created dummy rss feed won't attempt to update itself just quite yet.
*item_id = model->GetItemByPath(default_folder_path);
if (1 + *item_id != 0)
{
return OpStatus::OK; // exists
}
}
*item_id = model->AddFolder(default_folder_name, default_folder_path, FALSE, TRUE, TRUE, TRUE, TRUE);
return OpStatus::OK;
}
OP_STATUS MessageEngine::UpdateFolder(OpTreeModel* tree_model, UINT32 item_id, OpStringC& path, OpStringC& name)
{
GroupsModel* model = (GroupsModel*)tree_model;
model->UpdateFolder(item_id, path, name);
return OpStatus::OK;
}
OP_STATUS MessageEngine::DeleteFolder(OpTreeModel* tree_model, UINT32 item_id)
{
GroupsModel* model = static_cast<GroupsModel*>(tree_model);
GroupsModelItem* item = model->GetItemByID(item_id);
OP_STATUS ret;
OpString path;
if ((ret=item->GetPath(path)) != OpStatus::OK)
return ret;
UINT16 account_id = model->GetAccountId();
Account* account = GetAccountById(account_id);
// UINT32 index_id = item->GetIndexId();
// Index* index = (m_indexer ? m_indexer->GetIndexById(index_id) : NULL);
if (account && path.HasContent() && path.CompareI("INDEX"))
{
// Remove folder from account
account->DeleteFolder(path);
}
model->OnFolderRemoved(account_id, path);
return OpStatus::OK;
}
OP_STATUS MessageEngine::UpdateNewsGroupIndexList()
{
return m_indexer->UpdateNewsGroupIndexList();
}
// ----------------------------------------------------
OP_STATUS MessageEngine::GetIndexModel(OpTreeModel** index_model, Index* index, INT32& start_pos)
{
if (!m_store->HasFinishedLoading())
return OpStatus::ERR_YIELD;
start_pos = -1;
if (index)
{
OP_STATUS ret;
// search list first
for (UINT m = 0; m < m_index_models.GetCount(); m++)
{
IndexModel* model = m_index_models.Get(m);
if (model && model->GetIndexId() == index->GetId())
{
start_pos = model->GetStartPos();
model->IncRefCount();
*index_model = model;
return OpStatus::OK;
}
}
if ((ret=index->PreFetch()) != OpStatus::OK)
return ret;
IndexModel* model = OP_NEW(IndexModel, ());
if (!model)
return OpStatus::ERR_NO_MEMORY;
if ((ret=model->Init(index)) != OpStatus::OK)
return ret;
start_pos = model->GetStartPos();
model->IncRefCount(); // set refcount to 1
*index_model = model;
m_index_models.Add(model);
return OpStatus::OK;
}
return OpStatus::ERR;
}
// ----------------------------------------------------
#ifdef IRC_SUPPORT
ChatNetworkManager* MessageEngine::GetChatNetworks()
{
if (m_chat_networks == 0)
{
m_chat_networks = OP_NEW(ChatNetworkManager, ());
if (m_chat_networks != 0 &&
OpStatus::IsError(m_chat_networks->Init()))
{
OP_DELETE(m_chat_networks);
m_chat_networks = 0;
}
}
return m_chat_networks;
}
ChatFileTransferManager* MessageEngine::GetChatFileTransferManager()
{
if (m_chat_file_transfer_manager == 0)
m_chat_file_transfer_manager = OP_NEW(ChatFileTransferManager, ());
return m_chat_file_transfer_manager;
}
#endif
// ----------------------------------------------------
OP_STATUS MessageEngine::GetIndexModel(OpTreeModel** index_model, index_gid_t index_id, INT32& start_pos)
{
return GetIndexModel(index_model, m_indexer->GetIndexById(index_id), start_pos);
}
OP_STATUS MessageEngine::WriteViewPrefs(IndexTypes::ModelSort sort, BOOL ascending, IndexTypes::ModelType type, IndexTypes::GroupingMethods grouping_method)
{
TRAPD(status,
g_pcm2->WriteIntegerL(PrefsCollectionM2::DefaultMailSorting, sort);
g_pcm2->WriteIntegerL(PrefsCollectionM2::DefaultMailSortingAscending, ascending);
g_pcm2->WriteIntegerL(PrefsCollectionM2::DefaultMailFlatThreadedView, type);
g_pcm2->WriteIntegerL(PrefsCollectionM2::MailGroupingMethod, grouping_method);
g_prefsManager->CommitL());
return status;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::SetIndexModelType(index_gid_t index_id, IndexTypes::ModelType type, IndexTypes::ModelAge age, INT32 flags, IndexTypes::ModelSort sort, BOOL ascending, IndexTypes::GroupingMethods grouping_method, message_gid_t selected_message)
{
Index* index = m_indexer->GetIndexById(index_id);
if (index)
{
BOOL reinit = FALSE, reinit_all = FALSE;
if (index->GetModelFlags() != flags)
{
index->SetModelFlags(flags);
reinit = TRUE;
}
if (index->GetModelAge() != age)
{
index->SetModelAge(age);
reinit = TRUE;
}
if (index->GetOverrideDefaultSorting())
{
index->SetModelSort(sort);
index->SetModelSortAscending(ascending != FALSE);
index->SetModelGroup(grouping_method);
index->SetModelType(type);
}
else
{
if (g_pcm2->GetIntegerPref(PrefsCollectionM2::DefaultMailSorting) != sort)
{
reinit_all = TRUE;
}
if (g_pcm2->GetIntegerPref(PrefsCollectionM2::DefaultMailSortingAscending) != ascending)
{
reinit_all = TRUE;
}
// these indexes should always have a different type from the global
if (index->IsContact() ||
index->GetId() == IndexTypes::OUTBOX ||
index->GetId() == IndexTypes::SENT ||
index->GetId() == IndexTypes::DRAFTS ||
index->GetId() == IndexTypes::SPAM ||
index->GetId() == IndexTypes::TRASH )
{
if (index->GetModelType() != type)
{
index->SetModelType(type);
reinit = TRUE;
}
}
else
{
if (type != static_cast<IndexTypes::ModelType>(g_pcm2->GetIntegerPref(PrefsCollectionM2::DefaultMailFlatThreadedView)))
{
reinit_all = TRUE;
}
}
if (grouping_method != static_cast<IndexTypes::GroupingMethods>(g_pcm2->GetIntegerPref(PrefsCollectionM2::MailGroupingMethod)))
{
reinit_all = TRUE;
}
RETURN_IF_ERROR(WriteViewPrefs(sort, ascending, type, grouping_method));
}
index->SetModelSelectedMessage(selected_message);
if (reinit || reinit_all)
{
RETURN_IF_ERROR(m_indexer->UpdateIndex(index_id));
UINT32 count = m_index_models.GetCount();
for (UINT m = 0; m < count; m++)
{
IndexModel* model = m_index_models.Get(m);
if (model && (reinit_all || (model->GetIndexId() == index_id)))
{
model->ReInit();
}
}
}
if (index_id == IndexTypes::UNREAD_UI)
{
RETURN_IF_ERROR(SetIndexModelType(IndexTypes::UNREAD, type, age, flags, sort, ascending, grouping_method, selected_message));
OnIndexChanged(index_id);
}
return OpStatus::OK;
}
return OpStatus::ERR;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::GetIndexModelType(index_gid_t index_id, IndexTypes::ModelType& type, IndexTypes::ModelAge& age, INT32& flags, IndexTypes::ModelSort& sort, BOOL& ascending, IndexTypes::GroupingMethods& grouping_method, message_gid_t& selected_message)
{
if (index_id == IndexTypes::UNREAD_UI)
index_id = IndexTypes::UNREAD;
Index* index = m_indexer->GetIndexById(index_id);
if (index)
{
age = index->GetModelAge();
flags = index->GetModelFlags();
selected_message = index->GetModelSelectedMessage();
if (index->GetOverrideDefaultSorting())
{
sort = index->GetModelSort();
ascending = index->GetModelSortAscending();
type = index->GetModelType();
grouping_method = index->GetModelGrouping();
}
else
{
sort = static_cast<IndexTypes::ModelSort>(g_pcm2->GetIntegerPref(PrefsCollectionM2::DefaultMailSorting));
ascending = g_pcm2->GetIntegerPref(PrefsCollectionM2::DefaultMailSortingAscending);
if (index->IsContact() ||
index->GetId() == IndexTypes::OUTBOX ||
index->GetId() == IndexTypes::SENT ||
index->GetId() == IndexTypes::DRAFTS ||
index->GetId() == IndexTypes::SPAM ||
index->GetId() == IndexTypes::TRASH )
{
type = index->GetModelType();
}
else
{
type = static_cast<IndexTypes::ModelType>(g_pcm2->GetIntegerPref(PrefsCollectionM2::DefaultMailFlatThreadedView));
}
grouping_method = static_cast<IndexTypes::GroupingMethods>(g_pcm2->GetIntegerPref(PrefsCollectionM2::MailGroupingMethod));
}
return OpStatus::OK;
}
return OpStatus::ERR;
}
// ----------------------------------------------------
index_gid_t MessageEngine::GetIndexIDByAddress(OpString& address)
{
OpString temp;
temp.Set(address);
Index* index = m_indexer->GetCombinedContactIndex(temp);
return index ? index->GetId() : 0;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::ReleaseIndexModel(OpTreeModel* index_model)
{
if (index_model)
{
// search list first
UINT32 count = m_index_models.GetCount();
for (UINT m = 0; m < count; m++)
{
IndexModel* model = m_index_models.Get(m);
if (model && model == index_model)
{
if (model->DecRefCount() <= 0 && count > 50)
{
m_index_models.Delete(m);
}
return OpStatus::OK;
}
}
return OpStatus::OK;
}
return OpStatus::ERR;
}
// ----------------------------------------------------
Account* MessageEngine::GetAccountById(UINT16 account_id)
{
Account* account = NULL;
m_account_manager->GetAccountById(account_id, account);
return account;
}
// ----------------------------------------------------
#ifdef IRC_SUPPORT
ChatRoom* MessageEngine::GetChatRoom(UINT32 room_id)
{
return m_chatrooms_model->GetChatRoom(room_id);
}
ChatRoom* MessageEngine::GetChatRoom(UINT16 account_id, OpString& room)
{
return m_chatrooms_model->GetRoomItem(account_id, room);
}
ChatRoom* MessageEngine::GetChatter(UINT32 chatter_id)
{
return m_chatrooms_model->GetChatter(chatter_id);
}
OP_STATUS MessageEngine::DeleteChatRoom(UINT32 room_id)
{
m_chatrooms_model->DeleteChatRoom(room_id);
return OpStatus::OK;
}
#endif
UINT32 MessageEngine::GetIndexIdFromFolder(OpTreeModelItem* item)
{
GroupsModelItem* group_item = (GroupsModelItem*)item;
return group_item->GetIndexId();
}
// ----------------------------------------------------
#ifdef IRC_SUPPORT
OP_STATUS MessageEngine::GetChattersModel(OpTreeModel** chatters_model,
UINT16 account_id, const OpStringC& room)
{
*chatters_model = m_chatrooms_model->GetChattersModel(account_id, room);
if (*chatters_model)
{
return OpStatus::OK;
}
return OpStatus::ERR;
}
#endif // IRC_SUPPORT
// ----------------------------------------------------
OP_STATUS MessageEngine::Connect(UINT16 account_id)
{
Account* account = GetAccountById(account_id);
if (!account)
return OpStatus::ERR;
account->Connect();
return OpStatus::OK;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::JoinChatRoom(UINT16 account_id, const OpStringC& room, const OpStringC& password)
{
Account* account = GetAccountById(account_id);
if (!account)
return OpStatus::ERR;
account->JoinChatRoom(room, password);
return OpStatus::OK;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::LeaveChatRoom(UINT16 account_id, const ChatInfo& room)
{
Account* account = GetAccountById(account_id);
if (!account)
return OpStatus::ERR;
account->LeaveChatRoom(room);
return OpStatus::OK;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::SendChatMessage(UINT16 account_id,
EngineTypes::ChatMessageType type, const OpString& message, const ChatInfo& room,
const OpStringC& chatter)
{
Account* account = GetAccountById(account_id);
if (!account)
return OpStatus::ERR;
account->SendChatMessage(type, message, room, chatter);
return OpStatus::OK;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::SetChatProperty(UINT16 account_id,
const ChatInfo& room, const OpStringC& chatter, EngineTypes::ChatProperty property,
const OpStringC& property_string, INT32 property_value)
{
Account* account = GetAccountById(account_id);
if (!account)
return OpStatus::ERR;
return account->SetChatProperty(room, chatter, property, property_string, property_value);
}
// ----------------------------------------------------
OP_STATUS MessageEngine::SendFile(UINT16 account_id, const OpStringC& chatter, const OpStringC& filename)
{
Account* account = GetAccountById(account_id);
if (!account)
return OpStatus::ERR;
return account->SendFile(chatter, filename);
}
/***********************************************************************************
**
** Implementing the distribution of Engine events to listeners
**
***********************************************************************************/
// ----------------------------------------------------
void MessageEngine::OnImporterProgressChanged(const Importer* importer, const OpStringC& infoMsg, OpFileLength current, OpFileLength total, BOOL simple)
{
for (UINT32 i = 0; i < m_engine_listeners.GetCount(); i++)
{
m_engine_listeners.Get(i)->OnImporterProgressChanged(importer, infoMsg, current, total, simple);
}
}
// ----------------------------------------------------
void MessageEngine::OnImporterFinished(const Importer* importer, const OpStringC& infoMsg)
{
for (UINT32 i = 0; i < m_engine_listeners.GetCount(); i++)
{
m_engine_listeners.Get(i)->OnImporterFinished(importer, infoMsg);
}
}
// ----------------------------------------------------
void MessageEngine::OnIndexChanged(UINT32 index_id)
{
if (m_multiple_message_changes > 0 || m_index_changed.Contains(index_id) || !m_loop)
return;
OpStatus::Ignore(m_index_changed.Insert(index_id));
if (!m_posted_index_changed)
{
m_loop->Post(MSG_M2_INDEX_CHANGED, INDEX_CHANGE_DELAY);
m_posted_index_changed = TRUE;
}
}
OP_STATUS MessageEngine::ReinitAllIndexModels()
{
UINT32 count = m_index_models.GetCount();
for (UINT m = 0; m < count; m++)
{
RETURN_IF_ERROR(m_index_models.Get(m)->ReInit());
}
return OpStatus::OK;
}
void MessageEngine::OnActiveAccountChanged()
{
// heavy, but needed
RETURN_VOID_IF_ERROR(ReinitAllIndexModels());
for (UINT32 i = 0; i < m_engine_listeners.GetCount(); i++)
{
m_engine_listeners.Get(i)->OnActiveAccountChanged();
}
Index* index;
for (INT32 it = -1; (index = m_indexer->GetRange(0, IndexTypes::LAST, it)) != NULL; )
{
index->ResetUnreadCount(); // OK, doesn't need optimization
}
OnIndexChanged(static_cast<UINT32>(-1));
}
void MessageEngine::OnReindexingProgressChanged(INT32 progress, INT32 total)
{
for (UINT32 i = 0; i < m_engine_listeners.GetCount(); i++)
{
m_engine_listeners.Get(i)->OnReindexingProgressChanged(progress, total);
}
}
void MessageEngine::OnSettingsChanged(DesktopSettings* settings)
{
if (settings->IsChanged(SETTINGS_LANGUAGE) && m_message_database->IsInitialized())
{
m_indexer->UpdateTranslatedStrings();
}
}
void MessageEngine::OnAccountAdded(UINT16 account_id)
{
for (UINT32 i = 0; i < m_account_listeners.GetCount(); i++)
{
m_account_listeners.Get(i)->OnAccountAdded(account_id);
}
}
void MessageEngine::OnAccountRemoved(UINT16 account_id, AccountTypes::AccountType account_type)
{
for (UINT32 i = 0; i < m_account_listeners.GetCount(); i++)
{
m_account_listeners.Get(i)->OnAccountRemoved(account_id, account_type);
}
}
// ----------------------------------------------------
void MessageEngine::OnFolderAdded(UINT16 account_id, const OpStringC& name, const OpStringC& path, BOOL subscribedLocally, INT32 subscribedOnServer, BOOL editable)
{
for (UINT32 i = 0; i < m_account_listeners.GetCount(); i++)
{
m_account_listeners.Get(i)->OnFolderAdded(account_id, name, path, subscribedLocally, subscribedOnServer, editable);
}
}
void MessageEngine::OnFolderRemoved(UINT16 account_id, const OpStringC& path)
{
for (UINT32 i = 0; i < m_account_listeners.GetCount(); i++)
{
m_account_listeners.Get(i)->OnFolderRemoved(account_id, path);
}
}
void MessageEngine::OnFolderRenamed(UINT16 account_id, const OpStringC& old_path, const OpStringC& new_path)
{
for (UINT32 i = 0; i < m_account_listeners.GetCount(); i++)
{
m_account_listeners.Get(i)->OnFolderRenamed(account_id, old_path, new_path);
}
}
void MessageEngine::OnFolderLoadingCompleted(UINT16 account_id)
{
for (UINT32 i = 0; i < m_account_listeners.GetCount(); ++i)
{
m_account_listeners.Get(i)->OnFolderLoadingCompleted(account_id);
}
}
/***********************************************************************************
**
** Implementing the distribution of Message events to listeners
**
***********************************************************************************/
void MessageEngine::OnMessageBodyChanged(StoreMessage& message)
{
for (UINT32 i = 0; i < m_message_listeners.GetCount(); i++)
{
m_message_listeners.Get(i)->OnMessageBodyChanged(message.GetId());
}
}
// ----------------------------------------------------
void MessageEngine::OnMessageChanged(message_gid_t message_id)
{
if (m_multiple_message_changes > 0)
{
return;
}
for (UINT32 i = 0; i < m_message_listeners.GetCount(); i++)
{
m_message_listeners.Get(i)->OnMessageChanged(message_id);
}
}
// ----------------------------------------------------
void MessageEngine::OnMessageMadeAvailable(message_gid_t message_id, BOOL read)
{
for (INT32 i = (INT32)m_message_listeners.GetCount()-1; i >= 0 ; i--)
{
if (!m_multiple_message_changes)
m_message_listeners.Get(i)->OnMessageChanged(message_id);
m_message_listeners.Get(i)->OnMessageBodyChanged(message_id);
}
}
// ----------------------------------------------------
void MessageEngine::OnAllMessagesAvailable()
{
if (m_account_manager)
{
m_account_manager->OnAllMessagesAvailable();
OpStatus::Ignore(m_account_manager->ToOnlineMode());
}
if (g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRSTCLEAN)
InitDefaultAccounts();
for (UINT32 i = 0; i < m_message_listeners.GetCount(); i++)
{
m_message_listeners.Get(i)->OnMessageChanged(UINT_MAX);
m_message_listeners.Get(i)->OnMessageBodyChanged(UINT_MAX);
}
#ifdef M2_MAPI_SUPPORT
if (m_mapi_listener)
m_mapi_listener->OperaIsInitialized();
#endif //M2_MAPI_SUPPORT
}
// ----------------------------------------------------
void MessageEngine::OnMessageHidden(message_gid_t message_id, BOOL hidden)
{
if (m_multiple_message_changes > 0)
{
return;
}
// update unread status
Index* index = NULL;
for (INT32 it = -1; (index = m_indexer->GetRange(0, IndexTypes::LAST, it)) != NULL; )
{
if (message_id == UINT_MAX)
{
index->ResetUnreadCount(); // OK, doesn't need optimization
}
else if (index->Contains(message_id))
{
INT32 model_flags = index->GetModelFlags();
if ((model_flags&(1<<IndexTypes::MODEL_FLAG_HIDDEN))==0)
{
Index* unread = m_indexer->GetIndexById(IndexTypes::UNREAD);
if (unread->Contains(message_id))
{
index->ResetUnreadCount(); // OK, is only called from manual filtering
}
}
OnIndexChanged(index->GetId());
}
}
OnMessageChanged(message_id);
}
// ----------------------------------------------------
void MessageEngine::OnMessagesRead(const OpINT32Vector& message_ids, BOOL read)
{
for (UINT32 i = 0; i < m_message_listeners.GetCount(); i++)
{
m_message_listeners.Get(i)->OnMessagesRead(message_ids, read);
}
}
// ----------------------------------------------------
void MessageEngine::OnMessageReplied(message_gid_t message_id)
{
for (UINT32 i = 0; i < m_message_listeners.GetCount(); i++)
{
m_message_listeners.Get(i)->OnMessageReplied(message_id);
}
}
/***********************************************************************************
**
** Implementing the distribution of Interaction events to listeners
**
***********************************************************************************/
void MessageEngine::OnChangeNickRequired(UINT16 account_id, const OpStringC& old_nick)
{
for (UINT32 i = 0; i < m_interaction_listeners.GetCount(); i++)
{
m_interaction_listeners.Get(i)->OnChangeNickRequired(account_id, old_nick);
}
}
void MessageEngine::OnRoomPasswordRequired(UINT16 account_id, const OpStringC& room)
{
for (UINT32 i = 0; i < m_interaction_listeners.GetCount(); i++)
{
m_interaction_listeners.Get(i)->OnRoomPasswordRequired(account_id, room);
}
}
// ----------------------------------------------------
void MessageEngine::OnError(UINT16 account_id, const OpStringC& errormessage, const OpStringC& context, EngineTypes::ErrorSeverity severity)
{
for (UINT32 i = 0; i < m_interaction_listeners.GetCount(); i++)
{
//#pragma PRAGMAMSG("FG: Console doesn't handle anything but Critical very well yet (no prefs for opening severity 'Error' for M2)")
m_interaction_listeners.Get(i)->OnError(account_id, errormessage, context, EngineTypes::GENERIC_ERROR);
}
}
void MessageEngine::OnYesNoInputRequired(UINT16 account_id, EngineTypes::YesNoQuestionType type, OpString* sender, OpString* param)
{
for (UINT32 i = 0; i < m_interaction_listeners.GetCount(); i++)
{
m_interaction_listeners.Get(i)->OnYesNoInputRequired(account_id, type, sender, param);
}
}
/***********************************************************************************
**
** Implementing the distribution of Chat events to listeners
**
***********************************************************************************/
#ifdef IRC_SUPPORT
void MessageEngine::OnChatStatusChanged(UINT16 account_id)
{
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatStatusChanged(account_id);
}
}
// ----------------------------------------------------
void MessageEngine::OnChatMessageReceived(UINT16 account_id,
EngineTypes::ChatMessageType type, const OpStringC& message,
const ChatInfo& chat_info, const OpStringC& chatter, BOOL is_private_chat)
{
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatMessageReceived(account_id, type,
message, chat_info, chatter, is_private_chat);
}
}
// ----------------------------------------------------
void MessageEngine::OnChatServerInformation(UINT16 account_id, const OpStringC& server,
const OpStringC& information)
{
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatServerInformation(account_id, server, information);
}
}
// ----------------------------------------------------
void MessageEngine::OnChatRoomJoined(UINT16 account_id, const ChatInfo& room)
{
UINT32 i;
for (i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatRoomJoining(account_id, room);
}
for (i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatRoomJoined(account_id, room);
}
}
// ----------------------------------------------------
void MessageEngine::OnChatRoomLeft(UINT16 account_id, const ChatInfo& room,
const OpStringC& kicker, const OpStringC& kick_reason)
{
UINT32 i;
for (i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatRoomLeaving(account_id, room, kicker, kick_reason);
}
for (i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatRoomLeft(account_id, room, kicker, kick_reason);
}
}
// ----------------------------------------------------
void MessageEngine::OnChatterJoined(UINT16 account_id, const ChatInfo& room,
const OpStringC& chatter, BOOL is_operator, BOOL is_voiced,
const OpStringC& prefix, BOOL initial)
{
UINT32 i;
for (i = 0; i < m_chat_listeners.GetCount(); i++)
{
if (!m_chat_listeners.Get(i)->OnChatterJoining(account_id, room, chatter, is_operator, is_voiced, prefix, initial))
return;
}
for (i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatterJoined(account_id, room, chatter, is_operator, is_voiced, prefix, initial);
}
}
// ----------------------------------------------------
void MessageEngine::OnChatterLeft(UINT16 account_id, const ChatInfo& room,
const OpStringC& chatter, const OpStringC& message, const OpStringC& kicker)
{
UINT32 i;
for (i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatterLeaving(account_id, room, chatter, message, kicker);
}
for (i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatterLeft(account_id, room, chatter, message, kicker);
}
}
// ----------------------------------------------------
void MessageEngine::OnChatPropertyChanged(UINT16 account_id, const ChatInfo& room,
const OpStringC& chatter, const OpStringC& changed_by,
EngineTypes::ChatProperty property, const OpStringC& property_string,
INT32 property_value)
{
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnChatPropertyChanged(account_id, room, chatter, changed_by, property, property_string, property_value);
}
}
void MessageEngine::OnWhoisReply(UINT16 account_id, const OpStringC& nick, const OpStringC& user_id, const OpStringC& host,
const OpStringC& real_name, const OpStringC& server, const OpStringC& server_info, const OpStringC& away_message,
const OpStringC& logged_in_as, BOOL is_irc_operator, int seconds_idle, int signed_on, const OpStringC& channels)
{
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); i++)
{
m_chat_listeners.Get(i)->OnWhoisReply(account_id, nick, user_id, host, real_name, server,
server_info, away_message, logged_in_as, is_irc_operator, seconds_idle, signed_on, channels);
}
}
void MessageEngine::OnInvite(UINT16 account_id, const OpStringC& nick, const ChatInfo& room)
{
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); ++i)
{
m_chat_listeners.Get(i)->OnInvite(account_id, nick, room);
}
}
void MessageEngine::OnFileReceiveRequest(UINT16 account_id, const OpStringC& sender,
const OpStringC& filename, UINT32 file_size, UINT port_number, UINT id)
{
if (KioskManager::GetInstance()->GetNoSave() ||
KioskManager::GetInstance()->GetNoDownload())
{
// We can't accept files in kiosk mode.
return;
}
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); ++i)
{
m_chat_listeners.Get(i)->OnFileReceiveRequest(account_id, sender, filename, file_size, port_number, id);
}
}
void MessageEngine::OnUnattendedChatCountChanged(OpWindow* op_window, UINT32 unread)
{
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); ++i)
{
m_chat_listeners.Get(i)->OnUnattendedChatCountChanged(op_window, unread);
}
}
void MessageEngine::OnChatReconnecting(UINT16 account_id, const ChatInfo& room)
{
for (UINT32 i = 0; i < m_chat_listeners.GetCount(); ++i)
{
m_chat_listeners.Get(i)->OnChatReconnecting(account_id, room);
}
}
#endif // IRC_SUPPORT
/***********************************************************************************
**
** Implementing the reporting of results from interaction
**
***********************************************************************************/
OP_STATUS MessageEngine::ReportAuthenticationDialogResult(const OpStringC& user_name, const OpStringC& password, BOOL cancel, BOOL remember)
{
// TO DO, fill in code
return OpStatus::OK;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::ReportChangeNickDialogResult(UINT16 account_id, OpString& new_nick)
{
Account* account = GetAccountById(account_id);
if (!account)
return OpStatus::ERR;
return account->ChangeNick(new_nick);
}
OP_STATUS MessageEngine::ReportRoomPasswordResult(UINT16 account_id, OpString& room, OpString& password)
{
Account* account = GetAccountById(account_id);
if (!account)
return OpStatus::ERR;
// We MUST NOT lookup the password when responding to the dialog as we don't want
// it to find any passwords saved, if no password is entered, or something new
return account->JoinChatRoom(room, password, TRUE);
}
// ----------------------------------------------------
OP_STATUS MessageEngine::Sent(Account* account, message_gid_t uid, OP_STATUS transmit_status)
{
if (transmit_status == OpStatus::OK)
{
m_store->MessageSent(uid);
#ifdef ENABLE_USAGE_REPORT
if (g_mail_report)
g_mail_report->IncreaseSentMailCount();
#endif
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::SignalStartSession(BOOL incoming)
{
#if 0
BrowserUtils* browser_utils = GetGlueFactory()->GetBrowserUtils();
if (incoming)
{
m_incoming_sessions++;
if (m_incoming_sessions==1 && browser_utils)
browser_utils->UpdateAllInputActionsButtons();
}
else
{
m_outgoing_sessions++;
if (m_outgoing_sessions==1 && browser_utils)
browser_utils->UpdateAllInputActionsButtons();
}
#endif
return OpStatus::OK;
}
OP_STATUS MessageEngine::SignalEndSession(BOOL incoming, int message_count, BOOL report_session)
{
#if 0
BrowserUtils* browser_utils = GetGlueFactory()->GetBrowserUtils();
if (incoming)
{
if (report_session)
m_total_downloaded_messages += message_count;
m_incoming_sessions--;
if (m_incoming_sessions==0)
{
if (browser_utils)
browser_utils->UpdateAllInputActionsButtons();
}
}
else
{
if (report_session)
m_total_uploaded_messages += message_count;
m_outgoing_sessions--;
if (m_outgoing_sessions==0)
{
if (browser_utils)
browser_utils->UpdateAllInputActionsButtons();
}
}
m_report_sessions |= report_session;
if (m_incoming_sessions==0 && m_outgoing_sessions==0 && m_report_sessions)
{
OpString status_text;
if (m_total_downloaded_messages==0 && m_total_uploaded_messages==0)
{
OpStatus::Ignore(g_languageManager->GetString(Str::S_NO_NEW_MESSAGES, status_text));
}
else
{
OpString format_string;
if (m_total_downloaded_messages>0)
{
OpStatus::Ignore(g_languageManager->GetString(Str::S_DOWNLOADED_MESSAGE_COUNT, format_string));
OpString downloaded_string;
downloaded_string.AppendFormat(format_string.CStr(), m_total_downloaded_messages);
OpStatus::Ignore(status_text.Set(downloaded_string));
}
if (m_total_uploaded_messages>0)
{
if (status_text.HasContent())
OpStatus::Ignore(status_text.Append(UNI_L(", ")));
OpStatus::Ignore(g_languageManager->GetString(Str::S_MESSAGES_SENT, format_string));
OpString uploaded_string;
uploaded_string.AppendFormat(format_string.CStr(), m_total_uploaded_messages);
OpStatus::Ignore(status_text.Append(uploaded_string));
}
}
ProgressInfo dummy_progress;
BOOL dummy;
dummy_progress.Clear(dummy);
dummy_progress.m_display_flag = ProgressInfo::DISPLAY_NEWMESSAGES;
dummy_progress.m_protocol_count = m_total_downloaded_messages;
dummy_progress.m_protocol_size = m_total_uploaded_messages;
OnProgressChanged(dummy_progress, status_text);
m_total_downloaded_messages = m_total_uploaded_messages = 0;
m_report_sessions = FALSE;
}
#endif
return OpStatus::OK;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::CreateMessage(Message& new_message, UINT16 account_id, message_gid_t old_message_id, MessageTypes::CreateType type) const
{
return new_message.Init(account_id, old_message_id, type);
}
Account* MessageEngine::CreateAccount()
{
RETURN_VALUE_IF_ERROR(InitMessageDatabaseIfNeeded(), NULL);
return OP_NEW(Account, (*m_message_database));
}
OP_STATUS MessageEngine::SetOfflineMode(BOOL offline_mode)
{
if (offline_mode)
return m_account_manager->CloseAllConnections();
else
return m_account_manager->ToOnlineMode();
}
OP_STATUS MessageEngine::GetMessage(Message& message, message_gid_t id, BOOL full, BOOL timeout_request)
{
RETURN_IF_ERROR(m_store->GetMessage(message, id));
if (full && !m_multiple_message_changes)
{
BOOL has_body;
// Check if this message has a body, else we fetch it
RETURN_IF_ERROR(m_store->HasMessageDownloadedBody(id, has_body));
if (has_body)
RETURN_IF_ERROR(m_store->GetMessageData(message));
else if (message.GetAccountPtr())
RETURN_IF_ERROR(message.GetAccountPtr()->FetchMessage(id, !timeout_request, FALSE));
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::GetMessage(Message& message, const OpStringC8& message_id, BOOL full)
{
if (message_id.IsEmpty())
return OpStatus::OK;
message_gid_t id;
id = m_store->GetMessageByMessageId(message_id);
if (id == 0)
return OpStatus::ERR; //Not found
return GetMessage(message, id, full);
}
OP_STATUS MessageEngine::FetchCompleteMessage(message_gid_t message_id)
{
Account* account = GetAccountById(m_store->GetMessageAccountId(message_id));
if (account)
return account->FetchMessage(message_id, TRUE, TRUE);
return OpStatus::OK;
}
// ----------------------------------------------------
OP_STATUS MessageEngine::FetchMessages(BOOL enable_signalling, BOOL full_sync) const
{
if (!m_account_manager)
return OpStatus::ERR_NULL_POINTER;
Account* account = m_account_manager->GetFirstAccount();
while (account)
{
if (account->GetManualCheckEnabled() && account->GetIncomingProtocol() != AccountTypes::IRC)
{
if (full_sync)
RETURN_IF_ERROR(account->RefreshAll());
else
RETURN_IF_ERROR(account->FetchMessages(enable_signalling));
}
account = (Account*)account->Suc();
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::FetchMessages(UINT16 account_id, BOOL enable_signalling) const
{
if (!m_account_manager)
return OpStatus::ERR_NULL_POINTER;
OP_STATUS ret;
Account* account = NULL;
if (((ret=m_account_manager->GetAccountById(account_id, account)) != OpStatus::OK) || !account)
return ret;
return account->FetchMessages(enable_signalling);
}
OP_STATUS MessageEngine::SelectFolder(UINT32 index_id)
{
Index* index = m_indexer->GetIndexById(index_id);
INT16 account_id;
Account* account = NULL;
if (!m_account_manager || !index)
return OpStatus::ERR_NULL_POINTER;
// Check which account is associated with this index
account_id = (INT16)index->GetAccountId();
RETURN_IF_ERROR(m_account_manager->GetAccountById(account_id, account));
if (!account)
return OpStatus::OK;
// Select folder in account
return account->SelectFolder(index_id);
}
OP_STATUS MessageEngine::RefreshFolder(UINT32 index_id)
{
if (index_id >= IndexTypes::FIRST_ACCOUNT && index_id < IndexTypes::LAST_ACCOUNT)
{
Account* account = NULL;
RETURN_IF_ERROR(m_account_manager->GetAccountById(index_id - IndexTypes::FIRST_ACCOUNT, account));
if (!account)
return OpStatus::ERR;
return account->RefreshAll();
}
else
{
Index* index = m_indexer->GetIndexById(index_id);
if (!index)
return OpStatus::ERR;
if (index->GetType() == IndexTypes::UNIONGROUP_INDEX)
{
OpINT32Vector children;
RETURN_IF_ERROR(m_indexer->GetChildren(index_id, children));
for (UINT i = 0; i < children.GetCount(); i++)
RETURN_IF_ERROR(RefreshFolder(children.Get(i)));
return OpStatus::OK;
}
UINT32 account_id = index->GetAccountId();
if (account_id)
{
Account* account = NULL;
RETURN_IF_ERROR(m_account_manager->GetAccountById(account_id, account));
if (!account)
return OpStatus::ERR;
return account->RefreshFolder(index_id);
}
else
{
for (Account* account = m_account_manager->GetFirstAccount(); account; account = (Account*)account->Suc())
{
switch (account->GetType())
{
case AccountTypes::IMAP:
case AccountTypes::POP:
case AccountTypes::NEWS:
case AccountTypes::RSS:
account->RefreshAll();
break;
}
}
return OpStatus::OK;
}
}
}
OP_STATUS MessageEngine::StopFetchingMessages() const
{
if (!m_account_manager)
return OpStatus::ERR_NULL_POINTER;
Account* account = m_account_manager->GetFirstAccount();
while (account)
{
account->StopFetchingMessages();
account = (Account*)account->Suc();
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::StopSendingMessages()
{
if (!m_account_manager)
return OpStatus::ERR_NULL_POINTER;
Account* account = m_account_manager->GetFirstAccount();
while (account)
{
account->StopSendingMessage();
account = (Account*)account->Suc();
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::StopSendingMessages(UINT16 account_id)
{
if (!m_account_manager)
return OpStatus::ERR_NULL_POINTER;
Account* account = m_account_manager->GetFirstAccount();
while (account)
{
if(account->GetAccountId() == account_id)
{
account->StopSendingMessage();
return OpStatus::OK;
}
account = (Account*)account->Suc();
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::StopFetchingMessages(UINT16 account_id) const
{
if (!m_account_manager)
return OpStatus::ERR_NULL_POINTER;
OP_STATUS ret;
Account* account = NULL;
if (((ret=m_account_manager->GetAccountById(account_id, account)) != OpStatus::OK) || !account)
return ret;
return account->StopFetchingMessages();
}
OP_STATUS MessageEngine::SendMessages(UINT16 only_from_account_id)
{
Index* outbox = m_indexer->GetIndexById(IndexTypes::OUTBOX);
Index* trash = m_indexer->GetIndexById(IndexTypes::TRASH);
if (outbox == NULL)
{
return OpStatus::ERR;
}
for (INT32SetIterator it(outbox->GetIterator()); it; it++)
{
message_gid_t id = it.GetData();
if (trash->Contains(id))
continue;
Message message;
if (OpStatus::IsSuccess(GetMessage(message, id, FALSE)) &&
(only_from_account_id==0 || only_from_account_id==message.GetAccountId()))
{
Account* account = NULL;
RETURN_IF_ERROR(m_account_manager->GetAccountById(message.GetAccountId(), account));
if (account==NULL)
return OpStatus::ERR;
RETURN_IF_ERROR(account->SendMessage(message, FALSE));
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::SendMessage(Message& message, BOOL anonymous)
{
OpString error_context;
OpStatus::Ignore(error_context.Set("Sending mail"));
OP_STATUS ret;
UINT16 account_id = message.GetAccountId();
Account* account = NULL;
OP_ASSERT(m_account_manager);
// Get account
if (account_id == 0)
return OpStatus::ERR_OUT_OF_RANGE;
RETURN_IF_ERROR(m_account_manager->GetAccountById(account_id, account));
if (!account)
return OpStatus::ERR_NULL_POINTER;
// Set message properties
message.SetFlag(Message::IS_OUTGOING,TRUE);
message.SetFlag(Message::IS_READ, TRUE); // all outgoing are read
BOOL is_resent = message.IsFlagSet(Message::IS_RESENT);
OpString8 dummy_contenttype;
OpString from, organization, error_message;
if (OpStatus::IsError(account->GetFormattedEmail(from, TRUE)) ||
OpStatus::IsError(account->GetOrganization(organization)) ||
(from.HasContent() && OpStatus::IsError(message.SetFrom(from, TRUE))) ||
(!is_resent && organization.HasContent() && OpStatus::IsError(message.SetHeaderValue(Header::ORGANIZATION, organization, TRUE))))
{
OpString format_string;
g_languageManager->GetString(Str::S_FROM_OR_ORGANIZATION_FAILED, format_string);
error_message.AppendFormat(format_string.CStr(), from.CStr(), organization.CStr());
account->OnError(error_message);
return OpStatus::ERR;
}
if (from.IsEmpty())
{
account->OnError(Str::S_ILLEGAL_FROM_ADDRESS);
return OpStatus::ERR;
}
BOOL only_to_outbox = !anonymous &&
( account->GetQueueOutgoing() || //User has asked for message to be put in queue
g_pcnet->GetIntegerPref(PrefsCollectionNetwork::OfflineMode) ); //Opera is offline. Put in queue
//Generate ID for message if needed
if (message.GetId())
{
m_store->UpdateMessage(message, TRUE);
m_store->SetRawMessage(message);
}
else
{
message_gid_t new_id;
if (OpStatus::IsError(ret=m_store->AddMessage(new_id, message)))
{
account->OnError(Str::S_ADDMESSAGE_FAILED);
return ret;
}
}
// move from drafts to outbox
Index *outbox = m_indexer->GetIndexById(IndexTypes::OUTBOX);
Index *drafts = m_indexer->GetIndexById(IndexTypes::DRAFTS);
if (!drafts || !outbox)
{
account->OnError(Str::S_DRAFTS_OR_OUTBOX_NOT_FOUND);
return OpStatus::ERR;
}
if (OpStatus::IsError(ret=outbox->NewMessage(message.GetId())))
{
account->OnError(Str::S_FAILED_MOVING_TO_OUTBOX);
return ret;
}
if (OpStatus::IsError(ret=drafts->RemoveMessage(message.GetId())))
{
account->OnError(Str::S_FAILED_MOVING_FROM_DRAFTS);
return ret;
}
// finally send the message if not queueing
if (!only_to_outbox)
{
if (OpStatus::IsError(ret=account->SendMessage(message, anonymous)))
{
account->OnError(Str::S_SENDING_MESSAGE_FAILED);
return ret;
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::DisconnectAccount(UINT16 account_id) const
{
if (!m_account_manager)
return OpStatus::ERR_NULL_POINTER;
OP_STATUS ret;
Account* account = NULL;
if (((ret=m_account_manager->GetAccountById(account_id, account)) != OpStatus::OK) || !account)
return ret;
OpStatus::Ignore(account->Disconnect(TRUE));
OpStatus::Ignore(account->Disconnect(FALSE));
return OpStatus::OK;
}
OP_STATUS MessageEngine::DisconnectAccounts() const
{
if (!m_account_manager)
return OpStatus::ERR_NULL_POINTER;
Account* account = m_account_manager->GetFirstAccount();
while (account)
{
OpStatus::Ignore(account->Disconnect(TRUE));
OpStatus::Ignore(account->Disconnect(FALSE));
account = (Account*)account->Suc();
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::SaveDraft(Message* m2message)
{
Message* message = (Message*) m2message;
if (!message)
return OpStatus::ERR_NULL_POINTER;
message->SetFlag(Message::IS_OUTGOING,TRUE);
message->SetFlag(Message::IS_READ, TRUE); // all outgoing are read
/*
RETURN_IF_ERROR(message->MimeEncodeAttachments(FALSE, TRUE));
*/
//Generate ID for message if needed
message_gid_t new_id;
if (message->GetId())
{
m_store->UpdateMessage(*message, TRUE);
m_store->SetRawMessage(*message);
}
else
{
RETURN_IF_ERROR(m_store->AddMessage(new_id, *message));
RETURN_IF_ERROR(m_indexer->NewMessage(*message));
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::HasMessageDownloadedBody(message_gid_t id, BOOL& has_downloaded_body)
{
return m_store->HasMessageDownloadedBody(id, has_downloaded_body);
}
OP_STATUS MessageEngine::OnDeleted(message_gid_t message_id, BOOL permanently)
{
if (permanently)
{
return m_message_database->RemoveMessage(message_id);
}
else
{
Index* trash = m_indexer->GetIndexById(IndexTypes::TRASH);
Index* unread = m_indexer->GetIndexById(IndexTypes::UNREAD);
if (trash && unread)
{
RETURN_IF_ERROR(trash->NewMessage(message_id));
RETURN_IF_ERROR(unread->RemoveMessage(message_id));
RETURN_IF_ERROR(m_store->SetMessageFlag(message_id, Message::IS_READ, TRUE));
OnMessageChanged(message_id);
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::RemoveMessages(OpINT32Vector& message_ids, BOOL permanently)
{
OpAutoINT32HashTable<OpINT32Vector> account_message_ids;
Account* account;
RETURN_IF_ERROR(SplitIntoAccounts(message_ids, account_message_ids));
for (INT32HashIterator<OpINT32Vector> it(account_message_ids); it; it++)
{
account = GetAccountById(it.GetKey());
RETURN_IF_ERROR(RemoveMessages(*it.GetData(), account, permanently));
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::RemoveMessages(OpINT32Vector& message_ids, Account* account, BOOL permanently)
{
// Don't remove messages that are being edited
for (int i = message_ids.GetCount() - 1; i >= 0; i--)
{
if (m_messages_being_edited.Contains(message_ids.Get(i)))
message_ids.Remove(i);
}
// Remove messages from account (remote)
if(account)
account->RemoveMessages(message_ids, permanently);
// Remove messages from store and index (local)
MultipleMessageChanger changer(message_ids.GetCount());
for(UINT32 index = 0; index < message_ids.GetCount(); index++)
RETURN_IF_ERROR(OnDeleted(message_ids.Get(index), permanently));
return OpStatus::OK;
}
OP_STATUS MessageEngine::UndeleteMessages(const OpINT32Vector& message_ids)
{
Index *trash = m_indexer->GetIndexById(IndexTypes::TRASH);
if(!trash)
return OpStatus::ERR_NULL_POINTER;
OpAutoINT32HashTable<OpINT32Vector> account_message_ids;
RETURN_IF_ERROR(SplitIntoAccounts(message_ids, account_message_ids));
//Notify backends that message is removed from trash
for (INT32HashIterator<OpINT32Vector> it(account_message_ids); it; it++)
{
Account* account = GetAccountById(it.GetKey());
if (account)
OpStatus::Ignore(account->MessagesMovedFromTrash(*it.GetData()));
}
MultipleMessageChanger changer(message_ids.GetCount());
for(UINT32 index = 0; index < message_ids.GetCount(); index++)
{
RETURN_IF_ERROR(trash->RemoveMessage(message_ids.Get(index)));
OnMessageChanged(message_ids.Get(index));
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::EmptyTrash()
{
Index* trash = GetIndexById(IndexTypes::TRASH);
if (trash)
{
if (trash->MessageCount()==0)
{
//No messages to remove. Signal all active backends that we at least have had an Empty Trash request
Account* account = m_account_manager->GetFirstAccount();
while (account)
{
if (m_account_manager->IsAccountActive(account->GetAccountId()))
{
OpStatus::Ignore(account->EmptyTrash(FALSE));
OpStatus::Ignore(account->EmptyTrash(TRUE));
}
account = static_cast<Account*>(account->Suc());
}
}
else
{
for (INT32SetIterator it(trash->GetIterator()); it; it++)
{
message_gid_t message_id = it.GetData();
// Only remove messages from active accounts
if (message_id && m_account_manager->IsAccountActive(m_store->GetMessageAccountId(message_id)))
m_messages_to_delete.Add(message_id);
}
// trash the first 50 immediately
UINT trash_count = min(trash->MessageCount(), 50U);
for (UINT j = 0; j < trash_count; j++)
{
Receive(MSG_M2_EMPTY_TRASH);
}
return m_loop->Post(MSG_M2_EMPTY_TRASH);
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::Receive(OpMessage message)
{
switch (message)
{
case MSG_M2_EMPTY_TRASH:
if (m_messages_to_delete.GetCount() > 0)
{
if (!m_deleting_trash)
{
SignalStartSession(TRUE); //It is actually neither incoming not outgoing
m_deleting_trash = TRUE;
//Signal all accounts
Account* account = m_account_manager->GetFirstAccount();
while (account)
{
if (m_account_manager->IsAccountActive(account->GetAccountId()))
OpStatus::Ignore(account->EmptyTrash(FALSE));
account = static_cast<Account*>(account->Suc());
}
}
message_gid_t message_id = m_messages_to_delete.Remove(m_messages_to_delete.GetCount()-1);
Index* trash = (Index*)MessageEngine::GetInstance()->GetIndexById(IndexTypes::TRASH);
if (trash->Contains(message_id))
{
if (OnDeleted(message_id, TRUE) != OpStatus::OK) // not from_account, since EmptyTrash() will do that
{
OP_ASSERT(0);
}
}
if (m_messages_to_delete.GetCount() > 0)
{
return m_loop->Post(MSG_M2_EMPTY_TRASH);
}
else
{
//Signal all accounts
Account* account = m_account_manager->GetFirstAccount();
while (account)
{
if (m_account_manager->IsAccountActive(account->GetAccountId()))
OpStatus::Ignore(account->EmptyTrash(TRUE));
account = static_cast<Account*>(account->Suc());
}
SignalEndSession(TRUE, 0, FALSE);
m_deleting_trash = FALSE;
}
}
break;
case MSG_M2_INDEX_CHANGED:
for (unsigned i = 0; i < m_engine_listeners.GetCount(); i++)
{
for (unsigned j = 0; j < m_index_changed.GetCount(); j++)
m_engine_listeners.Get(i)->OnIndexChanged(m_index_changed.GetByIndex(j));
}
m_index_changed.Clear();
m_posted_index_changed = FALSE;
break;
case MSG_M2_MAILCOMMAND:
{
OP_STATUS result = OpStatus::ERR;
switch ((URLType)m_command_url.GetAttribute(URL::KType))
{
case URL_HTTP :
case URL_HTTPS :
result = MailCommandHTTP(m_command_url);
break;
#ifdef IRC_SUPPORT
case URL_IRC :
result = MailCommandIRC(m_command_url);
break;
case URL_CHAT_TRANSFER :
result = MailCommandChatTransfer(m_command_url);
break;
#endif // IRC_SUPPORT
case URL_NEWS :
case URL_SNEWS :
result = MailCommandNews(m_command_url);
break;
}
m_command_url = URL();
return result;
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::CancelMessage(message_gid_t message_id)
{
Message original_message;
if (OpStatus::IsError(GetMessage(original_message, message_id, FALSE)))
return OpStatus::OK; //No message to cancel
if (!original_message.IsFlagSet(Message::IS_OUTGOING) ||
!original_message.IsFlagSet(Message::IS_NEWS_MESSAGE) ||
original_message.IsFlagSet(Message::IS_CONTROL_MESSAGE))
{
return OpStatus::ERR_OUT_OF_RANGE;
}
Message cancel_message;
RETURN_IF_ERROR(CreateMessage(cancel_message, original_message.GetAccountId(), original_message.GetId(), MessageTypes::CANCEL_NEWSPOST));
return SendMessage(cancel_message, FALSE);
}
OP_STATUS MessageEngine::UpdateMessage(Message& message)
{
return m_store->UpdateMessage(message);
}
OP_STATUS MessageEngine::IndexRead(index_gid_t index_id)
{
Index* index = m_indexer->GetIndexById(index_id);
Index* unread = m_indexer->GetIndexById(IndexTypes::UNREAD);
OpINT32Vector message_ids;
if (index && unread)
{
Index common;
common.SetVisible(FALSE);
RETURN_IF_ERROR(m_indexer->IntersectionIndexes(common,unread,index,0));
for (INT32SetIterator it(common.GetIterator()); it; it++)
{
message_gid_t id = it.GetData();
if (id && !index->MessageHidden(id))
{
message_ids.Add(id);
}
}
return MessagesRead(message_ids, TRUE);
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::MessageFlagged(message_gid_t message_id, BOOL flagged)
{
RETURN_IF_ERROR(m_store->SetMessageFlag(message_id, Message::IS_FLAGGED, flagged));
GetIndexer()->AddToPinBoard(message_id, flagged);
Account* account = GetAccountById(m_store->GetMessageAccountId(message_id));
if (account)
return account->FlaggedMessage(message_id, flagged);
return OpStatus::OK;
}
OP_STATUS MessageEngine::MessageRead(Message& message, BOOL read)
{
OpINT32Vector message_ids;
// Mark local message as read
message.SetFlag(Message::IS_READ, read);
// Mark message as read in other instances
RETURN_IF_ERROR(message_ids.Add(message.GetId()));
return MessagesRead(message_ids, read);
}
OP_STATUS MessageEngine::MessagesRead(OpINT32Vector& message_ids, BOOL read)
{
MultipleMessageChanger changer(message_ids.GetCount());
for(int index = message_ids.GetCount() - 1; index >= 0; index--)
{
message_gid_t message_id = message_ids.Get(index);
// Check if message is already marked correctly
if (!(m_store->GetMessageFlags(message_id) & (1 << Message::IS_READ)) != read)
{
message_ids.Remove(index);
continue;
}
// sync unread index first
if (m_indexer->MessageRead(message_id, read) != OpStatus::OK)
{
OP_ASSERT(0);
}
// then toggle flag..
RETURN_IF_ERROR(m_store->SetMessageFlag(message_id, Message::IS_READ, read));
}
// Tell backends about changes if necessary
OpAutoINT32HashTable<OpINT32Vector> account_messages;
RETURN_IF_ERROR(SplitIntoAccounts(message_ids, account_messages));
for (INT32HashIterator<OpINT32Vector> it(account_messages); it; it++)
{
Account* account = GetAccountById(it.GetKey());
if (account)
account->ReadMessages(*it.GetData(), read);
}
OnMessagesRead(message_ids, read);
return OpStatus::OK;
}
OP_STATUS MessageEngine::MessageReplied(message_gid_t message, BOOL replied)
{
RETURN_IF_ERROR(m_store->SetMessageFlag(message, Message::IS_REPLIED, replied));
if (replied)
{
UINT16 account_id = m_store->GetMessageAccountId(message);
Account* account = GetAccountById(account_id);
if (account)
RETURN_IF_ERROR(account->ReplyToMessage(message));
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::MarkAsSpam(const OpINT32Vector& message_ids, BOOL is_spam, BOOL propagate_call, BOOL imap_move)
{
for (UINT32 i = 0; i < message_ids.GetCount(); i++)
{
if (is_spam)
{
m_indexer->Spam(message_ids.Get(i));
}
else
{
m_indexer->NotSpam(message_ids.Get(i), !propagate_call, 0);
}
}
OpAutoINT32HashTable<OpINT32Vector> account_message_ids;
Account* account;
RETURN_IF_ERROR(SplitIntoAccounts(message_ids, account_message_ids));
for (INT32HashIterator<OpINT32Vector> it(account_message_ids); it; it++)
{
account = GetAccountById(it.GetKey());
if (account)
RETURN_IF_ERROR(account->MarkMessagesAsSpam(*it.GetData(), is_spam, imap_move));
}
return OpStatus::OK;
}
void MessageEngine::SetSpamLevel(INT32 level)
{
OpStatus::Ignore(m_indexer->SetSpamLevel(level));
}
INT32 MessageEngine::GetSpamLevel()
{
return m_indexer->GetSpamLevel();
}
OP_STATUS MessageEngine::AddToContacts(message_gid_t message, int parent_folder_id)
{
return m_indexer->NotSpam(message,TRUE,parent_folder_id);
}
OP_STATUS MessageEngine::GetFromAddress(message_gid_t message_id, OpString& sender, BOOL do_quote_pair_encode)
{
sender.Empty();
Message message;
RETURN_IF_ERROR(GetMessage(message, message_id, FALSE));
return message.GetFromAddress(sender, do_quote_pair_encode);
}
OP_STATUS MessageEngine::ImportMessage(Message* message, OpString& original_folder_name, BOOL move_to_sent)
{
if (message == 0)
return OpStatus::ERR_NULL_POINTER;
message_gid_t message_id;
OpString8 x_opera_status;
if (OpStatus::IsSuccess(message->GetHeaderValue("X-Opera-Status", x_opera_status)) &&
x_opera_status.HasContent())
{
if (x_opera_status.Length() == 114)
{
// Get the value of the flags.
OpString8 flagsLW_string, flagsHW_string;
OpStatus::Ignore(flagsLW_string.Set(x_opera_status.SubString(34).CStr(), 8));
OpStatus::Ignore(flagsHW_string.Set(x_opera_status.SubString(50).CStr(), 8));
OpStatus::Ignore(flagsLW_string.Insert(0, "0x"));
OpStatus::Ignore(flagsHW_string.Insert(0, "0x"));
// Get the value of the label.
OpString8 label_string;
OpStatus::Ignore(label_string.Set(x_opera_status.SubString(60).CStr(), 2));
OpStatus::Ignore(label_string.Insert(0, "0x"));
char* end_ptr = 0;
const UINT64 flags = static_cast<UINT64>(op_strtol(flagsHW_string.CStr(), &end_ptr, 16)) << 32 | op_strtol(flagsLW_string.CStr(), &end_ptr, 16);
// Remember the default flags for this message.
const UINT32 default_flags = message->GetAllFlags();
// Update the message with the values we found.
message->SetAllFlags(flags);
// If the message is outgoing we can be pretty sure it should be
// moved to sent.
if (message->IsFlagSet(Message::IS_OUTGOING))
move_to_sent = TRUE;
// Most flags can't be trusted, so after examining those few we
// actually trust, it's best to just reset them.
message->SetAllFlags(default_flags);
}
else
OP_ASSERT(0); // Wrong length of X-Opera-Status, or header changed?
// We have the information we need, delete the old header.
message->RemoveXOperaStatusHeader();
message->CopyCurrentToOriginalHeaders();
}
message->SetFlag(Message::IS_IMPORTED, TRUE);
message->SetFlag(Message::IS_SEEN, TRUE);
if (move_to_sent)
{
message->SetFlag(Message::IS_NEWS_MESSAGE, FALSE); //just to be sure...
message->SetFlag(Message::IS_OUTGOING, TRUE);
message->SetFlag(Message::IS_SENT, TRUE);
}
RETURN_IF_ERROR(m_store->AddMessage(message_id, *message));
RETURN_IF_ERROR(m_indexer->NewMessage(*message));
if (move_to_sent) // add message to Sent index
{
Index* sent_index = m_indexer->GetIndexById(IndexTypes::SENT);
if (!sent_index)
return OpStatus::ERR;
sent_index->NewMessage(message_id);
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::ImportContact(OpString& full_name, OpString& email_address)
{
return OpStatus::OK;
}
OP_STATUS MessageEngine::RemoveIndex(index_gid_t id)
{
if ((id >= IndexTypes::FIRST_SEARCH && id < IndexTypes::LAST_SEARCH) ||
(id >= IndexTypes::FIRST_CONTACT && id < IndexTypes::LAST_CONTACT) ||
(id >= IndexTypes::FIRST_NEWSGROUP && id < IndexTypes::LAST_NEWSGROUP) ||
(id >= IndexTypes::FIRST_THREAD && id < IndexTypes::LAST_THREAD) ||
(id >= IndexTypes::FIRST_IMAP && id < IndexTypes::LAST_IMAP) ||
(id >= IndexTypes::FIRST_FOLDER && id < IndexTypes::LAST_FOLDER) ||
(id >= IndexTypes::FIRST_NEWSFEED && id < IndexTypes::LAST_NEWSFEED) ||
(id >= IndexTypes::FIRST_UNIONGROUP && id < IndexTypes::LAST_UNIONGROUP) ||
(id >= IndexTypes::FIRST_ARCHIVE && id < IndexTypes::LAST_ARCHIVE))
{
Account* account = NULL;
Index* index = m_indexer->GetIndexById(id);
if (!index)
return OpStatus::ERR_NULL_POINTER;
if (index->GetHideFromOther())
{
index->SetHideFromOther(FALSE);
}
// Clean out index models
for (unsigned m = 0; m < m_index_models.GetCount(); m++)
{
IndexModel* model = m_index_models.Get(m);
if (model && model->GetIndexId() == id)
model->Empty();
}
// See if there is an account for this index
OpStatus::Ignore(m_account_manager->GetAccountById(index->GetAccountId(), account));
// If there is an account, call appropriate functions, else just remove
if (account && (id < IndexTypes::FIRST_UNIONGROUP || id > IndexTypes::LAST_UNIONGROUP))
{
RETURN_IF_ERROR(account->RemoveSubscribedFolder(id));
return account->CommitSubscribedFolders();
}
else
{
if (id >= IndexTypes::FIRST_UNIONGROUP && id < IndexTypes::LAST_UNIONGROUP)
{
OpINT32Vector children;
m_indexer->GetChildren(id, children, TRUE);
for (UINT32 i = 0; i < children.GetCount(); i++)
{
RETURN_IF_ERROR(RemoveIndex(children.Get(i)));
}
}
index->Empty();
return m_indexer->RemoveIndex(index);
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::IndexRemoved(Indexer *indexer, UINT32 index_id)
{
UINT32 count = m_index_models.GetCount();
for (UINT m = 0; m < count; m++)
{
IndexModel* model = m_index_models.Get(m);
if (model && model->GetIndexId() == index_id)
{
model->Empty();
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::IndexKeywordChanged(Indexer *indexer, UINT32 index_id, const OpStringC8& old_keyword, const OpStringC8& new_keyword)
{
OpINT32Vector message_ids;
Index* index = GetIndexById(index_id);
if (!index)
return OpStatus::ERR_NULL_POINTER;
// For all messages in the index, remove the existing keyword, add the new one
for (INT32SetIterator it(index->GetIterator()); it; it++)
{
message_gid_t message_id = it.GetData();
RETURN_IF_ERROR(KeywordRemoved(indexer, message_id, old_keyword));
RETURN_IF_ERROR(KeywordAdded(indexer, message_id, new_keyword));
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::KeywordAdded(Indexer* indexer, message_gid_t message_id, const OpStringC8& keyword)
{
// Set property on message, to make sure that store knows this message has keywords and can
// remove them later (see also bug #330335)
m_store->SetMessageFlag(message_id, Message::HAS_KEYWORDS, TRUE);
// Find the account for this message
Account* account = GetAccountById(m_store->GetMessageAccountId(message_id));
if (!account)
return OpStatus::ERR_NULL_POINTER;
return account->KeywordAdded(message_id, keyword);
}
OP_STATUS MessageEngine::KeywordRemoved(Indexer* indexer, message_gid_t message_id, const OpStringC8& keyword)
{
// Find the account for this message
Account* account = GetAccountById(m_store->GetMessageAccountId(message_id));
if (!account)
return OpStatus::ERR_NULL_POINTER;
return account->KeywordRemoved(message_id, keyword);
}
Index* MessageEngine::CreateIndex(index_gid_t parent_id, BOOL visible)
{
if (
parent_id == IndexTypes::CATEGORY_LABELS ||
(parent_id >= IndexTypes::FIRST_FOLDER && parent_id < IndexTypes::LAST_FOLDER) ||
(parent_id >= IndexTypes::FIRST_ACCOUNT && parent_id < IndexTypes::LAST_ACCOUNT))
{
OpAutoPtr<Index> index(OP_NEW(Index, ()));
if (!index.get())
return NULL;
OpString index_name;
OpStatus::Ignore(g_languageManager->GetString(Str::S_DEFAULT_INDEX_NAME, index_name));
IndexTypes::Type index_type = IndexTypes::FOLDER_INDEX;
if (parent_id >= IndexTypes::FIRST_ACCOUNT && parent_id < IndexTypes::LAST_ACCOUNT)
{
if (index->AddM2Search() == NULL)
return NULL;
Account* account;
m_account_manager->GetAccountById((UINT16)(parent_id-IndexTypes::FIRST_ACCOUNT), account);
if (account)
{
if (account->GetIncomingProtocol() == AccountTypes::RSS)
{
index_type = IndexTypes::NEWSFEED_INDEX;
index->GetSearch()->SetSearchBody(SearchTypes::FOLDER_PATH);
RETURN_VALUE_IF_ERROR(index->GetSearch()->SetSearchText(UNI_L("http://example")), NULL);
index->SetAccountId(parent_id-IndexTypes::FIRST_ACCOUNT);
RETURN_VALUE_IF_ERROR(g_languageManager->GetString(Str::S_RSS_NEWSFOLDER, index_name), NULL);
}
else
{
return NULL;
}
}
else
{
return NULL;
}
}
else
{
// for regular filters, don't set the filtered flag by default
index->SetHideFromOther(FALSE);
index->EnableModelFlag(IndexTypes::MODEL_FLAG_SENT);
}
RETURN_VALUE_IF_ERROR(index->SetName(index_name.CStr()), NULL);
index->SetType(index_type);
RETURN_VALUE_IF_ERROR(m_indexer->NewIndex(index.get()), NULL);
index->SetParentId(parent_id);
index->SetVisible(visible != FALSE);
index->SetSaveToDisk(TRUE);
m_indexer->SaveAllToFile();
return index.release();
}
return NULL;
}
OP_STATUS MessageEngine::UpdateIndex(index_gid_t id)
{
return m_indexer->UpdateIndex(id);
}
BOOL MessageEngine::IsIndexMailingList(index_gid_t id)
{
Index* index = GetIndexById(id);
if (index)
{
IndexSearch* search = index->GetM2Search();
if (search)
{
if (search->GetSearchText().Find("@") == KNotFound)
{
return TRUE;
}
}
}
return FALSE;
}
BOOL MessageEngine::IsIndexNewsfeed(index_gid_t id)
{
if (!m_account_manager->GetRSSAccount(FALSE))
return FALSE;
// if there's no mail accounts setup yet, pretend it's a feed index (to get the feed toolbar for labels for instance)
if (m_account_manager->GetMailNewsAccountCount() == 0)
return TRUE;
else
return m_indexer->GetIndexById(id) ? m_indexer->GetIndexById(id)->GetAccountId() == (UINT32)m_account_manager->GetRSSAccount(FALSE)->GetAccountId() : FALSE;
}
OP_STATUS MessageEngine::ToClipboard(const OpINT32Vector& message_ids, index_gid_t source_index_id, BOOL cut)
{
Index* clipboard = m_indexer->GetIndexById(IndexTypes::CLIPBOARD);
if (!clipboard)
return OpStatus::ERR;
// Empty existing items on clipboard
RETURN_IF_ERROR(clipboard->Empty());
// Mark as copy/cut
m_clipboard_cut = cut;
// Save source index
m_clipboard_source = source_index_id;
// Add messages to clipboard
for (unsigned i = 0; i < message_ids.GetCount(); i++)
RETURN_IF_ERROR(clipboard->NewMessage(message_ids.Get(i)));
return OpStatus::OK;
}
OP_STATUS MessageEngine::PasteFromClipboard(index_gid_t dest_index_id)
{
// We only paste to filters, labels, IMAP folders, spam, trash and unread
// Pasting to filters or IMAP folders is just normal copy/pasting inside indexes
if (dest_index_id < IndexTypes::LAST_IMPORTANT)
{
RETURN_IF_ERROR(PasteFromClipboardToSpecialIndex(dest_index_id));
}
else if (IndexTypes::FIRST_ACCOUNT <= dest_index_id && dest_index_id < IndexTypes::LAST_ACCOUNT)
{
Account* account = GetAccountById(dest_index_id - IndexTypes::FIRST_ACCOUNT);
if (account && account->GetIncomingProtocol() == AccountTypes::ARCHIVE)
RETURN_IF_ERROR(PasteFromClipboardToFolderIndex(dest_index_id));
}
else if ((IndexTypes::FIRST_FOLDER <= dest_index_id && dest_index_id < IndexTypes::LAST_FOLDER) ||
(IndexTypes::FIRST_IMAP <= dest_index_id && dest_index_id < IndexTypes::LAST_IMAP) ||
(IndexTypes::FIRST_LABEL <= dest_index_id && dest_index_id < IndexTypes::LAST_LABEL) ||
(IndexTypes::FIRST_ARCHIVE <= dest_index_id && dest_index_id < IndexTypes::LAST_ARCHIVE))
{
RETURN_IF_ERROR(PasteFromClipboardToFolderIndex(dest_index_id));
}
m_clipboard_cut = FALSE;
return OpStatus::OK;
}
OP_STATUS MessageEngine::PasteFromClipboardToSpecialIndex(index_gid_t dest_index_id)
{
Index* clipboard = m_indexer->GetIndexById(IndexTypes::CLIPBOARD);
Index* destination_index = m_indexer->GetIndexById(dest_index_id);
if (!clipboard || !destination_index)
return OpStatus::ERR;
switch (dest_index_id)
{
case IndexTypes::SPAM:
{
OpINT32Vector messages;
RETURN_IF_ERROR(clipboard->GetAllMessages(messages));
return MarkAsSpam(messages, TRUE);
}
case IndexTypes::UNREAD_UI:
{
OpINT32Vector messages;
RETURN_IF_ERROR(clipboard->GetAllMessages(messages));
return MessagesRead(messages, FALSE);
}
case IndexTypes::TRASH:
{
OpINT32Vector messages;
RETURN_IF_ERROR(clipboard->GetAllMessages(messages));
return RemoveMessages(messages, FALSE);
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::PasteFromClipboardToFolderIndex(index_gid_t dest_index_id)
{
Index* clipboard = m_indexer->GetIndexById(IndexTypes::CLIPBOARD);
Index* source_index = m_indexer->GetIndexById(m_clipboard_source);
Index* dest_index = m_indexer->GetIndexById(dest_index_id);
if (!clipboard || !source_index || !dest_index)
return OpStatus::ERR;
// Check if we have something to do
if (clipboard->MessageCount() == 0 || m_clipboard_source == dest_index_id)
return OpStatus::OK;
Account* src_account = GetAccountById(source_index->GetAccountId());
Account* dst_account = GetAccountById(dest_index->GetAccountId());
// Pass on to the account if possible
if (dst_account)
{
if (dst_account != src_account && !EnsureAllBodiesDownloaded(IndexTypes::CLIPBOARD))
return SimpleDialog::ShowDialog(WINDOW_NAME_MAILBODY_MISSING,
g_application->GetActiveDesktopWindow(),
Str::S_MAIL_PANEL_BODY_MISSING,
Str::S_MESSAGE_BODY_NOT_DOWNLOADED,
Dialog::TYPE_OK,
Dialog::IMAGE_INFO);
OpINT32Vector message_ids;
for (INT32SetIterator it(clipboard->GetIterator()); it; it++)
{
RETURN_IF_ERROR(message_ids.Add(it.GetData()));
if (dest_index->GetSpecialUseType() == AccountTypes::FOLDER_SENT)
{
// move to a sent IMAP folder
INT64 flags = m_store->GetMessageFlags(it.GetData());
flags |= (1<<StoreMessage::IS_OUTGOING);
flags |= (1<<StoreMessage::IS_SENT);
OpStatus::Ignore(m_store->SetMessageFlags(it.GetData(), flags));
OpStatus::Ignore(GetIndexById(IndexTypes::SENT)->NewMessage(it.GetData()));
}
if (m_clipboard_cut)
{
switch (source_index->GetSpecialUseType())
{
case AccountTypes::FOLDER_SENT:
{
// move from an IMAP sent folder
INT64 flags = m_store->GetMessageFlags(it.GetData());
flags &= ~(1<<StoreMessage::IS_OUTGOING);
flags &= ~(1<<StoreMessage::IS_SENT);
OpStatus::Ignore(m_store->SetMessageFlags(it.GetData(), flags));
OpStatus::Ignore(GetIndexById(IndexTypes::SENT)->RemoveMessage(it.GetData()));
break;
}
case AccountTypes::FOLDER_TRASH:
{
GetIndexById(IndexTypes::TRASH)->RemoveMessage(it.GetData());
break;
}
}
}
}
if (source_index->GetSpecialUseType() == AccountTypes::FOLDER_SPAM)
{
RETURN_IF_ERROR(MarkAsSpam(message_ids, FALSE, FALSE, FALSE));
}
switch (dest_index->GetSpecialUseType())
{
case AccountTypes::FOLDER_SPAM:
case AccountTypes::FOLDER_TRASH:
{
// move to an IMAP trash or spam folder
OpINT32Vector clipboard_messages, *messages;
OpAutoINT32HashTable<OpINT32Vector> account_message_ids;
// only handle the messages for that account, assume the rest is by dropped there by mistake
RETURN_IF_ERROR(clipboard->GetAllMessages(clipboard_messages));
RETURN_IF_ERROR(SplitIntoAccounts(clipboard_messages, account_message_ids));
RETURN_IF_ERROR(account_message_ids.GetData(dest_index->GetAccountId(), &messages));
if (dest_index->GetSpecialUseType() == AccountTypes::FOLDER_TRASH)
{
return RemoveMessages(*messages, GetAccountById(dest_index->GetAccountId()), FALSE);
}
else
{
return MarkAsSpam(*messages, TRUE);
}
}
}
if (m_clipboard_cut)
return dst_account->MoveMessages(message_ids, m_clipboard_source, dest_index_id);
else
return dst_account->CopyMessages(message_ids, m_clipboard_source, dest_index_id);
}
else
{
for (INT32SetIterator it(clipboard->GetIterator()); it; it++)
{
// Add message to destination index
RETURN_IF_ERROR(dest_index->NewMessage(it.GetData()));
// Remove from source index if we were cutting
if (m_clipboard_cut)
{
if (src_account)
RETURN_IF_ERROR(src_account->RemoveMessage(it.GetData(), TRUE));
else
RETURN_IF_ERROR(source_index->RemoveMessage(it.GetData()));
}
}
}
return OpStatus::OK;
}
index_gid_t MessageEngine::GetClipboardSource()
{
Index* clipboard = m_indexer->GetIndexById(IndexTypes::CLIPBOARD);
if (clipboard && clipboard->MessageCount() > 0)
return m_clipboard_source;
return 0;
}
/***********************************************************************************
** Checks if all items in an index have bodies downloaded
**
** MessageEngine::HasAllBodiesDownloaded
** @param index_id Which index to check
** @return Whether all bodies are available
***********************************************************************************/
BOOL MessageEngine::HasAllBodiesDownloaded(index_gid_t index_id)
{
Index* index = m_indexer->GetIndexById(index_id);
if (!index)
return FALSE;
for (INT32SetIterator it(index->GetIterator()); it; it++)
{
BOOL has_body;
if (OpStatus::IsError(m_store->HasMessageDownloadedBody(it.GetData(), has_body)))
return FALSE;
if (!has_body)
{
return FALSE;
}
}
return TRUE;
}
/***********************************************************************************
** Ensure that all items in an index have bodies downloaded
**
** MessageEngine::EnsureAllBodiesDownloaded
** @param index_id Which index to check
** @return Whether all bodies are available, will start body fetch otherwise
***********************************************************************************/
BOOL MessageEngine::EnsureAllBodiesDownloaded(index_gid_t index_id)
{
Index* index = m_indexer->GetIndexById(index_id);
if (!index)
return FALSE;
BOOL all_bodies_downloaded = TRUE;
for (INT32SetIterator it(index->GetIterator()); it; it++)
{
BOOL has_body;
if (OpStatus::IsError(m_store->HasMessageDownloadedBody(it.GetData(), has_body)))
return FALSE;
if (!has_body)
{
Message message;
OpStatus::Ignore(GetMessage(message, it.GetData(), TRUE));
all_bodies_downloaded = FALSE;
}
}
return all_bodies_downloaded;
}
OP_STATUS MessageEngine::GetLexiconWords(uni_char **result, const uni_char *start_of_word, INT32 &count)
{
return m_indexer->FindWords(start_of_word, result, &count);
}
UINT32 MessageEngine::GetIndexCount()
{
return m_indexer ? m_indexer->IndexCount() : 0;
}
Index* MessageEngine::GetIndexById(index_gid_t id)
{
return m_indexer ? (Index*)(m_indexer->GetIndexById(id)) : NULL;
}
Index* MessageEngine::GetIndexRange(UINT32 range_start, UINT32 range_end, INT32& iterator)
{
return m_indexer ? (Index*)(m_indexer->GetRange(range_start, range_end, iterator)) : NULL;
}
INT32 MessageEngine::GetUnreadCount()
{
if (!m_indexer)
return 0;
Index* index = m_indexer->GetIndexById(IndexTypes::UNREAD_UI);
return index ? (INT32)index->UnreadCount() : 0;
}
BOOL MessageEngine::ImportInProgress() const
{
return (m_mail_import_in_progress > 0);
}
void MessageEngine::SetImportInProgress(BOOL status)
{
if (status)
{
m_mail_import_in_progress++;
}
else
{
m_mail_import_in_progress--;
}
}
EngineTypes::ImporterId MessageEngine::GetDefaultImporterId()
{
return ImportFactory::Instance()->GetDefaultImporterId();
}
OP_STATUS MessageEngine::ImportOPML(const OpStringC& filename)
{
RETURN_IF_ERROR(InitMessageDatabaseIfNeeded());
OPMLM2ImportHandler import_handler;
RETURN_IF_ERROR(import_handler.Init());
RETURN_IF_ERROR(OPML::Import(filename, import_handler));
return OpStatus::OK;
}
OP_STATUS MessageEngine::ExportOPML(const OpStringC& filename)
{
return OPML::Export(filename);
}
OP_STATUS MessageEngine::ExportToMbox(const index_gid_t index_id, const OpStringC& mbox_filename)
{
OpTreeModel* index_model = NULL;
INT32 start_pos = -1;
OP_STATUS res = GetIndexModel(&index_model, index_id, start_pos);
if (OpStatus::IsError(res))
{
return res;
}
INT32 count = index_model->GetItemCount();
if (0 == count)
{
return OpStatus::OK;
}
GlueFactory* glue_factory = MessageEngine::GetInstance()->GetGlueFactory();
OpFile* export_file = glue_factory->CreateOpFile(mbox_filename);
if (!export_file)
{
return OpStatus::ERR;
}
res = export_file->Open(OPFILE_WRITE|OPFILE_SHAREDENYREAD|OPFILE_SHAREDENYWRITE);
if (OpStatus::IsError(res))
{
glue_factory->DeleteOpFile(export_file);
return res;
}
BOOL first = TRUE;
BOOL ended_in_linefeed = TRUE;
for (INT32 pos = 0; pos < count; pos++)
{
OpTreeModelItem* item = index_model->GetItemByPosition(pos);
message_gid_t id = item->GetID();
Message message;
if (OpStatus::IsError(GetMessage(message, id, TRUE)))
{
// this is normal, the message just doesn't exist anymore
continue;
}
OpString8 raw;
message.GetRawMessage(raw, TRUE, TRUE, TRUE);
int raw_length = raw.Length();
if (raw_length > 0)
{
OpString8 from_line;
if (first)
{
from_line.Set("From ");
first = FALSE;
}
else
{
from_line.Set("\nFrom ");
if (!ended_in_linefeed)
from_line.Insert(0, "\n");
}
Header* from_header = message.GetHeader(Header::FROM);
if (from_header)
{
const Header::From* from = from_header->GetFirstAddress();
if (from)
{
OpString8 imaa_address;
RETURN_IF_ERROR(from->GetIMAAAddress(imaa_address));
RETURN_IF_ERROR(from_line.Append(imaa_address));
}
else
{
RETURN_IF_ERROR(from_line.Append("?@?"));
}
}
from_line.Append(" ");
time_t recv_time;
message.GetDate(recv_time);
if (recv_time)
{
struct tm* gmt = op_gmtime(&recv_time);
if (gmt)
{
RETURN_IF_ERROR(from_line.Append(asctime(gmt),24));
}
}
RETURN_IF_ERROR(from_line.Append("\r\n"));
if (export_file->Write(from_line.CStr(), from_line.Length())!=OpStatus::OK)
{
export_file->Close();
glue_factory->DeleteOpFile(export_file);
return OpStatus::ERR;
}
if (export_file->Write(raw.CStr(), raw_length)!=OpStatus::OK)
{
export_file->Close();
glue_factory->DeleteOpFile(export_file);
return OpStatus::ERR;
}
ended_in_linefeed = (raw_length>0 && (*(raw.CStr()+raw_length-1)=='\n' || *(raw.CStr()+raw_length-1)=='\r'));
}
}
export_file->Close();
glue_factory->DeleteOpFile(export_file);
return OpStatus::OK;
}
OP_STATUS MessageEngine::LoadRSSFeed(const OpStringC& url, URL& downloaded_url, BOOL manual_create, BOOL open_panel)
{
if (url.IsEmpty() && downloaded_url.IsEmpty())
return OpStatus::ERR;
OpString real_url;
if (url.IsEmpty())
RETURN_IF_ERROR(downloaded_url.GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI, real_url, TRUE));
RETURN_IF_ERROR(InitMessageDatabaseIfNeeded());
// assuming RSS for now:
Account* account = m_account_manager->GetFirstAccountWithType(AccountTypes::RSS);
if (account)
{
RSSBackend* backend = static_cast<RSSBackend*>(account->GetIncomingBackend());
if (!backend)
return OpStatus::ERR;
if (real_url.HasContent())
RETURN_IF_ERROR(backend->UpdateFeed(real_url, manual_create));
else
RETURN_IF_ERROR(backend->UpdateFeed(url, manual_create));
}
// signal that we have an RSS account available
g_application->SettingsChanged(SETTINGS_ACCOUNT_SELECTOR);
g_application->SettingsChanged(SETTINGS_MENU_SETUP);
g_application->SettingsChanged(SETTINGS_TOOLBAR_CONTENTS);
g_hotlist_manager->ShowPanelByName(UNI_L("Mail"), TRUE, open_panel);
return OpStatus::OK;
}
OP_STATUS MessageEngine::MailCommand(URL& url)
{
m_command_url = url;
return m_loop->Post(MSG_M2_MAILCOMMAND);
}
// ---------------------------------------------------------------------------
OP_STATUS MessageEngine::ConvertToBestChar8(IO OpString8& preferred_charset, BOOL force_charset, IN const OpStringC16& source, OUT OpString8& dest, int max_dst_length, int* converted)
{
dest.Empty();
OP_STATUS ret;
if (preferred_charset.IsEmpty())
{
if ((ret=preferred_charset.Set("utf-8")) != OpStatus::OK)
return ret;
}
int invalid_count=0;
OpString dummy_invalid_chars;
if ((ret=ConvertToChar8(preferred_charset, source, dest, invalid_count, dummy_invalid_chars, max_dst_length, converted))!=OpStatus::OK &&
ret!=OpStatus::ERR_OUT_OF_RANGE) //ConvertToChar8 will return ERR_OUT_OF_RANGE if an invalid charset is given
return ret;
if (ret==OpStatus::ERR_OUT_OF_RANGE && preferred_charset.CompareI("utf-8")==0) //If we have a legal charset, the error is a real OOM
return ret;
if ((ret==OpStatus::ERR_OUT_OF_RANGE || invalid_count>0) && !force_charset && preferred_charset.CompareI("utf-8")!=0)
{
preferred_charset.Empty(); //Will be set to utf-8 when entering this function again in the recursive call
return ConvertToBestChar8(preferred_charset, force_charset, source, dest, max_dst_length, converted);
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::ConvertToChar8(IO OpString8& charset, IN const OpStringC16& source, OUT OpString8& dest,
OUT int& invalid_count, OUT OpString16& invalid_chars, int max_dst_length, int* converted)
{
OutputConverter* conv_temp = 0;
if (OpStatus::IsError(OutputConverter::CreateCharConverter(charset.CStr(), &conv_temp)))
{
RETURN_IF_ERROR(OutputConverter::CreateCharConverter("iso-8859-1", &conv_temp));
}
OpAutoPtr<OutputConverter> conv (conv_temp);
RETURN_IF_ERROR(charset.Set(conv->GetDestinationCharacterSet()));
OP_STATUS ret = ConvertToChar8(conv.get(), source, dest, max_dst_length, converted);
invalid_count = conv->GetNumberOfInvalid();
#ifdef ENCODINGS_CAP_SPECIFY_INVALID
OpStatus::Ignore(invalid_chars.Set(conv->GetInvalidCharacters()));
#endif
return ret;
}
OP_STATUS MessageEngine::ConvertToChar8(OutputConverter* converter, IN const OpStringC16& source, OUT OpString8& dest, int max_dst_length, int* converted)
{
OP_STATUS ret;
dest.Empty();
if (converted)
{
*converted = 0;
}
OpString8 temp_buffer;
if (!temp_buffer.Reserve(max(2*source.Length(), max_dst_length)+9+1))
return OpStatus::ERR_NO_MEMORY;
//Buffer needs to be terminated to avoid problems in OpString::Append
if (temp_buffer.Capacity())
{
*(temp_buffer.CStr()+temp_buffer.Capacity()-1) = 0;
}
int read = 0;
char* src = (char*)source.CStr();
int src_len = UNICODE_SIZE(source.Length());
int dest_len = temp_buffer.Capacity()-1;
if (max_dst_length > -1 && max_dst_length < dest_len)
dest_len = max_dst_length;
while (src_len>0 && dest_len>0)
{
int l = converter->Convert(src, (dest_len>9 ? src_len : 2), (char*)temp_buffer.CStr(), (max_dst_length==-1 ? dest_len : (dest_len>9 ? dest_len-9 : dest_len)), &read); //9 is the worst-case longest self-contained sequence for a character
temp_buffer.CStr()[l] = 0;
if ((ret=dest.Append(temp_buffer.CStr(), l)) != OpStatus::OK)
return ret;
if (converted)
{
*converted += UNICODE_DOWNSIZE(read);
}
if (max_dst_length!=-1)
{
dest_len -= l;
if (converter->LongestSelfContainedSequenceForCharacter()>dest_len) //We might not have room for the next char
break;
}
if (!read) //We have data in the buffer that will not be converted. For now, we bail out with an OK
break;
src += read;
src_len -= read;
}
int len=converter->ReturnToInitialState(NULL);
if (len)
{
converter->ReturnToInitialState(temp_buffer.CStr());
temp_buffer.CStr()[len] = 0;
if ((ret=dest.Append(temp_buffer.CStr(), len)) != OpStatus::OK)
return ret;
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::MailCommandHTTP(URL& url)
{
NewsfeedSubscribeDialog* dialog = OP_NEW(NewsfeedSubscribeDialog, ());
if (!dialog)
return OpStatus::ERR_NO_MEMORY;
return dialog->Init(g_application->GetActiveDesktopWindow(), url);
}
// ***************************************************************************
//
// IRCURLNewAccountListener; class used by the function below.
//
// ***************************************************************************
#ifdef IRC_SUPPORT
class IRCURLNewAccountListener
: public DialogListener
{
public:
// Construction.
IRCURLNewAccountListener(AccountManager* account_manager, OpAutoPtr<IRCURLParser> irc_url_parser)
: m_account_manager(account_manager),
m_irc_url_parser(irc_url_parser)
{
OP_ASSERT(m_account_manager != 0);
}
private:
// DialogListener.
virtual void OnOk(Dialog* dialog, UINT32 result)
{
// Look up the account.
Account* account = 0;
m_account_manager->GetChatAccountByServer(account, m_irc_url_parser->Location());
if (account == 0)
return;
// Join the channels we should join.
const UINT channel_count = m_irc_url_parser->ChannelCount();
if (channel_count > 0)
{
OpString channel;
OpString key;
for (UINT index = 0; index < channel_count; ++index)
{
OpStatus::Ignore(m_irc_url_parser->Channel(index, channel, key));
if (channel.HasContent())
account->JoinChatRoom(channel, key);
}
}
else
account->SetChatStatus(AccountTypes::ONLINE);
// Engage in the private conversations we should.
{
OpString target;
for (UINT index = 0, query_count = m_irc_url_parser->QueryCount();
index < query_count; ++index)
{
OpStatus::Ignore(m_irc_url_parser->Query(index, target));
if (target.HasContent())
{
ChatInfo chat_info(target);
g_application->GoToChat(account->GetAccountId(), chat_info,
FALSE, FALSE, account->GetOpenPrivateChatsInBackground());
}
}
}
}
virtual void OnClose(Dialog* dialog) { OP_DELETE(this); }
// Members.
AccountManager* m_account_manager;
OpAutoPtr<IRCURLParser> m_irc_url_parser;
};
// ***************************************************************************
OP_STATUS MessageEngine::MailCommandIRC(URL& url)
{
OpAutoPtr<IRCURLParser> irc_url_parser(OP_NEW(IRCURLParser, ()));
if (irc_url_parser.get() == 0)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(irc_url_parser->Init(url));
// See if we allready have an account the the server specified by the
// IRC URL.
Account* account = 0;
RETURN_IF_ERROR(m_account_manager->GetChatAccountByServer(account,
irc_url_parser->Location()));
if (account == 0)
{
// Fetch the default irc account.
Account* irc_account = 0;
const UINT16 default_irc_account_id = m_account_manager->GetDefaultAccountId(AccountTypes::TYPE_CATEGORY_CHAT);
if (default_irc_account_id != 0)
{
OpStatus::Ignore(m_account_manager->GetAccountById(
default_irc_account_id, irc_account));
}
// If the default account doesn't exist, we fetch the first
// available IRC account.
if (irc_account == 0)
irc_account = m_account_manager->GetFirstAccountWithType(AccountTypes::IRC);
// We have a default IRC account we can use some settings from.
if (irc_account != 0 && irc_url_parser->HasLocation())
{
// Get the nickname to use.
OpString nickname;
if (irc_url_parser->HasNickname())
RETURN_IF_ERROR(nickname.Set(irc_url_parser->Nickname()));
else
RETURN_IF_ERROR(nickname.Set(irc_account->GetIncomingUsername()));
// Create a new temporary account.
RETURN_IF_ERROR(m_account_manager->AddTemporaryAccount(account,
AccountTypes::IRC, irc_url_parser->Location(), irc_url_parser->Port(), FALSE,
nickname, UNI_L("")));
// Set some properties from the default account.
OpString realname;
OpStatus::Ignore(irc_account->GetRealname(realname));
OpStatus::Ignore(account->SetRealname(realname));
OpString email;
OpStatus::Ignore(irc_account->GetEmail(email));
OpStatus::Ignore(account->SetEmail(email));
}
else if (irc_account == 0)
{
// Bring up the account wizard.
NewAccountWizard* account_wizard = OP_NEW(NewAccountWizard, ());
if (account_wizard == 0)
return OpStatus::ERR_NO_MEMORY;
// Set up a listener class to perform a join / connection when
// the wizard has finished.
OpString location;
OpStatus::Ignore(location.Set(irc_url_parser->Location()));
IRCURLNewAccountListener* listener = OP_NEW(IRCURLNewAccountListener, (m_account_manager, irc_url_parser));
if (listener == 0)
return OpStatus::ERR;
account_wizard->SetDialogListener(listener);
account_wizard->Init(AccountTypes::IRC,
g_application->GetActiveDesktopWindow(), location);
}
else if (irc_account != 0)
{
// If we get here, it means that the parsed host is empty. Just
// use the current account then.
account = irc_account;
}
}
if (account == 0)
return OpStatus::OK;
OP_ASSERT(irc_url_parser.get() != 0);
// Join the desired chat rooms if some are specified.
const UINT channel_count = irc_url_parser->ChannelCount();
if (channel_count > 0)
{
for (UINT index = 0; index < channel_count; ++index)
{
OpString channel;
OpString key;
OpStatus::Ignore(irc_url_parser->Channel(index, channel, key));
if (channel.HasContent())
{
RETURN_IF_ERROR(account->JoinChatRoom(channel, key));
// See if we allready are in this room, if so - focus it.
const OpStringC& room_name = (channel[0] == '#' ? channel.SubString(1) : channel);
if (m_chatrooms_model->GetRoomItem(account->GetAccountId(), room_name) != 0)
{
ChatInfo chat_info(room_name);
g_application->GoToChat(account->GetAccountId(), chat_info, TRUE, FALSE);
}
}
}
}
else
{
// No room was specified, just go online.
RETURN_IF_ERROR(account->SetChatStatus(AccountTypes::ONLINE));
}
// Engage in the private conversations we should.
{
OpString target;
for (UINT index = 0, query_count = irc_url_parser->QueryCount();
index < query_count; ++index)
{
OpStatus::Ignore(irc_url_parser->Query(index, target));
if (target.HasContent())
{
ChatInfo chat_info(target);
g_application->GoToChat(account->GetAccountId(), chat_info,
FALSE, FALSE, account->GetOpenPrivateChatsInBackground());
}
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::MailCommandChatTransfer(URL& url)
{
// The format of a dcc url will be "chattransfer:///accountid=%u&port=%u&transferid=%u".
OpString path;
RETURN_IF_ERROR(url.GetAttribute(URL::KUniPathAndQuery_Escaped, path));
if (path.IsEmpty())
return OpStatus::ERR;
OpString parameters;
if (path[0] == '/')
RETURN_IF_ERROR(parameters.Set(path.CStr() + 1));
else
RETURN_IF_ERROR(parameters.Set(path));
UINT account_id = 0;
UINT port = 0;
UINT transfer_id = 0;
StringTokenizer parameter_tokenizer(parameters, UNI_L("&"));
while (parameter_tokenizer.HasMoreTokens())
{
OpString parameter;
RETURN_IF_ERROR(parameter_tokenizer.NextToken(parameter));
if (parameter.HasContent())
{
if (parameter.CompareI("accountid=", 10) == 0)
account_id = uni_atoi(parameter.CStr() + 10);
else if (parameter.CompareI("port=", 5) == 0)
port = uni_atoi(parameter.CStr() + 5);
else if (parameter.CompareI("transferid=", 11) == 0)
transfer_id = uni_atoi(parameter.CStr() + 11);
}
}
// Get the account associated with the parsed account id and notify it.
Account* account = 0;
OpStatus::Ignore(m_account_manager->GetAccountById(account_id, account));
if (account != 0)
OpStatus::Ignore(account->AcceptReceiveRequest(port, transfer_id));
return OpStatus::OK;
}
#endif // IRC_SUPPORT
OP_STATUS MessageEngine::MailCommandNews(URL& url)
{
OP_STATUS ret;
Account* account = NULL;
OpString param_str;
OpString accesspoint_path;
OpString username, servername, password;
if ((ret=username.SetFromUTF8(url.GetAttribute(URL::KUserName).CStr()))!=OpStatus::OK ||
(ret=servername.Set(url.GetAttribute(URL::KHostName)))!=OpStatus::OK ||
(ret=password.Set(url.GetAttribute(URL::KPassWord)))!=OpStatus::OK) //Password is from the URL, and shouldn't need to be wiped
{
return ret;
}
BOOL bracket_messageID = username.HasContent() && *(username.CStr())=='<' && servername.HasContent() && *(servername.CStr()+servername.Length()-1)=='>';
BOOL nonbracket_messageID = username.HasContent() && password.IsEmpty();
if (bracket_messageID || nonbracket_messageID) // news://<messageID> or news://messageID ?
{
RETURN_IF_ERROR(url.GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI, param_str, TRUE));
int protocol_length = ((URLType)url.GetAttribute(URL::KType) == URL_SNEWS) ? 8 : 7; //'snews://' or 'news://'
if (param_str.Length() > protocol_length)
param_str.Delete(0, protocol_length); //Skip 'snews://' or 'news://'
if ((ret=m_account_manager->GetAccountByProperties(account, AccountTypes::NEWS, NULL, 0,
((URLType)url.GetAttribute(URL::KType) == URL_SNEWS), NULL)) != OpStatus::OK)
{
return ret;
}
uni_char* last_char = param_str.CStr()+param_str.Length()-1;
if (*last_char == '/')
*last_char = 0;
if ((ret=accesspoint_path.Set(param_str)) != OpStatus::OK)
return ret;
}
else
{
UINT16 port = url.GetAttribute(URL::KServerPort);
if (port==0) port = ((URLType)url.GetAttribute(URL::KType) == URL_NEWS) ? 119 : 563;
if ((ret=m_account_manager->GetAccountByProperties(account, AccountTypes::NEWS, servername, port,
((URLType)url.GetAttribute(URL::KType) == URL_SNEWS), username)) != OpStatus::OK)
{
account = NULL;
}
//No matching account defined. Add it as temporary account.
if (account==NULL)
{
if (servername.HasContent())
{
OpString password;
RETURN_IF_ERROR(password.Set(url.GetAttribute(URL::KPassWord)));
RETURN_IF_ERROR(InitMessageDatabaseIfNeeded());
if ((ret=m_account_manager->AddTemporaryAccount(account, AccountTypes::NEWS, servername, port, ((URLType)url.GetAttribute(URL::KType) == URL_SNEWS),
username, password)) != OpStatus::OK)
{
return ret;
}
if (!account)
return OpStatus::ERR_NULL_POINTER;
// This could have been the first account created ever, update the UI
g_application->SettingsChanged(SETTINGS_ACCOUNT_SELECTOR);
g_application->SettingsChanged(SETTINGS_MENU_SETUP);
g_application->SettingsChanged(SETTINGS_TOOLBAR_CONTENTS);
g_input_manager->InvokeAction(OpInputAction::ACTION_FOCUS_PANEL, 0, UNI_L("Mail"), g_application->GetActiveDesktopWindow());
}
else
{
// Show account setup wizard
g_application->ShowAccountNeededDialog(AccountTypes::NEWS);
return OpStatus::OK;
}
}
OpString parameter_string;
RETURN_IF_ERROR(url.GetAttribute(URL::KUniPathAndQuery_Escaped, parameter_string));
const uni_char* parameters = parameter_string.CStr();
if (parameters)
{
while (*parameters=='/') parameters++;
if ((ret=param_str.Set(parameters)) != OpStatus::OK)
return ret;
const uni_char* accesspoint_separator = parameters;
while (*accesspoint_separator && *accesspoint_separator != '/') accesspoint_separator++;
if ((ret=accesspoint_path.Set(parameters, accesspoint_separator ? accesspoint_separator-parameters : (int)KAll)) != OpStatus::OK)
return ret;
}
}
OpString accesspoint_name;
BOOL is_msgid = (accesspoint_path.FindFirstOf('@') != KNotFound);
if (is_msgid) //We don't know the access-point when only given Message-id
{
if ( ((ret=accesspoint_name.Set(UNI_L("news://"))) != OpStatus::OK) ||
((ret=accesspoint_name.Append(accesspoint_path)) != OpStatus::OK) )
{
return ret;
}
}
else
{
if ((ret=accesspoint_name.Set(accesspoint_path)) != OpStatus::OK)
return ret;
}
if (!account)
return OpStatus::ERR_NULL_POINTER;
if (accesspoint_path.IsEmpty()) //Link was probably <URL:news://news.server.domain/>
{
GetGlueFactory()->GetBrowserUtils()->SubscribeDialog(account->GetAccountId());
}
else
{
//Show (and Add, if needed) index
Index* index = m_indexer->GetSubscribedFolderIndex(account, accesspoint_path, 0, accesspoint_name, TRUE, TRUE);
if (index)
{
GetGlueFactory()->GetBrowserUtils()->ShowIndex(index->GetId(), FALSE);
if (is_msgid) //If we already have the message, no need to go asking for it again
{
if (param_str.HasContent())
{
UINT32 message_number = 0;
OpString8 message_id;
RETURN_IF_ERROR(message_id.Set(param_str.CStr()));
message_number = m_store->GetMessageByMessageId(message_id);
if (message_number!=0 && index->NewMessage(message_number)==OpStatus::OK)
{
return OpStatus::OK; //We have added it to the index. We are done.
}
}
}
else //Make sure newsgroup is subscribed
{
OpStatus::Ignore(account->AddSubscribedFolder(accesspoint_path));
}
OpString8 param_str8;
RETURN_IF_ERROR(param_str8.Set(param_str.CStr()));
return ((NntpBackend*)((Account*)account)->GetIncomingBackend())->FetchMessage(param_str8);
}
}
return OpStatus::OK;
}
OP_STATUS MessageEngine::SplitIntoAccounts(const OpINT32Vector& message_ids, OpINT32HashTable<OpINT32Vector>& hash_table)
{
OpINT32Vector *temp_vector;
// Split messages in different accounts
for(UINT32 index = 0; index < message_ids.GetCount(); index++)
{
UINT16 account_id = m_store->GetMessageAccountId(message_ids.Get(index));
if(hash_table.GetData(account_id, &temp_vector) != OpStatus::OK)
{
temp_vector = OP_NEW(OpINT32Vector, ());
if (!temp_vector)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(hash_table.Add(account_id, temp_vector));
}
RETURN_IF_ERROR(temp_vector->Add(message_ids.Get(index)));
}
return OpStatus::OK;
}
#ifdef M2_MAPI_SUPPORT
void MessageEngine::CheckDefaultMailClient()
{
if (!m_check_default_mailer)
return;
m_check_default_mailer = FALSE;
Account* account = g_m2_engine->GetAccountManager()->GetFirstAccountWithCategory(AccountTypes::TYPE_CATEGORY_MAIL);
if (!account)
return;
if ((g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRST ||
g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRSTCLEAN||
g_pcm2->GetIntegerPref(PrefsCollectionM2::ShowDefaultMailClientDialog)) &&
g_desktop_mail_client_utils->IsOperaAbleToBecomeDefaultMailClient())
{
ShowDialog(OP_NEW(DefaultMailClientDialog,()), g_global_ui_context, g_application->GetActiveMailDesktopWindow());
}
// Fix for DSK-362042 External mailto-links don't open compose window when Opera is already running
else if ((g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRSTCLEAN||
g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRST_NEW_BUILD_NUMBER) &&
g_desktop_mail_client_utils->IsOperaDefaultMailClient())
{
g_desktop_mail_client_utils->SetOperaAsDefaultMailClient();
}
}
#endif //M2_MAPI_SUPPORT
// ---------------------------------------------------------------------------------
MessageEngine::MultipleMessageChanger::MultipleMessageChanger(unsigned tochange)
: m_docount(g_m2_engine && (tochange == 0 || tochange > 5))
{
if (m_docount)
g_m2_engine->m_multiple_message_changes++;
}
MessageEngine::MultipleMessageChanger::~MultipleMessageChanger()
{
if (m_docount)
{
g_m2_engine->m_multiple_message_changes--;
if (g_m2_engine->m_multiple_message_changes == 0)
{
g_m2_engine->OnMessageChanged(UINT_MAX);
g_m2_engine->OnIndexChanged(UINT_MAX);
}
}
}
#endif //M2_SUPPORT
|
// TabTesterDlg.h: 헤더 파일
//
#pragma once
#include "CFirstDlg.h"
#include "CSecondDlg.h"
// CTabTesterDlg 대화 상자
class CTabTesterDlg : public CDialogEx
{
// 생성입니다.
public:
CTabTesterDlg(CWnd* pParent = nullptr); // 표준 생성자입니다.
// 대화 상자 데이터입니다.
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_TABTESTER_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
// 구현입니다.
protected:
HICON m_hIcon;
// 생성된 메시지 맵 함수
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CTabCtrl m_TabControl;
CFirstDlg m_firstTab;
CSecondDlg m_secondTab;
afx_msg void OnSelchangeTab1(NMHDR* pNMHDR, LRESULT* pResult);
CTreeCtrl m_TreeCtrl;
afx_msg void OnTvnSelchangedTree1(NMHDR* pNMHDR, LRESULT* pResult);
};
|
// Copyright (c) 2020 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 _TDataStd_GenericEmpty_HeaderFile
#define _TDataStd_GenericEmpty_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TDF_DerivedAttribute.hxx>
class TDF_RelocationTable;
class TDataStd_GenericEmpty;
DEFINE_STANDARD_HANDLE(TDataStd_GenericEmpty, TDF_Attribute)
//! An ancestor attribute for all attributes which have no fields.
//! If an attribute inherits this one it should not have drivers for persistence.
class TDataStd_GenericEmpty : public TDF_Attribute
{
public:
Standard_EXPORT void Restore (const Handle(TDF_Attribute)&) Standard_OVERRIDE {};
Standard_EXPORT void Paste (const Handle(TDF_Attribute)&, const Handle(TDF_RelocationTable)&) const Standard_OVERRIDE {}
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(TDataStd_GenericEmpty,TDF_Attribute)
};
#endif // _TDataStd_GenericEmpty_HeaderFile
|
#ifndef HcalTestBeam_HcalTB04Analysis_H
#define HcalTestBeam_HcalTB04Analysis_H
// -*- C++ -*-
//
// Package: HcalTestBeam
// Class : HcalTB04Analysis
//
/**\class HcalTB04Analysis HcalTB04Analysis.h SimG4CMS/HcalTestBeam/interface/HcalTB04Analysis.h
Description: Analysis of 2004 Hcal Test beam simulation
Usage: A Simwatcher class and can be activated from Oscarproducer module
*/
//
// Original Author: Sunanda Banerjee
// Created: Thu May 18 10:14:34 CEST 2006
//
// system include files
#include <iostream>
#include <memory>
#include <vector>
#include <string>
// user include files
#include "SimG4Core/Watcher/interface/SimProducer.h"
#include "SimG4Core/Notification/interface/Observer.h"
#include "SimG4CMS/Calo/interface/HcalQie.h"
#include "SimG4CMS/HcalTestBeam/interface/HcalTB04Histo.h"
#include "SimDataFormats/CaloHit/interface/CaloHit.h"
#include "SimDataFormats/HcalTestBeam/interface/PHcalTB04Info.h"
#include "G4Step.hh"
#include "G4Track.hh"
#include "G4ThreeVector.hh"
#include <boost/cstdint.hpp>
class BeginOfRun;
class BeginOfEvent;
class EndOfEvent;
class PHcalTB04Info;
namespace CLHEP {
class HepRandomEngine;
}
class HcalTB04Analysis : public SimProducer,
public Observer<const BeginOfRun *>,
public Observer<const BeginOfEvent *>,
public Observer<const EndOfEvent *>,
public Observer<const G4Step *> {
public:
HcalTB04Analysis(const edm::ParameterSet &p);
~HcalTB04Analysis() override;
void produce(edm::Event &, const edm::EventSetup &) override;
private:
HcalTB04Analysis(const HcalTB04Analysis &) = delete; // stop default
const HcalTB04Analysis &operator=(const HcalTB04Analysis &) = delete;
void init();
// observer methods
void update(const BeginOfRun *run) override;
void update(const BeginOfEvent *evt) override;
void update(const G4Step *step) override;
void update(const EndOfEvent *evt) override;
//User methods
void fillBuffer(const EndOfEvent *evt);
void qieAnalysis(CLHEP::HepRandomEngine *);
void xtalAnalysis(CLHEP::HepRandomEngine *);
void finalAnalysis();
void fillEvent(PHcalTB04Info &);
void clear();
int unitID(uint32_t id);
double scale(int det, int layer);
double timeOfFlight(int det, int layer, double eta);
private:
HcalQie *myQie;
HcalTB04Histo *histo;
// to read from parameter set
bool hcalOnly;
int mode, type;
double ecalNoise, beamOffset;
int iceta, icphi;
double scaleHB0, scaleHB16, scaleHO, scaleHE0;
std::vector<std::string> names;
G4RotationMatrix *beamline_RM;
// Constants for the run
int count;
int nTower, nCrystal;
std::vector<int> idHcal, idXtal;
std::vector<uint32_t> idTower, idEcal;
// Constants for the event
int nPrimary, particleType;
double pInit, etaInit, phiInit;
std::vector<CaloHit> ecalHitCache;
std::vector<CaloHit> hcalHitCache, hcalHitLayer;
std::vector<double> esimh, eqie, esime, enois;
std::vector<double> eseta, eqeta, esphi, eqphi, eslay, eqlay;
double etots, eecals, ehcals, etotq, eecalq, ehcalq;
bool pvFound;
int evNum, pvType;
G4ThreeVector pvPosition, pvMomentum, pvUVW;
std::vector<int> secTrackID, secPartID;
std::vector<G4ThreeVector> secMomentum;
std::vector<double> secEkin;
std::vector<int> shortLivedSecondaries;
};
#endif
|
#ifndef MSGBUS_INTERFACE_H
#define MSGBUS_INTERFACE_H
#include "NetMsgBusFuture.hpp"
#include <stdint.h>
#include <string>
#include <string.h>
#include <boost/shared_array.hpp>
#include <boost/weak_ptr.hpp>
#include <vector>
#include <map>
namespace NetMsgBus
{
struct MsgBusParam
{
MsgBusParam()
:paramdata(),
paramlen(0)
{
}
MsgBusParam(boost::shared_array<char> data, uint32_t len)
:paramdata(data),
paramlen(len)
{
}
MsgBusParam DeepCopy()
{
boost::shared_array<char> destcopy(new char[paramlen]);
memcpy(destcopy.get(), paramdata.get(), paramlen);
return MsgBusParam(destcopy, paramlen);
}
boost::shared_array<char> paramdata;
uint32_t paramlen;
};
class IMsgHandler
{
public:
virtual bool OnMsg(const std::string&, MsgBusParam& param, bool&) = 0;
virtual ~IMsgHandler(){}
protected:
IMsgHandler(){}
};
typedef boost::shared_ptr<IMsgHandler> MsgHandlerStrongRef;
typedef boost::weak_ptr<IMsgHandler> MsgHandlerWeakRef;
template <typename T> MsgBusParam BuildinType2Param(const T& src)
{
boost::shared_array<char> paramdata(new char[sizeof(T)]);
memcpy(paramdata.get(), (char*)&src, sizeof(T));
MsgBusParam msgparam(paramdata, sizeof(T));
return msgparam;
}
template <typename T> void Param2BuildinType(MsgBusParam param, T& result)
{
assert(param.paramlen == sizeof(T));
memcpy((char*)&result, param.paramdata.get(), sizeof(T));
}
template <typename T> MsgBusParam CustomType2Param(const T& src)
{
return src.ToMsgBusParam();
}
template <typename T> void Param2CustomType(MsgBusParam param, T& result)
{
result.FromMsgBusParam(param);
}
// convert protocol buffer types to msgbusparam.
template <typename T> MsgBusParam PBType2Param(const T& src)
{
int size = src.ByteSize();
boost::shared_array<char> paramdata(new char[size]);
src.SerializeToArray(paramdata.get(), size);
MsgBusParam msgparam(paramdata, size);
return msgparam;
}
template <typename T> void Param2PBType(MsgBusParam param, T& result)
{
result.ParseFromArray(param.paramdata.get(), param.paramlen);
}
template <typename T> void Param2CustomType(MsgBusParam param, std::vector<T>& result)
{
T::MsgBusParamToVectorType(param, result);
}
template <typename T> MsgBusParam CustomType2Param(const std::vector<T>& src)
{
return T::VectorTypeToMsgBusParam(src);
}
template <typename T> void Param2CustomType(MsgBusParam param, std::map<std::string, T>& result)
{
T::MsgBusParamToMapType(param, result);
}
template <typename T> MsgBusParam CustomType2Param(const std::map<std::string, T>& src)
{
return T::MapTypeToMsgBusParam(src);
}
template<> MsgBusParam CustomType2Param(const std::string& src);
template<> void Param2CustomType(MsgBusParam param, std::string& result);
enum kMsgSendType
{
// first try send to client directly, then try again when client host info updated from server.
SendDirectToClient = 1,
// just send data to server, and server will forward the message to dest client.
SendUseServerRelay = 2,
};
// each process only can have one netmsgbus and one localmsgbus.
// process can use the netmsgbus to communicate with other process, and then
// use netmsgbus to notify localmsgbus to handle the messages from other process.
bool InitMsgBus(long hmainwnd);
void DestroyMsgBus();
bool SendMsg(const std::string& msgid);
bool PostMsg(const std::string& msgid);
bool SendMsg(const std::string& msgid, MsgBusParam& param);
bool PostMsg(const std::string& msgid, MsgBusParam param);
bool SendMsg(const std::string& msgid, boost::shared_array<char>& param, uint32_t& paramlen);
bool PostMsg(const std::string& msgid, boost::shared_array<char> param, uint32_t paramlen);
bool RegisterMsg(const std::string& msgid, MsgHandlerStrongRef sp_handler_obj, bool must_called_inmsgbusthread = true);
void UnRegisterMsg(const std::string& msgid, IMsgHandler* p_handler_obj);
// connect the netmsgbus server before do something related to netmsgbus.
int NetMsgBusConnectServer(const std::string& serverip, unsigned short int serverport);
void NetMsgBusDisConnectFromServer();
void NetMsgBusDisConnectAll();
// register a receiver on the netmsgbus so that the client can receive messages from other client.
int NetMsgBusRegReceiver(const std::string& name, const std::string& hostip, unsigned short& hostport);
// send messages to a client connected with netmsgbus server. Use empty dest_name to broadcast messages on the netmsgbus.
//
bool NetMsgBusSendMsg(const std::string& dest_name, const std::string& msgid, MsgBusParam param, kMsgSendType sendtype);
bool NetMsgBusSendMsg(const std::string& dest_ip, unsigned short dest_port, const std::string& msgid,
MsgBusParam param);
// if you have no more data to send, then you can disconnect from the receiver.
//void NetMsgBusDisConnectFromClient(const std::string& name);
// get the ip and port info and cache them in client. just work like dns name resolve.
bool NetMsgBusQueryHostInfo(const std::string& clientname, std::string& ip, unsigned short int& port);
// send messages to a client and wait response data from it.
bool NetMsgBusGetData(const std::string& clientname, const std::string& msgid, MsgBusParam param,
std::string& rsp_data, int32_t timeout_sec = 30);
bool NetMsgBusGetData(const std::string& dest_ip, unsigned short dest_port, const std::string& msgid, MsgBusParam param,
std::string& rsp_data, int32_t timeout_sec = 30);
boost::shared_ptr<NetFuture> NetMsgBusAsyncGetData(const std::string& clientname, const std::string& msgid,
MsgBusParam param, NetFuture::futureCB callback = NULL);
boost::shared_ptr<NetFuture> NetMsgBusAsyncGetData(const std::string& dest_ip,
unsigned short dest_port, const std::string& msgid, MsgBusParam param, NetFuture::futureCB callback = NULL);
// query all available services that are registered on the net message bus server
int NetMsgBusQueryServices(const std::string& match_str, std::string& rsp);
void printAllMsgHandler(const std::string& msgid);
}
#endif
|
#include "phrase4.hpp"
#include <iostream>
#include <cstddef> // std::size_t
#include <string> // std::string
Alphabet::Alphabet()
{
alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','k','r','s','t','v','w','x','y','z'};
}
Alphabet::Alphabet(std::vector<char> &v)
{
alphabet=v;
}
Alphabet::Alphabet(const Alphabet &other)
{
alphabet = other.alphabet;
}
Alphabet& Alphabet::operator=(const Alphabet &A)
{
alphabet = A.alphabet;
return *this;
}
void Alphabet::put_alphabet(int i, char a)
{
alphabet[i] = a;
}
Alphabet Alphabet::get_alphabet()
{
return alphabet;
}
int Alphabet::taille() const
{
return alphabet.size();
}
bool Alphabet::teste_mot(std::string &s)
{
int compteur = 0;
bool r = false;
for(std::string::size_type i = 0; i < s.size(); i++){
for(int j = 0; j<alphabet.size(); j++){
if(s[i] == alphabet[j] ) compteur++ ;//return true;
}
if(compteur-(i+1)!=0) compteur = compteur-1; //eviter les doublons
}
std::cout << compteur << '\n';
if(compteur == s.size()) {r = true;}
return r;
}
std::ostream & operator <<(std::ostream & os, Alphabet A)
{
for(int i=0;i < A.alphabet.size();i++){
os << A.alphabet[i] << " ";
}
os << std::endl;
return os;
}
Dico::Dico()
{
Dico::alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','k','r','s','t','v','w','x','y','z'};
}
Dico::Dico(Alphabet a, std::vector<std::string> &s)
{
str = s;
alphab = a;
}
void Dico::aff_dico() const
{
for (int i = 0; i< str.size(); i++) {
std::cout << str[i] << '\n';
}
}
void Dico::aff_alphabet() const
{
for (int i = 0; i< alphabet.size(); i++) {
std::cout << alphabet[i] << '\n';
}
}
bool Dico::presence_mot(std::string &s)
{
for (int i = 0; i< str.size(); i++) {
if(str[i].compare(s) == 0) return true;
}
return false;
}
bool Dico::insere_mot(std::string &s)
{
if (presence_mot(s))
return false;
else{
int taille = str.size();
str.resize(taille++, s);
return true;
}
}
bool Dico::efface_mot(std::string &s)
{
if(!presence_mot(s)) return false;
else{
for (int i = 0; i<str.size(); i++){
if(str[i].compare(s) == 0){
for(int j=i; j<str.size()-1; j++){
str[j] = str[j+1];
}
int taille = str.size();
str.resize(taille--);
}
}
return true;
}
}
int main ()
{
int i,j;
// Partie 1 de l'examen
Alphabet alphab1;
std::vector<char> v1{'l','a','m','f','c','b','s','e','a','p'};
std::vector<char> v2{'k','l','k','h','d','u','y','q','a','z','p','m'};
Alphabet alphab2(v1);
Alphabet alphab3(v2);
std::cout << "alphab1 = " << alphab1;
std::cout << "v1 = {l,a,m,f,c,b,s,e,a,p}\n";
std::cout << "alphab2(v1) = " << alphab2;
std::cout << "v2 = {k,l,k,h,d,u,y,q,a,z,p,m}\n";
std::cout << "alphab3(v2) = " << alphab3;
// partie 2 de l'examen
Alphabet alphab4(alphab2);
Alphabet alphab5;
alphab5 = alphab3;
std::cout << "alphab4(alphab2) = " << alphab4;
std::cout << "alphab5 = alphab3 = " << alphab5;
std::string a1 = "melasse";
std::string a2 = "matelas";
std::cout << a1 << " dans aphab2 ? \n";
if (alphab2.teste_mot(a1))
std::cout << "oui"<< "\n";
else
std::cout << "non"<< "\n";
std::cout << a2 << " dans aphab2 ? \n";
if (alphab2.teste_mot(a2))
std::cout << "oui"<< "\n";
else
std::cout << "non"<< "\n";
//partie 3
Dico d1;
std::vector<std::string> vs={"base","lame","mua","dual","qhmp","pbcf","lafc"};
Dico d2(alphab2,vs);
Dico d3(alphab3,vs);
std::cout << "d1 :\n";
d1.aff_dico();
d1.aff_alphabet();
std::cout << "d2 :\n";
d2.aff_alphabet();
d2.aff_dico();
std::cout << "d3 :\n";
d3.aff_alphabet();
d3.aff_dico();
// partie 4 de l'examen
std::string ss0 = "base";
std::string ss1 = "balsa";
std::string ss2 = "khua";
if (d2.presence_mot(ss0))
std::cout << ss0 << " est présent dans d2 \n";
else
std::cout << ss0 << " n'est pas présent dans d2 \n";
if (d3.presence_mot(ss0))
std::cout << ss0 << " est présent dans d3 \n";
else
std::cout << ss0 << " n'est pas présent dans d3 \n";
if (d2.presence_mot(ss1))
std::cout << ss1 << " est présent dans d2 \n";
else
std::cout << ss1 << " n'est pas présent dans d2 \n";
if (d2.presence_mot(ss2))
std::cout << ss2 << " est présent dans d2 \n";
else
std::cout << ss2 << " n'est pas présent dans d2 \n";
if (d3.presence_mot(ss1))
std::cout << ss1 << " est présent dans d3 \n";
else
std::cout << ss1 << " n'est pas présent dans d3 \n";
if (d3.presence_mot(ss2))
std::cout << ss2 << " est présent dans d3 \n";
else
std::cout << ss2 << " n'est pas présent dans d3 \n";
// insertion
if (d2.insere_mot(ss0))
std::cout << "on insere "<< ss0 << " dans d2\n";
else
std::cout << "pas d'insertion de "<< ss0 << " dans d2\n";
if (d2.insere_mot(ss1))
std::cout << "on insere "<< ss1 << " dans d2\n";
else
std::cout << "pas d'insertion de "<< ss1 << " dans d2\n";
if (d2.insere_mot(ss2))
std::cout << "on insere "<< ss2 << " dans d2\n";
else
std::cout << "pas d'insertion de "<< ss2 << " dans d2\n";
if (d3.insere_mot(ss0))
std::cout << "on insere "<< ss0 << " dans d3\n";
else
std::cout << "pas d'insertion de "<< ss0 << " dans d3\n";
if (d3.insere_mot(ss1))
std::cout << "on insere "<< ss1 << " dans d3\n";
else
std::cout << "pas d'insertion de "<< ss1 << " dans d3\n";
if (d3.insere_mot(ss2))
std::cout << "on insere "<< ss2 << " dans d3\n";
else
std::cout << "pas d'insertion de "<< ss2 << " dans d3\n";
// effacement
if (d2.efface_mot(ss0))
std::cout << "on efface "<< ss0 << " dans d2\n";
else
std::cout << "pas d'effacement de "<< ss0 << " dans d2\n";
if (d2.efface_mot(ss1))
std::cout << "on efface "<< ss1 << " dans d2\n";
else
std::cout << "pas d'effacement de "<< ss1 << " dans d2\n";
if (d2.efface_mot(ss2))
std::cout << "on efface "<< ss2 << " dans d2\n";
else
std::cout << "pas d'effacement de "<< ss2 << " dans d2\n";
if (d3.efface_mot(ss0))
std::cout << "on efface "<< ss0 << " dans d3\n";
else
std::cout << "pas d'effacement de "<< ss0 << " dans d3\n";
if (d3.efface_mot(ss1))
std::cout << "on efface "<< ss1 << " dans d3\n";
else
std::cout << "pas d'effacement de "<< ss1 << " dans d3\n";
if (d3.efface_mot(ss2))
std::cout << "on efface "<< ss2 << " dans d3\n";
else
std::cout << "pas d'effacement de "<< ss2 << " dans d3\n";
//
std::cout << "Au final\n";
std::cout << "d2 :\n";
d2.aff_alphabet();
d2.aff_dico();
std::cout << "d3 :\n";
d3.aff_alphabet();
d3.aff_dico();
}
|
#pragma once
#include <string>
#include "Parser.h"
class Executor
{
private:
Executor() {}
Executor(const Executor&);
Executor& operator = ( Executor&);
std::vector<ICommand*> commands;
std::vector<int> executeOrder;
std::string buffer = "";
public:
static Executor& GetInstance() {
static Executor instance;
return instance;
}
//void ExecuteWorkFlow(std::string fileName);
//void ExecuteWorkFlow(std::string fileName, std::string in, std::string out);
void ExecuteWorkFlow(std::string fileName, ICommand* in = nullptr, ICommand* out = nullptr);
};
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
struct node{
int cou;
int s[2];
};
vector<node> V;
int root;
int newnode() {
node p;
p.cou = p.s[0] = p.s[1] = 0;
V.push_back(p);
return V.size()-1;
}
void ins(int k) {
int p = root;
for (int i = 29;i >= 0; i--) {
int loc = (k&(1 << i))?1:0;
if (V[p].s[loc]) p = V[p].s[loc];
else {
int sav = newnode();
V[p].s[loc] = sav;
p = V[p].s[loc];
}
V[p].cou++;
}
}
void del(int k) {
int p = root;
for (int i = 29;i >= 0; i--) {
int loc = (k&(1 << i))?1:0;
int sp = V[p].s[loc];
if ((--V[sp].cou) == 0) {
V[p].s[loc] = 0;
break;
}
p = sp;
}
}
int query(int k) {
int p = root,ans = 0;
for (int i = 29;i >= 0; i--) {
int loc = (k&(1 << i))?0:1;
int sp = V[p].s[loc],nsp = V[p].s[loc^1];
if (sp && V[sp].cou) {
p = sp;
ans += (1 << i);
} else if (nsp && V[nsp].cou) {
p = nsp;
} else {
ans += ((1 << (i+1))-1)&k;
break;
}
}
return max(ans,k);
}
int main() {
int n;
scanf("%d%*c",&n);
root = newnode();
char ch;int k;
while (n--) {
scanf("%c%d%*c",&ch,&k);
if (ch == '+') ins(k);
if (ch == '-') del(k);
if (ch == '?') printf("%d\n",query(k));
}
return 0;
}
|
#pragma once
#include <initializer_list>
namespace oakvr
{
namespace math
{
class Matrix;
class Vector3
{
public:
// constructors
Vector3() {};
Vector3( float x, float y, float z );
Vector3(const std::initializer_list<float> &coords);
Vector3( const class Vector4 &vec );
Vector3( const float *arr );
// cast operators
inline operator float * ();
inline operator const float * () const;
// assignment operators
auto operator += ( const Vector3 &vec ) -> Vector3&;
auto operator -= ( const Vector3 &vec ) -> Vector3&;
auto operator *= ( float scalar ) -> Vector3&;
auto operator /= ( float scalar ) -> Vector3&;
// unary operators
auto operator + () const -> Vector3;
auto operator - () const -> Vector3;
// binary operators
auto operator + ( const Vector3 &vec ) const -> Vector3;
auto operator - ( const Vector3 &vec ) const -> Vector3;
auto operator * ( float scalar ) const -> Vector3;
auto operator / ( float scalar ) const -> Vector3;
auto operator * ( const Matrix &mat ) const -> Vector3;
friend auto operator *(const Matrix &mat, const Vector3 &vec) -> Vector3;
friend auto operator * ( float scalar, const Vector3 &vec ) -> Vector3;
// equality operators
auto operator != ( const Vector3 &vec ) const -> bool;
auto operator ==(const Vector3& vec) const -> bool;
// other methods
auto GetLength() const -> float;
auto GetSquareLength() const -> float;
auto GetNormalized() const -> Vector3;
auto Normalize() -> float;
auto Dot( const Vector3 &vec ) const -> float;
auto Cross( const Vector3 &vec ) const -> Vector3;
// static constants
static Vector3 One;
static Vector3 Zero;
// members
float x, y, z;
};
auto operator * ( float scalar, const Vector3 &vec ) -> Vector3;
auto operator * ( const Matrix &mat, const Vector3 &vec ) -> Vector3;
//------------------------------------------------------
// cast operators
// --------------------------------------------------------------------------------
Vector3::operator float *()
{
return &x;
}
// --------------------------------------------------------------------------------
Vector3::operator const float *() const
{
return &x;
}
} // namespace Math
}
|
#include "f3lib/assets/world/Landscape.h"
#include "f3lib/utils/BinaryFileReader.h"
#include <sstream>
#include <iomanip>
using namespace f3;
constexpr float HGT_NOWALK = 1000.0f;
constexpr float HGT_NOFLY = 2000.0f;
constexpr float HGT_NOMOVE = 3000.0f;
constexpr float HGT_DIE = 4000.0f;
Landscape::Landscape()
{
memset(_heightField, 0, sizeof(float)*NUM_VERTICES);
}
Landscape::~Landscape()
{
}
float& Landscape::getHeightAtMutable(int x, int z)
{
return _heightField[x + NUM_VERTICES_ROW*(z)];
}
float Landscape::getHeightAt(int x, int z) const
{
return _heightField[x + NUM_VERTICES_ROW*(z)];
}
void Landscape::init()
{
//get attributes
for (int x = 0; x < NUM_FACES_ROW; ++x)
{
for (int z = 0; z < NUM_FACES_ROW; ++z)
{
float& height = getHeightAtMutable(x, z);
if (height >= HGT_NOWALK)
{
if (height >= HGT_DIE)
height -= HGT_DIE;
else if (height >= HGT_NOMOVE)
height -= HGT_NOMOVE;
else if (height >= HGT_NOFLY)
height -= HGT_NOFLY;
else
height -= HGT_NOWALK;
}
}
}
//CalculateNormals();
}
/*
void CLandscape::CalculateNormals()
{
Lime::int32 x,z,nVectorsUsed;
VECTOR3 vTmp;
VECTOR3 v1,v2,v3,v4,v5,v6,v7,v8;
VECTOR3 n1,n2,n3,n4,n5,n6,n7,n8;
v1.X = -1.0f;
v1.Z = 1.0f;
v2.X = 0.0f;
v2.Z = 1.0f;
v3.X = 1.0f;
v2.Z = 1.0f;
v4.X = 1.0f;
v4.Z = 0.0f;
v5.X = 1.0f;
v5.Z = -1.0f;
v6.X = 0.0f;
v6.Z = -1.0f;
v7.X = -1.0f;
v7.Z = -1.0f;
v8.X = -1.0f;
v8.Z = 0.0f;
for(x=0;x<NUM_VERTICES_ROW;++x)
{
for(z=0;z<NUM_VERTICES_ROW;++z)
{
//KURAI: Calculate vectors
if(x > 0 && z > 0)
v1.Y = HEIGHT_AT(x,z)-HEIGHT_AT(x-1,z-1);
if(z > 0)
v2.Y = HEIGHT_AT(x,z)-HEIGHT_AT(x,z-1);
if(x < 128 && z > 0)
v3.Y = HEIGHT_AT(x,z)-HEIGHT_AT(x+1,z-1);
if(x < 128)
v4.Y = HEIGHT_AT(x,z)-HEIGHT_AT(x+1,z);
if(x < 128 && z < 128)
v5.Y = HEIGHT_AT(x,z)-HEIGHT_AT(x+1,z+1);
if(z < 128)
v6.Y = HEIGHT_AT(x,z)-HEIGHT_AT(x,z+1);
if(x > 0 && z < 128)
v7.Y = HEIGHT_AT(x,z)-HEIGHT_AT(x-1,z+1);
if(x > 0)
v8.Y = HEIGHT_AT(x,z)-HEIGHT_AT(x-1,z);
//KURAI: calculate plane normals
n1 = VECTOR3Cross(v1,v2);
n2 = VECTOR3Cross(v2,v3);
n3 = VECTOR3Cross(v3,v4);
n4 = VECTOR3Cross(v4,v5);
n5 = VECTOR3Cross(v5,v6);
n6 = VECTOR3Cross(v6,v7);
n7 = VECTOR3Cross(v7,v8);
n8 = VECTOR3Cross(v8,v1);
NORMAL_AT(x,z) = (n1+n2+n3+n4+n5+n6+n7+n8)*0.125f;
VECTOR3Normalize(NORMAL_AT(x,z));
}
}
}
*/
float Landscape::getHeightAt(float x, float z) const
{
int x1 = static_cast<int>(x);
int x2 = x1 + 1;
int z1 = static_cast<int>(z);
int z2 = z1 + 1;
float topleft = getHeightAt(x1, z1);
float topright = getHeightAt(x2, z1);
float bottomleft = getHeightAt(x1, z2);
float bottomright = getHeightAt(x2, z2);
float tmp1 = (x2 - x) / (x2 - x1);
float tmp2 = (x - x1) / (x2 - x1);
float interpolatedHeight1 = tmp1*topleft +
tmp2*topright;
float interpolatedHeight2 = tmp1*bottomleft +
tmp2*bottomright;
return (z2 - z) / (z2 - z1)*interpolatedHeight1 +
(z - z1) / (z2 - z1)*interpolatedHeight2;
}
|
#include "bmp.h"
#include <iostream>
#include <cassert>
#include <fstream>
#include <cstring>
using namespace std;
//*** Auxilliary functions ***********************************
int negativeToZero(int x){
return x < 0 ? 0 : x;
}
namespace JiMP2 {
//************************************************************
void BMP::projectObjXY(const Obj &object,
unsigned char r, unsigned char g, unsigned char b){
// Adjust image scaling.
const AABB &aabb = object.getAABB();
double scale_x = getWidth() / (double)(aabb.x_max - aabb.x_min);
double scale_y = getHeight() / (double)(aabb.y_max - aabb.y_min);
double scale = std::min(scale_x, scale_y);
// Translate the camera.
float dx = -aabb.x_min,
dy = -aabb.y_min;
// Draw each triangle.
for(index_t i = 0; i != object.numberOfFaces(); ++i){
Point3 points[3]{
object.getVertexOfFace(i, 0),
object.getVertexOfFace(i, 1),
object.getVertexOfFace(i, 2)
};
// Draw a triangle.
for(int i = 0; i != 3; ++i){
int x0 = scale*(points[i%3].getX() + dx),
y0 = scale*(points[i%3].getY() + dy),
x1 = scale*(points[(i+1)%3].getX() + dx),
y1 = scale*(points[(i+1)%3].getY() + dy);
drawLine(
(uint16_t)negativeToZero(x0),
(uint16_t)negativeToZero(y0),
(uint16_t)negativeToZero(x1),
(uint16_t)negativeToZero(y1),
r, g, b
);
}
}
}
//************************************************************
void BMP::projectObjXZ(const Obj &object,
unsigned char r, unsigned char g, unsigned char b){
// Adjust image scaling.
const AABB &aabb = object.getAABB();
double scale_x = getWidth() / (double)(aabb.x_max - aabb.x_min);
double scale_z = getHeight() / (double)(aabb.z_max - aabb.z_min);
double scale = std::min(scale_x, scale_z);
// Translate a camera.
float dx = -aabb.x_min,
dz = -aabb.z_min;
// Draw each triangle.
for(index_t i = 0; i != object.numberOfFaces(); ++i){
Point3 points[3]{
object.getVertexOfFace(i, 0),
object.getVertexOfFace(i, 1),
object.getVertexOfFace(i, 2)
};
// Draw a triangle.
for(int i = 0; i != 3; ++i){
int x0 = scale*(points[i%3].getX() + dx),
z0 = scale*(points[i%3].getZ() + dz),
x1 = scale*(points[(i+1)%3].getX() + dx),
z1 = scale*(points[(i+1)%3].getZ() + dz);
drawLine(
(uint16_t)negativeToZero(x0),
(uint16_t)negativeToZero(z0),
(uint16_t)negativeToZero(x1),
(uint16_t)negativeToZero(z1),
r, g, b
);
}
}
}
//************************************************************
void BMP::projectObjYZ(const Obj &object,
unsigned char r, unsigned char g, unsigned char b){
// Adjust image scaling.
const AABB &aabb = object.getAABB();
double scale_y = getWidth() / (double)(aabb.y_max - aabb.y_min);
double scale_z = getHeight() / (double)(aabb.z_max - aabb.z_min);
double scale = std::min(scale_y, scale_z);
// Translate a camera.
float dy = -aabb.y_min,
dz = -aabb.z_min;
// Draw each triangle.
for(index_t i = 0; i != object.numberOfFaces(); ++i){
Point3 points[3]{
object.getVertexOfFace(i, 0),
object.getVertexOfFace(i, 1),
object.getVertexOfFace(i, 2)
};
// Draw a triangle.
for(int i = 0; i != 3; ++i){
int y0 = scale*(points[i%3].getY() + dy),
z0 = scale*(points[i%3].getZ() + dz),
y1 = scale*(points[(i+1)%3].getY() + dy),
z1 = scale*(points[(i+1)%3].getZ() + dz);
drawLine(
(uint16_t)negativeToZero(y0),
(uint16_t)negativeToZero(z0),
(uint16_t)negativeToZero(y1),
(uint16_t)negativeToZero(z1),
r, g, b
);
}
}
}
//************************************************************
BMP::BMP(uint16_t width, uint16_t height) :
bitmapCoreHeader(width, height) {
assert(IS_LITTLE_ENDIAN);
assert(width > 0);
assert(height > 0);
const unsigned int rowSize = ((bitmapCoreHeader.bitsPerPixel * width + 31)
/ 32) * 4;
const unsigned int imgSize = rowSize * height;
bmpFileHeader.size = 14 + bitmapCoreHeader.size + imgSize;
bmpFileHeader.dataOffset = 14 + bitmapCoreHeader.size;
pixelData = new unsigned char[imgSize];
std::memset(pixelData, 255, imgSize);
}
BMP::~BMP() {
delete[] pixelData;
}
void BMP::setPixel(uint16_t x, uint16_t y, unsigned char r, unsigned char g,
unsigned char b) {
assert(bitmapCoreHeader.bitsPerPixel == 24);
// Check if a pixel isn't outside a bitmap.
if(x >= getWidth() || y >= getHeight())
return;
const size_t rowSize = ((bitmapCoreHeader.bitsPerPixel
* bitmapCoreHeader.bmpWidth + 31) / 32) * 4;
const size_t offset = rowSize * (bitmapCoreHeader.bmpHeight - y)
+ x * (bitmapCoreHeader.bitsPerPixel / 8);
pixelData[offset + 0] = b;
pixelData[offset + 1] = g;
pixelData[offset + 2] = r;
}
void BMP::drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1,
unsigned char r, unsigned char g, unsigned char b){
int dx = abs(x1 - x0),
sx = x0 < x1 ? 1 : -1,
dy = -abs(y1 - y0),
sy = y0 < y1 ? 1 : -1;
int err = dx + dy,
e2;
while(true){
setPixel(x0, y0, r, g, b);
if(x0 == x1 && y0 == y1)
break;
e2 = 2*err;
if(e2 >= dy){
err += dy;
x0 += sx;
}
if(e2 <= dx){
err += dx;
y0 += sy;
}
}
}
std::ostream& operator<<(std::ostream& os, const BMP& bmp) {
os.write(bmp.bmpFileHeader.id, sizeof(bmp.bmpFileHeader.id));
os.write((const char*) &bmp.bmpFileHeader.size,
sizeof(bmp.bmpFileHeader.size));
os.write(bmp.bmpFileHeader.reserved, sizeof(bmp.bmpFileHeader.reserved));
os.write((const char*) &bmp.bmpFileHeader.dataOffset,
sizeof(bmp.bmpFileHeader.dataOffset));
os.write((const char*) &bmp.bitmapCoreHeader.size,
sizeof(bmp.bitmapCoreHeader.size));
os.write((const char*) &bmp.bitmapCoreHeader.bmpWidth,
sizeof(bmp.bitmapCoreHeader.bmpWidth));
os.write((const char*) &bmp.bitmapCoreHeader.bmpHeight,
sizeof(bmp.bitmapCoreHeader.bmpHeight));
os.write((const char*) &bmp.bitmapCoreHeader.colorPlanes,
sizeof(bmp.bitmapCoreHeader.colorPlanes));
os.write((const char*) &bmp.bitmapCoreHeader.bitsPerPixel,
sizeof(bmp.bitmapCoreHeader.bitsPerPixel));
const unsigned int rowSize = ((bmp.bitmapCoreHeader.bitsPerPixel
* bmp.bitmapCoreHeader.bmpWidth + 31) / 32) * 4;
const unsigned int imgSize = rowSize * bmp.bitmapCoreHeader.bmpHeight;
os.write((const char*) bmp.pixelData, imgSize);
return os;
}
}
|
#include "rat.h"
#include <iostream>
using namespace std;
int CRat::m_count = 0;
CRat::CRat() : m_id(0) {
m_id = m_count;
m_count++;
}
CRat::~CRat() {
cout << "ネズミ:" << m_id << "消去" << endl;
m_count--;
}
void CRat::showNum() {
cout << "現在のネズミの数は、" << m_count << "匹です。" << endl;
}
void CRat::squeak() {
cout << m_id << ":" << "チューチュー" << endl;
}
|
#include <sys/time.h>
#include <iostream>
using namespace std;
int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
// printf(result->tv_sec);
/* Return 1 if result is negative. */
return 0;
}
struct timeval t1, t2;
struct timezone tz;
void startTimer()
{
gettimeofday(&t1, &tz);
}
void stopTimer()
{
gettimeofday(&t2, &tz);
cout<<"It took "<< t2.tv_sec - t1.tv_sec <<" seconds and "<< t2.tv_usec - t1.tv_usec<<" microseconds"<<endl;;
}
// call "startTimer()" to start timer
// call "stopTimer()" to stop timer and print total time in microseconds.
|
#ifndef _GUARD_TIMER_H
#define _GUARD_TIMER_H
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "dbg.h"
#include "util.h"
#ifdef NTIMER
#define TIMER_CREATE(name)
#define TIMER_CREATE_WITH_PRECISION(name, precision)
#define TIMER_START(name)
#define TIMER_STOP(name)
#define TIMER_DUMP(name)
#else
namespace timer
{
class Timer
{
using count_type = unsigned long long;
public:
enum Precision { SECONDS, MILLISECONDS, MICROSECONDS };
enum { DECIMALS = 3 };
static bool enabled;
static std::ostream *out;
Timer(char const *name, Precision precision = SECONDS)
: _name(name),
_precision(precision),
_start(time())
{}
static bool exists(char const *name)
{ return _timers.find(name) != _timers.end(); }
static void create(char const *name, Precision precision = SECONDS)
{
if (!exists(name))
_timers.insert({name, Timer(name, precision)});
}
static void destroy(char const *name)
{ _timers.erase(find(name)); }
static Timer *get(char const *name)
{ return &find(name)->second; }
static std::vector<Timer *> get_all()
{
std::vector<Timer *> res;
for (auto &it : _timers)
res.push_back(&it.second);
return res;
}
void start()
{ _start = time(); }
void stop()
{
auto delta = time() - _start;
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(delta);
_meas.push_back(ns.count());
}
char const *name() const
{ return _name; }
char const *unit() const
{
switch (_precision) {
case SECONDS:
return "s";
case MILLISECONDS:
return "ms";
case MICROSECONDS:
return "us";
}
throw std::logic_error("unreachable");
}
std::vector<count_type>::size_type invoked() const
{ return _meas.size(); }
double total() const
{ return scale(std::accumulate(_meas.begin(), _meas.end(), 0ULL)); }
void mean_stddev(double *mean, double *stddev) const
{
count_type mean_, stddev_;
util::mean_stddev(_meas, &mean_, &stddev_);
*mean = scale(mean_);
*stddev = scale(stddev_);
}
private:
static std::map<std::string, Timer>::iterator find(char const *name)
{
auto it = _timers.find(name);
if (it == _timers.end())
throw std::logic_error("timer does not exist");
return it;
}
static std::chrono::high_resolution_clock::time_point time()
{ return std::chrono::high_resolution_clock::now(); }
double scale(count_type ns) const
{
double nsd = static_cast<double>(ns);
switch (_precision) {
case SECONDS:
return nsd / 1e9;
case MILLISECONDS:
return nsd / 1e6;
case MICROSECONDS:
return nsd / 1e3;
}
throw std::logic_error("unreachable");
}
char const *_name;
Precision _precision;
std::chrono::high_resolution_clock::time_point _start;
std::vector<count_type> _meas;
static std::map<std::string, Timer> _timers;
};
inline std::ostream &operator<<(std::ostream &s, Timer const &timer)
{
s << "TIMER (" << timer.name() << "): ";
if (timer.invoked() == 0) {
s << " never invoked";
} else {
s << std::setprecision(Timer::DECIMALS);
if (timer.invoked() == 1) {
s << timer.total() << timer.unit();
} else {
double mean, stddev;
timer.mean_stddev(&mean, &stddev);
s << "total: " << timer.total() << timer.unit()
<< " (" << timer.invoked() << " invokations)"
<< ", mean: " << mean << timer.unit()
<< ", stddev: " << stddev << timer.unit();
}
}
return s;
}
} // namespace timer
#define TIMER_ENABLE() do { timer::Timer::enabled = true; } while (0)
#define TIMER_GET_OUT() timer::Timer::out
#define TIMER_SET_OUT(os) do { timer::Timer::out = os; } while (0)
#define TIMER_OP(op) do { if (timer::Timer::enabled) { op; } } while (0)
#define TIMER_CREATE_WITH_PRECISION(name, precision) \
TIMER_OP(timer::Timer::create(name, precision))
#define TIMER_START(name) \
TIMER_OP(timer::Timer::create(name); timer::Timer::get(name)->start())
#define TIMER_STOP(name) \
TIMER_OP(timer::Timer::get(name)->stop())
#define TIMER_EXISTS(name) \
timer::Timer::exists(name)
#define TIMER_DUMP(name) \
TIMER_OP(*timer::Timer::out << *timer::Timer::get(name) << std::endl; \
timer::Timer::destroy(name))
#define TIMER_DUMP_ALL() \
TIMER_OP(for (auto *t : timer::Timer::get_all()) { \
*timer::Timer::out << *t << std::endl; \
timer::Timer::destroy(t->name()); \
})
#define TIMER_SECONDS timer::Timer::SECONDS
#define TIMER_MILLISECONDS timer::Timer::MILLISECONDS
#define TIMER_MICROSECONDS timer::Timer::MICROSECONDS
#endif
#endif // _GUARD_TIMER_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#ifndef __FL_BUFFER_H__
#define __FL_BUFFER_H__
/** Creates a binary array of the specified, hardcoded, length, and acesses it as a Byte Array*/
template <uint32 L>
class DataStream_LimitedBuffer : public DataStream_ByteArray
{
private:
byte buffer[L]; /* ARRAY OK 2009-05-25 yngve */
public:
DataStream_LimitedBuffer():DataStream_ByteArray(buffer, L){op_memset(buffer, 0, L);}
virtual ~DataStream_LimitedBuffer(){op_memset(buffer, 0, L);}
/** Array dereference, Access byte val directly read/write */
byte &operator[](uint32 val){return buffer[val < L ? val : 0];}
/** Array dereference, Access byte val, readonly */
byte operator[](uint32 val) const{return buffer[val < L ? val : 0];}
/** Assignment operator */
DataStream_LimitedBuffer &operator =(const DataStream_LimitedBuffer &src){op_memcpy(buffer, src.buffer, L); return *this;}
/** Copy the src buffer */
void Set(const byte *src){if(src) op_memcpy(buffer, src, L);}
#ifdef _DATASTREAM_DEBUG_
protected:
virtual const char *Debug_ClassName(){return "DataStream_LimitedBuffer";}
#endif
};
#endif // __FL_BUFFER_H__
|
#ifndef SMTSOLVER_H
#define SMTSOLVER_H
#include <utility>
#include <vector>
#include <map>
#include "SatCnf.h"
#include "SmtCnf.h"
struct SmtSatKernel {
std::map<std::pair<int, int>, int> to;
std::vector<std::pair<int, int>> from;
};
// generate a Sat formula and var i of the sat formula is the literal in the vector
std::pair<SmtSatKernel, SatCnf> gene(const SmtCnf& sc);
// decide if a list of literal or they opposed version is satisfiable.
// if it is satisfiable, the bool is true and vector are the equivalence classes
// if it is not, the bool is false and vector is the index of the literals that form a counter-example
std::pair<bool, std::vector<int>> decide(const SmtSatKernel& ker, std::vector<bool> vals);
// solve a SMT CNF
// empty vector if not satisfiable
std::vector<int> solve(const SmtCnf& sc, bool smtVerbose=false, bool satVerbose=false);
#endif
|
/****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#include "Graphics/D3D11Details.hpp"
#include "Diagnostics/Win32Exception.hpp"
#include <format>
#include <unordered_map>
namespace TG::Graphics
{
DXGI_FORMAT DirectXFormatMapping(TextureFormat format)
{
static std::unordered_map<TextureFormat, DXGI_FORMAT> map =
{
{TextureFormat::R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM},
};
return map[format];
}
Device<DeviceType::DirectX11>::Device()
{
CheckHResult(CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)));
RetrieveHardwareInfo();
CreateDeviceAndContext();
}
std::vector<DXGI_MODE_DESC1> Device<DeviceType::DirectX11>::GetOutputModes(DXGI_FORMAT format)
{
ComPtr<IDXGIOutput1> pOutput1;
CheckHResult(dxgiOutputs[0][0].As(&pOutput1));
DXGI_OUTPUT_DESC outputDesc;
CheckHResult(pOutput1->GetDesc(&outputDesc));
Debug::LogLine(std::format(L"Device name: {}", outputDesc.DeviceName));
UINT modeCount = 0;
CheckHResult(pOutput1->GetDisplayModeList1(format, DXGI_ENUM_MODES_SCALING, &modeCount, nullptr));
std::vector<DXGI_MODE_DESC1> outputModes(modeCount);
if (modeCount > 0)
{
CheckHResult(pOutput1->GetDisplayModeList1(format, DXGI_ENUM_MODES_SCALING,
&modeCount, outputModes.data()));
for (UINT i = 0; i < modeCount; ++i)
{
Debug::LogLine(std::format(L"Width: {} Height: {} Format: {} Refresh rate denominator: {} numerator: {}",
outputModes[i].Width, outputModes[i].Height,
(UINT)(outputModes[i].Format),
outputModes[i].RefreshRate.Denominator,
outputModes[i].RefreshRate.Numerator));
}
}
return outputModes;
}
void Device<DeviceType::DirectX11>::RetrieveHardwareInfo()
{
// 枚举所有显示适配器及其输出
ComPtr<IDXGIAdapter> pAdapter;
for (UINT i = 0; dxgiFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND; ++i)
{
dxgiAdapters.push_back(pAdapter);
DXGI_ADAPTER_DESC desc;
pAdapter->GetDesc(&desc);
Debug::LogLine(std::format(L"Adpater vendor: {}. Video memory size: {} MB",
desc.Description, desc.DedicatedVideoMemory / 1048576));
std::vector<ComPtr<IDXGIOutput>> outputs;
ComPtr<IDXGIOutput> pOutput;
for (UINT j = 0; pAdapter->EnumOutputs(j, &pOutput) != DXGI_ERROR_NOT_FOUND; ++j)
outputs.push_back(pOutput);
dxgiOutputs.push_back(outputs);
}
}
void Device<DeviceType::DirectX11>::CreateDeviceAndContext()
{
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
};
CheckHResult(D3D11CreateDevice(dxgiAdapters[0].Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, creationFlags,
featureLevels, 2, D3D11_SDK_VERSION, &d3dDevice, nullptr, &d3dContext));
}
Context<DeviceType::DirectX11>::Context(const std::shared_ptr<Device<DeviceType::DirectX11>>& device)
{
if (!device)
throw BaseException(L"'device' can not be null");
d3dContext.Swap(device->d3dContext);
}
void Context<DeviceType::DirectX11>::ClearFrameBuffer(const std::shared_ptr<FrameBuffer<DeviceType::DirectX11>>& frameBuffer,
const Math::Color& color)
{
if (frameBuffer)
d3dContext->ClearRenderTargetView(frameBuffer->renderTargetView.Get(), color.RGBA());
}
FrameBuffer<DeviceType::DirectX11>::FrameBuffer(const std::shared_ptr<Device<DeviceType::DirectX11>>& device,
const std::shared_ptr<Window>& window)
: window(window)
{
if (!device || !window)
throw BaseException(L"'device' and/or 'window' can not be null");
CheckHResult(device->d3dDevice->CheckMultisampleQualityLevels(backBufferFormat, sampleCount,
&numQualityLevels));
outputModes = device->GetOutputModes(backBufferFormat);
refreshRate = outputModes[0].RefreshRate;
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.BufferDesc.Width = window->Width();
swapChainDesc.BufferDesc.Height = window->Height();
swapChainDesc.BufferDesc.Format = backBufferFormat;
swapChainDesc.BufferDesc.RefreshRate = refreshRate;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.SampleDesc.Count = sampleCount;
swapChainDesc.SampleDesc.Quality = numQualityLevels - 1;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 1;
swapChainDesc.OutputWindow = window->Hwnd();
swapChainDesc.Windowed = true;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
CheckHResult(device->dxgiFactory->CreateSwapChain(device->d3dDevice.Get(), &swapChainDesc, &swapChain));
ComPtr<ID3D11Resource> pBackBuffer;
CheckHResult(swapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)));
CheckHResult(device->d3dDevice->CreateRenderTargetView(
pBackBuffer.Get(),
nullptr,
&renderTargetView
));
}
void FrameBuffer<DeviceType::DirectX11>::Present()
{
CheckHResult(swapChain->Present(1u, 0u));
}
#ifdef _DEBUG
DebugInfo<DeviceType::DirectX11>::DebugInfo()
{
module = GetModuleHandleW(L"dxgidebug.dll");
if (nullptr == module)
CheckLastError(L"Can not load dxgidebug.dll");
DxgiGetDebugInterface = reinterpret_cast<DXGIGetDebugInterface>(
GetProcAddress(module, "DXGIGetDebugInterface"));
if (nullptr == DxgiGetDebugInterface)
CheckLastError(L"Can not find DXGIGetDebugInterface function procedure address");
CheckHResult(DxgiGetDebugInterface(IID_PPV_ARGS(&dxgiDebug)));
CheckHResult(DxgiGetDebugInterface(IID_PPV_ARGS(&dxgiInfoQueue)));
next = 0;
}
DebugInfo<DeviceType::DirectX11>::~DebugInfo()
{
const auto end = dxgiInfoQueue->GetNumStoredMessages(DXGI_DEBUG_ALL);
while (next < end)
{
HRESULT hr;
SIZE_T messageLength;
hr = dxgiInfoQueue->GetMessage(DXGI_DEBUG_ALL, next, nullptr, &messageLength);
if (hr == S_OK)
{
DXGI_INFO_QUEUE_MESSAGE* pMessage = (DXGI_INFO_QUEUE_MESSAGE*)malloc(messageLength);
hr = dxgiInfoQueue->GetMessage(DXGI_DEBUG_ALL, next, pMessage, &messageLength);
if (hr == S_OK)
Debug::Log(std::format("{}\n", pMessage->pDescription));
free(pMessage);
}
next++;
}
}
void DebugInfo<DeviceType::DirectX11>::ReportLiveObjects()
{
dxgiDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL);
}
void DebugInfo<DeviceType::DirectX11>::OutputMessages()
{
const auto end = dxgiInfoQueue->GetNumStoredMessages(DXGI_DEBUG_ALL);
while (next < end)
{
SIZE_T messageLength;
CheckHResult(dxgiInfoQueue->GetMessage(DXGI_DEBUG_ALL, next, nullptr, &messageLength));
DXGI_INFO_QUEUE_MESSAGE* pMessage = (DXGI_INFO_QUEUE_MESSAGE*)malloc(messageLength);
CheckHResult(dxgiInfoQueue->GetMessage(DXGI_DEBUG_ALL, next++, pMessage, &messageLength));
Debug::Log(std::format("{}\n", pMessage->pDescription));
free(pMessage);
}
}
#endif
}
|
#ifndef TP_PPROJECT_COMMANDHANDLER_H
#define TP_PPROJECT_COMMANDHANDLER_H
#include <iostream>
#include <functional>
#include <boost/property_tree/ini_parser.hpp>
#include "src/server/lib/CompanyServer/MainServerLogic/MainLogic/MainLogic.h"
#include "src/server/lib/Connection/BaseConnection.h"
#include "src/server/lib/Connection/Connection.h"
#include "src/server/lib/CompanyServer/MainServerLogic/CommandCreator/CommandCreator.h"
/*
* The class responsible for the execution of the received query
*/
class CommandHandler {
public:
CommandHandler();
~CommandHandler() = default;
/*
* Executing a client request
*/
void runRequest(const std::shared_ptr<Connection>& connection, std::string &message);
private:
CommandCreator parser;
MainLogic mainLogic;
};
#endif
|
#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
static int slices = 25;
static int stacks = 17;
/* GLUT callback Handlers */
static void resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
}
static void display(void)
{
const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
const double a = t*90.0;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLUquadricObj *pObj;
glColor3d(1,0.9,0.39);
glPushMatrix();
pObj = gluNewQuadric();
gluQuadricNormals(pObj, GLU_SMOOTH);
glTranslatef(0.0f, 0.0f, -5.0f);
glRotated(-5,1,0,0);
//glutSolidSphere(0.6,slices,stacks);
glPushMatrix();
glTranslatef(0.0f, 0.8f, 0.0f);
gluSphere(pObj, 0.6, 26, 13);
glTranslatef(0.0f, -0.8f, 0.0f);
glRotated(-90, 1, 0, 0);
gluCylinder(pObj, 0.3, 0.51, 0.5, 26, 13);
glPopMatrix();
glPushMatrix();
glRotated(-90, 1, 0, 0);
glTranslatef(0.0f, 0.0f, 0.15f);
glColor3d(0.8, 0.8, 0.8);
glutSolidTorus(0.1, 0.3, 26, 13);
glTranslatef(0.0f, 0.0f, -0.06f);
glutSolidTorus(0.1, 0.3, 26, 13);
glTranslatef(0.0f, 0.0f, -0.06f);
glutSolidTorus(0.1, 0.3, 26, 13);
glTranslatef(0.0f, 0.0f, -0.06f);
glutSolidTorus(0.1, 0.3, 26, 13);
glTranslatef(0.0f, 0.0f, -0.06f);
glutSolidTorus(0.1, 0.3, 26, 13);
glTranslatef(0.0f, 0.0f, -0.06f);
glutSolidTorus(0.1, 0.3, 26, 13);
glColor3d(0, 0, 0);
glTranslatef(0.0f, 0.0f, -0.06f);
glutSolidTorus(0.1, 0.1, 26, 13);
glTranslatef(0.0f, 0.0f, -0.06f);
glutSolidTorus(0.1, 0.1, 26, 13);
glPopMatrix();
glPopMatrix();
glutSwapBuffers();
}
static void idle(void)
{
glutPostRedisplay();
}
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
/* Program entry point */
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(840,580);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("GLUT Shapes");
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutIdleFunc(idle);
glClearColor(1,1,1,1);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glutMainLoop();
return EXIT_SUCCESS;
}
|
#include "_pch.h"
#include "ModelDetail.h"
using namespace wh;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
ModelObjDetail::ModelObjDetail()
{
}
//---------------------------------------------------------------------------
void ModelObjDetail::Load()
{
wxString query = wxString::Format(
"SELECT cls.id, cls.title, cls.kind, cls.measure "
" , o.id, o.title "
" FROM obj o "
" RIGHT JOIN acls cls ON cls.id = o.cls_id "
" WHERE o.id = %s "
, mObjInfo.mObj.mId.toStr());
whDataMgr::GetDB().BeginTransaction();
auto table = whDataMgr::GetDB().ExecWithResultsSPtr(query);
if (table && table->GetRowCount())
{
mObjInfo.mCls.mId = table->GetAsString(0, 0);
mObjInfo.mCls.mLabel = table->GetAsString(1, 0);
mObjInfo.mCls.mType = table->GetAsString(2, 0);
mObjInfo.mCls.mMeasure = table->GetAsString(3, 0);
//mObjInfo.mObj.mId = table->GetAsString(4, 0);
mObjInfo.mObj.mLabel = table->GetAsString(5, 0);
}
query = wxString::Format(
"SELECT o.qty, o.pid, get_path_obj(o.pid, 1) "
" FROM obj o "
" WHERE o.id = %s "
, mObjInfo.mObj.mId.toStr());
if (mObjInfo.mCls.IsQuantity())
query += wxString::Format("AND o.pid = %s", mObjInfo.mObj.mParent.mId.toStr());
table = whDataMgr::GetDB().ExecWithResultsSPtr(query);
if (table && table->GetRowCount())
{
mObjInfo.mObj.mQty = table->GetAsString(0, 0);
mObjInfo.mObj.mParent.mId = table->GetAsString(1, 0);
//mObjInfo.mObj.mPath = table->GetAsString(2, 0);
}
whDataMgr::GetDB().Commit();
sigObjDetailUpdated(mObjInfo);
}
//---------------------------------------------------------------------------
const rec::ObjInfo& ModelObjDetail::Get()const
{
return mObjInfo;
}
//---------------------------------------------------------------------------
void ModelObjDetail::Set(const wxString& oid, const wxString& parent_oid)
{
mObjInfo.mObj.mId = oid;
mObjInfo.mObj.mParent.mId = parent_oid;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
ModelPageDetail::ModelPageDetail(const std::shared_ptr<rec::ObjInfo>& oi
, const std::shared_ptr<rec::PageHistory>& data)
{
// Сохраняем идентификатор и местоположение
//mObjInfo = *oi;
mModelObjDetail = std::make_shared<ModelObjDetail>();
mModelObjDetail->Set(oi->mObj.mId, oi->mObj.mParent.mId);
connModel_ObjDetailUpdated = mModelObjDetail->sigObjDetailUpdated
.connect([this](const rec::ObjInfo& rt)
{
UpdateTitle();
});
// настройки окна истории
auto cfg = std::make_shared<rec::PageHistory>(*data);
cfg->mVisibleColumnClsObj = false;
mModelPageHistory = std::make_shared<ModelPageHistory>(cfg);
// настройки фильтров
auto filter_list = mModelPageHistory->GetModelHistory().GetFilterList();
std::vector<ModelFilterList::NotyfyItem> nv(2);
std::shared_ptr<const ModelFilter> null_filter;
bool visible = false;
std::vector<wxString> val(1);
auto fobj = std::make_shared<ModelFilter>("Объект(Oid)", "mobj_id", FilterOp::foEq, ftLong, visible);
val[0] = oi->mObj.mId;// "3811";
fobj->SetValue(val);
auto oid_filter = std::shared_ptr<const ModelFilter>(fobj);
nv.emplace_back(ModelFilterList::NotyfyItem(null_filter, oid_filter));
nv.emplace_back(ModelFilterList::NotyfyItem(filter_list->FindBySysName("mcls_title"), null_filter));
nv.emplace_back(ModelFilterList::NotyfyItem(filter_list->FindBySysName("mobj_title"), null_filter));
filter_list->Update(nv);
}
//---------------------------------------------------------------------------
//virtual
void ModelPageDetail::UpdateTitle() //override;
{
const rec::ObjInfo& oi = mModelObjDetail->Get();
const wxString lbl = wxString::Format("[%s]%s (%s %s)"
, oi.mCls.mLabel.toStr()
, oi.mObj.mLabel.toStr()
, oi.mObj.mQty.toStr()
, oi.mCls.mMeasure.toStr()
);
const wxIcon* ico(&wxNullIcon);
if (!oi.mCls.mType.IsNull())
switch (oi.mCls.GetClsType())
{
default:
ico = &ResMgr::GetInstance()->m_ico_type_abstract24;
break;
case wh::ClsKind::QtyByFloat: case wh::ClsKind::QtyByOne:
ico = &ResMgr::GetInstance()->m_ico_obj_qty24;
break;
case wh::ClsKind::Single:
ico = &ResMgr::GetInstance()->m_ico_obj_num24;
break;
}//switch
sigUpdateTitle(lbl, *ico);
}
//---------------------------------------------------------------------------
//virtual
void ModelPageDetail::Init()//override
{
mModelObjDetail->Load();
const rec::ObjInfo& oi = mModelObjDetail->Get();
auto filter_list = mModelPageHistory->GetModelHistory().GetFilterList();
filter_list->UpdateFilter("mobj_id", oi.mObj.mId.toStr());
filter_list->Apply();
}
//---------------------------------------------------------------------------
//virtual
void ModelPageDetail::Load(const boost::property_tree::wptree& page_val)//override;
{
using ptree = boost::property_tree::wptree;
auto it = page_val.find(L"CtrlPageDetail");//CtrlPageHistory
if (page_val.not_found() != it)
{
mModelPageHistory->Load(it->second);
}
const wxString oid = page_val.get<std::wstring>(L"CtrlPageDetail.Oid");
const wxString parent_oid = page_val.get<std::wstring>(L"CtrlPageDetail.parentOid");
mModelObjDetail->Set(oid, parent_oid);
/////Update();
}
//---------------------------------------------------------------------------
//virtual
void ModelPageDetail::Save(boost::property_tree::wptree& page_val)//override;
{
using ptree = boost::property_tree::wptree;
ptree content;
mModelPageHistory->Save(content);
const rec::ObjInfo& obj = mModelObjDetail->Get();
content.put(L"Oid", obj.mObj.mId.toStr().wc_str());
content.put(L"parentOid", obj.mObj.mParent.mId.toStr().wc_str());
page_val.push_back(std::make_pair(L"CtrlPageDetail", content));
}
|
#pragma once
#include <vector>
#include <utility>
#include <iostream>
#include <variant>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libswscale/swscale.h>
}
#include "ffmpeg-common.hpp"
constexpr size_t BUFFER_SIZE = 8194;
struct Upload : public Common {
Upload() {
m_io_context = avio_alloc_context(
reinterpret_cast<uint8_t*>(av_malloc(BUFFER_SIZE)),
BUFFER_SIZE,
0,
this,
nullptr,
[](void* handler, uint8_t* buf, int buf_size) {
return reinterpret_cast<Upload*>(handler)->write_packet(buf, buf_size);
},
nullptr
);
if (avformat_alloc_output_context2(&m_format_context, nullptr, "mpeg", nullptr) < 0) {
throw std::runtime_error("Could not allocate context");
}
m_format_context->pb = m_io_context;
m_format_context->flags |= AVFMT_FLAG_CUSTOM_IO;
}
int write_packet(uint8_t* buffer, size_t buf_size) {
auto target = m_data.end();
m_data.resize(m_data.size() + buf_size);
std::copy(buffer, buffer + buf_size, target);
return buf_size;
}
};
|
//
// PostEffect.cpp
// Odin.MacOSX
//
// Created by Daniel on 24/10/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#include "PostEffect.h"
namespace odin
{
namespace render
{
PostEffect::PostEffect() :
m_fsQuad()
{
}
PostEffect::~PostEffect()
{
}
void PostEffect::apply(const RenderTexture& input, const RenderTarget& output)
{
UI32 offscreenTex = input.getColorAttachment();
render::lib::activeTexture(ODIN_TEXTURE0);
render::lib::bindTexture(ODIN_TEXTURE_2D, offscreenTex);
m_fsQuad.draw(m_renderStates);
}
void PostEffect::setRenderStates(const RenderStates& states)
{
m_renderStates = states;
}
}
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b>>c;
int d=__gcd(a,b);
int e=a*b/d;
d=__gcd(e,c);
int ans=e*c/d;
cout<<ans;
return 0;
}
|
#include <opencv2\imgproc.hpp>
#include "Paints.h"
#include <opencv2\imgcodecs.hpp>
void alphaBlend( cv::Mat& foreground, cv::Mat& background, cv::Mat& outImage )
{
// 计算像素数量
int numberOfPixels = foreground.rows * foreground.cols;
float sb;
float db;
// Get floating point pointers to the data matrices
byte* fptr = foreground.data;
byte* bptr = background.data;
//float* aptr = reinterpret_cast<float*>(alpha.data);
byte* outImagePtr = outImage.data;
// 一次性循环所有像素
for ( int i = 0; i < numberOfPixels; i++ )
{
sb = (float)fptr[3] / 255.0f;
db = 1.0f - sb;
outImagePtr[0] = ((float)fptr[0] * sb + (float)bptr[0] * db);
outImagePtr[1] = ((float)fptr[1] * sb + (float)bptr[1] * db);
outImagePtr[2] = ((float)fptr[2] * sb + (float)bptr[2] * db);
outImagePtr[3] = ((float)fptr[3] * sb + (float)bptr[3] * db);
fptr += 4;
bptr += 4;
outImagePtr += 4;
//*outImagePtr = (*fptr) * (*aptr) + (*bptr) * (1 - *aptr);
}
cv::imwrite( "./Images/Result.png", outImage );
}
void iberbar::Poster::SafeDrawMat( cv::Mat matSrc, cv::Mat matDest, const CRect2i& rcDest, const CColor4B* color )
{
cv::Size srcSize = matSrc.size();
SafeDrawMat( matSrc, CRect2i( 0, 0, srcSize.width, srcSize.height ), matDest, rcDest, color );
}
void iberbar::Poster::SafeDrawMat( cv::Mat matSrc, const CRect2i& srcRect, cv::Mat matDest, const CRect2i& destRect, const CColor4B* color )
{
if ( color != nullptr && color->a == 0 )
return;
cv::Size destSizeMax = matDest.size();
cv::Size srcSizeMax = matSrc.size();
if ( destRect.l > destSizeMax.width ||
destRect.t > destSizeMax.height ||
destRect.r < 0 ||
destRect.b < 0 )
return;
if ( srcRect.l > srcSizeMax.width ||
srcRect.t > srcSizeMax.height ||
srcRect.r < 0 ||
srcRect.b < 0 )
return;
CRect2i destRectNew = destRect;
CRect2i srcRectNew = srcRect;
cv::Size srcSize( srcRect.Width(), srcRect.Height() );
cv::Size destSize( destRect.Width(), destRect.Height() );
if ( destRect.l < 0 )
{
destRectNew.l = 0;
srcRectNew.l = srcRect.l + (0 - destRect.l) * srcSize.width / destSize.width;
}
if ( destRect.t < 0 )
{
destRectNew.t = 0;
srcRectNew.t = srcRect.t + (0 - destRect.t) * srcSize.height / destSize.height;
}
if ( destRect.r > destSizeMax.width )
{
destRectNew.r = destSizeMax.width;
srcRectNew.r = srcRect.r - (destRect.r - destSizeMax.width) * srcSize.width / destSize.width;
}
if ( destRect.b > destSizeMax.height )
{
destRectNew.b = destSizeMax.height;
srcRectNew.b = srcRect.b - (destRect.t - destSizeMax.height) * srcSize.height / destSize.height;
}
cv::Size srcSizeNew( srcRect.Width(), srcRect.Height() );
cv::Size destSizeNew( destRectNew.Width(), destRectNew.Height() );
cv::Mat matSrcNew = cv::Mat( matSrc, ToCvRect( srcRectNew ) );
if ( srcSizeNew.width == destSizeNew.width && srcSizeNew.height == destSizeNew.height )
{
}
else
{
cv::resize( matSrcNew, matSrcNew, destSizeNew );
}
float sb;
float db;
byte* fptr = matSrcNew.data;
byte* bptr = matDest.data;
//const byte* optr = (const byte*)color;
// 一次性循环所有像素
if ( color == nullptr )
{
for ( int i = 0; i < matSrcNew.rows; i++ )
{
bptr = matDest.data + (matDest.cols * (i + destRect.t) + destRect.l) * 4;
for ( int j = 0; j < matSrcNew.cols; j++ )
{
sb = (float)fptr[3] / 255.0f;
db = 1.0f - sb;
bptr[0] = ((float)fptr[0] * sb + (float)bptr[0] * db);
bptr[1] = ((float)fptr[1] * sb + (float)bptr[1] * db);
bptr[2] = ((float)fptr[2] * sb + (float)bptr[2] * db);
bptr[3] = ((float)fptr[3] * sb + (float)bptr[3] * db);
fptr += 4;
bptr += 4;
}
}
}
else
{
float pixel[4];
CColor4F color4f( *color );
for ( int i = 0; i < matSrcNew.rows; i++ )
{
bptr = matDest.data + (matDest.cols * (i + destRect.t) + destRect.l) * 4;
for ( int j = 0; j < matSrcNew.cols; j++ )
{
sb = (float)fptr[3] / 255.0f;
db = 1.0f - sb;
pixel[0] = (float)fptr[0] * color4f.b;
pixel[1] = (float)fptr[1] * color4f.g;
pixel[2] = (float)fptr[2] * color4f.r;
pixel[3] = (float)fptr[3] * color4f.a;
bptr[0] = ((float)pixel[0] * sb + (float)bptr[0] * db);
bptr[1] = ((float)pixel[1] * sb + (float)bptr[1] * db);
bptr[2] = ((float)pixel[2] * sb + (float)bptr[2] * db);
bptr[3] = ((float)pixel[3] * sb + (float)bptr[3] * db);
fptr += 4;
bptr += 4;
}
}
}
//alphaBlend( matSrcNew, matDestNew, matDestNew );
//cv::add( matSrcNew, matDestNew, matDestNew );
//cv::addWeighted( matDestNew, 1, matSrcNew, 1, 0, matDestNew );
//matDestNew = matSrcNew + matDestNew;
}
//void iberbar::Poster::SafeDrawMatInCircle( cv::Mat matSrc, cv::Mat matDest, const UPoint& pt, int radius )
//{
// cv::Mat matCircle = cv::Mat( cv::Size( radius, radius ), CV_8UC3 );
// cv::circle( matCircle, pt, radius, cv::Scalar( 0xff, 0xff, 0xff, 0xff ), -1 );
// matSrc.copyTo( , matCircle );
//
// cv::addWeighted( matCircle, 1, matSrc, 1, 0, matDest );
//}
cv::Mat iberbar::Poster::BuildMaskMat_Circle( int radius )
{
int w = radius << 1;
cv::Mat matCircle = cv::Mat::zeros( cv::Size( w, w ), CV_8U );
cv::circle( matCircle, cv::Point( radius, radius ), radius, cv::Scalar( 0xff, 0xff, 0xff, 0xff ), -1 );
return matCircle;
}
cv::Mat iberbar::Poster::BuildMaskMat_RectangleWithCorners( const CSize2i& size, int cornerRadius )
{
cv::Scalar color( 0xff, 0xff, 0xff, 0xff );
int deameter = cornerRadius << 1;
cv::Mat matMask = cv::Mat::zeros( ToCvSize( size ), CV_8U );
//cv::circle( matMask, cv::Point( cornerRadius, cornerRadius ), cornerRadius, cv::Scalar( 0xff, 0xff, 0xff, 0xff ), -1 );
cv::Rect rc2[2] = {
cv::Rect( cv::Point( cornerRadius, 0 ), cv::Size( size.w - deameter, size.h ) ),
cv::Rect( cv::Point( 0, cornerRadius ), cv::Size( size.w, size.h - deameter ) )
};
cv::rectangle( matMask, rc2[0], color, -1 );
cv::rectangle( matMask, rc2[1], color, -1 );
cv::Mat matCircle = cv::Mat::zeros( cv::Size( deameter, deameter ), CV_8U );
cv::circle( matCircle, cv::Point( cornerRadius, cornerRadius ), cornerRadius, cv::Scalar( 0xff, 0xff, 0xff, 0xff ), -1 );
cv::Mat matCornerSrc;
cv::Mat matCornerDest;
cv::Size cornerSize = cv::Size( cornerRadius, cornerRadius );
matCornerSrc = cv::Mat( matCircle, cv::Rect( cv::Point( 0, 0 ), cornerSize ) );
matCornerDest = cv::Mat( matMask, cv::Rect( cv::Point( 0, 0 ), cornerSize ) );
matCornerSrc.copyTo( matCornerDest );
matCornerSrc = cv::Mat( matCircle, cv::Rect( cv::Point( cornerRadius, 0 ), cornerSize ) );
matCornerDest = cv::Mat( matMask, cv::Rect( cv::Point( size.w - cornerRadius, 0 ), cornerSize ) );
matCornerSrc.copyTo( matCornerDest );
matCornerSrc = cv::Mat( matCircle, cv::Rect( cv::Point( cornerRadius, cornerRadius ), cornerSize ) );
matCornerDest = cv::Mat( matMask, cv::Rect( cv::Point( size.w - cornerRadius, size.h - cornerRadius ), cornerSize ) );
matCornerSrc.copyTo( matCornerDest );
matCornerSrc = cv::Mat( matCircle, cv::Rect( cv::Point( 0, cornerRadius ), cornerSize ) );
matCornerDest = cv::Mat( matMask, cv::Rect( cv::Point( 0, size.h - cornerRadius ), cornerSize ) );
matCornerSrc.copyTo( matCornerDest );
return matMask;
}
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
LL c[111][111];
LL C(int x, int y) {
for (int i = 0; i <=x ; i++) {
c[i][0] = 1;
for (int j = 1; j <= i; j++) c[i][j] = c[i-1][j] + c[i-1][j-1];
}
return c[x][y];
}
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
int x1, y1, x2, y2;
cin >> x1 >> x2 >> y1 >> y2;
cout << C(x1, y1) * C(x2, y2) << endl;
return 0;
}
|
// Copyright Low Entry. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "ELowEntryFileManagerYesNo.h"
#include "LowEntryFileManagerLibrary.generated.h"
class ULowEntryFileManagerDirectory;
class ULowEntryFileManagerFile;
UCLASS()
class LOWENTRYFILEMANAGER_API ULowEntryFileManagerLibrary : public UBlueprintFunctionLibrary
{
GENERATED_UCLASS_BODY()
public:
/**
* Returns the directory pointing to the root of UE4's file system.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Static", Meta = (DisplayName = "Get Root"))
static ULowEntryFileManagerDirectory* GetRoot();
/**
* Returns the directory pointing to the root of systems file system (so "/" for Unix and Mac and such, and "Computer:/" for Windows).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Static", Meta = (DisplayName = "Get Absolute Root"))
static ULowEntryFileManagerDirectory* GetAbsoluteRoot();
/**
* Returns the directory pointing to the given Path, the given Path can be relative, it will be relative to the root of UE4's file system then.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Static", Meta = (DisplayName = "Get Directory"))
static ULowEntryFileManagerDirectory* GetDirectory(const FString& Path);
/**
* Returns the disks of the filesystem (like "C:/", "D:/", etc) (only works for systems that have disks like that, such as Windows devices)
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|High Level|Static", Meta = (DisplayName = "Get Disks", Keywords = "harddrives"))
static TArray<ULowEntryFileManagerDirectory*> GetDisks();
public:
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Project Dir Path"))
static FString GetGameDirPath();
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Engine Dir Path"))
static FString GetEngineDirPath();
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Root Dir Path"))
static FString GetRootDirPath();
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Cloud Dir Path"))
static FString GetCloudDirPath();
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Project Persistant Download Dir Path"))
static FString GetGamePersistentDownloadDirPath();
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Project Saved Dir Path"))
static FString GetGameSavedDirPath();
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Engine Saved Dir Path"))
static FString GetEngineSavedDirPath();
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Project User Dir Path"))
static FString GetGameUserDirPath();
/**
* Returns a path of a certain file or directory (internal UE4 function).
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Project File Path"))
static FString GetProjectFilePath();
/**
* Returns the disk paths of the filesystem (like "C:/", "D:/", etc) (only works for systems that have disks like that, such as Windows devices)
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Get Disk Paths", Keywords = "harddrives"))
static TArray<FString> GetDiskPaths();
/**
* Returns true if a disk path of the filesystem (like "C:/", "D:/", etc) exists, will only return true for systems that have disks like that, such as Windows devices.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Has Disk Paths (Boolean)", Keywords = "harddrives"))
static bool HasDiskPathsBool();
/**
* Returns true if a file exists on the given path.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Utilities|Paths", Meta = (DisplayName = "Has Disk Paths", ExpandEnumAsExecs = "Branch"))
static void HasDiskPaths(ELowEntryFileManagerYesNo& Branch);
static bool IsDiskPath(const FString& Path);
static bool StartsWithDiskPath(const FString& Path);
public:
static FString RemoveCharactersExcept(const FString& String, const bool KeepLowercaseAZ, const bool KeepUppercaseAZ, const bool KeepNumbers, const FString& OtherCharactersToKeep);
static FString ReplaceCharactersExcept(const FString& String, const FString& ReplacementCharacter, const bool KeepLowercaseAZ, const bool KeepUppercaseAZ, const bool KeepNumbers, const FString& OtherCharactersToKeep);
/**
* Removes all characters except a-z, A-Z, 0-9, ".", "-", "_", " "
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Purge", Meta = (DisplayName = "Remove invalid filename characters"))
static FString RemoveInvalidFilenameCharacters(const FString& String);
/**
* Replaces all characters except a-z, A-Z, 0-9, ".", "-", "_", " "
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Purge", Meta = (DisplayName = "Replace invalid filename characters"))
static FString ReplaceInvalidFilenameCharacters(const FString& String, const FString& ReplacementCharacter = TEXT("-"));
/**
* Removes all characters except a-z, A-Z, 0-9, ".", "-", "_", " ", "/", "\"
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Purge", Meta = (DisplayName = "Remove invalid path characters"))
static FString RemoveInvalidPathCharacters(const FString& String);
/**
* Replaces all characters except a-z, A-Z, 0-9, ".", "-", "_", " ", "/", "\"
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Purge", Meta = (DisplayName = "Replace invalid path characters"))
static FString ReplaceInvalidPathCharacters(const FString& String, const FString& ReplacementCharacter = TEXT("-"));
/**
* Replaces all "\" by "/"
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Utilities|Purge", Meta = (DisplayName = "Convert backslashes to slashes"))
static FString ReplaceBackslashesBySlashes(const FString& String);
public:
/**
* Splits the path in 2 things: the path of the parent directory, and the name of the file or directory of the path.
*
* This blueprint is useful to get the parent path and the name of the given path.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Other", Meta = (DisplayName = "Split Path"))
static void SplitPath(const FString& Path, FString& PathPart, FString& NamePart);
/**
* Splits the (file)name in 2 things: the actual name, and the extension.
*
* Will return an empty ExtensionPart string if there is no dot (".") in the given Name.
* Multiple dots in the given Name will result in dots in the NamePart, since the split will only happen at the last dot.
*
* This blueprint is useful to get the actual name and the extension of a filename.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Other", Meta = (DisplayName = "Split Name"))
static void SplitName(const FString& Name, FString& NamePart, FString& ExtensionPart);
/**
* Returns an absolute path created by taking the given RelativePath and adding the root of the UE4's file system to it.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Other", Meta = (DisplayName = "Relative To Absolute Path"))
static FString RelativeToAbsolutePath(const FString& RelativePath);
/**
* Returns the paths of the files that exist in the given directory path.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Get Files"))
static TArray<FString> GetFiles(const FString& Directory);
/**
* Returns the paths of the directories that exist in the given directory path.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Get Directories"))
static TArray<FString> GetDirectories(const FString& Directory);
/**
* Returns the names of the files that exist in the given directory path.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Get File Names"))
static TArray<FString> GetFileNames(const FString& Directory);
/**
* Returns the names of the directories that exist in the given directory path.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Get Directory Names"))
static TArray<FString> GetDirectoryNames(const FString& Directory);
/**
* Returns true if a file exists on the given path.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Exists (File) (Boolean)"))
static bool FileExistsBool(const FString& File);
/**
* Returns true if a file exists on the given path.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Exists (File)", ExpandEnumAsExecs = "Branch"))
static void FileExists(const FString& File, ELowEntryFileManagerYesNo& Branch);
/**
* Returns true if a directory exists on the given path.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Exists (Directory) (Boolean)"))
static bool DirectoryExistsBool(const FString& Directory);
/**
* Returns true if a directory exists on the given path.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Exists (Directory)", ExpandEnumAsExecs = "Branch"))
static void DirectoryExists(const FString& Directory, ELowEntryFileManagerYesNo& Branch);
/**
* Creates a file if it doesn't exist yet.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Create (File)"))
static void CreateNewFile(const FString& File);
/**
* Creates a directory if it doesn't exist yet.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Create (Directory)"))
static void CreateNewDirectory(const FString& Directory);
/**
* Creates the parent directory of the given Path if it doesn't exist yet.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|Other", Meta = (DisplayName = "Create Parent Directory"))
static void CreateParentDirectory(const FString& Path);
/**
* Deletes a file if it exists.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Delete (File)"))
static void DeleteFile(const FString& File);
/**
* Deletes a directory if it exists.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Delete (Directory)"))
static void DeleteDirectory(const FString& Directory);
/**
* Returns true if the file is empty or doesn't exist.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Is Empty (File) (Boolean)"))
static bool IsFileEmptyBool(const FString& File);
/**
* Returns true if the file is empty or doesn't exist.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Is Empty (File)", ExpandEnumAsExecs = "Branch"))
static void IsFileEmpty(const FString& File, ELowEntryFileManagerYesNo& Branch);
/**
* Returns true if the directory is empty or doesn't exist.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Is Empty (Directory) (Boolean)"))
static bool IsDirectoryEmptyBool(const FString& Directory);
/**
* Returns true if the directory is empty or doesn't exist.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Is Empty (Directory)", ExpandEnumAsExecs = "Branch"))
static void IsDirectoryEmpty(const FString& Directory, ELowEntryFileManagerYesNo& Branch);
/**
* Sets the data of the file to an empty byte array, which also causes the file to be created if it didn't exist yet, basically causing the file to be existing and empty.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Clear (File)"))
static void ClearFile(const FString& File);
/**
* Removes the directory (and anything that is inside of it) and creates a new directory with the same name on the same location, basically causing the directory to be existing and empty.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Clear (Directory)"))
static void ClearDirectory(const FString& Directory);
/**
* Copies the file, won't do anything if the given NewFile already exists.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Copy (File)", Keywords = "clone duplicate"))
static void CopyFile(const FString& File, const FString& To);
/**
* Copies the directory, if the given NewDirectory already exists, the directory will merge with the existing directory.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Copy (Directory)", Keywords = "clone duplicate"))
static void CopyDirectory(const FString& Directory, const FString& To, bool OverrideExistingFiles);
/**
* Moves/renames the file, won't do anything if the given NewFile already exists.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Move (File)", Keywords = "rename"))
static void MoveFile(const FString& File, const FString& To);
/**
* Moves/renames the directory, if the given NewDirectory already exists, the directory will merge with the existing directory.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|Directory", Meta = (DisplayName = "Move (Directory)", Keywords = "rename"))
static void MoveDirectory(const FString& Directory, const FString& To, bool OverrideExistingFiles);
/**
* Returns true if the file is read only.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Is Read Only (File) (Boolean)"))
static bool IsFileReadOnlyBool(const FString& File);
/**
* Returns true if the file is read only.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Is Read Only (File)", ExpandEnumAsExecs = "Branch"))
static void IsFileReadOnly(const FString& File, ELowEntryFileManagerYesNo& Branch);
/**
* Sets the file read only.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Set Read Only (File)"))
static void SetFileReadOnly(const FString& File, const bool ReadOnly);
/**
* Executes the file and waits for it to fininsh, returns the output.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Execute (File)"))
static void ExecuteFile(const FString& File, const FString& Parameters, bool& Success, int32& ReturnCode, FString& StdOut, FString& StdErr);
/**
* Executes the file as a separate process.
*
* Hidden will cause the new process to not have a window or show up in the task bar.
* Priority can be: -2 idle, -1 low, 0 normal, 1 high, 2 higher.
* OptionalWorkingDirectory can be left empty to use the current work directory, otherwise an absolute path has to be given.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Execute Async (File)", AdvancedDisplay = "5"))
static void ExecuteFileAsync(const FString& File, const FString& Parameters, bool& Success, int32& ProcessID, const bool Hidden = true, const int32 Priority = 0, const FString& OptionalWorkingDirectory = TEXT(""));
/**
* Returns the data of the file, returns an empty byte array if the file doesn't exist.
*
* Note: Can only open files of 2GB and smaller, will return an empty byte array if it is bigger than 2GB.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Get Data (File)"))
static TArray<uint8> GetFileData(const FString& File);
/**
* Sets the data of the file, creates the file if it doesn't exist yet.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Set Data (File)"))
static void SetFileData(const FString& File, const TArray<uint8>& Data);
/**
* Appends data to the end of the file, creates the file if it doesn't exist yet.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Append Data (File)"))
static void AppendFileData(const FString& File, const TArray<uint8>& Data);
/**
* Returns the number of bytes the file has, returns 0 if the file does not exist.
*
* Note: Can only return sizes of 2GB and smaller, will return 0 if it is bigger than 2GB.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Get Size (File)"))
static int32 GetFileSize(const FString& File);
/**
* Returns the timestamp of the last edit of the file.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Get Timestamp (File)"))
static FDateTime GetFileTimestamp(const FString& File);
/**
* Sets the timestamp of the last edit of the file.
*/
UFUNCTION(BlueprintCallable, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Set Timestamp (File)"))
static void SetFileTimestamp(const FString& File, const FDateTime& Timestamp);
/**
* Returns the timestamp of the last access of the file.
*/
UFUNCTION(BlueprintPure, Category = "Low Entry|File Manager|Low Level|File", Meta = (DisplayName = "Get Access Timestamp (File)"))
static FDateTime GetFileAccessTimestamp(const FString& File);
};
|
/**
* Created by K. Suwatchai (Mobizt)
*
* Email: k_suwatchai@hotmail.com
*
* Github: https://github.com/mobizt/Firebase-ESP8266
*
* Copyright (c) 2023 mobizt
*
*/
// This example shows how error retry and queues work.
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#include <FirebaseESP32.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <FirebaseESP8266.h>
#elif defined(ARDUINO_RASPBERRY_PI_PICO_W)
#include <WiFi.h>
#include <FirebaseESP8266.h>
#endif
// Provide the token generation process info.
#include <addons/TokenHelper.h>
// Provide the RTDB payload printing info and other helper functions.
#include <addons/RTDBHelper.h>
/* 1. Define the WiFi credentials */
#define WIFI_SSID "WIFI_AP"
#define WIFI_PASSWORD "WIFI_PASSWORD"
// For the following credentials, see examples/Authentications/SignInAsUser/EmailPassword/EmailPassword.ino
/* 2. Define the API Key */
#define API_KEY "API_KEY"
/* 3. Define the RTDB URL */
#define DATABASE_URL "URL" //<databaseName>.firebaseio.com or <databaseName>.<region>.firebasedatabase.app
/* 4. Define the user Email and password that alreadey registerd or added in your project */
#define USER_EMAIL "USER_EMAIL"
#define USER_PASSWORD "USER_PASSWORD"
// Define Firebase Data object
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
bool taskCompleted = false;
std::vector<uint8_t> myblob;
double mydouble = 0;
uint32_t queueID[20];
uint8_t qIdx = 0;
int queueCnt = 0;
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
WiFiMulti multi;
#endif
void callback(QueueInfo queueinfo)
{
if (queueinfo.isQueueFull())
{
Serial.println("Queue is full");
}
Serial.print("Remaining queues: ");
Serial.println(queueinfo.totalQueues());
Serial.print("Being processed queue ID: ");
Serial.println(queueinfo.currentQueueID());
Serial.print("Data type:");
Serial.println(queueinfo.dataType());
Serial.print("Method: ");
Serial.println(queueinfo.firebaseMethod());
Serial.print("Path: ");
Serial.println(queueinfo.dataPath());
Serial.println();
}
void setup()
{
Serial.begin(115200);
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
multi.addAP(WIFI_SSID, WIFI_PASSWORD);
multi.run();
#else
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
#endif
Serial.print("Connecting to Wi-Fi");
unsigned long ms = millis();
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
if (millis() - ms > 10000)
break;
#endif
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
/* Assign the api key (required) */
config.api_key = API_KEY;
/* Assign the user sign in credentials */
auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;
/* Assign the RTDB URL (required) */
config.database_url = DATABASE_URL;
/* Assign the callback function for the long running token generation task */
config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h
// The WiFi credentials are required for Pico W
// due to it does not have reconnect feature.
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
config.wifi.clearAP();
config.wifi.addAP(WIFI_SSID, WIFI_PASSWORD);
#endif
// Or use legacy authenticate method
// config.database_url = DATABASE_URL;
// config.signer.tokens.legacy_token = "<database secret>";
// To connect without auth in Test Mode, see Authentications/TestMode/TestMode.ino
Firebase.begin(&config, &auth);
// Or use legacy authenticate method
// Firebase.begin(DATABASE_URL, DATABASE_SECRET);
Firebase.reconnectWiFi(true);
// Open and retore Firebase Error Queues from file.
// The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h.
if (Firebase.errorQueueCount(fbdo, "/test.txt", mem_storage_type_flash) > 0)
{
Firebase.restoreErrorQueue(fbdo, "/test.txt", mem_storage_type_flash);
Firebase.deleteStorageFile("/test.txt", mem_storage_type_flash);
}
// Set maximum Firebase read/store retry operation (0 - 255) in case of
// network problems and buffer overflow
Firebase.setMaxRetry(fbdo, 3);
// Set the maximum Firebase Error Queues in collection (0 - 255).
// Firebase read/store operation causes by network problems and buffer
// overflow will be added to Firebase Error Queues collection.
Firebase.setMaxErrorQueue(fbdo, 10);
Firebase.beginAutoRunErrorQueue(fbdo, callback);
// Firebase.beginAutoRunErrorQueue(fbdo);
}
void loop()
{
// Firebase.ready() should be called repeatedly to handle authentication tasks.
if (Firebase.ready() && !taskCompleted)
{
taskCompleted = true;
Serial.printf("Set double... %s\n", Firebase.setDouble(fbdo, "/test/double", 340.123456789) ? "ok" : fbdo.errorReason().c_str());
if (fbdo.httpCode() != FIREBASE_ERROR_HTTP_CODE_OK && Firebase.getErrorQueueID(fbdo) > 0)
{
Serial.printf("Error Queue ID: %d\n", (int)Firebase.getErrorQueueID(fbdo));
queueID[qIdx] = Firebase.getErrorQueueID(fbdo);
qIdx++;
}
// Create demo data
uint8_t data[256];
for (int i = 0; i < 256; i++)
data[i] = i;
Serial.printf("Set Blob... %s\n", Firebase.setBlob(fbdo, "/test/blob", data, sizeof(data)) ? "ok" : fbdo.errorReason().c_str());
if (fbdo.httpCode() != FIREBASE_ERROR_HTTP_CODE_OK && Firebase.getErrorQueueID(fbdo) > 0)
{
Serial.printf("Error Queue ID: %d\n", (int)Firebase.getErrorQueueID(fbdo));
queueID[qIdx] = Firebase.getErrorQueueID(fbdo);
qIdx++;
}
if (WiFi.status() == WL_CONNECTED)
{
Serial.println("--------------------------------------------------------------------------");
Serial.println("To test error queue, turn off WiFi AP to make error in the next operation");
Serial.println("--------------------------------------------------------------------------");
Serial.println();
delay(10000);
}
Serial.printf("Get double... %s\n", Firebase.getDouble(fbdo, "/test/double", &mydouble) ? "ok" : fbdo.errorReason().c_str());
if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK)
printResult(fbdo);
else
{
if (Firebase.getErrorQueueID(fbdo) > 0)
{
Serial.printf("Error Queue ID: %d\n", (int)Firebase.getErrorQueueID(fbdo));
queueID[qIdx] = Firebase.getErrorQueueID(fbdo);
qIdx++;
}
}
Serial.printf("Get blob... %s\n", Firebase.getBlob(fbdo, "/test/blob", myblob) ? "ok" : fbdo.errorReason().c_str());
if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK)
printResult(fbdo);
else
{
if (Firebase.getErrorQueueID(fbdo) > 0)
{
Serial.printf("Error Queue ID: %d\n", (int)Firebase.getErrorQueueID(fbdo));
queueID[qIdx] = Firebase.getErrorQueueID(fbdo);
qIdx++;
}
}
if (Firebase.errorQueueCount(fbdo) > 0)
{
Serial.println("-----------------------------------------------------------------------------");
Serial.println("Now turn on WiFi hotspot or router to process these queues");
Serial.println("-----------------------------------------------------------------------------");
Serial.println();
// Save Error Queues to file
// The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h.
Firebase.saveErrorQueue(fbdo, "/test.txt", mem_storage_type_flash);
}
// Stop error queue auto run process
// Firebase.endAutoRunErrorQueue(fbdo);
queueCnt = Firebase.errorQueueCount(fbdo);
}
/*
//if Firebase.beginAutoRunErrorQueue was not call,
//to manaul run the Firebase Error Queues, just call
//Firebase.processErrorQueue in loop
Firebase.processErrorQueue(fbdo);
delay(1000);
if (Firebase.isErrorQueueFull(fbdo))
{
Serial.println("Queue is full");
}
Serial.print("Remaining queues: ");
Serial.println(Firebase.errorQueueCount(fbdo));
for (uint8_t i = 0; i < qIdx; i++)
{
Serial.print("Error Queue ");
Serial.print(queueID[i]);
if (Firebase.isErrorQueueExisted(fbdo, queueID[i]))
Serial.println(" is queuing");
else
Serial.println(" is done");
}
Serial.println();
*/
if (queueCnt > 0)
{
if (mydouble > 0)
{
Serial.println("Double Data gets from Queue");
printf("%.9lf\n", mydouble);
Serial.println();
mydouble = 0;
}
if (myblob.size() > 0)
{
Serial.println("Blob Data gets from Queue");
for (size_t i = 0; i < myblob.size(); i++)
{
if (i > 0 && i % 16 == 0)
Serial.println();
if (myblob[i] < 16)
Serial.print("0");
Serial.print(myblob[i], HEX);
Serial.print(" ");
}
Serial.println();
Serial.println();
myblob.clear();
}
}
}
|
#include "TrantorThreadPool.h"
#include <assert.h>
#include <iostream>
using namespace std;
//static long cnt1 = 0;
//static long cnt2 = 0;
namespace trantor
{
TrantorFixedThreadPool::TrantorFixedThreadPool(const int thread_num):pool_alive_(true), wait_empty_(false)
{
assert(thread_num > 0);
for(int i = 0; i < thread_num; i++)
{
std::shared_ptr<std::thread> th_ptr = make_shared<std::thread>(&TrantorFixedThreadPool::threadFunc, this);
thread_queue_.push_back(th_ptr);
}
}
TrantorFixedThreadPool::~TrantorFixedThreadPool()
{
auto f = [=](std::shared_ptr<std::thread> iter)
{
if (iter)
{
iter->join();
}
};
{
std::unique_lock<std::mutex> lock(mtx_);
pool_alive_ = false;
not_empty_cv_.notify_all();
}
for_each(thread_queue_.begin(), thread_queue_.end(), f);
}
void TrantorFixedThreadPool::pushTask(std::function<void()> func)
{
std::unique_lock<std::mutex> lock(mtx_);
task_queue_.push(func);
//cout << "task push num: " << cnt1++<<" "<< task_queue_.size() << " " << std::this_thread::get_id() <<endl;
not_empty_cv_.notify_one();
}
void TrantorFixedThreadPool::waitUntilFinished()
{
std::unique_lock<std::mutex> lock(mtx_);
if (task_queue_.empty())
{
return;
}
else
{
wait_empty_ = true;
empty_cv_.wait(lock, [=]() {return task_queue_.empty(); });
wait_empty_ = false;
}
}
bool TrantorFixedThreadPool::isFree()
{
std::unique_lock<std::mutex> lock(mtx_);
return task_queue_.empty();
}
void TrantorFixedThreadPool::threadFunc()
{
std::function<void()> func_to_do;
while(pool_alive_)
{
{
std::unique_lock<std::mutex> lock(mtx_);
if (pool_alive_)
{
if (wait_empty_ && task_queue_.empty())
{
empty_cv_.notify_one();
}
not_empty_cv_.wait(lock, [=]() {return (!task_queue_.empty() || !pool_alive_); });
if (!task_queue_.empty())
{
func_to_do = task_queue_.front();
task_queue_.pop();
//cout << "task done num: " << cnt2++ << " " << std::this_thread::get_id() << endl;
}
}
}
if (func_to_do)
{
func_to_do();
}
}
}
void TrantorCachedThreadPool::pushTask(std::function<void()> func)
{
std::lock_guard<std::mutex> lock(mtx_);
if (single_thread_vec_.size() == 0)
{
std::shared_ptr<TrantorSingleThread> thread_ptr = std::make_shared<TrantorSingleThread>();
assert(thread_ptr);
thread_ptr->pushTask(func);
single_thread_vec_.push_back(thread_ptr);
}
else
{
std::vector<std::shared_ptr<TrantorSingleThread> >::iterator iter_tag = single_thread_vec_.begin();
for (auto iter = single_thread_vec_.begin(); iter != single_thread_vec_.end(); ++iter)
{
if ((*iter)->isFree())
{
(*iter)->pushTask(func);
return;
}
if ((*iter)->getTaskNumInQueue() < (*iter_tag)->getTaskNumInQueue())
{
iter_tag = iter;
}
}
if (single_thread_vec_.size() < max_thread_num_)
{
std::shared_ptr<TrantorSingleThread> thread_ptr = std::make_shared<TrantorSingleThread>();
assert(thread_ptr);
thread_ptr->pushTask(func);
single_thread_vec_.push_back(thread_ptr);
}
else
{
(*iter_tag)->pushTask(func);
}
}
}
uint16_t TrantorCachedThreadPool::getThreadNum()
{
std::lock_guard<std::mutex> lock(mtx_);
return single_thread_vec_.size();
}
void TrantorCachedThreadPool::waitUntilFinished()
{
std::lock_guard<std::mutex> lock(mtx_);
for (auto item : single_thread_vec_)
{
item->waitUntilFinished();
}
}
void TrantorCachedThreadPool::reset()
{
std::lock_guard<std::mutex> lock(mtx_);
single_thread_vec_.clear();
single_thread_vec_.resize(0);
}
}
|
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
this->data = d;
this->left = NULL;
this->right = NULL;
}
};
node* buildTree(node* root){
cout<<"Enter the data: ";
int data;
cin>>data;
root = new node(data);
if(data == -1){
return NULL;
}
cout<<"Enter data to insert in left of "<<data<<endl;
root->left = buildTree(root->left);
cout<<"Enter data to insert in right of "<<data<<endl;
root->right = buildTree(root->right);
return root;
}
void levelOrderTraversal(node* root){
queue<node*>q;
q.push(root);
q.push(NULL); // Seperator to show levels
while(!q.empty()){
node* temp = q.front();
q.pop();
if(temp == NULL){
cout<<endl;
if(!q.empty()){
q.push(NULL);
}
}
else{
cout<<temp->data<<" ";
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
}
}
// Reverse level order traversal:
// 1. Using stack and queues: Modify the level order travesal by instead of printing we will push it into stack.
// 2. Traversing trees first right subtree then left subtree to maintain order.
void reverseLevelOrderTraversal(node* root){
queue<node*>q;
stack<node*>s;
q.push(root);
while(!q.empty()){
node* temp = q.front();
q.pop();
if(temp == NULL){
s.push(temp);
if(!q.empty()){
q.push(NULL);
}
}
else{
s.push(temp);
if(temp->right){
q.push(temp->right);
}
if(temp->left){
q.push(temp->left);
}
}
}
cout<<s.size()<<endl;
while(!s.empty()){
node* temp = s.top();
s.pop();
if(temp == NULL){
cout<<endl;
}
else{
cout<<temp->data<<" ";
}
}
cout<<endl;
}
void Inorder(node* root){
if(root == NULL){
return;
}
Inorder(root->left);
cout<<root->data<<" ";
Inorder(root->right);
}
void Preorder(node* root){
if(root == NULL){
return;
}
cout<<root->data<<" ";
Preorder(root->left);
Preorder(root->right);
}
void Postorder(node* root){
if(root == NULL){
return;
}
Postorder(root->left);
Postorder(root->right);
cout<<root->data<<" ";
}
void Inorder_iter(node* root){
stack<node*>s;
node* curr = root;
while(!s.empty() || curr){
while(curr){
s.push(curr);
curr = curr->left;
}
curr = s.top();
cout<<curr->data<<" ";
s.pop();
curr = curr->right;
}
}
void Preorder_iter(node* root){
stack<node*>s;
node* curr = root;
while(!s.empty() || curr){
while(curr){
s.push(curr);
cout<<curr->data<<" ";
curr = curr->left;
}
curr = s.top();
s.pop();
curr = curr->right;
}
}
// Approach-1
/*
Use 2 stacks.
If we see well then reverse postorder traversal is similar to preorder traversal but with first going to right then to left.
Instead of printing modified preorder traversal, we will push it into new stack.
*/
void Postorder_iter1(node* root){
stack<node*>s1;
stack<node*>s2;
node* curr = root;
while(!s1.empty() || curr){
while(curr){
s1.push(curr);
s2.push(curr);
curr = curr->right;
}
curr = s1.top();
s1.pop();
curr = curr->left;
}
while(!s2.empty()){
node* temp = s2.top();
s2.pop();
cout<<temp->data<<" ";
}
}
int main(){
node *root = NULL;
root = buildTree(root);
// 5 7 8 -1 12 -1 -1 13 -1 -1 11 17 -1 -1 -1
cout<<endl;
cout<<"Level order: ";
levelOrderTraversal(root);
cout<<"Reverse Level order: ";
reverseLevelOrderTraversal(root);
cout<<"Inorder: ";
Inorder(root);
cout<<endl;
cout<<"Preorder: ";
Preorder(root);
cout<<endl;
cout<<"Postorder: ";
Postorder(root);
cout<<endl;
cout<<"Inorder Iteration: ";
Inorder_iter(root);
cout<<endl;
cout<<"Preorder Iteration: ";
Preorder_iter(root);
cout<<endl;
cout<<"PostOrder Iteration (two stack): ";
Postorder_iter1(root);
cout<<endl;
return 0;
}
|
#include "UicOnly.hpp"
int main(int argc, char* argv[])
{
UicOnly uicOnly;
return 0;
}
|
/*
* @lc app=leetcode.cn id=70 lang=cpp
*
* [70] 爬楼梯
*/
// @lc code=start
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n,0);
if(n==1)return 1;
if(n==2)return 2;
dp[0]=1;
dp[1]=2;
for(int i=2;i<n;++i){
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n-1];
}
};
// @lc code=end
|
// Copyright (c) 2016 Thomas Heller
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
namespace pika::detail {
template <typename T>
struct type_identity
{
using type = T;
};
} // namespace pika::detail
|
#ifndef __MUMUFRIEND_H__
#define __MUMUFIREND_H__
#include <QObject>
#include <QSqlQuery>
#include "networkmanager.h"
/**
* MumuFriend - A class that is friend of everyone
* This class is a glue between the system.
*/
class MumuFriend : public QObject
{
Q_OBJECT
public slots:
Q_INVOKABLE bool insertNewProcess(QString ip, QString path); ///< Send a file by the server
Q_INVOKABLE QObject *retornaPendentesModel(); ///< wrapper of method from DatabaseManager
Q_INVOKABLE QString getDestinationDir(); ///< wrapper of method from DatabaseManager
Q_INVOKABLE QString getServerAddress(); ///< wrapper of method from DatabaseManager
Q_INVOKABLE void updateDestDir(QString path); ///< wrapper of method from DatabaseManager
Q_INVOKABLE void updateServerAddress(QString address); ///< wrapper of method from DatabaseManager
public:
MumuFriend(QObject *parent = 0); ///< Default constructor
QSqlQuery returnOpenProcess(); ///< Return all pending actions that needs to be handled by server
void updateSendPieces(QString ip, QString file); ///< Updates the number of packets sent by server
private:
NetworkInterface *server; ///< Instance of the server
};
#endif //__MUMUFRIEND_H__
|
../1099/D.cpp
|
//
// RenderTexture.cpp
// Odin.MacOSX
//
// Created by Daniel on 24/10/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#include "RenderTexture.h"
namespace odin
{
namespace render
{
RenderTexture::RenderTexture() :
m_fbo(0),
m_colorAttachment(0),
m_depthAttachment(0),
m_stencilAttachment(0),
m_colorIsBuffer(false),
m_depthIsBuffer(false),
m_stencilIsBuffer(false)
{
}
RenderTexture::~RenderTexture()
{
deleteColorAttachment();
deleteDepthAttachment();
deleteStencilAttachment();
if (m_fbo)
lib::deleteFramebuffers(1, &m_fbo);
}
void RenderTexture::bind(UI32 target) const
{
if (m_fbo)
lib::bindFramebuffer(target, m_fbo);
}
void RenderTexture::unbind(UI32 target) const
{
lib::bindFramebuffer(target, 0);
}
math::ivec2 RenderTexture::getSize() const
{
return m_size;
}
UI32 RenderTexture::getColorAttachment() const
{
return m_colorAttachment;
}
UI32 RenderTexture::getDepthAttachment() const
{
return m_depthAttachment;
}
UI32 RenderTexture::getStencilAttachment() const
{
return m_stencilAttachment;
}
void RenderTexture::setColorTexture(UI32 target, I32 internalFormat, I32 width, I32 height, UI32 format, UI32 type, I32 filter)
{
if (!m_fbo)
lib::genFramebuffers(1, &m_fbo);
deleteColorAttachment();
bind(target);
lib::genTextures(1, &m_colorAttachment);
lib::bindTexture(ODIN_TEXTURE_2D, m_colorAttachment);
lib::texImage2D(ODIN_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, nullptr);
lib::texParameteri(ODIN_TEXTURE_2D, ODIN_TEXTURE_MIN_FILTER, filter);
lib::texParameteri(ODIN_TEXTURE_2D, ODIN_TEXTURE_MAG_FILTER, filter);
lib::framebufferTexture2D(target, ODIN_COLOR_ATTACHMENT0, ODIN_TEXTURE_2D, m_colorAttachment, 0);
lib::bindTexture(ODIN_TEXTURE_2D, 0);
unbind(target);
m_colorIsBuffer = false;
m_size.x = width;
m_size.y = height;
}
void RenderTexture::setDepthTexture(UI32 target, I32 width, I32 height, UI32 type)
{
if (!m_fbo)
lib::genFramebuffers(1, &m_fbo);
deleteDepthAttachment();
bind(target);
lib::genTextures(1, &m_depthAttachment);
lib::bindTexture(ODIN_TEXTURE_2D, m_depthAttachment);
lib::texImage2D(ODIN_TEXTURE_2D, 0, ODIN_DEPTH_COMPONENT, width, height, 0, ODIN_DEPTH_COMPONENT, type, nullptr);
lib::framebufferTexture2D(target, ODIN_DEPTH_ATTACHMENT, ODIN_TEXTURE_2D, m_depthAttachment, 0);
lib::bindTexture(ODIN_TEXTURE_2D, 0);
unbind(target);
m_depthIsBuffer = false;
m_size.x = width;
m_size.y = height;
}
void RenderTexture::setStencilTexture(UI32 target, I32 width, I32 height, UI32 type)
{
if (!m_fbo)
lib::genFramebuffers(1, &m_fbo);
deleteStencilAttachment();
bind(target);
lib::genTextures(1, &m_stencilAttachment);
lib::bindTexture(ODIN_TEXTURE_2D, m_stencilAttachment);
lib::texImage2D(ODIN_TEXTURE_2D, 0, ODIN_STENCIL_INDEX, width, height, 0, ODIN_STENCIL_INDEX, type, nullptr);
lib::framebufferTexture2D(ODIN_TEXTURE_2D, ODIN_STENCIL_ATTACHMENT, ODIN_TEXTURE_2D, m_stencilAttachment, 0);
lib::bindTexture(ODIN_TEXTURE_2D, 0);
unbind(target);
m_stencilIsBuffer = false;
m_size.x = width;
m_size.y = height;
}
void RenderTexture::setDepthStencilTexture(UI32 target, I32 width, I32 height, UI32 type)
{
if (!m_fbo)
lib::genFramebuffers(1, &m_fbo);
deleteDepthAttachment();
bind(target);
UI32 texture;
lib::genTextures(1, &texture);
lib::bindTexture(ODIN_TEXTURE_2D, texture);
lib::texImage2D(ODIN_TEXTURE_2D, 0, ODIN_DEPTH_STENCIL, width, height, 0, ODIN_DEPTH_STENCIL, type, nullptr);
lib::framebufferTexture2D(target, GL_DEPTH_STENCIL_ATTACHMENT, ODIN_TEXTURE_2D, texture, 0);
lib::bindTexture(ODIN_TEXTURE_2D, 0);
unbind(target);
m_depthAttachment = texture;
m_depthIsBuffer = false;
m_stencilAttachment = texture;
m_stencilIsBuffer = false;
m_size.x = width;
m_size.y = height;
}
void RenderTexture::setColorBuffer(UI32 target, I32 internalFormat, I32 width, I32 height)
{
if (!m_fbo)
lib::genFramebuffers(1, &m_fbo);
deleteColorAttachment();
bind(target);
lib::genRenderbuffers(1, &m_colorAttachment);
lib::bindRenderbuffer(m_colorAttachment);
lib::renderbufferStorage(internalFormat, width, height);
lib::framebufferRenderbuffer(target, ODIN_COLOR_ATTACHMENT0, ODIN_RENDERBUFFER, m_colorAttachment);
lib::bindRenderbuffer(0);
unbind(target);
m_colorIsBuffer = true;
m_size.x = width;
m_size.y = height;
}
void RenderTexture::setDepthBuffer(UI32 target, I32 internalFormat, I32 width, I32 height)
{
if (!m_fbo)
lib::genFramebuffers(1, &m_fbo);
deleteDepthAttachment();
bind(target);
lib::genRenderbuffers(1, &m_depthAttachment);
lib::bindRenderbuffer(m_depthAttachment);
lib::renderbufferStorage(internalFormat, width, height);
lib::framebufferRenderbuffer(target, ODIN_DEPTH_ATTACHMENT, ODIN_RENDERBUFFER, m_depthAttachment);
lib::bindRenderbuffer(0);
unbind(target);
m_depthIsBuffer = true;
m_size.x = width;
m_size.y = height;
}
void RenderTexture::setStencilBuffer(UI32 target, I32 internalFormat, I32 width, I32 height)
{
if (!m_fbo)
lib::genFramebuffers(1, &m_fbo);
deleteStencilAttachment();
bind(target);
lib::genRenderbuffers(1, &m_stencilAttachment);
lib::bindRenderbuffer(m_stencilAttachment);
lib::renderbufferStorage(internalFormat, width, height);
lib::framebufferRenderbuffer(target, ODIN_STENCIL_ATTACHMENT, ODIN_RENDERBUFFER, m_stencilAttachment);
lib::bindRenderbuffer(0);
unbind(target);
m_stencilIsBuffer = true;
m_size.x = width;
m_size.y = height;
}
void RenderTexture::setDepthStencilBuffer(UI32 target, I32 internalFormat, I32 width, I32 height)
{
if (!m_fbo)
lib::genFramebuffers(1, &m_fbo);
deleteDepthAttachment();
bind(target);
UI32 rbo;
lib::genRenderbuffers(1, &rbo);
lib::bindRenderbuffer(rbo);
lib::renderbufferStorage(internalFormat, width, height);
lib::framebufferRenderbuffer(target, ODIN_DEPTH_STENCIL_ATTACHMENT, ODIN_RENDERBUFFER, rbo);
lib::bindRenderbuffer(0);
unbind(target);
m_depthAttachment = rbo;
m_depthIsBuffer = true;
m_stencilAttachment = rbo;
m_stencilIsBuffer = true;
m_size.x = width;
m_size.y = height;
}
void RenderTexture::deleteColorAttachment()
{
if (m_colorAttachment)
m_colorIsBuffer == false ? lib::deleteTextures(1, &m_colorAttachment) : lib::deleteBuffers(1, &m_colorAttachment);
}
void RenderTexture::deleteDepthAttachment()
{
if (m_depthAttachment)
m_depthIsBuffer == false ? lib::deleteTextures(1, &m_depthAttachment) : lib::deleteBuffers(1, &m_depthAttachment);
}
void RenderTexture::deleteStencilAttachment()
{
if (m_stencilAttachment)
m_stencilIsBuffer == false ? lib::deleteTextures(1, &m_stencilAttachment) : lib::deleteBuffers(1, &m_stencilAttachment);
}
}
}
|
#ifndef __ALGO_TOP_H__
#define __ALGO_TOP_H__
#include <stdint.h>
#include <ap_axi_sdata.h>
#include <ap_int.h>
#include <hls_stream.h>
#include "algo_top_parameters.h"
template<int D, int U>
struct ap_axiu <D, U, 0, 0>{
ap_uint<D> data;
ap_uint<U> user;
ap_uint<1> last;
};
namespace algo {
typedef ap_axiu<32, 8, 0, 0> axiword32;
typedef ap_axiu<64, 8, 0, 0> axiword64;
typedef ap_axiu<256, 8, 0, 0> axiword256;
typedef ap_axiu<320, 8, 0, 0> axiword320;
typedef ap_axiu<384, 8, 0, 0> axiword384;
typedef ap_axiu<448, 8, 0, 0> axiword448;
typedef ap_axiu<512, 8, 0, 0> axiword512;
typedef ap_axiu<576, 8, 0, 0> axiword576;
}
void algo_top(
hls::stream<algo::axiword576> link_in[N_INPUT_LINKS],
hls::stream<algo::axiword576> link_out[N_OUTPUT_LINKS]
);
#endif /* !__ALGO_TOP_H__ */
|
#include "image.h"
#include "assertion.h"
#include <stdexcept>
#include <sdl2/SDL.h>
#include <sdl2/SDL_image.h>
ColorNorm RGBA(ColorRGBA rgba) {
return glm::vec4(rgba) / 255.0f;
}
ColorRGBA ColorAlpha(ColorChannel alpha) {
return ColorRGBA{ 255, 255, 255, alpha };
}
void Image::Load(glm::uvec2 Size, ColorRGBA DefaultValue) {
size = Size;
image.resize(size.x * size.y, DefaultValue);
}
void Image::Load(const std::string& file) {
SDL_Surface* surface = IMG_Load(file.c_str());
if (!surface) {
THROWERROR("Cannot load " + file + " image file");
}
Load(glm::uvec2{ surface->w, surface->h });
for (size_t i = 0; i < size.x * size.y; i++) {
uint32_t pixel = *(static_cast<uint32_t*>(surface->pixels) + i);
SDL_GetRGBA(pixel, surface->format, &image[i].r, &image[i].g, &image[i].b, &image[i].a);
}
SDL_FreeSurface(surface);
}
void Image::Save(const std::string& file) {
SDL_Surface* surface = SDL_CreateRGBSurface(0, size.x, size.y, 32, 0xff000000, 0xff0000, 0xff00, 0xff);
for (size_t i = 0; i < size.x * size.y; i++) {
uint32_t pixel = SDL_MapRGBA(surface->format, image[i].r, image[i].g, image[i].b, image[i].a);
*(static_cast<uint32_t*>(surface->pixels) + i) = pixel;
}
IMG_SavePNG(surface, file.c_str());
SDL_FreeSurface(surface);
}
void Image::Reset() {
size = { 0, 0 };
image.clear();
}
ColorRGBA& Image::operator[](glm::uvec2 pos) {
return image[pos.y * size.x + pos.x];
}
const ColorRGBA& Image::operator[](glm::uvec2 pos) const {
return image[pos.y * size.x + pos.x];
}
|
#include "TrantorSemaphore.h"
namespace trantor
{
void TrantorSemaphore::wait()
{
std::unique_lock<std::mutex> lock(mtx_);
cv_.wait(lock, [=]() {return avaliable_res_num_ > 0; });
avaliable_res_num_--;
}
void TrantorSemaphore::post()
{
{
std::unique_lock<std::mutex> lock(mtx_);
if (avaliable_res_num_ < max_res_num_)
{
avaliable_res_num_++;
}
}
cv_.notify_all();
}
uint16_t TrantorSemaphore::getResNum()
{
std::unique_lock<std::mutex> lock(mtx_);
return avaliable_res_num_;
}
}
|
#include "ColdSim.h"
#include "Struct.h"
#include "get_trace_tool.h"
#include "log.h"
class RUN
{
private:
get_trace_tool *gtt;
struct IoRecord *ior;
MemStruct *ms;
char logdir[200];
public:
RUN(const char *logd)
{
LogClear();
ms = new MemStruct();
strcpy(logdir,logd);
}
~RUN()
{
delete ms;
ms = NULL;
}
void exec(const char *depotid)
{
char ds1[40];
char ds2[40];
char logfile[200];
long time_stamp = get_today();
for (int i = 0; i < 1; i++)
{
get_ds1(ds1, time_stamp, i * 3600);
get_ds2(ds2, time_stamp, i * 3600);
long row_cnt = get_data(ds1, ds2, depotid);
//strcpy(logfile, "/data0/app/hivelog/");
strcpy(logfile, logdir);
strcat(logfile, depotid);
strcat(logfile, "/");
strcat(logfile, ds2);
if (row_cnt == 0)
{
LogWrite(2, "file %s doesn't exist!!!", logfile); //error info
continue;
}
LogWrite(1, "file %s start!!!", logfile); //start info
gtt = new get_trace_tool(logfile);
ior = gtt->get_ti(true);
while (ior != NULL)
{
process(ior);
ior = gtt->get_ti(true);
}
delete gtt;
cout << ms->getToTSize() << endl;
ms->getIndexMap();
if (i % 24 == 0)
{
//output_info(io_log);
}
}
//test();
}
void process(struct IoRecord *ior)
{
/*处理流程示例*/
ms->isExpired(ior);
struct BlockStruct *bs = ms->ioToBlock(ior);
struct BlockStruct *bshead = bs;
while (bs != NULL)
{
ms->updateTOT(bs);
bs = bs->next;
}
ms->freeBlockList(bshead);
}
long get_today()
{
//time_t curtime = time(NULL);
return 1515772800; /*2018.01.13-00:00:00*/
}
long get_max()
{
return 1523199600; /*2018.04.08-23:00:00*/
}
char *get_ds1(char *ds1, long time_tmp, int diff)
{
time_tmp += diff;
struct tm *ttime;
ttime = localtime(&time_tmp);
strftime(ds1, 64, "%Y-%m-%d %H", ttime);
return ds1;
}
char *get_ds2(char *ds1, long time_tmp, int diff)
{
time_tmp += diff;
struct tm *ttime;
ttime = localtime(&time_tmp);
strftime(ds1, 64, "%Y-%m-%d-%H", ttime);
return ds1;
}
long get_data(char *ds1, char *ds2, const char *para1)
{
char cmd_sh[200];
strcpy(cmd_sh, "sh get_data.sh ");
strcat(cmd_sh, para1);
strcat(cmd_sh, " '");
strcat(cmd_sh, ds1);
strcat(cmd_sh, "' ");
strcat(cmd_sh, ds2);
cout << cmd_sh << endl;
//system(cmd_sh);
strcpy(cmd_sh, logdir);
strcat(cmd_sh, para1);
strcat(cmd_sh, "/");
strcat(cmd_sh, ds2);
FILE *fh = fopen(cmd_sh, "r");
if (fh == NULL)
{
printf("%s doesn't exist\n", cmd_sh);
return 0;
}
fclose(fh);
strcpy(cmd_sh, "wc -l ");
strcat(cmd_sh,logdir);
strcat(cmd_sh, para1);
strcat(cmd_sh, "/");
strcat(cmd_sh, ds2);
strcat(cmd_sh, " | awk '{print $1}' > tmp");
cout << cmd_sh << endl;
long result;
system(cmd_sh);
FILE *fp;
fp = fopen("tmp", "r");
fscanf(fp, "%ld", &result);
fclose(fp);
return result;
}
void test()
{
ior = new IoRecord;
ior->alloc_time = 1514746000;
strcpy(ior->disksn, "12312aaaa");
ior->offset = 33435564;
ior->size = 16;
ior->io_type = 1;
process(ior);
//cout << ms->getToTSize() << endl;
//ms->getTOTMap();
ior = new IoRecord;
ior->alloc_time = 1514746000;
strcpy(ior->disksn, "12312aaaaAA");
ior->offset = 133435564;
ior->size = 16;
ior->io_type = 0;
process(ior);
//cout << ms->getToTSize() << endl;
//ms->getTOTMap();
ior = new IoRecord;
ior->alloc_time = 1514746000;
strcpy(ior->disksn, "12312aaaa");
ior->offset = 33435564;
ior->size = 16;
ior->io_type = 0;
process(ior);
cout << ms->getToTSize() << endl;
ms->getIndexMap();
}
};
|
// 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 "RPCTestNode.h"
#include <future>
#include <vector>
#include <thread>
#include "Common/StringTools.h"
#include "CryptoNoteCore/CryptoNoteTools.h"
#include "NodeRpcProxy/NodeRpcProxy.h"
#include "Rpc/CoreRpcServerCommandsDefinitions.h"
#include "Rpc/HttpClient.h"
#include "Rpc/JsonRpc.h"
#include "Logger.h"
#include "NodeCallback.h"
using namespace cn;
using namespace platform_system;
namespace Tests {
RPCTestNode::RPCTestNode(uint16_t port, platform_system::Dispatcher& d) :
m_rpcPort(port), m_dispatcher(d), m_httpClient(d, "127.0.0.1", port) {
}
bool RPCTestNode::startMining(size_t threadsCount, const std::string& address) {
LOG_DEBUG("startMining()");
try {
COMMAND_RPC_START_MINING::request req;
COMMAND_RPC_START_MINING::response resp;
req.miner_address = address;
req.threads_count = threadsCount;
invokeJsonCommand(m_httpClient, "/start_mining", req, resp);
if (resp.status != CORE_RPC_STATUS_OK) {
throw std::runtime_error(resp.status);
}
} catch (std::exception& e) {
std::cout << "startMining() RPC call fail: " << e.what();
return false;
}
return true;
}
bool RPCTestNode::getBlockTemplate(const std::string& minerAddress, cn::Block& blockTemplate, uint64_t& difficulty) {
LOG_DEBUG("getBlockTemplate()");
try {
COMMAND_RPC_GETBLOCKTEMPLATE::request req;
COMMAND_RPC_GETBLOCKTEMPLATE::response rsp;
req.wallet_address = minerAddress;
req.reserve_size = 0;
JsonRpc::invokeJsonRpcCommand(m_httpClient, "getblocktemplate", req, rsp);
if (rsp.status != CORE_RPC_STATUS_OK) {
throw std::runtime_error(rsp.status);
}
difficulty = rsp.difficulty;
BinaryArray blockBlob = (::common::fromHex(rsp.blocktemplate_blob));
return fromBinaryArray(blockTemplate, blockBlob);
} catch (std::exception& e) {
LOG_ERROR("JSON-RPC call startMining() failed: " + std::string(e.what()));
return false;
}
return true;
}
bool RPCTestNode::submitBlock(const std::string& block) {
LOG_DEBUG("submitBlock()");
try {
COMMAND_RPC_SUBMITBLOCK::request req;
COMMAND_RPC_SUBMITBLOCK::response res;
req.push_back(block);
JsonRpc::invokeJsonRpcCommand(m_httpClient, "submitblock", req, res);
if (res.status != CORE_RPC_STATUS_OK) {
throw std::runtime_error(res.status);
}
} catch (std::exception& e) {
LOG_ERROR("RPC call of submit_block returned error: " + std::string(e.what()));
return false;
}
return true;
}
bool RPCTestNode::stopMining() {
LOG_DEBUG("stopMining()");
try {
COMMAND_RPC_STOP_MINING::request req;
COMMAND_RPC_STOP_MINING::response resp;
invokeJsonCommand(m_httpClient, "/stop_mining", req, resp);
if (resp.status != CORE_RPC_STATUS_OK) {
throw std::runtime_error(resp.status);
}
} catch (std::exception& e) {
std::cout << "stopMining() RPC call fail: " << e.what();
return false;
}
return true;
}
bool RPCTestNode::getTailBlockId(crypto::Hash& tailBlockId) {
LOG_DEBUG("getTailBlockId()");
try {
COMMAND_RPC_GET_LAST_BLOCK_HEADER::request req;
COMMAND_RPC_GET_LAST_BLOCK_HEADER::response rsp;
JsonRpc::invokeJsonRpcCommand(m_httpClient, "getlastblockheader", req, rsp);
if (rsp.status != CORE_RPC_STATUS_OK) {
throw std::runtime_error(rsp.status);
}
return ::common::podFromHex(rsp.block_header.hash, tailBlockId);
} catch (std::exception& e) {
LOG_ERROR("JSON-RPC call getTailBlockId() failed: " + std::string(e.what()));
return false;
}
return true;
}
bool RPCTestNode::makeINode(std::unique_ptr<cn::INode>& node) {
std::unique_ptr<cn::INode> newNode(new cn::NodeRpcProxy("127.0.0.1", m_rpcPort));
NodeCallback cb;
newNode->init(cb.callback());
auto ec = cb.get();
if (ec) {
LOG_ERROR("init error: " + ec.message() + ':' + TO_STRING(ec.value()));
return false;
}
LOG_DEBUG("NodeRPCProxy on port " + TO_STRING(m_rpcPort) + " initialized");
node = std::move(newNode);
return true;
}
bool RPCTestNode::stopDaemon() {
try {
LOG_DEBUG("stopDaemon()");
COMMAND_RPC_STOP_DAEMON::request req;
COMMAND_RPC_STOP_DAEMON::response resp;
invokeJsonCommand(m_httpClient, "/stop_daemon", req, resp);
if (resp.status != CORE_RPC_STATUS_OK) {
throw std::runtime_error(resp.status);
}
} catch (std::exception& e) {
std::cout << "stopDaemon() RPC call fail: " << e.what();
return false;
}
return true;
}
uint64_t RPCTestNode::getLocalHeight() {
try {
cn::COMMAND_RPC_GET_INFO::request req;
cn::COMMAND_RPC_GET_INFO::response rsp;
invokeJsonCommand(m_httpClient, "/getinfo", req, rsp);
if (rsp.status == CORE_RPC_STATUS_OK) {
return rsp.height;
}
} catch (std::exception&) {
}
return 0;
}
}
|
#include <imageprocessing/ImageExtractor.h>
#include <sopnet/slices/SliceExtractor.h>
#include "GroundTruthSegmentExtractor.h"
#include "GroundTruthExtractor.h"
logger::LogChannel groundtruthextractorlog("groundtruthextractorlog", "[GroundTruthExtractor] ");
GroundTruthExtractor::GroundTruthExtractor(int firstSection, int lastSection) :
_sectionExtractor(boost::make_shared<ImageExtractor>()),
_segmentsAssembler(boost::make_shared<SegmentsAssembler>()),
_firstSection(firstSection),
_lastSection(lastSection) {
registerInput(_groundTruthSections, "ground truth sections");
registerOutput(_segmentsAssembler->getOutput("ground truth segments"), "ground truth segments");
_groundTruthSections.registerBackwardSlot(_update);
_groundTruthSections.registerBackwardCallback(&GroundTruthExtractor::onInputSet, this);
}
void
GroundTruthExtractor::onInputSet(const pipeline::InputSet<ImageStack>&) {
LOG_DEBUG(groundtruthextractorlog) << "ground truth sections set" << std::endl;
createPipeline();
}
void
GroundTruthExtractor::createPipeline() {
// clear previous pipeline
_sliceExtractors.clear();
_segmentExtractors.clear();
_segmentsAssembler->clearInputs("segments");
// make sure relevant input information is available
_update();
_sectionExtractor->setInput(_groundTruthSections.getAssignedOutput());
unsigned int firstSection = (_firstSection >= 0 ? _firstSection : 0);
unsigned int lastSection = (_lastSection >= 0 ? _lastSection : _groundTruthSections->size() - 1);
LOG_ALL(groundtruthextractorlog)
<< "extacting groundtruth from sections "
<< firstSection << " - " << lastSection
<< std::endl;
// create mser parameters suitable to extract ground-truth connected
// components
boost::shared_ptr<MserParameters> mserParameters = boost::make_shared<MserParameters>();
mserParameters->delta = 1;
mserParameters->minArea = 50; // this is to avoid this tiny annotation that mess up the result
mserParameters->maxArea = 10000000;
mserParameters->maxVariation = 100;
mserParameters->minDiversity = 0;
mserParameters->darkToBright = false;
mserParameters->brightToDark = true;
mserParameters->sameIntensityComponents = true; // only extract connected components of same intensity
for (unsigned int section = firstSection; section <= lastSection; section++) {
LOG_ALL(groundtruthextractorlog) << "creating pipeline for section " << section << std::endl;
// create a SliceExtractor
boost::shared_ptr<SliceExtractor> sliceExtractor = boost::make_shared<SliceExtractor>(section);
// give it the section it has to process and our mser parameters
sliceExtractor->setInput("membrane", _sectionExtractor->getOutput(section));
sliceExtractor->setInput("mser parameters", mserParameters);
// store it in the list of all slice extractors
_sliceExtractors.push_back(sliceExtractor);
if (_sliceExtractors.size() <= 1)
continue;
// get the previous slice extractor
boost::shared_ptr<SliceExtractor> prevSliceExtractor = _sliceExtractors[_sliceExtractors.size() - 2];
// create a segment extractor
boost::shared_ptr<GroundTruthSegmentExtractor> segmentExtractor = boost::make_shared<GroundTruthSegmentExtractor>();
// connect current and previous slices to that
segmentExtractor->setInput("previous slices", prevSliceExtractor->getOutput("slices"));
segmentExtractor->setInput("next slices", sliceExtractor->getOutput("slices"));
// store segment extractor
_segmentExtractors.push_back(segmentExtractor);
_segmentsAssembler->addInput("segments", segmentExtractor->getOutput("segments"));
}
}
GroundTruthExtractor::SegmentsAssembler::SegmentsAssembler() {
registerInputs(_segments, "segments");
registerOutput(_allSegments, "ground truth segments");
}
void
GroundTruthExtractor::SegmentsAssembler::updateOutputs() {
LOG_ALL(groundtruthextractorlog)
<< "assembling segments from "
<< _segments.size() << " inter-section intervals"
<< std::endl;
_allSegments->clear();
foreach (boost::shared_ptr<Segments> segments, _segments) {
LOG_ALL(groundtruthextractorlog) << "adding " << segments->size() << " segments" << std::endl;
_allSegments->addAll(segments);
}
}
|
// Copyright 2011 Yandex
#include <gtest/gtest.h>
#include <vector>
#include <string>
#include "ltr/crossvalidation/validation_result.h"
#include "ltr/scorers/fake_scorer.h"
using ltr::cv::ValidationResult;
using ltr::FakeScorer;
using std::vector;
using std::string;
TEST(CrossvalidationTest, ValidationResultTest) {
vector<string> names;
names.push_back("Measure1");
names.push_back("Measure2");
ValidationResult vr(names);
EXPECT_EQ(names.at(0), vr.getMeasureNames().at(0));
EXPECT_EQ(names.at(1), vr.getMeasureNames().at(1));
FakeScorer::Ptr fscorer1(new FakeScorer());
string report1 = "Report 1";
vector<double> measures1;
measures1.push_back(1);
measures1.push_back(2);
vr.addSplitInfo(fscorer1, report1, measures1);
EXPECT_EQ(1, vr.getSplitCount());
FakeScorer::Ptr fscorer2(new FakeScorer());
string report2 = "Report 2";
vector<double> measures2;
measures2.push_back(3);
measures2.push_back(4);
vr.addSplitInfo(fscorer2, report2, measures2);
EXPECT_EQ(2, vr.getSplitCount());
EXPECT_EQ(report2, vr.getReport(1));
EXPECT_EQ(fscorer1, vr.getScorer(0));
EXPECT_EQ(measures1[0], vr.getMeasureValues(0).at(0));
EXPECT_EQ(measures2[1], vr.getMeasureValues(1).at(1));
measures2.push_back(5);
EXPECT_ANY_THROW(vr.addSplitInfo(fscorer2, report2, measures2));
EXPECT_NO_THROW(ValidationResult copy = vr);
};
|
#include <iostream>
using namespace std;
template <typename T1, typename T2>
T1 addition(T1 num1, T2 num2)
{
return num1 + num2;
}
int main ()
{
cout<<"Addition of Integer Numbers : "<<addition(10,20)<<endl;
cout<<"Addition of Float Numbers : "<<addition(10.5,15)<<endl;
cout<<"Addition of Characters : "<<addition('C',5)<<endl;
return 0;
}
|
//
// server.h
// mini-sql
//
// Created by Дмитрий Маслюков on 21.02.2020.
// Copyright © 2020 Дмитрий Маслюков. All rights reserved.
//
#ifndef server_h
#define server_h
#ifdef _WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 /* Windows XP. */
#endif
#include <winsock2.h>
#include <Ws2tcpip.h>
#else
/* Assume that any non-Windows platform uses POSIX-style sockets instead. */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h> /* Needed for getaddrinfo() and freeaddrinfo() */
#include <unistd.h> /* Needed for close() */
#endif
#include <map>
#include <functional>
#include <future>
static const char * okhdr = "HTTP/1.1 200 OK\r\nContent-length:";
static const char * okbody = "\r\nContent-Type: %s\r\nConnection: close\r\n\r\n";
static const char * statdir = "/svelte-app/public";
class Server{
int sockfd;
public:
class Connection;
struct scope_vars{};
template<typename T>
struct _sv:public scope_vars{
T members;
};
class _handler{
virtual void operator()(Connection & conn) = 0;
};
using handler = std::function<void(Connection&)>;
private:
std::map<std::string, handler> router;
public:
void route(const char * path, handler hdl){
router[path] = hdl;
}
class Connection {
int clfd;
char rdbuf [2048];
char path [100];
public:
Connection(int cl, const char * src = 0, const char * path = "/"){
clfd = cl;
strcpy(this->path, path);
if(src){
strcpy(rdbuf, src);
}
}
const char * get_path() const {
return path;
}
const char * get_query() {
char encoded [2048];
char * writer = encoded;
for(char * rdr = rdbuf; *rdr != 0; ++rdr){
if( *rdr == '%' ){
rdr += 2;
char numbuf [3];
strncpy(numbuf, rdr-1, 2);
numbuf[2] = 0;
int res = (int)strtol(numbuf, 0, 16);
switch (res) {
case 34:
*writer ++ = '"';
break;
case 32:
*writer ++ = ' ';
break;
case 40:
*writer ++ = '(';
break;
case 41:
*writer ++ = ')';
break;
case 61:
*writer ++ = '=';
break;
case 60:
*writer ++ = '<';
break;
case 62:
*writer ++ = '>';
default:
break;
}
} else {
*writer ++ = *rdr;
}
}
*writer = 0;
strcpy(rdbuf, encoded);
return rdbuf;
}
void send_file( const char * fname ){
char strbuf [2000];
sprintf(strbuf, "%s/%s", statdir, fname);
FILE * f = fopen(strbuf + 1, "r");
fseek(f, 0, SEEK_END);
long len = ftell(f);
rewind(f);
write(clfd, okhdr, strlen(okhdr));
char clen [10];
char bodybuf [100];
char * ext = strchr(strbuf, '.') + 1;
const char * mime = "text/html";
if(strcmp(ext, "js")==0){
mime = "application/javascript";
}
if(strcmp(ext, "css")==0){
mime = "text/css";
}
if(strcmp(ext, "svg")==0){
mime = "image/svg+xml";
}
sprintf(bodybuf, okbody, mime);
sprintf(clen, "%lu", len);
write(clfd, clen, strlen(clen));
write(clfd, bodybuf, strlen(bodybuf));
char *rdbuf_ = (char*)malloc(len);
fread(rdbuf_, len, 1, f);
write(clfd, rdbuf_, len);
free(rdbuf_);
fclose(f);
close(clfd);
}
void write_answer( const char * answer ){
if(strncmp(answer, "HTTP/1.1", 8) != 0){
write(clfd, okhdr, strlen(okhdr));
char clen [10];
sprintf(clen, "%zu", strlen(answer));
char body [1000];
sprintf(body, okbody, "text/html");
write(clfd, clen, strlen(clen));
write(clfd, body, strlen(body));
}
write(clfd, answer, strlen(answer));
shutdown(clfd, SHUT_RDWR);
close(clfd);
}
};
Server(int portno = 27177){
#ifdef _WIN32
WSADATA wsa_data;
return WSAStartup(MAKEWORD(1,1), &wsa_data);
#endif
sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(portno);
int enable = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
listen(sockfd, 100);
printf("listening %d\n", portno);
}
Connection connect(){
socklen_t l;
struct sockaddr_in addr;
cl_connect:;
int clfd = accept(sockfd, (sockaddr*)&addr, &l);
printf("client fd: %d, my fd: %d\n", clfd, sockfd);
char rdbuf [4096];
bzero(rdbuf, 4095);
//firstly read the headers
int bread = 0;
int read = 1;
while(read && !strstr(rdbuf, "\r\n\r\n")){
read = (int)recv(clfd, rdbuf+bread, 1, MSG_WAITALL);
if( read < 0 )
return Connection(-1);
bread += read;
rdbuf[ bread ] = 0;
//printf( "Got %d, %s\n", read, rdbuf );
}
char type[10];
char path [2048];
sscanf(rdbuf, "%s%s", type, path);
char * path_wo_params = strtok(path, "?");
if(strstr(path_wo_params, ".") != 0){
char strbuf [2000];
char * fname = strchr(path_wo_params, '/');
sprintf(strbuf, "%s%s", statdir, fname);
FILE * f = fopen(strbuf + 1, "r");
if(!f){
const char * err404 = "HTTP/1.1 404";
write(clfd, err404, sizeof(err404));
goto cl_connect;
}
fseek(f, 0, SEEK_END);
long len = ftell(f);
rewind(f);
write(clfd, okhdr, strlen(okhdr));
char clen [10];
char bodybuf [100];
char * ext = strchr(strbuf, '.') + 1;
const char * mime = "text/html";
if(strcmp(ext, "js")==0){
mime = "application/javascript";
}
if(strcmp(ext, "css")==0){
mime = "text/css";
}
if(strcmp(ext, "svg")==0){
mime = "image/svg+xml";
}
sprintf(bodybuf, okbody, mime);
sprintf(clen, "%lu", len);
write(clfd, clen, strlen(clen));
write(clfd, bodybuf, strlen(bodybuf));
char *rdbuf_ = (char*)malloc(len);
fread(rdbuf_, len, 1, f);
write(clfd, rdbuf_, len);
free(rdbuf_);
fclose(f);
close(clfd);
goto cl_connect;
}
return Connection(clfd, strtok(0, "\r\n"), path_wo_params);
}
void serve(){
do{
Connection conn = connect();
if( router.find(conn.get_path()) == router.end() ){
conn.write_answer("requested url was not found");
} else {
auto f = router[conn.get_path()];
std::async([&]{f(conn);});
}
}while(1);
}
};
#endif /* server_h */
|
/*
* Copyright (c) 2015-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_ADAPTERS_SMALL_ARRAY_ADAPTER_H_
#define CPPSORT_ADAPTERS_SMALL_ARRAY_ADAPTER_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <array>
#include <cstddef>
#include <type_traits>
#include <utility>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include "../detail/any_all.h"
#include "../detail/type_traits.h"
namespace cppsort
{
namespace detail
{
////////////////////////////////////////////////////////////
// SFINAE helpers
template<typename T, typename=void>
struct has_domain:
std::false_type
{
using domain = void;
};
template<typename T>
struct has_domain<T, void_t<typename T::domain>>:
std::true_type
{
using domain = typename T::domain;
};
}
////////////////////////////////////////////////////////////
// Adapter
// When no domain is given along with the fixed-size sorter,
// it is assumed that it works for small arrays of any size
// and thus void is given
template<
template<std::size_t> class FixedSizeSorter,
typename Indices = typename detail::has_domain<
fixed_sorter_traits<FixedSizeSorter>
>::domain
>
struct small_array_adapter;
template<
template<std::size_t> class FixedSizeSorter,
std::size_t... Indices
>
struct small_array_adapter<FixedSizeSorter, std::index_sequence<Indices...>>:
fixed_sorter_traits<FixedSizeSorter>,
detail::sorter_facade_fptr<
small_array_adapter<FixedSizeSorter, std::index_sequence<Indices...>>,
detail::all(std::is_empty<FixedSizeSorter<Indices>>::value...)
>
{
template<
typename T,
std::size_t N,
typename... Args
>
auto operator()(std::array<T, N>& array, Args&&... args) const
-> std::enable_if_t<
detail::is_in_pack<N, Indices...>,
decltype(FixedSizeSorter<N>{}(array, std::forward<Args>(args)...))
>
{
return FixedSizeSorter<N>{}(array, std::forward<Args>(args)...);
}
template<
typename T,
std::size_t N,
typename... Args,
typename = std::enable_if_t<detail::is_in_pack<N, Indices...>>
>
auto operator()(T (&array)[N], Args&&... args) const
-> std::enable_if_t<
detail::is_in_pack<N, Indices...>,
decltype(FixedSizeSorter<N>{}(array, std::forward<Args>(args)...))
>
{
return FixedSizeSorter<N>{}(array, std::forward<Args>(args)...);
}
};
template<template<std::size_t> class FixedSizeSorter>
struct small_array_adapter<FixedSizeSorter, void>:
fixed_sorter_traits<FixedSizeSorter>,
detail::sorter_facade_fptr<
small_array_adapter<FixedSizeSorter, void>,
true // TODO: how can we do better?
>
{
template<
typename T,
std::size_t N,
typename... Args
>
auto operator()(std::array<T, N>& array, Args&&... args) const
-> decltype(FixedSizeSorter<N>{}(array, std::forward<Args>(args)...))
{
return FixedSizeSorter<N>{}(array, std::forward<Args>(args)...);
}
template<
typename T,
std::size_t N,
typename... Args
>
auto operator()(T (&array)[N], Args&&... args) const
-> decltype(FixedSizeSorter<N>{}(array, std::forward<Args>(args)...))
{
return FixedSizeSorter<N>{}(array, std::forward<Args>(args)...);
}
};
////////////////////////////////////////////////////////////
// is_stable specialization
template<
template<std::size_t> class FixedSizeSorter,
typename Indices,
typename T, std::size_t N,
typename... Args
>
struct is_stable<small_array_adapter<FixedSizeSorter, Indices>(std::array<T, N>&, Args...)>:
is_stable<FixedSizeSorter<N>(std::array<T, N>&, Args...)>
{};
template<
template<std::size_t> class FixedSizeSorter,
typename Indices,
typename T, std::size_t N,
typename... Args
>
struct is_stable<small_array_adapter<FixedSizeSorter, Indices>(T (&)[N], Args...)>:
is_stable<FixedSizeSorter<N>(T (&)[N], Args...)>
{};
}
#ifdef CPPSORT_ADAPTERS_SCHWARTZ_ADAPTER_H_
#include "../detail/schwartz_small_array.h"
#endif
#endif // CPPSORT_ADAPTERS_SMALL_ARRAY_ADAPTER_H_
|
#include <SFML/Graphics.hpp>
#include <math.h>
#include <iostream>
#include "terrain_generator.h"
int main()
{
unsigned int seed = 104, width = 256, height = 256;
auto terrain = TerrainGenerator(seed, width, height);
auto t = 10;
sf::Texture texture;
// if (!image->saveToFile("result.png"))
// return -1;
sf::RenderWindow window(sf::VideoMode(width, height), "My window");
sf::Sprite sprite;
sprite.setPosition(0,0);
terrain.generate(t);
sprite.setTexture(*terrain.getTexture());
auto dir = 1;
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
{
window.close();
break;
}
case sf::Event::KeyReleased:
{
switch(event.key.code)
{
case sf::Keyboard::Escape:
{
window.close();
break;
}
}
}
}
}
// clear the window with black color
window.clear(sf::Color::Black);
// draw everything here...
t += dir;
terrain.generate(t);
window.draw(sprite);
// end the current frame
window.display();
}
return 0;
}
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main()
{
freopen("mamxanh8.inp","r",stdin);
freopen("mamxanh8.out","w",stdout);
int a;
scanf("%d %d",&a);
printf("Binh phuong cua %d la: %d\n",a,a*a);
printf("Lap phuong cua %d la: %d\n",a,a*a*a);
return 0;
}
|
GLuint CreateAtmosphericScatteringLUT(double radius)
{
const int dim = 256;
float lut[dim][dim][4];
float planet_radius = radius / 1000.0;
float atmosphere_radius = 1.025f * planet_radius;
float atmosphere_height = atmosphere_radius - planet_radius;
float scale_height = (atmosphere_height) * 0.25f;
for (int j = 0; j < dim; ++j)
{
for (int i = 0; i < dim; ++i)
{
float x = float(i) / (dim - 1);
float y = float(j) / (dim - 1);
float dx = 1.0f - 2.0f * y;
float dy = Sqrt(1.0f - x*x);
float origin_len = planet_radius +
atmosphere_height * x;
float origin_x = dx * origin_len;
float origin_y = dy * origin_len;
float ray_len = Sqrt(Square(atmosphere_radius) -
Square(origin_y)) - origin_x;
int N = 50;
float step_len = ray_len / N;
float optical_depth = 0.0f;
for (int i = 0; i < N; i++)
{
float sample_x = origin_x + (0.5f + i)*step_len;
float sample_y = origin_y;
float height = Sqrt(Square(sample_x) +
Square(sample_y)) - planet_radius;
float density = Exp(-height / scale_height);
optical_depth += density * step_len;
}
float atmosphere_density =
Exp(-(atmosphere_height * x) / scale_height);
lut[j][i][0] = atmosphere_density;
lut[j][i][1] = optical_depth;
}
}
return CreateTexture2D(dim, dim, GL_RGBA, GL_FLOAT, lut);
}
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2012-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
// gdcm
#include <gdcmUIDGenerator.h>
// fwTools
#include <fwTools/dateAndTime.hpp>
#include "gdcmIO/writer/DicomStudyWriter.hpp"
#include "gdcmIO/helper/GdcmHelper.hpp"
namespace gdcmIO
{
namespace writer
{
//------------------------------------------------------------------------------
DicomStudyWriter::DicomStudyWriter():
m_studyID("1")
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
DicomStudyWriter::~DicomStudyWriter()
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
void DicomStudyWriter::write(::gdcm::DataSet & a_gDs)
{
SLM_TRACE_FUNC();
::fwData::Study::csptr study = this->getConcreteObject();
SLM_ASSERT("fwData::Study not instanced", study);
// Study's date
helper::GdcmData::setTagValue<0x0008,0x0020>(study->getDate(), a_gDs); // Type 2
OSLM_TRACE("Study's date : "<<study->getDate());
// Study's time
helper::GdcmData::setTagValue<0x0008,0x0030>(study->getTime(), a_gDs); // Type 2
OSLM_TRACE("Study's time : "<<study->getTime());
// Study 's accession number
helper::GdcmData::setTagValue<0x0008,0x0050>("", a_gDs); // Type 2
OSLM_TRACE("Study's accession number : "<<"");
// Study's description
helper::GdcmData::setTagValue<0x0008,0x1030>(study->getDescription(), a_gDs); // Type 3
OSLM_TRACE("Study's description : "<<study->getDescription());
// Study's UID
std::string studyUID = study->getUID();
if (studyUID.empty())
{// Generate an UID
::gdcm::UIDGenerator gUIDgen;
studyUID = gUIDgen.Generate();
}
helper::GdcmData::setTagValue<0x0020,0x000d>(studyUID, a_gDs); // Type 1
OSLM_TRACE("Study's UID : " << studyUID);
// Study's ID
helper::GdcmData::setTagValue<0x0020,0x0010>(m_studyID, a_gDs); // Type 2
OSLM_TRACE("Study's ID : " << m_studyID);
//***** Set the DicomInstance *****//
::boost::shared_ptr< DicomInstance > dicomInstance = this->getDicomInstance();
dicomInstance->setStudyInstanceUID( studyUID ); // Store study UID to be used and written later
dicomInstance->setModality( study->getModality() ); // Store modality to be used and written later
dicomInstance->setInstitutionName( study->getHospital() ); // Store hospital name to be used and written later
}
//------------------------------------------------------------------------------
void DicomStudyWriter::setStudyID(const unsigned int a_studyID)
{
this->m_studyID = ::fwTools::getString(a_studyID);
}
} // namespace writer
} // namespace gdcmIO
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
const int maxn = 110;
int n,k,f[maxn][maxn],a[maxn][maxn];
int dfs(int x,int y) {
if (f[x][y]) return f[x][y];
for (int i = x-k;i <= x+k; i++)
if (i >= 0 && i < n && a[x][y] < a[i][y]) f[x][y] = max(f[x][y],dfs(i,y));
for (int i = y-k;i <= y+k; i++)
if (i >= 0 && i < n && a[x][y] < a[x][i]) f[x][y] = max(f[x][y],dfs(x,i));
f[x][y] += a[x][y];
return f[x][y];
}
int main() {
while (scanf("%d%d",&n,&k) != EOF) {
if (n == -1 && k == -1) break;
memset(f,0,sizeof(f));
for (int i = 0;i < n; i++)
for (int j = 0;j < n; j++) scanf("%d",&a[i][j]);
printf("%d\n",dfs(0,0));
}
return 0;
}
|
#include "embedding.h"
#include "mask.h"
Embedding :: Embedding(ostream& os)
: output_stream(os)
{
}
Full_Embedding :: Full_Embedding(const Data& d, const uint p, const uint num_m, ostream& os)
: Embedding(os), data(d), pmax(p), high_moments(num_m)
{
Mask mask(data.Inputs());
// mask.Set_Mask("00000000001");
while (!mask.Empty()) {
Data embed_data(data, mask);
Gamma gamma(embed_data, pmax, high_moments);
output_stream << mask << "," << gamma << endl;
mask.Decrement();
}
}
River_Embedding :: River_Embedding(const Data& d, const uint p, const uint num_m, ostream& os)
: Embedding(os), data(d), pmax(p), high_moments(num_m)
{
cout << "1" << endl;
Mask mask(data.Inputs());
cout << "2" << endl;
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000001000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
//00000000000000000000
// mask.Set_Mask("111111111111111111111111111111111111111111111111111111111111111111111111111");
// Data embed_data(data, mask);
cout << "3" << endl;
// Gamma gamma(embed_data, pmax, high_moments);
cout << "4" << endl;
// output_stream << mask << "," << gamma << endl;
for (unsigned int j = 0; j < 16; j++) {
for (unsigned int i = 0; i < 20; i++) {
stringstream m;
for (unsigned int k = 0; k < j; k++) {
m << "00000000000000000000";
}
for (unsigned int k = 0; k < i; k++) {
m << "0";
}
m << "1";
for (unsigned int k = i+1; k < 20; k++) {
m << "0";
}
for (unsigned int k = j+1; k < 16; k++) {
m << "00000000000000000000";
}
m << "00000000000000000000";
cout << m << endl;
mask.Set_Mask(m.str().c_str());
Data embed_data(data, mask);
Gamma gamma(embed_data, pmax, high_moments);
// os << embed_data << endl;
output_stream << mask << "," << gamma << endl;
}
}
}
|
// Created on : Sat May 02 12:41:15 2020
// Created by: Irina KRYLOVA
// Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V3.0
// Copyright (c) Open CASCADE 2020
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepKinematics_PairRepresentationRelationship_HeaderFile_
#define _StepKinematics_PairRepresentationRelationship_HeaderFile_
#include <Standard.hxx>
#include <StepGeom_GeometricRepresentationItem.hxx>
#include <TCollection_HAsciiString.hxx>
#include <StepRepr_RepresentationOrRepresentationReference.hxx>
#include <StepRepr_RepresentationRelationshipWithTransformation.hxx>
DEFINE_STANDARD_HANDLE(StepKinematics_PairRepresentationRelationship, StepGeom_GeometricRepresentationItem)
//! Representation of STEP entity PairRepresentationRelationship
class StepKinematics_PairRepresentationRelationship : public StepGeom_GeometricRepresentationItem
{
public :
//! default constructor
Standard_EXPORT StepKinematics_PairRepresentationRelationship();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theRepresentationItem_Name,
const Handle(TCollection_HAsciiString)& theRepresentationRelationship_Name,
const Standard_Boolean hasRepresentationRelationship_Description,
const Handle(TCollection_HAsciiString)& theRepresentationRelationship_Description,
const StepRepr_RepresentationOrRepresentationReference& theRepresentationRelationship_Rep1,
const StepRepr_RepresentationOrRepresentationReference& theRepresentationRelationship_Rep2,
const StepRepr_Transformation& theRepresentationRelationshipWithTransformation_TransformationOperator);
//! Returns data for supertype RepresentationRelationshipWithTransformation
Standard_EXPORT Handle(StepRepr_RepresentationRelationshipWithTransformation) RepresentationRelationshipWithTransformation() const;
//! Sets data for supertype RepresentationRelationshipWithTransformation
Standard_EXPORT void SetRepresentationRelationshipWithTransformation (const Handle(StepRepr_RepresentationRelationshipWithTransformation)& theRepresentationRelationshipWithTransformation);
DEFINE_STANDARD_RTTIEXT(StepKinematics_PairRepresentationRelationship, StepGeom_GeometricRepresentationItem)
private:
Handle(StepRepr_RepresentationRelationshipWithTransformation) myRepresentationRelationshipWithTransformation; //!< supertype
};
#endif // _StepKinematics_PairRepresentationRelationship_HeaderFile_
|
#ifndef __QFB_NETWORK_H__
#define __QFB_NETWORK_H__
#include <QObject>
#include <QVariant>
#include <QSettings>
#include <QJsonArray>
#include <QJsonObject>
#include <QByteArray>
#include <QNetworkReply>
#include "network_manager.h"
/**
* The responsability of this class is to make all network related duties.
* It has a minimum logic to determine if a request has failed, in addition, it stores
* the data needed in order to continue doing requests.
*/
class QFbNetwork : public QObject {
Q_OBJECT
public:
QFbNetwork(QObject *parent = 0);
/** Initialices facebook variables (and cookies):
* * requestId
* * identifier
* * jsDatr -> this is going to be a cookie (datr)
* * lsd
*/
void init();
/** Performs Login, init must be called previously.
* init has to be called before!.
* This method sets the cookies ( datr, c_user, xs, csm, s, lu )
* @param email: fb email
* @param pass: fb password
*/
void login(const QString &email, const QString &pass);
/** Gets lasts conversations (MessengerMount) and friend list (InitialChatFriendsList)
* y DTSGInitialData.
* In order to work, login has to be called before. It needs the cookies already setted: datr, c_user, xs, csm, s, lu.
*
* This method provides contact list (only user id) and recent coversations.
* It sets the `dtsg` value
*/
void getBasicInformation();
void getUserInfo(const QJsonArray& ids);
void getThreadInfo(const QString& id, int offset=0, int limit=20);
void sendMessages(const QString& id, const QString& msg);
void pull();
/**
* @return true: if it is setted correctly, false if not
*/
bool setConfigurationValue(const QString& name, const QString& value);
signals:
void initResponse(bool error, QString desc);
void loginResponse(bool error, QString desc);
/** Data: {
* conversations: []
* friendsList: []
* }
*/
void getBasicInformationResponse(bool error, QJsonValue data);
/**
* data: { <user id>: {}, ... }
*/
void getUserInfoResponse(bool error, QJsonValue data);
void getThreadInfoResponse(bool error, QJsonValue data);
void sendMessagesResponse(bool error, QJsonValue data);
void pullResponse(bool error, QJsonValue data);
void pullEnd();
/** Signaled when a configuration value (requestId, identifier, datr, lsd, c_user, xs, csm, s, lu, dtsg) is created
*/
void newConfigurationValue(const QString& name, const QString& value);
protected slots:
void initFinished(QNetworkReply::NetworkError, const QByteArray&);
void loginFinished(QNetworkReply::NetworkError, const QByteArray&);
void getBasicInformationFinished(QNetworkReply::NetworkError, const QByteArray&);
void getUserInfoFinished(QNetworkReply::NetworkError, const QByteArray&);
void getThreadInfoFinished(QNetworkReply::NetworkError, const QByteArray&);
void sendMessagesFinished(QNetworkReply::NetworkError, const QByteArray&);
void pullMessage(const QByteArray&);
void pullFinished();
protected:
NetworkManager man;
QString getMatch(const QString& regexp, const QString& text);
void getRequestId(const QString&);
void getIdentifier(const QString&);
void getJsDatr(const QString&);
void getLsd(const QString&);
QJsonArray parseLastConversations(const QString& response);
QJsonArray parseInitialChatFriendsList(const QString& response);
void parseDtsg(const QString& response);
QJsonValue parseProfiles(const QString& response);
QJsonValue parseThread(const QString& response);
QString generateCb();
QString generateSessionId();
QString requestId;
QString identifier;
QString lsd;
QString dtsg;
QString userId;
QString pullSeq;
QString sessionId;
QString stickyToken;
QString stickyPool;
};
#endif
|
#include <iostream>
#include<algorithm>
#include<clocale>
using namespace std;
int main()
{
setlocale(LC_ALL, "Ukrainian");//додаємо українську мову
int N, M; //ініціалзуємо к-ксть членів множин A i B
cout << "Введiть кiлькiсть елементiв множини А: "; //Вводимо змінну
cin >> N; //N
cout << "Введiть кiлькiсть елементiв множини B: "; //і
cin >> M; //M з клавіатури
char *arr1=new char[N], *arr2=new char[M]; //створюємо масиви множин A i B
cout << "Введiть множину A: ";
for (int i = 0; i < N; i++) { //
cin >> arr1[i]; //вводимо множину A з клавіатури
} //
cout << "Введiть множину B: ";
for (int i = 0; i < M; i++) { //
cin >> arr2[i]; //вводимо множину B з клавіатури
} //
sort(&arr1[0], &arr1[N]); //сортуємо масив arr1
sort(&arr2[0], &arr2[M]); //сортуємо масив arr2
cout << "A перетин з B: ";
int F = 0;
char *arr3=new char[F]; //створюємо множину A^B
for (int i = 0; i < N; i++) { //запускаєм цикл з 0 по N
for (int j = 0; j < M; j++) { //запускаєм ще один цикл з 0 по M
if (arr1[i] == arr2[j]) { //перевіряємо чи arr1[i] дорівнює arr2[j]
arr3[F] = arr1[i]; //якщо в цих двох масивах є однакові елементи ми присвоюємо
F++; //arr3 значення arr1[i] і збільшуємо F на 1
}
}
}
sort(&arr3[0], &arr3[F]); //сортуємо масив arr3
for (int i = 0; i < F; i++) { //
cout << arr3[i] << " "; //виводимо множину A^B
} //
if (F == 0) {
cout << "Перетину немає";
}
cout << endl << "Потужнiсть множини перетину множин A i B: "<<F;
int U = N; //створюємо множину універсуму
char *arr4=new char[U]; //яка має таку ж к-ксть членів як множина A
for (int i = 0; i < U; i++) { //
arr4[i] = arr1[i]; //спершу у множину універсуму вводимо всі члени множини A
} //
int check = 0; //створюємо змінну check яку ми використаємо для перевірки
for (int j = 0; j < M; j++) { //створюємо цикл перевірки
for (int f = 0; f < F; f++) { //створюємо цикл перебору
if (arr2[j] != arr3[f]) { //якщо arr2[j] не дорівнює arr3[f]
check++; //змінна check збільшується на 1
} //
} //
if (check == F) { //якщо check дорівнює F це означає що член масиву arr2 не дорівнював
arr4[U] = arr2[j]; //жодному члену масиву arr3 отже його можна записати до універсуму
U++; //
} //
check = 0; //
} //
sort(&arr4[0], &arr4[U]); //сортуємо універсум
//cout << endl << "Універсум: ";
/*for (int i = 0; i < U; i++) {
cout << arr4[i] << " ";
}*/
cout <<endl<< "Симетрична рiзниця A i B: ";
int T = 0,check1=0;
char *arr5 = new char[U-F];
for (int i = 0; i <U ; i++) {
for (int j = 0; j < F; j++) {
if (arr4[i] != arr3[j]) { //
check1++; //
} //
} //
if (check1 == F) { //
arr5[T] = arr4[i]; //
T++; //
} //
check1 = 0; //
}
if (T == 0) {
cout << "Множини однаковi";
}
for (int i = 0; i <T; i++) {
cout << arr5[i] << " ";
}
cout << endl << "Потужнiсть множини симетричної рiзницi множин A i B: " << T<<endl<<endl<<endl;
return 0;
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
const long long LINF = (1e15);
const int INF = (1<<27);
#define EPS 1e-6
const int MOD = 1000000007;
using namespace std;
class GooseTattarrattatDiv1 {
public:
bool visited[55];
string conn,S;
int N;
void rec(int i) {
if (!visited[i]) {
visited[i] = true;
conn.push_back(S[i]);
for (int j=0; j<N; ++j) {
if (S[i] == S[j] || j == N - i - 1 ) {
rec(j);
}
}
}
}
int calc() {
int n = (int)conn.size(), m = 0;
for (char s : conn)
m = max(m, (int)count(conn.begin(), conn.end(), s));
return n - m;
}
int getmin(string S) {
memset(visited, false, sizeof(visited));
this->N = (int)S.size();
this->S = S;
int res = 0;
for (int i=0; i<N; ++i) if (!visited[i]) {
conn = "";
rec(i);
res += calc();
}
return res;
}
// 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(); if ((Case == -1) || (Case == 4)) test_case_4(); }
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 int &Expected, const int &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() { string Arg0 = "geese"; int Arg1 = 2; verify_case(0, Arg1, getmin(Arg0)); }
void test_case_1() { string Arg0 = "tattarrattat"; int Arg1 = 0; verify_case(1, Arg1, getmin(Arg0)); }
void test_case_2() { string Arg0 = "xyyzzzxxx"; int Arg1 = 2; verify_case(2, Arg1, getmin(Arg0)); }
void test_case_3() { string Arg0 = "xrepayuyubctwtykrauccnquqfuqvccuaakylwlcjuyhyammag"; int Arg1 = 11; verify_case(3, Arg1, getmin(Arg0)); }
void test_case_4() { string Arg0 = "abaabb"; int Arg1 = 3; verify_case(4, Arg1, getmin(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
GooseTattarrattatDiv1 ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include <sys/time.h>
#include <time.h>
#include <string>
#include <iostream>
#include <sys/epoll.h>
void usleep(uint64_t usec) {
struct timeval tv;
tv.tv_sec = usec / 1000000;
tv.tv_usec = usec % 1000000;
int epfd = epoll_create(1);
epoll_wait(epfd, NULL, 1, &tv);
// select(0, nullptr, nullptr, nullptr, &tv);
}
/*
void usleep2(uint64_t usec) {
struct epoll_event;
int epfd;
struct timeval tv;
epfd=epoll_create(1);
int nfds = epoll_wait(epfd, NULL, 1, 1000);
gettimeofday(&tv , NULL);
}
*/
void print() {
int count = 10;
while (count > 0) {
std::cout << "time is arrive." << std::endl;
usleep(5000000);
count--;
}
}
int main() {
print();
}
|
/*
* File: Tower.cpp
* Author: mohammedheader
*
* Created on November 23, 2014, 6:01 PM
*/
#include "HelloWorldScene.h"
#include "Tower.h"
USING_NS_CC;
Tower* Tower::create(HelloWorld* game, cocos2d::Vec2 location) {
Tower *tower = new (std::nothrow) Tower();
if (tower && tower->init(game,location))
{
tower->autorelease();
return tower;
}
CC_SAFE_DELETE(tower);
return nullptr;
}
Tower* Tower::init(HelloWorld* game, cocos2d::Vec2 location) {
theGame = game;
attackRange = 70;
damage = 10;
fireRate = 1;
mySprite = Sprite::create("tower.png");
addChild(mySprite);
mySprite->setPosition(location);
theGame->addChild(this);
scheduleUpdate();
return this;
}
void Tower::draw(Renderer* renderer, const cocos2d::Mat4& transform, unsigned int flags) {
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(Tower::onDrawPrimitives, this, transform);
renderer->addCommand(&_customCommand);
}
void Tower::update(float dt) {
if (chosenEnemy){
//We make it turn to target the enemy chosen
Vec2 normalized = ccpNormalize(Vec2(chosenEnemy->getSpritePosition().x-mySprite->getPositionX(),
chosenEnemy->getSpritePosition().y-mySprite->getPositionY()));
mySprite->setRotation(CC_RADIANS_TO_DEGREES(atan2(normalized.y,-normalized.x))+90);
if(! theGame->isCirclesCollide(Circle{mySprite->getPosition(),attackRange},Circle{chosenEnemy->getSpritePosition(),1}))
{
//lostSightOfEnemy();
chosenEnemy =nullptr;
unschedule(schedule_selector(Tower::shootWeapon));
}
} else {
for(auto enemy : theGame->getEnemies())
{
if(theGame->isCirclesCollide(Circle{mySprite->getPosition(),attackRange},Circle{enemy->getSpritePosition(),1}))
{
chosenEnemy = enemy;
schedule(schedule_selector(Tower::shootWeapon),fireRate);
break;
}
}
}
}
void Tower::onDrawPrimitives(const Mat4& transform) {
kmGLPushMatrix();
kmGLLoadMatrix(&transform);
// DrawPrimitives::setDrawColor4B(255, 255, 255, 255);
// DrawPrimitives::drawCircle(mySprite->getPosition(), attackRange, 360, 30, false);
}
void Tower::shootWeapon(float dt) {
auto bullet = Sprite::create("bullet.png");
bullet->setPosition(mySprite->getPosition());
theGame->addChild(bullet);
bullet->runAction(Sequence::create(
MoveTo::create(0.1,chosenEnemy->getSpritePosition()),
CallFunc::create(bullet, callfunc_selector(Sprite::removeFromParent)),
CallFunc::create(this, callfunc_selector(Tower::damageEnemy)),
NULL
));
}
void Tower::targetKilled() {
chosenEnemy = nullptr;
unschedule(schedule_selector(Tower::shootWeapon));
}
void Tower::damageEnemy() {
}
|
#include "field.h"
class test
{
int qqq;
};
Field::Field(QString mas[WIDTH][HEIGHT], int width, int height)
{
for(int i=0; i<width; i++)
for(int j=0; j<height; j++)
field[i][j].type=mas[i][j];
width_in_cells=width;
height_in_cells=height;
}
void Field::draw(float width, float height, QGraphicsScene *scene)
{
float optimal_height=height/height_in_cells;
float optimal_width=width/width_in_cells;
float size=optimal_height>optimal_width?optimal_width:optimal_height;
for(int i=0; i<width_in_cells; i++)
for(int j=0; j<height_in_cells; j++)
{
if(field[i][j].type=="abyss")
scene->addRect(i*size, j*size, size, size, QPen(Qt::black), QBrush(Qt::black));
else if(field[i][j].type=="empty")
scene->addRect(i*size, j*size, size, size, QPen(Qt::black), QBrush(Qt::white));
}
//scene->addEllipse(size/4, size/4, size/2, size/2, QPen(Qt::black), QBrush(Qt::red));//( , , , , border, filling)
}
|
#define OurCode 0
#if OurCode
#include <iostream>
#include <vector>
using namespace std;
struct vec2{
int x, y;
};
void displayPathtoPrincess(int n, char grid[3*3]){
vec2 pIndex; pIndex.x = pIndex.y = -1;
vec2 bIndex; bIndex.x = bIndex.y = 1;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
if (grid[i * n + j] == 'P'){
pIndex.x = i;
pIndex.y = j;
}
}
}
if (pIndex.x == -1){
cout << "The princess is in another castle" << endl;
exit(0);
}
vec2 path;
path.x = pIndex.x - bIndex.x;
path.y = pIndex.y - bIndex.y;
cout << " X: " << path.x << " Y: " << path.y;
}
int main(void) {
// oneDim[row * columns + column]
const int N = 3;
char grid[N* N];
for (int i = 0; i < N*N; i++){
grid[i] = '-';
}
// Left Top Corner
//grid[0] = 'x';
// Right top corner
//grid[0 * N + (N - 1)] = 'R';
// Right Bottom corner
grid[(N-1) * N + (N-1)] = 'P';
// Bot Position
grid[1 * N + 1] = 'M';
// Left Bottom corner
//grid[(N - 1) * N + 0] = 'P';
for (int i = 0; i < N * N; i++){
if (i % 3 == 0)
cout << endl;
cout << grid[i];
}
displayPathtoPrincess(N, grid);
cout << endl;
system("PAUSE");
return 0;
}
#else
// Hacker Rank
#include <iostream>
#include <vector>
using namespace std;
struct vec2{
int x, y;
};
void displayPathtoPrincess(int n, vector <char*> grid){
// Declare 2 vectors to store the position of the bot and princess
vec2 pIndex; pIndex.x = pIndex.y = -1;
vec2 bIndex; bIndex.x = bIndex.y = -1;
// Scan the board and get the bot and princess positions
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (grid[i][j] == 'p'){
pIndex.x = i;
pIndex.y = j;
}
else if (grid[i][j] == 'm'){
bIndex.x = i;
bIndex.y = j;
}
}
}
// Check bot and princess exist in the castle
if (pIndex.x == -1 ){
cout << "The princess is in another castle" << endl;
exit(0);
}
if (bIndex.x == -1){
cout << "There is no bot in this game !" << endl;
exit(0);
}
// Calculate the translation between the bot and princess
vec2 path;
path.x = pIndex.x - bIndex.x;
path.y = pIndex.y - bIndex.y;
// Print out the result of the bot's moves to reach to princess
while (path.x != 0){
if (path.x > 0){
cout << "DOWN" << endl;
path.x--;
}
else if (path.x < 0){
cout << "UP" << endl;
path.x++;
}
}
while (path.y != 0){
if (path.y > 0){
cout << "RIGHT" << endl;
path.y--;
}
else if (path.y < 0){
cout << "LEFT" << endl;
path.y++;
}
}
}
int main(void) {
int m;
vector <char*> grid;
cin >> m;
for (int i = 0; i<m; i++) {
char* s = new char[];
cin >> s;
grid.push_back(s);
}
displayPathtoPrincess(m, grid);
system("PAUSE");
return 0;
}
#endif
|
#include <bits/stdc++.h>
using namespace std;
char maze[51][51];
int main(){
int h, w;
cin >> h >> w;
for(int i=0; i<h; i++){
for(int j=0; j<w; j++) cin >> maze[i][j];
}
bool ans = true;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
if(maze[i][j] == '#'){
bool flag = false;
for(int k=0; k<4; k++){
int ny = i + dy[k];
int nx = j + dx[k];
if(0 <= nx && nx < w && 0 <= ny && ny < h && maze[ny][nx] == '#') flag = true;
}
if(flag == false) ans = false;
}
}
}
if(ans) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
|
#include <iostream>
using namespace std;
int main()
{
float nota_ve;
float nota_vc;
float p_vf;
while(1)
{
cout << "insira sua media de ve:\n";
cin >> nota_ve;
if(nota_ve <= 10)
{
cout << "Insira sua media de vc:\n";
cin >> nota_vc;
if(nota_vc <= 10)
{
p_vf = (5 - (nota_ve + nota_vc) / 4) * 2;
if(p_vf >= 4)
{
cout << "voce precisa tirar a seguinte nota na vf:\n" << p_vf;
}
else
{
cout << "voce precisa tirar 4 na vf\n";
}
break;
}
else
{
cout << "insina um valor menor que 10\n";
}
}
else
{
cout << "Insira um valor menor que 10\n";
}
}
return 0;
}
|
#include "aluno.h"
Aluno::Aluno()
{
}
void Aluno::setNome(QString a)
{
nome=a;
}
void Aluno::setMatricula(QString b)
{
matricula=b;
}
void Aluno::setCurso()
{
QString temp;
temp[0]=matricula[5];
temp[1]=matricula[6];
curso=temp.toInt();
}
QString Aluno::getNome()
{
return nome;
}
QString Aluno::getMatricula()
{
return matricula;
}
int Aluno::getCurso()
{
return curso;
}
bool Aluno::veterano()
{
QString temp;
temp[0]=matricula[0];
temp[1]=matricula[1];
temp[2]=matricula[2];
temp[3]=matricula[3];
temp[4]=matricula[4];
if(temp=="20182"){
return false;
}
else{return true;}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 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>
#ifdef DOM_EXTENSIONS_TAB_API_SUPPORT
#include "modules/dom/src/extensions/domtabapicachedobject.h"
#include "modules/dom/src/extensions/domextension_background.h"
#include "modules/dom/src/extensions/domtabapicache.h"
/* virtual */
DOM_TabApiCachedObject::~DOM_TabApiCachedObject()
{
if (DOM_ExtensionBackground* background = m_extension_support->GetBackground())
background->GetTabApiCache()->OnCachedObjectDestroyed(this);
}
#endif // DOM_EXTENSIONS_TAB_API_SUPPORT
|
///////////////////////////////////////////////////////////////////////////////
//
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is MP4v2.
//
// The Initial Developer of the Original Code is Kona Blend.
// Portions created by Kona Blend are Copyright (C) 2008.
// Portions created by David Byron are Copyright (C) 2010.
// All Rights Reserved.
//
// Contributors:
// Kona Blend, kona8lend@@gmail.com
// David Byron, dbyron@dbyron.com
//
///////////////////////////////////////////////////////////////////////////////
#include "util/impl.h"
namespace mp4v2 { namespace util {
using namespace itmf;
///////////////////////////////////////////////////////////////////////////////
class ArtUtility : public Utility
{
private:
enum ArtLongCode {
LC_ART_ANY = _LC_MAX,
LC_ART_INDEX,
LC_LIST,
LC_ADD,
LC_REMOVE,
LC_REPLACE,
LC_EXTRACT,
};
public:
ArtUtility( int, char** );
protected:
// delegates implementation
bool utility_option( int, bool& );
bool utility_job( JobContext& );
private:
struct ArtType {
string name;
string ext;
vector<string> cwarns; // compatibility warnings
string cerror; // compatibility error
};
bool actionList ( JobContext& );
bool actionAdd ( JobContext& );
bool actionRemove ( JobContext& );
bool actionReplace ( JobContext& );
bool actionExtract ( JobContext& );
bool extractSingle( JobContext&, const CoverArtBox::Item&, uint32_t );
private:
Group _actionGroup;
Group _parmGroup;
bool (ArtUtility::*_action)( JobContext& );
string _artImageFile;
uint32_t _artFilter;
};
///////////////////////////////////////////////////////////////////////////////
ArtUtility::ArtUtility( int argc, char** argv )
: Utility ( "mp4art", argc, argv )
, _actionGroup ( "ACTIONS" )
, _parmGroup ( "ACTION PARAMETERS" )
, _action ( NULL )
, _artFilter ( numeric_limits<uint32_t>::max() )
{
// add standard options which make sense for this utility
_group.add( STD_OPTIMIZE );
_group.add( STD_DRYRUN );
_group.add( STD_KEEPGOING );
_group.add( STD_OVERWRITE );
_group.add( STD_FORCE );
_group.add( STD_QUIET );
_group.add( STD_DEBUG );
_group.add( STD_VERBOSE );
_group.add( STD_HELP );
_group.add( STD_VERSION );
_group.add( STD_VERSIONX );
_parmGroup.add( "art-any", false, LC_ART_ANY, "act on all covr-boxes (default)" );
_parmGroup.add( "art-index", true, LC_ART_INDEX, "act on covr-box index IDX", "IDX" );
_groups.push_back( &_parmGroup );
_actionGroup.add( "list", false, LC_LIST, "list all covr-boxes" );
_actionGroup.add( "add", true, LC_ADD, "add covr-box from IMG file", "IMG" );
_actionGroup.add( "replace", true, LC_REPLACE, "replace covr-box with IMG file", "IMG" );
_actionGroup.add( "remove", false, LC_REMOVE, "remove covr-box" );
_actionGroup.add( "extract", false, LC_EXTRACT, "extract covr-box" );
_groups.push_back( &_actionGroup );
_usage = "[OPTION]... ACTION file...";
_description =
// 79-cols, inclusive, max desired width
// |----------------------------------------------------------------------------|
"\nFor each mp4 (m4a) file specified, perform the specified ACTION. An action"
"\nmust be specified. Some options are not applicable for some actions.";
}
///////////////////////////////////////////////////////////////////////////////
bool
ArtUtility::actionAdd( JobContext& job )
{
File in( _artImageFile, File::MODE_READ );
if( in.open() )
return herrf( "unable to open %s for read: %s\n", _artImageFile.c_str(), sys::getLastErrorStr() );
const uint32_t max = numeric_limits<uint32_t>::max();
if( in.size > max )
return herrf( "file too large: %s (exceeds %u bytes)\n", _artImageFile.c_str(), max );
CoverArtBox::Item item;
item.size = static_cast<uint32_t>( in.size );
item.buffer = static_cast<uint8_t*>( malloc( item.size ));
item.autofree = true;
File::Size nin;
if( in.read( item.buffer, item.size, nin ))
return herrf( "read failed: %s\n", _artImageFile.c_str() );
in.close();
verbose1f( "adding %s -> %s\n", _artImageFile.c_str(), job.file.c_str() );
if( dryrunAbort() )
return SUCCESS;
job.fileHandle = MP4Modify( job.file.c_str() );
if( job.fileHandle == MP4_INVALID_FILE_HANDLE )
return herrf( "unable to open for write: %s\n", job.file.c_str() );
if( CoverArtBox::add( job.fileHandle, item ))
return herrf( "unable to add covr-box\n" );
return SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
bool
ArtUtility::actionExtract( JobContext& job )
{
job.fileHandle = MP4Read( job.file.c_str() );
if( job.fileHandle == MP4_INVALID_FILE_HANDLE )
return herrf( "unable to open for read: %s\n", job.file.c_str() );
// single-mode
if( _artFilter != numeric_limits<uint32_t>::max() ) {
CoverArtBox::Item item;
if( CoverArtBox::get( job.fileHandle, item, _artFilter ))
return herrf( "unable to retrieve covr-box (index=%d): %s\n", _artFilter, job.file.c_str() );
return extractSingle( job, item, _artFilter );
}
// wildcard-mode
CoverArtBox::ItemList items;
if( CoverArtBox::list( job.fileHandle, items ))
return herrf( "unable to fetch list of covr-box: %s\n", job.file.c_str() );
bool onesuccess = false;
const CoverArtBox::ItemList::size_type max = items.size();
for( CoverArtBox::ItemList::size_type i = 0; i < max; i++ ) {
bool rv = extractSingle( job, items[i], (uint32_t)i );
if( !rv )
onesuccess = true;
if( !_keepgoing && rv )
return FAILURE;
}
return _keepgoing ? onesuccess : SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
bool
ArtUtility::actionList( JobContext& job )
{
ostringstream report;
const int widx = 3;
const int wsize = 8;
const int wtype = 9;
const string sep = " ";
if( _jobCount == 0 ) {
report << setw(widx) << right << "IDX" << left
<< sep << setw(wsize) << right << "BYTES" << left
<< sep << setw(8) << "CRC32"
<< sep << setw(wtype) << "TYPE"
<< sep << setw(0) << "FILE"
<< '\n';
report << setfill('-') << setw(70) << "" << setfill(' ') << '\n';
}
job.fileHandle = MP4Read( job.file.c_str() );
if( job.fileHandle == MP4_INVALID_FILE_HANDLE )
return herrf( "unable to open for read: %s\n", job.file.c_str() );
CoverArtBox::ItemList items;
if( CoverArtBox::list( job.fileHandle, items ))
return herrf( "unable to get list of covr-box: %s\n", job.file.c_str() );
int line = 0;
const CoverArtBox::ItemList::size_type max = items.size();
for( CoverArtBox::ItemList::size_type i = 0; i < max; i++ ) {
if( _artFilter != numeric_limits<uint32_t>::max() && _artFilter != i )
continue;
CoverArtBox::Item& item = items[i];
const uint32_t crc = crc32( item.buffer, item.size );
report << setw(widx) << right << i
<< sep << setw(wsize) << item.size
<< sep << setw(8) << setfill('0') << hex << crc << setfill(' ') << dec
<< sep << setw(wtype) << left << enumBasicType.toString( item.type );
if( line++ == 0 )
report << sep << setw(0) << job.file;
report << '\n';
}
verbose1f( "%s", report.str().c_str() );
return SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
bool
ArtUtility::actionRemove( JobContext& job )
{
job.fileHandle = MP4Modify( job.file.c_str() );
if( job.fileHandle == MP4_INVALID_FILE_HANDLE )
return herrf( "unable to open for write: %s\n", job.file.c_str() );
if( _artFilter == numeric_limits<uint32_t>::max() )
verbose1f( "removing covr-box (all) from %s\n", job.file.c_str() );
else
verbose1f( "removing covr-box (index=%d) from %s\n", _artFilter, job.file.c_str() );
if( dryrunAbort() )
return SUCCESS;
if( CoverArtBox::remove( job.fileHandle, _artFilter ))
return herrf( "remove failed\n" );
return SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
bool
ArtUtility::actionReplace( JobContext& job )
{
File in( _artImageFile, File::MODE_READ );
if( in.open() )
return herrf( "unable to open %s for read: %s\n", _artImageFile.c_str(), sys::getLastErrorStr() );
const uint32_t max = numeric_limits<uint32_t>::max();
if( in.size > max )
return herrf( "file too large: %s (exceeds %u bytes)\n", _artImageFile.c_str(), max );
CoverArtBox::Item item;
item.size = static_cast<uint32_t>( in.size );
item.buffer = static_cast<uint8_t*>( malloc( item.size ));
item.autofree = true;
File::Size nin;
if( in.read( item.buffer, item.size, nin ))
return herrf( "read failed: %s\n", _artImageFile.c_str() );
in.close();
if( _artFilter == numeric_limits<uint32_t>::max() )
verbose1f( "replacing %s -> %s (all)\n", _artImageFile.c_str(), job.file.c_str() );
else
verbose1f( "replacing %s -> %s (index=%d)\n", _artImageFile.c_str(), job.file.c_str(), _artFilter );
if( dryrunAbort() )
return SUCCESS;
job.fileHandle = MP4Modify( job.file.c_str() );
if( job.fileHandle == MP4_INVALID_FILE_HANDLE )
return herrf( "unable to open for write: %s\n", job.file.c_str() );
if( CoverArtBox::set( job.fileHandle, item, _artFilter ))
return herrf( "unable to add covr-box: %s\n", job.file.c_str() );
return SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
bool
ArtUtility::extractSingle( JobContext& job, const CoverArtBox::Item& item, uint32_t index )
{
// compute out filename
string out_name = job.file;
FileSystem::pathnameStripExtension( out_name );
ostringstream oss;
oss << out_name << ".art[" << index << ']';
// if implicit we try to determine type by inspecting data
BasicType bt = item.type;
if( bt == BT_IMPLICIT )
bt = computeBasicType( item.buffer, item.size );
// add file extension appropriate for known covr-box types
switch( bt ) {
case BT_GIF: oss << ".gif"; break;
case BT_JPEG: oss << ".jpg"; break;
case BT_PNG: oss << ".png"; break;
case BT_BMP: oss << ".bmp"; break;
default:
oss << ".dat";
break;
}
out_name = oss.str();
verbose1f( "extracting %s (index=%d) -> %s\n", job.file.c_str(), index, out_name.c_str() );
if( dryrunAbort() )
return SUCCESS;
File out( out_name, File::MODE_CREATE );
if( openFileForWriting( out ))
return FAILURE;
File::Size nout;
if( out.write( item.buffer, item.size, nout ))
return herrf( "write failed: %s\n", out_name.c_str() );
out.close();
return SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
bool
ArtUtility::utility_job( JobContext& job )
{
if( !_action )
return herrf( "no action specified\n" );
return (this->*_action)( job );
}
///////////////////////////////////////////////////////////////////////////////
bool
ArtUtility::utility_option( int code, bool& handled )
{
handled = true;
switch( code ) {
case LC_ART_ANY:
_artFilter = numeric_limits<uint32_t>::max();
break;
case LC_ART_INDEX:
{
istringstream iss( prog::optarg );
iss >> _artFilter;
if( iss.rdstate() != ios::eofbit )
return herrf( "invalid cover-art index: %s\n", prog::optarg );
break;
}
case LC_LIST:
_action = &ArtUtility::actionList;
break;
case LC_ADD:
_action = &ArtUtility::actionAdd;
_artImageFile = prog::optarg;
if( _artImageFile.empty() )
return herrf( "invalid image file: empty-string\n" );
break;
case LC_REMOVE:
_action = &ArtUtility::actionRemove;
break;
case LC_REPLACE:
_action = &ArtUtility::actionReplace;
_artImageFile = prog::optarg;
if( _artImageFile.empty() )
return herrf( "invalid image file: empty-string\n" );
break;
case LC_EXTRACT:
_action = &ArtUtility::actionExtract;
break;
default:
handled = false;
break;
}
return SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
}} // namespace mp4v2::util
///////////////////////////////////////////////////////////////////////////////
|
#include <stdio.h>
int main() {
int ht;
float vh, pd, sb, td, sl;
printf("Digite a quantidade de horas trabalhadas: ");
scanf("%d", &ht);
printf("Digite o valor por hora trabalhada: ");
scanf("%f", &vh);
printf("Digite o percentual de desconto: ");
scanf("%f", &pd);
sb = ht * vh;
td = (pd / 100) * sb;
sl = sb - td;
printf("Horas trabalhadas: %d\n", ht);
printf("Valor por hora: R$%.2f\n", vh);
printf("Percentual de desconto: %.2f%\n", pd);
printf("Salario Bruto: R$%.2f\n", sb);
printf("Total de Desconto: R$%.2f\n", td);
printf("Salario Liquido: R$%.2f", sl);
}
|
#include "bricks/core/timespan.h"
#if BRICKS_ENV_MINGW
#include <pthread.h>
#endif
#include <time.h>
#include <string.h>
#define BRICKS_TIMESPAN_CONVERSION_DAYS (864000000000LL)
#define BRICKS_TIMESPAN_CONVERSION_HOURS (36000000000LL)
#define BRICKS_TIMESPAN_CONVERSION_MINUTES (600000000LL)
#define BRICKS_TIMESPAN_CONVERSION_SECONDS 10000000
#define BRICKS_TIMESPAN_CONVERSION_MILLISECONDS (10000)
#define BRICKS_TIMESPAN_CONVERSION_MICROSECONDS (10)
#define BRICKS_TIMESPAN_CONVERSION_NANOSECONDS (100)
namespace Bricks {
Timespan::Timespan(int hours, int minutes, int seconds) :
ticks(hours * BRICKS_TIMESPAN_CONVERSION_HOURS + minutes * BRICKS_TIMESPAN_CONVERSION_MINUTES + seconds * BRICKS_TIMESPAN_CONVERSION_SECONDS)
{
}
Timespan::Timespan(int hours, int minutes, int seconds, int milliseconds) :
ticks(hours * BRICKS_TIMESPAN_CONVERSION_HOURS + minutes * BRICKS_TIMESPAN_CONVERSION_MINUTES + seconds * BRICKS_TIMESPAN_CONVERSION_SECONDS + milliseconds * BRICKS_TIMESPAN_CONVERSION_MILLISECONDS)
{
}
Timespan::Timespan(int days, int hours, int minutes, int seconds, int milliseconds) :
ticks(days * BRICKS_TIMESPAN_CONVERSION_DAYS + hours * BRICKS_TIMESPAN_CONVERSION_HOURS + minutes * BRICKS_TIMESPAN_CONVERSION_MINUTES + seconds * BRICKS_TIMESPAN_CONVERSION_SECONDS + milliseconds * BRICKS_TIMESPAN_CONVERSION_MILLISECONDS)
{
}
Timespan Timespan::FromDays(long days)
{
return Timespan(days * BRICKS_TIMESPAN_CONVERSION_DAYS);
}
Timespan Timespan::FromDays(float days)
{
return Timespan(days * BRICKS_TIMESPAN_CONVERSION_DAYS);
}
Timespan Timespan::FromHours(long hours)
{
return Timespan(hours * BRICKS_TIMESPAN_CONVERSION_HOURS);
}
Timespan Timespan::FromHours(float hours)
{
return Timespan(hours * BRICKS_TIMESPAN_CONVERSION_HOURS);
}
Timespan Timespan::FromMinutes(long minutes)
{
return Timespan(minutes * BRICKS_TIMESPAN_CONVERSION_MINUTES);
}
Timespan Timespan::FromMinutes(float minutes)
{
return Timespan(minutes * BRICKS_TIMESPAN_CONVERSION_MINUTES);
}
Timespan Timespan::FromSeconds(s64 seconds)
{
return Timespan(seconds * BRICKS_TIMESPAN_CONVERSION_SECONDS);
}
Timespan Timespan::FromSeconds(float seconds)
{
return Timespan(seconds * BRICKS_TIMESPAN_CONVERSION_SECONDS);
}
Timespan Timespan::FromMilliseconds(s64 milliseconds)
{
return Timespan(milliseconds * BRICKS_TIMESPAN_CONVERSION_MILLISECONDS);
}
Timespan Timespan::FromMilliseconds(float milliseconds)
{
return Timespan(milliseconds * BRICKS_TIMESPAN_CONVERSION_MILLISECONDS);
}
s64 Timespan::ConvertDays(long days) { return days * BRICKS_TIMESPAN_CONVERSION_DAYS; }
s64 Timespan::ConvertHours(long hours) { return hours * BRICKS_TIMESPAN_CONVERSION_HOURS; }
s64 Timespan::ConvertMinutes(long minutes) { return minutes * BRICKS_TIMESPAN_CONVERSION_MINUTES; }
s64 Timespan::ConvertSeconds(s64 seconds) { return seconds * BRICKS_TIMESPAN_CONVERSION_SECONDS; }
s64 Timespan::ConvertMilliseconds(s64 milliseconds) { return milliseconds * BRICKS_TIMESPAN_CONVERSION_MILLISECONDS; }
s64 Timespan::ConvertMicroseconds(s64 microseconds) { return microseconds * BRICKS_TIMESPAN_CONVERSION_MICROSECONDS; }
s64 Timespan::ConvertNanoseconds(s64 nanoseconds) { return nanoseconds / BRICKS_TIMESPAN_CONVERSION_NANOSECONDS; }
long Timespan::ConvertToDays(s64 ticks) { return ticks / BRICKS_TIMESPAN_CONVERSION_DAYS; }
long Timespan::ConvertToHours(s64 ticks) { return ticks / BRICKS_TIMESPAN_CONVERSION_HOURS; }
long Timespan::ConvertToMinutes(s64 ticks) { return ticks / BRICKS_TIMESPAN_CONVERSION_MINUTES; }
s64 Timespan::ConvertToSeconds(s64 ticks) { return ticks / BRICKS_TIMESPAN_CONVERSION_SECONDS; }
s64 Timespan::ConvertToMilliseconds(s64 ticks) { return ticks / BRICKS_TIMESPAN_CONVERSION_MILLISECONDS; }
s64 Timespan::ConvertToMicroseconds(s64 ticks) { return ticks / BRICKS_TIMESPAN_CONVERSION_MICROSECONDS; }
s64 Timespan::ConvertToNanoseconds(s64 ticks) { return ticks * BRICKS_TIMESPAN_CONVERSION_NANOSECONDS; }
int Timespan::GetDays() const
{
return ticks / BRICKS_TIMESPAN_CONVERSION_DAYS;
}
int Timespan::GetHours() const
{
return AsHours() % 24;
}
int Timespan::GetMinutes() const
{
return AsMinutes() % 60;
}
int Timespan::GetSeconds() const
{
return AsSeconds() % 60;
}
int Timespan::GetMilliseconds() const
{
return AsMilliseconds() % 60;
}
int Timespan::AsDays() const
{
return GetDays();
}
int Timespan::AsHours() const
{
return ticks / BRICKS_TIMESPAN_CONVERSION_HOURS;
}
int Timespan::AsMinutes() const
{
return ticks / BRICKS_TIMESPAN_CONVERSION_MINUTES;
}
s64 Timespan::AsSeconds() const
{
return ticks / BRICKS_TIMESPAN_CONVERSION_SECONDS;
}
s64 Timespan::AsMilliseconds() const
{
return ticks / BRICKS_TIMESPAN_CONVERSION_MILLISECONDS;
}
float Timespan::GetTotalDays() const
{
return (float)ticks / BRICKS_TIMESPAN_CONVERSION_DAYS;
}
float Timespan::GetTotalHours() const
{
return (float)ticks / BRICKS_TIMESPAN_CONVERSION_HOURS;
}
float Timespan::GetTotalMinutes() const
{
return (float)ticks / BRICKS_TIMESPAN_CONVERSION_MINUTES;
}
float Timespan::GetTotalSeconds() const
{
return (float)ticks / BRICKS_TIMESPAN_CONVERSION_SECONDS;
}
float Timespan::GetTotalMilliseconds() const
{
return (float)ticks / BRICKS_TIMESPAN_CONVERSION_MILLISECONDS;
}
timespec Timespan::GetTimespec() const
{
struct timespec spec;
memset(&spec, 0, sizeof(spec));
spec.tv_sec = AsSeconds();
spec.tv_nsec = (ticks - spec.tv_sec * BRICKS_TIMESPAN_CONVERSION_SECONDS) * BRICKS_TIMESPAN_CONVERSION_NANOSECONDS;
return spec;
}
Timespan Timespan::operator +(const Timespan& span) const
{
return Timespan(*this) += span;
}
Timespan Timespan::operator -(const Timespan& span) const
{
return Timespan(*this) -= span;
}
Timespan& Timespan::operator +=(const Timespan& span)
{
ticks += span.ticks;
return *this;
}
Timespan& Timespan::operator -=(const Timespan& span)
{
ticks -= span.ticks;
return *this;
}
}
|
#include <iostream>
#include <pthread.h>
using namespace std;
class Area
{
public:
int _len;
static Area *_instance;
static pthread_mutex_t _myLock;
public:
Area();
static Area *getInstance();
};
Area* Area::_instance = NULL;
pthread_mutex_t Area::_myLock;
Area::Area()
{
pthread_mutex_init(&_myLock, NULL);
cout << "construct" << endl;
}
Area* Area::getInstance()
{
if(_instance == NULL)
{
pthread_mutex_lock(&_myLock);
if(_instance == NULL)
{
_instance = new Area();
}
pthread_mutex_unlock(&_myLock);
}
return _instance;
}
int main(int argc, char** argv)
{
cout << "hello" << endl;
Area* p = Area::getInstance();
}
|
#include "Ground.h"
#include "Window.h"
#include "InputManager.h"
//材質の色
static GLfloat ambColor[4] = { 0.6f, 0.6f, 0.6f, 1.0f };
static GLfloat diffColor[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
static GLfloat specColor[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
static GLfloat shiness = 30.0f;
Ground::Ground(GLfloat width, GLfloat height, Physics* a_physics)
{
//TODO:回転値もメンバ変数としてrectに持たせる
//m_Rect = new Rect(width, height);
m_Cube = new CubeObject(Vector3(width, 0.25f, height), "PBR.vert", "PBR.frag", ambColor, diffColor, specColor, shiness);
physics = a_physics;
rigidBodyIndex = physics->CreateRigidBody(m_Cube->GetVertices(), m_Cube->GetNumvertices(), m_Cube->GetFaces(), m_Cube->GetNumFaces(), Vector3(width*0.1f, 0.25f, height*0.1f), MotionType::TypeStatic, Vector3(position.x(), position.y(), position.z()), 1.0, false);
//Quat q = Quat::identity();
//physics->SetRigidBodyRotate(rigidBodyIndex,q);
}
Ground::~Ground()
{
Common::Delete(m_Cube);
}
StaticObj* Ground::Update(){
StaticObj* s = this;
return this;
}
StaticObj* Ground::Draw(){
StaticObj* s = this;
//シェーダの使用
m_Cube->GetMaterial()->m_shader->Use();
Matrix mv = Window::ReturnMV()*InputManager::GetTrackBall()->Get();
Matrix mp = Window::getMp();
Quat q = physics->GetRigidBodyState(rigidBodyIndex).m_orientation;
Matrix mw = mv.rotateQuat(q)*Translate(GetPos().getX(), GetPos().getY(), GetPos().getZ());
m_Cube->GetMaterial()->GetShader()->loadMatrix(mp, mw, (Translate(GetPos().getX(), GetPos().getY(), GetPos().getZ())));
//描画
m_Cube->Draw();
return s;
}
|
#include<stdio.h>
#include<string.h>
main()
{
char str[20]="asdfghj";
int n;
n=strlen(str);
printf("%d\n",n);
}
|
/*******************************************************************************
* filename: M_Singleton.hpp
* description: Macros that generate skeleton singleton pattern classes
* author: Moritz Beber
* created: 2010-06-08
* copyright: Jacobs University Bremen. All rights reserved.
*******************************************************************************
* Three macros are provided that provide the skeleton for classes that implement
* the singleton pattern. Importantly, the base class is inheritable. The design
* is such that only one instance of the base class or child classes can exist.
*
* The instance is dynamically allocated on the heap and will only be destroyed
* once the program exits.
*
* The 'instance' member function of the base class should be overloaded so that
* child classes are dynamically created through it. It can do so because it is
* declared a 'friend' in all derived classes.
*
* The copy-constructor and assignment operator are unavailable for classes that
* use the singleton pattern.
*
* The default (and any other) constructor(s) and the destructor should at least
* be defined as empty in any implementation.
******************************************************************************/
#ifndef _M_SINGLETON_HPP
#define _M_SINGLETON_HPP
/*
* Necessary declarations for creating a base class implementing the singleton
* pattern.
*/
#define DECLARE_BASE_SINGLETON(CLASS) \
protected: \
CLASS(); \
virtual ~CLASS(); \
\
private: \
static CLASS* _instance; \
CLASS(const CLASS&); \
CLASS& operator=(const CLASS&); \
CLASS& operator=(CLASS&); \
\
class Guard { \
public: \
~Guard(); \
}; \
friend class Guard; \
\
public: \
static CLASS* instance();
/*
* Necessary definitions of base class member functions. The default 'instance'
* member function should be overloaded if child classes are used. If 'CLASS'
* resides within one or more namespaces you should invoke this macro with the
* full specifier or employ the appropriate 'using' directives.
*/
#define DEFINE_BASE_SINGLETON(CLASS) \
CLASS* CLASS::_instance = NULL; \
\
CLASS::Guard::~Guard() \
{ \
if (CLASS::_instance) { \
delete CLASS::_instance; \
CLASS::_instance = NULL; \
} \
}
/*
* 'static CLASS* instance()' is not defined in this macro in case the base
* is supposed to be 'pure virtual'. An example is given here:
*/
/*
CLASS*
CLASS::instance()
{
if (CLASS::_instance == 0) {
static CLASS::Guard g;
CLASS::_instance = new CLASS;
}
return CLASS::_instance;
}
*/
/*
* Necessary declarations for inheriting from a base singleton pattern class. If
* 'BASE' resides within one or more namespaces you should invoke this macro with
* the full specifier or employ the appropriate 'using' directives.
*/
#define DECLARE_DERIVED_SINGLETON(BASE, DERIVED) \
friend class BASE; \
\
protected: \
DERIVED(); \
virtual ~DERIVED(); \
\
private: \
DERIVED(const DERIVED&); \
DERIVED& operator=(const DERIVED&); \
DERIVED& operator=(DERIVED&);
#endif // _M_SINGLETON_HPP
|
/****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#pragma once
#if defined(_DEBUG) && defined(_WINDOWS)
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define TG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#else
#define TG_NEW new
#endif
|
/*
* Author: Zachary Eisenhauer
* Date: 12/2/2016
* Assignment: Program 3
*
* In Main.cpp
* Functions to read in graph.txt, commands.txt and print a created graph of them in list form and matrix form
*
* In Main.h
* The function prototypes in this file, the class definition for a node, and the libaries used
*/
// Include Statements
#include <iostream>
using std::cout;
using std::endl;
#include <fstream>
using std::ifstream;
#include <sstream>
#include <vector>
using std::vector;
#include <string>
using std::string;
#include <stdlib.h> /* exit, EXIT_FAILURE */
// Classes
class node{
public:
char name;
vector<char> connectedNodes;
};
// Function Prototypes
std::vector<node> inputGraph();
void commands(vector<node> &);
void printList(vector<node>);
void printMatrix(vector<node> nodes);
|
#include "EquisolidModel.h"
Cvl::EquisolidModel::EquisolidModel(double focalLengthX, double focalLengthY, double principalPointX, double principalPointY) :
ProjectionModel(focalLengthX, focalLengthY, principalPointX, principalPointY)
{
}
Cvl::ProjectionModel::Uptr Cvl::EquisolidModel::clone() const
{
return ProjectionModel::Uptr(new EquisolidModel(mFocalLengthX, mFocalLengthY, mPrincipalPointX, mPrincipalPointY));
}
Eigen::Array2Xd Cvl::EquisolidModel::project(Eigen::Array2Xd const& distortedPoints) const
{
Eigen::Array<double, 1, Eigen::Dynamic> norms = distortedPoints.matrix().colwise().norm();
Eigen::Array<double, 1, Eigen::Dynamic> angles = (norms.atan()*0.5).sin();
return (((distortedPoints.colwise() * Eigen::Array2d(2.0*mFocalLengthX, 2.0*mFocalLengthY)).rowwise() * angles).rowwise() / norms).colwise() + Eigen::Array2d(mPrincipalPointX, mPrincipalPointY);
}
Eigen::Array2Xd Cvl::EquisolidModel::unproject(Eigen::Array2Xd const& imagePoints) const
{
// this is the same solution as below to test eigen broadcasting and reduction features
//Eigen::Array2Xd result(2, imagePoints.cols());
//double pixelLengthRatio = mFocalLengthX / mFocalLengthY;
//double pixelLengthRatioSquared = pixelLengthRatio*pixelLengthRatio;
//Eigen::Array2d temp1;
//double radiusX = 0.0;
//double radiusTemp1 = 0.0;
//double radiusTemp2 = 0.0;
//double radiusCamera = 0.0;
//for (int i=0; i<imagePoints.cols(); ++i)
//{
// temp1 = imagePoints.col(i) - Eigen::Array2d(mPrincipalPointX, mPrincipalPointY);
// radiusX = std::sqrt(temp1.x()*temp1.x() + temp1.y()*temp1.y()*pixelLengthRatioSquared);
// radiusTemp1 = 0.5*radiusX / mFocalLengthX;
// radiusTemp2 = radiusTemp1 * radiusTemp1;
// radiusCamera = (2.0 * radiusTemp1 * sqrt(1.0 - radiusTemp2)) / (1.0 - 2.0 * radiusTemp2);
// result(0, i) = temp1.x() * radiusCamera / radiusX;
// result(1, i) = temp1.y() * radiusCamera * pixelLengthRatio / radiusX;
//}
//return result;
Eigen::Array2Xd centeredPoints = imagePoints.colwise() - Eigen::Array2d(mPrincipalPointX, mPrincipalPointY);
centeredPoints.row(1) *= mFocalLengthX / mFocalLengthY;
Eigen::Array<double, 1, Eigen::Dynamic> radiX = centeredPoints.matrix().colwise().norm().array();
Eigen::Array<double, 1, Eigen::Dynamic> radiX2f = radiX/(2.0*mFocalLengthX);
Eigen::Array<double, 1, Eigen::Dynamic> radiX2fSquared = radiX2f.square();
return (centeredPoints.rowwise() * ( (2.0 * radiX2f * (1.0 - radiX2fSquared).sqrt()) / (1.0 - 2.0 * radiX2fSquared) ) ).rowwise() / radiX;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "adjunct/quick_toolkit/widgets/CalloutDialogPlacer.h"
#include "adjunct/quick_toolkit/widgets/QuickOverlayDialog.h"
#include "modules/skin/OpSkinManager.h"
namespace
{
const int ANCHOR_OVERLAP = 4;
}
CalloutDialogPlacer::CalloutDialogPlacer(OpWidget& anchor_widget, Alignment alignment, const char* dialog_skin)
: m_anchor_widget(&anchor_widget)
, m_alignment(alignment)
, m_dialog_skin(dialog_skin)
{
}
OpRect CalloutDialogPlacer::CalculatePlacement(const OpRect& bounds, const OpRect& dialog_size)
{
INT32 up = 0, down = 0, left = 0, right = 0;
// because we are using root coordinates here (to avoid problems with
// scrolled containers), we also need to stay in sync with value
// returned in UsesRootCoordinates()
OpRect anchor = m_anchor_widget->GetRect(TRUE);
if (m_alignment == CENTER)
{
// Adjust anchor position for padding, and add overlap.
// But ensure the final rect is non-empty.
m_anchor_widget->AddPadding(anchor);
anchor = anchor.InsetBy(MIN(anchor.width/2 - 1, ANCHOR_OVERLAP), MIN(anchor.height/2 - 1, ANCHOR_OVERLAP));
}
else
{
anchor = anchor.InsetBy(0, MIN(anchor.height/2 - 1, ANCHOR_OVERLAP));
}
// Prefer aligning the dialog under the anchor, assume other positions are
// not needed.
down = bounds.Bottom() - anchor.Bottom();
// If the dialog doesn't fit under the anchor, calculate space on
// top of anchor. If it doesn't fit there either, calculate the
// horizontal space.
if (down < dialog_size.height)
{
up = anchor.Top() - bounds.Top();
if (up < dialog_size.height)
{
left = anchor.Left() - bounds.Left();
right = bounds.Right() - anchor.Right();
}
}
// Align dialog where most space is available
OpRect placement = dialog_size;
if (MAX(down, up) > MAX(left, right))
{
placement.x = anchor.x;
if (m_alignment == LEFT && m_dialog_skin)
{
INT32 p_left, p_right, p_top, p_bottom;
if (OpStatus::IsSuccess(g_skin_manager->GetPadding(m_dialog_skin, &p_left, &p_top, &p_right, &p_bottom)))
{
placement.x -= p_left;
}
if (m_anchor_widget->GetRTL())
placement.x += anchor.width + (anchor.x - placement.x) * 2 - placement.width;
}
else if (m_alignment == CENTER)
{
placement.x += (anchor.width - dialog_size.width) / 2;
}
if (down > up)
{
placement.y = anchor.Bottom();
}
else
{
placement.y = anchor.Top() - dialog_size.height;
}
}
else
{
placement.y = anchor.y;
if (m_alignment == LEFT && m_dialog_skin)
{
INT32 p_left, p_right, p_top, p_bottom;
if (OpStatus::IsSuccess(g_skin_manager->GetPadding(m_dialog_skin, &p_left, &p_top, &p_right, &p_bottom)))
{
placement.y -= p_top;
}
}
else if (m_alignment == CENTER)
{
placement.y += (anchor.height - dialog_size.height) / 2;
}
if (right > left)
{
placement.x = anchor.Right();
}
else
{
placement.x = anchor.Left() - dialog_size.width;
}
}
return placement;
}
void CalloutDialogPlacer::PointArrow(OpWidgetImage& arrow_skin, const OpRect& placement)
{
arrow_skin.PointArrow(placement, m_anchor_widget->GetRect(TRUE));
}
|
/*
* spinreflector.h
* deflektor-ds
*
* Created by Hugh Cole-Baker on 18/12/2008.
* A block that rotates, and only lets the beam through if it's aligned correctly.
* Otherwise the beam is reflected.
*/
#ifndef deflektor_spinreflector_h
#define deflektor_spinreflector_h
#include "spinblocker.h"
class SpinReflector : public SpinBlocker
{
protected:
int reflectiveSides;
public:
SpinReflector(int bg, int x, int y, unsigned int palIdx, unsigned int tile, BeamDirection initAngle, int ref);
virtual BeamResult beamEnters(unsigned int x, unsigned int y, BeamDirection atAngle);
};
#endif
|
#pragma once
#define _USE_MATH_DEFINES
#include <cmath>
#define M_PI 3.14159265358979323846
namespace LAB3
{
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Text::RegularExpressions;
/// <summary>
/// Сводка для MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::TabPage^ tabPage4;
private: System::Windows::Forms::TabPage^ tabPage3;
private: System::Windows::Forms::TabPage^ tabPage2;
private: System::Windows::Forms::TabPage^ tabPage1;
private: System::Windows::Forms::Label^ task3;
private: System::Windows::Forms::Label^ task2;
private: System::Windows::Forms::Label^ task1;
private: System::Windows::Forms::Label^ main_title;
private: System::Windows::Forms::TabControl^ tabControl1;
private: System::Windows::Forms::Label^ triangles_height;
private: System::Windows::Forms::Label^ triangles_base;
private: System::Windows::Forms::Label^ result;
private: System::Windows::Forms::Label^ triangles_square;
private: System::Windows::Forms::Button^ calculate;
private: System::Windows::Forms::TextBox^ height;
private: System::Windows::Forms::TextBox^ base;
private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel1;
private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel2;
private: System::Windows::Forms::TextBox^ line;
private: System::Windows::Forms::Button^ start;
private: System::Windows::Forms::Label^ parametr;
private: System::Windows::Forms::PictureBox^ pictureBox2;
private: System::Windows::Forms::PictureBox^ pictureBox1;
private: System::Windows::Forms::Timer^ generate;
private: System::Windows::Forms::Timer^ move;
private: System::Windows::Forms::Button^ stop;
private: System::Windows::Forms::Button^ start2;
private: System::Windows::Forms::PictureBox^ pictureBox3;
private: System::Windows::Forms::Timer^ rotater;
private: System::Windows::Forms::PictureBox^ pictureBox5;
private: System::Windows::Forms::PictureBox^ pictureBox4;
private: System::Windows::Forms::Timer^ formove;
private: System::ComponentModel::IContainer^ components;
private:
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MyForm::typeid));
this->tabPage4 = (gcnew System::Windows::Forms::TabPage());
this->stop = (gcnew System::Windows::Forms::Button());
this->start2 = (gcnew System::Windows::Forms::Button());
this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox());
this->tabPage3 = (gcnew System::Windows::Forms::TabPage());
this->tableLayoutPanel1 = (gcnew System::Windows::Forms::TableLayoutPanel());
this->tableLayoutPanel2 = (gcnew System::Windows::Forms::TableLayoutPanel());
this->line = (gcnew System::Windows::Forms::TextBox());
this->start = (gcnew System::Windows::Forms::Button());
this->parametr = (gcnew System::Windows::Forms::Label());
this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
this->tabPage2 = (gcnew System::Windows::Forms::TabPage());
this->pictureBox5 = (gcnew System::Windows::Forms::PictureBox());
this->pictureBox4 = (gcnew System::Windows::Forms::PictureBox());
this->pictureBox3 = (gcnew System::Windows::Forms::PictureBox());
this->triangles_height = (gcnew System::Windows::Forms::Label());
this->triangles_base = (gcnew System::Windows::Forms::Label());
this->result = (gcnew System::Windows::Forms::Label());
this->triangles_square = (gcnew System::Windows::Forms::Label());
this->calculate = (gcnew System::Windows::Forms::Button());
this->height = (gcnew System::Windows::Forms::TextBox());
this->base = (gcnew System::Windows::Forms::TextBox());
this->tabPage1 = (gcnew System::Windows::Forms::TabPage());
this->task3 = (gcnew System::Windows::Forms::Label());
this->task2 = (gcnew System::Windows::Forms::Label());
this->task1 = (gcnew System::Windows::Forms::Label());
this->main_title = (gcnew System::Windows::Forms::Label());
this->tabControl1 = (gcnew System::Windows::Forms::TabControl());
this->generate = (gcnew System::Windows::Forms::Timer(this->components));
this->move = (gcnew System::Windows::Forms::Timer(this->components));
this->rotater = (gcnew System::Windows::Forms::Timer(this->components));
this->formove = (gcnew System::Windows::Forms::Timer(this->components));
this->tabPage4->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->BeginInit();
this->tabPage3->SuspendLayout();
this->tableLayoutPanel1->SuspendLayout();
this->tableLayoutPanel2->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit();
this->tabPage2->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox5))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox4))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox3))->BeginInit();
this->tabPage1->SuspendLayout();
this->tabControl1->SuspendLayout();
this->SuspendLayout();
//
// tabPage4
//
this->tabPage4->Controls->Add(this->stop);
this->tabPage4->Controls->Add(this->start2);
this->tabPage4->Controls->Add(this->pictureBox2);
this->tabPage4->Location = System::Drawing::Point(4, 33);
this->tabPage4->Name = L"tabPage4";
this->tabPage4->Padding = System::Windows::Forms::Padding(3);
this->tabPage4->Size = System::Drawing::Size(626, 342);
this->tabPage4->TabIndex = 3;
this->tabPage4->Text = L"Task 3";
this->tabPage4->UseVisualStyleBackColor = true;
//
// stop
//
this->stop->BackColor = System::Drawing::Color::Purple;
this->stop->Enabled = false;
this->stop->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->stop->ForeColor = System::Drawing::SystemColors::Control;
this->stop->Location = System::Drawing::Point(314, 307);
this->stop->Name = L"stop";
this->stop->Size = System::Drawing::Size(306, 32);
this->stop->TabIndex = 2;
this->stop->Text = L"Stop";
this->stop->UseVisualStyleBackColor = false;
this->stop->Click += gcnew System::EventHandler(this, &MyForm::stop_Click);
//
// start2
//
this->start2->BackColor = System::Drawing::Color::Purple;
this->start2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->start2->ForeColor = System::Drawing::SystemColors::Control;
this->start2->Location = System::Drawing::Point(6, 307);
this->start2->Name = L"start2";
this->start2->Size = System::Drawing::Size(306, 32);
this->start2->TabIndex = 1;
this->start2->Text = L"Start";
this->start2->UseVisualStyleBackColor = false;
this->start2->Click += gcnew System::EventHandler(this, &MyForm::start2_Click);
//
// pictureBox2
//
this->pictureBox2->Location = System::Drawing::Point(3, 6);
this->pictureBox2->Name = L"pictureBox2";
this->pictureBox2->Size = System::Drawing::Size(616, 295);
this->pictureBox2->TabIndex = 0;
this->pictureBox2->TabStop = false;
this->pictureBox2->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MyForm::pictureBox1_Paint);
//
// tabPage3
//
this->tabPage3->Controls->Add(this->tableLayoutPanel1);
this->tabPage3->Location = System::Drawing::Point(4, 33);
this->tabPage3->Name = L"tabPage3";
this->tabPage3->Padding = System::Windows::Forms::Padding(3);
this->tabPage3->Size = System::Drawing::Size(626, 342);
this->tabPage3->TabIndex = 2;
this->tabPage3->Text = L"Task 2";
this->tabPage3->UseVisualStyleBackColor = true;
//
// tableLayoutPanel1
//
this->tableLayoutPanel1->ColumnCount = 1;
this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
50)));
this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
20)));
this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
20)));
this->tableLayoutPanel1->Controls->Add(this->tableLayoutPanel2, 0, 0);
this->tableLayoutPanel1->Controls->Add(this->pictureBox1, 0, 1);
this->tableLayoutPanel1->Location = System::Drawing::Point(6, 6);
this->tableLayoutPanel1->Name = L"tableLayoutPanel1";
this->tableLayoutPanel1->RowCount = 2;
this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50)));
this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Absolute, 288)));
this->tableLayoutPanel1->Size = System::Drawing::Size(614, 333);
this->tableLayoutPanel1->TabIndex = 0;
//
// tableLayoutPanel2
//
this->tableLayoutPanel2->ColumnCount = 3;
this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
50)));
this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
278)));
this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Absolute,
146)));
this->tableLayoutPanel2->Controls->Add(this->line, 1, 0);
this->tableLayoutPanel2->Controls->Add(this->start, 2, 0);
this->tableLayoutPanel2->Controls->Add(this->parametr, 0, 0);
this->tableLayoutPanel2->Location = System::Drawing::Point(3, 3);
this->tableLayoutPanel2->Name = L"tableLayoutPanel2";
this->tableLayoutPanel2->RowCount = 1;
this->tableLayoutPanel2->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 36.36364F)));
this->tableLayoutPanel2->Size = System::Drawing::Size(608, 39);
this->tableLayoutPanel2->TabIndex = 0;
//
// line
//
this->line->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->line->Location = System::Drawing::Point(187, 3);
this->line->Name = L"line";
this->line->Size = System::Drawing::Size(272, 29);
this->line->TabIndex = 1;
this->line->TextChanged += gcnew System::EventHandler(this, &MyForm::base_TextChanged);
this->line->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &MyForm::base_KeyPress);
//
// start
//
this->start->BackColor = System::Drawing::Color::Purple;
this->start->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->start->ForeColor = System::Drawing::SystemColors::Control;
this->start->Location = System::Drawing::Point(465, 3);
this->start->Name = L"start";
this->start->Size = System::Drawing::Size(140, 32);
this->start->TabIndex = 2;
this->start->Text = L"Start";
this->start->UseVisualStyleBackColor = false;
this->start->Click += gcnew System::EventHandler(this, &MyForm::start_Click);
//
// parametr
//
this->parametr->AutoSize = true;
this->parametr->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->parametr->Location = System::Drawing::Point(3, 0);
this->parametr->Name = L"parametr";
this->parametr->Padding = System::Windows::Forms::Padding(0, 6, 0, 0);
this->parametr->Size = System::Drawing::Size(139, 30);
this->parametr->TabIndex = 0;
this->parametr->Text = L"Enter parametr:";
//
// pictureBox1
//
this->pictureBox1->Location = System::Drawing::Point(3, 48);
this->pictureBox1->Name = L"pictureBox1";
this->pictureBox1->Size = System::Drawing::Size(608, 282);
this->pictureBox1->TabIndex = 1;
this->pictureBox1->TabStop = false;
//
// tabPage2
//
this->tabPage2->Controls->Add(this->pictureBox5);
this->tabPage2->Controls->Add(this->pictureBox4);
this->tabPage2->Controls->Add(this->pictureBox3);
this->tabPage2->Controls->Add(this->triangles_height);
this->tabPage2->Controls->Add(this->triangles_base);
this->tabPage2->Controls->Add(this->result);
this->tabPage2->Controls->Add(this->triangles_square);
this->tabPage2->Controls->Add(this->calculate);
this->tabPage2->Controls->Add(this->height);
this->tabPage2->Controls->Add(this->base);
this->tabPage2->Location = System::Drawing::Point(4, 33);
this->tabPage2->Name = L"tabPage2";
this->tabPage2->Padding = System::Windows::Forms::Padding(3);
this->tabPage2->Size = System::Drawing::Size(626, 342);
this->tabPage2->TabIndex = 1;
this->tabPage2->Text = L"Task 1";
this->tabPage2->UseVisualStyleBackColor = true;
//
// pictureBox5
//
this->pictureBox5->Location = System::Drawing::Point(533, 261);
this->pictureBox5->Name = L"pictureBox5";
this->pictureBox5->Size = System::Drawing::Size(50, 50);
this->pictureBox5->TabIndex = 9;
this->pictureBox5->TabStop = false;
//
// pictureBox4
//
this->pictureBox4->Location = System::Drawing::Point(288, 261);
this->pictureBox4->Name = L"pictureBox4";
this->pictureBox4->Size = System::Drawing::Size(50, 50);
this->pictureBox4->TabIndex = 8;
this->pictureBox4->TabStop = false;
//
// pictureBox3
//
this->pictureBox3->Location = System::Drawing::Point(39, 261);
this->pictureBox3->Name = L"pictureBox3";
this->pictureBox3->Size = System::Drawing::Size(50, 50);
this->pictureBox3->TabIndex = 7;
this->pictureBox3->TabStop = false;
//
// triangles_height
//
this->triangles_height->AutoSize = true;
this->triangles_height->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular,
System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0)));
this->triangles_height->Location = System::Drawing::Point(34, 94);
this->triangles_height->Name = L"triangles_height";
this->triangles_height->Size = System::Drawing::Size(193, 24);
this->triangles_height->TabIndex = 6;
this->triangles_height->Text = L"Triangles height (cm):";
//
// triangles_base
//
this->triangles_base->AutoSize = true;
this->triangles_base->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->triangles_base->Location = System::Drawing::Point(34, 40);
this->triangles_base->Name = L"triangles_base";
this->triangles_base->Size = System::Drawing::Size(182, 24);
this->triangles_base->TabIndex = 5;
this->triangles_base->Text = L"Triangles base (cm):";
//
// result
//
this->result->AutoSize = true;
this->result->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->result->Location = System::Drawing::Point(345, 204);
this->result->Name = L"result";
this->result->Size = System::Drawing::Size(0, 24);
this->result->TabIndex = 4;
//
// triangles_square
//
this->triangles_square->AutoSize = true;
this->triangles_square->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular,
System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0)));
this->triangles_square->Location = System::Drawing::Point(35, 204);
this->triangles_square->Name = L"triangles_square";
this->triangles_square->Size = System::Drawing::Size(255, 24);
this->triangles_square->TabIndex = 3;
this->triangles_square->Text = L"Triangle square equally (cm):";
//
// calculate
//
this->calculate->BackColor = System::Drawing::Color::Purple;
this->calculate->Enabled = false;
this->calculate->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->calculate->ForeColor = System::Drawing::SystemColors::Control;
this->calculate->Location = System::Drawing::Point(39, 152);
this->calculate->Name = L"calculate";
this->calculate->Size = System::Drawing::Size(544, 31);
this->calculate->TabIndex = 2;
this->calculate->Text = L"Calculate";
this->calculate->UseVisualStyleBackColor = false;
this->calculate->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
//
// height
//
this->height->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->height->Location = System::Drawing::Point(291, 91);
this->height->Name = L"height";
this->height->Size = System::Drawing::Size(292, 29);
this->height->TabIndex = 1;
this->height->TextChanged += gcnew System::EventHandler(this, &MyForm::base_TextChanged);
this->height->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &MyForm::base_KeyPress);
//
// base
//
this->base->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->base->Location = System::Drawing::Point(291, 37);
this->base->Name = L"base";
this->base->Size = System::Drawing::Size(292, 29);
this->base->TabIndex = 0;
this->base->TextChanged += gcnew System::EventHandler(this, &MyForm::base_TextChanged);
this->base->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &MyForm::base_KeyPress);
//
// tabPage1
//
this->tabPage1->Controls->Add(this->task3);
this->tabPage1->Controls->Add(this->task2);
this->tabPage1->Controls->Add(this->task1);
this->tabPage1->Controls->Add(this->main_title);
this->tabPage1->Location = System::Drawing::Point(4, 33);
this->tabPage1->Name = L"tabPage1";
this->tabPage1->Padding = System::Windows::Forms::Padding(6);
this->tabPage1->Size = System::Drawing::Size(626, 342);
this->tabPage1->TabIndex = 0;
this->tabPage1->Text = L"Main menu";
this->tabPage1->UseVisualStyleBackColor = true;
//
// task3
//
this->task3->AutoSize = true;
this->task3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12));
this->task3->Location = System::Drawing::Point(9, 221);
this->task3->Margin = System::Windows::Forms::Padding(3);
this->task3->Name = L"task3";
this->task3->Size = System::Drawing::Size(504, 100);
this->task3->TabIndex = 3;
this->task3->Text = resources->GetString(L"task3.Text");
//
// task2
//
this->task2->AutoSize = true;
this->task2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12));
this->task2->Location = System::Drawing::Point(9, 146);
this->task2->Margin = System::Windows::Forms::Padding(3);
this->task2->Name = L"task2";
this->task2->Size = System::Drawing::Size(443, 60);
this->task2->TabIndex = 2;
this->task2->Text = L"Task 2. Machine graphics\r\nFill the screen with a drawing of fish scales with a gi"
L"ven size of\r\nelementary scales.";
//
// task1
//
this->task1->AutoSize = true;
this->task1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->task1->Location = System::Drawing::Point(9, 71);
this->task1->Margin = System::Windows::Forms::Padding(3);
this->task1->Name = L"task1";
this->task1->Size = System::Drawing::Size(487, 60);
this->task1->TabIndex = 1;
this->task1->Text = L"Task 1. The simplest Windows applications\r\nApplication for triangle area calculat"
L"ion, if the base and height of the\r\ntriangle are known (in cm).\r\n";
//
// main_title
//
this->main_title->AutoSize = true;
this->main_title->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->main_title->Location = System::Drawing::Point(10, 15);
this->main_title->Margin = System::Windows::Forms::Padding(3);
this->main_title->Name = L"main_title";
this->main_title->Size = System::Drawing::Size(508, 40);
this->main_title->TabIndex = 0;
this->main_title->Text = L"This is the Main menu available here, where you can select the\r\nrequired laborato"
L"ry work and learn the text of its task.";
//
// tabControl1
//
this->tabControl1->Controls->Add(this->tabPage1);
this->tabControl1->Controls->Add(this->tabPage2);
this->tabControl1->Controls->Add(this->tabPage3);
this->tabControl1->Controls->Add(this->tabPage4);
this->tabControl1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->tabControl1->Location = System::Drawing::Point(14, 13);
this->tabControl1->Name = L"tabControl1";
this->tabControl1->SelectedIndex = 0;
this->tabControl1->Size = System::Drawing::Size(634, 379);
this->tabControl1->TabIndex = 0;
//
// generate
//
this->generate->Interval = 25;
this->generate->Tick += gcnew System::EventHandler(this, &MyForm::timer1_Tick);
//
// move
//
this->move->Interval = 25;
this->move->Tick += gcnew System::EventHandler(this, &MyForm::timer2_Tick);
//
// rotater
//
this->rotater->Interval = 1000;
this->rotater->Tick += gcnew System::EventHandler(this, &MyForm::rotater_Tick);
//
// formove
//
this->formove->Tick += gcnew System::EventHandler(this, &MyForm::formove_Tick);
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(657, 401);
this->Controls->Add(this->tabControl1);
this->DoubleBuffered = true;
this->Icon = (cli::safe_cast<System::Drawing::Icon^>(resources->GetObject(L"$this.Icon")));
this->MaximizeBox = false;
this->MaximumSize = System::Drawing::Size(673, 440);
this->MinimizeBox = false;
this->MinimumSize = System::Drawing::Size(673, 440);
this->Name = L"MyForm";
this->Text = L"Laboratory work №3";
this->tabPage4->ResumeLayout(false);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->EndInit();
this->tabPage3->ResumeLayout(false);
this->tableLayoutPanel1->ResumeLayout(false);
this->tableLayoutPanel2->ResumeLayout(false);
this->tableLayoutPanel2->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit();
this->tabPage2->ResumeLayout(false);
this->tabPage2->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox5))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox4))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox3))->EndInit();
this->tabPage1->ResumeLayout(false);
this->tabPage1->PerformLayout();
this->tabControl1->ResumeLayout(false);
this->ResumeLayout(false);
}
#pragma endregion
//Task 1
double rotate;
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
Regex^ r = gcnew Regex("^[0-9]*[,]?[0-9]+$");
Match^ name_ex = r->Match(base->Text);
Match^ name_ex2 = r->Match(height->Text);
double dbase = Convert::ToDouble(base->Text);
double dheight = Convert::ToDouble(height->Text);
if (name_ex->Success && name_ex2->Success)
{
if (dbase == 0 || dheight == 0)
MessageBox::Show("Incorrect data! Paramets can not be zero value.", "Error!", MessageBoxButtons::OK, MessageBoxIcon::Warning);
else
{
double square = dbase * dheight / 2;
result->Text = square.ToString();
}
}
else
MessageBox::Show("Incorrect data! Please use integer or real numbers.", "Error!", MessageBoxButtons::OK, MessageBoxIcon::Error);
int pw = pictureBox3->Width, ph = pictureBox3->Height;
Bitmap^ img = gcnew Bitmap(pw, ph);
Graphics^ g = Graphics::FromImage(img);
array<double>^ x = gcnew array<double>(3), ^ y = gcnew array<double>(3);
x[0] = 0; y[0] = 50;
x[1] = 25; y[1] = 0;
x[2] = 50; y[2] = 50;
Color customColor = Color::FromArgb(150, Color::Purple);
SolidBrush^ shadowBrush = gcnew SolidBrush(customColor);
g->FillPolygon(shadowBrush, gcnew array<Point>
{
Point(x[0], y[0]),
Point(x[1], y[1]),
Point(x[2], y[2])
});
g->DrawPolygon(Pens::Purple, gcnew array<Point>
{
Point(x[0], y[0]),
Point(x[1], y[1]),
Point(x[2], y[2])
});
this->pictureBox3->Image = img;
this->pictureBox4->Image = img;
this->pictureBox5->Image = img;
rotater->Start();
formove->Start();
}
private: System::Void formove_Tick(System::Object^ sender, System::EventArgs^ e)
{
result->Left += 10;
if (result->Left > 600)
result->Left = 300;
}
private: System::Void rotater_Tick(System::Object^ sender, System::EventArgs^ e)
{
this->pictureBox3->Image->RotateFlip(System::Drawing::RotateFlipType::Rotate90FlipXY);
this->pictureBox3->Invalidate();
this->pictureBox4->Invalidate();
this->pictureBox5->Invalidate();
}
private: System::Void base_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e)
{
if ((e->KeyChar >= '0') && (e->KeyChar <= '9'))
return;
if (e->KeyChar == '.')
{
e->KeyChar = ',';
return;
}
if (e->KeyChar == ',')
return;
if (Char::IsControl(e->KeyChar))
{
if (e->KeyChar == (char)Keys::Enter)
calculate->Focus();
return;
}
e->Handled = true;
}
private: System::Void base_TextChanged(System::Object^ sender, System::EventArgs^ e)
{
if ((base->Text->Length == 0) || (height->Text->Length == 0))
calculate->Enabled = false;
else
calculate->Enabled = true;
}
//Task 2
private: System::Void start_Click(System::Object^ sender, System::EventArgs^ e)
{
Regex^ r = gcnew Regex("^[0-9]*[,]?[0-9]+$");
Match^ value = r->Match(line->Text);
if (value->Success)
{
int pw = pictureBox1->Width, ph = pictureBox1->Height;
Bitmap^ img = gcnew Bitmap(pw, ph);
Graphics^ g = Graphics::FromImage(img);
double a = Convert::ToDouble(line->Text);
array<double>^ x = gcnew array<double>(6), ^ y = gcnew array<double>(6);
for (double ys = 0; ys < ph; ys += a)
{
for (double xs = 0; xs < pw; xs += a)
{
for (int i = 0; i < 6; i++)
{
double angle = M_PI * i / 3;
x[i] = cos(angle) * a + xs;
y[i] = sin(angle) * a + ys;
}
Color customColor = Color::FromArgb(150, Color::Black);
SolidBrush^ shadowBrush = gcnew SolidBrush(customColor);
g->FillPolygon(shadowBrush, gcnew array<PointF>
{
PointF(x[0], y[0]),
PointF(x[1], y[1]),
PointF(x[2], y[2]),
PointF(x[3], y[3]),
PointF(x[4], y[4]),
PointF(x[5], y[5])
});
g->DrawPolygon(Pens::Red, gcnew array<PointF>
{
PointF(x[0], y[0]),
PointF(x[1], y[1]),
PointF(x[2], y[2]),
PointF(x[3], y[3]),
PointF(x[4], y[4]),
PointF(x[5], y[5])
});
}
}
this->pictureBox1->Image = img;
}
else
MessageBox::Show("Incorrect data! Please use integer or real numbers.", "Error!", MessageBoxButtons::OK, MessageBoxIcon::Error);
}
private: System::Void line_TextChanged(System::Object^ sender, System::EventArgs^ e)
{
if (line->Text->Length == 0)
start->Enabled = false;
else
start->Enabled = true;
}
//Task 3
ref class ball
{
public:
int y, x, width, xrt, yrt, xlb, ylb, xrb, yrb;
ball()
{
y = x = width = xrt = yrt = xlb = ylb = xrb = yrb = 0;
}
void recalculate()
{
xrt = x + width;
yrt = y;
xlb = x;
ylb = y - width;
xrb = x + width;
yrb = y - width;
}
};
array<ball^>^ balls;
int point;
int max = 1000;
Random^ rndforballs = gcnew Random;
private: System::Void start2_Click(System::Object^ sender, System::EventArgs^ e)
{
balls = gcnew array<ball^>(max);
for (int i = 0; i < max; i++)
balls[i] = gcnew ball;
point = 0;
generate->Start();
move->Start();
this->stop->Text = L"Stop";
this->stop->Enabled = true;
}
private: System::Void stop_Click(System::Object^ sender, System::EventArgs^ e)
{
if (this->stop->Text == L"Stop")
{
generate->Stop();
move->Stop();
this->stop->Text = L"Restart";
}
else
if (this->stop->Text == L"Restart")
{
this->stop->Text = L"Stop";
generate->Start();
move->Start();
}
}
private: System::Void pictureBox1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e)
{
int pw = pictureBox1->Width, ph = pictureBox1->Height;
for (int i = 0; i < point; i++)
if (balls[i]->y + ph < 0)
{
balls[i]->y = 0;
balls[i]->width = 1;
balls[i]->recalculate();
}
for (int i = 0; i < point; i++)
for (int j = i + 1; j < point; j++)
{
if ((balls[i]->xlb == balls[j]->x && balls[i]->ylb <= balls[j]->y && balls[i]->xrb == balls[j]->xrt && balls[i]->yrb <= balls[j]->yrt && balls[i]->y > balls[j]->ylb && balls[i]->yrt > balls[j]->yrb) || //bottom
(balls[i]->x == balls[j]->xlb && balls[i]->y >= balls[j]->ylb && balls[i]->xrt == balls[j]->xrb && balls[i]->yrt >= balls[j]->yrb && balls[i]->y > balls[j]->ylb && balls[i]->yrt > balls[j]->yrb) || //top
(balls[i]->x <= balls[j]->xrt && balls[i]->y == balls[j]->yrt && balls[i]->xlb <= balls[j]->xrb && balls[i]->ylb == balls[j]->yrb && balls[i]->xrt > balls[j]->x && balls[i]->xrb > balls[j]->xlb) || //left
(balls[i]->xrt >= balls[j]->x && balls[i]->yrt == balls[j]->y && balls[i]->xrb >= balls[j]->xlb && balls[i]->yrb == balls[j]->ylb && balls[i]->x < balls[j]->xrt && balls[i]->xlb < balls[j]->xrb) || //right
(balls[i]->xrb > balls[j]->x && balls[i]->yrb < balls[j]->y && balls[i]->xrb < balls[j]->xrb && balls[i]->yrb > balls[j]->yrb) || //bottom right
(balls[i]->xlb < balls[j]->xrt && balls[i]->ylb < balls[j]->yrt && balls[i]->xlb > balls[j]->xlb && balls[i]->ylb > balls[j]->ylb) || //bottom left
(balls[i]->x > balls[j]->x && balls[i]->y < balls[j]->y && balls[i]->x < balls[j]->xrb && balls[i]->y > balls[j]->yrb) || //top left
(balls[i]->xrt > balls[j]->xlb && balls[i]->yrt > balls[j]->ylb && balls[i]->xrt < balls[j]->xrt && balls[i]->yrt < balls[j]->yrt) || //top right
(balls[i]->x<balls[j]->x && balls[i]->y>balls[j]->y && balls[i]->xrt>balls[j]->xrt && balls[i]->yrt>balls[j]->yrt && balls[i]->xrb>balls[j]->xrb && balls[i]->yrb<balls[j]->yrb && balls[i]->xlb<balls[j]->xlb && balls[i]->ylb<balls[j]->ylb) || //inside
(balls[i]->x>balls[j]->x && balls[i]->y<balls[j]->y && balls[i]->xrt < balls[j]->xrt && balls[i]->yrt > balls[j]->yrt && balls[i]->xrb < balls[j]->xrb && balls[i]->yrb > balls[j]->yrb && balls[i]->xlb > balls[j]->xlb && balls[i]->ylb < balls[j]->ylb) || //around
(balls[i]->xlb < balls[j]->x && balls[i]->ylb <= balls[j]->y && balls[i]->xrb > balls[j]->xrt && balls[i]->yrb <= balls[j]->yrt && balls[i]->x < balls[j]->xlb && balls[i]->y > balls[j]->ylb && balls[i]->xrt > balls[j]->xrb && balls[i]->yrt > balls[j]->yrb) || // inside bottom
(balls[i]->x < balls[j]->xlb && balls[i]->y >= balls[j]->ylb && balls[i]->xrt > balls[j]->xrb && balls[i]->yrt >= balls[j]->yrb && balls[i]->xlb > balls[j]->x && balls[i]->ylb > balls[j]->y && balls[i]->xrb > balls[j]->xrt && balls[i]->yrb > balls[j]->yrt) || // inside top
(balls[i]->x <= balls[j]->xrt && balls[i]->y > balls[j]->yrt && balls[i]->xlb <= balls[j]->xrb && balls[i]->ylb < balls[j]->yrb && balls[i]->xrt > balls[j]->x && balls[i]->yrt > balls[j]->y && balls[i]->xrb > balls[j]->xlb && balls[i]->yrb < balls[j]->ylb) || //inside left
(balls[i]->xrt >= balls[j]->x && balls[i]->yrt > balls[j]->y && balls[i]->xrb >= balls[j]->xlb && balls[i]->yrb < balls[j]->ylb && balls[i]->x < balls[j]->xrt && balls[i]->y > balls[j]->yrt && balls[i]->xlb < balls[j]->xrb && balls[i]->ylb < balls[j]->yrb) || //inside right
(balls[j]->xlb < balls[i]->x&& balls[j]->ylb <= balls[i]->y && balls[j]->xrb > balls[i]->xrt && balls[j]->yrb <= balls[i]->yrt && balls[j]->x < balls[i]->xlb&& balls[j]->y > balls[i]->ylb && balls[j]->xrt > balls[i]->xrb && balls[j]->yrt > balls[i]->yrb) || // around bottom
(balls[j]->x < balls[i]->xlb&& balls[j]->y >= balls[i]->ylb && balls[j]->xrt > balls[i]->xrb && balls[j]->yrt >= balls[i]->yrb && balls[j]->xlb > balls[i]->x && balls[j]->ylb > balls[i]->y && balls[j]->xrb > balls[i]->xrt && balls[j]->yrb > balls[i]->yrt) || // around top
(balls[j]->x <= balls[i]->xrt && balls[j]->y > balls[i]->yrt && balls[j]->xlb <= balls[i]->xrb && balls[j]->ylb < balls[i]->yrb && balls[j]->xrt > balls[i]->x && balls[j]->yrt > balls[i]->y && balls[j]->xrb > balls[i]->xlb && balls[j]->yrb < balls[i]->ylb) || //around left
(balls[j]->xrt >= balls[i]->x && balls[j]->yrt > balls[i]->y && balls[j]->xrb >= balls[i]->xlb && balls[j]->yrb < balls[i]->ylb && balls[j]->x < balls[i]->xrt&& balls[j]->y > balls[i]->yrt&& balls[j]->xlb < balls[i]->xrb&& balls[j]->ylb < balls[i]->yrb)) //around right
{
ball^ tmp = gcnew ball;
tmp->x = (balls[i]->x + balls[j]->x) / 2;
tmp->y = (balls[i]->y + balls[j]->y) / 2;
tmp->width = (balls[i]->width + balls[j]->width) / 2;
//tmp->width = Math::Sqrt(balls[i]->width + balls[j]->width);
tmp->recalculate();
balls[i] = tmp;
balls[j]->width = 10;
balls[j]->y = 0;
balls[j]->x += rndforballs->Next() % pw+3;
balls[j]->recalculate();
}
}
for (int i = 0; i < point; i++)
e->Graphics->DrawEllipse(Pens::Black, balls[i]->x, balls[i]->y + ph, balls[i]->width, balls[i]->width);
}
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)
{
Random^ rnd = gcnew Random;
int pw = pictureBox1->Width, ph = pictureBox1->Height;
int k = rnd->Next() % 2;
if (point > max - 1)
point = 0;
for (int i = 0; i < k && point < max; i++)
{
balls[point]->width = 1;
balls[point]->y = 0;
balls[point]->x += rnd->Next() % pw;
balls[point]->recalculate();
point++;
}
pictureBox2->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MyForm::pictureBox1_Paint);
}
private: System::Void timer2_Tick(System::Object^ sender, System::EventArgs^ e)
{
Random^ rnd = gcnew Random;
for (int i = 0; i < point; i++)
{
balls[i]->y -= rnd->Next() % 10;
balls[i]->width += rnd->Next() % 2;
balls[i]->recalculate();
}
pictureBox2->Invalidate();
}
};
}
|
#pragma once
// refer to http://en.wikipedia.org/wiki/Strict_weak_ordering#Properties
template<typename InputIterator, typename Predicate>
bool has_irreflexivity(InputIterator first, InputIterator last, Predicate pred)
{
for(; first != last; ++first)
{
if(pred(*first, *first)) return false;
}
return true;
}
template<typename ForwardIterator, typename Predicate>
bool has_asymmetry(ForwardIterator first, ForwardIterator last, Predicate pred)
{
for(ForwardIterator x = first; x != last; ++x)
{
for(ForwardIterator y = first; y != last; ++y)
{
if(x != y)
{
if(pred(*x,*y))
{
if(pred(*y,*x)) return false;
}
}
}
}
return true;
}
template<typename ForwardIterator, typename Predicate>
bool has_transitivity(ForwardIterator first, ForwardIterator last, Predicate pred)
{
for(ForwardIterator x = first; x != last; ++x)
{
for(ForwardIterator y = first; y != last; ++y)
{
if(pred(*x,*y))
{
for(ForwardIterator z = first; z != last; ++z)
{
if(pred(*y,*z))
{
if(!pred(*x,*z)) return false;
}
}
}
}
}
return true;
}
template<typename ForwardIterator, typename Predicate>
bool has_transitivity_of_equivalence(ForwardIterator first, ForwardIterator last, Predicate pred)
{
for(ForwardIterator x = first; x != last; ++x)
{
for(ForwardIterator y = first; y != last; ++y)
{
if(pred(*x,*y))
{
for(ForwardIterator z = first; z != last; ++z)
{
if(!(pred(*x,*z) || pred(*z,*y))) return false;
}
}
}
}
return true;
}
template<typename ForwardIterator, typename Predicate>
bool is_strict_weak_ordering(ForwardIterator first, ForwardIterator last, Predicate pred)
{
return has_irreflexivity(first,last,pred) && has_asymmetry(first,last,pred) && has_transitivity(first,last,pred) && has_transitivity_of_equivalence(first,last,pred);
}
|
#pragma once
#include <core/data/Array.h>
#include <core/Size.h>
#include <core/sequence/count.h>
#include <qt/QtCore/Qt>
#include <qt/QtWidgets/QFrame>
#include <qt/QtWidgets/QLayout>
namespace launcher {
namespace qt {
template<typename A, typename... Args>
A * make_layout(Args const&... args) {
auto layout = new A(args...);
layout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
layout->setMargin(0);
layout->setSpacing(0);
return layout;
}
template<typename A>
QWidget * make_horizontal_grid_view(core::data::Array<A> const& items, int const& row_count) {
using core::Size;
using core::sequence::count;
auto layout = make_layout<QGridLayout>();
for (auto i = Size {0}; i < count(items); i += 1)
layout->addWidget(items(i), i % row_count, i / row_count);
auto view = new QFrame {};
view->setLayout(layout);
return view;
}
template<typename A>
QWidget * make_vertical_grid_view(core::data::Array<A> const& items, int const& column_count) {
using core::Size;
using core::sequence::count;
auto layout = make_layout<QGridLayout>();
for (auto i = Size {0}; i < count(items); i += 1)
layout->addWidget(items(i), i / column_count, i % column_count);
auto view = new QFrame {};
view->setLayout(layout);
return view;
}
}
}
|
#include "DetectMemoryLeak.h"
#include "Inventory.h"
#include "WeaponInfo\WeaponInfo.h"
#include "WeaponManager.h"
Inventory::Inventory() : m_iWeaponIndex(0)
{
}
Inventory::~Inventory()
{
}
void Inventory::addWeaponToInventory(CWeaponInfo* _newObject)
{
if (_newObject == NULL)
return;
weaponList.push_back(_newObject);
}
bool Inventory::removeWeaponFromInventory(CWeaponInfo* _existingObject)
{
// Find the entity's iterator
std::vector<CWeaponInfo*>::iterator findIter = std::find(weaponList.begin(), weaponList.end(), _existingObject);
// Remove from weaponManager
WeaponManager::GetInstance()->removeWeapon(_existingObject);
// Delete the entity if found
if (findIter != weaponList.end())
{
//delete *findIter;
findIter = weaponList.erase(findIter);
return true;
}
// Return false if not found
std::cout << "weapon not found\n";
return false;
}
std::vector<CWeaponInfo*> Inventory::getWeaponList()
{
return weaponList;
}
CWeaponInfo* Inventory::getPrimaryWeapon()
{
if (weaponList.size() <= 0)
return NULL;
return weaponList[m_iWeaponIndex];
}
//set weaponIndex
void Inventory::setWeaponIndex(const int _weaponIndex)
{
m_iWeaponIndex = _weaponIndex;
}
//get weaponIndex
int Inventory::getWeaponIndex(void)
{
return m_iWeaponIndex;
}
|
//--------------------------------------------------------------------
//
// Laboratory 11, In-lab Exercise 1 database.cs
//
// (Shell) Indexed accounts database program
//
//--------------------------------------------------------------------
// Builds a binary search tree index for the account records in the
// text file accounts.dat.
#include <iostream>
#include <fstream>
#include "BSTree.cpp"
using namespace std;
//--------------------------------------------------------------------
//
// Declarations specifying the accounts database
//
const int nameLength = 11; // Maximum number of characters in
// a name
const long bytesPerRecord = 37; // Number of bytes used to store
// each record in the accounts
// database file
struct AccountRecord
{
int acctID; // Account identifier
char firstName[nameLength], // Name of account holder
lastName[nameLength];
double balance; // Account balance
};
//--------------------------------------------------------------------
//
// Declaration specifying the database index
//
struct IndexEntry
{
int acctID; // (Key) Account identifier
long recNum; // Record number
int getKey () const
{ return acctID; } // Return key field
};
//--------------------------------------------------------------------
/**
* @file database.cpp
* @author Henry Huffman
* @version 1.1
* @brief This program will use the structs and basic variables given in the shell from the instructor to perform basic data base info manipulation.
* @details More specifically, this program reads in from a file, stores the data in the given BST and structs, outputs all the specified data in
* ascending order, gets input from the user, and outputs data from the given file.
*
* @date Friday, October 17th, 2014
*/
int main ()
{
cout << endl;
ifstream acctFile ("accounts.dat"); // Accounts database file
AccountRecord acctRec; // Account record
BSTree<IndexEntry,int> index; // Database index
IndexEntry entry; // Index entry
int searchID; // User input account ID
long recNum; // Record number
///create a temporary string
// acctFile.clear();
// acctFile.open("accounts.dat");
string temp;
recNum = acctFile.tellg();
// Iterate through the database records. For each record, read the
// account ID and add the (account ID, record number) pair to the
// index.
///take in the searchID
acctFile>>searchID;
///while the end of the data file is not found
while(!acctFile.eof())
{
///place searchID into entry struct
entry.acctID = searchID;
///place recNum into entry struct
entry.recNum = recNum;
///place current struct into index BST
index.insert(entry);
///ignore to get to the end of line
acctFile.ignore(37,'\n');
///take in the searchID
recNum = acctFile.tellg();
acctFile>>searchID;
}
// Output the account IDs in ascending order.
///output all the keys using the write keys member function
cout << "Account IDs : " << endl;
index.writeKeys();
///////////////////////////////////////////////////////////////formatting?
cout << endl;
// Clear the status flags for the database file.
acctFile.clear();
// Read an account ID from the keyboard and output the
// corresponding record.
///take in the specified searchID from the user
cout << "Enter account ID : ";
cin>>searchID;
while(cin.good()){
acctFile.clear();
///check to see if searchID is in index BST
if(index.retrieve(searchID, entry))
{
///if searchID is found,
///move to specified record
acctFile.seekg((entry.recNum));
cout << (entry.recNum/37)<<" : ";
///place acctID from file into specified struct
acctFile>>acctRec.acctID;
///place firstName from file into specified struct
acctFile>>acctRec.firstName;
///place lastName from file into specified struct
acctFile>>acctRec.lastName;
///place the balance from file into specified struct
acctFile>>acctRec.balance;
///output the acctID
cout<<acctRec.acctID << ' ';
///output firstName
cout<<acctRec.firstName << ' ';
///output lastName
cout<<acctRec.lastName << ' ';
///output the balance
cout<<acctRec.balance << ' ' << endl;
}
else
{
cout << "No record with that account ID" << endl;
}
cout << "Enter account ID (EOF to quit): ";
cin>>searchID;
}
//acctFile.close();
return 0;
}
|
// Copyright 2009-2016 Sandia Corporation. Under the terms
// of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2016, Sandia Corporation
// All rights reserved.
//
// This file is part of the SST software package. For license
// information, see the LICENSE file in the top level directory of the
// distribution.
#include <sst_config.h>
#include "sst/core/element.h"
#include "sst/core/component.h"
//#include "ariel.h"
//#include "arielcpu.h"
//#include "arieltexttracegen.h"
//#ifdef HAVE_LIBZ
//#include "arielgzbintracegen.h"
//#endif
//#define STRINGIZE(input) #input
#include "Samba.h"
#include "TLBhierarchy.h"
#include<iostream>
using namespace SST;
using namespace SST::SambaComponent;
static Component* create_Samba(ComponentId_t id, Params& params)
{
return new Samba(id,params); //dynamic_cast<SST::Component*>( Samba(id,params));
};
static const ElementInfoStatistic Samba_statistics[] = {
{ "tlb_hits", "Number of TLB hits", "requests", 1}, // Name, Desc, Enable Level
{ "tlb_misses", "Number of TLB misses", "requests", 1}, // Name, Desc, Enable Level
{ "total_waiting", "The total waiting time", "cycles", 1}, // Name, Desc, Enable Level
{ "write_requests", "Stat write_requests", "requests", 1},
{ "tlb_shootdown", "Number of TLB clears because of page-frees", "shootdowns", 2 },
{ "tlb_page_allocs", "Number of pages allocated by the memory manager", "pages", 2 },
{ NULL, NULL, NULL, 0 }
};
static const ElementInfoParam Samba_params[] = {
{"corecount", "Number of CPU cores to emulate, i.e., number of private Sambas", "1"},
{"levels", "Number of TLB levels per Samba", "1"},
{"os_page_size", "This represents the size of frames the OS allocates in KB", "4"}, // This is a hack, assuming the OS allocated only one page size, this will change later
{"sizes_L%(levels)", "Number of page sizes supported by Samba", "1"},
{"page_size%(sizes)_L%(levels)d", "the page size of the supported page size number x in level y","4"},
{"max_outstanding_L%(levels)d", "the number of max outstanding misses","1"},
{"max_width_L%(levels)d", "the number of accesses on the same cycle","1"},
{"size%(sizes)_L%(levels)d", "the number of entries of page size number x on level y","1"},
{"upper_link_L%(levels)d", "the latency of the upper link connects to this structure","1"},
{"assoc%(sizes)_L%(levels)d", "the associativity of size number X in Level Y", "1"},
{"clock", "the clock frequency", "1GHz"},
{"latency_L%(levels)d", "the access latency in cycles for this level of memory","1"},
{"parallel_mode_L%(levels)d", "this is for the corner case of having a one cycle overlap with accessing cache","0"},
{"page_walk_latency", "This is the page walk latency in cycles just in case no page walker", "50"},
{NULL, NULL, NULL},
};
static const ElementInfoPort Samba_ports[] = {
{"cpu_to_mmu%(corecount)d", "Each Samba link to its core", NULL},
{"mmu_to_cache%(corecount)d", "Each Samba to its corresponding cache", NULL},
{"alloc_link_%(corecount)d", "Each core's link to an allocation tracker (e.g. memSieve)", NULL},
{NULL, NULL, NULL}
};
static const ElementInfoModule modules[] = {
{ NULL, NULL, NULL, NULL, NULL, NULL }
};
// Needs to have as much components as defined in the elemennt
static const ElementInfoComponent components[] = {
{ "Samba",
"Memory Management Unit (MMU) Componenet of SST",
NULL,
create_Samba,
Samba_params,
Samba_ports,
COMPONENT_CATEGORY_PROCESSOR,
Samba_statistics
},
{ NULL, NULL, NULL, NULL, NULL, NULL, 0 }
};
extern "C" {
ElementLibraryInfo Samba_eli = {
"Samba",
"MMU Unit",
components,
NULL, /* Events */
NULL, /* Introspectors */
modules
};
}
|
#pragma once
#include "CppCommons.hh"
#include <string>
#include <vector>
namespace SQLiteWrapper {
enum class DBType {
integer, real, const_char
};
struct Column {
inline const int toInt() const { return std::stoi(value); }
inline const float toFloat() const { return std::stof(value); }
inline const bool toBool() const { return static_cast<bool>(std::stoi(value)); }
std::string name{ "" };
std::string value{ "" };
int type{ 0 };
};
struct Row {
inline const int intAsId(const int _idx) const { return columns.at(_idx).toInt(); }
inline const std::string stringAsId(const int _idx) const { return columns.at(_idx).value; }
unsigned int id{ 0 };
std::vector<Column> columns;
};
}
|
// RTSPClientDlg.cpp: 实现文件
//
#include "stdafx.h"
#include "RTSPClient.h"
#include "RTSPClientDlg.h"
#include "afxdialogex.h"
#include <string>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CRTSPUrlDlg
class CRTSPUrlDlg : public CDialogEx
{
public:
CRTSPUrlDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_RTSP_URL };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
virtual BOOL OnInitDialog();
// 实现
protected:
DECLARE_MESSAGE_MAP()
public:
CEdit m_rtsp_url_ctrl;
CString m_rtsp_url;
CString getRtspUrl();
afx_msg void OnBnClickedOk();
};
CRTSPUrlDlg::CRTSPUrlDlg() : CDialogEx(IDD_RTSP_URL)
{
}
void CRTSPUrlDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_INPUT_URL, m_rtsp_url_ctrl);
}
BEGIN_MESSAGE_MAP(CRTSPUrlDlg, CDialogEx)
ON_BN_CLICKED(IDOK, &CRTSPUrlDlg::OnBnClickedOk)
END_MESSAGE_MAP()
CString CRTSPUrlDlg::getRtspUrl() {
CString temp;
m_rtsp_url_ctrl.GetWindowText(temp);
return temp;
}
BOOL CRTSPUrlDlg::OnInitDialog() {
CDialog::OnInitDialog();
m_rtsp_url_ctrl.SetWindowTextW(L"rtsp://rtsp.yunyoujun.cn:554/adamas.mp3");
return TRUE;
}
// CRTSPClientDlg 对话框
CRTSPClientDlg::CRTSPClientDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_RTSPCLIENT_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDI_LOGO);
}
CRTSPClientDlg::~CRTSPClientDlg()
{
//TEARDOWN
m_rtsp_request.RequestTeardown();
m_cs_tcp.Send(m_rtsp_request.request.c_str(), strlen(m_rtsp_request.request.c_str()));
// close
m_cs_tcp.Close();
m_cs_udp.Close();
m_fs.close();
}
void CRTSPClientDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_PROGRESS_SLIDER, m_progressBar);
DDX_Control(pDX, IDC_VOLUME_SLIDER, m_volBar);
DDX_Control(pDX, IDC_BTN_PLAY, m_btnPlay);
DDX_Control(pDX, IDC_BTN_STOP, m_btnStop);
DDX_Control(pDX, IDC_START_TIME, m_startTime);
DDX_Control(pDX, IDC_END_TIME, m_endTime);
DDX_Control(pDX, IDC_TXT_VOLUME, m_volText);
DDX_Control(pDX, IDC_AUDIO_NAME, m_audioName);
//DDX_Control(pDX, IDC_INPUT_URL, m_url);
DDX_Control(pDX, IDC_VOL, m_btnVol);
}
BEGIN_MESSAGE_MAP(CRTSPClientDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BTN_PLAY, &CRTSPClientDlg::OnBnClickedBtnPlay)
ON_BN_CLICKED(IDC_BTN_STOP, &CRTSPClientDlg::OnBnClickedBtnStop)
ON_WM_HSCROLL()
ON_WM_TIMER()
ON_WM_CTLCOLOR()
ON_COMMAND(ID_OPEN_RTSP, &CRTSPClientDlg::OnOpenRtsp)
ON_COMMAND(ID_OPEN_LOCAL, &CRTSPClientDlg::OnOpenLocal)
ON_BN_CLICKED(IDC_VOL, &CRTSPClientDlg::OnBnClickedVol)
END_MESSAGE_MAP()
// CRTSPClientDlg 消息处理程序
BOOL CRTSPClientDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
//icon
HBITMAP hBmp_play = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_PLAY));
HBITMAP hBmp_pause = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_PAUSE));
HBITMAP hBmp_stop = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_STOP));
HBITMAP hBmp_volUp = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_VOL_UP));
m_btnPlay.SetBitmap(hBmp_play);
m_btnStop.SetBitmap(hBmp_stop);
m_btnVol.SetBitmap(hBmp_volUp);
// TODO: 在此添加额外的初始化代码
g_init = FALSE;
g_rtsp = FALSE;
g_local = FALSE;
g_play = FALSE;
g_pause = FALSE;
g_adjust = FALSE;
g_mute = FALSE;
m_curTime = 0;
m_progressBar.SetRange(0, 100);
m_volBar.SetRange(0, 100);
m_volBar.SetPos(100);
m_volText.SetWindowText(_T("100"));
// bold
//CFont pfont;
//pfont.CreateFontW(10, 0, 0, 0, FW_BOLD, 0, 1, 0, 0, 0, 0, 0, 0, _T("Mircosoft YaHei"));
//m_audioName.SetFont(&pfont);
// whole y cannot be display
m_btnPlay.EnableWindow(FALSE);
m_progressBar.EnableWindow(FALSE);
//m_url = "rtsp://computing.cuc.edu.cn:8554/Angel.mp3";
//m_url = "rtsp://rtsp.yunyoujun.cn:554/test.mp3";
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CRTSPClientDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CRTSPClientDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
HBRUSH CRTSPClientDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hBrush = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
CRect ctrlRect;
pWnd->GetClientRect(&ctrlRect);
//switch (pWnd->GetDlgCtrlID())
//{
//case IDC_PROGRESS_SLIDER:
//case IDC_VOLUME_SLIDER:
CBrush mybrush(RGB(255, 255, 255));
pDC->FillRect(ctrlRect, &mybrush);
mybrush.DeleteObject();
pDC->SetBkMode(TRANSPARENT);
hBrush = (HBRUSH)GetStockObject(NULL_BRUSH);
//break;
//}
return hBrush;
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CRTSPClientDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CRTSPClientDlg::OnBnClickedBtnPlay()
{
if (!g_play)
{
if (g_local)
{
if (!g_init)
{
AfxBeginThread(playThread, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL);
g_init = TRUE;
}
else if (g_pause)
{
m_player.Play();
g_pause = FALSE;
g_play = TRUE;
HBITMAP hBmp_pause = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_PAUSE));
m_btnPlay.SetBitmap(hBmp_pause);
}
}
if (g_rtsp)
{
if (!g_init)
{
AfxBeginThread(rtspThread, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL);
g_init = TRUE;
}
else if (g_pause)
{
m_rtsp_request.RequestPlay(PLAY_AFTER_PAUSE);
m_cs_tcp.Send(m_rtsp_request.request.c_str(), strlen(m_rtsp_request.request.c_str()));
m_cs_tcp.Recv(m_buf);
m_rtsp_reply.response = m_buf;
m_player.Play();
if (!m_rtsp_reply.CheckRtspResponse(PLAY))
{
TRACE(L"PLAY failed with error.");
}
else {
g_play = TRUE;
g_pause = FALSE;
HBITMAP hBmp_pause = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_PAUSE));
m_btnPlay.SetBitmap(hBmp_pause);
}
}
}
}
else {
if (g_local)
{
m_player.Pause();
g_pause = TRUE;
g_play = FALSE;
HBITMAP hBmp_play = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_PLAY));
m_btnPlay.SetBitmap(hBmp_play);
}
if (g_rtsp)
{
m_player.Pause();
m_rtsp_request.RequestPause();
m_cs_tcp.Send(m_rtsp_request.request.c_str(), strlen(m_rtsp_request.request.c_str()));
m_cs_tcp.Recv(m_buf);
m_rtsp_reply.response = m_buf;
if (!m_rtsp_reply.CheckRtspResponse(PAUSE))
{
AfxMessageBox(L"PAUSE failed with error.");
}
else {
g_pause = TRUE;
g_play = FALSE;
HBITMAP hBmp_play = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_PLAY));
m_btnPlay.SetBitmap(hBmp_play);
}
}
}
}
void CRTSPClientDlg::OnBnClickedBtnStop()
{
CString volumeStr;
m_curTime = 0;
m_curPos = 0;
c_fileLength = 0;
m_player.Stop();
if (g_local)
{
g_local = FALSE;
KillTimer(SETLOCALTIME);
m_progressBar.SetPos(0);
m_startTime.SetWindowText(L"00:00");
}
if (g_rtsp)
{
g_rtsp = FALSE;
KillTimer(SETRTSPTIME);
m_progressBar.SetPos(0);
m_startTime.SetWindowText(L"00:00");
//TEARDOWN
m_rtsp_request.RequestTeardown();
m_cs_tcp.Send(m_rtsp_request.request.c_str(), strlen(m_rtsp_request.request.c_str()));
m_cs_tcp.Recv(m_buf);
m_rtsp_reply.response = m_buf;
if (!m_rtsp_reply.CheckRtspResponse(TEARDOWN) && m_rtsp_reply.Cseq != m_rtsp_request.Cseq)
{
TRACE(L"TEARDOWN failed with error.");
}
m_cs_tcp.Close();
m_cs_udp.Close();
m_fs.close();
}
g_init = FALSE;
g_pause = FALSE;
g_play = FALSE;
g_adjust = FALSE;
m_audioName.SetWindowText(L"YunYou - AudioPlayer");
AfxGetMainWnd()->SetWindowTextW(L"RTSPClient");
HBITMAP hBmp_play = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_PLAY));
m_btnPlay.SetBitmap(hBmp_play);
}
UINT CRTSPClientDlg::rtspThread(LPVOID lpParam)
{
CRTSPClientDlg *p = (CRTSPClientDlg *)lpParam;
p->m_rtsp_request.url = p->c_url;
if (!p->m_cs_tcp.Open(TCP))
{
AfxMessageBox(L"Socket failed with error.");
}
if (!p->m_cs_tcp.Connect(p->cur_url.getIp().c_str(), p->cur_url.getPort()))
{
AfxMessageBox(L"Connect failed with error.");
}
//OPTIONS
p->m_rtsp_request.RequestOptions();
p->m_cs_tcp.Send(p->m_rtsp_request.request.c_str(), strlen(p->m_rtsp_request.request.c_str()));
p->m_cs_tcp.Recv(p->m_buf);
p->m_rtsp_reply.response = p->m_buf;
if (!p->m_rtsp_reply.CheckRtspResponse(OPTIONS) || p->m_rtsp_reply.Cseq != p->m_rtsp_request.Cseq)
{
AfxMessageBox(L"OPTIONS failed with error.");
return -1;
}
//DESCRIBE
p->m_rtsp_request.RequestDescribe();
p->m_cs_tcp.Send(p->m_rtsp_request.request.c_str(), strlen(p->m_rtsp_request.request.c_str()));
p->m_cs_tcp.Recv(p->m_buf);
p->m_rtsp_reply.response = p->m_buf;
if (!p->m_rtsp_reply.CheckRtspResponse(DESCRIBE) || p->m_rtsp_reply.Cseq != p->m_rtsp_request.Cseq)
{
AfxMessageBox(L"DESCRIBE failed with error.");
return -1;
}
p->m_rtsp_reply.GetAudioLen();
// why? rtsp time more than local
p->c_fileLength = p->m_rtsp_reply.file_length;
//SETUP
p->m_rtsp_request.RequestSetup();
p->m_cs_tcp.Send(p->m_rtsp_request.request.c_str(), strlen(p->m_rtsp_request.request.c_str()));
p->m_cs_tcp.Recv(p->m_buf);
p->m_rtsp_reply.response = p->m_buf;
if (!p->m_rtsp_reply.CheckRtspResponse(SETUP) || p->m_rtsp_reply.Cseq != p->m_rtsp_request.Cseq)
{
AfxMessageBox(L"SETUP failed with error.");
return -1;
}
else {
p->m_rtsp_reply.GetResponseClientRtpPort();
p->m_rtsp_reply.GetResponseServerRtpPort();
p->c_clientRtpPort = p->m_rtsp_reply.ClientRtpPort;
p->c_serverRtpPort = p->m_rtsp_reply.ServerRtpPort;
}
//PLAY
p->m_rtsp_request.Session = p->m_rtsp_reply.Session;
p->m_rtsp_request.RequestPlay(0); // from head
p->m_cs_tcp.Send(p->m_rtsp_request.request.c_str(), strlen(p->m_rtsp_request.request.c_str()));
Sleep(100);
p->m_cs_tcp.Recv(p->m_buf);
p->m_rtsp_reply.response = p->m_buf;
if (!p->m_rtsp_reply.CheckRtspResponse(PLAY) || p->m_rtsp_reply.Cseq != p->m_rtsp_request.Cseq)
{
AfxMessageBox(L"PLAY failed with error.");
return -1;
}
else {
AfxBeginThread(rtpThread, p, THREAD_PRIORITY_NORMAL, 0, 0, NULL);
Sleep(1000);
AfxBeginThread(playThread, p, THREAD_PRIORITY_NORMAL, 0, 0, NULL);
}
//PARAMETER
// wait p->play change
Sleep(100);
while (p->g_rtsp && p->g_play)
{
p->m_rtsp_request.RequestGetparameter();
p->m_cs_tcp.Send(p->m_rtsp_request.request.c_str(), strlen(p->m_rtsp_request.request.c_str()));
p->m_cs_tcp.Recv(p->m_buf);
p->m_rtsp_reply.response = p->m_buf;
if (!p->m_rtsp_reply.CheckRtspResponse(GET_PARAMETER) || p->m_rtsp_reply.Cseq != p->m_rtsp_request.Cseq)
{
AfxMessageBox(L"GET PARAMETER failed with error.");
}
// because timeout: 65s
Sleep(60000);
}
p->m_cs_tcp.Close();
return 0;
}
UINT CRTSPClientDlg::rtpThread(LPVOID lpParam)
{
CRTSPClientDlg *p = (CRTSPClientDlg *)lpParam;
p->c_filePath = "./_cache.mp3";
p->m_fs.open(p->c_filePath, ios::out | ios::binary);
if (!p->m_cs_udp.Open(UDP))
{
AfxMessageBox(L"Socket failed with error.");
return -1;
}
if ( !p->m_cs_udp.Bind(atoi(p->c_clientRtpPort.c_str())) )
{
AfxMessageBox(L"Bind failed with error.");
return -1;
}
while (p->g_rtsp && p->m_cs_udp.m_socket != INVALID_SOCKET)
{
int recv_size = p->m_cs_udp.RecvFrom(p->m_rtp_buf, p->cur_url.getIp().c_str(), atoi(p->c_serverRtpPort.c_str()));
if (recv_size > 0) {
// header 16
// https://datatracker.ietf.org/doc/rfc3550/?include_text=1
// 5.1 RTP Fixed Header Fields
p->m_fs.write(p->m_rtp_buf + 16, recv_size - 16);
}
}
p->m_cs_udp.Close();
p->m_fs.close();
return 0;
}
UINT CRTSPClientDlg::playThread(LPVOID lpParam)
{
CRTSPClientDlg *p = (CRTSPClientDlg *)lpParam;
p->m_progressBar.EnableWindow(TRUE);
p->g_play = TRUE;
p->m_player.OpenMedia(p->c_filePath.c_str());
p->m_player.Play();
//p->m_btnPlay.SetWindowText(_T("PAUSE"));
HBITMAP hBmp_pause = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_PAUSE));
p->m_btnPlay.SetBitmap(hBmp_pause);
// set end time
libvlc_time_t local_fileLength;
local_fileLength = p->m_player.GetLength();
if (p->c_fileLength) {
local_fileLength = p->c_fileLength;
}
CTimeSpan length(static_cast<time_t>(local_fileLength / 1000));
CString endTimeStr;
endTimeStr.Format(L"%02d:%02d", length.GetMinutes(), length.GetSeconds());
p->m_endTime.SetWindowText(endTimeStr);
if (p->g_local) {
UINT_PTR m_nWindowTimer = p->SetTimer(SETLOCALTIME, 100, NULL);
}
else if (p->g_rtsp) {
UINT_PTR m_nWindowTimer = p->SetTimer(SETRTSPTIME, 100, NULL);
}
p->m_btnPlay.EnableWindow(TRUE);
return 0;
}
void CRTSPClientDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
//reinterpret_cast <new_type> (expression),从CScrollBar指针到CSliderCtrl指针
//reinterpret_cast运算符是用来处理无关类型之间的转换;它会产生一个新的值,这个值会有与原始参数(expression)有完全相同的比特位。
CSliderCtrl* pSlider = reinterpret_cast<CSliderCtrl*>(pScrollBar);
if (*pSlider == m_volBar)
{
g_mute = false;
int pos = m_volBar.GetPos();
m_player.SetVolume(pos);
CString volumeStr;
volumeStr.Format(L"%d", pos);
m_volText.SetWindowText(volumeStr);
// icon
HBITMAP hBmp_volDown = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_VOL_DOWN));
HBITMAP hBmp_volUp = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_VOL_UP));
HBITMAP hBmp_volMute = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_VOL_MUTE));
if (pos > 50) {
m_btnVol.SetBitmap(hBmp_volUp);
}
else if (pos > 0) {
m_btnVol.SetBitmap(hBmp_volDown);
}
else {
m_btnVol.SetBitmap(hBmp_volMute);
}
}
if (*pSlider == m_progressBar)
{
Sleep(100);
if (g_local)
{
int pos = m_progressBar.GetPos();
m_player.SetTime(pos * c_fileLength / 100);
}
if (g_rtsp)
{
int pos = m_progressBar.GetPos();
m_curTime = pos * c_fileLength / 100;
int start_second = pos * c_fileLength / 100;
m_rtsp_request.RequestPlay(start_second / 1000);
m_cs_tcp.Send(m_rtsp_request.request.c_str(), strlen(m_rtsp_request.request.c_str()));
m_cs_tcp.Recv(m_buf);
m_rtsp_reply.response = m_buf;
if (!m_rtsp_reply.CheckRtspResponse(PLAY) || m_rtsp_reply.Cseq != m_rtsp_request.Cseq)
{
TRACE(L"PLAY failed with error.");
}
g_adjust = TRUE;
}
}
CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);
}
void CRTSPClientDlg::OnTimer(UINT_PTR nIDEvent)
{
libvlc_time_t local_fileLength;
libvlc_time_t rtsp_fileLength;
if (nIDEvent == SETLOCALTIME)
{
local_fileLength = m_player.GetLength();
c_fileLength = local_fileLength;
m_curTime = m_player.GetPlayTime();
//将int转换为time_t类型
//time_t:秒数
//CTimeSpan:存储时间跨度中的秒数
CTimeSpan actualPosition(static_cast<time_t>(m_curTime / 1000));
CString currentTimeStr;
currentTimeStr.Format(L"%02d:%02d", actualPosition.GetMinutes(), actualPosition.GetSeconds());
m_startTime.SetWindowText(currentTimeStr);
m_curPos = (int)(m_curTime * 100 / local_fileLength) + 1;
m_progressBar.SetPos(m_curPos);
}
else if (nIDEvent == SETRTSPTIME)
{
rtsp_fileLength = c_fileLength;
if (g_adjust)
{
int pos = m_progressBar.GetPos();
m_curTime = pos * c_fileLength / 100;
g_adjust = FALSE;
}
else if (m_curTime < rtsp_fileLength && !g_pause)
{
m_curTime = m_curTime + 100;
}
// common
CTimeSpan actualPosition(static_cast<time_t>(m_curTime / 1000));
CString currentTimeStr;
currentTimeStr.Format(L"%02d:%02d", actualPosition.GetMinutes(), actualPosition.GetSeconds());
m_startTime.SetWindowText(currentTimeStr);
m_curPos = (int)(m_curTime * 100 / rtsp_fileLength);
m_progressBar.SetPos(m_curPos);
}
if (m_curPos == 100) {
g_play = FALSE;
}
CDialog::OnTimer(nIDEvent);
}
void CRTSPClientDlg::OnOpenRtsp()
{
// TODO: 在此添加命令处理程序代码
CRTSPUrlDlg m_open_rtsp;
if (m_open_rtsp.DoModal() == IDOK) {
OnBnClickedBtnStop();
m_url = m_open_rtsp.m_rtsp_url;
CString output;
//CW2A将宽字符集(Unicode)转化为多字符集(ASCII)
c_url = CT2CA(m_url);
cur_url.read(c_url);
if (cur_url.getProtocol() == "rtsp") {
g_rtsp = TRUE;
c_fileName = cur_url.getName();
output = c_fileName.c_str();
m_audioName.SetWindowText(CString(cur_url.getName().c_str()));
CString header = _T("RTSPClient - ") + output;
AfxGetMainWnd()->SetWindowTextW(header);
// play
OnBnClickedBtnPlay();
}
else {
MessageBox(L"The URL is invalid. Try again.");
return;
}
}
}
void CRTSPClientDlg::OnOpenLocal()
{
// TODO: 在此添加命令处理程序代码
CString filePath;
CFileDialog dlg(TRUE,
NULL,
NULL,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
(LPCTSTR)_TEXT("MPEG (*.mp3)|*.mp3|All Files (*.*)|*.*||"), //过滤,只能选择:mp3或all files
NULL);
if (dlg.DoModal() == IDOK)
{
OnBnClickedBtnStop();
filePath = dlg.GetPathName();
c_filePath = CT2CA(filePath.GetBuffer(0));
g_local = TRUE;
int pos = c_filePath.find_last_of('\\', c_filePath.length());
c_fileName = c_filePath.substr(pos + 1, c_filePath.length());
CString output;
output = c_fileName.c_str();
m_audioName.SetWindowText(output);
CString header = _T("RTSPClient - ") + output;
AfxGetMainWnd()->SetWindowTextW(header);
OnBnClickedBtnPlay();
}
}
void CRTSPUrlDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
m_rtsp_url = getRtspUrl();
CDialogEx::OnOK();
}
void CRTSPClientDlg::OnBnClickedVol()
{
HBITMAP hBmp_volDown = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_VOL_DOWN));
HBITMAP hBmp_volUp = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_VOL_UP));
HBITMAP hBmp_volMute = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_VOL_MUTE));
if (g_mute) {
g_mute = false;
int vol = m_volBar.GetPos();
if (vol > 50) {
m_btnVol.SetBitmap(hBmp_volUp);
}
else if (vol > 0){
m_btnVol.SetBitmap(hBmp_volDown);
}
m_player.SetVolume(vol);
}
else {
g_mute = true;
m_btnVol.SetBitmap(hBmp_volMute);
m_player.SetVolume(0);
}
}
|
// CmnDlgView.cpp : CCmnDlgView 类的实现
//
#include "stdafx.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "CmnDlg.h"
#endif
#include "CmnDlgDoc.h"
#include "CmnDlgView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CCmnDlgView
IMPLEMENT_DYNCREATE(CCmnDlgView, CView)
BEGIN_MESSAGE_MAP(CCmnDlgView, CView)
// 标准打印命令
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CCmnDlgView::OnFilePrintPreview)
ON_WM_CONTEXTMENU()
ON_WM_RBUTTONUP()
END_MESSAGE_MAP()
// CCmnDlgView 构造/析构
CCmnDlgView::CCmnDlgView()
{
// TODO: 在此处添加构造代码
}
CCmnDlgView::~CCmnDlgView()
{
}
BOOL CCmnDlgView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CView::PreCreateWindow(cs);
}
// CCmnDlgView 绘制
void CCmnDlgView::OnDraw(CDC* /*pDC*/)
{
CCmnDlgDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
}
// CCmnDlgView 打印
void CCmnDlgView::OnFilePrintPreview()
{
#ifndef SHARED_HANDLERS
AFXPrintPreview(this);
#endif
}
BOOL CCmnDlgView::OnPreparePrinting(CPrintInfo* pInfo)
{
// 默认准备
return DoPreparePrinting(pInfo);
}
void CCmnDlgView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加额外的打印前进行的初始化过程
}
void CCmnDlgView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加打印后进行的清理过程
}
void CCmnDlgView::OnRButtonUp(UINT /* nFlags */, CPoint point)
{
ClientToScreen(&point);
OnContextMenu(this, point);
}
void CCmnDlgView::OnContextMenu(CWnd* /* pWnd */, CPoint point)
{
#ifndef SHARED_HANDLERS
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
#endif
}
// CCmnDlgView 诊断
#ifdef _DEBUG
void CCmnDlgView::AssertValid() const
{
CView::AssertValid();
}
void CCmnDlgView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CCmnDlgDoc* CCmnDlgView::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCmnDlgDoc)));
return (CCmnDlgDoc*)m_pDocument;
}
#endif //_DEBUG
// CCmnDlgView 消息处理程序
|
/**
* @author: Karthick < karthikn2099@gmail.com >
* @github: https://github.com/karthikn2098
* @date: 08/01/2018
*/
#include <bits/stdc++.h>
using namespace std;
int sumOfDigits(int N) {
if( N == 0 ) {
return 0;
}
return ( sumOfDigits(N/10) + N%10 );
}
int main(void) {
int N;
cout << "Enter the Number: ";
cin >> N;
cout << "\nThe sum of digits = " << sumOfDigits(N);
return 0;
}
/*
---------------------
Sample Input/Output
---------------------
Enter the Number: 1234
The sum of digits = 10
*/
|
#include <jni.h>
#include <core/Defs.hpp>
#include <core/String.hpp>
#include <core/Vector2.hpp>
#include <core/Vector3.hpp>
#include "gdn/gast_node.h"
#include "gast_manager.h"
#include "utils.h"
// Current class and package names assumed for the Java side.
#undef JNI_PACKAGE_NAME
#define JNI_PACKAGE_NAME org_godotengine_plugin_gast
#undef JNI_CLASS_NAME
#define JNI_CLASS_NAME GastNode
namespace {
using namespace gast;
using namespace godot;
inline GastNode *from_pointer(jlong gast_node_pointer) {
return reinterpret_cast<GastNode *>(gast_node_pointer);
}
inline jlong to_pointer(GastNode *gast_node) {
return reinterpret_cast<intptr_t>(gast_node);
}
} // namespace
extern "C" {
JNIEXPORT jlong JNICALL
JNI_METHOD(acquireAndBindGastNode)(JNIEnv *env, jobject, jstring parent_node_path,
jboolean empty_parent) {
return to_pointer(GastManager::get_singleton_instance()->acquire_and_bind_gast_node(
jstring_to_string(env, parent_node_path), empty_parent));
}
JNIEXPORT void JNICALL
JNI_METHOD(unbindAndReleaseGastNode)(JNIEnv *, jobject, jlong node_pointer) {
GastManager::get_singleton_instance()->unbind_and_release_gast_node(from_pointer(node_pointer));
}
JNIEXPORT jstring JNICALL JNI_METHOD(nativeGetNodePath)(JNIEnv *env, jobject, jlong node_pointer) {
String node_path = String("");
GastNode *gast_node = from_pointer(node_pointer);
if (gast_node) {
node_path = gast_node->get_path();
}
return string_to_jstring(env, node_path);
}
JNIEXPORT void JNICALL
JNI_METHOD(nativeSetName)(JNIEnv *env, jobject, jlong node_pointer, jstring new_name) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_name(jstring_to_string(env, new_name));
}
JNIEXPORT jboolean JNICALL
JNI_METHOD(updateGastNodeParent)(JNIEnv *env, jobject, jlong node_pointer,
jstring new_parent_node_path, jboolean empty_parent) {
return GastManager::get_singleton_instance()->update_gast_node_parent(
from_pointer(node_pointer),
jstring_to_string(env, new_parent_node_path), empty_parent);
}
JNIEXPORT jint JNICALL
JNI_METHOD(getTextureId)(JNIEnv *, jobject, jlong node_pointer, jint surface_index) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL_V(gast_node, kInvalidTexId);
return gast_node->get_external_texture_id(surface_index);
}
JNIEXPORT void JNICALL
JNI_METHOD(updateGastNodeVisibility)(JNIEnv *, jobject, jlong node_pointer,
jboolean should_duplicate_parent_visibility,
jboolean visible) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
bool is_visible = should_duplicate_parent_visibility ? gast_node->is_visible_in_tree()
: gast_node->is_visible();
if (is_visible != visible) {
gast_node->set_visible(visible);
}
}
JNIEXPORT void JNICALL
JNI_METHOD(setGastNodeCollidable)(JNIEnv *, jobject, jlong node_pointer, jboolean collidable) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_collidable(collidable);
}
JNIEXPORT jboolean JNICALL
JNI_METHOD(isGastNodeCollidable)(JNIEnv *, jobject, jlong node_pointer) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL_V(gast_node, kDefaultCollidable);
return gast_node->is_collidable();
}
JNIEXPORT void JNICALL
JNI_METHOD(setGastNodeCurved)(JNIEnv *, jobject, jlong node_pointer, jboolean curved) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_curved(curved);
}
JNIEXPORT jboolean JNICALL
JNI_METHOD(isGastNodeCurved)(JNIEnv *, jobject, jlong node_pointer) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL_V(gast_node, kDefaultCurveValue);
return gast_node->is_curved();
}
JNIEXPORT jboolean JNICALL JNI_METHOD(isGazeTracking)(JNIEnv *, jobject, jlong node_pointer) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL_V(gast_node, kDefaultGazeTracking);
return gast_node->is_gaze_tracking();
}
JNIEXPORT void JNICALL
JNI_METHOD(setGazeTracking)(JNIEnv *, jobject, jlong node_pointer, jboolean gaze_tracking) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_gaze_tracking(gaze_tracking);
}
JNIEXPORT jboolean JNICALL JNI_METHOD(isRenderOnTop)(JNIEnv *, jobject, jlong node_pointer) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL_V(gast_node, kDefaultRenderOnTop);
return gast_node->is_render_on_top();
}
JNIEXPORT void JNICALL
JNI_METHOD(setRenderOnTop)(JNIEnv *, jobject, jlong node_pointer, jboolean render_on_top) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_render_on_top(render_on_top);
}
JNIEXPORT jlong JNICALL JNI_METHOD(getCollisionLayers)(JNIEnv*, jobject, jlong node_pointer) {
GastNode* gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL_V(gast_node, false);
return gast_node->get_collision_layer();
}
JNIEXPORT void JNICALL
JNI_METHOD(setCollisionLayers)(JNIEnv*, jobject, jlong node_pointer, jlong layers) {
GastNode* gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_collision_layer(layers);
}
JNIEXPORT jlong JNICALL JNI_METHOD(getCollisionMasks)(JNIEnv*, jobject, jlong node_pointer) {
GastNode* gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL_V(gast_node, false);
return gast_node->get_collision_mask();
}
JNIEXPORT void JNICALL
JNI_METHOD(setCollisionMasks)(JNIEnv*, jobject, jlong node_pointer, jlong masks) {
GastNode* gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_collision_mask(masks);
}
JNIEXPORT jfloat JNICALL
JNI_METHOD(getGastNodeGradientHeightRatio)(JNIEnv *, jobject, jlong node_pointer) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL_V(gast_node, kDefaultGradientHeightRatio);
return gast_node->get_gradient_height_ratio();
}
JNIEXPORT void JNICALL
JNI_METHOD(setGastNodeGradientHeightRatio)(JNIEnv *, jobject, jlong node_pointer, jfloat ratio) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_gradient_height_ratio(ratio);
}
JNIEXPORT void JNICALL
JNI_METHOD(updateGastNodeSize)(JNIEnv *, jobject, jlong node_pointer, jfloat width,
jfloat height) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_size(Vector2(width, height));
}
JNIEXPORT void JNICALL JNI_METHOD(updateAlpha)(JNIEnv *, jobject, jlong node_pointer, jfloat alpha) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_alpha(alpha);
}
JNIEXPORT void JNICALL
JNI_METHOD(updateGastNodeLocalTranslation)(JNIEnv *, jobject, jlong node_pointer,
jfloat x_translation, jfloat y_translation,
jfloat z_translation) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_translation(Vector3(x_translation, y_translation, z_translation));
}
JNIEXPORT void JNICALL
JNI_METHOD(updateGastNodeLocalScale)(JNIEnv *, jobject, jlong node_pointer, jfloat x_scale,
jfloat y_scale, jfloat z_scale) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_scale(Vector3(x_scale, y_scale, z_scale));
}
JNIEXPORT void JNICALL
JNI_METHOD(updateGastNodeLocalRotation)(JNIEnv *, jobject, jlong node_pointer,
jfloat x_rotation, jfloat y_rotation, jfloat z_rotation) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_rotation_degrees(Vector3(x_rotation, y_rotation, z_rotation));
}
JNIEXPORT void JNICALL
JNI_METHOD(nativeSetProjectionMeshType)(JNIEnv *, jobject, jlong node_pointer,
jint projection_mesh_type) {
GastNode *gast_node = from_pointer(node_pointer);
ERR_FAIL_NULL(gast_node);
gast_node->set_projection_mesh_type(projection_mesh_type);
}
}
|
#include<bits/stdc++.h>
using namespace std;
const int siz=10005;
const int INF=0x3f3f3f3f;
struct node{
int to,val;
};
vector<node> G[siz];
int n,d[siz],vis[siz];
void dij(int s){
int i,k,u,v;
memset(d,INF,sizeof(d));
memset(vis,0,sizeof(vis));
d[s]=0;
while(1){
k=-1;
for(i=1;i<=n;i++){
if(vis[i]==0&&(k==-1||d[i]<d[k]))
k=i;
}
if(k==-1)
break;
vis[k]=1;
for(i=0;i<G[k].size();i++){
u=G[k][i].to;
v=G[k][i].val;
d[u]=min(d[u],d[k]+v);
}
}
}
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack <TreeNode*> nodes;
TreeNode* prev = NULL;
while(root!=NULL || !nodes.empty()) {
while(root != NULL) {
nodes.push(root);
root = root->left;
}
root = nodes.top();
nodes.pop();
if(prev != NULL && prev->val >= root->val) return false;
prev = root;
root = root->right;
}
return true;
}
};
|
#include<iostream>
#include<climits>
//Cumulative Sum Approach
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int currsum[n+1];
currsum[0] = 0;
for(int i=1;i<=n;i++){
currsum[i] = currsum[i-1] + a[i-1];
}
int maxSum = INT_MIN;
for(int i=1;i<=n;i++){
int sum =0;
for(int j = 0;j<i;j++){
sum = currsum[i] - currsum[j];
maxSum= max(maxSum, sum);
}
}
cout<<maxSum<<endl;
return 0;
}
|
// Question 31 => Smallest subarray with sum greater than a given value
#include<iostream>
#include<climits>
using namespace std;
int main(){
int arr[] = {1,4,45,6,0,19};
int n = sizeof(arr) / sizeof(arr[0]);
int x;
cout<<"Please enter any number (Value of x): ";
cin>>x;
int minValue = INT_MAX;
for(int i=0; i<n; i++){
int sum = 0;
for(int j=i; j<n; j++){
sum += arr[j];
if(sum > x){
minValue = min(minValue, j-i+1);
}
}
}
cout<<minValue<<endl;
}
|
// Created by Oleksiy Grechnyev 2017
#pragma once
#include <string>
// ctor = Constructor, dtor = Destructor
// A Demo Class with ctor, dtor, copy/move ctor, copy/move assignment
// with a single std::string field name
// Note: after moving a std::string the original object has empty string,
// Which is show by the dtor
//
// Note: if you don't include any dtor or copy/move stuff, the
// Default copy/move ctors and assignments will be similar to mine
class Tjej{
public:
Tjej() noexcept{
std::cout << "Default ctor " << name << std::endl;
}
// No explicit here. But usually we make it explicit.
Tjej(const std::string & s) noexcept : name(s){
std::cout << "Ctor " << name << std::endl;
}
Tjej(const Tjej & rhs) noexcept : name(rhs.name) {
std::cout << "Copy Ctor " << name << std::endl;
}
// Uses rvalue ref (Tjej &&) and std::move
// Note : without noexcept vector would prefer copy Ctor !
Tjej(Tjej && rhs) noexcept : name(std::move(rhs.name)){
std::cout << "Move Ctor " << name << std::endl;
}
~Tjej(){
std::cout << "Dtor " << name << std::endl;
}
Tjej & operator= (const Tjej & rhs) noexcept {
// Check for self-assignment
if (this != &rhs)
name = rhs.name;
std::cout << "Copy Assignment " << name << std::endl;
return *this;
}
Tjej & operator= (Tjej && rhs) noexcept {
// Check for self-assignment
if (this != &rhs)
name = std::move(rhs.name);
std::cout << "Move Assignment " << name << std::endl;
return *this;
}
/// Getter
const std::string &getName() const noexcept {
return name;
}
/// Setter
void setName(const std::string &name) noexcept {
Tjej::name = name;
}
private:
/// Field wiith a default value
std::string name = "Lilith";
};
|
#ifndef MESH_H
#define MESH_H
#include <GL/glew.h>
class Mesh
{
public:
Mesh();
~Mesh();
void CreateMesh(GLfloat *vertices, unsigned int *indices, unsigned int numOfVertices, unsigned int numOfIndices);
void RenderMesh();
void ClearMesh();
void CreateMeshNew(GLfloat *vertices, unsigned int numOfVertices,
GLfloat *textures, unsigned int numTexCoord,
unsigned int *indices, unsigned int numOfIndices);
private:
GLuint VAO, VBO, IBO;
GLsizei indexCount;
GLuint vbo_cube_vertices, vbo_cube_texcoords;
};
#endif // MESH_H
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2009-2010.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#ifndef _FWDATATOOLS_OBJECT_GENERATOR_HPP_
#define _FWDATATOOLS_OBJECT_GENERATOR_HPP_
#include <fwCore/base.hpp>
#include <fwData/Array.hpp>
#include <fwData/Color.hpp>
#include <fwData/Composite.hpp>
#include <fwData/Dictionary.hpp>
#include <fwData/DictionaryOrgan.hpp>
#include <fwData/Material.hpp>
#include <fwData/Node.hpp>
#include <fwData/PatientDB.hpp>
#include <fwData/Plane.hpp>
#include <fwData/Point.hpp>
#include <fwData/Port.hpp>
#include <fwData/ProcessObject.hpp>
#include <fwData/ReconstructionTraits.hpp>
#include <fwData/Resection.hpp>
#include <fwData/ResectionDB.hpp>
#include <fwData/ROITraits.hpp>
#include <fwData/StructureTraits.hpp>
#include <fwData/StructureTraitsDictionary.hpp>
#include <fwData/TransferFunction.hpp>
#include "fwDataTools/export.hpp"
namespace fwDataTools
{
class ObjectGenerator
{
public:
FWDATATOOLS_API static ::fwData::PatientDB::sptr createPatientDB(const unsigned char nbPatient,
const unsigned char nbStudy,
const unsigned char nbAcquisition,
const unsigned char nbReconstruction);
FWDATATOOLS_API static ::fwData::Array::sptr randomizeArray(const std::string type, fwData::Array::SizeType sizes);
FWDATATOOLS_API static ::fwData::Color::sptr randomizeColor();
FWDATATOOLS_API static ::fwData::TransferFunction::sptr createTFColor(unsigned char nbPoints, double window, double level );
FWDATATOOLS_API static ::fwData::TransferFunction::sptr createTFColor();
FWDATATOOLS_API static ::fwData::StructureTraitsDictionary::sptr createStructureTraitsDictionary();
FWDATATOOLS_API static ::fwData::StructureTraits::sptr createStructureTraits();
/// Return a composite containing the ROITraits and a reference on its StructureTraits and mask node (because of weak ptr)
FWDATATOOLS_API static ::fwData::Composite::sptr createROITraits();
/// Return a composite containing the ReconstructionTraits and a reference on its StructureTraits and mask/mesh node (because of weak ptr)
FWDATATOOLS_API static ::fwData::Composite::sptr createReconstructionTraits();
FWDATATOOLS_API static ::fwData::Node::sptr createNode();
FWDATATOOLS_API static ::fwData::Port::sptr createPort();
FWDATATOOLS_API static ::fwData::Material::sptr createMaterial( );
FWDATATOOLS_API static ::fwData::ProcessObject::sptr createProcessObject();
FWDATATOOLS_API static ::fwData::ResectionDB::sptr generateResectionDB();
FWDATATOOLS_API static ::fwData::Resection::sptr generateResection();
FWDATATOOLS_API static ::fwData::Point::sptr generatePoint();
FWDATATOOLS_API static ::fwData::Plane::sptr generatePlane();
FWDATATOOLS_API static ::fwData::Dictionary::sptr createDictionary();
FWDATATOOLS_API static ::fwData::DictionaryOrgan::sptr createDictionaryOrgan();
};
} // namespace fwDataTools
#endif // _FWDATATOOLS_OBJECT_GENERATOR_HPP_
|
//В приют привозят собак разных пород.
//В словаре shelter по названию хранится количество особей каждого вида на текущий момент.
//Приют может принять определённое количество собак каждой породы. Оно указано в словаре max_amount.
//Напишите функцию, которая будет на основании вектора с именами поступивших собак обновлять словарь shelter и
//возвращать общее количество попавших в приют собак.
//Гарантируется, что никакие другие собаки, кроме известных из словаря max_amount, в приют не приедут.
//
//Пример входных данных для функции
//map<string, int>& shelter = { {"landseer"s, 1}, {"otterhound"s, 2}, {"pekingese"s, 2}, {"pointer"s, 3} };
//const map<string, int>& max_amount = { {"landseer"s, 2}, {"otterhound"s, 3}, {"pekingese"s, 4}, {"pointer"s, 7} };
//const vector<string>& new_dogs = { "landseer"s, "otterhound"s, "otterhound"s, "otterhound"s, "pointer"s };
//
//Пример вывода функции
//3
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
int CountAndAddNewDogs(const vector<string>& new_dogs,
const map<string, int>& max_amount, map<string, int>& shelter) {
//обычным способом
/*int count = 0;
for (auto& dog : new_dogs) {
int max_dogs = max_amount.find(dog)->second;
int now_dogs = shelter.find(dog)->second;
if (now_dogs < max_dogs) {
shelter[dog] = now_dogs + 1;
count++;
}
}*/
//через лямбду
int count = count_if(new_dogs.begin(), new_dogs.end(),
[&shelter, &max_amount](const string& dog) {
//return shelter[dog] < max_amount.at(dog) ? shelter[dog] += 1 : 0;
//или лучше так
int& current_amount = shelter[dog];
if (current_amount < max_amount.at(dog)) {
return ++current_amount;
}
else return 0;
});
return count;
}
int main() {
map<string, int> shelter = { {"landseer"s, 1}, {"otterhound"s, 2}, {"pekingese"s, 2}, {"pointer"s, 3} };
const map<string, int>& max_amount = { {"landseer"s, 2}, {"otterhound"s, 3}, {"pekingese"s, 4}, {"pointer"s, 7} };
const vector<string>& new_dogs = { "landseer"s, "otterhound"s, "otterhound"s, "otterhound"s, "pointer"s };
int taken_dogs = CountAndAddNewDogs(new_dogs, max_amount, shelter);
cout << taken_dogs << endl;
return 0;
}
|
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int main() {
int alph[26], n, ans = 0, class1, class2;
string s;
memset(alph, 0, 26 * sizeof(int));
cin >> n;
while(n--) {
cin >> s;
alph[s[0] - 97]++;
}
for(int i = 0; i < 26; i++) {
class1 = ceil(alph[i] / 2.0);
class2 = alph[i] / 2;
ans += (class1 * (class1 - 1)) / 2 + (class2 * (class2 - 1) ) / 2;
}
cout << ans << endl;
}
|
#pragma once
#include "CoreMinimal.h"
#include "Enum/SubQuestType.h"
#include "QuestSubInfo.generated.h"
USTRUCT(BlueprintType)
struct ARPG_API FQuestSubInfo
{
GENERATED_USTRUCT_BODY()
public:
// 퀘스트 서브 타입 : Npc 대화 / 몬스터 사냥 / 아이템 획득
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
ESubQuestType SubQuestType;
// 퀘스트 서브 타이틀
/// - 이 문자열은 퀘스트 제목 하단에 표시됩니다.
/// - ex) ~~~ 모으기 (0 / 3)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
FText QuestSubTitleText;
// 목표 코드
/// - Npc 코드, 아이템 코드, 몬스터 코드 ...
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
FName TargetCode;
// 목표 수치 / 금액 / 마리 수
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기본")
int32 TargetValue;
// 퀘스트 완료 시 수집한 아이템 / 은화를 회수할 것인지를 나타냅니다.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기타")
bool bRetrievalCollection;
// 현재 수치
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기타")
int32 CurrentValue;
// 완료 상태를 나타냅니다.
bool bIsComplete;
public :
FQuestSubInfo();
};
|
// Created on: 1996-03-26
// Created by: Christian CAILLET
// Copyright (c) 1996-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 _XSControl_SelectForTransfer_HeaderFile
#define _XSControl_SelectForTransfer_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <IFSelect_SelectExtract.hxx>
#include <Standard_Integer.hxx>
class XSControl_TransferReader;
class Transfer_ActorOfTransientProcess;
class Standard_Transient;
class Interface_InterfaceModel;
class TCollection_AsciiString;
class XSControl_SelectForTransfer;
DEFINE_STANDARD_HANDLE(XSControl_SelectForTransfer, IFSelect_SelectExtract)
//! This selection selects the entities which are recognised for
//! transfer by an Actor for Read : current one or another one.
//!
//! An Actor is an operator which runs transfers from interface
//! entities to objects for Imagine. It has a method to recognize
//! the entities it can process (by default, it recognises all,
//! this method can be redefined).
//!
//! A TransferReader brings an Actor, according to the currently
//! selected norm and transfer conditions.
//!
//! This selection considers, either the current Actor (brought by
//! the TransferReader, updated as required), or a precise one.
class XSControl_SelectForTransfer : public IFSelect_SelectExtract
{
public:
//! Creates a SelectForTransfer, non initialised
//! it sorts nothing, unless an Actor has been defined
Standard_EXPORT XSControl_SelectForTransfer();
//! Creates a SelectForTransfer, which will work with the
//! currently defined Actor brought by the TransferReader
Standard_EXPORT XSControl_SelectForTransfer(const Handle(XSControl_TransferReader)& TR);
//! Sets a TransferReader to sort entities : it brings the Actor,
//! which may change, while the TransferReader does not
Standard_EXPORT void SetReader (const Handle(XSControl_TransferReader)& TR);
//! Sets a precise actor to sort entities
//! This definition oversedes the creation with a TransferReader
Standard_EXPORT void SetActor (const Handle(Transfer_ActorOfTransientProcess)& act);
//! Returns the Actor used as precised one.
//! Returns a Null Handle for a creation from a TransferReader
//! without any further setting
Standard_EXPORT Handle(Transfer_ActorOfTransientProcess) Actor() const;
//! Returns the Reader (if created with a Reader)
//! Returns a Null Handle if not created with a Reader
Standard_EXPORT Handle(XSControl_TransferReader) Reader() const;
//! Returns True for an Entity which is recognized by the Actor,
//! either the precised one, or the one defined by TransferReader
Standard_EXPORT Standard_Boolean Sort (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
//! Returns a text defining the criterium : "Recognized for Transfer [(current actor)]"
Standard_EXPORT TCollection_AsciiString ExtractLabel() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(XSControl_SelectForTransfer,IFSelect_SelectExtract)
protected:
private:
Handle(XSControl_TransferReader) theTR;
Handle(Transfer_ActorOfTransientProcess) theAC;
};
#endif // _XSControl_SelectForTransfer_HeaderFile
|
#ifndef STATISTICA_H
#define STATISTICA_H
#include<iostream>
class Statistica
{
private:
Statistica(){}
Statistica(Statistica const&);
void operator=(Statistica const&);
static Statistica* instance;
public:
~Statistica(){}
int get_nr_pisici();
int get_nr_caini();
int get_nr_iepuri();
int get_nr_testoase();
int get_nr_papagali();
int get_nr_iguane();
int get_nr_corbi();
int get_nr_caracatite();
int get_nr_foci();
int get_nr_pesti();
int get_nr_porumbei();
int get_nr_serpi();
void Calcul();
static Statistica* Get_Instance()
{
if(instance == NULL)
instance = new Statistica;
return instance;
}
};
#endif // STATISTICA_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.