text
stringlengths
8
6.88M
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Alexander Remen (alexr) */ #include "core/pch.h" #include "InsertLinkDialog.h" #include "adjunct/quick_toolkit/widgets/Dialog.h" #include "adjunct/m2_ui/widgets/RichTextEditor.h" #include "modules/widgets/OpEdit.h" #ifdef M2_SUPPORT void InsertLinkDialog::Init(DesktopWindow * parent_window, RichTextEditor* rich_text_editor, OpString title) { m_title.Set(title); m_rich_text_editor = rich_text_editor; Dialog::Init(parent_window); } void InsertLinkDialog::OnInit() { if (m_title.HasContent()) { SetWidgetText("Title_edit",m_title.CStr()); SetWidgetEnabled("Title_edit",FALSE); } SetWidgetValue("Radio_use_web_address",TRUE); OpEdit* web_url_edit = GetWidgetByName<OpEdit>("web_url_edit", WIDGET_TYPE_EDIT); if (web_url_edit) { web_url_edit->SetText(UNI_L("http://")); web_url_edit->SetForceTextLTR(TRUE); } OpEdit* mailto_url_edit = GetWidgetByName<OpEdit>("mailto_url_edit", WIDGET_TYPE_EDIT); if (mailto_url_edit) { mailto_url_edit->SetEnabled(FALSE); mailto_url_edit->SetForceTextLTR(TRUE); if (SupportsExternalCompositing()) mailto_url_edit->autocomp.SetType(AUTOCOMPLETION_CONTACTS); } } void InsertLinkDialog::OnClick(OpWidget *widget, UINT32 id) { if (widget->IsNamed("Radio_use_web_address")) { SetWidgetEnabled("mailto_url_edit",FALSE); SetWidgetEnabled("web_url_edit",TRUE); } else if (widget->IsNamed("Radio_use_mailto_address")) { SetWidgetEnabled("mailto_url_edit",TRUE); SetWidgetEnabled("web_url_edit",FALSE); } Dialog::OnClick(widget, id); } UINT32 InsertLinkDialog::OnOk() { OpString address, title, resolved_address; GetWidgetText("Title_edit",title); if (GetWidgetValue("Radio_use_web_address")) { GetWidgetText("web_url_edit",address); } else { GetWidgetText("mailto_url_edit",address); if (address.Compare(UNI_L("mailto:")) != 0) address.Insert(0,UNI_L("mailto:")); } g_url_api->ResolveUrlNameL(address,resolved_address,TRUE); m_rich_text_editor->InsertLink(title,resolved_address); return 0; } #endif // M2_SUPPORT
#pragma once #include "FwdDecl.h" #include "Keng/Graphics/Resource/IEffect.h" #include "Resource/Shader/Shader.h" #include "Keng/GPU/PipelineInput/IInputLayout.h" #include "Keng/GPU/Shader/IDeviceShader.h" namespace keng::graphics { class Device; class Effect : public core::RefCountImpl<IEffect> { public: Effect(); ~Effect(); // IEffect virtual void InitDefaultInputLayout() override final; virtual void AssignToPipeline() override final; gpu::IInputLayoutPtr m_inputLayout; core::Ptr<Shader<ShaderType::Vertex>> vs; core::Ptr<Shader<ShaderType::Fragment>> fs; }; }
#pragma once #include "Keng/GPU/FwdDecl.h" #include "Keng/GraphicsCommon/FragmentFormat.h" #include "EverydayTools/Array/ArrayView.h" namespace keng::graphics::gpu { class ITexture : public core::IRefCountObject { public: virtual FragmentFormat GetFormat() const = 0; virtual void AssignToPipeline(const ShaderType& shaderType, size_t slot) = 0; virtual void CopyTo(ITexture&) const = 0; virtual void SetData(edt::DenseArrayView<const uint8_t> data) = 0; virtual size_t GetWidth() const = 0; virtual size_t GetHeight() const = 0; virtual IDevicePtr GetDevice() const = 0; virtual ~ITexture() = default; }; }
#include<stdio.h> #include<math.h> int main() { long long n, t, count; scanf("%lld",&t); for(int i = 1; i<=t; i++) { scanf("%lld",&n); count = 0; for (int i = 2; i <= sqrt(n); i++) { if (n%i == 0) { count = 1; break; } } if (count != 1 && n!=1) printf("Prime\n"); else printf("Not Prime\n"); } return 0; }
#include "vm/processor.hpp" #include <utility> #include <string> #include <type_traits> #include <cstdint> #include <algorithm> #include <iterator> #ifdef _MSC_VER # include <Windows.h> # define sys_debug_break() DebugBreak() #else # ifdef __GNUC__ // TODO: does this always work on gcc? Maybe let cmake find out and generate a configuration file. # include <csignal> # define sys_debug_break() std::raise(SIGTRAP) # else // the best we can do? # include <iostream> # define sys_debug_break() std::cerr << "please break here" << std::endl; # endif #endif namespace perseus { namespace detail { processor::processor( code_segment&& code, std::vector< syscall >&& syscalls ) : _code( std::move( code ) ) , _syscalls( std::move( syscalls ) ) { } stack processor::execute( const instruction_pointer::value_type start_address, stack&& parameters ) { std::vector< coroutine* > active_coroutines{ &_coroutine_manager.new_coroutine( _code, start_address, std::move( parameters ) ) }; while( true ) { coroutine& co = *active_coroutines.back(); instruction_pointer& ip = co.instruction_pointer; const opcode instruction = ip.read< opcode >(); switch( instruction ) { case opcode::no_operation: break; case opcode::exit: { if( active_coroutines.size() > 1 ) { throw exit_in_coroutine( "opcode::exit in coroutine!" ); } stack result = std::move( co.stack ); co.current_state = coroutine::state::dead; _coroutine_manager.delete_coroutine( co.index ); return result; } case opcode::syscall: { const std::uint32_t index = ip.read< std::uint32_t >(); if( index >= _syscalls.size() ) { throw invalid_syscall( "Invalid syscall!" ); } _syscalls[ index ]( co.stack ); break; } case opcode::low_level_break: { sys_debug_break(); break; } // Coroutines case opcode::absolute_coroutine: case opcode::indirect_coroutine: { const coroutine::identifier id = _coroutine_manager.new_coroutine( _code, instruction == opcode::absolute_coroutine ? ip.read< instruction_pointer::value_type >() : co.stack.pop< instruction_pointer::value_type >() ).index; co.stack.push< coroutine::identifier >( id ); break; } case opcode::resume_coroutine: case opcode::resume_pushing_everything: { coroutine& co_to_resume = _coroutine_manager.get_coroutine( co.stack.pop< coroutine::identifier >() ); if( co_to_resume.current_state == coroutine::state::live ) { throw resuming_live_coroutine( "Trying to resume a live coroutine!" ); } if( co_to_resume.current_state == coroutine::state::dead ) { throw resuming_dead_coroutine( "Trying to resume a dead coroutine!" ); } co_to_resume.stack.append( instruction == opcode::resume_coroutine ? co.stack.split( ip.read< std::uint32_t >() ) : std::move( co.stack ) ); co_to_resume.current_state = coroutine::state::live; active_coroutines.push_back( &co_to_resume ); break; } case opcode::coroutine_state: co.stack.push< coroutine::state >( _coroutine_manager.get_coroutine( co.stack.pop < coroutine::identifier >() ).current_state ); break; case opcode::delete_coroutine: _coroutine_manager.delete_coroutine( co.stack.pop< coroutine::identifier >() ); break; case opcode::coroutine_return: case opcode::yield: { // is this the root coroutine? can't leave that one without exit. if( active_coroutines.size() == 1 ) { throw no_coroutine( std::string( "Trying to " ) + ( instruction == opcode::yield ? "yield" : "return" ) + " from last coroutine!" ); } co.current_state = instruction == opcode::yield ? coroutine::state::suspended : coroutine::state::dead; active_coroutines.pop_back(); coroutine& previous_co = *active_coroutines.back(); previous_co.stack.append( co.stack.split( ip.read< std::uint32_t >() ) ); break; } case opcode::push_coroutine_identifier: co.stack.push< coroutine::identifier >( co.index ); break; // Push/Pop case opcode::push_8: co.stack.push< char >( ip.read< char >() ); break; case opcode::push_32: co.stack.push< std::int32_t >( ip.read< std::int32_t >() ); break; case opcode::reserve: co.stack.resize( co.stack.size() + ip.read< std::uint32_t >() ); break; case opcode::pop: co.stack.discard( ip.read< std::uint32_t >() ); break; // Load/Store case opcode::absolute_load_current_stack: case opcode::absolute_load_stack: case opcode::relative_load_stack: { const std::uint32_t size = ip.read< std::uint32_t >(); // FIXME: does not catch underflow errors // note: co.stack.size() would have to be from_co.stack.size(), but in the case of relative_load_stack from_co = co const std::uint32_t address = instruction == opcode::relative_load_stack ? ip.read< std::int32_t >() + co.stack.size() : co.stack.pop< std::uint32_t >(); const coroutine& from_co = instruction == opcode::absolute_load_stack ? _coroutine_manager.get_coroutine( co.stack.pop< std::uint32_t >() ) : co; if( address + size > from_co.stack.size() ) { throw stack_segmentation_fault( "stack segmentation fault: read above top of stack" ); } // ensure there are no iterator-invalidating reallocations during copying co.stack.reserve( co.stack.size() + size ); std::copy( from_co.stack.begin() + address, from_co.stack.begin() + address + size, std::back_inserter( co.stack ) ); break; } case opcode::absolute_store_current_stack: case opcode::absolute_store_stack: case opcode::relative_store_stack: { const std::uint32_t size = ip.read< std::uint32_t >(); // FIXME: does not catch underflow errors // as above: co.stack.size() should be to_co.stack.size(), but for relative_store_stack to_co = co const std::uint32_t address = instruction == opcode::relative_store_stack ? ip.read< std::int32_t >() + co.stack.size() : co.stack.pop< std::uint32_t >(); coroutine& to_co = instruction == opcode::absolute_store_stack ? _coroutine_manager.get_coroutine( co.stack.pop< std::uint32_t >() ) : co; if( address + size > to_co.stack.size() ) { throw stack_segmentation_fault( "stack segmentation fault: write above top of stack" ); } std::copy( co.stack.end() - size, co.stack.end(), to_co.stack.begin() + address ); break; } case opcode::push_stack_size: co.stack.push< std::uint32_t >( co.stack.size() ); break; // Jumps/Calls case opcode::absolute_jump: ip = ip.read< std::uint32_t >(); break; case opcode::relative_jump: ip += ip.read< std::int32_t >(); break; case opcode::relative_jump_if_false: { std::int32_t offset = ip.read< std::int32_t >(); if( !co.stack.pop< std::uint8_t >() ) { ip += offset; } break; } case opcode::indirect_jump: ip = co.stack.pop< std::uint32_t >(); break; case opcode::call: { const std::uint32_t target_address = ip.read< std::uint32_t >(); co.stack.push< std::uint32_t >( ip.value() ); ip = target_address; break; } case opcode::indirect_call: { const std::uint32_t target_address = co.stack.pop< std::uint32_t >(); co.stack.push< std::uint32_t >( ip.value() ); ip = target_address; break; } case opcode::return_: { const std::uint32_t return_address = co.stack.pop< std::uint32_t >(); // discard parameters co.stack.discard( ip.read< std::uint32_t >() ); ip = return_address; break; } // Boolean operations case opcode::and_b: { const std::uint8_t op2 = co.stack.pop< std::uint8_t >(), op1 = co.stack.pop< std::uint8_t >(); co.stack.push< std::uint8_t >( op1 && op2 ); break; } case opcode::or_b: { const std::uint8_t op2 = co.stack.pop< std::uint8_t >(), op1 = co.stack.pop< std::uint8_t >(); co.stack.push< std::uint8_t >( op1 || op2 ); break; } case opcode::equals_b: { const std::uint8_t op2 = co.stack.pop< std::uint8_t >(), op1 = co.stack.pop< std::uint8_t >(); co.stack.push< std::uint8_t >( op1 == op2 ); break; } case opcode::not_equals_b: { const std::uint8_t op2 = co.stack.pop< std::uint8_t >(), op1 = co.stack.pop< std::uint8_t >(); co.stack.push< std::uint8_t >( op1 != op2 ); break; } case opcode::negate_b: co.stack.push< std::uint8_t >( !co.stack.pop< std::uint8_t >() ); break; // 32 bit integer operations case opcode::add_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::int32_t >( op1 + op2 ); break; } case opcode::subtract_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::int32_t >( op1 - op2 ); break; } case opcode::multiply_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::int32_t >( op1 * op2 ); break; } case opcode::divide_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); if( op2 == 0 ) { throw divide_by_zero( "divide by zero" ); } co.stack.push< std::int32_t >( op1 / op2 ); break; } case opcode::equals_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::uint8_t >( op1 == op2 ); break; } case opcode::not_equals_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::uint8_t >( op1 != op2 ); break; } case opcode::less_than_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::uint8_t >( op1 < op2 ); break; } case opcode::less_than_or_equals_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::uint8_t >( op1 <= op2 ); break; } case opcode::greater_than_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::uint8_t >( op1 > op2 ); break; } case opcode::greater_than_or_equals_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); co.stack.push< std::uint8_t >( op1 >= op2 ); break; } case opcode::negate_i32: co.stack.push< std::int32_t >( -co.stack.pop< std::int32_t >() ); break; case opcode::modulo_i32: { const std::int32_t op2 = co.stack.pop< std::int32_t >(), op1 = co.stack.pop< std::int32_t >(); if( op2 == 0 ) { throw divide_by_zero( "divide by zero" ); } co.stack.push< std::int32_t >( op1 % op2 ); break; } default: throw invalid_opcode( "Invalid opcode " + std::to_string( static_cast< std::underlying_type_t< opcode > >( instruction ) ) ); } } } } }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2002 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 XSLT_SUPPORT #include "modules/xslt/src/xslt_template.h" #include "modules/xslt/src/xslt_parser.h" #include "modules/xslt/src/xslt_stylesheet.h" #include "modules/xslt/src/xslt_utils.h" #include "modules/xslt/src/xslt_program.h" #include "modules/xpath/xpath.h" #include "modules/util/tempbuf.h" XSLT_Template::XSLT_Template (XSLT_Import *import, unsigned import_precedence) : import (import), import_url (import ? import->url : URL()), import_precedence (import_precedence), match (GetXPathExtensions (), 0), has_name (FALSE), has_mode (FALSE), has_priority (FALSE), priority (0.f), params (NULL), program (XSLT_Program::TYPE_TEMPLATE) { OP_ASSERT (import_precedence != ~0u); #ifdef XSLT_PROGRAM_DUMP_SUPPORT program.program_description.SetL("anonymous template program"); #endif // XSLT_PROGRAM_DUMP_SUPPORT } XSLT_Template::~XSLT_Template () { while (params) { Param* next = params->next; OP_DELETE (params); params = next; } } void XSLT_Template::AddParamL (const XMLExpandedName &name, XSLT_Variable* variable) { OpStackAutoPtr<Param> param (OP_NEW_L (Param, ())); param->name.SetL (name); param->variable = variable; param->next = params; params = param.release (); } void XSLT_Template::CompileTemplateL (XSLT_StylesheetParserImpl *parser, XSLT_StylesheetImpl *stylesheet) { XSLT_XPathExtensions extensions (this, TRUE); match.PreprocessL (parser, &extensions); XSLT_Compiler compiler (stylesheet, parser); ANCHOR (XSLT_Compiler, compiler); XSLT_TemplateContent::CompileL (&compiler); compiler.FinishL (&program); if (has_mode) LEAVE_IF_ERROR (program.SetMode (mode)); #ifdef XSLT_PROGRAM_DUMP_SUPPORT if (has_name) { OpString8 template_name; template_name.SetUTF8FromUTF16L (name.GetLocalPart ()); program.program_description.Empty (); program.program_description.AppendFormat ("template program '%s'", template_name.CStr ()); } else if (match.GetSource()) { OpString8 source; source.SetUTF8FromUTF16L (match.GetSource ()); program.program_description.Empty (); program.program_description.AppendFormat ("template program matching '%s'", source.CStr ()); } #endif // XSLT_PROGRAM_DUMP_SUPPORT } float XSLT_Template::GetPatternPriority (unsigned index) { if (has_priority) return priority; else return match.GetPatterns ()[index]->GetPriority (); } /* virtual */ BOOL XSLT_Template::EndElementL (XSLT_StylesheetParserImpl *parser) { if (parser) { match.SetNamespaceDeclaration (parser); parser->GetStylesheet ()->AddTemplateL (this); return FALSE; } else return TRUE; } /* virtual */ void XSLT_Template::AddAttributeL (XSLT_StylesheetParserImpl *parser, XSLT_AttributeType type, const XMLCompleteNameN &completename, const uni_char *value, unsigned value_length) { switch (type) { case XSLTA_NAME: parser->SetQNameAttributeL (value, value_length, FALSE, 0, &name); has_name = TRUE; break; case XSLTA_MATCH: match.SetSourceL (parser, completename, value, value_length); break; case XSLTA_MODE: parser->SetQNameAttributeL (value, value_length, FALSE, 0, &mode); has_mode = TRUE; break; case XSLTA_PRIORITY: if (XSLT_Utils::ParseFloatL (priority, value, value_length)) has_priority = TRUE; else SignalErrorL (parser, "invalid priority attribute value"); break; default: XSLT_TemplateContent::AddAttributeL (parser, type, completename, value, value_length); } } #endif // XSLT_SUPPORT
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #include "ui/TabIcon.hpp" #include "draw.hpp" using namespace ui; TabIcon::TabIcon(){} void TabIcon::draw(const draw::DrawingAttr & attr){ drawing_point_t p; drawing_dim_t d; DrawingAttr icon_draw_attr; d = attr.d(); p = attr.p(); Tab::calc_square(p, d); icon_draw_attr = attr; icon_draw_attr.set_point(p); icon_draw_attr.set_dim(d); icon().draw(icon_draw_attr); }
#include "snake.h" #include<QKeyEvent> #include<QTimer> #include<QObject> #include<QList> #include "food.h" #include<QGraphicsScene> #include<QGraphicsView> #include<QGraphicsItem> #include<QDebug> #include<QPainter> #include<QPushButton> #include<QObject> #include<QApplication> #include "creasnake.h" #include<QLabel> snake::snake() { die->setMedia(QUrl("qrc:/sound/die.wav")); eat->setMedia(QUrl("qrc:/sound/eff.wav")); //set the music QBrush brush; brush.setStyle(Qt::SolidPattern); brush.setColor(Qt::black); view->setBackgroundBrush(brush); // set the color of the background playground->setSceneRect(0, 0, 550, 550); // set the size of the scene view->setFixedSize(550, 550); // set the size for the view playground->addItem(this); // add snake to the scene food* f = new food(); playground->addItem(f);// add food to the scene playground->addItem(scores); // add scores to the scene scores->setPos( 20, 20); // set the location of the score being displayed during the game /**********/ QBrush brush2; brush2.setStyle(Qt::SolidPattern); brush2.setColor(Qt::red); setBrush(brush2); // set color of the snake head setRect(275,275,20,20); // set location and size of the snake head setFlag(QGraphicsItem::ItemIsFocusable); setFocus(); // make the snake head focused sbody* body1 = new sbody(); bodies.prepend(body1); scene()->addItem(body1); // add a sbody to the scene QBrush brush3; brush3.setStyle(Qt::SolidPattern); brush3.setColor(Qt::yellow); body1->setBrush(brush3); // set the color for the sbody setPos(x(), y()+21); //avoid the collision between head and body at initial position headPos = pos(); } /* match the four direction keys to four movement functions */ void snake::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Left&!movingright&!movingleft) //avoid the snake going directly to an opposite position moveleft(); else if(event->key() == Qt::Key_Right&!movingleft&!movingright) moveright(); else if (event->key() == Qt::Key_Up&!movingdown&!movingup) moveup(); else if (event->key() == Qt::Key_Down&!movingup&!movingdown) movedown(); } void snake::moveup() { QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(down())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(left())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(right())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(up())); // disconnect the timer with all movements QObject::connect(timer, SIGNAL(timeout()),this,SLOT(up())); // connect the timer with upward movement timer->start(speed); // start the timer movingup = true; // make movingup true movingdown = false; movingleft = false; movingright =false; } /*reference the moveup() function, everything is defined in a similar fashion*/ void snake::movedown() { QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(up())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(down())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(left())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(right())); QObject::connect(timer, SIGNAL(timeout()),this,SLOT(down())); timer->start(speed); movingup = false; movingdown = true; movingleft = false; movingright =false; } /*reference the moveup() function, everything is defined in a similar fashion*/ void snake::moveleft() { QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(down())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(up())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(right())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(left())); QObject::connect(timer, SIGNAL(timeout()),this,SLOT(left())); timer->start(speed); movingup = false; movingdown = false; movingleft = true; movingright =false; } /*reference the moveup() function, everything is defined in a similar fashion*/ void snake::moveright() { QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(down())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(left())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(up())); QObject::disconnect(timer, SIGNAL(timeout()),this,SLOT(right())); QObject::connect(timer, SIGNAL(timeout()),this,SLOT(right())); timer->start(speed); movingup = false; movingdown = false; movingleft = false; movingright = true; } /* @brief enlarge the snake body by one unit */ void snake::enlarge() { check_win(); // check wheter the player wins the game sbody* body = new sbody(); bodies.prepend(body); // prepend the sbody to the beginning of the list scene()->addItem(body); // add body to the scene QBrush brush; brush.setStyle(Qt::SolidPattern); brush.setColor(Qt::yellow); body->setBrush(brush); //fill the body with yellow } /*a function called when the game is over*/ void snake::gameover() { timer->stop(); // stop the timer so the snake stop moving QString filename = ":/image/i3.jpng"; QImage image(filename); QGraphicsPixmapItem* item_graph = new QGraphicsPixmapItem(QPixmap::fromImage(image)); item_graph->setPos(-40, 120); reportwindow->addItem(item_graph); die->play(); // play the sound effect for dying QPushButton* again = new QPushButton("PLAY AGAIN"); QPushButton* quitgame = new QPushButton("QUIT"); again->setGeometry(0,0,120, 40); quitgame->setGeometry(0,50, 120, 40); //set the location of the two buttons QGraphicsProxyWidget* proxy1 = reportwindow->addWidget(again); QGraphicsProxyWidget* proxy2 = reportwindow->addWidget(quitgame); // add two buttons to the scene when game is over QObject::connect(quitgame, SIGNAL(clicked()), this, SLOT(quitgame())); // connect quit button with quitgame slots QObject::connect(again, SIGNAL(clicked()), this, SLOT(restart())); reportwindow->addItem(scores); // add scores to the gameover scene scores->setPos(20,-50); //set the position of the scores view->setScene(reportwindow); // make the gameover scene visible } /* handle the collision of items*/ void snake::handlecollision() { QList <QGraphicsItem*> collided = collidingItems(); // make a list of items that collides with the snake for(int i=0; i<collided.size();i++) { if(typeid(*collided[i]) == typeid(food)) // the food is collided with { eat->play(); // play the sound for eating scene()->removeItem(collided[i]); // remove the food from scene delete collided[i]; // delete the food scores->add(); // update the scores enlarge(); enlarge(); enlarge(); // enlarge the snake body by 3 units creafood(); // create a new food on the scene return;} if(typeid(*collided[i]) == typeid(sbody)) // if the sbody is collided with { qDebug() << "gameover"; gameover(); // call the gameover function } } } /*@Check whether the player wins the game*/ void snake::check_win() { if(scores->get_score()>=500) // if the socre reaches 500, call gameover() { gameover(); QGraphicsTextItem* win = new QGraphicsTextItem(); win -> setPlainText(QString("Congratulations! You Won!")); win -> setDefaultTextColor(Qt::yellow); win-> setFont(QFont("times", 20)); win->setPos(-45 , -100); reportwindow->addItem(win); // display winning scene } } /*@brief @return the scores of the snake*/ score *snake::get_scores() { return scores; } /* a slot that can set the speed of the snake*/ void snake::set_speed(int n) { speed = 100 - n; /*larger n means smaller speed, the speed is the Qtimer time so the snake will move faster*/ } /*@brief start a new game*/ void snake::restart() { get_view()->hide(); // hide the view creaSnake(speed); // create a new snake class } /*quit the application*/ void snake::quitgame() { QApplication::quit(); } /*@return view of the snake*/ QGraphicsView* snake::get_view() { return view; } /*set speed for the snake*/ void snake::set_sp(int sp) { speed = sp; } snake::~snake() // destructor { delete timer; delete scores; delete playground; delete reportwindow; delete view; delete eat; delete die; for(int i = 0; i < bodies.size(); i++) { delete bodies[i]; } // delete all the pointers created in the class } /*@brief slots that make the snake move*/ void snake::up() { handlecollision(); //check collision everytime before the position of the snake is changed if(y()<-275) //check boundary { setPos(x(), y() + 570); // if it is out of boundary, move to the other side of the boundary } setPos(x(), y()-21); // update the position of the snake head for(int i =0;i<bodies.size()-1;i++) // update the posisiton of the snake bodies { bodies[i]->setPos(bodies[i+1]->pos()); // every part of the bodies goes to the position of the sbody in front of it } bodies.last()->setPos(headPos); // the sbody directy following the snake head goes to the positon of the snake head headPos = pos(); } /*reference up() for comments, all move slots are defined in the same fashion*/ void snake::down() { handlecollision(); if(y()>275) { setPos(x(), y() - 570); } setPos(x(), y()+21); for(int i =0;i<bodies.size()-1;i++) { bodies[i]->setPos(bodies[i+1]->pos()); } bodies.last()->setPos(headPos); headPos = pos(); } /*reference up() for comments, all move slots are defined in the same fashion*/ void snake::left() { handlecollision(); if(x()<-275) { setPos(x()+570, y()); } setPos(x()-21, y()); for(int i =0;i<bodies.size()-1;i++) { bodies[i]->setPos(bodies[i+1]->pos()); } bodies.last()->setPos(headPos); headPos = pos(); } /*reference up() for comments, all move slots are defined in the same fashion*/ void snake::right() { handlecollision(); if(x()> 275) { setPos(x()-570, y()); } setPos(x()+21, y()); for(int i =0;i<bodies.size()-1;i++) { bodies[i]->setPos(bodies[i+1]->pos()); } bodies.last()->setPos(headPos); headPos = pos(); } /*function to create a food and add it to the scene*/ void snake::creafood() { food* newfood = new food(); scene()->addItem(newfood); newfood->check(); }
#include <iostream> using namespace std; int main() { cout << "Serendipity Booksellers\nInventory Database\n\n1. Look Up a Book\n2. Add a Book\n3. Edit " << "a Book's Record\n4. Delete a Book\n5. Return to the Main Menu\n\nEnter Your Choice: \n"; }
//git add pushbutton/sypushbutton.cpp //git commit -m "pushbutton" pushbutton/sypushbutton.cpp //git push -u origin master //http://www.cnblogs.com/emouse/archive/2013/07/14/3189319.html //http://www.360doc.com/content/11/1122/10/7899729_166398154.shtml //http://www.cnblogs.com/xj626852095/p/3648119.html //http://blog.163.com/qimo601@126/blog/static/15822093201432494134937/ //https://my.oschina.net/upday7/blog/109597 //http://www.xuebuyuan.com/1832172.html //http://blog.csdn.net/Qyee16/article/details/51234794 #include "sypushbutton.h" #include <QPixmap> #include <QPainter> #include <QMouseEvent> #include <QString> SYPushButton::SYPushButton(QWidget *parent) : QPushButton(parent) , cursorStatus(SY_INIT) { } void SYPushButton::setImages(QString &normalFileName, QString &horverFilenName, QString &pressFileName) { cursorStatus = SY_NORMAL; imageName[SY_NORMAL] = normalFileName; imageName[SY_HOVER] = horverFilenName; imageName[SY_PRESS] = pressFileName; } void SYPushButton::enterEvent(QEvent *) { if (cursorStatus == SY_INIT) { return; } cursorStatus = SY_HOVER; update(); } void SYPushButton::leaveEvent(QEvent *) { if (cursorStatus == SY_INIT) { return; } cursorStatus = SY_NORMAL; update(); } void SYPushButton::mousePressEvent(QMouseEvent *event) { if (cursorStatus == SY_INIT) { return; } if (event->button() == Qt::LeftButton) { cursorStatus = SY_PRESS; update(); } } void SYPushButton::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { if (cursorStatus != SY_INIT) { cursorStatus = SY_HOVER; update(); } // 鼠标释放的时候激发clicked信号 if (rect().contains(event->pos())) { emit clicked(); } } } void SYPushButton::paintEvent(QPaintEvent *event) { if (cursorStatus == SY_INIT) { QPushButton::paintEvent(event); return; } QPainter painter(this); QPixmap pixmap(imageName[cursorStatus]); painter.drawPixmap(rect(), pixmap); }
#include "KeyBoardState.h" KeyBoardState::KeyBoardState(void) { for(int i = 0; i < 256; ++i) { keys[i] = false; } } KeyBoardState::~KeyBoardState(void) { } bool KeyBoardState::IsKeyDown(KeyPad::Keys key) { return (keys[key] == true); } bool KeyBoardState::IsKeyUp(KeyPad::Keys key) { return (keys[key] == false); } void KeyBoardState::EventHandlerDown(WPARAM wParam) { keys[wParam] = true; } void KeyBoardState::EventHandlerUp(WPARAM wParam) { keys[wParam] = false; }
#include "quadtree.h" quadtree::quadtree(const Eigen::MatrixXd &f1, const Eigen::MatrixXd &f2, const IntervalVec<itv> &range) : m_mat_f1(f1), m_mat_f2(f2), m_min_size(1e-3), count(0) { m_mat_f1x = diff_about_x(m_mat_f1); m_mat_f1y = diff_about_y(m_mat_f1); m_mat_f2x = diff_about_x(m_mat_f2); m_mat_f2y = diff_about_y(m_mat_f2); } quadtree::~quadtree() { IntervalVec<itv> *current = nullptr; //清空Tlist while (!Tlist.empty()) { current = Tlist.front(); delete current; current = nullptr; Tlist.pop(); } } void quadtree::search_procedure(IntervalVec<itv> range) { IntervalVec<itv> *current = nullptr; //清空Tlist clear_Tlist(); Plist.clear(); current = new IntervalVec<itv>(range); int index_number = 0; while (1) { index_number++; ITERATIONINFO(index_number, *current); IntervalVec<itv> F_X = F_value(current->x, current->y); if (!F_X.contain_zero()) { delete current; current = nullptr; if (Tlist.empty()) { break; } current = Tlist.front(); Tlist.pop(); } else { IntervalMat<itv> F_prime_value_result = F_prime_value(current->x, current->y); Region m_F_prime = F_prime_value_result.mid_value(); if (m_F_prime.is_reversible()) { //可逆 Region Y = m_F_prime.inverse_mat(); IntervalMat<itv> R = Region(1.0, 0.0, 0.0, 1.0) - Y * F_prime_value_result; vec2d mX = vec2d(mid(current->x), mid(current->y)); IntervalVec<itv> delta = *current - mX; vec2d FmX = F_value(itv(mX.x, mX.x), itv(mX.y, mX.y)).mid_vec(); IntervalVec<itv> K = (mX - Y * FmX) + R * delta; if (K.is_empty_for_intersection(*current)) { //交集为空 delete current; current = nullptr; if (Tlist.empty()) { break; } current = Tlist.front(); //修改 Tlist.pop(); } else if (K.is_contained_in(*current)) { if (R.get_norm() < 1) { std::cout << *current << std::endl; delete current; current = nullptr; clear_Tlist(); break; } else { delete current; current = nullptr; search_procedure(K); clear_Tlist(); break; } } else { if (!Bisection(current, F_prime_value_result)) { clear_Tlist(); break; }; } } else { if (!Bisection(current, F_prime_value_result)) { clear_Tlist(); break; }; } } } // while (!Tlist.empty()) // { // current = Tlist.front(); // Tlist.pop(); // IntervalVec<itv> F_X = F_value(current->x, current->y); // if (!F_X.contain_zero()) // { // delete current; // current = nullptr; // continue; // } // IntervalMat<itv> F_prime_value_result = F_prime_value(current->x, current->y); // Region m_F_prime = F_prime_value_result.mid_value(); // if (m_F_prime.is_reversible()) // { // //可逆 // Region Y = m_F_prime.inverse_mat(); // IntervalMat<itv> R = Region(1.0, 0.0, 0.0, 1.0) - Y * F_prime_value_result; // vec2d mX = vec2d(mid(current->x), mid(current->y)); // IntervalVec<itv> delta = *current - mX; // vec2d FmX = F_value(itv(mX.x, mX.x), itv(mX.y, mX.y)).mid_vec(); // IntervalVec<itv> K = (mX - Y * FmX) + R * delta; // if (K.is_empty_for_intersection(*current)) // { // //交集为空 // delete current; // current = nullptr; // continue; // } // else if (K.is_contained_in(*current)) // { // std::cout << R.get_norm() << std::endl; // if (R.get_norm() < 1) // { // std::cout << *current << std::endl; // delete current; // current = nullptr; // //清空Tlist // while (!Tlist.empty()) // { // current = Tlist.front(); // delete current; // current = nullptr; // Tlist.pop(); // } // break; // } // else // { // delete current; // current = nullptr; // search_procedure(K); // } // } // else // { // Bisection(current, F_prime_value_result); // delete current; // current = nullptr; // } // } // else // { // //不可逆 // Bisection(current, F_prime_value_result); // delete current; // current = nullptr; // } // } } void quadtree::clear_Tlist() { IntervalVec<itv> *current = nullptr; while (!Tlist.empty()) { current = Tlist.front(); Tlist.pop(); delete current; current = nullptr; } } itv quadtree::estimate_range(const Eigen::MatrixXd &src, const itv &xrange, const itv &yrange) { itv result(0, 0); for (int i = 0; i < src.rows(); ++i) { for (int j = 0; j < src.cols(); ++j) { itv temp; temp = pow(xrange, i) * pow(yrange, j) * src(i, j); double temt = src(i, j); result += pow(xrange, i) * pow(yrange, j) * src(i, j); } } return itv(result.lower(), result.upper()); } IntervalVec<itv> quadtree::F_value(const itv &xrange, const itv &yrange) { return IntervalVec<itv>(estimate_range(m_mat_f1, xrange, yrange), estimate_range(m_mat_f2, xrange, yrange)); } IntervalMat<itv> quadtree::F_prime_value(const itv &xrange, const itv &yrange) { return IntervalMat<itv>(estimate_range(m_mat_f1x, xrange, yrange), estimate_range(m_mat_f1y, xrange, yrange), estimate_range(m_mat_f2x, xrange, yrange), estimate_range(m_mat_f2y, xrange, yrange)); } Eigen::MatrixXd quadtree::diff_about_x(const Eigen::MatrixXd &src) { if (src.rows() == 1) { Eigen::MatrixXd result(1, 1); result << 0; return result; } Eigen::MatrixXd result(src.rows() - 1, src.cols()); for (int i = 1; i < src.rows(); i++) { for (int j = 0; j < src.cols(); j++) { result(i - 1, j) = src(i, j) * i; } } return result; } Eigen::MatrixXd quadtree::diff_about_y(const Eigen::MatrixXd &src) { if (src.cols() == 1) { Eigen::MatrixXd result(1, 1); result << 0; return result; } Eigen::MatrixXd result(src.rows(), src.cols() - 1); for (int i = 0; i < src.rows(); ++i) { for (int j = 1; j < src.cols(); ++j) { result(i, j - 1) = src(i, j) * j; } } return result; } bool quadtree::Bisection(IntervalVec<itv> *&p, const IntervalMat<itv> &Fprime) { if (width(p->x) < m_min_size || width(p->y) < m_min_size) { Plist.push_back(*p); delete p; p = nullptr; return false; } std::pair<int, int> index = Fprime.find_mini_ij(); Eigen::MatrixXd Fprime_ij_mat; if (index.first == 1 && index.second == 1) { Fprime_ij_mat = m_mat_f1x; } if (index.first == 1 && index.second == 2) { Fprime_ij_mat = m_mat_f1y; } if (index.first == 2 && index.second == 1) { Fprime_ij_mat = m_mat_f2x; } if (index.first == 2 && index.second == 2) { Fprime_ij_mat = m_mat_f2y; } IntervalVec<itv> *first_try1 = nullptr; IntervalVec<itv> *first_try2 = nullptr; IntervalVec<itv> *second_try1 = nullptr; IntervalVec<itv> *second_try2 = nullptr; if (count % 2 == 0) { //先对x进行分割 first_try1 = new IntervalVec<itv>(itv(p->x.lower(), mid(p->x)), p->y); first_try2 = new IntervalVec<itv>(itv(mid(p->x), p->x.upper()), p->y); second_try1 = new IntervalVec<itv>(p->x, itv(p->y.lower(), mid(p->y))); second_try2 = new IntervalVec<itv>(p->x, itv(mid(p->y), p->y.upper())); } else { //先对y进行分割 first_try1 = new IntervalVec<itv>(p->x, itv(p->y.lower(), mid(p->y))); first_try2 = new IntervalVec<itv>(p->x, itv(mid(p->y), p->y.upper())); second_try1 = new IntervalVec<itv>(itv(p->x.lower(), mid(p->x)), p->y); second_try2 = new IntervalVec<itv>(itv(mid(p->x), p->x.upper()), p->y); } itv first_try1_range = estimate_range(Fprime_ij_mat, first_try1->x, first_try1->y); itv first_try2_range = estimate_range(Fprime_ij_mat, first_try2->x, first_try2->y); itv second_try1_range = estimate_range(Fprime_ij_mat, second_try1->x, second_try1->y); itv second_try2_range = estimate_range(Fprime_ij_mat, second_try2->x, second_try2->y); double try1_width = width(itv::hull(first_try1_range, first_try2_range)); double try2_width = width(itv::hull(second_try1_range, second_try2_range)); if (try1_width <= try2_width) { IntervalVec<itv> F_range1 = F_value(first_try1->x, first_try1->y); IntervalVec<itv> F_range2 = F_value(first_try2->x, first_try2->y); double temp1 = fabs(mid(F_range1.x)) + fabs(mid(F_range1.y)); double temp2 = fabs(mid(F_range2.x)) + fabs(mid(F_range2.y)); if (temp1 <= temp2) { delete p; p = first_try1; Tlist.push(first_try2); } else { delete p; p = first_try2; Tlist.push(first_try1); } delete second_try1; delete second_try2; second_try1 = nullptr; second_try2 = nullptr; } else { IntervalVec<itv> F_range1 = F_value(second_try1->x, second_try1->y); IntervalVec<itv> F_range2 = F_value(second_try2->x, second_try2->y); double temp1 = fabs(mid(F_range1.x)) + fabs(mid(F_range1.y)); double temp2 = fabs(mid(F_range2.x)) + fabs(mid(F_range2.y)); if (temp1 <= temp2) { delete p; p = second_try1; Tlist.push(second_try2); } else { delete p; p = second_try2; Tlist.push(second_try1); } delete first_try1; delete first_try2; first_try1 = nullptr; first_try2 = nullptr; } count ++; return true; }
/* ** EPITECH PROJECT, 2021 ** Untitled (Workspace) ** File description: ** RamInfos */ #include <string> #include <iostream> #include <cstdlib> #include <fstream> #include <atomic> #include <chrono> #include <thread> std::atomic<long unsigned int>mem_used; std::atomic<long unsigned int>mem_free; std::atomic<long unsigned int>mem_total; void updateRam(std::atomic<bool> &is_running) { const auto wait_duration = std::chrono::milliseconds(1000); while (is_running) { std::ifstream ram_file; std::string line; ram_file.open("/proc/meminfo"); std::getline(ram_file, line); line.erase(0, 11); mem_total.store(std::atol(line.c_str())); std::getline(ram_file, line); line.erase(0, 10); mem_free.store(std::atol(line.c_str())); ram_file.close(); mem_used.store(mem_total.load() - mem_free.load()); std::this_thread::sleep_for(wait_duration); } }
#ifndef MSG #define MSG #include <string> class Message{ public: Message(); std::string subject; std::string from; std::string to; std::string body; }; #endif //MSG
#pragma once #include "Events.h" #include "BaseObject.h" class Observer { public: virtual ~Observer() {}; virtual void onNotify(const BaseObject& entity, Event event) = 0; };
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <set> #include <stack> #include <cstdio> #include <cstring> #include <climits> #include <cstdlib> using namespace std; struct Cake { float amount, price; bool operator<(const Cake& rhs) const { return price / amount > rhs.price / rhs.amount; } }; int main() { int n, demand; scanf("%d %d", &n, &demand); vector<Cake> v; v.resize(n); for (int i = 0; i < n; i++) scanf("%f", &v[i].amount); for (int i = 0; i < n; i++) scanf("%f", &v[i].price); sort(v.begin(), v.end()); float res = 0.0; for (auto item : v) { if (item.amount <= demand) { res += item.price; demand -= item.amount; } else { res += item.price / item.amount * demand; break; } } printf("%.2f", res); return 0; }
#define POWITACQ_IMPLEMENTATION #include "powitacq_rgb.h" int main(int argc, char **argv) { using namespace powitacq_rgb; // load a BRDF BRDF brdf("cc_ibiza_sunset_rgb.bsdf"); // evaluate the BRDF { Vector3f wi = normalize(Vector3f(0, 0, 1)); Vector3f wo = normalize(Vector3f(1, 1, 1)); Vector3f fr = brdf.eval(wi, wo); /* print values to console */ printf("%f %f %f\n", fr[0], fr[1], fr[2]); } // sample the BRDF { Vector2f u = Vector2f(0.99334f, 0.231f); Vector3f wi = normalize(Vector3f(1, 1, 1)); Vector3f wo; float pdf; Vector3f fr = brdf.sample(u, wi, &wo, &pdf); /* print values to console */ printf("%f %f %f\n", fr[0], fr[1], fr[2]); } }
// dp de quantidade de numeros <= r com ate qt digitos diferentes de 0 ll dp(int idx, string& r, bool menor, int qt, vector<vector<vi>>& tab) { if(qt > 3) return 0; if(idx >= r.size()) { return 1; } if(tab[idx][menor][qt] != -1) return tab[idx][menor][qt]; ll res = 0; for(int i = 0; i <= 9; i++) { if(menor or i <= r[idx]-'0') { res += dp(idx+1, r, menor or i < (r[idx]-'0') , qt+(i>0), tab); } } return tab[idx][menor][qt] = res; }
#include <Buffers/UniformBuffer.h> #include <cstring> //#define BUFFER_USE_MAPPING CUniformBuffer::CUniformBuffer(GLsizeiptr size, GLuint binding) : _ubo(0) , _binding(binding) , _size(size) { glGenBuffers(1, &_ubo); bind(); glBufferData(GL_UNIFORM_BUFFER, _size, nullptr, GL_DYNAMIC_DRAW); reset(); glBindBufferBase(GL_UNIFORM_BUFFER, _binding, _ubo); unbind(); } CUniformBuffer::~CUniformBuffer() { glDeleteBuffers(1, &_ubo); } void CUniformBuffer::bind() const { glBindBufferBase(GL_UNIFORM_BUFFER, _binding, _ubo); } void CUniformBuffer::unbind() const { glBindBuffer(GL_UNIFORM_BUFFER, 0); } void CUniformBuffer::setData(const void *data) const { bind(); #ifndef BUFFER_USE_MAPPING glBufferSubData(GL_UNIFORM_BUFFER, 0, _size, data); #else void *buffer = glMapBuffer(GL_UNIFORM_BUFFER, GL_WRITE_ONLY); memcpy(buffer, data, _size); glUnmapBuffer(GL_UNIFORM_BUFFER); #endif unbind(); } void CUniformBuffer::setSubData(GLintptr offset, GLsizeiptr size, const void *data) const { bind(); #ifndef BUFFER_USE_MAPPING glBufferSubData(GL_UNIFORM_BUFFER, offset, size, data); #else uint8_t *buffer = static_cast<uint8_t *>(glMapBuffer(GL_UNIFORM_BUFFER, GL_WRITE_ONLY)); memcpy(buffer + offset, data, size); glUnmapBuffer(GL_UNIFORM_BUFFER); #endif unbind(); } void CUniformBuffer::reset() const { void *buffer = glMapBuffer(GL_UNIFORM_BUFFER, GL_WRITE_ONLY); memset(buffer, 0, _size); glUnmapBuffer(GL_UNIFORM_BUFFER); }
#include<bits/stdc++.h> #include<ext/rope> using namespace std; using namespace __gnu_cxx; struct ope{ int t,x,y,k; }; ope o[30000]; rope<int> *fa[30000]; int a[30000],ans[30000],n,m,tot=0; void readit(){ scanf("%d%d",&n,&m); for (int i=1;i<=m;i++){ int t; scanf("%d",&t); o[i].t=t; if (t==2) scanf("%d",&o[i].k); else scanf("%d%d",&o[i].x,&o[i].y); } } void writeit(){ for (int i=1;i<=tot;i++) printf("%d\n",ans[i]); } inline int root(int num,int x){ if ((*fa[num])[x]==x) return x; int rt=root(num,(*fa[num])[x]); (*fa[num]).replace(x,rt); return rt; } inline void uni(int num,int x,int y){ int u=root(num,x),v=root(num,y); (*fa[num]).replace(v,u); } void work(){ for (int i=1;i<=n;i++) a[i]=i; fa[0]=new rope<int>(a,a+n+1); for (int i=1;i<=m;i++){ int t=o[i].t; fa[i]=new rope<int>(*fa[i-1]); if (t==1){ int x=o[i].x,y=o[i].y; uni(i,x,y); } else if (t==2){ int k=o[i].k; fa[i]=fa[k]; } else{ int x=o[i].x,y=o[i].y; ans[++tot]=root(i,x)==root(i,y); } } } int main(){ readit(); work(); writeit(); return 0; }
/**************************************************************************** ** Meta object code from reading C++ file 'CSystemTrayIcon.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../CSystemTrayIcon.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'CSystemTrayIcon.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_CSystemTrayIcon_t { QByteArrayData data[14]; char stringdata[176]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_CSystemTrayIcon_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_CSystemTrayIcon_t qt_meta_stringdata_CSystemTrayIcon = { { QT_MOC_LITERAL(0, 0, 15), QT_MOC_LITERAL(1, 16, 20), QT_MOC_LITERAL(2, 37, 0), QT_MOC_LITERAL(3, 38, 5), QT_MOC_LITERAL(4, 44, 15), QT_MOC_LITERAL(5, 60, 16), QT_MOC_LITERAL(6, 77, 8), QT_MOC_LITERAL(7, 86, 14), QT_MOC_LITERAL(8, 101, 9), QT_MOC_LITERAL(9, 111, 6), QT_MOC_LITERAL(10, 118, 11), QT_MOC_LITERAL(11, 130, 22), QT_MOC_LITERAL(12, 153, 6), QT_MOC_LITERAL(13, 160, 15) }, "CSystemTrayIcon\0trayIconStateChanged\0" "\0state\0quitApplication\0hideOrShowWidget\0" "setState\0SMonitor::Type\0setHidden\0" "hidden\0selfUpgrade\0downloadFileErrorOccur\0" "errMsg\0downloadSuccess" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_CSystemTrayIcon[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 8, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 54, 2, 0x06 /* Public */, 4, 0, 57, 2, 0x06 /* Public */, 5, 0, 58, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 6, 1, 59, 2, 0x0a /* Public */, 8, 1, 62, 2, 0x0a /* Public */, 10, 0, 65, 2, 0x0a /* Public */, 11, 1, 66, 2, 0x09 /* Protected */, 13, 0, 69, 2, 0x09 /* Protected */, // signals: parameters QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Void, // slots: parameters QMetaType::Void, 0x80000000 | 7, 3, QMetaType::Void, QMetaType::Bool, 9, QMetaType::Void, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, 0 // eod }; void CSystemTrayIcon::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { CSystemTrayIcon *_t = static_cast<CSystemTrayIcon *>(_o); switch (_id) { case 0: _t->trayIconStateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->quitApplication(); break; case 2: _t->hideOrShowWidget(); break; case 3: _t->setState((*reinterpret_cast< SMonitor::Type(*)>(_a[1]))); break; case 4: _t->setHidden((*reinterpret_cast< bool(*)>(_a[1]))); break; case 5: _t->selfUpgrade(); break; case 6: _t->downloadFileErrorOccur((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 7: _t->downloadSuccess(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (CSystemTrayIcon::*_t)(int ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CSystemTrayIcon::trayIconStateChanged)) { *result = 0; } } { typedef void (CSystemTrayIcon::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CSystemTrayIcon::quitApplication)) { *result = 1; } } { typedef void (CSystemTrayIcon::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CSystemTrayIcon::hideOrShowWidget)) { *result = 2; } } } } const QMetaObject CSystemTrayIcon::staticMetaObject = { { &QSystemTrayIcon::staticMetaObject, qt_meta_stringdata_CSystemTrayIcon.data, qt_meta_data_CSystemTrayIcon, qt_static_metacall, 0, 0} }; const QMetaObject *CSystemTrayIcon::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *CSystemTrayIcon::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CSystemTrayIcon.stringdata)) return static_cast<void*>(const_cast< CSystemTrayIcon*>(this)); return QSystemTrayIcon::qt_metacast(_clname); } int CSystemTrayIcon::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QSystemTrayIcon::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 8) qt_static_metacall(this, _c, _id, _a); _id -= 8; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 8) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 8; } return _id; } // SIGNAL 0 void CSystemTrayIcon::trayIconStateChanged(int _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void CSystemTrayIcon::quitApplication() { QMetaObject::activate(this, &staticMetaObject, 1, 0); } // SIGNAL 2 void CSystemTrayIcon::hideOrShowWidget() { QMetaObject::activate(this, &staticMetaObject, 2, 0); } QT_END_MOC_NAMESPACE
#include "historydatawindow.h" #include "ui_historydatawindow.h" HistoryDataWindow::HistoryDataWindow(QWidget *parent, DataProcessor *processor) : QWidget(parent),dataPro(processor), ui(new Ui::HistoryDataWindow) { ui->setupUi(this); range=3600; mode=VMODE; // mode=NONMODE; const char plotnames[4]={'a','b','c','s'}; Qt::GlobalColor plotcolors[4]={Qt::red,Qt::blue,Qt::black,Qt::green}; for (int i=0;i<4;i++) { plots[i].addGraph(); ui->plotLayout->addWidget((QWidget*)&plots[i]); plots[i].graph(0)->setName(QString(plotnames[i])); plots[i].legend->setVisible(true); plots[i].graph(0)->setPen(QPen(plotcolors[i])); } replot(mode,range); ui->endDate->setDate(QDate::currentDate()); ui->beginDate->setDate(QDate::currentDate()); ui->endHour->setValue(QTime::currentTime().hour()); ui->beginHour->setValue(QTime::currentTime().hour()-1); } HistoryDataWindow::~HistoryDataWindow() { delete ui; } void HistoryDataWindow::on_vRadioBtn_toggled(bool checked) { if (checked) { // if (mode!=VMODE) // { replot(VMODE,range); mode=VMODE; for (int i=0;i<3;++i) { plots[i].yAxis->setLabel("电压/V"); } // } } } void HistoryDataWindow::on_iRadioBtn_toggled(bool checked) { if (checked) { // if (mode!=IMODE) // { replot(IMODE,range); mode=IMODE; for (int i=0;i<3;++i) { plots[i].yAxis->setLabel("电流/A"); } // } } } void HistoryDataWindow::on_epRadioBtn_toggled(bool checked) { if (checked) { if (mode!=EPMODE) { replot(EPMODE,range); mode=EPMODE; for (int i=0;i<4;++i) { plots[i].yAxis->setLabel("有功功率/KW"); } } } } void HistoryDataWindow::on_fpRadioBtn_toggled(bool checked) { if (checked) { if (mode!=RPMODE) { replot(RPMODE,range); mode=RPMODE; for (int i=0;i<4;++i) { plots[i].yAxis->setLabel("无功功率/Var"); } } } } void HistoryDataWindow::on_apRadioBtn_toggled(bool checked) { if (checked) { if (mode!=APMODE) { replot(APMODE,range); mode=APMODE; for (int i=0;i<4;++i) { plots[i].yAxis->setLabel("视在功率/KVA"); } } } } void HistoryDataWindow::on_pfRadioBtn_toggled(bool checked) { if (checked) { if (mode!=PFMODE) { replot(PFMODE,range); mode=PFMODE; for (int i=0;i<4;++i) { plots[i].yAxis->setLabel("功率因素/KVA"); } } } } void HistoryDataWindow::replot(int mode,int range) { //qDebug()<<"call plot************************"; //qDebug()<<"current mode is "<<mode; for (int i=0;i<4;i++) { plots[i].graph(0)->clearData(); plots[i].xAxis->setRange(0,range); } if (mode==VMODE || mode==IMODE) { ui->plotLayout->removeWidget(&plots[3]); plots[3].hide(); } else { if (ui->plotLayout->count()==3) { ui->plotLayout->addWidget(&plots[3]); plots[3].show(); } plots[3].graph(0)->clearData(); plots[3].xAxis->setRange(0,range); } for (int i=0;i<range;i++) { if (i>=datapoints.length()) break; if (mode==VMODE) { plots[0].graph(0)->addData(i,datapoints[i].va); plots[1].graph(0)->addData(i,datapoints[i].vb); plots[2].graph(0)->addData(i,datapoints[i].vc); for (int i=0;i<3;++i) { plots[i].yAxis->setLabel("电压/V"); } } else if (mode==IMODE) { plots[0].graph(0)->addData(i,datapoints[i].ia); plots[1].graph(0)->addData(i,datapoints[i].ib); plots[2].graph(0)->addData(i,datapoints[i].ic); for (int i=0;i<3;++i) { plots[i].yAxis->setLabel("电流/A"); } } else if (mode==EPMODE) { plots[0].graph(0)->addData(i,datapoints[i].epa); plots[1].graph(0)->addData(i,datapoints[i].epb); plots[2].graph(0)->addData(i,datapoints[i].epc); plots[3].graph(0)->addData(i,datapoints[i].eps); for (int i=0;i<4;++i) { plots[i].yAxis->setLabel("有功功率/KW"); } } else if (mode==RPMODE) { plots[0].graph(0)->addData(i,datapoints[i].rpa); plots[1].graph(0)->addData(i,datapoints[i].rpb); plots[2].graph(0)->addData(i,datapoints[i].rpc); plots[3].graph(0)->addData(i,datapoints[i].rps); for (int i=0;i<4;++i) { plots[i].yAxis->setLabel("无功功率/Var"); } } else if (mode==APMODE) { plots[0].graph(0)->addData(i,datapoints[i].apa); plots[1].graph(0)->addData(i,datapoints[i].apb); plots[2].graph(0)->addData(i,datapoints[i].apc); plots[3].graph(0)->addData(i,datapoints[i].aps); for (int i=0;i<4;++i) { plots[i].yAxis->setLabel("视在功率/KVA"); } } else if (mode==PFMODE) { plots[0].graph(0)->addData(i,datapoints[i].pfa); plots[1].graph(0)->addData(i,datapoints[i].pfb); plots[2].graph(0)->addData(i,datapoints[i].pfc); plots[3].graph(0)->addData(i,datapoints[i].pfs); for (int i=0;i<4;++i) { plots[i].yAxis->setLabel("功率因素/KVA"); } } } for (int i=0;i<4;i++) { plots[i].replot(); plots[i].yAxis->rescale(); } } void HistoryDataWindow::on_setRangeBtn_clicked() { QDateTime beginDateTime,endDateTime; beginDateTime.setDate(ui->beginDate->date()); beginDateTime.setTime(QTime(ui->beginHour->value(),0,0,0)); endDateTime.setDate(ui->endDate->date()); endDateTime.setTime(QTime(ui->endHour->value(),0,0,0)); range=360; dataPro->dataSlicer(beginDateTime,endDateTime,datapoints,range); replot(mode,range); } void HistoryDataWindow::on_returnBtn_clicked() { this->hide(); } void HistoryDataWindow::on_sincBtn_2_clicked() { ui->beginHour->setValue(ui->beginHour->value()+1); if (ui->beginHour->value()>23) ui->beginHour->setValue(23); } void HistoryDataWindow::on_sdecBtn_2_clicked() { ui->beginHour->setValue(ui->beginHour->value()-1); if (ui->beginHour->value()<0) ui->beginHour->setValue(0); } void HistoryDataWindow::on_eincBtn_clicked() { ui->endHour->setValue(ui->endHour->value()+1); if (ui->endHour->value()>23) ui->endHour->setValue(23); } void HistoryDataWindow::on_edecBtn_clicked() { ui->endHour->setValue(ui->endHour->value()-1); if (ui->endHour->value()<0) ui->endHour->setValue(0); }
/*========================================================================= University of Pittsburgh Bioengineering 1351/2351 Final project example code Copyright (c) 2011 by Damion Shelton All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <time.h> #include "FinalProjectApp.h" #include <string.h> #include <itkArray.h> #include <random> FinalProjectApp ::FinalProjectApp() { std::cout << "In FinalProjectApp constructor" << std::endl; // Initialize OpenCV things to null m_CameraImageOpenCV = 0; m_OpenCVCapture = 0; // We know the image size in advance. A better implementation would be // to set this only after connecting to the camera and checking the // actual image size. m_ImageWidth = 640; m_ImageHeight = 480; m_NumPixels = m_ImageWidth * m_ImageHeight; // Buffers to hold raw image data m_CameraFrameRGBBuffer = new unsigned char[m_NumPixels*3]; m_TempRGBABuffer = new unsigned char[m_NumPixels*4]; // Not yet connected to a camera m_ConnectedToCamera = false; // Filter parameter m_Threshold = 40; m_EyePairBigEnabled = true; updateAttentionBar(m_Threshold); m_FilterEnabled = false; //Start the counter m_attentionCounter = 0; // Load whichever Haar cascades we'll need so we don't have to read from file for every frame m_HaarLeftEye = LoadHaarCascade("haarcascade_mcs_lefteye.xml"); m_HaarRightEye = LoadHaarCascade("haarcascade_mcs_righteye.xml"); m_HaarEyePairSmall = LoadHaarCascade("haarcascade_mcs_eyepair_small.xml"); m_HaarEyePairBig = LoadHaarCascade("haarcascade_mcs_eyepair_big.xml"); m_HaarFrontalFace = LoadHaarCascade("haarcascade_frontalface_default.xml"); m_HaarMouth = LoadHaarCascade("haarcascade_mcs_mouth.xml"); m_HaarNose = LoadHaarCascade("haarcascade_mcs_nose.xml"); // Initialize a log file with hard coded headers m_logFile = fopen("Log File.csv","w"); fprintf(m_logFile, "%s,%s,%s,%s,%s\n", "Time", "Trial", "Feature", "Detect", "Epoch"); // Initialize the frame index for the arrays m_frame = 0; /** Initialize log file dynamic arrays */ int TotalFrames = 10000; m_TimeStamp = new double [TotalFrames]; m_Trial = new int [TotalFrames]; m_Feature = new int [TotalFrames]; m_Detect = new int [TotalFrames]; m_Epoch = new int [TotalFrames]; m_CurrentEpoch = 0; m_CurrentFeature = 1; //This is overrided with -1 if tracking is not enabled m_QTime.start(); m_CurrentTrial = 0; m_SuccessfulTrials = 0; m_FailedTrials = 0; //initialize random number seed to randomly advance the Epoch srand( time(NULL) ); } FinalProjectApp ::~FinalProjectApp() { std::cout << "In FinalProjectApp destructor" << std::endl; if(m_ConnectedToCamera) { std::cout << "In FinalProjectApp destructor: disconnecting camera" << std::endl; this->DisconnectCamera(); } // Automatically save a log file upon exiting the program SaveLog(); delete[] m_CameraFrameRGBBuffer; delete[] m_TempRGBABuffer; delete[] m_TimeStamp; delete[] m_Trial; delete[] m_Feature; delete[] m_Detect; delete[] m_Epoch; // Append feature definitions and Epoch numbers to the log file fprintf(m_logFile, "\n%s,\t%s,\t%s,\t%s,\t%s,\t%s", "bigEyePair = 1", "smallEyePair = 2", "frontalFace = 3", "leftRightEye = 4", "mouth = 5", "nose = 6"); fprintf(m_logFile, "\n%s,\t%s,\t%s","Epoch 0 = Intertrial", "Epoch 1 = Button Press", "Epoch 2 = Reach"); fclose(m_logFile); } void FinalProjectApp ::SetupApp() { if( this->SetupCamera() ) this->SetupITKPipeline(); } bool FinalProjectApp ::SetupCamera() { // Try to get any open camera m_OpenCVCapture = cvCaptureFromCAM(CV_CAP_ANY); // Proceed if we found a camera if(m_OpenCVCapture != 0) { // Set the width and height of the camera image cvSetCaptureProperty(m_OpenCVCapture, CV_CAP_PROP_FRAME_HEIGHT, m_ImageHeight); cvSetCaptureProperty(m_OpenCVCapture, CV_CAP_PROP_FRAME_WIDTH, m_ImageWidth); // Succesfully opened the camera m_ConnectedToCamera = true; return true; } else // Oops, no camera return false; } void FinalProjectApp ::DisconnectCamera() { // Free the video capture object cvReleaseCapture(&m_OpenCVCapture); } void FinalProjectApp ::RealtimeUpdate() { // If we're talking to the camera, we can do the cool stuff if(m_ConnectedToCamera) { // Snap an image from the webcam m_CameraImageOpenCV = cvQueryFrame(m_OpenCVCapture); // Did the capture fail? if(m_CameraImageOpenCV == NULL) return; /* RGB extraction is not necessary for our purposes. Keeping code just in case. // Extract RGB data from captured image unsigned char * openCVBuffer = (unsigned char*)(m_CameraImageOpenCV->imageData); // Store the RGB data in our local buffer for(int b = 0; b < m_NumPixels * 3; b++) { m_CameraFrameRGBBuffer[b] = openCVBuffer[b]; } // Update the ITK image this->CopyImageToITK(); */ if(m_FilterEnabled) { //Determine which radiobutton is selected and track appropriately if(m_EyePairBigEnabled) { CvRect m_EyePairBig = TrackFeature(m_CameraImageOpenCV, m_HaarEyePairBig); } else if(m_EyePairSmallEnabled) { CvRect m_EyePairSmall = TrackFeature(m_CameraImageOpenCV, m_HaarEyePairSmall); } else if(m_FrontalFaceEnabled) { CvRect m_FrontalFace = TrackFeature(m_CameraImageOpenCV, m_HaarFrontalFace); } else if(m_LeftRightEyeEnabled) { CvRect m_LeftEye = TrackFeature(m_CameraImageOpenCV, m_HaarLeftEye); CvRect m_RightEye = TrackFeature(m_CameraImageOpenCV, m_HaarRightEye); } else if(m_MouthEnabled) { CvRect m_Mouth = TrackFeature(m_CameraImageOpenCV, m_HaarMouth); } else if(m_NoseEnabled) { CvRect m_Nose = TrackFeature(m_CameraImageOpenCV, m_HaarNose); } QImage processedImage = *IplImage2QImage(m_CameraImageOpenCV); emit SendImage( processedImage ); emit updateAttentionBar( m_attentionCounter ); m_Feature[m_frame] = m_CurrentFeature; } else { // Signify with -1 that no tracking is being conducted m_Detect[m_frame] = -1; m_Feature[m_frame] = -1; // Log for the attention bar if(m_attentionCounter >0) { m_attentionCounter--; } QImage processedImage = *IplImage2QImage(m_CameraImageOpenCV); // Send a copy of the image out via signals/slots emit SendImage( processedImage ); emit updateAttentionBar( m_attentionCounter ); } // Within capture image but outside filter if statement m_Trial[m_frame] = m_CurrentTrial; m_Epoch[m_frame] = m_CurrentEpoch; m_TimeStamp[m_frame] = ((double)m_QTime.elapsed())/1000; // Create a frame index, make sure we don't overwrite the if(m_frame > 9998) SaveLog(); //m_frame will be reset to zero inside SaveLog() // Proceed to the next frame index else m_frame++; } /** Randomly advance to the next Epoch. This will be replaced by signals from the external controller program, but for now we want to make sure it's working **/ if(rand() % 10 == 1)AdvanceTrialEpoch( (m_CurrentEpoch+1)%3 ); // 10% chance to advance, set nextEpoch to next value, wrap from 2->0 } void FinalProjectApp ::SetupITKPipeline() { // Image size and spacing parameters unsigned long sourceImageSize[] = { m_ImageWidth, m_ImageHeight}; double sourceImageSpacing[] = { 1.0,1.0 }; double sourceImageOrigin[] = { 0,0 }; // Creates the sourceImage (but doesn't set the size or allocate memory) m_Image = ImageType::New(); m_Image->SetOrigin(sourceImageOrigin); m_Image->SetSpacing(sourceImageSpacing); // Create a size object native to the sourceImage type ImageType::SizeType sourceImageSizeObject; // Set the size object to the array defined earlier sourceImageSizeObject.SetSize( sourceImageSize ); // Create a region object native to the sourceImage type ImageType::RegionType largestPossibleRegion; // Resize the region largestPossibleRegion.SetSize( sourceImageSizeObject ); // Set the largest legal region size (i.e. the size of the whole sourceImage) to what we just defined m_Image->SetRegions( largestPossibleRegion ); // Now allocate memory for the sourceImage m_Image->Allocate(); //---------Next, set up the filter // This is really to setup the successful trial threshold m_ThresholdFilter = ThresholdType::New(); m_ThresholdFilter->SetInput( m_Image ); m_ThresholdFilter->SetOutsideValue( 255 ); m_ThresholdFilter->SetInsideValue( 0 ); m_ThresholdFilter->SetLowerThreshold( m_Threshold ); m_ThresholdFilter->SetUpperThreshold( 255 ); } void FinalProjectApp ::CopyImageToITK() { // Create the iterator itk::ImageRegionIterator<ImageType> it = itk::ImageRegionIterator<ImageType>(m_Image, m_Image->GetLargestPossibleRegion() ); // Move iterator to the start of the ITK image it.GoToBegin(); unsigned int linearByteIndex = 0; double r, g, b; for(int p = 0; p < m_NumPixels; p++) { r = (double)(m_CameraFrameRGBBuffer[linearByteIndex]); linearByteIndex++; g = (double)(m_CameraFrameRGBBuffer[linearByteIndex]); linearByteIndex++; b = (double)(m_CameraFrameRGBBuffer[linearByteIndex]); linearByteIndex++; /*Convert from RGB to grayscale If you're wondering why the scale factors are the way they are, the answer is that it's just one possible weighting. "Correct" perceptual values depend on the interaction of camera and human eye response and will vary from individual to individual and camera to camera. As an additional note, the OpenCV image is actually storing color data, and the FLTK display image (see app.h/app.cxx) is capable of displaying color data. I'm discarding it when copying to the ITK image because grayscale data is easier to work with. If you want to do a project involving color data, keep in mind that it's already here. You just have to use it - nothing will change in the capture code. */ unsigned char grayscale = (unsigned char)(0.3*r + 0.59*g + 0.11*b); it.Set(grayscale); // Move to next ITK pixel ++it; } } QImage FinalProjectApp ::RGBBufferToQImage(unsigned char* buffer) { unsigned int rgbCounter = 0; unsigned int rgbaCounter = 0; for(int b = 0; b < m_NumPixels; b++) { // Red m_TempRGBABuffer[rgbaCounter] = buffer[rgbCounter]; rgbCounter++; rgbaCounter++; // Green m_TempRGBABuffer[rgbaCounter] = buffer[rgbCounter]; rgbCounter++; rgbaCounter++; // Blue m_TempRGBABuffer[rgbaCounter] = buffer[rgbCounter]; rgbCounter++; rgbaCounter++; // Alpha m_TempRGBABuffer[rgbaCounter] = 255; rgbaCounter++; } // Convert to Qt format QImage result(m_TempRGBABuffer, m_ImageWidth, m_ImageHeight, QImage::Format_RGB32); return result; } QImage FinalProjectApp ::MonoBufferToQImage(unsigned char* buffer) { unsigned int rgbaCounter = 0; for(int b = 0; b < m_NumPixels; b++) { // Red m_TempRGBABuffer[rgbaCounter] = buffer[b]; rgbaCounter++; // Green m_TempRGBABuffer[rgbaCounter] = buffer[b]; rgbaCounter++; // Blue m_TempRGBABuffer[rgbaCounter] = buffer[b]; rgbaCounter++; // Alpha m_TempRGBABuffer[rgbaCounter] = 128; rgbaCounter++; } // Convert to Qt format QImage result(m_TempRGBABuffer, m_ImageWidth, m_ImageHeight, QImage::Format_RGB32); return result; } // The radio button functions to choose the tracked feature void FinalProjectApp ::SetApplyFilter(bool useFilter) { m_FilterEnabled = useFilter; } void FinalProjectApp ::SetRadioButtonEyePairBig(bool bigEyePair){ m_EyePairBigEnabled = bigEyePair; m_CurrentFeature = 1; } void FinalProjectApp ::SetRadioButtonEyePairSmall(bool smallEyePair){ m_EyePairSmallEnabled = smallEyePair; m_CurrentFeature = 2; } void FinalProjectApp ::SetRadioButtonFrontalFace(bool frontalFace){ m_FrontalFaceEnabled = frontalFace; m_CurrentFeature = 3; } void FinalProjectApp ::SetRadioButtonLeftRightEye(bool leftRightEye){ m_LeftRightEyeEnabled = leftRightEye; m_CurrentFeature = 4; } void FinalProjectApp ::SetRadioButtonMouth(bool mouth){ m_MouthEnabled = mouth; m_CurrentFeature = 5; } void FinalProjectApp ::SetRadioButtonNose(bool nose){ m_NoseEnabled = nose; m_CurrentFeature = 6; } // Load the settings file for which ever feature was selected to be tracked CvHaarClassifierCascade* FinalProjectApp ::LoadHaarCascade(char* m_CascadeFilename) { CvHaarClassifierCascade* m_Cascade = (CvHaarClassifierCascade*)cvLoad(m_CascadeFilename, 0, 0, 0); if( !m_Cascade ) { printf("Couldnt load Haar Cascade '%s'\n", m_CascadeFilename); exit(1); } return m_Cascade; } // The function to actually track the feature CvRect FinalProjectApp ::TrackFeature(IplImage* inputImg, CvHaarClassifierCascade* m_Cascade) { // Perform face detection on the input image, using the given Haar classifier CvRect eyeRect = detectEyesInImage(inputImg, m_Cascade); // Time stamp when the frame was taken m_TimeStamp[m_frame] = m_frame; // Make sure a valid face was detected. if (eyeRect.width > 0) { if(m_attentionCounter < m_Threshold) { m_attentionCounter++; } m_Detect[m_frame] = 1; } // No valid face was detected else { if(m_attentionCounter >0) { m_attentionCounter--; } m_Detect[m_frame] = 0; } // Trace a red rectangle over the detected area cvRectangle(inputImg,cvPoint(eyeRect.x,eyeRect.y), cvPoint(eyeRect.x+eyeRect.width,eyeRect.y+eyeRect.height), CV_RGB(255,0,0), 1, 8, 0); return eyeRect; } void FinalProjectApp ::SetThreshold(int threshold) { m_Threshold = threshold; m_ThresholdFilter->SetLowerThreshold( m_Threshold ); m_attentionCounter = 0; } // Create a log file from the data arrays void FinalProjectApp ::SaveLog() { for(int i = 0; i < m_frame; i++) { fprintf(m_logFile, "%f,%i,%i,%i,%i\n", m_TimeStamp[i], m_Trial[i], m_Feature[i], m_Detect[i], m_Epoch[i]); } // Reset the arrays to continue recording data m_frame = 0; std::cout << "Saved log file\n"; } /** Create an artificial function to cycle through the epochs, simulating trials. Replace with signals from the control computer when possible. */ void FinalProjectApp ::AdvanceTrialEpoch(int nextEpoch) { if(nextEpoch>=0 && nextEpoch<=2){ m_CurrentEpoch = nextEpoch; //Since the Epoch has advanced, lets see if we should update the LCDs if(m_CurrentEpoch == 0){ m_CurrentTrial++; //Determine if we call this a success, subject to change if(((double)m_attentionCounter) / ((double)m_Threshold) > 0.5) m_SuccessfulTrials++; else m_FailedTrials++; emit updateSuccessfulTrialsLCD(m_SuccessfulTrials); emit updateFailedTrialsLCD(m_FailedTrials); } } else printf("Error, invalid number for next Epoch (%i)",nextEpoch); } //******************* Copied Code **************************** // Perform face detection on the input image, using the given Haar Cascade. // Returns a rectangle for the detected region in the given image. CvRect FinalProjectApp ::detectEyesInImage(IplImage *inputImg, CvHaarClassifierCascade* cascade) { // Smallest face size. CvSize minFeatureSize = cvSize(10, 10); // Only search for 1 face. int flags = CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH; // How detailed should the search be. float search_scale_factor = 1.1f; //default 1.1f IplImage *detectImg; IplImage *greyImg = 0; CvMemStorage* storage; CvRect rc; double t; CvSeq* rects; CvSize size; int i, ms, nFaces; storage = cvCreateMemStorage(0); cvClearMemStorage( storage ); // If the image is color, use a greyscale copy of the image. detectImg = (IplImage*)inputImg; if (inputImg->nChannels > 1) { size = cvSize(inputImg->width, inputImg->height); greyImg = cvCreateImage(size, IPL_DEPTH_8U, 1 ); cvCvtColor( inputImg, greyImg, CV_BGR2GRAY ); detectImg = greyImg; // Use the greyscale image. } // Detect all the faces in the greyscale image. t = (double)cvGetTickCount(); rects = cvHaarDetectObjects( detectImg, cascade, storage, search_scale_factor, 3, flags, minFeatureSize); t = (double)cvGetTickCount() - t; ms = cvRound( t / ((double)cvGetTickFrequency() * 1000.0) ); nFaces = rects->total; //uncomment for debugging //printf("Face Detection took %d ms and found %d objects\n", ms, nFaces); // Get the first detected face (the biggest). if (nFaces > 0) rc = *(CvRect*)cvGetSeqElem( rects, 0 ); else rc = cvRect(-1,-1,-1,-1); // Couldn't find the face. if (greyImg) cvReleaseImage( &greyImg ); cvReleaseMemStorage( &storage ); //Now that we have permanent cascades (to improve performance) we don't want to release them //cvReleaseHaarClassifierCascade( &cascade ); return rc; // Return the biggest face found, or (-1,-1,-1,-1). } QImage* FinalProjectApp ::IplImage2QImage(IplImage *iplImg) { int h = iplImg->height; int w = iplImg->width; int channels = iplImg->nChannels; QImage *qimg = new QImage(w, h, QImage::Format_ARGB32); char *data = iplImg->imageData; for (int y = 0; y < h; y++, data += iplImg->widthStep) { for (int x = 0; x < w; x++) { char r, g, b, a = 0; if (channels == 1) { r = data[x * channels]; g = data[x * channels]; b = data[x * channels]; } else if (channels == 3 || channels == 4) { r = data[x * channels + 2]; g = data[x * channels + 1]; b = data[x * channels]; } if (channels == 4) { a = data[x * channels + 3]; qimg->setPixel(x, y, qRgba(r, g, b, a)); } else { qimg->setPixel(x, y, qRgb(r, g, b)); } } } return qimg; } IplImage* FinalProjectApp ::QImage2IplImage(QImage *qimg) { IplImage *imgHeader = cvCreateImageHeader( cvSize(qimg->width(), qimg->height()), IPL_DEPTH_8U, 4); imgHeader->imageData = (char*) qimg->bits(); uchar* newdata = (uchar*) malloc(sizeof(uchar) * qimg->byteCount()); memcpy(newdata, qimg->bits(), qimg->byteCount()); imgHeader->imageData = (char*) newdata; //cvClo return imgHeader; } CvRect FinalProjectApp ::intersect(CvRect r1, CvRect r2) { CvRect intersection; // find overlapping region intersection.x = (r1.x < r2.x) ? r2.x : r1.x; intersection.y = (r1.y < r2.y) ? r2.y : r1.y; intersection.width = (r1.x + r1.width < r2.x + r2.width) ? r1.x + r1.width : r2.x + r2.width; intersection.width -= intersection.x; intersection.height = (r1.y + r1.height < r2.y + r2.height) ? r1.y + r1.height : r2.y + r2.height; intersection.height -= intersection.y; // check for non-overlapping regions if ((intersection.width <= 0) || (intersection.height <= 0)) { intersection = cvRect(0, 0, 0, 0); } return intersection; }
#include<iostream> #include<vector> using namespace std; int main() { int i,j,n,m,x,y,count,nw,na,wake[26],years; char a,b,c; while(cin>>n) { vector<vector<int>> v(26); vector<int>stat; stat.assign(26,-1); cin>>m; cin>>a>>b>>c; stat[a-'A']=stat[b-'A']=stat[c-'A']=1; while(m--) { cin>>a>>b; x=a-'A';y=b-'A'; if(stat[x]!=1)stat[x]=0; if(stat[y]!=1)stat[y]=0; v[x].push_back(y); v[y].push_back(x); } years=0; while(1) { nw=0; na=0; for(i=0;i<26;i++) { count=0; if(stat[i]==0) { for(j=0;j<v[i].size();j++) if(stat[v[i][j]]==1)count++; if(count>=3){wake[nw]=i;nw++;} } else if(stat[i]==1)na++; } if(na<n&&nw==0){cout<<"THIS BRAIN NEVER WAKES UP\n";break;} else { if(nw==0&&na==n){cout<<"WAKE UP IN, "<<years<<", YEARS\n";break;} else{ for(i=0;i<nw;i++){stat[wake[i]]=1;}years++; } } } cin.ignore(); } return 0; }
#include <bits/stdc++.h> using namespace std; #define For(x) for(int i = 0; i < x; i++) #define For2(x) for(int j = 0; j < x; j++) #define For3(x) for(int k = 0; k < x; k++) #define Forv(vector) for(auto& i : vector) #define Forv2(vector) for(auto& j : vector) #define show(vector) for(auto& abcd : vector){cout<<abcd<<"\n";} ofstream fout ("gymnastics.out"); ifstream fin ("gymnastics.in"); int main(){ int K,N; fin>>K>>N; int rounds[K][N]; For(K){ For2(N){ int g; fin>>g; rounds[i][j] = g; } } int ans = 0; For(N){ For2(N){ if(i!=j){ bool works = true; For3(K){ int uno = distance(rounds[k], find(rounds[k], rounds[k] + N, i+1)); int dos = distance(rounds[k], find(rounds[k], rounds[k] + N, j+1)); if(uno < dos){ works = false; break; } } if(works){ ans++; } } } } fout<<ans<<"\n"; }
#pragma once class IBaseInterface { public: virtual ~IBaseInterface() {} }; typedef void *(*CreateInterfaceFn)(const char *pName, int *pReturnCode); typedef void *(*InstantiateInterfaceFn)();
// my O(n) solution class Solution { public: int removeDuplicates(vector<int>& nums) { int cnt = 0, i = 0, pos = 0, n = nums.size(); while(i < n){ ++cnt; nums[pos++] = nums[i]; while(i < n-1 && nums[i+1] == nums[i]) ++i; ++i; } return cnt; } };
//************************************************************************************************************* // // ゲームパオブジェクト処理 [GameObject.h] // Author : Sekine Ikuto // //************************************************************************************************************* #ifndef _GAMEOBJECT_H_ #define _GAMEOBJECT_H_ #define _CRT_SECURE_NO_WARNINGS //------------------------------------------------------------------------------------------------------------- // インクルードファイル //------------------------------------------------------------------------------------------------------------- #include "Scene.h" #include "MyEngine\CompoBehaviour.h" //------------------------------------------------------------------------------------------------------------- // マクロ定義 //------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------- // クラス定義 //------------------------------------------------------------------------------------------------------------- class CGameObject : public CScene, public mystd::CCompoBehaviour { public: /* メンバ関数 */ CGameObject(PRIORITY pri) : CScene(pri) {} // コンストラクタ virtual ~CGameObject() {} // デストラクタ virtual void Init(void) = 0; // 初期化 virtual void Uninit(void) = 0; // 終了 virtual void Update(void) = 0; // 更新 virtual void Draw(void) = 0; // 描画 private: protected: std::string m_ObjectName; // オブジェクト名 }; #endif
#include <cstdio> //n为食物种数 #include <cstring> //a为幸福值越大越好 #include <iostream> //b为每种食物的卡路里 using namespace std; //m为总卡路里量 int dp[100005]; int hate[105]; int happy[105]; int main() { while(1) { int n, m, a, b; cin >> n; for(int i = 0; i< n; i++) { scanf("%d %d", &happy[i], &hate[i]); } cin >> m; for(int i = 1; i <= n; i++) { int cc, vv; for(int k = 1; ; k++) { //盘数 if(k * hate[i] > m) break; cc = hate[i] * k; //卡路里 vv = happy[i] * k; // 幸福值 for(int w = m; w >= cc; w--) { dp[w] = max(dp[w - cc] + vv, dp[w]); //最大卡路里下的幸福值 } } } printf("%d\n", dp[m]); } return 0; }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int n, m, k; struct Tp { int x, y; } e[11111]; int d1[10011][505], d2[10011][505]; int id[505], pr[505]; int fs(int x) { if (pr[x] != x) pr[x] = fs(pr[x]); return pr[x]; } inline int CalcMerge(const int* d1, const int* d2) { memcpy(pr, d1, sizeof(pr[0]) * (n + 1)); for (int i = 1; i <= n; ++i) { if (pr[d2[i]] != pr[i]) pr[fs(i)] = fs(d2[i]); } int cnt = 0; for (int i = 1; i <= n; ++i) if (pr[i] == i) ++cnt; return cnt; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) { id[i] = i; d1[0][i] = i; } for (int i = 0; i < m; ++i) { scanf("%d%d", &e[i].x, &e[i].y); int ix = id[e[i].x]; int iy = id[e[i].y]; for (int j = 1; j <= n; ++j) { if (id[j] == ix) { id[j] = iy; } d1[i + 1][j] = id[j]; } } for (int i = 1; i <= n; ++i) { id[i] = i; d2[m][i] = i; } for (int i = m - 1; i >= 0; --i) { int ix = id[e[i].x]; int iy = id[e[i].y]; for (int j = 1; j <= n; ++j) { if (id[j] == ix) { id[j] = iy; } d2[i][j] = id[j]; } } scanf("%d", &k); for (int i = 0; i < k; ++i) { int l, r; scanf("%d%d", &l, &r); printf("%d\n", CalcMerge(d1[l - 1], d2[r])); } return 0; }
// // Created by zhou.lu on 2021/9/1. // #include "XParameter.h" extern "C" { #include <libavcodec/avcodec.h> };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright Opera Software ASA 2009 * * @author Daniel Spang */ #ifndef ES_PAGE_H #define ES_PAGE_H class ES_Chunk; class ES_ChunkAllocator; class ES_HeapHandle; class ES_Heap; class ES_PageHeader; #ifdef ES_USE_ALIGNED_SEGMENTS # include "modules/pi/system/OpMemory.h" #endif // ES_USE_ALIGNED_SEGMENTS /** * Small object pages are allocated from chunks. * * Note: If not using ES_USE_VIRTUAL_SEGMENTS, pages are aligned to the small * object page size and there will be some unused memory at the beginning and/or * end of the chunk storage. */ class ES_Chunk : public Link { public: ES_PageHeader *GetPage(); ES_Chunk *ReturnPage(ES_PageHeader *page); BOOL AllFree() { return free_pages_count == PAGES_PER_CHUNK; } void CheckIntegrity(); enum { PAGES_PER_CHUNK = ES_PARM_PAGES_PER_CHUNK, CHUNK_SIZE = ES_PARM_SMALL_PAGE_SIZE * PAGES_PER_CHUNK, #ifdef ES_USE_ALIGNED_SEGMENTS TOTAL_SIZE = CHUNK_SIZE #else // ES_USE_ALIGNED_SEGMENTS TOTAL_SIZE = CHUNK_SIZE + ES_PARM_SMALL_PAGE_SIZE - 1 #endif // ES_USE_ALIGNED_SEGMENTS }; #ifdef ES_HEAP_DEBUGGER unsigned CountFreePages() { return free_pages_count; } #endif // ES_HEAP_DEBUGGER private: friend class ES_ChunkAllocator; static ES_Chunk *Make(); ES_Chunk(); ~ES_Chunk(); ES_PageHeader *free_pages; unsigned free_pages_count; #ifdef ES_USE_ALIGNED_SEGMENTS const OpMemory::OpMemSegment *segment; char *storage; #else // ES_USE_ALIGNED_SEGMENTS char storage[TOTAL_SIZE]; #endif // ES_USE_ALIGNED_SEGMENTS }; /** * Header of page where garbage collected objects are allocated. * * A page consists of a page header, a card table (bit-field) representing the * remembered set, an object storage where the actual objects are stored and - * for large object pages - a footer with the excess card table. * * | header | card table | objects | excess card table | * * Both small and large object pages are aligned to the small object page size * to easily be able to find the beginning of the page. Since there is only one * large object in large object pages we can use the same method to find the * page start for those. * * The card table is a bit-field where each bit represents a possible position * of a pointer in the object storage which is part of the remembered set. * * The card table logically starts at the very beginning of the page. But since * the first pointer, that actually can be part of the remembered set, is * located after the card table, the first bits in the table are never set. We * use this space to store the header. * * Large object pages, which can vary in size, uses the card table in the header * for the first part of the object store. Pointers further up the object uses * the card table in the footer, since the card table in the header is fixed * sized. */ class ES_PageHeader { public: void Initialize(ES_Boxed *limit, ES_Chunk *owner = NULL, ES_PageHeader *next = NULL); static UINTPTR HeaderSize(); /**< Size of header (including possible card table) counting from the beginning of the page. */ static UINTPTR TotalSize(unsigned nbytes); /**< Total allocation size for page with 'nbytes' of useful payload. */ ES_Boxed *GetFirst() const; /**< First object stored. */ unsigned GetSize() const; /**< Size of the object storage. */ ES_Chunk *GetChunk() const { return owner; } /**< The chunk this page belongs to. NULL if not allocated on chunk, i.e., large object pages. */ BOOL GetHasMarkedObjects() const { return flags.has_marked_objects; } /**< Page has one or more marked objects. */ BOOL GetHasMustDestroyObjects() const { return flags.has_must_destroy_objects; } /**< Page has one or more objects that needs destroy. */ void SetHasMarkedObjects(BOOL value) { flags.has_marked_objects = value; } void SetHasMustDestroyObjects(BOOL value) { flags.has_must_destroy_objects = value; if (value) flags.has_marked_objects = value; } void SetHasMarkedObjects() { flags.has_marked_objects = TRUE; } void SetHasMustDestroyObjects() { flags.has_must_destroy_objects = flags.has_marked_objects = TRUE; } void ClearHasMarkedObjects() { flags.has_marked_objects = FALSE; } void ClearHasMustDestroyObjects() { flags.has_must_destroy_objects = FALSE; } ES_Chunk *ReturnToChunk(); ES_Boxed* limit; /**< Address past last object in page. */ ES_PageHeader *next; /**< Next page in the area. */ ES_Chunk *owner; /**< The chunk this page belongs to. NULL if not allocated on chunk, i.e., large object pages. */ private: union { unsigned raw; struct { unsigned has_marked_objects:1; unsigned has_must_destroy_objects:1; } flags; }; }; /** * Allocates chunks. This allocator is shared between heaps. */ class ES_ChunkAllocator { public: ES_ChunkAllocator() : stats() {} ES_Chunk *AllocateChunk(); void FreeChunk(ES_Chunk *chunk); void TrimChunks() {} class Statistics { public: Statistics() : allocated(0), max_allocated(0) {} unsigned allocated; unsigned max_allocated; }; Statistics stats; }; /** TRUE if 'pointer' is aligned on ES_LIM_ARENA_ALIGN. */ #define ES_IS_POINTER_PAGE_ALIGNED(pointer) ((reinterpret_cast<UINTPTR>(pointer) & (ES_LIM_ARENA_ALIGN - 1)) == 0) /** TRUE if 'size' is an integer multiple of ES_LIM_ARENA_ALIGN. */ #define ES_IS_SIZE_PAGE_ALIGNED(size) (((size) & (ES_LIM_ARENA_ALIGN - 1)) == 0) /** * Allocates aligned pages from chunks. Shared between related runtimes, hence * reference counted. */ class ES_PageAllocator #ifdef ES_HEAP_DEBUGGER : public Link #endif // ES_HEAP_DEBUGGER { public: ES_PageAllocator(ES_ChunkAllocator *chunk_allocator); ~ES_PageAllocator(); ES_PageHeader *AllocateFixed(ES_Context *context); /**< Allocate a small fixed sized page that is aligned to the page size. */ static ES_PageHeader *AllocateLarge(ES_Context *context, unsigned nbytes); /**< Allocate a large page that is aligned to ES_LIM_ARENA_ALIGN. */ void FreeFixed(ES_PageHeader *page); /**< Returns a page to the chunk. Deallocates the chunk if all pages in it is free. */ static void FreeLarge(ES_Context *context, ES_PageHeader *page); /**< Deallocates a large page. */ void MergeWith(ES_Heap *other_heap); /**< Merge other allocator with this one. */ void AddHeap(ES_HeapHandle *); void RemoveHeap(ES_HeapHandle *); #ifdef ES_HEAP_DEBUGGER unsigned CountChunks() { return current_chunks.Cardinal() + full_chunks.Cardinal(); } unsigned ChunkSize() { return ES_Chunk::TOTAL_SIZE; } unsigned CountPages(); unsigned PageSize() { return ES_PARM_SMALL_PAGE_SIZE; } ES_HeapHandle *GetFirstHeapHandle(); #endif // ES_HEAP_DEBUGGER private: ES_PageHeader *AllocateChunk(ES_Context *context, unsigned nbytes, unsigned align, BOOL update_top_and_limit); /**< Allocates a new chunk. */ ES_PageHeader *AllocateFixedSlow(ES_Context *context); /**< Allocates a new aligned page of fixed size from a chunk. */ Head current_chunks, full_chunks; /**< List of chunks where the first one is the one we currently allocate fixed pages from. This is a list because there can be more than one current chunk after a merge. */ Head heaps; /**< List of heaps using this allocator. */ ES_ChunkAllocator *chunk_allocator; unsigned reference_count; }; class ES_PageVisitor { public: virtual void Visit(ES_PageHeader *page) = 0; }; #endif // ES_PAGE_H
#ifndef SKELETON_H #define SKELETON_H #include "Enemy.h" const int SKELETONHEALTH = 15; const int SKELETONLOOT = 10; const float SKELETONSPEED = 0.25f; const glm::vec3 SKELETONSCALE = glm::vec3(0.1, 0.2, 1); class Skeleton : public Enemy { public: Skeleton(float, stack<Node*>, glm::vec3); }; #endif
#include <iostream> using namespace std; void cycleSortDistinct(int arr[],int n){ for(int cs=0;cs<n-1;cs++){ int pos=cs; int item=arr[cs]; for(int i=cs+1;i<n;i++){ if(arr[i]<item) pos++; } swap(item,arr[pos]); while(pos!=cs){ pos=cs; for(int i=cs+1;i<n;i++){ if(arr[i]<item) pos++; } swap(item,arr[pos]); } } } int main(int argc, char const *argv[]) { int arr[]={20,40,50,10,30}; int n=sizeof(arr)/sizeof(arr[0]); cycleSortDistinct(arr,n); for (size_t i = 0; i < n; i++) { std::cout << arr[i] << '\t'; /* code */ } return 0; }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef XSLT_XMLSOURCECODEOUTPUTHANDLER_H #define XSLT_XMLSOURCECODEOUTPUTHANDLER_H #ifdef XSLT_SUPPORT # include "modules/xslt/src/xslt_xmloutputhandler.h" class XSLT_OutputBuffer; class XSLT_XMLSourceCodeOutputHandler : public XSLT_XMLOutputHandler { public: XSLT_XMLSourceCodeOutputHandler (XSLT_OutputBuffer *buffer, XSLT_StylesheetImpl *stylesheet, BOOL expand_empty_elements = FALSE); private: /* From XSLT_OutputHandler via XSLT_XMLOutputHandler: */ virtual void AddTextL (const uni_char *data, BOOL disable_output_escaping); virtual void AddCommentL (const uni_char *data); virtual void AddProcessingInstructionL (const uni_char *target, const uni_char *data); virtual void EndOutputL (); /* From XSLT_XMLOutputHandler: */ virtual void OutputXMLDeclL (const XMLDocumentInformation &document_info); virtual void OutputDocumentTypeDeclL (const XMLDocumentInformation &document_info); virtual void OutputTagL (XMLToken::Type type, const XMLCompleteName &name); void CloseCDATASectionL (); XSLT_OutputBuffer *buffer; BOOL expand_empty_elements; BOOL in_cdata_section; }; #endif // XSLT_SUPPORT #endif // XSLT_XMLSOURCECODEOUTPUTHANDLER_H
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2011 Steven Lovegrove * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <pangolin/factory/factory_registry.h> #include <pangolin/utils/file_utils.h> #include <pangolin/video/drivers/pvn.h> #include <pangolin/video/iostream_operators.h> #include <iostream> using namespace std; namespace pangolin { PvnVideo::PvnVideo(const std::string& filename, bool realtime ) : frame_size_bytes(0), realtime(realtime), last_frame(TimeNow()) { file.open( PathExpand(filename).c_str(), ios::binary ); if(!file.is_open() ) throw VideoException("Cannot open file - does not exist or bad permissions."); ReadFileHeader(); } PvnVideo::~PvnVideo() { } void PvnVideo::ReadFileHeader() { string sfmt; float framerate; unsigned w, h; file >> sfmt; file >> w; file >> h; file >> framerate; file.get(); if(file.bad() || !(w >0 && h >0) ) throw VideoException("Unable to read video header"); const PixelFormat fmt = PixelFormatFromString(sfmt); StreamInfo strm0( fmt, w, h, (w*fmt.bpp) / 8, 0); frame_size_bytes += strm0.Pitch() * strm0.Height(); // frame_interval = TimeFromSeconds( 1.0 / framerate); streams.push_back(strm0); } void PvnVideo::Start() { } void PvnVideo::Stop() { } size_t PvnVideo::SizeBytes() const { return frame_size_bytes; } const std::vector<StreamInfo>& PvnVideo::Streams() const { return streams; } bool PvnVideo::GrabNext( unsigned char* image, bool /*wait*/ ) { file.read((char*)image, frame_size_bytes); const basetime next_frame = TimeAdd(last_frame, frame_interval); if( realtime ) { WaitUntil(next_frame); } last_frame = TimeNow(); return file.good(); } bool PvnVideo::GrabNewest( unsigned char* image, bool wait ) { return GrabNext(image,wait); } PANGOLIN_REGISTER_FACTORY(PvnVideo) { struct PvnVideoFactory : public FactoryInterface<VideoInterface> { std::unique_ptr<VideoInterface> Open(const Uri& uri) override { const std::string path = PathExpand(uri.url); if( !uri.scheme.compare("pvn") || FileType(uri.url) == ImageFileTypePvn ) { const bool realtime = uri.Contains("realtime"); return std::unique_ptr<VideoInterface>(new PvnVideo(path.c_str(), realtime)); } return std::unique_ptr<VideoInterface>(); } }; auto factory = std::make_shared<PvnVideoFactory>(); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 10, "pvn"); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 10, "file"); } }
//Lora SENDER #include <Arduino.h> #include <LoRa.h> #define ON_CNFRM 4 #define OFF_CNFRM 5 #define PING_PIN 6 long lastSendTime=0; int interval=50; long lastSendTime1=0; int interval1=50; bool state = false; void check_lora_connection(void); String send_data(String); String receive_data(void); const int buttonPin_NO = 2; const int buttonPin_NC = 3; void onReceive(int); int buttonState_NO = 0; int buttonState_NC = 0; void setup() { Serial.begin(9600); pinMode(buttonPin_NO, INPUT_PULLUP); pinMode(buttonPin_NC, INPUT_PULLUP); pinMode(ON_CNFRM, OUTPUT); pinMode(OFF_CNFRM, OUTPUT); pinMode(PING_PIN, OUTPUT); Serial.println("STARTING-LORA-SEND"); check_lora_connection(); digitalWrite(ON_CNFRM, LOW); digitalWrite(OFF_CNFRM, HIGH); Serial.println("LORA Connected"); send_data("hello testing sender here "); } void loop() { onReceive(LoRa.parsePacket()); if (millis() - lastSendTime1 > interval1) { buttonState_NO = digitalRead(buttonPin_NO); if (buttonState_NO == LOW) { // turn LED on: send_data("ON"); } lastSendTime1 = millis(); } if (millis() - lastSendTime > interval) { buttonState_NC = digitalRead(buttonPin_NC); if (buttonState_NC == LOW) { // turn LED on: send_data("OFF"); } lastSendTime = millis } } String send_data(String data) { String temp_data = "send successfull"; LoRa.beginPacket(); LoRa.print(data); LoRa.endPacket(); return temp_data; } void check_lora_connection() { if (!LoRa.begin(433E6)) { Serial.println("Starting LoRa failed!"); while (1); } } void onReceive(int packetSize) { if (packetSize == 0) return; String incoming = ""; while (LoRa.available()) { incoming += (char)LoRa.read(); } Serial.println("Message: " + incoming); Serial.println("RSSI: " + String(LoRa.packetRssi())); Serial.println(); if(incoming =="Motor Started successfully" || incoming=="Already On") { digitalWrite(ON_CNFRM, HIGH); digitalWrite(OFF_CNFRM, LOW); } if(incoming =="Motor Stopped successfully" || incoming=="Already OFF") { digitalWrite(ON_CNFRM, LOW); digitalWrite(OFF_CNFRM, HIGH); } }
#include <cstring> #include <cstdlib> #include <vector> #include <map> #include <string> #include <cstdio> #include <float.h> #include <string.h> #include <cmath> using namespace std; int num_threads; int trainTimes; float alpha; float reduce; int dimensionC; int dimensionWPE; float marginPositive; float marginNegative; float margin; float Belt; int window; int limit; int tt,tt1; float *matrixB1, *matrixRelation, *matrixW1, *matrixRelationDao; float *positionVecE1, *positionVecE2, *matrixW1PositionE1, *matrixW1PositionE2; int batch; int turn; float rate; float *matrixRelation_1; float *wordVec; long long wordTotal, dimension, relationTotal; long long PositionMinE1, PositionMaxE1, PositionTotalE1,PositionMinE2, PositionMaxE2, PositionTotalE2; std::vector<int *> trainLists, trainPositionE1, trainPositionE2; std::vector<int> trainLength; std::vector<int> headList, tailList, relationList; std::map<std::string,int> wordMapping; std::map<std::string,int> relationMapping; map<string,int> entity2id,relation2id; vector<double *> entity2vec,relation2vec; vector<std::string> nam; void __init() { num_threads = 7; trainTimes = 90; alpha = 0.02; reduce = 1; dimensionC = 400; dimensionWPE = 25; dimension = 150; marginPositive = 2.5; marginNegative = 0.5; margin = 2; Belt = 0.001; window = 3; limit = 30; batch = 16; rate = 1; } float CalcTanh(float con) { if (con > 20) return 1.0; if (con < -20) return -1.0; float sinhx = exp(con) - exp(-con); float coshx = exp(con) + exp(-con); return sinhx / coshx; } float tanhDao(float con) { float res = CalcTanh(con); return 1 - res * res; } float sigmod(float con) { if (con > 20) return 1.0; if (con < -20) return 0.0; con = exp(con); return con / (1 + con); } int getRand(int l,int r) { int len = r - l; int res = rand() % len; return res + l; } float getRandU(float l, float r) { float len = r - l; float res = (float)(rand()) / RAND_MAX; return res * len + l; } std::vector<int *> testtrainLists, testPositionE1, testPositionE2; std::vector<int> testtrainLength; std::vector<int> testheadList, testtailList, testrelationList; std::vector<int> testentityE1, testentityE2; int tipp; float ress; void test(int *sentence, int *testPositionE1, int *testPositionE2, int len, int e1, int e2, int r1, float &res, float *r) { int tip[dimensionC]; for (int i = 0; i < dimensionC; i++) { int last = i * dimension * window; int lastt = i * dimensionWPE * window; float mx = -FLT_MAX; for (int i1 = 0; i1 <= len - window; i1++) { float res = 0; int tot = 0; int tot1 = 0; for (int j = i1; j < i1 + window; j++) { int last1 = sentence[j] * dimension; for (int k = 0; k < dimension; k++) { res += matrixW1[last + tot] * wordVec[last1+k]; tot++; } int last2 = testPositionE1[j] * dimensionWPE; int last3 = testPositionE2[j] * dimensionWPE; for (int k = 0; k < dimensionWPE; k++) { res += matrixW1PositionE1[lastt + tot1] * positionVecE1[last2+k]; res += matrixW1PositionE2[lastt + tot1] * positionVecE2[last3+k]; tot1++; } } if (res > mx) mx = res; } r[i] = mx + matrixB1[i]; } for (int i = 0; i < dimensionC; i++) r[i] = CalcTanh(r[i]); float s2 = -FLT_MAX; int r2; for (int i = 0; i < dimensionC; i++) r[i] = CalcTanh(r[i]); for (int j = 1; j < relationTotal; j++) { float s = 0; for (int i = 0; i < dimensionC; i++) { s += matrixRelation_1[j * dimensionC + i] * r[i]; // s += matrixRelation_1[j * dimensionC + i] * (entity2vec[ee2][i] - entity2vec[ee1][i]); // float tmp = -relation2vec[j][i]+(entity2vec[ee2][i] - entity2vec[ee1][i]); // if (tmp>0) // s += tmp; else s -= tmp; } // if (j==r1) printf("%f ",s); if (s >= s2) { s2 = s; r2 = j; } } // printf("%f\n", s2); tipp = r2; if (s2 < 0) tipp = 0; ress = s2; // if (tipp==0 && r1!=0) printf("wrong 0 %lf\n",s2); // if (tipp!=0 && r1==0) printf("wrong !0 %lf\n",s2); } struct arr { int num; int ans; float res; }; arr work[100000]; struct cmp { bool operator()(const arr &a,const arr&b) { return a.res>b.res; } }; void test() { float *matrixW1Dao = (float*)calloc(dimensionC * dimension * window, sizeof(float)); float *matrixB1Dao = (float*)calloc(dimensionC, sizeof(float)); float *r = (float *)calloc(dimensionC, sizeof(float)); std::vector<int> ans; float res = 0; int re1 = testtrainLists.size(); ans.clear(); int tot=0; for (int k1 = 0; k1 < re1; k1++) { int i=k1; test(testtrainLists[i], testPositionE1[i], testPositionE2[i], testtrainLength[i], testheadList[i], testtailList[i], testrelationList[i], res, r); work[tot].num = 8001+k1; work[tot].ans = tipp; work[tot].res = ress; tot++; } res = 0; float mxxx=0; for (int i = 0; i <tot;i++) { if (work[i].ans==0) continue; if (work[i].ans == testrelationList[work[i].num-8001]) res+=1; mxxx+=1; } mxxx = res / mxxx; printf("%.6f\n: ",mxxx); float mxxy = res / 2263; printf("%.6f\n: ",mxxy); mxxx = 2/((1/mxxx)+(1/mxxy)); printf("%.6f\n: ",mxxx); FILE *out=fopen("out/output.txt","w"); for (int i=re1-1;i>=0;i--) fprintf(out, "%d %s\n", work[i].num, nam[work[i].ans].c_str()); fclose(out); free(matrixW1Dao); free(matrixB1Dao); free(r); } void Init() { __init(); char buffer[1000]; testentityE1.clear(); testentityE2.clear(); relationTotal = 0; FILE * f = fopen("data/relation2id.txt", "r"); while (fscanf(f,"%s",buffer)==1) { int id; fscanf(f,"%d",&id); relationMapping[(string)(buffer)] = id; relationTotal++; nam.push_back((std::string)(buffer)); } fclose(f); double num; f = fopen("data/vectors.bin", "rb"); fscanf(f, "%lld", &wordTotal); fscanf(f, "%lld", &dimension); PositionMinE1 = 0; PositionMaxE1 = 0; PositionMinE2 = 0; PositionMaxE2 = 0; wordVec = (float *)malloc(wordTotal * dimension * sizeof(float)); for (int b = 0; b < wordTotal; b++) { std::string name = ""; while (1) { char ch = fgetc(f); if (feof(f) || ch == ' ') break; if (ch != '\n') name = name + ch; } long long last = b * dimension; float smp = 0; for (int a = 0; a < dimension; a++) { fread(&wordVec[a + last], sizeof(float), 1, f); smp += wordVec[a + last]*wordVec[a + last]; } smp = sqrt(smp); for (int a = 0; a< dimension; a++) wordVec[a+last] = wordVec[a+last] / smp; wordMapping[name] = b; } fclose(f); f = fopen("data/test.txt", "r"); while (fscanf(f,"%s",buffer)==1) { int head = wordMapping[(std::string)(buffer)]; int head1 = entity2id[(std::string)(buffer)]; fscanf(f,"%s",buffer); int tail = wordMapping[(std::string)(buffer)]; int tail1 = entity2id[(std::string)(buffer)]; fscanf(f,"%s",buffer); int num = relationMapping[(string)(buffer)]; int len = 0 , lefnum = 0, rignum = 0; std::vector<int> tmpp; while (fscanf(f,"%s", buffer)==1) { std::string con = buffer; if (con=="#") break; int gg = wordMapping[con]; if (gg == -1) continue; if (gg == head) lefnum = len; if (gg == tail) rignum = len; len++; tmpp.push_back(gg); } if (head != -1 && tail != -1) { testheadList.push_back(head); testtailList.push_back(tail); testentityE1.push_back(head1); testentityE2.push_back(tail1); testrelationList.push_back(num); testtrainLength.push_back(len); int *con=(int *)calloc(len,sizeof(int)); int *conl=(int *)calloc(len,sizeof(int)); int *conr=(int *)calloc(len,sizeof(int)); for (int i = 0; i < len; i++) { con[i] = tmpp[i]; conl[i] = lefnum - i; conr[i] = rignum - i; if (conl[i] >= limit) conl[i] = limit; if (conr[i] >= limit) conr[i] = limit; if (conl[i] <= -limit) conl[i] = -limit; if (conr[i] <= -limit) conr[i] = -limit; if (conl[i] > PositionMaxE1) PositionMaxE1 = conl[i]; if (conr[i] > PositionMaxE2) PositionMaxE2 = conr[i]; if (conl[i] < PositionMinE1) PositionMinE1 = conl[i]; if (conr[i] < PositionMinE2) PositionMinE2 = conr[i]; } testtrainLists.push_back(con); testPositionE1.push_back(conl); testPositionE2.push_back(conr); } } fclose(f); for (int i = 0; i < testPositionE1.size(); i++) { int len = testtrainLength[i]; int *work1 = testPositionE1[i]; for (int j = 0; j < len; j++) work1[j] = work1[j] - PositionMinE1; int *work2 = testPositionE2[i]; for (int j = 0; j < len; j++) work2[j] = work2[j] - PositionMinE2; } for (int i = 0; i < trainPositionE1.size(); i++) { int len = trainLength[i]; int *work1 = trainPositionE1[i]; for (int j = 0; j < len; j++) work1[j] = work1[j] - PositionMinE1; int *work2 = trainPositionE2[i]; for (int j = 0; j < len; j++) work2[j] = work2[j] - PositionMinE2; } PositionTotalE1 = PositionMaxE1 - PositionMinE1 + 1; PositionTotalE2 = PositionMaxE2 - PositionMinE2 + 1; matrixRelation_1 = (float *)calloc(dimensionC * relationTotal, sizeof(float)); positionVecE1 = (float *)calloc(PositionTotalE1 * dimensionWPE, sizeof(float)); positionVecE2 = (float *)calloc(PositionTotalE2 * dimensionWPE, sizeof(float)); matrixW1 = (float*)calloc(dimensionC * dimension * window, sizeof(float)); matrixW1PositionE1 = (float *)calloc(dimensionC * dimensionWPE * window, sizeof(float)); matrixW1PositionE2 = (float *)calloc(dimensionC * dimensionWPE * window, sizeof(float)); matrixB1 = (float*)calloc(dimensionC, sizeof(float)); FILE *fout = fopen("matrixW1+B1.txt", "r"); for (int i = 0; i < dimensionC; i++) { for (int j = 0; j < dimension * window; j++) fscanf(fout, "%f\t",&matrixW1[i* dimension*window+j]); for (int j = 0; j < dimensionWPE * window; j++) fscanf(fout, "%f\t",&matrixW1PositionE1[i* dimensionWPE*window+j]); for (int j = 0; j < dimensionWPE * window; j++) fscanf(fout, "%f\t",&matrixW1PositionE2[i* dimensionWPE*window+j]); fscanf(fout, "%f\n", &matrixB1[i]); } fclose(fout); fout = fopen("matrixRl.txt", "r"); for (int i = 0; i < relationTotal; i++) { for (int j = 0; j < dimensionC; j++) fscanf(fout, "%f\t", &matrixRelation_1[i * dimensionC + j]); fscanf(fout, "\n"); } fclose(fout); fout = fopen("matrixPosition.txt", "r"); for (int i = 0; i < PositionTotalE1; i++) { for (int j = 0; j < dimensionWPE; j++) fscanf(fout, "%f\t", &positionVecE1[i * dimensionWPE + j]); fscanf(fout, "\n"); } for (int i = 0; i < PositionTotalE2; i++) { for (int j = 0; j < dimensionWPE; j++) fscanf(fout, "%f\t", &positionVecE2[i * dimensionWPE + j]); fscanf(fout, "\n"); } fclose(fout); } int main() { Init(); test(); return 0; }
#pragma once #include <constants.h> #include <Arduino.h> class arm { public: arm(uint8_t *SPI1, uint8_t *SPI2); void homeArm(void); void extendArm(void); void sleepArm(void); void wakeupArm(void); void moveSlider(int position); void moveLift(int position); void moveArm(int position); void dispenseStones(void); void collectStone(int stoneNumber); void storeStone(int stoneNumber); void raiseClaw(void); void lowerClaw(void); void openClaw(void); void closeClaw(void); void homeClaw(void); void extendSlider(void); void retractSlider(void); void homeSlider(void); void homeRotateArm(void); void poleRotateArm(void); int getLiftPosition(void); int getArmPosition(void); int getSliderPosition(void); private: uint8_t *SPIdata1; uint8_t *SPIdata2; int liftPosition; //Up is positive int armPosition; //Forwards is negative int sliderPosition; //CW is positive, CCW is negative };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 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 STDLIB_MODULE_REQUIRED #include "modules/stdlib/stdlib_module.h" #include "modules/stdlib/include/double_format.h" #include "modules/stdlib/src/stdlib_internal.h" #include "modules/util/handy.h" #ifdef DTOA_DAVID_M_GAY #include "modules/stdlib/src/thirdparty_dtoa_dmg/double_format.h" #endif // DTOA_DAVID_M_GAY StdlibModule::StdlibModule() { #ifndef HAVE_UNI_STRTOK m_uni_strtok_datum = NULL; #endif #ifdef DTOA_DAVID_M_GAY m_dtoa_p5s = NULL; m_dtoa_result = NULL; #endif // DTOA_DAVID_M_GAY #ifdef DTOA_FLOITSCH_DOUBLE_CONVERSION op_memset(m_dtoa_buffer, 0, ARRAY_SIZE(m_dtoa_buffer)); #endif // DTOA_FLOITSCH_DOUBLE_CONVERSION #ifdef STDLIB_DTOA_LOCKS m_dtoa_lock = 0; #endif // STDLIB_DTOA_LOCKS /* Phase 1: set up state */ #ifdef DTOA_DAVID_M_GAY for (size_t i = 0 ; i < ARRAY_SIZE(m_dtoa_freelist); i ++) { m_dtoa_freelist[i] = NULL; } # ifdef _DEBUG for (size_t j = 0 ; j < ARRAY_SIZE(m_dtoa_blocks); j ++) { m_dtoa_blocks[j] = 0; } m_dtoa_blocks_allocated = 0; m_dtoa_blocks_freed = 0; # endif // _DEBUG #endif // DTOA_DAVID_M_GAY #ifndef HAVE_RAND # ifdef MERSENNE_TWISTER_RNG op_memset(m_mt, 0, sizeof(m_mt)); m_mti = static_cast<int>(ARRAY_SIZE(m_mt) + 1); m_mag01[0] = 0;; m_mag01[1] = 0x9908b0dfU; # endif #endif m_infinity = op_implode_double(0x7ff00000U, 0U); #if !defined STDLIB_DTOA_CONVERSION && !defined HAVE_STRTOD && !defined HAVE_SSCANF m_negative_infinity = op_implode_double(0xfff00000UL, 0UL); #endif #ifdef QUIET_NAN_IS_ONE m_quiet_nan = op_implode_double(0x7fffffffUL, 0xffffffffUL); #else m_quiet_nan = op_implode_double(0x7ff7ffffUL, 0xffffffffUL); #endif /* Phase 2: initialization of subsystems */ // Cannot call op_srand() directly since it requires that the // g_opera pointer is set up correctly, which it might not // be until after we return. #ifndef HAVE_RAND /* C99 7.20.2.2 mandates that we should call srand(1) */ # ifdef MERSENNE_TWISTER_RNG stdlib_srand_init(1, m_mt, &m_mti); # else stdlib_srand_init(1, &m_random_state); # endif #endif /* Phase 3: Rudimentary self-tests for typical porting problems. */ // If you've misconfigured the floating point format for the target platform // it will get you here. #ifdef EPOC __ASSERT_ALWAYS(op_implode_double(0x40000000, 0x0) == 2.0, User::Panic(_L("stdlib_module.cpp"), __LINE__)); #else OP_ASSERT(op_implode_double( 0x40000000, 0x0) == 2.0); #endif #ifndef NAN_EQUALS_EVERYTHING // Typically it is a problem under Microsoft Visual C/C++ that NaN compares // equal with everything. This is bizarre and very wrong. If you hit the // assert below you must set SYSTEM_NAN_EQUALS_EVERYTHING = YES. // // Note you cannot change !(.. == ..) to (.. != ..). # ifdef EPOC __ASSERT_ALWAYS(!(m_quiet_nan == 1.0), User::Panic(_L("stdlib_module.cpp"), __LINE__ )); # else if (m_quiet_nan == 1) { OP_ASSERT(0); } # endif #endif #ifdef NAN_ARITHMETIC_OK // On some platforms NaN cannot be used for computation, it will crash the // program. If your program crashes here, then set SYSTEM_NAN_ARITHMETIC_OK = NO. double d = m_quiet_nan; d = d + 37; #endif } void StdlibModule::InitL(const OperaInitInfo &) { } void StdlibModule::Destroy() { #ifdef DTOA_DAVID_M_GAY stdlib_dtoa_shutdown(1); #endif // DTOA_DAVID_M_GAY } BOOL StdlibModule::FreeCachedData(BOOL) { #ifdef DTOA_DAVID_M_GAY // This is safe even while inside Balloc() stdlib_dtoa_shutdown(0); return TRUE; #else return FALSE; #endif // DTOA_DAVID_M_GAY } #ifdef STDLIB_DTOA_LOCKS bool StdlibModule::LockDtoa(int lock) { if (0 == lock) { return 0 == m_dtoa_lock ++; } return true; } void StdlibModule::UnlockDtoa(int lock) { if (0 == lock) { -- m_dtoa_lock; } } #endif #endif // STDLIB_MODULE_REQUIRED
#include <bits/stdc++.h> using namespace std; long long int N,M,i; char chairo; int main() { ios_base::sync_with_stdio(0); cin.tie(0); do{ cin >> chairo; if(chairo == 'A') N++; } while(chairo != '.'); cout << N; return 0; }
//===------------------------------------------------------------*- C++ -*-===// // // Created by F8LEFT on 2017/6/28. // Copyright (c) 2017. All rights reserved. //===----------------------------------------------------------------------===// // //===----------------------------------------------------------------------===// #ifndef FAOATDUMP_EXELF_H #define FAOATDUMP_EXELF_H #include "elf.h" #ifndef __SO64__ typedef Elf32_Ehdr Elf_Ehdr; typedef Elf32_Phdr Elf_Phdr; typedef Elf32_Shdr Elf_Shdr; typedef Elf32_Sym Elf_Sym; typedef Elf32_Dyn Elf_Dym; typedef Elf32_Rel Elf_Rel; typedef Elf32_Rela Elf_Rela; typedef Elf32_Addr Elf_Addr; typedef Elf32_Dyn Elf_Dyn; typedef Elf32_Word Elf_Word; #else typedef Elf64_Ehdr Elf_Ehdr; typedef Elf64_Phdr Elf_Phdr; typedef Elf64_Shdr Elf_Shdr; typedef Elf64_Sym Elf_Sym; typedef Elf64_Dyn Elf_Dym; typedef Elf64_Rel Elf_Rel; typedef Elf64_Rela Elf_Rela; typedef Elf64_Addr Elf_Addr; typedef Elf64_Dyn Elf_Dyn; typedef Elf64_Word Elf_Word; #endif #ifndef PAGE_SIZE #define PAGE_SIZE 0x1000 #define PAGE_MASK (~(PAGE_SIZE-1)) // Returns the address of the page containing address 'x'. #define PAGE_START(x) ((x) & PAGE_MASK) // Returns the offset of address 'x' in its page. #define PAGE_OFFSET(x) ((x) & ~PAGE_MASK) // Returns the address of the next page after address 'x', unless 'x' is // itself at the start of a page. #define PAGE_END(x) PAGE_START((x) + (PAGE_SIZE-1)) #endif #endif //FAOATDUMP_EXELF_H
#include<stdio.h> #include<conio.h> #include<graphics.h> #include<dos.h> void boundaryfill4(int x,int y,int f_color,int b_color) { if(getpixel(x,y)!= b_color && getpixel(x,y)!=f_color) { putpixel(x,y,f_color); delay(5); boundaryfill4(x+1,y,f_color,b_color); boundaryfill4(x,y+1,f_color,b_color); boundaryfill4(x-1,y,f_color,b_color); boundaryfill4(x,y-1,f_color,b_color); } } void draw_rectangle() { setcolor(15); rectangle(250,215,315,260); boundaryfill4(280,250,10,15); setcolor(RED); outtextxy(250,270,"RECTANGLE"); } void draw_circle() { setcolor(15); circle(250,250,30); boundaryfill4(250,250,3,15); setcolor(RED); outtextxy(230,290,"CIRCLE"); } void draw_triangle() { setcolor(15); line(140,250,90,310); line(140,250,200,310); line(90,310,200,310); boundaryfill4(140,290,5,15); setcolor(RED); outtextxy(110,320,"TRIANGLE"); } void main() { int gd=DETECT,gm,x,y,r,choice,run; do { initgraph(&gd,&gm,"C:\\TURBOC3\\BGI"); setcolor(YELLOW); outtextxy(250,20,"*** BOUNDARY FILL ALGORITHM ***"); printf(" \n\n\n"); printf("[1] TO FILL A RECTANGLE\n"); printf("[2] TO FILL A CIRCLE\n"); printf("[3] TO FILL A TRIANGLE\n"); printf(" \n\n"); printf("ENTER YOUR CHOICE ==> "); scanf("%d",&choice); switch(choice) { case 1: draw_rectangle(); break; case 2: draw_circle(); break; case 3: draw_triangle(); break; default: printf(" \n\nSHAPE NOT AVAILABLE !!!"); break; } getch(); closegraph(); printf("PRESS [1] TO DRAW AGAIN OR [0] TO EXIT ==> "); scanf("%d",&run); }while(run == 1); }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Adam Minchinton // #include "core/pch.h" #ifdef SUPPORT_SPEED_DIAL #include "adjunct/quick/speeddial/DesktopSpeedDial.h" #include "adjunct/quick/extensions/ExtensionUtils.h" #include "adjunct/quick/managers/DesktopExtensionsManager.h" #include "adjunct/quick/managers/SpeedDialManager.h" #include "adjunct/desktop_pi/DesktopOpSystemInfo.h" #include "modules/prefsfile/prefsfile.h" #include "modules/url/url_man.h" #if defined(_MACINTOSH_) && defined(PIXEL_SCALE_RENDERING_SUPPORT) #include "platforms/mac/util/CocoaPlatformUtils.h" #endif // _MACINTOSH_ && PIXEL_SCALE_RENDERING_SUPPORT //////////////////////////////////////////////////////////////////////////////////////////////////////// // // SpeedDial // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// DesktopSpeedDial::DesktopSpeedDial() : m_reload_timer(NULL), m_data_notification_timer_running(false), m_extension_data_updated(false), m_last_data_notification(0.0), m_is_loading(FALSE), m_is_reloading(FALSE), m_need_reload(FALSE) { OpStatus::Ignore(g_thumbnail_manager->AddListener(this)); m_data_notification_timer.SetTimerListener(this); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// DesktopSpeedDial::~DesktopSpeedDial() { // Kill the timer on shut down if it exists StopReloadTimer(); StopDataNotificationTimer(); if (!m_core_url.IsEmpty()) g_thumbnail_manager->DelThumbnailRef(m_core_url); // Kill the listener OpStatus::Ignore(g_thumbnail_manager->RemoveListener(this)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS DesktopSpeedDial::SetTitle(const OpStringC& title, BOOL custom) { if (m_title == title && m_is_custom_title == custom) return OpStatus::OK; OpString copy_of_title; RETURN_IF_ERROR(copy_of_title.Set(title)); // Get rid of characters that will mess up the formatting RETURN_IF_ERROR(copy_of_title.ReplaceAll(UNI_L("\\t"), UNI_L(""))); RETURN_IF_ERROR(copy_of_title.ReplaceAll(UNI_L("\\r"), UNI_L(""))); RETURN_IF_ERROR(copy_of_title.ReplaceAll(UNI_L("\\n"), UNI_L(""))); RETURN_IF_ERROR(SpeedDialData::SetTitle(copy_of_title, custom)); g_speeddial_manager->PostSaveRequest(); NotifySpeedDialDataChanged(); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS DesktopSpeedDial::SetURL(const OpStringC& url) { if (m_url == url) return OpStatus::OK; StopLoadingSpeedDial(); if (!m_core_url.IsEmpty()) g_thumbnail_manager->DelThumbnailRef(m_core_url); RETURN_IF_ERROR(SpeedDialData::SetURL(url)); if (!m_core_url.IsEmpty()) g_thumbnail_manager->AddThumbnailRef(m_core_url); g_speeddial_manager->PostSaveRequest(); NotifySpeedDialDataChanged(); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS DesktopSpeedDial::SetDisplayURL(const OpStringC& display_url) { if (m_display_url == display_url) return OpStatus::OK; SpeedDialData::SetDisplayURL(display_url); g_speeddial_manager->PostSaveRequest(); NotifySpeedDialUIChanged(); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS DesktopSpeedDial::Set(const SpeedDialData& original, bool retain_uid) { RETURN_IF_ERROR(SpeedDialData::Set(original, retain_uid)); // Restart or stop timer SetReload(original.GetReloadPolicy(), original.GetReloadTimeout(), original.GetReloadOnlyIfExpired()); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::OnAdded() { if (GetExtensionWUID().HasContent() && g_desktop_extensions_manager) OpStatus::Ignore(g_desktop_extensions_manager->SetExtensionDataListener( GetExtensionWUID(), this)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::OnRemoving() { StopDataNotificationTimer(); if (GetExtensionWUID().HasContent() && g_desktop_extensions_manager) OpStatus::Ignore(g_desktop_extensions_manager->SetExtensionDataListener( GetExtensionWUID(), NULL)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::OnShutDown() { if (m_data_notification_timer_running) { // It is too late to notify listeners (there shouldn't be any at this point), so just // notify manager that speed dials need to be saved. g_speeddial_manager->PostSaveRequest(); StopDataNotificationTimer(); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::SetReload(const ReloadPolicy policy, const int timeout, const BOOL only_if_expired) { ReloadPolicy pol = policy; if (timeout > 0 && (pol == SpeedDialData::Reload_PageDefined || pol == SpeedDialData::Reload_UserDefined)) { // If synching over link does not send us policy information (because that is a new property in 11.10) then // the timeout can be SPEED_DIAL_RELOAD_INTERVAL_DEFAULT with a policy of SpeedDialData::Reload_UserDefined // which means user selected "Never" in menu. if (timeout == SPEED_DIAL_RELOAD_INTERVAL_DEFAULT) { StopReloadTimer(); pol = SpeedDialData::Reload_NeverHard; } else { StartReloadTimer(timeout, only_if_expired); } } else { StopReloadTimer(); } //save new reload information SpeedDialData::SetReload(pol, timeout, only_if_expired); g_speeddial_manager->PostSaveRequest(); // Only ever sends a changed since the SetSpeedDial will be the thing that // will do the add/delete calls, this is extra information for an // active speed dial NotifySpeedDialDataChanged(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::StartReloadTimer(int timeout, BOOL only_if_expired) { // extensions should not be reloaded by the timer (DSK-369019) if (GetExtensionWUID().HasContent()) return; // Make sure we have a timeout if (timeout <= 0) timeout = SPEED_DIAL_ENABLED_RELOAD_INTERVAL_DEFAULT; m_timeout = timeout; m_only_if_expired = only_if_expired; if (!m_reload_timer) { if (!(m_reload_timer = OP_NEW(OpTimer, ()))) return; m_reload_timer->SetTimerListener(this); } // This is in ms m_reload_timer->Start(m_timeout * 1000); // Set the timer running flag m_reload_timer_running = TRUE; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::RestartReloadTimer(const URL &document_url) { // Check that we are restarting the timer for the matching URL and that there is a timer if (m_reload_timer && !m_reload_timer_running && IsMatchingCall(document_url)) { // If there are no Speed dials showing, postpone reloading until it is shown again if (g_speeddial_manager->GetSpeedDialTabsCount()) { int time_since_firing = max(m_reload_timer->TimeSinceFiring(), 0); int time_to_wait = m_timeout * 1000 - time_since_firing; m_reload_timer->Start(max(time_to_wait, 0)); } else { m_need_reload = TRUE; } // Set the timer running flag m_reload_timer_running = TRUE; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::StopReloadTimer() { if (m_reload_timer) { m_reload_timer->Stop(); OP_DELETE(m_reload_timer); m_reload_timer = NULL; } // Set the timer running flag m_reload_timer_running = FALSE; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::StartDataNotificationTimer(UINT32 timeout_in_ms) { m_data_notification_timer.Start(timeout_in_ms); m_data_notification_timer_running = true; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::StopDataNotificationTimer() { if (m_data_notification_timer_running) { m_data_notification_timer.Stop(); m_data_notification_timer_running = false; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::OnTimeOut(OpTimer* timer) { if (m_reload_timer == timer) { m_reload_timer_running = FALSE; SetExpired(); } else if (&m_data_notification_timer == timer) { g_speeddial_manager->PostSaveRequest(); NotifySpeedDialDataChanged(); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS DesktopSpeedDial::LoadL(PrefsFile& file, const OpStringC8& section_name) { BOOL custom = file.ReadIntL(section_name, SPEEDDIAL_KEY_CUSTOM_TITLE, FALSE); RETURN_IF_ERROR(SetTitle(file.ReadStringL(section_name, SPEEDDIAL_KEY_TITLE), custom)); RETURN_IF_ERROR(SetURL(file.ReadStringL(section_name, SPEEDDIAL_KEY_URL))); RETURN_IF_ERROR(SetDisplayURL(file.ReadStringL(section_name, SPEEDDIAL_KEY_DISPLAY_URL))); RETURN_IF_ERROR(SetExtensionID(file.ReadStringL(section_name, SPEEDDIAL_KEY_EXTENSION_ID))); RETURN_IF_ERROR(m_partner_id.Set(file.ReadStringL(section_name, SPEEDDIAL_KEY_PARTNER_ID))); /* Read the auto reload params */ SpeedDialData::ReloadPolicy reload_policy = SpeedDialData::Reload_NeverSoft; if (file.IsKey(section_name, SPEEDDIAL_KEY_RELOAD)) { // Upgrade. SPEEDDIAL_KEY_RELOAD will not be written to file again. It can be 0 or 1 int flag; flag = file.ReadIntL(section_name, SPEEDDIAL_KEY_RELOAD, SPEED_DIAL_RELOAD_ENABLED_DEFAULT); if (flag == 1) { int timeout; timeout = file.ReadIntL(section_name, SPEEDDIAL_KEY_RELOAD_INTERVAL, SPEED_DIAL_RELOAD_INTERVAL_DEFAULT); if (timeout == SPEED_DIAL_RELOAD_INTERVAL_DEFAULT) reload_policy = SpeedDialData::Reload_NeverHard; else reload_policy = SpeedDialData::Reload_UserDefined; } else reload_policy = SpeedDialData::Reload_NeverSoft; } else { int mode; mode = file.ReadIntL(section_name, SPEEDDIAL_KEY_RELOAD_POLICY, SpeedDialData::Reload_NeverSoft); switch(mode) { case Reload_NeverSoft: case Reload_UserDefined: case Reload_PageDefined: case Reload_NeverHard: reload_policy = (SpeedDialData::ReloadPolicy)mode; } } SetReload(reload_policy, file.ReadIntL(section_name, SPEEDDIAL_KEY_RELOAD_INTERVAL, SPEED_DIAL_RELOAD_INTERVAL_DEFAULT), file.ReadIntL(section_name, SPEEDDIAL_KEY_RELOAD_ONLY_IF_EXPIRED, SPEED_DIAL_RELOAD_ONLY_IF_EXPIRED_DEFAULT)); RETURN_IF_ERROR(m_unique_id.Set(file.ReadStringL(section_name, SPEEDDIAL_KEY_ID).CStr())); return OpStatus::OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::SaveL(PrefsFile& file, const OpStringC8& section_name) const { file.WriteStringL(section_name, SPEEDDIAL_KEY_TITLE, m_title.CStr()); file.WriteIntL(section_name, SPEEDDIAL_KEY_CUSTOM_TITLE, m_is_custom_title); file.WriteStringL(section_name, SPEEDDIAL_KEY_URL, m_url.CStr()); if (m_display_url.HasContent()) { file.WriteStringL(section_name, SPEEDDIAL_KEY_DISPLAY_URL, m_display_url.CStr()); } if (m_extension_id.HasContent()) { file.WriteStringL(section_name,SPEEDDIAL_KEY_EXTENSION_ID,m_extension_id.CStr()); } if (m_partner_id.HasContent()) { file.WriteStringL(section_name, SPEEDDIAL_KEY_PARTNER_ID, m_partner_id.CStr()); } file.WriteIntL(section_name, SPEEDDIAL_KEY_RELOAD_POLICY, GetReloadPolicy()); if (m_unique_id.HasContent()) { file.WriteStringL(section_name, SPEEDDIAL_KEY_ID, m_unique_id.CStr()); } file.WriteIntL(section_name, SPEEDDIAL_KEY_RELOAD_INTERVAL, GetReloadTimeout()); file.WriteIntL(section_name, SPEEDDIAL_KEY_RELOAD_ONLY_IF_EXPIRED, GetReloadOnlyIfExpired()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::NotifySpeedDialDataChanged() { StopDataNotificationTimer(); m_last_data_notification = g_op_time_info->GetRuntimeMS(); for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialDataChanged(*this); // If the data changed, then we always notify the UI as well. NotifySpeedDialUIChanged(); } void DesktopSpeedDial::NotifySpeedDialUIChanged() { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialUIChanged(*this); } void DesktopSpeedDial::NotifySpeedDialExpired() { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialExpired(); } void DesktopSpeedDial::NotifySpeedDialZoomRequest() { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialEntryScaleChanged(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::ReAddThumnailRef() { // This function should only ever be called after a Purge of the Thumbnail Manager // If this speeddial has a url then readd the thumbnail ref. if (!m_core_url.IsEmpty()) g_thumbnail_manager->AddThumbnailRef(m_core_url); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS DesktopSpeedDial::StartLoadingSpeedDial(BOOL reload, INT32 width, INT32 height) const { if (width <= 0 || height <= 0) return OpStatus::ERR; BOOL do_reload = reload; // StopLoadingSpeedDial() will cancel an ongoing reload if (m_is_reloading) do_reload = TRUE; RETURN_IF_ERROR(StopLoadingSpeedDial()); OpThumbnail::ThumbnailMode mode = OpThumbnail::SpeedDial; ReloadPolicy reload_policy = GetReloadPolicy(); if (Reload_UserDefined == reload_policy || Reload_PageDefined == reload_policy) mode = OpThumbnail::SpeedDialRefreshing; // If the timer stopped while all the speed dial tabs were closed and // this speed dial has reload every enabled, and this wasn't a forced // reload then we need to force a reload now if (m_need_reload && GetReloadEnabled()) do_reload = TRUE; // This is needed so that we can collect Preview-Refresh data from http header. // The value, if any, is used to automatically set reload interval. // In case the user has changed the aspect ratio, reconfigure the thumbnail manager. g_speeddial_manager->ConfigureThumbnailManager(); #ifdef PIXEL_SCALE_RENDERING_SUPPORT INT32 scale = static_cast<DesktopOpSystemInfo*>(g_op_system_info)->GetMaximumHiresScaleFactor(); PixelScaler scaler(scale); width = TO_DEVICE_PIXEL(scaler, width); height = TO_DEVICE_PIXEL(scaler, height); #endif // PIXEL_SCALE_RENDERING_SUPPORT RETURN_IF_ERROR(g_thumbnail_manager->RequestThumbnail(m_core_url, do_reload, do_reload, mode, width, height ) ); // Always make sure this is reset after a load is called m_need_reload = FALSE; return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS DesktopSpeedDial::StopLoadingSpeedDial() const { if (!m_is_loading) return OpStatus::OK; RETURN_IF_ERROR(g_thumbnail_manager->CancelThumbnail(m_core_url)); m_is_loading = FALSE; m_is_reloading = FALSE; return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool DesktopSpeedDial::HasInternalExtensionURL() const { return GetExtensionID().HasContent() && (GetURL().Find("widget://") != KNotFound ) ? true : false; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::OnThumbnailRequestStarted(const URL &document_url, BOOL reload) { // Only process the request for matching calls if (!IsMatchingCall(document_url)) return; m_is_loading = TRUE; m_is_reloading = reload; NotifySpeedDialUIChanged(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::OnThumbnailReady(const URL &document_url, const Image &thumbnail, const uni_char *title, long preview_refresh) { // Only process the request for matching calls if (!IsMatchingCall(document_url)) return; // these must be set before NotifySpeedDial*Changed() is called m_is_loading = FALSE; m_is_reloading = FALSE; // If the title has changed set the data and save to the file // This is need for any typed in entries because the title isn't retieved until the url is downloaded if (GetTitle() != title && !m_is_custom_title) { SetTitle(title, m_is_custom_title); // notifies of data change (and thus UI change) OpStatus::Ignore(g_speeddial_manager->Save()); } else { // no data changed, but still notify UI change NotifySpeedDialUIChanged(); } // The Preview-refresh value handling must be updated if the value changes m_preview_refresh = (int)preview_refresh; if (m_preview_refresh > 0 && m_reload_policy == SpeedDialData::Reload_NeverSoft && !GetReloadEnabled()) { SetReload(SpeedDialData::Reload_PageDefined, m_preview_refresh, GetReloadOnlyIfExpired()); OpStatus::Ignore(g_speeddial_manager->Save()); } else if (m_preview_refresh <= 0 && m_reload_policy == SpeedDialData::Reload_PageDefined && GetReloadEnabled()) { SetReload(SpeedDialData::Reload_NeverSoft, GetReloadTimeout(), GetReloadOnlyIfExpired()); OpStatus::Ignore(g_speeddial_manager->Save()); } else { RestartReloadTimer(document_url); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::OnThumbnailFailed(const URL &document_url, OpLoadingListener::LoadingFinishStatus status) { // Only process the request for matching calls if (!IsMatchingCall(document_url)) return; m_is_loading = FALSE; m_is_reloading = FALSE; NotifySpeedDialUIChanged(); RestartReloadTimer(document_url); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DesktopSpeedDial::OnExtensionDataUpdated(const OpStringC& title, const OpStringC& url) { bool changed = false; bool force_notification = !m_extension_data_updated; if (title != m_title) { if (m_title.IsEmpty()) { force_notification = true; } if (!m_is_custom_title && OpStatus::IsSuccess(m_title.Set(title))) { changed = true; } } else if (url != m_url) { if (m_url.IsEmpty()) { force_notification = true; } if (OpStatus::IsSuccess(m_url.Set(url))) { changed = true; } } if (changed) { // Extension can change its title and/or fallback-url very frequently, which // is not very useful and can lead to race conditions on the Link server // (if server receives updated data for extension that doesn't exist then // it will add that extension, which makes it difficult to delete extension // that constantly updates itself on some other instance of Opera). // To mitigage this OnSpeedDialDataChanged is delayed if: // - less than EXTENSION_UPDATE_INTERVAL seconds passed since last notification // - and at least EXTENSION_UPDATE_NO_DELAY_PERIOD passed since last notification. // The second condition is to ensure that if extension changes url and title at // the same time, which will result in two calls to this function, then either // both notifications are sent immediately or both are delayed. // UI notifications are always sent immediately. if (force_notification) { StopDataNotificationTimer(); } else if (!m_data_notification_timer_running) { double now = g_op_time_info->GetRuntimeMS(); if (now >= m_last_data_notification + EXTENSION_UPDATE_NO_DELAY_PERIOD && now - m_last_data_notification <= EXTENSION_UPDATE_INTERVAL) { StartDataNotificationTimer(EXTENSION_UPDATE_INTERVAL - (now - m_last_data_notification)); } } if (m_data_notification_timer_running) { NotifySpeedDialUIChanged(); } else { g_speeddial_manager->PostSaveRequest(); NotifySpeedDialDataChanged(); } m_extension_data_updated = true; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOL DesktopSpeedDial::IsMatchingCall(const URL &document_url) { // Only process the request for matching calls return !m_core_url.IsEmpty() && (m_core_url.Id() == document_url.Id()); } #endif // SUPPORT_SPEED_DIAL
// Created on: 1993-11-03 // Created by: Christian CAILLET // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IFSelect_SessionFile_HeaderFile #define _IFSelect_SessionFile_HeaderFile #include <NCollection_DataMap.hxx> #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <TColStd_SequenceOfAsciiString.hxx> #include <Standard_Integer.hxx> #include <TCollection_AsciiString.hxx> #include <Standard_CString.hxx> class IFSelect_WorkSession; class Standard_Transient; //! A SessionFile is intended to manage access between a //! WorkSession and an Ascii Form, to be considered as a Dump. //! It allows to write the File from the WorkSession, and later //! read the File to the WorkSession, by keeping required //! descriptions (such as dependances). //! //! The produced File is under an Ascii Form, then it may be //! easily consulted. //! It is possible to cumulate reading of several Files. But in //! case of Names conflict, the newer Names are forgottens. //! //! The Dump supports the description of XSTEP functionalities //! (Sharing an Interface File, with Selections, Dispatches, //! Modifiers ...) but does not refer to the Interface File //! which is currently loaded. //! //! SessionFile works with a library of SessionDumper type objects //! //! The File is Produced as follows : //! SessionFile produces all general Information (such as Int and //! Text Parameters, Types and Inputs of Selections, Dispatches, //! Modifiers ...) and calls the SessionDumpers to produce all //! the particular Data : creation arguments, parameters to be set //! It is Read in the same terms : //! SessionFile reads and interprets all general Information, //! and calls the SessionDumpers to recognize Types and for a //! recognized Type create the corresponding Object with its //! particular parameters as they were written. //! The best way to work is to have one SessionDumper for each //! consistent set of classes (e.g. a package). class IFSelect_SessionFile { public: DEFINE_STANDARD_ALLOC //! Creates a SessionFile, ready to read Files in order to load //! them into a given WorkSession. //! The following Read Operations must then be called. //! It is also possible to perform a Write, which produces a //! complete File of all the content of the WorkSession. Standard_EXPORT IFSelect_SessionFile(const Handle(IFSelect_WorkSession)& WS); //! Creates a SessionFile which Writes the content of a WorkSession //! to a File (directly calls Write) //! Then, IsDone aknowledges on the result of the Operation. //! But such a SessionFile may not Read a File to a WorkSession. Standard_EXPORT IFSelect_SessionFile(const Handle(IFSelect_WorkSession)& WS, const Standard_CString filename); //! Clears the lines recorded whatever for writing or for reading Standard_EXPORT void ClearLines(); //! Returns the count of recorded lines Standard_EXPORT Standard_Integer NbLines() const; //! Returns a line given its rank in the list of recorded lines Standard_EXPORT const TCollection_AsciiString& Line (const Standard_Integer num) const; //! Adds a line to the list of recorded lines Standard_EXPORT void AddLine (const Standard_CString line); //! Removes the last line. Can be called recursively. //! Does nothing if the list is empty Standard_EXPORT void RemoveLastLine(); //! Writes the recorded lines to a file named <name> then clears //! the list of lines. //! Returns False (with no clearing) if the file could not be //! created Standard_EXPORT Standard_Boolean WriteFile (const Standard_CString name); //! Reads the recorded lines from a file named <name>, after //! having cleared the list (stops if RecognizeFile fails) //! Returns False (with no clearing) if the file could not be read Standard_EXPORT Standard_Boolean ReadFile (const Standard_CString name); //! Recognizes the header line. returns True if OK, False else Standard_EXPORT Standard_Boolean RecognizeFile (const Standard_CString headerline); //! Performs a Write Operation from a WorkSession to a File //! i.e. calls WriteSession then WriteEnd, and WriteFile //! Returned Value is : 0 for OK, -1 File could not be created, //! >0 Error during Write (see WriteSession) //! IsDone can be called too (will return True for OK) Standard_EXPORT Standard_Integer Write (const Standard_CString filename); //! Performs a Read Operation from a file to a WorkSession //! i.e. calls ReadFile, then ReadSession and ReadEnd //! Returned Value is : 0 for OK, -1 File could not be opened, //! >0 Error during Read (see WriteSession) //! IsDone can be called too (will return True for OK) Standard_EXPORT Standard_Integer Read (const Standard_CString filename); //! Prepares the Write operation from a WorkSession (IFSelect) to //! a File, i.e. fills the list of lines (the file itself remains //! to be written; or NbLines/Line may be called) //! Important Remark : this excludes the reading of the last line, //! which is performed by WriteEnd //! Returns 0 if OK, status > 0 in case of error Standard_EXPORT Standard_Integer WriteSession(); //! Writes the trailing line. It is separate from WriteSession, //! in order to allow to redefine WriteSession without touching //! WriteEnd (WriteSession defines the body of the file) //! WriteEnd fills the list of lines. Returns a status of error, //! 0 if OK, >0 else Standard_EXPORT Standard_Integer WriteEnd(); //! Writes a line to the File. If <follow> is given, it is added //! at the following of the line. '\n' must be added for the end. Standard_EXPORT void WriteLine (const Standard_CString line, const Standard_Character follow = 0); //! Writes the Parameters own to each type of Item. Uses the //! Library of SessionDumpers //! Returns True if Done, False if <item> could not be treated //! (hence it remains written with no Own Parameter) Standard_EXPORT Standard_Boolean WriteOwn (const Handle(Standard_Transient)& item); //! Performs a Read Operation from a File to a WorkSession, i.e. //! reads the list of line (which must have already been loaded, //! by ReadFile or by calls to AddLine) //! Important Remark : this excludes the reading of the last line, //! which is performed by ReadEnd //! Returns 0 for OK, >0 status for Read Error (not a suitable //! File, or WorkSession given as Immutable at Creation Time) //! IsDone can be called too (will return True for OK) Standard_EXPORT Standard_Integer ReadSession(); //! Reads the end of a file (its last line). Returns 0 if OK, //! status >0 in case of error (not a suitable end line). Standard_EXPORT Standard_Integer ReadEnd(); //! Reads a Line and splits it into a set of alphanumeric items, //! which can then be queried by NbParams/ParamValue ... Standard_EXPORT Standard_Boolean ReadLine(); //! Internal routine which processes a line into words //! and prepares its exploration Standard_EXPORT void SplitLine (const Standard_CString line); //! Tries to Read an Item, by calling the Library of Dumpers //! Sets the list of parameters of the line to be read from the //! first own one Standard_EXPORT Standard_Boolean ReadOwn (Handle(Standard_Transient)& item); //! Adds an Item to the WorkSession, taken as Name the first //! item of the read Line. If this Name is not a Name but a Number //! or if this Name is already recorded in the WorkSession, it //! adds the Item but with no Name. Then the Name is recorded //! in order to be used by the method ItemValue //! <active> commands to make <item> active or not in the session Standard_EXPORT void AddItem (const Handle(Standard_Transient)& item, const Standard_Boolean active = Standard_True); //! Returns True if the last Read or Write operation has been correctly performed. //! Else returns False. Standard_EXPORT Standard_Boolean IsDone() const; //! Returns the WorkSession on which a SessionFile works. //! Remark that it is returned as Immutable. Standard_EXPORT Handle(IFSelect_WorkSession) WorkSession() const; //! At beginning of writing an Item, writes its basics : //! - either its name in the session if it has one //! - or its relative number of item in the file, else (preceded by a '_') //! - then, its Dynamic Type (in the sense of cdl : pk_class) //! This basic description can be followed by the parameters //! which are used in the definition of the item. Standard_EXPORT void NewItem (const Standard_Integer ident, const Handle(Standard_Transient)& par); //! Sets Parameters to be sent as Own if <mode> is True (their //! Name or Number or Void Mark or Text Value is preceded by a //! Column sign ':') else they are sent normally //! Hence, the Own Parameter are clearly identified in the File Standard_EXPORT void SetOwn (const Standard_Boolean mode); //! During a Write action, commands to send a Void Parameter //! i.e. a Parameter which is present but undefined //! Its form will be the dollar sign : $ Standard_EXPORT void SendVoid(); //! During a Write action, commands to send the identification of //! a Parameter : if it is Null (undefined) it is send as Void ($) //! if it is Named in the WorkSession, its Name is sent preceded //! by ':', else a relative Ident Number is sent preceded by '#' //! (relative to the present Write, i.e. starting at one, without //! skip, and counted part from Named Items) Standard_EXPORT void SendItem (const Handle(Standard_Transient)& par); //! During a Write action, commands to send a Text without //! interpretation. It will be sent as well Standard_EXPORT void SendText (const Standard_CString text); //! Sets the rank of Last General Parameter to a new value. It is //! followed by the Fist Own Parameter of the item. //! Used by SessionFile after reading general parameters. Standard_EXPORT void SetLastGeneral (const Standard_Integer lastgen); //! During a Read operation, SessionFile processes sequentially the Items to read. //! For each one, it gives access to the list //! of its Parameters : they were defined by calls to //! SendVoid/SendParam/SendText during Writing the File. //! NbParams returns the count of Parameters for the line //! currently read. Standard_EXPORT Standard_Integer NbParams() const; //! Returns True if a Parameter, given its rank in the Own List //! (see NbOwnParams), is Void. Returns also True if <num> is //! out of range (undefined parameters) Standard_EXPORT Standard_Boolean IsVoid (const Standard_Integer num) const; //! Returns True if a Parameter, in the Own List (see NbOwnParams) //! is a Text (between "..."). Else it is an Item (Parameter, //! Selection, Dispatch ...), which can be Void. Standard_EXPORT Standard_Boolean IsText (const Standard_Integer num) const; //! Returns a Parameter (alphanumeric item of a line) as it //! has been read Standard_EXPORT const TCollection_AsciiString& ParamValue (const Standard_Integer num) const; //! Returns the content of a Text Parameter (without the quotes). //! Returns an empty string if the Parameter is not a Text. Standard_EXPORT TCollection_AsciiString TextValue (const Standard_Integer num) const; //! Returns a Parameter as an Item. Returns a Null Handle if the //! Parameter is a Text, or if it is defined as Void Standard_EXPORT Handle(Standard_Transient) ItemValue (const Standard_Integer num) const; //! Specific Destructor (closes the File if not yet done) Standard_EXPORT void Destroy(); ~IFSelect_SessionFile() { Destroy(); } protected: Handle(IFSelect_WorkSession) thesess; Handle(TColStd_HArray1OfInteger) thenums; NCollection_DataMap<TCollection_AsciiString, Standard_Integer> thenames; Standard_Integer thenl; TColStd_SequenceOfAsciiString theline; private: Standard_Boolean themode; TColStd_SequenceOfAsciiString thelist; TCollection_AsciiString thebuff; Standard_Integer thelastgen; Standard_Boolean thedone; Standard_Boolean theownflag; Standard_Integer thenewnum; }; #endif // _IFSelect_SessionFile_HeaderFile
//--------------------------------------------------------- // // Project: dada // Module: geometry // File: Matrix3fUtils.h // Author: Viacheslav Pryshchepa // // Description: Utilities for nine-element square column aligned matrix // //--------------------------------------------------------- #ifndef DADA_GEOMETRY_MATRIX3FUTILS_H #define DADA_GEOMETRY_MATRIX3FUTILS_H namespace dada { class Matrix3f; class Vector3f; void dot(Matrix3f& res, const Matrix3f& a, const Matrix3f& b); void dot(Vector3f& res, const Matrix3f& a, const Vector3f& b); } // dada #endif // DADA_GEOMETRY_MATRIX3FUTILS_H
#pragma once namespace base64 { // must free out manual!!! int base64Decode(const unsigned char *in, unsigned int inLength, unsigned char **out); // must free out manual!!! int base64Encode(const unsigned char *in, unsigned int inLength, char **out); }
// Copyright (c) 2007-2021 Hartmut Kaiser // Copyright (c) 2017 Shoshana Jakobovits // Copyright (c) 2010-2011 Phillip LeBlanc, Dylan Stark // Copyright (c) 2011 Bryce Lelbach // // 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/assert.hpp> #include <pika/command_line_handling/command_line_handling.hpp> #include <pika/coroutines/detail/context_impl.hpp> #include <pika/detail/filesystem.hpp> #include <pika/execution/detail/execution_parameter_callbacks.hpp> #include <pika/execution_base/detail/spinlock_deadlock_detection.hpp> #include <pika/executors/exception_list.hpp> #include <pika/functional/bind_front.hpp> #include <pika/functional/function.hpp> #include <pika/futures/detail/future_data.hpp> #include <pika/init_runtime/detail/init_logging.hpp> #include <pika/init_runtime/init_runtime.hpp> #include <pika/lock_registration/detail/register_locks.hpp> #include <pika/modules/errors.hpp> #include <pika/modules/logging.hpp> #include <pika/modules/schedulers.hpp> #include <pika/modules/timing.hpp> #include <pika/program_options/parsers.hpp> #include <pika/program_options/variables_map.hpp> #include <pika/resource_partitioner/partitioner.hpp> #include <pika/runtime/config_entry.hpp> #include <pika/runtime/custom_exception_info.hpp> #include <pika/runtime/debugging.hpp> #include <pika/runtime/get_locality_id.hpp> #include <pika/runtime/runtime.hpp> #include <pika/runtime/runtime_handlers.hpp> #include <pika/runtime/shutdown_function.hpp> #include <pika/runtime/startup_function.hpp> #include <pika/string_util/classification.hpp> #include <pika/string_util/split.hpp> #include <pika/threading/thread.hpp> #include <pika/type_support/pack.hpp> #include <pika/type_support/unused.hpp> #include <pika/util/get_entry_as.hpp> #include <pika/version.hpp> #if defined(PIKA_HAVE_HIP) # include <hip/hip_runtime.h> # include <whip.hpp> #endif #if defined(__bgq__) # include <cstdlib> #endif #include <cmath> #include <cstddef> #include <exception> #include <functional> #include <iostream> #include <map> #include <memory> #include <new> #include <sstream> #include <string> #include <utility> #include <vector> #if !defined(PIKA_WINDOWS) # include <signal.h> #endif namespace pika { namespace detail { int init_helper(pika::program_options::variables_map& /*vm*/, util::detail::function<int(int, char**)> const& f) { std::string cmdline(pika::get_config_entry("pika.reconstructed_cmd_line", "")); using namespace pika::program_options; #if defined(PIKA_WINDOWS) std::vector<std::string> args = split_winmain(cmdline); #else std::vector<std::string> args = split_unix(cmdline); #endif // Copy all arguments which are not pika related to a temporary array std::vector<char*> argv(args.size() + 1); std::size_t argcount = 0; for (std::size_t i = 0; i != args.size(); ++i) { if (0 != args[i].find("--pika:")) { argv[argcount++] = const_cast<char*>(args[i].data()); } else if (7 == args[i].find("positional", 7)) { std::string::size_type p = args[i].find_first_of('='); if (p != std::string::npos) { args[i] = args[i].substr(p + 1); argv[argcount++] = const_cast<char*>(args[i].data()); } } } // add a single nullptr in the end as some application rely on that argv[argcount] = nullptr; // Invoke custom startup functions return f(static_cast<int>(argcount), argv.data()); } } // namespace detail // Print stack trace and exit. int init(std::function<int(pika::program_options::variables_map&)> f, int argc, const char* const* argv, init_params const& params) { return detail::init_start_impl(PIKA_MOVE(f), argc, argv, params, true); } int init(std::function<int(int, char**)> f, int argc, const char* const* argv, init_params const& params) { util::detail::function<int(pika::program_options::variables_map&)> main_f = pika::util::detail::bind_back(pika::detail::init_helper, f); return detail::init_start_impl(PIKA_MOVE(main_f), argc, argv, params, true); } int init(std::function<int()> f, int argc, const char* const* argv, init_params const& params) { util::detail::function<int(pika::program_options::variables_map&)> main_f = pika::util::detail::bind(f); return detail::init_start_impl(PIKA_MOVE(main_f), argc, argv, params, true); } int init(std::nullptr_t, int argc, const char* const* argv, init_params const& params) { util::detail::function<int(pika::program_options::variables_map&)> main_f; return detail::init_start_impl(PIKA_MOVE(main_f), argc, argv, params, true); } bool start(std::function<int(pika::program_options::variables_map&)> f, int argc, const char* const* argv, init_params const& params) { return 0 == detail::init_start_impl(PIKA_MOVE(f), argc, argv, params, false); } bool start(std::function<int(int, char**)> f, int argc, const char* const* argv, init_params const& params) { util::detail::function<int(pika::program_options::variables_map&)> main_f = pika::util::detail::bind_back(pika::detail::init_helper, f); return 0 == detail::init_start_impl(PIKA_MOVE(main_f), argc, argv, params, false); } bool start(std::function<int()> f, int argc, const char* const* argv, init_params const& params) { util::detail::function<int(pika::program_options::variables_map&)> main_f = pika::util::detail::bind(f); return 0 == detail::init_start_impl(PIKA_MOVE(main_f), argc, argv, params, false); } bool start(std::nullptr_t, int argc, const char* const* argv, init_params const& params) { util::detail::function<int(pika::program_options::variables_map&)> main_f; return 0 == detail::init_start_impl(PIKA_MOVE(main_f), argc, argv, params, false); } int finalize(error_code& ec) { if (!is_running()) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::finalize", "the runtime system is not active (did you already call finalize?)"); return -1; } if (&ec != &throws) ec = make_success_code(); runtime* rt = get_runtime_ptr(); if (nullptr == rt) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::finalize", "the runtime system is not active (did you already call pika::stop?)"); return -1; } rt->finalize(); return 0; } int stop(error_code& ec) { if (threads::detail::get_self_ptr()) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::stop", "this function cannot be called from a pika thread"); return -1; } std::unique_ptr<runtime> rt(get_runtime_ptr()); // take ownership! if (nullptr == rt.get()) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::stop", "the runtime system is not active (did you already call pika::stop?)"); return -1; } int result = rt->wait(); rt->stop(); rt->rethrow_exception(); return result; } int wait(error_code& ec) { runtime* rt = get_runtime_ptr(); if (nullptr == rt) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::wait", "the runtime system is not active (did you already call pika::stop?)"); return -1; } rt->get_thread_manager().wait(); return 0; } int suspend(error_code& ec) { if (threads::detail::get_self_ptr()) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::suspend", "this function cannot be called from a pika thread"); return -1; } runtime* rt = get_runtime_ptr(); if (nullptr == rt) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::suspend", "the runtime system is not active (did you already call pika::stop?)"); return -1; } return rt->suspend(); } int resume(error_code& ec) { if (threads::detail::get_self_ptr()) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::resume", "this function cannot be called from a pika thread"); return -1; } runtime* rt = get_runtime_ptr(); if (nullptr == rt) { PIKA_THROWS_IF(ec, pika::error::invalid_status, "pika::resume", "the runtime system is not active (did you already call pika::stop?)"); return -1; } return rt->resume(); } namespace detail { void activate_global_options(detail::command_line_handling& cmdline) { #if defined(__linux) || defined(linux) || defined(__linux__) || defined(__FreeBSD__) threads::coroutines::detail::posix::use_guard_pages = cmdline.rtcfg_.use_stack_guard_pages(); #endif #ifdef PIKA_HAVE_VERIFY_LOCKS if (cmdline.rtcfg_.enable_lock_detection()) { util::enable_lock_detection(); util::trace_depth_lock_detection(cmdline.rtcfg_.trace_depth()); } else { util::disable_lock_detection(); } #endif #ifdef PIKA_HAVE_THREAD_DEADLOCK_DETECTION threads::detail::set_deadlock_detection_enabled( cmdline.rtcfg_.enable_deadlock_detection()); #endif #ifdef PIKA_HAVE_SPINLOCK_DEADLOCK_DETECTION util::detail::set_spinlock_break_on_deadlock_enabled( cmdline.rtcfg_.enable_spinlock_deadlock_detection()); util::detail::set_spinlock_deadlock_detection_limit( cmdline.rtcfg_.get_spinlock_deadlock_detection_limit()); util::detail::set_spinlock_deadlock_warning_limit( cmdline.rtcfg_.get_spinlock_deadlock_warning_limit()); #endif #if defined(PIKA_HAVE_LOGGING) init_logging_local(cmdline.rtcfg_); #else warn_if_logging_requested(cmdline.rtcfg_); #endif } /////////////////////////////////////////////////////////////////////// void add_startup_functions(pika::runtime& rt, pika::program_options::variables_map& vm, startup_function_type startup, shutdown_function_type shutdown) { if (vm.count("pika:app-config")) { std::string config(vm["pika:app-config"].as<std::string>()); rt.get_config().load_application_configuration(config.c_str()); } if (!!startup) rt.add_startup_function(PIKA_MOVE(startup)); if (!!shutdown) rt.add_shutdown_function(PIKA_MOVE(shutdown)); if (vm.count("pika:dump-config-initial")) { std::cout << "Configuration after runtime construction:\n"; std::cout << "-----------------------------------------\n"; rt.get_config().dump(0, std::cout); std::cout << "-----------------------------------------\n"; } if (vm.count("pika:dump-config")) rt.add_startup_function(dump_config(rt)); } /////////////////////////////////////////////////////////////////////// int run(pika::runtime& rt, util::detail::function<int(pika::program_options::variables_map& vm)> const& f, pika::program_options::variables_map& vm, startup_function_type startup, shutdown_function_type shutdown) { LPROGRESS_; add_startup_functions(rt, vm, PIKA_MOVE(startup), PIKA_MOVE(shutdown)); // Run this runtime instance using the given function f. if (!f.empty()) return rt.run(util::detail::bind_front(f, vm)); // Run this runtime instance without a pika_main return rt.run(); } int start(pika::runtime& rt, util::detail::function<int(pika::program_options::variables_map& vm)> const& f, pika::program_options::variables_map& vm, startup_function_type startup, shutdown_function_type shutdown) { LPROGRESS_; add_startup_functions(rt, vm, PIKA_MOVE(startup), PIKA_MOVE(shutdown)); if (!f.empty()) { // Run this runtime instance using the given function f. return rt.start(util::detail::bind_front(f, vm)); } // Run this runtime instance without a pika_main return rt.start(); } int run_or_start(bool blocking, std::unique_ptr<pika::runtime> rt, detail::command_line_handling& cfg, startup_function_type startup, shutdown_function_type shutdown) { if (blocking) { return run(*rt, cfg.pika_main_f_, cfg.vm_, PIKA_MOVE(startup), PIKA_MOVE(shutdown)); } // non-blocking version start(*rt, cfg.pika_main_f_, cfg.vm_, PIKA_MOVE(startup), PIKA_MOVE(shutdown)); // pointer to runtime is stored in TLS pika::runtime* p = rt.release(); (void) p; return 0; } //////////////////////////////////////////////////////////////////////// void init_environment(detail::command_line_handling& cmdline) { PIKA_UNUSED(pika::detail::filesystem::initial_path()); pika::detail::set_assertion_handler(&pika::detail::assertion_handler); pika::detail::set_custom_exception_info_handler(&pika::detail::custom_exception_info); pika::detail::set_pre_exception_handler(&pika::detail::pre_exception_handler); pika::set_thread_termination_handler( [](std::exception_ptr const& e) { report_error(e); }); pika::lcos::detail::set_run_on_completed_error_handler([](std::exception_ptr const& e) { pika::detail::report_exception_and_terminate(e); }); pika::detail::set_get_full_build_string(&pika::full_build_string); #if defined(PIKA_HAVE_VERIFY_LOCKS) pika::util::set_registered_locks_error_handler( &pika::detail::registered_locks_error_handler); pika::util::set_register_locks_predicate(&pika::detail::register_locks_predicate); #endif #if !defined(PIKA_HAVE_DISABLED_SIGNAL_EXCEPTION_HANDLERS) if (pika::detail::get_entry_as<bool>( cmdline.rtcfg_, "pika.install_signal_handlers", false)) { set_signal_handlers(); } #endif pika::threads::detail::set_get_default_pool(&pika::detail::get_default_pool); pika::threads::detail::set_get_locality_id(&get_locality_id); pika::parallel::execution::detail::set_get_pu_mask(&pika::detail::get_pu_mask); pika::parallel::execution::detail::set_get_os_thread_count( []() { return pika::get_os_thread_count(); }); #if defined(__bgq__) || defined(__bgqion__) unsetenv("LANG"); unsetenv("LC_CTYPE"); unsetenv("LC_NUMERIC"); unsetenv("LC_TIME"); unsetenv("LC_COLLATE"); unsetenv("LC_MONETARY"); unsetenv("LC_MESSAGES"); unsetenv("LC_PAPER"); unsetenv("LC_NAME"); unsetenv("LC_ADDRESS"); unsetenv("LC_TELEPHONE"); unsetenv("LC_MEASUREMENT"); unsetenv("LC_IDENTIFICATION"); unsetenv("LC_ALL"); #endif } // make sure the runtime system is not active yet int ensure_no_runtime_is_up() { // make sure the runtime system is not active yet if (get_runtime_ptr() != nullptr) { std::cerr << "pika::init: can't initialize runtime system more than once! Exiting...\n"; return -1; } return 0; } /////////////////////////////////////////////////////////////////////// int run_or_start( util::detail::function<int(pika::program_options::variables_map& vm)> const& f, int argc, const char* const* argv, init_params const& params, bool blocking) { int result = 0; try { if ((result = ensure_no_runtime_is_up()) != 0) { return result; } pika::detail::command_line_handling cmdline{ pika::util::runtime_configuration(argv[0]), params.cfg, f}; // scope exception handling to resource partitioner initialization // any exception thrown during run_or_start below are handled // separately try { result = cmdline.call(params.desc_cmdline, argc, argv); pika::detail::affinity_data affinity_data{}; affinity_data.init(pika::detail::get_entry_as<std::size_t>( cmdline.rtcfg_, "pika.os_threads", 0), pika::detail::get_entry_as<std::size_t>(cmdline.rtcfg_, "pika.cores", 0), pika::detail::get_entry_as<std::size_t>( cmdline.rtcfg_, "pika.pu_offset", 0), pika::detail::get_entry_as<std::size_t>(cmdline.rtcfg_, "pika.pu_step", 0), 0, cmdline.rtcfg_.get_entry("pika.affinity", ""), cmdline.rtcfg_.get_entry("pika.bind", ""), !pika::detail::get_entry_as<bool>( cmdline.rtcfg_, "pika.ignore_process_mask", false)); pika::resource::partitioner rp = pika::resource::detail::make_partitioner( params.rp_mode, cmdline.rtcfg_, affinity_data); activate_global_options(cmdline); init_environment(cmdline); // check whether pika should be exited at this point // (parse_result is returning a result > 0, if the program options // contain --pika:help or --pika:version, on error result is < 0) if (result != 0) { if (result > 0) result = 0; return result; } // If thread_pools initialization in user main if (params.rp_callback) { params.rp_callback(rp, cmdline.vm_); } // Setup all internal parameters of the resource_partitioner rp.configure_pools(); } catch (pika::exception const& e) { std::cerr << "pika::init: pika::exception caught: " << pika::get_error_what(e) << "\n"; return -1; } #if defined(PIKA_HAVE_HIP) LPROGRESS_ << "run_local: initialize HIP"; whip::check_error(hipInit(0)); #endif // Initialize and start the pika runtime. LPROGRESS_ << "run_local: create runtime"; // Build and configure this runtime instance. std::unique_ptr<pika::runtime> rt; // Command line handling should have updated this by now. LPROGRESS_ << "creating local runtime"; rt.reset(new pika::runtime(cmdline.rtcfg_, true)); result = run_or_start(blocking, PIKA_MOVE(rt), cmdline, PIKA_MOVE(params.startup), PIKA_MOVE(params.shutdown)); } catch (pika::detail::command_line_error const& e) { std::cerr << "pika::init: std::exception caught: " << e.what() << "\n"; return -1; } return result; } } // namespace detail } // namespace pika
#include <iostream> #include <vector> #include <conio.h> #include <fstream> #include "Facebook.h" using namespace std; // prototype void DisplayMenu(void); int getOption(void); void import(Facebook& BookOfLife); void exportFile(Facebook& BookOfLife); int main() { Facebook BookOfLife; import (BookOfLife); while (true) { DisplayMenu(); int option = getOption(); if (option == 1) { BookOfLife.signIn(); } else if (option == 2) { BookOfLife.signUp(); } else if (option == 3) { exportFile(BookOfLife); return 0; } } } /* Main Function */ void DisplayMenu(void) { cout << "\n-----------------------------------\n" << "Welcome to Facebook (Changing Lives)\n\n" << "1. Sign in\n" << "2. Sign up\n" << "3. Exit\n" << "-----------------------------------\n\n"; } int getOption(void) { int temp; cin >> temp; return temp; } ostream& operator <<(ostream& outs, const Person& temp) { outs << "\nName = " << temp.Name << "\nUsername = " << temp.username << "\nAge = " << temp.Age; return outs; } bool isFriend(Person& temp1, Person& temp2) { for (int i = 0; i < temp1.friends.size(); i++) { if (temp2.getUsername() == temp1.friends[i].getUsername()) { return true; } } return false; } void mutualFriends(Person& temp1, Person& temp2) { for (int i = 0; i < temp1.friends.size(); i++ ) { if (isFriend(temp2, temp1.friends[i])) { cout << temp1.friends[i] << endl << endl; } } return; } void import(Facebook& BookOfLife) { ifstream file_members; file_members.open("members.txt"); int i = 0; while (!file_members.eof()) { Person temp; string line; int age; bool is_ad; file_members >> line; temp.setName(line); file_members >> line; temp.setUsername(line); file_members >> line; temp.setPassword(line); file_members >> age; temp.setAge(age); file_members >> is_ad; temp.setisAdmin(is_ad); BookOfLife.members.push_back(temp); i++; } file_members.close(); ifstream file_friends; file_friends.open("friends.txt"); int j = 0; string line; file_friends >> line; while (!file_friends.eof()) { string user = line; file_friends >> line; while (line != "*") { Person temp = BookOfLife.getPerson(line); BookOfLife.members[j].friends.push_back(temp); file_friends >> line; } j++; file_friends >> line; } file_friends.close(); } void exportFile(Facebook& BookOfLife) { ofstream file_members; file_members.open("members.txt"); for (int i = 0; i < BookOfLife.members.size(); i++) { file_members << BookOfLife.members[i].getName() << endl; file_members << BookOfLife.members[i].getUsername() << endl; file_members << BookOfLife.members[i].getPassword() << endl; file_members << BookOfLife.members[i].getAge() << endl; file_members << BookOfLife.members[i].getisAdmin() << endl; file_members << endl; } file_members.close(); ofstream file_friends; file_friends.open("friends.txt"); for (int i = 0; i < BookOfLife.members.size(); i++) { file_friends << BookOfLife.members[i].getUsername() << endl; for (int j = 0; j < BookOfLife.members[i].friends.size(); j++) { file_friends << BookOfLife.members[i].friends[j].getUsername() << endl; } file_friends << "*" << endl; } file_friends.close(); } /* Person's Class Member Functions */ Person::Person() { } Person::Person(string n, string user, string pass, int age) { Name = n; username = user; password = pass; isAdmin = false; Age = age; } void Person::setName(string n) { Name = n; return; } void Person::setPassword(string pass) { password = pass; return; } void Person::setUsername(string user) { username = user; } void Person::setisAdmin(bool is_ad) { isAdmin = is_ad; return; } void Person::setAge(int a) { Age = a; return; } string Person::getName() { return Name; } string Person::getPassword() { return password; } string Person::getUsername() { return username; } bool Person::getisAdmin() { return isAdmin; } int Person::getAge() { return Age; } void Person::viewAllFriends(void) { for (int i = 0; i < friends.size(); i++) { cout << friends[i] << endl; } return; } void Facebook::addAFriend(Person& _person) { string user; bool isMember = false; cout << "\nUsername : "; cin >> user; int temp = isAMember(user); if (temp != -1 && members[temp].getUsername() != _person.getUsername()) { for (int i = 0; i < members[temp].friendRequestSent.size(); i++) { if (_person.getUsername() == members[temp].friendRequestSent[i].getUsername()) { _person.friends.push_back(members[temp]); members[temp].friends.push_back(_person); members[temp].friendRequestSent.erase(members[temp].friendRequestSent.begin() + i); cout << "\nFriend Added!\n\n"; isMember = true; } } if (isMember == false) { _person.friendRequestSent.push_back(members[temp]); cout << "\nFriend Request Sent\n\n"; } return; } else { cout << "\nMember Not Found!\n"; return; } } void Facebook::viewAFriend(Person& temp) { string user; bool isMember = false; cout << "\nUsername : "; cin >> user; for (int i = 0; i < temp.friends.size(); i++) { if (user == temp.friends[i].getUsername()) { cout << temp.friends[i] << endl; cout << "\nMutual Friends\n\n"; mutualFriends(temp, temp.friends[i]); cout << "\n\nFriends\n\n"; temp.friends[i].viewAllFriends(); isMember = true; break; } } if (isMember == false) { cout << "\nFriend Not Found!\n\n"; } return; } void Person::viewFriendRequestsSent(void) { for (int i = 0; i < friendRequestSent.size(); i++) { cout << friendRequestSent[i] << endl << endl; } return; } /* Facebook's Class Member Functions */ Facebook::Facebook() { } void Facebook::signIn(void) { //clrscr(); string user; string pass; cout << "\n*******************\n" << "Login Screen\n" << "*******************\n\n"; cout << "\nUsername : "; cin >> user; cout << "Password : "; cin >> pass; if (user == "admin" && pass == "rider007") { adminMenu(); return; } for (int i = 0; i < members.size(); i++) { if (members[i].getUsername() == user && members[i].getPassword() == pass) { if (members[i].getisAdmin() == true) { adminMenu(members[i]); return; } else { userMenu(members[i]); return; } break; } } cout << "\nUsername or Password is invalid\n"; return; } void Facebook::signUp(void) { //clrscr(); string name; string user; string pass; int age; bool isUnique = true; cout << "\n*******************\n" << "SignUp Screen\n" << "*******************\n\n"; do { cout << "\nName : "; cin >> name; cout << "Username : "; cin >> user; cout << "Password : "; cin >> pass; cout << "Age : "; cin >> age; for (int i = 0; i < members.size(); i++) { if (members[i].getUsername() == user) { isUnique = false; cout << "\n\n Username Already Exists \n\n"; break; } } } while (isUnique == false); Person temp(name, user, pass, age); members.push_back(temp); return; } void Facebook::adminMenu(void) { cout << "\n*******************\n" << "Admin Area\n" << "*******************\n\n"; while (true) { cout << "\n1. View All Member\n" << "2. Delete A Member\n" << "3. Make Another Admin\n" << "4. Logout\n\n"; int option; cin >> option; if (option == 1) { viewAllMembers(); } else if (option == 2) { deleteMember(); } else if (option == 3) { makeAdmin(); } else if (option == 4) { return; } else { cout << "\nInvalid Option\n\n"; } } } void Facebook::adminMenu(Person& temp) { cout << "\n*******************\n" << "Welcome " << temp.getName() << " | Admin Area\n" << "*******************\n\n"; while (true) { cout << "\n1. View All Member\n" << "2. Delete A Member\n" << "3. Make Another Admin\n" << "4. View All Friends\n" << "5. Add A Friend\n" << "6. View A Friend\n" << "7. View Friend Requests Sent\n" << "8. Logout\n\n"; int option; cin >> option; if (option == 1) { viewAllMembers(); } else if (option == 2) { deleteMember(); } else if (option == 3) { makeAdmin(); } else if (option == 4) { temp.viewAllFriends(); } else if (option == 5) { addAFriend(temp); } else if (option == 6) { viewAFriend(temp); } else if (option == 7) { temp.viewFriendRequestsSent(); } else if (option == 8) { return; } else { cout << "\nInvalid Option\n\n"; } } } void Facebook::userMenu(Person& temp) { cout << "\n*******************\n" << "Welcome " << temp.getName() << endl << "*******************\n\n"; while (true) { cout << "\n1. View All Friends\n" << "2. Add A Friend\n" << "3. View A Friend\n" << "4. View Friend Requests Sent\n" << "5. View All Members on the Book Of Life\n" << "6. Logout\n\n"; int option; cin >> option; if (option == 1) { temp.viewAllFriends(); } else if (option == 2) { addAFriend(temp); } else if (option == 3) { viewAFriend(temp); } else if (option == 4) { temp.viewFriendRequestsSent(); } else if (option == 5) { viewAllMembers(); } else if (option == 6) { return; } else { cout << "\nInvalid Option\n\n"; } } } void Facebook::viewAllMembers(void) { for (int i = 0; i < members.size(); i++) { cout << members[i] << endl << endl; } return; } void Facebook::deleteMember(void) { string user; bool isMember = false; cout << "\nUsername : "; cin >> user; for (int i = 0; i < members.size(); i++) { if (members[i].getUsername() == user) { members.erase(members.begin() + i); isMember = true; break; } } if (isMember == false) { cout << "\nMember Not Found!\n\n"; } return; } void Facebook::makeAdmin(void) { string user; bool isMember = false; cout << "\nUsername : "; cin >> user; for (int i = 0; i < members.size(); i++) { if (members[i].getUsername() == user) { members[i].setisAdmin(true); isMember = true; break; } } if (isMember == false) { cout << "\nMember Not Found!\n\n"; } return; } int Facebook::isAMember(string username) { for (int i = 0; i < members.size(); i++) { if (members[i].getUsername() == username) { return i; break; } } return -1; } Person Facebook::getPerson(string user) { for (int i = 0; i < members.size(); i++) { if (members[i].getUsername() == user) { return members[i]; } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2009 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #ifdef FORMATS_DATAFILE_ENABLED #include "modules/formats/url_dfr.h" DataFile::DataFile(OpFileDescriptor *file_p) : DataStream_GenericFile(file_p, FALSE) { file_version = 0; app_version = 0; } DataFile::DataFile(OpFileDescriptor *file_p, uint32 app_ver, uint16 taglen, uint16 lenlen) : DataStream_GenericFile(file_p, TRUE) { file_version = DATA_FILE_CURRENT_VERSION; app_version = app_ver; spec.idtag_len = taglen; spec.tag_big_endian = TRUE; spec.tag_MSB_detection = TRUE; spec.length_len = lenlen; spec.length_big_endian = TRUE; } DataFile::~DataFile() { } void DataFile::PerformActionL(DataStream::DatastreamAction action, uint32 arg1, uint32 arg2) { switch(action) { case DataStream::KInternal_InitRead: { OP_STATUS op_err; uint32 temp_int; op_err = ReadIntegerL(this,file_version, 4, TRUE, FALSE); if(op_err == OpRecStatus::FINISHED) { op_err = ReadIntegerL(this,app_version, 4, TRUE, FALSE); if(op_err == OpRecStatus::FINISHED) { op_err = ReadIntegerL(this, temp_int, 2, TRUE, FALSE); if(op_err == OpRecStatus::FINISHED) { spec.idtag_len = (uint16) temp_int; op_err = ReadIntegerL(this, temp_int , 2, TRUE, FALSE); if(op_err == OpRecStatus::FINISHED) { spec.length_len = (uint16) temp_int; if (!spec.idtag_len && !spec.length_len) op_err = OpRecStatus::ILLEGAL_FORMAT; } } } } if(op_err != OpRecStatus::FINISHED) { ErrorClose(); if(!OpRecStatus::IsError(op_err)) op_err = OpRecStatus::ERR; LEAVE(op_err); } break; } case DataStream::KInternal_InitWrite: WriteIntegerL(file_version, 4, TRUE, FALSE, this); WriteIntegerL(app_version, 4, TRUE, FALSE, this); WriteIntegerL(spec.idtag_len, 2, TRUE, FALSE, this); WriteIntegerL(spec.length_len, 2, TRUE, FALSE, this); break; default: DataStream_GenericFile::PerformActionL(action, arg1, arg2); } } const DataRecord_Spec *DataFile::GetRecordSpec() { return &spec; } DataStream *DataFile::CreateRecordL() { DataFile_Record *rec = OP_NEW_L(DataFile_Record, ()); rec->SetRecordSpec(GetRecordSpec()); return rec; } DataFile_Record::DataFile_Record() { } DataFile_Record::DataFile_Record(uint32 _tag) { SetTag(_tag); } DataFile_Record::~DataFile_Record() { } DataStream *DataFile_Record::CreateRecordL() { DataFile_Record *rec = OP_NEW_L(DataFile_Record, ()); rec->SetRecordSpec(GetRecordSpec()); return rec; } void DataFile_Record::PerformActionL(DataStream::DatastreamAction action, uint32 arg1, uint32 arg2) { DataStream_GenericRecord_Large::PerformActionL(action, arg1, arg2); if(action == DataStream::KSetTag && (arg1 & MSB_VALUE) != 0) UsePayload(FALSE); } /* void DataFile_Record::AddContentL(const char *src) { DataStream_GenericRecord_Large::AddContentL(src); } void DataFile_Record::AddContentL(OpStringC8 &src) { DataStream_GenericRecord_Large::AddContentL(src); } void DataFile_Record::AddContentL(uint8 src) { AddContentL(&src, 1); } void DataFile_Record::AddContentL(uint16 src) { WriteIntegerL(src, 2, spec.numbers_big_endian, FALSE, this); } void DataFile_Record::AddContentL(uint32 src) { WriteIntegerL(src, 4, spec.numbers_big_endian, FALSE, this); } char *DataFile_Record::GetStringL() { return DataStream_GenericRecord_Large::GetStringL(); } void DataFile_Record::GetStringL(OpStringS8 &string) { DataStream_GenericRecord_Large::GetStringL(string); } */ #if 0 uint8 DataFile_Record::GetUInt8L() { uint8 buf=0; ReadDataL((byte *) &buf, 1); return buf; } uint16 DataFile_Record::GetUInt16L() { uint32 buf=0; ReadIntegerL(this,buf, 2, spec.numbers_big_endian, FALSE); return (uint16) buf; } #endif /* uint32 DataFile_Record::GetUInt32L(BOOL handle_oversized) { uint32 buf=0; ReadIntegerL(this,buf, (handle_oversized && spec.numbers_big_endian ? GetLength() : 4), spec.numbers_big_endian, FALSE); return (uint32) buf; } */ #if 0 int8 DataFile_Record::GetInt8L() { uint8 buf=0; ReadDataL((byte *) &buf, 1); return (int8) buf; } int16 DataFile_Record::GetInt16L() { uint32 buf=0; ReadIntegerL(this,buf, 2, spec.numbers_big_endian, FALSE); return (int16) buf; } #endif int32 DataFile_Record::GetInt32L() { uint32 buf=0; ReadIntegerL(this,buf, 4, spec.numbers_big_endian, FALSE); return (int32) buf; } #if 0 char *DataFile_Record::GetIndexedRecordStringL(uint32 _tag) { DataFile_Record *rec = GetIndexedRecord(_tag); if(!rec) return NULL; rec->ResetRead(); return rec->GetStringL(); } #endif void DataFile_Record::GetIndexedRecordStringL(uint32 _tag, OpStringS8 &string) { string.Empty(); DataFile_Record *rec = GetIndexedRecord(_tag); if(!rec) return; rec->ResetRead(); rec->GetStringL(string); } BOOL DataFile_Record::GetIndexedRecordBOOL(uint32 _tag) { DataFile_Record *rec = GetIndexedRecord(_tag); return (rec ? TRUE : FALSE); } unsigned long DataFile_Record::GetIndexedRecordUIntL(uint32 _tag) { DataFile_Record *rec = GetIndexedRecord(_tag); if(!rec) return 0; rec->ResetRead(); return rec->GetUInt32L(TRUE); } OpFileLength DataFile_Record::GetIndexedRecordUInt64L(uint32 _tag) { DataFile_Record *rec = GetIndexedRecord(_tag); if(!rec) return 0; rec->ResetRead(); return rec->GetUInt64L(TRUE); } long DataFile_Record::GetIndexedRecordIntL(uint32 _tag) { DataFile_Record *rec = GetIndexedRecord(_tag); if(!rec) return 0; rec->ResetRead(); return rec->GetInt32L(); } void DataFile_Record::AddRecordL(uint32 tag, const OpStringC8 &src) { #if 0 DataFile_Record temp_record(tag); ANCHOR(DataFile_Record, temp_record); temp_record.SetRecordSpec(GetRecordSpec()); temp_record.AddContentL(src); temp_record.WriteRecordL(this); #else if(spec.enable_tag) WriteIntegerL(tag, spec.idtag_len, spec.tag_big_endian, spec.tag_MSB_detection, this); uint32 len = src.Length(); if(spec.enable_length) WriteIntegerL(len, spec.length_len, spec.length_big_endian, FALSE, this); if(len) AddContentL((const unsigned char *) src.CStr(), len); #endif } void DataFile_Record::AddRecordL(uint32 tag, uint32 value) { #if 0 DataFile_Record temp_record(tag); ANCHOR(DataFile_Record, temp_record); temp_record.SetRecordSpec(GetRecordSpec()); temp_record.AddContentL(value); temp_record.WriteRecordL(this); #else if(spec.enable_tag) WriteIntegerL(tag, spec.idtag_len, spec.tag_big_endian, spec.tag_MSB_detection, this); if(spec.enable_length) WriteIntegerL(4, spec.length_len, spec.length_big_endian, FALSE, this); WriteIntegerL(value, 4, spec.numbers_big_endian, FALSE, this); #endif } void DataFile_Record::AddRecord64L(uint32 tag, OpFileLength value) { if(spec.enable_tag) WriteIntegerL(tag, spec.idtag_len, spec.tag_big_endian, spec.tag_MSB_detection, this); if(spec.enable_length) WriteIntegerL(8, spec.length_len, spec.length_big_endian, FALSE, this); WriteInteger64L(value, 8, spec.numbers_big_endian, FALSE, this); } /* OP_STATUS DataFile_Record::AddRecordL(uint32 tag, uint16 value) { DataFile_Record temp_record(tag); ANCHOR(DataFile_Record, temp_record); temp_record.SetRecordSpec(GetRecordSpec()); temp_record.AddContentL(value); return AddContentL(&temp_record); } OP_STATUS DataFile_Record::AddRecordL(uint32 tag, uint8 value) { DataFile_Record temp_record(tag); ANCHOR(DataFile_Record, temp_record); temp_record.SetRecordSpec(GetRecordSpec()); temp_record.AddContentL(value); return AddContentL(&temp_record); } */ void DataFile_Record::AddRecordL(uint32 tag) { #if 0 DataFile_Record temp_record(tag); ANCHOR(DataFile_Record, temp_record); temp_record.SetRecordSpec(GetRecordSpec()); temp_record.WriteRecordL(this); #else if(spec.enable_tag) WriteIntegerL(tag, spec.idtag_len, spec.tag_big_endian, spec.tag_MSB_detection, this); if((!spec.tag_MSB_detection && spec.enable_length) || (spec.tag_MSB_detection && (tag & MSB_VALUE) == 0) ) WriteIntegerL(0, spec.length_len, spec.length_big_endian, FALSE, this); #endif } #ifdef _DATASTREAM_DEBUG_ const char *DataFile::Debug_ClassName() { return "DataFile"; } const char *DataFile_Record::Debug_ClassName() { return "DataFile_Record"; } #endif #endif // FORMATS_DATAFILE_ENABLED
// Fri Apr 29 11:54:22 EDT 2016 // Evan S Weinberg // C++ file for BiCGStab inverter. // To do: // 1. Template to support float, double. #include <iostream> #include <cmath> #include <string> #include <sstream> #include <complex> #include "generic_traits.h" #include "generic_vector.h" #include "generic_bicgstab.h" using namespace std; // Solves lhs = A^(-1) rhs using bicgstab inversion_info minv_vector_bicgstab(double *phi, double *phi0, int size, int max_iter, double eps, void (*matrix_vector)(double*,double*,void*), void* extra_info, inversion_verbose_struct* verb) { // BICGSTAB solutions to Mphi = b // see www.mcs.anl.gov/papers/P3039-0912.pdf // "Analysis and Practical Use of Flexible BiCGStab // Initialize vectors. double *r, *r0, *p, *Ap, *s, *As; double rho, rhoNew, alpha, beta, omega; double rsq, bsqrt, truersq; int k,i; inversion_info invif; // Allocate memory. r = new double[size]; r0 = new double[size]; p = new double[size]; Ap = new double[size]; s = new double[size]; As = new double[size]; // Zero vectors. zero<double>(r, size); zero<double>(r0, size); zero<double>(p, size); zero<double>(Ap, size); zero<double>(s, size); zero<double>(As, size); // Initialize values. rsq = 0.0; bsqrt = 0.0; truersq = 0.0; // Find norm of rhs. bsqrt = sqrt(norm2sq<double>(phi0, size)); // 1. r = b - Ax. , r0 = arbitrary (use r). // Take advantage of initial guess in phi. (*matrix_vector)(Ap, phi, extra_info); invif.ops_count++; for(i = 0; i<size; i++) { r[i] = phi0[i] - Ap[i]; // 1. r0 = b-Ax0 } copy<double>(r0, r, size); // 2. p = r copy<double>(p, r, size); // 2a. Initialize rho = <r, r0>. rho = dot<double>(r0, r, size); // 2b. Initialize Ap. (*matrix_vector)(Ap, p, extra_info); invif.ops_count++; // 3. iterate till convergence for(k = 0; k< max_iter; k++) { // 4. alpha = <r0, r>/<r0, Ap> alpha = rho/dot<double>(r0, Ap, size); // 5. s = r - alpha Ap for (i = 0; i < size; i++) { s[i] = r[i] - alpha*Ap[i]; } // 6. Compute As, w = <s, As>/(As, As) (*matrix_vector)(As, s, extra_info); invif.ops_count++; omega = dot<double>(As, s, size)/dot<double>(As, As, size); // 7. Update phi = phi + alpha*p + omega*s for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i] + omega*s[i]; } // 8. Update r = s - omega*As for (i = 0; i < size; i++) { r[i] = s[i] - omega*As[i]; } // 8a. If ||r|| is sufficiently small, quit. rsq = norm2sq<double>(r, size); print_verbosity_resid(verb, "BiCGStab", k+1, invif.ops_count, sqrt(rsq)/bsqrt); if (sqrt(rsq) < eps*bsqrt || k ==max_iter-1) { break; } // 9. rhoNew = <r0, r>. rhoNew = dot<double>(r0, r, size); beta = rhoNew/rho*(alpha/omega); rho = rhoNew; // 10. Update p = r + beta*p - omega*beta*Ap for (i = 0; i < size; i++) { p[i] = r[i] + beta*(p[i] - omega*Ap[i]); } zero<double>(Ap, size); (*matrix_vector)(Ap, p, extra_info); invif.ops_count++; } if(k == max_iter-1) { //printf("CG: Failed to converge iter = %d, rsq = %e\n", k,rsq); invif.success = false; } else { //printf("CG: Converged in %d iterations.\n", k); invif.success = true; } k++; // Check the true residual. (*matrix_vector)(Ap,phi,extra_info); invif.ops_count++; truersq = diffnorm2sq<double>(Ap, phi0, size); // Free all the things! delete[] r; delete[] r0; delete[] p; delete[] Ap; delete[] s; delete[] As; print_verbosity_summary(verb, "BiCGStab", invif.success, k, invif.ops_count, sqrt(truersq)/bsqrt); // printf("# CG: Converged iter = %d, rsq = %e, truersq = %e\n",k,rsq,truersq); invif.resSq = truersq; invif.iter = k; invif.name = "BiCGStab"; return invif; // Convergence } // Performs BiCGStab(restart_freq) with restarts when restart_freq is hit. inversion_info minv_vector_bicgstab_restart(double *phi, double *phi0, int size, int max_iter, double res, int restart_freq, void (*matrix_vector)(double*,double*,void*), void* extra_info, inversion_verbose_struct* verb) { int iter; // counts total number of iterations. int ops_count; inversion_info invif; double bsqrt = sqrt(norm2sq<double>(phi0, size)); inversion_verbose_struct verb_rest; shuffle_verbosity_restart(&verb_rest, verb); stringstream ss; ss << "BiCGStab(" << restart_freq << ")"; iter = 0; ops_count = 0; do { invif = minv_vector_bicgstab(phi, phi0, size, restart_freq, res, matrix_vector, extra_info, &verb_rest); iter += invif.iter; ops_count += invif.ops_count; print_verbosity_restart(verb, ss.str(), iter, ops_count, sqrt(invif.resSq)/bsqrt); } while (iter < max_iter && invif.success == false && sqrt(invif.resSq)/bsqrt > res); invif.iter = iter; invif.ops_count = ops_count; print_verbosity_summary(verb, ss.str(), invif.success, iter, invif.ops_count, sqrt(invif.resSq)/bsqrt); invif.name = ss.str(); // invif.resSq is good. if (sqrt(invif.resSq)/bsqrt > res) { invif.success = false; } else { invif.success = true; } return invif; } // Solves lhs = A^(-1) rhs using bicgstab inversion_info minv_vector_bicgstab(complex<double> *phi, complex<double> *phi0, int size, int max_iter, double eps, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, inversion_verbose_struct* verb) { // BICGSTAB solutions to Mphi = b // see www.mcs.anl.gov/papers/P3039-0912.pdf // "Analysis and Practical Use of Flexible BiCGStab // Initialize vectors. complex<double> *r, *r0, *p, *Ap, *s, *As; complex<double> rho, rhoNew, alpha, beta, omega; double rsq, bsqrt, truersq; int k,i; inversion_info invif; // Allocate memory. r = new complex<double>[size]; r0 = new complex<double>[size]; p = new complex<double>[size]; Ap = new complex<double>[size]; s = new complex<double>[size]; As = new complex<double>[size]; // Zero vectors. zero<double>(r, size); zero<double>(r0, size); zero<double>(p, size); zero<double>(Ap, size); zero<double>(s, size); zero<double>(As, size); // Initialize values. rsq = 0.0; bsqrt = 0.0; truersq = 0.0; // Find norm of rhs. bsqrt = sqrt(norm2sq<double>(phi0, size)); // 1. r = b - Ax. , r0 = arbitrary (use r). // Take advantage of initial guess in phi. (*matrix_vector)(Ap, phi, extra_info); invif.ops_count++; for(i = 0; i<size; i++) { r[i] = phi0[i] - Ap[i]; // 1. r0 = b-Ax0 } copy<double>(r0, r, size); // 2. p = r copy<double>(p, r, size); // 2a. Initialize rho = <r, r0>. rho = dot<double>(r0, r, size); // 2b. Initialize Ap. (*matrix_vector)(Ap, p, extra_info); invif.ops_count++; // 3. iterate till convergence for(k = 0; k< max_iter; k++) { // 4. alpha = <r0, r>/<r0, Ap> alpha = rho/dot<double>(r0, Ap, size); // 5. s = r - alpha Ap for (i = 0; i < size; i++) { s[i] = r[i] - alpha*Ap[i]; } // 6. Compute As, w = <s, As>/(As, As) (*matrix_vector)(As, s, extra_info); invif.ops_count++; omega = dot<double>(As, s, size)/dot<double>(As, As, size); // 7. Update phi = phi + alpha*p + omega*s for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i] + omega*s[i]; } // 8. Update r = s - omega*As for (i = 0; i < size; i++) { r[i] = s[i] - omega*As[i]; } // 8a. If ||r|| is sufficiently small, quit. rsq = norm2sq<double>(r, size); print_verbosity_resid(verb, "BiCGStab", k+1, invif.ops_count, sqrt(rsq)/bsqrt); if (sqrt(rsq) < eps*bsqrt || k==max_iter-1) { break; } // 9. rhoNew = <r0, r>. rhoNew = dot<double>(r0, r, size); beta = rhoNew/rho*(alpha/omega); rho = rhoNew; // 10. Update p = r + beta*p - omega*beta*Ap for (i = 0; i < size; i++) { p[i] = r[i] + beta*(p[i] - omega*Ap[i]); } zero<double>(Ap, size); (*matrix_vector)(Ap, p, extra_info); invif.ops_count++; } if(k == max_iter-1) { //printf("CG: Failed to converge iter = %d, rsq = %e\n", k,rsq); invif.success = false; } else { //printf("CG: Converged in %d iterations.\n", k); invif.success = true; } k++; // Check the true residual. (*matrix_vector)(Ap,phi,extra_info); invif.ops_count++; truersq = diffnorm2sq<double>(Ap, phi0, size); // Free all the things! delete[] r; delete[] r0; delete[] p; delete[] Ap; delete[] s; delete[] As; print_verbosity_summary(verb, "BiCGStab", invif.success, k, invif.ops_count, sqrt(truersq)/bsqrt); // printf("# CG: Converged iter = %d, rsq = %e, truersq = %e\n",k,rsq,truersq); invif.resSq = truersq; invif.iter = k; invif.name = "BiCGStab"; return invif; // Convergence } // Performs BiCGStab with restarts when restart_freq is hit. // This may be sloppy, but it works. inversion_info minv_vector_bicgstab_restart(complex<double> *phi, complex<double> *phi0, int size, int max_iter, double res, int restart_freq, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, inversion_verbose_struct* verb) { int iter; // counts total number of iterations. int ops_count; inversion_info invif; double bsqrt = sqrt(norm2sq<double>(phi0, size)); stringstream ss; ss << "BiCGStab(" << restart_freq << ")"; inversion_verbose_struct verb_rest; shuffle_verbosity_restart(&verb_rest, verb); iter = 0; ops_count = 0; do { invif = minv_vector_bicgstab(phi, phi0, size, restart_freq, res, matrix_vector, extra_info, &verb_rest); iter += invif.iter; ops_count += invif.ops_count; print_verbosity_restart(verb, ss.str(), iter, ops_count, sqrt(invif.resSq)/bsqrt); } while (iter < max_iter && invif.success == false && sqrt(invif.resSq)/bsqrt > res); invif.iter = iter; invif.ops_count = ops_count; print_verbosity_summary(verb, ss.str(), invif.success, iter, invif.ops_count, sqrt(invif.resSq)/bsqrt); invif.name = ss.str(); // invif.resSq is good. if (sqrt(invif.resSq)/bsqrt > res) { invif.success = false; } else { invif.success = true; } return invif; } // Wikipedia implementation. // This is ultimately a permutation of operations along with a renaming of variables. // It has slightly different convergence because BiCGStab is just that damn numerically sensitive. // It's better for some matrices, worse for others. Whatever. /* // Solves lhs = A^(-1) rhs using bicgstab inversion_info minv_vector_bicgstab(double *phi, double *phi0, int size, int max_iter, double eps, void (*matrix_vector)(double*,double*,void*), void* extra_info, inversion_verbose_struct* verb) { // BICGSTAB solutions to Mphi = b // see https://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method // Initialize vectors. double *r, *r0, *v, *p, *s, *t; double rho, rhoNew, alpha, beta, omega; double ssq, bsqrt, truersq; int k,i; inversion_info invif; // Allocate memory. r = new double[size]; r0 = new double[size]; v = new double[size]; p = new double[size]; s = new double[size]; t = new double[size]; // Zero vectors. zero<double>(r, size); zero<double>(r0, size); zero<double>(v, size); zero<double>(p, size); zero<double>(s, size); zero<double>(t, size); // Initialize values. ssq = 0.0; bsqrt = 0.0; truersq = 0.0; // Find norm of rhs. bsqrt = sqrt(norm2sq<double>(phi0, size)); // 1. r = b - Ax. // Take advantage of initial guess in phi. (*matrix_vector)(v, phi, extra_info); for(i = 0; i<size; i++) { r[i] = phi0[i] - v[i]; // 1. r0 = b-Ax0 } // 2. rhat0 = r. copy<double>(r0, r, size); // 3. rho = alpha = omega = 1.0. rho = alpha = omega = 1.0; // 4. v = p = 0 (already done). // iterate till convergence for(k = 0; k< max_iter; k++) { // 5.1. rhoNew = <rhat0, ri-1> rhoNew = dot<double>(r0, r, size); // 5.2. beta = (rhoNew/rho)(alpha/omega_i-1) beta = (rhoNew/rho)*(alpha/omega); rho = rhoNew; // 5.3. p = r + beta(p - omega v) for (i = 0; i < size; i++) { p[i] = r[i] + beta*p[i] - beta*omega*v[i]; } // 5.4. v = Ap (*matrix_vector)(v, p, extra_info); // 5.5. alpha = rho/<rhat0, v> alpha = rho/dot<double>(r0, v, size); // 5.6. s = r - alpha v for (i = 0; i < size; i++) { s[i] = r[i] - alpha*v[i]; } // 5.7. If ||s|| is sufficiently small, x = x+alpha p, quit. ssq = norm2sq<double>(s, size); print_verbosity_resid(verb, "BiCGStab", k+1, sqrt(ssq)/bsqrt); if (sqrt(ssq) < eps*bsqrt) { // printf("Final rsq = %g\n", ssq); for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i]; } break; } // 5.8. t = As (*matrix_vector)(t, s, extra_info); // 4.9. omega = <t, s>/<t, t>; omega = dot<double>(t, s, size)/norm2sq<double>(t, size); // 4.10. x = x + alpha p + omega s for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i] + omega*s[i]; } // 4.11. If x_i is accurate enough, then quit. // We'll ignore this for now. // 4.12. r = s - omega t; for (i = 0; i < size; i++) { r[i] = s[i] - omega*t[i]; } } if(k == max_iter) { //printf("CG: Failed to converge iter = %d, rsq = %e\n", k,rsq); invif.success = false; for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i]; } } else { //printf("CG: Converged in %d iterations.\n", k); k++; // Fix a counting issue. invif.success = true; } // Check the true residual. truersq = 0.0; (*matrix_vector)(v,phi,extra_info); for(i=0; i < size; i++) truersq += real(conj(v[i] - phi0[i])*(v[i] - phi0[i])); // Free all the things! delete[] r; delete[] r0; delete[] v; delete[] p; delete[] s; delete[] t; print_verbosity_summary(verb, "BiCGStab", invif.success, k, sqrt(truersq)/bsqrt); // printf("# CG: Converged iter = %d, rsq = %e, truersq = %e\n",k,rsq,truersq); invif.resSq = truersq; invif.iter = k; invif.name = "BiCGStab"; return invif; // Convergence } inversion_info minv_vector_bicgstab(complex<double> *phi, complex<double> *phi0, int size, int max_iter, double eps, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, inversion_verbose_struct* verb) { // BICGSTAB solutions to Mphi = b // see https://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method // Initialize vectors. complex<double> *r, *r0, *v, *p, *s, *t; complex<double> rho, rhoNew, alpha, beta, omega; double ssq, bsqrt, truersq; int k,i; inversion_info invif; // Allocate memory. r = new complex<double>[size]; r0 = new complex<double>[size]; v = new complex<double>[size]; p = new complex<double>[size]; s = new complex<double>[size]; t = new complex<double>[size]; // Zero vectors. zero<double>(r, size); zero<double>(r0, size); zero<double>(v, size); zero<double>(p, size); zero<double>(s, size); zero<double>(t, size); // Initialize values. ssq = 0.0; bsqrt = 0.0; truersq = 0.0; // Find norm of rhs. bsqrt = sqrt(norm2sq<double>(phi0, size)); // 1. r = b - Ax. // Take advantage of initial guess in phi. (*matrix_vector)(v, phi, extra_info); for(i = 0; i<size; i++) { r[i] = phi0[i] - v[i]; // 1. r0 = b-Ax0 } // 2. rhat0 = r. copy<double>(r0, r, size); // 3. rho = alpha = omega = 1.0. rho = alpha = omega = 1.0; // 4. v = p = 0 (already done). // iterate till convergence for(k = 0; k< max_iter; k++) { // 5.1. rhoNew = <rhat0, ri-1> rhoNew = dot<double>(r0, r, size); // 5.2. beta = (rhoNew/rho)(alpha/omega_i-1) beta = (rhoNew/rho)*(alpha/omega); rho = rhoNew; // 5.3. p = r + beta(p - omega v) for (i = 0; i < size; i++) { p[i] = r[i] + beta*p[i] - beta*omega*v[i]; } // 5.4. v = Ap (*matrix_vector)(v, p, extra_info); // 5.5. alpha = rho/<rhat0, v> alpha = rho/dot<double>(r0, v, size); // 5.6. s = r - alpha v for (i = 0; i < size; i++) { s[i] = r[i] - alpha*v[i]; } // 5.7. If ||s|| is sufficiently small, x = x+alpha p, quit. ssq = norm2sq<double>(s, size); print_verbosity_resid(verb, "BiCGStab", k+1, sqrt(ssq)/bsqrt); if (sqrt(ssq) < eps*bsqrt) { // printf("Final rsq = %g\n", ssq); for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i]; } break; } // 5.8. t = As (*matrix_vector)(t, s, extra_info); // 4.9. omega = <t, s>/<t, t>; omega = dot<double>(t, s, size)/norm2sq<double>(t, size); // 4.10. x = x + alpha p + omega s for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i] + omega*s[i]; } // 4.11. If x_i is accurate enough, then quit. // We'll ignore this for now. // 4.12. r = s - omega t; for (i = 0; i < size; i++) { r[i] = s[i] - omega*t[i]; } } if(k == max_iter) { //printf("CG: Failed to converge iter = %d, rsq = %e\n", k,rsq); invif.success = false; for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i]; } } else { //printf("CG: Converged in %d iterations.\n", k); k++; // Fix a counting issue. invif.success = true; } // Check the true residual. truersq = 0.0; (*matrix_vector)(v,phi,extra_info); for(i=0; i < size; i++) truersq += real(conj(v[i] - phi0[i])*(v[i] - phi0[i])); // Free all the things! delete[] r; delete[] r0; delete[] v; delete[] p; delete[] s; delete[] t; print_verbosity_summary(verb, "BiCGStab", invif.success, k, sqrt(truersq)/bsqrt); // printf("# CG: Converged iter = %d, rsq = %e, truersq = %e\n",k,rsq,truersq); invif.resSq = truersq; invif.iter = k; invif.name = "BiCGStab"; return invif; // Convergence } */
// // Created by fab on 25/02/2020. // #include <iostream> #include <imgui/imgui.h> #include "../../headers/components/Transform.hpp" Transform::Transform() { position = glm::vec3(0.f); quat = glm::quat(); modelMatrix = glm::mat4(1.0f); scale = glm::vec3(1.0f); } void Transform::addPosition(glm::vec3 pos) { position += pos; } void Transform::updateMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::scale(modelMatrix, scale); //This is done manually for learning purpose /* Rotation matrix = * a^2+b^2-c^2-d^2 & 2bc-2ad & 2ac+2bd \\ 2ad+2bc & a^2-b^2+c^2-d^2 & 2cd-2ab \\ 2bd-2ac & 2ab+2cd & a^2-b^2-c^2+d^2 */ //could store all the temp var float a2 = quat.x * quat.x; float b2 = quat.y * quat.y; float c2 = quat.z * quat.z; float d2 = quat.w * quat.w; glm::mat4 rot = glm::mat4(1.0f); rot[0][0] = a2+b2-c2-d2; rot[0][1] = (2 * (quat.y * quat.z)) - 2 * (quat.x * quat.w); rot[0][2] = 2 * (quat.x * quat.z) + 2 * (quat.y * quat.w); rot[1][0] = 2 * (quat.x * quat.w) + 2 * (quat.y * quat.z); rot[1][1] = a2-b2+c2-d2; rot[1][2] = 2 * (quat.z * quat.w) - 2 * (quat.x * quat.y); rot[2][0] = 2 * (quat.y * quat.w) - 2 * (quat.x * quat.z); rot[2][1] = 2 * (quat.x * quat.y) + 2 * (quat.z * quat.w); rot[2][2] = a2-b2-c2+d2; modelMatrix = rot * modelMatrix; } void Transform::rotate(glm::vec3 axis, float angle) { axis = glm::normalize(axis); axis = glm::sin(glm::radians(angle/2)) * axis; glm::quat q; q.x = glm::cos(glm::radians(angle / 2)); //a q.y = axis.x; // b q.z = axis.y; // c q.w = axis.z; // d quat *= q; updateMatrix(); } void Transform::setPosition(float x, float y, float z) { position.x = x; position.y = y; position.z = z; modelMatrix[3] = glm::vec4(position, 1.0f); } void Transform::addPosition(float x, float y, float z) { position.x += x; position.y += y; position.z += z; modelMatrix[3] = glm::vec4(position, 1.0f); } void Transform::drawInspector() { ImGui::PushID(this); if(ImGui::InputFloat3("Scale", &scale.x)) { modelMatrix[0][0] = scale.x; modelMatrix[1][1] = scale.y; modelMatrix[2][2] = scale.z; } ImGui::PopID(); }
#include "aeScene.h" #include "aeRendererAddOn.h" namespace aeEngineSDK { aeScene::aeScene() { m_pszName = "New Scene"; } aeScene::aeScene(const String & Name) { m_pszName = Name; } aeScene::aeScene(const aeScene & O) { *this = O; } aeScene::~aeScene() { } void aeScene::SetName(const String & Name) { m_pszName = Name; } void aeScene::LoadScene(const String & Filename) { } void aeScene::AddGameObject(aeGameObject* pGameObject) { m_aGameObjects.push_back(pGameObject); } void aeScene::AddModels(aeModel* Output, aeGameObject* GO, const aeMatrix4& Transform) { if (GO->IsStatic()) { auto AO = GO->m_aAddOns.equal_range(AE_ADD_ON_ID::AE_RENDERER); aeMatrix4 Tr = GO->m_xTransform.GetRealMatrix() * Transform; for (auto it = AO.first; it != AO.second; ++it) { Vector<aeMesh> NM; NM = ((aeRendererAddOn*)it->second)->m_xModel.GetMeshes(); for (auto Mesh : NM) { for (auto vertex : Mesh.Vertices) { vertex.Pos = Tr * vertex.Pos; } Output->m_aMeshes.push_back(Mesh); Output->m_aMaterials.push_back(Mesh.pMaterial); Output->m_aMeshes.rbegin()->MaterialIndex = Output->m_aMaterials.size()-1; Output->m_aMeshes.rbegin()->pMaterial = Mesh.pMaterial; } } for (auto child : GO->m_xTransform.m_aChildren) { AddModels(Output, child->m_pGameObject, Tr); } } } aeModel* aeScene::TransformToModels() { aeModel* Output = ae_new<aeModel>(); for (auto GO : m_aGameObjects) { AddModels(Output, GO,aeMatrix4::Identity()); } return Output; } String aeScene::GetName() { return m_pszName; } }
/** * @file Tcp_Test.cpp * @author dtuchscherer <daniel.tuchscherer@hs-heilbronn.de> * @brief short description... * @details long description... * @version 1.0 * @copyright Copyright (c) 2015, dtuchscherer. * All rights reserved. * * Redistributions and use in source and binary forms, with * or without modifications, are permitted provided that the * following conditions are met: Redistributions of source code must * retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of the Heilbronn University nor the name of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS “AS IS” * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /******************************************************************************* * MODULES USED *******************************************************************************/ #include <iostream> #include "catch.hpp" #include "RTTask.h" #include "TcpServer.h" #include "TcpClient.h" /******************************************************************************* * DEFINITIONS AND MACROS *******************************************************************************/ /******************************************************************************* * TYPEDEFS, ENUMERATIONS, CLASSES *******************************************************************************/ class ServerTask : public RTThread< ServerTask, 80, 500000 > { public: ServerTask() noexcept : RTThread() { } void pre() noexcept { m_server.listen(m_client, 4444U); } void update() noexcept { m_server.accept(); } void post() noexcept { } private: TcpServer m_server; IpAddress m_client{"localhost"}; }; /******************************************************************************* * PROTOTYPES OF LOCAL FUNCTIONS *******************************************************************************/ /******************************************************************************* * EXPORTED VARIABLES *******************************************************************************/ /******************************************************************************* * GLOBAL MODULE VARIABLES *******************************************************************************/ /******************************************************************************* * EXPORTED FUNCTIONS *******************************************************************************/ /******************************************************************************* * FUNCTION DEFINITIONS *******************************************************************************/ TEST_CASE( "TCP Client connect and disconnect", "[client-connect-send-disconnect]" ) { IpAddress local("localhost"); uint8 send_ascii_zero = 0x30U; ServerTask t; TcpClient tcp; boolean connected = FALSE; while ( connected == FALSE ) { connected = tcp.connect(local, 4444U); } REQUIRE( connected == TRUE ); REQUIRE( tcp.send(&send_ascii_zero, 1U) == 1 ); REQUIRE( tcp.disconnect() == TRUE ); }
#include <Arduino.h> class FourDigitLCD { public: FourDigitLCD(); void init(); void display(int number); };
#include<iostream> #include<vector> #include<algorithm> #include<map> using namespace std; class Solution { public: vector<int> partitionLabels(string S) { //基本思想:排序+双指针,将问题转化为56合并区间 //通过map获取每个字符的区间范围,然后将这些区间合并即可 vector<int> res; map<char,pair<int,int>> Mapinterval; for(int i=0;i<S.size();i++) { if(Mapinterval.find(S[i])==Mapinterval.end()) Mapinterval[S[i]]={i,i}; else Mapinterval[S[i]].second=i; } vector<pair<int,int>> intervals; for(auto iter=Mapinterval.begin();iter!=Mapinterval.end();iter++) intervals.push_back((*iter).second); sort(intervals.begin(),intervals.end()); for(int i=0;i<intervals.size();) { int j=i+1; int left=intervals[i].first,right=intervals[i].second; while(j<intervals.size()&&intervals[j].first<right) { left=min(left,intervals[j].first); right=max(right,intervals[j].second); j++; } res.push_back(right-left+1); i=j; } return res; } }; int main() { Solution solute; string S = "ababcbacadefegdehijhklij"; vector<int> res=solute.partitionLabels(S); for_each(res.begin(),res.end(),[](int v){cout<<v<<endl;}); return 0; }
#pragma once #include "SystemBase.h" class ELevelManager : public SystemBase { DECLARE_SINGLE(ELevelManager) public: virtual void SetSystemOperationSlot() override; };
/* BEGIN LICENSE */ /***************************************************************************** * SKFind : the SK search engine * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: recordfilter.h,v 1.2.4.4 2005/02/21 14:22:44 krys Exp $ * * Authors: Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #ifndef __SKF_RECORDFILTER_H_ #define __SKF_RECORDFILTER_H_ // SKIRecordFilter #define SK_SKIRECORDFILTER_IID \ { 0x890d318d, 0xf0b7, 0x4e99, \ { 0xa9, 0xac, 0x60, 0x53, 0xf3, 0x28, 0x80, 0x28 } } class SKAPI SKIRecordFilter : public SKRefCount { public: SK_REFCOUNT_INTF_IID(SKIRecordFilter, SK_SKIRECORDFILTER_IID) virtual SKERR Reset(); virtual SKERR CheckRecord(SKIRecord *pRecord, PRBool* pbKeepIt) = 0; virtual SKERR SetRecordSet(SKIRecordSet *pRecordSet); SKERR GetRecordSet(SKIRecordSet **ppRecordSet); protected: skPtr<SKIRecordSet> m_pRecordSet; }; SK_REFCOUNT_DECLARE_INTERFACE(SKIRecordFilter, SK_SKIRECORDFILTER_IID) // SKRecordFilterJoinRSOnUNum #define SK_SKRECORDFILTERJOINRSONUNUM_IID \ { 0xc84d2518, 0x90f0, 0x490a, \ { 0x88, 0x25, 0x9f, 0xab, 0x85, 0xc8, 0xb7, 0x0a } } class SKAPI SKRecordFilterJoinRSOnUNum : public SKIRecordFilter { public: SK_REFCOUNT_INTF_DEFAULT(SKRecordFilterJoinRSOnUNum) SK_REFCOUNT_INTF_IID(SKRecordFilterJoinRSOnUNum, SK_SKRECORDFILTERJOINRSONUNUM_IID) SKRecordFilterJoinRSOnUNum(); ~SKRecordFilterJoinRSOnUNum(); SKERR SetFieldName(const char *pszFieldName); SKERR SetFilterData(SKCursor *pFilterCursor, SKIRecordSet *pFilterRecordSet, const char *pszFilterFieldName); virtual SKERR SetRecordSet(SKIRecordSet *pRecordSet); virtual SKERR Reset(); virtual SKERR CheckRecord(SKIRecord *pRecord, PRBool* pbKeepIt); private: char *m_pszFieldName; skPtr<SKIField> m_pField; skPtr<SKCursor> m_pFilterCursor; skPtr<SKIRecordSet> m_pFilterRecordSet; skPtr<SKIField> m_pFilterField; PRUint32 m_iLastRank; }; SK_REFCOUNT_DECLARE_INTERFACE(SKRecordFilterJoinRSOnUNum, SK_SKRECORDFILTERJOINRSONUNUM_IID) // SKRecordFilterUNumBitField struct BitFieldRule { PRBool bAction; PRUint32 iBitShift; PRUint32 iBitMask; PRUint32 iMin; PRUint32 iMax; }; #define SK_SKRECORDFILTERUNUMBITFIELD_IID \ { 0xf5586dcc, 0xc076, 0x407d, \ { 0x90, 0x1a, 0x47, 0x45, 0x15, 0x59, 0x2f, 0x15 } } class SKAPI SKRecordFilterUNumBitField : public SKIRecordFilter { public: SK_REFCOUNT_INTF_DEFAULT(SKRecordFilterUNumBitField) SK_REFCOUNT_INTF_IID(SKRecordFilterUNumBitField, SK_SKRECORDFILTERUNUMBITFIELD_IID) SKRecordFilterUNumBitField(); ~SKRecordFilterUNumBitField(); // this enables to use a "second level" recordset SKERR SetOptionalLink(const char *pszLinkFieldName, SKIRecordSet *pLinkRecordSet, PRBool bNoLinkLookup); // this is mandatory and is the field we are interested in SKERR SetField(const char *pszFieldName); SKERR Clear(); SKERR SetDefaultPolicy(PRBool bPolicy); SKERR AddRule(PRBool bAction, PRUint32 iBitShift, PRUint32 iBitMask, PRUint32 iMinValue, PRUint32 iMaxValue); SKERR AddAcceptedValue(PRUint32 value); SKERR AddAcceptedRange(PRUint32 min, PRUint32 max); SKERR AddRejectedValue(PRUint32 value); SKERR AddRejectedRange(PRUint32 min, PRUint32 max); virtual SKERR CheckRecord(SKIRecord *pRecord, PRBool *pbKeepIt); virtual SKERR SetRecordSet(SKIRecordSet *pRecordSet); private: char * m_pszLinkFieldName; skPtr<SKIField> m_pLinkField; skPtr<SKIRecordSet> m_pLinkRecordSet; PRBool m_bNoLinkLookup; char * m_pszFieldName; skPtr<SKIField> m_pField; PRBool m_bDefaultPolicy; PRUint32 m_iRuleSize; PRUint32 m_iRuleCount; BitFieldRule * m_pRules; }; SK_REFCOUNT_DECLARE_INTERFACE(SKRecordFilterUNumBitField, SK_SKRECORDFILTERUNUMBITFIELD_IID) #define SK_SKFRECORDFILTERUNUMINCURSOR_IID \ { 0x343ef156, 0xd5b3, 0x4a44, \ { 0xa1, 0x0f, 0xc8, 0x0b, 0x67, 0xf1, 0x31, 0xb8 } } class SKAPI skfRecordFilterUNumInCursor : public SKIRecordFilter { public: SK_REFCOUNT_INTF_DEFAULT(skfRecordFilterUNumInCursor) SK_REFCOUNT_INTF_IID(skfRecordFilterUNumInCursor, SK_SKFRECORDFILTERUNUMINCURSOR_IID) skfRecordFilterUNumInCursor() {}; ~skfRecordFilterUNumInCursor() {}; SKERR SetField(SKIField* pField) { m_pField = pField; return noErr; } SKERR SetCursor(SKCursor* pCursor); virtual SKERR CheckRecord(SKIRecord *pRecord, PRBool *pbKeepIt); private: skPtr<SKIField> m_pField; skPtr<SKCursor> m_pCursor; }; SK_REFCOUNT_DECLARE_INTERFACE(skfRecordFilterUNumInCursor, SK_SKFRECORDFILTERUNUMINCURSOR_IID) #else #error "Multiple inclusions of recordfilter.h" #endif
//: C09:Rectangle2.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Obserwatory i modyfikatory z przedrostkami "get" i "set" class Rectangle { int width, height; public: Rectangle(int w = 0, int h = 0) : width(w), height(h) {} int getWidth() const { return width; } void setWidth(int w) { width = w; } int getHeight() const { return height; } void setHeight(int h) { height = h; } }; int main() { Rectangle r(19, 47); // Change width & height: r.setHeight(2 * r.getWidth()); r.setWidth(2 * r.getHeight()); } ///:~
#include "socket_server.h" // GameShow* SocketServer::gameShow; struct mg_server* SocketServer::s_server = NULL; queue<string> SocketServer::messages; queue<Document*> SocketServer::incomingMessages; mutex SocketServer::queueMutex; SocketServer::SocketServer() { } SocketServer::~SocketServer() { } Document *SocketServer::getNextIncomingMessage() { // cout << "gnim" << endl; queueMutex.lock(); Document* tmp = 0; if(!incomingMessages.empty()){ tmp = incomingMessages.front(); // cout << "got tmp " << tmp << endl; incomingMessages.pop(); } queueMutex.unlock(); return tmp; } void SocketServer::enqueueMessage(string message){ queueMutex.lock(); messages.push(message); queueMutex.unlock(); } string SocketServer::dequeueMessage(){ // string ret; // strcpy(ret, messages.pop()); // return ret; return ""; } void SocketServer::messagePusher(){ while(1){ string tmp = ""; if(NULL != s_server){ // queueMutex.lock(); if(!messages.empty()){ tmp = messages.front(); messages.pop(); } // queueMutex.unlock(); if(strcmp("", tmp.c_str())){ sendMessage(tmp); } } usleep(1000); } } void SocketServer::startup() { // gameShow = _gameshow; // printf("_gameshow pointer is %p\n", _gameshow); // printf("gameShow pointer is %p\n", gameShow); // printf("starting up server\n"); std::thread t1(SocketServer::runThread); t1.detach(); std::thread t2(SocketServer::messagePusher); t2.detach(); } void SocketServer::runThread(){ // printf("at run thread\n"); // struct mg_server *server; // Create and configure the server s_server = mg_create_server(NULL, SocketServer::ev_handler); mg_set_option(s_server, "document_root", "./public_html"); mg_set_option(s_server, "listening_port", "8080"); // Serve request. Hit Ctrl-C to terminate the program printf("Starting on port %s\n", mg_get_option(s_server, "listening_port")); for (;;) { mg_poll_server(s_server, 100); // usleep(1000); } // Cleanup, and free server instance mg_destroy_server(&s_server); } void SocketServer::sendMessage(string message) { // cout << "Trying to send " << message << endl; if(NULL != s_server){ struct mg_connection *c; for (c = mg_next(s_server, NULL); c != NULL; c = mg_next(s_server, c)) { // struct conn_data *d2 = (struct conn_data *) c->connection_param; // printf("a\n"); if (!c->is_websocket){ continue; } // printf("b\n"); // data.c_str(), data.length() mg_websocket_printf(c, WEBSOCKET_OPCODE_TEXT, "%s", message.c_str()); // printf("c\n"); } } } int SocketServer::ev_handler(struct mg_connection *conn, enum mg_event ev) { switch (ev) { case MG_AUTH: return MG_TRUE; case MG_REQUEST: if(!strcmp(conn->uri, "/ws")){ return sendWsReply(conn); }else{ // printf("%s\n",conn->uri); return MG_FALSE; } default: return MG_FALSE; } } int SocketServer::sendWsReply(struct mg_connection *conn) { if(conn->is_websocket){ // cout << "WS: " << conn->content << endl; printf("%.*s\n", (int) conn->content_len, conn->content); if((int) conn->content_len >= 2047){ cout << "======= WS message too big ========" << endl; printf("[%.*s]\n", (int) conn->content_len, conn->content); exit(0); } char buffer[2048]; memcpy(buffer, conn->content, (int) conn->content_len); buffer[(int) conn->content_len] = 0; Document *document = new Document(); document->Parse(buffer); if(!document->IsObject()){ cout << "-- malformed json message --" << endl; return MG_FALSE; } if(!document->HasMember("message")){ cout << "-- json doesnt contain node 'message' --" << endl; return MG_FALSE; } // string message = document["message"].GetString(); // cout << "message is " << message << endl; // gameShow->processMessage(&document); incomingMessages.push(document); return MG_TRUE ; }else{ return MG_FALSE; } }
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define ll long long #define getint(n) scanf("%d",&n) ll dp[100][45000]; int main() { int t,n,a[100],sum,sum1; ll one = 1; getint(t); while(t--) { getint(n); sum = 0; for(int i = 0 ; i<n ; i++) { getint(a[i]); sum += a[i]; } dp[t][0] = 1; for(int i = 0 ; i<n ; i++) { for(int j = sum/2 ; j >= a[i] ; j--) { dp[t][j] = dp[t][j] | (dp[t][j-a[i]]<<1); } } for(int i = sum/2 ; i>=0 ; i--) { if( dp[t][i] & (one << n/2) || dp[t][i] & (one << ((n+1)/2))) { sum1 = i; break; } } sum -= sum1; if(sum > sum1) printf("%d %d",sum1,sum); else printf("%d %d",sum,sum1); if(t > 0) printf("\n\n"); else printf("\n"); } return 0; }
#ifndef UPENN_CONTROLLER_H #define UPENN_CONTROLLER_H #include <ros/ros.h> #include <Eigen/Dense> #include "quadrotor_sim/math_operations.h" #include "quadrotor_sim/controllers/controller_class.h" class upenn_controller: public control_class{ private: ros::NodeHandle nh_; //Eigen::Matrix3d J; double Kpos_x_, Kpos_y_, Kpos_z_; double Kvel_x_, Kvel_y_, Kvel_z_; double Kr, Kw; Eigen::Vector3d Kpos_, Kvel_, Kr_, Kw_; //Acceleration due to gravity in NED frame Eigen::Vector3d g_; double norm_thrust_const_; double max_fb_acc_; public: upenn_controller(const ros::NodeHandle& nh); virtual ~upenn_controller(); Eigen::Vector4d calculate_control_fb(Eigen::Vector3d&, Eigen::Vector3d&, Eigen::Vector3d&, Eigen::Vector3d&, Eigen::Vector3d&, double&, Eigen::Vector4d&, Eigen::Vector4d&); Eigen::Vector4d attcontroller(const Eigen::Vector4d&, const Eigen::Vector3d&, Eigen::Vector4d&, Eigen::Vector3d&, Eigen::Vector3d&, double); }; #endif
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; string st; int cou[30]; int main() { int t,k; scanf("%d",&t); while (t--) { long long ans = 0; memset(cou,0,sizeof(cou)); cin >> st >> k; int head = 0; for (int i = 0;i < st.size(); i++) { cou[st[i] - 'a']++; while (cou[st[i] - 'a'] > k) cou[st[head++] - 'a']--; ans += i - head + 1; } cout << ans << endl; } return 0; }
#pragma once #include "GlobalHeader.h" // fa::String #include <stdexcept> // std::logic_error, std::runtime_error #include <string> // std::string #include <gtest/gtest.h> // ::testing::internal::FloatingPoint #include <mylibs/utility.hpp> // pl::Uinteger #include <limits> // std::numeric_limits #include <type_traits> // std::is_same namespace fa { namespace utils { namespace detail { template <size_type> struct AddDelimiter final { static void func(OStringStream &ostr) { ostr << ", "; } }; template <> struct AddDelimiter<static_cast<size_type>(0U)> final { static void func(OStringStream &) { } }; template <class ...Args> void makeClassStringPairHelper(OStringStream &ostr) { ostr << ')'; } template <class StringType, class ValueType, class ...Args> void makeClassStringPairHelper(OStringStream &ostr, StringType const &str, ValueType const &val, Args &&...args) { ostr << str << ": " << val; AddDelimiter<sizeof...(Args)>::func(ostr); makeClassStringPairHelper(ostr, std::forward<Args>(args)...); } } // END of namespace detail /*! generates strings for the operator<< functions that print all defined classes in the following format: ClassName(member1name: member1value, ...) for instance: Nutrient(name: Vitamin A, ...) this function is to be called by operator<< functions so that they can print their argument the arguments shall be the class' name (className parameter) followed by (logical, not actual) two element tuples of each members identifier (as an fa::String) and that member's value. Note that the value must be printable. */ template <class ...Args> /* recursive templates are slow to compile and increase executable size significantly; possible replace this with much more clever trickery at some point */ String makeClassString(String const &className, Args &&...args) { OStringStream ostringstream{ }; ostringstream << className << '('; detail::makeClassStringPairHelper(ostringstream, std::forward<Args>(args)...); return ostringstream.str(); } namespace floating_point { template <class Type> bool almostEqual(Type first, Type second) { // doesn't support long double using TypeSet = brigand::set<double, float>; static_assert(brigand::contains<TypeSet, Type>::value, "Type in almostEqual was neither double nor float"); using TypeName = ::testing::internal::FloatingPoint<decltype(first)>; TypeName firstVal{ first }; TypeName secondVal{ second }; return firstVal.AlmostEquals(secondVal); } } // END of namespace floating_point } // END of namespace utils class DivideByZeroException : public std::logic_error { public: using this_type = DivideByZeroException; explicit DivideByZeroException(std::string const &message); virtual ~DivideByZeroException() override; virtual char const *what() const noexcept override; }; // END of class DivideByZeroException class NotYetImplementedException : public std::runtime_error { public: using this_type = NotYetImplementedException; explicit NotYetImplementedException(std::string const &message); virtual ~NotYetImplementedException() override; virtual char const *what() const noexcept override; }; // END of class NotYetImplementedException class IdOverflowException : public std::runtime_error { public: using this_type = IdOverflowException; explicit IdOverflowException(std::string const &message); virtual ~IdOverflowException() override; virtual char const *what() const noexcept override; }; // END of class IdOverflowException namespace detail { static auto constexpr idByteSize = 8; } // END of namespace detail using Id = pl::Uinteger<detail::idByteSize>; namespace detail { inline Id generateFoodIdImpl() { static Id currentId{ }; if (currentId == std::numeric_limits<Id>::max()) { throw IdOverflowException{ "Id overflow in generateFoodIdImpl, too many Ids generated for this type" }; } return currentId++; } } // END of namespace detail class AtomicFoodImpl; class CompoundFoodImpl; template <class TypeToGenerateIdFor> Id generateId() { if (std::is_same<TypeToGenerateIdFor, AtomicFoodImpl>::value || std::is_same<TypeToGenerateIdFor, CompoundFoodImpl>::value) { return detail::generateFoodIdImpl(); } static Id currentId{ }; if (currentId == std::numeric_limits<Id>::max()) { throw IdOverflowException{ "Id overflow in generateId, too many Ids generated for this type" }; } return currentId++; } //! turns all characters into lowercase except for the first character of a word, a word is any amount of characters following a space void wordify(String &); String wordifyCopy(String); } // END of namespace fa
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @file * @author Owner: Adam Minchinton (adamm) * @author Co-owner: Karianne Ekern (karie) * */ #ifndef __SYNC_MANAGER_H__ #define __SYNC_MANAGER_H__ #include "modules/sync/sync_coordinator.h" #include "adjunct/quick/sync/SyncBookmarkItems.h" #include "adjunct/quick/sync/SyncNoteItems.h" #include "adjunct/quick/sync/SyncSearchEntries.h" #include "adjunct/quick/sync/controller/SyncSettingsContext.h" #include "adjunct/quick/controller/FeatureController.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "adjunct/quick/managers/PrivacyManager.h" #include "adjunct/quick/managers/DesktopManager.h" #include "adjunct/quick/managers/OperaAccountManager.h" #include "adjunct/quick/sync/controller/SyncWidgetStateModifier.h" #define QUICK_HANDLE_SUPPORTS // Make DEBUG_LINK call the SyncLog function only when the DEBUG_LIVE_SYNC is defined and _DEBUG #if defined(DEBUG_LIVE_SYNC) && defined(_DEBUG) #define DEBUG_LINK SyncManager::GetInstance()->SyncLog #else inline void DEBUG_LINK(const void *, ...) {} #endif // defined(DEBUG_LIVE_SYNC) && defined(_DEBUG) class OpLabel; class Dialog; class OpInputAction; class SyncSpeedDialEntries; // Page shown after first use #define SYNC_INFO_PAGE UNI_L("http://www.opera.com/products/link/desktop/") #define g_sync_manager (SyncManager::GetInstance()) ////////////////////////////////////////////////////////////////////////////////////////////////////////////// class QuickSyncLock { public: QuickSyncLock(BOOL& lock, BOOL init_value, BOOL reset_to) : m_lock(lock), m_reset_to(reset_to) { m_lock = init_value; } ~QuickSyncLock() { m_lock = m_reset_to; } BOOL IsLocked(){return m_lock == TRUE;} private: BOOL& m_lock; BOOL m_reset_to; }; /************************************************************************* ** ** SyncController ** Feature controller for link. Facade for calls needed by link wizard. *************************************************************************/ class SyncController : public FeatureController { public: virtual ~SyncController() {} virtual void SetConfiguring(BOOL configuring) = 0; virtual BOOL IsConfiguring() = 0; }; /************************************************************************* ** ** SyncManager ** is a Singleton ** ** SyncManager::Listener ** ** **************************************************************************/ class SyncManager : public DesktopManager<SyncManager>, public OpTimerListener, public OpSyncUIListener, public MessageObject, public SyncController { public: enum SyncType { Now, Exit, Logout }; enum StatusTextType { Normal, Permanent, Temporary }; enum SyncDataType { SYNC_BOOKMARKS = SYNC_SUPPORTS_BOOKMARK, SYNC_NOTES = SYNC_SUPPORTS_NOTE, SYNC_SEARCHES = SYNC_SUPPORTS_SEARCHES, SYNC_TYPEDHISTORY = SYNC_SUPPORTS_TYPED_HISTORY, SYNC_URLFILTERS = SYNC_SUPPORTS_URLFILTER, SYNC_SPEEDDIAL = SYNC_SUPPORTS_SPEEDDIAL_2, SYNC_PASSWORD_MANAGER = SYNC_SUPPORTS_PASSWORD_MANAGER, SYNC_PERSONALBAR = SYNC_SUPPORTS_MAX // Desktop only }; public: SyncManager(); ~SyncManager(); OP_STATUS Init(); BOOL IsInited() { return m_inited; } OP_STATUS EnableIfRequired(BOOL& has_started); OP_STATUS ShowLoginDialog(BOOL* logged_in, DesktopWindow* parent = NULL); /** * Show Link login dialog, if the result from the dialog is that we are * logged in then enable Link. * * @param parent Parent window for the login dialog. * @return Status. */ OP_STATUS ShowLoginDialogAndEnableLink(DesktopWindow* parent = NULL); OP_STATUS ShowSetupWizard() { return ShowSetupWizard(NULL); } // not blocking OP_STATUS ShowSetupWizard(BOOL * sync_enabled) { return ShowSetupWizard(NULL, GetSavedSettings(), g_desktop_account_manager->GetAccountContext()); } // blocking if webserver_enabled != NULL OP_STATUS ShowSetupWizard(BOOL * sync_enabled, SyncSettingsContext * settings_context, OperaAccountContext* account_context); OP_STATUS ShowSettingsDialog(); OP_STATUS ShowStatus(); //=== MessageObject implementation =========== virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); virtual BOOL IsFeatureEnabled() const; virtual void EnableFeature(const FeatureSettingsContext* settings); virtual void DisableFeature(); virtual void SetFeatureSettings(const FeatureSettingsContext* settings); virtual void InvokeMessage(OpMessage msg, MH_PARAM_1 param_1, MH_PARAM_2 param_2); void SetSyncActive(BOOL active); BOOL SupportsType(SyncDataType data_type); OP_STATUS SetSupportsType(SyncDataType data_type, BOOL enable); void SetLinkEnabled(BOOL enabled, BOOL auto_login = FALSE, BOOL save_pref = TRUE); BOOL IsLinkEnabled() const { return m_settings_context.IsFeatureEnabled(); } void UpdateOffline(BOOL offline); // m_comm_not_working - TRUE if we got a communication error from the server BOOL IsCommWorking() { return !m_comm_not_working; } // m_sync_module_enabled - FALSE if the sync module couldn't start up BOOL SyncModuleEnabled() { return m_sync_module_enabled; } // Function to check if we can sync, TRUE if not in kiosk or offline mode. BOOL CanSync(); // OpTimerListener implementation void OnTimeOut(OpTimer* timer); /** * @see OpSyncUIListener */ virtual void OnSyncStarted(BOOL items_sent); virtual void OnSyncError(OpSyncError error, const OpStringC& error_msg); virtual void OnSyncFinished(OpSyncState& sync_state); virtual void OnSyncReencryptEncryptionKeyFailed(ReencryptEncryptionKeyContext* context); virtual void OnSyncReencryptEncryptionKeyCancel(ReencryptEncryptionKeyContext* context); OP_STATUS SyncNow(SyncManager::SyncType sync_type) { return SyncNow(sync_type, FALSE); } OP_STATUS SyncNow(SyncManager::SyncType sync_type, BOOL force_complete_sync); // Methods for integration with quick sync classes void StartSyncTimer(UINT32 interval); // returns true if sync state != 0 BOOL HasUsedSync(); OperaAccountManager::OAM_Status GetStatus() { return m_status; } #ifdef DEBUG_LIVE_SYNC // This is to write info out to a debug file void SyncLog(const uni_char *format, ...); #endif // DEBUG_LIVE_SYNC OP_STATUS BackupFile(OpFile& file, const uni_char* suffix = NULL); virtual void SetConfiguring(BOOL configuring); virtual BOOL IsConfiguring(); WidgetStateModifier* GetWidgetStateModifier() { return &m_state_modifier; } SyncSettingsContext* GetSavedSettings() { return &m_settings_context; } void RetryPasswordRecovery(const OpStringC& old_pass); void AbandonPasswordRecovery(); private: void SetFeatureSettingsWithoutEnabling(const FeatureSettingsContext* context); void SetDefaultSettings(); void LogError(OpSyncError error); BOOL m_inited; // Set to TRUE after a successful Init() call BOOL m_comm_not_working; // Set to TRUE if we receive an error saying we are having trouble commuicating with the link server BOOL m_is_syncing; // Set whenever SyncNow started a sync and waiting for the reply BOOL m_is_final_syncing; // Set after SyncNow is called. BOOL m_final_sync_and_close; // Set if the SyncNow is to close, otherwise it just logs out. BOOL m_sync_module_enabled; // TRUE if Sync module was initialized OpAutoPtr<OpTimer> m_status_timer; OpString m_current_permanent_status; OpAutoPtr<OpTimer> m_shutdown_timer; // Timer to show the shutdown progress dialog SyncBookmarkItems *m_bookmarks_syncer; SyncNoteItems *m_notes_syncer; SyncSpeedDialEntries *m_speed_dial_syncer; SyncSearchEntries* m_searches_syncer; BOOL m_pref_initialized; #ifdef DEBUG_LIVE_SYNC OpFile m_log_file; #endif // DEBUG_LIVE_SYNC OpString m_current_error_message; OperaAccountManager::OAM_Status m_status; // Status of the Opera Link service SyncWidgetStateModifier m_state_modifier; SyncSettingsContext m_settings_context; MessageHandler* m_msg_handler; INT32 m_suggested_error_action; private: void UpdateStatus(OperaAccountManager::OAM_Status status, BOOL force_now = FALSE); enum SyncConfigureStyle { NotConfiguring = 0, SetupWizard, SettingsDialog, LoginDialog }; SyncConfigureStyle m_configure_style; class SyncDialog* m_configure_dialog; ReencryptEncryptionKeyContext* m_reencryption_current_context; OperaAccountManager::OAM_Status m_reencryption_recovery_status; }; #endif // __SYNC_MANAGER_H__
#ifndef _SetTableStatusProc_H #define _SetTableStatusProc_H #include "CDLSocketHandler.h" #include "IProcess.h" class SetTableStatusProc :public IProcess { public: SetTableStatusProc(); virtual ~SetTableStatusProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt ) ; virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt ) ; }; #endif
#ifndef MANAGER_H #define MANAGER_H #include <iostream> #include <cstdlib> #include <string> #include <regex> #include "full_menu.h" #include "iterator.h" #include "full_menu.h" #include "category.h" using namespace std; class Manager { public: Manager(); Manager(string name,string number); void PrintOperations(); void AddCategory(FullMenu& menu); void AddCategory(FullMenu& menu, Category& newCat); void AddItemToCategory(FullMenu& menu, vector<Item>& item, int catIndex, int itemIndex); void DelCategory(FullMenu& menu); void ModifyCategory(FullMenu& menu, vector<Item>& item); void CreateItem(vector<Item>& item, vector<Ingredient>& ingredient); void ManageStorage(vector<Item>& item, vector<Ingredient>& ingredient); private: string _name,_number; void AddItemToCategory(FullMenu& menu, vector<Item>& item); void DeleteItemFromStorage(vector<Item>& item); void DeleteItemFromCategory(FullMenu& menu); void AddIngredientToItem(Item& item, vector<Ingredient>& ingredient); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef CPU_USAGE_TRACKERS_H #define CPU_USAGE_TRACKERS_H #ifdef CPUUSAGETRACKING class CPUUsageTracker; /** * List of all CPU Trackers in the system. Used for generating visual * displays of the CPU usage per tab (CPUUsageTracker is approximately * one per tab/Window, with a few global ones to cover the rest. */ class CPUUsageTrackers { CPUUsageTracker* m_first; CPUUsageTracker* m_last; public: /** Constructor */ CPUUsageTrackers() : m_first(NULL), m_last(NULL) {} class Iterator; private: friend class CPUUsageTracker; /** * Adds a tracker to the global list. Run from the CPUUsageTracker * constructor so nobody else should use it. * @param tracker The tracker to add. */ static void AddTracker(CPUUsageTracker* tracker); /** * Removes a tracker to the global list. Run from the * CPUUsageTracker destructor so nobody else should use it. * @param tracker The tracker to remove. */ static void RemoveTracker(CPUUsageTracker* tracker); public: /** * Initialises a cpu tracker iterator. */ void StartIterating(CPUUsageTrackers::Iterator& iterator); }; /** * Iterator over all CPU trackers. The tracker list must not be * modified while this is used. Typically created at the stack as a * local variable. See CPUUsageTrackerIterator::GetNext() for an * example how to use it. */ class CPUUsageTrackers::Iterator { friend class CPUUsageTrackers; CPUUsageTracker* m_next; public: /** Constructor */ Iterator() : m_next(NULL) {} /** * Gets the next CPUUsageTracker or NULL. * * Example usage: * * while (CPUUsageTracker* tracker = iterator.GetNext()) {} * * @returns CPUUsageTracker or NULL if there are no more trackers. */ CPUUsageTracker* GetNext(); }; #endif // CPUUSAGETRACKING #endif // !CPU_USAGE_TRACKERS_H
#pragma once #include <utility> #include "actor-register.h" #include "actor.h" namespace sim::events { /** * A base class for instances that are not actors, but have access to the Cloud * state and is able to schedule events */ class Observer { public: explicit Observer(std::string whoami) : whoami_(std::move(whoami)) {} const auto& WhoAmI() { return whoami_; } void SetActorRegister(const ActorRegister* actor_register) { actor_register_ = actor_register; } void SetScheduleFunction(ScheduleFunction schedule_function) { schedule_event = std::move(schedule_function); } void SetNowFunction(NowFunction now_function) { now = std::move(now_function); } void SetMonitoredActor(UUID monitored) { monitored_ = monitored; } virtual ~Observer() = default; protected: /// Observer can schedule events ScheduleFunction schedule_event; /// Observer can get current time NowFunction now; /// Observer can resolve actor UUID to an object using actor register const ActorRegister* actor_register_{}; /// Observer monitors some actor UUID monitored_{}; private: const std::string whoami_; }; } // namespace sim::events
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2008 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** @author Johannes Hoff jhoff@opera.com */ #ifndef MODULES_DOM_DOMSCOPECLIENT_H #define MODULES_DOM_DOMSCOPECLIENT_H #ifdef JS_SCOPE_CLIENT #include "modules/scope/scope_client.h" class ES_Value; class DOM_Runtime; class ES_Object; class JS_ScopeClient : public OpScopeClient { DOM_Runtime *owner; // callbacks ES_Object *cb_host_connected; ES_Object *cb_receive; ES_Object *cb_host_quit; class ServiceCallback : public Link { public: ServiceCallback(unsigned int tag, ES_Object *cb_service_enabled) : tag(tag) , cb_service_enabled(cb_service_enabled) {} unsigned int tag; ES_Object *cb_service_enabled; }; Head serviceCallbacks; // Contains ServiceCallback objects. enum State { /** * Client is not connected to a scope host and is waiting for a * connection in OnHostAttached(). This is the initial state. */ State_Idle /** * Client is waiting for the service list from the scope host. */ , State_ServiceList /** * The service list has been receieved and a scope.Connect call has * been made to the scope host, awaiting the response to the message. */ , State_ConnectResponse /** * Connect response was receievied, client is fully connected to the * scope host and normal processing may occur. */ , State_Connected }; State state; unsigned tag_counter; // Used to get a unique tag to be used internally, ie. not the DOM client itself. unsigned connect_tag; OpString service_list; BOOL host_quit_sent; OP_STATUS SetString(ES_Value *value, ByteBuffer *data, TempBuffer &tmp); /** * Disconnects the client from the JS script by calling the quit-callback. * Does nothing if @a host_quit_sent has been set to @c TRUE. */ OP_STATUS DisconnectJS(); public: JS_ScopeClient(DOM_Runtime *origining_runtime); /** * Disconnects the client from the host. * * @note If the JS client is to be notified of the client being removed it * must be done by calling Disconnect() before deleting the object. */ ~JS_ScopeClient(); OP_STATUS Construct(ES_Object *host_connected, ES_Object *host_receive, ES_Object *host_quit); virtual OP_STATUS EnableService(const uni_char *name, ES_Object *cb_service_enabled, unsigned int tag); /** * Disconnects the client from scope and optionally notifies the JS code * by calling the quit-callback. * * @param allow_js If @c TRUE then it will call the quit-callback * (unless already called), if @c FALSE it will only * disconnect from scope. */ void Disconnect(BOOL allow_js); virtual const uni_char *GetType() const { return UNI_L("javascript"); }; // From OpScopeClient virtual OP_STATUS OnHostAttached(OpScopeHost *host); virtual OP_STATUS OnHostDetached(OpScopeHost *host); virtual OP_STATUS OnHostMissing(); virtual OP_STATUS Receive(OpAutoPtr<OpScopeTPMessage> &message); virtual OP_STATUS Serialize(OpScopeTPMessage &to, const OpProtobufInstanceProxy &from, OpScopeTPHeader::MessageType type); virtual OP_STATUS Parse(const OpScopeTPMessage &from, OpProtobufInstanceProxy &to, OpScopeTPError &error); static OP_STATUS SerializeECMAScript(OpScopeTPMessage &msg, const OpProtobufInstanceProxy &proxy, ES_Runtime *runtime); OP_STATUS OnServices(OpAutoPtr<OpScopeTPMessage> &message); OP_STATUS OnQuit(); OP_STATUS OnHostConfigured(); }; #endif // JS_SCOPE_CLIENT #endif // MODULES_DOM_DOMSCOPECLIENT_H
#include<vector> using std::vector; #include<iostream> #include<algorithm> #include<memory> using std::shared_ptr; #include<string> using std::string; #include<stack> using std::stack; #include<queue> using std::priority_queue; #include<unordered_map> using std::unordered_map; /* Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") ¡ú false isMatch("aa","aa") ¡ú true isMatch("aaa","aa") ¡ú false isMatch("aa", "*") ¡ú true isMatch("aa", "a*") ¡ú true isMatch("ab", "?*") ¡ú true isMatch("aab", "c*a*b") ¡ú false */ class Solution { public: bool isMatch(string s, string p) { dp.resize(s.size()+1); for (auto& elems : dp)elems.resize(p.size()+1,-1); return isMatchImp(s, p, 0, 0); } private: vector<vector<int>> dp; bool isMatchImp(const string& s, const string&p, int si, int pi) { if (dp[si][pi] != -1)return dp[si][pi] == 1; if (si == s.size() && pi == p.size()) { dp[si][pi] = 1; return true; }; if ((si != s.size()) && (pi == p.size())) { dp[si][pi] = 0; return false; } if ((si == s.size()) && (pi != p.size())) { while (pi < p.size() && p[pi] == '*')pi++; if (pi == p.size()) { dp[si][pi] = 1; return true; } else { dp[si][pi] = 0; return false; } } if (s[si] == p[pi] || p[pi]=='?') { bool res = isMatchImp(s, p, si + 1, pi + 1); dp[si][pi] = res ? 1 : 0; return dp[si][pi]; } else if (p[pi]=='*'){ while (pi + 1 < p.size() && p[pi + 1] == '*')pi++; for (int nsi = si; nsi <= s.size(); nsi++) { bool res = isMatchImp(s, p, nsi, pi + 1); if (res) { dp[si][pi] = 1; return res; } } dp[si][pi] = 0; return false; } else { dp[si][pi] = 0; return false; } } }; int main() { Solution s; vector<int> i({ 0,2,0 }); std::cout<<s.isMatch("a","a*"); return 0; }
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(){ int A, B, K; cin >> A >> B >> K; for(int i = 0; i < K; i++) { int tmp; if (i % 2 == 0){ //A->B A -= A % 2; tmp = A / 2; A -= tmp; B += tmp; }else{ //B->A B -= B % 2; tmp = B / 2; B -= tmp; A += tmp; } } cout << A << " " << B << endl; }
#include "NecromancerAttack.h" NecromancerAttack::NecromancerAttack() { std::cout << " creating NecromancerAttack " << std::endl; } NecromancerAttack::~NecromancerAttack() { std::cout << " deleting NecromancerAttack " << std::endl; } // void NecromancerAttack::heal(Unit& ally, SpellCaster& healer) { // ally.takeTreatment(healer.getState().getTreatment() / 2); // }
/*10292*/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cassert> #include <vector> #include <string> #include <cmath> #include <algorithm> #include <list> #include <queue> #include <set> #include <cstdlib> #include <cmath> using namespace std; typedef vector<int> Vint; int main() { int n; Vint Tian, King; Tian.reserve(1000); King.reserve(1000); while (cin >> n) { if (n == 0) { break; } Tian.resize(n); King.resize(n); for (Vint::iterator iter = Tian.begin(); iter != Tian.end(); iter++) { cin >> (*iter); } for (Vint::iterator iter = King.begin(); iter != King.end(); iter++) { cin >> (*iter); } } return 0; }
#include<stdlib.h> #include<math.h> #include <iostream> using namespace std; int no_of_distinct_prime_factor(long); int no_of_distinct_prime_factor(long); int is_prime(long); int main() { long c=4,i,tmp,j; int flag; for(i=2;;i++) { flag=1; for(j=0;j<c;j++) if(!(c==no_of_distinct_prime_factor(i+j))) { flag=0; break; } if(flag) { cout << "Answer = " << i << endl; break; } } } int no_of_distinct_prime_factor(long n) { int i,counter=0; long product=1; if(is_prime(n)) return 1; for(i=2;i<=n/2;i++) { if(product*i > n) break; if(n%i==0 && is_prime(i)) { product*=i; counter++; } } return counter; } int is_prime(long n) { int i; for(i=2;i<=(long)sqrt((double)n);i++) if(n%i==0) return 0; return 1; }
#include<bits/stdc++.h> #include<string.h> using namespace std; void dupli(char string[]){ if (string[0] == '\0') return; if (string[0] == string[1]){ int i = 0; while (string[i] != '\0'){ string[i] = string[i + 1]; i++; } dupli(string); } dupli(string + 1); } int main(){ char string[20]; cout<<"Enter the string : "; cin>>string; cout<<"String before removing the duplicates : "<<string<<endl; dupli(string); cout<<"String after removing the duplicates : "<<string<<endl; return 0; }
#ifndef TREEFACE_UNIVERSAL_VALUE_H #define TREEFACE_UNIVERSAL_VALUE_H #include "treeface/gl/Enums.h" #include "treeface/gl/TypeUtils.h" #include "treeface/math/Vec2.h" #include "treeface/math/Vec3.h" #include "treeface/math/Vec4.h" #include "treeface/math/Mat2.h" #include "treeface/math/Mat3.h" #include "treeface/math/Mat4.h" class TestFramework; namespace treeface { class UniversalValue { friend class ::TestFramework; union UniversalValueData { UniversalValueData() {} UniversalValueData( const UniversalValueData &peer ) { memcpy( this, &peer, sizeof(UniversalValueData) ); } UniversalValueData( GLbyte value ): i8( value ) {} UniversalValueData( GLubyte value ): ui8( value ) {} UniversalValueData( GLshort value ): i16( value ) {} UniversalValueData( GLushort value ): ui16( value ) {} UniversalValueData( GLint value ): i32( value ) {} UniversalValueData( GLuint value ): ui32( value ) {} UniversalValueData( GLfloat value ): f32( value ) {} UniversalValueData( GLdouble value ): f64( value ) {} UniversalValueData( const Vec2f &value ): vec2( value ) {} UniversalValueData( const Vec3f &value ): vec3( value ) {} UniversalValueData( const Vec4f &value ): vec4( value ) {} UniversalValueData( const Mat2f &value ): mat2( value ) {} UniversalValueData( const Mat3f &value ): mat3( value ) {} UniversalValueData( const Mat4f &value ): mat4( value ) {} GLbyte i8; GLubyte ui8; GLshort i16; GLushort ui16; GLint i32; GLuint ui32; GLfloat f32; GLdouble f64; Vec2f vec2; Vec3f vec3; Vec4f vec4; Mat2f mat2; Mat3f mat3; Mat4f mat4; }; public: UniversalValue() noexcept {} UniversalValue( GLType type ) noexcept: m_type( type ) {} UniversalValue( bool value ) noexcept : m_type( TFGL_TYPE_BOOL ) , m_data( GLboolean( value ) ) {} UniversalValue( GLbyte value ) noexcept : m_type( TFGL_TYPE_BYTE ) , m_data( value ) {} UniversalValue( GLubyte value ) noexcept : m_type( TFGL_TYPE_UNSIGNED_BYTE ) , m_data( value ) {} UniversalValue( GLshort value ) noexcept : m_type( TFGL_TYPE_SHORT ) , m_data( value ) {} UniversalValue( GLushort value ) noexcept : m_type( TFGL_TYPE_UNSIGNED_SHORT ) , m_data( value ) {} UniversalValue( GLint value ) noexcept : m_type( TFGL_TYPE_INT ) , m_data( value ) {} UniversalValue( GLuint value ) noexcept : m_type( TFGL_TYPE_UNSIGNED_INT ) , m_data( value ) {} UniversalValue( GLfloat value ) noexcept : m_type( TFGL_TYPE_FLOAT ) , m_data( value ) {} UniversalValue( GLdouble value ) noexcept : m_type( TFGL_TYPE_DOUBLE ) , m_data( value ) {} UniversalValue( const Vec2f& value ) noexcept : m_type( TFGL_TYPE_VEC2F ) , m_data( value ) {} UniversalValue( const Vec3f& value ) noexcept : m_type( TFGL_TYPE_VEC3F ) , m_data( value ) {} UniversalValue( const Vec4f& value ) noexcept : m_type( TFGL_TYPE_VEC4F ) , m_data( value ) {} UniversalValue( const Mat2f& value ) noexcept : m_type( TFGL_TYPE_MAT2F ) , m_data( value ) {} UniversalValue( const Mat3f& value ) noexcept : m_type( TFGL_TYPE_MAT3F ) , m_data( value ) {} UniversalValue( const Mat4f& value ) noexcept : m_type( TFGL_TYPE_MAT4F ) , m_data( value ) {} /// /// \brief copy constructor /// UniversalValue( const UniversalValue& peer ) noexcept : m_type( peer.m_type ) , m_data( peer.m_data ) {} ~UniversalValue() noexcept {} GLType get_type() const noexcept { return m_type; } UniversalValue& operator =( const UniversalValue& peer ) noexcept { m_type = peer.m_type; memcpy( &m_data, &peer.m_data, sizeof(m_data) ); return *this; } UniversalValue& operator =( GLbyte value ) noexcept { treecore_assert( m_type == TFGL_TYPE_BYTE ); m_data.i8 = value; return *this; } UniversalValue& operator =( GLubyte value ) noexcept { treecore_assert( m_type == TFGL_TYPE_UNSIGNED_BYTE ); m_data.ui8 = value; return *this; } UniversalValue& operator =( GLshort value ) noexcept { treecore_assert( m_type == TFGL_TYPE_SHORT ); m_data.i16 = value; return *this; } UniversalValue& operator =( GLushort value ) noexcept { treecore_assert( m_type == TFGL_TYPE_UNSIGNED_SHORT ); m_data.ui16 = value; return *this; } UniversalValue& operator =( GLint value ) noexcept { treecore_assert( m_type == TFGL_TYPE_INT ); m_data.i32 = value; return *this; } UniversalValue& operator =( GLuint value ) noexcept { treecore_assert( m_type == TFGL_TYPE_UNSIGNED_INT ); m_data.ui32 = value; return *this; } UniversalValue& operator =( GLfloat value ) noexcept { treecore_assert( m_type == TFGL_TYPE_FLOAT ); m_data.f32 = value; return *this; } UniversalValue& operator =( GLdouble value ) noexcept { treecore_assert( m_type == TFGL_TYPE_DOUBLE ); m_data.f64 = value; return *this; } UniversalValue& operator =( const Vec2f& value ) noexcept { treecore_assert( m_type == TFGL_TYPE_FLOAT_VEC2 ); m_data.vec2 = value; return *this; } UniversalValue& operator =( const Vec3f& value ) noexcept { treecore_assert( m_type == TFGL_TYPE_FLOAT_VEC3 ); m_data.vec3 = value; return *this; } UniversalValue& operator =( const Vec4f& value ) noexcept { treecore_assert( m_type == TFGL_TYPE_FLOAT_VEC4 ); m_data.vec4 = value; return *this; } UniversalValue& operator =( const Mat2f& value ) noexcept { treecore_assert( m_type == TFGL_TYPE_FLOAT_MAT2 ); m_data.mat2 = value; return *this; } UniversalValue& operator =( const Mat3f& value ) noexcept { treecore_assert( m_type == TFGL_TYPE_FLOAT_MAT3 ); m_data.mat3 = value; return *this; } UniversalValue& operator =( const Mat4f& value ) noexcept { treecore_assert( m_type == TFGL_TYPE_FLOAT_MAT4 ); m_data.mat4 = value; return *this; } operator GLbyte() const noexcept { treecore_assert( m_type == TFGL_TYPE_BYTE ); return m_data.i8; } operator GLubyte() const noexcept { treecore_assert( m_type == TFGL_TYPE_UNSIGNED_BYTE ); return m_data.ui8; } operator GLshort() const noexcept { treecore_assert( m_type == TFGL_TYPE_SHORT ); return m_data.i16; } operator GLushort() const noexcept { treecore_assert( m_type == TFGL_TYPE_UNSIGNED_SHORT ); return m_data.ui16; } operator GLint() const noexcept { treecore_assert( m_type == TFGL_TYPE_INT ); return m_data.i32; } operator GLuint() const noexcept { treecore_assert( m_type == TFGL_TYPE_UNSIGNED_INT ); return m_data.ui32; } operator GLfloat() const noexcept { treecore_assert( m_type == TFGL_TYPE_FLOAT ); return m_data.f32; } operator GLdouble() const noexcept { treecore_assert( m_type == TFGL_TYPE_DOUBLE ); return m_data.f64; } operator Vec2f() const noexcept { treecore_assert( m_type == TFGL_TYPE_VEC2F ); return m_data.vec2; } operator Vec3f() const noexcept { treecore_assert( m_type == TFGL_TYPE_VEC3F ); return m_data.vec3; } operator Vec4f() const noexcept { treecore_assert( m_type == TFGL_TYPE_VEC4F ); return m_data.vec4; } operator Mat2f() const noexcept { treecore_assert( m_type == TFGL_TYPE_MAT2F ); return m_data.mat2; } operator Mat3f() const noexcept { treecore_assert( m_type == TFGL_TYPE_MAT2F ); return m_data.mat3; } operator Mat4f() const noexcept { treecore_assert( m_type == TFGL_TYPE_MAT2F ); return m_data.mat4; } bool operator ==( const UniversalValue& peer ) const; bool operator !=( const UniversalValue& peer ) const { return !operator ==( peer ); } private: GLType m_type; UniversalValueData m_data; }; } // namespace treeface #endif // TREEFACE_UNIVERSAL_VALUE_H
// // Created by faris on 4/28/2020. // #define DEGTORAD 0.0174532925199432957f #include "mylibrary/Bomb.h" #include "cinder/gl/gl.h" using namespace ci; Bomb::Bomb(b2World* world, const vec2& pos) { // b2Vec2 vertices[3]; // vertices[0].Set(0.0f, 0.0f); // vertices[1].Set(100.0f, 0.0f); // vertices[2].Set(0.0f, 100.0f); b2BodyDef myBodyDef; myBodyDef.type = b2_dynamicBody; myBodyDef.position.Set(pos.x, pos.y); m_body = world->CreateBody(&myBodyDef); GetShapeType = 6; bid = myapp::id++ + 700; m_body->SetUserData(this); b2CircleShape cs; cs.m_p.Set(0,0); cs.m_radius = 50.0f; b2FixtureDef fixtureDef; fixtureDef.shape = &cs; fixtureDef.density = 1.0f; fixtureDef.restitution = 0.0f; fixtureDef.friction = 0.0f; m_body->CreateFixture(&fixtureDef); m_contacting = false; }
#include<bits/stdc++.h> #define rep(i, s, n) for (int i = (s); i < (int)(n); i++) #define INF ((1LL<<62)-(1LL<<31)) /*オーバーフローしない程度に大きい数*/ #define MOD 1000000007 using namespace std; using ll = long long; using Graph = vector<vector<int>>; using pint = pair<int,int>; const double PI = 3.14159265358979323846; const int dx[4] = {1,0,-1,0}; const int dy[4] = {0,1,0,-1}; int main(){ string S; cin >> S; //読みにくいとtrue bool ans = true; for(int i = 0; i < (int)S.size(); i++){ if(i % 2 == 0){ if(S.at(i) >= 'A' && S.at(i) <= 'Z'){ ans = false; break; } } else { if(S.at(i) >= 'a' && S.at(i) <= 'z'){ ans = false; break; } } } if(ans)cout << "Yes" << endl; else cout << "No" << endl; }
#include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<=e;i++) //including end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define sful(a) scanf("%llu",&a); #define sfulul(a,b) scanf("%llu %llu",&a,&b); #define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different #define sfc(a) scanf("%c",&a); #define sfs(a) scanf("%s",a); #define getl(s) getline(cin,s); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define vi vector<int> #define vll vector<ll> #define mii map<int,int> #define mlli map<ll,int> #define mib map<int,bool> #define fs first #define sc second #define CASE(t) printf("Case %d: ",++t) // t initialized 0 #define cCASE(t) cout<<"Case "<<++t<<": "; #define D(v,status) cout<<status<<" "<<v<<endl; #define INF 1000000000 //10e9 #define EPS 1e-9 #define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c ) #define CONTEST 1 using namespace std; //Bitwise Sieve #define mx 10000005 /* n = p1^a1*p2^a2*p3^a3.. lets say, x = p1^x1*p2^x2*p3^x3.. y = p1^y1*p2^y2*p3^y3.. Now, a1 = max(x1,y1) [definition of LCM] So, at least one of x1,y1 must be = a1. Now, how many ways we can pair up the p1? Lets work with an example, n = 3^2*2^1 = 18 Pairings of 3 => (x),(y) 3^2,1 3^2,3 3^2,3^2 1,3^2 3,3^2 possible ways = 2*2+1 = 5 = 2*(a1+1) - 1(3^2,3^2 can't be repeated) Pairings of 2 => (x),(y) 2,1 1,2 2,2 possible ways = 2*1+1 = 3 = 2*(a2+1) - 1(2^1,2^1 can't be repeated) Now, when we combine these two sets we get, 18,1 9,2 18,2 ------ 18,3 9,6 18,6 ------ 18,9 9,18 18,18 ------ 2,9 1,18 2,18 ------ 18,3 9,6 18,6 ------ We observe that, in the list every tuple appears twice except (18,18). And we want to find the number of pairs, so we add 1 (only one (18,18) tuple) to make all tuples appear twice. Then, ans = the number of tuples/2 */ int prm[(mx/32)+5]; vector<int>prmls; bool Check(int N,int pos){return (bool)(N & (1<<pos));} int Set(int N,int pos){ return N=N | (1<<pos) ;} void BWsieve() { int i, j; prmls.pb(2); for( i = 3; i <= 10000000; i += 2 ) { if( Check(prm[i>>5],i&31)==0) { prmls.pb(i); if(i<=3165) for( j = i*i; j <= 10000000; j += (i<<1) ) { prm[j>>5]=Set(prm[j>>5],j & 31) ; } } } } int main() { int tc,cas=0; sfi(tc); BWsieve(); while(tc--) { ll n; sfl(n); ll ans = 1; ll sq = sqrt(n)+1; for(int i=0; i<prmls.size() && prmls[i]<=sq; i++) { ll cnt = 0; while(n%prmls[i]==0) { cnt++; n/=prmls[i]; } sq = sqrt(n); ans*=(2*cnt+1); } if(n>1) { ans*=3; } ans++; ans/=2; CASE(cas); pf("%lld\n",ans); } return 0; }
#include "network_query_list.h" #include <uriparser/Uri.h> #include <vector> #include <string> namespace ioremap { namespace swarm { class network_query_list_private { public: std::vector<std::pair<std::string, std::string> > items; }; network_query_list::network_query_list() : p(new network_query_list_private) { } network_query_list::network_query_list(const std::string &query) : p(new network_query_list_private) { set_query(query); } network_query_list::~network_query_list() { } void network_query_list::set_query(const std::string &query) { int item_count = 0; UriQueryListA *query_list = NULL; uriDissectQueryMallocA(&query_list, &item_count, query.c_str(), query.c_str() + query.size()); p->items.clear(); p->items.reserve(item_count); for (auto it = query_list; it; it = it->next) { p->items.emplace_back(it->key, it->value); } uriFreeQueryListA(query_list); } std::string network_query_list::to_string() const { if (p->items.empty()) return std::string(); std::vector<UriQueryListA> items(p->items.size()); for (size_t i = 0; i < p->items.size(); ++i) { auto &list_entry = items[i]; auto &item = p->items[i]; list_entry.key = item.first.c_str(); list_entry.value = item.second.c_str(); if (i + 1 < p->items.size()) list_entry.next = &items[i + 1]; else list_entry.next = NULL; } int requiredSize = 0; uriComposeQueryCharsRequiredA(&items[0], &requiredSize); std::string result; result.resize(requiredSize); uriComposeQueryA(&result[0], &items[0], result.size(), &requiredSize); result.resize(requiredSize); return result; } size_t network_query_list::count() const { return p->items.size(); } std::pair<std::string, std::string> network_query_list::item(size_t index) const { return p->items[index]; } void network_query_list::add_item(const std::string &key, const std::string &value) { p->items.emplace_back(key, value); } void network_query_list::remove_item(size_t index) { p->items.erase(p->items.begin() + index); } bool network_query_list::has_item(const std::string &key) const { for (size_t i = 0; i < p->items.size(); ++i) { if (p->items[i].first == key) return true; } return false; } std::string network_query_list::item_value(const std::string &key) const { for (size_t i = 0; i < p->items.size(); ++i) { if (p->items[i].first == key) return p->items[i].second; } return std::string(); } } // namespace swarm } // namespace ioremap
#include "stdafx.h" #include "Ara.h" Ara::Ara() { } Ara::~Ara() { }
#include <iostream> void drawM(char** &arr, char simbol, int chap) { for(int i = 0; i < chap; ++i) { arr[i][0] = simbol; } for(int i = 0;i < chap; ++i) { arr[i][chap -1] = simbol; } if(0 != chap % 2) { for(int i = 1;i <= chap / 2; ++i) { arr[i][i] = simbol; } for(int i = 1;i <= chap / 2; ++i) { arr[i][chap - 1 - i] = simbol; } } else { for(int i = 1;i < chap / 2; ++i) { arr[i][i] = simbol; } for(int i = 1;i < chap / 2; ++i) { arr[i][chap - 1 - i] = simbol; } } } int draw(char** &arr, char simbol) { int chap = 0; int m = 0; std::cout<<"Mutqagrel zangvaci chap@ (nax@ntreli e kent tiv)-> "; std::cin>>chap; if(3 > chap) { return 1; } else { arr = new char*[chap]; for(int i = 0;i < chap; ++i) { arr[i] = new char[chap]; } for(int i = 0;i < chap; ++i) { for(int j = 0;j < chap; ++j) { arr[i][j] = ' '; } } drawM(arr, simbol, chap); return chap; } } void replace(char** &arr, int l, char& simb, char simbN) { if((int)simb != (int)simbN) { for(int i = 0; i < l; ++i) { for(int j = 0; j < l; ++j) { if((int)simb == (int)arr[i][j]) { arr[i][j] = simbN; } } } for(int i = 0; i < l; ++i) { for(int j = 0; j < l; ++j) { std::cout<<arr[i][j]<<' '; } std::cout<<'\n'; } simb = simbN; } else { std::cout<<"Nuyn simvolneq mutqagrel \n"; } } int main() { char** arr; char simb; char simbN; std::cout<<"@ntrel simvol -> "; std::cin>>simb; int size = draw(arr, simb); if( 1 != size) { for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { std::cout<<arr[i][j]<<' '; } std::cout<<'\n'; } do { std::cout<<"Durs galu hamar mutqagreq E \n"; std::cout<<"Mutqagreq nor simvol@ -> "; std::cin>>simbN; replace(arr, size, simb, simbN); } while((int)'E' != (int)simbN); } else { std::cout<<"Sxal mutqagrum \n"; } for(int i = 0; i < size; ++i) { delete arr[i]; } delete [] arr; return 0; }
#include <iostream> using namespace std; bool isPrime(int x){ int cnt = 0; for(int i = 1; i <= x; ++i){ if(x % i == 0){ cnt++; } } if(cnt == 2) return true; return false; } void run_all_test(){ int tests[] = {1,2,3,4,5,6,7,8,9,10}; int answers[] = {0,1,1,0,1,0,1,0,0,0}; for(int i = 0; i < 10; ++i){ if(isPrime(tests[i]) == answers[i]){ cout << "test " << i + 1 << " passed!" << endl; }else{ cout << "test " << i + 1 << " failed!" << endl; } } } int main(int argc, char ** argv){ if(argc > 1){ run_all_test(); }else{ int x; cin >> x; cout << isPrime(x) << endl; } return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const int maxn = 1e6 + 100; long long n,seed; LL x,y; LL maxl,minl,maxr,minr; long long rand(long long l, long long r) { static long long mo=1e9+7, g=78125; return l+((seed*=g)%=mo)%(r-l+1); } int main() { int t; scanf("%d",&t); while (t--) { cin >> n >> seed; maxl = maxr = -3e9; minl = minr = 3e9; for (int i = 0; i < n; i++) { x = rand(-1000000000, 1000000000); y = rand(-1000000000, 1000000000); maxl = max(maxl,x+y); minl = min(minl,x+y); maxr = max(maxr,x-y); minr = min(minr,x-y); } printf("%d\n",max(maxl-minl,maxr-minr)); } return 0; }
#pragma once #include "../System.hpp" #include "Special/gameOver.hpp" namespace States { class MainMenu { public: static int8_t run(void) { int8_t selected = 0; int8_t menu = 0; while (true) { if( keyUp::isJustPressed() ) selected--; if( keyDown::isJustPressed() ) selected++; if( keyLeft::isJustPressed() ) { menu--; selected = 0; } if( keyRight::isJustPressed() ) { menu++; selected = 0; } if( keyA::isJustPressed() ) { if(selected == 0 && menu == 1) Light::toogle(); if(selected == 1 && menu == 1) SpecialStates::GameOver::clear(); if(menu == 0) return selected; } if(menu == -1) menu = 1; if(menu == 3) menu = 0; if(menu == 0 && selected == -1) selected = 2; if(menu == 1 && selected == -1) selected = 1; if(menu == 1 && selected == 2) selected = 0; if(menu == 0 && selected == 3) selected = 0; Display::clear(); Display::drawBorder(); Display::drawRectangle(0,Display::Hight-11,Display::Width,11,Display::Color::Black); Display::drawBitmap(2,39,6, 8, Display::LeftArrow, true ); Display::drawBitmap(84-5-2,39,6,8 , Display::RightArrow, true ); Display::drawBitmap(2,5+(10*selected),6,8, Display::RightArrow ); if(menu == 0) { Display::drawText( Display::Width/2-5*6/2,Display::Hight-9, _str("GAMES") ,true); Display::drawText( 10,5,_str("4096")); Display::drawText( 10,15,_str("FLAPPY BIRD")); Display::drawText( 10,25,_str("ARKANOID")); } else { Display::drawText( Display::Width/2-8*6/2,Display::Hight-9, _str("SETTINGS") ,true); Display::drawText( 10,5,_str("TOGGLE LIGHT")); Display::drawText( 10,15,_str("CLEAR SCORE")); } Display::display(); } } private: }; }
#include "Player.h" #include <stdio.h> #include <iostream> using namespace std; void Player::_generageDef(int def) { // Player defence does not decrease gradually because he is the main player and the game will become really hard. _defence = def; } Player::Player() { _x = 0; _y = 0; } void Player::init(int level, int health, int attack, int defence, int experience) { _level = level; _health = health; _attack = attack; _defence = defence; _experience = experience; } void Player::setPosition(int x, int y) { _x = x; _y = y; } void Player::getPosition(int & x, int & y) { x = _x; y = _y; } int Player::getPlayerAttack() { return _attack; } void Player::addExp(int exp) { _experience += exp; while (_experience > 50) { printf("Leveled up!\n"); _experience -= 50; _attack += 10; _health += 10; _defence += 20; _level++; system("PAUSE"); } } int Player::takeDamage(int attack) { int originalDef = _defence; int temp = attack; attack -= _defence; if (attack <= 0) { _defence -= temp; return 0; } _health -= attack; if (_health > 0) { return 0; } else return 1; } Player::~Player() { }
#ifndef AS64_GMP_ORIENT_H_ #define AS64_GMP_ORIENT_H_ // GMPo class // For encoding Cartesian Orientation. // #include <gmp_lib/GMP/GMP.h> #include <gmp_lib/GMP/GMP_nDoF.h> #include <gmp_lib/utils.h> namespace as64_ { namespace gmp_ { class GMPo : public GMP_nDoF { // =================================== // ======= Public Functions ======== // =================================== public: /* Constructs a GMP defined in the quat-log space. * @param[in] N_kernels: vector with the number of kernels for each dim of the quat log. * @param[in] D: vector with the damping for each dim of the quat log. * @param[in] K: vector with the stiffness for each dim of the quat log. * @param[in] kernels_std_scaling: Scaling for std of kernels (optional, default=2). * \note: Each of the arguments 'N_kernels', 'D', 'K' can be 1x1 or a 3x1 vector. * If a 1x1 vector is passed, the same value is passed to all three dim of quat log. */ GMPo(arma::uvec N_kernels, arma::vec D, arma::vec K, double kernels_std_scaling=1.0); /* Trains the GMPo. * @param[in] train_method: the training method to use, as a string ('LWR', 'LS'). * @param[in] Time: Row vector with the timestamps of the training data points. * @param[in] Quat_data: Matrix with the desired unit quaternion (4x1 vector) in each column. * @param[out] train_error: The training error expressed as the mse error. */ void train(const std::string &train_method, const arma::rowvec &Time, const arma::mat &Quat_data, arma::vec *train_error=0); // See @GMP_nDoF::update // void update(const gmp_::Phase &s, const arma::vec &y, const arma::vec &z, arma::vec y_c=arma::vec({0}), arma::vec z_c=arma::vec({0})); // See @GMP_nDoF.getYdot // arma::vec getYdot() const; // See @GMP_nDoF.getYdot // arma::vec getZdot() const; // See @GMP_nDoF.getYdot // arma::vec getYddot(arma::vec yc_dot=arma::vec({0})) const; // See @GMP_nDoF.getYdot // arma::vec calcYddot(const gmp_::Phase &s, const arma::vec &y, const arma::vec &y_dot, arma::vec yc=arma::vec({0}), arma::vec zc=arma::vec({0}), arma::vec yc_dot=arma::vec({0})) const; // See @GMP_nDoF.getYdot // unsigned numOfKernels(int i) const; /* Sets the initial orientation. * @param[in] Q0: Initial orientation (as unit quaternion). */ void setQ0(const arma::vec &Q0); arma::vec getQd0() const { return Qd0; } arma::vec getQdf() const { return q2quat(getYdf(),Qd0); } /* Sets goal/target orientation. * @param[in] Qg: Goal/target orientation (as unit quaternion). */ void setQg(const arma::vec &Qg); // See @GMP_nDoF.deepCopy // cp_obj = deepCopy() arma::vec getQd(double x) const; arma::vec getRotVeld(double x, double x_dot) const; arma::vec getRotAcceld(double x, double x_dot, double x_ddot) const; // See @GMP_nDoF.getYd // arma::vec getYd(double x) const; // See @GMP_nDoF.getYdDot // arma::vec getYdDot(double x, double x_dot) const; // See @GMP_nDoF.getYdDDot // arma::vec getYdDDot(double x, double x_dot, double x_ddot) const; arma::vec getRotVel(const arma::vec &Q) const; arma::vec getRotAccel(const arma::vec &Q, double tau_dot=0, const arma::vec &Yc_dot=arma::vec().zeros(3)) const; arma::vec calcRotAccel(const gmp_::Phase &s, const arma::vec &Q, const arma::vec &rotVel, const arma::vec &Qg, const arma::vec &Yc=arma::vec().zeros(3), const arma::vec &Zc=arma::vec().zeros(3), const arma::vec &Yc_dot=arma::vec().zeros(3)) const; arma::vec getY(const arma::vec &Q) const; arma::vec getZ(const arma::vec &rotVel, const arma::vec &Q) const; /* Export the GMP model to a file. * @param[in] filename: The name of the file. */ void exportToFile(const std::string &filename) const; /* Import a GMP model from a file. * @param[in] filename: The name of the file. */ static std::shared_ptr<GMPo> importFromFile(const std::string &filename); /* Write the GMP model to a file. * @param[in] fid: Object of type @FileIO associated with the file. * @param[in] prefix: The prefix that will be used for writing the names of all GMP params (optional, default=""). */ void writeToFile(FileIO &fid, const std::string &prefix="") const; /* Reads the GMP model from a file. * @param[in] fid: Object of type @FileIO associated with the file. * @param[in] prefix: The prefix that will be used for reading the names of all GMP params (optional, default=""). */ void readFromFile(FileIO &fid, const std::string &prefix=""); // =========================================================== // *********************************************************** // ************ Static Public Functions ************ // *********************************************************** // =========================================================== /* Expresses a given quaternion w.r.t. the initial orientation. * @param[in] Q: Orientation as unit quaternion. * @param[in] Q0: Initial quaternion. * @return: The orientation w.r.t. Q0, i.e. Q1 = Q*Q0^{-1}. */ static arma::vec quatTf(const arma::vec &Q, const arma::vec &Q0); /* Returns the log of a given orientation w.r.t. the initial orientation. * @param[in] Q: Orientation as unit quaternion. * @param[in] Q0: Initial quaternion. * @return: The logarithm of the Q w.r.t. Q0, i.e. q = log(Q*Q0^{-1}). */ static arma::vec quat2q(const arma::vec &Q, const arma::vec &Q0); /* Returns the quaternion Q given the initial orientation Q0 and the log of Q w.r.t. Q0. * @param[in] q: Logarithm of orientation w.r.t. the initial orientation. * @param[in] Q0: Initial orientation. * @return: The orientation corresponding to log, i.e. Q = exp(q)*Q0 */ static arma::vec q2quat(const arma::vec &q, const arma::vec &Q0); /* Returns derivative of log given the rotational velocity and orientation (expressed w.r.t. the initial orientation) * @param[in] rotVel: Rotational velocity. * @param[in] Q1: Orientation expressed w.r.t. the initial orientation. * @return: Derivative of log. */ static arma::vec rotVel2qdot(const arma::vec &rotVel, const arma::vec &Q1); /** \brief TODO doc.*/ static arma::vec qdot2rotVel(const arma::vec &qdot, const arma::vec &Q1); /** \brief TODO doc.*/ static arma::vec rotAccel2qddot(const arma::vec &rotAccel, const arma::vec &rotVel, const arma::vec &Q1); /** \brief TODO doc.*/ static arma::vec qddot2rotAccel(const arma::vec &ddeo, const arma::vec &rotVel, const arma::vec &Q1); /** \brief TODO doc.*/ static arma::mat jacobQq(const arma::vec &Q1); /** \brief TODO doc.*/ static arma::mat jacobqQ(const arma::vec &Q1); /** \brief TODO doc.*/ static arma::mat jacobDotqQ(const arma::vec &Q1, const arma::vec &rotVel); /** \brief TODO doc.*/ static arma::mat jacobDotQq(const arma::vec &Q1, const arma::vec &rotVel); // ======================================= // ======= Protected Properties ======== // ======================================= protected: arma::vec Q0; ///< initial orientation (as unit quaternion) arma::vec Qd0; ///< initial demonstrated orientation (as unit quaternion) // ======= Static properties ======== static double zero_tol; }; } // namespace gmp_ } // namespace as64_ #endif // AS64_GMP_ORIENT_H_
#ifndef AS64_gmp_MATH_LIB_H #define AS64_gmp_MATH_LIB_H #include <Eigen/Dense> #include <armadillo> namespace as64_ { namespace gmp_ { Eigen::Vector4d quatInv(const Eigen::Vector4d &quat); arma::vec quatInv(const arma::vec &quat); Eigen::Matrix4d quat2mat(const Eigen::Vector4d &quat); Eigen::Vector4d quatProd(const Eigen::Vector4d &quat1, const Eigen::Vector4d &quat2); arma::vec quatProd(const arma::vec &quat1, const arma::vec &quat2); Eigen::Vector4d quatExp(const Eigen::Vector3d &v_rot, double zero_tol=1e-16); arma::vec quatExp(const arma::vec &v_rot, double zero_tol=1e-16); Eigen::Vector3d quatLog(const Eigen::Vector4d &quat, double zero_tol=1e-16); arma::vec quatLog(const arma::vec &quat, double zero_tol=1e-16); } // namespace gmp_ } // namespace as64_ #endif // AS64_gmp_MATH_LIB_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef CREATE_REG_KEY_OPERATION_H #define CREATE_REG_KEY_OPERATION_H #include "adjunct/desktop_util/transactions/OpUndoableOperation.h" #include "platforms/windows/utils/authorization.h" /** * Undoable Registry key creation. * * @author Wojciech Dzierzanowski (wdzierzanowski) * @see OpTransaction */ class CreateRegKeyOperation : public OpUndoableOperation { public: /** * Constructs the operation object. * * @param ancestor_handle a handle to the ancestor key of the key to be * created * @param key_name the name of the key to be created, relative to * @a ancestor_handle */ CreateRegKeyOperation(HKEY ancestor_handle, const OpStringC& key_name); ~CreateRegKeyOperation(); virtual OP_STATUS Do(); virtual void Undo(); /** * @return ancestor_handle a handle to the ancestor key of the key to be * created */ HKEY GetAncestorHandle() const; /** * @return key_name the name of the key to be created, relative to the * ancestor handle */ const OpStringC& GetKeyName() const; private: const HKEY m_ancestor_handle; OpString m_key_name; WindowsUtils::RestoreAccessInfo* m_restore_access_info; }; #endif // CREATE_REG_KEY_OPERATION_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2008-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef CRYPTO_HASH_IMPL_H #define CRYPTO_HASH_IMPL_H #include "modules/libcrypto/include/CryptoHash.h" #ifdef CRYPTO_HASH_MD5_USE_CORE_IMPLEMENTATION #include "modules/libopeay/openssl/cryptlib.h" #include "modules/libopeay/openssl/md5.h" class CryptoHashMD5: public CryptoHash { public: CryptoHashMD5(){}; virtual inline ~CryptoHashMD5(); virtual inline OP_STATUS InitHash(); virtual inline void CalculateHash(const UINT8 *source, int len); virtual inline void CalculateHash(const char *source); virtual inline int BlockSize() { return 64; } virtual inline int Size() { return MD5_DIGEST_LENGTH; } virtual inline void ExtractHash(UINT8 *result); private: MD5_CTX m_md5_state; }; #endif // CRYPTO_HASH_MD5_USE_CORE_IMPLEMENTATION #ifdef CRYPTO_HASH_SHA1_USE_CORE_IMPLEMENTATION #include "modules/libopeay/openssl/cryptlib.h" #include "modules/libopeay/openssl/sha.h" class CryptoHashSHA1: public CryptoHash { public: CryptoHashSHA1(){}; virtual inline ~CryptoHashSHA1(); virtual inline OP_STATUS InitHash(); virtual inline void CalculateHash(const UINT8 *source, int len); virtual inline void CalculateHash(const char *source); virtual inline int BlockSize() { return 64; } virtual inline int Size() { return SHA_DIGEST_LENGTH; } virtual inline void ExtractHash(UINT8 *result); private: SHA_CTX m_sha1_state; }; #endif // CRYPTO_HASH_SHA1_USE_CORE_IMPLEMENTATION #ifdef CRYPTO_HASH_SHA256_USE_CORE_IMPLEMENTATION #include "modules/libopeay/openssl/cryptlib.h" #include "modules/libopeay/openssl/sha.h" class CryptoHashSHA256: public CryptoHash { public: CryptoHashSHA256(){}; virtual inline ~CryptoHashSHA256(); virtual inline OP_STATUS InitHash(); virtual inline void CalculateHash(const UINT8 *source, int len); virtual inline void CalculateHash(const char *source); virtual inline int BlockSize() { return 64; } virtual inline int Size() { return SHA256_DIGEST_LENGTH; } virtual inline void ExtractHash(UINT8 *result); private: SHA256_CTX m_sha256_state; }; #endif // CRYPTO_HASH_SHA256_USE_CORE_IMPLEMENTATION #endif /* CRYPTO_HASH_IMPL_H */
// Created by Suraj Parkale BTech Computer Engineer // Student of Vishwakarma Institute of Information Technology, Pune #include<iostream> using namespace std; int main(){ int n; cout<<"Enter the number of elements : "; cin>>n; int a[n],k,j; for(int i=0;i<n;i++){ cin>>a[i]; } cout<<"The elements of the array are : "; for(int i=0;i<n;i++){ cout<<a[i]<<" "; } cout<<"\n"; for(int i=1;i<n;i++){ j = i - 1; while(j>=0 && a[j+1] < a[j]){ int temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; j--; } cout<<"The elements of the array are : "; for(int i=0;i<n;i++){ cout<<a[i]<<" "; } cout<<"\n"; } cout<<"The elements of the array are : "; for(int i=0;i<n;i++){ cout<<a[i]<<" "; } cout<<"\n"; return 0; } /* Time Complexity: O(n*2) Auxiliary Space: O(1) Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted. Algorithmic Paradigm: Incremental Approach Sorting In Place: Yes Stable: Yes Online: Yes Uses: Insertion sort is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array. What is Binary Insertion Sort? We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort uses binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sorting takes O(i) (at ith iteration) in worst case. We can reduce it to O(logi) by using binary search. The algorithm, as a whole, still has a running worst case running time of O(n2) because of the series of swaps required for each insertion. */
#ifndef image_tga_hpp #define image_tga_hpp #include <fstream> #include "color.hpp" namespace image { class TGA { public: enum Format { GRAYSCALE = 1, RGB = 3, RGBA = 4 }; TGA(); TGA(int w, int h, int bpp); TGA(const TGA& image); TGA& operator=(const TGA& image); ~TGA(); bool read_tga_file(const char* filename); bool write_tga_file(const char* filename, bool rle = true); bool flip_horizontally(); bool flip_vertically(); bool scale(int w, int h); Color get(int x, int y); bool set(int x, int y, Color c); int get_width(); int get_height(); int get_bytespp(); unsigned char* buffer(); void clear(); protected: unsigned char* data; int width; int height; int bytespp; bool load_rle_data(std::ifstream& in); bool unload_rle_data(std::ofstream& out); }; } #endif // image_tga_hpp
$NetBSD$ Support NetBSD. --- scribus/util_debug.cpp.orig 2019-07-30 22:35:07.000000000 +0000 +++ scribus/util_debug.cpp @@ -24,7 +24,7 @@ for which a new license (GPL+exception) #include <QDateTime> #include <QtGlobal> -#if !defined(_WIN32) && !defined(Q_OS_MAC) +#if !defined(_WIN32) && !defined(Q_OS_MAC) && !defined(Q_OS_NETBSD) #include <execinfo.h> #include <cxxabi.h> #endif @@ -54,7 +54,7 @@ void tDebug(const QString& message) */ void printBacktrace ( int nFrames ) { -#if !defined(_WIN32) && !defined(Q_OS_MAC) && !defined(Q_OS_OPENBSD) && !defined(Q_OS_FREEBSD) +#if !defined(_WIN32) && !defined(Q_OS_MAC) && !defined(Q_OS_OPENBSD) && !defined(Q_OS_FREEBSD) && !defined(Q_OS_NETBSD) void ** trace = new void*[nFrames + 1]; char **messages = ( char ** ) nullptr; int i, trace_size = 0;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #ifndef CUEHTTP_SERVER_HPP_ #define CUEHTTP_SERVER_HPP_ #include <thread> #include <functional> #include <vector> #include <type_traits> #include "cuehttp/deps/asio/asio.hpp" #ifdef ENABLE_HTTPS #include "cuehttp/deps/asio/asio/ssl.hpp" #endif // ENABLE_HTTPS #include "cuehttp/context.hpp" #include "cuehttp/detail/connection.hpp" #include "cuehttp/detail/noncopyable.hpp" #include "cuehttp/detail/engines.hpp" namespace cue { namespace http { template <typename _Socket, typename _Ty> class base_server : safe_noncopyable { public: base_server() noexcept { } explicit base_server(std::function<void(context&)> handler) noexcept : handler_{std::move(handler)} { } virtual ~base_server() = default; base_server(base_server&& rhs) noexcept { swap(rhs); } base_server& operator=(base_server&& rhs) noexcept { swap(rhs); return *this; } void swap(base_server& rhs) noexcept { if (this != std::addressof(rhs)) { std::swap(handler_, rhs.handler_); std::swap(acceptor_, rhs.acceptor_); } } base_server& listen(unsigned port) { assert(port != 0); listen_impl(asio::ip::tcp::resolver::query{std::to_string(port)}); return *this; } template <typename _Host> base_server& listen(unsigned port, _Host&& host) { assert(port != 0); listen_impl(asio::ip::tcp::resolver::query{std::forward<_Host>(host), std::to_string(port)}); return *this; } void run() { detail::engines::default_engines().run(); } protected: void listen_impl(asio::ip::tcp::resolver::query&& query) { auto& engines = detail::engines::default_engines(); asio::ip::tcp::endpoint endpoint{*asio::ip::tcp::resolver{engines.get()}.resolve(query)}; acceptor_ = std::make_unique<asio::ip::tcp::acceptor>(engines.get()); acceptor_->open(endpoint.protocol()); acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true)); acceptor_->bind(endpoint); acceptor_->listen(); do_accept(); } void do_accept() { static_cast<_Ty&>(*this).do_accept_real(); } std::unique_ptr<asio::ip::tcp::acceptor> acceptor_; std::function<void(context&)> handler_; }; template <typename _Socket = detail::http_socket> class server final : public base_server<_Socket, server<_Socket>>, safe_noncopyable { public: server() noexcept = default; explicit server(std::function<void(context&)> handler) noexcept : base_server<_Socket, server<_Socket>>{std::move(handler)} { } server(server&& rhs) noexcept { swap(rhs); } server& operator=(server&& rhs) noexcept { swap(rhs); return *this; } void swap(server& rhs) noexcept { if (this != std::addressof(rhs)) { base_server<_Socket, server<_Socket>>::swap(rhs); } } void do_accept_real() { auto connector = std::make_shared<detail::connection<_Socket>>(this->handler_, detail::engines::default_engines().get()); this->acceptor_->async_accept(connector->socket(), [this, connector](const std::error_code& code) { if (!code) { connector->socket().set_option(asio::ip::tcp::no_delay{true}); connector->run(); } this->do_accept(); }); } }; #ifdef ENABLE_HTTPS template <> class server<detail::https_socket> final : public base_server<detail::https_socket, server<detail::https_socket>>, safe_noncopyable { public: server(std::function<void(context&)> handler, const std::string& key, const std::string& cert) noexcept : base_server{std::move(handler)}, ssl_context_{asio::ssl::context::sslv23} { ssl_context_.use_certificate_chain_file(cert); ssl_context_.use_private_key_file(key, asio::ssl::context::pem); } server(server&& rhs) noexcept : ssl_context_{asio::ssl::context::sslv23} { swap(rhs); } server& operator=(server&& rhs) noexcept { swap(rhs); return *this; } void swap(server& rhs) noexcept { if (this != std::addressof(rhs)) { base_server::swap(rhs); std::swap(ssl_context_, rhs.ssl_context_); } } void do_accept_real() { auto connector = std::make_shared<detail::connection<detail::https_socket>>( this->handler_, detail::engines::default_engines().get(), ssl_context_); this->acceptor_->async_accept(connector->socket(), [this, connector](const std::error_code& code) { if (!code) { connector->socket().set_option(asio::ip::tcp::no_delay{true}); connector->run(); } this->do_accept(); }); } private: asio::ssl::context ssl_context_; }; #endif // ENABLE_HTTPS using http_t = server<detail::http_socket>; struct http final : safe_noncopyable { template <typename... _Args> static http_t create_server(_Args&&... args) noexcept { return http_t{std::forward<_Args>(args)...}; } }; #ifdef ENABLE_HTTPS using https_t = server<detail::https_socket>; struct https final : safe_noncopyable { template <typename... _Args> static https_t create_server(_Args&&... args) noexcept { return https_t{std::forward<_Args>(args)...}; } }; #endif // ENABLE_HTTPS } // namespace http } // namespace cue #endif // CUEHTTP_SERVER_HPP_
#pragma once #include <cutil_inline.h> #include <cutil_math.h> #include "MatrixConversion.h" #include "VoxelUtilHashSDF.h" #include "DepthCameraUtil.h" #include "CUDAScan.h" #include "GlobalAppState.h" #include "TimingLog.h" extern "C" void computeHistogramCUDA(unsigned int* d_data, const VoxelHashData& voxelHashData, const HashParams& hashParams); extern "C" void resetHistrogramCUDA(unsigned int* d_data, unsigned int numValues); class CUDAHistrogramHashSDF { public: CUDAHistrogramHashSDF(const HashParams& hashParams) { create(hashParams); } ~CUDAHistrogramHashSDF() { destroy(); } void computeHistrogram(const VoxelHashData& voxelHashData, const HashParams& hashParams) { resetHistrogramCUDA(d_historgram, hashParams.m_hashBucketSize + 1 + hashParams.m_hashMaxCollisionLinkedListSize + 1); computeHistogramCUDA(d_historgram, voxelHashData, hashParams); printHistogram(hashParams); } private: void create(const HashParams& hashParams) { cutilSafeCall(cudaMalloc(&d_historgram, sizeof(unsigned int)*(hashParams.m_hashBucketSize + 1 + hashParams.m_hashMaxCollisionLinkedListSize + 1))); } void destroy() { cutilSafeCall(cudaFree(d_historgram)); } void printHistogram(const HashParams& hashParams) { unsigned int* h_data = new unsigned int[hashParams.m_hashBucketSize + 1 + hashParams.m_hashMaxCollisionLinkedListSize + 1]; cutilSafeCall(cudaMemcpy(h_data, d_historgram, sizeof(unsigned int)*(hashParams.m_hashBucketSize + 1 + hashParams.m_hashMaxCollisionLinkedListSize + 1), cudaMemcpyDeviceToHost)); std::streamsize oldPrec = std::cout.precision(4); std::ios_base::fmtflags oldFlags = std::cout.setf( std::ios::fixed, std:: ios::floatfield ); unsigned int nTotal = 0; unsigned int nElements = 0; for (unsigned int i = 0; i < hashParams.m_hashBucketSize+1; i++) { nTotal += h_data[i]; nElements += h_data[i]*i; } std::cout << nTotal << std::endl; std::cout << "Histogram for hash with " << (unsigned int)nElements <<" of " << hashParams.m_hashNumBuckets*hashParams.m_hashBucketSize << " elements:" << std::endl; std::cout << "--------------------------------------------------------------" << std::endl; unsigned int checkBuckets = 0; for (unsigned int i = 0; i < hashParams.m_hashBucketSize+1; i++) { float percent = 100.0f*(float)h_data[i]/(float)nTotal; std::cout << i << ":\t" << (percent < 10.0f ? " " : "" ) << percent << "%\tabsolute: " << h_data[i] << std::endl; checkBuckets += h_data[i]; } std::cout << std::endl; unsigned int checkLists = 0; for (unsigned int i = hashParams.m_hashBucketSize+1; i < hashParams.m_hashBucketSize+1+hashParams.m_hashMaxCollisionLinkedListSize; i++) { float percent = 100.0f*(float)h_data[i]/(float)hashParams.m_hashNumBuckets; std::cout << "listLen " << (i - (hashParams.m_hashBucketSize+1)) << ":\t" << (percent < 10.0f ? " " : "" ) << percent << "%\tabsolute: " << h_data[i] << std::endl; checkLists += h_data[i]; } std::cout << "--------------------------------------------------------------" << std::endl; std::cout << "checkBuckets\t " << checkBuckets << "\t" << ((checkBuckets == hashParams.m_hashNumBuckets) ? "OK" : "FAIL") << std::endl; std::cout << "checkLists\t " << checkLists << "\t" << ((checkBuckets == hashParams.m_hashNumBuckets) ? "OK" : "FAIL") << std::endl; std::cout << "--------------------------------------------------------------" << std::endl; std::cout.precision(oldPrec); std::cout.setf(oldFlags); SAFE_DELETE_ARRAY(h_data); } unsigned int* d_historgram; };
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2019 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018 Lee Clagett <https://github.com/vtnerd> * Copyright 2018-2019 tevador <tevador@gmail.com> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef XMRIG_RX_QUEUE_H #define XMRIG_RX_QUEUE_H #include "base/kernel/interfaces/IAsyncListener.h" #include "base/tools/Object.h" #include "crypto/common/HugePagesInfo.h" #include "crypto/rx/RxConfig.h" #include "crypto/rx/RxSeed.h" #include <condition_variable> #include <mutex> #include <thread> namespace xmrig { class IRxListener; class IRxStorage; class RxDataset; class RxQueueItem { public: RxQueueItem(const RxSeed &seed, const std::vector<uint32_t> &nodeset, uint32_t threads, bool hugePages, bool oneGbPages, RxConfig::Mode mode, int priority) : hugePages(hugePages), oneGbPages(oneGbPages), priority(priority), mode(mode), seed(seed), nodeset(nodeset), threads(threads) {} const bool hugePages; const bool oneGbPages; const int priority; const RxConfig::Mode mode; const RxSeed seed; const std::vector<uint32_t> nodeset; const uint32_t threads; }; class RxQueue : public IAsyncListener { public: XMRIG_DISABLE_COPY_MOVE(RxQueue); RxQueue(IRxListener *listener); ~RxQueue() override; HugePagesInfo hugePages(); RxDataset *dataset(const Job &job, uint32_t nodeId); template<typename T> bool isReady(const T &seed); void enqueue(const RxSeed &seed, const std::vector<uint32_t> &nodeset, uint32_t threads, bool hugePages, bool oneGbPages, RxConfig::Mode mode, int priority); protected: inline void onAsync() override { onReady(); } private: enum State { STATE_IDLE, STATE_PENDING, STATE_SHUTDOWN }; template<typename T> bool isReadyUnsafe(const T &seed) const; void backgroundInit(); void onReady(); IRxListener *m_listener = nullptr; IRxStorage *m_storage = nullptr; RxSeed m_seed; State m_state = STATE_IDLE; std::condition_variable m_cv; std::mutex m_mutex; std::shared_ptr<Async> m_async; std::thread m_thread; std::vector<RxQueueItem> m_queue; }; } /* namespace xmrig */ #endif /* XMRIG_RX_QUEUE_H */
// Created on: 1995-12-01 // Created by: EXPRESS->CDL V0.2 Translator // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepBasic_ApprovalPersonOrganization_HeaderFile #define _StepBasic_ApprovalPersonOrganization_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepBasic_PersonOrganizationSelect.hxx> #include <Standard_Transient.hxx> class StepBasic_Approval; class StepBasic_ApprovalRole; class StepBasic_ApprovalPersonOrganization; DEFINE_STANDARD_HANDLE(StepBasic_ApprovalPersonOrganization, Standard_Transient) class StepBasic_ApprovalPersonOrganization : public Standard_Transient { public: //! Returns a ApprovalPersonOrganization Standard_EXPORT StepBasic_ApprovalPersonOrganization(); Standard_EXPORT void Init (const StepBasic_PersonOrganizationSelect& aPersonOrganization, const Handle(StepBasic_Approval)& aAuthorizedApproval, const Handle(StepBasic_ApprovalRole)& aRole); Standard_EXPORT void SetPersonOrganization (const StepBasic_PersonOrganizationSelect& aPersonOrganization); Standard_EXPORT StepBasic_PersonOrganizationSelect PersonOrganization() const; Standard_EXPORT void SetAuthorizedApproval (const Handle(StepBasic_Approval)& aAuthorizedApproval); Standard_EXPORT Handle(StepBasic_Approval) AuthorizedApproval() const; Standard_EXPORT void SetRole (const Handle(StepBasic_ApprovalRole)& aRole); Standard_EXPORT Handle(StepBasic_ApprovalRole) Role() const; DEFINE_STANDARD_RTTIEXT(StepBasic_ApprovalPersonOrganization,Standard_Transient) protected: private: StepBasic_PersonOrganizationSelect personOrganization; Handle(StepBasic_Approval) authorizedApproval; Handle(StepBasic_ApprovalRole) role; }; #endif // _StepBasic_ApprovalPersonOrganization_HeaderFile
#include "sockets.h" // #include <stdio.h> CSocket::CSocket() { // printf("construct socket %08X \n", this); this->socket = -1; this->prevSocket = this->nextSocket = NULL; } CSocket::~CSocket() { // printf("destroy socket %08X \n", this); shutdown(this->socket, SD_BOTH); closesocket(this->socket); } CSocketList::CSocketList() { // printf("construct socketlist %08X \n", this); this->firstSocket = NULL; } CSocketList::~CSocketList() { // printf("destroy socketlist %08X \n", this); CSocket *s; while( (s = this->firstSocket) ) { this->firstSocket = s->nextSocket; delete s; } } int CSocketList::length() { int l=0; for(CSocket *s=this->firstSocket; s; s=s->nextSocket) l++; return(l); } void CSocketList::add(SOCKET socket) { //printf("add to socketlist %08X \n", this); CSocket *s; s = new CSocket(); s->prevSocket = NULL; if(this->firstSocket) this->firstSocket->prevSocket = s; s->nextSocket = this->firstSocket; this->firstSocket = s; s->socket = socket; //printf("socketlist length = %d \n", this->length()); } CSocket *CSocketList::remove(CSocket *s) { //printf("remove socket %08X \n", s); CSocket *ret; if(s->prevSocket) { s->prevSocket->nextSocket = s->nextSocket; } else { this->firstSocket = s->nextSocket; //printf(" was first, new first = %08X \n", this->firstSocket); } if( (ret = s->nextSocket) ) { s->nextSocket->prevSocket = s->prevSocket; } delete(s); //printf(" returning ret = %08X \n", ret); //printf("socketlist length = %d \n", this->length()); return(ret); }
#include <bits/stdc++.h> using namespace std; using ll = long long; struct wavelet_matrix { int n; int blk; int logn; vector<int> z; vector<vector<pair<int, int>>> b; wavelet_matrix(vector<int>& a) { n = a.size(); blk = (n + 32) >> 5; logn = 32 - __builtin_clz(*max_element(a.begin(), a.end())); // resize z.assign(logn, 0); b.assign(logn, vector<pair<int, int>>(blk)); // build for (int bit = logn - 1; bit >= 0; --bit) { auto f = [bit](int x) { return not(x >> bit & 1); }; auto& b = this->b[bit]; for (int i = 0; i < n; ++i) if (f(a[i])) b[i >> 5].first |= 1u << (i & 31); for (int i = 1; i < blk; ++i) b[i].second = b[i - 1].second + __builtin_popcount(b[i - 1].first); auto zeros = stable_partition(a.begin(), a.end(), f); z[bit] = distance(a.begin(), zeros); } } int rank0(int bit, int i) { return b[bit][i >> 5].second + __builtin_popcount(b[bit][i >> 5].first & ((1u << (i & 31)) - 1u)); } int rank1(int bit, int i) { return i - rank0(bit, i); } // kth number in range [l, r] int kth(int l, int r, int k) { r++; // switch to [l, r) indexing for convinence int ans = 0; for (int bit = logn - 1; bit >= 0; --bit) { int lf = rank0(bit, l); int rg = rank0(bit, r); if (k <= rg - lf) { l = lf; r = rg; } else { ans |= 1u << bit; k -= rg - lf; l += z[bit] - lf; r += z[bit] - rg; } } return ans; } }; int main() { cin.tie(0); cin.sync_with_stdio(0); int n, m; cin >> n >> m; vector<int> a(n); for (auto& x : a) cin >> x; auto b = a; sort(b.begin(), b.end()); b.resize(unique(b.begin(), b.end()) - b.begin()); for (auto& x : a) x = lower_bound(b.begin(), b.end(), x) - b.begin(); wavelet_matrix wx(a); while (m--) { int l, r, k; cin >> l >> r >> k; cout << b[wx.kth(l - 1, r - 1, k)] << '\n'; } }