text
stringlengths 8
6.88M
|
|---|
/* -*- 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 SUPPORT_DATA_SYNC
#include "modules/util/str.h"
#include "modules/util/opstring.h"
#include "modules/util/OpHashTable.h"
#include "modules/sync/sync_parser.h"
#include "modules/sync/sync_dataitem.h"
#include "modules/sync/sync_factory.h"
#include "modules/sync/sync_parser_myopera.h"
#include "modules/sync/sync_coordinator.h"
#include "modules/sync/sync_util.h"
#include "modules/xmlutils/xmltokenhandler.h"
#include "modules/xmlutils/xmltoken.h"
#include "modules/xmlutils/xmlparser.h"
#include "modules/util/opfile/opfile.h"
#include "modules/stdlib/util/opdate.h"
#include "modules/pi/OpLocale.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/prefs/prefsmanager/collections/pc_sync.h"
#include "modules/xmlutils/xmlnames.h"
#include "modules/xmlutils/xmlfragment.h"
#include "modules/util/adt/bytebuffer.h"
# define MYOPERAITEMTABLE_START() \
void init_MyOperaItemTable() { \
int i = 0; \
MyOperaItemTable* tmp_entry = g_opera->sync_module.m_myopera_item_table;
# define MYOPERAITEMTABLE_ENTRY(id, item_type, item_name, item_obfuscated_name, item_primary_key, preserve_whitespace) \
tmp_entry[i].key = id; \
tmp_entry[i].type = item_type; \
tmp_entry[i].name = item_name; \
tmp_entry[i].obfuscated_name = item_obfuscated_name; \
tmp_entry[i].primary_key = item_primary_key; \
tmp_entry[i++].keep_whitespace = preserve_whitespace;
# define MYOPERAITEMTABLE_END() \
OP_ASSERT(i <= OpSyncItem::SYNC_KEY_NONE+1); \
};
MYOPERAITEMTABLE_START()
// all elements use the id:
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_ID, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("id"), UNI_L("uuid"), TRUE, FALSE)
// <bookmark>
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_CREATED, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("created"), UNI_L("cre"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_DESCRIPTION, OpSyncDataItem::DATAITEM_CHILD, UNI_L("description"), UNI_L("desc"), FALSE, TRUE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_ICON, OpSyncDataItem::DATAITEM_CHILD, UNI_L("icon"), UNI_L("image"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_NICKNAME, OpSyncDataItem::DATAITEM_CHILD, UNI_L("nickname"), UNI_L("shortname"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_PANEL_POS, OpSyncDataItem::DATAITEM_CHILD, UNI_L("panel_pos"), UNI_L("ppos"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_PARENT, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("parent"), UNI_L("par"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_PERSONAL_BAR_POS, OpSyncDataItem::DATAITEM_CHILD, UNI_L("personal_bar_pos"), UNI_L("pbpos"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_PREV, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("previous"), UNI_L("prev"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_SHOW_IN_PANEL, OpSyncDataItem::DATAITEM_CHILD, UNI_L("show_in_panel"), UNI_L("show_ip"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_SHOW_IN_PERSONAL_BAR, OpSyncDataItem::DATAITEM_CHILD, UNI_L("show_in_personal_bar"), UNI_L("show_ipb"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_TITLE, OpSyncDataItem::DATAITEM_CHILD, UNI_L("title"), UNI_L("name"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_URI, OpSyncDataItem::DATAITEM_CHILD, UNI_L("uri"), UNI_L("link"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_VISITED, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("visited"), UNI_L("vis"), FALSE, FALSE)
// </bookmark>
// <bookmark_folder>
// uses "description", "nickname", "panel_pos" "parent", "personal_bar_pos",
// "previous", "show_in_panel", "show_in_personal_bar", "title"
// as defined for bookmark
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_TYPE, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("type"), UNI_L("type"), FALSE, FALSE)
// </bookmark_folder>
// <bookmark_folder>
// server created bookmark_folder to support new devices may have
// additional attributes:
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_DELETABLE, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("deletable"), UNI_L("del"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_MAX_ITEMS, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("max_items"), UNI_L("max"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_MOVE_IS_COPY, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("move_is_copy"), UNI_L("mic"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_SEPARATORS_ALLOWED, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("separators_allowed"), UNI_L("sa"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_SUB_FOLDERS_ALLOWED, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("sub_folders_allowed"), UNI_L("sfa"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_TARGET, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("target"), UNI_L("target"), FALSE, FALSE)
// </bookmark_folder>
// <extension>
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_AUTHOR, OpSyncDataItem::DATAITEM_CHILD, UNI_L("author"), UNI_L("author"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_EXTENSION_UPDATE_URI, OpSyncDataItem::DATAITEM_CHILD, UNI_L("extension_update_uri"), UNI_L("ext_upd_uri"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_VERSION, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("version"), UNI_L("ver"), FALSE, FALSE)
// </extension>
// <feed>
// uses "icon", "title", "uri"
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_LAST_READ, OpSyncDataItem::DATAITEM_CHILD, UNI_L("last_read"), UNI_L("lastread"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_UPDATE_INTERVAL, OpSyncDataItem::DATAITEM_CHILD, UNI_L("update_interval"), UNI_L("updint"), FALSE, FALSE)
// </feed>
// <note>
// uses "created", "parent", "previous", "uri"
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_CONTENT, OpSyncDataItem::DATAITEM_CHILD, UNI_L("content"), UNI_L("text"), FALSE, TRUE)
// </note>
// <note_folder>
// uses "created", "parent", "previous", "title", "type"
// </note_folder>
// <pm_form_auth>
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_FORM_DATA, OpSyncDataItem::DATAITEM_CHILD, UNI_L("form_data"), UNI_L("fdat"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_FORM_URL, OpSyncDataItem::DATAITEM_CHILD, UNI_L("form_url"), UNI_L("furl"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_MODIFIED, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("modified"), UNI_L("mdf"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_PAGE_URL, OpSyncDataItem::DATAITEM_CHILD, UNI_L("page_url"), UNI_L("purl"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_PASSWORD, OpSyncDataItem::DATAITEM_CHILD, UNI_L("password"), UNI_L("pwd"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_PM_FORM_AUTH_SCOPE, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("scope"), UNI_L("scp"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_TOPDOC_URL, OpSyncDataItem::DATAITEM_CHILD, UNI_L("topdoc_url"), UNI_L("turl"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_USERNAME, OpSyncDataItem::DATAITEM_CHILD, UNI_L("username"), UNI_L("usr"), FALSE, FALSE)
// </pm_form_auth>
// <pm_http_auth>
// uses "modified", "page_url", "password", "username"
// </pm_http_auth>
// <search_engine>
// uses "icon", "title", "type", "uri"
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_ENCODING, OpSyncDataItem::DATAITEM_CHILD, UNI_L("encoding"), UNI_L("enc"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_GROUP, OpSyncDataItem::DATAITEM_CHILD, UNI_L("group"), UNI_L("grp"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_HIDDEN, OpSyncDataItem::DATAITEM_CHILD, UNI_L("hidden"), UNI_L("hdn"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_IS_POST, OpSyncDataItem::DATAITEM_CHILD, UNI_L("is_post"), UNI_L("ispost"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_KEY, OpSyncDataItem::DATAITEM_CHILD, UNI_L("key"), UNI_L("key"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_POST_QUERY, OpSyncDataItem::DATAITEM_CHILD, UNI_L("post_query"), UNI_L("post"), FALSE, FALSE)
// </search_engine>
// <speeddial>
// uses "icon", "title", "uri"
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_CUSTOM_TITLE, OpSyncDataItem::DATAITEM_CHILD, UNI_L("custom_title"), UNI_L("cst_ttl"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_EXTENSION_ID, OpSyncDataItem::DATAITEM_CHILD, UNI_L("extension_id"), UNI_L("ext_id"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_PARTNER_ID, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("partner_id"), UNI_L("prtnrid"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_POSITION, OpSyncDataItem::DATAITEM_ATTRIBUTE, UNI_L("position"), UNI_L("pos"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_RELOAD_ENABLED, OpSyncDataItem::DATAITEM_CHILD, UNI_L("reload_enabled"), UNI_L("rle"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_RELOAD_INTERVAL, OpSyncDataItem::DATAITEM_CHILD, UNI_L("reload_interval"), UNI_L("rli"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_RELOAD_ONLY_IF_EXPIRED, OpSyncDataItem::DATAITEM_CHILD, UNI_L("reload_only_if_expired"), UNI_L("rloie"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_RELOAD_POLICY, OpSyncDataItem::DATAITEM_CHILD, UNI_L("reload_policy"), UNI_L("rlp"), FALSE, FALSE)
// </speeddial>
// <typed_history>
// uses "content", "type"
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_LAST_TYPED, OpSyncDataItem::DATAITEM_CHILD, UNI_L("last_typed"), UNI_L("typed"), FALSE, FALSE)
// </typed_history>
// <urlfilter>
// uses "content", "type"
// </urlfilter>
MYOPERAITEMTABLE_ENTRY(OpSyncItem::SYNC_KEY_THUMBNAIL, OpSyncDataItem::DATAITEM_CHILD, UNI_L("thumbnail"), UNI_L("thumb"), FALSE, FALSE)
MYOPERAITEMTABLE_ENTRY((OpSyncItem::Key)0, (OpSyncDataItem::DataItemType)0, NULL, NULL, FALSE, FALSE)
MYOPERAITEMTABLE_END()
// ==================== MyOperaSyncIgnoreXMLParserListener
/**
* This class is used by MyOperaSyncParser as an XMLParser::Listener that
* ignores all notifications. MyOperaSyncParser does not expect the
* notifications to be called or it does not need to do anything.
*/
class MyOperaSyncIgnoreXMLParserListener : public XMLParser::Listener
{
public:
MyOperaSyncIgnoreXMLParserListener() {}
virtual ~MyOperaSyncIgnoreXMLParserListener() {}
/**
* @name Implementation of XMLParser::Listener
* @{
*/
/**
* This method is only called when external entities are loaded, when
* parsing of an external entity has finished and parsing of the document
* entity should continue. The Opera Link protocol does not use external
* entities, so there is no need implement this method.
*/
virtual void Continue(XMLParser* parser) { OP_ASSERT(!"Unexpected call"); }
/**
* This method is called when parsing has stopped. This implementation has
* nothing to do.
* @todo Check if we should test the reason why it has stopped (see
* XMLParser::IsFinished(), XMLParser::IsFailed(),
* XMLParser::IsOutOfMemory()).
*/
virtual void Stopped(XMLParser* parser) {
OP_NEW_DBG("MyOperaSyncIgnoreXMLParserListener::Stopped()", "sync.xml");
OP_DBG(("finished: %s with %s%s", parser->IsFinished()?"yes":"no", parser->IsFailed()?"error":"success", parser->IsOutOfMemory()?"; OOM":""));
}
/** @} */ // Implementation of XMLParser::Listener
};
// ==================== MyOperaSyncXMLTokenHandler
/**
* The class MyOperaSyncXMLTokenHandler is used as the XMLTokenHandler for the
* XMLParser instance that parses the xml response from the Link server.
*/
class MyOperaSyncXMLTokenHandler : public XMLTokenHandler
{
public:
MyOperaSyncXMLTokenHandler(OpSyncParser* parser)
: m_parser(parser)
, m_current_element(OpSyncParser::OtherElement)
, m_current_sync_item(NULL)
, m_error_code(SYNC_OK)
, m_parsed_sync_state(false)
, m_parsed_server_info(false)
, m_dirty_sync_requested(false)
, m_server_version(SYNC_LINK_SERVER_VERSION_1_0)
{}
virtual ~MyOperaSyncXMLTokenHandler() { Reset(); }
/**
* Returns true if we received an error status from the Link server in the
* xml document.
* @see GetErrorMessage()
*/
bool HasError() const {
return m_error_message.HasContent() || (m_error_code != SYNC_OK);
}
/**
* Returns the error-message that was received from the Link server in the
* xml document.
*/
const OpStringC& GetErrorMessage() const { return m_error_message; }
OpString& TakeErrorMessage() { return m_error_message; }
/**
* Returns the error-code that was received from the Link server in the
* xml document.
*/
OpSyncError GetErrorCode() const { return m_error_code; }
/**
* Returns the OpSyncDataCollection of incoming OpSyncDataItem instances.
* The returned collection can be added to a caller's collection using
* OpSyncDataCollection::AppendItems() and thus the items are removed from
* this instance.
*/
OpSyncDataCollection* TakeIncomingItems() { return &m_incoming_sync_items; }
/**
* Returns true if the xml document that was received from the Link server
* contained a sync-state that was successfully parsed. The sync-state is
* available via GetSyncState().
*/
bool HasParsedNewSyncState() const { return m_parsed_sync_state; }
/**
* Returns the sync-state that was received from the Link server in the xml
* document.
* @see HasParsedNewSyncState()
*/
const OpString& GetSyncState() const { return m_sync_state; }
/**
* Returns true if the Link server requests to start a dirty sync.
*/
bool IsDirtySyncRequested() const { return m_dirty_sync_requested; }
/**
* Returns true if the xml document that was received from the Link server
* contained a 'server_info' element that was successfully parsed. The
* server information is available via GetServerInformation().
*/
bool HasParsedServerInformation() const { return m_parsed_server_info; }
/**
* Returns the OpSyncServerInformation that was received from the Link
* server in the xml document.
*/
const OpSyncServerInformation& GetServerInformation() const { return m_server_info; }
/**
* Resets the variables of the token handler to be able to start parsing a
* new xml document. The error message is cleared, the error code is set to
* SYNC_OK (so HasError() returns false), the OpSyncDataCollection of
* incoming items is cleared.
*/
void Reset() {
m_error_message.Empty();
m_error_code = SYNC_OK;
m_incoming_sync_items.Clear();
m_current_element = OpSyncParser::OtherElement;
m_content_string.Empty();
if (m_current_sync_item)
{
m_current_sync_item->DecRefCount();
m_current_sync_item = NULL;
}
m_dirty_sync_requested = false;
m_parsed_sync_state = false;
m_parsed_server_info = false;
m_sync_state.Empty();
m_server_info.Clear();
}
/**
* @name Implementation of XMLTokenHandler
* @{
*/
/**
* Depending on the type of the specified token (XMLToken::GetType()), this
* method calls HandleTextToken() (in case of XMLToken::TYPE_Text or
* XMLToken::TYPE_CDATA), HandleStartTagToken() (in case of
* XMLToken::TYPE_STag or XMLToken::TYPE_EmptyElemTag) or
* HandleEndTagToken() (in case of XMLToken::TYPE_ETag or
* XMLToken::TYPE_EmptyElemTag).
*/
virtual Result HandleToken(XMLToken& token) {
OP_NEW_DBG("MyOperaSyncXMLTokenHandler::HandleToken", "sync.xml");
OP_STATUS status = OpStatus::OK;
switch (token.GetType())
{
case XMLToken::TYPE_CDATA:
case XMLToken::TYPE_Text: status = HandleTextToken(token); break;
case XMLToken::TYPE_STag: status = HandleStartTagToken(token); break;
case XMLToken::TYPE_ETag: status = HandleEndTagToken(token); break;
case XMLToken::TYPE_EmptyElemTag:
status = HandleStartTagToken(token);
if (OpStatus::IsSuccess(status))
status = HandleEndTagToken(token);
break;
}
if (OpStatus::IsMemoryError(status))
return XMLTokenHandler::RESULT_OOM;
else if (OpStatus::IsError(status))
return XMLTokenHandler::RESULT_ERROR;
return XMLTokenHandler::RESULT_OK;
}
/** @} */ // Implementation of XMLTokenHandler
private:
/**
* Is called by HandleToken() when the m_xml_parser has found some text.
* This method adds the text to the m_content_string. The m_content_string
* is later used on handling the end-token (see HandleEndTagToken()).
*/
OP_STATUS HandleTextToken(XMLToken& token) {
uni_char* local_copy = NULL;
const uni_char* text_data = token.GetLiteralSimpleValue();
if (!text_data)
{
local_copy = token.GetLiteralAllocatedValue();
text_data = local_copy;
}
OP_STATUS s = m_content_string.Append(text_data, token.GetLiteralLength());
OP_DELETEA(local_copy);
return s;
}
/**
* Is called by HandleToken() when the m_xml_parser has found a start
* token. The m_current_element is set to the type that corresponds to the
* start-token:
* - "link" (this is the document element) => LinkStartElement
* - "server_info" (child of link) => ServerInfoElement
* - "data" (child of link) => DataElement
* All valid children of the "data" element are mapped by the table
* specified in SyncModule::m_accepted_format. If the current token starts a
* valid child of the "data" element, a new OpSyncDataItem instance is
* created and stored in m_current_sync_item (see GetSyncDataItem()), the
* attributes of the xml element are added as
* OpSyncDataItem::AddAttribute() and m_current_element is set to the
* ElementType of that valid child.
*
* The valid children may have further children. If a new child is started
* while the m_current_element is a valid child of the "data" element, we
* start to collect the content string in m_content_string (see also
* HandleEndToken).
*/
OP_STATUS HandleStartTagToken(XMLToken &token);
/**
* Is called by HandleToken() when the m_xml_parser has found an end token.
*
* If the m_current_element is a valid child of the "data" element, then we
* have two cases:
* - the token ends the m_current_element: in this case the
* m_current_sync_item is added to the OpSyncDataCollection
* m_incoming_sync_items and m_current_element is set to DataElement (to
* expect a new valid child, or the end of the "data" element).
* - the token ends a child of the valid child: in this case the child is
* added to m_current_element by calling OpSyncDataItem::AddChild() where
* the name of the element is the key and the content of the element (that
* was collected in m_content_string) is the data of the child.
*
* If the m_current_element is the ServerInfoElement, we handle the children
* - "error" (by setting m_error_message to the child's value),
* - "long_interval" (passing the value to m_server_info,
* OpSyncServerInformation::SetSyncIntervalLong()),
* - "short_interval" (passing the value to m_server_info,
* OpSyncServerInformation::SetSyncIntervalShort())
* - "maxitems" (passing the value to m_server_info,
* OpSyncServerInformation::SetSyncMaxItems()).
*/
OP_STATUS HandleEndTagToken(XMLToken &token);
static OpSyncError ErrorCodeToSyncError(const OpStringC& error_code) {
int code = uni_atoi(error_code.CStr());
switch (code)
{
case 101: return SYNC_ACCOUNT_AUTH_FAILURE;
case 102: return SYNC_ACCOUNT_USER_BANNED;
case 103: return SYNC_ACCOUNT_OAUTH_EXPIRED;
case 201: return SYNC_ERROR_INVALID_REQUEST;
case 202:
case 203: return SYNC_ERROR_PARSER;
case 204: return SYNC_ERROR_PROTOCOL_VERSION;
case 205: return SYNC_ERROR_CLIENT_VERSION;
case 305: return SYNC_ERROR_INVALID_STATUS;
case 310: return SYNC_ERROR_INVALID_BOOKMARK;
case 320: return SYNC_ERROR_INVALID_SPEEDDIAL;
case 330: return SYNC_ERROR_INVALID_NOTE;
case 340: return SYNC_ERROR_INVALID_SEARCH;
case 350: return SYNC_ERROR_INVALID_TYPED_HISTORY;
case 360: return SYNC_ERROR_INVALID_FEED;
case 401:
case 402: return SYNC_ACCOUNT_USER_UNAVAILABLE;
case 500: return SYNC_ERROR_SERVER;
default: return SYNC_ERROR;
}
}
OpSyncParser* m_parser;
OpSyncParser::ElementType m_current_element;
OpString m_content_string;
OpSyncDataItem* m_current_sync_item;
OpSyncDataCollection m_incoming_sync_items;
OpString m_error_message;
OpSyncError m_error_code;
bool m_parsed_sync_state;
bool m_parsed_server_info;
bool m_dirty_sync_requested;
OpString m_sync_state;
OpSyncServerInformation m_server_info;
enum OpSyncServerVersion {
SYNC_LINK_SERVER_VERSION_1_0,
SYNC_LINK_SERVER_VERSION_1_1,
SYNC_LINK_SERVER_VERSION_1_2
} m_server_version;
bool IsServerVersion1_1() const { return m_server_version >= SYNC_LINK_SERVER_VERSION_1_1; }
};
OP_STATUS MyOperaSyncXMLTokenHandler::HandleStartTagToken(XMLToken &token)
{
OP_NEW_DBG("MyOperaSyncXMLTokenHandler::HandleStartTagToken", "sync.xml");
OP_DBG(("current element: %s", OpSyncParser::ElementType2String(m_current_element)));
m_content_string.Empty();
// Fetch information about the element.
const XMLCompleteNameN& elemname = token.GetName();
if (uni_strncmp(UNI_L("link"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
m_current_element = OpSyncParser::LinkStartElement;
OP_DBG(("found element: %s", OpSyncParser::ElementType2String(m_current_element)));
// lets get the attributes for this element
XMLToken::Attribute* attributes = token.GetAttributes();
// unless specified we assume server version 1.0:
m_server_version = SYNC_LINK_SERVER_VERSION_1_0;
OpString key, value;
for (unsigned int index = 0; index < token.GetAttributesCount(); index++)
{
// add all attributes without validating, validation will happen later
RETURN_IF_ERROR(key.Set(attributes[index].GetName().GetLocalPart(), attributes[index].GetName().GetLocalPartLength()));
RETURN_IF_ERROR(value.Set(attributes[index].GetValue(), attributes[index].GetValueLength()));
if ((key == "syncstate") && value.HasContent())
{
RETURN_IF_ERROR(m_sync_state.TakeOver(value));
OP_DBG((UNI_L("new syncstate: '%s'"), m_sync_state.CStr()));
m_parsed_sync_state = true;
}
else if ((key == "dirty") && value.HasContent())
{
OP_DBG((UNI_L("dirty: '%s'"), value.CStr()));
m_dirty_sync_requested = (value == "true") || (value == "1");
}
else if (key == "version" && value.HasContent())
{
OP_DBG((UNI_L("version: '%s'"), value.CStr()));
if (value == UNI_L("1.0"))
m_server_version = SYNC_LINK_SERVER_VERSION_1_0;
else if (value == UNI_L("1.1"))
m_server_version = SYNC_LINK_SERVER_VERSION_1_1;
else if (value == UNI_L("1.2"))
m_server_version = SYNC_LINK_SERVER_VERSION_1_2;
}
}
}
else if (IsServerVersion1_1() && uni_strncmp(UNI_L("server_info"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0 ||
uni_strncmp(UNI_L("serverinfo"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
OP_ASSERT(m_current_element == OpSyncParser::LinkStartElement || !"The 'server_info' element is expected to be a child of the 'link' element");
m_current_element = OpSyncParser::ServerInfoElement;
OP_DBG(("found element: %s", OpSyncParser::ElementType2String(m_current_element)));
}
else if (uni_strncmp(UNI_L("data"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
OP_ASSERT(m_current_element == OpSyncParser::LinkStartElement || !"The 'data' element is expected to be a child of the 'link' element");
m_current_element = OpSyncParser::DataElement;
OP_DBG(("found element: %s", OpSyncParser::ElementType2String(m_current_element)));
}
else if (uni_strncmp(UNI_L("error"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
OP_ASSERT(m_current_element == OpSyncParser::ServerInfoElement);
// lets get the attributes for this element
XMLToken::Attribute* attributes = token.GetAttributes();
for (unsigned int index = 0; index < token.GetAttributesCount(); index++)
{
OpString key, value;
RETURN_IF_ERROR(key.Set(attributes[index].GetName().GetLocalPart(), attributes[index].GetName().GetLocalPartLength()));
RETURN_IF_ERROR(value.Set(attributes[index].GetValue(), attributes[index].GetValueLength()));
if ((key == "code") && value.HasContent())
m_error_code = ErrorCodeToSyncError(value);
// we ignore any other unknown attribute ...
}
OP_DBG((UNI_L("found element error with code: ")) << m_error_code);
}
else if (m_current_element == OpSyncParser::DataElement || IsParentForSubType(m_current_element))
{ /* The children of the data element are stored in the table
* SyncModule::m_accepted_format, see also sync_parser.cpp */
BOOL match_for_subtype;
SYNCACCEPTEDFORMAT* format = FindAcceptedFormat(elemname.GetLocalPart(), elemname.GetLocalPartLength(), match_for_subtype);
if (format)
{
if (match_for_subtype)
m_current_element = format->sub_element_type;
else
m_current_element = format->type;
OP_DBG(("found element: %s", OpSyncParser::ElementType2String(m_current_element)));
if (!format->sub_element_tag || // the element has no children
(m_current_element == format->sub_element_type)) // or the child is the active element
{
OP_ASSERT(m_current_sync_item == NULL);
m_current_sync_item = OP_NEW(OpSyncDataItem, ());
if (!m_current_sync_item)
return OpStatus::ERR_NO_MEMORY;
m_current_sync_item->IncRefCount();
m_current_sync_item->SetType(format->item_type);
const uni_char* primary_key = m_parser->GetPrimaryKeyName(format->item_type);
OpString key, value;
RETURN_IF_ERROR(key.Set(elemname.GetLocalPart(), elemname.GetLocalPartLength()));
OP_DBG((" item-type: ") << format->item_type);
OP_DBG((UNI_L(" element: '%s'; primary key: '%s'"), key.CStr(), primary_key?primary_key:UNI_L("<no key>")));
// lets get the attributes for this element
XMLToken::Attribute* attributes = token.GetAttributes();
for (unsigned int index = 0; index < token.GetAttributesCount(); index++)
{
/* add all attributes without validating, validation will happen
* later: */
RETURN_IF_ERROR(key.Set(attributes[index].GetName().GetLocalPart(), attributes[index].GetName().GetLocalPartLength()));
RETURN_IF_ERROR(value.Set(attributes[index].GetValue(), attributes[index].GetValueLength()));
OP_DBG((UNI_L("attribute %d: '%s'='%s'"), index, key.CStr(), value.CStr()));
if (primary_key && key.HasContent() && key == primary_key)
{
OP_ASSERT(value.HasContent() && "the data is missing for the primary key!");
OP_DBG((UNI_L("primary key: %s=%s"), key.CStr(), value.CStr()));
RETURN_IF_ERROR(m_current_sync_item->m_key.Set(key));
RETURN_IF_ERROR(m_current_sync_item->m_data.Set(value));
}
OpSyncDataItem::DataItemStatus action = OpSyncDataItem::DATAITEM_ACTION_NONE;
if (key == "status")
{
if (value == "added")
{
action = OpSyncDataItem::DATAITEM_ACTION_ADDED;
OP_DBG(("status=added"));
}
else if (value == "modified")
{
action = OpSyncDataItem::DATAITEM_ACTION_MODIFIED;
OP_DBG(("status=modified"));
}
else if (value == "deleted")
{
action = OpSyncDataItem::DATAITEM_ACTION_DELETED;
OP_DBG(("status=deleted"));
}
}
if (action == OpSyncDataItem::DATAITEM_ACTION_NONE)
RETURN_IF_ERROR(m_current_sync_item->AddAttribute(key.CStr(), value.CStr(), NULL));
else
m_current_sync_item->SetStatus(action);
}
}
}
else
{ /* This is an unknown child of the "data" element - ignore that
* child... */
OP_ASSERT(m_current_sync_item == NULL);
#ifdef _DEBUG
OpString element;
OpStatus::Ignore(element.Set(elemname.GetLocalPart(), elemname.GetLocalPartLength()));
OP_DBG((UNI_L("ignoring element '%s'"), element.CStr()));
OP_DBG(("child of '%s'", OpSyncParser::ElementType2String(m_current_element)));
#endif // _DEBUG;
}
}
else if (IsValidElement(m_current_element))
{ /* Now we expect to have a child for a valid element (a valid element is
* one of the children of the "data" element, all valid elements are
* specified in the table SyncModule::m_accepted_format. So we start to
* store the child's value in m_content_string and then add the child to
* the m_current_sync_item in HandleEndTagToken(), where the
* element-name is the child's key and the m_content_string is the
* child's data.
* We also expect that a valid child has no grand-children... */
/* @todo For now we only support to store the content of any child, but
* not the child's attributes. To support attributes for the children
* (e.g. needed for SYNC_SUPPORTS_CONTACT), we need to create an new
* OpSyncDataItem here, get the element's attributes, call
* child_item->AddAttribute() and set the child's data to the
* m_content_string in HandleEndToken(). */
#ifdef _DEBUG
OpString element;
OpStatus::Ignore(element.Set(elemname.GetLocalPart(), elemname.GetLocalPartLength()));
OP_DBG((UNI_L("found element '%s'"), element.CStr()));
OP_DBG(("child of '%s'", OpSyncParser::ElementType2String(m_current_element)));
#endif // _DEBUG;
}
else if (m_current_element == OpSyncParser::ServerInfoElement)
{ /* Now we expect children for the "server_info" element. The children
* are handled in HandleEndToken() */
#ifdef _DEBUG
OpString element;
OpStatus::Ignore(element.Set(elemname.GetLocalPart(), elemname.GetLocalPartLength()));
OP_DBG((UNI_L("found element '%s'"), element.CStr()));
OP_DBG(("child of '%s'", OpSyncParser::ElementType2String(m_current_element)));
#endif // _DEBUG;
}
else
{
#ifdef _DEBUG
OpString element;
OpStatus::Ignore(element.Set(elemname.GetLocalPart(), elemname.GetLocalPartLength()));
OP_DBG((UNI_L("found other element '%s'"), element.CStr()));
OP_DBG(("child of '%s'", OpSyncParser::ElementType2String(m_current_element)));
#endif // _DEBUG;
m_current_element = OpSyncParser::OtherElement;
if (m_current_sync_item)
{
m_current_sync_item->DecRefCount();
m_current_sync_item = NULL;
}
}
return OpStatus::OK;
}
OP_STATUS MyOperaSyncXMLTokenHandler::HandleEndTagToken(XMLToken& token)
{
OP_NEW_DBG("MyOperaSyncXMLTokenHandler::HandleEndTagToken", "sync.xml");
const XMLCompleteNameN& elemname = token.GetName();
if (IsValidElement(m_current_element))
{
BOOL match_for_subtype;
OP_DBG(("current element: %s", OpSyncParser::ElementType2String(m_current_element)));
SYNCACCEPTEDFORMAT* format = FindAcceptedFormat(elemname.GetLocalPart(), elemname.GetLocalPartLength(), match_for_subtype);
if (format)
{
OP_ASSERT((match_for_subtype ? format->sub_element_type == m_current_element : format->type == m_current_element) || !"A child of the data-element (m_current_element) seems to have a child which is named like other children of the data-element. Please re-design the xml specification such that the children of data have unique element names.");
if (m_current_sync_item)
{
switch (format->type) {
case OpSyncParser::EncryptionKeyElement:
case OpSyncParser::EncryptionTypeElement:
{ /* The encryption_key/type element is special, as it has a
* primary key "id" with value "0" (because there can only
* be one encryption-key) and a child with empty key and the
* content as the child's data: */
const uni_char* key = UNI_L("id");
const uni_char* value = UNI_L("0");
RETURN_IF_ERROR(m_current_sync_item->m_key.Set(key));
RETURN_IF_ERROR(m_current_sync_item->m_data.Set(value));
RETURN_IF_ERROR(m_current_sync_item->AddAttribute(key, value));
OP_DBG((UNI_L("Setting data: '%s'"), m_content_string.CStr()));
RETURN_IF_ERROR(m_current_sync_item->AddChild(UNI_L(""), m_content_string.CStr()));
break;
}
}
m_incoming_sync_items.AddItem(m_current_sync_item);
m_current_sync_item->DecRefCount();
m_current_sync_item = NULL;
}
// balance the closing tags
if (match_for_subtype)
m_current_element = format->type;
else
m_current_element = OpSyncParser::DataElement;
}
else
{
OpString key;
RETURN_IF_ERROR(key.Set(elemname.GetLocalPart(), elemname.GetLocalPartLength()));
RETURN_IF_ERROR(m_current_sync_item->AddChild(key.CStr(), m_content_string.CStr()));
OP_DBG((UNI_L("Added child: %s=%s"), key.CStr(), m_content_string.CStr()));
}
}
else if (m_current_element == OpSyncParser::ServerInfoElement)
{
if (IsServerVersion1_1() && uni_strncmp(UNI_L("server_info"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0 ||
uni_strncmp(UNI_L("serverinfo"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
m_parsed_server_info = true;
m_current_element = OpSyncParser::LinkStartElement;
}
else if (uni_strncmp(UNI_L("error"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
OP_DBG((UNI_L("server_info: error='%s'"), m_content_string.CStr()));
RETURN_IF_ERROR(m_error_message.Set(m_content_string));
}
else if (IsServerVersion1_1() && uni_strncmp(UNI_L("long_interval"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0 ||
uni_strncmp(UNI_L("longinterval"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
unsigned int interval = uni_atoi(m_content_string.CStr());
if (interval)
m_server_info.SetSyncIntervalLong(interval);
OP_DBG(("server_info: long interval: %u", interval));
}
else if (IsServerVersion1_1() && uni_strncmp(UNI_L("short_interval"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0 ||
uni_strncmp(UNI_L("shortinterval"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
unsigned int interval = uni_atoi(m_content_string.CStr());
if (interval)
m_server_info.SetSyncIntervalShort(interval);
OP_DBG(("server_info: short interval: %u", interval));
}
else if (IsServerVersion1_1() && uni_strncmp(UNI_L("max_items"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0 ||
uni_strncmp(UNI_L("maxitems"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
UINT32 maxitems = uni_atoi(m_content_string.CStr());
if (maxitems)
m_server_info.SetSyncMaxItems(maxitems);
OP_DBG(("server_info: max items: %u", maxitems));
}
}
else if (uni_strncmp(UNI_L("data"), elemname.GetLocalPart(), elemname.GetLocalPartLength()) == 0)
{
OP_ASSERT(m_current_element == OpSyncParser::DataElement);
m_current_element = OpSyncParser::LinkStartElement;
}
else
m_current_element = OpSyncParser::OtherElement;
m_content_string.Empty();
return OpStatus::OK;
}
// ==================== MyOperaSyncParser
MyOperaSyncParser::MyOperaSyncParser(OpSyncFactory* factory, OpInternalSyncListener* listener)
: OpSyncParser(factory, listener)
, m_xml_parser(NULL)
, m_xml_parser_listener(NULL)
, m_xml_token_handler(NULL)
{
OP_NEW_DBG("MyOperaSyncParser::MyOperaSyncParser", "sync");
#ifdef DEBUG_LIVE_SYNC
// Build the path to the link debug files
OpString tmp_storage;
m_log_folder.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_USERPREFS_FOLDER, tmp_storage));
m_log_folder.Append(UNI_L("link"));
m_log_folder.Append(PATHSEP);
#endif // DEBUG_LIVE_SYNC
}
MyOperaSyncParser::~MyOperaSyncParser()
{
OP_NEW_DBG("MyOperaSyncParser::~MyOperaSyncParser", "sync");
m_system_info.DeleteAll();
OP_DELETE(m_xml_parser);
m_xml_parser = NULL;
OP_DELETE(m_xml_parser_listener);
m_xml_parser_listener = NULL;
OP_DELETE(m_xml_token_handler);
m_xml_token_handler = NULL;
}
BOOL MyOperaSyncParser::MaintainWhitespace(const uni_char* tag_name)
{
for (unsigned int cnt = 0; g_sync_myopera_item_table[cnt].name; cnt++)
{
if (!ascii_strcmp(tag_name, g_sync_myopera_item_table[cnt].name))
return g_sync_myopera_item_table[cnt].keep_whitespace;
}
return FALSE;
}
const uni_char* MyOperaSyncParser::GetObfuscatedName(const uni_char* name)
{
for (unsigned int cnt = 0; g_sync_myopera_item_table[cnt].name; cnt++)
{
if (!ascii_strcmp(name, g_sync_myopera_item_table[cnt].name))
return g_sync_myopera_item_table[cnt].obfuscated_name;
}
/* If we didn't find the obfuscated name for the specified name, return the
* input argument back to the caller: */
return name;
}
const uni_char* MyOperaSyncParser::GetRegularName(const uni_char* obfuscated_name)
{
for (unsigned int cnt = 0; g_sync_myopera_item_table[cnt].name; cnt++)
{
if (!ascii_strcmp(obfuscated_name, g_sync_myopera_item_table[cnt].obfuscated_name))
return g_sync_myopera_item_table[cnt].name;
}
/* If we didn't find the regular name for the specified obfuscated name,
* return the input argument back to the caller: */
return obfuscated_name;
}
void MyOperaSyncParser::ClearIncomingSyncItems(BOOL remove_deleted)
{
OP_NEW_DBG("MyOperaSyncParser::ClearIncomingSyncItems", "sync");
for (OpSyncDataItemIterator item(m_incoming_sync_items.First()); *item; ++item)
{
if (remove_deleted)
{
if (item->GetList())
item->GetList()->RemoveItem(*item);
}
else if (item->GetStatus() != OpSyncDataItem::DATAITEM_ACTION_DELETED)
{
if (item->GetList())
item->GetList()->RemoveItem(*item);
}
}
}
OP_STATUS MyOperaSyncParser::GenerateXML(OpString8& xmlout, OpSyncDataCollection& items_to_sync)
{
OP_NEW_DBG("MyOperaSyncParser::GenerateXML()", "sync");
OpString state;
RETURN_IF_ERROR(m_sync_state.GetSyncState(state));
if (state.IsEmpty())
RETURN_IF_ERROR(state.Set(UNI_L("0")));
/* If the sync-state is "0" we want to add a merge-action for all supported
* types: */
BOOL do_merge = (state == UNI_L("0"));
XMLFragment xmlfragment;
xmlfragment.SetDefaultWhitespaceHandling(XMLWHITESPACEHANDLING_PRESERVE);
RETURN_IF_ERROR(xmlfragment.OpenElement(LINKNAME("link")));
#ifdef SYNC_HAVE_EXTENSIONS
/* The sync protocol version 1.2 is bound to extensions:
* - If extensions are enabled, then we must use protocol version greater
* or equal to 1.2, otherwise the Opera/Link server does not understand a
* request with an "extension" entry. Note: this also implies that
* speed-dial-2 is enabled.
* - If extensions are disabled, then we continue to use protocol version
* 1.1, because there is no other data in the protocol which we could use.
* Note: this also implies that we can still use "speeddial" entries, i.e.
* speed-dial-2 is not required. */
RETURN_IF_ERROR(xmlfragment.SetAttribute(UNI_L("version"), UNI_L("1.2")));
#else
RETURN_IF_ERROR(xmlfragment.SetAttribute(UNI_L("version"), UNI_L("1.1")));
#endif
RETURN_IF_ERROR(xmlfragment.SetAttribute(UNI_L("syncstate"), state.CStr()));
RETURN_IF_ERROR(xmlfragment.SetAttribute(UNI_L("dirty"), (m_flags & SYNC_PARSER_COMPLETE_SYNC) ? UNI_L("1") : UNI_L("0")));
RETURN_IF_ERROR(xmlfragment.OpenElement(LINKNAME("client_info")));
for (unsigned int i = 0; i < SYNC_SUPPORTS_MAX; i++)
{
OpSyncSupports supports = static_cast<OpSyncSupports>(i);
if (!m_supports_state.HasSupports(supports))
continue;
OP_DBG(("") << supports);
/* Check each supports-type if we need to set the merge-action: */
if (do_merge || m_sync_state.IsDefaultValue(supports))
m_merge_actions.SetSupports(supports, true);
// Open the supports element
RETURN_IF_ERROR(xmlfragment.OpenElement(LINKNAME("supports")));
OpString* target;
m_system_info.GetData(SYNC_SYSTEMINFO_TARGET, &target);
if (target)
RETURN_IF_ERROR(xmlfragment.SetAttribute(UNI_L("target"), target->CStr() ? target->CStr() : UNI_L("")));
switch (supports)
{
case SYNC_SUPPORTS_BOOKMARK:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("bookmark"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_CONTACT:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("contact"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_ENCRYPTION:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("encryption"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_EXTENSION:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("extension"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_FEED:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("feed"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_NOTE:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("note"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_PASSWORD_MANAGER:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("password_manager"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_SEARCHES:
{
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("search_engine"), (unsigned int)~0));
#ifdef SYNC_SEARCH_ENGINE_TARGET
OpString target;
RETURN_IF_ERROR(target.Set(UNI_L(SYNC_SEARCH_ENGINE_TARGET)));
// empty target is valid, in which case we skip it
if (target.HasContent())
RETURN_IF_ERROR(xmlfragment.SetAttribute(UNI_L("target"), target.CStr()));
#endif // SYNC_SEARCH_ENGINE_TARGET
break;
}
case SYNC_SUPPORTS_SPEEDDIAL:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("speeddial"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_SPEEDDIAL_2:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("speeddial2"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_TYPED_HISTORY:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("typed_history"), (unsigned int)~0));
break;
case SYNC_SUPPORTS_URLFILTER:
RETURN_IF_ERROR(xmlfragment.AddText(UNI_L("urlfilter"), (unsigned int)~0));
break;
}
// Add backlog_since if needed
if (m_sync_state.IsOutOfSync(supports))
{
OpString state;
RETURN_IF_ERROR(m_sync_state.GetSyncState(state, supports));
RETURN_IF_ERROR(xmlfragment.SetAttribute(UNI_L("backlog_since"), state.HasContent() ? state.CStr() : UNI_L("0")));
OP_DBG((UNI_L("backlog since: %s"), state.CStr()));
}
xmlfragment.CloseElement(); // </supports>
}
OpHashIterator* iter = m_system_info.GetIterator();
if (!iter)
return OpStatus::ERR_NO_MEMORY;
else
{ // scope for AutoPtr
OpAutoPtr<OpHashIterator> iter_ap(iter);
if (OpStatus::IsSuccess(iter->First()))
{
do
{
OpSyncSystemInformationType type = (OpSyncSystemInformationType)reinterpret_cast<ptrdiff_t>(iter->GetKey());
OpString* data = (OpString*)iter->GetData();
switch(type)
{
case SYNC_SYSTEMINFO_BUILD:
RETURN_IF_ERROR(xmlfragment.AddText(LINKNAME("build"), data->CStr() ? data->CStr() : UNI_L(""), data->CStr() ? data->Length() : ~0));
break;
case SYNC_SYSTEMINFO_SYSTEM:
RETURN_IF_ERROR(xmlfragment.AddText(LINKNAME("system"), data->CStr() ? data->CStr() : UNI_L(""), data->CStr() ? data->Length() : ~0));
break;
case SYNC_SYSTEMINFO_SYSTEMVERSION:
RETURN_IF_ERROR(xmlfragment.AddText(LINKNAME("system_version"), data->CStr() ? data->CStr() : UNI_L(""), data->CStr() ? data->Length() : ~0));
break;
case SYNC_SYSTEMINFO_PRODUCT:
RETURN_IF_ERROR(xmlfragment.AddText(LINKNAME("product"), data->CStr() ? data->CStr() : UNI_L(""), data->CStr() ? data->Length() : ~0));
break;
}
} while (OpStatus::IsSuccess(iter->Next()));
}
}
#ifdef SYNC_SEND_DEBUG_ELEMENT
RETURN_IF_ERROR(xmlfragment.AddText(LINKNAME("debug"), UNI_L("1"), 1));
#endif // SYNC_SEND_DEBUG_ELEMENT
xmlfragment.CloseElement(); // </client_info>
if (m_merge_actions.HasAnySupports() &&
/* If we still have queued items, then we're not at the last chunk. So
* we cannot send the merge action now: */
!m_data_queue->HasQueuedItems(TRUE))
{
RETURN_IF_ERROR(xmlfragment.OpenElement(LINKNAME("actions")));
for (unsigned int i = 0; i < SYNC_SUPPORTS_MAX; i++)
{
OpSyncSupports supports = static_cast<OpSyncSupports>(i);
if (!m_supports_state.HasSupports(supports) ||
!m_merge_actions.HasSupports(supports))
continue;
const uni_char* a = 0;
switch (supports)
{
case SYNC_SUPPORTS_BOOKMARK: a = UNI_L("bookmark"); break;
case SYNC_SUPPORTS_CONTACT: a = UNI_L("contact"); break;
case SYNC_SUPPORTS_ENCRYPTION: break;
case SYNC_SUPPORTS_EXTENSION: break;
case SYNC_SUPPORTS_FEED: break;
case SYNC_SUPPORTS_NOTE: a = UNI_L("note"); break;
case SYNC_SUPPORTS_PASSWORD_MANAGER: break;
case SYNC_SUPPORTS_SEARCHES: a = UNI_L("search_engine"); break;
case SYNC_SUPPORTS_SPEEDDIAL: a = UNI_L("speeddial"); break;
case SYNC_SUPPORTS_SPEEDDIAL_2: a = UNI_L("speeddial2"); break;
case SYNC_SUPPORTS_TYPED_HISTORY: break;
case SYNC_SUPPORTS_URLFILTER: a = UNI_L("urlfilter"); break;
}
if (a)
{
RETURN_IF_ERROR(xmlfragment.OpenElement(LINKNAME("merge")));
RETURN_IF_ERROR(xmlfragment.SetAttribute(UNI_L("datatype"), a));
xmlfragment.CloseElement(); // </merge>
}
m_merge_actions.SetSupports(supports, false);
}
xmlfragment.CloseElement(); // </actions>
}
OP_ASSERT(items_to_sync.Cardinal() <= m_data_queue->GetMaxItems());
RETURN_IF_ERROR(xmlfragment.OpenElement(LINKNAME("data")));
if (items_to_sync.HasItems())
RETURN_IF_ERROR(ToXML(items_to_sync, xmlfragment, FALSE, TRUE));
xmlfragment.CloseElement(); // </data>
xmlfragment.CloseElement(); // </link>
ByteBuffer buffer;
RETURN_IF_ERROR(xmlfragment.GetEncodedXML(buffer, TRUE, "utf-8", FALSE));
for (unsigned int chunk = 0; chunk < buffer.GetChunkCount(); chunk++)
{
unsigned int bytes = 0;
char* chunk_ptr = buffer.GetChunk(chunk, &bytes);
if (chunk_ptr)
RETURN_IF_ERROR(xmlout.Append(chunk_ptr, bytes));
}
#ifdef DEBUG_LIVE_SYNC
if (g_pcsync->GetIntegerPref(PrefsCollectionSync::SyncLogTraffic))
{
TempBuffer fileout;
fileout.SetExpansionPolicy(TempBuffer::AGGRESSIVE);
fileout.SetCachedLengthPolicy(TempBuffer::TRUSTED);
OP_STATUS status = xmlfragment.GetXML(fileout, TRUE, "utf-8", FALSE);
OpString debug_output;
if (OpStatus::IsSuccess(status))
status = debug_output.Set(fileout.GetStorage(), fileout.Length());
OpString datestring;
if (OpStatus::IsSuccess(status))
{
double date = g_op_time_info->GetTimeUTC();
status = SyncUtil::SyncDateToString(date, datestring);
}
/* Get a filename of form "link_<timestamp>-<count>_req.xml" that does
* not yet exist: */
OpString filename;
OpFile file;
unsigned int count = 1;
BOOL exists = TRUE;
do {
if (OpStatus::IsError(filename.Set("")) ||
OpStatus::IsError(filename.AppendFormat(UNI_L("%slink_%s-%d_req.xml"), m_log_folder.CStr(), datestring.CStr(), count)) ||
OpStatus::IsError(file.Construct(filename.CStr())))
status = OpStatus::ERR;
else
OpStatus::Ignore(file.Exists(exists));
count++;
} while (exists && count > 0);
if (OpStatus::IsSuccess(status) &&
OpStatus::IsSuccess(file.Open(OPFILE_WRITE)))
{
file.WriteUTF8Line(debug_output.CStr());
file.Close();
}
}
#endif // DEBUG_LIVE_SYNC
return OpStatus::OK;
}
OpSyncError MyOperaSyncParser::PrepareNew(const URL& url)
{
OP_NEW_DBG("MyOperaSyncParser::PrepareNew()", "sync");
if (m_xml_parser)
{
OP_DELETE(m_xml_parser);
m_xml_parser = NULL;
}
if (!m_xml_parser_listener)
m_xml_parser_listener = OP_NEW(MyOperaSyncIgnoreXMLParserListener, ());
if (!m_xml_token_handler)
m_xml_token_handler = OP_NEW(MyOperaSyncXMLTokenHandler, (this));
// Make an xml parser to parse the Link response
if (!m_xml_parser_listener ||
OpStatus::IsError(XMLParser::Make(m_xml_parser, m_xml_parser_listener, g_main_message_handler, m_xml_token_handler, url)))
return SYNC_ERROR_MEMORY;
return SYNC_OK;
}
OpSyncError MyOperaSyncParser::Parse(const uni_char* data, size_t length, const URL& url)
{
OP_NEW_DBG("MyOperaSyncParser::Parse()", "sync");
ClearError();
m_parsed_new_state = FALSE;
XMLParser::Configuration configuration;
configuration.load_external_entities = XMLParser::LOADEXTERNALENTITIES_NO;
configuration.max_tokens_per_call = 0; // unlimited
if (!m_xml_parser)
{
OpSyncError err = PrepareNew(url);
if (err != SYNC_OK)
return err;
}
m_xml_parser->SetConfiguration(configuration);
m_sync_state.SetDirty(FALSE);
#ifdef DEBUG_LIVE_SYNC
if (g_pcsync->GetIntegerPref(PrefsCollectionSync::SyncLogTraffic))
{
OpFile file;
double date = g_op_time_info->GetTimeUTC();
OpString datestring;
SyncUtil::SyncDateToString(date, datestring);
OP_STATUS status = OpStatus::OK;
OpString filename;
unsigned int count = 1;
// Get a filename that does not yet exist:
BOOL exists = TRUE;
do {
if (OpStatus::IsError(filename.Set("")) ||
OpStatus::IsError(filename.AppendFormat(UNI_L("%slink_%s-%d_res.xml"), m_log_folder.CStr(), datestring.CStr(), count)) ||
OpStatus::IsError(file.Construct(filename.CStr())))
status = OpStatus::ERR;
else
OpStatus::Ignore(file.Exists(exists));
count++;
} while (OpStatus::IsSuccess(status) && exists && count > 0);
if (OpStatus::IsSuccess(status) &&
OpStatus::IsSuccess(file.Open(OPFILE_WRITE)))
{
OP_DBG((UNI_L("Writing file %s"), filename.CStr()));
file.WriteUTF8Line(data);
file.Close();
}
}
#endif // DEBUG_LIVE_SYNC
m_xml_token_handler->Reset();
OP_STATUS err = m_xml_parser->Parse(data, UNICODE_SIZE(UNICODE_DOWNSIZE(length)), FALSE);
if (m_xml_token_handler->HasParsedServerInformation())
m_server_info = m_xml_token_handler->GetServerInformation();
// Check the result functions
if (OpStatus::IsError(err) ||
m_xml_parser->IsFailed() ||
m_xml_token_handler->HasError())
{
OP_DELETE(m_xml_parser);
m_xml_parser = NULL;
m_error_message.TakeOver(m_xml_token_handler->TakeErrorMessage());
if (!m_error_message.HasContent())
m_error_message.Append(data, UNICODE_SIZE(UNICODE_DOWNSIZE(length)));
// Don't tell about these items next time
ClearIncomingSyncItems(FALSE);
if (m_xml_token_handler->GetErrorCode() != SYNC_OK)
return m_xml_token_handler->GetErrorCode();
else
return SYNC_ERROR_PARSER;
}
else
{
/* We successfully parsed the xml document that we received from the
* Link server, so move all parsed data into this instance: */
m_parsed_new_state = m_xml_token_handler->HasParsedNewSyncState();
if (m_parsed_new_state)
{
m_sync_state.SetSyncState(m_xml_token_handler->GetSyncState());
/* Currently we receive only one sync-state from the server. So
* update all supported sync-states with the value of the
* global state.
* This may change in a future version of the Link protocol, where
* the sync-state is reported for each supports type. */
for (unsigned int i = 0; i < SYNC_SUPPORTS_MAX; i++)
{
OpSyncSupports supports = static_cast<OpSyncSupports>(i);
if (m_supports_state.HasSupports(supports))
m_sync_state.SetSyncState(m_xml_token_handler->GetSyncState(), supports);
}
}
m_sync_state.SetDirty(m_xml_token_handler->IsDirtySyncRequested());
m_incoming_sync_items.AppendItems(m_xml_token_handler->TakeIncomingItems());
}
return SYNC_OK;
}
OpSyncItem::Key MyOperaSyncParser::GetPrimaryKey(OpSyncDataItem::DataItemType datatype)
{
switch (datatype)
{
case OpSyncDataItem::DATAITEM_SPEEDDIAL: return OpSyncItem::SYNC_KEY_POSITION;
case OpSyncDataItem::DATAITEM_SPEEDDIAL_2_SETTINGS: return OpSyncItem::SYNC_KEY_PARTNER_ID;
case OpSyncDataItem::DATAITEM_TYPED_HISTORY: return OpSyncItem::SYNC_KEY_CONTENT;
default: return OpSyncItem::SYNC_KEY_ID;
}
}
const uni_char* MyOperaSyncParser::GetPrimaryKeyName(OpSyncDataItem::DataItemType datatype)
{
switch (datatype)
{
case OpSyncDataItem::DATAITEM_SPEEDDIAL: return UNI_L("position");
case OpSyncDataItem::DATAITEM_SPEEDDIAL_2_SETTINGS: return UNI_L("partner_id");
case OpSyncDataItem::DATAITEM_TYPED_HISTORY: return UNI_L("content");
default: return UNI_L("id");
}
}
OpSyncItem::Key MyOperaSyncParser::GetPreviousRecordKey(OpSyncDataItem::DataItemType datatype)
{
switch (datatype)
{
case OpSyncDataItem::DATAITEM_ENCRYPTION_KEY:
case OpSyncDataItem::DATAITEM_ENCRYPTION_TYPE:
/* The elements encryption_key and encryption_type are singleton
* elements. There can only exist one element, so there cannot be a
* previous key. */
return OpSyncItem::SYNC_KEY_NONE;
case OpSyncDataItem::DATAITEM_SPEEDDIAL: return OpSyncItem::SYNC_KEY_NONE;
default: return OpSyncItem::SYNC_KEY_PREV;
}
}
const uni_char* MyOperaSyncParser::GetPreviousRecordKeyName(OpSyncDataItem::DataItemType datatype)
{
switch (datatype)
{
case OpSyncDataItem::DATAITEM_ENCRYPTION_KEY:
case OpSyncDataItem::DATAITEM_ENCRYPTION_TYPE:
/* The elements encryption_key and encryption_type are singleton
* elements. There can only exist one element, so there cannot be a
* previous key. */
return 0;
case OpSyncDataItem::DATAITEM_SPEEDDIAL: return NULL;
default: return UNI_L("previous");
}
}
OpSyncItem::Key MyOperaSyncParser::GetParentRecordKey(OpSyncDataItem::DataItemType datatype)
{
switch (datatype)
{
case OpSyncDataItem::DATAITEM_BOOKMARK_FOLDER:
case OpSyncDataItem::DATAITEM_ENCRYPTION_KEY:
case OpSyncDataItem::DATAITEM_ENCRYPTION_TYPE:
case OpSyncDataItem::DATAITEM_NOTE_FOLDER:
case OpSyncDataItem::DATAITEM_SEARCH:
case OpSyncDataItem::DATAITEM_SPEEDDIAL:
case OpSyncDataItem::DATAITEM_SPEEDDIAL_2:
case OpSyncDataItem::DATAITEM_SPEEDDIAL_2_SETTINGS:
case OpSyncDataItem::DATAITEM_TYPED_HISTORY:
case OpSyncDataItem::DATAITEM_URLFILTER:
return OpSyncItem::SYNC_KEY_NONE;
default:
return OpSyncItem::SYNC_KEY_PARENT;
}
}
const uni_char* MyOperaSyncParser::GetParentRecordKeyName(OpSyncDataItem::DataItemType datatype)
{
switch (datatype)
{
case OpSyncDataItem::DATAITEM_BOOKMARK_FOLDER:
case OpSyncDataItem::DATAITEM_ENCRYPTION_KEY:
case OpSyncDataItem::DATAITEM_ENCRYPTION_TYPE:
case OpSyncDataItem::DATAITEM_NOTE_FOLDER:
case OpSyncDataItem::DATAITEM_SEARCH:
case OpSyncDataItem::DATAITEM_SPEEDDIAL:
case OpSyncDataItem::DATAITEM_SPEEDDIAL_2:
case OpSyncDataItem::DATAITEM_SPEEDDIAL_2_SETTINGS:
case OpSyncDataItem::DATAITEM_TYPED_HISTORY:
case OpSyncDataItem::DATAITEM_URLFILTER:
return NULL;
default:
return UNI_L("parent");
}
}
#endif // SUPPORT_DATA_SYNC
|
#include "device.h"
#include <iostream>
#include <string.h>
#include <vector>
#include <queue>
#ifdef CLIENT
#include <gtk/gtk.h>
#endif
#ifndef _SERIAL_DEVICE_H
#define _SERIAL_DEVICE_H
namespace csys
{
#ifdef CLIENT
class window;
#endif
namespace dev
{
class serialDevice: public device
{
/********************************** ENUMS *****************************************/
public:
struct err
{ enum error { NOERR, NOLNK, WRERR, TMERR, MSERR}; };
struct cmd
{ enum command { NOCMD, POLL, INIT }; };
/******************************** DEVICE DATA ************************************/
private:
struct dd
{
int error;
int command;
bool link;
double data;
dd(): error(err::NOERR),
command(cmd::NOCMD),
link(false), data(0.0){}
bool operator == (const dd& rhs)
{
if(error != rhs.error ||
command != rhs.command ||
data != rhs.data ||
link != rhs.link)
{ return false; }
return true;
}
bool operator != (const dd& rhs) { return !operator == (rhs); }
};
/************************************** COMMON ********************************************/
private:
/* current scan */
struct dd io_cs;
/* previous scan */
struct dd io_ps;
public:
~serialDevice();
void serialize();
void unserialize();
bool is_valid() { return (err::NOERR == io_cs.error) ? true : false ; }
#ifdef SERVER
/**********************************************************************************************/
private:
serial& port;
message& msg;
/* signal to send, reset by sender immediately */
bool send;
/* signal to receive, reset by receiver when data available */
bool receive;
/* no response signal, reset by error handler and sender */
bool norep;
char eot;
char dev_addr;
char* request;
char* reply;
std::queue<dd> reqQue;
/* internal methods */
void try_push();
void try_pop();
void sender();
void receiver();
void error_handler();
void request_handler();
void patch();
void dispatch();
void set_checksum();
bool checksum_isok();
public:
serialDevice(const char* lbl, const char* port, char addr);
void process(io &sys_io);
double get_data() { return io_cs.data; }
#endif
#ifdef CLIENT
/************************************ WIDGET *********************************************/
private:
class widget
{
private:
serialDevice* pObj;
static window* pWin;
GtkWidget *frame;
GtkWidget *align;
GtkWidget *fixed;
GtkWidget *tboxState;
GtkWidget *presTbox;
GtkWidget *serialDeviceImage;
GtkWidget *linkImage;
GtkWidget *errorImage;
GtkWidget *linkLabel;
GtkWidget *errorLabel;
GtkWidget *serialDeviceLabel;
GtkWidget *presLabel;
GtkWidget *initButton;
static gboolean time_handler(widget* pWid);
static void init(GtkWidget* pWid, gpointer pVal);
static gint delete_event(GtkWidget *pWid, GdkEvent *event, gpointer pVal);
const char* get_state_string();
public:
widget(serialDevice* p);
};
/***************************************************************************************************/
private:
widget* pWidget;
public:
serialDevice(const char* lbl);
void process();
void build_widget();
struct dd& get_dd() { return io_cs; }
void translator();
void translate_error(int);
void translate_state(int);
void translate_command(int);
#endif
};
}
}
#endif
|
#include "colorspace.hpp"
int main(int argc, char **argv)
{
cv::Mat l_imageOutdoor, l_imageIndoor;
l_imageOutdoor = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);
l_imageIndoor = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);
// argv[3] is the output.pgm
cv::Mat l_imageDepth = cv::imread(argv[4], CV_LOAD_IMAGE_ANYDEPTH);
cv::Mat l_imageResultDepth = cv::Mat(l_imageDepth.size(), CV_16UC1);
cv::Mat l_imageGray = cv::Mat::zeros(l_imageIndoor.size(), CV_8UC1);
cv::cvtColor(l_imageIndoor, l_imageGray, CV_RGB2GRAY);
cv::Mat l_magePGM = cv::Mat(l_imageGray.size(), CV_8UC2);
std::cout << "depth type: " << l_imageDepth.type() << std::endl; // prints 2 == CV_16UC1
std::cout << "CV_8UC2 type: " << CV_8UC2 << std::endl;
std::cout << "CV_16UC1 type: " << CV_16UC1 << std::endl;
// write a 16 bit binary P5 PGM image
std::ofstream stream(argv[3], std::ios_base::out |std::ios_base::binary);
ushort* l_imageDataPGM = new ushort[l_imageDepth.cols*l_imageDepth.rows];
stream << "P5" << " " << l_imageDepth.cols << " " << l_imageDepth.rows << " " << 65535U << "\n";
uchar* ptr = l_imageDepth.data;
ushort data;
for (int i = 0; i < 2 * l_imageDepth.cols * l_imageDepth.rows; ++i, ptr++)
{
l_imageResultDepth.data[i] = *ptr;
if (i % 2 == 0)
{
memcpy(&data, ptr, 2);
l_imageDataPGM[i / 2] = ((data << 8) | (data >> 8));
// stream.write(reinterpret_cast<char*>(ptr), sizeof(uchar));
// stream.write(reinterpret_cast<char*>(ptr+1), sizeof(uchar));
// OR
// stream.write(reinterpret_cast<char*>(ptr), sizeof(ushort));
}
}
stream.write(reinterpret_cast<char*>(l_imageDataPGM), 2 * l_imageDepth.cols * l_imageDepth.rows);
stream.close();
// write a 16 bit binary P5 PGM image from a Grayscale PNG
ushort* l_imageDataPNG = new ushort[l_imageGray.cols*l_imageGray.rows];
std::ofstream streampng(argv[5], std::ios_base::out | std::ios_base::binary);
streampng << "P5" << " " << l_imageGray.cols << " " << l_imageGray.rows << " " << 65535U << "\n";
uchar* ptrpng = l_imageGray.data;
uchar a[2];
ushort datapng;
for (int i = 0; i < l_imageGray.cols * l_imageGray.rows; ++i, ptrpng++)
{
a[0] = 0;
a[1] = *ptrpng;
memcpy(&datapng, a, 2);
// l_imageDataPNG[i] = datapng;
l_imageDataPNG[i] = ((datapng << 8) | (datapng >> 8));
}
streampng.write(reinterpret_cast<char*>(l_imageDataPNG), 2 * l_imageGray.cols * l_imageGray.rows);
streampng.close();
/*for (int col = 0; col < l_imageGray.cols; ++col) {for (int row = 0; row < l_imageGray.rows; ++row) {l_imageResult.at<uchar>(row, col) = l_imageGray.at<uchar>(row, col);}}*/
std::string win1_name = "Window1";
cv::namedWindow(win1_name);
cv::imshow(win1_name, l_imageResultDepth);
cv::imwrite("C:\\Users\\dawudmaxx\\Entwirkler\\Code\\cvt\\colorspace\\data\\depth-output.png", l_imageResultDepth);
cv::waitKey(0);
cv::destroyWindow(win1_name);
return 1;
}
|
#ifndef BASEPIECE_CPP_INCLUDED
#define BASEPIECE_CPP_INCLUDED
#include <iostream>
#include <string>
#include "BasePiece.h"
/**@summary Default Constructor
*/
BasePiece::BasePiece()
{
type = " ";
}
/**@summary Default Destructor
*/
BasePiece::~BasePiece()
{ }
/**@summary Print the chess piece to the screen
* @return void
*/
void BasePiece::print()
{
if (color == Black)
{
std::cout << "b";
}
else
{
std::cout << "w";
}
std::cout << type;
}
/**@summary Updates the position of the chess piece
* @param pos - New position
* @return void
*/
void BasePiece::setPosition(Position pos)
{
this->position = pos;
}
/**@summary Gets the current position of the piece
* @return Position
*/
Position BasePiece::getPosition()
{
return position;
}
/**@summary Gets the current color of the piece
* @return Color
*/
Color BasePiece::getColor()
{
return color;
}
/**@summary Gets the type of the piece
* @return Type
*/
std::string BasePiece::getType()
{
return type;
}
#endif // BASEPIECE_CPP_INCLUDED
|
// Copyright (c) 2023 ETH Zurich
//
// 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
#include <pika/config.hpp>
#include <pika/assert.hpp>
#include <pika/async_mpi/mpi_polling.hpp>
#include <pika/concepts/concepts.hpp>
#include <pika/datastructures/variant.hpp>
#include <pika/debugging/demangle_helper.hpp>
#include <pika/debugging/print.hpp>
#include <pika/execution/algorithms/detail/helpers.hpp>
#include <pika/execution/algorithms/detail/partial_algorithm.hpp>
#include <pika/execution/algorithms/just.hpp>
#include <pika/execution/algorithms/then.hpp>
#include <pika/execution/algorithms/transfer.hpp>
#include <pika/execution_base/any_sender.hpp>
#include <pika/execution_base/receiver.hpp>
#include <pika/execution_base/sender.hpp>
#include <pika/executors/thread_pool_scheduler.hpp>
#include <pika/functional/detail/tag_fallback_invoke.hpp>
#include <pika/functional/invoke.hpp>
#include <pika/mpi_base/mpi.hpp>
#include <exception>
#include <type_traits>
#include <utility>
namespace pika::mpi::experimental::detail {
// -----------------------------------------------------------------
// by convention the title is 7 chars (for alignment)
using namespace pika::debug::detail;
template <int Level>
inline constexpr print_threshold<Level, 0> mpi_tran("MPITRAN");
namespace ex = pika::execution::experimental;
// -----------------------------------------------------------------
template <typename T>
struct any_sender_helper
{
using type = ex::unique_any_sender<T>;
};
template <>
struct any_sender_helper<void>
{
using type = ex::unique_any_sender<>;
};
// -----------------------------------------------------------------
// is func(Ts..., MPI_Request) invocable
template <typename F, typename... Ts>
inline constexpr bool is_mpi_request_invocable_v =
std::is_invocable_v<F, std::add_lvalue_reference_t<std::decay_t<Ts>>..., MPI_Request*>;
// -----------------------------------------------------------------
// get return type of func(Ts..., MPI_Request)
template <typename F, typename... Ts>
using mpi_request_invoke_result_t = std::decay_t<
std::invoke_result_t<F, std::add_lvalue_reference_t<std::decay_t<Ts>>..., MPI_Request*>>;
// -----------------------------------------------------------------
// return a scheduler on the mpi pool, with or without stack
inline auto mpi_pool_scheduler(bool stack = true)
{
if (stack)
{
return ex::thread_pool_scheduler{&resource::get_thread_pool(get_pool_name())};
}
else
{
return ex::with_stacksize(
ex::thread_pool_scheduler{&resource::get_thread_pool(get_pool_name())},
execution::thread_stacksize::nostack);
}
}
// -----------------------------------------------------------------
// return a scheduler on the default pool with added priority if requested
inline auto default_pool_scheduler(execution::thread_priority p)
{
if (p == execution::thread_priority::normal)
{
return ex::thread_pool_scheduler{&resource::get_thread_pool("default")};
}
return ex::with_priority(
ex::thread_pool_scheduler{&resource::get_thread_pool("default")}, p);
}
// -----------------------------------------------------------------
// depending on mpi_status : calls set_value (with Ts...) or set_error on the receiver
template <typename Receiver, typename... Ts>
void set_value_error_helper(int mpi_status, Receiver&& receiver, Ts&&... ts)
{
static_assert(sizeof...(Ts) <= 1, "Expecting at most one value");
if (mpi_status == MPI_SUCCESS)
{
ex::set_value(PIKA_FORWARD(Receiver, receiver), PIKA_FORWARD(Ts, ts)...);
}
else
{
ex::set_error(PIKA_FORWARD(Receiver, receiver),
std::make_exception_ptr(mpi_exception(mpi_status)));
}
}
// -----------------------------------------------------------------
// adds a request callback to the mpi polling code which will call
// the set_value/set_error helper using the void return signature
template <typename OperationState>
void set_value_request_callback_void(MPI_Request request, OperationState& op_state)
{
detail::add_request_callback(
[&op_state](int status) mutable {
using namespace pika::debug::detail;
PIKA_DETAIL_DP(mpi_tran<5>,
debug(str<>(
"callback_void") /*, "stream", detail::stream_name(op_state.stream)*/));
set_value_error_helper(status, PIKA_MOVE(op_state.receiver));
},
request);
}
// -----------------------------------------------------------------
// adds a request callback to the mpi polling code which will call
// the set_value/set_error helper with a valid return value
template <typename Result, typename OperationState>
void set_value_request_callback_non_void(MPI_Request request, OperationState& op_state)
{
detail::add_request_callback(
[&op_state](int status) mutable {
using namespace pika::debug::detail;
PIKA_DETAIL_DP(mpi_tran<5>, debug(str<>("callback_nonvoid")));
PIKA_ASSERT(std::holds_alternative<Result>(op_state.result));
set_value_error_helper(status, PIKA_MOVE(op_state.receiver),
PIKA_MOVE(std::get<Result>(op_state.result)));
},
request);
}
// -----------------------------------------------------------------
// adds a request callback to the mpi polling code which will call
// notify_one to wake up a suspended task
template <typename OperationState>
void resume_request_callback(MPI_Request request, OperationState& op_state)
{
op_state.completed = false;
detail::add_request_callback(
[&op_state](int status) mutable {
using namespace pika::debug::detail;
PIKA_DETAIL_DP(mpi_tran<5>,
debug(str<>("callback_void_suspend_resume"), "status", status
/*, "stream", detail::stream_name(op_state.stream)*/));
// wake up the suspended thread
{
std::lock_guard lk(op_state.mutex);
op_state.status = status;
op_state.completed = true;
}
op_state.cond_var.notify_one();
},
request);
}
// -----------------------------------------------------------------
// adds a request callback to the mpi polling code which will call
// set_value/error on the receiver
template <typename Receiver>
void schedule_task_callback(MPI_Request request, Receiver&& receiver)
{
detail::add_request_callback(
[receiver = PIKA_MOVE(receiver)](int status) mutable {
using namespace pika::debug::detail;
PIKA_DETAIL_DP(mpi_tran<5>, debug(str<>("schedule_task_callback")));
if (status != MPI_SUCCESS)
{
ex::set_error(PIKA_FORWARD(Receiver, receiver),
std::make_exception_ptr(mpi_exception(status)));
}
else
{
// pass the result onto a new task and invoke the continuation
auto snd0 = ex::just(status) |
ex::transfer(default_pool_scheduler(execution::thread_priority::high)) |
ex::then([receiver = PIKA_MOVE(receiver)](int status) mutable {
PIKA_DETAIL_DP(
mpi_tran<5>, debug(str<>("set_value_error_helper"), status));
set_value_error_helper(status, PIKA_MOVE(receiver));
});
ex::start_detached(PIKA_MOVE(snd0));
}
},
request);
}
} // namespace pika::mpi::experimental::detail
|
//===========================================================================
//! @file collision_3D.h
//! @brief 3D 当たり判定
//===========================================================================
#pragma once
//===========================================================================
//! @class Collision3D
//===========================================================================
class Collision3D : public Collision
{
public:
//! @brief コンストラクタ
Collision3D() = default;
//! @brief デストラクタ
~Collision3D() override = default;
//-----------------------------------------------------------------------
//! @brief 球と球の距離求める
//! @param [in] p1 中心座標1
//! @param [in] p2 中心座標2
//! @param [in] r1 半径1
//! @param [in] r2 半径2
//! @return 距離
//-----------------------------------------------------------------------
static f32 distance(
const Vector3& p1,
const Vector3& p2,
f32 r1,
f32 r2);
//-----------------------------------------------------------------------
//! @brief 球と球の距離求める
//! @param [in] s0 球の形状1
//! @param [in] s1 球の形状2
//! @return 距離
//-----------------------------------------------------------------------
static f32 distance(
const Sphere3D& s0,
const Sphere3D& s1);
//---------------------------------------------------------------------------
//! @brief 線と点の距離を求める
//! @param [in] line 線
//! @param [in] point 点の位置
//! @return 距離
//---------------------------------------------------------------------------
static f32 distance(
const Line3D& line,
const Vector3& point);
//-----------------------------------------------------------------------
//! @brief 線と点の最短距離
//! @param [in] line 線
//! @param [in] point 点の位置
//! @return 最短距離
//-----------------------------------------------------------------------
static f32 nearestDistanceLine(
const Line3D& line,
const Vector3& point);
//-----------------------------------------------------------------------
//! @brief 線分と点の最短距離
//! @param [in] lineSegment 線分
//! @param [in] point 点の位置
//! @return 最短距離
//-----------------------------------------------------------------------
static Vector3 nearestDistanceLineSegment(
const LineSegment3D& lineSegment,
const Vector3& point);
//-----------------------------------------------------------------------
//! @brief 球 vs 球
//! @param [in] s1 球1
//! @param [in] s2 球2
//! @return true 衝突あり
//! @return false 衝突なし
//-----------------------------------------------------------------------
static bool isHit(
const Sphere3D& s1,
const Sphere3D& s2);
//-----------------------------------------------------------------------
//! @brief 球 vs 球 (関数内で押し出し)
//! @param [in] s1 球1
//! @param [in] s2 球2
//! @param [in] mass1 重さ1
//! @param [in] mass2 重さ2
//-----------------------------------------------------------------------
static void adjustPosition(
const Sphere3D& s1,
const Sphere3D& s2,
f32 mass1 = 1.0f,
f32 mass2 = 1.0f);
//-----------------------------------------------------------------------
//! @brief 球 vs 球 (関数外で押し出し)
//! @param [in] s1 球1
//! @param [in] s2 球2
//! @param [out] extrusion1 押し出し値1
//! @param [out] extrusion2 押し出し値2
//! @param [in] mass1 重さ1
//! @param [in] mass2 重さ2
//! @return true 衝突あり
//! @return false 衝突なし
//-----------------------------------------------------------------------
static bool adjustPosition(
const Sphere3D& s1,
const Sphere3D& s2,
Vector3& extrusion1,
Vector3& extrusion2,
f32 mass1 = 1.0f,
f32 mass2 = 1.0f);
//---------------------------------------------------------------------------
//! カプセル vs カプセル
//! @param [in] capsule1 カプセル1
//! @param [in] capsule2 カプセル2
//! @retval true 衝突あり
//! @retval false 衝突なし
//---------------------------------------------------------------------------
bool isHit(
const Capsule3D& capsule1,
const Capsule3D& capsule2);
//-----------------------------------------------------------------------
//! @brief カプセル vs カプセル (関数外で押し出し)
//! @param [in] c1 カプセル1
//! @param [in] c2 カプセル2
//! @param [out] extrusion1 押し出し値1
//! @param [out] extrusion2 押し出し値2
//! @param [in] mass1 重さ1
//! @param [in] mass2 重さ2
//-----------------------------------------------------------------------
static void isHit(
const Capsule3D& c1,
const Capsule3D& c2,
Vector3& extrusion1,
Vector3& extrusion2,
f32 mass1 = 1.0f,
f32 mass2 = 1.0f);
//-----------------------------------------------------------------------
//! @brief 球 vs ポリゴン
//! @param [in] sphere 球
//! @param [in] triangle ポリゴン
//! @param [in] magnifications 法線の向き (1.0 | -1.0)
//! @param [out] nearestHitPosition 当たった場所
//! @param [out] nearestHitNormal 当たった場所の法線
//! @return true 衝突あり
//! @return false 衝突なし
//-----------------------------------------------------------------------
static bool isHit(
const Sphere3D& sphere,
const Triangle3D& triangle,
const f32& magnifications = 1.0f,
Vector3* nearestHitPosition = nullptr,
Vector3* nearestHitNormal = nullptr);
//-----------------------------------------------------------------------
//! @brief カプセル vs ポリゴン
//! @param [in] sphere 球
//! @param [in] triangle ポリゴン
//! @param [in] magnifications 法線の向き (1.0 | -1.0)
//! @param [out] nearestHitPosition 当たった場所
//! @param [out] nearestHitNormal 当たった場所の法線
//! @return true 衝突あり
//! @return false 衝突なし
//-----------------------------------------------------------------------
static bool isHit(
const Capsule3D& capsule,
const Triangle3D& triangle,
const Vector3& collisionPosition,
const f32& magnifications = 1.0f,
Vector3* nearestHitPosition = nullptr,
Vector3* nearestHitNormal = nullptr);
//-----------------------------------------------------------------------
//! @brief カプセル vs 球
//! @param [in] capsule0 カプセル
//! @param [in] sphere0 球
//! @return true 衝突あり
//! @return false 衝突なし
//-----------------------------------------------------------------------
static bool isHit(
const Capsule3D& capsule,
const Sphere3D& sphere);
//-----------------------------------------------------------------------
//! @brief 壁ずりベクトル
//! @param [in] direction オブジェクトの向き
//! @param [in] normal オブジェクトの法線
//! @param [in] ratio 係数 (1.0=壁ずり, 2.0=反射)
//! @return 壁ずりベクトル
//-----------------------------------------------------------------------
static Vector3 wallShear(
const Vector3& direction,
const Vector3& normal,
f32 ratio = 1.0f);
//---------------------------------------------------------------------------
//! @brief 三角形の中に含まれるかどうか
//! param [in] triangle 三角形
//! param [in] p 点の位置
//! return true 含まれている
//! return false 含まれていない
//---------------------------------------------------------------------------
bool isInside(
const Triangle3D& triangle,
const Vector3& p);
};
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x) ,left(NULL), right(NULL) {}
};
TreeNode *helper(vector<int> &preorder, vector<int> &inorder, int pstart, int pend,
int istart, int iend){
if(pstart > pend || istart > iend) return NULL;
int pivot = istart;
for(int i=istart; i<=iend ; i++){
if(inorder[i] == preorder[pstart])
pivot = i;
}
TreeNode *p = new TreeNode(preorder[pstart]);
p->left = helper(preorder,inorder,pstart+1,pstart+pivot-istartjk,istart,pivot-1);
p->right = helper(preorder,inorder,pstart+pivot-istart+1,pend,pivot+1,iend);
return p;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder){
if(preorder.size()==0 || inorder.size()==0) return NULL;
TreeNode *res = helper(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
return res;
}
int main(){
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_UTIL_OPFILE_OPMEMFILE_H
#define MODULES_UTIL_OPFILE_OPMEMFILE_H
#ifndef HAVE_NO_OPMEMFILE
#include "modules/util/opfile/opfile.h"
/**
* OpMemFile contains functionality for simulating a file in memory
* instead of a file on a filesystem.
*/
class OpMemFile : public OpFileDescriptor
{
public:
OpMemFile();
virtual ~OpMemFile();
/**
* Creates an OpMemFile object which will consist of the 'data'
* buffer and have an initial file size and buffer size equal to
* size. The file pointer will be at the beginning of the buffer.
*
* @param data Buffer which describes the contents of the file.
*
* @param size The size of the 'data' buffer.
*
* @param take_over If FALSE, a new buffer will be allocated and data will
* be copied; otherwise data is used as file data and the caller MUST NOT
* free data or access it after the returned OpMemFile has been deleted.
*
* @param name The name of this file, defaults to NULL (treated as an empty
* string). A copy shall be saved and returned by GetName.
*
* @return NULL if either the new object or the new buffer could
* not be allocated, otherwise an new OpMemFile object.
*/
static OpMemFile* Create(unsigned char* data, OpFileLength size, BOOL take_over,
const uni_char *name = NULL);
/**
* @overload
*/
static OpMemFile* Create(const unsigned char* data, OpFileLength size,
const uni_char *name = NULL);
virtual OpFileType Type() const { return OPMEMFILE; }
virtual BOOL IsWritable() const { return TRUE; }
virtual OP_STATUS Open(int mode);
virtual BOOL IsOpen() const;
virtual OP_STATUS Close();
virtual BOOL Eof() const;
virtual OP_STATUS Exists(BOOL& exists) const;
virtual OP_STATUS GetFilePos(OpFileLength& pos) const;
virtual OP_STATUS SetFilePos(OpFileLength pos, OpSeekMode seek_mode=SEEK_FROM_START);
virtual uni_char* GetName() { return m_filename; }
/**
* Writes a buffer 'data' of size 'len' to the file. The internal
* buffer size is increased if needed. The buffer size is at least
* doubled when the current buffer is too small.
*
* @return OpStatus::ERR_NO_MEMORY if the buffer could not be
* increased enough to save the new data.
*/
virtual OP_STATUS Write(const void* data, OpFileLength len);
virtual OP_STATUS Read(void* data, OpFileLength len, OpFileLength* bytes_read);
virtual OP_STATUS ReadLine(OpString8& str);
/**
* Set this object as a copy of another OpMemFile. The contents of
* this file will be deleted.
*
* @param copy An OpMemFile object which will be copied to this object.
*
* @return OpStatus::ERR_NO_MEMORY if there was not enough memory
* to allocate a new buffer for the new copy. Otherwise OpStatus::OK.
*/
virtual OP_STATUS Copy(const OpFileDescriptor* copy);
/**
* Return a copy of this file.
*
* @return Copy of this file or NULL on OOM.
*/
virtual OpFileDescriptor* CreateCopy() const;
OP_STATUS GetFileLength(OpFileLength& len) const { len=m_file_len; return OpStatus::OK; }
OpFileLength GetFileLength() const { return m_file_len; }
unsigned char* GetBuffer() const { return m_data; }
private:
OP_STATUS Resize(OpFileLength new_size);
OP_STATUS GrowIfNeeded(OpFileLength desired_size);
private:
unsigned char* m_data;
OpFileLength m_size;
OpFileLength m_pos;
OpFileLength m_file_len;
BOOL m_open;
uni_char* m_filename;
/** Block assignment operator. */
OpMemFile &operator=(const OpMemFile &);
/** Block copy constructor. */
OpMemFile(const OpMemFile &);
};
#endif // !HAVE_NO_OPMEMFILE
#endif // !MODULES_UTIL_OPFILE_OPMEMFILE_H
|
#pragma once
#include "cursur_point.h"
#include "Board.h"
#include "score.h"
#define BLOCK_TYPE_COUNT 7
#define ROTATE_COUNT 4
const cursur_point g_nxt_block_init_pos(14, 17);
const cursur_point g_cur_block_init_pos(4, 18);
enum BLOCK_TYPE {
BLOCK_I, BLOCK_J, BLOCK_L, BLOCK_O, BLOCK_S, BLOCK_T, BLOCK_Z
};
class control_block
{
public:
control_block(Board *board, BLOCK_TYPE type);
virtual void Draw(cursur_point reference_pos);
virtual void Erase(cursur_point reference_pos);
bool MoveDown(cursur_point reference_pos);
void MoveRight(cursur_point reference_pos);
void MoveLeft(cursur_point reference_pos);
void Rotate(cursur_point reference_pos);
void GoBottom(cursur_point reference_pos);
virtual void MarkCurBlockPos(cursur_point reference_pos);
bool CheckEndCondition(void);
void SetCenterPos(cursur_point pos);
void SetScrCenterPos(void);
protected:
virtual bool CheckValidPos(void);
protected:
cursur_point center_pos_;
cursur_point scrcenter_pos;
score score_;
BLOCK_TYPE type_;
int rotate_;
Board *board_;
};
|
#include <iostream>
struct Node {
int m_value;
Node* m_next;
};
Node* addNumber(Node*, int);
int max(Node*);
void jnjel (Node*);
int main() {
Node* root = nullptr;
int a = 0;
std::cout<<"\nMutqagreq tver.avarti hamar greq - end ";
std::cin >> a;
addNumber(root,a);
root = addNumber(root, a);
Node* tmp = root;
while (std::cin){
std::cin >> a;
if (std::cin) {
root = addNumber(root, a);
}
}
while ( nullptr != tmp) {
std::cout << tmp->m_value << " ";
tmp = tmp->m_next;
}
std::cout<<"\nMaksimumy klini "<<max(root)<<"\n";
jnjel(root);
return 0;
}
Node* addNumber(Node* root, int value) {
Node* newNode = new Node;
newNode->m_value = value;
newNode->m_next = nullptr;
if (nullptr == root ) {
root = newNode;
} else {
Node* temp = root;
while (temp->m_next != nullptr) {
temp = temp -> m_next;
}
temp->m_next = newNode;
}
return root;
}
int max(Node* root) {
Node* tmp = root;
int max = root-> m_value;
while ( nullptr != tmp->m_next) {
tmp = tmp-> m_next;
if (max < tmp->m_value) {
max = tmp->m_value;
}
}
return max;
}
void jnjel (Node* root) {
Node* tmp;
while (nullptr != root) {
tmp = root->m_next;
root = tmp;
delete tmp;
tmp = nullptr;
}
}
|
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
dfs(root, expectNumber);
return result;
}
private:
vector<vector<int> > result;
vector<int> tmp;
void dfs(TreeNode* node, int expectNumber){
if(!node) return;
tmp.push_back(node->val);
if(expectNumber - node->val == 0 && !node->left && !node->right){
result.push_back(tmp);
}else{
dfs(node->left, expectNumber - node->val);
dfs(node->right, expectNumber - node->val);
}
tmp.pop_back();
}
};
|
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
int main()
{ setlocale(LC_ALL, "Russian");
float x, z, y, b;
cout << "Введите число x:" << endl;
cin >> x;
cout << "Введите число y:" << endl;
cin >> y;
cout << "Введите число z:" << endl;
cin >> z;
b = pow(y, pow(labs(x), 1. / 3)) + ((pow(cos(y), 3) * labs(x - y) * (1 + (pow(sin(z), 2) / sqrt(x + y)))) / (exp(labs(x - y)) + x / 2));
cout << "Ответом является число:" << b << endl;
system("pause");
return 0;
}
|
//
// WelcomeLayer.h
// Aircraft
//
// Created by lc on 12/3/14.
//
//
#ifndef __Aircraft__WelcomeLayer__
#define __Aircraft__WelcomeLayer__
#include <stdio.h>
#include "PlistHandler.h"
#include "GameScene.h"
#include "GameOverLayer.h"
USING_NS_CC;
class WelcomeLayer : public Layer {
private:
bool haveSaveFile();
void getHighestHistoryScore();
public:
CREATE_FUNC(WelcomeLayer);
virtual bool init();
void loadingDone(Node* target);
};
#endif /* defined(__Aircraft__WelcomeLayer__) */
|
#ifndef SOCKS6MSG_VERSIONCHECKER_HH
#define SOCKS6MSG_VERSIONCHECKER_HH
#include "bytebuffer.hh"
namespace S6M
{
template <uint8_t VER>
struct VersionChecker
{
VersionChecker() {}
VersionChecker(ByteBuffer *bb)
{
uint8_t *ver = bb->peek<uint8_t>();
if (*ver != VER)
throw BadVersionException(*ver);
}
};
}
#endif // SOCKS6MSG_VERSIONCHECKER_HH
|
#pragma once
#include "GameObject/GameObject.h"
class BaseBackGround : GameObject
{
private:
struct Vertex {
Vector2 position;
Vector2 uv;
};
Vertex vertice[4];
LPDIRECT3DTEXTURE9 pTex;
public:
BaseBackGround();
~BaseBackGround();
void Init();
void Release();
void Update();
void Render();
void SetTexture(LPDIRECT3DTEXTURE9 texture) { pTex = texture; }
};
|
#ifndef MENU_H
#define MENU_H
#include <string>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iomanip>
class menu
{
private:
std::string nom;
std::string *option;
unsigned int nbOption;
int longueurMax;
public:
menu(const std::string &_nom);
~menu();
int Afficher();
static void AttendreAppuiTouche();
};
#endif // MENU_H
|
#include <cstring>
#include <list>
#include <cstdio>
#include <iostream>
#include "z3++.h"
#include "Strategy.h"
using namespace std;
using namespace z3;
const static int X[5] = {0,1,-1,0,0};
const static int Y[5] = {0,0,0,1,-1};
Strategy::Strategy(Graph _graph):graph(_graph),solution(this->graph.size){}
void Strategy::computeroute()
{
if (!optimizedget()) printf("Opt can't be solved\n");
}
int Strategy::computeindex(int x,int y)
{
return y*this->graph.size+x;
}
void Strategy::computexy(int index,int& x,int& y)
{
x = index % this->graph.size;
y = index / this->graph.size;
}
expr Strategy::bool_to_int(expr a,context& c,bool special)
{
if (!special)
{
expr one = c.int_val(1);
expr zero = c.int_val(0);
return to_expr(c,Z3_mk_ite(c,a,one,zero));
}
else
{
expr one = c.int_val(1);
expr zero = c.int_val(1000);
return to_expr(c,Z3_mk_ite(c,a,one,zero));
}
}
void Strategy::initializeX(expr_vector& x,context& c,Graph& currentgraph)
{
for (unsigned int i = 0;i < currentgraph.points.size()/2;++i)
for (unsigned int j = 0;j < currentgraph.size*currentgraph.size;++j)
{
std::stringstream x_name;
x_name << "x_"<<i<<'_'<<j;
x.push_back(c.bool_const(x_name.str().c_str()));
}
}
void Strategy::setst(optimize& s,context& c,expr_vector& x,Graph& currentgraph)
{
for (unsigned i = 0;i < currentgraph.points.size()/2;++i)
{
int start = computeindex(currentgraph.points[i*2].x,currentgraph.points[i*2].y);
int terminal = computeindex(currentgraph.points[i*2+1].x,currentgraph.points[i*2+1].y);
s.add(x[i*currentgraph.size*currentgraph.size + start]);
s.add(x[i*currentgraph.size*currentgraph.size + terminal]);
}
}
void Strategy::movement(optimize& s,context& c,expr_vector& x,Graph& currentgraph)
{
for (unsigned i = 0;i < currentgraph.points.size()/2;i++)
for (unsigned j = 0;j <currentgraph.size*currentgraph.size;j++)
{
int tem = computeindex(currentgraph.points[2*i].x,currentgraph.points[2*i].y);
int start = computeindex(currentgraph.points[2*i+1].x,currentgraph.points[2*i+1].y);
int currentx,currenty;
computexy(j,currentx,currenty);
expr constfalse = c.bool_val(false);
if (j == tem || j == start)
{
expr tempted = bool_to_int(constfalse,c,false);
for (int k = 1;k <= 4;k++)
{
int newk = j + X[k]+Y[k] *currentgraph.size;
int newkx,newky;
computexy(newk,newkx,newky);
if ((abs(newkx - currentx) + abs(newky - currenty)) == 1)
if (int(j + X[k]+Y[k] *currentgraph.size) >= 0 &&
j + X[k] +Y[k] *currentgraph.size < currentgraph.size*currentgraph.size)
tempted = tempted + bool_to_int(x[i*currentgraph.size*currentgraph.size+newk],c,false);
}
s.add(tempted == 1 && x[i*currentgraph.size*currentgraph.size+ j] || !x[i*currentgraph.size*currentgraph.size+ j] );
}
else
{
expr conjecture = !x[i*currentgraph.size*currentgraph.size+j];
expr tempted = bool_to_int(constfalse,c,false);
for (int k = 1;k <= 4;++k)
{
int newk = j + X[k]+Y[k] *currentgraph.size;
int newkx,newky;
computexy(newk,newkx,newky);
if (newk >= 0 &&
newk < currentgraph.size*currentgraph.size
&& (newkx == currentx || newky == currenty))
tempted = tempted + bool_to_int(x[i*currentgraph.size*currentgraph.size+newk],c,false);
}
s.add((tempted == 2) || (conjecture));
}
}
}
void Strategy::fluidic(context& c,optimize& s,expr_vector& x,Graph& currentgraph)
{
for (unsigned j = 0;j < currentgraph.size*currentgraph.size;j++)
{
expr temp = c.bool_val(false);
for (unsigned k = 0;k < currentgraph.points.size()/2;k++)
{
expr conjecture = x[k*currentgraph.size*currentgraph.size+j];
for (unsigned i = 0;i < currentgraph.points.size()/2;i++)
if (i != k)
conjecture = conjecture && (!x[i*currentgraph.size*currentgraph.size+j]);
temp = temp || conjecture;
}
expr conjecture = c.bool_val(true);
for (unsigned k = 0;k < currentgraph.points.size()/2;k++)
conjecture = conjecture && (!x[k*currentgraph.size*currentgraph.size+j]);
temp = temp || conjecture;
s.add(temp);
}
}
void Strategy::block(context& c,optimize& s,expr_vector& x,Graph& currentgraph)
{
for (unsigned i = 0;i < currentgraph.blocks.size();i++)
{
expr temp = c.bool_val(false);
expr con = temp;
int p = computeindex(currentgraph.blocks[i].x,currentgraph.blocks[i].y);
for (unsigned k = 0;k < currentgraph.points.size()/2;k++)
con = con || x[k*currentgraph.size*currentgraph.size+p];
s.add(!con);
}
}
void Strategy::optimizeRoute(context& c,optimize& s,expr_vector& x,expr& z,Graph& currentgraph)
{
for (unsigned i = 0;i < currentgraph.points.size()/2;i++)
{
int tem = computeindex(currentgraph.points[2*i].x,currentgraph.points[2*i].y);
int start = computeindex(currentgraph.points[2*i+1].x,currentgraph.points[2*i+1].y);
for (unsigned j = 0;j < currentgraph.size*currentgraph.size;j++)
{
bool special = false;
if (j == tem || j == start) special = true;
z = z + bool_to_int(x[i*currentgraph.size*currentgraph.size+j],c,special);
}
}
}
int Strategy::exp(const int x)
{
int count = 1;
for (int i = 1;i <= x; ++i)
count = 2 *count;
return count;
}
int Strategy::checknum(int x,int size)
{
int count = 0;
int i = 0;
while (i < size)
{
count += (x >> i) % 2;
i++;
}
return count;
}
Graph Strategy::GetSolution()
{
return this->solution;
}
|
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/NameValueCollection.h"
#include "Poco/StreamCopier.h"
#include "Poco/JSON/JSON.h"
#include "Poco/JSON/Parser.h"
#include "Poco/URI.h"
using namespace Poco;
using namespace std;
using namespace Poco::Net;
std::string getUri(std::string url)
{
URI reqURI(url);
Net::HTTPClientSession session(reqURI.getHost(), reqURI.getPort());
try
{
string getPath(reqURI.getPathAndQuery());
if (getPath.empty())
getPath = "/";
Net::HTTPRequest pocoREQ(Net::HTTPRequest::HTTP_GET, getPath, Net::HTTPMessage::HTTP_1_1);
session.sendRequest(pocoREQ);
HTTPResponse res;
//std::cout << res.getStatus() << " " << res.getReason() << endl;
if (res.getStatus() != HTTPResponse::HTTPStatus::HTTP_OK)
return "";
istream &is = session.receiveResponse(res);
#if _MSC_VER == 1800
return std::string(istreambuf_iterator<char>(is), std::istreambuf_iterator<char>());
#elif _MSC_VER > 1800
return string(istreambuf_iterator<char>(is), {});
#endif
}
catch (Exception)
{
return "";
}
}
JSON::Object::Ptr getJSONObject(string text)
{
JSON::Parser parser;
Dynamic::Var result = parser.parse(text);
JSON::Object::Ptr arr = result.extract<JSON::Object::Ptr>();
return arr;
}
int getIntFromJSON(JSON::Object::Ptr object, string key)
{
return object->getValue<int>(key);
}
string getStringFromJSON(JSON::Object::Ptr object, string key)
{
return object->getValue<string>(key);
}
|
#ifndef _ABSTRACTMENU_
#define _ABSTRACTMENU_
#include "AbstractScene.h"
USING_NS_CC;
// All menu will derives from this classes
// who is already a subclass or AbstractScene
class AbstractMenu : public AbstractScene
{
protected:
public:
AbstractMenu();
~AbstractMenu();
// routine functions
virtual void Start();
virtual void update(float dt);
virtual void Exit();
virtual void Transit();
// will create item that will switch to other scene
virtual void createItem();
};
#endif
|
#ifndef MESH_H
#define MESH_H
#include "material.h"
#include <QOpenGLBuffer>
#include <QOpenGLShaderProgram>
#include <QOpenGLVertexArrayObject>
#include <QVector2D>
#include <QVector3D>
#include <QOpenGLTexture>
#include <QOpenGLFunctions>
#include <bullet/btBulletCollisionCommon.h>
class Mesh
{
public:
Mesh(const QVector<QVector3D> &positions,
const QVector<QVector2D> &uvs = QVector<QVector2D>(),
const QVector<QVector3D> &normals = QVector<QVector3D>(),
const QVector<unsigned int> &indices = QVector<unsigned int>(),
const Material &material = Material());
void render(QOpenGLFunctions* f, QOpenGLShaderProgram *shaderProgram);
const QVector<QVector3D> &getPositions() const;
const QVector<unsigned int> & getIndices() const;
int getVertexCount() const;
const Material &getMaterial() const;
void setMaterial(const Material &material);
private:
int vertexCount;
QOpenGLVertexArrayObject vao;
QOpenGLBuffer positionBuffer, uvBuffer, normalBuffer, elementBuffer;
Material material;
QVector<QVector3D> positions;
QVector<unsigned int> indices;
};
#endif // MESH_H
|
#include <bits/stdc++.h>
using namespace std;
void mySort(vector<int> &nums)
{
for (int i = 0; i < nums.size(); i++)
{
int j = i;
while (j > 0 && nums[j] < nums[j - 1])
{
//greater value
swap(nums[j], nums[j - 1]);
j--;
}
}
}
int main()
{
vector<int> unsorted = {5, 4, 3, 2, 1};
mySort(unsorted);
for (int i = 0; i < unsorted.size(); i++)
{
cout << unsorted[i] << "\t";
}
cout << endl;
return 0;
}
|
// 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 _Aspect_XRAnalogActionData_HeaderFile
#define _Aspect_XRAnalogActionData_HeaderFile
#include <NCollection_Vec3.hxx>
//! Analog input XR action data.
struct Aspect_XRAnalogActionData
{
uint64_t ActiveOrigin; //!< The origin that caused this action's current state
float UpdateTime; //!< Time relative to now when this event happened. Will be negative to indicate a past time
NCollection_Vec3<float> VecXYZ; //!< the current state of this action
NCollection_Vec3<float> DeltaXYZ; //!< deltas since the previous update
bool IsActive; //!< whether or not this action is currently available to be bound in the active action set
//! Return TRUE if delta is non-zero.
bool IsChanged() { return !DeltaXYZ.IsEqual (NCollection_Vec3<float> (0.0f, 0.0f, 0.0f)); }
//! Empty constructor.
Aspect_XRAnalogActionData() : ActiveOrigin (0), UpdateTime (0.0f), IsActive (false) {}
};
#endif // _Aspect_XRAnalogActionData_HeaderFile
|
#ifndef TEST_COMMON_H
#define TEST_COMMON_H
#undef NDEBUG
#include <cassert>
#include <cmath>
#define assert_false(expr) assert(!expr)
#define assert_throws(expr) { \
bool _ = false; \
try { \
expr; \
} catch (...) { \
_ = true; \
} \
assert(_); \
}
#define assert_nothrow(expr) { \
bool _ = false; \
try { \
expr; \
} catch (...) { \
_ = true; \
} \
assert(!_); \
}
class Approx {
public:
Approx(double val, double eps = 0.001) : val(val), eps(eps) {
assert(eps > 0);
}
double val, eps;
};
inline bool operator==(double val, const Approx &app) {
return std::abs(val - app.val) < app.eps;
}
inline bool operator==(float val, const Approx &app) {
return std::abs(val - app.val) < app.eps;
}
#endif
|
#include <iostream>
using namespace std;
void get_stdin_10_20() {
// 实际上只能存19个字符,因为最后一个是'\0'
char buffer[20];
cin.ignore(10);
cin.getline(buffer, 10);
/*
stdin: 1234567890asdfg
output: 0asdfg
*/
cout << buffer << endl;
}
void print_in_ladder_shape() {
int width = 4;
char str[20];
// 考虑结尾有'\0'
cin.width(width + 1);
while (cin >> str) {
cout.width(width++);
cout << str << endl;
cin.width(width + 1);
}
}
int main() {
// print_in_ladder_shape();
// exit(0);
int sum = 0;
int num;
while (cin >> num) {
sum += num;
while (cin.peek() == ' ') {
// 消耗掉cin流中的空格
cin.get();
}
if (cin.peek() == '\n') {
break;
}
}
cout << "sum = " << sum << endl;
// get_stdin_10_20();
return 0;
}
|
#include "stdafx.h"
#include "Program.h"
#include "GameObject\Rect.h"
#include "GameObject\BackGround.h"
#include "./Common/Camera.h"
Program::Program()
{
srand(time(NULL));
//SOUND->AddSound("Test", "sounds/영전3.wav", true, true);
SOUND->AddSound("BGM", "sounds/bgm.mp3", true, true);
mainCamera = new Camera;
HRESULT hr = D3DXCreateTextureFromFile(
D2D::GetDevice(),
L"Textures/bg.png",
&pTex[0]
);
assert(SUCCEEDED(hr));
hr = D3DXCreateTextureFromFile(
D2D::GetDevice(),
L"Textures/goku_9x1.png",
&pTex[1]
);
assert(SUCCEEDED(hr));
bg = new BackGround;
bg->SetTexture(pTex[0]);
bg->Init();
bg->SetCamera(mainCamera);
rect = new Rect;
rect->SetTexture(pTex[1]);
rect->Init();
rect->SetCamera(mainCamera);
D2D::GetDevice()->SetRenderState(
// 라이트 지정
D3DRS_LIGHTING,
// 사용 여부
FALSE
);
//SOUND->Play("Test");
}
Program::~Program()
{
bg->Release();
rect->Release();
SAFE_RELEASE(pTex[0]);
SAFE_RELEASE(pTex[1]);
SAFE_DELETE(rect);
SAFE_DELETE(mainCamera);
}
void Program::Update()
{
if (INPUT->GetKeyDown(VK_SPACE)) {
if (!SOUND->IsPlaySound("BGM"))
SOUND->Play("BGM");
}
mainCamera->UpdateCamToDevice();
bg->Update();
rect->Update();
}
void Program::Render()
{
bg->Render();
rect->Render();
}
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int> > res;
if(!root) return res;
vector<int> temp;
deque<TreeNode*> Q;
Q.push_back(root);
TreeNode *last = root;
TreeNode *nlast = NULL;
bool leftToRight = true;
while(!Q.empty()){
if(leftToRight){
root = Q.front();
Q.pop_front();
temp.push_back(root->val);
if(root->left){
nlast = nlast == NULL ? root->left:nlast;
Q.push_back(root->left);
}
if(root->right){
nlast = nlast == NULL ? root->right:nlast;
Q.push_back(root->right);
}
}else{
root = Q.back();
Q.pop_back();
temp.push_back(root->val);
if(root->right){
nlast = nlast == NULL ? root->right:nlast;
Q.push_front(root->right);
}
if(root->left){
nlast = nlast == NULL ? root->left:nlast;
Q.push_front(root->left);
}
}
if(root == last){
leftToRight = !leftToRight;
res.push_back(temp);
temp.clear();
last = nlast;
nlast = NULL;
}
}
return res;
}
};
|
#ifndef LYTWSTRING_H
#define LYTWSTRING_H
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <string.h>
#include <wchar.h>
#include <math.h>
#include <iomanip>
using namespace std;
class LytWString
{
protected:
int Length;
wchar_t* String;
public:
LytWString();
LytWString(const wchar_t& Temp);
LytWString(const wchar_t* Temp);
LytWString(const LytWString& Temp);
LytWString operator=(const wchar_t* Temp);
LytWString operator=(const LytWString& Temp);
bool operator==(const LytWString& Temp)const;
bool operator!=(const LytWString& Temp)const;
bool operator>(const LytWString& Temp)const;
bool operator<(const LytWString& Temp)const;
bool operator>=(const LytWString& Temp)const;
bool operator<=(const LytWString& Temp)const;
LytWString operator+(const LytWString& Temp)const;
LytWString operator+(const wchar_t* Temp)const;
LytWString operator++();
LytWString operator++(int);
LytWString operator--();
LytWString operator--(int);
//LytWString operator*();
friend LytWString operator+(const wchar_t* TempLeft, const LytWString& TempRight);
friend wostream& operator<<(wostream& Output, const LytWString& Temp);
friend wistream& operator>>(wistream& Input, LytWString& Temp);
friend LytWString Wchar_tToLytWString(const wchar_t& Temp);
LytWString Sub(const int Index, const int Count)const;
void Insert(const int Index, const LytWString Temp);
void Delete(int Index, int Count);
LytWString ToUpper()const;
LytWString ToLower()const;
LytWString Left(const int Count)const;
LytWString Right(const int Count)const;
LytWString TrimLeft()const;
LytWString TrimRight()const;
LytWString Trim()const;
int Pos(const LytWString& Temp)const;
int Replace(const LytWString& Find , const LytWString& Result);
int Size()const;
wchar_t& operator[](int Index);
const wchar_t* Buffer()const;
~LytWString();
};
#endif
|
// Example 5.2 : shared_ptr
// Created by Oleksiy Grechnyev 2017, 2020
// Class Tjej is used a lot here, it logs Ctors and Dtors
#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include "Tjej.h"
using namespace std;
//==============================
// Classes for inheritance
class Animal{
public:
Animal(const string & name) : name(name) {} // Ctor
virtual ~Animal() { // virtual Dtor never hurts
cout << "Animal Dtor : " << name << endl;
}
virtual void talk(){
cout << "Animal : " << name << endl;
}
protected:
string name;
};
class Bear: public Animal{
public:
Bear(const string & name) : Animal(name) {} // Ctor
void talk() override {
cout << " ANGRY BEAR " << name << " : GRRRRRR !!! AWWWWRRRR !!!" << endl;
}
};
//==============================
// This can be a node for a double linked list
struct Node{
Node(const string & data) : data(data) {}
~Node(){
cout << "Dtor Node : " << data << endl;
}
string data;
shared_ptr<Node> next; // shared_ptr in one direction
weak_ptr<Node> prev; // and weak_ptr in the other one
};
//==============================
int main(){
{
cout << "\nshared_ptr demo : \n" << endl;
shared_ptr<Tjej> s1 = make_shared<Tjej>("Maria Traydor"); // Create like this
auto s2 = make_shared<Tjej>("Nel Zelpher"); // Or like this
shared_ptr<Tjej> s3(new Tjej("Sophia Esteed")); // Or like this (ugly)
// You can also convert unique_ptr to shared_ptr (don't forget move !)
auto u = make_unique<Tjej>("Mirage Koas");
shared_ptr<Tjej> s4(move(u)); // u is destroyed, s4 takes over the object
// We can put them into a container (copy operations)
vector<shared_ptr<Tjej>> v;
v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
// And create another one directly in the vector
v.emplace_back(make_shared<Tjej>("Clair Lasbard"));
// Make some copies
auto s5 = s1;
auto s6 = s2;
// Move is OK as well
auto s7 = move(s3);
s2.reset(); // This is OK, only one copy is destroyed
Tjej * rawPtr = s1.get(); // Get Raw pointer (don't delete it !!!)
// Print the vector
for (const auto & s : v)
cout << "Vector : " << s->getName() << endl;
}
{
cout << "\nshared_ptr polymorhism demo : \n" << endl;
auto sB = make_shared<Bear>("Teddy"); // Create a shared_ptr<Bear> object
cout << "Ref upcast :" << endl;
Animal & rA = *sB;
rA.talk();
cout << "Raw ptr upcast :" << endl;
Animal *pA = sB.get(); // Get the raw Bear * ptr
pA->talk();
cout << "shared_ptr upcast :" << endl;
shared_ptr<Animal> sA = sB; // Implicit upcast
sA->talk();
cout << "shared_ptr downcast :" << endl;
shared_ptr<Bear> sB1 = static_pointer_cast<Bear>(sA); // No checks ! Unsafe.
shared_ptr<Bear> sB2 = dynamic_pointer_cast<Bear>(sA); // Checks. Safe.
sB1->talk();
sB2->talk();
} // The managed object is deleted here
{
cout << "\nweak_ptr demo : \n" << endl;
// Create 2 nodes pointing at each other
auto s1 = make_shared<Node>("Nel Zelpher");
auto s2 = make_shared<Node>("Maria Traydor");
s1->next = s2;
s2->prev = s1; // A weak_ptr
weak_ptr<Node> w = s2->prev; // weak_ptr can be copied
// We can create a shared_ptr out of a weak_ptr for a temporary ownership
if (! w.expired()){
shared_ptr<Node> s = w.lock(); // s is actually a copy of s1
cout << "s->data = " << s->data << endl;
} // s is destroyed here, s1, s2 are still alive
} // s1, s2 die here and delete the managed objects
return 0;
}
|
// ConsoleApplication1.cpp: определяет точку входа для консольного приложения.
//
#include "fstream"
#include <stdio.h>
//0- пешка //будем считать, что может рубить и вперед, и назад
//1- ладья
//2-конь
//3-слон
//4-ферзь
//5-король
int attack(int i, int j, int **table) {
if (i >= 0 && i < 8 && j >= 0 && j < 8 /*&& table[i][j] <= 0*/) {
if (table[i][j] <= 0) {
table[i][j]--;
return 1;
} else return -1;
} else return 0;
}
int free(int i, int j, int **table) {
if (i >= 0 && i < 8 && j >= 0 && j < 8 && table[i][j]< 0) {
table[i][j]++;
return 1;
} else return 0;
}
bool PutCheck(int i, int j, int dx, int dy, int **table) {
int k = 0;
int l = 0;
for (k = i + dy, l = j + dx; k < 8 && k >= 0 && l < 8 && l >= 0 && table[k][l] <= 0; k += dy, l += dx)
attack(k, l, table);
if (k < 8 && k >= 0 && l < 8 && l >= 0) return 0;
else return 1;
}
void FreeCheck(int i, int j, int dx, int dy, int **table) {
int k = 0;
int l = 0;
for (k = i + dy, l = j + dx; k < 8 && k >= 0 && l < 8 && l >= 0 && table[k][l] < 0; k += dy, l += dx)
free(k, l, table);
}
bool UpdateTable(bool putorremove, int piece, int i, int j, int **table) { //1- put, 0-remove
bool good_attack = 1; // изначально считаем, что когда ставим фигуру, то ни по кому не бьем (этот флаг необходим только при встаке фигуры)
if (putorremove) {
if (table[i][j] == 0)
table[i][j] = piece;
if (piece == 1) { //пешка
if (attack(i + 1, j + 1, table) == -1)
good_attack = 0;
if (attack(i + 1, j - 1, table) == -1)
good_attack = 0;
if (attack(i - 1, j + 1, table) == -1)
good_attack = 0;
if (attack(i - 1, j - 1, table) == -1)
good_attack = 0;
}
if (piece == 2) { // ладья
if (!PutCheck(i, j, 1, 0, table))
good_attack = 0;
if (!PutCheck(i, j, -1, 0, table))
good_attack = 0;
if (!PutCheck(i, j, 0, 1, table))
good_attack = 0;
if (!PutCheck(i, j, 0, -1, table))
good_attack = 0;
}
if (piece == 3) { //конь
if (attack(i + 2, j + 1, table) == -1)
good_attack = 0;
if (attack(i + 2, j - 1, table) == -1)
good_attack = 0;
if (attack(i + 1, j + 2, table) == -1)
good_attack = 0;
if (attack(i - 1, j + 2, table) == -1)
good_attack = 0;
if (attack(i + 1, j - 2, table) == -1)
good_attack = 0;
if (attack(i - 1, j - 2, table) == -1)
good_attack = 0;
if (attack(i - 2, j + 1, table) == -1)
good_attack = 0;
if (attack(i - 2, j - 1, table) == -1)
good_attack = 0;
}
if (piece == 4) { //слон
if (!PutCheck(i, j, 1, 1, table))
good_attack = 0;
if (!PutCheck(i, j, 1, -1, table))
good_attack = 0;
if (!PutCheck(i, j, -1, 1, table))
good_attack = 0;
if (!PutCheck(i, j, -1, -1, table))
good_attack = 0;
}
if (piece == 5) { // ферзь
if (!PutCheck(i, j, 0, 1, table))
good_attack = 0;
if (!PutCheck(i, j, 0, -1, table))
good_attack = 0;
if (!PutCheck(i, j, 1, 0, table))
good_attack = 0;
if (!PutCheck(i, j, -1, 0, table))
good_attack = 0;
if (!PutCheck(i, j, 1, 1, table))
good_attack = 0;
if (!PutCheck(i, j, 1, -1, table))
good_attack = 0;
if (!PutCheck(i, j, -1, 1, table))
good_attack = 0;
if (!PutCheck(i, j, -1, -1, table))
good_attack = 0;
}
if (piece == 6) { //король
if (attack(i + 1, j + 1, table) == -1)
good_attack = 0;
if (attack(i + 1, j - 1, table) == -1)
good_attack = 0;
if (attack(i - 1, j + 1, table) == -1)
good_attack = 0;
if (attack(i - 1, j - 1, table) == -1)
good_attack = 0;
if (attack(i + 1, j, table) == -1)
good_attack = 0;
if (attack(i, j + 1, table) == -1)
good_attack = 0;
if (attack(i - 1, j, table) == -1)
good_attack = 0;
if (attack(i, j - 1, table) == -1)
good_attack = 0;
}
} else {
table[i][j] = 0;
if (piece == 1) { //пешка
free(i + 1, j + 1, table);
free(i + 1, j - 1, table);
free(i - 1, j + 1, table);
free(i - 1, j - 1, table);
}
if (piece == 2) { //ладья
FreeCheck(i, j, 0, 1, table);
FreeCheck(i, j, 0, -1, table);
FreeCheck(i, j, 1, 0, table);
FreeCheck(i, j, -1, 0, table);
}
if (piece == 3) { //конь
free(i + 2, j + 1, table);
free(i + 2, j - 1, table);
free(i + 1, j + 2, table);
free(i - 1, j + 2, table);
free(i + 1, j - 2, table);
free(i - 1, j - 2, table);
free(i - 2, j + 1, table);
free(i - 2, j - 1, table);
}
if (piece == 4) { //слон
FreeCheck(i, j, 1, 1, table);
FreeCheck(i, j, 1, -1, table);
FreeCheck(i, j, -1, 1, table);
FreeCheck(i, j, -1, -1, table);
}
if (piece == 5) { //королева
FreeCheck(i, j, 0, 1, table);
FreeCheck(i, j, 0, -1, table);
FreeCheck(i, j, 1, 0, table);
FreeCheck(i, j, -1, 0, table);
FreeCheck(i, j, 1, 1, table);
FreeCheck(i, j, 1, -1, table);
FreeCheck(i, j, -1, 1, table);
FreeCheck(i, j, -1, -1, table);
}
if (piece == 6) { //король
free(i + 1, j + 1, table);
free(i + 1, j - 1, table);
free(i - 1, j + 1, table);
free(i - 1, j - 1, table);
free(i + 1, j, table);
free(i, j + 1, table);
free(i - 1, j, table);
free(i, j - 1, table);
}
}
return good_attack;
}
void PrintSolution(int **table)
{
for (int i = 7; i >= 0; i--) {
printf("\n\n");
for (int j = 0; j < 8; j++)
printf("%6d", table[i][j]);
}
printf("\n\n\n\n\n");
}
int RemovePiece(int i, int j, int** table, int *pieces) {
pieces[table[i][j] - 1]++;
int new_no_zeros = UpdateTable(0, table[i][j], i, j, table);
return new_no_zeros;
}
int PutPiece(int i, int j, int k, int **table, int *pieces) {
if (table[i][j] == 0) {
if (pieces[k] != 0) {
bool good_attack = UpdateTable(1, k + 1, i, j, table);
pieces[k] -= 1;
// PrintSolution(table);
if (good_attack == 1)
return 1;
else {
RemovePiece(i, j, table, pieces); //если не удалось поставить фигуру k на (i,j) позицию (она атакует остальные), то удаляем ее оттуда
// PrintSolution(table);
return -1;
}
}
return -1;
}
return -2;
}
void ComputeNextCoordinates(int i, int j, int* coordinates)
{
if (j < 7) {
j++;
coordinates[0] = i;
coordinates[1] = j;
return;
}
if (j == 7 && i < 7) {
i++;
j = 0;
coordinates[0] = i;
coordinates[1] = j;
return;
}
if (j == 7 && i == 7) {
coordinates[0] = -1;
return;
}
}
void SetIndependent(int i, int j, int *amount_of_pieces, int *amount_of_solutions, int **table, int *pieces)
{
int nextcoordinates[2];
ComputeNextCoordinates(i, j, nextcoordinates);
for (int k = 0; k < 6; k++) {
int put = PutPiece(i, j, k, table, pieces);
//PrintSolution();
if (put == -1) //если фигура k атакует уже поставленные или у нас такой фигуры нет, то пробуем следующую фигуру
continue;
if (put == -2) // если клетка, на которую хотим поставить фигуру, уже атакуется, то выходим из цикла
break;
*amount_of_pieces -= 1;
if (*amount_of_pieces == 0) {
//PrintSolution(table);
*amount_of_solutions += 1;
//printf("\n%d", *amount_of_solutions);
}
if (nextcoordinates[0] >= 0 && *amount_of_pieces >= 0)
SetIndependent(nextcoordinates[0], nextcoordinates[1], amount_of_pieces, amount_of_solutions, table, pieces);
RemovePiece(i, j, table, pieces);
*amount_of_pieces += 1;
}
if (*amount_of_pieces && (nextcoordinates[0] >= 0) && (*amount_of_pieces) <= (64 - (nextcoordinates[0] * 8 + nextcoordinates[1]))) //тут, в отличие от задачи на фигуры-часовые, в следствие иного перебора мы можем ставить фигуру в следующую клетку, даже если в предыдущую ее поставить не могли
SetIndependent(nextcoordinates[0], nextcoordinates[1], amount_of_pieces, amount_of_solutions, table, pieces);
}
int ReadInputFile(int argc, char* argv[], int *pieces, int *amount_of_pieces) {
std::string input;
if (argc == 1)
input = "input.txt";
else
input = argv[1];
std::ifstream in(input);
int i = 0; // пробегаем по массиву фигур (pieces) и заполняем его
while (in.good() && i < 6) {
in >> pieces[i];
if (pieces[i] < 0) { // фигур не может быть меньше нуля
//printf("");
return 2;
}
i++;
}
if (i < 6) { // если не удалось заполнить весь массив (не дошли до конца), то входной файл некорректен
printf("");
return 2;
}
if (i == 6 && in.fail()) { //если дошли до конца, но последний элемент был считан неверно, то входной файл также некорректен
//printf("");
return 2;
}
// int amount_of_pieces = 0;
for (int j = 0; j < 6; j++) {
*amount_of_pieces += pieces[j];
}
if (*amount_of_pieces > 64) { // число фигур не может быть больше 64
//printf("");
return 2;
}
}
int main(int argc, char* argv[])
{
int **table = new int*[8];
for (int i = 0; i < 8; i++) {
table[i] = new int[8];
for (int j = 0; j < 8; j++) {
table[i][j] = 0;
}
}
int pieces[6];
int amount_of_solutions = 0;
int amount_of_pieces = 0;
if (ReadInputFile(argc, argv, pieces, &amount_of_pieces) == 2) {
printf("\nwrong input data! \n");
return 0;
}
for (int i = 0; i < 6; i++)
printf("%d ", pieces[i]);
SetIndependent(0, 0, &amount_of_pieces, &amount_of_solutions, table, pieces);
printf("\n%d", amount_of_solutions);
FILE* fout;
fopen_s(&fout, "output.txt", "w");
fprintf(fout, "%d", amount_of_solutions);
fclose(fout);
for (int i = 0; i < 8; i++) {
delete table[i];
}
delete table;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
class listNode
{
public:
int data;
listNode *next;
listNode(int data)
{
this->data = data;
this->next = nullptr;
}
};
class mylist
{
public:
listNode *head;
mylist()
{
this->head = nullptr;
}
void addNode(int data)
{
listNode *newNode = new listNode(data), *temp = this->head;
if (this->head == nullptr)
{
this->head = newNode;
return;
}
while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = newNode;
// return this->head;
}
void printList(listNode *head)
{
if (head != nullptr)
{
cout << head->data << " ";
return printList(head->next);
}
return;
}
};
int main()
{
mylist *templist = new mylist();
templist->addNode(10);
templist->addNode(3);
templist->addNode(5);
templist->printList(templist->head);
// mergekSortedLists;
/* two solutions.
1. Take 2 at a time: (nk) : k = 8
// considering each list contains n/k elements
merge 1&2 => a ; (n/k) + n/k = 2n/k
merge a&3 => b : 2n/k + n/k = 3n/k
merge b&4 => c 3n/k + n/k = 4n/k
merge c&5 => d
merge d&6 => e
merge e&7 => f
merge f&8 => Final = 8n/k;
((k*k-1)/2) * n/k = O(kn)
2. DIVIDE AND CONQUER. O(nlogk) : k = 8, then
step 1: this step takes O(n) why ? access each element once
merge 1&2 => a
merge 3&4 => b
merge 5&6 => c
merge 7&8 => d
step 2: this step takes O(n)
merge a&b => A
merge c&d => B
step 3: this step takes O(n)
.
.
.
log k steps:
merge A&B => Final list
therefore O(n*logk)
*/
return 0;
}
|
// Created on : Thu May 14 15:13:19 2020
// Created by: Igor KHOZHANOV
// Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V2.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 _StepVisual_SurfaceStyleRendering_HeaderFile_
#define _StepVisual_SurfaceStyleRendering_HeaderFile_
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Transient.hxx>
#include <StepVisual_ShadingSurfaceMethod.hxx>
#include <StepVisual_Colour.hxx>
class StepVisual_SurfaceStyleRendering;
DEFINE_STANDARD_HANDLE(StepVisual_SurfaceStyleRendering, Standard_Transient)
//! Representation of STEP entity SurfaceStyleRendering
class StepVisual_SurfaceStyleRendering : public Standard_Transient
{
public :
//! default constructor
Standard_EXPORT StepVisual_SurfaceStyleRendering();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init(const StepVisual_ShadingSurfaceMethod theRenderingMethod,
const Handle(StepVisual_Colour)& theSurfaceColour);
//! Returns field RenderingMethod
Standard_EXPORT StepVisual_ShadingSurfaceMethod RenderingMethod() const;
//! Sets field RenderingMethod
Standard_EXPORT void SetRenderingMethod (const StepVisual_ShadingSurfaceMethod theRenderingMethod);
//! Returns field SurfaceColour
Standard_EXPORT Handle(StepVisual_Colour) SurfaceColour() const;
//! Sets field SurfaceColour
Standard_EXPORT void SetSurfaceColour (const Handle(StepVisual_Colour)& theSurfaceColour);
DEFINE_STANDARD_RTTIEXT(StepVisual_SurfaceStyleRendering, Standard_Transient)
private:
StepVisual_ShadingSurfaceMethod myRenderingMethod;
Handle(StepVisual_Colour) mySurfaceColour;
};
#endif // _StepVisual_SurfaceStyleRendering_HeaderFile_
|
#include "Demon.h"
Demon::Demon(Unit* warlock, const std::string& name, const std::string& type,const std::string& mutation, int health, int damage) : Unit(type, new DemonState(name, health, damage), new UnitAttack(), mutation) {
this->master = warlock;
this->getObserversList()->addObserver(this->master);
std::cout << " creating Demon " << std::endl;
}
Demon::~Demon() {
std::cout << " deleting Demon " << std::endl;
}
Unit* Demon::getMaster() const {
return this->master;
}
void Demon::demonIsDestroyed() {
this->master = nullptr;
}
std::ostream& operator<<(std::ostream& out, const Demon& demon) {
out << demon.getUnitType() << " [" << demon.getState() << "] ";
if ( demon.getMaster() ) {
out << "is mastered by " << demon.getMaster()->getUnitType() << " "<< demon.getMaster()->getState().getName() << '\n';
} else {
out << "is destroyed" << '\n';
}
return out;
}
|
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
#include "../Weapon.h"
const idEventDef EV_Railgun_RestoreHum( "<railgunRestoreHum>", "" );
class rvWeaponRailgun : public rvWeapon {
public:
CLASS_PROTOTYPE( rvWeaponRailgun );
rvWeaponRailgun ( void );
virtual void Spawn ( void );
virtual void Think ( void );
void Save ( idSaveGame *savefile ) const;
void Restore ( idRestoreGame *savefile );
void PreSave ( void );
void PostSave ( void );
void ClientUnstale ( void );
protected:
jointHandle_t jointBatteryView;
private:
stateResult_t State_Idle ( const stateParms_t& parms );
stateResult_t State_Fire ( const stateParms_t& parms );
stateResult_t State_Reload ( const stateParms_t& parms );
void Event_RestoreHum ( void );
CLASS_STATES_PROTOTYPE ( rvWeaponRailgun );
};
CLASS_DECLARATION( rvWeapon, rvWeaponRailgun )
EVENT( EV_Railgun_RestoreHum, rvWeaponRailgun::Event_RestoreHum )
END_CLASS
/*
================
rvWeaponRailgun::rvWeaponRailgun
================
*/
rvWeaponRailgun::rvWeaponRailgun ( void ) {
}
/*
================
rvWeaponRailgun::Spawn
================
*/
void rvWeaponRailgun::Spawn ( void ) {
SetState ( "Raise", 0 );
}
/*
================
rvWeaponRailgun::Save
================
*/
void rvWeaponRailgun::Save ( idSaveGame *savefile ) const {
savefile->WriteJoint( jointBatteryView );
}
/*
================
rvWeaponRailgun::Restore
================
*/
void rvWeaponRailgun::Restore ( idRestoreGame *savefile ) {
savefile->ReadJoint( jointBatteryView );
}
/*
================
rvWeaponRailgun::PreSave
================
*/
void rvWeaponRailgun::PreSave ( void ) {
//this should shoosh the humming but not the shooting sound.
StopSound( SND_CHANNEL_BODY2, 0);
}
/*
================
rvWeaponRailgun::PostSave
================
*/
void rvWeaponRailgun::PostSave ( void ) {
//restore the humming
PostEventMS( &EV_Railgun_RestoreHum, 10);
}
/*
================
rvWeaponRailgun::Think
================
*/
void rvWeaponRailgun::Think ( void ) {
// Let the real weapon think first
rvWeapon::Think ( );
if ( zoomGui && wsfl.zoom && !gameLocal.isMultiplayer ) {
int ammo = AmmoInClip();
if ( ammo >= 0 ) {
zoomGui->SetStateInt( "player_ammo", ammo );
}
}
}
/*
===============================================================================
States
===============================================================================
*/
CLASS_STATES_DECLARATION ( rvWeaponRailgun )
STATE ( "Idle", rvWeaponRailgun::State_Idle)
STATE ( "Fire", rvWeaponRailgun::State_Fire )
STATE ( "Reload", rvWeaponRailgun::State_Reload )
END_CLASS_STATES
/*
================
rvWeaponRailgun::State_Idle
================
*/
stateResult_t rvWeaponRailgun::State_Idle( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
if ( !AmmoAvailable ( ) ) {
SetStatus ( WP_OUTOFAMMO );
} else {
StopSound( SND_CHANNEL_BODY2, false );
StartSound( "snd_idle_hum", SND_CHANNEL_BODY2, 0, false, NULL );
SetStatus ( WP_READY );
}
PlayCycle( ANIMCHANNEL_ALL, "idle", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( wsfl.lowerWeapon ) {
StopSound( SND_CHANNEL_BODY2, false );
SetState ( "Lower", 4 );
return SRESULT_DONE;
}
if ( gameLocal.time > nextAttackTime && wsfl.attack && AmmoInClip ( ) ) {
SetState ( "Fire", 0 );
return SRESULT_DONE;
}
// Auto reload?
if ( AutoReload() && !AmmoInClip ( ) && AmmoAvailable () ) {
SetState ( "reload", 2 );
return SRESULT_DONE;
}
if ( wsfl.netReload || (wsfl.reload && AmmoInClip() < ClipSize() && AmmoAvailable()>AmmoInClip()) ) {
SetState ( "Reload", 4 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvWeaponRailgun::State_Fire
================
*/
stateResult_t rvWeaponRailgun::State_Fire ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
nextAttackTime = gameLocal.time + (fireRate * owner->PowerUpModifier ( PMOD_FIRERATE ));
Attack ( false, 1, spread, 0, 1.0f );
PlayAnim ( ANIMCHANNEL_ALL, "fire", 0 );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( ( gameLocal.isMultiplayer && gameLocal.time >= nextAttackTime ) ||
( !gameLocal.isMultiplayer && ( AnimDone ( ANIMCHANNEL_ALL, 2 ) ) ) ) {
SetState ( "Idle", 0 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvWeaponRailgun::State_Reload
================
*/
stateResult_t rvWeaponRailgun::State_Reload ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
if ( wsfl.netReload ) {
wsfl.netReload = false;
} else {
NetReload ( );
}
SetStatus ( WP_RELOAD );
PlayAnim ( ANIMCHANNEL_ALL, "reload", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_ALL, 4 ) ) {
AddToClip ( ClipSize() );
SetState ( "Idle", 4 );
return SRESULT_DONE;
}
if ( wsfl.lowerWeapon ) {
StopSound( SND_CHANNEL_BODY2, false );
SetState ( "Lower", 4 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
===============================================================================
Event
===============================================================================
*/
/*
================
rvWeaponRailgun::State_Reload
================
*/
void rvWeaponRailgun::Event_RestoreHum ( void ) {
StopSound( SND_CHANNEL_BODY2, false );
StartSound( "snd_idle_hum", SND_CHANNEL_BODY2, 0, false, NULL );
}
/*
================
rvWeaponRailgun::ClientUnStale
================
*/
void rvWeaponRailgun::ClientUnstale( void ) {
Event_RestoreHum();
}
|
/*
* tldupdater.h
* Opera
*
* Created by Adam Minchinton
* Copyright 2008 Opera ASA. All rights reserved.
*
*/
#ifndef _TLDUPDATER_H_INCLUDED_
#define _TLDUPDATER_H_INCLUDED_
#include "modules/hardcore/timer/optimer.h"
#include "adjunct/desktop_util/search/tlddownloader.h"
class TLDDownloader;
//////////////////////////////////////////////////////////////////////
class TLDUpdater : public OpTimerListener
{
public:
TLDUpdater();
virtual ~TLDUpdater();
OP_STATUS StartDownload();
void TLDDownloadFailed(TLDDownloader::DownloadStatus status);
protected:
// OpTimerListener implementation
virtual void OnTimeOut(OpTimer *timer);
private:
TLDDownloader* m_tld_downloader; ///< Holds the downloader that manages downloading of the tld.
time_t m_time_of_last_check; ///< Holds the time of the last call
OpTimer* m_update_check_timer; ///< Timer for rescheduling update check
UINT32 m_retry_interval; ///< Holds the length before the next retry
};
#endif // _TLDUPDATER_H_INCLUDED_
|
/**
* \copyright
* (c) 2012 - 2015 E.S.R. Labs GmbH (http://www.esrlabs.com)
* All rights reserved.
*/
/**
* Contains base types for iterators.
* \file SIteratorBaseTypes.h
* \ingroup sstl
*/
#ifndef SITERATORBASETYPES_H_
#define SITERATORBASETYPES_H_
/**
* input iterator
*
* \section Description
* May advance through a iterator range. Reads each
* value exactly one time.
*/
struct SInputIteratorTag {};
/**
* output iterator
*
* \section Description
* May advance through a iterator range and alter values.
*/
struct SOutputIteratorTag {};
/**
* forward iterator
*
* \section Description
* May advance through a iterator range and read each value
* more than on time.
*/
struct SForwardIteratorTag : public SInputIteratorTag {};
/**
* bidirectional iterator
*
* \section Description
* May go through a iterator range in both directions and
* read each value more than one time
*/
struct SBidirectionalIteratorTag : public SForwardIteratorTag {};
/**
* random access iterator
*
* \section Description
* May go through a iterator range like a pointer through an
* array and read each value more than one time.
*/
struct SRandomAccessIteratorTag : public SBidirectionalIteratorTag {};
/**
* optional base class for iterators
* \param Category iterators category
* \param T type iterator points to
* \param Distance signed integral type
* \param Pointer pointer to T
* \param Reference reference to T
*
* Classes may subclass this class to save some typedef work.
*/
template<
typename Category,
typename T,
typename Distance = signed int,
typename Pointer = T*,
typename Reference = T&>
struct SIterator
{
/** the iterators category */
typedef Category iterator_category;
/** type of value iterator points to */
typedef T value_type;
/** signed integral type */
typedef Distance difference_type;
/** pointer to value type */
typedef Pointer pointer;
/** reference to value type */
typedef Reference reference;
};
/**
* traits for iterators
* \param Iterator iterator to generate traits for
*/
template<typename Iterator>
struct SIteratorTraits
{
/** the iterators category */
typedef typename Iterator::iterator_category iterator_category;
/** type of value iterator points to */
typedef typename Iterator::value_type value_type;
/** signed integral type */
typedef typename Iterator::difference_type difference_type;
/** pointer to value */
typedef typename Iterator::pointer pointer;
/** reference to value */
typedef typename Iterator::reference reference;
};
/**
* special implementation for pointers
* \param T type of value for whose pointer traits are generated
*
* \see SIteratorTraits
*/
template<typename T>
struct SIteratorTraits<T*>
{
typedef SRandomAccessIteratorTag iterator_category;
typedef T value_type;
typedef signed int difference_type;
typedef value_type* pointer;
typedef value_type& reference;
};
/**
* special implementation for const pointers
* \param T type of value for whose const pointer traits are generated
*
* \see SIteratorTraits
*
*/
template<typename T>
struct SIteratorTraits<const T*>
{
typedef SRandomAccessIteratorTag iterator_category;
typedef T value_type;
typedef signed int difference_type;
typedef const value_type* pointer;
typedef const value_type& reference;
};
#endif /*SITERATORBASETYPES_H_*/
|
#ifndef GNMESHEBM_H
#define GNMESHEBM_H
class GnMeshEBM
{
public:
static void StartupEBM();
static void ShutdownEBM();
};
#endif // GNMESHEBM_H
|
/* XMRig
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "backend/cpu/CpuConfig.h"
#include "3rdparty/rapidjson/document.h"
#include "backend/cpu/CpuConfig_gen.h"
#include "backend/cpu/Cpu.h"
#include "base/io/json/Json.h"
#include <algorithm>
namespace xmrig {
const char *CpuConfig::kEnabled = "enabled";
const char *CpuConfig::kField = "cpu";
const char *CpuConfig::kHugePages = "huge-pages";
const char *CpuConfig::kHugePagesJit = "huge-pages-jit";
const char *CpuConfig::kHwAes = "hw-aes";
const char *CpuConfig::kMaxThreadsHint = "max-threads-hint";
const char *CpuConfig::kMemoryPool = "memory-pool";
const char *CpuConfig::kPriority = "priority";
const char *CpuConfig::kYield = "yield";
#ifdef XMRIG_FEATURE_ASM
const char *CpuConfig::kAsm = "asm";
#endif
#ifdef XMRIG_ALGO_ARGON2
const char *CpuConfig::kArgon2Impl = "argon2-impl";
#endif
#ifdef XMRIG_ALGO_ASTROBWT
const char *CpuConfig::kAstroBWTMaxSize = "astrobwt-max-size";
const char *CpuConfig::kAstroBWTAVX2 = "astrobwt-avx2";
#endif
extern template class Threads<CpuThreads>;
}
bool xmrig::CpuConfig::isHwAES() const
{
return (m_aes == AES_AUTO ? (Cpu::info()->hasAES() ? AES_HW : AES_SOFT) : m_aes) == AES_HW;
}
rapidjson::Value xmrig::CpuConfig::toJSON(rapidjson::Document &doc) const
{
using namespace rapidjson;
auto &allocator = doc.GetAllocator();
Value obj(kObjectType);
obj.AddMember(StringRef(kEnabled), m_enabled, allocator);
obj.AddMember(StringRef(kHugePages), m_hugePageSize == 0 || m_hugePageSize == kDefaultHugePageSizeKb ? Value(isHugePages()) : Value(static_cast<uint32_t>(m_hugePageSize)), allocator);
obj.AddMember(StringRef(kHugePagesJit), m_hugePagesJit, allocator);
obj.AddMember(StringRef(kHwAes), m_aes == AES_AUTO ? Value(kNullType) : Value(m_aes == AES_HW), allocator);
obj.AddMember(StringRef(kPriority), priority() != -1 ? Value(priority()) : Value(kNullType), allocator);
obj.AddMember(StringRef(kMemoryPool), m_memoryPool < 1 ? Value(m_memoryPool < 0) : Value(m_memoryPool), allocator);
obj.AddMember(StringRef(kYield), m_yield, allocator);
if (m_threads.isEmpty()) {
obj.AddMember(StringRef(kMaxThreadsHint), m_limit, allocator);
}
# ifdef XMRIG_FEATURE_ASM
obj.AddMember(StringRef(kAsm), m_assembly.toJSON(), allocator);
# endif
# ifdef XMRIG_ALGO_ARGON2
obj.AddMember(StringRef(kArgon2Impl), m_argon2Impl.toJSON(), allocator);
# endif
# ifdef XMRIG_ALGO_ASTROBWT
obj.AddMember(StringRef(kAstroBWTMaxSize), m_astrobwtMaxSize, allocator);
obj.AddMember(StringRef(kAstroBWTAVX2), m_astrobwtAVX2, allocator);
# endif
m_threads.toJSON(obj, doc);
return obj;
}
size_t xmrig::CpuConfig::memPoolSize() const
{
return m_memoryPool < 0 ? std::max(Cpu::info()->threads(), Cpu::info()->L3() >> 21) : m_memoryPool;
}
std::vector<xmrig::CpuLaunchData> xmrig::CpuConfig::get(const Miner *miner, const Algorithm &algorithm) const
{
if (algorithm.family() == Algorithm::KAWPOW) {
return {};
}
std::vector<CpuLaunchData> out;
const auto &threads = m_threads.get(algorithm);
if (threads.isEmpty()) {
return out;
}
const size_t count = threads.count();
out.reserve(count);
for (const auto &thread : threads.data()) {
out.emplace_back(miner, algorithm, *this, thread, count);
}
return out;
}
void xmrig::CpuConfig::read(const rapidjson::Value &value)
{
if (value.IsObject()) {
m_enabled = Json::getBool(value, kEnabled, m_enabled);
m_hugePagesJit = Json::getBool(value, kHugePagesJit, m_hugePagesJit);
m_limit = Json::getUint(value, kMaxThreadsHint, m_limit);
m_yield = Json::getBool(value, kYield, m_yield);
setAesMode(Json::getValue(value, kHwAes));
setHugePages(Json::getValue(value, kHugePages));
setMemoryPool(Json::getValue(value, kMemoryPool));
setPriority(Json::getInt(value, kPriority, -1));
# ifdef XMRIG_FEATURE_ASM
m_assembly = Json::getValue(value, kAsm);
# endif
# ifdef XMRIG_ALGO_ARGON2
m_argon2Impl = Json::getString(value, kArgon2Impl);
# endif
# ifdef XMRIG_ALGO_ASTROBWT
const auto& astroBWTMaxSize = Json::getValue(value, kAstroBWTMaxSize);
if (astroBWTMaxSize.IsNull() || !astroBWTMaxSize.IsInt()) {
m_shouldSave = true;
}
else {
m_astrobwtMaxSize = std::min(std::max(astroBWTMaxSize.GetInt(), 400), 1200);
}
const auto& astroBWTAVX2 = Json::getValue(value, kAstroBWTAVX2);
if (astroBWTAVX2.IsNull() || !astroBWTAVX2.IsBool()) {
m_shouldSave = true;
}
else {
m_astrobwtAVX2 = astroBWTAVX2.GetBool();
}
# endif
m_threads.read(value);
generate();
}
else if (value.IsBool()) {
m_enabled = value.GetBool();
generate();
}
else {
generate();
}
}
void xmrig::CpuConfig::generate()
{
if (!isEnabled() || m_threads.has("*")) {
return;
}
size_t count = 0;
count += xmrig::generate<Algorithm::CN>(m_threads, m_limit);
count += xmrig::generate<Algorithm::CN_LITE>(m_threads, m_limit);
count += xmrig::generate<Algorithm::CN_HEAVY>(m_threads, m_limit);
count += xmrig::generate<Algorithm::CN_PICO>(m_threads, m_limit);
count += xmrig::generate<Algorithm::CN_FEMTO>(m_threads, m_limit);
count += xmrig::generate<Algorithm::RANDOM_X>(m_threads, m_limit);
count += xmrig::generate<Algorithm::ARGON2>(m_threads, m_limit);
count += xmrig::generate<Algorithm::ASTROBWT>(m_threads, m_limit);
m_shouldSave |= count > 0;
}
void xmrig::CpuConfig::setAesMode(const rapidjson::Value &value)
{
if (value.IsBool()) {
m_aes = value.GetBool() ? AES_HW : AES_SOFT;
}
else {
m_aes = AES_AUTO;
}
}
void xmrig::CpuConfig::setHugePages(const rapidjson::Value &value)
{
if (value.IsBool()) {
m_hugePageSize = value.GetBool() ? kDefaultHugePageSizeKb : 0U;
}
else if (value.IsUint()) {
const uint32_t size = value.GetUint();
m_hugePageSize = size < kOneGbPageSizeKb ? size : kDefaultHugePageSizeKb;
}
}
void xmrig::CpuConfig::setMemoryPool(const rapidjson::Value &value)
{
if (value.IsBool()) {
m_memoryPool = value.GetBool() ? -1 : 0;
}
else if (value.IsInt()) {
m_memoryPool = value.GetInt();
}
}
|
#pragma once
#include "Player.h"
class RandomPlayer : public Player {
public:
RandomPlayer() {
field = new Field();
}
~RandomPlayer() {
delete field;
}
void Update();
};
|
#ifndef NO_H
#define NO_H
#include "Adjacencia.h"
class No
{
public:
No(int id, int label, int dado);
~No();
void adicionarAdj(No* destino, int peso);
void removerAdj(No* destino, int peso);
void removerAdjs(No* destino);
bool verificarMultiaresta(int ordem);
bool verificarSelfLoop();
bool existeAdj(int destino);
int getId();
void setId(int id);
int getFrequencia();
void setFrequencia(int freq);
int getDado();
int getLabel();
No* getProx();
void setProx(No* no);
int getGrau();
int getGrauEntrada();
int getGrauSaida();
void addGrauEntrada(int i);
Adjacencia* getAdjRaiz();
protected:
private:
Adjacencia* adjRaiz;
Adjacencia* ultimaAdj;
int id;
int dado;
int label;
int frequencia;
No* prox;
//descritores:
int grau; //Será considerado como grau de saída em grafos direcionados
int grauEntrada; //para grafos direcionados
};
#endif // NO_H
|
#include <benchmark/benchmark.h>
#include <permutations.h>
#include <alphabet.h>
#include <cmap.h>
#include <cmath>
#include <cmap-bench.hpp>
namespace {
// Permutation benchmarks
static void BM_permute_next(benchmark::State &state) {
auto arr = new int[state.range(0)];
for (int i = 0; i < state.range(0); i++)
arr[i] = i;
permuter *p = new_permuter(arr, (int) state.range(0),
sizeof(int), (CompareFn) cmp_int);
for (auto _ : state) {
void *permutation = next_permutation(p);
benchmark::DoNotOptimize(permutation);
reset_permuter(p);
}
permuter_dispose(p);
delete[] arr;
}
BENCHMARK(BM_permute_next)->Arg(5);
static void BM_permutation(benchmark::State &state) {
auto arr = new int[state.range(0)];
for (int i = 0; i < state.range(0); i++)
arr[i] = i;
permuter *p = new_permuter(arr, (int) state.range(0),
sizeof(int), (CompareFn) cmp_int);
for (auto _ : state) {
void *permutation;
reset_permuter(p);
for_permutations(p, permutation) {
benchmark::DoNotOptimize(permutation);
benchmark::ClobberMemory();
}
}
permuter_dispose(p);
delete[] arr;
}
BENCHMARK(BM_permutation)->DenseRange(3, 5, 1);
static void BM_permuter_reset(benchmark::State &state) {
auto arr = new int[state.range(0)];
for (int i = 0; i < state.range(0); i++)
arr[i] = -i;
permuter *p = new_permuter(arr, (int) state.range(0),
sizeof(int), (CompareFn) cmp_int);
for (auto _ : state) {
memcmp(get_permutation(p), arr, sizeof(int) * state.range(0));
reset_permuter(p);
}
permuter_dispose(p);
delete[] arr;
}
BENCHMARK(BM_permuter_reset)->Arg(3);
}
BENCHMARK_MAIN();
|
/********************************************************************************
** Form generated from reading UI file 'newcameradialog.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_NEWCAMERADIALOG_H
#define UI_NEWCAMERADIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialog>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSlider>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
#include "QtQuickWidgets/QQuickWidget"
#include "masklabel.h"
QT_BEGIN_NAMESPACE
class Ui_NewCameraDialog
{
public:
QPushButton *ok_button;
QPushButton *cancel_button;
QTabWidget *tabWidget;
QWidget *tab;
QWidget *gridLayoutWidget_2;
QGridLayout *gridLayout_2;
QCheckBox *setMirror;
QSpacerItem *verticalSpacer_4;
QLabel *label;
QLabel *addr_error_msg;
QSpacerItem *verticalSpacer;
QLabel *label_rotar;
QComboBox *rotate_count;
QLabel *label_direccion;
QCheckBox *invertColors;
QHBoxLayout *horizontalLayout_5;
QLabel *label_camera_user;
QLineEdit *cameraUser;
QSpacerItem *horizontalSpacer_4;
QLabel *label_camera_password;
QLineEdit *cameraPassword;
QLabel *label_buscar;
QHBoxLayout *horizontalLayout_7;
QLabel *label_camera_ip;
QLineEdit *cameraIP;
QSpacerItem *horizontalSpacer_2;
QLabel *label_camera_port;
QLineEdit *cameraPort;
QHBoxLayout *horizontalLayout_8;
QLabel *label_fabricante;
QComboBox *fabricante;
QSpacerItem *horizontalSpacer_3;
QLabel *progress;
QPushButton *searchCameras;
QHBoxLayout *horizontalLayout_9;
QLineEdit *selectName;
QLabel *name_error_msg;
QHBoxLayout *horizontalLayout_4;
QLineEdit *selectAddress;
QPushButton *reloadPreview;
QPushButton *copyAddress;
QListWidget *resultslist;
QWidget *tab_5;
QWidget *gridLayoutWidget_6;
QGridLayout *gridLayout_6;
QLabel *label_12;
MaskLabel *cut_label;
QSpacerItem *verticalSpacer_9;
QWidget *tab_2;
QWidget *gridLayoutWidget_8;
QGridLayout *gridLayout_8;
QCheckBox *record;
QCheckBox *changeFPS;
QCheckBox *loop_recording;
QLabel *label_5;
QSpinBox *setThreshold;
QLabel *label_10;
QLabel *label_9;
QLabel *gigas;
QPushButton *openScheduler;
QSlider *selectGigas;
QSpinBox *setHistory;
QCheckBox *scheduler;
QSpacerItem *verticalSpacer_2;
QLabel *sensitivity;
QSlider *setSensitivity;
QCheckBox *mov_detection;
QLabel *label_6;
QCheckBox *use_mask;
QPushButton *setmask;
QWidget *tab_3;
QWidget *gridLayoutWidget;
QGridLayout *gridLayout;
QListWidget *smtpList;
QLabel *label_13;
QCheckBox *alerts;
QComboBox *selectAddon;
QLineEdit *selectInstance;
QLabel *label_3;
QSpacerItem *verticalSpacer_3;
QLabel *label_4;
QLineEdit *selectAlertsIP;
QLabel *label_14;
QLabel *label_24;
QVBoxLayout *verticalLayout_2;
QPushButton *addSMTP;
QPushButton *removeSMTP;
QSpacerItem *verticalSpacer_7;
QLabel *label_2;
QListWidget *tgList;
QVBoxLayout *verticalLayout_3;
QPushButton *addTG;
QPushButton *removeTG;
QSpacerItem *verticalSpacer_8;
QListWidget *alertFilter;
QWidget *tab_6;
QWidget *gridLayoutWidget_7;
QGridLayout *gridLayout_7;
QCheckBox *use_ptz;
QLabel *label_20;
QSpacerItem *verticalSpacer_10;
QSpacerItem *verticalSpacer_11;
QLabel *label_7;
QHBoxLayout *horizontalLayout_3;
QLabel *label_25;
QSlider *tourtime_slider;
QLabel *tourtime;
QPushButton *setTour;
QLabel *label_8;
QHBoxLayout *horizontalLayout_6;
QLabel *ptz_vel;
QLabel *timeout;
QSlider *ptz_vel_slider;
QLabel *label_30;
QLabel *label_31;
QSlider *timeout_slider;
QHBoxLayout *horizontalLayout;
QLabel *label_15;
QLineEdit *ptz_ip;
QLabel *label_16;
QSpinBox *ptz_port;
QLabel *label_11;
QHBoxLayout *horizontalLayout_2;
QLabel *label_17;
QLineEdit *ptz_user;
QLabel *label_18;
QLineEdit *ptz_password;
QWidget *tab_4;
QWidget *gridLayoutWidget_4;
QGridLayout *gridLayout_4;
QCheckBox *alertAccess;
QComboBox *selectAccessAlertPos;
QListWidget *terminalList;
QLabel *label_22;
QVBoxLayout *verticalLayout;
QPushButton *addTerminal;
QPushButton *removeTerminal;
QSpacerItem *verticalSpacer_6;
QLabel *label_23;
QSpacerItem *verticalSpacer_5;
QWidget *tab_map;
QWidget *gridLayoutWidget_3;
QGridLayout *gridLayout_3;
QQuickWidget *container;
QLabel *label_21;
MaskLabel *prev;
QWidget *gridLayoutWidget_5;
QGridLayout *gridLayout_5;
QLabel *label_28;
QLabel *label_26;
QLabel *prev_resolucion;
QLabel *prev_codec;
QLabel *label_27;
QLabel *prev_fps;
QLabel *label_29;
QLabel *prev_format;
void setupUi(QDialog *NewCameraDialog)
{
if (NewCameraDialog->objectName().isEmpty())
NewCameraDialog->setObjectName(QStringLiteral("NewCameraDialog"));
NewCameraDialog->resize(860, 510);
NewCameraDialog->setMinimumSize(QSize(860, 510));
NewCameraDialog->setMaximumSize(QSize(860, 510));
QFont font;
font.setFamily(QStringLiteral("Ubuntu"));
font.setPointSize(8);
NewCameraDialog->setFont(font);
ok_button = new QPushButton(NewCameraDialog);
ok_button->setObjectName(QStringLiteral("ok_button"));
ok_button->setGeometry(QRect(750, 456, 89, 25));
ok_button->setFont(font);
cancel_button = new QPushButton(NewCameraDialog);
cancel_button->setObjectName(QStringLiteral("cancel_button"));
cancel_button->setGeometry(QRect(650, 456, 89, 25));
cancel_button->setFont(font);
tabWidget = new QTabWidget(NewCameraDialog);
tabWidget->setObjectName(QStringLiteral("tabWidget"));
tabWidget->setEnabled(true);
tabWidget->setGeometry(QRect(10, 10, 511, 481));
QFont font1;
font1.setPointSize(8);
tabWidget->setFont(font1);
tab = new QWidget();
tab->setObjectName(QStringLiteral("tab"));
gridLayoutWidget_2 = new QWidget(tab);
gridLayoutWidget_2->setObjectName(QStringLiteral("gridLayoutWidget_2"));
gridLayoutWidget_2->setGeometry(QRect(20, 10, 480, 426));
QFont font2;
font2.setFamily(QStringLiteral("Ubuntu"));
gridLayoutWidget_2->setFont(font2);
gridLayout_2 = new QGridLayout(gridLayoutWidget_2);
gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
gridLayout_2->setContentsMargins(0, 0, 0, 0);
setMirror = new QCheckBox(gridLayoutWidget_2);
setMirror->setObjectName(QStringLiteral("setMirror"));
QFont font3;
font3.setPointSize(8);
font3.setBold(true);
font3.setWeight(75);
setMirror->setFont(font3);
gridLayout_2->addWidget(setMirror, 7, 0, 1, 1);
verticalSpacer_4 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_2->addItem(verticalSpacer_4, 17, 2, 1, 1);
label = new QLabel(gridLayoutWidget_2);
label->setObjectName(QStringLiteral("label"));
QFont font4;
font4.setFamily(QStringLiteral("Ubuntu"));
font4.setPointSize(8);
font4.setBold(true);
font4.setWeight(75);
label->setFont(font4);
gridLayout_2->addWidget(label, 1, 0, 1, 1);
addr_error_msg = new QLabel(gridLayoutWidget_2);
addr_error_msg->setObjectName(QStringLiteral("addr_error_msg"));
QFont font5;
font5.setPointSize(7);
addr_error_msg->setFont(font5);
gridLayout_2->addWidget(addr_error_msg, 6, 2, 1, 1);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_2->addItem(verticalSpacer, 15, 2, 1, 1);
label_rotar = new QLabel(gridLayoutWidget_2);
label_rotar->setObjectName(QStringLiteral("label_rotar"));
label_rotar->setFont(font3);
gridLayout_2->addWidget(label_rotar, 8, 0, 1, 1);
rotate_count = new QComboBox(gridLayoutWidget_2);
rotate_count->setObjectName(QStringLiteral("rotate_count"));
rotate_count->setMaximumSize(QSize(110, 16777215));
rotate_count->setFont(font1);
gridLayout_2->addWidget(rotate_count, 8, 2, 1, 1);
label_direccion = new QLabel(gridLayoutWidget_2);
label_direccion->setObjectName(QStringLiteral("label_direccion"));
label_direccion->setFont(font3);
gridLayout_2->addWidget(label_direccion, 4, 0, 1, 1);
invertColors = new QCheckBox(gridLayoutWidget_2);
invertColors->setObjectName(QStringLiteral("invertColors"));
invertColors->setFont(font3);
gridLayout_2->addWidget(invertColors, 9, 0, 1, 1);
horizontalLayout_5 = new QHBoxLayout();
horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5"));
label_camera_user = new QLabel(gridLayoutWidget_2);
label_camera_user->setObjectName(QStringLiteral("label_camera_user"));
label_camera_user->setMinimumSize(QSize(50, 0));
QFont font6;
font6.setPointSize(7);
font6.setBold(false);
font6.setWeight(50);
label_camera_user->setFont(font6);
horizontalLayout_5->addWidget(label_camera_user);
cameraUser = new QLineEdit(gridLayoutWidget_2);
cameraUser->setObjectName(QStringLiteral("cameraUser"));
cameraUser->setMinimumSize(QSize(110, 0));
cameraUser->setMaximumSize(QSize(110, 16777215));
cameraUser->setFont(font5);
horizontalLayout_5->addWidget(cameraUser);
horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_5->addItem(horizontalSpacer_4);
label_camera_password = new QLabel(gridLayoutWidget_2);
label_camera_password->setObjectName(QStringLiteral("label_camera_password"));
label_camera_password->setFont(font6);
horizontalLayout_5->addWidget(label_camera_password);
cameraPassword = new QLineEdit(gridLayoutWidget_2);
cameraPassword->setObjectName(QStringLiteral("cameraPassword"));
cameraPassword->setMinimumSize(QSize(110, 0));
cameraPassword->setMaximumSize(QSize(110, 16777215));
cameraPassword->setFont(font5);
horizontalLayout_5->addWidget(cameraPassword);
gridLayout_2->addLayout(horizontalLayout_5, 12, 2, 1, 1);
label_buscar = new QLabel(gridLayoutWidget_2);
label_buscar->setObjectName(QStringLiteral("label_buscar"));
label_buscar->setFont(font3);
gridLayout_2->addWidget(label_buscar, 10, 2, 1, 1);
horizontalLayout_7 = new QHBoxLayout();
horizontalLayout_7->setObjectName(QStringLiteral("horizontalLayout_7"));
label_camera_ip = new QLabel(gridLayoutWidget_2);
label_camera_ip->setObjectName(QStringLiteral("label_camera_ip"));
label_camera_ip->setMinimumSize(QSize(50, 0));
label_camera_ip->setMaximumSize(QSize(50, 16777215));
label_camera_ip->setFont(font6);
horizontalLayout_7->addWidget(label_camera_ip);
cameraIP = new QLineEdit(gridLayoutWidget_2);
cameraIP->setObjectName(QStringLiteral("cameraIP"));
cameraIP->setMinimumSize(QSize(110, 0));
cameraIP->setMaximumSize(QSize(110, 16777215));
cameraIP->setFont(font5);
horizontalLayout_7->addWidget(cameraIP);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_7->addItem(horizontalSpacer_2);
label_camera_port = new QLabel(gridLayoutWidget_2);
label_camera_port->setObjectName(QStringLiteral("label_camera_port"));
label_camera_port->setFont(font6);
horizontalLayout_7->addWidget(label_camera_port);
cameraPort = new QLineEdit(gridLayoutWidget_2);
cameraPort->setObjectName(QStringLiteral("cameraPort"));
cameraPort->setMinimumSize(QSize(110, 0));
cameraPort->setMaximumSize(QSize(110, 16777215));
cameraPort->setFont(font5);
horizontalLayout_7->addWidget(cameraPort);
gridLayout_2->addLayout(horizontalLayout_7, 11, 2, 1, 1);
horizontalLayout_8 = new QHBoxLayout();
horizontalLayout_8->setObjectName(QStringLiteral("horizontalLayout_8"));
label_fabricante = new QLabel(gridLayoutWidget_2);
label_fabricante->setObjectName(QStringLiteral("label_fabricante"));
label_fabricante->setMinimumSize(QSize(70, 0));
label_fabricante->setMaximumSize(QSize(70, 16777215));
label_fabricante->setFont(font6);
horizontalLayout_8->addWidget(label_fabricante);
fabricante = new QComboBox(gridLayoutWidget_2);
fabricante->setObjectName(QStringLiteral("fabricante"));
fabricante->setMinimumSize(QSize(120, 0));
fabricante->setMaximumSize(QSize(120, 16777215));
fabricante->setFont(font5);
horizontalLayout_8->addWidget(fabricante);
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_8->addItem(horizontalSpacer_3);
progress = new QLabel(gridLayoutWidget_2);
progress->setObjectName(QStringLiteral("progress"));
QFont font7;
font7.setPointSize(10);
progress->setFont(font7);
horizontalLayout_8->addWidget(progress);
searchCameras = new QPushButton(gridLayoutWidget_2);
searchCameras->setObjectName(QStringLiteral("searchCameras"));
searchCameras->setMinimumSize(QSize(30, 30));
searchCameras->setMaximumSize(QSize(30, 30));
searchCameras->setFont(font5);
QIcon icon;
icon.addFile(QStringLiteral(":/new/buttons/images/device_discover.jpg"), QSize(), QIcon::Normal, QIcon::Off);
searchCameras->setIcon(icon);
searchCameras->setFlat(true);
horizontalLayout_8->addWidget(searchCameras);
gridLayout_2->addLayout(horizontalLayout_8, 13, 2, 1, 1);
horizontalLayout_9 = new QHBoxLayout();
horizontalLayout_9->setObjectName(QStringLiteral("horizontalLayout_9"));
selectName = new QLineEdit(gridLayoutWidget_2);
selectName->setObjectName(QStringLiteral("selectName"));
selectName->setMinimumSize(QSize(150, 0));
selectName->setMaximumSize(QSize(150, 16777215));
selectName->setFont(font);
horizontalLayout_9->addWidget(selectName);
name_error_msg = new QLabel(gridLayoutWidget_2);
name_error_msg->setObjectName(QStringLiteral("name_error_msg"));
name_error_msg->setMinimumSize(QSize(100, 0));
name_error_msg->setFont(font5);
horizontalLayout_9->addWidget(name_error_msg);
gridLayout_2->addLayout(horizontalLayout_9, 1, 2, 1, 1);
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
selectAddress = new QLineEdit(gridLayoutWidget_2);
selectAddress->setObjectName(QStringLiteral("selectAddress"));
selectAddress->setMinimumSize(QSize(0, 0));
selectAddress->setMaximumSize(QSize(16777215, 16777215));
selectAddress->setFont(font1);
horizontalLayout_4->addWidget(selectAddress);
reloadPreview = new QPushButton(gridLayoutWidget_2);
reloadPreview->setObjectName(QStringLiteral("reloadPreview"));
reloadPreview->setMinimumSize(QSize(24, 24));
reloadPreview->setMaximumSize(QSize(24, 24));
reloadPreview->setFlat(true);
horizontalLayout_4->addWidget(reloadPreview);
copyAddress = new QPushButton(gridLayoutWidget_2);
copyAddress->setObjectName(QStringLiteral("copyAddress"));
copyAddress->setMinimumSize(QSize(24, 24));
copyAddress->setMaximumSize(QSize(24, 24));
copyAddress->setFlat(true);
horizontalLayout_4->addWidget(copyAddress);
gridLayout_2->addLayout(horizontalLayout_4, 4, 2, 1, 1);
resultslist = new QListWidget(gridLayoutWidget_2);
resultslist->setObjectName(QStringLiteral("resultslist"));
resultslist->setFont(font5);
gridLayout_2->addWidget(resultslist, 14, 2, 1, 1);
tabWidget->addTab(tab, QString());
tab_5 = new QWidget();
tab_5->setObjectName(QStringLiteral("tab_5"));
gridLayoutWidget_6 = new QWidget(tab_5);
gridLayoutWidget_6->setObjectName(QStringLiteral("gridLayoutWidget_6"));
gridLayoutWidget_6->setGeometry(QRect(10, 20, 351, 341));
gridLayout_6 = new QGridLayout(gridLayoutWidget_6);
gridLayout_6->setObjectName(QStringLiteral("gridLayout_6"));
gridLayout_6->setContentsMargins(0, 0, 0, 0);
label_12 = new QLabel(gridLayoutWidget_6);
label_12->setObjectName(QStringLiteral("label_12"));
label_12->setFont(font3);
gridLayout_6->addWidget(label_12, 0, 0, 1, 1);
cut_label = new MaskLabel(gridLayoutWidget_6);
cut_label->setObjectName(QStringLiteral("cut_label"));
cut_label->setMinimumSize(QSize(310, 200));
cut_label->setMaximumSize(QSize(310, 200));
gridLayout_6->addWidget(cut_label, 1, 0, 1, 1);
verticalSpacer_9 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_6->addItem(verticalSpacer_9, 2, 0, 1, 1);
tabWidget->addTab(tab_5, QString());
tab_2 = new QWidget();
tab_2->setObjectName(QStringLiteral("tab_2"));
gridLayoutWidget_8 = new QWidget(tab_2);
gridLayoutWidget_8->setObjectName(QStringLiteral("gridLayoutWidget_8"));
gridLayoutWidget_8->setGeometry(QRect(10, 20, 481, 352));
gridLayout_8 = new QGridLayout(gridLayoutWidget_8);
gridLayout_8->setObjectName(QStringLiteral("gridLayout_8"));
gridLayout_8->setContentsMargins(0, 0, 0, 0);
record = new QCheckBox(gridLayoutWidget_8);
record->setObjectName(QStringLiteral("record"));
record->setFont(font4);
gridLayout_8->addWidget(record, 0, 0, 1, 1);
changeFPS = new QCheckBox(gridLayoutWidget_8);
changeFPS->setObjectName(QStringLiteral("changeFPS"));
changeFPS->setFont(font4);
gridLayout_8->addWidget(changeFPS, 1, 0, 1, 1);
loop_recording = new QCheckBox(gridLayoutWidget_8);
loop_recording->setObjectName(QStringLiteral("loop_recording"));
loop_recording->setFont(font4);
gridLayout_8->addWidget(loop_recording, 2, 0, 1, 1);
label_5 = new QLabel(gridLayoutWidget_8);
label_5->setObjectName(QStringLiteral("label_5"));
label_5->setFont(font);
gridLayout_8->addWidget(label_5, 7, 1, 1, 1);
setThreshold = new QSpinBox(gridLayoutWidget_8);
setThreshold->setObjectName(QStringLiteral("setThreshold"));
setThreshold->setFont(font);
setThreshold->setValue(50);
gridLayout_8->addWidget(setThreshold, 8, 2, 1, 1);
label_10 = new QLabel(gridLayoutWidget_8);
label_10->setObjectName(QStringLiteral("label_10"));
label_10->setFont(font);
gridLayout_8->addWidget(label_10, 8, 1, 1, 1);
label_9 = new QLabel(gridLayoutWidget_8);
label_9->setObjectName(QStringLiteral("label_9"));
label_9->setFont(font);
gridLayout_8->addWidget(label_9, 9, 1, 1, 1);
gigas = new QLabel(gridLayoutWidget_8);
gigas->setObjectName(QStringLiteral("gigas"));
gigas->setMinimumSize(QSize(40, 0));
gigas->setMaximumSize(QSize(40, 16777215));
gigas->setFont(font);
gridLayout_8->addWidget(gigas, 2, 3, 1, 1);
openScheduler = new QPushButton(gridLayoutWidget_8);
openScheduler->setObjectName(QStringLiteral("openScheduler"));
openScheduler->setMaximumSize(QSize(120, 16777215));
openScheduler->setFont(font1);
gridLayout_8->addWidget(openScheduler, 3, 2, 1, 1);
selectGigas = new QSlider(gridLayoutWidget_8);
selectGigas->setObjectName(QStringLiteral("selectGigas"));
QFont font8;
font8.setFamily(QStringLiteral("Ubuntu"));
font8.setPointSize(9);
selectGigas->setFont(font8);
selectGigas->setOrientation(Qt::Horizontal);
gridLayout_8->addWidget(selectGigas, 2, 2, 1, 1);
setHistory = new QSpinBox(gridLayoutWidget_8);
setHistory->setObjectName(QStringLiteral("setHistory"));
setHistory->setFont(font);
setHistory->setValue(50);
gridLayout_8->addWidget(setHistory, 9, 2, 1, 1);
scheduler = new QCheckBox(gridLayoutWidget_8);
scheduler->setObjectName(QStringLiteral("scheduler"));
scheduler->setFont(font4);
gridLayout_8->addWidget(scheduler, 3, 0, 1, 1);
verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_8->addItem(verticalSpacer_2, 10, 1, 1, 1);
sensitivity = new QLabel(gridLayoutWidget_8);
sensitivity->setObjectName(QStringLiteral("sensitivity"));
sensitivity->setFont(font);
gridLayout_8->addWidget(sensitivity, 7, 3, 1, 1);
setSensitivity = new QSlider(gridLayoutWidget_8);
setSensitivity->setObjectName(QStringLiteral("setSensitivity"));
setSensitivity->setFont(font2);
setSensitivity->setOrientation(Qt::Horizontal);
gridLayout_8->addWidget(setSensitivity, 7, 2, 1, 1);
mov_detection = new QCheckBox(gridLayoutWidget_8);
mov_detection->setObjectName(QStringLiteral("mov_detection"));
mov_detection->setFont(font4);
gridLayout_8->addWidget(mov_detection, 4, 0, 1, 1);
label_6 = new QLabel(gridLayoutWidget_8);
label_6->setObjectName(QStringLiteral("label_6"));
label_6->setFont(font3);
gridLayout_8->addWidget(label_6, 5, 1, 1, 1);
use_mask = new QCheckBox(gridLayoutWidget_8);
use_mask->setObjectName(QStringLiteral("use_mask"));
use_mask->setFont(font1);
gridLayout_8->addWidget(use_mask, 6, 1, 1, 1);
setmask = new QPushButton(gridLayoutWidget_8);
setmask->setObjectName(QStringLiteral("setmask"));
setmask->setMaximumSize(QSize(120, 16777215));
setmask->setFont(font1);
gridLayout_8->addWidget(setmask, 6, 2, 1, 1);
tabWidget->addTab(tab_2, QString());
tab_3 = new QWidget();
tab_3->setObjectName(QStringLiteral("tab_3"));
gridLayoutWidget = new QWidget(tab_3);
gridLayoutWidget->setObjectName(QStringLiteral("gridLayoutWidget"));
gridLayoutWidget->setGeometry(QRect(20, 20, 481, 391));
gridLayout = new QGridLayout(gridLayoutWidget);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
gridLayout->setContentsMargins(0, 0, 0, 0);
smtpList = new QListWidget(gridLayoutWidget);
smtpList->setObjectName(QStringLiteral("smtpList"));
smtpList->setMaximumSize(QSize(16777215, 70));
smtpList->setFont(font);
gridLayout->addWidget(smtpList, 6, 1, 1, 1);
label_13 = new QLabel(gridLayoutWidget);
label_13->setObjectName(QStringLiteral("label_13"));
label_13->setFont(font);
gridLayout->addWidget(label_13, 2, 0, 1, 1);
alerts = new QCheckBox(gridLayoutWidget);
alerts->setObjectName(QStringLiteral("alerts"));
alerts->setFont(font4);
gridLayout->addWidget(alerts, 0, 0, 1, 2);
selectAddon = new QComboBox(gridLayoutWidget);
selectAddon->setObjectName(QStringLiteral("selectAddon"));
selectAddon->setFont(font);
gridLayout->addWidget(selectAddon, 3, 1, 1, 1);
selectInstance = new QLineEdit(gridLayoutWidget);
selectInstance->setObjectName(QStringLiteral("selectInstance"));
selectInstance->setFont(font);
gridLayout->addWidget(selectInstance, 1, 1, 1, 1);
label_3 = new QLabel(gridLayoutWidget);
label_3->setObjectName(QStringLiteral("label_3"));
label_3->setFont(font);
gridLayout->addWidget(label_3, 1, 0, 1, 1);
verticalSpacer_3 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout->addItem(verticalSpacer_3, 8, 1, 1, 1);
label_4 = new QLabel(gridLayoutWidget);
label_4->setObjectName(QStringLiteral("label_4"));
label_4->setFont(font4);
gridLayout->addWidget(label_4, 5, 0, 1, 1);
selectAlertsIP = new QLineEdit(gridLayoutWidget);
selectAlertsIP->setObjectName(QStringLiteral("selectAlertsIP"));
selectAlertsIP->setFont(font);
gridLayout->addWidget(selectAlertsIP, 2, 1, 1, 1);
label_14 = new QLabel(gridLayoutWidget);
label_14->setObjectName(QStringLiteral("label_14"));
label_14->setFont(font);
gridLayout->addWidget(label_14, 3, 0, 1, 1);
label_24 = new QLabel(gridLayoutWidget);
label_24->setObjectName(QStringLiteral("label_24"));
label_24->setFont(font);
label_24->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);
gridLayout->addWidget(label_24, 6, 0, 1, 1);
verticalLayout_2 = new QVBoxLayout();
verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
addSMTP = new QPushButton(gridLayoutWidget);
addSMTP->setObjectName(QStringLiteral("addSMTP"));
addSMTP->setMinimumSize(QSize(24, 24));
addSMTP->setMaximumSize(QSize(24, 24));
QIcon icon1;
icon1.addFile(QStringLiteral("../images/icon/ptz_zoomin.png"), QSize(), QIcon::Normal, QIcon::Off);
addSMTP->setIcon(icon1);
addSMTP->setFlat(true);
verticalLayout_2->addWidget(addSMTP);
removeSMTP = new QPushButton(gridLayoutWidget);
removeSMTP->setObjectName(QStringLiteral("removeSMTP"));
removeSMTP->setMinimumSize(QSize(24, 24));
removeSMTP->setMaximumSize(QSize(24, 24));
QIcon icon2;
icon2.addFile(QStringLiteral("../images/icon/ptz_zoomout.png"), QSize(), QIcon::Normal, QIcon::Off);
removeSMTP->setIcon(icon2);
removeSMTP->setFlat(true);
verticalLayout_2->addWidget(removeSMTP);
verticalSpacer_7 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_2->addItem(verticalSpacer_7);
gridLayout->addLayout(verticalLayout_2, 6, 2, 1, 1);
label_2 = new QLabel(gridLayoutWidget);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setFont(font);
label_2->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);
gridLayout->addWidget(label_2, 7, 0, 1, 1);
tgList = new QListWidget(gridLayoutWidget);
tgList->setObjectName(QStringLiteral("tgList"));
tgList->setMaximumSize(QSize(16777215, 70));
tgList->setFont(font);
gridLayout->addWidget(tgList, 7, 1, 1, 1);
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
addTG = new QPushButton(gridLayoutWidget);
addTG->setObjectName(QStringLiteral("addTG"));
addTG->setMinimumSize(QSize(24, 24));
addTG->setMaximumSize(QSize(24, 24));
addTG->setIcon(icon1);
addTG->setFlat(true);
verticalLayout_3->addWidget(addTG);
removeTG = new QPushButton(gridLayoutWidget);
removeTG->setObjectName(QStringLiteral("removeTG"));
removeTG->setMinimumSize(QSize(24, 24));
removeTG->setMaximumSize(QSize(24, 24));
removeTG->setIcon(icon2);
removeTG->setFlat(true);
verticalLayout_3->addWidget(removeTG);
verticalSpacer_8 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_3->addItem(verticalSpacer_8);
gridLayout->addLayout(verticalLayout_3, 7, 2, 1, 1);
alertFilter = new QListWidget(gridLayoutWidget);
alertFilter->setObjectName(QStringLiteral("alertFilter"));
alertFilter->setMaximumSize(QSize(16777215, 70));
gridLayout->addWidget(alertFilter, 4, 1, 1, 1);
tabWidget->addTab(tab_3, QString());
tab_6 = new QWidget();
tab_6->setObjectName(QStringLiteral("tab_6"));
gridLayoutWidget_7 = new QWidget(tab_6);
gridLayoutWidget_7->setObjectName(QStringLiteral("gridLayoutWidget_7"));
gridLayoutWidget_7->setGeometry(QRect(20, 20, 471, 418));
gridLayout_7 = new QGridLayout(gridLayoutWidget_7);
gridLayout_7->setObjectName(QStringLiteral("gridLayout_7"));
gridLayout_7->setContentsMargins(0, 0, 0, 0);
use_ptz = new QCheckBox(gridLayoutWidget_7);
use_ptz->setObjectName(QStringLiteral("use_ptz"));
use_ptz->setFont(font3);
gridLayout_7->addWidget(use_ptz, 0, 0, 1, 1);
label_20 = new QLabel(gridLayoutWidget_7);
label_20->setObjectName(QStringLiteral("label_20"));
label_20->setFont(font3);
gridLayout_7->addWidget(label_20, 7, 0, 1, 1);
verticalSpacer_10 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_7->addItem(verticalSpacer_10, 13, 0, 1, 1);
verticalSpacer_11 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_7->addItem(verticalSpacer_11, 6, 0, 1, 1);
label_7 = new QLabel(gridLayoutWidget_7);
label_7->setObjectName(QStringLiteral("label_7"));
QFont font9;
font9.setPointSize(8);
font9.setBold(false);
font9.setWeight(50);
label_7->setFont(font9);
gridLayout_7->addWidget(label_7, 10, 0, 1, 1);
horizontalLayout_3 = new QHBoxLayout();
horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3"));
gridLayout_7->addLayout(horizontalLayout_3, 14, 0, 1, 1);
label_25 = new QLabel(gridLayoutWidget_7);
label_25->setObjectName(QStringLiteral("label_25"));
QFont font10;
font10.setBold(true);
font10.setWeight(75);
label_25->setFont(font10);
gridLayout_7->addWidget(label_25, 2, 0, 1, 1);
tourtime_slider = new QSlider(gridLayoutWidget_7);
tourtime_slider->setObjectName(QStringLiteral("tourtime_slider"));
tourtime_slider->setFont(font1);
tourtime_slider->setOrientation(Qt::Horizontal);
gridLayout_7->addWidget(tourtime_slider, 11, 2, 1, 1);
tourtime = new QLabel(gridLayoutWidget_7);
tourtime->setObjectName(QStringLiteral("tourtime"));
tourtime->setFont(font1);
gridLayout_7->addWidget(tourtime, 11, 1, 1, 1);
setTour = new QPushButton(gridLayoutWidget_7);
setTour->setObjectName(QStringLiteral("setTour"));
setTour->setMaximumSize(QSize(120, 16777215));
setTour->setFont(font1);
gridLayout_7->addWidget(setTour, 10, 2, 1, 1);
label_8 = new QLabel(gridLayoutWidget_7);
label_8->setObjectName(QStringLiteral("label_8"));
gridLayout_7->addWidget(label_8, 11, 0, 1, 1);
horizontalLayout_6 = new QHBoxLayout();
horizontalLayout_6->setObjectName(QStringLiteral("horizontalLayout_6"));
gridLayout_7->addLayout(horizontalLayout_6, 15, 0, 1, 1);
ptz_vel = new QLabel(gridLayoutWidget_7);
ptz_vel->setObjectName(QStringLiteral("ptz_vel"));
ptz_vel->setFont(font1);
gridLayout_7->addWidget(ptz_vel, 8, 1, 1, 1);
timeout = new QLabel(gridLayoutWidget_7);
timeout->setObjectName(QStringLiteral("timeout"));
timeout->setFont(font1);
gridLayout_7->addWidget(timeout, 9, 1, 1, 1);
ptz_vel_slider = new QSlider(gridLayoutWidget_7);
ptz_vel_slider->setObjectName(QStringLiteral("ptz_vel_slider"));
ptz_vel_slider->setFont(font1);
ptz_vel_slider->setOrientation(Qt::Horizontal);
gridLayout_7->addWidget(ptz_vel_slider, 8, 2, 1, 1);
label_30 = new QLabel(gridLayoutWidget_7);
label_30->setObjectName(QStringLiteral("label_30"));
label_30->setFont(font1);
gridLayout_7->addWidget(label_30, 8, 0, 1, 1);
label_31 = new QLabel(gridLayoutWidget_7);
label_31->setObjectName(QStringLiteral("label_31"));
label_31->setFont(font1);
gridLayout_7->addWidget(label_31, 9, 0, 1, 1);
timeout_slider = new QSlider(gridLayoutWidget_7);
timeout_slider->setObjectName(QStringLiteral("timeout_slider"));
timeout_slider->setFont(font1);
timeout_slider->setOrientation(Qt::Horizontal);
gridLayout_7->addWidget(timeout_slider, 9, 2, 1, 1);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
label_15 = new QLabel(gridLayoutWidget_7);
label_15->setObjectName(QStringLiteral("label_15"));
label_15->setMinimumSize(QSize(50, 0));
label_15->setFont(font1);
horizontalLayout->addWidget(label_15);
ptz_ip = new QLineEdit(gridLayoutWidget_7);
ptz_ip->setObjectName(QStringLiteral("ptz_ip"));
ptz_ip->setMinimumSize(QSize(75, 0));
ptz_ip->setMaximumSize(QSize(75, 16777215));
ptz_ip->setFont(font1);
horizontalLayout->addWidget(ptz_ip);
label_16 = new QLabel(gridLayoutWidget_7);
label_16->setObjectName(QStringLiteral("label_16"));
label_16->setMinimumSize(QSize(50, 0));
label_16->setFont(font1);
horizontalLayout->addWidget(label_16);
ptz_port = new QSpinBox(gridLayoutWidget_7);
ptz_port->setObjectName(QStringLiteral("ptz_port"));
ptz_port->setMinimumSize(QSize(75, 0));
ptz_port->setMaximumSize(QSize(75, 16777215));
ptz_port->setFont(font1);
horizontalLayout->addWidget(ptz_port);
gridLayout_7->addLayout(horizontalLayout, 1, 2, 1, 1);
label_11 = new QLabel(gridLayoutWidget_7);
label_11->setObjectName(QStringLiteral("label_11"));
label_11->setFont(font10);
gridLayout_7->addWidget(label_11, 1, 0, 1, 1);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
label_17 = new QLabel(gridLayoutWidget_7);
label_17->setObjectName(QStringLiteral("label_17"));
label_17->setMinimumSize(QSize(50, 0));
label_17->setFont(font1);
horizontalLayout_2->addWidget(label_17);
ptz_user = new QLineEdit(gridLayoutWidget_7);
ptz_user->setObjectName(QStringLiteral("ptz_user"));
ptz_user->setMinimumSize(QSize(75, 0));
ptz_user->setMaximumSize(QSize(75, 16777215));
ptz_user->setFont(font1);
horizontalLayout_2->addWidget(ptz_user);
label_18 = new QLabel(gridLayoutWidget_7);
label_18->setObjectName(QStringLiteral("label_18"));
label_18->setMinimumSize(QSize(50, 0));
label_18->setFont(font1);
horizontalLayout_2->addWidget(label_18);
ptz_password = new QLineEdit(gridLayoutWidget_7);
ptz_password->setObjectName(QStringLiteral("ptz_password"));
ptz_password->setMinimumSize(QSize(75, 0));
ptz_password->setMaximumSize(QSize(75, 16777215));
ptz_password->setFont(font1);
ptz_password->setEchoMode(QLineEdit::Password);
horizontalLayout_2->addWidget(ptz_password);
gridLayout_7->addLayout(horizontalLayout_2, 2, 2, 1, 1);
tabWidget->addTab(tab_6, QString());
tab_4 = new QWidget();
tab_4->setObjectName(QStringLiteral("tab_4"));
gridLayoutWidget_4 = new QWidget(tab_4);
gridLayoutWidget_4->setObjectName(QStringLiteral("gridLayoutWidget_4"));
gridLayoutWidget_4->setGeometry(QRect(20, 20, 481, 261));
gridLayout_4 = new QGridLayout(gridLayoutWidget_4);
gridLayout_4->setObjectName(QStringLiteral("gridLayout_4"));
gridLayout_4->setContentsMargins(0, 0, 0, 0);
alertAccess = new QCheckBox(gridLayoutWidget_4);
alertAccess->setObjectName(QStringLiteral("alertAccess"));
alertAccess->setEnabled(false);
alertAccess->setFont(font3);
gridLayout_4->addWidget(alertAccess, 0, 0, 1, 1);
selectAccessAlertPos = new QComboBox(gridLayoutWidget_4);
selectAccessAlertPos->setObjectName(QStringLiteral("selectAccessAlertPos"));
selectAccessAlertPos->setEnabled(false);
selectAccessAlertPos->setFont(font1);
gridLayout_4->addWidget(selectAccessAlertPos, 2, 1, 1, 1);
terminalList = new QListWidget(gridLayoutWidget_4);
terminalList->setObjectName(QStringLiteral("terminalList"));
terminalList->setEnabled(false);
terminalList->setMaximumSize(QSize(16777215, 100));
terminalList->setFont(font1);
gridLayout_4->addWidget(terminalList, 1, 1, 1, 1);
label_22 = new QLabel(gridLayoutWidget_4);
label_22->setObjectName(QStringLiteral("label_22"));
label_22->setEnabled(false);
label_22->setFont(font3);
label_22->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);
gridLayout_4->addWidget(label_22, 1, 0, 1, 1);
verticalLayout = new QVBoxLayout();
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
addTerminal = new QPushButton(gridLayoutWidget_4);
addTerminal->setObjectName(QStringLiteral("addTerminal"));
addTerminal->setEnabled(false);
addTerminal->setMinimumSize(QSize(24, 24));
addTerminal->setMaximumSize(QSize(24, 24));
addTerminal->setFont(font1);
QIcon icon3;
icon3.addFile(QStringLiteral(":/new/buttons/images/add_grey.jpg"), QSize(), QIcon::Normal, QIcon::Off);
addTerminal->setIcon(icon3);
verticalLayout->addWidget(addTerminal);
removeTerminal = new QPushButton(gridLayoutWidget_4);
removeTerminal->setObjectName(QStringLiteral("removeTerminal"));
removeTerminal->setEnabled(false);
removeTerminal->setMinimumSize(QSize(24, 24));
removeTerminal->setMaximumSize(QSize(24, 24));
removeTerminal->setFont(font1);
QIcon icon4;
icon4.addFile(QStringLiteral(":/new/buttons/images/remove_grey.jpg"), QSize(), QIcon::Normal, QIcon::Off);
removeTerminal->setIcon(icon4);
verticalLayout->addWidget(removeTerminal);
verticalSpacer_6 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer_6);
gridLayout_4->addLayout(verticalLayout, 1, 2, 1, 1);
label_23 = new QLabel(gridLayoutWidget_4);
label_23->setObjectName(QStringLiteral("label_23"));
label_23->setEnabled(false);
label_23->setFont(font3);
gridLayout_4->addWidget(label_23, 2, 0, 1, 1);
verticalSpacer_5 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_4->addItem(verticalSpacer_5, 3, 0, 1, 1);
tabWidget->addTab(tab_4, QString());
tab_map = new QWidget();
tab_map->setObjectName(QStringLiteral("tab_map"));
gridLayoutWidget_3 = new QWidget(tab_map);
gridLayoutWidget_3->setObjectName(QStringLiteral("gridLayoutWidget_3"));
gridLayoutWidget_3->setGeometry(QRect(10, 30, 491, 411));
gridLayout_3 = new QGridLayout(gridLayoutWidget_3);
gridLayout_3->setObjectName(QStringLiteral("gridLayout_3"));
gridLayout_3->setContentsMargins(0, 0, 0, 0);
container = new QQuickWidget(gridLayoutWidget_3);
container->setObjectName(QStringLiteral("container"));
container->setResizeMode(QQuickWidget::SizeRootObjectToView);
gridLayout_3->addWidget(container, 0, 0, 1, 1);
tabWidget->addTab(tab_map, QString());
label_21 = new QLabel(NewCameraDialog);
label_21->setObjectName(QStringLiteral("label_21"));
label_21->setGeometry(QRect(540, 17, 111, 17));
label_21->setFont(font1);
prev = new MaskLabel(NewCameraDialog);
prev->setObjectName(QStringLiteral("prev"));
prev->setGeometry(QRect(540, 40, 310, 200));
prev->setMinimumSize(QSize(310, 200));
prev->setMaximumSize(QSize(310, 200));
gridLayoutWidget_5 = new QWidget(NewCameraDialog);
gridLayoutWidget_5->setObjectName(QStringLiteral("gridLayoutWidget_5"));
gridLayoutWidget_5->setGeometry(QRect(540, 242, 131, 72));
gridLayoutWidget_5->setFont(font5);
gridLayout_5 = new QGridLayout(gridLayoutWidget_5);
gridLayout_5->setObjectName(QStringLiteral("gridLayout_5"));
gridLayout_5->setContentsMargins(0, 0, 0, 0);
label_28 = new QLabel(gridLayoutWidget_5);
label_28->setObjectName(QStringLiteral("label_28"));
QFont font11;
font11.setFamily(QStringLiteral("Ubuntu"));
font11.setPointSize(7);
label_28->setFont(font11);
gridLayout_5->addWidget(label_28, 2, 0, 1, 1);
label_26 = new QLabel(gridLayoutWidget_5);
label_26->setObjectName(QStringLiteral("label_26"));
label_26->setFont(font11);
gridLayout_5->addWidget(label_26, 0, 0, 1, 1);
prev_resolucion = new QLabel(gridLayoutWidget_5);
prev_resolucion->setObjectName(QStringLiteral("prev_resolucion"));
prev_resolucion->setFont(font11);
gridLayout_5->addWidget(prev_resolucion, 0, 1, 1, 1);
prev_codec = new QLabel(gridLayoutWidget_5);
prev_codec->setObjectName(QStringLiteral("prev_codec"));
prev_codec->setFont(font11);
gridLayout_5->addWidget(prev_codec, 2, 1, 1, 1);
label_27 = new QLabel(gridLayoutWidget_5);
label_27->setObjectName(QStringLiteral("label_27"));
label_27->setFont(font11);
gridLayout_5->addWidget(label_27, 1, 0, 1, 1);
prev_fps = new QLabel(gridLayoutWidget_5);
prev_fps->setObjectName(QStringLiteral("prev_fps"));
prev_fps->setFont(font11);
gridLayout_5->addWidget(prev_fps, 1, 1, 1, 1);
label_29 = new QLabel(gridLayoutWidget_5);
label_29->setObjectName(QStringLiteral("label_29"));
label_29->setFont(font11);
gridLayout_5->addWidget(label_29, 3, 0, 1, 1);
prev_format = new QLabel(gridLayoutWidget_5);
prev_format->setObjectName(QStringLiteral("prev_format"));
prev_format->setFont(font11);
gridLayout_5->addWidget(prev_format, 3, 1, 1, 1);
QWidget::setTabOrder(tabWidget, setMirror);
QWidget::setTabOrder(setMirror, rotate_count);
QWidget::setTabOrder(rotate_count, invertColors);
QWidget::setTabOrder(invertColors, cameraIP);
QWidget::setTabOrder(cameraIP, cameraPort);
QWidget::setTabOrder(cameraPort, cameraUser);
QWidget::setTabOrder(cameraUser, cameraPassword);
QWidget::setTabOrder(cameraPassword, fabricante);
QWidget::setTabOrder(fabricante, searchCameras);
QWidget::setTabOrder(searchCameras, alerts);
QWidget::setTabOrder(alerts, selectInstance);
QWidget::setTabOrder(selectInstance, selectAlertsIP);
QWidget::setTabOrder(selectAlertsIP, selectAddon);
QWidget::setTabOrder(selectAddon, smtpList);
QWidget::setTabOrder(smtpList, addSMTP);
QWidget::setTabOrder(addSMTP, removeSMTP);
QWidget::setTabOrder(removeSMTP, tgList);
QWidget::setTabOrder(tgList, addTG);
QWidget::setTabOrder(addTG, removeTG);
QWidget::setTabOrder(removeTG, use_ptz);
QWidget::setTabOrder(use_ptz, alertAccess);
QWidget::setTabOrder(alertAccess, terminalList);
QWidget::setTabOrder(terminalList, addTerminal);
QWidget::setTabOrder(addTerminal, removeTerminal);
QWidget::setTabOrder(removeTerminal, selectAccessAlertPos);
QWidget::setTabOrder(selectAccessAlertPos, cancel_button);
QWidget::setTabOrder(cancel_button, ok_button);
retranslateUi(NewCameraDialog);
tabWidget->setCurrentIndex(6);
QMetaObject::connectSlotsByName(NewCameraDialog);
} // setupUi
void retranslateUi(QDialog *NewCameraDialog)
{
NewCameraDialog->setWindowTitle(QApplication::translate("NewCameraDialog", "Nueva C\303\241mara", Q_NULLPTR));
ok_button->setText(QApplication::translate("NewCameraDialog", "Aceptar", Q_NULLPTR));
cancel_button->setText(QApplication::translate("NewCameraDialog", "Cancelar", Q_NULLPTR));
setMirror->setText(QApplication::translate("NewCameraDialog", "Espejar", Q_NULLPTR));
label->setText(QApplication::translate("NewCameraDialog", "Nombre", Q_NULLPTR));
addr_error_msg->setText(QString());
label_rotar->setText(QApplication::translate("NewCameraDialog", "Rotar", Q_NULLPTR));
rotate_count->clear();
rotate_count->insertItems(0, QStringList()
<< QApplication::translate("NewCameraDialog", "No rotate", Q_NULLPTR)
<< QApplication::translate("NewCameraDialog", "90\302\272 right", Q_NULLPTR)
<< QApplication::translate("NewCameraDialog", "180\302\272", Q_NULLPTR)
<< QApplication::translate("NewCameraDialog", "90\302\272 left", Q_NULLPTR)
);
label_direccion->setText(QApplication::translate("NewCameraDialog", "Direcci\303\263n", Q_NULLPTR));
invertColors->setText(QApplication::translate("NewCameraDialog", "Invertir colores", Q_NULLPTR));
label_camera_user->setText(QApplication::translate("NewCameraDialog", "Usuario", Q_NULLPTR));
label_camera_password->setText(QApplication::translate("NewCameraDialog", "Password", Q_NULLPTR));
label_buscar->setText(QApplication::translate("NewCameraDialog", "Buscar", Q_NULLPTR));
label_camera_ip->setText(QApplication::translate("NewCameraDialog", "IP", Q_NULLPTR));
label_camera_port->setText(QApplication::translate("NewCameraDialog", "Puerto", Q_NULLPTR));
label_fabricante->setText(QApplication::translate("NewCameraDialog", "Fabricante", Q_NULLPTR));
fabricante->clear();
fabricante->insertItems(0, QStringList()
<< QApplication::translate("NewCameraDialog", "Desconocido", Q_NULLPTR)
);
progress->setText(QString());
#ifndef QT_NO_TOOLTIP
searchCameras->setToolTip(QApplication::translate("NewCameraDialog", "<html><head/><body><p>Buscar c\303\241maras</p></body></html>", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
searchCameras->setText(QString());
selectName->setText(QString());
name_error_msg->setText(QString());
selectAddress->setText(QString());
#ifndef QT_NO_TOOLTIP
reloadPreview->setToolTip(QApplication::translate("NewCameraDialog", "<html><head/><body><p>Recargar vista previa</p></body></html>", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
reloadPreview->setText(QString());
#ifndef QT_NO_TOOLTIP
copyAddress->setToolTip(QApplication::translate("NewCameraDialog", "<html><head/><body><p>Copiar direcci\303\263n</p></body></html>", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
copyAddress->setText(QString());
tabWidget->setTabText(tabWidget->indexOf(tab), QApplication::translate("NewCameraDialog", "Generales", Q_NULLPTR));
label_12->setText(QApplication::translate("NewCameraDialog", "Recorte de subcamara", Q_NULLPTR));
cut_label->setText(QString());
tabWidget->setTabText(tabWidget->indexOf(tab_5), QApplication::translate("NewCameraDialog", "Recorte", Q_NULLPTR));
record->setText(QApplication::translate("NewCameraDialog", "Grabar", Q_NULLPTR));
changeFPS->setText(QApplication::translate("NewCameraDialog", "Disminuir FPS", Q_NULLPTR));
loop_recording->setText(QApplication::translate("NewCameraDialog", "Grabar en ciclos", Q_NULLPTR));
label_5->setText(QApplication::translate("NewCameraDialog", "Sensibilidad", Q_NULLPTR));
label_10->setText(QApplication::translate("NewCameraDialog", "Umbral", Q_NULLPTR));
label_9->setText(QApplication::translate("NewCameraDialog", "Fotogramas", Q_NULLPTR));
gigas->setText(QApplication::translate("NewCameraDialog", "Gb", Q_NULLPTR));
openScheduler->setText(QApplication::translate("NewCameraDialog", "Definir programa", Q_NULLPTR));
scheduler->setText(QApplication::translate("NewCameraDialog", "Programado", Q_NULLPTR));
sensitivity->setText(QApplication::translate("NewCameraDialog", "0", Q_NULLPTR));
mov_detection->setText(QApplication::translate("NewCameraDialog", "Detectar movimiento", Q_NULLPTR));
label_6->setText(QApplication::translate("NewCameraDialog", "Avanzado", Q_NULLPTR));
use_mask->setText(QApplication::translate("NewCameraDialog", "Usar mascara", Q_NULLPTR));
setmask->setText(QApplication::translate("NewCameraDialog", "Definir m\303\241scara", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(tab_2), QApplication::translate("NewCameraDialog", "Grabaci\303\263n local", Q_NULLPTR));
label_13->setText(QApplication::translate("NewCameraDialog", "IP", Q_NULLPTR));
alerts->setText(QApplication::translate("NewCameraDialog", "Recibir alertas", Q_NULLPTR));
selectInstance->setText(QApplication::translate("NewCameraDialog", "0", Q_NULLPTR));
label_3->setText(QApplication::translate("NewCameraDialog", "Nombre de instancia", Q_NULLPTR));
label_4->setText(QApplication::translate("NewCameraDialog", "Enviar alertas", Q_NULLPTR));
selectAlertsIP->setText(QString());
label_14->setText(QApplication::translate("NewCameraDialog", "Producto", Q_NULLPTR));
label_24->setText(QApplication::translate("NewCameraDialog", "SMTP", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
addSMTP->setToolTip(QApplication::translate("NewCameraDialog", "<html><head/><body><p>Nuevo email de destino</p></body></html>", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
addSMTP->setText(QString());
#ifndef QT_NO_TOOLTIP
removeSMTP->setToolTip(QApplication::translate("NewCameraDialog", "<html><head/><body><p>Nuevo email de destino</p></body></html>", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
removeSMTP->setText(QString());
label_2->setText(QApplication::translate("NewCameraDialog", "Telegram", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
addTG->setToolTip(QApplication::translate("NewCameraDialog", "<html><head/><body><p>Nuevo email de destino</p></body></html>", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
addTG->setText(QString());
#ifndef QT_NO_TOOLTIP
removeTG->setToolTip(QApplication::translate("NewCameraDialog", "<html><head/><body><p>Nuevo email de destino</p></body></html>", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
removeTG->setText(QString());
tabWidget->setTabText(tabWidget->indexOf(tab_3), QApplication::translate("NewCameraDialog", "Alertas", Q_NULLPTR));
use_ptz->setText(QApplication::translate("NewCameraDialog", "Activar Ptz (ONVIF)", Q_NULLPTR));
label_20->setText(QApplication::translate("NewCameraDialog", "Avanzado", Q_NULLPTR));
label_7->setText(QApplication::translate("NewCameraDialog", "Tour", Q_NULLPTR));
label_25->setText(QApplication::translate("NewCameraDialog", "Autenticaci\303\263n", Q_NULLPTR));
tourtime->setText(QString());
setTour->setText(QApplication::translate("NewCameraDialog", "Definir recorrido", Q_NULLPTR));
label_8->setText(QApplication::translate("NewCameraDialog", "Tiempo de permanencia", Q_NULLPTR));
ptz_vel->setText(QString());
timeout->setText(QString());
label_30->setText(QApplication::translate("NewCameraDialog", "Velocidad", Q_NULLPTR));
label_31->setText(QApplication::translate("NewCameraDialog", "Tiempo de movimiento", Q_NULLPTR));
label_15->setText(QApplication::translate("NewCameraDialog", "IP", Q_NULLPTR));
label_16->setText(QApplication::translate("NewCameraDialog", "Puerto", Q_NULLPTR));
label_11->setText(QApplication::translate("NewCameraDialog", "Conexi\303\263n", Q_NULLPTR));
label_17->setText(QApplication::translate("NewCameraDialog", "Usuario", Q_NULLPTR));
label_18->setText(QApplication::translate("NewCameraDialog", "Password", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(tab_6), QApplication::translate("NewCameraDialog", "PTZ", Q_NULLPTR));
alertAccess->setText(QApplication::translate("NewCameraDialog", "Habilitar control de accesos", Q_NULLPTR));
selectAccessAlertPos->clear();
selectAccessAlertPos->insertItems(0, QStringList()
<< QApplication::translate("NewCameraDialog", "Superior izquierda", Q_NULLPTR)
<< QApplication::translate("NewCameraDialog", "Superior derecha", Q_NULLPTR)
<< QApplication::translate("NewCameraDialog", "Centro", Q_NULLPTR)
<< QApplication::translate("NewCameraDialog", "Inferior izquierda", Q_NULLPTR)
<< QApplication::translate("NewCameraDialog", "Inferior derecha", Q_NULLPTR)
);
label_22->setText(QApplication::translate("NewCameraDialog", "C\303\263digos de terminales", Q_NULLPTR));
addTerminal->setText(QString());
removeTerminal->setText(QString());
label_23->setText(QApplication::translate("NewCameraDialog", "Posici\303\263n de la alerta", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(tab_4), QApplication::translate("NewCameraDialog", "Accesos", Q_NULLPTR));
tabWidget->setTabText(tabWidget->indexOf(tab_map), QApplication::translate("NewCameraDialog", "Ubicaci\303\263n", Q_NULLPTR));
label_21->setText(QApplication::translate("NewCameraDialog", "Previsualizar", Q_NULLPTR));
prev->setText(QString());
label_28->setText(QApplication::translate("NewCameraDialog", "Codec:", Q_NULLPTR));
label_26->setText(QApplication::translate("NewCameraDialog", "Resoluci\303\263n:", Q_NULLPTR));
prev_resolucion->setText(QString());
prev_codec->setText(QString());
label_27->setText(QApplication::translate("NewCameraDialog", "FPS:", Q_NULLPTR));
prev_fps->setText(QString());
label_29->setText(QApplication::translate("NewCameraDialog", "Format:", Q_NULLPTR));
prev_format->setText(QString());
} // retranslateUi
};
namespace Ui {
class NewCameraDialog: public Ui_NewCameraDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_NEWCAMERADIALOG_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 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 DATABASE_STORAGE_SUPPORT
#include "modules/database/opdatabase.h"
#include "modules/dom/src/storage/sqlresult.h"
#include "modules/dom/src/storage/storageutils.h"
#include "modules/dom/src/domglobaldata.h"
static OP_STATUS
SqlValueToESValue(const SqlValue* sql_value, ES_Value *value, ES_ValueString *string_w_len_holder)
{
OP_ASSERT(sql_value != NULL);
switch(sql_value->Type())
{
case SqlValue::TYPE_STRING:
DOM_Object::DOMSetStringWithLength(value,string_w_len_holder,sql_value->StringValue(), sql_value->StringValueLength());
break;
case SqlValue::TYPE_NULL:
DOM_Object::DOMSetNull(value);
break;
case SqlValue::TYPE_INTEGER:
DOM_Object::DOMSetNumber(value,static_cast<double>(sql_value->IntegerValue()));
break;
case SqlValue::TYPE_DOUBLE:
DOM_Object::DOMSetNumber(value,sql_value->DoubleValue());
break;
case SqlValue::TYPE_BLOB:
//TODO: add blob support in SqlValue::GetToESValue
//no biggie since it's not possible to ES to pass a blob in the 1st place to ES
return OpStatus::ERR;
default:
OP_ASSERT(!"Forgot a type on SqlValueToESValue(SqlValue,ES_Value)");
return OpStatus::ERR;
}
return OpStatus::OK;
}
/* static */ OP_STATUS
DOM_SQLResultSet::Make(DOM_SQLResultSet *&result_set, SqlResultSet *sql_result_set, DOM_Runtime *runtime)
{
OP_ASSERT(!sql_result_set->IsIterable() || sql_result_set->IsCachingEnabled());
return DOMSetObjectRuntime(result_set = OP_NEW(DOM_SQLResultSet, (sql_result_set)), runtime,
runtime->GetPrototype(DOM_Runtime::SQLRESULTSET_PROTOTYPE), "SQLResultSet");
}
DOM_SQLResultSet::DOM_SQLResultSet(SqlResultSet *sql_result_set)
: DOM_BuiltInConstructor(DOM_Runtime::SQLRESULTSET_PROTOTYPE),
m_sql_result_set(sql_result_set)
{
}
DOM_SQLResultSet::~DOM_SQLResultSet()
{
OP_DELETE(m_sql_result_set);
m_sql_result_set = NULL;
}
/* virtual */ ES_GetState
DOM_SQLResultSet::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_insertId:
if (value)
{
if (m_sql_result_set && m_sql_result_set->GetRowsAffected()!=0)
DOMSetNumber(value, (double)m_sql_result_set->LastInsertId());
else
return DOM_GETNAME_DOMEXCEPTION(INVALID_ACCESS_ERR);
}
return GET_SUCCESS;
case OP_ATOM_rowsAffected:
if (value)
{
DOMSetNumber(value, m_sql_result_set != NULL ? m_sql_result_set->GetRowsAffected() : 0);
}
return GET_SUCCESS;
case OP_ATOM_rows:
if (value)
{
if (DOMSetPrivate(value, DOM_PRIVATE_dbResultRows) == GET_SUCCESS)
return GET_SUCCESS;
DOM_SQLResultSetRowList *row_list;
GET_FAILED_IF_ERROR(DOM_SQLResultSetRowList::Make(row_list, this, this->GetRuntime()));
GET_FAILED_IF_ERROR(PutPrivate(DOM_PRIVATE_dbResultRows, *row_list));
return DOMSetPrivate(value, DOM_PRIVATE_dbResultRows);
}
return GET_SUCCESS;
}
return DOM_Object::GetName(property_name, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_SQLResultSet::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_insertId:
case OP_ATOM_rowsAffected:
case OP_ATOM_rows:
return PUT_READ_ONLY;
}
return DOM_Object::PutName(property_name, value, origining_runtime);
}
DOM_SQLResultSetRowList::~DOM_SQLResultSetRowList()
{
OP_DELETEA(m_all_rows);
}
/* static */ OP_STATUS
DOM_SQLResultSetRowList::Make(DOM_SQLResultSetRowList *&row_list, DOM_SQLResultSet* parent, DOM_Runtime *runtime)
{
return DOMSetObjectRuntime(row_list = OP_NEW(DOM_SQLResultSetRowList, (parent)), runtime,
runtime->GetPrototype(DOM_Runtime::SQLRESULTSETROWLIST_PROTOTYPE), "SQLResultSetRowList");
}
/* virtual */ ES_GetState
DOM_SQLResultSetRowList::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_name == OP_ATOM_length)
{
DOMSetNumber(value, GetLength());
return GET_SUCCESS;
}
return DOM_Object::GetName(property_name, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_SQLResultSetRowList::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_name == OP_ATOM_length)
return PUT_READ_ONLY;
return DOM_Object::PutName(property_name, value, origining_runtime);
}
unsigned
DOM_SQLResultSetRowList::GetLength()
{
OP_ASSERT(m_parent);
OP_ASSERT(m_parent->m_sql_result_set);
OP_ASSERT(!m_parent->m_sql_result_set->IsIterable() || m_parent->m_sql_result_set->IsCachingEnabled());
if (m_parent->m_sql_result_set->IsIterable())
{
/** GetLength cannot fail given that the result set has caching enabled
and therefore all rows have been retrieved, and the length is available
without any extra effort. */
unsigned value;
#ifdef DEBUG_ENABLE_OPASSERT
OP_STATUS status =
#endif
m_parent->m_sql_result_set->GetCachedLength(&value);
OP_ASSERT(OpStatus::IsSuccess(status));
return value;
}
else
return 0;
}
OP_STATUS
DOM_SQLResultSetRowList::GetItem(unsigned row_index, ES_Value *value)
{
unsigned length = GetLength();
if (length <= row_index)
return OpStatus::ERR_OUT_OF_RANGE;
if (m_all_rows == NULL)
{
RETURN_OOM_IF_NULL(m_all_rows = OP_NEWA(DOM_SQLResultSetRow *, length));
op_memset(m_all_rows, 0, sizeof(DOM_SQLResultSetRow *) * length);
}
DOM_SQLResultSetRow *row_obj = m_all_rows[row_index];
if (row_obj == NULL)
{
RETURN_IF_ERROR(DOMSetObjectRuntime(row_obj = OP_NEW(DOM_SQLResultSetRow, (this, row_index)), GetRuntime()));
m_all_rows[row_index] = row_obj;
}
DOMSetObject(value, row_obj);
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_SQLResultSetRowList::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index >= 0)
{
OP_STATUS status = GetItem(static_cast<unsigned>(property_index), value);
OP_ASSERT(status != OpStatus::ERR_OUT_OF_RANGE || property_index >= (int)GetLength());
if (status == OpStatus::ERR_NO_MEMORY)
return GET_NO_MEMORY;
else if (OpStatus::IsSuccess(status))
return GET_SUCCESS;
}
return DOM_Object::GetIndex(property_index, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_SQLResultSetRowList::PutIndex(int property_index, ES_Value* value, ES_Runtime* origining_runtime)
{
if (0 <= property_index && property_index < (int)GetLength())
return PUT_SUCCESS;
return DOM_Object::PutIndex(property_index, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_SQLResultSetRowList::GetIndexedPropertiesLength(unsigned &count, ES_Runtime *origining_runtime)
{
count = GetLength();
return GET_SUCCESS;
}
/* static */ int
DOM_SQLResultSetRowList::item(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(row_list, DOM_TYPE_SQL_RESULTSETROWLIST, DOM_SQLResultSetRowList);
DOM_CHECK_ARGUMENTS("n");
if (argv[0].value.number >= 0)
{
OP_STATUS status = row_list->GetItem(static_cast<unsigned>(argv[0].value.number), return_value);
if (status == OpStatus::ERR_NO_MEMORY)
return ES_NO_MEMORY;
else if (OpStatus::IsSuccess(status))
return ES_VALUE;
}
return ES_FAILED;
}
void
DOM_SQLResultSetRowList::GCTrace()
{
GCMark(m_parent);
if (m_all_rows)
for (unsigned k = 0, length = GetLength(); k < length; k++)
GCMark(m_all_rows[k]);
}
/* static */ OP_STATUS
DOM_SQLResultSetRow::Make(DOM_SQLResultSetRow *&row_obj, DOM_SQLResultSetRowList* parent, unsigned row_index, DOM_Runtime *runtime)
{
RETURN_IF_ERROR(DOMSetObjectRuntime(row_obj = OP_NEW(DOM_SQLResultSetRow, (parent, row_index)), runtime));
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_SQLResultSetRow::GetName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime)
{
const SqlValue *sql_value = NULL;
GET_FAILED_IF_ERROR(m_parent->m_parent->m_sql_result_set->GetCachedValueAtColumn(m_row_index, property_name, sql_value));
if (sql_value)
{
if (value)
GET_FAILED_IF_ERROR(SqlValueToESValue(sql_value, value, &m_parent->m_parent->m_value_string));
return GET_SUCCESS;
}
return GET_FAILED;
}
/* virtual */ ES_PutState
DOM_SQLResultSetRow::PutName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime)
{
unsigned index;
if (m_parent->m_parent->m_sql_result_set->GetColumnIndex(property_name, &index))
return PUT_READ_ONLY;
return PUT_FAILED;
}
/* virtual */ ES_GetState
DOM_SQLResultSetRow::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
uni_char number_str[16]; /* ARRAY OK joaoe 2009-09-03 */
uni_itoa(property_index, number_str, 10);
return GetName(number_str, OP_ATOM_UNASSIGNED, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_SQLResultSetRow::PutIndex(int property_index, ES_Value* value, ES_Runtime* origining_runtime)
{
uni_char number_str[16]; /* ARRAY OK joaoe 2009-09-03 */
uni_itoa(property_index, number_str, 10);
return PutName(number_str, OP_ATOM_UNASSIGNED, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_SQLResultSetRow::FetchPropertiesL(ES_PropertyEnumerator *enumerator, ES_Runtime *origining_runtime)
{
ES_GetState result = DOM_Object::FetchPropertiesL(enumerator, origining_runtime);
if (result != GET_SUCCESS)
return result;
SqlResultSet *rs = m_parent->m_parent->m_sql_result_set;
const uni_char *col_name;
if (rs->IsIterable())
for(unsigned index = 0, limit = rs->GetColumnCount(); index < limit; index++)
if (rs->GetColumnName(index, &col_name))
enumerator->AddPropertyL(col_name);
return GET_SUCCESS;
}
/* virtual */ void
DOM_SQLResultSetRow::GCTrace()
{
GCMark(m_parent);
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_SQLResultSetRowList)
DOM_FUNCTIONS_FUNCTION(DOM_SQLResultSetRowList, DOM_SQLResultSetRowList::item, "item", "n-")
DOM_FUNCTIONS_END(DOM_SQLResultSetRowList)
// NOTE!! Keep this in sync with the DOM_SQLError::ErrorCode enum
CONST_ARRAY(g_sql_error_strings, uni_char*)
CONST_ENTRY(UNI_L("Unknown error")),
CONST_ENTRY(UNI_L("Statement failed")),
CONST_ENTRY(UNI_L("The database version didn't match the expected version")),
CONST_ENTRY(UNI_L("Result set too large")),
CONST_ENTRY(UNI_L("Quota exceeded")),
CONST_ENTRY(UNI_L("SQL error")),
CONST_ENTRY(UNI_L("Constraint failure")),
CONST_ENTRY(UNI_L("Operation timed out"))
CONST_END(g_sql_error_strings)
DOM_SQLError::DOM_SQLError(ErrorCode code) :
DOM_BuiltInConstructor(DOM_Runtime::SQLERROR_PROTOTYPE),
m_code(code),
m_custom_message(NULL)
{}
DOM_SQLError::~DOM_SQLError()
{
OP_DELETEA((uni_char *)m_custom_message);
}
/*static*/ OP_STATUS
DOM_SQLError::Make(DOM_SQLError *&error_obj, DOM_SQLError::ErrorCode code, const uni_char *custom_message, DOM_Runtime *runtime)
{
DOM_SQLError* new_error_obj;
RETURN_IF_ERROR(DOMSetObjectRuntime(new_error_obj = OP_NEW(DOM_SQLError, (code)), runtime, runtime->GetPrototype(DOM_Runtime::SQLERROR_PROTOTYPE), "SQLError"));
if (custom_message)
RETURN_OOM_IF_NULL(new_error_obj->m_custom_message = UniSetNewStr(custom_message));
error_obj = new_error_obj;
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_SQLError::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch(property_name)
{
case OP_ATOM_code:
DOMSetNumber(value, m_code);
return GET_SUCCESS;
case OP_ATOM_message:
DOMSetString(value, m_custom_message ? m_custom_message : GetErrorDescription(m_code));
return GET_SUCCESS;
}
return GET_FAILED;
}
/* virtual */ ES_PutState
DOM_SQLError::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_name == OP_ATOM_code || property_name == OP_ATOM_message)
return PUT_READ_ONLY;
return PUT_FAILED;
}
/* static */ const uni_char *
DOM_SQLError::GetErrorDescription(ErrorCode code)
{
if (code >= UNKNOWN_ERR && code < LAST_SQL_ERROR_CODE)
return g_sql_error_strings[code];
else
return g_sql_error_strings[UNKNOWN_ERR];
}
/* static */ void
DOM_SQLError::ConstructSQLErrorObjectL(ES_Object *object, DOM_Runtime *runtime)
{
// http://dev.w3.org/html5/webdatabase/#errors-and-exceptions
PutNumericConstantL(object, "UNKNOWN_ERR", UNKNOWN_ERR, runtime);
PutNumericConstantL(object, "DATABASE_ERR", DATABASE_ERR, runtime);
PutNumericConstantL(object, "VERSION_ERR", VERSION_ERR, runtime);
PutNumericConstantL(object, "TOO_LARGE_ERR", TOO_LARGE_ERR, runtime);
PutNumericConstantL(object, "QUOTA_ERR", QUOTA_ERR, runtime);
PutNumericConstantL(object, "SYNTAX_ERR", SQL_SYNTAX_ERR, runtime);
PutNumericConstantL(object, "CONSTRAINT_ERR", CONSTRAINT_ERR, runtime);
PutNumericConstantL(object, "TIMEOUT_ERR", TIMEOUT_ERR, runtime);
}
#endif // DATABASE_STORAGE_SUPPORT
|
#include "window.h"
Window::Window()
{
button = new QPushButton("teste", this);
this->show();
}
|
// Copyright (c) 2021 Hartmut Kaiser
//
// 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)
/// \file parallel/executors/scheduler_executor.hpp
#pragma once
#include <pika/config.hpp>
#include <pika/execution/algorithms/bulk.hpp>
#include <pika/execution/algorithms/keep_future.hpp>
#include <pika/execution/algorithms/make_future.hpp>
#include <pika/execution/algorithms/start_detached.hpp>
#include <pika/execution/algorithms/sync_wait.hpp>
#include <pika/execution/algorithms/then.hpp>
#include <pika/execution/algorithms/transfer.hpp>
#include <pika/execution/executors/execution.hpp>
#include <pika/execution/executors/execution_parameters.hpp>
#include <pika/execution_base/execution.hpp>
#include <pika/execution_base/sender.hpp>
#include <pika/execution_base/traits/is_executor.hpp>
#include <pika/functional/bind_back.hpp>
#include <pika/functional/bind_front.hpp>
#include <pika/functional/deferred_call.hpp>
#include <pika/futures/promise.hpp>
#include <exception>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace pika::execution::experimental {
namespace detail {
#if defined(PIKA_HAVE_CXX20_PERFECT_PACK_CAPTURE)
template <typename F, typename Rng, typename... Ts>
auto captured_args_then_void(F&& f, Rng&& rng, Ts&&... ts)
{
return [f = PIKA_FORWARD(F, f), rng = PIKA_FORWARD(Rng, rng),
... ts = PIKA_FORWARD(Ts, ts)](auto i, auto&&... predecessor) mutable {
PIKA_INVOKE(PIKA_FORWARD(F, f), std::begin(rng)[i],
PIKA_FORWARD(decltype(predecessor), predecessor)..., PIKA_FORWARD(Ts, ts)...);
};
}
template <typename F, typename Rng, typename... Ts>
auto captured_args_then(F&& f, Rng&& rng, Ts&&... ts)
{
return [f = PIKA_FORWARD(F, f), rng = PIKA_FORWARD(Rng, rng),
... ts = PIKA_FORWARD(Ts, ts)](auto i, auto&& predecessor, auto& v) mutable {
v[i] = PIKA_INVOKE(PIKA_FORWARD(F, f), std::begin(rng)[i],
PIKA_FORWARD(decltype(predecessor), predecessor), PIKA_FORWARD(Ts, ts)...);
};
}
#else
template <typename F, typename Rng, typename... Ts>
auto captured_args_then_void(F&& f, Rng&& rng, Ts&&... ts)
{
return [f = PIKA_FORWARD(F, f), rng = PIKA_FORWARD(Rng, rng),
t = std::make_tuple(PIKA_FORWARD(Ts, ts)...)](
auto i, auto&&... predecessor) mutable {
std::apply(pika::util::detail::bind_front(PIKA_FORWARD(F, f), std::begin(rng)[i],
PIKA_FORWARD(decltype(predecessor), predecessor)...),
PIKA_MOVE(t));
};
}
template <typename F, typename Rng, typename... Ts>
auto captured_args_then(F&& f, Rng&& rng, Ts&&... ts)
{
return [f = PIKA_FORWARD(F, f), rng = PIKA_FORWARD(Rng, rng),
t = std::make_tuple(PIKA_FORWARD(Ts, ts)...)](
auto i, auto&& predecessor, auto& v) mutable {
v[i] = std::apply(
pika::util::detail::bind_front(PIKA_FORWARD(F, f), std::begin(rng)[i],
PIKA_FORWARD(decltype(predecessor), predecessor)),
PIKA_MOVE(t));
};
}
#endif
} // namespace detail
///////////////////////////////////////////////////////////////////////////
// A scheduler_executor wraps any P2300 scheduler and implements the
// executor functionalities for those.
template <typename BaseScheduler>
struct scheduler_executor
{
static_assert(pika::execution::experimental::is_scheduler_v<std::decay_t<BaseScheduler>>,
"scheduler_executor requires a scheduler");
constexpr scheduler_executor() = default;
template <typename Scheduler,
typename Enable = std::enable_if_t<
pika::execution::experimental::is_scheduler_v<std::decay_t<Scheduler>>>>
constexpr explicit scheduler_executor(Scheduler&& sched)
: sched_(PIKA_FORWARD(Scheduler, sched))
{
}
constexpr scheduler_executor(scheduler_executor&&) = default;
constexpr scheduler_executor& operator=(scheduler_executor&&) = default;
constexpr scheduler_executor(scheduler_executor const&) = default;
constexpr scheduler_executor& operator=(scheduler_executor const&) = default;
/// \cond NOINTERNAL
constexpr bool operator==(scheduler_executor const& rhs) const noexcept
{
return sched_ == rhs.sched_;
}
constexpr bool operator!=(scheduler_executor const& rhs) const noexcept
{
return sched_ != rhs.sched_;
}
constexpr auto const& context() const noexcept { return *this; }
template <typename Enable = std::enable_if_t<std::is_invocable_v<with_priority_t,
BaseScheduler, pika::execution::thread_priority>>>
friend scheduler_executor tag_invoke(pika::execution::experimental::with_priority_t,
scheduler_executor const& exec, pika::execution::thread_priority priority)
{
return scheduler_executor(with_priority(exec.sched_, priority));
}
template <
typename Enable = std::enable_if_t<std::is_invocable_v<get_priority_t, BaseScheduler>>>
friend pika::execution::thread_priority
tag_invoke(pika::execution::experimental::get_priority_t, scheduler_executor const& exec)
{
return get_priority(exec.sched_);
}
template <typename Enable = std::enable_if_t<std::is_invocable_v<with_stacksize_t,
BaseScheduler, pika::execution::thread_stacksize>>>
friend scheduler_executor tag_invoke(pika::execution::experimental::with_stacksize_t,
scheduler_executor const& exec, pika::execution::thread_stacksize stacksize)
{
return scheduler_executor(with_stacksize(exec.sched_, stacksize));
}
template <
typename Enable = std::enable_if_t<std::is_invocable_v<get_stacksize_t, BaseScheduler>>>
friend pika::execution::thread_stacksize
tag_invoke(pika::execution::experimental::get_stacksize_t, scheduler_executor const& exec)
{
return get_stacksize(exec.sched_);
}
template <typename Enable = std::enable_if_t<std::is_invocable_v<with_hint_t, BaseScheduler,
pika::execution::thread_schedule_hint>>>
friend scheduler_executor tag_invoke(pika::execution::experimental::with_hint_t,
scheduler_executor const& exec, pika::execution::thread_schedule_hint hint)
{
return scheduler_executor(with_hint(exec.sched_, hint));
}
template <
typename Enable = std::enable_if_t<std::is_invocable_v<get_hint_t, BaseScheduler>>>
friend pika::execution::thread_schedule_hint
tag_invoke(pika::execution::experimental::get_hint_t, scheduler_executor const& exec)
{
return get_hint(exec.sched_);
}
template <typename Enable = std::enable_if_t<
std::is_invocable_v<with_annotation_t, BaseScheduler, char const*>>>
friend scheduler_executor tag_invoke(pika::execution::experimental::with_annotation_t,
scheduler_executor const& exec, char const* annotation)
{
return scheduler_executor(with_annotation(exec.sched_, annotation));
}
template <typename Enable = std::enable_if_t<
std::is_invocable_v<with_annotation_t, BaseScheduler, std::string>>>
friend scheduler_executor tag_invoke(pika::execution::experimental::with_annotation_t,
scheduler_executor const& exec, std::string annotation)
{
return scheduler_executor(with_annotation(exec.sched_, annotation));
}
template <typename Enable =
std::enable_if_t<std::is_invocable_v<get_annotation_t, BaseScheduler>>>
friend char const*
tag_invoke(pika::execution::experimental::get_annotation_t, scheduler_executor const& exec)
{
return get_annotation(exec.sched_);
}
// Associate the parallel_execution_tag executor tag type as a default
// with this executor.
using execution_category = parallel_execution_tag;
// Associate the static_chunk_size executor parameters type as a default
// with this executor.
using executor_parameters_type = static_chunk_size;
template <typename T, typename... Ts>
using future_type = pika::future<T>;
// NonBlockingOneWayExecutor interface
template <typename F, typename... Ts>
void post(F&& f, Ts&&... ts)
{
start_detached(then(schedule(sched_),
pika::util::detail::deferred_call(PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)));
}
// OneWayExecutor interface
template <typename F, typename... Ts>
decltype(auto) sync_execute(F&& f, Ts&&... ts)
{
return pika::this_thread::experimental::sync_wait(then(schedule(sched_),
pika::util::detail::deferred_call(PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)));
}
// TwoWayExecutor interface
template <typename F, typename... Ts>
decltype(auto) async_execute(F&& f, Ts&&... ts)
{
return make_future(then(schedule(sched_),
pika::util::detail::deferred_call(PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)));
}
template <typename F, typename Future, typename... Ts>
decltype(auto) then_execute(F&& f, Future&& predecessor, Ts&&... ts)
{
auto&& predecessor_transfer_sched =
transfer(keep_future(PIKA_FORWARD(Future, predecessor)), sched_);
return make_future(then(PIKA_MOVE(predecessor_transfer_sched),
pika::util::detail::bind_back(PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)));
}
// BulkTwoWayExecutor interface
template <typename F, typename S, typename... Ts>
decltype(auto) bulk_async_execute(F&& f, S const& shape, Ts&&... ts)
{
using shape_element = typename pika::traits::range_traits<S>::value_type;
using result_type =
pika::util::detail::invoke_deferred_result_t<F, shape_element, Ts...>;
if constexpr (std::is_void_v<result_type>)
{
using size_type = decltype(pika::util::size(shape));
size_type const n = pika::util::size(shape);
auto f_helper = [](size_type const i, F& f, S const& shape, Ts&... ts) {
auto it = pika::util::begin(shape);
std::advance(it, i);
PIKA_INVOKE(f, *it, ts...);
};
auto discard_args = [](auto&&...) {};
std::vector<pika::future<void>> results;
results.reserve(1);
results.emplace_back(make_future(then(
bulk(transfer_just(sched_, PIKA_FORWARD(F, f), shape, PIKA_FORWARD(Ts, ts)...),
n, f_helper),
discard_args)));
return results;
}
else
{
using promise_vector_type = std::vector<pika::lcos::local::promise<result_type>>;
using result_vector_type = std::vector<pika::future<result_type>>;
using size_type = decltype(pika::util::size(shape));
size_type const n = pika::util::size(shape);
promise_vector_type promises(n);
result_vector_type results;
results.reserve(n);
for (size_type i = 0; i < n; ++i)
{
results.emplace_back(promises[i].get_future());
}
auto f_helper = [](size_type const i, promise_vector_type& promises, F& f,
S const& shape, Ts&... ts) {
pika::detail::try_catch_exception_ptr(
[&]() mutable {
auto it = pika::util::begin(shape);
std::advance(it, i);
promises[i].set_value(PIKA_INVOKE(f, *it, ts...));
},
[&](std::exception_ptr&& ep) { promises[i].set_exception(PIKA_MOVE(ep)); });
};
start_detached(bulk(transfer_just(sched_, PIKA_MOVE(promises), PIKA_FORWARD(F, f),
shape, PIKA_FORWARD(Ts, ts)...),
n, PIKA_MOVE(f_helper)));
return results;
}
}
template <typename F, typename S, typename... Ts>
void bulk_sync_execute(F&& f, S const& shape, Ts&&... ts)
{
pika::this_thread::experimental::sync_wait(
bulk(schedule(sched_), pika::util::size(shape),
detail::captured_args_then_void(
PIKA_FORWARD(F, f), shape, PIKA_FORWARD(Ts, ts)...)));
}
template <typename F, typename S, typename Future, typename... Ts>
decltype(auto) bulk_then_execute(F&& f, S const& shape, Future&& predecessor, Ts&&... ts)
{
using result_type =
parallel::execution::detail::then_bulk_function_result_t<F, S, Future, Ts...>;
if constexpr (std::is_void<result_type>::value)
{
// the overall return value is future<void>
auto prereq = keep_future(PIKA_FORWARD(Future, predecessor));
auto loop = bulk(transfer(PIKA_MOVE(prereq), sched_), pika::util::size(shape),
detail::captured_args_then_void(
PIKA_FORWARD(F, f), shape, PIKA_FORWARD(Ts, ts)...));
return make_future(PIKA_MOVE(loop));
}
else
{
// the overall return value is future<std::vector<result_type>>
auto prereq = when_all(keep_future(PIKA_FORWARD(Future, predecessor)),
just(std::vector<result_type>(pika::util::size(shape))));
auto loop = bulk(transfer(PIKA_MOVE(prereq), sched_), pika::util::size(shape),
detail::captured_args_then(PIKA_FORWARD(F, f), shape, PIKA_FORWARD(Ts, ts)...));
return make_future(then(PIKA_MOVE(loop),
[](auto&&, std::vector<result_type>&& v) { return PIKA_MOVE(v); }));
}
}
private:
BaseScheduler sched_;
/// \endcond
};
template <typename BaseScheduler>
explicit scheduler_executor(BaseScheduler&& sched)
-> scheduler_executor<std::decay_t<BaseScheduler>>;
} // namespace pika::execution::experimental
namespace pika::parallel::execution {
/// \cond NOINTERNAL
template <typename BaseScheduler>
struct is_one_way_executor<pika::execution::experimental::scheduler_executor<BaseScheduler>>
: std::true_type
{
};
template <typename BaseScheduler>
struct is_never_blocking_one_way_executor<
pika::execution::experimental::scheduler_executor<BaseScheduler>> : std::true_type
{
};
template <typename BaseScheduler>
struct is_bulk_one_way_executor<
pika::execution::experimental::scheduler_executor<BaseScheduler>> : std::true_type
{
};
template <typename BaseScheduler>
struct is_two_way_executor<pika::execution::experimental::scheduler_executor<BaseScheduler>>
: std::true_type
{
};
template <typename BaseScheduler>
struct is_bulk_two_way_executor<
pika::execution::experimental::scheduler_executor<BaseScheduler>> : std::true_type
{
};
/// \endcond
} // namespace pika::parallel::execution
|
#pragma once
const int SCREEN_WIDTH = 900;
const int SCREEN_HEIGHT = 700;
const int INITIAL_X = 0;
const int INITIAL_Y = 0;
const int HUD_WIDTH = 200;
const int GAME_SPRITES_SIZE = 35;
const std::string SPLASH_IMAGE_ID = "SplashImage";
const std::string SPLASH_BACKGROUND_PATH = "../../res/img/SPLASH.png";
namespace MENU_FONT
{
const std::string ID = "MenuFont";
const std::string PATH = "../../res/ttf/PAC-FONT.ttf";
const int SIZE = 30;
}
namespace PLAY_FONT
{
const std::string ID = "PlayFont";
const std::string PATH = "../../res/ttf/Gameplay.ttf";
const int SIZE = 20;
}
namespace PLAY_BUTTON
{
const std::string ID = "PlayButton";
const std::string TEXT = "PLAY";
const std::string HOVER_ID = "PlayButtonHover";
const std::string HOVER_TEXT = "play";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 275;
const int H = 100;
const int X = 335;
const int Y = 125;
}
namespace RANKING_BUTTON
{
const std::string ID = "RankingButton";
const std::string TEXT = "RANKING";
const std::string HOVER_ID = "RankingButtonHover";
const std::string HOVER_TEXT = "ranking";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 255;
const int H = 50;
const int X = 335;
const int Y = 275;
}
namespace SOUND_BUTTON
{
const std::string ID = "SoundButton";
const std::string TEXT = "SOUND ON";
const std::string HOVER_ID = "SoundButtonHover";
const std::string HOVER_TEXT = "sound on";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 350;
const int H = 50;
const int X = 285;
const int Y = 375;
}
namespace EXIT_BUTTON
{
const std::string ID = "ExitButton";
const std::string TEXT = "EXIT";
const std::string HOVER_ID = "ExitButtonHover";
const std::string HOVER_TEXT = "exit";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 125;
const int H = 50;
const int X = 395;
const int Y = 475;
}
namespace BACK_BUTTON
{
const std::string ID = "BackButton";
const std::string TEXT = "BACK";
const std::string HOVER_ID = "BackButtonHover";
const std::string HOVER_TEXT = "back";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 125;
const int H = 50;
const int X = 395;
const int Y = 475;
}
namespace PACMAN_SPRITESHEET
{
const std::string ID = "PacmanSpritesheet";
const std::string TEXT = "";
const std::string PATH = "../../res/img/PacManSpritesheet.png";
const Color COLOR = Color(255, 255, 255, 0);
const int W = 1024;
const int H = 1024;
const int SPRITES_SIZE = 128;
}
const int SIZE = GAME_SPRITES_SIZE;
namespace PLAYER
{
const int X_UP_OPEN_SPRITE = 0;
const int X_UP_CLOSE_SPRITE = 1;
const int X_DOWN_OPEN_SPRITE = 2;
const int X_DOWN_CLOSE_SPRITE = 3;
const int X_RIGHT_OPEN_SPRITE = 4;
const int X_RIGHT_CLOSE_SPRITE = 5;
const int X_LEFT_OPEN_SPRITE = 6;
const int X_LEFT_CLOSE_SPRITE = 7;
const int Y_SPRITE_POSITION = 0;
const int X_DYING_1 = 0;
const int X_DYING_2 = 1;
const int X_DYING_3 = 2;
const int X_DYING_4 = 3;
const int X_DYING_5 = 4;
const int X_DYING_6 = 5;
const int X_DYING_7 = 6;
const int X_DYING_8 = 7;
const int Y_DYING_1 = 4;
const int Y_DYING_2 = 5;
}
namespace BLINKY
{
const int X_UP_OPEN_SPRITE = 0;
const int X_UP_CLOSE_SPRITE = 1;
const int X_DOWN_OPEN_SPRITE = 2;
const int X_DOWN_CLOSE_SPRITE = 3;
const int X_RIGHT_OPEN_SPRITE = 4;
const int X_RIGHT_CLOSE_SPRITE = 5;
const int X_LEFT_OPEN_SPRITE = 6;
const int X_LEFT_CLOSE_SPRITE = 7;
const int Y_SPRITE_POSITION = 1;
}
namespace INKY
{
const int X_UP_OPEN_SPRITE = 0;
const int X_UP_CLOSE_SPRITE = 1;
const int X_DOWN_OPEN_SPRITE = 2;
const int X_DOWN_CLOSE_SPRITE = 3;
const int X_RIGHT_OPEN_SPRITE = 4;
const int X_RIGHT_CLOSE_SPRITE = 5;
const int X_LEFT_OPEN_SPRITE = 6;
const int X_LEFT_CLOSE_SPRITE = 7;
const int Y_SPRITE_POSITION = 2;
}
namespace CLYDE
{
const int X_UP_OPEN_SPRITE = 0;
const int X_UP_CLOSE_SPRITE = 1;
const int X_DOWN_OPEN_SPRITE = 2;
const int X_DOWN_CLOSE_SPRITE = 3;
const int X_RIGHT_OPEN_SPRITE = 4;
const int X_RIGHT_CLOSE_SPRITE = 5;
const int X_LEFT_OPEN_SPRITE = 6;
const int X_LEFT_CLOSE_SPRITE = 7;
const int Y_SPRITE_POSITION = 3;
}
namespace POWERUP
{
const int X_SPRITE_POSITION = 6;
const int Y_SPRITE_POSITION = 6;
}
namespace WALL
{
const int X_SPRITE_POSITION = 4;
const int Y_SPRITE_POSITION = 6;
}
namespace POINT
{
const int X_SPRITE_POSITION = 5;
const int Y_SPRITE_POSITION = 6;
}
namespace STRAWBERRY
{
const int X_SPRITE_POSITION = 1;
const int Y_SPRITE_POSITION = 6;
}
namespace CHERRY
{
const int X_SPRITE_POSITION = 0;
const int Y_SPRITE_POSITION = 6;
}
namespace ORANGE
{
const int X_SPRITE_POSITION = 2;
const int Y_SPRITE_POSITION = 6;
}
namespace PLAYER_INITIAL_INFO
{
const int DIRECTION = 0;
const int VELOCITY = 2;
const int SCORE = 0;
const int LIVES = 3;
}
namespace POWERUP_DATA
{
const int POINTS = 20;
const int TIME_EFFECT = 10;
}
namespace POINT_DATA
{
const int POINTS = 1;
}
namespace STRAWBERRY_DATA
{
const int POINTS = 15;
}
namespace CHERRY_DATA
{
const int POINTS = 10;
}
namespace ORANGE_DATA
{
const int POINTS = 20;
}
namespace BLINKY_INITIAL_INFO
{
const int DIRECTION = 1;
const int VELOCITY = 2;
}
namespace INKY_INITIAL_INFO
{
const int DIRECTION = 0;
const int VELOCITY = 2;
}
namespace CLYDE_INITIAL_INFO
{
const int DIRECTION = 1;
const int VELOCITY = 2;
}
namespace POWER_UP_INFO
{
const int VELOCITY = 1;
const int X_GREY_1_SPRITE = 0;
const int X_GREY_2_SPRITE = 1;
const int X_BLUE_1_SPRITE = 2;
const int X_BLUE_2_SPRITE = 3;
const int Y_SPRITE_POSITION = 4;
}
namespace HUD_INFO
{
const int X_BACKGROUND = 7;
const int Y_BACKGROUND = 6;
const int X_STRAWBERRY = 1;
const int Y_STRAWBERRY = 6;
const int STRAWBERRY_SIZE = 70;
const int INITIAL_STRAWBERRY_X = 705;
const int INITIAL_STRAWBERRY_Y = 265;
const int X_CHERRY = 0;
const int Y_CHERRY = 6;
const int CHERRY_SIZE = 70;
const int INITIAL_CHERRY_X = 705;
const int INITIAL_CHERRY_Y = 195;
const int X_ORANGE = 2;
const int Y_ORANGE = 6;
const int ORANGE_SIZE = 70;
const int INITIAL_ORANGE_X = 705;
const int INITIAL_ORANGE_Y = 335;
const int X_LIVE = 7;
const int Y_LIVE = 0;
const int LIVE_SIZE = 70;
const int INITIAL_LIVE_X = 695;
const int INITIAL_LIVE_Y = 600;
const int SCORE_W = 40;
const int SCORE_H = 80;
const int SCORE_INITIAL_X = 710;
const int SCORE_INITIAL_Y = 50;
const int X_TRANSPARENT = 0;
const int Y_TRANSPARENT = 7;
const int X_NULL = 3;
const int Y_NULL = 6;
const int INITIAL_MULTIPLIER_X = 780;
const int INITIAL_FRUITS_COUNT_X = 820;
const int INITIAL_STRAWBERRY_COUNT_Y = 266;
const int INITIAL_CHERRY_COUNT_Y = 201;
const int INITIAL_ORANGE_COUNT_Y = 331;
const int INITIAL_STRAWBERRY_MULTIPLIER_Y = 270;
const int INITIAL_CHERRY_MULTIPLIER_Y = 205;
const int INITIAL_ORANGE_MULTIPLIER_Y = 335;
const int MULTIPLIER_X_SIZE = 42;
const int MULTIPLIER_Y_SIZE = 70;
}
namespace RANKING_INFO
{
const Color COLOR = Color(200, 200, 200, 255);
const int INITIAL_HEIGHT = 100;
const int INITIAL_WIDTH = 375;
const int WIDTH = 150;
const int HEIGHT = 40;
}
namespace SCORE_0
{
const std::string ID = "SCORE_0";
const std::string TEXT = "0";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_1
{
const std::string ID = "SCORE_1";
const std::string TEXT = "1";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_2
{
const std::string ID = "SCORE_2";
const std::string TEXT = "2";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_3
{
const std::string ID = "SCORE_3";
const std::string TEXT = "3";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_4
{
const std::string ID = "SCORE_4";
const std::string TEXT = "4";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_5
{
const std::string ID = "SCORE_5";
const std::string TEXT = "5";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_6
{
const std::string ID = "SCORE_6";
const std::string TEXT = "6";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_7
{
const std::string ID = "SCORE_7";
const std::string TEXT = "7";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_8
{
const std::string ID = "SCORE_8";
const std::string TEXT = "8";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_9
{
const std::string ID = "SCORE_9";
const std::string TEXT = "9";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace SCORE_X
{
const std::string ID = "SCORE_X";
const std::string TEXT = "X";
const Color COLOR = Color(0, 0, 0, 255);
}
namespace PRESS_SPACE1
{
const std::string ID = "Start Game Button1";
const std::string TEXT = "PrEs SpAcE";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 385;
const int H = 60;
const int X = 200;
const int Y = 250;
}
namespace PRESS_SPACE2
{
const std::string ID = "Start Game Button2";
const std::string TEXT = "tO sTaRt........";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 385;
const int H = 60;
const int X = 200;
const int Y = 325;
}
namespace STOP_PRESS_SPACE1
{
const std::string ID = "Stop Button1";
const std::string TEXT = "StOp";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 385;
const int H = 100;
const int X = 200;
const int Y = 50;
}
namespace STOP_PRESS_SPACE2
{
const std::string ID = "Stop Button2";
const std::string TEXT = "PrEs SpAcE";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 385;
const int H = 60;
const int X = 200;
const int Y = 175;
}
namespace STOP_PRESS_SPACE3
{
const std::string ID = "Stop Button3";
const std::string TEXT = "tO rElEaCe";
const Color COLOR = Color(255, 0, 0, 255);
const int W = 385;
const int H = 60;
const int X = 200;
const int Y = 250;
}
namespace SOUND_PAUSE
{
const std::string ID = "Sound Pause";
const std::string TEXT = "SoUnD oN";
const Color COLOR = Color(255, 255, 255, 255);
const int W = 275;
const int H = 50;
const int X = 250;
const int Y = 400;
}
namespace NULL_TEXT
{
const std::string ID = "Null Text";
const std::string TEXT = " ";
const Color COLOR = Color(0, 0, 0, 0);
const int W = 350;
const int H = 50;
const int X = 285;
const int Y = 375;
}
|
#include <iostream>
#define MAX(a,b) a>b?a:b
using namespace std;
int arr[10001];
int d[10001] = { 0 };
int main(){
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> arr[i];
}
d[1] = arr[1];
d[2] = arr[1] + arr[2];
for (int i = 3; i <= n; i++) {
int max = d[i - 1];
if (max < d[i - 2] + arr[i])
max = d[i - 2] + arr[i];
if(max < d[i-3]+arr[i-1]+arr[i])
max = d[i-3]+arr[i-1]+arr[i];
d[i] = max;
}
cout << d[n];
system("pause");
return 0;
}
|
#ifndef _PCTIME_H_
#define _PCTIME_H_
#ifndef _TIME_H_
#include <time.h>
#define _TIME_H_
#endif
class TimerTest{
public:
void setTime();
double getTime();
private:
double str_t;
};
void TimerTest::setTime(){
str_t=time(NULL);
}
double TimerTest::getTime(){
return time(NULL)-str_t;
}
void Delay(double t){
double str_t=time(NULL);
while(time(NULL)-str_t<t)
;
}
#endif //_PCTIME_H_
|
#include<iostream>
#include<cassert>
#include<errno.h>
#include<cstring>
#include<type_traits>
#include<signal.h>
#include<sys/socket.h>
#include<cstdio>
#include<unistd.h>
#include<cstdlib>
#include<sys/ipc.h>
#include<sys/types.h>
#include<string>
#include<arpa/inet.h>
using namespace std;
//#define INET_ADDRSTRLEN 16
bool stop=false;
int main(int argc, char **argv){
if(argc!=3){
printf("error argu");
}
int sock=socket(PF_INET,SOCK_STREAM, 0 );
assert(sock>=0);
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family=AF_INET;
const string ip=argv[1];
int port=atoi(argv[2]);
inet_pton(AF_INET, ip.c_str(), &address.sin_addr);
address.sin_port=htons(port);
int connId=connect(sock, (sockaddr*)&address, sizeof(address));
if(connId<0){
cout<<errno<<endl;
}else{
//这里并没有得到跟书上一样的结果,接收到的URG数据乱码,发送的第三个数据,并没有接到
string send_str( "hellookska");
string oob_str("world");
send(sock, send_str.c_str(), sizeof(send_str), 0);
send(sock, oob_str.c_str(), sizeof(oob_str), MSG_OOB);
send(sock, send_str.c_str(), sizeof(send_str), 0);
close(sock);
}
//test what accept will do if clients close or being disrupted the established state
//sockaddr_in client;
//socklen_t cli_addr_in=sizeof(client);
//int sock_id=accept(sock, (sockaddr*)&client, &cli_addr_in);
//if(sock_id<=0){
// cout<<"error ="<<errno<<endl;
//}else{
// char remote[INET_ADDRSTRLEN];
// cout<<"the host ip"<<inet_ntop(AF_INET, &client.sin_addr,remote, INET_ADDRSTRLEN)<<endl;
// cout<<"the port"<<ntohs(client.sin_port)<<endl;
// close(sock_id);
//}
//close(sock);
return 0;
}
|
#include "BasePlayerController.h"
#include "Single/GameInstance/RPGGameInst.h"
#include "Single/PlayerManager/PlayerManager.h"
#include "Actor/Character/PlayerCharacter/PlayerCharacter.h"
#include "Component/WndToggler/WndTogglerComponent.h"
#include "Widget/WidgetControllerWidget/WidgetControllerWidget.h"
ABasePlayerController::ABasePlayerController()
{
static ConstructorHelpers::FClassFinder<UWidgetControllerWidget> BP_WIDGET_CONTROLLER_WIDGET(
TEXT("WidgetBlueprint'/Game/Blueprints/Widget/WidgetController/BP_WidgetController.BP_WidgetController_C'"));
if (BP_WIDGET_CONTROLLER_WIDGET.Succeeded()) BP_WidgetController = BP_WIDGET_CONTROLLER_WIDGET.Class;
else { UE_LOG(LogTemp, Error, TEXT("BasePlayerController.cpp :: %d LINE :: BP_WIDGET_CONTROLLER_WIDGET is not loaded!"), __LINE__); }
WndToggler = CreateDefaultSubobject<UWndTogglerComponent>(TEXT("WND_TOGGLER"));
DefaultInputMode = EInputModeType::IM_GameOnly;
bDefaultCursorVisibility = false;
}
void ABasePlayerController::OnPossess(APawn* aPawn)
{
Super::OnPossess(aPawn);
GetManager(UPlayerManager)->RegisterPlayer(this, Cast<APlayerCharacter>(aPawn));
WidgetControllerWidget = CreateWidget<UWidgetControllerWidget>(this, BP_WidgetController);
WidgetControllerWidget->InitializeWidgetControllerWidget(this);
WidgetControllerWidget->AddToViewport();
}
void ABasePlayerController::ChangeViewTarget(AActor* targetActor, float blendTime)
{
SetViewTargetWithBlend(targetActor, blendTime);
}
void ABasePlayerController::ResetViewTarget(float blendTime)
{
auto playerCharacter = GetManager(UPlayerManager)->GetPlayerCharacter();
if (!IsValid(playerCharacter)) return;
SetViewTargetWithBlend(playerCharacter, blendTime);
}
|
#pragma once
#include "DynamicObject.h"
class MotorBike :
public DynamicObject
{
public:
MotorBike(int id, std::string name, int x, int y) :DynamicObject(id, name, x, y) {};
void printPosition() override;
void move(Position) override;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2004 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef MEM_UTILS_H
#define MEM_UTILS_H
# include "modules/util/simset.h"
#ifdef MEMTEST
# ifndef _BUILDING_OPERA_
# define _BUILDING_OPERA_
# endif
void oom_add_unanchored_object(char *allocation_address, void *object_address);
void oom_delete_unanchored_object(void *object_address);
void oom_remove_anchored_object(void *object_address);
void oom_report_and_remove_unanchored_objects(char *caller = NULL);
extern int *global_oom_dummy;
#define OOM_REPORT_UNANCHORED_OBJECT() \
do { \
int dummy; \
char *caller_address = 0; \
if (( (void*) this > (void*) &dummy && (void*) this < (void*) global_oom_dummy) || \
( (void*) this < (void*) &dummy && (void*) this > (void*) global_oom_dummy)) { \
GET_CALLER(caller_address); \
oom_add_unanchored_object(caller_address, this); \
} \
} while (0)
class oom_UnanchoredObject : public Link
{
public:
oom_UnanchoredObject(char* alloc_address, void *object_address, int depth) :
allocation_address(alloc_address),
address(object_address),
trap_depth(depth)
{}
char *allocation_address;
void *address;
int trap_depth;
};
class oom_TrapInfo : public Link
{
public:
oom_TrapInfo();
~oom_TrapInfo();
char* m_call_address;
BOOL m_is_left;
};
#endif
class MemUtil
{
public:
#ifdef ADDR2LINE_SUPPORT
class ModuleMatchList : public Link
{
public:
ModuleMatchList(const char* match_string) { m_match_string = (char*)match_string; }
~ModuleMatchList() { delete [] m_match_string; }
char* GetString() { return m_match_string; }
private:
char* m_match_string;
};
static void AddIncludeModule(Link* include_module) { include_module->Into(&s_include_module_list); }
static void AddExcludeModule(Link* exclude_module) { exclude_module->Into(&s_exclude_module_list); }
static BOOL MatchesModule(void* const stack[], const int stack_levels);
static BOOL MatchesModule(void* stack);
#endif // ADDR2LINE_SUPPORT
private:
#ifdef ADDR2LINE_SUPPORT
static Head s_include_module_list;
static Head s_exclude_module_list;
#endif // ADDR2LINE_SUPPORT
};
#endif // MEM_UTILS_H
|
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long LL;
struct Tp {
int x, y;
bool operator<(const Tp& t) const {
return x < t.x || x == t.x && y < t.y;
}
bool operator==(const Tp& t) const {
return x == t.x && y == t.y;
}
} a[333];
int main() {
freopen("cottages.in", "r", stdin);
freopen("cottages.out", "w", stdout);
int n;
scanf("%d\n", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &a[i].x, &a[i].y);
}
sort(a, a + n);
n = unique(a, a + n) - a;
long long ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int A = a[j].y - a[i].y;
int B = a[i].x - a[j].x;
int C = -A * a[i].x - B * a[i].y;
int c = 0;
int maxx = max(a[i].x, a[j].x);
int maxy = max(a[i].y, a[j].y);
int minx = min(a[i].x, a[j].x);
int miny = min(a[i].y, a[j].y);
for (int k = 0; k < n; ++k) {
if (k == i) ++c;else
if (k == j) ++c;else
if (A * a[k].x + B * a[k].y + C == 0) {
if (a[k].x >= minx && a[k].x <= maxx && a[k].y >= miny && a[k].y <= maxy) {
c = -1;
break;
}
++c;
}
}
if(c != -1) {
ans += 2;
}
}
}
cout << ans << endl;
return 0;
}
|
#include <iostream>
#include <fstream>
using namespace std;
inline const char* const BoolToString(bool b) {
return b ? "1" : "0";
}
int main() {
FILE* fp;
char path[1035];
std::string siteUrl;
bool fullscreen = false;
fp = _popen("electron --version", "r");
// wait until output is read
while (fgets(path, sizeof(path) - 1, fp) != NULL) {}
_pclose(fp);
// if electron is not installed, must first be installed (assumes node is installed)
if (path[0] != 'v') {
cout << "Electron is not installed!";
}
// electron is installed, proceed with program
else {
cout << "Electron is installed!\n";
// prompt user for URL
cout << "Enter the URL of the Website: ";
std::cin >> siteUrl;
// prompt if fullscreen
cout << "Would you like the application to be fullscreen? (y/n): ";
string result;
cin >> result;
if (result == "y" || result =="Y" || result == "yes" || result =="Yes") {
fullscreen = true;
}
// Verify siteUrl is a valid URL (https://stackoverflow.com/questions/38608116/how-to-check-a-specified-string-is-a-valid-url-or-not-using-c-code)
// write URL to file (which is then imported by the electron main.js)
std::ofstream out("electron-files/site.json");
std::string jsonString;
jsonString = "{\n\t\"url\":\"" + siteUrl + "\",\n\t\"fullscreen\":" + BoolToString(fullscreen) + "\n}";
out << jsonString;
out.close();
// run electron main.js
system("run-electron.bat");
}
return 0;
}
|
/* ***** 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 ****** */
#include "gdcmIO/reader/DicomSRReader.hpp"
#include "gdcmIO/reader/DicomLandmarkReader.hpp"
#include "gdcmIO/reader/DicomDistanceReader.hpp"
#include "gdcmIO/helper/GdcmHelper.hpp"
#include "gdcmIO/DicomDictionarySR.hpp"
namespace gdcmIO
{
namespace reader
{
//------------------------------------------------------------------------------
DicomSRReader::DicomSRReader()
{
SLM_TRACE_FUNC();
this->setReader( ::boost::shared_ptr< ::gdcm::Reader >( new ::gdcm::Reader ) );
}
//------------------------------------------------------------------------------
DicomSRReader::~DicomSRReader()
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
void DicomSRReader::read() throw (::fwTools::Failed)
{
SLM_TRACE_FUNC();
::fwData::Image::sptr image = this->getConcreteObject();
SLM_ASSERT("fwData::Image not instanced", image);
::boost::shared_ptr< DicomInstance > dicomInstance = this->getDicomInstance();
SLM_ASSERT("gdcmIO::DicomInstance not set", dicomInstance);
//***** Get all file names *****//
const std::vector< std::string > & docSR = this->getCRefFileNames();
const unsigned int nbDocSR = docSR.size();
OSLM_TRACE("Number of SR files : " << nbDocSR);
if (nbDocSR > 1)
{
OSLM_WARN("More than one document SR was found in series. Just the first one will be read.");
}
// Get the basic GDCM reader
::boost::shared_ptr< ::gdcm::Reader > gReader = this->getReader();
//***** Init tools *****//
DicomLandmarkReader landmarkReader;
landmarkReader.setObject( image );
landmarkReader.setReader( gReader );
landmarkReader.setDicomInstance( dicomInstance );
DicomDistanceReader distanceReader;
distanceReader.setObject( image );
distanceReader.setReader( gReader );
distanceReader.setDicomInstance( dicomInstance );
//***** Read first file *****//
gReader->SetFileName( docSR[0].c_str() );
if ( gReader->Read() )
{
OSLM_TRACE("SR document reading : "<<docSR[0].c_str());
// Landmarks
try
{// Read all landmarks found in the document SR
landmarkReader.read();
}
catch (::fwTools::Failed &e)
{
OSLM_ERROR("Landmark reading failed: "<<e.what());
}
// Distances
try
{// Read all distances found in the document SR
distanceReader.read();
}
catch (::fwTools::Failed &e)
{
OSLM_ERROR("Distance reading failed: "<<e.what());
}
}
else
{
OSLM_ERROR("SR document reading error in file : "<<docSR[0].c_str());
}
}
} // namespace reader
} // namespace gdcmIO
|
//
// Created by 송지원 on 2020/06/29.
//
#include <iostream>
#include <queue>
#include <utility>
using namespace std;
#define X first
#define Y second
int N, M;
int board[105][105];
bool vis[105][105];
int len[105][105];
string s;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
for (int i = 0; i < N; i++) {
cin >> s;
for (int j = 0; j < M; j++) {
board[i][j] = (int)(s.at(j) - '0');
len[i][j] = 1000;
}
}
queue<pair<int, int>> Q;
Q.push({0, 0});
vis[0][0] = 1;
// int LEN = 1;
len[0][0] = 1;
while(!Q.empty()) {
pair<int, int> cur = Q.front();
int temp_len = len[cur.X][cur.Y];
Q.pop();
for (int dir=0; dir<4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue;
if (!board[nx][ny] || vis[nx][ny]) continue;
Q.push({nx, ny});
vis[nx][ny] = 1;
// len[nx][ny] = min(len[nx][ny], temp_len+1) ;
len[nx][ny] = temp_len+1;
}
}
cout << len[N-1][M-1];
}
|
/*
Copyright 2021 University of Manchester
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http: // www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include "gmock/gmock.h"
#include "query_manager_interface.hpp"
using orkhestrafs::dbmstodspi::QueryManagerInterface;
class MockQueryManager : public QueryManagerInterface {
private:
using ReuseLinks = std::map<std::string, std::map<int, MemoryReuseTargets>>;
using MappedResultParameters =
std::map<std::string, std::vector<StreamResultParameters>>;
using ExecutionReadyNodes =
std::pair<std::vector<AcceleratedQueryNode>, MappedResultParameters>;
using ScheduledNodes =
std::pair<ReuseLinks,
std::queue<std::pair<ConfigurableModulesVector,
std::vector<std::shared_ptr<QueryNode>>>>>;
using MappedMemoryBlocks =
std::unordered_map<std::string, MemoryBlockInterface*>;
using MappedRecordSizes =
std::map<std::string, std::vector<RecordSizeAndCount>>;
using TableMap = std::map<std::string, TableMetadata>;
using SchedulingNodeMap =
std::unordered_map<std::string, SchedulingQueryNode>;
using QueryNodeVector = std::vector<QueryNode*>;
using Counter = std::unordered_map<std::string, int>;
using Matrix = std::vector<std::vector<int>>;
using HWLibrary = std::map<QueryOperationType, OperationPRModules>;
public:
MOCK_METHOD(std::vector<long>, GetData, (), (override));
MOCK_METHOD(long, GetConfigTime, (), (override));
MOCK_METHOD(void, MeasureBitstreamConfigurationSpeed,
(const HWLibrary& hw_library,
orkhestrafs::dbmstodspi::MemoryManagerInterface* memory_manager),
(override));
MOCK_METHOD(ReuseLinks, GetCurrentLinks,
(std::queue<ReuseLinks> & all_reuse_links), (override));
MOCK_METHOD(ExecutionReadyNodes, SetupAccelerationNodesForExecution,
(DataManagerInterface * data_manager,
MemoryManagerInterface* memory_manager,
AcceleratorLibraryInterface* accelerator_library,
const std::vector<QueryNode*>& current_query_nodes,
const TableMap& current_tables_metadata,
MappedMemoryBlocks& table_memory_blocks, Counter& table_counter,
bool print_write_times),
(override));
MOCK_METHOD(void, LoadNextBitstreamIfNew,
(MemoryManagerInterface * memory_manager,
std::string bitstream_file_name, Config config),
(override));
/*MOCK_METHOD(bool, IsRunValid, (std::vector<AcceleratedQueryNode>
current_run), (override));*/
MOCK_METHOD(void, ExecuteAndProcessResults,
(MemoryManagerInterface * memory_manager,
FPGAManagerInterface* fpga_manager,
const DataManagerInterface* data_manager,
MappedMemoryBlocks& table_memory_blocks,
const MappedResultParameters& result_parameters,
const std::vector<AcceleratedQueryNode>& execution_query_nodes,
TableMap& scheduling_table_data, Counter& table_counter,
int timeout),
(override));
MOCK_METHOD(
(std::queue<std::pair<std::vector<ScheduledModule>, QueryNodeVector>>),
ScheduleNextSetOfNodes,
(QueryNodeVector & query_nodes,
const std::unordered_set<std::string>& first_node_names,
const std::unordered_set<std::string>& starting_nodes,
const SchedulingNodeMap& graph, TableMap& tables,
AcceleratorLibraryInterface& drivers, const Config& config,
NodeSchedulerInterface& node_scheduler,
const std::vector<ScheduledModule>& current_configuration,
std::unordered_set<std::string>& skipped_nodes, Counter& table_counter,
const std::unordered_set<std::string>& blocked_nodes),
(override));
MOCK_METHOD(void, LoadInitialStaticBitstream,
(MemoryManagerInterface * memory_manager, int clock_speed),
(override));
MOCK_METHOD(void, LoadEmptyRoutingPRRegion,
(MemoryManagerInterface * memory_manager,
AcceleratorLibraryInterface& driver_library),
(override));
MOCK_METHOD(long, LoadPRBitstreams,
(MemoryManagerInterface * memory_manager,
const std::vector<std::string>& bitstream_names,
AcceleratorLibraryInterface& driver_library),
(override));
MOCK_METHOD((std::pair<std::vector<std::string>,
std::vector<std::pair<QueryOperationType, bool>>>),
GetPRBitstreamsToLoadWithPassthroughModules,
(std::vector<ScheduledModule> & current_config,
const std::vector<ScheduledModule>& next_config,
std::vector<std::string>& current_routing),
(override));
MOCK_METHOD((void), BenchmarkScheduling,
(const std::unordered_set<std::string>& first_node_names,
const std::unordered_set<std::string>& starting_nodes,
std::unordered_set<std::string>& processed_nodes,
const SchedulingNodeMap& graph, TableMap& tables,
AcceleratorLibraryInterface& drivers, const Config& config,
NodeSchedulerInterface& node_scheduler,
std::vector<ScheduledModule>& current_configuration,
const std::unordered_set<std::string>& blocked_nodes),
(override));
MOCK_METHOD((void), PrintBenchmarkStats, (), (override));
MOCK_METHOD((int), GetRecordSizeFromParameters,
(const DataManagerInterface* data_manager,
const Matrix& node_parameters, int stream_index),
(const override));
};
|
#define true 1
#define false 0
class CarShops {
/*
* ARRAY FORMAT:
* 0: STRING (Classname)
* 1: STRING (Condition)
* FORMAT:
* STRING (Conditions) - Must return boolean :
* String can contain any amount of conditions, aslong as the entire
* string returns a boolean. This allows you to check any levels, licenses etc,
* in any combination. For example:
* "call cxp_coplevel && license_civ_someLicense"
* This will also let you call any other function.
*
* BLUFOR Vehicle classnames can be found here: https://community.bistudio.com/wiki/Arma_3_CfgVehicles_WEST
* OPFOR Vehicle classnames can be found here: https://community.bistudio.com/wiki/Arma_3_CfgVehicles_EAST
* Independent Vehicle classnames can be found here: https://community.bistudio.com/wiki/Arma_3_CfgVehicles_GUER
* Civilian Vehicle classnames can be found here: https://community.bistudio.com/wiki/Arma_3_CfgVehicles_CIV
*/
class civ_car {
side = "civ";
vehicles[] = {
{ "B_Quadbike_01_F", "" },
{ "C_Hatchback_01_F", "" },
{ "C_Offroad_01_F", "" },
{ "C_SUV_01_F", "" },
{ "C_Hatchback_01_sport_F", "" },
{ "C_Offroad_02_unarmed_F", "" },
{ "C_Offroad_01_repair_F", "" },
{ "C_Van_01_transport_F", "" },
{ "C_Van_01_fuel_F", "" },
{ "C_Van_02_vehicle_F", "" },
{ "C_Van_02_transport_F", "" }
};
};
class bounty_veh_store {
side = "civ";
vehicles[] = {
{ "C_Offroad_01_F", "" }
};
};
class kart_shop {
side = "civ";
vehicles[] = {
{ "C_Kart_01_Blu_F", "" },
{ "C_Kart_01_Fuel_F", "" },
{ "C_Kart_01_Red_F", "" },
{ "C_Kart_01_Vrana_F", "" }
};
};
class civ_truck {
side = "civ";
vehicles[] = {
{ "C_Van_01_box_F", "" },
{ "B_Truck_01_transport_F", "" },
{ "I_Truck_02_transport_F", "" },
{ "I_Truck_02_covered_F", "" },
{ "B_Truck_01_covered_F", "" },
{ "O_Truck_03_transport_F", "" },
{ "O_Truck_03_covered_F", "" },
{ "B_Truck_01_box_F", "" },
{ "B_Truck_01_ammo_F", "" },
{ "I_Truck_02_fuel_F", "" },
{ "B_Truck_01_fuel_F", "" },
{ "O_Truck_03_ammo_F", "" },
{ "O_Truck_03_device_F", "" }
};
};
class civ_air {
side = "civ";
vehicles[] = {
{ "C_Heli_Light_01_civil_F", "" }, // m-900
{ "B_Heli_Light_01_F", "" }, // mh-9
{ "O_Heli_Light_02_unarmed_F", "" }, // orca
{ "B_Heli_Transport_03_unarmed_F", "" }, // huron
{ "C_Plane_Civil_01_racing_F", "" }, // caesar
{ "I_Heli_Transport_02_F", "" } // mohawk
};
};
class civ_ship {
side = "civ";
vehicles[] = {
{ "C_Rubberboat", "" },
{ "C_Scooter_Transport_01_F", "" },
{ "C_Boat_Civil_01_F", "" },
{ "O_SDV_01_F", "" }
};
};
/* REBELDE */
class reb_car_b {
side = "civ";
vehicles[] = {
{ "B_Quadbike_01_F", "" }, // quadbike
{ "C_SUV_01_F", "" }, // suv
{ "B_G_Offroad_01_F", "" }, // offroad rebelde
{ "C_Offroad_02_unarmed_F", "" }, // jeep
{ "I_MRAP_03_F", "" }, // strider
{ "O_MRAP_02_F", "" } // ifrit
};
};
class reb_air {
side = "civ";
vehicles[] = {
{ "B_Heli_Light_01_stripped_F", "" }, //mh-9(reb)
{ "O_Heli_Light_02_unarmed_F", "" }, // orca(reb)
{ "I_Heli_light_03_unarmed_F", "" }, // hellcat(reb)
{ "O_Heli_Transport_04_box_F", "" } // taru carga(reb)
};
};
/* REBELDE - FIM */
// "call cxp_mediclevel >= 1" , "call cxp_mediclevel >= 2" , "call cxp_mediclevel >= 3", etc...
class med_shop {
side = "med";
vehicles[] = {
{ "I_Truck_02_fuel_F", "call cxp_mediclevel >= 1" }, // zamak shell
{ "C_Offroad_01_F", "call cxp_mediclevel >= 1" },// offroad
{ "O_MRAP_02_F", "call cxp_mediclevel >= 1" },// ifrit
{ "B_MRAP_01_F", "call cxp_mediclevel >= 1" },// Hunter
{ "I_MRAP_03_F", "call cxp_mediclevel >= 1" },// Hunter
{ "C_SUV_01_F", "call cxp_mediclevel >= 1" },// SUV
{ "C_Van_02_medevac_F", "call cxp_mediclevel >= 1" }, // Van
{ "C_IDAP_Van_02_medevac_F", "call cxp_mediclevel >= 1" } // Van
};
};
class med_air_hs {
side = "med";
vehicles[] = {
{ "B_Heli_Light_01_F", "call cxp_mediclevel >= 1" }, // humming bird samu
{ "O_Heli_Light_02_unarmed_F", "call cxp_mediclevel >= 1" }, // orca
{ "O_Heli_Transport_04_medevac_F", "call cxp_mediclevel >= 1" }, // taru samu
{ "I_Heli_Transport_02_F", "call cxp_mediclevel >= 1" } // mowhank samu
};
};
// "call cxp_coplevel >= 1" , "call cxp_coplevel >= 2" , "call cxp_coplevel >= 3", etc...
class cop_car {
side = "cop";
vehicles[] = {
{ "B_Quadbike_01_F", "call cxp_coplevel >= 1" },
{ "C_Offroad_01_F", "call cxp_coplevel >= 1" },
{ "C_SUV_01_F", "call cxp_coplevel >= 1" },
{ "C_Hatchback_01_sport_F", "call cxp_coplevel >= 1" },
{ "I_Truck_02_fuel_F", "call cxp_coplevel >= 3" },
{ "B_MRAP_01_F", "call cxp_coplevel >=3" }, // Hunter
{ "O_MRAP_02_F", "call cxp_coplevel >=3" }, // Hunter
{ "B_GEN_Van_02_Vehicle_F", "call cxp_coplevel >=3" }, // Hunter
{ "C_Van_02_transport_F", "call cxp_coplevel >=3" }
};
};
class cop_air {
side = "cop";
vehicles[] = {
{ "B_Heli_Light_01_F", "call cxp_coplevel >= 3" }, // MH-9 Hummingbird Policia
{ "I_Heli_light_03_unarmed_F", "call cxp_coplevel >= 3" }, //WY-55 Hellcat
{ "O_Heli_Transport_04_F", "call cxp_coplevel >= 3"} //Taru Policia
};
};
class cop_ship {
side = "cop";
vehicles[] = {
{ "B_Boat_Transport_01_F", "call cxp_coplevel >= 3" },
{ "C_Boat_Civil_01_police_F", "call cxp_coplevel >= 3" },
{ "B_SDV_01_F", "call cxp_coplevel >= 3" }
};
};
};
class CxpCfgVehicles {
/*
* Vehicle Configs (Contains textures and other stuff)
*
* "price" e o preco basico para civis
* "price_cop" e o preco basico para policiais
* "price_samu" e o preco basico para medicos
*
* Default Multiplier Values & Calculations:
* Civilian [Purchase, Sell]: [1.0, 0.5]
* Cop [Purchase, Sell]: [0.5, 0.5]
* Medic [Purchase, Sell]: [0.75, 0.5]
* ChopShop: Payout = price * 0.25
* GarageSell: Payout = price * [0.5, 0.5, 0.5, -1]
* Cop Impound: Payout = price * 0.1
* Pull Vehicle from Garage: Cost = price * [1, 0.5, 0.75, -1] * [0.5, 0.5, 0.5, -1]
* -- Pull Vehicle & GarageSell Array Explanation = [civ,cop,medic,east]
*
* 1: STRING (Condition)
* Textures config follows { Texture Name, side, {texture(s)path}, Condition}
* Texture(s)path follows this format:
* INDEX 0: Texture Layer 0
* INDEX 1: Texture Layer 1
* INDEX 2: Texture Layer 2
* etc etc etc
*
class Default {
vItemSpace = -1; // Tamanho do inventario virtual
conditions = ""; // condicao para esse veiculo ser comprado/usado
price = -1; // preco para civis
price_cop = -1; // preco para cops
price_samu = -1; // preco para medicos
textures[] = {}; // skins desse veiculo
desarmar = false; // 'true': deixa veiculo (armado) sem suas municoes....'false': deixa veiculo (armado) com suas municoes ---> By Casperento
};
*/
class I_Truck_02_medical_F {
vItemSpace = 150;
conditions = "";
price = 25000;
price_cop = 10000;
price_samu = 7500;
textures[] = {};
desarmar = false;
};
class C_Plane_Civil_01_racing_F {
vItemSpace = 150;
conditions = "license_civ_pilot || {!(playerSide isEqualTo civilian)}";
price = 6000000;
price_cop = 3000000;
price_samu = 1500000;
textures[] = {};
desarmar = false;
};
class O_Plane_Fighter_02_F {
vItemSpace = 180;
conditions = "license_cop_cAir";
price = -1;
price_cop = 1000000;
price_samu = -1;
textures[] = {};
desarmar = true;
};
class B_Heli_Transport_03_unarmed_F {
vItemSpace = 400;
conditions = "license_civ_pilot || {!(playerSide isEqualTo civilian)}";
price = 5500000;
price_cop = 2550000;
price_samu = 1225000;
textures[] = {};
desarmar = false;
};
class B_Heli_Transport_03_unarmed_green_F {
vItemSpace = 50;
conditions = "license_med_mAir";
price = 3800000;
price_cop = 1520000;
price_samu = 1140000;
textures[] = {};
desarmar = false;
};
class B_Heli_Light_01_stripped_F {
vItemSpace = 200;
conditions = "license_civ_rebellic || {!(playerSide isEqualTo civilian)}";
price = 1600000;
price_cop = 640000;
price_samu = 480000;
textures[] = {
{ "Rebel Digital", "reb", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_digital_co.paa"
}, "" }
};
desarmar = false;
};
class O_Heli_Transport_04_F {
vItemSpace = 200;
conditions = "license_cop_cAir || {!(playerSide isEqualTo west)}";
price = 1600000;
price_cop = 640000;
price_samu = 480000;
textures[] = {
{ "SAMU", "med", {
"textures\cop\veh\c_taru1.jpg",
"textures\cop\veh\c_taru2.jpg"
}, "" }
};
desarmar = false;
};
class I_Heli_Transport_02_F {
vItemSpace = 350;
conditions = "license_civ_pilot || license_med_mAir || license_cop_cAir ";
price = 2200000;
price_cop = 880000;
price_samu = 660000;
textures[] = {
{ "Civil", "civ", {
"\a3\air_f_beta\Heli_Transport_02\Data\Skins\heli_transport_02_1_dahoman_co.paa",
"\a3\air_f_beta\Heli_Transport_02\Data\Skins\heli_transport_02_2_dahoman_co.paa",
"\a3\air_f_beta\Heli_Transport_02\Data\Skins\heli_transport_02_3_dahoman_co.paa"
}, "" },
{ "Civil 2", "civ", {
"\a3\air_f_beta\Heli_Transport_02\Data\Skins\Heli_Transport_02_1_ion_CO.paa",
"\a3\air_f_beta\Heli_Transport_02\Data\Skins\Heli_Transport_02_2_ion_CO.paa",
"\a3\air_f_beta\Heli_Transport_02\Data\Skins\heli_transport_02_3_ion_co.paa"
}, "" },
{ "Resgate", "med", {
"textures\resgate\veh\m_mon1.jpg",
"textures\resgate\veh\m_mon2.jpg",
"textures\resgate\veh\m_mon3.jpg"
}, "" }
};
desarmar = false;
};
class B_GEN_Van_02_Vehicle_F {
vItemSpace = 300;
conditions = "license_civ_rebellic || license_cop_cAir || license_med_mAir";
price = 2000000;
price_cop = 800000;
price_samu = 600000;
textures[] = {
{ "HellCat GATE", "cop", {
"textures\cop\veh\c_vantrans.jpg"
}, "" }
};
desarmar = false;
};
class I_Heli_light_03_unarmed_F {
vItemSpace = 300;
conditions = "license_civ_rebellic || license_cop_cAir || license_med_mAir";
price = 2000000;
price_cop = 800000;
price_samu = 600000;
textures[] = {
{ "REBELDE", "reb", {
"\a3\air_f_epb\Heli_Light_03\data\Heli_Light_03_base_CO.paa"
}, "" },
{ "HellCat GATE", "cop", {
"textures\cop\veh\hellcat_cop.jpg"
}, "" }
};
desarmar = false;
};
class I_Heli_light_03_dynamicLoadout_F : I_Heli_light_03_unarmed_F {
conditions = "license_cop_cAir";
desarmar = true;
};
class B_Heli_Transport_01_F : I_Heli_light_03_unarmed_F {
conditions = "license_cop_cAir";
price_cop = 850000;
desarmar = true;
};
class O_Heli_Transport_04_medevac_F {
vItemSpace = 0;
conditions = "license_med_mAir";
price = 3600000;
price_cop = 1440000;
price_samu = 1080000;
textures[] = {
{ "SAMU", "med", {
"textures\resgate\veh\taru_samu_0.jpg",
"textures\resgate\veh\taru_samu_1.jpg",
"textures\resgate\veh\taru_samu_2.jpg",
"textures\resgate\veh\taru_samu_3.jpg"
}, "" }
};
desarmar = false;
};
class O_Heli_Transport_04_box_F {
vItemSpace = 580;
conditions = "license_civ_rebellic || {!(playerSide isEqualTo civilian)}";
price = 3800000;
price_cop = 1520000;
price_samu = 1140000;
textures[] = {};
desarmar = false;
};
class B_T_VTOL_01_vehicle_F {
vItemSpace = 950;
conditions = "license_civ_rebellic || {!(playerSide isEqualTo civilian)}";
price = 15000000;
price_cop = 6000000;
price_samu = 4500000;
textures[] = {};
desarmar = false;
};
class O_T_LSV_02_unarmed_F {
vItemSpace = 95;
conditions = "license_civ_rebellic || {!(playerSide isEqualTo civilian)}";
price = 110000;
price_cop = 44000;
price_samu = 33000;
textures[] = {};
desarmar = false;
};
class O_LSV_02_unarmed_F {
vItemSpace = 90;
conditions = "{!(playerSide isEqualTo civilian)}";
price = 110000;
price_cop = 44000;
price_samu = 33000;
textures[] = {};
desarmar = false;
};
class B_MRAP_01_F {
vItemSpace = 70;
conditions = "license_civ_rebellic || {!(playerSide isEqualTo civilian)}";
price = 400000;
price_cop = 160000;
price_samu = 120000;
textures[] = {
{ "COP", "cop", {
"textures\cop\veh\hunter_cop_0.jpg",
"textures\cop\veh\hunter_cop_1.jpg"
}, "" },
{ "Resgate", "med", {
"textures\resgate\veh\m_hunter1.jpg",
"textures\resgate\veh\m_hunter2.jpg"
}, "" }
};
desarmar = false;
};
class O_MRAP_02_F {
vItemSpace = 70;
conditions = "license_civ_rebellic || {!(playerSide isEqualTo civilian)}";
price = 600000;
price_cop = 240000;
price_samu = 180000;
textures[] = {
{ "Gate", "cop", {
"textures\cop\veh\c1_ifrit.jpg",
"textures\cop\veh\c2_ifrit.jpg"
}, "" },
{ "Resgate", "med", {
"textures\resgate\veh\m_ifrit1.jpg",
"textures\resgate\veh\m_ifrit2.jpg"
}, "" }
};
desarmar = false;
};
class I_MRAP_03_F {
vItemSpace = 60;
conditions = "license_civ_rebellic || {!(playerSide isEqualTo civilian)}";
price = 400000;
price_cop = 160000;
price_samu = 120000;
textures[] = {
{ "REB", "reb", {
"\A3\soft_f_beta\MRAP_03\Data\MRAP_03_ext_INDP_CO.paa"
}, "" },
{ "Samu", "med", {
"textures\resgate\veh\strider_samu.jpg"
}, "" }
};
desarmar = false;
};
class O_Truck_03_medical_F {
vItemSpace = 10;
conditions = "";
price = 45000;
price_cop = 18000;
price_samu = 13500;
textures[] = {};
desarmar = false;
};
class B_Truck_01_medical_F {
vItemSpace = 10;
conditions = "";
price = 60000;
price_cop = 24000;
price_samu = 18000;
textures[] = {};
desarmar = false;
};
class C_Rubberboat {
vItemSpace = 45;
conditions = "license_civ_boat || {!(playerSide isEqualTo civilian)}";
price = 5000;
price_cop = 2000;
price_samu = 1500;
textures[] = { };
desarmar = false;
};
class C_Scooter_Transport_01_F {
vItemSpace = 35;
conditions = "license_civ_boat || {!(playerSide isEqualTo civilian)}";
price = 15000;
price_cop = 6000;
price_samu = 4500;
textures[] = { };
desarmar = false;
};
class B_Boat_Transport_01_F {
vItemSpace = 45;
conditions = "license_cop_cg";
price = 3000;
price_cop = 1200;
price_samu = 900;
textures[] = { };
desarmar = false;
};
class O_Truck_03_transport_F {
vItemSpace = 700;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 700000;
price_cop = 224000;
price_samu = 168000;
textures[] = { };
desarmar = false;
};
class O_Truck_03_device_F {
vItemSpace = 450;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 2000000;
price_cop = 800000;
price_samu = 600000;
textures[] = { };
desarmar = false;
};
class O_Truck_03_ammo_F {
vItemSpace = 600;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 1300000;
price_cop = 520000;
price_samu = 390000;
textures[] = { };
desarmar = false;
};
class Land_CargoBox_V1_F {
vItemSpace = 5000;
conditions = "";
price = -1;
price_cop = -1;
price_samu = -1;
textures[] = {};
desarmar = false;
};
class Box_IND_Grenades_F {
vItemSpace = 350;
conditions = "";
price = -1;
price_cop = -1;
price_samu = -1;
textures[] = {};
desarmar = false;
};
class B_supplyCrate_F {
vItemSpace = 700;
conditions = "";
price = -1;
price_cop = -1;
price_samu = -1;
textures[] = {};
desarmar = false;
};
class B_G_Offroad_01_F {
vItemSpace = 90;
conditions = "license_civ_rebellic || {!(playerSide isEqualTo civilian)}";
price = 60000;
price_cop = 24000;
price_samu = 18000;
textures[] = { };
desarmar = false;
};
class C_Boat_Civil_01_F {
vItemSpace = 85;
conditions = "license_civ_boat || {!(playerSide isEqualTo civilian)}";
price = 22000;
price_cop = 8800;
price_samu = 6600;
textures[] = { };
desarmar = false;
};
class O_SDV_01_F {
vItemSpace = 200;
conditions = "license_civ_boat || {!(playerSide isEqualTo civilian)}";
price = 200000;
price_cop = 80000;
price_samu = 60000;
textures[] = { };
desarmar = false;
};
class C_Boat_Civil_01_police_F {
vItemSpace = 85;
conditions = "license_cop_cg || {!(playerSide isEqualTo west)}";
price = 20000;
price_cop = 8000;
price_samu = 6000;
textures[] = {};
desarmar = false;
};
class B_SDV_01_F {
vItemSpace = 85;
conditions = "license_cop_cg || {!(playerSide isEqualTo west)}";
price = 20000;
price_cop = 9000;
price_samu = 6000;
textures[] = {};
desarmar = false;
};
class B_Truck_01_box_F {
vItemSpace = 950;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 1900000;
price_cop = 760000;
price_samu = 570000;
textures[] = { };
desarmar = false;
};
class B_Truck_01_ammo_F {
vItemSpace = 850;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 850000;
price_cop = 700000;
price_samu = 525000;
textures[] = { };
desarmar = false;
};
class I_Truck_02_fuel_F {
vItemSpace = 350;
vFuelSpace = 60000;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 400000;
price_cop = 160000;
price_samu = 120000;
textures[] = {
{ "Shell", "civ", {
"textures\civ\veh\zamaktank.jpg",
"textures\civ\veh\zamaktank2.jpg"
}, "" }
};
desarmar = false;
};
class B_Truck_01_fuel_F {
vItemSpace = 300;
vFuelSpace = 30000;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 400000;
price_cop = 160000;
price_samu = 120000;
textures[] = { };
desarmar = false;
};
class B_Truck_01_transport_F {
vItemSpace = 300;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 300000;
price_cop = 392000;
price_samu = 294000;
textures[] = { };
desarmar = false;
};
class O_T_LSV_02_unarmed_black_F {
vItemSpace = 100;
conditions = "{!(playerSide isEqualTo civilian)}";
price = 150000;
price_cop = 60000;
price_samu = 45000;
textures[] = { };
desarmar = false;
};
class C_Offroad_01_F {
vItemSpace = 90;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 90000;
price_cop = 36000;
price_samu = 27000;
textures[] = {
{ "Red", "civ", {
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_co.paa",
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_co.paa"
}, "" },
{ "Yellow", "civ", {
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE01_CO.paa",
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE01_CO.paa"
}, "" },
{ "White", "civ", {
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE02_CO.paa",
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE02_CO.paa"
}, "" },
{ "Blue", "civ", {
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE03_CO.paa",
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE03_CO.paa"
}, "" },
{ "Dark Red", "civ", {
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE04_CO.paa",
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE04_CO.paa"
}, "" },
{ "Blue / White", "civ", {
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE05_CO.paa",
"\A3\soft_F\Offroad_01\Data\offroad_01_ext_BASE05_CO.paa"
}, "" },
{ "AMARELA", "civ", {
"#(argb,8,8,3)color(0.6,0.3,0.01,1)"
}, "" },
{ "PM", "cop", {
"textures\cop\veh\c_offpm.jpg"
}, "" },
{ "GATE", "cop", {
"textures\cop\veh\c_offgate.jpg"
}, "" },
{ "RESGATE", "med", {
"textures\resgate\veh\offSAMU.jpg"
}, "" }
};
desarmar = false;
};
class C_Van_02_transport_F {
vItemSpace = 90;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 200000;
price_cop = 36000;
price_samu = 27000;
textures[] = {
{ "Preto", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_black_CO.paa"
}, "" },
{ "Azul", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_blue_CO.paa"
}, "" },
{ "Branco", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_white_CO.paa"
}, "" },
{ "Laranja", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_Orange_CO.paa"
}, "" },
{ "Gate", "Cop", {
"textures\cop\veh\c_vantrans.jpg"
}, "" },
{ "Maconha", "civ", {
"textures\civ\veh\VANMACONHA.jpg"
}, "" }
};
desarmar = false;
};
class C_Van_02_service_F {
vItemSpace = 90;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 200000;
price_cop = 36000;
price_samu = 27000;
textures[] = {
{ "Serviço", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_CivService_CO.paa"
}, "" },
{ "Maconha", "civ", {
"textures\civ\veh\VANMACONHA.jpg"
}, "" }
};
desarmar = false;
};
class C_Van_02_vehicle_F {
vItemSpace = 150;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 200000;
price_cop = 36000;
price_samu = 27000;
textures[] = {
{ "Empresa", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_Armazon_CO.paa"
}, "" },
{ "Jornal", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_AAN_CO.paa"
}, "" },
{ "Empresa2", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_Daltgreen_CO.paa"
}, "" },
{ "Combustivel", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_Fuel_CO.paa"
}, "" },
{ "Redstone", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_Redstone_CO.paa"
}, "" },
{ "Empresa3", "civ", {
"\A3\soft_f_orange\Van_02\Data\van_body_Vrana_CO.paa"
}, "" },
{ "Maconha", "civ", {
"textures\civ\veh\VANMACONHA.jpg"
}, "" }
};
desarmar = false;
};
class C_Van_02_medevac_F {
vItemSpace = 300;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 100000;
price_cop = 50000;
price_samu = 20000;
textures[] = {
{ "SAMU", "med", {
"textures\resgate\veh\vansamu.jpg"
}, "" }
};
desarmar = false;
};
class C_IDAP_Van_02_medevac_F {
vItemSpace = 300;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 100000;
price_cop = 50000;
price_samu = 20000;
textures[] = {
{ "SAMU", "med", {
"textures\resgate\veh\vansamu.jpg"
}, "" }
};
desarmar = false;
};
class C_Offroad_01_repair_F {
vItemSpace = 100;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 100000;
price_cop = 40000;
price_samu = 30000;
textures[] = {};
desarmar = false;
};
class C_Kart_01_Blu_F {
vItemSpace = 0;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 15000;
price_cop = 6000;
price_samu = 4500;
textures[] = {};
desarmar = false;
};
/*
To edit another information in this classes you can use this exemple.
class C_Kart_01_Fuel_F : C_Kart_01_Blu_F{
vItemSpace = 40;
price = ;
};
will modify the virtual space and the price of the vehicle, but other information such as license and textures will pick up the vehicle declare at : Vehicle {};
*/
class C_Kart_01_Fuel_F : C_Kart_01_Blu_F{}; // Get all information of C_Kart_01_Blu_F
class C_Kart_01_Red_F : C_Kart_01_Blu_F{};
class C_Kart_01_Vrana_F : C_Kart_01_Blu_F{};
class C_Hatchback_01_sport_F {
vItemSpace = 60;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 90000;
price_cop = 45000;
price_samu = 20000;
textures[] = {
{ "Red", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_sport01_co.paa"
}, "" },
{ "Dark Blue", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_sport02_co.paa"
}, "" },
{ "Orange", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_sport03_co.paa"
}, "" },
{ "Black / White", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_sport04_co.paa"
}, "" },
{ "Beige", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_sport05_co.paa"
}, "" },
{ "Green", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_sport06_co.paa"
}, "" },
{ "Laranja Custom.", "civ", {
"textures\civ\veh\laranjacustom.jpg"
}, "" },
{ "Maconha", "civ", {
"textures\civ\veh\weedhatch.jpg"
}, "" },
{ "Atletico Min.", "civ", {
"textures\civ\veh\htb_atletc.jpg"
}, "" },
{ "Corinthians", "civ", {
"textures\civ\veh\htb_corint.jpg"
}, "" },
{ "Atletico Min.", "civ", {
"textures\civ\veh\htb_atletc.jpg"
}, "" },
{ "Cruzeiro", "civ", {
"textures\civ\veh\htb_cruz.jpg"
}, "" },
{ "Gremio", "civ", {
"textures\civ\veh\htb_gremio.jpg"
}, "" },
{ "Internacional", "civ", {
"textures\civ\veh\htb_inter.jpg"
}, "" },
{ "Flamengo", "civ", {
"textures\civ\veh\htb_mengo.jpg"
}, "" },
{ "Palmeiras", "civ", {
"textures\civ\veh\htb_palm.jpg"
}, "" },
{ "RbsNoticias", "civ", {
"textures\civ\veh\rbs.jpg"
}, "" },
{ "SbtNoticias", "civ", {
"textures\civ\veh\sbt.jpg"
}, "" },
{ "COP", "cop", {
"textures\cop\veh\hatspo_cop.jpg"
}, "" },
{ "Google", "civ", {
"textures\civ\veh\google.jpg"
}, "" }
};
desarmar = false;
};
class B_Quadbike_01_F {
vItemSpace = 40;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 5000;
price_cop = 2000;
price_samu = 1500;
textures[] = {
{ "Digi Desert", "reb", {
"\A3\Soft_F\Quadbike_01\Data\quadbike_01_opfor_co.paa"
}, "" },
{ "Black", "civ", {
"\A3\Soft_F_beta\Quadbike_01\Data\quadbike_01_civ_black_co.paa"
}, "" },
{ "Blue", "civ", {
"\A3\Soft_F_beta\Quadbike_01\Data\quadbike_01_civ_blue_co.paa"
}, "" },
{ "Red", "civ", {
"\A3\Soft_F_beta\Quadbike_01\Data\quadbike_01_civ_red_co.paa"
}, "" },
{ "White", "civ", {
"\A3\Soft_F_beta\Quadbike_01\Data\quadbike_01_civ_white_co.paa"
}, "" },
{ "Digi Green", "civ", {
"\A3\Soft_F_beta\Quadbike_01\Data\quadbike_01_indp_co.paa"
}, "" },
{ "Hunter Camo", "civ", {
"\a3\soft_f_gamma\Quadbike_01\data\quadbike_01_indp_hunter_co.paa"
}, "" },
{ "Rebel Camo", "reb", {
"\a3\soft_f_gamma\Quadbike_01\data\quadbike_01_indp_hunter_co.paa"
}, "" },
{ "Quad", "cop", {
"textures\cop\veh\c_quad.jpg"
}, "" }
};
desarmar = false;
};
class I_Truck_02_covered_F {
vItemSpace = 500;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 500000;
price_cop = 168000;
price_samu = 126000;
textures[] = {
{ "Orange", "civ", {
"\A3\Soft_F_Beta\Truck_02\data\truck_02_kab_co.paa",
"\a3\soft_f_beta\Truck_02\data\truck_02_kuz_co.paa"
}, "" },
{ "Black", "cop", {
"#(argb,8,8,3)color(0.05,0.05,0.05,1)"
}, "" }
};
desarmar = false;
};
class I_Truck_02_transport_F {
vItemSpace = 400;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 400000;
price_cop = 112000;
price_samu = 84000;
textures[] = {
{ "Orange", "civ", {
"\A3\Soft_F_Beta\Truck_02\data\truck_02_kab_co.paa",
"\a3\soft_f_beta\Truck_02\data\truck_02_kuz_co.paa"
}, "" },
{ "Black", "cop", {
"#(argb,8,8,3)color(0.05,0.05,0.05,1)"
}, "" }
};
desarmar = false;
};
class B_Truck_01_covered_F {
vItemSpace = 600;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 600000;
price_cop = 80000;
price_samu = 60000;
textures[] = {};
desarmar = false;
};
class O_Truck_03_covered_F {
vItemSpace = 800;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 800000;
price_cop = 280000;
price_samu = 210000;
textures[] = {};
desarmar = false;
};
class C_Offroad_02_unarmed_F {
vItemSpace = 98;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 110000;
price_cop = 44000;
price_samu = 33000;
textures[] = {
{ "Azul", "civ", {
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_ext_blue_co.paa",
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_int_blue_co.paa"
}, "" },
{ "Verde", "civ", {
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_ext_green_co.paa",
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_int_green_co.paa"
}, "" },
{ "Laranja", "civ", {
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_ext_orange_co.paa",
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_int_orange_co.paa"
}, "" },
{ "Vermelho", "reb", {
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_ext_red_co.paa",
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_int_red_co.paa"
}, "" },
{ "Branco", "civ", {
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_ext_white_co.paa",
"\A3\Soft_F_Exp\Offroad_02\Data\offroad_02_int_white_co.paa"
}, "" }
};
desarmar = false;
};
class C_Hatchback_01_F {
vItemSpace = 60;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 45000;
price_cop = 18000;
price_samu = 13500;
textures[] = {
{ "Beige", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_base01_co.paa"
}, "" },
{ "Green", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_base02_co.paa"
}, "" },
{ "Blue", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_base03_co.paa"
}, "" },
{ "Dark Blue", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_base04_co.paa"
}, "" },
{ "Yellow", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_base06_co.paa"
}, "" },
{ "White", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_base07_co.paa"
}, "" },
{ "Grey", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_base08_co.paa"
}, "" },
{ "Laranja Custom.", "civ", {
"textures\civ\veh\laranjacustom.jpg"
}, "" },
{ "Maconha", "civ", {
"textures\civ\veh\weedhatch.jpg"
}, "" },
{ "Black", "civ", {
"\a3\soft_f_gamma\Hatchback_01\data\hatchback_01_ext_base09_co.paa"
}, "" },
{ "Atletico Min.", "civ", {
"textures\civ\veh\htb_atletc.jpg"
}, "" },
{ "Corinthians", "civ", {
"textures\civ\veh\htb_corint.jpg"
}, "" },
{ "Atletico Min.", "civ", {
"textures\civ\veh\htb_atletc.jpg"
}, "" },
{ "Cruzeiro", "civ", {
"textures\civ\veh\htb_cruz.jpg"
}, "" },
{ "Gremio", "civ", {
"textures\civ\veh\htb_gremio.jpg"
}, "" },
{ "Internacional", "civ", {
"textures\civ\veh\htb_inter.jpg"
}, "" },
{ "Flamengo", "civ", {
"textures\civ\veh\htb_mengo.jpg"
}, "" },
{ "Palmeiras", "civ", {
"textures\civ\veh\htb_palm.jpg"
}, "" },
{ "RbsNoticias", "civ", {
"textures\civ\veh\rbs.jpg"
}, "" },
{ "SbtNoticias", "civ", {
"textures\civ\veh\sbt.jpg"
}, "" },
{ "Google", "civ", {
"textures\civ\veh\google.jpg"
}, "" },
{ "PM", "cop", {
"textures\cop\veh\c_hatch.jpg"
}, "" },
{ "Br Shooting", "civ", {
"textures\civ\veh\hatch_brsh.jpg"
}, "" }
};
desarmar = false;
};
class C_SUV_01_F {
vItemSpace = 70;
conditions = "license_civ_driver || {!(playerSide isEqualTo civilian)}";
price = 65000;
price_cop = 26000;
price_samu = 19500;
textures[] = {
{ "Dark Red", "civ", {
"\a3\soft_f_gamma\SUV_01\Data\suv_01_ext_co.paa"
}, "" },
{ "Silver", "civ", {
"\a3\soft_f_gamma\SUV_01\Data\suv_01_ext_03_co.paa"
}, "" },
{ "Orange", "civ", {
"\a3\soft_f_gamma\SUV_01\Data\suv_01_ext_04_co.paa"
}, "" },
{ "GATE", "cop", {
"textures\cop\veh\cop_suv.jpg"
}, "" },
{ "RESGATE", "med", {
"textures\resgate\veh\samu_suv.jpg"
}, "" },
{ "Monster", "civ", {
"textures\civ\veh\monstersuv.jpg"
}, "" }
};
desarmar = false;
};
class C_Van_01_box_F {
vItemSpace = 250;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 250000;
price_cop = 67200;
price_samu = 50400;
textures[] = {
{ "Colombo", "civ", {
"textures\civ\veh\van_colomboF.jpg",
"textures\civ\veh\van_colomboB.jpg"
}, "" },
{ "MagazineLuiza", "civ", {
"textures\civ\veh\van_magazineF.jpg",
"textures\civ\veh\van_magazineB.jpg"
}, "" },
{ "PontoFrio", "civ", {
"textures\civ\veh\van_pontoF.jpg",
"textures\civ\veh\van_pontoB.jpg"
}, "" }
};
desarmar = false;
};
class C_Van_01_transport_F {
vItemSpace = 200;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 200000;
price_cop = 80000;
price_samu = 60000;
textures[] = {};
desarmar = false;
};
class C_Van_01_fuel_F {
vItemSpace = 150;
vFuelSpace = 19500;
conditions = "license_civ_trucking || {!(playerSide isEqualTo civilian)}";
price = 125000;
price_cop = 125000;
price_samu = 125000;
textures[] = {};
desarmar = false;
};
class B_Heli_Light_01_F {
vItemSpace = 90;
conditions = "license_civ_pilot || license_cop_cAir || license_med_mAir";
price = 2500000;
price_cop = 1750000;
price_samu = 950000;
textures[] = {
{ "Sheriff", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_sheriff_co.paa"
}, "" },
{ "Civ Blue", "civ", {
"\a3\air_f\Heli_Light_01\Data\heli_light_01_ext_blue_co.paa"
}, "" },
{ "Civ Red", "civ", {
"\a3\air_f\Heli_Light_01\Data\heli_light_01_ext_co.paa"
}, "" },
{ "Blueline", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_blueline_co.paa"
}, "" },
{ "Elliptical", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_elliptical_co.paa"
}, "" },
{ "Furious", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_furious_co.paa"
}, "" },
{ "Jeans Blue", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_jeans_co.paa"
}, "" },
{ "Speedy Redline", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_speedy_co.paa"
}, "" },
{ "Sunset", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_sunset_co.paa"
}, "" },
{ "Vrana", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_vrana_co.paa"
}, "" },
{ "Waves Blue", "civ", {
"\a3\air_f\Heli_Light_01\Data\Skins\heli_light_01_ext_wave_co.paa"
}, "" },
{ "COP", "cop", {
"textures\cop\veh\hbird_cop.jpg"
}, "" }
};
desarmar = false;
};
class B_Heli_Light_01_armed_F {
vItemSpace = 0;
conditions = "license_cop_cAir";
price = 300000;
price_cop = 120000;
price_samu = 90000;
textures[] = {
{ "COP", "cop", {
"textures\cop\veh\hbird_cop.jpg"
}, "" }
};
desarmar = false;
};
class C_Heli_Light_01_civil_F : B_Heli_Light_01_F {
vItemSpace = 80;
price = 2000000;
price_cop = 1000000;
price_samu = 500000;
conditions = "license_civ_pilot || {!(playerSide isEqualTo civilian)}";
};
class C_Heli_light_01_red_F {
vItemSpace = 90;
conditions = "license_med_mAir";
price = 245000;
price_cop = 98000;
price_samu = 73500;
textures[] = {};
desarmar = false;
};
class O_Heli_Light_02_unarmed_F {
vItemSpace = 250;
conditions = "license_civ_rebellic || license_civ_pilot || license_med_mAir || license_cop_cAir";
price = 3200000;
price_cop = 1600000;
price_samu = 800000;
textures[] = {
{ "RESGATE", "med", {
"textures\resgate\veh\orca_samu.jpg"
}, "" },
{ "Black", "cop", {
"\a3\air_f\Heli_Light_02\Data\heli_light_02_ext_co.paa"
}, "" },
{ "White / Blue", "civ", {
"\a3\air_f\Heli_Light_02\Data\heli_light_02_ext_civilian_co.paa"
}, "" },
{ "Digi Green", "reb", {
"\a3\air_f\Heli_Light_02\Data\heli_light_02_ext_indp_co.paa"
}, "" },
{ "Desert Digi", "reb", {
"\a3\air_f\Heli_Light_02\Data\heli_light_02_ext_opfor_co.paa"
}, "" }
};
desarmar = false;
};
};
|
#include <json/json.h>
#include "Player.h"
#include "Configure.h"
#include "AllocSvrConnect.h"
#include "Logger.h"
#include "GameCmd.h"
#include "GameApp.h"
#include "MoneyAgent.h"
#include "CoinConf.h"
#include "IProcess.h"
#include "Protocol.h"
int pase_json(Json::Value& value, const char* key, int def)
{
int v = def;
try{
v = value[key].asInt();
}
catch(...)
{
v = def;
}
return v;
}
std::string pase_json(Json::Value& value, const char* key, std::string def)
{
std::string v = def;
try{
v = value[key].asString();
}
catch(...)
{
v = def;
}
return v;
}
void Player::init()
{
id = 0;
memset(name, 0, sizeof(name));
memset(json, 0, sizeof(json));
m_nStatus = 0;
m_nTabIndex = -1;
m_nHallid = 0;
tid = -1;
source = 0;
m_bisCall = 0;
isonline = true;
m_bhasOpen = false;
m_nWin = 0;
m_nLose = 0;
m_nRunAway = 0;
m_nTie = 0;
isbankerlist =false;
isCanlcebanker = false;
m_lWinScore = 0;
m_lReturnScore = 0;
tax = 0;
//memset(m_lResultArray, 0, sizeof(m_lResultArray));
memset(m_lBetArray, 0, sizeof(m_lBetArray));
m_lTempScore = 0;
m_lLostScore = 0;
m_nLastBetTime = 0;
m_seatid = 0;
}
void Player::reset()
{
m_lWinScore = 0;
m_lReturnScore = 0;
m_bisCall = 0;
tax = 0;
m_lLostScore = 0;
memset(m_lBetArray, 0, sizeof(m_lBetArray));
//memset(m_lResultArray, 0, sizeof(m_lResultArray));
}
void Player::login()
{
short clevel = Configure::getInstance()->m_nLevel;
isonline = true;
if(strlen(json)>=2 && json[0]=='{')
{
Json::Reader reader;
Json::Value value;
if (reader.parse(json, value))
{
this->cid = pase_json(value,"cid",0);
this->sid = pase_json(value,"sid",0);
this->pid = pase_json(value,"pid",0);
this->gid = pase_json(value,"gameid",0);
//是机器人则用传过来的战绩
//if(source == 30)
//{
int totalNum = pase_json(value,"totalNum",20);
int winNum = pase_json(value,"winNum",5);
string link = pase_json(value,"picUrl","http://192.126.114.225/ucenter/data/icon/manphoto.png");
strcpy(this->headlink, link.c_str());
this->m_nWin = winNum;
this->m_nLose = totalNum - winNum;
//}
}
}
else
{
//_LOG_ERROR_("json parse error [%s]\n", json);
}
AllocSvrConnect::getInstance()->userEnterGame(this);
this->setEnterTime(time(NULL));
this->m_nLastBetTime = time(NULL);
}
void Player::leave(bool isSendToUser)
{
if(isSendToUser)
{
AllocSvrConnect::getInstance()->userLeaveGame(this);
}
IProcess::UpdateDBActiveTime(this);
OutputPacket respone;
respone.Begin(UPDATE_LEAVE_GAME_SERVER);
respone.WriteInt(this->id);
respone.End();
if(this->source != 30)
{
if (MoneyServer()->Send(&respone) < 0)
{
ULOGGER(E_LOG_ERROR, this->id) << "Send request to MoneyServer Error";
}
}
IProcess::UpdateDBActiveTime(this);
this->m_nStatus = STATUS_PLAYER_LOGOUT;
this->tid = -1;
this->m_nTabIndex = -1;
ULOGGER(E_LOG_DEBUG , this->id) << "clear player obj info, set status STATUS_PLAYER_LOGOUT, the next user can use this obj again";
}
void Player::enter()
{
AllocSvrConnect::getInstance()->userUpdateStatus(this, this->m_nStatus);
this->setEnterTime(time(NULL));
}
bool Player::notBetCoin()
{
ULOGGER(E_LOG_INFO, id) << "bet array[0] = " << m_lBetArray[0];
if(m_lBetArray[0] != 0)
return false;
return true;
}
|
#define F_CPU 16000000
#include<avr/io.h>
#include<avr/interrupt.h>
#include<util/delay.h>
#include <ads1292r.h>
#include <SPI.h>
ads1292r ADS1292; // define class
volatile uint8_t SPI_Dummy_Buff[30];
uint8_t DataPacketHeader[16];
volatile signed long s32DaqVals[8];
uint8_t data_len = 8;
volatile byte SPI_RX_Buff[15] ;
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile bool ads1292dataReceived =false;
unsigned long uecgtemp = 0;
signed long secgtemp=0;
int i,j;
byte k = 0;
byte tmpstr[5];
byte zsync = 0;
byte wait = 0;
byte cycle = 0;
char c;
float temp=0.0;
void setup()
{
//USART1 INIT - SpO2 INIT
UCSR1B = 0x00;
UCSR1A = 0x00;
UCSR1C = 0x06;
UBRR1L = 0x08;
UBRR1H = 0x00;
UCSR1B = 0x98;
//USART0 INIT - Data Transmission To PC
Serial.begin(9600);
//ECG Shield INIT
pinMode(ADS1292_DRDY_PIN, INPUT); //6
pinMode(ADS1292_CS_PIN, OUTPUT); //7
pinMode(ADS1292_START_PIN, OUTPUT); //5
pinMode(ADS1292_PWDN_PIN, OUTPUT); //4
ADS1292.ads1292_Init(); //initalize ADS1292 slave
//LM35 INIT
pinMode(A0, OUTPUT);
pinMode(A1, INPUT);
pinMode(A2, OUTPUT);
digitalWrite(A0, HIGH);
digitalWrite(A2, LOW);
}
void loop()
{
if((digitalRead(ADS1292_DRDY_PIN)) == LOW) // Sampling rate is set to 125SPS ,DRDY ticks for every 8ms
{
SPI_RX_Buff_Ptr = ADS1292.ads1292_Read_Data(); // Read the data,point the data to a pointer
for(i = 0; i < 9; i++)
{
SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i); // store the result data in array
}
ads1292dataReceived = true;
}
if(ads1292dataReceived == true) // process the data
{
j=0;
for(i=0;i<6;i+=3) // data outputs is (24 status bits + 24 bits Respiration data + 24 bits ECG data)
{
uecgtemp = (unsigned long) ( ((unsigned long)SPI_RX_Buff[i+3] << 16) | ( (unsigned long) SPI_RX_Buff[i+4] << 8) | (unsigned long) SPI_RX_Buff[i+5]);
uecgtemp = (unsigned long) (uecgtemp << 8);
secgtemp = (signed long) (uecgtemp);
secgtemp = (signed long) (secgtemp >> 8);
s32DaqVals[j++]=secgtemp;
}
DataPacketHeader[1] = s32DaqVals[1]; // 4 bytes ECG data
DataPacketHeader[2] = s32DaqVals[1]>>8;
DataPacketHeader[3] = s32DaqVals[1]>>16;
DataPacketHeader[4] = s32DaqVals[1]>>24;
DataPacketHeader[5] = s32DaqVals[0]; // 4 bytes Respiration data
DataPacketHeader[6] = s32DaqVals[0]>>8;
DataPacketHeader[7] = s32DaqVals[0]>>16;
DataPacketHeader[8] = s32DaqVals[0]>>24;
Serial.println("1101");
for(i=1; i<9; i++)
{
Serial.println(DataPacketHeader[i]); // transmit the data over USB
}
}
ads1292dataReceived = false;
SPI_RX_Buff_Count = 0;
temp = (5.0 * analogRead(A1) * 100.0) / 1024;
}
ISR(USART1_RX_vect)
{
c = UDR1;
if((byte)c == 0x00)
{
cycle++; /* wait a few zero synch bytes */
zsync = 1;
i = 0;
}
if(zsync == 1 && cycle == 10)
{
if((byte)c != 0xFF)
{
tmpstr[i] = c;
if(i == 3)
{
Serial.println(tmpstr[1]);
Serial.println(tmpstr[2]);
Serial.println(tmpstr[3]);
Serial.println(temp);
zsync = 0;
wait = 1;
cycle = 0;
}
i++;
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2004-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** \author { Anders Oredsson <anderso@opera.com> }
*/
#include "core/pch.h"
#ifdef SUPPORT_PROBETOOLS
#include "modules/probetools/src/probeidentifiers.h"
#include "modules/probetools/src/probenamemapper.h"
#include "modules/probetools/generated/probedefines.h"
#include "modules/hardcore/mh/messages.h"
// Put probe index_parameter name-mappings into this method.
// Only usable in special cases, returns false if no name was copied
bool
OpProbeNameMapper::GetMappedProbeParameterName(OpProbeIdentifier& probe_id, char* targetBuffer, size_t targetBufferLen)
{
bool result = false;
switch(probe_id.get_location())
{
case OP_PROBE_HC_MSG:
op_snprintf(targetBuffer, targetBufferLen, "%s",
GetStringFromMessage(static_cast<OpMessage>(probe_id.get_index_parameter())));
result = true;
break;
#ifdef HC_MODULE_INIT_PROFILING
case OP_PROBE_HC_INIT_MODULE:
op_snprintf(targetBuffer, targetBufferLen,
"OP_PROBE_HC_INIT_MODULE(%s)",
g_opera->module_names[probe_id.get_index_parameter()]);
result = true;
break;
case OP_PROBE_HC_DESTROY_MODULE:
op_snprintf(targetBuffer, targetBufferLen,
"OP_PROBE_HC_DESTROY_MODULE(%s)",
g_opera->module_names[probe_id.get_index_parameter()]);
result = true;
break;
#endif // HC_MODULE_INIT_PROFILING
#ifdef GADGET_SUPPORT
case OP_PROBE_GADGETS_ISTHISA:
{
const char* type_name = "unknown";
switch (probe_id.get_index_parameter())
{
#ifdef WEBSERVER_SUPPORT
case URL_UNITESERVICE_INSTALL_CONTENT: type_name = "unite_service"; break;
#endif // WEBSERVER_SUPPORT
#ifdef EXTENSION_SUPPORT
case URL_EXTENSION_INSTALL_CONTENT: type_name = "extension"; break;
#endif // EXTENSION_SUPPORT
case URL_GADGET_INSTALL_CONTENT: type_name = "gadget"; break;
default:
OP_ASSERT(!"Unknown gadget install content type");
}
op_snprintf(targetBuffer, targetBufferLen,
"OP_PROBE_GADGETS_ISTHISA(%s)", type_name);
result = true;
break;
}
#endif // GADGET_SUPPORT
}
// return what we found
return result;
}
#endif
|
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
CLASS_DECLARATION( idForce, idForce_Constant )
END_CLASS
/*
================
idForce_Constant::idForce_Constant
================
*/
idForce_Constant::idForce_Constant( void ) {
force = vec3_zero;
physics = NULL;
id = 0;
point = vec3_zero;
}
/*
================
idForce_Constant::~idForce_Constant
================
*/
idForce_Constant::~idForce_Constant( void ) {
}
/*
================
idForce_Constant::Save
================
*/
void idForce_Constant::Save( idSaveGame *savefile ) const {
savefile->WriteVec3( force );
// TOSAVE: idPhysics * physics
savefile->WriteInt( id );
savefile->WriteVec3( point );
}
/*
================
idForce_Constant::Restore
================
*/
void idForce_Constant::Restore( idRestoreGame *savefile ) {
// Owner needs to call SetPhysics!!
savefile->ReadVec3( force );
savefile->ReadInt( id );
savefile->ReadVec3( point );
}
/*
================
idForce_Constant::SetPosition
================
*/
void idForce_Constant::SetPosition( idPhysics *physics, int id, const idVec3 &point ) {
this->physics = physics;
this->id = id;
this->point = point;
}
/*
================
idForce_Constant::SetForce
================
*/
void idForce_Constant::SetForce( const idVec3 &force ) {
this->force = force;
}
/*
================
idForce_Constant::SetPhysics
================
*/
void idForce_Constant::SetPhysics( idPhysics *physics ) {
this->physics = physics;
}
/*
================
idForce_Constant::Evaluate
================
*/
void idForce_Constant::Evaluate( int time ) {
idVec3 p;
if ( !physics ) {
return;
}
p = physics->GetOrigin( id ) + point * physics->GetAxis( id );
physics->AddForce( id, p, force );
}
/*
================
idForce_Constant::RemovePhysics
================
*/
void idForce_Constant::RemovePhysics( const idPhysics *phys ) {
if ( physics == phys ) {
physics = NULL;
}
}
|
#include "State.h"
#include "GameScene.h"
void RunOnBallState::execute(GameScene *gameScene)
{
if (gameScene->isRunFinish())
{
gameScene->runFinish();
}
else
{
gameScene->runOnBall();
}
}
void PassBallState::execute(GameScene *gameScene)
{
if (gameScene->isPassFinish())
{
gameScene->passFinish();
}
else
{
gameScene->passBall();
}
}
void ReceiveBallState::execute(GameScene *gameScene)
{
if (gameScene->isReceiveFinish())
{
gameScene->receiveFinish();
}
}
|
//知识点:树形DP
/*
题目要求:
求一个树上点的点集 a,
使 ai != father[aj] (i,j ∈ [1,n])
求此点集 的最大权值和
分析题意:
对于一个点,
选择它 或 不选择它
只会对其 直接的儿子结点 产生影响
也就是说,
如果其直系儿子节点的状态已经确定
就可以推出 该点的状态
算法实现:
设: f[i] 表示 选择第 i 个点后,其子树的最大权值和
g[i]表示 , 不选择第i个点,其子树的最大权值和
那么对于一个子树的根节点 i,
及其 直系儿子结点 集合 son
其状态转移方程为:
f[i] = r[i] + ∑(g[v]) (v∈ son);
g[i] = ∑max(f[v],g[v]) (v∈ son);
对于根节点最后的状态有两种情况
答案只需在 f[root] 与 g[root]取最大值即可
注意的点:
由于可能出现负点权
所以有时选择此点 ,
比不选择此点更劣
要注意进行判断
*/
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#define int long long
const int MARX = 6e3+10;
//=============================================================
struct edge
{
int u,v,ne;
}e[MARX];
int n,num,root,head[MARX],in[MARX];//graph building
int r[MARX] , f[MARX],g[MARX];
//f[i]表示i参加的以i为根节点的子树的最大权值和,g[i]为不参加
//=============================================================
inline int read()
{
int s=1, w=0; char ch=getchar();
for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1;
for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0';
return s*w;
}
void add(int u,int v)//建图
{
e[++num].u=u,e[num].v=v;
e[num].ne=head[u],head[u]=num;
}
void dfs(int u)
{
int sum1=0,sum2=0;
for(int i=head[u];i;i=e[i].ne)
{
dfs(e[i].v);//优先更新儿子结点
sum1+=std::max(f[e[i].v],g[e[i].v]);//求得两和
sum2+=g[e[i].v];
}
f[u]=sum2+r[u] , g[u]=sum1;//更新子树根节点的值
// printf("%lld %lld %lld\n",u,f[u],g[u]);
}
//=============================================================
signed main()
{
n=read();
for(int i=1;i<=n;i++) r[i]=read();
for(int i=1;i<n;i++)
{
int v=read(),u=read();
add(u,v);
in[v]++;//入度++
}
for(int i=1;i<=n;i++)//寻找根节点
if(!in[i]) {root=i;break;}
dfs(root);
printf("%lld",std::max(f[root],g[root]));//选择最终更优的状态
}
|
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Please enter the text and quit with #: " << endl;
cin >> ch;
while (ch != '#') { // blank,制表符,回车都不会被计入
cout << ch;
++count;
cin >> ch;
}
cout << endl << count << " characters read\n";
cin.ignore(1024, '\n'); // 将上一段程序的结尾回车影响消除
count = 0;
cout << "Please enter the text and quit with #: " << endl;
cin.get(ch); // get可以得到输入的下一个字符,包括空格
while (ch != '#') {
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " characters read\n";
cin.ignore(1024, '\n'); // 将上一段程序的结尾回车影响消除
count = 0;
cout << "Please enter the text and quit with EOF: " << endl;
cin.get(ch);
while (cin.fail() == false) { // quit with EOF(Ctrl+Z)
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " characters read \n";
cin.ignore(1024, '\n'); // 将上一段程序的结尾回车影响消除
cin.clear();
count = 0;
cout << "Please enter the text and quit with EOF: " << endl;
while (cin.get(ch)) { // cin.get()这个表达式的值是你输入的那个字符
cout << ch; // cin可以作为bool值,当最后一次读取成功,cin==true,而cin.get(char)的返回值是cin,因此可以简化程序像这样
++count;
}
cout << endl << count << " characters read \n";
cin.clear();
while (cin.get() != 'q') {
;
}
return 0;
}
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//#include <dequeue>
struct Node {
int data;
Node *left;
Node *right;
Node(int a):data(a), left(NULL), right(NULL) {}
};
void insert_bst(Node **root, int data)
{
Node *new_node = new Node(data);
Node **node = root;
while (*node) {
if (data < (*node)->data)
node = &(*node)->left;
else
node = &(*node)->right;
}
*node = new_node;
}
void print_bst(Node *root) {
if (root == NULL) return;
print_bst(root->left);
printf("%d " , root->data);
print_bst(root->right);
}
/*
void print_tree(Node *node) {
dequeue<Node*> queue;
queue.push_back(node);
while(!queue.empty()) {
Node *item = queue.front();
queue.pop_front();
}
}
*/
/* Approach
* generate list for left tree call it as l1
* generate list for right tree call it as l2
* sandwitch node between l1 and l2 = l1 + node + l2
* keep doing it recursively.
*/
void bst2dll(Node *node, Node **head, Node **tail) {
Node *h1,*t1,*h2,*t2;
// If this is the NULL node , then do not return any list
if (node == NULL) {
if (head) *head = NULL;
if (tail) *tail = NULL;
return;
}
// recursively generate list for left and right tree
bst2dll(node->left, &h1, &t1);
bst2dll(node->right, &h2, &t2);
// add the node between two lists.
node->left = t1; if(t1) t1->right = node;
node->right = h2; if(h2) h2->left = node;
// If right and left tree are empty then
// return tree with one element only
// else return head or left list as new head
// and tail of right list as new tail.
if (head) *head = h1? h1 : node;
if (tail) *tail = t2? t2 : node;
}
void print_list(Node *head) {
while (head) {
printf("%d ", head->data);
head = head->right;
}
printf("\n");
}
int main(int argc, char **argv)
{
Node *root = NULL;
Node *dl, *tl;
int v;
for(int i = 0; i < 10; i++) {
v = rand() % 100;
printf("%d ", v);
insert_bst(&root, v);
}
printf("\n");
print_bst(root);
printf("\n");
bst2dll(root, &dl, &tl);
printf("%p %p\n", dl, tl);
print_list(dl);
return 0;
};
|
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> combinations;
vector<int> combination;
combinationSum(k, n, 0, combinations, combination);
return combinations;
}
private:
void combinationSum(int k, int n, int begin,
vector<vector<int>> &combinations, vector<int> &combination)
{
if (combination.size() == k) {
if (n == 0) {
combinations.push_back(combination);
}
return;
}
for (int i = begin; i < 9 && n >= i + 1; i++) {
combination.push_back(i + 1);
combinationSum(k, n - (i + 1), i + 1, combinations, combination);
combination.pop_back();
}
}
};
|
#pragma once
#include <iosfwd>
template <typename T>
class Point2 {
private:
T x, y;
public:
bool CheckForNaNs() const { return (std::isnan(x) || std::isnan(y)); };
inline Point2()
{ x = 0; y = 0;};
inline Point2(T a, T b) {
x = a; y = b;
assert(!CheckForNaNs());
};
inline T getX() {
return x;
}
inline T getY() {
return y;
}
inline T getZ() {
return z;
}
Point2<T> operator +( Vector2<T> &vec) const
{ return Point2<T>(x + vec.getX(), y + vec.getY());};
Point2<T> operator +=( Vector2<T> vec) const {
x += vec.x; y += vec.y;
return *this;
};
Point2<T> operator -( Vector2<T> &vec) const
{ return Point2<T>(x - vec.getX(), y - vec.getY());};
Point2<T> operator -=( Vector2<T> &vec) const {
x -= vec.getX(); y -= vec.getY();
return *this;
};
Vector2<T> operator -(const Point2<T> &poi) const
{ return Vector2<T>(x - poi.x, y - poi.y);};
inline float getDistance(const Point2<T> &p2)
{ return (*this - p2).getLen();}
inline float getDistanceSquared(const Point2<T> &p2)
{return (*this - 2).getLenSquared();}
};
template <typename T>
class Point3 {
private:
T x, y, z;
public:
bool CheckForNaNs() const { return (std::isnan(x) || std::isnan(y) || std::isnan(z)); };
inline Point3()
{ x = 0; y = 0; z = 0;};
inline Point3(Vector3<T> &a) {
x = a.getX();
y = a.getY();
z = a.getZ();
}
inline Point3(T a, T b, T c){
x = a; y = b; z = c;
assert(!CheckForNaNs());
};
inline T getX() {
return x;
}
inline T getY() {
return y;
}
inline T getZ() {
return z;
}
Point3<T> operator +(Vector3<T> &vec) const
{ return Point3<T>(x + vec.getX(), y + vec.getY(), z + vec.getZ());};
Point3<T> operator +=(Vector3<T> vec) const {
x += vec.getX(); y += vec.getY(); z += vec.getZ();
return *this;
}
Point3<T> operator -( Vector3<T> &vec) const
{ return Point3<T>(x - vec.getX(), y - vec.getY(), z - vec.getZ());}
Point3<T> operator -=( Vector3<T> &vec) const{
x -= vec.getX(); y -= vec.getY(); z -= vec.getZ();
return *this;
};
Vector3<T> operator -(const Point3<T> &poi) const
{ return Vector3<T>(x - poi.x, y - poi.y, z - poi.z);};
inline operator Point2<T>() const
{ return Point2<T>(x, y);};
inline operator Vector3<T>() const
{ return Vector3<T>(x, y, z); };
inline float getDistance(const Point3<T> &p2)
{ return (*this - p2).getLen();}
inline float getDistanceSquared(const Point3<T> &p2)
{ return (*this-2).getLenSquared();}
};
namespace point {
template <typename T>
inline float Distance(const Point3<T> &p1, const Point3<T> &p2)
{return (p1 - p2).getLen();}
template <typename T>
inline float Distance(const Point2<T> &p1, const Point2<T> &p2)
{return (p1 - p2).getLen();}
template <typename T>
inline float DistanceSquared(const Point3<T> &p1, const Point3<T> &p2)
{return (p1 - p2).getLenSquared();}
template <typename T>
inline float DistanceSquared(const Point2<T> &p1, const Point2<T> &p2)
{return (p1 - p2).getLenSquared();}
template <typename T>
Point3<T> Lerp(float a, const Point3<T> &p1, const Point3<T> &p2)
{return (1-a)*p1+t*p2;}
template <typename T>
Point2<T> Lerp(float a, const Point2<T> &p1, const Point2<T> &p2)
{return (1-a)*p1+t*p2;}
}
typedef Point2<float> Point2f;
typedef Point2<int> Point2i;
typedef Point3<float> Point3f;
typedef Point3<int> Point3i;
|
#include "EnemySnake.h"
#include<shadyengine/random.h>
using namespace shady_engine;
EnemySnake::EnemySnake(
std::shared_ptr<shady_engine::sprite_renderer> pRenderer,
std::shared_ptr<shady_engine::texture2D> pTexture,
const glm::vec2& pHeadPosition,
const glm::vec2& pHeadVelocity,
float pSpeed,
float pRadius,
int pStartLength,
const glm::vec4& pColor,
bool pSecured
)
:
mRenderer(pRenderer),
mRadius(pRadius),
mSize(2 * mRadius),
mColor(pColor),
mSpeed(pSpeed),
mTexture(pTexture),
mSecured(pSecured)
{
mUpdateVelocityTime = random::getInstance()->real(3.0f, 6.0f);
Block head;
head.position = pHeadPosition;
head.velocity = pHeadVelocity;
head.center = head.position + (mSize*.5f);
head.collider = AABB(head.position, mSize);
mBlocks.push_back(head);
for (int i = 0; i < pStartLength; i++)
pushNewBlock();
}
EnemySnake::~EnemySnake()
{
mBlocks.clear();
}
void EnemySnake::pushNewBlock()
{
Block lastBlock = (*(mBlocks.end() - 1));
Block newBlock;
newBlock.position = lastBlock.position + (-lastBlock.velocity*10.0f);
newBlock.center = newBlock.position + (mSize*.5f);
newBlock.collider = AABB(newBlock.position, mSize);
mBlocks.push_back(newBlock);
}
void EnemySnake::negateVelocity()
{
Block& head = (*mBlocks.begin());
head.velocity *= -1.0f;
}
void EnemySnake::tick(float pDT)
{
Block& head = (*mBlocks.begin());
mUpdateVelocityTime -= pDT;
if (mUpdateVelocityTime <= 0.0f)
{
float angle = random::getInstance()->real(0.0f,360.0f);
head.velocity = glm::vec2(
cos(glm::radians(angle)), sin(glm::radians(angle)));
mUpdateVelocityTime = random::getInstance()->real(3.0f, 6.0f);
}
head.lastPosition = head.position;
head.position += ((head.velocity*mSpeed)*pDT);
head.center = head.position + (mSize*.5f);
head.collider.update(head.position, mSize);
for (auto iter = (mBlocks.begin() + 1); iter != mBlocks.end(); iter++)
{
Block& child = (*iter);
Block& parent = (*(iter - 1));
child.velocity = glm::normalize(
parent.center - child.center
);
child.lastPosition = child.position;
child.position = parent.position + (-child.velocity*10.0f);
child.center = child.position + (mSize*0.5f);
child.collider.update(child.position, mSize);
}
}
void EnemySnake::render(const glm::mat4 & pProjection, const glm::mat4 & pView)
{
auto head = *(mBlocks.begin());
mRenderer->draw_image(pProjection, pView, mTexture, head.position, mSize, 0.0f);
}
|
/**********************************************************************
* Felix Winterstein, Imperial College London
*
* File: lloyds.cpp
*
* Revision 1.01
* Additional Comments: distributed under a BSD license, see LICENSE.txt
*
**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h>
#include <math.h>
#include "lloyds.h"
// kernel function of lloyd's algorithm
void lloyds(data_type_short *points, centre_type *centres, uint k, uint n, bool last_run, data_type_short *output_array)
{
data_type_short centre_positions[KMAX];
for (uint i=0; i<k; i++) {
centre_positions[i] = centres[i].position_short;
}
// consider all data points
for (uint i=0; i<n; i++) {
uint idx;
data_type_short closest_centre;
// search for closest centre to this point
closest_to_point_direct_fi_short(points[i], centre_positions, k, &idx, &closest_centre);
coord_type tmp_dist;
compute_distance_fi_short(points[i], closest_centre, &tmp_dist);
centres[idx].count_short++;
// update centre buffer with info of closest centre
for (uint d=0; d<D; d++) {
centres[idx].wgtCent.value[d] += points[i].value[d];
}
centres[idx].sum_sq += tmp_dist;
if (last_run == true) {
output_array[i] = closest_centre;
}
}
}
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
long long n, a[200000], gcd, maxi = -1, ans;
vector<long long> changes;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
maxi = max(maxi, a[i]);
}
for (int i = 0; i < n; i++)
{
if (a[i] != maxi)
{
changes.push_back(maxi - a[i]);
}
}
if (changes.size() == 1)
{
cout << 1 << " " << changes[0] << endl;;
exit(0);
}
gcd = changes[0];
for (int i = 1; i < changes.size(); i++)
gcd = __gcd(changes[i], gcd);
ans = 0;
for (int i = 0; i < changes.size(); i++)
ans += changes[i] / gcd;
cout << ans << " " << gcd << endl;
}
|
#include <iostream>
#include "Alien.h"
int main()
{
Alien alien(20, 20, 'm');
std::cout << alien.getWeight();
return 0;
}
|
/*
Name : Aman Jain
Date : 16-07-2020
Question-> https://practice.geeksforgeeks.org/problems/count-ways-to-reach-the-nth-stair/0
In the given problem we have to find the no. of ways in which we can reach the top of ladder from the bottom, where
n = total number of steps in ladder.
k = maximum numbers of steps that can be taken at a time.
Time complexity : O(nk)
Space Complexity : O(n)
*/
#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
long long ladders(int n,long long dp[],int k){
if(n<0)
return 0;
if(n==0 || n==1)
return 1;
if(dp[n]!=0){
return dp[n];
}
long long ans=0;
for(int i=k; i>0 ;i--)
ans+=ladders(n-i,dp,k);
dp[n]=ans;
return dp[n]%mod;
}
int main(){
int t;
cin>>t;
while(t--){
int n,k;
cin>>n>>k;
long long dp[100005]={0};
cout<<ladders(n,dp,k)<<endl;
}
}
|
// Copyright (c) 2016 Daniel Bourgeois
//
// 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)
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <pika/testing.hpp>
#include <iostream>
#include <map>
#include <set>
#include <utility>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
int pika_main()
{
using pair_type = std::pair<std::map<int, int>, std::set<int>>;
using pair_fut_type = std::pair<pika::future<std::map<int, int>>, pika::future<std::set<int>>>;
std::map<int, int> mm;
// fill mm with arbitrary values
mm[123] = 321;
mm[999] = 999;
mm[6] = 43556;
// fill ss with arbitrary values
std::set<int> ss{0, 1, 10, 100, 101, 2000};
pair_type p = std::make_pair(mm, ss);
pika::future<pair_type> f_pair = pika::make_ready_future(p);
// given a future of a pair, get a pair of futures
pair_fut_type pair_f = pika::split_future(std::move(f_pair));
// see if the values of mm2 and ss2 are the same
std::map<int, int> mm2 = pair_f.first.get();
std::cout << "Printing map: ";
for (auto val : mm2) std::cout << "(" << val.first << ", " << val.second << ") ";
std::cout << std::endl;
PIKA_TEST_EQ(mm.size(), mm2.size());
std::map<int, int>::const_iterator mm_it = mm.begin(), mm_it2 = mm2.begin();
std::map<int, int>::const_iterator mm_end = mm.end(), mm_end2 = mm2.end();
for (/**/; mm_it != mm_end && mm_it2 != mm_end2; ++mm_it, ++mm_it2)
{
PIKA_TEST_EQ((*mm_it).first, (*mm_it2).first);
PIKA_TEST_EQ((*mm_it).second, (*mm_it2).second);
}
std::set<int> ss2 = pair_f.second.get();
std::cout << "Printing set: ";
for (auto val : ss2) std::cout << val << " ";
std::cout << std::endl;
PIKA_TEST_EQ(ss.size(), ss2.size());
std::set<int>::const_iterator ss_it = ss.begin(), ss_it2 = ss2.begin();
std::set<int>::const_iterator ss_end = ss.end(), ss_end2 = ss2.end();
for (/**/; ss_it != ss_end && ss_it2 != ss_end2; ++ss_it, ++ss_it2)
{
PIKA_TEST_EQ(*ss_it, *ss_it2);
}
return pika::finalize();
}
int main(int argc, char* argv[])
{
PIKA_TEST_EQ(pika::init(pika_main, argc, argv), 0);
return 0;
}
|
/**
* Peripheral Definition File
*
* FLASH - Flash memory controller
*
* MCUs containing this peripheral:
* - STM32F0xx
*/
#pragma once
#include <cstdint>
#include <cstddef>
namespace io {
struct Flash {
/** Flash access control register
*/
struct Acr {
Acr(const uint32_t raw=0) { r = raw; }
struct Bits {
uint32_t LATENCY : 3; // Latency
uint32_t : 1;
uint32_t PRFTBE : 1; // Prefetch buffer enable
const uint32_t PRFTBS : 1; // Prefetch buffer status
uint32_t : 26;
};
union {
uint32_t r;
Bits b;
};
};
/** Flash status register
*/
struct Sr {
Sr(const uint32_t raw=0) { r = raw; }
struct Bits {
const uint32_t BSY : 1; // Busy
uint32_t : 1;
uint32_t PGERR : 1; // Programming error
uint32_t : 1;
uint32_t WRPRTERR : 1; // Write protection error
uint32_t EOP : 1; // End of operation
uint32_t : 26;
};
union {
uint32_t r;
Bits b;
};
};
/** Flash control register
*/
struct Cr {
Cr(const uint32_t raw=0) { r = raw; }
struct Bits {
uint32_t PG : 1; // Programming
uint32_t PER : 1; // Page erase
uint32_t MER : 1; // Mass erase
uint32_t : 1;
uint32_t OPTPG : 1; // Option byte programming
uint32_t OPTER : 1; // Option byte erase
uint32_t STRT : 1; // Start
uint32_t LOCK : 1; // Lock
uint32_t : 1;
uint32_t OPTWRE : 1; // Option byte write enable
uint32_t ERRIE : 1; // Error interrupt enable
uint32_t : 1;
uint32_t EOPIE : 1; // End of operation interrupt enable
uint32_t OBL_LAUNCH : 1; // Force option byte loading
uint32_t : 18;
};
union {
uint32_t r;
Bits b;
};
};
/** Flash option byte register
*/
struct Obr {
Obr(const uint32_t raw=0) { r = raw; }
struct Bits {
const uint32_t OPTERR : 1; // Option byte error
const uint32_t RDPRT : 2; // Read protection level status
uint32_t : 5;
const uint32_t WDG_SW : 1;
const uint32_t RST_STOP : 1;
const uint32_t RST_STDBY : 1;
const uint32_t BOOT0 : 1;
const uint32_t BOOT1 : 1;
const uint32_t VDDA_MONITOR : 1;
const uint32_t RAM_PARITY_CHECK : 1;
const uint32_t BOOT_SEL : 1;
const uint32_t DATA0 : 8;
const uint32_t DATA1 : 8;
};
union {
uint32_t r;
Bits b;
};
};
volatile Acr ACR; // Flash access control register
volatile uint32_t KEYR; // Flash key register
volatile uint32_t OPTKEYR; // Flash option key register
volatile Sr SR; // Flash status register
volatile Cr CR; // Flash control register
volatile uint32_t AR; // Flash address register
uint32_t __res0;
volatile Obr OBR; // Flash option byte register
volatile uint32_t WRPR; // Write protection register
static const size_t BASE = 0x40022000;
};
static Flash &FLASH = *reinterpret_cast<Flash *>(Flash::BASE);
}
|
/*
* Lanq(Lan Quick)
* Solodov A. N. (hotSAN)
* 2016
* LqPrtScan (LanQ Port Scanner) - Scan ports of local or remote machine. Creates sockets and just trying connect
*/
#include "LqPrtScan.hpp"
#include "LqWrkBoss.hpp"
#include "LqTime.h"
#include "LqStrSwitch.h"
#include "LqFile.h"
#include "LqFileTrd.h"
#include "LqSbuf.h"
#include "LqCp.h"
#include "LqLib.h"
#include "LqStr.hpp"
#include "LqStr.hpp"
#include "LqDef.hpp"
#include "LqTime.hpp"
#include <stdint.h>
#include <stdlib.h>
#include <type_traits>
#include <vector>
struct ConnScan {
LqConn Conn;
LqEvntFd LiveTime;
uint16_t Port;
std::atomic<uint8_t> CountPtr;
LqLocker<uint8_t> Locker;
};
struct ProtoScan {
LqProto Proto;
std::atomic<uintptr_t> CountConn;
int WaitEvent;
LqPtdArr<uint16_t> OpenedPorts;
};
static void LQ_CALL ConnScanHandler(LqConn* Conn, LqEvntFlag Flag) {
if(!(Flag & LQEVNT_FLAG_ERR))
((ProtoScan*)Conn->Proto)->OpenedPorts.push_back(((ConnScan*)Conn)->Port);
LqClientSetClose(Conn);
}
static void LQ_CALL TimerHandler(LqEvntFd* Fd, LqEvntFlag Flag) {
LqClientSetClose(Fd);
}
static void LQ_CALL TimerEnd(LqEvntFd* TimerFd) {
ProtoScan* Proto;
ConnScan* Conn;
Conn = LqStructByField(ConnScan, LiveTime, TimerFd);
Conn->Locker.LockWrite();
if(Conn->CountPtr == 2)
LqClientSetClose(Conn);
Conn->CountPtr--;
if(Conn->CountPtr <= 0) {
auto Proto = ((ProtoScan*)Conn->Conn.Proto);
closesocket(Conn->Conn.Fd);
LqFastAlloc::Delete(Conn);
Proto->CountConn--;
LqEventSet(Proto->WaitEvent);
return;
}
Conn->Locker.UnlockWrite();
}
static void LQ_CALL EndProc(LqConn* Connection) {
ProtoScan* Proto;
ConnScan* Conn = (ConnScan*)Connection;
Conn->Locker.LockWrite();
if(Conn->CountPtr == 2)
LqClientSetClose(&Conn->LiveTime);
Conn->CountPtr--;
if(Conn->CountPtr <= 0) {
Proto = ((ProtoScan*)Conn->Conn.Proto);
closesocket(Conn->Conn.Fd);
LqFastAlloc::Delete(Conn);
Proto->CountConn--;
LqEventSet(Proto->WaitEvent);
return;
}
Conn->Locker.UnlockWrite();
}
LQ_EXTERN_CPP bool LQ_CALL LqPrtScanDo(LqConnAddr* Addr, std::vector<std::pair<uint16_t, uint16_t>>& PortRanges, int MaxScanConn, LqTimeMillisec ConnWait, std::vector<uint16_t>& OpenPorts) {
ProtoScan Proto;
LqConnAddr AddrLoc;
int Fd, Res, TimerFd;
ConnScan* Conn;
LqProtoInit(&Proto.Proto);
Proto.Proto.Handler = ConnScanHandler;
Proto.Proto.CloseHandler = EndProc;
if((Proto.WaitEvent = LqEventCreate(LQ_O_NOINHERIT)) == -1)
return -1;
Proto.CountConn = 0;
for(auto& i : PortRanges) {
for(auto j = i.first; j <= i.second; j++) {
if(Proto.CountConn >= MaxScanConn) {
lblWaitAgain:
LqPollCheckSingle(Proto.WaitEvent, LQ_POLLIN | LQ_POLLOUT, 60 * 2 * 1000);
LqEventReset(Proto.WaitEvent);
if(Proto.CountConn >= MaxScanConn)
goto lblWaitAgain;
}
if((Fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) == -1)
continue;
LqConnSwitchNonBlock(Fd, 1);
AddrLoc = *Addr;
if(AddrLoc.Addr.sa_family == AF_INET) {
AddrLoc.AddrInet.sin_port = htons(j);
} else if(AddrLoc.Addr.sa_family == AF_INET6) {
AddrLoc.AddrInet6.sin6_port = htons(j);
}
if((Res = connect(Fd, &AddrLoc.Addr, sizeof(AddrLoc))) == 0) {
Proto.OpenedPorts.push_back(j);
closesocket(Fd);
} else if(LQERR_IS_WOULD_BLOCK) {
Conn = LqFastAlloc::New<ConnScan>();
LqConnInit(Conn, Fd, &Proto.Proto, LQEVNT_FLAG_CONNECT | LQEVNT_FLAG_HUP);
TimerFd = LqTimerCreate(LQ_O_NOINHERIT);
LqTimerSet(TimerFd, ConnWait);
LqEvntFdInit(&Conn->LiveTime, TimerFd, LQEVNT_FLAG_RD, TimerHandler, TimerEnd);
Conn->CountPtr = 2;
Conn->Port = j;
Proto.CountConn++;
LqClientAdd((LqClientHdr*)&Conn->LiveTime, NULL);
LqClientAdd((LqClientHdr*)Conn, NULL);
} else {
closesocket(Fd);
}
}
}
while(Proto.CountConn > 0) {
LqPollCheckSingle(Proto.WaitEvent, LQ_POLLIN | LQ_POLLOUT, 60 * 2 * 1000);
LqEventReset(Proto.WaitEvent);
}
for(auto i : Proto.OpenedPorts)
OpenPorts.push_back(i);
LqFileClose(Proto.WaitEvent);
return true;
}
#define __METHOD_DECLS__
#include "LqAlloc.hpp"
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#define REP(i,n) for(int i=0; i<n; ++i)
#define REP_R(i,n,m) for(int i=m; i<n; ++i)
#define NMAX 50
#define MMAX 1230
int N, M;
bool graph[NMAX+1][MMAX+1];
int p[MMAX+1];
int q[MMAX+1];
bool visited[NMAX];
void dfs(int v);
int main() {
int a,b;
cin >> N >> M;
REP(i,M) {
scanf("%d %d", &a, &b);
p[i] = a-1; q[i] = b-1;
graph[a-1][b-1] = graph[b-1][a-1] = true;
}
int ans = 0;
REP(number,M) {
REP(i,N) visited[i] = false;
graph[p[number]][q[number]] = graph[q[number]][p[number]] = false;
dfs(0);
bool judge = false;
REP(i,N) {
if (!visited[i]) {
judge = true;
break;
}
}
if (judge) ans++;
graph[p[number]][q[number]] = graph[q[number]][p[number]] = true;
}
cout << ans << endl;
}
void dfs(int v) {
visited[v] = true;
REP(i,N) {
if (!graph[v][i]) continue;
if (visited[i]) continue;
dfs(i);
}
}
|
#pragma once
#include <algorithm>
#include <utility>
namespace MathiSMO {
namespace Concepts {
template<class V>
concept Vec = requires(V vec) {
vec.x;
vec.y;
};
template<typename Type>
concept Numeric = std::is_floating_point_v<Type> || std::is_integral_v<Type>;
}
template<typename Type, std::size_t Dimension>
class Vec;
using Vec2 = Vec<float, 2>;
using Vec3 = Vec<float, 3>;
using Vec4 = Vec<float, 4>;
using Vec2f = Vec<float, 2>;
using Vec3f = Vec<float, 3>;
using Vec4f = Vec<float, 4>;
using Vec2d = Vec<double, 2>;
using Vec3d = Vec<double, 3>;
using Vec4d = Vec<double, 4>;
using Vec2i = Vec<int, 2>;
using Vec3i = Vec<int, 3>;
using Vec4i = Vec<int, 4>;
template<Concepts::Numeric ...Num>
Vec(Num&& ...nums) -> Vec<std::common_type_t<Num...>, sizeof...(Num)>;
}
template<typename Type, std::size_t Dimension>
class MathiSMO::Vec {
static_assert(Dimension < 5);
static_assert(Dimension > 1);
};
// Vec2 ------------------------------------------------------------------------------------------
template<typename Type>
class MathiSMO::Vec<Type, 2> {
public:
constexpr static int Dimension = 2;
union {
struct { Type x, y; };
struct { Type r, g; };
};
[[nodiscard]] const Type* data() const {
const Type data[Dimension] {this->x, this->y};
return std::move(data);
}
template<Concepts::Vec Vec>
[[nodiscard]] constexpr auto operator+(Vec&& vec) const {
return MathiSMO::Vec<Type, Dimension>{
.x = this->x + vec.x,
.y = this->y + vec.y
};
}
template<Concepts::Numeric Num>
[[nodiscard]] constexpr auto operator+(Num&& value) const {
return MathiSMO::Vec<Type, Dimension>{
.x = this->x + value,
.y = this->y + value
};
}
};
// Vec3 ------------------------------------------------------------------------------------------
template<typename Type>
class MathiSMO::Vec<Type, 3> {
public:
constexpr static int Dimension = 3;
union {
struct { Type x, y, z; };
struct { Type r, g, b; };
};
[[nodiscard]] const Type* data() const {
const Type data[Dimension] {this->x, this->y, this->z};
return std::move(data);
}
template<Concepts::Vec Vec>
[[nodiscard]] constexpr auto operator+(Vec&& vec) const {
return MathiSMO::Vec<Type, Dimension>{
.x = this->x + vec.x,
.y = this->y + vec.y,
.z = this->z + vec.z
};
}
template<Concepts::Numeric Num>
[[nodiscard]] constexpr auto operator+(Num&& value) const {
return MathiSMO::Vec<Type, Dimension>{
.x = this->x + value,
.y = this->y + value,
.z = this->z + value
};
}
};
// Vec4 ------------------------------------------------------------------------------------------
template<typename Type>
class MathiSMO::Vec<Type, 4> {
public:
constexpr static int Dimension = 4;
union {
struct { Type x, y, z, w; };
struct { Type r, g, b, a; };
};
[[nodiscard]] const Type* data() const {
const Type data[Dimension] {this->x, this->y, this->z, this->w};
return std::move(data);
}
template<Concepts::Vec Vec>
[[nodiscard]] constexpr auto operator+(Vec&& vec) const {
return MathiSMO::Vec<Type, Dimension>{
.x = this->x + vec.x,
.y = this->y + vec.y,
.z = this->z + vec.z,
.w = this->w + vec.w
};
}
template<Concepts::Numeric Num>
[[nodiscard]] constexpr auto operator+(Num&& value) const {
return MathiSMO::Vec<Type, Dimension>{
.x = this->x + value,
.y = this->y + value,
.z = this->z + value,
.w = this->w + value
};
}
};
|
// SPDX-FileCopyrightText: 2021 Samuel Cabrero <samuel@orica.es>
//
// SPDX-License-Identifier: MIT
#include <Log.h>
#include "config.h"
#include "global.h"
#include "state.h"
TGlobal Global;
TGlobal::TGlobal() : m_state(&StateUnarmored) {
}
TState *TGlobal::getState() {
return m_state;
}
void TGlobal::setState(TState *state) {
m_state->exit();
Log.info("Change state to %s", state->name());
m_state = state;
m_state->enter();
}
|
/********************************************************************************
** Form generated from reading UI file 'groupconfigdialog.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_GROUPCONFIGDIALOG_H
#define UI_GROUPCONFIGDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
QT_BEGIN_NAMESPACE
class Ui_GroupConfigDialog
{
public:
QGridLayout *gridLayout;
QSpacerItem *verticalSpacer;
QLabel *label_2;
QPushButton *pushButton_2;
QLabel *label;
QLineEdit *lineEdit;
QPushButton *pushButton;
void setupUi(QDialog *GroupConfigDialog)
{
if (GroupConfigDialog->objectName().isEmpty())
GroupConfigDialog->setObjectName(QStringLiteral("GroupConfigDialog"));
GroupConfigDialog->resize(310, 241);
QFont font;
font.setPointSize(8);
GroupConfigDialog->setFont(font);
gridLayout = new QGridLayout(GroupConfigDialog);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout->addItem(verticalSpacer, 3, 0, 1, 1);
label_2 = new QLabel(GroupConfigDialog);
label_2->setObjectName(QStringLiteral("label_2"));
gridLayout->addWidget(label_2, 2, 0, 1, 1);
pushButton_2 = new QPushButton(GroupConfigDialog);
pushButton_2->setObjectName(QStringLiteral("pushButton_2"));
gridLayout->addWidget(pushButton_2, 4, 1, 1, 1);
label = new QLabel(GroupConfigDialog);
label->setObjectName(QStringLiteral("label"));
gridLayout->addWidget(label, 0, 0, 1, 1);
lineEdit = new QLineEdit(GroupConfigDialog);
lineEdit->setObjectName(QStringLiteral("lineEdit"));
gridLayout->addWidget(lineEdit, 1, 0, 1, 2);
pushButton = new QPushButton(GroupConfigDialog);
pushButton->setObjectName(QStringLiteral("pushButton"));
gridLayout->addWidget(pushButton, 4, 2, 1, 1);
QWidget::setTabOrder(pushButton, lineEdit);
QWidget::setTabOrder(lineEdit, pushButton_2);
retranslateUi(GroupConfigDialog);
QMetaObject::connectSlotsByName(GroupConfigDialog);
} // setupUi
void retranslateUi(QDialog *GroupConfigDialog)
{
GroupConfigDialog->setWindowTitle(QApplication::translate("GroupConfigDialog", "Dialog", Q_NULLPTR));
label_2->setText(QApplication::translate("GroupConfigDialog", "Icono", Q_NULLPTR));
pushButton_2->setText(QApplication::translate("GroupConfigDialog", "Cancelar", Q_NULLPTR));
label->setText(QApplication::translate("GroupConfigDialog", "Nombre", Q_NULLPTR));
pushButton->setText(QApplication::translate("GroupConfigDialog", "Aceptar", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class GroupConfigDialog: public Ui_GroupConfigDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_GROUPCONFIGDIALOG_H
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int n;
while(cin>>n)
{
int i, ar[200];
for(i=1; i<=n; i++)
{
cin>>ar[i];
}
for(int j=1; j<=n; j++)
{
for(i=1; i<=n; i++)
{
if(ar[i]==j)
cout<<i;
}
if(j==n)break;
cout<<" ";
}
cout<<endl;
}
return 0;
}
|
#include <iostream>
using namespace std;
bool isPrime(int n)
{
if (n <= 1)
return false;
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
bool isEmirp(int n)
{
if (isPrime(n) == false)
return false;
int rev = 0;
while (n != 0)
{
int d = n % 10;
rev = rev * 10 + d;
n /= 10;
}
return isPrime(rev);
}
int main()
{
int n;
cin>>n;
if (isEmirp(n) == true)
cout <<n<<" is an emirp number";
else
cout <<n<<" is not an emirp number";
return 0;
}
|
#ifndef UPDATE_APP_H
#define UPDATE_APP_H
#include "qt-tools/application.h"
#include <string>
class update_app : public application
{
public:
update_app (int argc, char** argv) : application (argc, argv) {}
bool run () override;
void at_exit () override;
private:
std::string start_program_;
bool error_ = false;
};
#endif // UPDATE_APP_H
|
#include <iostream>
using namespace std;
struct node{
int data;
struct node *left;
struct node *right;
};
class tree{
public:
struct node *newNode(int n){
node *nn=new node;
nn->data=n;
nn->left=NULL;
nn->right=NULL;
return (nn);
}
void preOrder(struct node *nn){
if(nn==NULL) return;
cout<<nn->data<<" ";
preOrder(nn->left);
preOrder(nn->right);
}
void inOrder(struct node *nn){
if(nn==NULL) return;
inOrder(nn->left);
cout<<nn->data<<" ";
inOrder(nn->right);
}
void postOrder(struct node *nn){
if(nn==NULL) return;
postOrder(nn->left);
postOrder(nn->right);
cout<<nn->data<<" ";
}
};
int main(){
tree t;
struct node * root = t.newNode(1);
root->left = t.newNode(2);
root->right = t.newNode(3);
root->left->left = t.newNode(4);
root->left->right = t.newNode(5);
t.preOrder(root);
cout<<endl;
t.inOrder(root);
cout<<endl;
t.postOrder(root);
}
|
#include "stage.h"
#include "demon.h"
#include<vector>
Stage::Stage()
{
Demon *e;
float positionEnemy [4][2]= {{400,350},{250,250},{250,350},{150,520}};
int nbEnemy = sf::Randomizer::Random(0, 4);
sf::Vector2f vecPos(0.f,0.f);
for(int i=0;i<nbEnemy;i++)
{
vecPos.x=positionEnemy[i][0];
vecPos.y=positionEnemy[i][1];
e= new Demon(vecPos,3, 1, 1, "sprites/demon.png");
lenemy.push_back(*e);
}
}
|
#include "Net/UdpSocket.h"
#include "Net/proto/cmd/SendProto.h"
#include "Net/proto/pb/cliReq.pb.h"
#include <thread>
#include <iostream>
using namespace std;
using namespace CPPClient::Net;
using namespace CPPClient::Net::Cmd;
int main(int argc, const char *argv[])
{
UdpSocket::connectServer("127.0.0.1", 4567);
SendProto::CliEnterRoom(10, "test");
int x;
cin >> x;
if (x == 0)
{
UdpSocket::closeUdpSocket();
}
this_thread::sleep_for(chrono::milliseconds(1000));
return 0;
}
|
#include "MenuMode.h"
MenuMode::MenuMode()
{
QJSEngine* engine = initScript();
initTextColors(engine);
delete engine;
widgetDistance = 10.0f;
totalCombobox=NULL;
mGui3D=NULL;
mMousePointerLayer=NULL;
mMousePointer=NULL;
Ogre::Viewport * _viewport= rEngine->m_pViewport;
mGui3D = new Gui3D::Gui3D(&mMyPurplePanelColors);
mGui3D->createScreen(_viewport, "purple", "mainScreen");
// Create a layer for the mousePointer
mNormalizedMousePosition = Ogre::Vector2(0.5, 0.5);
mMousePointerLayer = mGui3D->getScreen("mainScreen")->createLayer();
mMousePointer = mMousePointerLayer->createRectangle(_viewport->getActualWidth()/2,
_viewport->getActualHeight()/2, 12, 18);
mMousePointer->background_image("mousepointer");
_createDemoPanel();
rEngine->m_pLog->logMessage("Menu initialized");
}
void MenuMode::update(const Ogre::FrameEvent& evt)
{
panel->injectTime(evt.timeSinceLastFrame);
checkForNewHitbox();
}
void MenuMode::init()
{
panel->getGUILayer()->show();
Ogre::SceneNode* panelNode = panel->mNode;
panelNode->setPosition(rEngine->mFPC->getPosition());
panelNode->setOrientation(rEngine->mFPC->getOrientation());
panelNode->translate(0.0f,0.0f,-widgetDistance,Ogre::Node::TS_LOCAL);
}
bool MenuMode::keyPressed(const OIS::KeyEvent &keyEventRef)
{
panel->injectKeyPressed(keyEventRef);
return true;
}
bool MenuMode::keyReleased(const OIS::KeyEvent &keyEventRef)
{
input->keyReleased(keyEventRef);
panel->injectKeyReleased(keyEventRef);
return true;
}
bool MenuMode::mouseMoved(const OIS::MouseEvent &evt)
{
// Raycast for the actual panel
Ogre::Real xMove = static_cast<Ogre::Real>(evt.state.X.rel);
Ogre::Real yMove = static_cast<Ogre::Real>(evt.state.Y.rel);
Ogre::Viewport* mViewport = rEngine->m_pViewport;
mNormalizedMousePosition.x += xMove / mViewport->getActualWidth();
mNormalizedMousePosition.y += yMove / mViewport->getActualHeight();
mNormalizedMousePosition.x = std::max<Ogre::Real>(mNormalizedMousePosition.x, 0);
mNormalizedMousePosition.y = std::max<Ogre::Real>(mNormalizedMousePosition.y, 0);
mNormalizedMousePosition.x = std::min<Ogre::Real>(mNormalizedMousePosition.x, 1);
mNormalizedMousePosition.y = std::min<Ogre::Real>(mNormalizedMousePosition.y, 1);
mMousePointer->position(mNormalizedMousePosition.x * mViewport->getActualWidth(), mNormalizedMousePosition.y * mViewport->getActualHeight());
panel->injectMouseMoved(rEngine->mFPC->getCameraToViewportRay(mNormalizedMousePosition.x, mNormalizedMousePosition.y));
return true;
}
bool MenuMode::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
panel->injectMousePressed(evt,id);
if(mNormalizedMousePosition.x<0.6)
{
if(totalCombobox->getOvered())
{
Mode::addModel(totalCombobox->getValue());
currentModel = NULL;
setCaptionText(noneSelected);
}
else if(addedCombobox->getOvered())
Mode::selectModel(addedCombobox);
}
return true;
}
void MenuMode::checkForNewHitbox()
{
if(currentModel)
{
if(shapeTypeSelector->getValue() != currentModel->hitboxShapeType)
{
switchHitbox();
}
}
}
void MenuMode::switchHitbox()
{
removeCurrentBody();
currentModel->hitboxShapeType = shapeTypeSelector->getValue();
int shapeType = hitboxSelection(currentModel->hitboxShapeType);
currentModel->rigidBody = world->addRigidBody(0,currentModel->entity,shapeType);
}
void MenuMode::removeCurrentBody()
{
btCollisionShape* currentShape = currentModel->rigidBody->getCollisionShape();
world->getWorld()->removeCollisionObject(currentModel->rigidBody);
delete currentModel->rigidBody;
delete currentShape;
}
bool MenuMode::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
panel->injectMouseReleased(evt,id);
return true;
}
void MenuMode::_createDemoPanel()
{
Ogre::ResourceGroupManager* rGrpMgr = Ogre::ResourceGroupManager::getSingletonPtr();
Ogre::SceneManager* mSceneMgr = rEngine->m_pSceneMgr;
panel = new Gui3D::Panel(mGui3D, mSceneMgr, Ogre::Vector2(_width, _height),_distance, "purple", "model_select_panel");
Gui3D::Caption* temp = panel->makeCaption(_widthPadding, 0, _wP, _boxHeight*0.2, "add Model");
temp->textColor(titleColor);
for(int i=0; i<rEngine->groupNames.size(); i++)
{
Ogre::FileInfoListPtr filesPtr = rGrpMgr->listResourceFileInfo( rEngine->groupNames[i] );
Ogre::FileInfoList fileInfoList = *filesPtr.getPointer();
for(int j=0; j<fileInfoList.size(); j++)
{
if(hasEnding(fileInfoList[j].filename,".mesh"))
{
totalModels.push_back(fileInfoList[j].basename);
}
}
}
std::vector<std::string> collisionTypes;
collisionTypes.push_back("Sphere");
collisionTypes.push_back("Box");
collisionTypes.push_back("Trimesh");
collisionTypes.push_back("Cylinder");
collisionTypes.push_back("Convex");
collisionTypes.push_back("Capsule");
totalCombobox = panel->makeCombobox(_widthPadding/2,_boxHeight*0.2,_wP,_boxHeight*0.8,totalModels,5);
temp = panel->makeCaption(_widthPadding/2, _boxHeight*1.0, _wP, _boxHeight*0.2, "added Models:");
addedCombobox = panel->makeCombobox(_widthPadding/2,_boxHeight*1.2,_wP,_boxHeight*0.8,addedModels,5);
captionCombobox = panel->makeCaption(_widthPadding/2, _boxHeight*2.0, _wP, _boxHeight*0.2, noneSelected);
shapeTypeSelector= panel->makeInlineSelector(_widthPadding/2, _boxHeight*2.2, _wP, _boxHeight*0.2,collisionTypes);
captionCombobox->textColor(titleColor);
temp->textColor(titleColor);
for(int i=0; i<3; i++)
{
hitBoxTranslationZone[i] = panel->makeTextZone(_widthPadding/2+(_wP/8.0)*i, _boxHeight*2.75,_wP/8.0,_boxHeight*0.15,"0");
hitBoxRotationZone[i] = panel->makeTextZone(_widthPadding/2+(_wP/8.0)*i+(_wP/8.0)*5.0, _boxHeight*2.75,_wP/8.0,_boxHeight*0.15,"0");
hitBoxScaleZone[i] = panel->makeTextZone(_widthPadding/2+(_wP/8.0)*(i+0.5)+(_wP/4.0), _boxHeight*2.9, _wP/8.0, _boxHeight*0.15, "0");
hitBoxTranslationZone[i]->setValueChangedCallback(this,&MenuMode::readHitBoxOffset);
hitBoxRotationZone[i]->setValueChangedCallback(this,&MenuMode::readHitBoxOffset);
hitBoxScaleZone[i]->setValueChangedCallback(this,&MenuMode::readHitBoxOffset);
}
temp = panel->makeCaption(_widthPadding/2+(_wP/8.0)*2.5, _boxHeight*2.4, _wP, _boxHeight*0.2, "HitBox/Mesh Offset:");
temp->textColor(titleColor);
temp = panel->makeCaption(_widthPadding/2, _boxHeight*2.55, _wP, _boxHeight*0.2, "Translation");
temp->textColor(textColor);
temp = panel->makeCaption(_widthPadding/2+(_wP/8.0)*5.0, _boxHeight*2.55, _wP, _boxHeight*0.2, "Rotation");
temp->textColor(textColor);
temp = panel->makeCaption(_widthPadding/2+(_wP/8.0)*(0.5)+(_wP/4.0),_boxHeight*3.05, _wP/4.0, _boxHeight*0.15, "Scale");
temp->textColor(textColor);
panel->mNode->setPosition(0, 2.1, -8);
}
bool MenuMode::readHitBoxOffset(Gui3D::PanelElement* e)
{
if(currentModel)
{
for(int i=0; i<3; i++)
{
currentModel->hitBoxTranslationOffset.m_floats[i] = ::atof(hitBoxTranslationZone[i] ->getValue().c_str());
currentModel->hitBoxRotationOffset.m_floats[i] = ::atof(hitBoxRotationZone[i] ->getValue().c_str());
currentModel->hitBoxScaleOffset.m_floats[i] = ::atof(hitBoxScaleZone[i] ->getValue().c_str());
BtOgre::RigidBodyState* motionState = static_cast< BtOgre::RigidBodyState * >( currentModel->rigidBody->getMotionState() );
btTransform hitBoxOffset;
hitBoxOffset.setIdentity();
hitBoxOffset.setOrigin(currentModel->hitBoxTranslationOffset);
btQuaternion quatRotation;
quatRotation.setEuler( currentModel->hitBoxRotationOffset.getY()/offsetRotPrec,
currentModel->hitBoxRotationOffset.getX()/offsetRotPrec, currentModel->hitBoxRotationOffset.getZ()/offsetRotPrec);
hitBoxOffset.setRotation(quatRotation);
btTransform currentTransform;
motionState->setCenterOfMassOffset(hitBoxOffset);
motionState->getWorldTransform(currentTransform);
motionState->setWorldTransform(currentTransform);
currentModel->rigidBody->getCollisionShape()->setLocalScaling(BtOgre::Convert::toBullet(currentModel->scaleNode->getScale())
+currentModel->hitBoxScaleOffset);
}
}
return true;
}
QJSEngine* MenuMode::initScript()
{
QJSEngine* engine = new QJSEngine();
Q_INIT_RESOURCE(Scripts);
QString fileName = ":/testscript.js";
QFile scriptFile(fileName);
if (!scriptFile.exists())
assert(!"JS File not found!!!");
if (!scriptFile.open(QIODevice::ReadOnly))
assert(!"JS File not opened!!!");
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close();
engine->evaluate(contents);
return engine;
}
void MenuMode::initTextColors(QJSEngine* engine)
{
titleColor = jsToColor( engine->evaluate("TitleColor") );
textColor = jsToColor( engine->evaluate("TextColor") );
}
Ogre::ColourValue MenuMode::jsToColor(QJSValue jsArr)
{
float colors[3];
for(int i=0; i<3; i++)
{
colors[i] = jsArr.property(i).toNumber();
}
return Ogre::ColourValue(colors[0], colors[1], colors[2]);
}
|
#include "myCstring.h"
void myStrCpy(char text1[],size_t size ,const char text2[]) {
int i = 0;
for (; text2[i] != '\0' && i < size; i++) {
text1[i] = text2[i];
}
text1[i] = '\0';
}
int myStrlen(const char arr[]) {
int cnt = 0;
while (arr[cnt]) {
++cnt;
}
return cnt;
}
void toSmall(char arr[]) {
for (int i = 0; arr[i] != '\0'; i++) {
if (arr[i] >= 'A' && arr[i] <= 'Z') {
arr[i] = arr[i] + 32;
}
}
}
int myStrcmp(char text1[],const char text2[]) {
while (*text1 && *text2 && *text1 == *text2) {
++text1;
++text2;
}
return *text1 - *text2;
}
|
#ifndef SOCKET_HANDLER_H
#define SOCKET_HANDLER_H
#include "CDLSocketServer.h"
#include "CDLSocketHandler.h"
#include "DLDecoder.h"
#include "Packet.h"
#include <string>
using namespace std;
#ifdef MAX_CALL_BACK
# undef MAX_CALL_BACK
# define MAX_CALL_BACK 100
#else
# define MAX_CALL_BACK 100
#endif
class ClientHandler: public CDLSocketHandler
{
public:
ClientHandler();
virtual ~ClientHandler() ;
string m_addrremote; //远端地址
int m_nPort; //端口
int addCallbackSeq(unsigned short seq);
void deleteCallbackSeq(unsigned short seq);
void clearCallbackSeq();
int Send(OutputPacket* packet, bool encode=true)
{
if(encode)
packet->EncryptBuffer();
return CDLSocketHandler::Send((const char*)packet->packet_buf(), packet->packet_size()) >= 0 ? 0 : -1;
}
int close(){return 0;};
int OnConnected(void);
int OnClose();
private:
int OnPacketComplete(const char* data,int len);
CDL_Decoder* CreateDecoder()
{
return &DLDecoder::getInstance();
}
void GetRemoteAddr(void);
unsigned short callback_count;
unsigned short callback_seq[MAX_CALL_BACK];
InputPacket pPacket;
};
//实例化一个Server
typedef SocketServer<ClientHandler> RobotServer;
#endif
|
class Game_system {
public:
enum KEYS{UP,DOWN,LEFT,RIGHT};
ALLEGRO_DISPLAY * display;
ALLEGRO_EVENT_QUEUE * event_queue;
ALLEGRO_TIMER * timer;
ALLEGRO_BITMAP * tileset;
ALLEGRO_SAMPLE * sample;
ALLEGRO_FONT * font;
bool done;
bool keys[4];
bool redraw;
bool write_dialogue;
vector<int> wid_height;
int FPS;
time_t timer1;
int frame_counter;
string cur_map;
Creature hero;
vector<Entity> mve;
vector<Tile> mv;
void loop();
void set_values();
void draw_map(int,int);
void walk_animation(int,int,int,int,int,int,int,int,int);
void move_hero();
void three_frame_animation(int,int,int,int,int,int,int,int,int,int,int);
void make_map();
};
void Game_system::set_values() {
/*
Allegro variables
*/
display=NULL;
event_queue=NULL;
timer=NULL;
tileset = NULL;
sample = NULL;
font = NULL;
/*
Primitive variables
*/
done = false;
keys[0] = false;
keys[1] = false;
keys[2] = false;
keys[3] = false;
redraw = true;
write_dialogue = false;
/*
wid_height initialization
*/
wid_height.push_back(1);
wid_height.push_back(1);
wid_height[0] = 30; //col x
wid_height[1] = 30; //col y
/*
Integer variables
*/
FPS = 100;
/*
Timing variables
*/
timer1 = clock();
frame_counter = 0;
hero.set_loc(12,15);
hero.facing = 'd';
hero.is_swing_hoe = false;
hero.move_animation = false;
hero.wait_time=1;
display = al_create_display((wid_height[0]*16)-1,(wid_height[1]*16)-1);
/*
Initialize allegro modules.
*/
al_install_keyboard();
al_init_primitives_addon();
al_init_image_addon();
al_install_audio();
al_init_acodec_addon();
al_reserve_samples(1);
al_init_font_addon();
al_init_ttf_addon();
/*
Initialize allegro variables.
*/
sample = al_load_sample("neg_resources/collision.ogg");
font = al_load_font("neg_resources/arial.ttf",16,0);
timer = al_create_timer(1.0/FPS);
event_queue = al_create_event_queue();
//game init
al_register_event_source(event_queue, al_get_timer_event_source(timer));
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_register_event_source(event_queue, al_get_display_event_source(display));
al_start_timer(timer);
mve.resize(wid_height[0]*wid_height[1]);
init_map_house(cur_map, mve);
make_map();
init_map_house_entity(mve);
tileset = al_load_bitmap("neg_resources/tileset.png");
al_convert_mask_to_alpha(tileset, al_map_rgb(0,255,255));
}
void Game_system::loop() {
while(!done)
{
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue,&ev);
if(ev.type == ALLEGRO_EVENT_TIMER){
redraw = true;
}
if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch(ev.keyboard.keycode) {
case ALLEGRO_KEY_UP:
write_dialogue = false;
keys[UP] = true;
break;
case ALLEGRO_KEY_DOWN:
write_dialogue = false;
keys[DOWN]=true;
break;
case ALLEGRO_KEY_RIGHT:
write_dialogue = false;
keys[RIGHT]=true;
break;
case ALLEGRO_KEY_LEFT:
write_dialogue = false;
keys[LEFT]=true;
break;
case ALLEGRO_KEY_RCTRL:
if (hero.move_animation == false && hero.is_swing_hoe == false) {
hero.sta_frame = 1;
hero.is_swing_hoe = true;
}
break;
case ALLEGRO_KEY_Z:
if(write_dialogue == true) {
write_dialogue = false;
}
else if (hero.can_interact(write_dialogue,mve) == true){ //neeeds if statement.
write_dialogue = true;
}
}
}
else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
if (ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
done = true;
}
//keys no longer held down.
switch(ev.keyboard.keycode) {
case ALLEGRO_KEY_UP:
keys[UP] = false;
break;
case ALLEGRO_KEY_DOWN:
keys[DOWN]=false;
break;
case ALLEGRO_KEY_RIGHT:
keys[RIGHT]=false;
break;
case ALLEGRO_KEY_LEFT:
keys[LEFT]=false;
break;
}
}
else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
{
done = true;
}
//WAIT UNTIL ANIMATION IS OVER - If key is still pressed animate again. (Pokemon esque)
if (hero.move_animation == false) {
if (keys[UP]==true) {
hero.creature_turning('u',mv);
}
else if (keys[DOWN]==true) {
hero.creature_turning('d',mv);
}
else if (keys[LEFT] == true) {
hero.creature_turning('l',mv);
}
else if (keys[RIGHT] == true) {
hero.creature_turning('r',mv);
}
}
//CHECK FOR ON STEP EVENT
if(mve[(hero.hloc*30)+hero.wloc].step_on == 'y') {
if (mve[(hero.hloc*30)+hero.wloc].map_warp == "house") {
hero.set_loc(mve[(hero.hloc*30)+hero.wloc].warp_col,mve[(hero.hloc*30)+hero.wloc].warp_row);
init_map_entity_cleanup(mve);
init_map_house_entity(mve);
init_map_house(cur_map,mve);
make_map();
}
else if (mve[(hero.hloc*30)+hero.wloc].map_warp == "home") {
hero.set_loc(mve[(hero.hloc*30)+hero.wloc].warp_col,mve[(hero.hloc*30)+hero.wloc].warp_row);
init_map_entity_cleanup(mve);
init_map_home_entity(mve);
init_map_home(cur_map,mve);
make_map();
}
}
hero.wait_time++;
//This block runs 60 times per second
if(redraw && al_is_event_queue_empty(event_queue))
{
redraw = false;
//DRAW MAP
draw_map(0,0);
//DRAW & ANIMATE HERO
frame_counter++;
if ((clock() - timer1) >= 1000) {
cout<<frame_counter<<"\n";
frame_counter = 0;
timer1 = clock();
}
move_hero();
//display message
if(write_dialogue == true) {
entity_message(tileset,hero,font,mve,wid_height);
}
al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));
}
}
}
void Game_system::draw_map (int radj, int cadj)
//Draws map and you can modify pixel by pixel with radj and cadj. (Row adjustment and Column adjustment). Set them to zero if you desire no modification.
{
for(int col=0;col<wid_height[0];col++) {
for(int row=0;row<wid_height[1];row++) {
al_draw_bitmap_region(tileset,
mv[(col*30)+row].sx * 16, mv[(col*30)+row].sy * 16,
16,16,
(row*16 - hero.wloc*16)+((wid_height[1]/2)*16) + radj,
(col*16 - hero.hloc*16)+((wid_height[0]/2)*16) + cadj,
0);
}
}
}
void Game_system::walk_animation (int tw, int aheight, int awidth, int ci1,int ci2,int ci3,int ri1, int ri2, int ri3)
/*
Draws the walking animation
Variable description
#######################
Entity being animated, tileset,map vector 1-3
tile width, animation height in tiles, and animation width in tiles
height, and width of map in tiles.
ci1,ci2,ci3 column of the three animations
ri1,ri2,ri3 row of the three animations
*/
{
if(hero.move_animation==true) {
int frameintv=0;
int frameinth=0;
int hl=0;
int vl=0;
switch (hero.facing) {
case 'u':
vl = -1;
frameintv = hero.frame * 3;
break;
case 'd' :
vl=1;
frameintv = (hero.frame * 3) *-1;
break;
case 'l' :
hl=-1;
frameinth = hero.frame * 3;
break;
case 'r':
hl=1;
frameinth = (hero.frame * 3) *-1;
break;
}
//Draw Map in motion
draw_map(frameinth,frameintv);
if (hero.frame<= 2) {
al_draw_bitmap_region(tileset, ri2*tw, ci2*tw, tw, tw, 15*tw, 15*tw, 0);
}
else if (hero.frame < 5) {
al_draw_bitmap_region(tileset, ri3*tw, ci3*tw, tw, tw, 15*tw, 15*tw, 0);
}
else if(hero.frame == 5) {
al_draw_bitmap_region(tileset, ri3*tw, ci3*tw, tw, tw, 15*tw, 15*tw, 0);
hero.move_animation = false;
hero.hloc+=vl; //moving line.
hero.wloc+=hl; // moving line.
}
hero.frame++;
}
else {
al_draw_bitmap_region(tileset, ri1 * tw, ci1 * tw, tw, tw, 15*tw, 15*tw, 0);
}
}
void Game_system::move_hero () {
int tw = 16;
if(hero.move_animation==false) {
if(hero.is_swing_hoe == true) {
switch (hero.facing) {
case 'u':
three_frame_animation(tw,16,16,16,0,1,2,2,1,-1,-2);
break;
case 'd' :
three_frame_animation(tw,13,13,13,0,1,2,3,1,-1,-2);
break;
case 'l':
three_frame_animation(tw,18,18,18,0,2,4,2,2,-2,-2);
break;
case 'r':
three_frame_animation(tw,20,20,20,0,2,4,2,2,-1,-2);
break;
}
hero.sta_frame++;
}
}
if(hero.is_swing_hoe == false) {
switch (hero.facing) {
case 'u':
walk_animation(tw,1,1,3,3,3,0,1,2);
break;
case 'd':
walk_animation(tw,1,1,2,2,2,0,1,2);
break;
case 'l':
walk_animation(tw,1,1,4,4,4,0,1,2);
break;
case 'r':
walk_animation(tw,1,1,5,5,5,0,1,2);
break;
}
}
}
void Game_system::three_frame_animation(int tw, int ci1,int ci2, int ci3, int ri1, int ri2, int ri3,int aheight,int awidth,int radj, int cadj)
/*draws 3 frame animations.
variables description
##############################
tileset, tile width, Entity being animated, 1-3
column for first, second, and third frames. 4-6
row for first,second, and third frames. 7-9
animation height in tiles, animation width in tiles. 10,11
radj, and cadj are for adjusting the center of animation. makes function tweakable.
*/
{
if(hero.sta_frame<=2) {
al_draw_bitmap_region(tileset, (ri1)*tw, (ci1)*tw, tw*awidth, tw*aheight, (16+radj)*tw, (16+cadj)*tw, 0);
}
else if(hero.sta_frame<=4) {
al_draw_bitmap_region(tileset, (ri2)*tw, (ci2)*tw, tw*awidth, tw*aheight, (16+radj)*tw, (16+cadj)*tw, 0);
}
else if(hero.sta_frame<=5) {
al_draw_bitmap_region(tileset, (ri3)*tw, (ci3)*tw, tw*awidth, tw*aheight, (16+radj)*tw, (16+cadj)*tw, 0);
}
else if (hero.sta_frame <= 6) {
al_draw_bitmap_region(tileset, (ri3)*tw, (ci3)*tw, tw*awidth, tw*aheight, (16+radj)*tw, (16+cadj)*tw, 0);
hero.is_swing_hoe = false;
}
}
void Game_system::make_map() {
mv.resize(wid_height[0]*wid_height[1]);
for(int i=0;i<mv.size();i++) {
switch(cur_map[i]) {
case 'X'://Wooden log
mv[i].set_values('x','n',0,0);
break;
case 'O' ://empty
mv[i].set_values('o','y',1,3);
break;
case 'V': //the void
mv[i].set_values('v','n',2,4);
break;
case 'G'://grass (long)
mv[i].set_values('g','y',1,1);
break;
case 'T'://tree
mv[i].set_values('t','n',0,2);
break;
case 'S'://sign
mv[i].set_values('s','n',0,3);
break;
case 'B'://blood
mv[i].set_values('b','y',1,4);
break;
case 'D': //dirt
mv[i].set_values('d','y',2,3);
break;
case 'W': //dirt
mv[i].set_values('w','y',4,3);
break;
case 'F': //floor
mv[i].set_values('f','y',1,2);
break;
case 'R': //left rug
mv[i].set_values('r','y',5,3);
break;
case 'Y': //right rug
mv[i].set_values('y','y',5,4);
break;
case '1'://left of roof
mv[i].set_values('1','n',7,3);
break;
case '2'://roof center
mv[i].set_values('2','n',7,4);
break;
case '3'://small window leftside on roof
mv[i].set_values('3','n',7,5);
break;
case '4': //flowerpot window
mv[i].set_values('4','n',7,6);
break;
case '5': //small window rightside on roof
mv[i].set_values('5','n',7,7);
break;
case '6'://right of roof
mv[i].set_values('6','n',7,8);
break;
case '7': //left wall
mv[i].set_values('7','n',8,3);
break;
case '8': //wall
mv[i].set_values('8','n',8,4);
break;
case '9': //rake
mv[i].set_values('9','n',8,5);
break;
case '!': //door
mv[i].set_values('!','y',8,6);
break;
case '@': //broom
mv[i].set_values('@','n',8,7);
break;
case '#': //right wall
mv[i].set_values('#','n',8,8);
break;
case '$': //left of shingles
mv[i].set_values('$','n',6,3);
break;
case '%': //shingles
mv[i].set_values('%','n',6,4);
break;
case '^': //right of shingles
mv[i].set_values('^','n',6,5);
break;
case 'P': //Turnip greens
mv[i].set_values('p','y',5,5);
break;
}
}
}
|
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool check(const long long &num, const vector<int> ×,
const int &n) {
int target = 0;
for (int i : times) {
target += num / i;
}
return target < n;
}
long long solution(int n, vector<int> times) {
long long max = (long long)times.back() * n;
long long answer = max;
long long min = 0;
long long mid;
while (min <= max) {
mid = (max + min) / 2;
if(check(mid, times, n)){
min = mid + 1;
}else{
if(answer > mid){
answer = mid;
}
max = mid - 1;
}
}
return answer;
}
int main() {
cout << solution(6, {7, 10}) << '\n';
return 0;
}
|
//Write a c++ program that reads a year and checks wheather the entered year is leap year oe not.
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"Enter any year"<<endl;
cin>>a;
if(a%4==0 && a%100!=0 || a%400==0)
cout<<a<<" is a leap year";
else
cout<<a<<" is not leap year";
}
|
#pragma once
#ifndef _INITINFO_H_
#define _INITINFO_H_
#define MINUTESPERDAY (24*60);
#ifndef FLOAT_EQ
#define EPSILON 0.001 // floating point comparison tolerance
#define FLOAT_EQ(x,v) (((v - EPSILON) < x) && (x <( v + EPSILON)))
#define MINUTESPERDAY (24*60);
#endif
struct TInitInfo
{
public:
TInitInfo()
{
char description[255] = "\0";
char cultivar[255]="\0";
GDD_rating = 1331;
genericLeafNo=15;
latitude = 38.0; longitude = 0.0; altitude = 50.0;
sowingDay = 150;
beginDay = 1; endDay = 365;
year = 2004;
timeStep=5.0;
plantDensity = 8.0;
CO2 = 370.0;
Rmax_LIR=.0978;
Rmax_LTAR = 0.53;
DayLengthSensitive=true;
PhyllochronsToSilk=8;
PhyllochronsToTassel = 1;
stayGreen = 4.5;
LM_min = 125.0;
}
char description[255];
char cultivar[255];
int GDD_rating; // GDD or GTI rating of the cv, see Stewart 1999 for conversion between MRMR and other ratings
int genericLeafNo; // leaf number at the end of juvenile phase independent of environmental ques of leaf initiation
double plantDensity;
double latitude, longitude, altitude;
int sowingDay, beginDay, endDay;
double CO2;
int year;
double timeStep;
bool DayLengthSensitive; //1 if daylength sensitive
double Rmax_LIR, Rmax_LTAR; // Maximum Leaf tip initiation and appearance rates
double stayGreen; // staygreen trait of the hybrid (originally 4.5)
double LM_min; //Length of largest leaf
// stay green for this value times growth period after peaking before senescence begins
// An analogy for this is that with no other stresses involved, it takes 15 years to grow up, stays active for 60 years, and age the last 15 year if it were for a 90 year life span creature.
//Once fully grown, the clock works differently so that the hotter it is quicker it ages
double PhyllochronsToSilk; //number of phyllochrons from tassel initiation for 75% silking.
double PhyllochronsToTassel; // number of phyllochrons past tassel initiation when tassels are fully emerged. (not input yet)
//todo these above 2 variables are also in development - need to remove them from there.
//check units
};
#endif
|
/**
* @file messagedecodersystem.h
*
* @brief This file outlines the functions that are available for message decoding
* @version 0.1
* @date 2021-08-14
*
* @copyright Copyright (c) 2021
*
*/
#include "ArduinoJson.h"
#include "globals.h"
#include "message.h"
#include "messagedecoderbase.h"
// Decoders
#include "messagedecodertest.h"
#ifndef MESSAGEDECODER_H
#define MESSAGEDECODER_H
/**
* @brief Contains all the decoder system functions.
*
*
*/
namespace DecoderSystem{
// The internal Static json object buffer
extern StaticJsonDocument<MAX_MESSAGE_LENGTH> jsonObj;
// The different decoders are defined here
extern ExampleDecoder exampledecoder;
// Storage for the different internal message decoder classes
extern unsigned int num_decoders;// = 1;
extern MessageDecoderBase * decoders[];// = {&exampledecoder};
/**
* @brief Decode and then execute a message object
*
* @param Message::Message - The message object to decode
* @returns Decode success status - True on success - False on failure
*/
bool decode_execute(Message * msg);
};
#endif
|
// generated by Fast Light User Interface Designer (fluid) version 1.0302
#include "CTaLibFuncViewUI.h"
CTaLibFuncViewUI::CTaLibFuncViewUI() {
{ m_window = new Fl_Double_Window(780, 385, "Technical Analysis Function Browser");
m_window->user_data((void*)(this));
{ m_taLibView = new Fl_Group(-35, 0, 815, 470);
m_taLibView->box(FL_DOWN_BOX);
{ Fl_Tile* o = new Fl_Tile(5, 5, 770, 345);
o->box(FL_FLAT_BOX);
o->color(FL_YELLOW);
{ m_funcTree = new Fl_Tree(5, 5, 260, 345);
m_funcTree->color((Fl_Color)20);
m_funcTree->root()->label("FUNCTIONS");
m_funcTree->root()->labelcolor(FL_RED);
} // Fl_Tree* m_funcTree
{ m_funcInfo = new Fl_Group(265, 5, 510, 345);
m_funcInfo->box(FL_DOWN_BOX);
m_funcInfo->color((Fl_Color)43);
m_funcInfo->align(Fl_Align(65));
{ m_funcName = new Fl_Box(270, 10, 500, 25, "<-- Select a Function");
m_funcName->labeltype(FL_SHADOW_LABEL);
m_funcName->labelsize(20);
m_funcName->labelcolor(FL_BACKGROUND2_COLOR);
m_funcName->align(Fl_Align(FL_ALIGN_CLIP));
} // Fl_Box* m_funcName
{ Fl_Tabs* o = new Fl_Tabs(270, 40, 505, 310);
{ m_summaryGroup = new Fl_Group(270, 60, 505, 290, "SUMMARY");
{ m_funcDescription = new Fl_Box(385, 68, 365, 55);
m_funcDescription->labeltype(FL_SHADOW_LABEL);
m_funcDescription->labelsize(20);
m_funcDescription->labelcolor(FL_BACKGROUND2_COLOR);
m_funcDescription->align(Fl_Align(197|FL_ALIGN_INSIDE));
} // Fl_Box* m_funcDescription
{ m_funcGroup = new Fl_Box(386, 125, 380, 25);
m_funcGroup->labeltype(FL_SHADOW_LABEL);
m_funcGroup->labelsize(20);
m_funcGroup->labelcolor(FL_BACKGROUND2_COLOR);
m_funcGroup->align(Fl_Align(68|FL_ALIGN_INSIDE));
} // Fl_Box* m_funcGroup
{ m_funcInputs = new Fl_Box(387, 157, 365, 30);
m_funcInputs->labeltype(FL_SHADOW_LABEL);
m_funcInputs->labelsize(20);
m_funcInputs->labelcolor(FL_BACKGROUND2_COLOR);
m_funcInputs->align(Fl_Align(68|FL_ALIGN_INSIDE));
} // Fl_Box* m_funcInputs
{ m_funcOptInputs = new Fl_Box(387, 195, 360, 30);
m_funcOptInputs->labeltype(FL_SHADOW_LABEL);
m_funcOptInputs->labelsize(20);
m_funcOptInputs->labelcolor(FL_BACKGROUND2_COLOR);
m_funcOptInputs->align(Fl_Align(68|FL_ALIGN_INSIDE));
} // Fl_Box* m_funcOptInputs
{ m_funcOutputs = new Fl_Box(387, 235, 325, 30);
m_funcOutputs->labeltype(FL_SHADOW_LABEL);
m_funcOutputs->labelsize(20);
m_funcOutputs->labelcolor(FL_BACKGROUND2_COLOR);
m_funcOutputs->align(Fl_Align(68|FL_ALIGN_INSIDE));
} // Fl_Box* m_funcOutputs
{ m_funcDisplayTypes = new Fl_Box(386, 278, 384, 69);
m_funcDisplayTypes->labeltype(FL_SHADOW_LABEL);
m_funcDisplayTypes->labelsize(20);
m_funcDisplayTypes->labelcolor(FL_BACKGROUND2_COLOR);
m_funcDisplayTypes->align(Fl_Align(69|FL_ALIGN_INSIDE));
} // Fl_Box* m_funcDisplayTypes
{ Fl_Box* o = new Fl_Box(275, 70, 105, 25, " DESCRIPTION:");
o->align(Fl_Align(FL_ALIGN_RIGHT|FL_ALIGN_INSIDE));
} // Fl_Box* o
{ Fl_Box* o = new Fl_Box(275, 164, 105, 25, " INPUTS:");
o->align(Fl_Align(FL_ALIGN_RIGHT|FL_ALIGN_INSIDE));
} // Fl_Box* o
{ new Fl_Box(279, 128, 105, 25, " GROUP:");
} // Fl_Box* o
{ Fl_Box* o = new Fl_Box(275, 200, 105, 25, " OPT-INPUTS:");
o->align(Fl_Align(FL_ALIGN_RIGHT|FL_ALIGN_INSIDE));
} // Fl_Box* o
{ Fl_Box* o = new Fl_Box(275, 239, 105, 25, " OUTPUTS:");
o->align(Fl_Align(FL_ALIGN_RIGHT|FL_ALIGN_INSIDE));
} // Fl_Box* o
{ Fl_Box* o = new Fl_Box(275, 280, 105, 25, " VISUAL TYPE:");
o->align(Fl_Align(FL_ALIGN_RIGHT|FL_ALIGN_INSIDE));
} // Fl_Box* o
m_summaryGroup->end();
} // Fl_Group* m_summaryGroup
{ m_inputsTable = new Fl_Table(270, 60, 500, 280, "INPUTS");
m_inputsTable->box(FL_THIN_UP_FRAME);
m_inputsTable->hide();
m_inputsTable->end();
} // Fl_Table* m_inputsTable
{ m_optInputsTable = new Fl_Table(270, 60, 500, 280, "OPT-INPUTS");
m_optInputsTable->box(FL_THIN_UP_FRAME);
m_optInputsTable->hide();
m_optInputsTable->end();
} // Fl_Table* m_optInputsTable
{ m_outputsTable = new Fl_Table(270, 60, 500, 280, "OUTPUTS");
m_outputsTable->box(FL_THIN_UP_FRAME);
m_outputsTable->hide();
m_outputsTable->end();
} // Fl_Table* m_outputsTable
o->end();
} // Fl_Tabs* o
m_funcInfo->end();
} // Fl_Group* m_funcInfo
o->end();
} // Fl_Tile* o
m_taLibView->end();
Fl_Group::current()->resizable(m_taLibView);
} // Fl_Group* m_taLibView
m_window->end();
} // Fl_Double_Window* m_window
}
|
#include "item.h"
#include "room.h"
Item::Item (string itemDescription)
{
this->itemDescription = itemDescription;
}
string Item::getShortDescription()
{
return itemDescription;
}
string Item::getLongDescription()
{
return " item(s), " + itemDescription + ".\n";
}
string Room:: getItem()
{
return itemDescription;
}
|
//------------------------------------------------------------------------------
/*
This file is part of valueAdded: https://github.com/valueAdd/valueAdded
Copyright (c) 2012, 2013 valueAdd Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef VALUEADD_SERVER_BASEPEER_H_INCLUDED
#define VALUEADD_SERVER_BASEPEER_H_INCLUDED
#include <valueAdd/server/Port.h>
#include <valueAdd/server/impl/io_list.h>
#include <valueAdd/beast/utility/WrappedSink.h>
#include <boost/asio.hpp>
#include <atomic>
#include <cassert>
#include <functional>
#include <string>
namespace valueAdd {
// Common part of all peers
template<class Handler, class Impl>
class BasePeer
: public io_list::work
{
protected:
using clock_type = std::chrono::system_clock;
using error_code = boost::system::error_code;
using endpoint_type = boost::asio::ip::tcp::endpoint;
using waitable_timer = boost::asio::basic_waitable_timer <clock_type>;
Port const& port_;
Handler& handler_;
endpoint_type remote_address_;
beast::WrappedSink sink_;
beast::Journal j_;
boost::asio::io_service::work work_;
boost::asio::io_service::strand strand_;
public:
BasePeer(Port const& port, Handler& handler,
endpoint_type remote_address,
boost::asio::io_service& io_service,
beast::Journal journal);
void
close() override;
private:
Impl&
impl()
{
return *static_cast<Impl*>(this);
}
};
//------------------------------------------------------------------------------
template<class Handler, class Impl>
BasePeer<Handler, Impl>::
BasePeer(Port const& port, Handler& handler,
endpoint_type remote_address,
boost::asio::io_service& io_service,
beast::Journal journal)
: port_(port)
, handler_(handler)
, remote_address_(remote_address)
, sink_(journal.sink(),
[]
{
static std::atomic<unsigned> id{0};
return "##" + std::to_string(++id) + " ";
}())
, j_(sink_)
, work_(io_service)
, strand_(io_service)
{
}
template<class Handler, class Impl>
void
BasePeer<Handler, Impl>::
close()
{
if (! strand_.running_in_this_thread())
return strand_.post(std::bind(
&BasePeer::close, impl().shared_from_this()));
error_code ec;
impl().ws_.lowest_layer().close(ec);
}
} // valueAdd
#endif
|
#include "lateral_controller.hpp"
#include <tf2_eigen/tf2_eigen.h>
#include <utils_ros/ros_console.hpp>
#include <boost/algorithm/clamp.hpp>
#include <boost/math/special_functions/sign.hpp>
#include <boost/range/algorithm/min_element.hpp>
#include "lateral_control_ros_tool/discrete_curvature.h"
#include "motor_interface_ros_tool/ServoCommand.h"
#include "safe_iterator_operations.h"
namespace anicar_lateral_control_ros_tool {
using ServoCommand = motor_interface_ros_tool::ServoCommand;
LateralController::LateralController(ros::NodeHandle nh_public, ros::NodeHandle nh_private)
: params_{nh_private}, reconfigureServer_{nh_private}, tfListener_{tfBuffer_} {
/**
* Initialization
*/
utils_ros::setLoggerLevel(nh_private);
params_.fromParamServer();
/**
* Publishers & subscriber
*/
servo_command_publisher_ = nh_private.advertise<ServoCommand>(params_.servo_command_topic, params_.msg_queue_size);
// Instantiate subscriber last, to assure all objects are initialised when first message is received.
path_subscriber_ = nh_private.subscribe(params_.path_topic,
params_.msg_queue_size,
&LateralController::pathCallback,
this,
ros::TransportHints().tcpNoDelay());
control_loop_timer_ =
nh_private.createTimer(ros::Rate(params_.control_loop_rate), &LateralController::controlLoopCallback, this);
/**
* Set up dynamic reconfiguration
*/
reconfigureServer_.setCallback(boost::bind(&LateralController::reconfigureRequest, this, _1, _2));
utils_ros::showNodeInfo();
}
void LateralController::pathCallback(const nav_msgs::Path::ConstPtr& msg) {
path_.clear();
path_.reserve(msg->poses.size());
for (const auto& pose_stamped : msg->poses) {
Eigen::Affine3d pose;
tf2::fromMsg(pose_stamped.pose, pose);
path_.push_back(pose);
}
}
double signedAngleBetween(const Eigen::Vector3d& a, const Eigen::Vector3d& b) {
const double vz = boost::math::sign(a.cross(b).z());
return vz * std::acos(a.normalized().dot(b.normalized()));
}
void LateralController::controlLoopCallback(const ros::TimerEvent& timer_event) {
if (path_.size() < 5) {
ROS_INFO_STREAM("No Path received yet");
return;
}
/*
* Lookup the latest transform from vehicle to map frame
*/
Eigen::Affine3d vehicle_pose;
try {
const geometry_msgs::TransformStamped tf_ros =
tfBuffer_.lookupTransform(params_.map_frame_id, params_.vehicle_frame_id, ros::Time(0));
vehicle_pose = tf2::transformToEigen(tf_ros);
} catch (const tf2::TransformException& e) {
ROS_WARN_STREAM(e.what());
return;
}
const Eigen::Vector3d vehicle_position = vehicle_pose.translation();
/*
* Shift Rear-axle in current direction -> kos_shift
*/
const Eigen::Vector3d vehicle_frame_unit_x = [&vehicle_pose]() {
Eigen::Vector3d p = vehicle_pose.rotation() * Eigen::Vector3d::UnitX();
p.z() = 0.0;
return p.normalized();
}();
const Eigen::Vector3d shifted_vehicle_position = vehicle_position + vehicle_frame_unit_x * params_.kos_shift;
auto const& it = boost::range::min_element(
path_, [&shifted_vehicle_position](const Eigen::Affine3d& lhs, const Eigen::Affine3d& rhs) {
return (lhs.translation() - shifted_vehicle_position).squaredNorm() <
(rhs.translation() - shifted_vehicle_position).squaredNorm();
});
if (it == std::prev(path_.end())) {
ROS_ERROR("Reached end of trajectory!");
return;
}
const Eigen::Vector3d closest_trajectory_point = it->translation();
/**
* Find look ahead point
*/
// params_.index_shift --- lookaheadpoint
// params_.ii_off --- point offset for curvature approximation
auto const& it_lb = safe_next(it, params_.index_shift, std::prev(path_.end()));
const Eigen::Vector3d& p_lookahead = it_lb->translation();
// Determine three points for approximation
const Eigen::Vector3d& p_prev = safe_prev(it_lb, params_.ii_off, path_.begin())->translation();
const Eigen::Vector3d& p_next = safe_next(it_lb, params_.ii_off, std::prev(path_.end()))->translation();
const double curv = discreteCurvature(p_prev.head<2>(), p_lookahead.head<2>(), p_next.head<2>());
const Eigen::Vector3d target_direction = p_next - p_lookahead;
/*
* Compute angle difference
*/
const double delta_angle = signedAngleBetween(target_direction, vehicle_frame_unit_x);
/*
* Calculation of the sign for distance control (= determine side of trajectory)
*/
const double vz_dist =
boost::math::sign(target_direction.cross(closest_trajectory_point - shifted_vehicle_position).z());
const double dist = (closest_trajectory_point - shifted_vehicle_position).norm();
/*
* Controller law
*/
double r_ang = -1. * params_.k_ang * delta_angle;
double r_dist = params_.k_dist * vz_dist * dist;
double steering_angle = std::atan(params_.wheel_base * (curv + r_ang + r_dist));
steering_angle = boost::algorithm::clamp(steering_angle, -params_.max_steering_angle, params_.max_steering_angle);
ROS_DEBUG_STREAM("Steering_angle: " << steering_angle);
ServoCommand servo_command;
servo_command.header.stamp = timer_event.current_expected;
servo_command.steering_angle = steering_angle;
servo_command_publisher_.publish(servo_command);
}
/**
* This callback is called at startup or whenever a change was made in the dynamic_reconfigure window
*/
void LateralController::reconfigureRequest(const Config& config, uint32_t level) {
params_.fromConfig(config);
}
} // namespace anicar_lateral_control_ros_tool
|
#include <iostream>
#include "MyApp.hpp"
#include "MyModule.hpp"
namespace cdt {
MyApp::MyApp() {
std::cout << "CTR" << std::endl;
}
MyApp::~MyApp() {
std::cout << "DTR" << std::endl;
}
void MyApp::load() {
std::cout << "Loading app..." << std::endl;
this->addModule("TEST", cdt::createMyModule());
this->addModule("TEST", cdt::createMyModule());
ModulePtr mod = this->replaceModule("TEST", cdt::createMyModule());
}
void MyApp::run() {
std::cout << "run" << std::endl;
}
void MyApp::clean() {
std::cout << "clean" << std::endl;
}
} // namespace cdt
|
/*
* 题目:146. LRU 缓存机制
* 链接:https://leetcode-cn.com/problems/lru-cache/
* 知识点:哈希表+双向链表
*/
struct LRULinkedNode {
int key, value;
LRULinkedNode *pre;
LRULinkedNode *next;
LRULinkedNode():key(0), value(0), pre(nullptr), next(nullptr) {};
LRULinkedNode(int _key, int _value):key(_key), value(_value), pre(nullptr), next(nullptr) {};
};
class LRUCache {
private:
unordered_map<int, LRULinkedNode *> cache; // 缓存
LRULinkedNode *head; // 双端链表虚拟头结点
LRULinkedNode *tail; // 双端链表虚拟尾结点
int capacity; // 可用容量
int size; // 已用容量
// 将 node 添加到头结点
void addToHead(LRULinkedNode *node) {
// 处理 node 节点
node->next = head->next;
node->pre = head;
// 处理 head 节点
head->next->pre = node;
head->next = node;
}
// 删除 node 节点
void removeNode(LRULinkedNode *node) {
// 处理 node 的左右节点
node->pre->next = node->next;
node->next->pre = node->pre;
}
// 将 node 移动到头部位置
void moveToHead(LRULinkedNode *node) {
removeNode(node);
addToHead(node);
}
// 淘汰尾部节点
LRULinkedNode* removeTail() {
LRULinkedNode *node = tail->pre;
removeNode(node);
return node;
}
public:
LRUCache(int capacity):capacity(capacity), size(0) {
head = new LRULinkedNode();
tail = new LRULinkedNode();
head->next = tail;
tail->pre = head;
}
int get(int key) {
if (!cache.count(key)) {
return -1;
}
LRULinkedNode *node = cache[key];
moveToHead(node);
return node->value;
}
void put(int key, int value) {
if (!cache.count(key)) {
// 创建
LRULinkedNode *node = new LRULinkedNode(key, value);
// 插入
addToHead(node);
cache[key] = node;
size++;
// 判断是否淘汰
if (size > capacity) {
LRULinkedNode *node = removeTail();
cache.erase(node->key);
size--;
delete node;
}
} else {
// 通过获取节点
LRULinkedNode *node = cache[key];
// 修改节点值
node->value = value;
// 移动到前方
moveToHead(node);
}
}
};
|
/**********************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
********************************************************************/
#if USE_OPENCL
#include "calc_test_cl.h"
#include "clw_test.h"
#include "clw_test_cl.h"
#include "radeon_rays_apitest_cl.h"
#include "radeon_rays_conformance_test_cl.h"
//#include "radeon_rays_performance_test_cl.h"
#include "radeon_rays_test_cl.h"
#endif
#if USE_VULKAN
#include "calc_test_vk.h"
#include "radeon_rays_apitest_vk.h"
#include "radeon_rays_conformance_test_vk.h"
//#include "radeon_rays_performance_test_vk.h"
#endif
#if USE_EMBREE
#include "radeon_rays_apitest_embree.h"
#include "radeon_rays_conformance_test_embree.h"
#endif
#include "gtest/gtest.h"
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.