text
stringlengths 8
6.88M
|
|---|
#include<cstdio>
#include<cmath>
using namespace std;
bool zhi[21000];
int ans[3];
int judge=0;
void zz(int a,int s)
{
if(s==1)
{
if(zhi[a]==0 && a>=2)
{
ans[2]=a;
judge=1;
printf("%d %d %d",ans[0],ans[1],ans[2]);
}
return ;
}
for(int i=2;i<=a;i++)
{
if(zhi[i]==0)
{
ans[3-s]=i;
zz(a-i,s-1);
if(judge==1)
return ;
}
}
}
int main()
{
int a;
scanf("%d",&a);
for(int i=2;i<=a;i++)
{
if(!zhi[i])
for(int j=2*i;j<=a;j++)
if(j%i==0)
zhi[j]=1;
}
zz(a,3);
}
|
#define LED 13 // Pin 13 onde esta conectado o LED
char rxChar= 0; // RXcHAR holds the received command.
//Funcao com menu
void printMenu(){
Serial.println("--- Serial Monitor ---");
Serial.println("a -> Ligar o LED");
Serial.println("d -> Desligar o LED");
Serial.println("s -> Status do LED");
}
void setup(){
Serial.begin(9600); // Open serial port (9600 bauds).
pinMode(LED, OUTPUT); // Sets pin 13 as OUTPUT.
Serial.flush(); // Clear receive buffer.
printMenu(); // Print the command list.
}
void loop(){
if (Serial.available() >0){ // Verifica se recebeu alguma coisa no buffer
rxChar = Serial.read(); // Salva o caracter lido
Serial.flush(); // Limpa o buffer
switch (rxChar) {
case 'a':
case 'A':
if (digitalRead(LED) == LOW){
digitalWrite(LED,HIGH);
Serial.println("LED Ligado");
} else
Serial.println("LED ja esta ligado");
break;
case 'd':
case 'D':
if (digitalRead(LED) == HIGH){
digitalWrite(LED,LOW);
Serial.println("LED desligado");
}
else Serial.println("LED ja esta desligado");
break;
case 's':
case 'S':
if (digitalRead(LED) == HIGH)
Serial.println("LED status: Ligado");
else
Serial.println("LED status: Desligado");
break;
default:
Serial.print("'");
Serial.print((char)rxChar);
Serial.println("' nao eh um comando valido!");
}
}
}
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 10 //최대 큐 크기
//함수 선언
void enqueue(char);
void dequeue();
void peek();
//큐 구조체
struct queue {
char array[MAX_QUEUE_SIZE]; //배열로 만든 환형 큐
int front = 0; //front 인덱스
int rear = 0; //rear 인덱스
} queue;
int main(void)
{
//예1
printf("예1\n");
enqueue('A'); peek(); enqueue('B'); peek(); enqueue('C'); peek(); dequeue(); dequeue();
enqueue('D'); peek(); enqueue('E'); peek(); dequeue(); dequeue(); dequeue(); dequeue();
//예2
printf("\n\n예2\n");
queue.rear = queue.front = 0; //큐 초기화
enqueue('A'); dequeue(); enqueue('B'); dequeue(); enqueue('C'); dequeue(); dequeue();
printf("\n");
queue.rear = queue.front = 0; //큐 초기화
enqueue('A'); enqueue('B'); enqueue('C'); enqueue('D'); enqueue('E'); enqueue('F');
enqueue('G'); enqueue('H'); enqueue('I'); dequeue(); peek(); enqueue('J'); enqueue('K');
}
//큐 원소 삽입 함수
void enqueue(char newone)
{
//큐가 포화 상태면 overflow라고 알려주기
if (queue.front == (queue.rear + 1) % MAX_QUEUE_SIZE)
printf("\"queue overflow\" ");
//포화상태 아니면 rear index 1 늘려서 거기에 원소 추가
else {
queue.rear = (queue.rear + 1) % MAX_QUEUE_SIZE;
queue.array[queue.rear] = newone;
}
}
//큐 원소 삭제 함수
void dequeue()
{
//큐가 비어있으면 큐가 비어있다고 알려주기
if (queue.front == queue.rear)
printf("\"queue empty\" ");
//빈게 아니라면 front 인덱스 1 추가해서 삭제할 원소 출력
else {
queue.front = (queue.front + 1) % MAX_QUEUE_SIZE;
printf("%c ", queue.array[queue.front]);
}
}
//다음에 삭제할 원소 출력
void peek()
{
//큐가 비어있으면 비어있다고 알려주기
if (queue.front == queue.rear)
printf("\"queue empty\" ");
//큐가 안비어있으면 다음에 삭제할 원소 알려주기
else {
printf("%c ", queue.array[queue.front + 1]);
}
}
|
#ifndef TRAININGDATAGENERATIONDIALOG_H
#define TRAININGDATAGENERATIONDIALOG_H
#include <QDialog>
#include "ui_TrainingDataGenerationDialog.h"
class TrainingDataGenerationDialog : public QDialog
{
Q_OBJECT
public:
TrainingDataGenerationDialog(QWidget *parent = 0);
~TrainingDataGenerationDialog();
public slots:
void onCGADirectory();
void onOutputDirectory();
void onOK();
void onCancel();
void onCenteringNoiseClicked();
void onModifyImageClicked();
void onEdgeNoiseClicked();
public:
Ui::TrainingDataGenerationDialog ui;
};
#endif // TRAININGDATAGENERATIONDIALOG_H
|
// Copyright (C) 2012-2013 Mihai Preda
#include "SymbolTable.h"
#include "GC.h"
#include "Object.h"
#include "Array.h"
#include "String.h"
#include <stdio.h>
SymbolTable::SymbolTable() {
((Object *) this)->setType(O_SYMTAB);
enterBlock(true);
}
SymbolTable::~SymbolTable() {
exitBlock(true);
}
void SymbolTable::traverse(GC *gc) {
gc->markValVect(names.buf(), names.size());
}
void SymbolTable::add(GC *gc, Array *regs, const char *name, Value v) {
regs->push(v);
set(String::value(gc, name), regs->size() - 1);
}
int SymbolTable::localsTop() {
return starts.top()->localsTop;
}
void SymbolTable::addLocalsTop(int inc) {
starts.top()->localsTop += inc;
}
void SymbolTable::enterBlock(bool isProto) {
if (isProto) {
starts.push(BlockInfo(slots.size()));
protos.push(starts.size() - 1);
} else {
starts.push(BlockInfo(slots.size(), starts.top()));
}
}
int SymbolTable::exitBlock(bool isProto) {
assert(isProto == (*protos.top() == starts.size() - 1));
if (isProto) {
protos.pop();
}
BlockInfo *info = starts.top();
int m = max(info->localsTop, info->maxLocalsTop);
const int sz = info->start;
starts.pop();
if (!isProto) {
info = starts.top();
info->maxLocalsTop = max(info->maxLocalsTop, m);
}
names.setSize(sz);
slots.setSize(sz);
return m;
}
int SymbolTable::getProtoLevel(int pos) {
for (int i = protos.size()-1; i >= 0; --i) {
if (starts[protos[i]].start <= pos) { return i; }
}
return -1;
}
int SymbolTable::getBlockLevel(int pos) {
for (int i = starts.size() - 1; i >= 0; --i) {
if (starts[i].start <= pos) { return i; }
}
return -1;
}
int SymbolTable::findPos(Value name) {
for (Value *buf = names.buf(), *p = buf + names.size() - 1; p >= buf; --p) {
if (equals(name, *p)) {
return p - buf;
}
}
return -1;
}
bool SymbolTable::get(Value name, int *slot, int *protoLevel, int *blockLevel) {
int pos = findPos(name);
if (pos == -1) { return false; }
if (slot) {
*slot = slots.get(pos);
}
if (protoLevel) {
*protoLevel = getProtoLevel(pos);
}
if (blockLevel) {
*blockLevel = getBlockLevel(pos);
}
return true;
}
bool SymbolTable::definedInThisBlock(Value name) {
int nameLevel = 0;
int blockLevel = this->blockLevel();
get(name, 0, 0, &nameLevel);
assert(blockLevel > 0 && nameLevel <= blockLevel);
return nameLevel == blockLevel;
}
void SymbolTable::set(Value name, int slot) {
names.push(name);
slots.push(slot);
}
int SymbolTable::set(Value name) {
int slot = starts.top()->localsTop++;
set(name, slot);
return slot;
}
void SymbolTable::setUpval(Value name, int slot, int protoLevel) {
assert(slot < 0);
int block = protos.get(protoLevel);
int pos = starts.get(block).start;
names.insertAt(pos, name);
slots.insertAt(pos, slot);
for (BlockInfo *buf = starts.buf(), *p = buf + block + 1, *end = buf + starts.size(); p < end; ++p) { ++(p->start); }
}
|
#include<iostream>
#include<vector>
using namespace std;
//caluculate area of rectangle
int area(int length, int width) {
return length*width;
}
double area(double length, double width) {
return length*width;
}
int framed_area(int x, int y) {
return area(x - 2, y - 2);
}
int main() {
int x = -1;
int y = 2;
int z = 4;
int area1 = area(x, y);
int area2 = framed_area(1, z);
int area3 = framed_area(y, z);
cout << area1 << endl;
cout << area2 << endl;
cout << area3 << endl;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int a,b,c,d,n;
int ok(int x){
if(x>=1&&x<=n)
return 1;
else return 0;
}
int main(){
cin>>n>>a>>b>>c>>d;
int e;
long long int ans=0;
for(int i=1;i<=n;i++){
e=i;
if(ok(e+a-d)&&ok(e+b-c)&&ok(e+a+b-c-d))
ans++;
}
ans*=n;
printf("%lld",ans);
return 0;
}
|
// Created on: 1999-11-26
// Created by: Andrey BETENEV
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepBasic_ActionMethod_HeaderFile
#define _StepBasic_ActionMethod_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Transient.hxx>
class TCollection_HAsciiString;
class StepBasic_ActionMethod;
DEFINE_STANDARD_HANDLE(StepBasic_ActionMethod, Standard_Transient)
//! Representation of STEP entity ActionMethod
class StepBasic_ActionMethod : public Standard_Transient
{
public:
//! Empty constructor
Standard_EXPORT StepBasic_ActionMethod();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Standard_Boolean hasDescription, const Handle(TCollection_HAsciiString)& aDescription, const Handle(TCollection_HAsciiString)& aConsequence, const Handle(TCollection_HAsciiString)& aPurpose);
//! Returns field Name
Standard_EXPORT Handle(TCollection_HAsciiString) Name() const;
//! Set field Name
Standard_EXPORT void SetName (const Handle(TCollection_HAsciiString)& Name);
//! Returns field Description
Standard_EXPORT Handle(TCollection_HAsciiString) Description() const;
//! Set field Description
Standard_EXPORT void SetDescription (const Handle(TCollection_HAsciiString)& Description);
//! Returns True if optional field Description is defined
Standard_EXPORT Standard_Boolean HasDescription() const;
//! Returns field Consequence
Standard_EXPORT Handle(TCollection_HAsciiString) Consequence() const;
//! Set field Consequence
Standard_EXPORT void SetConsequence (const Handle(TCollection_HAsciiString)& Consequence);
//! Returns field Purpose
Standard_EXPORT Handle(TCollection_HAsciiString) Purpose() const;
//! Set field Purpose
Standard_EXPORT void SetPurpose (const Handle(TCollection_HAsciiString)& Purpose);
DEFINE_STANDARD_RTTIEXT(StepBasic_ActionMethod,Standard_Transient)
protected:
private:
Handle(TCollection_HAsciiString) theName;
Handle(TCollection_HAsciiString) theDescription;
Handle(TCollection_HAsciiString) theConsequence;
Handle(TCollection_HAsciiString) thePurpose;
Standard_Boolean defDescription;
};
#endif // _StepBasic_ActionMethod_HeaderFile
|
#include "stdafx.h"
#include "BitmapTooltip.h"
IMPLEMENT_DYNAMIC(CBitmapTooltip, CWnd)
BEGIN_MESSAGE_MAP(CBitmapTooltip, CWnd)
ON_WM_SIZE()
ON_WM_PAINT()
ON_WM_ERASEBKGND()
END_MESSAGE_MAP()
CBitmapTooltip::CBitmapTooltip( CRect& rect )
{
// Register your unique class name that you wish to use
CString strMyClass;
// load stock cursor, brush, and icon for
// my own window class
try
{
strMyClass = AfxRegisterWndClass(
CS_VREDRAW | CS_HREDRAW,
::LoadCursor(NULL, IDC_ARROW),
(HBRUSH) ::GetStockObject(NULL_BRUSH),
NULL);
}
catch (CResourceException* pEx)
{
AfxMessageBox(
_T("Couldn't register class! (Already registered?)"));
pEx->Delete();
}
BOOL hRes = CreateEx( WS_EX_TOOLWINDOW | WS_EX_TOPMOST, strMyClass, "", WS_VISIBLE | WS_POPUP | WS_BORDER , rect, GetDesktopWindow(), 0 );
if ( hRes )
{
ModifyStyle(WS_CAPTION,0);
SetMenu(NULL);
CRect rectCL;
GetClientRect(rectCL);
m_Image.Create(_T(""), WS_CHILD|WS_VISIBLE|SS_BITMAP, rectCL,this, 0);
m_Text.Create( "", WS_CHILD | WS_VISIBLE | SS_LEFT, CRect( 0, 0, 0, 0 ), this, 1 );
m_Image.ModifyStyleEx( 0, WS_EX_STATICEDGE );
m_Text.ModifyStyleEx( 0, WS_EX_STATICEDGE );
}
LoadImage("nskingr.jpg");
}
CBitmapTooltip::~CBitmapTooltip()
{
if ( m_Bitmap.m_hObject )
{
m_Bitmap.DeleteObject();
}
}
bool CBitmapTooltip::LoadImage( const CString& imageFileName )
{
if ( !m_hWnd )
return false;
if ( m_FileName == imageFileName )
return true;
m_FileName = imageFileName;
Ogre::Image image;
image.load(m_FileName.GetBuffer(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
CString imgInfo;
imgInfo.Format( "%dX%d (%d) %s", image.getWidth(), image.getHeight(), image.getBPP(),
Ogre::PixelUtil::getFormatName( image.getPixelBox().format ).c_str() );
m_Text.SetWindowText( imgInfo );
int w = image.getWidth();
int h = image.getHeight();
if ( w > 256 || w == 0 )
{
w = 256;
}
if ( h > 256 || h == 0 )
{
h = 256;
}
w = 256;
h = 256;
CRect rc;
GetWindowRect(rc);
if ( rc.Width() != w || rc.Height() != h )
{
SetWindowPos( NULL, 0, 0, w + 4, h + 4 + 20, SWP_NOMOVE );
}
ShowWindow(SW_SHOW);
CRect bmpRc;
m_Image.GetClientRect( bmpRc );
w = bmpRc.Width();
h = bmpRc.Height();
//image.resize( w, h );
w = image.getWidth();
h = image.getHeight();
Ogre::PixelBox* pixel_box = &image.getPixelBox();
int rowSpan = image.getBPP() / 8;
const int nPixelCount = w * h;
const unsigned char *pPBData = (unsigned char *)pixel_box->data;
Ogre::uint8 *pImage = new Ogre::uint8[w * h*4];
Ogre::uint8 r, g, b, a;
for (int i=0; i<nPixelCount; i++)
{
Ogre::PixelUtil::unpackColour(&r, &g, &b, &a, pixel_box->format, pPBData + i*rowSpan);
if ( pixel_box->format == Ogre::PF_A8R8G8B8 )
{
pImage[i*4] = b;
pImage[i*4+1] = g;
pImage[i*4+2] = r;
pImage[i*4+3] = a;
}
else
{
pImage[i*4] = b;
pImage[i*4+1] = g;
pImage[i*4+2] = r;
pImage[i*4+3] = a;
}
}
BOOL bOk = m_Bitmap.CreateBitmap( w, h, 1, 32, pImage );
delete[] pImage;
//if ( m_Bitmap.m_hObject )
//{
// m_Image.SetBitmap( m_Bitmap );
//}
//else
//{
// m_Image.SetBitmap( NULL );
//}
m_Image.SetBitmap( NULL );
RedrawWindow();
Invalidate();
return true;
}
void CBitmapTooltip::OnSize(UINT nType, int cx, int cy)
{
__super::OnSize(nType,cx,cy);
if ( m_Image.m_hWnd )
{
CRect rcClient;
GetClientRect(rcClient);
CRect rc(rcClient);
rc.bottom -= 20;
m_Image.MoveWindow(rc,FALSE);
rc = rcClient;
rc.top = rc.bottom - 20;
m_Text.MoveWindow(rc, FALSE);
}
}
BOOL CBitmapTooltip::OnEraseBkgnd(CDC* pDC)
{
// "Tile" bitmap (see demo for actual code)
return TRUE; // tell Windows we handled it
}
void CBitmapTooltip::OnPaint()
{
CPaintDC dc(this);
HBITMAP hBitmap = m_Bitmap;
if( hBitmap )
{
CDC bitmapDC;
CRect rect;
GetClientRect(rect);
dc.FillSolidRect(&rect,RGB(125, 125, 125));
if (bitmapDC.CreateCompatibleDC(&dc))
{
BITMAP bm;
m_Bitmap.GetBitmap(&bm);
CBitmap* pOldBmp = bitmapDC.SelectObject(&m_Bitmap);
dc.StretchBlt(1,1,257,258,&bitmapDC, 0,0,bm.bmWidth,bm.bmHeight, SRCCOPY);
bitmapDC.SelectObject(pOldBmp);
}
}
}
|
//
// George O'Neill @ University of York, 2020
//
// This file holds methods for gates, except they actually are all short enough for the header
//
#include "../include/Gate.h"
namespace fnt{ // create unique working area
} // end namespace fnt
void Gate(){} // allow root compilation
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Cpp.h"
#include "BattleHUD.h"
#include "TargetActor.h"
void ABattleHUD::DrawHUD()
{
const FVector2D ViewportSize = FVector2D(GEngine->GameViewport->Viewport->GetSizeXY());
ViewportSizeX = ViewportSize.X;
ViewportSizeY = ViewportSize.Y;
ViewportCenter = FVector2D(ViewportSize.X / 2, ViewportSize.Y / 2);
UE_LOG(LogTemp, Warning, TEXT("I am Battle HUD"));
FoundActors.Reset();
GetActorsInSelectionRectangle(GetSelectionPointA(), GetSelectionPointB(), FoundActors, bIncludeNonCollidingComponents, bActorMustBeFullyEnclosed);
//gotta add this to a function!
Draw2DLine(GetSelectionPointA().X, GetSelectionPointA().Y, GetSelectionPointA().X, GetSelectionPointB().Y, FColor::Red);
Draw2DLine(GetSelectionPointA().X, GetSelectionPointA().Y, GetSelectionPointB().X, GetSelectionPointA().Y, FColor::Red);
Draw2DLine(GetSelectionPointA().X, GetSelectionPointB().Y, GetSelectionPointB().X, GetSelectionPointB().Y, FColor::Red);
Draw2DLine(GetSelectionPointB().X, GetSelectionPointA().Y, GetSelectionPointB().X, GetSelectionPointB().Y, FColor::Red);
}
FVector2D ABattleHUD::GetSelectionPointA() {
const FVector2D Result = FVector2D(ViewportCenter.X - CrosshairSize*ViewportSizeX/10, ViewportCenter.Y - CrosshairSize*ViewportSizeX / 10);
return Result;
}
FVector2D ABattleHUD::GetSelectionPointB() {
const FVector2D Result = FVector2D(ViewportCenter.X + CrosshairSize*ViewportSizeX/10, ViewportCenter.Y + CrosshairSize*ViewportSizeX / 10);
return Result;
}
|
void nextComb(int left, int sum, vector<int> A, int B, vector<int> comb, vector<vector<int> > &ans) {
if (sum == B) {
ans.push_back(comb);
return;
}
// if (sum == B) {
// if (ans.empty())
// ans.push_back(comb);
// else if (ans[ans.size() - 1] != comb)
// ans.push_back(comb);
// return;
// }
for (int i = left; i < A.size(); i++) {
// This will take once and skip duplicate entries
if (i > left && A[i] == A[i - 1])
continue;
if (sum + A[i] <= B) {
comb.push_back(A[i]);
sum += A[i];
nextComb(i + 1, sum, A, B, comb, ans);
comb.pop_back();
sum -= A[i];
}
}
}
vector<vector<int> > Solution::combinationSum(vector<int> &A, int B) {
sort(A.begin(), A.end());
vector<vector<int> > ans;
nextComb(0, 0, A, B, vector<int> (), ans);
return ans;
}
|
/*
* This code prints that how many
* days in a day with user input
* In this code switch-case method was used
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int month = 0;
int year = 0; //for february
printf("Enter yhe month (in numbers): ");
scanf("%d", &month);
switch (month)
{
case 2:
printf("Enter the year: ");
scanf("%d", &year);
printf("%s days\n", year % 4 == 0 ? "29" : "28");
break;
case 4:
case 6:
case 9:
case 11:
printf("30 days\n");
break;
default:
printf("31 days\n");
break;
}
return EXIT_SUCCES;
}
|
#include<iostream>
using namespace std;
class stack{
int arr[50],top,max,x;
public:
stack()
{
top=-1;
max=25;
}
int isfull()
{
return(top==max);
}
int isempty()
{
return(top<0);
}
void push()
{
if (isfull())
cout<<"stack overflow";
else{
cout<<"enter the number to push: ";
cin>>x;
top++;
arr[top]=x;
}
}
void pop()
{
if (isempty())
cout<<"stack is empty"<<endl;
else
{
cout<<"the number popped is: "<<arr[top]<<endl;
top--;
}
}
void display()
{
cout<<"the stack is\n";
if(top>-1)
for(int i=top;i>=0;i--)
cout<<arr[i]<<endl;
else
cout<<"empty \n";
}
~stack()
{
cout<"destructor called";
}
};
int main()
{
stack s;
int k,l;
char c;
do{
cout<<"enter the number of elements to push:"<<endl;
cin >>k;
for(int i=0;i<k;i++)
s.push();
s.display();
cout<<"enter the number of elements to pop:"<<endl;
cin>>l;
for(int i=0;i<l;i++)
s.pop();
s.display();
cout<<"do you want to continue?"<<endl;
cin>>c;
}
while(c=='y'||c=='Y');
return 0;
}
|
/*********************************************************************************************
cfglp : A CFG Language Processor
--------------------------------
About:
Implemented by Tanu Kanvar (tanu@cse.iitb.ac.in) and Uday
Khedker (http://www.cse.iitb.ac.in/~uday) for the courses
cs302+cs306: Language Processors (theory and lab) at IIT
Bombay.
Release date Jan 15, 2013. Copyrights reserved by Uday
Khedker. This implemenation has been made available purely
for academic purposes without any warranty of any kind.
Documentation (functionality, manual, and design) and related
tools are available at http://www.cse.iitb.ac.in/~uday/cfglp
***********************************************************************************************/
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
#include"user-options.hh"
#include"error-display.hh"
#include"local-environment.hh"
#include"symbol-table.hh"
#include"ast.hh"
#include"basic-block.hh"
#include"procedure.hh"
#include"program.hh"
Ast::Ast()
{}
Ast::~Ast()
{}
bool Ast::check_ast(int line)
{
report_internal_error("Should not reach, Ast : check_ast");
}
Data_Type Ast::get_data_type()
{
report_internal_error("Should not reach, Ast : get_data_type");
}
void Ast::print_value(Local_Environment & eval_env, ostream & file_buffer)
{
report_internal_error("Should not reach, Ast : print_value");
}
int Ast::get_successor()
{
report_internal_error("Should not reach, Ast : get_successor");
}
Eval_Result & Ast::get_value_of_evaluation(Local_Environment & eval_env)
{
report_internal_error("Should not reach, Ast : get_value_of_evaluation");
}
void Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result)
{
report_internal_error("Should not reach, Ast : set_value_of_evaluation");
}
////////////////////////////////////////////////////////////////
Assignment_Ast::Assignment_Ast(Ast * temp_lhs, Ast * temp_rhs)
{
lhs = temp_lhs;
rhs = temp_rhs;
successor = -1;
}
Assignment_Ast::~Assignment_Ast()
{
delete lhs;
delete rhs;
}
Data_Type Assignment_Ast::get_data_type()
{
return node_data_type;
}
bool Assignment_Ast::check_ast(int line)
{
if (lhs->get_data_type() == rhs->get_data_type())
{
node_data_type = lhs->get_data_type();
return true;
}
report_error("Assignment statement data type not compatible", line);
}
void Assignment_Ast::print_ast(ostream & file_buffer)
{
file_buffer << "\n";
file_buffer << AST_SPACE << "Asgn:\n";
file_buffer << AST_NODE_SPACE << "LHS (";
lhs->print_ast(file_buffer);
file_buffer << ")\n";
file_buffer << AST_NODE_SPACE << "RHS (";
rhs->print_ast(file_buffer);
file_buffer << ")";
}
int Assignment_Ast::get_successor(){
return successor;
}
Eval_Result & Assignment_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
Eval_Result & result = rhs->evaluate(eval_env, file_buffer);
//printf("\n:: %d \n",result.is_variable_defined() );
lhs->set_value_of_evaluation(eval_env, result);
// Print the result
file_buffer << "\n";
file_buffer << AST_SPACE << "Asgn:\n";
file_buffer << AST_NODE_SPACE << "LHS (";
lhs->print_ast(file_buffer);
file_buffer << ")\n";
file_buffer << AST_NODE_SPACE << "RHS (";
rhs->print_ast(file_buffer);
file_buffer << ")";
lhs->print_value(eval_env, file_buffer);
return result;
}
/////////////////////////////////////////////////////////////////
Goto_Ast::Goto_Ast(int temp_bb)
{
bb = temp_bb;
successor = temp_bb;
}
Goto_Ast::~Goto_Ast()
{
}
Data_Type Goto_Ast::get_data_type()
{
return node_data_type;
}
bool Goto_Ast::check_ast(int line)
{
if (bb > 1)
{
return true;
}
report_error("Basic block should be greater than one.", line);
}
void Goto_Ast::print_ast(ostream & file_buffer)
{
file_buffer << "\n";
file_buffer << AST_SPACE << "Goto statement:\n";
file_buffer << AST_NODE_SPACE << "Successor: " << bb;
}
int Goto_Ast::get_successor(){
return successor;
}
Eval_Result & Goto_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
// Print the result
print_ast(file_buffer);
Eval_Result & result = *new Eval_Result_Value_Int();
result.set_value(bb);
file_buffer << "\n";
file_buffer << AST_SPACE << "GOTO (BB " << successor << ")\n";
successor = bb;
return result;
}
/////////////////////////////////////////////////////////////////
If_Else_Ast::If_Else_Ast(Ast * temp_gotoTrue, Ast * temp_condition, Ast * temp_gotoFalse)
{
gotoTrue = temp_gotoTrue;
condition = temp_condition;
gotoFalse = temp_gotoFalse;
successor = -3;
}
If_Else_Ast::~If_Else_Ast()
{
delete gotoTrue;
delete gotoFalse;
delete condition;
}
Data_Type If_Else_Ast::get_data_type()
{
return node_data_type;
}
bool If_Else_Ast::check_ast(int line)
{
if ((gotoTrue->get_successor() > 1) && (gotoFalse->get_successor() > 1))
{
return true;
}
report_error("Basic block should be greater than one.", line);
}
void If_Else_Ast::print_ast(ostream & file_buffer)
{
file_buffer << "\n";
file_buffer << AST_SPACE << "If_Else statement:";
condition->print_ast(file_buffer);
file_buffer << "\n";
file_buffer << AST_NODE_SPACE << "True Successor: " << gotoTrue->get_successor();
file_buffer << "\n";
file_buffer << AST_NODE_SPACE << "False Successor: " << gotoFalse ->get_successor();
}
int If_Else_Ast::get_successor(){
return successor;
}
Eval_Result & If_Else_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
// Print the result
file_buffer << "\n";
file_buffer << AST_SPACE << "If_Else statement:";
condition->print_ast(file_buffer);
Eval_Result & conditionResult = condition->evaluate(eval_env, file_buffer);
int value = conditionResult.get_value();
Eval_Result & result = *new Eval_Result_Value_Int();
file_buffer << "\n";
file_buffer << AST_NODE_SPACE << "True Successor: " << gotoTrue->get_successor();
file_buffer << "\n";
file_buffer << AST_NODE_SPACE << "False Successor: " << gotoFalse ->get_successor();
file_buffer << "\n";
if(value == 1){
file_buffer << AST_SPACE << "Condition True : Goto (BB " << gotoTrue->get_successor() << ")\n";
successor = gotoTrue->get_successor();
}
else{
file_buffer << AST_SPACE << "Condition False : Goto (BB " << gotoFalse->get_successor() << ")\n";
successor = gotoFalse->get_successor();
}
result.set_value(successor);
return result;
}
/////////////////////////////////////////////////////////////////
Relational_Expr_Ast::Relational_Expr_Ast(Ast * temp_lhs, relational_operators temp_oper, Ast * temp_rhs)
{
lhs = temp_lhs;
rhs = temp_rhs;
oper = temp_oper;
node_data_type = int_data_type;
successor = -1;
}
Relational_Expr_Ast::~Relational_Expr_Ast()
{
delete lhs;
delete rhs;
}
Data_Type Relational_Expr_Ast::get_data_type()
{
return node_data_type;
}
bool Relational_Expr_Ast::check_ast(int line)
{
if (lhs->get_data_type() == rhs->get_data_type())
{
//change here
node_data_type = int_data_type;
return true;
}
report_error("Relational expression data type not compatible", line);
}
void Relational_Expr_Ast::print_ast(ostream & file_buffer)
{
file_buffer << "\n";
file_buffer << AST_NODE_SPACE << "Condition: ";
if (oper == LT) {
file_buffer << "LT\n";
}
else if (oper == LE) {
file_buffer << "LE\n";
}
else if (oper == GT) {
file_buffer << "GT\n";
}
else if (oper == GE){
file_buffer << "GE\n";
}
else if (oper == EQ){
file_buffer << "EQ\n";
}
else if (oper == NE){
file_buffer << "NE\n";
}
else if (oper == AND){
file_buffer << "AND\n";
}
else if (oper == OR){
file_buffer << "OR\n";
}
else if (oper == NOT){
file_buffer << "NOT\n";
}
file_buffer << AST_SMALL_SPACE << AST_NODE_SPACE << "LHS (";
lhs->print_ast(file_buffer);
file_buffer << ")\n";
if (oper != NOT){
file_buffer << AST_SMALL_SPACE << AST_NODE_SPACE << "RHS (";
rhs->print_ast(file_buffer);
file_buffer << ")";
}
}
int Relational_Expr_Ast::get_successor(){
return successor;
}
Eval_Result & Relational_Expr_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(oper == GT){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on lhs of condition", NOLINE);
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if (rhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on lhs of condition", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if(lhsResult.get_value() > rhsResult.get_value()){
result.set_value(1);
}
else{
result.set_value(0);
}
return result;
}
else if(oper == LT){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if (rhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if(lhsResult.get_value() < rhsResult.get_value()){
result.set_value(1);
}
else{
result.set_value(0);
}
return result;
}
else if(oper == GE){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if (rhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if(lhsResult.get_value() >= rhsResult.get_value()){
result.set_value(1);
}
else{
result.set_value(0);
}
return result;
}
else if(oper == LE){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if (rhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if(lhsResult.get_value() <= rhsResult.get_value()){
result.set_value(1);
}
else{
result.set_value(0);
}
return result;
}
else if(oper == EQ){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if (rhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if(lhsResult.get_value() == rhsResult.get_value()){
result.set_value(1);
}
else{
result.set_value(0);
}
return result;
}
else if(oper == NE){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if (rhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if(lhsResult.get_value() != rhsResult.get_value()){
result.set_value(1);
}
else{
result.set_value(0);
}
return result;
}
else if(oper == AND){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if (rhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if((lhsResult.get_value()) && (rhsResult.get_value())){
result.set_value(1);
}
else{
result.set_value(0);
}
return result;
}
else if(oper == OR){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if (rhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if((lhsResult.get_value()) || (rhsResult.get_value())){
result.set_value(1);
}
else{
result.set_value(0);
}
return result;
}
else if(oper == NOT){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if (lhsResult.is_variable_defined() == false)
report_error("Variable should be defined to be on rhs", NOLINE);
Eval_Result & result = *new Eval_Result_Value_Int();
if(lhsResult.get_value()){
result.set_value(0);
}
else{
result.set_value(1);
}
return result;
}
}
//////////////////////////////////////////////////////////////////////////////////////
Arithmetic_Expr_Ast::Arithmetic_Expr_Ast(Ast * temp_lhs, arithmetic_operators temp_oper, Ast * temp_rhs){
lhs = temp_lhs;
rhs = temp_rhs;
oper = temp_oper;
successor = -1;
}
Arithmetic_Expr_Ast::~Arithmetic_Expr_Ast()
{
delete lhs;
delete rhs;
}
Data_Type Arithmetic_Expr_Ast::get_data_type()
{
return node_data_type;
}
bool Arithmetic_Expr_Ast::check_ast(int line)
{
if(rhs != NULL){
if (lhs->get_data_type() == rhs->get_data_type())
{
node_data_type = lhs->get_data_type();
return true;
}
}
else{
if(oper == UMINUS){
node_data_type = lhs->get_data_type();
}
else if(oper == I_NUM){
node_data_type = int_data_type;
}
else if(oper == F_NUM){
node_data_type = float_data_type;
}
else if(oper == VAR){
node_data_type = lhs->get_data_type();
}
return true;
}
report_error("Arithmetic expression data type not compatible", line);
}
void Arithmetic_Expr_Ast::print_ast(ostream & file_buffer)
{
if (oper == VAR || oper == F_NUM || oper == I_NUM){
lhs->print_ast(file_buffer);
}
else{
file_buffer << "\n";
file_buffer << AST_NODE_SPACE << "Arith: ";
if (oper == PLUS) {
file_buffer << "PLUS\n";
}
else if (oper == MINUS) {
file_buffer << "MINUS\n";
}
else if (oper == MULT) {
file_buffer << "MULT\n";
}
else if (oper == DIV){
file_buffer << "DIV\n";
}
else if (oper == UMINUS){
file_buffer << "UMINUS\n";
}
file_buffer << AST_SMALL_SPACE << AST_NODE_SPACE << "LHS (";
lhs->print_ast(file_buffer);
file_buffer << ")";
if (oper != I_NUM && oper != F_NUM && oper != UMINUS){
file_buffer << "\n" << AST_SMALL_SPACE << AST_NODE_SPACE << "RHS (";
rhs->print_ast(file_buffer);
file_buffer << ")";
}
}
}
int Arithmetic_Expr_Ast::get_successor(){
return successor;
}
Eval_Result & Arithmetic_Expr_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer){
Eval_Result & lhsResult = lhs->evaluate(eval_env, file_buffer);
if(rhs != NULL){
Eval_Result & rhsResult = rhs->evaluate(eval_env, file_buffer);
if(lhs->get_data_type() == int_data_type && rhs->get_data_type() == int_data_type){
Eval_Result & result = *new Eval_Result_Value_Int();
if(oper == PLUS){
int lh_result = lhsResult.get_value();
int rh_result = rhsResult.get_value();
int res = lh_result + rh_result;
result.set_value(res);
}
if(oper == MINUS){
int lh_result = lhsResult.get_value();
int rh_result = rhsResult.get_value();
int res = lh_result - rh_result;
result.set_value(res);
}
if(oper == DIV){
if((int) rhsResult.get_value() != 0){
int lh_result = lhsResult.get_value();
int rh_result = rhsResult.get_value();
int res = lh_result / rh_result;
result.set_value(res);
}
else{
report_error("Divided by zero", NOLINE);
}
}
if(oper == MULT){
int lh_result = lhsResult.get_value();
int rh_result = rhsResult.get_value();
int res = lh_result * rh_result;
result.set_value(res);
}
return result;
}
else if(lhs->get_data_type() == float_data_type && rhs->get_data_type() == float_data_type){
Eval_Result & result = *new Eval_Result_Value_Float();
if(oper == PLUS){
result.set_value((float) (lhsResult.get_value() + rhsResult.get_value()) );
}
if(oper == MINUS){
result.set_value((float) (lhsResult.get_value() - rhsResult.get_value()) );
}
if(oper == DIV){
if(rhsResult.get_value() != 0){
result.set_value((float) (lhsResult.get_value() / rhsResult.get_value()) );
}
else{
report_error("Divided by zero", NOLINE);
}
}
if(oper == MULT){
result.set_value((float) (lhsResult.get_value() * rhsResult.get_value()) );
}
return result;
}
}
else{
if(oper == F_NUM){
Eval_Result_Value_Float & result = *new Eval_Result_Value_Float();
//file_buffer << fixed << setprecision(2) << lhsResult.get_value();
result.set_value((float) lhsResult.get_value());
return result;
}
else if(lhs->get_data_type() == int_data_type){
Eval_Result_Value_Int & result = *new Eval_Result_Value_Int();
if(oper == UMINUS){
result.set_value((int) -1*lhsResult.get_value());
}
if(oper == VAR){
result.set_value((int) lhsResult.get_value());
}
if(oper == I_NUM){
result.set_value((int) lhsResult.get_value());
}
return result;
}
else{
Eval_Result_Value_Float & result = *new Eval_Result_Value_Float();
if(oper == UMINUS){
result.set_value((float) -1*lhsResult.get_value());
}
if(oper == VAR){
result.set_value((float) lhsResult.get_value());
}
if(oper == I_NUM){
result.set_value((float) lhsResult.get_value());
}
return result;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////
Function_Call_Ast::Function_Call_Ast(string name , Data_Type return_data_type, list <Ast *> * input_list){
func_name = name;
input_argument_list = input_list;
successor = -1;
node_data_type = return_data_type;
}
Function_Call_Ast::~Function_Call_Ast()
{
}
Data_Type Function_Call_Ast::get_data_type()
{
return node_data_type;
}
bool Function_Call_Ast::check_ast(int line)
{
}
void Function_Call_Ast::print_ast(ostream & file_buffer)
{
Procedure *funct_call = program_object.get_procedure(func_name);
if(!funct_call->is_body_defined()){
report_error("Procedure Body is not defined" , NOLINE);
}
file_buffer<<"\n";
file_buffer << AST_SPACE << "FN CALL: ";
list<Ast *>::iterator i;
if(input_argument_list != NULL){
//file_buffer << AST_NODE_SPACE ;
file_buffer <<func_name << "(";
for(i = input_argument_list->begin(); i != input_argument_list->end(); i++){
file_buffer<<"\n";
file_buffer << AST_NODE_SPACE ;
(*i)->print_ast(file_buffer);
}
}
else
file_buffer <<func_name << "(";
file_buffer << ")";
}
int Function_Call_Ast::get_successor(){
return successor;
}
Eval_Result & Function_Call_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer){
Procedure *funct_call = program_object.get_procedure(func_name);
if(!funct_call->is_body_defined()){
report_error("Procedure Body is not defined" , NOLINE);
}
Argument_Table & arg = funct_call->get_argument_symbol_table();
Local_Environment & func_eval_env = *new Local_Environment();
//arg.create(func_eval_env);
list<Ast *>::iterator i;
if(input_argument_list!=NULL){
list<Symbol_Table_Entry *>::iterator j;
i = input_argument_list->begin();
j = arg.variable_table.begin();
for(;i != input_argument_list->end();i++,j++){
Eval_Result_Value * k;
string variable_name = (*j)->get_variable_name();
Eval_Result & result = (*i)->evaluate(eval_env, file_buffer);
if (result.get_result_enum() == int_result && (*j)->get_data_type() == int_data_type)
{
k = new Eval_Result_Value_Int();
k->set_value((int)result.get_value());
func_eval_env.put_variable_value(*k, variable_name);
}
else if(result.get_result_enum() == float_result && (*j)->get_data_type() == float_data_type){
k = new Eval_Result_Value_Float();
k->set_value(result.get_value());
func_eval_env.put_variable_value(*k, variable_name);
}
else{
report_error("Passed argument is not compatible",NOLINE);
}
}
}
Eval_Result & return_result = funct_call->evaluate(func_eval_env,file_buffer);
return return_result;
}
/////////////////////////////////////////////////////////////////
Name_Ast::Name_Ast(string & name, Symbol_Table_Entry & var_entry)
{
variable_name = name;
variable_symbol_entry = var_entry;
successor = -1;
}
Name_Ast::~Name_Ast()
{}
Data_Type Name_Ast::get_data_type()
{
return variable_symbol_entry.get_data_type();
}
void Name_Ast::print_ast(ostream & file_buffer)
{
//printf("arith_ast ");
file_buffer << "Name : " << variable_name;
}
void Name_Ast::print_value(Local_Environment & eval_env, ostream & file_buffer)
{
Eval_Result_Value * loc_var_val = eval_env.get_variable_value(variable_name);
Eval_Result_Value * glob_var_val = interpreter_global_table.get_variable_value(variable_name);
file_buffer << "\n" << AST_SPACE << variable_name << " : ";
if (!eval_env.is_variable_defined(variable_name) && !interpreter_global_table.is_variable_defined(variable_name))
file_buffer << "undefined";
else if (eval_env.is_variable_defined(variable_name) && loc_var_val != NULL)
{
if (loc_var_val->get_result_enum() == int_result)
file_buffer << (int) loc_var_val->get_value() << "\n";
else if(loc_var_val->get_result_enum() == float_result)
file_buffer << fixed << setprecision(2) << loc_var_val->get_value() << "\n";
else
report_internal_error("Result type can only be int and float");
}
else
{
if (glob_var_val->get_result_enum() == int_result)
{
if (glob_var_val == NULL)
file_buffer << "0\n";
else
file_buffer << (int) glob_var_val->get_value() << "\n";
}
else if(glob_var_val->get_result_enum() == float_result){
if (glob_var_val == NULL)
file_buffer << "0\n";
else
file_buffer << fixed << setprecision(2) << glob_var_val->get_value() << "\n";
}
else
report_internal_error("Result type can only be int and float");
}
file_buffer << "\n";
}
int Name_Ast::get_successor(){
return successor;
}
Eval_Result & Name_Ast::get_value_of_evaluation(Local_Environment & eval_env)
{
if (eval_env.does_variable_exist(variable_name))
{
Eval_Result * result = eval_env.get_variable_value(variable_name);
if (result->is_variable_defined() == 0)
report_error("Variable should be defined before its use", NOLINE);
return *result;
}
Eval_Result * result = interpreter_global_table.get_variable_value(variable_name);
return *result;
}
void Name_Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result)
{
Eval_Result_Value * i;
if (result.get_result_enum() == int_result)
{
i = new Eval_Result_Value_Int();
i->set_value((int)result.get_value());
if (eval_env.does_variable_exist(variable_name))
eval_env.put_variable_value(*i, variable_name);
else
interpreter_global_table.put_variable_value(*i, variable_name);
}
else if(result.get_result_enum() == float_result){
i = new Eval_Result_Value_Float();
i->set_value(result.get_value());
if (eval_env.does_variable_exist(variable_name))
eval_env.put_variable_value(*i, variable_name);
else
interpreter_global_table.put_variable_value(*i, variable_name);
}
}
Eval_Result & Name_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
return get_value_of_evaluation(eval_env);
}
///////////////////////////////////////////////////////////////////////////////
template <class DATA_TYPE>
Number_Ast<DATA_TYPE>::Number_Ast(DATA_TYPE number, Data_Type constant_data_type)
{
constant = number;
node_data_type = constant_data_type;
successor = -1;
}
template <class DATA_TYPE>
Number_Ast<DATA_TYPE>::~Number_Ast()
{}
template <class DATA_TYPE>
Data_Type Number_Ast<DATA_TYPE>::get_data_type()
{
return node_data_type;
}
template <class DATA_TYPE>
void Number_Ast<DATA_TYPE>::print_ast(ostream & file_buffer)
{
if(node_data_type == int_data_type)
file_buffer << "Num : " << constant;
else
file_buffer << "Num : " << fixed << setprecision(2) << constant;
}
template <class DATA_TYPE>
int Number_Ast<DATA_TYPE>::get_successor(){
return successor;
}
template <class DATA_TYPE>
Eval_Result & Number_Ast<DATA_TYPE>::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if (node_data_type == int_data_type)
{
Eval_Result & result = *new Eval_Result_Value_Int();
result.set_value(constant);
return result;
}
if(node_data_type == float_data_type){
Eval_Result & result = *new Eval_Result_Value_Float();
result.set_value(constant);
return result;
}
}
///////////////////////////////////////////////////////////////////////////////
Return_Ast::Return_Ast(Ast * to_return)
{
return_Ast = to_return;
successor = -2;
if(return_Ast == NULL){
node_data_type = void_data_type;
}
}
Return_Ast::~Return_Ast()
{}
int Return_Ast::get_successor(){
return successor;
}
Data_Type Return_Ast::get_data_type()
{
return node_data_type;
}
bool Return_Ast::check_ast(int line){
if(return_Ast == NULL){
node_data_type = void_data_type;
}
}
void Return_Ast::print_ast(ostream & file_buffer)
{
if(return_Ast == NULL){
file_buffer <<"\n";
file_buffer << AST_SPACE << "RETURN <NOTHING>\n";
}
else{
file_buffer <<"\n";
file_buffer << AST_SPACE << "RETURN ";
return_Ast->print_ast(file_buffer);
file_buffer<<"\n";
}
}
Eval_Result & Return_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(return_Ast!=NULL){
Eval_Result & result = return_Ast->evaluate(eval_env,file_buffer);
print_ast(file_buffer);
return result;
}
else{
Eval_Result & result = *new Eval_Result_Value_Int();
result.set_result_enum(void_result);
print_ast(file_buffer);
return result;
}
}
template class Number_Ast<int>;
template class Number_Ast<float>;
|
//#include "globalTypes.h"
#include "tableParser.h"
#include <fstream>
#include <string>
#include <string.h>
#include <vector>
#include <dirent.h>
using namespace std;
#define MAX_ROWS_CHUNK 128
uint32_t rowChunk[MAX_ROWS_CHUNK][MAX_COLS];
vector<string> getTokens(string const &in){
const size_t len = in.length();
size_t i = 0;
vector<string> container;
while (i < len){
// Eat leading whitespace
i = in.find_first_not_of(" \t\n", i);
if (i == string::npos)
break; // Nothing left but white space
// Find the end of the token
size_t j = in.find_first_of(",", i);
// Push token
if (j == string::npos)
{
//std::cout << in.substr(i,j) << std::endl;
container.push_back(in.substr(i,j));
break;
}
else{
//std::cout << in.substr(i,j) << std::endl;
container.push_back(in.substr(i, j-i));
}
// Set up for next loop
i = j + 1;
}
return container;
}
/*
void loadChunk(uint32_t start_addr, uint32_t rowOffset, uint32_t numRows, uint32_t numCols, InportProxyT<RowReq> &rowReq, InportProxyT<RowBurst> &wrBurst){
RowReq request;
MemOp wr_op;
wr_op.m_val = MemOp::e_WRITE;
RowReqType reqType;
reqType.m_val = RowReqType::e_REQ_NROWS;
request.m_tableAddr = start_addr;
request.m_rowOffset = rowOffset;
request.m_numRows = numRows;
request.m_numCols = numCols;
request.m_reqSrc = 0;
request.m_reqType = reqType;
request.m_op = wr_op;
rowReq.sendMessage(request);
printf("\nWriting Chunk");
for (uint32_t i = 0; i < numRows; i++){
printf("\n");
for (uint32_t j = 0; j < numCols; j++){
printf("%d\t",rowChunk[i][j]);
// if ( j < numCols){
wrBurst.sendMessage(rowChunk[i][j]);
//}
// else{
//wrBurst.sendMessage(0);
//}
}
}
}
*/
bool parsecsv(const char *filename, const uint32_t tb_num, const uint32_t start_addr,InportProxyT<RowReq> &rowReq, InportProxyT<RowBurst> &wrBurst){
//FILE *file = fopen(filename, "r");
ifstream file(filename);
string line;
uint32_t numLines = 0;
//uint32_t rowOffset = 0;
//uint32_t mem_addr = start_addr;
uint32_t numRows = 0;
//uint32_t chunk_ptr = 0;
RowReq request;
MemOp wr_op;
wr_op.m_val = MemOp::e_WRITE;
RowReqType reqType;
reqType.m_val = RowReqType::e_REQ_ALLROWS;
request.m_tableAddr = start_addr;
request.m_rowOffset = 0;
//request.m_numRows = numRows;
//request.m_numCols = numCols;
request.m_reqSrc = 0;
request.m_reqType = reqType;
request.m_op = wr_op;
rowReq.sendMessage(request);
while (file.good()){
getline(file,line);
vector<string> tokens = getTokens(line);
switch (numLines){
case 0:
if (tokens.size() > 0){
strcpy(globalTableMeta[tb_num].tableName, tokens[0].c_str());
//globalTableMeta[tb_num].numRows = strtoul(tokens[1].c_str(),NULL,10);
//globalTableMeta[tb_num].numCols = strtoul(tokens[2].c_str(),NULL,10);
globalTableMeta[tb_num].startAddr = start_addr;
numLines++;
globalTableMeta[tb_num].inMem = true;
}
break;
case 1:
if (tokens.size() > 0){
globalTableMeta[tb_num].numCols = tokens.size();
for ( uint32_t i = 0; i < tokens.size(); i++)
strcpy(globalTableMeta[tb_num].colNames[i], tokens[i].c_str());
numLines++;
}
break;
default:
/*
if (chunk_ptr == MAX_ROWS_CHUNK){
loadChunk(mem_addr,rowOffset, chunk_ptr, globalTableMeta[tb_num].numCols, rowReq, wrBurst);
chunk_ptr = 0;
rowOffset += MAX_ROWS_CHUNK;
}
*/
if (tokens.size() >= globalTableMeta[tb_num].numCols){
for ( uint32_t i = 0; i < globalTableMeta[tb_num].numCols; i++){
//rowChunk[chunk_ptr][i] = strtoul(tokens[i].c_str(), NULL, 10);
wrBurst.sendMessage(strtoul(tokens[i].c_str(), NULL, 10));
}
//chunk_ptr++;
//mem_addr++;
numRows++;
}
else if (tokens.size() > 0){
fprintf(stderr, "FAIL: Not Enough Data Fields");
return false;
}
break;
}
}
//loadChunk(mem_addr, rowOffset, chunk_ptr,globalTableMeta[tb_num].numCols, rowReq, wrBurst);
wrBurst.sendMessage(-1);
globalTableMeta[tb_num].numRows = numRows;
/*
RowReq request;
MemOp wr_op;
wr_op.m_val = MemOp::e_WRITE;
RowReqType reqType;
reqType.m_val = RowReqType::e_REQ_EOT;
request.m_tableAddr = mem_addr;
request.m_rowOffset = numRows;
request.m_numRows = 8;
request.m_numCols = globalTableMeta[tb_num].numCols;
request.m_reqSrc = 0;
request.m_reqType = reqType;
request.m_op = wr_op;
rowReq.sendMessage(request);
*/
return true;
}
/*
void printTable(uint32_t tb_num){
cout << "Table Name:\t" << globalTableMeta[tb_num].tableName;
uint32_t nRows = globalTableMeta[tb_num].numRows;
uint32_t nCols = globalTableMeta[tb_num].numCols;
uint32_t addr_ptr = globalTableMeta[tb_num].startAddr;
cout << "\nColumn Names:\n";
for (uint32_t i = 0; i < nCols; i++){
cout << globalTableMeta[tb_num].colNames[i] << "\t";
}
cout << "\nData:\n";
for (uint32_t i = 0; i < nRows; i++){
for (uint32_t j = 0; j < nCols; j++){
cout << globalMem[addr_ptr+i][j] <<"\t";
}
cout << endl;
}
cout << "------" << endl;
}
*/
void printTable(uint32_t tb_num, InportProxyT<RowReq> &rowReq, OutportQueueT<RowBurst> &rdBurst){
if ( globalTableMeta[tb_num].inMem == false) return;
RowReq request;
MemOp wr_op;
wr_op.m_val = MemOp::e_READ;
RowReqType reqType;
reqType.m_val = RowReqType::e_REQ_ALLROWS;
cout << "Table Name:\t" << globalTableMeta[tb_num].tableName;
uint32_t nCols = globalTableMeta[tb_num].numCols;
uint32_t nRowsMax = globalTableMeta[tb_num].numRows+32; //for printing purposes when table is empty
uint32_t addr_ptr = globalTableMeta[tb_num].startAddr;
printf("\tTable Addr: %x",addr_ptr);
request.m_tableAddr = addr_ptr;
request.m_rowOffset = 0;
request.m_numCols = nCols;
request.m_reqSrc = 0;
request.m_reqType = reqType;
request.m_op = wr_op;
rowReq.sendMessage(request);
cout << "\nColumn Names:\n";
for (uint32_t i = 0; i < nCols; i++){
cout << globalTableMeta[tb_num].colNames[i] << "\t";
}
cout << "\nData:\n";
uint32_t resp = 0;
uint32_t colCnt = 0;
uint32_t rowCnt = 0;
// while (true) {
while ( (resp != 0xFFFFFFFF) && (rowCnt < nRowsMax) ){
//printf("here\n");
//fflush(stdout);
resp = rdBurst.getMessage();
if (colCnt == nCols){
colCnt = 0;
rowCnt++;
cout << endl;
}
cout << resp << "\t";
colCnt++;
}
printf("\n\n");
if (rowCnt == nRowsMax) {
printf("Note: max nrows reached, stopped printing\n");
}
//printf("\none table done\n\n");
}
void dumpMemory(InportProxyT<RowReq> &rowReq, OutportQueueT<RowBurst> &rdBurst){
for (uint32_t tb_num = 0; tb_num < globalNextMeta; tb_num++){
printTable(tb_num, rowReq, rdBurst);
}
}
bool parsecsv(InportProxyT<RowReq> &rowReq, InportProxyT<RowBurst> &wrBurst){
DIR *pDIR;
struct dirent *entry;
char input_dir[] = "./input/";
char filename[MAX_CHARS];
if( (pDIR=opendir(input_dir)) ){
while((entry = readdir(pDIR))){
//uint32_t str_len = strlen(entry->d_name);
if( strstr(entry->d_name,".csv") != NULL ){
strcpy(filename, input_dir);
strcat(filename, entry->d_name);
cout << "\nParsing Table: " << entry->d_name;
if (parsecsv(filename, globalNextMeta, globalNextAddr, rowReq, wrBurst)){
//cout << globalNextMeta << " " << globalNextAddr << endl;
//printTable(globalNextMeta);
globalNextAddr = globalNextAddr + globalTableMeta[globalNextMeta].numRows + 8;
globalNextMeta++;
}
else{
return false;
}
}
}
closedir(pDIR);
}
return true;
}
|
//: C03:SimpleStruct3.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Uzywanie wskaznikow do struktur
typedef struct Structure3 {
char c;
int i;
float f;
double d;
} Structure3;
int main() {
Structure3 s1, s2;
Structure3* sp = &s1;
sp->c = 'a';
sp->i = 1;
sp->f = 3.14;
sp->d = 0.00093;
sp = &s2; // Wskazuje na inna strukture
sp->c = 'a';
sp->i = 1;
sp->f = 3.14;
sp->d = 0.00093;
} ///:~
|
#include <iostream>
#include <algorithm>
#include <chrono>
#include <thread>
#include "DatabaseClientApi.hpp"
std::string random_string(size_t length)
{
auto randchar = []() -> char
{
const char charset[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
const size_t max_index = (sizeof(charset) - 1);
return charset[ rand() % max_index ];
};
std::string str(length,0);
std::generate_n( str.begin(), length, randchar );
return str;
}
int main(int argc, char* argv[])
{
DatabaseClientApi::Connect();
while(true)
{
std::string s = random_string(10);
DatabaseClientApi::Put(s,s);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
DatabaseClientApi::Disconnect();
return 0;
}
|
#ifndef TEXTURE_H_INCLUDED
#define TEXTURE_H_INCLUDED
#include <string>
/* forward declarations begin */
struct SDL_Point;
struct SDL_Rect;
struct SDL_Texture;
/* forward declarations end */
struct FailedToLoadTextureException {};
class Texture {
public:
Texture();
Texture(char const* path);
~Texture();
Texture(Texture const&) = delete;
Texture(Texture&&) = delete;
void load(char const* path);
int w() const { return _w; }
int h() const { return _h; }
void render(int x, int y) const;
void render(int x, int y, float angle) const;
void render(int x, int y, float angle, int w, int h) const;
void render(SDL_Point const& pos) const;
void render(SDL_Point const& pos, float angle) const;
void render(SDL_Point const& pos, float angle, SDL_Rect const& clip) const;
void render(SDL_Point const& pos, SDL_Rect const& clip) const;
private:
SDL_Texture* _tex = nullptr;
int _w = 0;
int _h = 0;
};
Texture& textures(std::string const& name);
#endif // TEXTURE_H_INCLUDED
|
/*
Name: �����߷�
Copyright:
Author: Hill bamboo
Date: 2019/8/15 20:23:01
Description: ����
�տ�ʼ�뵽����DFSд�ģ����Ǻ������ֲ�����д�����Ǻ�����ֱ������ķ�ʽ����ʵ�����ַ���Ҳ�ܿ��
*/
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10 + 5;
int maze[maxn][maxn];
int m, n;
int main() {
maze[0][0] = 1;
scanf("%d %d", &m, &n);
for (int j = 0; j <= n; ++j) maze[0][j] = 1;
for (int i = 1; i <= m; ++i) maze[i][0] = 1;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
maze[i][j] = maze[i - 1][j] + maze[i][j - 1];
}
}
printf("%d\n", maze[m][n]);
return 0;
}
|
#include "CollisionCircle.hpp"
#include "CollisionControl.hpp"
#include <algorithm>
namespace game {
//インスタンス実体化
CollisionControl CollisionControl::m_instance;
CollisionControl::~CollisionControl()
{
}
void CollisionControl::PushCollisionData(CollisionData & colliData)
{
m_collisions.emplace_back(std::unique_ptr<CollisionData>(&colliData));
}
void CollisionControl::Update()
{
//無効なCollisionDataをerase-removeイディオムで削除する
auto itr =
std::remove_if(m_collisions.begin(), m_collisions.end(), [](std::unique_ptr<CollisionData>& colliData) {
return colliData->IsDelete();
});
m_collisions.erase(itr, m_collisions.end());
//あたり判定する
for (size_t i = 0; i < m_collisions.size(); i++) {
for (size_t j = i + 1; j < m_collisions.size(); j++) {
m_collisions[i]->GetCollision().HitCheck(m_collisions[j]->GetCollision());
}
}
}
}
|
#include<iostream>
using namespace std;
int fact(int n) {
int f = 0;
if (n <= 1) {
f = 1;
}
else {
f = n * fact(n - 1); // 5 * (5 - 1), 6 * (4 - 1) ect.
}
return f;
}
int fact2(int n) {
int f = 1;
cout << "Множители: " << n << endl;
if (n > 1) {
f = n * fact2(n - 1);
}
cout << "Результаты: " << f << endl;
return f;
}
int factorial(int n) {
int f = 1;
while (n > 1) {
cout << "Вверх: " << n << endl;
f *= n;
n -= 1;
cout << "Вниз: " << f << endl;
}
return f;
}
int main() {
//cout << fact(5) << endl;
//cout << factorial(5) << endl;
cout << fact2(6) << endl;
return 0;
}
/*----------------------------------------------------------------
5 * (5 - 1), 20
5 * (4 - 1), 15
5 * (3 - 1), 10
5 * (2 - 1), 5
5 * (1 - 1) 0
*/
|
#include "Tema1.h"
#include <iostream>
using namespace std;
Tema1::Tema1()
{
}
Tema1::~Tema1()
{
delete paddle;
delete ball;
delete wall;
delete brickManager;
}
void Tema1::Init()
{
// Initialize camera
camera = new Camera(glm::vec3(0, 0, 40), glm::vec3(0, 0, 0),
glm::vec3(0, 1, 0));
// Set logic space
lSpace.x = 0;
lSpace.y = 0;
lSpace.width = window->GetResolution().x;
lSpace.height = window->GetResolution().y;
// Init the paddle
paddle = new Paddle("paddle", 300, 25, lSpace.width / 2.0f, 30.0f,
glm::vec3(1, 0, 0));
AddMeshToList(paddle->CreateMesh());
// Init the ball
ball = new Ball("ball", 20, lSpace.width / 2.0f, 80, glm::vec3(0, 1, 0));
ball->InitPosition(paddle->GetPosition(), paddle->GetSize());
AddMeshToList(ball->CreateMesh());
// Add lifes to be rendered
for (Circle *c : ball->GetBalls()) {
AddMeshToList(c->CreateMesh());
}
// Init the wall
wall = new Wall(lSpace.width, lSpace.height, 30, 150, glm::vec3(1, 0, 1));
for (CollidableSquare *c : wall->GetAllCollidableSquares())
AddMeshToList(c->CreateMesh());
// Init the Brick Manager
brickManager = new BrickManager(3);
brickManager->SetBoard(10, 7, 80, 30, 20,
glm::vec2(lSpace.width, lSpace.height), level);
brickManager->SetBallRef(ball);
brickManager->SetMeshes(meshes);
for (CollidableSquare *c : brickManager->GetAllBricks())
AddMeshToList(c->CreateMesh());
}
void Tema1::FrameStart()
{
}
void Tema1::Update(float deltaTimeSeconds)
{
glm::ivec2 resolution = window->GetResolution();
// Sets the screen area where to draw - the left half of the window
vSpace = Display::ViewportSpace(0, 0, resolution.x, resolution.y);
Display::SetViewportArea(*camera, vSpace, glm::vec3(0), true);
// Compute uniform 2D visualization matrix
glm::mat3 visMatrix = Display::LogicToViewportTransformation(&lSpace, &vSpace);
// Reset game when no more lives left
if (ball->GetNumBalls() == 0) {
level = 1;
ResetScene();
}
// Go to next level
if (brickManager->GetAllBricks().size() == 0) {
level++;
ResetScene();
}
// Update brick manager
brickManager->SetPaddlePos(paddle->GetPosition());
brickManager->SetPaddleSize(paddle->GetSize());
brickManager->Update(deltaTimeSeconds);
// Set Wall powerup if needed
wall->SetBottomWall(ball->IsBottomWallActive());
// Add collidable objects
ball->AddNearCollidableObjs(brickManager->GetAllCollidableSquares());
ball->AddNearCollidableObjs(wall->GetAllCollidableSquares());
ball->Update(deltaTimeSeconds, paddle->GetPosition(), paddle->GetSize());
ball->ResetOnOffScreen(window->GetResolution(), paddle->GetPosition(), paddle->GetSize());
ball->ClearCollidableObjs();
// Draw the entire scene
DrawScene(visMatrix);
}
void Tema1::DrawScene(glm::mat3 visMatrix)
{
// Draw the paddle
Display::RenderMesh(meshes["paddle"], shaders["VertexColor"],
visMatrix * paddle->GetModelMatrix(), camera);
// Draw the ball
Display::RenderMesh(meshes["ball"], shaders["VertexColor"],
visMatrix * ball->GetModelMatrix(), camera);
// Draw lifes
for (int i = 0; i < ball->GetNumBalls(); i++) {
Circle *c = ball->GetBalls()[i];
Display::RenderMesh(meshes[c->GetName()], shaders["VertexColor"],
visMatrix * c->GetModelMatrix(), camera);
}
// Draw the wall
for (CollidableSquare *c : wall->GetAllCollidableSquares())
{
Display::RenderMesh(meshes[c->GetName()], shaders["VertexColor"],
visMatrix * c->GetModelMatrix(), camera);
}
// Draw bricks
for (CollidableSquare *c : brickManager->GetAllBricks())
{
Display::RenderMesh(meshes[c->GetName()], shaders["VertexColor"],
visMatrix * c->GetModelMatrix(), camera);
}
// Draw the powerUps
for (PowerUp *p : brickManager->GetAllPowerUpsOnDisplay()) {
Display::RenderMesh(meshes[p->GetName()], shaders["VertexColor"],
visMatrix * p->GetModelMatrix(), camera);
}
}
void Tema1::FrameEnd()
{
}
void Tema1::OnInputUpdate(float deltaTime, int mods)
{
// treat continuous update based on input
};
void Tema1::OnKeyPress(int key, int mods)
{
// add key press event
};
void Tema1::OnKeyRelease(int key, int mods)
{
// add key release event
};
void Tema1::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
paddle->Update(glm::vec2(mouseX, mouseY));
};
void Tema1::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// Deploy the ball on mouse click
ball->DeployOnClick(paddle->GetPosition(), paddle->GetSize());
ball->SetSticked(false);
};
void Tema1::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// add mouse button release event
}
void Tema1::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
// treat mouse scroll event
}
void Tema1::OnWindowResize(int width, int height)
{
// treat window resize event
}
void Tema1::ResetScene()
{
// Reset paddle
paddle->Update(glm::vec2(lSpace.width / 2.0f, 30.0f));
// Reset ball
ball->SetSticked(true);
ball->ResetNumBalls();
ball->ClearCollidableObjs();
ball->SetVelocity(glm::vec2(0));
ball->SetAcceleration(0);
ball->SetPowerUp(PowerUpsEnum::NO_POWERUP, 0);
ball->InitPosition(paddle->GetPosition(), paddle->GetSize());
// Reset Brick Manager
brickManager->Reset();
brickManager->SetBoard(10, 7, 80, 30, 20,
glm::vec2(lSpace.width, lSpace.height), level);
for (CollidableSquare *c : brickManager->GetAllBricks())
AddMeshToList(c->CreateMesh());
}
|
/*
* pirflinx
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <iostream>
#include <sys/stat.h>
#include <unistd.h>
#include <syslog.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <execinfo.h>
#include "Logger.h"
#define DAEMON_NAME "pirflinx"
#define PID_FILE "/var/run/pirflinx.pid"
std::string szStartupFolder;
CLogger _log;
std::string logfile = "";
int socketPort = 9999;
bool g_bStopApplication = false;
bool g_bRunAsDaemon = false;
int pidFilehandle = 0;
int fatal_handling = 0;
int g_RepeatDefault = 1;
long g_DelayDefault = 5000L;
void signal_handler(int sig_num) {
switch(sig_num) {
case SIGHUP:
if (logfile!="") {
_log.SetOutputFile(logfile.c_str());
}
break;
case SIGINT:
case SIGTERM:
g_bStopApplication = true;
break;
case SIGSEGV:
case SIGILL:
case SIGABRT:
case SIGFPE:
if (fatal_handling) {
exit(EXIT_FAILURE);
}
fatal_handling = 1;
// re-raise signal to enforce core dump
signal(sig_num, SIG_DFL);
raise(sig_num);
break;
}
}
void daemonShutdown() {
if (pidFilehandle != 0) {
close(pidFilehandle);
pidFilehandle = 0;
}
}
void daemonize(const char *rundir, const char *pidfile) {
int pid, sid, i;
char str[10];
struct sigaction newSigAction;
sigset_t newSigSet;
/* Check if parent process id is set */
if (getppid() == 1) {
/* PPID exists, therefore we are already a daemon */
return;
}
/* Set signal mask - signals we want to block */
sigemptyset(&newSigSet);
sigaddset(&newSigSet, SIGCHLD); /* ignore child - i.e. we don't need to wait for it */
sigaddset(&newSigSet, SIGTSTP); /* ignore Tty stop signals */
sigaddset(&newSigSet, SIGTTOU); /* ignore Tty background writes */
sigaddset(&newSigSet, SIGTTIN); /* ignore Tty background reads */
sigprocmask(SIG_BLOCK, &newSigSet, NULL); /* Block the above specified signals */
/* Set up a signal handler */
newSigAction.sa_handler = signal_handler;
sigemptyset(&newSigAction.sa_mask);
newSigAction.sa_flags = 0;
/* Signals to handle */
sigaction(SIGTERM, &newSigAction, NULL); // catch term signal
sigaction(SIGINT, &newSigAction, NULL); // catch interrupt signal
sigaction(SIGSEGV, &newSigAction, NULL); // catch segmentation fault signal
sigaction(SIGABRT, &newSigAction, NULL); // catch abnormal termination signal
sigaction(SIGILL, &newSigAction, NULL); // catch invalid program image
sigaction(SIGHUP, &newSigAction, NULL); // catch HUP, for logrotation
/* Fork*/
pid = fork();
if (pid < 0) {
/* Could not fork */
exit(EXIT_FAILURE);
}
if (pid > 0) {
/* Child created ok, so exit parent process */
exit(EXIT_SUCCESS);
}
/* Ensure only one copy */
pidFilehandle = open(pidfile, O_RDWR | O_CREAT, 0600);
if (pidFilehandle == -1) {
/* Couldn't open lock file */
syslog(LOG_INFO, "Could not open PID lock file %s, exiting", pidfile);
exit(EXIT_FAILURE);
}
/* Try to lock file */
if (lockf(pidFilehandle, F_TLOCK, 0) == -1) {
/* Couldn't get lock on lock file */
syslog(LOG_INFO, "Could not lock PID lock file %s, exiting", pidfile);
exit(EXIT_FAILURE);
}
/* Get and format PID */
sprintf(str, "%d\n", getpid());
/* write pid to lockfile */
write(pidFilehandle, str, strlen(str));
/* Child continues */
umask(027); /* Set file permissions 750 */
if (logfile!="") {
_log.SetOutputFile(logfile.c_str());
}
/* Get a new process group */
sid = setsid();
if (sid < 0) {
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Route I/O connections */
/* Open STDIN */
i = open("/dev/null", O_RDWR);
/* STDOUT */
dup(i);
/* STDERR */
dup(i);
chdir(rundir); /* change running directory */
}
static size_t getExecutablePathName(char* pathName, size_t pathNameCapacity) {
size_t pathNameSize = readlink("/proc/self/exe", pathName, pathNameCapacity - 1);
pathName[pathNameSize] = '\0';
return pathNameSize;
}
static unsigned int getNum(char *str, int *err) {
unsigned int val;
char *endptr;
*err = 0;
val = strtoll(str, &endptr, 0);
if (*endptr) {*err = 1; val = -1;}
return val;
}
static void usage() {
fprintf(stderr, "\n" \
"Usage: sudo xxxx [OPTION] ...\n" \
" -p value, socket port, 1024-32000, default 9999\n" \
"EXAMPLE\n" \
"sudo xxxx -p 9998\n" \
"\n");
}
static void initOpts(int argc, char *argv[]) {
int opt, err, i;
unsigned int mask;
while ((opt = getopt(argc, argv, "dp:l:r:x:")) != -1) {
switch (opt) {
case 'd':
g_bRunAsDaemon = false;
break;
case 'p':
i = getNum(optarg, &err);
socketPort = i;
break;
case 'l':
logfile = strdup(optarg);
break;
case 'r':
i= getNum(optarg, &err);
g_RepeatDefault = i;
break;
case 'x':
i= getNum(optarg, &err);
g_DelayDefault = i;
break;
default: /* '?' */
usage();
exit(-1);
}
}
}
int pirfserver_start(int socketPort);
int pirfserver_stop();
int main(int argc, char **argv) {
//ignore pipe errors
signal(SIGPIPE, SIG_IGN);
g_bRunAsDaemon = true;
/* check command line parameters */
initOpts(argc, argv);
if (g_bRunAsDaemon) {
setlogmask(LOG_UPTO(LOG_INFO));
openlog(DAEMON_NAME, LOG_CONS | LOG_PERROR, LOG_USER);
syslog(LOG_INFO, "pirflinx is starting up");
}
char szStartupPath[255];
getExecutablePathName((char*)&szStartupPath,255);
szStartupFolder=szStartupPath;
if (szStartupFolder.find_last_of('/')!=std::string::npos)
szStartupFolder=szStartupFolder.substr(0,szStartupFolder.find_last_of('/')+1);
if (g_bRunAsDaemon)
/* Deamonize */
daemonize(szStartupFolder.c_str(), PID_FILE);
// Need here to start main worker thread
pirfserver_start(socketPort);
while (!g_bStopApplication) {
sleep(1);
}
fflush(stdout);
_log.Log(LOG_STATUS, "Stopping worker...");
// Stop main worker ???
pirfserver_stop();
if (g_bRunAsDaemon) {
syslog(LOG_INFO, "pirflinx stopped");
daemonShutdown();
// Delete PID file
remove(PID_FILE);
}
return 0;
}
|
#include "Ammunition.h"
#include "math.h"
void Ammunition::generateNewBullets(float delta, Scene* scene, Sprite* hero) {
for (auto numDirection = 0; numDirection < m_Direction.size(); numDirection++)
{
m_bullets.pushBack(this->generateSimpleBullet(delta, scene, hero, m_Direction[numDirection]));
}
;
if (isFlash)
{
this->downLevel(UfoType::FLASH_UFO);
}
else {
this->downLevel(UfoType::MULTIPLY_UFO);
}
}
Sprite* Ammunition::generateSimpleBullet(float delta, Scene* scene, Sprite* hero, float Dir) {
auto bullet = Sprite::createWithSpriteFrameName("bullet1.png");
bullet->setPosition(hero->getPositionX(), hero->getPositionY() + hero->getContentSize().height / 5);
bullet->setRotation(Dir); //从方向集合中选择方向 并调整子弹方向
auto distance = bullet->getContentSize().height / 2 + SIZE.height - bullet->getPositionY();
auto move = MoveBy::create(distance / m_bullet_speed, Vec2(distance * sin(Dir * (3.1415926 / 180.0f)), distance));
//m_bulletmove.push_back(move);
bullet->runAction(move);
scene->addChild(bullet);
return bullet;
}
void Ammunition::moveAllBullets(float delta) {
checkBulletsInVisibleSize();
}
bool Ammunition::isHit(Enemy* enemy) {
for (auto bullet : m_bullets) {
if (enemy->getBoundingBox().intersectsRect(bullet->getBoundingBox())) {
enemy->hit(HERO_DAMAGE);
m_bullets.eraseObject(bullet);
bullet->removeFromParentAndCleanup(true);
return true;
}
}
return false;
}
void Ammunition::checkBulletsInVisibleSize() {
Vector<Sprite *> removableBullets;
for (auto bullet : m_bullets) {
if (bullet->getPositionY() >=
Director::getInstance()->getVisibleSize().height + bullet->getContentSize().height / 2) {
bullet->removeFromParent();
// 不能在遍历集合时修改集合成员数量,所以暂时存放到一个“失效集合”中
removableBullets.pushBack(bullet);
}
}
for (auto bullet : removableBullets) {
m_bullets.eraseObject(bullet);
}
}
void Ammunition::getDirection(int numMulti){ //通过行数改变方向集合
switch (numMulti)
{
case 1: m_Direction = {0.0f}; //一行时只有0度子弹
break;
case 2: m_Direction = { -60.0f,60.0f }; //两行时 左偏60 和右偏60度 两个方向
break;
case 3: m_Direction = { -60.0f,0.0f,60.0f }; //三行时 在两行基础 中间加一行
break;
case 4: m_Direction = { -60.0f,-30.0f,30.0f,60.0f };//4行时候排布
break;
default: m_Direction = { -60.0f,-30.0f,0.0f,30.0f,60.0f };///默认超过五排都为5排,
break;
}
}
void Ammunition::upLevel(UfoType type) { //吃到道具升级
switch (type)
{
case UfoType::FLASH_UFO:
{
log("UP Flash");
m_flashBulletsCount += FLASHBULLET_NUM;
log("flahbullnum is %d", m_flashBulletsCount);
isFlash = true;
log("isFlash? %d", isFlash);
m_numMulti = 3; //超级子弹默认3列
m_Direction = { -60.0f,0.0f,60.0f };
}
break;
case UfoType::MULTIPLY_UFO:
if (m_numMulti == 5) { //5种子弹记录5种buff剩下的子弹数
m_Direction = { -60.0f,-30.0f,0.0f,30.0f,60.0f };
this->m_5BulletsCount = MUILBULLET_NUM;
}
if (m_numMulti == 4) {
this->m_numMulti++;
m_Direction = { -60.0f,-30.0f,0.0f,30.0f,60.0f };
this->m_5BulletsCount = MUILBULLET_NUM + m_4BulletsCount;
}
if (m_numMulti == 3) {
this->m_numMulti++;
m_Direction = { -60.0f,-30.0f,30.0f,60.0f };
this->m_4BulletsCount = MUILBULLET_NUM + m_3BulletsCount;
}
if (m_numMulti == 2) {
this->m_numMulti++;
m_Direction = { -60.0f,0.0f,60.0f };
this->m_3BulletsCount = MUILBULLET_NUM + m_2BulletsCount;
}
if (m_numMulti == 1) {
this->m_numMulti++;
this->m_Direction = { -60.0f,60.0f };
this->m_2BulletsCount = MUILBULLET_NUM;
}
break;
default:
break;
}
}
void Ammunition::downLevel(UfoType type) {
switch (type)
{
case UfoType::FLASH_UFO: {
if (m_flashBulletsCount >= 0) {
isFlash = true;
this->m_flashBulletsCount--;
}
else {
this->isFlash = false;
this->downLevel(UfoType::MULTIPLY_UFO);
}
}
break;
case UfoType::MULTIPLY_UFO:
{
if (m_flashBulletsCount >= 0) { //如果有闪电子弹
this->downLevel(UfoType::FLASH_UFO);
}
if (m_5BulletsCount >= 0) //5种buff子弹有优先级 从5列子弹开始发射
{
this->m_5BulletsCount--;
if (m_5BulletsCount == 0)
{
m_Direction = { -60.0f,-30.0f,30.0f,60.0f };
m_numMulti--;
}
}
else if (m_4BulletsCount >= 0)
{
this->m_4BulletsCount--;
if (m_4BulletsCount == 0)
{
m_Direction = { -60.0f,0.0f,60.0f };
m_numMulti--;
}
}
else if (m_3BulletsCount >= 0)
{
this->m_3BulletsCount--;
if (m_3BulletsCount == 0)
{
m_Direction = { -60.0f,0.0f,60.0f };
m_numMulti--;
}
}
else if (m_2BulletsCount >= 0)
{
this->m_2BulletsCount--;
if (m_2BulletsCount == 0)
{
m_Direction = { -60.0f,60.0f };
m_numMulti--;
}
}
else
{
this->m_numMulti = 1;
m_Direction = { 0.0f };
}
}
break;
default:
break;
}
}
|
#include <iostream>
#include <conio.h>
#include <string>
#include <vector>
using namespace std;
struct Employee
{
int ID;
string firstName;
string lastName;
double payRate;
int hours;
};
void Print(Employee const&e)
{
cout << "Here is your employee report: " << endl;
cout << e.ID << " " << e.firstName << " " << e.lastName << " " << e.payRate * e.hours << endl;
}
int main()
{
//Employee em[10], *p;
vector<int> em;
char input = 'y';
int num;
do
{
cout << "How Many Employees? ";
cin >> num;
}
int n, j, q = 0;
cout << "How many employees?: " << endl;
cin >> n;
cout << "Please enter your data: " << endl;
for (em; em + n; em++)
{
q++;
cout << "\nEnter the employee ID for " << q << " employee : ";
cin >> p->ID;
cout << "\nEnter the employee first name for " << q << " employee : ";
cin >> p->firstName;
cout << "\nEnter the employee last name for " << q << " employee : ";
cin >> p->lastName;
cout << "\nEnter the employee payRate for " << q << " employee : ";
cin >> p->payRate;
cout << "\nEnter the employee hours worked for " << q << " employee : ";
cin >> p->hours;
}
p = em;
cout << "\nYour Entered Data is:" << endl;
//p = 0;
while (p < em + n)
{
q++;
cout << p->ID << " " << p->firstName << " " << p->lastName << " " << p->payRate * p->hours << " " << endl;
p++;
}
_getch();
return 0;
}
|
#ifndef HEADER_CURL_MEMDEBUG_H
#define HEADER_CURL_MEMDEBUG_H
#ifdef CURLDEBUG
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* CAUTION: this header is designed to work when included by the app-side
* as well as the library. Do not mix with library internals!
*/
#include "curl_setup.h"
#include <curl/curl.h>
#define CURL_MT_LOGFNAME_BUFSIZE 512
#define logfile curl_debuglogfile
extern FILE *logfile;
/* memory functions */
CURL_EXTERN void *curl_domalloc(size_t size, int line, const char *source);
CURL_EXTERN void *curl_docalloc(size_t elements, size_t size, int line,
const char *source);
CURL_EXTERN void *curl_dorealloc(void *ptr, size_t size, int line,
const char *source);
CURL_EXTERN void curl_dofree(void *ptr, int line, const char *source);
CURL_EXTERN char *curl_dostrdup(const char *str, int line, const char *source);
#if defined(WIN32) && defined(UNICODE)
CURL_EXTERN wchar_t *curl_dowcsdup(const wchar_t *str, int line,
const char *source);
#endif
CURL_EXTERN void curl_memdebug(const char *logname);
CURL_EXTERN void curl_memlimit(long limit);
CURL_EXTERN void curl_memlog(const char *format, ...);
/* file descriptor manipulators */
CURL_EXTERN curl_socket_t curl_socket(int domain, int type, int protocol,
int line , const char *source);
CURL_EXTERN void curl_mark_sclose(curl_socket_t sockfd,
int line , const char *source);
CURL_EXTERN int curl_sclose(curl_socket_t sockfd,
int line , const char *source);
CURL_EXTERN curl_socket_t curl_accept(curl_socket_t s, void *a, void *alen,
int line, const char *source);
#ifdef HAVE_SOCKETPAIR
CURL_EXTERN int curl_socketpair(int domain, int type, int protocol,
curl_socket_t socket_vector[2],
int line , const char *source);
#endif
/* FILE functions */
CURL_EXTERN FILE *curl_fopen(const char *file, const char *mode, int line,
const char *source);
#ifdef HAVE_FDOPEN
CURL_EXTERN FILE *curl_fdopen(int filedes, const char *mode, int line,
const char *source);
#endif
CURL_EXTERN int curl_fclose(FILE *file, int line, const char *source);
#ifndef MEMDEBUG_NODEFINES
/* Set this symbol on the command-line, recompile all lib-sources */
#undef strdup
#define strdup(ptr) curl_dostrdup(ptr, __LINE__, __FILE__)
#define malloc(size) curl_domalloc(size, __LINE__, __FILE__)
#define calloc(nbelem,size) curl_docalloc(nbelem, size, __LINE__, __FILE__)
#define realloc(ptr,size) curl_dorealloc(ptr, size, __LINE__, __FILE__)
#define free(ptr) curl_dofree(ptr, __LINE__, __FILE__)
#ifdef WIN32
# ifdef UNICODE
# undef wcsdup
# define wcsdup(ptr) curl_dowcsdup(ptr, __LINE__, __FILE__)
# undef _wcsdup
# define _wcsdup(ptr) curl_dowcsdup(ptr, __LINE__, __FILE__)
# undef _tcsdup
# define _tcsdup(ptr) curl_dowcsdup(ptr, __LINE__, __FILE__)
# else
# undef _tcsdup
# define _tcsdup(ptr) curl_dostrdup(ptr, __LINE__, __FILE__)
# endif
#endif
#define socket(domain,type,protocol)\
curl_socket(domain, type, protocol, __LINE__, __FILE__)
#undef accept /* for those with accept as a macro */
#define accept(sock,addr,len)\
curl_accept(sock, addr, len, __LINE__, __FILE__)
#ifdef HAVE_SOCKETPAIR
#define socketpair(domain,type,protocol,socket_vector)\
curl_socketpair(domain, type, protocol, socket_vector, __LINE__, __FILE__)
#endif
#ifdef HAVE_GETADDRINFO
#if defined(getaddrinfo) && defined(__osf__)
/* OSF/1 and Tru64 have getaddrinfo as a define already, so we cannot define
our macro as for other platforms. Instead, we redefine the new name they
define getaddrinfo to become! */
#define ogetaddrinfo(host,serv,hint,res) \
curl_dogetaddrinfo(host, serv, hint, res, __LINE__, __FILE__)
#else
#undef getaddrinfo
#define getaddrinfo(host,serv,hint,res) \
curl_dogetaddrinfo(host, serv, hint, res, __LINE__, __FILE__)
#endif
#endif /* HAVE_GETADDRINFO */
#ifdef HAVE_GETNAMEINFO
#undef getnameinfo
#define getnameinfo(sa,salen,host,hostlen,serv,servlen,flags) \
curl_dogetnameinfo(sa, salen, host, hostlen, serv, servlen, flags, \
__LINE__, __FILE__)
#endif /* HAVE_GETNAMEINFO */
#ifdef HAVE_FREEADDRINFO
#undef freeaddrinfo
#define freeaddrinfo(data) \
curl_dofreeaddrinfo(data, __LINE__, __FILE__)
#endif /* HAVE_FREEADDRINFO */
/* sclose is probably already defined, redefine it! */
#undef sclose
#define sclose(sockfd) curl_sclose(sockfd,__LINE__,__FILE__)
#define fake_sclose(sockfd) curl_mark_sclose(sockfd,__LINE__,__FILE__)
#undef fopen
#define fopen(file,mode) curl_fopen(file,mode,__LINE__,__FILE__)
#undef fdopen
#define fdopen(file,mode) curl_fdopen(file,mode,__LINE__,__FILE__)
#define fclose(file) curl_fclose(file,__LINE__,__FILE__)
#endif /* MEMDEBUG_NODEFINES */
#endif /* CURLDEBUG */
/*
** Following section applies even when CURLDEBUG is not defined.
*/
namespace youmecommon
{
#ifndef fake_sclose
#define fake_sclose(x) Curl_nop_stmt
#endif
/*
* Curl_safefree defined as a macro to allow MemoryTracking feature
* to log free() calls at same location where Curl_safefree is used.
* This macro also assigns NULL to given pointer when free'd.
*/
#define Curl_safefree(ptr) \
do { free((ptr)); (ptr) = NULL;} WHILE_FALSE
}
#endif /* HEADER_CURL_MEMDEBUG_H */
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
long long int a , b , c;
for (int i = 0; i < t; i++)
{
cin>>a>>b>>c;
if (a < c)
{
cout<<1<< " ";
}
else if (a >= c)
{
cout<<-1<<" ";
}
if (a*b <= c)
{
cout<<-1<<endl;
}
else if (a*b > c)
{
cout<<b<<endl;
}
}
return 0;
}
|
#include "msg_0x2a_removeentityeffect_stc.h"
namespace MC
{
namespace Protocol
{
namespace Msg
{
RemoveEntityEffect::RemoveEntityEffect()
{
_pf_packetId = static_cast<int8_t>(0x2A);
_pf_initialized = false;
}
RemoveEntityEffect::RemoveEntityEffect(int32_t _entityId, int32_t _effectId)
: _pf_entityId(_entityId)
, _pf_effectId(_effectId)
{
_pf_packetId = static_cast<int8_t>(0x2A);
_pf_initialized = true;
}
size_t RemoveEntityEffect::serialize(Buffer& _dst, size_t _offset)
{
_pm_checkInit();
if(_offset == 0) _dst.clear();
_offset = WriteInt8(_dst, _offset, _pf_packetId);
_offset = WriteInt32(_dst, _offset, _pf_entityId);
_offset = WriteInt32(_dst, _offset, _pf_effectId);
return _offset;
}
size_t RemoveEntityEffect::deserialize(const Buffer& _src, size_t _offset)
{
_offset = _pm_checkPacketId(_src, _offset);
_offset = ReadInt32(_src, _offset, _pf_entityId);
_offset = ReadInt32(_src, _offset, _pf_effectId);
_pf_initialized = true;
return _offset;
}
int32_t RemoveEntityEffect::getEntityId() const { return _pf_entityId; }
int32_t RemoveEntityEffect::getEffectId() const { return _pf_effectId; }
void RemoveEntityEffect::setEntityId(int32_t _val) { _pf_entityId = _val; }
void RemoveEntityEffect::setEffectId(int32_t _val) { _pf_effectId = _val; }
} // namespace Msg
} // namespace Protocol
} // namespace MC
|
#pragma once
#include <QStandardItemModel>
#include <envire_core/items/Transform.hpp>
namespace envire { namespace viz {
/**A qt model for TransformWithCovariance that can be used with tables and
* tree views etc. */
class TransformModel : public QStandardItemModel
{
Q_OBJECT
public:
TransformModel();
signals:
/**Emitted when the transform is changed either by the user or by
* setTransform().*/
void transformChanged(const envire::core::Transform& newValue);
public slots:
/** Used to programatically change the transform
* This method should be invoked in the gui thread*/
void setTransform(const envire::core::Transform& newValue);
/*If set to false, the model will be read only */
void setEditable(const bool value);
const envire::core::Transform& getTransform() const;
private slots:
void itemChangedSlot(QStandardItem * item);
private:
QStandardItemModel model;
envire::core::Transform tf;
QStandardItem transXItem;
QStandardItem transYItem;
QStandardItem transZItem;
QStandardItem rotXItem;
QStandardItem rotYItem;
QStandardItem rotZItem;
QStandardItem rotWItem;
QStandardItem timestampItem;
};
}}
|
//
// Created by Yujing Shen on 29/05/2017.
//
#ifndef TENSORGRAPH_RELUNODE_H
#define TENSORGRAPH_RELUNODE_H
#include "../SessionNode.h"
namespace sjtu{
class ReluNode: public SessionNode
{
public:
ReluNode(Session *sess, const Shape& shape);
~ReluNode();
virtual Node forward() override ;
virtual Node backward() override ;
virtual Node optimize() override ;
};
}
#endif //TENSORGRAPH_RELUNODE_H
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 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 MEMTOOLS_ENABLE_STACKGUARD
#include "modules/memtools/stacktraceguard.h"
/* static */
BOOL OpStackTraceGuard::StackAddressIsOK(void* addr)
{
return g_current_top_of_stack == 0 ||
(char*)g_current_top_of_stack > (char*)addr;
}
//
// This global variable needs to go, but we keep it until
// memtools gets its own proper MemtoolsModule in
// the global opera object.
//
OpStackTraceGuard* OpStackTraceGuard::g_current_top_of_stack = 0;
#endif // MEMTOOLS_ENABLE_STACKGUARD
|
#pragma once
namespace json {
class Object;
class Array;
template<typename Provider, typename Parent, typename Index>
class AutoCommitT: public Provider {
public:
AutoCommitT(const Value &oldVal, Parent &parent, const Index &index)
:Provider(oldVal),parent(parent),index(index) {}
~AutoCommitT() {
if (this->dirty()) {
parent.set(index, *this);
}
}
void commit() {
if (this->dirty()) {
parent.set(index, *this);
this->revert();
}
}
protected:
Parent &parent;
Index index;
};
typedef AutoCommitT<Object, Object, StringView<char> > Object2Object;
typedef AutoCommitT<Object, Array, std::size_t > Object2Array;
typedef AutoCommitT<Array, Object, StringView<char> > Array2Object ;
typedef AutoCommitT<Array, Array, std::size_t > Array2Array;
}
|
//
#include <iberbar/Paper2d/ComponentSystem.h>
//#include <iberbar/Paper2d/Component_Updatable.h>
//#include <iberbar/Paper2d/Component_HandleMouseInput.h>
//#include <iberbar/Paper2d/Component_HandleKeyboardInput.h>
//#include <iberbar/Paper2d/Node.h>
//
//
//
//iberbar::Paper2d::CComponentSystem_Updatable* iberbar::Paper2d::CComponentSystem_Updatable::sm_pSharedInstance = nullptr;
//
////
////iberbar::Paper2d::CComponentSystem_Updatable::CComponentSystem_Updatable()
//// : m_ComponentList()
//// , m_ComponentList_NewComing()
////{
//// sm_pSharedInstance = this;
////}
////
////
////iberbar::Paper2d::CComponentSystem_Updatable::~CComponentSystem_Updatable()
////{
//// sm_pSharedInstance = nullptr;
////
//// if ( m_ComponentList_NewComing.empty() == false )
//// {
//// auto iter = m_ComponentList_NewComing.begin();
//// auto end = m_ComponentList_NewComing.end();
//// for ( ; iter != end; iter ++ )
//// {
//// UNKNOWN_SAFE_RELEASE_NULL( *iter );
//// }
//// }
////
//// if ( m_ComponentList.empty() == false )
//// {
//// auto iter = m_ComponentList.begin();
//// auto end = m_ComponentList.end();
//// for ( ; iter != end; iter++ )
//// {
//// UNKNOWN_SAFE_RELEASE_NULL(*iter);
//// }
//// }
////
//// m_ComponentList_NewComing.clear();
//// m_ComponentList.clear();
////}
////
////
////void iberbar::Paper2d::CComponentSystem_Updatable::AddComponent( CComponent_Updatable* pComponent )
////{
//// if ( pComponent == nullptr )
//// return;
////
//// if ( m_ComponentList_NewComing.empty() == false )
//// {
//// auto iter = m_ComponentList_NewComing.begin();
//// auto end = m_ComponentList_NewComing.end();
//// for ( ; iter != end; iter++ )
//// {
//// if ( (*iter) == pComponent )
//// return;
//// }
//// }
////
//// if ( m_ComponentList.empty() == false )
//// {
//// auto iter = m_ComponentList.begin();
//// auto end = m_ComponentList.end();
//// for ( ; iter != end; iter++ )
//// {
//// if ( (*iter) == pComponent )
//// return;
//// }
//// }
////
//// pComponent->AddRef();
//// m_ComponentList_NewComing.push_back( pComponent );
////}
////
////
////void iberbar::Paper2d::CComponentSystem_Updatable::Update( float nDelta )
////{
//// ExecuteList( nDelta );
////}
//
//
//
//
//
//
//
//iberbar::Paper2d::CComponentSystem_HandleMouseInput* iberbar::Paper2d::CComponentSystem_HandleMouseInput::sm_pSharedInstance = nullptr;
//
//
//iberbar::Paper2d::CComponentSystem_HandleMouseInput::CComponentSystem_HandleMouseInput()
// : m_ComponentList()
// , m_ComponentList_NewComing()
//{
// sm_pSharedInstance = this;
//}
//
//
//iberbar::Paper2d::CComponentSystem_HandleMouseInput::~CComponentSystem_HandleMouseInput()
//{
// sm_pSharedInstance = nullptr;
//
// if ( m_ComponentList_NewComing.empty() == false )
// {
// auto iter = m_ComponentList_NewComing.begin();
// auto end = m_ComponentList_NewComing.end();
// for ( ; iter != end; iter++ )
// {
// UNKNOWN_SAFE_RELEASE_NULL( *iter );
// }
// }
//
// if ( m_ComponentList.empty() == false )
// {
// auto iter = m_ComponentList.begin();
// auto end = m_ComponentList.end();
// for ( ; iter != end; iter++ )
// {
// UNKNOWN_SAFE_RELEASE_NULL( *iter );
// }
// }
//
// m_ComponentList_NewComing.clear();
// m_ComponentList.clear();
//}
//
//
//void iberbar::Paper2d::CComponentSystem_HandleMouseInput::AddComponent( CComponent_HandleMouseInput* pComponent )
//{
// if ( pComponent == nullptr )
// return;
//
// pComponent->AddRef();
// m_ComponentList_NewComing.push_back( pComponent );
//}
//
//
//void iberbar::Paper2d::CComponentSystem_HandleMouseInput::HandleMouse( const UComponentMouseEventData* EventData )
//{
// if ( m_ComponentList_NewComing.empty() == false )
// {
// auto iter = m_ComponentList_NewComing.begin();
// auto end = m_ComponentList_NewComing.end();
// for ( ; iter != end; iter++ )
// {
// m_ComponentList.push_back( (*iter) );
// }
// m_ComponentList_NewComing.clear();
// }
//
// if ( m_ComponentList.empty() == false )
// {
// auto iter = m_ComponentList.begin();
// auto end = m_ComponentList.end();
// for ( ; iter != end; )
// {
// if ( (*iter)->WillRemoveFromSystem() == true )
// {
// UNKNOWN_SAFE_RELEASE_NULL( *iter );
// iter = m_ComponentList.erase( iter );
// }
// else
// {
// if ( (*iter)->GetOwner()->IsEnable() )
// {
// (*iter)->OnMouseEvent( EventData );
// }
// iter++;
// }
// }
// }
//}
//
//
//
//
//
//
//
//
//iberbar::Paper2d::CComponentSystem_HandleKeyboardInput* iberbar::Paper2d::CComponentSystem_HandleKeyboardInput::sm_pSharedInstance = nullptr;
//
//
//iberbar::Paper2d::CComponentSystem_HandleKeyboardInput::CComponentSystem_HandleKeyboardInput()
// : m_ComponentList()
// , m_ComponentList_NewComing()
//{
// sm_pSharedInstance = this;
//}
//
//
//iberbar::Paper2d::CComponentSystem_HandleKeyboardInput::~CComponentSystem_HandleKeyboardInput()
//{
// sm_pSharedInstance = nullptr;
//
// if ( m_ComponentList_NewComing.empty() == false )
// {
// auto iter = m_ComponentList_NewComing.begin();
// auto end = m_ComponentList_NewComing.end();
// for ( ; iter != end; iter++ )
// {
// UNKNOWN_SAFE_RELEASE_NULL( *iter );
// }
// }
//
// if ( m_ComponentList.empty() == false )
// {
// auto iter = m_ComponentList.begin();
// auto end = m_ComponentList.end();
// for ( ; iter != end; iter++ )
// {
// UNKNOWN_SAFE_RELEASE_NULL( *iter );
// }
// }
//
// m_ComponentList_NewComing.clear();
// m_ComponentList.clear();
//}
//
//
//void iberbar::Paper2d::CComponentSystem_HandleKeyboardInput::AddComponent( CComponent_HandleKeyboardInput* pComponent )
//{
// if ( pComponent == nullptr )
// return;
//
// pComponent->AddRef();
// m_ComponentList_NewComing.push_back( pComponent );
//}
//
//
//void iberbar::Paper2d::CComponentSystem_HandleKeyboardInput::HandleKeyboard( const UComponentKeyboardEventData* EventData )
//{
// if ( m_ComponentList_NewComing.empty() == false )
// {
// auto iter = m_ComponentList_NewComing.begin();
// auto end = m_ComponentList_NewComing.end();
// for ( ; iter != end; iter++ )
// {
// m_ComponentList.push_back( (*iter) );
// }
// m_ComponentList_NewComing.clear();
// }
//
// if ( m_ComponentList.empty() == false )
// {
// auto iter = m_ComponentList.begin();
// auto end = m_ComponentList.end();
// for ( ; iter != end; )
// {
// if ( (*iter)->WillRemoveFromSystem() == true )
// {
// UNKNOWN_SAFE_RELEASE_NULL( *iter );
// iter = m_ComponentList.erase( iter );
// }
// else
// {
// if ( (*iter)->GetOwner()->IsEnable() )
// {
// (*iter)->OnKeyboardEvent( EventData );
// }
// iter++;
// }
// }
// }
//}
//
|
//////////////////////////////////////////////////////////////////////////
//
// This software is distributed under the terms of the GNU GENERAL
// PUBLIC LICENSE Version 2, June 1991. See the package LICENSE
// file for more information.
//
//////////////////////////////////////////////////////////////////////////
#ifndef CHNGPTBOOT_CC
#define CHNGPTBOOT_CC
// the following leads to many problem
//#ifndef SCYTHE_LAPACK
//#define SCYTHE_LAPACK
#include "fastgrid_helper.h"
#include "matrix.h"
#include "distributions.h"
#include "stat.h"
#include "la.h"
#include "ide.h"
#include "smath.h"
#include <R.h> // needed to use Rprintf()
#include <R_ext/Utils.h> // needed to allow user interrupts
#include <Rdefines.h>
#include <Rinternals.h>
#include <float.h> //DBL_EPSILON
#include <R_ext/Lapack.h>
#include <Rmath.h>
#define RUNIF runif
#define PRINTF Rprintf
#define MAX(A,B) ((A) > (B) ? (A) : (B))
#define MIN(A,B) ((A) < (B) ? (A) : (B))
using namespace std;
using namespace scythe;
double M33c_search(
Matrix<double,Row>& B, Matrix<double,Row>& r, vector<double>& x, vector<double>& w,
int * thresholdIdx, vector<double>& thresholds, int nThresholds,
// forward cumulative sum
Matrix<double,Row>& Bcusum, vector<double>& rcusum, vector<double>& Wcusum, vector<double>& xcusum,
vector<double>& x2cusum, vector<double>& x3cusum, vector<double>& x4cusum, vector<double>& x5cusum,
vector<double>& xrcusum, vector<double>& x2rcusum, Matrix<double,Row>& xBcusum, Matrix<double,Row>& x2Bcusum,
// reverse cumulative sum
Matrix<double,Row>& BcusumR, vector<double>& rcusumR, vector<double>& WcusumR, vector<double>& xcusumR,
vector<double>& x2cusumR, vector<double>& x3cusumR, vector<double>& x4cusumR, vector<double>& x5cusumR,
vector<double>& xrcusumR, vector<double>& x2rcusumR, Matrix<double,Row>& xBcusumR, Matrix<double,Row>& x2BcusumR,
double* logliks)
{
// loop index.
int i,j,tt;
int k; // k has a meaning in the algorithm
int chosen=0;//initialize to get rid of compilation warning
int n=B.rows();
int p=B.cols()+1;
// need a copy of x in the calculation
vector<double> x_cpy(n);
for(i=0; i<n; i++) x_cpy[i] = x[i];
if(p>1) BcusumR(n-1,_) = B(n-1,_)* w[n-1];
rcusumR[n-1] = r(n-1)* w[n-1];
WcusumR[n-1] = w[n-1]* w[n-1];
xcusumR[n-1] = x[n-1] * w[n-1]* w[n-1]; // xcusumR is the last columnn of BcusumR, but perhaps better to be its own variable
x2cusumR[n-1] = pow(x[n-1],2) * w[n-1]* w[n-1];
x3cusumR[n-1] = pow(x[n-1],3) * w[n-1]* w[n-1];
x4cusumR[n-1] = pow(x[n-1],4) * w[n-1]* w[n-1];
x5cusumR[n-1] = pow(x[n-1],5) * w[n-1]* w[n-1];
xrcusumR[n-1] = x[n-1] * r(n-1)* w[n-1];
x2rcusumR[n-1] = pow(x[n-1],2) * r(n-1)* w[n-1];
if(p>1) xBcusumR(n-1,_) = x[n-1] * B(n-1,_)* w[n-1];
if(p>1) x2BcusumR(n-1,_)= pow(x[n-1],2) * B(n-1,_)* w[n-1];
for (i=n-2; i>=0; i--) {
if(p>1) BcusumR(i,_) = BcusumR(i+1,_) + B(i,_)* w[i];
rcusumR[i] = rcusumR[i+1] + r(i)* w[i];
WcusumR[i] = WcusumR[i+1] + w[i]* w[i];
xcusumR[i] = xcusumR[i+1] + x[i]* w[i]* w[i];
x2cusumR[i] = x2cusumR[i+1] + pow(x[i],2)* w[i]* w[i];
x3cusumR[i] = x3cusumR[i+1] + pow(x[i],3)* w[i]* w[i];
x4cusumR[i] = x4cusumR[i+1] + pow(x[i],4)* w[i]* w[i];
x5cusumR[i] = x5cusumR[i+1] + pow(x[i],5)* w[i]* w[i];
xrcusumR[i] = xrcusumR[i+1] + x[i]* r(i)* w[i];
x2rcusumR[i] = x2rcusumR[i+1] + pow(x[i],2)* r(i)* w[i];
if(p>1) xBcusumR(i,_) = xBcusumR(i+1,_) + x[i]* B(i,_)* w[i];
if(p>1) x2BcusumR(i,_)= x2BcusumR(i+1,_) + pow(x[i],2)* B(i,_)* w[i];
}
if(p>1) Bcusum(0,_) = B(0,_)* w[0];
rcusum[0] = r(0)* w[0];
Wcusum[0] = w[0]* w[0];
xcusum[0] = x[0] * w[0]* w[0];
x2cusum[0] = pow(x[0],2) * w[0]* w[0];
x3cusum[0] = pow(x[0],3) * w[0]* w[0];
x4cusum[0] = pow(x[0],4) * w[0]* w[0];
x5cusum[0] = pow(x[0],5) * w[0]* w[0];
xrcusum[0] = x[0] * r(0)* w[0];
x2rcusum[0] = pow(x[0],2) * r(0)* w[0];
if(p>1) xBcusum(0,_) = x[0] * B(0,_)* w[0];
if(p>1) x2Bcusum(0,_)= pow(x[0],2) * B(0,_)* w[0];
for (i=1; i<n; i++) {
if(p>1) Bcusum(i,_) = Bcusum(i-1,_) + B(i,_)* w[i];
rcusum[i] = rcusum[i-1] + r(i)* w[i];
Wcusum[i] = Wcusum[i-1] + w[i]* w[i];
xcusum[i] = xcusum[i-1] + x[i]* w[i]* w[i];
x2cusum[i] = x2cusum[i-1] + pow(x[i],2)* w[i]* w[i];
x3cusum[i] = x3cusum[i-1] + pow(x[i],3)* w[i]* w[i];
x4cusum[i] = x4cusum[i-1] + pow(x[i],4)* w[i]* w[i];
x5cusum[i] = x5cusum[i-1] + pow(x[i],5)* w[i]* w[i];
xrcusum[i] = xrcusum[i-1] + x[i]* r(i)* w[i];
x2rcusum[i] = x2rcusum[i-1] + pow(x[i],2)* r(i)* w[i];
if(p>1) xBcusum(i,_) = xBcusum(i-1,_) + x[i]* B(i,_)* w[i];
if(p>1) x2Bcusum(i,_)= x2Bcusum(i-1,_) + pow(x[i],2)* B(i,_)* w[i];
}
//for (i=0; i<n; i++) {for (j=0; j<p; j++) PRINTF("%f ", Bcusum(i,j)); PRINTF("\n");}
//for (i=0; i<n; i++) PRINTF("%f ", rcusum[i]); PRINTF("\n");
// Step 2: Initialize VV, Vr and VB
Matrix <double,Row,Concrete> VV(4, 4), Vr(4, 1), VB(4, p-1);
double e, d, d2, d3, crit, crit_max=R_NegInf;// d2 is defined as difference in squared threshold
VV(2,3)=VV(3,2)=0;
// x-e, not thresholded
for(i=0; i<n; i++) x[i]=x[i]-thresholds[0];
VV(0,0)=0; for (i=0; i<n; i++) VV(0,0) += pow(x[i],2)* w[i]* w[i];
VV(1,1)=0; for (i=0; i<n; i++) VV(1,1) += pow(x[i],4)* w[i]* w[i];
VV(0,1)=0; for (i=0; i<n; i++) VV(0,1) += pow(x[i],3)* w[i]* w[i];
VV(1,0)=VV(0,1);
Vr(0,0)=0; for (i=0; i<n; i++) Vr(0,0) += x[i]*r(i)* w[i];
Vr(1,0)=0; for (i=0; i<n; i++) Vr(1,0) += pow(x[i],2)*r(i)* w[i];
for (j=0; j<p-1; j++) {
VB(0,j)=0; for (i=0; i<n; i++) VB(0,j) += x[i] * B(i,j)* w[i]; // remember the first p-1 column of B is B after _preprocess()
VB(1,j)=0; for (i=0; i<n; i++) VB(1,j) += pow(x[i],2) * B(i,j)* w[i]; // remember the first p-1 column of B is B after _preprocess()
}
// threshold x (stored in the last column of B) at the first threshold value
// Upper hinge (x-e)-
for(i=0; i<thresholdIdx[0]; i++) x[i]=x_cpy[i]-thresholds[0];
for(i=thresholdIdx[0]; i<n; i++) x[i]=0;
VV(2,2)=0; for (i=0; i<n; i++) VV(2,2) += pow(x[i],6)* w[i]* w[i];
VV(0,2)=0; for (i=0; i<n; i++) VV(0,2) += pow(x[i],4)* w[i]* w[i];
VV(1,2)=0; for (i=0; i<n; i++) VV(1,2) += pow(x[i],5)* w[i]* w[i];
VV(2,0)=VV(0,2);
VV(2,1)=VV(1,2);
Vr(2,0)=0; for (i=0; i<n; i++) Vr(2,0) += pow(x[i],3)*r(i)* w[i];
for (j=0; j<p-1; j++) {
VB(2,j)=0; for (i=0; i<n; i++) VB(2,j) += pow(x[i],3) * B(i,j)* w[i]; // remember the first p-1 column of B is B after _preprocess()
}
// threshold x (stored in the last column of B) at the first threshold value
// Hinge (x-e)+
for(i=0; i<thresholdIdx[0]; i++) x[i]=0;
for(i=thresholdIdx[0]; i<n; i++) x[i]=x_cpy[i]-thresholds[0];
VV(3,3)=0; for (i=0; i<n; i++) VV(3,3) += pow(x[i],6)* w[i]* w[i];
VV(0,3)=0; for (i=0; i<n; i++) VV(0,3) += pow(x[i],4)* w[i]* w[i];
VV(1,3)=0; for (i=0; i<n; i++) VV(1,3) += pow(x[i],5)* w[i]* w[i];
VV(3,0)=VV(0,3);
VV(3,1)=VV(1,3);
Vr(3,0)=0; for (i=0; i<n; i++) Vr(3,0) += pow(x[i],3)*r(i)* w[i];
for (j=0; j<p-1; j++) {
VB(3,j)=0; for (i=0; i<n; i++) VB(3,j) += pow(x[i],3) * B(i,j)* w[i]; // remember the first p-1 column of B is B after _preprocess()
}
// Step 4 (Step 3 = Step 4b)
for(tt=0; tt<nThresholds; tt++) {
// Step 4a: update VV, Vr and VB
if(tt>0) {
d=thresholds[tt]-thresholds[tt-1]; //B(tt,p-1)-B(tt-1,p-1); //PRINTF("%f ", d); PRINTF("\n");
d2=pow(thresholds[tt],2) - pow(thresholds[tt-1],2);
d3=pow(thresholds[tt],3) - pow(thresholds[tt-1],3);
// e.g, when tt=1, we are at the second threshold, we want to update vv, vr and vB for e_2
// tt=1 and tt+1=2
k = thresholdIdx[tt-1]; // k is 1-based index of x, e_t = x_k
e = thresholds[tt-1];
double c7=-2*d*xcusum[n-1] + 2*Wcusum[n-1]*d*e + Wcusum[n-1]* pow(d,2);
double c8=-4*d*x3cusum[k-1] + (6*d*e+3*d2+3*d*d)*x2cusum[k-1] - (3*d*e*e+3*d2*e+d3+3*d*d2)*xcusum[k-1] + Wcusum[k-1]*d*e*e*e + Wcusum[k-1]*d3*e + Wcusum[k-1]*d*d3;
double c9=-5*d*x4cusum[k-1] + (12*d*e+4*d2+6*d*d)*x3cusum[k-1] - (9*d*e*e+9*d2*e+d3+9*d*d2)*x2cusum[k-1] + (2*d*e*e*e+6*d2*e*e+2*d3*e+2*d*d3+3*d2*d2)*xcusum[k-1] - (Wcusum[k-1]*d2*e*e*e + Wcusum[k-1]*d3*e*e + Wcusum[k-1]*d2*d3);
double c10=-6*d*x5cusum[k-1] + (18*d*e+6*d2+9*d*d)*x4cusum[k-1] - (18*d*e*e+18*d2*e+2*d3+18*d*d2)*x3cusum[k-1] + (6*d*e*e*e+18*d2*e*e+6*d3*e+6*d*d3+9*d2*d2)*x2cusum[k-1] - (6*d2*e*e*e+6*d3*e*e+6*d2*d3)*xcusum[k-1] + (2*Wcusum[k-1]*d3*e*e*e + Wcusum[k-1]*d3*d3);
double c11= -3*d*x2cusum[n-1] + (4*d*e+d2+2*d*d)*xcusum[n-1] -(Wcusum[n-1]*d*e*e + Wcusum[n-1]*d2*e + Wcusum[n-1]*d*d2);
double c12= -4*d*x3cusumR[k] + (6*d*e+3*d2+3*d*d)*x2cusumR[k] - (3*d*e*e+3*d2*e+d3+3*d*d2)*xcusumR[k] + WcusumR[k]*d*e*e*e + WcusumR[k]*d3*e + WcusumR[k]*d*d3;
double c13= -4*d*x3cusum[n-1] + (8*d*e+2*d2+4*d*d)*x2cusum[n-1] - (4*d*e*e+4*d2*e+4*d*d2)*xcusum[n-1] + 2*Wcusum[n-1]*d2*e*e + Wcusum[n-1]*d2*d2;
double c14= -5*d*x4cusumR[k] + (12*d*e+4*d2+6*d*d)*x3cusumR[k] - (9*d*e*e+9*d2*e+d3+9*d*d2)*x2cusumR[k] + (2*d*e*e*e+6*d2*e*e+2*d3*e+2*d*d3+3*d2*d2)*xcusumR[k] - (WcusumR[k]*d2*e*e*e + WcusumR[k]*d3*e*e + WcusumR[k]*d2*d3);
double c15= -6*d*x5cusumR[k] + (18*d*e+6*d2+9*d*d)*x4cusumR[k] - (18*d*e*e+18*d2*e+2*d3+18*d*d2)*x3cusumR[k] + (6*d*e*e*e+18*d2*e*e+6*d3*e+6*d*d3+9*d2*d2)*x2cusumR[k] - (6*d2*e*e*e+6*d3*e*e+6*d2*d3)*xcusumR[k] + (2*WcusumR[k]*d3*e*e*e + WcusumR[k]*d3*d3);
VV(0,0) += c7;
VV(1,1) += c13;
VV(2,2) += c10;
VV(3,3) += c15;
VV(0,1) += c11; VV(1,0) = VV(0,1);
VV(0,2) += c8; VV(2,0) = VV(0,2);
VV(0,3) += c12; VV(3,0) = VV(0,3);
VV(1,2) += c9; VV(2,1) = VV(1,2);
VV(1,3) += c14; VV(3,1) = VV(1,3);
Vr[0] += -d * rcusum[n-1];
Vr[1] += -2*d * xrcusum[n-1] + d2 * rcusum[n-1] ;
Vr[2] += -3*d * x2rcusum[k-1] +3*d2 * xrcusum[k-1] -d3 * rcusum[k-1] ;
Vr[3] += -3*d * x2rcusumR[k] +3*d2 * xrcusumR[k] -d3 * rcusumR[k] ;
for (j=0; j<p-1; j++) {
VB(0,j) += -d * Bcusum(n-1,j);
VB(1,j) += -2*d * xBcusum(n-1,j) + d2 * Bcusum(n-1,j);
VB(2,j) += -3*d * x2Bcusum(k-1,j) +3*d2 * xBcusum(k-1,j) -d3 * Bcusum(k-1,j);
VB(3,j) += -3*d * x2BcusumR(k ,j) +3*d2 * xBcusumR(k ,j) -d3 * BcusumR(k ,j);
}
// if(tt==1) {
// for (i=0; i<4; i++) {for (j=0; j<4; j++) PRINTF("%f ", VV(i,j)); PRINTF("\n");}
// for (i=0; i<4; i++) {for (j=0; j<1; j++) PRINTF("%f ", Vr(i,j)); PRINTF("\n");}
// for (i=0; i<4; i++) {for (j=0; j<p-1; j++) PRINTF("%f ", VB(i,j)); PRINTF("\n");}
// }
} // end if tt==0
// if(tt==0) {
// for (i=0; i<4; i++) {for (j=0; j<4; j++) PRINTF("%f ", VV(i,j)); PRINTF("\n");}
// for (i=0; i<4; i++) {for (j=0; j<1; j++) PRINTF("%f ", Vr(i,j)); PRINTF("\n");}
// for (i=0; i<4; i++) {for (j=0; j<p-1; j++) PRINTF("%f ", VB(i,j)); PRINTF("\n");}
// }
// Step 4b: compute r'H_eY - r'HY
if (p>1) {
crit = ( t(Vr) * chol_solve(VV - VB * t(VB), Vr) ) (0,0);
} else { // VB has 0 columns
crit = ( t(Vr) * chol_solve(VV, Vr) ) (0,0);
}
logliks[tt] = crit;
if(crit>=crit_max) {
chosen = tt;
crit_max=crit;
}
}
//PRINTF("logliks: \n"); for(i=0; i<nThresholds; i++) PRINTF("%f ", logliks[i]); PRINTF("\n");
return thresholds[chosen];
}
#endif
//#endif
|
#include "service.h"
#include "health.h"
const KeyStroke KeyStrokes[]= {
{ SHINE_RCVD_SIG, "SHINE_RCVD", 'i'},
{ CENTRAL_BUTTON_PRESSED_SIG, "CENTRAL_BUTTON_PRESSED", 'b'},
{ TIME_TICK_1S_SIG, "TIME_TICK_1S", 's'},
{ TIME_TICK_1M_SIG, "TIME_TICK_1M", 'm'},
{ DMG_RCVD_SIG, "DMG_RCVD", 'd'},
{ PILL_HEAL_SIG, "PILL_HEAL", 'h'},
{ PILL_RESET_SIG, "PILL_RESET", 'r'},
{ PILL_TAILOR_SIG, "PILL_TAILOR", 't'},
{ PILL_STALKER_SIG, "PILL_STALKER", 'p'},
{ PILL_LOCAL_SIG, "PILL_LOCAL", 'l'},
{ FIRST_BUTTON_PRESSED_SIG, "FIRST_BUTTON_PRESSED", 'f'},
{ SHINE_SIG, "SHINE", 'h'},
{ PILL_MUTANT_SIG, "PILL_MUTANT", 'u'},
{ SHINE_ORDER_SIG, "SHINE_ORDER", 'o'},
{ TERMINATE_SIG, "TERMINATE", 0x1B }
};
unsigned int KeyNumber() {
return sizeof(KeyStrokes)/sizeof(KeyStrokes[0]);
}
|
/*! @file LogVol_CCHardCovering_Base.hh
@brief Defines mandatory user class LogVol_CCHardCovering_Base.
@date August, 2012
@author Flechas (D. C. Flechas dcflechasg@unal.edu.co)
@version 1.9
In this header file, the 'physical' setup is defined: materials, geometries and positions.
This class defines the experimental hall used in the toolkit.
*/
/* no-geant4 classes*/
#include "LogVol_CCHardCovering_Base.hh"
/* units and constants */
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
/* geometric objects */
#include "G4Box.hh"
#include "G4Tubs.hh"
#include "G4Polycone.hh"
#include "G4UnionSolid.hh"
#include "G4SubtractionSolid.hh"
/* logic and physical volume */
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
/* geant4 materials */
#include "G4NistManager.hh"
#include "G4Material.hh"
/* visualization */
#include "G4VisAttributes.hh"
LogVol_CCHardCovering_Base:: LogVol_CCHardCovering_Base(G4String fname):
G4LogicalVolume(new G4Box(fname+"_Sol",65*cm/2.0,65*cm/2.0,50*cm/2.0),(G4NistManager::Instance())->FindOrBuildMaterial("G4_Al"),fname,0,0,0)
{
/* set variables */
SetName(fname);
//material=(G4NistManager::Instance())->FindOrBuildMaterial("G4_Al");
Cyl_height = 1.8*cm;
Cyl_radius = 23.4/2.0*cm;
Box_height = 1.7*cm;
Box_length = 28.0*cm;
Box_width = 23.4*cm;
Base_thickness = 0.3*cm;
/* Construct solid volume */
ConstructSolidVol_CCHardCovering_Base();
/* Visualization */
G4VisAttributes* gray_vis
= new G4VisAttributes(true,G4Colour(0.5,0.5,0.5));
gray_vis->SetForceWireframe(false);
gray_vis->SetForceSolid(false);
this->SetVisAttributes(gray_vis);
}
LogVol_CCHardCovering_Base::~LogVol_CCHardCovering_Base()
{}
void LogVol_CCHardCovering_Base::ConstructSolidVol_CCHardCovering_Base(void)
{
/// Outer part ///
const G4int numZPlanes_Cyl = 2;
G4double zPlane_Cyl[numZPlanes_Cyl] = {0.0*cm,Cyl_height};
G4double rInner_Cyl[numZPlanes_Cyl] = {0.0*cm,0.0*cm};
G4double rOuter_Cyl[numZPlanes_Cyl] = {Cyl_radius,Cyl_radius};
G4Polycone* Cyl_Outer = new G4Polycone(Name+"_CylOut_Sol",0.*rad,2*M_PI*rad,numZPlanes_Cyl,
zPlane_Cyl,rInner_Cyl,rOuter_Cyl);
G4Box* Box_Outer = new G4Box(Name+"_BoxOut_Sol",Box_width/2.0,Box_length/2.0,Box_height/2.0);
G4UnionSolid* Base_Outer = new G4UnionSolid(Name+"_BaseOut_Sol", Cyl_Outer, Box_Outer,0,
G4ThreeVector(0.,Box_length/2.0,Box_height/2.0));
/// Inner space ////
const G4int numZPlanes_Cyl_In = 2;
G4double zPlane_Cyl_In[numZPlanes_Cyl_In] = {0.0*cm,Cyl_height};
G4double rInner_Cyl_In[numZPlanes_Cyl_In] = {0.0*cm,0.0*cm};
G4double rOuter_Cyl_In[numZPlanes_Cyl_In] = {Cyl_radius-Base_thickness,
Cyl_radius-Base_thickness};
G4Polycone* Cyl_Inner = new G4Polycone(Name+"_CylOut_Sol",0.*rad,2*M_PI*rad,numZPlanes_Cyl_In,
zPlane_Cyl_In,rInner_Cyl_In,rOuter_Cyl_In);
G4Box* Box_Inner = new G4Box(Name+"_BoxOut_Sol",(Box_width-2.0*Base_thickness)/2.0,
(Box_length-Base_thickness)/2.0,
Box_height/2.0);
G4UnionSolid* Base_Inner = new G4UnionSolid(Name+"_BaseInn_Sol", Cyl_Inner, Box_Inner,0,
G4ThreeVector(0.,
(Box_length-Base_thickness)/2.0,
Box_height/2.0));
CCHardCovering_Base_solid = new G4SubtractionSolid(Name+"_Sol",
Base_Outer,Base_Inner,
0,G4ThreeVector(0.,0.,Base_thickness));
/*** Main trick here: Set the new solid volume ***/
SetSolidVol_CCHardCovering_Base();
}
void LogVol_CCHardCovering_Base::SetSolidVol_CCHardCovering_Base(void)
{
/*** Main trick here: Set the new solid volume ***/
if(CCHardCovering_Base_solid)
this->SetSolid(CCHardCovering_Base_solid);
}
|
#pragma once
#include "Unit.h"
#include "Cell.h"
#include <map>
#include "LandScape.h"
#include "Bonus.h"
class Cavalry : public Unit
{
public:
std::map<std::string, int> getMap();
static std::map<std::string, int> CBonus;
std::string getName();
//bool doAction(std::string);
Cavalry(int Health, int Demage, const Cell *cell, Player& player);
Cavalry(int Health, int Demage, const Cell* cell, Player* player);
~Cavalry();
};
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Игра "Угадай букву!". Пример использования оператора break в бесконечном цикле
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include <iostream>
int main() {
using namespace std;
int count = 0;
cout << "Guess the letter!" << endl;
int con = 0;
// Выводим английские буквы в алфавитном порядке
// в столбик по 13 букв
for (char ch = 'a'; ch <= 'z'; ++ch) {
++con;
if (con % 13 == 0) {
cout << "\n";
}
cout << ch << " ";
}
while (true) {
cout << "\nEnter letter: ";
char sm;
cin >> sm;
if (sm == 'e') {
break;
}
++count;
cout << sm << "Iteration: " << count << endl; // Номер попытки
cout << "Try again!" << endl;
}
cout << "Sum iteration: " << count << endl; // Сумма попыток
return 0;
}
// Output:
/*
Enter letter: k
kIteration: 3
Try again!
Enter letter: q
qIteration: 4
Try again!
Enter letter: e
Sum iteration: 4
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#include <stdio.h>
#include <stdlib.h>
#include "Player.h"
#include "Logger.h"
#include "BaseProcess.h"
#include "HallHandler.h"
#include "GameCmd.h"
#include "ProcessManager.h"
#include "Configure.h"
//static int betnum[7]={100, 500, 1000, 2000, 5000, 10000, 50000};
static int betnum[6] = { 100, 500, 1000, 5000, 10000, 50000 };
int pase_json(Json::Value& value, const char* key, int def)
{
int v = def;
try{
v = value[key].asInt();
}
catch(...)
{
v = def;
}
return v;
}
void Player::init()
{
timer.init(this);
level = 1;
id = -1; //用户id
memset(name,0,sizeof(name));
tid = 0; //当前属于哪个桌子id
tab_index = -1;//当前在桌子的位置
money = 0; //金币数
nwin = 0; //赢牌数
nlose = 0; //输牌数
memset(json, 0, sizeof(json)); //json字符串
status = 0; //状态 0 未登录 1 在玩牌
source = 0; //用户来源
clevel = 0; //当前金币场底注 0-无底注
isdropline = false; //是否已经掉线
betNum = 0;
bettype = 0;
betcoin = 0;
playNum = 0;
willPlayCount = 0;
bankeruid = 0;
bankerwinCount = 0;
bankerhasNum = 0;
memset(m_lBetArray , 0 , sizeof(m_lBetArray));
}
int Player::login()
{
BaseProcess* process = ProcessManager::getInstance().getProcesser(HALL_USER_LOGIN);
return process->doRequest(this->handler, NULL, NULL);
}
int Player::logout()
{
BaseProcess* process = ProcessManager::getInstance().getProcesser(CLIENT_MSG_LEAVE);
return process->doRequest(this->handler, NULL, NULL);
}
int Player::heartbeat()
{
BaseProcess* process = ProcessManager::getInstance().getProcesser(USER_HEART_BEAT);
return process->doRequest(this->handler, NULL, NULL);
}
int getCoin(int64_t money)
{
int randnum = rand()%6;
int willbetcoin = betnum[randnum];
while(randnum >= 0)
{
int willbetcoin = betnum[randnum];
if(money < willbetcoin)
--randnum;
else
return willbetcoin;
}
return 0;
}
int getBetCoin(int64_t money)
{
//return 100;
int randnum = rand()%6;
if(randnum < 2)
randnum = 2;
int willbetcoin = betnum[randnum];
while(randnum >= 0)
{
int willbetcoin = betnum[randnum];
if(money < willbetcoin)
--randnum;
else
return willbetcoin;
}
return 0;
}
int getLowCoin(int64_t money)
{
int randnum = rand()%3;
int willbetcoin = betnum[randnum];
while(randnum >= 0)
{
int willbetcoin = betnum[randnum];
if(money < willbetcoin)
--randnum;
else
return willbetcoin;
}
return 0;
}
int Player::betCoin()
{
srand(time(NULL));
if(Configure::getInstance()->level == 3)
{
for (int i = 0; i < rand() % 10 + 1; i++)
{
if (this->betNum < 10)
{
this->betNum++;
/*if(this->betcoin == 0)
this->betcoin = getBetCoin(this->money);
else
this->betcoin = this->betcoin;
if(this->betNum > 2)
this->betcoin = getLowCoin(this->money);
if(this->bettype == 0)
{
int num = rand()%2;
this->bettype = (num == 0) ? 1 : 3;
}
else if(this->bettype == 1)
this->bettype = 3;
else
{
this->bettype = 1;
}
//this->bettype = ((num==1) ? 1 : 3);
if(this->betcoin == 0)
return 0;*/
// int num = rand()%1000;
// this->betcoin = getBetCoin(this->money);
// if(num < 750)
// {
// int betnum = rand()%2;
// this->bettype = ((betnum==1) ? 4 : 5);
// }
// if(num >= 750 && num < 850)
// {
// this->betcoin = getLowCoin(this->money);
// int betnum = rand()%2;
// this->bettype = ((betnum==1) ? 1 : 3);
// }
//
// if(num >= 850 && num < 1000)
// {
// int randmin = rand()%100;
// if(randmin < 60)
// this->betcoin = getLowCoin(this->money);
//
// this->bettype = 2;
// }
int bt = rand() % 100;
int num = rand() % 1000;
int big_rate = rand() % 100;
_LOG_DEBUG_("当前下注情况: 总压闲[%ld], 总压庄[%ld], 总压和[%ld], 总压庄对[%ld], 总压闲对[%ld]" ,
m_lBetArray[4] , m_lBetArray[5] , m_lBetArray[2] , m_lBetArray[3] , m_lBetArray[1]);
//庄闲下注区域总额偏差超过 70%,选择小额区域下注
if (m_lBetArray[4] > m_lBetArray[5] && m_lBetArray[4] - m_lBetArray[5] > 500 && m_lBetArray[5] * 100 / m_lBetArray[4] <= 70)
{
if (big_rate < 50)
{
this->betcoin = getBetCoin(this->money);
}
else if (big_rate < 90)
{
this->betcoin = 0;
}
else
{
this->betcoin = getLowCoin(this->money);
}
_LOG_DEBUG_("总压闲太少,机器人:%s 压闲[%d]", this->name, this->betcoin);
this->bettype = 5; // 压闲
}
else if (m_lBetArray[5] > m_lBetArray[4] && m_lBetArray[5] - m_lBetArray[4] > 500 && m_lBetArray[4] * 100 / m_lBetArray[5] <= 70)
{
if (big_rate < 50)
{
this->betcoin = getBetCoin(this->money);
}
else if (big_rate < 90)
{
this->betcoin = 0;
}
else
{
this->betcoin = getLowCoin(this->money);
}
_LOG_DEBUG_("总压庄太少,机器人:%s 压庄", this->name, this->betcoin);
this->bettype = 4; // 压庄
}
else
{
//if (bt < 75)
if (bt < 40) // 40%概率压庄或闲
{
this->bettype = 4;
//if (num < 500)
if (num < 300)
{
if (m_lBetArray[5] - m_lBetArray[4] > 100)
{
this->betcoin = getBetCoin(this->money);
}
else
{
this->betcoin = getLowCoin(this->money);
}
}
//else if (num >= 500 && num < 980)
else if (num >= 300 && num < 600)
{
this->bettype = 5;
if (m_lBetArray[5] - m_lBetArray[4] > 100)
{
this->betcoin = getBetCoin(this->money);
}
else
{
this->betcoin = getLowCoin(this->money);
}
}
else
{
this->betcoin = 0; //极低几率不下注
}
}
//else if (bt >= 75 && bt < 85)
else if (bt >= 40 && bt < 50)
{
this->bettype = 1;
if (num < 200) // 5%压闲对
{
this->betcoin = getLowCoin(this->money);
}
else if (num >= 200 && num < 500) // // 不到5%的概率压庄对
{
this->bettype = 3;
this->betcoin = getLowCoin(this->money);
}
else
{
this->betcoin = 0; //极低几率不下注
}
}
else
{
this->bettype = 2;
// 5%的概率压庄对, 大额压的概率是2.5%, 小额压的概率是2.5%
//if (num < 980)
if (num < 26)
{
this->betcoin = getLowCoin(this->money);
}
//else if (num >= 980 && num < 995)
else if (num >= 26 && num < 29)
{
this->betcoin = getBetCoin(this->money);
}
else
{
this->betcoin = 0; //极低几率不下注
}
}
}
// if (num < 500)
// {
// this->betcoin = getCoin(this->money);
// }
// else if (num >= 500 && num < 750)
// {
// this->betcoin = getLowCoin(this->money);
// }
// else if (num >= 750 && num < 980)
// {
// this->betcoin = getBetCoin(this->money);
// }
// else
// {
// this->betcoin = 0; //极低几率不下注
// }
_LOG_DEBUG_("id:%d bettype:%d betcoin:%d\n", this->id, this->bettype, this->betcoin);
if (this->betcoin == 0)
continue;
BaseProcess* process = ProcessManager::getInstance().getProcesser(CLIENT_MSG_BET_COIN);
return process->doRequest(this->handler, NULL, NULL);
}
}
}
// if(Configure::getInstance()->level == 1)
// {
// this->betNum++;
// if(this->bettype == 0)
// {
// int rate = rand() % 1000;
// if (rate <= 850)
// {
// int num = rand() % 2;
// this->bettype = (num == 0) ? 1 : 3;
// }
// else
// {
// this->bettype = 2;
// }
// }
// this->betcoin = getCoin(this->money);
// if(this->betcoin == 0)
// return 0;
// }
//this->betcoin /= 1000;
return 0;
}
void Player::startHeartTimer(int timeout)
{
timer.startHeartTimer(timeout);
}
void Player::startBetTimer(int timeout)
{
timer.startBetCoinTimer(timeout);
printf("id:%d time:%d start time\n", this->id, timeout);
}
void Player::stopBetTimer()
{
timer.stopBetCoinTimer();
}
|
#include "HealthBar.h"
HealthBar::HealthBar() {
TextureManager::Instance()->load("...Assets/Textures/HealthBar3.png", "healthbar3");
TextureManager::Instance()->load("...Assets/Textures/HealthBar2.png", "healthbar2");
TextureManager::Instance()->load("...Assets/Textures/HealthBar1.png", "healthbar1");
TextureManager::Instance()->load("...Assets/Textures/HealthBar0.png", "healthbar0");
}
HealthBar::~HealthBar()
= default;
void HealthBar::draw() {
const auto x = getTransform()->position.x;
const auto y = getTransform()->position.y;
switch (health) {
case 3:
TextureManager::Instance()->draw("healthbar3", x, y, 0, 255, true);
break;
case 2:
TextureManager::Instance()->draw("healthbar2", x, y, 0, 255, true);
break;
case 1:
TextureManager::Instance()->draw("healthbar1", x, y, 0, 255, true);
break;
case 0:
TextureManager::Instance()->draw("healthbar0", x, y, 0, 255, true);
break;
default:
TextureManager::Instance()->draw("healthbar3", x, y, 0, 255, true);
break;
}
}
void HealthBar::update(){}
void HealthBar::clean(){}
|
#include <iostream>
using namespace std;
int partition(int A[], int p, int r){
int x = A[r];
int i = p-1;
for(int j=p; j<r; j++){
if(A[j] <= x){
i++;
swap(A[i], A[j]);
}
}
swap(A[i+1], A[r]);
return i+1;
}
int main(void){
int n;
int A[100001];
cin >> n;
for(int i=0; i<n; i++) cin >> A[i];
int q = partition(A, 0, n-1);
for(int i=0; i<n; i++){
cout << (i ? " " : "") << (i==q ? "[" : "") << A[i] << (i==q ? "]" : "");
}
cout << endl;
return 0;
}
|
#include <iostream>
#include <cmath>
#include <unordered_map>
using namespace std;
class Solution {
public:
string fractionToDecimal(long numerator, long denominator) {
if(numerator == 0)
return "0";
string res;
if((0 > numerator) ^ (0 > denominator))
res += "-";
numerator = labs(numerator);
denominator = labs(denominator);
long r = numerator % denominator;
res += to_string(numerator / denominator);
if(!r)
return res;
res += ".";
unordered_map<int, int> map;
while(r){
if(map.count(r)){
res.insert(map[r], "(");
res += ")";
break;
}
map.insert({r, res.size()});
r *= 10;
res += to_string(r / denominator);
r %= denominator;
}
return res;
}
};
int main(void){
Solution sol;
cout << sol.fractionToDecimal(4, 2) << endl;
cout << sol.fractionToDecimal(1, 2) << endl;
cout << sol.fractionToDecimal(2, 3) << endl;
cout << sol.fractionToDecimal(-2147483648, 1) << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* 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 Anders Karlsson (pugo)
*/
#ifndef POSTSCRIPT_PROLOG_H
#define POSTSCRIPT_PROLOG_H
#ifdef VEGA_POSTSCRIPT_PRINTING
#include "modules/libvega/src/postscript/postscriptcommandbuffer.h"
class OpFileDescriptor;
class TrueTypeConverter;
/** @brief Helper class to abstract creation of a PostScript document prolog part (upper part with meta info and resources).
*/
class PostScriptProlog : public PostScriptCommandBuffer
{
public:
PostScriptProlog();
/** Destructor */
~PostScriptProlog();
/**
* @param file A closed, constructed file object - will be opened for writing
*/
OP_STATUS Init(OpFileDescriptor& file, PostScriptOutputMetrics* screen_metrics, PostScriptOutputMetrics* paper_metrics);
/** Add a font to be included in the document. This involves converting the
* font to PostScript Type42 and writing the results in hexcode.
*
* A hash table of currently included fonts makes sure that only new ones
* are added. This makes it safe to call this multiple times for the same font.
*
* @param font font to add to document
* @param ps_fontname upon return this will point to the
generated PostScript name for this font - pointer is owned by
current_handled_font
* @return OK on success, ERR_NO_MEMORY on OOM, ERR on other error.
*/
OP_STATUS addFont(OpFont* font, const char*& ps_fontname);
/** Finish generation of the prolog. This includes ending the setup part of the prolog */
OP_STATUS finish();
/** Return TrueTypeConverter for the currently used font
* @return pointer to TrueTypeConverter for currently used font. Null if no font is currently used. */
TrueTypeConverter* getCurrentFontConverter();
/** Get current font data and its size
* @param font_data (out) pointer to current font data
* @param font_data_size (out) current font data size */
void getCurrentFontData(UINT8*& font_data, UINT32& font_data_size);
private:
class HandledFont
{
public:
HandledFont(UINT32 checksum, TrueTypeConverter* font_converter, OpString8& ps_fontname)
: checksum(checksum), has_slanted_copy(false)
{ this->ps_fontname.TakeOver(ps_fontname); this->font_converter = font_converter; }
~HandledFont();
UINT32 checksum;
OpString8 ps_fontname;
TrueTypeConverter* font_converter;
bool has_slanted_copy;
OpString8 ps_fontname_slanted;
};
/**
adds a truetype font
@param font should be a font in g_font_cache - on success
ownership will be transformed to this, font will be referenced
via g_font_cache->ReferenceFont(...) and later released via
g_font_cache->ReleaseFont(...)
@param font_data should be fetched using
OpFont::GetFontData(...) - on success ownership will be
trasferred to this and later released via
OpFont::ReleaseFontData
@param font_data_size the size of the font data
@param ps_fontname the internal name of the font (OperaFontX) - this pointer is owned by the HandledFont
*/
OP_STATUS addTrueTypeFont(OpFont* font, UINT8* font_data, UINT32 font_data_size, const char*& ps_fontname);
/**
creates a new HandledFont and stores it in handled_fonts
@param font_converter will be deleted on failure, on success ownership is transferred to handled_font
@param checksum GLYF checksum for the font
@param font_name the internal name of the font
@param handled_font (out) handle to the created HandledFont
@return OpStatus::OK on success, OpStatus::ERR on failure, OpStatus::ERR_NO_MEMORY on OOM
*/
OP_STATUS addHandledFont(TrueTypeConverter* font_converter, UINT32 checksum, OpString8& font_name, HandledFont*& handled_font);
bool checkNeedsManualSlant(OpFont* font, bool glyphs_are_italic);
/**
@param slanted_fontname - owned by handled_font
*/
OP_STATUS getSlantedFontCopy(HandledFont* handled_font, const char*& slanted_fontname);
OP_STATUS generateFontResource(TrueTypeConverter* converter, OpString8& ps_fontname);
OP_STATUS addSuppliedResource(OpString8& resource_name);
PostScriptOutputMetrics* screen_metrics;
PostScriptOutputMetrics* paper_metrics;
UINT32 font_count;
HandledFont* current_handled_font;
OpFont* current_opfont;
UINT8* current_font_data;
UINT32 current_font_data_size;
OpString8 document_supplied_resources;
OpString8 document_slanted_fonts;
OpAutoINT32HashTable<HandledFont> handled_fonts;
};
#endif // VEGA_POSTSCRIPT_PRINTING
#endif // POSTSCRIPT_P_H
|
//
// ZXSpectrum.cpp
// Clock Signal
//
// Created by Thomas Harte on 17/03/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "ZXSpectrum.hpp"
#include "Video.hpp"
#define LOG_PREFIX "[Spectrum] "
#include "../../../Activity/Source.hpp"
#include "../../MachineTypes.hpp"
#include "../../../Processors/Z80/Z80.hpp"
#include "../../../Components/AudioToggle/AudioToggle.hpp"
#include "../../../Components/AY38910/AY38910.hpp"
// TODO: possibly there's a better factoring than this, but for now
// just grab the CPC's version of an FDC.
#include "../../AmstradCPC/FDC.hpp"
#include "../../../Outputs/Log.hpp"
#include "../../../Outputs/Speaker/Implementation/CompoundSource.hpp"
#include "../../../Outputs/Speaker/Implementation/LowpassSpeaker.hpp"
#include "../../../Outputs/Speaker/Implementation/SampleSource.hpp"
#include "../../../Storage/Tape/Tape.hpp"
#include "../../../Storage/Tape/Parsers/Spectrum.hpp"
#include "../../../Analyser/Static/ZXSpectrum/Target.hpp"
#include "../../Utility/MemoryFuzzer.hpp"
#include "../../Utility/Typer.hpp"
#include "../../../ClockReceiver/JustInTime.hpp"
#include "../../../Processors/Z80/State/State.hpp"
#include "../Keyboard/Keyboard.hpp"
#include <array>
namespace Sinclair {
namespace ZXSpectrum {
using Model = Analyser::Static::ZXSpectrum::Target::Model;
using CharacterMapper = Sinclair::ZX::Keyboard::CharacterMapper;
template<Model model> class ConcreteMachine:
public Activity::Source,
public ClockingHint::Observer,
public Configurable::Device,
public CPU::Z80::BusHandler,
public Machine,
public MachineTypes::AudioProducer,
public MachineTypes::MappedKeyboardMachine,
public MachineTypes::MediaTarget,
public MachineTypes::ScanProducer,
public MachineTypes::TimedMachine,
public Utility::TypeRecipient<CharacterMapper> {
public:
ConcreteMachine(const Analyser::Static::ZXSpectrum::Target &target, const ROMMachine::ROMFetcher &rom_fetcher) :
Utility::TypeRecipient<CharacterMapper>(Sinclair::ZX::Keyboard::Machine::ZXSpectrum),
z80_(*this),
ay_(GI::AY38910::Personality::AY38910, audio_queue_),
audio_toggle_(audio_queue_),
mixer_(ay_, audio_toggle_),
speaker_(mixer_),
keyboard_(Sinclair::ZX::Keyboard::Machine::ZXSpectrum),
keyboard_mapper_(Sinclair::ZX::Keyboard::Machine::ZXSpectrum),
tape_player_(clock_rate() * 2),
fdc_(clock_rate() * 2)
{
set_clock_rate(clock_rate());
speaker_.set_input_rate(float(clock_rate()) / 2.0f);
// With only the +2a and +3 currently supported, the +3 ROM is always
// the one required.
std::vector<ROMMachine::ROM> rom_names;
const std::string machine = "ZXSpectrum";
switch(model) {
case Model::SixteenK:
case Model::FortyEightK:
rom_names.emplace_back(machine, "the 48kb ROM", "48.rom", 16 * 1024, 0xddee531f);
break;
case Model::OneTwoEightK:
rom_names.emplace_back(machine, "the 128kb ROM", "128.rom", 32 * 1024, 0x2cbe8995);
break;
case Model::Plus2:
rom_names.emplace_back(machine, "the +2 ROM", "plus2.rom", 32 * 1024, 0xe7a517dc);
break;
case Model::Plus2a:
case Model::Plus3: {
const std::initializer_list<uint32_t> crc32s = { 0x96e3c17a, 0xbe0d9ec4 };
rom_names.emplace_back(machine, "the +2a/+3 ROM", "plus3.rom", 64 * 1024, crc32s);
} break;
}
const auto roms = rom_fetcher(rom_names);
if(!roms[0]) throw ROMMachine::Error::MissingROMs;
memcpy(rom_.data(), roms[0]->data(), std::min(rom_.size(), roms[0]->size()));
// Register for sleeping notifications.
tape_player_.set_clocking_hint_observer(this);
// Set up initial memory map.
update_memory_map();
set_video_address();
Memory::Fuzz(ram_);
// Insert media.
insert_media(target.media);
// Possibly depress the enter key.
if(target.should_hold_enter) {
// Hold it for five seconds, more or less.
duration_to_press_enter_ = Cycles(5 * clock_rate());
keyboard_.set_key_state(ZX::Keyboard::KeyEnter, true);
}
}
~ConcreteMachine() {
audio_queue_.flush();
}
static constexpr unsigned int clock_rate() {
constexpr unsigned int OriginalClockRate = 3'500'000;
constexpr unsigned int Plus3ClockRate = 3'546'875; // See notes below; this is a guess.
// Notes on timing for the +2a and +3:
//
// Standard PAL produces 283.7516 colour cycles per line, each line being 64µs.
// The oft-quoted 3.5469 Mhz would seem to imply 227.0016 clock cycles per line.
// Since those Spectrums actually produce 228 cycles per line, but software like
// Chromatrons seems to assume a fixed phase relationship, I guess that the real
// clock speed is whatever gives:
//
// 228 / [cycles per line] * 283.7516 = [an integer].
//
// i.e. 228 * 283.7516 = [an integer] * [cycles per line], such that cycles per line ~= 227
// ... which would imply that 'an integer' is probably 285, i.e.
//
// 228 / [cycles per line] * 283.7516 = 285
// => 227.00128 = [cycles per line]
// => clock rate = 3.546895 Mhz?
//
// That is... unless I'm mistaken about the PAL colour subcarrier and it's actually 283.75,
// which would give exactly 227 cycles/line and therefore 3.546875 Mhz.
//
// A real TV would be likely to accept either, I guess. But it does seem like
// the Spectrum is a PAL machine with a fixed colour phase relationship. For
// this emulator's world, that's a first!
return model < Model::OneTwoEightK ? OriginalClockRate : Plus3ClockRate;
}
// MARK: - TimedMachine.
void run_for(const Cycles cycles) override {
z80_.run_for(cycles);
// Use this very broad timing base for the automatic enter depression.
// It's not worth polluting the main loop.
if(duration_to_press_enter_ > Cycles(0)) {
if(duration_to_press_enter_ < cycles) {
duration_to_press_enter_ = Cycles(0);
keyboard_.set_key_state(ZX::Keyboard::KeyEnter, false);
} else {
duration_to_press_enter_ -= cycles;
}
}
}
void flush() {
video_.flush();
update_audio();
audio_queue_.perform();
if constexpr (model == Model::Plus3) {
fdc_.flush();
}
}
// MARK: - ScanProducer.
void set_scan_target(Outputs::Display::ScanTarget *scan_target) override {
video_->set_scan_target(scan_target);
}
Outputs::Display::ScanStatus get_scaled_scan_status() const override {
return video_->get_scaled_scan_status();
}
void set_display_type(Outputs::Display::DisplayType display_type) override {
video_->set_display_type(display_type);
}
// MARK: - BusHandler.
forceinline HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) {
using PartialMachineCycle = CPU::Z80::PartialMachineCycle;
const uint16_t address = cycle.address ? *cycle.address : 0x0000;
// Apply contention if necessary.
if constexpr (model >= Model::Plus2a) {
// Model applied: the trigger for the ULA inserting a delay is the falling edge
// of MREQ, which is always half a cycle into a read or write.
if(
is_contended_[address >> 14] &&
cycle.operation >= PartialMachineCycle::ReadOpcodeStart &&
cycle.operation <= PartialMachineCycle::WriteStart) {
const HalfCycles delay = video_.last_valid()->access_delay(video_.time_since_flush() + HalfCycles(1));
advance(cycle.length + delay);
return delay;
}
} else {
switch(cycle.operation) {
default:
advance(cycle.length);
return HalfCycles(0);
case CPU::Z80::PartialMachineCycle::InputStart:
case CPU::Z80::PartialMachineCycle::OutputStart: {
// The port address is loaded prior to IOREQ being visible; a contention
// always occurs if it is in the $4000–$8000 range regardless of current
// memory mapping.
HalfCycles delay;
HalfCycles time = video_.time_since_flush() + HalfCycles(1);
if((address & 0xc000) == 0x4000) {
for(int c = 0; c < ((address & 1) ? 4 : 2); c++) {
const auto next_delay = video_.last_valid()->access_delay(time);
delay += next_delay;
time += next_delay + 2;
}
} else {
if(!(address & 1)) {
delay = video_.last_valid()->access_delay(time + HalfCycles(2));
}
}
advance(cycle.length + delay);
return delay;
}
case PartialMachineCycle::ReadOpcodeStart:
case PartialMachineCycle::ReadStart:
case PartialMachineCycle::WriteStart: {
// These all start by loading the address bus, then set MREQ
// half a cycle later.
if(is_contended_[address >> 14]) {
const HalfCycles delay = video_.last_valid()->access_delay(video_.time_since_flush() + HalfCycles(1));
advance(cycle.length + delay);
return delay;
}
}
case PartialMachineCycle::Internal: {
// Whatever's on the address bus will remain there, without IOREQ or
// MREQ interceding, for this entire bus cycle. So apply contentions
// all the way along.
if(is_contended_[address >> 14]) {
const auto half_cycles = cycle.length.as<int>();
assert(!(half_cycles & 1));
HalfCycles time = video_.time_since_flush() + HalfCycles(1);
HalfCycles delay;
for(int c = 0; c < half_cycles; c += 2) {
const auto next_delay = video_.last_valid()->access_delay(time);
delay += next_delay;
time += next_delay + 2;
}
advance(cycle.length + delay);
return delay;
}
}
case CPU::Z80::PartialMachineCycle::Input:
case CPU::Z80::PartialMachineCycle::Output:
case CPU::Z80::PartialMachineCycle::Read:
case CPU::Z80::PartialMachineCycle::Write:
case CPU::Z80::PartialMachineCycle::ReadOpcode:
// For these, carry on into the actual handler, below.
break;
}
}
// For all other machine cycles, model the action as happening at the end of the machine cycle;
// that means advancing time now.
advance(cycle.length);
switch(cycle.operation) {
default: break;
case PartialMachineCycle::ReadOpcode:
// Fast loading: ROM version.
//
// The below patches over part of the 'LD-BYTES' routine from the 48kb ROM.
if(use_fast_tape_hack_ && address == 0x056b && read_pointers_[0] == &rom_[classic_rom_offset()]) {
// Stop pressing enter, if neccessry.
if(duration_to_press_enter_ > Cycles(0)) {
duration_to_press_enter_ = Cycles(0);
keyboard_.set_key_state(ZX::Keyboard::KeyEnter, false);
}
if(perform_rom_ld_bytes_56b()) {
*cycle.value = 0xc9; // i.e. RET.
break;
}
}
case PartialMachineCycle::Read:
if constexpr (model == Model::SixteenK) {
// Assumption: with nothing mapped above 0x8000 on the 16kb Spectrum,
// read the floating bus.
if(address >= 0x8000) {
*cycle.value = video_->get_floating_value();
break;
}
}
*cycle.value = read_pointers_[address >> 14][address];
if constexpr (model >= Model::Plus2a) {
if(is_contended_[address >> 14]) {
video_->set_last_contended_area_access(*cycle.value);
}
}
break;
case PartialMachineCycle::Write:
// Flush video if this access modifies screen contents.
if(is_video_[address >> 14] && (address & 0x3fff) < 6912) {
video_.flush();
}
write_pointers_[address >> 14][address] = *cycle.value;
if constexpr (model >= Model::Plus2a) {
// Fill the floating bus buffer if this write is within the contended area.
if(is_contended_[address >> 14]) {
video_->set_last_contended_area_access(*cycle.value);
}
}
break;
// Partial port decodings here and in ::Input are as documented
// at https://worldofspectrum.org/faq/reference/ports.htm
case PartialMachineCycle::Output:
// Test for port FE.
if(!(address&1)) {
update_audio();
audio_toggle_.set_output(*cycle.value & 0x10);
video_->set_border_colour(*cycle.value & 7);
// b0–b2: border colour
// b3: enable tape input (?)
// b4: tape and speaker output
}
// Test for classic 128kb paging register (i.e. port 7ffd).
if (
(model >= Model::OneTwoEightK && model <= Model::Plus2 && (address & 0x8002) == 0x0000) ||
(model >= Model::Plus2a && (address & 0xc002) == 0x4000)
) {
port7ffd_ = *cycle.value;
update_memory_map();
// Set the proper video base pointer.
set_video_address();
// Potentially lock paging, _after_ the current
// port values have taken effect.
disable_paging_ |= *cycle.value & 0x20;
}
// Test for +2a/+3 paging (i.e. port 1ffd).
if constexpr (model >= Model::Plus2a) {
if((address & 0xf002) == 0x1000) {
port1ffd_ = *cycle.value;
update_memory_map();
update_video_base();
if constexpr (model == Model::Plus3) {
fdc_->set_motor_on(*cycle.value & 0x08);
}
}
}
// Route to the AY if one is fitted.
if constexpr (model >= Model::OneTwoEightK) {
switch(address & 0xc002) {
case 0xc000:
// Select AY register.
update_audio();
GI::AY38910::Utility::select_register(ay_, *cycle.value);
break;
case 0x8000:
// Write to AY register.
update_audio();
GI::AY38910::Utility::write_data(ay_, *cycle.value);
break;
}
}
// Check for FDC accesses.
if constexpr (model == Model::Plus3) {
switch(address & 0xf002) {
default: break;
case 0x3000: case 0x2000:
fdc_->write((address >> 12) & 1, *cycle.value);
break;
}
}
break;
case PartialMachineCycle::Input: {
bool did_match = false;
*cycle.value = 0xff;
if(!(address&1)) {
did_match = true;
// Port FE:
//
// address b8+: mask of keyboard lines to select
// result: b0–b4: mask of keys pressed
// b6: tape input
*cycle.value &= keyboard_.read(address);
*cycle.value &= tape_player_.get_input() ? 0xbf : 0xff;
// If this read is within 200 cycles of the previous,
// count it as an adjacent hit; if 20 of those have
// occurred then start the tape motor.
if(use_automatic_tape_motor_control_) {
if(cycles_since_tape_input_read_ < HalfCycles(400)) {
++recent_tape_hits_;
if(recent_tape_hits_ == 20) {
tape_player_.set_motor_control(true);
}
} else {
recent_tape_hits_ = 0;
}
cycles_since_tape_input_read_ = HalfCycles(0);
}
}
if constexpr (model >= Model::OneTwoEightK) {
if((address & 0xc002) == 0xc000) {
did_match = true;
// Read from AY register.
update_audio();
*cycle.value &= GI::AY38910::Utility::read(ay_);
}
}
if constexpr (model >= Model::Plus2a) {
// Check for a +2a/+3 floating bus read; these are particularly arcane.
// See footnote to https://spectrumforeveryone.com/technical/memory-contention-floating-bus/
// and, much more rigorously, http://sky.relative-path.com/zx/floating_bus.html
if(!disable_paging_ && (address & 0xf003) == 0x0001) {
*cycle.value &= video_->get_floating_value();
}
}
if constexpr (model == Model::Plus3) {
switch(address & 0xf002) {
default: break;
case 0x3000: case 0x2000:
*cycle.value &= fdc_->read((address >> 12) & 1);
break;
}
}
if constexpr (model <= Model::Plus2) {
if(!did_match) {
*cycle.value = video_->get_floating_value();
}
}
} break;
}
return HalfCycles(0);
}
private:
void advance(HalfCycles duration) {
time_since_audio_update_ += duration;
video_ += duration;
if(video_.did_flush()) {
z80_.set_interrupt_line(video_.last_valid()->get_interrupt_line(), video_.last_sequence_point_overrun());
}
if(!tape_player_is_sleeping_) tape_player_.run_for(duration.as_integral());
// Update automatic tape motor control, if enabled; if it's been
// 3 seconds since software last possibly polled the tape, stop it.
if(use_automatic_tape_motor_control_ && cycles_since_tape_input_read_ < HalfCycles(clock_rate() * 6)) {
cycles_since_tape_input_read_ += duration;
if(cycles_since_tape_input_read_ >= HalfCycles(clock_rate() * 6)) {
tape_player_.set_motor_control(false);
recent_tape_hits_ = 0;
}
}
if constexpr (model == Model::Plus3) {
fdc_ += Cycles(duration.as_integral());
}
if(typer_) typer_->run_for(duration);
}
void type_string(const std::string &string) override {
Utility::TypeRecipient<CharacterMapper>::add_typer(string);
}
bool can_type(char c) const override {
return Utility::TypeRecipient<CharacterMapper>::can_type(c);
}
public:
// MARK: - Typer.
HalfCycles get_typer_delay(const std::string &) const override {
return z80_.get_is_resetting() ? Cycles(7'000'000) : Cycles(0);
}
HalfCycles get_typer_frequency() const override{
return Cycles(70'908);
}
KeyboardMapper *get_keyboard_mapper() override {
return &keyboard_mapper_;
}
// MARK: - Keyboard.
void set_key_state(uint16_t key, bool is_pressed) override {
keyboard_.set_key_state(key, is_pressed);
}
void clear_all_keys() override {
keyboard_.clear_all_keys();
// Caveat: if holding enter synthetically, continue to do so.
if(duration_to_press_enter_ > Cycles(0)) {
keyboard_.set_key_state(ZX::Keyboard::KeyEnter, true);
}
}
// MARK: - MediaTarget.
bool insert_media(const Analyser::Static::Media &media) override {
// If there are any tapes supplied, use the first of them.
if(!media.tapes.empty()) {
tape_player_.set_tape(media.tapes.front());
set_use_fast_tape();
}
// Insert up to four disks.
int c = 0;
for(auto &disk : media.disks) {
fdc_->set_disk(disk, c);
c++;
if(c == 4) break;
}
return !media.tapes.empty() || (!media.disks.empty() && model == Model::Plus3);
}
// MARK: - ClockingHint::Observer.
void set_component_prefers_clocking(ClockingHint::Source *, ClockingHint::Preference) override {
tape_player_is_sleeping_ = tape_player_.preferred_clocking() == ClockingHint::Preference::None;
}
// MARK: - Tape control.
void set_use_automatic_tape_motor_control(bool enabled) {
use_automatic_tape_motor_control_ = enabled;
if(!enabled) {
tape_player_.set_motor_control(false);
}
}
void set_tape_is_playing(bool is_playing) final {
tape_player_.set_motor_control(is_playing);
}
bool get_tape_is_playing() final {
return tape_player_.get_motor_control();
}
// MARK: - Configuration options.
std::unique_ptr<Reflection::Struct> get_options() override {
auto options = std::make_unique<Options>(Configurable::OptionsType::UserFriendly); // OptionsType is arbitrary, but not optional.
options->automatic_tape_motor_control = use_automatic_tape_motor_control_;
options->quickload = allow_fast_tape_hack_;
return options;
}
void set_options(const std::unique_ptr<Reflection::Struct> &str) override {
const auto options = dynamic_cast<Options *>(str.get());
set_video_signal_configurable(options->output);
set_use_automatic_tape_motor_control(options->automatic_tape_motor_control);
allow_fast_tape_hack_ = options->quickload;
set_use_fast_tape();
}
// MARK: - AudioProducer.
Outputs::Speaker::Speaker *get_speaker() override {
return &speaker_;
}
// MARK: - Activity Source.
void set_activity_observer(Activity::Observer *observer) override {
if constexpr (model == Model::Plus3) fdc_->set_activity_observer(observer);
tape_player_.set_activity_observer(observer);
}
private:
CPU::Z80::Processor<ConcreteMachine, false, false> z80_;
// MARK: - Memory.
std::array<uint8_t, 64*1024> rom_;
std::array<uint8_t, 128*1024> ram_;
std::array<uint8_t, 16*1024> scratch_;
const uint8_t *read_pointers_[4];
uint8_t *write_pointers_[4];
uint8_t pages_[4];
bool is_contended_[4];
bool is_video_[4];
uint8_t port1ffd_ = 0;
uint8_t port7ffd_ = 0;
bool disable_paging_ = false;
void update_memory_map() {
// If paging is permanently disabled, don't react.
if(disable_paging_) {
return;
}
if(port1ffd_ & 0x01) {
// "Special paging mode", i.e. one of four fixed
// RAM configurations, port 7ffd doesn't matter.
switch(port1ffd_ & 0x06) {
default:
case 0x00:
set_memory(0, 0);
set_memory(1, 1);
set_memory(2, 2);
set_memory(3, 3);
break;
case 0x02:
set_memory(0, 4);
set_memory(1, 5);
set_memory(2, 6);
set_memory(3, 7);
break;
case 0x04:
set_memory(0, 4);
set_memory(1, 5);
set_memory(2, 6);
set_memory(3, 3);
break;
case 0x06:
set_memory(0, 4);
set_memory(1, 7);
set_memory(2, 6);
set_memory(3, 3);
break;
}
} else {
// Apply standard 128kb-esque mapping (albeit with extra ROM to pick from).
set_memory(0, 0x80 | ((port1ffd_ >> 1) & 2) | ((port7ffd_ >> 4) & 1));
set_memory(1, 5);
set_memory(2, 2);
set_memory(3, port7ffd_ & 7);
}
}
void set_memory(int bank, uint8_t source) {
if constexpr (model >= Model::Plus2a) {
is_contended_[bank] = (source >= 4 && source < 8);
} else {
is_contended_[bank] = source & 1;
}
pages_[bank] = source;
uint8_t *const read = (source < 0x80) ? &ram_[source * 16384] : &rom_[(source & 0x7f) * 16384];
const auto offset = bank*16384;
read_pointers_[bank] = read - offset;
write_pointers_[bank] = ((source < 0x80) ? read : scratch_.data()) - offset;
}
void set_video_address() {
video_->set_video_source(&ram_[((port7ffd_ & 0x08) ? 7 : 5) * 16384]);
update_video_base();
}
void update_video_base() {
const uint8_t video_page = (port7ffd_ & 0x08) ? 7 : 5;
is_video_[0] = pages_[0] == video_page;
is_video_[1] = pages_[1] == video_page;
is_video_[2] = pages_[2] == video_page;
is_video_[3] = pages_[3] == video_page;
}
// MARK: - Audio.
Concurrency::DeferringAsyncTaskQueue audio_queue_;
GI::AY38910::AY38910<false> ay_;
Audio::Toggle audio_toggle_;
Outputs::Speaker::CompoundSource<GI::AY38910::AY38910<false>, Audio::Toggle> mixer_;
Outputs::Speaker::LowpassSpeaker<Outputs::Speaker::CompoundSource<GI::AY38910::AY38910<false>, Audio::Toggle>> speaker_;
HalfCycles time_since_audio_update_;
void update_audio() {
speaker_.run_for(audio_queue_, time_since_audio_update_.divide_cycles(Cycles(2)));
}
// MARK: - Video.
using VideoType =
std::conditional_t<
model <= Model::FortyEightK, Video<VideoTiming::FortyEightK>,
std::conditional_t<
model <= Model::Plus2, Video<VideoTiming::OneTwoEightK>,
Video<VideoTiming::Plus3>
>
>;
JustInTimeActor<VideoType> video_;
// MARK: - Keyboard.
Sinclair::ZX::Keyboard::Keyboard keyboard_;
Sinclair::ZX::Keyboard::KeyboardMapper keyboard_mapper_;
// MARK: - Tape.
Storage::Tape::BinaryTapePlayer tape_player_;
bool tape_player_is_sleeping_ = false;
bool use_automatic_tape_motor_control_ = true;
HalfCycles cycles_since_tape_input_read_;
int recent_tape_hits_ = 0;
bool allow_fast_tape_hack_ = false;
bool use_fast_tape_hack_ = false;
void set_use_fast_tape() {
use_fast_tape_hack_ = allow_fast_tape_hack_ && tape_player_.has_tape();
}
// Reimplements the 'LD-BYTES' routine, as documented at
// https://skoolkid.github.io/rom/asm/0556.html but picking
// up from address 56b i.e.
//
// In:
// A': 0x00 or 0xff for block type;
// F': carry set if loading, clear if verifying;
// DE: block length;
// IX: start address.
//
// Out:
// F: carry set for success, clear for error.
//
// And, empirically:
// IX: one beyond final address written;
// DE: 0;
// L: parity byte;
// H: 0 for no error, 0xff for error;
// A: same as H.
// BC: ???
bool perform_rom_ld_bytes_56b() {
using Parser = Storage::Tape::ZXSpectrum::Parser;
Parser parser(Parser::MachineType::ZXSpectrum);
using Register = CPU::Z80::Register;
uint8_t flags = uint8_t(z80_.get_value_of_register(Register::FlagsDash));
if(!(flags & 1)) return false;
const uint8_t block_type = uint8_t(z80_.get_value_of_register(Register::ADash));
const auto block = parser.find_block(tape_player_.get_tape());
if(!block || block_type != (*block).type) return false;
uint16_t length = z80_.get_value_of_register(Register::DE);
uint16_t target = z80_.get_value_of_register(Register::IX);
flags = 0x93;
uint8_t parity = 0x00;
while(length--) {
auto next = parser.get_byte(tape_player_.get_tape());
if(!next) {
flags &= ~1;
break;
}
write_pointers_[target >> 14][target] = *next;
parity ^= *next;
++target;
}
auto stored_parity = parser.get_byte(tape_player_.get_tape());
if(!stored_parity) {
flags &= ~1;
} else {
z80_.set_value_of_register(Register::L, *stored_parity);
}
z80_.set_value_of_register(Register::Flags, flags);
z80_.set_value_of_register(Register::DE, length);
z80_.set_value_of_register(Register::IX, target);
const uint8_t h = (flags & 1) ? 0x00 : 0xff;
z80_.set_value_of_register(Register::H, h);
z80_.set_value_of_register(Register::A, h);
return true;
}
static constexpr int classic_rom_offset() {
switch(model) {
case Model::SixteenK:
case Model::FortyEightK:
return 0x0000;
case Model::OneTwoEightK:
case Model::Plus2:
return 0x4000;
case Model::Plus2a:
case Model::Plus3:
return 0xc000;
}
}
// MARK: - Disc.
JustInTimeActor<Amstrad::FDC, Cycles> fdc_;
// MARK: - Automatic startup.
Cycles duration_to_press_enter_;
};
}
}
using namespace Sinclair::ZXSpectrum;
Machine *Machine::ZXSpectrum(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) {
const auto zx_target = dynamic_cast<const Analyser::Static::ZXSpectrum::Target *>(target);
switch(zx_target->model) {
case Model::SixteenK: return new ConcreteMachine<Model::SixteenK>(*zx_target, rom_fetcher);
case Model::FortyEightK: return new ConcreteMachine<Model::FortyEightK>(*zx_target, rom_fetcher);
case Model::OneTwoEightK: return new ConcreteMachine<Model::OneTwoEightK>(*zx_target, rom_fetcher);
case Model::Plus2: return new ConcreteMachine<Model::Plus2>(*zx_target, rom_fetcher);
case Model::Plus2a: return new ConcreteMachine<Model::Plus2a>(*zx_target, rom_fetcher);
case Model::Plus3: return new ConcreteMachine<Model::Plus3>(*zx_target, rom_fetcher);
}
return nullptr;
}
Machine::~Machine() {}
|
#include<iostream>
#include<cstring>
#define FOR(i,n) for(i=0;i<n;i++)
#define MAX(a,b) (a)>(b)?(a):(b)
using namespace std;
long long A[21][21][21];
long long calcsum(int i,int l,int j,int m, int k)
{
long long s=0;
s=A[l][m][k];
if(i>0)s-=A[i-1][m][k];
if(j>0)s-=A[l][j-1][k];
if(i>0&&j>0)s+=A[i-1][j-1][k];
return s;
}
int main()
{
long long in[21][21][21],a,b,c,t,i,j,k,l,m,n,sum,ans;
cin>>t;
while(t--)
{
cin>>a>>b>>c;
FOR(i,a)
FOR(j,b)
FOR(k,c)
cin>>in[i][j][k];
FOR(i,c)
FOR(j,a)
FOR(k,b)
FOR(l,a)
FOR(m,b)
{
A[j][k][i]=in[j][k][i];
if(j>0)A[j][k][i]+=A[j-1][k][i];
if(k>0)A[j][k][i]+=A[j][k-1][i];
if(j>0&&k>0)A[j][k][i]-=A[j-1][k-1][i];
}
ans=-858993459200;
FOR(i,a)
FOR(j,b)
for(l=i;l<a;l++)
for(m=j;m<b;m++)
{
sum=0;
for(k=0;k<c;k++)
{
sum+=calcsum(i,l,j,m,k);
ans=MAX(sum,ans);
if(sum<0)sum=0;
}
}
cout<<ans<<endl;
if(t)cout<<endl;
}
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
char s[22][22];
char mon[22][22];
int res[21][21][21][21];
int cnt = 0, step = 100000, nxt = step;
int solve(int r1, int c1, int r2, int c2) {
int ans = res[r1][c1][r2][c2];
if (ans != -1) return ans;
cerr << r1 << " " << c1 << " " << r2 << " " << c2 << endl;
if (++cnt == nxt) {
cerr << cnt << endl;
nxt += step;
}
vector<int> v;
for (int i = r1; i <= r2; ++i) {
for (int j = c1; j <= c2; ++j) {
if (mon[i][j]) {
v.push_back( solve(r1, c1, i - 1, j - 1) ^
solve(r1, j + 1 , i - 1, c2) ^
solve(i + 1, c1, r2, j - 1) ^
solve(i + 1, j + 1, r2, c2)
);
}
}
}
ans = 0;
sort(v.begin(), v.end());
for (int i = 0; i < v.size();)
if (ans == v[i])
++ans;
else
if (ans > v[i])
++i;
else
break;
return ans;
}
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
int T;
scanf("%d", &T);
while (T--) {
int n, m;
scanf("%d%d\n", &n, &m);
for (int i = 0; i < n; ++i) {
gets(s[i]);
}
memset(mon, 0, sizeof(mon));
memset(res, -1, sizeof(res));
for (int i = 2; i < n - 2; ++i) {
for (int j = 2; j < m - 2; ++j) {
if (s[i][j] == '^' &&
s[i + 1][j] == '^' && s[i + 2][j] == '^' &&
s[i - 1][j] == '^' && s[i - 2][j] == '^' &&
s[i][j + 1] == '^' && s[i][j + 2] == '^' &&
s[i][j - 1] == '^' && s[i][j - 2] == '^'
)
{
mon[i][j] = true;
}
}
}
cout << (solve(0, 0, n - 1, m - 1) ? "Asuna": "Kirito") << endl;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2009 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"
#include "modules/display/vis_dev.h"
#ifdef VEGA_OPPAINTER_SUPPORT /* Implied by CSS_TRANSFORMS */
#include "modules/libvega/src/oppainter/vegaoppainter.h"
#endif // VEGA_OPPAINTER_SUPPORT
// AffineTransform
#ifdef CSS_TRANSFORMS
BOOL AffineTransform::operator==(const AffineTransform &trfm) const
{
return
values[0] == trfm[0] && values[1] == trfm[1] &&
values[2] == trfm[2] && values[3] == trfm[3] &&
values[4] == trfm[4] && values[5] == trfm[5];
}
#ifdef SELFTEST
BOOL AffineTransform::IsEqual(const AffineTransform &trfm, float eps) const
{
#define FLT_IS_CLOSE(a,b) (op_fabs((a)-(b)) < eps)
return
FLT_IS_CLOSE(values[0], trfm[0]) && FLT_IS_CLOSE(values[1], trfm[1]) &&
FLT_IS_CLOSE(values[2], trfm[2]) && FLT_IS_CLOSE(values[3], trfm[3]) &&
FLT_IS_CLOSE(values[4], trfm[4]) && FLT_IS_CLOSE(values[5], trfm[5]);
#undef FLT_IS_CLOSE
}
#endif // SELFTEST
void AffineTransform::LoadIdentity()
{
values[1] = values[2] = values[3] = values[5] = 0.0f;
values[0] = values[4] = 1.0f;
}
// load(a, b, c, d, e, f) = [a b c; d e f]
void AffineTransform::LoadValues(float a, float b, float c, float d, float e, float f)
{
values[0] = a;
values[1] = b;
values[2] = c;
values[3] = d;
values[4] = e;
values[5] = f;
}
// translate(tx, ty) = [1 0 tx; 0 1 ty]
void AffineTransform::LoadTranslate(float tx, float ty)
{
values[0] = values[4] = 1.0f;
values[1] = values[3] = 0.0f;
values[2] = tx;
values[5] = ty;
}
// scale(sx, sy) = [sx 0 0; 0 sy 0]
void AffineTransform::LoadScale(float sx, float sy)
{
values[1] = values[2] = values[3] = values[5] = 0.0f;
values[0] = sx;
values[4] = sy;
}
// rotate(a) = [cos(a) -sin(a) 0; sin(a) cos(a) 0]
void AffineTransform::LoadRotate(float angle)
{
float sin_a = (float)op_sin(angle);
float cos_a = (float)op_cos(angle);
values[0] = cos_a;
values[1] = -sin_a;
values[3] = sin_a;
values[4] = cos_a;
values[2] = values[5] = 0.0f;
}
// skew(anglex, angley) = [1 tan(anglex) 0; tan(angley) 1 0]
//
// (the way webkit seems to do it; thus:
// skewX(anglex) = skew(anglex, 0) and
// skewY(angley) = skew(0, angley))
void AffineTransform::LoadSkew(float anglex, float angley)
{
values[1] = (float)op_tan(anglex);
values[3] = (float)op_tan(angley);
values[0] = values[4] = 1.0f;
values[2] = values[5] = 0.0f;
}
//
// Decomposition as required by CSS3 transforms.
//
// Based on:
// Thomas, Spencer W., Decomposing a Matrix Into Simple Transformations, Graphics Gems II, p. 320-323
// http://tog.acm.org/GraphicsGems/gemsii/unmatrix.c
//
BOOL AffineTransform::Decompose(Decomposition& d) const
{
if (Determinant() == 0.0f)
return FALSE;
// Get translation
d.tx = values[2];
d.ty = values[5];
float r0_x = values[0];
float r0_y = values[3];
float r1_x = values[1];
float r1_y = values[4];
// Calculate X-scale
d.sx = (float)op_sqrt(r0_x * r0_x + r0_y * r0_y);
if (d.sx != 0.0f) // Can this actually be zero-length?
{
r0_x /= d.sx;
r0_y /= d.sx;
}
// Calculate shear/skew
d.shear = r0_x * r1_x + r0_y * r1_y;
r1_x = r1_x + r0_x * (-d.shear);
r1_y = r1_y + r0_y * (-d.shear);
// Calculate Y-scale
d.sy = (float)op_sqrt(r1_x * r1_x + r1_y * r1_y);
if (d.sy != 0.0f) // Can this actually be zero-length?
{
r1_x /= d.sy;
r1_y /= d.sy;
}
d.shear /= d.sy;
OP_ASSERT(op_fabs(r0_x * r1_x + r0_y * r1_y) < 1e-8);
// Need to flip?
if (r0_x * r1_y - r0_y * r1_x < 0)
{
d.sx = -d.sx, d.sy = -d.sy;
r0_x = -r0_x, r0_y = -r0_y;
r1_x = -r1_x, r1_y = -r1_y;
}
// Calculate rotation
d.rotate = (float)op_atan2(r0_y, r0_x);
return TRUE;
}
// Compose a matrix from a 'decomposition' (In the order: T * R * Sh * S)
void AffineTransform::Compose(const Decomposition& d)
{
// T * R => [ 1 0 tx; 0 1 ty ] * [ c -s 0; s c 0 ] => [ c -s tx; s c ty ]
LoadRotate(d.rotate);
values[2] = d.tx;
values[5] = d.ty;
// (T * R) * Sh => [ a b c; d e f ] * [ 1 sh 0; 0 1 0 ] => [ a sh*a+b c; d sh*d+e f ]
values[1] += values[0] * d.shear;
values[4] += values[3] * d.shear;
// (T * R * Sh) * S => [ a b c; d e f ] * [ sx 0 0; 0 sy 0 ] => [ sx*a sy*b c; sx*d sy*e f ]
values[0] *= d.sx;
values[3] *= d.sx;
values[1] *= d.sy;
values[4] *= d.sy;
}
float AffineTransform::Determinant() const
{
return values[0] * values[4] - values[1] * values[3];
}
BOOL AffineTransform::Invert()
{
float det = Determinant();
if (det == 0.0f)
return FALSE;
AffineTransform t = *this;
values[0] = t.values[4] / det;
values[1] = -t.values[1] / det;
values[2] = (t.values[1] * t.values[5] - t.values[4] * t.values[2]) / det;
values[3] = -t.values[3] / det;
values[4] = t.values[0] / det;
values[5] = -(t.values[0] * t.values[5] - t.values[3] * t.values[2]) / det;
return TRUE;
}
void AffineTransform::PostTranslate(float tx, float ty)
{
values[2] += tx * values[0] + ty * values[1];
values[5] += tx * values[3] + ty * values[4];
}
void AffineTransform::PostMultiply(const AffineTransform& mat)
{
float m00 = values[0] * mat.values[0] + values[1] * mat.values[3];
float m01 = values[0] * mat.values[1] + values[1] * mat.values[4];
values[2] = values[0] * mat.values[2] + values[1] * mat.values[5] + values[2];
values[0] = m00;
values[1] = m01;
float m10 = values[3] * mat.values[0] + values[4] * mat.values[3];
float m11 = values[3] * mat.values[1] + values[4] * mat.values[4];
values[5] = values[3] * mat.values[2] + values[4] * mat.values[5] + values[5];
values[3] = m10;
values[4] = m11;
}
void AffineTransform::TransformPoint(const OpPoint& p, float& out_x, float& out_y) const
{
out_x = values[0] * p.x + values[1] * p.y + values[2];
out_y = values[3] * p.x + values[4] * p.y + values[5];
}
OpPoint AffineTransform::TransformPoint(const OpPoint& p) const
{
float vx, vy;
TransformPoint(p, vx, vy);
return OpPoint((int)vx, (int)vy);
}
OpRect AffineTransform::GetTransformedBBox(const OpRect& in_r) const
{
float minx, miny;
TransformPoint(in_r.TopLeft(), minx, miny);
float maxx = minx, maxy = miny, x, y;
TransformPoint(in_r.TopRight(), x, y);
minx = MIN(minx, x); miny = MIN(miny, y);
maxx = MAX(maxx, x); maxy = MAX(maxy, y);
TransformPoint(in_r.BottomRight(), x, y);
minx = MIN(minx, x); miny = MIN(miny, y);
maxx = MAX(maxx, x); maxy = MAX(maxy, y);
TransformPoint(in_r.BottomLeft(), x, y);
minx = MIN(minx, x); miny = MIN(miny, y);
maxx = MAX(maxx, x); maxy = MAX(maxy, y);
OpRect out_r;
out_r.x = (int)op_floor(minx);
out_r.y = (int)op_floor(miny);
out_r.width = (int)op_ceil(maxx) - out_r.x;
out_r.height = (int)op_ceil(maxy) - out_r.y;
return out_r;
}
RECT AffineTransform::GetTransformedBBox(const RECT& in_r) const
{
float minx, miny;
TransformPoint(OpPoint(in_r.left, in_r.top), minx, miny);
float maxx = minx, maxy = miny, x, y;
TransformPoint(OpPoint(in_r.right, in_r.top), x, y);
minx = MIN(minx, x); miny = MIN(miny, y);
maxx = MAX(maxx, x); maxy = MAX(maxy, y);
TransformPoint(OpPoint(in_r.right, in_r.bottom), x, y);
minx = MIN(minx, x); miny = MIN(miny, y);
maxx = MAX(maxx, x); maxy = MAX(maxy, y);
TransformPoint(OpPoint(in_r.left, in_r.bottom), x, y);
minx = MIN(minx, x); miny = MIN(miny, y);
maxx = MAX(maxx, x); maxy = MAX(maxy, y);
RECT out_r;
out_r.left = (int)op_floor(minx);
out_r.top = (int)op_floor(miny);
out_r.right = (int)op_ceil(maxx);
out_r.bottom = (int)op_ceil(maxy);
return out_r;
}
VEGATransform AffineTransform::ToVEGATransform() const
{
VEGATransform vtrans;
vtrans[0] = VEGA_FLTTOFIX(values[0]);
vtrans[1] = VEGA_FLTTOFIX(values[1]);
vtrans[2] = VEGA_FLTTOFIX(values[2]);
vtrans[3] = VEGA_FLTTOFIX(values[3]);
vtrans[4] = VEGA_FLTTOFIX(values[4]);
vtrans[5] = VEGA_FLTTOFIX(values[5]);
return vtrans;
}
// == Transform handling ===========================================
OP_STATUS VisualDeviceTransform::PushTransform(const AffineTransform& afftrans)
{
const AffineTransform* prev = GetCurrentTransform();
if (!transform_stack || transform_stack->count == TransformStack::BLOCK_SIZE)
{
// Create new block
TransformStack* new_block = OP_NEW(TransformStack, ());
if (!new_block)
return OpStatus::ERR_NO_MEMORY;
new_block->count = 0;
new_block->next = transform_stack;
transform_stack = new_block;
}
transform_stack->count++;
AffineTransform* curr = GetCurrentTransform();
if (prev)
{
*curr = *prev;
}
else
{
curr->LoadTranslate((float)translation_x, (float)translation_y);
}
curr->PostMultiply(afftrans);
return OpStatus::OK;
}
void VisualDeviceTransform::PopTransform()
{
OP_ASSERT(transform_stack); // This would indicate unbalanced Push/Pop
if (!transform_stack)
return;
OP_ASSERT(transform_stack->count > 0);
if (--transform_stack->count == 0)
{
TransformStack* ts = transform_stack;
transform_stack = transform_stack->next;
OP_DELETE(ts);
}
}
// Base = T(offset) * T(scaled_scroll_ofs) * S(zoom) | offset_transform * T(scroll_ofs)
AffineTransform VisualDevice::GetBaseTransform()
{
AffineTransform base;
if (!offset_transform_is_set)
{
base.LoadIdentity();
if (IsScaled())
base[0] = base[4] = (float)scale_multiplier / scale_divider;
base[2] = (float)(offset_x - view_x_scaled);
base[5] = (float)(offset_y - view_y_scaled);
}
else
{
base = offset_transform;
base.PostTranslate((float)-rendering_viewport.x, (float)-rendering_viewport.y);
}
return base;
}
VDStateTransformed VisualDevice::EnterTransformMode()
{
vd_screen_ctm = GetBaseTransform();
// Flush backgrounds
bg_cs.FlushAll(this);
// Invalidate current font
logfont.SetChanged();
return BeginTransformedPainting();
}
void VisualDevice::LeaveTransformMode()
{
if (painter)
{
VEGAOpPainter* vpainter = static_cast<VEGAOpPainter*>(painter);
vpainter->ClearTransform();
}
// Invalidate current font
logfont.SetChanged();
EndTransformedPainting(untransformed_state);
}
void VisualDevice::UpdatePainterTransform(const AffineTransform& at)
{
OP_ASSERT(painter);
AffineTransform screen_ctm = vd_screen_ctm;
screen_ctm.PostMultiply(at);
VEGAOpPainter* vpainter = static_cast<VEGAOpPainter*>(painter);
vpainter->SetTransform(screen_ctm.ToVEGATransform());
}
OP_STATUS VisualDevice::PushTransform(const AffineTransform& afftrans)
{
BOOL had_transform = HasTransform();
RETURN_IF_ERROR(VisualDeviceTransform::PushTransform(afftrans));
if (!had_transform)
untransformed_state = EnterTransformMode();
if (painter)
UpdatePainterTransform(*GetCurrentTransform());
return OpStatus::OK;
}
void VisualDevice::AppendTranslation(int tx, int ty)
{
VisualDeviceTransform::AppendTranslation(tx, ty);
if (painter)
UpdatePainterTransform(*GetCurrentTransform());
}
void VisualDevice::PopTransform()
{
VisualDeviceTransform::PopTransform();
if (!HasTransform())
LeaveTransformMode();
else if (painter)
UpdatePainterTransform(*GetCurrentTransform());
}
#endif // CSS_TRANSFORMS
VDCTMState VisualDeviceTransform::SaveCTM()
{
VDCTMState saved;
saved.translation_x = translation_x;
saved.translation_y = translation_y;
#ifdef CSS_TRANSFORMS
saved.transform_stack = transform_stack;
transform_stack = NULL;
#endif // CSS_TRANSFORMS
translation_x = 0;
translation_y = 0;
return saved;
}
void VisualDeviceTransform::RestoreCTM(const VDCTMState& state)
{
#ifdef CSS_TRANSFORMS
if (HasTransform())
{
PopTransform();
// This assumes that you did what you should, and popped
// everything you pushed.
OP_ASSERT(!HasTransform());
}
transform_stack = state.transform_stack;
#endif // CSS_TRANSFORMS
translation_x = state.translation_x;
translation_y = state.translation_y;
}
VDCTMState VisualDevice::SaveCTM()
{
VDCTMState saved;
saved.translation_x = translation_x;
saved.translation_y = translation_y;
#ifdef CSS_TRANSFORMS
saved.transform_stack = transform_stack;
transform_stack = NULL;
if (saved.transform_stack)
LeaveTransformMode();
#endif // CSS_TRANSFORMS
translation_x = 0;
translation_y = 0;
return saved;
}
void VisualDevice::RestoreCTM(const VDCTMState& state)
{
#ifdef CSS_TRANSFORMS
if (HasTransform())
{
PopTransform();
// This assumes that you did what you should, and popped
// everything you pushed.
OP_ASSERT(!HasTransform());
}
if (state.transform_stack)
{
EnterTransformMode();
UpdatePainterTransform(state.transform_stack->Top());
}
transform_stack = state.transform_stack;
#endif // CSS_TRANSFORMS
translation_x = state.translation_x;
translation_y = state.translation_y;
}
BOOL VisualDeviceTransform::TestIntersection(const RECT& lrect, const OpPoint& p) const
{
OpPoint doc_p = p;
if (actual_viewport)
{
doc_p.x += actual_viewport->x;
doc_p.y += actual_viewport->y;
}
#ifdef CSS_TRANSFORMS
if (HasTransform())
return TestIntersectionTransformed(lrect, doc_p);
#endif // CSS_TRANSFORMS
if (lrect.left != LONG_MIN && doc_p.x - translation_x < lrect.left)
return FALSE;
if (lrect.top != LONG_MIN && doc_p.y - translation_y < lrect.top)
return FALSE;
if (lrect.right != LONG_MAX && doc_p.x - translation_x >= lrect.right)
return FALSE;
if (lrect.bottom != LONG_MAX && doc_p.y - translation_y >= lrect.bottom)
return FALSE;
return TRUE;
}
BOOL VisualDeviceTransform::TestIntersection(const RECT& lrect, const RECT& rect) const
{
RECT doc_rect = rect;
if (actual_viewport)
{
doc_rect.left += actual_viewport->x;
doc_rect.right += actual_viewport->x;
doc_rect.top += actual_viewport->y;
doc_rect.bottom += actual_viewport->y;
}
#ifdef CSS_TRANSFORMS
if (HasTransform())
return TestIntersectionTransformed(lrect, doc_rect);
#endif // CSS_TRANSFORMS
// Horizontal extents
if (lrect.left != LONG_MIN &&
doc_rect.right <= lrect.left + translation_x)
return FALSE;
if (lrect.right != LONG_MAX &&
doc_rect.left >= lrect.right + translation_x)
return FALSE;
// Vertical extents
if (lrect.top != LONG_MIN &&
doc_rect.bottom <= lrect.top + translation_y)
return FALSE;
if (lrect.bottom != LONG_MAX &&
doc_rect.top >= lrect.bottom + translation_y)
return FALSE;
return TRUE;
}
BOOL VisualDeviceTransform::TestInclusion(const OpRect& lrect, const AffinePos* transform, const OpRect& rect, OpRect* translated_lrect_ptr /*= NULL*/) const
{
//Compute the total translation or transformation matrix from lrect to rect
AffinePos total_transformation = GetCTM();
if (transform)
{
AffinePos transform_inv = *transform;
if (!transform_inv.Invert())
return FALSE;
total_transformation.Prepend(transform_inv);
}
#ifdef CSS_TRANSFORMS
if (total_transformation.IsTransform() && !total_transformation.GetTransform().IsNonSkewing())
return TestInclusionTransformed(lrect, total_transformation.GetTransform(), rect);
#endif // CSS_TRANSFORMS
// Simpler way, when we know, that transformed lrect is still a rectangle with the edges parallel to the axes
OpRect translated_lrect = lrect;
total_transformation.Apply(translated_lrect);
if (translated_lrect.Contains(rect))
return TRUE;
if (translated_lrect_ptr)
*translated_lrect_ptr = translated_lrect;
return FALSE;
}
BOOL
VisualDeviceTransform::TestInclusionOfLocal(const OpRect& lrect, const AffinePos* transform, const OpRect& rect) const
{
//Compute the total translation or transformation matrix from rect to lrect
AffinePos total_transformation = GetCTM();
if (!total_transformation.Invert())
return FALSE;
if (transform)
total_transformation.Append(*transform);
#ifdef CSS_TRANSFORMS
if (total_transformation.IsTransform() && !total_transformation.GetTransform().IsNonSkewing())
return TestInclusionTransformed(rect, total_transformation.GetTransform(), lrect);
#endif // CSS_TRANSFORMS
// Simpler way, when we know, that transformed rect is still a rectangle with the edges parallel to the axes
OpRect translated_rect = rect;
total_transformation.Apply(translated_rect);
return translated_rect.Contains(lrect);
}
#ifdef CSS_TRANSFORMS
static inline BOOL VectorProductPosZTest(float ox, float oy, float dx, float dy, BOOL include_parallel)
{
// o x d
float vector_prod_z = ox * dy - oy * dx;
return include_parallel ? vector_prod_z >= 0 : vector_prod_z > 0;
}
static BOOL IsRectInPosHalfSpace(float ox, float oy, float dx, float dy, const RECT& r, BOOL include_parallel)
{
float oy_top = r.top != LONG_MIN ? r.top - oy : r.top;
float ox_left = r.left != LONG_MIN ? r.left - ox : r.left;
if (!VectorProductPosZTest(ox_left, oy_top, dx, dy, include_parallel))
{
float ox_right = r.right != LONG_MAX ? r.right - 1 - ox : r.right;
if (!VectorProductPosZTest(ox_right, oy_top, dx, dy, include_parallel))
{
float oy_bottom = r.bottom != LONG_MAX ? r.bottom - 1 - oy : r.bottom;
return VectorProductPosZTest(ox_right, oy_bottom, dx, dy, include_parallel) ||
VectorProductPosZTest(ox_left, oy_bottom, dx, dy, include_parallel);
}
}
return TRUE;
}
static BOOL IsRectFullyInPosHalfSpace(float ox, float oy, float dx, float dy, const OpRect& r, BOOL include_parallel)
{
float oy_top = r.Top() - oy;
float ox_left = r.Left() - ox;
if (VectorProductPosZTest(ox_left, oy_top, dx, dy, include_parallel))
{
float ox_right = r.Right() - 1 - ox;
if (VectorProductPosZTest(ox_right, oy_top, dx, dy, include_parallel))
{
float oy_bottom = r.Bottom() - 1 - oy;
return VectorProductPosZTest(ox_right, oy_bottom, dx, dy, include_parallel) &&
VectorProductPosZTest(ox_left, oy_bottom, dx, dy, include_parallel);
}
}
return FALSE;
}
BOOL VisualDeviceTransform::TestIntersectionTransformed(const RECT& lrect, const OpPoint& doc_p) const
{
const AffineTransform& aff = *GetCurrentTransform();
float det = aff.Determinant();
if (det == 0.0f)
return FALSE;
float c0_x = aff[0], c0_y = aff[3];
float c1_x = aff[1], c1_y = aff[4];
if (det < 0)
{
// Flip
c1_x = -c1_x, c1_y = -c1_y;
c0_x = -c0_x, c0_y = -c0_y;
}
if (lrect.left != LONG_MIN && !VectorProductPosZTest(doc_p.x - (lrect.left * aff[0] + aff[2]),
doc_p.y - (lrect.left * aff[3] + aff[5]),
c1_x, c1_y, TRUE))
return FALSE;
if (lrect.top != LONG_MIN && !VectorProductPosZTest(doc_p.x - (lrect.top * aff[1] + aff[2]),
doc_p.y - (lrect.top * aff[4] + aff[5]),
-c0_x, -c0_y, TRUE))
return FALSE;
if (lrect.right != LONG_MAX && !VectorProductPosZTest(doc_p.x - (lrect.right * aff[0] + aff[2]),
doc_p.y - (lrect.right * aff[3] + aff[5]),
-c1_x, -c1_y, FALSE))
return FALSE;
if (lrect.bottom != LONG_MAX && !VectorProductPosZTest(doc_p.x - (lrect.bottom * aff[1] + aff[2]),
doc_p.y - (lrect.bottom * aff[4] + aff[5]),
c0_x, c0_y, FALSE))
return FALSE;
return TRUE;
}
BOOL VisualDeviceTransform::TestIntersectionTransformed(const RECT& lrect, const RECT& doc_rect) const
{
const AffineTransform& aff = *GetCurrentTransform();
BOOL inverse_halfplanes_check;
if (lrect.left != LONG_MIN && lrect.top != LONG_MIN &&
lrect.right != LONG_MAX && lrect.bottom != LONG_MAX)
{
RECT lrect_in_doc = aff.GetTransformedBBox(lrect);
/** First check the intersection of doc_rect against the BBox of lrect.
If it fails we're done. If not, go to the halfplanes method (instead of checking
the intersection of lrect against the BBox of doc_rect, which would require
inverse calculation. */
if (lrect_in_doc.left >= doc_rect.right || lrect_in_doc.right <= doc_rect.left ||
lrect_in_doc.top >= doc_rect.bottom || lrect_in_doc.bottom <= doc_rect.top)
return FALSE;
inverse_halfplanes_check = FALSE;
}
else
/** First check the doc_rect against the halfplanes derived from lrect.
If that does not eliminate the possibility of an intersection,
then we need to calculate the inverse and check lrect against the halfplanes derived from doc_rect. */
inverse_halfplanes_check = TRUE;
float det = aff.Determinant();
if (det == 0.0f)
return FALSE;
float c0_x = aff[0], c0_y = aff[3];
float c1_x = aff[1], c1_y = aff[4];
if (det < 0)
{
// Flip
c1_x = -c1_x, c1_y = -c1_y;
c0_x = -c0_x, c0_y = -c0_y;
}
if (lrect.left != LONG_MIN && !IsRectInPosHalfSpace(lrect.left * aff[0] + aff[2],
lrect.left * aff[3] + aff[5],
c1_x, c1_y, doc_rect, TRUE))
return FALSE;
if (lrect.top != LONG_MIN && !IsRectInPosHalfSpace(lrect.top * aff[1] + aff[2],
lrect.top * aff[4] + aff[5],
-c0_x, -c0_y, doc_rect, TRUE))
return FALSE;
if (lrect.right != LONG_MAX && !IsRectInPosHalfSpace(lrect.right * aff[0] + aff[2],
lrect.right * aff[3] + aff[5],
-c1_x, -c1_y, doc_rect, FALSE))
return FALSE;
if (lrect.bottom != LONG_MAX && !IsRectInPosHalfSpace(lrect.bottom * aff[1] + aff[2],
lrect.bottom * aff[4] + aff[5],
c0_x, c0_y, doc_rect, FALSE))
return FALSE;
if (inverse_halfplanes_check)
{
AffineTransform inverted = aff;
inverted.Invert();
float c0_x = inverted[0], c0_y = inverted[3];
float c1_x = inverted[1], c1_y = inverted[4];
if (det < 0) //det_inv = 1 / det, keeps the sign
{
// Flip
c1_x = -c1_x, c1_y = -c1_y;
c0_x = -c0_x, c0_y = -c0_y;
}
if (!IsRectInPosHalfSpace(doc_rect.left * inverted[0] + inverted[2],
doc_rect.left * inverted[3] + inverted[5],
c1_x, c1_y, lrect, TRUE))
return FALSE;
if (!IsRectInPosHalfSpace(doc_rect.top * inverted[1] + inverted[2],
doc_rect.top * inverted[4] + inverted[5],
-c0_x, -c0_y, lrect, TRUE))
return FALSE;
if (!IsRectInPosHalfSpace(doc_rect.right * inverted[0] + inverted[2],
doc_rect.right * inverted[3] + inverted[5],
-c1_x, -c1_y, lrect, FALSE))
return FALSE;
if (!IsRectInPosHalfSpace(doc_rect.bottom * inverted[1] + inverted[2],
doc_rect.bottom * inverted[4] + inverted[5],
c0_x, c0_y, lrect, FALSE))
return FALSE;
}
return TRUE;
}
/*static*/
BOOL VisualDeviceTransform::TestInclusionTransformed(const OpRect& rect1, const AffineTransform& transform, const OpRect& rect2)
{
float det = transform.Determinant();
if (det == 0.0f)
return FALSE;
float c0_x = transform[0], c0_y = transform[3];
float c1_x = transform[1], c1_y = transform[4];
if (det < 0)
{
// Flip
c1_x = -c1_x, c1_y = -c1_y;
c0_x = -c0_x, c0_y = -c0_y;
}
if (!IsRectFullyInPosHalfSpace(rect1.Left() * transform[0] + transform[2],
rect1.Left() * transform[3] + transform[5],
c1_x, c1_y, rect2, TRUE))
return FALSE;
if (!IsRectFullyInPosHalfSpace(rect1.Top() * transform[1] + transform[2],
rect1.Top() * transform[4] + transform[5],
-c0_x, -c0_y, rect2, TRUE))
return FALSE;
if (!IsRectFullyInPosHalfSpace(rect1.Right() * transform[0] + transform[2],
rect1.Right() * transform[3] + transform[5],
-c1_x, -c1_y, rect2, FALSE))
return FALSE;
if (!IsRectFullyInPosHalfSpace(rect1.Bottom() * transform[1] + transform[2],
rect1.Bottom() * transform[4] + transform[5],
c0_x, c0_y, rect2, FALSE))
return FALSE;
return TRUE;
}
#endif // CSS_TRANSFORMS
|
#include <iostream>
#include <vector>
#include <set>
using namespace std;
void solve () {
int n;
cin >> n;
int a[n];
for (auto& it: a) cin >> it;
vector<vector<int>> pref(26, vector<int>(n + 1));
for (int i=0; i<n; ++i) {
for (int j=0; j<26; ++j) pref[j][i+1] = pref[j][i];
++pref[a[i]-1][i+1];
}
int ans = 0;
for (int i=0; i<26; ++i) ans = max(ans, pref[i][n]);
for (int l=0; l<n; ++l) for (int r=l; r<n; ++r) {
int cnt_in = 0, cnt_out = 0;
for (int i=0; i<26; ++i) {
cnt_in = max(cnt_in, pref[i][r+1] - pref[i][l]);
cnt_out = max(cnt_out, min(pref[i][l], pref[i][n] - pref[i][r+1]));
}
ans = max(ans, cnt_in + 2*cnt_out);
}
cout << ans << endl;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
|
//
// 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.
//
// @author Arjan van Leeuwen (arjanl)
//
#ifndef MISC_COMMANDS_H
#define MISC_COMMANDS_H
#include "adjunct/m2/src/backend/imap/commands/ImapCommandItem.h"
#include "adjunct/m2/src/backend/imap/imap-flags.h"
#include "adjunct/m2/src/backend/imap/imap-protocol.h"
#include "adjunct/m2/src/backend/imap/imapmodule.h"
namespace ImapCommands
{
/** @brief CAPABILITY command
*/
class Capability : public ImapCommandItem
{
public:
int NeedsState(BOOL secure, IMAP4& protocol) const { return ImapFlags::STATE_CONNECTED; }
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.Append("CAPABILITY"); }
};
/** @brief ID command
*/
class ID : public ImapCommandItem
{
public:
int NeedsState(BOOL secure, IMAP4& protocol) const { return ImapFlags::STATE_RECEIVED_CAPS; }
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol);
};
/** @brief LIST command
*/
class List : public ImapCommandItem
{
public:
OP_STATUS OnSuccessfulComplete(IMAP4& protocol)
{ return protocol.GetBackend().ProcessConfirmedFolderList(); }
protected:
virtual OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol)
{ return command.AppendFormat("LIST %s \"*\"", protocol.GetBackend().GetFolderPrefix().CStr()); }
ProgressInfo::ProgressAction GetProgressAction() const
{ return ProgressInfo::FETCHING_FOLDER_LIST; }
};
/** @brief SpecialUseList command is either XLIST or LIST (SPECIAL-USE)
*/
class SpecialUseList : public List
{
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol);
};
/** @brief LOGOUT command
*/
class Logout : public ImapCommandItem
{
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.Append("LOGOUT"); }
};
/** @brief LSUB command
*/
class Lsub : public ImapCommandItem
{
public:
OP_STATUS PrepareToSend(IMAP4& protocol);
OP_STATUS OnSuccessfulComplete(IMAP4& protocol)
{ return protocol.ProcessSubscribedFolderList(); }
ProgressInfo::ProgressAction GetProgressAction() const
{ return ProgressInfo::FETCHING_FOLDER_LIST; }
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol)
{ return command.AppendFormat("LSUB %s \"*\"", protocol.GetBackend().GetFolderPrefix().CStr()); }
};
/** @brief NAMESPACE command
*/
class Namespace : public ImapCommandItem
{
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.Append("NAMESPACE"); }
};
/** @brief STARTTLS command
*/
class Starttls : public ImapCommandItem
{
public:
OP_STATUS OnSuccessfulComplete(IMAP4& protocol)
{ return protocol.UpgradeToTLS(); }
int NeedsState(BOOL secure, IMAP4& protocol) const
{ return ImapFlags::STATE_CONNECTED | ImapFlags::STATE_RECEIVED_CAPS; }
OP_STATUS OnFailed(IMAP4& protocol, const OpStringC8& failed_msg)
{ protocol.SetCapabilities(protocol.GetCapabilities() & ~ImapFlags::CAP_STARTTLS); return OpStatus::OK; }
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol) { return command.Append("STARTTLS"); }
};
/** @brief IDLE command
*/
class Idle : public ImapCommandItem
{
public:
Idle() : m_continuation(FALSE) {}
BOOL IsUnnecessary(const IMAP4& protocol) const
{ return !m_continuation && Suc() != NULL; }
BOOL WaitForNext() const
{ return m_continuation; }
OP_STATUS OnSuccessfulComplete(IMAP4& protocol)
{ return protocol.StopIdleTimer(); }
OP_STATUS PrepareContinuation(IMAP4& protocol, const OpStringC8& response_text)
{ m_continuation = TRUE; return protocol.StartIdleTimer(); }
BOOL IsContinuation() const
{ return m_continuation; }
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol)
{ return command.Append(m_continuation ? "DONE" : "IDLE"); }
BOOL m_continuation;
};
/** @brief ENABLE command
*/
class EnableQResync : public ImapCommandItem
{
public:
int NeedsState(BOOL secure, IMAP4& protocol) const
{ return GetDefaultFlags(secure, protocol) & ~ImapFlags::STATE_ENABLED_QRESYNC; }
OP_STATUS OnSuccessfulComplete(IMAP4& protocol);
OP_STATUS OnFailed(IMAP4& protocol, const OpStringC8& failed_msg)
{ protocol.SetCapabilities(protocol.GetCapabilities() & ~ImapFlags::CAP_QRESYNC); return OpStatus::OK; }
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol)
{ return command.Append("ENABLE QRESYNC"); }
};
/** @brief COMPRESS command
*/
class Compress : public ImapCommandItem
{
public:
int NeedsState(BOOL secure, IMAP4& protocol) const
{ return GetDefaultFlags(secure, protocol) & ~ImapFlags::STATE_COMPRESSED; }
OP_STATUS OnSuccessfulComplete(IMAP4& protocol)
{ protocol.AddState(ImapFlags::STATE_COMPRESSED); return OpStatus::OK; }
OP_STATUS OnFailed(IMAP4& protocol, const OpStringC8& failed_msg)
{ protocol.SetCapabilities(protocol.GetCapabilities() & ~ImapFlags::CAP_COMPRESS_DEFLATE); return OpStatus::OK; }
protected:
OP_STATUS AppendCommand(OpString8& command, IMAP4& protocol)
{ return command.Append("COMPRESS DEFLATE"); }
};
};
#endif // MISC_COMMANDS_H
|
// Copyright (C) 2004 Id Software, Inc.
//
#ifndef __RENDERER_H__
#define __RENDERER_H__
/*
===============================================================================
idRenderSystem is responsible for managing the screen, which can have
multiple idRenderWorld and 2D drawing done on it.
===============================================================================
*/
// Contains variables specific to the OpenGL configuration being run right now.
// These are constant once the OpenGL subsystem is initialized.
typedef struct glconfig_s {
const char *renderer_string;
const char *vendor_string;
const char *version_string;
const char *extensions_string;
const char *wgl_extensions_string;
float glVersion; // atof( version_string )
int maxTextureSize; // queried from GL
int maxTextureUnits;
int maxTextureCoords;
int maxTextureImageUnits;
float maxTextureAnisotropy;
int colorBits, depthBits, stencilBits;
// RAVEN BEGIN
int alphaBits;
// RAVEN END
bool multitextureAvailable;
bool anisotropicAvailable;
bool textureLODBiasAvailable;
bool textureEnvAddAvailable;
bool textureEnvCombineAvailable;
// RAVEN BEGIN
// jscott: added
bool blendSquareAvailable;
// RAVEN END
bool registerCombinersAvailable;
bool cubeMapAvailable;
bool envDot3Available;
bool texture3DAvailable;
bool sharedTexturePaletteAvailable;
// RAVEN BEGIN
// dluetscher: added
bool drawRangeElementsAvailable;
bool blendMinMaxAvailable;
bool floatBufferAvailable;
// RAVEN END
bool ARBVertexBufferObjectAvailable;
bool ARBVertexProgramAvailable;
bool ARBFragmentProgramAvailable;
bool twoSidedStencilAvailable;
bool textureNonPowerOfTwoAvailable;
bool depthBoundsTestAvailable;
// RAVEN BEGIN
// rjohnson: new shader stage system
bool GLSLProgramAvailable;
// RAVEN END
// RAVEN BEGIN
// dluetscher: added check for NV_vertex_program and NV_fragment_program support
bool nvProgramsAvailable;
// RAVEN END
// ati r200 extensions
bool atiFragmentShaderAvailable;
// ati r300
bool atiTwoSidedStencilAvailable;
int vidWidth, vidHeight; // passed to R_BeginFrame
int displayFrequency;
bool isFullscreen;
#ifndef _CONSOLE
bool preferNV20Path; // for FX5200 cards
// RAVEN BEGIN
// dluetscher: added preferSimpleLighting flag
bool preferSimpleLighting; // for the ATI 9700 cards
// RAVEN END
#endif
bool allowNV20Path;
bool allowNV10Path;
bool allowR200Path;
bool allowARB2Path;
bool isInitialized;
// INTEL BEGIN
// Anu adding support to toggle SMP
#ifdef ENABLE_INTEL_SMP
bool isSmpAvailable;
int isSmpActive;
int rearmSmp;
#endif
// INTEL END
} glconfig_t;
// font support
#define GLYPH_COUNT 256
typedef struct glyphInfo_s
{
float width; // number of pixels wide
float height; // number of scan lines
float horiAdvance; // number of pixels to advance to the next char
float horiBearingX; // x offset into space to render glyph
float horiBearingY; // y offset
float s1; // x start tex coord
float t1; // y start tex coord
float s2; // x end tex coord
float t2; // y end tex coord
} glyphInfo_t;
typedef struct fontInfo_s
{
glyphInfo_t glyphs[GLYPH_COUNT];
float pointSize;
float fontHeight; // max height of font
float ascender;
float descender;
idMaterial *material;
} fontInfo_t;
typedef struct {
fontInfo_t fontInfoSmall;
fontInfo_t fontInfoMedium;
fontInfo_t fontInfoLarge;
float maxHeight;
float maxWidth;
float maxHeightSmall;
float maxWidthSmall;
float maxHeightMedium;
float maxWidthMedium;
float maxHeightLarge;
float maxWidthLarge;
char name[64];
// RAVEN BEGIN
// mwhitlock: Xenon texture streaming
#if defined(_XENON)
idList<idMaterial*> allMaterials;
#endif
// RAVEN END
} fontInfoEx_t;
const int TINYCHAR_WIDTH = 4;
const int TINYCHAR_HEIGHT = 8;
const int SMALLCHAR_WIDTH = 8;
const int SMALLCHAR_HEIGHT = 16;
const int BIGCHAR_WIDTH = 16;
const int BIGCHAR_HEIGHT = 16;
// all drawing is done to a 640 x 480 virtual screen size
// and will be automatically scaled to the real resolution
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
// RAVEN BEGIN
// rjohnson: new blur special effect
typedef enum
{
SPECIAL_EFFECT_NONE = 0,
SPECIAL_EFFECT_BLUR = 0x00000001,
SPECIAL_EFFECT_AL = 0x00000002,
SPECIAL_EFFECT_MAX,
} ESpecialEffectType;
// RAVEN END
class idRenderWorld;
class idRenderSystem {
public:
virtual ~idRenderSystem() {}
// set up cvars and basic data structures, but don't
// init OpenGL, so it can also be used for dedicated servers
// RAVEN BEGIN
// nrausch: Init things that touch the render state seperately
virtual void DeferredInit( void ) { }
// RAVEN END
virtual void Init( void ) = 0;
// only called before quitting
virtual void Shutdown( void ) = 0;
// RAVEN BEGIN
// mwhitlock: Dynamic memory consolidation
#if defined(_RV_MEM_SYS_SUPPORT)
virtual void FlushLevelImages( void ) = 0;
#endif
// RAVEN END
virtual void InitOpenGL( void ) = 0;
virtual void ShutdownOpenGL( void ) = 0;
virtual bool IsOpenGLRunning( void ) const = 0;
virtual void GetValidModes( idStr &Mode4x3Text, idStr &Mode4x3Values, idStr &Mode16x9Text, idStr &Mode16x9Values,
idStr &Mode16x10Text, idStr &Mode16x10Values ) = 0;
virtual bool IsFullScreen( void ) const = 0;
virtual int GetScreenWidth( void ) const = 0;
virtual int GetScreenHeight( void ) const = 0;
// allocate a renderWorld to be used for drawing
virtual idRenderWorld * AllocRenderWorld( void ) = 0;
virtual void FreeRenderWorld( idRenderWorld * rw ) = 0;
// RAVEN BEGIN
virtual void RemoveAllModelReferences( idRenderModel *model ) = 0;
// RAVEN BEGIN
// All data that will be used in a level should be
// registered before rendering any frames to prevent disk hits,
// but they can still be registered at a later time
// if necessary.
virtual void BeginLevelLoad( void ) = 0;
virtual void EndLevelLoad( void ) = 0;
// RAVEN BEGIN
// mwhitlock: changes for Xenon to enable us to use texture resources from .xpr
// bundles.
#if defined(_XENON)
// Like BeginLevelLoad and EndLevelLoad, but only deals with textures.
virtual void XenonBeginLevelLoadTextures( void ) = 0;
virtual void XenonEndLevelLoadTextures( void ) = 0;
#endif
// RAVEN END
#ifdef Q4SDK_MD5R
virtual void ExportMD5R( bool compressed ) = 0;
virtual void CopyPrimBatchTriangles( idDrawVert *destDrawVerts, glIndex_t *destIndices, void *primBatchMesh, void *silTraceVerts ) = 0;
#else // Q4SDK_MD5R
// RAVEN BEGIN
// dluetscher: added call to write out the MD5R models that have been converted at load,
// also added call to retrieve idDrawVert geometry from a MD5R primitive batch
// from the game DLL
#if defined( _MD5R_WRITE_SUPPORT ) && defined( _MD5R_SUPPORT )
virtual void ExportMD5R( bool compressed ) = 0;
#endif
#if defined( _MD5R_SUPPORT )
virtual void CopyPrimBatchTriangles( idDrawVert *destDrawVerts, glIndex_t *destIndices, rvMesh *primBatchMesh, const rvSilTraceVertT *silTraceVerts ) = 0;
#endif
#endif // !Q4SDK_MD5R
// jnewquist: Track texture usage during cinematics for streaming purposes
#ifndef _CONSOLE
enum TextureTrackCommand {
TEXTURE_TRACK_BEGIN,
TEXTURE_TRACK_UPDATE,
TEXTURE_TRACK_END
};
virtual void TrackTextureUsage( TextureTrackCommand command, int frametime = 0, const char *name=NULL ) = 0;
#endif
// RAVEN END
// font support
virtual bool RegisterFont( const char *fontName, fontInfoEx_t &font ) = 0;
// GUI drawing just involves shader parameter setting and axial image subsections
virtual void SetColor( const idVec4 &rgba ) = 0;
virtual void SetColor4( float r, float g, float b, float a ) = 0;
virtual void DrawStretchPic( const idDrawVert *verts, const glIndex_t *indexes, int vertCount, int indexCount, const idMaterial *material, bool clip = true ) = 0;
virtual void DrawStretchPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, const idMaterial *material ) = 0;
// RAVEN BEGIN
// jnewquist: Deal with flipped back-buffer copies on Xenon
virtual void DrawStretchCopy( float x, float y, float w, float h, float s1, float t1, float s2, float t2, const idMaterial *material ) = 0;
// RAVEN END
virtual void DrawStretchTri ( idVec2 p1, idVec2 p2, idVec2 p3, idVec2 t1, idVec2 t2, idVec2 t3, const idMaterial *material ) = 0;
virtual void GlobalToNormalizedDeviceCoordinates( const idVec3 &global, idVec3 &ndc ) = 0;
virtual void GetGLSettings( int& width, int& height ) = 0;
virtual void PrintMemInfo( MemInfo *mi ) = 0;
virtual void DrawTinyChar( int x, int y, int ch, const idMaterial *material ) = 0;
virtual void DrawTinyStringExt( int x, int y, const char *string, const idVec4 &setColor, bool forceColor, const idMaterial *material ) = 0;
virtual void DrawSmallChar( int x, int y, int ch, const idMaterial *material ) = 0;
virtual void DrawSmallStringExt( int x, int y, const char *string, const idVec4 &setColor, bool forceColor, const idMaterial *material ) = 0;
virtual void DrawBigChar( int x, int y, int ch, const idMaterial *material ) = 0;
virtual void DrawBigStringExt( int x, int y, const char *string, const idVec4 &setColor, bool forceColor, const idMaterial *material ) = 0;
// dump all 2D drawing so far this frame to the demo file
virtual void WriteDemoPics() = 0;
// draw the 2D pics that were saved out with the current demo frame
virtual void DrawDemoPics() = 0;
// FIXME: add an interface for arbitrary point/texcoord drawing
// a frame cam consist of 2D drawing and potentially multiple 3D scenes
// window sizes are needed to convert SCREEN_WIDTH / SCREEN_HEIGHT values
virtual void BeginFrame( int windowWidth, int windowHeight ) = 0;
// RAVEN BEGIN
virtual void BeginFrame( struct viewDef_s *viewDef, int windowWidth, int windowHeight ) = 0;
virtual void RenderLightFrustum( const struct renderLight_s &renderLight, idPlane lightFrustum[6] ) = 0;
virtual void LightProjectionMatrix( const idVec3 &origin, const idPlane &rearPlane, idVec4 mat[4] ) = 0;
virtual void ToggleSmpFrame( void ) = 0;
// RAVEN END
// RAVEN BEGIN
// rjohnson: new blur special effect
virtual void SetSpecialEffect( ESpecialEffectType Which, bool Enabled ) = 0;
virtual void SetSpecialEffectParm( ESpecialEffectType Which, int Parm, float Value ) = 0;
virtual void ShutdownSpecialEffects( void ) = 0;
// RAVEN END
// if the pointers are not NULL, timing info will be returned
virtual void EndFrame( int *frontEndMsec = NULL, int *backEndMsec = NULL, int *numVerts = NULL, int *numIndexes = NULL ) = 0;
// aviDemo uses this.
// Will automatically tile render large screen shots if necessary
// Samples is the number of jittered frames for anti-aliasing
// If ref == NULL, session->updateScreen will be used
// This will perform swapbuffers, so it is NOT an approppriate way to
// generate image files that happen during gameplay, as for savegame
// markers. Use WriteRender() instead.
// RAVEN BEGIN
// rjohnson: added basePath
virtual void TakeJPGScreenshot( int width, int height, const char *fileName, int blends, struct renderView_s *ref, const char *basePath = "fs_savepath" ) = 0;
virtual void TakeScreenshot( int width, int height, const char *fileName, int blends, struct renderView_s *ref, const char *basePath = "fs_savepath" ) = 0;
// RAVEN END
// the render output can be cropped down to a subset of the real screen, as
// for save-game reviews and split-screen multiplayer. Users of the renderer
// will not know the actual pixel size of the area they are rendering to
// the x,y,width,height values are in virtual SCREEN_WIDTH / SCREEN_HEIGHT coordinates
// to render to a texture, first set the crop size with makePowerOfTwo = true,
// then perform all desired rendering, then capture to an image
// if the specified physical dimensions are larger than the current cropped region, they will be cut down to fit
virtual void CropRenderSize( int width, int height, bool makePowerOfTwo = false, bool forceDimensions = false ) = 0;
virtual void CaptureRenderToImage( const char *imageName ) = 0;
virtual void CaptureRenderToMemory( void *buffer ) = 0;
// fixAlpha will set all the alpha channel values to 0xff, which allows screen captures
// to use the default tga loading code without having dimmed down areas in many places
virtual void CaptureRenderToFile( const char *fileName, bool fixAlpha = false ) = 0;
virtual void UnCrop() = 0;
virtual void GetCardCaps( bool &oldCard, bool &nv10or20 ) = 0;
virtual bool UploadImage( const char *imageName, const byte *data, int width, int height ) = 0;
virtual void DebugGraph( float cur, float min, float max, const idVec4 &color ) = 0;
virtual void ShowDebugGraph( void ) = 0;
};
extern idRenderSystem * renderSystem;
#endif /* !__RENDERER_H__ */
|
#ifndef EXAMPLE_CLASS_HPP
#define EXAMPLE_CLASS_HPP
class ExampleClass{
public:
ExampleClass();
virtual ~ExampleClass();
int setNewAndReturnLast(int n);
private:
int x;
};
#endif //EXAMPLE_CLASS_HPP
|
#include <wpp/qt/QGuiApplication.h>
#include <wpp/qt/QQmlApplicationEngine.h>
int main(int argc, char *argv[])
{
wpp::qt::QGuiApplication app(argc, argv);
wpp::qt::QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
|
#pragma once
#include "MarchingCubes.hpp"
#include "LookupTables.hpp"
#include "atlas\utils\Utils.hpp"
#include "atlas/math/Math.hpp"
#include <math.h>
#include <iostream>
namespace assignment2
{
void MarchingCubes::createMesh(std::vector<Sphere*>& SceneSpheres, std::vector<Normal> &vertices, std::vector<Normal> &normals )
{
mSceneSpheres = SceneSpheres;
//Create the grid that contains the objects
if (generateGrid() == 1)
{
printf("Failed to generate a grid for the spheres in the scene");
};
float *vertexValueGrid1 = new float[mSceneGrid.xSize * mSceneGrid.zSize];
float *vertexValueGrid2 = new float[mSceneGrid.xSize * mSceneGrid.zSize];
std::cout << "Size of Grid = " << mSceneGrid.xSize * mSceneGrid.zSize << std::endl;
calculateVertexValues(vertexValueGrid1, 0);
for (int y = 1; y < mSceneGrid.ySize; y++)
{
if (y % 2 == 1)
{
calculateVertexValues(vertexValueGrid2, y);
calculateVoxels(vertexValueGrid1, vertexValueGrid2, y-1, vertices, normals);
}
else
{
calculateVertexValues(vertexValueGrid1, y);
calculateVoxels(vertexValueGrid2, vertexValueGrid1, y-1, vertices, normals);
}
}
delete[] vertexValueGrid1;
delete[] vertexValueGrid2;
}
void MarchingCubes::calculateVertexValues(float *vertexArray, int y)
{
for (int x = 0; x < mSceneGrid.xSize; x++)
{
for (int z = 0; z < mSceneGrid.zSize; z++)
{
Vector3 position = Vector3(mSceneGrid.boundingBox[0].x + (x * VOXEL_SIZE),
mSceneGrid.boundingBox[0].y + (y * VOXEL_SIZE),
mSceneGrid.boundingBox[0].z + (z * VOXEL_SIZE));
float value = 1;
for (int i = 0; i < mSceneSpheres.size(); i++)
{
value = mSceneSpheres.at(i)->contains(position);
if (value == 0)
{
break;
}
}
vertexArray[x * mSceneGrid.zSize + z] = value;
}
}
}
void MarchingCubes::calculateVoxels(float * bottomVertexArray, float *topVertexArray, int y, std::vector<Vector3> &vertices, std::vector<Normal> &normals)
{
for (int x = 0; x < mSceneGrid.xSize - 1; x++)
{
for (int z = 0; z < mSceneGrid.zSize - 1; z++)
{
Voxel voxel;
//back side positions
voxel.cornerPositions[0] = Vector3(mSceneGrid.boundingBox[0].x + (x * VOXEL_SIZE), mSceneGrid.boundingBox[0].y + (y * VOXEL_SIZE), mSceneGrid.boundingBox[0].b + (z * VOXEL_SIZE));
voxel.cornerPositions[1] = Vector3(mSceneGrid.boundingBox[0].x + ((x + 1) * VOXEL_SIZE), mSceneGrid.boundingBox[0].y + (y * VOXEL_SIZE), mSceneGrid.boundingBox[0].z + (z * VOXEL_SIZE));
voxel.cornerPositions[2] = Vector3(mSceneGrid.boundingBox[0].x + ((x + 1) * VOXEL_SIZE), mSceneGrid.boundingBox[0].y + (y * VOXEL_SIZE), mSceneGrid.boundingBox[0].z + ((z + 1) * VOXEL_SIZE));
voxel.cornerPositions[3] = Vector3(mSceneGrid.boundingBox[0].x + (x * VOXEL_SIZE), mSceneGrid.boundingBox[0].y + (y * VOXEL_SIZE), mSceneGrid.boundingBox[0].z + ((z + 1) * VOXEL_SIZE));
//front side positions
voxel.cornerPositions[4] = Vector3(mSceneGrid.boundingBox[0].x + (x * VOXEL_SIZE), mSceneGrid.boundingBox[0].y + ((y + 1) * VOXEL_SIZE), mSceneGrid.boundingBox[0].z + (z * VOXEL_SIZE));
voxel.cornerPositions[5] = Vector3(mSceneGrid.boundingBox[0].x + ((x + 1) * VOXEL_SIZE), mSceneGrid.boundingBox[0].y + ((y + 1) * VOXEL_SIZE), mSceneGrid.boundingBox[0].z + (z * VOXEL_SIZE));
voxel.cornerPositions[6] = Vector3(mSceneGrid.boundingBox[0].x + ((x + 1) * VOXEL_SIZE), mSceneGrid.boundingBox[0].y + ((y + 1) * VOXEL_SIZE), mSceneGrid.boundingBox[0].z + ((z + 1) * VOXEL_SIZE));
voxel.cornerPositions[7] = Vector3(mSceneGrid.boundingBox[0].x + (x * VOXEL_SIZE), mSceneGrid.boundingBox[0].y + ((y + 1) * VOXEL_SIZE), mSceneGrid.boundingBox[0].z + ((z + 1) * VOXEL_SIZE));
//back side values
voxel.cornerValue[0] = bottomVertexArray[x * mSceneGrid.zSize + z];
voxel.cornerValue[1] = bottomVertexArray[(x + 1) * mSceneGrid.zSize + z];
voxel.cornerValue[2] = bottomVertexArray[(x + 1) * mSceneGrid.zSize + (z + 1)];
voxel.cornerValue[3] = bottomVertexArray[x * mSceneGrid.zSize + (z + 1)];
//front side values
voxel.cornerValue[4] = topVertexArray[x * mSceneGrid.zSize + z];
voxel.cornerValue[5] = topVertexArray[(x + 1) * mSceneGrid.zSize + z ];
voxel.cornerValue[6] = topVertexArray[(x + 1) * mSceneGrid.zSize + (z + 1)];
voxel.cornerValue[7] = topVertexArray[x * mSceneGrid.zSize + (z + 1)];
polygonizeVoxel(voxel, vertices, normals, ISO_VALUE);
}
}
}
int MarchingCubes::generateGrid()
{
if (mSceneSpheres.size() == 0)
{
return 1;
}
//Create BoundingBox
Sphere *sphere = mSceneSpheres.at(0);
int minX = (int)floor(sphere->x() - sphere->radius());
int minY = (int)floor(sphere->y() - sphere->radius());
int minZ = (int)floor(sphere->z() - sphere->radius());
int maxX = (int)ceil(sphere->x() + sphere->radius());
int maxY = (int)ceil(sphere->y() + sphere->radius());
int maxZ = (int)ceil(sphere->z() + sphere->radius());
int temp;
for (int i = 1; i < mSceneSpheres.size(); i++)
{
sphere = mSceneSpheres.at(i);
if ((temp = (int)floor(sphere->x() - sphere->radius())) < minX) minX = temp;
if ((temp = (int)floor(sphere->y() - sphere->radius())) < minY) minY = temp;
if ((temp = (int)floor(sphere->z() - sphere->radius())) < minZ) minZ = temp;
if ((temp = (int)ceil(sphere->x() + sphere->radius())) > maxX) maxX = temp;
if ((temp = (int)ceil(sphere->y() + sphere->radius())) > maxY) maxY = temp;
if ((temp = (int)ceil(sphere->z() + sphere->radius())) > maxZ) maxZ = temp;
}
mSceneGrid.boundingBox[0] = Vector3(minX, minY, minZ);
mSceneGrid.boundingBox[1] = Vector3(maxX, minY, minZ);
mSceneGrid.boundingBox[2] = Vector3(minX, maxY, minZ);
mSceneGrid.boundingBox[3] = Vector3(maxX, maxY, minZ);
mSceneGrid.boundingBox[4] = Vector3(minX, minY, maxZ);
mSceneGrid.boundingBox[5] = Vector3(maxX, minY, maxZ);
mSceneGrid.boundingBox[6] = Vector3(minX, maxY, maxZ);
mSceneGrid.boundingBox[7] = Vector3(maxX, maxY, maxZ);
mSceneGrid.xSize = (int) ((maxX - minX) / VOXEL_SIZE) + 1;
mSceneGrid.ySize = (int) ((maxY - minY) / VOXEL_SIZE) + 1;
mSceneGrid.zSize = (int) ((maxZ - minZ) / VOXEL_SIZE) + 1;
return 0;
}
void MarchingCubes::polygonizeVoxel(Voxel voxel, std::vector<Vector3> &vertices, std::vector<Normal> &normals, float isoLevel)
{
Vector3 vertexList[12];
int voxelIndex = 0;
if (voxel.cornerValue[0] < isoLevel) voxelIndex |= 1;
if (voxel.cornerValue[1] < isoLevel) voxelIndex |= 2;
if (voxel.cornerValue[2] < isoLevel) voxelIndex |= 4;
if (voxel.cornerValue[3] < isoLevel) voxelIndex |= 8;
if (voxel.cornerValue[4] < isoLevel) voxelIndex |= 16;
if (voxel.cornerValue[5] < isoLevel) voxelIndex |= 32;
if (voxel.cornerValue[6] < isoLevel) voxelIndex |= 64;
if (voxel.cornerValue[7] < isoLevel) voxelIndex |= 128;
if (edgeTable[voxelIndex] == 0)
return;
if (edgeTable[voxelIndex] & 1)
{
vertexList[0] = vertexLinearInterp(voxel.cornerPositions[0], voxel.cornerPositions[1], voxel.cornerValue[0], voxel.cornerValue[1]);
}
if (edgeTable[voxelIndex] & 2)
{
vertexList[1] = vertexLinearInterp(voxel.cornerPositions[1], voxel.cornerPositions[2], voxel.cornerValue[1], voxel.cornerValue[2]);
}
if (edgeTable[voxelIndex] & 4)
{
vertexList[2] = vertexLinearInterp(voxel.cornerPositions[2], voxel.cornerPositions[3], voxel.cornerValue[2], voxel.cornerValue[3]);
}
if (edgeTable[voxelIndex] & 8)
{
vertexList[3] = vertexLinearInterp(voxel.cornerPositions[3], voxel.cornerPositions[0], voxel.cornerValue[3], voxel.cornerValue[0]);
}
if (edgeTable[voxelIndex] & 16)
{
vertexList[4] = vertexLinearInterp(voxel.cornerPositions[4], voxel.cornerPositions[5], voxel.cornerValue[4], voxel.cornerValue[5]);
}
if (edgeTable[voxelIndex] & 32)
{
vertexList[5] = vertexLinearInterp(voxel.cornerPositions[5], voxel.cornerPositions[6], voxel.cornerValue[5], voxel.cornerValue[6]);
}
if (edgeTable[voxelIndex] & 64)
{
vertexList[6] = vertexLinearInterp(voxel.cornerPositions[6], voxel.cornerPositions[7], voxel.cornerValue[6], voxel.cornerValue[7]);
}
if (edgeTable[voxelIndex] & 128)
{
vertexList[7] = vertexLinearInterp(voxel.cornerPositions[7], voxel.cornerPositions[4], voxel.cornerValue[7], voxel.cornerValue[4]);
}
if (edgeTable[voxelIndex] & 256)
{
vertexList[8] = vertexLinearInterp(voxel.cornerPositions[0], voxel.cornerPositions[4], voxel.cornerValue[0], voxel.cornerValue[4]);
}
if (edgeTable[voxelIndex] & 512)
{
vertexList[9] = vertexLinearInterp(voxel.cornerPositions[1], voxel.cornerPositions[5], voxel.cornerValue[1], voxel.cornerValue[5]);
}
if (edgeTable[voxelIndex] & 1024)
{
vertexList[10] = vertexLinearInterp(voxel.cornerPositions[2], voxel.cornerPositions[6], voxel.cornerValue[2], voxel.cornerValue[6]);
}
if (edgeTable[voxelIndex] & 2048)
{
vertexList[11] = vertexLinearInterp(voxel.cornerPositions[3], voxel.cornerPositions[7], voxel.cornerValue[3], voxel.cornerValue[7]);
}
/* Add triangle vertices to entire vertices vector */
for (int i = 0; triangleTable[voxelIndex][i] != -1; i += 3) {
Vector3 vec1 = vertexList[triangleTable[voxelIndex][i]];
Vector3 vec2 = vertexList[triangleTable[voxelIndex][i + 1]];
Vector3 vec3 = vertexList[triangleTable[voxelIndex][i + 1]];
Normal norm = glm::normalize(glm::cross(vec2 - vec1, vec3 - vec1));
normals.push_back(norm);
normals.push_back(norm);
normals.push_back(norm);
vertices.push_back(vertexList[triangleTable[voxelIndex][i]]);
vertices.push_back(vertexList[triangleTable[voxelIndex][i + 1]]);
vertices.push_back(vertexList[triangleTable[voxelIndex][i + 2]]);
}
return;
}
Vector3 MarchingCubes::vertexLinearInterp(const Vector3 & p1, const Vector3 & p2, float valueP1, float valueP2)
{
return (p1 + (-valueP1 / (valueP2 - valueP1)) * (p2 - p1));
}
}
|
//A*
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 5010;
const int maxm = 400010;
const int inf = 2e9;
int n, m, s, t, k, u, v, ww, H[maxn], cnt[maxn];
int cur, h[maxn], nxt[maxm], p[maxm], w[maxm];
int cur1, h1[maxn], nxt1[maxm], p1[maxm], w1[maxm];
bool tf[maxn];
void add_edge(int x, int y, double z) {
cur++;
nxt[cur] = h[x];
h[x] = cur;
p[cur] = y;
w[cur] = z;
}
void add_edge1(int x, int y, double z) {
cur1++;
nxt1[cur1] = h1[x];
h1[x] = cur1;
p1[cur1] = y;
w1[cur1] = z;
}
struct node {
int x, v;
bool operator<(node a) const { return v + H[x] > a.v + H[a.x]; }
};
priority_queue<node> q;
struct node2 {
int x, v;
bool operator<(node2 a) const { return v > a.v; }
} x;
priority_queue<node2> Q;
int main() {
scanf("%d%d%d%d%d", &n, &m, &s, &t, &k);
while (m--) {
scanf("%d%d%d", &u, &v, &ww);
add_edge(u, v, ww);
add_edge1(v, u, ww);
}
for (int i = 1; i <= n; i++) H[i] = inf;
Q.push({t, 0});
while (!Q.empty()) {
x = Q.top();
Q.pop();
if (tf[x.x]) continue;
tf[x.x] = true;
H[x.x] = x.v;
for (int j = h1[x.x]; j; j = nxt1[j]) Q.push({p1[j], x.v + w1[j]});
}
q.push({s, 0});
while (!q.empty()) {
node x = q.top();
q.pop();
cnt[x.x]++;
if (x.x == t && cnt[x.x] == k) {
printf("%d\n", x.v);
return 0;
}
if (cnt[x.x] > k) continue;
for (int j = h[x.x]; j; j = nxt[j]) q.push({p[j], x.v + w[j]});
}
printf("-1\n");
return 0;
}
//可持久化堆
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 200010;
int n, m, s, t, k, x, y, ww, cnt, fa[maxn];
struct Edge {
int cur, h[maxn], nxt[maxn], p[maxn], w[maxn];
void add_edge(int x, int y, int z) {
cur++;
nxt[cur] = h[x];
h[x] = cur;
p[cur] = y;
w[cur] = z;
}
} e1, e2;
int dist[maxn];
bool tf[maxn], vis[maxn], ontree[maxn];
struct node {
int x, v;
node* operator=(node a) {
x = a.x;
v = a.v;
return this;
}
bool operator<(node a) const { return v > a.v; }
} a;
priority_queue<node> Q;
void dfs(int x) {
vis[x] = true;
for (int j = e2.h[x]; j; j = e2.nxt[j])
if (!vis[e2.p[j]])
if (dist[e2.p[j]] == dist[x] + e2.w[j])
fa[e2.p[j]] = x, ontree[j] = true, dfs(e2.p[j]);
}
struct LeftistTree {
int cnt, rt[maxn], lc[maxn * 20], rc[maxn * 20], dist[maxn * 20];
node v[maxn * 20];
LeftistTree() { dist[0] = -1; }
int newnode(node w) {
cnt++;
v[cnt] = w;
return cnt;
}
int merge(int x, int y) {
if (!x || !y) return x + y;
if (v[x] < v[y]) swap(x, y);
int p = ++cnt;
lc[p] = lc[x];
v[p] = v[x];
rc[p] = merge(rc[x], y);
if (dist[lc[p]] < dist[rc[p]]) swap(lc[p], rc[p]);
dist[p] = dist[rc[p]] + 1;
return p;
}
} st;
void dfs2(int x) {
vis[x] = true;
if (fa[x]) st.rt[x] = st.merge(st.rt[x], st.rt[fa[x]]);
for (int j = e2.h[x]; j; j = e2.nxt[j])
if (fa[e2.p[j]] == x && !vis[e2.p[j]]) dfs2(e2.p[j]);
}
int main() {
scanf("%d%d%d%d%d", &n, &m, &s, &t, &k);
for (int i = 1; i <= m; i++)
scanf("%d%d%d", &x, &y, &ww), e1.add_edge(x, y, ww), e2.add_edge(y, x, ww);
Q.push({t, 0});
while (!Q.empty()) {
a = Q.top();
Q.pop();
if (tf[a.x]) continue;
tf[a.x] = true;
dist[a.x] = a.v;
for (int j = e2.h[a.x]; j; j = e2.nxt[j]) Q.push({e2.p[j], a.v + e2.w[j]});
}
if (k == 1) {
if (tf[s])
printf("%d\n", dist[s]);
else
printf("-1\n");
return 0;
}
dfs(t);
for (int i = 1; i <= n; i++)
if (tf[i])
for (int j = e1.h[i]; j; j = e1.nxt[j])
if (!ontree[j])
if (tf[e1.p[j]])
st.rt[i] = st.merge(
st.rt[i],
st.newnode({e1.p[j], dist[e1.p[j]] + e1.w[j] - dist[i]}));
for (int i = 1; i <= n; i++) vis[i] = false;
dfs2(t);
if (st.rt[s]) Q.push({st.rt[s], dist[s] + st.v[st.rt[s]].v});
while (!Q.empty()) {
a = Q.top();
Q.pop();
cnt++;
if (cnt == k - 1) {
printf("%d\n", a.v);
return 0;
}
if (st.lc[a.x])
Q.push({st.lc[a.x], a.v - st.v[a.x].v + st.v[st.lc[a.x]].v});
if (st.rc[a.x])
Q.push({st.rc[a.x], a.v - st.v[a.x].v + st.v[st.rc[a.x]].v});
x = st.rt[st.v[a.x].x];
if (x) Q.push({x, a.v + st.v[x].v});
}
printf("-1\n");
return 0;
}
|
#include <iostream>
#include <getopt.h>
#include <string>
#include <fstream>
#include <Eigen/Dense>
#include "quadtree.h"
using namespace std;
using namespace Eigen;
template <typename T>
T load_csv(const std::string &path)
{
std::ifstream in;
in.open(path);
std::string line;
std::vector<double> values;
uint rows = 0;
while (std::getline(in, line))
{
std::stringstream ss(line);
std::string cell;
while (std::getline(ss, cell, ','))
{
double val = std::stod(cell);
values.push_back(val);
}
++rows;
}
return Eigen::Map<const Eigen::Matrix<
typename T::Scalar,
T::RowsAtCompileTime,
T::ColsAtCompileTime,
Eigen::RowMajor>>(values.data(), rows, values.size() / rows);
}
void usage()
{
std::cout << "Options:" << endl;
std::cout << " -a, --f1=f1.csv A csv file of polynomial about f1" << endl;
std::cout << " -b, --f2=f2.csv A csv file of polynomial about f2" << endl;
std::cout << " -o, --out=OUT The path of output file" << endl;
std::cout << " default value is './curves@f1@f2.csv'" << endl;
std::cout << " The fist line records the time, and " << endl;
std::cout << " the second line records the number of roots" << endl;
std::cout << " -t, --tolerance Set default precision 1e-6" << endl;
std::cout << " -h, --help(no value) Print the message and exit" << endl;
}
int main(int argc, char *argv[])
{
string f1_path;
string f2_path;
double precision = 1e-6;
string outpath = "./result.json";
static struct option long_options[] = {
{"f1", required_argument, 0, 'a'},
{"f2", required_argument, 0, 'b'},
{"out", optional_argument, 0, 'o'},
{"help", no_argument, 0, 'h'},
{"tolerance", optional_argument, 0, 't'},
{0, 0, 0, 0}};
int getopt_ret, option_index;
bool status = true;
while (1)
{
getopt_ret = getopt_long(argc, argv, "a:b:o::ht::", long_options, &option_index);
if (getopt_ret == -1)
break;
switch (getopt_ret)
{
case 0:
status = false;
break;
case 'a':
f1_path = optarg;
break;
case 'b':
f2_path = optarg;
break;
case 'o':
outpath = optarg;
break;
case 'h':
usage();
status = false;
break;
case 't':
precision = atof(optarg);
break;
case '?':
status = false;
break;
default:
status = false;
break;
}
}
if (status)
{
if (access((f1_path).c_str(), F_OK) != 0)
{
std::cout << "The path '" << f1_path << "' does not exist, pleasure check first" << std::endl;
return -1;
}
if (access((f2_path).c_str(), F_OK) != 0)
{
std::cout << "The path '" << f2_path << "' does not exist, pleasure check first" << std::endl;
return -1;
}
Eigen::MatrixXd f1_mat = load_csv<Eigen::MatrixXd>(f1_path);
Eigen::MatrixXd f2_mat = load_csv<Eigen::MatrixXd>(f2_path);
IntervalVec<itv> range(itv(0, 1), itv(0, 1));
quadtree * solver = new quadtree(f1_mat, f2_mat, range);
solver->search_procedure(range);
delete solver;
solver = nullptr;
}
}
|
//
// Created by Nikita Kruk on 08.08.18.
//
#ifndef SPRAPPROXIMATEBAYESIANCOMPUTATION_FREEBOUNDARYCONDITIONSCONFIGURATION_HPP
#define SPRAPPROXIMATEBAYESIANCOMPUTATION_FREEBOUNDARYCONDITIONSCONFIGURATION_HPP
#include "../Definitions.hpp"
#include "BoundaryConditionsConfiguration.hpp"
#include "Vector2D.hpp"
#include <vector>
class FreeBoundaryConditionsConfiguration : public BoundaryConditionsConfiguration
{
public:
FreeBoundaryConditionsConfiguration(Real x_size, Real y_size);
~FreeBoundaryConditionsConfiguration();
void BoundedParticleDistance(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy);
void BoundedParticleDistance(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij);
virtual void ClassAEffectiveParticleDistance(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy);
virtual void ClassAEffectiveParticleDistance(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij);
virtual void ClassBEffectiveParticleDistance_signed(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy);
virtual void ClassBEffectiveParticleDistance_unsigned(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy);
virtual void ClassBEffectiveParticleDistance_signed(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij);
virtual void ClassBEffectiveParticleDistance_unsigned(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij);
virtual void ClassCEffectiveParticleDistance_signed(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy);
virtual void ClassCEffectiveParticleDistance_unsigned(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy);
virtual void ClassCEffectiveParticleDistance_signed(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij);
virtual void ClassCEffectiveParticleDistance_unsigned(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij);
virtual void ApplyPeriodicBoundaryConditions(Real x, Real y, Real &x_pbc, Real &y_pbc);
virtual void ApplyPeriodicBoundaryConditions(std::vector<Real> &system_state, int N);
virtual void ApplyPeriodicBoundaryConditions(const Vector2D &r, Vector2D &r_pbc);
};
#endif //SPRAPPROXIMATEBAYESIANCOMPUTATION_FREEBOUNDARYCONDITIONSCONFIGURATION_HPP
|
#ifndef VECTOR_HPP
#define VECTOR_HPP
#define SIZE 4
class Vector {
private:
double _coords [SIZE];
public:
Vector();
Vector(const Vector & v);
Vector(double x, double y, double z, double s);
~Vector();
bool isPosition();
bool isDirection();
double getXCoord ();
double getYCoord ();
double getZCoord ();
double getS();
double getNthCoord(int);
void normalize();
void print();
void printLine();
Vector& operator+=(const Vector& rhs);
Vector& operator=(Vector rhs);
double& operator[](int);
const double& operator[](int) const;
Vector& add (Vector &V);
Vector& add (double val);
double scalar(Vector &V);
};
Vector operator+(Vector lop, const Vector& rop);
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/pi/network/OpSocket.h"
#include "modules/url/url_socket_wrapper.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#ifdef SOCKS_SUPPORT
#include "modules/socks/OpSocksSocket.h"
#include "modules/socks/socks_module.h"
//#define LOG_SOCKS_ACTIVITY //uncomment this line if you want to enable socks logging in debug mode
#ifdef LOG_SOCKS_ACTIVITY
class SocksLogger {
OpString buf;
public:
void logIt() {
//OP_NEW_DBG("-", "SOCKS");
//OP_DBG_LEN(buf, buf.Length());
OutputDebugString(buf.CStr());
buf.Delete(0);
}
~SocksLogger() {
logIt();
}
SocksLogger& operator << (const uni_char* str) {
buf.Append(str);
return *this;
}
SocksLogger& operator << (const char* str) {
buf.Append(str);
return *this;
}
SocksLogger& operator << (const OpString& str) {
buf.Append(str);
return *this;
}
SocksLogger& operator << (int n) {
buf.AppendFormat(UNI_L("%d"), n);
return *this;
}
SocksLogger& operator << (const void* ptr) {
buf.AppendFormat(UNI_L("0x%x"), (UINTPTR)ptr);
return *this;
}
SocksLogger& operator << (OpSocketAddress* addr) {
OpString temp;
if (addr)
addr->ToString(&temp);
return *this << temp;
}
};
#define DEBUG_OUT(STREAM) SocksLogger() << STREAM << "\n"
#else
#define DEBUG_OUT(STREAM) do {} while (0)
#endif // LOG_SOCKS_ACTIVITY
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** Global PrefsCollectionSocks object (singleton). */
#define g_pc_network (g_opera->prefs_module.PrefsCollectionNetwork())
OpSocksSocket::OpSocksSocket(OpSocketListener* listener, BOOL secure, OpSocket &inner_socket)
: m_secure(secure)
, m_socks_socket(&inner_socket)
, m_target_host()
, m_target_port(0)
, m_actual_target_address(NULL)
, m_listener(listener)
, m_nb_sent_ignore(0)
, m_nb_recv_ignore(0)
, m_host_resolver(NULL)
, m_socks_address(NULL)
, m_socks_server_name(NULL)
, m_state(SS_CONSTRUCTED)
{
m_socks_socket->SetListener(this);
}
OpSocksSocket::~OpSocksSocket()
{
DEBUG_OUT(this << "->~destroy " << " (connected to " << m_target_host << ")");
if (m_socks_socket != NULL) OP_DELETE(m_socks_socket);
if (m_actual_target_address != NULL) OP_DELETE(m_actual_target_address);
if (m_host_resolver != NULL) OP_DELETE(m_host_resolver);
if (m_socks_address != NULL) OP_DELETE(m_socks_address);
if (m_socks_server_name != NULL) m_socks_server_name = NULL;
}
OP_STATUS
OpSocksSocket::Create(OpSocket** psocket, OpSocket& inner_socket, OpSocketListener* listener, BOOL secure, ServerName* socks_server_name, UINT socks_server_port)
{
OpAutoPtr<OpSocksSocket> socket(OP_NEW(OpSocksSocket, (listener, secure, inner_socket)));
RETURN_OOM_IF_NULL(socket.get());
RETURN_IF_ERROR(OpSocketAddress::Create(&socket->m_socks_address));
socket->m_socks_address->SetPort(socks_server_port);
if (socks_server_name->IsHostResolved())
{
socket->m_socks_address->Copy(socks_server_name->SocketAddress());
socket->m_state = SS_SOCKS_RESOLVED;
*psocket = socket.release();
return OpStatus::OK;
}
RETURN_IF_ERROR(SocketWrapper::CreateHostResolver(&socket->m_host_resolver, socket.get()));
socket->m_socks_server_name = socks_server_name;
RETURN_IF_ERROR(socket->m_host_resolver->Resolve(socks_server_name->UniName()));
socket->m_state = SS_RESOLVING_SOCKS;
*psocket = socket.release();
return OpStatus::OK;
}
void OpSocksSocket::OnHostResolved(OpHostResolver* host_resolver)
{
OP_ASSERT(m_host_resolver == host_resolver);
if (m_host_resolver != host_resolver || host_resolver->GetAddressCount() == 0)
{
Error(SS_SOCKS_RESOLVE_FAILED);
return;
}
host_resolver->GetAddress(m_socks_address, 0);
OP_DELETE(m_host_resolver);
m_host_resolver = NULL;
if (m_socks_server_name != NULL && m_socks_address->IsValid())
{
// cache resolved address so we don't need to resolve it every other next:
m_socks_server_name->SetSocketAddress(m_socks_address);
m_socks_server_name = NULL;
}
switch (m_state)
{
case SS_RESOLVING_SOCKS:
m_state = SS_SOCKS_RESOLVED;
return;
case SS_WAITING_RESOLVING_SOCKS:
CommonConnect();
break;
default:
OP_ASSERT(!"Unexpected SOCKS socket state !");
break;
}
}
void OpSocksSocket::OnHostResolverError(OpHostResolver* host_resolver, OpHostResolver::Error error)
{
m_state = SS_CONNECTION_FAILED;
}
void
OpSocksSocket::Error(State state)
{
OP_ASSERT(state < 0);
if (m_listener)
{
switch (state)
{
default:
OP_ASSERT(!"Unexpected SOCKS socket state !");
// fall through
case SS_CONNECTION_FAILED:
DEBUG_OUT(this << " SS_CONNECTION_FAILED");
m_listener->OnSocketConnectError(this, CONNECTION_FAILED);
break;
case SS_AUTH_FAILED:
DEBUG_OUT(this << " SS_CONNECTION_REFUSED");
m_listener->OnSocketConnectError(this, CONNECTION_REFUSED);
break;
case SS_SOCKS_RESOLVE_FAILED:
DEBUG_OUT(this << " SS_SOCKS_RESOLVE_FAILED");
if (m_state == SS_WAITING_RESOLVING_SOCKS)
m_listener->OnSocketConnectError(this, CONNECTION_REFUSED);
break;
}
}
m_state = state;
}
OP_STATUS
OpSocksSocket::Connect(const uni_char* target_host, signed short target_port)
{
OP_STATUS stat = m_target_host.Set(target_host);
if (OpStatus::IsError(stat))
{
Error(SS_CONNECTION_FAILED);
return stat;
}
m_target_port = target_port;
return CommonConnect();
}
OP_STATUS
OpSocksSocket::Connect(OpSocketAddress* socket_address)
{
OP_ASSERT(socket_address->IsValid());
DEBUG_OUT(this << "->Connect " << " to " << socket_address);
// copy the target address:
OP_STATUS stat = socket_address->ToString(&m_target_host);
if (OpStatus::IsError(stat))
{
Error(SS_CONNECTION_FAILED);
return stat;
}
m_target_port = socket_address->Port();
return CommonConnect();
}
OP_STATUS
OpSocksSocket::CommonConnect()
{
OP_STATUS stat = OpStatus::OK;
if (m_state == SS_RESOLVING_SOCKS)
{
m_state = SS_WAITING_RESOLVING_SOCKS;
return OpStatus::OK;
}
if (m_state == SS_SOCKS_RESOLVE_FAILED)
{
m_state = SS_WAITING_RESOLVING_SOCKS; // required to fire the approp. error listener
Error(SS_SOCKS_RESOLVE_FAILED); // that is to fire the approp. error listener
return OpStatus::ERR;
}
OP_ASSERT(m_socks_socket); // should have been set by the constructor
m_socks_socket->SetListener(this);
// connect socket to the socks server:
OpSocketAddress* socksServerAddress;
if (m_socks_address != NULL)
socksServerAddress = m_socks_address;
else
socksServerAddress = g_opera->socks_module.GetSocksServerAddress();
if (!socksServerAddress->IsValid()) // invalid or unresolved socks proxy address
goto failure;
DEBUG_OUT(this << " SS_SOCKET_TO_SOCKS_CREATED");
m_state = SS_SOCKET_TO_SOCKS_CREATED;
stat = m_socks_socket->Connect(socksServerAddress);
if (OpStatus::IsError(stat)) goto failure;
return OpStatus::OK;
failure:
Error(SS_CONNECTION_FAILED);
return stat;
}
void
OpSocksSocket::OnSocketConnected(OpSocket* socket)
{
OP_ASSERT(socket == m_socks_socket);
OP_ASSERT(m_state == SS_SOCKET_TO_SOCKS_CREATED);
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
DEBUG_OUT(this << "->OnSocketConnected");
OP_STATUS stat;
if (g_opera->socks_module.HasUserPassSpecified())
{
UINT8 rq1_data[] = { 5, 2, 0, 2 }; // support 2 methods- <no auth> and <username/password> // ARRAY OK stansialvj 2010-12-01
m_nb_sent_ignore += ARRAY_SIZE(rq1_data);
stat = socket->Send(rq1_data, ARRAY_SIZE(rq1_data));
}
else
{
UINT8 rq1_data[] = { 5, 1, 0 }; // support 1 method- <no auth> // ARRAY OK stansialvj 2010-12-01
m_nb_sent_ignore += ARRAY_SIZE(rq1_data);
stat = socket->Send(rq1_data, ARRAY_SIZE(rq1_data));
}
if (!OpStatus::IsError(stat))
{
DEBUG_OUT(this << " SS_RQ1_SENT");
m_state = SS_RQ1_SENT;
}
else
// in case sending over the m_socks_socket fails, signal it to this socket's listener:
Error(SS_CONNECTION_FAILED);
}
#define NEEDS_NB_INBUF(NBR, BUF) \
{ \
UINT nb_recv = 0, nb_expected = (NBR);\
if (nb_expected) \
{ \
OP_STATUS stat = socket->Recv(buf, nb_expected, &nb_recv); \
if (nb_recv < (NBR) || OpStatus::IsError(stat)) \
return; \
} \
}
void
OpSocksSocket::OnSocketDataReady(OpSocket* socket)
{
OP_ASSERT(socket == m_socks_socket);
OP_STATUS stat = OpStatus::OK;
UINT8 buf[32]; // ARRAY OK stansialvj 2010-12-01
DEBUG_OUT(this << "->DataReady case #" << m_state);
switch (m_state)
{
case SS_SOCKET_TO_SOCKS_CREATED:
OP_ASSERT(!"Unexpected SOCKS socket state"); // ?
// ... are we really meant to fall through here ? or break; ?
case SS_RQ1_SENT:
DEBUG_OUT(this << "->DataReady case SS_RQ1_SENT");
NEEDS_NB_INBUF(2, buf);
if (buf[1] == 0) // <no auth>
{
DEBUG_OUT(this << "->DataReady case SS_RQ1_SENT :> NO auth required");
SocksSendConnectRequest();
}
else if (buf[1] == 2) // <username/password>
{
OP_ASSERT(g_opera->socks_module.HasUserPassSpecified());
const char* user_pass_datagram = g_opera->socks_module.GetUserPassDatagram();
UINT length = g_opera->socks_module.GetUserPassDatagramLength();
m_nb_sent_ignore += length;
stat = socket->Send(user_pass_datagram, length);
if (OpStatus::IsSuccess(stat))
{
DEBUG_OUT(this << "->DataReady case SS_RQ1_SENT :> SS_USERNAME_PASSWORD_SENT");
m_state = SS_USERNAME_PASSWORD_SENT;
}
else
{
// in case sending over the m_socks_socket fails, signal it to this socket's listener:
Error(SS_CONNECTION_FAILED);
}
}
return;
case SS_USERNAME_PASSWORD_SENT:
// Server response should look like this:
// +----+--------+
// |VER | STATUS |
// +----+--------+
// | 1 | 1 |
// +----+--------+
DEBUG_OUT(this << "->DataReady case SS_USERNAME_PASSWORD_SENT");
NEEDS_NB_INBUF(2, buf);
OP_ASSERT(buf[0] == 1);
if (buf[1] != 0)
{
DEBUG_OUT(this << "->DataReady case SS_USERNAME_PASSWORD_SENT: CONNECTION_REFUSED");
Error(SS_AUTH_FAILED);
return;
}
//CONSUME_NBR(2); // consume the top 2 octets
SocksSendConnectRequest();
return;
case SS_TARGET_ADDR_SENT:
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
// where REP is as follows:
// o X'00' succeeded
// o X'01' general SOCKS server failure
// o X'02' connection not allowed by ruleset
// o X'03' Network unreachable
// o X'04' Host unreachable
// o X'05' Connection refused
// o X'06' TTL expired
// o X'07' Command not supported
// o X'08' Address type not supported
// o X'09' to X'FF' unassigned
//
// where ATYP (address type) is as follows:
// o IP V4 address: X'01'
// o DOMAINNAME: X'03'
// o IP V6 address: X'04'
DEBUG_OUT(this << "->DataReady case SS_TARGET_ADDR_SENT");
NEEDS_NB_INBUF(5, buf);
OP_ASSERT(buf[0] == 5);
OP_ASSERT(buf[2] == 0);
UINT rep; rep = buf[1];
if (rep != 0)
{
Error(rep == 2 || rep == 5 ? SS_AUTH_FAILED : SS_CONNECTION_FAILED);
return;
}
m_state = SS_TARGET_CONNECTED;
if (buf[3] == 1) // IPv4 address
{
// 5 left to read -- 3 bytes IPv4 addr left + 2 bytes port left
UINT bytesExpected = 5;
UINT bytesReceived = 0;
buf[0] = buf[4];
stat = socket->Recv(buf+1, bytesExpected, &bytesReceived);
if (OpStatus::IsError(stat) || bytesReceived < bytesExpected) // TODO: we should really wait for more data rather than fail the connection.
goto conn_failed;
if (buf[0] || buf[1] || buf[2] || buf[3])
{
stat = OpSocketAddress::Create(&m_actual_target_address);
if (OpStatus::IsError(stat))
goto conn_failed;
uni_char str[16]; // ARRAY OK stansialvj 2010-12-01
uni_snprintf(str, ARRAY_SIZE(str), UNI_L("%u.%u.%u.%u"), buf[0], buf[1], buf[2], buf[3]);
m_actual_target_address->FromString(str);
m_actual_target_address->SetPort((UINT)(buf[4] << 8) + buf[5]);
DEBUG_OUT(this << "->DataReady case SS_TARGET_CONNECTED: actual target IP: " << str);
}
else
{
DEBUG_OUT(this << "->DataReady case SS_TARGET_CONNECTED: actual target IP: N/A");
}
}
else if (buf[3] == 3) // domain name
{
UINT bytesExpected = buf[4] + 2;
UINT bytesReceived = 0;
char domainName[255+2+1]; // ARRAY OK stansialvj 2010-12-01
stat = socket->Recv(domainName, bytesExpected, &bytesReceived); // buf[4] bytes domain name left + 2 bytes port left
if (OpStatus::IsError(stat) || bytesReceived < bytesExpected) // TODO: we should really wait for more data rather than fail the connection.
goto conn_failed;
stat = OpSocketAddress::Create(&m_actual_target_address);
if (OpStatus::IsError(stat))
goto conn_failed;
OpString16 str;
if (OpStatus::IsError(str.Set(domainName, bytesReceived - 2)))
goto conn_failed;
if (OpStatus::IsError(m_actual_target_address->FromString(str.CStr())))
goto conn_failed;
m_actual_target_address->SetPort((UINT)(domainName[bytesReceived-2] << 8) + domainName[bytesReceived-1]);
DEBUG_OUT(this << "->DataReady case SS_TARGET_CONNECTED: actual target hostname: " << str);
}
else if (buf[3] == 4) // IPv6 ?! just skip -- don't de-serialize
{
UINT bytesExpected = 15 + 2; // 15 bytes left over from the IPv6 addres + 2 bytes port number
UINT bytesReceived = 0;
char ipBuf[15 + 2];
stat = socket->Recv(ipBuf, bytesExpected, &bytesReceived);
if (OpStatus::IsError(stat) || bytesReceived < bytesExpected) // TODO: we should really wait for more data rather than fail the connection.
goto conn_failed;
DEBUG_OUT(this << "->DataReady case SS_TARGET_CONNECTED: but IPv6 ?!");
}
else
{
OP_ASSERT(!"Unexpected fourth byte");
conn_failed:
Error(SS_CONNECTION_FAILED);
return;
}
if (m_listener)
m_listener->OnSocketConnected(this);
return;
default: // unhandled enum case?!!
case SS_CONSTRUCTED:
case SS_AUTH_FAILED:
DEBUG_OUT(this << "->DataReady socket in trouble " << m_target_host);
OP_ASSERT(!"Unexpected SOCKS socket state");
case SS_CONNECTION_FAILED:
case SS_TARGET_CONNECTED:
if (m_listener)
m_listener->OnSocketDataReady(this);
return;
}
}
OP_STATUS
OpSocksSocket::SocksSendConnectRequest()
{
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
if (m_target_port == 0)
{
Error(SS_CONNECTION_FAILED);
return OpStatus::ERR;
}
OpString str_host_name;
OP_STATUS stat = str_host_name.Set(m_target_host);
if (OpStatus::IsError(stat))
{
error:
Error(SS_CONNECTION_FAILED);
return stat;
}
if (0 < str_host_name.FindFirstOf(':')) // IPv6 address is not supported yet
{
stat = OpStatus::ERR;
goto error;
}
INT length = (INT)str_host_name.Length();
INT ndots = 0, last_dot_idx = -1;
UINT8 addr[4]; // ARRAY OK stansialvj 2010-12-01
BOOL is_IPv4_addr = TRUE; // IPv4 address vs. hostname
// If RemoteSocksDNS is enabled we let the proxy handle all IPv4/host name issues.
if (g_pcnet->GetIntegerPref(PrefsCollectionNetwork::RemoteSocksDNS))
is_IPv4_addr = FALSE;
for (INT i = 0; is_IPv4_addr && i < length; ++i)
{
uni_char c = str_host_name.DataPtr()[i];
if (c == '.')
{
if (ndots >= 3 || i - last_dot_idx <= 1) // that's the 4th dot or two conseq dots which *is* a problem
is_IPv4_addr = FALSE;
else
{
str_host_name.DataPtr()[i] = uni_char(0);
addr[ndots++] = uni_atoi(str_host_name.CStr() + last_dot_idx + 1);
str_host_name.DataPtr()[i] = uni_char('.');
last_dot_idx = i;
}
}
else if (c < '0' || '9' < c) // not a digit
is_IPv4_addr = FALSE;
}
if (is_IPv4_addr && ndots != 3 || length - last_dot_idx <= 1)
is_IPv4_addr = FALSE;
UINT port = m_target_port;
UINT8 port_hi = (port >> 8) & 0xff;
UINT8 port_lo = port & 0xff;
if (is_IPv4_addr) // IPv4 address:
{
DEBUG_OUT(this << "->SocksSendConnectRequest target address: " << str_host_name);
addr[3] = uni_atoi(str_host_name.CStr() + last_dot_idx + 1);
UINT8 buf[10] = { 5, 1, 0, 1, addr[0], addr[1], addr[2], addr[3], port_hi, port_lo }; // ARRAY OK stansialvj 2010-12-01
m_nb_sent_ignore += ARRAY_SIZE(buf);
stat = m_socks_socket->Send(buf, ARRAY_SIZE(buf));
}
else
{
if (length > 255)
{
OP_ASSERT(!"Host name is way too long!");
stat = OpStatus::ERR;
goto error;
}
DEBUG_OUT(this << "->SocksSendConnectRequest target name: " << str_host_name);
UINT8 buf[255+8]; // ARRAY OK stansialvj 2010-12-01
UINT8 *put = buf;
*put++ = 5;
*put++ = 1;
*put++ = 0;
*put++ = 3;
*put++ = (UINT8)length;
for (INT i=0; i < length; i++)
*put++ = (UINT8)str_host_name.DataPtr()[i];
*put++ = port_hi;
*put++ = port_lo;
m_nb_sent_ignore += (put - buf);
stat = m_socks_socket->Send(buf, (put - buf));
}
if (OpStatus::IsError(stat))
{
goto error;
}
else
{
DEBUG_OUT(this << "->SocksSendConnectRequest m_state: SS_TARGET_ADDR_SENT");
m_state = SS_TARGET_ADDR_SENT;
}
return stat;
}
OP_STATUS OpSocksSocket::Recv(void* buffer, UINT length, UINT* bytes_received)
{
DEBUG_OUT(this << "->Recv ");
if (m_socks_socket)
return m_socks_socket->Recv(buffer, length, bytes_received);
else
return OpStatus::ERR;
}
OP_STATUS OpSocksSocket::Send(const void* data, UINT length)
{
DEBUG_OUT(this << "->Send (" << length << ")");
if (m_socks_socket)
return m_socks_socket->Send(data, length);
else
return OpStatus::ERR;
}
/** Data has been sent on the socket. */
void OpSocksSocket::OnSocketDataSent(OpSocket* socket, UINT bytes_sent)
{
if (m_nb_sent_ignore >= bytes_sent)
{
m_nb_sent_ignore -= bytes_sent;
return;
}
if (m_nb_sent_ignore > 0)
{
bytes_sent -= m_nb_sent_ignore;
m_nb_sent_ignore = 0;
}
DEBUG_OUT(this << "->OnSocketDataSent (" << bytes_sent << ")");
if (m_listener)
{
m_listener->OnSocketDataSent(this, bytes_sent);
}
else
{
DEBUG_OUT(this << "\t\t... no listener!");
}
}
/** The socket has closed. */
void OpSocksSocket::OnSocketClosed(OpSocket* socket)
{
if (m_listener)
m_listener->OnSocketClosed(this);
m_state = SS_CONNECTION_CLOSED;
}
/** An error has occured on the socket whilst connecting. */
void OpSocksSocket::OnSocketConnectError(OpSocket* socket, OpSocket::Error error)
{
if (m_listener)
m_listener->OnSocketConnectError(this, error);
if (m_state >= 0)
m_state = SS_CONNECTION_FAILED;
}
/** An error has occured on the socket whilst receiving. */
void OpSocksSocket::OnSocketReceiveError(OpSocket* socket, OpSocket::Error error)
{
if (m_listener)
m_listener->OnSocketReceiveError(this, error);
if (m_state >= 0)
m_state = SS_CONNECTION_FAILED;
}
/** An error has occured on the socket whilst sending. */
void OpSocksSocket::OnSocketSendError(OpSocket* socket, OpSocket::Error error)
{
if (m_listener)
m_listener->OnSocketSendError(this, error);
if (m_state >= 0)
m_state = SS_CONNECTION_FAILED;
}
/** An error has occured on the socket whilst closing. */
void OpSocksSocket::OnSocketCloseError(OpSocket* socket, OpSocket::Error error)
{
if (m_listener)
m_listener->OnSocketCloseError(this, error);
if (m_state >= 0)
m_state = SS_CONNECTION_CLOSED;
}
#ifdef SOCKET_LISTEN_SUPPORT
OP_STATUS OpSocksSocket::Listen(OpSocketAddress* socket_address, int queue_size)
{
OP_ASSERT(!"Listen() support not provided with SOCKS");
return OpStatus::ERR_NOT_SUPPORTED;
}
OP_STATUS OpSocksSocket::Accept(OpSocket* socket)
{
OP_ASSERT(!"No SOCKS Listen() support, so how did Accept() get called ?");
return OpStatus::ERR_NOT_SUPPORTED;
}
void OpSocksSocket::OnSocketConnectionRequest(OpSocket* socket)
{
OP_ASSERT(!"No SOCKS Listen() support, so who called OnSocketConnectionRequest() ?");
}
void OpSocksSocket::OnSocketListenError(OpSocket* socket, OpSocket::Error error)
{
OP_ASSERT(!"No SOCKS Listen() support, so who called OnSocketListenError() ?");
}
#endif // SOCKET_LISTEN_SUPPORT
#undef NEEDS_NB_INBUF
#undef LOG_SOCKS_ACTIVITY
#undef DEBUG_OUT
#endif //SOCKS_SUPPORT
|
//
// ArbolBinario.cpp
// Arboles
//
// Created by Daniel on 20/10/14.
// Copyright (c) 2014 Gotomo. All rights reserved.
//
#include "ArbolBinario.h"
|
// Created on: 1994-08-31
// Created by: Jacques GOUSSARD
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Draft_EdgeInfo_HeaderFile
#define _Draft_EdgeInfo_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopoDS_Face.hxx>
#include <gp_Pnt.hxx>
class Geom_Curve;
class Geom2d_Curve;
class Draft_EdgeInfo
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT Draft_EdgeInfo();
Standard_EXPORT Draft_EdgeInfo(const Standard_Boolean HasNewGeometry);
Standard_EXPORT void Add (const TopoDS_Face& F);
Standard_EXPORT void RootFace (const TopoDS_Face& F);
Standard_EXPORT void Tangent (const gp_Pnt& P);
Standard_EXPORT Standard_Boolean IsTangent (gp_Pnt& P) const;
Standard_EXPORT Standard_Boolean NewGeometry() const;
Standard_EXPORT void SetNewGeometry (const Standard_Boolean NewGeom);
Standard_EXPORT const Handle(Geom_Curve)& Geometry() const;
Standard_EXPORT const TopoDS_Face& FirstFace() const;
Standard_EXPORT const TopoDS_Face& SecondFace() const;
Standard_EXPORT const Handle(Geom2d_Curve)& FirstPC() const;
Standard_EXPORT const Handle(Geom2d_Curve)& SecondPC() const;
Standard_EXPORT Handle(Geom_Curve)& ChangeGeometry();
Standard_EXPORT Handle(Geom2d_Curve)& ChangeFirstPC();
Standard_EXPORT Handle(Geom2d_Curve)& ChangeSecondPC();
Standard_EXPORT const TopoDS_Face& RootFace() const;
Standard_EXPORT void Tolerance (const Standard_Real tol);
Standard_EXPORT Standard_Real Tolerance() const;
protected:
private:
Standard_Boolean myNewGeom;
Handle(Geom_Curve) myGeom;
TopoDS_Face myFirstF;
TopoDS_Face mySeconF;
Handle(Geom2d_Curve) myFirstPC;
Handle(Geom2d_Curve) mySeconPC;
TopoDS_Face myRootFace;
Standard_Boolean myTgt;
gp_Pnt myPt;
Standard_Real myTol;
};
#endif // _Draft_EdgeInfo_HeaderFile
|
#include <cstdint>
#include <iostream>
#include <string.h>
#include <vector>
#include <sched.h>
namespace {
class Value {
public:
Value(std::string &f, int64_t v)
: format(f), value(v) {}
std::string format;
int64_t value;
};
#if defined(__i386__)
uint64_t rdtsc() {
uint64_t x;
__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
return x;
}
#elif defined(__x86_64__)
uint64_t rdtsc() {
uint32_t hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ((uint64_t)lo)|(((uint64_t)hi)<<32 );
}
#endif
template<typename T>
uint64_t measure(T code) {
uint64_t a = rdtsc();
code();
uint64_t b = rdtsc();
return (b - a);
}
void run(int loop_count, std::vector<Value> &values) {
char buf[2048];
uint64_t time;
for (int x = 0; x < loop_count; ++x) {
time = measure([=, &buf, &values]() {
for (auto &v : values) {
sprintf(buf, v.format.c_str(), v.value);
}
});
}
std::cout << time << std::endl;
}
}
int main(int argc, char *argv[]) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(0, &mask);
if (sched_setaffinity(0, sizeof(mask), &mask) < 0) {
perror("sched_setaffinity");
}
int loop_count = 1;
if (argc > 1) {
loop_count = atoi(argv[1]);
if (loop_count < 1) {
std::cerr << "Invalid argument: loop counter" << std::endl;
return 1;
}
}
std::vector<Value> values;
std::string line;
std::string format_str;
while (std::cin) {
if (!std::getline(std::cin, format_str))
break;
if (!std::getline(std::cin, line))
break;
uint32_t n = atoi(line.c_str());
int64_t value = 0;
for (uint32_t i = 0; i < n; i++) {
std::getline(std::cin, line);
const char *c = line.c_str();
if (!strncmp("i32:", c, 4)) {
} else if (!strncmp("i64:", c, 4)) {
value = atoll(c+4);
} else if (!strncmp("f64:", c, 4)) {
} else if (!strncmp("str:", c, 4)) {
}
}
values.emplace_back(format_str, value);
}
run(loop_count, values);
return 0;
}
|
#ifndef NODO_H
#define NODO_H
#include <iostream>
using namespace std;
class Nodo
{
private:
int valor;
Nodo* siguiente;
public:
Nodo(int v, Nodo* s = NULL){
valor = v;
siguiente = s;
}
int dameTuValor(void){
return valor;
}
void modificaTuValor(int v){
valor = v;
}
Nodo* dameTuSiguiente(void){
return siguiente;
}
void modificaTuSiguiente(Nodo* s){
siguiente = s;
}
};
#endif // NODO_H
|
#include "talents.hpp"
#include <QDebug>
TalentsGUI::TalentsGUI()
: m_Layout_Talents(new QVBoxLayout)
, m_Layout_TopRow(new QHBoxLayout)
, m_Layout_BottomRow(new QHBoxLayout)
, m_Frame_TopRow(new QFrame)
, m_Frame_BottomRow(new QFrame)
, m_Frame_Talents(new QFrame)
{
initGUI();
}
TalentsGUI::TalentGroup::TalentGroup(QString talentGroupName)
: TalentGroupName(talentGroupName)
, TableWidget(new QTableWidget)
{}
TalentsGUI::Talent::Talent(QString talentName, QString propertieOne, QString propertieTwo, QString propertieThree)
: NameTalent(talentName)
, NamePropertyOne(propertieOne)
, NamePropertyTwo(propertieTwo)
, NamePropertyThree(propertieThree)
, LabelTalent(new QLabel)
, LabelPropertyOne(new QLabel)
, LabelPropertyTwo(new QLabel)
, LabelPropertyThree(new QLabel)
, LCDNumberPropertyOne(new QLCDNumber)
, LCDNumberPropertyTwo(new QLCDNumber)
, LCDNumberPropertyThree(new QLCDNumber)
, SpinBox(new MySpinBox)
, TableWidget(new QTableWidget)
{}
void TalentsGUI::initTalentGroup() {
m_TalentGUI.insert(std::make_pair(GESELLSCHAFTSTALENTE, TalentGroup("Gesellschaftstalente")));
m_TalentGUI.insert(std::make_pair(HANDWERKSTALENTE, TalentGroup("Handwerkstalente")));
m_TalentGUI.insert(std::make_pair(KOERPERTALENTE, TalentGroup("Körpertalente")));
m_TalentGUI.insert(std::make_pair(KRIEGSKUNSTTALENTE, TalentGroup("Kriegskunsttalente")));
m_TalentGUI.insert(std::make_pair(NATURTALENTE, TalentGroup("Naturtalente")));
m_TalentGUI.insert(std::make_pair(WISSENSTALENTE, TalentGroup("Wissenstalente")));
setTalentData(GESELLSCHAFTSTALENTE);
setTalentData(HANDWERKSTALENTE);
setTalentData(KOERPERTALENTE);
setTalentData(KRIEGSKUNSTTALENTE);
setTalentData(NATURTALENTE);
setTalentData(WISSENSTALENTE);
}
void TalentsGUI::initLabel() {
for(auto& varOne : m_TalentGUI)
{
for(Talent& talentData : varOne.second.Data)
{
talentData.LabelTalent->setText(talentData.NameTalent);
talentData.LabelPropertyOne->setText(talentData.NamePropertyOne);
talentData.LabelPropertyTwo->setText(talentData.NamePropertyTwo);
talentData.LabelPropertyThree->setText(talentData.NamePropertyThree);
talentData.LabelTalent->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
talentData.LabelPropertyOne->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
talentData.LabelPropertyTwo->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
talentData.LabelPropertyThree->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
}
}
}
void TalentsGUI::initSpinbox() {
for(auto varOne : m_TalentGUI) {
for(Talent& talentData : varOne.second.Data) {
talentData.SpinBox->setRange(0, 99);
talentData.SpinBox->setFocusPolicy(Qt::StrongFocus);
talentData.SpinBox->setFont(QFont("Times New Roman", 16, QFont::Bold));
}
}
}
void TalentsGUI::initTableTalentData() {
for(auto& varOne : m_TalentGUI)
{
for (Talent& talentData : varOne.second.Data) {
setTableTalentData(talentData.TableWidget, 5, 2);
addLabelToTalentDataTable(talentData.TableWidget, {talentData.LabelTalent, talentData.LabelPropertyOne,
talentData.LabelPropertyTwo, talentData.LabelPropertyThree});
addLCDNumberToTalentDataTable(talentData.TableWidget, {talentData.LCDNumberPropertyOne,
talentData.LCDNumberPropertyTwo, talentData.LCDNumberPropertyThree});
addSpinBoxToTalentDataTable(talentData.TableWidget, talentData.SpinBox);
mergeTalentDataTableCells(talentData.TableWidget);
}
}
}
void TalentsGUI::initTableTalentGroup() {
int row = 0;
for (auto varOne : m_TalentGUI) {
setTableTalentGroup(varOne.second.TableWidget, {varOne.second.TalentGroupName}, varOne.second.Data.size());
for (Talent& talentData : varOne.second.Data) {
addTalentDataToTalentGroupTable(varOne.second.TableWidget, talentData.TableWidget, row);
++row;
}
row = 0;
}
}
void TalentsGUI::initGUI() {
initTalentGroup();
initLabel();
initSpinbox();
initTableTalentData();
initTableTalentGroup();
m_Layout_TopRow->addWidget(m_TalentGUI.at(HANDWERKSTALENTE).TableWidget);
m_Layout_TopRow->addWidget(m_TalentGUI.at(KOERPERTALENTE).TableWidget);
m_Layout_TopRow->addWidget(m_TalentGUI.at(WISSENSTALENTE).TableWidget);
m_Layout_BottomRow->addWidget(m_TalentGUI.at(GESELLSCHAFTSTALENTE).TableWidget);
m_Layout_BottomRow->addWidget(m_TalentGUI.at(KRIEGSKUNSTTALENTE).TableWidget);
m_Layout_BottomRow->addWidget(m_TalentGUI.at(NATURTALENTE).TableWidget);
m_Layout_Talents->addWidget(m_Frame_TopRow);
m_Layout_Talents->addWidget(m_Frame_BottomRow);
m_Frame_TopRow->setLayout(m_Layout_TopRow);
m_Frame_BottomRow->setLayout(m_Layout_BottomRow);
m_Frame_Talents->setLayout(m_Layout_Talents);
}
void TalentsGUI::setTalentData(TalentGroupNames talentGroupName) {
switch (talentGroupName) {
case GESELLSCHAFTSTALENTE: {
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Betören", "MU", "CH", "SE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Diplomatie", "CH", "KL", "SE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Einschüchtern", "MU", "IN", "KK"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Etikette", "KL", "IN", "CH"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Gassenwissen", "KL", "IN", "CH"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Handeln", "CH", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Menschenkenntnis", "KL", "IN", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Singen", "CH", "KL", "KO"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Überreden", "CH", "KL", "IN"));
break;
}
case HANDWERKSTALENTE: {
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Heilkunde Handwerk", "KL", "GE", "MU"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Holzbearbeitung", "GE", "KK", "GE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Kochen", "IN", "GE", "KL"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Lederbearbeitung", "GE", "IN", "GE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Malen & Zeichnen", "IN", "GE", "KL"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Mechanik", "KL", "GE", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Metallbearbeitung", "GE", "KO", "KK"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Musizieren", "CH", "GE", "KL"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Steinbearbeitung", "GE", "GE", "KK"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Stoffbearbeitung", "GE", "IN", "KL"));
break;
}
case KOERPERTALENTE: {
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Fesseln", "KL", "GE", "KK"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Fliegen", "MU", "IN", "GE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Gaukeleien", "GE", "CH", "KO"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Klettern", "KK", "KO", "MU"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Körperbeherrschung", "GE", "KO", "KK"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Kraftakt", "KK", "KO", "KK"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Reiten", "GE", "KO", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Schwimmen", "KO", "MU", "GE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Taschendiebstahl", "MU", "GE", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Zechen", "SE", "KO", "KL"));
break;
}
case KRIEGSKUNSTTALENTE: {
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Ausbildung", "KL", "CH", "SE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Belagern", "KL", "IN", "MU"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Fernkämpfer führen", "MU", "IN", "CH"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("GeoStrategien", "KL", "IN", "MU"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Infanterie führen", "MU", "IN", "CH"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Kavalerie führen", "MU", "IN", "CH"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Logistik", "KL", "IN", "KL"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Waffenkunde", "KL", "KL", "IN"));
break;
}
case NATURTALENTE: {
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Fährtensuche", "IN", "KL", "SE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Fallenstellen", "GE", "IN", "KK"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Fischen", "SE", "GE", "KL"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Jagdstrategien", "KL", "IN", "MU"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Orientiereung", "IN", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Verstohlenheit", "KL", "IN", "GE"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Wildnisleben", "IN", "KL", "MU"));
break;
}
case WISSENSTALENTE: {
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Dynastiekunde", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Flora & Fauna", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Geographie", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Geschichtswissen", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Götter & Kulte", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Heilkundewissen", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Legenden", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Magiekunde", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Rechtskunde", "KL", "KL", "IN"));
m_TalentGUI.at(talentGroupName).Data.push_back(Talent("Sternenkunde", "KL", "KL", "IN"));
break;
}
default: {
break;
}
}
}
void TalentsGUI::setTableTalentData(QTableWidget* obj, int columns, int rows) {
obj->verticalHeader()->setVisible(false);
obj->horizontalHeader()->setVisible(false);
obj->setColumnCount(columns);
obj->setRowCount(rows);
for (int var = 0; var < columns; ++var)
{
if(var == 0) {
obj->setColumnWidth(var, 160);
}
else if((columns - var) == 1) {
obj->setColumnWidth(var, 50);
}
else {
obj->setColumnWidth(var, 40);
}
}
for (int var = 0; var < rows; ++var) {
obj->setRowHeight(var, 25);
}
obj->setSelectionMode(QTableWidget::NoSelection);
obj->setFocusPolicy(Qt::NoFocus);
}
void TalentsGUI::setTableTalentGroup(QTableWidget* obj, QStringList header, int rows) {
obj->verticalHeader()->setVisible(false);
obj->setColumnCount(1);
obj->setRowCount(rows);
obj->setHorizontalHeaderLabels(header);
obj->horizontalHeader()->setFont(QFont("Times New Roman", 14, QFont::Bold));
obj->setColumnWidth(0, 350);
for (int var = 0; var < obj->rowCount(); ++var) {
obj->setRowHeight(var, 54);
}
obj->setFixedSize(345, 350);
obj->setFont(QFont("Times New Roman", 12, QFont::Bold));
}
void TalentsGUI::setPropertyValues(int ch, int ge, int in, int kk, int kl, int ko, int mu, int se) {
for (auto var : m_TalentGUI) {
for (Talent talentData : var.second.Data) {
checkPropertyType(talentData.LabelPropertyOne, talentData.LCDNumberPropertyOne, {ch, ge, in, kk, kl, ko, mu, se});
checkPropertyType(talentData.LabelPropertyTwo, talentData.LCDNumberPropertyTwo, {ch, ge, in, kk, kl, ko, mu, se});
checkPropertyType(talentData.LabelPropertyThree, talentData.LCDNumberPropertyThree, {ch, ge, in, kk, kl, ko, mu, se});
}
}
}
void TalentsGUI::checkPropertyType(QLabel* property, QLCDNumber* display, std::vector<int> values) {
if(property->text() == "CH") {
display->setDigitCount(values.at(0));
}
else if(property->text() == "GE") {
display->setDigitCount(values.at(1));
}
else if(property->text() == "IN") {
display->setDigitCount(values.at(2));
}
else if(property->text() == "KK") {
display->setDigitCount(values.at(3));
}
else if(property->text() == "KL") {
display->setDigitCount(values.at(4));
}
else if(property->text() == "KO") {
display->setDigitCount(values.at(5));
}
else if(property->text() == "MU") {
display->setDigitCount(values.at(6));
}
else if(property->text() == "SE") {
display->setDigitCount(values.at(7));
}
}
void TalentsGUI::addLabelToTalentDataTable(QTableWidget* obj, std::vector<QLabel*> label) {
if(obj->columnCount()-1 == (int)label.size()) {
for (int var = 0; var < obj->columnCount()-1; ++var) {
obj->setCellWidget(0, var, label.at(var));
}
}
}
void TalentsGUI::addLCDNumberToTalentDataTable(QTableWidget* obj, std::vector<QLCDNumber*> lcdNumber) {
if(obj->columnCount()-2 == (int)lcdNumber.size()) {
for (int var = 0; var < (int)lcdNumber.size(); ++var) {
lcdNumber.at(var)->setDigitCount(2);
lcdNumber.at(var)->setSegmentStyle(QLCDNumber::Flat);
obj->setCellWidget(1, var+1, lcdNumber.at(var));
}
}
}
void TalentsGUI::addSpinBoxToTalentDataTable(QTableWidget* obj, QSpinBox* spinBox) {
obj->setCellWidget(0, obj->columnCount()-1, spinBox);
}
void TalentsGUI::addTalentDataToTalentGroupTable(QTableWidget* obj, QTableWidget* talentData, int row) {
if(row <= obj->rowCount()) {
obj->setCellWidget(row, 0, talentData);
}
}
void TalentsGUI::mergeTalentDataTableCells(QTableWidget *obj) {
obj->setSpan(0, 0, 2, 1);
obj->setSpan(0, obj->columnCount()-1, 2, 1);
}
QFrame* TalentsGUI::getFrame() const {
return m_Frame_Talents;
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
#define debug(x) std::cerr << (x) << std::endl;
#define roll(x) for (auto itr : x) { debug(itr); }
int rev(int x) {
int t = 0, ten = 1;
vector<int> v;
while (x > 0) { v.push_back(x % 10); x /= 10; }
for (int i = 0; i < v.size() - 1; ++i) {
ten *= 10;
}
for (int i = 0; i < v.size(); ++i) {
t += v.at(i) * ten;
ten /= 10;
}
return t;
}
vector< vector<int> > G;
int main() {
const int MAX = 1000;
int N, M; cin >> N >> M;
int V = MAX * MAX;
G.assign(V, vector<int>());
vector<int> deg(V, 0);
for (int x = 1; x < MAX; ++x) {
for (int y = 1; y < MAX; ++y) {
int nx = x, ny = y;
if (x < y) nx = rev(x);
else ny = rev(y);
if (nx < ny) ny -= nx;
else nx -= ny;
int from = x * MAX + y;
int to = nx * MAX + ny;
G[to].push_back(from);
deg[from] += 1;
}
}
queue<int> que;
vector<int> seen(V, 0);
for (int v = 0; v < V; ++v) if (deg[v] == 0) que.push(v);
while (!que.empty()) {
auto v = que.front(); que.pop();
seen[v] = true;
for (auto nv : G[v]) {
if (seen[nv]) continue;
--deg[nv];
if (deg[nv] == 0) que.push(nv);
}
}
// 答え
int res = 0;
for (int x = 1; x <= N; ++x) {
for (int y = 1; y <= M; ++y) {
int id = x * MAX + y;
if (!seen[id]) ++res;
}
}
cout << res << endl;
}
|
#include<iostream>
#include<vector>
using namespace std;
int main(void){
double d = 98.25;
vector<int> result;
vector<int> result_d;
int a = floor(d);
double b = d - a;
int op;
while(a){
op = a % 2;
a = a / 2;
result.push_back(op);
}
while(b){
op = floor(b * 2);
b = b*2 - op;
result_d.push_back(op);
}
if(result[result.size()-1]) cout << result[result.size()-1];
for(int i=result.size()-2;i>=0;i--)
cout << result[i];
cout << ".";
for(int i=0;i<result_d.size();i++)
cout<<result[i];
return 0;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Engine/GameInstance.h"
#include "OnlineSubsystem.h"
#include "OnlineSessionInterface.h"
#include "MenuSystem/MenuInterface.h"
#include "ArenaNetGameInstance.generated.h"
/**
*
*/
UCLASS()
class UNREALNETARENA_API UArenaNetGameInstance : public UGameInstance, public IMenuInterface
{
GENERATED_BODY()
public:
UArenaNetGameInstance(const FObjectInitializer &ObjectInitializer);
virtual void Init() override;
UFUNCTION(BlueprintCallable)
void LoadMenuWidget();
UFUNCTION(BlueprintCallable)
void InGameLoadMenu();
void StartSession();
UFUNCTION(Exec)
virtual void Host(FString serverName) override;
UFUNCTION(Exec)
virtual void Join(uint32 serverIndex) override;
virtual void LoadMainMenu() override;
virtual void RefreshServerList() override;
private:
TSubclassOf<class UUserWidget> MenuClass;
class UMainMenu* Menu;
TSubclassOf<class UUserWidget> InGameMenuClass;
IOnlineSessionPtr SessionInterface;
TSharedPtr<class FOnlineSessionSearch> SessionSearch;
void OnCreateSessionComplete(FName sessionName, bool success);
void OnDestroySessionComplete(FName sessionName, bool success);
void OnFindSessionsComplete(bool success);
void OnJoinSessionComplete(FName sessionName, EOnJoinSessionCompleteResult::Type joinResult);
FString DesiredServerName;
void CreateSession();
};
|
#pragma once
#include "Interface/IRuntimeModule.h"
namespace Rocket
{
Interface IMemoryManager : inheritance IRuntimeModule
{
public:
IMemoryManager() = default;
virtual ~IMemoryManager() = default;
virtual void* AllocatePage(size_t size) = 0;
virtual void FreePage(void* p) = 0;
};
}
|
//////////////////////
//My name in "fade".//
//////////////////////
#include "stdafx.h"
#include "Fade.h"
Fade::Fade()
{
m_black = NewGO<SpriteRender>(31, "sp");
m_black->Init(L"Assets/sprite/fade_black.dds", 1280,720);
m_black->SetMulCol(m_mulcol);
}
void Fade::OnDestroy()
{
DeleteGO(m_black);
}
void Fade::Update()
{
switch (m_state)
{
case enFadein:
{
float add = m_speed * IGameTime().GetFrameDeltaTime();
m_mulcol.w -= add;
if (m_mulcol.w <= 0)
{
m_mulcol.w = 0;
m_state = enFadeStop;
}
m_black->SetMulCol(m_mulcol);
}
break;
case enFadeout:
{
float add = m_speed * IGameTime().GetFrameDeltaTime();
m_mulcol.w += add;
if (m_mulcol.w >= 1)
{
m_mulcol.w = 1;
m_state = enFadeStop;
}
m_black->SetMulCol(m_mulcol);
break;
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* 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 Anders Karlsson (pugo)
*/
#ifndef POSTSCRIPT_VEGA_PRINTER_LISTENER_H
#define POSTSCRIPT_VEGA_PRINTER_LISTENER_H
#ifdef VEGA_POSTSCRIPT_PRINTING
#ifdef VEGA_PRINTER_LISTENER_SUPPORT
#include "modules/libvega/src/oppainter/vegaprinterlistener.h"
#include "modules/util/opfile/opfile.h"
#include "modules/libvega/src/postscript/postscriptprolog.h"
#include "modules/libvega/src/postscript/postscriptbody.h"
class OpFileDescriptor;
class PostScriptBody;
class VEGAPath;
class VEGAStencil;
/** @brief Helper class that generates PostScript image data
*/
class PostScriptVEGAPrinterListener : public VEGAPrinterListener
{
public:
PostScriptVEGAPrinterListener(OpFile& file);
OP_STATUS Init(PostScriptOutputMetrics* screen_metrics, PostScriptOutputMetrics* paper_metrics);
virtual void SetClipRect(const OpRect& clip);
virtual void SetColor(UINT8 red, UINT8 green, UINT8 blue, UINT8 alpha);
/**
sets current_font to font - use updateFont to set current_font as used
*/
virtual void SetFont(OpFont* font);
virtual void DrawRect(const OpRect& rect, UINT32 width);
virtual void FillRect(const OpRect& rect);
virtual void DrawEllipse(const OpRect& rect, UINT32 width);
virtual void FillEllipse(const OpRect& rect);
virtual void FillPath(VEGAPath *path, VEGAStencil *stencil);
virtual void DrawLine(const OpPoint& from, const OpPoint& to, UINT32 width);
virtual void DrawString(const OpPoint& pos, const uni_char* text, UINT32 len, INT32 extra_char_spacing, short word_width);
virtual void DrawBitmapClipped(const OpBitmap* bitmap, const OpRect& source, OpPoint p);
OP_STATUS startPage();
OP_STATUS endPage();
void printFinished();
void printAborted();
private:
void DrawString(const OpPoint& pos, const struct ProcessedString* processed_string);
void DrawPath(VEGAPath *path);
void AddLineToPath(VEGA_FIX* line, int& curpos_x, int& curpos_y);
/**
calls updateFont, and on success returns prolog.getCurrentFontConverter()
*/
TrueTypeConverter* getFontConverter();
/**
changes the currently used font (used_font) to current_font
@return OpStatus::OK on success, OpStatus::ERR on failure, OpStatus::ERR_NO_MEMORY on OOM
*/
OP_STATUS updateFont();
void updateColor();
OP_STATUS concatenatePostScriptParts();
PostScriptOutputMetrics* screen_metrics;
PostScriptOutputMetrics* paper_metrics;
OpFile& destination_file;
OpFile body_temp_file;
PostScriptProlog prolog;
PostScriptBody body;
OpRect current_cliprect;
UINT32 current_color;
UINT32 used_color;
OpFont* current_font; ///< font currently set with setFont
OpFont* used_font; ///< font currently in use
};
#endif // VEGA_PRINTER_LISTENER_SUPPORT
#endif // VEGA_POSTSCRIPT_PRINTING
#endif // POSTSCRIPT_VEGA_PRINTER_LISTENER_H
|
/**********************************************************************
*Project : EngineTask
*
*Author : Jorge Cásedas
*
*Starting date : 24/06/2020
*
*Ending date : 03/07/2020
*
*Purpose : Creating a 3D engine that can be used later on for developing a playable demo, with the engine as static library
*
**********************************************************************/
#pragma once
namespace engine
{
class EntityTask;
class RenderTask;
class InputTask;
class MessageBus;
///
/// Class in charge of managing all the tasks
///
class Kernel
{
EntityTask* entityTask;
RenderTask* renderTask;
InputTask* inputTask;
MessageBus* messageBus;
public:
Kernel(EntityTask* _entityTask, RenderTask* _renderTask, InputTask* _inputTask, MessageBus* _messageBus);
void Update();
};
}
|
#include <fstream>
#include <iostream>
#include <vector>
#include <assert.h>
#include <string>
#include "openAddress.cpp"
using namespace std;
int main ()
{
ifstream read;
vector <string> dict;
read.open("dict.txt");
while(!read.eof())
{
string Buffer;
getline(read,Buffer,'\n');
dict.push_back(Buffer);
}
read.close();
int test = 0;
OpenAddress Dictionary(34);
long tableSize = Dictionary.getSize();
for(int i = 0 ; i < dict.size() ; i++)
{
Dictionary.insertItem(dict[i]);
string result = Dictionary.lookUp(dict[i]);
if(result == dict[i])
{
cout << result << endl;
test++;
}
}
long newSize = Dictionary.getSize();
assert(test == dict.size());
assert(newSize > tableSize);
cout << "Everything Works!" << endl;
return 0;
}
|
/*
* Copyright [2017] <Bonn-Rhein-Sieg University>
*
* Author: Torsten Jandt
*
*/
#include <mir_planner_executor/actions/executor_action.h>
#include <ros/console.h>
void ExecutorAction::initialize(KnowledgeUpdater* knowledge_updater) {
knowledge_updater_ = knowledge_updater;
}
|
class Convolution{
private:
// ATTRIBUTES
int method;
int convKernel[3][3];
// CONTRUCTORS
Convolution(){
method = 0;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
convKernel[i][j] = 0;
}
}
}
public:
void convolute(int **input, int **output, int **kernel){
int convolute = 0; // This holds the convolution results for an index.
int x, y; // Used for input matrix index
// Fill output matrix: rows and columns are i and j respectively
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
x = i;
y = j;
// Kernel rows and columns are k and l respectively
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
// Convolute here.
convolute += kernel[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j; // Restart column position
}
output[i][j] = convolute; // Add result to output matrix.
convolute = 0; // Needed before we move on to the next index.
}
}
}
void setKernel(int **kernel, int kernelsize){
for (int i = 0; i < kernelsize; i++){
for (int j = 0; j < kernelsize; j++){
convKernel[i][j] = kernel[i][j];
}
}
}
};
|
#ifndef DMA_H
#define DMA_H
/*
* DMA.h
*
* Used to define the DMA: allows devices to stream data directly from RAM
* CPU --write--> DMA --command--> (GPU/SPU/MDEC..)
*/
// includes
#include <Memory.h>
#include <vector>
// all devices which have a DMA channel inherit from this class.
class dmaDevice
{
public:
virtual void wordFromDMA(word in) = 0;
virtual word wordToDMA() = 0;
virtual void executeCommand() = 0;
};
// channel for individual device
class dmaChannel
{
// some sort of device access.
dmaDevice* device;
RAMImpl* main_ram;
// address where reading begins
unsigned base_address;
// number and size of blocks to transfer
word block_control;
// channel control
union {
struct {
unsigned transfer_direction : 1;
unsigned mem_address_step : 1;
unsigned : 6;
unsigned chopping : 1;
unsigned sync_mode : 2;
unsigned : 5;
unsigned chop_dma_window_size : 3;
unsigned : 1;
unsigned chop_cpu_window_size : 3;
unsigned : 1;
unsigned start_busy : 1;
unsigned : 3;
unsigned start_trigger : 1;
unsigned : 3;
} bit_fields;
word data_field;
} channel_control;
bool transfer_direction;
bool mem_address_step;
bool chopping;
unsigned sync_mode;
unsigned chop_dma_window_size;
unsigned chop_cpu_window_size;
bool start_busy;
bool start_trigger;
public:
dmaChannel(dmaDevice* device_ptr, RAMImpl* ram_ptr) :
device(device_ptr), main_ram(ram_ptr) {}
// transfers a block between RAM and device
void transferBlock();
/*enum DMAReg
{
DMABase = 0,
DMABlockControl = 1,
DMAChannelControl = 2
};*/
// write base address, block control or channel control.
void writeRegister(word data, unsigned reg);
// read base address, block control or channel control.
word readRegister(unsigned reg);
private:
// transfers a single word from RAM, into device
void transferWordFromRAM();
// transfers a single word from device, into RAM
void transferWordToRAM();
};
// dma will be accessed through memBus
// this works out which channel to send/receive data
class dma : public memoryInterface
{
std::vector<dmaChannel> channel_list;
word control_reg;
word interrupt_reg;
public:
// constructor creates dmaChannel for each device
dma(RAMImpl* main_ram, std::vector<dmaDevice*>& devices);
// memoryInterface functions
word readWord(unsigned address) override;
void writeWord(unsigned address, word in) override;
private:
// main interface functions: these are mapped from memoryInterface functions
// these set registers and can trigger DMA channels to go active
inline word readRegister(unsigned address)
{
unsigned device = (address * 4) & 0xFF;
if ((device < 0xF0) && (device >= 0x80))
return channel_list[device - 8].readRegister(address % 0x3);
else if (device == 0xF0)
return control_reg;
else if (device == 0xF4)
return interrupt_reg;
// exception? idk.
else
return 0;
}
inline void writeRegister(unsigned address, word in)
{
unsigned device = address & 0xFF;
if ((device < 0xF0) && (device >= 0x80))
channel_list[device - 8].writeRegister(in, address % 0x3);
else if (device == 0xF0)
control_reg = in;
else if (device == 0xF4)
interrupt_reg = in;
}
};
#endif
|
//
// C++ Implementation: UdpData
//
// Description:
//
//
// Author: cwll <cwll2009@126.com> ,(C)2012
// Jally <jallyx@163.com>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
// 2012.02 在接收消息中去掉了群组模式,群组模式只用来发消息
//
#include "config.h"
#include "UdpData.h"
#include "ProgramData.h"
#include "CoreThread.h"
#include "MainWindow.h"
#include "DialogPeer.h"
#include "DialogGroup.h"
#include "SoundSystem.h"
#include "Command.h"
#include "RecvFile.h"
#include "SendFile.h"
#include "wrapper.h"
#include "dialog.h"
#include "utils.h"
extern ProgramData progdt;
extern CoreThread cthrd;
extern MainWindow mwin;
extern SoundSystem sndsys;
/**
* 类构造函数.
*/
UdpData::UdpData():ipv4(0), size(0), encode(NULL)
{
}
/**
* 类析构函数.
*/
UdpData::~UdpData()
{
g_free(encode);
}
/**
* UDP数据解析入口.
* @param ipv4 ipv4
* @param buf[] 数据缓冲区
* @param size 数据有效长度
*/
void UdpData::UdpDataEntry(in_addr_t ipv4, const char buf[], size_t size)
{
UdpData udata;
udata.ipv4 = ipv4;
udata.size = size < MAX_UDPLEN ? size : MAX_UDPLEN;
memcpy(udata.buf, buf, size);
if (size != MAX_UDPLEN)
udata.buf[size] = '\0';
udata.DispatchUdpData();
}
/**
* 分派UDP数据到相应的函数去进行处理.
*/
void UdpData::DispatchUdpData()
{
uint32_t commandno;
/* 如果开启了黑名单处理功能,且此地址正好被列入了黑名单 */
/* 嘿嘿,那就不要怪偶心狠手辣了 */
if (FLAG_ISSET(progdt.flags, 1) && cthrd.BlacklistContainItem(ipv4))
return;
/* 决定消息去向 */
commandno = iptux_get_dec_number(buf, ':', 4);
switch (GET_MODE(commandno)) {
case IPMSG_BR_ENTRY:
SomeoneEntry();
break;
case IPMSG_BR_EXIT:
SomeoneExit();
break;
case IPMSG_ANSENTRY:
SomeoneAnsentry();
break;
case IPMSG_BR_ABSENCE:
SomeoneAbsence();
break;
case IPMSG_SENDMSG:
SomeoneSendmsg();
break;
case IPMSG_RECVMSG:
SomeoneRecvmsg();
break;
case IPTUX_ASKSHARED:
SomeoneAskShared();
break;
case IPTUX_SENDICON:
SomeoneSendIcon();
break;
case IPTUX_SENDSIGN:
SomeoneSendSign();
break;
case IPTUX_SENDMSG:
SomeoneBcstmsg();
break;
default:
break;
}
}
/**
* 好友信息数据丢失默认处理函数.
* 若xx并不在好友列表中,但是程序却期望能够接受xx的本次会话,
* 所以必须以默认数据构建好友信息数据并插入好友列表 \n
*/
void UdpData::SomeoneLost()
{
PalInfo *pal;
/* 创建好友数据 */
pal = new PalInfo;
pal->ipv4 = ipv4;
pal->segdes = progdt.FindNetSegDescription(ipv4);
if (!(pal->version = iptux_get_section_string(buf, ':', 0)))
pal->version = g_strdup("?");
if (!(pal->user = iptux_get_section_string(buf, ':', 2)))
pal->user = g_strdup("???");
if (!(pal->host = iptux_get_section_string(buf, ':', 3)))
pal->host = g_strdup("???");
pal->name = g_strdup(_("mysterious"));
pal->group = g_strdup(_("mysterious"));
pal->photo = NULL;
pal->sign = NULL;
pal->iconfile = g_strdup(progdt.palicon);
pal->encode = g_strdup(encode ? encode : "utf-8");
FLAG_SET(pal->flags, 1);
pal->packetn = 0;
pal->rpacketn = 0;
/* 加入好友列表 */
gdk_threads_enter();
pthread_mutex_lock(cthrd.GetMutex());
cthrd.AttachPalToList(pal);
pthread_mutex_unlock(cthrd.GetMutex());
mwin.AttachItemToPaltree(ipv4);
gdk_threads_leave();
}
/**
* 好友上线.
*/
void UdpData::SomeoneEntry()
{
Command cmd;
pthread_t pid;
PalInfo *pal;
/* 转换缓冲区数据编码 */
ConvertEncode(progdt.encode);
/* 加入或更新好友列表 */
gdk_threads_enter();
pthread_mutex_lock(cthrd.GetMutex());
if ( (pal = cthrd.GetPalFromList(ipv4))) {
UpdatePalInfo(pal);
cthrd.UpdatePalToList(ipv4);
} else {
pal = CreatePalInfo();
cthrd.AttachPalToList(pal);
}
pthread_mutex_unlock(cthrd.GetMutex());
if (mwin.PaltreeContainItem(ipv4))
mwin.UpdateItemToPaltree(ipv4);
else
mwin.AttachItemToPaltree(ipv4);
gdk_threads_leave();
/* 通知好友本大爷在线 */
cmd.SendAnsentry(cthrd.UdpSockQuote(), pal);
if (FLAG_ISSET(pal->flags, 0)) {
pthread_create(&pid, NULL, ThreadFunc(CoreThread::SendFeatureData), pal);
pthread_detach(pid);
}
}
/**
* 好友退出.
*/
void UdpData::SomeoneExit()
{
PalInfo *pal;
/* 从好友链表中删除 */
gdk_threads_enter();
if (mwin.PaltreeContainItem(ipv4))
mwin.DelItemFromPaltree(ipv4);
pthread_mutex_lock(cthrd.GetMutex());
if ( (pal = cthrd.GetPalFromList(ipv4))) {
cthrd.DelPalFromList(ipv4);
FLAG_CLR(pal->flags, 1);
}
pthread_mutex_unlock(cthrd.GetMutex());
gdk_threads_leave();
}
/**
* 好友在线.
*/
void UdpData::SomeoneAnsentry()
{
Command cmd;
pthread_t pid;
PalInfo *pal;
const char *ptr;
/* 若好友不兼容iptux协议,则需转码 */
ptr = iptux_skip_string(buf, size, 3);
if (!ptr || *ptr == '\0')
ConvertEncode(progdt.encode);
/* 加入或更新好友列表 */
gdk_threads_enter();
pthread_mutex_lock(cthrd.GetMutex());
if ( (pal = cthrd.GetPalFromList(ipv4))) {
UpdatePalInfo(pal);
cthrd.UpdatePalToList(ipv4);
} else {
pal = CreatePalInfo();
cthrd.AttachPalToList(pal);
}
pthread_mutex_unlock(cthrd.GetMutex());
if (mwin.PaltreeContainItem(ipv4))
mwin.UpdateItemToPaltree(ipv4);
else
mwin.AttachItemToPaltree(ipv4);
gdk_threads_leave();
/* 更新本大爷的数据信息 */
if (FLAG_ISSET(pal->flags, 0)) {
pthread_create(&pid, NULL, ThreadFunc(CoreThread::SendFeatureData), pal);
pthread_detach(pid);
} else if (strcasecmp(progdt.encode, pal->encode) != 0)
cmd.SendAnsentry(cthrd.UdpSockQuote(), pal);
}
/**
* 好友更改个人信息.
*/
void UdpData::SomeoneAbsence()
{
PalInfo *pal;
const char *ptr;
/* 若好友不兼容iptux协议,则需转码 */
pal = cthrd.GetPalFromList(ipv4); //利用好友链表只增不减的特性,无须加锁
ptr = iptux_skip_string(buf, size, 3);
if (!ptr || *ptr == '\0')
ConvertEncode(pal ? pal->encode : progdt.encode);
/* 加入或更新好友列表 */
gdk_threads_enter();
pthread_mutex_lock(cthrd.GetMutex());
if (pal) {
UpdatePalInfo(pal);
cthrd.UpdatePalToList(ipv4);
} else {
pal = CreatePalInfo();
cthrd.AttachPalToList(pal);
}
pthread_mutex_unlock(cthrd.GetMutex());
if (mwin.PaltreeContainItem(ipv4))
mwin.UpdateItemToPaltree(ipv4);
else
mwin.AttachItemToPaltree(ipv4);
gdk_threads_leave();
}
/**
* 好友发送消息.
*
*/
void UdpData::SomeoneSendmsg()
{
GroupInfo *grpinf;
PalInfo *pal;
Command cmd;
uint32_t commandno, packetno;
char *text;
pthread_t pid;
DialogPeer *dlgpr;
GtkWidget *window;
/* 如果对方兼容iptux协议,则无须再转换编码 */
pal = cthrd.GetPalFromList(ipv4);
if (!pal || !FLAG_ISSET(pal->flags, 0))
ConvertEncode(pal ? pal->encode : progdt.encode);
/* 确保好友在线,并对编码作出适当调整 */
pal = AssertPalOnline();
if (strcasecmp(pal->encode, encode ? encode : "utf-8") != 0) {
g_free(pal->encode);
pal->encode = g_strdup(encode ? encode : "utf-8");
}
/* 回复好友并检查此消息是否过时 */
commandno = iptux_get_dec_number(buf, ':', 4);
packetno = iptux_get_dec_number(buf, ':', 1);
if (commandno & IPMSG_SENDCHECKOPT)
cmd.SendReply(cthrd.UdpSockQuote(), pal, packetno);
if (packetno <= pal->packetn)
return;
pal->packetn = packetno;
/* 插入消息&在消息队列中注册 */
text = ipmsg_get_attach(buf, ':', 5);
if (text && *text != '\0') {
/*/* 插入消息 */
// if ((commandno & IPMSG_BROADCASTOPT) || (commandno & IPMSG_MULTICASTOPT))
// InsertMessage(pal, GROUP_BELONG_TYPE_BROADCAST, text);
// else
InsertMessage(pal, GROUP_BELONG_TYPE_REGULAR, text);
}
g_free(text);
/*/* 注册消息 */
pthread_mutex_lock(cthrd.GetMutex());
// if ((commandno & IPMSG_BROADCASTOPT) || (commandno & IPMSG_MULTICASTOPT))
// grpinf = cthrd.GetPalBroadcastItem(pal);
// else
grpinf = cthrd.GetPalRegularItem(pal);
if (!grpinf->dialog && !cthrd.MsglineContainItem(grpinf))
cthrd.PushItemToMsgline(grpinf);
pthread_mutex_unlock(cthrd.GetMutex());
/* 标记位处理 先处理底层数据,后面显示窗口*/
if (commandno & IPMSG_FILEATTACHOPT) {
if ((commandno & IPTUX_SHAREDOPT) && (commandno & IPTUX_PASSWDOPT)) {
pthread_create(&pid, NULL, ThreadFunc(ThreadAskSharedPasswd), pal);
pthread_detach(pid);
} else
RecvPalFile();
}
window = GTK_WIDGET(grpinf->dialog);
//这里不知道为什么运行时一直会提示window不是object
dlgpr = (DialogPeer *)(g_object_get_data(G_OBJECT(window),"dialog"));
if(grpinf->dialog)
dlgpr->ShowDialogPeer(dlgpr);
/* 是否直接弹出聊天窗口 */
if (FLAG_ISSET(progdt.flags, 7)) {
gdk_threads_enter();
if (!(grpinf->dialog)) {
// switch (grpinf->type) {
// case GROUP_BELONG_TYPE_REGULAR:
DialogPeer::PeerDialogEntry(grpinf);
// break;
// case GROUP_BELONG_TYPE_SEGMENT:
// case GROUP_BELONG_TYPE_GROUP:
// case GROUP_BELONG_TYPE_BROADCAST:
// DialogGroup::GroupDialogEntry(grpinf);
// default:
// break;
// }
} else {
gtk_window_present(GTK_WINDOW(grpinf->dialog));
}
gdk_threads_leave();
}
/* 播放提示音 */
if (FLAG_ISSET(progdt.sndfgs, 1))
sndsys.Playing(progdt.msgtip);
}
/**
* 好友接收到消息.
*/
void UdpData::SomeoneRecvmsg()
{
uint32_t packetno;
PalInfo *pal;
if ( (pal = cthrd.GetPalFromList(ipv4))) {
packetno = iptux_get_dec_number(buf, ':', 5);
if (packetno == pal->rpacketn)
pal->rpacketn = 0; //标记此包编号已经被回复
}
}
/**
* 好友请求本计算机的共享文件.
*/
void UdpData::SomeoneAskShared()
{
Command cmd;
pthread_t pid;
PalInfo *pal;
const char *limit;
char *passwd;
if (!(pal = cthrd.GetPalFromList(ipv4)))
return;
limit = cthrd.GetAccessPublicLimit();
if (!limit || *limit == '\0') {
pthread_create(&pid, NULL, ThreadFunc(ThreadAskSharedFile), pal);
pthread_detach(pid);
} else if (!(iptux_get_dec_number(buf, ':', 4) & IPTUX_PASSWDOPT)) {
cmd.SendFileInfo(cthrd.UdpSockQuote(), pal,
IPTUX_SHAREDOPT | IPTUX_PASSWDOPT, "");
} else if ( (passwd = ipmsg_get_attach(buf, ':', 5))) {
if (strcmp(passwd, limit) == 0) {
pthread_create(&pid, NULL, ThreadFunc(ThreadAskSharedFile), pal);
pthread_detach(pid);
}
g_free(passwd);
}
}
/**
* 好友发送头像数据.
*/
void UdpData::SomeoneSendIcon()
{
PalInfo *pal;
char *iconfile;
if (!(pal = cthrd.GetPalFromList(ipv4)) || FLAG_ISSET(pal->flags, 2))
return;
/* 接收并更新数据 */
if ( (iconfile = RecvPalIcon())) {
g_free(pal->iconfile);
pal->iconfile = iconfile;
gdk_threads_enter();
pthread_mutex_lock(cthrd.GetMutex());
cthrd.UpdatePalToList(ipv4);
pthread_mutex_unlock(cthrd.GetMutex());
mwin.UpdateItemToPaltree(ipv4);
gdk_threads_leave();
}
}
/**
* 好友发送个性签名.
*/
void UdpData::SomeoneSendSign()
{
PalInfo *pal;
char *sign;
if (!(pal = cthrd.GetPalFromList(ipv4)))
return;
/* 若好友不兼容iptux协议,则需转码 */
if (!FLAG_ISSET(pal->flags, 0))
ConvertEncode(pal->encode);
/* 对编码作适当调整 */
if (strcasecmp(pal->encode, encode ? encode : "utf-8") != 0) {
g_free(pal->encode);
pal->encode = g_strdup(encode ? encode : "utf-8");
}
/* 更新 */
if ( (sign = ipmsg_get_attach(buf, ':', 5))) {
g_free(pal->sign);
pal->sign = sign;
gdk_threads_enter();
pthread_mutex_lock(cthrd.GetMutex());
cthrd.UpdatePalToList(ipv4);
pthread_mutex_unlock(cthrd.GetMutex());
mwin.UpdateItemToPaltree(ipv4);
gdk_threads_leave();
}
}
/**
* 好友广播消息.
*/
void UdpData::SomeoneBcstmsg()
{
GroupInfo *grpinf;
PalInfo *pal;
uint32_t commandno, packetno;
char *text;
/* 如果对方兼容iptux协议,则无须再转换编码 */
pal = cthrd.GetPalFromList(ipv4);
if (!pal || !FLAG_ISSET(pal->flags, 0))
ConvertEncode(pal ? pal->encode : progdt.encode);
/* 确保好友在线,并对编码作出适当调整 */
pal = AssertPalOnline();
if (strcasecmp(pal->encode, encode ? encode : "utf-8") != 0) {
g_free(pal->encode);
pal->encode = g_strdup(encode ? encode : "utf-8");
}
/* 检查此消息是否过时 */
packetno = iptux_get_dec_number(buf, ':', 1);
if (packetno <= pal->packetn)
return;
pal->packetn = packetno;
/* 插入消息&在消息队列中注册 */
text = ipmsg_get_attach(buf, ':', 5);
if (text && *text != '\0') {
commandno = iptux_get_dec_number(buf, ':', 4);
/*/* 插入消息 */
switch (GET_OPT(commandno)) {
case IPTUX_BROADCASTOPT:
InsertMessage(pal, GROUP_BELONG_TYPE_BROADCAST, text);
break;
case IPTUX_GROUPOPT:
InsertMessage(pal, GROUP_BELONG_TYPE_GROUP, text);
break;
case IPTUX_SEGMENTOPT:
InsertMessage(pal, GROUP_BELONG_TYPE_SEGMENT, text);
break;
case IPTUX_REGULAROPT:
default:
InsertMessage(pal, GROUP_BELONG_TYPE_REGULAR, text);
break;
}
/*/* 注册消息 */
pthread_mutex_lock(cthrd.GetMutex());
switch (GET_OPT(commandno)) {
case IPTUX_BROADCASTOPT:
grpinf = cthrd.GetPalBroadcastItem(pal);
break;
case IPTUX_GROUPOPT:
grpinf = cthrd.GetPalGroupItem(pal);
break;
case IPTUX_SEGMENTOPT:
grpinf = cthrd.GetPalSegmentItem(pal);
break;
case IPTUX_REGULAROPT:
default:
grpinf = cthrd.GetPalRegularItem(pal);
break;
}
if (!grpinf->dialog && !cthrd.MsglineContainItem(grpinf))
cthrd.PushItemToMsgline(grpinf);
pthread_mutex_unlock(cthrd.GetMutex());
}
g_free(text);
/* 播放提示音 */
if (FLAG_ISSET(progdt.sndfgs, 1))
sndsys.Playing(progdt.msgtip);
}
/**
* 创建好友信息数据.
* @return 好友数据
*/
PalInfo *UdpData::CreatePalInfo()
{
PalInfo *pal;
pal = new PalInfo;
pal->ipv4 = ipv4;
pal->segdes = progdt.FindNetSegDescription(ipv4);
if (!(pal->version = iptux_get_section_string(buf, ':', 0)))
pal->version = g_strdup("?");
if (!(pal->user = iptux_get_section_string(buf, ':', 2)))
pal->user = g_strdup("???");
if (!(pal->host = iptux_get_section_string(buf, ':', 3)))
pal->host = g_strdup("???");
if (!(pal->name = ipmsg_get_attach(buf, ':', 5)))
pal->name = g_strdup(_("mysterious"));
pal->group = GetPalGroup();
pal->photo = NULL;
pal->sign = NULL;
if (!(pal->iconfile = GetPalIcon()))
pal->iconfile = g_strdup(progdt.palicon);
if ( (pal->encode = GetPalEncode()))
FLAG_SET(pal->flags, 0);
else
pal->encode = g_strdup(encode ? encode : "utf-8");
FLAG_SET(pal->flags, 1);
pal->packetn = 0;
pal->rpacketn = 0;
return pal;
}
/**
* 更新好友信息数据.
* @param pal 好友数据
*/
void UdpData::UpdatePalInfo(PalInfo *pal)
{
g_free(pal->segdes);
pal->segdes = progdt.FindNetSegDescription(ipv4);
g_free(pal->version);
if (!(pal->version = iptux_get_section_string(buf, ':', 0)))
pal->version = g_strdup("?");
g_free(pal->user);
if (!(pal->user = iptux_get_section_string(buf, ':', 2)))
pal->user = g_strdup("???");
g_free(pal->host);
if (!(pal->host = iptux_get_section_string(buf, ':', 3)))
pal->host = g_strdup("???");
if (!FLAG_ISSET(pal->flags, 2)) {
g_free(pal->name);
if (!(pal->name = ipmsg_get_attach(buf, ':', 5)))
pal->name = g_strdup(_("mysterious"));
g_free(pal->group);
pal->group = GetPalGroup();
g_free(pal->iconfile);
if (!(pal->iconfile = GetPalIcon()))
pal->iconfile = g_strdup(progdt.palicon);
FLAG_CLR(pal->flags, 0);
g_free(pal->encode);
if ( (pal->encode = GetPalEncode()))
FLAG_SET(pal->flags, 0);
else
pal->encode = g_strdup(encode ? encode : "utf-8");
}
FLAG_SET(pal->flags, 1);
pal->packetn = 0;
pal->rpacketn = 0;
}
/**
* 插入消息.
* @param pal class PalInfo
* @param btype 消息所属类型
* @param msg 消息
*/
void UdpData::InsertMessage(PalInfo *pal, GroupBelongType btype, const char *msg)
{
MsgPara para;
ChipData *chip;
/* 构建消息封装包 */
para.pal = pal;
para.stype = MESSAGE_SOURCE_TYPE_PAL;
para.btype = btype;
chip = new ChipData;
chip->type = MESSAGE_CONTENT_TYPE_STRING;
chip->data = g_strdup(msg);
para.dtlist = g_slist_append(NULL, chip);
/* 交给某人处理吧 */
cthrd.InsertMessage(¶);
}
/**
* 将缓冲区中的数据转换为utf8编码.
* @param enc 原数据首选编码
*/
void UdpData::ConvertEncode(const char *enc)
{
char *ptr;
size_t len;
/* 将缓冲区内有效的'\0'字符转换为ASCII字符 */
ptr = buf + strlen(buf) + 1;
while ((size_t)(ptr - buf) <= size) {
*(ptr - 1) = NULL_OBJECT;
ptr += strlen(ptr) + 1;
}
/* 转换字符集编码 */
/**
* @note 请不要采用以下做法,它在某些环境下将导致致命错误: \n
* if (g_utf8_validate(buf, -1, NULL)) {encode = g_strdup("utf-8")} \n
* e.g. 系统编码为GB18030的xx发送来纯ASCII字符串 \n
*/
if (enc && strcasecmp(enc, "utf-8") != 0
&& (ptr = convert_encode(buf, "utf-8", enc)))
encode = g_strdup(enc);
else
ptr = iptux_string_validate(buf, progdt.codeset, &encode);
if (ptr) {
len = strlen(ptr);
size = len < MAX_UDPLEN ? len : MAX_UDPLEN;
memcpy(buf, ptr, size);
if (size < MAX_UDPLEN)
buf[size] = '\0';
g_free(ptr);
}
/* 将缓冲区内的ASCII字符还原为'\0'字符 */
ptr = buf;
while ( (ptr = (char *)memchr(ptr, NULL_OBJECT, buf + size - ptr))) {
*ptr = '\0';
ptr++;
}
}
/**
* 获取好友群组名称.
* @return 群组
*/
char *UdpData::GetPalGroup()
{
const char *ptr;
if ((ptr = iptux_skip_string(buf, size, 1)) && *ptr != '\0')
return g_strdup(ptr);
return NULL;
}
/**
* 获取好友头像图标.
* @return 头像
*/
char *UdpData::GetPalIcon()
{
char path[MAX_PATHLEN];
const char *ptr;
if ((ptr = iptux_skip_string(buf, size, 2)) && *ptr != '\0') {
snprintf(path, MAX_PATHLEN, __PIXMAPS_PATH "/icon/%s", ptr);
if (access(path, F_OK) == 0)
return g_strdup(ptr);
}
return NULL;
}
/**
* 获取好友系统编码.
* @return 编码
*/
char *UdpData::GetPalEncode()
{
const char *ptr;
if ((ptr = iptux_skip_string(buf, size, 3)) && *ptr != '\0')
return g_strdup(ptr);
return NULL;
}
/**
* 接收好友头像数据.
* @return 头像文件名
*/
char *UdpData::RecvPalIcon()
{
GdkPixbuf *pixbuf;
char path[MAX_PATHLEN];
char *iconfile;
size_t len;
int fd;
/* 若无头像数据则返回null */
if ((len = strlen(buf) + 1) >= size)
return NULL;
/* 将头像数据刷入磁盘 */
snprintf(path, MAX_PATHLEN, "%s" ICON_PATH "/%" PRIx32,
g_get_user_cache_dir(), ipv4);
if ((fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1)
return NULL;
xwrite(fd, buf + len, size - len);
close(fd);
/* 将头像pixbuf加入内建 */
iconfile = NULL;
gdk_threads_enter();
if ( (pixbuf = gdk_pixbuf_new_from_file(path, NULL))) {
iconfile = g_strdup_printf("%" PRIx32, ipv4);
gtk_icon_theme_add_builtin_icon(iconfile, MAX_ICONSIZE, pixbuf);
g_object_unref(pixbuf);
}
gdk_threads_leave();
return iconfile;
}
/**
* 确保好友一定在线.
* @return 好友数据
*/
PalInfo *UdpData::AssertPalOnline()
{
PalInfo *pal;
if ( (pal = cthrd.GetPalFromList(ipv4))) {
/* 既然好友不在线,那么他自然不在列表中 */
if (!FLAG_ISSET(pal->flags, 1)) {
FLAG_SET(pal->flags, 1);
gdk_threads_enter();
pthread_mutex_lock(cthrd.GetMutex());
cthrd.UpdatePalToList(ipv4);
pthread_mutex_unlock(cthrd.GetMutex());
mwin.AttachItemToPaltree(ipv4);
gdk_threads_leave();
}
} else {
SomeoneLost();
pal = cthrd.GetPalFromList(ipv4);
}
return pal;
}
/**
* 接收好友文件信息.
*/
void UdpData::RecvPalFile()
{
uint32_t packetno, commandno;
const char *ptr;
pthread_t pid;
GData *para;
packetno = iptux_get_dec_number(buf, ':', 1);
commandno = iptux_get_dec_number(buf, ':', 4);
ptr = iptux_skip_string(buf, size, 1);
/* 只有当此为共享文件信息或文件信息不为空才需要接收 */
if ((commandno & IPTUX_SHAREDOPT) || (ptr && *ptr != '\0')) {
para = NULL;
g_datalist_init(¶);
g_datalist_set_data(¶, "palinfo", cthrd.GetPalFromList(ipv4));
g_datalist_set_data_full(¶, "extra-data", g_strdup(ptr),
GDestroyNotify(g_free));
g_datalist_set_data(¶, "packetno", GUINT_TO_POINTER(packetno));
g_datalist_set_data(¶, "commandno", GUINT_TO_POINTER(commandno));
pthread_create(&pid, NULL, ThreadFunc(RecvFile::RecvEntry), para);
pthread_detach(pid);
}
}
/**
* 请求获取好友共享文件的密码.
* @param pal class PalInfo
*/
void UdpData::ThreadAskSharedPasswd(PalInfo *pal)
{
Command cmd;
gchar *passwd, *epasswd;
gdk_threads_enter();
passwd = pop_obtain_shared_passwd(pal);
gdk_threads_leave();
if (passwd && *passwd != '\0') {
epasswd = g_base64_encode((guchar *)passwd, strlen(passwd));
cmd.SendAskShared(cthrd.UdpSockQuote(), pal, IPTUX_PASSWDOPT, epasswd);
g_free(epasswd);
}
g_free(passwd);
}
/**
* 某好友请求本计算机的共享文件.
* @param pal class PalInfo
*/
void UdpData::ThreadAskSharedFile(PalInfo *pal)
{
SendFile sfile;
bool permit;
if (FLAG_ISSET(progdt.flags, 0)) {
gdk_threads_enter();
permit = pop_request_shared_file(pal);
gdk_threads_leave();
if (permit)
sfile.SendSharedInfoEntry(pal);
} else
sfile.SendSharedInfoEntry(pal);
}
|
#include "../headers/Window.h"
/* Constructor por defecto. */
Window::Window():pWindow(NULL){
}
/* Este metodo podria borrarse y pasar todo su codigo al constructor de Window. Ver después.
* @return: true si salió todo bien (que debería ser siempre)
*/
bool Window::Create(const char* title, int width, int height){
/* Clavo este assert acá para evitar crear la ventana dos veces. */
assert(!pWindow);
pWindow = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN);
this->width = width;
this->height = height;
return true;
}
/* Destructor */
Window::~Window(){
if(pWindow)
SDL_DestroyWindow(pWindow);
}
|
#include "core.h"
void ArrayOut(int size, double* array)
{
cout << "Array: ";
for (int i = 0; i < size; i++)
cout << array[i] << ' ';
cout << endl;
}
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void leftviewprint(struct node *root,int level,int *max_level);
struct node
{
struct node *left;
struct node *right;
int data;
};
struct node *newnode(int a)
{
struct node *n = (struct node *)malloc(sizeof(struct node));
n->data = a;
n->left = n->right = NULL;
return n;
}
void printtree(struct node *root)
{
if(root==NULL)
return;
else
{
printtree(root->left);
printf("%d",root->data);
printtree(root->right);
}
}
void leftview(struct node *root)
{
int max_level = 0;
leftviewprint(root,1,&max_level);
}
void leftviewprint(struct node *root,int level,int *max_level)
{
if(root == NULL)
return;
if(*max_level <level)
{
printf("%d",root->data);
*max_level = level;
}
leftviewprint(root->left,level+1,max_level);
leftviewprint(root->right,level+1,max_level);
}
int main()
{
struct node *root = newnode(12);
root->left = newnode(10);
root->right = newnode(30);
root->right->left = newnode(25);
root->right->right = newnode(40);
printtree(root);
printf("\n");
leftview(root);
getch();
}
|
// #include <stdio.h>
// #include <unistd.h>
// #include <string.h>
// #include <sys/socket.h>
// #include <arpa/inet.h>
// #include <openssl/ssl.h>
// #include <openssl/err.h>
// #include <iostream>
// //https://security.stackexchange.com/questions/90422/ssl-certificates-and-cipher-suites-correspondence
// int create_socket(int port)
// {
// int s;
// struct sockaddr_in addr;
// addr.sin_family = AF_INET;
// addr.sin_port = htons(port);
// addr.sin_addr.s_addr = htonl(INADDR_ANY);
// s = socket(AF_INET, SOCK_STREAM, 0);
// bind(s, (struct sockaddr *)&addr, sizeof(addr));
// listen(s, 1);
// return s;
// }
// void cleanup_openssl()
// {
// EVP_cleanup();
// }
// int main(int argc, char **argv)
// {
// SSL_load_error_strings();
// OpenSSL_add_ssl_algorithms();
// const SSL_METHOD *method = TLS_server_method();
// SSL_CTX *ctx = SSL_CTX_new(method);
// SSL_CTX_set_min_proto_version(ctx, TLS1_1_VERSION);
// SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
// SSL_CTX_set_cipher_list(ctx, "TLS13-AES-256-GCM-SHA384");
// SSL_CTX_set_ecdh_auto(ctx, 1);
// SSL_CTX_use_certificate_file(ctx, "certificate.pem", SSL_FILETYPE_PEM);
// SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM);
// SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, [](int, X509_STORE_CTX *) {
// printf("Verifying.");
// return 1;
// });
// const int sock = create_socket(4443);
// const char reply[] = "test\n";
// while (1)
// {
// int client = accept(sock, nullptr, nullptr);
// SSL *ssl = SSL_new(ctx);
// SSL_set_fd(ssl, client);
// std::cout << "Server Ciphers" << std::endl;
// auto ciphers = SSL_get_ciphers(ssl);
// while (auto top = sk_SSL_CIPHER_pop(ciphers))
// {
// std::cout << SSL_CIPHER_get_name(top) << " " << SSL_CIPHER_get_id(top) << std::endl;
// }
// const auto accepted = SSL_accept(ssl);
// ERR_print_errors_fp(stderr);
// std::cout << "Accepted:" << accepted << std::endl;
// std::cout << "Client Ciphers" << std::endl;
// ciphers = SSL_get_client_ciphers(ssl);
// while (auto top = sk_SSL_CIPHER_pop(ciphers))
// {
// std::cout << SSL_CIPHER_get_name(top) << " " << SSL_CIPHER_get_id(top) << std::endl;
// }
// SSL_write(ssl, reply, strlen(reply));
// SSL_shutdown(ssl);
// SSL_free(ssl);
// close(client);
// std::cout << "Closed" << std::endl;
// }
// close(sock);
// SSL_CTX_free(ctx);
// cleanup_openssl();
// }
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <iostream>
int create_socket(int port)
{
int s;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0)
{
perror("Unable to create socket");
exit(EXIT_FAILURE);
}
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("Unable to bind");
exit(EXIT_FAILURE);
}
if (listen(s, 1) < 0)
{
perror("Unable to listen");
exit(EXIT_FAILURE);
}
return s;
}
void cleanup_openssl()
{
EVP_cleanup();
}
int main(int argc, char **argv)
{
int sock;
SSL_load_error_strings();
// OpenSSL_add_ssl_algorithms();
const SSL_METHOD *method = TLS_server_method();
SSL_CTX *ctx = SSL_CTX_new(method);
SSL_CTX_set_cipher_list(ctx, "TLS13-AES-256-GCM-SHA384");
SSL_CTX_set_ecdh_auto(ctx, 1);
SSL_CTX_use_certificate_file(ctx, "certificate.pem", SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM);
sock = create_socket(4443);
while (1)
{
int client = accept(sock, nullptr, nullptr);
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, client);
SSL_accept(ssl);
//https://www.openssl.org/docs/man1.1.0/man3/SSL_get_current_cipher.html
// const auto ciphers = SSL_get_client_ciphers(ssl);
// while (const auto cipher = sk_SSL_CIPHER_pop(ciphers))
// {
// std::cout << "Cipher: " << SSL_CIPHER_get_name(cipher) << std::endl;
// }
const auto current_cipher = SSL_get_current_cipher(ssl);
std::cout << "Current: " << SSL_CIPHER_get_name(current_cipher) << std::endl;
const char reply[] = "test\n";
SSL_write(ssl, reply, strlen(reply));
SSL_shutdown(ssl);
SSL_free(ssl);
close(client);
}
close(sock);
SSL_CTX_free(ctx);
cleanup_openssl();
}
|
#pragma once
#include <vector>
#include <SDL2/SDL_image.h>
#include "fwd.hpp"
#include "engine/graphics/PhysicsObject.hpp"
#include "engine/net/ServerNet.hpp"
#include "engine/net/ClientNet.hpp"
using namespace std;
enum FLOOR_TYPE{
GRASS,
STONE
};
enum WALL_TYPE{
ORANGE,
BROWN,
SILVER,
SILVER_FILLED
};
class TileMap
{
private:
LTexture* gTileSheet;
pthread_mutex_t mutex1;
// Different map styles
int floor_type = GRASS;
int wall_type = BROWN;
vector<Entity> floor;
vector<RigidBody> walls;
// To get the position in source to clip from
bool getWhenZero(int i,vector<int> zero, vector<int> one);
void getTileClip(int bitmask, SDL_Rect& clip);
// generate the vector of 0s and 1s denoting w=positions with walls
void generateMap();
void generateMap1(double density);
// generate floors and walls
void generateTiles();
public:
TileMap(ClientNet* client, ServerNet* server);
~TileMap();
bool loadTexture();
vector<vector<bool>> map;
void render();
void generateTiles(ServerNet* server);
void handleCollisions(KinematicBody* body);
void handleThrowables(Throwable* x);
void updateMapfromServer(vector<int> map_vec);
bool getMap(int i, int j);
void setMap(int i, int j, bool val);
void initializeMap(int i, int j);
pair<int, int> getMapSize();
void cloneMap(vector<vector<bool>> &vec_to_clone);
void sendMapToClient(ServerNet* server);
};
|
#ifndef VLEX_TOKEN_H
#define VLEX_TOKEN_H 1
#include <string>
#include <FlexLexer.h>
namespace vlex{
struct YYSTYPE{
int pos;
int ival;
std::string sval;
};
extern YYSTYPE yylval;
extern yyFlexLexer *lexer;
const int ID = 257;
const int STRING = 258;
const int INT = 259;
const int COMMA = 260;
const int COLON = 261;
const int SEMICOLON = 262;
const int LPAREN = 263;
const int RPAREN = 264;
const int LBRACK = 265;
const int RBRACK = 266;
const int LBRACE = 267;
const int RBRACE = 268;
const int DOT = 269;
const int PLUS = 270;
const int MINUS = 271;
const int TIMES = 272;
const int DIVIDE = 273;
const int EQ = 274;
const int NEQ = 275;
const int LT = 276;
const int LE = 277;
const int GT = 278;
const int GE = 279;
const int AND = 280;
const int OR = 281;
const int ASSIGN = 282;
const int ARRAY = 283;
const int IF = 284;
const int THEN = 285;
const int ELSE = 286;
const int WHILE = 287;
const int FOR = 288;
const int TO = 289;
const int DO = 290;
const int LET = 291;
const int IN = 292;
const int END = 293;
const int OF = 294;
const int BREAK = 295;
const int NIL = 296;
const int FUNCTION = 297;
const int VAR = 298;
const int TYPE = 299;
}// namespace vlex
#endif
|
#ifndef APRIORI_H
#define APRIORI_H
#include <bitset>
#include <vector>
const int MAX_ITEM_LEN_ = 100;
const int MAX_INPUT_LINE_ = 3200;
using namespace std;
using std::bitset;
class Apriori
{
private:
bitset<MAX_ITEM_LEN_> data[MAX_INPUT_LINE_];
vector<bitset<MAX_ITEM_LEN_>> L1_item;
vector<int> L1_sup;
double min_sup;
int ans;
public:
Apriori(bitset<MAX_ITEM_LEN_> input[], int line_ans, double sup);
~Apriori();
void genL1();
void genLk(vector<bitset<MAX_ITEM_LEN_>> Lk_1, int num);
void getResult();
};
#endif
|
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
const int INF = 987654321;
string N;
// N[a..b] 구간의 난이도를 반환한다.
int classify(int a, int b){
// 숫자 조작을 가져온다.
string M = N.substr(a, b-a+1);
// 첫글자만으로 이루어진 문자열과 같으면 난이도는 1
if(M == string(M.size(), M[0])) return 1;
// 등차수열인지 검사
bool progressive = true;
for(int i = 0; i< M.size()-1; i++){
if(M[i+1] - M[i] != M[1] - M[0]){
progressive = false;
}
}
// 등차수열이고 공차가 1 혹은 -1이면 난이도는 2
if(progressive && abs(M[1] - M[0]) == 1){
return 2;
}
// 두 수가 번갈아 등장하는지 확인
bool alternating = true;
for(int i = 0; i < M.size(); i++){
if(M[i] != M[i%2]){
alternating = false;
}
}
if(alternating) return 4;
if(progressive) return 5;
return 10;
}
int cache[10002];
// 수열 N[begin..]을 외우는 방법 중 난이도의 최소 합을 출력
int memorize(int begin){
// 기저사례: 수열의 끝에 도달했을 경우
if(begin == N.size()) return 0;
// 메모이제이션
int& ret = cache[begin];
if(ret != -1) return ret;
ret = INF;
for(int L = 3; L <= 5; L++){
if(begin + L <= N.size()){
ret = min(ret, memorize(begin+L) + classify(begin, begin + L -1));
}
}
return ret;
}
int main(){
int numTest;
int answer;
cin >> numTest;
while(numTest--){
cin >> N;
if(N.length() < 8 || N.length() > 10000){
cout << "입력 케이스 길이 오류, 8 <= x <= 100000" << endl;
return -1;
}
memset(cache, -1, sizeof(cache));
answer = memorize(0);
cout << answer << endl;
}
return 0;
}
|
#include <thread>
#include <vector>
#include <iostream>
std::mutex g_m;
thread_local int counter = 0;
void func1() {
std::lock_guard<std::mutex> lck{g_m};
std::cout << "thread " << std::this_thread::get_id() << " counter address "
<< &counter << std::endl;
}
void test() {
std::mutex mmm;
try {
mmm.lock();
mmm.lock();
} catch (std::system_error& e) {
mmm.unlock();
std::cout << e.what() << "\n";
std::cout << e.what() << "\n";
}
}
int main() {
std::vector<std::thread> threads;
for (int i=0; i<10; ++i) {
threads.push_back(std::thread{func1});
}
for (auto& t : threads)
t.join();
test();
return 0;
}
|
// This example illustates basic use of the NMEA library.
// It assumes that a GPS receiver is connected to serial
// port 'Serial1' at 4800 bps, and that a LED is connected
// to digital i/o pin 0.
//
// A GPS data connection of type GPRMC is created, and
// used to get position information. When the GPS position
// is in the state of Colorado (USA), the LED lights up,
// otherwise it is off.
#include <nmea.h>
// create a GPS data connection to GPRMC sentence type
NMEA gps(GPRMC);
void setup() {
Serial1.begin(4800);
pinMode(0, OUTPUT);
}
void loop() {
if (Serial1.available() > 0 ) {
// read incoming character from GPS
char c = Serial1.read();
// check if the character completes a valid GPS sentence
if (gps.decode(c)) {
// check if GPS positioning was active
if (gps.gprmc_status() == 'A') {
// check if you are in Colorado, USA
boolean inColorado = (gps.gprmc_latitude() > 37.0)
&& (gps.gprmc_latitude() < 41.0)
&& (gps.gprmc_longitude() < -102.05)
&& (gps.gprmc_longitude() > -109.05);
// set led accordingly
if (inColorado) {
digitalWrite(0, HIGH);
} else {
digitalWrite(0, LOW);
}
}
}
}
}
|
#pragma once
namespace jstexture
{
void init();
}
|
#pragma once
#include "x/x_platform.h"
namespace x
{
class X_API x_Android : public x_Platform
{
public:
x_Android();
virtual ~x_Android();
x_Bool createWindow(x_String windowTitle, x_Sint32 width, x_Sint32 height);
void destroyWindow();
x_Sint32 messagePump();
x_WindowHandler getWindowHandler();
void setWindowHandler(x_WindowHandler windowHandler);
x_DeviceContextHandler getDeviceContextHandler();
void setDeviceContextHandler(x_DeviceContextHandler deviceContextHandler);
};
}
|
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
string DEFAULT_HOST = "localhost";
int DEFAULT_PORT = 10036;
double DEFAULT_GREMLIN_COR = 0.0;
double DEFAULT_GREMLIN_DRO = 0.0;
double DEFAULT_GREMLIN_DEL = 0.0;
int DEFAULT_GREMLIN_DEL_T = 0;
string DEFAULT_REQUEST_FILE = "{put your files here}";
string DEFAULT_OUT_FILE = "{put your html files here}";
string args[] = {};
map<string, vector<string>> params = parseCommandArgs(args);
if (tolower(params.get("run").get(0)).equals("server"))
{
Server udpServer = initServer(params);
udpServer.listen();
}
else if (tolower(params.get("run").get(0)).equals("client"))
{
Client udpClient = initClient(params);
udpClient.get();
}
else
{
cout << ("Flags improperly set please use -run client or -run server");
}
}
Client initClient(map<string, vector<string>> params)
{
int port = DEFAULT_PORT;
string host = DEFAULT_HOST;
double gremlin_cor = DEFAULT_GREMLIN_COR;
double gremlin_dro = DEFAULT_GREMLIN_DRO;
double gremlin_del = DEFAULT_GREMLIN_DEL;
int gremlin_del_t = DEFAULT_GREMLIN_DEL_T;
string requestFile = DEFAULT_REQUEST_FILE;
string outFile = DEFAULT_OUT_FILE;
if (params.findKey("port"))
{
port = int(params.get("port").get(0));
}
if (params.findKey("host"))
{
host = params.get("host").get(0);
}
if (params.findKey("gremlin_cor"))
{
gremlin_cor = double(params.get("gremlin_cor").get(0));
}
if (params.findKey("gremlin_dro"))
{
gremlin_dro = double(params.get("gremlin_dro").get(0));
}
if (params.findKey("gremlin_del"))
{
gremlin_del = double(params.get("gremlin_del").get(0));
}
if (params.findKey("gremlin_del_t"))
{
gremlin_del_t = int(params.get("gremlin_del_t").get(0));
}
if (params.findKey("rfile"))
{
requestFile = params.get("rfile").get(0);
}
if (params.findKey("ofile"))
{
outFile = params.get("ofile").get(0);
}
return new Client(port, host, gremlin_cor, gremlin_dro, gremlin_del, gremlin_del_t, requestFile, outFile);
}
Server initServer(map<string, vector<string>> params)
{
int port = DEFAULT_PORT;
string host = DEFAULT_HOST;
if (params.findKey("port"))
{
port = int(params.get("port").get(0));
}
if (params.containsKey("host"))
{
host = params.get("host").get(0);
}
return Server(port, host);
}
map<string, vector<string>> parseCommandArgs(string args[])
{
map<string, vector<string>> out = map<string, vector<string>>();
vector<string> options;
for (string a : args)
{
if (a.at(0) == '-')
{
if (a.length() < 2)
{
cout << ("Error at argument " + a);
return out;
}
options = vector<string>();
out.put(a.substring(1), options);
}
else if (options != null)
{
options.add(a);
}
else
{
cout << "Illegal parameter usage. Use '-run server' or '-run client'";
return out;
}
}
return out;
}
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <iostream>
#include "mp3manager.h"
#include "mp3filemanager.h"
#include "taglib/taglib/tag.h"
#include "bass/bass.h"
#include <string>
#include "mp3player.h"
#include <thread>
#include <vector>
#include <QTimer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void slotTimerAlarm();
private slots:
void on_volumeSlider_valueChanged(int value);
private slots:
void on_positionSlider_sliderMoved(int position);
private slots:
void on_positionSlider_valueChanged(int value);
private slots:
void on_positionSlider_sliderReleased();
private slots:
void on_positionSlider_sliderPressed();
private slots:
void on_playButton_clicked();
private slots:
void on_searchButton_clicked();
private slots:
void on_songList_doubleClicked(const QModelIndex &index);
private slots:
void on_addPathButton_clicked();
private slots:
void on_loadButton_clicked();
private slots:
void on_saveButton_clicked();
private:
Ui::MainWindow *ui;
mp3FileManager fManager;
mp3Manager manager;
mp3Player player;
void updateList(vector<song>);
vector<song> currentSongs;
QTimer *timer;
void mySliderValueChanged(int newPos);
};
#endif // MAINWINDOW_H
|
#include ".\waypoint.h"
#include "graphics.h"
#include "input.h"
extern Input *input;
Waypoint::Waypoint(void)
{
type = E_WAYPOINT;
family = EF_ENVIRONMENT;
}
Waypoint::~Waypoint(void)
{
}
void Waypoint::render() {
if (input->inputContext == EditMode) {
glPushAttrib(GL_ALL_ATTRIB_BITS);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glBegin(GL_LINES);
glColor3f(1,1,1);
glVertex3f(position.x,position.y,position.z);
glVertex3f(position.x,position.y+10.0f,position.z);
glEnd();
glPopAttrib();
}
}
|
#include <iostream>
using namespace std;
using ll = long long;
int main() {
int n;
ll t;
cin >> n >> t;
ll a[n];
for (int i = 0; i < n; ++i) cin >> a[i];
ll ans = 0;
while (true) {
ll cnt = 0, cost = 0;
for (int i = 0; i < n; ++i) {
if (t - cost >= a[i]) {
cost += a[i];
++cnt;
}
}
if (cnt == 0) break;
ans += cnt * (t / cost);
t %= cost;
}
cout << ans << endl;
return 0;
}
|
#include <bitset>
#include <ostream>
namespace precision
{
template<std::size_t N>
class UnsignedInteger
{
private:
std::bitset<N> bits;
const std::size_t size = N;
public:
const std::bitset<N> &get_bits() const
{
return bits;
}
void set_bits(const std::bitset<N> &new_bits)
{
bits = new_bits;
}
std::string get_string() const
{
return bits.to_string();
}
std::size_t get_size() const
{
return size;
}
operator std::bitset<N>&()
{
return bits;
}
UnsignedInteger<N> operator<<(const size_t &pos) const
{
return {bits<<pos};
}
UnsignedInteger<N> &operator<<=(const size_t &pos)
{
bits<<=pos;
return *this;
}
UnsignedInteger<N> operator>>(const size_t &pos) const
{
return {bits>>pos};
}
UnsignedInteger<N> &operator>>=(const size_t &pos)
{
bits>>=pos;
return *this;
}
UnsignedInteger<N> &operator&=(const UnsignedInteger<N> &right)
{
bits&=right.get_bits();
return *this;
}
UnsignedInteger<N> &operator|=(const UnsignedInteger<N> &right)
{
bits|=right.get_bits();
return *this;
}
UnsignedInteger<N> &operator^=(const UnsignedInteger<N> &right)
{
bits^=right.get_bits();
return *this;
}
UnsignedInteger<N> operator~() const
{
return {~bits};
}
UnsignedInteger<N> &operator+=(const UnsignedInteger<N> &right)
{
*this = *this+right;
return *this;
}
UnsignedInteger<N> &operator+=(const unsigned long long &right)
{
*this = *this+UnsignedInteger<N>(right);
return *this;
}
UnsignedInteger<N> &operator-=(const UnsignedInteger<N> &right)
{
*this = *this-right;
return *this;
}
UnsignedInteger<N> &operator-=(const unsigned long long &right)
{
*this = *this-UnsignedInteger<N>(right);
return *this;
}
UnsignedInteger<N> &operator*=(const UnsignedInteger<N> &right)
{
*this = *this*right;
return *this;
}
UnsignedInteger<N> &operator*=(const unsigned long long &right)
{
*this = *this*UnsignedInteger<N>(right);
return *this;
}
UnsignedInteger<N> &operator/=(const UnsignedInteger<N> &right)
{
*this = *this/right;
return *this;
}
UnsignedInteger<N> &operator/=(const unsigned long long &right)
{
*this = *this/UnsignedInteger<N>(right);
return *this;
}
UnsignedInteger<N> &operator++()
{
*this += 1;
}
UnsignedInteger<N> &operator--()
{
*this -= 1;
}
UnsignedInteger<N> &operator++(int tmp)
{
*this += 1;
}
UnsignedInteger<N> &operator--(int tmp)
{
*this -= 1;
}
const bool operator==(const UnsignedInteger<N> &right) const
{
return bits==right.get_bits();
}
const bool operator==(const unsigned long long &right) const
{
return bits==std::bitset<N>(right);
}
const bool operator!=(const UnsignedInteger<N> &right) const
{
return bits!=right.get_bits();
}
const bool operator!=(const unsigned long long &right) const
{
return bits!=std::bitset<N>(right);
}
UnsignedInteger<N> &operator=(const UnsignedInteger<N> &right)
{
bits = right.get_bits();
}
UnsignedInteger<N> &operator=(const unsigned long long &right)
{
bits = std::bitset<N>(right);
}
UnsignedInteger() : bits(), size(N) {}
UnsignedInteger(const int &a) : bits(a), size(N) {}
UnsignedInteger(const std::string &str) : bits{str}, size{N} {}
UnsignedInteger(const unsigned long long &a) : bits(a), size{N} {}
UnsignedInteger(const std::bitset<N> &bs) : bits{bs}, size{N} {}
};
template<std::size_t N>
UnsignedInteger<N> operator&(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
return {left.get_bits()&right.get_bits()};
}
template<std::size_t N>
UnsignedInteger<N> operator&(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return {left.get_bits()&std::bitset<N>(right)};
}
template<std::size_t N>
UnsignedInteger<N> operator|(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
return {left.get_bits()|right.get_bits()};
}
template<std::size_t N>
UnsignedInteger<N> operator|(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return {left.get_bits()|std::bitset<N>(right)};
}
template<std::size_t N>
UnsignedInteger<N> operator^(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
return {left.get_bits()^right.get_bits()};
}
template<std::size_t N>
UnsignedInteger<N> operator^(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return {left.get_bits()^std::bitset<N>(right)};
}
template<std::size_t N>
const bool operator> (const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
if(left == right)
return false;
for(std::size_t i = left.get_bits().size()-1; i >= 0; --i)
{
if(left.get_bits()[i] != right.get_bits()[i])
{
if(right.get_bits()[i])
return false;
else
return true;
}
}
return false;
}
template<std::size_t N>
const bool operator> (const UnsignedInteger<N> &left, const unsigned long long &right)
{
return left>UnsignedInteger<N>(right);
}
template<std::size_t N>
const bool operator>=(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
if(left == right)
return true;
for(std::size_t i = left.get_bits().size()-1; i >= 0; --i)
{
if(left.get_bits()[i] != right.get_bits()[i])
{
if(right.get_bits()[i])
return false;
else
return true;
}
}
return true;
}
template<std::size_t N>
const bool operator>=(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return left>=UnsignedInteger<N>(right);
}
template<std::size_t N>
const bool operator< (const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
if(left == right)
return false;
for(std::size_t i = left.get_bits().size()-1; i >= 0; --i)
{
if(left.get_bits()[i] != right.get_bits()[i])
{
if(right.get_bits()[i])
return true;
else
return false;
}
}
std::cout<<left.get_string()<<"\n";
std::cout<<right.get_string()<<"\n";
return false;
}
template<std::size_t N>
const bool operator< (const UnsignedInteger<N> &left, const unsigned long long &right)
{
return left<UnsignedInteger<N>(right);
}
template<std::size_t N>
const bool operator<=(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
if(left == right)
return true;
for(std::size_t i = left.get_bits().size()-1; i >= 0; --i)
{
if(left.get_bits()[i] != right.get_bits()[i])
{
if(right.get_bits()[i])
return true;
else
return false;
}
}
return true;
}
template<std::size_t N>
const bool operator<=(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return left<=UnsignedInteger<N>(right);
}
template<std::size_t N>
UnsignedInteger<N> operator+(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
std::bitset<N> ret;
bool carry = false;
for(std::size_t i = 0; i < ret.size(); ++i)
{
if(left.get_bits()[i] && right.get_bits()[i])
{
ret[i] = carry;
carry = true;
}
else if(left.get_bits()[i] || right.get_bits()[i])
{
ret[i] = !carry;
}
else
{
ret[i] = carry;
carry = false;
}
}
return {ret};
}
template<std::size_t N>
UnsignedInteger<N> operator+(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return left+UnsignedInteger<N>(right);
}
template<std::size_t N>
UnsignedInteger<N> operator-(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
std::bitset<N> ret;
bool carry = false;
for(std::size_t i = 0; i < ret.size(); ++i)
{
if(left.get_bits()[i] && right.get_bits()[i])
{
ret[i] = carry;
}
else if(left.get_bits()[i] || right.get_bits()[i])
{
ret[i] = !carry;
carry = right.get_bits()[i];
}
else
{
ret[i] = carry;
}
}
return {ret};
}
template<std::size_t N>
UnsignedInteger<N> operator-(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return left-UnsignedInteger<N>(right);
}
template<std::size_t N>
UnsignedInteger<N> operator*(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
std::bitset<N> ret;
for(std::size_t i = 0; i < right.get_bits().size(); ++i)
{
std::bitset<N> tmp;
for(std::size_t j = 0; j < tmp.size(); ++j)
{
tmp[j] = (right.get_bits()[i] && left.get_bits()[j]);
}
ret = UnsignedInteger<N>(ret)+UnsignedInteger<N>(tmp<<i);
}
return {ret};
}
template<std::size_t N>
UnsignedInteger<N> operator*(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return left*UnsignedInteger<N>(right);
}
template<std::size_t N>
UnsignedInteger<N> operator/(const UnsignedInteger<N> &left, const UnsignedInteger<N> &right)
{
UnsignedInteger<N> result, tmp = left;
while(tmp >= right)
{
++result;
tmp -= right;
}
return result;
}
template<std::size_t N>
UnsignedInteger<N> operator/(const UnsignedInteger<N> &left, const unsigned long long &right)
{
return left/UnsignedInteger<N>(right);
}
template<std::size_t N>
std::ostream& operator<<(std::ostream &stream, const UnsignedInteger<N> &obj)
{
return stream << obj.get_bits();
}
typedef UnsignedInteger<128> uint128_t;
} // namespace precision
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2009-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef GEOLOCATION_TOOLS_H
#define GEOLOCATION_TOOLS_H
#ifdef GEOLOCATION_SUPPORT
#include "modules/pi/OpGeolocation.h"
#ifdef OPERA_CONSOLE
#include "modules/console/opconsoleengine.h"
#endif // OPERA_CONSOLE
struct GeoCoordinate
{
double longitude;
double latitude;
};
class GeoTools
{
public:
/** Calculate the distance between two points on the earth's surface.
*
* Uses the haversine formula, assumes a perfectly round earth, etc., but
* it should be good enough for our purposes.
*
* @param lat1 Latitude, in degrees, of the first point
* @param long1 Longitude, in degrees, of the first point
* @param lat2 Latitude, in degrees, of the second point
* @param long2 Longitude, in degrees, of the second point
* @return distance between points in meters
*/
static double Distance(double lat1, double long1, double lat2, double long2);
/** Calculate the distance between two points on the earth's surface.
*
* Same as overloaded function with four parameters.
*
* @param point1 Coordinates of first point
* @param point2 Coordinates of second point
* @return distance between points in meters
*/
static double Distance(const GeoCoordinate &point1, const GeoCoordinate &point2);
/** Check if the difference between two WiFi data sets is significant.
*
* @param data_a A set of WiFi data, sorted by MAC address.
* @param data_b A set of WiFi data, sorted by MAC address.
* return TRUE if the difference between WiFi data is to be considered significant.
*/
static BOOL SignificantWifiChange(OpWifiData *data_a, OpWifiData *data_b);
/** Check if the difference between two radio cell data sets is significant.
*
* @param data_a A set of cell towers data.
* @param data_b A set of cell towers data.
* return TRUE if the difference between cell towers data is to be considered significant.
*/
static BOOL SignificantCellChange(OpRadioData *data_a, OpRadioData *data_b);
#ifdef OPERA_CONSOLE
/** Post message to error console.
*
* @param msg Message string to display on error console.
* @param msg_part2 Optional second part of the message, to be concatenated with the first one.
*/
static void PostConsoleMessage(OpConsoleEngine::Severity severity, const uni_char *msg, const uni_char *msg_part2 = NULL);
/** Returns a note about a custom location provider URL being set.
*
* It is to be used as part of console messages.
* The note is either empty or informs about the preference setting that is modified.
*/
static const uni_char *CustomProviderNote();
#endif // OPERA_CONSOLE
};
#endif //GEOLOCATION_SUPPORT
#endif // GEOLOCATION_TOOLS_H
|
//
// Created by 송지원 on 2020-03-08.
//
//exit code 11 뜸. 출
// 뭔가 알아봤는데 sort() 함 수 내에서 자신을 호출할 때,
// 두번째 호출에서 sort(mid +1, end) 이렇게 호출해야 하는데
// 그냥 mid를 호출함.
// typo error!
#include <iostream>
using namespace std;
int a[1000000];
int b[1000000];
//void swap(int &x, int &y) {
// int z = x;
// x = y;
// y = z;
//}
void merge( int start, int end) {
int mid = (start + end)/2;
int i = start;
int j = mid + 1;
int k = 0;
while (i<=mid && j<=end) {
if (a[i] <= a[j]) {
b[k++] = a[i++];
} else {
b[k++] = a[j++];
}
}
while (i <= mid) {
b[k++] = a[i++];
}
while (j <= end) {
b[k++] = a[j++];
}
for (int i=start; i<=end; i++) {
a[i] = b[i-start];
}
}
void sort(int start, int end) {
if (start == end) {
return;
}
int mid = (start + end)/2;
sort(start, mid);
sort(mid+1, end);
merge(start, end);
}
int main() {
int n;
scanf("%d", &n);
for (int i=0; i<n; i++) {
scanf("%d", &a[i]);
}
sort(0, n-1);
for (int i=0; i<n; i++) {
printf("%d ", a[i]);
}
return 0;
}
|
//
// Created by 钟奇龙 on 2019-05-17.
//
#include <vector>
#include <iostream>
using namespace std;
/*
* 原问题
*/
void leftUnique(vector<int> &arr){
if(arr.size() < 2) return;
int left = 0;
int right = 1;
while(right < arr.size()){
if(arr[right] != arr[left]){
swap(arr[left+1],arr[right]);
left++;
}
right++;
}
}
/*
* 荷兰国旗问题
*/
void sortForThreeColors(vector<int> &arr){
if(arr.size() < 2) return;
int left = -1;
int right = arr.size();
int index = 0;
while(index < right){
if(arr[index] == 0){
swap(arr[index++],arr[++left]);
}else if(arr[index] == 2){
swap(arr[index],arr[--right]);
}else{
++index;
}
}
}
int main(){
// vector<int> arr = {1,2,2,2,3,3,4,5,6,6,7,7,8,8,8,9};
// leftUnique(arr);
vector<int> arr = {1,0,2,2,1,0,0,1,2,0};
sortForThreeColors(arr);
}
|
#include <LeftistHeap.h>
#include <iostream>
#include <Wrapper.h>
#include <PuttingVisitor.h>
int main(void)
{
LeftistHeap lh;
Int *ip1 = new Int(1);
Int *ip2 = new Int(2);
Int *ip3 = new Int(3);
Int *ip4 = new Int(4);
Int *ip5 = new Int(5);
Int *ip6 = new Int(6);
Int *ip7 = new Int(7);
using namespace std;
PuttingVisitor pv(cout);
lh.Enqueue(*ip4);
lh.Enqueue(*ip5);
lh.Enqueue(*ip6);
lh.Enqueue(*ip7);
lh.Enqueue(*ip1);
lh.Enqueue(*ip2);
lh.Enqueue(*ip3);
lh.Accept(pv);
cout<<lh.DequeueMin ()<<endl;
cout<<lh.DequeueMin ()<<endl;
cout<<lh.DequeueMin ()<<endl;
cout<<lh.DequeueMin ()<<endl;
cout<<lh.DequeueMin ()<<endl;
cout<<lh.DequeueMin ()<<endl;
cout<<lh.DequeueMin ()<<endl;
}
|
#include "../include/Scaleable.h"
using namespace sf;
Texture Scaleable::getTexture()
{
return texture;
}
Vector2f Scaleable::getSize()
{
return size;
}
Vector2f Scaleable::getScale()
{
return scale;
}
Vector2f Scaleable::getPosition()
{
return position;
}
void Scaleable::setTexture(Texture t)
{
texture = t;
textureSize = t.getSize();
}
void Scaleable::setSize(Vector2f scale)
{
size = Vector2f(textureSize.x * scale.x, textureSize.y * scale.y);
}
void Scaleable::setScale(Vector2f s)
{
scale = s;
}
void Scaleable::setPosition(Vector2f p)
{
position = p;
}
Sprite Scaleable::createSprite()
{
Sprite sprite = Sprite(texture);
sprite.setScale(scale);
sprite.setPosition(position);
return sprite;
}
|
#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn=100000+10 ;
struct P
{
int id ; LL val ;
bool operator < (const P &rhs) const
{
return val>rhs.val ;
}
};
int n,m,k ;
LL h[maxn],a[maxn],num[maxn],p ;
priority_queue<P> pq ;
bool check(LL h0)
{
while(!pq.empty()) pq.pop() ;
memset(num,0,sizeof(num)) ;
for(int i=1;i<=n;i++) if(h0-a[i]*m < h[i])
pq.push((P){i,h0/a[i]}) ;
for(int i=1;!pq.empty() && i<=m;i++)
for(int _k=1;!pq.empty() && _k<=k;_k++)
{
P u=pq.top() ; pq.pop() ;
if(u.val<i) return 0 ;
num[u.id]++ ;
if(h0+p*num[u.id]-a[u.id]*m<h[u.id])
pq.push((P){u.id,(h0+p*num[u.id])/a[u.id]}) ;
}
return pq.empty() ;
}
main()
{
scanf("%d%d%d%lld",&n,&m,&k,&p) ;
LL l=0 , r=0 ;
for(int i=1;i<=n;i++)
{
scanf("%lld%lld",&h[i],&a[i]) ;
l=max(l,a[i]) ;
r=max(r,h[i]+m*a[i]) ;
}
l-- ;
while(r-l>1)
{
LL mid=(r+l)/2 ;
if(check(mid)) r=mid ;
else l=mid ;
}
printf("%lld\n",r) ;
}
|
/**
@file
@author Nicholas Gillian <ngillian@media.mit.edu>
@version 1.0
@section LICENSE
GRT MIT License
Copyright (c) <2012> <Nicholas Gillian, Media Lab, MIT>
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.
*/
/*
GRT Custom Makefile
This example provides a basic makefile template for the GRT.
*/
//You might need to set the specific path of the GRT header relative to your project
#include <GRT/GRT.h>
using namespace GRT;
#include <fstream>
using namespace std;
class KfoldTimeSeriesData {
protected:
LabelledTimeSeriesClassificationData inputDataset;
vector< vector< vector< UINT > > > crossValidationIndexs;
bool crossValidationSetup;
UINT kFoldValue;
UINT numDimensions;
vector< ClassTracker > classTracker;
public:
KfoldTimeSeriesData(LabelledTimeSeriesClassificationData);
virtual ~KfoldTimeSeriesData();
bool spiltDataIntoKFolds(const UINT);
TimeSeriesClassificationDataStream getTestFoldData(const UINT) const;
LabelledTimeSeriesClassificationData getTrainingFoldData(const UINT, const UINT) const;
UINT getFoldSize();
};
KfoldTimeSeriesData::KfoldTimeSeriesData(GRT::LabelledTimeSeriesClassificationData inputDataset):
inputDataset(inputDataset){
crossValidationSetup = false;
crossValidationIndexs.clear();
kFoldValue = 0;
classTracker = inputDataset.getClassTracker();
numDimensions = inputDataset.getNumDimensions();
UINT totalNumSamples = inputDataset.getNumSamples();
}
KfoldTimeSeriesData::~KfoldTimeSeriesData() {}
bool KfoldTimeSeriesData::spiltDataIntoKFolds(const GRT::UINT K) {
kFoldValue = K;
//K can not be zero
if( K == 0 ){
std::cout << "spiltDataIntoKFolds(UINT K) - K can not be zero!" << std::endl;
return false;
}
//K can not be larger than the number of examples
if( K > inputDataset.getNumSamples()){
std::cout << "spiltDataIntoKFolds(UINT K,bool useStratifiedSampling) - K can not be 0!" << std::endl;
return false;
}
//K can not be larger than the number of examples in a specific class if the stratified sampling option is true
for(UINT c=0; c < inputDataset.getNumClasses(); c++) {
if( K > classTracker[c].counter ){
cout << "spiltDataIntoKFolds(UINT K,bool useStratifiedSampling) - K can not be larger than the number of samples in any given class!" << std::endl;
return false;
}
}
//Setup the dataset for k-fold cross validation
kFoldValue = K;
vector< UINT > indexs( inputDataset.getNumSamples() );
//Work out how many samples are in each fold, the last fold might have more samples than the others
UINT numSamplesPerFold = (UINT) floor( inputDataset.getNumSamples() / double(K) );
//Create the random partion indexs
Random random;
UINT randomIndex = 0;
//Break the data into seperate classes
vector< vector< UINT > > classData( inputDataset.getNumClasses() );
//Add the indexs to their respective classes
for(UINT i = 0; i < inputDataset.getNumSamples(); i++) {
classData[ inputDataset.getClassLabelIndexValue(
inputDataset[i].getClassLabel() ) ].push_back( i );
}
//Randomize the order of the indexs in each of the class index buffers
for(UINT c = 0; c < inputDataset.getNumClasses(); c++) {
UINT numSamples = (UINT)classData[c].size();
for(UINT x = 0; x < numSamples; x++) {
//Pick a random index
randomIndex = random.getRandomNumberInt(0, numSamples);
//Swap the indexs
SWAP( classData[c][ x ] , classData[c][ randomIndex ] );
}
}
//Resize the cross validation indexs buffer
crossValidationIndexs.resize( K );
for (UINT k = 0; k < K; k++) {
crossValidationIndexs[k].resize(inputDataset.getNumClasses());
}
//Loop over each of the classes and add the data equally to each of the k folds until there is no data left
vector< UINT >::iterator iter;
for(UINT c = 0; c < inputDataset.getNumClasses(); c++){
iter = classData[ c ].begin();
UINT k = 0;
while( iter != classData[c].end() ){
crossValidationIndexs[ k ][c].push_back( *iter );
iter++;
k = ++k % K;
}
}
crossValidationSetup = true;
return true;
}
LabelledTimeSeriesClassificationData KfoldTimeSeriesData::getTrainingFoldData(const UINT foldIndex, const UINT numSamplesPerClass) const {
UINT index = 0;
unsigned int randomNumber;
unsigned int indexClassLabel;
unsigned int numSamplesRemaining;
LabelledTimeSeriesClassificationData trainingData;
if( !crossValidationSetup ) {
cout << "getTrainingFoldData(UINT foldIndex) - Cross Validation has not been setup! You need to call the spiltDataIntoKFolds(UINT K,bool useStratifiedSampling) function first before calling this function!" << endl;
return trainingData;
}
if( foldIndex >= kFoldValue ) {
cout << "Fold index too big" << endl;
return trainingData;
}
Random random;
trainingData.setNumDimensions( numDimensions );
/* Put all K-1 training folds in one data set */
vector <vector< UINT > > MergedIndexs(inputDataset.getNumClasses());
for(UINT k = 0; k < kFoldValue; k++) {
if( k == foldIndex ) {
continue;
}
for (UINT classLabel = 0 ; classLabel < crossValidationIndexs[k].size(); classLabel++) {
for (UINT i = 0; i < crossValidationIndexs[k][classLabel].size(); i++) {
MergedIndexs[classLabel].push_back(crossValidationIndexs[k][classLabel][i]);
}
}
}
/* For each class peak randomly "numSamplesPerClass" samples */
for (unsigned int classLabel = 0; classLabel < inputDataset.getNumClasses() ; classLabel++) {
for (unsigned int numSamples = 1; numSamples <= numSamplesPerClass; numSamples++) {
numSamplesRemaining = MergedIndexs[classLabel].size();
if (numSamplesRemaining == 0) {
printf("The \"numSamplesPerClass\" variable is bigger that the samples for this class");
break;
}
randomNumber = random.getRandomNumberInt(0, numSamplesRemaining);
index = MergedIndexs[classLabel][randomNumber];
/* Remove added sample so that it is not added again */
MergedIndexs[classLabel].erase(MergedIndexs[classLabel].begin() + randomNumber);
trainingData.addSample( inputDataset[ index ].getClassLabel(),
inputDataset[ index ].getData() );
}
}
return trainingData;
}
TimeSeriesClassificationDataStream KfoldTimeSeriesData::getTestFoldData(const UINT foldIndex) const {
TimeSeriesClassificationDataStream testData;
if( !crossValidationSetup ) {
cout << "getTestFoldData(UINT foldIndex) - Cross Validation has not been setup! You need to call the spiltDataIntoKFolds(UINT K,bool useStratifiedSampling) function first before calling this function!" << endl;
return testData;
}
if( foldIndex >= kFoldValue ) {
cout << "Fold index too big" << endl;
return testData;
}
//Add the data to the training
testData.setNumDimensions( numDimensions );
UINT index = 0;
for(UINT classLabel = 0; classLabel < crossValidationIndexs[foldIndex].size(); classLabel++) {
for (UINT i = 0; i < crossValidationIndexs[foldIndex][classLabel].size(); i++) {
index = crossValidationIndexs[foldIndex][classLabel][i];
testData.addSample( inputDataset[ index ].getClassLabel(),
inputDataset[ index ].getData() );
}
}
return testData;
}
UINT KfoldTimeSeriesData::getFoldSize() {
if (crossValidationSetup) {
UINT maxSize = crossValidationIndexs[0].size();
for (UINT k = 0; k < kFoldValue; k++) {
if (crossValidationIndexs[k].size() > maxSize) {
maxSize = crossValidationIndexs[k].size();
}
}
return inputDataset.getNumSamples() - maxSize;
}
return 0;
}
int main (int argc, const char * argv[])
{
TimeSeriesClassificationData trainingData; //This will store our training data
GestureRecognitionPipeline pipeline; //This is a wrapper for our classifier and any pre/post processing modules
string dirPath = "/home/vlad/AndroidStudioProjects/DataCapture/dataSetGenerator/build";
if (!trainingData.loadDatasetFromFile(dirPath + "/acc-training-set-segmented.data")) {
printf("Cannot open training segmented set\n");
return 0;
}
printf("Successfully opened training data set ...\n");
DTW dtw;
// LowPassFilter lpf(0.1, 1, 1);
// pipeline.setPreProcessingModule(lpf);
// DoubleMovingAverageFilter filter( 1000, 3 );
// pipeline.setPreProcessingModule(filter);
//dtw.enableNullRejection( true );
//Set the null rejection coefficient to 3, this controls the thresholds for the automatic null rejection
//You can increase this value if you find that your real-time gestures are not being recognized
//If you are getting too many false positives then you should decrease this value
//dtw.setNullRejectionCoeff( 5 );
dtw.enableTrimTrainingData(true, 0.1, 90);
// dtw.setOffsetTimeseriesUsingFirstSample(true);
pipeline.setClassifier( dtw );
UINT KFolds = 5;
/* Separate input dataset using KFold */
KfoldTimeSeriesData* kFoldTS = new KfoldTimeSeriesData(trainingData);
if( !kFoldTS->spiltDataIntoKFolds(KFolds) ) {
printf("BaseTGTestModel: Failed to spiltDataIntoKFolds!");
return 0;
}
UINT maxTrainigSetSize = trainingData.getNumSamples() * (KFolds - 1) / (KFolds * trainingData.getNumClasses());
// KFolds
ofstream myfile;
myfile.open ("example.txt");
Float acc = 0;
for (GRT::UINT k = 1 ; k < KFolds; k++) {
printf("Running tests for: %d fold", k);
// maxTrainigSetSize
// for (UINT trainingSetSize = 1; trainingSetSize <= maxTrainigSetSize; trainingSetSize ++) {
/* Set up training datasets for current fold */
TimeSeriesClassificationData trainingDataset = kFoldTS->getTrainingFoldData(k, maxTrainigSetSize);
/* Set up validation datasets for current fold */
TimeSeriesClassificationDataStream testDataset = kFoldTS->getTestFoldData(k);
/* Log test dataset size */
//printf("Data set size: training %d; testing %d",
// trainingDataset.getNumSamples(), testDataset.getNumSamples());
/* Run test for current fold */
pipeline.train(trainingDataset);
pipeline.test(testDataset);
myfile << pipeline.getTestAccuracy() << "\n";
// }
}
myfile.close();
printf("Accuracy = %f ; %d\n", acc, maxTrainigSetSize);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.