text
stringlengths 8
6.88M
|
|---|
/**
* Copyright (c) 2014, 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 "environ_vtab.hh"
#include <stdlib.h>
#include <string.h>
#include "base/auto_mem.hh"
#include "base/lnav_log.hh"
#include "config.h"
extern char** environ;
const char* const ENVIRON_CREATE_STMT = R"(
-- Access lnav's environment variables through this table.
CREATE TABLE environ (
name TEXT PRIMARY KEY,
value TEXT
);
)";
struct env_vtab {
sqlite3_vtab base;
sqlite3* db;
};
struct env_vtab_cursor {
sqlite3_vtab_cursor base;
char** env_cursor;
};
static int vt_destructor(sqlite3_vtab* p_svt);
static int
vt_create(sqlite3* db,
void* pAux,
int argc,
const char* const* argv,
sqlite3_vtab** pp_vt,
char** pzErr)
{
env_vtab* p_vt;
/* Allocate the sqlite3_vtab/vtab structure itself */
p_vt = (env_vtab*) sqlite3_malloc(sizeof(*p_vt));
if (p_vt == nullptr) {
return SQLITE_NOMEM;
}
memset(&p_vt->base, 0, sizeof(sqlite3_vtab));
p_vt->db = db;
*pp_vt = &p_vt->base;
int rc = sqlite3_declare_vtab(db, ENVIRON_CREATE_STMT);
return rc;
}
static int
vt_destructor(sqlite3_vtab* p_svt)
{
env_vtab* p_vt = (env_vtab*) p_svt;
/* Free the SQLite structure */
sqlite3_free(p_vt);
return SQLITE_OK;
}
static int
vt_connect(sqlite3* db,
void* p_aux,
int argc,
const char* const* argv,
sqlite3_vtab** pp_vt,
char** pzErr)
{
return vt_create(db, p_aux, argc, argv, pp_vt, pzErr);
}
static int
vt_disconnect(sqlite3_vtab* pVtab)
{
return vt_destructor(pVtab);
}
static int
vt_destroy(sqlite3_vtab* p_vt)
{
return vt_destructor(p_vt);
}
static int vt_next(sqlite3_vtab_cursor* cur);
static int
vt_open(sqlite3_vtab* p_svt, sqlite3_vtab_cursor** pp_cursor)
{
env_vtab* p_vt = (env_vtab*) p_svt;
p_vt->base.zErrMsg = nullptr;
env_vtab_cursor* p_cur = (env_vtab_cursor*) new env_vtab_cursor();
if (p_cur == nullptr) {
return SQLITE_NOMEM;
} else {
*pp_cursor = (sqlite3_vtab_cursor*) p_cur;
p_cur->base.pVtab = p_svt;
p_cur->env_cursor = environ;
}
return SQLITE_OK;
}
static int
vt_close(sqlite3_vtab_cursor* cur)
{
env_vtab_cursor* p_cur = (env_vtab_cursor*) cur;
/* Free cursor struct. */
delete p_cur;
return SQLITE_OK;
}
static int
vt_eof(sqlite3_vtab_cursor* cur)
{
env_vtab_cursor* vc = (env_vtab_cursor*) cur;
return vc->env_cursor[0] == nullptr;
}
static int
vt_next(sqlite3_vtab_cursor* cur)
{
env_vtab_cursor* vc = (env_vtab_cursor*) cur;
if (vc->env_cursor[0] != nullptr) {
vc->env_cursor += 1;
}
return SQLITE_OK;
}
static int
vt_column(sqlite3_vtab_cursor* cur, sqlite3_context* ctx, int col)
{
env_vtab_cursor* vc = (env_vtab_cursor*) cur;
const char* eq = strchr(vc->env_cursor[0], '=');
switch (col) {
case 0:
sqlite3_result_text(ctx,
vc->env_cursor[0],
eq - vc->env_cursor[0],
SQLITE_TRANSIENT);
break;
case 1:
sqlite3_result_text(ctx, eq + 1, -1, SQLITE_TRANSIENT);
break;
}
return SQLITE_OK;
}
static int
vt_rowid(sqlite3_vtab_cursor* cur, sqlite_int64* p_rowid)
{
env_vtab_cursor* p_cur = (env_vtab_cursor*) cur;
*p_rowid = (int64_t) p_cur->env_cursor[0];
return SQLITE_OK;
}
static int
vt_best_index(sqlite3_vtab* tab, sqlite3_index_info* p_info)
{
return SQLITE_OK;
}
static int
vt_filter(sqlite3_vtab_cursor* p_vtc,
int idxNum,
const char* idxStr,
int argc,
sqlite3_value** argv)
{
return SQLITE_OK;
}
static int
vt_update(sqlite3_vtab* tab,
int argc,
sqlite3_value** argv,
sqlite_int64* rowid)
{
const char* name
= (argc > 2 ? (const char*) sqlite3_value_text(argv[2]) : nullptr);
env_vtab* p_vt = (env_vtab*) tab;
int retval = SQLITE_ERROR;
if (argc != 1
&& (argc < 3 || sqlite3_value_type(argv[2]) == SQLITE_NULL
|| sqlite3_value_type(argv[3]) == SQLITE_NULL
|| sqlite3_value_text(argv[2])[0] == '\0'))
{
tab->zErrMsg = sqlite3_mprintf(
"A non-empty name and value must be provided when inserting an "
"environment variable");
return SQLITE_ERROR;
}
if (name != nullptr && strchr(name, '=') != nullptr) {
tab->zErrMsg = sqlite3_mprintf(
"Environment variable names cannot contain an equals sign (=)");
return SQLITE_ERROR;
}
if (sqlite3_value_type(argv[0]) != SQLITE_NULL) {
int64_t index = sqlite3_value_int64(argv[0]);
const char* var = (const char*) index;
const char* eq = strchr(var, '=');
size_t namelen = eq - var;
char name[namelen + 1];
memcpy(name, var, namelen);
name[namelen] = '\0';
unsetenv(name);
retval = SQLITE_OK;
} else if (name != nullptr && getenv(name) != nullptr) {
#ifdef SQLITE_FAIL
int rc;
rc = sqlite3_vtab_on_conflict(p_vt->db);
switch (rc) {
case SQLITE_FAIL:
case SQLITE_ABORT:
tab->zErrMsg = sqlite3_mprintf(
"An environment variable with the name '%s' already exists",
name);
return rc;
case SQLITE_IGNORE:
return SQLITE_OK;
case SQLITE_REPLACE:
break;
default:
return rc;
}
#endif
}
if (name != nullptr && argc == 4) {
const unsigned char* value = sqlite3_value_text(argv[3]);
setenv((const char*) name, (const char*) value, 1);
return SQLITE_OK;
}
return retval;
}
static sqlite3_module vtab_module = {
0, /* iVersion */
vt_create, /* xCreate - create a vtable */
vt_connect, /* xConnect - associate a vtable with a connection */
vt_best_index, /* xBestIndex - best index */
vt_disconnect, /* xDisconnect - disassociate a vtable with a connection */
vt_destroy, /* xDestroy - destroy a vtable */
vt_open, /* xOpen - open a cursor */
vt_close, /* xClose - close a cursor */
vt_filter, /* xFilter - configure scan constraints */
vt_next, /* xNext - advance a cursor */
vt_eof, /* xEof - inidicate end of result set*/
vt_column, /* xColumn - read data */
vt_rowid, /* xRowid - read data */
vt_update, /* xUpdate - write data */
nullptr, /* xBegin - begin transaction */
nullptr, /* xSync - sync transaction */
nullptr, /* xCommit - commit transaction */
nullptr, /* xRollback - rollback transaction */
nullptr, /* xFindFunction - function overloading */
};
int
register_environ_vtab(sqlite3* db)
{
auto_mem<char, sqlite3_free> errmsg;
int rc;
rc = sqlite3_create_module(db, "environ_vtab_impl", &vtab_module, nullptr);
ensure(rc == SQLITE_OK);
if ((rc = sqlite3_exec(
db,
"CREATE VIRTUAL TABLE environ USING environ_vtab_impl()",
nullptr,
nullptr,
errmsg.out()))
!= SQLITE_OK)
{
fprintf(stderr, "unable to create environ table %s\n", errmsg.in());
}
return rc;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2002-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 ES_UTILS_ESSCHED_H
#define ES_UTILS_ESSCHED_H
#include "modules/ecmascript_utils/esthread.h"
#include "modules/ecmascript/ecmascript.h"
class ES_Runtime;
class Window;
class ES_ThreadScheduler
{
public:
static ES_ThreadScheduler *Make(ES_Runtime *runtime, BOOL always_enabled = FALSE, BOOL is_dom_runtime = FALSE);
/**< Create a scheduler running threads with the specified runtime. The
created scheduler object is owned by the called and must be freed
using the delete operator.
@param runtime The runtime. MUST NOT be NULL.
@param always_enabled If TRUE, this scheduler will always be
enabled, regardless of preferences.
@param is_dom_runtime If TRUE, the scheduler's runtime is guaranteed to be
a DOM runtime.
@return A thread scheduler or NULL on OOM. */
virtual ~ES_ThreadScheduler();
/**< Destructor. When called, the scheduler MUST have no runnable tasks.
That should be achieved by terminating the scheduler by adding a
terminating action or by calling ES_ThreadScheduler::RemoveThreads(TRUE). */
#ifdef ESUTILS_SYNCIF_SUPPORT
virtual OP_STATUS ExecuteThread(ES_Thread *thread, unsigned timeslice, BOOL leave_thread_alive) = 0;
/**< Execute thread until it finishes, or fail if it hasn't
finished in the time allowed by the timeslice parameter.
If the thread becomes blocked (except if
blocked by an interrupting thread) it is cancelled and this call fails.
The thread to execute should not be added to the scheduler prior to
this call; it will be added implicitly first in the queue of runnable
threads by this function, and always removed before this call returns.
@param thread Thread to execute.
@param timeslice The maximum amount of time to execute scripts before
returning in milliseconds. A script might execute
slightly longer than this since a single
uninterruptible operation might bring us over the
limit.
@param leave_thread_alive If the thread didn't complete, it would normally
be terminated but if this TRUE then it will be left as is ready
to be run again/more.
@return OpStatus::OK, OpStatus::ERR if the thread was cancelled either
because it hadn't finished when the timeslice ended or because
it became blocked and leave_thread_alive was FALSE,
or OpStatus::ERR_NO_MEMORY on OOM. */
#endif // ESUTILS_SYNCIF_SUPPORT
virtual OP_BOOLEAN AddRunnable(ES_Thread *new_thread, ES_Thread *interrupt_thread = NULL) = 0;
/**< Add an immediately runnable thread to the scheduler. A thread MUST
only be added to one scheduler, and would normally only be added once.
The scheduler assumes ownership of the thread and will delete it
immediately if it was not added to the scheduler (signalled by any
other return value than OpBoolean::IS_TRUE).
The interrupt thread, if not NULL, will be blocked during the execution
of the new thread. If the interrupt thread belongs to this scheduler,
the new thread will be added immediately before it in the list of
runnable threads, otherwise the interrupt thread will be blocked with
the block type ES_BLOCK_FOREIGN_THREAD.
@param new_thread The new, runnable thread. MUST NOT be NULL.
@param interrupt_thread Optional thread to interrupt.
@return OpStatus::ERR_NO_MEMORY, OpStatus::ERR (in case of invalid
arguments), OpBoolean::IS_TRUE if the thread was added
or else OpBoolean::IS_FALSE. */
virtual OP_STATUS AddTerminatingAction(ES_TerminatingAction *action, ES_Thread *interrupt_thread = NULL, ES_Thread *blocking_thread = NULL) = 0;
/**< Add a terminating action to this scheduler. This will add a terminating
thread to the scheduler if this is the first terminating action being
added. The scheduler will continue executing its current set of runnable
threads, then it will perform the terminating action(s).
The scheduler assumes ownership of the action and will delete it.
@param action A terminating action. MUST NOT be NULL.
@param interrupt_thread Optional thread that the terminating thread will
interrupt, if a new terminating thread is created
and added to the scheduler. The interrupt_thread
MUST NOT be a thread in this scheduler.
@param blocking_thread Optional thread which will block the
terminating thread until finished.
@return OpStatus::ERR_NO_MEMORY or OpStatus::OK. */
virtual BOOL TestTerminatingAction(BOOL final, BOOL conditional) = 0;
/**< Test if a terminating action with the given properties could be added
to the scheduler. Returns FALSE if the scheduler is already being
terminated by a terminating action that wouldn't be overridden.
@param final The 'final' property of the imaginary action to test with.
@param conditional The 'conditional' property of the action.
@return TRUE if the imaginary action would be added by a call to
AddTerminatingAction. */
virtual void RemoveThreads(BOOL terminating = FALSE, BOOL final = FALSE) = 0;
/**< Remove threads from the scheduler. If terminating is TRUE, it removes all
runnable threads. If final is TRUE is also removes all waiting threads.
If neither are TRUE, no threads are removed, but the scheduler stops
executing somewhat.
This function MUST NOT be called while the scheduler is active, except if
it is currently executing its terminating thread.
@param terminating If TRUE, remove runnable threads. Use this only when
there is no time to use a terminating action (e.g. when the
user closes a window to which this scheduler belongs).
@param final If TRUE, also remove waiting threads. Use this when the
scheduler will never be used again (that is, when its document
is being deleted rather than just being made inactive). */
virtual OP_STATUS MigrateThread(ES_Thread *thread) = 0;
/**< Migrate a running thread from its current scheduler to this one. Will
also migrate all threads that the thread has interrupted, while
cancelling any other threads that have interrupted those threads.
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */
virtual OP_STATUS CancelThreads(ES_ThreadType type) = 0;
/**< Cancel (by calling CancelThread()) all threads of given type.
@see CancelThread()
@param type A type of the thread to cancel. @see ES_ThreadType.
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY. Note: the threads are
cancelled and deleted regardless of the return value, only the
signalling to the threads can fail. */
virtual OP_STATUS CancelThread(ES_Thread *thread) = 0;
/**< Unconditionally cancel a thread in the scheduler. If the thread has been
interrupted, the interrupting thread(s) will be cancelled too, before
this thread.
@param thread A thread to cancel. MUST NOT be NULL, MUST be a thread added
to this scheduler (either runnable or waiting).
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY. Note: the thread is
cancelled and deleted regardless of the return value, only the
signalling to the thread can fail. */
virtual OP_STATUS CancelAllTimeouts(BOOL cancel_runnable, BOOL cancel_waiting) = 0;
/**< Cancels all timeout or interval threads.
@param cancel_runnable Whether to cancel timeout threads from runnable queue.
@param cancel_waiting Whether to cancel waiting threads.
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY (signals OOM only if
posting a delayed message fails.) */
virtual OP_STATUS CancelTimeout(unsigned id) = 0;
/**< Cancels the timeout or interval thread scheduled for execution.
The thread is identified by the id.
@param id The id of the timeout/interval thread to cancel.
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY in case of OOM */
virtual OP_STATUS Activate() = 0;
/**< (Re)activate the scheduler. Currently, this includes reactivating
timeout and interval threads that were active when the scheduler was
terminated and calling Reset().
@return OpStatus::ERR_NO_MEMORY or OpStatus::OK. */
virtual void Reset() = 0;
/**< Reset this scheduler to the state it was in when it was constructed.
This is necessary when a scheduler is being reused after being terminated
as it would otherwise refuse new threads. */
virtual void Block(ES_Thread *thread, ES_ThreadBlockType type = ES_BLOCK_UNSPECIFIED) = 0;
/**< Equivalent to "thread->Block(type)". See ES_Thread::Block().
@param thread The thread to block.
@param type The type (reason) of blocking. */
virtual OP_STATUS Unblock(ES_Thread *thread, ES_ThreadBlockType type = ES_BLOCK_UNSPECIFIED) = 0;
/**< Equivalent to "thread->Unblock(type)". See ES_Thread::Unblock().
@param thread The thread to unblock.
@param type The type (reason) of blocking.
@return OpStatus::ERR_NO_MEMORY, OpStatus::ERR (if type does not match
the argument to the last call to Block() for this thread) or
OpStatus::OK. */
virtual BOOL IsActive() = 0;
/**< Check if this scheduler is active (currently executing).
@return TRUE if this scheduler is currently executing a thread. */
virtual BOOL IsBlocked() = 0;
/**< Check if the current thread of this scheduler is blocked, i.e., if
this entire scheduler is blocked.
@return TRUE if this scheduler is blocked. */
virtual BOOL IsDraining() = 0;
/**< Check if this scheduler is being terminated, i.e., if it is currently
draining its list of runnable threads.
@return TRUE if this scheduler is being terminated. */
virtual BOOL HasRunnableTasks() = 0;
/**< Check if the scheduler has runnable threads. Note that having runnable
threads does not mean the scheduler can run right now. Runnable threads
are simply threads in the list of runnable threads, they can still be
blocked.
@return TRUE if the scheduler has runnable threads. */
virtual BOOL HasTerminatingThread() = 0;
/**< Check if scheduler has a terminating thread, i.e., if it is currently
being terminated.
@return TRUE if the scheduler has a terminating thread. */
virtual ES_TerminatingThread *GetTerminatingThread() = 0;
/**< Get the scheduler's terminating thread, if it has one.
@return A terminating thread or NULL. */
virtual ES_Runtime *GetRuntime() = 0;
/**< Get the scheduler's runtime.
@return A runtime. Can not NULL. */
virtual FramesDocument *GetFramesDocument() = 0;
/**< Get the scheduler's runtime's frames document, if there is one.
@return A frames document or NULL if the scheduler's runtime is not
associated with a document. */
virtual ES_TimerManager *GetTimerManager() = 0;
/**< Get the scheduler's timer manager.
@return A timer manager. Can not NULL. */
virtual ES_Thread *GetCurrentThread() = 0;
/**< Get the scheduler's current thread. When the scheduler is active,
this is the thread currently being executed. When the scheduler is
inactive, this is the thread that would be executed if the scheduler
became active right now, i.e., the first thread in the list of runnable
threads.
@return The current thread, or NULL if the list of runnable threads is
empty. */
virtual ES_Thread *SetOverrideCurrentThread(ES_Thread *thread) = 0;
/**< Temporarily override the return value of GetCurrentThread(). Typically
used when this scheduler (or rather its associated ES_Runtime) must
seem to be the active one, but actually isn't. To unset, another call
should be made with the return value of the call that set the override.
@return The previous override current thread, or NULL if there was no
override set before. Never returns the actual current thread
of this scheduler. */
virtual ES_Thread *GetErrorHandlerInterruptThread(ES_Runtime::ErrorHandler::ErrorType type) = 0;
/**< Get the thread that should be interrupted if the window.onerror error
handler is called, either for a compilation error or uncaught runtime
error. For runtime errors, the scheduler simply returns the currently
executing thread.
For compilation errors, callers of ES_Runtime::CompileProgram() needs
to use SetErrorHandlerInterruptThread() to set the appropriate thread
(if there is one) and ResetErrorHandlerInterruptThread() after the
call.
@param type Type of error being handled.
@return Thread to interrupt or NULL. */
virtual void SetErrorHandlerInterruptThread(ES_Thread *thread) = 0;
/**< Temporarily set thread to interrupt when calling the window.onerror
error handler. Caller must make sure to reset it again. Must be reset
before the thread could conceivably finish and die. */
virtual void ResetErrorHandlerInterruptThread() = 0;
/**< Reset the error handler interrupt thread. */
virtual const uni_char *GetThreadInfoString() = 0;
/**< Return a string describing the currently executing thread (used by
the JavaScript console when reporting errors). The returned string is
constant or stored in the buffer returned by g_memory_manager->GetTempBuf.
@return A informational string. */
virtual OP_STATUS GetLastError() = 0;
/**< Return the last error that was raised during the execution of a thread.
Only meant to be used from a thread listener that wants to know the
reason for a ES_SIGNAL_FAILED, its value in any other situation is
undefined.
@return An error code. */
virtual void ResumeIfNeeded() = 0;
/**< Something has changed that might affect whether this scheduler should
be executing scripts right now. Reevaluate, and if needed, resume
script execution (that is, post a message about it.) */
virtual void PushNestedActivation() = 0;
/**< Used by nested message loops to hide the fact that the scheduler is
already running in lower levels of nesting. That means that it's
possible that the scheduler is active when IsActive() is FALSE, but
in a lower level message loop. If that case is interesting then check
IsPresentOnTheStack().
Only to be used if IsActive() returns TRUE. */
virtual void PopNestedActivation() = 0;
/**< Used to balance calls to PushNestedActivation when nested message
loops unwind.
Since PushNestedActivation() is only called when IsActive() is TRUE, this
will result in IsActive() being TRUE. */
virtual BOOL IsPresentOnTheStack() = 0;
/**< Normally IsActive would be a good enough indication of whether the
scheduler is on the stack, but when we run nested message
loops this is one of the few objects
that might be present on the stack of the hidden message loops.
Use this method to see if that is the case and then act accordingly.
For instance deleting the object or running thread would be wrong. */
virtual OP_STATUS SerializeThreads(ES_Thread *execute_first, ES_Thread *execute_last) = 0;
/**< Block the thread 'execute_last' until the thread 'execute_first' has
finished if the threads are in different schedulers. If 'execute_last'
is canceled 'execute_first' will also be canceled unless it has been
migrated to a different scheduler. If 'execute_first' is canceled it is
no longer blocking 'execute_last'.
@return OpStatus::ERR_NO_MEMORY on OOM otherwise OpStatus::OK. */
virtual void GCTrace() = 0;
/**< Should be called by the owner of scheduler when the garbage collector
runs on the heap associated with the scheduler's runtime. The
scheduler propagates the call to its threads. */
};
#endif /* ES_UTILS_ESSCHED_H */
|
#ifndef WINDOWRECOGNIZER_HH_
#define WINDOWRECOGNIZER_HH_
#include "Window.hh"
#include "AudioInputController.hh"
#include "WidgetRecognitionArea.hh"
#include "WidgetComparisonArea.hh"
#include "WidgetStatus.hh"
#include "RecognizerListener.hh"
#include "RecognizerProcess.hh"
#include "RecognizerStatus.hh"
#include <pgbutton.h>
#include <pglabel.h>
#include <pgcheckbutton.h>
/** This is the most important gui class which controls the recognition process.
* It has a few child widgets for taking responsibility of some tasks. */
class WindowRecognizer : public Window
{
public:
WindowRecognizer(RecognizerProcess *recognizer);
virtual ~WindowRecognizer();
virtual void initialize();
protected:
virtual void do_opening();
virtual void do_running();
virtual void do_closing(int return_value);
/** Calculates the rect from the top part of the window according to the
* given indexes.
* \param column_index Column.
* \param row_index Row.
* \return The rectangle area of the window. */
PG_Rect calculate_button_rect(unsigned int column_index,
unsigned int row_index);
/** A function to automate the creation of ParaGUI buttons.
* \param label Text of the button.
* \param column_index Column of the button.
* \param row_index Row of the button.
* \param callback Callback function for the button.
* \return The created button. */
PG_Button* construct_button(const std::string &label,
unsigned int column_index,
unsigned int row_index,
const SigC::Slot0<bool> &callback);
/** Sends pause or unpause message to recognizer.
* \param enable true to unpause, false to pause. */
void enable_recognizer(bool enable);
// Callback functions for ParaGUI buttons.
bool handle_stop_button(); //!< Stop audio.
bool handle_record_button(); //!< Reset recognizer and start recording.
bool handle_recognize_button();
bool handle_pause_button();
bool handle_exit_button();
bool handle_resetrecog_button();
bool handle_pauserecog_button();
bool handle_settings_button();
bool handle_adaptation_button();
bool handle_resetadaptation_button();
bool handle_save_button();
bool handle_open_button();
bool handle_showadvanced_button();
bool handle_key_event(const SDL_KeyboardEvent *key);
/** Sets Pause button pressed (or unpressed) and calls the callback function.
* \param pause Whether to pause or unpause. */
void pause_audio_input(bool pause);
/** Sends reset message to recognizer, and optionally may also clear all
* audio data.
* \param reset_audio True if audio data should be cleared too. */
void reset(bool reset_audio);
/** Sends end audio message to recognizer and sets the gui according to that
* state. */
void end_of_audio();
/** Flushes the out queue to recognizer. Only this function should be used to
* flush the queue, because this has a proper broken pipe handling. */
void flush_out_queue();
/** Disables or enables the window, so it won't disturb e.g. child window.
* \param pause true to disable, false to enable.*/
virtual void pause_window_functionality(bool pause);
/** Handles broken pipe. Shows error message of the broken pipe and tries to
* restart the recognition process. If restart fails, sends quit signal.
* \return false if failed to restart. */
bool handle_broken_pipe();
RecognizerProcess *m_recog_proc; //!< Process and pipes to recognizer.
RecognizerStatus m_recog_status; //!< Recognition and status.
RecognizerListener m_recog_listener; //!< In queue parser.
/** Widget which contains time axis, wave and spectrogram views, recognition
* text, scroll bar and autoscroll radios. */
WidgetRecognitionArea *m_recognition_area;
/** Widget which contains reference and hypothesis text fields and some
* buttons for handling them. */
WidgetComparisonArea *m_comparison_area;
/** Widget which contains status texts for recognition and adaptation. */
WidgetStatus *m_status_bar;
private:
/** Some gui buttons in the top part of the window. */
PG_Button *m_record_button;
PG_Button *m_recognize_button;
PG_Button *m_stop1_button; // Both stop buttons are identical, they just
PG_Button *m_stop2_button; // have different location.
PG_Button *m_pause_button;
PG_Button *m_showadvanced_button;
PG_Button *m_adapt_button;
PG_Button *m_resetadapt_button;
PG_Button *m_pauserecog_button;
PG_Button *m_reset_button;
/** Flag to indicate that recognizer process is disconnected. */
bool m_broken_pipe;
/** Class to handle audio input and output. Sends the audio messages to
* out queue. Handles playback also. */
AudioInputController *m_audio_input;
};
#endif /*WINDOWRECOGNIZER_HH_*/
|
#include <gtest/gtest.h>
#include <vm/mix_generic_word.h>
namespace mix {
TEST(GenericWordTestSuite, set_positive_address) {
GenericWord<5> word;
word.set_address(70);
EXPECT_EQ(1, word.bytes[0]);
EXPECT_EQ(6, word.bytes[1]);
EXPECT_EQ(Sign::Positive, word.sign);
}
TEST(GenericWordTestSuite, set_negative_address) {
GenericWord<5> word;
word.set_address(-71);
EXPECT_EQ(1, word.bytes[0]);
EXPECT_EQ(7, word.bytes[1]);
EXPECT_EQ(Sign::Negative, word.sign);
}
TEST(GenericWordTestSuite, get_positive_address) {
GenericWord<5> word;
word.bytes[0] = 1;
word.bytes[1] = 6;
word.sign = Sign::Positive;
EXPECT_EQ(70, word.get_address());
}
TEST(GenericWordTestSuite, get_negative_address) {
GenericWord<5> word;
word.bytes[0] = 1;
word.bytes[1] = 7;
word.sign = Sign::Negative;
EXPECT_EQ(-71, word.get_address());
}
} // namespace mix
|
#ifndef _GameOverProc_H_
#define _GameOverProc_H_
#include "BaseProcess.h"
class GameOverProc :public BaseProcess
{
public:
GameOverProc();
virtual ~GameOverProc();
virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) ;
virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ;
};
#endif
|
#include "widget.h"
#include <QApplication>//包含应用程序类
//main函数程序入口
//arg命令行变量的数量 agv命令行变量数组
int main(int argc, char *argv[])
{
//a为应用程序对象
QApplication a(argc, argv);
//窗口对象
Widget w;
w.show();
//让a进入消息循环
return a.exec();
}
|
/** Kabuki SDK
@file /.../Source/Kabuki_SDK-Impl/_G/Scene.h
@author Cale McCollough
@copyright CopYright 2016 Cale McCollough ©
@license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt
*/
#pragma once
#include <string>
#include "LaYer.h"
#include "Entity.h"
namespace _G {
/** */
class _G_API Scene : public Layer
{
public:
Scene ();
Scene (const std::string& Description);
void Delete ();
void Draw (_G.Cell& C);
private:
Layer* head;
void DeconstructScene (Layer* L);
};
} //< namespace _G
|
#ifndef MyTruthAnalysis_HelperFunctions_H
#define MyTruthAnalysis_HelperFunctions_H
// xAOD
#include <xAODTruth/TruthParticle.h>
#include <xAODJet/JetContainer.h>
#include <xAODJet/Jet.h>
#include <exception>
namespace TruthAna
{
class TauIsNotFinalOrDecayNoNeutrino : public std::exception
{
};
constexpr float GeV = 1'000;
bool hasChild(const xAOD::TruthParticle *parent, const int absPdgId);
bool hasChild(const xAOD::TruthParticle *parent, const int absPdgId, std::vector<unsigned int> &indices);
bool isFromHiggs(const xAOD::TruthParticle *particle);
/// this uses TruthFlavour
bool isBJet(const xAOD::Jet *jet);
/// truth flavour is not available, this use dR matching to truth b partons
bool isDiBJet(const xAOD::Jet *fatjet, const xAOD::TruthParticle* b0, const xAOD::TruthParticle* b1);
bool isBTruth(const xAOD::TruthParticle *parton);
bool isTauTruth(const xAOD::TruthParticle *tau);
bool contains(const std::vector<int> &v, const std::size_t &element);
std::string printVec(const std::vector<int> &v, const std::string &message);
const xAOD::TruthParticle *getFinal(const xAOD::TruthParticle *particle);
void getFinalHelper(const xAOD::TruthParticle *particle, xAOD::TruthParticle *&final);
TLorentzVector tauVisP4(const xAOD::TruthParticle *tau);
bool isGoodEvent(); // TODO
bool isOS(const xAOD::TruthParticle *p0, const xAOD::TruthParticle *p1);
bool isGoodTau(const xAOD::TruthParticle *tau, double ptCut, double etaCut);
bool isGoodB(const xAOD::TruthParticle *b, double ptCut, double etaCut);
bool isNotOverlap(const xAOD::TruthParticle *b0, const xAOD::TruthParticle *b1, const xAOD::TruthParticle *tau0, const xAOD::TruthParticle *tau1, double minDR);
} // namespace TruthAna
#endif
|
#include <cstdlib>
#include <time.h>
#include "MazeGenerator.h"
#include "MazePointStack.h"
MazePointStack stack;
MazeGenerator::MazeGenerator(void)
{
srand(time(NULL));
}
MazeGenerator::~MazeGenerator(void)
{
}
int** MazeGenerator::getMaze() { return _maze; }
void MazeGenerator::generateNewMaze(int width, int height)
{
_width = width;
_height = height;
_maze = new int*[width];
_visited = new bool*[width];
for (int i = 0; i < width; ++i)
{
_maze[i] = new int[height];
_visited[i] = new bool[height];
}
for (int i = 0; i < width; i++)
for(int j = 0; j < height; j++)
{
_maze[i][j] = 1;
_visited[i][j] = false;
}
// Set starting point to 0,0 and set visited
_startPoint.setPoint(0, 0);
_maze[0][0] = 0;
_visited[0][0] = true;
_current = _startPoint;
pathForward(_startPoint);
}
MazePoint MazeGenerator::pathForward(MazePoint current)
{
MazePoint next = choosePath(current);
if (next.getX() != -1)
{
stack.push(current);
carvePath(current, next);
current = next;
return pathForward(current);
}
else if (!stack.isEmpty())
{
MazePoint prev;
prev = stack.pop();
current = prev;
return pathForward(current);
}
else
{
MazePoint end;
end.setPoint(0, 0);
return end;
}
}
void MazeGenerator::carvePath(MazePoint from, MazePoint to)
{
int dx = to.getX() - from.getX();
int dy = to.getY() - from.getY();
if (dx == -2)
dx = -1;
else if (dx == 2)
dx = 1;
if (dy == -2)
dy = -1;
else if (dy == 2)
dy = 1;
int midX = from.getX() + dx;
int midY = from.getY() + dy;
_maze[midX][midY] = 0;
_visited[midX][midY] = true;
}
MazePoint MazeGenerator::choosePath(MazePoint point)
{
MazePoint validPoint[4];
int counter = 0;
// West
if (point.getX() - 2 >= 0 && _visited[point.getX() - 2][point.getY()] == false)
validPoint[counter++].setPoint(point.getX() - 2, point.getY());
// East
if (point.getX() + 2 < _width && _visited[point.getX() + 2][point.getY()] == false)
validPoint[counter++].setPoint(point.getX() + 2, point.getY());
// South
if (point.getY() - 2 >= 0 && _visited[point.getX()][point.getY() - 2] == false)
validPoint[counter++].setPoint(point.getX(), point.getY() - 2);
// North
if (point.getY() + 2 < _height && _visited[point.getX()][point.getY() + 2] == false)
validPoint[counter++].setPoint(point.getX(), point.getY() + 2);
// No valid paths
if (counter == 0)
{
MazePoint n;
n.setPoint(-1, -1);
return n;
}
// Fill in rest?
while (counter < 4)
validPoint[counter++].setPoint(-1, -1);
int num, test;
MazePoint selected;
do
{
num = rand() % 4;
selected = validPoint[num];
test = selected.getX();
} while (validPoint[num].getX() == -1);
// mark as visited
_maze[selected.getX()][selected.getY()] = 0;
_visited[selected.getX()][selected.getY()] = true;
return selected;
}
|
#include<iostream>
#include "Poco/Net/HTMLForm.h"
#include "Poco/URI.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/StreamCopier.h"
#include "Poco/Net/NetException.h"
void pocoPost1()
{
Poco::Net::HTMLForm form1;
form1.add("abc","333");
form1.add("abc","222");
form1.write(std::cout);
}
void pocoPost2(const std::string &url, const std::string &key, const std::string &value)
{
Poco::URI purl(url);
try
{
Poco::Net::HTTPClientSession session( purl.getHost(), purl.getPort() );
session.setProxy("172.18.172.251",80);
Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, purl.getPath(), Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTMLForm form;
form.add(key, value);
// Send the request.
form.prepareSubmit(req);
std::ostream& ostr = session.sendRequest(req);
form.write(ostr);
Poco::Net::HTTPResponse res;
std::istream& istr = session.receiveResponse(res);
Poco::StreamCopier::copyStream(istr, std::cout);
std::cout<<std::endl;
}
catch(Poco::Net::NetException& ex)
{
std::cout<<"post wrong: "<<ex.displayText();
}
}
|
#pragma once
#include "plbase/PluginBase.h"
#include "CEntity.h"
#pragma pack(push, 4)
class PLUGIN_API CDummy : public CEntity {
public:
};
#pragma pack(pop)
VALIDATE_SIZE(CDummy, 0x38);
|
#include <iberbar/Paper2d/Transform.h>
iberbar::Paper2d::CNodeTransform::CNodeTransform()
: m_floatx_Anchor( 0.0f, 0.0f )
, m_floatx_Pivot( 0.0f, 0.0f )
, m_floatx_Position( 0.0f, 0.0f )
, m_floatx_ContentSize( 0.0f, 0.0f )
, m_floatx_Scaling( 1.0f, 1.0f )
, m_vec_Anchor()
, m_vec_Pivot()
, m_vec_Scaling()
, m_vec_Translation()
, m_mat_Transform( DirectX::XMMatrixIdentity() )
, m_mat_Transform_ForChildren( DirectX::XMMatrixIdentity() )
{
m_vec_Anchor = DirectX::XMLoadFloat2( &m_floatx_Anchor );
m_vec_Pivot = DirectX::XMLoadFloat2( &m_floatx_Pivot );
m_vec_Translation = DirectX::XMLoadFloat2( &m_floatx_Position );
m_vec_Scaling = DirectX::XMLoadFloat2( &m_floatx_Scaling );
}
|
#pragma once
#include "hardware/i2c.h"
#include "hardware/irq.h"
#ifdef __cplusplus
extern "C" {
#endif
void pi_alarm_init(uint alarm_num, irq_handler_t callback, uint32_t delay_us);
// declaring it static inline seems to fix the fluttering problems
static inline void pi_alarm_rearm(int alarm_num, uint32_t delay_us)
{
// Clear the alarm irq
hw_clear_bits(&timer_hw->intr, 1u << alarm_num);
//uint32_t delay_us = 2 * 1'000'000; // 2 secs
// Alarm is only 32 bits so if trying to delay more
// than that need to be careful and keep track of the upper
// bits
//uint64_t target = timer_hw->timerawl + delay_us;
// Write the lower 32 bits of the target time to the alarm which
// will arm it
//timer_hw->alarm[alarm_num] = (uint32_t) target;
timer_hw->alarm[alarm_num] = timer_hw->timerawl + delay_us;
}
typedef enum {INPUT, OUTPUT, INPUT_PULLUP, INPUT_PULLDOWN} pi_gpio_mode_e;
void pi_gpio_init(uint gpio, pi_gpio_mode_e mode);
void pi_gpio_high(uint gpio);
void pi_gpio_low(uint gpio);
void pi_gpio_out(uint gpio);
int pi_gpio_is_high(uint gpio);
void pi_gpio_toggle(uint gpio);
extern i2c_inst_t *pi_i2c_default_port;
void pi_i2c_init(int sda);
void pi_max7219_init(void);
void pi_max7219_show_count(int count);
void pi_max7219_tfr(uint8_t address, uint8_t value);
void pi_spi_init_std(void);
#ifdef __cplusplus
}
class GpioOut {
public:
GpioOut(uint gpio);
void on(void);
void off(void);
private:
uint m_gpio;
};
#endif // __cplusplus
|
/*
Copyright (c) 2014 Mircea Daniel Ispas
This file is part of "Push Game Engine" released under zlib license
For conditions of distribution and use, see copyright notice in Push.hpp
*/
#pragma once
#include "Math/Vector.hpp"
#include <cstdint>
namespace Push
{
class Touch
{
public:
enum class State
{
Unknown,
Began,
Moved,
Fixed,
Ended,
Canceled
};
public:
uint32_t m_id = 0;
State m_state = State::Unknown;
Vector m_currentPosition{0.f, 0.f};
Vector m_previousPosition{0.f, 0.f};
};
}
|
#include<bits/stdc++.h>
#define rep(i,n) for (int i =0; i <(n); i++)
using namespace std;
using ll = long long;
int main(){
int N,W;
cin >> N >> W;
//方針:まずは各時刻の配列を用意する
//入力を受け取ったら、Timetable[S]は加算、Timetable[T]をPだけ減算する
//累積和を取り、数字がWを超えたらNoを出力する
vector<int>Time_table(200100,0);
rep(i,N){
int S, T , P;
cin >> S >> T >> P;
Time_table[S] += P;
Time_table[T] -= P;
}
int now = 0;
//累積和を取る
vector<int>S(200100);
rep(i,200000){
now += Time_table[i];
if(now > W){
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
}
|
// task3.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include "pch.h"
#include <iostream>
#include <cstdio>
#include <time.h>
using namespace std;
int main(int argc, char *argv[])
{
int i = 0;
time_t Time = 0;// для sub и add
time_t Time1 = 0, Time2 = 0; // для diff
int operation = 0, aTime = 0;
//cout << argv[0] << ' ' << argv[1] << ' ' << argv[2] << ' ';
if (!strcmp(argv[1], "add") || !strcmp(argv[1], "sub")) {
Time = atoi(argv[3]);
if (!strcmp(argv[2], "day"))
Time *= 60 * 60 * 24;
else if (!strcmp(argv[2], "hour"))
Time *= 60 * 60;
else if (!strcmp(argv[2], "min"))
Time *= 60;
else cout << "Wrong time (use only day, hour, min, sec)";
}
time_t timer = 0;
struct tm *today = 0;
if (!strcmp(argv[1], "add")) {
time(&timer);
timer += Time;
today = localtime(&timer);
cout << asctime(today);
}
else if (!strcmp(argv[1], "sub")) {
time(&timer);
timer -= Time;
today = localtime(&timer);
cout << asctime(today);
}
else if (!strcmp(argv[1], "diff")) {
for (i = 2; i < argc; i++) {
int hour = 0, min = 0, sec = 0;
//Далее идет запись в вышеперечисленные переменные и проверка шаблона
if (sscanf(argv[i], "%2d:%2d:%2d", &hour, &min, &sec) != 3 || strlen(argv[i]) != 8
|| hour > 23 || min && sec > 59 || hour && min && sec < 0) {
cout << "Wrong time format (23:59:59 - max, 00:00:00 - min)";
return -1;
}
int diffsec = hour * 60 * 60 + min * 60 + sec;
if (i == 2) Time1 = diffsec;
else Time2 = diffsec;
}
timer = abs(Time1 - Time2);
cout << timer << endl;
}
if (timer < 0) { //Если меньше, чем 00 1 января 1970 года - выход
cout << "Can't get result" << endl;
return -1;
}
}
// Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
// Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
// Советы по началу работы
// 1. В окне обозревателя решений можно добавлять файлы и управлять ими.
// 2. В окне Team Explorer можно подключиться к системе управления версиями.
// 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
// 4. В окне "Список ошибок" можно просматривать ошибки.
// 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
// 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
|
#ifndef GAMELOGIC_H
#define GAMELOGIC_H
#include <vector>
#include "gamecell.h"
#include <unordered_map>
class GameLogic
{
public:
static void handleCellRevealed(std::vector<std::vector<GameCell*>> &gameBoard, GameCell* cell);
private:
static void addNeigbors(std::vector<std::vector<GameCell*>> &gameBoard, GameCell* cell,
std::unordered_map<int,GameCell*> &cellMap);
static int getHashCode(int row, int column);
};
#endif // GAMELOGIC_H
|
#include <iostream>
#include "shape.h"
#include"twoD.h"
using namespace std;
main(){
two2D o;
}
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.UX.PropertyAccessor.h>
namespace g{namespace Uno{namespace UX{struct PropertyObject;}}}
namespace g{namespace Uno{namespace UX{struct Selector;}}}
namespace g{struct app18_accessor_ButtonEntryMyCoupon_Category;}
namespace g{
// internal sealed class app18_accessor_ButtonEntryMyCoupon_Category :121
// {
::g::Uno::UX::PropertyAccessor_type* app18_accessor_ButtonEntryMyCoupon_Category_typeof();
void app18_accessor_ButtonEntryMyCoupon_Category__ctor_1_fn(app18_accessor_ButtonEntryMyCoupon_Category* __this);
void app18_accessor_ButtonEntryMyCoupon_Category__GetAsObject_fn(app18_accessor_ButtonEntryMyCoupon_Category* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval);
void app18_accessor_ButtonEntryMyCoupon_Category__get_Name_fn(app18_accessor_ButtonEntryMyCoupon_Category* __this, ::g::Uno::UX::Selector* __retval);
void app18_accessor_ButtonEntryMyCoupon_Category__New1_fn(app18_accessor_ButtonEntryMyCoupon_Category** __retval);
void app18_accessor_ButtonEntryMyCoupon_Category__get_PropertyType_fn(app18_accessor_ButtonEntryMyCoupon_Category* __this, uType** __retval);
void app18_accessor_ButtonEntryMyCoupon_Category__SetAsObject_fn(app18_accessor_ButtonEntryMyCoupon_Category* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin);
void app18_accessor_ButtonEntryMyCoupon_Category__get_SupportsOriginSetter_fn(app18_accessor_ButtonEntryMyCoupon_Category* __this, bool* __retval);
struct app18_accessor_ButtonEntryMyCoupon_Category : ::g::Uno::UX::PropertyAccessor
{
static ::g::Uno::UX::Selector _name_;
static ::g::Uno::UX::Selector& _name() { return _name_; }
static uSStrong< ::g::Uno::UX::PropertyAccessor*> Singleton_;
static uSStrong< ::g::Uno::UX::PropertyAccessor*>& Singleton() { return Singleton_; }
void ctor_1();
static app18_accessor_ButtonEntryMyCoupon_Category* New1();
};
// }
} // ::g
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL){}
};
int solve(TreeNode *node, int sum){
int sum = sum*10+node->val;
if(node == NULL) return 0;
if(node->right == NULL && node->left == NULL) return sum;
return solve(node->left,sum)+solve(node->right,sum)
}
int sumNumbers(TreeNode *root){
return solve(root,0);
}
int main(){
}
|
#include<cstdio>
#include<malloc.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
int a;
struct node *next;
};
void insert(struct node **ptr,int data)
{
struct node *newnode,*temp;
if(*ptr == NULL)
{
(*ptr) = (struct node *)malloc(sizeof(struct node));
(*ptr)->a = data;
(*ptr)->next = NULL;
}
else
{
temp = *ptr;
while(temp->next != NULL)
{
temp = temp->next;
}
newnode = (struct node*)malloc(sizeof(struct node));
newnode->a=data;
newnode->next=NULL;
temp->next = newnode;
}
}
struct node * operation(struct node **head_ref)
{
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
void display(struct node *ptr)
{
while(ptr !=NULL)
{
printf("%d \n",ptr->a);
ptr=ptr->next;
}
}
struct node *merge(struct node **a,struct node **b)
{
struct node *ans = *a;
while(ans->next!=NULL)
{
ans=ans->next;
}
ans->next=*b;
return *a;
}
int countnodes(struct node *p)
{
int cnt= 0;
if(p!=NULL)
{
cnt++;
p=p->next;
}
return cnt;
}
int main()
{
struct node *p,*temp,*ans,*temp1,*ans1;
p = NULL;
int i;
for(i=1;i<11;i++)
insert(&p,i);
struct node *t = p;
struct node *t1 = p;
display(p);
int k=4,ax=8;
int c = countnodes(p);
if(c==0)
printf("no nodes");
else
{
while(t1!=NULL && ax>1)
{t1=t1->next;
ax--;
}
temp1=t1->next;
t1->next=NULL;
// display(temp1);
while(t!=NULL && k>1)
{t=t->next;
k--;
}
temp=t->next;
t->next=NULL;
operation(&p);
// display(p);
operation(&temp);
// display(temp);
ans = merge(&p,&temp);
ans1 = merge(&ans,&temp1);
//ans->next=temp1;
display(ans1);
}
getch();
}
|
#pragma once
#include "CShader.h"
#include "TScopedResource.h"
#include "Noncopyable.h"
class CShader;
class CShaderResource : Noncopyable
{
public:
CShaderResource();
~CShaderResource();
bool Load(
void*& shader,
ID3D11InputLayout*& inputLayout,
ID3DBlob*& blob,
const char* filePath,
const char* entryFuncName,
CShader::EnType shaderType
);
/*!
*@brief 開放。
*@details
* 明示的なタイミングで開放したい場合に使用してください。
*/
void Release();
private:
struct SShaderProgram {
std::unique_ptr<char[]> program;
int programSize;
};
struct SShaderResource {
void* shader; //!<シェーダー。
ID3D11InputLayout* inputLayout; //!<入力レイアウト。
CShader::EnType type; //!<シェーダータイプ。
TScopedResource<ID3DBlob> blobOut;
};
typedef std::unique_ptr<SShaderResource> SShaderResourcePtr;
typedef std::unique_ptr<SShaderProgram> SShaderProgramPtr;
std::map<int, SShaderProgramPtr> m_shaderProgramMap; //!<読み込み済みのシェーダープログラムのマップ。
std::map<int, SShaderResourcePtr> m_shaderResourceMap; //!<シェーダーリソースのマップ
};
|
/*
* Copyright (c) 2016-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_PROBES_ENC_H_
#define CPPSORT_PROBES_ENC_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <functional>
#include <iterator>
#include <type_traits>
#include <utility>
#include <vector>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include <cpp-sort/utility/as_function.h>
#include <cpp-sort/utility/branchless_traits.h>
#include <cpp-sort/utility/functional.h>
#include <cpp-sort/utility/static_const.h>
#include "../detail/functional.h"
#include "../detail/iterator_traits.h"
#include "../detail/lower_bound.h"
namespace cppsort
{
namespace probe
{
namespace detail
{
template<typename ForwardIterator, typename T, typename Compare, typename Projection>
auto enc_lower_bound(std::vector<std::pair<ForwardIterator, ForwardIterator>>& lists,
T& value, Compare compare, Projection projection,
ForwardIterator std::pair<ForwardIterator, ForwardIterator>::* accessor)
-> typename std::vector<std::pair<ForwardIterator, ForwardIterator>>::iterator
{
using value_type = cppsort::detail::value_type_t<ForwardIterator>;
using projected_type = cppsort::detail::projected_t<ForwardIterator, Projection>;
constexpr bool can_optimize =
utility::is_probably_branchless_comparison_v<Compare, projected_type> &&
utility::is_probably_branchless_projection_v<Projection, value_type>;
auto proj = [&projection, &accessor](const auto& list) -> decltype(auto) {
return projection(*(list.*accessor));
};
if (can_optimize) {
return cppsort::detail::lower_monobound_n(
lists.begin(), lists.size() - 1, value,
std::move(compare), proj
);
} else {
return cppsort::detail::lower_bound_n(
lists.begin(), lists.size() - 1, value,
std::move(compare), proj
);
}
}
struct enc_impl
{
template<
typename ForwardIterator,
typename Compare = std::less<>,
typename Projection = utility::identity,
typename = std::enable_if_t<
is_projection_iterator_v<Projection, ForwardIterator, Compare>
>
>
auto operator()(ForwardIterator first, ForwardIterator last,
Compare compare={}, Projection projection={}) const
-> cppsort::detail::difference_type_t<ForwardIterator>
{
auto&& comp = utility::as_function(compare);
auto&& proj = utility::as_function(projection);
if (first == last || std::next(first) == last) {
return 0;
}
// Heads an tails of encroaching lists
std::vector<std::pair<ForwardIterator, ForwardIterator>> lists;
lists.emplace_back(first, first);
++first;
////////////////////////////////////////////////////////////
// Create encroaching lists
while (first != last) {
auto&& value = proj(*first);
auto& last_list = lists.back();
if (not comp(value, proj(*last_list.second))) {
// Element belongs to the tails (bigger elements)
auto insertion_point = enc_lower_bound(
lists, value, cppsort::detail::invert(compare), proj,
&std::pair<ForwardIterator, ForwardIterator>::second
);
insertion_point->second = first;
} else if (not comp(proj(*last_list.first), value)) {
// Element belongs to the heads (smaller elements)
auto insertion_point = enc_lower_bound(
lists, value, compare, proj,
&std::pair<ForwardIterator, ForwardIterator>::first
);
insertion_point->first = first;
} else {
// Element does not belong to the existing encroaching lists,
// create a new list for it
lists.emplace_back(first, first);
}
++first;
}
return lists.size() - 1;
}
template<typename Integer>
static constexpr auto max_for_size(Integer n)
-> Integer
{
return n == 0 ? 0 : (n + 1) / 2 - 1;
}
};
}
namespace
{
constexpr auto&& enc = utility::static_const<
sorter_facade<detail::enc_impl>
>::value;
}
}}
#endif // CPPSORT_PROBES_ENC_H_
|
#include <iostream>
#include <algorithm>
using namespace std;
#define NUM 3
struct node {
int a;
int b;
double c;
};
bool cmp(node x, node y) {
if(x.a != y.a) return x.a < y.a;
if(x.b != y.b) return x.b > y.b;
return x.c > y.c;
}
int main() {
node nodeArr[NUM] = {
{2, 2, 1.2},
{3, 4, 1.6},
{2, 3, 1.4}
};
sort(nodeArr, nodeArr + NUM, cmp);
for (int i = 0; i < NUM; i++) {
cout<<nodeArr[i].a<<" "<<nodeArr[i].b<<" "<<nodeArr[i].c<<endl;
}
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
}
struct Node {
int data;
Node* left;
Node* right;
};
// utility fxn
Node* newNode(int n) {
Node* temp = new Node;
temp->data = n;
temp->left = temp->right = NULL;
return(temp);
}
int maxSum(Node* root) {
if(root == NULL) return 0;
int left = maxSum(root->left);
int right = maxSum(root->right);
return max(left,right) + root->data;
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
// int sum = 0;
cout << maxSum(root) << endl;
return 0;
}
|
#pragma once
#include "PCH.hpp"
#include "GameObject.hpp"
class Tree : public GameObject
{
public:
Tree(Game* game);
void Update();
void Render();
void Clean();
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2009 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef DOM_JIL_API_SUPPORT
#include "modules/dom/src/domjil/domjilexceptions.h"
#include "modules/dom/src/domenvironmentimpl.h"
class DOM_EnvironmentImpl;
DOM_JILException_Constructor::DOM_JILException_Constructor()
: DOM_BuiltInConstructor(DOM_Runtime::JIL_EXCEPTION_PROTOTYPE)
{}
/*virtual*/ int
DOM_JILException_Constructor::Construct(ES_Value* argv, int argc, ES_Value* return_value, ES_Runtime* origining_runtime)
{
DOM_Runtime* dom_runtime = GetEnvironment()->GetDOMRuntime();
CALL_FAILED_IF_ERROR(DOM_Object::CreateJILException(JIL_UNKNOWN_ERR, return_value, dom_runtime));
return ES_VALUE;
}
#endif // DOM_JIL_API_SUPPORT
|
#include "vertex_buffer.h"
#include <Windows.h>
#include <DirectXMath.h>
#include "device.h"
HRESULT VertexBuffer::initialize(UINT capacity, VertexBuffer::SimpleVertex* vertices, D3D11_PRIMITIVE_TOPOLOGY topology,const Device& device) {
//--------------------
// 頂点バッファの定義
//--------------------
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.ByteWidth = sizeof(VertexBuffer::SimpleVertex) * capacity; // バッファのサイズ(バイト単位)
bd.Usage = D3D11_USAGE_DEFAULT; // バッファの使用法(D3D11_USAGE_DEFAULTはGPUによる読み書きができるバッファ)
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // バッファを描画パイプラインにバインドする方法
// D3D11_BIND_VERTEX_BUFFERならば頂点バッファとして入力アセンブラにバインドする
bd.CPUAccessFlags = 0; // CPUアクセスフラグ(CPUアクセスが不必要ならば0)
//-------------------
// 頂点バッファを作成
//-------------------
D3D11_SUBRESOURCE_DATA InitData; // 初期化データ
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = vertices;
HRESULT hr = device.getDevice()->CreateBuffer(&bd, &InitData, &pVertexBuffer);
if (FAILED(hr))
return hr;
//-------------------
// 頂点バッファの登録
//-------------------
UINT stride = sizeof(VertexBuffer::SimpleVertex);
UINT offset = 0;
device.getDeviceContext()->IASetVertexBuffers(
0, // バッファをバインドする入力スロット番号
1, // 配列内の頂点バッファの数
&pVertexBuffer, // 登録する頂点バッファ配列
&stride, // 頂点バッファ内の要素のサイズ(頂点バッファごとに指定するので配列のポインタを指定する)
&offset // 頂点バッファのオフセット(頂点バッファごとに指定するので配列のポインタを指定する)
);
//-------------------
// 頂点群の解釈を定義
//-------------------
device.getDeviceContext()->IASetPrimitiveTopology(topology);
return S_OK;
}
void VertexBuffer::finalize() {
//----------------
// リソースの解放
//----------------
if (pVertexBuffer)
pVertexBuffer->Release();
}
|
#include "dynamicbody.h"
namespace sge { namespace physics {
DynamicBody::DynamicBody(float x, float y, float width, float height)
:Body(Type::Dynamic, x, y, width, height) {
m_Speed = math::vec2(0,0);
}
DynamicBody::~DynamicBody(){}
void DynamicBody::onUpdate() {
Body::onUpdate();
}
void DynamicBody::setSpeed(math::vec2 speed){
applyImpulse(speed);
}
void DynamicBody::applyImpulse(math::vec2 desiredVel){
b2Vec2 vel = body->GetLinearVelocity();
float velChangeX = desiredVel.x - vel.x;
float velChangeY = desiredVel.y - vel.y;
float impulseX = body->GetMass() * velChangeX;
float impulseY = body->GetMass() * velChangeY;
body->ApplyLinearImpulse( b2Vec2(impulseX,impulseY), body->GetWorldCenter(), true);
}
} }
|
//
// Created by gurumurt on 4/6/18.
//
#ifndef OPENCLDISPATCHER_SELECTION_H
#define OPENCLDISPATCHER_SELECTION_H
#endif //OPENCLDISPATCHER_SELECTION_H
#include <cstring>
#include "../Environment.h";
#include "../globals.h";
class selection_kernel {
public:
string name = "selection";
string kernel_src;
int global_size;
selection_kernel(string name){
generate_kernel(name);
}
void set_global_size(int tuples){
global_size /=32;
}
void generate_kernel(string op, string additional_name = "selection") {
name = additional_name + op;
if (op.compare("between") == 0) {
kernel_src = "__kernel void " + name +
"("
" __global unsigned int* data,"
" __global unsigned int* bitmap,"
"unsigned int c1, unsigned int c2) {"
" size_t pos = 32 * get_global_id(0); "
" unsigned int bm = 0;"
" for (unsigned int i=0; i<32; ++i) {"
" bm |= ((c1 < data[pos])&(data[pos] < c2)) ? 0x1 << i : 0;"
" pos++;"
" }"
" bitmap[get_global_id(0)] = bm;"
"}";
global_size /=32;
} else if (op.compare("<") == 0) {
kernel_src = "__kernel void " + name +
"("
" __global unsigned int* data,"
" __global unsigned int* bitmap,"
" unsigned int c) {"
" size_t pos = 32 * get_global_id(0); "
" unsigned int bm = 0;"
" for (unsigned int i=0; i<32; ++i) {"
" bm |= data[pos++] < c ? 0x1 << i : 0;"
" }"
" bitmap[get_global_id(0)] = bm;"
"}";
} else if (op.compare("=") == 0) {
kernel_src = "__kernel void " + name +
"("
" __global unsigned int* data,"
" __global unsigned int* bitmap,"
" unsigned int c) {"
" size_t pos = 32 * get_global_id(0); "
" unsigned int bm = 0;"
" for (unsigned int i=0; i<32; ++i) {"
" bm |= data[pos++] == c ? 0x1 << i : 0;"
" }"
" bitmap[get_global_id(0)] = bm;"
"}";
} else {
kernel_src = "__kernel void " + name +
"("
" __global unsigned int* data,"
" __global unsigned int* bitmap,"
" unsigned int c) {"
" size_t pos = 32 * get_global_id(0); "
" unsigned int bm = 0;"
" for (unsigned int i=0; i<32; ++i) {"
" bm |= data[pos++] > c ? 0x1 << i : 0;"
" }"
" bitmap[get_global_id(0)] = bm;"
"}";
}
}
string get_kernel_name(){
return this->name;
}
string get_kernel_source(){
return this->kernel_src;
}
};
|
#include <bits/stdc++.h>
using namespace std;
#define LimSUP 1e15
#define LimINF 31622777
unsigned long long int cuantos;
vector<unsigned long long int> criba(LimINF);
vector<unsigned long long int> primos;
vector<unsigned long long int> factores(1003);
vector<unsigned long long> enes(1003);
vector<bool> usados;
set<unsigned long long int> extra;
unsigned long long int M, N, K, grado, factor, tamanio;
void cribale(){
for(unsigned long long int i=2; i<=LimINF; i++){
if(!criba[i]){
primos.push_back(i);
for(unsigned long long int a=i*i; a<=LimINF; a+=i){
criba[a]=1;
}
}
}
}
void busca(unsigned long long int n,unsigned long long int cuantosFactores){
for(unsigned long long int i= 0; (i<tamanio && cuantosFactores >0 && (primos[i]* primos[i]) <=n ); i++){
if(n%primos[i] == 0){
usados[i] = true;
cuantosFactores--;
while(n%primos[i] == 0){
n /= primos[i];
}
}
}
if(cuantosFactores){
extra.insert(n);
}
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cribale();
tamanio = primos.size();
usados.resize(tamanio+2);
cin >> M >> N >> K;
for(unsigned long long int i =1; i<=N; i++){
cin >> enes[i];
}
unsigned long long int m,n,d;
for(unsigned long long int i=0; i<K; i++){
cin >> m >> n >> d;
factores[n]++;
}
for(unsigned long long int i=1; i<=N; i++){
busca(enes[i], factores[i]);
}
//unsigned long long int cestras = extra.size();
unsigned long long int utilizados = 0;
for(unsigned long long int i=0; i<tamanio; i++){
if(usados[i]){
if(utilizados > 0){
cout << " ";
}
cout << primos[i];
utilizados++;
}
}
unsigned long long int otroUsados = 0;
for(unsigned long long int ex : extra){
if(utilizados > 0){
cout << " ";
}else if( otroUsados > 0){
cout << " ";
}
cout << ex << " ";
otroUsados++;
}
return 0;
}
|
/*
* BHMain.cpp
*
* Created on: Aug 26, 2014
* Author: ushnish
*
Copyright (c) 2014 Ushnish Ray
All rights reserved.
*/
#include "dmc.h"
#define MPI
using namespace std;
extern int setup(int rank, string baseSpecFile);
int main(int argc,char* argv[])
{
#ifdef MPI
if(argc<2)
{
cout<<"Format is: <filenamelist>"<<endl;
return -1;
}
int rank;
int prov;
MPI_Status Stat;
MPI_Init_thread(&argc,&argv,MPI_THREAD_MULTIPLE, &prov);
if(prov == MPI_THREAD_SINGLE)
cout<<"Thread Support: SINGLE"<<endl;
else if(prov == MPI_THREAD_FUNNELED)
cout<<"Thread Support: FUNNEL"<<endl;
else if(prov == MPI_THREAD_SERIALIZED)
cout<<"Thread Support: SERIALIZED"<<endl;
else if(prov == MPI_THREAD_MULTIPLE)
cout<<"Thread Support: MULTIPLE"<<endl;
else
cout<<"Thread Support: ERROR"<<endl;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
string bfile(argv[1]);
int status;
status = setup(rank,bfile);
MPI_Finalize();
#else
#endif
}
|
#include "game.hpp"
int main(int argc, char* args[])
{
Game game;
return 0;
}
|
#ifndef COMMON_TESTS_PATHAPPENDERTEST_H
#define COMMON_TESTS_PATHAPPENDERTEST_H
#include "AutoTest.h"
namespace common
{
namespace util
{
namespace tests
{
class PathAppenderTest final : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase_data();
void combineTest();
void operatorTest();
};
}
}
}
#endif // COMMON_TESTS_PATHAPPENDERTEST_H
|
// proyecto bomba de agua
// Control con transistor C2344
// Etapa de potecia por relevador controlado por transistor
int baseAgua=45;
int entCisterna = A7; //
int tinAlto =A6; //
int tinBajo =A5; //
int tinOut=12;
int b_apagada=11;
int a_cisterna= 3;
int tran=2;
int estado; //1-lleno, 2-Vacio, 3-Sin agua
int cisSinAgua=10;
int lecturaAlto;
int lecturaBajo;
int cisterna_val;
void setup() {
pinMode(cisSinAgua,OUTPUT);
pinMode(a_cisterna,OUTPUT);
pinMode(tran,OUTPUT);
pinMode(tinOut,OUTPUT);
pinMode(b_apagada,OUTPUT);
Serial.begin(9600);
digitalWrite(tinOut,HIGH);
digitalWrite(a_cisterna,HIGH);
//lee iniciales:
if(analogRead(entCisterna)<baseAgua){
estado=3; // no hay agua
}else if(analogRead(tinBajo)<baseAgua){
estado=2; // tanque vacio
}else{ //if(analogRead(tinBajo)>baseAgua)
estado=1; // tanque lleno
}
}
void prendeBomba(){
digitalWrite(tran,HIGH);
digitalWrite(b_apagada,LOW);
}
void apagaBomba(){
digitalWrite(tran,LOW);
digitalWrite(b_apagada,OUTPUT);
}
int revisaCisterna(){ // solo prende y apaga foquito
int auxCis;
auxCis=analogRead(entCisterna);
if(auxCis<baseAgua){
digitalWrite(cisSinAgua,HIGH); // no hay agua
}else{
digitalWrite(cisSinAgua,LOW);
}
return auxCis;
}
void loop() {
if (estado==1){ //////////////////////////////
apagaBomba();
lecturaBajo=analogRead(tinBajo);
cisterna_val=revisaCisterna();
Serial.println("estado");
Serial.println(estado);
Serial.println(lecturaBajo);
delay(999);
if(lecturaBajo<baseAgua){ // se vacio
estado=2;
}
}else if(estado ==2){ ///////////////////////
prendeBomba();
lecturaAlto=analogRead(tinAlto);
cisterna_val=revisaCisterna();
Serial.println("estado");
Serial.println(estado);
Serial.println(lecturaAlto);
delay(999);
if(cisterna_val<baseAgua){
estado=3;
}else if(lecturaAlto>baseAgua){
estado=1;
}
}else if(estado==3){ ////////////////////////
apagaBomba();
digitalWrite(cisSinAgua,HIGH);
cisterna_val=revisaCisterna();
Serial.println("estado");
Serial.println(estado);
Serial.println(cisterna_val);
delay(999);
if(analogRead(entCisterna)<baseAgua){
estado=3; // no hay agua
}else if(analogRead(tinBajo)<baseAgua){
estado=2; // tanque vacio
digitalWrite(cisSinAgua,LOW);
}else{ //if(analogRead(tinBajo)>baseAgua)
estado=1; // tanque lleno
digitalWrite(cisSinAgua,LOW);
}
}
}
|
#include "EventHandler.hpp"
EventHandler::EventHandler(){
m_eventRunning = false;
m_eventLoaded = false;
ResourceManager& rm = ResourceManager::GetInstance();
m_textFont = rm.loadFont("default22", "data/default.ttf", DRAW_TEXT_SIZE);
m_titleFont = rm.loadFont("default26", "data/default.ttf", DRAW_TEXT_SIZE + 10);
}
EventHandler::~EventHandler(){
}
void EventHandler::playEvent(void) {
if (m_eventLoaded) {
m_eventRunning = true;
m_currentBlock = m_events[0];
}
}
void EventHandler::events(const SDL_Event& e) {
if (m_eventRunning) {
if (e.type == SDL_KEYDOWN && e.key.repeat == 0) {
switch (e.key.keysym.sym) {
case SDLK_w: incrementSelection(); break;
case SDLK_s: decrementSelection(); break;
case SDLK_RETURN: next(); break;
}
}
}
}
bool EventHandler::loadEvent(const char* file) {
Debug& dbg = Debug::GetInstance();
dbg.Print("Loading Event: %s", file);
std::ifstream reader(file);
if (!reader.good()) {
dbg.Print("Error - Failed to read event file");
return false;
}
std::string line, text, dest;
size_t first, last;
int txtLineCtr = -1;
int index = -1;
while (reader.good()) {
std::getline(reader, line);
switch (line[0]) {
case '@':
index++;
txtLineCtr = -1;
m_events.push_back(new Event());
first = line.find("@");
m_events[index]->name = line.substr(first + 1);
m_events[index]->type = EBLOCK_TEXT;
break;
case '<':
first = line.find('<');
last = line.find('>');
text = line.substr(first + 1, (last - 1) - first);
first = line.find('>');
dest = line.substr(first + 1, line.size());
m_events[index]->branches.push_back(new Branch(dest, text));
m_events[index]->type = EBLOCK_BRANCH;
break;
case '.':
first = line.find('.');
m_events[index]->retn = line.substr(first + 1);
m_events[index]->type = EBLOCK_END;
break;
case '#':
//This is just so comments are not read as dialog
break;
case '>':
first = line.find(">");
m_events[index]->jump = line.substr(first + 1);
m_events[index]->type = EBLOCK_JUMP;
break;
default:
if (txtLineCtr > -1) {
m_events[index]->lines[txtLineCtr] = line;
} else {
m_events[index]->title = line;
}
txtLineCtr++;
break;
}
}
m_eventLoaded = true;
reader.close();
return true;
}
void EventHandler::next(void) {
std::string temp;
Event* nextBlock;
switch (m_currentBlock->type) {
case EBLOCK_TEXT:
if (m_eventIndex + 1 < m_events.size()) {
m_currentBlock = m_events[++m_eventIndex];
}
break;
case EBLOCK_BRANCH:
temp = m_currentBlock->branches[m_branchIndex]->dest;
nextBlock = getEvent(temp);
if (nextBlock != NULL) {
m_currentBlock = nextBlock;
}
break;
case EBLOCK_JUMP:
nextBlock = getEvent(m_currentBlock->jump);
if (nextBlock != NULL) {
m_currentBlock = nextBlock;
}
break;
case EBLOCK_END:
m_return = m_currentBlock->retn;
m_currentBlock = NULL;
m_eventLoaded = false;
m_eventRunning = false;
m_events.clear();
break;
}
for (int i = 0; i < MAXLINES; i++) {
m_drawText[i].clear();
}
m_drawLine = 0;
m_drawChar = 0;
}
Event * EventHandler::getEvent(std::string name) {
for (int i = 0; i < m_events.size(); i++) {
if (m_events[i]->name.compare(name) == 0) {
return m_events[i];
}
}
return NULL;
}
void EventHandler::incrementSelection(void) {
if (m_branchIndex + 1 < m_currentBlock->branches.size()) {
m_branchIndex++;
} else {
m_branchIndex = 0;
}
}
void EventHandler::decrementSelection(void) {
if (m_branchIndex - 1 >= 0) {
m_branchIndex--;
} else {
m_branchIndex = m_currentBlock->branches.size() - 1;
}
}
void EventHandler::drawTextBlock(const Dimension<int>& screen) {
if (m_drawChar < m_currentBlock->lines[m_drawLine].size()) {
char c = m_currentBlock->lines[m_drawLine].at(m_drawChar);
m_drawText[m_drawLine] = m_drawText[m_drawLine] + c;
m_drawChar++;
} else {
if (m_drawLine < MAXLINES - 1) {
m_drawChar = 0;
m_drawLine++;
}
}
if (m_drawCtr < 2) {
m_drawCtr++;
} else {
m_drawCtr = 0;
}
int x1 = (screen.width / 2) - (DRAW_WIDTH / 2);
int y1 = (screen.height - DRAW_HEIGHT) - DRAW_SCREEN_PADDING_Y;
SDL_Rect innerBox;
innerBox.x = x1;
innerBox.y = y1;
innerBox.w = DRAW_WIDTH;
innerBox.h = DRAW_HEIGHT;
float rectColor[][3] = { {1,1,1},{ 0,0,0 } };
Graphics2D::DrawRoundedQuadEX(x1, y1, DRAW_WIDTH, DRAW_HEIGHT, 4, 10, rectColor);
int x2 = x1 + DRAW_TEXT_OFFSET + 4;
int y2 = y1;
float white[] = { 1,1,1,1 };
m_drawTexture.loadFromRenderedText(m_titleFont, white, m_currentBlock->title);
m_drawTexture.render(x2, y2 - 2);
y2 += DRAW_TEXT_SIZE + 14;
Graphics2D::DrawFilledQuad(x1, y2 - 4, DRAW_WIDTH, 2);
for (int i = 0; i < MAXLINES; i++) {
m_drawTexture.loadFromRenderedText(m_textFont, white, m_drawText[i]);
m_drawTexture.render(x2, y2);
y2 += DRAW_TEXT_SIZE;
}
}
void EventHandler::drawSwitchBlock(const Dimension<int>& screen) {
const int x1 = (screen.width / 2) - (DRAW_WIDTH / 2);
const int y1 = (screen.height - DRAW_HEIGHT) - DRAW_SCREEN_PADDING_Y;
Graphics2D::SetColor(0, 0, 0);
float rectColor[][3] = { { 1,1,1 },{ 0,0,0 } };
Graphics2D::DrawRoundedQuadEX(x1, y1, DRAW_WIDTH, DRAW_HEIGHT, 4, 10, rectColor);
int x2 = x1 + DRAW_TEXT_OFFSET + 4;
int y2 = y1;
float white[] = { 1,1,1,1 };
float selectColor[] = { 1,1,0,1 };
m_drawTexture.loadFromRenderedText(m_titleFont, white, m_currentBlock->title);
m_drawTexture.render(x2, y2);
y2 += DRAW_TEXT_SIZE;
for (int i = 0; i < m_currentBlock->branches.size(); i++) {
if (i == m_branchIndex) {
m_drawTexture.loadFromRenderedText(m_textFont, selectColor, "-> " + m_currentBlock->branches[i]->text);
m_drawTexture.render(x2, y2 += DRAW_TEXT_SIZE);
} else {
m_drawTexture.loadFromRenderedText(m_textFont, white, m_currentBlock->branches[i]->text);
m_drawTexture.render(x2, y2 += DRAW_TEXT_SIZE);
}
}
}
std::string EventHandler::getResult(void) {
std::string result = m_return;
m_return.clear();
return result;
}
void EventHandler::render(const Dimension<int>& screen) {
if(m_eventRunning) {
if (m_currentBlock != NULL) {
if (m_currentBlock->type == EBLOCK_BRANCH) {
drawSwitchBlock(screen);
} else {
drawTextBlock(screen);
}
}
}
}
|
#pragma once
class Fade;
class MusicFade;
class LoadBalancingListener;
class ModeSelect;
class ExchangeData;
class backParticle;
class GameCursor;
class ReturnButton;
class NetPVPMode :public GameObject
{
public:
NetPVPMode();
void init(std::vector<std::string > files, int monai[3], int moid[3],int aimode[3]);
bool Start() override;
void Update() override;
void OnDestroy() override;
private:
//Scene遷移
void BattleStart();
void BackToMenu();
//Fade
Fade* m_fade = nullptr;
bool m_isfade = false;
//Ai Data
std::vector<std::string> m_files; //pythonファイルの名前
int m_aimode[6] = { 0 }; //PythonAIかVisualAiを識別する物
int m_monai[6] = { 0 }; //モンスターのAI
int m_moid[6] = { 0 }; //モンスターのID
int m_enemyAi[3] = { 0 }; //敵のモンスターのAI
int m_enemyId[3] = { 0 }; //敵のモンスターのID
//通信
LoadBalancingListener* m_lbl = nullptr;
void RaiseData();
void RaiseRatingData();
void RaiseMonsterID();
void RaiseAiTextData();
void RaiseAiVaData();
void LoadEnemyData();
void CheckDatas();
bool m_dataLoaded = false; //相手のデータを読み込み済みか
//データ送信状況管理
bool m_monsterDataRaised = false;
bool m_monsterAisRaised = false;
bool m_RateInfoRaised = false;
float m_dataRaiseTimer = 0.f; //データ送信のインターバル用タイマー
//送信用情報読み込み状態
bool m_myPyAIsLoaded = false;
bool m_myVaAIsLoaded = false;
//TimeOut
void TimeOut();
void Reconnect();
void UpdateTimeOutTimer();
void UpdateTimeOutProc();
bool m_isTimeout = false;
int timeout = 100;
float m_timer = 0.f; //タイムアウト用のタイマー
int m_recTime = 120; //再接続するまでに待つ時間(frame)
int m_rcuTime = 0;
float startTimer = 0;
float errorTimer = 0;
//UI
void InitUI();
void UiUpdate();
int m_numParticle = 20;
bool m_isEnemyHere = false;
GameCursor* m_cur = nullptr;
FontRender* m_font = nullptr;
CVector3 m_bbPos = { -500,-300,0 };
SpriteRender* m_wallpaper = nullptr;
std::vector<backParticle*> m_particles;
ReturnButton* m_returnButton = nullptr;
CVector2 m_findFontPos = { -270.f,320.f };
SpriteRender* m_informationSp = nullptr;
CVector3 m_informationPos = { 0.f,300.f,0.f };
CVector2 m_waitingFontPos = { -180.f,320.f };
};
|
#include<bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define pb push_back
#define mp make_pair
#define fi first
#define se second
typedef long long ll;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--) {
int n,m;
cin>>n>>m;
int P[n+1][m+1];
P[0][0]=0;
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++)
cin>>P[i][j];
}
int pre[n+1][m+1],inv[n+1][m+1];
for(int i=1;i<=m;i++) {
pre[0][i]=inv[0][i]=i;
pre[1][i]=P[1][i];
inv[1][pre[1][i]]=i;
}
for(int i=2;i<=n;i++) {
for(int j=1;j<=m;j++) {
pre[i][j]=P[i][pre[i-1][j]];
inv[i][pre[i][j]]=j;
}
}
int q;
cin>>q;
map<pair<int,int>, long> cache;
while(q--) {
int l,r;
cin>>l>>r;
if(cache[{l,r}]) {
cout<<cache[{l,r}]<<"\n";
} else {
long ans=0;
for(int i=1;i<=m;i++) {
//cout<<pre[r][i]<<" ";
// if(l!=1) {
//cout<<pre[r][inv[l-1][i]]<<" ";
ans+=(long)i*pre[r][inv[l-1][i]];
/*}
else {
//cout<<pre[r][i]<<" ";
ans+=i*pre[r][i];
}*/
}
cache[{l,r}]=ans;
cout<<ans<<"\n";
}
}
}
return 0;
}
|
/* -*- coding: utf-8 -*-
!@time: 2019-09-16 14:58
!@author: superMC @email: 18758266469@163.com
!@fileName: 0001_find_num_in_two_dims_array.cpp
*/
#include "environment.h"
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
if (array.size() == 0) {
return false;
}
if (array[0].size() == 0) {
return false;
}
int i = array.size(); //行高
int cols = array[0].size(); //列宽
i--; //最底
int j = 0;
while (i >= 0 && j < cols) {
if (target < array[i][j]) {
i--;
} else if (target > array[i][j]) {
j++;
} else {
return true;
}
}
return false;
}
//思路:首先我们选择从左下角开始搜寻,(为什么不从左上角开始搜寻,左上角向右和向下都是递增,
// 那么对于一个点,对于向右和向下会产生一个岔路;如果我们选择从左下脚开始搜寻的话,如果大于就向右,如果小于就向下)。
bool Find_Template(int target, vector<vector<int> > array) {
if (array.size() == 0) {
return false;
}
if (array[0].size() == 0) {
return false;
}
// array是二维数组,这里没做判空操作
int rows = array.size();
int cols = array[0].size();
int i = rows - 1, j = 0;//左下角元素坐标
while (i >= 0 && j < cols) {//使其不超出数组范围
if (target < array[i][j])
i--;//查找的元素较少,往上找
else if (target > array[i][j])
j++;//查找元素较大,往右找
else
return true;//找到
}
return false;
}
};
void trimLeftTrailingSpaces(string &input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
vector<int> stringToIntegerVector(string input) {
vector<int> output;
input = input.substr(1, input.length() - 2);
stringstream ss;
ss.str(input);
string item;
char delim = ',';
while (getline(ss, item, delim)) {
output.push_back(stoi(item));
}
return output;
}
vector<vector<int>> stringToVectorIntegerVector(string input) {
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
stringstream ss;
ss.str(input);
string item;
vector<vector<int>> res;
char delim = ']';
int i = 0;
while (getline(ss, item, delim)) {
if (i == 0) {
vector<int> tmp = stringToIntegerVector(item + "]");
res.push_back(tmp);
} else {
res.push_back(stringToIntegerVector(item.substr(1, item.size()) + ']'));
}
i++;
}
return res;
}
string boolToString(bool input) {
return input ? "True" : "False";
}
int fun() {
string line = "[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]";
int target = 5;
vector<vector<int>> input = stringToVectorIntegerVector(line);
bool ret = Solution().Find(target, input);
string out = boolToString(ret);
cout << out << endl;
return 0;
}
|
// Created on: 1995-12-01
// Created by: EXPRESS->CDL V0.2 Translator
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepBasic_ProductDefinitionFormationWithSpecifiedSource_HeaderFile
#define _StepBasic_ProductDefinitionFormationWithSpecifiedSource_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepBasic_Source.hxx>
#include <StepBasic_ProductDefinitionFormation.hxx>
class TCollection_HAsciiString;
class StepBasic_Product;
class StepBasic_ProductDefinitionFormationWithSpecifiedSource;
DEFINE_STANDARD_HANDLE(StepBasic_ProductDefinitionFormationWithSpecifiedSource, StepBasic_ProductDefinitionFormation)
class StepBasic_ProductDefinitionFormationWithSpecifiedSource : public StepBasic_ProductDefinitionFormation
{
public:
//! Returns a ProductDefinitionFormationWithSpecifiedSource
Standard_EXPORT StepBasic_ProductDefinitionFormationWithSpecifiedSource();
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aId, const Handle(TCollection_HAsciiString)& aDescription, const Handle(StepBasic_Product)& aOfProduct, const StepBasic_Source aMakeOrBuy);
Standard_EXPORT void SetMakeOrBuy (const StepBasic_Source aMakeOrBuy);
Standard_EXPORT StepBasic_Source MakeOrBuy() const;
DEFINE_STANDARD_RTTIEXT(StepBasic_ProductDefinitionFormationWithSpecifiedSource,StepBasic_ProductDefinitionFormation)
protected:
private:
StepBasic_Source makeOrBuy;
};
#endif // _StepBasic_ProductDefinitionFormationWithSpecifiedSource_HeaderFile
|
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int trap(vector<int>& height) {
int N = height.size();
vector<int> left(N, 0), right(N, 0);
int leftLimit = 0, rightLimit = 0;
for(int i=0;i<N;i++){
leftLimit = max(leftLimit, height[i]);
left[i] = leftLimit;
}
for(int i=N-1;i>=0;i--){
rightLimit = max(rightLimit, height[i]);
right[i] = rightLimit;
}
int res = 0;
for(int i=0;i<N;i++)
res += min(left[i], right[i]) - height[i];
return res;
}
};
int main(){
Solution s;
std::vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(0);
v.push_back(2);
v.push_back(1);
v.push_back(0);
v.push_back(1);
v.push_back(3);
v.push_back(2);
v.push_back(1);
v.push_back(2);
v.push_back(1);
cout << s.trap(v) << endl;
}
|
#include <glaux.h>
#include <types.hpp>
#include <windows.h>
class CGL
{
private:
HDC dc;
HGLRC rc;
public:
CGL();
~CGL();
void InitOpenGL(HWND hWnd);
void Resize(HWND hWnd);
void StopOpenGL();
void StartSceneDraw();
void StopSceneDraw();
void Light(int Light, float X,float Y, float Z, bool Positional);
};
|
#pragma once
#include "Fornitual.h"
class Sofa :
virtual public Fornitual
{
public:
Sofa(float l, float w, float h);
void sit();
};
|
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int a[50];
int i,n,p,nr;
printf("Dati numarul de elemente ale tabloului mai mici sau egal cu 50:\n");
scanf("%d",&n);
printf("Introducerea a %d elemente:\n",n);
for(i=0;i<n;i++)
{
printf("a[%d]=",i+1);
scanf("%d",&a[i]);
}
printf("\nTabloul este:");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
p=1;
nr=0;
for(i=0;i<n;i++)
{
if(fmod(a[i],2)!=0)
{
p=p*a[i];
nr++;
}
}
printf("produsul este %d",p);
printf("\nprodusul este %d",nr);
getch();
return 0;
}
|
// Copyright (c) 2021 ETH Zurich
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/init.hpp>
#include <pika/modules/execution.hpp>
#include <pika/testing.hpp>
#include <pika/execution_base/tests/algorithm_test_utils.hpp>
#include <atomic>
#include <exception>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
namespace ex = pika::execution::experimental;
namespace tt = pika::this_thread::experimental;
// NOTE: This is not a conforming sync_wait implementation. It only exists to
// check that the tag_invoke overload is called.
void tag_invoke(tt::sync_wait_t, custom_sender2 s) { s.tag_invoke_overload_called = true; }
int pika_main()
{
// Success path
{
std::atomic<bool> start_called{false};
std::atomic<bool> connect_called{false};
std::atomic<bool> tag_invoke_overload_called{false};
tt::sync_wait(custom_sender{start_called, connect_called, tag_invoke_overload_called});
PIKA_TEST(start_called);
PIKA_TEST(connect_called);
PIKA_TEST(!tag_invoke_overload_called);
}
{
PIKA_TEST_EQ(tt::sync_wait(ex::just(3)), 3);
}
{
PIKA_TEST_EQ(tt::sync_wait(ex::just(custom_type_non_default_constructible{42})).x, 42);
}
{
PIKA_TEST_EQ(
tt::sync_wait(ex::just(custom_type_non_default_constructible_non_copyable{42})).x, 42);
}
{
int x = 42;
PIKA_TEST_EQ(tt::sync_wait(ex::just(const_reference_sender<int>{x})).x.get(), 42);
}
// operator| overload
{
std::atomic<bool> start_called{false};
std::atomic<bool> connect_called{false};
std::atomic<bool> tag_invoke_overload_called{false};
tt::sync_wait(custom_sender{start_called, connect_called, tag_invoke_overload_called});
PIKA_TEST(start_called);
PIKA_TEST(connect_called);
PIKA_TEST(!tag_invoke_overload_called);
}
{
PIKA_TEST_EQ(tt::sync_wait(ex::just(3)), 3);
}
// tag_invoke overload
{
std::atomic<bool> start_called{false};
std::atomic<bool> connect_called{false};
std::atomic<bool> tag_invoke_overload_called{false};
tt::sync_wait(custom_sender2{
custom_sender{start_called, connect_called, tag_invoke_overload_called}});
PIKA_TEST(!start_called);
PIKA_TEST(!connect_called);
PIKA_TEST(tag_invoke_overload_called);
}
// Failure path
{
bool exception_thrown = false;
try
{
tt::sync_wait(error_sender{});
PIKA_TEST(false);
}
catch (std::runtime_error const& e)
{
PIKA_TEST_EQ(std::string(e.what()), std::string("error"));
exception_thrown = true;
}
PIKA_TEST(exception_thrown);
}
{
bool exception_thrown = false;
try
{
tt::sync_wait(const_reference_error_sender{});
PIKA_TEST(false);
}
catch (std::runtime_error const& e)
{
PIKA_TEST_EQ(std::string(e.what()), std::string("error"));
exception_thrown = true;
}
PIKA_TEST(exception_thrown);
}
return pika::finalize();
}
int main(int argc, char* argv[])
{
PIKA_TEST_EQ_MSG(pika::init(pika_main, argc, argv), 0, "pika main exited with non-zero status");
return 0;
}
|
#ifndef LEVELINTERFACE_H_
#define LEVELINTERFACE_H_
#include "SceneInterface.h"
#include "Player.h"
class LevelInterface : public SceneInterface
{
public:
LevelInterface();
virtual ~LevelInterface();
virtual void update();
};
#endif
|
#ifndef AD_CNMETHOD_H
#define AD_CNMETHOD_H
#include "../FDRegularMethod.hpp"
#include "../implicit/EuroImplicitMethod.hpp"
template<typename X>
class EuroCNMethod : public FDRegularMethod<X> {
protected:
std::vector<X> *prev_K;
std::vector<X> *cur_K;
public:
EuroCNMethod(Option<X> *_option, X xl, X xu, int _N, int _M);
virtual ~EuroCNMethod();
std::vector<X> decomposition(const std::vector<X> &q);
std::vector<X> D(const std::vector<X> &q);
void solve(bool showStable = false) override;
protected:
X A(const int &j) override;
X B(const int &j) override;
X C(const int &j) override;
X E1(const int &j);
X E2(const int &j);
X F1(const int &j);
X F2(const int &j);
X G1(const int &j);
X G2(const int &j);
};
#include "EuroCNMethod.tpp"
#endif //AD_CNMETHOD_H
|
#include <bits/stdc++.h>
using namespace std;
vector <bool> kidsCandies(vector <int> &candies , int eCandies)
{
int n = candies.size() , mCandies = 0;
for(int i = 0 ; i < n ; i++)
if(candies[i] > mCandies)
mCandies = candies[i];
vector <bool> result(n);
for(int i = 0 ; i < n ; i++)
result[i] = (candies[i] + eCandies >= mCandies);
return result;
}
int main()
{
vector <int> candies = {2, 3, 5, 1, 3};
int eCandies = 3;
for(bool x : kidsCandies(candies , eCandies))
cout << (x ? "true" : "false") << " ";
cout <<endl;
return 0;
}
|
#ifndef DPDK_LOGGER_CLASS_METRIC_INTERFACE_H
#define DPDK_LOGGER_CLASS_METRIC_INTERFACE_H
#include "rte_eal.h"
class MetricInterface{
public:
MetricInterface(){}
virtual ~MetricInterface(){};
// Initialize the Metrics library. A pointer can be supplied as a parameter
virtual bool initialize_metrics(void *data) = 0;
// Register a new metric to system. Its ID is returned with ID parameter.
virtual bool register_metric(const char *metric_name, int &id) = 0;
/** Update The Registered Metric Value.
* @param absolute: If true, metric value is set to @param value. Else value is added to current value
*
* **/
virtual bool update_metric(int metric_id, int64_t value, bool absolute) = 0;
// Get the metric value by ID.
virtual bool get_metric(int metric_id, uint64_t &metric_value) = 0;
protected:
// Print the Currently Registered Metrics to screen. Should be used for testing purposes. Real Outputting will be done in
// Logger class itself since this is the class that knows the structure of the registered metrics.
virtual void print_metrics() = 0;
private:
};
#endif
|
/*
* =====================================================================================
*
* Filename: branch.h
*
* Description: All branching related classes
*
* Version: 1.0
* Created: Monday 12 November 2012 09:30:29 IST
* Revision: none
* Compiler: gcc
*
* Author: Vaibhav Agarwal (), vaisci310@gmail.com
* Company:
*
* =====================================================================================
*/
#ifndef BRANCH_H
#define BRANCH_H
#define BTBSIZE 32
#define HISTORY_TABLE_LENGTH 128
#define NO_OF_BITS 3
#define LENGTH_PREDICTOR 2
typedef struct _BTBentry
{
int PC;
int branchAddress;
}BTBentry;
class BTB
{
private:
BTBentry entries[BTBSIZE];
public:
BTB();
int getBranchAddress ( int PC );
void addBranchAddress ( int PC , int branchAddress );
};
class BranchPrediction
{
public:
int historyTableEntries[HISTORY_TABLE_LENGTH];
int localPredictionEntries[8];
BranchPrediction();
bool predictBranch ( int PC );
void setBranchResult ( int PC , bool taken );
};
#endif
|
#pragma once
#include <boost/smart_ptr/shared_ptr.hpp>
#include "Networking/General/SG_ClientSession.h"
#include "Packets/MMO/Social/SocialPackets.h"
class SG_ChatHandler
{
public:
typedef enum
{
CHAT_NORMAL = 1, // normal, white chat
CHAT_NORMAL2 = 2, // same
CHAT_ALL = 3, // orange message
CHAT_MP = 5, // same
CHAT_SYSTEM_ANNOUNCEMENT = 10, // red, caps lock, center of the screen
CHAT_WHISP_OUT = 11, // yellow, like system messages
CHAT_GM = 20, // pink
CHAT_CLAN = 21, // purple
CHAT_SYSTEM_INFO = 99, // yellow, like system messages
CHAT_DEBUG = 100 // red
} CHAT_TYPE;
static void HandleChatMessage(const boost::shared_ptr<SG_ClientSession> Session, const BM_SC_CHAT_MESSAGE* packet);
static void HandleAdminCommand(const boost::shared_ptr<SG_ClientSession> Session, const BM_SC_CHAT_MESSAGE* packet);
static void HandleUserCommand(const boost::shared_ptr<SG_ClientSession> Session, const BM_SC_CHAT_MESSAGE* packet);
};
|
#include <iostream>
#include <vector>
#include "utils.h"
using namespace std;
// 给定一个数组,将其中的奇数放在数组的左边,偶数放在数组的右边,且保持奇数与奇数的稳定性,偶数与偶数的稳定性
class OddEvenPartition {
public:
void reOrderArray(vector<int>& array) {
vector<int> odd, even;
for (int elem : array) {
if (elem % 2 == 1) odd.emplace_back(elem);
else even.emplace_back(elem);
}
array.clear();
for (int elem : odd) array.emplace_back(elem);
for (int elem : even) array.emplace_back(elem);
}
void test() {
vector<int> arr = { 3, 6, 7, 2, 4, 11, 19, 18, 22 };
reOrderArray(arr);
for (int elem : arr) cout << elem << " ";
cout << endl;
}
};
int main() {
/* code here */
return 0;
}
|
#pragma once
#include <Kinect.VisualGestureBuilder.h>
#include <Kinect.h>
#include <iostream>
#include <list>
#include <stdio.h>
#include "renderer.h"
#define FRAME_DEPTH 0
#define FRAME_COLOR 1
#define FRAME_INFRARED 2
#define FRAME_BODY 3
#define VIRTUAL_RECTANGLE_CORNER_L_X 0.05
#define VIRTUAL_RECTANGLE_CORNER_L_Y 0.75
#define VIRTUAL_RECTANGLE_CORNER_R_X 0.35
#define VIRTUAL_RECTANGLE_CORNER_R_Y 0.25
#define THRESHOLD_DISTANCE_SWAP_CANDIDATES 0.1
#define THRESHOLD_DISTANCE_ZOOMING 0.1
#define THRESHOLD_TIMER 1
#define NO_GESTURE 0
#define SELECT 1
#define PANNING 2
#define ZOOM_IN 4
#define ZOOM_OUT 5
#define SELECTION_PROGRESS 6
#define BUFFER_SIZE 10
class KinectSensor {
private:
IKinectSensor *pKinectSensor;
IDepthFrameReader *pDepthFrameReader;
IColorFrameReader *pColorFrameReader;
IInfraredFrameReader *pInfraredFrameReader;
IBodyFrameReader *pBodyFrameReader;
IVisualGestureBuilderFrameReader
*pVisualGestureBuilderFrameReader[BODY_COUNT];
ICoordinateMapper *m_pCoordinateMapper;
IVisualGestureBuilderDatabase *pGestureDatabase;
void error(std::string e, HRESULT hr);
public:
KinectSensor();
~KinectSensor();
IDepthFrameReader *getDepthFrameReader();
IColorFrameReader *getColorFrameReader();
IInfraredFrameReader *getInfraredFrameReader();
IBodyFrameReader *getBodyFrameReader();
ICoordinateMapper *getCoordinateMapper();
IVisualGestureBuilderDatabase *GestureDatabase;
IGesture *pGesture;
static Renderer::DisplayMode mode;
static int gestureType;
static int timer;
static float hand_distance;
static float hand_pos_x;
static float hand_pos_y;
static float panning_delta_x;
static float panning_delta_y;
static float zoom_delta;
static bool rightHand_closed;
static bool leftHand_closed;
/* Returns the next frame from the depth reader */
IDepthFrame *getNextDepthFrame();
/* Returns the next frame from the color reader */
IColorFrame *getNextColorFrame();
/* Returns the next frame from the depth reader */
IInfraredFrame *getNextInfraredFrame();
/* Returns the next frame from the depth reader */
IBodyFrame *getNextBodyFrame();
/* Updates the hand position variable. (Put this into a thread)*/
static void updateHandPosition();
static void mapHandToCursor(float *handPosition, int screenWidth,
int screenHeight, int *cursor);
static float *handCoords;
static bool KeepUpdatingHandPos;
static float getHandsDistance(IBody *pBody);
/* Gesture builder functions */
static void updateGesture(IBody *pBody);
static std::string getGestureType();
/* Releases any Kinect interface */
template <class Interface> void SafeRelease(Interface *&pInterface); // TODO
static std::list<float> handPosXBuf, handPosYBuf, handPosZBuf;
static std::list<float> spinePosXBuf, spinePosYBuf, spinePosZBuf;
static void addHandJoint(Joint handJoint);
static void addSpineJoint(Joint spineJoint);
static float getHandJointPosX();
static float getHandJointPosY();
static float getHandJointPosZ();
static float getSpineJointPosX();
static float getSpineJointPosY();
static float getSpineJointPosZ();
};
|
#include "Asteroid.h"
Asteroid::Asteroid(SDL_Rect *r, SDL_Surface *s,double x, double y, double a,double sp):DynamicGameObject(r,s,x,y,a,sp)
{
health = 100*rect->w;
damage = 10*rect->w;
}
|
#pragma once
#include <Sys/Signal_.h>
#include "BaseElement.h"
namespace Gui {
class ButtonBase : public BaseElement {
protected:
enum eState { ST_NORMAL, ST_FOCUSED, ST_PRESSED };
eState state_;
public:
ButtonBase(const Vec2f &pos, const Vec2f &size, const BaseElement *parent);
void Focus(const Vec2i &p) override;
void Focus(const Vec2f &p) override;
void Press(const Vec2i &p, bool push) override;
void Press(const Vec2f &p, bool push) override;
Sys::Signal<void()> pressed_signal;
};
}
|
#ifndef ADJACENCY_MATRIX
#define ADJACENCY_MATRIX 1
#include <stdexcept>
#include "GraphAdjacencyBase.hpp"
#include "include/list.hpp"
#include "include/seq_linear_list.hpp"
namespace cs202 {
class AdjacencyMatrix : public GraphAdjacencyBase {
private:
LinearList<int> matrix;
int v;
bool is_valid_index(int i, int j) const {
return (i < v && j < v);
}
int index_of(int i, int j) const {
return v * i + j;
}
int& get(int i, int j) {
if (is_valid_index(i, j)) {
return matrix[index_of(i, j)];
} else {
throw std::invalid_argument("Invalid indices to matrix.");
}
}
const int& const_get(int i, int j) const {
if (is_valid_index(i, j)) {
return matrix.at(index_of(i, j));
} else {
throw std::invalid_argument("Invalid indices to matrix.");
}
}
public:
AdjacencyMatrix(int in_v) : matrix(in_v * in_v, 0), v(in_v) {
}
/* Destructor:
* releases all resources acquired by the class
*/
virtual ~AdjacencyMatrix() override {
// no need to do anything, the matrix will delete itself
}
/*
* Function: edgeExists
* Returns true if an edge exists between vertices i and j, false otherwise.
*/
virtual bool edgeExits(int i, int j) const override {
return (const_get(i, j) != 0);
}
/*
* Function: vertices
* Returns the number of vertices in the adjacency structure.
*/
virtual int vertices() const override {
return v;
}
/*
* Function: edges
* Returns the number of edges in the adjacency structure.
*/
virtual int edges() const override {
int edges = 0;
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
if (edgeExits(i, j)) {
edges++;
}
}
}
return edges;
}
/*
* Function add:
* Adds an edge between vertices i and j
*/
virtual void add(int i, int j, int weight) override {
get(i, j) = weight;
}
/*
* Function: remove
* Deleted the edge between vertices i and j
*/
virtual void remove(int i, int j) override {
get(i, j) = 0;
}
/*
* Function: degree
* Returns the degree of the vertex i
*/
virtual int outdegree(int i) const override {
int d = 0;
for (int j = 0; j < v; j++) {
if (edgeExits(i, j)) {
d++;
}
}
return d;
}
virtual int indegree(int i) const override {
int edges = 0;
for (int j = 0; j < vertices(); j++) {
if (edgeExits(j, i)) {
edges++;
}
}
return edges;
}
virtual const list<GraphEdge> adjacentVertices(int i) const override {
if (!is_valid_index(i, 0)) {
throw std::invalid_argument("Invalid index for adjacency list.");
}
list<GraphEdge> adjacents;
for (int j = 0; j < vertices(); j++) {
if (edgeExits(i, j)) {
adjacents.append(GraphEdge(j, const_get(i, j)));
}
}
return adjacents;
}
const LinearList<int>& peak() const {
return matrix;
}
};
}
#endif /* ifndef ADJACENCY_MATRIX */
|
#include "serveur.h"
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main(int argc, char* argv[])
{
u_short port;
string pseudo;
pthread_t thread1;
pthread_t thread2;
data serverData;
cout << "Port: ";
cin >> port;
cout << "Pseudo: ";
cin >> pseudo;
serverData.mutex = PTHREAD_MUTEX_INITIALIZER;
serverData.server.setPseudo(pseudo);
serverData.server.setPort(port);
serverData.server.start();
pthread_create(&thread1, NULL, threadAcceptClient, (void*)&serverData);
pthread_create(&thread2, NULL, threadSendMessage, (void*)&serverData);
serverData.server.receiveMessage();
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
|
//
// Created by yutianzuo on 2018/5/8.
//
#ifndef USELIBCURL_GETREQUEST_H
#define USELIBCURL_GETREQUEST_H
#include "request.h"
class HttpGetRequest : public HttpRequest<HttpGetRequest>
{
public:
HttpGetRequest(HttpGetRequest &&rvalue) = delete;
void operator=(HttpGetRequest &&) = delete;
HttpGetRequest(const HttpGetRequest &src) = delete;
HttpGetRequest &operator=(const HttpGetRequest &src) = delete;
HttpGetRequest() : HttpRequest()
{
}
};
#endif //USELIBCURL_GETREQUEST_H
|
/// \file NiCfRunAction.hh
/// \brief Definition of the NiCfRunAction class; adapted from
/// Geant4 example B5 B5RunAction.hh
#ifndef NiCfRunAction_h
#define NiCfRunAction_h 1
#include "G4UserRunAction.hh"
#include "globals.hh"
class NiCfEventAction;
class G4Run;
/// Run action class
class NiCfRunAction : public G4UserRunAction
{
public:
NiCfRunAction(NiCfEventAction* eventAction);
virtual ~NiCfRunAction();
virtual void BeginOfRunAction(const G4Run*);
virtual void EndOfRunAction(const G4Run*);
private:
NiCfEventAction* fEventAction;
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#endif
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 2003-2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Morten Stenshorne
*/
#ifndef __X11_OPPAINTER_H__
#define __X11_OPPAINTER_H__
#include "platforms/unix/base/common/common_oppainter.h"
#include "platforms/unix/base/common/scaling.h"
#ifndef VEGA_OPPAINTER_SUPPORT
#ifdef GADGET_SUPPORT
/********************************************************************
*
* struct ShapedWindowData
*
*
********************************************************************/
struct ShapedWindowData
{
ShapedWindowData(bool is_tool_shape)
{
m_buffer = 0;
m_buffer_width = 0;
m_buffer_height = 0;
m_width = 0;
m_height = 0;
m_changed = FALSE;
m_has_applied_shape = FALSE;
m_is_tool_shape = is_tool_shape;
m_transparent_pixel = 0;
m_init_pixel = 0;
}
~ShapedWindowData()
{
OP_DELETEA(m_buffer);
}
// fill_value = 0x00: becomes transparent
// fill_value = 0xFF: becomes visible
void setup( int width, int height, unsigned char fill_value=0x00 )
{
if( width > 0 && height > 0 )
{
if( m_width != width || height != m_height )
{
m_width = width;
m_height = height;
m_buffer_width = m_width + 8 - m_width%8;
m_buffer_height = m_height;
OP_DELETEA(m_buffer);
m_buffer = OP_NEWA(unsigned char, (m_buffer_width*m_buffer_height)>>3);
memset(m_buffer, fill_value, (m_buffer_width*m_buffer_height)>>3);
}
}
m_changed = FALSE;
}
bool isFullyTransparent()
{
int size = (m_buffer_width*m_buffer_height)>>3;
for( int i=0; i<size; i++ )
if( m_buffer[i] )
return false;
return true;
}
bool isToolShape() const { return m_is_tool_shape; }
void apply( int drawable );
unsigned char* m_buffer;
INT32 m_buffer_width;
INT32 m_buffer_height;
INT32 m_width;
INT32 m_height;
BOOL m_changed;
BOOL m_is_tool_shape;
BOOL m_has_applied_shape;
UINT32 m_transparent_pixel; // Background color after all drawing has been made
UINT32 m_init_pixel; // Background color gefore all drawing
};
#endif
/********************************************************************
*
* X11OpPainter
*
*
********************************************************************/
class X11OpPainter : public CommonOpPainter
{
private:
class X11OpPainterInternal *d;
X11FontSwitcher m_fontswitcher;
bool m_doublebuffer;
/*******************************************
*
* ClipRect
*
*******************************************/
class ClipRect
{
public:
ClipRect *prev;
OpRect coords;
ClipRect(const OpRect &coords)
: coords(coords) { prev = 0; }
};
ClipRect *m_cliprect_stack_top;
int m_x_offs;
int m_y_offs;
int m_viewtrans_x;
int m_viewtrans_y;
OpRect m_paintrect;
public:
X11OpPainter();
~X11OpPainter();
void GetDPI(UINT32 *horizontal, UINT32 *vertical);
void SetColor(UINT8 red, UINT8 green, UINT8 blue, UINT8 alpha=255);
void SetFont(OpFont *font);
OP_STATUS SetClipRect(const OpRect &rect);
void RemoveClipRect();
void GetClipRect(OpRect *rect);
void DrawRect(const OpRect &rect, UINT32 width = 1);
void FillRect(const OpRect &rect);
void DrawEllipse(const OpRect &rect, UINT32 width = 1);
void FillEllipse(const OpRect &rect);
virtual void DrawPolygon(const OpPoint* points, int count, UINT32 width = 1);
void DrawLine(const OpPoint &from, UINT32 length, BOOL horizontal, UINT32 width=1);
void DrawLine(const OpPoint &from, const OpPoint &to, UINT32 width=1);
void DrawString(const OpPoint &pos, uni_char *text, UINT32 len, INT32 extra_char_spacing=0
#ifdef PI_CAP_LINEAR_TEXT_SCALE
, short word_width=-1
#endif // PI_CAP_LINEAR_TEXT_SCALE
);
void InvertRect(const OpRect &rect);
void InvertBorderRect(const OpRect &rect, int border);
void InvertBorderEllipse(const OpRect &rect, int border);
void InvertBorderPolygon(const OpPoint *point_array, int points, int border);
void DrawBitmapClipped(const OpBitmap *bitmap, const OpRect &source, OpPoint p);
void DrawBitmapClippedTransparent(const OpBitmap *bitmap, const OpRect &source, OpPoint p);
void DrawBitmapClippedAlpha(const OpBitmap* bitmap, const OpRect &source, OpPoint p);
void DrawBitmapScaled(const OpBitmap *bitmap, const OpRect &source, const OpRect &dest);
void DrawBitmapScaledTransparent(const OpBitmap *bitmap, const OpRect &source, const OpRect &dest);
void DrawBitmapScaledAlpha(const OpBitmap *bitmap, const OpRect &source, const OpRect &dest);
OP_STATUS DrawBitmapTiled(const OpBitmap *bitmap, const OpPoint &source, const OpRect &dest, INT32 scale);
OP_STATUS DrawBitmapTiled(const OpBitmap *bitmap, const OpPoint &source, const OpRect &dest, INT32 scale, UINT32 bitmapWidth, UINT32 bitmapHeight);
OpBitmap *CreateBitmapFromBackground(const OpRect &rect);
BOOL Supports(SUPPORTS supports);
OP_STATUS BeginOpacity(const OpRect& rect, UINT8 opacity) { return OpStatus::ERR; }
void EndOpacity() {}
UINT32 GetColor();
PainterType GetPainterType() { return X11_OPPAINTER; }
DeviceType GetDeviceType() { return SCREEN; }
// -------- Implementation specific methods: ---------------------------
class X11OpPainterInternal *GetInternal() { return d; }
OP_STATUS Init();
/** Begin the paint operation. Call End() to end the paint operation. */
void Begin(
unsigned long drawable, const OpRect &rect, BOOL nobackbuffer,
OpPoint *view_translation=0,
BOOL try_argb_visual = FALSE);
/** Begin the paint operation. Call End() to end the paint operation. */
OP_STATUS Begin(class X11OpBitmap *bitmap);
/** End the paint operation. Must be called before a new Begin(), and also
* before TakeOverBitmap().
* @param flush_buffer If true, copy the double-buffer bitmap to the screen
* (when in double-buffering mode) and remove our reference to the pixmap.
* If false, just end the paint operation, so that the bitmap can be gotten
* with TakeOverBitmap().
*/
void End(bool flush_buffer = true);
/** Have the caller take over the ownership of the bitmap. Must be called
* after End().
* @return The bitmap used by this painter, if any, and only if the bitmap
* is owned by this painter. Returns NULL otherwise.
*/
X11OpBitmap *TakeOverBitmap();
void SetClipRectInternal(const OpRect &rect);
void UseDoublebuffer(BOOL on) { m_doublebuffer = on; }
BOOL HasDoublebuffer() const { return m_doublebuffer; }
void DrawBitmap(const OpBitmap *bitmap, const OpRect &source,
const OpPoint &dest, int use_w, int use_h);
const OpRect& GetPaintRect() { return m_paintrect; }
UnixFontSwitcher *GetFontSwitcher() { return &m_fontswitcher; }
void Transform(OpPoint &p) {
p.x -= m_x_offs;
p.y -= m_y_offs;
}
void Transform(OpRect &r) {
r.x -= m_x_offs;
r.y -= m_y_offs;
}
#ifdef GADGET_SUPPORT
void ApplyShape(int drawable, ShapedWindowData& shape);
#endif
};
#endif // !VEGA_OPPAINTER_SUPPORT
#endif // __X11_OPPAINTER_H__
|
#include <iostream>
#include "queue.h"
// Creates an empty queue
queue::queue(){
front = nullptr;
back = nullptr;
queue_size = 0;
}
// Copy constructor
queue::queue(const queue& q){
front = nullptr;
back = nullptr;
node* new_node = q.front;
queue_size = q.queue_size;
while (new_node){
node* new_back = new node (new_node -> value);
if (!front){
front = new_back;
} else {
back -> next = new_back;
}
back = new_back;
new_node = new_node -> next;
new_back = nullptr;
}
new_node = nullptr;
}
// Initializer list constructor
queue::queue(std::initializer_list<int> ilist){
front = nullptr;
back = nullptr;
queue_size = ilist.size();
for (auto i : ilist){
node* new_back = new node(i);
if (!front){
front = new_back;
} else {
back -> next = new_back;
}
back = new_back;
}
}
// Copy assignment
queue& queue::operator=(const queue& q){
if(queue_size==q.queue_size){
node* q_node = q.front;
node* node=front;
while(q_node!=nullptr){
node->value=q_node->value;
node=node->next;
q_node=q_node->next;
}
} else {
clear();
node* new_node = q.front;
while (new_node){
node* new_back = new node(new_node->value);
if (!front){
front = new_back;
} else {
back -> next = new_back;
}
back = new_back;
new_node = new_node -> next;
new_back = nullptr;
}
queue_size = q.queue_size;
new_node = nullptr;
}
return *this;
}
// Insert an item at the back of the queue
void queue::push(int val){
node* new_back = new node (val);
if (!front){
front = new_back;
back = new_back;
} else {
back -> next = new_back;
}
back = new_back;
++queue_size;
}
// Returns the value of the front-most item of the queue;
// throws an exception if the queue is empty
int queue::peek() const{
if(this -> empty()){
throw std::invalid_argument("404. queue not found");
}
return front -> value;
}
// Remove the front-most item from the queue
// throws an exception if the queue is empty
void queue::pop(){
if(!front){
throw std::invalid_argument("404. queue not found");
// throw an exception
}
node* cur = front;
front = front -> next;
delete cur;
queue_size --;
}
// Remove everything from the queue
void queue::clear(){
while (front){
pop();
}
front = nullptr;
back = nullptr;
queue_size = 0;
}
// Returns the number of items on the queue
size_t queue::size() const {
return queue_size;
}
// Returns whether or not the queue is currently empty
bool queue::empty() const {
return !queue_size;
}
// Merges the given queue x at the end of this -> queue
// and then clears the queue x.
// If x is the same object with this -> then does nothing.
void queue::merge (queue& x){
if (this == &x){
return;
} else if (!x.front){
return;
} else if (!front){
front = x.front;
back = x.back;
queue_size = x.queue_size;
x.queue_size=0;
x.front = nullptr;
x.back = nullptr;
} else {
back-> next = x.front;
back = x.back;
queue_size += x.queue_size;
x.front = x.back = nullptr;
x.queue_size = 0;
}
}
// Destructor
queue::~queue(){
clear();
}
|
//===========================================================================
//! @file model_base.h
//===========================================================================
#pragma once
//===========================================================================
//! @class ModelBase
//===========================================================================
class ModelBase
{
public:
//----------------------------------------------------------
//! @name 初期化
//----------------------------------------------------------
//! コンストラクタ
ModelBase() = default;
//! デストラクタ
~ModelBase() = default;
//----------------------------------------------------------
//! @nam タスク
//----------------------------------------------------------
//! 描画
void render();
//! 解放
void cleanup();
//! tmp pos
void setPosition(const Vector3& pos)
{
position_ = pos;
}
private:
//----------------------------------------------------------
//! @name 読み込み関数まとめ
//----------------------------------------------------------
//! 頂点座標読み込み
void loadPoint(FILE* fp);
//! 頂点番号読み込み
void loadIndex(FILE* fp);
//! 法線読み込み
void loadNroaml();
private:
std::vector<Vertex> vertices_;
std::vector<Vector3> points_;
std::vector<u32> indices_;
u32 pointCount_ = 0;
u32 indexCount_ = 0;
std::unique_ptr<gpu::Texture> texture0_;
gpu::ConstantBuffer<CB_World> cbModel_;
gpu::Buffer vertexBuffer_;
gpu::Buffer indexBuffer_;
Vector3 position_;
};
|
#include <Array.h>
#include <iostream>
using namespace std;
int main(void)
{
Array<int> ta(102400);
Array<int> tb = ta;
for(int i = 0 ; i < 102400 ; i++) {
tb[i] = i;
}
cout<<"data is:"<< tb.Data() << endl
<<"base is:"<< tb.Base() << endl
<<"lenth is:"<< tb.Length()<< endl;
for(int i = 0; i < 10 ; i++) {
cout <<tb[i] <<'\n';
}
for(int i = 12400 -1 ; i > 12380 ; i--) {
cout <<tb[i] <<'\n';
}
try {
cout<<tb[102444];
}
catch(const out_of_range &e) {
cout<< e.what()<<endl;
}
return 0;
}
|
#include <iostream>
using namespace std;
class Fraction {
friend ostream &operator<<(ostream &out, const Fraction &c);
friend Fraction operator+(const Fraction &leftFrac, const Fraction &rightFrac);
public:
Fraction(int newNum=1, int newdeNum=1);
Fraction& operator++();
Fraction operator++(int);
//Fraction operator+(const Fraction& plusFrac) const;
private:
int num, denum;
};
Fraction::Fraction(int newNum, int newDenum) : num(newNum), denum(newDenum) {}
Fraction &Fraction::operator++() {
num += denum;
return *this;
}
Fraction Fraction::operator++(int) {
Fraction old = *this;
num += denum;
return *this;
}
/*Fraction Fraction::operator+(const Fraction& plusFrac) const {
Fraction newFrac;
newFrac.num = num*plusFrac.denum + denum*plusFrac.num;
newFrac.denum = denum*plusFrac.denum;
return newFrac;
}*/
Fraction operator+(const Fraction &leftFrac, const Fraction &rightFrac) {
Fraction newFrac;
newFrac.num = leftFrac.num*rightFrac.denum + leftFrac.denum*rightFrac.num;
newFrac.denum = leftFrac.denum * rightFrac.denum;
return newFrac;
}
ostream &operator<<(ostream &out, const Fraction &c) {
out << c.num << "/" << c.denum << endl;
return out;
}
int main() {
Fraction n1(2,3);
Fraction n2(5, 6);
Fraction n;
n = 2 + n2;
cout << n;
return 0;
}
|
// https://oj.leetcode.com/problems/interleaving-string/
// Use DP
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int size1 = s1.size(), size2 = s2.size(), size3 = s3.size();
if (size3 != size1 + size2) {
return false;
}
bool match[s1.size() + 1][s2.size() + 1];
match[0][0] = true;
for (int i = 1; i <= size1; i++) {
match[i][0] = (match[i-1][0]) && (s1[i-1] == s3[i-1]);
}
for (int j = 1; j <= size2; j++) {
match[0][j] = (match[0][j-1]) && (s2[j-1] == s3[j-1]);
}
for (int i = 1; i <= size1; i++) {
for (int j = 1; j <= size2; j++) {
match[i][j] = (match[i-1][j] && (s1[i-1] == s3[i+j-1])
|| (match[i][j-1] && (s2[j-1] == s3[i+j-1])));
}
}
return match[size1][size2];
}
};
|
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "CrearHistoria.h"
#include "Clases.h"
#include "TablasDatos.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm6 *Form6;
Paciente pac;
//---------------------------------------------------------------------------
__fastcall TForm6::TForm6(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm6::Button2Click(TObject *Sender)
{
if(ComboBox1->Text!="")
{
pac.GuardarHistoria(ComboBox1->Text.SubString(0,8));
this->Close();
}
else
{
ShowMessage("Campor Cédula Vacío.");
ComboBox1->SetFocus();
}
}
//---------------------------------------------------------------------------
void __fastcall TForm6::ComboBox1Change(TObject *Sender)
{
pac.VerHistoria(ComboBox1->Text.SubString(0,8), true);
}
//---------------------------------------------------------------------------
|
#include <torch/torch.h>
#include <ATen/Context.h>
#include <iostream>
torch::Tensor ActivationFunction(const torch::Tensor &x)
{
// Sigmoid function.
auto retVal = 1/(1+torch::exp(-x));
return retVal;
}
torch::Tensor SoftMax(const torch::Tensor &x)
{
auto sum = torch::sum(torch::exp(x),1);
return torch::exp(x)/sum.view({-1, 1});
}
int main()
{
// Download the MNIST data using the script present in,
// ../scripts/download_mnist.py
// Create a data loader for the MNIST dataset.
auto trainLoader = torch::data::make_data_loader(
torch::data::datasets::MNIST("/opt/MNIST/").map(
torch::data::transforms::Stack<>()),
/*batch_size=*/64);
auto batch = std::begin(*trainLoader);
auto images = batch->data;
auto target = batch->target;
std::cout << "images = " << images.sizes() << "\n";
std::cout << "targets = " << target.sizes() << "\n";
// Seed for Random number
torch::manual_seed(9);
auto inputs = images.view({images.size(0),-1});
std::cout << "inputs = " << inputs.sizes() << "\n";
// Create parameters
auto w1 = torch::randn({784, 256});
std::cout << "w1 =" << w1.sizes() << "\n";
auto b1 = torch::randn({256});
std::cout << "b1 =" << b1.sizes() << "\n";
auto w2 = torch::randn({256, 10});
std::cout << "w2 =" << w2.sizes() << "\n";
auto b2 = torch::randn({10});
std::cout << "b2 =" << b2.sizes() << "\n";
auto h = ActivationFunction(torch::mm(inputs, w1) + b1);
std::cout << "h =" << h.sizes() << "\n";
auto out = torch::mm(h, w2) + b2;
std::cout << "out =" << out.sizes() << "\n";
//std::cout << "out =" << out << "\n";
auto pred = SoftMax(out);
std::cout << "pred = " << pred.sizes() << "\n";
// std::cout << "pred = " << pred << "\n";
auto predSum = torch::sum(pred, 1);
std::cout << "predsum shape = " << predSum.sizes() << "\n";
//std::cout << "predsum = " << predSum << "\n";
return 0;
}
|
#include "DemoApp.h"
#include "SceneManager.h"
#include "CollisionChecker.h"
DemoApp::DemoApp(void)
{
}
DemoApp::~DemoApp(void)
{
}
void DemoApp::OnStart()
{
AllocConsole();
FILE* pCout;
freopen_s(&pCout, "conin$", "r", stdin);
freopen_s(&pCout, "conout$", "w", stdout);
freopen_s(&pCout, "conout$", "w", stderr);
fclose(pCout);
printf("Debugging Window:\n");
GameEngine::OnStart();
Camera* camera = new Camera();
camera->SetPerspectiveMatrix(90, 16.0f/9.0f, 1.0f, 50.0f);
camera->position = amVec3(0.0f, 0.0f, 5.0f);
camera->up = amVec3(0.0f, 1.0f, 0.0f);
camera->direction = amVec3(0.0f, 0.0f, 0.0f);
sceneManager->SetActiveCamera(camera);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
model = new SimpleModel();
model->Initialize();
modelManager.LoadCubeModel();
model->ApplyMesh(modelManager.GetMesh("Cube"));
modelNode = sceneManager->CreateRootChildSceneNode();
modelNode->AttachModel(model);
modelNodeChild = modelNode->CreateChildSceneNode();
modelNodeChild->AttachModel(model);
modelNodeChild->position = amVec3(2.0f, 0.0f, 0.0f);
modelNodeChild2 = modelNodeChild->CreateChildSceneNode();
modelNodeChild2->AttachModel(model);
modelNodeChild2->position = amVec3(2.0f, 0.0f, 0.0f);
modelNode->position = amVec3(0.0f, 0.0f, 0.0f);
BoundingSphere sphere1(amVec3(), 1.0f);
BoundingSphere sphere2(amVec3(5.0f, 0.0f, 0.0f), 1.0f);
Ray ray(amVec3(0.0f, -5.0f, 0.0f), amVec3(0, 1, 0));
if(CollisionChecker::SphereToSphereCollision(sphere1, sphere2))
printf("true");
if(CollisionChecker::SphereToRayCollision(sphere1, ray))
printf("Ray Collision");
}
void DemoApp::PreRender(float time)
{
GameEngine::PreRender(time);
}
float rotationAmount = 1.0f;
void DemoApp::Render()
{
modelNode->position.x -= 1.0f;
if(modelNode->position.x <= -20.0f)
modelNode->position.x = 0.0f;
GameEngine::Render();
rotationAmount++;
if(rotationAmount > 360)
rotationAmount = 0;
modelNode->orientation = amQuaternion(rotationAmount, 0.0f, 0.0f, 1.0f);
modelNodeChild->orientation = amQuaternion(rotationAmount, 0.0f, 1.0f, 0.0f);
modelNodeChild2->orientation = amQuaternion(rotationAmount, 1.0f, 0.0f, 0.0f);
//renderer->RenderPrimitive(AbstractRenderer::Triangle);
//renderer->RenderPrimitive(AbstractRenderer::Quad);
}
void DemoApp::PostRender()
{
GameEngine::PostRender();
}
void DemoApp::OnEnd()
{
GameEngine::OnEnd();
}
|
//Program Name: Triangle Challenge with Structures
//Created by Kartik Nagpal - kn8767 - kartiknagpal@utexas.edu
#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
using std::string;
struct triangle {
float a;
float b;
float c;
float Theta1;
float Theta2;
};
int solve(triangle &t1, triangle &t2);
float radToDeg(float r);
int main() {
triangle T1;
triangle T2;
float* a = T1.a;
cout << "What is the value of A for Triangle 1? ";
cin >> T1.a;
cout << "What is the value of B for Triangle 1? ";
cin >> T1.b;
cout << "What is the value of A for Triangle 2? ";
cin >> T2.a;
cout << "What is the value of B for Triangle 2? ";
cin >> T2.b;
solve(T1, T2);
return 0;
}
int solve(triangle &t1, triangle &t2) {
t1.c = sqrt(pow(t1.a, 2) + pow(t1.b, 2));
t1.Theta1 = asin(t1.a/t1.c);
t1.Theta2 = asin(t1.b/t1.c);
cout << "For A=" << t1.a << " and B=" << t1.b << endl;
cout << "Hypotnuse = " << t1.c << endl;
cout << "Theta1 = " << t1.Theta1 << " radians" << "(" << radToDeg(t1.Theta1) << " degrees)" << endl;
cout << "Theta2 = " << t1.Theta2 << " radians" << "(" << radToDeg(t1.Theta2) << " degrees)" << endl << endl;
t2.c = sqrt(pow(t2.a, 2) + pow(t2.b, 2));
t2.Theta1 = asin(t2.a/t2.c);
t2.Theta2 = asin(t2.b/t2.c);
cout << "For A=" << t2.a << " and B=" << t2.b << endl;
cout << "Hypotnuse = " << t2.c << endl;
cout << "Theta1 = " << t2.Theta1 << " radians" << "(" << radToDeg(t2.Theta1) << " degrees)" << endl;
cout << "Theta2 = " << t2.Theta2 << " radians" << "(" << radToDeg(t2.Theta2) << " degrees)" << endl << endl;
return 0;
}
float radToDeg(float r) {
float d = (r/M_PI)*180;
return d;
}
|
#include <bits/stdc++.h>
using namespace std;
int n, m, p, a, b, f[10010];
int find(int x) {if (f[x] != x) f[x] = find(f[x]); return f[x];}
int main()
{
scanf("%d%d%d", &n, &m, &p);
for (int i = 1; i <= n; i++) f[i] = i;
for (int i = 1; i <= m; i++) scanf("%d%d", &a, &b), f[find(b)] = find(a);
for (int i = 1; i <= p; i++)
{
scanf("%d%d", &a, &b);
if (find(a) == find(b)) printf("Yes\n"); else printf("No\n");
}
}
|
#pragma once
#include <unordered_map>
namespace oglml
{
class PostProcessor;
}
namespace breakout
{
class APostEffectState;
class PostEffectsStateManager
{
using EnumStateName = int;
public:
static PostEffectsStateManager& Get();
void Init();
void Begin();
void End();
void Draw(float dtMilliseconds);
void SwitchState(EnumStateName state);
bool IsActiveState(EnumStateName stateId) const;
private:
PostEffectsStateManager();
~PostEffectsStateManager();
PostEffectsStateManager(PostEffectsStateManager&) = delete;
PostEffectsStateManager(PostEffectsStateManager&&) = delete;
void operator=(PostEffectsStateManager&) = delete;
void operator=(PostEffectsStateManager&&) = delete;
std::unordered_map<EnumStateName, APostEffectState*> m_states = {};
APostEffectState* m_currState = nullptr;
EnumStateName m_currStateType = -1;
oglml::PostProcessor* m_postProcessor = nullptr;
};
}
|
#pragma once
#include <vector>
#include <memory>
#include <cstdint>
namespace trevi
{
class Block
{
public:
Block(){}
Block( const Block& other )
{
*this = other;
}
Block& operator = ( const Block& other )
{
_data = other._data;
}
virtual ~Block(){}
std::vector< uint64_t > getMembership();
void setMembership( const std::vector< uint64_t >& values );
private:
std::shared_ptr< uint8_t > _data;
protected:
};
}
|
// Created on: 1993-01-11
// Created by: Christian CAILLET
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IFSelect_SelectUnion_HeaderFile
#define _IFSelect_SelectUnion_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <IFSelect_SelectCombine.hxx>
class Interface_EntityIterator;
class Interface_Graph;
class TCollection_AsciiString;
class IFSelect_SelectUnion;
DEFINE_STANDARD_HANDLE(IFSelect_SelectUnion, IFSelect_SelectCombine)
//! A SelectUnion cumulates the Entities issued from several other
//! Selections (union of results : "OR" operator)
class IFSelect_SelectUnion : public IFSelect_SelectCombine
{
public:
//! Creates an empty SelectUnion
Standard_EXPORT IFSelect_SelectUnion();
//! Returns the list of selected Entities, which is the addition
//! result from all input selections. Uniqueness is guaranteed.
Standard_EXPORT Interface_EntityIterator RootResult (const Interface_Graph& G) const Standard_OVERRIDE;
//! Returns a text defining the criterium : "Union (OR)"
Standard_EXPORT TCollection_AsciiString Label() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IFSelect_SelectUnion,IFSelect_SelectCombine)
protected:
private:
};
#endif // _IFSelect_SelectUnion_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef PIFORMS_H
#define PIFORMS_H
class HTML_Element;
class InputObject;
class VisualDevice;
class OpEdit;
class OpFont;
class FramesDocument;
class ES_Thread;
class WidgetListener;
#include "modules/logdoc/logdocenum.h"
#include "modules/widgets/OpWidget.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/hardcore/timer/optimer.h"
class DocumentManager;
class HTMLayoutProperties;
class ValidationErrorWindow;
/**
* This class represents the special information that connects an
* HTML Element to something visual with data.
*/
class FormObject
: public OpInputContext
{
// Implement suitable operators new/delete that will do
// pooling and/or memory accounting or neither depending
// on configuration.
OP_ALLOC_ACCOUNTED_POOLING
OP_ALLOC_ACCOUNTED_POOLING_SMO_DOCUMENT
protected:
/**
* The widget that is used to visualize the form element.
*/
OpWidget* opwidget;
/**
* The document the control belongs to.
*/
FramesDocument* m_doc;
/**
* The form control's visual device.
*/
VisualDevice* m_vis_dev;
/**
* The listener that is used to get information from the widget.
*/
WidgetListener* m_listener;
/**
* The width of the form object in pixels.
*/
int m_width;
/**
* The height of the form object in pixels.
*/
int m_height;
/**
* If the form object is displayed.
*/
BOOL m_displayed;
/**
* The HTML Element that this form object represents.
*/
HTML_Element* m_helm;
/**
* Set when display properties should be updated.
*/
BOOL m_update_properties;
/**
* Used when a formobject is temporarily saved during
* reflow. Should not touch document etc when this is TRUE;
*/
BOOL m_locked;
/**
* The validation error window.
*/
ValidationErrorWindow* m_validation_error;
/**
* If this form element has already processed its autofocus
* attribute (if any). Should this maybe be in FormValue instead?
*/
BOOL m_autofocus_attribute_processed;
int m_memsize;
public:
/**
* Constructor. Base information about the form element.
* @param vd The VisualDevice for this FormObject.
* @param he The HTML_Element this object will be connected to.
* @param doc The document where this FormObject can be found.
*/
FormObject(VisualDevice *vd, HTML_Element* he, FramesDocument* doc);
/**
* Destructor.
*/
virtual ~FormObject();
/**
* Lock or unlock the form control.
* Locking is performed during the reflow when the form control's layout box is removed.
* After recreating the form control's layout box, the form control is unlocked.
* Note that when there's no need to recreate the form control's layout box (e.g. its style.display = 'none')
* the form control remains locked.
* Also note that this needs to be called in order to inform the widget connected
* with the form object about the lock's state as it may need
* to take some actions (e.g. hiding on lock and showing on unlock).
*
* @param status TRUE if the FormObject should locked, FALSE
* if it should be unlocked.
*/
void SetLocked(BOOL status)
{
OP_ASSERT(opwidget);
opwidget->SetLocked(status);
m_locked = status;
}
/**
* The width of the form object in pixels.
*
* @return The width of the form object's widget.
*/
int Width() { return m_width; }
/**
* The height of the form object in pixels.
*
* @return the height of the form object's widget.
*/
int Height() { return m_height; }
/**
* Calculates position in document.
*
* @param doc_pos An out parameter that will contain the position.
*/
void GetPosInDocument(AffinePos* doc_pos);
#ifdef OP_KEY_CONTEXT_MENU_ENABLED
/**
* Used to determine the location of the caret so that a context menu can be shown at its
* position.
*
* @param[out] x The x coordinate of the caret.
*
* @param[out] y The y coordinate of the caret.
*
* @returns TRUE if there was a visible caret with a well defined position, FALSE otherwise.
*/
BOOL GetCaretPosInDocument(INT32* x, INT32* y);
#endif // OP_KEY_CONTEXT_MENU_ENABLED
/**
* Returns the rect for the object with CSS borders.
*
* @return the border.
*/
OpRect GetBorderRect();
/**
* Sets the widget position, calling both SetRect and SetPosInDocument. also sets visual device.
* @param vis_dev A VisualDevice
*/
void SetWidgetPosition(VisualDevice* vis_dev);
/**
* Displays the form control by painting it.
*
* @param props Layout properties to use.
* @param vis_dev A VisualDevice.
*
* @return Status.
*
* @todo Check if the vis_dev parameter is necessary. It gets a
* VisualDevice in the constructor.
*
*/
OP_STATUS Display(const HTMLayoutProperties& props, VisualDevice* vis_dev);
/**
* Gets the default background color to be used for this form
* object.
*/
COLORREF GetDefaultBackgroundColor() const;
/**
* Selects the text in the form control if possible. Does nothing
* if it's not possible to select it.
*/
void SelectText();
/**
* Get current selection in the out varibles
* or 0, 0 if there is no selection or the selection.
* Any code outside of FormValue should call the same
* function on FormValue which will take care of special
* cases where FormObject doesn't exist.
*
* @param start_ofs The offset of the first selected character.
* @param stop_ofs The offset of the character after the last
* selected character. stop_ofs == start_ofs means that no
* character is selected.
* @param direction The direction of the selection
*/
virtual void GetSelection(INT32& start_ofs, INT32& stop_ofs, SELECTION_DIRECTION& direction);
/**
* Get current selection in the out varibles
* or 0, 0 if there is no selection or the selection.
* Any code outside of FormValue should call the same
* function on FormValue which will take care of special
* cases where FormObject doesn't exist.
*
* @param start_ofs The offset of the first selected character.
* @param stop_ofs The offset of the character after the last
* selected character. stop_ofs == start_ofs means that no
* character is selected.
*/
void GetSelection(INT32 &start_ofs, INT32 &stop_ofs) { SELECTION_DIRECTION direction; GetSelection(start_ofs, stop_ofs, direction); }
/**
* Set current selection. Values incompatible with the current
* text contents will cause variables to be truncated to legal
* values before being used. To clear selection use
* ClearSelection() unless you need it to be collapsed at a
* particular point. Any code outside of FormValue should call
* the same function on FormValue which will take care of special
* cases where FormObject doesn't exist.
*
* @param start_ofs The offset of the first selected character.
* @param stop_ofs The offset of the character after the last selected
* character. stop_ofs == start_ofs means that no character is selected.
*/
virtual void SetSelection(INT32 start_ofs, INT32 stop_ofs, SELECTION_DIRECTION direction = SELECTION_DIRECTION_DEFAULT);
/**
* Highlight the search result by selection.
* Values incompatible with the current
* text contents will cause variables to be truncated to legal
* values before being used. To clear selection use
* ClearSelection() unless you need it to be collapsed at a
* particular point. Any code outside of FormValue should call
* the same function on FormValue which will take care of special
* cases where FormObject doesn't exist.
*
* @param start_ofs The offset of the first selected character.
* @param stop_ofs The offset of the character after the last selected character. stop_ofs == start_ofs means that no character is selected.
* @param is_active_hit TRUE if this is the active search result.
*/
void SelectSearchHit(INT32 start_ofs, INT32 stop_ofs, BOOL is_active_hit);
/**
* @return TRUE if current selection is a search hit.
*/
BOOL IsSearchHitSelected();
/**
* @return TRUE if current selection is an active search hit.
*/
BOOL IsActiveSearchHitSelected();
/**
* Removes any visible traces of the selection. There might still be a
* collapsed selection somewhere but it will not be visible. This operation
* will not affect any scroll positions.
*/
void ClearSelection();
/**
* Returns the current position of the caret in the form value.
*
* Any code outside of FormValue should call the same
* function on FormValue which will take care of special
* cases where FormObject doesn't exist.
*
* @returns 0 if the caret is first in the field or
* if "caret position" has no meaning for the form value.
*/
virtual INT32 GetCaretOffset();
/**
* Sets the current caret position.
* Values incompatible with the
* current text contents
* will cause variables to be truncated to legal values before being used.
*
* Any code outside of FormValue should call the same
* function on FormValue which will take care of special
* cases where FormObject doesn't exist.
*
* @param caret_ofs The number of characters before the caret. 0 is at
* the beginning of the field. 1 is after the first character.
*/
virtual void SetCaretOffset(INT32 caret_ofs);
/**
* If the FormObject's widget can show partial content (like a textarea too small for its content)
* then this function scrolls it to make the active part (caret/selection) visible.
*
* @param[in] scroll_document_if_needed If the FormObject itself isn't visible and this parameter is TRUE,
* try making the FormObject visible as well.
*/
void EnsureActivePartVisible(BOOL scroll_document_if_needed) { GetWidget()->ScrollIfNeeded(scroll_document_if_needed); }
/**
* Fills out_value with the value and returns a
* OpStatus::OK if it succedes. When
* allow_wrap is TRUE the textarea is allowed to insert hardbreaks
* if the WRAP attribute is HARD. It should be TRUE when
* f.ex. submitting the form content, and FALSE when caching the
* value for history or Wand.
*
* @param[out] out_value An empty OpString to be filled with the widget content.
*/
virtual OP_STATUS GetFormWidgetValue(OpString& out_value, BOOL allow_wrap = TRUE) = 0;
/**
* Set the value of the form control.
*/
virtual OP_STATUS SetFormWidgetValue(const uni_char* val) = 0;
/**
* Set the value of the form control.
*/
virtual OP_STATUS SetFormWidgetValue(const uni_char * val, BOOL use_undo_stack){ return SetFormWidgetValue(val); }
/**
* Returns the value as a integer (For button, checkbutton and radio)
*
* @return The value as an integer. Only works for buttons (state),
* checkbuttons and radio buttons.
*/
INT32 GetIntWidgetValue() { return opwidget->GetValue(); }
/**
* Checks if there are internal tab stops to take care of after the current focused
* widget part.
*
* @param forward - TRUE if we should look forward. FALSE if we should look backwards.
*
* @return TRUE is focus is in the last available tab stop in the specified direction. Will only
* return FALSE if a TAB can be handled internally.
*
* @todo Remove fallback code when widget is released.
*/
BOOL IsAtLastInternalTabStop(BOOL forward)
{
return !opwidget || opwidget->IsAtLastInternalTabStop(forward);
}
/**
* Returns FALSE if there was no later internal tab stop.
*
* @param forward - TRUE if we should look forward. FALSE if we should look backwards.
*
* @returns TRUE if something was found and had SetFocus called on itself.
*/
BOOL FocusNextInternalTabStop(BOOL forward);
/**
* Focus the last/first internal widget in the potentially nested widget.
*
* This is used when moving sequentially through the document so that you
* enter a widget from the right direction.
*
* @param[in] front If TRUE, focus the first internal widget, if FALSE, focuse the
* last internal widet.
*/
void FocusInternalEdge(BOOL front);
/**
* Click it (for radio or checkbox) and when someone is clicking on a label for this element.
*
* @param thread If script generated, the thread that generated the click, otherwise NULL.
*/
virtual void Click(ES_Thread* thread) {}
/**
* Check it.
*
* @param radio_elm The radio element.
* @param widget The widget.
* @param form_obj A form object.
* @param send_onchange TRUE if the element should receive an ONCHANGE event (true for user initiated changes, false for scripted changes)
* @param thread The ECMAScript thread that caused this to happen. Needed to get events in the correct order.
*
* @todo Study this strange thing. Why should it have parameters that we already know? It isn't static.
*/
void CheckRadio(HTML_Element *radio_elm, OpWidget* widget);
/**
* Check next radio thing.
*
* @param forward TRUE if we should move the check forward one
* step. FALSE if it should be moved backwards.
*/
BOOL CheckNextRadio(BOOL forward);
/**
* @return TRUE if this is a radio button form object.
*
* @todo Check if it overlaps with GetInputType.
*/
virtual BOOL IsRadioButton() { return FALSE; }
/**
* Which type is this?
*
* @return The type of the control.
*/
virtual InputType
GetInputType() const { return INPUT_NOT_AN_INPUT_OBJECT; }
/**
* Get the visual device.
*/
VisualDevice* GetVisualDevice() { return m_vis_dev; }
/**
* Get the HTML Element.
*/
HTML_Element* GetHTML_Element() { return m_helm; }
/**
* Get the widget. This will never return NULL.
*/
OpWidget* GetWidget() { return opwidget; }
/**
* Get the default element (if any?).
*/
HTML_Element* GetDefaultElement();
/**
* Mark default button.
*/
void UpdateDefButton();
/**
* Reset default button. This function shouldn't be used.
* Use the static function with an argument instead. It will not
* affect this FormObject, but the one that is currently default.
*
* @deprecated This is replaced by a static function.
*/
DEPRECATED(void ResetDefaultButton());
/**
* Reset default button. This remove the current default button
* from that role.
*/
static void ResetDefaultButton(FramesDocument* doc);
/**
* Returns TRUE if disabled.
*/
BOOL IsDisabled() const { return !opwidget->IsEnabled(); }
/**
* Returns TRUE if displayed.
*/
BOOL IsDisplayed() const { return m_displayed; }
/**
* Set enabled/disabled.
*
* @param enabled state to set the form object to.
* @param regain_focus if TRUE along with 'enabled', have form
* object reaquire input focus along with becoming (re-)enabled.
*/
void SetEnabled(BOOL enabled, BOOL regain_focus = FALSE);
#ifdef INTERNAL_SPELLCHECK_SUPPORT
/**
* Creates a spell session id for the widget or 0 if it
* isn't possible.
*
* @param point A point in the field which should be spell checked.
*/
int CreateSpellSessionId(OpPoint *point = NULL);
#endif // INTERNAL_SPELLCHECK_SUPPORT
/**
* If the user can edit the widget. Used to control which context menu we present.
*/
BOOL IsUserEditableText();
/**
* Set readonly/writeable. Only relevant for textareas and file upload controls.
*/
void SetReadOnly(BOOL readonly);
/**
* Set allow-multiple flag. Only relevant for file upload controls.
*/
void SetMultiple(BOOL multiple);
/**
* Set indeterminate status. Only relevant for checkboxes.
*/
void SetIndeterminate(BOOL indeterminate);
/**
* Set minimum and/or maximum values. Only relevant for type=range.
*
* @param new_min If non-NULL, the new minimum value for this
* form object.
* @param new_max If non-NULL, the new maximum value for this
* form object.
*/
void SetMinMax(double *new_min, double *new_max);
/**
* Initialise the widget.
*/
void InitialiseWidget(const HTMLayoutProperties& props);
/**
* Set that it's no longer displayed.
*/
void SetUndisplayed() { m_displayed = FALSE; }
/**
* Callback. When options collected.
*/
void OnOptionsCollected();
/**
* Updates the background-color, color, font etc.
*/
void UpdateProperties() { m_update_properties = TRUE; }
/**
* Get the document.
*/
FramesDocument* GetDocument() { return m_doc; }
/**
* Updates the position relative to view.
*/
void UpdatePosition();
/**
* Set size of the form control.
*/
virtual void SetSize(int new_width, int new_height);
/**
* Will update the widget with properties, and then calculate the
* preferred size (returned in preferred_width and preferred_height).
* The preferred size includes padding and formsborder. That means
* that if HasSpecifiedBorders is TRUE, the border will not be
* included as the widget doesn't have it itself.
*/
virtual void GetPreferredSize(int &preferred_width, int &preferred_height, int html_cols, int html_rows, int html_size, const HTMLayoutProperties& props);
/**
* Try to update the external representation of this text-editable
* value to be that of the input type of the given element.
* Used when the 'type' of a text-editable input element is dynamically
* updated, first attempting to in-place update the underlying
* widget into the new type.
*
* Returns TRUE if the conversion went ahead.
*/
virtual BOOL ChangeTypeInplace(HTML_Element *he) { return FALSE; }
// == Hooks ==============================================
#ifndef MOUSELESS
/**
* Called on mouse move.
*/
void OnMouseMove(const OpPoint &point);
/**
* Should be called when mouse is pressed.
*
* @param script_cancelled If the mousedown was cancelled by scripts. That should prevent us from
* setting focus but still cause some other things to happen, like opening dropdowns.
*
* @returns FALSE if the mouse was pressed on a scrollbar.
*/
BOOL OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks, BOOL script_cancelled = FALSE);
/**
* Called on mouse up.
*/
void OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks = 1);
/**
Call OnMouseWheel on the form objects widget (or a child to it).
@param point the mouse position (in document coordinates)
@param delta the mouse wheel delta
@param vertical if TRUE, the mouse wheel delta is to be interpreted as vertical
@return TRUE if the wheel event was handled or if it typically handle scroll events (even though it didn't this time).
*/
BOOL OnMouseWheel(const OpPoint &point, INT32 delta, BOOL vertical);
/**
* Called when cursor is positioned.
*/
void OnSetCursor(const OpPoint &point);
#endif // !MOUSELESS
// Implementing OpInputContext interface
/**
* Called when an input action happens.
*/
virtual BOOL OnInputAction(OpInputAction* action);
/**
* The name of the input context.
*/
virtual const char* GetInputContextName() { return "Form"; }
/**
* Set focus.
*/
virtual void SetFocus(FOCUS_REASON reason);
/**
* Called when focus is gained or lost.
*/
virtual void OnFocus(BOOL focus, FOCUS_REASON reason);
/**
* Called when keyboard focus is moved to this object.
*/
virtual void OnKeyboardInputGained(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason);
/**
* Called when keyboard focus is moved away from this object.
*/
virtual void OnKeyboardInputLost(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason);
/**
* Focus gained.
*/
void HandleFocusGained(FOCUS_REASON reason);
/**
* Focus lost.
*/
void HandleFocusLost(FOCUS_REASON reason);
/**
* Is the widget in RTL mode?
*
* @returns TRUE if the UI widget is in RTL (right to left) mode.
*/
BOOL IsInRTLMode() { return opwidget->GetRTL(); }
#ifdef SELFTEST
/**
* Sets that the value in this FormValue was input in RTL (right-to-left) mode.
* The default is FALSE (ltr).
*
* @param set_to_rtl TRUE if RTL, FALSE if LTR.
*/
void SetInRTLMode(BOOL set_to_rtl) { opwidget->SetRTL(set_to_rtl); }
#endif // SELFTEST
/**
* Inform the formobject/widget of what kind of borders to use.
* This is needed to prevent the widget from drawing an extra
* layer of borders and for it to be able to calculate its
* size accurately.
*
* @param props The CSS for this object.
*/
void SetCssBorders(const HTMLayoutProperties& props);
/**
* Checks if the author has specified a border that should be
* drawn with CSS borders (or not drawn at all). When this
* returns FALSE we draw borders with the default skinnable
* widget borders.
*
* @param props The resolved CSS properties for the element.
*
* @param helm The HTML_Element that the CSS is placed on.
*/
static BOOL HasSpecifiedBorders(const HTMLayoutProperties& props,
HTML_Element* helm);
/**
* Checks if the author has specified a background image that
* should be drawn.
*
* @param frm_doc The document this html element belongs to.
* @param props The resolved CSS properties for the element.
* @param helm The HTML_Element that the CSS is placed on.
*/
static BOOL HasSpecifiedBackgroundImage(FramesDocument* frm_doc,
const HTMLayoutProperties& props,
HTML_Element* helm);
/**
* Stores a validation error window in the FormObject for tracking
* while displaying.
*
* @param error The window to set.
*/
void SetValidationError(ValidationErrorWindow* error) { m_validation_error = error; }
/**
* Returns a window set with SetValidationError
*
* @returns The window or NULL if no window was set.
*/
ValidationErrorWindow* GetValidationError() { return m_validation_error; }
#ifdef WIDGETS_IME_SUPPORT
/**
* Set the IME style of an OpEdit from the ISTYLE attribute or the
* input-format css property
*/
void UpdateIMStyle();
void HandleFocusEventFinished();
#endif // WIDGETS_IME_SUPPORT
/**
* Returns the element that is most relevant to mouse events at a
* certain position. Is most likely the formobject's own element
* but might be a HE_OPTION for instance.
*
* @returns an element, never NULL.
*/
HTML_Element* GetInnermostElement(int document_x, int document_y);
/**
* Returns TRUE if the given input type has a textfield widget
* as external representation.
*
*/
static BOOL IsEditFieldType(InputType type);
public:
/**
* The CSS border left width. This shouldn't be public and should
* have a m_ prefix.
*/
int css_border_left_width;
/**
* The CSS border top width.
*/
int css_border_top_width;
/**
* The CSS border rigth width.
*/
int css_border_right_width;
/**
* The CSS border bottom width.
*/
int css_border_bottom_width;
protected:
/**
* Sets widget properties by checking what the HTML says.
*
* @param set_start_value If it is allowed to change the value to some default value.
*/
virtual OP_STATUS ConfigureWidgetFromHTML(BOOL set_start_value);
/**
* Helper that converts from document coordinates to coordinates relative to the widget
*/
static OpPoint ToWidgetCoords(OpWidget* widget, const OpPoint& doc_point);
private:
#ifdef WAND_HAS_MATCHES_WARNING
/**
* Sometimes we don't want to let the user enter a
* text field until we have informed the user
* about the availability of wand data. This is
* the case for instance in the BREW version.
* In those cases this method will return TRUE
* and display a warning. Otherwise it
* will return FALSE and do nothing.
*
* @returns TRUE if the method displayed/initiated a warning.
*/
BOOL WarnIfWandHasData();
#endif // WAND_HAS_MATCHES_WARNING
/**
* Paint borders special to this form object. F.ex border that indicates that the object
* has wand data.
*
* @param props Layout properties to use.
* @param vis_dev A VisualDevice.
*/
void PaintSpecialBorders(const HTMLayoutProperties& props, VisualDevice* vis_dev);
};
/**
* Form object representing an input object.
*/
class InputObject : public FormObject
{
private:
/**
* Constructor.
*/
InputObject(VisualDevice* vd,
FramesDocument* doc,
InputType type,
HTML_Element* he,
BOOL read_only);
/**
* Second part of the constructor (check boxes and radio things). This may fail.
*/
OP_STATUS Construct(VisualDevice* vd,
const HTMLayoutProperties& props,
InputType type,
HTML_Element* he);
/**
* Second part of the constructor. This may fail.
*/
OP_STATUS Construct(VisualDevice* vd,
const HTMLayoutProperties& props,
InputType type,
int maxlength,
HTML_Element* he,
const uni_char* label);
/**
* The type of the object.
*/
InputType object_type;
/**
* Some flags.
*/
/**
* If it is checked.
*/
unsigned int m_is_checked:1;
/**
* If it is checked by default.
*/
unsigned int m_is_checked_by_default:1;
/**
* The default text of the control.
*/
uni_char* m_default_text;
public:
/**
* The way to construct objects. This takes care of the steps
* needed. This is for check boxes and radio things.
*/
static InputObject* Create(VisualDevice* vd,
const HTMLayoutProperties& props,
FramesDocument* doc,
InputType type,
HTML_Element* he,
BOOL read_only);
/**
* The way to construct objects. This takes care of the steps
* needed.
*/
static InputObject* Create(VisualDevice *vd,
const HTMLayoutProperties& props,
FramesDocument* doc,
InputType type,
HTML_Element* he,
int maxlength,
BOOL read_only,
const uni_char* label);
virtual OP_STATUS GetFormWidgetValue(OpString& out_value, BOOL allow_wrap = TRUE);
virtual OP_STATUS SetFormWidgetValue(const uni_char* val);
virtual OP_STATUS SetFormWidgetValue(const uni_char* val, BOOL use_undo_stack);
virtual void Click(ES_Thread* thread);
/**
* @returns TRUE if this check box/radio button is checked by default.
*/
BOOL GetDefaultCheck() const;
/**
* Sets the value read by GetDefaultCheck.
* @param is_checked_default The new value.
* @returns TRUE if this check box/radio button is checked by default.
*/
void SetDefaultCheck(BOOL is_checked_default);
virtual BOOL IsRadioButton() { return object_type == INPUT_RADIO; }
/**
* The input type.
*/
virtual InputType GetInputType() const { return object_type; }
// See base class documentation.
virtual BOOL ChangeTypeInplace(HTML_Element *he);
protected:
virtual OP_STATUS ConfigureWidgetFromHTML(BOOL set_start_value);
/**
* Configure the underlying text edit widget as needed to
* to hold an input element corresponding to the given element.
*
* @param he The element with the text-editable input element.
* @param edit The edit widget to configure.
* @param placeholder If non-NULL, the placeholder text
* to set.
*/
static void ConfigureEditWidgetFromHTML(HTML_Element *he, OpEdit *edit, const uni_char *placeholder);
};
/**
* This object represents a select.
*/
class SelectionObject : public FormObject, private OpTimerListener
{
private:
/**
* Number of visible elements.
*/
int m_page_requested_size;
/**
* Multi select control.
*/
BOOL m_multi_selection;
/**
* Min width in pixels.
*/
int m_min_width;
/**
* Max width in pixels.
*/
int m_max_width;
/**
* Cached value to make it possible to add elements outside of the layout engine.
*/
BOOL m_last_set_need_intrinsic_width;
/**
* Cached value to make it possible to add elements outside of the layout engine.
*/
BOOL m_last_set_need_intrinsic_height;
/**
* The timer used for asynchronous rebuild of the FormValueList.
* @see ScheduleFormValueRebuild()
*/
OpTimer m_form_value_rebuild_timer;
/**
* TRUE if a rebuild timer has been started but hasn't fired.
* @see ScheduleFormValueRebuild()
*/
BOOL m_form_value_rebuild_timer_active;
/**
* Init with layout information.
*
* @param props Layout information
* @param doc Used to look up site
* specific layout preferences.
*/
void Init(const HTMLayoutProperties& props, FramesDocument* doc);
/**
* Constructor. Private.
*
* @param vd The visual device.
* @param doc The doc this form object belongs to
* @param multi If it's a listbox (TRUE) or a dropdown (FALSE).
*/
SelectionObject(VisualDevice* vd,
FramesDocument* doc,
BOOL multi,
int size,
int min_width,
int max_width,
HTML_Element* he);
public:
~SelectionObject()
{
m_form_value_rebuild_timer.Stop();
}
/**
* Constructor. The right way to get a SelectionObject.
*
* @param vd The visual device.
* @param props The current look of this form thing.
* @param doc The doc this form object belongs to
* @param multi If it's a listbox (TRUE) or a dropdown (FALSE).
* @param size The expected size.
* @param form_width The width
* @param form_height The height
* @param min_width The minimum allowed width
* @param max_width The maximum allowed width
* @param he The HTML Element thing this is connected to.
* @param use_default_font
* @param created_selection_object Out parameter that will contain
* the constructed object if the method returns OpStatus::OK
*
*/
static OP_STATUS ConstructSelectionObject(VisualDevice* vd,
const HTMLayoutProperties& props,
FramesDocument* doc,
BOOL multi,
int size,
int form_width,
int form_height,
int min_width,
int max_width,
HTML_Element* he,
BOOL use_default_font,
FormObject*& created_selection_object);
/**
* Constructor.
*/
OP_STATUS ConstructInternals(const HTMLayoutProperties& props,
int form_width,
int form_height,
BOOL use_default_font);
/**
* Add a new element.
*/
OP_STATUS AddElement(const uni_char* txt, BOOL selected, BOOL disabled, int idx = -1);
/**
* Apply layout properties to an option element.
*
* @param[in] idx The index (zero-based) of the option. Has to exist in the SelectionObject.
*
* @param[in] props The CSS properties to apply to the option.
*/
void ApplyProps(int idx, class LayoutProperties* props);
/**
* Change an option element, giving it a new text.
*/
OP_STATUS ChangeElement(const uni_char* txt, BOOL selected, BOOL disabled, int idx);
/**
* Remove an element.
*/
void RemoveElement(int idx);
/**
* Remove all elements.
*/
void RemoveAll();
/**
* Begin an option group.
*
* @param[in] The HE_OPTGROUP element.
*
* @param[in] props The style for the option. If this is not NULL, then elm
* can be NULL. If this is NULL, then we will use elm to get a rough estimate.
*/
OP_STATUS BeginGroup(HTML_Element* elm, const HTMLayoutProperties* props = NULL);
/**
* End an option group.
*
* @param[in] The HE_OPTGROUP element.
*
*/
void EndGroup(HTML_Element* elm);
/**
* Remove an option group.
*/
void RemoveGroup(int idx);
/**
* Remove all option groups.
*/
void RemoveAllGroups();
/**
* Returns TRUE if the element at the index
* (counting all elements, including starts
* and stops) is a group stop.
*/
BOOL ElementAtRealIndexIsOptGroupStop(unsigned int idx);
/**
* Returns TRUE if the element at the index
* (counting all elements, including starts
* and stops) is a group start.
*/
BOOL ElementAtRealIndexIsOptGroupStart(unsigned int idx);
/**
* Changes the multi attribute. If multi is TRUE and it is a
* dropdown, it will switch to a listbox. If it is a listbox and
* multi is FALSE and size is 1, it switches to a dropdown
*/
// OP_STATUS ChangeMulti(BOOL multi);
/**
* Overridden GetValue.
*/
virtual OP_STATUS GetFormWidgetValue(OpString& out_value, BOOL allow_wrap = TRUE);
/**
* Overridden SetValue.
*/
virtual OP_STATUS SetFormWidgetValue(const uni_char * szValue);
/**
* Dispatches click event when clicking on a label for this element.
*/
virtual void Click(ES_Thread* thread);
/**
* Returns TRUE if the specified element is selected.
*/
BOOL IsSelected(int idx);
/**
* Returns TRUE if the specified element is disabled.
*/
BOOL IsDisabled(int idx);
/**
* Needed so that the base class' IsDisabled becomes reachable.
*/
BOOL IsDisabled() { return FormObject::IsDisabled(); }
/**
* TRUE if multi selection control.
*/
BOOL IsMultiSelection() { return m_multi_selection; }
/**
* TRUE if it's a list box.
*/
BOOL IsListbox()
{
#ifdef FORMS_SELECT_IGNORE_SIZE // tweak used by Opera Mini
return m_multi_selection;
#else
return m_page_requested_size > 1 || m_multi_selection;
#endif // FORMS_SELECT_IGNORE_SIZE
}
/**
* Select or unselect element.
*/
void SetElement(int i, BOOL selected);
/**
* Get count of elements. It doesn't include group start and group end elements.
*/
int GetElementCount();
/**
* Get count of elements. This does include group start and group end elements.
*/
unsigned int GetFullElementCount();
/**
* If it's a listbox and the selected element is outside of the
* currently visible are, it will be scrolled to display the
* selected element.
*/
void ScrollIfNeeded();
/**
* Get selected index (single selection).
*/
int GetSelectedIndex();
/**
* Set selected index (single selection).
*/
void SetSelectedIndex(int index);
/**
* Start add element.
*/
void StartAddElement() {}
/**
* End adding elements.
*
* @return The preferred width of the widget, or
* the current width if need_intrinsic_width is FALSE.
*/
INT32 EndAddElement(BOOL need_intrinsic_width, BOOL need_intrinsic_height);
/**
* End adding elements.
*
* @return The preferred width of the widget, or the current width if
* need_intrinsic_width was FALSE in the last call to EndAddElement(BOOL, BOOL).
*/
INT32 EndAddElement();
/**
* Recalculate the size and update the layout
*/
void ChangeSizeIfNeeded();
/**
* Tells the widget to recalculate their width.
*/
void RecalculateWidestItem();
/**
* The number of options ([start, stop[) that need be updated when
* SelectContent::Paint is called. This is so that styles are
* applied to all relevant option elements in a select. For a
* list box, only the options overlapped by area need be updated,
* since drawing always comes from layout. for a closed dropdown,
* only the selected option need be updated. for an open dropdown,
* all options need be updated, since drawing typically doesn't
* come from layout.
*
* @param[in] area The area in document coordinates.
*
* @param[out] start The index (zero-based) of the first option
* affected by a paint in the area.
*
* @param[out] stop The option after the last affected option. The
* same as start for an empty range.
*/
void GetRelevantOptionRange(const OpRect& area, UINT32& start, UINT32& stop);
/**
* Set min and max width.
*/
void SetMinMaxWidth(int min_width, int max_width) { m_min_width = min_width; m_max_width = max_width; }
/**
* Returns the scrollbar positions, or 0 if none.
*/
int GetWidgetScrollPosition();
/**
* Sets the widget scroll positions. The values should come from an
* earlier call to GetWidgetScrollPosition.
*/
void SetWidgetScrollPosition(int scroll);
/**
* Returns the option (HE_OPTION) at the document coordinates or
* NULL if no such option could be found. Is only relevant and may
* only be called if IsListBox returns TRUE.
*/
HTML_Element* GetOptionAtPos(int document_x, int document_y);
/**
* Locks/unlocks the underlying widget's update.
* The behavior when locked may be different depending on widget's type e.g.
* for OpDropDown when it's locked when opened no changes are propagated
* to its internal OpListBox so it behaves as if it was closed.
*/
void LockWidgetUpdate(BOOL lock);
/**
* Forces an update of the underlying widget e.g. widget's geometry,
* a position of the scrollbar, etc. The behavior may be different depending on widget's type.
* Note that the widget may refuse to update when locked.
* @see LockWidgetUpdate().
*/
void UpdateWidget();
/**
* Schedules an asynchronous rebuild of the FormValueList.
* @see FormaValueList::Rebuild().
*/
void ScheduleFormValueRebuild();
// OpTimerListener's interface.
void OnTimeOut(OpTimer*);
/**
* Returns TRUE if an async rebuild of the widget tree has been
* scheduled, but hasn't yet started.
*/
BOOL HasAsyncRebuildScheduled() { return m_form_value_rebuild_timer_active; }
protected:
/**
* Sets widget properties by checking what the HTML says.
*
* @param set_start_value If it is allowed to change the value to some default value.
*/
virtual OP_STATUS ConfigureWidgetFromHTML(BOOL set_start_value);
};
/**
* Form object representing a text area.
*/
class TextAreaObject : public FormObject
{
/**
* Private constructor. Use the ConstructTextAreaObject method.
*/
TextAreaObject(VisualDevice* vd,
FramesDocument* doc,
int xsize,
int ysize,
BOOL read_only,
HTML_Element* he);
public:
/**
* Constructor. The right way to get a TextAreaObject.
*
* @param vd The visual device.
* @param props The current look of this form thing.
* @param doc The doc this form object belongs to
* @param xsize The expected size.
* @param ysize The expected size.
* @param read_only Set to TRUE to get a read only control.
* @param value The text to put in the text area.
* @param form_width The width
* @param form_height The height
* @param he The HTML Element thing this is connected to.
* @param use_default_font
* @param created_textarea_object Out parameter that will contain
* the constructed object if the method returns OpStatus::OK
*
*/
static OP_STATUS ConstructTextAreaObject(VisualDevice* vd,
const HTMLayoutProperties& props,
FramesDocument* doc,
int xsize,
int ysize,
BOOL read_only,
const uni_char* value,
int form_width,
int form_height,
HTML_Element* he,
BOOL use_default_font,
FormObject*& created_textarea_object);
/**
* The input type of the text area (INPUT_TEXTAREA).
*/
virtual InputType GetInputType() const { return INPUT_TEXTAREA; }
/**
* Overridden GetValue.
*/
virtual OP_STATUS GetFormWidgetValue(OpString& out_value, BOOL allow_wrap = TRUE);
/**
* Overridden SetValue.
* @param szValue text to set
* @param use_undo_stack whether the undo buffer
* should be used to store the previous value
* so this SetText call is undoable
*/
virtual OP_STATUS SetFormWidgetValue(const uni_char * szValue);
virtual OP_STATUS SetFormWidgetValue(const uni_char * szValue, BOOL use_undo_stack);
// See base class documentation
virtual void Click(ES_Thread* thread);
/**
* The number of rows.
*/
int GetRows() const { return m_rows; }
/**
* the number of cols.
*/
int GetCols() const { return m_cols; }
/**
* Get preferred height.
*/
int GetPreferredHeight() const;
/**
* This is used to make sure that we don't drop a document
* with user changes from the cache. This was added in core-1.
* Make sure the code calling this code is also merged from core-2.
*/
void SetIsUserModified() { m_is_user_modified = TRUE; }
/**
* This is used to make sure that we don't drop a document
* with user changes from the cache. This was added in core-1.
* Make sure the code calling this code is also merged from core-2.
*/
BOOL IsUserModified() { return m_is_user_modified; }
/**
* Returns the scrollbar positions, or 0 if none.
*/
void GetWidgetScrollPosition(int& out_scroll_x, int& out_scroll_y);
/**
* Sets the widget scroll positions. The values should come from an
* earlier call to GetWidgetScrollPosition.
*/
void SetWidgetScrollPosition(int scroll_x, int scroll_y);
/**
* Returns the size of the inner area in the widget. This
* changes when the user edits the text. Used by DOM code
* so that scripts can dynamically resize the textarea.
*
* @param[out] out_width The scrollable width of the widget
*
* @param[out] out_height The scrollable height of the widget
*/
void GetScrollableSize(int& out_width, int& out_height);
// see base class documentation.
virtual void GetSelection(INT32& start_ofs, INT32& stop_ofs, SELECTION_DIRECTION& direction);
// see base class documentation.
virtual void SetSelection(INT32 start_ofs, INT32 stop_ofs, SELECTION_DIRECTION direction = SELECTION_DIRECTION_DEFAULT);
// see base class documentation.
virtual INT32 GetCaretOffset();
// see base class documentation.
virtual void SetCaretOffset(INT32 caret_ofs);
protected:
/**
* Sets widget properties by checking what the HTML says.
*
* @param set_start_value If it is allowed to change the value to some default value.
*/
virtual OP_STATUS ConfigureWidgetFromHTML(BOOL set_start_value);
private:
/**
* Helper method.
*
* @param props Layout properties.
*
* @param form_width width.
*
* @param form_height height.
*
* @param use_default_font TRUE if a default font should be used.
*/
OP_STATUS ConstructInternals(const HTMLayoutProperties& props,
const uni_char* value,
int form_width,
int form_height,
BOOL use_default_font);
/**
* count of rows.
*/
int m_rows;
/**
* Count of cols.
*/
int m_cols;
/**
* If the user has modified the text. We'll use this to prevent ourselves from
* dropping documents with user changed data from the cache.
*/
BOOL m_is_user_modified;
/**
* Set text.
*
* @param value the text to set
* @param use_undo_stack whether the undo buffer
* should be used to store the previous value
* so this SetText call is undoable
*/
OP_STATUS SetText(const uni_char* value, BOOL use_undo_stack = FALSE);
};
/**
* Form object for a file upload field.
*/
class FileUploadObject : public FormObject
{
public:
/**
* Private constructor. Use the ConstructFileUploadObject method.
*/
FileUploadObject(VisualDevice* vd,
FramesDocument* doc,
BOOL read_only,
HTML_Element* he);
/**
* Constructor. The right way to get a FileUploadObject
*
* @param vd The visual device.
* @param props The current look of this form thing.
* @param doc The doc this form object belongs to
* @param read_only If it should be read only or not.
* @param szValue The value to put in the newly created file upload.
* @param he The HTML Element thing this is connected to.
* @param use_default_font
* @param created_file_upload_object Out parameter that will contain
* the constructed object if the method returns OpStatus::OK
*
*/
static OP_STATUS ConstructFileUploadObject(VisualDevice* vd,
const HTMLayoutProperties& props,
FramesDocument* doc,
BOOL read_only,
const uni_char* szValue,
HTML_Element* he,
BOOL use_default_font,
FormObject*& created_file_upload_object);
OP_STATUS ConstructInternals(const HTMLayoutProperties& props,
const uni_char* szValue,
BOOL use_default_font);
/** Symbolic value representing the maximum number of files that
the underlying upload file widget will allow selection of.
The widget currently only checks to see if the value is greater
than 1, so any value higher than that suffices to provide multiple
file selection. */
enum { MaxNumberOfUploadFiles = 10000 };
/**
* Overridden GetValue.
*/
virtual OP_STATUS GetFormWidgetValue(OpString& out_value, BOOL allow_wrap = TRUE);
/**
* Overridden SetValue.
*/
virtual OP_STATUS SetFormWidgetValue(const uni_char * szValue);
/**
* Overridden GetInputType, returning INPUT_FILE.
*/
virtual InputType GetInputType() const { return INPUT_FILE; }
/**
* Overridden Click.
*
* @param thread If script generated, the thread that generated the click, otherwise NULL.
*/
virtual void Click(ES_Thread* thread);
};
#endif // PIFORMS_H
|
#include <iostream>
#include <vector>
#include <algorithm>
#define mid lt + (rt-lt)/2
#define vx Element *
using namespace std;
struct Window {
int y, r, l;
char ble;
};
Window make_window(int y, int l, int r, char ble) {
Window *node = new Window;
node->y = y;
node->r = r;
node->l = l;
node->ble = ble;
return *node;
}
struct Element {
int maxi = INT_MIN;
long long add = 0;
vx right = nullptr;
vx left = nullptr;
int x = 0;
};
void setMax(vx v) {
if (!v)
return;
if (v->left && v->right) {
if (v->left->maxi > v->right->maxi) {
v->maxi = v->left->maxi;
v->x = v->left->x;
} else {
v->maxi = v->right->maxi;
v->x = v->right->x;
}
} else if (v->left) {
v->maxi = v->left->maxi;
v->x = v->left->x;
} else if (v->right) {
v->maxi = v->right->maxi;
v->x = v->right->x;
}
}
vx make_vertex(vx left, vx right) {
vx node = new Element();
node->right = right;
node->left = left;
setMax(node);
return node;
}
vx make_list(int value, int x) {
vx node = new Element();
node->maxi = value;
node->left = nullptr;
node->right = nullptr;
node->x = x;
return node;
}
class SegTree {
public:
SegTree(int n) : size(n) {
root = build(0, size - 1);
}
pair<int, int> get(int l, int r) {
return get(root, l, r, 0, size - 1);
}
void Add(int l, int r, int value) {
Add(root, value, 0, size - 1, l, r);
}
private:
int size;
vx root;
void Add(vx v, int value, int lt, int rt, int l, int r) {
if (lt > r || rt < l)
return;
if (v->add) {
if (v->left) {
v->left->add += v->add;
v->left->maxi += v->add;
}
if (v->right) {
v->right->add += v->add;
v->right->maxi += v->add;
}
v->add = 0;
}
if (l <= lt && rt <= r) {
v->add += value;
v->maxi += value;
} else {
Add(v->left, value, lt, mid, l, r);
Add(v->right, value, mid + 1, rt, l, r);
setMax(v);
}
}
vx build(int lt, int rt) {
if (lt == rt)
return make_list(0, lt);
return make_vertex(build(lt, mid), build(mid + 1, rt));
}
pair<int, int> get(vx v, int l, int r, int lt, int rt) {
return {v->maxi, v->x};
}
};
bool comp(Window a, Window b) {
return (a.y == b.y) ? a.ble < b.ble : a.y < b.y;
}
const int off = 1000000;
int main() {
int n, x1, y1, x2, y2;
cin >> n;
vector<Window> W;
for (int i = 0; i < n; i++) {
cin >> x1 >> y1 >> x2 >> y2;
W.push_back(make_window(y1, x1, x2, 'b'));
W.push_back(make_window(y2, x1, x2, 'e'));
}
sort(W.begin(), W.end(), comp);
SegTree tree(2 * off);
int bla;
int ans = INT_MIN;
int x, y;
pair<int, int> q;
for (int i = 0; i < 2 * n; i++) {
if (W[i].ble == 'b') bla = 1;
else bla = -1;
tree.Add(W[i].l + off, W[i].r + off, bla);
q = tree.get(0, 2 * n - 1);
if (q.first > ans) {
ans = q.first;
x = q.second - off;
y = W[i].y;
}
}
cout << ans << endl << x << ' ' << y << endl;
return 0;
}
|
#include "COtherCategory.h"
COtherCategory::COtherCategory(QObject *parent)
: CERPCategory(parent)
{
}
COtherCategory::~COtherCategory()
{
}
QString COtherCategory::Category()const
{
return QString::fromLocal8Bit("ÆäËû");
}
|
#pragma once
#include"Padre.h"
#include"PoderTeamA.h"
#include<List>
using namespace System::Drawing;
using namespace std;
class TeamA:public Padre
{
private:
bool transparente;
int puntoH;
int puntoV;
int AnchoI;
int AltoI;
public:
TeamA(int x,int y,Bitmap^bmp);
TeamA();
~TeamA();
void SET_transparente(bool k);
void SET_puntoH(int k);
void SET_puntoV(int k);
void SET_AnchoI(int k);
void SET_AltoI(int k);
bool GET_transparente();
int GET_puntoH();
int GET_puntoV();
int GET_AnchoI();
int GET_AltoI();
void Dibujar(Graphics^gr, Bitmap^bmp);
void Mover(Graphics^gr, Bitmap^bmp);
void DibujarVida(Graphics^gr);
//poder
list<PoderTeamA*> list_PoderA;
void AgregarPoder(int x, int y, Bitmap^bmp);
void MostrarPoder(Graphics^gr, Bitmap^bmp);
};
TeamA::TeamA(int x, int y, Bitmap^bmp)
{
SET_X(x);
SET_Y(y);
SET_transparente(true);
SET_puntoH(0);
SET_puntoV(2);
SET_AnchoI(bmp->Width / 12);
SET_AltoI(bmp->Height / 8);
SET_Dx(0);
SET_Dy(0);
SET_Alto(30);
SET_Ancho(30);
SET_movimiento(Direccion::Ninguno);
SET_Vida(30);
}
TeamA::TeamA()
{
}
TeamA::~TeamA()
{
}
void TeamA::SET_transparente(bool k){ transparente = k; }
void TeamA::SET_puntoH(int k){ puntoH = k; }
void TeamA::SET_puntoV(int k){ puntoV = k; }
void TeamA::SET_AnchoI(int k){ AnchoI = k; }
void TeamA::SET_AltoI(int k){ AltoI = k; }
bool TeamA::GET_transparente(){return transparente;}
int TeamA::GET_puntoH(){return puntoH;}
int TeamA::GET_puntoV(){return puntoV;}
int TeamA::GET_AnchoI(){return AnchoI;}
int TeamA::GET_AltoI(){return AltoI;}
void TeamA::Dibujar(Graphics^gr, Bitmap^bmp){
Rectangle Origen = Rectangle(GET_AnchoI()*GET_puntoH(), GET_AltoI()*GET_puntoV(), GET_AnchoI(), GET_AltoI());
Rectangle Fin = Rectangle(GET_X(), GET_Y(), GET_Ancho(), GET_Alto());
gr->DrawImage(bmp, Fin, Origen, GraphicsUnit::Pixel);
if (puntoH == 2){
puntoH = 0;
}
puntoH++;
}
void TeamA::Mover(Graphics^gr, Bitmap^bmp){
switch (GET_movimiento())
{
case Arriba:
SET_Dy(-5);
SET_Y(GET_Y() + GET_Dy());
SET_puntoV(3);
break;
case Abajo:
SET_Dy(5);
SET_Y(GET_Y() + GET_Dy());
SET_puntoV(0);
break;
case Derecha:
SET_Dx(5);
SET_X(GET_X() + GET_Dx());
SET_puntoV(2);
break;
case Izquiera:
SET_Dx(-5);
SET_X(GET_X() + GET_Dx());
SET_puntoV(1);
break;
case Ninguno:
SET_Dx(0);
SET_Dy(0);
SET_puntoV(2);
break;
}
Dibujar(gr, bmp);
}
void TeamA::DibujarVida(Graphics^gr){
gr->DrawRectangle(gcnew Pen(Color::Black),GET_X()-1,GET_Y()-6,31,4);
gr->FillRectangle(gcnew SolidBrush(Color::Red), GET_X(), GET_Y()-5, GET_Vida(), 3);
}
//poder
void TeamA::AgregarPoder(int x, int y, Bitmap^bmp){
list_PoderA.push_back(new PoderTeamA(x, y, bmp));
}
void TeamA::MostrarPoder(Graphics^gr, Bitmap^bmp){
for (list<PoderTeamA*>::iterator it = list_PoderA.begin(); it != list_PoderA.end(); ++it){
(*it)->Dibujar(gr, bmp);
}
}
//197-133
|
#include <iostream>
#include <vector>
#include <map>
using namespace std;
map<int, int> myMap;
int c[200000];
void modMerge(int a[], int l, int m, int r)
{
int n = r-l+1, k, i, j;
for(i=m, j=r, k=n-1; i>=l && j>m; )
{
if(a[i] > a[j])
{
map<int, int>::iterator it = myMap.find(a[i]);
it->second += j-m;
c[k] = a[i];
--k;--i;
}
else
{
c[k] = a[j];
--k;--j;
}
}
while(i>=l) { c[k] = a[i]; --i; --k; }
while(j>m) { c[k] = a[j]; --j; --k; }
// copy into the original
for(i=0; i<n; ++i)
a[l+i] = c[i];
}
void modMergeSort(int a[], int l, int r)
{
if(l >= r)
return;
int mid = l + (r-l)/2;
modMergeSort(a, l, mid);
modMergeSort(a, mid+1, r);
modMerge(a, l, mid, r);
}
int main()
{
int t, n, m, i, j, x;
int a[100000], b[100000];
cin >> t;
while(t--)
{
cin >> n;
myMap.clear();
for(i=0; i<n; ++i)
{
cin >> a[i];
myMap[a[i]] = 0;
b[i] = a[i];
}
modMergeSort(a, 0, n-1);
for(i=0; i<n; ++i)
{
cout<<myMap.find(b[i])->second<<" ";
}
cout<<endl;
}
return 0;
}
|
/*
plane.cpp
Colin Fitt -- cfitt -- C6312039
Course CpSci 1020, Prof. Catherine Hochrine
Major Programming Assignment #3: Due 11:59pm Sunday, April 20th
This program parses and loads the data for the plane structure.
Also a printerer function.
*/
#include "ray.h"
pparm_t plane_parse[] = {
{"point", 3, sizeof(double), "%lf", 0},
{"normal", 3, sizeof(double), "%lf", 0},
};
#define NUM_ATTRS (sizeof(plane_parse) / sizeof(pparm_t))
plane_t::plane_t(FILE *in, model_t *model,int attrmax) : object_t(in, model)
{
int mask;
strcpy(obj_type, "plane");
/* The parser is fairly generic but the address of where to */
/* put the data must be updated for each new object */
plane_parse[0].loc = &point;
plane_parse[1].loc = &normal;
mask = parser(in, plane_parse, NUM_ATTRS, attrmax);
assert(mask == 3);
vec_unit(&normal, &normal);
vec_copy(&normal, &last_normal);
ndotq = vec_dot(&point, &normal);
}
double plane_t::hits(
vec_t *base, /* ray base */
vec_t *dir) /* unit direction vector */
{
double ndotd;
double t;
double ndotb;
ndotq = vec_dot(&normal, &point);
ndotd = vec_dot(dir, &normal);
if (ndotd == 0)
return(-1);
ndotb = vec_dot(&normal, base);
t = (ndotq - ndotb) / ndotd;
if (t <= 0)
return(-1);
vec_scale(t, dir, &last_hitpt);
vec_sum(&last_hitpt, base, &last_hitpt);
if ((last_hitpt.z > 0.01) && (strcmp(obj_type, "projector")))
return(-1);
return(t);
}
void plane_t::printer(FILE *out)
{
object_t::printer(out);
fprintf(out, "%-12s %5.1lf %5.1lf %5.1lf \n",
"normal", normal.x, normal.y, normal.z);
fprintf(out, "%-12s %5.1lf %5.1lf %5.1lf \n",
"point", point.x, point.y, point.z);
}
|
/* -*- 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.
*/
/*
Cross-module security manager: DOM model
Lars T Hansen.
See documentation/document-security.txt in the documentation directory. */
#ifndef SECURITY_DOM_H
#define SECURITY_DOM_H
class OpSecurityContext;
class OpSecurityState;
class OpSecurityCheckCallback;
class OpSecurityCheckCancel;
class DOM_Runtime;
class OpSecurityManager_DOM
{
public:
OpSecurityManager_DOM();
#ifdef SECMAN_ALLOW_DISABLE_XHR_ORIGIN_CHECK
OP_STATUS SetSkipXHROriginCheck(DOM_Runtime* runtime, BOOL& state);
/**< Sets a flag in the runtime which causes it to skip origin checks
while doing XHR. This allows cross-domain XHR, use with caution.
This function will return OpStatus::FAILED unless AllowSetSkiptXHROriginCheck
has been set.*/
void AllowSetSkipXHROriginCheck(BOOL& allow);
/**< This will set a flag to allow the SetSkipXHROriginCheck to be run. */
#endif // SECMAN_ALLOW_DISABLE_XHR_ORIGIN_CHECK
BOOL AllowedToNavigate(const OpSecurityContext& source, const OpSecurityContext& target);
/**< Checks if a context is allowed to navigate another context, e.g., by changing
window.location. Based on policy in HTML5 spec. */
#ifndef SELFTEST
private:
#endif //SELFTEST
static double GetProtocolMatchRank(const OpString& protocol, const OpString& pattern);
/**< Returns the number telling how well the protocol name matches the given pattern;
* e.g. 1.0 means a perfect match. */
protected:
#ifdef SECMAN_ALLOW_DISABLE_XHR_ORIGIN_CHECK
BOOL allow_set_skip_origin_check;
#endif // SECMAN_ALLOW_DISABLE_XHR_ORIGIN_CHECK
OP_STATUS CheckLoadSaveSecurity(const OpSecurityContext& source, const OpSecurityContext& target, BOOL& allowed, OpSecurityState& state);
/**< Check that the source context can run a specific script in the target
context. The target context must include the source code for the script. */
OP_STATUS CheckLoadSaveSecurity(const OpSecurityContext& source, const OpSecurityContext& target, OpSecurityCheckCallback* security_callback, OpSecurityCheckCancel **security_cancel);
/**< Check that the source context allows loading or saving resources
at the target context. Callback is notified of outcome. */
BOOL CheckOperaConnectSecurity(const OpSecurityContext &source);
/**< Check that the source context is allowed access to the 'opera.connect' API.
The source context must include the runtime making the request. */
#ifdef JS_SCOPE_CLIENT
BOOL CheckScopeSecurity(const OpSecurityContext &source);
/**< Check that the source context is allowed access to the 'opera.scope*'
API functions. The source context must include the runtime making
the request. */
#endif // JS_SCOPE_CLIENT
#ifdef EXTENSION_SUPPORT
OP_STATUS CheckExtensionSecurity(const OpSecurityContext& source, const OpSecurityContext& target, BOOL& allowed);
/**< Check that the source context can run a specific script in the target
context, optionally owned by an extension. The target context must
include the source URL and the extension owning it. */
#endif // EXTENSION_SUPPORT
#if defined(DOCUMENT_EDIT_SUPPORT) && defined(USE_OP_CLIPBOARD)
BOOL CheckClipboardAccess(const OpSecurityContext& source);
/**< Check whether the context is allowed to read and write into the
system clipboard. */
#endif // DOCUMENT_EDIT_SUPPORT && USE_OP_CLIPBOARD
#ifdef WEB_HANDLERS_SUPPORT
OP_STATUS CheckWebHandlerSecurity(const OpSecurityContext& source, const OpSecurityContext& target, BOOL& allowed);
/**< Check that a page is allowed to register handler for a protocol
stored in the target security context's text data. The page and
handler URLs are stored in the source and target contexts,
respectively. */
#endif// WEB_HANDLERS_SUPPORT
#ifdef DOM_WEBWORKERS_SUPPORT
OP_STATUS CheckWorkerScriptImport(const OpSecurityContext& source, const OpSecurityContext& target, BOOL& allowed);
/**< Check that a Web Worker's source context is allowed to import a
a script from target. */
#endif // DOM_WEBWORKERS_SUPPORT
};
#endif // SECURITY_DOM_H
|
#include "gtest/gtest.h"
using namespace testing;
class ConfigurableEventListener : public TestEventListener
{
protected:
TestEventListener* eventListener;
public:
/**
* Show the names of each test case.
*/
bool showTestCases;
/**
* Show the names of each test.
*/
bool showTestNames;
/**
* Show each success.
*/
bool showSuccesses;
/**
* Show each failure as it occurs. You will also see it at the bottom after the full suite is run.
*/
bool showInlineFailures;
/**
* Show the setup of the global environment.
*/
bool showEnvironment;
explicit ConfigurableEventListener(TestEventListener* theEventListener) : eventListener(theEventListener)
{
showTestCases = true;
showTestNames = true;
showSuccesses = true;
showInlineFailures = true;
showEnvironment = true;
}
virtual ~ConfigurableEventListener()
{
delete eventListener;
}
virtual void OnTestProgramStart(const UnitTest& unit_test)
{
eventListener->OnTestProgramStart(unit_test);
}
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration)
{
eventListener->OnTestIterationStart(unit_test, iteration);
}
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test)
{
if(showEnvironment) {
eventListener->OnEnvironmentsSetUpStart(unit_test);
}
}
virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test)
{
if(showEnvironment) {
eventListener->OnEnvironmentsSetUpEnd(unit_test);
}
}
virtual void OnTestCaseStart(const TestCase& test_case)
{
if(showTestCases) {
eventListener->OnTestCaseStart(test_case);
}
}
virtual void OnTestStart(const TestInfo& test_info)
{
if(showTestNames) {
eventListener->OnTestStart(test_info);
}
}
virtual void OnTestPartResult(const TestPartResult& result)
{
eventListener->OnTestPartResult(result);
}
virtual void OnTestEnd(const TestInfo& test_info)
{
if((showInlineFailures && test_info.result()->Failed()) || (showSuccesses && !test_info.result()->Failed())) {
eventListener->OnTestEnd(test_info);
}
}
virtual void OnTestCaseEnd(const TestCase& test_case)
{
if(showTestCases) {
eventListener->OnTestCaseEnd(test_case);
}
}
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test)
{
if(showEnvironment) {
eventListener->OnEnvironmentsTearDownStart(unit_test);
}
}
virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test)
{
if(showEnvironment) {
eventListener->OnEnvironmentsTearDownEnd(unit_test);
}
}
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration)
{
eventListener->OnTestIterationEnd(unit_test, iteration);
}
virtual void OnTestProgramEnd(const UnitTest& unit_test)
{
eventListener->OnTestProgramEnd(unit_test);
}
};
int main(int argc, char **argv)
{
// initialize
::testing::InitGoogleTest(&argc, argv);
// remove the default listener
testing::TestEventListeners& listeners = testing::UnitTest::GetInstance()->listeners();
auto default_printer = listeners.Release(listeners.default_result_printer());
// add our listener, by default everything is on (the same as using the default listener)
// here I am turning everything off so I only see the 3 lines for the result
// (plus any failures at the end), like:
// [==========] Running 149 tests from 53 test cases.
// [==========] 149 tests from 53 test cases ran. (1 ms total)
// [ PASSED ] 149 tests.
ConfigurableEventListener *listener = new ConfigurableEventListener(default_printer);
listener->showEnvironment = false;
listener->showTestCases = false;
listener->showTestNames = false;
listener->showSuccesses = false;
listener->showInlineFailures = false;
listeners.Append(listener);
// run
return RUN_ALL_TESTS();
}
|
#pragma once
#include "../stdafx.hpp"
class CLI
{
public:
CLI( void ) = default;
bool RegisterCommand( const std::string& command );
bool RegisterHelpCommand( const std::string& command, const std::string& helper );
bool IsCommand( const std::string& command ) const;
bool NeedHelp( void ) const;
std::string GetCommandValue( const std::string& command ) const;
std::string GetHelp( void ) const;
void parse( int32_t argc, char** argv );
public:
bool m_NeedHelp = false;
std::string m_Helper = "";
std::map< std::string, std::string > m_cCommands;
};
|
#include "linear_form.hpp"
#include "integration.hpp"
namespace space {
namespace {
double EvalHatFn(double x, double y, Element2D *elem, size_t i) {
auto bary = elem->BarycentricCoordinates(x, y);
assert((bary.array() >= 0).all());
return bary[i];
}
} // namespace
std::array<double, 3> LinearForm::QuadEval(Element2D *elem) const {
std::array<double, 3> result;
for (size_t i = 0; i < 3; i++)
result[i] = Integrate(
[&](double x, double y) { return f_(x, y) * EvalHatFn(x, y, elem, i); },
*elem, quad_order_ + 1);
return result;
}
} // namespace space
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
#include <assert.h>
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;
const int N = 88;
int c[N], c2[N];
int d[N][N], d2[N][N];
int cc[N][N];
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
int T;
cin >> T;
for (int __it = 1; __it <= T; __it++) {
int n;
cin >> n;
memset(d, 63, sizeof(d));
for (int i = 1; i <= n; ++i) cin >> c[i];
for (int x = 1; x < n; ++x) {
int y;
cin >> y;
d[x][y] = 1;
d[y][x] = 1;
}
for (int k = 1; k <= n; ++k) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (d[i][k] + d[k][j] < d[i][j]) {
d[i][j] = d[i][k] + d[k][j];
}
}
}
}
int ans = 0;
for (int sx = 1; sx <= n; ++sx) {
for (int sy = 1; sy <= n; ++sy) if (sx != sy) {
int x = sx;
int y = sy;
int cx = 0;
int cy = 0;
int turn = 0;
memcpy(c2, c, sizeof(c));
memcpy(d2, d, sizeof(d));
while (true) {
if ((++turn) & 1) {
if (x == -1) continue;
int to = -1;
for (int j = 1; j <= n; ++j) {
if (d2[x][j] == 1 && d2[j][y] >= d2[x][y]) {
ans = max(ans, cx + maxcost(x, j));
} else
if (d2[x][j] == 1) {
to = j;
}
}
x += c2[x];
c2[x] = 0;
if (to != -1)
d[x][to] = d[to][x] = 0;
x = to;
} else {
}
}
}
}
cout << "Case #" << __it << ": " << ans << endl;
}
return 0;
}
|
#include "compiler/iterators.hpp"
namespace perseus
{
namespace detail
{
istreambuf_multipass_position_iterator::istreambuf_multipass_position_iterator()
{
}
/// Adapting an istreambuf_multipass_utf32_iterator
istreambuf_multipass_position_iterator::istreambuf_multipass_position_iterator( istreambuf_multipass_iterator current, istreambuf_multipass_iterator end )
: _current( current ), _end( end ), _value( current == end ? '\0' : *current )
{
}
/// Destructible
istreambuf_multipass_position_iterator::~istreambuf_multipass_position_iterator() = default;
/// MoveConstructible
istreambuf_multipass_position_iterator::istreambuf_multipass_position_iterator( istreambuf_multipass_position_iterator && rhs )
: _current( rhs._current ), _end( rhs._end ), _position( rhs._position ), _value( rhs._value )
{
rhs._current = istreambuf_multipass_iterator{};
rhs._end = istreambuf_multipass_iterator{};
}
/// MoveAssignable
istreambuf_multipass_position_iterator& istreambuf_multipass_position_iterator::operator=( istreambuf_multipass_position_iterator&& rhs )
{
_current = rhs._current;
_end = rhs._end;
_position = rhs._position;
_value = rhs._value;
rhs._current = istreambuf_multipass_iterator{};
rhs._end = istreambuf_multipass_iterator{};
return *this;
}
/// CopyConstructible
istreambuf_multipass_position_iterator::istreambuf_multipass_position_iterator( const istreambuf_multipass_position_iterator& rhs )
: _current( rhs._current ), _end( rhs._end ), _position( rhs._position ), _value( rhs._value )
{
}
/// CopyAssignable
istreambuf_multipass_position_iterator& istreambuf_multipass_position_iterator::operator=( const istreambuf_multipass_position_iterator& rhs )
{
_current = rhs._current;
_end = rhs._end;
_position = rhs._position;
_value = rhs._value;
return *this;
}
/// EqualityComparable
bool istreambuf_multipass_position_iterator::operator==( const istreambuf_multipass_position_iterator& rhs ) const
{
return std::tie( _current, _end ) == std::tie( rhs._current, rhs._end );
}
/// Inequality comparison
bool istreambuf_multipass_position_iterator::operator!=( const istreambuf_multipass_position_iterator& rhs ) const
{
return !( ( *this ) == rhs );
}
// Element selection through pointer omitted since that makes no sense in the context of char32_t
/// Dereference
const istreambuf_multipass_position_iterator::value_type& istreambuf_multipass_position_iterator::operator*() const
{
return _value;
}
/// Postfix increment
istreambuf_multipass_position_iterator istreambuf_multipass_position_iterator::operator++( int )
{
istreambuf_multipass_position_iterator res( *this );
++( *this );
return res;
}
/// Retrieve position in file
const file_position& istreambuf_multipass_position_iterator::get_position() const
{
return _position;
}
istreambuf_multipass_position_iterator& istreambuf_multipass_position_iterator::operator++()
{
assert( _current != _end );
if( _value == '\n' )
{
_position.line += 1;
_position.column = 0;
}
++_current;
if( _current != _end )
{
_value = *_current;
// don't count continuation bytes
if( ( _value & 0b1100'0000 ) != 0b1000'0000 )
{
_position.column += 1;
}
}
return *this;
}
std::tuple< enhanced_istream_iterator, enhanced_istream_iterator > enhanced_iterators( std::istream& stream )
{
istreambuf_multipass_iterator multipass_begin{ istreambuf_iterator{ stream } };
istreambuf_multipass_iterator multipass_end{ istreambuf_iterator{} };
enhanced_istream_iterator begin{ multipass_begin, multipass_end };
enhanced_istream_iterator end;
return std::make_tuple( begin, end );
}
bool skip_byte_order_mark( enhanced_istream_iterator& it, const enhanced_istream_iterator& end )
{
const detail::enhanced_istream_iterator begin = it;
if(
( it != end && *it++ == '\xEF' ) &&
( it != end && *it++ == '\xBB' ) &&
( it != end && *it++ == '\xBF' )
)
{
return true;
}
else
{
it = begin;
return false;
}
}
}
}
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Triad National Security, LLC. This file is part of the
// Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms
// in the LICENSE file found in the top-level directory of this distribution.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef INTERPFLUXAVG_H
#define INTERPFLUXAVG_H
#include <vector>
// Epetra support
#include "Epetra_Comm.h"
//teuchos support
#include <Teuchos_RCP.hpp>
//#define TUSAS_INTERPFLUXAVG
class interpfluxavg
{
public:
/// Constructor.
interpfluxavg(const Teuchos::RCP<const Epetra_Comm>& comm,
const std::string datafileString );
/// Destructor.
~interpfluxavg();
bool get_source_value(const double time, const int index, double &val);
private:
const Teuchos::RCP<const Epetra_Comm> comm_;
const std::string datafileString_;
const int stride_;
int timeindex_;
std::vector<double> data;
void read_file();
};
#endif
|
#include <iostream>
using namespace std;
int main()
{
int t, n, k, rem, sz, temp, r;
string ans = "";
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> n >> k;
rem = n % k;
sz = n / k;
for (int i = 0, r = 1; i < n; i++)
{
ans += (char)(96 + r);
r = (r + 1) % (k + 1);
if (r == 0)
r = 1;
}
cout << ans << endl;
ans = "";
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2005 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 SVG_SUPPORT
#include "modules/svg/src/svgpch.h"
#include "modules/svg/src/SVGCanvasState.h"
#include "modules/svg/src/svgpaintserver.h"
#include "modules/svg/src/svgpainter.h"
#include "modules/layout/layoutprops.h"
SVGCanvasState::SVGCanvasState() :
m_fill_seq(0)
,m_stroke_seq(0)
,m_stroke_dasharray(NULL)
,m_dasharray_seq(0)
,m_vector_effect(SVGVECTOREFFECT_NONE)
#ifdef SVG_SUPPORT_PAINTSERVERS
,m_fill_pserver(NULL)
,m_stroke_pserver(NULL)
#endif // SVG_SUPPORT_PAINTSERVERS
,m_has_decoration_paint(FALSE)
,m_old_underline_color(USE_DEFAULT_COLOR)
,m_old_overline_color(USE_DEFAULT_COLOR)
,m_old_linethrough_color(USE_DEFAULT_COLOR)
,m_shape_rendering(SVGSHAPERENDERING_AUTO)
,m_fill_opacity(255)
,m_stroke_opacity(255)
,m_prev(NULL)
{
m_current.element = NULL;
m_last_intersected.element = NULL;
}
SVGCanvasState::~SVGCanvasState()
{
#ifdef SVG_SUPPORT_PAINTSERVERS
SVGPaintServer::DecRef(m_fill_pserver);
SVGPaintServer::DecRef(m_stroke_pserver);
#endif // SVG_SUPPORT_PAINTSERVERS
SVGResolvedDashArray::DecRef(m_stroke_dasharray);
}
BOOL SVGCanvasState::DecorationsChanged(const HTMLayoutProperties& props)
{
if (props.underline_color != m_old_underline_color ||
props.overline_color != m_old_overline_color ||
props.linethrough_color != m_old_linethrough_color)
{
m_old_underline_color = props.underline_color;
m_old_overline_color = props.overline_color;
m_old_linethrough_color = props.linethrough_color;
return TRUE;
}
return props.svg->info.has_textdecoration ? TRUE : FALSE;
}
SVGCanvasState* SVGCanvasState::GetDecorationState()
{
SVGCanvasState* s = this;
while (s && s->m_has_decoration_paint == FALSE)
s = s->m_prev;
return s;
}
OP_STATUS SVGCanvasState::SetDecorationPaint()
{
SVGCanvasState* decostate = GetDecorationState();
if (decostate == this)
return OpStatus::OK;
if (decostate != NULL)
{
SetFillColor(decostate->m_fillcolor);
switch (decostate->m_use_fill)
{
#ifdef SVG_SUPPORT_PAINTSERVERS
case USE_PSERVER:
SVGPaintServer::IncRef(decostate->m_fill_pserver);
SetFillPaintServer(decostate->m_fill_pserver);
break;
#endif // SVG_SUPPORT_PAINTSERVERS
}
EnableFill(decostate->m_use_fill);
SetStrokeColor(decostate->m_strokecolor);
switch (decostate->m_use_stroke)
{
#ifdef SVG_SUPPORT_PAINTSERVERS
case USE_PSERVER:
SVGPaintServer::IncRef(decostate->m_stroke_pserver);
SetStrokePaintServer(decostate->m_stroke_pserver);
break;
#endif // SVG_SUPPORT_PAINTSERVERS
}
EnableStroke(decostate->m_use_stroke);
}
else
{
// Use default paint
EnableFill(SVGCanvasState::USE_COLOR);
SetFillColorRGB(0,0,0);
SetFillOpacity(0xff);
EnableStroke(SVGCanvasState::USE_NONE);
}
return OpStatus::OK;
}
void SVGCanvasState::GetDecorationPaints(SVGPaintDesc* paints)
{
SVGCanvasState* decostate = GetDecorationState();
if (decostate)
{
paints[0].color = decostate->GetActualFillColor();
paints[0].opacity = decostate->GetFillOpacity();
#ifdef SVG_SUPPORT_PAINTSERVERS
SVGPaintServer::AssignRef(paints[0].pserver, decostate->GetFillPaintServer());
#endif // SVG_SUPPORT_PAINTSERVERS
paints[1].color = decostate->GetActualStrokeColor();
paints[1].opacity = decostate->GetStrokeOpacity();
#ifdef SVG_SUPPORT_PAINTSERVERS
SVGPaintServer::AssignRef(paints[1].pserver, decostate->GetStrokePaintServer());
#endif // SVG_SUPPORT_PAINTSERVERS
}
else
{
// Use default paint
paints[0].color = 0xff000000; // Black
paints[0].opacity = 255;
#ifdef SVG_SUPPORT_PAINTSERVERS
SVGPaintServer::AssignRef(paints[0].pserver, NULL);
#endif // SVG_SUPPORT_PAINTSERVERS
paints[1].color = 0xff000000; // Black
paints[1].opacity = 0;
#ifdef SVG_SUPPORT_PAINTSERVERS
SVGPaintServer::AssignRef(paints[1].pserver, NULL);
#endif // SVG_SUPPORT_PAINTSERVERS
}
}
// With ref-counted paint servers this is probably not needed any more
void SVGCanvasState::ResetDecorationPaint()
{
SVGCanvasState* decostate = GetDecorationState();
if (decostate == NULL || decostate == this)
return;
// To avoid deleting paints that were used previously
#ifdef SVG_SUPPORT_PAINTSERVERS
if (m_use_fill == USE_PSERVER)
{
SVGPaintServer::DecRef(m_fill_pserver);
m_fill_pserver = NULL;
}
if (m_use_stroke == USE_PSERVER)
{
SVGPaintServer::DecRef(m_stroke_pserver);
m_stroke_pserver = NULL;
}
#endif // SVG_SUPPORT_PAINTSERVERS
}
OP_STATUS SVGCanvasState::SetDashes(SVGNumber* dasharray, unsigned arraycount)
{
SVGResolvedDashArray* new_dasharray = NULL;
if (dasharray)
{
new_dasharray = OP_NEW(SVGResolvedDashArray, ());
if (!new_dasharray)
{
OP_DELETEA(dasharray);
return OpStatus::ERR_NO_MEMORY;
}
new_dasharray->dashes = dasharray;
new_dasharray->dash_size = arraycount;
}
SVGResolvedDashArray::DecRef(m_stroke_dasharray);
m_stroke_dasharray = new_dasharray;
return OpStatus::OK;
}
#ifdef SVG_SUPPORT_PAINTSERVERS
void SVGCanvasState::SetFillPaintServer(SVGPaintServer* pserver)
{
SVGPaintServer::DecRef(m_fill_pserver);
m_fill_pserver = pserver;
}
void SVGCanvasState::SetStrokePaintServer(SVGPaintServer* pserver)
{
SVGPaintServer::DecRef(m_stroke_pserver);
m_stroke_pserver = pserver;
}
#endif // SVG_SUPPORT_PAINTSERVERS
BOOL SVGCanvasState::AllowPointerEvents(int type)
{
if (m_pointer_events == SVGPOINTEREVENTS_NONE)
return FALSE;
if (m_pointer_events == SVGPOINTEREVENTS_ALL)
return TRUE;
if (m_pointer_events == SVGPOINTEREVENTS_VISIBLE &&
m_visibility == SVGVISIBILITY_VISIBLE)
return TRUE;
if (type & SVGALLOWPOINTEREVENTS_FILL)
{
if (m_pointer_events == SVGPOINTEREVENTS_FILL)
return TRUE;
if (m_pointer_events == SVGPOINTEREVENTS_VISIBLEFILL &&
m_visibility == SVGVISIBILITY_VISIBLE)
return TRUE;
if (m_pointer_events == SVGPOINTEREVENTS_PAINTED &&
UseFill())
return TRUE;
if (m_pointer_events == SVGPOINTEREVENTS_VISIBLEPAINTED &&
m_visibility == SVGVISIBILITY_VISIBLE &&
UseFill())
return TRUE;
if (m_pointer_events == SVGPOINTEREVENTS_BOUNDINGBOX)
return TRUE;
}
if (type & SVGALLOWPOINTEREVENTS_STROKE)
{
if (m_pointer_events == SVGPOINTEREVENTS_STROKE)
return TRUE;
if (m_pointer_events == SVGPOINTEREVENTS_VISIBLESTROKE &&
m_visibility == SVGVISIBILITY_VISIBLE)
return TRUE;
if (m_pointer_events == SVGPOINTEREVENTS_PAINTED &&
UseStroke())
return TRUE;
if (m_pointer_events == SVGPOINTEREVENTS_VISIBLEPAINTED &&
m_visibility == SVGVISIBILITY_VISIBLE &&
UseStroke())
return TRUE;
}
/* No match */
return FALSE;
}
BOOL
SVGCanvasState::AllowDraw(BOOL ignore_pointer_events)
{
return GetVisibility() == SVGVISIBILITY_VISIBLE || (!ignore_pointer_events && AllowPointerEvents());
}
OP_STATUS SVGCanvasState::SaveState()
{
SVGCanvasState* saved_state = OP_NEW(SVGCanvasState, ());
if (saved_state == NULL)
return OpStatus::ERR_NO_MEMORY;
// Save values
saved_state->m_transform.Copy(m_transform);
saved_state->m_use_fill = m_use_fill;
saved_state->m_fill_seq = m_fill_seq;
saved_state->m_use_stroke = m_use_stroke;
saved_state->m_stroke_seq = m_stroke_seq;
saved_state->m_fillcolor = m_fillcolor;
#ifdef SVG_SUPPORT_PAINTSERVERS
SVGPaintServer::IncRef(m_fill_pserver);
saved_state->m_fill_pserver = m_fill_pserver;
SVGPaintServer::IncRef(m_stroke_pserver);
saved_state->m_stroke_pserver = m_stroke_pserver;
#endif // SVG_SUPPORT_PAINTSERVERS
saved_state->m_strokecolor = m_strokecolor;
saved_state->m_stroke_linewidth = m_stroke_linewidth;
saved_state->m_stroke_flatness = m_stroke_flatness;
saved_state->m_stroke_miter_limit = m_stroke_miter_limit;
saved_state->m_stroke_captype = m_stroke_captype;
saved_state->m_stroke_jointype = m_stroke_jointype;
saved_state->m_stroke_dashoffset = m_stroke_dashoffset;
SVGResolvedDashArray::IncRef(m_stroke_dasharray);
saved_state->m_stroke_dasharray = m_stroke_dasharray;
saved_state->m_dasharray_seq = m_dasharray_seq;
saved_state->m_vector_effect = m_vector_effect;
saved_state->m_fillrule = m_fillrule;
saved_state->m_visibility = m_visibility;
saved_state->m_pointer_events = m_pointer_events;
saved_state->m_logfont = m_logfont;
saved_state->m_has_decoration_paint = m_has_decoration_paint;
m_has_decoration_paint = FALSE;
saved_state->m_old_underline_color = m_old_underline_color;
saved_state->m_old_overline_color = m_old_overline_color;
saved_state->m_old_linethrough_color = m_old_linethrough_color;
saved_state->m_shape_rendering = m_shape_rendering;
saved_state->m_fill_opacity = m_fill_opacity;
saved_state->m_stroke_opacity = m_stroke_opacity;
saved_state->m_prev = m_prev;
m_prev = saved_state;
return OpStatus::OK;
}
OP_STATUS SVGCanvasState::Copy(SVGCanvasState* copy)
{
m_transform.Copy(copy->m_transform);
m_use_fill = copy->m_use_fill;
m_use_stroke = copy->m_use_stroke;
m_fillcolor = copy->m_fillcolor;
#ifdef SVG_SUPPORT_PAINTSERVERS
SVGPaintServer::AssignRef(m_fill_pserver, copy->m_fill_pserver);
SVGPaintServer::AssignRef(m_stroke_pserver, copy->m_stroke_pserver);
#endif // SVG_SUPPORT_PAINTSERVERS
m_strokecolor = copy->m_strokecolor;
m_stroke_linewidth = copy->m_stroke_linewidth;
m_stroke_flatness = copy->m_stroke_flatness;
m_stroke_miter_limit = copy->m_stroke_miter_limit;
m_stroke_captype = copy->m_stroke_captype;
m_stroke_jointype = copy->m_stroke_jointype;
m_stroke_dashoffset = copy->m_stroke_dashoffset;
SVGResolvedDashArray::IncRef(copy->m_stroke_dasharray);
m_stroke_dasharray = copy->m_stroke_dasharray;
m_vector_effect = copy->m_vector_effect;
m_fillrule = copy->m_fillrule;
m_visibility = copy->m_visibility;
m_pointer_events = copy->m_pointer_events;
m_logfont = copy->m_logfont;
m_shape_rendering = copy->m_shape_rendering;
m_fill_opacity = copy->m_fill_opacity;
m_stroke_opacity = copy->m_stroke_opacity;
return OpStatus::OK;
}
void SVGCanvasState::RestoreState()
{
OP_ASSERT(m_prev); // We had an OOM condition in SaveState above or have unbalanced SaveState/RestoreState !
if (m_prev == NULL)
return;
// Pick out the last state on the stack, free it and update current state.
SVGCanvasState* old_state_stack = m_prev;
// Restore values
m_transform.Copy(m_prev->m_transform);
m_use_fill = m_prev->m_use_fill;
m_fill_seq = m_prev->m_fill_seq;
m_use_stroke = m_prev->m_use_stroke;
m_stroke_seq = m_prev->m_stroke_seq;
m_fillcolor = m_prev->m_fillcolor;
#ifdef SVG_SUPPORT_PAINTSERVERS
SVGPaintServer::AssignRef(m_fill_pserver, m_prev->m_fill_pserver);
SVGPaintServer::AssignRef(m_stroke_pserver, m_prev->m_stroke_pserver);
#endif // SVG_SUPPORT_PAINTSERVERS
m_strokecolor = m_prev->m_strokecolor;
m_stroke_linewidth = m_prev->m_stroke_linewidth;
m_stroke_flatness = m_prev->m_stroke_flatness;
m_stroke_miter_limit = m_prev->m_stroke_miter_limit;
m_stroke_captype = m_prev->m_stroke_captype;
m_stroke_jointype = m_prev->m_stroke_jointype;
m_stroke_dashoffset = m_prev->m_stroke_dashoffset;
SVGResolvedDashArray::AssignRef(m_stroke_dasharray, m_prev->m_stroke_dasharray);
m_stroke_dasharray = m_prev->m_stroke_dasharray;
m_dasharray_seq = m_prev->m_dasharray_seq;
m_vector_effect = m_prev->m_vector_effect;
m_fillrule = m_prev->m_fillrule;
m_visibility = m_prev->m_visibility;
m_pointer_events = m_prev->m_pointer_events;
m_logfont = m_prev->m_logfont;
m_has_decoration_paint = m_prev->m_has_decoration_paint;
m_old_underline_color = m_prev->m_old_underline_color;
m_old_overline_color = m_prev->m_old_overline_color;
m_old_linethrough_color = m_prev->m_old_linethrough_color;
m_shape_rendering = m_prev->m_shape_rendering;
m_fill_opacity = m_prev->m_fill_opacity;
m_stroke_opacity = m_prev->m_stroke_opacity;
m_prev = m_prev->m_prev;
OP_DELETE(old_state_stack);
}
unsigned int SVGCanvasState::GetShapeRenderingVegaQuality()
{
switch(m_shape_rendering)
{
case SVGSHAPERENDERING_CRISPEDGES:
case SVGSHAPERENDERING_OPTIMIZESPEED:
return 0;
case SVGSHAPERENDERING_AUTO:
default:
return VEGA_DEFAULT_QUALITY;
}
}
void SVGCanvasState::SetDefaults(int rendering_quality)
{
SetFillRule(SVGFILL_NON_ZERO);
UINT32 opaqueBlack = 0xFF000000;
SetFillColor(opaqueBlack);
SetFillOpacity(0xFF);
SetFillSeq(0);
SetLineCap(SVGCAP_BUTT);
SetLineJoin(SVGJOIN_MITER);
SetLineWidth(SVGNumber(1));
SetMiterLimit(SVGNumber(4));
SetFlatness(SVGNumber(rendering_quality) / 100);
UINT32 none = 0x00000000;
SetStrokeColor(none);
SetStrokeOpacity(0xFF);
SetStrokeSeq(0);
SetVectorEffect(SVGVECTOREFFECT_NONE);
SetDashArraySeq(0);
SetDashes(NULL, 0);
m_old_underline_color = m_old_overline_color = m_old_linethrough_color = USE_DEFAULT_COLOR;
m_has_decoration_paint = FALSE;
#ifdef SVG_SUPPORT_PAINTSERVERS
SetFillPaintServer(NULL);
SetStrokePaintServer(NULL);
#endif // SVG_SUPPORT_PAINTSERVERS
EnableFill(SVGCanvasState::USE_COLOR);
EnableStroke(SVGCanvasState::USE_NONE);
SetVisibility(SVGVISIBILITY_VISIBLE);
SetPointerEvents(SVGPOINTEREVENTS_VISIBLEPAINTED);
SetShapeRendering(SVGSHAPERENDERING_AUTO);
}
#endif // SVG_SUPPORT
|
#pragma once
#include <QObject>
class CIOCPNet;
class CMessageEventMediator;
class CSoftUpgradeWidget;
class CNetClass : public QObject
{
Q_OBJECT
public:
CNetClass(QObject *parent = 0);
virtual ~CNetClass(void);
static CNetClass* Instance();
CIOCPNet *m_pNetClt;
CMessageEventMediator *m_pMessageEventMediator;
CSoftUpgradeWidget *m_pSoftUpgradeWidget;
private:
static CNetClass* m_Instance;
};
#define NetClass CNetClass::Instance()
|
#include <algorithm>
#include <time.h>
#include "stack_plate.h"
/*
* question:
* Imagine a (literal) stack of plates. if the stack get too high, it might topple,therefore ,in real life, we would likely start a new stack when the previous stack exceeds some threshold, Implement a data structure, SetOfStack the mimics this. SetOfStacks should be composed of several stacks, and should create a new stack once the previous one exceed capacity. SetOfStacks.push and SetOfStack.pop should behave identically to a single stack.
* what is more, you should implement a function popAt(int index). which performs a pop operation on a specific substack.
*
*/
using namespace std;
const uint MAX = 20;
//int main(){
// srand(uint(time(0)));
//
// DATA dataArray[MAX];
// for(uint i = 0; i < MAX; ++i){
// dataArray[i] = i;
// }
// //random_shuffle(dataArray, dataArray + MAX);
// StackPlate myStack(5);
// for(uint i = 0; i < MAX; ++i){
// myStack.PushData(dataArray[i]);
// printf("current stack data are:\n");
// myStack.PrintData();
// /*
// if(i % 3 == 0 && i != 0){
// DATA data = myStack.PopData();
// printf("pop data %d\n",data);
// }*/
// if(i % 2 == 0 && i != 0){
// DATA data;
// if(myStack.PopAtIndex(data, 0)){
// printf("\npop at %d ,data is %d\n", 0, data);
// }
// }
// }
//
// return 0;
//}
|
#include<iostream.h>
#include<conio.h>
#include<limits.h>
int matrixmul(int a[],int n)
{ int k,l,m[10][10],s[10][10],q,i,j;
for(i=1;i<n;i++)
{
m[i][i]=0;
}
for(l=2;l<n;l++)
{
for(i=1;i<(n-l+1);i++)
{
j=i+l-1;
m[i][j]=INT_MAX;
for(k=i;k<=j-1;k++)
{
q=m[i][k]+m[k+1][j]+(a[i-1]*a[k]*a[j]);
if(q<m[i][j])
{
m[i][j]=q;
s[i][j]=k;
}
}
}
}
for(i=1;i<n;i++)
{
for(j=1;j<n;j++)
{
cout<<m[i][j]<<"\t";
}
cout<<endl;
}
return m[1][n-1];
}
void main()
{
clrscr();
int a[10],n,i;
cout<<"enter no order of matrix :";
cin>>n;
cout<<"enter in array";
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Maximum multiplication ="<<matrixmul(a,n);
getch();
}
|
#include"mOpenCL.h"
int main() {
cl_device_type devtype = CL_DEVICE_TYPE_GPU;
//cl_device_type devtype = CL_DEVICE_TYPE_GPU || CL_DEVICE_TYPE_ACCELERATOR;
mOpenCL openCL_obj(devtype);
cl_char slp;
std::cout << "Enter a key to end the program." << std::endl;
std::cin >> slp;
return 0;
}
|
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
using namespace std;
int main() {
int rand1 = rand() % 10;
int rand2 = rand() % 10;
int id = shmget(69, 0x1000, IPC_CREAT | 0666);
if (id == -1) {
cout << "Page creation failed: " << id << endl;
} else {
int *p = (int *)shmat(id, 0, 0);
if (p != (int *)-1){
p[0] = rand1;
p[1] = rand2;
cout << p[0] << endl;
cout << p[1] << endl;
while(p[2]==0){
sleep(2);
}
cout << p[2] << endl;
shmdt(p);
} else cout << "Pointer creation failed" << endl;
}
return 0;
}
|
#ifndef WALKENEMY_H
#define WALKENEMY_H
#include "Enemy.h"
#include "../FrameTimer.h"
namespace gnGame {
/// <summary>
/// 歩く敵
/// 一直線に歩いていく
/// </summary>
class WalkEnemy : public Enemy{
public:
WalkEnemy(const Vector2 _pos, const ActorParameter _parameter);
virtual ~WalkEnemy() = default;
virtual void onStart() override;
virtual void onUpdate() override;
void action();
private:
FrameTimer frameTimer;
AnimSprite waitAnimSprite; // 待機用の画像
AnimSprite actionAnimSprite; // アニメーション用の画像
};
}
#endif // !WALKENEMY_H
|
// This program is free software: you can use, modify and/or redistribute it
// under the terms of the simplified BSD License. You should have received a
// copy of this license athis program. If not, see
// <http://www.opensource.org/licenses/bsd-license.html>.
//
// Copyright (C) 2017, Onofre Martorell <onofremartorelln@gmail.com>
// All rights reserved.
#ifndef TVL2_MODEL_OCC
#define TVL2_MODEL_OCC
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include "energy_structures.h"
#include "aux_energy_model.h"
#include "parameters.h"
extern "C" {
#include "bicubic_interpolation.h"
}
#include "utils.h"
#include <iostream>
////INITIALIZATION OF EACH METHOD
void intialize_stuff_tvl2coupled_occ(
SpecificOFStuff& ofStuff,
const OpticalFlowData& ofCore) {
const int w = ofCore.params.w;
const int h = ofCore.params.h;
//Occlusion variable
ofStuff.tvl2_occ.chix = new float[w*h];
ofStuff.tvl2_occ.chiy = new float[w*h];
ofStuff.tvl2_occ.diff_u_N = new float[w*h];
//Weigth
ofStuff.tvl2_occ.g = new float[w*h];
//Dual variables
ofStuff.tvl2_occ.xi11 = new float[w*h];
ofStuff.tvl2_occ.xi12 = new float[w*h];
ofStuff.tvl2_occ.xi21 = new float[w*h];
ofStuff.tvl2_occ.xi22 = new float[w*h];
ofStuff.tvl2_occ.u1x = new float[w*h];
ofStuff.tvl2_occ.u1y = new float[w*h];
ofStuff.tvl2_occ.u2x = new float[w*h];
ofStuff.tvl2_occ.u2y = new float[w*h];
ofStuff.tvl2_occ.v1 = new float[w*h];
ofStuff.tvl2_occ.v2 = new float[w*h];
ofStuff.tvl2_occ.rho_c1 = new float[w*h];
ofStuff.tvl2_occ.rho_c_1 = new float[w*h];
ofStuff.tvl2_occ.grad_1 = new float[w*h];
ofStuff.tvl2_occ.grad__1 = new float[w*h];
if (ofCore.params.step_algorithm == GLOBAL_STEP){
ofStuff.tvl2_occ.I0x = new float[w*h];
ofStuff.tvl2_occ.I0y = new float[w*h];
}else{
ofStuff.tvl2_occ.I0x = nullptr;
ofStuff.tvl2_occ.I0y = nullptr;
}
ofStuff.tvl2_occ.I1x = new float[w*h];
ofStuff.tvl2_occ.I1y = new float[w*h];
ofStuff.tvl2_occ.I1w = new float[w*h];
ofStuff.tvl2_occ.I1wx = new float[w*h];
ofStuff.tvl2_occ.I1wy = new float[w*h];
ofStuff.tvl2_occ.I_1x = new float[w*h];
ofStuff.tvl2_occ.I_1y = new float[w*h];
ofStuff.tvl2_occ.I_1w = new float[w*h];
ofStuff.tvl2_occ.I_1wx = new float[w*h];
ofStuff.tvl2_occ.I_1wy = new float[w*h];
ofStuff.tvl2_occ.vi_div1 = new float[w*h];
ofStuff.tvl2_occ.grad_x1 = new float[w*h];
ofStuff.tvl2_occ.grad_y1 = new float[w*h];
ofStuff.tvl2_occ.vi_div2 = new float[w*h];
ofStuff.tvl2_occ.grad_x2 = new float[w*h];
ofStuff.tvl2_occ.grad_y2 = new float[w*h];
ofStuff.tvl2_occ.g_xi11 = new float[w*h];
ofStuff.tvl2_occ.g_xi12 = new float[w*h];
ofStuff.tvl2_occ.g_xi21 = new float[w*h];
ofStuff.tvl2_occ.g_xi22 = new float[w*h];
ofStuff.tvl2_occ.div_g_xi1 = new float[w*h];
ofStuff.tvl2_occ.div_g_xi2 = new float[w*h];
ofStuff.tvl2_occ.eta1 = new float[w*h];
ofStuff.tvl2_occ.eta2 = new float[w*h];
ofStuff.tvl2_occ.F = new float[w*h];
ofStuff.tvl2_occ.G = new float[w*h];
ofStuff.tvl2_occ.div_u = new float[w*h];
ofStuff.tvl2_occ.g_eta1 = new float[w*h];
ofStuff.tvl2_occ.g_eta2 = new float[w*h];
ofStuff.tvl2_occ.div_g_eta = new float[w*h];
}
void free_stuff_tvl2coupled_occ(SpecificOFStuff *ofStuff){
delete [] ofStuff->tvl2_occ.chix;
delete [] ofStuff->tvl2_occ.chiy;
delete [] ofStuff->tvl2_occ.g;
delete [] ofStuff->tvl2_occ.diff_u_N;
delete [] ofStuff->tvl2_occ.xi11;
delete [] ofStuff->tvl2_occ.xi12;
delete [] ofStuff->tvl2_occ.xi21;
delete [] ofStuff->tvl2_occ.xi22;
delete [] ofStuff->tvl2_occ.v1;
delete [] ofStuff->tvl2_occ.v2;
delete [] ofStuff->tvl2_occ.rho_c1;
delete [] ofStuff->tvl2_occ.rho_c_1;
delete [] ofStuff->tvl2_occ.grad_1;
delete [] ofStuff->tvl2_occ.grad__1;
delete [] ofStuff->tvl2_occ.vi_div1;
delete [] ofStuff->tvl2_occ.grad_x1;
delete [] ofStuff->tvl2_occ.grad_y1;
delete [] ofStuff->tvl2_occ.vi_div2;
delete [] ofStuff->tvl2_occ.grad_x2;
delete [] ofStuff->tvl2_occ.grad_y2;
delete [] ofStuff->tvl2_occ.g_xi11;
delete [] ofStuff->tvl2_occ.g_xi12;
delete [] ofStuff->tvl2_occ.g_xi21;
delete [] ofStuff->tvl2_occ.g_xi22;
delete [] ofStuff->tvl2_occ.div_g_xi1;
delete [] ofStuff->tvl2_occ.div_g_xi2;
delete [] ofStuff->tvl2_occ.eta1;
delete [] ofStuff->tvl2_occ.eta2;
delete [] ofStuff->tvl2_occ.F;
delete [] ofStuff->tvl2_occ.G;
delete [] ofStuff->tvl2_occ.div_u;
delete [] ofStuff->tvl2_occ.g_eta1;
delete [] ofStuff->tvl2_occ.g_eta2;
delete [] ofStuff->tvl2_occ.div_g_eta;
delete [] ofStuff->tvl2_occ.I1x;
delete [] ofStuff->tvl2_occ.I1y;
delete [] ofStuff->tvl2_occ.I1w;
delete [] ofStuff->tvl2_occ.I1wx;
delete [] ofStuff->tvl2_occ.I1wy;
if (ofStuff->tvl2_occ.I0x){
delete [] ofStuff->tvl2_occ.I0x;
delete [] ofStuff->tvl2_occ.I0y;
}
delete [] ofStuff->tvl2_occ.I_1x;
delete [] ofStuff->tvl2_occ.I_1y;
delete [] ofStuff->tvl2_occ.I_1w;
delete [] ofStuff->tvl2_occ.I_1wx;
delete [] ofStuff->tvl2_occ.I_1wy;
}
//////////////////////////////////////////////////////////////
////TV-l2 COUPLED OPTICAL FLOW PROBLEM WITH OCCLUSIONS////////
/////////////////////////////////////////////////////////////
float eval_tvl2coupled_occ(
const float *I0, // source image
const float *I1, // forward image
const float *I_1, // backward image
OpticalFlowData *ofD,
Tvl2CoupledOFStuff_occ *tvl2_occ,
const PatchIndexes index,
Parameters params
){
const float *u1 = ofD->u1;
const float *u2 = ofD->u2;
float *u1_ba = ofD->u1_ba;
float *u2_ba = ofD->u2_ba;
//Occlusion variables
const float *chi = ofD->chi;
float *chix = tvl2_occ->chix;
float *chiy = tvl2_occ->chiy;
//Columns and Rows
const int nx = ofD->params.w;
const int ny = ofD->params.h;
//Optical flow derivatives
const float *v1 = tvl2_occ->v1;
const float *v2 = tvl2_occ->v2;
float *u1x = tvl2_occ->u1x;
float *u1y = tvl2_occ->u1y;
float *u2x = tvl2_occ->u2x;
float *u2y = tvl2_occ->u2y;
//Weigth
const float *g = tvl2_occ->g;
float *div_u = tvl2_occ->div_u;
float *I_1w = tvl2_occ->I_1w;
float *I1w = tvl2_occ->I1w;
//Derivatives and warping of I2
const float *I1x = tvl2_occ->I1x;
const float *I1y = tvl2_occ->I1y;
float *I1wx = tvl2_occ->I1wx;
float *I1wy = tvl2_occ->I1wy;
//Derivatives and warping of I0
const float *I_1x = tvl2_occ->I_1x;
const float *I_1y = tvl2_occ->I_1y;
float *I_1wx = tvl2_occ->I_1wx;
float *I_1wy = tvl2_occ->I_1wy;
float ener = 0.0;
forward_gradient_patch(u1, u1x, u1y, index.ii, index.ij, index.ei, index.ej, nx);
forward_gradient_patch(u2, u2x, u2y, index.ii, index.ij, index.ei, index.ej, nx);
forward_gradient_patch(chi, chix, chiy, index.ii, index.ij, index.ei, index.ej, nx);
divergence_patch(u1, u2, div_u, index.ii, index.ij, index.ei, index.ej, nx);
//#pragma omp simd collapse(2)
//#pragma omp for schedule(dynamic, 1) collapse(2)
for (int l = index.ij; l < index.ej; l++){
for (int k = index.ii; k < index.ei; k++){
const int i = l*nx + k;
u1_ba[i] = -u1[i];
u2_ba[i] = -u2[i];
}
}
// Compute the warping of I1 and its derivatives I1(x + u1o), I1x (x + u1o) and I1y (x + u2o)
bicubic_interpolation_warp_patch(I1, u1, u2, I1w, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
bicubic_interpolation_warp_patch(I1x, u1, u2, I1wx, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
bicubic_interpolation_warp_patch(I1y, u1, u2, I1wy, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
// Compute the warping of I0 and its derivatives I0(x - u1o), I0x (x - u1o) and I0y (x - u2o)
bicubic_interpolation_warp_patch(I_1, u1_ba, u2_ba, I_1w, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
bicubic_interpolation_warp_patch(I_1x, u1_ba, u2_ba, I_1wx, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
bicubic_interpolation_warp_patch(I_1y, u1_ba, u2_ba, I_1wy, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
//Energy for all the patch. Maybe it would be useful only the 8 pixels around the seed.
int m = 0;
//#pragma omp simd collapse(2) reduction(+:ener)
//#pragma omp for schedule(dynamic, 1) collapse(2)
for (int l = index.ij; l < index.ej; l++){
for (int k = index.ii; k < index.ei; k++){
const int i = l*nx + k;
const float diff_uv_term = (1/(2*params.theta))*
((u1[i] - v1[i])*(u1[i]- v1[i]) + (u2[i] - v2[i])*(u2[i] - v2[i]));
const float norm_v_term = (params.alpha/2)*chi[i]*(v1[i]*v1[i] + v2[i]*v2[i]);
const float div_u_term = params.beta*chi[i]*div_u[i];
const float rho_1 = fabs(I1w[i] - I1wx[i] * u1[i] - I1wy[i] * u2[i] - I0[i]
+ I1wx[i] * v1[i] + I1wy[i] * v2[i]);
const float rho__1 = fabs(I_1w[i] - I_1wx[i] * u1[i] - I_1wy[i] * u2[i] - I0[i]
+ I_1wx[i] * v1[i] + I_1wy[i] * v2[i]);
const float data_term = params.lambda * ((1 - chi[i])*rho_1 + chi[i]*rho__1);
const float grad_u1 = sqrt(u1x[i] * u1x[i] + u1y[i] * u1y[i]);
const float grad_u2 = sqrt(u2x[i] * u2x[i] + u2y[i] * u2y[i]);
const float grad_chi = sqrt(chix[i] * chix[i] + chiy[i] * chiy[i]);
const float smooth_term = g[i]*(grad_u1 + grad_u2 + params.mu*grad_chi);
if (!std::isfinite(data_term)){
std::printf("Datos corruptos\n");
}
if (!std::isfinite(smooth_term)){
std::printf("Regularizacion corrupta\n");
}
ener += data_term + smooth_term + div_u_term + norm_v_term + diff_uv_term;
m++;
}
}
ener /= (m*1.0);
return ener;
}
/////////////////////////////////////
//////////// Minimization ///////////
/////////////////////////////////////
//Dual variables for u
static void tvl2coupled_get_xi_patch(
float *xi11, //Dual variable
float *xi12, //Dual variable
float *xi21, //Dual variable
float *xi22, //Dual variable
const float *g,
const float *v1,
const float *v2,
float *chix,
float *chiy,
float *vi_div1,
float *grad_x1,
float *grad_y1,
float *vi_div2,
float *grad_x2,
float *grad_y2,
float *g_xi11,
float *g_xi12,
float *g_xi21,
float *g_xi22,
float *div_g_xi1,
float *div_g_xi2,
const PatchIndexes index,
const Parameters params
){
float tau_theta = params.tau_u/params.theta;
int nx = params.w;
for (int k = 1; k < ITER_XI; k++){
//What goes inside gradient
for (int l = index.ij; l < index.ej; l++){
for (int j = index.ii; j < index.ei; j++){
const int i = l*nx + j;
g_xi11[i] = g[i]*xi11[i];
g_xi12[i] = g[i]*xi12[i];
g_xi21[i] = g[i]*xi21[i];
g_xi22[i] = g[i]*xi22[i];
}
}
divergence_patch(g_xi11, g_xi12, div_g_xi1, index.ii, index.ij, index.ei, index.ej, nx);
divergence_patch(g_xi21, g_xi22, div_g_xi2, index.ii, index.ij, index.ei, index.ej, nx);
for (int l = index.ij; l < index.ej; l++){
for (int j = index.ii; j < index.ei; j++){
const int i = l*nx + j;
vi_div1[i] = v1[i] + params.theta*div_g_xi1[i] + params.theta*params.beta*chix[i];
vi_div2[i] = v2[i] + params.theta*div_g_xi2[i] + params.theta*params.beta*chiy[i];
}
}
forward_gradient_patch(vi_div1, grad_x1, grad_y1, index.ii, index.ij, index.ei, index.ej, nx);
forward_gradient_patch(vi_div2, grad_x2, grad_y2, index.ii, index.ij, index.ei, index.ej, nx);
for (int l = index.ij; l < index.ej; l++){
for (int j = index.ii; j < index.ei; j++){
const int i = l*nx + j;
//Dual variables x11 and x12
const float vec11 = g[i]*grad_x1[i];
const float vec12 = g[i]*grad_y1[i];
const float norm_vec1 = sqrt(vec11 * vec11 + vec12 * vec12);
xi11[i] = (xi11[i] + tau_theta*vec11)/(1 + tau_theta*norm_vec1);
xi12[i] = (xi12[i] + tau_theta*vec12)/(1 + tau_theta*norm_vec1);
//Dual variables x21 and x22
const float vec21 = g[i]*grad_x2[i];
const float vec22 = g[i]*grad_y2[i];
const float norm_vec2 = sqrt(vec21 * vec21 + vec22 * vec22);
xi21[i] = (xi21[i] + tau_theta*vec21)/(1 + tau_theta*norm_vec2);
xi22[i] = (xi22[i] + tau_theta*vec22)/(1 + tau_theta*norm_vec2);
}
}
}
//Compute divergence for last time
for (int l = index.ij; l < index.ej; l++){
for (int j = index.ii; j < index.ei; j++){
const int i = l*nx + j;
g_xi11[i] = g[i]*xi11[i];
g_xi12[i] = g[i]*xi12[i];
g_xi21[i] = g[i]*xi21[i];
g_xi22[i] = g[i]*xi22[i];
}
}
divergence_patch(g_xi11, g_xi12, div_g_xi1, index.ii, index.ij, index.ei, index.ej, nx);
divergence_patch(g_xi21, g_xi22, div_g_xi2, index.ii, index.ij, index.ei, index.ej, nx);
}
//Minimization of occlusion variable
static void tvl2coupled_get_chi_patch(
float *chi,
float *chix,
float *chiy,
const float *F,
const float *G,
const float *g,
float *eta1,
float *eta2,
float *div_u,
float *g_eta1,
float *g_eta2,
float *div_g_eta,
const PatchIndexes index,
Parameters params){
int nx = params.w;
for (int k = 1; k < ITER_CHI; k++){
//Compute dual variable eta
//#pragma omp simd collapse(2)
for (int l = index.ij; l < index.ej; l++){
for (int j = index.ii; j < index.ei; j++){
const int i = l*nx + j;
//Compute new values of eta
const float eta_new1 = eta1[i] + params.mu*params.tau_eta * g[i] * chix[i];
const float eta_new2 = eta2[i] + params.mu*params.tau_eta * g[i] * chiy[i];
const float norm_eta = sqrt(eta_new1*eta_new1 + eta_new2*eta_new2);
//Put eta in the unit ball, [0, 1]
if (norm_eta <= 1){
eta1[i] = eta_new1;
eta2[i] = eta_new2;
}else{
eta1[i] = eta_new1/norm_eta;
eta2[i] = eta_new2/norm_eta;
}
//Compute values for the needed divergence
g_eta1[i] = g[i]*eta1[i];
g_eta2[i] = g[i]*eta2[i];
}
}
divergence_patch(g_eta1, g_eta2, div_g_eta, index.ii, index.ij, index.ei, index.ej, nx);
//Compute chi
//#pragma omp simd collapse(2)
//#pragma omp for schedule(dynamic, 1) collapse(2)
for (int l = index.ij; l < index.ej; l++){
for (int j = index.ii; j < index.ei; j++){
const int i = l*nx + j;
const float chi_new = chi[i] + params.tau_chi*(params.mu*div_g_eta[i] - params.beta*div_u[i] - F[i] - G[i]);
chi[i] = max(min(chi_new, 1), 0);
}
}
forward_gradient_patch(chi, chix, chiy, index.ii, index.ij, index.ei, index.ej, nx);
}
//Make thresholding in chi
//#pragma omp for schedule(dynamic,1) collapse(2)
for (int l = index.ij; l < index.ej; l++){
for (int j = index.ii; j < index.ei; j++){
const int i = l*nx + j;
chi[i] = (chi[i] > THRESHOLD_DELTA) ? 1 : 0;
//std::cout << chi[i] << '\n';
}
}
}
// Variational Optical flow method based on initial fixed values
// It minimizes the energy of \int_{B(x)} ||J(u)|| + |I_{1}(x+u)-I_{0}(x)|
// s.t u = u_0 for i.seeds
// J(u) = (u_x, u_y; v_x, v_y)
void guided_tvl2coupled_occ(
const float *I0, // source image
const float *I1, // forward image
const float *I_1, // backward image
OpticalFlowData *ofD,
Tvl2CoupledOFStuff_occ *tvl2_occ,
float *ener_N,
const PatchIndexes index
) {
float *u1 = ofD->u1;
float *u2 = ofD->u2;
float *u1_ba = ofD->u1_ba;
float *u2_ba = ofD->u2_ba;
//Columns and Rows
const int nx = ofD->params.w;
const int ny = ofD->params.h;
const int size = nx*ny;
float *diff_u_N = tvl2_occ->diff_u_N;
//Occlusion variables
float *chi = ofD->chi;
float *chix = tvl2_occ->chix;
float *chiy = tvl2_occ->chiy;
//Weigth
float *g = tvl2_occ->g;
//Dual variables
float *xi11 = tvl2_occ->xi11;
float *xi12 = tvl2_occ->xi12;
float *xi21 = tvl2_occ->xi21;
float *xi22 = tvl2_occ->xi22;
//Dual variables of chi
float *eta1 = tvl2_occ->eta1;
float *eta2 = tvl2_occ->eta2;
float *v1 = tvl2_occ->v1;
float *v2 = tvl2_occ->v2;
float *rho_c1 = tvl2_occ->rho_c1;
float *rho_c_1 = tvl2_occ->rho_c_1;
float *grad_1 = tvl2_occ->grad_1;
float *grad__1 = tvl2_occ->grad__1;
float *I0x = tvl2_occ->I0x;
float *I0y = tvl2_occ->I0y;
//Derivatives and warping of I2
float *I1x = tvl2_occ->I1x;
float *I1y = tvl2_occ->I1y;
float *I1w = tvl2_occ->I1w;
float *I1wx = tvl2_occ->I1wx;
float *I1wy = tvl2_occ->I1wy;
//Derivatives and warping of I0
float *I_1x = tvl2_occ->I_1x;
float *I_1y = tvl2_occ->I_1y;
float *I_1w = tvl2_occ->I_1w;
float *I_1wx = tvl2_occ->I_1wx;
float *I_1wy = tvl2_occ->I_1wy;
float *vi_div1 = tvl2_occ->vi_div1;
float *grad_x1 = tvl2_occ->grad_x1;
float *grad_y1 = tvl2_occ->grad_y1;
float *vi_div2 = tvl2_occ->vi_div2;
float *grad_x2 = tvl2_occ->grad_x2;
float *grad_y2 = tvl2_occ->grad_y2;
float *g_xi11 = tvl2_occ->g_xi11;
float *g_xi12 = tvl2_occ->g_xi12;
float *g_xi21 = tvl2_occ->g_xi21;
float *g_xi22 = tvl2_occ->g_xi22;
float *div_g_xi1 = tvl2_occ->div_g_xi1;
float *div_g_xi2 = tvl2_occ->div_g_xi2;
float *F = tvl2_occ->F;
float *G = tvl2_occ->G;
float *div_u = tvl2_occ->div_u;
float *g_eta1 = tvl2_occ->g_eta1;
float *g_eta2 = tvl2_occ->g_eta2;
float *div_g_eta = tvl2_occ->div_g_eta;
const float alpha = ofD->params.alpha;
const float theta = ofD->params.theta;
const float lambda = ofD->params.lambda;
const float l_t = lambda * theta;
//Initialization of dual variables and updating backward flow
for (int l = index.ij; l < index.ej; l++){
for (int k = index.ii; k < index.ei; k++){
const int i = l*nx + k;
xi11[i] = xi12[i] = xi21[i] = xi22[i] = 0.0;
u1_ba[i] = -u1[i];
u2_ba[i] = -u2[i];
}
}
//Initialize gradients from images and weight for global step
if (ofD->params.step_algorithm == GLOBAL_STEP){
//Compute derivatives of all images
centered_gradient(I1, I1x, I1y, nx, ny);
centered_gradient(I_1, I_1x, I_1y, nx, ny);
centered_gradient(I0, I0x, I0y, nx, ny);
//Initialize weight
init_weight(g, I0x, I0y, size);
}
for (int warpings = 0; warpings < ofD->params.warps; warpings++) {
// Compute the warping of I1 and its derivatives I1(x + u1o), I1x (x + u1o) and I1y (x + u2o)
bicubic_interpolation_warp_patch(I1, u1, u2, I1w, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
bicubic_interpolation_warp_patch(I1x, u1, u2, I1wx, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
bicubic_interpolation_warp_patch(I1y, u1, u2, I1wy, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
// Compute the warping of I0 and its derivatives I0(x - u1o), I0x (x - u1o) and I0y (x - u2o)
bicubic_interpolation_warp_patch(I_1, u1_ba, u2_ba, I_1w, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
bicubic_interpolation_warp_patch(I_1x, u1_ba, u2_ba, I_1wx, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
bicubic_interpolation_warp_patch(I_1y, u1_ba, u2_ba, I_1wy, index.ii, index.ij, index.ei, index.ej, nx, ny, false);
//Compute values that will not change during the whole wraping
//#pragma omp simd collapse(2)
for (int l = index.ij; l < index.ej; l++){
for (int k = index.ii; k < index.ei; k++){
const int i = l*nx + k;
const float I1_x2 = I1wx[i] * I1wx[i];
const float I1_y2 = I1wy[i] * I1wy[i];
const float I_1_x2 = I_1wx[i] * I_1wx[i];
const float I_1_y2 = I_1wy[i] * I_1wy[i];
// store the |Grad(I2)|^2
grad_1[i] = (I1_x2 + I1_y2);
grad__1[i] = (I_1_x2 + I_1_y2);
// Compute the constant part of the rho function
rho_c1[i] = I1w[i] - I1wx[i] * u1[i]
- I1wy[i] * u2[i] - I0[i];
rho_c_1[i] = I_1w[i] - I_1wx[i] * u1[i]
- I_1wy[i] * u2[i] - I0[i];
}
}
//Minimization of the functional
int n = 0;
float err_D = INFINITY;
while (err_D > ofD->params.tol_OF*ofD->params.tol_OF && n < ofD->params.iterations_of){
n++;
// estimate the values of the variable (v1, v2)
//#pragma omp simd collapse(2)
for (int l = index.ij; l < index.ej; l++){
for (int k = index.ii; k < index.ei; k++){
const int i = l*nx + k;
// rho function forward and backward
const float rho_1 = rho_c1[i]
+ I1wx[i] * u1[i] + I1wy[i] * u2[i];
const float rho__1 = rho_c_1[i]
+ I_1wx[i] * u1[i] + I_1wy[i] * u2[i];
//Stuff depending if pixel is occluded or not
int eps;
float alpha_i, mu, Lambda, grad, Iwx, Iwy, rho;
if (chi[i] == 0){
eps = 1;
alpha_i = 1;
mu = l_t;
Lambda = rho_1;
grad = grad_1[i];
Iwx = I1wx[i];
Iwy = I1wy[i];
rho = rho_1;
}else{
eps = -1;
alpha_i = 1/(1 + alpha*theta);
mu = l_t/(1 + alpha*theta);
Lambda = rho__1 +
alpha*theta/(1 + alpha*theta) * (u1[i]*I_1wx[i] + u2[i]*I_1wy[i]);
grad = grad__1[i];
Iwx = I_1wx[i];
Iwy = I_1wy[i];
rho = rho__1;
}
//Decide what to assign to v
if (Lambda > mu * grad){
v1[i] = alpha_i * u1[i] - mu * eps * Iwx;
v2[i] = alpha_i * u2[i] - mu * eps * Iwy;
}else{
if (Lambda < - mu * grad){
v1[i] = alpha_i * u1[i] + mu * eps * Iwx;
v2[i] = alpha_i * u2[i] + mu * eps * Iwy;
}else{
// if gradient is too small, we treat it as zero
if (grad < GRAD_IS_ZERO){
v1[i] = u1[i];
v2[i] = u2[i];
}else{
v1[i] = u1[i] - eps * rho * Iwx/grad;
v2[i] = u2[i] - eps * rho * Iwy/grad;
}
}
}
}
}
//Estimate the values of the variable (u1, u2)
//Compute derivatives of chi
forward_gradient_patch(chi, chix, chiy, index.ii, index.ij, index.ei, index.ej, nx);
//Compute dual variables
tvl2coupled_get_xi_patch(xi11, xi12, xi21, xi22, g, v1, v2,
chix, chiy, vi_div1, grad_x1, grad_y1, vi_div2, grad_x2, grad_y2,
g_xi11, g_xi12, g_xi21, g_xi22, div_g_xi1, div_g_xi2,
index, ofD->params);
//Compute several stuff
//#pragma omp simd collapse(2)
for (int l = index.ij; l < index.ej; l++){
for (int k = index.ii; k < index.ei; k++){
const int i = l*nx + k;
//Previous value for u
const float u1k = u1[i];
const float u2k = u2[i];
//New value for (u1, u2)
u1[i] = v1[i] + theta*div_g_xi1[i] + theta * ofD->params.beta * chix[i];
u2[i] = v2[i] + theta*div_g_xi2[i] + theta * ofD->params.beta * chiy[i];
//Difference between previous and new value of u
diff_u_N[i] = (u1[i] - u1k) * (u1[i] - u1k) +
(u2[i] - u2k) * (u2[i] - u2k);
const float rho__1 = rho_c_1[i]
+ I_1wx[i] * v1[i] + I_1wy[i] * v2[i];
const float rho_1 = rho_c1[i]
+ I1wx[i] * v1[i] + I1wy[i] * v2[i];
F[i] = lambda*(std::abs(rho__1) - std::abs(rho_1));
G[i] = alpha/2*(v1[i]*v1[i] + v2[i]*v2[i]);
}
}
//Compute chi
tvl2coupled_get_chi_patch(chi, chix, chiy, F, G,
g, eta1, eta2, div_u, g_eta1, g_eta2,
div_g_eta, index, ofD->params);
//Get the max val
float err_u = 0;
int i = 0;
for (int l = index.ij; l < index.ej; l++){
for (int k = index.ii; k < index.ei; k++){
i = l*nx + k;
if (err_u < diff_u_N[i]){
err_u = diff_u_N[i];
}
}
}
err_D = err_u;
}
if (ofD->params.step_algorithm == GLOBAL_STEP && ofD->params.verbose)
std::printf("Warping: %d, Iter: %d "
"Error: %f\n", warpings, n, err_D);
}
if (ofD->params.step_algorithm == LOCAL_STEP){
*ener_N = eval_tvl2coupled_occ(I0, I1, I_1, ofD, tvl2_occ, index, ofD->params);
}
}
#endif //TVL2-L1 functional
|
//
// Created by 钟奇龙 on 2019-05-14.
//
#include <iostream>
#include <vector>
using namespace std;
int minSortLenght(vector<int> arr){
if(arr.size() < 2) return 0;
int noMinIndex = -1;
int minValue = arr[arr.size()-1];
for(int i=arr.size()-2; i>=0; --i){
if(arr[i] < minValue){
minValue = arr[i];
}else{
noMinIndex = i;
}
}
if(noMinIndex == -1) return 0;
int noMaxIndex = -1;
int maxValue = arr[0];
for(int i=1; i<arr.size(); ++i){
if(arr[i] > maxValue){
maxValue = arr[i];
}else{
noMaxIndex = i;
}
}
return noMaxIndex - noMinIndex + 1;
}
int main(){
vector<int> arr = {1,5,4,3,2,6,7};
cout<<minSortLenght(arr)<<endl;
return 0;
}
|
/*
* @lc app=leetcode.cn id=322 lang=cpp
*
* [322] 零钱兑换
*/
// @lc code=start
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1, -1);
dp[0] = 0;
// for(int i=0;i<coins.size();++i)
// if(coins[i]<=amount)
// dp[coins[i]]=1;
for(int i=1;i<=amount;++i)
{
int m = INT_MAX;
for(int j=0;j<coins.size();++j)
{
if(i - coins[j] < 0)
{
continue;
}
if(dp[i - coins[j]] == -1)
continue;
m = min(dp[i - coins[j]], m);
}
if(m == INT_MAX){
dp[i] = -1;
continue;
}
dp[i] = m + 1;
}
return dp[amount];
}
};
// @lc code=end
|
#ifndef INPUTFIELD_H
#define INPUTFIELD_H
#include <SFML/Graphics.hpp>
#include "Dimensions.h"
//#include "Interface.h"
using namespace sf;
class InputField
{
public:
InputField(Vector2f position, String text);
~InputField() {}
bool isInside(Vector2f position);
void createOutline(Vector2f pos);
void draw(RenderWindow& window);
void onClick();
void clearCell();
//void setText(String inputText);
private:
int lineW = 1;
bool selected = false;
Text FunctionStr;
Font ariel;
Font times;
RectangleShape inputCell;
RectangleShape outline;
RectangleShape bullet;
};
#endif
|
#include "util.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string>
string formatString(const char *fmt, ...) {
// Do a bunch of formatting. This part shamelessly stolen from the printf
// man page.
/* Guess we need no more than 100 bytes. */
int n, size = 100;
char *p;
va_list ap;
if ((p = (char*)malloc (size)) == NULL)
return NULL;
while (1) {
/* Try to print in the allocated space. */
va_start(ap, fmt);
n = vsnprintf (p, size, fmt, ap);
va_end(ap);
/* If that worked, return the string. */
if (n > -1 && n < size)
break;
/* Else try again with more space. */
if (n > -1) /* glibc 2.1 */
size = n+1; /* precisely what is needed */
else /* glibc 2.0 */
size *= 2; /* twice the old size */
if ((p = (char*)realloc (p, size)) == NULL)
assert(false);
}
// Make it into a nice string and return it.
string r = string(p);
free(p);
return r;
}
void eatComments(ostream& out, istream &in) {
// Passes lines between two streams, stripping out all of the lines starting
// with a pound sign (#). A strstream might be a good choice for the out
// parameter.
const int bufferSize = 1024;
char buf[bufferSize];
while(in) {
in.getline(buf, bufferSize);
if(buf[0] != '#') {
out << buf << endl;
}
}
}
int argmin3(double a, double b, double c) {
if(a <= b && b <= c) return 1;
if(b <= a && b <= c) return 2;
return 3;
}
double *canonicalColor(int i) {
// Successive calls to this function return different "nice-looking" colors.
const int number = 7;
double static colors[7][3] = {
{ 1, 0, 0 }, // red
{ 0, 1, 0 }, // green
{ 0, 0, 1 }, // blue
{ 1, 0, 1 }, // magenta
{ 1, 1, 0 }, // yellow
{ 0, 1, 1 }, // cyan
{ 0, 0, 0 }, // black
};
/*
{ 0.5, 0, 0 }, // redish
{ 0, 0.5, 0 }, // greenish
{ 0, 0, 0.5 }, // blueish
{ 0.5, 0, 0.5 }, // magentaish
{ 0.5, 0.5, 0 }, // yellowish
{ 0, 0.5, 0.5 }, // cyanish
};
*/
return colors[i % number];
}
|
#pragma once
#include "misc\Vector2.h"
class Ref {
public:
const static int WIN_W[3];
const static int WIN_H[3];
static float pxRate;
const static int FLD_W;
const static int FLD_H;
const static int ENEMY_MAX;
const static int PLAYER_SHOT_MAX;
const static int ENEMY_SHOT_MAX;
const static int EFFECT_MAX;
const static int ITEM_MAX;
const static int ITEM_INDRAW_HEIGHT;
const static int SHOT_FUNC_MAX;
const static int DEATH_FUNC_MAX;
const static int ENEMY_SCRIPT_MAX;
const static float PI;
const static float PI2;
const static Vector2 VectorZero;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.