text
stringlengths 8
6.88M
|
|---|
#include "DataProcess.h"
DataProcess::DataProcess()
{
}
DataProcess::~DataProcess()
{
}
bool DataProcess::DataLoad(const char * filename,int numbers)
{
cv::FileStorage fs(filename, cv::FileStorage::READ);
if (!fs.isOpened())
{
std::cout << "Open File Error" << std::endl;
return false;
}
std::vector<cv::Mat> temp;
for (int i = 0; i < numbers; i++)
{
std::strstream strnum;
strnum << i;
std::string str1,str("mat");
strnum >> str1;
str.append(str1);
cv::Mat data;
fs[str] >> data;
temp.push_back(data);
}
fs.release();
mat = temp;
return true;
}
void DataProcess::resizeMat(cv::Size size)
{
for (auto c : mat)
{
cv::resize(c, c, size);
}
}
void DataProcess::MatExpend()
{
std::vector<cv::Mat> temp;
for (auto c : mat)
{
temp.push_back(c.reshape(0, 1));
}
mat = temp;
}
bool DataProcess::mergeRows()
{
if (mat.size() == 0)
return false;
int totalRows = mat.size() * mat[0].rows;
cv::Mat mergeDescriptors(totalRows, mat[0].cols, mat[0].type());
int count = 0;
for (auto c : mat)
{
cv::Mat submat = mergeDescriptors.rowRange(count, count + 1);
c.copyTo(submat);
count++;
}
BigMatrix = mergeDescriptors;
return true;
}
void DataProcess::Start(const char *filename,int number)
{
this->DataLoad(filename, number);
this->MatExpend();
this->mergeRows();
}
cv::Mat DataProcess::append(DataProcess & data2)
{
cv::Mat data2_matrix = data2.getBigMatrix();
cv::Mat temp(BigMatrix.rows + data2_matrix.rows, BigMatrix.cols, BigMatrix.type());
cv::Mat submat = temp.rowRange(0, BigMatrix.rows);
BigMatrix.copyTo(submat);
submat = temp.rowRange(BigMatrix.rows, BigMatrix.rows + data2_matrix.rows);
data2_matrix.copyTo(submat);
return temp;
}
void DataProcess::setBigMatrix(const cv::Mat & mat)
{
BigMatrix = mat;
}
cv::Mat DataProcess::getBigMatrix()
{
return BigMatrix;
}
std::vector<cv::Mat> DataProcess::getmat()
{
return mat;
}
cv::Mat DataProcess::PcaProcess(int dimension)
{
if (BigMatrix.empty())
std::cout << "No Data";
BigMatrix.convertTo(BigMatrix, CV_32FC1);
std::cout << BigMatrix.cols;
cv::PCA pca(BigMatrix, cv::Mat(), cv::PCA::DATA_AS_ROW, dimension);
cv::Mat result(BigMatrix.rows, dimension, BigMatrix.type());
for (int i = 0; i < BigMatrix.rows; i++)
{
cv::Mat projectedMat(1, dimension, BigMatrix.type());
pca.project(BigMatrix.row(i), projectedMat);
result.row(i) = projectedMat.row(0) + 0;
}
return result;
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ICharacter.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Kwillum <daniilxod@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/12 18:58:58 by kwillum #+# #+# */
/* Updated: 2021/01/13 00:15:24 by Kwillum ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef ICHARACTER_HPP
# define ICHARACTER_HPP
# include <iostream>
# include <string>
class ICharacter;
# include "AMateria.hpp"
class ICharacter
{
public:
virtual ~ICharacter() {}
virtual std::string const & getName() const = 0;
virtual void equip(AMateria* m) = 0;
virtual void unequip(int idx) = 0;
virtual void use(int idx, ICharacter& target) = 0;
};
#endif
|
#include <iostream>
#include <cstdio>
using namespace std;
struct Stack{
int top;
unsigned capacity;
int * array;
};
int infixToPostfix(char * exp){
//Create a stack of capacity equal to expression size
struct Stack * stack = createStack(strlen(exp));
if(!stack){
//See if stack was created successfully
return -1;
}
for(int i = 0,int k = -1; exp[i]; ++i){
if(isOperand(exp[i])){
exp[++k] = exp[i];
}else if(exp[i] == '('){
push(stack,exp[i]);
}
}
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++){
char exp[400];
scanf("%s",exp);
infixToPostfix(exp);
}
return 0;
}
|
#define SDL_PLUSPLUS_INIT
#include <sdl/sdl>
#include <SDL2/SDL_video.h>
#define LOG(...) fprintf(stdout, __VA_ARGS__)
namespace sdl {
namespace detail {
graphic_context::graphic_context(const window &_w):
id(0), context_flags(0), w(_w) {
memset(attributes, 0, sizeof(attributes));
}
graphic_context::~graphic_context() {
LOG("Destroy graphic context %p\n", id);
SDL_GL_DeleteContext(id);
}
graphic_context& graphic_context::doublebuffered() {
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
return *this;
}
graphic_context &graphic_context::version(const int major, const int minor) {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor);
return *this;
}
graphic_context& graphic_context::with_core_profile() {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
return *this;
}
graphic_context& graphic_context::with_forward_context() {
context_flags |= SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG;
return *this;
}
graphic_context &graphic_context::with_debug_context() {
context_flags |= SDL_GL_CONTEXT_DEBUG_FLAG;
return *this;
}
graphic_context& graphic_context::create() {
LOG("Create graphic context %p\n", id);
if (context_flags)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, context_flags);
id = SDL_GL_CreateContext(static_cast<SDL_Window*>(w.id));
return *this;
}
} // namespace detail
} // namespace sdl
|
#pragma once
#include "glfw3.h"
#include "Engine2d.h"
#include <string>
namespace Engine2d {
class DebugCircle {
public:
std::string name;
GLfloat lineVertices[32];
DebugCircle() {};
DebugCircle(float x, float y, float radius, std::string name = "");
void draw() const;
private:
float x = 0;
float y = 0;
float radius = 0;
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2010-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef DOM_ACCOUNTMANAGER_SUPPORT
#include "modules/dom/src/opera/domoperaaccountmanager.h"
#include "modules/dom/src/domglobaldata.h"
#include "modules/opera_auth/opera_auth_module.h"
#include "modules/opera_auth/opera_account_manager.h"
/* static */ void
DOM_OperaAccountManager::MakeL(DOM_OperaAccountManager *&new_obj, DOM_Runtime *origining_runtime)
{
new_obj = OP_NEW_L(DOM_OperaAccountManager, ());
LEAVE_IF_ERROR(DOMSetObjectRuntime(new_obj, origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::OPERAACCOUNTMANAGER_PROTOTYPE), "OperaAccountManager"));
new_obj->ConstructL();
}
DOM_OperaAccountManager::DOM_OperaAccountManager()
: m_onauthenticationchange(NULL)
{
}
#define PUT_ERROR_CODE_L(x) PutNumericConstantL(object, #x, CoreOperaAccountManager::OPERA_ACCOUNT_##x, runtime)
void
DOM_OperaAccountManager::ConstructL()
{
ES_Object *object = GetNativeObject();
DOM_Runtime *runtime = GetRuntime();
PutNumericConstantL(object, "LOGGED_OUT", 0, runtime);
PutNumericConstantL(object, "LOGIN_ATTEMPT", 1, runtime);
PutNumericConstantL(object, "LOGGED_IN", 2, runtime);
PUT_ERROR_CODE_L(SUCCESS);
PUT_ERROR_CODE_L(ALREADY_LOGGED_IN);
PUT_ERROR_CODE_L(INVALID_USERNAME_PASSWORD);
PUT_ERROR_CODE_L(USER_BANNED);
PUT_ERROR_CODE_L(USER_ALREADY_EXISTS);
PUT_ERROR_CODE_L(INVALID_ENCRYPTION_KEY_USED);
PUT_ERROR_CODE_L(REQUEST_ABORTED);
PUT_ERROR_CODE_L(REQUEST_ERROR);
PUT_ERROR_CODE_L(REQUEST_TIMEOUT);
PUT_ERROR_CODE_L(REQUEST_ALREADY_IN_PROGRESS);
PUT_ERROR_CODE_L(INTERNAL_SERVER_ERROR);
PUT_ERROR_CODE_L(INTERNAL_CLIENT_ERROR);
PUT_ERROR_CODE_L(BAD_REQUEST);
PUT_ERROR_CODE_L(OUT_OF_MEMORY);
PUT_ERROR_CODE_L(PARSING_ERROR);
PUT_ERROR_CODE_L(USERNAME_TOO_SHORT);
PUT_ERROR_CODE_L(USERNAME_TOO_LONG);
PUT_ERROR_CODE_L(USERNAME_CONTAINS_INVALID_CHARACTERS);
PUT_ERROR_CODE_L(PASSWORD_TOO_SHORT);
PUT_ERROR_CODE_L(PASSWORD_TOO_LONG);
PUT_ERROR_CODE_L(EMAIL_ADDRESS_INVALID);
PUT_ERROR_CODE_L(EMAIL_ADDRESS_ALREADY_IN_USE);
LEAVE_IF_ERROR(g_opera_account_manager->AddListener(this));
}
#undef PUT_ERROR_CODE_L
/* virtual */
DOM_OperaAccountManager::~DOM_OperaAccountManager()
{
if (g_opera_account_manager) // This may happen after OperaAuthModule::Destroy().
g_opera_account_manager->RemoveListener(this);
}
/* virtual */ ES_GetState
DOM_OperaAccountManager::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_username:
DOMSetString(value, g_opera_account_manager->GetUsername().CStr());
return GET_SUCCESS;
case OP_ATOM_rememberMe:
DOMSetBoolean(value, g_opera_account_manager->GetSavePasswordSetting());
return GET_SUCCESS;
case OP_ATOM_authState:
DOMSetNumber(value, g_opera_account_manager->IsLoggedIn() ? 2 : g_opera_account_manager->IsRequestInProgress() ? 1 : 0);
return GET_SUCCESS;
case OP_ATOM_authStatus:
DOMSetNumber(value, (int)g_opera_account_manager->LastError());
return GET_SUCCESS;
case OP_ATOM_onauthenticationchange:
DOMSetObject(value, m_onauthenticationchange);
return GET_SUCCESS;
}
return DOM_Object::GetName(property_name, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_OperaAccountManager::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_username:
case OP_ATOM_rememberMe:
case OP_ATOM_authState:
case OP_ATOM_authStatus:
return PUT_READ_ONLY;
case OP_ATOM_onauthenticationchange:
if (value->type != VALUE_OBJECT)
return PUT_SUCCESS;
m_onauthenticationchange = value->value.object;
return PUT_SUCCESS;
}
return DOM_Object::PutName(property_name, value, origining_runtime);
}
/* virtual */ void
DOM_OperaAccountManager::GCTrace()
{
GCMark(m_onauthenticationchange);
}
/* static */ int
DOM_OperaAccountManager::createAccount(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_OPERA_ACCOUNT_MANAGER);
DOM_CHECK_ARGUMENTS("sss|b");
OpString username, password, email;
username.Set(argv[0].value.string);
password.Set(argv[1].value.string);
email.Set(argv[2].value.string);
BOOL rememberMe = FALSE;
if (argc > 3)
rememberMe = argv[3].value.boolean;
g_opera_account_manager->CreateAccount(username, password, email, rememberMe);
return ES_FAILED; // No return value.
}
/* static */ int
DOM_OperaAccountManager::login(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_OPERA_ACCOUNT_MANAGER);
DOM_CHECK_ARGUMENTS("ss|b");
OpString username, password;
username.Set(argv[0].value.string);
password.Set(argv[1].value.string);
BOOL rememberMe = FALSE;
if (argc > 2)
rememberMe = argv[2].value.boolean;
g_opera_account_manager->Login(username, password, rememberMe);
return ES_FAILED; // No return value.
}
/* static */ int
DOM_OperaAccountManager::logout(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_OPERA_ACCOUNT_MANAGER);
g_opera_account_manager->Logout();
return ES_FAILED; // No return value.
}
/* static */ int
DOM_OperaAccountManager::abort(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_OPERA_ACCOUNT_MANAGER);
g_opera_account_manager->Abort();
return ES_FAILED; // No return value.
}
DOM_FUNCTIONS_START(DOM_OperaAccountManager)
DOM_FUNCTIONS_FUNCTION(DOM_OperaAccountManager, DOM_OperaAccountManager::createAccount, "createAccount", "sssb-")
DOM_FUNCTIONS_FUNCTION(DOM_OperaAccountManager, DOM_OperaAccountManager::login, "login", "ssb-")
DOM_FUNCTIONS_FUNCTION(DOM_OperaAccountManager, DOM_OperaAccountManager::logout, "logout", "")
DOM_FUNCTIONS_FUNCTION(DOM_OperaAccountManager, DOM_OperaAccountManager::abort, "abort", "")
DOM_FUNCTIONS_END(DOM_OperaAccountManager)
/* virtual */ void
DOM_OperaAccountManager::OnAccountLoginStateChange()
{
DOM_Runtime *runtime = GetRuntime();
ES_AsyncInterface *asyncif = runtime->GetEnvironment()->GetAsyncInterface();
if (!m_onauthenticationchange)
return;
if (op_strcmp(ES_Runtime::GetClass(m_onauthenticationchange), "Function") == 0)
{
asyncif->CallFunction(m_onauthenticationchange, NULL, 0, NULL, NULL);
return;
}
// Make a dummy Event argument.
ES_Value arguments[1];
DOM_Event *event = OP_NEW(DOM_Event, ());
RETURN_VOID_IF_ERROR(DOMSetObjectRuntime(event, runtime, runtime->GetPrototype(DOM_Runtime::EVENT_PROTOTYPE), "AuthenticationChangeEvent"));
event->InitEvent(DOM_EVENT_CUSTOM, NULL);
RETURN_VOID_IF_ERROR(event->SetType(UNI_L("AuthenticationChangeEvent")));
DOM_Object::DOMSetObject(&arguments[0], event);
asyncif->CallMethod(m_onauthenticationchange, UNI_L("handleEvent"), 1, arguments, NULL);
}
#endif // DOM_ACCOUNTMANAGER_SUPPORT
|
#include <stdio.h>
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8};
int (*p)[4]=a;//数组的指针,指向大小为4的一维数组
printf("%d\n",*(p)[2]);
return 1;
}
|
/* -*- 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.
*/
#ifndef OP_WIDGET_H
#define OP_WIDGET_H
#include "modules/pi/OpInputMethod.h"
#include "modules/util/simset.h"
class VisualDevice;
class Window;
class HTMLayoutProperties;
#ifdef NAMED_WIDGET
class OpNamedWidgetsCollection;
#endif // NAMED_WIDGET
#ifdef INTERNAL_SPELLCHECK_SUPPORT
class OpEditSpellchecker;
#endif // INTERNAL_SPELLCHECK_SUPPORT
#include "modules/display/cursor.h"
#include "modules/display/vis_dev_transform.h" // AffinePos
#include "modules/pi/OpWindow.h"
#include "modules/hardcore/timer/optimer.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/pi/ui/OpUiInfo.h"
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
# include "modules/accessibility/opaccessibleitem.h"
class AccessibleOpWidgetLabel;
#endif
#include "modules/inputmanager/inputcontext.h"
#include "modules/widgets/OpEditCommon.h"
#include "modules/widgets/OpWidgetPainterManager.h"
#include "modules/util/adt/opvector.h"
#include "modules/util/OpHashTable.h"
#ifdef SKIN_SUPPORT
# include "modules/skin/OpWidgetImage.h"
#endif // SKIN_SUPPORT
#include "modules/widgets/optextfragmentlist.h"
#ifdef WIDGETS_IMS_SUPPORT
#include "modules/widgets/OpIMSObject.h"
#endif // WIDGETS_IMS_SUPPORT
#ifdef USE_OP_CLIPBOARD
# include "modules/dragdrop/clipboard_manager.h"
#endif // USE_OP_CLIPBOARD
// Will probably be turned into tweaks at some point.. Trying to clean up things.
#if defined(QUICK) || defined(GOGI)
#define WIDGETS_UI
#endif
#define WIDGETS_MOVE_CARET_TO_SELECTION_STARTSTOP
// How to modify the look & feel
//
// OpWidgetPainter.
// Inherit to make a entire new painter for the widgets. The default
// widgetpainter supports CSS. Any function can return FALSE to
// fallback to the original CssWidgetPainter.
//
// To support CSS you just need to NOT draw borders or backgrounds if
// OpWidget::HasCssBorder.. is TRUE. The actual drawing of CSS is done by core.
//
// A widgetpainter is set on the global paintermanager.
//
// OpWidgetInfo.
// Inherit your own version and override what you want
// to change the behaviours or the size of the widgets.
// Return it from OpWidgetPainter::GetInfo().
//
// Additional info
// -IndpWidgetPainter draws skinned forms.
// -Editing and all kind of keyboard interaction is specified
// with the input.ini.
// -The colors used by default in the CssWidgetPainter is the
// systemcolors in OpSystemInfo.
//
// Need more?
// emil@opera.com
//
class AutoCompletePopup;
class OpWidget;
class OpButton;
class OpRadioButton;
class OpCheckBox;
class OpListBox;
class OpScrollbar;
class OpToolbar;
class OpSplitter;
class OpTreeView;
class OpEdit;
class OpMultilineEdit;
class OpResizeCorner;
class OpBrowserView;
class OpFileChooserEdit;
class OpDropDown;
class OpFontInfo;
class OpTreeModel;
class OpStringItem;
class OpWidgetString;
class OpBitmap;
class FormObject;
class WidgetContainer;
class OpDragObject;
class DesktopWindow;
class OpWorkspace;
class OpItemSearch;
class OpIMSObject;
class OpIMSUpdateList;
class OpCalendar;
#define REPORT_AND_RETURN_IF_ERROR(status) if (OpStatus::IsError(status)) \
{ \
if (OpStatus::IsMemoryError(status)) \
ReportOOM(); \
return; \
}
#define CHECK_STATUS(status) if (OpStatus::IsError(status)) \
{ \
init_status = status; \
return; \
}
#define DEFINE_CONSTRUCT(objecttype) OP_STATUS objecttype::Construct(objecttype** obj) \
{ \
*obj = OP_NEW(objecttype, ()); \
if (*obj == NULL) \
return OpStatus::ERR_NO_MEMORY; \
if (OpStatus::IsError((*obj)->init_status)) \
{ \
OP_DELETE(*obj); \
return OpStatus::ERR_NO_MEMORY; \
} \
return OpStatus::OK; \
}
#ifdef WIDGETS_IME_SUPPORT
/** Input method info */
struct IME_INFO {
INT16 start, stop; ///< Position of eventual inputmethodstring.
INT16 can_start, can_stop; ///< Position of eventual candidate in inputmethodstring.
OpInputMethodString* string;
};
#endif // WIDGETS_IME_SUPPORT
/** A collection of all the globals that the widgetmodule use. */
struct WIDGET_GLOBALS {
// For OpWidget
OpPoint start_point; ///< used to decide threshold for drag-n-drop
OpPoint last_mousemove_point; ///< last mouse position over the last hovered widget
OpWidget* hover_widget; ///< Current hovering widget
#ifdef DRAG_SUPPORT
OpWidget* drag_widget; ///< Current drag source or drog target widget
#endif // DRAG_SUPPORT
#ifndef MOUSELESS
/**
* A captured widget will receieve all mousemoves and the mouseup
* event even if those happens outside the widget. It's typically
* triggered by a mousedown "arming" the widget.
*/
OpWidget* captured_widget;
#endif // !MOUSELESS
#ifdef SKIN_SUPPORT
/**
* The widget that is currently painted with skin elements.
*/
OpWidget* skin_painted_widget;
/**
* Additional widget states of the widget that is currently
* painted with skin elements. The information is intended for
* native skin drawing code.
*/
INT32 painted_widget_extra_state;
#endif
// For OpWidgetString
uni_char * passwd_char; ///< the character to show instead of the typed character in password fields
const uni_char * dummy_str; ///< should always be empty, used to avoid doing null-checks and such
#ifdef WIDGETS_IME_SUPPORT
IME_INFO ime_info;
#endif
// OpDropDown
/**
X11 sends two mouse events when a popup window is closed. We have to
block the second when the mouse clicked on the dropdown arrow when
the dropdown was already visible.
The pointer itself is never used, we just compare it with the 'this'
pointer
*/
OpDropDown* m_blocking_popup_dropdown_widget;
// Op(Multi)Edit-related
// Instances of all CharRecognizer subclasses
WordCharRecognizer word_char_recognizer;
WhitespaceCharRecognizer whitespace_char_recognizer;
WordDelimiterCharRecognizer word_delimiter_char_recognizer;
// char_recognizers is an array containing all instances of
// CharRecognizer subclasses
CharRecognizer* char_recognizers[N_CHAR_RECOGNIZERS];
/**
X11 sends two mouse events when a popup window is closed. We have to
block the second when the mouse clicked on the dropdown arrow when
the dropdown was already visible.
The pointer itself is never used, we just compare it with the 'this'
pointer
*/
OpCalendar* m_blocking_popup_calender_widget;
// OpListBox
BOOL had_selected_items; ///< fix for OnChange if no items where selected in a dropdown. (If selectedindex was set to -1)
BOOL is_down; ///< keep track on whether a listbox widget has received mouse down but not mouse up
OpItemSearch* itemsearch; ///< used for keyboard input searching in listbox
// AutoCompletePopup
AutoCompletePopup* curr_autocompletion; ///< for autocompletion
BOOL autocomp_popups_visible; ///< for autocompletion
};
/**
Listener for events used by all widgets
*/
class OpWidgetListener
{
public:
virtual ~OpWidgetListener() {}; ///< destructor, does nothing
/** Sent by OpWidget when widget is enabled/disabled */
virtual void OnEnabled(OpWidget *widget, BOOL enabled) {};
/** Sent by OpWidget when widget's contents should be laid out*/
virtual void OnLayout(OpWidget *widget) {};
/** Send when relayout occurs */
virtual void OnRelayout(OpWidget* widget) {};
/** Send when post-layout occurs */
virtual void OnLayoutAfterChildren(OpWidget* widget) {};
/** Used by all objects */
virtual void OnClick(OpWidget *widget, UINT32 id = 0) { }
/** Widget has been painted */
virtual void OnPaint(OpWidget *widget, const OpRect &paint_rect) {}
/** Send before wigdet is painted */
virtual void OnBeforePaint(OpWidget *widget) { }
/**
* Used by button widgets in addition to OnClick to inform the
* listener that a click was generated internally in the button,
* maybe as a response to a keypress or action.
*/
virtual void OnGeneratedClick(OpWidget *widget, UINT32 id = 0) { }
/** Used by OpEdit, OpMultilineEdit, OpListbox, OpCombobox, OpTreeView */
virtual void OnChange(OpWidget *widget, BOOL changed_by_mouse = FALSE) {};
/** Used by OpEdit, OpMultilineEdit
Should be called if the widget has been changed when it loses the focus (since it got the focus).
*/
virtual void OnChangeWhenLostFocus(OpWidget *widget) {};
/**
* Same as OnMouseEvent, but always called before the widget gets time to
* handle the mouse event. May consume the mouse event.
* Only called for OpEdit and OpMultiEdit.
* @return TRUE if the mouse event was consumed by the listener and the widget should
* not continue processing it, FALSE otherwise.
*/
virtual BOOL OnMouseEventConsumable(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks) { return FALSE; }
virtual void OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks) { }
/** Called when the mouse pointer moves over the widget.
@param widget the widget in question
*/
virtual void OnMouseMove(OpWidget *widget, const OpPoint &point) {};
/** Called when the mouse pointer leaves the widget.
@param widget the widget in question
*/
virtual void OnMouseLeave(OpWidget *widget) {}
/**
* User requested popup menu (right mouse up, or keyboard etc)
* @param widget The widget on top of which the popup is opened
* @param child_index The index of the child widget, e.g. in a toolbar, that is sending the OnContextMenu request
* @param menu_point The position (relative to the widget) where the popup should appear
* @param avoid_rect The area that should not be covered by the popup. NULL if not needed.
* @param keyboard_invoked TRUE if context menu is invoked by keypress (as opposed to mouse).
*/
virtual BOOL OnContextMenu(OpWidget* widget, INT32 child_index, const OpPoint &menu_point, const OpRect *avoid_rect, BOOL keyboard_invoked) { return FALSE; }
/** Used by OpEdit, OpMultilineEdit when the selection changes */
virtual void OnSelect(OpWidget *widget) {};
/** Used by OpScrollbar
caused_by_input is FALSE if the scroll is caused by f.ex. a SetLimit which shrinks the position, or a SetValue
called by YOU. */
virtual void OnScroll(OpWidget *widget, INT32 old_val, INT32 new_val, BOOL caused_by_input) {};
#ifdef NOTIFY_ON_INVOKE_ACTION
/** Used by OpEdit to broadcast that an action will now be invoked */
virtual void OnInvokeAction(OpWidget *widget, BOOL invoked_by_mouse) {}
#endif // NOTIFY_ON_INVOKE_ACTION
#ifdef QUICK
/** Used by OpTreeView */
virtual void OnItemChanged(OpWidget *widget, INT32 pos) {};
virtual void OnItemEdited(OpWidget *widget, INT32 pos, INT32 column, OpString& text) {};
/* Returns TRUE if change can be accepted, @ref OnItemEdited is called immediately after this */
virtual BOOL OnItemEditVerification(OpWidget *widget, INT32 pos, INT32 column, const OpString& text) { return TRUE; };
virtual void OnItemEditAborted(OpWidget *widget, INT32 pos, INT32 column, OpString& text) {};
virtual void OnSortingChanged(OpWidget *widget) {};
/** Should generally be used by all so that we can provide better UI feedback */
virtual void OnFocusChanged(OpWidget *widget, FOCUS_REASON reason) {}
#endif
#ifdef DRAG_SUPPORT
/** Used for drag'n'drop */
virtual void OnDragStart(OpWidget* widget, INT32 pos, INT32 x, INT32 y);
virtual void OnDragMove(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y) {}
virtual void OnDragDrop(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y) {}
virtual void OnDragLeave(OpWidget* widget, OpDragObject* drag_object) {};
virtual void OnDragCancel(OpWidget* widget, OpDragObject* drag_object) {};
#endif // DRAG_SUPPORT
/** Called from widgets that receive lowlevel key events
to check if the key input should be accepted.
@param value The character value string produced by the key press/input.
@return TRUE if the input should be accepted as consumed, FALSE
if it shouldn't be. */
virtual BOOL OnCharacterEntered( const uni_char *value ) { return TRUE; }
/** Called with show TRUE *before* the dropdown occurs.
Called with show FALSE *after* the dropdown has been closed.
*/
virtual void OnDropdownMenu(OpWidget *widget, BOOL show) {}
/** May be passed to OnResizeRequest() to indicate no change in size. */
static const INT32 NO_RESIZE = -1;
/** Called when a resize is requested by the user.
The dimensions are "border-box" dimensions, which means that they
represent the actual footprint the OpWidget should end up with on
the page, including padding and borders.
@param widget The OpWidget that was resized.
@param w The new width of the OpWidget. (Use NO_RESIZE to leave size unchanged).
@param h The new height of the OpWidget. (Use NO_RESIZE to leave size unchanged). */
virtual void OnResizeRequest(OpWidget *widget, INT32 w, INT32 h) {};
};
/**
Listener for misc widgets events, set globally for entire opera. Several instances of this listener can be set.
*/
class OpWidgetExternalListener : public Link
{
public:
/** widget has received or lost focus. */
virtual void OnFocus(OpWidget *widget, BOOL focus, FOCUS_REASON reason) {}
/** Widget will be deleted sometime very soon after this call. */
virtual void OnDeleted(OpWidget *widget) {}
};
struct WIDGET_COLOR {
BOOL use_default_foreground_color; ///< If TRUE, you should not care about foreground_color
BOOL use_default_background_color; ///< If TRUE, you should not care about background_color
UINT32 foreground_color; ///< foreground (i.e. text/checkmark) color
UINT32 background_color; ///< background color
};
/**
justification enum
*/
enum JUSTIFY {
JUSTIFY_LEFT, ///< text is left-aligned
JUSTIFY_CENTER, ///< text is centered
JUSTIFY_RIGHT ///< text is right-aligned
};
enum WIDGET_V_ALIGN {
WIDGET_V_ALIGN_TOP = 0,
WIDGET_V_ALIGN_MIDDLE
};
/**
the widget's font info
*/
struct WIDGET_FONT_INFO {
const OpFontInfo* font_info; ///< the OpFontInfo of the widget's font
INT16 size; ///< the size of the font
BOOL italic; ///< true if the text is italic
short weight; ///< the weight of the font
int char_spacing_extra; ///< any extra character space
JUSTIFY justify; ///< the justification
};
/**
IDs for margins, for GetItemMargin
*/
enum WIDGET_MARGIN {
MARGIN_TOP, ///< top margin
MARGIN_LEFT, ///< left margin
MARGIN_RIGHT, ///< right margin
MARGIN_BOTTOM ///< bottom margin
};
enum WIDGET_TEXT_DECORATION {
WIDGET_LINE_THROUGH = 0x01 /// < Draw a line on top of text
};
/**
scrollbar mode for widgets
*/
enum WIDGET_SCROLLBAR_STATUS {
SCROLLBAR_STATUS_AUTO, ///< show vertical scrollbar always, and horizontal only when needed
SCROLLBAR_STATUS_ON, ///< show both scrollbars always
SCROLLBAR_STATUS_OFF ///< show no scrollbars
};
/**
Describes how a OpWidget can be resized by the user.
*/
enum WIDGET_RESIZABILITY {
WIDGET_RESIZABILITY_NONE = 0x0, ///< Not resizable. Hide resize corner.
WIDGET_RESIZABILITY_HORIZONTAL = 0x1, ///< Resizable horizontally only.
WIDGET_RESIZABILITY_VERTICAL = 0x2, ///< Resizable vertically only.
WIDGET_RESIZABILITY_BOTH = WIDGET_RESIZABILITY_HORIZONTAL | WIDGET_RESIZABILITY_VERTICAL
};
/**
Describes hove a widget should move or resize when the parent widget resize.
*/
enum RESIZE_EFFECT
{
RESIZE_FIXED, ///< Isn't affected at all
RESIZE_MOVE, ///< Move as much as the parent resize so that if follows the right or bottom of the parent.
RESIZE_SIZE, ///< Don't move, but resize as much as the parent.
RESIZE_CENTER ///< Move so it is centered in the parent.
};
/**
search mode when searching for text in widgets
*/
enum SEARCH_TYPE {
SEARCH_FROM_CARET, ///< search starts from the current caret pos
SEARCH_FROM_BEGINNING, ///< search starts from the beginning of the contents
SEARCH_FROM_END ///< search starts from the end of the contents
};
/**
the different parts of the scrollbar
*/
enum SCROLLBAR_PART_CODE {
INVALID_PART = 0x00,
LEFT_OUTSIDE_ARROW = 0x01, ///< the left arrow on a horizontal scrollbar (with one arrow placed on either side)
LEFT_INSIDE_ARROW = 0x02, ///< the right arrow on a horizontal scrollbar with both buttons placed to the left
LEFT_TRACK = 0x04, ///< the part between the handle and left arrow button of a horizontal scrollbar
KNOB = 0x08, ///< the handle in the middle of the scrollbar, that indicates the current scroll position
RIGHT_TRACK = 0x10, ///< the part between the handle and right arrow button of a horizontal scrollbar
RIGHT_INSIDE_ARROW = 0x20, ///< the left arrow on a horizontal scrollbar with both button placed to the right
RIGHT_OUTSIDE_ARROW = 0x40, ///< the right arrow on a horizontal scrollbar (with one arrow placed on either side)
TOP_OUTSIDE_ARROW = LEFT_OUTSIDE_ARROW,
TOP_INSIDE_ARROW = LEFT_INSIDE_ARROW,
TOP_TRACK = LEFT_TRACK,
BOTTOM_TRACK = RIGHT_TRACK,
BOTTOM_INSIDE_ARROW = RIGHT_INSIDE_ARROW,
BOTTOM_OUTSIDE_ARROW = RIGHT_OUTSIDE_ARROW
};
/**
the type of scrollbar
*/
enum SCROLLBAR_ARROWS_TYPE {
ARROWS_NORMAL = 0x00, ///< normal scrollbar, one arrow button on each end
ARROWS_AT_TOP = 0x01, ///< both arrow buttons are at top
ARROWS_AT_BOTTOM = 0x02, ///< both arrow buttons are at bottom
ARROWS_AT_BOTTOM_AND_TOP = 0x04 ///< both arrow buttons are at both bottom and top
};
/**
ellipsis is drawing three dots whenever there's not enough room for all text in a widget
*/
enum ELLIPSIS_POSITION {
ELLIPSIS_NONE = 0, ///< If there is no room for all text, it will be clipped.
ELLIPSIS_CENTER = 1, ///< If there is no room for all text, the beginning and end will be drawn. The center will have ellipsis ("...")
ELLIPSIS_END ///< If there is no room for all text, the beginning will be drawn and end with ellipsis ("...")
};
/**
Unknown QUICK feature that is not used in core.
*/
enum DROP_POSITION {
DROP_ALL = 0x00,
DROP_CENTER = 0x01,
DROP_LEFT = 0x02,
DROP_RIGHT = 0x04,
DROP_TOP = 0x10,
DROP_BOTTOM = 0x20
};
/**
Unknown QUICK feature.
*/
enum UpdateNeededWhen {
UPDATE_NEEDED_NEVER = 0,
UPDATE_NEEDED_WHEN_VISIBLE,
UPDATE_NEEDED_ALWAYS
};
/**
Info about sizes and some behaviours for all default widgets used by piforms.
*/
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
enum AccessibilityPrune {
ACCESSIBILITY_DONT_PRUNE = 0,
ACCESSIBILITY_PRUNE,
ACCESSIBILITY_PRUNE_WHEN_INVISIBLE
};
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
class OpWidgetInfo
{
public:
virtual ~OpWidgetInfo() {} ///< destructor
/** Se OpWidget.h for parameter details. */
virtual void GetPreferedSize(OpWidget* widget, OpTypedObject::Type type, INT32* w, INT32* h, INT32 cols, INT32 rows);
/** Se OpWidget.h for parameter details. */
virtual void GetMinimumSize(OpWidget* widget, OpTypedObject::Type type, INT32* minw, INT32* minh);
/**
if skinning is enabled, asks skin. if not, asks OpUiInfo.
@param color which color is wanted
@return the color
*/
virtual UINT32 GetSystemColor(OP_SYSTEM_COLOR color);
virtual UINT32 GetVerticalScrollbarWidth();
virtual UINT32 GetHorizontalScrollbarHeight();
/** Shrinks the rect with the border size */
virtual void AddBorder(OpWidget* widget, OpRect *rect);
virtual void GetBorders(OpWidget* widget, INT32& left, INT32& top, INT32& right, INT32& bottom);
virtual INT32 GetItemMargin(WIDGET_MARGIN margin);
virtual void GetItemMargin(INT32 &left, INT32 &top, INT32 &right, INT32 &bottom);
virtual INT32 GetDropdownButtonWidth(OpWidget* widget);
virtual INT32 GetDropdownLeftButtonWidth(OpWidget* widget);
/** Return the height of the upper button (for a vertical scrollbar), or the width of the left button. */
virtual INT32 GetScrollbarFirstButtonSize();
virtual INT32 GetScrollbarSecondButtonSize();
/**
* Return the preferred style for scrollbar arrows, default is ARROWS_NORMAL which means a single
* arrow in each end of the scrollbar.
*/
virtual SCROLLBAR_ARROWS_TYPE GetScrollbarArrowStyle();
/**
Return which direction a scrollbar button points to. Could be used to make scrollbars with f.eks. no button in
the top and 2 at the bottom.
pos is the mousepos relative to the buttons x position (for a horizontal scrollbar) or y position (for a vertical).
Return values should be: 0 for UP (or LEFT),
1 for DOWN (or RIGHT)
*/
virtual BOOL GetScrollbarButtonDirection(BOOL first_button, BOOL horizontal, INT32 pos);
/**
* Decide which part of a scrollbar is at the given point.
* Override this method and return TRUE to make OpScrollbar use it instead of the built in click-detection.
* The hit part should be passed back in the parameter hitPart.
*
* Returns FALSE by default.
*/
virtual BOOL GetScrollbarPartHitBy(OpWidget *widget, const OpPoint &pt, SCROLLBAR_PART_CODE &hitPart);
#ifdef PAGED_MEDIA_SUPPORT
/**
* Get the height of a page control widget.
*/
virtual INT32 GetPageControlHeight();
#endif // PAGED_MEDIA_SUPPORT
/** Returnvalue should be in milliseconds. */
UINT32 GetCaretBlinkDelay() { return 500; }
UINT32 GetScrollDelay(BOOL bigstep, BOOL first_step);
/** Return how far away the user can drag outside the scrollbar without dropping it. */
INT32 GetDropScrollbarLength() { return 100; }
/** Return TRUE if a button should be released when moving outside it. */
BOOL CanDropButton() { return TRUE; }
};
/// Handles fontswitching/painting/justifying and storage of a string.
class OpWidgetString
{
public:
OpWidgetString();
~OpWidgetString();
INT32 GetMaxLength() const { return max_length; }
void SetMaxLength(INT32 length) { max_length = length; }
void SetPasswordMode(BOOL password_mode) { m_packed.password_mode = password_mode; }
BOOL GetPasswordMode() { return m_packed.password_mode; }
void SetConvertAmpersand(BOOL convert_ampersand) {m_packed.convert_ampersand = convert_ampersand;}
BOOL GetConvertAmpersand() {return m_packed.convert_ampersand;}
void SetDrawAmpersandUnderline(BOOL draw_ampersand_underline) {m_packed.draw_ampersand_underline = draw_ampersand_underline;}
BOOL GetDrawAmpersandUnderline() {return m_packed.draw_ampersand_underline;}
/**
* Set one or more text decoration properties on the string. Use
* 0 to clear the property.
*
* @param text_decoration One or more of WIDGET_TEXT_DECORATION types
* @param replace If TRUE, the current value is fully replaced, if FALSE
* the new value is added to the current value
*/
void SetTextDecoration(INT32 text_decoration, BOOL replace)
{ m_text_decoration = replace ? text_decoration : m_text_decoration | text_decoration; }
INT32 GetTextDecoration() const {return m_text_decoration; }
/** Set if the widgetstring should have italic style even if the OpWidget doesn't have that style. */
void SetForceItalic(BOOL force) { m_packed.force_italic = force; }
BOOL GetForceItalic() { return m_packed.force_italic; }
/** Set if the widgetstring should have bold style even if the OpWidget doesn't have that style. */
void SetForceBold(BOOL force) { m_packed.force_bold = force; }
BOOL GetForceBold() { return m_packed.force_bold; }
/** Set if the widgetstring should be treated as LTR even if the OpWidget is RTL. */
void SetForceLTR(BOOL force) { m_packed.force_ltr = force; }
BOOL GetForceLTR() const { return m_packed.force_ltr; }
#ifdef WIDGETS_ADDRESS_SERVER_HIGHLIGHTING
enum DomainHighlight
{
None,
RootDomain, // abc.google.com -> highlight "google.com"
WholeDomain // abc.google.com -> highlight all
};
/** Set if the widgetstring should grey out the parts that does not belong to a server name if the string is a web address.
So a address like http://my.opera.com/community/ would have http:// and /community greyed out.
@param type highlight type
*/
void SetHighlightType(DomainHighlight type);
INT32 GetHighlightType() {return m_highlight_type;}
#endif // WIDGETS_ADDRESS_SERVER_HIGHLIGHTING
void ToggleOverstrike() {m_packed.is_overstrike = !m_packed.is_overstrike;}
BOOL GetOverstrike() {return m_packed.is_overstrike;}
void Reset(OpWidget* widget);
OP_STATUS Set(const uni_char* str, OpWidget* widget);
OP_STATUS Set(const uni_char* str, int len, OpWidget* widget);
const uni_char* Get() const;
void SelectNone();
void SelectFromCaret(INT32 caret_pos, INT32 delta);
void Select(INT32 start, INT32 stop);
#ifdef WIDGETS_IME_SUPPORT
// Input Methods. (For showing the underline in composemode and marking the right candidates in candidatemode).
void SetIMNone();
void SetIMPos(INT32 pos, INT32 length);
void SetIMCandidatePos(INT32 pos, INT32 length);
void SetIMString(OpInputMethodString* string);
INT16 GetIMLen() { return m_ime_info ? m_ime_info->stop - m_ime_info->start : 0; }
#ifdef SUPPORT_IME_PASSWORD_INPUT
void ShowPasswordChar(int caret_pos);
void HidePasswordChar();
#endif // SUPPORT_IME_PASSWORD_INPUT
#endif // WIDGETS_IME_SUPPORT
/** Returns the character position (offset) at the point, if the string where drawn in rect.
* @param rect The rect the string would be drawn inside.
* @param point The point.
* @param snap_forward Will return TRUE if the offset has 2 visual positions (As with BIDI) and the second is the one that was found.
*/
INT32 GetCaretPos(OpRect rect, OpPoint point, BOOL* snap_forward = NULL);
/** Returns the x position for the caret_pos (offset), if the string where drawn in rect.
* @param rect The rect the string would be drawn inside.
* @param caret_pos The logical offset you want to get the x position of.
* @param snap_forward If TRUE and there is 2 visual positions for the offset (As with BIDI), the second is the one that is returned.
*/
INT32 GetCaretX(OpRect rect, int caret_pos, BOOL snap_forward);
/** Justify and apply text-indent on the string as if inside rect, and return the new x. */
int GetJustifyAndIndent(const OpRect &rect);
INT32 GetWidth();
INT32 GetHeight();
/** Make the widget update any cached into next time it's needed (such as width, height, fragments) */
void NeedUpdate() {m_packed.need_update = TRUE;}
/** Update cached values and fragments if NeedUpdate has been called (otherwise it does nothing). */
OP_STATUS Update(VisualDevice* vis_dev = 0);
#ifdef WIDGETS_ELLIPSIS_SUPPORT
BOOL DrawFragmentSpecial(VisualDevice* vis_dev, int &x_pos, int y, OP_TEXT_FRAGMENT* frag, ELLIPSIS_POSITION ellipsis_position, int &used_space, const OpRect& rect);
#endif
/**
* You can use OpWidgetStringDrawer class instead of this function to get more control on the drawing options.
* @see OpWidgetStringDrawer
*/
// original prototype :
//void Draw(OpRect rect, VisualDevice* vis_dev, UINT32 color,
// INT32 caret_pos = -1, ELLIPSIS_POSITION ellipsis_position = ELLIPSIS_NONE,
// BOOL underline = FALSE, INT32 x_scroll = 0, BOOL caret_snap_forward = FALSE, BOOL only_text = FALSE);
void Draw(const OpRect& rect, VisualDevice* vis_dev, UINT32 color);
static OP_SYSTEM_COLOR GetSelectionTextColor(BOOL is_search_hit, BOOL is_focused);
static OP_SYSTEM_COLOR GetSelectionBackgroundColor(BOOL is_search_hit, BOOL is_focused);
void SetScript(WritingSystem::Script script);
/** Gets a list of rectangles a text selection consist of (if any) and a rectangle being a union of all rectangles in the list.
*
* @param vis_dev - the edit's visual device.
* @param list - a pointer to the list to be filled in.
* @param union_rect - a union of all rectangles in the list.
* @param scroll - edit's scroll position in pixels.
* @param text_rect - edit's text rectangle.
* @param only_visible - If true only the visible selection's part will be taken into account.
*/
OP_STATUS GetSelectionRects(VisualDevice* vis_dev, OpVector<OpRect>* list, OpRect& union_rect, int scroll, const OpRect& text_rect, BOOL only_visible);
/** Checks if a given point in contained by any of the selection rectangle.
*
* @param vis_dev - the edit's visual device.
* @param point - a point to be checked.
* @param scroll - edit's scroll position in pixels.
* @param text_rect - edit's text rectangle.
*/
BOOL IsWithinSelection(VisualDevice* vis_dev, const OpPoint& point , int scroll, const OpRect& text_rect);
private:
#ifdef _NO_GLOBALS_
friend struct Globals;
#endif
friend class OpEdit;
#ifdef INTERNAL_SPELLCHECK_SUPPORT
friend class OpEditSpellchecker;
#endif // INTERNAL_SPELLCHECK_SUPPORT
friend class OpWidgetStringDrawer;
OpWidget* widget;
const uni_char* str;
uni_char* str_original; ///< If we have text_translation on the widget we must keep the unmodified string.
OpTextFragmentList fragments;
OP_STATUS UpdateFragments();
void UpdateVisualDevice(VisualDevice *vis_dev = NULL);
BOOL ShouldDrawFragmentsReversed(const OpRect& rect, ELLIPSIS_POSITION ellipsis_position) const;
int GetFontNumber();
OpWidget* GetWidget() const { return widget; }
const uni_char* GetStr() const { return str; }
OpTextFragmentList* GetFragments() { return &fragments; }
BOOL UseAccurateFontSize();
#if defined(WIDGETS_IME_SUPPORT) && defined(SUPPORT_IME_PASSWORD_INPUT)
OP_STATUS UpdatePasswordText();
int uncoveredChar;
#endif
union
{
struct
{
unsigned char is_overstrike:1;
unsigned char password_mode:1;
unsigned char convert_ampersand:1;
unsigned char draw_ampersand_underline:1;
unsigned char need_update:1;
unsigned char force_italic:1;
unsigned char force_bold:1;
unsigned char force_ltr:1;
#ifdef WIDGETS_HEURISTIC_LANG_DETECTION
unsigned char need_update_script:1;
#endif // WIDGETS_HEURISTIC_LANG_DETECTION
unsigned char draw_centerline:1;
} m_packed;
unsigned short m_packed_init;
};
INT32 width;
INT16 height;
INT32 max_length;
WritingSystem::Script m_script;
#ifdef WIDGETS_ADDRESS_SERVER_HIGHLIGHTING
DomainHighlight m_highlight_type;
OP_STATUS UpdateHighlightOffset();
#endif // WIDGETS_ADDRESS_SERVER_HIGHLIGHTING
#ifdef WIDGETS_HEURISTIC_LANG_DETECTION
WritingSystem::Script m_heuristic_script;
#endif // WIDGETS_HEURISTIC_LANG_DETECTION
INT32 m_text_decoration;
public:
#ifdef WIDGETS_IME_SUPPORT
IME_INFO* m_ime_info;
#endif //WIDGETS_IME_SUPPORT
INT32 sel_start, sel_stop;
#ifdef WIDGETS_ADDRESS_SERVER_HIGHLIGHTING
INT16 m_highlight_ofs;
INT16 m_highlight_len;
#endif // WIDGETS_ADDRESS_SERVER_HIGHLIGHTING
};
#ifdef QUICK
# include "adjunct/quick_toolkit/widgets/QuickOpWidgetBase.h"
#endif // QUICK
/** Base class for all widgets.
*/
class OpWidget : public Link, public OpInputContext, public OpTimerListener, public MessageObject
#if defined (QUICK)
, public QuickOpWidgetBase
#endif
#ifdef SKIN_SUPPORT
, public OpWidgetImageListener
#endif
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
, public OpAccessibleItem
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
#ifdef WIDGETS_IMS_SUPPORT
, public OpIMSListener
#endif // WIDGETS_IMS_SUPPORT
#ifdef USE_OP_CLIPBOARD
, public ClipboardListener
#endif // USE_OP_CLIPBOARD
{
friend class ResourceManager;
friend class OpWidgetString;
friend class OpDropDown;
friend class QuickOpWidgetBase;
public:
/**
constructor. initializes anything to nothing.
*/
OpWidget();
protected:
/**
destructor is protected because it is illegal to destruct an item that has a parent..
use Delete() instead so it can remove itself first
*/
virtual ~OpWidget();
public:
/** This is here for compability-reasons. You should NOT write new code using OpWidget::over_widget or OpWidget::hover_widget.
Use g_widget_globals->hover_widget instead!! */
static OpWidget*& over_widget();
/** This is here for compability-reasons. You should NOT write new code using OpWidget::over_widget or OpWidget::hover_widget.
Use g_widget_globals->hover_widget instead!! */
#define over_widget over_widget()
#ifndef MOUSELESS
/**
calls OnCaptureLost on any captured widget and zero:s the pointer
*/
static void ZeroCapturedWidget();
/**
calls OnMouseLeave on any currently hovered widget and zero:s the pointer
*/
static void ZeroHoveredWidget();
/**
gets hooked_widget, which is the same as captured_widget. whenever a widget receives mouse down,
this widget is set as the hooked widget. when the widget receives its last mouse up or a mouse
leave, hooked_widget is zero:ed.
@return a reference to the hooked widget pointer
*/
static OpWidget*& hooked_widget();
/**
shorthand for OpWidget::hooked_widget()
*/
#define hooked_widget hooked_widget()
#endif
/**
initializes all global stuff in the widget class. might LEAVE.
*/
static void InitializeL();
/**
cleans up all global stuff in the widget class
*/
static void Free();
/**
prepares the widget for deletion. removes the widget, calls OnDeleted on the widget and inserts it in the deleted_widgets list.
*/
void Delete();
// OpInputContext
// currently only handles pan actions, though scrolling via mousewheel probably ought to go through here as well
/**
called on input action. currently only handles pan actions.
*/
virtual BOOL OnInputAction(OpInputAction* /*action*/);
/**
@param return the writing system of the widget
*/
WritingSystem::Script GetScript() { return m_script; }
void GetBorders(short& left, short& top, short& right, short& bottom) const;
void SetMargins(short margin_left, short margin_top, short margin_right, short margin_bottom);
void GetMargins(short& left, short& top, short& right, short& bottom) const;
#ifdef SKIN_SUPPORT
/**
documented in OpWidgetPainterManager
*/
BOOL UseMargins(short margin_left, short margin_top, short margin_right, short margin_bottom,
UINT8& left, UINT8& top, UINT8& right, UINT8& bottom);
/**
should return TRUE for widgets that want to draw their focus
rect in the margins - will cause margins to be included when
invalidating and clipping
*/
virtual BOOL FocusRectInMargins() { return FALSE; }
/**
sets the skin manager for all skins, and all children's skins
@param skin_manager the new skin manager
*/
virtual void SetSkinManager(OpSkinManager* skin_manager);
/**
@param return the current skin manager
*/
OpSkinManager* GetSkinManager() {return m_skin_manager;}
/**
sets whether the widget should be drawn using skin or not. if packed.is_skinned is true and the widget doesn't need
to be drawn with the CssWidgetPainter, the border is drawn using its skin.
@param skinned tells the widget to draw its borders using its skin if possible
*/
void SetSkinned(BOOL skinned) { packed.is_skinned = skinned != FALSE; }
/**
@return TRUE if the widget will draw its background and borders using its skin if possible
*/
BOOL GetSkinned() { return packed.is_skinned; }
/**
sets whether the skin in this widget should be considered a background for child widgets only. If set, the skin
will only be drawn if/when skinned children are drawn over it.
*/
void SetSkinIsBackground(BOOL is_background) { packed.skin_is_background = is_background != FALSE; }
/** Is the widget in minisize. A UI widget in minisize should take up less space than normally. */
BOOL IsMiniSize() const { return packed.is_mini; }
virtual void SetMiniSize(BOOL is_mini);
/** Is the widget floating. A floating widget is a widget that should not be affected by normal UI-layout. */
BOOL IsFloating() const { return packed.is_floating; }
virtual void SetFloating(BOOL is_floating) { packed.is_floating = is_floating; }
#ifdef WIDGET_IS_HIDDEN_ATTRIB
BOOL IsHidden() const { return packed.is_hidden; }
virtual void SetHidden(BOOL is_hidden) { packed.is_hidden = is_hidden; }
#endif // WIDGET_IS_HIDDEN_ATTRIB
/** Draw the background and border skins for this widget. contents need still be drawn via OnPaint. */
void EnsureSkin(const OpRect& rect, BOOL clip = TRUE, BOOL force = FALSE);
/** Draw the overlay skins for this widget. Overlay is drawn after OnPaint. */
void EnsureSkinOverlay(const OpRect& rect);
/**
@return the border skin of the widget
*/
OpWidgetImage* GetBorderSkin() {return &m_border_skin;}
/**
@return the foreground skin of the widget
*/
OpWidgetImage* GetForegroundSkin() {return &m_foreground_skin;}
#endif
#ifdef QUICK
/** Restrict the foreground skin to 16x16 or the size specified in skin element "Window Document Icon" */
virtual void SetRestrictImageSize(BOOL b) { m_foreground_skin.SetRestrictImageSize(b); }
/** @return TRUE if the foreground skin is restricted in size */
BOOL GetRestrictImageSize() { return m_foreground_skin.GetRestrictImageSize(); }
#endif
virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
/** Adds a childwidget (f.eks scrollbars in listbox).
Childwidgets will automatically be deleted when this widget is deleted.
*/
virtual void AddChild(OpWidget* child, BOOL is_internal_child = FALSE, BOOL first = FALSE);
/** Gives ability to add child before or after the given reference child widget
* @param child widget which is to be inserted.
* @param ref_widget is a reference widget and based on this one child widget is
* inserted before or after it.
* If ref_widget is NULL then this widget will be inserted at the end of the list
* @param after_ref_widget flag if TRUE then widget will be inserted after given
* 'ref_widget' otherwise before.
* @param is_internal_child flag if TRUE then widget will be inserted as a internal
* child.
* @param first flag if TRUE, widget will be added first in the list
* @note Out of 'first' and 'ref_widget' arguments 'first' will be given priority.
*/
virtual void InsertChild(OpWidget* child,
OpWidget* ref_widget = NULL,
BOOL after_ref_widget = TRUE,
BOOL is_internal_child = FALSE,
BOOL first = FALSE);
/**
removes the widget. generates OpRemovoing and OnRemoved on the widget, and removes all children.
*/
void Remove();
enum Z {
Z_TOP, ///< Visually on top over other widgets
Z_BOTTOM ///< Visually at bottom behind other widgets.
};
/** Set the Z order of this widget relatively to its siblings */
void SetZ(Z z);
/**
@return the parent widget
*/
OpWidget* GetParent() const { return parent; }
/**
@return a pointer to the widget's OpWidgetInfo instance
*/
OpWidgetInfo* GetInfo();
/**
@return TRUE if the widget is enabled
*/
BOOL IsEnabled() const { return packed.is_enabled; }
/**
@return TRUE if the widget is visible
*/
BOOL IsVisible() const { return packed.is_visible; }
/**
@return TRUE if the widget and all its ancestors are visible
*/
BOOL IsAllVisible() const;
/**
@return TRUE if the widget is an internal child (i.e. the button or edit field of a file upload widget)
*/
BOOL IsInternalChild() const { return packed.is_internal_child; }
/**
@return if TRUE, the widget will not get focus when cycling focus using TAB
*/
BOOL IsTabStop() const { return packed.is_tabstop; }
/** Set if the image should not care about mouse events. */
BOOL IgnoresMouse() const { return packed.ignore_mouse; }
/** @param ignore Set if the image should not care about mouse events. */
void SetIgnoresMouse(BOOL ignore) {packed.ignore_mouse = ignore;}
/**
* @param forward - TRUE if we should look forward. FALSE if we should look backwards.
* @return TRUE if the current focused subwidget is the last focusable.
*/
BOOL IsAtLastInternalTabStop(BOOL forward) const;
/**
* @param forward - TRUE if we should look forward. FALSE if we should look backwards.
* @return NULL if none was found.
*/
OpWidget* GetNextInternalTabStop(BOOL forward) const;
/**
* Used to find the first/last internal widget to focus when moving
* through widgets.
*
* @param[in] front If TRUE, then return the first
* internal widget, if FALSE, the last internal widget.
*
* @returns The first/last internal widget that can be focused or NULL if none found, not even this.
*/
OpWidget* GetFocusableInternalEdge(BOOL front) const;
BOOL CanHaveFocusInPopup() const { return packed.can_have_focus_in_popup; }
void SetCanHaveFocusInPopup(BOOL new_val);
/** When true, No border should be drawn. It is drawn by the layoutengine. */
BOOL HasCssBorder() const { return packed.has_css_border; }
/** When true, No background should be drawn. It is drawn by the layoutengine. */
BOOL HasCssBackgroundImage() const { return packed.has_css_backgroundimage; }
/** When true, draw focus rect if it has focus. */
BOOL HasFocusRect() const { return packed.has_focus_rect; }
/** When true 'box-sizing' is 'border-box' for this widget. */
BOOL IsBorderBox() const { return packed.border_box; }
/**
* Gets the size of this OpWidget, in border-box.
*
* The border-box of an element is the actual footprint the element leaves
* on the page, i.e. the content-box plus padding plus borders.
*
* Note that this returns the border-box dimensions, regardless of the
* return value of IsBorderBox().
*
* @param[out] width The border-box width.
* @param[out] height The border-box height.
*/
void GetBorderBox(INT32& width, INT32& height);
/**
sets the widget's form object
@param form the new form object
*/
void SetFormObject(FormObject* form) {form_object = form;}
/**
@return TRUE if the widget or one of its ancestors has a form object
*/
BOOL IsForm();
/**
sets the padding of the widget
@param padding_left the widget's left paddding
@param padding_top the widget's top paddding
@param padding_right the widget's right paddding
@param padding_bottom the widget's bottom paddding
*/
void SetPadding(short padding_left, short padding_top, short padding_right, short padding_bottom);
/** Add the padding values to the rect */
void AddPadding(OpRect& rect);
// Get the padding values (inside spacing) values of the widget
virtual void GetPadding(INT32* left, INT32* top, INT32* right, INT32* bottom);
/**
@return the widget's left padding
*/
short GetPaddingLeft() {return m_padding_left;}
/**
@return the widget's top padding
*/
short GetPaddingTop() {return m_padding_top;}
/**
@return the widget's right padding
*/
short GetPaddingRight() {return m_padding_right;}
/**
@return the widget's bottom padding
*/
short GetPaddingBottom() {return m_padding_bottom;}
/** If several properties are going to be set, this can be used to minimize updating of the widgets internals, but it is not required.
(F.ex: not reformatting a OpMultiEdit for each change, like SetFontInfo, SetRect etc..) */
virtual void BeginChangeProperties() {}
/** If several properties are going to be set, this can be used to minimize updating of the widgets internals, but it is not required.
(F.ex: not reformatting a OpMultiEdit for each change, like SetFontInfo, SetRect etc..) */
virtual void EndChangeProperties() {}
/**
sets the widget's listener. will call SetListener with same arguments for all non-internal children.
@param listener the listener
@param force if TRUE, listener replaces the widget's previous listener if present
*/
virtual void SetListener(OpWidgetListener* listener, BOOL force = TRUE);
/**
@return the widget's listener
*/
OpWidgetListener* GetListener() {return listener;}
/**
sets the widget's pointer to its visual device to vis_dev. the same is done for all children.
@param vis_dev
*/
void SetVisualDevice(VisualDevice* vis_dev);
/**
tells the widget whether it has CSS borders or not. a widget with CSS borders should always have its borders
drawn by core. this also has some implications on the size of the widgets - widgets without CSS border get a 2px
sunken border on all sides.
*/
void SetHasCssBorder(BOOL has_css_border);
/**
tells the widget whether it has CSS background or not. a widget with CSS background should always have its
background drawn by core.
*/
void SetHasCssBackground(BOOL has_css_background);
/**
determines if a focus rect should be drawn around the widget
@param has_focus_rect TRUE if a focus rect should be drawn around the rectangle
*/
void SetHasFocusRect(BOOL has_focus_rect);
/** Starts a timer which will call OnTimer.
If the timer is already running, it will be stopped before it starts again. */
void StartTimer(UINT32 millisec);
/** Stops the timer if it is running. */
void StopTimer();
/**
returns the timer delay. if non-zero, the timer is running and will be restarted with the same delay again
when it times out.
*/
UINT32 GetTimerDelay() const;
/** @return TRUE if the timer is running */
BOOL IsTimerRunning() const;
/**
changes the dimensions and position of the widget to the ones denoted by rect.
@param rect the new dimensions of the widget
@param invalidate if TRUE, the entire widget (old rect and new rect) is invalidated
@param resize_children if TRUE, children will be resized as well (applies only for QUICK)
*/
void SetRect(const OpRect &rect, BOOL invalidate = TRUE, BOOL resize_children = TRUE);
/**
changes the dimentions of the widget to the ones denoted by w, h.
will generate OnResized to any listener if the widget was resized.
will generate OnMove to any listener if the widget was moved.
@param w the new width of the widget
@param h the new height of the widget
\note calls SetRect with default values for invalidate and resize_children
*/
void SetSize(INT32 w, INT32 h);
/**
moves the widget to the position denoted by pos. will generate OnMove to any listener if the widget was moved.
@param pos the new position of the widget
*/
void SetPosInDocument(const AffinePos& pos);
/**
@return the widget's container
*/
WidgetContainer* GetWidgetContainer() {return m_widget_container;}
/**
sets the widget's container
@param container the container
*/
void SetWidgetContainer(WidgetContainer* container);
/** Handle pending paint operations */
void Sync();
/**
Reports a OOM situation to the core.
In functions which returns a OP_STATUS this is not neccesary.
Any OOM in the constructor should set the init_status member.
*/
void ReportOOM();
/** Get mouse position relative to this widget.
You should always use the point parameter sent during mouse events instead.
This should be used only if there is no other solution. */
virtual OpPoint GetMousePos();
/** Returns the position in the document, in document coordinates relative to the top of the document. */
AffinePos GetPosInDocument();
/** Returns the position of the widget, in document coordinates relative to the origo of the root document. */
AffinePos GetPosInRootDocument();
/** Returns the rect */
OpRect GetRect(BOOL relative_to_root = FALSE);
/** Returns the rect in document coordinates (if applicable) */
OpRect GetDocumentRect(BOOL relative_to_root = FALSE);
/** Returns the rect translated to 0, 0. if include_margin is TRUE any margins will be added to the rect. */
OpRect GetBounds(BOOL include_margin = FALSE);
/** Add the nonclickable margins to rect (areas that should not be hit by the mouse). */
OpRect AddNonclickableMargins(const OpRect& rect);
/** Returns the clickable rect relative to the parent widget (Same as GetRect but excluding areas that should not be hit by the mouse). */
OpRect GetClickableRect() { return AddNonclickableMargins(GetRect()); }
/** Returns the clickable rect relative to this widget. */
OpRect GetClickableBounds() { return AddNonclickableMargins(GetBounds()); }
/** Returns the rect relative to screen */
OpRect GetScreenRect();
/**
@return the color of the widget
*/
WIDGET_COLOR GetColor() const { return m_color; }
/**
@param color the new color of the widget
*/
void SetColor(WIDGET_COLOR color) { m_color = color; }
/**
@return the widget's visual device
*/
VisualDevice* GetVisualDevice() const { return vis_dev; }
/**
@return TRUE if the widget or one of its ancestors is part of a form
*/
BOOL IsInWebForm() const;
/**
returns a pointer to the widget's form object. if it hasn't got one and iterate_parents is TRUE,
the call will bubble upwards through its ancestors.
@param iterate_parents if TRUE, bubble upwards
@return the form object
*/
FormObject* GetFormObject(BOOL iterate_parents = FALSE) const;
/**
@return the width of the widget
*/
INT32 GetWidth() {return rect.width;}
/**
@return the height of the widget
*/
INT32 GetHeight() {return rect.height;}
/** Sets the cliprect relative to this widget. */
void SetClipRect(const OpRect &rect);
/** Removes the cliprect */
void RemoveClipRect();
/** Get the cliprect relative to this widget. */
OpRect GetClipRect();
/** Returns true if the widget is someway visible and if it is, it sets rect
to the cliprect of the parent layoutobject (f.eks. a div).
Note, that it doesn't check the visibility of the documentview or window */
BOOL GetIntersectingCliprect(OpRect &rect);
/**
Get the visible child widget that intersect point, or this if none where found.
@param point The point relative to this widget.
@param include_internal_children If TRUE, widgets marked as internal-child can also be returned.
@param include_ignored_mouse If TRUE, widgets that's marked SetIgnoresMouse(TRUE) can also be returned.
*/
OpWidget* GetWidget(OpPoint point, BOOL include_internal_children = FALSE, BOOL include_ignored_mouse = FALSE);
OpWidget* Suc() { return (OpWidget*) Link::Suc(); }
OpWidget* Pred() { return (OpWidget*) Link::Pred(); }
/** @return the first child */
OpWidget* GetFirstChild() {return (OpWidget*) childs.First();}
/** @return the last child */
OpWidget* GetLastChild() {return (OpWidget*) childs.Last();}
/** @return next sibling */
OpWidget* GetNextSibling() {return Suc();}
/** @return previous sibling */
OpWidget* GetPreviousSibling() {return Pred();}
/**
deletes any current input actions and keeps action. probably used by quick.
@param action the new input action
*/
virtual void SetAction(OpInputAction* action);
/**
@return the currently stored input action
*/
virtual OpInputAction* GetAction() {return m_action;}
/**
tries to obtain the widget's parent window, through widget container if present, otherwize through document manager
@return the parent window
*/
OpWindow* GetParentOpWindow();
/** Invalidates rect, relative to the widget. If intersect is TRUE, the rectangle will be clipped to not
invalidate a bigger rect than this widget.
If timed is TRUE, the update might be delayed. See VisualDevice::Update for more info about that. */
void Invalidate(const OpRect &rect, BOOL intersect = TRUE, BOOL force = FALSE, BOOL timed = FALSE);
/**
invalidates the entire contents of the widget
*/
void InvalidateAll();
/**
sets the enabled-status of the widget
@param enabled if TRUE, the widget is enabled
*/
virtual void SetEnabled(BOOL enabled);
/**
sets the read-only status of the widget
@param readonly if TRUE, the widget is put in read-only mode
*/
virtual void SetReadOnly(BOOL readonly) {}
/**
gets the read-only status of the widget
*/
virtual BOOL IsReadOnly() { return FALSE; }
/**
sets the visibility of the widget
@param visible if TRUE, the widget is set to visible
*/
void SetVisibility(BOOL visible);
/**
sets if this widget should be focused when tabbing (otherwise it will be skipped).
*/
void SetTabStop(BOOL is_tabstop) {packed.is_tabstop = is_tabstop;};
/**
sets if this widget should be treated like a FormObject even though it doesn't have one.
F.ex the <button> element has no FormObject but should still be treated like one.
*/
void SetSpecialForm(BOOL val) { packed.is_special_form = val; }
/** sets if this widget wants the OnMove callback. If TRUE, it will recurse to set its
parents to TRUE too. */
void SetOnMoveWanted(BOOL onmove_wanted);
/** Set ellipsis. Single line widgets will respect this value, but not multiline widgets (might change). */
virtual void SetEllipsis(ELLIPSIS_POSITION ellipsis) { packed.ellipsis = (unsigned int)ellipsis; }
virtual ELLIPSIS_POSITION GetEllipsis() { return (ELLIPSIS_POSITION)packed.ellipsis; }
// DEPRICATED!!!
BOOL HasCenterEllipsis() { return GetEllipsis() == ELLIPSIS_CENTER; }
/** sets if this widget is a dead widget. A dead widget look normal but doesn't invoke on input. */
void SetDead(BOOL dead) {packed.is_dead = dead;}
BOOL IsDead() {
#ifdef QUICK
return packed.is_dead || IsCustomizing();
#else
return packed.is_dead;
#endif //QUICK
}
/**
@param relayout_needed if TRUE, relayout is needed
*/
void SetRelayoutNeeded(BOOL relayout_needed) {packed.relayout_needed = relayout_needed;};
/**
@return TRUE if relayout is needed
*/
BOOL IsRelayoutNeeded() const {return packed.relayout_needed;}
/**
@param layout_needed if TRUE, layout is needed
*/
void SetLayoutNeeded(BOOL layout_needed) {packed.layout_needed = layout_needed;};
/**
@return TRUE if layout is needed
*/
BOOL IsLayoutNeeded() const {return packed.layout_needed;}
/** Sets that this widget is invalidated and are waiting for a paint. Note, that the widget might still
get a paint even though this hasn't been set */
void SetPaintingPending();
/** Return TRUE if this widget are waiting for a OnPaint. Note, that it might get OnPaint even if this isn't TRUE,
and even if it's TRUE, it might never get a OnPaint (f.ex if it is hidden) */
BOOL IsPaintingPending() const {return packed.is_painting_pending;}
/** Update this widgets visual states with current properties. Default implementation is empty and most widget doesn't
do anything since they update themselfs when properties change. */
virtual void Update() {}
/**
returns the foreground color of the widget
@param def_color fallback, in case the widget couldn't get the foreground color from any skin or ancestor
@param state really a SkinState bitmask, used to obtain the foreground color from a skin
@return the foreground color, or def_color if no foreground color was obtained
*/
UINT32 GetForegroundColor(UINT32 def_color, INT32 state);
/**
returns the background color of the widget
@param def_color fallback, in case the widget is set to use its default background color
@return the background color, or def_color if default background color is to be used
*/
UINT32 GetBackgroundColor(UINT32 def_color);
/**
sets the foreground (i.e. text/check mark) color of the widget and its children.
color will only be changed on non-form widgets or if styling of forms is enabled in prefs.
@param color the color
\note format might be dependent on platform, but the macro RGB can be used
*/
void SetForegroundColor(UINT32 color);
/**
sets the background color of the widget and its children.
color will only be changed on non-form widgets or if styling of forms is enabled in prefs.
@param color the color
\note format might be dependent on platform, but the macro RGB can be used
*/
void SetBackgroundColor(UINT32 color);
/**
tells the widget and all its children to use its default foreground color
*/
void UnsetForegroundColor();
/**
tells the widget and all its children to use its default background color
*/
void UnsetBackgroundColor();
/**
sets the painter manager for the widget and all its children
@param painter_manager the painter manager
*/
void SetPainterManager(OpWidgetPainterManager* painter_manager);
/**
@return the widget's painter manager
*/
OpWidgetPainterManager* GetPainterManager() { return painter_manager; }
/**
changes the font information for the widget and its children. if anything changes, OnFontChanged is called.
will set custom_font to true, which will bail calls to UpdateSystemFont unles force_system_font is TRUE.
@param font_info a pointer to a font_info instance
@param size the new font size
@param italic TRUE if the font should be italic
@param weight the new weight of the font
@param justify the new justification mode of the widget
@param char_spacing_extra the new extra char spacing value
@return TRUE if the font changed on this widget or any of the child widgets.
*/
BOOL SetFontInfo(const OpFontInfo* font_info, INT32 size, BOOL italic, INT32 weight, JUSTIFY justify, int char_spacing_extra = 0);
BOOL SetFontInfo(const WIDGET_FONT_INFO& wfi);
/** Set justify for the textcontent.
If changed_by_user is TRUE, the justify value will be sticky (It won't change to something else unless changed_by_user is TRUE).
That should be used if user changes justify manually and we don't want it to be reset by css or something else. */
BOOL SetJustify(JUSTIFY justify, BOOL changed_by_user);
/**
updates the widget's font to the font for the message-box CSS system UI element. (see
documentation for GetUICSSFont in pi/ui.) will bail if SetFontInfo has been called for
the widget if force_system_font is not set.
@param force_system_font force update to system font even if the widget has a custom font
*/
void SetVerticalAlign(WIDGET_V_ALIGN align);
WIDGET_V_ALIGN GetVerticalAlign() { return (WIDGET_V_ALIGN) packed.v_align; }
void UpdateSystemFont(BOOL force_system_font = FALSE);
/**
sets the text transform mode for the widget
@param value the text-transform value. valid types documented in layout/cssprops.h
*/
void SetTextTransform(short value) { text_transform = value; }
/**
Set various CSS properties on the widget.
*/
void SetProps(const HTMLayoutProperties& props);
/** Set the current cursor. Should be called from OnSetCursor to have effect. */
void SetCursor(CursorType cursor);
/** Searches for txt.
@param txt The searchstring
@param len The length of the searchstring
@param forward Forward or backward search
@param match_case Match case or not
@param words Match whole word only
@param type Search from beginning, end or current caret position
@param select_match Select the found match, or do nothing when it's found.
@param scroll_to_selected_match if TRUE, scrolling to any selected match will be performed
@return TRUE if text was found.
*/
BOOL SearchText(const uni_char* txt, int len, BOOL forward, BOOL match_case,
BOOL words, SEARCH_TYPE type, BOOL select_match,
BOOL scroll_to_selected_match = TRUE)
{ return SearchText(txt, len, forward, match_case, words, type, select_match, scroll_to_selected_match, FALSE, TRUE); }
virtual BOOL SearchText(const uni_char* txt, int len, BOOL forward, BOOL match_case,
BOOL words, SEARCH_TYPE type, BOOL select_match,
BOOL scroll_to_selected_match, BOOL wrap, BOOL next) { return FALSE; }
/** If include_document is TRUE the document is eventual scrolled so that the caret will be visible */
virtual void ScrollIfNeeded(BOOL include_document = FALSE, BOOL smooth_scroll = FALSE) {}
/** should return true if the widget contains text, of which some is selected */
virtual BOOL HasSelectedText() { return FALSE; }
/** should deselect any selected text in the widget */
virtual void SelectNothing() {}
/** should select all text in the widget */
virtual void SelectAll() {}
/** Get current selection or 0->0->SELECTION_DIRECTION_DEFAULT if there is no selection */
virtual void GetSelection(INT32& start_ofs, INT32& stop_ofs, SELECTION_DIRECTION& direction, BOOL line_normalized = FALSE) { start_ofs = stop_ofs = 0; direction = SELECTION_DIRECTION_DEFAULT; }
/** Get current selection or 0->0 if there is no selection */
void GetSelection(INT32 &start_ofs, INT32 &stop_ofs, BOOL line_normalized = FALSE) { SELECTION_DIRECTION direction; GetSelection(start_ofs, stop_ofs, direction, line_normalized); }
/** Gets a list of rectangles a text selection consist of (if any) and a rectangle being a union of all rectangles in the list.
*
* @param list - a pointer to the list.
* @param union_rect - a union of all rectangles in the list.
* @param visible_only - If true only the visible selection's part will be taken into account.
*/
virtual OP_STATUS GetSelectionRects(OpVector<OpRect>* list, OpRect& union_rect, BOOL visible_only) { return OpStatus::OK; }
/** Checks if given x and y are over a text selection.
*
* @param x - the x coordinate to be checked (in widget coordinates).
* @param y - the y coordinate to be checked (in widget coordinates).
*
* @return TRUE if (x, y) point is over the selection. FALSE othewise.
*/
virtual BOOL IsWithinSelection(int x, int y) { return FALSE; }
/**
should select any text between start_ofs and stop_ofs
@param start_ofs the start offset
@param stop_ofs the stop offset
@param direction the direction of the selection
@param line_normalized flag controlling interpretation of line terminator.
*/
virtual void SetSelection(INT32 start_ofs, INT32 stop_ofs, SELECTION_DIRECTION direction, BOOL line_normalized = FALSE) {}
/**
should select any text between start_ofs and stop_ofs
@param start_ofs the start offset
@param stop_ofs the stop offset
*/
void SetSelection(INT32 start_ofs, INT32 stop_ofs, BOOL line_normalized = FALSE) { SetSelection(start_ofs, stop_ofs, SELECTION_DIRECTION_DEFAULT, line_normalized); }
/**
should select any text between start_ofs and stop_ofs
@param start_ofs the start offset
@param stop_ofs the stop offset
*/
virtual void SelectSearchHit(INT32 start_ofs, INT32 stop_ofs, BOOL is_active_hit) { SetSelection(start_ofs, stop_ofs); }
virtual BOOL IsSearchHitSelected() { return FALSE; }
virtual BOOL IsActiveSearchHitSelected() { return FALSE; }
/**
should return the offset from the start of any (editable) text to the caret position
@return the caret offset
*/
virtual INT32 GetCaretOffset() { return 0; }
/**
should move the caret to the position designated by caret_ofs
@param caret_ofs the new caret position
*/
virtual void SetCaretOffset(INT32 caret_ofs) {}
/** Return TRUE if it has scrollbar and it is scrollable in any direction. */
virtual BOOL IsScrollable(BOOL vertical) { return FALSE; }
#ifdef WIDGETS_CLONE_SUPPORT
/** Clones most properties from source to this widget. */
OP_STATUS CloneProperties(OpWidget *source, INT32 font_size = 0);
/** Create new widget cloned from this one. Must specify a parent widget for the new widget.
Can specify a different font-size, or 0 if the same fontsize should be used. */
virtual OP_STATUS CreateClone(OpWidget **obj, OpWidget *parent, INT32 font_size, BOOL expanded) { return OpStatus::ERR_NOT_SUPPORTED; }
/** Returns TRUE of this widget is cloneable */
virtual BOOL IsCloneable() { return FALSE; }
#endif
/**
sets the text direction of the widget
@param is_rtl if TRUE, the widget is set to have RTL text direction
*/
void SetRTL(BOOL is_rtl);
/**
returns the text direction of the widget
@return TRUE if the text direction of the widget is RTL
*/
BOOL GetRTL() const { return packed.is_rtl; }
/** Returns TRUE if UI elements (like scrollbars) should be placed to the left,
takes user preferences and Right-To-Left content into account */
BOOL LeftHandedUI();
/** Read the EnableStylingOnForms prefs and see if styling is allowed for this widget. */
BOOL GetAllowStyling();
/** Change the resizability of the OpWidget.
Note that not all OpWidget subclasses are resizable at all. It is up
to each subclass to respond to this setting.
Calling this function will trigger OnResizabilityChanged().
@param resizability The new resizability of the OpWidget.
*/
void SetResizability(WIDGET_RESIZABILITY resizability);
/** @return the resizability of this OpWidget. */
WIDGET_RESIZABILITY GetResizability() const { return static_cast<WIDGET_RESIZABILITY>(packed.resizability); }
/** @return TRUE if the OpWidget is resizable along at least one axis. */
BOOL IsResizable() const { return (packed.resizability & WIDGET_RESIZABILITY_BOTH) != 0; }
/** @return TRUE if the OpWidget is at least resizable along the horizontal axis. */
BOOL IsHorizontallyResizable() const { return (packed.resizability & WIDGET_RESIZABILITY_HORIZONTAL) != 0; }
/** @return TRUE if the OpWidget is at least resizable along the vertical axis. */
BOOL IsVerticallyResizable() const { return (packed.resizability & WIDGET_RESIZABILITY_VERTICAL) != 0; }
/**
Is called to see which size the widget wants to have. cols and rows is the (by html/css) specified
width/height in characters or items (for listbox). They are 0 if they are not specified.
*/
virtual void GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows) {}
/**
Is called to see which size the widget needs to have.
*/
virtual void GetMinimumSize(INT32* minw, INT32* minh) {}
#ifndef QUICK
virtual void GetRequiredSize(INT32& width, INT32& height) {GetPreferedSize(&width, &height, 0, 0);}
#endif
#ifdef WIDGETS_IME_SUPPORT
/**
triggered from FramesDocument::HandleEventFinished, to allow
widgets that suppressed IME spawning on focus to spawn from
here instead.
*/
void IMEHandleFocusEvent(BOOL focused) { if (!m_suppress_ime) return; m_suppress_ime = FALSE; IMEHandleFocusEventInt(focused, m_suppressed_ime_reason); }
/**
called from IMEHandleFocusEvent if IME spawning was suppressed.
@param reason reason why IME was focused
@return FALSE if an attempt to spawn an IME failed, TRUE
otherwise
*/
virtual BOOL IMEHandleFocusEventInt(BOOL focused, FOCUS_REASON reason) { return TRUE; }
#endif // WIDGETS_IME_SUPPORT
#ifdef SKIN_SUPPORT
// Implementing OpWidgetImageListener interface
/**
implements the OpWidgetImageListener interface. called when an image has chaged. invalidates the widget.
if animated skins are allowed, starts any animation of the image.
*/
virtual void OnImageChanged(OpWidgetImage* widget_image);
#ifdef ANIMATED_SKIN_SUPPORT
virtual void OnAnimatedImageChanged(OpWidgetImage* widget_image);
virtual BOOL IsAnimationVisible();
#endif
#endif
// Hooks
/**
called when the window is activated
*/
virtual void OnWindowActivated(BOOL activate) {}
/**
called when the window is moved
*/
virtual void OnWindowMoved() {}
/** Return TRUE if scrolling was performed, FALSE otherwize. */
virtual BOOL OnScrollAction(INT32 delta, BOOL vertical, BOOL smooth = TRUE) { return FALSE; }
#ifndef MOUSELESS
/**
called when the widget revceives a mouse move
*/
virtual void OnMouseMove(const OpPoint &point) {}
/**
called when the widget revceives a mouse leave
*/
virtual void OnMouseLeave() {}
/**
called when the widget revceives a mouse down
*/
virtual void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks) {}
/**
deprecated. Change your implementation to the new OnMouseUp that takes UINT8 nclicks as third parameter!
*/
virtual struct DEPRECATED_DUMMY_RET *OnMouseUp(const OpPoint &point, MouseButton button) { return NULL; }
/**
called when the widget revceives a mouse up
*/
virtual void OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks) {}
/** Return TRUE if you use this hook, FALSE to send it to the parent or document. */
virtual BOOL OnMouseWheel(INT32 delta,BOOL vertical) { return FALSE; }
#endif // !MOUSELESS
/**
* called when a context menu is requested for the widget. should return TRUE if a context menu is shown.
* otherwize, the call will bubble upwards.
* @param menu_point The position (relative to the widget) where the popup should appear
* @param avoid_rect The area that should not be covered by the popup. NULL if not needed.
* @param keyboard_invoked TRUE if context menu is invoked by keypress (as opposed to mouse).
*/
virtual BOOL OnContextMenu(const OpPoint &menu_point, const OpRect *avoid_rect, BOOL keyboard_invoked) { return FALSE; }
/**
called before the widget is painted
*/
virtual void OnBeforePaint() {}
/**
should paint the widget
*/
virtual void OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect) {}
/**
called after all the widget's children are painted
*/
virtual void OnPaintAfterChildren(OpWidgetPainter* widget_painter, const OpRect &paint_rect) {}
/**
called whenever the widget's timer times out
*/
virtual void OnTimer() {}
/**
called when the widget is added
*/
virtual void OnAdded() {}
/**
called when the widget is removed, before removing it
*/
virtual void OnRemoving() {}
/**
called when the widget is removed, after removing it
*/
virtual void OnRemoved() {}
/**
called when the widget is deleted
*/
virtual void OnDeleted() {}
/**
called when the widget's justification mode is changed
*/
virtual void OnJustifyChanged() {}
/**
called when the widget's font has changed
*/
virtual void OnFontChanged() {}
/**
called when the widget's text direction has changed
*/
virtual void OnDirectionChanged() {}
/** Get widget opacity, from 0 (fully transparent) to 255 (fully solid) */
virtual UINT8 GetOpacity();
#ifndef MOUSELESS
/** Called when moving the mouse into the widget. Default sets the defaultcursor. */
virtual void OnSetCursor(const OpPoint &point);
#endif // !MOUSELESS
virtual void OnSelectAll() {}
/**
Called when the widgets size changes. new_w and new_h contains the new size
and can be changed to force/limit the widgets size.
*/
virtual void OnResize(INT32* new_w, INT32* new_h) {}
#ifdef DRAG_SUPPORT
virtual void OnDragLeave(OpDragObject* drag_object)
{
if (listener)
listener->OnDragLeave(this, drag_object);
}
virtual void OnDragCancel(OpDragObject* drag_object)
{
if (listener)
listener->OnDragCancel(this, drag_object);
}
virtual void OnDragMove(OpDragObject* drag_object, const OpPoint& point);
virtual void OnDragStart(const OpPoint& point);
virtual void OnDragDrop(OpDragObject* drag_object, const OpPoint& point)
{
if (listener)
listener->OnDragDrop(this, drag_object, 0, point.x, point.y);
}
virtual void GenerateOnDragStart(const OpPoint& point);
virtual void GenerateOnDragMove(OpDragObject* drag_object, const OpPoint& point);
virtual void GenerateOnDragDrop(OpDragObject* drag_object, const OpPoint& point);
virtual void GenerateOnDragLeave(OpDragObject* drag_object);
virtual void GenerateOnDragCancel(OpDragObject* drag_object);
#endif // DRAG_SUPPORT
virtual BOOL IsSelecting() { return FALSE; }
virtual void OnResizeRequest(INT32 w, INT32 h)
{
if (listener)
listener->OnResizeRequest(this, w, h);
}
/**
Called when widget will be shown / hidden due to SetVisibility being called on this widget or parent etc
*/
virtual void OnShow(BOOL show) {}
/**
Called when widget has been moved relative to root somehow. (that means it might not have been moved relative
to parent, but OnMove is still called.)
NOTE: it is only called for widgets that have asked for it with SetOnMoveWanted(TRUE)
*/
virtual void OnMove() {}
/** Called when a relayout occurs.. default implementation is to let listener know about it */
virtual void OnRelayout() {if (listener) listener->OnRelayout(this);}
/** Called when layout occurs.. widget should layout its contents.. default implementation is to ask listener to do it */
virtual void OnLayout() {if (listener) listener->OnLayout(this);}
/** Called when layout is done, and post layout occurs.. widget should do post layout tasks.. default implementation is to ask listener to do it */
virtual void OnLayoutAfterChildren() {if (listener) listener->OnLayoutAfterChildren(this);}
/** Called when widget becomes resizable, or when the widget is no longer resizable. */
virtual void OnResizabilityChanged() {}
virtual void SetLocked(BOOL locked) { packed.locked = locked; }
virtual BOOL IsLocked() { return packed.locked; }
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
public:
void AccessibilitySkipsMe(BOOL skip_me = TRUE) {packed.accessibility_skip = skip_me;}
void AccessibilityPrunesMe(AccessibilityPrune prune_me = ACCESSIBILITY_PRUNE) {packed.accessibility_prune = prune_me;}
BOOL AccessibilitySkips() {return packed.accessibility_skip;}
BOOL AccessibilityPrunes() const {return (packed.accessibility_prune == ACCESSIBILITY_PRUNE || packed.accessibility_prune == ACCESSIBILITY_PRUNE_WHEN_INVISIBLE && !IsVisible());}
void SetAccessibilityLabel(AccessibleOpWidgetLabel* label) { m_acc_label = label; }
void DisableAccessibleItem();
#ifdef NAMED_WIDGET
void FindLabelAssociations();
#endif
void SetAccessibleParent (OpAccessibleItem* parent) {m_accessible_parent = parent; }
// accessibility methods
virtual BOOL AccessibilityIsReady() const;
virtual OP_STATUS AccessibilityClicked();
virtual OP_STATUS AccessibilitySetValue(int value);
virtual OP_STATUS AccessibilitySetText(const uni_char* text);
virtual BOOL AccessibilityChangeSelection(Accessibility::SelectionSet flags, OpAccessibleItem* child);
virtual BOOL AccessibilitySetFocus();
virtual OP_STATUS AccessibilityGetAbsolutePosition(OpRect &rect);
virtual OP_STATUS AccessibilityGetValue(int &value);
virtual OP_STATUS AccessibilityGetText(OpString& str);
virtual OP_STATUS AccessibilityGetDescription(OpString& str);
virtual OP_STATUS AccessibilityGetURL(OpString& str);
virtual OP_STATUS AccessibilityGetKeyboardShortcut(ShiftKeyState* shifts, uni_char* kbdShortcut);
virtual Accessibility::ElementKind AccessibilityGetRole() const {return Accessibility::kElementKindUnknown;}
virtual Accessibility::State AccessibilityGetState();
virtual OpAccessibleItem* GetAccessibleLabelForControl();
virtual int GetAccessibleChildrenCount();
virtual OpAccessibleItem* GetAccessibleParent();
virtual OpAccessibleItem* GetAccessibleChild(int);
virtual int GetAccessibleChildIndex(OpAccessibleItem* child);
virtual OpAccessibleItem* GetAccessibleChildOrSelfAt(int x, int y);
virtual OpAccessibleItem* GetNextAccessibleSibling();
virtual OpAccessibleItem* GetPreviousAccessibleSibling();
virtual OpAccessibleItem* GetAccessibleFocusedChildOrSelf();
virtual OpAccessibleItem* GetLeftAccessibleObject();
virtual OpAccessibleItem* GetRightAccessibleObject();
virtual OpAccessibleItem* GetDownAccessibleObject();
virtual OpAccessibleItem* GetUpAccessibleObject();
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
#ifdef WIDGETS_HEURISTIC_LANG_DETECTION
/** If multilingual is true heuristic language detection will be run on the widget text(if any) */
BOOL IsMultilingual() const { return packed.multilingual; }
void SetMultilingual(BOOL val) { packed.multilingual = val; }
#endif // WIDGETS_HEURISTIC_LANG_DETECTION
#ifdef USE_OP_CLIPBOARD
// ClipboardListener API
void OnPaste(OpClipboard* clipboard) {}
void OnCopy(OpClipboard* clipboard) {}
void OnCut(OpClipboard* clipboard) {}
#endif // USE_OP_CLIPBOARD
/** By default, widget is not hoverable when disabled. Set this to true, to override this behaviour */
BOOL IsAlwaysHoverable() const { return packed.is_always_hoverable; }
void SetAlwaysHoverable(BOOL val);
protected:
INT32 m_id; ///< Identification for widgets used in UI
AffinePos document_ctm; ///< Position in document (if any)
OpRect rect;
short text_transform;
short text_indent;
OpWidgetPainterManager* painter_manager;
OpWidgetListener* listener;
WIDGET_COLOR m_color;
VisualDevice* vis_dev;
OpWindow* opwindow;
WritingSystem::Script m_script;
short m_overflow_wrap;
short m_border_left, m_border_top, m_border_right, m_border_bottom;
short m_margin_left, m_margin_top, m_margin_right, m_margin_bottom;
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
AccessibleOpWidgetLabel* m_acc_label;
OpAccessibleItem* m_accessible_parent;
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
/** triggers OnScaleChanged if needed */
void CheckScale();
/** called from CheckScale (mainly triggered from GenerteOnPaint) if scale of vis_dev has changed */
virtual void OnScaleChanged() { }
/** vis_dev scale - should be used as comparison to trigger
OnScaleChanged only, may not always correspond to actual scale
of visual device */
int m_vd_scale;
#ifdef WIDGETS_IME_SUPPORT
BOOL m_suppress_ime;
BOOL m_suppress_ime_mouse_down; // only suppresses ime due to mouse down
FOCUS_REASON m_suppressed_ime_reason; ///< Focus reason used when suppressing IME. Only valid if m_suppress_ime is TRUE.
# ifdef SELFTEST
public:
BOOL IMESuppressed() const { return m_suppress_ime; }
# endif // SELFTEST
#endif // WIDGETS_IME_SUPPORT
private:
struct {
unsigned int is_internal_child:1; ///< Used on f.ex. scrollbars which listener should never be redirected recursive from SetListener.
unsigned int is_enabled:1;
unsigned int is_visible:1;
unsigned int is_tabstop:1;
unsigned int has_css_border:1;
unsigned int has_css_backgroundimage:1;
unsigned int has_focus_rect:1; // only draw focus rect if keyboard navigation is being used
unsigned int is_special_form:1; ///< It might belong to the document even though it has no FormObject.
unsigned int wants_onmove:1;
unsigned int ellipsis:2; ///< For widgets that draw text that must be clipped. Must have enough bits to hold ELLIPSIS_POSITION.
unsigned int custom_font:1;
unsigned int justify_changed_by_user:1;
unsigned int relayout_needed:1;
unsigned int layout_needed:1;
unsigned int is_painting_pending:1;
unsigned int is_dead:1;
unsigned int is_added:1;
unsigned int is_rtl:1;
unsigned int ignore_mouse:1;
unsigned int can_have_focus_in_popup:1;
unsigned int is_mini:1; ///< Set for a widget to try and show itself with it's .mini state (i.e. smaller)
unsigned int v_align:2; ///< Must have enough bits to hold WIDGET_V_ALIGN
#ifdef WIDGET_IS_HIDDEN_ATTRIB
unsigned int is_hidden:1; ///< Set for widget that should be included in hierarchy but not used in the layout
#endif // WIDGET_IS_HIDDEN_ATTRIB
unsigned int is_floating:1; ///< A floating widget is a widget that should not be affected by normal UI-layout
unsigned int has_received_user_input:1;
#ifdef NAMED_WIDGET
unsigned int added_to_name_collection:1;
#endif // NAMED_WIDGET
unsigned int locked:1;
unsigned int multilingual:1;
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
unsigned int accessibility_skip:1;
unsigned int accessibility_prune:2; ///<Must have enough bits to hold AccessibilityPrune
unsigned int accessibility_is_ready:1;
unsigned int checked_for_label:1;
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
unsigned int is_always_hoverable:1; ///< Set when you want to override m_enabled for mouse events
#ifdef SKIN_SUPPORT
unsigned int is_skinned:1;
unsigned int skin_is_background:1; ///< Set when the skin set on this element should only be painted as a background for widgets on top of it
#endif // SKIN_SUPPORT
unsigned int resizability:3; ///< @see WIDGET_RESIZABILITY
unsigned int border_box:1; ///< TRUE of box-sizing is set to border-box for this OpWidget.
} packed;
OpInputAction* m_action;
WidgetContainer* m_widget_container;
FormObject* form_object;
OpTimer* m_timer;
UINT32 m_timer_delay;
short m_padding_left;
short m_padding_top;
short m_padding_right;
short m_padding_bottom;
#ifdef SKIN_SUPPORT
OpWidgetImage m_border_skin;
OpWidgetImage m_foreground_skin;
OpSkinManager* m_skin_manager;
#endif // SKIN_SUPPORT
#ifndef MOUSELESS
unsigned char m_button_mask;
#endif // !MOUSELESS
public:
Head childs; ///< the list of children, composite widgets such as the file upload consist of several widgets
OpWidget* parent; ///< the parent widget
WIDGET_FONT_INFO font_info; ///< the widget's font-info struct
/**
implements OpTimerListener::OnTimeOut - called when m_timer times out. calls UpdatePosition on any form object.
will restart timer with m_timer_delay. calls OnTimer.
*/
virtual void OnTimeOut(OpTimer* timer);
OP_STATUS init_status; ///< Should be set if the constructor fails (It is automatically OpStatus::OK).
/**
called when highlight rect changes. will translate the rect to view coords and call OnHighlightRectChanged on the view.
*/
void GenerateHighlightRectChanged(const OpRect &rect, BOOL report_caret = FALSE);
/// Functions that generates hooks for the apropriate childobjects in this widget
/**
sets the widget's visual device, window and widget container. sets its parent as parent input context.
executes GenerateOnAdded for all children. calls OnAdded.
generates OpWidget::OnAdded
@param vd the widget's visual device
@param container the widget's container
@param window the widget's window
*/
virtual void GenerateOnAdded(VisualDevice* vd, WidgetContainer* container, OpWindow* window);
/**
runs GenerateOnRemoved on all children. resets state a bit. calls OnRemoved.
*/
virtual void GenerateOnRemoved();
/**
runs GenerateOnDeleted for all children. stops timer and zero:s listener. calls OnDeleted.
*/
virtual void GenerateOnDeleted();
/**
runs GenerateOnRemoving for all children. calls OnRemoving.
*/
virtual void GenerateOnRemoving();
/**
will call OnMove and run GenerateOnMove on all children if widget says it wants OnMove events
*/
virtual void GenerateOnMove();
/**
will call OnWindowActivated and run GenerateOnWindowActivated for all children
*/
virtual void GenerateOnWindowActivated(BOOL activate);
/**
will call OnWindowMoved and run GenerateOnWindowMoved for all children
*/
virtual void GenerateOnWindowMoved();
/**
if the widget is not visible, nothing is done. if it is, is_painting_pending will be set to FALSE, call
OnBeforePaint and run GenerateOnBeforePaint for all children.
*/
virtual void GenerateOnBeforePaint();
/**
if paint_rect is empty (width or height 0) or marked not visible, nothing is done. for widgets that have not
yet received OnBeforePaint, GenerateOnBeforePaint is called.
will update visual device with the font properties of the widget and draw it, using doublebuffering if requested.
will run GenerateOnPaint on all children that fall inside the paint rect.
@param paint_rect the rect to be painted
@param force_ensure_skin if TRUE, widget background and border will be drawn using skin even if it doesn't want to
*/
virtual void GenerateOnPaint(const OpRect &paint_rect, BOOL force_ensure_skin = FALSE);
/**
will call OnScrollAction
@param delta the scroll delta
@param vertical TRUE if vertical scrolling is to be performed
@param smooth if TRUE, smooth scrolling is to be used
*/
virtual BOOL GenerateOnScrollAction(INT32 delta, BOOL vertical, BOOL smooth = TRUE);
#ifndef MOUSELESS
/**
if there is a captured widget, will make the capured widget the current mouse input context, transform the
mouse coords in point to coords local to the captured widget and call OnMouseMove on it.
if not, the widget will search its children for a widget that contains the point and call OnMouseMove on it.
if none is found, widget will make itself the current input context. if it is enabled, it will change hovered
widget to itself if necessary (and generate OnMouseLeave on the previously hovered widget) and call OnMouseMove
on itself. if the widget is not enabled it will simply generate OnMouseLeave on any hovered widget.
@param point the mouse position (in local document coords)
*/
virtual void GenerateOnMouseMove(const OpPoint &point);
/**
zero:s and genreates OnMouseLeave to the hovered and/or captured widget, in that order.
*/
virtual void GenerateOnMouseLeave();
#if defined(WIDGETS_IME_SUPPORT) && defined(WIDGETS_IME_SUPPRESS_ON_MOUSE_DOWN)
/**
Find the child widget containing the point and call SuppressIMEOnMouseDown on it if it is enabled.
@param point the mouse position (in local document coords)
*/
virtual void TrySuppressIMEOnMouseDown(const OpPoint &point);
/**
Set flags to not spawn IME after OnMouseDown
*/
virtual void SuppressIMEOnMouseDown();
#endif
/**
scans children for one that contains mouse. if there is one, GenerateOnMouseLeave is called on the child and nothing more is done.
otherwise, this widget will be set as the captured widget, and is made mouse input context. if the widget is enabled, OnMouseDown
will be called on it. if not, any listener will receive OnMouseEvent.
@param point the mouse position (in local document coords)
@param button the mouse button that was pushed down
@param nclicks the number of clicks
*/
virtual void GenerateOnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks);
/**
if captured_widget is not set, nothing is done. otherwise, if the captured widget is enabled it will receive OnMouseUp.
otherwise any listener will receive OnMouseEvent.
if button that was released was MOUSE_BUTTON_2, the widget will try to spawn a context menu. if the widget fails,
any listener gets a go. if this also fails, the same process is repeated for its parent, until a context menu is shown
or no parent exists.
@param point the mouse position (in local document coords)
@param button the mouse button that was pushed down
@param nclicks the number of clicks
*/
virtual void GenerateOnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks = 1);
/**
if the widget is tagged as non-visible, nothing is done. otherwise, OnMouseWheel is called.
@param delta the mouse wheel delta
@param vertical if TRUE, the mouse wheel delta is to be interpreted as vertical
*/
virtual BOOL GenerateOnMouseWheel(INT32 delta,BOOL vertical);
/**
will generate an OnSetCursor event if widget is hovered and tagged visible.
*/
virtual void GenerateOnSetCursor(const OpPoint &point);
/**
will call OnMouseUp for all mouse buttons for which the widget has received mouse down but not mouse up
*/
virtual void OnCaptureLost();
#endif // !MOUSELESS
/**
called when the widget is shown/hidden due to SetVisibility being called on this widget or parent etc.
if the widget is to be hidden and is the hover widget, OnMouseLeave is called and hover widget is cleared.
OnShow is called for the widget, and all its visible children.
@param show if TRUE, the widget is to be shown
*/
virtual void GenerateOnShow(BOOL show);
// - GetFocused() returns the focused widget (may be NULL).
/**
returns the currently focused widget
@return the currently focused widget, or NULL if none is focused
*/
static OpWidget* GetFocused();
// Overloading OpInputContext functionality
/**
Overloading OpInputContext functionality. if this widget is new_input_context, GenerateHighlightRectChanged may be called.
@param new_input_context the input context that gained keyboard input focus
@param old_input_context the input context that lost keyboard input focus
@param reason the reason for the change in keyboard input focus
*/
virtual void OnKeyboardInputGained(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason);
/**
Overloading OpInputContext functionality.
@param new_input_context the input context that gained keyboard input focus
@param old_input_context the input context that lost keyboard input focus
@param reason the reason for the change in keyboard input focus
*/
virtual void OnKeyboardInputLost(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason);
/**
Overloading OpInputContext functionality.
@param reason the reason for the change in input focus
@return TRUE if the widget is available for focusing
*/
virtual BOOL IsInputContextAvailable(FOCUS_REASON reason);
/**
Overloading OpInputContext functionality.
@param reason the reason for the change in input focus
*/
virtual void RestoreFocus(FOCUS_REASON reason);
/**
Overloading OpInputContext functionality.
@param parent_context the parent context
*/
virtual void SetParentInputContext(OpInputContext* parent_context, BOOL keep_keyboard_focus = FALSE);
#ifdef QUICK
// Implementing the OpTreeModelItem interface
virtual OP_STATUS GetItemData(ItemData* item_data);
void SetID(INT32 id) { m_id = id; }
#endif // QUICK
/**
returns the ID of the widget. used for UI widgets only.
@return the ID of the widget
*/
virtual INT32 GetID() {return m_id;}
/**
returns the type of the widget. this is the top-level type: WIDGET_TYPE. inheriting widgets should overload.
@return WIDGET_TYPE
*/
virtual Type GetType() {return WIDGET_TYPE;}
/** Return TRUE if the OpWidget is of a specific type. The difference from GetType is that this should propagate up if the
type mismatch.
Note: You must ensure that the subclass of the type you want to check for implements this call! */
virtual BOOL IsOfType(Type type) { return type == WIDGET_TYPE; }
// Almost every widget needs a SetText() / GetText() call, so let's make it common
/**
sets the contents of a widget that contains text to text.
@param text the new text
@return OpStatus::OK if the text was successfully changed, OpStatus::ERR_NO_MEMORY on OOM, OpStatus::ERR for other errors
*/
virtual OP_STATUS SetText(const uni_char* text) {return OpStatus::ERR_NOT_SUPPORTED;}
#ifdef WIDGETS_UNDO_REDO_SUPPORT
/**
* Sets the contents of a widget that contains text with the parameter text.
* Typically, SetText clears the entire undo history because the undo stack only
* stores differences between different input actions from the user.
* Because SetText does a full replace that would be equivalent to
* removing all text and setting a new value. However, that would generate two
* undo events. ideally, when undoing or redoing, both events (remove+insert)
* should be handled simultaneously.
* This method ensures that the SetText call is undoable by the user
*
* @param text the new text
* @return OpStatus::OK if the text was successfully changed, OpStatus::ERR_NO_MEMORY on OOM, OpStatus::ERR for other errors
*/
virtual OP_STATUS SetTextWithUndo(const uni_char* text) { return OpStatus::ERR_NOT_SUPPORTED; }
#endif
/**
gets the contents of a widget that contains text.
@param text (out) filled with the contents of the widget, if it contains text
@return OpStatus::OK if the text was successfully retrieved, OpStatus::ERR_NO_MEMORY on OOM, OpStatus::ERR for other errors
*/
virtual OP_STATUS GetText(OpString& text) {return OpStatus::ERR_NOT_SUPPORTED;}
/**
* Tells if the widget has received user input. This flag is set on OnInputAction
* which is typically triggered by user input, if there has been a change of the value
* held by the widget.
* User input is text or anything that might change the value of the widget.
* Interaction that does not change the value of the widget, like panning or scrolling
* does not affect this state.
*/
inline BOOL HasReceivedUserInput() const { return packed.has_received_user_input; }
/**
* Sets flag which tells if the widget has received user input.
* This flag is used to tell if the undo stack should be used for SetText operations
* and if the UNDO and REDO actions should be always consumed.
* So, after being set, it should be set forever, even when changed not by the user.
* Override with reason.
**/
inline BOOL SetReceivedUserInput(BOOL b = TRUE) { return packed.has_received_user_input = b; }
// .. and some widgets need a SetValue() / GetValue() call, so let's make it common
/**
used by all sorts of widgets that have a value that can be seen as an int.
@param value the value to set
*/
virtual void SetValue(INT32 value) {}
/**
@return the value
*/
virtual INT32 GetValue() {return 0;}
#ifdef WIDGETS_IMS_SUPPORT
/**
* For select widgets: call from sub class to request the platform
* to show and handle the activated widget.
*
* The widget object will receive a response in either DoCommitIMS() or DoCancelIMS().
*
*
* @return OP_STATUS::OK if the platform successfully handled this activated widget
* OP_STATUS::ERR_NOT_SUPPORTED if the platform doesn't support handling this activated widget
* OP_STATUS::<other error message> if the platform does support handling activated widgets, but failed in doing so because of e.g. OOM
*/
OP_STATUS StartIMS();
/**
* For select widgets: call from the sub class to notify platform that
* a widget which was previously activated with StartIMS() now has been
* updated.
*
* @return OP_STATUS::OK if the platform successfully handled this event
* OP_STATUS::ERR_NOT_SUPPORTED if the platform doesn't support handling this event
* OP_STATUS::<other error message> if the platform does support this event, but failed in doing so because of e.g. OOM
*/
OP_STATUS UpdateIMS();
/**
* For select widgets: call from the sub class to notify platform
* that the widget was destroyed when it was active (i.e. after
* StartIMS() but befor DoCommitIMS()/DoCancelIMS().
*
* The sub class will not receive DoCommitIMS() or DoCancelIMS()
* after having called DestroyIMS().
*/
void DestroyIMS();
/**
* OpIMSListener interfaces.
*
* Do not implement these, but implement DoCommitIMS() and
* DoCancelIMS() instead.
*/
void OnCommitIMS(OpIMSUpdateList* updates);
void OnCancelIMS();
protected:
/**
Called from OpWidget when IMS is committed -- derived classes need to override this.
*/
virtual void DoCommitIMS(OpIMSUpdateList* updates) {}
/**
Called from OpWidget when IMS is cancelled -- derived classes need to override this.
*/
virtual void DoCancelIMS() {}
/**
* Set any widget specific information in the OpIMSObject that
* will be used with communicating with the platform
*
* Contains a default implementation to set rectangle etc
* correctly; override, set widget specific attributs and call
* baseclass in derived class.
*
* @return OP_STATUS::OK if information was successfully set
* OP_STATUS::<error message> otherwise
*/
virtual OP_STATUS SetIMSInfo(OpIMSObject& ims_object);
private:
OpIMSObject m_ims_object;
#endif // WIDGETS_IMS_SUPPORT
// ---------------------------------------
// Extended APIS exported by module.export
//
// Products that want to use these will have
// to explicitly import them.
// ---------------------------------------
#ifdef NAMED_WIDGET
friend class OpNamedWidgetsCollection;
public:
/** Return the closest parent collection of named widgets. It may return NULL as some widgets may not have a collection. */
virtual OpNamedWidgetsCollection *GetNamedWidgetsCollection() { return parent ? parent->GetNamedWidgetsCollection() : NULL; }
/**
* Sets the name of the widget, this is only necessary for widgets
* that you will want to search for by name. Note that that means
* that the name will have to be unique within a collection. By default that means unique within its
* WidgetContainer but you can create new collections for any widget by implementing GetNamedWidgetsCollection.
*
* @param name of the widget
*/
void SetName(const OpStringC8 & name);
/**
* Gets the name of a widget. Note that most widgets will not have
* names.
*
* @return the name of the widget
*/
const OpStringC8 & GetName() {return m_name; }
/**
* @return whether the widget has a name
*/
BOOL HasName() {return m_name.HasContent();}
/**
* Checks if the name of the widget is the same as name.
*
* @param name to compare with
* @return true if name has content and that content is the same as the name of the widget
*/
BOOL IsNamed(const OpStringC8 & name) {return name.HasContent() && m_name.CompareI(name) == 0;}
/**
* Search the closest parent collection for the widget with this name. This uses the function
* by the same name in OpNamedWidgetsCollection. Note that this function will therefore
* only work for widgets that are in a collection (widgets in a WidgetContainer will always have one).
*
* @param name to search for
* @return pointer to the widget with that name or NULL if no such widget exists
*/
OpWidget* GetWidgetByName(const OpStringC8 & name);
/**
* Search only the subtree below this widget for the widget with that name.
* Note : this is slower than using GetWidgetByName and is not recomended
* unless that is specifically what you want to do.
*
* @param name to search for
* @return pointer to the widget with that name or NULL if no such widget exists
*/
OpWidget * GetWidgetByNameInSubtree(const OpStringC8 & name);
protected :
/**
* Will be called if/when the name of this widget has been set.
* Can be redefined in the subclasses to perform actions that
* depend on the widget name being known.
*/
virtual void OnNameSet() {}
private :
OpString8 m_name;
#ifdef DEBUG_ENABLE_OPASSERT
BOOL m_has_duplicate_named_widget;
#endif // DEBUG_ENABLE_OPASSERT
#endif // NAMED_WIDGET
};
// ---------------------------------------------------------------------------------
#ifdef QUICK
// Cannot use normal OpVector because DeleteAll doesn't work with
// OpWidget's protected destructor
template<class T>
class OpWidgetVector : private OpGenericVector
{
public:
/**
* Creates a vector, with a specified allocation step size.
*/
OpWidgetVector() {}
/**
* Clear vector, returning the vector to an empty state
*/
void Clear() { OpGenericVector::Clear(); }
/**
* Makes this a duplicate of vec.
*/
OP_STATUS DuplicateOf(const OpVector<T>& vec) { return OpGenericVector::DuplicateOf(vec); }
/**
* Replace the item at index with new item
*/
OP_STATUS Replace(UINT32 idx, T* item) { return OpGenericVector::Replace(idx, item); }
/**
* Insert and add an item of type T at index idx. The index must be inside
* the current vector, or added to the end. This does not replace, the vector will grow.
*/
OP_STATUS Insert(UINT32 idx, T* item) { return OpGenericVector::Insert(idx, item); }
/**
* Adds the item to the end of the vector.
*/
OP_STATUS Add(T* item) { return OpGenericVector::Add(item); }
/**
* Removes item if found in vector
*/
OP_STATUS RemoveByItem(T* item) { return OpGenericVector::RemoveByItem(item); }
/**
* Removes count items starting at index idx and returns the pointer to the first item.
*/
T* Remove(UINT32 idx, UINT32 count = 1) { return static_cast<T*>(OpGenericVector::Remove(idx, count)); }
/**
* Removes AND Delete (call actual delete operator) item if found
*/
OP_STATUS Delete(T* item)
{
RETURN_IF_ERROR(RemoveByItem(item));
item->Delete();
return OpStatus::OK;
}
/**
* Removes AND Delete (call actual delete operator) count items starting at index idx
*/
void Delete(UINT32 idx, UINT32 count = 1)
{
// delete items
for (UINT32 i = 0; i < count; i++)
{
Get(idx + i)->Delete();
}
// clear nodes
Remove(idx, count);
}
/**
* Removes AND Delete (call actual delete operator) all items.
*/
void DeleteAll()
{
Delete(0, GetCount());
}
/**
* Finds the index of a given item
*/
INT32 Find(T* item) const { return OpGenericVector::Find(item); }
/**
* Returns the item at index idx.
*/
T* Get(UINT32 idx) const { return static_cast<T*>(OpGenericVector::Get(idx)); }
/**
* Returns the number of items in the vector.
*/
UINT32 GetCount() const { return OpGenericVector::GetCount(); }
};
#endif // QUICK
/**
* WidgetSafePointer will keep a OpWidget pointer that will automatically be set to NULL
* if the widget is deleted. Only use this for short periods, for example on the stack to
* detect if a call result in a widget being deleted. Do not create excessive amounts of
* it, because it's expensive.
*/
class WidgetSafePointer : public OpWidgetExternalListener
{
public:
WidgetSafePointer(OpWidget* widget)
: m_widget(widget)
, m_deleted(FALSE)
{
g_opera->widgets_module.AddExternalListener(this);
}
~WidgetSafePointer()
{
g_opera->widgets_module.RemoveExternalListener(this);
}
OpWidget* GetPointer() { return m_widget; }
BOOL IsDeleted() { return m_deleted; }
private:
virtual void OnDeleted(OpWidget *widget)
{
if (m_widget == widget)
{
m_widget = NULL;
m_deleted = TRUE;
}
}
OpWidget* m_widget;
BOOL m_deleted;
};
#endif // OP_WIDGET_H
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define show(x) for(auto i: x){cout << i << " ";}
#define showm(m) for(auto i: m){cout << m.x << " ";}
typedef long long ll;
typedef pair<int, int> P;
int main()
{
int n, m;
cin >> n >> m;
vector<vector<int>> s(m);
rep(i, m){
int k;
cin >> k;
rep(j, k){
int tmps; cin >> tmps;
tmps--;
s[i].push_back(tmps);
}
}
vector<int> p;
rep(i, m){
int tmpp; cin >> tmpp;
p.push_back(tmpp);
}
int ans = 0;
rep(i, 1<<n){
bool ng = false;
rep(j, m){
int right = 0;
for(auto sw: s[j]){
if (i>>sw & 1) right += 1;
}
if (right % 2 != p[j]) ng = true;
}
if (!ng) ans++;
}
cout << ans << endl;
}
|
//
// appliquerFiltre.cpp
// main
//
// Created by Wilfried Kamga on 2017-12-01.
//
#include <stdio.h>
#include "common.hpp"
using namespace tp3;
void appliquerFiltre(const cv::Mat& image, cv::Mat& gradients, const cv::Mat_<float>& noyau,
const int ligneDest, const int colonneDest, const int canal)
{
gradients.at<cv::Vec3f>(ligneDest, colonneDest)[canal] = 0;
int distance = noyau.rows / 2;
int ligImg = (-1) * distance;
for (int ligne = 0; ligne < noyau.rows; ligne++)
{
int colImg = (-1) * distance;
for (int colonne = 0; colonne < noyau.cols; colonne++)
{
int vraiColImg = colImg + colonneDest;
int vraiLigImg = ligImg + ligneDest;
gradients.at<cv::Vec3f>(ligneDest, colonneDest)[canal] += image.at<cv::Vec3b>(vraiLigImg, vraiColImg)[canal]
* noyau.at<float>(ligne, colonne);
colImg++;
}
ligImg++;
}
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int a, b, c, d, e, k;
bool flag = false;
cin >> a >> b >> c >> d >> e >> k;
if(b - a > k) flag = true;
else if(c - a > k) flag = true;
else if(d - a > k) flag = true;
else if(e - a > k) flag = true;
else if(c - b > k) flag = true;
else if(d - b > k) flag = true;
else if(e - b > k) flag = true;
else if(d - c > k) flag = true;
else if(e - c > k) flag = true;
else if(e - d > k) flag = true;
if(flag == false) cout << "Yay!" << endl;
else cout << ":(" << endl;
return 0;
}
|
#include <Digraph.h>
#include <DFSearcher.h>
bool Digraph::is_acyclic() const {
for(auto& n : nods) {
if(DFSearcher(*this,n.first).isReachable(n.first))
return false;
}
return true;
}
|
// Created on: 2003-08-22
// Created by: Sergey KUUL
// Copyright (c) 2003-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol_HeaderFile
#define _StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepDimTol_GeometricTolerance.hxx>
class StepDimTol_GeometricToleranceTarget;
class StepDimTol_GeometricToleranceWithDatumReference;
class StepDimTol_ModifiedGeometricTolerance;
class StepDimTol_PositionTolerance;
class TCollection_HAsciiString;
class StepBasic_MeasureWithUnit;
class StepRepr_ShapeAspect;
class StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol;
DEFINE_STANDARD_HANDLE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol, StepDimTol_GeometricTolerance)
class StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol : public StepDimTol_GeometricTolerance
{
public:
Standard_EXPORT StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol();
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(TCollection_HAsciiString)& aDescription, const Handle(StepBasic_MeasureWithUnit)& aMagnitude, const Handle(StepRepr_ShapeAspect)& aTolerancedShapeAspect, const Handle(StepDimTol_GeometricToleranceWithDatumReference)& aGTWDR, const Handle(StepDimTol_ModifiedGeometricTolerance)& aMGT);
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(TCollection_HAsciiString)& aDescription, const Handle(StepBasic_MeasureWithUnit)& aMagnitude, const StepDimTol_GeometricToleranceTarget& aTolerancedShapeAspect, const Handle(StepDimTol_GeometricToleranceWithDatumReference)& aGTWDR, const Handle(StepDimTol_ModifiedGeometricTolerance)& aMGT);
Standard_EXPORT void SetGeometricToleranceWithDatumReference (const Handle(StepDimTol_GeometricToleranceWithDatumReference)& aGTWDR);
Standard_EXPORT Handle(StepDimTol_GeometricToleranceWithDatumReference) GetGeometricToleranceWithDatumReference() const;
Standard_EXPORT void SetModifiedGeometricTolerance (const Handle(StepDimTol_ModifiedGeometricTolerance)& aMGT);
Standard_EXPORT Handle(StepDimTol_ModifiedGeometricTolerance) GetModifiedGeometricTolerance() const;
Standard_EXPORT void SetPositionTolerance (const Handle(StepDimTol_PositionTolerance)& aPT);
Standard_EXPORT Handle(StepDimTol_PositionTolerance) GetPositionTolerance() const;
DEFINE_STANDARD_RTTIEXT(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol,StepDimTol_GeometricTolerance)
protected:
private:
Handle(StepDimTol_GeometricToleranceWithDatumReference) myGeometricToleranceWithDatumReference;
Handle(StepDimTol_ModifiedGeometricTolerance) myModifiedGeometricTolerance;
Handle(StepDimTol_PositionTolerance) myPositionTolerance;
};
#endif // _StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol_HeaderFile
|
#ifndef __BANK_HPP__
#define __BANK_HPP__
#include <iostream>
#include "Account.hpp"
// Definisikan TransactionFailedException di sini
// TransactionFailedException merupakan anak dari kelas BaseException, memiliki:
// - exc bertipe BaseException*
// - constructor menerima argumen exc
// - printMessage yang menuliskan "Transaksi gagal dengan pesan kesalahan:\n"
// diikuti dengan pemanggilan exc->printMessage()
// Definisikan AccountNotFoundException di sini
// AccountNotFoundException merupakan anak dari kelas BaseException, memiliki:
// - number bertipe string
// - constructor menerima argumen number
// - printMessage yang menuliskan "Tidak ditemukan rekening dengan nomor {number}\n"
class Bank {
private:
Account* accounts;
static const int maxEl = 100;
public:
Bank() {
this->accounts = new Account[Bank::maxEl];
}
~Bank() {
delete[] this->accounts;
}
Account& getAccount(int idx) {
return this->accounts[idx];
}
int findAccountIdx(string number) {
// Mengembalikan indeks rekening yang memiliki nomor number
int idx = -1;
for (int i = 0; i < Bank::maxEl; i++) {
if (this->accounts[i].getNumber() == number) {
idx = i;
}
}
return idx;
// TODO: Melempar AccountNotFoundException* bila tidak ditemukan
// rekening dengan nomor number
}
void transfer(string fromNumber, string toNumber, int amount) {
// Mengirimkan uang sebanyak amount dari account dengan nomor
// fromNumber ke account dengan nomor toNumber
Account& fromAccount = this->accounts[this->findAccountIdx(fromNumber)];
Account& toAccount = this->accounts[this->findAccountIdx(toNumber)];
// TODO: Menambah balance dari account tujuan dengan method add
// dan mengurangi balance dari account asal dengan method withdraw.
// TODO: Menangkap semua jenis Exception yang dilempar dan melempar TransactionFailedException*.
// Hint: jangan menangkap tiap jenis exception, manfaatkan BaseException.
// Jika transaksi gagal, PASTIKAN balance kedua rekening tidak ada yang
// berubah.
}
};
#endif
|
#ifndef SHERLOCK_H
#define SHERLOCK_H
#include "../Bricks/port.h"
#include <vector>
#include <string>
#include <mutex>
#include <memory>
#include <thread>
#include <type_traits>
#include <iostream> // TODO(dkorolev): Remove it from here.
#include "../Bricks/net/api/api.h"
#include "../Bricks/time/chrono.h"
#include "../Bricks/waitable_atomic/waitable_atomic.h"
#include "optionally_owned/optionally_owned.h"
// Sherlock is the overlord of data storage and processing in KnowSheet.
// Its primary entity is the stream of data.
// Sherlock's streams are persistent, immutable, append-only typed sequences of records.
//
// The stream is defined by:
//
// 1) Type, which may be:
// a) Single type for simple streams (ex. `UserRecord'),
// b) Base class type for polymorphic streams (ex. `UserActionBase`), or
// c) Base class plus a type list for real-time dispatching (ex. `LogEntry, tuple<Impression, Click>`).
// TODO(dkorolev): The type should also present an unambiguous way to extract a timestamp of it.
//
// 2) Name, which is used for local storage and external access, most notably replication and subscriptions.
//
// 3) Optional type signature, to prevent data corruption when trying to serialize data using the wrong type.
//
// New streams are registred as `auto my_stream = sherlock::Stream<MyType>("my_stream");`.
//
// Sherlock runs as a singleton. The stream of a specific name can only be added once.
// TODO(dkorolev): Implement it this way. :-)
// A user of C++ Sherlock interface should keep the return value of `sherlock::Stream<T>`,
// as it is later used as the proxy to publish and subscribe to the data from this stream.
//
// Sherlock streams can be published into and subscribed to.
// At any given point of time a stream can have zero or one publisher and any number of listeners.
//
// The publishing is done via `my_stream.Publish(MyType{...});`.
//
// NOTE: It is the caller's full responsibility to ensure that:
// 1) Publishing is done from one thread only (since Sherlock offers no locking), and
// 2) The published entries come in non-decreasing order of their timestamps. TODO(dkorolev): Assert this.
//
// Subscription is done by via `my_stream.Subscribe(my_listener);`,
// where `my_listener` is an instance of the class doing the listening.
//
// NOTE: that Sherlock runs each listener in a dedicated thread.
//
// The `my_listener` object should expose the following member functions:
//
// 1) `bool Entry(const T_ENTRY& entry, size_t index, size_t total)`:
// The `T_ENTRY` type is RTTI-dispatched against the supplied type list.
// As long as `my_listener` returns `true`, it will keep receiving new entries,
// which may end up blocking the thread until new, yet unseen, entries have been published.
// Returning `false` will lead to no more entries passed to the listener, and the thread will be
// terminated.
//
// 2) `void CaughtUp()`:
// TODO(dkorolev): Implement it.
// This method will be called as soon as the "historical data replay" phase is completed,
// and the listener has entered the mode of serving the new entires coming in the real time.
// This method is designed to flip some external variable or endpoint to the "healthy" state,
// when the listener is considered eligible to serve incoming data requests.
// TODO(dkorolev): Discuss the case if the listener falls behind again.
//
// 3) `void TerminationRequest()`:
// This member function will be called if the listener has to be terminated externally,
// which happens when the handler returned by `Subscribe()` goes out of scope.
//
// The call to `my_stream.Subscribe(my_listener);` launches the listener and returns
// an instance of a handle, the scope of which will define the lifetime of the listener.
//
// If the subscribing thread would like the listener to run forever, it can
// use use `.Join()` or `.Detach()` on the handle. `Join()` will block the calling thread unconditionally,
// until the listener itself decides to stop listening. `Detach()` will ensure
// that the ownership of the listener object has been transferred to the thread running the listener,
// and detach this thread to run in the background.
//
// TODO(dkorolev): Data persistence and tests.
// TODO(dkorolev): Add timestamps support and tests.
// TODO(dkorolev): Ensure the timestamps always come in a non-decreasing order.
namespace sherlock {
template <typename E>
struct ExtractTimestampImpl {
static bricks::time::EPOCH_MILLISECONDS ExtractTimestamp(const E& entry) { return entry.ExtractTimestamp(); }
};
template <typename E>
struct ExtractTimestampImpl<std::unique_ptr<E>> {
static bricks::time::EPOCH_MILLISECONDS ExtractTimestamp(const std::unique_ptr<E>& entry) {
return entry->ExtractTimestamp();
}
};
template <typename E>
bricks::time::EPOCH_MILLISECONDS ExtractTimestamp(E&& entry) {
return ExtractTimestampImpl<typename std::remove_reference<E>::type>::ExtractTimestamp(
std::forward<E>(entry));
}
template <typename E>
class PubSubHTTPEndpoint {
public:
PubSubHTTPEndpoint(const std::string& value_name, Request r)
: value_name_(value_name),
http_request_(std::move(r)),
http_response_(http_request_.SendChunkedResponse()) {
if (http_request_.url.query.has("recent")) {
serving_ = false; // Start in 'non-serving' mode when `recent` is set.
from_timestamp_ =
r.timestamp - static_cast<bricks::time::MILLISECONDS_INTERVAL>(
bricks::strings::FromString<uint64_t>(http_request_.url.query["recent"]));
}
if (http_request_.url.query.has("n")) {
serving_ = false; // Start in 'non-serving' mode when `n` is set.
bricks::strings::FromString(http_request_.url.query["n"], n_);
cap_ = n_; // If `?n=` parameter is set, it sets `cap_` too by default. Use `?n=...&cap=0` to override.
}
if (http_request_.url.query.has("n_min")) {
// `n_min` is same as `n`, but it does not set the cap; just the lower bound for `recent`.
serving_ = false; // Start in 'non-serving' mode when `n_min` is set.
bricks::strings::FromString(http_request_.url.query["n_min"], n_);
}
if (http_request_.url.query.has("cap")) {
bricks::strings::FromString(http_request_.url.query["cap"], cap_);
}
}
inline bool Entry(E& entry, size_t index, size_t total) {
// TODO(dkorolev): Should we always extract the timestamp and throw an exception if there is a mismatch?
try {
if (!serving_) {
const bricks::time::EPOCH_MILLISECONDS timestamp = ExtractTimestamp(entry);
// Respect `n`.
if (total - index <= n_) {
serving_ = true;
}
// Respect `recent`.
if (from_timestamp_ != static_cast<bricks::time::EPOCH_MILLISECONDS>(-1) &&
timestamp >= from_timestamp_) {
serving_ = true;
}
}
if (serving_) {
http_response_(entry, value_name_);
if (cap_) {
--cap_;
if (!cap_) {
return false;
}
}
}
return true;
} catch (const bricks::net::NetworkException&) {
return false;
}
}
inline void Terminate() { http_response_("{\"error\":\"The subscriber has terminated.\"}\n"); }
private:
// Top-level JSON object name for Cereal.
const std::string& value_name_;
// `http_request_`: need to keep the passed in request in scope for the lifetime of the chunked response.
Request http_request_;
// `http_response_`: the instance of the chunked response object to use.
bricks::net::HTTPServerConnection::ChunkedResponseSender http_response_;
// Conditions on which parts of the stream to serve.
bool serving_ = true;
// If set, the number of "last" entries to output.
size_t n_ = 0;
// If set, the hard limit on the maximum number of entries to output.
size_t cap_ = 0;
// If set, the timestamp from which the output should start.
bricks::time::EPOCH_MILLISECONDS from_timestamp_ = static_cast<bricks::time::EPOCH_MILLISECONDS>(-1);
PubSubHTTPEndpoint() = delete;
PubSubHTTPEndpoint(const PubSubHTTPEndpoint&) = delete;
void operator=(const PubSubHTTPEndpoint&) = delete;
PubSubHTTPEndpoint(PubSubHTTPEndpoint&&) = delete;
void operator=(PubSubHTTPEndpoint&&) = delete;
};
template <typename T>
class StreamInstanceImpl {
public:
inline explicit StreamInstanceImpl(const std::string& name, const std::string& value_name)
: name_(name), value_name_(value_name) {
// TODO(dkorolev): Register this stream under this name.
}
inline void Publish(const T& entry) {
data_.MutableUse([&entry](std::vector<T>& data) { data.emplace_back(entry); });
}
template <typename... ARGS>
inline void Emplace(const ARGS&... entry_params) {
// TODO(dkorolev): Am I not doing this C++11 thing right, or is it not yet supported?
// data_.MutableUse([&entry_params](std::vector<T>& data) { data.emplace_back(entry_params...); });
auto scope = data_.MutableScopedAccessor();
scope->emplace_back(entry_params...);
}
template <typename E>
inline void PublishPolymorphic(const E& polymorphic_entry) {
data_.MutableUse([&polymorphic_entry](std::vector<T>& data) { data.emplace_back(polymorphic_entry); });
}
template <typename F>
class ListenerScope {
public:
inline explicit ListenerScope(bricks::WaitableAtomic<std::vector<T>>& data, OptionallyOwned<F> listener)
: impl_(new Impl(data, std::move(listener))) {}
// TODO(dkorolev): Think whether it's worth it to transfer the scope.
// ListenerScope(ListenerScope&&) = delete;
inline ListenerScope(ListenerScope&& rhs) : impl_(std::move(rhs.impl_)) {}
inline void Join() { impl_->Join(); }
inline void Detach() { impl_->Detach(); }
private:
struct ReallyAtomicFlag {
// TODO(dkorolev): I couldn't figure out shared_ptr + atomic + memory orders at 3am.
bool value_ = false;
mutable std::mutex mutex_;
bool Get() const {
std::unique_lock<std::mutex> lock(mutex_);
return value_;
}
void Set() {
std::unique_lock<std::mutex> lock(mutex_);
value_ = true;
}
};
class Impl {
public:
inline Impl(bricks::WaitableAtomic<std::vector<T>>& data, OptionallyOwned<F> listener)
: listener_is_detachable_(listener.IsDetachable()),
data_(data),
terminate_flag_(new ReallyAtomicFlag()),
listener_thread_(
&Impl::StaticListenerThread, terminate_flag_, std::ref(data), std::move(listener)) {}
inline ~Impl() {
// Indicate to the listener thread that the listener handle is going out of scope.
if (listener_thread_.joinable()) {
// Buzz all active listeners. Ineffective, but does the right thing semantically, and passes the test.
terminate_flag_->Set();
data_.Notify();
// Wait for the thread to terminate.
// Note that this code will only be executed if neither `Join()` nor `Detach()` has been done before.
listener_thread_.join();
}
}
inline void Join() {
if (listener_thread_.joinable()) {
listener_thread_.join();
}
}
inline void Detach() {
if (listener_is_detachable_) {
if (listener_thread_.joinable()) {
listener_thread_.detach();
}
} else {
// TODO(dkorolev): Custom exception type here.
throw std::logic_error("Can not detach a non-unique_ptr-created listener.");
}
}
inline static void StaticListenerThread(std::shared_ptr<ReallyAtomicFlag> terminate,
bricks::WaitableAtomic<std::vector<T>>& data,
OptionallyOwned<F> listener) {
size_t cursor = 0;
while (true) {
data.Wait([&cursor, &terminate](const std::vector<T>& data) {
return terminate->Get() || data.size() > cursor;
});
if (terminate->Get()) {
listener->Terminate();
break;
}
bool user_initiated_terminate = false;
data.ImmutableUse([&listener, &cursor, &user_initiated_terminate](const std::vector<T>& data) {
// Entries are often instances of polymorphic types, that make it into various message queues.
// The most straightforward way to store them is a `unique_ptr`, and the most straightforward
// way to pass `unique_ptr`-s between threads is via `Emplace*(ptr.release())`.
// If `Entry()` is being passed immutable records, the pain of cloning data from `unique_ptr`-s
// becomes the user's pain. This shall not be allowed.
//
// Thus, here we need to make a copy.
// The below implementation is imperfect, but it serves the purpose semantically.
// TODO(dkorolev): Fix it.
const std::string json = JSON(data[cursor]);
T copy_of_entry;
try {
ParseJSON(json, copy_of_entry);
} catch (const std::exception& e) {
std::cerr << "Something went terribly wrong." << std::endl;
std::cerr << e.what();
::exit(-1);
}
// TODO(dkorolev): Perhaps RTTI dispatching here.
if (!listener->Entry(copy_of_entry, cursor, data.size())) {
user_initiated_terminate = true;
}
++cursor;
});
if (user_initiated_terminate) {
break;
}
}
}
const bool listener_is_detachable_; // Indicates whether `Detach()` is legal.
bricks::WaitableAtomic<std::vector<T>>& data_; // Just to `.Notify()` when terminating.
// A termination flag that outlives both the `Impl` and its thread.
std::shared_ptr<ReallyAtomicFlag> terminate_flag_;
// The thread that runs the listener. It owns the actual `OptionallyOwned<F>` handler;
std::thread listener_thread_;
Impl() = delete;
Impl(const Impl&) = delete;
Impl(Impl&&) = delete;
void operator=(const Impl&) = delete;
void operator=(Impl&&) = delete;
};
std::unique_ptr<Impl> impl_;
ListenerScope() = delete;
ListenerScope(const ListenerScope&) = delete;
void operator=(const ListenerScope&) = delete;
void operator=(ListenerScope&&) = delete;
};
// There are two forms of `Subscribe()`: One takes a reference to the listener, and one takes a `unique_ptr`.
// They both go through `OptionallyOwned<F>`, with the one taking a `unique_ptr` being detachable,
// while the one taking a reference to the listener being scoped-only.
// I'd rather implement them as two separate methods to avoid any confusions. - D.K.
template <typename F>
inline ListenerScope<F> Subscribe(F& listener) {
return std::move(ListenerScope<F>(data_, OptionallyOwned<F>(listener)));
}
template <typename F>
inline ListenerScope<F> Subscribe(std::unique_ptr<F>&& listener) {
return std::move(ListenerScope<F>(data_, OptionallyOwned<F>(std::move(listener))));
}
void ServeDataViaHTTP(Request r) {
Subscribe(make_unique(new PubSubHTTPEndpoint<T>(value_name_, std::move(r)))).Detach();
}
private:
const std::string name_;
const std::string value_name_;
// FTR: This is really an inefficient reference implementation. TODO(dkorolev): Revisit it.
bricks::WaitableAtomic<std::vector<T>> data_;
StreamInstanceImpl() = delete;
StreamInstanceImpl(const StreamInstanceImpl&) = delete;
void operator=(const StreamInstanceImpl&) = delete;
StreamInstanceImpl(StreamInstanceImpl&&) = delete;
void operator=(StreamInstanceImpl&&) = delete;
};
// TODO(dkorolev): Move into Bricks/util/ ?
template <typename B, typename E>
struct can_be_stored_in_unique_ptr {
static constexpr bool value = false;
};
template <typename B, typename E>
struct can_be_stored_in_unique_ptr<std::unique_ptr<B>, E> {
static constexpr bool value = std::is_same<B, E>::value || std::is_base_of<B, E>::value;
};
template <typename T>
struct StreamInstance {
StreamInstanceImpl<T>* impl_;
inline explicit StreamInstance(StreamInstanceImpl<T>* impl) : impl_(impl) {}
inline void Publish(const T& entry) { impl_->Publish(entry); }
template <typename... ARGS>
inline void Emplace(const ARGS&... entry_params) {
impl_->Emplace(entry_params...);
}
// TODO(dkorolev): Add a test for this code.
// TODO(dkorolev): Perhaps eliminate the copy.
template <typename E>
typename std::enable_if<can_be_stored_in_unique_ptr<T, E>::value>::type Publish(const E& polymorphic_entry) {
impl_->PublishPolymorphic(new E(polymorphic_entry));
}
template <typename F>
inline typename StreamInstanceImpl<T>::template ListenerScope<F> Subscribe(F& listener) {
return std::move(impl_->Subscribe(listener));
}
template <typename F>
inline typename StreamInstanceImpl<T>::template ListenerScope<F> Subscribe(std::unique_ptr<F> listener) {
return std::move(impl_->Subscribe(std::move(listener)));
}
void operator()(Request r) { impl_->ServeDataViaHTTP(std::move(r)); }
template <typename F>
using ListenerScope = typename StreamInstanceImpl<T>::template ListenerScope<F>;
};
template <typename T>
inline StreamInstance<T> Stream(const std::string& name, const std::string& value_name = "entry") {
// TODO(dkorolev): Validate stream name, add exceptions and tests for it.
// TODO(dkorolev): Chat with the team if stream names should be case-sensitive, allowed symbols, etc.
// TODO(dkorolev): Ensure no streams with the same name are being added. Add an exception for it.
// TODO(dkorolev): Add the persistence layer.
return StreamInstance<T>(new StreamInstanceImpl<T>(name, value_name));
}
} // namespace sherlock
#endif // SHERLOCK_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#include "core/pch.h"
#if defined(_NATIVE_SSL_SUPPORT_)
#include "modules/libssl/sslbase.h"
#include "modules/libssl/protocol/sslver.h"
#include "modules/libssl/protocol/sslplainrec.h"
#include "modules/libssl/protocol/sslcipherrec.h"
#include "modules/libssl/methods/sslhash.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#ifdef LIBSSL_ENABLE_SSL_FALSE_START
#include "modules/libssl/protocol/ssl_false_start_manager.h"
#endif // LIBSSL_ENABLE_SSL_FALSE_START
#ifdef YNP_WORK
#include "modules/libssl/debug/tstdump2.h"
#define SSL_VERIFIER
#endif
struct Handshake_actions_st : public Link
{
int id;
SSL_HandShakeType msg_type;
SSL_Handshake_Status msg_status;
SSL_Handshake_Action action;
Handshake_actions_st(int _id, SSL_HandShakeType mtyp, SSL_Handshake_Status _stat, SSL_Handshake_Action actn):id(_id), msg_type(mtyp), msg_status(_stat), action(actn){};
};
SSL_Version_Dependent::SSL_Version_Dependent(uint8 ver_major, uint8 ver_minor)
: version(ver_major, ver_minor), cipher_desc(NULL)
{
Init();
}
void SSL_Version_Dependent::Init()
{
conn_state = NULL;
if (final_hash.Ptr())
final_hash->ForwardTo(this);
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Hello_Request, SSL_Hello_Request, Handshake_Ignore, Handshake_No_Action);
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Server_Hello, SSL_Server_Hello, Handshake_Expected, Handshake_Handle_Message);
}
SSL_Version_Dependent::~SSL_Version_Dependent()
{
Send_Queue.Clear();
Receive_Queue.Clear();
}
void SSL_Version_Dependent::SetCipher(const SSL_CipherDescriptions *desc)
{
cipher_desc = desc;
}
BOOL SSL_Version_Dependent::SendClosure() const
{
return TRUE;
}
void SSL_Version_Dependent::AddHandshakeHash(SSL_secure_varvector32 *source)
{
if(!source)
return;
SSL_secure_varvector32 *temp = OP_NEW(SSL_secure_varvector32, ());
if(temp)
{
temp->ForwardTo(this);
temp->Set(source);
if(!temp->Error())
temp->Into(&handshake_queue);
else
OP_DELETE(temp);
}
else
RaiseAlert(SSL_Internal,SSL_Allocation_Failure);
if(final_hash->HashID() != SSL_NoHash)
final_hash->CalculateHash(*source);
#if defined _DEBUG && defined YNP_WORK
handshake.Append(*source);
#endif
}
void SSL_Version_Dependent::GetHandshakeHash(SSL_SignatureAlgorithm alg,
SSL_secure_varvector32 &target)
{
SSL_Hash_Pointer hasher;
hasher = SignAlgToHash(alg);
GetHandshakeHash(hasher);
hasher->ExtractHash(target);
}
void SSL_Version_Dependent::GetHandshakeHash(SSL_Hash_Pointer &hasher)
{
hasher->InitHash();
SSL_secure_varvector32 *temp= handshake_queue.First();
while(temp)
{
hasher->CalculateHash(*temp);
temp = (SSL_secure_varvector32 *) temp->Suc();
}
}
void SSL_Version_Dependent::ClearHandshakeActions(Handshake_Queue action_queue)
{
if(action_queue == Handshake_Receive)
Receive_Queue.Clear();
else
Send_Queue.Clear();
}
void SSL_Version_Dependent::AddHandshakeAction(Handshake_Queue action_queue, SSL_V3_handshake_id id,
SSL_HandShakeType mtyp, SSL_Handshake_Status _mstat, SSL_Handshake_Action actn,
Handshake_Add_Point add_policy, SSL_V3_handshake_id add_id)
{
Head *target = (action_queue == Handshake_Receive ? &Receive_Queue : &Send_Queue);
Handshake_actions_st *item = OP_NEW(Handshake_actions_st, (id, mtyp, _mstat, actn));
if(item == NULL)
{
RaiseAlert(SSL_Internal, SSL_Allocation_Failure);
return;
}
switch(add_policy)
{
case Handshake_Add_In_Front:
item->IntoStart(target);
break;
case Handshake_Add_Before_ID:
case Handshake_Add_After_ID:
{
Handshake_actions_st *action = GetHandshakeItem( action_queue, add_id);
if(action)
{
if(add_policy == Handshake_Add_Before_ID)
item->Precede(action);
else
item->Follow(action);
break;
}
// else use default action
}
case Handshake_Add_At_End:
default:
item->Into(target);
break;
}
}
void SSL_Version_Dependent::RemoveHandshakeAction(Handshake_Queue action_queue, int id, Handshake_Remove_Point remove_policy)
{
Handshake_actions_st *action = GetHandshakeItem( action_queue, id);
if(action)
{
if(remove_policy == Handshake_Remove_Only_ID)
{
action->Out();
OP_DELETE(action);
}
else
{
Handshake_actions_st *current_action;
do{
current_action = action;
action = (Handshake_actions_st *) current_action->Suc();
current_action->Out();
OP_DELETE(current_action);
}while(action);
}
}
}
SSL_Handshake_Status SSL_Version_Dependent::GetHandshakeStatus(Handshake_Queue action_queue, int id)
{
Handshake_actions_st *action = GetHandshakeItem( action_queue, id);
return (action ? action->msg_status : Handshake_Undecided);
}
Handshake_actions_st *SSL_Version_Dependent::GetHandshakeItem(Handshake_Queue action_queue, int id)
{
Handshake_actions_st *action = (Handshake_actions_st *) (action_queue == Handshake_Receive ? Receive_Queue.First() : Send_Queue.First());
while(action && action->id != id)
{
action = (Handshake_actions_st *) action->Suc();
}
return action ;
}
SSL_Handshake_Action SSL_Version_Dependent::HandleHandshakeMessage(SSL_HandShakeType mtyp)
{
Handshake_actions_st *action = (Handshake_actions_st *) Receive_Queue.First();
while(action)
{
if(action->msg_type == mtyp)
{
if(action->msg_status == Handshake_Expected || action->msg_status == Handshake_MustReceive)
{
action->msg_status = Handshake_Received;
return action->action;
}
else if(action->msg_status == Handshake_Ignore)
return action->action; // Dont bother, but return action
break; // else unexpected message
}
else if(action->msg_status == Handshake_MustReceive)
break; // unexpected message
action = (Handshake_actions_st *) action->Suc();
}
RaiseAlert(SSL_Fatal, SSL_Unexpected_Message);
return Handshake_Handle_Error;
}
SSL_Handshake_Action SSL_Version_Dependent::NextHandshakeAction(SSL_HandShakeType &mtyp)
{
Handshake_actions_st *action = (Handshake_actions_st *) Send_Queue.First();
while(action)
{
if(action->msg_status == Handshake_Block_Messages)
break;
if(action->msg_status == Handshake_Will_Send)
{
SSL_Handshake_Action actn = action->action;
action->msg_status = Handshake_Sent;
mtyp = action->msg_type;
if(actn == Handshake_Completed)
{
//action = NULL; // implicit
ClearHandshakeActions(Handshake_Send);
ClearHandshakeActions(Handshake_Receive);
// Preparing for renegotiation of the session
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Hello_Request, SSL_Hello_Request, Handshake_Expected, Handshake_Restart);
}
return actn;
}
action = (Handshake_actions_st *) action->Suc();
}
mtyp = SSL_NONE;
return Handshake_No_Action;
}
SSL_Record_Base *SSL_Version_Dependent::GetRecord(SSL_ENCRYPTMODE mode) const
{
SSL_PlainText *rec = NULL;
switch (mode)
{
case SSL_RECORD_ENCRYPTED_COMPRESSED:
case SSL_RECORD_ENCRYPTED_UNCOMPRESSED:
rec = OP_NEW(SSL_CipherText, ());
break;
/* Compression Disabled */
// case SSL_RECORD_COMPRESSED : return new SSL_Compressed;
case SSL_RECORD_PLAIN :
default:
rec = OP_NEW(SSL_PlainText, ());
break;
}
if(rec)
rec->SetVersion(Version());
return rec;
}
void SSL_Version_Dependent::SessionUpdate(SSL_SessionUpdate state)
{
switch(state)
{
case Session_Resume_Session:
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Server_Cipher_Change, SSL_NONE, Handshake_Expected, Handshake_No_Action);
break;
case Session_New_Session:
//case Session_New_Export_Session:
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Certificate, SSL_Certificate, Handshake_MustReceive, Handshake_Handle_Message);
// fall-through
case Session_New_Anonymous_Session:
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Server_keys, SSL_Server_Key_Exchange, Handshake_Expected, Handshake_Handle_Message);
// Anonymous Sessions Do not use
if(state != Session_New_Anonymous_Session)
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Certificate_Request, SSL_CertificateRequest, Handshake_Expected, Handshake_Handle_Message);
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Server_Done, SSL_Server_Hello_Done, Handshake_Expected, Handshake_Handle_Message);
AddHandshakeAction(Handshake_Send, SSL_V3_Send_Pause, SSL_NONE, Handshake_Block_Messages, Handshake_No_Action);
break;
case Session_Server_Done_Received:
RemoveHandshakeAction(Handshake_Receive, SSL_V3_Recv_Server_Hello, Handshake_Remove_From_ID);
RemoveHandshakeAction(Handshake_Send, SSL_V3_Send_Pause, Handshake_Remove_Only_ID);
AddHandshakeAction(Handshake_Send, SSL_V3_Send_PreMaster_Key, SSL_Client_Key_Exchange, Handshake_Will_Send, Handshake_Send_Message,Handshake_Add_Before_ID,SSL_V3_Pre_Certficate_Verify);
AddHandshakeAction(Handshake_Send, SSL_V3_Send_Change_Cipher, SSL_NONE, Handshake_Will_Send, Handshake_ChangeCipher, Handshake_Add_After_ID, SSL_V3_Post_Certficate);
AddHandshakeAction(Handshake_Send, SSL_V3_Send_Client_Finished, SSL_Finished, Handshake_Will_Send, Handshake_Send_Message);
#ifdef LIBSSL_ENABLE_SSL_FALSE_START
if (g_ssl_false_start_manager->ConnectionApprovedForSSLFalseStart(conn_state))
AddHandshakeAction(Handshake_Send, SSL_V3_Send_False_Start_Application_Data, SSL_NONE, Handshake_Will_Send, Handshake_False_Start_Send_Application_Data);
#endif // LIBSSL_ENABLE_SSL_FALSE_START
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Server_Cipher_Change, SSL_NONE, Handshake_Expected, Handshake_No_Action);
break;
case Session_Certificate_Configured:
AddHandshakeAction(Handshake_Send, SSL_V3_Send_Certficate, SSL_Certificate, Handshake_Will_Send, Handshake_Send_Message);
AddHandshakeAction(Handshake_Send, SSL_V3_Pre_Certficate_Verify, SSL_NONE, Handshake_Ignore, Handshake_No_Action);
AddHandshakeAction(Handshake_Send, SSL_V3_Send_Certficate_Verify, SSL_Certificate_Verify, Handshake_Will_Send, Handshake_Send_Message);
AddHandshakeAction(Handshake_Send, SSL_V3_Post_Certficate, SSL_NONE, Handshake_Ignore, Handshake_No_Action);
break;
case Session_No_Certificate:
AddHandshakeAction(Handshake_Send, SSL_V3_Send_No_Certficate, SSL_NONE, Handshake_Will_Send, Handshake_Send_No_Certificate);
break;
case Session_Changed_Server_Cipher:
AddHandshakeAction(Handshake_Receive, SSL_V3_Recv_Server_Finished, SSL_Finished, Handshake_Expected, Handshake_Handle_Message);
break;
case Session_Finished_Confirmed:
if(GetHandshakeStatus(Handshake_Send, SSL_V3_Send_Change_Cipher) != Handshake_Sent)
{
AddHandshakeAction(Handshake_Send, SSL_V3_Send_Change_Cipher, SSL_NONE, Handshake_Will_Send, Handshake_ChangeCipher);
AddHandshakeAction(Handshake_Send, SSL_V3_Send_Client_Finished, SSL_Finished, Handshake_Will_Send, Handshake_Send_Message);
}
AddHandshakeAction(Handshake_Send, SSL_V3_Send_Handshake_Complete, SSL_NONE, Handshake_Will_Send, Handshake_Completed);
break;
}
}
BOOL SSL_Version_Dependent::ExpectingCipherChange()
{
if(GetHandshakeStatus(Handshake_Receive, SSL_V3_Recv_Server_Cipher_Change) != Handshake_Expected)
return FALSE;
RemoveHandshakeAction(Handshake_Receive, SSL_V3_Recv_Server_Cipher_Change);
return TRUE;
}
#endif
|
#include <iostream>
#include <math.h>
using namespace std;
int main(){
int primecount = 1;
int numprim = 2;
int i = 1;
bool amprime = true;
// int root = numprim/2;
cout<<"Initialization\n";
while(primecount <= 10001){
double root = sqrt(numprim);
for( int i = 1; i <= root; i++){
// cout<<"numprime = "<<numprim<<" and i = "<<i;
if (numprim % i == 0 && i!=1){
amprime = false;
// cout<<" and I am setting amprime = false";
}
// cout<<"\n";
}
// if( amprime == false )
// cout<<"I am "<<numprim<<" and I am not a prime.\n";
// else{
if( amprime == true ){
cout<<"I am "<<numprim<<" and I am Optimus prime. My prime index = "<<primecount<<"\n";
primecount++;
}
amprime = true;
numprim++;
}
return 0;
}
|
/*
* source.cpp
*
* Created on: 2021. 6. 9.
* Author: dhjeong
*/
#include <stdio.h>
class test{
public:
void run() {
printf("hello\n");
}
};
|
#ifndef OBJECTSTATUS_H
#define OBJECTSTATUS_H
#include "Array.h"
class Object;
class ObjectStatus
{
friend class Object;
private:
ObjectStatus(void);
ObjectStatus(const ObjectStatus&);
public:
const Array<Object*>& getAttachedObjects(void);
void attach(Object*);
void detach(Object*);
bool isReadyCrash(void);
void setReadyCrash(void);
void setDoneCrash(void);
private:
Array<Object*> attachedObjects;
bool readyCrash;
};
#endif
|
class Solution {
public:
bool isBipartite(int V, vector<int>adj[]){
vector<int> color(V,-1);
for(int i = 0;i<V;i++){
if(color[i]==-1){
color[i]= 0;
queue<int> q;
q.push(i);
while(!q.empty()){
int currentVertex = q.front();
q.pop();
for(auto nbr:adj[currentVertex]){
if(nbr==currentVertex) return false;
if(color[nbr]==color[currentVertex]) return false;
else if(color[nbr]==-1) {
color[nbr] = 1-color[currentVertex];
q.push(nbr);
}
}
}
}
}
return true;
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2011-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 __OPBATCH_REQUEST_H__
#define __OPBATCH_REQUEST_H__
#include "modules/network/op_request.h"
/** @class OpBatchRequestListener
*
* OpBatchRequestListener is used for observing multiple OpRequests sent through the OpBatchRequest class.
* Basically it is the same as a OpRequestListener, but in addition you get a OnBatchResponsesFinished when
* all requests have been processed.
* Usage:
*
* @code
*
* class Listener : public OpBatchRequestListener
* {
* virtual void OnRequestFailed(OpRequest *req, OpResponse *res, Str::LocaleString error) { ... }
* virtual void OnResponseAvailable(OpRequest *req, OpResponse *res) { ... }
* virtual void OnResponseDataLoaded(OpRequest *req, OpResponse *res) { ... }
* virtual void OnResponseFinished(OpRequest *req, OpResponse *res) { ... }
* virtual void OnBatchResponsesFinished() { ... }
* };
*
* OpBatchRequest *batch_request;
* Listener *listener = OP_NEW(Listener,());
* OpBatchRequest::Make(batch_request, listener);
* OpURL url1 = OpURL::Make("http://t/core/networking/http/cache/data/blue.jpg");
* OpURL url2 = OpURL::Make("http://t/core/networking/http/cache/data/yellow.jpg");
* OpURL referrer;
* OpRequest *request;
* OP_STATUS result = OpRequest::Make(request, NULL, url1, referrer);
* batch_request.SendRequest(request)
* result = OpRequest::Make(request, NULL, url2, referrer);
* batch_request->SendRequest(request)
*
* @endcode
*/
class OpBatchRequestListener:public OpRequestListener
{
public:
virtual void OnBatchResponsesFinished() = 0;
};
/** @class OpBatchRequest
*
* OpBatchRequest is used for sending multiple OpRequests at once. After all requests
* have been processed you will get a OnBatchResponsesFinished callback through an
* OpBatchRequestListener. Deleting the batch request deletes (and aborts) all the contained requests.
*/
class OpBatchRequest: public OpRequestListener
{
public:
virtual ~OpBatchRequest() {};
static OP_STATUS Make(OpBatchRequest *&req, OpBatchRequestListener *listener);
/** Add requests to the batch and send. If you have delays between sending each request it is possible to receive
* the OnBatchResponsesFinished() callback in between sending the requests.
*/
virtual OP_STATUS SendRequest(OpRequest *req) = 0;
/** Delete all request objects after a batch has completed. */
virtual void ClearRequests() = 0;
/** Retrieve the first request, and use Next() to traverse all requests in the batch. */
virtual OpRequest *GetFirstRequest() = 0;
};
#endif
|
/*
* Copyright (c) 2020 sayandipde
* Eindhoven University of Technology
* Eindhoven, The Netherlands
*
* Name : image_signal_processing.cpp
*
* Authors : Sayandip De (sayandip.de@tue.nl)
* Sajid Mohamed (s.mohamed@tue.nl)
*
* Date : March 26, 2020
*
* Function : run denoise-cpu profiling with multiple image workloads
*
* History :
* 26-03-20 : Initial version.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <cstdio>
//#include <chrono>
#include <iostream>
#ifdef PROFILEWITHCHRONO
#include "../my_profiler.hpp"
#endif
#include "nl_means.h"
// #include "nl_means_auto_schedule.h"
#include "halide_benchmark.h"
#include "HalideBuffer.h"
#include "halide_image_io.h"
#include <fstream>
using namespace std;
using namespace Halide::Runtime;
using namespace Halide::Tools;
#ifdef PROFILEWITHCHRONO
template<class Container>
std::ostream& write_container(const Container& c, std::ostream& out, string pipeversion, char delimiter = ',')
{
out << pipeversion;
out << delimiter;
bool write_sep = false;
for (const auto& e: c) {
if (write_sep)
out << delimiter;
else
write_sep = true;
out << e;
}
return out;
}
#endif
int main(int argc, char **argv) {
if (argc < 5) {
printf("Usage: ./denoise_multiple.o input.png patch_size search_area sigma\n"
"e.g.: ./denoise_multiple.o input.png 7 7 0.12\n");
return 0;
}
const char * img_path = argv[1];
int patch_size = atoi(argv[2]);
int search_area = atoi(argv[3]);
float sigma = atof(argv[4]);
// int timing_iterations = atoi(argv[5]);
// int timing_iterations = 1;
Buffer<float> input;
vector<vector<double>> wc_avg_bc_tuples;
string in_string, out_string;
for (int version = 0; version <= 7; version++){
cout << "- profiling version: " << version << endl;
out_string = "chrono/runtime_denoise_multiple_v" + to_string(version) + "_.csv";
std::ofstream outfile(out_string);
for (int i = 0; i < 200; i++){
cout << i << endl;
in_string = std::string(img_path)+"v"+to_string(version)+"/demosaic/img_dem_"+to_string(i)+".png";
input = load_and_convert_image(in_string);
Buffer<float> output(input.width(), input.height(), 3);
//////////////////////////////////////////////////////////////////////////////////////////////////
// Timing code
// statistical
#ifdef PROFILEWITHCHRONO
wc_avg_bc_tuples = do_benchmarking( [&]() {
nl_means(input, patch_size, search_area, sigma, output);
} );
write_container(wc_avg_bc_tuples[0], outfile, "img_"+to_string(i));
outfile << "\n";
// Save the output
convert_and_save_image(output, (std::string(img_path)+"v"+to_string(version)+"/denoise/img_den_"+to_string(i)+".png").c_str());
#endif
}
}
return 0;
}
|
/*
* TInfoBox.cpp
*
* Created on: May 27, 2017
* Author: Alex
*/
#include "TInfoBox.h"
#include <efl_extension.h>
void popup_close_cb(void *data, Evas_Object *obj, void *event_info);
TInfoBox::TInfoBox(const char* text):TPopupBox() {
elm_popup_align_set(myPopup, 0.5, 0.5);
evas_object_size_hint_weight_set(myPopup, EVAS_HINT_EXPAND, 0.5);
eext_object_event_callback_add(myPopup, EEXT_CALLBACK_BACK, popup_close_cb, this);
evas_object_smart_callback_add(myPopup, "block,clicked", popup_close_cb, this);
elm_object_text_set(myPopup, text);
/* Evas_Object* textBlock = evas_object_textblock_add((Evas*)myPopup);
evas_object_size_hint_weight_set(textBlock, 0.5, EVAS_HINT_EXPAND);
evas_object_size_hint_min_set(textBlock, 300, 450);
evas_object_size_hint_align_set(textBlock, 0.5, 0.5);
evas_object_show(textBlock);
Evas_Textblock_Style *st = evas_textblock_style_new();
evas_textblock_style_set(st, "DEFAULT='font=Sans font_size=22 color=#114 wrap=word'");
evas_object_textblock_style_set(textBlock, st);
elm_object_content_set(myPopup, textBlock);
evas_object_textblock_text_markup_set(textBlock, text);
*/
/* Continue button */
Evas_Object *btn = elmButtonAdd("Continue","default", 1);
elm_object_part_content_set(myPopup, "button1", btn);
}
TInfoBox::~TInfoBox() {
// TODO Auto-generated destructor stub
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* configFileParser.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user42 <user42@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/14 08:46:39 by trbonnes #+# #+# */
/* Updated: 2021/03/26 16:41:47 by user42 ### ########.fr */
/* */
/* ************************************************************************** */
#include "Config.hpp"
#include "ConfigServer.hpp"
#include "Location.hpp"
void checkEndLine(size_t pos, std::string configFile) {
size_t i;
for (i = configFile.find("\n", pos); pos < i; pos++) {
if (configFile[pos] == ';')
return ;
}
throw Config::InvalidConfigException();
}
size_t findClosingBracket(size_t pos, std::string configFile) {
size_t i;
size_t indentationLvl = 0;
for (i = pos + 1; configFile[i]; i++) {
if (configFile[i] == '}' && indentationLvl == 0)
return i;
if (configFile[i] == '}')
indentationLvl--;
if (configFile[i] == '{')
indentationLvl++;
}
return configFile.npos;
}
std::vector<std::string> readAuthFile(std::string file) {
int fd;
int ret;
char *line;
std::vector<std::string> v;
if ((fd = open(file.c_str(), O_RDONLY)) >= 0) {
while ((ret = get_next_line(fd, &line)) > 0)
{
v.push_back(line);
free(line);
line = NULL;
}
if(line)
v.push_back(line);
free(line);
line = NULL;
close(fd);
}
return v;
}
std::string configFileParseServerLocation(std::string parseServer, ConfigServer *server) {
size_t pos;
size_t i;
std::string s;
std::string tmp;
Location location;
if ((pos = parseServer.find("location")) == parseServer.npos)
return 0;
if ((i = findClosingBracket(parseServer.find("{", pos), parseServer)) == parseServer.npos) {
throw Config::InvalidConfigException();
}
s = parseServer.substr(pos, i - pos + 1);
//LOCATION
pos = 8;
while (s[pos] == ' ') { pos++; }
i = pos;
while (s[i] != ' ') { i++; }
location._location = s.substr(pos, i - pos);
//METHOD
if ((pos = s.find(" method")) != s.npos) {
i = s.find(";", pos);
checkEndLine(pos, s);
if (s.substr(pos, i - pos).find("GET") != s.npos)
location._allow.push_back("GET");
if (s.substr(pos, i - pos).find("HEAD") != s.npos)
location._allow.push_back("HEAD");
if (s.substr(pos, i - pos).find("POST") != s.npos)
location._allow.push_back("POST");
if (s.substr(pos, i - pos).find("PUT") != s.npos)
location._allow.push_back("PUT");
if (s.substr(pos, i - pos).find("DELETE") != s.npos)
location._allow.push_back("DELETE");
if (s.substr(pos, i - pos).find("CONNECT") != s.npos)
location._allow.push_back("CONNECT");
if (s.substr(pos, i - pos).find("OPTIONS") != s.npos)
location._allow.push_back("OPTIONS");
if (s.substr(pos, i - pos).find("TRACE") != s.npos)
location._allow.push_back("TRACE");
}
//ROOT
if ((pos = s.find("root")) != s.npos) {
pos += 4;
checkEndLine(pos, s);
while (s[pos] == ' ') { pos++; }
i = s.find(";", pos);
location._root = s.substr(pos, i - pos);
}
//INDEX
if ((pos = s.find(" index")) != s.npos) {
pos += 6;
checkEndLine(pos, s);
i = pos;
while (s[i] != ';') {
while (s[pos] == ' ') { pos++; }
i = pos;
while (s[i] != ' ' && s[i] != ';') { i++; }
location._index.push_back(s.substr(pos, i - pos));
pos = i;
}
}
//TYPE
if ((pos = s.find("type", i)) != s.npos) {
pos += 4;
checkEndLine(pos, s);
while (s[pos] == ' ') { pos++; }
i = s.find(";", pos);
location._type = s.substr(pos, i - pos);
}
//CHARSET
if ((pos = s.find("charset", i)) != s.npos) {
pos += 7;
checkEndLine(pos, s);
while (s[pos] == ' ') { pos++; }
i = s.find(";", pos);
location._charset = s.substr(pos, i - pos);
}
//LANGUAGE
if ((pos = s.find("language")) != s.npos) {
size_t j;
std::vector<std::string> vs;
pos += 8;
checkEndLine(pos, s);
i = s.find(";", pos);
while (pos != i) {
while (s[pos] == ' ') { pos++; }
j = pos;
while (s[j] &&s[j] != ' ' && s[j] != ';' && s[j] != '\n') { j++; }
if (!s[j] || s[j] == '\n')
throw Config::InvalidConfigException();
vs.push_back(s.substr(pos, j - pos));
pos = j;
}
location._language = vs;
}
//AUTOINDEX
if ((pos = s.find("auto_index")) != s.npos) {
checkEndLine(pos, s);
if ((i = s.find("auto_index on", pos)) != s.npos)
location._autoindex = 1;
else if ((i = s.find("auto_index off", pos)) != s.npos)
location._autoindex = 0;
else
throw Config::InvalidConfigException();
}
//CLIENTBODYSIZE
if ((pos = s.find("client_max_body_size")) != s.npos) {
pos += 20;
checkEndLine(pos, s);
while (s[pos] == ' ') { pos++; }
i = s.find(";", pos);
tmp = s.substr(pos, i - pos);
location._clientBodySize = ft_atoi(tmp.c_str());
}
//ALIAS
if ((pos = s.find("alias")) != s.npos) {
pos += 5;
checkEndLine(pos, s);
while (s[pos] == ' ') { pos++; }
i = s.find(";", pos);
location._alias = s.substr(pos, i - pos);
}
//CGI
if ((pos = s.find("cgi ")) != s.npos) {
pos += 3;
checkEndLine(pos, s);
size_t j;
i = s.find(";", pos);
while (pos != i) {
while (s[pos] == ' ') { pos++; }
j = pos;
while (s[j] &&s[j] != ' ' && s[j] != ';' && s[j] != '\n') { j++; }
if (!s[j] || s[j] == '\n')
throw Config::InvalidConfigException();
location._cgi.push_back(s.substr(pos, j - pos));
pos = j;
}
if ((pos = s.find("cgi_method")) != s.npos) {
i = s.find(";", pos);
checkEndLine(pos, s);
if (s.substr(pos, i - pos).find("GET") != s.npos)
location._cgi_allow.push_back("GET");
if (s.substr(pos, i - pos).find("HEAD") != s.npos)
location._cgi_allow.push_back("HEAD");
if (s.substr(pos, i - pos).find("POST") != s.npos)
location._cgi_allow.push_back("POST");
if (s.substr(pos, i - pos).find("PUT") != s.npos)
location._cgi_allow.push_back("PUT");
if (s.substr(pos, i - pos).find("DELETE") != s.npos)
location._cgi_allow.push_back("DELETE");
if (s.substr(pos, i - pos).find("CONNECT") != s.npos)
location._cgi_allow.push_back("CONNECT");
if (s.substr(pos, i - pos).find("OPTIONS") != s.npos)
location._cgi_allow.push_back("OPTIONS");
if (s.substr(pos, i - pos).find("TRACE") != s.npos)
location._cgi_allow.push_back("TRACE");
}
else
throw Config::InvalidConfigException();
if ((pos = s.find("cgi_root")) != s.npos) {
pos += 8;
checkEndLine(pos, s);
while (s[pos] == ' ') { pos++; }
i = s.find(";", pos);
location._cgi_root = s.substr(pos, i - pos);
}
else
throw Config::InvalidConfigException();
}
//AUTH
if ((pos = s.find("auth_basic")) != s.npos) {
pos += 10;
checkEndLine(pos, s);
while (s[pos] != '\"') { pos++; }
pos++;
i = s.find("\"", pos);
location._auth_basic = s.substr(pos, i - pos);
}
if ((pos = s.find("auth_basic_user_file")) != s.npos) {
pos += 20;
checkEndLine(pos, s);
while (s[pos] == ' ') { pos++; }
i = s.find(";", pos);
location._auth_basic_user_file = s.substr(pos, i - pos);
location._authorizations = readAuthFile(location._auth_basic_user_file);
}
server->insertLocation(location._location, location);
pos = parseServer.find(s);
i = pos;
while (parseServer[i] != '{') { i++; }
i = findClosingBracket(i, parseServer);
parseServer.erase(pos, i - pos + 1);
if (parseServer.find("location") != parseServer.npos)
return configFileParseServerLocation(parseServer, server);
return parseServer;
}
int configFileParseServerUnit(std::string configFile, std::vector<ConfigServer> *v) {
size_t pos;
size_t i;
std::string parseServer;
std::string tmp;
pos = configFile.find("server {");
if ((i = findClosingBracket(configFile.find("{", pos), configFile)) == configFile.npos) {
throw Config::InvalidConfigException();
}
v->push_back(ConfigServer());
parseServer = configFile.substr(pos, i - pos + 1);
parseServer = configFileParseServerLocation(parseServer, &(v->back()));
//PORT
if ((pos = parseServer.find("listen")) != parseServer.npos) {
while (pos != parseServer.npos) {
pos += 6;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
i = parseServer.find(";", pos);
tmp = parseServer.substr(pos, i - pos);
v->back().setPort(ft_atoi(tmp.c_str()));
pos = parseServer.find("listen", i);
}
}
else
throw Config::InvalidConfigException();
//SERVER NAME
if ((pos = parseServer.find("server_name")) != parseServer.npos) {
size_t j;
std::vector<std::string> vs;
pos += 11;
checkEndLine(pos, parseServer);
i = parseServer.find(";", pos);
while (pos != i) {
while (parseServer[pos] == ' ') { pos++; }
j = pos;
while (parseServer[j] &&parseServer[j] != ' ' && parseServer[j] != ';' && parseServer[j] != '\n') { j++; }
if (!parseServer[j] || parseServer[j] == '\n')
throw Config::InvalidConfigException();
vs.push_back(parseServer.substr(pos, j - pos));
pos = j;
}
v->back().setServer_name(vs);
}
else
throw Config::InvalidConfigException();
//METHOD
if ((pos = parseServer.find(" method")) != parseServer.npos) {
std::vector<std::string> allow;
i = parseServer.find(";", pos);
checkEndLine(pos, parseServer);
if (parseServer.substr(pos, i - pos).find("GET") != parseServer.npos)
allow.push_back("GET");
if (parseServer.substr(pos, i - pos).find("HEAD") != parseServer.npos)
allow.push_back("HEAD");
if (parseServer.substr(pos, i - pos).find("POST") != parseServer.npos)
allow.push_back("POST");
if (parseServer.substr(pos, i - pos).find("PUT") != parseServer.npos)
allow.push_back("PUT");
if (parseServer.substr(pos, i - pos).find("DELETE") != parseServer.npos)
allow.push_back("DELETE");
if (parseServer.substr(pos, i - pos).find("CONNECT") != parseServer.npos)
allow.push_back("CONNECT");
if (parseServer.substr(pos, i - pos).find("OPTIONS") != parseServer.npos)
allow.push_back("OPTIONS");
if (parseServer.substr(pos, i - pos).find("TRACE") != parseServer.npos)
allow.push_back("TRACE");
v->back().setAllow(allow);
}
//ROOT
if ((pos = parseServer.find("root")) != parseServer.npos) {
pos += 4;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
i = parseServer.find(";", pos);
v->back().setRoot(parseServer.substr(pos, i - pos));
}
//INDEX
if ((pos = parseServer.find(" index")) != parseServer.npos) {
std::vector<std::string> vi;
pos += 6;
checkEndLine(pos, parseServer);
i = pos;
while (parseServer[i] != ';') {
while (parseServer[pos] == ' ') { pos++; }
i = pos;
while (parseServer[i] != ' ' && parseServer[i] != ';') { i++; }
vi.push_back(parseServer.substr(pos, i - pos));
pos = i;
}
v->back().setIndex(vi);
}
//AUTOINDEX
if ((pos = parseServer.find("auto_index")) != parseServer.npos) {
checkEndLine(pos, parseServer);
if ((i = parseServer.find("auto_index on", pos)) != parseServer.npos)
v->back().setAutoIndex(1);
else if ((i = parseServer.find("auto_index off", pos)) != parseServer.npos)
v->back().setAutoIndex(0);
else
throw Config::InvalidConfigException();
}
//TYPE
if ((pos = parseServer.find("type", i)) != parseServer.npos) {
pos += 4;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
i = parseServer.find(";", pos);
v->back().setType(parseServer.substr(pos, i - pos));
}
//CHARSET
if ((pos = parseServer.find("charset", i)) != parseServer.npos) {
pos += 7;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
i = parseServer.find(";", pos);
v->back().setCharset(parseServer.substr(pos, i - pos));
}
//LANGUAGE
if ((pos = parseServer.find("language")) != parseServer.npos) {
size_t j;
std::vector<std::string> vs;
pos += 8;
checkEndLine(pos, parseServer);
i = parseServer.find(";", pos);
while (pos != i) {
while (parseServer[pos] == ' ') { pos++; }
j = pos;
while (parseServer[j] &&parseServer[j] != ' ' && parseServer[j] != ';' && parseServer[j] != '\n') { j++; }
if (!parseServer[j] || parseServer[j] == '\n')
throw Config::InvalidConfigException();
vs.push_back(parseServer.substr(pos, j - pos));
pos = j;
}
v->back().setLanguage(vs);
}
//CLIENTBODYSIZE
if ((pos = parseServer.find("client_max_body_size")) != parseServer.npos) {
pos += 20;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
i = parseServer.find(";", pos);
tmp = parseServer.substr(pos, i - pos);
v->back().setClientBodySize(ft_atoi(tmp.c_str()));
}
//CGI
if ((pos = parseServer.find("cgi ")) != parseServer.npos) {
pos += 3;
checkEndLine(pos, parseServer);
std::string tmp;
size_t j;
std::vector<std::string> vc;
i = parseServer.find(";", pos);
while (pos != i) {
while (parseServer[pos] == ' ') { pos++; }
j = pos;
while (parseServer[j] &&parseServer[j] != ' ' && parseServer[j] != ';' && parseServer[j] != '\n') { j++; }
if (!parseServer[j] || parseServer[j] == '\n')
throw Config::InvalidConfigException();
vc.push_back(parseServer.substr(pos, j - pos));
pos = j;
}
v->back().setCGI(vc);
if ((pos = parseServer.find("cgi_method")) != parseServer.npos) {
std::vector<std::string> vc;
i = parseServer.find(";", pos);
checkEndLine(pos, parseServer);
if (parseServer.substr(pos, i - pos).find("GET") != parseServer.npos)
vc.push_back("GET");
if (parseServer.substr(pos, i - pos).find("HEAD") != parseServer.npos)
vc.push_back("HEAD");
if (parseServer.substr(pos, i - pos).find("POST") != parseServer.npos)
vc.push_back("POST");
if (parseServer.substr(pos, i - pos).find("PUT") != parseServer.npos)
vc.push_back("PUT");
if (parseServer.substr(pos, i - pos).find("DELETE") != parseServer.npos)
vc.push_back("DELETE");
if (parseServer.substr(pos, i - pos).find("CONNECT") != parseServer.npos)
vc.push_back("CONNECT");
if (parseServer.substr(pos, i - pos).find("OPTIONS") != parseServer.npos)
vc.push_back("OPTIONS");
if (parseServer.substr(pos, i - pos).find("TRACE") != parseServer.npos)
vc.push_back("TRACE");
v->back().setCGI_allow(vc);
}
else
throw Config::InvalidConfigException();
if ((pos = parseServer.find("cgi_root")) != parseServer.npos) {
pos += 8;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
i = parseServer.find(";", pos);
v->back().setCGI_root(parseServer.substr(pos, i - pos));
}
else
throw Config::InvalidConfigException();
}
//AUTH
if ((pos = parseServer.find("auth_basic")) != parseServer.npos) {
pos += 10;
checkEndLine(pos, parseServer);
while (parseServer[pos] != '\"') { pos++; }
pos++;
i = parseServer.find("\"", pos);
v->back().setAuth_basic(parseServer.substr(pos, i - pos));
}
if ((pos = parseServer.find("auth_basic_user_file")) != parseServer.npos) {
pos += 20;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
i = parseServer.find(";", pos);
v->back().setAuth_basic_user_file(parseServer.substr(pos, i - pos));
v->back().setAuthorizations(readAuthFile(parseServer.substr(pos, i - pos)));
}
//ERROR PAGES
if ((pos = parseServer.find("error_root", i)) != parseServer.npos) {
pos += 10;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
i = parseServer.find(";", pos);
v->back().setErrorRoot(parseServer.substr(pos, i - pos));
}
i = 0;
if ((pos = parseServer.find("error_page", i)) != parseServer.npos) {
while ((pos = parseServer.find("error_page", i)) != parseServer.npos) {
std::string page;
std::string errorCode;
bool isX = false;
pos += 10;
checkEndLine(pos, parseServer);
while (parseServer[pos] == ' ') { pos++; }
if ((i = parseServer.find("/", pos)) == parseServer.npos)
throw Config::InvalidConfigException();
size_t j = parseServer.find(";", i);
page = parseServer.substr(i, j - i);
size_t tmp = page.find(".");
if (page[tmp - 1] == 'x')
isX = true;
while (pos != i) {
j = pos;
while (parseServer[j] != ' ' && j != i) { j++; }
errorCode = parseServer.substr(pos, j - pos);
if (isX) {
page[tmp - 1] = errorCode[errorCode.size() - 1];
}
v->back().setErrorPages(ft_atoi(errorCode.c_str()), page);
pos = j;
while (parseServer[pos] == ' ') { pos++; }
}
}
}
pos = configFile.find("server {");
if ((i = findClosingBracket(configFile.find("{", pos), configFile)) == configFile.npos) {
throw Config::InvalidConfigException();
}
configFile.erase(pos, i - pos + 1);
if (configFile.find("server {") != configFile.npos)
return configFileParseServerUnit(configFile, v);
return 0;
}
int configFileParseServers(std::string configFile, Config *config) {
std::vector<ConfigServer> v;
size_t pos;
size_t i;
pos = configFile.find("http {");
if (pos == configFile.npos) {
throw Config::InvalidConfigException();
}
if ((i = findClosingBracket(configFile.find("{", pos), configFile)) == configFile.npos) {
throw Config::InvalidConfigException();
}
configFile.erase(i);
configFile.erase(0, pos + 7);
if ((pos = configFile.find("server {")) == configFile.npos) {
throw Config::InvalidConfigException();
}
configFileParseServerUnit(configFile, &v);
config->setServer(v);
return 0;
}
int configFileParseWorkers(std::string configFile, Config *config) {
size_t pos;
size_t i;
std::string tmp;
if ((pos = configFile.find("worker_processes")) == configFile.npos)
throw Config::InvalidConfigException();
checkEndLine(pos, configFile);
while (!isdigit(configFile[pos]) && configFile[pos] != ';') { pos++; }
i = pos;
while (configFile[i] != ';') { i++; }
tmp = configFile.substr(pos, i);
config->setWorker(ft_atoi(tmp.c_str()));
if (configFile.find("events") != configFile.npos) {
pos = configFile.find("worker_connections");
checkEndLine(pos, configFile);
while (!isdigit(configFile[pos]) && configFile[pos] != ';') { pos++; }
i = pos;
while (configFile[i] != ';') { i++; }
tmp = configFile.substr(pos, i);
config->setWorkerConnections(ft_atoi(tmp.c_str()));
}
return 0;
}
Config *configFileParser(int fd) {
Config *config = new Config();
char c[4096];
std::string configFile;
for (int i = 0; i < 4096; i++)
c[i] = '\0';
while (int ret = read(fd, c, 4096) > 0) {
if (ret == -1) {
delete config;
throw Config::InvalidConfigException();
return NULL;
}
configFile.append(c);
for (int i = 0; i < 4096; i++)
c[i] = '\0';
}
try
{
configFileParseWorkers(configFile, config);
configFileParseServers(configFile, config);
}
catch(const std::exception& e)
{
std::cerr << "Error while parsing : " << e.what() << '\n';
delete config;
throw Config::InvalidConfigException();
}
return config;
}
|
#pragma once
#include "framework.h"
class DftProduct{
protected :
int m_nPdCode; // 상품코드
string m_sPdName; // 상품명
string m_sPdCompany; // 제조사
string m_sPdSellerNM; // 판매자
int m_nStock; // 재고 수량
int m_nPrice; // 가격
public :
DftProduct();
DftProduct(int code, string name, string company, string seller, int price, int stock);
DftProduct(int code, const char * name, const char * company, const char * seller, int price, int stock);
DftProduct(const DftProduct & cp);
~DftProduct();
int getPdCode() const ; // 상품코드
string getPdName()const; // 상품명
string getPdCompany()const; // 제조사
string getPdSellerNM()const; // 판매자
int getStock()const; // 재고 수량
int getPrice()const;
void setPdCode(int code); // 상품코드
void setPdName(string name); // 상품명
void setPdCompany(string company); // 제조사
void setPdSellerNM(string name); // 판매자
void setPdName(const char * name); // 상품명
void setPdCompany(const char * company); // 제조사
void setPdSellerNM(const char * name); // 판매자
void setPrice (int price);
void setStock(int stock); // 재고 수량
void viewInfo() const;
bool saveData(const char* const filename);
};
|
//
// Created by peto184 on 26-Oct-17.
//
#ifndef PPGSO_CAMERA_H
#define PPGSO_CAMERA_H
#include <memory>
#include <glm/glm.hpp>
#include <ppgso/ppgso.h>
#include "src/playground/entities/player.h"
class Player;
class Camera {
public:
glm::vec3 up{0,1,0};
glm::vec3 position{0,0,0};
glm::vec3 target{0,0,0};
glm::mat4 viewMatrix;
glm::mat4 projectionMatrix;
enum CameraMode {
SIDE_CAMERA = 0,
BEHIND_CAMERA = 1,
FIRST_PERSON = 2
};
CameraMode mCameraMode = SIDE_CAMERA;
bool mSwitchCamera = false;
/*!
* Create new Camera that will generate viewMatrix and projectionMatrix based on its position, up and back vectors
* @param fow - Field of view in degrees
* @param ratio - Viewport screen ratio (usually width/height of the render window)
* @param near - Distance to the near frustum plane
* @param far - Distance to the far frustum plane
*/
explicit Camera(float fow = 45.0f, float ratio = 1.0f, float near = 0.1f, float far = 10.0f);
/*!
* Update Camera viewMatrix based on up, position and back vectors
*/
void update(Scene &scene);
};
#endif //PPGSO_CAMERA_H
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
//
// Copyright (C) 1995-2003 Opera Software ASA. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Espen Sand
//
#ifndef __PLUGIN_PATH_DIALOG_H__
#define __PLUGIN_PATH_DIALOG_H__
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/desktop_pi/desktop_file_chooser.h"
#include "adjunct/desktop_util/treemodel/simpletreemodel.h"
class OpEdit;
/***************************************************************
*
* PluginPathDialog
*
***************************************************************/
class PluginPathDialog : public Dialog,
public DesktopFileChooserListener
{
public:
PluginPathDialog(OpEdit* dest_edit) :
m_path_model(2),
m_dest_edit(dest_edit),
m_block_change_detection(FALSE),
m_chooser(0),
m_action_change(FALSE) { }
~PluginPathDialog();
static void Create(DesktopWindow* parent_window, OpEdit* dest_edit);
virtual void OnInit();
void OnSetFocus();
BOOL OnInputAction(OpInputAction* action);
virtual BOOL GetModality() {return TRUE;}
virtual BOOL GetIsBlocking() {return TRUE;}
virtual Type GetType() {return DIALOG_TYPE_PLUGIN_PATH;}
virtual const char* GetWindowName() {return "Plugin Path Dialog";}
INT32 GetButtonCount() { return 2; };
// DesktopFileChooserListener
void OnFileChoosingDone(DesktopFileChooser* chooser, const DesktopFileChooserResult& result);
// OpWidgetListener
void OnItemChanged(OpWidget *widget, INT32 pos);
private:
void UpdateFullPath();
private:
static PluginPathDialog* m_dialog;
SimpleTreeModel m_path_model;
OpEdit* m_dest_edit;
BOOL m_block_change_detection;
OpString m_selected_directory;
DesktopFileChooserRequest m_request;
DesktopFileChooser* m_chooser;
BOOL m_action_change;
};
/***************************************************************
*
* PluginRecoveryDialog
*
***************************************************************/
class PluginRecoveryDialog : public Dialog
{
public:
PluginRecoveryDialog() : m_path_model(2) {}
~PluginRecoveryDialog();
void OnSetFocus();
static BOOL Create(DesktopWindow* parent_window);
static void TestPluginsLoaded(DesktopWindow* parent_window);
virtual void OnInit();
BOOL OnInputAction(OpInputAction* action);
virtual BOOL GetModality() {return TRUE;}
virtual BOOL GetIsBlocking() {return TRUE;}
virtual Type GetType() {return DIALOG_TYPE_PLUGIN_RECOVERY;}
virtual const char* GetWindowName() {return "Plugin Recovery Dialog";}
INT32 GetButtonCount() { return 2; };
private:
void SaveSetting();
private:
static PluginRecoveryDialog* m_dialog;
static BOOL m_ok_pressed;
SimpleTreeModel m_path_model;
};
/***************************************************************
*
* PluginCheckDialog
*
***************************************************************/
class PluginCheckDialog : public Dialog
{
public:
PluginCheckDialog() : m_plugin_model(4) {}
~PluginCheckDialog();
void OnSetFocus();
static void Create(DesktopWindow* parent_window);
static INT32 Populate( OpTreeView* treeview, SimpleTreeModel* model );
virtual void OnInit();
BOOL OnInputAction(OpInputAction* action);
virtual BOOL GetModality() {return TRUE;}
virtual BOOL GetIsBlocking() {return TRUE;}
virtual Type GetType() {return DIALOG_TYPE_PLUGIN_CHECK;}
virtual const char* GetWindowName() {return "Plugin Check Dialog";}
INT32 GetButtonCount() { return 2; };
private:
void SaveSetting();
private:
static PluginCheckDialog* m_dialog;
SimpleTreeModel m_plugin_model;
};
#endif
|
/*
kamalsam
*/
#include<iostream>
using namespace std;
int main()
{
int t,i;
cin>>t;
for(i=0;i<t;i++)
{
long long third,j,lthird,sum,num,first,diff;
cin>>third>>lthird>>sum;
num=(2*sum)/(third+lthird);
diff=(lthird-third)/(num-5);
first=third-(2*diff);
cout<<num<<endl;
for(j=0;j<num;j++)
{
cout<<first<<" ";
first+=diff;
}
cout<<endl;
}
return 0;
}
|
#include "ShapesBlocks.h"
void SqrBaseRectBlocks::sortLengthOfCylinder(){
sort(length.begin(), length.end());
cout << "Sorted \n";
for (auto x : length)
cout << x << endl;
}
|
/**
* Copyright (c) 2022, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "plain_text_source.hh"
#include "base/itertools.hh"
#include "config.h"
static std::vector<plain_text_source::text_line>
to_text_line(const std::vector<attr_line_t>& lines)
{
file_off_t off = 0;
return lines | lnav::itertools::map([&off](const auto& elem) {
auto retval = plain_text_source::text_line{
off,
elem,
};
off += elem.length() + 1;
return retval;
});
}
plain_text_source::plain_text_source(const std::string& text)
{
size_t start = 0, end;
while ((end = text.find('\n', start)) != std::string::npos) {
size_t len = (end - start);
this->tds_lines.emplace_back(start, text.substr(start, len));
start = end + 1;
}
if (start < text.length()) {
this->tds_lines.emplace_back(start, text.substr(start));
}
this->tds_longest_line = this->compute_longest_line();
}
plain_text_source::plain_text_source(const std::vector<std::string>& text_lines)
{
this->replace_with(text_lines);
}
plain_text_source::plain_text_source(const std::vector<attr_line_t>& text_lines)
: tds_lines(to_text_line(text_lines))
{
this->tds_longest_line = this->compute_longest_line();
}
plain_text_source&
plain_text_source::replace_with(const attr_line_t& text_lines)
{
this->tds_lines.clear();
this->tds_doc_sections = lnav::document::discover_metadata(text_lines);
file_off_t off = 0;
auto lines = text_lines.split_lines();
while (!lines.empty() && lines.back().empty()) {
lines.pop_back();
}
for (auto& line : lines) {
auto line_len = line.length() + 1;
this->tds_lines.emplace_back(off, std::move(line));
off += line_len;
}
this->tds_longest_line = this->compute_longest_line();
if (this->tss_view != nullptr) {
this->tss_view->set_needs_update();
}
return *this;
}
plain_text_source&
plain_text_source::replace_with(const std::vector<std::string>& text_lines)
{
file_off_t off = 0;
for (const auto& str : text_lines) {
this->tds_lines.emplace_back(off, str);
off += str.length() + 1;
}
this->tds_longest_line = this->compute_longest_line();
if (this->tss_view != nullptr) {
this->tss_view->set_needs_update();
}
return *this;
}
void
plain_text_source::clear()
{
this->tds_lines.clear();
this->tds_longest_line = 0;
this->tds_text_format = text_format_t::TF_UNKNOWN;
if (this->tss_view != nullptr) {
this->tss_view->set_needs_update();
}
}
plain_text_source&
plain_text_source::truncate_to(size_t max_lines)
{
while (this->tds_lines.size() > max_lines) {
this->tds_lines.pop_back();
}
if (this->tss_view != nullptr) {
this->tss_view->set_needs_update();
}
return *this;
}
size_t
plain_text_source::text_line_width(textview_curses& curses)
{
return this->tds_longest_line;
}
void
plain_text_source::text_value_for_line(textview_curses& tc,
int row,
std::string& value_out,
text_sub_source::line_flags_t flags)
{
value_out = this->tds_lines[row].tl_value.get_string();
}
void
plain_text_source::text_attrs_for_line(textview_curses& tc,
int line,
string_attrs_t& value_out)
{
value_out = this->tds_lines[line].tl_value.get_attrs();
if (this->tds_reverse_selection && tc.is_selectable()
&& tc.get_selection() == line)
{
value_out.emplace_back(line_range{0, -1},
VC_STYLE.value(text_attrs{A_REVERSE}));
}
}
size_t
plain_text_source::text_size_for_line(textview_curses& tc,
int row,
text_sub_source::line_flags_t flags)
{
return this->tds_lines[row].tl_value.length();
}
text_format_t
plain_text_source::get_text_format() const
{
return this->tds_text_format;
}
size_t
plain_text_source::compute_longest_line()
{
size_t retval = 0;
for (auto& iter : this->tds_lines) {
retval = std::max(retval, (size_t) iter.tl_value.length());
}
return retval;
}
nonstd::optional<vis_line_t>
plain_text_source::line_for_offset(file_off_t off) const
{
struct cmper {
bool operator()(const file_off_t& lhs, const text_line& rhs)
{
return lhs < rhs.tl_offset;
}
bool operator()(const text_line& lhs, const file_off_t& rhs)
{
return lhs.tl_offset < rhs;
}
};
if (this->tds_lines.empty()) {
return nonstd::nullopt;
}
auto iter = std::lower_bound(
this->tds_lines.begin(), this->tds_lines.end(), off, cmper{});
if (iter == this->tds_lines.end()) {
if (this->tds_lines.back().contains_offset(off)) {
return nonstd::make_optional(
vis_line_t(std::distance(this->tds_lines.end() - 1, iter)));
}
return nonstd::nullopt;
}
if (!iter->contains_offset(off) && iter != this->tds_lines.begin()) {
--iter;
}
return nonstd::make_optional(
vis_line_t(std::distance(this->tds_lines.begin(), iter)));
}
void
plain_text_source::text_crumbs_for_line(int line,
std::vector<breadcrumb::crumb>& crumbs)
{
const auto initial_size = crumbs.size();
const auto& tl = this->tds_lines[line];
this->tds_doc_sections.m_sections_tree.visit_overlapping(
tl.tl_offset,
[&crumbs, initial_size, meta = &this->tds_doc_sections, this](
const auto& iv) {
auto path = crumbs | lnav::itertools::skip(initial_size)
| lnav::itertools::map(&breadcrumb::crumb::c_key)
| lnav::itertools::append(iv.value);
crumbs.template emplace_back(
iv.value,
[meta, path]() { return meta->possibility_provider(path); },
[this, meta, path](const auto& key) {
auto curr_node = lnav::document::hier_node::lookup_path(
meta->m_sections_root.get(), path);
if (!curr_node) {
return;
}
auto* parent_node = curr_node.value()->hn_parent;
if (parent_node == nullptr) {
return;
}
key.template match(
[this, parent_node](const std::string& str) {
auto sib_iter
= parent_node->hn_named_children.find(str);
if (sib_iter
== parent_node->hn_named_children.end()) {
return;
}
this->line_for_offset(sib_iter->second->hn_start) |
[this](const auto new_top) {
this->tss_view->set_selection(new_top);
};
},
[this, parent_node](size_t index) {
if (index >= parent_node->hn_children.size()) {
return;
}
auto sib = parent_node->hn_children[index].get();
this->line_for_offset(sib->hn_start) |
[this](const auto new_top) {
this->tss_view->set_selection(new_top);
};
});
});
});
auto path = crumbs | lnav::itertools::skip(initial_size)
| lnav::itertools::map(&breadcrumb::crumb::c_key);
auto node = lnav::document::hier_node::lookup_path(
this->tds_doc_sections.m_sections_root.get(), path);
if (node && !node.value()->hn_children.empty()) {
auto poss_provider = [curr_node = node.value()]() {
std::vector<breadcrumb::possibility> retval;
for (const auto& child : curr_node->hn_named_children) {
retval.template emplace_back(child.first);
}
return retval;
};
auto path_performer = [this, curr_node = node.value()](
const breadcrumb::crumb::key_t& value) {
value.template match(
[this, curr_node](const std::string& str) {
auto child_iter = curr_node->hn_named_children.find(str);
if (child_iter != curr_node->hn_named_children.end()) {
this->line_for_offset(child_iter->second->hn_start) |
[this](const auto new_top) {
this->tss_view->set_selection(new_top);
};
}
},
[this, curr_node](size_t index) {
auto* child = curr_node->hn_children[index].get();
this->line_for_offset(child->hn_start) |
[this](const auto new_top) {
this->tss_view->set_selection(new_top);
};
});
};
crumbs.emplace_back(
"", "\u22ef", std::move(poss_provider), std::move(path_performer));
crumbs.back().c_expected_input = node.value()->hn_named_children.empty()
? breadcrumb::crumb::expected_input_t::index
: breadcrumb::crumb::expected_input_t::index_or_exact;
}
}
nonstd::optional<vis_line_t>
plain_text_source::row_for_anchor(const std::string& id)
{
nonstd::optional<vis_line_t> retval;
if (this->tds_doc_sections.m_sections_root == nullptr) {
return retval;
}
lnav::document::hier_node::depth_first(
this->tds_doc_sections.m_sections_root.get(),
[this, &id, &retval](const lnav::document::hier_node* node) {
for (const auto& child_pair : node->hn_named_children) {
auto child_anchor
= text_anchors::to_anchor_string(child_pair.first);
if (child_anchor == id) {
retval = this->line_for_offset(child_pair.second->hn_start);
}
}
});
return retval;
}
std::unordered_set<std::string>
plain_text_source::get_anchors()
{
std::unordered_set<std::string> retval;
lnav::document::hier_node::depth_first(
this->tds_doc_sections.m_sections_root.get(),
[&retval](const lnav::document::hier_node* node) {
for (const auto& child_pair : node->hn_named_children) {
retval.emplace(
text_anchors::to_anchor_string(child_pair.first));
}
});
return retval;
}
nonstd::optional<std::string>
plain_text_source::anchor_for_row(vis_line_t vl)
{
nonstd::optional<std::string> retval;
if (vl > this->tds_lines.size()
|| this->tds_doc_sections.m_sections_root == nullptr)
{
return retval;
}
const auto& tl = this->tds_lines[vl];
this->tds_doc_sections.m_sections_tree.visit_overlapping(
tl.tl_offset, [&retval](const lnav::document::section_interval_t& iv) {
retval = iv.value.match(
[](const std::string& str) {
return nonstd::make_optional(
text_anchors::to_anchor_string(str));
},
[](size_t) { return nonstd::nullopt; });
});
return retval;
}
|
#include "catch.hpp"
#include "../Input.h"
TEST_CASE("fetcDataFromFile function") {
SECTION("Blank reviews file") {
Input reviewsInput;
reviewsInput.fetchDataFromFile("blankReviews.csv");
REQUIRE(reviewsInput.getReviews().empty());
REQUIRE(reviewsInput.getSentiments().empty());
}
SECTION("Multiple reviews file") {
Input reviewsInput;
reviewsInput.fetchDataFromFile("multipleReviews.csv");
std::vector<int> sentimentsExpected{ 1,1 };
std::vector<int> sentimentsActual = reviewsInput.getSentiments();
REQUIRE(sentimentsActual == sentimentsExpected);
BagOfWords review1("review1");
BagOfWords review2("review2");
std::vector<BagOfWords> reviewsExpected{ review1, review2 };
std::vector<BagOfWords> reviewsActual = reviewsInput.getReviews();
REQUIRE(reviewsExpected == reviewsActual);
}
SECTION("Single review file") {
Input reviewsInput;
reviewsInput.fetchDataFromFile("singleReview.csv");
std::vector<int> sentimentsExpected{ 1 };
std::vector<int> sentimentsActual = reviewsInput.getSentiments();
REQUIRE(sentimentsActual == sentimentsExpected);
BagOfWords review1("review1");
std::vector<BagOfWords> reviewsExpected{ review1 };
std::vector<BagOfWords> reviewsActual = reviewsInput.getReviews();
REQUIRE(reviewsExpected == reviewsActual);
}
}
|
#include "msg_0x27_attachentity_stc.h"
namespace MC
{
namespace Protocol
{
namespace Msg
{
AttachEntity::AttachEntity()
{
_pf_packetId = static_cast<int8_t>(0x27);
_pf_initialized = false;
}
AttachEntity::AttachEntity(int32_t _entityId, int32_t _vehicleId)
: _pf_entityId(_entityId)
, _pf_vehicleId(_vehicleId)
{
_pf_packetId = static_cast<int8_t>(0x27);
_pf_initialized = true;
}
size_t AttachEntity::serialize(Buffer& _dst, size_t _offset)
{
_pm_checkInit();
if(_offset == 0) _dst.clear();
_offset = WriteInt8(_dst, _offset, _pf_packetId);
_offset = WriteInt32(_dst, _offset, _pf_entityId);
_offset = WriteInt32(_dst, _offset, _pf_vehicleId);
return _offset;
}
size_t AttachEntity::deserialize(const Buffer& _src, size_t _offset)
{
_offset = _pm_checkPacketId(_src, _offset);
_offset = ReadInt32(_src, _offset, _pf_entityId);
_offset = ReadInt32(_src, _offset, _pf_vehicleId);
_pf_initialized = true;
return _offset;
}
int32_t AttachEntity::getEntityId() const { return _pf_entityId; }
int32_t AttachEntity::getVehicleId() const { return _pf_vehicleId; }
void AttachEntity::setEntityId(int32_t _val) { _pf_entityId = _val; }
void AttachEntity::setVehicleId(int32_t _val) { _pf_vehicleId = _val; }
} // namespace Msg
} // namespace Protocol
} // namespace MC
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-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 Cihat Imamoglu (cihati)
*/
#include "core/pch.h"
#include "adjunct/quick_toolkit/widgets/QuickRadioButton.h"
OP_STATUS QuickRadioButton::ConstructSelectableQuickWidget()
{
GetOpWidget()->SetButtonType(OpButton::TYPE_RADIO);
GetOpWidget()->SetJustify(JUSTIFY_LEFT, FALSE);
RETURN_IF_ERROR(FindImageSizes("Radio Button Skin"));
return OpStatus::OK;
}
|
#ifndef GAMEHANDLER_H
#define GAMEHANDLER_H
#include "GameLayer.h"
class GameHandler {
public:
WindowRef window;
GameLayer* UI;
GameLayer* MainLayer;
GameLayer* Background;
GameHandler(WindowRef ref);
void setWindow(WindowRef window);
~GameHandler();
void drawGame();
};
#endif
|
#include "TestView.h"
MY_IMPLEMENT_DYNCREATE(CTestView, CMyView)
CTestView::CTestView()
{
}
CTestView::~CTestView()
{
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-1999 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef DOM_LSCONTENTHANDLER
#define DOM_LSCONTENTHANDLER
#ifdef DOM3_LOAD
#include "modules/ecmascript/ecmascript.h"
#include "modules/dom/src/domload/lsparser.h"
class DOM_LSLoader;
class ES_Thread;
class ES_ThreadListener;
class DOM_LSContentHandler_AsyncCallback;
class DOM_LSContentHandler_MutationListener;
class DOM_LSContentHandler_InsertionPoint;
class XMLDocumentInformation;
class DOM_LSContentHandler
{
protected:
DOM_LSParser *parser;
DOM_LSLoader *loader;
unsigned whatToShow;
ES_Object *filter;
ES_Thread *handler_thread, *calling_thread;
ES_Value return_value;
DOM_LSContentHandler_AsyncCallback *callback;
BOOL callback_in_use;
DOM_LSContentHandler_MutationListener *mutationlistener;
DOM_Node *parent, *before;
BOOL done, blocked, empty, restart_insertBefore, after_filter, skip, reject, interrupt;
DOM_LSContentHandler_InsertionPoint *insertionpoint;
XMLDocumentInformation *docinfo;
OP_STATUS StartElement(HTML_Element *element);
OP_STATUS EndElement(DOM_Node *node);
OP_STATUS PushInsertionPoint(DOM_Node *parent, DOM_Node *before);
void PopInsertionPoint();
public:
DOM_LSContentHandler(DOM_LSParser *parser, DOM_LSLoader *loader, unsigned whatToShow, ES_Object *filter);
~DOM_LSContentHandler();
void SetInsertionPoint(DOM_Node *parent, DOM_Node *before);
void SetCallingThread(ES_Thread *calling_thread);
void Abort();
void GCTrace();
void ThreadRemoved();
void ThreadCancelled();
BOOL IsDone() { return done; }
BOOL IsEmpty() { return empty; }
BOOL IsRunning() { return handler_thread != NULL; }
void DisableParsing() { parser->DisableParsing(); }
OP_STATUS HandleElements();
OP_STATUS HandleFinished();
OP_STATUS HandleDocumentInfo(const XMLDocumentInformation &docinfo);
OP_STATUS MoreElementsAvailable();
OP_STATUS FilterFinished(const ES_Value &result);
ES_Thread *GetInterruptThread();
};
#endif // DOM3_LOAD
#endif // DOM_LSCONTENTHANDLER
|
#include <iostream>
#include <string.h>
#include <vector>
#include <bitset>
#include <map>
#include <fstream>
#include <algorithm>
#include "../lib/structs.cpp"
#include "../lib/trie.cpp"
/*
#ifndef STRUCTS_I
#define STRUCTS_I
#include "../lib/structs.cpp"
#endif
#ifndef XCHECK_I
#define XCHECK_I
#include "../moves/xcheck.cpp"
#endif
*/
using namespace std;
string findPartial(Tile anchor, vector<Tile> row){
/* -rlyshw. this is finished. needs testing
I think this should be done on rows of tiles, not the entire board. this
* way we understand the orientation we are working with.
* In this case, row is a generic list of Tiles, could be either vertical
* or horizontal
* args: Tile anchor; the anchor from which we are computing
* Board board; the actual board object
* RETURNS: the string of the prefix to the left(or above) of anchor, only from tiles that are already on the board
* I'm going to assume the input is the row
*/
int dir = anchor.orient;
int x=anchor.coords.at(dir-1);
if(x==0)return "";
int i= x-1;
string out;
for(i;row.at(i).letter!=0&&i>0;i--);//
for(i;i<x;i++){
out.append(string(1,row.at(i).letter));
}
if(out[0]==0)out=out.substr(1,out.size()-1);
return out;
}
void crossCheck(Tile& tile, Board& board){
// Nazim
/* Need to deal with orientation and other side of the tile
tile.orient is 1 if just horizontal, 2 if just vertical, 3 if both
Scenario 1 passes orient 1 (taken care of automatically)
after running partial word horizontally (if necessary) => result 1
do get col, run findPartial on the right tile => result 2
loop tile.xchecks to result 1 AND result 2
*/
Trie trie = getTrie();
string word;
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
vector<Tile> row;
if(tile.orient==1)row = board.getRow(tile.coords[1]);
else if(tile.orient==2)row = board.getCol(tile.coords[0]);
string leftSide = findPartial(tile, row);
reverse(row.begin(),row.end());
tile.coords.at(tile.orient-1)=14-tile.coords.at(tile.orient-1);
string rightSide = findPartial(tile, row);
reverse(rightSide.begin(),rightSide.end());
reverse(row.begin(),row.end());
tile.coords.at(tile.orient-1)=14-tile.coords.at(tile.orient-1);
//cout << "xcheck at ("<<tile.coords[0]<<","<<tile.coords[1]<<");"<<tile.orient<<": "<<leftSide<<"_"<<rightSide<<endl;
bitset<26> old = tile.xchecks;
for (int i = 0; i < 26; i++){
int wordLength = leftSide.length()+1+rightSide.length();
word = leftSide + alphabet[i] + rightSide;
char * y = new char[wordLength+1];
copy(word.begin(),word.end(),y);
y[wordLength] = '\0';
tile.xchecks[i] = trie.hasWord(y, wordLength); // I'm a genius. That's Nazim. He really is.
delete[] y;
}
tile.xchecks = tile.xchecks & old;
}
vector<Tile> getAnchors(Board& board){
//Sam
/* Args: board; a Board with tiles on it. Tiles should have a completed xchecks vector associated w/ them.
* RETURNS: vector<Tile> a list of all of the tiles that are anchors.
* anchors are defined as the leftmost empty tiles adjacent to already placed tiles with non-trivial xchecks.
* That is; they are the blank spots to the left of words already on the board(tile.letter==0)
* and they have non-trivial crosschecks(there is at least one '1' in tile.xchecks
* once we decide a tile is an anchor, run xcheck on it.
* Anchors should mark the tile as such. Tile.anchor = true;
* Anchors should also be denoted as a row or a col anchor.
do this by setting tile.orient = 0, or 1, 2, 3;
tiles should default to 0.
1 means horizontal. 2 means vertical.
I need to know this to know which direction to compute the partialWord.
added int orient to Tile struct
*/
vector<Tile> anchors;
vector<Tile> finalAnchs;
for (int i = 0; i< 15; i++){ //rows
vector<Tile> row = board.getRow(i);
vector<Tile> col = board.getCol(i);
for (int j = 0; j < 14; j++){
if (row.at(j).letter == 0 && isalpha(row.at(j+1).letter)){ //checks if the tile is empty and the tile next to it has a letter
board.getTile(j,i).orient = 1; //horizontal (the way the board normally looks)
anchors.push_back(board.getTile(j,i));
}
else if (col.at(j).letter == 0 && isalpha(col.at(j+1).letter)){
board.getTile(i,j).orient = 2; //vertically
if(i==0&&j==11)cout << "ZERO ELEVEN"<<board.getTile(i,j).orient<<endl;
anchors.push_back(board.getTile(i,j));
}
}
}
//cross checks everything that is adjacent to a filled tile.
for (int j = 0; j < 15; j++){
vector<Tile> row = board.getRow(j);
vector<Tile> col = board.getCol(j);
for (int i =0; i < 15; i++){
if (i ==0){
if (row.at(i).letter == 0 && (isalpha(row.at(i+1).letter))){
board.getTile(j,i).orient = 1;
crossCheck(board.getTile(j,i), board);
}
if (col.at(i).letter == 0 && (isalpha(col.at(i+1).letter))){
board.getTile(i,j).orient = 2;
crossCheck(board.getTile(i,j), board);
}
}
else if (i ==14){
if (row.at(i).letter == 0 && (isalpha(row.at(i-1).letter))){
board.getTile(j,i).orient = 1;
crossCheck(board.getTile(j,i), board);
}
if (col.at(i).letter == 0 && (isalpha(col.at(i-1).letter))){
board.getTile(i,j).orient = 2;
crossCheck(board.getTile(i,j), board);
}
}
else {
if (row.at(i).letter == 0 && (isalpha(row.at(i+1).letter) || isalpha(row.at(i-1).letter))){
board.getTile(j,i).orient = 1;
crossCheck(board.getTile(j,i), board);
}
if (col.at(i).letter == 0 && (isalpha(col.at(i+1).letter) || isalpha(col.at(i-1).letter))){
board.getTile(i,j).orient = 2;
crossCheck(board.getTile(i,j), board);
}
}
}
}
for (int i = 0; i < anchors.size(); i++){ // runs xcheck on all the anchors
if ((anchors.at(i).xchecks).count() !=0){ //checks to make sure the bitset isn't trivial (all 0s)
finalAnchs.push_back(anchors.at(i));
}
}
for (int i = 0; i<finalAnchs.size(); i++){
finalAnchs.at(i).anchor = true;
}
cout << "anchor 0,11 orient: " << finalAnchs[0].orient << endl;
return finalAnchs;
}
int findLimit(Tile anchor, vector<Tile> row){
//Sam
/* args: Tile anchor, the anchor we want to find the left limit of.
* Board board, the board to analyze
* returns: the number of non-anchor tiles to the left of anchor.
*/
int limit = 0;
int xcoord = anchor.coords.at(anchor.orient-1);
//find the coordinate of the anchor on the board
//check from the anchor to the beginning of the row to add to limit count
//if it reaches another anchor limit is stopped
for (int i = xcoord; i > 0; i--){
//stops the limit count if it hits another anchor
if (row.at(i).anchor){
return limit;
}
//increases the limit count for each non-anchor tile left of it that it reaches
else{
limit++;
}
}
return limit;
}
vector<int> scoreit(Tile t){
vector<int> ans(4);
if (t.bonus ==0){
ans.at(0) += t.weight;
}
if (t.bonus == 2){
ans.at(0) += t.bonus * t.weight;
}
if (t.bonus == 3){
ans.at(0) += t.bonus * t.weight;
}
if (t.bonus == 3){
ans.at(1)++;
}
if (t.bonus == 4){
ans.at(2)++;
}
if (t.letter == 0){
ans.at(3)++;
}
return ans;
}
int getScore(string partialWord, Board board, Tile end){
//Josh
/* ARGS: partialWord; legal partial word combination formed from rack tiles
* board; current board
* endTile; last tile of the word in question
*RETURNS: The score of the playable word
*/
Board tempBoard = board;
Tile endTile = end;
int score = 0;
int doublebonus = 0;
int triplebonus = 0;
int rack = 0;
int xcoord = endTile.coords.at(0);
int ycoord = endTile.coords.at(1);
int length = partialWord.length();
//If the word is horizontally oriented, this is the right-most board letter of the word
if (endTile.orient = 1){
for (int i = 0; i < length; i++){
Tile temp = board.getTile(xcoord-i, ycoord);
vector<int> scoreDoubTripRack(4);
scoreDoubTripRack = scoreit(temp);
score += scoreDoubTripRack.at(0);
doublebonus += scoreDoubTripRack.at(1);
triplebonus += scoreDoubTripRack.at(2);
rack += scoreDoubTripRack.at(3);
tempBoard.getTile(xcoord-i, ycoord).letter = partialWord.at(length-1-i);
int j = 1;
while (isalpha(tempBoard.getTile(xcoord, ycoord +j).letter) && (ycoord + j) <15){
score += tempBoard.getTile(xcoord, ycoord +j).weight;
j++;
}
while (isalpha(tempBoard.getTile(xcoord, ycoord -j).letter) && (ycoord - j) >=0){
score += tempBoard.getTile(xcoord, ycoord -j).weight;
j++;
}
}
}
if (endTile.orient = 2){
for (int i = 0; i < length; i++){
Tile temp = board.getTile(xcoord, ycoord-i);
vector<int> scoreDoubTripRack(4);
scoreDoubTripRack = scoreit(temp);
score += scoreDoubTripRack.at(0);
doublebonus += scoreDoubTripRack.at(1);
triplebonus += scoreDoubTripRack.at(2);
rack += scoreDoubTripRack.at(3);
tempBoard.getTile(xcoord, ycoord-i).letter = partialWord.at(length-1-i);
int j = 1;
while (isalpha(tempBoard.getTile(xcoord + j, ycoord).letter) && (ycoord + j) <15){
score += tempBoard.getTile(xcoord+ j, ycoord).weight;
j++;
}
while (isalpha(tempBoard.getTile(xcoord-j, ycoord).letter) && (ycoord - j) >=0){
score += tempBoard.getTile(xcoord-j, ycoord).weight;
j++;
}
}
if(doublebonus > 0){
score = score*2*doublebonus;
}
if(triplebonus > 0){
score = score*3*triplebonus;
}
if(rack == 7){
score += 50;
}
return score;
}
}
|
class BMP2_HQ_CDF;
class BMP2_HQ_CDF_DZ: BMP2_HQ_CDF {
scope = 2;
displayName = "$STR_VEH_NAME_BMP2_CDF";
vehicleClass = "DayZ Epoch Vehicles";
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
transportMaxMagazines = 100;
transportMaxWeapons = 20;
transportmaxbackpacks = 6;
enableGPS = 0;
supplyRadius = 1.8;
class Turrets; // External class reference
class MainTurret; // External class reference
};
class BMP2_HQ_CDF_DZE: BMP2_HQ_CDF_DZ {
scope = 2;
class Turrets: Turrets
{
class MainTurret: MainTurret
{
magazines[] = {"SmokeLauncherMag","SmokeLauncherMag","SmokeLauncherMag"};
};
};
class Upgrades {
ItemTankORP[] = {"BMP2_HQ_CDF_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class BMP2_HQ_CDF_DZE1: BMP2_HQ_CDF_DZE {
displayName = "$STR_VEH_NAME_BMP2_CDF+";
original = "BMP2_HQ_CDF_DZE";
maxspeed = 90; // base 65
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"BMP2_HQ_CDF_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class BMP2_HQ_CDF_DZE2: BMP2_HQ_CDF_DZE1 {
displayName = "$STR_VEH_NAME_BMP2_CDF++";
armor = 320; // base 250
damageResistance = 0.035; // base 0.01796
class Upgrades {
ItemTankLRK[] = {"BMP2_HQ_CDF_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BMP2_HQ_CDF_DZE3: BMP2_HQ_CDF_DZE2 {
displayName = "$STR_VEH_NAME_BMP2_CDF+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"BMP2_HQ_CDF_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class BMP2_HQ_CDF_DZE4: BMP2_HQ_CDF_DZE3 {
displayName = "$STR_VEH_NAME_BMP2_CDF++++";
fuelCapacity = 1200; // base 700
};
class BMP2_HQ_INS;
class BMP2_HQ_INS_DZ: BMP2_HQ_INS {
scope = 2;
displayName = "$STR_VEH_NAME_BMP2_INS";
vehicleClass = "DayZ Epoch Vehicles";
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
transportMaxMagazines = 100;
transportMaxWeapons = 20;
transportmaxbackpacks = 6;
enableGPS = 0;
supplyRadius = 1.8;
class Turrets; // External class reference
class MainTurret; // External class reference
};
class BMP2_HQ_INS_DZE: BMP2_HQ_INS_DZ {
scope = 2;
class Turrets: Turrets
{
class MainTurret: MainTurret
{
magazines[] = {"SmokeLauncherMag","SmokeLauncherMag","SmokeLauncherMag"};
};
};
class Upgrades {
ItemTankORP[] = {"BMP2_HQ_INS_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class BMP2_HQ_INS_DZE1: BMP2_HQ_INS_DZE {
displayName = "$STR_VEH_NAME_BMP2_INS+";
original = "BMP2_HQ_INS_DZE";
maxspeed = 90; // base 65
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"BMP2_HQ_INS_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class BMP2_HQ_INS_DZE2: BMP2_HQ_INS_DZE1 {
displayName = "$STR_VEH_NAME_BMP2_INS++";
armor = 320; // base 250
damageResistance = 0.035; // base 0.01796
class Upgrades {
ItemTankLRK[] = {"BMP2_HQ_INS_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BMP2_HQ_INS_DZE3: BMP2_HQ_INS_DZE2 {
displayName = "$STR_VEH_NAME_BMP2_INS+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"BMP2_HQ_INS_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class BMP2_HQ_INS_DZE4: BMP2_HQ_INS_DZE3 {
displayName = "$STR_VEH_NAME_BMP2_INS++++";
fuelCapacity = 1200; // base 700
};
class BMP2_HQ_TK_EP1;
class BMP2_HQ_TK_EP1_DZ: BMP2_HQ_TK_EP1 {
scope = 2;
displayName = "$STR_VEH_NAME_BMP2_TK";
vehicleClass = "DayZ Epoch Vehicles";
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
transportMaxMagazines = 100;
transportMaxWeapons = 20;
transportmaxbackpacks = 6;
enableGPS = 0;
supplyRadius = 1.8;
class Turrets; // External class reference
class MainTurret; // External class reference
};
class BMP2_HQ_TK_EP1_DZE: BMP2_HQ_TK_EP1_DZ {
scope = 2;
class Turrets: Turrets
{
class MainTurret: MainTurret
{
magazines[] = {"SmokeLauncherMag","SmokeLauncherMag","SmokeLauncherMag"};
};
};
class Upgrades {
ItemTankORP[] = {"BMP2_HQ_TK_EP1_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class BMP2_HQ_TK_EP1_DZE1: BMP2_HQ_TK_EP1_DZE {
displayName = "$STR_VEH_NAME_BMP2_TK+";
original = "BMP2_HQ_TK_EP1_DZE";
maxspeed = 90; // base 65
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"BMP2_HQ_TK_EP1_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class BMP2_HQ_TK_EP1_DZE2: BMP2_HQ_TK_EP1_DZE1 {
displayName = "$STR_VEH_NAME_BMP2_TK++";
armor = 320; // base 250
damageResistance = 0.035; // base 0.01796
class Upgrades {
ItemTankLRK[] = {"BMP2_HQ_TK_EP1_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BMP2_HQ_TK_EP1_DZE3: BMP2_HQ_TK_EP1_DZE2 {
displayName = "$STR_VEH_NAME_BMP2_TK+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"BMP2_HQ_TK_EP1_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class BMP2_HQ_TK_EP1_DZE4: BMP2_HQ_TK_EP1_DZE3 {
displayName = "$STR_VEH_NAME_BMP2_TK++++";
fuelCapacity = 1200; // base 700
};
class BMP2_Ambul_INS;
class BMP2_Ambul_INS_DZE: BMP2_Ambul_INS {
scope = 2;
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_INS";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_INS";
vehicleClass = "DayZ Epoch Vehicles";
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
transportMaxMagazines = 100;
transportMaxWeapons = 20;
transportmaxbackpacks = 6;
enableGPS = 0;
supplyRadius = 1.8;
attendant = 0;
class Upgrades {
ItemTankORP[] = {"BMP2_Ambul_INS_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_INS_DZE1: BMP2_Ambul_INS_DZE {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_INS+";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_INS+";
original = "BMP2_Ambul_INS_DZE";
maxspeed = 90; // base 65
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"BMP2_Ambul_INS_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_INS_DZE2: BMP2_Ambul_INS_DZE1 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_INS++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_INS++";
armor = 320; // base 250
damageResistance = 0.035; // base 0.01796
class Upgrades {
ItemTankLRK[] = {"BMP2_Ambul_INS_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_INS_DZE3: BMP2_Ambul_INS_DZE2 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_INS+++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_INS+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"BMP2_Ambul_INS_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class BMP2_Ambul_INS_DZE4: BMP2_Ambul_INS_DZE3 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_INS++++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_INS++++";
fuelCapacity = 1200; // base 700
};
class BMP2_Ambul_CDF;
class BMP2_Ambul_CDF_DZE: BMP2_Ambul_CDF {
scope = 2;
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF";
vehicleClass = "DayZ Epoch Vehicles";
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
transportMaxMagazines = 100;
transportMaxWeapons = 20;
transportmaxbackpacks = 6;
enableGPS = 0;
supplyRadius = 1.8;
attendant = 0;
class Upgrades {
ItemTankORP[] = {"BMP2_Ambul_CDF_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_CDF_DZE1: BMP2_Ambul_CDF_DZE {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF+";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF+";
original = "BMP2_Ambul_CDF_DZE";
maxspeed = 90; // base 65
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"BMP2_Ambul_CDF_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_CDF_DZE2: BMP2_Ambul_CDF_DZE1 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF++";
armor = 320; // base 250
damageResistance = 0.035; // base 0.01796
class Upgrades {
ItemTankLRK[] = {"BMP2_Ambul_CDF_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_CDF_DZE3: BMP2_Ambul_CDF_DZE2 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF+++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"BMP2_Ambul_CDF_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class BMP2_Ambul_CDF_DZE4: BMP2_Ambul_CDF_DZE3 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF++++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF++++";
fuelCapacity = 1200; // base 700
};
class BMP2_Ambul_Winter_DZE: BMP2_Ambul_CDF_DZE {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER";
hiddenSelectionsTextures[] = {"\dayz_epoch_c\skins\bmp\bmp2_01_camo_winter_co.paa","\dayz_epoch_c\skins\bmp\bmp2_02_camo_winter_co.paa"};
class Upgrades {
ItemTankORP[] = {"BMP2_Ambul_Winter_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_Winter_DZE1: BMP2_Ambul_Winter_DZE {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER+";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER+";
original = "BMP2_Ambul_Winter_DZE";
maxspeed = 90; // base 65
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"BMP2_Ambul_Winter_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_Winter_DZE2: BMP2_Ambul_Winter_DZE1 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER++";
armor = 320; // base 250
damageResistance = 0.035; // base 0.01796
class Upgrades {
ItemTankLRK[] = {"BMP2_Ambul_Winter_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class BMP2_Ambul_Winter_DZE3: BMP2_Ambul_Winter_DZE2 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER+++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"BMP2_Ambul_Winter_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class BMP2_Ambul_Winter_DZE4: BMP2_Ambul_Winter_DZE3 {
displayName = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER++++";
displayNameShort = "$STR_VEH_NAME_BMP2_AMBULANCE_CDF_WINTER++++";
fuelCapacity = 1200; // base 700
};
class BMP2_INS;
class BMP2_RUST: BMP2_INS {
displayName = "$STR_VEH_NAME_BMP2_RUST";
hiddenSelectionsTextures[] = {"\dayz_epoch_c\skins\bmp\bmp2_01_wrecked_co.paa","\dayz_epoch_c\skins\bmp\bmp2_02_wrecked_co.paa"};
};
class BMP2_WINTER: BMP2_INS {
displayName = "$STR_VEH_NAME_BMP2_WINTER";
hiddenSelectionsTextures[] = {"\dayz_epoch_c\skins\bmp\bmp2_01_winter.paa","\dayz_epoch_c\skins\bmp\bmp2_02_winter.paa"};
};
|
// File: fileio.cpp
// Written by Joshua Green
#include <iostream>
#include "fileio.h"
#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
fileio::fileio() {
_buffer = 0;
_rdbuffer = 0;
_file = 0;
_clear();
}
fileio::~fileio() {
close();
}
void fileio::_clear() {
if (_buffer != 0) delete[] _buffer;
if (_rdbuffer != 0) delete[] _rdbuffer;
if (_file != 0) fclose(_file);
_size = 0;
_pointer = 0;
_open = false;
_bufferfilled = 0;
_rdpos = 0;
_rdfilled = 0;
_filename.clear();
}
// default behavior: read binary, if failed, write binary
bool fileio::open(string filename) {
if (_open) return false;
_open_file(filename, "rb+");
return _open;
}
bool fileio::open(string filename, string mode) {
if (_open) return false;
if (mode == "r") mode = "rb";
else if (mode == "r+" || mode == "rw") mode = "rb+";
else if (mode == "w") mode = "wb";
else if (mode == "w+") mode = "wb+";
if (mode[1] != 'b') return false;
_open_file(filename, mode);
return _open;
}
// attempts to open with supplied mode, upon failure attempts to open with wb+
void fileio::_open_file(const string &filename, const string &mode) {
_file = fopen(filename.c_str(), mode.c_str());
if (_file != 0) _open = true;
/*else {
_file = fopen(filename.c_str(), "wb+");
if (_file != 0) _open = true;
else _open = false;
}*/
if (_open) {
_filename = filename;
_buffer = new char[BUFFER_SIZE+1];
_rdbuffer = new char[BUFFER_SIZE+1];
for (int i=0;i<BUFFER_SIZE;i++) {
_buffer[i] = '\0';
_rdbuffer[i] = '\0';
}
fseek(_file, 0, SEEK_SET);
_refresh_size();
_pointer = 0;
clearerr(_file);
}
}
void fileio::close() {
if (_open) {
// dump buffer before closing...
if (_bufferfilled > 0) {
fseek(_file, 0, SEEK_END);
_put(_buffer, _bufferfilled);
}
fclose(_file);
_file = 0;
_clear();
}
}
bool fileio::is_open() {
return _open;
}
long long int fileio::write(const string &data) {
if (!is_open()) return 0;
long long int length = data.size();
long long int stored = 0;
// maintain read buffer:
if ((_rdpos > -1) && _pointer >= _rdpos && _pointer < _rdpos+BUFFER_SIZE && _rdfilled > 0) {
for (long int i=0;i<BUFFER_SIZE;i++) {
if (i >= data.length() || (i+(_pointer-_rdpos) >= BUFFER_SIZE)) break;
_rdbuffer[i+(_pointer-_rdpos)] = data[i];
// maintain _rdfilled (the amount of read buffer that is filled)
if (i+(_pointer-_rdpos) >= _rdfilled) _rdfilled++;
}
}
// if overwriting data:
if (_pointer < _size+_bufferfilled) {
// if overwriting file:
if (_pointer < _size) {
fseek(_file, _pointer, SEEK_SET); // Ensure the file is writing to the place the user thinks it is
long long int bytes_into_file = _size-_pointer;
if (bytes_into_file > length) bytes_into_file = length;
char *c_data = new char[bytes_into_file+1];
for (int i=0;i<bytes_into_file;i++) {
c_data[i] = data[i];
}
c_data[bytes_into_file] = '\0';
long long int written;
written = _put(c_data, bytes_into_file);
stored += written;
_pointer += written;
_refresh_size();
delete[] c_data;
}
// if overwriting buffer:
if (stored < length) {
for (int i=(_pointer-_size);i<_bufferfilled;i++) {
if (stored >= length) return stored;
_buffer[i] = data[stored];
stored++;
_pointer++;
}
}
}
// if appending to buffer:
if (_pointer >= _size+_bufferfilled && stored < length) {
while (stored < length) {
// write buffer to file if buffer overflowed:
if (_bufferfilled >= BUFFER_SIZE) {
_put(_buffer, _bufferfilled);
_bufferfilled = 0;
}
// store new data into buffer:
_buffer[_bufferfilled] = data[stored];
_bufferfilled++;
// update file pointer:
_pointer++;
stored++;
}
}
return stored;
}
long long int fileio::write(int data) {
string temp;
temp += data;
return write(temp);
}
// _put()
// Doesn't move _pointer
// Moves the actual file pointer to the end of the written data
// Recalculates _size
long long int fileio::_put(char *data, int size) {
if (_file == 0) return 0;
clearerr(_file);
_flush();
int written = fwrite(data, sizeof(char), size, _file);
_flush();
// Recalculate _size
_refresh_size();
return written;
}
long long int fileio::pos() {
return _pointer;
}
long long int fileio::seek(long long int fpos) {
if (!is_open()) return 0;
if (fpos < 0) fpos = 0;
clearerr(_file);
// Allow pointer to access position in buffer:
if (fpos >= _size) {
if (fpos > _bufferfilled+_size) fpos = _bufferfilled+_size;
_pointer = fpos;
fseek(_file, _size, SEEK_SET);
}
else {
fseek(_file, fpos, SEEK_SET);
_pointer = ftell(_file);
}
clearerr(_file);
return _pointer;
}
long long int fileio::seek(string fpos) {
if (!is_open()) return 0;
clearerr(_file);
if (fpos == "END" || fpos == "end") {
_pointer = _size+_bufferfilled;
fseek(_file, 0, SEEK_END);
}
clearerr(_file);
return _pointer;
}
string fileio::read(long int length, char delim) {
return read(length, string(1, delim));
}
string fileio::read(long int length, string delim) {
if (!is_open()) return "";
if (length < 0) length = size();
long long int read_length = 0;
string data;
char c;
if (_pointer < _size) fseek(_file, _pointer, SEEK_SET); // ensure proper internal file pointer
clearerr(_file);
// deliminator variable:
delim_checker deliminator(delim);
// load and maintain read buffer
// if pointer is less than currently loaded read buffer pos
// and pointer is not reading from the write buffer
if ((_pointer < _rdpos || _pointer > _rdpos+_rdfilled || _rdpos < 0) && _pointer < _size) {
_rdpos = ftell(_file);
_rdfilled=0;
for (int i=0;i<BUFFER_SIZE && i<_size-_pointer;i++) {
_rdbuffer[i] = (char)getc(_file);
_rdfilled++;
}
}
// Read from read buffer
if (_pointer >= _rdpos && _pointer < _rdpos+_rdfilled) {
for (long long int i=0;i<BUFFER_SIZE;i++) {
if (_pointer-_rdpos >= _rdfilled) break;
data.push_back(_rdbuffer[_pointer-_rdpos]);
read_length++;
_pointer++;
// delim check:
if (deliminator.next(_rdbuffer[(_pointer-1)-_rdpos])) {
deliminator.clean(data);
return data;
}
if (read_length >= length) return data;
}
}
// Read from file:
if (_pointer < _size) fseek(_file, _pointer, SEEK_SET); // ensure proper internal file pointer
clearerr(_file);
_flush();
while (_pointer < _size) {
c = (char)getc(_file);
data.push_back(c);
_pointer++;
read_length++;
// delim check:
if (deliminator.next(c)) {
deliminator.clean(data);
return data;
}
if (read_length >= length) return data;
}
// Read from write buffer:
while (_pointer < _size+_bufferfilled && _pointer-_size >= 0) {
data.push_back(_buffer[_pointer-_size]);
_pointer++;
read_length++;
// delim check:
if (deliminator.next(_buffer[(_pointer-1)-_size])) {
deliminator.clean(data);
return data;
}
if (read_length >= length) return data;
}
_flush();
return data;
}
long long int fileio::size() {
if (!is_open()) return 0;
_refresh_size();
return _size+_bufferfilled;
}
long long int fileio::flush() {
if (!is_open()) return 0;
long long int written;
written = _put(_buffer, _bufferfilled);
_bufferfilled = 0;
return written;
}
void fileio::_refresh_size() {
long long int pos = ftell(_file);
fseek(_file, 0, SEEK_END);
_size = ftell(_file);
fseek(_file, pos, SEEK_SET);
}
void fileio::_flush() {
long long int fpos = ftell(_file);
fflush(_file);
fseek(_file, fpos, SEEK_SET);
}
string fileio::filename() {
return _filename;
}
void fileio::rm() {
string filename = _filename;
_bufferfilled = 0;
close();
remove(filename.c_str());
}
void fileio::mv(const string &new_name) {
string filename = _filename;
close();
rename(filename.c_str(), new_name.c_str());
open(new_name);
}
// -----------------------------------------------------------
// Deliminator Checker Class:
// -----------------------------------------------------------
delim_checker::delim_checker(const string &delim) {
set(delim);
}
bool delim_checker::found() {
return ((_delim == _matched) && (_delim.length() > 0));
}
bool delim_checker::next(char c) {
if (index >= _delim.length()) return found();
if (_delim[index] == c) {
_matched.append(1, c);
index++;
}
else {
index = 0;
_matched.clear();
}
return found();
}
void delim_checker::clean(string &data) {
if (found()) data.erase(data.length()-_delim.length(), _delim.length());
}
void delim_checker::reset() {
_delim.clear();
_matched.clear();
index = 0;
}
void delim_checker::set(const string &delim) {
reset();
_delim = delim;
}
// -----------------------------------------------------------
// Debug Functions:
// -----------------------------------------------------------
void fileio::file_dump() {
string data;
long long int pos = ftell(_file),
size =0;
fseek(_file, 0, SEEK_END);
size = ftell(_file);
fseek(_file, 0, SEEK_SET);
char *c_data = new char[size+1];
fread(c_data, sizeof(char), size, _file);
for (int i=0;i<size;i++) {
data.append(1, c_data[i]);
}
delete[] c_data;
fseek(_file, pos, SEEK_SET);
cout << "-------FILE-------" << endl;
cout << "|" << data << "|" << endl;
cout << "------------------" << endl;
}
void fileio::fpos_dump() {
cout << "-------FPOS-------" << endl;
cout << ftell(_file) << endl;
cout << "------------------" << endl;
}
void fileio::buffer_dump() {
cout << "-------BUFF-------" << endl;
cout << "|";
for (int i=0;i<_bufferfilled;i++) cout << _buffer[i];
if (_bufferfilled+1 < BUFFER_SIZE) cout << "[" << _buffer[_bufferfilled+1] << "]";
if (_bufferfilled+2 < BUFFER_SIZE) cout << "[" << _buffer[_bufferfilled+2] << "]...";
cout << "|" << endl;
cout << "------RDBUFF------" << endl;
cout << "|";
for (int i=0;i<_rdfilled;i++) cout << _rdbuffer[i];
if (_rdfilled+1 < BUFFER_SIZE) cout << "[" << _rdbuffer[_rdfilled+1] << "]";
if (_rdfilled+2 < BUFFER_SIZE) cout << "[" << _rdbuffer[_rdfilled+2] << "]...";
cout << "|" << endl;
cout << "------------------" << endl;
}
void fileio::data_dump() {
cout << "-------DATA------" << endl;
cout << "_size = " << _size << endl;
cout << "_pointer = " << _pointer << endl;
cout << "_open = " << _open << endl;
cout << "BUFFER_SIZE = " << BUFFER_SIZE << endl;
cout << "_bufferfilled = " << _bufferfilled << endl;
cout << "_rdpos = " << _rdpos << endl;
cout << "_rdfilled = " << _rdfilled << endl;
cout << "------------------" << endl;
}
// -----------------------------------------------------------
|
/********************************************************************************
** Form generated from reading UI file 'stats.ui'
**
** Created by: Qt User Interface Compiler version 5.13.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_STATS_H
#define UI_STATS_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QScrollArea>
#include <QtWidgets/QScrollBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Stats
{
public:
QScrollArea *scrollArea;
QWidget *scrollAreaWidgetContents_4;
QGridLayout *gridLayout;
QLabel *label_lose_lv_2;
QLabel *label_maxSc_2;
QLabel *label_maxScore_9;
QLabel *label_lose_lv;
QLabel *label_losedLv5;
QLabel *label_losedLv1;
QLabel *label_losedLv6;
QLabel *label_maxSc_5;
QPushButton *pushButton_back;
QLabel *label_lose_lv_5;
QLabel *label_losedLv9;
QLabel *label_losedLv4;
QLabel *label_stdDev;
QLabel *label_pCampaign;
QLabel *label_maxScore_10;
QLabel *label_username;
QScrollBar *verticalScrollBar;
QLabel *label_lose_lv_4;
QLabel *label_median;
QLabel *label_confidence;
QLabel *label_lose_lv_3;
QLabel *label_maxSc_3;
QLabel *label_5;
QLabel *label_maxScore_8;
QLabel *label_maxSc_6;
QLabel *label_losedLv7;
QLabel *label_mean;
QLabel *label_lose_lv_9;
QLabel *label_maxSc_4;
QLabel *label_7;
QLabel *played_campaign;
QLabel *played_survival;
QLabel *label_3;
QLabel *label_losedLv8;
QLabel *label_maxScore_4;
QLabel *label_maxSc_7;
QLabel *label_variance;
QLabel *label_10;
QLabel *label_maxScore;
QLabel *label_pSurvival;
QLabel *label_maxSc_8;
QLabel *label_maxSc_9;
QLabel *label_lose_lv_8;
QLabel *label_losedLv3;
QLabel *label_4;
QLabel *label_maxSc;
QLabel *label_maxScore_7;
QLabel *label_losedLv2;
QLabel *label_8;
QLabel *label_maxScore_5;
QLabel *label_maxScore_3;
QLabel *label_lose_lv_7;
QLabel *label_maxSc_10;
QLabel *label_6;
QLabel *label_2;
QLabel *label_proportion;
QLabel *label_lose_lv_6;
QLabel *label_maxScore_6;
QLabel *label_maxScore_2;
QLabel *label_email;
void setupUi(QDialog *Stats)
{
if (Stats->objectName().isEmpty())
Stats->setObjectName(QString::fromUtf8("Stats"));
Stats->resize(436, 380);
scrollArea = new QScrollArea(Stats);
scrollArea->setObjectName(QString::fromUtf8("scrollArea"));
scrollArea->setGeometry(QRect(10, 20, 385, 351));
scrollArea->setWidgetResizable(true);
scrollAreaWidgetContents_4 = new QWidget();
scrollAreaWidgetContents_4->setObjectName(QString::fromUtf8("scrollAreaWidgetContents_4"));
scrollAreaWidgetContents_4->setGeometry(QRect(0, 0, 388, 424));
gridLayout = new QGridLayout(scrollAreaWidgetContents_4);
gridLayout->setSpacing(5);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
gridLayout->setContentsMargins(10, 10, 10, 10);
label_lose_lv_2 = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv_2->setObjectName(QString::fromUtf8("label_lose_lv_2"));
gridLayout->addWidget(label_lose_lv_2, 4, 1, 1, 2);
label_maxSc_2 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_2->setObjectName(QString::fromUtf8("label_maxSc_2"));
gridLayout->addWidget(label_maxSc_2, 4, 5, 1, 2);
label_maxScore_9 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_9->setObjectName(QString::fromUtf8("label_maxScore_9"));
gridLayout->addWidget(label_maxScore_9, 11, 3, 1, 2);
label_lose_lv = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv->setObjectName(QString::fromUtf8("label_lose_lv"));
gridLayout->addWidget(label_lose_lv, 3, 1, 1, 2);
label_losedLv5 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv5->setObjectName(QString::fromUtf8("label_losedLv5"));
gridLayout->addWidget(label_losedLv5, 7, 0, 1, 1);
label_losedLv1 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv1->setObjectName(QString::fromUtf8("label_losedLv1"));
gridLayout->addWidget(label_losedLv1, 3, 0, 1, 1);
label_losedLv6 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv6->setObjectName(QString::fromUtf8("label_losedLv6"));
gridLayout->addWidget(label_losedLv6, 8, 0, 1, 1);
label_maxSc_5 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_5->setObjectName(QString::fromUtf8("label_maxSc_5"));
gridLayout->addWidget(label_maxSc_5, 7, 5, 1, 2);
pushButton_back = new QPushButton(scrollAreaWidgetContents_4);
pushButton_back->setObjectName(QString::fromUtf8("pushButton_back"));
gridLayout->addWidget(pushButton_back, 12, 0, 1, 1);
label_lose_lv_5 = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv_5->setObjectName(QString::fromUtf8("label_lose_lv_5"));
gridLayout->addWidget(label_lose_lv_5, 7, 1, 1, 2);
label_losedLv9 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv9->setObjectName(QString::fromUtf8("label_losedLv9"));
gridLayout->addWidget(label_losedLv9, 11, 0, 1, 1);
label_losedLv4 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv4->setObjectName(QString::fromUtf8("label_losedLv4"));
gridLayout->addWidget(label_losedLv4, 6, 0, 1, 1);
label_stdDev = new QLabel(scrollAreaWidgetContents_4);
label_stdDev->setObjectName(QString::fromUtf8("label_stdDev"));
gridLayout->addWidget(label_stdDev, 16, 1, 1, 1);
label_pCampaign = new QLabel(scrollAreaWidgetContents_4);
label_pCampaign->setObjectName(QString::fromUtf8("label_pCampaign"));
gridLayout->addWidget(label_pCampaign, 2, 0, 1, 2);
label_maxScore_10 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_10->setObjectName(QString::fromUtf8("label_maxScore_10"));
gridLayout->addWidget(label_maxScore_10, 3, 7, 1, 1);
label_username = new QLabel(scrollAreaWidgetContents_4);
label_username->setObjectName(QString::fromUtf8("label_username"));
gridLayout->addWidget(label_username, 0, 4, 1, 2);
verticalScrollBar = new QScrollBar(scrollAreaWidgetContents_4);
verticalScrollBar->setObjectName(QString::fromUtf8("verticalScrollBar"));
verticalScrollBar->setOrientation(Qt::Vertical);
gridLayout->addWidget(verticalScrollBar, 2, 10, 1, 1);
label_lose_lv_4 = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv_4->setObjectName(QString::fromUtf8("label_lose_lv_4"));
gridLayout->addWidget(label_lose_lv_4, 6, 1, 1, 2);
label_median = new QLabel(scrollAreaWidgetContents_4);
label_median->setObjectName(QString::fromUtf8("label_median"));
gridLayout->addWidget(label_median, 14, 1, 1, 1);
label_confidence = new QLabel(scrollAreaWidgetContents_4);
label_confidence->setObjectName(QString::fromUtf8("label_confidence"));
gridLayout->addWidget(label_confidence, 17, 1, 1, 1);
label_lose_lv_3 = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv_3->setObjectName(QString::fromUtf8("label_lose_lv_3"));
gridLayout->addWidget(label_lose_lv_3, 5, 1, 1, 2);
label_maxSc_3 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_3->setObjectName(QString::fromUtf8("label_maxSc_3"));
gridLayout->addWidget(label_maxSc_3, 5, 5, 1, 2);
label_5 = new QLabel(scrollAreaWidgetContents_4);
label_5->setObjectName(QString::fromUtf8("label_5"));
gridLayout->addWidget(label_5, 15, 0, 1, 1);
label_maxScore_8 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_8->setObjectName(QString::fromUtf8("label_maxScore_8"));
gridLayout->addWidget(label_maxScore_8, 10, 3, 1, 2);
label_maxSc_6 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_6->setObjectName(QString::fromUtf8("label_maxSc_6"));
gridLayout->addWidget(label_maxSc_6, 8, 5, 1, 2);
label_losedLv7 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv7->setObjectName(QString::fromUtf8("label_losedLv7"));
gridLayout->addWidget(label_losedLv7, 9, 0, 1, 1);
label_mean = new QLabel(scrollAreaWidgetContents_4);
label_mean->setObjectName(QString::fromUtf8("label_mean"));
gridLayout->addWidget(label_mean, 13, 1, 1, 1);
label_lose_lv_9 = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv_9->setObjectName(QString::fromUtf8("label_lose_lv_9"));
gridLayout->addWidget(label_lose_lv_9, 11, 1, 1, 2);
label_maxSc_4 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_4->setObjectName(QString::fromUtf8("label_maxSc_4"));
gridLayout->addWidget(label_maxSc_4, 6, 5, 1, 2);
label_7 = new QLabel(scrollAreaWidgetContents_4);
label_7->setObjectName(QString::fromUtf8("label_7"));
gridLayout->addWidget(label_7, 17, 0, 1, 1);
played_campaign = new QLabel(scrollAreaWidgetContents_4);
played_campaign->setObjectName(QString::fromUtf8("played_campaign"));
gridLayout->addWidget(played_campaign, 2, 2, 1, 3);
played_survival = new QLabel(scrollAreaWidgetContents_4);
played_survival->setObjectName(QString::fromUtf8("played_survival"));
gridLayout->addWidget(played_survival, 2, 9, 1, 1);
label_3 = new QLabel(scrollAreaWidgetContents_4);
label_3->setObjectName(QString::fromUtf8("label_3"));
gridLayout->addWidget(label_3, 13, 0, 1, 1);
label_losedLv8 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv8->setObjectName(QString::fromUtf8("label_losedLv8"));
gridLayout->addWidget(label_losedLv8, 10, 0, 1, 1);
label_maxScore_4 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_4->setObjectName(QString::fromUtf8("label_maxScore_4"));
gridLayout->addWidget(label_maxScore_4, 6, 3, 1, 2);
label_maxSc_7 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_7->setObjectName(QString::fromUtf8("label_maxSc_7"));
gridLayout->addWidget(label_maxSc_7, 9, 5, 1, 2);
label_variance = new QLabel(scrollAreaWidgetContents_4);
label_variance->setObjectName(QString::fromUtf8("label_variance"));
gridLayout->addWidget(label_variance, 15, 1, 1, 1);
label_10 = new QLabel(scrollAreaWidgetContents_4);
label_10->setObjectName(QString::fromUtf8("label_10"));
gridLayout->addWidget(label_10, 19, 0, 1, 1);
label_maxScore = new QLabel(scrollAreaWidgetContents_4);
label_maxScore->setObjectName(QString::fromUtf8("label_maxScore"));
gridLayout->addWidget(label_maxScore, 3, 3, 1, 2);
label_pSurvival = new QLabel(scrollAreaWidgetContents_4);
label_pSurvival->setObjectName(QString::fromUtf8("label_pSurvival"));
gridLayout->addWidget(label_pSurvival, 2, 7, 1, 2);
label_maxSc_8 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_8->setObjectName(QString::fromUtf8("label_maxSc_8"));
gridLayout->addWidget(label_maxSc_8, 10, 5, 1, 2);
label_maxSc_9 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_9->setObjectName(QString::fromUtf8("label_maxSc_9"));
gridLayout->addWidget(label_maxSc_9, 11, 5, 1, 2);
label_lose_lv_8 = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv_8->setObjectName(QString::fromUtf8("label_lose_lv_8"));
gridLayout->addWidget(label_lose_lv_8, 10, 1, 1, 2);
label_losedLv3 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv3->setObjectName(QString::fromUtf8("label_losedLv3"));
gridLayout->addWidget(label_losedLv3, 5, 0, 1, 1);
label_4 = new QLabel(scrollAreaWidgetContents_4);
label_4->setObjectName(QString::fromUtf8("label_4"));
gridLayout->addWidget(label_4, 14, 0, 1, 1);
label_maxSc = new QLabel(scrollAreaWidgetContents_4);
label_maxSc->setObjectName(QString::fromUtf8("label_maxSc"));
gridLayout->addWidget(label_maxSc, 3, 5, 1, 2);
label_maxScore_7 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_7->setObjectName(QString::fromUtf8("label_maxScore_7"));
gridLayout->addWidget(label_maxScore_7, 9, 3, 1, 2);
label_losedLv2 = new QLabel(scrollAreaWidgetContents_4);
label_losedLv2->setObjectName(QString::fromUtf8("label_losedLv2"));
gridLayout->addWidget(label_losedLv2, 4, 0, 1, 1);
label_8 = new QLabel(scrollAreaWidgetContents_4);
label_8->setObjectName(QString::fromUtf8("label_8"));
gridLayout->addWidget(label_8, 18, 0, 1, 1);
label_maxScore_5 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_5->setObjectName(QString::fromUtf8("label_maxScore_5"));
gridLayout->addWidget(label_maxScore_5, 7, 3, 1, 2);
label_maxScore_3 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_3->setObjectName(QString::fromUtf8("label_maxScore_3"));
gridLayout->addWidget(label_maxScore_3, 5, 3, 1, 2);
label_lose_lv_7 = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv_7->setObjectName(QString::fromUtf8("label_lose_lv_7"));
gridLayout->addWidget(label_lose_lv_7, 9, 1, 1, 2);
label_maxSc_10 = new QLabel(scrollAreaWidgetContents_4);
label_maxSc_10->setObjectName(QString::fromUtf8("label_maxSc_10"));
gridLayout->addWidget(label_maxSc_10, 3, 8, 1, 1);
label_6 = new QLabel(scrollAreaWidgetContents_4);
label_6->setObjectName(QString::fromUtf8("label_6"));
gridLayout->addWidget(label_6, 16, 0, 1, 1);
label_2 = new QLabel(scrollAreaWidgetContents_4);
label_2->setObjectName(QString::fromUtf8("label_2"));
gridLayout->addWidget(label_2, 0, 1, 1, 3);
label_proportion = new QLabel(scrollAreaWidgetContents_4);
label_proportion->setObjectName(QString::fromUtf8("label_proportion"));
gridLayout->addWidget(label_proportion, 18, 1, 1, 1);
label_lose_lv_6 = new QLabel(scrollAreaWidgetContents_4);
label_lose_lv_6->setObjectName(QString::fromUtf8("label_lose_lv_6"));
gridLayout->addWidget(label_lose_lv_6, 8, 1, 1, 2);
label_maxScore_6 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_6->setObjectName(QString::fromUtf8("label_maxScore_6"));
gridLayout->addWidget(label_maxScore_6, 8, 3, 1, 2);
label_maxScore_2 = new QLabel(scrollAreaWidgetContents_4);
label_maxScore_2->setObjectName(QString::fromUtf8("label_maxScore_2"));
gridLayout->addWidget(label_maxScore_2, 4, 3, 1, 2);
label_email = new QLabel(scrollAreaWidgetContents_4);
label_email->setObjectName(QString::fromUtf8("label_email"));
gridLayout->addWidget(label_email, 1, 1, 1, 1);
scrollArea->setWidget(scrollAreaWidgetContents_4);
retranslateUi(Stats);
QMetaObject::connectSlotsByName(Stats);
} // setupUi
void retranslateUi(QDialog *Stats)
{
Stats->setWindowTitle(QCoreApplication::translate("Stats", "Dialog", nullptr));
label_lose_lv_2->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_maxSc_2->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_maxScore_9->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_lose_lv->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_losedLv5->setText(QCoreApplication::translate("Stats", "total losed in Lv5:", nullptr));
label_losedLv1->setText(QCoreApplication::translate("Stats", "total losed in Lv1:", nullptr));
label_losedLv6->setText(QCoreApplication::translate("Stats", "total losed in Lv6:", nullptr));
label_maxSc_5->setText(QCoreApplication::translate("Stats", "0", nullptr));
pushButton_back->setText(QCoreApplication::translate("Stats", "back", nullptr));
label_lose_lv_5->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_losedLv9->setText(QCoreApplication::translate("Stats", "total losed in Lv9:", nullptr));
label_losedLv4->setText(QCoreApplication::translate("Stats", "total losed in Lv4:", nullptr));
label_stdDev->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_pCampaign->setText(QCoreApplication::translate("Stats", "total played in campaign:", nullptr));
label_maxScore_10->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_username->setText(QCoreApplication::translate("Stats", "None", nullptr));
label_lose_lv_4->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_median->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_confidence->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_lose_lv_3->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_maxSc_3->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_5->setText(QCoreApplication::translate("Stats", "Variance:", nullptr));
label_maxScore_8->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_maxSc_6->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_losedLv7->setText(QCoreApplication::translate("Stats", "total losed in Lv7:", nullptr));
label_mean->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_lose_lv_9->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_maxSc_4->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_7->setText(QCoreApplication::translate("Stats", "confidence interv:", nullptr));
played_campaign->setText(QCoreApplication::translate("Stats", "0", nullptr));
played_survival->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_3->setText(QCoreApplication::translate("Stats", "Sample mean:", nullptr));
label_losedLv8->setText(QCoreApplication::translate("Stats", "total losed in Lv8:", nullptr));
label_maxScore_4->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_maxSc_7->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_variance->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_10->setText(QString());
label_maxScore->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_pSurvival->setText(QCoreApplication::translate("Stats", "total played in survival:", nullptr));
label_maxSc_8->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_maxSc_9->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_lose_lv_8->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_losedLv3->setText(QCoreApplication::translate("Stats", "total losed in Lv3:", nullptr));
label_4->setText(QCoreApplication::translate("Stats", "Median:", nullptr));
label_maxSc->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_maxScore_7->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_losedLv2->setText(QCoreApplication::translate("Stats", "total losed in Lv2:", nullptr));
label_8->setText(QCoreApplication::translate("Stats", "proportion:", nullptr));
label_maxScore_5->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_maxScore_3->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_lose_lv_7->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_maxSc_10->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_6->setText(QCoreApplication::translate("Stats", "Std deviation:", nullptr));
label_2->setText(QCoreApplication::translate("Stats", "Stats of the player", nullptr));
label_proportion->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_lose_lv_6->setText(QCoreApplication::translate("Stats", "0", nullptr));
label_maxScore_6->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_maxScore_2->setText(QCoreApplication::translate("Stats", "maxScore:", nullptr));
label_email->setText(QCoreApplication::translate("Stats", "none", nullptr));
} // retranslateUi
};
namespace Ui {
class Stats: public Ui_Stats {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_STATS_H
|
/*
* DISK READ/WRITE MONITOR
* diskrw version 0.1
*/
#include <windows.h>
#include <pdh.h>
#include "resource.h"
// conf
#define WCLSNAME TEXT( "disk read/write" )
#define WTITLE NULL
#define MYWM_NOTIFYICON (WM_APP + 17)
#define TM_INTERVAL 500 // time-out value, in milliseconds
#define TIPS TEXT( "Disk Access Lamp Ver 0.1" )
#define MSG_TITLE WCLSNAME
typedef enum {
RW_ERR = -1, RW_NONE = 0, RW_READ, RW_WRITE, RW_BOTH, RW_ERROR, RW_MAX
} rw_stat_t;
// BSS
HINSTANCE HInstance;
UINT TimerId;
HICON HIcons[RW_MAX];
// pdh
HQUERY hQueryRead;
HCOUNTER hCounterRead;
HQUERY hQueryWrite;
HCOUNTER hCounterWrite;
//
// -- REPORT -------------------------------------------------------
//
void REPORT( TCHAR * format, ... ) {
TCHAR buf[1024];
va_list args;
va_start( args, format );
wvsprintf( buf, format, args );
MessageBox( NULL, buf, TEXT( "message" ), MB_OK | MB_ICONINFORMATION );
va_end( args );
}
/*
* -- load icon ------------------------------------------------------
*/
BOOL makeIcon( HWND hWnd ) {
UNREFERENCED_PARAMETER( hWnd );
HIcons[RW_NONE] = LoadIcon( HInstance, MAKEINTRESOURCE( IDI_NOACCESS ) );
HIcons[RW_READ] = LoadIcon( HInstance, MAKEINTRESOURCE( IDI_READONLY ) );
HIcons[RW_WRITE] = LoadIcon( HInstance, MAKEINTRESOURCE( IDI_WRITEDONLY ) );
HIcons[RW_BOTH] = LoadIcon( HInstance, MAKEINTRESOURCE( IDI_READWRITED ) );
HIcons[RW_ERROR] = LoadIcon( HInstance, MAKEINTRESOURCE( IDI_SOMEERROR ) );
if ( NULL == HIcons[RW_NONE] || NULL == HIcons[RW_READ]
|| NULL == HIcons[RW_WRITE] || NULL == HIcons[RW_BOTH]
|| NULL == HIcons[RW_ERROR]
) {
return FALSE;
}
return TRUE;
}
VOID deleteIcon( VOID ) {
}
/*
* -- pdh ------------------------------------------------------------
*/
BOOL pdh_init( VOID ) {
PDH_STATUS stat;
LPCTSTR szPathRead = TEXT( "\\PhysicalDisk(_Total)\\% Disk Read Time" );
LPCTSTR szPathWrite = TEXT( "\\PhysicalDisk(_Total)\\% Disk Write Time" );
stat = PdhOpenQuery( NULL, 0, &hQueryRead );
if ( ERROR_SUCCESS != stat ) {
goto stage1;
}
stat = PdhAddCounter( hQueryRead, szPathRead, 0, &hCounterRead );
if ( ERROR_SUCCESS != stat ) {
goto stage2;
}
stat = PdhOpenQuery( NULL, 0, &hQueryWrite );
if ( ERROR_SUCCESS != stat ) {
goto stage3;
}
stat = PdhAddCounter( hQueryWrite, szPathWrite, 0, &hCounterWrite );
if ( ERROR_SUCCESS != stat ) {
goto stage4;
}
return TRUE;
stage4:
PdhCloseQuery( hQueryWrite );
stage3:
stage2:
PdhCloseQuery( hQueryRead );
stage1:
return FALSE;
}
VOID pdh_settle( VOID ) {
PdhCloseQuery( hQueryWrite );
PdhCloseQuery( hQueryRead );
}
rw_stat_t getstat( VOID ) {
PDH_FMT_COUNTERVALUE cvRead;
PDH_FMT_COUNTERVALUE cvWrite;
PDH_STATUS stat;
stat = PdhCollectQueryData( hQueryRead );
if ( ERROR_SUCCESS != stat ) return RW_ERROR;
stat = PdhGetFormattedCounterValue(
hCounterRead, PDH_FMT_LONG, NULL, &cvRead
);
if ( ERROR_SUCCESS != stat ) return RW_ERROR;
stat = PdhCollectQueryData( hQueryWrite );
if ( ERROR_SUCCESS != stat ) return RW_ERROR;
stat = PdhGetFormattedCounterValue(
hCounterWrite, PDH_FMT_LONG, NULL, &cvWrite
);
if ( ERROR_SUCCESS != stat ) return RW_ERROR;
if ( 0 < cvRead.longValue && 0 < cvWrite.longValue ) return RW_BOTH;
if ( 0 < cvRead.longValue ) return RW_READ;
if ( 0 < cvWrite.longValue ) return RW_WRITE;
return RW_NONE;
}
/*
* -- Timer ----------------------------------------------------------
*/
VOID starttimer( HWND hWnd ) {
TimerId = SetTimer( hWnd, GetCurrentProcessId(), TM_INTERVAL, NULL );
if ( 0 == TimerId ) {
REPORT( TEXT( "ERROR: SetTimer()" ) );
SendMessage( hWnd, WM_DESTROY, 0, 0 );
}
}
VOID stoptimer( HWND hWnd ) {
KillTimer( hWnd, TimerId );
}
/*
* -- Task Tray ------------------------------------------------------
*/
VOID staytray( HWND hWnd ) {
NOTIFYICONDATA notifyicondata;
notifyicondata.cbSize = sizeof( notifyicondata );
notifyicondata.hWnd = hWnd;
notifyicondata.uID = GetCurrentProcessId();
notifyicondata.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
notifyicondata.uCallbackMessage = MYWM_NOTIFYICON;
notifyicondata.hIcon = HIcons[RW_NONE];
lstrcpyn(
notifyicondata.szTip
, TIPS
, sizeof( notifyicondata.szTip )
);
BOOL b = Shell_NotifyIcon( NIM_ADD, ¬ifyicondata );
if ( 0 == b ) {
REPORT( TEXT( "ERROR: Shell_NotifyIcon( NIM_ADD )" ) );
SendMessage( hWnd, WM_DESTROY, 0, 0 );
}
}
VOID removetray( HWND hWnd ) {
NOTIFYICONDATA notifyicondata;
notifyicondata.cbSize = sizeof( notifyicondata );
notifyicondata.hWnd = hWnd;
notifyicondata.uID = GetCurrentProcessId();
notifyicondata.uFlags = 0;
Shell_NotifyIcon( NIM_DELETE, ¬ifyicondata );
}
VOID updatetray( HWND hWnd ) {
static rw_stat_t prev_stat = RW_NONE;
rw_stat_t stat;
NOTIFYICONDATA notifyicondata;
stat = getstat();
/*
if ( RW_ERR == stat ) {
SendMessage( hWnd, WM_DESTROY, 0, 0 );
return;
}
*/
if ( prev_stat == stat ) {
return;
}
notifyicondata.cbSize = sizeof( notifyicondata );
notifyicondata.hWnd = hWnd;
notifyicondata.uID = GetCurrentProcessId();
notifyicondata.uFlags = NIF_ICON;
notifyicondata.hIcon = HIcons[stat];
BOOL b = Shell_NotifyIcon( NIM_MODIFY, ¬ifyicondata );
if ( 0 != b ) {
prev_stat = stat;
}
}
/*
* -- Timer Handler --------------------------------------------------
*/
VOID updateview( HWND hWnd ) {
updatetray( hWnd );
}
/*
* -- Popup Menu -----------------------------------------------------
*/
VOID showpopupmenu( HWND hWnd ) {
HMENU hMenu;
HMENU hSubMenu;
POINT pt;
if ( FALSE == SetForegroundWindow( hWnd ) ) {
MessageBox( hWnd, TEXT( "ERROR: SetForegroundWindow" ), MSG_TITLE, MB_OK );
return;
}
hMenu = LoadMenu( HInstance, MAKEINTRESOURCE( IDM_POPUPMENU ) );
if ( NULL == hMenu ) {
MessageBox( hWnd, TEXT( "ERROR:Load Menu" ), MSG_TITLE, MB_OK );
return;
}
hSubMenu = GetSubMenu( hMenu, 0 );
if ( NULL == hSubMenu ) {
MessageBox( hWnd, TEXT( "ERROR:Load Popup Menu" ), MSG_TITLE, MB_OK );
DestroyMenu( hMenu );
return;
}
GetCursorPos( &pt );
TrackPopupMenu(
hSubMenu
, TPM_CENTERALIGN
, pt.x
, pt.y
, 0
, hWnd
, NULL
);
DestroyMenu( hSubMenu );
DestroyMenu( hMenu );
}
/*
* -- Main Process ---------------------------------------------------
*/
VOID hidewindow( HWND hWnd ) {
ShowWindow( hWnd, SW_HIDE );
}
/*
* -- Main Handle ----------------------------------------------------
*/
LRESULT CALLBACK WindowProcedure (
HWND hwnd
, UINT message
, WPARAM wParam
, LPARAM lParam
) {
switch ( message ) {
case WM_CREATE:
if ( FALSE == makeIcon( hwnd ) ) {
REPORT( TEXT( "FAIL: WM_CREATE: makeIcon()" ));
SendMessage( hwnd, WM_DESTROY, 0, 0 );
}
if ( FALSE == pdh_init() ) {
REPORT( TEXT( "FAIL: WM_CREATE: pdh_init()" ));
SendMessage( hwnd, WM_DESTROY, 0, 0 );
}
staytray( hwnd );
starttimer( hwnd );
break;
case WM_DESTROY :
stoptimer( hwnd );
removetray( hwnd );
pdh_settle();
deleteIcon();
PostQuitMessage( 0 );
break;
case WM_PAINT:
if ( IsWindowVisible( hwnd ) ) {
hidewindow( hwnd );
}
break;
case WM_TIMER :
if ( TimerId == wParam ) {
updateview( hwnd );
}
break;
case WM_COMMAND :
switch ( LOWORD( wParam ) ) {
case IDM_POPUP_CLOSE :
SendMessage( hwnd, WM_DESTROY, 0, 0 );
break;
}
break;
case MYWM_NOTIFYICON :
if ( WM_RBUTTONUP == lParam ) {
showpopupmenu( hwnd );
}
break;
default:
break;
}
return DefWindowProc( hwnd, message, wParam, lParam );
}
/*
* -- Main Entry ------------------------------------------------------
*/
int WINAPI WinMain(
HINSTANCE hThisInstance
, HINSTANCE hPrevInstance
, LPSTR lpCmdLine
, int nCmdShow
) {
UNREFERENCED_PARAMETER( hPrevInstance );
UNREFERENCED_PARAMETER( lpCmdLine );
UNREFERENCED_PARAMETER( nCmdShow );
HWND hwnd;
MSG messages;
WNDCLASSEX wincl;
HInstance = hThisInstance;
wincl.hInstance = hThisInstance;
wincl.lpszClassName = WCLSNAME;
wincl.lpfnWndProc = WindowProcedure;
wincl.style = CS_DBLCLKS;
wincl.cbSize = sizeof( WNDCLASSEX );
wincl.hIcon = LoadIcon( hThisInstance, MAKEINTRESOURCE( IDI_MAINWINDOW ) );
wincl.hIconSm = LoadIcon( NULL, IDI_APPLICATION );
wincl.hCursor = LoadCursor( NULL, IDC_ARROW );
wincl.lpszMenuName = NULL;
wincl.cbClsExtra = 0;
wincl.cbWndExtra = 0;
wincl.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
if( !RegisterClassEx( &wincl ) ) {
REPORT( TEXT( "FAIL: RegisterClassEx()" ));
return EXIT_FAILURE;
}
hwnd = CreateWindowEx(
0
, WCLSNAME
, WTITLE
, WS_OVERLAPPEDWINDOW
, 0
, 0
, 0
, 0
, NULL
, NULL
, hThisInstance
, NULL
);
if ( NULL == hwnd ) {
REPORT( TEXT( "ERROR: CreateWindowEx()" ) );
return EXIT_FAILURE;
}
// ShowWindow( hwnd, nFunsterStil );
while ( GetMessage( &messages, NULL, 0, 0 ) ) {
TranslateMessage( &messages );
DispatchMessage( &messages );
}
return messages.wParam;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author karie
*
*/
#include "core/pch.h"
#include "adjunct/quick/controller/BookmarkPropertiesController.h"
#include "adjunct/quick/managers/DesktopBookmarkManager.h"
#include "adjunct/quick/dialogs/BookmarkDialog.h"
#include "adjunct/quick/managers/CommandLineManager.h"
#include "adjunct/quick/managers/DesktopClipboardManager.h"
#include "adjunct/quick/managers/RedirectionManager.h"
#include "adjunct/quick/managers/SyncManager.h"
#include "adjunct/quick/hotlist/HotlistManager.h"
#include "adjunct/quick/hotlist/HotlistModel.h"
#include "adjunct/quick/hotlist/hotlistparser.h"
#include "adjunct/desktop_pi/DesktopOpSystemInfo.h"
#include "adjunct/desktop_util/resources/ResourceSetup.h"
#include "modules/bookmarks/bookmark_manager.h"
#include "modules/bookmarks/bookmark_sync.h"
#include "modules/bookmarks/bookmark_ini_storage.h"
#include "modules/prefs/prefsmanager/collections/pc_sync.h"
#include "adjunct/quick/models/BookmarkAdrStorage.h"
// from HotlistManager
extern void ReplaceIllegalSinglelineText( OpString& text );
DesktopBookmarkManager::~DesktopBookmarkManager()
{
if (m_model)
{
m_model->RemoveModelListener(this);
}
OP_DELETE(m_clipboard);
// note that if a operation is pending SetStorageProvider refuse to do anything.
// so we cancel pending operation first so that bookmark manager won't try to use deleted storage provider later
g_bookmark_manager->CancelPendingOperation();
g_bookmark_manager->SetStorageProvider(NULL);
}
OP_STATUS DesktopBookmarkManager::SaveDirtyModelToDisk()
{
// nothing to save if the model is not dirty
if (!m_model || !m_model->IsDirty())
return OpStatus::OK;
// model could be dirty before it actually finish loading
// e.g. Bookmark::OnHistoryItemAccessed change the visited time attribute
// but don't try to save in this case
if (!m_model->Loaded())
return OpStatus::ERR_YIELD;
// the bookmarks file path for the error dialog
OpFile hotlistfile;
OpString hotlistfile_path;
RETURN_IF_LEAVE(g_pcfiles->GetFileL(PrefsCollectionFiles::HotListFile, hotlistfile));
RETURN_IF_ERROR(hotlistfile_path.Set(hotlistfile.GetFullPath()));
OP_STATUS save_result;
// loop until the file is saved without errors, or the user decides that he's ok
// for example, if the file is on a removable drive, he can try to reconnect it
do
{
save_result = g_bookmark_manager->SaveImmediately();
}
while (OpStatus::IsError(save_result) && g_hotlist_manager->ShowSavingFailureDialog(hotlistfile_path));
return save_result;
}
/*************************************************************************
*
* BookmarkInit
*
* Starts loading of bookmarks file
*
* Upgrade default bookmarks
*
*************************************************************************/
OP_STATUS DesktopBookmarkManager::Init()
{
m_edit_folder_tree_view = NULL;
m_clipboard = OP_NEW(BookmarkClipboard, ());
if (!m_clipboard)
return OpStatus::ERR_NO_MEMORY;
m_clipboard->Init();
OP_ASSERT(g_bookmark_manager);
m_model = g_hotlist_manager->GetBookmarksModel();
m_model->AddModelListener(this);
// Bookmarks will be loaded into model when OpBootManager gets
// name of user's region. This may be delayed for a few seconds
// if Opera needs to contact the autoupdate server to get IP-based
// country code (DSK-351304).
#ifdef DEBUG_ENABLE_OPASSERT
m_broadcasting_loaded = FALSE;
#endif // DEBUG_ENABLE_OPASSERT
return OpStatus::OK;
}
OP_STATUS DesktopBookmarkManager::Load(bool copy_default_bookmarks)
{
if (copy_default_bookmarks)
{
OpFile hotlistfile;
RETURN_IF_LEAVE(g_pcfiles->GetFileL(PrefsCollectionFiles::HotListFile, hotlistfile));
BOOL exists;
if (OpStatus::IsSuccess(hotlistfile.Exists(exists)) && !exists)
{
// Provide initital content of bookmarks.adr file.
// 1. If another instance of Opera is set as default browser and its bookmarks store uses
// adr format then copy it. Partner bookmarks will be updated when model is loaded.
// 2. Otherwise copy bookmarks.adr file for current region/language from package.
// Bookmarks from the default browser will be imported after model is loaded.
// Model will contain current partner bookmarks, so no update in this case.
if (!g_pcui->GetIntegerPref(PrefsCollectionUI::DisableBookmarkImport) &&
!g_commandline_manager->GetArgument(CommandLineManager::WatirTest)) // DSK-361259
{
DesktopOpSystemInfo* system_info = static_cast<DesktopOpSystemInfo*>(g_op_system_info);
DesktopOpSystemInfo::DefaultBrowser default_browser = system_info->GetDefaultBrowser();
switch (default_browser)
{
case DesktopOpSystemInfo::DEFAULT_BROWSER_OPERA:
m_import_format = HotlistModel::OperaBookmark; // import now
break;
case DesktopOpSystemInfo::DEFAULT_BROWSER_FIREFOX:
m_import_format = HotlistModel::NetscapeBookmark; // will be imported after model is loaded
break;
case DesktopOpSystemInfo::DEFAULT_BROWSER_IE:
m_import_format = HotlistModel::ExplorerBookmark; // will be imported after model is loaded
break;
default:
m_import_format = HotlistModel::NoFormat;
break;
}
if (m_import_format != HotlistModel::NoFormat)
{
if (OpStatus::IsError(system_info->GetDefaultBrowserBookmarkLocation(default_browser, m_import_path)) ||
m_import_path.IsEmpty())
{
m_import_format = HotlistModel::NoFormat;
}
}
if (m_import_format == HotlistModel::OperaBookmark)
{
OpFile srcfile;
if (!IsIniFile(m_import_path) &&
OpStatus::IsSuccess(srcfile.Construct(m_import_path)) &&
OpStatus::IsSuccess(hotlistfile.CopyContents(&srcfile, FALSE)))
{
copy_default_bookmarks = false;
// leave m_import_format set - this will trigger upgrade
// of partner bookmarks after model is loaded
}
else
{
m_import_format = HotlistModel::NoFormat;
}
// no longer needed
m_import_path.Empty();
}
}
if (copy_default_bookmarks)
{
OpFile srcfile;
if (OpStatus::IsSuccess(ResourceSetup::GetDefaultPrefsFile(DESKTOP_RES_PACKAGE_BOOKMARK, srcfile)))
{
OpStatus::Ignore(hotlistfile.CopyContents(&srcfile, FALSE));
}
}
}
}
return m_model->Init();
}
/************************************************************************
*
* DropItem
*
*
************************************************************************/
BOOL DesktopBookmarkManager::DropItem(const BookmarkItemData& item_data,
INT32 onto,
DesktopDragObject::InsertType insert_type,
BOOL execute,
OpTypedObject::Type drag_object_type,
INT32* first_id)
{
if (!m_model->Loaded()) // DSK-351304
return FALSE;
if( execute )
{
HotlistModelItem* to = GetItemByID(onto);
CoreBookmarkPos pos(to, insert_type);
AddBookmark(&item_data, pos.Previous(), pos.Parent());
}
return TRUE;
}
OP_STATUS DesktopBookmarkManager::EditItem(INT32 id, DesktopWindow* parent)
{
HotlistModelItem* item = m_model->GetItemByID(id);
RETURN_VALUE_IF_NULL(item, OpStatus::ERR_NULL_POINTER);
if (!item->IsFolder())
{
BookmarkPropertiesController* controller = OP_NEW(BookmarkPropertiesController, (item));
RETURN_OOM_IF_NULL(controller);
RETURN_IF_ERROR(ShowDialog(controller, g_global_ui_context, parent));
}
else
{
EditBookmarkDialog* dialog = OP_NEW(EditBookmarkDialog, (TRUE));
RETURN_OOM_IF_NULL(dialog);
RETURN_IF_ERROR(dialog->Init(parent, item));
}
return OpStatus::OK;
}
BOOL DesktopBookmarkManager::NewBookmark( const HotlistManager::ContactData& cd, INT32 parent_id, DesktopWindow* parent, BOOL interactive )
{
BookmarkItemData item_data;
item_data.name.Set(cd.name.CStr());
item_data.url.Set(cd.url.CStr());
item_data.panel_position = cd.in_panel ? 0 : -1;
return NewBookmark(item_data, parent_id, parent, interactive );
}
BOOL DesktopBookmarkManager::NewBookmark( INT32 parent_id, DesktopWindow* parent_window )
{
BookmarkItemData item_data;
return NewBookmark(item_data, parent_id, parent_window, TRUE);
}
BOOL DesktopBookmarkManager::NewBookmark( BookmarkItemData& item_data, INT32 parent_id )
{
return NewBookmark(item_data, parent_id, 0, FALSE);
}
/************************************************************************
*
* NewBookmark
*
************************************************************************/
BOOL DesktopBookmarkManager::NewBookmark( BookmarkItemData& item_data, INT32 parent_id, DesktopWindow* parent_window, BOOL interactive )
{
// trying to add new bookmark before loading bookmarks.adr?
OP_ASSERT(m_model->Loaded());
HotlistModelItem* parent = m_model->GetItemByID(parent_id);
if(interactive)
{
HotlistModelItem* item = m_model->GetByURL(item_data.url.CStr(), FALSE);
// Check for duplicate
if (item && !item->GetIsInsideTrashFolder())
{
EditBookmarkDialog* dialog = OP_NEW(EditBookmarkDialog, (TRUE));
if (dialog)
dialog->Init(parent_window, item);
}
else
{
AddBookmarkDialog* dialog = OP_NEW(AddBookmarkDialog, ());
if (dialog)
dialog->Init( parent_window, &item_data, parent);
}
}
else
{
// Since we do not use a dialog we fill in the url address as name.
if( !item_data.name.HasContent() )
{
item_data.name.Set(item_data.url);
}
AddBookmarkLast(&item_data, GetItemByID(parent_id));
}
return TRUE;
}
BOOL DesktopBookmarkManager::NewSeparator(INT32 parent_id)
{
// trying to add new separator before loading bookmarks.adr?
OP_ASSERT(m_model->Loaded());
BookmarkItem* separator = OP_NEW(BookmarkItem, ());
if (!separator)
return FALSE;
CoreBookmarkPos pos(GetItemByID(parent_id), DesktopDragObject::INSERT_INTO);
return OpStatus::IsSuccess(g_bookmark_manager->AddSeparator(separator, pos.previous, pos.parent));
}
/************************************************************************
*
* NewBookmarkFolder
*
*
************************************************************************/
BOOL DesktopBookmarkManager::NewBookmarkFolder(const OpStringC& name, INT32 parent_id, OpTreeView* treeView )
{
// trying to add new folder before loading bookmarks.adr?
OP_ASSERT(m_model->Loaded());
m_edit_folder_tree_view = treeView;
HotlistModelItem* parent_folder = GetItemByID( parent_id );
BookmarkItemData item_data;
item_data.name.Set(name);
item_data.type = FOLDER_NORMAL_FOLDER;
AddBookmarkLast(&item_data, parent_folder);
// Make sure treeview isn't matching text, to prevent the newly created item
// being invisible
if (treeView)
OpStatus::Ignore(treeView->SetText(0));
return TRUE;
}
/************************************************************************
*
* Rename
*
*
************************************************************************/
BOOL DesktopBookmarkManager::Rename( OpTreeModelItem *item, OpString& text )
{
if (!item) return FALSE;
HotlistModelItem* bookmark = static_cast<HotlistModelItem*>(item);
bookmark->SetName( text.CStr() );
return TRUE;
}
/************************************************************************
*
* CopyItems
*
* Copy all items to clipboard
*
************************************************************************/
void DesktopBookmarkManager::CopyItems(OpINT32Vector& id_list, BOOL handle_target_folder ) // Duh. Change name
{
OpString global_clipboard_text;
INT32 count = id_list.GetCount();
if (count > 0)
GetClipboard()->Clear();
for (INT32 i = 0; i < count; i++)
{
// The easiest way to do this is if the id_list only contains top level items
// and copying one means do the whole tree,
// -- NO, there can be holes in the list
HotlistModelItem* bookmark = GetItemByID(id_list.Get(i));
if(bookmark && !bookmark->GetIsTrashFolder())
{
if (!handle_target_folder && bookmark->GetTarget().HasContent())
continue;
// If this is the first in the list. clipboard should be cleared
// then this item should be added first (addlast)
// OBS: This must add a copy of the item !!
GetClipboard()->CopyItem(GetClipboard()->m_manager,BookmarkWrapper(bookmark)->GetCoreItem());
// If this is not the first in the list, the item should be added relative
// to its core parent and previous -
// the parent is not necessarily relevant if it's not also copied
// the previous is neccessarily there
// m_clipboard->AddNewItem(bookmark); // Add single, or relative to its parent and previous? Make two func.s for this!
OpInfoText text;
text.SetAutoTruncate(FALSE);
bookmark->GetInfoText(text);
if (text.HasStatusText())
{
if (global_clipboard_text.HasContent())
{
global_clipboard_text.Append(UNI_L("\n"));
}
global_clipboard_text.Append(text.GetStatusText().CStr());
}
}
}
if (global_clipboard_text.HasContent())
{
g_desktop_clipboard_manager->PlaceText(global_clipboard_text.CStr(), g_application->GetClipboardToken());
#if defined(_X11_SELECTION_POLICY_)
// Mouse selection
g_desktop_clipboard_manager->PlaceText(global_clipboard_text.CStr(), g_application->GetClipboardToken(), true);
#endif
}
}
/************************************************************************
*
* Delete
*
*
************************************************************************/
void DesktopBookmarkManager::Delete(OpINT32Vector& id_list, BOOL real_delete, BOOL handle_target_folder)
{
OpINT32Vector target_folders;
// the lock will update the whole tree in EndChange, which
// make it even slower when operating small amount of items
BOOL use_model_lock = id_list.GetCount() > 50;
if (use_model_lock)
m_model->BeginChange();
for(UINT32 i = 0; i < id_list.GetCount(); i++)
{
HotlistModelItem* item = m_model->GetItemByID(id_list.Get(i));
// item might has been deleted when it's parent folder got deleted
if(item)
{
// If they don't want to delete just stop.
if (item->GetTarget().HasContent())
{
// currently the tree view model is not in sync with the BookmarkModel,
// don't do any UI stuff here, showing a dialog will run a message loop
// and possibly paint the tree view thus crash!
target_folders.Add(id_list.Get(i));
}
else
m_model->DeleteItem(item, real_delete);
}
}
if (use_model_lock)
m_model->EndChange();
for(UINT32 i = 0; i < target_folders.GetCount(); i++)
{
HotlistModelItem* item = m_model->GetItemByID(target_folders.Get(i));
if (handle_target_folder && g_hotlist_manager->ShowTargetDeleteDialog(item))
{
m_model->DeleteItem(item, TRUE);
}
}
}
/************************************************************************
*
* CutItems
*
*
************************************************************************/
// OBS, TODO: Need a way to not delete the item when it is removed from core list of bookmarks?
void DesktopBookmarkManager::CutItems(OpINT32Vector& id_list)
{
// OBS: TODO: This should be changed to just move the items over to the clipboard, instead of copying
// But then it must still remove the wrappers from the quick model
CopyItems(id_list, FALSE);
Delete(id_list, TRUE, FALSE);
}
OP_STATUS DesktopBookmarkManager::PasteItems(HotlistModelItem* at, DesktopDragObject::InsertType insert_type)
{
FolderModelItem* max_item_parent = at ? at->GetIsInMaxItemsFolder() : NULL;
if(max_item_parent && max_item_parent->GetMaximumItemReached(GetClipboard()->GetCount()))
{
g_hotlist_manager->ShowMaximumReachedDialog(max_item_parent);
return OpStatus::ERR;
}
return GetClipboard()->PasteToModel(*m_model, at, insert_type);
}
/************************************************************************
*
* GetItemValue
*
*
************************************************************************/
BOOL DesktopBookmarkManager::GetItemValue( OpTreeModelItem* item, BookmarkItemData& data/*, INT32& flag_changed*/ )
{
HotlistModelItem* hmi = static_cast<HotlistModelItem*>(item);
if( !hmi)
{
return FALSE;
}
OpString tmp;
data.name.Set(hmi->GetName());
if (!hmi->IsFolder())
data.url.Set( hmi->GetUrl() );
data.image.Set( hmi->GetImage() );
data.description.Set( hmi->GetDescription() );
data.shortname.Set( hmi->GetShortName() );
data.created.Set( hmi->GetCreatedString() );
if (!hmi->IsFolder() )
data.visited.Set( hmi->GetVisitedString() );
data.direct_image_pointer = hmi->GetImage();
INT32 pos = hmi->GetPersonalbarPos();
data.personalbar_position = pos;
if (!hmi->IsFolder())
{
pos = ((Bookmark*)hmi)->GetPanelPos();
data.panel_position = pos;
}
if (hmi->GetHasDisplayUrl())
data.display_url.Set(hmi->GetDisplayUrl());
return TRUE;
}
/************************************************************************
*
* SetItemValue
*
*
************************************************************************/
BOOL DesktopBookmarkManager::SetItemValue( OpTreeModelItem *item, const BookmarkItemData& data, BOOL validate, UINT32 flag_changed )
{
HotlistModelItem* hmi = static_cast<HotlistModelItem*>(item); // ??
if( !hmi )
{
return FALSE;
}
if ( flag_changed & HotlistModel::FLAG_NAME )
{
hmi->SetName( data.name.CStr() );
}
if( !hmi->IsFolder() && (flag_changed & HotlistModel::FLAG_URL))
{
if (hmi->GetUrl().Compare(data.url.CStr()) != 0)
{
hmi->SetUrl(data.url.CStr());
// Reset the Partner ID and Display URL when user changed the url
AddDeletedDefaultBookmark(hmi->GetPartnerID());
hmi->SetPartnerID(NULL);
hmi->SetDisplayUrl(NULL);
}
}
if ( flag_changed & HotlistModel::FLAG_DESCRIPTION )
{
hmi->SetDescription( data.description.CStr() );
}
if ( flag_changed & HotlistModel::FLAG_NICK )
{
if ( validate )
{
OpString tmp;
tmp.Set( data.shortname );
ReplaceIllegalSinglelineText( tmp );
hmi->SetShortName( tmp.CStr());
}
else
{
hmi->SetShortName( data.shortname.CStr() );
}
}
if ( flag_changed & HotlistModel::FLAG_PERSONALBAR )
{
hmi->SetPersonalbarPos( data.personalbar_position );
}
if ( flag_changed & HotlistModel::FLAG_PANEL )
{
hmi->SetPanelPos( data.panel_position );
}
if ( flag_changed & HotlistModel::FLAG_SMALLSCREEN )
{
hmi->SetSmallScreen( data.small_screen );
}
hmi->GetModel()->SetDirty( TRUE );
hmi->Change( TRUE );
g_bookmark_manager->SetSaveTimer();
hmi->GetModel()->BroadcastHotlistItemChanged(hmi, FALSE, flag_changed);
return TRUE;
}
void DesktopBookmarkManager::ClearSensitiveSettings(int flag, BOOL always_write_to_disk)
{
BOOL changed = always_write_to_disk;
for( INT32 i=0; i<m_model->GetCount(); i++ )
{
HotlistModelItem* bm = m_model->GetItemByIndex(i);
if( bm )
{
BOOL item_changed = FALSE;
if( flag & VisitedTime )
{
item_changed |= bm->ClearVisited();
changed |= item_changed;
}
if( flag & CreatedTime )
{
item_changed |= bm->ClearCreated();
changed |= item_changed;
}
if( item_changed )
{
m_model->BroadcastHotlistItemChanged(bm, HotlistModel::FLAG_CREATED | HotlistModel::FLAG_VISITED);
m_model->Change(i, FALSE);
}
}
}
if( changed )
{
m_model->SetDirty( TRUE );
}
}
void DesktopBookmarkManager::OnHotlistItemAdded(HotlistModelItem* item)
{
if(m_edit_folder_tree_view && item->IsFolder())
{
INT32 pos = m_edit_folder_tree_view->GetItemByModelItem(item);
m_edit_folder_tree_view->EditItem(pos);
m_edit_folder_tree_view = NULL;
}
// Remember the partner bookmarks in user profile
if (item->GetPartnerID().HasContent() && !FindDefaultBookmark(item->GetPartnerID()))
m_default_bookmarks.Add(item->GetID());
if (item->GetDisplayUrl().HasContent() && item->GetDisplayUrl().Compare(item->GetUrl()) != 0)
m_default_bookmarks_with_display_url.Add(item->GetID());
}
void DesktopBookmarkManager::OnHotlistItemRemoved(HotlistModelItem* item, BOOL removed_as_child)
{
// When a default bookmark is deleted add it to the black list to prevent
// bringing it back when upgrading
if (item->GetPartnerID().HasContent() && item->IsBookmark())
AddDeletedDefaultBookmark(item->GetPartnerID());
m_default_bookmarks.RemoveByItem(item->GetID());
m_default_bookmarks_with_display_url.RemoveByItem(item->GetID());
}
void DesktopBookmarkManager::BroadcastBookmarkLoaded()
{
CreateTrashFolderIfNeeded();
UpgradeDefaultBookmarks();
g_hotlist_manager->ImportCustomFileOnce();
if (m_import_path.HasContent())
{
if (m_import_format != HotlistModel::OperaBookmark) // OperaBookmark is handled in Load
{
OP_ASSERT(m_import_format != HotlistModel::NoFormat);
g_hotlist_manager->Import(0, m_import_format, m_import_path, TRUE, FALSE);
}
m_import_path.Empty(); // no longer needed
}
#ifdef DEBUG_ENABLE_OPASSERT
m_broadcasting_loaded = TRUE;
#endif // DEBUG_ENABLE_OPASSERT
for (OpListenersIterator iterator(m_bookmark_listeners); m_bookmark_listeners.HasNext(iterator);)
m_bookmark_listeners.GetNext(iterator)->OnBookmarkModelLoaded();
#ifdef DEBUG_ENABLE_OPASSERT
m_broadcasting_loaded = FALSE;
#endif // DEBUG_ENABLE_OPASSERT
}
OP_STATUS DesktopBookmarkManager::ImportAdrBookmark(const uni_char* path)
{
BookmarkAdrStorage adr_parser(g_bookmark_manager, path, FALSE, TRUE);
OP_STATUS ret = OpStatus::OK;
// prevent core from automatically issuing any save request when we're busy reading
g_bookmark_manager->SetSaveBookmarksTimeout(BookmarkManager::NO_AUTO_SAVE, 0);
{
GenericTreeModel::ModelLock lock(m_model);
while (adr_parser.MoreBookmarks())
{
BookmarkItem* item = OP_NEW(BookmarkItem, ());
if (!item)
{
ret = OpStatus::ERR_NO_MEMORY;
break;
}
ret = adr_parser.LoadBookmark(item);
if (OpStatus::IsError(ret))
{
OP_DELETE(item);
if (ret != OpStatus::ERR_OUT_OF_RANGE)
break;
}
}
}
m_model->SetDirty(TRUE);
if (ret != OpStatus::OK && ret != OpStatus::ERR_OUT_OF_RANGE)
return ret;
// Force a complete sync
// the imported items are not added to sync queue one by one since
// OpSyncItem::CommitItem(FALSE, TRUE) is too slow to do for a lot of items
// (OpSyncDataCollection::Find is using a linear search!! )
if (g_sync_manager->SupportsType(SyncManager::SYNC_BOOKMARKS))
{
TRAPD(err, g_pcsync->WriteIntegerL(PrefsCollectionSync::CompleteSync, TRUE));
g_sync_manager->SyncNow(SyncManager::Now, TRUE);
}
return OpStatus::OK;
}
BOOL DesktopBookmarkManager::IsIniFile(const OpString& name)
{
if (name.Length() < 4 || name.FindI(UNI_L(".ini")) != name.Length() - 4)
return FALSE;
OpFile file;
RETURN_VALUE_IF_ERROR(file.Construct(name), FALSE);
// This is just in case the file is actually an Adr file which happens
// sometimes due to sharing profile between different Opera installs
RETURN_VALUE_IF_ERROR(file.Open(OPFILE_READ), FALSE);
OpString8 line;
file.ReadLine(line);
file.Close();
if (line.FindI("Opera Preferences") != 0)
return FALSE;
return TRUE;
}
OP_STATUS DesktopBookmarkManager::UpgradeDefaultBookmarks()
{
Application::RunType run_type = g_application->DetermineFirstRunType();
if (run_type == Application::RUNTYPE_FIRST_NEW_BUILD_NUMBER ||
run_type == Application::RUNTYPE_FIRST ||
// bookmarks were copied from the default Opera, which may be an older version
m_import_format == HotlistModel::OperaBookmark ||
g_run_type->m_added_custom_folder ||
// usually when region changes default bookmarks also change, so bookmarks.adr
// has to be upgraded
// one exception is the first session - the flag is true (initial region is
// always "new"), but default bookmarks for the region were copied in Load()
(g_region_info->m_changed && run_type != Application::RUNTYPE_FIRSTCLEAN))
{
DefaultBookmarkUpgrader upgrader;
return upgrader.Run();
}
return OpStatus::OK;
}
HotlistModelItem* DesktopBookmarkManager::FindDefaultBookmark(OpStringC partner_id)
{
for (UINT32 i=0; i<m_default_bookmarks.GetCount(); i++)
{
HotlistModelItem* item = g_hotlist_manager->GetItemByID(m_default_bookmarks.Get(i));
if (item && item->GetPartnerID().CompareI(partner_id) == 0)
return item;
}
return NULL;
}
BOOL DesktopBookmarkManager::IsDeletedDefaultBookmark(OpStringC partner_id)
{
for (UINT32 i=0; i<m_deleted_default_bookmarks.GetCount(); i++)
{
if (m_deleted_default_bookmarks.Get(i)->CompareI(partner_id) == 0)
return TRUE;
}
return FALSE;
}
void DesktopBookmarkManager::AddDeletedDefaultBookmark(OpStringC partner_id)
{
if (partner_id.HasContent() && !IsDeletedDefaultBookmark(partner_id))
{
OpString* new_id = OP_NEW(OpString, ());
if (new_id)
{
new_id->Set(partner_id);
m_deleted_default_bookmarks.Add(new_id);
}
}
}
HotlistModelItem* DesktopBookmarkManager::FindDefaultBookmarkByURL(OpStringC url)
{
for (UINT32 i=0; i<m_default_bookmarks_with_display_url.GetCount(); i++)
{
HotlistModelItem* item = g_hotlist_manager->GetItemByID(m_default_bookmarks_with_display_url.Get(i));
if (item)
{
OpString resolved_url, resolved_display_url, resolved_input;
TRAPD(err, g_url_api->ResolveUrlNameL(item->GetUrl(), resolved_url);
g_url_api->ResolveUrlNameL(item->GetDisplayUrl(), resolved_display_url);
g_url_api->ResolveUrlNameL(url, resolved_input));
if (OpStatus::IsSuccess(err) && (resolved_url.Compare(resolved_input) == 0
|| resolved_display_url.Compare(resolved_input) == 0))
return item;
}
}
return NULL;
}
/************************************************************
*
* AddCoreItem
*
* Adds a new item to the bookmark tree in core.
*
****************************************************************/
OP_STATUS DesktopBookmarkManager::AddCoreItem(BookmarkItem* core_item,
HotlistModelItem* previous,
HotlistModelItem* parent,
BOOL last)
{
if (!core_item)
return FALSE;
if (previous && !BookmarkWrapper(previous)->GetCoreItem())
return FALSE;
if (parent && !BookmarkWrapper(parent)->GetCoreItem())
return FALSE;
// Core allows adding several folders with type trash.
if (core_item->GetFolderType() == FOLDER_TRASH_FOLDER && g_bookmark_manager->GetTrashFolder())
return FALSE;
// parent shouldn't be trash
if( parent && (parent->GetIsInsideTrashFolder() || parent->GetIsTrashFolder()) )
{
parent = NULL;
previous = NULL;
}
// parent should be a folder, else use it as previous
if( parent && !parent->IsFolder() )
{
if(!previous)
previous = parent;
parent = NULL;
}
if (core_item->GetFolderType() == FOLDER_NORMAL_FOLDER && parent && !parent->GetSubfoldersAllowed())
return FALSE;
BookmarkItem* core_parent = parent ? BookmarkWrapper(parent)->GetCoreItem() : 0;
BookmarkItem* core_previous = previous ? BookmarkWrapper(previous)->GetCoreItem() : 0;
if (last)
{
if (core_parent)
core_previous = static_cast<BookmarkItem*>(core_parent->LastChild());
else
core_previous = static_cast<BookmarkItem*>(g_bookmark_manager->GetRootFolder()->LastChild());
}
return OpStatus::IsSuccess(AddCoreItem(core_item, core_previous, core_parent));
}
/**********************************************************************************
*
* AddCoreItem
*
*
*********************************************************************************/
OP_STATUS DesktopBookmarkManager::AddCoreItem(BookmarkItem* core_item,
BookmarkItem* core_previous,
BookmarkItem* core_parent)
{
// Core only send ADD message to sync server when calling g_bookmark_manager->AddNewBookmark
// but that function doesn't support previous, so set these fields ourselves and use AddBookmark
core_item->SetAdded(TRUE);
core_item->SetModified(FALSE);
return g_bookmark_manager->AddBookmark(core_item, core_previous, core_parent ? core_parent : g_bookmark_manager->GetRootFolder());
}
/**********************************************************************************
*
* AddBookmark
*
*
*********************************************************************************/
OP_STATUS DesktopBookmarkManager::AddBookmark(const BookmarkItemData* item_data,
HotlistModelItem* previous,
HotlistModelItem* parent)
{
BookmarkItem* core_item = OP_NEW(BookmarkItem, ());
RETURN_OOM_IF_NULL(core_item);
::SetDataFromItemData(item_data, core_item);
return AddCoreItem(core_item, previous, parent);
}
OP_STATUS DesktopBookmarkManager::AddBookmarkLast(const BookmarkItemData* item_data, HotlistModelItem* parent)
{
BookmarkItem* core_item = OP_NEW(BookmarkItem, ());
RETURN_OOM_IF_NULL(core_item);
::SetDataFromItemData(item_data, core_item);
return AddCoreItem(core_item, NULL, parent, TRUE);
}
void DesktopBookmarkManager::CreateTrashFolderIfNeeded()
{
static const char* unique_id = "14C645A5B8A3470FB3B52CC32C97E2B8";
// Create a trash folder if it doesn't exist, but only after loading finished
if (!m_model->GetTrashFolder())
{
BookmarkItemData item_data;
item_data.type = FOLDER_TRASH_FOLDER;
item_data.deletable = FALSE;
if (!m_model->GetByUniqueGUID(unique_id))
item_data.unique_id.Set(unique_id);
g_languageManager->GetString(Str::DI_IDSTR_M2_FOLDER_IDX_TRASH, item_data.name);
AddBookmarkLast(&item_data);
}
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <cstdio>
#include <QDebug>
#include <librealsense/rs.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
namespace Ui {
class Mainwindow;
}
class Mainwindow : public QMainWindow
{
Q_OBJECT
public:
explicit Mainwindow(QWidget *parent = 0);
~Mainwindow();
void onMouse( int event ); // , int x, int y, int, void* window_name
bool initialize_streaming();
cv::Mat display_next_frame();
rs::context _rs_ctx;
rs::device& _rs_camera = *_rs_ctx.get_device( 0 );
rs::intrinsics _depth_intrin;
rs::intrinsics _color_intrin;
rs::intrinsics _infrared;
private:
Ui::Mainwindow *ui;
};
#endif // MAINWINDOW_H
|
#include <iostream>
#include <string>
#include "stack.h"
#include "queue.h"
using namespace std;
int main(){
string name = "Abdulmalek";
cs2420::Stack<char> s;
for(char c : name){
s.push(c);
}
while(!s.empty()){
cout << s.pop();
}
cout << endl;
return 0;
}
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/components/web_app_helpers.h"
#include "chrome/browser/web_applications/web_app.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace web_app {
TEST(WebAppRegistrar, CreateRegisterUnregister) {
auto registrar = std::make_unique<WebAppRegistrar>();
EXPECT_EQ(nullptr, registrar->GetAppById(AppId()));
const GURL launch_url = GURL("https://example.com/path");
const AppId app_id = GenerateAppIdFromURL(launch_url);
const std::string name = "Name";
const std::string description = "Description";
const GURL launch_url2 = GURL("https://example.com/path2");
const AppId app_id2 = GenerateAppIdFromURL(launch_url2);
auto web_app = std::make_unique<WebApp>(app_id);
auto web_app2 = std::make_unique<WebApp>(app_id2);
web_app->SetName(name);
web_app->SetDescription(description);
web_app->SetLaunchUrl(launch_url.spec());
EXPECT_EQ(nullptr, registrar->GetAppById(app_id));
EXPECT_EQ(nullptr, registrar->GetAppById(app_id2));
registrar->RegisterApp(std::move(web_app));
WebApp* app = registrar->GetAppById(app_id);
EXPECT_EQ(app_id, app->app_id());
EXPECT_EQ(name, app->name());
EXPECT_EQ(description, app->description());
EXPECT_EQ(launch_url.spec(), app->launch_url());
EXPECT_EQ(nullptr, registrar->GetAppById(app_id2));
registrar->RegisterApp(std::move(web_app2));
WebApp* app2 = registrar->GetAppById(app_id2);
EXPECT_EQ(app_id2, app2->app_id());
registrar->UnregisterApp(app_id);
EXPECT_EQ(nullptr, registrar->GetAppById(app_id));
// Check that app2 is still registered.
app2 = registrar->GetAppById(app_id2);
EXPECT_EQ(app_id2, app2->app_id());
registrar->UnregisterApp(app_id2);
EXPECT_EQ(nullptr, registrar->GetAppById(app_id2));
}
TEST(WebAppRegistrar, DestroyRegistrarOwningRegisteredApps) {
auto registrar = std::make_unique<WebAppRegistrar>();
const AppId app_id = GenerateAppIdFromURL(GURL("https://example.com/path"));
const AppId app_id2 = GenerateAppIdFromURL(GURL("https://example.com/path2"));
auto web_app = std::make_unique<WebApp>(app_id);
registrar->RegisterApp(std::move(web_app));
auto web_app2 = std::make_unique<WebApp>(app_id2);
registrar->RegisterApp(std::move(web_app2));
registrar.reset();
}
} // namespace web_app
|
/*
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 <memory>
#include <utility>
#include <vector>
#include "accelerated_query_node.hpp"
#include "dma_interface.hpp"
#include "dma_setup_interface.hpp"
#include "ila.hpp"
#include "operation_types.hpp"
#include "read_back_module.hpp"
#include "table_data.hpp"
using orkhestrafs::core_interfaces::operation_types::QueryOperationType;
using orkhestrafs::core_interfaces::table_data::TableMetadata;
namespace orkhestrafs::dbmstodspi {
/**
* @brief Implemented by #AcceleratorLibrary
*/
class AcceleratorLibraryInterface {
public:
virtual ~AcceleratorLibraryInterface() = default;
virtual auto IsIncompleteOperationSupported(QueryOperationType operation_type) -> bool = 0;
virtual void SetupOperation(const AcceleratedQueryNode& node_parameters) = 0;
virtual auto GetDMAModule() -> std::unique_ptr<DMAInterface> = 0;
virtual auto GetDMAModuleSetup() -> DMASetupInterface& = 0;
virtual auto ExportLastModulesIfReadback()
-> std::vector<std::unique_ptr<ReadBackModule>> = 0;
virtual auto GetILAModule() -> std::unique_ptr<ILA> = 0;
virtual auto IsMultiChannelStream(bool is_input, int stream_index,
QueryOperationType operation_type)
-> bool = 0;
virtual auto GetMultiChannelParams(
bool is_input, int stream_index, QueryOperationType operation_type,
const std::vector<std::vector<int>>& operation_parameters)
-> std::pair<int, std::vector<int>> = 0;
virtual auto GetNodeCapacity(
QueryOperationType operation_type,
const std::vector<std::vector<int>>& operation_parameters)
-> std::vector<int> = 0;
virtual auto IsNodeConstrainedToFirstInPipeline(
QueryOperationType operation_type) -> bool = 0;
virtual auto IsOperationSorting(QueryOperationType operation_type)
-> bool = 0;
virtual auto GetMinSortingRequirements(QueryOperationType operation_type,
const TableMetadata& table_data)
-> std::vector<int> = 0;
virtual auto GetWorstCaseProcessedTables(
QueryOperationType operation_type, const std::vector<int>& min_capacity,
const std::vector<std::string>& input_tables,
const std::map<std::string, TableMetadata>& data_tables,
const std::vector<std::string>& output_table_names)
-> std::map<std::string, TableMetadata> = 0;
virtual auto GetWorstCaseNodeCapacity(
QueryOperationType operation_type, const std::vector<int>& min_capacity,
const std::vector<std::string>& input_tables,
const std::map<std::string, TableMetadata>& data_tables,
QueryOperationType next_operation_type) -> std::vector<int> = 0;
virtual auto UpdateDataTable(
QueryOperationType operation_type,
const std::vector<int>& module_capacity,
const std::vector<std::string>& input_table_names,
std::map<std::string, TableMetadata>& resulting_tables) -> bool = 0;
virtual auto IsInputSupposedToBeSorted(QueryOperationType operation_type)
-> bool = 0;
// TODO(Kaspar): This method needs improving
virtual auto GetResultingTables(
QueryOperationType operation, const std::vector<std::string>& table_names,
const std::map<std::string, TableMetadata>& tables)
-> std::vector<std::string> = 0;
virtual auto IsOperationReducingData(QueryOperationType operation)
-> bool = 0;
virtual auto IsOperationDataSensitive(QueryOperationType operation)
-> bool = 0;
virtual auto GetEmptyModuleNode(QueryOperationType operation,
int module_position, const std::vector<int>& module_capacity)
-> AcceleratedQueryNode = 0;
virtual auto SetMissingFunctionalCapacity(
const std::vector<int>& bitstream_capacity,
std::vector<int>& missing_capacity, const std::vector<int>& node_capacity,
bool is_composed, QueryOperationType operation_type) -> bool = 0;
};
} // namespace orkhestrafs::dbmstodspi
|
#include <Qt3D/qglbuilder.h>
#include <Qt3D/qglbezierpatches.h>
#include "qtjambiglbuilder.h"
QtJambiGLBuilder::QtJambiGLBuilder(QGLMaterialCollection *materials)
: QGLBuilder(materials){}
QtJambiGLBuilder::~QtJambiGLBuilder(){}
void QtJambiGLBuilder::addPatches(const QGLBezierPatches &patches){
*this << patches;
}
QGLSceneNode * QtJambiGLBuilder::sceneNode(){
return QGLBuilder::sceneNode();
}
QGLSceneNode * QtJambiGLBuilder::currentNode(){
return QGLBuilder::currentNode();
}
QGLSceneNode * QtJambiGLBuilder::newNode(){
return QGLBuilder::newNode();
}
QGLSceneNode * QtJambiGLBuilder::pushNode(){
return QGLBuilder::pushNode();
}
QGLSceneNode * QtJambiGLBuilder::popNode(){
return QGLBuilder::popNode();
}
QGLMaterialCollection * QtJambiGLBuilder::palette(){
return QGLBuilder::palette();
}
QGLSceneNode * QtJambiGLBuilder::finalizedSceneNode(){
return QGLBuilder::finalizedSceneNode();
}
void QtJambiGLBuilder::addTriangles(const QGeometryData &triangle){
QGLBuilder::addTriangles(triangle);
}
void QtJambiGLBuilder::addQuads(const QGeometryData &quad){
QGLBuilder::addQuads(quad);
}
void QtJambiGLBuilder::addTriangleFan(const QGeometryData &fan){
QGLBuilder::addTriangleFan(fan);
}
void QtJambiGLBuilder::addTriangleStrip(const QGeometryData &strip){
QGLBuilder::addTriangleStrip(strip);
}
void QtJambiGLBuilder::addTriangulatedFace(const QGeometryData &face){
QGLBuilder::addTriangulatedFace(face);
}
void QtJambiGLBuilder::addQuadStrip(const QGeometryData &strip){
QGLBuilder::addQuadStrip(strip);
}
void QtJambiGLBuilder::addQuadsInterleaved(const QGeometryData &top,
const QGeometryData &bottom){
QGLBuilder::addQuadsInterleaved(top, bottom);
}
void QtJambiGLBuilder::addPane(qreal size){
QGLBuilder::addPane(size);
}
void QtJambiGLBuilder::addPane(QSizeF size){
QGLBuilder::addPane(size);
}
void QtJambiGLBuilder::addCube(const QGLCube &cube){
*this << cube;
}
void QtJambiGLBuilder::addCylinder(const QGLCylinder &cylinder){
*this << cylinder;
}
void QtJambiGLBuilder::addDome(const QGLDome &dome){
*this << dome;
}
void QtJambiGLBuilder::addSphere(const QGLSphere &sphere){
*this << sphere;
}
void QtJambiGLBuilder::newSection(QGL::Smoothing sm){
QGLBuilder::newSection(sm);
}
|
#pragma once
// Traver_DLG 对话框
class Traver_DLG : public CDialogEx
{
DECLARE_DYNAMIC(Traver_DLG)
public:
Traver_DLG(CWnd* pParent = NULL); // 标准构造函数
virtual ~Traver_DLG();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOG6 };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
CString str;
};
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
QString dirs[12]= {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-"};
//Очень важно: это массив полных названий приложений, которые нужно будет потом открывать, итак суть:
//У нас 12 клавиш, на каждую своё приложение, поэтому мы создаём глобальный массив строк,
//dirs[0] будет отвечать за путь к приложению для F1, dirs[3] для F4 и тд.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::Change() { //GetAsyncKeyState проверяет, нажалась ли кнопка, если да, то передаём её номер в функцию OpenFile
while(1){ //бесконечный цикл
for(int i =8; i <= 190; i++)
{
if (GetAsyncKeyState(i) == -32767)
OpenFile(i);
}
}
}
void MainWindow::OpenFile(int i) { //112-123 это коды клавиш F1-F12,
switch(i) {
case 112: { //112 - код клавиши F1, 113-F2 и тд.
wstring z = dirs[0].toStdWString(); //wstring - тип строк, к которому мы конвертируем элемент из dirs типа QString, нужно для работы ShellExecute
const wchar_t *w = z.c_str(); //Далее уже из wstring, преобразованием к си строке, мы получаем строку const wchar_t *w
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT); //вызываем открытие файла по его полному имени, в обычном режиме.
break;
}
case 113: {
wstring z = dirs[1].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 114: {
wstring z = dirs[2].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 115: {
wstring z = dirs[3].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 116: {
wstring z = dirs[4].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 117: {
wstring z = dirs[5].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 118: {
wstring z = dirs[6].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 119: {
wstring z = dirs[7].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 120: {
wstring z = dirs[8].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 121: {
wstring z = dirs[9].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 122: {
wstring z = dirs[10].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
case 123: {
wstring z = dirs[11].toStdWString();
const wchar_t *w = z.c_str();
ShellExecute(NULL, L"open", w ,NULL, NULL, SW_SHOWDEFAULT);
break;
}
};
}
void MainWindow::on_F1_clicked() //Если кликнута визуальная кнопка в менюшке, то открываем проводник и выбираем приложение, на открытие которого переназначим соответвующую кнопку
{
dirs[0] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F1_dir->setText(dirs[0]);
}
//при нажатии на кнопку загрузки настроек, будет предложено откуда грузить, файл должен быть текстовым содержанием:
//Путь к файлу
//Путь к файлу
//..ещё 9 путей к файлу
//Путь к файлу
//Итого - 12 путей к файлу, каждый на новой строке.
//Безопаснее всего заполнить через менюшку - нажимая на кнопки, а потом сохраняя в файл по кнопке сохранить настройки в файл.
//set ui->F1_dir->setText(dirs[0]) - заполняют тексты после соответствующих кнопок, чисто для визуала
void MainWindow::on_getFile_clicked()
{
QString dir = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ifstream file(dir.toStdString());
if (file.is_open()) {
string str;
for (int i = 0; i < 12; i++) {
getline(file, str);
dirs[i] = QString::fromStdString(str);
}
file.close();
ui->F1_dir->setText(dirs[0]);
ui->F2_dir->setText(dirs[1]);
ui->F3_dir->setText(dirs[2]);
ui->F4_dir->setText(dirs[3]);
ui->F5_dir->setText(dirs[4]);
ui->F6_dir->setText(dirs[5]);
ui->F7_dir->setText(dirs[6]);
ui->F8_dir->setText(dirs[7]);
ui->F9_dir->setText(dirs[8]);
ui->F10_dir->setText(dirs[9]);
ui->F11_dir->setText(dirs[10]);
ui->F12_dir->setText(dirs[11]);
}
}
void MainWindow::on_F2_clicked()
{
dirs[1] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F2_dir->setText(dirs[1]);
}
void MainWindow::on_F3_clicked()
{
dirs[2] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F3_dir->setText(dirs[2]);
}
void MainWindow::on_F4_clicked()
{
dirs[3] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F4_dir->setText(dirs[3]);
}
void MainWindow::on_F5_clicked()
{
dirs[4] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F5_dir->setText(dirs[4]);
}
void MainWindow::on_F6_clicked()
{
dirs[5] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F6_dir->setText(dirs[5]);
}
void MainWindow::on_F7_clicked()
{
dirs[6] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F7_dir->setText(dirs[6]);
}
void MainWindow::on_F8_clicked()
{
dirs[7] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F8_dir->setText(dirs[7]);
}
void MainWindow::on_F9_clicked()
{
dirs[8] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F9_dir->setText(dirs[8]);
}
void MainWindow::on_F10_clicked()
{
dirs[9] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F10_dir->setText(dirs[9]);
}
void MainWindow::on_F11_clicked()
{
dirs[10] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F11_dir->setText(dirs[10]);
}
void MainWindow::on_F12_clicked()
{
dirs[11] = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ui->F12_dir->setText(dirs[11]);
}
//Сохранение текущих настроек в файл - открывается менюшка с выбором файла
//Выбираем текстовый документ, в который хотим сохраниться
//Туда произойдёт сохранение текущих настроек
//QString dir - это строка, в которую запишется полный путь файла.
void MainWindow::on_saveButton_clicked()
{
QString dir = QFileDialog::getOpenFileName(this, QString("Открыть файл"), QDir::currentPath(), "Text (*.txt);All files (*.*)");
ofstream file(dir.toStdString());
for (int i = 0; i < 12; i++) {
file << dirs[i].toStdString() << '\n';
}
}
|
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// UnityEngine.ParticleSystem[]
struct ParticleSystemU5BU5D_t808643063;
// UnityEngine.ParticleSystem
struct ParticleSystem_t56787138;
// System.Object
struct Il2CppObject;
// UnityStandardAssets.Utility.ParticleSystemDestroyer
struct ParticleSystemDestroyer_t2578584915;
#include "mscorlib_System_Object837106420.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5
struct U3CStartU3Ec__Iterator5_t4138896572 : public Il2CppObject
{
public:
// UnityEngine.ParticleSystem[] UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<systems>__0
ParticleSystemU5BU5D_t808643063* ___U3CsystemsU3E__0_0;
// UnityEngine.ParticleSystem[] UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<$s_8>__1
ParticleSystemU5BU5D_t808643063* ___U3CU24s_8U3E__1_1;
// System.Int32 UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<$s_9>__2
int32_t ___U3CU24s_9U3E__2_2;
// UnityEngine.ParticleSystem UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<system>__3
ParticleSystem_t56787138 * ___U3CsystemU3E__3_3;
// System.Single UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<stopTime>__4
float ___U3CstopTimeU3E__4_4;
// UnityEngine.ParticleSystem[] UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<$s_10>__5
ParticleSystemU5BU5D_t808643063* ___U3CU24s_10U3E__5_5;
// System.Int32 UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<$s_11>__6
int32_t ___U3CU24s_11U3E__6_6;
// UnityEngine.ParticleSystem UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<system>__7
ParticleSystem_t56787138 * ___U3CsystemU3E__7_7;
// System.Int32 UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::$PC
int32_t ___U24PC_8;
// System.Object UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::$current
Il2CppObject * ___U24current_9;
// UnityStandardAssets.Utility.ParticleSystemDestroyer UnityStandardAssets.Utility.ParticleSystemDestroyer/<Start>c__Iterator5::<>f__this
ParticleSystemDestroyer_t2578584915 * ___U3CU3Ef__this_10;
public:
inline static int32_t get_offset_of_U3CsystemsU3E__0_0() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CsystemsU3E__0_0)); }
inline ParticleSystemU5BU5D_t808643063* get_U3CsystemsU3E__0_0() const { return ___U3CsystemsU3E__0_0; }
inline ParticleSystemU5BU5D_t808643063** get_address_of_U3CsystemsU3E__0_0() { return &___U3CsystemsU3E__0_0; }
inline void set_U3CsystemsU3E__0_0(ParticleSystemU5BU5D_t808643063* value)
{
___U3CsystemsU3E__0_0 = value;
Il2CppCodeGenWriteBarrier(&___U3CsystemsU3E__0_0, value);
}
inline static int32_t get_offset_of_U3CU24s_8U3E__1_1() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CU24s_8U3E__1_1)); }
inline ParticleSystemU5BU5D_t808643063* get_U3CU24s_8U3E__1_1() const { return ___U3CU24s_8U3E__1_1; }
inline ParticleSystemU5BU5D_t808643063** get_address_of_U3CU24s_8U3E__1_1() { return &___U3CU24s_8U3E__1_1; }
inline void set_U3CU24s_8U3E__1_1(ParticleSystemU5BU5D_t808643063* value)
{
___U3CU24s_8U3E__1_1 = value;
Il2CppCodeGenWriteBarrier(&___U3CU24s_8U3E__1_1, value);
}
inline static int32_t get_offset_of_U3CU24s_9U3E__2_2() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CU24s_9U3E__2_2)); }
inline int32_t get_U3CU24s_9U3E__2_2() const { return ___U3CU24s_9U3E__2_2; }
inline int32_t* get_address_of_U3CU24s_9U3E__2_2() { return &___U3CU24s_9U3E__2_2; }
inline void set_U3CU24s_9U3E__2_2(int32_t value)
{
___U3CU24s_9U3E__2_2 = value;
}
inline static int32_t get_offset_of_U3CsystemU3E__3_3() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CsystemU3E__3_3)); }
inline ParticleSystem_t56787138 * get_U3CsystemU3E__3_3() const { return ___U3CsystemU3E__3_3; }
inline ParticleSystem_t56787138 ** get_address_of_U3CsystemU3E__3_3() { return &___U3CsystemU3E__3_3; }
inline void set_U3CsystemU3E__3_3(ParticleSystem_t56787138 * value)
{
___U3CsystemU3E__3_3 = value;
Il2CppCodeGenWriteBarrier(&___U3CsystemU3E__3_3, value);
}
inline static int32_t get_offset_of_U3CstopTimeU3E__4_4() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CstopTimeU3E__4_4)); }
inline float get_U3CstopTimeU3E__4_4() const { return ___U3CstopTimeU3E__4_4; }
inline float* get_address_of_U3CstopTimeU3E__4_4() { return &___U3CstopTimeU3E__4_4; }
inline void set_U3CstopTimeU3E__4_4(float value)
{
___U3CstopTimeU3E__4_4 = value;
}
inline static int32_t get_offset_of_U3CU24s_10U3E__5_5() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CU24s_10U3E__5_5)); }
inline ParticleSystemU5BU5D_t808643063* get_U3CU24s_10U3E__5_5() const { return ___U3CU24s_10U3E__5_5; }
inline ParticleSystemU5BU5D_t808643063** get_address_of_U3CU24s_10U3E__5_5() { return &___U3CU24s_10U3E__5_5; }
inline void set_U3CU24s_10U3E__5_5(ParticleSystemU5BU5D_t808643063* value)
{
___U3CU24s_10U3E__5_5 = value;
Il2CppCodeGenWriteBarrier(&___U3CU24s_10U3E__5_5, value);
}
inline static int32_t get_offset_of_U3CU24s_11U3E__6_6() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CU24s_11U3E__6_6)); }
inline int32_t get_U3CU24s_11U3E__6_6() const { return ___U3CU24s_11U3E__6_6; }
inline int32_t* get_address_of_U3CU24s_11U3E__6_6() { return &___U3CU24s_11U3E__6_6; }
inline void set_U3CU24s_11U3E__6_6(int32_t value)
{
___U3CU24s_11U3E__6_6 = value;
}
inline static int32_t get_offset_of_U3CsystemU3E__7_7() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CsystemU3E__7_7)); }
inline ParticleSystem_t56787138 * get_U3CsystemU3E__7_7() const { return ___U3CsystemU3E__7_7; }
inline ParticleSystem_t56787138 ** get_address_of_U3CsystemU3E__7_7() { return &___U3CsystemU3E__7_7; }
inline void set_U3CsystemU3E__7_7(ParticleSystem_t56787138 * value)
{
___U3CsystemU3E__7_7 = value;
Il2CppCodeGenWriteBarrier(&___U3CsystemU3E__7_7, value);
}
inline static int32_t get_offset_of_U24PC_8() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U24PC_8)); }
inline int32_t get_U24PC_8() const { return ___U24PC_8; }
inline int32_t* get_address_of_U24PC_8() { return &___U24PC_8; }
inline void set_U24PC_8(int32_t value)
{
___U24PC_8 = value;
}
inline static int32_t get_offset_of_U24current_9() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U24current_9)); }
inline Il2CppObject * get_U24current_9() const { return ___U24current_9; }
inline Il2CppObject ** get_address_of_U24current_9() { return &___U24current_9; }
inline void set_U24current_9(Il2CppObject * value)
{
___U24current_9 = value;
Il2CppCodeGenWriteBarrier(&___U24current_9, value);
}
inline static int32_t get_offset_of_U3CU3Ef__this_10() { return static_cast<int32_t>(offsetof(U3CStartU3Ec__Iterator5_t4138896572, ___U3CU3Ef__this_10)); }
inline ParticleSystemDestroyer_t2578584915 * get_U3CU3Ef__this_10() const { return ___U3CU3Ef__this_10; }
inline ParticleSystemDestroyer_t2578584915 ** get_address_of_U3CU3Ef__this_10() { return &___U3CU3Ef__this_10; }
inline void set_U3CU3Ef__this_10(ParticleSystemDestroyer_t2578584915 * value)
{
___U3CU3Ef__this_10 = value;
Il2CppCodeGenWriteBarrier(&___U3CU3Ef__this_10, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
#include <iostream>
using namespace std;
void make_map(int xx, int yy, int wide, int height) // xx, yy는 시작 좌표
{
for (int y = yy; y + height + 3; y++)
{
if () // 시작좌표일 때 || 마지막 좌표일 때
{
for (int x = xx; x + wide + 3; x++)
{
cout << "■";
}
}
else
{
// 그 라인의 첫 번째와 마지막 좌표에만 ■
}
}
}
|
#include<vector>
#include<iostream>
using namespace std;
class Solution1{
public:
int line;
int tot;
int chessboard[3][50];
vector<int> reslte;
Solution1(int a){
line=a;
tot=0;
reslte.assign(line,0);
for(int i=0;i<3;i++){
for(int j=0;j<50;j++){
chessboard[i][j]=0;
}
}
cout<<"start porject......"<<endl;
}
void getmesolution(){
dfs(0);
}
private:
void dfs(int cur){
if(cur==line){
for(int i=0;i<line;i++){
for(int j=0;j<line;j++){
if(reslte[i]==j)cout<<"x ";
else
cout<<"O ";
}
cout<<"---"<<reslte[i]<<endl;
}
cout<<endl;
tot++;
}
else
{
for(int i=0;i<line;i++){
if( !chessboard[0][i] && !chessboard[1][cur+i] && !chessboard[2][cur-i+line]){
reslte[cur]=i;
chessboard[0][i]=1;
chessboard[1][cur+i]=1;
chessboard[2][cur-i+line]=1;
dfs(cur+1);
chessboard[0][i]=0;
chessboard[1][cur+i]=0;
chessboard[2][cur-i+line]=0;
}
}
}
}
};
class Solution2{
public:
int n,m;
int x,y;
int tot;
vector<int> h;
vector<vector<int>> chessboard;
Solution2(int a,int b,int c,int d){
n=a;//³€
m=b;//Ών
x=c-1;
y=d-1;
tot=0;
sum=n*m;
h.assign(n,0);
chessboard.assign(m,h);
cout<<"start porject......"<<endl;
}
void getmesolution(){
dfs(x,y,0);
}
private:
int sum;
void dfs(int x,int y,int cur){
if(inboard(x,y) && !chessboard[x][y]){
cur++;
chessboard[x][y]=cur;
if(cur==sum){
tot++;
cout<<"Case# "<<tot<<endl;
outchess(chessboard);
cout<<endl;
chessboard[x][y]=0;
return;
}
else{
dfs(x-1,y-2,cur);
dfs(x-1,y+2,cur);
dfs(x-2,y-1,cur);
dfs(x-2,y+1,cur);
dfs(x+1,y-2,cur);
dfs(x+1,y+2,cur);
dfs(x+2,y-1,cur);
dfs(x+2,y+1,cur);
chessboard[x][y]=0;
}
}
}
void outchess(vector<vector<int>> chessboard){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
printf("%4d",chessboard[i][j]);
}
cout<<endl;
}
}
int inboard(int x,int y){
if(x<n && x>=0 && y<m && y>=0)return 1;
return 0;
}
};
int main(){
char n;
cout<<"input what question you want to know: ";
cin>>n;
if(n=='1'){
int line;
cout<<"input the number of queen:"<<endl;
cin>>line;
Solution1 putdonwthequeen(line);
putdonwthequeen.getmesolution();
cout<<"To sum up : "<<putdonwthequeen.tot<<endl;
}
if(n=='2'){
int chang,kuan,x,y;
cout<<"input ³€/Ών:"<<endl;
cin>>chang>>kuan;
cout<<"input x/y:"<<endl;
cin>>x>>y;
Solution2 runhours(chang,kuan,x,y);
runhours.getmesolution();
}
return 0;
}
|
#ifndef _МояИгра_Н
#define _МояИгра_Н
#include <SFML/Graphics.hpp> //аудио
#include <SFML/Audio.hpp> //графика
#include <sstream> //работа с текстом
#include <random> //случайные числа
#include <list> //массив обьектов
//скаченые библиотеки совместимости с программами SpriteDecomposer и Tiled
#include "Анимация.h"
#include "level.hpp"
using namespace sf;
static int Клетка = 100; //размер 1 клетки в пикселях
//обстрактный базовый класс
class объект
{
protected:
std::vector<Object> обьект; //обьекты, с которыми класс будит взаимодействовать (стены, бонусы)
std::string имя; //имя обьекта, нужно чтобы различать их в массиве
bool выстрел = 0; //флаг состояния выстрела
bool смерть = 0; //флаг состояния удара
int кадуд; //сколько кадров в анимации удара
std::string текст; //сообщения для вывода над персонажем
bool жив, зеркало; //флаг жизни и поворота
bool приследование = 0; //флаг состояния вписледования персонажа
double Жизнь, урон;
bool t = 1; bool уд = 1; //вспомогательные флаги для анимации
double x, y, dx, dy, w, h; //размеры и скорость обьекта
менеджер_анимации анимация; //анимация
public:
//доступ к переменным
менеджер_анимации пок_анимация() { return анимация; };
void изм_Жизнь(double x) { Жизнь = x; };
double пок_Жизнь() { return Жизнь; };
double пок_урон() { return урон; };
int пок_кадуд() { return кадуд; };
bool пок_уд() { return уд; };
void изм_уд() { уд = 0; };
bool пок_t() { return t; };
void изм_t(bool x) { t = x; };
bool пок_приследование() { return приследование; };
void изм_приследование(bool x) { приследование = x; };
bool пок_жив() { return жив; };
void изм_жив(bool x) { жив = x; };
bool пок_зеркало() { return зеркало; };
void изм_зеркало(bool x) { зеркало = x; };
std::string пок_имя() { return имя; };
std::string пок_текст() { return текст; };
bool пок_выстрел() { return выстрел; };
void сдел_выстрел() { выстрел = 1; };
double пок_h() { return h; };
double пок_x() { return x; };
void изм_x(double х) { x = х; };
double пок_y() { return y; };
void изм_y(double х) { y = х; };
//основные функции
объект(менеджер_анимации a, int X, int Y); //конструктор
FloatRect размер(); //возращает размеры персонажа
virtual void показать(RenderWindow& window); //отобразить персонажа
virtual void option(std::string NAME, double SPEED = 0, double жизнь = 1, std::string FIRST_ANIM = ""); //инициализовать начальные характеристики
virtual void обновить(double время) = 0; //основная ф-ия, обновляет персонажа
};
class Игрок : public объект
{
private:
int ЗапасСтрел = 10; //сколько осталось выстрелов
double скорасть_игрока = 0.3; //скорость игрока пешком
FloatRect позиция; //координаты
bool на_земле = 0; //нужно ли придовать ускорение падения
Sprite игрок; //картинка
public:
//доступ к переменным
int пок_ЗапасСтрел() { return ЗапасСтрел; };
void изм_ЗапасСтрел(int x) { ЗапасСтрел = x; };
void доб_ЗапасСтрел(int x) { ЗапасСтрел += x; };
//основные функции
Игрок(менеджер_анимации& анимация, Level& lvl, int x, int y); //конструктор
void Анимация(double time); //анимация
void НачПозиц(char буква); //чтение начальной позиции
void yправление(); //управление персонадем
void обновить(double время); //основная ф-ия, обновляет персонажа
bool столкновение(bool ось); //взаимоотношение со стенами
};
class Стрела : public объект {
public:
Стрела(менеджер_анимации& a, Level& lev, int x, int y, bool dir); //свой конструктор
void обновить(double time); //основная ф-ия, обновляет персонажа
Стрела(менеджер_анимации& a, Level& lev, int x, int y) : объект(a, x, y) {} //конструктор для связи потомков с предками
};
class Камень : public Стрела {
public:
Камень(менеджер_анимации& a, Level& lev, int x, int y, bool dir); //конструктор
};
class Бонус : public объект {
public:
Бонус(std::string NAME, менеджер_анимации& a, int x, int y) : объект(a, x, y) {//конструктор
option(NAME); //загрузка основных параметров
}
void обновить(double time) {}; //обновление не требуется
};
class Гоблин : public объект {
protected:
bool выстрел2 = 0; //у наследников много типов ударов, но все пользуются обновлением гоблина
bool направление = 0; //куда двигаться
int смер = 0; //нужен чтобы загружать разные по размерам картинки смерти персонажа
bool f = 1; //флаг для проигрывания анимациии смерти
double скорость = 0.3; //стартовая скорость
bool на_земле = 0; //нужно ли придовать ускорение падения
public:
//доступ к переменным
void изм_выстрел2(bool x) { выстрел2 = x; };
//основные функции
virtual void поведение();//что делать после встречи с припядствием
virtual void Анимация(double time);//анимация персонажа
Гоблин(менеджер_анимации& анимация, Level& lvl, int x, int y, double SPEED, double жизнь); //конструктор
Гоблин(менеджер_анимации& a, Level& lev, int x, int y) : объект(a, x, y) {} //связь наследников с предками
void обновить(double время); //основная ф-ия, обновляет персонажа
bool столкновение(bool ось); //взаимоотношение со стенами
};
class Нпс1 : public Гоблин {
protected:
int удар = 0; //переключатель типов ударов
public:
virtual void Анимация(double time); //проигрывать анимацию
Нпс1(менеджер_анимации& анимация, Level& lvl, int x, int y); //конструктор
};
class Халк : public Гоблин {
protected:
bool прыжок = 0; //флаг начала прыжка
//флаги для анимаций
bool t4 = 1;
bool t3 = 0;
double t2; //запоминанее позиции чтобы сменить повиденее при повторении пути
double выспрышеп = 0.6; //ускорение при прышке
int удар = 0; // который удар проигрывать
public:
//доступ к переменным
int пок_удар() { return удар; };
//основные функции
virtual void Анимация(double time); //проигрывать анимацию
void поведение(); //что делать при встречи со стеной
Халк(менеджер_анимации& анимация, Level& lvl, int x, int y); //конструктор
Халк(менеджер_анимации& анимация, Level& lvl, int x, int y, int t) : Гоблин(анимация, lvl, x, y) {} //конструктор для связи наследников с предками
};
class Бос : public Халк {
private:
double прыжокустены; //запоминанее позиции чтобы сменить повиденее при повторении пути
public:
//доступ к переменным
double пок_прыжокустены() { return прыжокустены; };
//основные функции
void Анимация(double time); //проигрыванее анимации
Бос(менеджер_анимации& анимация, Level& lvl, int x, int y); //конструктор
};
#endif
|
#include "stdafx.h"
StockInputException::StockInputException(string inmessage) {
message = "StockInputException: ";
if (inmessage != "") {
message.append(inmessage);
} else {
"An error occured while trying to read stock data from your input file.";
}
}
string StockInputException::what() {
return message;
}
|
#pragma once
#include "Commonheader.h"
#include "Window.h"
#include "TrackBall.h"
//入力を管理するマネージャー
static class InputManager
{
public:
enum ButtonFlag{
FLAG_SPACE = 1,
FLAG_P = 1 << 1,
FLAG_R = 1 << 2,
FLAG_T = 1 << 3,
FLAG_B = 1 << 4
};
enum MoveFlag{
FLAG_UP = 1,
FLAG_RIGHT = 1 << 1,
FLAG_DOWN = 1 << 2,
FLAG_LEFT = 1 << 3
};
static bool CheckInputSpace(); static bool PressSpace;
static bool CheckInputP(); static bool PressP;
static bool CheckInputR(); static bool PressR;
static bool CheckInputT(); static bool PressT;
static bool CheckInputB(); static bool PressB;
static bool CheckInputMoveUp();
static bool CheckInputMoveRight();
static bool CheckInputMoveDown();
static bool CheckInputMoveLeft();
static void SetMyWindow(GLFWwindow* w);
static void CheckInputMove();
static void CheckInputMouseDrag(GLFWwindow *window);
static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods);
static void MouseCallback(GLFWwindow *window, int button, int action, int mods);
static TrackBall* GetTrackBall(){
CheckInputMouseDrag(myWindow);
return m_trackBall;
}
private:
static GLFWwindow* myWindow;
InputManager(){
};
~InputManager(){
};
static unsigned int mInputButtonFlag;
static unsigned int mInputMoveFlag;
static TrackBall* m_trackBall;
};
|
#include "axis.hpp"
using namespace Ogre;
void AxisObject::addBox(ManualObject* obj, Vector3 dim, Vector3 pos, ColourValue color, short boxMask)
{
if(!obj)
return;
obj->begin("Axis", Ogre::RenderOperation::OT_TRIANGLE_LIST);
dim/=2;
Ogre::Real l = dim.x;
Ogre::Real h = dim.y;
Ogre::Real w = dim.z;
obj->position(Ogre::Vector3(-l, h, w) + pos);
obj->colour(color);
obj->position(Ogre::Vector3(-l, -h, w) + pos);
obj->colour(color);
obj->position(Ogre::Vector3(l, -h, w) + pos);
obj->colour(color);
obj->position(Ogre::Vector3(l, h, w) + pos);
obj->position(Ogre::Vector3(-l, h, -w) + pos);
obj->colour(color);
obj->position(Ogre::Vector3(-l, -h, -w) + pos);
obj->colour(color);
obj->position(Ogre::Vector3(l, -h, -w) + pos);
obj->colour(color);
obj->position(Ogre::Vector3(l, h, -w) + pos);
// front back
if(boxMask & BOX_FRONT)
obj->quad(0, 1, 2, 3);
if(boxMask & BOX_BACK)
obj->quad(7, 6, 5, 4);
// top bottom
if(boxMask & BOX_TOP)
obj->quad(0, 3, 7, 4);
if(boxMask & BOX_BOT)
obj->quad(2, 1, 5, 6);
// end caps
if(boxMask & BOX_RIGHT)
obj->quad(1, 0, 4, 5);
if(boxMask & BOX_LEFT)
obj->quad(3, 2, 6, 7);
obj->end();
}
void AxisObject::addMaterial(const Ogre::String &mat, Ogre::ColourValue const & clr, Ogre::SceneBlendType sbt)
{
static int init=false;
if(init)
return;
else
init=true;
Ogre::MaterialPtr matptr = Ogre::MaterialManager::getSingleton().create(mat, "General");
matptr->setReceiveShadows(false);
matptr->getTechnique(0)->setLightingEnabled(true);
matptr->getTechnique(0)->getPass(0)->setDiffuse(clr);
matptr->getTechnique(0)->getPass(0)->setAmbient(clr);
matptr->getTechnique(0)->getPass(0)->setSelfIllumination(clr);
matptr->getTechnique(0)->getPass(0)->setSceneBlending(sbt);
matptr->getTechnique(0)->getPass(0)->setLightingEnabled(false);
matptr->getTechnique(0)->getPass(0)->setVertexColourTracking(Ogre::TVC_DIFFUSE);
}
Ogre::ManualObject* AxisObject::createAxis(Ogre::SceneManager *scene, const Ogre::String &name, Ogre::Real scale)
{
addMaterial("Axis", Ogre::ColourValue(1,1,1,.75), Ogre::SBT_TRANSPARENT_ALPHA);
Ogre::ManualObject* axis = scene->createManualObject(name);
Ogre::Real len=scale;
Ogre::Real scl=len*.1;
Ogre::Real loc=len/2+scl/2;
Ogre::Real fade=.5;
Ogre::Real solid=.8;
addBox(axis, Vector3(len, scl, scl), Vector3(loc,0,0), ColourValue(0, 0, solid, solid), (BOX_ALL & ~BOX_RIGHT));
// addBox(axis, Vector3(len, scl, scl), Vector3(-loc,0,0), ColourValue(0, 0, fade, fade), (BOX_ALL & ~BOX_LEFT));
addBox(axis, Vector3(scl, len, scl), Vector3(0,loc,0), ColourValue(0, solid, 0, solid), (BOX_ALL & ~BOX_BOT));
// addBox(axis, Vector3(scl, len, scl), Vector3(0,-loc,0), ColourValue(0, fade, 0, fade), (BOX_ALL & ~BOX_TOP));
addBox(axis, Vector3(scl, scl, len), Vector3(0,0,loc), ColourValue(solid, 0, 0, solid), (BOX_ALL & ~BOX_BACK));
// addBox(axis, Vector3(scl, scl, len), Vector3(0,0,-loc), ColourValue(fade, 0, 0, fade), (BOX_ALL & ~BOX_FRONT));
axis->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1);
return axis;
}
|
#include"Convert.h"
//Prototype
string plusString(string a, string b);
string MultiStringTo2(string str);
string Power2String(int exp);
string Div2String(string num, bool& bit);
bool* Convert::DecToBin(QInt num) {
bool* result = new bool[128];
for (int i = 127; i >= 0; i--) {
result[i] = num.GetBit(i);
}
return result;
}
QInt Convert::BinToDec(bool* bin) {
QInt res;
for (int i = 127; i >= 0; i--) {
res.SetBit(i, bin[i]);
}
return res;
}
QInt Convert::ToBu2(QInt num) {
QInt result;
result = 0;
result = ~num;;
//+1 de chuyen sang bu 2
int bitNho = 1;
for (int i = 127; i >= 0; i--) {
//Khi bit nhớ = 1 thì mới thực hiện cộng vào
if (bitNho == 1) {
bool curBit = result.GetBit(i);
if (curBit == 1) {
result.SetBit(i, 0);
}
else {
bitNho = 0;
result.SetBit(i, 1);
}
}
}
return result;
}
string Convert::QIntToStringNumber(QInt x) {
string result = "";
//Kiểm tra bit đầu
if (x.GetBit(0) == 1) {
x = Convert::ToBu2(x);
result = "-";
}
string valueNotSign = "";
for (int i = 127; i >= 0; i--) {
if (x.GetBit(i) == 1) {//nếu là 1 thì mới cộng thêm
valueNotSign = plusString(valueNotSign, Power2String(127 - i));
}
}
result += valueNotSign;
return result;
}
QInt Convert::StringNumberToQInt(string num) {
QInt result;
bool isNegative = false;
if (num[0] == '-') {
isNegative = true;
//Chuyen so dau tien thanh 0 de thuc hien phep chia
num[0] = '0';
}
else if (num[0] == '+') {
num[0] = '0';
}
bool bit;
int vt = 127;
while (num!="0" && num!="")
{
num = Div2String(num, bit);
result.SetBit(vt, bit);
vt--;
}
if (isNegative) {
result = ToBu2(result);
}
return result;
}
/*------------ Các hàm hỗ trợ xử lý chuỗi---------------*/
string plusString(string a, string b) {
{
//Luon dat so dai hon ben tren
if (a.length() < b.length()) {
swap(a, b);
}
//Thuc hiện thao tác đặt phép cộng , thuật toán cơ ở tiểu học
string res = "";
int lengthA = a.length();
int lengthB = b.length();
int nho = 0; //Phép cộng sẽ có nhớ
int resCol = 0; //Kết quả khi cộng xong tại 1 cột(%10)
int endPlus = lengthA - lengthB; //Khi đã cộng xong hết cho B , các cột còn lại chỉ cần hạ xuống
for (int i = lengthA - 1; i >= 0; i--) {
//Kiểm tra xem hết phép cộng chưa
if (i >= endPlus) {
resCol = (int)(a[i] - '0') + (int)(b[i - endPlus] - '0') + nho;
}
else if (nho != 0) { //Sau khi đã cộng hết b , thì check nhớ
resCol = (int)(a[i] - '0') + nho;
}
else if (nho == 0) { //hạ xuống
resCol = (int)(a[i] - '0');
}
nho = resCol / 10;
resCol %= 10;
res += to_string(resCol);
}
//Nếu tại i=0 mà bit nhớ vẫn còn
if (nho != 0) {
res += to_string(nho);
}
//Vì kết quả đang lưu ngược nên phải revert lại
string myResult = "";
int length = res.length();
for (int i = length - 1; i >= 0; i--) {
myResult += res[i];
}
return myResult;
}
}
string MultiStringTo2(string str) {
//lưu giá trị đảo ngược của phép nhân
string resTemp = "";
//dùng thuật toán cơ bản của tiểu học:
int length = str.length();
int nho = 0;
int resCol = 0;
for (int i = length - 1; i >= 0; i--) {
resCol = (int)(str[i] - '0') * 2 + nho;
nho = resCol / 10;
resCol %= 10;
resTemp += to_string(resCol);
}
//Nếu bị tràn :
if (nho != 0) {
resTemp += to_string(nho);
}
string myResult = "";
int myLength = resTemp.length();
for (int i = myLength - 1; i >= 0; i--) {
myResult += resTemp[i];
}
return myResult;
}
string Power2String(int exp) {
string res = "1";
if (exp < 0) return 0;
for (int i = 0; i < exp; i++) {
res = MultiStringTo2(res);
}
return res;
}
string Div2String(string num , bool& bit) { //Bit du sau khi chia 2
if ((int)(num[num.length() - 1] - '0') % 2 == 0)
bit = 0;
else
bit = 1;
//chia cho 2 , cung la 1 thuat toan co ban tieu hoc
int length = num.length();
int resCol = 0;
int mod = 0;
string result = "";
for (int i = 0; i < length; i++) {
resCol = (int)(num[i] - '0') + mod * 10;
mod = resCol % 2;
resCol /= 2;
if (resCol == 0 && i == 0) { //Khi gia tri tai i = 0 < 2 thi khong them 0 vao
continue;
}
result += to_string(resCol);
}
return result;
}
|
#ifndef _FINCHSTD_H_
#define _FINCHSTD_H_
namespace finchstd
{
int inpInt(const char *);
}
#endif
|
#include "StaticObjectPotionView.h"
#include "Core.h"
void StaticObjectPotionView::initView(StaticObjectModel* staticObjectModel)
{
m_staticObjectModel = staticObjectModel;
//Obtain the atlas key looking up where the mesh is. Could be any mesh.
m_atlasKey = Core::singleton().textureManager().findAtlas("cpotion");
addAnim("cpotion", Core::singleton().textureManager().getTextureAtlas(m_atlasKey)->mesh("cpotion"));
setAnim("cpotion");
}
|
/*
* Copyright 2016 Robert Bond
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <iostream>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include "opencv2/core/core.hpp"
#include "opencv2/gpu/gpu.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
using namespace cv::gpu;
#include "hw.h"
#include "util.h"
#include "neuro.h"
#include "player.h"
#include "ants.h"
// Frame number for debug
extern int frame_index;
player::player(const char *filename)
{
FILE *fd = fopen(filename, "r");
if (!fd) {
printf("Cant open %s\n", filename);
exit(1);
}
bool more_to_read = true;
int n;
while (more_to_read) {
int ch = fgetc(fd);
if (ch == EOF)
more_to_read = false;
if (ch == '\n')
n++;
}
pos = new struct rpos[n];
rewind(fd);
for (int i = 0; i < n; i++) {
struct rpos *pr = &pos[i];
fscanf(fd, "%d %d %d %d\n",
&pr->x, &pr->y, &pr->npix, &pr->frame);
}
cpos = 0;
npos = n;
done = false;
}
// Tries to predict the result of the pyrDown.
struct pix_tbl {
int target;
int len;
int width;
};
struct pix_tbl pix_tbl_1[] = {
{ 1, 1, 1 },
{ 2, 1, 2 },
{ 3, 1, 3 },
{ 4, 2, 2 },
{ 6, 2, 3 },
{ 8, 2, 4 },
{ 9, 3, 3 },
{ 10, 2, 5 },
{ 12, 3, 4 },
{ 14, 2, 7 },
{ 15, 3, 5 },
{ 16, 4, 4 },
{ 18, 3, 6 },
{ 20, 4, 5 },
{ 21, 3, 7 },
{ 24, 4, 6 },
{ 0, 0, 0}
};
void interp(Mat &frame, struct rpos *pc, struct rpos *pn)
{
double r = (double)(frame_index - pc->frame) /
(double)(pn->frame - pc->frame);
int px = round(r * (double)(pn->x - pc->x) + pc->x);
int py = round(r * (double)(pn->y - pc->y) + pc->y);
// Figure out ideal size - should match code in ant_score
int ideal_size = get_ant_size(px, py);
struct pix_tbl *pix_tbl;
int scale = xpix / frame.cols;
int width, len;
if (scale == 1) {
pix_tbl = pix_tbl_1;
} else {
DPRINTF("player.cpp: interp: No support for scale = %d!\n", scale);
return;
}
for (int i = 0; pix_tbl[i+1].target > 0; i++)
if (ideal_size >= pix_tbl[i].target &&
ideal_size < pix_tbl[i+1].target) {
len = pix_tbl[i].len;
width = pix_tbl[i].width;
break;
}
px /= scale;
py /= scale;
DPRINTF("Play %d %d ideal_size: %d npix: %d frame: %d\n", px, py, ideal_size, width*len, frame_index);
for (int i = 0; i < len; i++)
for (int j = 0; j < width; j++)
frame.at<uchar>(py + i, px + j) = 0;
}
void player::add_ant(Mat &frame)
{
if (done)
return;
if (cpos == 0 && frame_index < pos[0].frame)
return;
struct rpos *pc = &pos[cpos];
struct rpos *pn = &pos[cpos + 1];
if (frame_index >= pc->frame && frame_index <= pn->frame)
interp(frame, pc, pn);
if (frame_index == pn->frame) {
cpos++;
if (cpos >= npos - 1)
done = true;
}
}
|
#include <bits/stdc++.h>
using namespace std;
struct Cosa{
vector <int> arreglo;
int id;
const bool operator < (const Cosa otro ) const{
return id < otro.id;
}
};
vector<Cosa > soluciones;
bool existe[2097155];
long long int problema[25];
long long int N, G, aprobatoria = 0, total;
float aprueba;
bool jala = false;
void usa(int cual, int quedan,vector<int> usados,int suma, int id){
if(quedan == 0) return;
suma += problema[cual];
id += pow(2,(cual));
usados.push_back(cual);
if( ((suma*100)/total) >= G){
if(!existe[id]){
existe[id] = true;
jala = true;
Cosa solucion;
solucion.arreglo = usados;
solucion.id = id;
soluciones.push_back(solucion);
return;
}
}
for(int i=cual+1; i<N; i++){
usa(i,quedan-1,usados,suma,id);
}
}
void rifate(){
int aUsar;
for(int i=1; i<=N; i++){
aUsar = i;
for(int j= 0; j<N; j++){
vector<int> usados;
usa(j,aUsar,usados,0,0);
}
if(jala) break;
}
cout << aUsar << " " << soluciones.size() << '\n';
sort(soluciones.begin(),soluciones.end());
for(Cosa vektorCosa: soluciones){
vector<int> vektor = vektorCosa.arreglo;
int promedio =0;
for(int i=0; i<vektor.size(); i++){
promedio += problema[vektor[i]];
}
promedio *= 100;
promedio /= total;
cout << promedio << " ";
for(int i=0; i<vektor.size()-1; i++){
cout << vektor[i]+1 << " ";
}
cout << vektor[vektor.size()-1]+1 << '\n';
}
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> N >> G;
for(int i=0; i<N; i++){
cin >> problema[i];
aprobatoria += problema[i];
}
total = aprobatoria;
aprobatoria *= G;
aprueba = aprobatoria;
aprobatoria /= 100;
aprobatoria /= 100;
rifate();
return 0;
}
|
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Graphic3d_CLight_HeaderFile
#define _Graphic3d_CLight_HeaderFile
#include <gp_Dir.hxx>
#include <Graphic3d_TypeOfLightSource.hxx>
#include <Graphic3d_Vec.hxx>
#include <NCollection_List.hxx>
#include <TCollection_AsciiString.hxx>
#include <Quantity_ColorRGBA.hxx>
//! Generic light source definition.
//! This class defines arbitrary light source - see Graphic3d_TypeOfLightSource enumeration.
//! Some parameters are applicable only to particular light type;
//! calling methods unrelated to current type will throw an exception.
class Graphic3d_CLight : public Standard_Transient
{
DEFINE_STANDARD_RTTIEXT(Graphic3d_CLight, Standard_Transient)
public:
//! Empty constructor, which should be followed by light source properties configuration.
Standard_EXPORT Graphic3d_CLight (Graphic3d_TypeOfLightSource theType);
//! Copy parameters from another light source excluding source type.
Standard_EXPORT void CopyFrom (const Handle(Graphic3d_CLight)& theLight);
//! Returns the Type of the Light, cannot be changed after object construction.
Graphic3d_TypeOfLightSource Type() const { return myType; }
//! Returns light source name; empty string by default.
const TCollection_AsciiString& Name() const { return myName; }
//! Sets light source name.
void SetName (const TCollection_AsciiString& theName) { myName = theName; }
//! Returns the color of the light source; WHITE by default.
const Quantity_Color& Color() const { return myColor.GetRGB(); }
//! Defines the color of a light source by giving the basic color.
Standard_EXPORT void SetColor (const Quantity_Color& theColor);
//! Check that the light source is turned on; TRUE by default.
//! This flag affects all occurrences of light sources, where it was registered and activated;
//! so that it is possible defining an active light in View which is actually in disabled state.
Standard_Boolean IsEnabled() const { return myIsEnabled; }
//! Change enabled state of the light state.
//! This call does not remove or deactivate light source in Views/Viewers;
//! instead it turns it OFF so that it just have no effect.
Standard_EXPORT void SetEnabled (Standard_Boolean theIsOn);
//! Return TRUE if shadow casting is enabled; FALSE by default.
//! Has no effect in Ray-Tracing rendering mode.
Standard_Boolean ToCastShadows() const { return myToCastShadows; }
//! Enable/disable shadow casting.
Standard_EXPORT void SetCastShadows (Standard_Boolean theToCast);
//! Returns true if the light is a headlight; FALSE by default.
//! Headlight flag means that light position/direction are defined not in a World coordinate system, but relative to the camera orientation.
Standard_Boolean IsHeadlight() const { return myIsHeadlight; }
//! Alias for IsHeadlight().
Standard_Boolean Headlight() const { return myIsHeadlight; }
//! Setup headlight flag.
Standard_EXPORT void SetHeadlight (Standard_Boolean theValue);
//! @name positional/spot light properties
public:
//! Returns location of positional/spot light; (0, 0, 0) by default.
const gp_Pnt& Position() const { return myPosition; }
//! Setup location of positional/spot light.
Standard_EXPORT void SetPosition (const gp_Pnt& thePosition);
//! Returns location of positional/spot light.
void Position (Standard_Real& theX,
Standard_Real& theY,
Standard_Real& theZ) const
{
theX = myPosition.X();
theY = myPosition.Y();
theZ = myPosition.Z();
}
//! Setup location of positional/spot light.
void SetPosition (Standard_Real theX, Standard_Real theY, Standard_Real theZ) { SetPosition (gp_Pnt (theX, theY, theZ)); }
//! Returns constant attenuation factor of positional/spot light source; 1.0f by default.
//! Distance attenuation factors of reducing positional/spot light intensity depending on the distance from its position:
//! @code
//! float anAttenuation = 1.0 / (ConstAttenuation() + LinearAttenuation() * theDistance + QuadraticAttenuation() * theDistance * theDistance);
//! @endcode
Standard_ShortReal ConstAttenuation() const { return myParams.x(); }
//! Returns linear attenuation factor of positional/spot light source; 0.0 by default.
//! Distance attenuation factors of reducing positional/spot light intensity depending on the distance from its position:
//! @code
//! float anAttenuation = 1.0 / (ConstAttenuation() + LinearAttenuation() * theDistance + QuadraticAttenuation() * theDistance * theDistance);
//! @endcode
Standard_ShortReal LinearAttenuation() const { return myParams.y(); }
//! Returns the attenuation factors.
void Attenuation (Standard_Real& theConstAttenuation,
Standard_Real& theLinearAttenuation) const
{
theConstAttenuation = ConstAttenuation();
theLinearAttenuation = LinearAttenuation();
}
//! Defines the coefficients of attenuation; values should be >= 0.0 and their summ should not be equal to 0.
Standard_EXPORT void SetAttenuation (Standard_ShortReal theConstAttenuation,
Standard_ShortReal theLinearAttenuation);
//! @name directional/spot light additional properties
public:
//! Returns direction of directional/spot light.
gp_Dir Direction() const { return gp_Dir (myDirection.x(), myDirection.y(), myDirection.z()); }
//! Sets direction of directional/spot light.
Standard_EXPORT void SetDirection (const gp_Dir& theDir);
//! Returns the theVx, theVy, theVz direction of the light source.
void Direction (Standard_Real& theVx,
Standard_Real& theVy,
Standard_Real& theVz) const
{
theVx = myDirection.x();
theVy = myDirection.y();
theVz = myDirection.z();
}
//! Sets direction of directional/spot light.
void SetDirection (Standard_Real theVx, Standard_Real theVy, Standard_Real theVz) { SetDirection (gp_Dir (theVx, theVy, theVz)); }
//! Returns location of positional/spot/directional light, which is the same as returned by Position().
const gp_Pnt& DisplayPosition() const { return myPosition; }
//! Setup location of positional/spot/directional light,
//! which is the same as SetPosition() but allows directional light source
//! (technically having no position, but this point can be used for displaying light source presentation).
Standard_EXPORT void SetDisplayPosition (const gp_Pnt& thePosition);
//! @name spotlight additional definition parameters
public:
//! Returns an angle in radians of the cone created by the spot; 30 degrees by default.
Standard_ShortReal Angle() const { return myParams.z(); }
//! Angle in radians of the cone created by the spot, should be within range (0.0, M_PI).
Standard_EXPORT void SetAngle (Standard_ShortReal theAngle);
//! Returns intensity distribution of the spot light, within [0.0, 1.0] range; 1.0 by default.
//! This coefficient should be converted into spotlight exponent within [0.0, 128.0] range:
//! @code
//! float aSpotExponent = Concentration() * 128.0;
//! anAttenuation *= pow (aCosA, aSpotExponent);"
//! @endcode
//! The concentration factor determines the dispersion of the light on the surface, the default value (1.0) corresponds to a minimum of dispersion.
Standard_ShortReal Concentration() const { return myParams.w(); }
//! Defines the coefficient of concentration; value should be within range [0.0, 1.0].
Standard_EXPORT void SetConcentration (Standard_ShortReal theConcentration);
//! @name Ray-Tracing / Path-Tracing light properties
public:
//! Returns the intensity of light source; 1.0 by default.
Standard_ShortReal Intensity() const { return myIntensity; }
//! Modifies the intensity of light source, which should be > 0.0.
Standard_EXPORT void SetIntensity (Standard_ShortReal theValue);
//! Returns the smoothness of light source (either smoothing angle for directional light or smoothing radius in case of positional light); 0.0 by default.
Standard_ShortReal Smoothness() const { return mySmoothness; }
//! Modifies the smoothing radius of positional/spot light; should be >= 0.0.
Standard_EXPORT void SetSmoothRadius (Standard_ShortReal theValue);
//! Modifies the smoothing angle (in radians) of directional light source; should be within range [0.0, M_PI/2].
Standard_EXPORT void SetSmoothAngle (Standard_ShortReal theValue);
//! Returns TRUE if maximum distance of point light source is defined.
bool HasRange() const { return myDirection.w() != 0.0f; }
//! Returns maximum distance on which point light source affects to objects and is considered during illumination calculations.
//! 0.0 means disabling range considering at all without any distance limits.
//! Has sense only for point light sources (positional and spot).
Standard_ShortReal Range() const { return myDirection.w(); }
//! Modifies maximum distance on which point light source affects to objects and is considered during illumination calculations.
//! Positional and spot lights are only point light sources.
//! 0.0 means disabling range considering at all without any distance limits.
Standard_EXPORT void SetRange (Standard_ShortReal theValue);
//! @name low-level access methods
public:
//! @return light resource identifier string
const TCollection_AsciiString& GetId() const { return myId; }
//! Packed light parameters.
const Graphic3d_Vec4& PackedParams() const { return myParams; }
//! Returns the color of the light source with dummy Alpha component, which should be ignored.
const Graphic3d_Vec4& PackedColor() const { return myColor; }
//! Returns direction of directional/spot light and range for positional/spot light in alpha channel.
const Graphic3d_Vec4& PackedDirectionRange() const { return myDirection; }
//! Returns direction of directional/spot light.
Graphic3d_Vec3 PackedDirection() const { return myDirection.xyz(); }
//! @return modification counter
Standard_Size Revision() const { return myRevision; }
//! Dumps the content of me into the stream
Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
private:
//! Access positional/spot light constant attenuation coefficient from packed vector.
Standard_ShortReal& changeConstAttenuation() { return myParams.x(); }
//! Access positional/spot light linear attenuation coefficient from packed vector.
Standard_ShortReal& changeLinearAttenuation() { return myParams.y(); }
//! Access spotlight angle parameter from packed vector.
Standard_ShortReal& changeAngle() { return myParams.z(); }
//! Access spotlight concentration parameter from packed vector.
Standard_ShortReal& changeConcentration() { return myParams.w(); }
private:
//! Generate unique object id.
void makeId();
//! Update modification counter.
void updateRevisionIf (bool theIsModified)
{
if (theIsModified)
{
++myRevision;
}
}
private:
Graphic3d_CLight (const Graphic3d_CLight& );
Graphic3d_CLight& operator= (const Graphic3d_CLight& );
protected:
TCollection_AsciiString myId; //!< resource id
TCollection_AsciiString myName; //!< user given name
gp_Pnt myPosition; //!< light position
Quantity_ColorRGBA myColor; //!< light color
Graphic3d_Vec4 myDirection; //!< direction of directional/spot light
Graphic3d_Vec4 myParams; //!< packed light parameters
Standard_ShortReal mySmoothness; //!< radius for point light or cone angle for directional light
Standard_ShortReal myIntensity; //!< intensity multiplier for light
const Graphic3d_TypeOfLightSource myType; //!< Graphic3d_TypeOfLightSource enumeration
Standard_Size myRevision; //!< modification counter
Standard_Boolean myIsHeadlight; //!< flag to mark head light
Standard_Boolean myIsEnabled; //!< enabled state
Standard_Boolean myToCastShadows;//!< casting shadows is requested
};
DEFINE_STANDARD_HANDLE(Graphic3d_CLight, Standard_Transient)
#endif // Graphic3d_CLight_HeaderFile
|
#include <iostream>
using namespace std;
int n, m;
char matrix[51][51];
int ans = 987654321;
int check(int iN, int iM){
int flag = (iN + iM) % 2;
char base = matrix[iN][iM];
int ret = 0;
for (int i = iN; i <= iN + 7; i++){
for (int j = iM; j <= iM + 7; j++){
if (((i + j) % 2 == flag && matrix[i][j] != base) ||
((i + j) % 2 != flag && matrix[i][j] == base))
{
ret++;
}
}
}
ret = (ret < 64 - ret) ? ret : 64 - ret;
return ret;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
cin >> matrix[i][j];
}
}
for (int i = 1; i <= n - 7; i++){
for (int j = 1; j <= m - 7; j++){
int tp = check(i, j);
if(ans > tp){
ans = tp;
}
}
}
cout << ans << '\n';
return 0;
}
|
#ifndef MESHLOADER_H
#define MESHLOADER_H
//--------------------------------------------------------------------------------------------------------------
#include "Mesh/mesh.h"
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
//--------------------------------------------------------------------------------------------------------------
/// @author Idris Miles
/// @version 1.0
/// @date 01/06/2017
//--------------------------------------------------------------------------------------------------------------
/// @class MeshLoader
/// @brief This class loads in models using ASSIMP behind the scenes
class MeshLoader
{
public:
/// @brief constructor
MeshLoader();
/// @brief Static method to load a moel into a vector of meshes
static std::vector<Mesh> LoadMesh(const std::string _meshFile);
};
//--------------------------------------------------------------------------------------------------------------
#endif // MESHLOADER_H
|
#ifndef __PLAYER_H__
#define __PLAYER_H__
#include "common.hpp"
#include "board.hpp"
#include "gametree.hpp"
#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
class Player {
public:
Player(Side side);
~Player();
Move *doMove(Move *opponentsMove, int msLeft);
Board *board; // Board used to store Othello game state
private:
Side side; // Stores the side (BLACK/WHITE) the player is on
Node *root; // Root of the game tree
};
#endif
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
int n, a[111], b[111];
LL f[1111111];
bool corr[1111111];
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i] >> b[i];
}
for (int i = 0; i < (1 << n); i++) {
corr[i] = true;
for (int j = 0; j < n; j++) if ((1 << j) & i) {
for (int k = 0; k < j; k++) if (!((1 << k) & i)) {
if (a[j] == a[k] && b[j] == b[k]) {
corr[i] = false;
break;
}
}
if (!corr[i]) break;
}
}
f[0] = 1;
for (int i = 0; i < (1 << n); ++i) {
for (int j = 0; j < n; j++) if (((1<<j) & i) == 0 && corr[(1 << j) | i]) {
f[(1 << j) | i] += f[i];
}
}
cout << f[(1 << n) - 1] << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef __SECURE_MIME_FUNCTIONS_H__
#define __SECURE_MIME_FUNCTIONS_H__
#ifdef _MIME_SUPPORT_
// This file defines the functions used to create
// the various MIME_Decoders for secure types, like PGP and S/MIME
class MIME_Multipart_Encrypted_Parameters;
class MIME_Security_Body;
MIME_Security_Body *CreatePGPDecoderL(MIME_ContentTypeID id, HeaderList &hdrs, URLType url_type);
MIME_Multipart_Encrypted_Parameters *CreatePGPEncParametersL(MIME_ContentTypeID id, HeaderList &hdrs, URLType url_type);
MIME_Decoder *CreateSecureMultipartDecoderL(MIME_ContentTypeID id, HeaderList &hdrs, URLType url_type);
#endif // _MIME_SUPPORT_
#endif
|
struct treeNode {
int val;
treeNode* parent;
treeNode* LeftChild;
treeNode* RightChild;
}
|
//Tugas Kendali Motor Servo
#include <Servo.h>
Servo servo1;//buat objek motor servo 1
Servo servo2; // buat objek motor servo 2
//maksimum 8 objek servo yang bisa dibuat dari library ini
int sudut= 0; //variabel untuk menyimpan sudut posisi servo
void setup()
{
servo1.attach(9);
servo2.attach(7);
}
void loop()
{
for(sudut = 0; sudut < 180; sudut += 1) {
servo1.write(sudut);
servo2.write(sudut);
delay(15);
}
for(sudut = 180; sudut>=1; sudut-=1){
servo1.write(sudut);
servo2.write(sudut);
delay(15);
}
}
|
#include "predict.h" // import file to test
#include <math.h>
#include <random>
#include "configfile.h"
#include "ut.hpp"
using namespace boost::ut;
using namespace boost::ut::bdd;
/**
* I went through the math and came up with a way to test.
* The motion model is defined as follows:
* \f[
* \vec{x}(t) = [x(t), y(t), \alpha(t)]^T \\
*
* \vec{x}'(t) = [V \cdot \cos(\alpha),
* V \cdot \sin(\alpha),
* V \cdot \frac{\sin(G)}{WB}]^T
* \f]
*
* Note in particular that \f$x'[2](t)\f$ is only dependent on the input \f$G(t)\f$.
* This means with a given \f$G(t)\f$ we can analytically derive the solution of \f$x[2](t)\f$ and then derive either \f$x(t)\f$ or \f$y(t)\f$.
* Let \f$G(t) = G\f$ be constant.
* Then we can solve
* \f[
* \begin{align}
* \alpha(t) &= \int_0^t V \cdot \sin(G) / WB \cdot dt \\
* &= t \cdot V \cdot \sin(G) / WB
* \end{align}
* \f]
*
* Now we can derive \f$x(t)\f$:
* \f[
* \begin{align}
* x(t) &= \int_0^t V \cdot cos(\alpha(t)) \cdot dt \\
* &= \int_0^t V \cdot cos(t \cdot V \cdot \sin(G) / WB) \cdot dt \\
* & \text{let } C = V \cdot \sin(G) / WB \text{ and substitute } s = t \cdot C \\
* &= \int_0^{t \cdot C} cos(s) \cdot ds \cdot 1/C \\
* &= \sin(s)[t \cdot C; 0] \cdot 1/C \\
* &= \sin(t \cdot C) \cdot 1/C
* \end{align}
* \f]
* Note that with a constant G, we expect the car to drive in a circle.
* Thus, assuming the car starts at \f$[0,0,0]^T\f$, let's calculate the time when x passes through zero again, i.e. either a half or a full circle has been made:
* \f[
* \begin{align}
* & x(t) \stackrel{!}{=} 0 \\
* \Leftrightarrow& \sin(t \cdot C) \cdot 1/C = 0 \\
* \Leftrightarrow& t \cdot C = k \cdot pi \\
* \Leftrightarrow& t = k \cdot \frac{\pi \cdot (WB)}{V \cdot \sin(G)} \text{ with } k \in\{1,2,\dots\}
* \end{align}
* \f]
* Note that the derivation for \f$y\f$ is basically the same.
* Thus, we can test the following:
* Speficy some \f$V, WB, G\f$, calculate the time t for a half, full and double cirlce and each time check \f$x\f$ and \f$y\f$ if they are close to the expected value.
* Note that because some basic Euler scheme is used, the precision will likely not be super high...
*/
int main() {
/*
"predict"_test = [] {
given("I have a particle at position (x=1,y=1,theta=pi/2)") = [] {
auto is_close = [](double lhs, double rhs) {
return fabs(lhs - rhs) < 1e-4;
};
auto is_approx = [](double lhs, double rhs) {
return fabs(lhs - rhs) < 2*1e-1;
};
SWITCH_PREDICT_NOISE = 0;
Vector3d initial_pos = {1, 1, M_PI/2};
Particle p;
initParticle(&p, 10, initial_pos);
when("I give a constant control (steering angle) and calculate the time it takes to drive half a circle") = [&] {
double Q[4] = {0, 0, 0, 0};
const double V = 1; //random()*1.0/RAND_MAX;
const double G = M_PI/4.;
auto time_per_half_circle = [V] (double G) { // note that static variables don't need to be captured
return 1 * (M_PI * WHEELBASE)/(V * sin(G));
};
double T = time_per_half_circle(G);
int k_per_half_circle = int( T * V / 0.01);
const double dt = T / k_per_half_circle; // make sure T is divisable by dt, and one timestep make about 1cm progress
then("Before moving, it's in the starting position") = [&] {
expect(that % is_close(p.xv[0], initial_pos[0]) == true) << "p.xv[0] = " << p.xv[0];
expect(that % is_close(p.xv[1], initial_pos[1]) == true) << "p.xv[1] = " << p.xv[1];
expect(that % is_close(p.xv[2], initial_pos[2]) == true) << "p.xv[2] = " << p.xv[2];
};
for (size_t i = 0; i < k_per_half_circle; i++) {
predict(&p, V, G, Q, WHEELBASE, dt);
}
then("After half a circle, the angle is opposite and the y values is the same again (but not he x value)!") = [&] {
expect(that % is_close(p.xv[0], initial_pos[0]) == false) << "p.xv[0] = " << p.xv[0];
expect(that % is_approx(p.xv[1], initial_pos[1]) == true ) << "p.xv[1] = " << p.xv[1];
expect(that % is_close(p.xv[2], -initial_pos[2]) == true ) << "p.xv[2] = " << p.xv[2];
};
for (size_t i = 0; i < k_per_half_circle; i++) {
predict(&p, V, G, Q, WHEELBASE, dt);
}
then("After another half a circle, x, y and the angle is the same as initial position") = [&] {
expect(that % is_close(p.xv[0], initial_pos[0]) == true);
expect(that % is_close(p.xv[1], initial_pos[1]) == true) << "p.xv[1] = " << p.xv[1];
expect(that % is_close(p.xv[2], initial_pos[2]) == true) << "p.xv[2] = " << p.xv[2];
};
for (size_t i = 0; i < k_per_half_circle; i++) {
predict(&p, V, G, Q, WHEELBASE, dt);
}
then("After one and a half circle, it's in the same pos as during the first test") = [&] {
expect(that % is_close(p.xv[0], initial_pos[0]) == false) << "p.xv[0] = " << p.xv[0];
expect(that % is_approx(p.xv[1], initial_pos[1]) == true) << "p.xv[1] = " << p.xv[1];
expect(that % is_close(p.xv[2], -initial_pos[2]) == true) << "p.xv[2] = " << p.xv[2];
};
};
delParticleMembers(&p);
};
};
*/
}
|
/*
* userList.cpp
*
* Created on: Apr 7, 2019
* Author: dgv130030
*/
#include <iostream>
#include <iomanip>
#include <utility>
#include <string>
#include "stack.h"
#include "userList.h"
bool userList::find(std::string userid) const
{
// return true if the user id exists and false otherwise
return ids.find(userid) != ids.end();
}
bool userList::add(const userEntry &entry)
{
bool result = false;
if ( !find(entry.getName()) )
{
// item was not found
// add it
auto insertResult = ids.insert(std::make_pair(entry.getName(), entry.getPassword()));
result = insertResult.second;
}
return result;
}
bool userList::erase(std::string userid)
{
auto numErased = ids.erase(userid);
return numErased != 0;
}
bool userList::update(const userEntry &entry)
{
bool result = false;
if ( find(entry.getName()) )
{
// item was found
// update it
ids[entry.getName()] = entry.getPassword();
result = true;
}
return result;
}
void userList::print(std::ostream &out) const
{
const int NAME_LEN = 20;
const int PASSWORD_LEN = 25;
out << std::setw(NAME_LEN) << "User id";
out << std::setw(PASSWORD_LEN) << "Password" << std::endl;
for (const auto &elem : ids)
{
out << std::setw(NAME_LEN) << elem.first;
out << std::setw(PASSWORD_LEN) << elem.second << std::endl;
}
}
//In this member function, I had to create a stack and add the entries from the user id list to the stack
void userList::printReverse(std::ostream &out) const
{
//This is used to initialize the value for the name length and the password length
const int NAME_LENGTH = 20;
const int PASSWORD_LENGTH = 25;
//When the key part is retrieved from the map the type of object. So we get the first value and the second value
stack<std::pair<const std::string, std::string>> list;
for(const auto &elem : ids)
{;
list.push(elem);
}
out << std:: endl;
out << std::setw(NAME_LENGTH) << "User id";
out << std::setw(PASSWORD_LENGTH) << "Password" << std::endl;
//This is what occurs when the list is not empty
while(!list.empty())
{
const std::pair<const std::string, std::string> &next = list.top();
out << std::setw(NAME_LENGTH) << next.first;
out << std::setw(PASSWORD_LENGTH) << next.second << std::endl;
list.pop();
}
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Arjan van Leeuwen (arjanl)
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
#include "adjunct/m2/src/engine/store/mboxmonthly.h"
#include "adjunct/m2/src/engine/store/storemessage.h"
#include "modules/util/opfile/opfile.h"
/***********************************************************************************
** Fully update an existing message in the store (overwrites existing message)
**
** MboxMonthly::UpdateMessage
** @param message Message to update
** @param mbx_data Existing mbx_data from the store if there was any, 0 otherwise.
** Might be changed by this function to have new mbx_data.
** @return OpStatus::OK if save was successful, error codes otherwise
***********************************************************************************/
OP_STATUS MboxMonthly::UpdateMessage(StoreMessage& message,
INT64& mbx_data)
{
// Construct file - will be closed on destruction
OpFile file;
// Get sent time of message
time_t date;
RETURN_IF_ERROR(message.GetDateHeaderValue(Header::DATE, date));
// Prepare file for writing
RETURN_IF_ERROR(PrepareFile(file, message.GetId(), message.GetAccountId(), date, FALSE, mbx_data != 0));
// Go to correct position (if there already was mbx_data), which is past the from header - else write the from header
if (mbx_data != 0)
RETURN_IF_ERROR(file.SetFilePos(mbx_data));
else
RETURN_IF_ERROR(WriteFromLine(message, file));
// Set the mbx_data past the from header, start of the raw message
OpFileLength length;
RETURN_IF_ERROR(file.GetFilePos(length));
mbx_data = length;
// Write message to file
RETURN_IF_ERROR(WriteRawMessage(message, file));
// Close file, making sure it's written to disk
return file.SafeClose();
}
/***********************************************************************************
** Update the status of an existing message in the store
**
** MboxMonthly::UpdateMessageStatus
** @param message Message to update
** @param mbx_data Existing mbx_data from the store if there was any, 0 otherwise.
** Might be changed by this function to have new mbx_data.
** @return OpStatus::OK if save was successful, error codes otherwise
***********************************************************************************/
OP_STATUS MboxMonthly::UpdateMessageStatus(StoreMessage& message,
INT64& mbx_data)
{
OpFile file;
OpString8 buf;
time_t sent_date;
// Get sent time of message
RETURN_IF_ERROR(message.GetDateHeaderValue(Header::DATE, sent_date));
// Prepare file for reading and writing
RETURN_IF_ERROR(PrepareFile(file, message.GetId(), message.GetAccountId(), sent_date, FALSE, mbx_data));
// Write X-Opera-Status line
return WriteStatusLine(message, file);
}
/***********************************************************************************
** Get a message from the store
**
** MboxMonthly::GetMessage
** @param mbx_data mbx_data that was saved with the message
** @param message Where to place the message if found, prefilled with ID, account
** ID and sent date
** @return OpStatus::OK if message was found and retrieved,
** OpStatus::ERR_FILE_NOT_FOUND if not found, error codes otherwise
***********************************************************************************/
OP_STATUS MboxMonthly::GetMessage(INT64 mbx_data,
StoreMessage& message,
BOOL override)
{
OpFile file;
// Get time of message
time_t date;
RETURN_IF_ERROR(message.GetDateHeaderValue(Header::DATE, date));
// Prepare file for reading
RETURN_IF_ERROR(PrepareFile(file, message.GetId(), message.GetAccountId(), date, TRUE, mbx_data));
// Read message from file
return ReadRawMessage(message, file, override);
}
/***********************************************************************************
** Remove a message from the store
**
** MboxMonthly::RemoveMessage
** @param mbx_data mbx_data that was saved with the message
** @param id Message to remove
** @param account_id Account of this message
** @param sent_date Time when message was sent
** @param draft Whether this was a draft
** @return OpStatus::OK if delete was successful or if message didn't exist, error
** codes otherwise
***********************************************************************************/
OP_STATUS MboxMonthly::RemoveMessage(INT64 mbx_data,
message_gid_t id,
UINT16 account_id,
time_t sent_date,
BOOL draft)
{
// TODO: implement
return OpStatus::OK;
}
/***********************************************************************************
** Prepare a file for reading or writing
**
** MboxMonthly::PrepareFile
**
***********************************************************************************/
OP_STATUS MboxMonthly::PrepareFile(OpFile& file,
message_gid_t id,
UINT16 account_id,
time_t sent_date,
BOOL read_only,
INT64 mbx_data)
{
OpString filename;
// Get the filename
RETURN_IF_ERROR(GetFilename(id, account_id, sent_date, filename));
// Construct file
RETURN_IF_ERROR(file.Construct(filename.CStr()));
// If we have mbx_data, file has to exist
if (mbx_data != 0)
{
BOOL exists;
RETURN_IF_ERROR(file.Exists(exists));
if (!exists)
return OpStatus::ERR_FILE_NOT_FOUND;
}
// Setup file mode: read for read-only, read-write if we're changing an existing
// message, append if this is a new message
int mode = OPFILE_READ;
if (!read_only)
{
if (mbx_data != 0)
mode |= OPFILE_WRITE;
else
mode = OPFILE_APPEND;
}
// Open file
RETURN_IF_ERROR(file.Open(mode));
// Go to right position in file
if (mbx_data != 0)
RETURN_IF_ERROR(file.SetFilePos(mbx_data));
return OpStatus::OK;
}
/***********************************************************************************
** Gets the file path for a specific message
**
** MboxMonthly::GetFilename
**
***********************************************************************************/
OP_STATUS MboxMonthly::GetFilename(message_gid_t id,
UINT16 account_id,
time_t sent_date,
OpString& filename)
{
filename.Empty();
// Get date details
struct tm* time = op_gmtime(&sent_date);
if (!time)
{
sent_date = 0; // fallback to 1970, date was probably before 1970.
time = op_gmtime(&sent_date);
if (!time)
return OpStatus::ERR;
}
// Make filename
OpString mail_folder;
RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_MAIL_FOLDER, mail_folder));
return filename.AppendFormat(UNI_L("%s%cstore%caccount%d%c%d-%02d.mbs"),
m_store_path.HasContent() ? m_store_path.CStr() : mail_folder.CStr(),
PATHSEPCHAR,
PATHSEPCHAR, account_id,
PATHSEPCHAR, time->tm_year + 1900,
time->tm_mon + 1);
}
#endif // M2_SUPPORT
|
#include<stdio.h>
struct node
{
int x; //城市编号
int s; //转机次数
};
int main()
{
struct node que[2501];
int e[51][51] = {0}, book[51] = {0};
int head, tail;
int i, j, n, m, a, b, cur, start, end, flag = 0;
scanf("%d %d %d %d", &n, &m, &start, &end);
//初始化二维矩阵
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
if(i == j) e[i][j] = 0;
else e[i][j] = 999999999;
//读入城市之间的航班
for(i = 1; i <= m; i++)
{
scanf("%d %d", &a, &b);
//注意这里是无向图
e[a][b] = 1;
e[b][a] = 1;
}
//队列初始化
head = 1;
tail = 1;
//从start号城市出发,将start号城市加入队列
que[tail].x = start;
que[tail].s = 0;
tail++;
book[start] = 1; //标记start号城市已在队列中
//当队列不为空的时候循环
while(head < tail)
{
cur = que[head].x; //当前队列中首城市的编号
for(j = 1; j <= n; j++)
{
//从城市cur到城市j是否有航班并判断城市j是否已经在队列中
if(e[cur][j] != 99999999&&book[j] == 0)
{
//如果从城市cur到城市j有航班并且城市j不在队列中,则将城市j入队
que[tail].x = j;
que[tail].s = que[head].s + 1; //转机次数加一
tail++;
//标记这个城市j已经在队列中
book[j] = 1;
}
//如果达到目标城市,停止扩展,任务结束,退出循环
if(que[tail-1].x == end)
{
//注意下面两句话的位置不能颠倒
flag = 1;
break;
}
}
if(flag == 1)
break;
head++; //千万不要忘记当一个点扩展结束后,head++才能扩展下一个点
}
//打印队列中末尾最后一个目标城市的转机次数
//注意tail是指向队列末尾的下一个位置,所以需要-1
printf("%d", que[tail-1].s);
getchar();
getchar();
return 0;
}
|
#include <iostream>
#include <vector>
using namespace std;
typedef vector<double> Vec;
typedef vector<Vec> Mat;
int main(){
int i, j, m, n;
cout << "Enter the number of rows in the matrix \n";
cin >> m;
cout << "Enter the number of columns in the matrix \n";
cin >> n;
// Allocate space for the vectors
Vec row(n);
Mat a;
cout << "Enter the matrix\n";
for (i = 0; i < m; i++){
for (j = 0; j < n; j++) {
cin >> row[j];
}
a.push_back(row);
}
}
|
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
if(nums.size()<3)
{
vector<vector<int>> v;
return v;
}
sort(nums.begin(),nums.end());
vector<vector<int>> result;
for(int i=0;i<nums.size()-2;++i)
{
int target=nums[i];
int pre=i+1,end=nums.size()-1;
while(pre<end)
{
if((nums[pre]+nums[end])==-target)
{
int temp1=nums[pre],temp2=nums[end];
result.push_back({target,nums[pre],nums[end]});
while (pre < end && nums[end] == temp1) pre++;
while (pre < end && nums[end] == temp2) end--;
}
else if((nums[pre]+nums[end])>-target)
{
end--;
}
else
{
pre++;
}
}
while (i + 1 < nums.size() && nums[i + 1] == nums[i])
i++;
}
return result;
}
};
|
//
// GameBegin.h
// GetFish
//
// Created by zhusu on 15/5/12.
//
//
#ifndef __GetFish__GameBegin__
#define __GetFish__GameBegin__
#include "cocos2d.h"
#include "ButtonWithSpriteManage.h"
#include "Fish.h"
USING_NS_CC;
class GameBegin : public CCLayer
{
public:
static const int DEAD_TYPE_NODEAD = 0;
static const int DEAD_TYPE_BACK = 1;
static const int DEAD_TYPE_TOGAME = 2;
static GameBegin* create(int score,int type,int fishID,int num,int tishi1,int tishi2);
virtual bool init(int score,int type,int fishID,int num,int tishi1,int tishi2);
GameBegin();
virtual ~GameBegin();
void touchesBegan(CCSet * touchs,CCEvent * event);
void touchesMoved(CCSet * touchs,CCEvent * event);
void touchesCancelled(CCSet * touchs,CCEvent * event);
void touchesEnded(CCSet * touchs,CCEvent * event);
CC_SYNTHESIZE(int, _dead, Dead);
protected:
ButtonWithSpriteManage* _buttons;
CCArmature* fish;
CCLabelAtlas* _score;
CCLabelAtlas* _num;
GameBegin* _begin;
};
#endif /* defined(__GetFish__GameBegin__) */
|
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int find(int l, int r,int n){
long long m = (l+r)/2;
if(m*m==n){
return m;
}
if(l>r){
return r;
}
if(m*m>n){
find(l,m-1,n);
}
else if(m*m<n){
find(m+1,r,n);
}
}
int main(){
int A;
cin>>A;
cout<<find(0,A,A);
}
|
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x;
cout<<"Enter a value for x:";
cin>>x;
int s = x * x;
cout<<"The Square Root of x:"<<s;
getch();
}
|
// Created on: 2004-11-23
// Created by: Pavel TELKOV
// Copyright (c) 2004-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
// The original implementation Copyright: (C) RINA S.p.A
#ifndef TObj_ReferenceIterator_HeaderFile
#define TObj_ReferenceIterator_HeaderFile
#include <TObj_LabelIterator.hxx>
/**
* This class provides an iterator by references of the object
* (implements TObj_ReferenceIterator interface)
*/
class TObj_ReferenceIterator : public TObj_LabelIterator
{
public:
/*
* Constructor
*/
//! Creates the iterator on references in partition
//! theType narrows a variety of iterated objects
Standard_EXPORT TObj_ReferenceIterator
(const TDF_Label& theLabel,
const Handle(Standard_Type)& theType = NULL,
const Standard_Boolean theRecursive = Standard_True);
protected:
/**
* Internal methods
*/
//! Shift iterator to the next object
virtual Standard_EXPORT void MakeStep() Standard_OVERRIDE;
Handle(Standard_Type) myType; //!< Type of objects to iterate on
public:
//! CASCADE RTTI
DEFINE_STANDARD_RTTIEXT(TObj_ReferenceIterator,TObj_LabelIterator)
};
//! Define handle class for TObj_ReferenceIterator
DEFINE_STANDARD_HANDLE(TObj_ReferenceIterator,TObj_LabelIterator)
#endif
#ifdef _MSC_VER
#pragma once
#endif
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename MatrixType> void miscMatrices(const MatrixType& m)
{
/* this test covers the following files:
DiagonalMatrix.h Ones.h
*/
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, 1, MatrixType::ColsAtCompileTime> RowVectorType;
Index rows = m.rows();
Index cols = m.cols();
Index r = ei_random<Index>(0, rows-1), r2 = ei_random<Index>(0, rows-1), c = ei_random<Index>(0, cols-1);
VERIFY_IS_APPROX(MatrixType::Ones(rows,cols)(r,c), static_cast<Scalar>(1));
MatrixType m1 = MatrixType::Ones(rows,cols);
VERIFY_IS_APPROX(m1(r,c), static_cast<Scalar>(1));
VectorType v1 = VectorType::Random(rows);
v1[0];
Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
square(v1.asDiagonal());
if(r==r2) VERIFY_IS_APPROX(square(r,r2), v1[r]);
else VERIFY_IS_MUCH_SMALLER_THAN(square(r,r2), static_cast<Scalar>(1));
square = MatrixType::Zero(rows, rows);
square.diagonal() = VectorType::Ones(rows);
VERIFY_IS_APPROX(square, MatrixType::Identity(rows, rows));
}
void test_miscmatrices()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( miscMatrices(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( miscMatrices(Matrix4d()) );
CALL_SUBTEST_3( miscMatrices(MatrixXcf(3, 3)) );
CALL_SUBTEST_4( miscMatrices(MatrixXi(8, 12)) );
CALL_SUBTEST_5( miscMatrices(MatrixXcd(20, 20)) );
}
}
|
#pragma once
#include <QWidget>
namespace Ui {
class AddAppraisedRangeForm;
}
class AppraisedRange;
class AddAppraisedRangeForm : public QWidget
{
Q_OBJECT
public:
explicit AddAppraisedRangeForm(QWidget *parent = 0);
~AddAppraisedRangeForm();
void setAppraisedRange(const AppraisedRange &appraisedRange);
AppraisedRange getAppraisedRange() const;
signals:
void editingFinished(const AppraisedRange &range);
private slots:
void onAddBtnClicked();
void onLowerBoundChanged(int value);
void onUpperBoundChanged(int value);
private:
AppraisedRange makeAppraisedRange() const;
Ui::AddAppraisedRangeForm *ui;
};
|
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
using namespace std;
#define PORT 8822
void die(char *s)
{
perror(s);
exit(1);
}
int main()
{
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
die("Socket Create error");
}
// server structure
struct sockaddr_in server, client;
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
// bind
if ((bind(sockfd, (struct sockaddr *)&server, sizeof(server))) == -1)
{
die("Bind error");
}
if (listen(sockfd, 5) < 0)
{
die("Connection Failure");
}
socklen_t cli = sizeof(client);
int newsock = accept(sockfd, (struct sockaddr *)&client, &cli);
int m;
char a[10];
bzero((char *)a, sizeof(a));
m = recv(newsock, a, 9, 0);
cout << "Number 1 is " << a;
char b[10];
bzero((char *)b, sizeof(b));
m = recv(newsock, b, 9, 0);
cout << "Number 2 is " << b;
char op[10];
bzero((char *)op, sizeof(op));
m = recv(newsock, op,9, 0);
cout << "operator :" << op;
float ans, n1, n2;
n1 = atof(a);
n2 = atof(b);
switch (op[0])
{
case '+':
{
char res[10];
bzero((char *)res, sizeof(res));
ans = n1 + n2;
sprintf(res, "%f", ans);
send(newsock, res, 9, 0);
}
break;
case '-':
{
char res[10];
bzero((char *)&res, sizeof(res));
ans = n1 - n2;
sprintf(res, "%f", ans);
send(newsock, res, 9, 0 );
break;
}
}
return 0;
}
|
#include "zerodisplaycomponentprovider.h"
using namespace std;
namespace sbg {
template<int n>
DisplayComponentProvider<n> makeZeroDisplayComponentProvier()
{
return {Vector<n, double>(), Vector<freedom(n), double>(), Vector<n, double>{1}};
}
template DisplayComponentProvider<2> makeZeroDisplayComponentProvier<2>();
template DisplayComponentProvider<3> makeZeroDisplayComponentProvier<3>();
}
|
#ifndef BOTTOMNAVIGATION_H
#define BOTTOMNAVIGATION_H
#include "bottombutton.h"
#include <QDesktopServices>
#include <QEvent>
#include <QHBoxLayout>
#include <QProcess>
#include <QUrl>
#include <QMap>
#include <DWidget>
#include <dimagebutton.h>
DWIDGET_USE_NAMESPACE
class BottomNavigation : public DWidget
{
Q_OBJECT
public:
explicit BottomNavigation(DWidget *parent = nullptr);
private slots:
void onButtonClicked();
protected:
bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE;
private:
QMap<DWidget*, QString> m_buttons;
};
#endif // BOTTOMNAVIGATION_H
|
/*
* Copyright (c) 2014, Majenko Technologies
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* * Neither the name of Majenko Technologies nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Slideshow
*
* Copy the folder "slides" from the "files" folder onto an SD card.
* This is meant to be run on a picLCD-35T
*/
#include <DSPI.h>
#include <TFT.h>
#include <SD.h>
#include <BMPFile.h>
// Configure the display
TFTPMP myPMP;
HX8357 tft(&myPMP);
void setup() {
analogWrite(PIN_BACKLIGHT, 255);
tft.initializeDevice();
tft.setRotation(0);
tft.fillScreen(Color::Black);
tft.setFont(Fonts::Topaz);
tft.setTextColor(Color::White, Color::Black);
tft.setCursor(0, 0);
tft.print("Initializing SD card...");
if (!SD.begin(PIN_SD_SS)) {
tft.print("failed");
while(1);
}
tft.println("OK");
}
void loop() {
File myFile = SD.open("/slides");
dir_t p;
myFile.seek(0);
while (myFile.readDir(&p)) {
if (p.name[0] == DIR_NAME_FREE) {
break;
}
if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') {
continue;
}
if (!DIR_IS_FILE_OR_SUBDIR(&p)) {
continue;
}
if (!strncmp((const char *)p.name+8, "BMP", 3)) {
char fn[15];
char fullPath[100];
dirToChar(p, fn);
sprintf(fullPath, "/slides/%s", fn);
File f = SD.open(fullPath);
BMPFile bmp(f);
uint32_t start = millis();
bmp.draw(&tft, 0, 0);
uint32_t end = millis();
uint32_t len = end - start;
tft.setCursor(0, 0);
tft.print(len);
f.close();
delay(5000);
}
}
myFile.close();
}
void dirToChar(dir_t &p, char *s) {
memset(s, 0, 14);
char *ptr = s;
for (int i = 0; i < 11; i++) {
if (p.name[i] == ' ') {
continue;
}
if (i == 8) {
*ptr++ = '.';
}
*ptr++ = p.name[i];
}
}
|
/************************************************************************
* @project : sloth
* @class : Line
* @version : v1.0.0
* @description : 存储一行文字
* @author : Oscar Shen
* @creat : 2017年2月27日21:42:05
* @revise :
************************************************************************
* Copyright @ OscarShen 2017. All rights reserved.
************************************************************************/
#pragma once
#ifndef SLOTH_LINE_HPP
#define SLOTH_LINE_HPP
#include <sloth.h>
#include "word.hpp"
namespace sloth {
class Line
{
private:
double m_MaxLength;
double m_SpaceSize;
std::shared_ptr<std::vector<std::shared_ptr<Word>>> m_Words;
double m_CurrentLineLength = 0.0;
public:
Line(double spaceWidth, double fontSize, double maxLength)
:m_SpaceSize(spaceWidth * fontSize), m_MaxLength(maxLength),
m_Words(new std::vector<std::shared_ptr<Word>>) {}
/***********************************************************************
* @description : 尝试在本行增加单词,如果长度不够则加载失败
* @author : Oscar Shen
* @creat : 2017年2月27日21:39:26
***********************************************************************/
bool tryToAddWord(std::shared_ptr<Word> word)
{
double anotherLength = word->getWordWidth();
anotherLength += m_Words->empty() ? 0 : m_SpaceSize;
if (m_CurrentLineLength + anotherLength <= m_MaxLength) {
m_Words->push_back(word);
m_CurrentLineLength += anotherLength;
return true;
}
return false;
}
inline double getMaxLength() const { return m_MaxLength; }
inline double getLineLength() const { return m_CurrentLineLength; }
inline std::shared_ptr<std::vector<std::shared_ptr<Word>>> getWords() { return m_Words; }
};
}
#endif // !SLOTH_LINE_HPP
|
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
//简化版:找规律,循环周期n=2*numRows-2,第一行和第numRows行,按照n间隔摆放
//其他行,每次摆放两个字符,分别按照n-2*(i-1)和2*(i-1)间隔摆放
if(numRows==1) return s;
string res;
int n=2*numRows-2;
for(int i=1;i<=numRows;i++)
{
int index=i-1;
if(i==1||i==numRows)
{
while(index<s.size())
{
res.push_back(s[index]);
index+=n;
}
}
else
{
while(index<s.size())
{
res.push_back(s[index]);
index+=n-2*(i-1);
if(index<s.size())
res.push_back(s[index]);
index+=2*(i-1);
}
}
}
return res;
}
};
class Solution1 {
public:
string convert(string s, int numRows) {
int len = s.size(); //字符串s的长度
int m = numRows; //输入的行号
int n = 2 * m - 2; //Z字循环的最小单元长度
if (m == 1) //输入的行号为1,直接返回s
return s;
int i, j, stride = 0; //stride为字符串s的下标按Z字行依次摆放的字符位置
string ret;
//按Z字摆放,依次读取m行
for (i = 1; i <= m; i++)
{
stride = i - 1;
//对于每一行,依次读取摆放的字符(字符位于s的位置是s[stride])添加到字符串ret的后面,stride下标小于字符串s的长度len
while (stride < len)
{
//第一行和第m行字符摆放的规律是字符所在s的位置下标每隔n取一次摆放
if (i == 1 || i == m)
{
ret.push_back(s[stride]);
stride += n;
}
//其他行字符摆放的规律是字符所在s的位置下标每隔n-2*(i-1)和2*(i-1)取两次摆放,n是循环的最小单元长度,i是行号
else
{
ret.push_back(s[stride]);
stride += n - 2 * (i - 1);
if (stride < len)
ret.push_back(s[stride]);
stride += 2 * (i - 1);
}
}
}
return ret;
}
};
int main()
{
Solution solute;
string s = "LEETCODEISHIRING";
int numRows = 4;
cout << solute.convert(s, numRows) << endl;
return 0;
}
|
#include<stdio.h>
#include<conio.h>
struct game
{
int ma;
char ten[50];
float tien;
char tacgia[100];
};
void them1maychoigame(game a[], int &n)
{
printf("nhap ma game: ");
scanf_s("%d", &a[n].ma);
printf("nhap ten: ");
gets_s(a[n].ten);
printf("nhap gia tien: ");
scanf_s("%f", &a[n].tien);
printf("nhap ten tac gia: ");
gets_s(a[n].tacgia);
}
void themnhieumaychoigame(game a[], int &n)
{
int m;
printf("ban muon them bao nhieu may choi game: ");
scanf_s("%d", &m);
for (int i = 0; i < n; i++)
{
printf("nhap ma game: ");
scanf_s("%d", &a[n].ma);
printf("nhap ten: ");
gets_s(a[n].ten);
printf("nhap gia tien: ");
scanf_s("%f", &a[n].tien);
printf("nhap ten tac gia: ");
gets_s(a[n].tacgia);
}
}
void main() {
game a;
int a = n;
int chon = 1, tieptuc;
do
{
printf("-------menu------\n");
printf("them 1 may choi game");
printf("them nhieu may choi game");
printf("chon chuc nang: ");
scanf_s("%d", chon);
switch (tieptuc)
{
case 0:return;
case 1:them1maychoigame(a, n);
break;
case 2:
break;
default:
break;
}
} while (chon != 0);
}
|
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
struct Node
{
int i;
Node* pLeft;
Node* pRight;
Node(int iIn) : i(iIn), pLeft(nullptr), pRight(nullptr) {}
};
void InsertToTree(Node*& pRoot, Node* pNew)
{
if (!pRoot)
{
pRoot = pNew;
return;
}
if (pNew->i <= pRoot->i)
InsertToTree(pRoot->pLeft, pNew);
else
InsertToTree(pRoot->pRight, pNew);
}
void PrintTree(Node* pRoot, int Level)
{
if (!pRoot)
return;
PrintTree(pRoot->pRight, Level + 1);
for (int i = 0; i < Level; i++)
cout << " ";
cout << pRoot->i << endl;
PrintTree(pRoot->pLeft, Level + 1);
}
int LargestSumOfNodes(Node* pRoot, vector<Node*>& branch) {
if (pRoot == nullptr)
return 0;
branch.push_back(pRoot);
int sum = pRoot->i;
if (pRoot->pLeft != nullptr && pRoot->pRight != nullptr) {
int leftSum = LargestSumOfNodes(pRoot->pLeft, branch);
int rightSum = LargestSumOfNodes(pRoot->pRight, branch);
if(leftSum > rightSum)
sum += leftSum;
else
sum += rightSum;
}
else if (pRoot->pLeft != nullptr)
sum += LargestSumOfNodes(pRoot->pLeft, branch);
else if (pRoot->pRight != nullptr)
sum += LargestSumOfNodes(pRoot->pRight, branch);
return sum;
}
void PrintBranchAndSum(Node* pRoot) {
vector<Node*> branch;
int largestSum = LargestSumOfNodes(pRoot, branch);
cout << "Branch with the largest sum is: ";
for (int j = 0; j < branch.size(); j++)
cout << branch[j]->i << " ";
cout << "-> SUM = " << largestSum;
}
void main()
{
int i;
Node* pRoot = nullptr;
while (true)
{
cin >> i;
if (i == 99)
break;
Node* p = new Node(i);
InsertToTree(pRoot, p);
}
PrintTree(pRoot, 1);
PrintBranchAndSum(pRoot);
}
|
#include "pch.h"
#include "Input_Keyboard.h"
KeyboardEvent::KeyboardEvent()
{
m_eventType = Event::Invalid;
m_key = 0u;
}
KeyboardEvent::KeyboardEvent(const Event type, const unsigned char key)
{
m_eventType = type;
m_key = key;
}
bool KeyboardEvent::isPressed() const
{
return m_eventType == Event::Pressed;
}
bool KeyboardEvent::isReleased() const
{
return m_eventType == Event::Released;
}
bool KeyboardEvent::isValid() const
{
return m_eventType != Event::Invalid;
}
Event KeyboardEvent::getEvent() const
{
return m_eventType;
}
unsigned char KeyboardEvent::getKey() const
{
return m_key;
}
Keyboard::Keyboard()
{
for (int i = 0; i < 256; i++)
{
m_keyStatus[i] = false;
}
}
void Keyboard::onKeyPressed(const unsigned char key)
{
m_keyStatus[key] = true;
m_keyBuffer.push(KeyboardEvent(Event::Pressed, key));
}
void Keyboard::onRelease(const unsigned char key)
{
m_keyStatus[key] = false;
m_keyBuffer.push(KeyboardEvent(Event::Released, key));
}
bool Keyboard::isKeyPressed(const unsigned char key) const
{
return m_keyStatus[key];
}
bool Keyboard::empty() const
{
return m_keyBuffer.empty();
}
std::queue<KeyboardEvent> Keyboard::getKeyBufferCopy()
{
return m_keyBuffer;
}
KeyboardEvent Keyboard::readKey()
{
if (m_keyBuffer.empty())
{
return KeyboardEvent();
}
else
{
KeyboardEvent inputEvent = m_keyBuffer.front();
m_keyBuffer.pop();
return inputEvent;
}
}
|
#include"BTree_head.h"
int main() {
system("color F0");
system("title 图书管理系统");
InitLibrary();
int i;
printf("——————————\n");
printf("图书管理系统\n");
printf("——————————\n");
while (1) {
printf("1:书本入库 2:借书 3:还书 4:清书 \n5:显示图书 6:查书 7:预约 8:时间链\n0:退出系统\n");
printf("——————————\n");
scanf_s("%d", &i);
printf("——————\n");
switch (i) {
case 0: return 0;
case 1: Business_1(); break;
case 2: Business_2(); break;
case 3: Business_3(); break;
case 4: Business_4(); break;
case 5: Business_5(); break;
case 6: Business_6(); break;
case 7: Business_7(); break;
case 8: Business_8(); break;
case 9: Business_9(); break;
default: break;
}
}
return 0;
}
|
/* leetcode 486
*
*
*
*/
#include <vector>
#include <deque>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> mem; // mem[left][right]: biggest numbers we can get in situation nums[left, right]
vector<int> sum; // sum[n]: sum between nums[0, n]
int helper(vector<int>& nums, int left, int right) { // biggest numbers in situation nums[left, right]
if (left == right) {
return nums[left];
}
if (mem[left][right] != -1)
return mem[left][right];
int total = sum[right] - sum[left] + nums[left]; // sum between nums[left, right]
int ans = max(total - helper(nums, left + 1, right), // if we i chose left, then you will get the biggest numbers in situation nums[left + 1, right]
// thus, the present numbers we get is total - helpers(nums, left + 1, right)
total - helper(nums, left, right-1)); // if we i chose right, then you will get the biggest numbers in situation nums[left, right - 1]
// thus, the present numbers we get is total - helpers(nums, left, right - 1)
return mem[left][right] = ans;
}
bool PredictTheWinner(vector<int>& nums) {
int n = nums.size();
mem.resize(n, vector<int>(n, -1));
sum.resize(n);
int t = 0;
for (int i = 0; i < nums.size(); ++i) {
t += nums[i];
sum[i] = t;
}
int total = sum.back();
int maxV = helper(nums, 0, n-1);
return maxV >= total-maxV;
}
};
/************************** run solution **************************/
bool _solution_run(vector<int>& nums)
{
Solution leetcode_486;
bool ans = leetcode_486.PredictTheWinner(nums);
return ans;
}
#ifdef USE_SOLUTION_CUSTOM
ListNode* _solution_custom(TestCases &tc)
{
return leetcode_2.addTwoNumbers(l1, l2);
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
#pragma once
#include "misc.h"
#include <QPushButton>
using namespace std;
enum combinations{ nothing, pair_r, double_pair, set_t, less_streit, big_streit, full_house, kare, poker };
class dice
{
private:
// цена кости
double value;
//псевдографическая модель
QString model;
QPushButton *diceButton;
public:
dice(int val = 1);
//ассоциировать с кнопкой
void shape_dice(QPushButton *button);
//изменение ценности кости вместе с моделью
void change_value(int val);
//узнать ценность
int getvalue() {return value;}
//изменить ценность
void editvalue(int vl) {value=vl;}
//вернуть указатель на кнопку
QPushButton* get_button() {return diceButton;}
};
|
#include "Client.h"
#include "Server.h"
#ifdef WIN32
#define EXPORT __declspec(dllexport)
#endif
extern "C"
{
struct NativeServer
{
Server * engine;
};
struct NativeClient
{
Client * engine;
};
struct NativeMsgArg
{
MsgArg * msg;
};
#pragma region Server
EXPORT
int __stdcall Server_Initialize(NativeServer server)
{
return server.engine->Initialize();
}
EXPORT
int __stdcall Server_Start(NativeServer server)
{
return server.engine->Start();
};
EXPORT
int __stdcall Server_Stop(NativeServer server)
{
return server.engine->Stop();
};
EXPORT
NativeServer __stdcall Server_Create(const char* prefix, const char* name)
{
NativeServer server;
server.engine = new Server(prefix, name);
return server;
}
EXPORT
void __stdcall Server_Destroy(NativeServer server)
{
delete server.engine;
};
EXPORT
bool __stdcall Server_RegisterCallbacks(NativeServer server,
CreateInterfaceCallback handle) {
server.engine->RegisterCreateInterface(handle);
return true;
}
EXPORT
bool __stdcall Server_AddInterfaceMember(
NativeServer server,
const char* name,
const char* inputSig,
const char* outSig,
const char* argNames,
int memberType) // 0 signal, 1 method
{
return server.engine->AddInterfaceMember(name, inputSig, outSig, argNames, memberType);
}
/* OLD
EXPORT
int __stdcall Server_SendSignal(
NativeServer server, NativeSignal signal) {
int ret = server.engine->Send(signal);
NativeSignal_Destroy(signal);
return ret;
}
*/
//
// Type dependant register functions for registering callbacks from managed code
//
/**
* DEPRECATED ?
*/
/*
EXPORT
bool __stdcall Server_RegisterTypeCallbacks(NativeServer server, SendStringArg arg) {
return server.engine->RegisterCallback<SendStringArg>(arg, AllJoynTypeId::ALLJOYN_STRING);
};
*/
EXPORT
void __stdcall Server_SetMethodHandler(NativeServer server, MethodCall func)
{
server.engine->SetMethodCall(func);
}
EXPORT
void __stdcall Server_SetSignalHandler(NativeServer server, SignalEvent func)
{
server.engine->SetSignalCall(func);
}
EXPORT
void __stdcall Server_RegisterMethodHandler(NativeServer server, const char * intfName)
{
QStatus st = server.engine->RegisterMethodHandler(intfName);
}
EXPORT
void __stdcall Server_RegisterSignalHandler(NativeServer server, const char * intfName)
{
QStatus st = server.engine->RegisterSignalHandler(intfName);
}
EXPORT
void __stdcall Server_SendSignal(NativeServer server, const char * intfName, MsgArg** msg, int numArgs)
{
server.engine->SendSignal(intfName, msg, numArgs);
}
#pragma endregion Server
#pragma region Client
EXPORT
int __stdcall Client_Start(NativeClient client)
{
return client.engine->Start();
};
EXPORT
int __stdcall Client_Initialize(NativeClient client)
{
return client.engine->Initialize();
};
EXPORT
int __stdcall Client_Stop(NativeClient client)
{
return client.engine->Stop();
};
EXPORT
NativeClient __stdcall Client_Create(const char * prefix, const char * name)
{
NativeClient client;
client.engine = new Client(prefix, name);
return client;
}
EXPORT
void __stdcall Client_Destroy(NativeClient client)
{
delete client.engine;
};
EXPORT
bool __stdcall Client_AddInterfaceMember(
NativeClient client,
const char* name,
const char* inputSig,
const char* outSig,
const char* argNames,
int memberType) // 0 signal, 1 method
{
return client.engine->AddInterfaceMember(name, inputSig, outSig, argNames, memberType);
}
EXPORT
bool __stdcall Client_RegisterCreateInterface(NativeClient client,
CreateInterfaceCallback handle) {
client.engine->RegisterCreateInterface(handle);
return true;
}
EXPORT
const Message* __stdcall Client_CallMethod(NativeClient client, const char * member, MsgArg** msgs, int size)
{
return client.engine->CallMethod(member, msgs, size);
}
EXPORT
void __stdcall Client_SetSignalHandler(NativeClient client, SignalEvent func)
{
client.engine->SetSignalCall(func);
}
EXPORT
void __stdcall Client_RegisterSignalHandler(NativeClient client, const char * intfName)
{
QStatus st = client.engine->RegisterSignalHandler(intfName);
}
#pragma endregion Client
#pragma region Alljoyn Wrapper
/// AllJoyn wrapper for MsgArg and Message
EXPORT
const MsgArg* __stdcall MessageGetArg(Message * message, int index)
{
return (*message)->GetArg(index);
}
EXPORT
int __stdcall MessageGetSignature(Message * msg, char * buff)
{
const char * ret = (*msg)->GetSignature();
if (strlen(ret) != 0)
{
strncpy(buff, ret, 1024);
return strlen(buff) + 1;
}
return 0;
}
#pragma region MsgArgConstructors
EXPORT
const NativeMsgArg __stdcall CreateMsgArgShort(short val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("n", val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgInt(int val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("i", val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgLong(long val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("x", val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgShortUInt(uint16_t val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("q", val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgUInt(uint32_t val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("u", val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgLongUInt(uint64_t val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("t", val);
return nMsgArg;
}
EXPORT
NativeMsgArg __stdcall CreateMsgArgDouble(double val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("d", val);
return nMsgArg;
}
EXPORT
NativeMsgArg __stdcall CreateMsgArgBool(bool val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("b", val);
return nMsgArg;
}
EXPORT
NativeMsgArg __stdcall CreateMsgArgString(const char * val)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("s", val);
nMsgArg.msg->Stabilize();
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgShortArray(short* val, int numArgs)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("an", numArgs, val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgIntArray(int* val, int numArgs)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("ai", numArgs, val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgLongArray(long long* val, int numArgs)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("ax", numArgs, val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgShortUIntArray(uint16_t* val, int numArgs)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("aq", numArgs, val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgUIntArray(uint32_t* val, int numArgs)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("au", numArgs, val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgLongUIntArray(uint64_t* val, int numArgs)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("at", numArgs, val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgDoubleArray(double* val, int numArgs)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("ad", numArgs, val);
return nMsgArg;
}
EXPORT
const NativeMsgArg __stdcall CreateMsgArgBoolArray(bool* val, int numArgs)
{
NativeMsgArg nMsgArg;
nMsgArg.msg = new MsgArg("ab", numArgs, val);
return nMsgArg;
}
#pragma endregion
#pragma region MsgArgGetters
EXPORT
int __stdcall MsgArgGetStringPtr(const MsgArg* msg, char *buff)
{
const char * c = msg->v_string.str;
strncpy(buff, c, 1024);
return strlen(buff) + 1;
}
EXPORT
int __stdcall MsgArgGetShort(MsgArg* mess)
{
return mess->v_int16;
}
EXPORT
int __stdcall MsgArgGetInt(MsgArg* mess)
{
return mess->v_int32;
}
EXPORT
long long __stdcall MsgArgGetLong(MsgArg* mess)
{
return mess->v_int64;
}
EXPORT
int __stdcall MsgArgGetShortUInt(MsgArg* mess)
{
return mess->v_uint16;
}
EXPORT
int __stdcall MsgArgGetUInt(MsgArg* mess)
{
return mess->v_uint32;
}
EXPORT
long long __stdcall MsgArgGetLongUInt(MsgArg* mess)
{
return mess->v_uint64;
}
EXPORT
double __stdcall MsgArgGetDouble(MsgArg* msg)
{
double val;
msg->Get("d", &val);
return val;
}
EXPORT
int __stdcall MsgArgGetBool(MsgArg* msg)
{
bool val;
msg->Get("b", &val);
return val;
}
EXPORT
int __stdcall MsgArgGetNumArguments(MsgArg* msg, const char * type)
{
size_t numArg = 0;
void * val;
msg->Get(type, &numArg, &val);
return numArg;
}
EXPORT
int __stdcall MsgArgGetDoubleArray(MsgArg* msg, double * values)
{
double* msgValues;
size_t numArg;
QStatus s = msg->Get("ad", &numArg, &msgValues);
for (size_t i = 0; i < numArg; i++)
{
values[i] = msgValues[i];
}
return (int)s;
}
EXPORT
int __stdcall MsgArgGetShortArray(MsgArg* msg, short * values)
{
short* msgValues;
size_t numArg;
QStatus s = msg->Get("an", &numArg, &msgValues);
for (size_t i = 0; i < numArg; i++)
values[i] = msgValues[i];
return (int)s;
}
EXPORT
int __stdcall MsgArgGetIntArray(MsgArg* msg, int * values)
{
int* msgValues;
size_t numArg;
QStatus s = msg->Get("ai", &numArg, &msgValues);
for (size_t i = 0; i < numArg; i++)
values[i] = msgValues[i];
return (int)s;
}
EXPORT
int __stdcall MsgArgGetLongArray(MsgArg* msg, long long* values)
{
long long* msgValues;
size_t numArg;
QStatus s = msg->Get("ax", &numArg, &msgValues);
for (size_t i = 0; i < numArg; i++)
values[i] = msgValues[i];
return (int)s;
}
EXPORT
int __stdcall MsgArgGetShortUIntArray(MsgArg* msg, uint16_t * values)
{
uint16_t* msgValues;
size_t numArg;
QStatus s = msg->Get("aq", &numArg, &msgValues);
for (size_t i = 0; i < numArg; i++)
values[i] = msgValues[i];
return (int)s;
}
EXPORT
int __stdcall MsgArgGetUIntArray(MsgArg* msg, uint32_t * values)
{
uint32_t* msgValues;
size_t numArg;
QStatus s = msg->Get("au", &numArg, &msgValues);
for (size_t i = 0; i < numArg; i++)
values[i] = msgValues[i];
return (int)s;
}
EXPORT
int __stdcall MsgArgGetLongUIntArray(MsgArg* msg, uint64_t * values)
{
uint64_t* msgValues;
size_t numArg;
QStatus s = msg->Get("at", &numArg, &msgValues);
for (size_t i = 0; i < numArg; i++)
values[i] = msgValues[i];
return (int)s;
}
EXPORT
int __stdcall MsgArgGetBoolArray(MsgArg* msg, bool * values)
{
bool* msgValues;
size_t numArg;
QStatus s = msg->Get("ab", &numArg, &msgValues);
for (size_t i = 0; i < numArg; i++)
values[i] = msgValues[i];
return (int)s;
}
#pragma endregion
#pragma endregion AllJoyn Wrapper
//
// List of types that ARE SUPPORTED so far.
//
//ALLJOYN_STRING = 's', ///< AllJoyn UTF-8 NULL terminated string basic type
//
// List of types that ARE NOT SUPPORTED so far.
//
//ALLJOYN_ARRAY = 'a', ///< AllJoyn array container type
//ALLJOYN_BOOLEAN = 'b', ///< AllJoyn boolean basic type, @c 0 is @c FALSE and @c 1 is @c TRUE - Everything else is invalid
//ALLJOYN_DOUBLE = 'd', ///< AllJoyn IEEE 754 double basic type
//ALLJOYN_DICT_ENTRY = 'e', ///< AllJoyn dictionary or map container type - an array of key-value pairs
//ALLJOYN_SIGNATURE = 'g', ///< AllJoyn signature basic type
//ALLJOYN_HANDLE = 'h', ///< AllJoyn socket handle basic type
//ALLJOYN_INT32 = 'i', ///< AllJoyn 32-bit signed integer basic type
//ALLJOYN_INT16 = 'n', ///< AllJoyn 16-bit signed integer basic type
//ALLJOYN_OBJECT_PATH = 'o', ///< AllJoyn Name of an AllJoyn object instance basic type
//ALLJOYN_UINT16 = 'q', ///< AllJoyn 16-bit unsigned integer basic type
//ALLJOYN_STRUCT = 'r', ///< AllJoyn struct container type
//ALLJOYN_UINT64 = 't', ///< AllJoyn 64-bit unsigned integer basic type
//ALLJOYN_UINT32 = 'u', ///< AllJoyn 32-bit unsigned integer basic type
//ALLJOYN_VARIANT = 'v', ///< AllJoyn variant container type
//ALLJOYN_INT64 = 'x', ///< AllJoyn 64-bit signed integer basic type
//ALLJOYN_BYTE = 'y', ///< AllJoyn 8-bit unsigned integer basic type
//ALLJOYN_STRUCT_OPEN = '(', /**< Never actually used as a typeId: specified as ALLJOYN_STRUCT */
//ALLJOYN_STRUCT_CLOSE = ')', /**< Never actually used as a typeId: specified as ALLJOYN_STRUCT */
//ALLJOYN_DICT_ENTRY_OPEN = '{', /**< Never actually used as a typeId: specified as ALLJOYN_DICT_ENTRY */
//ALLJOYN_DICT_ENTRY_CLOSE = '}', /**< Never actually used as a typeId: specified as ALLJOYN_DICT_ENTRY */
//ALLJOYN_BOOLEAN_ARRAY = ('b' << 8) | 'a', ///< AllJoyn array of booleans
//ALLJOYN_DOUBLE_ARRAY = ('d' << 8) | 'a', ///< AllJoyn array of IEEE 754 doubles
//ALLJOYN_INT32_ARRAY = ('i' << 8) | 'a', ///< AllJoyn array of 32-bit signed integers
//ALLJOYN_INT16_ARRAY = ('n' << 8) | 'a', ///< AllJoyn array of 16-bit signed integers
//ALLJOYN_UINT16_ARRAY = ('q' << 8) | 'a', ///< AllJoyn array of 16-bit unsigned integers
//ALLJOYN_UINT64_ARRAY = ('t' << 8) | 'a', ///< AllJoyn array of 64-bit unsigned integers
//ALLJOYN_UINT32_ARRAY = ('u' << 8) | 'a', ///< AllJoyn array of 32-bit unsigned integers
//ALLJOYN_INT64_ARRAY = ('x' << 8) | 'a', ///< AllJoyn array of 64-bit signed integers
//ALLJOYN_BYTE_ARRAY = ('y' << 8) | 'a', ///< AllJoyn array of 8-bit unsigned integers
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,p=1;
cin>>n;
int a[n];
cout<<"Enter Elements";
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
for(int j=0;j<n;j++)
{
if(a[j]==a[j+1])
cout<<a[j]<<" ";
}
for(int k=0;k<=n;k++)
{
if(a[k]==p)
p++;
else
cout<<p<<' ';
}
return 0;
}
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
const int N = 1e5;
#define SIEVE
vector<int> pr(N,1);
vector<int> primes;
// cout << pr[0] << endl;
pr[0] = 0;
pr[1] = 0;
void sieve() {
for(int i=2; i*i<N; i++) {
if(pr[i] == 1) {
for(int j=i*i; j<N; j+=i) {
pr[j] = 0;
}
}
}
for(int i=0; i<N; i++) {
if(pr[i] == 1) {
primes.push_back(i);
}
}
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
int t;
cin >> t;
while(t--) {
int d;
cin >> d;
int x = *upper_bound(primes.begin(), primes.end(), d+1);
int y = *upper_bound(primes.begin(), primes.end(), x + d -1);
cout << x*y << endl;
}
return 0;
}
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
int n, t;
LD f[555][555], p[555], q[555];
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
cin >> n >> t;
for (int i = 0; i < n; i++) cin >> p[i];
for (int i = 0; i < n; i++) cin >> q[i];
for (int i = 0; i <= t; i++) f[n][i] = 1.;
for (int i = n - 1; i >= 0; i--) {
for (int j = t; j >= 0; j--) {
LD res1 = p[i] * f[i + 1][j + 1];
LD res2 = (1. - p[i]) * q[i] * f[i][j + 2] +
p[i] * f[i + 1][j + 2];
f[i][j] = max(res1, res2);
}
}
cout.precision(15);
cout << fixed << f[0][0] << endl;
return 0;
}
|
class Solution1 {
public:
bool increasingTriplet(vector<int>& nums) {
int num1 = INT_MAX, num2 = INT_MAX;
for(int num : nums){
if(num1 >= num){
num1 = num;
}else if(num2 >= num){
num2 = num;
}else{
return true;
}
}
return false;
}
};
class Solution2 {
public:
bool increasingTriplet(vector<int>& nums) {
if(nums.size() < 3) return false;
int n = nums.size();
vector<int> forword(n,nums[0]),backword(n,nums[n-1]);
for(int i=1; i<n; ++i){
forword[i] = min(forword[i-1],nums[i]);
}
for(int i=n-2; i>=0; --i){
backword[i] = max(backword[i+1],nums[i]);
}
for(int i=0; i<n; ++i){
if(forword[i] < nums[i] && nums[i] < backword[i]){
return true;
}
}
return false;
}
};
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
struct point {
int s,t;
};
point a[110];
bool vis[110];
int main() {
int n,T = 1;
while (scanf("%d",&n) != EOF && n) {
memset(vis,0,sizeof(vis));
for (int i = 1;i <= n; i++) {
scanf("%d%d",&a[i].s,&a[i].t);
a[i].s *= 2;a[i].t *= 2;
}
int ans = 0;
for (int i = 16;i < 48; i++) {
int loc = 0,ed = 49;
for (int j = 1;j <= n; j++) {
if (!vis[j] && i >= a[j].s && i < a[j].t && a[j].t < ed) {loc = j;ed = a[j].t;}
}
if (loc) {
vis[loc] = true;
ans++;
}
}
printf("On day %d Emma can attend as many as %d parties.\n",T++,ans);
}
return 0;
}
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Gogul Balakrishnan, Akash Lal
// University of Wisconsin, Madison.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// 3. Neither the name of the University of Wisconsin, Madison nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// e-mail: bgogul@cs.wisc.edu, akash@cs.wisc.edu
//
//////////////////////////////////////////////////////////////////////////////
#pragma warning (disable: 4786)
#include "ARSemiring.hpp"
#include "ModuleSpace.hpp"
#include "AffineRels.hpp"
namespace AR {
bool ARSemiring::exact_equality = true;
//-------------------------------------------
// For Nick's wpds implementation
//--------------------------------------------
//---------------------------------------------------------------
// semiring for wpds
//----------------------------------------------------------------
ARSemiring* ARSemiring::_one=new ARSemiring(new ModuleSpace(AR::dim,true), 1);
ARSemiring* ARSemiring::_zero=new ARSemiring(new ModuleSpace(AR::dim), 1);
//--------------------------------------
// Constructor
//--------------------------------------
ARSemiring::ARSemiring(ModuleSpace *_p_vs,unsigned c):p_vs(_p_vs), count(c) {
}
//--------------------------------------
// Destructor
//--------------------------------------
ARSemiring::~ARSemiring() {
}
//-----------------------------------------
// return the zero element of the semring
//-----------------------------------------
ARSemiring *ARSemiring::zero() {
return _zero;
}
//-----------------------------------------
// return one of the semring
//-----------------------------------------
ARSemiring *ARSemiring::one() {
return _one;
}
//----------------------------
//
//----------------------------
ModuleSpace *ARSemiring::vs() {
// FIXME: It is dangerous to lose control of a pointer, when it is
// ref counted. The safe thing would be to return "const ModuleSpace*" here.
// However, most of the ModuleSpace functions (even queries like isEmpty())
// need to invoke findBasis() that changes the object. Therefore, it is not
// possible to return "const ModuleSpace*" here! Be careful about how you use
// the pointer.
return p_vs.get_ptr();
}
//-----------------------------------------
// extend
//-----------------------------------------
ARSemiring *ARSemiring::extend(ARSemiring *op2) {
return new ARSemiring(op2->p_vs->compose(p_vs.get_ptr()));
}
//-----------------------------------------
// combine
//-----------------------------------------
ARSemiring *ARSemiring::combine(ARSemiring *op2) {
return new ARSemiring(this->p_vs->join(op2->p_vs.get_ptr()));
}
ARSemiring* ARSemiring::quasiOne() const{
return ARSemiring::one();
}
//---------------------------------------------
// this-op2
//---------------------------------------------
ARSemiring *ARSemiring::diff(ARSemiring *op2) const {
ModuleSpace* diffValue=this->p_vs->diff(op2->p_vs.get_ptr());
return new ARSemiring(diffValue);
}
//-----------------------------------------
// are the two elements equal?
//-----------------------------------------
bool ARSemiring::equal(ARSemiring *op2) const {
bool isequal = false;
if( exact_equality ) {
isequal=p_vs->isExactEqual(op2->p_vs.get_ptr());
}
else {
isequal=p_vs->isEqual(op2->p_vs.get_ptr());
}
return isequal;
}
//-----------------------------------------
// print to the given ostream
//-----------------------------------------
std::ostream &ARSemiring::print(std::ostream &os) const {
if(this==_one) {
os << "O #\n";
return os;
}
if(this==_zero) {
os << "Z #\n";
return os;
}
p_vs->prettyPrint(os);
return os;
}
} // namespace AR
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.