text
stringlengths 8
6.88M
|
|---|
#pragma once
#include "bricks/core/object.h"
namespace Bricks {
namespace ValueType {
enum Enum {
Pointer,
Boolean,
Byte,
Int16,
Int32,
Int64,
Float32,
Float64,
Float = Float32,
Double = Float64
};
}
class Value : public Object
{
protected:
u8 data[0x08];
ValueType::Enum type;
public:
Value(const void* data, ValueType::Enum type) : type(type) { SetData(data); }
Value(const void* value) : type(ValueType::Pointer) { SetData(&value); }
Value(bool value) : type(ValueType::Boolean) { SetData(&value); }
Value(u8 value) : type(ValueType::Byte) { SetData(&value); }
Value(u16 value) : type(ValueType::Int16) { SetData(&value); }
Value(u32 value) : type(ValueType::Int32) { SetData(&value); }
Value(int value) : type(ValueType::Int32) { SetData(&value); }
Value(u64 value) : type(ValueType::Int64) { SetData(&value); }
Value(f32 value) : type(ValueType::Float32) { SetData(&value); }
Value(f64 value) : type(ValueType::Float64) { SetData(&value); }
ValueType::Enum GetType() const { return type; }
int GetSize() const { return SizeOfType(type); }
const void* GetData() const { return data; }
void SetData(const void* value);
void SetType(ValueType::Enum value);
void* GetPointerValue() const;
bool GetBooleanValue() const;
u8 GetByteValue() const;
u16 GetInt16Value() const;
u32 GetInt32Value() const;
u64 GetInt64Value() const;
f32 GetFloat32Value() const;
f64 GetFloat64Value() const;
f32 GetFloatValue() const { return GetFloat32Value(); }
f32 GetDoubleValue() const { return GetFloat64Value(); }
int GetIntValue() const { return GetInt32Value(); }
void SetValue(const void* value);
void SetValue(bool value);
void SetValue(u8 value);
void SetValue(u16 value);
void SetValue(u32 value);
void SetValue(u64 value);
void SetValue(f32 value);
void SetValue(f64 value);
void SetValue(int value) { SetValue((u32)value); }
static int SizeOfType(ValueType::Enum type);
};
}
|
#ifndef POINT_H
#define POINT_H
// PCL
#ifdef COMPILE_PCL
#include <pcl/point_types.h>
#endif
// Eigen
#include <Eigen/Dense>
// Local
#include "tools/exception.h"
template<typename T>
class Point
{
public:
enum{
X = 0,
Y = 1,
Z = 2
};
~Point()
{
deallocate();
}
Point(const Eigen::Matrix<T,3,1>& point): m_owns_data(false)
{
allocate();
fromEigen(point);
}
Point(const Point& other): m_owns_data(false)
{
allocate();
set(other.x(),other.y(),other.z());
}
Point(): m_owns_data(false)
{
allocate();
set(T(0),T(0),T(0));
}
Point(T const* data): m_owns_data(false)
{
allocate();
set(data);
}
Point(T* data): m_owns_data(false)
{
set(data);
}
Point(T x, T y, T z): m_owns_data(false)
{
allocate();
set(x,y,z);
}
T x() const
{
checkInitialized();
return m_data[X];
}
T y() const
{
checkInitialized();
return m_data[Y];
}
T z() const
{
checkInitialized();
return m_data[Z];
}
void set(T x, T y, T z)
{
checkInitialized();
m_data[X] = x;
m_data[Y] = y;
m_data[Z] = z;
}
void setX(T x)
{
checkInitialized();
m_data[X] = x;
}
void setY(T y)
{
checkInitialized();
m_data[Y] = y;
}
void setZ(T z)
{
checkInitialized();
m_data[Z] = z;
}
void set(const Eigen::Matrix<T,3,1>& point)
{
checkInitialized();
setX(point(0,0));
setY(point(1,0));
setZ(point(2,0));
}
void fromEigen(const Eigen::Matrix<T,3,1>& point)
{
set(point);
}
Eigen::Matrix<T,3,1> toEigen()
{
checkInitialized();
return Eigen::Matrix<T,3,1>(x(),y(),z());
}
void set(T const* data)
{
allocate();
for ( int i = 0; i< 3; i++ ) m_data[i] = data[i];
}
void set(T* data)
{
deallocate();
m_data = data;
}
T mod2() const
{
checkInitialized();
T result(0);
result += pow(x(),2);
result += pow(y(),2);
result += pow(z(),2);
return result;
}
T mod() const
{
T md2 = mod2();
if (md2 == T(0))
return T(0);
else
return sqrt(mod2());
}
Point cross(const Point& other) const
{
T x = this->y()*other.z() - this->z()*other.y();
T y = this->z()*other.x() - this->x()*other.z();
T z = this->x()*other.y() - this->y()*other.x();
return Point(x,y,z);
}
T dot(const Point& other) const
{
T result(0);
result += other.x()*this->x();
result += other.y()*this->y();
result += other.z()*this->z();
return result;
}
Point& operator+=(const Point& rhs)
{
checkInitialized();
m_data[X] += rhs.x();
m_data[Y] += rhs.y();
m_data[Z] += rhs.z();
return *this;
}
friend Point& operator+(Point& lhs, const Point& rhs)
{
lhs += rhs;
return lhs;
}
friend Point operator+(const Point& lhs, const Point& rhs)
{
Point l(lhs);
l += rhs;
return l;
}
Point& operator-=(const Point& rhs)
{
checkInitialized();
m_data[X] -= rhs.x();
m_data[Y] -= rhs.y();
m_data[Z] -= rhs.z();
return *this;
}
friend Point& operator-(Point& lhs, const Point& rhs)
{
lhs -= rhs;
return lhs;
}
friend Point operator-(const Point& lhs, const Point& rhs)
{
Point l(lhs);
l -= rhs;
return l;
}
T* data()
{
checkInitialized();
return m_data;
}
Point& operator*=(const T& scale)
{
checkInitialized();
m_data[X] *= scale;
m_data[Y] *= scale;
m_data[Z] *= scale;
return *this;
}
friend Point operator*(T scale, const Point& rhs)
{
Point out(rhs);
out *= scale;
return out;
}
friend Point operator*(const Point& lhs, T scale)
{
Point out(lhs);
out *= scale;
return out;
}
Point& operator/=(const T& scale)
{
checkInitialized();
m_data[X] /= scale;
m_data[Y] /= scale;
m_data[Z] /= scale;
return *this;
}
friend Point operator/(const Point& lhs, T scale)
{
Point out(lhs);
out /= scale;
return out;
}
Point& operator=(const Point& other)
{
if (this == &other)
return *this;
set(other.x(),other.y(),other.z());
return *this;
}
Point normalize() const
{
return *this/this->mod();
}
#ifdef COMPILE_PCL
pcl::PointXYZ pcl()
{
return pcl::PointXYZ(x(),y(),z());
}
#endif
protected:
void checkInitialized() const
{
if (m_data == NULL)
EXCEPTION("Point data has not been initialized")
}
void deallocate()
{
if (m_owns_data)
delete[] m_data;
}
void allocate()
{
deallocate();
m_data = new T[6];
m_owns_data = true;
}
private:
T* m_data;
bool m_owns_data;
};
template<typename T>
std::ostream& operator<<(std::ostream& out, const Point<T>& p)
{
out<<"["<<p.x()<<","<<p.y()<<","<<p.z()<<"]";
return out;
}
template<typename T>
std::istream& operator>>(std::istream& in, Point<T>& point)
{
double x,y,z;
in>>x>>y>>z;
point.setX(x);
point.setY(y);
point.setZ(z);
return in;
}
#endif // POINT_H
|
#include<bits/stdc++.h>
#define rep(i,n) for (int i =0; i <(n); i++)
using namespace std;
using ll = long long;
const double PI = 3.14159265358979323846;
const ll MOD = 998244353;
int main(){
vector<int>A(4);
rep(i,4)cin >> A[i];
sort(A.begin(), A.end());
if(A[0] + A[3] == A[1] + A[2] || A[0] + A[1] + A[2] == A[3]){
cout << "Yes" << endl;
}
else cout << "No" << endl;
return 0;
}
|
#include <iostream>
#include "ABB.h"
#include "NodoABB.h"
using namespace std;
int main()
{
ABB A;
A.inserta(16);
A.inserta(23);
A.inserta(18);
A.inserta(3);
A.inserta(5);
A.inserta(14);
A.entreorden();
cout << endl << "Numero nodos con un hijo: " << A.numeroNodos() << endl;
return 0;
}
|
#include "WidgetControllerWidget.h"
#include "Actor/Controller/PlayerController/BasePlayerController.h"
#include "Components/CanvasPanel.h"
#include "Components/CanvasPanelSlot.h"
#include "Components/GridSlot.h"
#include "Widget/ClosableWnd/MessageBoxWnd/MessageBoxWnd.h"
#include "Widget/ClosableWnd/ClosableWnd.h"
UWidgetControllerWidget::UWidgetControllerWidget(const FObjectInitializer& ObjectInitializer) :
Super(ObjectInitializer)
{
static ConstructorHelpers::FClassFinder<UMessageBoxWnd> BP_MESSAGE_BOX_WND(
TEXT("WidgetBlueprint'/Game/Blueprints/Widget/ClosableWnd/MessageBoxWnd/BP_MessageBoxWnd.BP_MessageBoxWnd_C'"));
if (BP_MESSAGE_BOX_WND.Succeeded()) BP_MessageBoxWnd = BP_MESSAGE_BOX_WND.Class;
static ConstructorHelpers::FClassFinder<UUserWidget> BP_MESSAGE_BOX_BACKGROUND(
TEXT("WidgetBlueprint'/Game/Blueprints/Widget/ClosableWnd/MessageBoxWnd/BP_MessageBoxBackground.BP_MessageBoxBackground_C'"));
if (BP_MESSAGE_BOX_BACKGROUND.Succeeded()) BP_MessageBoxBackground = BP_MESSAGE_BOX_BACKGROUND.Class;
}
void UWidgetControllerWidget::InitializeWidgetControllerWidget(
class ABasePlayerController* basePlayerController)
{
PlayerController = basePlayerController;
}
void UWidgetControllerWidget::ResetInputMode(bool bForceChange)
{
// 열린 창과 위젯이 존재하지 않는다면 입력 모드를 변경합니다.
if (bForceChange ||
((AllocatedWnds.Num() == 0) && (AllocatedWidgets.Num() == 0)))
{
// 입력 모드를 설정
PlayerController->ChangeInputModeToDefault();
// 커서 표시
PlayerController->bShowMouseCursor = PlayerController->GetDefaultCursorVisibility();
}
}
void UWidgetControllerWidget::SaveWndPosition(const UClosableWnd* closableWnd)
{
FString wndClsName = closableWnd->GetClass()->GetName();
FVector2D wndPosition = closableWnd->GetCanvasPanelSlot()->GetPosition();
if (PrevClosedWndPositions.Contains(wndClsName))
PrevClosedWndPositions[wndClsName] = wndPosition;
else PrevClosedWndPositions.Add(wndClsName, wndPosition);
}
UMessageBoxWnd* UWidgetControllerWidget::CreateMessageBox(FText titleText, FText msg, bool bUseBackground, uint8 buttons)
{
UUserWidget* msgBoxBackground = nullptr;
if (bUseBackground)
{
msgBoxBackground = CreateWidget<UUserWidget>(this, BP_MessageBoxBackground);
CanvasPanel_WndParent->AddChild(msgBoxBackground);
UCanvasPanelSlot* messageBoxCanvasPanelSlot = Cast<UCanvasPanelSlot>(msgBoxBackground->Slot);
messageBoxCanvasPanelSlot->SetAnchors(FAnchors(0.0f, 0.0f, 1.0f, 1.0f));
messageBoxCanvasPanelSlot->SetOffsets(FMargin(0.0f, 0.0f, 0.0f, 0.0f));
}
UMessageBoxWnd* msgBox = Cast<UMessageBoxWnd>(
CreateWnd(BP_MessageBoxWnd, false, EInputModeType::IM_UIOnly, true));
msgBox->MsgBoxBackground = msgBoxBackground;
msgBox->InitializeMessageBox(titleText, msg, buttons);
return msgBox;
}
UClosableWnd* UWidgetControllerWidget::CreateWnd(
TSubclassOf<class UClosableWnd> wndClass,
bool bUsePrevPosition,
EInputModeType changeInputMode,
bool bShowMouseCursor,
float alignmentX, float alignmentY,
float anchorMinX, float anchorMinY,
float anchorMaxX, float anchorMaxY)
{
// 새로운 창 위젯을 생성합니다.
UClosableWnd* newClosableWnd = CreateWidget<UClosableWnd>(this, wndClass);
newClosableWnd->WidgetController = this;
// 할당된 창 배열에 추가합니다.
AllocatedWnds.Add(newClosableWnd);
// CanvasPanel_WndParent 의 자식 위젯으로 추가합니다.
CanvasPanel_WndParent->AddChild(newClosableWnd);
// Anchor / Alignment 설정
auto wndCanvasPanelSlot = newClosableWnd->GetCanvasPanelSlot();
wndCanvasPanelSlot->SetAnchors(FAnchors(anchorMinX, anchorMinY, anchorMaxX, anchorMaxY));
wndCanvasPanelSlot->SetAlignment(FVector2D(alignmentX, alignmentY));
// 창 크기를 설정합니다.
wndCanvasPanelSlot->SetSize(newClosableWnd->GetWndSize());
// 이전 창 위치를 사용한다면
if (bUsePrevPosition)
{
// 이전 창 위치가 기록되어 있는지 확인합니다.
//if (PrevClosedWndPositions.Contains(newClosableWnd->GetClass()->GetName()))
if (PrevClosedWndPositions.Contains(wndClass->GetName()))
{
// 창 위치를 이전 위치로 설정합니다.
wndCanvasPanelSlot->SetPosition(PrevClosedWndPositions[wndClass->GetName()]);
}
}
// 입력 모드와 커서 표시 여부를 변경합니다.
if (changeInputMode != EInputModeType::IM_Default)
PlayerController->SetInputModeFromNewInputModeType(changeInputMode);
PlayerController->bShowMouseCursor = bShowMouseCursor;
// 생성한 창 객체를 반환합니다.
return newClosableWnd;
}
void UWidgetControllerWidget::CloseWnd(bool bAllClose, UClosableWnd* closableWndInstanceToClose)
{
// 만약 열린 창이 존재하지 않는 경우 실행하지 않습니다.
if (AllocatedWnds.Num() == 0) return;
// 모든 창을 닫도록 하였다면
if (bAllClose)
{
for (auto wnd : AllocatedWnds)
{
// 닫힘 처리된 창이라면 실행하지 않습니다.
if (wnd->bBeClose) continue;
wnd->bBeClose = true;
// 창 닫힘 이벤트를 발생시킵니다.
if (wnd->OnWndClosedEvent.IsBound())
wnd->OnWndClosedEvent.Broadcast(wnd);
// 모든 자식 창을 닫습니다.
wnd->CloseAllChildWnd();
// 창 위치를 저장합니다.
SaveWndPosition(wnd);
// 부모 창에서 떼어냅니다.
wnd->DetachFromParent();
// CanvasPanel_WndParent 위젯의 자식에서 제거합니다.
CanvasPanel_WndParent->RemoveChild(wnd);
}
// 항당된 창 배열을 비웁니다.
AllocatedWnds.Empty();
}
// 특정한 창만 닫도록 하였다면
else
{
// 닫을 창이 지정되지 않았다면 마지막으로 열린 창을 닫을 창으로 지정합니다.
closableWndInstanceToClose = (closableWndInstanceToClose != nullptr) ?
closableWndInstanceToClose :
AllocatedWnds[AllocatedWnds.Num() - 1];
// 곧 닫힐 창이 아니라면
if (!closableWndInstanceToClose->bBeClose)
{
// 닫힐 창으로 설정합니다.
closableWndInstanceToClose->bBeClose = true;
// 창 닫힘 이벤트를 발생시킵니다.
if (closableWndInstanceToClose->OnWndClosedEvent.IsBound())
closableWndInstanceToClose->OnWndClosedEvent.Broadcast(closableWndInstanceToClose);
// 모든 자식 창을 제거합니다.
closableWndInstanceToClose->CloseAllChildWnd();
// 할당된 창 배열에서 제외합니다.
AllocatedWnds.Remove(closableWndInstanceToClose);
// 창 위치를 저장합니다.
SaveWndPosition(closableWndInstanceToClose);
// 부모 창에서 떼어냅니다.
closableWndInstanceToClose->DetachFromParent();
// CanvasPanel_WndParent 위젯의 자식에서 제거합니다.
CanvasPanel_WndParent->RemoveChild(closableWndInstanceToClose);
}
}
// 입력 모드 초기화
ResetInputMode();
}
void UWidgetControllerWidget::AddChildWidget(UUserWidget* childWidgetInstance,
EInputModeType changeInputMode, bool bShowMouseCursor,
float width, float height)
{
if (childWidgetInstance == nullptr)
{
UE_LOG(LogTemp, Error,
TEXT("WidgetControllerWidget.cpp :: %d LINE :: childWidgetInstance is nullptr"), __LINE__);
return;
}
CanvasPanel_WidgetParent->AddChild(childWidgetInstance);
/// - Widget->AddChild(childWidget) : childWidget 을 Widget 의 하위로 추가합니다.
Cast<UCanvasPanelSlot>(childWidgetInstance->Slot)->SetSize(FVector2D(width, height));
// 입력 모드와 커서 가시성을 설정합니다.
PlayerController->SetInputModeFromNewInputModeType(changeInputMode);
PlayerController->bShowMouseCursor = bShowMouseCursor;
AllocatedWidgets.Add(childWidgetInstance);
}
void UWidgetControllerWidget::CloseChildWidget(UUserWidget* childWidgetInstance)
{
if (childWidgetInstance == nullptr)
{
UE_LOG(LogTemp, Error,
TEXT("WidgetControllerWidget.cpp :: %d LINE :: childWidgetInstance is nullptr"), __LINE__);
return;
}
// 제거하려는 위젯을 AllocatedWidgets 에서 제거합니다.
AllocatedWidgets.Remove(childWidgetInstance);
// 제거하려는 위젯을 화면에서 떼어냅니다.
CanvasPanel_WidgetParent->RemoveChild(childWidgetInstance);
/// - 부모 위젯에서 자식 위젯을 제거합니다.
//childWidgetInstance->RemoveFromParent();
/// - 자식 위젯에서 부모와 연결을 끊습니다.
// 입력 모드를 기본 값으로 설정합니다.
ResetInputMode();
}
void UWidgetControllerWidget::SetHighestPriorityWnd(UClosableWnd* closableWndInstance)
{
// 우선순위를 변경시킬 위젯의 슬롯을 얻습니다.
UCanvasPanelSlot* wndSlot = closableWndInstance->GetCanvasPanelSlot();
// 최상단으로 설정하려는 위젯이 최상단에 배치되어 있지 않다면
if (CanvasPanel_WndParent->GetChildIndex(closableWndInstance) !=
/// - GetChildIndex(widget) : widget 의 계층구조 순서를 반환합니다.
CanvasPanel_WndParent->GetSlots().Num() - 1)
/// - GetSlots() : 추가된 위젯들의 슬롯 정보를 저장하는 배열을 반환합니다.
{
// 위치, Anchor, Alignment 를 저장합니다.
FVector2D prevPosition = wndSlot->GetPosition();
FAnchors prevAnchors = wndSlot->GetAnchors();
FVector2D prevAlignment = wndSlot->GetAlignment();
// 위젯을 재등록합니다.
CanvasPanel_WndParent->AddChild(closableWndInstance);
// Anchor, Alignment, 위치, 크기를 재설정합니다.
wndSlot = closableWndInstance->GetCanvasPanelSlot();
wndSlot->SetAnchors(prevAnchors);
wndSlot->SetAlignment(prevAlignment);
wndSlot->SetPosition(prevPosition);
wndSlot->SetSize(closableWndInstance->GetWndSize());
}
}
void UWidgetControllerWidget::SortGridPanelElem(
UUserWidget* gridPanelElem,
int maxColumnCount,
int& refCurrentColumCount)
{
UGridSlot* gridSlot = Cast<UGridSlot>(gridPanelElem->Slot);
if (!IsValid(gridSlot)) return;
// 그리드 행과 열을 설정합니다.
gridSlot->SetColumn(refCurrentColumCount % maxColumnCount);
gridSlot->SetRow(refCurrentColumCount / maxColumnCount);
++refCurrentColumCount;
}
|
#pragma once
#ifndef LIGHT_H
#define LIGHT_H
class Light
{
};
#endif
|
#include "BookInfo.h"
BookInfo::BookInfo():m_nPrice(0){ m_sTitle = string(); m_sAuthor = string(); m_sCompany = string(); }
BookInfo::BookInfo(const char* const title, const char* const author, const char* const company, int price) :
m_sTitle(title),m_sAuthor(author),m_sCompany(company),m_nPrice(price){}
BookInfo::BookInfo(const string title, const string author, const string company, int price) :
m_sTitle(title),m_sAuthor(author),m_sCompany(company),m_nPrice(price){}
BookInfo::BookInfo(const BookInfo& src){
this->m_sTitle = string(src.m_sTitle);
this->m_sAuthor = string(src.m_sAuthor);
this->m_sCompany = string(src.m_sCompany);
this->m_nPrice = src.m_nPrice;
}
string BookInfo::getTitle() { return this->m_sTitle; }
string BookInfo::getCompany() { return this->m_sAuthor; }
string BookInfo::getAuthor() { return this->m_sCompany; }
int BookInfo::getPrice() { return this->m_nPrice; }
void BookInfo::setTitle(string title) {this->m_sTitle = string(title);}
void BookInfo::setTitle(const char* const title) {this->m_sTitle = string(title);}
void BookInfo::setCompany(string company) {this->m_sCompany = string(company);}
void BookInfo::setCompany(const char* const company) {this->m_sCompany = string(company);}
void BookInfo::setAuthor(string author) {this->m_sAuthor = string(author);}
void BookInfo::setAuthor(const char* const author) {this->m_sAuthor = string(author);}
void BookInfo::setPrice(int price) { this->m_nPrice = price;}
void BookInfo::viewBookInfo(){
cout <<m_sTitle <<"\t" <<m_sAuthor <<"\t" <<m_sCompany<< "\t" <<m_nPrice<<endl;
}
BookInfo::~BookInfo() { cout << "CaLlEd BoOk InFo InStAnCe DeStRuCt" << endl; }
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
#include "modules/accessibility/acctree/AccessibilityTreeRootNode.h"
#include "modules/accessibility/AccessibleDocument.h"
AccessibilityTreeRootNode::AccessibilityTreeRootNode(AccessibleDocument* document)
: AccessibilityTreeNode(NULL, document)
{
}
OpAccessibleItem* AccessibilityTreeRootNode::GetAccessibleObject() const
{
return GetDocument();
}
AccessibilityTreeNode::TreeNodeType AccessibilityTreeRootNode::NodeType() const
{
return TREE_NODE_TYPE_ROOT;
}
#endif // ACCESSIBILITY_EXTENSION_SUPPORT
|
#include <iostream>
#include<stdio.h>
#include<string.h>
#include <vector>
#include <string>
#include <cctype>
#include<math.h>
using namespace std;
|
// Copyright 2019 Erik Teichmann <kontakt.teichmann@gmail.com>
#include <vector>
#include "test/catch.hpp"
#include "test/harmonic_oscillator_ode.hpp"
#include "include/sam/system/euler_system.hpp"
#include "include/sam/observer/position_observer.hpp"
TEST_CASE("integrate simple system") {
// Integrate correctly changes the position
// Analytic solution is x=A*sin(omega*t + phi)
// for x(0)=0 and \dot{x}(0)=1 and with omega=2
// the solution is x = 0.5*sin(omega*t), \dot{x} = cos(omega*t)
double omega = 2.;
unsigned int N = 1;
unsigned int dimension = 2;
double dt = 0.01;
unsigned int n = 100;
double t = dt*static_cast<double>(n);
std::vector<double> initial_condition({0., 1.});
sam::EulerSystem<HarmonicOscillatorODE> system(N, dimension, omega);
system.SetPosition(initial_condition);
SECTION("integrate without observer") {
double t_0 = system.GetTime();
system.Integrate(dt, n);
std::vector<double> analytical = {1./omega*sin(omega*t), cos(omega*t)};
std::vector<double> numerical = system.GetPosition();
REQUIRE(numerical.size() == analytical.size());
CHECK(numerical[0] == Approx(analytical[0]).margin(0.01));
CHECK(numerical[1] == Approx(analytical[1]).margin(0.01));
// Integrate increases time correctly
double t_1 = system.GetTime();
CHECK(t == Approx(t_1 - t_0).margin(0.000001));
}
SECTION("integrate with observer") {
unsigned int n = 10;
std::vector<double> initial_condition {0., 1.};
system.SetPosition(initial_condition);
std::vector<std::vector<double>> position;
std::vector<double> t;
system.Integrate(dt, n,
sam::PositionObserver<std::vector<double>>(position, t));
REQUIRE(position.size() == n+1);
REQUIRE(t.size() == n+1);
for (size_t i = 0; i < t.size(); ++i) {
CHECK(dt*static_cast<double>(i) == Approx(t[i]).margin(0.0001));
std::vector<double> analytical = {0.5*sin(omega*t[i]),
cos(omega*t[i])};
std::vector<double> numerical = position[i];
REQUIRE(numerical.size() == analytical.size());
CHECK(numerical[0] == Approx(analytical[0]).margin(0.01));
CHECK(numerical[1] == Approx(analytical[1]).margin(0.01));
}
}
}
|
// Copyright (c) 2012-2016, The CryptoNote developers, The Bytecoin developers
// Copyright (c) 2019, The TurtleCoin Developers
// Copyright (c) 2019, The Karbo Developers
//
// This file is part of Karbo.
//
// Karbo is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Karbo is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Karbo. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <random>
#include <limits>
namespace Randomize
{
/* Used to obtain a random seed */
static thread_local std::random_device device;
/* Generator, seeded with the random device */
static thread_local std::mt19937 gen(device());
/* The distribution to get numbers for - in this case, uint8_t */
static std::uniform_int_distribution<int> distribution{0, (std::numeric_limits<uint8_t>::max)()};
/**
* Generate n random bytes (uint8_t), and place them in *result. Result should be large
* enough to contain the bytes.
*/
inline void randomBytes(size_t n, uint8_t *result)
{
for (size_t i = 0; i < n; i++)
{
result[i] = distribution(gen);
}
}
/**
* Generate n random bytes (uint8_t), and return them in a vector.
*/
inline std::vector<uint8_t> randomBytes(size_t n)
{
std::vector<uint8_t> result;
result.reserve(n);
for (size_t i = 0; i < n; i++)
{
result.push_back(distribution(gen));
}
return result;
}
/**
* Generate a random value of the type specified, in the full range of the
* type
*/
template <typename T>
T randomValue()
{
std::uniform_int_distribution<T> distribution{
std::numeric_limits<T>::min(), std::numeric_limits<T>::max()
};
return distribution(gen);
}
/**
* Generate a random value of the type specified, in the range [min, max]
* Note that both min, and max, are included in the results. Therefore,
* randomValue(0, 100), will generate numbers between 0 and 100.
*
* Note that min must be <= max, or undefined behaviour will occur.
*/
template <typename T>
T randomValue(T min, T max)
{
std::uniform_int_distribution<T> distribution{min, max};
return distribution(gen);
}
/**
* Obtain the generator used internally. Helpful for passing to functions
* like std::shuffle.
*/
inline std::mt19937 generator()
{
return gen;
}
}
|
#include <cmath>
#include <iostream>
using namespace std;
const int INF = 1 << 30;
int main() {
int N, M;
cin >> N >> M;
int a[N][M];
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
cin >> a[i][j];
}
}
if (N == 1) {
int ans = INF;
for (int j = 0; j < M - 1; ++j) {
ans = min(ans, abs(a[0][j + 1] - a[0][j]));
}
cout << ans << endl;
return 0;
}
int cost[N][N], dcost[N][N];
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
cost[i][j] = INF;
for (int k = 0; k < M; ++k) {
cost[i][j] = min(cost[i][j], abs(a[i][k] - a[j][k]));
}
dcost[i][j] = INF;
for (int k = 0; k < M - 1; ++k) {
dcost[i][j] = min(dcost[i][j], abs(a[i][k + 1] - a[j][k]));
}
}
}
int ans = 0;
for (int i = 0; i < N; ++i) {
int dp[1 << N][N];
fill(dp[0], dp[1 << N], 0);
dp[1 << i][i] = INF;
for (int b = 0; b < (1 << N); ++b) {
for (int k = 0; k < N; ++k) {
if (((b >> k) & 1) == 0) continue;
for (int l = 0; l < N; ++l) {
if ((b >> l) & 1) continue;
dp[b | (1 << l)][l] = max(dp[b | (1 << l)][l], min(dp[b][k], cost[k][l]));
}
}
}
for (int j = 0; j < N; ++j) {
ans = max(ans, min(dp[(1 << N) - 1][j], dcost[i][j]));
}
}
cout << ans << endl;
return 0;
}
|
#pragma once
#include "shape/Shape.h"
#include "shape/ElevationMap.h"
#include <typelib/typelib.h>
namespace siu {
/**
* Битовая карта с возможностью масштабирования (м-биткарта).
*/
template< size_t SX, size_t SY, size_t SZ >
class ScaleBitMap {
public:
/**
* Ссылки на масштабируемую битовую карту.
*/
typedef std::shared_ptr< ScaleBitMap > Ptr;
typedef std::unique_ptr< ScaleBitMap > UPtr;
/**
* Тип для статической битовой карты.
*/
typedef typelib::BitMap< SX, SY, SZ > bm_t;
/**
* Тип для ссылки на форму (источник).
*/
typedef typename shape::Shape< SX, SY, SZ >::Ptr shape_t;
/**
* Тип для ссылки на м-биткарту (источник).
*/
typedef Ptr scaleBitMap_t;
public:
ScaleBitMap();
virtual ~ScaleBitMap();
/**
* @return Сформированная битовая карта.
*/
bm_t const& draw() const;
/**
* Источником м-биткарты становится указанная форма: карта высот,
* эллипосид, биткарта и т.п..
*/
template< size_t OSX, size_t OSY, size_t OSZ >
ScaleBitMap& operator<<( const typename shape::Shape< OSX, OSY, OSZ >& source );
/**
* @return Ссылка на форму, которой инициирована эта м-биткарта.
*/
inline shape_t const& shape() const {
return mShape;
}
protected:
/**
* Форма для создания битовой карты.
*/
shape_t mShape;
/**
* Вычисленная битовая карта (кеш).
*
* @see draw()
*/
mutable bm_t bm_;
};
} // siu
#include "ScaleBitMap.inl"
|
#if !defined(FILEDOWNLOAD_HPP)
#define FILEDOWNLOAD_HPP
#include "http/response/HttpResponse.hpp"
class FileDownload : public HttpResponse
{
public:
FileDownload(ResponseContext& ctx, BufferChain& writeChain, struct stat *file);
~FileDownload();
};
#endif // FILEDOWNLOAD_HPP
|
#include<iostream>
using namespace std;
typedef unsigned long long int ll;
void nhap(ll &n,bool *&was,int *&a){
cin>>n;
was=new bool[n+1];
a=new int[n+1];
for(ll i=0;i<=n;i++) was[i]=true;
}
void xuat(ll n,int *a){
for(ll i=1;i<=n;i++) cout<<a[i];
cout<<endl;
}
void backtracking(ll n,bool *was,ll j,int *a){
for(ll i=1;i<=n;i++) if(was[i]){
a[j]=i;
was[i]=false;
if(j==n) xuat(n,a);
else backtracking(n,was,j+1,a);
was[i]=true;
}
}
int main(){
ll n,k=1,i;
bool *was;
int *a;
nhap(n,was,a);
for(ll i=2;i<=n;i++) k=k*i;
cout<<k<<endl;
backtracking(n,was,1,a);
delete []a;
delete []was;
return 0;
}
|
#pragma once
#include <aeMath.h>
#include "aePrerequisitesGraphics.h"
namespace aeEngineSDK
{
enum struct AE_FRUSTUM_DETECTIONS : uint8
{
AE_FRUSTUM_OUT,
AE_FRUSTUM_INTERSECTION,
AE_FRUSTUM_IN
};
class AE_GRAPHICS_EXPORT aeFrustum
{
public:
aeFrustum();
aeFrustum(const aeFrustum& F);
aeFrustum(const float& Near, const float& Far, const float& FOV);
~aeFrustum();
public:
float GetZoom();
float GetFOV();
float GetNearDistance();
float GetFarDistance();
void SetZoom(const float& Zoom);
void SetFOV(const float& FOV);
void SetNearDistance(const float& Near);
void SetFarDistance(const float& Far);
public:
void UpdateFrustum(const aeQuaternion& Rotation, const aeVector3& Position);
void UpdateFrustum(const aeMatrix3& Rotation, const aeVector3& Position);
void UpdateFrustum(const aeMatrix4& Transform);
AE_FRUSTUM_DETECTIONS DetectIntersection(const aeVector3& Point);
private:
float m_fNear, m_fFar, m_fFOV;
aeMatrix4 m_xTransform;
union
{
struct
{
aePlane m_xNear, m_xFar, m_xLeft, m_xRight, m_xBottom, m_xTop;
};
aePlane P[6];
};
};
}
|
#ifndef MATAILLE_H
#define MATAILLE_H
#include <QDialog>
#include <QSize>
#include "ui_MaTaille.h"
class CMaTaille : public QDialog
{
Q_OBJECT
public:
CMaTaille(QWidget *parent, int Largeur, int Hauteur);
~CMaTaille();
QSize getDim ();
bool IsModifier;
private:
Ui::CMaTaille ui;
double m_proportion;
int m_nLargeur;
int m_nHauteur;
private slots:
void MonOk();
void Larg();
void Haut();
};
#endif // MATAILLE_H
|
#include<vector> // vector
#include<iterator> //iterators
#include<iostream> //cin cout
#include<algorithm> // sort
using namespace std;
int main ()
{
// create a vector to hold numbers typed in
vector<int> v;
cout << "Please enter numbers (ctrl-D) ends sequence" << endl;
istream_iterator<int> start (cin); //input iterator from stream
istream_iterator<int> end;
// end of stream iterator
back_insert_iterator<vector<int> > dest (v); // append integers to vector
copy (start, end, dest); // copy cin numbers to vector
sort(v.begin(), v.end()); // sort the vector
copy (v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));
return 0;
}
|
#ifndef SPECEX_PSF_PROC__H
#define SPECEX_PSF_PROC__H
#include <string>
namespace specex {
// loading routines
void load_psf_work(specex::PSF_p psf);
}
#endif
|
#ifndef _GAME_H_
#define _GAME_H_
#include <SDL.h>
#include <vector>
#include "TextureManager.h"
#include "GameStateMachine.h"
class GameObject;
class Game
{
public :
bool init( const char* title, int xpos, int ypos, int width, int height, bool fullscreen );
void render();
void update();
void handleEvents();
void clean();
bool running() { return m_bRunning; }
void setRunning(bool _bool) { m_bRunning = _bool; }
static Game* Instance()
{
if (s_pInstance == nullptr)
{
s_pInstance = new Game();
}
return s_pInstance;
}
SDL_Renderer* get_Renderer() const { return m_pRenderer; }
GameStateMachine* getStateMachine() { return m_pGameStateMachine; }
private:
Game();
static Game* s_pInstance;
SDL_Window* m_pWindow;
SDL_Renderer* m_pRenderer;
SDL_Texture* m_pTexture;
int m_currentFrame;
int m_currentFrame2;
bool m_bRunning;
std::vector<GameObject*> m_gameObjects;
GameObject* m_go;
GameObject* m_player;
GameObject* m_enemy;
GameStateMachine* m_pGameStateMachine;
}typedef TheGame;
#endif // !
|
#include <cassert>
#include <map>
#include <regex>
#include <set>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
namespace {
static const std::set<std::string> GetValidSymbolsSet() {
const std::vector<std::string> valid_symbols = {
"AA", "AA0", "AA1", "AA2", "AE", "AE0", "AE1", "AE2", "AH", "AH0",
"AH1", "AH2", "AO", "AO0", "AO1", "AO2", "AW", "AW0", "AW1", "AW2",
"AY", "AY0", "AY1", "AY2", "B", "CH", "D", "DH", "EH", "EH0",
"EH1", "EH2", "ER", "ER0", "ER1", "ER2", "EY", "EY0", "EY1", "EY2",
"F", "G", "HH", "IH", "IH0", "IH1", "IH2", "IY", "IY0", "IY1",
"IY2", "JH", "K", "L", "M", "N", "NG", "OW", "OW0", "OW1",
"OW2", "OY", "OY0", "OY1", "OY2", "P", "R", "S", "SH", "T",
"TH", "UH", "UH0", "UH1", "UH2", "UW", "UW0", "UW1", "UW2", "V",
"W", "Y", "Z", "ZH"};
std::set<std::string> symbol_set;
for (auto &s : valid_symbols) {
symbol_set.insert(s);
}
return symbol_set;
}
// https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words-of-a-string
std::vector<std::string> split(const std::string &text,
const std::string &delims) {
std::vector<std::string> tokens;
std::size_t start = text.find_first_not_of(delims), end = 0;
while ((end = text.find_first_of(delims, start)) != std::string::npos) {
tokens.push_back(text.substr(start, end - start));
start = text.find_first_not_of(delims, end);
}
if (start != std::string::npos) tokens.push_back(text.substr(start));
return tokens;
}
static std::string GetPronounciation(
const std::set<std::string> &valid_symbols_set, const std::string &s) {
assert(s.size() >= 1);
std::string ss = s;
ss.pop_back(); // strip
std::vector<std::string> parts = split(ss, " ");
for (auto &part : parts) {
if (!valid_symbols_set.count(part)) {
return std::string();
}
}
// ' '.join(parts)
std::string ret;
for (size_t i = 0; i < parts.size(); i++) {
ret += parts[i];
if (i != (parts.size() - 1)) {
ret += ' ';
}
}
return ret;
}
// CMUDict data. http://www.speech.cs.cmu.edu/cgi-bin/cmudict
static bool ParseCMUDict(const std::string &filename,
std::map<std::string, std::vector<std::string>> *cmudict) {
std::ifstream ifs(filename);
if (!ifs) {
return false;
}
cmudict->clear();
std::set<std::string> valid_symbols_set = GetValidSymbolsSet();
std::regex alt_re("\\([0-9]+\\)");
std::string line;
while (std::getline(ifs, line)) {
if ((line.size() > 0) &&
(((line[0] >= 'A') && (line[0] <= 'Z')) || (line[0] == '\''))) {
std::vector<std::string> parts = split(line, " ");
if (parts.size() >= 2) {
std::string word;
assert(!word.empty());
std::string pronounciation =
GetPronounciation(valid_symbols_set, parts[1]);
if (!pronounciation.empty()) {
(*cmudict)[word].push_back(pronounciation);
}
}
}
}
return true;
}
/*
cleaners.py
'''
Cleaners are transformations that run over the input text at both training and eval time.
Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
hyperparameter. Some cleaners are English-specific. You'll typically want to use:
1. "english_cleaners" for English text
2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
the Unidecode library (https://pypi.python.org/pypi/Unidecode)
3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
the symbols in symbols.py to match your data).
'''
# Regular expression matching whitespace:
_whitespace_re = re.compile(r'\s+')
# List of (regular expression, replacement) pairs for abbreviations:
_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
('mrs', 'misess'),
('mr', 'mister'),
('dr', 'doctor'),
('st', 'saint'),
('co', 'company'),
('jr', 'junior'),
('maj', 'major'),
('gen', 'general'),
('drs', 'doctors'),
('rev', 'reverend'),
('lt', 'lieutenant'),
('hon', 'honorable'),
('sgt', 'sergeant'),
('capt', 'captain'),
('esq', 'esquire'),
('ltd', 'limited'),
('col', 'colonel'),
('ft', 'fort'),
]]
def expand_abbreviations(text):
for regex, replacement in _abbreviations:
text = re.sub(regex, replacement, text)
return text
def expand_numbers(text):
return normalize_numbers(text)
def lowercase(text):
return text.lower()
def collapse_whitespace(text):
return re.sub(_whitespace_re, ' ', text)
def convert_to_ascii(text):
return unidecode(text)
def basic_cleaners(text):
'''Basic pipeline that lowercases and collapses whitespace without transliteration.'''
text = lowercase(text)
text = collapse_whitespace(text)
return text
def transliteration_cleaners(text):
'''Pipeline for non-English text that transliterates to ASCII.'''
text = convert_to_ascii(text)
text = lowercase(text)
text = collapse_whitespace(text)
return text
def english_cleaners(text):
'''Pipeline for English text, including number and abbreviation expansion.'''
text = convert_to_ascii(text)
text = lowercase(text)
text = expand_numbers(text)
text = expand_abbreviations(text)
text = collapse_whitespace(text)
return text
symbols.py
_pad = '_'
_eos = '~'
_characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\'(),-.:;? '
# Prepend "@" to ARPAbet symbols to ensure uniqueness (some are the same as uppercase letters):
_arpabet = ['@' + s for s in cmudict.valid_symbols]
# Export all symbols:
symbols = [_pad, _eos] + list(_characters) + _arpabet
numbers.py
_inflect = inflect.engine()
_comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])')
_decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)')
_pounds_re = re.compile(r'£([0-9\,]*[0-9]+)')
_dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)')
_ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)')
_number_re = re.compile(r'[0-9]+')
def _remove_commas(m):
return m.group(1).replace(',', '')
def _expand_decimal_point(m):
return m.group(1).replace('.', ' point ')
def _expand_dollars(m):
match = m.group(1)
parts = match.split('.')
if len(parts) > 2:
return match + ' dollars' # Unexpected format
dollars = int(parts[0]) if parts[0] else 0
cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
if dollars and cents:
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
cent_unit = 'cent' if cents == 1 else 'cents'
return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit)
elif dollars:
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
return '%s %s' % (dollars, dollar_unit)
elif cents:
cent_unit = 'cent' if cents == 1 else 'cents'
return '%s %s' % (cents, cent_unit)
else:
return 'zero dollars'
def _expand_ordinal(m):
return _inflect.number_to_words(m.group(0))
def _expand_number(m):
num = int(m.group(0))
if num > 1000 and num < 3000:
if num == 2000:
return 'two thousand'
elif num > 2000 and num < 2010:
return 'two thousand ' + _inflect.number_to_words(num % 100)
elif num % 100 == 0:
return _inflect.number_to_words(num // 100) + ' hundred'
else:
return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ')
else:
return _inflect.number_to_words(num, andword='')
def normalize_numbers(text):
text = re.sub(_comma_number_re, _remove_commas, text)
text = re.sub(_pounds_re, r'\1 pounds', text)
text = re.sub(_dollars_re, _expand_dollars, text)
text = re.sub(_decimal_number_re, _expand_decimal_point, text)
text = re.sub(_ordinal_re, _expand_ordinal, text)
text = re.sub(_number_re, _expand_number, text)
return text
*/
} // namespace
int main(int argc, char **argv) {
(void)argc;
(void)argv;
std::string cmudict_filename = "";
std::map<std::string, std::vector<std::string>> cmudict;
bool ret = ParseCMUDict(cmudict_filename, &cmudict);
if (!ret) {
std::cerr << "Failed to load/parse CMU dict file : " << cmudict_filename << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
//min element after any number of operation.
#include<iostream>
#include<stack>
// 1=push, 2=pop(), 3=min()
using namespace std;
int main()
{
stack<int> mainstack;
stack<int> auxistack;
int n,opn,data,temp,i,c=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&opn);
switch(opn)
{
case 1:
{
scanf("%d",&data);
mainstack.push(data);
if(auxistack.empty())
auxistack.push(data);
else
{
if(data<auxistack.top())
auxistack.push(data);
else{}
}
break;
c++;
}
case 2 :
{
temp=mainstack.top();
mainstack.pop();
if(temp==auxistack.top())
{
auxistack.pop();
}
break;
}
case 3 :
{
printf("%d \n",auxistack.top());
break;
}
default :
{
}
}
}
|
/*
* Copyright (c) 2012 Oleg Linkin MaledictusDeMagog@gmail.com
*
* 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.
*/
#pragma once
#include <string>
#include <boost/asio.hpp>
#include <libtorrent/torrent_info.hpp>
#include <libtorrent/session.hpp>
namespace IFVGrabber
{
class TorrentManager
{
libtorrent::session *Session_;
boost::asio::io_service IoService_;
boost::asio::deadline_timer *Timer_;
std::map<libtorrent::torrent_handle, std::pair<std::string, std::string>> DownloadedFile2SaveDir_;
public:
static const int DownloadSize_ = 10000000;
TorrentManager ();
~TorrentManager ();
void AddFile (const std::string& torrent,
const std::string& file, const std::string& dir);
void AddDownload (const std::string& torrent,
const std::string& file, const std::string& dir);
void ParseFile (const std::string& path);
void QueryLibtorrentForWarnings (const boost::system::error_code& error);
void PostDownloadHandler (const libtorrent::torrent_handle& handle);
private:
void Init ();
bool IsTorrentFile (const std::string& path) const;
};
}
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Triad National Security, LLC. This file is part of the
// Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms
// in the LICENSE file found in the top-level directory of this distribution.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef NOX_THYRA_MODEL_EVALUATOR_HEAT_DECL_HPP
#define NOX_THYRA_MODEL_EVALUATOR_HEAT_DECL_HPP
#include "Thyra_StateFuncModelEvaluatorBase.hpp"
#include "Mesh.h"
#include "preconditioner.hpp"
#include "timestep.hpp"
template<class Scalar> class ModelEvaluatorHEAT;
template<class Scalar>
Teuchos::RCP<ModelEvaluatorHEAT<Scalar> >
modelEvaluatorHEAT(const Teuchos::RCP<const Epetra_Comm>& comm,
Mesh &mesh,
Teuchos::ParameterList plist);
/// DEPRECATED
template<class Scalar>
class ModelEvaluatorHEAT
: public ::timestep<Scalar>, public ::Thyra::StateFuncModelEvaluatorBase<Scalar>
{
public:
ModelEvaluatorHEAT(const Teuchos::RCP<const Epetra_Comm>& comm,
Mesh *mesh,
Teuchos::ParameterList plist);
~ModelEvaluatorHEAT();
void set_x0(const Teuchos::ArrayView<const Scalar> &x0);
void setShowGetInvalidArgs(bool showGetInvalidArg);
void set_W_factory(const Teuchos::RCP<const ::Thyra::LinearOpWithSolveFactoryBase<Scalar> >& W_factory);
Teuchos::RCP<const ::Thyra::VectorSpaceBase<Scalar> > get_x_space() const;
Teuchos::RCP<const ::Thyra::VectorSpaceBase<Scalar> > get_f_space() const;
::Thyra::ModelEvaluatorBase::InArgs<Scalar> getNominalValues() const;
Teuchos::RCP< ::Thyra::LinearOpBase<Scalar> > create_W_op() const;
Teuchos::RCP<const ::Thyra::LinearOpWithSolveFactoryBase<Scalar> > get_W_factory() const;
::Thyra::ModelEvaluatorBase::InArgs<Scalar> createInArgs() const;
Teuchos::RCP< ::Thyra::PreconditionerBase< Scalar > > create_W_prec() const;
void init_nox();
void initialize();
void finalize();
void advance();
void compute_error( double *u);
void write_exodus(){};
private:
virtual Teuchos::RCP<Epetra_CrsGraph> createGraph();
::Thyra::ModelEvaluatorBase::OutArgs<Scalar> createOutArgsImpl() const;
void evalModelImpl(
const ::Thyra::ModelEvaluatorBase::InArgs<Scalar> &inArgs,
const ::Thyra::ModelEvaluatorBase::OutArgs<Scalar> &outArgs
) const;
private: // data members
const Teuchos::RCP<const Epetra_Comm> comm_;
Mesh *mesh_;
Teuchos::ParameterList paramList;
double dt_;
Teuchos::RCP<const ::Thyra::VectorSpaceBase<Scalar> > x_space_;
Teuchos::RCP<const Epetra_Map> x_owned_map_;
Teuchos::RCP<const ::Thyra::VectorSpaceBase<Scalar> > f_space_;
Teuchos::RCP<const Epetra_Map> f_owned_map_;
Teuchos::RCP<Epetra_CrsGraph> W_graph_;
Teuchos::RCP<const ::Thyra::LinearOpWithSolveFactoryBase<Scalar> > W_factory_;
::Thyra::ModelEvaluatorBase::InArgs<Scalar> nominalValues_;
Teuchos::RCP< ::Thyra::VectorBase<Scalar> > x0_;
bool showGetInvalidArg_;
::Thyra::ModelEvaluatorBase::InArgs<Scalar> prototypeInArgs_;
::Thyra::ModelEvaluatorBase::OutArgs<Scalar> prototypeOutArgs_;
Teuchos::RCP<Epetra_CrsMatrix> P_;
Teuchos::RCP<preconditioner <Scalar> > prec_;
Teuchos::RCP<NOX::Solver::Generic> solver_;
Teuchos::RCP<Epetra_Vector> u_old_;
double time_;
};
//==================================================================
#include "ModelEvaluatorHEAT_def.hpp"
//==================================================================
#endif
|
#include "printHelp.h"
#include "tokenStream.h"
#include "keys.h"
void Token_stream::putback (Token t)
{
if (full)
error("putback() into a full buffer");
buffer = t;
full = true;
}
Token Token_stream::get ()
{
if (full)
{
full = false;
return buffer;
}
char ch;
cin >> ch;
switch (ch)
{
case print:
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '%':
case '=':
case ',':
return Token{ ch };
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
cin.putback(ch);
double val;
cin >> val;
return Token{ number, val };
}
default:
if (isalpha(ch))
{
string s;
s += ch;
while (cin.get(ch) &&
(isalpha(ch) || isdigit(ch) || ch == '_'))
s += ch;
cin.putback(ch);
if (s == quitString) return Token{ quit};
if (s == declkey) return Token{ let };
if (s == sqrtString) return Token{ sqrtKey};
if (s == powString) return Token{ powKey};
if (s == logString) return Token { logKey };
if (s == helpString) {
printHelp();
return Token{ help };
}
return Token{ name, s };
} else {
string s;
s += ch;
cout << s << endl;
if (s == declkey) return Token{ let };
}
error("Bad token");
}
}
void Token_stream::ignore (char c)
{
if (full && c == buffer.kind)
{
full = false;
return;
}
full = false;
char ch;
while (cin >> ch)
if (ch == c) return;
}
|
#include "Mesh.h"
// BASE MESH CONSTRUCTOR
Mesh::Mesh() :
m_vbo(0),
m_vao(0),
m_ibo(0),
m_size(0)
{
}
// MESH OVERLOAD PASSING IN VERTEX AND INDEX ARRAYS
Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices) {
generateMesh(vertices, indices);
}
// DESTRUCTOR
Mesh::~Mesh() {
if (m_vbo) glDeleteBuffers(1, &m_vbo);
if (m_ibo) glDeleteBuffers(1, &m_ibo);
if (m_vao) glDeleteVertexArrays(1, &m_vao);
}
// GENERATE A MESH BASED ON PASSED IN VERTEX AND INDEX ARRAYS
void Mesh::generateMesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices) {
if (!m_vao) glGenVertexArrays(1, &m_vao);
if (!m_vbo) glGenBuffers(1, &m_vbo);
if (!m_ibo) glGenBuffers(1, &m_ibo);
m_size = indices.size();
glBindVertexArray(m_vao);
// VERTEX BUFFER OBJECT
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);
// INDEX BUFFER OBJECT
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
// VERTEX ATTRIBUTE POINTERS (POSITION, TEXTURE COORDINATES, NORMALS)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_textureCoord));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_normal));
}
// SEND MESH TO GPU TO RENDER
void Mesh::draw() const {
// BIND VERTEX ARRAY
glBindVertexArray(m_vao);
// ENABLE VERTEX ATTRIBUTE ARRAYS
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
// DRAW THE DAMN TRIANGLES
glDrawElements(GL_TRIANGLES, m_size, GL_UNSIGNED_INT, 0);
// DISABLE VERTEX ATTRIBUTE ARRAYS
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
// UNBIND VERTEX ARRAY
glBindVertexArray(0);
}
|
/**
* Copyright (c) 2007-2012, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file vt52_curses.hh
*/
#ifndef vt52_curses_hh
#define vt52_curses_hh
#include <list>
#include <string>
#include "view_curses.hh"
/**
* VT52 emulator for curses, useful for mediating between curses and readline,
* which don't play well together. It is expected that a subclass of this
* class will fork off a child process that sends and receives VT52 keycodes(?)
* which is translated by this class into curses calls.
*
* VT52 seems to be the simplest terminal to emulate since we do not need to
* maintain the state of the screen, beyond past lines. For example, when
* inserting a character, VT52 moves the cursor to the insertion point, clears
* the rest of the line and then rewrites the rest of the line with the new
* character. This is in contrast to VT100 which moves the cursor to the
* insertion point and then sends a code to insert the character and relying
* on the terminal to shift the rest of the line to the right a character.
*/
class vt52_curses : public view_curses {
public:
/** @param win The curses window this view is attached to. */
void set_window(WINDOW* win) { this->vc_window = win; }
/** @return The curses window this view is attached to. */
WINDOW* get_window() { return this->vc_window; }
void set_left(int left) { this->vc_left = left; }
int get_left() const { return this->vc_left; }
/**
* Set the Y position of this view on the display. A value greater than
* zero is considered to be an absolute size. A value less than zero makes
* the position relative to the bottom of the enclosing window.
*
* @param y The Y position of the cursor on the curses display.
*/
void set_y(int y) { this->vc_y = y; }
/** @return The abs/rel Y position of the cursor on the curses display. */
int get_y() const { return this->vc_y; }
/** @param x The X position of the cursor on the curses display. */
void set_x(int x) { this->vc_x = x; }
/** @return The X position of the cursor on the curses display. */
int get_x() const { return this->vc_x; }
/**
* @return The height of this view, which consists of a single line for
* input, plus any past lines of output, which will appear ABOVE the Y
* position for this view.
* @todo Kinda hardwired to the way readline works.
*/
int get_height() { return 1; }
void set_max_height(int mh) { this->vc_max_height = mh; }
int get_max_height() const { return this->vc_max_height; }
/**
* Map an ncurses input keycode to a vt52 sequence.
*
* @param ch The input character.
* @param len_out The length of the returned sequence.
* @return The vt52 sequence to send to the child.
*/
const char* map_input(int ch, int& len_out);
/**
* Map VT52 output to ncurses calls.
*
* @param output VT52 encoded output from the child process.
* @param len The length of the output array.
*/
void map_output(const char* output, int len);
/**
* Paints any past lines and moves the cursor to the current X position.
*/
void do_update();
const static char ESCAPE = 27; /*< VT52 Escape key value. */
const static char BACKSPACE = 8; /*< VT52 Backspace key value. */
const static char BELL = 7; /*< VT52 Bell value. */
const static char STX = 2; /*< VT52 Start-of-text value. */
protected:
/** @return The absolute Y position of this view. */
int get_actual_y()
{
unsigned long width, height;
int retval;
getmaxyx(this->vc_window, height, width);
if (this->vc_y < 0) {
retval = height + this->vc_y;
} else {
retval = this->vc_y;
}
return retval;
}
int get_actual_width()
{
auto retval = getmaxx(this->vc_window);
if (this->vc_width < 0) {
retval -= this->vc_left;
retval += this->vc_width;
} else if (this->vc_width > 0) {
retval = this->vc_width;
} else {
retval = retval - this->vc_left;
}
return retval;
}
WINDOW* vc_window{nullptr}; /*< The window that contains this view. */
int vc_left{0};
int vc_x{0}; /*< The X position of the cursor. */
int vc_y{0}; /*< The Y position of the cursor. */
int vc_max_height{0};
char vc_escape[16]; /*< Storage for escape sequences. */
int vc_escape_len{0}; /*< The number of chars in vc_escape. */
int vc_expected_escape_len{-1};
char vc_map_buffer{0}; /*<
* Buffer returned by map_input for trivial
* translations (one-to-one).
*/
attr_line_t vc_line;
};
#endif
|
#include <windows.h>
struct S {
~S() { SetLastError(2); }
};
void foo() {
S s;
}
int main(int, const char**) {
foo();
return GetLastError()-2;
}
|
#ifndef FLYWEIGHT_H
#define FLYWEIGHT_H
#include<iostream>
#include<string>
class Flyweight {
public:
virtual ~Flyweight();
virtual void Operation(const std::string &extrinsicState);
std::string GetIntrinsicState();
protected:
explicit Flyweight(std::string intrinsicState);
private:
std::string _intrinsicState;
};
class ConcreteFlyweight :public Flyweight {
public:
explicit ConcreteFlyweight(std::string intrinsicState);
~ConcreteFlyweight();
void Operation(const std::string &extrinsicState) override;
};
#endif
|
#include "stdafx.h"
#include "Prof-UIS.h"
// constants
#define CONTROLBAR_CLASSNAME "CExtControlBar"
#define CONTROLBAR_AUTOHIDEBUTTON_CLASSNAME "CExtBarNcAreaButtonAutoHide"
#define CONTROLBAR_CLOSEBUTTON_CLASSNAME "CExtBarNcAreaButtonClose"
#define CONTROLBAR_EXPANDBUTTON_CLASSNAME "CExtBarNcAreaButtonExpand"
#define CONTROLBAR_MENUBUTTON_CLASSNAME "CExtBarNcAreaButtonMenu"
// forward declaration of functions
CExtControlBar* uiSalGetControlBarObject(HWND controlBarHandle);
CExtBarNcAreaButton* uiSalGetBarNcAreaButtonObject(CExtControlBar* controlBar, LPCSTR buttonClassName);
bool uiSalRemoveBarNcAreaButtonObject(CExtControlBar* controlBar, LPCSTR buttonClassName);
bool uiSalIsDerivedFrom(CRuntimeClass* runtimeClass, LPCSTR className);
extern "C" __declspec(dllexport) BOOL WINAPI UISalControlBarAppearInDockSiteControlBarPopupMenu(HWND controlBarHandle, BOOL appearInDockSiteControlBarPopupMenu)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar == NULL) { return FALSE; }
// change the value
BOOL previousAppearInDockSiteControlBarPopupMenu = controlBar->m_bAppearInDockSiteControlBarPopupMenu;
controlBar->m_bAppearInDockSiteControlBarPopupMenu = appearInDockSiteControlBarPopupMenu;
return previousAppearInDockSiteControlBarPopupMenu;
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarToggleDocking(HWND controlBarHandle)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// toggle docking
controlBar->ToggleDocking();
}
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarRemoveAllButtons(HWND controlBarHandle)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// remove all buttons
controlBar->NcButtons_RemoveAll();
}
}
extern "C" __declspec(dllexport) BOOL WINAPI UISalControlBarIsAutoHideButtonPresent(HWND controlBarHandle)
{
// get object
BOOL result = FALSE;
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// check AutoHide button
CExtBarNcAreaButton* button = uiSalGetBarNcAreaButtonObject(controlBar, CONTROLBAR_AUTOHIDEBUTTON_CLASSNAME);
result = (button != NULL);
}
return result;
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarRemoveAutoHideButton(HWND controlBarHandle)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// remove AutoHide button
uiSalRemoveBarNcAreaButtonObject(controlBar, CONTROLBAR_AUTOHIDEBUTTON_CLASSNAME);
}
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarEnableAutoHideButton(HWND controlBarHandle, BOOL enable)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// enable AutoHide button
CExtBarNcAreaButton* button = uiSalGetBarNcAreaButtonObject(controlBar, CONTROLBAR_AUTOHIDEBUTTON_CLASSNAME);
if (button != NULL)
{
button->DisabledSet((enable ? false : true));
}
}
}
extern "C" __declspec(dllexport) BOOL WINAPI UISalControlBarIsCloseButtonPresent(HWND controlBarHandle)
{
// get object
BOOL result = FALSE;
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// check Close button
CExtBarNcAreaButton* button = uiSalGetBarNcAreaButtonObject(controlBar, CONTROLBAR_CLOSEBUTTON_CLASSNAME);
result = (button != NULL);
}
return result;
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarRemoveCloseButton(HWND controlBarHandle)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// remove Close button
uiSalRemoveBarNcAreaButtonObject(controlBar, CONTROLBAR_CLOSEBUTTON_CLASSNAME);
}
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarEnableCloseButton(HWND controlBarHandle, BOOL enable)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// enable Close button
CExtBarNcAreaButton* button = uiSalGetBarNcAreaButtonObject(controlBar, CONTROLBAR_CLOSEBUTTON_CLASSNAME);
if (button != NULL)
{
button->DisabledSet((enable ? false : true));
}
}
}
extern "C" __declspec(dllexport) BOOL WINAPI UISalControlBarIsExpandButtonPresent(HWND controlBarHandle)
{
// get object
BOOL result = FALSE;
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// check Expand button
CExtBarNcAreaButton* button = uiSalGetBarNcAreaButtonObject(controlBar, CONTROLBAR_EXPANDBUTTON_CLASSNAME);
result = (button != NULL);
}
return result;
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarRemoveExpandButton(HWND controlBarHandle)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// remove Expand button
uiSalRemoveBarNcAreaButtonObject(controlBar, CONTROLBAR_EXPANDBUTTON_CLASSNAME);
}
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarEnableExpandButton(HWND controlBarHandle, BOOL enable)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// enable Expand button
CExtBarNcAreaButton* button = uiSalGetBarNcAreaButtonObject(controlBar, CONTROLBAR_EXPANDBUTTON_CLASSNAME);
if (button != NULL)
{
button->DisabledSet((enable ? false : true));
}
}
}
extern "C" __declspec(dllexport) BOOL WINAPI UISalControlBarIsMenuButtonPresent(HWND controlBarHandle)
{
// get object
BOOL result = FALSE;
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// check Menu button
CExtBarNcAreaButton* button = uiSalGetBarNcAreaButtonObject(controlBar, CONTROLBAR_MENUBUTTON_CLASSNAME);
result = (button != NULL);
}
return result;
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarRemoveMenuButton(HWND controlBarHandle)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// remove Menu button
uiSalRemoveBarNcAreaButtonObject(controlBar, CONTROLBAR_MENUBUTTON_CLASSNAME);
}
}
extern "C" __declspec(dllexport) void WINAPI UISalControlBarEnableMenuButton(HWND controlBarHandle, BOOL enable)
{
// get object
CExtControlBar* controlBar = uiSalGetControlBarObject(controlBarHandle);
if (controlBar != NULL)
{
// enable Menu button
CExtBarNcAreaButton* button = uiSalGetBarNcAreaButtonObject(controlBar, CONTROLBAR_MENUBUTTON_CLASSNAME);
if (button != NULL)
{
button->DisabledSet((enable ? false : true));
}
}
}
CExtControlBar* uiSalGetControlBarObject(HWND controlBarHandle)
{
// try to find the according CExtControlBar object
HWND windowToVerify = controlBarHandle;
while (windowToVerify != NULL)
{
// get window object
CWnd* window = CWnd::FromHandlePermanent(windowToVerify);
if (window == NULL) { return NULL; }
// now determine object name
CRuntimeClass* runtimeClass = window->GetRuntimeClass();
if (uiSalIsDerivedFrom(runtimeClass, CONTROLBAR_CLASSNAME))
{
// object found
return (CExtControlBar*)CExtControlBar::FromHandlePermanent(windowToVerify);
}
// step up to parent window
windowToVerify = ::GetAncestor(windowToVerify, GA_PARENT);
}
// object not found
return NULL;
}
CExtBarNcAreaButton* uiSalGetBarNcAreaButtonObject(CExtControlBar* controlBar, LPCSTR buttonClassName)
{
// find button object
CExtBarNcAreaButton* result = NULL;
if (controlBar != NULL)
{
// enumerate all existing buttons
INT buttonCount = controlBar->NcButtons_GetCount();
for (INT buttonIndex = 0; buttonIndex < buttonCount; buttonIndex++)
{
// get button and detect type
CExtBarNcAreaButton* button = controlBar->NcButtons_GetAt(buttonIndex);
if (button != NULL)
{
// detect type
CRuntimeClass* runtimeClass = button->GetRuntimeClass();
if (uiSalIsDerivedFrom(runtimeClass, buttonClassName))
{
// button found
result = button;
break;
}
}
}
}
return result;
}
bool uiSalRemoveBarNcAreaButtonObject(CExtControlBar* controlBar, LPCSTR buttonClassName)
{
// find button object
bool result = false;
if (controlBar != NULL)
{
// enumerate all existing buttons
INT buttonCount = controlBar->NcButtons_GetCount();
for (INT buttonIndex = 0; buttonIndex < buttonCount; buttonIndex++)
{
// get button and detect type
CExtBarNcAreaButton* button = controlBar->NcButtons_GetAt(buttonIndex);
if (button != NULL)
{
// detect type
CRuntimeClass* runtimeClass = button->GetRuntimeClass();
if (uiSalIsDerivedFrom(runtimeClass, buttonClassName))
{
// button found
controlBar->NcButtons_RemoveAt(buttonIndex);
result = true;
break;
}
}
}
}
return result;
}
bool uiSalIsDerivedFrom(CRuntimeClass* runtimeClass, LPCSTR className)
{
// check class hierarchy
bool result = false;
while ((runtimeClass != NULL) && (runtimeClass->m_pfnGetBaseClass != NULL))
{
// test for className
if (strcmp(runtimeClass->m_lpszClassName, className) == 0)
{
// class found
result = true;
break;
}
// get base class
runtimeClass = runtimeClass->m_pfnGetBaseClass();
}
return result;
}
|
//--------------------------------------------------------------------------------------
// File : s3d_hdr.h
// Desc : HDR File Module.
// Copyright(c) Project Asura. All right reserved.
//--------------------------------------------------------------------------------------
#pragma once
//--------------------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------------------
#include <s3d_typedef.h>
namespace s3d {
//--------------------------------------------------------------------------------------
//! @brief HDRファイルに保存します.
//!
//! @param[in] filename ファイル名です.
//! @param[in] width 画像の横幅です.
//! @param[in] height 画像の縦幅です.
//! @param[in] gamma ガンマ値です.
//! @param[in] exposure 露光値です.
//! @param[in] pPixels ピクセルデータです.
//--------------------------------------------------------------------------------------
bool SaveToHDR(
const char* filename,
const s32 width,
const s32 height,
const s32 component,
const f32 gamma,
const f32 expsoure,
const f32* pPixel );
//--------------------------------------------------------------------------------------
//! @brief HDRファイルから読み込みします.
//!
//! @param[in] filename ファイル名です.
//! @param[out] width 画像の横幅です.
//! @param[out] height 画像の縦幅です.
//! @param[out] gamma ガンマ値です.
//! @param[out] exposure 露光値です.
//! @param[out] ppPixels ピクセルデータです.
//--------------------------------------------------------------------------------------
bool LoadFromHDR(
const char* filename,
s32& width,
s32& height,
f32& gamma,
f32& exposure,
f32** ppPixel );
} // namespace s3d
|
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <tuple>
#include <algorithm>
#include <types.hpp>
#include <property.hpp>
#include <model.hpp>
#include <shaderman.h>
Material1::~Material1()
{
for (uint i = 0; i < this->Materials.size(); i++)
for (uint j = 0; j < this->Materials[i].size(); j++)
glDeleteTextures(1, &(this->Materials[i][j].id));
}
bool
Material1::load(const aiScene *scene)
{
std::map<std::string, GLuint> textures_cache;
std::string root_path = this->model->getRootPath();
this->Materials.resize(scene->mNumMaterials);
for (GLuint i = 0; i < scene->mNumMaterials; i++) {
std::cerr << "material indx: " << i << std::endl;
aiMaterial *mat = scene->mMaterials[i];
aiString path;
Material material;
GLuint gpu_handle;
for (GLuint j = 0; j < TEX_NASSIMP_TYPE; j++) {
if (mat->GetTextureCount(texture_types_supported[j].aiTextype) > 0) {
mat->GetTexture(texture_types_supported[j].aiTextype, 0, &path);
std::string full_path = root_path + "/" + std::string(path.C_Str());
auto it = textures_cache.find(full_path);
if (it == textures_cache.end()) {
gpu_handle = load2DTexture2GPU(full_path);
textures_cache.insert(std::make_pair(full_path, gpu_handle));
} else
gpu_handle = it->second;
material.push_back(
Texture(gpu_handle,
texture_types_supported[j].ourTextype));
}
}
this->Materials[i] = material;
}
return scene->mNumMaterials;
}
void
Material1::draw(const msg_t material_id)
{
const ShaderMan *sm = this->model->currentShader();
//assume I already enabled the program
const Material& mat = this->Materials[material_id.u];
for (uint i = 0; i < mat.size(); i++) {
GLuint texi = sm->getTexUniform(mat[i].type);
glActiveTexture(GL_TEXTURE0 + texi);
glBindTexture(GL_TEXTURE_2D, mat[i].id);
}
}
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <glog/logging.h>
#include "server.h"
#include "proto/machine_study.pb.h"
using namespace std::placeholders;
static void readcb(int fd, char* buf, int len)
{
net::Coder coder;
coder.decoding(buf, len);
printf("msg %s\n", coder.getMsgName().c_str());
invorkfun(fd, coder.getMsgName(), coder.getBody());
}
static void heart(int fd, const message_t & v)
{
mstudy::Heart * msg = dynamic_cast<mstudy::Heart *>(v.get());
LOG(INFO) << "Heart: " << msg->heart();
}
int main(int argc, char * argv[])
{
int port = atoi(argv[1]);
registerfunc<mstudy::Heart>(std::bind(heart,_1, _2));
LOG(INFO) << "Service listen at prot " << port;
co_setreadcb(readcb);
co_service(port, 2);
return 0;
}
|
#pragma once
using BNN_TYPE = float;
struct NodeBuilder
{
virtual ~NodeBuilder() = default;
};
|
#include<bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define pb push_back
#define mp make_pair
#define MAX 50004
typedef long long ll;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--) {
int n;
cin>>n;
int arr[n],gcd;
for(int i=0;i<n;i++) {
cin>>arr[i];
if(i==0)
gcd=arr[i];
else
gcd=__gcd(gcd,arr[i]);
}
if(gcd==1) {
cout<<0<<"\n";
} else {
cout<<-1<<"\n";
}
}
return 0;
}
|
#ifndef SHOOTER_H
#define SHOOTER_H
#include "aggressor.h"
#include "movable.h"
class Shooter :
public Aggressor,
public Movable
{
void updateGunPos();
protected:
XY _gun_pos;
public:
Shooter(XY pos, XY size, int hp, double velo_value, int attack_frequency, Team *my_team, GameManager *game);
void updateElement();
~Shooter();
};
#endif // SHOOTER_H
|
#ifndef DetectorConstruction_h
#define DetectorConstruction_h 1
#include<globals.hh>
#include<G4VUserDetectorConstruction.hh>
#include<G4VSolid.hh>
#include<G4LogicalVolume.hh>
#include<G4VPhysicalVolume.hh>
#include<G4Material.hh>
class World {
protected:
G4VSolid *solid;
G4LogicalVolume *logic;
G4VPhysicalVolume *physic;
G4Material *mater;
double sizex, sizey, sizez;
public:
World(double size_x, double size_y, double size_z, G4Material *mater_=NULL);
operator G4LogicalVolume*() {return logic;}
G4LogicalVolume *getLogic() {return logic;}
G4VSolid *getSolid() {return solid;}
G4VPhysicalVolume *getPhysic() {return physic;}
};
class DetectorConstruction : public G4VUserDetectorConstruction
{
public:
DetectorConstruction();
~DetectorConstruction();
G4VPhysicalVolume* Construct();
protected:
World *world;
};
#endif
|
#include "module/config.h"
#include <fstream>
#include <iostream>
using namespace std;
int loadDataFromFile() {
ifstream fin("/usr/lib/work-more/cfg/list.txt");
int i = 0;
string str;
while (getline(fin, str)) {
if (i >= 50) {
break;
}
cout << "===" << str << endl;
}
return 0;
}
int loadListData(char** list) {
ifstream fin("~/.work-more/cfg/list.txt");
if (fin) {
cout << "==1111=" << endl;
} else {
cout << "==2222=" << endl;
ifstream fin("/usr/lib/work-more/cfg/list.txt");
}
int i = 0;
string str;
while (getline(fin, str)) {
if (i >= 50) {
break;
}
int len = str.length();
list[i] = (char *) malloc((len + 1) * sizeof(char));
str.copy(list[i], len, 0);
i++;
}
return i;
}
|
#pragma once
enum MonsterID;
class MonsterBox
{
public:
bool isGot(MonsterID id);
void GetMonster(MonsterID id);
static MonsterBox& GetInstance() {
static MonsterBox instance;
return instance;
}
private:
void initFile();
void LoadMyBox();
int m_monsters[30] = { 0 };
};
static MonsterBox& IMonsterBox() {
return MonsterBox::GetInstance();
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Engine/UserDefinedEnum.h"
#include "MyEnums.generated.h"
/**
*
*/
UCLASS()
class FIGHTWITHBLOCK_API UMyEnums : public UUserDefinedEnum
{
GENERATED_BODY()
};
UENUM(BlueprintType)
enum class ECamp: uint8
{
EBlue UMETA(DisplayName = "Blue"),
ERed UMETA(DisplayName = "Red"),
EDefault UMETA(DisplayName = "neutral")
};
UENUM(BlueprintType)
enum class EGameState: uint8
{
ENormal UMETA(DisplayName = "Normal"),
EReady UMETA(DisplayName = "Ready"),
ERunning UMETA(DisplayName = "Running")
};
|
#include<bits/stdc++.h>
using namespace std;
class BinaryTreeNode{
public:
int data;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int data){
this -> data = data;
this -> left = NULL;
this -> right = NULL;
}
};
class BST{
private:
BinaryTreeNode* root;
bool hasData(int data,BinaryTreeNode* node){
if(root == NULL){
return false;
}
if(data == node -> data){
return true;
}else if(data < node -> data){
return hasData(data,node -> left);
}else{
return hasData(data,node -> right);
}
}
BinaryTreeNode* insertData(int data,BinaryTreeNode* node){
if(node == NULL){
BinaryTreeNode* newNode = new BinaryTreeNode(data);
return newNode;
}
if(data < node -> data){
node -> left = insertData(data,node -> left);
}else{
node -> right = insertData(data,node -> right);
}
return node;
}
BinaryTreeNode* deleteData(int data,BinaryTreeNode* node){
if(node == NULL){
return NULL;
}
if(data < node -> data){
node -> left = deleteData(data,node -> left);
return node;
}else if(data > node -> data){
node -> right = deleteData(data,node -> right);
return node;
}else{
if(node -> left == NULL && node -> right == NULL){
delete node;
return NULL;
}else if(node -> left == NULL){
BinaryTreeNode* temp = node -> right;
node -> right = NULL;
delete node;
return temp;
}else if(node -> right == NULL){
BinaryTreeNode* temp = node -> left;
node -> left = NULL;
delete node;
return temp;
}else{
BinaryTreeNode* minNode = node -> right;
while(minNode -> left != NULL){
minNode = minNode -> left;
}
int rightMin = minNode -> data;
node -> data = rightMin;
node -> right = deleteData(rightMin,node -> right);
return node;
}
}
}
void printTree(BinaryTreeNode* node){
if(node == NULL){
return;
}
cout << node -> data << ":";
if(node -> left != NULL){
cout << "L:" << node -> left -> data;
}
if(node -> right != NULL){
cout << "R:" << node -> right -> data;
}
cout << endl;
printTree(node -> left);
printTree(node -> right);
}
public:
BST(){
this -> root = NULL;
}
bool hasData(int data){
return hasData(data,root);
}
void insertData(int data){
root = insertData(data,root);
}
void deleteData(int data){
root = deleteData(data,root);
}
void printTree(){
printTree(root);
}
};
int main(){
BST b;
b.insertData(4);
b.insertData(2);
b.insertData(6);
b.insertData(1);
b.insertData(3);
b.insertData(5);
b.insertData(7);
b.printTree();
b.deleteData(4);
b.printTree();
return 0;
}
|
#ifndef POINTLISTFILE_H
#define POINTLISTFILE_H
#include <QObject>
#include <deque>
#include <map>
#include <vector>
#include "abstractmanager.h"
//#include "routestruct.h"
#include "computional.h"
#define MAXNODENUMBER 1000
class PointListFile : public QObject
{
Q_OBJECT
public:
PointListFile(QObject *parent =0);
~PointListFile();
bool ReadFile(QString& file);
bool ReadFile();
bool WriteFile();
bool hasLoadedRoute();
void ResetList();
void SetFileName(QString name){ FileName = name; }
///一组返回文件记录结果的函数
std::vector<Ogre::Vector3> ReturnNodeList(){ return m_MapNodeList; };
std::vector<Edge> ReturnMap(int NodeNumber){ return m_vMap[NodeNumber]; };
std::map<Ogre::String, int> ReturnmpChk(){ return m_mpChk; };
int retMapNodeNum(){ return m_nMapNodeNum; }
int retMapEdgeNum(){ return m_nMapEdgeNum; }
void SetNodeList(std::vector<Ogre::Vector3> list){ m_MapNodeList = list; }
void SetMap(std::vector<Edge> list, int num){ m_vMap[num] = list; }
void SetmpChk(std::map<Ogre::String, int> map){ m_mpChk = map; }
void SetMapNodeNum(int num){ m_nMapNodeNum = num; }
void SetMapEdgeNum(int num){ m_nMapEdgeNum = num; }
private:
QString FileName;
//std::deque < Ogre::Vector3 > LoadList;
int m_nMapNodeNum, m_nMapEdgeNum;
std::vector<Ogre::Vector3> m_MapNodeList;
std::vector<Edge> m_vMap[MAXNODENUMBER];
std::map<Ogre::String, int> m_mpChk; ///<根据名字确定点
};
#endif // POINTLISTFILE_H
|
/* https://www.codechef.com/SEPT14/problems/CHEFLR/ */
#include <bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false);
#define endl "\n"
#define gc getchar_unlocked
#define ONLINE_JUDGE freopen("iceparticle.in","r",stdin);
#define terminate exit (EXIT_FAILURE)
#define os_iterator ostream_iterator<data> screen(cout,endl)
#define output(vec) copy(vec.begin(),vec.end(),screen)
#define MAX 1000000007
typedef int data;
typedef long long ll;
typedef char character;
typedef double decimal;
inline ll input(data &x) {
register data c = gc();
ll neg = 0; x = 0;
for( ;(( c>57 || c<48 ) && c!='-');c=gc());
if(c=='-') { neg=1; c=gc(); }
for( ; c<58 && c>47 ;c = gc() ) x= (x << 1)+(x << 3)+c-48;
if(neg) return -x; else return x;
}
inline void process() {
register data t;
ll c;
string m;
input(t); for(;t--;)
{
cin >> m;
if( m[0]=='r' ) c=4;
if( m[0]=='l' ) c=2;
if( m.length()>1)
{
for( register data i=1; i<=m.length()-1; ++i)
{
if( m[i]=='r' && i%2==1 )
c=(c*2)+1;
else if( m[i]=='r' && i%2!=1 )
c=(c*2)+2;
if( m[i]=='l' && i%2==1 )
c=(c*2)-1;
else if( m[i]=='l' && i%2!=1 )
c*=2;
c= c % MAX;
if(c<0)
c+=MAX;
}
}
printf("%d\n",c);
}
}
int main () {
decimal bios_memsize;
clock_t execution;
execution=clock();
process();
bios_memsize=(clock()-execution)/(decimal)CLOCKS_PER_SEC;
return 0;
}
|
#include <iostream>
#include <string>
#include <vector>
#include <set>
using namespace std;
const int MAX_CHARS = 256;
// This function returns true if str1 and str2 are ismorphic
bool areIsomorphic(string str1, string str2)
{
int m = str1.length(), n = str2.length();
// Length of both strings must be same for one to one
// corresponance
if (m != n)
return false;
// To mark visited characters in str2
bool marked[MAX_CHARS] = { false };
// To store mapping of every character from str1 to
// that of str2. Initialize all entries of map as -1.
int map[MAX_CHARS];
memset(map, -1, sizeof(map));
// Process all characters one by on
for (int i = 0; i < n; i++)
{
// If current character of str1 is seen first
// time in it.
if (map[str1[i]] == -1)
{
// If current character of str2 is already
// seen, one to one mapping not possible
if (marked[str2[i]] == true)
return false;
// Mark current character of str2 as visited
marked[str2[i]] = true;
// Store mapping of current characters
map[str1[i]] = str2[i];
}
// If this is not first appearance of current
// character in str1, then check if previous
// appearance mapped to same character of str2
else if (map[str1[i]] != str2[i])
return false;
}
return true;
}
int getIsomorphicCount(vector<string> &words)
{
set<string> isoWords;
for (int i = 0; i < words.size(); ++i) { //sorting algorithm
string first = words[i];
for (int j = i + 1; j < words.size(); ++j) {
string second = words[j];
if (first.length() == second.length()) {
if (areIsomorphic(first, second)) {
isoWords.insert(first);
isoWords.insert(second);
}
}
}
}
return isoWords.size();
}
void printVect(vector<string> &words)
{
cout << "words in vector = ";
for (int i = 0; i < words.size(); ++i)
cout << words[i] << '\t';
cout << endl << endl;
}
// Driver program
int main()
{
vector<string> words = { "aa", "bb" }; //, "abc", "bbc", "ijk", "opq"};
//vector<string> words2 = { "aad", "bbd", "abcd", "bbcm", "lkijk", "o" };
//vector<string> words3 = {"abcdefgh ijkl mn", "opqrstuv wxyx aa"};
printVect(words);
cout << "Isomorphic count = " << getIsomorphicCount(words) << endl << endl;
//printVect(words2);
//cout << "Isomorphic count = " << getIsomorphicCount(words2) << endl << endl;
//cout << "Isomorphic count = " << getIsomorphicCount(words3) << endl << endl;
return 0;
}
|
#ifndef DERIVATIVE_H // To make sure you don't declare the function more than once by including the header multiple times.
#define DERIVATIVE_H
#include "mujoco.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#ifdef __cplusplus
extern "C" void worker(const mjModel* m, const mjData* dmain, mjData* d, int id);
extern "C" double relnorm(mjtNum* residual, mjtNum* base, int n);
extern "C" void checkderiv(const mjModel* m, mjData* d, mjtNum error[7]);
extern "C" void cmptJac(mjtNum* ptr, mjtNum* accu_ptr, mjModel* m, mjData* dold);
#else
void worker(const mjModel* m, const mjData* dmain, mjData* d, int id);
double relnorm(mjtNum* residual, mjtNum* base, int n);
void checkderiv(const mjModel* m, mjData* d, mjtNum error[7]);
void cmptJac(mjtNum* ptr, mjtNum* accu_ptr, mjModel* m, mjData* dold);
#endif
#endif
|
#pragma once
#include "Keng/Graphics/FwdDecl.h"
#include "Keng/ResourceSystem/IResource.h"
namespace keng::graphics
{
class IEffect : public resource::IResource
{
public:
virtual void AssignToPipeline() = 0;
virtual void InitDefaultInputLayout() = 0;
virtual ~IEffect() = default;
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include <core/pch.h>
#ifdef GEOLOCATION_SUPPORT
#include "modules/geolocation/src/geo_google2011_network_api.h"
#include "modules/ecmascript/json_parser.h"
#include "modules/formats/uri_escape.h"
#include "modules/geolocation/src/geo_google2011_network_api_response_parser.h"
#include "modules/geolocation/src/geo_tools.h"
#include "modules/prefs/prefsmanager/collections/pc_geoloc.h"
OP_STATUS
OpGeolocationGoogle2011NetworkApi::MakeRequestUrl(URL &request_url, GeoWifiData *wifi_data, GeoRadioData *radio_data, GeoGpsData *gps_data)
{
OpString request_url_string;
OpStringC provider_url(g_pcgeolocation->GetStringPref(PrefsCollectionGeolocation::LocationProviderUrl));
if (provider_url.IsEmpty())
RETURN_IF_ERROR(request_url_string.Set(UNI_L("https://maps.googleapis.com/maps/api/browserlocation/json")));
else
RETURN_IF_ERROR(request_url_string.Set(provider_url));
RETURN_IF_ERROR(AppendQueryString(request_url_string, wifi_data, radio_data, gps_data, GetAccessToken()));
request_url = g_url_api->GetURL(request_url_string);
if (request_url.IsEmpty())
return OpStatus::ERR;
RETURN_IF_ERROR(request_url.SetAttribute(URL::KDisableProcessCookies, TRUE));
return OpStatus::OK;
}
OP_STATUS
OpGeolocationGoogle2011NetworkApi::ProcessResponse(const uni_char *response_buffer, unsigned long response_length, OpGeolocation::Position &pos)
{
Google2011NetworkApiResponseParser parse_data;
JSONParser parser(&parse_data);
OP_STATUS parse_status = parser.Parse(response_buffer, response_length);
#ifdef OPERA_CONSOLE
if (OpStatus::IsError(parse_status) && !OpStatus::IsMemoryError(parse_status))
GeoTools::PostConsoleMessage(OpConsoleEngine::Error, UNI_L("Location provider responded with invalid data."), GeoTools::CustomProviderNote());
#endif // OPERA_CONSOLE
RETURN_IF_ERROR(parse_status);
if (parse_data.GetStatus() != Google2011NetworkApiResponseParser::OK)
{
#ifdef OPERA_CONSOLE
GeoTools::PostConsoleMessage(OpConsoleEngine::Error, UNI_L("Location provider responded with an error."), GeoTools::CustomProviderNote());
#endif // OPERA_CONSOLE
return OpStatus::ERR;
}
if (op_isnan(parse_data.GetAccuracy()) || parse_data.GetAccuracy() < 0 || op_isnan(parse_data.GetLongitude()) || op_isnan(parse_data.GetLatitude()))
{
#ifdef OPERA_CONSOLE
GeoTools::PostConsoleMessage(OpConsoleEngine::Error, UNI_L("Location provider responded with insufficient data."), GeoTools::CustomProviderNote());
#endif // OPERA_CONSOLE
return OpStatus::ERR;
}
pos.timestamp = g_op_time_info->GetTimeUTC();
pos.capabilities = OpGeolocation::Position::STANDARD;
pos.latitude = parse_data.GetLatitude();
pos.longitude = parse_data.GetLongitude();
pos.horizontal_accuracy = parse_data.GetAccuracy();
if (parse_data.GetAccessToken() != NULL)
{
TRAPD(error, g_pcgeolocation->WriteStringL(g_pcgeolocation->Google2011LocationProviderAccessToken, parse_data.GetAccessToken()));
// If we can't store the access token, we still can use the result.
// OTOH, in practice we're most likely to get OOM in which case something else will fail anyway.
if (OpStatus::IsMemoryError(error))
g_memory_manager->RaiseCondition(error);
}
return OpStatus::OK;
}
static OP_STATUS
AppendEscapedValue(OpString &target, const uni_char *value)
{
OpString escaped;
RETURN_IF_ERROR(escaped.Set(value));
RETURN_IF_ERROR(escaped.ReplaceAll(UNI_L("\\"), UNI_L("\\\\")));
RETURN_IF_ERROR(escaped.ReplaceAll(UNI_L("|"), UNI_L("\\|")));
return target.Append(escaped);
}
static int
RadioTypeCode(OpRadioData::RadioType radio_type)
{
switch(radio_type)
{
case OpRadioData::RADIO_TYPE_GSM: return 1;
case OpRadioData::RADIO_TYPE_CDMA: return 2;
case OpRadioData::RADIO_TYPE_WCDMA: return 3;
default:
OP_ASSERT(!"Unexpected radio network type.");
/* fallthrough */
case OpRadioData::RADIO_TYPE_UNKNOWN: return 0;
}
}
/** Compute how much space should be left in the request URI
* for radio data.
*
* The computed value is the upper bound for 5 cell tower
* entries.
*/
inline static int
ComputeRadioDataReserve(GeoRadioData *radio_data)
{
const int MAX_DEVICE_SEGMENT_LENGTH = 54;
const int MAX_CELL_SEGMENT_LENGTH = 82;
return MAX_DEVICE_SEGMENT_LENGTH + MAX_CELL_SEGMENT_LENGTH * MIN(radio_data->m_data.cell_towers.GetCount(), 5);
}
/* static */ OP_STATUS
OpGeolocationGoogle2011NetworkApi::AppendQueryString(OpString &url_string, GeoWifiData *wifi_data, GeoRadioData *radio_data, GeoGpsData *gps_data, const uni_char *access_token)
{
const int MAX_URI_LENGTH = 2048; // As per Google's spec.
RETURN_IF_ERROR(url_string.AppendFormat(UNI_L("?browser=opera&sensor=true")));
if (access_token)
{
RETURN_IF_ERROR(url_string.Append(UNI_L("&token=")));
RETURN_IF_ERROR(UriEscape::AppendEscaped(url_string, access_token, UriEscape::FormUnsafe));
}
int url_string_length = url_string.Length();
if (wifi_data)
{
int max_length;
if (radio_data)
max_length = MAX_URI_LENGTH - ComputeRadioDataReserve(radio_data);
else
max_length = MAX_URI_LENGTH;
// Precondition: wifi_data->m_data.wifi_towers are sorted by signal strength, strongest first.
for (UINT32 i = 0; i < wifi_data->m_data.wifi_towers.GetCount(); ++i)
{
OpWifiData::AccessPointData *ap = wifi_data->m_data.wifi_towers.Get(i);
OpString wifi_string;
// Mandatory values
RETURN_IF_ERROR(wifi_string.AppendFormat(UNI_L("mac:%s|ss:%d|ssid:"), ap->mac_address.CStr(), ap->signal_strength));
RETURN_IF_ERROR(AppendEscapedValue(wifi_string, ap->ssid));
// Optional values
if (wifi_data->Timestamp() > 0)
RETURN_IF_ERROR(wifi_string.AppendFormat(UNI_L("|age:%u"), static_cast<unsigned>(g_op_time_info->GetTimeUTC() - wifi_data->Timestamp())));
if (ap->channel > 0)
RETURN_IF_ERROR(wifi_string.AppendFormat(UNI_L("|chan:%u"), ap->channel));
if (ap->snr > 0)
RETURN_IF_ERROR(wifi_string.AppendFormat(UNI_L("|snr:%d"), ap->snr));
int escaped_length = UriEscape::GetEscapedLength(wifi_string.CStr(), wifi_string.Length(), UriEscape::FormUnsafe);
if (escaped_length + url_string_length + 6 > max_length)
break;
RETURN_IF_ERROR(url_string.Append("&wifi="));
RETURN_IF_ERROR(UriEscape::AppendEscaped(url_string, wifi_string, UriEscape::FormUnsafe));
url_string_length += 6 + escaped_length;
}
}
if (radio_data)
{
OpString device_string;
RETURN_IF_ERROR(device_string.AppendFormat(UNI_L("mcc:%d|mnc:%d|rt:%d"),
radio_data->m_data.home_mobile_country_code,
radio_data->m_data.home_mobile_network_code,
RadioTypeCode(radio_data->m_data.radio_type)));
RETURN_IF_ERROR(url_string.Append("&device="));
RETURN_IF_ERROR(UriEscape::AppendEscaped(url_string, device_string, UriEscape::FormUnsafe));
url_string_length = url_string.Length();
// Precondition: radio_data->m_data.cell_towers are sorted by signal strength, strongest first.
for (UINT32 i = 0; i < radio_data->m_data.cell_towers.GetCount(); ++i)
{
OpRadioData::CellData *cell = radio_data->m_data.cell_towers.Get(i);
OpString cell_string;
RETURN_IF_ERROR(cell_string.AppendFormat(UNI_L("id:%d|lac:%u|mcc:%d|mnc:%d|ss:%d|ta:%d"),
cell->cell_id,
cell->location_area_code,
cell->mobile_country_code,
cell->mobile_network_code,
cell->signal_strength,
cell->timing_advance));
int escaped_length = UriEscape::GetEscapedLength(cell_string.CStr(), cell_string.Length(), UriEscape::FormUnsafe);
if (url_string_length + escaped_length + 6 > MAX_URI_LENGTH)
break;
RETURN_IF_ERROR(url_string.Append("&cell="));
RETURN_IF_ERROR(UriEscape::AppendEscaped(url_string, cell_string, UriEscape::FormUnsafe));
url_string_length += 6 + escaped_length;
}
}
if (gps_data)
{
RETURN_IF_ERROR(url_string.AppendFormat(UNI_L("&location=lat%%3A%f%%7Clng%%3A%f"), gps_data->m_data.latitude, gps_data->m_data.longitude));
if (url_string.Length() > MAX_URI_LENGTH) // Too long? Revert
url_string.Delete(url_string_length);
}
return OpStatus::OK;
}
const uni_char *
OpGeolocationGoogle2011NetworkApi::GetAccessToken()
{
OpStringC access_token = g_pcgeolocation->GetStringPref(PrefsCollectionGeolocation::Google2011LocationProviderAccessToken);
return access_token.IsEmpty() ? NULL : access_token.CStr();
}
#endif // GEOLOCATION_SUPPORT
|
class Category_492 {
class UralRefuel_TK_EP1_DZ {
type = "trade_any_vehicle";
buy[] = {7,"ItemGoldBar10oz"};
sell[] = {3,"ItemGoldBar10oz"};
};
class V3S_Refuel_TK_GUE_EP1_DZ {
type = "trade_any_vehicle";
buy[] = {7,"ItemGoldBar10oz"};
sell[] = {3,"ItemGoldBar10oz"};
};
class KamazRefuel_DZ {
type = "trade_any_vehicle";
buy[] = {7,"ItemGoldBar10oz"};
sell[] = {3,"ItemGoldBar10oz"};
};
class MtvrRefuel_DES_EP1_DZ {
type = "trade_any_vehicle";
buy[] = {7,"ItemGoldBar10oz"};
sell[] = {3,"ItemGoldBar10oz"};
};
class MtvrRefuel_DZ {
type = "trade_any_vehicle";
buy[] = {7,"ItemGoldBar10oz"};
sell[] = {3,"ItemGoldBar10oz"};
};
};
class Category_595 {
duplicate = 492;
};
|
#include <iostream>
#include <chrono>
#include <functional>
#include <atomic>
#include <iomanip>
#include <memory_resource>
#include "threadpool.hpp"
using namespace std::chrono;
namespace mjs {
using namespace vks;
class MinimalJobSystem {
ThreadPool m_pool;
uint32_t m_thread_count = 0;
public:
MinimalJobSystem(uint32_t& thread_count) {
m_pool.setThreadCount(thread_count);
m_thread_count = thread_count;
}
void schedule(std::function<void()>&& job) {
m_pool.threads[rand() % m_thread_count]->addJob(std::move(job));
}
void schedule(std::pmr::vector<std::function<void()>>&& jobs) {
for (int i = 0; i < jobs.size(); i++)
m_pool.threads[i % m_thread_count]->addJob(std::move(jobs[i])); // Spread jobs over all threads evenly
/*for (auto& job : jobs) // Alternatively schedule each job to a random thread
schedule(std::move(job));
*/
}
void wait() {
m_pool.wait();
}
uint32_t get_thread_count() {
return m_thread_count;
}
};
void func_perf(int micro, int i = 1) {
volatile unsigned int counter = 1;
volatile double root = 0.0;
auto start = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(high_resolution_clock::now() - start);
while (duration.count() < micro) {
for (int i = 0; i < 10; ++i) {
counter += counter;
root = sqrt((float)counter);
}
duration = duration_cast<microseconds>(high_resolution_clock::now() - start);
}
//std::cout << duration.count() << std::endl;
}
template<bool WITHALLOCATE = false, typename FT = std::function<void(void)>>
std::tuple<double, double> performance_function(MinimalJobSystem& mjs, bool print = true, bool wrtfunc = true, int num = 1000, int micro = 1, unsigned int loops = 20, std::pmr::memory_resource* mr = std::pmr::new_delete_resource()) {
double duration0_sum = 0;
double duration2_sum = 0;
for (uint32_t i = 0; i < loops; i++) { // run multiple times to even out fluctuations
// no JS
auto start0 = high_resolution_clock::now();
for (int i = 0; i < num; ++i) func_perf(micro);
auto duration0 = duration_cast<microseconds>(high_resolution_clock::now() - start0);
duration0_sum += duration0.count();
// allocation
std::pmr::vector<FT> perfv{ mr };
if constexpr (!WITHALLOCATE) {
perfv.resize(num, std::function<void(void)>{[&]() { func_perf(micro); }});
}
// Set total number of jobs to be executed
//g_job_count = num;
// multithreaded
//g_start = high_resolution_clock::now(); // use timers in threadpool.hpp
auto start2 = high_resolution_clock::now();
// time allocation as well
if constexpr (WITHALLOCATE) {
perfv.resize(num, std::function<void(void)>{ [&]() { func_perf(micro); }});
}
mjs.schedule(std::move(perfv)); // start jobs in mjs
mjs.wait(); // sync
//g_duration = duration_cast<microseconds>(high_resolution_clock::now() - g_start);
auto duration2 = duration_cast<microseconds>(high_resolution_clock::now() - start2);
duration2_sum += duration2.count();
}
// calculate + output
double speedup0 = duration0_sum / duration2_sum;
double efficiency0 = speedup0 / mjs.get_thread_count();
if (print /* && efficiency0 > 0.85 */) {
std::cout << "Wrt function calls: Work/job " << std::right << std::setw(3) << micro << " us Speedup " << std::left << std::setw(8) << speedup0 << " Efficiency " << std::setw(8) << efficiency0 << std::endl;
}
return std::make_tuple(speedup0, efficiency0);
}
template<bool WITHALLOCATE = false, typename FT>
void performance_driver(MinimalJobSystem& mjs, std::string text, std::pmr::memory_resource* mr = std::pmr::new_delete_resource(), int runtime = 400000) {
int num = runtime;
const int st = 0;
const int mt = 100;
const int dt1 = 1;
const int dt2 = 1;
const int dt3 = 1;
const int dt4 = 10;
int mdt = dt1;
bool wrt_function = true; //speedup wrt to sequential function calls w/o JS
std::cout << "\nPerformance for " << text << " on " << mjs.get_thread_count() << " threads\n\n";
performance_function<WITHALLOCATE, FT>(mjs, false, wrt_function, (int)(num), 0); //heat up, allocate enough jobs
for (int us = st; us <= mt; us += mdt) {
int loops = (us == 0 ? num : (runtime / us));
auto [speedup, eff] = performance_function<WITHALLOCATE, FT>(mjs, true, wrt_function, loops, us);
if (/* eff > 0.95 && */ us >= 10) return;
if (us >= 15) mdt = dt2;
if (us >= 20) mdt = dt3;
if (us >= 50) mdt = dt4;
}
}
void test(uint32_t num_threads) {
MinimalJobSystem mjs(num_threads);
std::cout << "\n\nPerformance: min work (in microsconds) per job so that efficiency is >0.85 or >0.95\n";
performance_driver<false, std::function<void(void)>>(mjs, "std::function calls (w / o allocate)");
}
}
|
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <iostream>
#define BUFSZ PIPE_BUF
int main(int argc, char *argv[]) {
FILE* fp;
int count;
char buf[BUFSZ];
char command[150];
sprintf(command, "ps -ef | grep postgres | grep 27575 | grep con | grep -v grep | wc -l");
if ((fp = popen(command,"r")) == NULL) {
std::cout << "popen error" << std::endl;
}
if ((fgets(buf,BUFSZ,fp)) != NULL) {
count = atoi(buf);
if (count == 0)
std::cout << "postgres 27575 not found!" << std::endl;
else if (count == 1)
std::cout << "postgres 27575 exist!" << std::endl;
else
std::cout << "ps result:" << count << std::endl;
}
pclose(fp);
}
|
#include "Includes.h"
#include <iostream>
using namespace std;
int main() {
printf("Selecciona un problema de UVa por su ID\n");
int id;
scanf("%d", &id);
switch(id) {
case 11571:
printHello();
break;
case 11057:
uva11057Main();
break;
case 10077:
uva10077Main();
break;
case 957:
uva957Main();
break;
case 108:
uva108Main();
break;
case 10656:
uva10656Main();
break;
case 11264:
uva11264Main();
break;
case 11389:
uva11389Main();
break;
case 11827:
uva11827Main();
break;
case 412:
uva412Main();
break;
case 11902:
uva11902Main();
break;
case 543:
uva543Main();
break;
case 499:
uva499Main();
break;
case 895:
uva895Main();
break;
case 10252:
uva10252Main();
break;
default:
break;
}
return 0;
}
|
#include "aDDict.h"
#define fullscr false
//inner truth
char *s2s = new char[256];
/* sprintf(ss,"%d",texgenmenu);
MessageBox( 0, ss, "HelloWorld", MB_OK );*/
bool aCid=false;
int music_len,music_pos;
unsigned int memopen(char *name) { return 1; }
void memclose(unsigned int handle) {}
int memread(void *buffer, int size, unsigned int handle)
{
if (music_pos + size >= music_len) size = music_len - music_pos;
memcpy(buffer, (char *)music_data+music_pos, size);
music_pos += size;
return size;
}
void memseek(unsigned int handle, int pos, signed char mode)
{
if (mode == SEEK_SET) music_pos = pos;
else if (mode == SEEK_CUR) music_pos += pos;
else if (mode == SEEK_END) music_pos = music_len + pos;
if (music_pos > music_len) music_pos = music_len;
}
int memtell(unsigned int handle) { return music_pos; }
char lastfilename[256];
GLuint cubetex,mainmenutex,texbutton1,texbutton2,texbutton3,texts1;
char musfilename[40];
char *music_data;
bool musicloaded=false;
FMUSIC_MODULE *mod;
bool fulls = fullscr;
scene *scenelist=newscene();
scene *lastscene=scenelist;
char tooltip[256];
char defaulttooltip[256];
material *materiallist=NULL,*lastmaterial=NULL;
GLuint texlayers[4],prelayers[4];
GLuint pretextures[6][8];
GLuint background;
int mainmenu = 0;
int texgenmenu=0;
int texsubmenu[6];
texturecommand texdata[6][8];
int x,y,z = 0;
bool waitleftbutton=false;
bool waitrightbutton=false;
texture generatedtexture,buffertexture;
bool randomed = false;
tfilelist *atglist=NULL;
tfilelist *scnlist=NULL,*prjlist=NULL,*xmlist=NULL,*synclist=NULL;
tTexture *actualtexture=NULL,*texturelist=new tTexture[1],*lasttexture;
int atgbarpos=0;
int atgselected=0;
int selbarpos=0;
int selselected=0;
int scnbarpos=0;
int scnselected=0;
tfilelist *pf=NULL;
char *st=new char[256];
FILE *f;
byte b;
byte k;
texturecommand cmd;
int commandselected=0;
int commandpos=0;
char *commandnames[256];
scene *actualscene=scenelist;
int modellermenu=0;
bool xformmenu=true;
bool createmenu=true;
int transformation=0;
bool centertransform=false;
bool transform=false;
object *o;
int selectedtexture=0, texturestart=0;
unsigned int mattexture;
int selectstart=0;
int lofttrack=0,loftmesh=0;
int loftstart=0,loftcounter=0,tracknumber=0,trackstart=0,trackcounter=0;
int modellsubmenu[8];
int matstart=0,matselected=0;
byte spherex=12,spherey=12;
byte gridx=10,gridy=10;
byte tubex=12,tubey=12;
bool tubetop=1;
byte conex=12;
bool conetop=1;
byte arcx=12;
int arcy=360;
byte linex=10;
byte *backraw;
int objnumber;
bool backdraw=false;
char *cursorstring = new char[256];
bool scntexturesave=true, scncamerasave=false, scnselectionsave=true, scnlightsave=false, scnobjectsave=true, scnenvironmentsave=false;
void init()
{
memset(lastfilename,0,256);
memset(musfilename,0,40);
initGUI();
sprintf(scenelist->name,"Default");
memset(tooltip,0,256);
memset(defaulttooltip,0,256);
sprintf(defaulttooltip,"a.D.D.i.c.t. (c) BoyC 2002");
actualtexture=texturelist;
lasttexture=texturelist;
memset(texturelist,0,sizeof(tTexture));
texturelist->next=NULL;
sprintf(texturelist->name,"Default");
memset(cursorstring,0,256);
for (x=0;x<=7;x++) modellsubmenu[x]=0;
init3dengine();
InitModellerGUI();
BuildFont();
BuildFont2();
BuildFontSmall();
inittextureengine();
generatedtexture.init();
buffertexture.init();
memset(pretextures,0,sizeof(pretextures));
memset(texdata,0,sizeof(texdata));
memset(texsubmenu,0,sizeof(texsubmenu));
texdata[0][3].command[3]=4;
texdata[0][5].command[3]=14;
texdata[0][5].command[4]=100;
texdata[0][6].command[3]=30;
texdata[1][1].command[2]=128;
texdata[2][4].command[3]=128;
texdata[3][2].command[2]=128;
texdata[3][4].command[4]=255;
texdata[3][6].c.param1=255;
texdata[3][6].c.param3=255;
texdata[3][6].c.param5=255;
glGenTextures(1,&mattexture);
glBindTexture(GL_TEXTURE_2D,mattexture);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,4,256,256,0,GL_RGBA,GL_UNSIGNED_BYTE,generatedtexture.layers[0]);
for (x=0;x<4;x++)
{
glGenTextures(1,&(prelayers[x]));
glBindTexture(GL_TEXTURE_2D,prelayers[x]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,4,256,256,0,GL_RGBA,GL_UNSIGNED_BYTE,generatedtexture.layers[x]);
}
for (x=0;x<4;x++)
{
glGenTextures(1,&(texlayers[x]));
glBindTexture(GL_TEXTURE_2D,texlayers[x]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,4,256,256,0,GL_RGBA,GL_UNSIGNED_BYTE,generatedtexture.layers[x]);
}
for (x=0;x<4;x++)
{
glGenTextures(1,&alayers[x]);
glBindTexture(GL_TEXTURE_2D,alayers[x]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,4,256,256,0,GL_RGBA,GL_UNSIGNED_BYTE,generatedtexture.layers[x]);
}
glGenTextures(1,&background);
glBindTexture(GL_TEXTURE_2D, background);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
commandnames[DD_fractal] ="Fractal ";
commandnames[DD_plasma] ="Plasma ";
commandnames[DD_cells] ="Cells ";
commandnames[DD_envmap] ="Envmap ";
commandnames[DD_subplasm] ="Subplasma ";
commandnames[DD_clear] ="Clear ";
commandnames[DD_text] ="Text ";
commandnames[DD_sindist] ="SinDist ";
commandnames[DD_offset] ="Offset ";
commandnames[DD_twirl] ="Twirl ";
commandnames[DD_blur] ="Blur ";
commandnames[DD_map] ="MapDist ";
commandnames[DD_dirblur] ="DirBlur ";
commandnames[DD_xchng] ="Xchange ";
commandnames[DD_copy] ="Copy ";
commandnames[DD_mix] ="Mix ";
commandnames[DD_mul] ="Mul ";
commandnames[DD_add] ="Add ";
commandnames[DD_max] ="Max ";
commandnames[DD_contrast] ="Contrast ";
commandnames[DD_invert] ="Invert ";
commandnames[DD_shade] ="Shade ";
commandnames[DD_bright] ="Brighten ";
commandnames[DD_sincol] ="Color Sine ";
commandnames[DD_scale] ="Scale ";
commandnames[DD_hsv] ="HSV ";
commandnames[DD_colorize] ="Colorize ";
commandnames[DD_mixmap] ="MixMap ";
commandnames[DD_emboss] ="Emboss ";
commandnames[DD_stored] ="Stored ";
initkeyframergui();
FSOUND_File_SetCallbacks(memopen, memclose, memread, memseek, memtell);
FSOUND_Init(44100,32);
}
void menu(byte mode)
{
if (button(12,1,12+107,1+23,mainmenutex,0,0,107.0/512.0,23.0/128.0,mainmenu==0,mode) == DDgui_LeftClick) mainmenu=0;
if (button(119,1,183,1+23,mainmenutex,0,23.0/128.0,63.0/512.0,46.0/128.0,mainmenu==1,mode)== DDgui_LeftClick) mainmenu=1;
if (button(183,1,261,1+23,mainmenutex,0,46.0/128.0,78.0/512.0,69.0/128.0,mainmenu==2,mode) == DDgui_LeftClick)
{
if (materiallist!=NULL)
{
material *pt=materiallist;
for (x=1;x<=matselected;x++) pt=pt->next;
mattexture=pt->handle;
}
mainmenu=2;
}
if (button(261,1,345,1+23,mainmenutex,0,69.0/128.0,84.0/512.0,92.0/128.0,mainmenu==3,mode) == DDgui_LeftClick) mainmenu=3;
if (button(345,1,396,1+23,mainmenutex,0,92.0/128.0,51.0/512.0,115.0/128.0,mainmenu==4,mode) == DDgui_LeftClick) { mainmenu=4; prjlist=findfile(projectmask);}
switch (mainmenu) {
case 0 : {introeditor(mode); break;}
case 1 : {TextureGeneratorGUI(mode); break;}
case 2 : {ModellerGUI(mode); break;}
case 3 : {keyframergui(mode); break;}
case 4 : {filemenu(mode); break;}
}
}
void mainloop()
{
while (!done)
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else if (keys[VK_ESCAPE]) done=true;
else
{
memcpy(tooltip,defaulttooltip,256);
glClear(0x4100);
switchto2d();
/*glPushAttrib(GL_ALL_ATTRIB_BITS);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glColor4d( 40.0/255.0,
75.0/255.0,
128.0/255.0,1.0);
glVertex2i(0,0);
glVertex2i(800,0);
glColor4f(backgroundcol);
glVertex2i(800,600);
glVertex2i(0,600);
glEnd();
glPopAttrib();*/
glBindTexture(GL_TEXTURE_2D,cubetex);
/*glEnable(GL_TEXTURE_2D); //145*32 addict logo
glColor4f(1,1,1,1);
glBegin(GL_QUADS);
glTexCoord2d(0,(255.0-31.0)/256.0);
glVertex2i(800-144,0);
glTexCoord2d(144.0/256.0,(255.0-31.0)/256.0);
glVertex2i(800,0);
glTexCoord2d(144.0/256.0,1.0);
glVertex2i(800,31);
glTexCoord2d(0,1.0);
glVertex2i(800-144,31);
glEnd();
glDisable(GL_TEXTURE_2D);*/
menu(DD_Check);
if (keys[46] && (mainmenu==2)) { delete_selected(); keys[46]=false; }
if (keys[65] && (mainmenu==2)) { { o=actualscene->objects; while (o!=NULL) { if (!o->effect) o->selected=true; o=o->next; } } keys[65]=false; }
if (keys[78] && (mainmenu==2)) { { o=actualscene->objects; while (o!=NULL) { o->selected=false; o=o->next; } } keys[78]=false; }
if (keys[73] && (mainmenu==2)) { { o=actualscene->objects; while (o!=NULL) { if (!o->effect) o->selected=!o->selected; o=o->next; } } keys[73]=false; }
if (keys[77] && (mainmenu==2)) { for (int x=0; x<4; x++) modellviews[x].transformation=1; keys[77]=false; }
if (keys[82] && (mainmenu==2)) { for (int x=0; x<4; x++) modellviews[x].transformation=2; keys[82]=false; }
if (keys[83] && (mainmenu==2)) { for (int x=0; x<4; x++) modellviews[x].transformation=3; keys[83]=false; }
if (keys[79] && (mainmenu==2)) { for (int x=0; x<4; x++) modellviews[x].centertransform=!modellviews[x].centertransform; keys[79]=false; }
//if (keys[79] && (mainmenu==2)) { sprintf(s2s,"eye: %.3f %.3f %.3f\n dest: %.3f %.3f %.3f",modellviews[3].cam2.eye.b.x,modellviews[3].cam2.eye.b.y,modellviews[3].cam2.eye.b.z,modellviews[3].cam2.target.b.x,modellviews[3].cam2.target.b.y,modellviews[3].cam2.target.b.z); MessageBox( 0, s2s, "HelloWorld", MB_OK ); keys[79]=false; }
menu(DD_Draw);
if ((strlen(cursorstring)!=0)) //&& (leftbutton || rightbutton))
{
glColor4f(1,1,1,1);
if (leftbutton)
{
line(lx-5,ly,lx+5,ly);
line(lx,ly-5,lx,ly+5);
}
glDisable(GL_DEPTH_TEST);
glRasterPos2i(mx+15,my+15);
glPrint(cursorstring,base2);
glEnable(GL_DEPTH_TEST);
memset(cursorstring,0,256);
}
glColor4f(buttontextlit);
/*glRasterPos2i(495,14);
glPrint(tooltip,base);*/
glColor4f(1,1,1,1);
SwapBuffers(hDC);
menu(DD_AfterCheck);
if (waitleftbutton) {waitforleftbuttonrelease(); waitleftbutton=false;}
if (waitrightbutton) {waitforrightbuttonrelease(); waitrightbutton=false;}
if (keys[VK_ESCAPE]) {done=false; keys[VK_ESCAPE]=false;}
if (leftbutton || rightbutton || middlebutton) SetCapture(hWnd); else ReleaseCapture();
wheel=0;
Sleep(10);
}
}
}
void checkini()
{
FILE *inifile=fopen("addict.ini","rt");
if (inifile!=NULL)
{
int a;
if (fscanf(inifile,"%d",&a)!=0)
{
if (a) fulls=true; else fulls=false;
}
if (fscanf(inifile,"%d",&a)==1)
{
if (a) aCid=true; else aCid=false;
}
fclose(inifile);
}
/*FILE *a,*b,*c;
a=fopen("fmodsux\\dll.txt","rt");
b=fopen("fmodsux\\mini.txt","rt");
c=fopen("fmodsux\\dif.txt","w+t");
for (int x=0; x<106; x++)
{
int i,j;
fscanf(a,"%d",&i); //dll
fscanf(b,"%d",&j); //mini
j=j-19;
fprintf(c,"Dif: %d Mult: %.10f\n",i-j,(float)i/(float)j);
}*/
}
INT WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow )
{
checkini();
DD_CreateWindow("a.D.D.i.c.t. - advanced Digital Dynamite intro creation tool v0.9 (c) BoyC 2002-2003", 800, 600, 32, fulls, LoadIcon(hInstance, MAKEINTRESOURCE(101)));
glClearColor(backgroundcol);
glClear(0x4100);
SwapBuffers(hDC);
initintroeditor();
init();
FILE *inifile=fopen("back.raw","rb");
if (inifile!=NULL)
{
backraw=new byte[196608];
fread(backraw,256*256,3,inifile);
backdraw=true;
glGenTextures(1,&backrawtex);
glBindTexture(GL_TEXTURE_2D,backrawtex);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,3,256,256,0,GL_RGB,GL_UNSIGNED_BYTE,backraw);
fclose(inifile);
}
//glClearColor(50.0f/255.0f,65.0f/255.0f,89.0f/255.0f,0);
mainloop();
KillGLWindow();
return 0;
}
|
// Created on: 1992-02-03
// Created by: Christian CAILLET
// Copyright (c) 1992-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 _Interface_NodeOfReaderLib_HeaderFile
#define _Interface_NodeOfReaderLib_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Transient.hxx>
class Interface_GlobalNodeOfReaderLib;
class Standard_Transient;
class Interface_ReaderModule;
class Interface_Protocol;
class Interface_ReaderLib;
class Interface_NodeOfReaderLib;
DEFINE_STANDARD_HANDLE(Interface_NodeOfReaderLib, Standard_Transient)
class Interface_NodeOfReaderLib : public Standard_Transient
{
public:
//! Creates an empty Node, with no Next
Standard_EXPORT Interface_NodeOfReaderLib();
//! Adds a couple (Module,Protocol), that is, stores it into
//! itself if not yet done, else creates a Next Node to do it
Standard_EXPORT void AddNode (const Handle(Interface_GlobalNodeOfReaderLib)& anode);
//! Returns the Module designated by a precise Node
Standard_EXPORT const Handle(Interface_ReaderModule)& Module() const;
//! Returns the Protocol designated by a precise Node
Standard_EXPORT const Handle(Interface_Protocol)& Protocol() const;
//! Returns the Next Node. If none was defined, returned value
//! is a Null Handle
Standard_EXPORT const Handle(Interface_NodeOfReaderLib)& Next() const;
DEFINE_STANDARD_RTTI_INLINE(Interface_NodeOfReaderLib,Standard_Transient)
protected:
private:
Handle(Interface_GlobalNodeOfReaderLib) thenode;
Handle(Interface_NodeOfReaderLib) thenext;
};
#endif // _Interface_NodeOfReaderLib_HeaderFile
|
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp> // TODO: opencv3?
#include <cv_bridge/cv_bridge.h>
#include <ctime>
#include <cstdlib>
#include <string>
#include <dynamic_reconfigure/server.h>
#include <ltu_actor_inputprocess_camadjust/CamPubConfig.h>
#include <vector>
/**
* Image publisher for cv images
* Publishes images at ~30fps
*/
ltu_actor_inputprocess_camadjust::CamPubConfig config;
image_transport::Publisher *pub = 0;
image_transport::Subscriber *img_input = 0;
cv::Ptr<cv::CLAHE> clahe;
dynamic_reconfigure::Server<ltu_actor_inputprocess_camadjust::CamPubConfig> *server = 0;
std::string cam_topic;
bool enabled_;
void dynConfigCB(ltu_actor_inputprocess_camadjust::CamPubConfig &config_, uint32_t level)
{
config = config_;
}
void inputCB(const sensor_msgs::ImageConstPtr &input)
{
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(input, sensor_msgs::image_encodings::BGR8);
}
catch (cv_bridge::Exception &e)
{
ROS_ERROR("cv_bridge exceptions: %s", e.what());
return;
}
sensor_msgs::ImagePtr msg;
cv::Mat frame = cv_ptr->image;
if(config.resize < 0.99)
cv::resize(frame, frame, cv::Size(), config.resize, config.resize, cv::INTER_AREA);
if(config.enable_less_color)
{
cv::cvtColor(frame, frame, cv::COLOR_BGR2HSV);
std::vector<cv::Mat> channels(3);
cv::split(frame, channels);
channels[2] -= config.less_color_mux * channels[1];
cv::merge(channels, frame);
cv::cvtColor(frame, frame, cv::COLOR_HSV2BGR);
}
if(config.enable_clahe)
{
std::vector<cv::Mat> channels(3);
cv::split(frame, channels);
clahe->setClipLimit(config.clahe_clip);
clahe->apply(channels[0], channels[0]);
clahe->apply(channels[1], channels[1]);
clahe->apply(channels[2], channels[2]);
cv::merge(channels, frame);
}
if(config.enable_color_correct)
{
frame.convertTo(frame, CV_16UC3);
std::vector<cv::Mat> channels(3);
cv::split(frame, channels);
channels[0] = channels[0]*config.cc_alpha + config.cc_beta;
channels[1] = channels[1]*config.cc_alpha + config.cc_beta;
channels[2] = channels[2]*config.cc_alpha + config.cc_beta;
cv::merge(channels, frame);
frame.convertTo(frame, CV_8UC3);
}
if(config.enable_sharpen)
{
cv::Mat out;
cv::GaussianBlur(frame, out, cv::Size(0, 0), config.sharp_kernel*2+1);
cv::addWeighted(frame, 1.0+config.sharp_weight, out, -1.0*config.sharp_weight, 0, out);
out.copyTo(frame);
}
msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", frame).toImageMsg();
if(pub->getNumSubscribers() > 0)
pub->publish(msg);
cv::waitKey(3);
}
bool hasSub(image_transport::Publisher &pub_){
return (pub_.getNumSubscribers());
}
bool isEnabled(){
return enabled_;
}
void startup(image_transport::ImageTransport &it, image_transport::Subscriber &img_input_){
img_input_ = it.subscribe(cam_topic, 1, &inputCB, 0);
enabled_ = true;
}
void shutdown(image_transport::Subscriber &img_input_){
img_input_ = image_transport::Subscriber();
enabled_ = false;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "cam_repub");
ros::NodeHandle nh{"~"};
image_transport::ImageTransport it(nh);
image_transport::Publisher pub_;
image_transport::Publisher pub_orig_;
image_transport::Subscriber img_input_;
dynamic_reconfigure::Server<ltu_actor_inputprocess_camadjust::CamPubConfig> server_;
pub = &pub_;
img_input = &img_input_;
server = &server_;
clahe = cv::createCLAHE();
server_.setCallback(dynConfigCB);
server_.getConfigDefault(config);
if (nh.hasParam("resize")) { nh.getParam("resize", config.resize); }
if (nh.hasParam("enable_less_color")) { nh.getParam("enable_less_color", config.enable_less_color); }
if (nh.hasParam("less_color_mux")) { nh.getParam("less_color_mux", config.less_color_mux); }
if (nh.hasParam("enable_clahe")) { nh.getParam("enable_clahe", config.enable_clahe); }
if (nh.hasParam("clahe_clip")) { nh.getParam("clahe_clip", config.clahe_clip); }
if (nh.hasParam("enable_color_correct")) { nh.getParam("enable_color_correct", config.enable_color_correct); }
if (nh.hasParam("cc_alpha")) { nh.getParam("cc_alpha", config.cc_alpha); }
if (nh.hasParam("cc_beta")) { nh.getParam("cc_beta", config.cc_beta); }
if (nh.hasParam("enable_sharpen")) { nh.getParam("enable_sharpen", config.enable_sharpen); }
if (nh.hasParam("sharp_weight")) { nh.getParam("sharp_weight", config.sharp_weight); }
if (nh.hasParam("sharp_kernel")) { nh.getParam("sharp_kernel", config.sharp_kernel); }
server_.updateConfig(config);
if (!nh.getParam("cam_topic", cam_topic))
{
ROS_ERROR_STREAM("[FATAL] Sign detection: param 'camera_topic' not defined");
exit(0);
}
pub_ = it.advertise("image", 1);
ros::Rate r(10);
while (ros::ok()){
if (hasSub(pub_)){
if (!isEnabled()){
startup(it, img_input_);
}
} else {
if (isEnabled()){
shutdown(img_input_);
}
}
ros::spinOnce();
r.sleep();
}
}
|
#include <string>
#include <iostream>
#include <time.h>
#define LEN 100
#define SIZE 80
using namespace std;
typedef long long int lint;
lint L[SIZE];
lint ipow(lint x, lint n)
{
lint i, ret = 1;
for (i = 0; i < n; i++)
ret *= x;
return ret;
}
lint f(lint n) {
return ipow(7, n) * (19 * n + 127);
}
char D(string A, string B, lint n, lint* L) {
lint k = 1;
while (L[k] < n) k++;
while (L[0] < n) {
if (L[k - 2] < n) {
n = n - L[k - 2];
k--;
}
else
k -= 2;
}
if (k % 2 == 0) return A[n - 1];
else return B[n - 1];
}
void PE0230() {
string A("1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679");
string B("8214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196");
L[0] = L[1] = LEN;
for (lint i = 2; i < SIZE; i++)
L[i] = L[i - 1] + L[i - 2];
for (lint i = 17; i >= 0; i--)
cout << D(A, B, f(i), L);
cout << endl;
}
int main()
{
clock_t start, end;
start = clock();
PE0230();
end = clock();
printf("%d msec.\n", end - start);
return 0;
}
|
#include<cstdio>
using namespace std;
int pre[30010];
int find(int x)
{
if(pre[x]==x) return x;
else return pre[x]=find(pre[x]);
}
void join(int x,int y)
{
int r1=find(x);
int r2=find(y);
if(r1!=r2)
pre[r1]=r2;
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
pre[i]=i;
for(int i=1;i<=m;i++)
{
int zi,xi,yi;
scanf("%d%d%d",&zi,&xi,&yi);
if(zi==1)
join(xi,yi);
if(zi==2)
{
if(find(xi)==find(yi))
printf("Y\n");
else
printf("N\n");
}
}
}
|
/* -*- 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.
*/
#include "core/pch.h"
#include "adjunct/quick/widgets/OpPagebar.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/hotlist/HotlistManager.h"
#include "adjunct/quick/menus/DesktopMenuHandler.h"
#include "adjunct/quick/managers/DesktopClipboardManager.h"
#include "adjunct/quick/managers/opsetupmanager.h"
#include "adjunct/quick/models/DesktopHistoryModel.h"
#include "adjunct/quick/models/DesktopGroupModelItem.h"
#include "adjunct/quick/quick-widget-names.h"
#include "adjunct/quick/widgets/OpToolbarMenuButton.h"
#include "adjunct/quick/windows/BrowserDesktopWindow.h"
#include "adjunct/quick/windows/DocumentDesktopWindow.h"
#include "adjunct/quick/WindowCommanderProxy.h"
#include "adjunct/quick/widgets/OpTabGroupButton.h"
#include "adjunct/quick/widgets/OpThumbnailPagebar.h"
#include "adjunct/quick/widgets/PagebarButton.h"
#include "adjunct/desktop_util/file_utils/filenameutils.h"
#include "modules/inputmanager/inputmanager.h"
#include "modules/display/vis_dev.h"
#include "modules/prefs/prefsmanager/collections/pc_ui.h"
#include "modules/skin/OpSkinManager.h"
#include "modules/widgets/WidgetContainer.h"
#include "modules/logdoc/logdoc_util.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/dragdrop/dragdrop_data_utils.h"
#include "modules/dragdrop/dragdrop_manager.h"
#ifdef VEGA_OPPAINTER_SUPPORT
#include "adjunct/quick/managers/AnimationManager.h"
#endif
// Turn on to get debug pagebar by dumping it out
#ifdef _DEBUG // Safeguard to avoid printfs in release
//#define PAGEBAR_DUMP_DEBUGGING
#endif // _DEBUG
/***********************************************************************************
**
** OpPagebar
**
***********************************************************************************/
namespace {
INT32 MINIMUM_BUTTON_WIDTH_SHOWING_CLOSE_BUTTON = 80;
}
OP_STATUS OpPagebar::CreateToolbar(OpToolbar** toolbar)
{
return OpToolbar::Construct(toolbar);
}
OP_STATUS OpPagebar::InitPagebar()
{
// Head
RETURN_IF_ERROR(CreateToolbar(&m_head_bar));
m_head_bar->SetContentListener(this);
m_head_bar->GetBorderSkin()->SetImage("Pagebar Head Skin");
m_head_bar->SetName("Pagebar Head");
#ifndef _MACINTOSH_
// Set the head bar to not stretch when it can contain the enu button.
// Needed for compatibility with the aero integration where the head bar never grows
// On mac it never contains the menu button, so leave it as growing
m_head_bar->SetFixedHeight(FIXED_HEIGHT_NONE);
#endif // !_MACINTOSH_
AddChild(m_head_bar, TRUE);
// Tail
RETURN_IF_ERROR(CreateToolbar(&m_tail_bar));
m_tail_bar->GetBorderSkin()->SetImage("Pagebar Tail Skin");
m_tail_bar->SetName("Pagebar Tail");
AddChild(m_tail_bar, TRUE);
// Floating
RETURN_IF_ERROR(CreateToolbar(&m_floating_bar));
m_floating_bar->GetBorderSkin()->SetImage("Pagebar Floating Skin");
m_floating_bar->SetName("Pagebar Floating");
AddChild(m_floating_bar);
SetName("Pagebar");
if(g_pcui->GetIntegerPref(PrefsCollectionUI::ShowMenu))
{
EnsureMenuButton(FALSE);
}
m_initialized = TRUE; // Must be the last statement
return OpStatus::OK;
}
OP_STATUS OpPagebar::Construct(OpPagebar** obj, OpWorkspace* workspace)
{
OpAutoPtr<OpThumbnailPagebar> pagebar(OP_NEW(OpThumbnailPagebar, (workspace->GetParentDesktopWindow()->GetToplevelDesktopWindow()->PrivacyMode())));
if (!pagebar.get())
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsError(pagebar->init_status))
return pagebar->init_status;
// Workspace
RETURN_IF_ERROR(pagebar->SetWorkspace(workspace));
RETURN_IF_ERROR(pagebar->InitPagebar());
*obj = pagebar.release();
return OpStatus::OK;
}
OP_STATUS OpPagebar::SetWorkspace(OpWorkspace* workspace)
{
if (m_workspace)
m_workspace->RemoveListener(this);
if(workspace)
RETURN_IF_ERROR(workspace->AddListener(this));
m_workspace = workspace;
return OpStatus::OK;
}
OpPagebar::OpPagebar(BOOL privacy_mode)
: OpToolbar(PrefsCollectionUI::PagebarAlignment, PrefsCollectionUI::PagebarAutoAlignment)
,m_head_bar(NULL)
,m_tail_bar(NULL)
,m_workspace(NULL)
,m_floating_bar(NULL)
,m_initialized(FALSE)
,m_is_handling_action(FALSE)
,m_allow_menu_button(TRUE)
,m_dragged_pagebar_button(-1)
,m_settings(NULL)
,m_extra_top_padding_head(0)
,m_extra_top_padding_normal(0)
,m_extra_top_padding_tail(0)
,m_extra_top_padding_tail_width(0)
{
SetListener(this);
SetWrapping(OpBar::WRAPPING_OFF);
SetSelector(TRUE);
SetFixedHeight(FIXED_HEIGHT_BUTTON);
SetShrinkToFit(TRUE);
SetFillToFit(TRUE);
SetButtonType(OpButton::TYPE_PAGEBAR);
SetStandardToolbar(FALSE);
#ifdef QUICK_FISHEYE_SUPPORT
SetFisheyeShrink(TRUE);
#endif // QUICK_FISHEYE_SUPPORT
GetBorderSkin()->SetImage("Pagebar Skin");
SetFixedMaxWidth(GetSkinManager()->GetOptionValue("Pagebar max button width", 150));
SetFixedMinWidth(GetSkinManager()->GetOptionValue("Pagebar min button width", 150));
}
void OpPagebar::OnDeleted()
{
SetWorkspace(NULL);
OpToolbar::OnDeleted();
}
INT32 OpPagebar::GetRowHeight()
{
INT32 w, row_height;
GetBorderSkin()->GetSize(&w, &row_height);
return row_height;
}
INT32 OpPagebar::GetRowWidth()
{
INT32 row_width, h;
GetBorderSkin()->GetSize(&row_width, &h);
return row_width;
}
void OpPagebar::SetHeadAlignmentFromPagebar(Alignment pagebar_alignment, BOOL force_on)
{
if (pagebar_alignment != ALIGNMENT_OFF)
{
if (force_on || m_head_bar->GetResultingAlignment() != ALIGNMENT_OFF)
{
if(pagebar_alignment == ALIGNMENT_LEFT || pagebar_alignment == ALIGNMENT_RIGHT)
{
m_head_bar->SetAlignment(ALIGNMENT_TOP, TRUE);
}
else
{
m_head_bar->SetAlignment(pagebar_alignment, TRUE);
}
}
// we still want to use the skin types from the page bar
SkinType skin_type = GetBorderSkin()->GetType();
if(m_head_bar->GetButtonSkinType() != skin_type)
{
m_head_bar->SetButtonSkinType(skin_type);
}
}
}
void OpPagebar::SetTailAlignmentFromPagebar(Alignment pagebar_alignment)
{
if (pagebar_alignment != ALIGNMENT_OFF)
{
if (m_tail_bar->GetResultingAlignment() != ALIGNMENT_OFF)
{
if(pagebar_alignment == ALIGNMENT_LEFT || pagebar_alignment == ALIGNMENT_RIGHT)
{
// move it to just after head in the layout
// m_tail_bar->Remove();
// AddChild(m_tail_bar, FALSE, TRUE);
// m_head_bar->Remove();
// AddChild(m_head_bar, FALSE, TRUE);
m_tail_bar->SetAlignment(ALIGNMENT_TOP, TRUE);
}
else
{
// move it back to the end
// m_tail_bar->Remove();
// AddChild(m_tail_bar);
m_tail_bar->SetAlignment(pagebar_alignment, TRUE);
}
}
// we still want to use the skin types from the page bar
SkinType skin_type = GetBorderSkin()->GetType();
if(m_tail_bar->GetButtonSkinType() != skin_type)
{
m_tail_bar->SetButtonSkinType(skin_type);
}
}
}
/***********************************************************************************
**
** OnRelayout
**
***********************************************************************************/
void OpPagebar::OnRelayout()
{
BOOL target = IsTargetToolbar();
OpBar::OnRelayout();
Alignment alignment = GetResultingAlignment();
// head and tail toolbars get the same alignment as pagebar in order to define
// their skinning based on the pagebar's position
if (alignment != ALIGNMENT_OFF)
{
SetHeadAlignmentFromPagebar(alignment);
if (m_floating_bar->GetResultingAlignment() != ALIGNMENT_OFF)
{
m_floating_bar->SetAlignment(alignment);
}
// we still want to use the skin types from the page bar
SkinType skin_type = GetBorderSkin()->GetType();
if(m_floating_bar->GetButtonSkinType() != skin_type)
{
m_floating_bar->SetButtonSkinType(skin_type);
}
if(GetButtonSkinType() != skin_type)
{
SetButtonSkinType(skin_type);
}
SetTailAlignmentFromPagebar(alignment);
}
if(target)
{
UpdateTargetToolbar(TRUE);
}
}
/***********************************************************************************
**
** OnLayout - Calculate the nominal size needed for the pagebar using the standard
** toolbar layout code, then add the extra spacing we might need
**
***********************************************************************************/
void OpPagebar::OnLayout()
{
INT32 left, top, right, bottom;
OpToolbar::GetPadding(&left, &top, &right, &bottom);
// layout head and tail toolbars to be within the padding of this toolbar
OpRect rect = GetBounds();
rect.x += left;
rect.y += top;
rect.width -= left + right;
rect.height -= top + bottom;
INT32 row_height = GetRowHeight();
// INT32 row_width = GetRowWidth();
OpBar::OnLayout();
OpRect head_rect;
OpRect tail_rect;
m_head_bar->GetRequiredSize(head_rect.width, head_rect.height);
m_tail_bar->GetRequiredSize(tail_rect.width, tail_rect.height);
// only show an empty tail-bar if it is customized at the very moment
if (m_tail_bar->GetWidgetCount() == 0 && !g_application->IsCustomizingToolbars())
tail_rect.width = 0;
if (IsHorizontal())
{
if (GetWrapping() != WRAPPING_NEWLINE)
row_height = rect.height;
head_rect.x = rect.x;
if (row_height-(INT32)m_extra_top_padding_head > head_rect.height)
head_rect.height = row_height-m_extra_top_padding_head;
int tail_padding = m_extra_top_padding_normal;
if (m_extra_top_padding_tail > m_extra_top_padding_normal && tail_rect.height+(INT32)m_extra_top_padding_tail > row_height)
{
tail_rect.x = rect.x + rect.width - tail_rect.width - m_extra_top_padding_tail_width;
}
else
{
if (m_extra_top_padding_tail > m_extra_top_padding_normal)
tail_padding = m_extra_top_padding_tail;
tail_rect.x = rect.x + rect.width - tail_rect.width;
}
if (row_height-tail_padding > tail_rect.height)
tail_rect.height = row_height-tail_padding;
if (GetWrapping() == WRAPPING_NEWLINE)
{
// bottom-align tail-bar
tail_rect.y = rect.y + rect.height - tail_rect.height;
if (GetAlignment() == ALIGNMENT_TOP)
{
// top align head toolbar
head_rect.y = rect.y + m_extra_top_padding_head;
}
else
{
// top-align head-bar (close to hotlist)
head_rect.y = rect.y;
}
}
else // center-align head- and tail-bar
{
if (m_head_bar->HasFixedHeight())
head_rect.y = rect.y + (rect.height - head_rect.height) / 2;
else
head_rect.y = rect.y + m_extra_top_padding_head;
tail_rect.y = rect.y + tail_padding + (rect.height - tail_padding - tail_rect.height) / 2;
}
}
else
{
head_rect.x = rect.x; // top-align head_rect
head_rect.y = rect.y;
tail_rect.x = rect.x; // bottom-align tail_rect
// tail_rect.y = rect.y + rect.height - tail_rect.height;
tail_rect.y = rect.y;
}
LayoutChildToAvailableRect(m_head_bar, head_rect);
if(IsHorizontal())
{
LayoutChildToAvailableRect(m_tail_bar, tail_rect);
}
if (m_floating_bar->IsOn())
{
// align "add tab" floating toolbar
OpRect floating_rect;
m_floating_bar->GetRequiredSize(floating_rect.width, floating_rect.height);
INT32 pos = GetWidgetCount();
OpWidget *last_button = pos ? GetWidget(pos - 1) : NULL;
// position the floating bar after the last _visible_ tab always. With extender menu,
// the last tab might not be visible
while(last_button && !last_button->IsVisible())
{
last_button = pos ? GetWidget(--pos) : NULL;
}
OpRect last_rect = head_rect;
if (last_button)
last_rect = last_button->IsFloating() ? last_button->GetOriginalRect() : last_button->GetRect();
// get margins
m_floating_bar->GetSkinMargins(&left, &top, &right, &bottom);
if (IsHorizontal())
{
int top_padding = m_extra_top_padding_normal;
if (m_extra_top_padding_tail > m_extra_top_padding_normal && tail_rect.height+(INT32)m_extra_top_padding_tail <= row_height &&
floating_rect.height+(INT32)m_extra_top_padding_tail <= row_height)
top_padding = m_extra_top_padding_tail;
if (row_height-top_padding > floating_rect.height)
floating_rect.height = row_height-top_padding;
// if floating toolbar fits in between last button and tail-bar
// (this is not the case when the extender menu is on)
// if (last_rect.x + last_rect.width + floating_rect.width <= tail_rect.x - right)
{
if (GetRTL())
floating_rect.x = last_rect.x - floating_rect.width - left;
else
floating_rect.x = last_rect.x + last_rect.width + left;
if (top_padding > (INT32)m_extra_top_padding_normal)
{
floating_rect.y = (rect.y + top_padding + (rect.height - top_padding - floating_rect.height) / 2);
}
else
{
// center the toolbar (needed when tabs are higher than this toolbar)
floating_rect.y = (last_rect.y + (last_rect.height - floating_rect.height) / 2);
}
}
m_floating_bar->LayoutToAvailableRect(floating_rect);
}
else
{
// if (row_width > floating_rect.width)
// floating_rect.width = row_width;
if(last_rect.y + last_rect.height + floating_rect.height <= rect.height)
{
floating_rect.y = last_rect.y + last_rect.height + top;
}
else
{
floating_rect.y = rect.height - floating_rect.height - top;
}
// floating_rect.x = 0;
floating_rect.x = (last_rect.x + (last_rect.width - floating_rect.width) / 2);
// align on top of tail-bar
// floating_rect.x = rect.x;
// floating_rect.y = rect.y + rect.height - floating_rect.height;
tail_rect.x = rect.width - tail_rect.width;
LayoutChildToAvailableRect(m_floating_bar, floating_rect);
LayoutChildToAvailableRect(m_tail_bar, tail_rect);
}
}
OpBar::OnLayout();
}
INT32 OpPagebar::OnBeforeAvailableWidth(INT32 available_width)
{
/*
if(GetWrapping() == WRAPPING_EXTENDER)
{
OpRect tail_rect = m_tail_bar->GetRect();
return available_width - tail_rect.width;
}
*/
return available_width;
};
BOOL OpPagebar::OnBeforeExtenderLayout(OpRect& extender_rect)
{
Alignment alignment = GetAlignment();
BOOL overflow = FALSE;
if(alignment == ALIGNMENT_TOP || alignment == ALIGNMENT_BOTTOM)
{
OpRect floating_rect = m_floating_bar->GetRect();
OpRect tail_rect = m_tail_bar->GetRect();
if (GetRTL())
{
extender_rect.x = floating_rect.x - extender_rect.width;
if (extender_rect.x < tail_rect.Right())
{
extender_rect.x = tail_rect.Right();
overflow = TRUE;
}
if (extender_rect.Right() > floating_rect.x)
extender_rect.x = floating_rect.x - extender_rect.width;
// floating_rect and tail_rect are already in RTL, and so is
// extender_rect. But OpToolbar will adjust extender_rect for RTL
// later, because OpToolbar is more general. Need to flip one more
// time here so that the end result is RTL.
extender_rect = AdjustForDirection(extender_rect);
}
else
{
extender_rect.x = floating_rect.Right();
if (extender_rect.Right() > tail_rect.x)
{
extender_rect.x = tail_rect.x - extender_rect.width;
overflow = TRUE;
}
extender_rect.x = MAX(extender_rect.x, floating_rect.Right());
}
}
else if(alignment == ALIGNMENT_LEFT || alignment == ALIGNMENT_RIGHT)
{
OpRect floating_rect = m_floating_bar->GetRect();
OpRect tail_rect = m_tail_bar->GetRect();
extender_rect.y = floating_rect.Bottom();
if (extender_rect.Bottom() > tail_rect.y)
{
extender_rect.y = tail_rect.y - extender_rect.height;
overflow = TRUE;
}
extender_rect.y = MAX(extender_rect.y, floating_rect.Bottom());
}
return overflow;
}
BOOL OpPagebar::OnBeforeWidgetLayout(OpWidget *widget, OpRect& layout_rect)
{
if(widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
PagebarButton *button = static_cast<PagebarButton *>(widget);
if(button->IsCompactButton())
{
// Limit the height of the pinned button (make it look good when using thumbnail tabs)
INT32 w, h;
button->GetRequiredSize(w, h);
if(GetAlignment() == ALIGNMENT_BOTTOM)
{
layout_rect.y = 0;
}
else
{
layout_rect.y = layout_rect.Bottom() - h;
}
layout_rect.height = h;
}
}
return TRUE;
}
INT32 OpPagebar::GetPagebarButtonMin()
{
INT32 min = 0;
if (IsHorizontal() && GetRTL())
{
if (m_floating_bar->IsOn())
{
min = m_floating_bar->GetRect().Right();
INT32 left = 0, top = 0, right = 0, bottom = 0;
m_floating_bar->GetSkinMargins(&left, &top, &right, &bottom);
min += right;
}
else if (m_tail_bar->IsOn())
{
min = m_tail_bar->GetRect().Right();
}
}
else if (m_head_bar->IsOn())
{
if (IsHorizontal())
{
if (m_extra_top_padding_head + m_head_bar->GetRect().height >= m_extra_top_padding_normal)
{
min += m_head_bar->GetRect().width;
}
}
else
{
min += m_head_bar->GetRect().height;
}
}
return min;
}
INT32 OpPagebar::GetPagebarButtonMax()
{
INT32 max = IsHorizontal() ? GetRect().width : GetRect().height;
if (IsHorizontal() && GetRTL())
{
if (m_extra_top_padding_head + m_head_bar->GetRect().height >= m_extra_top_padding_normal)
max = m_head_bar->GetRect().x;
}
else
{
if (m_floating_bar->IsOn())
{
max = IsHorizontal() ? m_floating_bar->GetRect().x : m_floating_bar->GetRect().y;
// take margins into account
INT32 m_left = 0, m_top = 0, m_right = 0, m_bottom = 0;
m_floating_bar->GetSkinMargins(&m_left, &m_top, &m_right, &m_bottom);
max -= IsHorizontal() ? m_left : m_top;
}
else if (m_tail_bar->IsOn())
{
max -= IsHorizontal() ? m_tail_bar->GetRect().width : m_tail_bar->GetRect().height;
}
}
return max;
}
/***********************************************************************************
**
** GetPadding
**
***********************************************************************************/
void OpPagebar::GetPadding(INT32* left, INT32* top, INT32* right, INT32* bottom)
{
OpToolbar::GetPadding(left, top, right, bottom);
// add to padding what head and tail (and sometimes add-button) is eating of space
INT32 head_width = 0, head_height = 0;
INT32 tail_width = 0, tail_height = 0;
if (m_head_bar->IsOn())
{
m_head_bar->GetRequiredSize(head_width, head_height);
}
BOOL move_float_left = FALSE;
INT32 row_height = GetRowHeight();
if (GetWrapping() != WRAPPING_NEWLINE)
{
OpRect rect = GetBounds();
rect.height -= *top + *bottom;
row_height = rect.height;
}
int right_padding = m_extra_top_padding_tail_width;
if (m_tail_bar->IsOn())
{
m_tail_bar->GetRequiredSize(tail_width, tail_height);
if (m_extra_top_padding_tail > m_extra_top_padding_normal && tail_height+(INT32)m_extra_top_padding_tail > row_height)
{
move_float_left = TRUE;
right_padding += tail_width;
}
}
INT32 floating_height = 0;
if (m_floating_bar->IsOn() && m_floating_bar->GetWidgetCount() > 0) // if the "add tab" button isn't auto-layouted
{
INT32 button_width = 0, button_height = 0;
m_floating_bar->GetRequiredSize(button_width, button_height);
// take margins into account
INT32 marg_left = 0, marg_top = 0, marg_right = 0, marg_bottom = 0;
m_floating_bar->GetSkinMargins(&marg_left, &marg_top, &marg_right, &marg_bottom);
if (IsHorizontal())
{
tail_width += (marg_right+button_width);
}
else
{
floating_height = marg_bottom + button_height;
}
if (move_float_left)
{
right_padding += button_width+marg_right;
}
else if (m_extra_top_padding_tail > m_extra_top_padding_normal && button_height+(INT32)m_extra_top_padding_tail > row_height)
{
right_padding += button_width;
}
}
if (IsHorizontal())
{
if(m_extra_top_padding_head + head_height >= m_extra_top_padding_normal)
{
*left += head_width;
}
*right += max(tail_width, right_padding);
*top += m_extra_top_padding_normal;
}
else
{
*top += max(tail_height, head_height);
*bottom += floating_height;
}
}
/***********************************************************************************
**
** SetSelected
**
***********************************************************************************/
BOOL OpPagebar::SetSelected(INT32 pos, BOOL invoke_listeners)
{
// just return.. wait for proper OnDesktopWindowActivated
return FALSE;
}
/***********************************************************************************
**
** SetAlignment
**
***********************************************************************************/
BOOL OpPagebar::SetAlignment(Alignment alignment, BOOL write_to_prefs)
{
SkinType skin_type = GetBorderSkin()->GetType();
// head and tail toolbars get the same alignment as pagebar in order to define
// their skinning based on the pagebar's position
if (alignment != ALIGNMENT_OFF)
{
SetHeadAlignmentFromPagebar(alignment);
if (m_floating_bar->GetResultingAlignment() != ALIGNMENT_OFF)
{
m_floating_bar->SetAlignment(alignment);
}
m_floating_bar->SetButtonSkinType(skin_type);
SetTailAlignmentFromPagebar(alignment);
}
OpString8 style_name;
style_name.Set(GetName());
style_name.Append(".style");
if (alignment != GetAlignment() && alignment != ALIGNMENT_OFF && GetAlignment() != ALIGNMENT_OFF && alignment != ALIGNMENT_OLD_VISIBLE)
{
// NOTE: When alignment changes from horizontal (top or bottom) to vertical (left or right) alignment we force
// wrapping to be WRAPPING_EXTENDER and from vertical to horizontal alignment we force wrapping to be WRAPPING_OFF.
if(alignment == ALIGNMENT_LEFT || alignment == ALIGNMENT_RIGHT)
{
// we need to show the expander on the left or right as we have no other way
// to ensure we can show all tabs.
OpToolbar::SetWrapping(WRAPPING_EXTENDER);
}
else
{
OpToolbar::SetWrapping(WRAPPING_OFF);
}
// Update pref if necessary
if (!g_application->IsCustomizingToolbars() && IsInitialized() && !m_settings)
{
PrefsFile* prefs_file = g_setup_manager->GetSetupFile(OPTOOLBAR_SETUP, TRUE);
TRAPD(err, prefs_file->ClearSectionL(style_name.CStr()));
OnWriteStyle(prefs_file, style_name.CStr());
}
}
else if (m_settings && m_settings->IsChanged(SETTINGS_CUSTOMIZE_END_CANCEL))
{
PrefsSection *style_section = NULL;
TRAPD(err, style_section = g_setup_manager->GetSectionL(style_name.CStr(), OPTOOLBAR_SETUP, NULL, FALSE));
if(style_section)
OnReadStyle(style_section);
}
BOOL rc = OpBar::SetAlignment(alignment, write_to_prefs);
SetButtonSkinType(skin_type);
return rc;
}
OpSkinElement* OpPagebar::GetGroupBackgroundSkin(BOOL use_thumbnails)
{
return g_skin_manager->GetSkinElement(use_thumbnails ? "Tab Thumbnail Group Group Expanded Background Skin" : "Tab Group Expanded Background Skin", GetBorderSkin()->GetType());
}
INT32 OpPagebar::GetGroupSpacing(BOOL use_thumbnails)
{
OpSkinElement *elm = GetGroupBackgroundSkin(use_thumbnails);
if(elm)
{
INT32 spacing;
if (OpStatus::IsSuccess(elm->GetSpacing(&spacing, 0)))
return spacing;
}
return 0;
}
void OpPagebar::PaintGroupRect(OpRect &overlay_rect, BOOL use_thumbnails)
{
OpSkinElement *elm = GetGroupBackgroundSkin(use_thumbnails);
if(elm)
{
INT32 left, right, top, bottom;
elm->GetMargin(&left, &top, &right, &bottom, 0);
overlay_rect.x += left;
overlay_rect.y += top;
overlay_rect.width -= left + right;
overlay_rect.height -= top + bottom;
elm->Draw(GetVisualDevice(), overlay_rect, 0, 0, NULL);
}
}
void OpPagebar::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect)
{
OpToolbar::OnPaint(widget_painter, paint_rect);
BOOL use_thumbnails = FALSE;
OpRect overlay_rect;
UINT32 current_group = 0;
int last_x = 0;
int count = GetWidgetCount();
for(int i = 0; i < count; i++)
{
OpWidget *widget = GetWidget(i);
UINT32 this_group = 0;
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
PagebarButton *button = static_cast<PagebarButton *>(widget);
this_group = button->GetGroupNumber();
use_thumbnails = button->CanUseThumbnails();
}
else if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
this_group = current_group;
}
if (this_group != current_group && !overlay_rect.IsEmpty())
{
// We have the whole group, paint it!
PaintGroupRect(overlay_rect, use_thumbnails);
overlay_rect.Empty();
}
if (this_group && !widget->IsHidden())
{
// Use the original rect if it's floating, except for collapsed groups
OpRect rect = widget->IsFloating() ? widget->GetOriginalRect() : widget->GetRect();
if (!IsGroupExpanded(this_group))
rect = widget->GetRect();
if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
// Need to be sure the group button doesn't extend the height of the group area.
// This may happen because of misalignment in skin and cause paint artifacts.
if (IsHorizontal())
{
rect.y = overlay_rect.y;
rect.height = overlay_rect.height;
}
else
{
rect.x = overlay_rect.x;
rect.width = overlay_rect.width;
}
}
bool wrapped = false;
if (!overlay_rect.IsEmpty())
wrapped = IsHorizontal() && GetRTL() ? rect.x > last_x : rect.x < last_x;
if (wrapped)
{
// We must have wrapped to a new line. Flush what we have and begin a new group.
PaintGroupRect(overlay_rect, use_thumbnails);
overlay_rect.Empty();
}
last_x = rect.x;
overlay_rect.UnionWith(rect);
}
current_group = this_group;
}
if(!overlay_rect.IsEmpty())
{
// We had a pending paint for a group, paint it!
PaintGroupRect(overlay_rect, use_thumbnails);
}
}
int OpPagebar::FindActiveTab(int position, UINT32 group_number)
{
if (group_number)
{
for (int i = position; i < GetWidgetCount(); i++)
{
OpWidget* widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) &&
static_cast<PagebarButton*>(widget)->GetGroupNumber() == group_number)
{
if (static_cast<PagebarButton*>(widget)->IsActiveTabForGroup())
return i;
}
}
}
return -1;
}
int OpPagebar::FindFirstGroupTab(INT32 position)
{
OpWidget* widget = GetWidget(position);
if (widget && IsInGroup(position))
{
unsigned int group_number = static_cast<PagebarButton*>(widget)->GetGroupNumber();
if (!IsGroupExpanded(group_number, NULL))
{
for (int i = position-1; i >=0; i--)
{
widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
if (static_cast<PagebarButton*>(widget)->GetGroupNumber() != group_number)
return i+1;
}
else if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
return i+1;
}
}
return 0;
}
}
return position;
}
int OpPagebar::FindLastGroupTab(INT32 position)
{
OpWidget* widget = GetWidget(position);
if (widget && IsInGroup(position))
{
unsigned int group_number = static_cast<PagebarButton*>(widget)->GetGroupNumber();
if (IsGroupExpanded(group_number, NULL))
{
return position+1;
}
else
{
for (int i = position+1; i < GetWidgetCount(); i++)
{
widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
if (static_cast<PagebarButton*>(widget)->GetGroupNumber() != group_number)
return i;
}
}
return GetWidgetCount();
}
}
return position;
}
int OpPagebar::FindFirstTab(INT32 position, UINT32 group_number)
{
if (group_number)
{
for (int i = position; i < GetWidgetCount(); i++)
{
OpWidget* widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) &&
static_cast<PagebarButton*>(widget)->GetGroupNumber() == group_number)
{
return i;
}
}
}
return -1;
}
bool OpPagebar::IsInExpandedGroup(INT32 position)
{
OpWidget* widget = GetWidget(position);
if (widget && IsInGroup(position))
{
unsigned int group_number = static_cast<PagebarButton*>(widget)->GetGroupNumber();
return !!IsGroupExpanded(group_number, NULL);
}
return false;
}
bool OpPagebar::IsInGroup(INT32 position)
{
OpWidget* widget = GetWidget(position);
if (widget)
{
if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
return true;
else if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
return !!static_cast<PagebarButton *>(widget)->IsGrouped();
}
return false;
}
INT32 OpPagebar::GetActiveTabInGroup(INT32 position)
{
OpWidget* widget = GetWidget(position);
if (widget && widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
int group_number = static_cast<PagebarButton*>(widget)->GetGroupNumber();
if (group_number > 0 && !IsGroupExpanded(group_number, NULL))
{
int start = FindFirstTab(0, group_number);
if (start != -1)
{
int active = FindActiveTab(start, group_number);
if (active != -1)
return active;
}
}
}
return position;
}
void OpPagebar::IncDropPosition(int& position, bool step_out_of_group)
{
OpWidget* widget = GetWidget(position);
if (widget)
{
if (IsInGroup(position))
{
unsigned int group_number = static_cast<PagebarButton*>(widget)->GetGroupNumber();
if (!IsGroupExpanded(group_number, NULL))
{
for (int i = position; i < GetWidgetCount(); i++)
{
widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
position = i + (step_out_of_group ? 1 : 0);
return;
}
}
}
}
position ++; // Default / fallback behavior
}
}
void OpPagebar::OnAlignmentChanged()
{
// Fixed height will not work well with expand/collapse buttons in vertical mode. They should only use as much space they need.
SetFixedHeight(IsHorizontal() ? FIXED_HEIGHT_BUTTON : FIXED_HEIGHT_NONE);
OpToolbar::OnAlignmentChanged();
}
BOOL OpPagebar::OnReadWidgetType(const OpString8& type)
{
if (!m_allow_menu_button && type.CompareI("MenuButton") == 0)
return FALSE;
return TRUE;
}
/***********************************************************************************
**
** IsCloseButtonVisible
**
***********************************************************************************/
BOOL OpPagebar::IsCloseButtonVisible(DesktopWindow* desktop_window, BOOL check_for_space_only)
{
if (!check_for_space_only && desktop_window && !desktop_window->IsClosableByUser())
return FALSE;
if (!g_pcui->GetIntegerPref(PrefsCollectionUI::ShowCloseButtons))
return FALSE;
if (!IsHorizontal())
return TRUE;
if (GetWrapping() != OpBar::WRAPPING_OFF)
return TRUE;
if (desktop_window && desktop_window->IsActive())
return TRUE;
INT32 visible_width = GetVisibleButtonWidth(desktop_window);
if (check_for_space_only && visible_width < 0)
return TRUE;
if (visible_width > MINIMUM_BUTTON_WIDTH_SHOWING_CLOSE_BUTTON)
return TRUE;
return FALSE;
}
/***********************************************************************************
**
** OnMouseDown
**
***********************************************************************************/
void OpPagebar::OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks)
{
OpToolbar::OnMouseDown(point, button, nclicks);
if ((button == MOUSE_BUTTON_1 && nclicks == 2) || button == MOUSE_BUTTON_3)
{
OpString text;
if( button == MOUSE_BUTTON_3 )
{
INT32 midclickaction = g_pcui->GetIntegerPref(PrefsCollectionUI::PagebarOpenURLOnMiddleClick);
// Default for UNIX for get data from selection buffer
#if defined(_X11_SELECTION_POLICY_)
if (midclickaction == 1)
{
g_desktop_clipboard_manager->GetText(text, true);
}
#endif
// All platforms will get data from clipboard buffer. Fallback for UNIX
if (midclickaction == 1 && text.IsEmpty())
g_desktop_clipboard_manager->GetText(text);
}
// Normally, we would use g_application->IsOpeningInBackgroundPreferred()
// but expected behaviour clashes with tweak configuration on Mac.
// That's why we prefer to use default tweak value here.
// see DSK-338217
BOOL open_in_background = (g_op_system_info->GetShiftKeyState() == SHIFTKEY_CTRL);
BOOL saved_open_page_setting = g_pcui->GetIntegerPref(PrefsCollectionUI::OpenPageNextToCurrent);
TRAPD(rc,g_pcui->WriteIntegerL(PrefsCollectionUI::OpenPageNextToCurrent, FALSE));
if( text.IsEmpty() )
{
g_application->GetBrowserDesktopWindow(
FALSE, // force new window
open_in_background,
TRUE, // create new page
NULL, NULL, 0, 0, TRUE, FALSE,
TRUE // ignore modifier keys - since we already passed our own open_in_background
);
}
else
{
g_application->OpenURL( text, NO, YES, open_in_background ? YES : NO );
}
TRAP(rc,g_pcui->WriteIntegerL(PrefsCollectionUI::OpenPageNextToCurrent, saved_open_page_setting));
}
}
/***********************************************************************************
**
** OnSettingsChanged
**
***********************************************************************************/
void OpPagebar::OnSettingsChanged(DesktopSettings* settings)
{
m_settings = settings;
OpToolbar::OnSettingsChanged(settings);
m_settings = NULL;
if(g_pcui->GetIntegerPref(PrefsCollectionUI::ShowMenu))
{
EnsureMenuButton(FALSE);
}
if (settings->IsChanged(SETTINGS_SKIN))
{
SetFixedMaxWidth(GetSkinManager()->GetOptionValue("Pagebar max button width", 150));
SetFixedMinWidth(GetSkinManager()->GetOptionValue("Pagebar min button width", 150));
PrefsSection* pagebar_section = NULL;
TRAPD(err, pagebar_section = g_setup_manager->GetSectionL("Pagebar.style", OPTOOLBAR_SETUP));
BOOL found_style_entry = pagebar_section && pagebar_section->FindEntry(UNI_L("Button style"));
if(!found_style_entry && g_skin_manager->GetOptionValue("PageCloseButtonOnLeft", 0))
{
SetButtonStyle(OpButton::STYLE_IMAGE_AND_TEXT_ON_LEFT);
}
else
{
SetButtonStyle(m_default_button_style);
}
OP_DELETE(pagebar_section);
// Need to check the "Inverted Pagebar Icons" skin option again
OpWidget* child = (OpWidget*) childs.First();
while(child)
{
if(child->GetType() == WIDGET_TYPE_BUTTON)
{
OpButton *button = (OpButton *)child;
OpWidgetImage *image = button->GetForegroundSkin();
if(image)
{
OpString8 image_name;
image_name.Set(image->GetImage());
if(g_skin_manager->GetOptionValue("Inverted Pagebar Icons", 0))
{
if(image_name.FindI(" Inverted") == KNotFound)
{
if(OpStatus::IsSuccess(image_name.Append(" Inverted")))
{
if(g_skin_manager->GetSkinElement(image_name.CStr()))
{
button->GetForegroundSkin()->SetImage(image_name.CStr());
}
}
}
}
else
{
int pos = 0;
if((pos = image_name.FindI(" Inverted")) > KNotFound)
{
image_name.Delete(pos, op_strlen(" Inverted"));
if(g_skin_manager->GetSkinElement(image_name.CStr()))
{
button->GetForegroundSkin()->SetImage(image_name.CStr());
}
}
}
}
}
child = (OpWidget*) child->Suc();
}
}
}
/***********************************************************************************
**
** OnMouseEvent
**
***********************************************************************************/
void OpPagebar::OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks)
{
if ( widget == this)
{
BOOL shift = vis_dev->GetView()->GetShiftKeys() & SHIFTKEY_SHIFT;
DesktopWindow* window = (DesktopWindow*) GetUserData(pos);
if (window)
{
if( down && button == MOUSE_BUTTON_1 && shift )
{
g_input_manager->InvokeAction(OpInputAction::ACTION_CLOSE_PAGE, 1, NULL, this);
}
else if( down && (button == MOUSE_BUTTON_3 || ( g_pcui->GetIntegerPref(PrefsCollectionUI::DoubleclickToClose) && button == MOUSE_BUTTON_1 && nclicks == 2 )) )
{
g_input_manager->InvokeAction(OpInputAction::ACTION_CLOSE_PAGE, 1, NULL, this);
}
}
}
else
{
OpToolbar::OnMouseEvent(widget, pos, x, y, button, down, nclicks);
}
}
/***********************************************************************************
**
** GetDragSourcePos
**
***********************************************************************************/
INT32 OpPagebar::GetDragSourcePos(DesktopDragObject* drag_object)
{
if (drag_object->GetType() == DRAG_TYPE_WINDOW)
{
DesktopWindow* desktop_window = g_application->GetDesktopWindowCollection().GetDesktopWindowByID(drag_object->GetID(0));
return FindWidgetByUserData(desktop_window);
}
return -1;
}
void OpPagebar::StartDrag(OpWidget* widget, INT32 pos, INT32 x, INT32 y)
{
if (widget->GetType() == OpTypedObject::WIDGET_TYPE_BUTTON && !IsExtenderButton(widget) )
{
OpButton* button = (OpButton*) widget;
DesktopWindow* window = (DesktopWindow*) button->GetUserData();
if (!window)
return;
DesktopDragObject* drag_object = widget->GetDragObject(OpTypedObject::DRAG_TYPE_WINDOW, x, y);
if (drag_object)
{
drag_object->AddID(window->GetID());
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
drag_object->SetID(window->GetID());
m_dragged_pagebar_button = drag_object->GetID();
}
if (window->GetType() == WINDOW_TYPE_DOCUMENT)
{
drag_object->SetURL(((DocumentDesktopWindow*)window)->GetWindowCommander()->GetCurrentURL(FALSE));
drag_object->SetTitle(((DocumentDesktopWindow*)window)->GetWindowCommander()->GetCurrentTitle());
OpString description;
WindowCommanderProxy::GetDescription(window->GetWindowCommander(), description);
if( description.HasContent() )
{
ReplaceEscapes( description.CStr(), description.Length(), TRUE );
DragDrop_Data_Utils::SetText(drag_object, description.CStr());
}
}
g_drag_manager->StartDrag(drag_object, NULL, FALSE);
}
}
}
/***********************************************************************************
**
** OnDragDrop
**
***********************************************************************************/
void OpPagebar::OnDragDrop(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y)
{
if (widget->IsOfType(WIDGET_TYPE_BUTTON))
{
OpWidget* parent = widget->GetParent();
if (parent && parent->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
// We are on top of the 'x' button in the pagebar button
OpRect rect = widget->GetRect(FALSE);
widget = parent;
x += rect.x;
y += rect.y;
}
}
if (drag_object->GetType() == DRAG_TYPE_WINDOW || drag_object->GetType() == DRAG_TYPE_THUMBNAIL)
return OnDragDropOfPreviouslyDraggedPagebarButton(widget, drag_object, pos, x, y);
if (widget != this)
{
// Triggers a recursive call to OpPagebar::OnDragDrop()
OpToolbar::OnDragDrop(widget, static_cast<DesktopDragObject*>(drag_object), pos, x, y);
}
else
{
OnDrop(widget, static_cast<DesktopDragObject*>(drag_object), pos, x, y);
RemoveAnyHighlightOnTargetButton();
}
}
void OpPagebar::OnDragMove(OpWidget* widget, OpDragObject* drag_object, INT32 pos, INT32 x, INT32 y)
{
if (widget->IsOfType(WIDGET_TYPE_BUTTON))
{
OpWidget* parent = widget->GetParent();
if (parent && parent->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
// We are on top of the 'x' button in the pagebar button
OpRect rect = widget->GetRect(FALSE);
widget = parent;
x += rect.x;
y += rect.y;
}
}
DesktopDragObject* desktop_drag_object = static_cast<DesktopDragObject *>(drag_object);
if (desktop_drag_object->GetID() == m_dragged_pagebar_button)
return OnDragMoveOfPreviouslyDraggedPagebarButton(widget, drag_object, pos, x, y);
// Convert to pagebar button position
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) && drag_object->GetSource() != widget)
{
OnDragOnButton(static_cast<PagebarButton*>(widget), desktop_drag_object, x, y);
// Coordinates in pagebar scope needed for OnDragMove()
OpRect rect = widget->GetRect(FALSE);
OpToolbar::OnDragMove(desktop_drag_object, OpPoint(rect.x + x, rect.y + y));
return;
}
else if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
OpRect rect = widget->GetRect(FALSE);
OpToolbar::OnDragMove(desktop_drag_object, OpPoint(rect.x + x, rect.y + y));
return;
}
OnDrag(widget, desktop_drag_object, pos, x, y);
}
void OpPagebar::OnDrag(OpWidget* widget, DesktopDragObject* drag_object, INT32 pos, INT32 x, INT32 y)
{
if (drag_object->GetType() == DRAG_TYPE_WINDOW ||
drag_object->GetType() == DRAG_TYPE_THUMBNAIL)
{
if (pos >= GetWidgetCount() && drag_object->GetID() != m_dragged_pagebar_button)
{
pos = GetWidgetCount() - 1;
}
INT32 id = GetWidget(pos) ? GetWidget(pos)->GetID() : 0;
DesktopWindowCollection& model = g_application->GetDesktopWindowCollection();
model.OnDragWindows(drag_object, model.GetItemByID(id));
}
else if (drag_object->GetType() == DRAG_TYPE_RESIZE_SEARCH_DROPDOWN)
{
drag_object->SetDesktopDropType(DROP_NONE);
}
else
{
drag_object->SetDesktopDropType(DROP_COPY);
}
}
void OpPagebar::OnDrop(OpWidget* widget, DesktopDragObject* drag_object, INT32 pos, INT32 x, INT32 y)
{
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
PagebarButton *button = static_cast<PagebarButton *>(widget);
button->CancelDelayedActivation();
}
// This fixes the jumping cursor problem when there is space between buttons
if (pos > GetWidgetCount() || pos == -1)
pos = GetWidgetPosition( x, y );
switch (drag_object->GetType())
{
case DRAG_TYPE_WINDOW: /* fallthrough */
case DRAG_TYPE_THUMBNAIL:
{
int widget_count = GetWidgetCount();
INT32 button_pos;
if (!widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) && !widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
button_pos= GetWidgetPosition(x, y );
else
button_pos = GetWidgetPos(widget);
if (button_pos >= widget_count)
button_pos = widget_count > 0 ? widget_count-1 : 0;
OpWidget *button_widget = GetWidget(button_pos);
PagebarButton* button = NULL;
DesktopWindowCollectionItem* button_item = NULL;
// Ungroup
for (INT32 i = drag_object->GetIDCount() - 1; i >= 0; i--)
{
if (drag_object->GetType() == DRAG_TYPE_WINDOW)
{
DesktopWindow* desktop_window = g_application->GetDesktopWindowCollection().GetDesktopWindowByID(drag_object->GetID(i));
DesktopWindowCollectionItem* item = g_application->GetDesktopWindowCollection().GetItemByID(drag_object->GetID(i));
DesktopWindowCollectionItem* item_parent_group = item ? item->GetParentItem() : NULL;
OpWidget *drag_widget = desktop_window ? desktop_window->GetWidgetByTypeAndId(OpTypedObject::WIDGET_TYPE_BUTTON, drag_object->GetID(i)) : NULL;
if (drag_widget && drag_widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
PagebarButton *button = static_cast<PagebarButton *>(drag_widget);
if (button && button->IsGrouped() && item_parent_group && item_parent_group->GetChildCount() <= 2)
{
g_application->GetDesktopWindowCollection().UnGroup(item_parent_group);
}
}
}
}
if (button_widget && button_widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
button = button_widget ? static_cast<PagebarButton*>(button_widget) : NULL;
if (button)
button_item = button->GetModelItem();
}
DesktopWindowCollection& model = g_application->GetDesktopWindowCollection();
INT32 id = button ? button->GetID() : 0;
if (id == 0)
{
id = button_widget ? button_widget->GetID() : 0;
button_item = model.GetItemByID(id);
}
model.OnDropWindows(drag_object, button_item);
break;
}
case DRAG_TYPE_BOOKMARK:
OnDropBookmark(widget, drag_object, pos, x, y);
break;
case DRAG_TYPE_CONTACT:
OnDropContact(widget, drag_object, pos, x, y);
break;
case DRAG_TYPE_HISTORY:
OnDropHistory(widget, drag_object, pos, x, y);
break;
default:
OnDropURL(widget, drag_object, pos, x, y);
break;
}
}
BOOL OpPagebar::OnDragOnButton(PagebarButton* button, DesktopDragObject* drag_object, INT32 x, INT32 y)
{
button->SetUseHoverStackOverlay(FALSE);
INT32 drop_area = IsHorizontal() ? button->GetDropArea(x, -1) : button->GetDropArea(-1, y);
if (!(drop_area & DROP_CENTER))
return TRUE;
if (drag_object->GetType() == DRAG_TYPE_WINDOW)
{
for (INT32 i = 0; i < drag_object->GetIDCount(); i++)
{
// don't allow the tab to be dropped on itself
if (button->GetDesktopWindow()->GetID() == drag_object->GetID(i))
{
// But activate tab. We can still drop in on a text field etc to use the address.
if (!button->HasScheduledDelayedActivation())
button->DelayedActivation(TAB_DELAYED_ACTIVATION_TIME);
return FALSE;
}
}
}
// Activate page that is associated with the tab
if (!button->HasScheduledDelayedActivation())
button->DelayedActivation(TAB_DELAYED_ACTIVATION_TIME);
button->SetUseHoverStackOverlay(TRUE);
return TRUE;
}
void OpPagebar::OnDropBookmark(OpWidget* widget, DesktopDragObject* drag_object, INT32 pos, INT32 x, INT32 y)
{
if (!drag_object->GetIDCount())
return;
DesktopWindow* parent_window = GetParentDesktopWindow();
if (parent_window)
parent_window->Activate();
// We can not use the provided position if opening within a group. Recalculate position
bool closed_group = false;
pos = CalculateDropPosition(x, y, closed_group);
INT32 window_pos = 0;
DesktopWindowCollectionItem* parent = GetDropWindowPosition(pos, window_pos, closed_group);
DesktopWindow* target_window = GetTargetWindow(pos, x, y);
BOOL3 new_page = target_window ? MAYBE : YES;
g_hotlist_manager->OpenUrls(drag_object->GetIDs(), NO, new_page, MAYBE, target_window, window_pos, parent);
}
void OpPagebar::OnDropContact(OpWidget* widget, DesktopDragObject* drag_object, INT32 pos, INT32 x, INT32 y)
{
if (!drag_object->GetIDCount())
return;
DesktopWindow* parent = GetParentDesktopWindow();
if (parent)
parent->Activate();
DesktopWindow* target_window = GetTargetWindow(pos, x, y);
BOOL3 new_page = target_window ? MAYBE : YES;
INT32 window_pos = 0;
GetDropWindowPosition(pos, window_pos, TRUE);
g_hotlist_manager->OpenContacts(drag_object->GetIDs(), NO, new_page, MAYBE, target_window, window_pos);
}
void OpPagebar::OnDropHistory(OpWidget* widget, DesktopDragObject* drag_object, INT32 pos, INT32 x, INT32 y)
{
DesktopWindow* parent_window = GetParentDesktopWindow();
if (parent_window)
parent_window->Activate();
// We can not use the provided position if opening within a group. Recalculate position
bool closed_group = false;
pos = CalculateDropPosition(x, y, closed_group);
INT32 window_pos = 0;
DesktopWindowCollectionItem* parent = GetDropWindowPosition(pos, window_pos, closed_group);
DesktopWindow* target_window = GetTargetWindow(pos, x, y);
DesktopHistoryModel* history_model = DesktopHistoryModel::GetInstance();
for (INT32 i = 0; i < drag_object->GetIDCount(); i++)
{
HistoryModelItem* history_item = history_model->FindItem(drag_object->GetID(i));
if (history_item)
{
OpString address;
RETURN_VOID_IF_ERROR(history_item->GetAddress(address));
OpenURL(address, target_window, parent, window_pos);
// Let link 2,3... open in new tabs to the right
target_window = NULL;
window_pos ++;
}
}
}
void OpPagebar::OnDropURL(OpWidget* widget, DesktopDragObject* drag_object, INT32 pos, INT32 x, INT32 y)
{
DesktopWindow* parent_window = GetParentDesktopWindow();
if (parent_window)
parent_window->Activate();
// We can not use the provided position if opening within a group. Recalculate position
bool closed_group = false;
pos = CalculateDropPosition(x, y, closed_group);
INT32 window_pos = 0;
DesktopWindowCollectionItem* parent = GetDropWindowPosition(pos, window_pos, closed_group);
DesktopWindow* target_window = GetTargetWindow(pos, x, y);
if( drag_object->GetURLs().GetCount() > 0 )
{
for( UINT32 i=0; i<drag_object->GetURLs().GetCount(); i++ )
{
OpenURL(*drag_object->GetURLs().Get(i), target_window, parent, window_pos);
// Let link 2,3... open in new tabs to the right
target_window = NULL;
window_pos ++;
}
}
else if (drag_object->GetURL())
{
PagebarButton* drop_button = FindDropButton();
if (drop_button)
target_window = drop_button->GetDesktopWindow();
OpenURL(drag_object->GetURL(), target_window, parent, window_pos);
}
else
{
OpDragDataIterator& iter = drag_object->GetDataIterator();
if (iter.First())
{
do
{
if (iter.IsFileData())
{
const OpFile* file = iter.GetFileData();
if (file)
{
OpString url_string;
if (OpStatus::IsSuccess(ConvertFullPathtoURL(url_string, file->GetFullPath())))
OpenURL(url_string, target_window, parent, window_pos);
}
}
} while (iter.Next());
}
}
}
void OpPagebar::OpenURL(const OpStringC& url, DesktopWindow* target_window, DesktopWindowCollectionItem* parent, INT32 pos)
{
OpenURLSetting setting;
RETURN_VOID_IF_ERROR(setting.m_address.Set(url));
setting.m_new_window = NO;
setting.m_new_page = target_window ? MAYBE : YES;
setting.m_in_background = g_pcui->GetIntegerPref(PrefsCollectionUI::OpenDraggedLinkInBackground) ? YES : MAYBE;
setting.m_target_window = target_window;
setting.m_target_position = pos;
setting.m_target_parent = parent;
g_application->OpenURL( setting );
}
int OpPagebar::CalculateDropPosition(int x, int y, bool& closed_group)
{
closed_group = false;
int position = GetWidgetPosition(x, y);
OpWidget* widget = GetWidget(position);
if (widget)
{
OpRect rect = widget->GetRect(FALSE);
int wx = x - rect.x;
int wy = y - rect.y;
if (IsHorizontal())
wx = MAX(wx, 0);
else
wy = MAX(wy, 0);
PagebarDropLocation loc = CalculatePagebarDropLocation(widget, wx, wy);
if (IsInGroup(position))
{
closed_group = !IsInExpandedGroup(position);
if (loc == NEXT)
position = FindLastGroupTab(position);
else if (loc == PREVIOUS)
position = FindFirstGroupTab(position);
}
else
{
closed_group = true;
if (loc == NEXT)
position ++;
}
}
return position;
}
DesktopWindowCollectionItem* OpPagebar::GetDropWindowPosition(INT32 pos, INT32& window_pos, BOOL ignore_groups)
{
if (pos < 0 || pos >= GetWidgetCount())
{
window_pos = pos < 0 ? 0 : m_workspace->GetModelItem()->GetChildCount();
return m_workspace->GetModelItem();
}
// If the position refers to the last (rightmost) button in a group of
// tabs then that is the expand/collapse button. In order to iterate over
// the tabs in the group we have to step back to the last tab in this group
// and start from there.
int offset = 0;
if (pos > 0)
{
OpWidget* widget = GetWidget(pos);
if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
offset = 1;
}
DesktopWindowCollectionItem* item = g_application->GetDesktopWindowCollection().GetItemByID(GetWidget(pos-offset)->GetID());
if (!item)
return NULL;
if (ignore_groups)
{
// go up to the workspace level, ignoring all groups in between
while (item->GetParentItem() && item->GetParentItem()->GetType() != WINDOW_TYPE_BROWSER)
item = item->GetParentItem();
}
// Get the position by counting all items in the tree at the same level before this one
for (window_pos = offset; item->GetPreviousItem(); window_pos++)
item = item->GetPreviousItem();
return item->GetParentItem();
}
DesktopWindow* OpPagebar::GetTargetWindow(INT32 pos, INT32 x, INT32 y)
{
if (pos >= GetWidgetCount())
return NULL;
OpButton* button = static_cast<OpButton*>(GetWidget(pos));
if (button)
{
OpRect rect = button->GetRect(FALSE);
int wx = x - rect.x;
int wy = y - rect.y;
if (IsHorizontal())
wx = MAX(wx, 0);
else
wy = MAX(wy, 0);
INT32 drop_area = IsHorizontal() ? button->GetDropArea(wx, -1) : button->GetDropArea(-1, wy);
if (drop_area & DROP_CENTER)
return static_cast<DesktopWindow*>(button->GetUserData());
}
return NULL;
}
void OpPagebar::OnNewDesktopGroup(OpWorkspace* workspace, DesktopGroupModelItem& group)
{
DesktopWindowCollectionItem* first = group.GetChildItem();
DesktopWindowCollectionItem* last = group.GetLastChildItem();
if (first && last)
{
INT32 main_pos = FindPagebarButton(first->GetDesktopWindow(), 0);
PagebarButton* main_button = static_cast<PagebarButton*>(GetWidget(main_pos));
INT32 second_pos = FindPagebarButton(last->GetDesktopWindow(), 0);
PagebarButton* second_button = static_cast<PagebarButton*>(GetWidget(second_pos));
if (!main_button || !second_button)
return;
INT32 group_no = group.GetID();
for (DesktopWindowCollectionItem* child = group.GetChildItem(); child; child = child->GetSiblingItem())
{
PagebarButton* btn = child->GetDesktopWindow() ? child->GetDesktopWindow()->GetPagebarButton() : NULL;
if (btn)
btn->SetGroupNumber(group_no);
}
SetGroupCollapsed(group_no, group.IsCollapsed());
AddTabGroupButton(MAX(main_pos, second_pos) + 1, group);
}
OpStatus::Ignore(group.AddListener(this));
}
void OpPagebar::OnDragMoveOfPreviouslyDraggedPagebarButton(OpWidget* widget, OpDragObject* op_drag_object, INT32 pos, INT32 x, INT32 y)
{
// drop == FALSE
DesktopDragObject* drag_object = static_cast<DesktopDragObject*>(op_drag_object);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
// If OnDragOnButton says we can't drop, don't go any further
if (!OnDragOnButton(static_cast<PagebarButton*>(widget), drag_object, x, y))
{
drag_object->SetDesktopDropType(DROP_NOT_AVAILABLE);
return;
}
}
pos = m_widgets.Find(widget);
if (pos == KNotFound)
{
// It may be between buttons or after the last
int widget_count = m_widgets.GetCount();
pos = GetWidgetPosition(x + widget->GetRect().x, y + widget->GetRect().y);
if (pos >= widget_count)
pos = widget_count > 0 ? widget_count-1 : 0;
widget = GetWidget(pos);
if (!widget)
return;
}
PagebarDropLocation drop_location = CalculatePagebarDropLocation(widget, x, y);
if (drop_location == PREVIOUS)
drag_object->SetInsertType(DesktopDragObject::INSERT_BEFORE);
else if (drop_location == NEXT)
drag_object->SetInsertType(DesktopDragObject::INSERT_AFTER);
bool show_drop_marker = true;
if (pos != -1 && pos < GetWidgetCount())
{
OpWidget* widget = GetWidget(pos);
if (widget)
{
int drop_area = IsHorizontal() ? widget->GetDropArea(x,-1) : widget->GetDropArea(-1,y);
if (drop_area & DROP_CENTER)
show_drop_marker = false;
else if (drop_area & (DROP_RIGHT|DROP_BOTTOM))
IncDropPosition(pos, true);
}
}
OnDrag(widget, drag_object, pos, x, y);
int src_pos = GetDragSourcePos(drag_object);
bool noDrop = (pos == src_pos);
if (drop_location != STACK)
noDrop |= (pos == src_pos+1);
if (noDrop)
{
drag_object->SetDesktopDropType(DROP_NONE);
show_drop_marker = false;
}
else
{
drag_object->SetDesktopDropType(DROP_MOVE);
}
UpdateDropPosition(show_drop_marker ? pos : -1);
}
void OpPagebar::OnDragDropOfPreviouslyDraggedPagebarButton(OpWidget* widget, OpDragObject* op_drag_object, INT32 pos, INT32 x, INT32 y)
{
if (!widget)
return;
// drop == TRUE
DesktopDragObject* drag_object = static_cast<DesktopDragObject*>(op_drag_object);
int widget_count = m_widgets.GetCount();
pos = GetWidgetPosition(x + widget->GetRect().x, y + widget->GetRect().y);
if (pos >= widget_count)
pos = widget_count > 0 ? widget_count-1 : 0;
PagebarDropLocation drop_location = CalculatePagebarDropLocation(widget, x, y);
if (drop_location == PREVIOUS)
drag_object->SetInsertType(DesktopDragObject::INSERT_BEFORE);
else if (drop_location == NEXT)
drag_object->SetInsertType(DesktopDragObject::INSERT_AFTER);
bool drop_center = false;
if (pos != -1 && pos < GetWidgetCount())
{
OpWidget* widget = GetWidget(pos);
if (widget)
{
int drop_area = IsHorizontal() ? widget->GetDropArea(x,-1) : widget->GetDropArea(-1,y);
if (drop_area & DROP_CENTER)
{
drop_center = true;
}
else if (drop_area & (DROP_RIGHT|DROP_BOTTOM))
IncDropPosition(pos, true);
}
}
// The position is the marker position. So pos = 1 is left with the second
// button etc. Modify settings so that behavior matches with other kind of drops
if (pos >= GetWidgetCount())
{
// Allows drop after all buttons on the bar
pos = GetWidgetCount() - 1;
drag_object->SetInsertType(DesktopDragObject::INSERT_AFTER);
}
else if (drop_location == NEXT)
{
if (IsInGroup(pos) && !IsInExpandedGroup(pos) && drop_center)
{
drag_object->SetInsertType(DesktopDragObject::INSERT_INTO);
}
else
{
drag_object->SetInsertType(DesktopDragObject::INSERT_AFTER);
}
}
else
{
if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
// Allows drop inside a group when dropped on an expander button
drag_object->SetInsertType(DesktopDragObject::INSERT_AFTER);
}
else if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) && drop_center)
{
// Allow dropping into a tab that's either not in a group, or in a non-expanded group
if (!IsInGroup(pos) || (IsInGroup(pos) && !IsInExpandedGroup(pos)))
drag_object->SetInsertType(DesktopDragObject::INSERT_INTO);
}
}
OnDrop(widget, drag_object, pos, x, y);
RemoveAnyHighlightOnTargetButton();
// This removes drop position indicator from the pagebar.
OpToolbar::OnDragLeave(drag_object);
}
bool OpPagebar::IsDropAvailable(DesktopDragObject* drag_object, int x, int y)
{
if (drag_object->GetType() != DRAG_TYPE_WINDOW && drag_object->GetType() != DRAG_TYPE_THUMBNAIL)
return OpToolbar::IsDropAvailable(drag_object, x, y);
if (drag_object->GetID() != m_dragged_pagebar_button)
return OpToolbar::IsDropAvailable(drag_object, x, y);
int src_pos = GetDragSourcePos(drag_object);
if (src_pos <= -1)
return OpToolbar::IsDropAvailable(drag_object, x, y);
int widget_count = m_widgets.GetCount();
if (widget_count == 0)
return OpToolbar::IsDropAvailable(drag_object, x, y);
INT32 target_pos = GetWidgetPosition(x, y);
if (target_pos >= widget_count)
{
// After/below all tabs. Allow if source is not the last tab
return src_pos + 1 >= widget_count ? false : true;
}
else
{
OpWidget* widget = GetWidget(target_pos);
if (!widget)
return OpToolbar::IsDropAvailable(drag_object, x, y);
OpRect rect = widget->GetRect(FALSE);
int wx = x - rect.x;
int wy = y - rect.y;
if (IsHorizontal())
wx = MAX(wx, 0);
else
wy = MAX(wy, 0);
PagebarDropLocation drop_location = CalculatePagebarDropLocation(widget, wx, wy);
int marker_position = target_pos;
if (drop_location == NEXT)
marker_position ++;
else if (drop_location == STACK)
marker_position = -1;
if (marker_position == src_pos || marker_position == (src_pos+1))
marker_position = -1;
return marker_position != -1;
}
}
void OpPagebar::UpdateDropAction(DesktopDragObject* drag_object, bool accepted)
{
if (drag_object->GetType() == DRAG_TYPE_WINDOW)
drag_object->SetDropType(accepted ? DROP_MOVE : DROP_NONE);
else
drag_object->SetDropType(accepted ? DROP_COPY : DROP_NONE);
}
OpPagebar::PagebarDropLocation OpPagebar::CalculatePagebarDropLocation(OpWidget* widget, INT32 x, INT32 y)
{
INT32 drop_area = IsHorizontal() ? widget->GetDropArea(x,-1) : widget->GetDropArea(-1,y);
if (drop_area & (DROP_LEFT | DROP_TOP))
return PREVIOUS;
if (drop_area & DROP_CENTER)
return STACK;
if (drop_area & (DROP_RIGHT | DROP_BOTTOM))
return NEXT;
return PREVIOUS;
}
void OpPagebar::RemoveAnyHighlightOnTargetButton()
{
PagebarButton* target_button = FindDropButton();
if (target_button)
target_button->SetUseHoverStackOverlay(FALSE);
}
void OpPagebar::OnDragLeave(OpWidget* widget, OpDragObject* drag_object)
{
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
PagebarButton *button = static_cast<PagebarButton *>(widget);
button->CancelDelayedActivation();
button->SetUseHoverStackOverlay(FALSE);
}
OpToolbar::OnDragLeave(widget, (DesktopDragObject*)drag_object);
}
void OpPagebar::OnDragCancel(OpWidget* widget, OpDragObject* drag_object)
{
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
PagebarButton *button = static_cast<PagebarButton *>(widget);
button->CancelDelayedActivation();
button->SetUseHoverStackOverlay(FALSE);
}
OpToolbar::OnDragCancel(widget, (DesktopDragObject*)drag_object);
}
/***********************************************************************************
**
** Group Functions
**
***********************************************************************************/
void OpPagebar::HideGroupOpTabGroupButton(PagebarButton* button, BOOL hide)
{
for (INT32 pos = GetWidgetPos(button) + 1; pos < GetWidgetCount(); pos++)
{
if (!GetWidget(pos)->IsOfType(WIDGET_TYPE_PAGEBAR_ITEM))
continue;
OpPagebarItem* item = static_cast<OpPagebarItem*>(GetWidget(pos));
if (item->GetGroupNumber() != button->GetGroupNumber())
return;
if (item->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
if (item->IsHidden() == hide)
Relayout();
item->SetHidden(hide);
return;
}
}
}
BOOL OpPagebar::IsGroupExpanded(UINT32 group_number, PagebarButton* exclude)
{
// return TRUE if there is no group number since it should
// behave like and expanded group
if (!group_number)
return TRUE;
INT32 count = GetWidgetCount();
for(INT32 pos = 0; pos < count; pos++)
{
OpWidget* widget = GetWidget(pos);
if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
OpTabGroupButton* button = static_cast<OpTabGroupButton*>(widget);
if (button->GetGroupNumber() == group_number)
return !button->GetValue(); // value == 1 <==> collapsed
}
}
return TRUE;
}
void OpPagebar::SetGroupCollapsed(UINT32 group_number, BOOL collapsed)
{
if (!group_number)
return;
for (int i = 0; i < GetWidgetCount(); i++)
{
OpWidget* widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) &&
static_cast<PagebarButton*>(widget)->GetGroupNumber() == group_number)
{
PagebarButton* button = static_cast<PagebarButton*>(widget);
button->SetHidden(collapsed && !button->IsActiveTabForGroup());
}
}
}
BOOL OpPagebar::IsGroupCollapsing(UINT32 group_number)
{
if (IsGroupExpanded(group_number, NULL))
{
INT32 i, count = GetWidgetCount();
for (i = 0; i < count; i++)
{
OpWidget *widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
OpTabGroupButton* button = static_cast<OpTabGroupButton*>(widget);
if (button->GetValue() && group_number == button->GetGroupNumber())
return TRUE;
}
}
}
return FALSE;
}
void OpPagebar::AddTabGroupButton(INT32 pos, DesktopGroupModelItem& group)
{
OpTabGroupButton* group_button;
RETURN_VOID_IF_ERROR(OpTabGroupButton::Construct(&group_button, group));
group_button->SetName(WIDGET_NAME_TABGROUP_BUTTON);
AddButton(group_button, NULL, NULL, NULL, NULL, pos);
}
void OpPagebar::SetOriginalGroupNumber(UINT32 group_number)
{
for (INT32 i = 0; i < GetWidgetCount(); i++)
{
if (GetWidget(i)->GetType() != WIDGET_TYPE_PAGEBAR_BUTTON)
continue;
PagebarButton* btn = static_cast<PagebarButton*>(GetWidget(i));
if (btn->GetGroupNumber() == group_number)
btn->SetOriginalGroupNumber(group_number);
}
}
void OpPagebar::ResetOriginalGroupNumber()
{
for (INT32 i = 0; i < GetWidgetCount(); i++)
{
if (GetWidget(i)->GetType() == WIDGET_TYPE_PAGEBAR_BUTTON)
static_cast<PagebarButton*>(GetWidget(i))->SetOriginalGroupNumber(-1);
}
}
void OpPagebar::AnimateAllWidgetsToNewRect(INT32 ignore_pos)
{
if (!g_animation_manager->GetEnabled())
return;
AnimateWidgets(0, GetWidgetCount() - 1, ignore_pos, TAB_GROUP_ANIMATION_DURATION);
// Layout of the floating bar is not done by the OpToolbar layout so we have to create a animation for it explicitly.
QuickAnimationParams params(m_floating_bar);
params.duration = TAB_GROUP_ANIMATION_DURATION / 1000.0;
params.curve = ANIM_CURVE_SLOW_DOWN;
params.move_type = ANIM_MOVE_RECT_TO_ORIGINAL;
g_animation_manager->startAnimation(params);
}
/***********************************************************************************
**
** OnContextMenu
**
***********************************************************************************/
BOOL OpPagebar::OnContextMenu(OpWidget* widget, INT32 child_index, const OpPoint& menu_point, const OpRect* avoid_rect, BOOL keyboard_invoked)
{
if (widget != this)
{
// try to find button clicked
child_index = FindWidget(widget, TRUE);
if (child_index == -1)
return FALSE;
}
DesktopWindow* window = child_index == -1 ? 0 : (DesktopWindow*) GetUserData(child_index);
const PopupPlacement at_cursor = PopupPlacement::AnchorAtCursor();
if(widget && widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) && static_cast<PagebarButton *>(widget)->IsGrouped())
{
g_application->GetMenuHandler()->ShowPopupMenu("Pagebar Item Group Popup Menu", at_cursor, 0, keyboard_invoked);
}
else if (window && m_workspace && m_workspace->GetActiveDesktopWindow() == window)
{
g_application->GetMenuHandler()->ShowPopupMenu("Pagebar Item Popup Menu", at_cursor, 0, keyboard_invoked);
}
else if( window )
{
g_application->GetMenuHandler()->ShowPopupMenu("Pagebar Inactive Item Popup Menu", at_cursor, 0, keyboard_invoked);
}
else
{
g_application->GetMenuHandler()->ShowPopupMenu("Pagebar Popup Menu", at_cursor, 0, keyboard_invoked);
}
return TRUE;
}
/***********************************************************************************
**
** CreateButton
**
***********************************************************************************/
OP_STATUS OpPagebar::CreatePagebarButton(PagebarButton*& button, DesktopWindow* desktop_window)
{
return PagebarButton::Construct(&button, desktop_window);
}
/***********************************************************************************
**
** SetupButton
**
***********************************************************************************/
void OpPagebar::SetupButton(PagebarButton* button)
{
button->SetRestrictImageSize(TRUE);
button->UpdateTextAndIcon(true, true, false);
}
/***********************************************************************************
**
** OnDesktopWindowAdded
**
***********************************************************************************/
void OpPagebar::OnDesktopWindowAdded(OpWorkspace* workspace, DesktopWindow* desktop_window)
{
INT32 widget_pos = GetWindowPos(desktop_window);
PagebarButton* button;
RETURN_VOID_IF_ERROR(CreatePagebarButton(button, desktop_window));
OpInputAction* button_action = OP_NEW(OpInputAction, (OpInputAction::ACTION_ACTIVATE_WINDOW));
if (!button_action)
return;
button_action->SetActionData(desktop_window->GetID());
AddButton(button, desktop_window->GetTitle(), NULL, button_action, desktop_window, widget_pos);
SetupButton(button);
// move our button to the end again
INT32 orgpos = FindWidget(m_floating_bar);
if(orgpos != -1)
{
MoveWidget(orgpos, GetWidgetCount());
}
DesktopWindowCollectionItem& item = desktop_window->GetModelItem();
if (!item.GetParentItem())
{
OP_ASSERT(!"Desktop window item does not have a parent");
return;
}
else
{
if (item.GetParentItem()->GetType() == OpTypedObject::WINDOW_TYPE_GROUP )
{
DesktopGroupModelItem* group = static_cast<DesktopGroupModelItem*>(item.GetParentItem());
if (group)
{
INT32 button_index = FindTabGroupButton(group->GetID(), 0);
if (button_index < 0)
AddTabGroupButton(widget_pos + 1, *group);
}
}
// Restore group order, since newly added window might be grouped
RestoreOrder(workspace->GetModelItem(), 0, 0);
}
}
INT32 OpPagebar::GetWindowPos(DesktopWindow* desktop_window)
{
DesktopWindowCollectionItem* after = desktop_window->GetModelItem().GetPreviousItem();
if (!after)
return 0;
for (INT32 pos = 0; pos < GetWidgetCount(); pos++)
{
if (GetWidget(pos)->GetID() == after->GetID())
return pos + 1;
}
OP_ASSERT(!"Can't find previous item, should not be possible");
return -1;
}
/***********************************************************************************
**
** OnDesktopWindowRemoved
**
***********************************************************************************/
void OpPagebar::OnDesktopWindowRemoved(OpWorkspace* workspace, DesktopWindow* desktop_window)
{
INT32 widget_id = FindWidgetByUserData(desktop_window);
if (widget_id < 0)
return;
// RemoveWidget delays the deletion of the PagebarButton,
// so make sure that the PagebarButton doesn't get a timed tooltip query before it's
// really deleted, as this will cause it to access the deleted DesktopWindow
OpWidget *widget = GetWidget(widget_id);
if (widget == g_application->GetToolTipListener())
g_application->SetToolTipListener(NULL);
RemoveWidget(widget_id);
}
/***********************************************************************************
**
** OnDesktopWindowOrderChanged
**
***********************************************************************************/
void OpPagebar::OnDesktopWindowOrderChanged(OpWorkspace* workspace)
{
DesktopWindowCollectionItem* parent = workspace->GetModelItem();
if (!parent)
return;
// Order all widgets in this pagebar to represent the children of the workspace
INT32 widget_pos = RestoreOrder(parent, 0, 0);
// All widgets before widget_pos now represent the correct widgets for this
// workspace. Remove the rest, they were no longer in this workspace
for (INT32 i = GetWidgetCount() - 1; i >= widget_pos; i--)
RemoveWidget(i);
}
INT32 OpPagebar::RestoreOrder(DesktopWindowCollectionItem* item, UINT32 group_id, INT32 widget_pos)
{
if (item->GetDesktopWindow() && !item->GetDesktopWindow()->VisibleInWindowList())
return widget_pos;
for (DesktopWindowCollectionItem* child = item->GetChildItem(); child; child = child->GetSiblingItem())
{
INT32 child_group_id = item->GetType() == WINDOW_TYPE_GROUP && !group_id ? item->GetID() : group_id;
widget_pos = RestoreOrder(child, child_group_id, widget_pos);
}
OpWidget* widget = GetWidget(widget_pos);
if (!widget)
return widget_pos;
switch (item->GetType())
{
case WINDOW_TYPE_BROWSER:
return widget_pos;
case WINDOW_TYPE_GROUP:
if (!widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON) ||
static_cast<OpTabGroupButton*>(widget)->GetGroupNumber() != (UINT32)item->GetID())
{
INT32 button_pos = FindTabGroupButton(item->GetID(), widget_pos);
OpTabGroupButton* button = static_cast<OpTabGroupButton*>(GetWidget(button_pos));
if (!button)
return widget_pos;
MoveWidget(button_pos, widget_pos);
}
return widget_pos + 1;
default:
PagebarButton* button = static_cast<PagebarButton*>(widget);
if (!widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) ||
button->GetGroupNumber() != group_id ||
button->GetDesktopWindow() != item->GetDesktopWindow() ||
button->IsHidden() != (button->GetGroup() && button->GetGroup()->IsCollapsed() && !button->IsActiveTabForGroup()))
{
INT32 button_pos = FindPagebarButton(item->GetDesktopWindow(), widget_pos);
button = static_cast<PagebarButton*>(GetWidget(button_pos));
if (!button)
return widget_pos;
MoveWidget(button_pos, widget_pos);
button->SetGroupNumber(group_id);
button->SetHidden(button->GetGroup() && button->GetGroup()->IsCollapsed() && !button->IsActiveTabForGroup());
}
return widget_pos + 1;
}
}
INT32 OpPagebar::FindPagebarButton(DesktopWindow* window, INT32 start_pos)
{
for (INT32 i = start_pos; i < GetWidgetCount(); i++)
{
OpWidget* widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) &&
static_cast<PagebarButton*>(widget)->GetDesktopWindow() == window)
return i;
}
return -1;
}
INT32 OpPagebar::FindTabGroupButton(INT32 group_no, INT32 start_pos)
{
for (INT32 i = start_pos; i < GetWidgetCount(); i++)
{
OpWidget* widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON) &&
static_cast<OpTabGroupButton*>(widget)->GetGroupNumber() == (UINT32)group_no)
return i;
}
return -1;
}
OpTabGroupButton* OpPagebar::FindTabGroupButtonByGroupNumber(INT32 group_no)
{
INT32 index = FindTabGroupButton(group_no, 0);
return index < 0 ? NULL : static_cast<OpTabGroupButton*>(GetWidget(index));
}
/***********************************************************************************
**
** OnDesktopWindowActivated
**
***********************************************************************************/
void OpPagebar::OnDesktopWindowActivated(OpWorkspace* workspace, DesktopWindow* desktop_window, BOOL activate)
{
INT32 pos = FindWidgetByUserData(desktop_window);
if (pos < 0)
return;
if (activate)
{
OpToolbar::SetSelected(pos, FALSE);
}
else if (pos == GetSelected())
{
OpToolbar::SetSelected(-1, FALSE);
}
}
/***********************************************************************************
**
** OnDesktopWindowChanged
**
***********************************************************************************/
void OpPagebar::OnDesktopWindowChanged(OpWorkspace* workspace, DesktopWindow* desktop_window)
{
INT32 pos = FindWidgetByUserData(desktop_window);
if (pos < 0)
return;
OpWidget* widget = GetWidget(pos);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
desktop_window->UpdateUseFixedImage();
static_cast<PagebarButton *>(widget)->UpdateTextAndIcon(true, true, true);
}
else
OP_ASSERT(FALSE); // does this ever happen?
}
/***********************************************************************************
**
** OnDesktopGroupCreated
**
***********************************************************************************/
void OpPagebar::OnDesktopGroupCreated(OpWorkspace* workspace, DesktopGroupModelItem& group)
{
OnNewDesktopGroup(workspace, group);
}
void OpPagebar::OnDesktopGroupAdded(OpWorkspace* workspace, DesktopGroupModelItem& group)
{
OnNewDesktopGroup(workspace, group);
}
void OpPagebar::OnDesktopGroupRemoved(OpWorkspace* workspace, DesktopGroupModelItem& group)
{
group.RemoveListener(this);
}
/***********************************************************************************
**
** OnWorkspaceDeleted
**
***********************************************************************************/
void OpPagebar::OnWorkspaceDeleted(OpWorkspace* workspace)
{
m_workspace = NULL;
}
/***********************************************************************************
**
** GetFocusedButton
**
***********************************************************************************/
PagebarButton* OpPagebar::GetFocusedButton()
{
if (GetFocused() == -1)
return NULL;
OpWidget *focused = GetWidget(GetFocused());
if (!focused->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
return NULL;
PagebarButton *button = static_cast<PagebarButton *>(focused);
if(button->GetType() != WIDGET_TYPE_BUTTON)
return NULL;
return button;
}
/***********************************************************************************
**
** OnInputAction
**
***********************************************************************************/
BOOL OpPagebar::OnInputAction(OpInputAction* action)
{
// Fix for bug 329748
if(action->GetAction() == OpInputAction::ACTION_SET_BUTTON_STYLE)
{
if((OpButton::ButtonStyle)action->GetActionData() == OpButton::STYLE_IMAGE_AND_TEXT_ON_RIGHT && g_skin_manager->GetOptionValue("PageCloseButtonOnLeft", 0))
{
action->SetActionData((INTPTR)OpButton::STYLE_IMAGE_AND_TEXT_ON_LEFT);
}
}
if (OpToolbar::OnInputAction(action))
return TRUE;
PagebarButton *button = GetFocusedButton();
if(!button)
return FALSE;
switch(action->GetAction())
{
case OpInputAction::ACTION_GET_ACTION_STATE:
{
OpInputAction* child_action = action->GetChildAction();
BOOL is_locked = button->IsLockedByUser();
switch (child_action->GetAction())
{
case OpInputAction::ACTION_LOCK_PAGE:
{
if (button->GetDesktopWindow()->GetWindowCommander() &&
button->GetDesktopWindow()->GetWindowCommander()->GetGadget())
{
child_action->SetSelected(FALSE);
child_action->SetEnabled(FALSE);
return TRUE;
}
child_action->SetSelected(is_locked);
return TRUE;
}
case OpInputAction::ACTION_UNLOCK_PAGE:
{
if (button->GetDesktopWindow()->GetWindowCommander() &&
button->GetDesktopWindow()->GetWindowCommander()->GetGadget())
{
child_action->SetSelected(FALSE);
child_action->SetEnabled(FALSE);
return TRUE;
}
child_action->SetSelected(!is_locked);
return TRUE;
}
case OpInputAction::ACTION_SHOW_POPUP_MENU:
{
if(child_action->GetActionDataString() && !uni_strcmp(child_action->GetActionDataString(), UNI_L("Browser Button Menu Bar")))
{
child_action->SetEnabled(TRUE);
BOOL show_menu = g_pcui->GetIntegerPref(PrefsCollectionUI::ShowMenu);
if(show_menu)
{
EnsureMenuButton(FALSE);
}
return TRUE;
}
// we don't handle other menus
return FALSE;
}
case OpInputAction::ACTION_RESTORE_TO_DEFAULTS:
{
child_action->SetEnabled(TRUE);
return TRUE;
}
}
break;
}
case OpInputAction::ACTION_UNLOCK_PAGE:
case OpInputAction::ACTION_LOCK_PAGE:
{
DesktopWindow* tab = button->GetDesktopWindow();
if (tab)
{
tab->SetLockedByUser(!button->IsLockedByUser());
if(button->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
tab->UpdateUserLockOnPagebar();
}
else
{
button->Relayout(TRUE, TRUE);
}
g_input_manager->UpdateAllInputStates();
return TRUE;
}
break;
}
case OpInputAction::ACTION_RESTORE_TO_DEFAULTS:
{
if(m_head_bar)
{
m_head_bar->RestoreToDefaults();
}
if(m_tail_bar)
{
m_tail_bar->RestoreToDefaults();
}
if(m_floating_bar)
{
m_floating_bar->RestoreToDefaults();
}
RestoreToDefaults();
return TRUE;
}
case OpInputAction::ACTION_DISSOLVE_TAB_GROUP:
{
if (button->IsGrouped())
{
g_application->GetDesktopWindowCollection().UnGroup(button->GetGroup());
Relayout();
}
return TRUE;
}
case OpInputAction::ACTION_CLOSE_TAB_GROUP:
{
if (button->IsGrouped())
{
g_application->GetDesktopWindowCollection().DestroyGroup(button->GetGroup());
Relayout();
}
return TRUE;
}
}
if (!m_is_handling_action)
{
m_is_handling_action = TRUE;
BOOL handled = button->WindowOnInputAction(action);
m_is_handling_action = FALSE;
return handled;
}
return FALSE;
}
/***********************************************************************************
**
** OnReadStyle
**
***********************************************************************************/
void OpPagebar::OnReadStyle(PrefsSection *section)
{
OpToolbar::OnReadStyle(section);
m_default_button_style = GetButtonStyle();
if(!section->FindEntry(UNI_L("Button style")) && g_skin_manager->GetOptionValue("PageCloseButtonOnLeft", 0))
{
SetButtonStyle(OpButton::STYLE_IMAGE_AND_TEXT_ON_LEFT);
}
}
/***********************************************************************************
**
** OnWriteStyle
**
***********************************************************************************/
void OpPagebar::OnWriteStyle(PrefsFile* prefs_file, const char* name)
{
OpToolbar::OnWriteStyle(prefs_file, name);
m_default_button_style = GetButtonStyle();
}
/***********************************************************************************
**
** EnsureMenuButton - Ensure that the menu button is available in the head toolbar
**
***********************************************************************************/
OP_STATUS OpPagebar::EnsureMenuButton(BOOL show)
{
BOOL found = FALSE;
// This button should never ever show on Mac See DSK-258242
#ifdef _MACINTOSH_
show = FALSE;
#else
if (!m_allow_menu_button)
show = FALSE;
#endif
OpWidget* child = (OpWidget*) m_head_bar->childs.First();
while(child)
{
if(child->GetType() == WIDGET_TYPE_TOOLBAR_MENU_BUTTON)
{
found = TRUE;
if(!show)
{
m_head_bar->RemoveWidget(m_head_bar->FindWidget(child));
}
break;
}
child = (OpWidget*) child->Suc();
}
if(found && child && show)
{
BOOL needs_visibility = m_head_bar->GetWidgetCount() < 1; // assumes the menu button is the only button on the toolbar by default, change to 2 if the panel button returns there
if(needs_visibility)
{
SetHeadAlignmentFromPagebar(GetResultingAlignment(), TRUE);
}
if(!child->IsVisible())
{
child->SetVisibility(TRUE);
}
}
else if(!found)
{
if(show)
{
OpToolbarMenuButton *button;
RETURN_IF_ERROR(OpToolbarMenuButton::Construct(&button));
BOOL needs_visibility = m_head_bar->GetWidgetCount() == 0;
m_head_bar->AddWidget(button, 0);
if(needs_visibility)
{
SetHeadAlignmentFromPagebar(GetResultingAlignment(), TRUE);
}
m_head_bar->WriteContent();
}
}
return OpStatus::OK;
}
/***********************************************************************************
**
** ShowMenuButtonMenu - Show the menu attached to the menu button at the right position
**
***********************************************************************************/
void OpPagebar::ShowMenuButtonMenu()
{
#ifdef QUICK_NEW_OPERA_MENU
g_input_manager->InvokeAction(OP_NEW(OpInputAction, (OpInputAction::ACTION_SHOW_MENU, 0)));
#else
BOOL found = FALSE;
OpRect show_rect;
OpWidget* child = (OpWidget*) m_head_bar->childs.First();
while(child)
{
if(child->GetType() == WIDGET_TYPE_TOOLBAR_MENU_BUTTON && child->IsVisible())
{
found = TRUE;
show_rect = child->GetScreenRect();
break;
}
child = (OpWidget*) child->Suc();
}
if(!found)
{
show_rect = GetScreenRect();
}
g_application->GetMenuHandler()->ShowPopupMenu("Browser Button Menu Bar", PopupPlacement::AnchorBelow(show_rect));
#endif
}
void OpPagebar::ActivateNext(BOOL forwards)
{
if (!m_workspace->GetActiveDesktopWindow())
return;
int start = forwards ? 0 : GetWidgetCount() - 1;
int end = forwards ? GetWidgetCount() : -1;
bool activate_next = false;
for (int i = start; true; forwards ? ++i : --i)
{
if (i == end)
{
// cycle back to the start when we're at the end
activate_next = true;
i = start;
}
if (!GetWidget(i)->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
continue;
PagebarButton* button = static_cast<PagebarButton*>(GetWidget(i));
if (button->IsHiddenOrHiding())
continue;
if (activate_next)
{
button->GetDesktopWindow()->Activate();
break;
}
if (button->GetDesktopWindow()->IsActive())
activate_next = true;
}
}
void OpPagebar::EnableTransparentSkin(BOOL enable)
{
if (enable)
{
GetBorderSkin()->SetImage("Pagebar Transparent Skin");
}
else
{
GetBorderSkin()->SetImage("Pagebar Skin");
}
}
void OpPagebar::UpdateIsTopmost(BOOL top)
{
int height = GetRect(TRUE).height;
if (top != m_reported_on_top || (top && height != m_reported_height))
{
m_reported_on_top = top;
m_reported_height = height;
m_workspace->GetOpWindow()->OnPagebarMoved(top, height);
}
}
void OpPagebar::SetExtraTopPaddings(unsigned int head_top_padding, unsigned int normal_top_padding, unsigned int tail_top_padding, unsigned int tail_top_padding_width)
{
m_extra_top_padding_head = head_top_padding;
m_extra_top_padding_normal = normal_top_padding;
m_extra_top_padding_tail = tail_top_padding;
m_extra_top_padding_tail_width = tail_top_padding_width;
}
void OpPagebar::OnLockedByUser(PagebarButton *button, BOOL locked)
{
button->UpdateLockedTab();
// Pinned compact tabs only occur when non-grouped and horizontal
if (button->IsGrouped() || !IsHorizontal() || locked == button->IsCompactButton())
return;
button->SetIsCompactButton(locked);
UpdateWidget(button);
// Find the last non-grouped locked tab on the left
DesktopWindowCollectionItem& button_item = button->GetDesktopWindow()->GetModelItem();
DesktopWindowCollectionItem* last_locked = NULL;
DesktopWindowCollectionItem* parent = GetWorkspace()->GetModelItem();
for (DesktopWindowCollectionItem* item = parent->GetChildItem(); item; item = item->GetSiblingItem())
{
if (item == &button_item)
continue;
if (item->IsContainer() || !item->GetDesktopWindow() || !item->GetDesktopWindow()->IsLockedByUser())
break;
last_locked = item;
}
// Move the tab to the new position
g_application->GetDesktopWindowCollection().ReorderByItem(button_item, parent, last_locked);
// Since we change size on this tab, make sure all widgets in the toolbar animate to their new positions
AnimateAllWidgetsToNewRect();
}
void OpPagebar::ClearAllHoverStackOverlays()
{
for (int i = 0; i < GetWidgetCount(); i++)
{
if (GetWidget(i)->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
static_cast<PagebarButton*>(GetWidget(i))->SetUseHoverStackOverlay(FALSE);
}
}
PagebarButton* OpPagebar::FindDropButton()
{
for (int i = 0; i < GetWidgetCount(); i++)
{
if (!GetWidget(i)->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
continue;
PagebarButton* button = static_cast<PagebarButton*>(GetWidget(i));
if (button->GetUseHoverStackOverlay())
return button;
}
return NULL;
}
PagebarButton* OpPagebar::GetPagebarButton(const OpPoint& point)
{
BOOL horizontal = IsHorizontal();
for (INT32 i = 0; i < GetWidgetCount(); i++)
{
if (GetWidget(i)->IsFloating() || !GetWidget(i)->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
continue;
PagebarButton* button = static_cast<PagebarButton*>(GetWidget(i));
OpRect button_rect = button->GetRectWithoutMargins();
if (horizontal && button_rect.Left() <= point.x && point.x < button_rect.Right())
return button;
if (!horizontal && button_rect.Top() <= point.y && point.y < button_rect.Bottom())
return button;
}
return NULL;
}
INT32 OpPagebar::GetVisibleButtonWidth(DesktopWindow *window)
{
INT32 width = 0;
OpRect rect;
if(window->GetPagebarButton())
{
// the fast, but maybe not available code path
rect = window->GetPagebarButton()->GetRect();
width = rect.width;
}
else
{
INT32 i, count = GetWidgetCount();
for (i = 0; i < count; ++i)
{
OpWidget *widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON) && !widget->IsHidden())
{
PagebarButton *button = static_cast<PagebarButton *>(widget);
if(button->GetDesktopWindow() && button->GetDesktopWindow() == window)
{
rect = widget->GetRect();
width = rect.width;
break;
}
}
}
}
if (rect.x == -10000 && rect.y == -10000 && rect.width == 0)
{
// this means, that button was not laid out yet
return -1;
}
return width;
}
INT32 OpPagebar::GetPosition(PagebarButton* button)
{
INT32 count = GetWidgetCount();
int num = 0;
for (INT32 i = 0; i < count; ++i)
{
OpWidget *widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
if (widget == button)
return num;
num++;
}
}
return -1;
}
INT32 OpPagebar::GetWidgetPos(OpWidget* widget)
{
INT32 i;
INT32 count = GetWidgetCount();
for (i = 0; i < count; i++)
{
if (GetWidget(i) == widget)
{
return i;
}
}
return -1;
}
#ifdef PAGEBAR_DUMP_DEBUGGING
void OpPagebar::DumpPagebar()
{
INT32 i, count = GetWidgetCount();
// Loop all the widgets in reverse and just add/remove the OpTabGroupButton as required
for (i = 0; i < count; i++)
{
OpWidget *widget = GetWidget(i);
if (widget->IsOfType(WIDGET_TYPE_PAGEBAR_BUTTON))
{
printf("Group %d, PagebarButton, Hidden %d, Active: %d\n", static_cast<PagebarButton *>(widget)->GetGroupNumber(), static_cast<PagebarButton *>(widget)->IsHiddenOrHiding(), static_cast<PagebarButton *>(widget)->IsActiveTabForGroup());
}
else if (widget->IsOfType(WIDGET_TYPE_TAB_GROUP_BUTTON))
{
printf("Group %d, OpTabGroupButton, Hidden %d\n", static_cast<OpTabGroupButton *>(widget)->GetGroupNumber(), static_cast<OpTabGroupButton *>(widget)->IsHidden());
}
else if (widget->IsOfType(WIDGET_TYPE_SHRINK_ANIMATION))
{
printf("WIDGET_TYPE_SHRINK_ANIMATION\n");
}
else
{
printf("Unknown\n");
}
}
}
#endif // PAGEBAR_DUMP_DEBUGGING
|
#include <iostream>
#include "TestExecutive.h"
/*int main(int argc, char * argv[])
{
argc = 5;
argv[0] = "Upload";
argv[1] = "Category3";
argv[2] = "..\\files\\";
argv[3] = "*.h";
argv[4] = "*.cpp";
std::cout << "Upload function" << std::endl;
MsgClient c1;
//c1.cparguments(argc, argv);
std::thread t1(
[&]() { c1.execute(100, 1); }
);
t1.join();
BlockingQueue<HttpMessage> clientReceiverQ_;
try
{
SocketListener sl(8081, Socket::IP6); //client listens to the server
ClientReceiver receiver(clientReceiverQ_);
sl.start(receiver);
while (true)
{
HttpMessage msg = clientReceiverQ_.deQ(); //BlockingQueue.h
Show::write("\n\n Client received message with body contents:\n" + msg.bodyString());
}
}
catch (std::exception& exc)
{
Show::write("\n Exeception caught: ");
std::string exMsg = "\n " + std::string(exc.what()) + "\n\n";
Show::write(exMsg);
}
}*/
|
#include "../include/quaternaryMask.h"
//#define DEBUG 1
void quaternaryMask::setMask(int blackLMax, int whiteLMin, int greenHMean, int greenHVar, int greenSMin){
this->blackLMax = blackLMax;
this->whiteLMin = whiteLMin;
this->greenHMean = greenHMean;
this->greenHVar = greenHVar;
this->greenSMin = greenSMin;
}
void quaternaryMask::generateMask(cv::Mat frame){
cv::Mat maskHLS;
// Converts to HSV colorspace
cv::cvtColor(frame, maskHLS, cv::COLOR_BGR2HLS);
// As each pixel is going to be classified in one of four categories
// we start by detecting the easiest one so we can move to more difficult ones later
// We should go: white, green, black, others (left)
// White Threshold
cv::inRange(maskHLS, cv::Scalar(0, whiteLMin, 0), cv::Scalar(255, 255, 255), this->whiteMask);
// Green Threshold
cv::inRange(maskHLS, cv::Scalar(greenHMean-greenHVar, blackLMax, greenSMin), cv::Scalar(greenHMean+greenHVar, whiteLMin, 255), this->greenMask);
// Black Threshold
cv::inRange(maskHLS, cv::Scalar(0, 0, 0), cv::Scalar(255, blackLMax, 255), this->blackMask);
}
|
#include "../include/BulletManager.h"
#include "../include/EnemyManager.h"
#include "../include/Player.h"
#include "../include/Bullet.h"
#include "../include/Enemy.h"
#include "../include/Map.h"
#include "../include/GameScene.h"
#include "../include/Map.h"
#include "../include/MapBlock.h"
#include "../include/Camera.h"
namespace gnGame {
BulletManager* BulletManager::getIns()
{
static BulletManager Instance;
return &Instance;
}
BulletManager::~BulletManager()
{
}
void BulletManager::addBullet(BulletPtr& _bullet)
{
for (size_t i{ 0 }; i < bulletList.size(); ++i) {
if (!bulletList[i]) {
bulletList[i] = _bullet;
return;
}
}
bulletList.emplace_back(_bullet);
}
void BulletManager::onUpdateBulletList()
{
for (auto& bullet : bulletList) {
if (!bullet) {
continue;
}
bullet->onUpdate();
// ここで弾が画面外に出たら削除
if (!Camera::isOnScreen(bullet->transform.pos)) {
bullet = nullptr;
}
}
}
// TODO: 関数自体が大きくなってきているので、小さくさせる
void BulletManager::collisionActor(Player& _player, GameScene* _gameScene)
{
// 敵のリストを全探索
for (size_t i{ 0 }; i < EnemyManager::getIns()->getListSize(); ++i) {
if (!EnemyManager::getIns()->getEnemy(i)) {
continue;
}
// 弾のリストを全探索
for (auto& bullet : bulletList) {
if (!bullet) {
continue;
}
auto bulletType = bullet->getBulletType();
// プレイヤーが打った弾の時
if (bulletType == BulletType::Player) {
if (bullet->hitEnemy(EnemyManager::getIns()->getEnemy(i))) {
auto enemy = EnemyManager::getIns()->getEnemy(i);
enemy->getEnemyBody().damage(bullet->getAttack());
if (enemy->getEnemyType() == EnemyType::Nomal) {
// 普通の敵の場合
if (EnemyManager::getIns()->getEnemy(i)->getParameter().hp <= 0) {
EnemyManager::getIns()->removeActor(i);
}
}
else if (enemy->getEnemyType() == EnemyType::Boss) {
// ボスを倒したときの場合
if (EnemyManager::getIns()->getEnemy(i)->getParameter().hp <= 0) {
_gameScene->nextMap();
}
}
bullet = nullptr;
return;
}
}
else if (bulletType == BulletType::Enemy) {
// 敵が打った弾の時
if (bullet->hitPlayer(_player)) {
_player.getPlayerBody().damage(bullet->getAttack());
if (_player.getPlayerBody().getParameter().hp <= 0) {
_player.death();
}
bullet = nullptr;
return;
}
}
}
}
}
void BulletManager::collisionMap(Map& _map)
{
for (auto& bullet : bulletList) {
if (!bullet) {
continue;
}
// プレイヤーが放った弾と敵が接触した場合
if (bullet->intersectMap(_map)) {
bullet = nullptr;
}
}
}
void BulletManager::claerList()
{
bulletList.clear();
}
}
|
#include <GL/glut.h>
#include "Pavimento.h"
Pavimento::Pavimento() {
}
Pavimento::Pavimento(double l1, double l2) {
lunghezza = l1;
larghezza = l2;
}
double Pavimento::getLarghezza() {
return larghezza;
}
void Pavimento::setLarghezza(double l) {
larghezza = l;
}
double Pavimento::getLunghezza() {
return lunghezza;
}
void Pavimento::setLunghezza(double l) {
lunghezza = l;
}
void Pavimento::disegna() {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, idTexture);
glBegin(GL_QUADS);
glNormal3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-larghezza/2, 0, 0);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-larghezza/2, lunghezza, 0);
glTexCoord2f(1.0f, 1.0f); glVertex3f(larghezza/2, lunghezza, 0);
glTexCoord2f(0.0f, 1.0f); glVertex3f(larghezza/2, 0, 0);
glEnd();
glDisable(GL_TEXTURE_2D);
}
void Pavimento::reset() {
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
long long k, r, i;
while(cin>>k>>r)
{
i=1;
while(((k%10)!=0)&&((k%10)!=r))
{
k+=(k/i);
i++;
}
cout<<i<<endl;
}
return 0;
}
|
#ifndef OBJ_P_HPP
#define OBJ_P_HPP
#include <QObject>
class ObjPrivate : public QObject
{
Q_OBJECT
public:
ObjPrivate();
~ObjPrivate();
};
#endif
|
//
// Note.cpp
// DrumConsole
//
// Created by Paolo Simonazzi on 08/03/2016.
//
//
#include "../JuceLibraryCode/JuceHeader.h"
#include "SoundFromFile.hpp"
#include "MyMemoryMappedAudioFormatReader.cpp"
#define IDXCHECK(x, y) ((x)<0?0:((x)>(y)?(y):(x)))
SoundFromFile::SoundFromFile() {
/*
for (int idx=0; idx<numOfLayersUsed; ++idx) {
readerSourceSamples[idx] = nullptr;
}
*/
formatManager.registerBasicFormats();
}
SoundFromFile::~SoundFromFile() {
for(int idx=0; idx<numOfLayersUsed;++idx) {
//readerSourceSamples[idx]->releaseResources();
//delete readerSourceSamples[idx];
}
}
void SoundFromFile::createSample (int idx, const File& audioFile) {
WavAudioFormat wFormat;
AudioFormatReader *pp = formatManager.createReaderFor(audioFile);
//pp->
MemoryMappedAudioFormatReader *mm = wFormat.createMemoryMappedReader(audioFile);
readers[idx] = formatManager.createReaderFor(audioFile);
readersMappededInMemory[idx] = wFormat.createMemoryMappedReader(audioFile);
readersMappededInMemory[idx]->mapEntireFile();
if (readers[idx] != nullptr) {
//readerSourceSamples[idx] = new AudioFormatReaderSource (readers[idx], true);
} else {
std::cout << "file not found\n";
}
}
void SoundFromFile::loadSamplesFromFolder (const String& soundName, const String& folderPath, int numOfSamples) {
for (int idx = 0; idx<numOfSamples; ++idx) {
String fileName = folderPath + soundName + std::to_string(idx) + ".wav";
createSample(IDXCHECK(idx, numOfLayersUsed), fileName);
}
}
MemoryMappedAudioFormatReader* SoundFromFile::getMemoryMappedReaderByVolume(float volume) {
int readerToPickUp = volume * (numOfLayersUsed - 1);
return readersMappededInMemory[readerToPickUp];
}
int SoundFromFile::Lines(float value) {
const float th1 = 0.4, th2 = 0.9;
if (value < th1) {
return 0;
} else if (value < th2) {
return 1;
}
return 2;
}
AudioFormatReader* SoundFromFile::getReaderByVolume (float volume) {
return readers[Lines(volume)];
}
|
#include <iostream>
using namespace std;
int main() {
int js = 0, jp = 0, jf = 0;
int jchui = 0, jbu = 0, jjian = 0;
int ychui = 0, ybu = 0, yjian = 0;
char j, y;
int n;
cin >> n;
while(n--) {
cin >> j >> y;
if(j == y) {
jp++;
if(j == 'C') {
jchui++;
ychui++;
}
if(j == 'B') {
jbu++;
ybu++;
}
if(j == 'J') {
jjian++;
yjian++;
}
} else if(j == 'C' && y == 'B') {
jf++;
jchui++;
ybu++;
} else if(j == 'C' && y == 'J') {
js++;
jchui++;
yjian++;
} else if(j == 'B' && y == 'C') {
js++;
jbu++;
ychui++;
} else if(j == 'B' && y == 'J') {
jf++;
jbu++;
yjian++;
} else if(j == 'J' && y == 'B'){
js++;
jjian++;
ybu++;
} else if(j == 'J' && y == 'C') {
jf++;
jjian++;
ychui++;
}
}
printf("%d %d %d\n", js, jp, jf);
printf("%d %d %d\n", jf, jp, js);
if(jbu > jchui) {
if(jbu > jjian)
cout << "B ";
} else if(jbu == jchui) {
if(jbu >= jjian)
cout << "B ";
else
cout << "J ";
} else {
if(jchui >= jjian)
cout << "C ";
else
cout << "J ";
}
if(ybu > ychui) {
if(ybu > yjian)
cout << "B";
} else if(ybu == ychui) {
if(ybu >= yjian)
cout << "B";
else
cout << "J";
} else {
if(ychui >= yjian)
cout << "C";
else
cout << "J";
}
return 0;
}
|
// Created on: 1993-01-09
// Created by: CKY / Contract Toubro-Larsen ( TCD )
// 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 _IGESGeom_OffsetSurface_HeaderFile
#define _IGESGeom_OffsetSurface_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_XYZ.hxx>
#include <IGESData_IGESEntity.hxx>
class gp_Vec;
class IGESGeom_OffsetSurface;
DEFINE_STANDARD_HANDLE(IGESGeom_OffsetSurface, IGESData_IGESEntity)
//! defines IGESOffsetSurface, Type <140> Form <0>
//! in package IGESGeom
//! An offset surface is a surface defined in terms of an
//! already existing surface.If S(u, v) is a parametrised
//! regular surface and N(u, v) is a differential field of
//! unit normal vectors defined on the whole surface, and
//! "d" a fixed non zero real number, then offset surface
//! to S is a parametrised surface S(u, v) given by
//! O(u, v) = S(u, v) + d * N(u, v);
//! u1 <= u <= u2; v1 <= v <= v2;
class IGESGeom_OffsetSurface : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESGeom_OffsetSurface();
//! This method is used to set the fields of the class
//! OffsetSurface
//! - anIndicator : Offset indicator
//! - aDistance : Offset distance
//! - aSurface : Surface that is offset
Standard_EXPORT void Init (const gp_XYZ& anIndicatoR, const Standard_Real aDistance, const Handle(IGESData_IGESEntity)& aSurface);
//! returns the offset indicator
Standard_EXPORT gp_Vec OffsetIndicator() const;
//! returns the offset indicator after applying Transf. Matrix
Standard_EXPORT gp_Vec TransformedOffsetIndicator() const;
//! returns the distance by which surface is offset
Standard_EXPORT Standard_Real Distance() const;
//! returns the surface that has been offset
Standard_EXPORT Handle(IGESData_IGESEntity) Surface() const;
DEFINE_STANDARD_RTTIEXT(IGESGeom_OffsetSurface,IGESData_IGESEntity)
protected:
private:
gp_XYZ theIndicator;
Standard_Real theDistance;
Handle(IGESData_IGESEntity) theSurface;
};
#endif // _IGESGeom_OffsetSurface_HeaderFile
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
const int mod = 1000000007;
struct mint {
ll x; // typedef long long ll;
mint(ll x=0):x((x%mod+mod)%mod){}
mint operator-() const { return mint(-x);}
mint& operator+=(const mint a) {
if ((x += a.x) >= mod) x -= mod;
return *this;
}
mint& operator-=(const mint a) {
if ((x += mod-a.x) >= mod) x -= mod;
return *this;
}
mint& operator*=(const mint a) {
(x *= a.x) %= mod;
return *this;
}
mint operator+(const mint a) const {
mint res(*this);
return res+=a;
}
mint operator-(const mint a) const {
mint res(*this);
return res-=a;
}
mint operator*(const mint a) const {
mint res(*this);
return res*=a;
}
mint pow(ll t) const {
if (!t) return 1;
mint a = pow(t>>1);
a *= a;
if (t&1) a *= *this;
return a;
}
// for prime mod
mint inv() const {
return pow(mod-2);
}
mint& operator/=(const mint a) {
return (*this) *= a.inv();
}
mint operator/(const mint a) const {
mint res(*this);
return res/=a;
}
};
struct combination {
vector<mint> fact, ifact;
combination(int n):fact(n+1),ifact(n+1) {
assert(n < mod);
fact[0] = 1;
for (int i = 1; i <= n; ++i) fact[i] = fact[i-1]*i;
ifact[n] = fact[n].inv();
for (int i = n; i >= 1; --i) ifact[i-1] = ifact[i]*i;
}
mint operator()(int n, int k) {
if (k < 0 || k > n) return 0;
return fact[n]*ifact[k]*ifact[n-k];
}
};
const int MAX_N = 200050;
vector<int> node[MAX_N];
combination cb(MAX_N);
typedef struct {
mint pat;
int node;
} c_info_t;
//親nodeはpattern数とnode数を受け取る必要がある
c_info_t dfs(int now, int parent){
//
vector<c_info_t> child;
int node_all = 0;
for(auto next: node[now]){
if (next == parent) continue;
c_info_t tmp = dfs(next, now);
node_all += tmp.node;
child.push_back(tmp);
}
mint pat(1);
int node_tmp = node_all;
rep(i, child.size()){
pat *= child[i].pat;
pat *= cb(node_tmp, child[i].node);
node_tmp -= child[i].node;
}
node_all++;
// printf("%d %d: %lld:%d\n",now+1, parent+1, pat.x, node_all);
return {pat, node_all};
}
int main()
{
int n;
cin >> n;
rep(i, n-1){
int tmpa, tmpb; cin >> tmpa >> tmpb;
tmpa--; tmpb--;
node[tmpa].push_back(tmpb);
node[tmpb].push_back(tmpa);
}
rep(i, n){
cout << dfs(i, -1).pat.x << endl;
}
// cout << dfs(1, -1).pat.x << endl;
}
/*
木dpを行うと、dp[parent][child]の値が再利用できる
9C2 * 7C2 * 5C5 = 9! / 2! 2! 5!と置ける
"部分木"と"根に向かう辺"で情報を管理すると、O(N)でできる
子に向かう辺の情報はdfs,親に向かう辺の情報はbfs
計算にO(d) d:次数かかるので、bfs時の導出は、総和から引くことで計算量を壊さないようにする
*/
|
#include "Uc3App.h"
void Uc3App::setupScene()
{
Ogre::SceneManager * ogreManager = OgreFramework::getSingletonPtr()->m_pSceneMgr;
ogreManager->createLight("Light")->setPosition(75,75,75);
Ogre::Plane floorPlane(Ogre::Vector3::UNIT_Y, 0);
Ogre::MeshManager::getSingleton().createPlane("ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
floorPlane, 1500, 1500, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);
Ogre::SceneNode *floorNode = ogreManager->getRootSceneNode()->createChildSceneNode("floorNode");
Ogre::Entity* entGround = OgreFramework::getSingletonPtr()->m_pSceneMgr->createEntity("GroundEntity", "ground");
entGround->setMaterialName("UC3/Basic");
entGround->setCastShadows(true);
ogreManager->getRootSceneNode()->createChildSceneNode()->attachObject(entGround);
Ogre::Entity* entNinja = ogreManager->createEntity("Ninja", "ninja.mesh");
entNinja->setCastShadows(true);
ogreManager->getRootSceneNode()->createChildSceneNode()->attachObject(entNinja);
}
|
#include <cstdlib>
#include <cstdint>
#include <cmath>
#include <fstream>
#include <iostream>
#include <exception>
#include <stdexcept>
#include <utility>
#include <tuple>
#include <limits>
#include <vector>
#include <string>
#include <ostream>
#include "flow_complex.hpp"
template <typename nt, typename st>
FC::flow_complex<nt, st> simplify(FC::flow_complex<nt, st>, nt t);
template <typename nt, typename st>
void print_histogram(std::ostream &, FC::flow_complex<nt, st>);
int main(int argc, char ** argv) {
try {
using float_t = double;
using size_type = std::uint32_t;
if (4 != argc)
throw std::invalid_argument("usage: simplify <<t> | -p> <in_file> <out_file>");
// read the flow complex from file
auto fc = FC::flow_complex<float_t, size_type>(42, 42); // dummy
{
auto in_filename = argv[2];
std::ifstream in_file(in_filename);
in_file >> fc;
}
char const* action = argv[1];
if (std::string(action) == "-p") {
char const* out_filename = argv[3];
std::ofstream out_file(out_filename);
print_histogram(out_file, std::move(fc));
} else {
// simplify
float_t const t = std::atof(argv[1]);
if (t < 1)
throw std::invalid_argument("prerequisite: t >= 1");
fc = simplify(std::move(fc), t);
// write result flow complex to file
char const* out_filename = argv[3];
std::ofstream out_file(out_filename);
out_file << fc;
}
} catch (std::exception & e) {
std::cerr << e.what() << std::endl;
std::exit(EXIT_FAILURE);
}
std::exit(EXIT_SUCCESS);
}
template <typename nt, typename st>
std::tuple<typename FC::flow_complex<nt, st>::cp_type *,
typename FC::flow_complex<nt, st>::cp_type *,
nt>
get_min_incidence(FC::flow_complex<nt, st> & fc) {
auto r = std::make_tuple(&*fc.begin(), &*fc.begin(),
std::numeric_limits<nt>::infinity());
auto & min_a = std::get<0>(r);
auto & min_b = std::get<1>(r);
auto & min_ratio = std::get<2>(r);
for (auto & a : fc) {
if (0 == a.index())
continue; // the ratio is not defined for a_dist == 0
nt const a_dist = std::sqrt(a.sq_dist());
for (auto b_it = a.succ_begin(); b_it != a.succ_end(); ++b_it) {
auto & b = **b_it;
if ((! b.is_max_at_inf()) && (1 == (b.index() - a.index()))) {
nt const ratio_ab = std::sqrt(b.sq_dist()) / a_dist;
if (ratio_ab < min_ratio) {
min_a = &a;
min_b = &b;
min_ratio = ratio_ab;
}
}
}
}
return r;
}
/**
@brief Performs a single reduction step.
*/
template <typename nt, typename st>
FC::flow_complex<nt, st> reduce(FC::flow_complex<nt, st> fc,
FC::critical_point<nt, st> * a_ptr,
FC::critical_point<nt, st> * b_ptr) {
// used types
using fc_type = FC::flow_complex<nt, st>;
using cp_type = typename fc_type::cp_type;
static std::vector<cp_type *> in_a;
static std::vector<cp_type *> out_a;
static std::vector<cp_type *> in_b;
in_a.clear(); in_b.clear(); out_a.clear(); // init
for (auto & cp : fc) { // determine In(a) and In(b)
for (auto it = cp.succ_begin(); it != cp.succ_end(); ++it) {
if (*it == a_ptr) {
in_a.push_back(&cp); break;
} else if (*it == b_ptr) {
in_b.push_back(&cp); break;
}
}
}
out_a.insert(out_a.end(), a_ptr->succ_begin(), a_ptr->succ_end()); // Out(a)
// update the incidences
for (auto ib : in_b)
for (auto oa : out_a)
if (ib->succ_end() == std::find(ib->succ_begin(), ib->succ_end(), oa))
ib->add_successor(oa);
// remove a and be and possible incidences to them
for (auto ia : in_a)
ia->erase(a_ptr);
for (auto ib : in_b)
ib->erase(b_ptr);
fc.erase(*a_ptr);
fc.erase(*b_ptr);
return fc;
}
/**
@brief Performs a series of reductions until the threshold is exceeded.
*/
template <typename nt, typename st>
FC::flow_complex<nt, st> simplify(FC::flow_complex<nt, st> fc,
nt t) {
// tuple: predecessor a, successor b, ratio t_ab
auto min_incidence = get_min_incidence(fc);
auto & a_ptr = std::get<0>(min_incidence);
auto & b_ptr = std::get<1>(min_incidence);
auto & min_ratio = std::get<2>(min_incidence);
while (min_ratio <= t) {
fc = reduce(std::move(fc), a_ptr, b_ptr);
// prepare next iteration
min_incidence = get_min_incidence(fc);
}
return fc;
}
template <typename nt, typename st>
void print_histogram(std::ostream & os, FC::flow_complex<nt, st> fc) {
auto const INF = std::numeric_limits<nt>::infinity();
auto min_incidence = get_min_incidence(fc);
auto & a_ptr = std::get<0>(min_incidence);
auto & b_ptr = std::get<1>(min_incidence);
auto & min_ratio = std::get<2>(min_incidence);
using fc_type = FC::flow_complex<nt, st>;
auto print_hist = [&os] (nt ratio, fc_type const& fc) {
auto hist = compute_hist(fc);
os << ratio;
for (auto & p : hist)
os << " " << p.second;
os << std::endl;
};
print_hist(1, fc); // print initial fc
while (INF != min_ratio) {
fc = reduce(std::move(fc), a_ptr, b_ptr);
print_hist(min_ratio, fc);
// prepare next iteration
min_incidence = get_min_incidence(fc);
}
}
|
#include "Pt.h"
Pt::Pt(int size, sf::RenderWindow* window) {
this->x = 0.f;
this->y = 0.f;
setRadius(size);
setFillColor(sf::Color(255, 255, 255, 127));
for (int i = 0; i < 720; i++)
{
rays[i] = Ray(this->x, this->y, (float)i);
}
}
//Updating pos every frame
void Pt::posUpdate(sf::RenderWindow* window)
{
this->x = window->mapPixelToCoords(sf::Mouse::getPosition(*window)).x;
this->y = window->mapPixelToCoords(sf::Mouse::getPosition(*window)).y;
setPosition(sf::Vector2f(x - getRadius() / 2 - 8, y - getRadius() / 2 - 8));
window->draw(*this);
}
void Pt::drawRay(sf::RenderWindow* window, sf::Vertex walls[][2], float size) {
int xVal = this->x, yVal = this->y;
for (int i = 0; i < 720; i++)
{
rays[i].updateRay(xVal, yVal, i/2.0, size);
for (int j = 0; j < 10; j++)
{
if (check(walls[j], rays[i].line) != sf::Vector2f(-1, -1))
{
rays[i].line[1].position = check(walls[j], rays[i].line);
}
}
rays[i].drawRay(window);
}
}
|
/*
Copyright 2021 University of Manchester
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http: // www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <map>
#include <string>
#include <vector>
namespace orkhestrafs::core_interfaces::hw_library {
/**
* @brief Data about a single PR module on where it fits on the board
*/
struct PRModuleData {
std::vector<int> fitting_locations;
int length;
std::vector<int> capacity;
std::string resource_string;
bool is_backwards;
};
/**
* @brief Data containing all PR modules for a certain operation and a vector
* placing all of the modules.
*/
struct OperationPRModules {
std::vector<std::vector<std::string>> starting_locations;
std::map<std::string, PRModuleData> bitstream_map;
};
} // namespace orkhestrafs::core_interfaces::hw_library
|
#include <iostream>
using namespace std;
int possiblepaths(int m, int n)
{
if (m == 1 || n == 1)
return 1;
return possiblepaths(m - 1, n) + possiblepaths(m, n - 1);
}
int main()
{
int m, n;
cout<<"Enter m & n\n";
cin>>m>>n;
int out;
out=possiblepaths(m,n);
cout<<"possible paths are "<<out;
return 0;
}
|
//
// Created by Alex on 06/09/2018.
//
#include "Asset.h"
//// Constructors ////
Asset::Asset() = default;
Asset::Asset(std::string ID_, Asset::DataSource Source_) : ID(ID_)
{
if (Source_ == QUANDL) {
std::vector<std::string> DataDownload = QuandlDownload(ID);
Header = TimeSeriesHeaderReader(DataDownload);
std::string DataSource("QUANDL");
if(Header.GetIsInitialised()) {
// Assumes header is in line one and ignores it
for(int i = 1; i < DataDownload.size()-1; i++){
TimeSeriesData tempResult(DataDownload[i], Header, DataSource);
DataSet.push_back(tempResult);
}
}
} else if (Source_ == ALPHA) {
std::vector<std::string> DataDownload = AlphaDownload(ID);
Header = TimeSeriesHeaderReader(DataDownload);
std::string DataSource("ALPHA");
if(Header.GetIsInitialised()) {
// Assumes header is in line one and ignores it
for(int i = 1; i < DataDownload.size()-1; i++){
TimeSeriesData tempResult(DataDownload[i], Header, DataSource);
DataSet.push_back(tempResult);
}
}
}
//// Only runs the following section of the dataset contains data ////
if (!DataSet.empty()) {
IsInitialised = true;
std::cout << "Asset data for " << ID << " has been downloaded successfully." << std::endl;
CustomDate EarliestDate(DataSet[0].GetDate());
CustomDate LatestDate(DataSet[0].GetDate());
for (auto CurrentData : DataSet) {
if (CurrentData.GetDate()<EarliestDate){
EarliestDate = CurrentData.GetDate();
}
if (CurrentData.GetDate()>LatestDate){
LatestDate = CurrentData.GetDate();
}
}
EarliestAvailableDate = EarliestDate;
LatestAvailableDate = LatestDate;
this->SortDataByDate();
this->CalcDailyReturns();
} else {
std::cout << "ERROR: Asset data for " << ID
<< " could not be initialised properly and was not included." << std::endl;
}
}
//// Functions Used During Construction ////
bool DateSortFunction(TimeSeriesData Point1, TimeSeriesData Point2) {
return (Point1.GetDate() < Point2.GetDate());
}
void Asset::SortDataByDate() {
std::sort(DataSet.begin(),DataSet.end(),DateSortFunction);
}
void Asset::CalcDailyReturns() {
AssetReturns.emplace_back(DataSet[0]);
for(int i = 1; i < DataSet.size(); i++) {
AssetReturns.emplace_back(DataSet[i],DataSet[i-1]);
}
};
//// Search Functions ////
TimeSeriesData Asset::DataDateSearch(CustomDate Date_) const {
for (auto Data : DataSet) {
if (Data.GetDate() == Date_) {
return Data;
}
}
return TimeSeriesData();
}
DailyReturns Asset::ReturnsDateSearch(CustomDate Date_) const {
for (auto Returns : AssetReturns) {
if (Returns.GetDate() == Date_) {
return Returns;
}
}
return {};
}
//// Time Dependent Data Calculations functions ////
long double Asset::Mean(TimeSeriesData::Variable Var_, CustomDate StartDate_, CustomDate EndDate_) const {
CustomDate StartDate = this->EarliestDateCheck(StartDate_);
CustomDate EndDate = this->LatestDateCheck(EndDate_);
long double Sum = 0;
unsigned int Points = 0;
for(auto i : DataSet){
if (i.GetDate() >= StartDate && i.GetDate() <= EndDate) {
Sum += i.GetDataMember(Var_);
Points ++;
}
}
if(Points!=0) {
return Sum/Points;
} else {
std::cout << "Error in mean calculation, zero points were entered." << std::endl;
return 0;
}
}
long double Asset::StdDev(TimeSeriesData::Variable Var_, CustomDate StartDate_, CustomDate EndDate_) const {
CustomDate StartDate = this->EarliestDateCheck(StartDate_);
CustomDate EndDate = this->LatestDateCheck(EndDate_);
long double Mean = this->Mean(Var_, StartDate, EndDate);
long double SquareDiff = 0;
unsigned int Points = 0;
for(auto i : DataSet){
if (i.GetDate() >= StartDate && i.GetDate() <= EndDate) {
double long value = (i.GetDataMember(Var_) - Mean);
SquareDiff += value * value;
Points++;
}
}
if(Points > 1) {
long double Variance = SquareDiff / (Points - 1);
long double StdDev = sqrt(Variance);
return StdDev;
} else {
std::cout << "Error in standard deviation calculation, less than 2 points were entered." << std::endl;
return 0;
}
}
long double CoVar(const Asset &Asset1, const Asset &Asset2, TimeSeriesData::Variable Var_, CustomDate StartDate_, CustomDate EndDate_) {
CustomDate StartDate = Asset1.EarliestDateCheck(StartDate_);
StartDate = Asset2.EarliestDateCheck(StartDate);
CustomDate EndDate = Asset1.LatestDateCheck(EndDate_);
EndDate = Asset2.LatestDateCheck(EndDate);
long double Mean1 = Asset1.Mean(Var_, StartDate, EndDate);
long double Mean2 = Asset2.Mean(Var_, StartDate, EndDate);
long double SquareDiff = 0;
unsigned int Points = 0;
unsigned int MissedPoints = 0;
for(auto Data1 : Asset1.DataSet) {
if (Data1.IsInitialised()) {
if(Data1.GetDate() >= StartDate && Data1.GetDate() <= EndDate) {
TimeSeriesData Data2 = Asset2.DataDateSearch(Data1.GetDate());
if (Data2.IsInitialised()) {
double long Value1 = (Data1.GetDataMember(Var_) - Mean1);
double long Value2 = (Data2.GetDataMember(Var_) - Mean2);
SquareDiff += Value1*Value2;
Points ++;
} else {
MissedPoints ++;
}
}
}
}
if(Points > 1) {
long double CoVar = (SquareDiff)/(Points-1);
if (MissedPoints > 0) {
std::cout << "There were " << MissedPoints << " number of mismatched dates in the calculation of covariance."
<< std::endl;
}
return CoVar;
} else {
std::cout << "Error in covariance calculation, less than 2 points were entered." << std::endl;
return 0;
}
}
long double CorrCoef(const Asset &Asset1, const Asset &Asset2, TimeSeriesData::Variable Var_, CustomDate StartDate_, CustomDate EndDate_) {
CustomDate StartDate = Asset1.EarliestDateCheck(StartDate_);
StartDate = Asset2.EarliestDateCheck(StartDate);
CustomDate EndDate = Asset1.LatestDateCheck(EndDate_);
EndDate = Asset2.LatestDateCheck(EndDate);
long double Mean1 = Asset1.Mean(Var_, StartDate, EndDate);
long double Mean2 = Asset2.Mean(Var_, StartDate, EndDate);
long double SquareDiffBoth = 0;
long double SquareDiff1 = 0;
long double SquareDiff2 = 0;
unsigned int Points = 0;
unsigned int MissedPoints = 0;
for(auto Data1 : Asset1.DataSet) {
if (Data1.IsInitialised()) {
if(Data1.GetDate() >= StartDate && Data1.GetDate() <= EndDate) {
TimeSeriesData Data2 = Asset2.DataDateSearch(Data1.GetDate());
if (Data2.IsInitialised()) {
double long Value1 = (Data1.GetDataMember(Var_) - Mean1);
double long Value2 = (Data2.GetDataMember(Var_) - Mean2);
SquareDiffBoth += Value1*Value2;
SquareDiff1 += Value1*Value1;
SquareDiff2 += Value2*Value2;
Points ++;
} else {
MissedPoints ++;
}
}
}
}
if(Points > 1) {
long double CoVar = (SquareDiffBoth)/ static_cast<long double>(Points-1);
long double Var1 = (SquareDiff1)/ static_cast<long double>(Points-1);
long double Var2 = (SquareDiff2)/ static_cast<long double>(Points-1);
long double StdDev1 = sqrt(Var1);
long double StdDev2 = sqrt(Var2);
long double CorrCoef = CoVar/(StdDev1*StdDev2);
if (MissedPoints > 0) {
std::cout << "There were " << MissedPoints << " number of mismatched dates in the calculation of correlation coefficient."
<< std::endl;
}
return CorrCoef;
} else {
std::cout << "Error in correlation coefficient calculation, less than 2 points were entered." << std::endl;
return 0;
}
}
long double Beta(const Asset &Asset_, const Asset &Index_, TimeSeriesData::Variable Var_, CustomDate StartDate_, CustomDate EndDate_) {
CustomDate StartDate = Asset_.EarliestDateCheck(StartDate_);
StartDate = Index_.EarliestDateCheck(StartDate);
CustomDate EndDate = Asset_.LatestDateCheck(EndDate_);
EndDate = Index_.LatestDateCheck(EndDate);
long double MeanAsset = Asset_.Mean(Var_, StartDate, EndDate);
long double MeanIndex = Index_.Mean(Var_, StartDate, EndDate);
long double SquareDiffBoth = 0;
long double SquareDiffIndex = 0;
unsigned int Points = 0;
unsigned int MissedPoints = 0;
for(auto DataAsset : Asset_.DataSet) {
if (DataAsset.IsInitialised()) {
if(DataAsset.GetDate() >= StartDate && DataAsset.GetDate() <= EndDate) {
TimeSeriesData DataIndex = Index_.DataDateSearch(DataAsset.GetDate());
if (DataIndex.IsInitialised()) {
double long ValueAsset = (DataAsset.GetDataMember(Var_) - MeanAsset);
double long ValueIndex = (DataIndex.GetDataMember(Var_) - MeanIndex);
SquareDiffBoth += ValueAsset*ValueIndex;
SquareDiffIndex += ValueIndex*ValueIndex;
Points ++;
} else {
MissedPoints ++;
}
}
}
}
if(Points > 1) {
long double CoVar = (SquareDiffBoth)/(Points-1);
long double IndexVar = (SquareDiffIndex)/(Points-1);
long double CorrCoef = CoVar/(IndexVar);
if (MissedPoints > 0) {
std::cout << "There were " << MissedPoints << " number of mismatched dates in the calculation of beta."
<< std::endl;
}
return CorrCoef;
} else {
std::cout << "Error in beta calculation, less than 2 points were entered." << std::endl;
return 0;
}
}
//// Returns Calculations Functions ////
long double Asset::ReturnsMean(CustomDate StartDate_, CustomDate EndDate_) const {
CustomDate StartDate = this->EarliestDateCheck(StartDate_);
CustomDate EndDate = this->LatestDateCheck(EndDate_);
long double Sum = 0;
unsigned int Points = 0;
for(auto Returns : AssetReturns){
if (Returns.GetDate() >= StartDate && Returns.GetDate() <= EndDate) {
Sum += Returns.GetReturns();
Points ++;
}
}
if(Points!=0) {
return Sum/Points;
} else {
std::cout << "Error in mean calculation, zero points were entered." << std::endl;
return 0;
}
}
long double Asset::ReturnsStdDev(CustomDate StartDate_, CustomDate EndDate_) const {
CustomDate StartDate = this->EarliestDateCheck(StartDate_);
CustomDate EndDate = this->LatestDateCheck(EndDate_);
long double ReturnsMean = this->ReturnsMean(StartDate, EndDate);
long double SquareDiff = 0;
unsigned int Points = 0;
for(auto Returns : AssetReturns){
if (Returns.GetDate() >= StartDate && Returns.GetDate() <= EndDate) {
double long value = (Returns.GetReturns() - ReturnsMean);
SquareDiff += value * value;
Points++;
}
}
if(Points > 1) {
long double Variance = SquareDiff / (Points - 1);
long double StdDev = sqrt(Variance);
return StdDev;
} else {
std::cout << "Error in standard deviation calculation, less than 2 points were entered." << std::endl;
return 0;
}
}
long double ReturnsCoVar(const Asset &Asset1, const Asset &Asset2, CustomDate StartDate_, CustomDate EndDate_) {
CustomDate StartDate = Asset1.EarliestDateCheck(StartDate_);
StartDate = Asset2.EarliestDateCheck(StartDate);
CustomDate EndDate = Asset1.LatestDateCheck(EndDate_);
EndDate = Asset2.LatestDateCheck(EndDate);
long double Mean1 = Asset1.ReturnsMean(StartDate, EndDate);
long double Mean2 = Asset2.ReturnsMean(StartDate, EndDate);
long double SquareDiff = 0;
unsigned int Points = 0;
unsigned int MissedPoints = 0;
for(auto Returns1 : Asset1.AssetReturns) {
if (Asset1.GetIsInitialised()) {
if(Returns1.GetDate() >= StartDate && Returns1.GetDate() <= EndDate) {
DailyReturns Returns2 = Asset2.ReturnsDateSearch(Returns1.GetDate());
if (Returns2.GetIsInitialised()) {
double long Value1 = (Returns1.GetReturns() - Mean1);
double long Value2 = (Returns2.GetReturns() - Mean2);
SquareDiff += Value1*Value2;
Points ++;
} else {
MissedPoints ++;
}
}
}
}
if(Points > 1) {
long double CoVar = (SquareDiff)/(Points-1);
if (MissedPoints > 0) {
std::cout << "There were " << MissedPoints << " number of mismatched dates in the calculation of covariance."
<< std::endl;
}
return CoVar;
} else {
std::cout << "Error in covariance calculation, less than 2 points were entered." << std::endl;
return 0;
}
}
long double ReturnsCorrCoef(const Asset &Asset1, const Asset &Asset2, CustomDate StartDate_, CustomDate EndDate_) {
CustomDate StartDate = Asset1.EarliestDateCheck(StartDate_);
StartDate = Asset2.EarliestDateCheck(StartDate);
CustomDate EndDate = Asset1.LatestDateCheck(EndDate_);
EndDate = Asset2.LatestDateCheck(EndDate);
long double Mean1 = Asset1.ReturnsMean(StartDate, EndDate);
long double Mean2 = Asset2.ReturnsMean(StartDate, EndDate);
long double SquareDiffBoth = 0;
long double SquareDiff1 = 0;
long double SquareDiff2 = 0;
unsigned int Points = 0;
unsigned int MissedPoints = 0;
for(auto Returns1 : Asset1.AssetReturns) {
if (Returns1.GetIsInitialised()) {
if(Returns1.GetDate() >= StartDate && Returns1.GetDate() <= EndDate) {
DailyReturns Returns2 = Asset2.ReturnsDateSearch(Returns1.GetDate());
if (Returns2.GetIsInitialised()) {
double long Value1 = (Returns1.GetReturns() - Mean1);
double long Value2 = (Returns2.GetReturns() - Mean2);
SquareDiffBoth += Value1*Value2;
SquareDiff1 += Value1*Value1;
SquareDiff2 += Value2*Value2;
Points ++;
} else {
MissedPoints ++;
}
}
}
}
if(Points > 1) {
long double CoVar = (SquareDiffBoth)/ static_cast<long double>(Points-1);
long double Var1 = (SquareDiff1)/ static_cast<long double>(Points-1);
long double Var2 = (SquareDiff2)/ static_cast<long double>(Points-1);
long double StdDev1 = sqrt(Var1);
long double StdDev2 = sqrt(Var2);
long double CorrCoef = CoVar/(StdDev1*StdDev2);
if (MissedPoints > 0) {
std::cout << "There were " << MissedPoints << " number of mismatched dates in the calculation of correlation coefficient."
<< std::endl;
}
return CorrCoef;
} else {
std::cout << "Error in correlation coefficient calculation, less than 2 points were entered." << std::endl;
return 0;
}
}
long double ReturnsBeta(const Asset &Asset_, const Asset &Index_, CustomDate StartDate_, CustomDate EndDate_) {
CustomDate StartDate = Asset_.EarliestDateCheck(StartDate_);
StartDate = Index_.EarliestDateCheck(StartDate);
CustomDate EndDate = Asset_.LatestDateCheck(EndDate_);
EndDate = Index_.LatestDateCheck(EndDate);
long double MeanAsset = Asset_.ReturnsMean(StartDate, EndDate);
long double MeanIndex = Index_.ReturnsMean(StartDate, EndDate);
long double SquareDiffBoth = 0;
long double SquareDiffIndex = 0;
unsigned int Points = 0;
unsigned int MissedPoints = 0;
for(auto ReturnsAsset : Asset_.AssetReturns) {
if (ReturnsAsset.GetIsInitialised()) {
if(ReturnsAsset.GetDate() >= StartDate && ReturnsAsset.GetDate() <= EndDate) {
DailyReturns ReturnsIndex = Index_.ReturnsDateSearch(ReturnsAsset.GetDate());
if (ReturnsIndex.GetIsInitialised()) {
double long ValueAsset = (ReturnsAsset.GetReturns() - MeanAsset);
double long ValueIndex = (ReturnsIndex.GetReturns() - MeanIndex);
SquareDiffBoth += ValueAsset*ValueIndex;
SquareDiffIndex += ValueIndex*ValueIndex;
Points ++;
} else {
MissedPoints ++;
}
}
}
}
if(Points > 1) {
long double CoVar = (SquareDiffBoth)/(Points-1);
long double IndexVar = (SquareDiffIndex)/(Points-1);
long double CorrCoef = CoVar/(IndexVar);
if (MissedPoints > 0) {
std::cout << "There were " << MissedPoints << " number of mismatched dates in the calculation of beta."
<< std::endl;
}
return CorrCoef;
} else {
std::cout << "Error in beta calculation, less than 2 points were entered." << std::endl;
return 0;
}
}
//// Utility Functions ////
std::string Asset::GetIDStr() const { return ID; }
bool Asset::GetIsInitialised() const { return IsInitialised; }
void Asset::DumptoConsole() const {
std::cout << Header;
for(auto i : DataSet) {
std::cout << i;
}
return;
}
void Asset::DumptoCSV(std::string Filename_) const {
std::ofstream CSVfile;
CSVfile.open (Filename_);
CSVfile << Header;
for(auto i : DataSet) {
CSVfile << i;
}
return;
}
void Asset::DumpReturnstoConsole() const {
unsigned int ColWidth = 12;
std::cout << std::setfill (' ') << std::setw (ColWidth) << "Date"
<< std::setfill (' ') << std::setw (ColWidth+2) << "Returns" << std::endl;
for(auto Returns : AssetReturns) {
std::cout << std::setfill (' ') << std::setw (ColWidth) << std::setprecision(3) << Returns.GetDate().GetDateStd()
<< std::setfill (' ') << std::setw (ColWidth) << std::setprecision(3) << Returns.GetReturns()*100.0 << " %" << std::endl;
}
return;
}
CustomDate Asset::EarliestDateCheck(CustomDate StartDate_) const {
if (StartDate_ >= EarliestAvailableDate) {
return StartDate_;
} else {
std::cout << "The date entered is before the earliest available date of the data present and has been replace with "
<< EarliestAvailableDate.GetDateStd() << "." << std::endl;
return EarliestAvailableDate;
}
}
CustomDate Asset::LatestDateCheck(CustomDate EndDate_) const {
if (EndDate_ <= LatestAvailableDate) {
return EndDate_;
} else {
std::cout << "The date entered is after the latest available date of the data present and has been replace with "
<< LatestAvailableDate.GetDateStd() << "." << std::endl;
return LatestAvailableDate;
}
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#ifndef UNIX_DESKTOP_FILE_CHOOSER_H
#define UNIX_DESKTOP_FILE_CHOOSER_H
#include "adjunct/desktop_pi/desktop_file_chooser.h"
#include "modules/hardcore/mh/messobj.h"
#include "platforms/quix/toolkits/ToolkitFileChooser.h"
class UnixDesktopFileChooser
: public DesktopFileChooser
, public ToolkitFileChooserListener
, public MessageObject
{
public:
UnixDesktopFileChooser(ToolkitFileChooser* toolkit_chooser);
virtual ~UnixDesktopFileChooser();
// From DesktopFileChooser
virtual OP_STATUS Execute(OpWindow* parent,
DesktopFileChooserListener* listener,
const DesktopFileChooserRequest& request);
virtual void Cancel();
// From ToolkitFileChooserListener
virtual bool OnSaveAsConfirm(ToolkitFileChooser* chooser);
virtual void OnChoosingDone(ToolkitFileChooser* chooser);
// From MessageObject
virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
private:
ToolkitFileChooser* m_chooser;
DesktopFileChooserListener* m_listener;
};
#endif // UNIX_DESKTOP_FILE_CHOOSER_H
|
#include "UserRole.h"
#include <QString>
// :: Constants ::
const QString JSON_USER_ROLE_USER = "User";
const QString JSON_USER_ROLE_ADMIN = "Admin";
const QString USER_ROLE_USER_STRING = "Пользователь";
const QString USER_ROLE_ADMIN_STRING = "Администратор";
// :: Public functions ::
QString userRoleToJson(UserRole role) {
switch (role) {
case UserRole::User: return JSON_USER_ROLE_USER;
case UserRole::Admin: return JSON_USER_ROLE_ADMIN;
default: return QString();
}
}
UserRole userRoleFromJson(const QString &json) {
if (json == JSON_USER_ROLE_ADMIN) {
return UserRole::Admin;
} else {
return UserRole::User;
}
}
QString userRoleToString(UserRole role) {
switch (role) {
case UserRole::User: return USER_ROLE_USER_STRING;
case UserRole::Admin: return USER_ROLE_ADMIN_STRING;
default: return QString();
}
}
|
#pragma once
#include "Visitor.h"
#include "Table.h"
#include "Frame.h"
#include "Wrappers.h"
#include <assert.h>
#include <vector>
namespace Translate {
// Вспомогательная структура для хранения информации о фрагментах
struct CFragment {
CFragment( const Frame::CFrame* _frame, const IRTree::IStm* _rootStm, std::string& _name ) :
methodFrame( _frame ), rootStatement( _rootStm ), fullMethodName( _name ) {}
const Frame::CFrame* methodFrame; // указатель на фрейм метода
const IRTree::IStm* rootStatement; // указатель на корневую инструкцию метода
std::string fullMethodName; // вспомогательное поле, хранящее название метода
};
class CTranslate : public IVisitor
{
public:
CTranslate( CSymbolsTable::CTable* _table ) :
table( _table ),
currentFrame( NULL ), currentClass( NULL ), currentMethod( NULL ), expList( NULL ) {
assert( _table != NULL );
}
void Visit( const CProgram* node );
void Visit( const CMainClassDeclaration* node );
void Visit( const CClassDeclaration* node );
void Visit( const CClassExtendsDeclaration* node );
void Visit( const CClassDeclarationList* node );
void Visit( const CVariableDeclaration* node );
void Visit( const CVariableDeclarationList* node );
void Visit( const CMethodDeclaration* node );
void Visit( const CMethodDeclarationList* node );
void Visit( const CFormalList* node );
void Visit( const CFormalRestList* node );
void Visit( const CBuiltInType* node );
void Visit( const CUserType* node );
void Visit( const CStatementList* node );
void Visit( const CStatementBlock* node );
void Visit( const CIfStatement* node );
void Visit( const CWhileStatement* node );
void Visit( const CPrintStatement* node );
void Visit( const CAssignmentStatement* node );
void Visit( const CArrayElementAssignmentStatement* node );
void Visit( const CBinaryOperatorExpression* node );
void Visit( const CIndexAccessExpression* node );
void Visit( const CLengthExpression* node );
void Visit( const CMethodCallExpression* node );
void Visit( const CIntegerOrBooleanExpression* node );
void Visit( const CIdentifierExpression* node );
void Visit( const CThisExpression* node );
void Visit( const CNewIntegerArrayExpression* node );
void Visit( const CNewObjectExpression* node );
void Visit( const CNegationExpression* node );
void Visit( const CParenthesesExpression* node );
void Visit( const CExpressionList* node );
// метод представляет собой указатель на фрейм и вершину дерева
// std::vector<std::pair< const Frame::CFrame*, const IRTree::IStm* > > Methods;
std::vector<CFragment> Methods;
private:
CSymbolsTable::CClassInformation* currentClass; // Текущий класс, в котором находится посетитель
CSymbolsTable::CMethodInformation* currentMethod; // Текущий метод
CSymbolsTable::CTable* table; // таблица, к которой мы обращаемся
Frame::CFrame* currentFrame; // текущий фрейм вызова метода
Translate::ISubtreeWrapper* lastWrapper; // узел, который "возвращаем"
IRTree::CExpList* expList; // вспомогательная переменная, при помощи которой собираем список из CExp
};
}
|
#include <fstream>
#include "harris_mini_opt.h"
int main() {
ofstream in_pix("input_pixels_regression_result_harris_mini_opt.txt");
ofstream fout("regression_result_harris_mini_opt.txt");
HWStream<hw_uint<32> > img_update_0_read;
HWStream<hw_uint<32> > harris_mini_update_0_write;
// Loading input data
// cmap : { img_update_0[root = 0, img_0, img_1] -> img_oc[0, 0] : -2 <= img_0 <= 33 and -2 <= img_1 <= 33 }
// read map: { img_oc[0, 0] -> img_update_0[root = 0, img_0, img_1] : -2 <= img_0 <= 33 and -2 <= img_1 <= 33 }
// rng : { img_update_0[root = 0, img_0, img_1] : -2 <= img_0 <= 33 and -2 <= img_1 <= 33 }
for (int i = 0; i < 1296; i++) {
hw_uint<32> in_val;
set_at<0*32, 32, 32>(in_val, 1*i + 0);
in_pix << in_val << endl;
img_update_0_read.write(in_val);
}
harris_mini_opt(img_update_0_read, harris_mini_update_0_write);
for (int i = 0; i < 1024; i++) {
hw_uint<32> actual = harris_mini_update_0_write.read();
auto actual_lane_0 = actual.extract<0*32, 31>();
fout << actual_lane_0 << endl;
}
in_pix.close();
fout.close();
return 0;
}
|
#include "tgaimage.h"
#include "geometry.h"
bool is_steep(int, int, int, int);
void line(int x0, int y0, int x1, int y1, TGAImage &image, TGAColor color) {
bool steep = is_steep(x0, x1, y0, y1);
if (steep) {
std::swap(x0, y0);
std::swap(x1, y1);
}
if (x0 > x1) {
std::swap(x0, x1);
std::swap(y0, y1);
}
int dx = x1 - x0;
int dy = y1 - y0;
int derror2 = std::abs(dy) * 2;
int error2 = 0;
int y = y0;
for (int x = x0; x <= x1; x++) {
if (steep) {
image.set(y, x, color);
} else {
image.set(x, y, color);
}
error2 += derror2;
if (error2 > dx) {
y += (y1 > y0 ? 1 : -1);
error2 -= dx * 2;
}
}
}
void line(Vec2i t0, Vec2i t1, TGAImage &image, TGAColor color) {
line(t0.x, t0.y, t1.x, t1.y, image, color);
}
bool is_steep(int x0, int x1, int y0, int y1) {
return std::abs(x0 - x1) < std::abs(y0 - y1);
}
|
//
// Created by 송지원 on 2020/05/22.
//
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char stra[51];
char strb[51];
int lena, lenb;
int min = 50;
scanf("%s%s", stra, strb);
lena = strlen(stra);
lenb = strlen(strb);
for (int i=0; i<=lenb - lena; i++) {
int temp = 0;
for (int j=0; j<lena; j++) {
if (stra[j] != strb[i+j]) {
temp++;
}
}
if (temp < min) {
min = temp;
}
}
printf("%d", min);
}
|
#include <bits/stdc++.h>
using namespace std;
//const int maxn = 100 + 5;
//int a[maxn]; n;
/*void quicksort(int l, int r) {
int t, temp;
if(l > r) return;
temp = a[l]; // temp是基准数
while(l != r) {
while(l < r && a[r] >= temp) l--;
while(l < r && a[l] <= temp) r++;
if(r < l) {
t = a[r];
a[r] = a[l];
a[l] = t;
}
}
a[l]
}
*/
void quicksort(int a[], int low, int hight) {
if(low >= hight) return;
int l = low;
int r = hight;
int key = a[l];
while(l != r) {
while(l != r && a[r] >= key) r--;
a[l] = a[r];
while(l != r && a[l] <= key) l++;
a[r] = a[l];
a[l] = key;
}
quicksort(a, low, l - 1);
quicksort(a, l + 1, hight);
}
|
/*
* robot_info.cpp
* Copyright: 2018 Shanghai Yikun Electrical Engineering Co,Ltd
*/
#include "yikun_common/cluster_manager/robot_info.h"
namespace yikun_common {
RobotInfo::RobotInfo(const Robot robot)
: robot_(robot)
{
db_ = boost::make_shared<DbHelper>(robot_.addr,"yk");
cluster_db_ = boost::make_shared<DbHelper>("127.0.0.1","yk");
}
RobotInfo::~RobotInfo()
{}
bool RobotInfo::connect()
{
if(cluster_db_->dbconnect() && db_->dbconnect()) {
return true;
}
return false;
}
bool RobotInfo::disconnect()
{
if(cluster_db_->dbdisconnect() && db_->dbdisconnect()) {
return true;
}
return false;
}
float RobotInfo::checkCommunication()
{
if(db_.use_count() == 0) {
ROS_ERROR("db has not initialized!!!");
return -1;
}
std::string out;
std::cout<<robot_.addr<<std::endl;
float time_delay = SystemHelper::ping(robot_.addr,out);
// std::cout<<robot_.addr<<std::endl;
if(cluster_db_->updateTimeDelay(robot_.id,time_delay)) {
// ROS_INFO("%s: %fms",robot_.hostname.data(),time_delay);
}
return time_delay;
}
bool RobotInfo::getRuntimeInfo(RuntimeInfo &info)
{
if(db_.use_count() == 0) {
ROS_ERROR("db has not initialized!!!");
return false;
}
if(db_->getRuntimeInfo(info)) {
// int id = atoi(info.map_id.c_str());
// info.map_id.erase();
// if(db_->getMapStrId(info.map_id,id)) {
return true;
// }
}
return false;
}
}//namespace
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
#include <time.h>
#include <ctype.h>
#include "adjunct/m2/src/backend/smtp/smtp-protocol.h"
#include "adjunct/m2/src/engine/account.h"
#include "adjunct/m2/src/backend/smtp/smtpmodule.h"
#include "adjunct/m2/src/engine/engine.h"
#include "adjunct/m2/src/util/authenticate.h"
#include "adjunct/m2/src/util/misc.h"
#include "adjunct/m2/src/util/qp.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/url/protocols/comm.h"
#include "modules/util/str.h"
#include "modules/util/excepts.h"
static const char SMTP_EmptySenderAddr[] = "root@localhost.com";
static const char SMTP_EmptyField[] = " ";
static const char SMTP_HELO_start[] = "HELO ";
static const char SMTP_HELO_end[] = "\r\n";
static const char SMTP_EHLO_start[] = "EHLO ";
static const char SMTP_EHLO_end[] = "\r\n";
static const char SMTP_MAIL_start[] = "MAIL FROM:<";
static const char SMTP_MAIL_end[] = ">\r\n";
static const char SMTP_RCPT_start[] = "RCPT TO:<";
static const char SMTP_RCPT_end[] = ">\r\n";
static const char SMTP_DATA_cmd[] = "DATA\r\n";
static const char SMTP_content_end[] = "\r\n.\r\n";
static const char SMTP_RSET_cmd[] = "RSET\r\n";
static const char SMTP_QUIT_cmd[] = "QUIT\r\n";
static const char SMTP_STARTTLS_cmd[] = "STARTTLS\r\n";
static const char SMTP_AUTH_start[] = "AUTH ";
static const char SMTP_AUTH_end[] = "\r\n";
#define SMTP_HELO_start_len STRINGLENGTH(SMTP_HELO_start)
#define SMTP_HELO_end_len STRINGLENGTH(SMTP_HELO_end)
#define SMTP_EHLO_start_len STRINGLENGTH(SMTP_EHLO_start)
#define SMTP_EHLO_end_len STRINGLENGTH(SMTP_EHLO_end)
#define SMTP_MAIL_start_len STRINGLENGTH(SMTP_MAIL_start)
#define SMTP_MAIL_end_len STRINGLENGTH(SMTP_MAIL_end)
#define SMTP_RCPT_start_len STRINGLENGTH(SMTP_RCPT_start)
#define SMTP_RCPT_end_len STRINGLENGTH(SMTP_RCPT_end)
#define SMTP_DATA_cmd_len STRINGLENGTH(SMTP_DATA_cmd)
#define SMTP_content_end_len STRINGLENGTH(SMTP_content_end)
#define SMTP_RSET_cmd_len STRINGLENGTH(SMTP_RSET_cmd)
#define SMTP_QUIT_cmd_len STRINGLENGTH(SMTP_QUIT_cmd)
#define SMTP_STARTTLS_cmd_len STRINGLENGTH(SMTP_STARTTLS_cmd)
#define SMTP_AUTH_start_len STRINGLENGTH(SMTP_AUTH_start)
#define SMTP_AUTH_end_len STRINGLENGTH(SMTP_AUTH_end)
//********************************************************************
SMTP::SMTP(SmtpBackend* smtp_backend)
: m_smtp_backend(smtp_backend),
// m_port ?
m_is_connected(FALSE),
m_is_secure_connection(FALSE),
m_is_authenticated(FALSE),
m_is_sending_mail(FALSE),
m_current_message_info(NULL),
m_to_item(NULL),
m_cc_item(NULL),
m_bcc_item(NULL),
m_first_command_after_starttls(FALSE),
m_connection_has_failed(FALSE),
m_is_uploading(FALSE), //This is set to FALSE now and when GetNextBlock returns done=TRUE
m_content_finished(FALSE), //This is set to TRUE when comm is finished sending data
m_reply_buf(NULL),
m_reply_buf_len(0),
m_reply_buf_loaded(0),
m_what_to_send(SMTP_SEND_NOTHING),
m_error(SMTP_NO_REPLY),
// m_successful_rcpt ?
m_request(NULL),
m_request_buf_len(0),
m_rfc822_message_start(NULL),
m_rfc822_message_remaining(NULL),
// m_message_size ?
// m_message_size_remaining ?
m_servercapabilities(0),
m_network_buffer_size(g_pcnet->GetIntegerPref(PrefsCollectionNetwork::NetworkBufferSize) * 1024),
m_sent(0)
{
m_previous_buffer_end[0] = m_previous_buffer_end[1] = 0;
}
SMTP::~SMTP()
{
StopLoading();
if (m_request)
{
FreeMem(m_request);
m_request = NULL;
}
OP_DELETEA(m_rfc822_message_start);
OP_DELETEA(m_reply_buf);
}
OP_STATUS SMTP::Init(const OpStringC8& servername, UINT16 port)
{
m_is_sending_mail = FALSE;
m_port = port;
return m_servername.Set(servername);
}
//********************************************************************
OP_STATUS SMTP::CheckRequestBuf(int min_len)
{
if (!m_request)
{
m_request_buf_len = max(SMTP_REQ_BUF_MIN_LEN, min_len);
m_request = AllocMem(m_request_buf_len);
if (!m_request)
return OpStatus::ERR_NO_MEMORY;
}
else if (min_len > m_request_buf_len)
{ //Don't we have a realloc?
char* old_buffer = m_request;
int old_buffer_len = m_request_buf_len;
m_request_buf_len = min_len;
m_request = AllocMem(m_request_buf_len);
if (!m_request)
return OpStatus::ERR_NO_MEMORY;
op_memcpy(m_request, old_buffer, old_buffer_len); // Copies complete old buffer including NULL-termination
FreeMem(old_buffer);
}
return OpStatus::OK;
}
void SMTP::RequestMoreData()
{
if (m_what_to_send == SMTP_SEND_content && !m_content_finished)
{
char* buffer = NULL;
int buffer_len = 0;
if (m_rfc822_message_start && m_is_uploading)
{
buffer = AllocMem(m_network_buffer_size+1); //Don't use m_request here, as its content might not be sent yet
if (!buffer)
{
//#pragma PRAGMAMSG("FG: OOM [20020710]")
buffer_len = 0;
}
else
{
buffer_len = min(m_message_size_remaining, m_network_buffer_size);
memcpy(buffer, m_rfc822_message_remaining, buffer_len);
buffer[buffer_len]=0;
if (buffer_len >= m_message_size_remaining)
{
m_is_uploading = FALSE;
OP_DELETEA(m_rfc822_message_start);
m_rfc822_message_start = m_rfc822_message_remaining = NULL;
m_message_size_remaining = 0;
if (buffer_len==0) //This should not happen...
{
FreeMem(buffer);
buffer_len = 0;
buffer = NULL;
}
}
else
{
m_rfc822_message_remaining += buffer_len;
m_message_size_remaining -= buffer_len;
}
if (AddDotPrefix(&buffer) != OpStatus::OK)
{
buffer_len = 0;
buffer = NULL;
}
else
{
buffer_len = op_strlen(buffer);
}
//we don't know the length of the queue here, or if there is one, so we don't report count
//m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::SENDING_MESSAGES);
m_smtp_backend->GetProgress().SetSubProgress(m_message_size-m_message_size_remaining, m_message_size);
}
}
if (buffer)
{
m_previous_buffer_end[0] = buffer_len>1 ? buffer[buffer_len-2] : (char)0;
m_previous_buffer_end[1] = buffer_len>0 ? buffer[buffer_len-1] : (char)0;
}
else
{
m_previous_buffer_end[0] = m_previous_buffer_end[1] = 0;
buffer_len = SMTP_content_end_len;
buffer = AllocMem(buffer_len+1);
if (!buffer)
{
//#pragma PRAGMAMSG("FG: OOM [20020710]")
buffer_len = 0;
}
else
{
op_strcpy(buffer, SMTP_content_end); // "\r\n.\r\n"
m_content_finished = TRUE;
}
}
SendData(buffer, buffer_len);
buffer = NULL; //the buffer is taken over by communication, we need a new one
}
}
//********************************************************************
char* SMTP::ComposeRequest(int& len)
{
switch (m_what_to_send)
{
case SMTP_SEND_STARTTLS:
{
len = SMTP_STARTTLS_cmd_len;
CheckRequestBuf(len+1);
sprintf(m_request,"%s", SMTP_STARTTLS_cmd);
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::AUTHENTICATING);
break;
}
case SMTP_SEND_EHLO:
{
//m_rcpt_idx = 0;
m_successful_rcpt = 0;
OpString fqdn;
OpString8 fqdn8;
Account* account_ptr = m_smtp_backend->GetAccountPtr();
if (account_ptr)
{
if (account_ptr->GetFQDN(fqdn)==OpStatus::OK)
{
OpStatus::Ignore(OpMisc::ConvertToIMAAAddress(UNI_L(""), fqdn, fqdn8));
}
}
if (fqdn8.IsEmpty())
{
fqdn8.Set("error.opera.illegal");
}
len = SMTP_EHLO_start_len + fqdn8.Length() + SMTP_EHLO_end_len;
CheckRequestBuf(len+1);
sprintf(m_request,"%s%s%s", SMTP_EHLO_start, fqdn8.HasContent() ? fqdn8.CStr() : "", SMTP_EHLO_end);
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::AUTHENTICATING);
break;
}
case SMTP_SEND_HELO:
{
m_successful_rcpt = 0;
const char* localhostname = NULL;
localhostname = Comm::GetLocalHostName();
if (!localhostname)
{
localhostname = "error.opera.illegal";
}
len = op_strlen(localhostname) + SMTP_HELO_start_len + SMTP_HELO_end_len;
CheckRequestBuf(len+1);
sprintf(m_request,"%s%s%s", SMTP_HELO_start, localhostname, SMTP_HELO_end);
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::CONNECTING);
break;
}
case SMTP_SEND_MAIL:
{
const char* senderaddr = 0;
OpString8 email_adr;
if (!m_current_message_info->m_anonymous)
{
OP_STATUS ret;
if ((ret=email_adr.Set(m_from)) != OpStatus::OK)
{
len = 0;
return NULL;
}
if (email_adr.IsEmpty())
{
if ((ret=m_smtp_backend->GetAccountPtr()->GetEmail(email_adr)) != OpStatus::OK)
{
len = 0;
return NULL;
}
}
senderaddr = email_adr.CStr();
}
if (!senderaddr)
{
senderaddr = SMTP_EmptySenderAddr;
}
len = op_strlen(senderaddr) + SMTP_MAIL_start_len + SMTP_MAIL_end_len;
CheckRequestBuf(len+1);
sprintf(m_request,"%s%s%s", SMTP_MAIL_start, senderaddr, SMTP_MAIL_end);
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::SENDING_MESSAGES);
break;
}
case SMTP_SEND_RCPT:
{
OP_STATUS ret;
OpString8 email_adr;
const Header::From* temp_item = NULL;
if (m_to_item)
{
temp_item = m_to_item;
m_to_item = (Header::From*)m_to_item->Suc();
}
else if (m_cc_item)
{
temp_item = m_cc_item;
m_cc_item = (Header::From*)m_cc_item->Suc();
}
else if (m_bcc_item)
{
temp_item = m_bcc_item;
m_bcc_item = (Header::From*)m_bcc_item->Suc();
}
if (!temp_item)
{
len=0;
return NULL;
}
BOOL imaa_failed = FALSE;
if ((ret=temp_item->GetIMAAAddress(email_adr, &imaa_failed)) != OpStatus::OK || imaa_failed)
{
len=0;
return NULL;
}
len = email_adr.Length() + SMTP_RCPT_start_len + SMTP_RCPT_end_len;
CheckRequestBuf(len+1);
sprintf(m_request, "%s%s%s", SMTP_RCPT_start, email_adr.CStr(), SMTP_RCPT_end);
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::SENDING_MESSAGES);
break;
}
case SMTP_SEND_DATA:
{
len = SMTP_DATA_cmd_len;
CheckRequestBuf(len+1);
sprintf(m_request,"%s", SMTP_DATA_cmd);
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::SENDING_MESSAGES);
break;
}
case SMTP_SEND_content:
{
OP_ASSERT(m_is_sending_mail);
if (!m_is_sending_mail)
{
len = 0;
return NULL;
}
CheckRequestBuf(m_network_buffer_size+1);
len = min(m_message_size_remaining, m_request_buf_len-1);
memcpy(m_request, m_rfc822_message_remaining, len);
m_request[len]=0;
if (len >= m_message_size_remaining)
{
m_is_uploading = FALSE;
OP_DELETEA(m_rfc822_message_start);
m_rfc822_message_start = m_rfc822_message_remaining = NULL;
m_message_size_remaining = 0;
}
else
{
m_is_uploading = TRUE;
m_rfc822_message_remaining += len;
m_message_size_remaining -= len;
}
if (AddDotPrefix(&m_request) != OpStatus::OK)
{
len = 0;
return NULL;
}
else
{
len = op_strlen(m_request);
}
m_previous_buffer_end[0] = (len>1 && m_is_uploading) ? m_request[len-2] : (char)0;
m_previous_buffer_end[1] = (len>0 && m_is_uploading) ? m_request[len-1] : (char)0;
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::SENDING_MESSAGES);
m_smtp_backend->GetProgress().SetSubProgress(m_message_size-m_message_size_remaining, m_message_size);
break;
}
case SMTP_SEND_RSET:
{
len = SMTP_RSET_cmd_len;
CheckRequestBuf(len+1);
sprintf(m_request,"%s", SMTP_RSET_cmd);
break;
}
case SMTP_SEND_AUTH:
{
AccountTypes::AuthenticationType authmethod = m_smtp_backend->GetAuthenticationMethod();
OP_ASSERT(authmethod!=AccountTypes::NONE); //Shouldn't get here if no authentication is requested
#ifdef AUTODETECT_SMTP_PLAINTEXT_AUTH
if (authmethod==AccountTypes::PLAIN && m_smtp_backend->GetCurrentAuthMethod()!=AccountTypes::LOGIN) //PLAIN should first try LOGIN, then PLAIN (no reason to let users choose between them, it will only clutter UI)
authmethod = AccountTypes::LOGIN;
#endif
if (authmethod == AccountTypes::AUTOSELECT)
{
authmethod = m_smtp_backend->GetCurrentAuthMethod();
if (authmethod == AccountTypes::AUTOSELECT)
authmethod = GetNextAuthenticationMethod(authmethod);
}
m_smtp_backend->SetCurrentAuthMethod(authmethod);
const char* authtype = 0;
switch(m_smtp_backend->GetCurrentAuthMethod())
{
case AccountTypes::PLAIN:
authtype = "PLAIN";
break;
case AccountTypes::LOGIN:
authtype = "LOGIN";
break;
case AccountTypes::CRAM_MD5:
authtype = "CRAM-MD5";
break;
case AccountTypes::NONE: //Fallthrough
default:
authtype = "unsupported";
OP_ASSERT(!"Should never try to send unsupported authentication methods");
break;
}
len = op_strlen(authtype) + SMTP_AUTH_start_len + SMTP_AUTH_end_len + 3;
CheckRequestBuf(len+1);
sprintf(m_request,"%s%s%s", SMTP_AUTH_start, authtype, SMTP_AUTH_end);
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::AUTHENTICATING);
}
break;
case SMTP_SEND_AUTH_PLAIN:
case SMTP_SEND_AUTH_LOGIN_USER:
case SMTP_SEND_AUTH_LOGIN_PASS:
case SMTP_SEND_AUTH_CRAMMD5:
{
OpAuthenticate login_info;
const OpStringC8* response;
len = 0;
RETURN_VALUE_IF_ERROR(m_smtp_backend->GetLoginInfo(login_info, m_server_challenge), 0);
if (m_what_to_send == SMTP_SEND_AUTH_LOGIN_USER)
response = &login_info.GetUsername();
else if (m_what_to_send == SMTP_SEND_AUTH_LOGIN_PASS)
response = &login_info.GetPassword();
else
response = &login_info.GetResponse();
len = response->Length() + SMTP_AUTH_end_len;
CheckRequestBuf(len + 1);
sprintf(m_request, "%s%s", response->CStr(), SMTP_AUTH_end);
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::AUTHENTICATING);
}
break;
/*
case SMTP_SEND_AUTH_DIGESTMD5:
{
}
break;
*/
case SMTP_SEND_QUIT:
{
len = SMTP_QUIT_cmd_len;
CheckRequestBuf(len+1);
sprintf(m_request,"%s", SMTP_QUIT_cmd);
break;
}
default:
len = 0;
break;
}
m_smtp_backend->Log("SMTP OUT : ", m_request);
if (m_request)
{
len = op_strlen(m_request);
}
return m_request;
}
//********************************************************************
int SMTP::CheckReply()
{
OP_NEW_DBG("SMTP::CheckReply", "m2");
m_smtp_backend->Log("SMTP IN : ", m_reply_buf);
if (m_reply_buf_loaded > 3)
{
char *tmp = m_reply_buf;
while (tmp)
{
char* tmp2 = op_strchr(tmp, '\n');
if (tmp2 && *tmp>='0' && *tmp<='9')
{
if (*(tmp+3) == '-')
tmp = tmp2+1;
else
{
m_reply_buf_loaded = 0;
return atoi(tmp);
}
}
else
tmp = 0;
}
}
OP_DBG(("SMTP::Error:?? No reply!!\r\n"));
return SMTP_NO_REPLY;
}
//********************************************************************
OP_STATUS SMTP::ProcessReceivedData()
{
OP_NEW_DBG("SMTP::ProcessReceivedData", "m2");
m_connection_has_failed = FALSE;
int cnt_len;
if (m_reply_buf_len-m_reply_buf_loaded <= 512)
{
int new_len = m_reply_buf_len + 1024;
char *tmp = OP_NEWA(char, new_len);
if (!tmp)
return OpStatus::ERR_NO_MEMORY;
memcpy(tmp, m_reply_buf, (int)m_reply_buf_loaded);
OP_DELETE(m_reply_buf);
m_reply_buf = tmp;
m_reply_buf_len = new_len;
}
cnt_len = ReadData(m_reply_buf+m_reply_buf_loaded, m_reply_buf_len-m_reply_buf_loaded-1);
if (cnt_len <= 0)
{
return OpStatus::ERR;
}
*(m_reply_buf+m_reply_buf_loaded+cnt_len) = '\0';
m_reply_buf_loaded += cnt_len;
m_first_command_after_starttls = FALSE;
OP_DBG((m_reply_buf));
int reply = CheckReply();
if (reply == SMTP_NO_REPLY)
return OpStatus::ERR;
switch (m_what_to_send)
{
case SMTP_SEND_NOTHING: //first
if (reply == SMTP_220_service_ready)
{
m_is_connected = TRUE;
m_what_to_send = SMTP_SEND_EHLO;
}
else
{
switch(reply)
{
case SMTP_421_unavailable: m_error = ERR_SMTP_SERVICE_UNAVAILABLE; break;
default: m_error = ERR_SMTP_INTERNAL_ERROR;
}
}
break;
case SMTP_SEND_STARTTLS:
if (reply == SMTP_220_service_ready)
{
if(StartTLSConnection()) // Start TLS authentication
{
m_is_secure_connection = TRUE;
m_servercapabilities = 0; //A client must forget about old server capabilities after starting a TLS connection
m_what_to_send = SMTP_SEND_EHLO;
m_first_command_after_starttls = TRUE;
}
else
{
// Failed to start TLS authentication
m_is_secure_connection = FALSE;
m_error = ERR_SMTP_SERVICE_UNAVAILABLE;
m_what_to_send = SMTP_SEND_QUIT;
}
}
else if (reply == SMTP_454_TLS_not_available)
{
// TLS authentication not available right now
m_is_secure_connection = FALSE;
m_error = ERR_SMTP_SERVICE_UNAVAILABLE;
m_what_to_send = SMTP_SEND_QUIT;
}
else
{
// Does not support TLS
m_is_secure_connection = FALSE;
m_error = ERR_SMTP_SERVICE_UNAVAILABLE;
m_what_to_send = SMTP_SEND_QUIT;
}
break;
case SMTP_SEND_HELO:
if (reply == SMTP_250_mail_ok)
{
OpStatus::Ignore(Parse250Response()); //updates m_servercapabilities
m_what_to_send = SMTP_SEND_MAIL;
m_error = SMTP_NO_REPLY;
}
else
{
m_content_finished = FALSE;
switch(reply)
{
case SMTP_421_unavailable: m_error = ERR_SMTP_SERVICE_UNAVAILABLE; break;
default: m_error = ERR_SMTP_INTERNAL_ERROR;
}
}
break;
case SMTP_SEND_EHLO:
if (reply == SMTP_250_mail_ok)
{
OpStatus::Ignore(Parse250Response()); //updates m_servercapabilities
RETURN_IF_ERROR(DetermineNextCommand(SMTP_SEND_EHLO));
}
else // try HELO which should be supported by all servers
{
m_content_finished = FALSE; // this is not an error, EHLO is optionally supported by the server
m_what_to_send = SMTP_SEND_HELO;
m_error = SMTP_NO_REPLY;
}
break;
case SMTP_SEND_AUTH:
{
if(reply == SMTP_334_continue_req)
{
switch (m_smtp_backend->GetCurrentAuthMethod())
{
case AccountTypes::CRAM_MD5: m_what_to_send = SMTP_SEND_AUTH_CRAMMD5; m_server_challenge.Set(m_reply_buf+4); break;
case AccountTypes::LOGIN: m_what_to_send = SMTP_SEND_AUTH_LOGIN_USER; break;
case AccountTypes::PLAIN: m_what_to_send = SMTP_SEND_AUTH_PLAIN; break;
default: m_what_to_send = SMTP_SEND_QUIT; m_error = ERR_SMTP_AUTHENTICATION_ERROR; break;
}
}
else if(reply == SMTP_235_go_ahead)
{
OP_ASSERT(0); //Is it possible to get here?
m_is_authenticated = TRUE;
m_what_to_send = SMTP_SEND_MAIL;
}
else if(reply == SMTP_535_auth_failure)
{
AskForPassword(m_reply_buf);
}
else
{
AccountTypes::AuthenticationType selected_auth = m_smtp_backend->GetAuthenticationMethod();
if (m_smtp_backend->GetCurrentAuthMethod() != AccountTypes::NONE &&
(selected_auth==AccountTypes::AUTOSELECT
#ifdef AUTODETECT_SMTP_PLAINTEXT_AUTH
|| selected_auth==AccountTypes::PLAIN
#endif
) )
{
m_smtp_backend->SetCurrentAuthMethod(GetNextAuthenticationMethod(m_smtp_backend->GetCurrentAuthMethod()));
if (m_smtp_backend->GetCurrentAuthMethod() == AccountTypes::NONE)
m_what_to_send = SMTP_SEND_MAIL;
else
m_what_to_send = SMTP_SEND_AUTH; //Try next authentication method
}
else
{
switch(reply)
{
case SMTP_421_unavailable:
case SMTP_500_syntax_error: m_error = ERR_SMTP_SERVICE_UNAVAILABLE; break;
default: m_error = ERR_SMTP_INTERNAL_ERROR;
}
}
}
}
break;
case SMTP_SEND_AUTH_LOGIN_USER:
{
if(reply == SMTP_334_continue_req)
{
m_what_to_send = SMTP_SEND_AUTH_LOGIN_PASS;
}
else
{
AskForPassword(m_reply_buf);
}
}
break;
case SMTP_SEND_AUTH_LOGIN_PASS:
{
if(reply == SMTP_235_go_ahead)
{
m_smtp_backend->SetCurrentAuthMethod(AccountTypes::LOGIN);
m_is_authenticated = TRUE;
m_what_to_send = SMTP_SEND_MAIL;
}
else //if(SMTP_535_auth_failure)
{
AskForPassword(m_reply_buf);
}
}
break;
case SMTP_SEND_AUTH_PLAIN:
{
if(reply == SMTP_235_go_ahead)
{
m_smtp_backend->SetCurrentAuthMethod(AccountTypes::PLAIN);
m_is_authenticated = TRUE;
m_what_to_send = SMTP_SEND_MAIL;
}
else //if(SMTP_535_auth_failure)
{
AskForPassword(m_reply_buf);
}
}
break;
case SMTP_SEND_AUTH_CRAMMD5:
{
if(reply == SMTP_235_go_ahead)
{
m_smtp_backend->SetCurrentAuthMethod(AccountTypes::CRAM_MD5);
m_is_authenticated = TRUE;
m_what_to_send = SMTP_SEND_MAIL;
}
else //if(SMTP_535_auth_failure)
{
AskForPassword(m_reply_buf);
}
}
break;
case SMTP_SEND_MAIL:
if (reply == SMTP_250_mail_ok)
{
m_what_to_send = SMTP_SEND_RCPT;
}
else
{
switch(reply)
{
case SMTP_421_unavailable: m_error = ERR_SMTP_SERVICE_UNAVAILABLE; break;
case SMTP_451_local_error:
case SMTP_452_insuff_sys_storage: m_error = ERR_SMTP_SERVER_TMP_ERROR; break;
case SMTP_552_storage_alloc_exeed: m_error = ERR_SMTP_SERVER_ERROR; break;
case SMTP_535_auth_failure: AskForPassword(m_reply_buf); break;
default: m_error = ERR_SMTP_INTERNAL_ERROR;
}
}
break;
case SMTP_SEND_RCPT:
if (reply == SMTP_250_mail_ok || reply == SMTP_251_user_not_local)
{
m_successful_rcpt++;
if (m_what_to_send == SMTP_SEND_RCPT && !m_to_item && !m_cc_item && !m_bcc_item)
{
m_what_to_send = SMTP_SEND_DATA;
}
}
else
{
switch(reply)
{
case SMTP_421_unavailable: m_error = ERR_SMTP_SERVICE_UNAVAILABLE; break;
case SMTP_450_mailbox_unavailable:
case SMTP_451_local_error:
case SMTP_452_insuff_sys_storage: m_error = ERR_SMTP_RCPT_ERROR; break;
case SMTP_500_syntax_error:
case SMTP_501_parm_syntax_error:
case SMTP_553_mailbox_not_allowed: m_error = ERR_SMTP_RCPT_ERROR; break;
case SMTP_550_mailbox_unavailable: m_error = ERR_SMTP_RCPT_ERROR; break;
case SMTP_551_user_not_local: m_error = ERR_SMTP_RCPT_ERROR; break;
case SMTP_552_storage_alloc_exeed: m_error = ERR_SMTP_SERVER_ERROR; break;
case SMTP_571_relay_not_allowed: m_error = ERR_SMTP_RCPT_ERROR; break;
default: m_error = ERR_SMTP_INTERNAL_ERROR;
}
}
break;
case SMTP_SEND_DATA:
if (reply == SMTP_354_start_input)
{
m_what_to_send = SMTP_SEND_content;
}
else
{
switch(reply)
{
case SMTP_421_unavailable: m_error = ERR_SMTP_SERVICE_UNAVAILABLE; break;
case SMTP_451_local_error: m_error = ERR_SMTP_SERVER_TMP_ERROR; break;
default: m_error = ERR_SMTP_INTERNAL_ERROR;
}
}
break;
case SMTP_SEND_content:
if (reply == SMTP_250_mail_ok)
{
m_sent++;
m_smtp_backend->GetProgress().UpdateCurrentAction();
if (m_smtp_backend->Sent(m_current_message_info->m_id, OpStatus::OK) != OpStatus::OK)
{
OpString errorstring;
OpStatus::Ignore(g_languageManager->GetString(Str::S_FAILED_MOVING_OUT_OF_OUTBOX, errorstring));
m_smtp_backend->OnError(errorstring);
}
m_message_queue.Delete(m_current_message_info);
m_current_message_info = NULL;
if (m_message_queue.GetCount()==0)
{
m_what_to_send = SMTP_SEND_QUIT;
}
else
{
OP_ASSERT(m_is_connected);
while (OpStatus::IsError(SendFirstQueuedMessage()))
{
if (m_message_queue.GetCount()==0)
{
m_what_to_send = SMTP_SEND_QUIT;
break;
}
}
//Bail out if SendFirstQueuedMessage has taken down the connection
if (!m_is_connected)
return OpStatus::OK;
}
}
else
{
switch(reply)
{
case SMTP_421_unavailable: m_error = ERR_SMTP_SERVICE_UNAVAILABLE; break;
case SMTP_451_local_error:
case SMTP_452_insuff_sys_storage: m_error = ERR_SMTP_SERVER_TMP_ERROR; break;
case SMTP_552_storage_alloc_exeed:
case SMTP_554_transaction_failed: m_error = ERR_SMTP_SERVER_ERROR; break;
default: m_error = ERR_SMTP_INTERNAL_ERROR;
}
}
break;
case SMTP_SEND_RSET:
{
//We have failed to send one message. Remove it from progress-information
m_smtp_backend->GetProgress().AddToCurrentAction(-1);
m_smtp_backend->GetProgress().UpdateCurrentAction(-1);
m_smtp_backend->GetProgress().SetSubProgress(0, 0);
m_message_queue.Delete(m_current_message_info);
m_current_message_info = NULL;
if (m_message_queue.GetCount()==0)
{
m_what_to_send = SMTP_SEND_QUIT;
}
else
{
OP_ASSERT(m_is_connected);
while (OpStatus::IsError(SendFirstQueuedMessage()))
{
if (m_message_queue.GetCount()==0)
{
m_what_to_send = SMTP_SEND_QUIT;
break;
}
}
//Bail out if SendFirstQueuedMessage has taken down the connection
if (!m_is_connected)
return OpStatus::OK;
}
}
break;
case SMTP_SEND_QUIT:
{
OP_DELETEA(m_rfc822_message_start);
m_rfc822_message_start = m_rfc822_message_remaining = NULL;
m_what_to_send = SMTP_SEND_NOTHING;
OnClose(OpStatus::OK); //Drop connection, we're done
return OpStatus::OK;
}
break;
default:
OP_ASSERT(0);
m_error = ERR_SMTP_INTERNAL_ERROR;
}
//Skip this mail if something failed
if (m_error!=SMTP_NO_REPLY && m_what_to_send!=SMTP_SEND_QUIT)
{
m_what_to_send = SMTP_SEND_RSET;
OpString server_string;
if (server_string.Set(m_reply_buf)==OpStatus::OK)
{
OpStatus::Ignore(ReportError(m_error, server_string));
m_error = SMTP_NO_REPLY;
}
}
int len;
ComposeRequest(len);
OP_DBG(("SMTP::m_request= %s\n", m_request));
if(m_request)
{
SendData(m_request, len);
m_request = NULL; //the buffer is taken over by communication, we need a new one
}
return OpStatus::OK;
}
//********************************************************************
OP_STATUS SMTP::DetermineNextCommand(int currentcommand)
{
switch(currentcommand)
{
case SMTP_SEND_EHLO:
{
OP_STATUS ret = OpStatus::OK;
if (!m_is_secure_connection) //Check if we should send STARTTLS
{
BOOL use_tls;
if ((ret=m_smtp_backend->GetUseSecureConnection(use_tls)) != OpStatus::OK)
{
return ret;
}
if (use_tls)
{
if(!(m_servercapabilities & (1 << SMTP_SUPPORT_STARTTLS_F)) )
{
m_error = ERR_SMTP_TLS_UNAVAILABLE;
m_what_to_send = SMTP_SEND_QUIT;
return OpStatus::OK;
}
m_what_to_send = SMTP_SEND_STARTTLS;
return OpStatus::OK;
}
}
m_is_authenticated = m_smtp_backend->GetCurrentAuthMethod() == AccountTypes::NONE;
if (m_is_authenticated)
m_what_to_send = SMTP_SEND_MAIL;
else
m_what_to_send = SMTP_SEND_AUTH;
}
break;
default:
{
OP_ASSERT(0);
//should not happen
}
}
return OpStatus::OK;
}
BOOL SMTP::MessageIsInQueue(message_gid_t id) const
{
for (int i = m_message_queue.GetCount() - 1; i >= 0; i--)
{
MessageInfo* queue_item = m_message_queue.Get(i);
if (queue_item && queue_item->m_id == id)
return TRUE;
}
return FALSE;
}
//********************************************************************
void SMTP::OnClose(OP_STATUS rc)
{
OP_ASSERT(!m_first_command_after_starttls);
m_smtp_backend->Log("SMTP IN : ", "Disconnected");
// callback to engine
if(rc == OpStatus::ERR_NO_ACCESS)
{
m_error = ERR_SMTP_SERVER_UNAVAILABLE;
}
if (m_what_to_send==SMTP_SEND_MAIL || m_what_to_send==SMTP_SEND_AUTH) //Server dropped connection when we tried to send a mail. Probably because it didn't like our authentication state
{
if (m_error==SMTP_NO_REPLY)
m_error = ERR_SMTP_CONNECTION_DROPPED;
}
m_smtp_backend->Disconnect();
if (m_error != SMTP_NO_REPLY)
{
if (m_error == ERR_SMTP_SERVER_UNAVAILABLE)
{
if (m_connection_has_failed)
{
m_error = SMTP_NO_REPLY;
return;
}
else
{
m_connection_has_failed = TRUE;
}
}
ReportError(m_error, UNI_L(""));
m_error = SMTP_NO_REPLY;
}
}
//********************************************************************
void SMTP::OnRestartRequested()
{
Finished();
SendFirstQueuedMessage();
}
//********************************************************************
OP_STATUS SMTP::ReportError(int errorcode, const OpStringC& server_string)
{
int title_id;
switch(m_error)
{
case ERR_SMTP_SERVER_UNAVAILABLE: title_id = Str::S_SMTP_ERR_SENDING_FAILED; break;
case ERR_SMTP_SERVICE_UNAVAILABLE: title_id = Str::S_SMTP_ERR_SERVICE_UNAVAILABLE; break;
case ERR_SMTP_INTERNAL_ERROR: title_id = Str::S_SMTP_ERR_INTERNAL_ERROR; break;
case ERR_SMTP_SERVER_TMP_ERROR: title_id = Str::S_SMTP_ERR_TEMPORARY_SERVER_ERROR; break;
case ERR_SMTP_SERVER_ERROR: title_id = Str::S_SMTP_ERR_SERVER_ERROR; break;
case ERR_SMTP_RCPT_SYNTAX_ERROR: title_id = Str::S_SMTP_ERR_RECIPIENT_SYNTAX_ERROR; break;
case ERR_SMTP_RCPT_UNAVAILABLE_ERROR: title_id = Str::S_SMTP_ERR_RECIPIENT_UNAVAILABLE; break;
case ERR_SMTP_RCPT_NOT_LOCAL_ERROR: title_id = Str::S_SMTP_ERR_RECIPIENT_NOT_LOCAL; break;
case ERR_SMTP_NO_SERVER_SPEC: title_id = Str::S_SMTP_ERR_NO_SERVER_SPECIFIED; break;
case ERR_SMTP_ERROR: title_id = Str::S_SMTP_ERROR; break;
case ERR_SMTP_RCPT_ERROR: title_id = Str::S_SMTP_ERR_RECIPIENT_ERROR; break;
case ERR_SMTP_AUTHENTICATION_ERROR: title_id = Str::S_SMTP_ERR_AUTHENTICATION_ERROR; break;
case ERR_SMTP_TLS_UNAVAILABLE: title_id = Str::S_SMTP_ERR_TLS_NOT_SUPPORTED; break;
case ERR_SMTP_AUTH_UNAVAILABLE: title_id = Str::S_SMTP_ERR_SMTP_AUTH_NOT_SUPPORTED; break;
case ERR_SMTP_CONNECTION_DROPPED: title_id = Str::S_SMTP_ERR_SERVER_DROPPED_CONNECTION; break;
default: title_id = Str::S_SMTP_ERR_UNSPECIFIED; break;
}
OP_STATUS ret;
OpString status_message;
RETURN_IF_ERROR(g_languageManager->GetString((Str::LocaleString)title_id, status_message));
if (server_string.HasContent())
{
OpString error_message;
if ((ret=error_message.Set(UNI_L(" [")))!=OpStatus::OK ||
(ret=error_message.Append(server_string))!=OpStatus::OK ||
(ret=error_message.Append(UNI_L("]")))!=OpStatus::OK)
{
return ret;
}
RemoveChars(error_message, UNI_L("\r\n\t")); // FIX OOM
if ((ret=status_message.Append(error_message))!=OpStatus::OK)
return ret;
}
if (status_message.HasContent())
m_smtp_backend->OnError(status_message);
return OpStatus::OK;
}
//********************************************************************
int SMTP::Finished()
{
StopLoading();
m_is_sending_mail = FALSE;
m_is_connected = FALSE;
m_is_secure_connection = FALSE;
m_is_authenticated = FALSE;
m_smtp_backend->GetProgress().EndCurrentAction(TRUE);
return 0;
}
int SMTP::GetUploadCount() const
{
return m_sent;
}
//********************************************************************
OP_STATUS SMTP::SendMessage(Message& message, BOOL anonymous)
{
if (!MessageIsInQueue(message.GetId()))
{
MessageInfo* info = OP_NEW(MessageInfo, ());
if (!info)
return OpStatus::ERR_NO_MEMORY;
info->m_id = message.GetId();
info->m_anonymous = anonymous;
OP_STATUS ret = m_message_queue.Add(info);
if (OpStatus::IsError(ret))
{
OP_DELETE(info);
return ret;
}
m_smtp_backend->GetProgress().AddToCurrentAction(1);
}
if (!m_is_sending_mail)
return SendFirstQueuedMessage();
return OpStatus::OK;
}
OP_STATUS SMTP::SendFirstQueuedMessage()
{
OP_STATUS ret;
/// Find and prepare first message in queue
m_current_message_info = m_message_queue.Get(0);
if (!m_current_message_info)
return OpStatus::ERR_NULL_POINTER;
Account* account = m_smtp_backend->GetAccountPtr();
Message message;
if (account)
{
if ((ret=account->PrepareToSendMessage(m_current_message_info->m_id, m_current_message_info->m_anonymous, message)) != OpStatus::OK)
{
m_message_queue.Delete(m_current_message_info);
m_current_message_info = NULL;
m_smtp_backend->Log("SMTP OUT : ", "M2 failed to prepare message for sending");
return ret;
}
}
BOOL is_resent = message.IsFlagSet(Message::IS_RESENT);
//Find sender
m_from.Empty();
Header* temp_header = message.GetHeader(is_resent ? Header::RESENTFROM : Header::FROM);
const Header::From* from = temp_header?temp_header->GetFirstAddress():NULL;
BOOL imaa_failed = FALSE;
if (from && ((ret=from->GetIMAAAddress(m_from, &imaa_failed))!=OpStatus::OK || imaa_failed))
{
if (imaa_failed && ret==OpStatus::OK)
ret=OpStatus::ERR_PARSING_FAILED;
return ret;
}
//Find recipients
m_to_item = m_cc_item = m_bcc_item = NULL; //Clear references to headers
if (message.GetHeader(is_resent ? Header::RESENTTO : Header::TO))
{
m_to_header = *message.GetHeader(is_resent ? Header::RESENTTO : Header::TO);
m_to_header.DetachFromMessage();
m_to_item = m_to_header.GetFirstAddress();
}
if (message.GetHeader(is_resent ? Header::RESENTCC : Header::CC))
{
m_cc_header = *message.GetHeader(is_resent ? Header::RESENTCC : Header::CC);
m_cc_header.DetachFromMessage();
m_cc_item = m_cc_header.GetFirstAddress();
}
if (message.GetHeader(is_resent ? Header::RESENTBCC : Header::BCC))
{
m_bcc_header = *message.GetHeader(is_resent ? Header::RESENTBCC : Header::BCC);
m_bcc_header.DetachFromMessage();
m_bcc_item = m_bcc_header.GetFirstAddress();
}
//If we have noone to send message to, ignore it and send next message
OP_ASSERT(m_to_item || m_cc_item || m_bcc_item);
if (!m_to_item && !m_cc_item && !m_bcc_item)
{
m_message_queue.Delete(m_current_message_info);
m_current_message_info = NULL;
if (m_message_queue.GetCount() > 0)
{
return SendFirstQueuedMessage();
}
else //No more messages. End session
{
m_smtp_backend->StopSendingMessage();
return OpStatus::OK;
}
}
#ifdef _DEBUG
OpString8 debug_rawmessage;
OpStatus::Ignore(message.GetRawMessage(debug_rawmessage, FALSE, FALSE, FALSE));
message.CopyCurrentToOriginalHeaders();
#endif
//Get raw message
OpString8 tmp_rawmessage;
if ((ret=message.GetRawMessage(tmp_rawmessage, FALSE, FALSE, FALSE)) != OpStatus::OK) //Bcc will be removed here
return ret;
#ifdef _DEBUG
int first_diff = debug_rawmessage.Compare(tmp_rawmessage);
OP_ASSERT(first_diff==0);
#endif
int tmp_rawmessagelen = tmp_rawmessage.Length();
OP_DELETEA(m_rfc822_message_start); // can be left over if previous message upload failed
m_rfc822_message_start = OP_NEWA(char, tmp_rawmessagelen+1);
if (!m_rfc822_message_start)
return OpStatus::ERR_NO_MEMORY;
memcpy(m_rfc822_message_start, tmp_rawmessage.CStr(), tmp_rawmessagelen);
m_rfc822_message_start[tmp_rawmessagelen] = 0;
m_rfc822_message_remaining = m_rfc822_message_start;
m_message_size_remaining = tmp_rawmessagelen;
m_message_size = tmp_rawmessagelen;
//BCC (or, for redirected messages, RESENTBCC) header MUST not be among the headers sent
OP_ASSERT(op_stristr(m_rfc822_message_start, is_resent ? "Resent-bcc: " : "Bcc: ")==NULL); //This might trigger too often, but searching for "\nbcc: " would trigger to seldom, and that is no good
//Date must be present
OP_ASSERT(op_stristr(m_rfc822_message_start, is_resent ? "Resent-date: " : "Date: ")!=NULL);
/// Send message
m_successful_rcpt = 0;
m_is_sending_mail = TRUE;
m_smtp_backend->GetProgress().UpdateCurrentAction();
m_smtp_backend->GetProgress().SetSubProgress(0, 0);
m_what_to_send = m_is_connected ? SMTP_SEND_MAIL : SMTP_SEND_NOTHING;
m_error = SMTP_NO_REPLY;
m_previous_buffer_end[0] = m_previous_buffer_end[1] = 0;
m_is_uploading = FALSE; //This is set to FALSE now and when GetNextBlock returns done=TRUE
m_content_finished = FALSE; //This is set to TRUE when comm is finished sending data
if (!m_is_connected)
{
m_sent = 0;
m_is_secure_connection = m_port==465;
m_first_command_after_starttls = FALSE;
if (m_servername.IsEmpty())
return OpStatus::ERR_NULL_POINTER;
m_smtp_backend->Log("SMTP OUT : ", "Connecting...");
m_smtp_backend->GetProgress().SetCurrentAction(ProgressInfo::CONNECTING);
return StartLoading(m_servername.CStr(), "smtp", m_port, m_is_secure_connection, m_is_secure_connection);
}
return OpStatus::OK;
}
OP_STATUS SMTP::AddDotPrefix(char** allocated_buffer)
{
if (!allocated_buffer)
return OpStatus::ERR_NULL_POINTER;
if (!(*allocated_buffer)) //Empty buffer, nothing to do
return OpStatus::OK;
// Detect previous unfinished dot-stuffing
BOOL dot_stuff_first_dot =
(m_previous_buffer_end[0] == '\r' && m_previous_buffer_end[1] == '\n' && (*allocated_buffer)[0] == '.') ||
(m_previous_buffer_end[1] == '\r' && (*allocated_buffer)[0] == '\n' && (*allocated_buffer)[1] == '.');
int grow_count = dot_stuff_first_dot > 0 ? 1 : 0;
int old_length = 0;
char* temp = *allocated_buffer;
while (*temp)
{
if ((temp[0] == '\r' && temp[1] == '\n' && temp[2] == '.'))
grow_count++;
old_length++;
temp++;
}
if (grow_count > 0)
{
char* new_allocated_buffer = OP_NEWA(char, old_length + grow_count + 1);
char* temp_dest = new_allocated_buffer;
char* temp_src = *allocated_buffer;
if (!new_allocated_buffer)
return OpStatus::ERR_NO_MEMORY;
while (*temp_src)
{
if (temp_src[0] == '\r' && temp_src[1] == '\n' && temp_src[2] == '.')
{
op_memcpy(temp_dest, "\r\n..", 4); // NULL-terminated after loop
temp_dest += 4;
temp_src += 3;
}
else
{
if (dot_stuff_first_dot && temp_src[0] == '.')
{
*(temp_dest++) = '.';
dot_stuff_first_dot = FALSE;
}
*(temp_dest++) = *(temp_src++);
}
}
*temp_dest = '\0';
OP_DELETEA(*allocated_buffer);
*allocated_buffer = new_allocated_buffer;
}
return OpStatus::OK;
}
void SMTP::AskForPassword(const OpStringC8& server_message)
{
OpString server_message16;
OpStatus::Ignore(server_message16.Set(server_message));
m_smtp_backend->OnAuthenticationRequired(server_message16);
if (m_smtp_backend->GetProgress().GetCount() > 0)
m_smtp_backend->GetProgress().UpdateCurrentAction(-1);
if (m_smtp_backend->GetProgress().GetTotalCount() > 0)
m_smtp_backend->GetProgress().AddToCurrentAction(-1);
m_what_to_send = SMTP_SEND_QUIT;
}
OP_STATUS SMTP::Parse250Response()
{
char* serverresponse = op_strstr(m_reply_buf, "\r\n");
if(serverresponse)
{
OpString8 category;
const char* authresponse = op_stristr(serverresponse, "250-AUTH");
if(!authresponse)
authresponse = op_stristr(serverresponse, "250 AUTH");
if(authresponse)
{
m_servercapabilities |= (1 << SMTP_SUPPORT_AUTH_F);
const char* endofcategory = op_stristr(authresponse+1, "\r\n");
category.Set(authresponse+8, (endofcategory-(authresponse+8)));
if(KNotFound != category.FindI("CRAM-MD5"))
{
m_servercapabilities |= (1 << SMTP_SUPPORT_AUTH_CRAMMD5_F);
}
if(KNotFound != category.FindI("PLAIN"))
{
m_servercapabilities |= (1 << SMTP_SUPPORT_AUTH_PLAIN_F);
}
if(KNotFound!=category.FindI("LOGIN") && KNotFound==category.FindI("LOGINDISABLED"))
{
m_servercapabilities |= (1 << SMTP_SUPPORT_AUTH_LOGIN_F);
}
}
const char* tlsresponse = op_stristr(serverresponse, "250-STARTTLS");
if(!tlsresponse)
tlsresponse = op_stristr(serverresponse, "250 STARTTLS");
if(tlsresponse)
{
m_servercapabilities |= (1 << SMTP_SUPPORT_STARTTLS_F);
}
}
else
{
return OpStatus::ERR;
}
return OpStatus::OK;
}
AccountTypes::AuthenticationType SMTP::GetNextAuthenticationMethod(AccountTypes::AuthenticationType current_method) const
{
UINT32 supported_authentication = 0;
if(m_servercapabilities & (1<<SMTP_SUPPORT_AUTH_CRAMMD5_F)) supported_authentication |= 1<<AccountTypes::CRAM_MD5;
if(m_servercapabilities & (1<<SMTP_SUPPORT_AUTH_LOGIN_F)) supported_authentication |= 1<<AccountTypes::LOGIN;
if(m_servercapabilities & (1<<SMTP_SUPPORT_AUTH_PLAIN_F)) supported_authentication |= 1<<AccountTypes::PLAIN;
if (supported_authentication==0) //If server doesn't tell us what it supports, try all we support
supported_authentication = m_smtp_backend->GetAuthenticationSupported();
return m_smtp_backend->GetNextAuthenticationMethod(current_method, supported_authentication);
}
#endif //M2_SUPPORT
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Tomasz Jamroszczak tjamroszczak@opera.com
*
*/
#ifndef DOM_DOMJILEMAILACCOUNT_H
#define DOM_DOMJILEMAILACCOUNT_H
#ifdef DOM_JIL_API_SUPPORT
#include "modules/dom/src/domjil/domjilobject.h"
#include "modules/pi/device_api/OpMessaging.h"
class DOM_JILEmailAccount : public DOM_JILObject
{
public:
DOM_JILEmailAccount() {}
~DOM_JILEmailAccount() {}
virtual BOOL IsA(int type) { return type == DOM_TYPE_JIL_EMAILACCOUNT || DOM_JILObject::IsA(type); }
virtual ES_PutState InternalPutName(OpAtom property_atom, ES_Value* value, DOM_Runtime* origining_runtime, ES_Value* restart_value);
virtual ES_GetState InternalGetName(OpAtom property_atom, ES_Value* value, DOM_Runtime* origining_runtime, ES_Value* restart_value);
static OP_STATUS Make(DOM_JILEmailAccount*& new_obj, DOM_Runtime* runtime);
OP_STATUS SetAccount(const OpMessaging::EmailAccount* account);
private:
OpString m_id;
OpString m_name;
struct NullOrUndefSt
{
unsigned int id:2;
unsigned int name:2;
} m_undefnull;
};
class DOM_JILEmailAccount_Constructor : public DOM_BuiltInConstructor
{
public:
DOM_JILEmailAccount_Constructor() : DOM_BuiltInConstructor(DOM_Runtime::JIL_EMAILACCOUNT_PROTOTYPE) {}
virtual int Construct(ES_Value* argv, int argc, ES_Value* return_value, ES_Runtime *origining_runtime);
};
#endif // DOM_JIL_API_SUPPORT
#endif // DOM_DOMJILEMAILACCOUNT_H
|
#include <iostream>
#include <algorithm>
#include <random>
#include "../src/NeuralNetwork.hpp"
#include "../src/Trainer.hpp"
using namespace nanoNet;
int main() {
NeuralNetwork network;
network.addLayer({2, 8, {ActivationFunction::Which::Relu}});
network.addLayer({8, 1, {ActivationFunction::Which::Linear}});
// 10000 epochs, batch size = 2, training rate = 0.002
Trainer trainer { 10000 , 2 , 0.002 };
Trainer::DataSet data {{
{{{0.0, 0.0}},{{0.0}}},
{{{0.0, 1.0}},{{1.0}}},
{{{1.0, 0.0}},{{1.0}}},
{{{1.0, 1.0}},{{0.0}}}
}};
// stochastic gradient descent
trainer.train ( network, data );
auto rnd_base = []( float k ){ return [=]( float x ){ return ( int(x*k+0.5) ) / k; }; };
auto rnd = rnd_base(2);
std::cout << '\n';
std::cout << rnd(network.predict({{0.0, 0.0}})[0]) << '\n';
std::cout << rnd(network.predict({{0.0, 1.0}})[0]) << '\n';
std::cout << rnd(network.predict({{1.0, 0.0}})[0]) << '\n';
std::cout << rnd(network.predict({{1.0, 1.0}})[0]) << '\n';
std::cout << '\n';
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int m=n;
n=(n*2)-1;
int I;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
//cout<<m-abs(m-1-i)-1<<j<<" ";
if(m-abs(m-1-i)-1<=j && m-abs(m-1-i)-1+j<n)
cout<<"*";
else cout<<" ";
}
cout<<endl;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef VEGA_SUPPORT
#include "modules/libvega/src/vegafiltermerge.h"
#include "modules/libvega/src/vegapixelformat.h"
#include "modules/libvega/src/vegacomposite.h"
#include "modules/libvega/src/vegabackend.h"
#ifdef VEGA_3DDEVICE
#include "modules/libvega/src/vegabackend_hw3d.h"
#endif // VEGA_3DDEVICE
VEGAFilterMerge::VEGAFilterMerge() : mergeType(VEGAMERGE_NORMAL), opacity(255)
{
}
VEGAFilterMerge::VEGAFilterMerge(VEGAMergeType mt) : mergeType(mt), opacity(255)
{
}
#define VEGA_CLAMP_U8(v) (((v) > 255) ? 255 : (((v) < 0) ? 0 : (v)))
#define PREMULTIPLY(a,r,g,b) \
{ \
(r) = ((r) * ((a) + 1)) >> 8;\
(g) = ((g) * ((a) + 1)) >> 8;\
(b) = ((b) * ((a) + 1)) >> 8;\
}
#ifdef USE_PREMULTIPLIED_ALPHA
static inline VEGA_PIXEL clamp_and_pack_rgba(int da, int dr, int dg, int db)
{
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
return VEGA_PACK_ARGB(da, dr, dg, db);
}
#define CLAMP_AND_PACK(a,r,g,b) clamp_and_pack_rgba(a,r,g,b)
#else
static inline VEGA_PIXEL unpremult_clamp_and_pack_rgba(int da, int dr, int dg, int db)
{
if (da == 0)
return 0;
if (da >= 0xff)
{
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
return VEGA_PACK_RGB(dr, dg, db);
}
dr = (dr*255)/da;
dg = (dg*255)/da;
db = (db*255)/da;
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
return VEGA_PACK_ARGB(da, dr, dg, db);
}
#define CLAMP_AND_PACK(a,r,g,b) unpremult_clamp_and_pack_rgba(a,r,g,b)
#endif // USE_PREMULTIPLIED_ALPHA
//
// Legend:
// qr = Result opacity value
// cr = Result color (RGB) - premultiplied
// qa = Opacity value at a given pixel for image A
// qb = Opacity value at a given pixel for image B
// ca = Color (RGB) at a given pixel for image A - premultiplied
// cb = Color (RGB) at a given pixel for image B - premultiplied
//
//
// Arithmetic (SVG: http://www.w3.org/TR/SVG11/filters.html#feComposite)
//
// cr = k1 * ca * cb + k2 * ca + k3 * cb + k4
// qr = k1 * qa * qb + k2 * qa + k3 * qb + k4
//
void VEGAFilterMerge::mergeArithmetic(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
int sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
int da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
#ifndef USE_PREMULTIPLIED_ALPHA
PREMULTIPLY(da, dr, dg, db);
PREMULTIPLY(sa, sr, sg, sb);
#endif // !USE_PREMULTIPLIED_ALPHA
VEGA_FIX fda = k1*((da*sa)/255) + k2*sa + k3*da + k4*255;
VEGA_FIX fdr = k1*((dr*sr)/255) + k2*sr + k3*dr + k4*255;
VEGA_FIX fdg = k1*((dg*sg)/255) + k2*sg + k3*dg + k4*255;
VEGA_FIX fdb = k1*((db*sb)/255) + k2*sb + k3*db + k4*255;
fda = (fda > VEGA_INTTOFIX(255)) ? VEGA_INTTOFIX(255) :
(fda < 0) ? 0 : fda;
da = VEGA_FIXTOINT(fda);
if (da)
{
#ifndef USE_PREMULTIPLIED_ALPHA
VEGA_FIX mf = VEGA_FIXDIV(VEGA_INTTOFIX(255), fda);
dr = VEGA_FIXTOINT(VEGA_FIXMUL(fdr, mf));
dg = VEGA_FIXTOINT(VEGA_FIXMUL(fdg, mf));
db = VEGA_FIXTOINT(VEGA_FIXMUL(fdb, mf));
#else
dr = VEGA_FIXTOINT(fdr);
dg = VEGA_FIXTOINT(fdg);
db = VEGA_FIXTOINT(fdb);
#endif // !USE_PREMULTIPLIED_ALPHA
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
dst.StoreARGB(da, dr, dg, db);
}
else
dst.Store(0);
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Multiply (SVG: http://www.w3.org/TR/SVG11/filters.html#feBlend)
//
// cr = (1 - qa) * cb + (1 - qb) * ca + ca * cb
// qr = 1 - (1-qa)*(1-qb)
//
void VEGAFilterMerge::mergeMultiply(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
#ifdef USE_PREMULTIPLIED_ALPHA
int sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
int da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
dr = dr + sr + (((dr*sr) - (dr*sa) - (sr*da)) >> 8);
dg = dg + sg + (((dg*sg) - (dg*sa) - (sg*da)) >> 8);
db = db + sb + (((db*sb) - (db*sa) - (sb*da)) >> 8);
da = sa + da - ((sa*da) >> 8);
da = VEGA_CLAMP_U8(da);
dst.Store(CLAMP_AND_PACK(da, dr, dg, db));
#else
int sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
int da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
if (sa >= 0xff)
{
if (da >= 0xff)
{
dr = ((dr * sr) >> 8);
dg = ((dg * sg) >> 8);
db = ((db * sb) >> 8);
}
else
{
dr = sr + ((sr*dr*da/255 - sr*da) >> 8);
dg = sg + ((sg*dg*da/255 - sg*da) >> 8);
db = sb + ((sb*db*da/255 - sb*da) >> 8);
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
}
dst.StoreRGB(dr, dg, db);
}
else
{
VEGA_PIXEL d;
if (da >= 0xff)
{
dr = dr + ((dr*sr*sa/255 - dr*sa) >> 8);
dg = dg + ((dg*sg*sa/255 - dg*sa) >> 8);
db = db + ((db*sb*sa/255 - db*sa) >> 8);
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
d = VEGA_PACK_RGB(dr, dg, db);
}
else
{
PREMULTIPLY(sa, sr, sg, sb);
PREMULTIPLY(da, dr, dg, db);
dr = dr + sr + (((dr*sr) - (dr*sa) - (sr*da)) >> 8);
dg = dg + sg + (((dg*sg) - (dg*sa) - (sg*da)) >> 8);
db = db + sb + (((db*sb) - (db*sa) - (sb*da)) >> 8);
da = sa + da - ((sa*da) >> 8);
da = VEGA_CLAMP_U8(da);
d = CLAMP_AND_PACK(da, dr, dg, db);
}
dst.Store(d);
}
#endif // USE_PREMULTIPLIED_ALPHA
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Screen (SVG: http://www.w3.org/TR/SVG11/filters.html#feBlend)
//
// cr = cb + ca - ca * cb
// qr = 1 - (1-qa)*(1-qb)
//
void VEGAFilterMerge::mergeScreen(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
int sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
int da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
#ifndef USE_PREMULTIPLIED_ALPHA
PREMULTIPLY(sa, sr, sg, sb);
PREMULTIPLY(da, dr, dg, db);
#endif // !USE_PREMULTIPLIED_ALPHA
dr = dr + sr - ((dr*sr) >> 8);
dg = dg + sg - ((dg*sg) >> 8);
db = db + sb - ((db*sb) >> 8);
da = da + sa - ((da*sa) >> 8);
da = VEGA_CLAMP_U8(da);
dst.Store(CLAMP_AND_PACK(da, dr, dg, db));
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Darken (SVG: http://www.w3.org/TR/SVG11/filters.html#feBlend)
//
// cr = Min ((1 - qa) * cb + ca, (1 - qb) * ca + cb)
// qr = 1 - (1-qa)*(1-qb)
//
void VEGAFilterMerge::mergeDarken(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
#ifdef USE_PREMULTIPLIED_ALPHA
unsigned sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
unsigned da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
unsigned inv_sa = 255 - sa;
unsigned inv_da = 255 - da;
dr = MIN(sr + ((inv_sa * dr) >> 8), dr + ((inv_da * sr) >> 8));
dg = MIN(sg + ((inv_sa * dg) >> 8), dg + ((inv_da * sg) >> 8));
db = MIN(sb + ((inv_sa * db) >> 8), db + ((inv_da * sb) >> 8));
da = sa + ((inv_sa * da) >> 8);
dst.Store(CLAMP_AND_PACK(da, dr, dg, db));
#else
int sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
int da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
if (sa >= 0xff)
{
VEGA_PIXEL d;
if (da >= 0xff)
{
dr = MIN(dr, sr);
dg = MIN(dg, sg);
db = MIN(db, sb);
d = VEGA_PACK_RGB(dr, dg, db);
}
else
{
dr = sr + MIN(0, (da*(dr - sr)) >> 8);
dg = sg + MIN(0, (da*(dg - sg)) >> 8);
db = sb + MIN(0, (da*(db - sb)) >> 8);
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
d = VEGA_PACK_RGB(dr, dg, db);
}
dst.Store(d);
}
else if (sa > 0)
{
VEGA_PIXEL d;
if (da >= 0xff)
{
dr = dr + MIN(0, (sa*(sr - dr)) >> 8);
dg = dg + MIN(0, (sa*(sg - dg)) >> 8);
db = db + MIN(0, (sa*(sb - db)) >> 8);
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
d = VEGA_PACK_RGB(dr, dg, db);
}
else
{
// General case
PREMULTIPLY(sa, sr, sg, sb);
PREMULTIPLY(da, dr, dg, db);
dr = sr + dr - (MAX(dr*sa, sr*da) >> 8);
dg = sg + dg - (MAX(dg*sa, sg*da) >> 8);
db = sb + db - (MAX(db*sa, sb*da) >> 8);
da = da + sa - ((da*sa) >> 8);
d = CLAMP_AND_PACK(da, dr, dg, db);
}
dst.Store(d);
}
#endif // USE_PREMULTIPLIED_ALPHA
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Lighten (SVG: http://www.w3.org/TR/SVG11/filters.html#feBlend)
//
// cr = Max ((1 - qa) * cb + ca, (1 - qb) * ca + cb)
// qr = 1 - (1-qa)*(1-qb)
//
void VEGAFilterMerge::mergeLighten(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
#ifdef USE_PREMULTIPLIED_ALPHA
unsigned sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
unsigned da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
unsigned inv_sa = 255 - sa;
unsigned inv_da = 255 - da;
dr = MAX(sr + ((inv_sa * dr) >> 8), dr + ((inv_da * sr) >> 8));
dg = MAX(sg + ((inv_sa * dg) >> 8), dg + ((inv_da * sg) >> 8));
db = MAX(sb + ((inv_sa * db) >> 8), db + ((inv_da * sb) >> 8));
da = sa + ((inv_sa * da) >> 8);
dst.Store(CLAMP_AND_PACK(da, dr, dg, db));
#else
int sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
int da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
if (sa >= 0xff)
{
if (da >= 0xff)
{
dr = MAX(dr, sr);
dg = MAX(dg, sg);
db = MAX(db, sb);
}
else
{
dr = sr + MAX(0, (da*(dr - sr)) >> 8);
dg = sg + MAX(0, (da*(dg - sg)) >> 8);
db = sb + MAX(0, (da*(db - sb)) >> 8);
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
}
dst.StoreRGB(dr, dg, db);
}
else if (sa > 0)
{
VEGA_PIXEL d;
if (da >= 0xff)
{
dr = dr + MAX(0, (sa*(sr - dr)) >> 8);
dg = dg + MAX(0, (sa*(sg - dg)) >> 8);
db = db + MAX(0, (sa*(sb - db)) >> 8);
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
d = VEGA_PACK_RGB(dr, dg, db);
}
else
{
// General case
PREMULTIPLY(sa, sr, sg, sb);
PREMULTIPLY(da, dr, dg, db);
dr = dr + sr - (MIN(dr*sa, sr*da) >> 8);
dg = dg + sg - (MIN(dg*sa, sg*da) >> 8);
db = db + sb - (MIN(db*sa, sb*da) >> 8);
da = sa + da - ((sa*da) >> 8);
d = CLAMP_AND_PACK(da, dr, dg, db);
}
dst.Store(d);
}
#endif // USE_PREMULTIPLIED_ALPHA
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Plus/Add
//
// cr = ca + cb
// qr = qa + qb
//
void VEGAFilterMerge::mergePlus(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
unsigned sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
unsigned da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
#ifndef USE_PREMULTIPLIED_ALPHA
if (sa == 0)
{
sr = sg = sb = 0;
}
else if (sa < 0xff)
{
PREMULTIPLY(sa, sr, sg, sb);
}
if (da == 0)
{
dr = dg = db = 0;
}
else if (da < 0xff)
{
PREMULTIPLY(da, dr, dg, db);
}
#endif // !USE_PREMULTIPLIED_ALPHA
da += sa;
dr += sr;
dg += sg;
db += sb;
da = da > 255 ? 255 : da;
dst.Store(CLAMP_AND_PACK(da, dr, dg, db));
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Porter-Duff 'atop'
//
// cr = ca * qb + cb * (1 - qa)
// qr = qa * qb + qb * (1 - qa)
//
void VEGAFilterMerge::mergeAtop(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
#ifdef USE_PREMULTIPLIED_ALPHA
unsigned da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
unsigned sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
dr = (sr * (da+1) + dr * (256 - sa)) >> 8;
dg = (sg * (da+1) + dg * (256 - sa)) >> 8;
db = (sb * (da+1) + db * (256 - sa)) >> 8;
dr = (dr > 255) ? 255 : dr;
dg = (dg > 255) ? 255 : dg;
db = (db > 255) ? 255 : db;
dst.StoreARGB(da, dr, dg, db);
#else
VEGA_PIXEL d = dst.Load();
int da = VEGA_UNPACK_A(d);
if (da == 0)
{
dst.Store(0);
}
else
{
int sa, sr, sg, sb;
src.LoadUnpack(sa, sr, sg, sb);
if (sa >= 0xff)
{
dst.StoreARGB(da, sr, sg, sb);
}
else if (sa > 0)
{
int dr = VEGA_UNPACK_R(d);
int dg = VEGA_UNPACK_G(d);
int db = VEGA_UNPACK_B(d);
// This is the general case
dr = dr + ((sa*(sr - dr)) >> 8);
dg = dg + ((sa*(sg - dg)) >> 8);
db = db + ((sa*(sb - db)) >> 8);
dr = VEGA_CLAMP_U8(dr);
dg = VEGA_CLAMP_U8(dg);
db = VEGA_CLAMP_U8(db);
dst.StoreARGB(da, dr, dg, db);
}
}
#endif // USE_PREMULTIPLIED_ALPHA
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Porter-Duff 'xor'
//
// cr = ca * (1 - qb) + cb * (1 - qa)
// qr = qa * (1 - qb) + qb * (1 - qa)
//
void VEGAFilterMerge::mergeXor(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
VEGA_PIXEL s = src.Load();
unsigned sa = VEGA_UNPACK_A(s);
if (sa >= 0xff)
{
VEGA_PIXEL d = dst.Load();
unsigned da = VEGA_UNPACK_A(d);
if (da == 0)
{
dst.Store(s);
}
else if (da >= 0xff)
{
dst.Store(0);
}
else
{
da = 255 - da;
#ifdef USE_PREMULTIPLIED_ALPHA
unsigned inv_da = da + 1;
unsigned dr = (inv_da * VEGA_UNPACK_R(s)) >> 8;
unsigned dg = (inv_da * VEGA_UNPACK_G(s)) >> 8;
unsigned db = (inv_da * VEGA_UNPACK_B(s)) >> 8;
dst.StoreARGB(da, dr, dg, db);
#else
dst.StoreARGB(da, VEGA_UNPACK_R(s), VEGA_UNPACK_G(s), VEGA_UNPACK_B(s));
#endif // USE_PREMULTIPLIED_ALPHA
}
}
else if (sa > 0)
{
unsigned da, dr, dg, db;
dst.LoadUnpack(da, dr, dg, db);
if (da >= 0xff)
{
da = 255 - sa;
#ifdef USE_PREMULTIPLIED_ALPHA
unsigned inv_sa = da + 1;
dr = (inv_sa * dr) >> 8;
dg = (inv_sa * dg) >> 8;
db = (inv_sa * db) >> 8;
#endif // USE_PREMULTIPLIED_ALPHA
dst.StoreARGB(da, dr, dg, db);
}
else if (da > 0)
{
unsigned sr = VEGA_UNPACK_R(s);
unsigned sg = VEGA_UNPACK_G(s);
unsigned sb = VEGA_UNPACK_B(s);
// General case
#ifndef USE_PREMULTIPLIED_ALPHA
PREMULTIPLY(sa, sr, sg, sb);
PREMULTIPLY(da, dr, dg, db);
#endif // !USE_PREMULTIPLIED_ALPHA
dr = (dr*(255 - sa) + sr*(255 - da)) >> 8;
dg = (dg*(255 - sa) + sg*(255 - da)) >> 8;
db = (db*(255 - sa) + sb*(255 - da)) >> 8;
da = (da*(255 - sa) + sa*(255 - da)) >> 8;
dst.Store(CLAMP_AND_PACK(da, dr, dg, db));
}
else
{
dst.Store(s);
}
}
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Porter-Duff 'out'
//
// cr = ca * (1 - qb)
// qr = qa * (1 - qb)
//
void VEGAFilterMerge::mergeOut(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
VEGA_PIXEL d = dst.Load();
unsigned da = VEGA_UNPACK_A(d);
if (da >= 0xff)
{
dst.Store(0);
}
else if (da > 0)
{
VEGA_PIXEL s = src.Load();
unsigned sa = VEGA_UNPACK_A(s);
if (sa > 0)
{
unsigned inv_da = 256 - da;
da = (sa * inv_da) >> 8;
#ifdef USE_PREMULTIPLIED_ALPHA
unsigned dr = (inv_da * VEGA_UNPACK_R(s)) >> 8;
unsigned dg = (inv_da * VEGA_UNPACK_G(s)) >> 8;
unsigned db = (inv_da * VEGA_UNPACK_B(s)) >> 8;
dst.StoreARGB(da, dr, dg, db);
#else
dst.StoreARGB(da, VEGA_UNPACK_R(s), VEGA_UNPACK_G(s), VEGA_UNPACK_B(s));
#endif // USE_PREMULTIPLIED_ALPHA
}
else
{
dst.Store(0);
}
}
else
{
dst.Store(src.Load());
}
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// Porter-Duff 'in'
//
// cr = ca * qb
// qr = qa * qb
//
void VEGAFilterMerge::mergeIn(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride() - dstbuf.width;
unsigned dstPixelStride = dstbuf.GetPixelStride() - dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
VEGA_PIXEL s = src.Load();
unsigned sa = VEGA_UNPACK_A(s);
if (sa == 0)
{
dst.Store(0);
}
else if (sa > 0)
{
VEGA_PIXEL d = dst.Load();
unsigned da = VEGA_UNPACK_A(d);
if (da >= 0xff)
{
dst.Store(src.Load());
}
else if (da > 0)
{
unsigned alpha = da + 1;
#ifdef USE_PREMULTIPLIED_ALPHA
unsigned dr = (alpha * VEGA_UNPACK_R(s)) >> 8;
unsigned dg = (alpha * VEGA_UNPACK_G(s)) >> 8;
unsigned db = (alpha * VEGA_UNPACK_B(s)) >> 8;
da = (alpha * sa) >> 8;
dst.StoreARGB(da, dr, dg, db);
#else
da = (alpha * sa) >> 8;
dst.StoreARGB(da, VEGA_UNPACK_R(s), VEGA_UNPACK_G(s), VEGA_UNPACK_B(s));
#endif // USE_PREMULTIPLIED_ALPHA
}
else
{
dst.Store(0);
}
}
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// [Approximately: (A in O) over B, where O is the opacity]
//
// [o = opacity]
// cr = ca * o + cb * (1 - qa * o)
// qr = qa * o + qb * (1 - qa * o)
//
void VEGAFilterMerge::mergeOpacity(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride();
unsigned dstPixelStride = dstbuf.GetPixelStride();
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
VEGACompOverIn(dst.Ptr(), src.Ptr(), opacity, dstbuf.width);
src += srcPixelStride;
dst += dstPixelStride;
}
}
//
// 'Copy'
//
// cr = ca
// qr = qa
//
void VEGAFilterMerge::mergeReplace(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride();
unsigned dstPixelStride = dstbuf.GetPixelStride();
if (sourceAlphaOnly)
{
srcPixelStride -= dstbuf.width;
dstPixelStride -= dstbuf.width;
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
unsigned cnt = dstbuf.width;
while (cnt-- > 0)
{
dst.StoreARGB(VEGA_UNPACK_A(src.Load()), 0, 0, 0);
++src;
++dst;
}
src += srcPixelStride;
dst += dstPixelStride;
}
}
else
{
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
dst.CopyFrom(src.Ptr(), dstbuf.width);
src += srcPixelStride;
dst += dstPixelStride;
}
}
}
//
// Porter-Duff 'over'
//
// cr = ca + cb * (1 - qa)
// qr = qa + qb * (1 - qa)
//
void VEGAFilterMerge::mergeOver(const VEGASWBuffer& dstbuf, const VEGASWBuffer& srcbuf)
{
VEGAConstPixelAccessor src = srcbuf.GetConstAccessor(0, 0);
VEGAPixelAccessor dst = dstbuf.GetAccessor(0, 0);
unsigned srcPixelStride = srcbuf.GetPixelStride();
unsigned dstPixelStride = dstbuf.GetPixelStride();
for (unsigned int yp = 0; yp < dstbuf.height; ++yp)
{
VEGACompOver(dst.Ptr(), src.Ptr(), dstbuf.width);
src += srcPixelStride;
dst += dstPixelStride;
}
}
OP_STATUS VEGAFilterMerge::apply(const VEGASWBuffer& dest, const VEGAFilterRegion& region)
{
VEGASWBuffer sub_src = source.CreateSubset(region.sx, region.sy, region.width, region.height);
VEGASWBuffer sub_dst = dest.CreateSubset(region.dx, region.dy, region.width, region.height);
switch (mergeType)
{
case VEGAMERGE_ARITHMETIC:
mergeArithmetic(sub_dst, sub_src);
break;
case VEGAMERGE_MULTIPLY:
mergeMultiply(sub_dst, sub_src);
break;
case VEGAMERGE_SCREEN:
mergeScreen(sub_dst, sub_src);
break;
case VEGAMERGE_DARKEN:
mergeDarken(sub_dst, sub_src);
break;
case VEGAMERGE_LIGHTEN:
mergeLighten(sub_dst, sub_src);
break;
case VEGAMERGE_PLUS:
mergePlus(sub_dst, sub_src);
break;
case VEGAMERGE_ATOP:
mergeAtop(sub_dst, sub_src);
break;
case VEGAMERGE_XOR:
mergeXor(sub_dst, sub_src);
break;
case VEGAMERGE_OUT:
mergeOut(sub_dst, sub_src);
break;
case VEGAMERGE_IN:
mergeIn(sub_dst, sub_src);
break;
case VEGAMERGE_OPACITY:
mergeOpacity(sub_dst, sub_src);
break;
case VEGAMERGE_REPLACE:
mergeReplace(sub_dst, sub_src);
break;
case VEGAMERGE_NORMAL:
case VEGAMERGE_OVER:
default:
mergeOver(sub_dst, sub_src);
break;
}
return OpStatus::OK;
}
#ifdef VEGA_3DDEVICE
bool VEGAFilterMerge::setBlendingFactors()
{
switch (mergeType)
{
case VEGAMERGE_PLUS:
// one, one
srcBlend = VEGA3dRenderState::BLEND_ONE;
dstBlend = VEGA3dRenderState::BLEND_ONE;
break;
case VEGAMERGE_ATOP:
// dsta, 1-srca
srcBlend = VEGA3dRenderState::BLEND_DST_ALPHA;
dstBlend = VEGA3dRenderState::BLEND_ONE_MINUS_SRC_ALPHA;
break;
case VEGAMERGE_XOR:
// 1-dsta, 1-srca
srcBlend = VEGA3dRenderState::BLEND_ONE_MINUS_DST_ALPHA;
dstBlend = VEGA3dRenderState::BLEND_ONE_MINUS_SRC_ALPHA;
break;
case VEGAMERGE_OUT:
// 1-dsta, 0
srcBlend = VEGA3dRenderState::BLEND_ONE_MINUS_DST_ALPHA;
dstBlend = VEGA3dRenderState::BLEND_ZERO;
break;
case VEGAMERGE_IN:
// dsta, 0
srcBlend = VEGA3dRenderState::BLEND_DST_ALPHA;
dstBlend = VEGA3dRenderState::BLEND_ZERO;
break;
case VEGAMERGE_OPACITY:
// one, 1-srca
// use color opacity,opacity,opacity,opacity
srcBlend = VEGA3dRenderState::BLEND_ONE;
dstBlend = VEGA3dRenderState::BLEND_ONE_MINUS_SRC_ALPHA;
break;
case VEGAMERGE_REPLACE:
// one, zero
srcBlend = VEGA3dRenderState::BLEND_ONE;
dstBlend = VEGA3dRenderState::BLEND_ZERO;
break;
default:
case VEGAMERGE_NORMAL:
case VEGAMERGE_OVER:
// one, 1-srca
srcBlend = VEGA3dRenderState::BLEND_ONE;
dstBlend = VEGA3dRenderState::BLEND_ONE_MINUS_SRC_ALPHA;
break;
case VEGAMERGE_ARITHMETIC:
case VEGAMERGE_MULTIPLY:
case VEGAMERGE_SCREEN:
case VEGAMERGE_DARKEN:
case VEGAMERGE_LIGHTEN:
// Just set dev and let there be light
break;
}
return true;
}
OP_STATUS VEGAFilterMerge::setupVertexBuffer(VEGA3dDevice* device, VEGA3dBuffer** out_vbuf, VEGA3dVertexLayout** out_vlayout, unsigned int* out_startIndex, VEGA3dTexture* tex, VEGA3dShaderProgram* sprog,
const VEGAFilterRegion& region)
{
VEGA3dTexture* tex1 = source2Tex;
return createVertexBuffer_Binary(device, out_vbuf, out_vlayout, out_startIndex, tex, tex1, sprog, region);
}
OP_STATUS VEGAFilterMerge::getShader(VEGA3dDevice* device, VEGA3dShaderProgram** out_shader, VEGA3dTexture* srcTex)
{
VEGA3dShaderProgram::ShaderType shdtype;
switch (mergeType)
{
case VEGAMERGE_ARITHMETIC:
shdtype = VEGA3dShaderProgram::SHADER_MERGE_ARITHMETIC;
break;
case VEGAMERGE_MULTIPLY:
shdtype = VEGA3dShaderProgram::SHADER_MERGE_MULTIPLY;
break;
case VEGAMERGE_SCREEN:
shdtype = VEGA3dShaderProgram::SHADER_MERGE_SCREEN;
break;
case VEGAMERGE_DARKEN:
shdtype = VEGA3dShaderProgram::SHADER_MERGE_DARKEN;
break;
case VEGAMERGE_LIGHTEN:
shdtype = VEGA3dShaderProgram::SHADER_MERGE_LIGHTEN;
break;
default:
OP_ASSERT(FALSE);
return OpStatus::ERR;
}
VEGA3dShaderProgram* shader = NULL;
RETURN_IF_ERROR(device->createShaderProgram(&shader, shdtype, VEGA3dShaderProgram::WRAP_CLAMP_CLAMP));
device->setShaderProgram(shader);
if (mergeType == VEGAMERGE_ARITHMETIC)
{
shader->setScalar(shader->getConstantLocation("k1"), k1);
shader->setScalar(shader->getConstantLocation("k2"), k2);
shader->setScalar(shader->getConstantLocation("k3"), k3);
shader->setScalar(shader->getConstantLocation("k4"), k4);
}
device->setTexture(0, srcTex);
device->setTexture(1, source2Tex);
*out_shader = shader;
return OpStatus::OK;
}
void VEGAFilterMerge::putShader(VEGA3dDevice* device, VEGA3dShaderProgram* shader)
{
OP_ASSERT(device && shader);
VEGARefCount::DecRef(shader);
}
OP_STATUS VEGAFilterMerge::apply(VEGABackingStore_FBO* destStore, const VEGAFilterRegion& region, unsigned int frame)
{
if (!setBlendingFactors())
return applyFallback(destStore, region);
VEGA3dDevice* dev = g_vegaGlobals.vega3dDevice;
VEGA3dRenderTarget* destRT = destStore->GetWriteRenderTarget(frame);
if (sourceRT == destRT ||
sourceRT->getType() != VEGA3dRenderTarget::VEGA3D_RT_TEXTURE ||
!static_cast<VEGA3dFramebufferObject*>(sourceRT)->getAttachedColorTexture())
{
if (mergeType == VEGAMERGE_REPLACE && destRT->getType() == VEGA3dRenderTarget::VEGA3D_RT_TEXTURE &&
static_cast<VEGA3dFramebufferObject*>(destRT)->getAttachedColorTexture())
{
dev->setRenderTarget(sourceRT);
dev->setRenderState(dev->getDefault2dNoBlendNoScissorRenderState());
dev->copyToTexture(static_cast<VEGA3dFramebufferObject*>(destRT)->getAttachedColorTexture(), VEGA3dTexture::CUBE_SIDE_NONE, 0,
region.dx, region.dy, region.sx, region.sy, region.width, region.height);
return OpStatus::OK;
}
// merge filters can only be applied if they have an attached
// color texture.
OP_ASSERT(!"unhandled merge from window (or multi-sampled backbuffer)");
return OpStatus::ERR;
}
// FIXME: A lot of checking done twice
if (mergeType == VEGAMERGE_ARITHMETIC || mergeType == VEGAMERGE_MULTIPLY ||
mergeType == VEGAMERGE_SCREEN || mergeType == VEGAMERGE_DARKEN ||
mergeType == VEGAMERGE_LIGHTEN)
{
VEGA3dTexture* tmpTex = NULL;
VEGA3dRenderTarget* destReadRT = destStore->GetReadRenderTarget();
if (destReadRT != destRT && destReadRT->getType() == VEGA3dRenderTarget::VEGA3D_RT_TEXTURE)
{
tmpTex = static_cast<VEGA3dFramebufferObject*>(destReadRT)->getAttachedColorTexture();
}
OP_STATUS status = OpStatus::OK;
if (tmpTex)
VEGARefCount::IncRef(tmpTex);
else
{
// This assumes that applyShader does not use the temp texture. It only uses tempTexture
// when creating clamp texure or source==dest, which is already checked for
// source2Tex and destination must use same coordinates, so always clone from 0,0
status = cloneToTempTexture(dev, destReadRT, region.dx, region.dy,
region.width, region.height, true, &tmpTex);
}
if (OpStatus::IsSuccess(status))
{
source2Tex = tmpTex;
status = applyShader(destStore, region, frame);
}
VEGARefCount::DecRef(tmpTex);
if (OpStatus::IsSuccess(status))
return status;
return applyFallback(destStore, region);
}
dev->setRenderTarget(destRT);
if (srcBlend == VEGA3dRenderState::BLEND_ONE && dstBlend == VEGA3dRenderState::BLEND_ONE_MINUS_SRC_ALPHA)
{
VEGA3dRenderState* state = dev->getDefault2dRenderState();
dev->setScissor(0, 0, destRT->getWidth(), destRT->getHeight());
dev->setRenderState(state);
}
else if (srcBlend == VEGA3dRenderState::BLEND_ONE && dstBlend == VEGA3dRenderState::BLEND_ZERO)
{
VEGA3dRenderState* state = dev->getDefault2dNoBlendRenderState();
dev->setScissor(0, 0, destRT->getWidth(), destRT->getHeight());
dev->setRenderState(state);
}
else
{
VEGA3dRenderState state;
state.enableBlend(true);
state.setBlendFunc(srcBlend, dstBlend);
dev->setRenderState(&state);
}
VEGA3dTexture* tex = static_cast<VEGA3dFramebufferObject*>(sourceRT)->getAttachedColorTexture();
dev->setTexture(0, tex);
UINT32 color = 0xffffffff;
if (mergeType == VEGAMERGE_OPACITY)
color = (opacity<<24)|(opacity<<16)|(opacity<<8)|opacity;
else if (mergeType == VEGAMERGE_REPLACE && sourceAlphaOnly)
color = 0xff000000;
VEGA3dShaderProgram* shd;
OP_STATUS err = dev->createShaderProgram(&shd, VEGA3dShaderProgram::SHADER_VECTOR2D, VEGA3dShaderProgram::WRAP_CLAMP_CLAMP);
if (OpStatus::IsSuccess(err))
{
VEGA3dBuffer* vbuf = NULL;
VEGA3dVertexLayout* vlayout = NULL;
unsigned int vbufStartIndex = 0;
err = createVertexBuffer_Unary(dev, &vbuf, &vlayout, &vbufStartIndex, tex, shd, region, color);
if (OpStatus::IsSuccess(err))
{
dev->setShaderProgram(shd);
shd->setOrthogonalProjection();
err = dev->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE_STRIP, vlayout, vbufStartIndex, 4);
VEGARefCount::DecRef(vlayout);
VEGARefCount::DecRef(vbuf);
}
VEGARefCount::DecRef(shd);
}
return err;
}
#endif // VEGA_3DDEVICE
#ifdef VEGA_2DDEVICE
OP_STATUS VEGAFilterMerge::apply(VEGA2dSurface* destRT, const VEGAFilterRegion& region)
{
VEGA2dDevice* dev2d = g_vegaGlobals.vega2dDevice;
if (mergeType != VEGAMERGE_OPACITY ||
!dev2d->supportsCompositeOperator(VEGA2dDevice::COMPOSITE_SRC_OPACITY))
return VEGAFilter::apply(destRT, region);
sourceStore->Validate();
dev2d->setRenderTarget(destRT);
dev2d->setColor(opacity, opacity, opacity, opacity);
dev2d->setClipRect(0, 0, destRT->getWidth(), destRT->getHeight());
dev2d->setCompositeOperator(VEGA2dDevice::COMPOSITE_SRC_OPACITY);
dev2d->blit(sourceSurf, region.sx, region.sy, region.width, region.height, region.dx, region.dy);
dev2d->setCompositeOperator(VEGA2dDevice::COMPOSITE_SRC_OVER);
return OpStatus::OK;
}
#endif // VEGA_2DDEVICE
#undef VEGA_CLAMP_U8
#undef PREMULTIPLY
#undef CLAMP_AND_PACK
#endif // VEGA_SUPPORT
|
#ifndef wali_witness_WITNESS_WRAPPER_GUARD
#define wali_witness_WITNESS_WRAPPER_GUARD 1
/**
* @author Nicholas Kidd
*/
#include "wali/Common.hpp"
#include "wali/MergeFn.hpp"
#include "wali/wpds/Wrapper.hpp"
namespace wali
{
namespace witness
{
/**
* @class WitnessWrapper
*/
class WitnessWrapper : public ::wali::wpds::Wrapper
{
public:
WitnessWrapper() {}
virtual ~WitnessWrapper() {}
virtual sem_elem_t wrap( wfa::ITrans const & t );
virtual sem_elem_t wrap( wpds::Rule const & r );
virtual merge_fn_t wrap( wpds::ewpds::ERule const & r, merge_fn_t user_merge );
virtual sem_elem_t unwrap( sem_elem_t se );
virtual merge_fn_t unwrap( merge_fn_t mf );
}; // namespace WitnessWrapper
} // namespace witness
} // namespace wali
#endif // wali_witness_WITNESS_WRAPPER_GUARD
|
//không phải mình làm
#include <iostream>
#include <string>
#include <cmath>
#include <math.h>
#include <stdio.h>
using namespace std;
class PhanSo
{
protected:
int tu, mau;
public:
PhanSo() { tu = 0; mau = 1; };
PhanSo(int x, int y)
{
tu = x; mau = y;
kiemtra();
}
PhanSo(const PhanSo&a)
{
tu = a.tu;
mau = a.mau;
}
int gettu() { return tu; }
int getmau() { return mau; }
void kiemtra()
{
if (mau < 0)
{
tu *= -1;
mau *= -1;
}
}
friend istream&operator>>(istream&cin, PhanSo& a);
friend ostream&operator<<(ostream&cout, PhanSo a);
void rutgon();
float lamtron()
{
float x, y,r;
x = float(tu);
y = float(mau);
r = round(x / y * 10000) / 10000;
return r;
}
};
istream&operator>>(istream&cin, PhanSo& a)
{
cin >> a.tu >> a.mau;
a.kiemtra();
return cin;
}
ostream&operator<<(ostream&cout, PhanSo a)
{
cout << a.tu << "/" << a.mau;
return cout;
}
void PhanSo::rutgon()
{
int x, y, r;
x = tu > mau ? tu : mau;
y = tu > mau ? mau : tu;
do
{
r = x % y;
x = y;
y = r;
} while (r != 0);
tu /= x;
mau /= x;
}
int main()
{
float a; int b,a1;
cin >> a;
if (cin >> b)
{
PhanSo ps;
a1 = int(a);
ps = PhanSo(a1, b);
ps.rutgon();
cout <<ps <<endl;
cout << ps.lamtron();
}
else
{
PhanSo ps1;
a1 = int(a * 10000);
b = 10000;
ps1 = PhanSo(a1, b);
ps1.rutgon();
ps1.kiemtra();
cout << ps1 << endl;
}
}
|
#include <iostream>
using namespace std;
void f(int xval)
{
int x;
x = xval;
cout<<"&x is: "<<&x<<endl;
}
void g(int yval)
{
int y;
cout<<"&y is: "<<&y<<endl;
}
int main()
{
f(7);
g(11);
//địa chỉ của hai biến x và y là giống nhau.
// vì khi f chạy xong biến x sẽ được thu hồi và sau đó chương trình tiếp tục để biến y sử dụng địa chỉ đó.
return 0;
}
|
#include "gtest/gtest.h"
#include "../../../../options/Option.hpp"
#include "../../../../options/OptionPut.hpp"
#include "../../../../binomial_method/case/Case.hpp"
#include "../../../../options/OptionCall.hpp"
#include "../../../../libs/cache/OptionsFunction.h"
#include "../../../../libs/cache/OptionsCache.h"
#include "../../../../binomial_method/case/LeisenKlassenMOT.hpp"
#include "../../../../binomial_method/method/regular/euro/EuroBinomialMethod.hpp"
#include "../../../../black_scholes/BlackScholesMertonPut.hpp"
#include "../../../../black_scholes/BlackScholesMertonCall.hpp"
#define GREEK_VER 2
#if GREEK_VER == 3
#include "../../../../greekjet/greekjet3/GreekJet3.h"
typedef GreekJet3 GreekJet;
#elif GREEK_VER == 3
#include "../../../../greekjet/greekjet2/GreekJet2.h"
typedef GreekJet2 GreekJet;
#else
#include "../../../../greekjet/greekjet1/GreekJet.h"
#endif
#define STEPS 1400
template<class T>
class EuroRegularPutA : public OptionsFunction<T> {
public:
T calculate(const T &i_s,
const T &i_r,
const T &i_t,
const T &i_sigma,
const int steps
) {
T e(10.);
Option<GreekJet> *option = new OptionPut<GreekJet>(i_t, i_s, i_r, i_sigma, e);
Case<GreekJet> *aCase = new LeisenKlassenMOT<GreekJet>(option, steps);
EuroBinomialMethod<GreekJet> *method = new EuroBinomialMethod<GreekJet>(aCase);
method->solve();
GreekJet result = method->getResult();
delete option;
delete aCase;
delete method;
return result;
}
};
template<class T>
class EuroRegularCallA : public OptionsFunction<T> {
T calculate(const T &i_s,
const T &i_r,
const T &i_t,
const T &i_sigma,
const int steps
) {
T e(10.);
Option<GreekJet> *option = new OptionCall<GreekJet>(i_t, i_s, i_r, i_sigma, e);
Case<GreekJet> *aCase = new LeisenKlassenMOT<GreekJet>(option, steps);
EuroBinomialMethod<GreekJet> *method = new EuroBinomialMethod<GreekJet>(aCase);
method->solve();
GreekJet result(method->getResult());
delete option;
delete aCase;
delete method;
return result;
}
};
EuroRegularCallA<GreekJet> *euroRegularCallA = new EuroRegularCallA<GreekJet>();
EuroRegularPutA<GreekJet> *euroRegularPutA = new EuroRegularPutA<GreekJet>();
OptionsCache<GreekJet> euroRegularCallACache(euroRegularCallA);
OptionsCache<GreekJet> euroRegularPutACache(euroRegularPutA);
GreekJet i_s(5., GreekJetVar ::S), i_r(0.06, GreekJetVar ::R), i_t(1., GreekJetVar ::T), i_sigma(0.3, GreekJetVar ::SIGMA);
/*************************************************************************/
TEST(greeks, EuroRegularCallA) {
BlackScholesMertonCall bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularCallACache(i_s, i_r, i_t, i_sigma, STEPS).val(), bs.calculate(0.0), 0.001);
}
TEST(greeks, EuroRegularPutB) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).val(), bs.calculate(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroDeltaRegularCallA) {
BlackScholesMertonCall bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularCallACache(i_s, i_r, i_t, i_sigma, STEPS).delta(), bs.delta(0.0), 0.001);
}
TEST(greeks, EuroDeltaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).delta(), bs.delta(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroGammaRegularCallA) {
BlackScholesMertonCall bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularCallACache(i_s, i_r, i_t, i_sigma, STEPS).gamma(), bs.gamma(0.0), 0.001);
}
TEST(greeks, EuroGammaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).gamma(), bs.gamma(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroThetaRegularCallA) {
BlackScholesMertonCall bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularCallACache(i_s, i_r, i_t, i_sigma, STEPS).theta(), bs.theta(0.0), 0.001);
}
TEST(greeks, EuroThetaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).theta(), bs.theta(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroVegaRegularCallA) {
BlackScholesMertonCall bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularCallACache(i_s, i_r, i_t, i_sigma, STEPS).vega(), bs.vega(0.0), 0.0051);
}
TEST(greeks, EuroVegaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).vega(), bs.vega(0.0), 0.0051);
}
/*************************************************************************/
TEST(greeks, EuroRhoRegularCallA) {
BlackScholesMertonCall bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularCallACache(i_s, i_r, i_t, i_sigma, STEPS).rho(), bs.rho(0.0), 0.001);
}
TEST(greeks, EuroRhoRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).rho(), bs.rho(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroVannaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).vanna(), bs.vanna(0.0), 0.0016);
}
/*************************************************************************/
TEST(greeks, EuroVommaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).vomma(), bs.vomma(0.0), 0.0106);
}
/*************************************************************************/
TEST(greeks, EuroCharmRegularCallA) {
BlackScholesMertonCall bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularCallACache(i_s, i_r, i_t, i_sigma, STEPS).charm(), bs.charm(0.0), 0.001);
}
TEST(greeks, EuroCharmRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).charm(), bs.charm(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroVetaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).veta(), bs.veta(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroVeraRegularPutA) {
EXPECT_NEAR(euroRegularCallACache(i_s, i_r, i_t, i_sigma, STEPS).vera(), 1.9071, 0.007);
}
/*************************************************************************/
TEST(greeks, EuroColorRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).color(), bs.color(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroSpeedRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).speed(), bs.speed(0.0), 0.001);
}
/*************************************************************************/
TEST(greeks, EuroUltimaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).ultima(), bs.ultima(0.0), 0.11);
}
/*************************************************************************/
TEST(greeks, EuroZommaRegularPutA) {
BlackScholesMertonPut bs(i_s.val(), 10., i_r.val(), i_sigma.val(), i_t.val());
EXPECT_NEAR(euroRegularPutACache(i_s, i_r, i_t, i_sigma, STEPS).zomma(), bs.zomma(0.0), 0.0038);
}
TEST(greeks, clean) {
delete euroRegularCallA;
delete euroRegularPutA;
}
|
/**
* Peripheral Definition File
*
* PWR - Power control
*
* MCUs containing this peripheral:
* - STM32F0xx
*/
#pragma once
#include <cstdint>
#include <cstddef>
namespace io {
struct Pwr {
/** Power control register
*/
struct Cr {
Cr(const uint32_t raw=0) { r = raw; }
struct Bits {
uint32_t LPDS : 1; // Low power deep sleep
uint32_t PDDS : 1; // Power down deep sleep
uint32_t CWUF : 1; // Clear wakeup flag
uint32_t CSBF : 1; // Clear standby flag
uint32_t PVDE : 1; // Power voltage detector enable (F0x1, F0x2, F0x8)
uint32_t PLS : 3; // PVD level selection (F0x1, F0x2, F0x8)
uint32_t DBP : 1; // Disable RTC domain write protection
uint32_t : 23;
};
struct Pls {
static const uint32_t PVD_2_2 = 0;
static const uint32_t PVD_2_3 = 1;
static const uint32_t PVD_2_4 = 2;
static const uint32_t PVD_2_5 = 3;
static const uint32_t PVD_2_6 = 4;
static const uint32_t PVD_2_7 = 5;
static const uint32_t PVD_2_8 = 6;
static const uint32_t PVD_2_9 = 7;
};
union {
uint32_t r;
Bits b;
};
};
/** Power control status register
*/
struct Csr {
Csr(const uint32_t raw=0) { r = raw; }
struct Bits {
const uint32_t WUF : 1; // Wakeup flag
const uint32_t SBF : 1; // Standby flag
const uint32_t PVDO : 1; // PVD output (F0x1, F0x2, F0x8)
const uint32_t VREFINTRDY : 1; // VREFINT reference voltage ready (F0x1, F0x2, F0x8)
uint32_t : 4;
uint32_t EWUP1 : 1; // Enable WKUPx pins
uint32_t EWUP2 : 1;
uint32_t EWUP3 : 1;
uint32_t EWUP4 : 1;
uint32_t EWUP5 : 1;
uint32_t EWUP6 : 1;
uint32_t EWUP7 : 1;
uint32_t EWUP8 : 1;
uint32_t : 16;
};
union {
uint32_t r;
Bits b;
};
};
volatile Cr CR; // Power control register
volatile Csr CSR; // Power control status register
};
namespace base {
static const size_t PWR = 0x40007000;
}
static Pwr &PWR = *reinterpret_cast<Pwr *>(base::PWR);
}
|
#include "BSerialPort.h"
#include <stdio.h>
#ifndef LINUX
BSerialPort::BSerialPort() :
hSerial(NULL)
{
}
BSerialPort::~BSerialPort()
{
Close();
}
int BSerialPort::Open(const char *devname)
{
printf("BSerialPort::Open(%s)\n", devname);
hSerial = CreateFile(devname, // //"COM1"
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if (hSerial==INVALID_HANDLE_VALUE)
{
if (GetLastError()==ERROR_FILE_NOT_FOUND)
{
//serial port does not exist. Inform user.
printf("Serial port does not exist\n");
return -1;
}
//some other error occurred. Inform user.
printf("Open serial port error\n");
return -1;
}
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 0;
if (!SetCommTimeouts(hSerial, &timeouts))
{
//error occurred. Inform user
printf("SetCommTimeouts Error\n");
return -1;
}
// return -1 if an error occurred or 0 on success
return 0;
}
int BSerialPort::Close()
{
printf("BSerialPort::Close()\n");
if (hSerial != NULL)
{
CloseHandle(hSerial);
hSerial = NULL;
}
else
return -1;
// return -1 if an error occurred or 0 on success
return 0;
}
int BSerialPort::SetBaudrate(BHBaud baud)
{
printf("BSerialPort::SetBaudrate(%d)\n", baud);
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams))
{
// error getting state
printf("SetBaudrate GetCommState Error\n");
return -1;
}
switch (baud)
{
case wxBAUD_600: { dcbSerialParams.BaudRate = CBR_600; break; }
case wxBAUD_1200: { dcbSerialParams.BaudRate = CBR_1200; break; }
case wxBAUD_2400: { dcbSerialParams.BaudRate = CBR_2400; break; }
case wxBAUD_4800: { dcbSerialParams.BaudRate = CBR_4800; break; }
case wxBAUD_9600: { dcbSerialParams.BaudRate = CBR_9600; break; }
case wxBAUD_19200: { dcbSerialParams.BaudRate = CBR_19200; break; }
case wxBAUD_38400: { dcbSerialParams.BaudRate = CBR_38400; break; }
default:
{
}
}
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if (!SetCommState(hSerial, &dcbSerialParams))
{
//error setting serial port state
printf("SetBaudrate SetCommState Error\n");
return -1;
}
// return -1 if an error occurred or 0 on success
return 0;
}
int BSerialPort::Read(char *buf, int len)
{
//printf("BSerialPort::Read(%d)\n", len);
//printf("R ");
DWORD dwBytesRead = 0;
if (!ReadFile(hSerial, buf, len, &dwBytesRead, NULL))
{
//error occurred. Report to user.
//printf("Error");
return 0;
}
return dwBytesRead; // never blocks, returns 0 or the number of bytes read
}
int BSerialPort::Readv(char *buf, int len, unsigned int timeout_in_ms)
{
//printf("BSerialPort::Readv(%d)\n", len);
//printf("Rv ");
int n = 0;
unsigned int startTicks = GetTickCount();
while (1)
{
DWORD dwBytesRead = 0;
{
if (!ReadFile(hSerial, buf, len - n, &dwBytesRead, NULL))
{
//error occurred. Report to user.
printf("ReadFile error %d ", (unsigned int)dwBytesRead);
//Sleep(1);
}
else
{
n += dwBytesRead;
buf += dwBytesRead;
if (n == len)
return n;
//else
// printf("polling %d of %d ", n, len);
//SleepEx(0);
Sleep(1); // works sortof
/*if(!SetCommMask(hSerial, EV_RXCHAR))
{
//Handle Error Condition
}*/
/*DWORD dwEventMask;
if (WaitCommEvent(hSerial, &dwEventMask, NULL))
{
}
unsigned int dt = GetTickCount() - startTicks;
if (dt >= timeout_in_ms)
{
printf("Readv long delay %d of %d dt = %d\n", n, len, dt);
}*/
}
}
unsigned int dt = GetTickCount() - startTicks;
if (timeout_in_ms != wxTIMEOUT_INFINITY && dt >= timeout_in_ms)
{
printf("Readv timeout %d of %d\n", n, len);
return n;
}
}
}
int BSerialPort::Writev(const char *buf, int len, unsigned int timeout_in_ms)
{
//printf("BSerialPort::Writev(%d)\n", len);
//printf("Wv ");
int n = 0;
unsigned int startTicks = GetTickCount();
while (1)
{
DWORD dwBytesWritten = 0;
if (!WriteFile(hSerial, buf, len - n, &dwBytesWritten, NULL))
{
//error occurred. Report to user.
printf("WriteFile error %d", (unsigned int)dwBytesWritten);
}
else
{
n += dwBytesWritten;
buf += dwBytesWritten;
if (n == len)
return n;
}
unsigned int dt = GetTickCount() - startTicks;
if (timeout_in_ms != wxTIMEOUT_INFINITY && dt >= timeout_in_ms)
return n;
}
}
#endif // LINUX
|
#ifndef ZOOM_H
#define ZOOM_H
#include "..\Statements\Statement.h"
#include "..\ApplicationManager.h"
#include "Action.h"
class Zoom : public Action
{
private:
char type; //Position where the user clicks to add the stat.
//static int G;
image i;
Point Position;
public:
Zoom(ApplicationManager *pAppManager,char c);
//static void setG(int n);
//Read Assignemt statements position
virtual void ReadActionParameters();
//Create and add an assignemnt statement to the list of statements
virtual void Execute() ;
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll as[1000010];
main()
{
ll n;
while(cin>>n)
{
ll i, ans=0, ans2=0, c=0;
for(i=1; i<=n; i++)
{
cin>>as[i];
if(i<=2)ans++;
else
{
if(as[i-1]+as[i-2]==as[i])c++;
else
c=0;
}
ans2=max(ans2, c);
}
cout<<ans+ans2<<endl;
}
return 0;
}
|
/*******************************************************************************************
Programme: main.cpp
Acteur: Kponaho Anne-Laure Magnane
Date de création: 07/04/21
But du programme: Programme principal qui fait appel aux fonctions servant *
*a implementer le jeu*
*********************************************************************************************/
#include "rectangle.h"
#include "square.h"
#include "piece.h"
using namespace std;
//prototype de la fonction
void initGrille(square grilleJeu[5][5], int nbLigne, int nbCol);
void printGrille(square grilleJeu[5][5], int nbLigne, int nbCol);
void initPiece(piece pieceJeu[], int taille);
int nextPiece(piece pieceJeu[], int taille);
int choixCase();
void putPiece(const piece& pieceJeu, square grilleJeu[5][5], int ligne, int col);
bool collisionPiece(const piece& pieceJeu, square grilleJeu[5][5], int ligne, int col);
void main()
{
//system("cls");
square grilleJeu[5][5];
piece pieceJeu[10];
bool lose = false;
int score = 0;
srand(time(nullptr)); //ajouter srand au début du main, il doit être appelé une seule fois
initGrille(grilleJeu, 5, 5); //appel de la fonction qui initialise la grille
while (!lose) //lose est un bool à false
{
system("cls");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << "Bienvenue dans ce petit jeu ou vous pouvez placer des pieces sur la grille\n"
<< "mais attention de ne pas choisir un emplacement qui est deja occupe.\n";
printGrille(grilleJeu, 5, 5); //appel de la fonction qui print la grille
initPiece(pieceJeu, 10); //appel de la fonction qui initialise et qui affiche la piece
int indicePiece = nextPiece(pieceJeu, 10);
int noCase = choixCase(); //appel de la fonction qui demande le choix de case entre 1 et 25
int ligne = (noCase - 1) / 5; //ici c’est la division entière
int col = (noCase - 1) % 5; //ici c’est le reste du modulo
if (!collisionPiece(pieceJeu[indicePiece], grilleJeu, ligne, col))
{
putPiece(pieceJeu[indicePiece], grilleJeu, ligne, col); //appel de la fonction qui
//place la piece dans la grille
printGrille(grilleJeu, 5, 5); //appel de la fonction qui initialise la grille
Sleep(100);
}
else
{
gotoxy(0, 38);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);
cout << "Cette place est impossible!";
}
Sleep(200);
}
system("PAUSE>0");
}
//fonction qui initialise la grille
void initGrille(square grilleJeu[5][5], int nbLigne, int nbCol)
{
for (int i = 0; i < nbLigne; i++)
for (int j = 0; j < nbCol; j++)
grilleJeu[i][j].setSquare(j * 8, i * 4 + 3, 5, 9, 9, i * 5 + (j + 1), false);
}
//fonction qui print la grille
void printGrille(square grilleJeu[5][5], int nbLigne, int nbCol)
{
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++) {
if (grilleJeu[i][j].isActive())
{
grilleJeu[i][j].drawFull(cout);
}
else
{
grilleJeu[i][j].draw(cout);
}
}
}
//fonction qui initialise et qui print la piece
void initPiece(piece pieceJeu[], int taille)
{
int color = rand() % 13 + 1; //change la couleur interieur de la piece aleatoirement
for (int noPiece = 0; noPiece < taille; noPiece++)
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
pieceJeu[noPiece].setPiece(i, j, square(j * 8, i * 4 + 26, 5, color, 9));
pieceJeu[0].setPieceActive(true, true, true, true); // gros carré
pieceJeu[1].setPieceActive(true, true, true, false); // | ⁻
pieceJeu[2].setPieceActive(true, true, false, true); // ⁻|
pieceJeu[3].setPieceActive(false, true, true, true); // |
pieceJeu[4].setPieceActive(true, false, true, true); // | _
pieceJeu[5].setPieceActive(true, false, true, false); // |
pieceJeu[6].setPieceActive(true, true, false, false); // --
pieceJeu[7].setPieceActive(true, false, false, false); // un petit cube
pieceJeu[8].setPieceActive(false, true, true, false); // /
pieceJeu[9].setPieceActive(true, false, false, true); // \
}
//fonction qui genere l’indice aleatoire et affiche la prochaine piece
int nextPiece(piece pieceJeu[], int taille)
{
gotoxy(0, 25);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
cout << "Prochaine piece\n";
int indicePiece = rand() % 10; //générera un nombre entre 0 et 9 et c’est ce qu’on veut
pieceJeu[indicePiece].draw(cout); //voyez si les pièces changent à l’écran
return indicePiece;
}
//fonction qui demande le choix de case entre 1 et 25
int choixCase()
{
int noCase;
do
{
gotoxy(0, 36);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
cout << "Choisissez l'endroit ou placer cette piece: ";
gotoxy(45, 36);
cin >> noCase;
gotoxy(0, 36);
cout << " ";
gotoxy(0, 37);
cout << " ";
} while (noCase < 1 || noCase > 25);
return noCase;
}
//fonction qui place la piece dans la grille
void putPiece(const piece& pieceJeu, square grilleJeu[5][5], int ligne, int col)
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
if (pieceJeu.getPiece(i, j).isActive() && (ligne + i < 5 && col + j < 5))
{
grilleJeu[ligne + i][col + j].setColor(pieceJeu.getPiece(i, j).getColor());
grilleJeu[ligne + i][col + j].setActive(pieceJeu.getPiece(i, j).isActive());
grilleJeu[ligne + i][col + j].drawFull(cout);
}
}
//fonction qui vérifie les collisions entre les pieces et retourne
//vrai s'il y a une piece dans la grille
bool collisionPiece(const piece& pieceJeu, square grilleJeu[5][5], int ligne, int col)
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
if (pieceJeu.getPiece(i,j).isActive())
{
if (ligne + i >= 5 || col + j >= 5)
return true;
if (grilleJeu[ligne + i][col + j].isActive())
return true;
}
return false;
}
|
#pragma once
#include "ofApp.h"
class ofDisplay : public ofBaseApp{
public:
void setup();
void update();
void draw();
// Pointer to main window
shared_ptr<ofApp> main;
// Which display am I?
int display;
// ofxSyphonServer displayOneServer;
// ofxSyphonClient mClient;
};
|
#pragma once
#include <DxLib.h>
#include <stdio.h>
const int QUESTION_MAX = 20; //最大問題数(一つの問題集の中の)
const int QUESTION_ELEMENT = 256; //問題文の一行の最大文字数
const int CHOICES_ELEMENT = 100; //選択肢の一行の最大文字数
enum Difficulty { //問題の難易度
EASY,
BASIC,
HARD,
DIFFICULTYMAX
};
struct q_load {
FILE* fp; //ファイル型ポインタ
char num[ 10 ]; //テキストファイルを見やすくするために書いた問題番号
char questionStatement[ 3 * QUESTION_MAX ][ QUESTION_ELEMENT ]; //問題文
char choices[ 4 * QUESTION_MAX ][ CHOICES_ELEMENT ]; //選択肢
int answerNum[ QUESTION_MAX ]; //正解番号
};
//==問題データを管理するクラス
class QuestionManager {
q_load _questionData[ DIFFICULTYMAX ]; //問題に関する構造体
public:
//--------------------------------------
//コンストラクタ・デストラクタ
QuestionManager( );
~QuestionManager( );
//--------------------------------------
//--------------------------------------
//----------------------------------------------------
//--ゲッター
q_load GetQuestionData( Difficulty difficulty );
//----------------------------------------------------
//----------------------------------------------------
//----------------------------------------------------
//--セッター
//----------------------------------------------------
//----------------------------------------------------
void LoadQuestion( ); //問題データを読み込む関数
};
|
#include "../Commands/HTTP.h"
#include "../../_CPlugin_Helper.h"
#include "../Commands/Common.h"
#include "../../ESPEasy_Log.h"
#include "../../src/DataStructs/ControllerSettingsStruct.h"
#include "../../ESPEasy_fdwdecl.h"
#include "../../ESPEasy_common.h"
String Command_HTTP_SendToHTTP(struct EventStruct *event, const char* Line)
{
if (WiFiConnected()) {
String host = parseString(Line, 2);
const int port = parseCommandArgumentInt(Line, 2);
if (loglevelActiveFor(LOG_LEVEL_DEBUG)) {
String log = F("SendToHTTP: Host: ");
log += host;
log += F(" port: ");
log += port;
addLog(LOG_LEVEL_DEBUG, log);
}
if (!port < 0 || port > 65535) return return_command_failed();
// FIXME TD-er: This is not using the tolerant settings option.
// String path = tolerantParseStringKeepCase(Line, 4);
String path = parseStringToEndKeepCase(Line, 4);
#ifndef BUILD_NO_DEBUG
if (loglevelActiveFor(LOG_LEVEL_DEBUG)) {
String log = F("SendToHTTP: Path: ");
log += path;
addLog(LOG_LEVEL_DEBUG, log);
}
#endif
WiFiClient client;
client.setTimeout(CONTROLLER_CLIENTTIMEOUT_DFLT);
const bool connected = connectClient(client, host.c_str(), port);
if (connected) {
String hostportString = host;
if (port != 0 && port != 80) {
hostportString += ':';
hostportString += port;
}
String request = do_create_http_request(hostportString, F("GET"), path);
#ifndef BUILD_NO_DEBUG
addLog(LOG_LEVEL_DEBUG, request);
#endif
send_via_http(F("Command_HTTP_SendToHTTP"), client, request, false);
}
}
return return_command_success();
}
|
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<conio.h>
#include<dos.h>
#include<math.h>
void main()
{
int gd=DETECT,gm;
int x,y,r,x1,y1,p,run;
do
{
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
printf("Enter the value of r\n==> ");
scanf("%d",&r);
printf("Enter the value of (x1,y1)\n==> ");
scanf("%d%d",&x1,&y1);
setcolor(YELLOW);
outtextxy(x1-130,y1+130,"***MID-POINT CIRCLE DRAWING ALGORITHM***");
x=0;
y=r;
p=(5/4)-r;
while(x<y)
{
putpixel(x+x1,y+y1,RED);
putpixel(x+x1,-y+y1,YELLOW);
putpixel(-x+x1,-y+y1,GREEN);
putpixel(-x+x1,y+y1,BLUE);
putpixel(y+x1,x+y1,CYAN);
putpixel(y+x1,-x+y1,WHITE);
putpixel(-y+x1,-x+y1,RED);
putpixel(-y+x1,x+y1,GREEN);
delay(50);
if(p<0)
{
p=p+2*x+3;
}
else
{
p=p+2*(x-y)+5;
y=y-1;
}
x=x+1;
}
setcolor(CYAN);
line(x1,y1+r,x1,y1);
setcolor(RED);
outtextxy(x1-3,y1-3,"*(x1,y1)");
getch();
closegraph();
printf("PRESS [1] to draw another circle or [0] to EXIT\n==> ");
scanf("%d",&run);
}while(run ==1);
}
|
#pragma once
#define DECLARE_COMPONENT_POOL(type,size) \
static const uint32_t s_kMax##type##s = size;\
type m_##type##s[size]; \
ComponentPool<type> m_##type##Pool
#define INIT_COMPONENT_POOL(type) ComponentPoolInit( SID(type), m_##type##s, &m_##type##Pool, s_kMax##type##s )
#include "Component\IComponent.h"
namespace Hourglass
{
class BaseComponentPool
{
public:
virtual IComponent* GetFree() = 0;
virtual void UpdatePooled() = 0;
virtual void StartPooled() = 0;
};
template<typename T>
class ComponentPool : public BaseComponentPool
{
public:
void Init( T* data, unsigned int size );
virtual void StartPooled();
virtual IComponent* GetFree();
virtual void UpdatePooled();
private:
T* m_data;
uint32_t m_Size;
};
template<typename T>
void ComponentPool<T>::Init( T* data, unsigned int size )
{
m_data = data;
m_Size = size;
for (unsigned int i = 0; i < m_Size; ++i)
{
data[i].Init();
}
}
template<typename T>
inline void ComponentPool<T>::StartPooled()
{
for (unsigned int i = 0; i < m_Size; ++i)
{
if(m_data[i].IsAlive())
m_data[i].Start();
}
}
template<typename T>
IComponent* ComponentPool<T>::GetFree()
{
for (unsigned int i = 0; i < m_Size; ++i)
{
if (!m_data[i].IsAlive())
{
m_data[i].SetAlive( true );
return (IComponent*)&m_data[i];
}
}
return nullptr;
}
template<typename T>
void ComponentPool<T>::UpdatePooled()
{
for (unsigned int i = 0; i < m_Size; ++i)
{
if (m_data[i].IsAlive() && m_data[i].IsEnabled())
{
m_data[i].Update();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.