text
stringlengths 8
6.88M
|
|---|
#include <bidirectionallist.h>
#include <iostream>
#include <string>
#include <sstream>
#include <variant>
int main()
{
//1. Зацикливание
BidirectionalList list1;
list1.push_back(1);
std::cout << "list1: " << list1;
//2. Зацикливание
BidirectionalList list2;
list2.push_front(1.1f);
list2.push_front(2.2f);
std::cout << "list2: " << list2;
//3. Зацикливание
BidirectionalList list3;
std::cout << "list3: " << list3;
list3.push_back(2.2f);
list3.push_front(1.1f);
std::cout << "list3: " << list3;
//4. Падение
BidirectionalList list4;
list4.push_front(1);
list4.clear();
std::cout << "list4: " << list4;
//5. Падение
BidirectionalList list5;
list5.push_front(1);
list5.pop_front();
std::cout << "list5: " << list5;
BidirectionalList list6;
list6.push_front(1);
list6.pop_front();
std::cout << "list6: " << list6;
BidirectionalList list7;
list7.push_back(1);
list7.pop_front();
std::cout << "list7: " << list7;
BidirectionalList list8;
list8.push_back(1);
list8.pop_back();
std::cout << "list8: " << list8;
//// My test
std::cout << "\nMy tests\n\n";
BidirectionalList list;
list.push_front(std::string("front"));
list.push_back(10);
list.push_back(10.1f);
std::cout << "list: " << list;
BidirectionalList copy = list;
std::cout << "copy: " << copy;
copy.push_back(777);
copy.push_front(555.555f);
std::cout << "copy after push_back and push_front: " << copy;
list.pop_back();
list.pop_front();
std::cout << "list after pop_back and pop_front: " << list;
std::cout << "list front and back: " << list.front() << " " << list.back() << '\n';
std::cout << "copy front and back: " << copy.front() << " " << copy.back() << '\n';
list.clear();
std::cout << "is list empty after clear? " << list.empty() << '\n';
std::cout << "copy size " << copy.size() << '\n';
BidirectionalList mvCopy(std::move(copy));
std::cout << "movable copy: " << mvCopy << "is copy empty after move?: " << copy.empty() << '\n';
copy = std::move(mvCopy);
std::cout << "copy after operator= (&& mvCopy): " << copy << "is moveble copy empty after move?: " << mvCopy.empty() << '\n';
BidirectionalList::const_iterator it = copy.erase(++copy.begin());
std::cout << "copy after erase second: " << copy << "next after erase element: " << *it << " copy size: " << copy.size() << '\n';
copy.insert(++copy.begin(), 3);
std::cout << "copy after insert int 3 after first: " << copy;
copy.insert(++copy.begin(), 3.3f);
std::cout << "copy after insert float 3.3 after first: " << copy;
BidirectionalList::const_iterator it2 = copy.insert(--copy.end(), std::string("3str"));
std::cout << "copy after insert string before last: " << copy << "copy size: " << copy.size() << " insert value: " << *it2 << '\n';
return 0;
}
|
#include <BinomialQueue.h>
#include <stdexcept>
//
// This file contains the C++ code from Program 11.15 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm11_15.cpp
//
void BinomialQueue::AddTree (BinomialTree& tree)
{
list.Append (&tree);
count += tree.Count ();
}
void BinomialQueue::RemoveTree (BinomialTree& tree)
{
list.Extract (&tree);
count -= tree.Count ();
}
BinomialTree& BinomialQueue::FindMinTree (void) const
{
ListElement<BinomialTree*> const* ptr;
BinomialTree* minTree = 0;
for (ptr = list.Head (); ptr != 0; ptr = ptr->Next ())
{
BinomialTree* tree = ptr->Datum ();
if (minTree == 0 || tree->Key () < minTree->Key ())
minTree = tree;
}
return *minTree;
}
Object& BinomialQueue::FindMin () const
{
if (count == 0)
throw std::domain_error ("priority queue is empty");
return FindMinTree ().Key ();
}
void BinomialQueue::Merge (MergeablePriorityQueue& queue)
{
BinomialQueue& arg = dynamic_cast<BinomialQueue&> (queue);
LinkedList<BinomialTree*> oldList = list;
list.Purge ();
count = 0;
ListElement<BinomialTree*> const* p =
oldList.Head ();
ListElement<BinomialTree*> const* q =
arg.list.Head();
BinomialTree* carry = 0;
for (unsigned int i = 0; p || q || carry; ++i)
{
BinomialTree* a = 0;
if (p && p->Datum ()->Degree () == i)
{ a = p->Datum (); p = p->Next (); }
BinomialTree* b = 0;
if (q && q->Datum ()->Degree () == i)
{ b = q->Datum (); q = q->Next (); }
BinomialTree* sum = Sum (a, b, carry);
if (sum)
AddTree (*sum);
carry = Carry (a, b, carry);
}
arg.list.Purge ();
arg.count = 0;
}
BinomialTree* BinomialQueue::Sum (
BinomialTree* a, BinomialTree* b, BinomialTree* c)
{
if (a && !b && !c)
return a;
else if (!a && b && !c)
return b;
else if (!a && !b && c)
return c;
else if (a && b && c)
return c;
else
return 0;
}
BinomialTree* BinomialQueue::Carry (
BinomialTree* a, BinomialTree* b, BinomialTree* c)
{
if (a && b && !c)
{ a->Add (*b); return a; }
else if (a && !b && c)
{ a->Add (*c); return a; }
else if (!a && b && c)
{ b->Add (*c); return b; }
else if (a && b && c)
{ a->Add (*b); return a; }
else
return 0;
}
void BinomialQueue::Enqueue (Object& object)
{
BinomialQueue queue;
queue.AddTree (*new BinomialTree (object));
Merge (queue);
}
Object& BinomialQueue::DequeueMin ()
{
if (count == 0)
throw std::domain_error ("priority queue is empty");
BinomialTree& minTree = FindMinTree ();
RemoveTree (minTree);
BinomialQueue queue;
while (minTree.Degree () > 0)
{
BinomialTree& child = minTree.Subtree (0);
minTree.DetachSubtree (child);
queue.AddTree (child);
}
Merge (queue);
Object& result = minTree.Key ();
minTree.RescindOwnership ();
delete &minTree;
return result;
}
void BinomialQueue::Purge(void)
{
if(IsOwner()){
list.Purge();
}
}
void BinomialQueue::Accept(Visitor& visitor) const
{
ListElement<BinomialTree*> const* ptr;
for(ptr = list.Head(); ptr; ptr = ptr->Next()){
BinomialTree* tree = ptr->Datum();
tree->Accept(visitor);
}
}
int BinomialQueue::CompareTo(const Object&) const
{
return 0;
}
|
#pragma once
#include "matched_filter.hpp"
namespace ugsdr {
class IppMatchedFilter : public MatchedFilter<IppMatchedFilter> {
protected:
friend class MatchedFilter<IppMatchedFilter>;
template <typename UnderlyingType, typename T>
static void Process(std::vector<std::complex<UnderlyingType>>& src_dst, const std::vector<T>& impulse_response) {
}
template <typename UnderlyingType, typename T>
static auto Process(const std::vector<std::complex<UnderlyingType>>& src_dst, const std::vector<T>& impulse_response) {
auto dst = src_dst;
return dst;
}
};
}
|
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = nullptr;
bool l1_finished = false;
bool l2_finished = false;
int carry = 0;
ListNode* p1 = l1;
ListNode* p2 = l2;
ListNode* p3 = nullptr;
while (true) {
int lhs = 0;
int rhs = 0;
if (l1_finished && l2_finished) {
if (carry > 0) {
ListNode* carryNode = new ListNode(carry);
p3->next = carryNode;
}
break;
}
if (p1 != nullptr) {
lhs = p1->val;
p1 = p1->next;
if (p1 == nullptr)
l1_finished = true;
}
if (p2 != nullptr) {
rhs = p2->val;
p2 = p2->next;
if (p2 == nullptr)
l2_finished = true;
}
int sum = lhs + rhs + carry;
carry = sum / 10;
ListNode* node = new ListNode(sum % 10);
if (head == nullptr) {
head = node;
p3 = head;
}
else {
p3->next = node;
p3 = node;
}
}
return head;
}
|
#include <iostream>
//Функция расчёта рас-ия меж 2-мя точками
//Функция сравнения 3-ёх чисел на равность хотя бы 2-ух их них
int main()
{
std::cout << "Hello World!\n";
}
|
//======include header======
#include "Lives.h"
//===============C-TORS===============
Lives::Lives(int lives) : m_number_of_live(lives) {};
//----------------------------------------------------------------------------
//===============Helpers===============
// decreases the lives
void Lives::decrese() { m_number_of_live--; }
//----------------------------------------------------------------------------
// get function which returns the lives
int Lives::get_lives() { return m_number_of_live; };
//----------------------------------------------------------------------------
|
#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
#include <cmath>
#include "repast_hpc/Utilities.h"
#include "repast_hpc/Properties.h"
#include <fstream>
#include <sstream>
using namespace std;
int main(void){
// open calibration output file
std::ofstream calibration_write;
std::cout << "print 1" <<endl;
std::string fileName = "calibration/calibration_output.csv";
calibration_write.open(fileName, std::ios_base::app);
std::vector<std::string> data,datas;
std::vector<int> model_data;
std::vector<int> target_data;
// data.clear();
std::ofstream file_11;
std::string output_file1 = "output";
file_11.open(output_file1.c_str());
std::ifstream file_22;
std::string input_file1 = "household.csv";
file_22.open(input_file1.c_str());
if (!file_22.is_open())
std::cout << "ERROR: File Open input\n";
std::string value1;
while(getline(file_22, value1,'\n') && file_22.good()){
file_11<<value1;
}
// read input file
std::ifstream file_1;
std::string input_file = "input";
file_1.open(input_file.c_str());
if (!file_1.is_open())
std::cout << "ERROR: File Open input\n";
std::string value;
while(getline(file_1, value,'\n') && file_1.good()){
data.push_back(value);
}
// read output file
std::ifstream file_2;
std::string output_file = "output";
file_2.open(output_file.c_str());
if (!file_2.is_open())
std::cout << "ERROR: File Open ouput\n";
std::cout << "print 1" <<endl;
while(getline(file_2, value,' ') && file_2.good()){
model_data.push_back(repast::strToInt(value));
}
//std::cout << "print 1" <<endl;
// read target file
std::ifstream file_3;
std::string target_file = "target_data.csv";
file_3.open(target_file.c_str());
if (!file_3.is_open())
std::cout << "ERROR: File Open\n";
std::string line;
while (getline(file_3, line)){
std::stringstream ss(line);
while(getline(ss, value,',') && file_3.good()){
target_data.push_back(repast::strToInt(value));
}
}
//std::cout << "print 4" <<endl;
double RSME = 0;
double MAE = 0;
for (int i=0; i<model_data.size(); i++){
RSME = RSME + (model_data[i]-target_data[i])*(model_data[i]-target_data[i]);
MAE = MAE + abs(model_data[i]-target_data[i]);
}
RSME = sqrt(RSME/model_data.size());
MAE = MAE/model_data.size();
// compare output and target data
// save result
//std::cout << "print 5" <<endl;
// write to output file
calibration_write << RSME << ", ";
calibration_write << MAE << ", ";
calibration_write << repast::strToInt(data[0]) << ", ";
calibration_write << repast::strToInt(data[1]) << ", ";
calibration_write << repast::strToInt(data[2]) << ", ";
calibration_write << repast::strToInt(data[3]) << ", ";
calibration_write << repast::strToDouble(data[4]) << ", ";
calibration_write << repast::strToDouble(data[5]) << ", ";
calibration_write << repast::strToDouble(data[6]) << ", ";
std::cout << "print 6" <<endl;
calibration_write.close();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_HARDCORE_LOGGING_OPMESSAGELOGGER_H
#define MODULES_HARDCORE_LOGGING_OPMESSAGELOGGER_H
#ifdef HC_MESSAGE_LOGGING
class OpTypedMessage;
/** Interface for an OpTypedMessage logger.
*
* The implementer shall log dispatching and performing various actions on
* OpTypedMessages. Dispatching is handled separately to allow producing
* tree-like log structures, with traceable message flow histories.
*
* The implementer is free to choose the medium and format of the log, for
* example a text file, ecmascript DOM or an input to an external tool.
*
* Failures to log are expected to be either handled internally, quietly ignored
* or logged within the medium (ex. "Unable to log, reason: ..."). This is because
* it's not expected from the application code to contain extra logic for handling
* errors within the optional, debug-only logging system. The application treats
* the logging facilities as "fire and forget".
*/
class OpMessageLogger
{
public:
/** Called after the message has been taken off the message queue and
* scheduled for dispatching in OpComponentManager::DispatchMessage().
*
* @param msg Pointer to the message that will be dispatched momentarily.
*/
virtual void BeforeDispatch(const OpTypedMessage* msg) = 0;
/** Called after OpComponentManager::DispatchMessage() has returned.
*
* @param msg Pointer to the message that has just been dispatched.
*/
virtual void AfterDispatch(const OpTypedMessage* msg) = 0;
/** Called when an arbitrary action (like "Sending", "Adding to inbox" etc.)
* is performed on the message.
*
* @param msg Pointer to message upon which the action is performed.
* @param action Null-terminated string description of the action.
*/
virtual void Log(const OpTypedMessage* msg, const uni_char* action) = 0;
/** Checks whether the logger is able to log.
*
* A logger may be unable to log if, for example, there's an OOM situation,
* the medium is unavailable or some invariant is broken. In such situation,
* the implementation is free to ignore calls to AfterDispatch(),
* BeforeDispatch() or Log() by returning immediately.
*
* @return true if able to log, false otherwise.
*/
virtual bool IsAbleToLog() const = 0;
virtual ~OpMessageLogger() {}
};
#endif // HC_MESSAGE_LOGGING
#endif // MODULES_HARDCORE_LOGGING_OPMESSAGELOGGER_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef NS4P_COMPONENT_PLUGINS
#include "modules/hardcore/component/OpSyncMessenger.h"
#include "modules/ns4plugins/component/plugin_component_instance.h"
#include "modules/pi/OpPluginImage.h"
#include "platforms/windows/CustomWindowMessages.h"
#include "platforms/windows/IPC/WindowsOpComponentPlatform.h"
#include "platforms/windows_common/pi_impl/WindowsOpPluginTranslator.h"
#include "platforms/windows_common/src/generated/g_message_windows_common_messages.h"
#if defined(_PLUGIN_SUPPORT_) && defined(NS4P_COMPONENT_PLUGINS)
extern HINSTANCE hInst;
/* Class of the plugin window on the wrapper side. */
const uni_char WindowsOpPluginTranslator::s_wrapper_wndproc_class[] = UNI_L("PluginWrapperWindow");
OpWindowsPointerHashTable<const HWND, WindowsOpPluginTranslator*> WindowsOpPluginTranslator::s_wrapper_windows;
OpWindowsPointerHashTable<const HWND, void*> WindowsOpPluginTranslator::s_old_wndprocs;
/* Dummy window for use in hooked TrackPopupMenu. */
HWND WindowsOpPluginTranslator::s_dummy_contextmenu_window = NULL;
const uni_char WindowsOpPluginTranslator::s_dummy_activation_wndproc_class[] = UNI_L("PluginContextActivationWindow");
/* List of known browser window handles for use in hooked GetWindowInfo and others.
Handle is a pointer but also it can be shared between processes so we are
assuming that INT32 is appropriate in this case. */
OpINT32Vector WindowsOpPluginTranslator::s_browser_window_handles;
/* Tracking focused plugin instance. Answer is valid only within this process. */
WindowsOpPluginTranslator* WindowsOpPluginTranslator::s_focused_plugin = NULL;
/* Whether subclassing should be removed before (NO) or after (YES) calling window procedure of subclassed window (DSK-365584). */
BOOL3 WindowsOpPluginTranslator::s_unsubclass_after_wndproc = MAYBE;
OP_STATUS OpPluginTranslator::Create(OpPluginTranslator** translator, const OpMessageAddress& instance, const OpMessageAddress* adapter, const NPP npp)
{
if (!adapter)
return OpStatus::ERR_NULL_POINTER;
// Create the channel and store inside newly created instance.
OpChannel* channel = g_component->CreateChannel(*adapter);
RETURN_OOM_IF_NULL(channel);
// Create the plugin translator.
*translator = OP_NEW(WindowsOpPluginTranslator, (channel, reinterpret_cast<PluginComponentInstance*>(npp->ndata)));
if (!*translator)
{
OP_DELETE(channel);
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
bool OpPluginTranslator::GetGlobalValue(NPNVariable variable, void* ret_value, NPError* result)
{
return false;
}
WindowsOpPluginTranslator::WindowsOpPluginTranslator(OpChannel* channel, PluginComponentInstance* component_instance)
: m_channel(channel)
, m_plugin_window(NULL)
, m_wrapper_window(NULL)
, m_hdc(NULL)
, m_old_cliprect(NULL)
, m_shared_mem(NULL)
, m_bitmap(NULL)
, m_need_to_recreate_bitmap(true)
, m_component_instance(component_instance)
{
}
WindowsOpPluginTranslator::~WindowsOpPluginTranslator()
{
OP_DELETE(m_channel);
DeleteDC(m_hdc);
if (GetFocusedPlugin() == this)
SetFocusedPlugin(NULL);
WindowsOpPluginTranslator* wrapper = NULL;
OpStatus::Ignore(s_wrapper_windows.Remove(m_wrapper_window, &wrapper));
if (m_shared_mem)
if (WindowsSharedBitmapManager* bitmap_manager = WindowsSharedBitmapManager::GetInstance())
bitmap_manager->CloseMemory(m_identifier);
}
OP_STATUS WindowsOpPluginTranslator::UpdateNPWindow(NPWindow& out_npwin, const OpRect& rect, const OpRect& clip_rect, NPWindowType type)
{
// Request window information from the browser component.
// Hopefully we won't have to do it later, if core updates window handle by itself.
if (m_channel && !m_plugin_window)
{
OpSyncMessenger sync(m_channel);
RETURN_IF_ERROR(sync.SendMessage(OpWindowsPluginWindowInfoMessage::Create()));
// Take back ownership of the channel.
m_channel = sync.TakePeer();
// Get response message from browser component.
OpWindowsPluginWindowInfoResponseMessage* response = OpWindowsPluginWindowInfoResponseMessage::Cast(sync.GetResponse());
RETURN_OOM_IF_NULL(response);
m_plugin_window = reinterpret_cast<HWND>(response->GetWindow());
if (type == NPWindowTypeDrawable)
{
if (!m_hdc)
{
HDC dc = GetDC(m_plugin_window);
m_hdc = CreateCompatibleDC(dc);
ReleaseDC(m_plugin_window, dc);
}
// Create dummy context menu activation window for Flash. We should
// have some quirks system so that we do that only for Flash.
if (!s_dummy_contextmenu_window)
CreateDummyPopupActivationWindow(m_plugin_window);
// Add the browser window pointer to the list.
if (s_browser_window_handles.Find(reinterpret_cast<INT32>(m_plugin_window) == -1))
s_browser_window_handles.Add(reinterpret_cast<INT32>(m_plugin_window));
}
else if (!m_wrapper_window)
{
m_wrapper_window = CreateWindow(s_wrapper_wndproc_class, UNI_L(""), WS_CHILD | WS_VISIBLE, 0, 0, rect.width, rect.height, m_plugin_window, NULL, hInst, NULL);
if (!m_wrapper_window)
return OpStatus::ERR;
#ifndef SIXTY_FOUR_BIT
/* Some plugins use ANSI API's to retrieve the window procedure. If we
don't set it explicitly, the plugin will get garbage pointer and
crash on calling it.*/
SetWindowLongPtrA(m_wrapper_window, GWL_WNDPROC, reinterpret_cast<LONG_PTR>(WindowsOpPluginTranslator::WrapperWndProc));
#endif // !SIXTY_FOUR_BIT
s_wrapper_windows.Add(m_wrapper_window, this);
PostMessage(m_plugin_window, WM_WRAPPER_WINDOW_READY, 0, reinterpret_cast<LPARAM>(m_wrapper_window));
}
}
if (rect.width > m_plugin_rect.width || rect.height > m_plugin_rect.height)
m_need_to_recreate_bitmap = true;
// Store plugin rect.
m_plugin_rect.Set(rect);
// Set up position and size.
out_npwin.x = rect.x;
out_npwin.y = rect.y;
out_npwin.width = rect.width;
out_npwin.height = rect.height;
// Set-up clip-rect.
out_npwin.clipRect.top = clip_rect.Top();
out_npwin.clipRect.right = clip_rect.Right();
out_npwin.clipRect.bottom = clip_rect.Bottom();
out_npwin.clipRect.left = clip_rect.Left();
// Set up window and type.
out_npwin.type = type;
out_npwin.window = type == NPWindowTypeWindow ? reinterpret_cast<void*>(m_wrapper_window) : m_hdc;
return OpStatus::OK;
}
OP_STATUS WindowsOpPluginTranslator::CreateFocusEvent(OpPlatformEvent** out_event, bool got_focus)
{
SetFocusedPlugin(got_focus ? this : NULL);
WindowsOpPlatformEvent* event = OP_NEW(WindowsOpPlatformEvent, ());
RETURN_OOM_IF_NULL(event);
event->m_event.event = got_focus ? WM_SETFOCUS : WM_KILLFOCUS;
event->m_event.wParam = 0;
event->m_event.lParam = 0;
*out_event = event;
return OpStatus::OK;
}
OP_STATUS WindowsOpPluginTranslator::CreateKeyEventSequence(OtlList<OpPlatformEvent*>& events, OpKey::Code key, uni_char value, OpPluginKeyState key_state, ShiftKeyState modifiers, UINT64 data1, UINT64 data2)
{
WindowsOpPlatformEvent* event = OP_NEW(WindowsOpPlatformEvent, ());
RETURN_OOM_IF_NULL(event);
// Core generates a key_down and a key_pressed for the first WM_KEYDOWN it receives.
// If bit 30 of lParam is not set, it means that the key_press message isn't indicating
// a key repeat and we can ignore it.
if ((key_state == PLUGIN_KEY_PRESSED) && ((data2 & 1<<30) == 0))
return OpStatus::OK;
event->m_event.event = (key_state == PLUGIN_KEY_UP) ? WM_KEYUP : WM_KEYDOWN;
event->m_event.wParam = static_cast<WPARAM>(data1);
event->m_event.lParam = static_cast<LPARAM>(data2);
RETURN_IF_ERROR(events.Append(event));
return OpStatus::OK;
}
OP_STATUS WindowsOpPluginTranslator::CreateMouseEvent(OpPlatformEvent** out_event, OpPluginEventType event_type, const OpPoint& point, int button_or_delta, ShiftKeyState modifiers)
{
WindowsOpPlatformEvent* event = OP_NEW(WindowsOpPlatformEvent, ());
RETURN_OOM_IF_NULL(event);
event->m_event.wParam = 0;
switch (event_type)
{
case PLUGIN_MOUSE_DOWN_EVENT:
event->m_event.event = button_or_delta == MOUSE_BUTTON_1 ? WM_LBUTTONDOWN : button_or_delta == MOUSE_BUTTON_2 ? WM_RBUTTONDOWN : WM_MBUTTONDOWN;
break;
case PLUGIN_MOUSE_UP_EVENT:
event->m_event.event = button_or_delta == MOUSE_BUTTON_1 ? WM_LBUTTONUP : button_or_delta == MOUSE_BUTTON_2 ? WM_RBUTTONUP : WM_MBUTTONUP;
break;
case PLUGIN_MOUSE_MOVE_EVENT:
case PLUGIN_MOUSE_ENTER_EVENT:
case PLUGIN_MOUSE_LEAVE_EVENT:
event->m_event.event = WM_MOUSEMOVE;
break;
case PLUGIN_MOUSE_WHEELV_EVENT:
case PLUGIN_MOUSE_WHEELH_EVENT:
{
// Cached value of the SPI_GETWHEELSCROLLLINES user setting.
static UINT lines_to_scroll_value = 0;
// Delta value got from core is converted to the number of lines that
// should be scrolled. It needs to be converted back to delta.
// We can't do that precisely though as number of lines is rounded
// but that is not really an issue.
if (!lines_to_scroll_value)
{
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0 , &lines_to_scroll_value, 0);
// Guard from 0 value that would crash on dividing.
lines_to_scroll_value = MAX(1, lines_to_scroll_value);
}
int delta = (-button_or_delta / lines_to_scroll_value) * WHEEL_DELTA;
event->m_event.event = event_type == PLUGIN_MOUSE_WHEELV_EVENT ? WM_MOUSEWHEEL : WM_MOUSEHWHEEL;
event->m_event.wParam = MAKEWPARAM(0, delta);
break;
}
default:
OP_DELETE(event);
return OpStatus::ERR_NOT_SUPPORTED;
}
// Convert from plugin to window coordinates.
event->m_event.lParam = MAKELONG(m_plugin_rect.x + point.x, m_plugin_rect.y + point.y);
if (modifiers & SHIFTKEY_CTRL)
event->m_event.wParam |= MK_CONTROL;
if (modifiers & SHIFTKEY_SHIFT)
event->m_event.wParam |= MK_SHIFT;
if (GetKeyState(VK_LBUTTON) & 0x8000)
event->m_event.wParam |= MK_LBUTTON;
if (GetKeyState(VK_RBUTTON) & 0x8000)
event->m_event.wParam |= MK_RBUTTON;
if (GetKeyState(VK_MBUTTON) & 0x8000)
event->m_event.wParam |= MK_MBUTTON;
*out_event = event;
return OpStatus::OK;
}
OP_STATUS WindowsOpPluginTranslator::CreatePaintEvent(OpPlatformEvent** out_event, OpPluginImageID dest, OpPluginImageID bg, const OpRect& paint_rect, NPWindow* npwin, bool* npwindow_was_modified)
{
OpAutoPtr<WindowsOpPlatformEvent> event = OP_NEW(WindowsOpPlatformEvent, ());
RETURN_OOM_IF_NULL(event.get());
// Create rect in window coordinates.
OpAutoPtr<RECT> dirty_area = OP_NEW(RECT, ());
RETURN_OOM_IF_NULL(dirty_area.get());
dirty_area->left = m_plugin_rect.x; // + paint_rect.x;
dirty_area->top = m_plugin_rect.y; // + paint_rect.y;
dirty_area->right = m_plugin_rect.x + m_plugin_rect.width; // dirty_area->left + paint_rect.width;
dirty_area->bottom = m_plugin_rect.y + m_plugin_rect.height; // dirty_area->top + paint_rect.height;
SetViewportOrgEx(m_hdc, -m_plugin_rect.x, -m_plugin_rect.y, NULL);
// Open shared memory and create bitmap the size of plugin rect.
if (!m_shared_mem || m_need_to_recreate_bitmap)
{
WindowsSharedBitmapManager* bitmap_manager = WindowsSharedBitmapManager::GetInstance();
RETURN_OOM_IF_NULL(bitmap_manager);
m_shared_mem = bitmap_manager->OpenMemory(dest);
RETURN_OOM_IF_NULL(m_shared_mem);
m_identifier = dest;
int width;
int height;
m_shared_mem->GetDimensions(width, height);
BITMAPINFO bi = {0};
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = width;
bi.bmiHeader.biHeight = -height;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biSizeImage = 0;
bi.bmiHeader.biXPelsPerMeter = 0;
bi.bmiHeader.biYPelsPerMeter = 0;
bi.bmiHeader.biClrUsed = 0;
bi.bmiHeader.biClrImportant = 0;
void* bitmap_data = NULL;
m_bitmap = CreateDIBSection(m_hdc, &bi, DIB_RGB_COLORS, &bitmap_data, m_shared_mem->GetFileMappingHandle(), m_shared_mem->GetDataOffset());
RETURN_OOM_IF_NULL(m_bitmap);
SelectObject(m_hdc, m_bitmap);
m_need_to_recreate_bitmap = false;
}
event->m_event.event = WM_PAINT;
event->m_event.wParam = reinterpret_cast<uintptr_t>(m_hdc);
event->m_event.lParam = reinterpret_cast<uintptr_t>(dirty_area.release());
*out_event = event.release();
return OpStatus::OK;
}
OP_STATUS WindowsOpPluginTranslator::FinalizeOpPluginImage(OpPluginImageID, const NPWindow&)
{
SetViewportOrgEx(m_hdc, 0, 0, NULL);
return OpStatus::OK;
}
OP_STATUS WindowsOpPluginTranslator::CreateWindowPosChangedEvent(OpPlatformEvent** out_event)
{
WindowsOpPlatformEvent* event = OP_NEW(WindowsOpPlatformEvent, ());
RETURN_OOM_IF_NULL(event);
// Set structure with plugin rect relative to the browser window.
WINDOWPOS *winpos = OP_NEW(WINDOWPOS, ());
op_memset(winpos, 0, sizeof(WINDOWPOS));
winpos->x = m_plugin_rect.x;
winpos->y = m_plugin_rect.y;
winpos->cx = m_plugin_rect.width;
winpos->cy = m_plugin_rect.height;
event->m_event.event = WM_WINDOWPOSCHANGED;
event->m_event.wParam = 0;
event->m_event.lParam = reinterpret_cast<uintptr_t>(winpos);
*out_event = event;
return OpStatus::OK;
}
bool WindowsOpPluginTranslator::GetValue(NPNVariable variable, void* ret_value, NPError* result)
{
if (variable == NPNVnetscapeWindow)
{
if (!m_plugin_window)
return false;
*(static_cast<void**>(ret_value)) = m_plugin_window;
return true;
}
return false;
}
bool WindowsOpPluginTranslator::ConvertPlatformRegionToRect(NPRegion invalid_region, NPRect &invalid_rect)
{
RECT rect;
if (GetRgnBox(static_cast<HRGN>(invalid_region), &rect) == SIMPLEREGION)
{
invalid_rect.top = static_cast<uint16>(rect.top);
invalid_rect.left = static_cast<uint16>(rect.left);
invalid_rect.bottom = static_cast<uint16>(rect.bottom);
invalid_rect.right = static_cast<uint16>(rect.right);
return TRUE;
}
return FALSE;
}
void WindowsOpPluginTranslator::SubClassPluginWindowproc(HWND hwnd)
{
WNDPROC plugin_wndproc;
if (!s_old_wndprocs.Contains(hwnd))
{
if (hwnd == m_wrapper_window)
plugin_wndproc = reinterpret_cast<WNDPROC>(SetWindowLongPtr(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(WindowsOpPluginTranslator::WrapperSubclassWndProc)));
else
plugin_wndproc = reinterpret_cast<WNDPROC>(SetWindowLongPtr(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(WindowsOpPluginTranslator::WrapperSubclassChildWndProc)));
s_old_wndprocs.Add(hwnd, plugin_wndproc);
}
}
/*static*/
LRESULT WindowsOpPluginTranslator::CallSubclassedWindowProc(void* wndproc, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (s_unsubclass_after_wndproc == MAYBE)
{
WindowsOpPluginTranslator* wrapper = NULL;
if (OpStatus::IsSuccess(s_wrapper_windows.GetData(hWnd, &wrapper)) && wrapper)
{
PluginComponent* component = wrapper->m_component_instance ? wrapper->m_component_instance->GetComponent() : NULL;
if (component && component->GetLibrary())
{
UniString name;
if (OpStatus::IsSuccess(component->GetLibrary()->GetName(&name)) && name.StartsWith(UNI_L("Google Talk Plugin")))
{
s_unsubclass_after_wndproc = YES; // fix for DSK-365364
}
else
{
s_unsubclass_after_wndproc = NO;
}
}
}
}
if (s_unsubclass_after_wndproc != YES)
{
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(wndproc));
}
LRESULT ret = CallWindowProc(reinterpret_cast<WNDPROC>(wndproc), hWnd, msg, wParam, lParam);
if (s_unsubclass_after_wndproc == YES)
{
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(wndproc));
}
return ret;
}
OP_STATUS WindowsOpPluginTranslator::GetPluginFromHWND(HWND hwnd, BOOL search_parents, WindowsOpPluginTranslator* &wrapper)
{
OP_STATUS err = s_wrapper_windows.GetData(hwnd, &wrapper);
if (!search_parents || (OpStatus::IsSuccess(err) && wrapper))
return err;
hwnd = GetParent(hwnd);
if (hwnd == NULL)
return OpStatus::ERR;
else
return GetPluginFromHWND(hwnd, search_parents, wrapper);
}
/*static*/
void WindowsOpPluginTranslator::RegisterWrapperWndProcClass()
{
WNDCLASSEX plugin_window_class = {0};
plugin_window_class.cbSize = sizeof(plugin_window_class);
plugin_window_class.style = CS_DBLCLKS;
plugin_window_class.lpfnWndProc = WindowsOpPluginTranslator::WrapperWndProc;
plugin_window_class.hInstance = hInst;
plugin_window_class.lpszClassName = s_wrapper_wndproc_class;
RegisterClassEx(&plugin_window_class);
}
/*static*/
void WindowsOpPluginTranslator::UnregisterWrapperWndProcClass()
{
UnregisterClass(s_wrapper_wndproc_class, NULL);
}
/*static*/
LRESULT WindowsOpPluginTranslator::WrapperWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_NCDESTROY:
{
if (s_wrapper_windows.Contains(hWnd))
{
WindowsOpPluginTranslator* wrapper = NULL;
OpStatus::Ignore(s_wrapper_windows.Remove(hWnd, &wrapper));
wrapper->m_wrapper_window = NULL;
}
break;
}
case WM_ENTERMENULOOP:
case WM_EXITMENULOOP:
case WM_MENUSELECT:
/* Opera window has to know about these events so that it can reset
InputManager state when invoking plugin's context menu. It doesn't
really matter to which Opera window these messages are sent. */
if (s_browser_window_handles.GetCount())
SendMessage(reinterpret_cast<HWND>(s_browser_window_handles.Get(0)), msg, wParam, lParam);
break;
// Fix for DSK-256843, workaround for a bug in flash.
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
::ReleaseCapture();
break;
default:
{
LRESULT result;
if (HandleMessage(hWnd, msg, wParam, lParam, result))
return result;
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
/*static*/
LRESULT WindowsOpPluginTranslator::WrapperSubclassChildWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
//We are receiving a sent (and thus probably blocking) message, probably from a parent process.
//Reply to it before handling it
if (InSendMessage() && (msg == WM_WINDOWPOSCHANGED || msg == WM_KILLFOCUS || msg == WM_SETFOCUS || msg == WM_PAINT))
ReplyMessage(0);
void* old_wndproc;
if (OpStatus::IsError(s_old_wndprocs.Remove(hWnd, &old_wndproc)))
return NULL;
if (old_wndproc)
{
return CallSubclassedWindowProc(old_wndproc, hWnd, msg, wParam, lParam);
}
//If this happens, it means that some window got its wndproc subclassed by this one, but the old window proc
//wasn't found in s_old_wndprocs.
OP_ASSERT(false);
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(old_wndproc));
return WrapperWndProc(hWnd, msg, wParam, lParam);
}
/*static*/
LRESULT WindowsOpPluginTranslator::WrapperSubclassWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
//We are receiving a sent (and thus probably blocking) message, probably from a parent process.
//Reply to it before handling it
if (InSendMessage() && (msg == WM_WINDOWPOSCHANGED || msg == WM_KILLFOCUS || msg == WM_SETFOCUS || msg == WM_PAINT))
ReplyMessage(0);
void* old_wndproc;
if (OpStatus::IsError(s_old_wndprocs.Remove(hWnd, &old_wndproc)))
return NULL;
if (old_wndproc)
{
switch (msg)
{
case WM_DESTROY:
{
WindowsOpPluginTranslator* wrapper = NULL;
GetPluginFromHWND(hWnd, FALSE, wrapper);
//Fix for DSK-350479
if (InSendMessage())
wrapper->m_component_instance->SetRequestsAllowed(FALSE);
break;
}
case WM_NCCALCSIZE:
if (InSendMessage())
{
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(old_wndproc));
return 0;
}
}
LRESULT result;
if (HandleMessage(hWnd, msg, wParam, lParam, result))
{
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(old_wndproc));
return result;
}
else
{
return CallSubclassedWindowProc(old_wndproc, hWnd, msg, wParam, lParam);
}
}
//If this happens, it means that some window got its wndproc subclassed by this one, but the old window proc
//wasn't found in s_old_wndprocs.
OP_ASSERT(false);
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(old_wndproc));
return WrapperWndProc(hWnd, msg, wParam, lParam);
}
/*static*/
bool WindowsOpPluginTranslator::HandleMessage(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam, LRESULT& result)
{
bool handled = false;
switch (msg)
{
/* Prevent some modifications to plugin window by the plugin. This
message is triggered by ShowWindow, SetWindowPos and probably many
other API calls so it should handle most cases. */
case WM_WINDOWPOSCHANGING:
{
WINDOWPOS* winpos = reinterpret_cast<WINDOWPOS*>(lparam);
winpos->flags &= ~SWP_SHOWWINDOW & ~SWP_HIDEWINDOW;
winpos->flags |= SWP_NOMOVE;
result = 0;
handled = true;
}
case WM_SETFOCUS:
{
WindowsOpPluginTranslator* wrapper = NULL;
if (OpStatus::IsSuccess(s_wrapper_windows.GetData(hwnd, &wrapper)))
SetFocusedPlugin(wrapper);
break;
}
case WM_KILLFOCUS:
SetFocusedPlugin(NULL);
break;
}
return handled;
}
/*static*/
void WindowsOpPluginTranslator::CreateDummyPopupActivationWindow(HWND parent_window)
{
if (s_dummy_contextmenu_window)
return;
// Reusing normal wrapper window proc. Might be better to create new class for it.
s_dummy_contextmenu_window = CreateWindow(s_wrapper_wndproc_class, NULL, WS_CHILD, 0, 0, 0, 0, parent_window, NULL, hInst, NULL);
}
/*static*/
void WindowsOpPluginTranslator::RemoveDummyPopupActivationWindow()
{
if (s_dummy_contextmenu_window)
{
DestroyWindow(s_dummy_contextmenu_window);
s_dummy_contextmenu_window = NULL;
}
}
/*static*/
WINBOOL WINAPI WindowsOpPluginTranslator::TrackPopupMenuHook(HMENU menu, UINT flags, int x, int y, int reserved, HWND hwnd, const RECT* rect)
{
/* Overriding window handle because Flash in opaque mode calls this method
with handle that is in another process and that fails.
If plugin wants to be notified about menu selection using the return
value then we can safely override window handle as it should not need
to handle the menu messages. Otherwise better not mess with it. */
if (s_dummy_contextmenu_window && (flags & TPM_RETURNCMD))
hwnd = s_dummy_contextmenu_window;
return TrackPopupMenu(menu, flags, x, y, reserved, hwnd, rect);
}
/*static*/
WINBOOL WINAPI WindowsOpPluginTranslator::GetWindowInfoHook(HWND hwnd, PWINDOWINFO pwi)
{
/* Replace window rect with client rect if plugin attempts
to retrieve info about our browser window. */
static HWND last_opera_hwnd = NULL;
WINBOOL ret = GetWindowInfo(hwnd, pwi);
if (ret && (hwnd == last_opera_hwnd || s_browser_window_handles.Find(reinterpret_cast<INT32>(hwnd) != -1)))
{
pwi->rcWindow = pwi->rcClient;
last_opera_hwnd = hwnd;
}
return ret;
}
/* static */
HWND WINAPI WindowsOpPluginTranslator::GetFocusHook()
{
if (!GetFocusedPlugin())
return reinterpret_cast<HWND>(-1);
return GetFocus();
}
#endif // _PLUGIN_SUPPORT_ && NS4P_COMPONENT_PLUGINS
#endif // NS4P_COMPONENT_PLUGINS
|
#include <iostream>
#include <typeinfo>
#include <vector>
using namespace std;
class geshenk {
public:
virtual void rozpakuj() {
cout << "ta daaa" << endl;
}
virtual void typ() {
cout << typeid(*this).name() << endl;
}
};
class schlapmyca : public geshenk {
public:
void zaloz() {
cout << "jest ciepla" << endl;
}
};
class pieniadze : public geshenk {
public:
void wydaj() {
cout << "teraz juz nic nie masz" << endl;
}
};
class czekolada : public geshenk {
public:
void zjedz() {
cout << "zjadles" << endl;
}
};
int main() {
geshenk * geshenki;
vector<geshenk*> lista = {
new schlapmyca,
new pieniadze,
new czekolada,
new pieniadze
};
for (auto geshenk : lista) {
if (czekolada* nowe = dynamic_cast<czekolada*>(geshenk)) {
nowe->zjedz();
nowe->typ();
cout << endl;
}
if (pieniadze* nowe = dynamic_cast<pieniadze*>(geshenk)) {
nowe->wydaj();
nowe->typ();
cout << endl;
}
if (schlapmyca* nowe = dynamic_cast<schlapmyca*>(geshenk)) {
nowe->zaloz();
nowe->typ();
cout << endl;
}
}
return 0;
}
|
/*
这里包括交换排序的算法
1.冒泡排序
2.快速排序
*/
#include "iostream"
using namespace std;
#define MAXSIZE 10
typedef int KeyType;
typedef struct{
KeyType key;
}RedType;
typedef struct{
RedType r[MAXSIZE+1];
int length;
}SqList;
void InitSqList(SqList &L)
{
L.length =0;
}
void CreateSqList(SqList &L)
{
int i=0;
for(i=1;i<=MAXSIZE;i++)
{
cout << "num:";
cin >> L.r[i].key;
L.length++;
}
}
//Bubble_Sort
void Bubble_Sort(SqList &L)
{
int m,j,i;
RedType x;
for(m=1;m<=L.length-1;m++)
{
for(j=1;j<=L.length-m;j++){
if(L.r[j].key>L.r[j+1].key){
x=L.r[j];
L.r[j]=L.r[j+1];
L.r[j+1]=x;
}
}
}
}
//Get the pivotloc
int Partition(SqList &L,int low,int high)
{
L.r[0]=L.r[low];
int pivotloc = L.r[low].key;
while(low<high){
while(low<high&&L.r[high].key>=pivotloc) --high;
L.r[low]=L.r[high];
while(low<high&&L.r[low].key<=pivotloc) ++low;
L.r[high]=L.r[low];
}
L.r[low]=L.r[0];
return low;
}
//QuickSort
void QSort(SqList &L,int low,int high)
{
int pivotloc;
if(low<high){
pivotloc = Partition(L,low,high);
QSort(L,low,pivotloc-1);
QSort(L,pivotloc+1,high);
}
}
void Output(SqList &L)
{
int i=0;
for(i=1;i<=L.length;i++)
{
cout << L.r[i].key << " ";
}
cout << endl;
}
int main()
{
SqList L;
InitSqList(L);
CreateSqList(L);
cout << "BubbleSort:"<<endl;
Output(L);
Bubble_Sort(L);
Output(L);
cout << "QuickSort:"<<endl;
QSort(L,1,L.length);
Output(L);
return 0;
}
|
//
// Created by manout on 17-6-29.
//
#ifndef PRACTICE_FOR_CODING_ALL_INCLUDE_H
#define PRACTICE_FOR_CODING_ALL_INCLUDE_H
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <algorithm>
#include <stack>
#include <queue>
#include <cstring>
#include <iterator>
//STL容器
using std::string;
using std::unordered_map;
using std::vector;
using std::map;
using std::set;
using std::pair;
using std::stack;
using std::queue;
using std::reverse_iterator;
using std::prev;
using std::next;
using std::swap;
//STL算法
using std::sort;
using std::unique;
using std::make_pair;
using std::max;
using std::min;
#endif //PRACTICE_FOR_CODING_ALL_INCLUDE_H
|
/*
* Control.cpp
*
* Created on: Jan 21, 2018
* Author: robert
*/
#include "../inc/Control.h"
Control::Control() {
// TODO Auto-generated constructor stub
this->blue=0;
this->red=0;
this->fan=0;
this->crio=0;
}
Control::~Control() {
// TODO Auto-generated destructor stub
}
void Control::SetParams(int red,int blue,int fan,int crio)
{
this->red=red;
this->blue=blue;
this->fan=fan;
this->crio=crio;
}
|
/*
@lc app=leetcode.cn id=337 lang=cpp
*
[337] 打家劫舍 III
*/
// @lc code=start
/**
Definition for a binary tree node. */
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
// struct TreeNode {
// int val;
// TreeNode *left;
// TreeNode *right;
// TreeNode(int x) : val(x), left(NULL), right(NULL) {}
// };
class Solution {
public:
int rob(TreeNode* root) {
vector<int> ans = dp(root);
return max(ans[0], ans[1]);
}
// 这个思路的核心是,用一个pair保存抢或者不抢能够获得的最大值
vector<int> dp(TreeNode* root){
if(root==NULL)return vector<int>(2, 0);
vector<int> left = dp(root->left);
vector<int> right = dp(root->right);
int rob = root->val + left[0] + right[0];
int not_rob = max(left[0],left[1]) + max(right[0], right[1]);
vector<int> ans;
ans.push_back(not_rob);
ans.push_back(rob);
return ans;
}
// map<TreeNode*,int> memo;
// int rob(TreeNode* root) {
// memo.clear();
// return dfs(root);
// }
// int dfs(TreeNode* root)
// {
// if(root==NULL)return 0;
// if(memo.find(root)!=memo.end()){
// return memo[root];
// }
// int do_it = root->val +
// (root->left==NULL ? 0 : rob(root->left->left)+rob(root->left->right)) +
// (root->right==NULL ? 0 : rob(root->right->left) + rob(root->right->right));
// int not_do = rob(root->left) + rob(root->right);
// int res = max(do_it, not_do);
// memo[root] = res;
// return res;
// }
};
// @lc code=end
|
#include <iostream>
#include <fstream>
#include "JackTokenizer.h"
#include "CompilationEngine.h"
int main(int argc, char* argv[]){
if(argc == 0){
std::cout << "Usage: JackCompiler file1.jack file2.jack ..." << std::endl;
return 1;
}
std::string fileName;
for(int i = 1; i < argc; i++){
fileName = argv[i];
int fileExt = fileName.find(".jack");
if(fileExt == std::string::npos){
continue;
}
else{
JackTokenizer jt(fileName);
while(jt.hasMoreTokens()){
jt.advance();
}
SymbolTable st;
CompilationEngine ce(fileName, &jt, &st);
}
}
return 0;
}
|
#include "rdtsc_benchmark.h"
#include "ut.hpp"
#include <iostream>
#include <random>
#include <algorithm>
#include <math.h>
#include <functional>
#include <vector>
#include <immintrin.h>
#include "compute_jacobians.h"
#include "linalg.h"
using namespace boost::ut; // provides `expect`, `""_test`, etc
using namespace boost::ut::bdd; // provides `given`, `when`, `then`
Particle* particle_preloader(Vector3d xv, Vector2d xf[], Matrix2d Pf[], const size_t Nfa) {
Particle* particle = newParticle(50, xv);
for (int i = 0; i< Nfa; i++) {
set_xfi(particle, xf[i], i);
set_Pfi(particle, Pf[i], i);
}
return particle;
}
void enforce_symmetry_Pf(Matrix2d Pf[], const size_t Nfa) {
for ( int i = 0; i<Nfa; i++) {
Pf[i][2] = Pf[i][1];
}
}
// I will try to add this as smooth as possible to the benchmark, but for now do this
void set_work(Benchmark<decltype(&compute_jacobians)>& bench, Particle* particle,
int idf[],
size_t N_z,
Matrix2d R,
Vector2d zp[],
Matrix23d Hv[],
Matrix2d Hf[],
Matrix2d Sf[]) {
bench.funcFlops[0] = compute_jacobians_base_flops(particle, idf, N_z, R, zp, Hv, Hf, Sf);
bench.funcBytes[0] = 8 * compute_jacobians_base_memory(particle, idf, N_z, R, zp, Hv, Hf, Sf);
for (int i = 1; i < bench.numFuncs; i++) {
bench.funcFlops[i] = compute_jacobians_active_flops(particle, idf, N_z, R, zp, Hv, Hf, Sf);
bench.funcBytes[i] = 8 * compute_jacobians_active_memory(particle, idf, N_z, R, zp, Hv, Hf, Sf);
}
}
int main() {
// Initialize Input
// prepare particle
srand(0);
Vector3d xv = {0,0,0}; //! robot pose: x,y,theta (heading dir)
const size_t Nfa = 20;
Vector2d xf[Nfa];
Matrix2d Pf[Nfa];
fill_rand(*xf, 2*Nfa, -2.0,2.0);
fill_rand(*Pf, 4*Nfa, 0.0,0.2); //Ignore symmetry for computation for now. Pos. semi-definite
enforce_symmetry_Pf(Pf, Nfa);
Particle* particle = particle_preloader(xv,xf,Pf, Nfa);
Matrix2d R __attribute__((aligned(32))) = {1,0,0,1};
// outputs
Vector2d zp[Nfa] __attribute__((aligned(32)));
Matrix23d* Hv = static_cast<Matrix23d *>(aligned_alloc(32, Nfa * sizeof(Matrix23d)));
Matrix2d* Hf = static_cast<Matrix2d *>(aligned_alloc(32, Nfa * sizeof(Matrix2d)));
Matrix2d* Sf = static_cast<Matrix2d *>(aligned_alloc(32, Nfa * sizeof(Matrix2d)));
//Input -> Change this as you like
const size_t Nfz = 12; // Nfz <= Nfa
int idf[Nfz] __attribute__((aligned(32))) = {0,1,2,3,4,5,6,7,8,9,10,11}; //Unique
// Compare two methods
"functional equality"_test = [&] {
auto is_close = [&](double lhs, double rhs) -> bool {return std::abs(lhs - rhs) < 1e-4;};
Vector2d zp_base[Nfa] __attribute__((aligned(32)));
Matrix23d Hv_base[Nfa] __attribute__((aligned(32)));
Matrix2d Hf_base[Nfa] __attribute__((aligned(32)));
Matrix2d Sf_base[Nfa] __attribute__((aligned(32)));
compute_jacobians_base(particle, idf, Nfz, R, zp_base, Hv_base, Hf_base, Sf_base);
compute_jacobians_fast(particle, idf, Nfz, R, zp, Hv, Hf, Sf);
for (int i = 0; i < Nfz; i++) {
for (int j = 0; j<4;j++) {
expect(is_close(Hf_base[i][j], Hf[i][j])) <<i << "Hf" <<j;
expect(is_close(Sf_base[i][j], Sf[i][j])) <<i <<"Sf"<<j << Sf[i][j]<< Sf_base[i][j];
}
for (int j = 0; j<6;j++) {
expect(is_close(Hv_base[i][j], Hv[i][j])) <<i << "Hv"<<j;
}
for (int j = 0; j<2;j++) {
expect(is_close(zp_base[i][j], zp[i][j])) <<i << "zp"<<j << zp[i][j]<< zp_base[i][j];
}
}
};
auto ymm0 = _mm256_set_pd(3,2,1,0);
// Initialize the benchmark struct by declaring the type of the function you want to benchmark
Benchmark<decltype(&compute_jacobians)> bench("compute_jacobians Benchmark");
bench.add_function(&compute_jacobians_base, "compute_jacobians_base", 0.0);
bench.add_function(&compute_jacobians_fast, "compute_jacobians_fast", 0.0);
#ifdef __AVX2__
bench.add_function(&compute_jacobians_advanced_optimizations, "compute_jacobians_jonathan", 0.0);
#endif
//bench.add_function(&compute_jacobians, "compute_jacobians", work);
bench.add_function(&compute_jacobians_simd, "compute_jacobians_simd", 0.0);
bench.add_function(&compute_jacobians_nik, "compute_jacobians_nik", 0.0);
bench.add_function(&compute_jacobians_scalar_replacement, "compute_jacobians_scalar_replacement", 0.0);
bench.add_function(&compute_jacobians_linalg_inplace, "compute_jacobians_linalg_inplace", 0.0);
int idf_4[1] = {5};
set_work(bench, particle, idf_4, 1, R, zp, Hv, Hf, Sf);
bench.run_benchmark(particle, idf_4, 1, R, zp, Hv, Hf, Sf);
set_work(bench, particle, idf, Nfz, R, zp, Hv, Hf, Sf);
bench.run_benchmark(particle, idf, Nfz, R, zp, Hv, Hf, Sf);
int idf_2[Nfz] __attribute__((aligned(32))) = {0,2,4,6,8,10,12,14,16,17,18,19};
set_work(bench, particle, idf_2, Nfz, R, zp, Hv, Hf, Sf);
bench.run_benchmark(particle, idf_2, Nfz, R, zp, Hv, Hf, Sf);
int idf_3[20] __attribute__((aligned(32))) = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
set_work(bench, particle, idf_3, 20, R, zp, Hv, Hf, Sf);
bench.run_benchmark(particle, idf_3, 20, R, zp, Hv, Hf, Sf);
delParticleMembersAndFreePtr(particle);
free(Hv);
free(Hf);
free(Sf);
bench.details();
return 0;
}
|
#include "pch.h"
#include "Quicksort.h"
#include "Swap.h"
#include <vector>
#include <chrono>
Quicksort::Quicksort() {}
Quicksort::~Quicksort() {}
int Quicksort::partition(std::vector<int> &vec, int low, int high) {
Swap sp;
int pivot = vec[high]; //pivot, the last value gave best results
int i = (low - 1); //index of smaller element
for (int j = low; j <= high - 1; j++) { //moves the elements and returns the pivot location
if (vec[j] <= pivot) {
i++;
sp.swap(&vec[i], &vec[j]);
}
}
sp.swap(&vec[i + 1], &vec[high]);
return (i + 1);
}
void Quicksort::quickSortClone(std::vector<int> &vec, int low, int high) {
checkpoint:
if (low < high) {
int pi = partition(vec, low, high);
if (pi < (low + high) / 2) {
quickSortClone(vec, low, pi - 1);
low = pi + 1; goto checkpoint;
}
else {
quickSortClone(vec, pi + 1, high);
high = pi - 1; goto checkpoint;
}
}
}
int Quicksort::quickSort(std::vector<int> &vec, int low, int high) {
std::chrono::time_point<std::chrono::system_clock> now =
std::chrono::system_clock::now();
auto duration = now.time_since_epoch();
int microStart = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
checkpoint: //used to solve stack overflow issue at 10,000 and 50,000 elements
if (low < high) {
int pi = partition(vec, low, high); //pivot
if (pi < (low + high)/2) {
quickSortClone(vec, low, pi - 1);
low = pi + 1; goto checkpoint;
}
else {
quickSortClone(vec, pi + 1, high);
high = pi - 1; goto checkpoint;
}
}
now = std::chrono::system_clock::now();
duration = now.time_since_epoch();
int microEnd = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
return (microEnd - microStart);
}
|
#include "../include/PlayerBody.h"
#include "../include/Lib.h"
namespace gnGame {
namespace {
// プレイヤーのパラメータ
const ActorParameter MaxPlayerParameter{100.0f, 120.0f, 5.0f, 5.0f, 10.0f};
}
// テスト用のコンストラクタ
PlayerBody::PlayerBody()
: PlayerBody({100.0f, 100.f, 10.0f, 10.0f, 10.0f})
{
}
PlayerBody::PlayerBody(ActorParameter _parameter)
: parameter(_parameter)
, invincibleTime(0.0f)
, isDamage(false)
, hp()
, mp()
{
}
void PlayerBody::onUpdate()
{
if (isDamage) {
invincibleTime += Time::deltaTime();
if (invincibleTime >= 1.0f) {
invincibleTime = 0.0f;
isDamage = false;
}
}
hp.onUpdate(0.0f, 0.0f, parameter.hp, 30.0f);
mp.onUpdate(0.0f, 32.0f, parameter.mp, 20.0f);
}
void PlayerBody::setParamater(const ActorParameter& _parameter)
{
parameter = _parameter;
}
ActorParameter& PlayerBody::getParameter()
{
return parameter;
}
void PlayerBody::setHP(float _hp)
{
auto temp = parameter.hp + _hp;
parameter.hp = clamp(temp, 0.0f, 100.0f);
}
void PlayerBody::setMP(float _mp)
{
parameter.mp = _mp;
}
void PlayerBody::setAttack(float _power)
{
parameter.attack = _power;
}
void PlayerBody::setDefence(float _defens)
{
parameter.defence = _defens;
}
void PlayerBody::setSpeed(float _speed)
{
parameter.speed = _speed;
}
void PlayerBody::damage(float _damage)
{
if (isDamage) {
return;
}
parameter.hp -= _damage;
parameter.hp = clamp(parameter.hp, 0.f, 100.0f);
isDamage = true;
}
void PlayerBody::subMp(float _mp)
{
parameter.mp -= _mp;
parameter.mp = clamp(parameter.mp, 0.f, 100.0f);
}
}
|
#include<iostream>
#include<cstdio>
#define getint(n) scanf("%d",&n)
#define getd(a) scanf("%lf",&a)
using namespace std;
struct object {
int m;
double r;
int c;
}arr[100];
int main() {
int t,n,m,c,u,index = 0;;
double d,r,best;
getint(t);
while(t--) {
getd(d);
getint(u);
getint(n);
index = 0;
for(int i = 0; i < n; i++) {
getint(arr[i].m);
getd(arr[i].r);
getint(arr[i].c);
}
best = d*u;
for(int i = 0; i < n; i++) {
if(arr[i].r * u + arr[i].c/(arr[i].m * 1.0) < best) {
best = (arr[i].r * u + arr[i].c/(arr[i].m * 1.0));
index = i + 1;
}
}
printf("%d\n",index);
}
return 0;
}
|
// subsurf - main program for Subdivision Surface editor
//
// Zoran Popovic, Mar 1996 first incarnation as GerbilPole test prog.
// Paul Heckbert, Feb 1998 modified for 15-463 assignment P2 "surfed"
// Andrew Bernard, Feb 1999 modified for 15-463 assignment P2 "cellview"
// Paul Heckbert, Mar 1999 modified for 15-463 assignment P3 "subsurf"
// sections that you'll need to modify are marked by "//HINT:"
#ifndef SUBSURF_H
#define SUBSURF_H
class Vertex;
class Face;
class Cell;
Vertex *control_point_pick( Cell *, View *, int mx, int my);
void sphere(double r, double g, double b, Vec3& cen, double radius);
void drawFaceFilled(Face *face);
void drawFilled(Cell *cell);
void drawFaceWireframe(Face *face);
void drawWireframe(Cell *cell);
#endif
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowTitle("Compute");
this->pgen = new ProblemGenerator();
this->p = this->pgen->nextProblem();
this->updateDisplay();
this->updateButtons();
}
MainWindow::~MainWindow()
{
delete ui;
delete this->p;
delete this->pgen;
}
void MainWindow::updateDisplay(void)
{
ui->label->setText(QString::number(this->p->getCurrentMovs()));
ui->label_4->setText(QString::number(this->p->getGoal()));
if(this->p->isSolved())
ui->label_5->setText("SOLVED");
else
ui->label_5->setText(QString::number(this->p->getCurrentValue()));
}
void MainWindow::updateButtons(void)
{
setButton(ui->pushButton, 0);
setButton(ui->pushButton_2, 1);
setButton(ui->pushButton_3, 2);
setButton(ui->pushButton_4, 3);
setButton(ui->pushButton_5, 4);
setButton(ui->pushButton_6, 5);
setButton(ui->pushButton_7, 6);
setButton(ui->pushButton_8, 7);
setButton(ui->pushButton_9, 8);
}
void MainWindow::setButton(QPushButton* button, size_t idx)
{
const Operation* op = this->p->getOperation(idx);
if(op == nullptr)
{
button->setDisabled(true);
button->setText(" ");
}
else
{
button->setDisabled(false);
button->setText(op->toQString());
}
}
void MainWindow::triggerOperation(size_t op_idx)
{
this->p->input(this->p->getOperation(op_idx));
this->updateDisplay();
}
void MainWindow::on_pushButton_released()
{
triggerOperation(0);
}
void MainWindow::on_pushButton_4_released()
{
triggerOperation(3);
}
void MainWindow::on_pushButton_2_released()
{
triggerOperation(1);
}
void MainWindow::on_pushButton_3_released()
{
triggerOperation(2);
}
void MainWindow::on_pushButton_5_released()
{
triggerOperation(4);
}
void MainWindow::on_pushButton_6_released()
{
triggerOperation(5);
}
void MainWindow::on_pushButton_7_released()
{
triggerOperation(6);
}
void MainWindow::on_pushButton_8_released()
{
triggerOperation(7);
}
void MainWindow::on_pushButton_9_released()
{
triggerOperation(8);
}
void MainWindow::on_pushButton_10_released()
{
delete this->p;
this->p = this->pgen->nextProblem();
this->updateDisplay();
this->updateButtons();
}
void MainWindow::on_pushButton_11_released()
{
this->p->reset();
this->updateDisplay();
}
|
// Copyright (c) 2012-2017 The Cryptonote developers
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <vector>
#include <unordered_map>
#include "CryptoNoteCore/Account.h"
#include "CryptoNoteCore/CryptoNoteBasic.h"
#include "CryptoNoteCore/Currency.h"
#include "CryptoNoteCore/BlockchainIndices.h"
#include "crypto/hash.h"
#include "../TestGenerator/TestGenerator.h"
class TestBlockchainGenerator
{
public:
TestBlockchainGenerator(const cn::Currency& currency);
//TODO: get rid of this method
std::vector<cn::Block>& getBlockchain();
std::vector<cn::Block> getBlockchainCopy();
void generateEmptyBlocks(size_t count);
bool getBlockRewardForAddress(const cn::AccountPublicAddress& address);
bool generateTransactionsInOneBlock(const cn::AccountPublicAddress& address, size_t n);
bool getSingleOutputTransaction(const cn::AccountPublicAddress& address, uint64_t amount);
void addTxToBlockchain(const cn::Transaction& transaction);
bool getTransactionByHash(const crypto::Hash& hash, cn::Transaction& tx, bool checkTxPool = false);
const cn::AccountBase& getMinerAccount() const;
bool generateFromBaseTx(const cn::AccountBase& address);
void putTxToPool(const cn::Transaction& tx);
void getPoolSymmetricDifference(std::vector<crypto::Hash>&& known_pool_tx_ids, crypto::Hash known_block_id, bool& is_bc_actual,
std::vector<cn::Transaction>& new_txs, std::vector<crypto::Hash>& deleted_tx_ids);
void putTxPoolToBlockchain();
void clearTxPool();
void cutBlockchain(uint32_t height);
bool addOrphan(const crypto::Hash& hash, uint32_t height);
bool getGeneratedTransactionsNumber(uint32_t height, uint64_t& generatedTransactions);
bool getOrphanBlockIdsByHeight(uint32_t height, std::vector<crypto::Hash>& blockHashes);
bool getBlockIdsByTimestamp(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t blocksNumberLimit, std::vector<crypto::Hash>& hashes, uint32_t& blocksNumberWithinTimestamps);
bool getPoolTransactionIdsByTimestamp(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t transactionsNumberLimit, std::vector<crypto::Hash>& hashes, uint64_t& transactionsNumberWithinTimestamps);
bool getTransactionIdsByPaymentId(const crypto::Hash& paymentId, std::vector<crypto::Hash>& transactionHashes);
uint32_t getCurrentHeight() const { return static_cast<uint32_t>(m_blockchain.size()) - 1; }
bool getTransactionGlobalIndexesByHash(const crypto::Hash& transactionHash, std::vector<uint32_t>& globalIndexes);
bool getMultisignatureOutputByGlobalIndex(uint64_t amount, uint32_t globalIndex, cn::MultisignatureOutput& out);
void setMinerAccount(const cn::AccountBase& account);
private:
struct MultisignatureOutEntry {
crypto::Hash transactionHash;
uint16_t indexOut;
};
struct KeyOutEntry {
crypto::Hash transactionHash;
uint16_t indexOut;
};
void addGenesisBlock();
void addMiningBlock();
const cn::Currency& m_currency;
test_generator generator;
cn::AccountBase miner_acc;
std::vector<cn::Block> m_blockchain;
std::unordered_map<crypto::Hash, cn::Transaction> m_txs;
std::unordered_map<crypto::Hash, std::vector<uint32_t>> transactionGlobalOuts;
std::unordered_map<uint64_t, std::vector<MultisignatureOutEntry>> multisignatureOutsIndex;
std::unordered_map<uint64_t, std::vector<KeyOutEntry>> keyOutsIndex;
std::unordered_map<crypto::Hash, cn::Transaction> m_txPool;
mutable std::mutex m_mutex;
cn::PaymentIdIndex m_paymentIdIndex;
cn::TimestampTransactionsIndex m_timestampIndex;
cn::GeneratedTransactionsIndex m_generatedTransactionsIndex;
cn::OrphanBlocksIndex m_orthanBlocksIndex;
void addToBlockchain(const cn::Transaction& tx);
void addToBlockchain(const std::vector<cn::Transaction>& txs);
void addToBlockchain(const std::vector<cn::Transaction>& txs, const cn::AccountBase& minerAddress);
void addTx(const cn::Transaction& tx);
bool doGenerateTransactionsInOneBlock(cn::AccountPublicAddress const &address, size_t n);
};
|
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
class BlackAndWhiteSolitaire {
public:
int minimumTurns(string cardFront)
{
int bcnt = 0;
char f = 'B';
for (int i=1; i<cardFront.size(); i+=2) {
if (f == cardFront.at(i)) {
++bcnt;
}
}
for (int i=0; i<cardFront.size(); i+=2) {
if (f != cardFront.at(i)) {
++bcnt;
}
}
int wcnt = 0;
f = 'W';
for (int i=1; i<cardFront.size(); i+=2) {
if (f == cardFront.at(i)) {
++wcnt;
}
}
for (int i=0; i<cardFront.size(); i+=2) {
if (f != cardFront.at(i)) {
++wcnt;
}
}
int cnt = min(wcnt,bcnt);
return cnt;
}
};
|
#ifndef __CHSSHA1_H__
#define __CHSSHA1_H__
#include "CHSSHABASE.h"
class CHSSHA1 : public CHSSHABASE
{
private:
static const unsigned __int32 DefaultMessageDijest[5];
unsigned __int32 MessageDijest[5];
unsigned __int32 Rotate(unsigned __int32,int);
unsigned __int32 GetConstData(int);
unsigned __int32 LogicalExp(int , unsigned __int32,unsigned __int32,unsigned __int32);
void HashBlock(void);
public:
CHSSHA1();
};
#endif // !__CHSSHA1_H__
|
#include "DPolygon.h"
// **************** Constructor ***************************
DPolygon::DPolygon():
open(false)
{
}
// **************** set ***********************************
/*
void DPolygon::set(ClipInfo& clip, SDL_Point& _pos)
{
SDL_Rect rect = clip.clip;
pos = _pos;
focus = clip.focus;
originalPoints.clear();
originalPoints.reserve(4);
originalPoints.emplace_back(SDL_Point{pos.x, pos.y});
originalPoints.emplace_back(SDL_Point{pos.x + rect.w, pos.y});
originalPoints.emplace_back(SDL_Point{pos.x + rect.w, pos.y + rect.h});
originalPoints.emplace_back(SDL_Point{pos.x, pos.y + rect.h});
reset();
}
*/
// **************** reset *********************************
void DPolygon::reset()
{
rotatedPoints = originalPoints;
enclosePoints();
}
// **************** addPoint ******************************
void DPolygon::addPoint(int x, int y)
{
SDL_Point point = { x, y };
addPoint(SDL_Point(point));
}
void DPolygon::addPoint(SDL_Point point)
{
originalPoints.push_back(point);
reset();
enclosePoints();
}
// **************** translate *****************************
void DPolygon::translate(int x, int y)
{
for (SDL_Point& it: rotatedPoints)
{
it.x += x;
it.y += y;
}
focus.x += x;
focus.y += y;
}
// **************** rotate ********************************
void DPolygon::rotate(float angle)
{
for (auto& it: rotatedPoints) rotate(it, angle);
}
void DPolygon::rotate(SDL_Point& point, float angle)
{
float x = (float) (point.x - focus.x - pos.x);
float y = (float) (point.y - focus.y - pos.y);
point.x = (int) (((x * cos(angle)) - (y * sin(angle)))) + pos.x;
point.y = (int) (((y * cos(angle)) + (x * sin(angle)))) + pos.y;
}
// **************** absoluteAngle *************************
void DPolygon::absoluteAngle(float angle)
{
reset();
rotate(angle);
enclosePoints();
}
// **************** checkBounds ***************************
bool DPolygon::checkBounds(int x, int y)
{
if (x < boundingBox.x) return false;
if (x > boundingBox.x + boundingBox.w) return false;
if (y < boundingBox.y) return false;
if (y > boundingBox.y + boundingBox.h) return false;
return true;
}
// **************** windingNumber *************************
int DPolygon::windingNumber(int x, int y)
{
// Algorithm from http://geomalgorithms.com/a03-_inclusion.html Accessed 20 Feb 2014
SDL_Point mouse = { x, y };
vector<SDL_Point> temp = rotatedPoints;
temp.push_back(rotatedPoints.at(0));
int wind = 0;
int points = rotatedPoints.size();
for(int point = 0; point < points; ++point)
{
if (temp.at(point).y <= mouse.y)
{
if (temp.at(point + 1).y > mouse.y) // Going up
{
if (triangleArea(temp.at(point), temp.at(point + 1), mouse) > 0) ++wind;
}
}
else
{
if (temp.at(point + 1).y <= mouse.y) // Going down
{
if (triangleArea(temp.at(point), temp.at(point + 1), mouse) < 0) --wind;
}
}
}
return wind;
}
// **************** hit ***********************************
bool DPolygon::hit(int x, int y)
{
if (open) return false;
if (rotatedPoints.size() < 3) return false;
if (!checkBounds(x, y)) return false;
DLine line (boundingBox.x - 10, y, x, y);
if (intersections(line) % 2 == 1) return true;
//if (abs(windingNumber(x, y)) % 2 == 1) return true;
return false;
}
// **************** render ********************************
void DPolygon::render(SDL_Renderer* renderer, SDL_Color& color)
{
if (rotatedPoints.empty()) return;
// SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF);
// SDL_RenderDrawRect(renderer, &boundingBox);
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
SDL_RenderDrawLines(renderer, &rotatedPoints[0], rotatedPoints.size());
if (!open) SDL_RenderDrawLine(renderer, rotatedPoints.front().x, rotatedPoints.front().y, rotatedPoints.back().x, rotatedPoints.back().y);
}
// **************** triangleArea **************************
float DPolygon::triangleArea(SDL_Point& p0, SDL_Point& p1, SDL_Point& p2)
{
/*
Algorithm from http://geomalgorithms.com/a01-_area.html Accessed 20 Feb 2014
< 0 area for clockwise points
= 0 area for colinear points
> 0 area for counterclockwise points
if p1.y > p0.y positive results mean p2 lies to the right, negative to the left
if p1.y < p0.y positive results mean p2 lies to the left, negative to the right
*/
return 0.5 * ((float) (((p1.x - p0.x) * (p2.y - p0.y)) - ((p2.x - p0.x) * (p1.y - p0.y))));
}
unsigned int DPolygon::intersections(DLine& line, DPoint* clipPoint)
{
unsigned int cross = 0;
size_t points = rotatedPoints.size();
for (size_t i = 0; i < points - 1; ++i)
{
DLine polyEdge(rotatedPoints[i], rotatedPoints[i + 1]);
if (line.intersect(polyEdge, clipPoint)) ++cross;
}
if (!open)
{
DLine polyEdge(rotatedPoints.back(), rotatedPoints.front());
if (line.intersect(polyEdge, clipPoint)) ++cross;
}
return cross;
}
bool DPolygon::clip(DPolygon& poly)
{
size_t points = rotatedPoints.size();
for (size_t i = 0; i < points - 1; ++i)
{
DLine polyEdge(rotatedPoints[i], rotatedPoints[i + 1]);
if (poly.intersections(polyEdge) > 0) return true;
}
if (!open)
{
DLine polyEdge(rotatedPoints.back(), rotatedPoints.front());
if (poly.intersections(polyEdge) > 0) return true;
}
return false;
}
|
#pragma once
#include "ChangeMesh.h"
#include "Vertex.h"
#include <vector>
using std::vector;
struct Apples
{
typedef enum ApplesStates
{
SPAWNING,
SPAWNED,
ROTTING,
DECAYED,
};
ApplesStates appleStates;
ChangeMesh *appleMesh;
Vector3 position;
float timer;
bool spawned;
Vector3 newPosition;
float despawn;
int probability;
int randomProb;
float probabilityCountDown;
bool notRotted = false;
};
class AppleSpawning
{
public:
vector<Apples> GetAppleVec();
vector<Vertex>GetTreeVec();
void Init(int probability);
void InitApples(int probability);
void InitTrees();
void RespawnApples();
void GetAppleState();
void UpdateApplesFSM(double dt);
void SetAppleDespawn(int despawn, int appleid);
AppleSpawning();
virtual ~AppleSpawning();
int countRot = 0;
int countNoRot = 0;
private:
vector<Apples>appleVec;
vector<Vertex>treeVec;
Vertex trees;
Apples apples;
bool addCount = false;
};
|
// SamplesS.h : main header file for the SAMPLESS application
//
#if !defined(AFX_SAMPLESS_H__F1F04740_CD06_456F_A97C_BA992D125C6C__INCLUDED_)
#define AFX_SAMPLESS_H__F1F04740_CD06_456F_A97C_BA992D125C6C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CSamplesSApp:
// See SamplesS.cpp for the implementation of this class
//
class CSamplesSApp : public CWinApp
{
public:
CSamplesSApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSamplesSApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CSamplesSApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SAMPLESS_H__F1F04740_CD06_456F_A97C_BA992D125C6C__INCLUDED_)
|
#include <iostream>
#include <cstring>
#define endl "\n"
#define MAX 30 + 1
using namespace std;
int N, M;
int dp[MAX][MAX];
void Initialize()
{
memset(dp, 0, sizeof(dp));
}
void Input() {
//scanf("%d %d", &n, &m);
cin>>N>>M;
}
// Solution int -> void 로 했더니 runtime error 해결됨ㅠㅠ
void Solution() {
for(int i=1; i<=M; i++)
{
dp[1][i] = i;
}
for (int i = 2; i <= N; i++)
{
for (int j = i; j <= M; j++)
{
for (int k = j; k >= i; k--)
{
dp[i][j]= dp[i][j] + dp[i-1][k-1];
}
}
}
//printf("%d\n",d[n][m]);
cout<<dp[N][M]<<endl;
}
void Solve(){
int TC;
cin>>TC;
//scanf("%d",&T);
for(int T=1; T<=TC; T++)
{
Initialize();
Input();
Solution();
}
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
Solve();
return 0;
}
|
// ----------------------------------------------------------------------------
// nexus | OpticalMaterialProperties.cc
//
// Optical properties of relevant materials.
//
// The NEXT Collaboration
// ----------------------------------------------------------------------------
#include "OpticalMaterialProperties.h"
#include "LiquidArgonProperties.h"
#include <G4MaterialPropertiesTable.hh>
#include <assert.h>
using namespace CLHEP;
G4MaterialPropertiesTable* OpticalMaterialProperties::OpticalLAr()
{
LiquidArgonProperties LAr_prop;
G4MaterialPropertiesTable* LAr_mpt = new G4MaterialPropertiesTable();
const G4int ri_entries = 200;
G4double eWidth = (optPhotMaxE_ - optPhotMinE_) / ri_entries;
std::vector<G4double> ri_energy;
for (int i=0; i<ri_entries; i++)
{
ri_energy.push_back(optPhotMinE_ + i * eWidth);
}
std::vector<G4double> ri_index;
for (G4int i=0; i<ri_entries; i++)
{
ri_index.push_back(LAr_prop.RefractiveIndex(ri_energy[i]));
}
assert(ri_energy.size() == ri_index.size());
LAr_mpt->AddProperty("RINDEX", ri_energy.data(), ri_index.data(), ri_energy.size());
// Sampling from 128 +- 25 (103 nm --> 153 nm) [12.04 eV --> 8.104 eV]
const G4int sc_entries = 500;
eWidth = (12.04*eV - 8.104*eV) / sc_entries;
std::vector<G4double> sc_energy;
for (int j=0; j<sc_entries; j++)
{
sc_energy.push_back(8.104*eV + j * eWidth);
}
std::vector<G4double> intensity;
LAr_prop.Scintillation(sc_energy, intensity);
assert(sc_energy.size() == intensity.size());
LAr_mpt->AddProperty("FASTCOMPONENT", sc_energy.data(), intensity.data(), sc_energy.size());
LAr_mpt->AddProperty("SLOWCOMPONENT", sc_energy.data(), intensity.data(), sc_energy.size());
// LAr_mpt->AddConstProperty("SCINTILLATIONYIELD", 51282.1/MeV);
LAr_mpt->AddConstProperty("SCINTILLATIONYIELD", 2./MeV);
LAr_mpt->AddConstProperty("RESOLUTIONSCALE", 1);
LAr_mpt->AddConstProperty("RAYLEIGH", 95.*cm);
LAr_mpt->AddConstProperty("FASTTIMECONSTANT", 6.*ns);
LAr_mpt->AddConstProperty("SLOWTIMECONSTANT", 1590.*ns);
// LAr_mpt->AddConstProperty("IONIZATIONENERGY", 42372.9/MeV);
// LAr_mpt->AddConstProperty("FANOFACTOR", 0.107);
// for (int i=0; i<100; ++i){G4cout << "MAT" <<"\t"<< LAr_mpt->GetConstProperty("IONIZATIONENERGY") << G4endl;}
// Yeild ratio from here
// https://journals.aps.org/prd/pdf/10.1103/PhysRevD.103.043001
LAr_mpt->AddConstProperty("YIELDRATIO", 0.84);
std::vector<G4double> abs_energy = {optPhotMinE_, optPhotMaxE_};
std::vector<G4double> abs_length = {noAbsLength_, noAbsLength_};
assert(abs_energy.size() == abs_length.size());
LAr_mpt->AddProperty("ABSLENGTH", abs_energy.data(), abs_length.data(), abs_energy.size());
return LAr_mpt;
}
/// Fake Grid ///
G4MaterialPropertiesTable* OpticalMaterialProperties::FakeGrid(G4double transparency,
G4double thickness,
G4int sc_yield)
{
G4MaterialPropertiesTable* mpt = new G4MaterialPropertiesTable();
// PROPERTIES FROM Liquid Argon
G4MaterialPropertiesTable* LAr_pt = OpticalLAr();
mpt->AddProperty("RINDEX", LAr_pt->GetProperty("RINDEX"));
mpt->AddProperty("FASTCOMPONENT", LAr_pt->GetProperty("FASTCOMPONENT"));
mpt->AddProperty("SLOWCOMPONENT", LAr_pt->GetProperty("SLOWCOMPONENT"));
mpt->AddConstProperty("SCINTILLATIONYIELD", LAr_pt->GetConstProperty("SCINTILLATIONYIELD"));
mpt->AddConstProperty("RESOLUTIONSCALE", LAr_pt->GetConstProperty("RESOLUTIONSCALE"));
mpt->AddConstProperty("FASTTIMECONSTANT", LAr_pt->GetConstProperty("FASTTIMECONSTANT"));
mpt->AddConstProperty("SLOWTIMECONSTANT", LAr_pt->GetConstProperty("SLOWTIMECONSTANT"));
mpt->AddConstProperty("YIELDRATIO", LAr_pt->GetConstProperty("YIELDRATIO"));
mpt->AddConstProperty("ATTACHMENT", LAr_pt->GetConstProperty("ATTACHMENT"));
// ABSORPTION LENGTH
G4double abs_length = -thickness/log(transparency);
G4double abs_energy[] = {optPhotMinE_, optPhotMaxE_};
G4double absLength[] = {abs_length, abs_length};
mpt->AddProperty("ABSLENGTH", abs_energy, absLength, 2);
// PHOTOELECTRIC REEMISSION
// https://aip.scitation.org/doi/10.1063/1.1708797
G4double stainless_wf = 4.3 * eV; // work function
mpt->AddConstProperty("WORK_FUNCTION", stainless_wf);
return mpt;
}
/// PTFE (== TEFLON) ///
G4MaterialPropertiesTable* OpticalMaterialProperties::PTFE()
{
G4MaterialPropertiesTable* mpt = new G4MaterialPropertiesTable();
// REFLECTIVITY
const G4int REFL_NUMENTRIES = 7;
G4double ENERGIES[REFL_NUMENTRIES] = {
optPhotMinE_, 2.8 * eV, 3.5 * eV, 4. * eV,
6. * eV, 7.2 * eV, optPhotMaxE_
};
G4double REFLECTIVITY[REFL_NUMENTRIES] = {
.98, .98, .98, .98,
.72, .72, .72
};
mpt->AddProperty("REFLECTIVITY", ENERGIES, REFLECTIVITY, REFL_NUMENTRIES);
// REFLEXION BEHAVIOR
const G4int NUMENTRIES = 2;
G4double ENERGIES_2[NUMENTRIES] = {optPhotMinE_, optPhotMaxE_};
// Specular reflection about the normal to a microfacet.
// Such a vector is chosen according to a gaussian distribution with
// sigma = SigmaAlhpa (in rad) and centered in the average normal.
G4double specularlobe[NUMENTRIES] = {0., 0.};
// specular reflection about the average normal
G4double specularspike[NUMENTRIES] = {0., 0.};
// 180 degrees reflection.
G4double backscatter[NUMENTRIES] = {0., 0.};
// 1 - the sum of these three last parameters is the percentage of Lambertian reflection
mpt->AddProperty("SPECULARLOBECONSTANT", ENERGIES_2, specularlobe, NUMENTRIES);
mpt->AddProperty("SPECULARSPIKECONSTANT",ENERGIES_2, specularspike, NUMENTRIES);
mpt->AddProperty("BACKSCATTERCONSTANT", ENERGIES_2, backscatter, NUMENTRIES);
// REFRACTIVE INDEX
G4double rIndex[] = {1.41, 1.41};
mpt->AddProperty("RINDEX", ENERGIES_2, rIndex, NUMENTRIES);
return mpt;
}
/// TPB (tetraphenyl butadiene) ///
G4MaterialPropertiesTable* OpticalMaterialProperties::TPB()
{
// Data from https://doi.org/10.1140/epjc/s10052-018-5807-z
G4MaterialPropertiesTable* mpt = new G4MaterialPropertiesTable();
// REFRACTIVE INDEX
const G4int rIndex_numEntries = 2;
G4double rIndex_energies[rIndex_numEntries] = {optPhotMinE_, optPhotMaxE_};
G4double TPB_rIndex[rIndex_numEntries] = {1.67 , 1.67};
mpt->AddProperty("RINDEX", rIndex_energies,
TPB_rIndex, rIndex_numEntries);
// ABSORPTION LENGTH
// Assuming no absorption except WLS
G4double abs_energy[] = {optPhotMinE_, optPhotMaxE_};
G4double absLength[] = {noAbsLength_, noAbsLength_};
mpt->AddProperty("ABSLENGTH", abs_energy, absLength, 2);
// WLS ABSORPTION LENGTH (Version NoSecWLS)
// The NoSecWLS is forced by setting the WLS_absLength to noAbsLength_
// for wavelengths higher than 380 nm where the WLS emission spectrum starts.
G4double WLS_abs_energy[] = {
optPhotMinE_,
h_Planck * c_light / (380. * nm), h_Planck * c_light / (370. * nm),
h_Planck * c_light / (360. * nm), h_Planck * c_light / (330. * nm),
h_Planck * c_light / (320. * nm), h_Planck * c_light / (310. * nm),
h_Planck * c_light / (300. * nm), h_Planck * c_light / (270. * nm),
h_Planck * c_light / (250. * nm), h_Planck * c_light / (230. * nm),
h_Planck * c_light / (210. * nm), h_Planck * c_light / (190. * nm),
h_Planck * c_light / (170. * nm), h_Planck * c_light / (150. * nm),
h_Planck * c_light / (100. * nm), optPhotMaxE_
};
const G4int WLS_abs_entries = sizeof(WLS_abs_energy) / sizeof(G4double);
G4double WLS_absLength[] = {
noAbsLength_,
noAbsLength_, 50. * nm, // 380 , 370 nm
30. * nm, 30. * nm, // 360 , 330 nm
50. * nm, 80. * nm, // 320 , 310 nm
100. * nm, 100. * nm, // 300 , 270 nm
400. * nm, 400. * nm, // 250 , 230 nm
350. * nm, 250. * nm, // 210 , 190 nm
350. * nm, 400. * nm, // 170 , 150 nm
400. * nm, noAbsLength_ // 100 nm
};
//for (int i=0; i<WLS_abs_entries; i++)
// G4cout << "* TPB WLS absLength: " << std::setw(8) << WLS_abs_energy[i] / eV
// << " eV == " << std::setw(8) << (h_Planck * c_light / WLS_abs_energy[i]) / nm
// << " nm -> " << std::setw(6) << WLS_absLength[i] / nm << " nm" << G4endl;
assert(sizeof(WLS_absLength) == sizeof(WLS_abs_energy));
mpt->AddProperty("WLSABSLENGTH", WLS_abs_energy,
WLS_absLength, WLS_abs_entries);
// WLS EMISSION SPECTRUM
// Implemented with formula (7), with parameter values in table (3)
// Sampling from ~380 nm to 600 nm <--> from 2.06 to 3.26 eV
const G4int WLS_emi_entries = 120;
G4double WLS_emi_energy[WLS_emi_entries];
for (int i=0; i<WLS_emi_entries; i++)
WLS_emi_energy[i] = 2.06 * eV + 0.01 * i * eV;
G4double WLS_emiSpectrum[WLS_emi_entries];
G4double A = 0.782;
G4double alpha = 3.7e-2;
G4double sigma1 = 15.43;
G4double mu1 = 418.10;
G4double sigma2 = 9.72;
G4double mu2 = 411.2;
for (int i=0; i<WLS_emi_entries; i++) {
G4double wl = (h_Planck * c_light / WLS_emi_energy[i]) / nm;
WLS_emiSpectrum[i] = A * (alpha/2.) * exp((alpha/2.) *
(2*mu1 + alpha*pow(sigma1,2) - 2*wl)) *
erfc((mu1 + alpha*pow(sigma1,2) - wl) / (sqrt(2)*sigma1)) +
(1-A) * (1 / sqrt(2*pow(sigma2,2)*3.1416)) *
exp((-pow(wl-mu2,2)) / (2*pow(sigma2,2)));
// G4cout << "* TPB WLSemi: " << std::setw(4)
// << wl << " nm -> " << WLS_emiSpectrum[i] << G4endl;
};
assert(sizeof(WLS_emiSpectrum) == sizeof(WLS_emi_energy));
mpt->AddProperty("WLSCOMPONENT", WLS_emi_energy,
WLS_emiSpectrum, WLS_emi_entries);
// WLS Delay
mpt->AddConstProperty("WLSTIMECONSTANT", 1.2 * ns);
// WLS Quantum Efficiency
// According to the paper, the QE of TPB depends on the incident wavelength.
// As Geant4 doesn't allow this possibility, it is set to the value corresponding
// to Xe scintillation spectrum peak.
mpt->AddConstProperty("WLSMEANNUMBERPHOTONS", 0.65);
return mpt;
}
|
#include "BluetoothSerial.h"
#include <M5Core2.h>
#include "Spark.h"
#include "SparkIO.h"
#include "SparkComms.h"
SparkIO spark_io(false); // do NOT do passthru as only one device here, no serial to the app
SparkComms spark_comms;
unsigned int cmdsub;
SparkMessage msg;
SparkPreset preset;
SparkPreset presets[6];
unsigned long last_millis;
int my_state;
int scr_line;
char str[50];
SparkPreset preset0{0x0,0x7f,
"07079063-94A9-41B1-AB1D-02CBC5D00790","Silver Ship","0.7","1-Clean","icon.png",120.000000,{
{"bias.noisegate", false, 3, {0.138313, 0.224643, 0.000000}},
{"LA2AComp", true, 3, {0.000000, 0.852394, 0.373072}},
{"Booster", false, 1, {0.722592}},
{"RolandJC120", true, 5, {0.632231, 0.281820, 0.158359, 0.671320, 0.805785}},
{"Cloner", true, 2, {0.199593, 0.000000}},
{"VintageDelay", false, 4, {0.378739, 0.425745, 0.419816, 1.000000}},
{"bias.reverb", true, 7, {0.285714, 0.408354, 0.289489, 0.388317, 0.582143, 0.650000, 0.200000}} },
0xb4 };
SparkPreset preset1{0x01,0x01,
"07079063-94A9-41B1-AB1D-02CBC5D00790","Wilver Whip","0.7","1-Clean","icon.png",120.000000,{
{"bias.noisegate", false, 3, {0.138313, 0.224643, 0.000000}},
{"LA2AComp", true, 3, {0.000000, 0.852394, 0.373072}},
{"Booster", false, 1, {0.722592}},
{"RolandJC120", true, 5, {0.632231, 0.281820, 0.158359, 0.671320, 0.805785}},
{"Cloner", true, 2, {0.199593, 0.000000}},
{"VintageDelay", false, 4, {0.378739, 0.425745, 0.419816, 1.000000}},
{"bias.reverb", true, 7, {0.285714, 0.408354, 0.289489, 0.388317, 0.582143, 0.650000, 0.200000}} },
0xb4 };
/*
SparkPreset preset1{0x0,0x00,
"97979963-94A9-41B1-AB1D-02CBC5D00790","Sjlver Ship","0.7","1-Clean","icon.png",120.000000,{
{"bias.noisegate", true, 3, {0.138313, 0.224643, 0.000000}},
{"LA2AComp", true, 3, {0.000000, 0.852394, 0.373072}},
{"Booster", true, 1, {0.722592}},
{"RolandJC120", true, 5, {0.632231, 0.281820, 0.158359, 0.671320, 0.805785}},
{"Cloner", true, 2, {0.199593, 0.000000}},
{"VintageDelay", false, 4, {0.378739, 0.425745, 0.419816, 1.000000}},
{"bias.reverb", true, 7, {0.285714, 0.408354, 0.289489, 0.388317, 0.582143, 0.650000, 0.200000}} },
0xb4 };
*/
void printit(char *str) {
if (scr_line >= 8) {
M5.Lcd.fillScreen(TFT_BLACK);
M5.Lcd.setCursor(0, 0);
M5.Lcd.println("Preset Analyser");
M5.Lcd.println();
scr_line = 1;
}
M5.Lcd.println(str);
scr_line++;
}
void dump_preset(SparkPreset preset) {
int i,j;
Serial.print(preset.curr_preset); Serial.print(" ");
Serial.print(preset.preset_num); Serial.print(" ");
Serial.print(preset.Name); Serial.print(" ");
Serial.println(preset.Description);
for (j=0; j<7; j++) {
Serial.print(" ");
Serial.print(preset.effects[j].EffectName); Serial.print(" ");
if (preset.effects[j].OnOff == true) Serial.print(" On "); else Serial.print (" Off ");
for (i = 0; i < preset.effects[j].NumParameters; i++) {
Serial.print(preset.effects[j].Parameters[i]); Serial.print(" ");
}
Serial.println();
}
Serial.println(preset.chksum);
Serial.println();
}
void setup() {
M5.begin();
M5.Lcd.fillScreen(TFT_BLACK);
M5.Lcd.setTextSize(2);
scr_line = 1;
printit("Alive");
Serial.println("Alive");
spark_io.comms = &spark_comms;
spark_comms.start_bt();
spark_comms.connect_to_spark();
printit("Connected");
last_millis = millis();
my_state = 0;
delay(2000);
printit("Starting");
}
void loop() {
spark_io.process();
if (spark_io.get_message(&cmdsub, &msg, &preset)) {
sprintf(str, "< %4.4x", cmdsub);
printit(str);
if (cmdsub == 0x0301) { // got a response to a 0x0201 preset info request
dump_preset(preset);
}
}
if (millis() - last_millis > 1000) {
last_millis = millis();
switch (my_state) {
case 0:
spark_io.change_hardware_preset(0x00);
break;
case 1:
spark_io.create_preset(&preset0);
spark_io.change_hardware_preset(0x7f);
break;
case 2:
spark_io.get_preset_details(0x007f);
break;
case 3:
spark_io.create_preset(&preset1);
spark_io.change_hardware_preset(0x03); // *************
break;
case 4:
Serial.println("007f");
spark_io.get_preset_details(0x0001);
default:
Serial.println (">>>>");
spark_io.get_preset_details(0x0101);
break;
}
my_state++;
}
}
|
/*
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
*/
#include "Core/Log.hpp"
#include "Core/Stream.hpp"
#include "Core/Settings.hpp"
#include <cstdio>
namespace Push
{
bool GetResourceFile(std::ifstream& stream, const Path& name)
{
stream.open(Settings::GetInstance()->GetPath(BundleType::Resource, name).GetPath(), std::ios::binary);
Log(!stream.good(), LogType::Warning, "Stream", "File %s not found!", Settings::GetInstance()->GetPath(BundleType::Resource, name).GetPath());
return stream.good();
}
bool GetResourceFile(std::ofstream& stream, const Path& name)
{
stream.open(Settings::GetInstance()->GetPath(BundleType::Resource, name).GetPath(), std::ios::binary);
Log(!stream.good(), LogType::Warning, "Stream", "File %s not found!", Settings::GetInstance()->GetPath(BundleType::Resource, name).GetPath());
return stream.good();
}
bool GetSettingsFile(std::ifstream& stream, const Path& name)
{
stream.open(Settings::GetInstance()->GetPath(BundleType::Settings, name).GetPath(), std::ios::binary);
Log(!stream.good(), LogType::Warning, "Stream", "File %s not found!", Settings::GetInstance()->GetPath(BundleType::Resource, name).GetPath());
return stream.good();
}
bool GetSettingsFile(std::ofstream& stream, const Path& name)
{
stream.open(Settings::GetInstance()->GetPath(BundleType::Settings, name).GetPath(), std::ios::binary);
Log(!stream.good(), LogType::Warning, "Stream", "File %s not found!", Settings::GetInstance()->GetPath(BundleType::Resource, name).GetPath());
return stream.good();
}
void Read(std::istream& stream, Buffer& buffer)
{
uint32_t size = 0;
stream.read(reinterpret_cast<char*>(&size), sizeof(uint32_t));
char* data = new char[size];
stream.read(data, static_cast<std::streamsize>(size));
buffer = Buffer(reinterpret_cast<uint8_t*>(data), static_cast<size_t>(size));
}
void Write(std::ostream& stream, const Buffer& buffer)
{
std::streamsize size = static_cast<std::streamsize>(buffer.size());
stream.write(reinterpret_cast<char*>(&size), sizeof(uint32_t));
stream.write(reinterpret_cast<const char*>(buffer.begin()), size);
}
static Buffer ReadFile(const Path& fullPath)
{
FILE* file = fopen(fullPath.GetPath(), "rb");
if(file)
{
fseek(file, 0, SEEK_END);
auto size = static_cast<size_t>(ftell(file));
fseek(file, 0, SEEK_SET);
auto data = new uint8_t[size];
fread(data, size, 1, file);
fclose(file);
return Buffer(data, static_cast<size_t>(size));
}
else
{
Log(LogType::Warning, "Stream", "File %s not found!", fullPath.GetPath());
}
return Buffer(nullptr, 0);
}
Buffer ReadResourceFile(const Path& name)
{
return ReadFile(Settings::GetInstance()->GetPath(BundleType::Resource, name));
}
Buffer ReadSettingsFile(const Path& name)
{
return ReadFile(Settings::GetInstance()->GetPath(BundleType::Settings, name));
}
}
|
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
#include "loop.hh"
#include <stdexcept>
#include "net/http_response_parser.hh"
#include "net/protobuf_stream_parser.hh"
#include "thunk/ggutils.hh"
#include "util/exception.hh"
#include "util/optional.hh"
#include "protobufs/gg.pb.h"
using namespace std;
using namespace PollerShortNames;
using ReductionResult = gg::cache::ReductionResult;
ExecutionLoop::ExecutionLoop()
: signals_( { SIGCHLD, SIGCONT, SIGHUP, SIGTERM, SIGQUIT } ),
signal_fd_( signals_ )
{
signals_.set_as_mask();
poller_.add_action(
Poller::Action(
signal_fd_.fd(), Direction::In,
[&]() { return handle_signal( signal_fd_.read_signal() ); },
[&]() { return ( child_processes_.size() > 0 or
connections_.size() > 0 or
ssl_connections_.size() > 0 ); }
)
);
}
Poller::Result ExecutionLoop::loop_once( const int timeout_ms )
{
return poller_.poll( timeout_ms );
}
template<>
typename list<shared_ptr<TCPConnection>>::iterator
ExecutionLoop::create_connection( TCPSocket && socket )
{
return connections_.emplace( connections_.end(),
make_shared<TCPConnection>( move( socket ) ) );
}
template<>
typename list<shared_ptr<SSLConnection>>::iterator
ExecutionLoop::create_connection( NBSecureSocket && socket )
{
return ssl_connections_.emplace( ssl_connections_.end(),
make_shared<SSLConnection>( move( socket ) ) );
}
template<>
void ExecutionLoop::remove_connection<TCPConnection>( const list<shared_ptr<TCPConnection>>::iterator & it )
{
connections_.erase( it );
}
template<>
void ExecutionLoop::remove_connection<SSLConnection>( const list<shared_ptr<SSLConnection>>::iterator & it )
{
ssl_connections_.erase( it );
}
template<>
shared_ptr<TCPConnection>
ExecutionLoop::add_connection( TCPSocket && socket,
const function<bool(shared_ptr<TCPConnection>, string &&)> & data_callback,
const function<void()> & error_callback,
const function<void()> & close_callback )
{
auto connection_it = create_connection<TCPSocket>( move( socket ) );
shared_ptr<TCPConnection> & connection = *connection_it;
auto real_close_callback =
[connection_it, cc=move( close_callback ), this] ()
{
cc();
remove_connection<TCPConnection>( connection_it );
};
auto fderror_callback =
[error_callback, real_close_callback]
{
error_callback();
real_close_callback();
};
poller_.add_action(
Poller::Action(
connection->socket_, Direction::Out,
[connection] ()
{
string::const_iterator last_write =
connection->socket_.write( connection->write_buffer_.begin(),
connection->write_buffer_.cend() );
connection->write_buffer_.erase( 0, last_write - connection->write_buffer_.cbegin() );
return ResultType::Continue;
},
[connection] { return connection->write_buffer_.size(); },
fderror_callback
)
);
poller_.add_action(
Poller::Action(
connection->socket_, Direction::In,
[connection,
data_callback { move( data_callback ) },
close_callback { move( real_close_callback ) }] ()
{
string data { move( connection->socket_.read() ) };
if ( data.empty() or not data_callback( connection, move( data ) ) ) {
close_callback();
return ResultType::CancelAll;
}
return ResultType::Continue;
},
[connection]() { return true; },
fderror_callback
)
);
return *connection_it;
}
template<>
shared_ptr<SSLConnection>
ExecutionLoop::add_connection( NBSecureSocket && socket,
const function<bool(shared_ptr<SSLConnection>, string &&)> & data_callback,
const function<void()> & error_callback,
const function<void()> & close_callback )
{
const auto connection_it = create_connection<NBSecureSocket>( move( socket ) );
shared_ptr<SSLConnection> & connection = *connection_it;
auto real_close_callback =
[connection_it, cc=move( close_callback ), this] ()
{
cc();
remove_connection<SSLConnection>( connection_it );
};
auto fderror_callback =
[error_callback, real_close_callback]
{
error_callback();
real_close_callback();
};
poller_.add_action(
Poller::Action(
connection->socket_, Direction::Out,
[connection] ()
{
connection->socket_.ezwrite( move( connection->write_buffer_ ) );
connection->write_buffer_ = string {};
return ResultType::Continue;
},
[connection] { return connection->write_buffer_.size(); },
fderror_callback
)
);
poller_.add_action(
Poller::Action(
connection->socket_, Direction::In,
[connection,
data_callback=move( data_callback ),
close_callback=move( real_close_callback )] ()
{
string data { move( connection->socket_.ezread() ) };
if ( data.empty() or not data_callback( connection, move( data ) ) ) {
close_callback();
return ResultType::CancelAll;
}
return ResultType::Continue;
},
[connection]() { return true; },
fderror_callback
)
);
return *connection_it;
}
template<>
shared_ptr<TCPConnection>
ExecutionLoop::make_connection( const Address & address,
const function<bool(shared_ptr<TCPConnection>, string &&)> & data_callback,
const function<void()> & error_callback,
const function<void()> & close_callback )
{
TCPSocket socket;
socket.set_blocking( false );
socket.connect_nonblock( address );
return add_connection<TCPSocket>( move( socket ), data_callback, error_callback, close_callback );
}
template<>
shared_ptr<SSLConnection>
ExecutionLoop::make_connection( const Address & address,
const function<bool(shared_ptr<SSLConnection>, string &&)> & data_callback,
const function<void()> & error_callback,
const function<void()> & close_callback )
{
TCPSocket socket;
socket.set_blocking( false );
socket.connect_nonblock( address );
NBSecureSocket secure_socket { move( ssl_context_.new_secure_socket( move( socket ) ) ) };
secure_socket.connect();
return add_connection<NBSecureSocket>( move( secure_socket ), data_callback, error_callback, close_callback );
}
template<class ConnectionType>
uint64_t ExecutionLoop::make_http_request( const string & tag,
const Address & address,
const HTTPRequest & request,
HTTPResponseCallbackFunc response_callback,
FailureCallbackFunc failure_callback )
{
const uint64_t connection_id = current_id_++;
auto parser = make_shared<HTTPResponseParser>();
parser->new_request_arrived( request );
auto data_callback =
[parser, connection_id, tag, response_callback] ( shared_ptr<ConnectionType>, string && data ) {
parser->parse( data );
if ( not parser->empty() ) {
response_callback( connection_id, tag, parser->front() );
parser->pop();
return false;
}
return true;
};
auto error_callback =
[connection_id, tag, failure_callback]
{ failure_callback( connection_id, tag ); };
auto close_callback = [] {};
auto connection = make_connection<ConnectionType>( address, data_callback, error_callback, close_callback );
connection->write_buffer_ = move( request.str() );
return connection_id;
}
template<class ConnectionType, class RequestType, class ResponseType>
uint64_t ExecutionLoop::make_protobuf_request( const std::string & tag,
const Address & address,
const RequestType & request,
ProtobufResponseCallbackFunc<ResponseType>
response_callback,
FailureCallbackFunc failure_callback )
{
static_assert(is_base_of<google::protobuf::Message, RequestType>::value,
"Request not a protobuf type");
static_assert(is_base_of<google::protobuf::Message, ResponseType>::value,
"Response not a protobuf type");
const uint64_t connection_id = current_id_++;
auto parser = make_shared<ProtobufStreamParser<gg::protobuf::ExecutionResponse>>();
auto data_callback =
[parser, connection_id, tag, response_callback] (shared_ptr<ConnectionType>, string && data) {
parser->parse(data);
if (not parser->empty()) {
response_callback(connection_id, tag, parser->front());
parser->pop();
return false;
}
return true;
};
auto error_callback =
[connection_id, tag, failure_callback]
{ failure_callback(connection_id, tag); };
auto close_callback = [] {};
auto connection = make_connection<ConnectionType>( address, data_callback, error_callback, close_callback );
string serialized_request(sizeof(size_t), 0);
*((size_t*) &serialized_request[0]) = request.ByteSize();
serialized_request.append(request.SerializeAsString());
connection->write_buffer_ = move(serialized_request);
return connection_id;
}
uint64_t ExecutionLoop::make_listener( const Address & address,
const function<bool(ExecutionLoop &,
TCPSocket &&)> & connection_callback )
{
TCPSocket socket;
socket.set_blocking( false );
socket.set_reuseaddr();
socket.bind( address );
socket.listen();
auto connection_it = create_connection<TCPSocket>( move( socket ) );
shared_ptr<TCPConnection> & connection_ptr = *connection_it;
poller_.add_action( Poller::Action( (*connection_it)->socket_,
Direction::In,
[connection_ptr, connection_it, connection_callback, this] () -> ResultType
{
if ( not connection_callback( *this, move( connection_ptr->socket_.accept() ) ) ) {
remove_connection<TCPConnection>( connection_it );
return ResultType::CancelAll;
}
return ResultType::Continue;
} ) );
return current_id_++;
}
uint64_t ExecutionLoop::add_child_process( const string & tag,
LocalCallbackFunc callback,
function<int()> && child_procedure,
const bool throw_if_failed )
{
child_processes_.emplace_back( current_id_, throw_if_failed, callback,
ChildProcess( tag, move( child_procedure ) ) );
return current_id_++;
}
Poller::Action::Result ExecutionLoop::handle_signal( const signalfd_siginfo & sig )
{
switch ( sig.ssi_signo ) {
case SIGCONT:
for ( auto & child : child_processes_ ) {
get<3>( child ).resume();
}
break;
case SIGCHLD:
if ( child_processes_.empty() ) {
throw runtime_error( "received SIGCHLD without any managed children" );
}
for ( auto it = child_processes_.begin(); it != child_processes_.end(); it++ ) {
ChildProcess & child = get<3>( *it );
if ( child.terminated() or ( not child.waitable() ) ) {
continue;
}
child.wait( true );
if ( child.terminated() ) {
if ( get<1>( *it ) and child.exit_status() != 0 ) {
child.throw_exception();
}
auto & callback = get<2>( *it );
callback( get<0>( *it ), child.name(), child.exit_status() );
it = child_processes_.erase( it );
it--;
}
else if ( not child.running() ) {
/* suspend parent too */
CheckSystemCall( "raise", raise( SIGSTOP ) );
}
}
break;
case SIGHUP:
case SIGTERM:
case SIGQUIT:
throw runtime_error( "interrupted by signal" );
default:
throw runtime_error( "unknown signal" );
}
return ResultType::Continue;
}
template
uint64_t ExecutionLoop::make_http_request<TCPConnection>( const string &,
const Address &,
const HTTPRequest &,
HTTPResponseCallbackFunc,
FailureCallbackFunc );
template
uint64_t ExecutionLoop::make_http_request<SSLConnection>( const string &,
const Address &,
const HTTPRequest &,
HTTPResponseCallbackFunc,
FailureCallbackFunc );
template
uint64_t ExecutionLoop::make_protobuf_request<TCPConnection>( const string &,
const Address &,
const gg::protobuf::ExecutionRequest &,
ProtobufResponseCallbackFunc<gg::protobuf::ExecutionResponse>,
FailureCallbackFunc );
|
/**
* created: 2013-4-9 16:51
* filename: FKDBSvrWorkThread
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#include "FKDBSvr.h"
//------------------------------------------------------------------------
unsigned int __stdcall DBService::SimpleMsgProcessThread(CLD_ThreadBase* pthread,void* param){
GETCURREIP(pcurraddr);
THREAD_REGDEBUGINFO(thdebuginfo,pcurraddr,"SimpleMsgProcessThread",60);
while(!pthread->IsTerminated()){
DWORD startruntick=GetTickCount();
thdebuginfo.debuginfo()->thisRunBeginTime=time(NULL);
do{
CLoginSvrDBConnecter* pqpsocket = NULL;
AILOCKT(m_loginsvrconnter);
CSyncSet< CLoginSvrDBConnecter* >::iterator it,itnext;
for (it=m_loginsvrconnter.begin(),itnext=it;it!=m_loginsvrconnter.end();it=itnext){
itnext++;
pqpsocket=(*it);
if (!pqpsocket->isTerminate() && pqpsocket->IsConnected()){
pqpsocket->run();
}
}
} while (false);
do {
if (m_checknamesvrconnecter){ m_checknamesvrconnecter->run(); }
if (m_logsvrconnecter){ m_logsvrconnecter->run(); }
}while(false);
thdebuginfo.debuginfo()->thisRunBeginTime=0;
Sleep(safe_min((DWORD)50,(DWORD)(50-(GetTickCount()-startruntick))));
}
thdebuginfo.debuginfo()->thisRunBeginTime=0;
return 0;
}
//------------------------------------------------------------------------
unsigned int __stdcall DBService::LogicProcessThread(CLD_ThreadBase* pthread,void* param){
GETCURREIP(pcurraddr);
THREAD_REGDEBUGINFO(thdebuginfo,pcurraddr,"LogicProcessThread",60);
while(!pthread->IsTerminated()){
DWORD startruntick=GetTickCount();
thdebuginfo.debuginfo()->thisRunBeginTime=time(NULL);
do{
CGameSvrSession* pUserSession = NULL;
AILOCKT(m_gamesvrsession);
CSyncSet< CGameSvrSession* >::iterator it,itnext;
for (it=m_gamesvrsession.begin(),itnext=it;it!=m_gamesvrsession.end();it=itnext){
itnext++;
pUserSession=((CGameSvrSession*)*it);
if (!pUserSession->isTerminate() && pUserSession->IsConnected()){
pUserSession->run();
}
}
} while (false);
thdebuginfo.debuginfo()->thisRunBeginTime=0;
Sleep(safe_min((DWORD)50,(DWORD)(50-(GetTickCount()-startruntick))));
}
thdebuginfo.debuginfo()->thisRunBeginTime=0;
return 0;
}
//------------------------------------------------------------------------
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <unsupported/Eigen/AlignedVector3>
template<typename Scalar>
void alignedvector3()
{
Scalar s1 = ei_random<Scalar>();
Scalar s2 = ei_random<Scalar>();
typedef Matrix<Scalar,3,1> RefType;
typedef Matrix<Scalar,3,3> Mat33;
typedef AlignedVector3<Scalar> FastType;
RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),
r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());
FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);
Mat33 m1(Mat33::Random());
VERIFY_IS_APPROX(f1,r1);
VERIFY_IS_APPROX(f4,r4);
VERIFY_IS_APPROX(f4+f1,r4+r1);
VERIFY_IS_APPROX(f4-f1,r4-r1);
VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);
VERIFY_IS_APPROX(f4+=f3,r4+=r3);
VERIFY_IS_APPROX(f4-=f5,r4-=r5);
VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);
VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);
VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2);
VERIFY_IS_APPROX(m1*f4,m1*r4);
VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);
VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));
VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));
VERIFY_IS_APPROX(f2.norm(),r2.norm());
VERIFY_IS_APPROX(f2.normalized(),r2.normalized());
VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());
f2.normalize();
r2.normalize();
VERIFY_IS_APPROX(f2,r2);
}
void test_alignedvector3()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( alignedvector3<float>() );
}
}
|
#ifndef _NIHTTPD_HTTP_H
#define _NIHTTPD_HTTP_H 1
#include <nihttpd/socket.h>
#include <map>
#include <vector>
#include <string>
#include <exception>
namespace nihttpd {
typedef std::map<std::string, std::string> key_val_t;
enum http_status_nums {
HTTP_200_OK = 200,
HTTP_400_BAD_REQUEST = 400,
HTTP_403_FORBIDDEN = 403,
HTTP_404_NOT_FOUND = 404,
HTTP_413_ENTITY_TOO_LARGE = 413,
};
class http_request {
public:
// TODO: add another constructor to construct arbitary headers
http_request( connection conn, size_t max_headers = 64 );
void parse_headers( connection &conn, size_t max_headers );
void parse_body( connection &conn, size_t max_size = 0x2000 );
bool valid_post( void );
std::string action;
std::string location;
std::string version;
std::string body;
key_val_t headers;
key_val_t get_params;
key_val_t post_params;
};
class http_response {
public:
void send_to( connection conn );
void send_headers( connection conn );
void send_content( connection conn, const std::vector<char> &vec );
void set_content( std::string &str );
std::vector<char> content;
key_val_t headers;
unsigned status = HTTP_200_OK;
};
class http_error : public std::exception {
public:
http_error( unsigned num ) : std::exception() { error_num = num; };
unsigned error_num;
};
std::string status_string( unsigned status );
std::string url_decode( const std::string &str );
std::string url_encode_path( const std::string &str );
std::string sanitize( const std::string &str );
std::string find_get_fields( const std::string &location );
bool path_below_root( const std::string &str );
size_t get_fields_offset( const std::string &location );
std::string strip_get_fields( const std::string &location );
key_val_t parse_fields( const std::string &args );
}
#endif
|
#pragma once
#include <algorithm>
#include <atomic>
#include <exception>
#include <functional>
#include <future>
#include <iomanip>
#include <iostream>
#include <memory>
#include <shared_mutex>
#include <unordered_map>
#include "IAsyncDictionary.hpp"
#include "tools.hpp"
#define SIZE 26
class AsyncNode
{
public:
AsyncNode();
~AsyncNode();
std::atomic<bool> leaf_ = false;
std::atomic<bool> is_deleted_ = false;
std::atomic<AsyncNode*> children_[SIZE];
};
class AsyncTrie : public IAsyncDictionary
{
public:
AsyncTrie();
template <class Iterator>
AsyncTrie(Iterator begin, Iterator end);
void init(const std::vector<std::string>&) final;
std::future<result_t> search(const std::string&) const final;
std::future<void> insert(const std::string&) final;
std::future<void> erase(const std::string&) final;
int erase_rec(AsyncNode*, const char*);
int have_children(AsyncNode*);
void search_rec(std::string, AsyncNode*, const char, const char, int*, int*,
std::size_t, const std::string&, result_t&) const;
void print(std::string = std::string(""));
void print_rec(std::string, AsyncNode*);
private:
std::unique_ptr<AsyncNode> root;
mutable std::shared_mutex m;
};
template <class Iterator>
AsyncTrie::AsyncTrie(Iterator begin, Iterator end)
: AsyncTrie()
{
for (; begin != end; begin++)
this->insert(*begin).get();
}
|
#define GLEW_STATIC
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#include <stdio.h>
#include "CL/cl.h"
#include "CL/cl_gl.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <GL/glx.h>
#include <iostream>
#include <stdio.h>
#include <vector>
cl_context context;
cl_command_queue queue;
cl_uint num_of_platforms=0;
cl_platform_id platform_id;
cl_device_id device_id;
cl_uint num_of_devices=0;
cl_kernel kernel_image;
cl_mem mem;
size_t global;
GLuint texture;
int bufferSize = 10; //Now it is 10, but this variable will be determined by openCL size data.
int tex_height=10, tex_width=10; //Now it is 0, but this variable will be determined by openCL size data.
#define DATA_SIZE 10
float inputData[DATA_SIZE]={4, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //simulation of the data
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main(){
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Interoperability", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
if (clGetPlatformIDs(1, &platform_id, &num_of_platforms)!= CL_SUCCESS)
{
int a = num_of_platforms;
printf("Number of platforms: %d\n",a);
printf("Unable to get platform_id\n");
return 1;
}
//Additional attributes to OpenCL context creation
// Create CL context properties, add WGL context & handle to DC
cl_context_properties props[] =
{
CL_CONTEXT_PLATFORM, (cl_context_properties)platform_id, //OpenCL platform
CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(), //OpenGL context
CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay() ,0 ////HDC used to create the OpenGL context
};
// try to get a supported GPU device
if (clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_CPU, 1, &device_id, &num_of_devices) != CL_SUCCESS)
{
printf("Unable to get device_id\n");
return 1;
}
//Creating the context and the queue
context = clCreateContext(props,1,&device_id,0,0,NULL);
queue = clCreateCommandQueue(context,device_id,CL_QUEUE_PROFILING_ENABLE,NULL);
// 1.Create 2D texture (OpenGL)
//generate the texture ID
glGenTextures(1, &texture);
//bdinding the texture and setting the
glBindTexture(GL_TEXTURE_2D, texture);
//regular sampler params
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//need to set GL_NEAREST
//(and not GL_NEAREST_MIPMAP_* which results in CL_INVALID_GL_OBJECTlater)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//specify texture dimensions, format etc (tiene tex_width & tex_height, maybe they shouldnt)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
//2.Create the OpenCL image corresponding to the texture
cl_mem mem = clCreateFromGLTexture(context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0,texture,NULL);
//3.Acquire the ownership via clEnqueueAcquireGLObjects
glFinish();
clEnqueueAcquireGLObjects(queue, 1, &mem, 0, 0, NULL);
//4 Execute the OpenCL kernel that alters the image
clSetKernelArg(kernel_image, 0, sizeof(mem), &mem);
//global=DATA_SIZE;
clEnqueueNDRangeKernel(queue, kernel_image, 1, NULL, &global, NULL, 0, NULL, NULL);
//5. Releasing the ownership via clEnqueueReleaseGLObjects
clFinish(queue);
clEnqueueReleaseGLObjects(queue, 1, &mem, 0, 0, NULL);
}
|
#include <iostream>
using namespace std;
void selectionSort(int arr[])
{
for (int i = 0; i < 5 - 1; i++)
{
int min = i;
for (int j = i + 1; j < 5; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
if (min != i)
{
int temp;
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
int main()
{
int myArray[5];
cout << "Enter the 5 Elements" << endl;
for (int i = 0; i < 5; i++)
{
cin >> myArray[i];
}
cout << "Before Sorting" << endl;
for (int j = 0; j < 5; j++)
{
cout << myArray[j] << " ";
}
selectionSort(myArray);
cout << endl;
cout << "After Sorting Sorting" << endl;
for (int j = 0; j < 5; j++)
{
cout << myArray[j] << " ";
}
return 0;
}
|
/******************************************************************************
* Given a positive integer n, generate a square matrix filled with elements
* from 1 to n2 in spiral order.
******************************************************************************/
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ma(n,vector<int>(n));
int pos=0;
int ele=1;
int len=n;
while(len>0) {
for(int i=pos; i<pos+len; i++)
{ ma[pos][i]=ele++; }
if(ele>n*n)
{ break; }
for(int i=pos+1; i<pos+len; i++)
{ ma[i][pos+len-1]=ele++; }
if(ele>n*n)
{ break; }
for(int i=pos+len-2; i>=pos; i--)
{ ma[pos+len-1][i]=ele++; }
if(ele>n*n)
{ break; }
for(int i=pos+len-2; i>pos; i--)
{ ma[i][pos]=ele++; }
if(ele>n*n)
{ break; }
pos++;
len-=2;
}
return ma;
}
|
#define CATCH_CONFIG_MAIN
#include "../external/catch2/catch.hpp"
#include "../src/math/pair_prod.hpp"
#include <unordered_map>
#include <vector>
template <typename T, typename U>
struct TestStruct
{
std::vector<T> num1;
std::vector<U> num2;
std::unordered_map<T, U> actual;
TestStruct(
std::vector<T> num1,
std::vector<U> num2,
std::unordered_map<T, U> actual
) : num1(num1), num2(num2), actual(actual)
{
}
};
TEST_CASE("Pair Prod Test", "[pair_prod]")
{
std::vector<TestStruct<int, char>> testVec {
{
{1, 2},
{'a', 'b'},
{
{1, 'a'},
{1, 'b'},
{2, 'a'},
{2, 'b'}
}
},
{
{1, 2, 3},
{'a', 'b'},
{
{1, 'a'},
{1, 'b'},
{2, 'a'},
{2, 'b'},
{3, 'a'},
{3, 'b'}
}
}
};
for (auto&& var : testVec)
{
REQUIRE(Math::pairProd(var.num1, var.num2) == var.actual);
}
}
|
//
// Copyright (C) BlockWorks Consulting Ltd - All Rights Reserved.
// Unauthorized copying of this file, via any medium is strictly prohibited.
// Proprietary and confidential.
// Written by Steve Tickle <Steve@BlockWorks.co>, September 2014.
//
#ifndef __SCHEDULER_HPP__
#define __SCHEDULER_HPP__
#include <cstdint>
#include <stdio.h>
#include <stdint.h>
extern "C"
{
#include "DebugText.h"
#include "Timestamp.h"
}
typedef uint8_t uint8x8_t[8];
typedef uint64_t uint64x8_t[8];
//
//
//
template < uint32_t iterationDuration,
typename Schedulee1Type,
typename Schedulee2Type,
typename Schedulee3Type,
typename Schedulee4Type,
typename Schedulee5Type,
typename Schedulee6Type,
typename Schedulee7Type,
typename Schedulee8Type
>
class Scheduler
{
public:
Scheduler( Schedulee1Type& _schedulee1,
Schedulee2Type& _schedulee2,
Schedulee3Type& _schedulee3,
Schedulee4Type& _schedulee4,
Schedulee5Type& _schedulee5,
Schedulee6Type& _schedulee6,
Schedulee7Type& _schedulee7,
Schedulee8Type& _schedulee8
) :
schedulee1(_schedulee1),
schedulee2(_schedulee2),
schedulee3(_schedulee3),
schedulee4(_schedulee4),
schedulee5(_schedulee5),
schedulee6(_schedulee6),
schedulee7(_schedulee7),
schedulee8(_schedulee8)
{
}
//
// 8xTimeslots, each 24MHz/8 in duration = 8 channels at 1MHz.
//
void PeriodicProcessing( uint8_t inputValue, uint8_t& outputValue )
{
static uint32_t cycleCount = 0;
uint32_t timestamp = cycleCount;
cycleCount++;
#define PROCESS_SCHEDULEE(bitNumber, s) \
bits[bitNumber] = (inputValue & (1<<bitNumber)) >> bitNumber; \
if( (bits[bitNumber] == 0) && (previousBits[bitNumber] == 1) ) \
{ \
s.ProcessNegativeEdge(); \
} \
if( (bits[bitNumber] == 1) && (previousBits[bitNumber] == 0) ) \
{ \
s.ProcessPositiveEdge(); \
} \
if( (timestamp-previousTimestamps[bitNumber]) >= s.GetPeriod() ) \
{ \
s.PeriodicProcessing( inputValue, outputValue ); \
previousTimestamps[bitNumber] = timestamp; \
} \
previousBits[bitNumber] = bits[bitNumber];
PROCESS_SCHEDULEE(0, schedulee1);
PROCESS_SCHEDULEE(1, schedulee2);
PROCESS_SCHEDULEE(2, schedulee3);
PROCESS_SCHEDULEE(3, schedulee4);
PROCESS_SCHEDULEE(4, schedulee5);
PROCESS_SCHEDULEE(5, schedulee6);
PROCESS_SCHEDULEE(6, schedulee7);
PROCESS_SCHEDULEE(7, schedulee8);
}
private:
Schedulee1Type& schedulee1;
Schedulee2Type& schedulee2;
Schedulee3Type& schedulee3;
Schedulee4Type& schedulee4;
Schedulee5Type& schedulee5;
Schedulee6Type& schedulee6;
Schedulee7Type& schedulee7;
Schedulee8Type& schedulee8;
volatile uint8x8_t bits;
volatile uint8x8_t previousBits;
volatile uint64x8_t previousTimestamps;
};
////////////////////////////////////////////////////////////////////////////
#endif
|
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include <QTimer>
#include <rep_Controller_source.h>
class Controller : public ControllerSimpleSource
{
Q_OBJECT
public:
Controller(QObject *parent = nullptr);
~Controller();
bool currentState() const;
void setCurrentState(bool currentState);
virtual void testFunction(QString string);
public Q_SLOTS:
void timeout_slot();
private:
bool m_currentState = false;
QTimer *stateChangeTimer;
};
#endif // CONTROLLER_H
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2019 The TurtleCoin developers
// Copyright (c) 2016-2020 The Karbo developers
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "CryptoNoteProtocolHandler.h"
#include <future>
#include <boost/scope_exit.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <System/Dispatcher.h>
#include <boost/optional.hpp>
#include "CryptoNoteCore/CryptoNoteBasicImpl.h"
#include "CryptoNoteCore/CryptoNoteFormatUtils.h"
#include "CryptoNoteCore/CryptoNoteTools.h"
#include "CryptoNoteCore/Currency.h"
#include "CryptoNoteCore/VerificationContext.h"
#include "P2p/LevinProtocol.h"
using namespace logging;
using namespace common;
namespace cn
{
namespace
{
template <class t_parametr>
bool post_notify(IP2pEndpoint &p2p, typename t_parametr::request &arg, const CryptoNoteConnectionContext &context)
{
return p2p.invoke_notify_to_peer(t_parametr::ID, LevinProtocol::encode(arg), context);
}
template <class t_parametr>
void relay_post_notify(IP2pEndpoint &p2p, typename t_parametr::request &arg, const net_connection_id *excludeConnection = nullptr)
{
p2p.relay_notify_to_all(t_parametr::ID, LevinProtocol::encode(arg), excludeConnection);
}
} // namespace
CryptoNoteProtocolHandler::CryptoNoteProtocolHandler(const Currency ¤cy, platform_system::Dispatcher &dispatcher, ICore &rcore, IP2pEndpoint *p_net_layout, logging::ILogger &log) :
m_currency(currency),
m_p2p(p_net_layout),
m_core(rcore),
m_synchronized(false),
m_stop(false),
m_observedHeight(0),
m_peersCount(0),
logger(log, "protocol"),
m_dispatcher(dispatcher)
{
if (!m_p2p)
m_p2p = &m_p2p_stub;
}
size_t CryptoNoteProtocolHandler::getPeerCount() const
{
return m_peersCount;
}
void CryptoNoteProtocolHandler::set_p2p_endpoint(IP2pEndpoint *p2p)
{
if (p2p)
m_p2p = p2p;
else
m_p2p = &m_p2p_stub;
}
void CryptoNoteProtocolHandler::onConnectionOpened(CryptoNoteConnectionContext &context)
{
}
void CryptoNoteProtocolHandler::onConnectionClosed(CryptoNoteConnectionContext &context)
{
bool updated = false;
{
std::lock_guard<std::mutex> lock(m_observedHeightMutex);
uint64_t prevHeight = m_observedHeight;
recalculateMaxObservedHeight(context);
if (prevHeight != m_observedHeight)
{
updated = true;
}
}
if (updated)
{
logger(TRACE) << "Observed height updated: " << m_observedHeight;
m_observerManager.notify(&ICryptoNoteProtocolObserver::lastKnownBlockHeightUpdated, m_observedHeight);
}
if (context.m_state != CryptoNoteConnectionContext::state_befor_handshake)
{
m_peersCount--;
m_observerManager.notify(&ICryptoNoteProtocolObserver::peerCountUpdated, m_peersCount.load());
}
}
void CryptoNoteProtocolHandler::stop()
{
m_stop = true;
}
bool CryptoNoteProtocolHandler::start_sync(CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "Starting synchronization";
if (context.m_state == CryptoNoteConnectionContext::state_synchronizing)
{
assert(context.m_needed_objects.empty());
assert(context.m_requested_objects.empty());
NOTIFY_REQUEST_CHAIN::request r = boost::value_initialized<NOTIFY_REQUEST_CHAIN::request>();
r.block_ids = m_core.buildSparseChain();
logger(logging::TRACE) << context << "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size();
post_notify<NOTIFY_REQUEST_CHAIN>(*m_p2p, r, context);
}
return true;
}
bool CryptoNoteProtocolHandler::get_stat_info(core_stat_info &stat_inf)
{
return m_core.get_stat_info(stat_inf);
}
void CryptoNoteProtocolHandler::log_connections()
{
std::stringstream ss;
ss << std::setw(30) << std::left << "Remote Host"
<< std::setw(20) << std::left << "Peer id"
<< std::setw(25) << std::left << "State"
<< std::setw(20) << std::left << "Lifetime(seconds)" << std::endl;
m_p2p->for_each_connection([&ss](const CryptoNoteConnectionContext &cntxt, PeerIdType peer_id)
{ ss << std::setw(30) << std::left << std::string(cntxt.m_is_income ? "[INC]" : "[OUT]") + common::ipAddressToString(cntxt.m_remote_ip) + ":" + std::to_string(cntxt.m_remote_port)
<< std::setw(20) << std::left << std::hex << peer_id
<< std::setw(25) << std::left << get_protocol_state_string(cntxt.m_state)
<< std::setw(20) << std::left << std::to_string(time(nullptr) - cntxt.m_started) << std::endl; });
logger(INFO) << "Connections: \n"
<< ss.str();
}
/* Get a list of daemons connected to this node */
std::vector<std::string> CryptoNoteProtocolHandler::all_connections()
{
std::vector<std::string> connections;
connections.clear();
m_p2p->for_each_connection([&connections](const CryptoNoteConnectionContext &cntxt, [[maybe_unused]] PeerIdType peer_id)
{
std::string ipAddress = common::ipAddressToString(cntxt.m_remote_ip);
connections.push_back(ipAddress);
});
return connections;
}
uint32_t CryptoNoteProtocolHandler::get_current_blockchain_height()
{
uint32_t height;
crypto::Hash blockId;
m_core.get_blockchain_top(height, blockId);
return height;
}
bool CryptoNoteProtocolHandler::process_payload_sync_data(const CORE_SYNC_DATA &hshd, CryptoNoteConnectionContext &context, bool is_inital)
{
if (context.m_state == CryptoNoteConnectionContext::state_befor_handshake && !is_inital)
return true;
if (context.m_state == CryptoNoteConnectionContext::state_synchronizing)
{
}
else if (m_core.have_block(hshd.top_id))
{
if (is_inital)
{
on_connection_synchronized();
context.m_state = CryptoNoteConnectionContext::state_pool_sync_required;
}
else
{
context.m_state = CryptoNoteConnectionContext::state_normal;
}
}
else
{
int64_t diff = static_cast<int64_t>(hshd.current_height) - static_cast<int64_t>(get_current_blockchain_height());
logger(diff >= 0 ? (is_inital ? logging::INFO : DEBUGGING) : logging::TRACE) << context << "Unknown top block: " << get_current_blockchain_height() << " -> " << hshd.current_height
<< std::endl
<< "Synchronization started";
logger(DEBUGGING) << "Remote top block height: " << hshd.current_height << ", id: " << hshd.top_id;
//let the socket to send response to handshake, but request callback, to let send request data after response
logger(logging::TRACE) << context << "requesting synchronization";
context.m_state = CryptoNoteConnectionContext::state_sync_required;
}
updateObservedHeight(hshd.current_height, context);
context.m_remote_blockchain_height = hshd.current_height;
if (is_inital)
{
m_peersCount++;
m_observerManager.notify(&ICryptoNoteProtocolObserver::peerCountUpdated, m_peersCount.load());
}
return true;
}
bool CryptoNoteProtocolHandler::get_payload_sync_data(CORE_SYNC_DATA &hshd)
{
uint32_t current_height;
m_core.get_blockchain_top(current_height, hshd.top_id);
hshd.current_height = current_height;
hshd.current_height += 1;
return true;
}
template <typename Command, typename Handler>
int notifyAdaptor(const BinaryArray &reqBuf, CryptoNoteConnectionContext &ctx, Handler handler)
{
typedef typename Command::request Request;
int command = Command::ID;
Request req = boost::value_initialized<Request>();
if (!LevinProtocol::decode(reqBuf, req))
{
throw std::runtime_error("Failed to load_from_binary in command " + std::to_string(command));
}
return handler(command, req, ctx);
}
#define HANDLE_NOTIFY(CMD, Handler) \
case CMD::ID: \
{ \
ret = notifyAdaptor<CMD>(in, ctx, std::bind(Handler, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); \
break; \
}
int CryptoNoteProtocolHandler::handleCommand(bool is_notify, int command, const BinaryArray &in, BinaryArray &out, CryptoNoteConnectionContext &ctx, bool &handled)
{
int ret = 0;
handled = true;
switch (command)
{
HANDLE_NOTIFY(NOTIFY_NEW_BLOCK, &CryptoNoteProtocolHandler::handle_notify_new_block)
HANDLE_NOTIFY(NOTIFY_NEW_TRANSACTIONS, &CryptoNoteProtocolHandler::handle_notify_new_transactions)
HANDLE_NOTIFY(NOTIFY_REQUEST_GET_OBJECTS, &CryptoNoteProtocolHandler::handle_request_get_objects)
HANDLE_NOTIFY(NOTIFY_RESPONSE_GET_OBJECTS, &CryptoNoteProtocolHandler::handle_response_get_objects)
HANDLE_NOTIFY(NOTIFY_REQUEST_CHAIN, &CryptoNoteProtocolHandler::handle_request_chain)
HANDLE_NOTIFY(NOTIFY_RESPONSE_CHAIN_ENTRY, &CryptoNoteProtocolHandler::handle_response_chain_entry)
HANDLE_NOTIFY(NOTIFY_REQUEST_TX_POOL, &CryptoNoteProtocolHandler::handle_request_tx_pool)
HANDLE_NOTIFY(NOTIFY_NEW_LITE_BLOCK, &CryptoNoteProtocolHandler::handle_notify_new_lite_block)
HANDLE_NOTIFY(NOTIFY_MISSING_TXS, &CryptoNoteProtocolHandler::handle_notify_missing_txs)
default:
handled = false;
}
return ret;
}
#undef HANDLE_NOTIFY
int CryptoNoteProtocolHandler::handle_notify_new_block(int command, NOTIFY_NEW_BLOCK::request &arg, CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "NOTIFY_NEW_BLOCK (hop " << arg.hop << ")";
updateObservedHeight(arg.current_blockchain_height, context);
context.m_remote_blockchain_height = arg.current_blockchain_height;
if (context.m_state != CryptoNoteConnectionContext::state_normal)
{
return 1;
}
for (auto tx_blob_it = arg.b.txs.begin(); tx_blob_it != arg.b.txs.end(); tx_blob_it++)
{
cn::tx_verification_context tvc = boost::value_initialized<decltype(tvc)>();
auto transactionBinary = asBinaryArray(*tx_blob_it);
//crypto::Hash transactionHash = crypto::cn_fast_hash(transactionBinary.data(), transactionBinary.size());
//logger(DEBUGGING) << "transaction " << transactionHash << " came in NOTIFY_NEW_BLOCK";
m_core.handle_incoming_tx(transactionBinary, tvc, true);
if (tvc.m_verification_failed)
{
logger(logging::INFO) << context << "Block verification failed: transaction verification failed, dropping connection";
m_p2p->drop_connection(context, true);
return 1;
}
}
block_verification_context bvc = boost::value_initialized<block_verification_context>();
m_core.handle_incoming_block_blob(asBinaryArray(arg.b.block), bvc, true, false);
if (bvc.m_verification_failed)
{
logger(logging::DEBUGGING) << context << "Block verification failed, dropping connection";
m_p2p->drop_connection(context, true);
return 1;
}
if (bvc.m_added_to_main_chain)
{
++arg.hop;
//TODO: Add here announce protocol usage
//relay_post_notify<NOTIFY_NEW_BLOCK>(*m_p2p, arg, &context.m_connection_id);
relay_block(arg);
// relay_block(arg, context);
if (bvc.m_switched_to_alt_chain)
{
requestMissingPoolTransactions(context);
}
}
else if (bvc.m_marked_as_orphaned)
{
context.m_state = CryptoNoteConnectionContext::state_synchronizing;
NOTIFY_REQUEST_CHAIN::request r = boost::value_initialized<NOTIFY_REQUEST_CHAIN::request>();
r.block_ids = m_core.buildSparseChain();
logger(logging::TRACE) << context << "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size();
post_notify<NOTIFY_REQUEST_CHAIN>(*m_p2p, r, context);
}
return 1;
}
int CryptoNoteProtocolHandler::handle_notify_new_transactions(int command, NOTIFY_NEW_TRANSACTIONS::request &arg, CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "NOTIFY_NEW_TRANSACTIONS";
if (context.m_state != CryptoNoteConnectionContext::state_normal)
return 1;
if (context.m_pending_lite_block)
{
logger(logging::TRACE) << context
<< " Pending lite block detected, handling request as missing lite block transactions response";
std::vector<BinaryArray> _txs;
for (const auto& tx : arg.txs)
{
_txs.push_back(asBinaryArray(tx));
}
return doPushLiteBlock(context.m_pending_lite_block->request, context, std::move(_txs));
}
else
{
for (auto tx_blob_it = arg.txs.begin(); tx_blob_it != arg.txs.end();)
{
auto transactionBinary = asBinaryArray(*tx_blob_it);
crypto::Hash transactionHash = crypto::cn_fast_hash(transactionBinary.data(), transactionBinary.size());
logger(DEBUGGING) << "transaction " << transactionHash << " came in NOTIFY_NEW_TRANSACTIONS";
cn::tx_verification_context tvc = boost::value_initialized<decltype(tvc)>();
m_core.handle_incoming_tx(transactionBinary, tvc, false);
if (tvc.m_verification_failed)
{
logger(logging::DEBUGGING) << context << "Tx verification failed";
}
if (!tvc.m_verification_failed && tvc.m_should_be_relayed)
{
++tx_blob_it;
}
else
{
tx_blob_it = arg.txs.erase(tx_blob_it);
}
}
if (arg.txs.size())
{
//TODO: add announce usage here
relay_post_notify<NOTIFY_NEW_TRANSACTIONS>(*m_p2p, arg, &context.m_connection_id);
}
}
return true;
}
int CryptoNoteProtocolHandler::handle_request_get_objects(int command, NOTIFY_REQUEST_GET_OBJECTS::request &arg, CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "NOTIFY_REQUEST_GET_OBJECTS";
if(arg.blocks.size() > COMMAND_RPC_GET_OBJECTS_MAX_COUNT || arg.txs.size() > COMMAND_RPC_GET_OBJECTS_MAX_COUNT)
{
logger(logging::ERROR) << context << "GET_OBJECTS_MAX_COUNT exceeded blocks: " << arg.blocks.size() << " txes: " << arg.txs.size();
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
NOTIFY_RESPONSE_GET_OBJECTS::request rsp;
if (!m_core.handle_get_objects(arg, rsp))
{
logger(logging::ERROR) << context << "failed to handle request NOTIFY_REQUEST_GET_OBJECTS, dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
logger(logging::TRACE) << context << "-->>NOTIFY_RESPONSE_GET_OBJECTS: blocks.size()=" << rsp.blocks.size() << ", txs.size()=" << rsp.txs.size()
<< ", rsp.m_current_blockchain_height=" << rsp.current_blockchain_height << ", missed_ids.size()=" << rsp.missed_ids.size();
post_notify<NOTIFY_RESPONSE_GET_OBJECTS>(*m_p2p, rsp, context);
return 1;
}
int CryptoNoteProtocolHandler::handle_response_get_objects(int command, NOTIFY_RESPONSE_GET_OBJECTS::request& arg, CryptoNoteConnectionContext& context) {
logger(logging::TRACE) << context << "NOTIFY_RESPONSE_GET_OBJECTS";
if (context.m_last_response_height > arg.current_blockchain_height) {
logger(logging::ERROR) << context << "sent wrong NOTIFY_HAVE_OBJECTS: arg.m_current_blockchain_height=" << arg.current_blockchain_height
<< " < m_last_response_height=" << context.m_last_response_height << ", dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
updateObservedHeight(arg.current_blockchain_height, context);
context.m_remote_blockchain_height = arg.current_blockchain_height;
size_t count = 0;
std::vector<crypto::Hash> block_hashes;
block_hashes.reserve(arg.blocks.size());
std::vector<parsed_block_entry> parsed_blocks;
parsed_blocks.reserve(arg.blocks.size());
for (const block_complete_entry& block_entry : arg.blocks) {
++count;
Block b;
BinaryArray block_blob = asBinaryArray(block_entry.block);
if (block_blob.size() > m_currency.maxBlockBlobSize()) {
logger(logging::ERROR) << context << "sent wrong block: too big size " << block_blob.size() << ", dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
if (!fromBinaryArray(b, block_blob)) {
logger(logging::ERROR) << context << "sent wrong block: failed to parse and validate block: \r\n"
<< toHex(block_blob) << "\r\n dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
//to avoid concurrency in core between connections, suspend connections which delivered block later then first one
auto blockHash = get_block_hash(b);
if (count == 2) {
if (m_core.have_block(blockHash)) {
context.m_state = CryptoNoteConnectionContext::state_idle;
context.m_needed_objects.clear();
context.m_requested_objects.clear();
logger(DEBUGGING) << context << "Connection set to idle state.";
return 1;
}
}
auto req_it = context.m_requested_objects.find(blockHash);
if (req_it == context.m_requested_objects.end()) {
logger(logging::ERROR) << context << "sent wrong NOTIFY_RESPONSE_GET_OBJECTS: block with id=" << common::podToHex(blockHash)
<< " wasn't requested, dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
if (b.transactionHashes.size() != block_entry.txs.size()) {
logger(logging::ERROR) << context << "sent wrong NOTIFY_RESPONSE_GET_OBJECTS: block with id=" << common::podToHex(blockHash)
<< ", transactionHashes.size()=" << b.transactionHashes.size() << " mismatch with block_complete_entry.m_txs.size()=" << block_entry.txs.size() << ", dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
context.m_requested_objects.erase(req_it);
block_hashes.push_back(blockHash);
parsed_block_entry parsedBlock;
parsedBlock.block = std::move(b);
for (auto& tx_blob : block_entry.txs) {
auto transactionBinary = asBinaryArray(tx_blob);
parsedBlock.txs.push_back(transactionBinary);
}
parsed_blocks.push_back(parsedBlock);
}
if (context.m_requested_objects.size()) {
logger(logging::ERROR, logging::BRIGHT_RED) << context <<
"returned not all requested objects (context.m_requested_objects.size()="
<< context.m_requested_objects.size() << "), dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
uint32_t height;
crypto::Hash top;
{
m_core.pause_mining();
// we lock all the rest to avoid having multiple connections redo a lot
// of the same work, and one of them doing it for nothing: subsequent
// connections will wait until the current one's added its blocks, then
// will add any extra it has, if any
std::lock_guard<std::recursive_mutex> lk(m_sync_lock);
// dismiss what another connection might already have done (likely everything)
m_core.get_blockchain_top(height, top);
uint64_t dismiss = 1;
for (const auto &h : block_hashes) {
if (top == h) {
logger(DEBUGGING) << "Found current top block in synced blocks, dismissing "
<< dismiss << "/" << arg.blocks.size() << " blocks";
while (dismiss--) {
arg.blocks.erase(arg.blocks.begin());
parsed_blocks.erase(parsed_blocks.begin());
}
break;
}
++dismiss;
}
BOOST_SCOPE_EXIT_ALL(this) { m_core.update_block_template_and_resume_mining(); };
int result = processObjects(context, parsed_blocks);
if (result != 0) {
return result;
}
}
m_core.get_blockchain_top(height, top);
logger(DEBUGGING, BRIGHT_GREEN) << "Local blockchain updated, new height = " << height;
if (!m_stop && context.m_state == CryptoNoteConnectionContext::state_synchronizing) {
request_missing_objects(context, true);
}
return 1;
}
int CryptoNoteProtocolHandler::processObjects(CryptoNoteConnectionContext& context, const std::vector<parsed_block_entry>& blocks) {
for (const parsed_block_entry& block_entry : blocks) {
if (m_stop) {
break;
}
//process transactions
for (size_t i = 0; i < block_entry.txs.size(); ++i) {
auto transactionBinary = block_entry.txs[i];
crypto::Hash transactionHash = crypto::cn_fast_hash(transactionBinary.data(), transactionBinary.size());
logger(DEBUGGING) << "transaction " << transactionHash << " came in processObjects";
// check if tx hashes match
if (transactionHash != block_entry.block.transactionHashes[i]) {
logger(DEBUGGING) << context << "transaction mismatch on NOTIFY_RESPONSE_GET_OBJECTS, \r\ntx_id = "
<< common::podToHex(transactionHash) << ", dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
tx_verification_context tvc = boost::value_initialized<decltype(tvc)>();
m_core.handle_incoming_tx(transactionBinary, tvc, true);
if (tvc.m_verification_failed) {
logger(DEBUGGING) << context << "transaction verification failed on NOTIFY_RESPONSE_GET_OBJECTS, \r\ntx_id = "
<< common::podToHex(transactionHash) << ", dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
}
// process block
block_verification_context bvc = boost::value_initialized<block_verification_context>();
m_core.handle_incoming_block(block_entry.block, bvc, false, false);
if (bvc.m_verification_failed) {
logger(DEBUGGING) << context << "Block verification failed, dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
} else if (bvc.m_marked_as_orphaned) {
logger(logging::INFO) << context << "Block received at sync phase was marked as orphaned, dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
} else if (bvc.m_already_exists) {
logger(DEBUGGING) << context << "Block already exists, switching to idle state";
context.m_state = CryptoNoteConnectionContext::state_idle;
context.m_needed_objects.clear();
context.m_requested_objects.clear();
return 1;
}
m_dispatcher.yield();
}
return 0;
}
bool CryptoNoteProtocolHandler::on_idle()
{
return m_core.on_idle();
}
int CryptoNoteProtocolHandler::handle_request_chain(int command, NOTIFY_REQUEST_CHAIN::request &arg, CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << arg.block_ids.size();
if (arg.block_ids.empty())
{
logger(logging::ERROR, logging::BRIGHT_RED) << context << "Failed to handle NOTIFY_REQUEST_CHAIN. block_ids is empty";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
if (arg.block_ids.back() != m_core.getBlockIdByHeight(0))
{
logger(logging::ERROR) << context << "Failed to handle NOTIFY_REQUEST_CHAIN. block_ids doesn't end with genesis block ID";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
NOTIFY_RESPONSE_CHAIN_ENTRY::request r;
r.m_block_ids = m_core.findBlockchainSupplement(arg.block_ids, BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT, r.total_height, r.start_height);
logger(logging::TRACE) << context << "-->>NOTIFY_RESPONSE_CHAIN_ENTRY: m_start_height=" << r.start_height << ", m_total_height=" << r.total_height << ", m_block_ids.size()=" << r.m_block_ids.size();
post_notify<NOTIFY_RESPONSE_CHAIN_ENTRY>(*m_p2p, r, context);
return 1;
}
bool CryptoNoteProtocolHandler::request_missing_objects(CryptoNoteConnectionContext &context, bool check_having_blocks)
{
if (context.m_needed_objects.size())
{
//we know objects that we need, request this objects
NOTIFY_REQUEST_GET_OBJECTS::request req;
size_t count = 0;
auto it = context.m_needed_objects.begin();
while (it != context.m_needed_objects.end() && count < BLOCKS_SYNCHRONIZING_DEFAULT_COUNT)
{
if (!(check_having_blocks && m_core.have_block(*it)))
{
req.blocks.push_back(*it);
++count;
context.m_requested_objects.insert(*it);
}
it = context.m_needed_objects.erase(it);
}
logger(logging::TRACE) << context << "-->>NOTIFY_REQUEST_GET_OBJECTS: blocks.size()=" << req.blocks.size() << ", txs.size()=" << req.txs.size();
post_notify<NOTIFY_REQUEST_GET_OBJECTS>(*m_p2p, req, context);
}
else if (context.m_last_response_height < context.m_remote_blockchain_height - 1)
{ //we have to fetch more objects ids, request blockchain entry
NOTIFY_REQUEST_CHAIN::request r = boost::value_initialized<NOTIFY_REQUEST_CHAIN::request>();
r.block_ids = m_core.buildSparseChain();
logger(logging::TRACE) << context << "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size();
post_notify<NOTIFY_REQUEST_CHAIN>(*m_p2p, r, context);
}
else
{
if (!(context.m_last_response_height ==
context.m_remote_blockchain_height - 1 &&
!context.m_needed_objects.size() &&
!context.m_requested_objects.size()))
{
logger(logging::ERROR, logging::BRIGHT_RED)
<< "request_missing_blocks final condition failed!"
<< "\r\nm_last_response_height=" << context.m_last_response_height
<< "\r\nm_remote_blockchain_height=" << context.m_remote_blockchain_height
<< "\r\nm_needed_objects.size()=" << context.m_needed_objects.size()
<< "\r\nm_requested_objects.size()=" << context.m_requested_objects.size()
<< "\r\non connection [" << context << "]";
return false;
}
requestMissingPoolTransactions(context);
context.m_state = CryptoNoteConnectionContext::state_normal;
logger(logging::INFO, logging::BRIGHT_GREEN) << context << "Synchronization complete";
on_connection_synchronized();
}
return true;
}
bool CryptoNoteProtocolHandler::on_connection_synchronized()
{
bool val_expected = false;
if (m_synchronized.compare_exchange_strong(val_expected, true))
{
logger(logging::INFO) << ENDL << "********************************************************************************" << ENDL
<< "You are now synchronized with the Conceal network." << ENDL
<< "Please note, that the blockchain will be saved only after you quit the daemon" << ENDL
<< "with the \"exit\" command or if you use the \"save\" command." << ENDL
<< "Otherwise, you will possibly need to synchronize the blockchain again." << ENDL
<< "Use \"help\" command to see the list of available commands." << ENDL
<< "********************************************************************************";
m_core.on_synchronized();
uint32_t height;
crypto::Hash hash;
m_core.get_blockchain_top(height, hash);
m_observerManager.notify(&ICryptoNoteProtocolObserver::blockchainSynchronized, height);
}
return true;
}
int CryptoNoteProtocolHandler::handle_response_chain_entry(int command, NOTIFY_RESPONSE_CHAIN_ENTRY::request &arg, CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "NOTIFY_RESPONSE_CHAIN_ENTRY: m_block_ids.size()=" << arg.m_block_ids.size()
<< ", m_start_height=" << arg.start_height << ", m_total_height=" << arg.total_height;
if (!arg.m_block_ids.size())
{
logger(logging::ERROR) << context << "sent empty m_block_ids, dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
if (!m_core.have_block(arg.m_block_ids.front()))
{
logger(logging::ERROR)
<< context << "sent m_block_ids starting from unknown id: "
<< common::podToHex(arg.m_block_ids.front())
<< " , dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
context.m_remote_blockchain_height = arg.total_height;
context.m_last_response_height = arg.start_height + static_cast<uint32_t>(arg.m_block_ids.size()) - 1;
if (context.m_last_response_height > context.m_remote_blockchain_height)
{
logger(logging::ERROR)
<< context
<< "sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with \r\nm_total_height="
<< arg.total_height << "\r\nm_start_height=" << arg.start_height
<< "\r\nm_block_ids.size()=" << arg.m_block_ids.size();
context.m_state = CryptoNoteConnectionContext::state_shutdown;
}
for (auto &bl_id : arg.m_block_ids)
{
if (!m_core.have_block(bl_id))
context.m_needed_objects.push_back(bl_id);
}
request_missing_objects(context, false);
return 1;
}
int CryptoNoteProtocolHandler::handle_notify_new_lite_block(int command, NOTIFY_NEW_LITE_BLOCK::request &arg,
CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "NOTIFY_NEW_LITE_BLOCK (hop " << arg.hop << ")";
updateObservedHeight(arg.current_blockchain_height, context);
context.m_remote_blockchain_height = arg.current_blockchain_height;
if (context.m_state != CryptoNoteConnectionContext::state_normal)
{
return 1;
}
return doPushLiteBlock(std::move(arg), context, {});
}
int CryptoNoteProtocolHandler::handle_notify_missing_txs(int command, NOTIFY_MISSING_TXS::request &arg,
CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "NOTIFY_MISSING_TXS";
NOTIFY_NEW_TRANSACTIONS::request req;
std::list<Transaction> txs;
std::list<crypto::Hash> missedHashes;
m_core.getTransactions(arg.missing_txs, txs, missedHashes, true);
if (!missedHashes.empty())
{
logger(logging::DEBUGGING) << "Failed to Handle NOTIFY_MISSING_TXS, Unable to retrieve requested "
"transactions, Dropping Connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
else
{
for (auto &tx : txs)
{
req.txs.push_back(asString(toBinaryArray(tx)));
}
}
logger(logging::DEBUGGING) << "--> NOTIFY_RESPONSE_MISSING_TXS: "
<< "txs.size() = " << req.txs.size();
if (post_notify<NOTIFY_NEW_TRANSACTIONS>(*m_p2p, req, context))
{
logger(logging::DEBUGGING) << "NOTIFY_MISSING_TXS response sent to peer successfully";
}
else
{
logger(logging::DEBUGGING) << "Error while sending NOTIFY_MISSING_TXS response to peer";
}
return 1;
}
int CryptoNoteProtocolHandler::handle_request_tx_pool(int command, NOTIFY_REQUEST_TX_POOL::request &arg,
CryptoNoteConnectionContext &context)
{
logger(logging::TRACE) << context << "NOTIFY_REQUEST_TX_POOL: txs.size() = " << arg.txs.size();
std::vector<Transaction> addedTransactions;
std::vector<crypto::Hash> deletedTransactions;
m_core.getPoolChanges(arg.txs, addedTransactions, deletedTransactions);
if (!addedTransactions.empty())
{
NOTIFY_NEW_TRANSACTIONS::request notification;
for (auto &tx : addedTransactions)
{
notification.txs.push_back(asString(toBinaryArray(tx)));
}
bool ok = post_notify<NOTIFY_NEW_TRANSACTIONS>(*m_p2p, notification, context);
if (!ok)
{
logger(logging::WARNING, logging::BRIGHT_YELLOW) << "Failed to post notification NOTIFY_NEW_TRANSACTIONS to " << context.m_connection_id;
}
}
return 1;
}
void CryptoNoteProtocolHandler::relay_block(NOTIFY_NEW_BLOCK::request &arg)
{
// generate a lite block request from the received normal block
NOTIFY_NEW_LITE_BLOCK::request lite_arg;
lite_arg.current_blockchain_height = arg.current_blockchain_height;
lite_arg.block = arg.b.block;
lite_arg.hop = arg.hop;
// encoding the request for sending the blocks to peers
auto buf = LevinProtocol::encode(arg);
auto lite_buf = LevinProtocol::encode(lite_arg);
// logging the msg size to see the difference in payload size
logger(logging::DEBUGGING) << "NOTIFY_NEW_BLOCK - MSG_SIZE = " << buf.size();
logger(logging::DEBUGGING) << "NOTIFY_NEW_LITE_BLOCK - MSG_SIZE = " << lite_buf.size();
std::list<boost::uuids::uuid> liteBlockConnections, normalBlockConnections;
// sort the peers into their support categories
m_p2p->for_each_connection([this, &liteBlockConnections, &normalBlockConnections](
const CryptoNoteConnectionContext &ctx, uint64_t peerId) {
if (ctx.version >= P2P_LITE_BLOCKS_PROPOGATION_VERSION)
{
logger(logging::DEBUGGING) << ctx << "Peer supports lite-blocks... adding peer to lite block list";
liteBlockConnections.push_back(ctx.m_connection_id);
}
else
{
logger(logging::DEBUGGING) << ctx << "Peer doesn't support lite-blocks... adding peer to normal block list";
normalBlockConnections.push_back(ctx.m_connection_id);
}
});
// first send lite blocks as it's faster
if (!liteBlockConnections.empty())
{
m_p2p->externalRelayNotifyToList(NOTIFY_NEW_LITE_BLOCK::ID, lite_buf, liteBlockConnections);
}
if (!normalBlockConnections.empty())
{
auto buf = LevinProtocol::encode(arg);
m_p2p->externalRelayNotifyToAll(NOTIFY_NEW_BLOCK::ID, buf, nullptr);
}
}
void CryptoNoteProtocolHandler::relay_transactions(NOTIFY_NEW_TRANSACTIONS::request &arg)
{
auto buf = LevinProtocol::encode(arg);
m_p2p->externalRelayNotifyToAll(NOTIFY_NEW_TRANSACTIONS::ID, buf, nullptr);
}
void CryptoNoteProtocolHandler::requestMissingPoolTransactions(const CryptoNoteConnectionContext &context)
{
if (context.version < cn::P2P_VERSION_1)
{
return;
}
auto poolTxs = m_core.getPoolTransactions();
NOTIFY_REQUEST_TX_POOL::request notification;
for (auto &tx : poolTxs)
{
notification.txs.emplace_back(getObjectHash(tx));
}
bool ok = post_notify<NOTIFY_REQUEST_TX_POOL>(*m_p2p, notification, context);
if (!ok)
{
logger(logging::WARNING, logging::BRIGHT_YELLOW) << "Failed to post notification NOTIFY_REQUEST_TX_POOL to " << context.m_connection_id;
}
}
void CryptoNoteProtocolHandler::updateObservedHeight(uint32_t peerHeight, const CryptoNoteConnectionContext &context)
{
bool updated = false;
{
std::lock_guard<std::mutex> lock(m_observedHeightMutex);
uint32_t height = m_observedHeight;
if (peerHeight > context.m_remote_blockchain_height)
{
m_observedHeight = std::max(m_observedHeight, peerHeight);
if (m_observedHeight != height)
{
updated = true;
}
}
else if (peerHeight != context.m_remote_blockchain_height && context.m_remote_blockchain_height == m_observedHeight)
{
//the client switched to alternative chain and had maximum observed height. need to recalculate max height
recalculateMaxObservedHeight(context);
if (m_observedHeight != height)
{
updated = true;
}
}
}
if (updated)
{
logger(TRACE) << "Observed height updated: " << m_observedHeight;
m_observerManager.notify(&ICryptoNoteProtocolObserver::lastKnownBlockHeightUpdated, m_observedHeight);
}
}
void CryptoNoteProtocolHandler::recalculateMaxObservedHeight(const CryptoNoteConnectionContext &context)
{
//should be locked outside
uint32_t peerHeight = 0;
m_p2p->for_each_connection([&peerHeight, &context](const CryptoNoteConnectionContext &ctx, PeerIdType peerId) {
if (ctx.m_connection_id != context.m_connection_id)
{
peerHeight = std::max(peerHeight, ctx.m_remote_blockchain_height);
}
});
uint32_t localHeight = 0;
crypto::Hash ignore;
m_core.get_blockchain_top(localHeight, ignore);
m_observedHeight = std::max(peerHeight, localHeight + 1);
if (context.m_state == CryptoNoteConnectionContext::state_normal)
{
m_observedHeight = localHeight;
}
}
uint32_t CryptoNoteProtocolHandler::getObservedHeight() const
{
std::lock_guard<std::mutex> lock(m_observedHeightMutex);
return m_observedHeight;
};
bool CryptoNoteProtocolHandler::addObserver(ICryptoNoteProtocolObserver *observer)
{
return m_observerManager.add(observer);
}
bool CryptoNoteProtocolHandler::removeObserver(ICryptoNoteProtocolObserver *observer)
{
return m_observerManager.remove(observer);
}
int CryptoNoteProtocolHandler::doPushLiteBlock(NOTIFY_NEW_LITE_BLOCK::request arg, CryptoNoteConnectionContext &context,
std::vector<BinaryArray> missingTxs)
{
Block b;
if (!fromBinaryArray(b, asBinaryArray(arg.block)))
{
logger(logging::WARNING) << context << "Deserialization of Block Template failed, dropping connection";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
std::unordered_map<crypto::Hash, BinaryArray> provided_txs;
provided_txs.reserve(missingTxs.size());
for (const auto &missingTx : missingTxs)
{
provided_txs[getBinaryArrayHash(missingTx)] = missingTx;
}
std::vector<BinaryArray> have_txs;
std::vector<crypto::Hash> need_txs;
if (context.m_pending_lite_block)
{
for (const auto &requestedTxHash : context.m_pending_lite_block->missed_transactions)
{
if (provided_txs.find(requestedTxHash) == provided_txs.end())
{
logger(logging::DEBUGGING) << context
<< "Peer didn't provide a missing transaction, previously "
"acquired for a lite block, dropping connection.";
context.m_pending_lite_block.reset();
context.m_state = CryptoNoteConnectionContext::state_shutdown;
return 1;
}
}
}
/*
* here we are finding out which txs are present in the pool and which are not
* further we check for transactions in the blockchain to accept alternative blocks
*/
for (const auto &transactionHash : b.transactionHashes)
{
auto providedSearch = provided_txs.find(transactionHash);
if (providedSearch != provided_txs.end())
{
have_txs.push_back(providedSearch->second);
}
else
{
Transaction tx;
if (m_core.getTransaction(transactionHash, tx, true))
{
have_txs.push_back(toBinaryArray(tx));
}
else
{
need_txs.push_back(transactionHash);
}
}
}
/*
* if all txs are present then continue adding the block to
* blockchain storage and relaying the lite-block to other peers
*
* if not request the missing txs from the sender
* of the lite-block request
*/
if (need_txs.empty())
{
context.m_pending_lite_block = boost::none;
for (auto transactionBinary : have_txs)
{
cn::tx_verification_context tvc = boost::value_initialized<decltype(tvc)>();
m_core.handle_incoming_tx(transactionBinary, tvc, true);
if (tvc.m_verification_failed)
{
logger(logging::INFO) << context << "Lite block verification failed: transaction verification failed, dropping connection";
m_p2p->drop_connection(context, true);
return 1;
}
}
block_verification_context bvc = boost::value_initialized<block_verification_context>();
m_core.handle_incoming_block_blob(asBinaryArray(arg.block), bvc, true, false);
if (bvc.m_verification_failed)
{
logger(logging::DEBUGGING) << context << "Lite block verification failed, dropping connection";
m_p2p->drop_connection(context, true);
return 1;
}
if (bvc.m_added_to_main_chain)
{
++arg.hop;
//TODO: Add here announce protocol usage
relay_post_notify<NOTIFY_NEW_LITE_BLOCK>(*m_p2p, arg, &context.m_connection_id);
if (bvc.m_switched_to_alt_chain)
{
requestMissingPoolTransactions(context);
}
}
else if (bvc.m_marked_as_orphaned)
{
context.m_state = CryptoNoteConnectionContext::state_synchronizing;
NOTIFY_REQUEST_CHAIN::request r = boost::value_initialized<NOTIFY_REQUEST_CHAIN::request>();
r.block_ids = m_core.buildSparseChain();
logger(logging::TRACE) << context << "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size();
post_notify<NOTIFY_REQUEST_CHAIN>(*m_p2p, r, context);
}
}
else
{
if (context.m_pending_lite_block)
{
context.m_pending_lite_block = boost::none;
logger(logging::DEBUGGING) << context
<< " Peer has a pending lite block but didn't provide all necessary "
"transactions, dropping the connection.";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
}
else
{
NOTIFY_MISSING_TXS::request req;
req.current_blockchain_height = arg.current_blockchain_height;
req.blockHash = get_block_hash(b);
req.missing_txs = std::move(need_txs);
context.m_pending_lite_block = PendingLiteBlock{arg, {req.missing_txs.begin(), req.missing_txs.end()}};
if (!post_notify<NOTIFY_MISSING_TXS>(*m_p2p, req, context))
{
logger(logging::DEBUGGING) << context
<< "Lite block is missing transactions but the publisher is not "
"reachable, dropping connection.";
context.m_state = CryptoNoteConnectionContext::state_shutdown;
}
}
}
return 1;
}
}; // namespace cn
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
bool cmp(pair<int, int> a, pair<int, int> b){
return a.first > b.first;
}
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *head = NULL, *tail = NULL;
vector< pair<int, int> > V;
make_heap(V.begin(), V.end(), cmp);
for(int i=0;i<lists.size();i++){
if(lists[i]){
V.push_back(make_pair(lists[i] -> val, i));
lists[i] = lists[i] -> next;
push_heap(V.begin(), V.end(), cmp);
}
}
int i = 0;
while(!V.empty()){
pair<int, int> cur = V[0];
pop_heap(V.begin(), V.end(), cmp);
V.pop_back();
if(lists[cur.second]){
V.push_back(make_pair(lists[cur.second] -> val, cur.second));
lists[cur.second] = lists[cur.second] -> next;
push_heap(V.begin(), V.end(), cmp);
}
ListNode *next = new ListNode(cur.first);
if(!head)
head = tail = next;
else{
tail -> next = next;
tail = next;
}
}
return head;
}
};
int main(){
Solution s;
std::vector<ListNode*> v;
for(int i=0;i<10;i++){
ListNode *head, *tail;
head = tail = new ListNode(10*i);
for(int j=1;j<10;j++){
ListNode *next = new ListNode(10*i+j);
tail -> next = next;
tail = next;
}
v.push_back(head);
}
ListNode *merged = s.mergeKLists(v);
while(merged){
cout << merged -> val << ' ';
merged = merged -> next;
}
}
|
//#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include "header.h"
#include <fstream>
//TIMINT returns time step based on the CFL limit and the number of time steps needed to reach TTERM
//---------------------OUTPUT VARIABLES---------------------//
struct TIMINTstruct TIMINT(double LMAX) {
//----------------------BEGIN TIMINT COMP.---------------//
//CALCULATE TIMESTEP BASED ON MAX. EIGENVAULE AND CFL NUMBER
TIMINTstruct t;
t.DT = (CFLFRAC * 2) / (C*sqrt(LMAX*(1 + 2 * BETA)));
t.DT = t.DT / dtscale;
/*
if (debug4 == 1) {
t.DT = 3.25062e-06;
std::cout << "Do you really want to prescribe the time step size?" << std::endl;
system("PAUSE ");
}
*/
/*
if (FEM == 1) {
t.DT = XHE / C / sqrt(1 + 2 * BETA); //this would actually make the FEM solution unstable
}
*/
//CALCULATE THE NUMBER OF TIMESTEPS
//t.NDT = int(TTERM / t.DT) + 1;
//t.NDT = round(TTERM / t.DT) + 1;
t.NDT = floor(TTERM / t.DT) + 1;
std::cout << "DT is: " << t.DT << std::endl;
std::cout << "number of time step is: " << t.NDT << std::endl;
//-------------------------END TIMINT COMP.-----------------//
return t;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef VIS_DEV_LISTENERS_H
#define VIS_DEV_LISTENERS_H
#include "modules/display/vis_dev.h"
#include "modules/dom/domeventtypes.h"
#include "modules/widgets/OpWidget.h"
#include "modules/widgets/OpScrollbar.h"
class OpView;
class Window;
class DocumentManager;
class FramesDocument;
class HTML_Element;
void ShowHotclickMenu(VisualDevice* vis_dev, Window* window, CoreView* view, DocumentManager* doc_man, FramesDocument* doc, BOOL reset_pos = FALSE);
#ifdef DISPLAY_CLICKINFO_SUPPORT
class MouseListenerClickInfo
{
public:
MouseListenerClickInfo();
void Reset();
void SetLinkElement( FramesDocument* document, HTML_Element* link_element );
void SetTitleElement( FramesDocument* document, HTML_Element* element );
void SetImageElement( HTML_Element* image_element );
void GetLinkTitle( OpString &title );
HTML_Element* GetImageElement() const { return m_image_element; }
HTML_Element* GetLinkElement() const { return m_link_element; }
private:
FramesDocument* m_document;
HTML_Element* m_image_element;
HTML_Element* m_link_element;
};
#endif // DISPLAY_CLICKINFO_SUPPORT
class PaintListener : public CoreViewPaintListener
{
public:
VisualDevice* vis_dev;
PaintListener(VisualDevice* vis_dev);
BOOL BeforePaint();
void OnPaint(const OpRect &rect, OpPainter* painter, CoreView* view, int translate_x, int translate_y);
void OnMoved();
};
#ifndef MOUSELESS
class MouseListener : public CoreViewMouseListener, public OpTimerListener
{
public:
OpPoint mousepos;
OpPoint docpos;
VisualDevice* vis_dev;
BOOL in_editable_element;
MouseListener(VisualDevice* vis_dev);
OP_STATUS Init();
~MouseListener();
CoreView* GetMouseHitView(const OpPoint &point, CoreView* view);
void UpdateOverlappedStatus(CoreView* view);
void OnMouseMove(const OpPoint &point, ShiftKeyState keystate, CoreView* view);
void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks, ShiftKeyState keystate, CoreView* view);
void OnMouseUp(const OpPoint &point, MouseButton button, ShiftKeyState keystate, CoreView* view);
void OnMouseLeave();
void OnSetCursor();
BOOL OnMouseWheel(INT32 delta, BOOL vertical, ShiftKeyState keystate, CoreView* view);
// from OpTimerListener:
void OnTimeOut(OpTimer* timer);
#ifdef DISPLAY_CLICKINFO_SUPPORT
static MouseListenerClickInfo& GetClickInfo() { return *g_opera->display_module.mouse_click_info; }
#endif // DISPLAY_CLICKINFO_SUPPORT
private:
void OnMouseLeft3Clk(CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, ShiftKeyState keystate);
void OnMouseLeft4Clk(CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, ShiftKeyState keystate);
BOOL haveActivatedALink; //< if first click in a doubleclick activated a link
void OnMouseLeftDown (CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, UINT8 nclicks, ShiftKeyState keystate);
void OnMouseLeftUp (CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, UINT8 nclicks, ShiftKeyState keystate);
void OnMouseLeftDblClk(CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, ShiftKeyState keystate);
void OnMouseRightDown (CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, UINT8 nclicks, ShiftKeyState keystate);
void OnMouseRightUp (CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, UINT8 nclicks, ShiftKeyState keystate);
void OnMouseRightDblClk(CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, ShiftKeyState keystate);
void OnMouseMiddleDown (CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, UINT8 nclicks, ShiftKeyState keystate);
void OnMouseMiddleUp (CoreView* view, Window* window, DocumentManager* doc_man, FramesDocument* doc, UINT8 nclicks, ShiftKeyState keystate);
void PropagateMouseEvent(CoreView* view, Window* window, FramesDocument* doc, MouseButton button, UINT8 nclicks, ShiftKeyState keystate);
#ifdef DRAG_SUPPORT
BOOL3 is_dragging;
OpPoint drag_point;
OpTimer* dragTimer;
void StopDragging();
#endif // DRAG_SUPPORT
BOOL right_key_is_down;
BOOL left_key_is_down;
BOOL left_while_right_down;
};
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
class TouchListener : public CoreViewTouchListener
{
public:
TouchListener(VisualDevice* vis_dev);
void OnTouchDown(int id, const OpPoint &point, int radius, ShiftKeyState modifiers, CoreView* view, void* user_data);
void OnTouchUp(int id, const OpPoint &point, int radius, ShiftKeyState modifiers, CoreView* view, void* user_data);
void OnTouchMove(int id, const OpPoint &point, int radius, ShiftKeyState modifiers, CoreView* view, void* user_data);
void OnTouch(DOM_EventType type, int id, const OpPoint &point, int radius, ShiftKeyState modifiers, void* user_data);
CoreView* GetTouchHitView(const OpPoint &point, CoreView* view);
void UpdateOverlappedStatus(CoreView* view);
private:
VisualDevice* vis_dev;
BOOL in_editable_element;
};
#endif // TOUCH_EVENTS_SUPPORT
class ScrollListener :
public OpSmoothScroller,
public OpWidgetListener
{
public:
VisualDevice* vis_dev;
ScrollListener(VisualDevice* vis_dev);
/** OpSmoothScroller::OnSmoothScroll - Happens when smoothscroll is running */
BOOL OnSmoothScroll(INT32 value);
/** OpWidgetListener::OnScroll - Happens when the OpScrollbar has changed value. */
void OnScroll(OpWidget *widget, INT32 old_val, INT32 new_val, BOOL caused_by_input);
};
#ifdef DRAG_SUPPORT
class DragListener : public CoreViewDragListener
{
public:
VisualDevice* m_vis_dev;
DragListener(VisualDevice* vis_dev) : m_vis_dev(vis_dev) {}
virtual ~DragListener() {}
// CoreViewDragListener's interface
virtual void OnDragStart(CoreView* view, const OpPoint& start_point, ShiftKeyState modifiers, const OpPoint& current_point);
virtual void OnDragEnter(CoreView* view, OpDragObject* drag_object, const OpPoint& point, ShiftKeyState modifiers);
virtual void OnDragCancel(CoreView* view, OpDragObject* drag_object, ShiftKeyState modifiers);
virtual void OnDragLeave(CoreView* view, OpDragObject* drag_object, ShiftKeyState modifiers);
virtual void OnDragMove(CoreView* view, OpDragObject* drag_object, const OpPoint& point, ShiftKeyState modifiers);
virtual void OnDragDrop(CoreView* view, OpDragObject* drag_object, const OpPoint& point, ShiftKeyState modifiers);
virtual void OnDragEnd(CoreView* view, OpDragObject* drag_object, const OpPoint& point, ShiftKeyState modifiers);
};
#endif
#endif // VIS_DEV_LISTENERS_H
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/freeglut.h>
#endif
#include "instructions.h"
//Globals
Instructions ins;
bool isDrawPoint = true;
bool isDrawLine = false;
bool isDrawRect = false;
bool isDrawCircle = false;
bool isDrawRadial = false;
int xi, yi, xf, yf;
int first = 0;
int ww = 600, wh = 600; //window size, ww: WindowWidth, wh: WindowHeight
float pointSize = 7.0;
float red, green, blue = 0.0f; //colour used to draw
void putPixel(int x, int y)
{
glColor3f(red, green, blue);
glPointSize(pointSize);
glBegin(GL_POINTS);
//glVertex2i(x, y); //sets pixel coord
glVertex2f((GLdouble)x, (GLdouble)y);
glEnd();
}
//-----------------------------------------------------------------
void bresenhamAlg(int x0, int y0, int x1, int y1) //copied from internet
{
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int x, y;
if (dx >= dy)
{
int d = 2 * dy - dx;
int ds = 2 * dy;
int dt = 2 * (dy - dx);
if (x0 < x1)
{
x = x0;
y = y0;
}
else
{
x = x1;
y = y1;
x1 = x0;
y1 = y0;
}
putPixel(x, y);
while (x < x1)
{
if (d < 0)
d += ds;
else
{
if (y < y1)
{
y++;
d += dt;
}
else
{
y--;
d += dt;
}
}
x++;
putPixel(x, y);
}
}
else
{
int d = 2 * dx - dy;
int ds = 2 * dx;
int dt = 2 * (dx - dy);
if (y0 < y1)
{
x = x0;
y = y0;
}
else
{
x = x1;
y = y1;
y1 = y0;
x1 = x0;
}
putPixel(x, y);
while (y < y1)
{
if (d < 0)
d += ds;
else
{
if (x > x1)
{
x--;
d += dt;
}
else
{
x++;
d += dt;
}
}
y++;
putPixel(x, y);
}
}
}
void drawPoints(int x, int y)
{
//xi = x;
//yi = (wh - y); //invert axis
bresenhamAlg(xf, wh - yf, x, wh - y);
//putPixel(xf, yf);
xf = x;
yf = y;
//display
// {
// switch (first)
// {
// case 0:
// xi = x;
// yi = (wh - y);
// first = 1;
// break;
// case 1:
// xf = x;
// yf = (wh - y);
// bresenhamAlg(xi, yi, xf, yf);
// //putPixel(xf, yf);
// first = 0;
// break;
// }
// }
}
void drawLine(int x, int y)
{
switch (first)
{
case 0:
xi = x;
yi = (wh - y);
first = 1;
break;
case 1:
xf = x;
yf = (wh - y);
bresenhamAlg(xi, yi, xf, yf);
//putPixel(xf, yf);
first = 0;
break;
}
}
void drawRect(int x, int y)
{
switch (first)
{
case 0:
xi = x;
yi = (wh - y);
first = 1;
break;
case 1:
xf = x;
yf = (wh - y);
bresenhamAlg(xi, yi, xf, yi); // connect 4 lines based off two opposite coords
bresenhamAlg(xi, yi, xi, yf);
bresenhamAlg(xf, yi, xf, yf);
bresenhamAlg(xi, yf, xf, yf);
//putPixel(xf, yf);
first = 0;
break;
}
}
// void drawCircle(int x, int y) {
// {
// for ( float angle = 0; angle <= 2*3.142; angle+=0.1)
// {
// x =( .3) * cos (angle);
// y =( .3) * sin (angle);
// putPixel(x, y);
// }
// }
// }
void drawCircle(int x, int y)
{
switch (first)
{
case 0:
xi = x;
yi = (wh - y);
first = 1;
break;
case 1:
xf = x;
yf = (wh - y);
float r = sqrt((xf - x) * (xf - x) + (yf - y) * (yf - y)); //r = x^2 + y^2
float deg = 0.0174532925; //constant part of circle algorithm
for (float theta = deg; theta <= 361 * deg; theta += deg)
{
bresenhamAlg(
(x + r * cos(theta)),
(y + r * sin(theta)),
(x + r * cos(theta + deg)),
(y + r * sin(theta + deg)));
}
first = 0;
break;
}
}
/* display function - GLUT display callback function
* clears the screen, sets the camera position, draws the ground plane and movable box
*/
void display(void)
{
glColor3f(0.2, 0.3, 0.3);
//glClear(GL_COLOR_BUFFER_BIT);
glutSwapBuffers();
}
void resize(int w, int h)
{
glutReshapeWindow(ww, wh); //locks screen resize
}
//}
//**************************************************
//OpenGL functions
//keyboard stuff
void keyboard(unsigned char key, int xIn, int yIn)
{
int mod = glutGetModifiers();
switch (key)
{
case 'q':
case 27: //27 is the esc key
printf("Quitting Program, see you later!\n");
exit(0);
break;
case 'm': //increase brush size
printf("Increasing brush size\n");
pointSize++;
printf("Current brush size is: %.0f\n", pointSize);
break;
case 'n': //decrease brush size
printf("Decreasing brush size\n");
pointSize--;
if (pointSize <= 1.00)
{ //minimum size is 1.00
pointSize = 1.00;
}
printf("Current brush size is: %.0f\n", pointSize);
break;
case 'd':
if (mod == GLUT_ACTIVE_ALT)
{
printf("ALT + d: Screen cleared\n");
glClear(GL_COLOR_BUFFER_BIT);
}
else
{
printf("Hold Alt and tap 'd' to clear screen\n");
}
break;
case 'h': //help
printf("Help! Printing instructions\n");
ins.instructions();
break;
}
}
void special(int key, int xIn, int yIn)
{
switch (key)
{
case GLUT_KEY_DOWN:
printf("arrow down\n");
break;
}
}
//mouse
void mouse(int btn, int state, int x, int y)
{
if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
xf = x;
yf = y;
if (isDrawPoint)
{
drawPoints(x, y);
}
if (isDrawLine)
{
drawLine(x, y);
}
else if (isDrawRect)
{
drawRect(x, y);
}
else if (isDrawCircle)
{
drawCircle(x, y); //fix radius
}
else if (isDrawRadial)
{
}
}
//glutPostRedisplay();
}
void mouseMotion(int x, int y)
{
// if (draw brush)
// {
// xf = x;
// yf = (wh - y);
// bresenhamAlg(x, y, xf, yf);
// //putPixel(xf, yf);
// }
if (isDrawPoint)
{
drawPoints(x, y);
}
}
void mousePassiveMotion(int x, int y)
{
//printf("mousePassive coords: %i,%i\n", x, y);
}
//initialization
void init(void)
{
glViewport(0, 0, ww, wh);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble)ww, 0.0, (GLdouble)wh);
glMatrixMode(GL_MODELVIEW);
}
void FPSTimer(int value)
{ //60fps
glutTimerFunc(17, FPSTimer, 0);
glutPostRedisplay();
}
double randomNumGen()
{ //stackoverflow
return (double)rand() / (RAND_MAX + 1.0);
}
//menu stuff
void mainMenuProc(int value)
{
switch (value)
{
case 1: //clear screen
glClear(GL_COLOR_BUFFER_BIT);
printf("Screen cleared.\n");
break;
case 2: //choose random colour
printf("A random colour has been selected.\n");
red = randomNumGen();
green = randomNumGen();
blue = randomNumGen();
printf("Colour scheme: Red %.1f, Green %.1f, Blue %.1f.\n", red, green, blue);
break;
case 3: //radial paintBrush
printf("Selected Radial PaintBrush.\n");
break;
case 4:
printf("Quitting Program, see you later!\n");
exit(0);
default:
break;
}
}
//could use a seperate menu processor for submenu!
void shapesMenuProc(int value)
{
switch (value)
{
case 1: //Point
isDrawPoint = true;
isDrawLine = false;
isDrawRect = false;
isDrawCircle = false;
printf("Point selected.\n");
break;
case 2:
isDrawPoint = false;
isDrawLine = true;
isDrawRect = false;
isDrawCircle = false;
printf("Line selected.\n");
break;
case 3:
isDrawPoint = false;
isDrawLine = false;
isDrawRect = true;
isDrawCircle = false;
printf("Rectangle selected\n");
break;
case 4:
isDrawPoint = false;
isDrawLine = false;
isDrawRect = false;
isDrawCircle = true;
printf("Circle selected\n");
break;
default:
break;
}
}
void colourMenuProc(int value)
{
switch (value)
{
case 1: //Red
red = 1.0;
green = 0.0;
blue = 0.0;
printf("Red selected.\n");
break;
case 2: //Green
red = 0.0;
green = 1.0;
blue = 0.0;
printf("Green selected.\n");
break;
case 3: //Blue
red = 0.0;
green = 0.0;
blue = 1.0;
printf("Blue selected\n");
break;
case 4: //Purple
red = 0.6;
green = 0.2;
blue = 0.8;
printf("Purple selected\n");
break;
case 5: //Yellow
printf("Yellow selected\n");
red = 1.0;
green = 1.0;
blue = 0.0;
break;
default:
break;
}
}
void createMenu()
{
//int subMenu_id = glutCreateMenu(menuProc2);
int colourSubMenu_id = glutCreateMenu(colourMenuProc);
glutAddMenuEntry("Red", 1);
glutAddMenuEntry("Green", 2);
glutAddMenuEntry("Blue", 3);
glutAddMenuEntry("Purple", 4);
glutAddMenuEntry("Yellow", 5);
int shapesSubMenu_id = glutCreateMenu(shapesMenuProc);
glutAddMenuEntry("Point", 1);
glutAddMenuEntry("Line", 2);
glutAddMenuEntry("Rectangle", 3);
glutAddMenuEntry("Circle", 4);
int main_id = glutCreateMenu(mainMenuProc);
glutAddSubMenu("Colour", colourSubMenu_id);
glutAddSubMenu("Shapes", shapesSubMenu_id);
glutAddMenuEntry("Clear Screen", 1);
glutAddMenuEntry("Random Colour", 2);
glutAddMenuEntry("Radial PaintBrush", 3);
glutAddMenuEntry("Quit Program", 4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
/* main function - program entry point */
int main(int argc, char **argv)
{
ins.instructions();
glutInit(&argc, argv); //starts up GLUT
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(ww, wh);
glutInitWindowPosition(50, 50);
glutCreateWindow("Paint.x"); //creates the window
//display callback
glutDisplayFunc(display);
glutReshapeFunc(resize);
init();
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
createMenu();
//keyboard callback
glutKeyboardFunc(keyboard);
glutSpecialFunc(special);
//mouse callbacks
glutMouseFunc(mouse);
glutMotionFunc(mouseMotion);
glutPassiveMotionFunc(mousePassiveMotion);
//fps timer callback
glutTimerFunc(5, FPSTimer, 0);
glutMainLoop(); //starts the event glutMainLoop
return (0); //return may not be necessary on all compilers
}
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using u8 = uint8_t;
// const u8 ALPHA_SIZE = 128;
// u8 dist[ALPHA_SIZE];
int main(){
//vector<int> input;
int goodCount = 0;
while(!(cin.eof())){
// memset(dist, 0, ALPHA_SIZE*sizeof(u8));
unsigned int low, high;
char ch, dch;
string s;
// "1-13"
cin >> low >> dch >> high;
cout << dch << " ";
assert(low <= high);
cout << low << " " << high << " ";
// " z : "
cin >> ch; cout << ch << " ";
cin >> dch; cout << dch << " ";
// "string\n"
cin >> s;
cout << s << endl;
u8 cc = 0;
for(u8 i = 0; i < s.length(); i++){
assert('a' <= s[i] && s[i] <= 'z');
if(s[i] == ch){
cc++;
}
}
if(low <= cc && cc <= high){
cout << "good!" << endl;
goodCount++;
} else {
cout << "bad!" << endl;
}
}
cout << goodCount << endl;
return 0;
}
|
/* -*- 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 MODULES_LIBVEGA_LIBVEGA_MODULE_H
#define MODULES_LIBVEGA_LIBVEGA_MODULE_H
#ifdef VEGA_SUPPORT
#define VEGA_USE_LINEDATA_POOL
#ifdef VEGA_3DDEVICE
# include "modules/libvega/vega3ddevice.h"
#endif // VEGA_3DDEVICE
/** The global objects used by the libvega module. */
class LibvegaModule : public OperaModule
{
public:
LibvegaModule();
void InitL(const OperaInitInfo& info);
void Destroy();
static class VEGARendererBackend* InstantiateRasterBackend(unsigned int w, unsigned int h, unsigned int q, unsigned int rasterBackend);
class VEGARendererBackend* CreateRasterBackend(unsigned int w, unsigned int h, unsigned int q, unsigned int forcedBackend);
class VEGARendererBackend* SelectRasterBackend(unsigned int w, unsigned int h, unsigned int q);
class VEGA3dDevice* vega3dDevice;
class VEGA2dDevice* vega2dDevice;
enum
{
BACKEND_NONE,
BACKEND_HW3D,
BACKEND_HW2D,
BACKEND_SW
};
unsigned int rasterBackend;
#ifdef VEGA_USE_GRADIENT_CACHE
class VEGAGradientCache* gradientCache;
#endif // VEGA_USE_GRADIENT_CACHE
#ifdef VEGA_OPPAINTER_SUPPORT
class VEGAWindow* mainNativeWindow;
const uni_char* default_font;
const uni_char* default_serif_font;
const uni_char* default_sans_serif_font;
const uni_char* default_cursive_font;
const uni_char* default_fantasy_font;
const uni_char* default_monospace_font;
#endif // VEGA_OPPAINTER_SUPPORT
#ifdef VEGA_3DDEVICE
/** The 3d hardware backend batches together multiple draw calls
* and flush the batches as needed.
* If more than one renderer batches at the same time there can
* be an issue with bitmaps being modified by a renderer while
* they are still in a pending batch in other renderer.
* To get around this we limit the batching to only allow batching
* of one renderer at the time. */
class VEGABackend_HW3D* m_current_batcher;
OP_STATUS getShaderLocations(int* worldProjMatrix2dLocationV,
int* texTransSLocationV,
int* texTransTLocationV,
int* stencilCompBasedLocation,
int* straightAlphaLocation);
bool shaderLocationsInitialized;
int worldProjMatrix2dLocationV[VEGA3dShaderProgram::WRAP_MODE_COUNT];
int texTransSLocationV[VEGA3dShaderProgram::WRAP_MODE_COUNT];
int texTransTLocationV[VEGA3dShaderProgram::WRAP_MODE_COUNT];
int stencilCompBasedLocation[VEGA3dShaderProgram::WRAP_MODE_COUNT];
int straightAlphaLocation[VEGA3dShaderProgram::WRAP_MODE_COUNT];
/** This is a texture atlas used by VEGAGradient to avoid creating
* (and binding) a new texture for every gradient needed.
*/
class VEGA3dTexture* m_gradient_texture;
/** m_gradient_texture is filled in from the top with full lines.
* This variable holds the number of lines filled in so far.
*/
unsigned int m_gradient_texture_next_line;
#endif // VEGA_3DDEVICE
#ifdef VEGA_USE_LINEDATA_POOL
void* linedata_pool;
#endif // VEGA_USE_LINEDATA_POOL
#ifdef VEGA_USE_ASM
class VEGADispatchTable* dispatchTable;
#endif // VEGA_USE_ASM
};
// We can only enable support the Canvas Text APIs if SVG is supported.
#if defined(SVG_SUPPORT) && defined(SVG_PATH_TO_VEGAPATH)
# define CANVAS_TEXT_SUPPORT
#endif // SVG_SUPPORT && SVG_PATH_TO_VEGAPATH
#if defined(VEGA_2DDEVICE) || defined(VEGA_3DDEVICE)
# define VEGA_USE_HW
#endif // VEGA_2DDEVICE || VEGA_3DDEVICE
#define g_vegaGlobals (g_opera->libvega_module)
#ifdef VEGA_USE_ASM
#define g_vegaDispatchTable (g_vegaGlobals.dispatchTable)
#endif // VEGA_USE_ASM
#define LIBVEGA_MODULE_REQUIRED
#endif // VEGA_SUPPORT
#endif // !MODULES_LIBVEGA_LIBVEGA_MODULE_H
|
// ChatSocket.cpp : implementation file
//
#include "stdafx.h"
#include "Chat.h"
#include "ChatSocket.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CWnd* CChatSocket::pWndMsgProc = NULL;
/////////////////////////////////////////////////////////////////////////////
// CChatSocket
CChatSocket::CChatSocket()
: m_bIsServer(false), m_pParent(NULL), m_pClient(NULL)
{
}
CChatSocket::~CChatSocket()
{
if (m_bIsServer)
{
m_pClient->Close();
delete m_pClient;
m_pClient = NULL;
m_bIsServer = false;
}
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CChatSocket, CSocket)
//{{AFX_MSG_MAP(CChatSocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/////////////////////////////////////////////////////////////////////////////
// CChatSocket member functions
void CChatSocket::OnAccept(int nErrorCode)
{
m_bIsServer = true;
m_pClient = new CChatSocket();
m_pClient->m_pParent = this;
Accept(*m_pClient);
if (pWndMsgProc)
{
pWndMsgProc->SendMessage(WM_ON_ACCEPT, (WPARAM) (LPCSTR) m_pClient, (LPARAM) ParamPtr());
}
CSocket::OnAccept(nErrorCode);
}
void CChatSocket::OnClose(int nErrorCode)
{
if (pWndMsgProc)
{
pWndMsgProc->SendMessage(WM_ON_CLOSE, 0, (LPARAM) ParamPtr());
}
CSocket::OnClose(nErrorCode);
}
void CChatSocket::OnReceive(int nErrorCode)
{
char buff[4097];
int ret = Receive(buff, 4096);
switch (ret) {
case 0:
Close();
break;
case SOCKET_ERROR:
if (GetLastError() != WSAEWOULDBLOCK)
{
Close();
}
break;
default:
for (int i = 0; i < ret; i++) {
m_recvQueue.push_back(buff[i]);
}
// m_recvQueue.insert(m_recvQueue.end(), &buff[0], &buff[ret]);
}
if (pWndMsgProc) {
pWndMsgProc->SendMessage(WM_ON_RECEIVE, (WPARAM) &m_recvQueue, (LPARAM) ParamPtr());
}
CSocket::OnReceive(nErrorCode);
}
void CChatSocket::OnSend(int nErrorCode)
{
if (m_sendQueue.size() > 0)
{
Send();
}
CSocket::OnSend(nErrorCode);
}
int CChatSocket::Send(const void* lpBuf, int nBufLen, int nFlags)
{
if (m_bIsServer)
{
return m_pClient->Send(lpBuf, nBufLen, nFlags);
}
int i;
for (i = 0; i < 4; i++) {
m_sendQueue.push_back(((char*) &nBufLen)[i]);
}
for (i = 0; i < nBufLen; i++) {
m_sendQueue.push_back(((char*) lpBuf)[i]);
}
// m_sendQueue.insert(m_sendQueue.end(), (char*) &nBufLen, (char*) (&nBufLen + 1));
// m_sendQueue.insert(m_sendQueue.end(), (char*) lpBuf, (char*) lpBuf + nBufLen);
return Send();
}
int CChatSocket::Send(CChatPacket& packet)
{
if (m_bIsServer)
{
return m_pClient->Send(packet);
}
DWORD packetSize = packet.getPacketSize();
CChatPacket::PacketType packetType = packet.getType();
DWORD totalSize = sizeof(packetSize) + sizeof(packetType) + packetSize;
int i;
for (i = 0; i < 4; i++) {
m_sendQueue.push_back(((char*) &totalSize)[i]);
}
for (i = 0; i < 4; i++) {
m_sendQueue.push_back(((char*) &packetType)[i]);
}
// m_sendQueue.insert(m_sendQueue.end(), (char*) &totalSize, (char*) (&totalSize + 1));
// m_sendQueue.insert(m_sendQueue.end(), (char*) &packetType, (char*) (&packetType + 1));
if (packetSize > 0) {
BYTE* pData = packet.getPacketPtr();
m_sendQueue.reserve(totalSize + m_sendQueue.size());
for (i = 0; i < (int)packetSize; i++) {
m_sendQueue.push_back(pData[i]);
}
// m_sendQueue.insert(m_sendQueue.end(), (char*) packet.getPacketPtr(), (char*) (packet.getPacketPtr() + packetSize));
}
return Send();
}
int CChatSocket::Send()
{
int sendLength = (int) m_sendQueue.size();
// 한번에 보낼 데이터 크기를 10k로 한정
if (sendLength > 10240) {
sendLength = 10240;
}
int ret = CSocket::Send((void*) &m_sendQueue.front(), sendLength, 0);
switch (ret) {
case 0:
break;
case SOCKET_ERROR:
if (GetLastError() != WSAEWOULDBLOCK)
{
Close();
}
break;
default:
m_sendQueue.erase(m_sendQueue.begin(), m_sendQueue.begin() + ret);
}
return ret;
}
void CChatSocket::Close()
{
if (m_bIsServer) {
if (m_pClient) {
m_pClient->Close();
delete m_pClient;
m_pClient = NULL;
}
m_bIsServer = false;
}
CSocket::Close();
}
CChatSocket* CChatSocket::ParamPtr()
{
return (m_pParent) ? m_pParent->ParamPtr() : this;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
#include "rssmodule.h"
#include "adjunct/m2/src/engine/account.h"
#include "adjunct/m2/src/engine/engine.h"
#include "adjunct/m2/src/engine/indexer.h"
#include "adjunct/m2/src/include/defs.h"
#include "adjunct/m2/src/include/mailfiles.h"
#include "adjunct/quick/Application.h"
#include "adjunct/m2/src/backend/rss/rss-protocol.h"
#include "modules/prefsfile/prefsfile.h"
// ***************************************************************************
//
// RSSBackend
//
// ***************************************************************************
RSSBackend::RSSBackend(MessageDatabase& database)
: ProtocolBackend(database),
m_protocol(NULL),
m_file(NULL),
m_feed_index(0),
m_no_dialogs(0)
{
}
RSSBackend::~RSSBackend()
{
MessageEngine::GetInstance()->GetGlueFactory()->DeletePrefsFile(m_file);
}
OP_STATUS RSSBackend::MailCommand(URL& url)
{
// If the account does not exist yet, this might be NULL.
if (m_protocol.get() == 0)
RETURN_IF_ERROR(SettingsChanged(FALSE)); // Initialize the account.
if (m_protocol.get() != 0)
m_protocol->OnProgress(url, OpTransferListener::TRANSFER_DONE);
return OpStatus::OK;
}
OP_STATUS RSSBackend::UpdateFeed(const OpStringC& url, BOOL display_dialogs)
{
if (!display_dialogs)
m_no_dialogs++;
// If the account does not exist yet, this might be NULL.
if (m_protocol.get() == 0)
RETURN_IF_ERROR(SettingsChanged(FALSE)); // Initialize the account.
// Check if we already have the feed
Index* index = MessageEngine::GetInstance()->GetIndexer()->GetSubscribedFolderIndex(GetAccountPtr(), url, 0, 0, FALSE, FALSE);
if (index && GetRSSDialogs())
g_application->GoToMailView(index->GetId());
RETURN_IF_ERROR(m_protocol->FetchMessages(url));
// Update progress.
RETURN_IF_ERROR(m_progress.SetCurrentAction(ProgressInfo::UPDATING_FEEDS, m_progress.GetTotalCount() + 1));
return OpStatus::OK;
}
void RSSBackend::FeedCheckingCompleted()
{
if (m_no_dialogs)
m_no_dialogs--;
// Update progress.
m_progress.UpdateCurrentAction();
// Have we checked all feeds now?
if (m_progress.GetCount() >= m_progress.GetTotalCount())
{
m_progress.EndCurrentAction(TRUE);
// Give a notification
MessageEngine::GetInstance()->GetMasterProgress().NotifyReceived(GetAccountPtr());
}
}
OP_STATUS RSSBackend::Init(Account* account)
{
if (!account)
return OpStatus::ERR_NULL_POINTER;
m_account = account;
OpString file_path;
RETURN_IF_ERROR(m_account->GetIncomingOptionsFile(file_path));
GlueFactory* glue_factory = MessageEngine::GetInstance()->GetGlueFactory();
if (!file_path.IsEmpty())
m_file = glue_factory->CreatePrefsFile(file_path);
return OpStatus::OK;
}
OP_STATUS RSSBackend::SettingsChanged(BOOL startup)
{
// Init the protocol.
m_protocol = OP_NEW(RSSProtocol, (*this));
if (m_protocol.get() == 0)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(m_protocol->Init());
return OpStatus::OK;
}
OP_STATUS RSSBackend::FetchMessages(BOOL enable_signalling)
{
OP_NEW_DBG("RSSBackend::FetchMessages", "m2");
OP_DBG(("retrieving messages with rss"));
if (m_account == 0 || m_protocol.get() == 0)
return OpStatus::ERR_NULL_POINTER;
// Check which feeds we need to update
Indexer* indexer = MessageEngine::GetInstance()->GetIndexer();
OP_ASSERT(indexer != 0);
Index* index;
for (INT32 it = -1; (index = indexer->GetRange(IndexTypes::FIRST_NEWSFEED, IndexTypes::LAST_NEWSFEED, it)) != NULL; )
{
if ((index->GetAccountId() == m_account->GetAccountId()) && (index->GetSearch() != 0))
{
OpStatus::Ignore(UpdateFeedIfNeeded(index));
}
}
return OpStatus::OK;
}
OP_STATUS RSSBackend::FetchMessage(const OpStringC8& internet_location, message_index_t index)
{
RETURN_IF_ERROR(UpdateFeed(index));
return OpStatus::OK;
}
OP_STATUS RSSBackend::SelectFolder(UINT32 index_id, const OpStringC16& folder)
{
RETURN_IF_ERROR(UpdateFeedIfNeeded(index_id, folder));
return OpStatus::OK;
}
OP_STATUS RSSBackend::RefreshAll()
{
Indexer* indexer = MessageEngine::GetInstance()->GetIndexer();
Index* index;
for (INT32 it = -1; (index = indexer->GetRange(IndexTypes::FIRST_NEWSFEED, IndexTypes::LAST_NEWSFEED, it)) != NULL; )
{
// Force all feeds to update
if ((index->GetAccountId() == m_account->GetAccountId()) && (index->GetSearch() != 0))
{
OpStatus::Ignore(UpdateFeed(index->GetId()));
}
}
return OpStatus::OK;
}
OP_STATUS RSSBackend::StopFetchingMessages()
{
if (m_protocol.get() == 0)
return OpStatus::ERR_NULL_POINTER;
OP_STATUS ret = m_protocol->StopFetching();
m_progress.EndCurrentAction(TRUE);
return ret;
}
OP_STATUS RSSBackend::RemoveSubscribedFolder(UINT32 index_id)
{
Index* index = MessageEngine::GetInstance()->GetIndexById(index_id);
if (!index)
return OpStatus::ERR_NULL_POINTER;
// Remove both the messages inside this folder and the folder
RETURN_IF_ERROR(MessageEngine::GetInstance()->GetIndexer()->RemoveMessagesInIndex(index));
// Delete the search_engine file associated to the feed index:
OpString filename;
OpFile btree_file;
RETURN_IF_ERROR(MailFiles::GetNewsfeedFilename(index_id,filename));
RETURN_IF_ERROR(btree_file.Construct(filename.CStr()));
RETURN_IF_ERROR(btree_file.Delete());
return MessageEngine::GetInstance()->GetIndexer()->RemoveIndex(index);
}
void RSSBackend::GetAllFolders()
{
Indexer* indexer = MessageEngine::GetInstance()->GetIndexer();
time_t update_frequency = 3600;
Index* index;
for (INT32 it = -1; (index = indexer->GetRange(IndexTypes::FIRST_NEWSFEED, IndexTypes::LAST_NEWSFEED, it)) != NULL; )
{
if (index->GetAccountId() == m_account->GetAccountId() && index->GetSearch())
{
OpString feed_name;
BOOL subscribed = TRUE;
IndexSearch* search = index->GetSearch();
if (search && search->GetSearchText().HasContent())
{
index->GetName(feed_name);
GetAccountPtr()->OnFolderAdded(feed_name, search->GetSearchText(), subscribed, subscribed);
AddToFile(feed_name, search->GetSearchText(), update_frequency, subscribed);
}
}
}
UINT32 next_feed_id;
TRAPD(err, next_feed_id = m_file->ReadIntL("Feeds", "Next Feed ID", 0));
// FIXME: do what if err is bad ?
OpString feed_url, feed_name;
OpString8 current;
if (!current.Reserve(128))
return;
for (UINT32 i = 0; i <= next_feed_id; i++)
{
BOOL subscribed = 0;
op_sprintf(current.CStr(), "Feed %d", i);
TRAP(err, m_file->ReadStringL(current.CStr(), "Name", feed_name);
m_file->ReadStringL(current.CStr(), "URL", feed_url));
// FIXME: do what if err is bad ?
if (feed_url.IsEmpty())
continue;
if (NULL == indexer->GetSubscribedFolderIndex(m_account, feed_url, 0, feed_name, FALSE, FALSE))
{
GetAccountPtr()->OnFolderAdded(feed_name, feed_url, subscribed, subscribed);
}
}
}
OP_STATUS RSSBackend::DeleteFolder(OpString& completeFolderPath)
{
Index* index = MessageEngine::GetInstance()->GetIndexer()->GetSubscribedFolderIndex(m_account, completeFolderPath, '\0', UNI_L(""), FALSE, FALSE);
if (index)
OpStatus::Ignore(RemoveSubscribedFolder(index->GetId()));
int next_feed_id = 0;
RETURN_IF_LEAVE(next_feed_id = m_file->ReadIntL("Feeds", "Next Feed ID", 0));
for (int i = 0; i <= next_feed_id; i++)
{
OpString feed_url;
OpString8 current;
current.Reserve(128);
op_sprintf(current.CStr(), "Feed %d", i);
RETURN_IF_LEAVE(m_file->ReadStringL(current.CStr(), "URL", feed_url));
if (feed_url.CompareI(completeFolderPath) == 0)
{
RETURN_IF_LEAVE(m_file->DeleteSectionL(current.CStr()));
RETURN_IF_LEAVE(m_file->CommitL());
return OpStatus::OK;
}
}
return OpStatus::ERR;
}
OP_STATUS RSSBackend::AddToFile(const OpStringC& feed_name, const OpStringC& feed_url, time_t update_frequency, BOOL subscribed)
{
OpString8 section;
if (!section.Reserve(128))
return OpStatus::ERR_NO_MEMORY;
UINT32 next_feed_id;
RETURN_IF_LEAVE(next_feed_id = m_file->ReadIntL("Feeds", "Next Feed ID", 0));
OpString current_url;
OpString8 current_section;
if (!current_section.Reserve(128))
return OpStatus::ERR_NO_MEMORY;
for (UINT32 i = 0; i <= next_feed_id; i++)
{
op_sprintf(current_section.CStr(), "Feed %d", i);
RETURN_IF_LEAVE(m_file->ReadStringL(current_section.CStr(), "URL", current_url));
if (current_url.CompareI(feed_url) == 0)
{
// already in list
return OpStatus::OK;
}
}
RETURN_IF_LEAVE(m_file->WriteIntL("Feeds", "Next Feed ID", ++next_feed_id);
op_sprintf(section.CStr(), "Feed %d", next_feed_id);
m_file->WriteStringL(section.CStr(), "Name", feed_name);
m_file->WriteStringL(section.CStr(), "URL", feed_url);
m_file->WriteIntL(section.CStr(), "Update Frequency", update_frequency);
m_file->WriteIntL(section.CStr(), "Subscribed", subscribed);
m_file->CommitL());
return OpStatus::OK;
}
OP_STATUS RSSBackend::UpdateFeed(UINT32 index_id)
{
Index* index = MessageEngine::GetInstance()->GetIndexById(index_id);
if (!index)
return OpStatus::ERR;
IndexSearch* search = index->GetSearch();
if (!search)
return OpStatus::ERR;
return UpdateFeed(search->GetSearchText(), FALSE);
}
OP_STATUS RSSBackend::UpdateFeedIfNeeded(Index* index, const OpStringC& url)
{
OP_ASSERT(index != 0);
const time_t update_frequency = index->GetUpdateFrequency();
if (update_frequency != -1)
{
const time_t current_time = MessageEngine::GetInstance()->GetGlueFactory()->GetBrowserUtils()->CurrentTime();
const time_t last_update_time = index->GetLastUpdateTime();
const time_t next_update_time = last_update_time + update_frequency;
if (current_time >= next_update_time)
{
if (url.IsEmpty())
{
IndexSearch* search = index->GetSearch();
if (search && search->GetSearchText().HasContent())
OpStatus::Ignore(UpdateFeed(search->GetSearchText(), FALSE));
}
else
OpStatus::Ignore(UpdateFeed(url, FALSE));
}
}
return OpStatus::OK;
}
OP_STATUS RSSBackend::UpdateFeedIfNeeded(UINT32 index_id, const OpStringC& url)
{
Indexer* indexer = MessageEngine::GetInstance()->GetIndexer();
OP_ASSERT(indexer != 0);
Index* index = indexer->GetIndexById(index_id);
if (index == 0)
return OpStatus::ERR;
RETURN_IF_ERROR(UpdateFeedIfNeeded(index, url));
return OpStatus::OK;
}
#endif //M2_SUPPORT
|
#include<iostream>
using namespace std;
int main(int argc, char const *argv[])
{
string a;
cout<<"Enter String: ";
cin>>a;
cout<<"Enter frame size: ";
int n;
cin>>n;
char f[n];
int j = 0;
int miss = 0;
int hit = 0;
for(int i = 0; i < a.length(); i++)
{
if(f[j] == a[i])
{
hit++;
j = (j+1)%n;
}
else
{
miss++;
f[j] = a[i];
j = (j+1)%n;
}
}
cout<<"Hit: "<<hit<<"\n";
cout<<"Miss: "<<miss<<"\n";
float hit_p = (float)hit*100/a.length();
float miss_p = (float)miss*100/a.length();
cout<<"Hit Percentage: "<<hit_p<<"\n";
cout<<"Miss Percentage: "<<miss_p<<"\n";
return 0;
}
|
// Created on: 1994-03-09
// Created by: Isabelle GRIGNON
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ChFiDS_Stripe_HeaderFile
#define _ChFiDS_Stripe_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <ChFiDS_HData.hxx>
#include <Standard_Integer.hxx>
#include <TopAbs_Orientation.hxx>
#include <Standard_Transient.hxx>
class ChFiDS_Spine;
class Geom2d_Curve;
class ChFiDS_Stripe;
DEFINE_STANDARD_HANDLE(ChFiDS_Stripe, Standard_Transient)
//! Data characterising a band of fillet.
class ChFiDS_Stripe : public Standard_Transient
{
public:
Standard_EXPORT ChFiDS_Stripe();
//! Reset everything except Spine.
Standard_EXPORT void Reset();
const Handle(ChFiDS_HData)& SetOfSurfData() const;
const Handle(ChFiDS_Spine)& Spine() const;
TopAbs_Orientation OrientationOnFace1() const;
TopAbs_Orientation OrientationOnFace2() const;
Standard_Integer Choix() const;
Handle(ChFiDS_HData)& ChangeSetOfSurfData();
Handle(ChFiDS_Spine)& ChangeSpine();
void OrientationOnFace1 (const TopAbs_Orientation Or1);
void OrientationOnFace2 (const TopAbs_Orientation Or2);
void Choix (const Standard_Integer C);
void FirstParameters (Standard_Real& Pdeb, Standard_Real& Pfin) const;
void LastParameters (Standard_Real& Pdeb, Standard_Real& Pfin) const;
void ChangeFirstParameters (const Standard_Real Pdeb, const Standard_Real Pfin);
void ChangeLastParameters (const Standard_Real Pdeb, const Standard_Real Pfin);
Standard_Integer FirstCurve() const;
Standard_Integer LastCurve() const;
void ChangeFirstCurve (const Standard_Integer Index);
void ChangeLastCurve (const Standard_Integer Index);
const Handle(Geom2d_Curve)& FirstPCurve() const;
const Handle(Geom2d_Curve)& LastPCurve() const;
Handle(Geom2d_Curve)& ChangeFirstPCurve();
Handle(Geom2d_Curve)& ChangeLastPCurve();
TopAbs_Orientation FirstPCurveOrientation() const;
TopAbs_Orientation LastPCurveOrientation() const;
void FirstPCurveOrientation (const TopAbs_Orientation O);
void LastPCurveOrientation (const TopAbs_Orientation O);
Standard_Integer IndexFirstPointOnS1() const;
Standard_Integer IndexFirstPointOnS2() const;
Standard_Integer IndexLastPointOnS1() const;
Standard_Integer IndexLastPointOnS2() const;
void ChangeIndexFirstPointOnS1 (const Standard_Integer Index);
void ChangeIndexFirstPointOnS2 (const Standard_Integer Index);
void ChangeIndexLastPointOnS1 (const Standard_Integer Index);
void ChangeIndexLastPointOnS2 (const Standard_Integer Index);
Standard_EXPORT void Parameters (const Standard_Boolean First, Standard_Real& Pdeb, Standard_Real& Pfin) const;
Standard_EXPORT void SetParameters (const Standard_Boolean First, const Standard_Real Pdeb, const Standard_Real Pfin);
Standard_EXPORT Standard_Integer Curve (const Standard_Boolean First) const;
Standard_EXPORT void SetCurve (const Standard_Integer Index, const Standard_Boolean First);
Standard_EXPORT const Handle(Geom2d_Curve)& PCurve (const Standard_Boolean First) const;
Standard_EXPORT Handle(Geom2d_Curve)& ChangePCurve (const Standard_Boolean First);
Standard_EXPORT TopAbs_Orientation Orientation (const Standard_Integer OnS) const;
Standard_EXPORT void SetOrientation (const TopAbs_Orientation Or, const Standard_Integer OnS);
Standard_EXPORT TopAbs_Orientation Orientation (const Standard_Boolean First) const;
Standard_EXPORT void SetOrientation (const TopAbs_Orientation Or, const Standard_Boolean First);
Standard_EXPORT Standard_Integer IndexPoint (const Standard_Boolean First, const Standard_Integer OnS) const;
Standard_EXPORT void SetIndexPoint (const Standard_Integer Index, const Standard_Boolean First, const Standard_Integer OnS);
Standard_EXPORT Standard_Integer SolidIndex() const;
Standard_EXPORT void SetSolidIndex (const Standard_Integer Index);
//! Set nb of SurfData's at end put in DS
Standard_EXPORT void InDS (const Standard_Boolean First, const Standard_Integer Nb = 1);
//! Returns nb of SurfData's at end being in DS
Standard_EXPORT Standard_Integer IsInDS (const Standard_Boolean First) const;
DEFINE_STANDARD_RTTIEXT(ChFiDS_Stripe,Standard_Transient)
protected:
private:
Standard_Real pardeb1;
Standard_Real parfin1;
Standard_Real pardeb2;
Standard_Real parfin2;
Handle(ChFiDS_Spine) mySpine;
Handle(ChFiDS_HData) myHdata;
Handle(Geom2d_Curve) pcrv1;
Handle(Geom2d_Curve) pcrv2;
Standard_Integer myChoix;
Standard_Integer indexOfSolid;
Standard_Integer indexOfcurve1;
Standard_Integer indexOfcurve2;
Standard_Integer indexfirstPOnS1;
Standard_Integer indexlastPOnS1;
Standard_Integer indexfirstPOnS2;
Standard_Integer indexlastPOnS2;
Standard_Integer begfilled;
Standard_Integer endfilled;
TopAbs_Orientation myOr1;
TopAbs_Orientation myOr2;
TopAbs_Orientation orcurv1;
TopAbs_Orientation orcurv2;
};
#include <ChFiDS_Stripe.lxx>
#endif // _ChFiDS_Stripe_HeaderFile
|
#include "engine.h"
std::vector<Color*> Color::table = (std::vector<Color*>)0;
std::vector<Color*> Color::ntable = (std::vector<Color*>)0;
double Color::max_mass = 5.0;
double Color::min_mass = 1.0;
static void grav_exit()
{
if (g_render->ren)
SDL_DestroyRenderer(g_render->ren);
if (g_render->win)
SDL_DestroyWindow(g_render->win);
delete g_render;
SDL_Quit();
exit(0);
}
template <class ttype>
static inline void check_error(ttype check, std::string message)
{
if (check == (ttype)0)
{
std::cerr << message;
grav_exit();
}
}
Color::Color()
{
}
Color::Color(unsigned char nr, unsigned char ng, unsigned char nb)
{
this->r = nr;
this->g = ng;
this->b = nb;
}
void Color::init_color_table()
{
unsigned char r;
unsigned char g;
unsigned char b;
Color::table = std::vector<Color*>(32);
for (int i = 0; i < 32; ++i)
{
r = 255.0;
g = 255 - (float)i * 8.0;
b = 0.0;
Color::table[i] = new Color(r, g, b);
}
}
void Color::ninit_color_table()
{
unsigned char r;
unsigned char g;
unsigned char b;
Color::ntable = std::vector<Color*>(32);
for (int i = 0; i < 32; ++i)
{
r = 0.0;
g = 255 - (float)i * 8.0;
b = 255.0;
Color::ntable[i] = new Color(r, g, b);
}
}
Color::~Color()
{
}
|
#include "gongdou_ptts.hpp"
#include "title_ptts.hpp"
#include "utils.hpp"
#include "mail_ptts.hpp"
#include "chat_ptts.hpp"
namespace nora {
namespace config {
gongdou_ptts& gongdou_ptts_instance() {
static gongdou_ptts inst;
return inst;
}
void gongdou_ptts_set_funcs() {
gongdou_ptts_instance().check_func_ = [] (const auto& ptt) {
if (!check_conditions(ptt.conditions())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " check conditions failed";
}
if (!check_conditions(ptt.target_conditions())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " check target_conditions failed";
}
if (!check_events(ptt.events())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " check events failed";
}
if (!check_events(ptt.target_events())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " check target_events failed";
}
};
gongdou_ptts_instance().modify_func_ = [] (auto& ptt) {
modify_events_by_conditions(ptt.conditions(), *ptt.mutable_events());
};
gongdou_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!verify_conditions(ptt.conditions())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " verify conditions failed";
}
if (!verify_events(ptt.events())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " verify events failed";
}
if (!verify_events(ptt.target_events())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " verify target_events failed";
}
for (const auto& i : ptt.deform().male_pools()) {
for (const auto& j : i.spine()) {
if (!SPINE_PTTS_HAS(j.part(), j.pttid())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " deform spine not exist " << pd::spine_part_Name(j.part()) << " " << j.pttid();
}
}
for (const auto& j : i.huanzhuang()) {
if (!HUANZHUANG_PTTS_HAS(j.part(), j.pttid())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " deform huanzhuang not exist " << pd::huanzhuang_part_Name(j.part()) << " " << j.pttid();
}
}
}
for (const auto& i : ptt.deform().female_pools()) {
for (const auto& j : i.spine()) {
if (!SPINE_PTTS_HAS(j.part(), j.pttid())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " deform spine not exist " << pd::spine_part_Name(j.part()) << " " << j.pttid();
}
}
for (const auto& j : i.huanzhuang()) {
if (!HUANZHUANG_PTTS_HAS(j.part(), j.pttid())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " deform huanzhuang not exist " << pd::huanzhuang_part_Name(j.part()) << " " << j.pttid();
}
}
}
for (const auto& i : ptt.slander()) {
if (!PTTS_HAS(title, i.title())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " slander title not exist " << i.title();
}
if (!PTTS_HAS(system_chat, i.system_chat())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " slander system_chat not exist " << i.system_chat();
}
}
if (ptt.type() == pd::GT_SLANDER && ptt.slander_size() < 2) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " title pool need at least 2 titles";
}
if (ptt.type() == pd::GT_SORCERY && ptt.sorcery().female_icon_pool_size() < 2) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " female icon pool need at least 2 icons";
}
if (ptt.type() == pd::GT_SORCERY && ptt.sorcery().male_icon_pool_size() < 2) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " male icon pool need at least 2 icons";
}
if (ptt.has_gongdou_by_other_mail()) {
if (!PTTS_HAS(mail, ptt.gongdou_by_other_mail())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " gonggou_by_other_mail not exist " << ptt.gongdou_by_other_mail();
}
}
if (ptt.has_system_chat()) {
if (!PTTS_HAS(system_chat, ptt.system_chat())) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " has no system_chat";
}
}
for (auto i : ptt.buffs()) {
if (!PTTS_HAS(buff, i)) {
CONFIG_ELOG << pd::gongdou_type_Name(ptt.type()) << " buff not exist " << i;
}
}
};
}
}
}
|
#include "Stage.h"
#include <string>
#include <iostream>
#include <fstream>
#include "Game.h"
Stage::Stage(const std::string& init_data) {
//-------------------------
// ステージ幅,高さの取得
//-------------------------
width_ = init_data.find('\n');
height_ = 0;
auto w = width_;
while (w != -1) {
data_ += init_data.substr((width_ + 1) * height_, width_);
// ステージ幅が統一されていない場合エラー
if ((w - ((width_ + 1) * height_)) != width_) {
std::cout << "Error!!: Stage data is invalid." << std::endl;
char tmp;
std::cin >> tmp;
exit(EXIT_FAILURE);
}
height_++;
w = init_data.find('\n', (width_ + 1) * height_ + 1);
}
//------------
// 荷物初期化
//------------
auto idx = data_.find(Game::CARGO_CHAR);
while (idx != -1) {
cargoes_.emplace_back(idx % width_, idx / width_);
data_[idx] = Game::SPACE_CHAR;
idx = data_.find(static_cast<char>(Game::CARGO_CHAR), idx + 1);
}
//---------------------
// プレイヤー文字の削除
//---------------------
data_[data_.find(Game::PLAYER_CHAR)] = Game::SPACE_CHAR;
}
char Stage::getObject(int x, int y) const {
//---------
// 範囲確認
//---------
if (width_ * y + x >= data_.size())
return '\0';
//-------------------
// 荷物かどうかの確認
//-------------------
for (const auto& c : cargoes_) {
if (x == c.X() && y == c.Y()) {
// ゴール上にある荷物か確認
if (data_[width_ * y + x] == Game::GOAL_CHAR)
return Game::CARGO_ON_GOAL_CHAR;
else
return Game::CARGO_CHAR;
}
}
return data_[width_ * y + x];
}
bool Stage::moveCargo(int cargo_x, int cargo_y, char direction) {
//-------------
// 移動先の確認
//-------------
int dst_x;
int dst_y;
switch (direction) {
case Game::MOVE_LEFT:
dst_x = cargo_x - 1;
dst_y = cargo_y;
break;
case Game::MOVE_RIGHT:
dst_x = cargo_x + 1;
dst_y = cargo_y;
break;
case Game::MOVE_UP:
dst_x = cargo_x;
dst_y = cargo_y - 1;
break;
case Game::MOVE_DOWN:
dst_x = cargo_x;
dst_y = cargo_y + 1;
break;
}
switch (getObject(dst_x, dst_y)) {
case '\0':
case Game::WALL_CHAR:
case Game::CARGO_CHAR:
case Game::CARGO_ON_GOAL_CHAR:
return false;
break;
}
//-----------
// 荷物を移動
//-----------
for (auto& c : cargoes_) {
if (cargo_x == c.X() && cargo_y == c.Y())
c.move(dst_x, dst_y);
}
return true;
}
bool Stage::isClear() {
for (const auto& c : cargoes_) {
if (data_[width_ * c.Y() + c.X()] != Game::GOAL_CHAR)
return false;
}
return true;
}
void Stage::draw(std::string& drawing_area) {
drawing_area = data_;
for (auto& c : cargoes_)
c.draw(*this, drawing_area);
}
|
#include <stack>
#include <iostream>
using namespace std;
void HeightOfCylinder(int *h,stack<int> s[]) {//to calculate the height of towers
for(int i=0;i<3;i++) {
int sum=0;
stack<int> temp=s[i];//temporary stack
while(!temp.empty()) {
sum+=temp.top();
temp.pop();
}
*(h+i)=sum;//assigning the caluclted height of respected tower
}
}
int main() {
stack<int> s[3];//store towers
int h[3];//store the heights of three towers
int n[3];//store the number of cylinder in each tower
cout<<"enter the input with same pattern given in problem"<<endl;
int input;
cin>>n[0]>>n[1]>>n[2];
for (int i = 0; i < n[0]; i++){//filling tower1 with cylinders
cin>>input;
s[0].push(input);
}
for (int i = 0; i < n[1]; i++) {//filling tower2 with cylinders
cin>>input;
s[1].push(input);
}
for (int i = 0; i < n[2]; i++) {//filling tower3 with cylinders
cin>>input;
s[2].push(input);
}
for (int i = 0; i < 3; i++) {//this loop is to reverse the three stacks
//for the purpose to maintain the pattern of input in given probem
stack<int> temp=s[i];
while(!s[i].empty()) {
s[i].pop();
}
for (int j = 0; j < n[i]; j++) {
s[i].push(temp.top());
temp.pop();
}
}
HeightOfCylinder(h,s);//calculating the height of each tower
while(!(h[0]==h[1]&&h[0]==h[2])) {//logic to solve the given problem is in this loop
if(h[0]>=h[1]&&h[0]>=h[2]) {
h[0]=h[0]-s[0].top();
s[0].pop();
}
else if(h[1]>=h[0]&&h[1]>=h[2]) {
h[1]=h[1]-s[1].top();
s[1].pop();
}
else if(h[2]>=h[0]&&h[2]>=h[1]) {
h[2]=h[2]-s[2].top();
s[2].pop();
}
}
cout<<"output"<<endl;
cout<<h[0]<<endl;//showing output at console
return 0;
}
|
#pragma once
#include "cocos2d.h"
USING_NS_CC;
class SelectScene : public Scene {
public:
static SelectScene* createScene();
bool init() override;
CREATE_FUNC(SelectScene);
};
|
#include "stdafx.h"
#include <wrl/client.h>
#include "ApplicationMetadata.h"
#include "ziparchive.h"
#include "helper.h"
using doo::metrodriver::ApplicationMetadata;
using Windows::Data::Xml::Dom::XmlDocument;
using Windows::Data::Xml::Dom::XmlLoadSettings;
// instantiate Metadata from an extracted manifest on the disk
ApplicationMetadata^ ApplicationMetadata::CreateFromManifest(Platform::String^ manifestPath) {
std::ifstream input(manifestPath->Data(), std::ifstream::in);
if (!input.is_open()) {
throw ref new Platform::InvalidArgumentException(L"Could not open manifest");
}
// read the file into a string
std::string str((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
input.close();
return ref new ApplicationMetadata(str);
}
#define THROW_ERROR(msg) { \
wchar_t* errorMsg = msg;\
_tprintf_s(errorMsg); \
throw ref new Platform::InvalidArgumentException(ref new Platform::String(errorMsg));\
}
// instantiate Metadata from an appx file
ApplicationMetadata^ ApplicationMetadata::CreateFromAppx(Platform::String^ appxPath) {
try {
Microsoft::WRL::ComPtr<IAppxFactory> appxFactory;
auto hr = CoCreateInstance(
__uuidof(AppxFactory),
NULL,
CLSCTX_INPROC_SERVER,
__uuidof(IAppxFactory),
(LPVOID*)(&appxFactory));
// Create a stream over the input Appx package
Microsoft::WRL::ComPtr<IStream> inputStream;
if (SUCCEEDED(hr)) {
hr = SHCreateStreamOnFileEx(
appxPath->Data(),
STGM_READ | STGM_SHARE_EXCLUSIVE,
0, // default file attributes
FALSE, // do not create new file
NULL, // no template
&inputStream);
}
Microsoft::WRL::ComPtr<IAppxPackageReader> packageReader;
if (SUCCEEDED(hr)) {
hr = appxFactory->CreatePackageReader(
inputStream.Get(),
&packageReader);
}
Microsoft::WRL::ComPtr<IAppxManifestReader> manifestReader;
if (SUCCEEDED(hr)) {
hr = packageReader->GetManifest(&manifestReader);
}
return ref new ApplicationMetadata(manifestReader);
} catch (Platform::COMException^ e) {
_tprintf_s(L"Error decompressing appx file from %s: %s\n", appxPath->Data(), e->Message->Data());
throw e;
}
}
ApplicationMetadata::ApplicationMetadata(Microsoft::WRL::ComPtr<IAppxManifestReader> manifestReader) {
Microsoft::WRL::ComPtr<IAppxManifestApplicationsEnumerator> appEnumerator;
auto hr = manifestReader->GetApplications(&appEnumerator);
if (SUCCEEDED(hr)) {
Microsoft::WRL::ComPtr<IAppxManifestApplication> app;
hr = appEnumerator->GetCurrent(&app);
if (SUCCEEDED(hr)) {
LPWSTR appUserModelId;
hr = app->GetStringValue(L"id", &appUserModelId);
if (SUCCEEDED(hr)) {
appId = ref new Platform::String(appUserModelId);
CoTaskMemFree(appUserModelId);
}
}
}
Microsoft::WRL::ComPtr<IAppxManifestPackageId> packageId;
hr = manifestReader->GetPackageId(&packageId);
if (SUCCEEDED(hr)) {
APPX_PACKAGE_ARCHITECTURE arch;
hr = packageId->GetArchitecture(&arch);
if (SUCCEEDED(hr)) {
switch (arch) {
case APPX_PACKAGE_ARCHITECTURE_ARM:
architecture = "ARM";
break;
case APPX_PACKAGE_ARCHITECTURE_X64:
architecture = "x64";
break;
case APPX_PACKAGE_ARCHITECTURE_X86:
architecture = "x86";
break;
}
}
LPWSTR appxName;
packageId->GetName(&appxName);
packageName = ref new Platform::String(appxName);
CoTaskMemFree(appxName);
LPWSTR appxPublisher;
packageId->GetPublisher(&appxPublisher);
publisher = ref new Platform::String(appxPublisher);
CoTaskMemFree(appxPublisher);
UINT64 appxVersion;
packageId->GetVersion(&appxVersion);
WORD revision = (appxVersion);
WORD build = (appxVersion >> 0x10);
WORD minor = (appxVersion >> 0x20);
WORD major = (appxVersion >> 0x30);
std::wstringstream versionBuilder;
versionBuilder << major << L"." << minor << L"." << build << L"." << revision;
packageVersion = ref new Platform::String(versionBuilder.str().c_str());
LPWSTR appxPackageFullId;
hr = packageId->GetPackageFullName(&appxPackageFullId);
if (SUCCEEDED(hr)) {
packageFullName = ref new Platform::String(appxPackageFullId);
CoTaskMemFree(appxPackageFullId);
}
}
}
// read metadata from the manifest
ApplicationMetadata::ApplicationMetadata(const std::string& xml) {
auto manifest = ref new XmlDocument();
// skip the BOM (first three bytes) if it exists
auto platformString = stringToPlatformString(xml[0] == -17 ? xml.data()+3 : xml.data());
manifest->LoadXml(platformString);
auto identityNode = manifest->SelectSingleNodeNS("//mf:Package/mf:Identity", "xmlns:mf=\"http://schemas.microsoft.com/appx/2010/manifest\"");
packageName = identityNode->Attributes->GetNamedItem("Name")->NodeValue->ToString();
packageVersion = identityNode->Attributes->GetNamedItem("Version")->NodeValue->ToString();
publisher = identityNode->Attributes->GetNamedItem("Publisher")->NodeValue->ToString();
architecture = identityNode->Attributes->GetNamedItem("ProcessorArchitecture")->NodeValue->ToString();
auto applicationNode = manifest->SelectSingleNodeNS("//mf:Package/mf:Applications/mf:Application[1]", "xmlns:mf=\"http://schemas.microsoft.com/appx/2010/manifest\"");
appId = applicationNode ? applicationNode->Attributes->GetNamedItem("Id")->NodeValue->ToString() : nullptr;
}
|
#include "receiver.h"
#include <QDebug>
Receiver::Receiver(QObject *parent) :
QObject(parent)
{
}
void Receiver::receiveFromQml(QString longi, QString lat) {
qDebug() << "Received in C++ from QML:" << longi <<" " <<lat;
}
|
#ifndef MENUCHECKBOX_H
#define MENUCHECKBOX_H
#include "MenuCaller.h"
class MenuCheckbox : public MenuCaller<void, bool>
{
public:
MenuCheckbox(std::string text, bool checked, Caller<void, bool>* calLOnClick = 0, UINT id = 0);
virtual ~MenuCheckbox();
void onClick();
bool insertControl(HMENU insertInto, UINT index);
bool updateControl(HMENU insertInto, UINT index);
private:
MenuCheckbox();
bool checked;
};
#endif // MENUCHECKBOX_H
|
#include "X11/Xlib.h"
#include "X11/Xutil.h"
#include "X11/Xos.h"
#include "stdlib.h"
#include "stdio.h"
Display *dis;
int screen;
Window win;
GC gc;
void init_x() {
/* get the colors black and white (see section for details) */
unsigned long black,white;
/* use the information from the environment variable DISPLAY
to create the X connection:
*/
dis=XOpenDisplay((char *)0);
screen=DefaultScreen(dis);
black=BlackPixel(dis,screen), /* get color black */
white=WhitePixel(dis, screen); /* get color white */
/* once the display is initialized, create the window.
This window will be have be 200 pixels across and 300 down.
It will have the foreground white and background black
*/
win=XCreateSimpleWindow(dis,DefaultRootWindow(dis),0,0,
200, 300, 5, white, black);
/* here is where some properties of the window can be set.
The third and fourth items indicate the name which appears
at the top of the window and the name of the minimized window
respectively.
*/
XSetStandardProperties(dis,win,"My Window","HI!",None,NULL,0,NULL);
/* this routine determines which types of input are allowed in
the input. see the appropriate section for details...
*/
XSelectInput(dis, win, ExposureMask|ButtonPressMask|KeyPressMask);
/* create the Graphics Context */
gc=XCreateGC(dis, win, 0,0);
/* here is another routine to set the foreground and background
colors _currently_ in use in the window.
*/
XSetBackground(dis,gc,white);
XSetForeground(dis,gc,white);
/* clear the window and bring it on top of the other windows */
XClearWindow(dis, win);
XMapRaised(dis, win);
};
void close_x() {
/* it is good programming practice to return system resources to the
system...
*/
XFreeGC(dis, gc);
XDestroyWindow(dis,win);
XCloseDisplay(dis);
exit(1);
}
int main() {
init_x();
XEvent event; /* the XEvent declaration !!! */
KeySym key; /* a dealie-bob to handle KeyPress Events */
char text[255]; /* a char buffer for KeyPress Events */
/* look for events forever... */
while(1) {
/* get the next event and stuff it into our event variable.
Note: only events we set the mask for are detected!
*/
XNextEvent(dis, &event);
if (event.type==Expose && event.xexpose.count==0) {
/* the window was exposed redraw it! */
// redraw();
}
if (event.type==KeyPress&&
XLookupString(&event.xkey,text,255,&key,0)==1) {
/* use the XLookupString routine to convert the invent
KeyPress data into regular text. Weird but necessary...
*/
if (text[0]=='q') {
close_x();
}
if (text[0] == 'l') {
//int x1 = 5;
//int x2 = 5;
//int y1 = 50;
//int y2 = 50;
//XDrawLine(dis,win,gc, x1,y1, x2,y2);
XCreatei
}
printf("You pressed the %c key!\n",text[0]);
}
if (event.type==ButtonPress) {
/* tell where the mouse Button was Pressed */
printf("You pressed a button at (%i,%i)\n",
event.xbutton.x,event.xbutton.y);
}
}
close_x();
}
|
#include<iostream>
#include<stdlib.h>
#include<pthread.h>
#include <time.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
#include <unistd.h>
#include <signal.h>
using namespace std ;
#define SHARED 0
#define BUFSIZE 20
int terminatethreads=0;
sem_t *Sempty, *Sfull, *Sflag; /* the semaphore descriptors */
char sem1[] = "/semEmpty"; //The names for the semaphores
char sem2[] = "/semFull";
//char sem3[] = "/semFlag";
int buf[BUFSIZE]; /* shared buffer */
int mycount;
#include "producer.h"
#include "consumer.h"
/*static void sig_alarm(int signo)
{
cout << "\nWe got the Signal Alarm, Terminating the threads...\n"<< endl;
terminatethreads=1;
return;
}
*/
int main(int argc, char *argv[])
{
int ans;
time_t now;
pthread_t pid, cid;
// time (&now);
// srand (now);
// if (signal (SIGALRM, sig_alarm) == SIG_ERR) {
// cout << "The signal function returned an error" << endl;
// exit (1);
// }
//Here we set the alarm to specified seconds.
// alarm (atoi(argv[1]));
// cout << "Alarm set. Now for semaphores" << endl;
// Sflag = sem_open (sem3, O_CREAT, 660, 1);
Sfull = sem_open (sem2, O_CREAT, 0666, 0);
Sempty = sem_open (sem1, O_CREAT, 0666, BUFSIZE);
mycount = 0;
cout << "main started" << endl;
pthread_create(&pid, 0, Producer, NULL);
pthread_create(&cid, 0, Consumer, NULL);
cout << "Created both threads" << endl;
pthread_join(pid, NULL);
pthread_join(cid, NULL);
cout << "The number of items still in the buffer is " << mycount << endl;
sem_getvalue(Sfull, &ans);
cout << "The value of Sfull is " << ans << endl;
// sem_close(Sflag);
sem_close(Sfull);
sem_close(Sempty);
sem_unlink(sem1);
sem_unlink(sem2);
// sem_unlink(sem3);
cout << "Main done\n" << endl;
return 0;
}
|
#include "VeritasEngine.h"
#include "Drawable.h"
#include "ConstantBuffers.h"
std::unique_ptr<VertexConstantBuffer<TransformCbuf::Transforms>> TransformCbuf::pVcbuf;
TransformCbuf::TransformCbuf(VeritasEngine& gfx, const Drawable& parent, UINT slot)
{
pParent = &parent;
if (!pVcbuf)
{
pVcbuf = std::make_unique<VertexConstantBuffer<Transforms>>(gfx, slot);
}
}
void TransformCbuf::Bind(VeritasEngine& gfx)
{
UpdateBindImpl(gfx, GetTransforms(gfx));
}
void TransformCbuf::UpdateBindImpl(VeritasEngine& gfx, const Transforms& tf) noexcept
{
assert(pParent != nullptr);
pVcbuf->Update(gfx, tf);
pVcbuf->Bind(gfx);
}
TransformCbuf::Transforms TransformCbuf::GetTransforms(VeritasEngine& gfx) noexcept
{
assert(pParent != nullptr);
const auto modelView = pParent->GetTransformXM() * gfx.GetCamera();
return { modelView,
modelView *
gfx.GetProjection()
};
}
|
// Copyright PixelSpawn 2020
#include "PressurePlateDepress.h"
#include "Components/AudioComponent.h"
#include "Components/StaticMeshComponent.h"
#include "GameFramework/Actor.h"
// Sets default values for this component's properties
UPressurePlateDepress::UPressurePlateDepress()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UPressurePlateDepress::BeginPlay()
{
Super::BeginPlay();
CheckPressurePlateVolume();
CheckMesh();
FindAudioComponent();
}
// Called every frame
void UPressurePlateDepress::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (PressurePlateVolume && TotalMassOfActors() > MassToOpenDoor)
{
LowerPressurePlate(DeltaTime);
}
else
{
if (GetWorld()->GetTimeSeconds() - PressurePlateLastDepressed > PressurePlateRaiseDelay)
{
RaisePressurePlate(DeltaTime);
}
}
GetWorld()->GetTimeSeconds();
}
void UPressurePlateDepress::CheckPressurePlateVolume()
{
if (!PressurePlateVolume)
{
UE_LOG(LogTemp, Error, TEXT("%s has the PressurePlateDepress component on it, but no Pressure Plate set!"), *GetOwner()->GetName());
}
}
void UPressurePlateDepress::CheckMesh()
{
for (auto Component : GetOwner()->GetComponents())
{
if (Component->GetName() == "SM_Button")
{
Mesh = Cast<UStaticMeshComponent>(Component);
break;
}
}
if (!Mesh)
{
UE_LOG(LogTemp, Error, TEXT("No SM_Button Static Mesh component found on %s"), *GetOwner()->GetName());
}
else
{
UE_LOG(LogTemp, Warning, TEXT("%s SM found on %s"), *Mesh->GetName(), *GetOwner()->GetName());
InitialPosition = Mesh->GetComponentLocation().Z;
CurrentPosition = InitialPosition;
TargetPosition += InitialPosition;
}
}
void UPressurePlateDepress::LowerPressurePlate(float DeltaTime)
{
if (!Mesh) {return;}
CurrentPosition = (FMath::FInterpTo(CurrentPosition, TargetPosition, DeltaTime, PressurePlateSpeed));
FVector PressurePlatePosition = Mesh->GetComponentLocation();
PressurePlatePosition.Z = CurrentPosition;
Mesh->SetWorldLocation(PressurePlatePosition);
RaiseAudioPlayed = false;
if (!AudioComponent){return;}
if (!LowerAudioPlayed)
{
AudioComponent->Play(0.f);
LowerAudioPlayed = true;
}
}
void UPressurePlateDepress::RaisePressurePlate(float DeltaTime)
{
if (!WillRaise) {return;}
if (!Mesh) {return;}
CurrentPosition = (FMath::FInterpTo(CurrentPosition, InitialPosition, DeltaTime, PressurePlateSpeed));
FVector PressurePlatePosition = Mesh->GetComponentLocation();
PressurePlatePosition.Z = CurrentPosition;
Mesh->SetWorldLocation(PressurePlatePosition);
LowerAudioPlayed = false;
if (!AudioComponent){return;}
if (!RaiseAudioPlayed)
{
AudioComponent->Play(0.f);
RaiseAudioPlayed = true;
}
}
float UPressurePlateDepress::TotalMassOfActors() const
{
float TotalMass = 0.f;
// Find all overlapping Actors
TArray<AActor*> OverlappingActors;
if (!PressurePlateVolume){return TotalMass;} // Protecting against a nullptr
PressurePlateVolume->GetOverlappingActors(OUT OverlappingActors);
// Add up their masses
for (AActor* OverlappingActor : OverlappingActors)
{
if (OverlappingActor->GetName().Contains("PressurePlate"))
{
continue; // ignore PressurePlate in mass calculation
}
else
{
TotalMass += OverlappingActor->FindComponentByClass<UPrimitiveComponent>()->GetMass();
}
}
return TotalMass;
}
void UPressurePlateDepress::FindAudioComponent()
{
AudioComponent = GetOwner()->FindComponentByClass<UAudioComponent>();
if (!AudioComponent)
{
UE_LOG(LogTemp, Error, TEXT("Audio Component missing on %s"), *GetOwner()->GetName());
}
else
{
UE_LOG(LogTemp, Error, TEXT("Audio Component found on %s"), *GetOwner()->GetName());
}
}
|
#include "Estoque.hpp"
#ifndef ESTOQUECAMISETAS_HPP_
#define ESTOQUECAMISETAS_HPP_
class EstoqueCamisetas: public Estoque{
public:
//Construtor
EstoqueCamisetas();
//Destrutor
~EstoqueCamisetas();
//Funções para manutenção do estoque.
void registraProduto(int qntd, char nome[50], float preco); //Exemplo Polimorfismo - Checar implemetação do método em EstoqueCamisetas.cpp
friend class Estoque;
friend class Cliente;
};
#endif
|
#include "CCDirector.h"
#include "CCGreePlatform.h"
#include "CCGreeUser.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxGreePlatform.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxGreeUser.h"
#include "jni/JniHelper.h"
#define JAVAVM cocos2d::JniHelper::getJavaVM()
using namespace cocos2d;
NS_CC_GREE_EXT_BEGIN
static bool getEnv(JNIEnv **env){
bool bRet = false;
do{
if (JAVAVM->GetEnv((void**)env, JNI_VERSION_1_4) != JNI_OK){
CCLog("Failed to get the environment using GetEnv()");
break;
}
if (JAVAVM->AttachCurrentThread(env, 0) < 0){
CCLog("Failed to get the environment using AttachCurrentThrea d()");
break;
}
bRet = true;
} while (0);
return bRet;
}
CCGreeUser::CCGreeUser(void* user){
JNIEnv *pEnv = 0;
getEnv(&pEnv);
mGreeUser = (void*)(pEnv->NewGlobalRef((jobject)user));
}
CCGreeUser::~CCGreeUser(){
JNIEnv *pEnv = 0;
getEnv(&pEnv);
pEnv->DeleteGlobalRef((jobject)mGreeUser);
}
CCString *CCGreeUser::getNickname(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getNickname, mGreeUser);
}
CCString *CCGreeUser::getDisplayName(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getDisplayName, mGreeUser);
}
CCString *CCGreeUser::getId(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getUserId, mGreeUser);
}
CCString *CCGreeUser::getRegion(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getRegion, mGreeUser);
}
CCString *CCGreeUser::getSubregion(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getSubregion, mGreeUser);
}
CCString *CCGreeUser::getLanguage(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getLanguage, mGreeUser);
}
CCString *CCGreeUser::getTimezone(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getTimezone, mGreeUser);
}
CCString *CCGreeUser::getAboutMe(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getAboutMe, mGreeUser);
}
CCString *CCGreeUser::getBirthday(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getBirthday, mGreeUser);
}
CCString *CCGreeUser::getGender(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getGender, mGreeUser);
}
CCString *CCGreeUser::getAge(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getAge, mGreeUser);
}
CCString *CCGreeUser::getBloodType(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getBloodType, mGreeUser);
}
CCString *CCGreeUser::getUserHash(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getUserHash, mGreeUser);
}
CCString *CCGreeUser::getUserType(){
CALL_JNI_STRING_METHOD_WITHOBJECT(getUserType, mGreeUser);
}
bool CCGreeUser::getHasApp(){
CALL_JNI_BOOL_METHOD_WITHOBJECT(getHasApp, mGreeUser);
}
int CCGreeUser::getUserGrade(){
CALL_JNI_BOOL_METHOD_WITHOBJECT(getUserGrade, mGreeUser);
}
bool CCGreeUser::loadThumbnail(int size){
bool ret = false;
if(mGreeUser != NULL){
ret = loadUserThumbnailJni((jobject)mGreeUser, size, (void *)this);
}
return ret;
}
void CCGreeUser::loadFriends(int offset, int count){
if(mGreeUser != NULL){
loadFriendsJni((jobject)mGreeUser, offset, count, (void *)this);
}
}
void CCGreeUser::loadIgnoredUserIds(int offset, int count){
if(mGreeUser != NULL){
loadIgnoredUserIdsJni((jobject)mGreeUser, offset, count, (void *)this);
}
}
void CCGreeUser::isIgnoringUserWithId(const char *pid){
if(mGreeUser != NULL){
isIgnoringUserWithIdJni((jobject)mGreeUser, pid, (void *)this);
}
}
void CCGreeUser::loadUserWithId(const char *pid)
{
loadUserWithIdJni(pid);
}
// Callback Handling
void CCGreeUser::handleLoadThumbnailOnSuccess(int *arr, int width, int height){
CCImage* img = new CCImage();
img->autorelease();
img->initWithImageData((void *)arr, width * height * 4, CCImage::kFmtRawData, width, height);
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
delegate->loadThumbnailSuccess(this, img);
}
}
void CCGreeUser::handleLoadThumbnailOnFailure(int responseCode, const char *response){
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
CCString *str = new CCString(response);
str->autorelease();
delegate->loadThumbnailFailure(this, responseCode, str);
}
}
void CCGreeUser::handleLoadFriendsOnSuccess(int index, int count, void **users)
{
CCArray *userArray = new CCArray();
for(int i = 0; i < count; i++){
CCGreeUser* user = new CCGreeUser(users[i]);
user->autorelease();
userArray->addObject(user);
}
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
delegate->loadFriendsSuccess(this, index, count, userArray);
}
}
void CCGreeUser::handleLoadFriendsOnFailure(int responseCode, const char *response){
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
CCString *str = new CCString(response);
str->autorelease();
delegate->loadFriendsFailure(this, responseCode, str);
}
}
void CCGreeUser::handleLoadUserWithIdOnSuccess(int index, int count, void **users)
{
CCArray *userArray = new CCArray();
for(int i = 0; i < count; i++){
CCGreeUser *user = new CCGreeUser(users[i]);
user->autorelease();
//TODO : Want to remove retain().
// But in such case, developer have to issue retain() by himself to use
// object outside the function where it has gotten
// Furthermore some of current callbacks are including correspoding
// object information and to get them developer also have to issue retain()
// not to be automatically released.
user->retain();
userArray->addObject(user);
}
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
delegate->loadUserWithIdSuccess(index, count, userArray);
}
}
void CCGreeUser::handleLoadUserWithIdOnFailure(int responseCode, const char *response){
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
CCString *str = new CCString(response);
str->autorelease();
delegate->loadUserWithIdFailure(responseCode, str);
}
}
void CCGreeUser::handleLoadIgnoredUserIdsOnSuccess(int index, int count, const char **users)
{
CCArray *userStringArray = new CCArray();
for(int i = 0; i < count; i++){
CCString *str = new CCString(users[i]);
str->autorelease();
userStringArray->addObject(str);
}
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
delegate->loadIgnoredUserIdsSuccess(this, index, count, userStringArray);
}
}
void CCGreeUser::handleLoadIgnoredUserIdsOnFailure(int responseCode, const char *response){
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
CCString *str = new CCString(response);
str->autorelease();
delegate->loadIgnoredUserIdsFailure(this, responseCode, str);
}
}
void CCGreeUser::handleIsIgnoringUserWithIdOnSuccess(int index, int count, const char **users)
{
CCArray *userStringArray = new CCArray();
for(int i = 0; i < count; i++){
CCString *str = new CCString(users[i]);
str->autorelease();
userStringArray->addObject(str);
}
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
delegate->isIgnoringUserWithIdSuccess(this, index, count, userStringArray);
}
}
void CCGreeUser::handleIsIgnoringUserWithIdOnFailure(int responseCode, const char *response){
CCGreeUserDelegate *delegate = CCGreePlatform::getUserDelegate();
if(delegate != NULL){
CCString *str = new CCString(response);
str->autorelease();
delegate->isIgnoringUserWithIdFailure(this, responseCode, str);
}
}
NS_CC_GREE_EXT_END
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2011-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_OTL_RANGE_H
#define MODULES_OTL_RANGE_H
/**
* A generic range class that is based on iterators.
*
* A range can be used to iterate over a range [begin, end) of elements.
*
* Example:
*
* @code
* OtlList<int> list = ...;
* OtlRange< OtlList<int>::ConstIterator > range;
* for (range(list.Begin(), list.End()); range; ++range)
* print("value: %d\n", *range);
* @endcode
*
* @note A range is not a copy of the original data, it is only a view onto the
* data. If the code using a range modifies the current item (taken that
* \c _Iterator allows to modify the current item), then the item is
* modified in the original collection.
*
* @note It is possible to remove the current beginning of the range while
* iterating the range.
*/
template<typename _Iterator, typename _ConstIterator=_Iterator>
class OtlRange
{
public:
/// The iterator type that is used for the beginning of the range.
typedef _Iterator Iterator;
/**
* The iterator type that is used for the end of the range.
*
* This iterator type must be compatible with _Iterator for comparison.
*/
typedef _ConstIterator ConstIterator;
/// A reference of the type the \c Iterator iterates over.
typedef typename _Iterator::Reference Reference;
/**
* A const reference of the type the \c Iterator iterates over.
*
* If the iterator's Reference type is <code>T&</code>, then the iterator's
* ConstReference type should be defined as <code>const T&</code>.
*/
typedef typename _Iterator::ConstReference ConstReference;
/// A pointer to the type the \c Iterator iterates over.
typedef typename _Iterator::Pointer Pointer;
/// The default constructor creates an empty range.
OtlRange() { }
/**
* Creates a range from the specified \c begin until (and excluding) the
* specified \c end.
*
* @note The caller must ensure that both \c begin and \c end are in the
* same collection, i.e. that after some finite number of calls to
* the ++ operator on \c begin, \c begin equals \c end.
*
* @note This condition also means that the specified \c end shall not be
* removed from its collection.
*
* @param begin is the iterator that points to the first element of the
* range.
* @param end is the iterator that points past the last element of the
* range. The end is excluded from the range.
*/
OtlRange(const _Iterator& begin, const _ConstIterator& end)
: m_current(begin)
, m_end(end)
{ }
/// Returns true if the range is empty.
bool IsEmpty() const { return m_current == m_end; }
/// Returns true if the range is not empty.
operator bool() const { return !IsEmpty(); }
/// Returns the current beginning of the range.
Iterator Current() { return m_current; }
const Iterator& Current() const { return m_current; }
/// Returns the end of the range.
const ConstIterator& End() const { return m_end; }
/**
* The dereference operator returns a reference of the item at the
* beginning of the range.
*
* @note This method must only be called if the range is not empty.
*/
Reference operator*() const { OP_ASSERT(!IsEmpty()); return *m_current; }
/**
* The pointer operator returns a pointer to the item at the beginning of
* the range.
*
* @note This method must only be called if the range is not empty.
*/
Pointer operator->() const { OP_ASSERT(!IsEmpty()); return &(operator*()); }
/**
* The increment operator advances the Current() iterator by one.
*
* @note This method must only be called if the range is not empty.
* @return A reference to this range. Note that the range may be empty after
* this operator was called.
*/
OtlRange& operator++() { OP_ASSERT(!IsEmpty()); ++m_current; return *this; }
/**
* Search for the specified item in this range.
*
* If the item is found, true is returned and the Begin() of the range
* points to the found item. If the item is not found, false is returned
* and the range will be empty.
*
* @note This method uses O(n). Depending on the underlying collection it
* may be better to use the collection's find method. E.g. a tree or
* a hash table implement a search algorithm that is significantly
* faster.
*
* @param item is the value to find.
* @return true if the specified item was found and false if it was not
* found.
*/
bool FindItem(ConstReference item)
{
for (; !IsEmpty() && *(*this) != item; ++(*this)) {}
return !IsEmpty();
}
private:
/// Points to the beginning of the range.
Iterator m_current;
/// Points to the end of the range.
ConstIterator m_end;
}; // OtlRange
#endif // MODULES_OTL_RANGE_H
|
#pragma once
#include "Keng/Core/IRefCountObject.h"
#include "Keng/GraphicsCommon/FwdDecl.h"
namespace keng::graphics::gpu
{
class ISampler : public core::IRefCountObject
{
public:
virtual void AssignToPipeline(const ShaderType& shaderType, size_t index) = 0;
};
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;
class PermutationSignature {
public:
int
getmin(vector<bool> &s,int pop)
{
int cnt = 0;
for (int i=0; i<s.size(); ++i) {
if (!s[i]) {
if (cnt == pop) {
return i+1;
}
++cnt;
}
}
return -1;
}
vector <int>
reconstruct(string signature)
{
int n = (int)signature.size()+1;
vector<bool> s(n);
vector<int> ans;
for (int i=0; i<n-1; ++i) {
int p = getmin(s,0);
if (signature[i]=='D') {
int pop = 1;
for (int j=i+1; j<n-1; ++j) {
if (signature[j]=='D') ++pop;
else break;
}
p = getmin(s, pop);
if (p==-1) return vector<int>();
}
ans.push_back(p);
s[p-1]=true;
}
ans.push_back(getmin(s, 0));
return ans;
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2006 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"
#if defined(SVG_SUPPORT) && defined(SVG_DOM) && defined(SVG_TINY_12)
#include "modules/svg/src/svgpch.h"
#include "modules/svg/src/svgdom/svgdompathimpl.h"
SVGDOMPathImpl::SVGDOMPathImpl(OpBpath* path) :
m_path(path)
{
SVGObject::IncRef(m_path);
}
/* virtual */
SVGDOMPathImpl::~SVGDOMPathImpl()
{
SVGObject::DecRef(m_path);
}
/* virtual */ const char*
SVGDOMPathImpl::GetDOMName()
{
return "SVGPath";
}
/* virtual */ OP_STATUS
SVGDOMPathImpl::GetSegment(unsigned long cmdIndex, short& outsegment)
{
SVGPathSeg* seg = m_path->GetPathSeg(cmdIndex);
if(seg)
{
switch(seg->info.type)
{
case SVGPathSeg::SVGP_CLOSE:
outsegment = SVGDOMPath::SVGPATH_CLOSE;
return OpStatus::OK;
case SVGPathSeg::SVGP_MOVETO_ABS:
outsegment = SVGDOMPath::SVGPATH_MOVETO;
return OpStatus::OK;
case SVGPathSeg::SVGP_LINETO_ABS:
outsegment = SVGDOMPath::SVGPATH_LINETO;
return OpStatus::OK;
case SVGPathSeg::SVGP_CURVETO_CUBIC_ABS:
outsegment = SVGDOMPath::SVGPATH_CURVETO;
return OpStatus::OK;
case SVGPathSeg::SVGP_CURVETO_QUADRATIC_ABS:
outsegment = SVGDOMPath::SVGPATH_QUADTO;
return OpStatus::OK;
default:
OP_ASSERT(!"This segment type is not supported in normalized lists. Who put it here?");
break;
}
}
return OpStatus::ERR;
}
/* virtual */ OP_STATUS
SVGDOMPathImpl::GetSegmentParam(unsigned long cmdIndex, unsigned long paramIndex, double& outparam)
{
SVGPathSeg* seg = m_path->GetPathSeg(cmdIndex);
if(seg)
{
switch(seg->info.type)
{
case SVGPathSeg::SVGP_LINETO_ABS:
case SVGPathSeg::SVGP_MOVETO_ABS:
if(paramIndex == 0)
{
outparam = seg->x.GetFloatValue();
return OpStatus::OK;
}
else if(paramIndex == 1)
{
outparam = seg->y.GetFloatValue();
return OpStatus::OK;
}
break;
case SVGPathSeg::SVGP_CURVETO_CUBIC_ABS:
switch(paramIndex)
{
case 0:
outparam = seg->x1.GetFloatValue();
return OpStatus::OK;
case 1:
outparam = seg->y1.GetFloatValue();
return OpStatus::OK;
case 2:
outparam = seg->x2.GetFloatValue();
return OpStatus::OK;
case 3:
outparam = seg->y2.GetFloatValue();
return OpStatus::OK;
case 4:
outparam = seg->x.GetFloatValue();
return OpStatus::OK;
case 5:
outparam = seg->y.GetFloatValue();
return OpStatus::OK;
default:
break;
}
break;
case SVGPathSeg::SVGP_CURVETO_QUADRATIC_ABS:
switch(paramIndex)
{
case 0:
outparam = seg->x1.GetFloatValue();
return OpStatus::OK;
case 1:
outparam = seg->y1.GetFloatValue();
return OpStatus::OK;
case 2:
outparam = seg->x.GetFloatValue();
return OpStatus::OK;
case 3:
outparam = seg->y.GetFloatValue();
return OpStatus::OK;
default:
break;
}
break;
case SVGPathSeg::SVGP_CLOSE:
break;
default:
OP_ASSERT(!"This segment type is not supported in normalized lists. Who put it here?");
break;
}
}
return OpStatus::ERR;
}
#endif // SVG_SUPPORT && SVG_DOM && SVG_TINY_12
|
//
// Created by litalfel@wincs.cs.bgu.ac.il on 16/01/2020.
//
#include <thread>
#include "../include/connectionHandler.h"
#include "../include/StompProtocol.h"
#include "../include/User.h"
#include <iostream>
vector<string> make_vector(string basicString);
using namespace std;
//login 127.0.0.1:6666 lital fel
// login 127.0.0.1:6666 bob alice
// login 127.0.0.1:6666 ofir ben
int main(int argc, const char *argv[]) {
cout << "enter command:" << endl;
string input;
getline(cin, input);
vector<string> messageVector = make_vector(input);
if (messageVector.size() == 4) {
if (messageVector[0] == "login") {
string commend = "CONNECT";
Header acceptVersion = Header("accept-version", "1.2");
int pos = messageVector[1].find(":");
Header host = Header("host", messageVector[1].substr(0, pos));
Header name = Header("login", messageVector[2]);
Header pass = Header("passcode", messageVector[3]);
string host1 = messageVector[1].substr(0, pos);
short port = stoi(messageVector[1].substr(pos + 1));
vector<Header> headers;
headers.push_back(acceptVersion);
headers.push_back(host);
headers.push_back(name);
headers.push_back(pass);
Frame frame = Frame(commend, headers, "");
string toSend = frame.frameToString();
ConnectionHandler *connectionHandler = new ConnectionHandler(host1, port);
User *user=new User(messageVector[2]);
StompProtocol proto = StompProtocol(user,connectionHandler);
if (connectionHandler->connect()) {
connectionHandler->sendLine(toSend);
cout<<"message was sent:"+toSend<<endl;
string response;
if (connectionHandler->getLine(response)) {
cout << "server got string:\n"+ response << endl;
if (response.substr(0, response.find('\n')) != "ERROR") {
cout << "Login successful." << endl;
// proto.connectUser();//user is connected
thread thread1(&StompProtocol::runKeyboard, &proto);
thread thread2(&StompProtocol::runSocket, &proto);
thread1.join();
thread2.join();
cout << "about to close connection" << endl;
cout << "deleting..." << endl;
}
}
} else
cout << "Could not connect to server" << endl;
delete (connectionHandler);
} else {
cout << "wrong input" << endl;
return 0;
}
} else {
cout << "wrong input" << endl;
return 0;
}
}
vector<string> make_vector(string s) {
string word;
vector<string> v;
for (char i : s) {
if (i != ' ')
word = word + i;
else {
v.push_back(word);
word = "";
}
}
if (!word.empty())
v.push_back(word);
return v;
}
|
#ifndef HEADER_CURL_SIGPIPE_H
#define HEADER_CURL_SIGPIPE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(HAVE_SIGNAL_H) && defined(HAVE_SIGACTION) && defined(USE_OPENSSL)
#include <signal.h>
struct sigpipe_ignore {
struct sigaction old_pipe_act;
bool no_signal;
};
#define SIGPIPE_VARIABLE(x) struct sigpipe_ignore x
/*
* sigpipe_ignore() makes sure we ignore SIGPIPE while running libcurl
* internals, and then sigpipe_restore() will restore the situation when we
* return from libcurl again.
*/
static void sigpipe_ignore(struct SessionHandle *data,
struct sigpipe_ignore *ig)
{
/* get a local copy of no_signal because the SessionHandle might not be
around when we restore */
ig->no_signal = data->set.no_signal;
if(!data->set.no_signal) {
struct sigaction action;
/* first, extract the existing situation */
memset(&ig->old_pipe_act, 0, sizeof(struct sigaction));
sigaction(SIGPIPE, NULL, &ig->old_pipe_act);
action = ig->old_pipe_act;
/* ignore this signal */
action.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &action, NULL);
}
}
/*
* sigpipe_restore() puts back the outside world's opinion of signal handler
* and SIGPIPE handling. It MUST only be called after a corresponding
* sigpipe_ignore() was used.
*/
static void sigpipe_restore(struct sigpipe_ignore *ig)
{
if(!ig->no_signal)
/* restore the outside state */
sigaction(SIGPIPE, &ig->old_pipe_act, NULL);
}
#else
/* for systems without sigaction */
namespace youmecommon
{
#define sigpipe_ignore(x,y) Curl_nop_stmt
#define sigpipe_restore(x) Curl_nop_stmt
#define SIGPIPE_VARIABLE(x)
}
#endif
#endif /* HEADER_CURL_SIGPIPE_H */
|
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <set>
#include <cstring>
using namespace std;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
//#define int long long int
#define ld long double
#define F first
#define S second
#define P pair <int,int>
#define vi vector <int>
#define vs vector <string>
#define vb vector <bool>
#define all(x) x.begin(),x.end()
#define sz(x) (int)x.size()
#define REP(i,a,b) for(int i=(int)a;i<=(int)b;i++)
#define REV(i,a,b) for(int i=(int)a;i>=(int)b;i--)
#define sp(x,y) fixed<<setprecision(y)<<x
#define pb push_back
#define endl '\n'
const int mod = 1e9 + 7;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
const int N = 5e4 + 5;
vi Graph[N];
int lca[N][17];
int level[N];
int n;
void dfs(int src, int par, int l = 0) {
level[src] = l;
lca[src][0] = par;
REP(i, 1, 16) {
if (lca[src][i - 1] != -1) {
int p = lca[src][i - 1];
lca[src][i] = lca[p][i - 1];
}
}
for (int to : Graph[src]) {
if (to != par) {
dfs(to, src, l + 1);
}
}
}
int find_lca(int a, int b) {
if (level[a] > level[b])
swap(a, b);
int diff = level[b] - level[a];
while (diff > 0) {
int i = log2(diff);
b = lca[b][i];
diff -= (1 << i);
}
if (a == b)
return a;
REV(i, 16, 0) {
if (lca[a][i] != -1 && (lca[a][i] != lca[b][i])) {
a = lca[a][i];
b = lca[b][i];
}
}
return lca[a][0];
}
int dist(int a, int b) {
return (level[a] + level[b] - 2 * level[find_lca(a, b)]);
}
void solve() {
REP(i, 0, N - 1) {
REP(j, 0, 16) {
lca[i][j] = -1;
}
Graph[i].clear();
level[i] = 0;
}
cin >> n;
REP(i, 1, n - 1) {
int u, v; cin >> u >> v;
Graph[u].pb(v);
Graph[v].pb(u);
}
dfs(1, -1);
int q; cin >> q;
while (q--) {
int u, v; cin >> u >> v;
cout << dist(u, v) << endl;
}
return ;
}
int main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
solve();
return 0;
}
|
#include <ESP8266WiFi.h>
#include "DHT.h"
#define DHTPIN D1 //Pin to attach the DHT
#define DHTTYPE DHT11 //type of DTH
const char* ssid = "your ssid";
const char* password = "your password";
//const int sleepTimeS = 1; //18000 for Half hour, 300 for 5 minutes etc.
///////////////Weather////////////////////////
char server [] = "weatherstation.wunderground.com";
char WEBPAGE [] = "GET /weatherstation/updateweatherstation.php?";
char ID [] = "Your ID";
char PASSWORD [] = "password";
/////////////IFTTT///////////////////////
const char* host = "maker.ifttt.com";//dont change
const String IFTTT_Event = "button";
const int puertoHost = 80;
const String Maker_Key = "hp6E0mOyit50FuCCCd3S2tG9tt_H2Hln2wsBe9oZZMl";
String conexionIF = "POST /trigger/"+IFTTT_Event+"/with/key/"+Maker_Key +" HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n\r\n";
//////////////////////////////////////////
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
Serial.begin(115200);
dht.begin();
delay(1000);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void loop(){
//Check battery
/* int level = analogRead(A0);
level = map(level, 0, 1024, 0, 100);
if(level<50)
{
mandarNot(); //Send IFTT
Serial.println("Low batter");
delay(500);
}*/
//Get sensor data
float tempc = dht.readTemperature();
float tempf = (tempc * 9.0)/ 5.0 + 32.0;
float humidity = dht.readHumidity();
float dewptf = (dewPoint(tempf, dht.readHumidity()));
//check sensor data
Serial.println("+++++++++++++++++++++++++");
Serial.print("tempF= ");
Serial.print(tempf);
Serial.println(" *F");
Serial.print("tempC= ");
Serial.print(tempc);
Serial.println(" *C");
Serial.print("dew point= ");
Serial.println(dewptf);
Serial.print("humidity= ");
Serial.println(humidity);
//Send data to Weather Underground
Serial.print("connecting to ");
Serial.println(server);
WiFiClient client;
if (!client.connect(server, 80)) {
Serial.println("Conection Fail");
return;
}
client.print(WEBPAGE);
client.print("ID=");
client.print(ID);
client.print("&PASSWORD=");
client.print(PASSWORD);
client.print("&dateutc=");
client.print("now");
client.print("&tempf=");
client.print(tempf);
client.print("&dewptf=");
client.print(dewptf);
client.print("&humidity=");
client.print(humidity);
client.print("&softwaretype=ESP%208266O%20version1&action=updateraw&realtime=1&rtfreq=2.5");
client.println();
delay(2500);
// sleepMode();
}
double dewPoint(double tempf, double humidity) //Calculate dew Point
{
double A0= 373.15/(273.15 + tempf);
double SUM = -7.90298 * (A0-1);
SUM += 5.02808 * log10(A0);
SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
SUM += log10(1013.246);
double VP = pow(10, SUM-3) * humidity;
double T = log(VP/0.61078);
return (241.88 * T) / (17.558-T);
}
void mandarNot(){
WiFiClient client;
if (!client.connect(host, puertoHost)) //Check connection
{
Serial.println("Failed connection");
return;
}
client.print(conexionIF);//Send information
delay(10);
while(client.available())
{
String line = client.readStringUntil('\r');
Serial.print(line);
}
}
/*void sleepMode(){
Serial.print(F("Sleeping..."));
ESP.deepSleep(sleepTimeS * 1000000);
}*/
|
#include <vector>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
#define MAX 1000000
class DengklekTryingToSleep {
public:
int minDucks(vector <int> ducks)
{
int mx = 0;
int mn = MAX;
for (int i=0; i<ducks.size(); ++i) {
mx = max(mx,ducks.at(i));
mn = min(mn,ducks.at(i));
}
return (mx-mn+1)-static_cast<int>(ducks.size());
}
};
|
#include "stitchTower.h"
void stitchNeighbors(size_t stitchType, Tower inA, Tower inB, Tower &outA, Tower &outB) {
#pragma HLS PIPELINE II=9
#pragma HLS INLINE
bool etaStitch = (stitchType == stitch_in_eta &&
inA.peak_eta() == inB.peak_eta() &&
inA.peak_phi() == 4 &&
inB.peak_phi() == 0
);
bool phiStitch = (stitchType == stitch_in_phi &&
inA.peak_phi() == inB.peak_phi() &&
inA.peak_eta() == 4 &&
inB.peak_eta() == 0
);
if(etaStitch || phiStitch){
#ifndef __SYNTHESIS__
cout<<" merging neighbors..."<<inA.cluster_et()<<" with "<<inB.cluster_et()<<endl;
#endif
ap_uint<12> cEtSum = inA.cluster_et() + inB.cluster_et();
ap_uint<10> pegged_cEtSum = (cEtSum > 0x3FF) ? (ap_uint<10>)0x3FF : (ap_uint<10>) cEtSum;
if(inA.cluster_et() > inB.cluster_et()){
ap_uint<12> tEtSum = inA.tower_et() + inB.cluster_et();
ap_uint<10> pegged_tEtSum = (tEtSum > 0x3FF) ? (ap_uint<10>)0x3FF : (ap_uint<10>) tEtSum;
ap_uint<10> tEt_leftOver = inB.tower_et() - inB.cluster_et();
outA = Tower(pegged_cEtSum, pegged_tEtSum, inA.peak_phi(), inA.peak_eta(), inA.peak_time(), inA.hOe());
outB = Tower( 0, tEt_leftOver, inB.peak_phi(), inB.peak_eta(), inB.peak_time(), inB.hOe());
}
else{
ap_uint<12> tEtSum = inB.tower_et() + inA.cluster_et();
ap_uint<10> pegged_tEtSum = (tEtSum > 0x3FF) ? (ap_uint<10>)0x3FF : (ap_uint<10>) tEtSum;
ap_uint<10> tEt_leftOver = inA.tower_et() - inA.cluster_et();
outA = Tower( 0, tEt_leftOver, inA.peak_phi(), inA.peak_eta(), inA.peak_time(), inA.hOe());
outB = Tower(pegged_cEtSum, pegged_tEtSum, inB.peak_phi(), inB.peak_eta(), inB.peak_time(), inB.hOe());
}
}
else{
outA = inA;
outB = inB;
}
#ifndef __SYNTHESIS__
if(etaStitch || phiStitch){
if(etaStitch) cout<<"merging in eta"<<endl;
if(phiStitch) cout<<"merging in phi"<<endl;
cout<<std::dec<<"--- inA: "<<inA.toString()<<endl;
cout<<std::dec<<"--- inB: "<<inB.toString()<<endl;
cout<<std::dec<<"++++++++++ oA: "<<outA.toString()<<endl;
cout<<std::dec<<"++++++++++ oB: "<<outB.toString()<<endl;
cout<<endl;
}
#endif
}
|
//
// Created by manout on 17-8-12.
//
#include <iostream>
#include <sstream>
#include <string>
#include <climits>
using std::string;
using std::stringstream;
using std::cout;
int reverse(int x)
{
int flag;
long num;
stringstream ss;
string num_str, re_str;
flag = x >= 0 ? 1 : -1;
ss << x;
ss >> num_str;
re_str.assign(num_str.rbegin(), num_str.rend());
// 当上一次的字符流使用完毕时,会留下一个 eofbit 的error state
// 所以当再次使用该字符流时,应该调用clear清空错误码,否则输入流会不进行操作退出
ss.clear();
ss << re_str;
ss >> num;
if (num > INT_MAX)
{
return 0;
}
return static_cast<int>(num * flag);
}
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
if (pre.empty())
{
return NULL;
}
TreeNode* p = new TreeNode(pre[0]); //前序序列第一个数为根结点
if (pre.size() == 1)
{
return p;
}
int root = pre[0];
int flag;
vector<int> left_pre, right_pre, left_vin, right_vin;
//pre.erase(pre.begin() + 0);
for (int i = 0; i < vin.size(); i++) //根节点的中序序列下标储存到flag里,注意,i是有符号int,size是无符号,所以会有警告
{
if (vin[i] == root)
{
flag = i;
break;
}
}
for (int i = 0; i < flag; i++) //更新左右中序序列
left_vin.push_back(vin[i]);
for (int i = flag + 1; i < vin.size(); i++)
right_vin.push_back(vin[i]);
for (int i = 1; i < flag+1; i++) //更新左右前序序列
left_pre.push_back(pre[i]);
for (int i = flag + 1; i < pre.size(); i++)
right_pre.push_back(pre[i]);
p->left = reConstructBinaryTree(left_pre, left_vin); //更新根节点的左孩子,迭代
p->right = reConstructBinaryTree(right_pre, right_vin); //更新根节点的右孩子,迭代
return p; //返回根节点:这里必须加上,因为不管size为1或是大于1,都已经创建了根节点,区别只是大于1时要赋值left和right
}
void preOrder(TreeNode* &T)
{
if (T == NULL) return;
else
{
cout << T->val << " ";
preOrder(T->left);
preOrder(T->right);
}
}
};
int main()
{
system("color f0");
system("title 重建二叉树");
Solution S;
vector<int> pre({ 1,2,4,7,3,5,6,8 });
vector<int> vin({ 4,7,2,1,5,3,8,6 });
TreeNode* p = S.reConstructBinaryTree(pre, vin);
cout << "创建二叉树成功!" << endl;
cout << "前序遍历二叉树:" << endl;
S.preOrder(p);
system("pause");
return 0;
}
|
#include ".\building.h"
#include "library.h"
#include "terrain.h"
#include "graphics.h"
#include "Camera.h"
#include "variables.h"
#include "input.h"
#include "timer.h"
extern Timer * timer;
extern gamevars *vars;
extern Camera *camera;
extern Library *library;
extern Terrain *terrain;
extern Graphics *renderer;
extern Input *input;
Building::Building(void)
{
family = EF_BUILDING;
model = NULL;
health = 1000;
toolWindow = 0;
completed = 0;
}
Building::~Building(void)
{
}
void Building::init() {
toolWindow = 0;
buildTexture = renderer->LoadTexture("data/UI/wood.JPG");
}
extern int currentID;
void Building::onSelected() {
if (toolWindow) {
currentID = id;
toolWindow->closeButton.pressed = false;
toolWindow->visible = true;
input->inputContext = BuildMenu;
}
}
void Building::onUnSelected() {
if (toolWindow) {
toolWindow->closeButton.pressed = true;
input->inputContext = NormalInput;
}
}
void Building::SetModel(const char*mname, const char*tname) {
// at this point, position and size should already be set
if (model) delete model;
model = new Md2Object;
model->setModel((Model_MD2*)library->Export(mname));
position.y = terrain->getInterpolatedHeight(position.x,position.z);
texture = renderer->LoadTexture(tname);
terrain->setContents((int)position.x,(int)position.z,(int)size.x, (int)size.z,TC_STRUCTURE);
}
void Building::process() {
Think();
if (health < 0) alive = false;
if (completed < 100) completed += timer->frameDifference * 10;
if (spawnQueue.size() > 0 && timer->time - startBuildTime >= 10) {
startBuildTime = timer->time;
// SpawnEntity(spawnQueue.front().c_str(),spawnPoint);
spawnQueue.pop();
}
}
void Building::render() {
if (camera->frustum.pointInFrustum(position) && alive) {
if (this->completed < 100) {
glBindTexture(GL_TEXTURE_2D,buildTexture);
DrawCube(position+Vector(0,100-completed,0),Vector(size.x,(size.x+size.z)/2,size.z));
}
if (completed < 5 || completed > 99) {
model->setPosition(position);
model->setRotation(rotation);
model->setScale(scale);
glColor3f(1,1,1);
glBindTexture(GL_TEXTURE_2D,texture);
model->drawObjectFrame(0,model->kDrawImmediate);
}
renderToolTip();
}
}
|
/*
Copyright 2021 University of Manchester
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http: // www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include "table_data.hpp"
using orkhestrafs::core_interfaces::table_data::ColumnDataType;
namespace orkhestrafs::dbmstodspi {
/**
* @brief Class to convert different types of data to string and integer
* formats.
*/
class TypesConverter {
public:
/**
* @brief Add integer typed data to the output vector given input data in
* string format.
* @param string_data Input data vector.
* @param integer_data Output data vector.
* @param data_types_vector Column data types.
*/
static void AddIntegerDataFromStringData(
const std::vector<std::vector<std::string>>& string_data,
std::vector<uint32_t>& integer_data,
const std::vector<std::pair<ColumnDataType, int>>& data_types_vector);
static void ConvertRecordStringToIntegers(
const std::vector<std::string>& row,
const std::vector<std::pair<ColumnDataType, int>>& data_types_vector,
std::vector<uint32_t>& integer_data);
/**
* @brief Add string typed data to the output vector given input data in
* integer format.
* @param integer_data Input data vector.
* @param resulting_string_data Output data vector.
* @param data_types_vector Column data types.
*/
static void AddStringDataFromIntegerData(
const std::vector<uint32_t>& integer_data,
std::vector<std::vector<std::string>>& resulting_string_data,
const std::vector<std::pair<ColumnDataType, int>>& data_types_vector);
/**
* @brief Convert string table element to integers.
* @param input String element.
* @param data_vector Output integer vector.
* @param output_size String size.
*/
static void ConvertStringValuesToIntegerData(
const std::string& input, std::vector<uint32_t>& data_vector,
int output_size);
/**
* @brief Convert integer table element to integers.
* @param input String input representing an integer.
* @param data_vector Output integer vector.
* @param output_size How many integers should be added to the output.
*/
static void ConvertIntegerValuesToIntegerData(
const std::string& input, std::vector<uint32_t>& data_vector,
int output_size);
/**
* @brief Convert null table element to integers.
* @param input String input representing a NULL value.
* @param data_vector Output integer vector.
* @param output_size How many integers should be added to the output.
*/
static void ConvertNullValuesToIntegerData(const std::string& input,
std::vector<uint32_t>& data_vector,
int output_size);
/**
* @brief Convert decimal table element to integers.
* @param input String input representing a decimal value.
* @param data_vector Output integer vector.
* @param output_size How many integers should be added to the output.
*/
static void ConvertDecimalValuesToIntegerData(
const std::string& input, std::vector<uint32_t>& data_vector,
int output_size);
/**
* @brief Convert date table element to integers.
* @param input String input representing a date value.
* @param data_vector Output integer vector.
* @param output_size How many integers should be added to the output
*/
static void ConvertDateValuesToIntegerData(const std::string& input,
std::vector<uint32_t>& data_vector,
int output_size);
/**
* @brief Convert a vector of integers to string format.
* @param input_value Integer vector representing a string value.
* @param string_vector Output string vector.
*/
static void ConvertStringValuesToString(
const std::vector<uint32_t>& input_value,
std::vector<std::string>& string_vector);
/**
* @brief Convert a vector of integers to string format.
* @param input_value Integer vector representing an integer value.
* @param string_vector Output string vector.
*/
static void ConvertIntegerValuesToString(
const std::vector<uint32_t>& input_value,
std::vector<std::string>& string_vector);
/**
* @brief Convert a vector of integers to string format.
* @param input_value Integer vector representing a NULL value.
* @param string_vector Output string vector.
*/
static void ConvertNullValuesToString(
const std::vector<uint32_t>& input_value,
std::vector<std::string>& string_vector);
/**
* @brief Convert a vector of integers to string format.
* @param input_value Integer vector representing a decimal value.
* @param string_vector Output string vector.
*/
static void ConvertDecimalValuesToString(
const std::vector<uint32_t>& input_value,
std::vector<std::string>& string_vector);
/**
* @brief Convert a vector of integers to string format.
* @param input_value Integer vector representing a date value.
* @param string_vector Output string vector.
*/
static void ConvertDateValuesToString(
const std::vector<uint32_t>& input_value,
std::vector<std::string>& string_vector);
private:
static void ConvertDataToIntegers(
ColumnDataType data_type, const std::string& input_string,
std::vector<uint32_t>& converted_data_vector, int string_size);
static void ConvertDataToString(
ColumnDataType data_type, const std::vector<uint32_t>& input_integer_data,
std::vector<std::string>& converted_data_vector);
/**
* @brief Helper method to convert strings with hexadecimal values to strings.
* @param hex Input string with hex values which can be converted to a string
* with ASCII characters.
* @return Converted Ascii string.
*/
static auto ConvertHexStringToString(const std::string& hex) -> std::string;
/**
* @brief Helper method to convert strings to ASCII integer values.
* @param input_string String to be converted to integers.
* @param output_size How many integers can be used.
* @return Vector of integers representing the ASCII integer value of the
* input string.
*/
static auto ConvertCharStringToAscii(const std::string& input_string,
int output_size) -> std::vector<int>;
};
} // namespace orkhestrafs::dbmstodspi
|
#include <Servo.h>
#include <HCSR04.h>
UltraSonicDistanceSensor Torre (13,12);
Servo Servo1;
float valor[10];
int angulo=-180;
int LED1 = 9;
int gambiarra = 0;
void setup (){
Serial.begin(9600);
Servo1.attach(3);
pinMode(9,OUTPUT);
digitalWrite(9,LOW);
}
void loop (){
Watch();
}
int Watch (){
int i=0;
float dist=100;
for (i=angulo;i<180;i++){
Servo1.write(abs(i));
delay(5);
if (i%2==0){
dist = Torre.measureDistanceCm();
}
if (gambiarra==1){
Serial.print(abs(angulo));
Serial.print('/');
Serial.print(dist);
Serial.print('z');
}
if (dist<30.0){
while (Torre.measureDistanceCm()<30) {
digitalWrite(9,HIGH);
dist = Torre.measureDistanceCm();
}
delay(100);
angulo=i;
digitalWrite(9, LOW);
gambiarra=1;
return 1;
}
}
angulo = -180;
return 0;
}
|
#ifndef __HallHandler_H__
#define __HallHandler_H__
#include <map>
#include "CDLSocketHandler.h"
#include "Packet.h"
#include "DLDecoder.h"
#ifdef CRYPT
#include "CryptDecoder.h"
#endif
class HallHandler :public CDLSocketHandler, public CDLSocketHandler::PacketListener
{
public:
HallHandler();
virtual ~HallHandler();
int OnConnected() ;
int OnClose();
int Send(OutputPacket* outPacket, bool isEncrypt);
private:
bool OnPacketCompleteEx(const char* data, int len);
int OnPacketComplete(const char* data, int len);
CDL_Decoder* CreateDecoder()
{
#ifndef CRYPT
return &DLDecoder::getInstance();
#else
return &CryptDecoder::getInstance();
#endif
}
public:
int uid;
#ifdef CRYPT
private:
std::string m_strAuthKey;
#endif
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2000-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Yngve Pettersen
*/
#include "core/pch.h"
#ifdef _MIME_SUPPORT_
#include "modules/mime/mimedec2.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/viewers/viewers.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefs/prefsmanager/collections/pc_m2.h"
#include "modules/url/url_man.h"
#include "modules/url/url_rep.h"
#include "modules/url/url_ds.h"
#include "modules/mime/mime_cs.h"
#include "modules/encodings/utility/charsetnames.h"
#include "modules/olddebug/tstdump.h"
#ifdef MHTML_ARCHIVE_REDIRECT_SUPPORT
#include "modules/url/url_loading.h"
#endif
void CleanFileName(OpString &name)
{
int pos;
while((pos = name.FindFirstOf(OpStringC16(UNI_L("/\\:")))) != KNotFound)
name.Delete(0, pos+1);
//remove trailing dots from suggested filename for windows.
if(name.Length() && name[name.Length()-1]=='.')
for (;name.Length() && name[name.Length()-1]=='.';)
name[name.Length()-1]=0;
}
MIME_Payload::MIME_Payload(HeaderList &hdrs, URLType url_type)
: MIME_Decoder(hdrs, url_type)
{
is_attachment = FALSE;
}
MIME_Payload::~MIME_Payload()
{
}
void MIME_Payload::HandleHeaderLoadedL()
{
MIME_Decoder::HandleHeaderLoadedL();
HeaderEntry *header = headers.GetHeaderByID(HTTP_Header_Content_Disposition);
if(header)
{
ParameterList *parameters = header->GetParametersL((PARAM_SEP_SEMICOLON| PARAM_ONLY_SEP | PARAM_STRIP_ARG_QUOTES_GENTLY | PARAM_HAS_RFC2231_VALUES), KeywordIndex_HTTP_General_Parameters);
if(parameters && !parameters->Empty())
{
if(parameters->First()->GetNameID() == HTTP_General_Tag_Attachment /*||
parameters->First()->GetNameID() == HTTP_General_Tag_Inline*/)
is_attachment = TRUE;
if(name.IsEmpty())
{
parameters->GetValueStringFromParameterL(name, default_charset, HTTP_General_Tag_Name,PARAMETER_ASSIGNED_ONLY);
CleanFileName(name);
}
if(filename.IsEmpty())
{
parameters->GetValueStringFromParameterL(filename, default_charset, HTTP_General_Tag_Filename,PARAMETER_ASSIGNED_ONLY);
CleanFileName(filename);
}
}
}
if(name.IsEmpty())
{
header = headers.GetHeaderByID(HTTP_Header_Content_Type);
if (header != NULL)
{
ParameterList *parameters = header->SubParameters();
if(!parameters)
parameters = header->GetParametersL((PARAM_SEP_SEMICOLON| PARAM_ONLY_SEP | PARAM_STRIP_ARG_QUOTES_GENTLY | PARAM_HAS_RFC2231_VALUES), KeywordIndex_HTTP_General_Parameters);
if(parameters && !parameters->Empty())
{
parameters->GetValueStringFromParameterL(name, default_charset, HTTP_General_Tag_Name,PARAMETER_ASSIGNED_ONLY);
CleanFileName(name);
}
}
}
}
void MIME_Payload::RegisterFilenameL(OpStringC8 fname)
{
filename.SetL(fname);
}
URL MIME_Payload::ConstructAttachmentURL_L(HeaderEntry *content_id, const uni_char *ext, HeaderEntry *content_type)
{
return MIME_Decoder::ConstructAttachmentURL_L(content_id, ext, content_type, (filename.HasContent() ? filename : name), &content_id_url);
}
void MIME_Payload::ProcessDecodedDataL(BOOL more)
{
const char *force_charset = NULL;
if(attachment->IsEmpty())
{
ANCHORD(URL, temp_url);
temp_url= ConstructAttachmentURL_L(headers.GetHeaderByID(HTTP_Header_Content_ID), NULL, content_type_header);
#ifdef MHTML_ARCHIVE_REDIRECT_SUPPORT
if (IsValidMHTMLArchive() && !cloc_url.IsEmpty())
{
temp_url = cloc_url;
if(!content_id_url.IsEmpty())
content_id_url.SetAttributeL(URL::KAliasURL, cloc_url);
}
#endif
attachment.SetURL(temp_url);
if (forced_charset_id != 0)
force_charset = g_charsetManager->GetCharsetFromID(forced_charset_id);
OP_STATUS op_err;
if(content_type_header && content_type_header->Value())
{
MIME_ContentTypeID mimeid;
const char *mimetype = content_type_header->Value();
ParameterList *parameters;
parameters = content_type_header->GetParametersL(PARAM_SEP_SEMICOLON| PARAM_ONLY_SEP | PARAM_STRIP_ARG_QUOTES | PARAM_HAS_RFC2231_VALUES, KeywordIndex_HTTP_General_Parameters);
if(parameters && parameters->First())
{
Parameters *param = parameters->First();
mimeid = FindContentTypeId(param->Name());
if ((mimeid == MIME_Text || mimeid == MIME_Plain_text) && op_stricmp(param->Name(), "text/plain") != 0)
{
g_mime_module.SetOriginalContentTypeL(attachment, param->Name());
mimetype = "text/plain";
}
}
attachment->SetAttributeL(URL::KMIME_ForceContentType, mimetype);
if (force_charset == NULL)
force_charset = g_pcdisplay->GetForceEncoding();
if (force_charset && *force_charset && !strni_eq(force_charset, "AUTODETECT-", 11))
{
attachment->SetAttributeL(URL::KMIME_CharSet, force_charset);
}
}
else
{
ANCHORD(OpString8, type);
if (force_charset == NULL)
force_charset = (g_pcdisplay->GetForceEncoding() ? g_pcdisplay->GetForceEncoding() : "iso-8859-1");
if (strni_eq(force_charset, "AUTODETECT-", 11))
force_charset = "";
LEAVE_IF_ERROR(type.SetConcat("text/plain", (*force_charset ? "; charset=" : ""), force_charset) );
attachment->SetAttributeL(URL::KMIME_ForceContentType, type);
}
if(!cloc_url.IsEmpty() && cloc_url.GetAttribute(URL::KLoadStatus) == URL_UNLOADED && !(cloc_url == attachment))
{
cloc_url.SetAttributeL(URL::KAliasURL, attachment);
alias = cloc_url;
}
else
alias = URL();
if(!cloc_base_url.IsEmpty() && (filename.HasContent() || name.HasContent()))
{
URL temp_alias = urlManager->GetURL(cloc_base_url, (filename.HasContent() ? filename.CStr() : name.CStr()));
if(!temp_alias.IsEmpty() && !(temp_alias == attachment) && temp_alias.GetAttribute(URL::KLoadStatus) == URL_UNLOADED)
{
temp_alias.SetAttributeL(URL::KAliasURL, attachment);
alias1 = temp_alias;
}
}
if(!cloc_url.IsEmpty())
attachment->SetAttributeL(URL::KBaseAliasURL, cloc_url);
else if(!cloc_base_url.IsEmpty())
attachment->SetAttributeL(URL::KBaseAliasURL, cloc_base_url);
if(content_typeid == MIME_Binary)
{
URL_DataStorage *url_ds = attachment->GetRep()->GetDataStorage();
if(url_ds)
{
URLContentType ctype = URL_UNDETERMINED_CONTENT;
ANCHORD(OpString, path);
attachment->GetAttribute(URL::KUniPath, 0, path);
OpStatus::Ignore(url_ds->FindContentType(ctype, NULL, NULL, path.CStr())); // Not critical if this fails
url_ds->SetAttributeL(URL::KContentType, ctype);
const char *mimetype = NULL;
mimetype = g_viewers->GetContentTypeString(ctype);
if(mimetype)
{
if(op_stricmp(mimetype, "text") == 0)
mimetype = "text/plain";
op_err = url_ds->SetAttribute(URL::KMIME_Type,mimetype);
if(op_err == OpStatus::ERR_NO_MEMORY)
g_memory_manager->RaiseCondition(op_err);
// Errors here only affect presentation of attachments, no need to abort.
content_typeid = FindContentTypeId(mimetype);
}
}
}
attachment->SetAttributeL(URL::KHTTP_Response_Code, HTTP_OK); // Prevents reload of images due to Expired
attachment->SetAttributeL(URL::KForceCacheKeepOpenFile, TRUE);
attachment->SetAttributeL(URL::KLoadStatus, URL_LOADING);
InheritExpirationDataL(attachment, base_url);
}
#ifdef _DEBUG
/*
else
int i = 1;
*/
#endif
#ifdef MIME_DEBUG
PrintfTofile("mimeatt.txt", "SaveData data %p %s\n",this, attachment->GetAttribute(URL::KName_Username_Password_Escaped_NOT_FOR_UI).CStr());
//DumpTofile(AccessDecodedData(), GetLengthDecodedData(), "saving data","mimeatt.txt");
#endif
attachment->WriteDocumentData(URL::KNormal, (char *) AccessDecodedData(), GetLengthDecodedData());
CommitDecodedDataL(GetLengthDecodedData());
if(attachment->GetRep()->GetDataStorage())
{
URL_DataStorage *url_ds = attachment->GetRep()->GetDataStorage();
if(!attachment->GetAttribute(URL::KHeaderLoaded))
{
url_ds->BroadcastMessage(MSG_HEADER_LOADED, attachment->Id(), 0, MH_LIST_ALL);
attachment->SetAttribute(URL::KHeaderLoaded,TRUE);
}
OP_ASSERT(attachment->GetAttribute(URL::KLoadStatus, URL::KFollowRedirect) == URL_LOADING || attachment->GetAttribute(URL::KLoadStatus, URL::KFollowRedirect) == URL_LOADED);
url_ds->BroadcastMessage(MSG_URL_DATA_LOADED, attachment->Id(), 0, MH_LIST_ALL);
}
}
#ifdef MHTML_ARCHIVE_REDIRECT_SUPPORT
BOOL MIME_Decoder::IsValidMHTMLArchiveURL(URL_Rep* url)
{
return url && (URLContentType)url->GetAttribute(URL::KContentType) == URL_MHTML_ARCHIVE &&
// Avoid spoofing exploits:
url->GetAttribute(URL::KIsUserInitiated) && (URLType)url->GetAttribute(URL::KType) == URL_FILE;
}
BOOL MIME_Decoder::IsValidMHTMLArchive()
{
const MIME_Decoder* top_decoder = this;
while (top_decoder->parent)
top_decoder = top_decoder->parent;
return IsValidMHTMLArchiveURL(base_url) &&
top_decoder->GetContentTypeID() == MIME_Multipart_Related &&
!top_decoder->GetRelatedStartURL().IsEmpty() &&
!top_decoder->cloc_url.IsEmpty();
}
#ifdef URL_SEPARATE_MIME_URL_NAMESPACE
// Cleanup item used to remove the context when the main URL in the context is deleted
class MIME_ContextRemover : public Link
{
URL_CONTEXT_ID ctx_id;
public:
MIME_ContextRemover(URL_CONTEXT_ID context_id) : ctx_id(context_id) {}
~MIME_ContextRemover() { urlManager->RemoveContext(ctx_id, TRUE); }
};
#endif // URL_SEPARATE_MIME_URL_NAMESPACE
#endif // MHTML_ARCHIVE_REDIRECT_SUPPORT
void MIME_Payload::HandleFinishedL()
{
MIME_Decoder::HandleFinishedL();
if(!attachment->IsEmpty() && attachment->GetAttribute(URL::KLoadStatus) == URL_LOADING)
{
attachment->WriteDocumentDataFinished();
OP_ASSERT(attachment->GetAttribute(URL::KLoadStatus, URL::KFollowRedirect) != URL_LOADING);
URL_DataStorage *url_ds = attachment->GetRep()->GetDataStorage();
if(url_ds)
{
if(!attachment->GetAttribute(URL::KHeaderLoaded))
{
url_ds->BroadcastMessage(MSG_HEADER_LOADED, attachment->Id(), 0, MH_LIST_ALL);
attachment->SetAttribute(URL::KHeaderLoaded,TRUE);
}
url_ds->BroadcastMessage(MSG_URL_DATA_LOADED, attachment->Id(), 0, MH_LIST_ALL);
}
#ifdef MHTML_ARCHIVE_REDIRECT_SUPPORT
// If this part is the child of the top element, and the top element is a
// multipart/related with a start-id that matches the content-id of this element,
// and this element has a specified content-location, and we are loading a valid
// MHTML archive, we assume the user actually wants *this* part to be the main document.
if (parent && !parent->GetParent() && GetContentIdURL() == parent->GetRelatedStartURL() &&
!cloc_url.IsEmpty() && IsValidMHTMLArchive() && base_url->GetDataStorage())
{
#ifdef URL_SEPARATE_MIME_URL_NAMESPACE
if (GetContextID() != 0)
{
urlManager->SetContextIsOffline(GetContextID(), TRUE);
// Context should be removed when document is deleted
MIME_ContextRemover *context_remover = OP_NEW_L(MIME_ContextRemover, (GetContextID()));
attachment->GetRep()->AddCleanupItem(context_remover);
}
#endif
URL original_url(base_url, (char*)NULL);
attachment->SetAttributeL(g_mime_module.GetOriginalURLAttribute(), original_url); // To allow display of the original url if desired
attachment->SetAttributeL(g_mime_module.GetInternalRedirectAttribute(), TRUE); // To prevent reload during redirect
base_url->SetAttributeL(URL::KMovedToURL, attachment);
IAmLoadingThisURL yesIAm(attachment);
LEAVE_IF_ERROR(base_url->GetDataStorage()->ExecuteRedirect_Stage2(FALSE));
}
#endif // MHTML_ARCHIVE_REDIRECT_SUPPORT
}
}
void MIME_Payload::WriteDisplayDocumentL(URL &target, DecodedMIME_Storage *attach_target)
{
return; // Don't display anything
}
void MIME_Payload::WriteDisplayAttachmentsL(URL &target, DecodedMIME_Storage *attach_target, BOOL display_as_links)
{
if(!alias.IsEmpty())
attach_target->AddMIMEAttachment(alias, FALSE);
if(!alias1.IsEmpty())
attach_target->AddMIMEAttachment(alias1, FALSE);
if(!content_id_url.IsEmpty())
attach_target->AddMIMEAttachment(content_id_url, FALSE);
if(!attachment->IsEmpty())
attach_target->AddMIMEAttachment(attachment, info.displayed);
if(!info.displayed && display_as_links && !attachment->IsEmpty())
{
#if defined(NEED_URL_MIME_DECODE_LISTENERS)
if(target.GetAttribute(URL::KMIME_HasAttachmentListener))
{
target.SetAttributeL(URL::KMIME_SignalAttachmentListeners, attachment);
}
#endif // NEED_URL_MIME_DECODE_LISTENERS
ANCHORD(OpString, url);
attachment->GetAttributeL(URL::KUniName_Escaped, 0, url);
if(url.HasContent()
#if defined(NEED_URL_MIME_DECODE_LISTENERS)
&& g_pcm2->GetIntegerPref(PrefsCollectionM2::ShowAttachmentsInline)
#endif // NEED_URL_MIME_DECODE_LISTENERS
)
{
attachment->DumpSourceToDisk(TRUE);
ANCHORD(OpString, name);
ANCHORD(OpString, pathname);
ANCHORD(OpString, iconurl);
attachment->GetAttributeL(URL::KSuggestedFileName_L, name);
target.WriteDocumentData(URL::KNormal, UNI_L("<div class=\"attachments\"><a href=\""));
target.WriteDocumentData(URL::KXMLify, url);
target.WriteDocumentData(URL::KNormal, UNI_L("\""));
if(iconurl.HasContent())
{
target.WriteDocumentData(URL::KNormal, UNI_L("><img src=\""));
target.WriteDocumentData(URL::KXMLify, iconurl.CStr());
target.WriteDocumentData(URL::KNormal, UNI_L("\" alt=\"attachment\"/>"));
}
else
{
target.WriteDocumentData(URL::KNormal, UNI_L(" class=\"unknown\">"));
}
target.WriteDocumentData(URL::KXMLify, name);
target.WriteDocumentData(URL::KNormal, UNI_L("</a></div>\r\n"));
}
}
}
BOOL MIME_Payload::HaveAttachments()
{
if(!alias.IsEmpty())
return TRUE;
if(!alias1.IsEmpty())
return TRUE;
if(!content_id_url.IsEmpty())
return TRUE;
if(!info.displayed && !attachment->IsEmpty())
return TRUE;
return FALSE;
}
// Only performed when no output is generated
void MIME_Payload::RetrieveAttachementList(DecodedMIME_Storage *attach_target)
{
if(!attach_target)
return;
if(!attachment->IsEmpty())
attach_target->AddMIMEAttachment(attachment, TRUE);
}
void MIME_Payload::SetUseNoStoreFlag(BOOL no_store)
{
MIME_Decoder::SetUseNoStoreFlag(no_store);
if(no_store && !attachment->IsEmpty())
attachment->SetAttributeL(URL::KCachePolicy_NoStore, no_store);
}
#endif // MIME_SUPPORT
|
#ifndef PLAYER_H
#define PLAYER_H
#include<iostream>
#include<SFML/Graphics.hpp>
#include<../debugging_tolls.h>
#include<string>
/*!
* \brief Player class - pointers to player have a lot of usage in program.
* All Squares have pointer to player which were marked by
* pointers to players are also used by Engine class to set whose turn is now.
*/
class Player
{
public:
Player(); ///< empty constructor
virtual ~Player(); ///< empty destructor only msg
void setTexture(char* fileDir); ///< function setting player texture (initialization staff)
sf::Texture* getTexturePtr(); ///<returns pointer to current player texture (texture_marked)
std::string& toStr();
void setName(std::string);
virtual bool getMovePremission(){return move_premission;}
bool move_premission;
protected:
int player_number;
std::string name;
sf::Texture texture_marked; ///< texture to draw when a player marked square.
//TODO(FOTO#5#): set default texture to be copied from default square texture, or gonna make that const , get deafult from square when creating and print circle crosss square on it before creating a player
};
#endif // PLAYER_H
|
// 3.23实验View.cpp: CMy323实验View 类的实现
//
#include "pch.h"
#include "framework.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "3.23实验.h"
#endif
#include "3.23实验Doc.h"
#include "3.23实验View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMy323实验View
IMPLEMENT_DYNCREATE(CMy323实验View, CView)
BEGIN_MESSAGE_MAP(CMy323实验View, CView)
ON_COMMAND(ID_Circles, &CMy323实验View::OnCircles)
ON_WM_TIMER()
END_MESSAGE_MAP()
// CMy323实验View 构造/析构
CMy323实验View::CMy323实验View() noexcept
{
// TODO: 在此处添加构造代码
set = true;
N = 5;
}
CMy323实验View::~CMy323实验View()
{
}
BOOL CMy323实验View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CView::PreCreateWindow(cs);
}
// CMy323实验View 绘图
void CMy323实验View::OnDraw(CDC* /*pDC*/)
{
CMy323实验Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
}
// CMy323实验View 诊断
#ifdef _DEBUG
void CMy323实验View::AssertValid() const
{
CView::AssertValid();
}
void CMy323实验View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMy323实验Doc* CMy323实验View::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMy323实验Doc)));
return (CMy323实验Doc*)m_pDocument;
}
#endif //_DEBUG
// CMy323实验View 消息处理程序
void CMy323实验View::OnCircles()
{
// TODO: 在此添加命令处理程序代码
GetClientRect(&m_window);
// TODO: 在此添加命令处理程序代码
int x1 = (m_window.left + m_window.right) / 2;
int x2 = (m_window.bottom + m_window.top) / 2;
GetClientRect(&cr);
CClientDC DC(this);
cr.left = x1 - 50;
cr.right = x1 + 50;
cr.top = x2 - 50;
cr.bottom = x2 + 50;
if (set)
{
for (int i = 0; i < N; i++)
{
SetTimer(i, 200, NULL);
}
set = false;
}
}
void CMy323实验View::OnTimer(UINT_PTR nIDEvent)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CView::OnTimer(nIDEvent);
CView::OnTimer(nIDEvent);
CClientDC dc(this);
int i = nIDEvent;
cr.left -= 5;
cr.right += 5;
cr.top -= 5;
cr.bottom += 5;
dc.Ellipse(cr);
CPen pen(PS_SOLID, 20, RGB(rand() % 150, rand() % 150, rand() % 150));
CPen* color;
color = dc.SelectObject(&pen);
dc.Ellipse(cr);
CView::OnTimer(nIDEvent);
}
|
#include "ModelManager.h"
ModelManager::ModelManager(void)
{
}
ModelManager::~ModelManager(void)
{
}
ResourceHandle ModelManager::LoadResource(std::string filename)
{
auto iter = models.find(filename);
if(iter != models.end())
{
return iter->first;
}
}
ResourceHandle ModelManager::LoadCubeModel()
{
auto iter = models.find("Cube");
if(iter != models.end())
{
return "Cube";
}
GLfloat vertices[24] = {
-0.5f, 0.5f, 0.5f, //front top left
0.5f, 0.5f, 0.5f, //front top right
-0.5f, -0.5f, 0.5f, //front bottom left
0.5f, -0.5f, 0.5f, //front bottom right
-0.5f, 0.5f, -0.5f, //back top left
0.5f, 0.5f, -0.5f, //back top right
-0.5f, -0.5f, -0.5f, //back bottom left
0.5f, -0.5f, -0.5f//back bottom right
};
GLuint indices[36] = {
0, 1, 2, //front face
2, 1, 3,
3, 2, 6, //Bottom face
6, 3, 7,
7, 3, 1, //Right face
1, 7, 5,
5, 7, 6, //Back face
6, 5, 4,
4, 5, 1, //Top face
1, 4, 0,
0, 2, 6, //Left face
6, 0, 4
};
Mesh* mesh = new Mesh();
mesh->minVertex = amVec3(-0.5f, -0.5f, -0.5f);
mesh->maxVertex = -mesh->minVertex;
//Generate object
glGenVertexArrays(1, &mesh->vao);
//Bind object
glBindVertexArray(mesh->vao);
//Generate buffers
glGenBuffers(Mesh::Buffers::NumberOfBuffers, mesh->vbos);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vbos[Mesh::Buffers::Vertex]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->vbos[Mesh::Buffers::Index]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glBindVertexArray(0);
models.insert(std::pair<std::string, Mesh*>("Cube", mesh));
return "Cube";
}
void ModelManager::ReleaseResource(ResourceHandle handle)
{
auto iter = models.find(handle);
if(iter != models.end())
{
delete iter->second;
models.erase(iter);
}
}
|
// Copyright (c) 2020 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/execution.hpp>
#include <pika/init.hpp>
#include <pika/testing.hpp>
#include <atomic>
#include <cstddef>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
// This test verifies that all parameters customization points dispatch
// through the executor before potentially being handled by the parameters
// object.
std::atomic<std::size_t> params_count(0);
std::atomic<std::size_t> exec_count(0);
///////////////////////////////////////////////////////////////////////////////
// get_chunks_size
struct test_executor_get_chunk_size : pika::execution::parallel_executor
{
test_executor_get_chunk_size()
: pika::execution::parallel_executor()
{
}
template <typename Parameters, typename F>
static std::size_t
get_chunk_size(Parameters&& /* params */, F&& /* f */, std::size_t cores, std::size_t count)
{
++exec_count;
return (count + cores - 1) / cores;
}
};
namespace pika::parallel::execution {
template <>
struct is_two_way_executor<test_executor_get_chunk_size> : std::true_type
{
};
} // namespace pika::parallel::execution
struct test_chunk_size
{
template <typename Executor, typename F>
static std::size_t
get_chunk_size(Executor&& /* exec */, F&& /* f */, std::size_t cores, std::size_t count)
{
++params_count;
return (count + cores - 1) / cores;
}
};
namespace pika::parallel::execution {
/// \cond NOINTERNAL
template <>
struct is_executor_parameters<test_chunk_size> : std::true_type
{
};
/// \endcond
} // namespace pika::parallel::execution
///////////////////////////////////////////////////////////////////////////////
void test_get_chunk_size()
{
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::get_chunk_size(
test_chunk_size{}, pika::execution::par.executor(), [](std::size_t) { return 0; }, 1,
1);
PIKA_TEST_EQ(params_count.load(), std::size_t(1));
PIKA_TEST_EQ(exec_count.load(), std::size_t(0));
}
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::get_chunk_size(
test_chunk_size{}, test_executor_get_chunk_size{}, [](std::size_t) { return 0; }, 1, 1);
PIKA_TEST_EQ(params_count.load(), std::size_t(0));
PIKA_TEST_EQ(exec_count.load(), std::size_t(1));
}
}
///////////////////////////////////////////////////////////////////////////////
// maximal_number_of_chunks
struct test_executor_maximal_number_of_chunks : pika::execution::parallel_executor
{
test_executor_maximal_number_of_chunks()
: pika::execution::parallel_executor()
{
}
template <typename Parameters>
static std::size_t maximal_number_of_chunks(Parameters&&, std::size_t, std::size_t num_tasks)
{
++exec_count;
return num_tasks;
}
};
namespace pika::parallel::execution {
template <>
struct is_two_way_executor<test_executor_maximal_number_of_chunks> : std::true_type
{
};
} // namespace pika::parallel::execution
struct test_number_of_chunks
{
template <typename Executor>
std::size_t maximal_number_of_chunks(Executor&&, std::size_t, std::size_t num_tasks)
{
++params_count;
return num_tasks;
}
};
namespace pika::parallel::execution {
template <>
struct is_executor_parameters<test_number_of_chunks> : std::true_type
{
};
} // namespace pika::parallel::execution
///////////////////////////////////////////////////////////////////////////////
void test_maximal_number_of_chunks()
{
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::maximal_number_of_chunks(
test_number_of_chunks{}, pika::execution::par.executor(), 1, 1);
PIKA_TEST_EQ(params_count.load(), std::size_t(1));
PIKA_TEST_EQ(exec_count.load(), std::size_t(0));
}
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::maximal_number_of_chunks(
test_number_of_chunks{}, test_executor_maximal_number_of_chunks{}, 1, 1);
PIKA_TEST_EQ(params_count.load(), std::size_t(0));
PIKA_TEST_EQ(exec_count.load(), std::size_t(1));
}
}
///////////////////////////////////////////////////////////////////////////////
// reset_thread_distribution
struct test_executor_reset_thread_distribution : pika::execution::parallel_executor
{
test_executor_reset_thread_distribution()
: pika::execution::parallel_executor()
{
}
template <typename Parameters>
static void reset_thread_distribution(Parameters&&)
{
++exec_count;
}
};
namespace pika::parallel::execution {
template <>
struct is_two_way_executor<test_executor_reset_thread_distribution> : std::true_type
{
};
} // namespace pika::parallel::execution
struct test_thread_distribution
{
template <typename Executor>
void reset_thread_distribution(Executor&&)
{
++params_count;
}
};
namespace pika::parallel::execution {
template <>
struct is_executor_parameters<test_thread_distribution> : std::true_type
{
};
} // namespace pika::parallel::execution
///////////////////////////////////////////////////////////////////////////////
void test_reset_thread_distribution()
{
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::reset_thread_distribution(
test_thread_distribution{}, pika::execution::par.executor());
PIKA_TEST_EQ(params_count.load(), std::size_t(1));
PIKA_TEST_EQ(exec_count.load(), std::size_t(0));
}
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::reset_thread_distribution(
test_thread_distribution{}, test_executor_reset_thread_distribution{});
PIKA_TEST_EQ(params_count.load(), std::size_t(0));
PIKA_TEST_EQ(exec_count.load(), std::size_t(1));
}
}
///////////////////////////////////////////////////////////////////////////////
// processing_units_count
struct test_executor_processing_units_count : pika::execution::parallel_executor
{
test_executor_processing_units_count()
: pika::execution::parallel_executor()
{
}
template <typename Parameters>
static std::size_t processing_units_count(Parameters&&)
{
++exec_count;
return 1;
}
};
namespace pika::parallel::execution {
template <>
struct is_two_way_executor<test_executor_processing_units_count> : std::true_type
{
};
} // namespace pika::parallel::execution
struct test_processing_units
{
template <typename Executor>
static std::size_t processing_units_count(Executor&&)
{
++params_count;
return 1;
}
};
namespace pika::parallel::execution {
template <>
struct is_executor_parameters<test_processing_units> : std::true_type
{
};
} // namespace pika::parallel::execution
///////////////////////////////////////////////////////////////////////////////
void test_processing_units_count()
{
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::processing_units_count(
test_processing_units{}, pika::execution::par.executor());
PIKA_TEST_EQ(params_count.load(), std::size_t(1));
PIKA_TEST_EQ(exec_count.load(), std::size_t(0));
}
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::processing_units_count(
test_processing_units{}, test_executor_processing_units_count{});
PIKA_TEST_EQ(params_count.load(), std::size_t(0));
PIKA_TEST_EQ(exec_count.load(), std::size_t(1));
}
}
///////////////////////////////////////////////////////////////////////////////
// mark_begin_execution, mark_end_of_scheduling, mark_end_execution
struct test_executor_begin_end : pika::execution::parallel_executor
{
test_executor_begin_end()
: pika::execution::parallel_executor()
{
}
template <typename Parameters>
void mark_begin_execution(Parameters&&)
{
++exec_count;
}
template <typename Parameters>
void mark_end_of_scheduling(Parameters&&)
{
++exec_count;
}
template <typename Parameters>
void mark_end_execution(Parameters&&)
{
++exec_count;
}
};
namespace pika::parallel::execution {
template <>
struct is_two_way_executor<test_executor_begin_end> : std::true_type
{
};
} // namespace pika::parallel::execution
struct test_begin_end
{
template <typename Executor>
void mark_begin_execution(Executor&&)
{
++params_count;
}
template <typename Executor>
void mark_end_of_scheduling(Executor&&)
{
++params_count;
}
template <typename Executor>
void mark_end_execution(Executor&&)
{
++params_count;
}
};
namespace pika::parallel::execution {
template <>
struct is_executor_parameters<test_begin_end> : std::true_type
{
};
} // namespace pika::parallel::execution
///////////////////////////////////////////////////////////////////////////////
void test_mark_begin_execution()
{
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::mark_begin_execution(
test_begin_end{}, pika::execution::par.executor());
PIKA_TEST_EQ(params_count.load(), std::size_t(1));
PIKA_TEST_EQ(exec_count.load(), std::size_t(0));
}
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::mark_begin_execution(
test_begin_end{}, test_executor_begin_end{});
PIKA_TEST_EQ(params_count.load(), std::size_t(0));
PIKA_TEST_EQ(exec_count.load(), std::size_t(1));
}
}
void test_mark_end_of_scheduling()
{
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::mark_end_of_scheduling(
test_begin_end{}, pika::execution::par.executor());
PIKA_TEST_EQ(params_count.load(), std::size_t(1));
PIKA_TEST_EQ(exec_count.load(), std::size_t(0));
}
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::mark_end_of_scheduling(
test_begin_end{}, test_executor_begin_end{});
PIKA_TEST_EQ(params_count.load(), std::size_t(0));
PIKA_TEST_EQ(exec_count.load(), std::size_t(1));
}
}
void test_mark_end_execution()
{
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::mark_end_execution(
test_begin_end{}, pika::execution::par.executor());
PIKA_TEST_EQ(params_count.load(), std::size_t(1));
PIKA_TEST_EQ(exec_count.load(), std::size_t(0));
}
{
params_count = 0;
exec_count = 0;
pika::parallel::execution::mark_end_execution(test_begin_end{}, test_executor_begin_end{});
PIKA_TEST_EQ(params_count.load(), std::size_t(0));
PIKA_TEST_EQ(exec_count.load(), std::size_t(1));
}
}
///////////////////////////////////////////////////////////////////////////////
int pika_main()
{
test_get_chunk_size();
test_maximal_number_of_chunks();
test_reset_thread_distribution();
test_processing_units_count();
test_mark_begin_execution();
test_mark_end_of_scheduling();
test_mark_end_execution();
return pika::finalize();
}
int main(int argc, char* argv[])
{
// By default this test should run on all available cores
std::vector<std::string> const cfg = {"pika.os_threads=all"};
// Initialize and run pika
pika::init_params init_args;
init_args.cfg = cfg;
PIKA_TEST_EQ_MSG(
pika::init(pika_main, argc, argv, init_args), 0, "pika main exited with non-zero status");
return 0;
}
|
#include "dataflow.h"
using namespace std;
using namespace TENET;
Dataflow::Dataflow(Statement &&st, PEArray &&pe, Mapping &&mp):
_st(move(st)),
_pe(move(pe)),
_mp(move(mp))
{}
isl_union_map*
Dataflow::GetSpaceMap()
{
isl_union_map *space_map = _mp.GetSpaceMap();
space_map = isl_union_map_intersect_domain(space_map, _st.GetDomain());
return space_map;
}
isl_union_map*
Dataflow::GetTimeMap()
{
isl_union_map *time_map = _mp.GetTimeMap();
time_map = isl_union_map_intersect_domain(time_map, _st.GetDomain());
return time_map;
}
isl_union_map*
Dataflow::GetSpaceTimeMap()
{
isl_union_map *space_time_map = _mp.GetSpaceTimeMap();
space_time_map = isl_union_map_intersect_domain(space_time_map, _st.GetDomain());
return space_time_map;
}
isl_union_set*
Dataflow::GetDomain()
{
return _st.GetDomain();
}
isl_union_map*
Dataflow::GetAccess(
string tensor_name,
AccessType type)
{
return _st.GetAccess(tensor_name, type);
}
isl_union_set*
Dataflow::GetSpaceDomain()
{
return isl_union_set_apply(this->GetDomain(), this->GetSpaceMap());
}
isl_union_set*
Dataflow::GetTimeDomain()
{
return isl_union_set_apply(this->GetDomain(), this->GetTimeMap());
}
isl_union_set*
Dataflow::GetSpaceTimeDomain()
{
return isl_union_set_apply(this->GetDomain(), this->GetSpaceTimeMap());
}
isl_union_map*
Dataflow::MapTimeToPrev(unsigned distance, bool is_range)
{
if (is_range == false) // querying the exact distance
{
if (distance == 0)
return isl_union_set_identity(this->GetTimeDomain());
else
{
isl_union_map *outer = this->MapTimeToPrev(distance, true);
isl_union_map *inner = this->MapTimeToPrev(distance - 1, true);
return isl_union_map_subtract(outer, inner);
}
}
else // querying time within a given distance
{
isl_union_map * ret = isl_union_set_identity(GetTimeDomain());
isl_union_map * neighbor = isl_union_set_lex_gt_union_set(GetTimeDomain(),
GetTimeDomain());
neighbor = isl_union_map_lexmax(neighbor);
neighbor = isl_union_map_union(neighbor, isl_union_map_copy(ret));
for (unsigned i = 0; i < distance; i++)
ret = isl_union_map_apply_range(ret, isl_union_map_copy(neighbor));
isl_union_map_free(neighbor);
return ret;
}
}
isl_union_map*
Dataflow::MapSpaceToNeighbor(unsigned distance, bool is_range)
{
if (is_range == false) // querying the exact distance
{
if (distance == 0)
return isl_union_set_identity(GetSpaceDomain());
else
{
isl_union_map *outer = this->MapSpaceToNeighbor(distance, true);
isl_union_map *inner = this->MapSpaceToNeighbor(distance - 1, true);
return isl_union_map_subtract(outer, inner);
}
}
else // querying space within a given distance
{
isl_union_map *ret = isl_union_set_identity(GetSpaceDomain());
isl_union_map *neighbor = _pe.GetInterconnect();
neighbor = isl_union_map_union(neighbor, isl_union_set_identity(_pe.GetDomain()));
for (unsigned i = 0; i < distance; i++)
ret = isl_union_map_apply_range(ret, isl_union_map_copy(neighbor));
isl_union_map_free(neighbor);
return ret;
}
}
/*
This function is used by many dataflow analysis methods to map a point representing
space-time to its neighbor. Space_distance and time_distance represent how many steps
should be counted.space_is_range and time_is_range represent whether we want neighbors
within a certain distance or neighbors with exact some distance. include_self represent
whether the point itself should be counted into neighbors. A usual setting is let
space_distance=time_distance=1, space_is_range=time_is_range=true, include_self=false.
Which count all points within one cycle and within 1 distance in PE array, not
including the point itself.
*/
isl_union_map*
Dataflow::MapSpaceTimeToNeighbor(
unsigned space_distance,
bool space_is_range,
unsigned time_distance,
bool time_is_range,
bool include_self)
{
isl_union_map *space_to_neighbor = MapSpaceToNeighbor(space_distance, space_is_range);
isl_union_map *time_to_neighbor = MapTimeToPrev(time_distance, time_is_range);
isl_union_map *space_time_to_neighbor = isl_union_map_product(space_to_neighbor, time_to_neighbor);
if (include_self == false)
{
isl_union_map *space_time_identity = isl_union_set_identity(GetSpaceTimeDomain());
space_time_to_neighbor = isl_union_map_subtract(space_time_to_neighbor, space_time_identity);
}
return space_time_to_neighbor;
}
isl_union_map *
Dataflow::MapSpaceTimeToAccess(string tensor_name, AccessType type)
{
isl_union_map *space_time_to_domain = isl_union_map_reverse(GetSpaceTimeMap());
isl_union_map *access = _st.GetAccess(tensor_name, type);
return isl_union_map_apply_range(space_time_to_domain, access);
}
/*
* GetUniqueVolume: the size of data required that cannot be find from
* neighbor in space-time domain
*/
int
Dataflow::GetUniqueVolume(
string tensor_name,
AccessType type,
isl_union_map *space_time_to_neighbor)
{
isl_union_map *access = MapSpaceTimeToAccess(tensor_name, type);
isl_union_map *neighbor_access = isl_union_map_apply_range(space_time_to_neighbor,
isl_union_map_copy(access));
isl_union_map *unique_access = isl_union_map_subtract(access, neighbor_access);
isl_union_pw_qpolynomial *unique_access_num = isl_union_map_card(unique_access);
#ifdef DEBUG
fprintf(stdout,"Unique Access Num for %s:\n",tensor_name.c_str());
p = isl_printer_print_union_pw_qpolynomial(p, unique_access_num);
p = isl_printer_end_line(p);
#endif
unique_access_num = isl_union_pw_qpolynomial_sum(unique_access_num); // sum on time
unique_access_num = isl_union_pw_qpolynomial_sum(unique_access_num); // sum on space
return convert_upwqp_to_int(unique_access_num);
}
/*
* GetTotalVolume: the size of data required in total when no data reuse
* is considered
*/
int
Dataflow::GetTotalVolume(string tensor_name, AccessType type)
{
isl_union_map *access = GetAccess(tensor_name, type);
isl_union_pw_qpolynomial *access_num = isl_union_map_card(access);
access_num = isl_union_pw_qpolynomial_sum(access_num);
return convert_upwqp_to_int(access_num);
}
double
Dataflow::GetTemporalReuseVolume(string tensor_name, AccessType type)
{
isl_union_map *stt_prev = MapSpaceTimeToNeighbor(0, false, 1, false, false);
int total_volume = GetTotalVolume(tensor_name, type);
int unique_volume = GetUniqueVolume(tensor_name, type, stt_prev);
int dsize = GetDomainSize();
return (double)(total_volume - unique_volume) / dsize;
}
double
Dataflow::GetSpatialReuseVolume(string tensor_name, AccessType type, isl_union_map *stt_neighbor)
{
if (stt_neighbor == NULL)
stt_neighbor = MapSpaceTimeToNeighbor(1, false, 1, true, false);
isl_union_map *stt_access = MapSpaceTimeToAccess(tensor_name, type);
isl_union_map *neighbor_access = isl_union_map_apply_range(isl_union_map_copy(stt_neighbor), isl_union_map_copy(stt_access));
isl_union_map *spatial_reuse = isl_union_map_intersect(stt_access, neighbor_access);
isl_union_pw_qpolynomial *spatial_reuse_num = isl_union_map_card(spatial_reuse);
spatial_reuse_num = isl_union_pw_qpolynomial_sum(spatial_reuse_num); // sum on time
spatial_reuse_num = isl_union_pw_qpolynomial_sum(spatial_reuse_num); // sum on space
double number = convert_upwqp_to_int(spatial_reuse_num);
int dsize = GetDomainSize();
double res = number / dsize;
return res;
}
/*
* GetReuseFactor: calculate reuse factor by TotalVolume/UniqueVolume
*/
double
Dataflow::GetReuseFactor(string tensor_name, AccessType type,
isl_union_map* space_time_to_neighbor)
{
int unique_volume = GetUniqueVolume(tensor_name, type, space_time_to_neighbor);
int total_volume = GetTotalVolume(tensor_name, type);
float reuse_factor = (float)total_volume / unique_volume;
return reuse_factor;
}
// this function is used to convert a union piecewise quasi-polynomial function that
// HAVE A EMPTY DOMAIN (that is, only have a value) to int
// upwqp is freed by this function.
int
Dataflow::convert_upwqp_to_int(isl_union_pw_qpolynomial *upwqp)
{
isl_printer *p = isl_printer_to_str(isl_union_pw_qpolynomial_get_ctx(upwqp));
p = isl_printer_set_output_format(p, ISL_FORMAT_ISL);
p = isl_printer_print_union_pw_qpolynomial(p, upwqp);
char *s = isl_printer_get_str(p);
int ret = atoi(s + 1);
isl_union_pw_qpolynomial_free(upwqp);
isl_printer_free(p);
return ret;
}
int
Dataflow::GetDomainSize()
{
isl_union_set *domain = _st.GetDomain();
isl_union_pw_qpolynomial* domain_size = isl_union_set_card(domain);
int dsize = convert_upwqp_to_int(domain_size);
return dsize;
}
/* Calculate the number of MACs by calculating number of instances* MACs
* per instance
*/
int
Dataflow::GetMacNum(int mac_per_instance)
{
int dsize = GetDomainSize();
return dsize * mac_per_instance;
}
int
Dataflow::GetTotalTime()
{
isl_union_set *time_domain = GetTimeDomain();
isl_union_pw_qpolynomial* domain_size = isl_union_set_card(time_domain);
int time_elapse = convert_upwqp_to_int(domain_size);
return time_elapse;
}
int
Dataflow::GetPENum()
{
isl_union_set *space_domain = GetSpaceDomain();
isl_union_pw_qpolynomial* domain_size = isl_union_set_card(space_domain);
int dsize = convert_upwqp_to_int(domain_size);
return dsize;
}
int
Dataflow::GetMacNumPerPE(int mac_per_instance)
{
int mac_num = GetMacNum(mac_per_instance);
// use GetSpaceDomain instead of pe.Getdomain() here in case some pes
// are idle
int dsize = GetPENum();
return mac_num / dsize;
}
int
Dataflow::GetActivePENum()
{
isl_union_set *space_domain = GetSpaceDomain();
isl_union_pw_qpolynomial* domain_size = isl_union_set_card(space_domain);
int dsize = convert_upwqp_to_int(domain_size);
return dsize;
}
/* return the average active PE num over time-domain*/
double
Dataflow::GetAverageActivePENum()
{
isl_union_set *space_time_domain = GetSpaceTimeDomain();
isl_union_pw_qpolynomial* space_time_domain_size = isl_union_set_card(space_time_domain);
int stsize = convert_upwqp_to_int(space_time_domain_size);
isl_union_set *time_domain = GetTimeDomain();
isl_union_pw_qpolynomial* time_domain_size = isl_union_set_card(time_domain);
int tsize = convert_upwqp_to_int(time_domain_size);
double avg_active_pe = (double)stsize / tsize;
return avg_active_pe;
}
int
Dataflow::GetIngressDelay(isl_union_map* space_time_to_neighbor, string tensor_name)
{
long long ingress_volume =
GetUniqueVolume(tensor_name, AccessType::READ, space_time_to_neighbor)*BIT_PER_ITEM;
return ingress_volume / _pe.GetBandwidth() + _pe.GetAvgLatency() - 1;
}
int
Dataflow::GetEgressDelay(isl_union_map* space_time_to_neighbor, string tensor_name)
{
long long egress_volume =
GetUniqueVolume(tensor_name, AccessType::WRITE, space_time_to_neighbor)*BIT_PER_ITEM;
return egress_volume / _pe.GetBandwidth() + _pe.GetAvgLatency() - 1;
}
int
Dataflow::GetComputationDelay()
{
return GetMacNumPerPE();
}
int
Dataflow::GetDelay(isl_union_map* space_time_to_neighbor)
{
// int max_delay = 0;
int ingress_delay = GetIngressDelay(isl_union_map_copy(space_time_to_neighbor));
int egress_delay = GetEgressDelay(space_time_to_neighbor);
int compute_delay = GetComputationDelay();
return max(max(ingress_delay, egress_delay), compute_delay);
}
int
Dataflow::GetL1Read(string tensor_name, AccessType type)
{
if (type == AccessType::READ || type == AccessType::WRITE)
return GetTotalVolume(tensor_name, type);
else
// for tensor that both be input and output, one L1 read for L1->PE and one for L1->L2
return GetTotalVolume(tensor_name, AccessType::READ) + GetTotalVolume(tensor_name, AccessType::WRITE);
}
int
Dataflow::GetL1Write(string tensor_name, AccessType type)
{
if (type == AccessType::READ || type == AccessType::WRITE)
return GetTotalVolume(tensor_name, type);
else
// for tensor that both be input and output, one L1 write for L2->L1 and one for PE->L1
return GetTotalVolume(tensor_name, AccessType::READ) + GetTotalVolume(tensor_name, AccessType::WRITE);
}
int
Dataflow::GetL2Read(
string tensor_name,
AccessType type,
isl_union_map* space_time_to_neighbor)
{
if (type == AccessType::READ || type == AccessType::WRITE)
// reuse can be exploited to reduce L2 read
return GetUniqueVolume(tensor_name, type, space_time_to_neighbor);
else
// for tensor that both be input and output, one L2 read for L2->L1 and one for L2->DRAM
return GetUniqueVolume( tensor_name, AccessType::READ,
isl_union_map_copy(space_time_to_neighbor)
) + GetUniqueVolume(tensor_name, AccessType::WRITE, space_time_to_neighbor);
}
int
Dataflow::GetL2Write(
string tensor_name,
AccessType type,
isl_union_map* space_time_to_neighbor)
{
if (type == AccessType::READ || type == AccessType::WRITE)
// reuse can be exploited to reduce L2 write
return GetUniqueVolume(tensor_name, type, space_time_to_neighbor);
else
// for tensor that both be input and output, one L2 write for DRAM->L2 and one for L1->L2
return GetUniqueVolume(tensor_name, AccessType::READ, isl_union_map_copy(space_time_to_neighbor)) +
GetUniqueVolume(tensor_name, AccessType::WRITE, space_time_to_neighbor);
}
int
Dataflow::GetEnergy(isl_union_map* space_time_to_neighbor)
{
int energy = GetMacNum(); // energy cost of MAC
auto [input, output] = _st.GetTensorList();
for (auto& iter : input)
{
energy += l1_multiplier * GetL1Read(iter, AccessType::READ);
energy += l1_multiplier * GetL1Write(iter, AccessType::READ);
energy += l2_multiplier * GetL2Read(iter, AccessType::READ,
isl_union_map_copy(space_time_to_neighbor));
energy += l2_multiplier * GetL2Write(iter, AccessType::READ,
isl_union_map_copy(space_time_to_neighbor));
}
for (auto& iter:output)
{
energy += l1_multiplier * GetL1Read(iter, AccessType::WRITE);
energy += l1_multiplier * GetL1Write(iter, AccessType::WRITE);
energy += l2_multiplier * GetL2Read(iter, AccessType::WRITE,
isl_union_map_copy(space_time_to_neighbor));
energy += l2_multiplier * GetL2Write(iter, AccessType::WRITE,
isl_union_map_copy(space_time_to_neighbor));
}
isl_union_map_free(space_time_to_neighbor);
return energy;
}
Dataflow
Dataflow::copy() const
{
return Dataflow(_st.copy(), _pe.copy(), _mp.copy());
}
|
#include "search-condition.h"
#include "wx/valgen.h"
#include "wx/valtext.h"
BEGIN_EVENT_TABLE(DisasterSearchDlg, wxDialog)
EVT_BUTTON(wxID_OK, DisasterSearchDlg::OnOk)
END_EVENT_TABLE()
DisasterSearchDlg::DisasterSearchDlg(const wxString& title)
:wxDialog(NULL,-1,title,wxDefaultPosition, wxSize(400,340))
{
new wxCheckBox(this,-1,wxT("类型"),wxPoint(30,30),wxSize(60,30),0,wxGenericValidator(&condition.istype));
comboInstanceType = new wxComboBox(this, -1, wxT("未知"),wxPoint(110,30),wxSize(100,30), 0, NULL, wxCB_READONLY|wxCB_DROPDOWN,wxGenericValidator(&typeName));
for(size_t index=0;index<DisasterInstance::disasterKind; index ++)
{
comboInstanceType->Append(DisasterInstance::DisasterNames[index] );
}
new wxCheckBox(this,-1,wxT("年份"),wxPoint(30,80),wxSize(60,30),0,wxGenericValidator(&condition.isyear));
new wxStaticText(this, -1, wxT("起始"),wxPoint(110,85),wxSize(30,30));
new wxTextCtrl(this, -1, wxT("2010"),wxPoint(150,80),wxSize(60,30), 0, wxTextValidator(wxFILTER_NUMERIC,&condition.beginYear) );
new wxStaticText(this, -1, wxT("结束"),wxPoint(260,85),wxSize(30,30));
new wxTextCtrl(this, -1, wxT("2010"),wxPoint(300,80),wxSize(60,30), 0, wxTextValidator(wxFILTER_NUMERIC,&condition.endYear) );
new wxCheckBox(this,-1,wxT("月份"),wxPoint(30,130),wxSize(60,30),0,wxGenericValidator(&condition.ismonth));
new wxStaticText(this, -1, wxT("起始"),wxPoint(110,135),wxSize(30,30));
new wxTextCtrl(this, -1, wxT("1"),wxPoint(150,130),wxSize(60,30), 0, wxTextValidator(wxFILTER_NUMERIC,&condition.beginMonth) );
new wxStaticText(this, -1, wxT("结束"),wxPoint(260,135),wxSize(30,30));
new wxTextCtrl(this, -1, wxT("12"),wxPoint(300,130),wxSize(60,30), 0, wxTextValidator(wxFILTER_NUMERIC,&condition.endMonth) );
new wxCheckBox(this,-1,wxT("关键词"),wxPoint(30,180),wxSize(70,30),0,wxGenericValidator(&condition.isword));
new wxTextCtrl(this, -1, wxT("输入关键词"),wxPoint(110,180),wxSize(250,30),0,wxGenericValidator(&condition.searchWord));
new wxButton(this, wxID_CANCEL, wxT("取消"),wxPoint(30,250),wxSize(100,30));
new wxButton(this, wxID_OK, wxT("搜索"),wxPoint(260,250),wxSize(100,30));
}
void DisasterSearchDlg::OnOk(wxCommandEvent& WXUNUSED(event) )
{
if ( Validate() && TransferDataFromWindow() )
{
condition.dstType = DisasterInstance::GetDisasterType(typeName);
EndModal(wxID_OK);
}
}
|
#pragma once
#include <iberbar/Utility/Platform.h>
#include <xmemory>
namespace iberbar
{
// 游戏命令基类
// 用于处理一些回调内部
class __iberbarUtilityApi__ CBaseCommand abstract
{
public:
virtual ~CBaseCommand() {}
virtual void Execute() = 0;
};
struct UCommandQueueOptions
{
bool bSync;
};
class __iberbarUtilityApi__ CCommandQueue abstract
{
public:
virtual ~CCommandQueue() {}
virtual void AddCommand( CBaseCommand* pCommand ) = 0;
virtual void Execute() = 0;
};
__iberbarUtilityApi__ CCommandQueue* CreateCommandQueue(
const UCommandQueueOptions& Options,
std::pmr::memory_resource* pMemoryRes );
__iberbarUtilityApi__ void DestroyCommandQueue( CCommandQueue* pQueue );
}
|
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_CHRONO_CPUMETER_H_INCLUDED
#define BEAST_CHRONO_CPUMETER_H_INCLUDED
#include "RelativeTime.h"
#include "ScopedTimeInterval.h"
#include "../threads/SharedData.h"
#include "../Atomic.h"
namespace beast {
/** Measurements of CPU utilization. */
class CPUMeter
{
private:
struct MeasureIdle
{
explicit MeasureIdle (CPUMeter& meter)
: m_meter (&meter)
{ }
void operator() (RelativeTime const& interval) const
{ m_meter->addIdleTime (interval); }
CPUMeter* m_meter;
};
struct MeasureActive
{
explicit MeasureActive (CPUMeter& meter)
: m_meter (&meter)
{ }
void operator() (RelativeTime const& interval) const
{ m_meter->addActiveTime (interval); }
CPUMeter* m_meter;
};
enum
{
// The amount of time an aggregate must accrue before a swap
secondsPerAggregate = 3
// The number of aggregates in the rolling history buffer
,numberOfAggregates = 20
};
// Aggregated sample data
struct Aggregate
{
RelativeTime idle;
RelativeTime active;
// Returns the total number of seconds in the aggregate
double seconds () const
{ return idle.inSeconds() + active.inSeconds(); }
// Reset the accumulated times
void clear ()
{ idle = RelativeTime (0); active = RelativeTime (0); }
Aggregate& operator+= (Aggregate const& other)
{ idle += other.idle; active += other.active; return *this; }
Aggregate& operator-= (Aggregate const& other)
{ idle -= other.idle; active -= other.active; return *this; }
};
struct State
{
State () : index (0)
{
}
// Returns a reference to the current aggregate
Aggregate& front ()
{
return history [index];
}
// Checks the current aggregate to see if we should advance
void update()
{
if (front().seconds() >= secondsPerAggregate)
advance();
}
// Advance the index in the rolling history
void advance ()
{
usage += history [index];
index = (index+1) % numberOfAggregates;
usage -= history [index];
history [index].clear ();
}
// Index of the current aggregate we are accumulating
int index;
// Delta summed usage over the entire history buffer
Aggregate usage;
// The rolling history buffer
Aggregate history [numberOfAggregates];
};
typedef SharedData <State> SharedState;
SharedState m_state;
void addIdleTime (RelativeTime const& interval)
{
SharedState::Access state (m_state);
state->front().idle += interval;
state->update();
}
void addActiveTime (RelativeTime const& interval)
{
SharedState::Access state (m_state);
state->front().active += interval;
state->update();
}
public:
/** The type of container that measures idle time. */
typedef ScopedTimeInterval <MeasureIdle> ScopedIdleTime;
typedef ScopedTimeInterval <MeasureActive> ScopedActiveTime;
/** Returns the fraction of time that the CPU is being used. */
double getUtilization () const
{
SharedState::ConstAccess state (m_state);
double const seconds (state->usage.seconds());
if (seconds > 0)
return (state->usage.active.inSeconds() / seconds);
return 0;
}
};
}
#endif
|
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
#define MAX_N 100000
int n, e[MAX_N], m[MAX_N];
int heat()
{
// pair 두 객체를 하나의 객체로 취급
vector<pair<int,int>> order;
for (int i = 0;i< n; ++i)
{
// make_pair 변수1,2 가 들어간 pair 만들기
order.push_back(make_pair(-e[i],i));
}
sort(order.begin(), order.end());
int ret = 0, beginEat = 0;
for (int i = 0; i < n; ++i)
{
int box = order[i].second;
beginEat += m[box];
ret = max(ret, beginEat + e[box]);
}
return ret;
}
int main(void)
{
cout << "LUNCHBOX"<<endl;
for (int i = 0; i < 2; i++)
{
e[i] = 2;
m[i] = 2;
}
int heat_n;
heat_n = heat();
cout << heat_n <<endl;
return 1;
}
|
#pragma once
#include <string>
#include <d3d11.h>
#include <DirectXMath.h>
class Device;
class VertexShader {
public:
// コンストラクタ
VertexShader() = default;
VertexShader(const VertexShader&) = default;
VertexShader(VertexShader&&) = default;
// デストラクタ
~VertexShader() = default;
// 代入演算子
VertexShader& operator=(const VertexShader&) = default;
VertexShader& operator=(VertexShader&&) = default;
/**
* 頂点シェーダの初期化関数
*
* file_name コンパイル済シェーダのパス
* device シェーダを登録するデバイス
*/
HRESULT initialize(const std::string& file_name, const Device& device);
/**
* 頂点シェーダの終了処理
*/
void finalize();
/**
* 頂点シェーダの取得
*/
ID3D11VertexShader* get() const { return pVertexShader; };
private:
// メンバ
ID3D11VertexShader* pVertexShader; // 作成した頂点シェーダの格納先
ID3D11InputLayout* pVertexLayout; // 作成した入力レイアウトの格納先
};
|
/****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#pragma once
namespace TG::Math
{
template<typename Scalar, typename PacketType, bool IsAligned, int Index, int Stop>
struct VectorizedDot
{
static void Run(Scalar& dot, Scalar const* left, Scalar const* right)
{
Scalar temp[unpacket_traits<PacketType>::Size];
pstoreu(temp,
pmul(ploadt<PacketType, IsAligned>(left + Index),
ploadt<PacketType, IsAligned>(right + Index))
);
for (int i = 0; i < unpacket_traits<PacketType>::Size; ++i)
dot += temp[i];
constexpr static int NextIndex = Index + unpacket_traits<PacketType>::Size;
VectorizedDot<Scalar, PacketType, IsAligned, NextIndex, Stop>::Run(dot, left, right);
}
};
template<typename Scalar, typename PacketType, bool IsAligned, int Stop>
struct VectorizedDot<Scalar, PacketType, IsAligned, Stop, Stop>
{
static void Run(Scalar&, Scalar const*, Scalar const*) {}
};
template<typename Scalar, int Index, int Stop>
struct DefaultDot
{
static void Run(Scalar& dot, Scalar const* left, Scalar const* right)
{
dot += left[Index] * right[Index];
DefaultDot<Scalar, Index + 1, Stop>::Run(dot, left, right);
}
};
template<typename Scalar, int Stop>
struct DefaultDot<Scalar, Stop, Stop>
{
static void Run(Scalar&, Scalar const*, Scalar const*) {}
};
template<typename Matrix>
struct DotOp
{
using Scalar = traits<Matrix>::Scalar;
constexpr static int SizeAtCompileTime = traits<Matrix>::SizeAtCompileTime;
static Scalar Run(const Matrix& left, const Matrix& right)
{
Scalar dot = 0;
if constexpr(SUPPORT_SIMD)
{
using PacketType = best_packet<Scalar, SizeAtCompileTime>;
constexpr static int Alignment = traits<Matrix>::IsDynamic ? DEFAULT_ALIGN_BYTES
: default_alignment<Scalar, SizeAtCompileTime>;
constexpr static bool IsAligned = Alignment >= unpacket_traits<PacketType>::Alignment;
constexpr static int VectorizableSize = (SizeAtCompileTime / unpacket_traits<PacketType>::Size)
* unpacket_traits<PacketType>::Size;
VectorizedDot<Scalar, PacketType, IsAligned, 0, VectorizableSize>::Run(dot, left.data(), right.data());
DefaultDot<Scalar, VectorizableSize, SizeAtCompileTime>::Run(dot, left.data(), right.data());
}
else
{
DefaultDot<Scalar, 0, SizeAtCompileTime>::Run(dot, left.data(), right.data());
}
return dot;
}
};
}
|
/*
This file is part of SMonitor.
Copyright 2015~2016 by: rayx email rayx.cn@gmail.com
SMonitor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SMonitor is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
// SMonitorApp.cpp : IMPLEMENTATION
//
#include "CSMonitorClient.h"
#include "CLoginDialog.h"
#include "NetClt.h"
#include "NetClass.h"
#include "CMessageDataMediator.h"
#include "SMonitorApp.h"
#include "CMisc.h"
#include "stdafx.h"
#include "CMessageEventMediator.h"
#include <QtWidgets/QApplication>
#include <QMessageBox>
#include <QSettings>
#include <QFile>
#include <QDebug>
#include <QTranslator>
#include <QTextCodec>
// CSMonitorApp
IMPLEMENT_DYNCREATE(CSMonitorApp, CWinApp)
CSMonitorApp::CSMonitorApp()
{
}
CSMonitorApp::~CSMonitorApp()
{
}
BOOL CSMonitorApp::InitInstance()
{
int nNum = 0;
char *chPara = "";
QApplication a(nNum, &chPara);
CoInitialize(NULL);
WSADATA wsaData;
int nResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (NO_ERROR != nResult)
{
QMessageBox::warning(NULL, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("SOCKET库启动失败"));
return FALSE;
}
//禁止双开
HANDLE hObject = CreateMutex(NULL, FALSE, m_pszExeName);
if(ERROR_ALREADY_EXISTS == GetLastError())
{
CloseHandle(hObject);
QMessageBox::warning(NULL, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("软件已经启动"));
return FALSE;
}
ClientLogger->Start(QApplication::applicationDirPath() + "/Log/");
NetClass->m_pMessageEventMediator = new CMessageEventMediator();
NetClass->m_pNetClt = new CNetClt(NetClass->m_pMessageEventMediator);
ClientLogger->AddLog(QString::fromLocal8Bit("---------------------------------------------"));
ClientLogger->AddLog(QString::fromLocal8Bit("客户端启动"));
//读取INI配置
readConfigure();
NetClass->m_pNetClt->SetIP(m_strSvrIP.toStdString().c_str());
NetClass->m_pNetClt->SetPort(m_nSvrPort);
NetClass->m_pNetClt->Start();
QFile file(":/Resources/blue.css");
if(file.open(QFile::ReadOnly))
{
ClientLogger->AddLog(QString::fromLocal8Bit("打开样式文件成功"));
if(CMisc::IsOsVerHigherXP())
qApp->setStyleSheet(QLatin1String(file.readAll()));
else
qApp->setStyleSheet(QLatin1String(file.readAll().append("\r\nQProgressBar::chunk{margin: 0.5px; background-color: #06B025;}")));
qApp->setPalette(QPalette(QColor("#F0F0F0")));
if(MessageDataMediator->m_bTextMode)
ClientLogger->AddLog(qApp->styleSheet());
file.close();
}
//查询门店信息
MessageDataMediator->QueryShopInfo(true);
CLoginDialog dlg;
bool bInputID = false;
if(m_strClientID.isEmpty())
{
if(dlg.exec() == QDialog::Rejected){
a.quit();
return 0;
}
bInputID = true;
}
CSMonitorClient w;
// if(bInputID || NetClass->m_pNetClt->m_bIsOnLine)
// {
// NetClass->m_pNetClt->SendMsg(EMSG_REQUESTXML, true);
// }
// else
// {
// NetClass->m_pNetClt->m_bAutoSendQueryXMLMsg = true;
// }
w.show();
return a.exec();
}
int CSMonitorApp::ExitInstance()
{
CoUninitialize();
WSACleanup();
return CWinApp::ExitInstance();
}
void CSMonitorApp::readConfigure()
{
QString path = QApplication::applicationDirPath() + "/configure.ini";
QSettings settings(path, QSettings::IniFormat);
settings.setIniCodec("UTF-8");
MessageDataMediator->m_strNewId = m_strClientID = getId();
m_strSvrIP = settings.value("ServerInfo/ServerIP", QVariant("")).toString();
m_nSvrPort = settings.value("ServerInfo/ServerPort", QVariant("")).toInt();
m_strHostName = settings.value("ServerInfo/HostName", QVariant("")).toString();
if(m_strSvrIP.isEmpty() && !m_strHostName.isEmpty())
{
QStringList strIpList = CMisc::GetIpByHostName(m_strHostName);
if(strIpList.count() <= 0)
{
ClientLogger->AddLog(QString::fromLocal8Bit("解析域名失败,错误码[%1]").arg(WSAGetLastError()));
}
else
{
m_strSvrIP = strIpList[0];
}
}
ClientLogger->AddLog(QString::fromLocal8Bit("服务器IP[%1]").arg(m_strSvrIP));
if(m_strSvrIP.isEmpty())
{
m_strSvrIP = "127.0.0.1";
}
if(0 == m_nSvrPort)
{
m_nSvrPort = 14640;
}
QSettings settingsRegedit(HKCU, QSettings::NativeFormat);
settingsRegedit.setIniCodec(QTextCodec::codecForName("UTF-8"));
MessageDataMediator->m_strSvrUpdateXmlUrl = settingsRegedit.value("XmlUrl/UpdateXml").toString();
MessageDataMediator->m_strHelpInfoXmlUrl = settingsRegedit.value("XmlUrl/HelpInfoXml").toString();
MessageDataMediator->m_strVersionCheckFile = settingsRegedit.value("XmlUrl/VersionCheckFile").toString();
//MessageDataMediator->m_bTextMode = settingsRegedit.value("Connect/TextMode").toString() == "1"; yhb
ClientLogger->AddLog(QString::fromLocal8Bit("客户端模式:[%1]").arg(MessageDataMediator->m_bTextMode ? QString::fromLocal8Bit("测试") : QString::fromLocal8Bit("正常")));
}
QString CSMonitorApp::getId()
{
QSettings settings(HKCU, QSettings::NativeFormat);
settings.setIniCodec("UTF-8");
return settings.value("RegisterID/ID", QString("")).toString();
}
BEGIN_MESSAGE_MAP(CSMonitorApp, CWinApp)
END_MESSAGE_MAP()
// CSMonitorApp 消息处理程序
|
#ifndef ImWrapper_H
#define ImWrapper_H
#include "YIM.h"
class ImWrapper : public IYIMChatRoomCallback,
public IYIMContactCallback,
public IYIMDownloadCallback,
public IYIMLoginCallback,
public IYIMMessageCallback,
public IYIMNoticeCallback
{
public:
ImWrapper();
~ImWrapper();
virtual void OnLogin(YIMErrorcode, const XString&){}
//登出回调
virtual void OnLogout(YIMErrorcode){ }
//被踢下线
virtual void OnKickOff(){ }
//加入频道回调
virtual void OnJoinChatRoom(YIMErrorcode, const XString) { }
//离开频道回调
virtual void OnLeaveChatRoom(YIMErrorcode , const XString& ) { }
//其他用户加入频道通知
virtual void OnUserJoinChatRoom(const XString&, const XString&) { }
//其他用户退出频道通知
virtual void OnUserLeaveChatRoom(const XString&, const XString&) { }
virtual void OnGetRoomMemberCount(YIMErrorcode, const XString&,
unsigned int) { }
//获取最近联系人回调
virtual void OnGetRecentContacts(YIMErrorcode,
std::list<std::shared_ptr<IYIMContactsMessageInfo> >& /*contactList*/) { }
//获取用户信息回调(用户信息为JSON格式)
virtual void OnGetUserInfo(YIMErrorcode,
const XString& /*userID*/, const XString& /*userInfo*/) { }
//查询用户状态回调
virtual void OnQueryUserStatus(YIMErrorcode,
const XString& userID, YIMUserStatus status) { }
//发送消息回调
virtual void OnSendMessageStatus(XUINT64 /*requestID*/, YIMErrorcode,
bool /*isForbidRoom*/, int /*reasonType*/, XUINT64 /*forbidEndTime*/ ) { }
//停止语音回调(调用StopAudioMessage停止语音之后,发送语音消息之前)
virtual void OnStartSendAudioMessage(XUINT64 requestID, YIMErrorcode,
const XString& text, const XString& audioPath, unsigned int audioTime) { }
//发送语音消息回调
virtual void OnSendAudioMessageStatus(XUINT64 /*requestID*/, YIMErrorcode,
const XString& /*text*/, const XString& /*audioPath*/,
unsigned int /*audioTime*/,
bool /*isForbidRoom*/,
int /*reasonType*/, XUINT64 /*forbidEndTime*/) { }
//收到消息
virtual void OnRecvMessage( std::shared_ptr<IYIMMessage> message) { }
//获取消息历史纪录回调
virtual void OnQueryHistoryMessage(YIMErrorcode,
const XString& /*targetID*/,
int /*remain*/, std::list<std::shared_ptr<IYIMMessage> > /*messageList*/) { }
//获取房间历史纪录回调
virtual void OnQueryRoomHistoryMessage(YIMErrorcode,
std::list<std::shared_ptr<IYIMMessage> > /*messageList*/) { }
//语音上传后回调
virtual void OnStopAudioSpeechStatus(YIMErrorcode,
std::shared_ptr<IAudioSpeechInfo> /*audioSpeechInfo*/) { }
//新消息通知(只有SetReceiveMessageSwitch设置为不自动接收消息,才会收到该回调)
virtual void OnReceiveMessageNotify(YIMChatType /*chatType*/,
const XString& /*targetID*/) { }
//文本翻译完成回调
virtual void OnTranslateTextComplete(YIMErrorcode,
unsigned int /*requestID*/, const XString& /*text*/,
LanguageCode /*srcLangCode*/, LanguageCode /*destLangCode*/) { }
//举报处理结果通知
virtual void OnAccusationResultNotify(AccusationDealResult /*result*/,
const XString& /*userID*/, unsigned int /*accusationTime*/) { }
virtual void OnGetForbiddenSpeakInfo( YIMErrorcode,
std::vector< std::shared_ptr<IYIMForbidSpeakInfo> > /*vecForbiddenSpeakInfos*/ ) { }
virtual void OnRecvNotice(YIMNotice * /*notice*/) {}
/*
* 功能:屏蔽/解除屏蔽用户消息回调
* @param errorcode:错误码
* @param userID
* @param block true-屏蔽 false-解除屏蔽
*/
virtual void OnBlockUser(YIMErrorcode,
const XString& /*userID*/, bool /*block*/) { }
/*
* 功能:解除所有已屏蔽用户回调
* @param errorcode 错误码
*/
virtual void OnUnBlockAllUser(YIMErrorcode) { }
/*
* 功能:获取被屏蔽消息用户回调
* @param errorcode:错误码
* @param userList userID集
*/
virtual void OnGetBlockUsers(YIMErrorcode, std::list<XString>) { }
private:
};
#endif // ImWrapper_H
|
// Plot BSM Z' Monte-Carlo kinematics.
//
// Created by Samvel Khalatyan, Apr 14, 2011
// Copyright 2011, All rights reserved
#include <boost/logic/tribool.hpp>
#include <TH1D.h>
#include <TLorentzVector.h>
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "DataFormats/HepMCCandidate/interface/GenParticle.h"
#include "bsm_mc/kinematics/interface/ZprimeKinematics.h"
using std::string;
using boost::tribool;
using edm::Handle;
using edm::InputTag;
using edm::LogInfo;
using edm::LogWarning;
using edm::ParameterSet;
using reco::Candidate;
using reco::GenParticle;
using reco::GenParticleCollection;
using bsm::ZprimeKinematics;
using bsm::Kinematics;
using bsm::DeltaKinematics;
ZprimeKinematics::ZprimeKinematics(const ParameterSet &config)
{
_gen_particles_collection_tag = config.getParameter<string>("genParticles");
}
ZprimeKinematics::~ZprimeKinematics()
{
}
// Privates
//
void ZprimeKinematics::beginJob()
{
edm::Service<TFileService> file_service;
_zprime_kinematics.reset(new Kinematics("zprime",
file_service.operator->()));
_zprime_kinematics->pt()->GetXaxis()->Set(50, 0, 500);
_top_kinematics.reset(new Kinematics("top",
file_service.operator->()));
_antitop_kinematics.reset(new Kinematics("atop",
file_service.operator->()));
_ttbar_kinematics.reset(new DeltaKinematics("ttbar",
file_service.operator->()));
_ttbar_mass = file_service->make<TH1D>("mtt", "M_{t#bar{t}}",
1000, 0, 5000);
_ttbar_mass->Sumw2();
_top_hadronic_kinematics.reset(new DeltaKinematics("top_hadronic",
file_service.operator->()));
_top_leptonic_kinematics.reset(new DeltaKinematics("top_leptonic",
file_service.operator->()));
_wboson_hadronic_kinematics.reset(new DeltaKinematics("wjj",
file_service.operator->()));
_wboson_leptonic_kinematics.reset(new DeltaKinematics("wlnu",
file_service.operator->()));
}
void ZprimeKinematics::analyze(const edm::Event &event,
const edm::EventSetup &setup)
{
if (event.isRealData())
return;
Handle<GenParticleCollection> gen_particles;
event.getByLabel(InputTag(_gen_particles_collection_tag), gen_particles);
int zprimes = 0;
for(GenParticleCollection::const_iterator particle = gen_particles->begin();
gen_particles->end() != particle;
++particle)
{
if (ZPRIME == abs(particle->pdgId()) &&
3 == particle->status() &&
1 == ++zprimes)
zprime(*particle);
}
if (1 < zprimes)
LogWarning("warning") << zprimes << " Zprimes are found in the same event";
}
void ZprimeKinematics::zprime(const GenParticle &particle)
{
_zprime_kinematics->process(particle);
const Candidate *top_candidate = 0;
const Candidate *antitop_candidate = 0;
int tops = 0;
int antitops = 0;
for(GenParticle::const_iterator product = particle.begin();
particle.end() != product;
++product)
{
if (3 != product->status())
continue;
switch(product->pdgId())
{
case TOP: if (1 == ++tops)
{
top(*product);
top_candidate = &*product;
}
break;
case ANTI_TOP: if (1 == ++antitops)
{
antitop(*product);
antitop_candidate = &*product;
}
break;
default: continue;
}
}
if (1 < tops)
LogWarning("warning") << tops << " tops are found in the Zprime decay";
if (1 < antitops)
LogWarning("warning") << antitops << " anti-tops are found in the Zprime decay";
if (!top_candidate ||
!antitop_candidate)
return;
ttbar(top_candidate, antitop_candidate);
}
void ZprimeKinematics::top(const Candidate &particle)
{
_top_kinematics->process(particle);
topDecay(particle);
}
void ZprimeKinematics::antitop(const Candidate &particle)
{
_antitop_kinematics->process(particle);
topDecay(particle);
}
void ZprimeKinematics::topDecay(const Candidate &particle)
{
tribool is_wboson_hadronic_decay = boost::indeterminate;
const Candidate *wboson = 0;
const Candidate *bottom = 0;
int wbosons = 0;
int bottoms = 0;
for(GenParticle::const_iterator product = particle.begin();
particle.end() != product;
++product)
{
if (3 != product->status())
continue;
switch(abs(product->pdgId()))
{
case BOTTOM: if (1 == ++bottoms)
bottom = &*product;
break;
case WBOSON: if (1 == ++wbosons)
{
is_wboson_hadronic_decay = isHadronicWbosonDecay(*product);
wboson = &*product;
}
break;
default: continue;
}
}
if (1 < wbosons)
LogWarning("warning") << wbosons << " wbosons are found in the top decay";
if (1 < bottoms)
LogWarning("warning") << bottoms << " bottoms are found in the top decay";
if (boost::indeterminate(is_wboson_hadronic_decay))
LogWarning("warning") << "Unsupported top decay";
else if (!bottom)
LogWarning("warning") << "bottom is not found";
else
{
if (is_wboson_hadronic_decay)
wbosonHadronicDecay(wboson, bottom);
else
wbosonLeptonicDecay(wboson, bottom);
}
}
void ZprimeKinematics::wbosonHadronicDecay(const Candidate *wboson,
const Candidate *bottom)
{
_top_hadronic_kinematics->process(wboson, bottom);
// Find two quarks
//
const Candidate *quark_1 = 0;
const Candidate *quark_2 = 0;
for(GenParticle::const_iterator product = wboson->begin();
wboson->end() != product
&& (!quark_1 || !quark_2);
++product)
{
if (3 != product->status())
continue;
if (!quark_1)
quark_1 = &*product;
else
quark_2 = &*product;
}
if (!quark_1 ||
!quark_2)
{
LogWarning("warning") << "Wboson hadronic decay: didn't find two quarks";
return;
}
_wboson_hadronic_kinematics->process(quark_1, quark_2);
}
void ZprimeKinematics::wbosonLeptonicDecay(const Candidate *wboson,
const Candidate *bottom)
{
_top_leptonic_kinematics->process(wboson, bottom);
// Find lepton and qark
//
const Candidate *lepton = 0;
for(GenParticle::const_iterator product = wboson->begin();
wboson->end() != product
&& !lepton;
++product)
{
if (3 != product->status())
continue;
switch(abs(product->pdgId()))
{
case ELECTRON: // fall through
case MUON: lepton = &*product;
break;
default: break;
}
}
if (!lepton)
return;
_wboson_leptonic_kinematics->process(lepton, bottom);
}
void ZprimeKinematics::ttbar(const Candidate *top, const Candidate *antitop)
{
_ttbar_kinematics->process(top, antitop);
TLorentzVector p4_top(top->p4().px(),
top->p4().py(),
top->p4().pz(),
top->p4().energy());
TLorentzVector p4_anti_top(antitop->p4().px(),
antitop->p4().py(),
antitop->p4().pz(),
antitop->p4().energy());
_ttbar_mass->Fill((p4_top + p4_anti_top).M());
}
bool ZprimeKinematics::isHadronicWbosonDecay(const Candidate &particle)
{
bool is_hadronic_decay = true;
for(GenParticle::const_iterator product = particle.begin();
particle.end() != product
&& is_hadronic_decay;
++product)
{
if (3 != product->status())
continue;
int pdgid = abs(product->pdgId());
if (10 < pdgid &&
19 > pdgid)
is_hadronic_decay = false;
}
return is_hadronic_decay;
}
// Utility: Kinematics
//
Kinematics::Kinematics(const std::string &prefix, TFileService *service)
{
_pt = service->make<TH1D>((prefix + "_pt").c_str(), "P_{T}",
100, 0, 1000);
_pt->Sumw2();
_eta = service->make<TH1D>((prefix + "_eta").c_str(), "#eta",
100, -5, 5);
_eta->Sumw2();
_phi = service->make<TH1D>((prefix + "_phi").c_str(), "#phi",
80, -4, 4);
_phi->Sumw2();
}
void Kinematics::process(const Candidate &particle)
{
if (_pt)
_pt->Fill(particle.p4().Pt());
if (_eta)
_eta->Fill(particle.p4().Eta());
if (_phi)
_phi->Fill(particle.p4().Phi());
}
TH1 *Kinematics::pt() const
{
return _pt;
}
TH1 *Kinematics::eta() const
{
return _eta;
}
TH1 *Kinematics::phi() const
{
return _phi;
}
// Utility: DeltaKinematics
//
DeltaKinematics::DeltaKinematics(const std::string &prefix, TFileService *service)
{
_dr = service->make<TH1D>((prefix + "_dr").c_str(), "#{delta}R",
100, 0, 10);
_dr->Sumw2();
}
void DeltaKinematics::process(const Candidate *p1, const Candidate *p2)
{
TLorentzVector p4_1(p1->p4().px(),
p1->p4().py(),
p1->p4().pz(),
p1->p4().energy());
TLorentzVector p4_2(p2->p4().px(),
p2->p4().py(),
p2->p4().pz(),
p2->p4().energy());
if (_dr)
_dr->Fill(p4_1.DeltaR(p4_2));
}
TH1 *DeltaKinematics::dr() const
{
return _dr;
}
DEFINE_FWK_MODULE(ZprimeKinematics);
|
#include<iostream>
#include<fstream>
#include <map>
#include<string>
using namespace std;
struct Hash_Map {
typedef long long datatype;
struct node {
datatype data = 0;
node *next = NULL;
node(datatype data, node *next) :data(data), next(next) {}
node() {}
};
long long search(const long long &a) {
long long i = a % capicity;
node *q = &hashmap[i];
for (auto p = q->next; p; q = p, p = p->next) {
if (p->data == a) {
return i;
}
}
return -1;
}
void del(const long long &a) {
node *q = &hashmap[a % capicity];
for (auto p = q->next; p; q = p, p = p->next) {
if (p->data == a) {
q->next = p->next;
delete(p);
mapsize--;
hashmap[a % capicity].data--;
cout << "deleted" << endl;
return;
}
}
cerr << "not found" << endl;
}
void insert(const long long &a) {
long long d = search(a);
if (d != -1) {
cerr << "exist" << endl;
return;
}
d = a % capicity;
hashmap[d].data++;
hashmap[d].next = new node(a, hashmap[d].next);
if (++mapsize > loadfactor*capicity)
rehash();
}
void print() {
for (long long i = 0; i < capicity; ++i) {
cout << i << ":";
for (auto p = hashmap[i].next; p; p = p->next) {
cout << p->data << ' ' ;
}
cout << endl;
}
cout << endl;
}
void print2() {
map<long long, long long> m;
for (long long i = 0; i < capicity; ++i) {
if (hashmap[i].data == 0) cout << '1';
m[hashmap[i].data]++;
//cout << i << ":" << hashmap[i].data<<endl;
//for (auto p = hashmap[i].next; p; p = p->next) {
// cout << p->data << ' ';
//}
//cout << endl;
}
//long long sum = 0;
//for (auto j : m) {
//cout << j.first << ":" << j.second << endl;
//sum += j.second;
//}
//cout << sum << ' ' << capicity << endl;
cout << m[0] << endl << capicity;
cout << "\n0rate: "<<(double) m[0] / capicity;
cout << endl;
}
void rehash() {
long long top = 0;
node **hashmap_tmp = new node*[mapsize];
node *newhashmap = new node[2 * capicity];
for (long long i = 0; i < capicity; ++i) {
for (auto p = hashmap[i].next; p; p = p->next)
hashmap_tmp[top++] = p;
}
capicity *= 2;
for (long long i = 0; i < mapsize; ++i) {
node *p = hashmap_tmp[i];
long long j = p->data % capicity;
p->next = newhashmap[j].next;
newhashmap[j].next = p;
newhashmap[j].data++;
}
delete[] hashmap;
hashmap = newhashmap;
}
Hash_Map() {
hashmap = new node[capicity];
}
private:
node *hashmap;
long long mapsize = 0;
long long capicity = 3;
double loadfactor = 3;
};
void test() {
Hash_Map h;
ifstream fin("f:\\desktop\\testData_0_9999999.csv");
long long n, a, b;
//fin.getline();
string str;
getline(fin, str);
for (long long i = 0; i < 10000000; ++i) {
fin >> a;
h.insert(a);
}
fin.close();
h.print2();
}
void main() {
test();
system("pause");
/*
Hash_Map h;
long long a;
cout << "1:insert 2:search 3:delete 4:print -1:exit\n";
for (;;) {
if (cin >> a, a == -1) break;
switch (a) {
case 1:
cin >> a;
h.insert(a);
break;
case 2:
cin >> a;
if (h.search(a) != -1)
cout << "found" << endl;
else
cout << "not found" << endl;
break;
case 3:
cin >> a;
h.del(a);
break;
case 4:
cout <<"size:"<< h.size() << endl;
h.print();
break;
default:
break;
}
}*/
}
|
/*
Copyright (c) 2021-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/tests/blob/main/LICENSE.txt
*/
#ifndef _ISHIKO_CPP_TESTS_HPP_
#define _ISHIKO_CPP_TESTS_HPP_
#include "TestFramework/Core.hpp"
#if 0 // TODO
#ifdef _DEBUG
#pragma comment(lib, "IshikoTestFramework-d.lib")
#else
#pragma comment(lib, "IshikoTestFramework.lib")
#endif
#endif
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.