text
stringlengths 8
6.88M
|
|---|
#include "entity.h"
using namespace std;
namespace sbg {
Entity::Entity(Entity&& o) = default;
Entity& Entity::operator=(Entity&& o) = default;
}
|
//
// tutorialTriangle.cpp
// OpenGLProjects
//
// Created by Dayuan Chen on 9/8/19.
// Copyright © 2019 N33MO. All rights reserved.
//
// add "shader" file to Build Phases - Copy Files
#include <iostream>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include "shaderexample.h"
const GLint WIDTH = 800, HEIGHT = 640;
//const GLchar *vertexShaderSource =
//"#version 330 core\n"
//"layout ( location = 0 ) in vec3 position;\n"
//"void main( )\n"
//"{\n"
//"gl_Position = vec4( position.x, position.y, position.z, 1.0 );\n"
//"}\n";
//
//const GLchar *fragmentShaderSource =
//"#version 330 core\n"
//"out vec4 color;\n"
//"void main( )\n"
//"{\n"
//"color = vec4( 1.0f, 0.5f, 0.2f, 0.1f );\n"
//"}\n";
int main( )
{
glfwInit();
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); // required for Mac users, won't conflict with Win
glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );
GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "Learn OpenGL", NULL, NULL);
// following two lines required for Mac Users, won't conflict with Win
//Get actual window size that relevant to your Mac (Retina Display things)
int screenWidth, screenHeight;
glfwGetFramebufferSize( window, &screenWidth, &screenHeight );
if ( !window )
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent( window );
glewExperimental = GL_TRUE;
if ( GLEW_OK != glewInit() )
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
glViewport(0, 0, screenWidth, screenHeight);
// Shader
// GLuint vertexShader = glCreateShader( GL_VERTEX_SHADER );
// glShaderSource( vertexShader, 1, &vertexShaderSource, NULL );
// glCompileShader( vertexShader );
//
// GLint success;
// GLchar infoLog[512];
//
// glGetShaderiv( vertexShader, GL_COMPILE_STATUS, &success );
//
// if ( !success ) {
// glGetShaderInfoLog( vertexShader, 512, NULL, infoLog );
// std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
// }
//
// GLuint fragmentShader = glCreateShader( GL_FRAGMENT_SHADER );
// glShaderSource( fragmentShader, 1, &fragmentShaderSource, NULL );
// glCompileShader( fragmentShader );
//
// glGetShaderiv( fragmentShader, GL_COMPILE_STATUS, &success );
//
// if ( !success ) {
// glGetShaderInfoLog( fragmentShader, 512, NULL, infoLog );
// std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
// }
//
// GLuint shaderProgram = glCreateProgram( );
// glAttachShader( shaderProgram, vertexShader );
// glAttachShader( shaderProgram, fragmentShader );
// glLinkProgram( shaderProgram );
//
// glGetProgramiv( shaderProgram, GL_LINK_STATUS, &success );
//
// if ( !success ) {
// glGetProgramInfoLog( shaderProgram, 512, NULL, infoLog );
// std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
// }
//
// glDeleteShader( vertexShader );
// glDeleteShader( fragmentShader );
Shader ourShader("shader/basic.vert", "shader/basic.frag"); // /Users/n33mo/MyLib/XcodeProjects/OpenGLProjects/OpenGLProjects/tutorialModernOpenGL/
GLfloat vertices[] =
{
// position // color
-0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom right
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // middle top
};
GLuint VAO, VBO;
glGenVertexArrays( 1, &VAO );
glGenBuffers( 1, &VBO );
glBindVertexArray( VAO );
glBindBuffer( GL_ARRAY_BUFFER, VBO );
glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof( GLfloat ), ( GLvoid * ) 0 );
glEnableVertexAttribArray( 0 );
glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof( GLfloat ), ( GLvoid * ) ( 3 * sizeof( GLfloat ) ) );
glEnableVertexAttribArray( 1 );
glBindVertexArray( 0 );
while ( !glfwWindowShouldClose( window ))
{
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear( GL_COLOR_BUFFER_BIT );
ourShader.Use( );
glBindVertexArray( VAO );
glDrawArrays( GL_TRIANGLES, 0, 3 );
glBindVertexArray( 0 );
glfwSwapBuffers( window );
}
glDeleteVertexArrays( 1, &VAO );
glDeleteBuffers( 1, &VBO );
glfwTerminate();
return 0;
}
|
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#include <errno.h>
#include <iface/link.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "sys/Appfs.hpp"
#include "sys/Dir.hpp"
#include "sys/File.hpp"
using namespace sys;
int Appfs::create(const char * name, const void * buf, int nbyte, const char * mount, bool (*update)(void *, int, int), void * context, link_transport_mdriver_t * driver){
char buffer[LINK_PATH_MAX];
File file;
int tmp;
const char * p = (const char*)buf;
appfs_createattr_t attr;
int loc;
unsigned int bw; //bytes written
link_appfs_file_t f;
strcpy(buffer, mount);
strcat(buffer, "/flash/");
strcat(buffer, name);
#ifdef __link
file.set_driver(driver);
#endif
//delete the settings if they exist
tmp = errno;
unlink(buffer);
errno = tmp;
strncpy(f.hdr.name, name, LINK_NAME_MAX);
f.hdr.mode = 0666;
f.exec.code_size = nbyte + sizeof(f); //total number of bytes in file
f.exec.signature = APPFS_CREATE_SIGNATURE;
File::remove(buffer, driver);
if( file.open("/app/.install", File::WRONLY) < 0 ){
return -1;
}
memcpy(attr.buffer, &f, sizeof(f));
//now copy some bytes
attr.nbyte = APPFS_PAGE_SIZE - sizeof(f);
if( nbyte < (int)attr.nbyte ){
attr.nbyte = nbyte;
}
memcpy(attr.buffer + sizeof(f), p, attr.nbyte);
attr.nbyte += sizeof(f);
loc = 0;
bw = 0;
do {
if( loc != 0 ){ //when loc is 0 -- header is copied in
if( (f.exec.code_size - bw) > APPFS_PAGE_SIZE ){
attr.nbyte = APPFS_PAGE_SIZE;
} else {
attr.nbyte = f.exec.code_size - bw;
}
memcpy(attr.buffer, p, attr.nbyte);
}
//location gets modified by the driver so it needs to be fixed on each loop
attr.loc = loc;
if( (tmp = file.ioctl(I_APPFS_CREATE, &attr)) < 0 ){
file.close();
return tmp;
}
if( loc != 0 ){
p += attr.nbyte;
} else {
p += (attr.nbyte - sizeof(f));
}
bw += attr.nbyte;
loc += attr.nbyte;
if( update ){
update(context, bw, f.exec.code_size);
}
} while( bw < f.exec.code_size);
file.close();
return nbyte;
}
#ifndef __link
int Appfs::cleanup(bool data){
struct stat st;
Dir dir;
char buffer[LINK_PATH_MAX];
const char * name;
if( dir.open("/app/ram") < 0 ){
perror("failed to open dir");
return -1;
}
while( (name = dir.read()) != 0 ){
strcpy(buffer, "/app/ram/");
strcat(buffer, name);
if( stat(buffer, &st) < 0 ){
perror("Failed to stat");
}
if( ((st.st_mode & (LINK_S_IXUSR|LINK_S_IXGRP|LINK_S_IXOTH)) || data) && (name[0] != '.') ){
if( unlink(buffer) < 0){
dir.close();
return -1;
}
}
}
dir.close();
return 0;
}
#endif
|
#include "DFCman.h"
void AddComponentToMap(dfComponent* dfc)
{
std::type_index infer = typeid(*dfc);
dfComponent* comp = dfComponentMap[typeid(*dfc)];
if(comp)
{
dfComponent* prev = 0;
while(comp != 0)
{
prev = comp;
comp = comp->nextInList;
}
prev->nextInList = dfc;
dfc->nextInList = 0;
}
else
{
dfComponentMap[typeid(*dfc)] = dfc;
dfc->nextInList = 0;
}
}
void RemoveComponentFromMap(dfComponent* dfc)
{
dfComponent* current = dfComponentMap[typeid(*dfc)];
dfComponent* prev = 0;
if(!current)
return;
while(current != dfc)
{
prev = current;
current = current->nextInList;
if(!current)
{
dfLog("Component does not exist in DFC map");
return;
}
}
if(current == dfComponentMap[typeid(*dfc)])
{
if(current->nextInList != 0)
dfComponentMap[typeid(*dfc)] = current->nextInList;
else
dfComponentMap[typeid(*dfc)] = 0;
}
else
{
if(current->nextInList != 0)
prev->nextInList = current->nextInList;
else
prev->nextInList = 0;
}
}
|
/*
该函数对2^64以内的数都能有效辨别。
*/
const int cstPrime[10]={2,3,5,7,11,13,17,19,23,29};
bool Miller_Rabin(ll a,ll n)
{
ll r=0,s=n-1;
while(!(s&1)) r++,s>>=1; //n-1==2^r*s
ll as=pow_mod(a,s,n); //as=a^s%n
if(as==1 || as==n-1) return true; //if as==1 or as^i%n==n-1 then it is likely be prime
for(int i=1;i<r;i++)
{
as=mod(as,as,n);//as=as*as%n;
if(as==1) return false;//if as==1,it's no use to do the rest.
if(as==n-1) return true;
}
return false;
}
bool isPrime(ll n) //true if n is prime
{
for(int i=0;i<10;++i)//test all 10 base
if(n==cstPrime[i])return true;
else{
if(n%cstPrime[i]==0) return false;
if(!Miller_Rabin(cstPrime[i],n)) return false;
}
return true;
}
|
#include "stdafx.h" //________________________________________ CalculadoraIMC.cpp
#include "CalculadoraIMC.h"
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR cmdLine, int cmdShow) {
CalculadoraIMC app;
return app.BeginDialog(IDI_CalculadoraIMC, hInstance);
}
void CalculadoraIMC::Window_Open(Win::Event& e)
{
//________________________________________________________ lsIMC
lsIMC.StateCount = 3;
lsIMC.SetState(0, 0.0, 20.5, RGB(240, 190, 250), L"Obesidad");
lsIMC.SetState(1, 30.0, 24.5, RGB(50, 220, 50), L"Sobrepeso");
lsIMC.SetState(2, 60.0, 29.5, RGB(50, 250, 220), L"Normal");
lsIMC.SetState(3, 60.0, 45.0, RGB(0, 250, 250), L"Bajo Peso");
lsIMC.Level = 45.0;
this->radioHombre.Checked = true;
this->radioMujer.Checked = false;
}
void CalculadoraIMC::btCalcular_Click(Win::Event& e)
{
const double peso = tbxPeso.DoubleValue;
const double altura = tbxAltura.DoubleValue;
double IMC = peso / (altura*altura);
if (radioHombre.Checked == true)
{
}
}
|
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <set>
using namespace std;
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
#define int long long
#define ld long double
#define F first
#define S second
#define P pair <int,int>
#define vi vector <int>
#define vs vector <string>
#define vb vector <bool>
#define all(x) x.begin(),x.end()
#define FOR(a,b) for(int i=a;i<b;i++)
#define REP(a,b) for(int i=a;i<=b;i++)
#define sp(x,y) fixed<<setprecision(y)<<x
#define pb push_back
#define mod 1e9+7
#define endl '\n'
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
const int N = 1e5 + 5;
vi graph[N];
vi vis;
vi col;
bool flag;
int n, m;
void bfs(int src, int c) {
col[src] = c;
vis[src] = 1;
queue <int> q;
q.push(src);
while (!q.empty()) {
int temp = q.front();
q.pop();
for (int to : graph[temp]) {
if (!vis[to]) {
vis[to] = 1;
q.push(to);
if (col[temp] == 1)
col[to] = 2;
else
col[to] = 1;
}
else {
if (col[to] == col[temp]) {
flag = false;
return ;
}
}
}
}
}
typedef vector <int> vii;
void solve() {
vis = vii(N, 0);
col = vii(N, -1);
flag = true;
cin >> n >> m;
for (int i = 0; i <= n; i++)
graph[i].clear();
while (m--) {
int u, v; cin >> u >> v;
graph[u].pb(v);
graph[v].pb(u);
}
bool temp = true;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
bfs(i, 1);
if (!flag) {
temp = false;
break;
}
}
}
if (!temp) {
cout << "IMPOSSIBLE" << endl;
return ;
}
for (int i = 1; i <= n; i++)
cout << col[i] << " ";
cout << endl;
return ;
}
int32_t main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
//int t;cin>>t;while(t--)
solve();
return 0;
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#if 0
#ifndef BAJKA_VIEW_TEXT_H_
#define BAJKA_VIEW_TEXT_H_
#include <SDL_opengl.h>
#include "ReflectionMacros.h"
#include "resource/IFont.h"
#include "Primitive.h"
namespace View {
class Text : public Primitive {
public:
C__ (void)
b_ ("Primitive")
Text () : hash (0), texWidth (0), texHeight (0), imgWidth (0), imgHeight (0), multiline (false), align (IFont::LEFT) {}
virtual ~Text () {}
/// Do the drawing.
virtual void update (Model::IModel *model, Event::UpdateEvent *e);
Ptr <IFont> getFont () const { return font; }
S_ (setFont) void setFont (Ptr <IFont> f) { font = f; }
std::string getText () const { return text; }
m_ (setText) void setText (std::string const &s) { text = s; }
bool getMultiline () const { return multiline; }
m_ (setMultiline) void setMultiline (bool b) { multiline = b; }
IFont::TextAlign getAlign () const { return align; }
m_ (setAlign) void setAlign (int a) { align = (IFont::TextAlign)a; } // TODO typ na Align
double getWidthHint () const;
double getHeightHint () const;
private:
void init ();
void initIf ();
private:
Ptr <IFont> font;
std::string text;
std::size_t hash;
GLuint texName;
// Rozmiary textury (potęga 2jki)
int texWidth, texHeight;
// Faktyczne rozmiary bitmapy (równe rozmiarom regionu, lub rozmiarom obrazka, jeśli region pusty).
int imgWidth, imgHeight;
bool multiline;
IFont::TextAlign align;
E_ (Text)
};
} /* namespace View */
#endif /* TEXT_H_ */
#endif
|
//O(n1 + n2). Here n1 and n2 are length of the linked lists l1 and l2 respectively.
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL && l2 == NULL){
return NULL;
}
if(l1 == NULL){
return l2;
}
if(l2 == NULL){
return l1;
}
ListNode *head = NULL;
ListNode *tail = NULL;
while(l1 != NULL && l2 != NULL){
if(l1 -> val <= l2 -> val){
if(head == NULL){
head = l1;
tail = l1;
}else{
tail -> next = l1;
tail = l1;
}
l1 = l1 -> next;
}else{
if(head == NULL){
head = l2;
tail = l2;
}else{
tail -> next = l2;
tail = l2;
}
l2 = l2 -> next;
}
}
if(l2 != NULL){
tail -> next = l2;
}
if(l1 != NULL){
tail -> next = l1;
}
return head;
}
};
|
#pragma once
#include <System.h>
#include <utility>
namespace breakout
{
class CanvasWidget;
class GuiSystem : public BaseSystem
{
using CurrGameState = int;
public:
static EBaseSystemType GetType()
{
return EBaseSystemType::GUI;
}
GuiSystem();
virtual ~GuiSystem() {};
virtual void Init() override;
virtual void Update(float dtMilliseconds) override;
void UpdateGUIByGameState();
private:
std::pair<CurrGameState, CanvasWidget*> m_currWidgetByState = {-1, nullptr};
};
}
|
#include "gtest/gtest.h"
#include "wali/wfa/WFA.hpp"
#include "wali/wfa/State.hpp"
#include "fixtures.hpp"
#include "../../../fixtures/StringWeight.hpp"
using namespace testing;
namespace wali {
namespace wfa {
TEST(wali$wfa$$pathSummary, canCallPathSummaryWithNoFinalStates)
{
Letters l;
WFA wfa;
sem_elem_t one = Reach(true).one();
sem_elem_t zero = Reach(true).zero();
Key s1 = getKey("state1");
Key s2 = getKey("state2");
Key s3 = getKey("state3");
Key a = getKey("sym");
wfa.addState(s1, zero);
wfa.addState(s2, zero);
wfa.addState(s3, zero);
wfa.setInitialState(s1);
wfa.addTrans(s1, a, s2, one);
wfa.addTrans(s1, a, s3, one);
wfa.addTrans(s3, a, s2, one);
wfa.addTrans(s2, a, s1, one);
wfa.path_summary_crosscheck_all();
}
TEST(wali$wfa$$pathSummary, oneTransitionWfa)
{
Letters l;
WFA wfa;
sem_elem_t one = Reach(true).one();
sem_elem_t zero = Reach(true).zero();
Key s1 = getKey("state1");
Key s2 = getKey("state2");
Key a = getKey("sym");
wfa.addState(s1, zero);
wfa.addState(s2, zero);
wfa.setInitialState(s1);
wfa.addFinalState(s2);
wfa.addTrans(s1, a, s2, one);
sem_elem_t initial_weight = wfa.getState(s1)->weight();
ASSERT_TRUE(initial_weight->equal(zero));
wfa.path_summary_crosscheck_all();
initial_weight = wfa.getState(s1)->weight();
ASSERT_TRUE(initial_weight->equal(one));
}
TEST(wali$wfa$$pathSummary, parallelTransitionsWfa)
{
Letters l;
WFA wfa;
sem_elem_t w1 = new StringWeight("w1");
sem_elem_t w2 = new StringWeight("w2");
sem_elem_t either = new StringWeight("w1 | w2");
sem_elem_t zero = w1->zero();
Key s1 = getKey("state1");
Key s2 = getKey("state2");
Key a = getKey("sym1");
Key b = getKey("sym2");
wfa.addState(s1, zero);
wfa.addState(s2, zero);
wfa.setInitialState(s1);
wfa.addFinalState(s2);
wfa.addTrans(s1, a, s2, w1);
wfa.addTrans(s1, b, s2, w2);
sem_elem_t initial_weight = wfa.getState(s1)->weight();
ASSERT_TRUE(initial_weight->equal(zero));
wfa.path_summary_crosscheck_all();
initial_weight = wfa.getState(s1)->weight();
ASSERT_TRUE(initial_weight->equal(either));
}
TEST(wali$wfa$$pathSummary, twoSequentialTransitionsReverseQuery)
{
Letters l;
WFA wfa;
sem_elem_t w1 = new StringWeight("w1");
sem_elem_t w2 = new StringWeight("w2");
sem_elem_t seq = new StringWeight("w2 w1");
sem_elem_t zero = w1->zero();
Key s1 = getKey("state1");
Key s2 = getKey("state2");
Key s3 = getKey("state3");
Key a = getKey("sym1");
wfa.addState(s1, zero);
wfa.addState(s2, zero);
wfa.addState(s3, zero);
wfa.setInitialState(s1);
wfa.addFinalState(s3);
wfa.addTrans(s1, a, s2, w1);
wfa.addTrans(s2, a, s3, w2);
sem_elem_t initial_weight = wfa.getState(s1)->weight();
ASSERT_TRUE(initial_weight->equal(zero));
wfa.setQuery(WFA::REVERSE);
wfa.path_summary_crosscheck_all();
initial_weight = wfa.getState(s1)->weight();
std::cerr << initial_weight->toString() << "\n";
ASSERT_TRUE(initial_weight->equal(seq));
}
TEST(wali$wfa$$pathSummary, twoSequentialTransitionsForwardQuery)
{
Letters l;
WFA wfa;
sem_elem_t w1 = new StringWeight("w1");
sem_elem_t w2 = new StringWeight("w2");
sem_elem_t seq = new StringWeight("w1 w2");
sem_elem_t zero = w1->zero();
Key s1 = getKey("state1");
Key s2 = getKey("state2");
Key s3 = getKey("state3");
Key a = getKey("sym1");
wfa.addState(s1, zero);
wfa.addState(s2, zero);
wfa.addState(s3, zero);
wfa.setInitialState(s1);
wfa.addFinalState(s3);
wfa.addTrans(s1, a, s2, w1);
wfa.addTrans(s2, a, s3, w2);
sem_elem_t initial_weight = wfa.getState(s1)->weight();
ASSERT_TRUE(initial_weight->equal(zero));
wfa.setQuery(WFA::INORDER);
wfa.path_summary_crosscheck_all();
initial_weight = wfa.getState(s1)->weight();
std::cerr << initial_weight->toString() << "\n";
ASSERT_TRUE(initial_weight->equal(seq));
}
}
}
|
#include <node.h>
#include <v8.h>
using namespace v8;
void hello(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() < 2 || !args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
Local<Function> callback = Local<Function>::Cast(args[1]);
Local<Value> argv[1] = {
String::Concat(Local<String>::Cast(args[0]), String::NewFromUtf8(isolate, " world"))
};
callback->Call(isolate->GetCurrentContext()->Global(), 1, argv);
}
void init(Handle<Object> exports) {
NODE_SET_METHOD(exports, "hello", hello);
}
NODE_MODULE(test, init);
|
/* $Id$ -*- mode: c++ -*- */
/** \file parser.yy Contains the example Bison parser source */
%{ /*** C/C++ Declarations ***/
#include <fstream>
#include <stdio.h>
#include <string>
#include <vector>
#include "expression.h"
#include <magma/ast/translation_unit.h>
#include <magma/parse/parser.h>
using translation_unit_ptr = std::unique_ptr<magma::ast::translation_unit>;
%}
/*** yacc/bison Declarations ***/
/* Require bison 2.3 or later */
%require "3.0.4"
/* add debug output code to generated parser. disable this for release
* versions. */
%debug
/* start symbol is named "module" */
%start module
/* write out a header file containing the token defines */
%defines
/* use newer C++ skeleton file */
%skeleton "lalr1.cc"
/* namespace to enclose parser in */
%name-prefix="example"
/* set the parser's class identifier */
%define "parser_class_name" "Parser"
%define api.namespace {magma::yacc}
/* Use C++ variant support, enabling nodes to use raw C++ types. */
%define api.value.type variant
/* keep track of the current position within the input */
%locations
/**
* Run before parsing starts.
*/
%initial-action
{
// initialize the initial location object
@$.begin.filename = @$.end.filename = &driver.path_;
};
/* The driver is passed by reference to the parser and to the scanner. This
* provides a simple but effective pure interface, not relying on global
* variables. */
%param { magma::parse::parser& driver }
/* verbose error messages */
%error-verbose
/*** BEGIN EXAMPLE - Change the example grammar's tokens below ***/
%token END 0 "end of file"
%token sep_colon ":"
%token sep_term ";"
%token sep_comma ","
%token identifier "identifier"
%token kw_uniform "uniform"
%token kw_vector "vector"
%token kw_fn "fn"
%token kw_vs "vs"
%token kw_hs "hs"
%token kw_ds "ds"
%token kw_gs "gs"
%token kw_fs "fs"
%token kw_cs "cs"
%token op_assign "="
%token op_add "+"
%token op_sub "-"
%token op_mul "*"
%token op_div "/"
%token lit_int "int-literal"
%token lit_float "fp-literal"
%token lparen "("
%token rparen ")"
%token LBRACE "{"
%token RBRACE "}"
%token INTEGER "integer"
%token DOUBLE "double"
%token STRING "string"
/*** END EXAMPLE - Change the example grammar's tokens above ***/
%{
#include "driver.h"
#include "scanner.h"
/* this "connects" the bison parser in the driver to the flex scanner class
* object. it defines the yylex() function call to pull the next token from the
* current lexer object of the driver context. */
#undef yylex
#define yylex reinterpret_cast<example::Scanner*>(driver.lexer)->lex
%}
%% /*** Grammar Rules ***/
/*** BEGIN EXAMPLE - Change the example grammar rules below ***/
literal: lit_int
| lit_float
variable: identifier
| literal
expr: variable
| binary_expr
| call_expr
binary_op: op_add
| op_sub
| op_mul
| op_div
binary_expr: expr binary_op expr
expr_list: expr
| expr sep_comma expr_list
call_expr: identifier lparen rparen
| identifier lparen expr_list rparen
kw_decl: kw_uniform
| kw_vector
vardecl : kw_decl identifier sep_colon identifier op_assign expr
statement : sep_term
| vardecl sep_term
statement_list : /* empty */
| statement statement_list
function : kw_fn identifier lparen rparen LBRACE statement_list RBRACE
globaldecl : function
globaldecls : globaldecl
| globaldecl globaldecls
module : /* empty */ END
| globaldecls
/*** END EXAMPLE - Change the example grammar rules above ***/
%% /*** Additional Code ***/
void magma::yacc::Parser::error(const Parser::location_type &l,
const std::string &m) {
driver.error(l, m);
}
int magma::parse::parser::parse(const char* path) {
std::fstream in{path};
example::Scanner scanner{&in};
scanner.set_debug(true);
this->lexer = &scanner;
magma::yacc::Parser parser{*this};
parser.parse();
return 0;
}
|
// Created on: 1997-02-12
// Created by: Alexander BRIVIN
// Copyright (c) 1997-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 _Vrml_Translation_HeaderFile
#define _Vrml_Translation_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <gp_Vec.hxx>
#include <Standard_OStream.hxx>
//! defines a Translation of VRML specifying transform
//! properties.
//! This node defines a translation by 3D vector.
//! By default :
//! myTranslation (0,0,0)
class Vrml_Translation
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT Vrml_Translation();
Standard_EXPORT Vrml_Translation(const gp_Vec& aTranslation);
Standard_EXPORT void SetTranslation (const gp_Vec& aTranslation);
Standard_EXPORT gp_Vec Translation() const;
Standard_EXPORT Standard_OStream& Print (Standard_OStream& anOStream) const;
protected:
private:
gp_Vec myTranslation;
};
#endif // _Vrml_Translation_HeaderFile
|
#define NOMINMAX
#include <functional>
#include <array>
#include "buffers.h"
#include "ctalib.h"
#include "pytorchcpp.h"
#include "moneybars.h"
template<class T>
using vec_iterator = typename std::vector<T>::iterator;
// an indicator the each sample calculated
// depends itself + window-1 samples before it
// or u need window samples to produce 1 output
// simplest example: z
// - diff 1st order : window = 2 samples, out[t] = x[t]-x[t-1]
// - m_prev_data.resize(2-1) only need 1 previous sample
// TypeSt for storage - can have multiple buffers to store
// TypeIn for input
template<typename TypeSt, typename TypeIn, int NumberBuffers>
class CWindowIndicator
{
protected:
std::array<buffer<TypeSt>, NumberBuffers> m_buffers;
size_t m_buffersize;
size_t m_window; // minimum number of input samples to produce 1 output sample
size_t m_prev_needed; // m_prev_need + 1 = 1 to produce 1 output sample
// last data
// used to make previous calculations size window
// needed to calculate next batch of new samples
// true or false for existing previous values
buffer<TypeIn> m_prev_data;
std::vector<TypeIn> m_calculating; // now calculating
// just calculated, can have multiple outputs due multiple buffers
std::array<std::vector<TypeSt>, NumberBuffers> m_calculated; // outputs have storage type
size_t m_nprev; // size of already stored data previous
size_t m_new; // size of recent call new data
// where starts non EMPTY values
size_t m_total_count; // count added samples (like size()) but continues beyound BUFFERSIZE
// Event on Refresh for Son indicator
std::function<void(int)> m_onRefresh; // pass number of empty samples created or 0 for none
size_t m_nempty; // number of dummy/empty samples added on last call
size_t m_ndummy; // total dummy/empty on buffer
size_t m_ncalculated; // number of samples being calculated or calculated on the last call
public :
CWindowIndicator(int buffersize){
m_window = 1; // output is m_window -1 + 1
m_ncalculated = m_nempty = m_ndummy = m_total_count = m_new = m_nprev = m_prev_needed = 0;
m_buffersize = buffersize;
// max sized to avoid resizing during calls
m_calculating.resize(m_buffersize);
for (int i = 0; i < NumberBuffers; i++) {
m_calculated[i].resize(m_buffersize);
m_buffers[i].set_capacity(m_buffersize);
}
}
CWindowIndicator() : CWindowIndicator(BUFFERSIZE)
{};
void Init(int window) {
m_window = window;
m_prev_needed = m_window - 1;
m_prev_data.set_capacity(m_prev_needed);
}
// overload better than break everything
template<class iterator_type>
int Refresh(iterator_type start,
iterator_type end) {
auto count = std::distance(start, end);
m_ncalculated = 0;
m_nempty = 0;
m_new = count;
m_nprev = m_prev_data.size(); // number of previous data
if (count==0) // no data
return 0;
// needs m_window-1 previous samples + count > 0 to calculate 1 output sample
// check enough samples using previous
if (m_nprev < m_prev_needed) { // m_prev_need + 1 = 1 output
if (m_nprev + count < m_window) { // cannot calculate 1 output
// not enough data now, but insert on previous data
m_prev_data.addrange<iterator_type>(start, end);
// add dummy samples to mainting allignment with time and buffers
m_nempty = count;
m_total_count += m_nempty;
AddEmpty(m_nempty);
if (m_onRefresh)
m_onRefresh(m_nempty);
return 0;
}
else { // now can calculate 1 or more outputs
// insert the missing EMPTY_VALUES
m_nempty = m_prev_needed - m_nprev;
m_total_count += m_nempty;
AddEmpty(m_nempty);
}
}
// copy previous data
std::copy(m_prev_data.begin(), m_prev_data.end(), m_calculating.begin());
// copy in sequence new data
std::copy(start, end, m_calculating.begin() + m_nprev);
// needs m_window-1 previous samples to calculate 1 output sample
///////
m_ncalculated = (m_nprev + m_new) - m_prev_needed;
Calculate(m_calculating.data(), (m_nprev + m_new), m_calculated);
AddLatest();
// copy the now previous data for the subsequent call
m_prev_data.addrange<iterator_type>(end-m_new, end);
m_total_count += m_ncalculated;
// if exists son indicator you can
// call its Refresh now
if (m_onRefresh)
m_onRefresh(m_nempty);
return m_ncalculated;
}
// number of samples being calculated or calculated on the last Refresh() call
size_t nCalculated() { return m_ncalculated; }
// samples needed to calculated 1 output sample
size_t Window() { return m_window; }
// using vBegin()
// you dont need to keep track of valid indexes etc.
// begin removing empty == first invalid samples
typename buffer<TypeSt>::const_iterator vBegin(int buffer_index) {
// this wont be called that many times
// correction wether circular buffer is full or not
size_t offset = (m_total_count > m_buffersize) ? 0 : m_ndummy;
// it will be end() if dont have any valid samples
return m_buffers[buffer_index].begin() + offset;
}
typename buffer<TypeSt>::const_iterator Begin(int buffer_index) {
// this wont be called that many times
// correction wether circular buffer is full or not
return m_buffers[buffer_index].begin();
}
typename buffer<TypeSt>::const_iterator End(int buffer_index) {
return m_buffers[buffer_index].end();
}
// return the buffer by index, default to first buffer
typename buffer<TypeSt> & operator [](int buffer_index) {
return m_buffers[buffer_index];
}
// return the buffer by index - no check, default to first buffer
typename buffer<TypeSt>& Buffer(int buffer_index=0) {
return m_buffers[buffer_index];
}
// last calculated samples begin
typename buffer<TypeSt>::const_iterator vLastBegin(int buffer_index) {
return m_buffers[buffer_index].end() - m_ncalculated;
}
// last calculated samples begin
typename buffer<TypeSt>::const_iterator LastBegin(int buffer_index) {
return m_buffers[buffer_index].end() - m_new;
}
// number of valid samples
size_t vCount() {
return std::distance(vBegin(0), End(0));
}
size_t Count() { // number of elements on buffer(s)/same
return m_buffers[0].size();
}
// add a son indicator 'refresh' function
void addOnRefresh(std::function<void(int)> on_refresh) {
m_onRefresh = on_refresh;
}
// size
size_t BufferSize() {
return m_buffersize;
}
private:
// latest calculated data added on all buffers
void AddLatest() {
for (int i = 0; i < NumberBuffers; i++) {
m_buffers[i].addrange(m_calculated[i].data(), m_ncalculated);
}
}
protected:
// perform indicator calculation on indata
// will only be called with enough samples
// number of new samples calculated is m_ncalculated
// output on outdata
virtual void Calculate(TypeIn *indata, int size, std::array<std::vector<TypeSt>, NumberBuffers> &outdata) = 0;
// cannot happen as virtual - also (TypeIn*indata, int size) is optimal for most
// indicators calculations
//template<class iterator_type>
//virtual void Calculate(iterator_type start, iterator_type end,
// std::array<std::vector<TypeSt>, NumberBuffers>& outdata) = 0;
void AddEmpty(int count) {
m_ndummy += count;
for (int i = 0; i < NumberBuffers; i++) // empty value / dummy on all buffers
m_buffers[i].addempty(count);
}
};
class CWindowIndicatorDouble : public CWindowIndicator<double, double, 1>
{
public:
CWindowIndicatorDouble(int buffersize) : CWindowIndicator<double, double, 1>(buffersize)
{};
CWindowIndicatorDouble(void) : CWindowIndicatorDouble(BUFFERSIZE)
{};
};
//
// Indicators based on Ctalib
//
class CTaSTDDEV : public CWindowIndicatorDouble {
public:
CTaSTDDEV(void) : CWindowIndicatorDouble() {};
void Init(int window);
void Calculate(double *indata, int size, std::array<std::vector<double>, 1> &outdata) override;
};
class CTaMA : public CWindowIndicatorDouble {
protected:
int m_tama_type;
public:
CTaMA(void) {};
void Init(int window, int tama_type);
void Calculate(double* indata, int size, std::array<std::vector<double>, 1> &outdata) override;
};
// double up, down; array - up[0], down[1]
class CTaBBANDS : public CWindowIndicator<double, double, 2>
{
protected:
int m_tama_type;
double m_devs; // number of deviatons from the mean
// middle band calculated values needed for ctalib
std::vector<double> m_out_middle;
public:
CTaBBANDS() {
m_out_middle.resize(m_buffersize);
};
void Init(int window, double devs, int ma_type);
void Calculate(double* indata, int size, std::array<std::vector<double>, 2> &outdata) override;
// first buffer Upper Band
inline double Up(size_t index) { return m_buffers[0].at(index); }
// second buffer Lower Band
inline double Down(size_t index) { return m_buffers[1].at(index); }
};
//
// FracDiff
//
class CFracDiff : public CWindowIndicator<float, float, 1>
{
protected:
float m_dfraction; // fractional difference
public:
CFracDiff() { m_dfraction = 1; };
void Init(int window, float dfraction);
void Calculate(float* indata, int size, std::array<std::vector<float>, 1> &outdata) override;
};
//
// Return on MoneyBars price[i+1]/price[i] - 1.
// weighted return considering h, l and open inside each bar
//
class CMbReturn : public CWindowIndicator<double, MoneyBar, 1>
{
public:
CMbReturn() : CWindowIndicator() {};
void Init();
void Calculate(MoneyBar* inbars, int size, std::array<std::vector<double>, 1>& outdata) override;
};
//
// Windowed Augmented Dickey-Fuller test or SADF (supremum) ADF
// SADF very optimized for GPU using Libtorch C++ Pytorch
//
// must be double because of MT5
// each SADF(t) point have two values associated
class CSADF : public CWindowIndicator<float, float, 2>
{
protected:
int m_minw, m_maxw; // minimum and maximum backward window
int m_order; // max lag order of AR model
bool m_usedrift; // wether to include drift on AR model
float m_gpumemgb; // how much GPU memory each batch of SADF(t) should have
bool m_verbose; // wether show verbose messages when calculating
// for calculation using pytorchpp.dll
public:
CSADF(int buffersize);
void Init(int maxwindow, int minwindow, int order, bool usedrift=false, float gpumemgb=2.0, bool verbose=false);
void Calculate(float* indata, int size, std::array<std::vector<float>, 2> &outdata) override;
// SADF(t) value - first buffer
inline float SADFt(size_t index) { return m_buffers[0].at(index); }
// max values percentile dispersion of ADF on backward expanding window
inline float MaxADFdisp(size_t index) { return m_buffers[1].at(index); }
};
// Cum Sum filter
// due numpy/mt5 NAN's usage better use float as storage instead of int
class CCumSum : public CWindowIndicator<float, float, 1>
{
protected:
double m_cum_reset; // cumsum increment and reset level
double m_cum_up; // up cumsum
double m_cum_down; // down cumsum
public:
CCumSum(int buffersize);
void Init(double cum_reset);
void Calculate(float* indata, int size, std::array<std::vector<float>, 1>& outdata) override;
};
// Cum Sum filter
// due numpy/mt5 NAN's usage better use float as storage instead of int
class CCumSumSADF : public CCumSum
{
protected:
int m_sadf_prevn;
public:
CCumSumSADF(int buffersize);
void Init(double cum_reset, CSADF* pSADF);
void Calculate(float* indata, int size, std::array<std::vector<float>, 1>& outdata) override;
inline double At(size_t index) { return m_buffers[0].at(index); }
};
// Volatility on Money Bars average Returns - STDEV on Returns
// also use inside day from money bars for calculation
class CStdevMbReturn : public CTaSTDDEV
{
int m_mbret_prevn;
public:
CStdevMbReturn() : CTaSTDDEV() {};
void Init(int window, CMbReturn* pMbReturns);
void Calculate(double* indata, int size, std::array<std::vector<double>, 1>& outdata) override;
inline double At(size_t index) { return m_buffers[0].at(index); }
};
///// previous implementation
// probably useless but I am unwilling to delete
// due all effort envolved
// Cum Sum filter
// due numpy/mt5 NAN's usage better use float as storage instead of int
class CCumSumPair : public CWindowIndicator<float, std::pair<float, int>, 1>
{
protected:
double m_cum_reset; // cumsum increment and reset level
double m_cum_up; // up cumsum
double m_cum_down; // down cumsum
public:
CCumSumPair(int buffersize);
void Init(double cum_reset);
void Calculate(std::pair<float, int>* indata, int size, std::array<std::vector<float>, 1>& outdata) override;
};
// valid intraday operational window - not needed in fact
// 0 for not valid 1 for valid
// applied on timebars
//class CIntraday : public CWindowIndicator<int, MoneyBar, 1>
//{
// float m_start_hour, m_end_hour;
//
//public:
//
// CIntraday(int buffersize);
//
// void Init(float start_hour, float end_hour);
//
// void Calculate(MoneyBar* indata, int size, std::array<std::vector<int>, 1> & outdata) override;
//
// inline int isIntraday(size_t index) { return m_buffers[0].at(index); }
//
//};
//// Cum Sum filter on SADF
class CCumSumSADFPair : public CCumSumPair
{
int m_sadf_prevn;
public:
CCumSumSADFPair(int buffersize);
void Init(double cum_reset, CSADF* pSADF, MoneyBarBuffer* pBars);
void Calculate(std::pair<float, int>* indata, int size, std::array<std::vector<float>, 1>& outdata) override;
};
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t, n, k, dig, ans;
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> n >> k;
ans= 0;
for (int j = 0; j < n; j++)
{
cin >> dig;
if (i % 2){
if(abs(ans) >= 0)
ans -= dig;
else
ans += dig;
}
else{
if(abs(ans) > 0)
ans += dig;
else
ans -= dig;
}
}
cout << abs(ans);
if( abs(ans) >= k)
cout << 1 << endl;
else
cout << 2 << endl;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "InputManagerDialog.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeView.h"
#include "adjunct/quick_toolkit/widgets/OpQuickFind.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/prefsfile/prefsentry.h"
#include "modules/prefsfile/prefssection.h"
#include "modules/url/url_man.h"
#include "modules/util/OpLineParser.h"
#include "modules/widgets/WidgetContainer.h"
#include "modules/widgets/OpWidgetFactory.h"
#include "modules/locale/locale-enum.h"
#include "modules/locale/oplanguagemanager.h"
const char* InputManagerDialog::m_shortcut_sections[] =
{
"Application",
"Browser Window",
"Mail Window",
"Document Window",
"Compose Window",
"Bookmarks Panel",
"Contacts Panel",
"History Panel",
"Links Panel",
// "Chat Panel",
"Mail Panel",
"Transfers Panel",
"Windows Panel",
"Notes Panel",
NULL,
};
const char* InputManagerDialog::m_advanced_shortcut_sections[] =
{
"Dialog",
"Form",
"Widget Container",
"Browser Widget",
"Bookmarks Widget",
"Contacts Widget",
"Notes Widget",
"Button Widget",
"Radiobutton Widget",
"Checkbox Widget",
"Dropdown Widget",
"List Widget",
"Tree Widget",
"Edit Widget",
"Address Dropdown Widget",
NULL
};
#ifdef _MACINTOSH_
const uni_char* TranslateModifiersVolatile(const uni_char* instr, BOOL forWrite)
{
static OpString opstr;
static OpString meta;
static OpString ctrl;
static OpString alt;
static OpString shift;
if(alt.IsEmpty()) {
g_languageManager->GetString(Str::M_KEY_ALT, alt);
}
#ifdef _ALLOW_CONTROL_KEY_AND_COMMAND_KEY_IN_SHORTCUTS_
if(meta.IsEmpty()) {
g_languageManager->GetString(Str::M_KEY_META, meta);
}
#endif
if(ctrl.IsEmpty()) {
g_languageManager->GetString(Str::M_KEY_CTRL, ctrl);
}
if(shift.IsEmpty()) {
g_languageManager->GetString(Str::M_KEY_SHIFT, shift);
}
if (ctrl.IsEmpty() ||
#ifdef _ALLOW_CONTROL_KEY_AND_COMMAND_KEY_IN_SHORTCUTS_
meta.IsEmpty() ||
#endif
alt.IsEmpty() ||
shift.IsEmpty())
{
return instr;
}
opstr.Empty();
while (instr)
{
uni_char* scan = uni_strchr(instr, UNI_L(' '));
int len = scan ? scan-instr : uni_strlen(instr);
if(forWrite)
{
if (len==ctrl.Length() && !uni_strncmp(instr, ctrl.CStr(), len))
opstr.Append("ctrl");
else if (len==alt.Length() && !uni_strncmp(instr, alt.CStr(), len))
opstr.Append("alt");
else if (len==meta.Length() && !uni_strncmp(instr, meta.CStr(), len))
opstr.Append("meta");
else if (len==shift.Length() && !uni_strncmp(instr, shift.CStr(), len))
opstr.Append("shift");
else
opstr.Append(instr, len);
}
else {
if (len==4 && !uni_strncmp(instr, UNI_L("ctrl"), len))
opstr.Append(ctrl.CStr());
else if (len==3 && !uni_strncmp(instr, UNI_L("alt"), len))
opstr.Append(alt.CStr());
else if (len==4 && !uni_strncmp(instr, UNI_L("meta"), len))
opstr.Append(meta.CStr());
else if (len==5 && !uni_strncmp(instr, UNI_L("shift"), len))
opstr.Append(shift.CStr());
else
opstr.Append(instr, len);
}
if (scan)
opstr.Append(" ");
instr = scan?scan+1:scan;
}
return opstr.CStr();
}
#endif
/***********************************************************************************
**
** InputManagerDialog
**
***********************************************************************************/
InputManagerDialog::~InputManagerDialog()
{
OP_DELETE(m_input_prefs);
}
/***********************************************************************************
**
** OnInit
**
***********************************************************************************/
void InputManagerDialog::OnInit()
{
// this is the one we will change and write
OpString title;
switch(m_input_type)
{
case OPKEYBOARD_SETUP:
{
m_old_file_index = g_setup_manager->GetIndexOfKeyboardSetup();
INT32 index = m_input_index < 0 || m_input_index >= (INT32)g_setup_manager->GetKeyboardConfigurationCount() ? m_old_file_index : m_input_index;
TRAPD(rc, m_input_prefs = g_setup_manager->GetSetupPrefsFileL(index, m_input_type, NULL, TRUE));
m_new_file_index = g_setup_manager->GetIndexOfKeyboardSetup();
g_languageManager->GetString(Str::D_EDIT_KEYBOARD_SETUP, title);
}
break;
case OPMOUSE_SETUP:
{
m_old_file_index = g_setup_manager->GetIndexOfMouseSetup();
INT32 index = m_input_index < 0 || m_input_index >= (INT32)g_setup_manager->GetMouseConfigurationCount() ? m_old_file_index : m_input_index;
TRAPD(rc, m_input_prefs = g_setup_manager->GetSetupPrefsFileL(index, m_input_type, NULL, TRUE));
m_new_file_index = g_setup_manager->GetIndexOfMouseSetup();
g_languageManager->GetString(Str::D_EDIT_MOUSE_SETUP, title);
}
break;
default:
{
OP_ASSERT(FALSE); //unknown type... look into it!
}
break;
}
SetTitle(title.CStr());
m_input_treeview = (OpTreeView*) GetWidgetByName("Input_treeview");
OpQuickFind* quickfind = (OpQuickFind*) GetWidgetByName("Quickfind_edit");
m_input_treeview->SetAutoMatch(TRUE);
m_input_treeview->SetShowThreadImage(TRUE);
quickfind->SetTarget(m_input_treeview);
OpString str;
g_languageManager->GetString(Str::S_CONTEXT_AND_SHORTCUT, str);
m_input_model.SetColumnData(0, str.CStr());
g_languageManager->GetString(Str::S_ACTIONS, str);
m_input_model.SetColumnData(1, str.CStr());
AddShortcutSections(m_shortcut_sections, -1);
Item *new_item = OP_NEW(Item, (ITEM_CATEGORY, NULL));
if (new_item)
{
INT32 parent_index = m_input_model.AddItem(UNI_L("Advanced"), NULL, 0, -1, new_item);
AddShortcutSections(m_advanced_shortcut_sections, parent_index);
}
m_input_treeview->SetTreeModel(&m_input_model);
}
/***********************************************************************************
**
** GetHelpAnchor
**
***********************************************************************************/
const char* InputManagerDialog::GetHelpAnchor()
{
switch (m_input_type)
{
case OPKEYBOARD_SETUP:
// deliberate fall through to OPMOUSE_SETUP
case OPMOUSE_SETUP:
return "mouse.html";
break;
default:
{
OP_ASSERT(FALSE); //unknown type... look into it!
}
break;
}
return "";
}
/***********************************************************************************
**
** OnInitVisibility
**
***********************************************************************************/
void InputManagerDialog::OnInitVisibility()
{
}
/***********************************************************************************
**
** AddShortcutSections
**
***********************************************************************************/
void InputManagerDialog::AddShortcutSections(const char** shortcut_section, INT32 root)
{
for (; *shortcut_section; shortcut_section++)
{
AddShortcutSection(*shortcut_section, root, -1, FALSE);
}
}
/***********************************************************************************
**
** AddShortcutSections
**
***********************************************************************************/
void InputManagerDialog::AddShortcutSection(const char* shortcut_section, INT32 root, INT32 parent_index, BOOL force_default)
{
if (!m_input_prefs)
return;
BOOL was_default = FALSE;
PrefsSection* section = m_input_prefs->IsSection(shortcut_section) && !force_default ? m_input_prefs->ReadSectionL(shortcut_section) : g_setup_manager->GetSectionL(shortcut_section, m_input_type, &was_default, TRUE);
if (parent_index == -1)
{
Item* item = OP_NEW(Item, (ITEM_SECTION, shortcut_section));
if (item)
{
OpString8 name8;
item->MakeSectionString(name8, was_default);
OpString name;
name.Set(name8);
parent_index = m_input_model.AddItem(name.CStr(), NULL, 0, root, item);
}
}
else
{
OpString8 name8;
m_input_model.GetItem(parent_index)->MakeSectionString(name8, was_default);
OpString name;
name.Set(name8);
m_input_model.SetItemData(parent_index, 0, name.CStr());
while (m_input_model.GetChildIndex(parent_index) != -1)
{
m_input_model.DeleteItem(m_input_model.GetChildIndex(parent_index));
}
}
if (section)
{
for (const PrefsEntry *entry = section->Entries(); entry; entry = (const PrefsEntry *) entry->Suc())
{
const uni_char* key = entry->Key();
// translate voice commands, for example
OpString translated_key;
Str::LocaleString key_id(Str::NOT_A_STRING);
if (key && uni_stristr(key, UNI_L(",")) == NULL && m_input_type != OPKEYBOARD_SETUP)
{
OpLineParser key_line(key);
key_line.GetNextLanguageString(translated_key, &key_id);
if (translated_key.HasContent())
{
OpLineParser key_line(key);
key_line.GetNextLanguageString(translated_key, &key_id);
if (translated_key.HasContent())
{
key = translated_key.CStr();
}
}
}
Item *new_item = OP_NEW(Item, (ITEM_ENTRY, shortcut_section));
if (new_item)
{
#ifdef _MACINTOSH_
INT32 got_index = m_input_model.AddItem(TranslateModifiersVolatile(key, FALSE), NULL, 0, parent_index, new_item);
#else
INT32 got_index = m_input_model.AddItem(key, NULL, 0, parent_index, new_item);
#endif
OpLineParser line(entry->Value());
OpString8 action;
line.GetNextToken8(action);
m_input_model.SetItemData(got_index, 1, entry->Value(), action.CStr());
}
}
OP_DELETE(section);
}
}
/***********************************************************************************
**
** OnOk
**
***********************************************************************************/
UINT32 InputManagerDialog::OnOk()
{
if (!m_input_prefs)
return 0;
for (OP_MEMORY_VAR INT32 i = 0; i < m_input_model.GetItemCount(); i++)
{
Item* item = m_input_model.GetItem(i);
if (item && item->IsSection() && item->IsChanged())
{
m_input_prefs->ClearSectionL(item->GetSection().CStr());
for (OP_MEMORY_VAR INT32 j = m_input_model.GetChildIndex(i);
j != -1; j = m_input_model.GetSiblingIndex(j))
{
Item* item = m_input_model.GetItem(j);
if (item && item->IsEntry())
{
const uni_char* trigger = m_input_model.GetItemString(j, 0);
const uni_char* action = m_input_model.GetItemString(j, 1);
if (trigger && *trigger && action && *action)
{
OpString8 trigger8;
#ifdef _MACINTOSH_
trigger8.Set(TranslateModifiersVolatile(trigger, TRUE));
#else
trigger8.Set(trigger);
#endif
TRAPD(err, m_input_prefs->WriteStringL(item->GetSection().CStr(), trigger8, action));
}
}
}
}
}
TRAPD(rc,m_input_prefs->CommitL());
//this will update the preferences dialog page for both keyboard and mouse
g_application->SettingsChanged(SETTINGS_KEYBOARD_SETUP);
g_setup_manager->ReloadSetupFile(m_input_type);
return 0;
}
/***********************************************************************************
**
** OnMouseEvent
**
***********************************************************************************/
void InputManagerDialog::OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks)
{
if (widget == m_input_treeview && nclicks == 2)
{
Item* item = m_input_model.GetItem(m_input_treeview->GetModelPos(pos));
if (item && item->IsEntry())
{
OpRect rect;
if (m_input_treeview->GetCellRect(pos, 1, rect) && rect.Contains(OpPoint(x,y)))
{
m_input_treeview->EditItem(pos, 1, TRUE, AUTOCOMPLETION_ACTIONS);
}
else
{
m_input_treeview->EditItem(pos, 0, TRUE);
}
}
}
}
/***********************************************************************************
**
** OnItemEdited
**
***********************************************************************************/
void InputManagerDialog::OnItemEdited(OpWidget *widget, INT32 pos, INT32 column, OpString& text)
{
if (column == 0)
{
m_input_model.SetItemData(m_input_treeview->GetModelPos(pos), column, text.CStr());
}
else
{
OpLineParser line(text.CStr());
OpString8 action;
line.GetNextToken8(action);
m_input_model.SetItemData(m_input_treeview->GetModelPos(pos), column, text.CStr(), action.CStr());
}
OnItemChanged(m_input_treeview->GetModelPos(pos));
}
/***********************************************************************************
**
** OnItemChanged
**
***********************************************************************************/
void InputManagerDialog::OnItemChanged(INT32 model_pos)
{
model_pos = m_input_model.GetParentIndex(model_pos);
Item* item = m_input_model.GetItem(model_pos);
if (item && item->IsSection())
{
item->SetChanged(TRUE);
OpString8 name8;
item->MakeSectionString(name8, FALSE);
OpString name;
name.Set(name8);
m_input_model.SetItemData(model_pos, 0, name.CStr());
}
}
/***********************************************************************************
**
** OnChange
**
***********************************************************************************/
void InputManagerDialog::OnChange(OpWidget *widget, BOOL changed_by_mouse)
{
}
/***********************************************************************************
**
** OnInputAction
**
***********************************************************************************/
BOOL InputManagerDialog::OnInputAction(OpInputAction* action)
{
if (!m_input_treeview)
return Dialog::OnInputAction(action);
if (m_input_treeview->OnInputAction(action))
return TRUE;
INT32 pos = m_input_treeview->GetSelectedItemPos();
INT32 model_pos = m_input_treeview->GetSelectedItemModelPos();
Item* item = m_input_model.GetItem(model_pos);
if (!item || item->IsCategory())
return Dialog::OnInputAction(action);
switch (action->GetAction())
{
case OpInputAction::ACTION_LOWLEVEL_PREFILTER_ACTION:
{
switch (action->GetChildAction()->GetAction())
{
case OpInputAction::ACTION_FOCUS_NEXT_WIDGET:
{
if (m_input_treeview->GetEditColumn() == 0)
{
m_input_treeview->EditItem(m_input_treeview->GetEditPos(), 1, TRUE, AUTOCOMPLETION_ACTIONS);
return TRUE;
}
else if (m_input_treeview->GetEditColumn() == 1)
{
m_input_treeview->FinishEdit();
return TRUE;
}
break;
}
}
return FALSE;
}
case OpInputAction::ACTION_RESET_SHORTCUTS:
{
if (item->IsEntry())
{
model_pos = m_input_model.GetParentIndex(model_pos);
item = m_input_model.GetItem(model_pos);
}
AddShortcutSection(item->GetSection().CStr(), -1, model_pos, TRUE);
item->SetChanged(TRUE);
return TRUE;
}
case OpInputAction::ACTION_NEW_SHORTCUT:
{
INT32 got_index;
Item *new_item = OP_NEW(Item, (ITEM_ENTRY, item->GetSection().CStr()));
if (new_item)
{
if (item->IsSection())
{
got_index = m_input_model.AddItem(NULL, NULL, 0, model_pos, new_item);
}
else
{
got_index = m_input_model.InsertBefore(model_pos, NULL, NULL, 0, new_item);
}
m_input_treeview->EditItem(m_input_treeview->GetItemByModelPos(got_index), 0, TRUE);
}
return TRUE;
}
case OpInputAction::ACTION_DELETE:
{
if (item->IsEntry())
{
OnItemChanged(model_pos); // Do this first, otherwise it will fail
m_input_model.DeleteItem(model_pos);
}
return TRUE;
}
case OpInputAction::ACTION_EDIT_PROPERTIES:
{
if (item->IsEntry())
{
m_input_treeview->EditItem(pos, 0, TRUE);
}
return TRUE;
}
}
return Dialog::OnInputAction(action);
}
/***********************************************************************************
**
** WriteShortcutSections
**
***********************************************************************************/
/*static*/ void InputManagerDialog::WriteShortcutSections(OpSetupType input_type, URL& url)
{
url.WriteDocumentData(URL::KNormal, "<h1>", 4);
if (input_type == OPKEYBOARD_SETUP)
{
OpString keyboard_setup;
g_languageManager->GetString(Str::S_KEYBOARD_SETUP, keyboard_setup);
url.WriteDocumentData(URL::KNormal, keyboard_setup.CStr());
}
else
{
OpString mouse_setup;
g_languageManager->GetString(Str::S_MOUSE_SETUP, mouse_setup);
url.WriteDocumentData(URL::KNormal, mouse_setup.CStr());
}
url.WriteDocumentData(URL::KNormal, "</h1>", 5);
WriteShortcutSections(input_type, m_shortcut_sections, url);
WriteShortcutSections(input_type, m_advanced_shortcut_sections, url);
}
/***********************************************************************************
**
** WriteShortcutSections
**
***********************************************************************************/
/*static*/ void InputManagerDialog::WriteShortcutSections(OpSetupType input_type, const char** shortcut_section, URL& url)
{
for (; *shortcut_section; shortcut_section++)
{
PrefsSection* section = g_setup_manager->GetSectionL(*shortcut_section, input_type, NULL, FALSE);
url.WriteDocumentData(URL::KNormal, "<h2>", 4);
url.WriteDocumentData(URL::KNormal, *shortcut_section, op_strlen(*shortcut_section));
url.WriteDocumentData(URL::KNormal, "</h2><table>", 12);
if (section)
{
for (const PrefsEntry *entry = section->Entries(); entry; entry = (const PrefsEntry *) entry->Suc())
{
url.WriteDocumentData(URL::KNormal, "<tr><td>", 8);
#ifdef _MACINTOSH_
url.WriteDocumentData(URL::KNormal, TranslateModifiersVolatile(entry->Key(), TRUE));
#else
url.WriteDocumentData(URL::KNormal, entry->Key());
#endif
url.WriteDocumentData(URL::KNormal, "</td><td>", 9);
url.WriteDocumentData(URL::KNormal, entry->Value());
url.WriteDocumentData(URL::KNormal, "</td></tr>", 10);
}
OP_DELETE(section);
}
url.WriteDocumentData(URL::KNormal, "</table>", 8);
}
}
/***********************************************************************************
**
** OnCancel
**
***********************************************************************************/
void InputManagerDialog::OnCancel()
{
//revert to old file, and delete the copied file, if any
if(m_new_file_index != m_old_file_index)
{
//delete the copied file
TRAPD(err, g_setup_manager->DeleteSetupL(m_new_file_index, m_input_type));
g_setup_manager->SelectSetupFile(m_old_file_index, m_input_type, FALSE);
}
//this will update the preferences dialog page for both keyboard and mouse
g_application->SettingsChanged(SETTINGS_KEYBOARD_SETUP);
}
|
// DrawButton.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "DrawButton.h"
#define MAX_LOADSTRING 100
// Global Variables:
HWND hWnd;
HWND hNew;
HWND hDlg;
//TCHAR buff[10];
int x1 = 100, x2 = 200, y1 = 150, y2 = 300;
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
BOOL CALLBACK DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_DRAWBUTTON, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_DRAWBUTTON));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DRAWBUTTON));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = 0; //MAKEINTRESOURCEW(IDC_DRAWBUTTON);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 400, nullptr, nullptr, hInstance, nullptr);
CreateWindow(TEXT("BUTTON"), TEXT("Show"), WS_CHILD | WS_VISIBLE, 30, 30, 80, 40, hWnd, (HMENU)999, nullptr, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case 1998:
{
SetWindowText(hWnd, L"Catch");
if (!hNew)
{
hNew = CreateWindow(TEXT("BUTTON"), TEXT("NEW"), WS_CHILD | WS_VISIBLE, x1, y1, x2, y2, ::hWnd, (HMENU)995, nullptr, nullptr);
}
else
{
DestroyWindow(hNew);
hNew = CreateWindow(TEXT("BUTTON"), TEXT("NEW"), WS_CHILD | WS_VISIBLE, x1, y1, x2, y2, ::hWnd, (HMENU)995, nullptr, nullptr);
}
//InvalidateRect(hNew, NULL, FALSE);
//UpdateWindow(hWnd);
break;
}
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case 999:
{
if (!hDlg)
{
hDlg = CreateDialog(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, DLGPROC(DlgProc));
}
else
{
DestroyWindow(hDlg);
hDlg = CreateDialog(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, DLGPROC(DlgProc));
}
SetWindowText(hWnd, L"Wait enter...");
ShowWindow(hDlg, 1);
}
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
BOOL CALLBACK DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CLOSE:
DestroyWindow(hDlg);
return TRUE;
case WM_COMMAND:
{
int Id = LOWORD(wParam);
switch (Id)
{
case IDC_BUTTON1:
{
TCHAR buff[10];
GetDlgItemText(hDlg, IDC_EDIT1, buff, 10);
x1 = _wtoi(buff);
GetDlgItemText(hDlg, IDC_EDIT2, buff, 10);
y1 = _wtoi(buff);
GetDlgItemText(hDlg, IDC_EDIT3, buff, 10);
x2 = _wtoi(buff);
GetDlgItemText(hDlg, IDC_EDIT4, buff, 10);
y2 = _wtoi(buff);
SetWindowText(::hWnd, L"Draw...");
SendMessage(::hWnd, 1998, WPARAM(NULL), LPARAM(NULL));
}
return TRUE;
}
}
}
return FALSE;
}
|
#pragma once
class CSync
{
private:
CRITICAL_SECTION m_cs;
public:
CSync();
~CSync();
void Lock();
void Unlock();
};
|
#pragma once
#include <SFML/Network.hpp>
#include <list>
#include "../Shared/GameConfig.h"
#include "RectangleCollider.h"
class GameObject
{
public:
GameObject(float x, float y, conf::Dir dir_, float animation_speed_,
int frame_amount_, float speed_, conf::ObjectType type_);
GameObject();
virtual ~GameObject() = default;
void set_position(sf::Vector2f& pos);
void set_direction(conf::Dir dir_);
void set_speed(float speed);
void set_active(bool act);
int animate(float time);
virtual void update(sf::Time time, std::list<GameObject*>& objects) = 0;
virtual void compress_packet(sf::Packet& packet) = 0;
virtual void get_damage(int size);
sf::Vector2f get_position() const;
conf::Dir get_direction() const;
float get_speed() const;
conf::ObjectType get_type() const;
int get_current_frame() const;
bool get_active() const;
const RectangleCollider& get_collider() const;
float distance(sf::Vector2f pos);
float fast_square_root(float n);
sf::Vector2f compute_unit_vector(const sf::Vector2f &first, const sf::Vector2f &second);
sf::Vector2f get_shift(conf::Dir dir, float tm);
protected:
sf::Vector2f position;
float speed;
float diag_speed;
conf::Dir dir;
float animation_speed;
float current_frame;
int frame_amount;
RectangleCollider collider;
conf::ObjectType type;
bool is_active;
virtual void interract(std::list<GameObject*>& objects, sf::Time time) = 0;
bool check_border() const;
};
|
// Created on: 1993-04-15
// Created by: Bruno DUMORTIER
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Adaptor2d_OffsetCurve_HeaderFile
#define _Adaptor2d_OffsetCurve_HeaderFile
#include <Adaptor2d_Curve2d.hxx>
#include <GeomAbs_CurveType.hxx>
#include <GeomAbs_Shape.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_Array1OfReal.hxx>
class gp_Pnt2d;
class gp_Vec2d;
class gp_Lin2d;
class gp_Circ2d;
class gp_Elips2d;
class gp_Hypr2d;
class gp_Parab2d;
class Geom2d_BezierCurve;
class Geom2d_BSplineCurve;
//! Defines an Offset curve (algorithmic 2d curve).
class Adaptor2d_OffsetCurve : public Adaptor2d_Curve2d
{
DEFINE_STANDARD_RTTIEXT(Adaptor2d_OffsetCurve, Adaptor2d_Curve2d)
public:
//! The Offset is set to 0.
Standard_EXPORT Adaptor2d_OffsetCurve();
//! The curve is loaded. The Offset is set to 0.
Standard_EXPORT Adaptor2d_OffsetCurve(const Handle(Adaptor2d_Curve2d)& C);
//! Creates an OffsetCurve curve.
//! The Offset is set to Offset.
Standard_EXPORT Adaptor2d_OffsetCurve(const Handle(Adaptor2d_Curve2d)& C, const Standard_Real Offset);
//! Create an Offset curve.
//! WFirst,WLast define the bounds of the Offset curve.
Standard_EXPORT Adaptor2d_OffsetCurve(const Handle(Adaptor2d_Curve2d)& C, const Standard_Real Offset, const Standard_Real WFirst, const Standard_Real WLast);
//! Shallow copy of adaptor
Standard_EXPORT virtual Handle(Adaptor2d_Curve2d) ShallowCopy() const Standard_OVERRIDE;
//! Changes the curve. The Offset is reset to 0.
Standard_EXPORT void Load (const Handle(Adaptor2d_Curve2d)& S);
//! Changes the Offset on the current Curve.
Standard_EXPORT void Load (const Standard_Real Offset);
//! Changes the Offset Curve on the current Curve.
Standard_EXPORT void Load (const Standard_Real Offset, const Standard_Real WFirst, const Standard_Real WLast);
const Handle(Adaptor2d_Curve2d)& Curve() const { return myCurve; }
Standard_Real Offset() const { return myOffset; }
virtual Standard_Real FirstParameter() const Standard_OVERRIDE { return myFirst; }
virtual Standard_Real LastParameter() const Standard_OVERRIDE { return myLast; }
Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE;
//! If necessary, breaks the curve in intervals of
//! continuity <S>. And returns the number of
//! intervals.
Standard_EXPORT Standard_Integer NbIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Stores in <T> the parameters bounding the intervals
//! of continuity <S>.
//!
//! The array must provide enough room to accommodate
//! for the parameters. i.e. T.Length() > NbIntervals()
Standard_EXPORT void Intervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Returns a curve equivalent of <me> between
//! parameters <First> and <Last>. <Tol> is used to
//! test for 3d points confusion.
//! If <First> >= <Last>
Standard_EXPORT Handle(Adaptor2d_Curve2d) Trim (const Standard_Real First, const Standard_Real Last, const Standard_Real Tol) const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE;
Standard_EXPORT Standard_Real Period() const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve.
Standard_EXPORT gp_Pnt2d Value (const Standard_Real U) const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve.
Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt2d& P) const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve with its
//! first derivative.
//! Raised if the continuity of the current interval
//! is not C1.
Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V) const Standard_OVERRIDE;
//! Returns the point P of parameter U, the first and second
//! derivatives V1 and V2.
//! Raised if the continuity of the current interval
//! is not C2.
Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2) const Standard_OVERRIDE;
//! Returns the point P of parameter U, the first, the second
//! and the third derivative.
//! Raised if the continuity of the current interval
//! is not C3.
Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3) const Standard_OVERRIDE;
//! The returned vector gives the value of the derivative for the
//! order of derivation N.
//! Raised if the continuity of the current interval
//! is not CN.
//! Raised if N < 1.
Standard_EXPORT gp_Vec2d DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE;
//! Returns the parametric resolution corresponding
//! to the real space resolution <R3d>.
Standard_EXPORT Standard_Real Resolution (const Standard_Real R3d) const Standard_OVERRIDE;
//! Returns the type of the curve in the current
//! interval : Line, Circle, Ellipse, Hyperbola,
//! Parabola, BezierCurve, BSplineCurve, OtherCurve.
Standard_EXPORT GeomAbs_CurveType GetType() const Standard_OVERRIDE;
Standard_EXPORT gp_Lin2d Line() const Standard_OVERRIDE;
Standard_EXPORT gp_Circ2d Circle() const Standard_OVERRIDE;
Standard_EXPORT gp_Elips2d Ellipse() const Standard_OVERRIDE;
Standard_EXPORT gp_Hypr2d Hyperbola() const Standard_OVERRIDE;
Standard_EXPORT gp_Parab2d Parabola() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer Degree() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsRational() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbPoles() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbKnots() const Standard_OVERRIDE;
Standard_EXPORT Handle(Geom2d_BezierCurve) Bezier() const Standard_OVERRIDE;
Standard_EXPORT Handle(Geom2d_BSplineCurve) BSpline() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbSamples() const Standard_OVERRIDE;
private:
Handle(Adaptor2d_Curve2d) myCurve;
Standard_Real myOffset;
Standard_Real myFirst;
Standard_Real myLast;
};
DEFINE_STANDARD_HANDLE(Adaptor2d_OffsetCurve, Adaptor2d_Curve2d)
#endif // _Adaptor2d_OffsetCurve_HeaderFile
|
// Lyric Player v1.0
// Date: 2015-5-12
#include <windows.h>
// #define _WIN32_WINNT 0x0600
#define MAX_TAGS 128
#define MAX_LYRICS 8192
#define FAST_RUNNING_RATE 20
#define REDUNDANCY 50
CONST CONSOLE_CURSOR_INFO CURSOR_INVISIBLE
= {25, FALSE};
CONST WORD FOREGROUND_NORMAL
= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
CONST WORD FOREGROUND_HIGHLIGHT
= FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;
struct {
INT milliseconds;
PTCH begin, end;
DWORD length;
COORD position;
} tags[MAX_TAGS];
DWORD count = 0;
TCHAR lyrics[MAX_LYRICS];
DWORD length;
bool schema_1 (TCHAR c) { return c == TEXT('['); }
bool schema_2 (TCHAR c) { return c >= TEXT('0') && c <= TEXT('9'); }
bool schema_3 (TCHAR c) { return c == TEXT(':'); }
bool schema_4 (TCHAR c) { return c >= TEXT('0') && c <= TEXT('5'); }
bool schema_5 (TCHAR c) { return c == TEXT('.'); }
bool schema_6 (TCHAR c) { return c == TEXT(']'); }
bool (* schema[10]) (TCHAR c) = { schema_1, schema_2, schema_2,
schema_3, schema_4, schema_2,
schema_5, schema_2, schema_2,
schema_6 };
class Timer {
public:
Timer();
VOID setTime(INT milliseconds);
VOID setRate(INT rate);
INT getTime();
INT getRate() const;
private:
LONGLONG frequency, countOrigin, countBegin, countEnd;
INT runningRate;
};
Timer::Timer() {
QueryPerformanceFrequency( (PLARGE_INTEGER) &frequency );
runningRate = 1;
setTime( 0 );
}
VOID Timer::setTime(INT milliseconds) {
countOrigin = frequency * milliseconds / 1000;
QueryPerformanceCounter( (PLARGE_INTEGER) &countBegin );
}
VOID Timer::setRate(INT rate) {
QueryPerformanceCounter( (PLARGE_INTEGER) &countEnd );
countOrigin = countOrigin + (countEnd - countBegin) * runningRate;
runningRate = rate;
QueryPerformanceCounter( (PLARGE_INTEGER) &countBegin );
}
INT Timer::getTime() {
QueryPerformanceCounter( (PLARGE_INTEGER) &countEnd );
INT milliseconds = INT( (countOrigin + (countEnd - countBegin) * runningRate) * 1000 / frequency );
if (milliseconds < 0) {
setTime( 0 );
return 0;
} else
return milliseconds;
}
INT Timer::getRate() const {
return runningRate;
}
int main() {
HANDLE hFile = CreateFile(TEXT("lyric.txt"), GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
ReadFile(hFile, lyrics, sizeof(lyrics), &length, NULL);
length = lstrlen(lyrics);
CloseHandle(hFile);
DWORD i, j;
tags[count].milliseconds = 0;
tags[count].begin = tags[count].end = lyrics;
tags[count].length = 0;
tags[count].position.X = tags[count].position.Y = 0;
++count;
for(i=0, j=0; i<length; ++i)
if( schema[j](lyrics[i]) ) {
if(j==9) {
tags[count].milliseconds = (lyrics[i-8] - '0') * 10 + (lyrics[i-7] - '0');
tags[count].milliseconds = tags[count].milliseconds * 6 + (lyrics[i-5] - '0');
tags[count].milliseconds = tags[count].milliseconds * 10 + (lyrics[i-4] - '0');
tags[count].milliseconds = tags[count].milliseconds * 10 + (lyrics[i-2] - '0');
tags[count].milliseconds = tags[count].milliseconds * 10 + (lyrics[i-1] - '0');
tags[count].milliseconds *= 10;
tags[count].begin = lyrics + i + 1;
++count;
j=0;
} else ++j;
} else j=0;
for(i=1; i<count-1; ++i) {
tags[i].end = tags[i+1].begin - 10;
tags[i].length = tags[i].end - tags[i].begin;
}
tags[i].end = lyrics + length;
tags[i].length = tags[i].end - tags[i].begin;
tags[count].milliseconds = tags[count-1].milliseconds + 1000;
tags[count].begin = tags[count].end = lyrics + length;
tags[count].length = 0;
tags[count].position.X = tags[count].position.Y = 0;
++count;
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
// GetCurrentConsoleFontEx(hStdout, FALSE, lpConsoleCurrentFontEx);
// SetCurrentConsoleFontEx(hStdout, FALSE, lpConsoleCurrentFontEx);
SetConsoleCursorInfo(hStdout, &CURSOR_INVISIBLE);
SetConsoleTextAttribute(hStdout, FOREGROUND_NORMAL);
for(i=0; i<count; ++i) {
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(hStdout, &info);
tags[i].position = info.dwCursorPosition;
WriteConsole(hStdout, tags[i].begin, tags[i].end-tags[i].begin, NULL, NULL);
}
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleMode(hStdin, 0);
INPUT_RECORD inputRecord;
DWORD numbleRead, numbleWritten;
DWORD currentTagIndex = 0;
Timer timer;
for(;;) {
INT millisecondsToWait = INFINITE;
if (timer.getRate() > 0) {
millisecondsToWait = ( tags[currentTagIndex+1].milliseconds - timer.getTime() )
/ timer.getRate() - REDUNDANCY;
if (millisecondsToWait < 0) millisecondsToWait = 0;
}
if (timer.getRate() < 0) {
millisecondsToWait = ( tags[currentTagIndex].milliseconds - timer.getTime() )
/ timer.getRate() - REDUNDANCY;
if (millisecondsToWait < 0) millisecondsToWait = 0;
}
if (WaitForSingleObject(hStdin, millisecondsToWait) == WAIT_OBJECT_0) {
ReadConsoleInput(hStdin, &inputRecord, 1, &numbleRead);
if (inputRecord.EventType == KEY_EVENT) {
if (inputRecord.Event.KeyEvent.bKeyDown == TRUE) {
if (inputRecord.Event.KeyEvent.wVirtualKeyCode == VK_ESCAPE) {
SetConsoleCursorPosition(hStdout, tags[count-2].position);
break;
}
if (timer.getRate() == 1 && inputRecord.Event.KeyEvent.wVirtualKeyCode == 'A')
timer.setRate( -FAST_RUNNING_RATE );
if (timer.getRate() == 1 && inputRecord.Event.KeyEvent.wVirtualKeyCode == 'D')
timer.setRate( +FAST_RUNNING_RATE );
} else {
if (timer.getRate() < 0 && inputRecord.Event.KeyEvent.wVirtualKeyCode == 'A')
timer.setRate( 1 );
if (timer.getRate() > 0 && inputRecord.Event.KeyEvent.wVirtualKeyCode == 'D')
timer.setRate( 1 );
}
} else if (inputRecord.EventType == FOCUS_EVENT) {
if (timer.getRate() != 1 && inputRecord.Event.FocusEvent.bSetFocus == FALSE)
timer.setRate( 1 );
}
}
while (currentTagIndex+1 < count && tags[currentTagIndex+1].milliseconds <= timer.getTime()) {
FillConsoleOutputAttribute(hStdout, FOREGROUND_NORMAL, tags[currentTagIndex].length,
tags[currentTagIndex].position, &numbleWritten);
++currentTagIndex;
FillConsoleOutputAttribute(hStdout, FOREGROUND_HIGHLIGHT, tags[currentTagIndex].length,
tags[currentTagIndex].position, &numbleWritten);
SetConsoleCursorPosition(hStdout, tags[currentTagIndex].position);
}
while (currentTagIndex > 0 && tags[currentTagIndex].milliseconds > timer.getTime()) {
FillConsoleOutputAttribute(hStdout, FOREGROUND_NORMAL, tags[currentTagIndex].length,
tags[currentTagIndex].position, &numbleWritten);
--currentTagIndex;
FillConsoleOutputAttribute(hStdout, FOREGROUND_HIGHLIGHT, tags[currentTagIndex].length,
tags[currentTagIndex].position, &numbleWritten);
SetConsoleCursorPosition(hStdout, tags[currentTagIndex].position);
}
if (currentTagIndex == count - 1) {
currentTagIndex = 0;
timer.setTime( 0 );
}
}
return 0;
}
|
/*
* ???????????? ?????????????? ???????? ?????????? ? ?? ??????????????? ???????
*/
#pragma once
class CProgram;
class CMainClassDeclaration;
class CClassDeclaration;
class CClassDeclarationList;
class CClassExtendsDeclaration;
class CVariableDeclaration;
class CVariableDeclarationList;
class CMethodDeclaration;
class CMethodDeclarationList;
class CFormalList;
class CFormalRestList;
class CBuiltInType;
class CUserType;
class CStatementList;
class CStatementBlock;
class CIfStatement;
class CWhileStatement;
class CPrintStatement;
class CAssignmentStatement;
class CArrayElementAssignmentStatement;
class CBinaryOperatorExpression;
class CIndexAccessExpression;
class CLengthExpression;
class CMethodCallExpression;
class CIntegerOrBooleanExpression;
class CIdentifierExpression;
class CThisExpression;
class CNewIntegerArrayExpression;
class CNewObjectExpression;
class CNegationExpression;
class CParenthesesExpression;
class CExpressionList;
|
#include <iostream>
#include <string>
using namespace std;
void test() {
int R;
string str;
cin >> R >> str;
int size = str.size();
for(int i=0; i<size; i++)
for(int j=0; j<R; j++)
cout << str[i];
cout << '\n';
}
int main() {
int T;
cin >> T;
while(T--) {
test();
}
return 0;
}
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvl;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<pair<int, int>> vpi;
typedef vector<pair<ll, ll>> vpll;
typedef pair<int, int> pi;
typedef pair<ll, ll> pll;
typedef tuple<ll, ll, ll> ti;
using namespace __gnu_pbds;
template <class T>
using ordered_set = __gnu_pbds::tree<T, null_type, less<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>;
#define FOR(i, a, b) for (ll i = (a), _b = (b); i < _b; i++)
#define FORD(i, b, a) for (ll i = (b), _a = (a); i > _a; i--)
#define pb push_back
#define vout(v) \
do { \
for (auto i : v) \
cout << i << ' '; \
cout << '\n'; \
} while (false)
#define matout(mat) \
do { \
for (auto i : mat) { \
for (auto j : i) \
cout << j << ' '; \
cout << '\n'; \
} \
} while (false)
#define vin(v) \
for (auto &i : v) \
cin >> i
#define matin(mat) \
do { \
for (auto &i : mat) \
vin(i); \
} while (false)
ld PI = 3.141592653589793238;
ll M = 1e9 + 7;
ll gcd(ll a, ll b) {
if (a > b)
return gcd(b, a);
if (a == 0)
return b;
return gcd(b % a, a);
}
ll power(ll x, ll y) {
if (y == 0)
return 1;
ll p = power(x, y / 2) % M;
p = (p * p) % M;
return y % 2 ? (x * p) % M : p;
}
bool is_prime(ll n) {
if (n == 2)
return true;
if (n < 2)
return false;
if (n % 2 == 0)
return false;
for (int i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
bool is_palindrome(string s) {
return equal(s.rbegin(), s.rend(), s.begin());
}
void insert(set<pll>& low, set<pll>& high, pll p, ll k) {
if (*(low.rbegin()) > p) {
low.insert(p);
if (low.size() > (k + 1) / 2) {
high.insert(*(low.rbegin()));
low.erase(*(low.rbegin()));
}
} else {
high.insert(p);
if (high.size() > k / 2) {
low.insert(*(high.begin()));
high.erase(*(high.begin()));
}
}
}
void remove(set<pll>& low, set<pll>& high, pll p, ll k) {
if (*(low.rbegin()) >= p) {
low.erase(p);
} else high.erase(p);
if (low.empty()) {
low.insert(*(high.begin()));
high.erase(*(high.begin()));
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t, n, m, k, q, x, y;
string s;
bool flag;
set<pll> low, high, st;
set<pll>::iterator it, it2;
cin >> n >> k;
vll v(n);
vin(v);
low.insert({v[0], 0});
FOR (i, 1, k) insert(low, high, {v[i], i}, k);
ll j = k, i = 0;
bool odd = k % 2;
while (j <= n) {
cout << low.rbegin()->first << ' ';
remove(low, high, {v[i], i}, k);
if (j < n) insert(low, high, {v[j], j}, k);
i++;
j++;
}
cout << '\n';
return 0;
}
|
// test_config.cpp
#include <memory>
#include <vector>
#include "catch/catch.hpp"
#include "BlobCrystallinOligomer/config.h"
#include "BlobCrystallinOligomer/ifile.h"
#include "BlobCrystallinOligomer/monomer.h"
#include "BlobCrystallinOligomer/particle.h"
#include "BlobCrystallinOligomer/random_gens.h"
#include "BlobCrystallinOligomer/shared_types.h"
SCENARIO("Basic tests of configuration property calculation and access") {
using config::Config;
using ifile::ParticleData;
using ifile::MonomerData;
using monomer::Monomer;
using particle::Particle;
using random_gens::RandomGens;
using shared_types::vecT;
using shared_types::CoorSet;
using shared_types::distT;
using std::vector;
using std::unique_ptr;
GIVEN("System with two monomers of two simple particles in a box with PBC") {
RandomGens random_num {};
distT box_len {10};
distT radius {1};
vector<MonomerData> mds;
for (int i {0}; i != 2; i++) {
vector<ParticleData> pds;
for (int j {0}; j != 2; j++) {
vecT pos {i*2 + j, 0, 0};
vecT ore {0, 0, 0};
ParticleData pd {j, "", "SimpleParticle", 0, pos, ore, ore};
pds.push_back(pd);
}
MonomerData md {i, pds};
mds.push_back(md);
}
Config conf {mds, random_num, box_len, radius};
// Quick reference
Monomer& m1 {conf.get_monomer(0)};
Monomer& m2 {conf.get_monomer(1)};
// Get particles to test distance calculations on
Particle& p1 {m1.get_particles()[0].get()};
Particle& p2 {m2.get_particles()[1].get()};
WHEN("Monomers are adjacent in middle of box") {
THEN("Calculated distance is between those copies of the particles") {
distT e_dist {3};
distT c_dist {conf.calc_dist(p1, CoorSet::current, p2, CoorSet::current)};
REQUIRE(e_dist == c_dist);
}
}
WHEN("Monomers are moved to opposite sides of box") {
m1.translate({-4, 0, 0});
m1.trial_to_current();
m2.translate({1, 0, 0});
m2.trial_to_current();
THEN("Calculated distance follows the minimum image convention") {
distT e_dist {2};
distT c_dist {conf.calc_dist(p1, CoorSet::current, p2, CoorSet::current)};
REQUIRE(e_dist == c_dist);
}
}
}
}
|
#include "Model.h"
Model::Model(){
type = 0;
}
Model::Model(const Model &original){
type = original.type;
}
Model& Model::operator=(const Model& original){
if (this != &original){
type = original.type;
}
return *this;
}
Model *Model::clone(){
return new Model(*this);
}
Model::~Model(){
}
void Model::run(Population *population, Profile *profile, mt19937 &generator){
cout << "Model::run - Not Implemented.\n";
}
|
#ifndef __RPC_RESOURCE_HEADER__
#define __RPC_RESOURCE_HEADER__
#include <string>
#include <map>
#ifndef __RPC_RESOURCE_MANAGER_MODULE__
#error "DO NOT include this file. This head file can be included by rpc_resource_manager module only."
#endif//__RPC_RESOURCE_MANAGER_MODULE__
using namespace std;
/*--------------------------------------------------*/
/* RPC ¶à¿òÈÕÖ¾´¦ÀíÀàÐÍ */
typedef void (*rpc_trans_log)( const unsigned char* user_name,
const unsigned char* user_ip,
const unsigned char* usermode,
const unsigned int chassic_number,
const unsigned char* input,
size_t inputlen,
const unsigned char* output,
size_t outputlen,
unsigned int func_id);
/*--------------------------------------------------*/
/* ¶à¿òÈÕÖ¾Êý×éÀàÐͶ¨Ò壬Êý×éÊǶ¨ÒåÔÚ¶à¿òÄ£¿éÖУ¬ÕâÀïÖ»ÊÇÍⲿÒýÓà */
typedef struct rpc_tran_log_fun
{
unsigned int funIndex;//¹¦ÄÜË÷Òý
rpc_trans_log funcall;//º¯ÊýÖ¸Õë
char * descript;
} RPC_TRAN_LOG_FUN;
/*--------------------------------------------------*/
/* Íⲿ±äÁ¿ÉùÃ÷ */
extern const RPC_TRAN_LOG_FUN rpc_tran_log_list[];
extern "C" const RPC_CALLFUN_ST rpc_smm_fun_internal[];
extern "C" const RPC_DOMAIN_AUTHORITY_FUN rpc_domain_autority_fun[];
extern "C" const RPC_FUN_AUTHDEFINE_ST rpc_fun_authdefine_internal[];
/*--------------------------------------------------*/
/* rpc º¯ÊýÖ¸ÕëÉùÃ÷ */
typedef VOS_UINT32 ( *rpc_call_smm)(VOS_UCHAR*username, VOS_UCHAR *userIP,VOS_UCHAR *usermode,
VOS_UINT32 chassisnumber,
VOS_UCHAR *input, SIZE_T inputlen, VOS_UCHAR *output,SIZE_T outputlen);
/*--------------------------------------------------*/
// ÄÚ²¿¹éÒ»µÄRPC×ÊÔ´À࣬±¾º¯ÊýÊÇ´¿Ð麯Êý£¬
// ÐèÒªÌí¼ÓеÄRPC½Ó¿Ú±ØÐë´Ó´ËÀàÅÉÉú
// È»ºó½«ÅÉÉúÀàÌí¼Ó
/*--------------------------------------------------*/
class RPC_RESORCE_ITEM
{
protected:
VOS_UINT32 mRpcFunIndex;//¹¦ÄÜË÷Òý
rpc_call_smm mRpcFuncall;//º¯ÊýÖ¸Õë
string mFundes; //¹¦Äܺ¯ÊýÃèÊö
U8 mPrivilege;
VOS_UINT32 mNeedOplog;
public:
/* ¹¹Ô캯Êý */
RPC_RESORCE_ITEM( void );
virtual ~RPC_RESORCE_ITEM( void );
public:
/* »ñÈ¡RPCº¯ÊýÖ¸Õë */
virtual rpc_call_smm GetRpcFuncall( void ) = 0;
/* ±¾RPCÊÇ·ñÐèÒª¼Ç¼ÈÕÖ¾£¬ÐèÒª¼Ç¼·µ»Ø1£¬·ñÔò·µ»Ø0£¬
ÔÚ¶à¿î´¦ÀíÈÕÖ¾ÖлáµôÓñ¾º¯ÊýÅжÏÊÇ·ñÐèÒª¼Ç¼ÈÕÖ¾ */
virtual VOS_UINT32 GetRpcNeedTransLog( void ){return mNeedOplog;};
/* »ñÈ¡RPCµÄ¹¦ÄÜÃèÊö */
const string& GetRpcFunDescription( void );
/* ¿Ë¡º¯Êý£¬·µ»Ø±¾Ê¾ÀýµÄ¿½±´ */
virtual RPC_RESORCE_ITEM* Clone(void)=0;
/* ¶à¿ò²Ù×÷ÈÕÖ¾¼Ç¼º¯Êý£¬Èç¹ûGetRpcNeedTransLog ·µ»Ø0£¬±¾º¯Êý¾Í²»»á±»µ÷Óà */
virtual void RpcTransLog( const unsigned char* user_name, const unsigned char* user_ip,
const unsigned char* usermode, const unsigned int chassic_number,
const unsigned char* input, size_t inputlen, const unsigned char* output,
size_t outputlen, unsigned int func_id ){return;};
/*¶à¿òͳһ¼øÈ¨º¯Êý*/
virtual VOS_UINT32 RpcresUserDomainAuthority( const VOS_UCHAR* user_name, const VOS_UCHAR* user_ip,
const VOS_UCHAR* usermode, const VOS_UCHAR chassic_number,
const VOS_UCHAR* input, SIZE_T inputlen,
const VOS_UCHAR* output, SIZE_T outputlen,
VOS_UINT32 func_id ) = 0;
/*»ñÈ¡±¾RPCµÄÓû§È¨ÏÞ*/
virtual U8 GetPrivilege(void){ return mPrivilege; };
/*»ñÈ¡±¾RPCµÄË÷ÒýID*/
virtual VOS_UINT32 GetRpcIdx(void){return mRpcFunIndex;};
};
class RpcResource
{
protected:
typedef map<unsigned int, RPC_RESORCE_ITEM*>::iterator IterRpcResTab;
public:
static VOS_INT32 LinkItem( RPC_RESORCE_ITEM* item );
static VOS_INT32 AddItem( RPC_RESORCE_ITEM& item );
static RPC_RESORCE_ITEM* FindItem( unsigned int rpc_index );
protected:
RpcResource();
static map<unsigned int, RPC_RESORCE_ITEM*> smRpcResTab;
};
#endif//__RPC_RESOURCE_HEADER__
|
#ifndef FLAC_STREAM_ENCODER_H_
#define FLAC_STREAM_ENCODER_H_
#include <alloca.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h> /* Iftah: for mkfifo */
#include <jni.h>
#include <android/log.h>
#include "FLAC/metadata.h"
#include "FLAC/stream_encoder.h"
#include "jni/jni_utils.h"
#include "jni/FLACStreamEncoder.h"
namespace {
class FLACStreamEncoder {
public:
jobject m_obj; // pointer to the java object
// Write FIFO
struct write_fifo_t {
write_fifo_t(FLAC__int32 * buf, int fillsize) :
m_next(NULL), m_buffer(buf) // Taking ownership here.
, m_buffer_fill_size(fillsize) {
}
~write_fifo_t() {
// We have ownership!
delete[] m_buffer;
delete m_next;
}
write_fifo_t * last() volatile {
volatile write_fifo_t * last = this;
while (last->m_next) {
last = last->m_next;
}
return (write_fifo_t *) last;
}
write_fifo_t * m_next;
FLAC__int32 * m_buffer;
int m_buffer_fill_size;
};
// Thread trampoline arguments
struct trampoline {
typedef void * (FLACStreamEncoder::*func_t)(void * args);
FLACStreamEncoder * m_encoder;
func_t m_func;
void * m_args;
trampoline(FLACStreamEncoder * encoder, func_t func, void * args) :
m_encoder(encoder), m_func(func), m_args(args) {
}
};
/**
* Takes ownership of the outfile.
* Iftah: pass NULL outfile in order to use the write_callback instead
**/
FLACStreamEncoder(char * outfile, int sample_rate, int channels,
int bits_per_sample, bool verify, int frame_size, jobject obj);
/**
* There are no exceptions here, so we need to "construct" outside the ctor.
* Returns NULL on success, else an error message
**/
char const * const init();
/**
* Destroys encoder instance, releases outfile
**/
~FLACStreamEncoder();
/**
* Flushes internal buffers to disk.
**/
void flush();
/**
* Writes bufsize elements from buffer to the stream. Returns the number of
* bytes actually written.
**/
int write(char * buffer, int bufsize);
/**
* Writer thread function.
**/
void * writer_thread(void * args);
float getMaxAmplitude();
float getAverageAmplitude();
private:
/**
* Append current write buffer to FIFO, and clear it.
**/
inline void flush_to_fifo() {
if (!m_write_buffer) {
return;
}
//__android_log_print(ANDROID_LOG_DEBUG, LTAG, "Flushing to FIFO.");
write_fifo_t * next = new write_fifo_t(m_write_buffer,
m_write_buffer_offset);
m_write_buffer = NULL;
pthread_mutex_lock(&m_fifo_mutex);
if (m_fifo) {
write_fifo_t * last = m_fifo->last();
last->m_next = next;
} else {
m_fifo = next;
}
//__android_log_print(ANDROID_LOG_DEBUG, LTAG, "FIFO: %p, new entry: %p", m_fifo, next);
pthread_mutex_unlock(&m_fifo_mutex);
}
/**
* Wrapper around templatized copyBuffer that writes to the current write
* buffer at the current offset.
**/
inline int copyBuffer(char * buffer, int bufsize, int bufsize32) {
FLAC__int32 * buf = m_write_buffer + m_write_buffer_offset;
//__android_log_print(ANDROID_LOG_VERBOSE, LTAG, "Adding %d to JNI buffer", bufsize32);
//__android_log_print(ANDROID_LOG_DEBUG, LTAG, "Writing at %p[%d] = %p", m_write_buffer, m_write_buffer_offset, buf);
if (8 == m_bits_per_sample) {
copyBuffer<int8_t>(buf, buffer, bufsize);
m_write_buffer_offset += bufsize32;
} else if (16 == m_bits_per_sample) {
copyBuffer<int16_t>(buf, buffer, bufsize);
m_write_buffer_offset += bufsize32;
} else {
// XXX should never happen, just exit.
return 0;
}
return bufsize;
}
/**
* Copies inbuf to outpuf, assuming that inbuf is really a buffer of
* sized_sampleT.
* As a side effect, m_max_amplitude, m_average_sum and m_average_count are
* modified.
**/
template<typename sized_sampleT>
void copyBuffer(FLAC__int32 * outbuf, char * inbuf, int inbufsize) {
sized_sampleT * inbuf_sized = reinterpret_cast<sized_sampleT *>(inbuf);
for (int i = 0; i < inbufsize / sizeof(sized_sampleT); ++i) {
sized_sampleT cur = inbuf_sized[i];
// Convert sized sample to int32
outbuf[i] = cur;
// Convert to float on a range from 0..1
if (cur < 0) {
// Need to lose precision here, the positive value range is lower than
// the negative value range in a signed integer.
cur = -(cur + 1);
}
float amp = static_cast<float>(cur)
/ type_traits<sized_sampleT>::MAX;
// Store max amplitude
if (amp > m_max_amplitude) {
m_max_amplitude = amp;
}
// Sum average.
if (!(i % m_channels)) {
m_average_sum += amp;
++m_average_count;
}
}
}
static void * trampoline_func(void * args);
// Configuration values passed to ctor
char * m_outfile;
int m_sample_rate;
int m_channels;
int m_bits_per_sample;
// FLAC encoder instance
FLAC__StreamEncoder * m_encoder;
// Max amplitude measured
float m_max_amplitude;
float m_average_sum;
int m_average_count;
// JNI thread's buffer.
FLAC__int32 * m_write_buffer;
int m_write_buffer_size;
int m_write_buffer_offset;
bool m_verify;
int m_frame_size;
// Write FIFO
volatile write_fifo_t * m_fifo;
pthread_mutex_t m_fifo_mutex;
// Writer thread
pthread_t m_writer;
pthread_cond_t m_writer_condition;
volatile bool m_kill_writer;
};
} // namespace
#endif
|
//
// OutputRead.cpp
// fast_convolution
//
// Created by Ying Zhan on 2/1/16.
// Copyright (c) 2016 Ying Zhan. All rights reserved.
//
#include "OutputRead.h"
circularBuffer<float>* OutputRead::getOutputBuffer() {
return output_buffer;
}
void OutputRead::printOutputResult() {
std::cout << "OUTPUT RESULT" << std::endl;
output_buffer->print();
std::cout << "////////////" << std::endl;
}
float OutputRead::writeResultToChannel() {
float sample;
sample = output_buffer->readFunction(0);
output_buffer->moveReadPtr();
return sample;
}
int OutputRead::getOutputRptr() {
return output_rptr;
}
void OutputRead::updateOutputWptr() {
output_wptr = output_wptr + 1;
}
void OutputRead::updateOutputRptr(int total_irs) {
//std::cout << "before_output_rtpr: " << output_rptr<<std::endl;
output_rptr = output_rptr + 1;
output_rptr = output_rptr % total_irs;
//std::cout << "OUTPUT_PTR: " << output_rptr << std::endl;
}
|
//
// BUnitGetter.cpp for MyTexture in /home/paumar_a/projet/git/AW_like/Graph/Texture
//
// Made by cedric paumard
// Login <paumar_a@epitech.net>
//
// Started on Sun Jul 27 12:32:59 2014 cedric paumard
// Last update Tue Jul 29 17:26:40 2014 cedric paumard
//
#include "MyTexture.hh"
const sf::Texture &MyTexture::getBUnitTank(void)const
{
return (this->_unit_tank_b);
}
const sf::Texture &MyTexture::getBUnitBers(void)const
{
return (this->_unit_bers_b);
}
const sf::Texture &MyTexture::getBUnitHeli(void)const
{
return (this->_unit_heli_b);
}
const sf::Texture &MyTexture::getBUnitMiss(void)const
{
return (this->_unit_miss_b);
}
const sf::Texture &MyTexture::getBUnitBaso(void)const
{
return (this->_unit_bazo_b);
}
const sf::Texture &MyTexture::getBUnitJeep(void)const
{
return (this->_unit_jeep_b);
}
|
// Created on: 1993-08-06
// Created by: Martine LANGLOIS
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepToTopoDS_PointPair_HeaderFile
#define _StepToTopoDS_PointPair_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
class StepGeom_CartesianPoint;
//! Stores a pair of Points from step
class StepToTopoDS_PointPair
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT StepToTopoDS_PointPair(const Handle(StepGeom_CartesianPoint)& P1, const Handle(StepGeom_CartesianPoint)& P2);
friend class StepToTopoDS_PointPairHasher;
protected:
private:
Handle(StepGeom_CartesianPoint) myP1;
Handle(StepGeom_CartesianPoint) myP2;
};
#endif // _StepToTopoDS_PointPair_HeaderFile
|
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#define LIMIT 10000000
#define REPEAT 10000
typedef int number;
number a[LIMIT], b[LIMIT], c[LIMIT], * s = a, * p = b;
char x;
int n, offset;
ifstream fin("input.txt");
void output() {
for (size_t i = offset; i < offset + 8; i++)
{
number test = a[i];
cout << test;
}
cout << endl;
}
//inb4 browsing Reddit and realizing this could have been solved using partial sums. HOW I DID NOT THINK OF IT! This day is far from optimal
void part1() {
offset = 0;
for (size_t phase = 0; phase < 100; phase++)
{
for (size_t i = offset; i < n; i++)
{
bool state = 1;
p[i] = 0;
for (size_t j = i; j < n; j += (i + 1) * 2)
{
for (size_t k = 0; k <= i && j + k < n; k++)
{
if (state) {
p[i] += s[j + k];
}
else
{
p[i] -= s[j + k];
}
}
state = !state;
}
p[i] = abs(p[i]) % 10;
}
swap(s, p);
}
output();
}
void part2() {
for (size_t i = n; i < n * REPEAT; i++)
{
s[i] = s[i - n];
}
n *= REPEAT;
offset = 0;
for (size_t i = 0; i < 7; i++)
{
offset = offset * 10 + s[i];
}
for (size_t phase = 0; phase < 100; phase++)
{
//quite upset of the way I had to solve this day. I had to rely on the fact that the first digits point at least at half the input.
if (offset >= n / 2)
{
int sum = 0;
for (size_t i = n - 1; i >= offset; i--)
{
sum += s[i];
p[i] = sum;
}
for (size_t i = offset; i < n; i++)
{
p[i] = abs(p[i]) % 10;
}
}
//here's the code that should work universally, estimate of 10 hours to solve actual inputs
else
{
for (size_t i = offset; i < n; i++)
{
bool state = 1;
p[i] = 0;
for (size_t j = i; j < n; j += (i + 1) * 2)
{
for (size_t k = 0; k <= i && j + k < n; k++)
{
if (state) {
p[i] += s[j + k];
}
else
{
p[i] -= s[j + k];
}
}
state = !state;
}
p[i] = abs(p[i]) % 10;
}
}
swap(s, p);
}
output();
}
int main() {
fin >> x;
do {
s[n] = x - '0';
n++;
} while (fin >> x);
memcpy(c, a, LIMIT);
part1();
memcpy(a, c, LIMIT);
part2();
}
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SKLAND_GRAPHIC_INTERNAL_FONT_META_HPP_
#define SKLAND_GRAPHIC_INTERNAL_FONT_META_HPP_
#include "SkFont.h"
namespace skland {
/**
* @ingroup graphic_intern
* @brief Structure to encapsulate a sk_sp<SkFont> object
*/
struct FontMeta {
FontMeta() {}
FontMeta(const sk_sp<SkFont> &font)
: sk_font(font) {}
FontMeta(const FontMeta &other)
: sk_font(other.sk_font) {}
FontMeta &operator=(const FontMeta &other) {
sk_font = other.sk_font;
return *this;
}
FontMeta &operator=(const sk_sp<SkFont> &font) {
sk_font = font;
return *this;
}
sk_sp<SkFont> sk_font;
};
}
#endif // SKLAND_GRAPHIC_INTERNAL_FONT_META_HPP_
|
#include "motor.hpp"
#include <Arduino.h>
/**
* @brief Construct a new Motor:: Motor object
*
* @param _pin1 direction pin, or HIGH->fwd pin
* @param _pin2 pwm pin, or LOW->fwd pin
* @param _isDirType Driver is direction/pwm type
* @param _isInverted invert the polarity
*/
Motor::Motor(int _pin1, int _pin2, bool _isDirType=true, bool _isInverted=false):
pin1(_pin1), pin2(_pin2), isDirType(_isDirType), isInverted(_isInverted){
// set the pin modes to outputs
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
}
/**
* @brief
*
* @param _speed -255 <= _speed <= 255
*/
void Motor::write(int _speed){
// write speed and direction to pins
_speed = constrain(_speed, -255, 255);
if((_speed > 0 && !isInverted) || (_speed<0 && isInverted)){
if(isDirType){
digitalWrite(pin1, HIGH);
analogWrite(pin2, abs(_speed));
}
else{
analogWrite(pin1, abs(_speed));
analogWrite(pin2, 0);
}
}
else{
if(isDirType){
digitalWrite(pin1, LOW);
analogWrite(pin2, abs(_speed));
}
else{
analogWrite(pin1, 0);
analogWrite(pin2, abs(_speed));
}
}
}
void Motor::invert(){
isInverted = !isInverted;
}
|
#ifndef __LOADER_H__
#define __LOADER_H__
#include <iostream>
#include <fstream>
#include <cstring>
#include "BaseNode.h"
using namespace std;
#define LINE_SIZE 1024
#define TOKEN_LENGTH 8
enum TokenID { T_NONE=-1, T_VERT, T_FACE};
struct TokenPair
{
char strval[TOKEN_LENGTH];
TokenID tokID;
bool operator==(const TokenPair & rhs) const
{
return strcmp(strval,rhs.strval) == 0 && tokID == rhs.tokID;
}
bool operator!=(const TokenPair & rhs) const
{
return !(*this==rhs);
}
};
class TrimeshLoader
{
public:
static TokenPair EMPTY_PAIR;
static TokenPair tokenMap[];
static char TOK_SEPS[];
TokenPair * tokenMatch(char * srchtok)
{
if(!srchtok) return 0;
TokenPair * ptokp = &tokenMap[0];
for(; *ptokp != EMPTY_PAIR && strcmp(ptokp->strval,srchtok) != 0; ptokp++);
if(*ptokp==EMPTY_PAIR) ptokp=0;
return ptokp;
}
void loadOBJ(GeometryNode * pmesh)
{
ifstream ifs;
char line[LINE_SIZE];
char * tok;
ifs.open(pmesh->path);
if(!ifs.fail()){
while(!ifs.eof())
{
ifs.getline(line,LINE_SIZE);
tok=strtok(line,TOK_SEPS);
TokenPair * ptokp=tokenMatch(tok);
if(ptokp)
{
switch(ptokp->tokID)
{
case T_VERT : processVertex(tok,pmesh); break;
case T_FACE : processFace(tok,pmesh); break;
default: processSkip(tok); break;
}
}
}
ifs.close();
}
}
int readFloats(char * tok, float * buf, int bufsz)
{
int i=0;
while((tok=strtok(0, TOK_SEPS)) != 0 && i<bufsz)
buf[i++]=atof(tok);
return i;
}
int readInts(char * tok, int * buf, int bufsz)
{
int i=0;
while((tok=strtok(0, TOK_SEPS)) != 0 && i<bufsz)
buf[i++]=atoi(tok);
return i;
}
void processSkip(char * tok)
{}
void processVertex(char * tok, GeometryNode * pmsh)
{
float values[3];
int cnt=readFloats(tok,values,3);
if(cnt>=3) pmsh->addVertex(values);
}
bool processFace(char * tok, GeometryNode * pmsh)
{
int ids[256];
int cnt=readInts(tok,ids,256);
if(cnt>=3)
{
int tri[3]={ids[0]-1,ids[1]-1,ids[2]-1};
pmsh->addFace(tri);
for(int i=3;i<cnt;i++)
{
tri[1]=tri[2];
tri[2]=ids[i]-1;
pmsh->addFace(tri);
}
}
return true;
}
};
TokenPair TrimeshLoader::EMPTY_PAIR={"",T_NONE};
TokenPair TrimeshLoader::tokenMap[] = {
{"v", T_VERT}, {"f",T_FACE},
EMPTY_PAIR
};
char TrimeshLoader::TOK_SEPS[] = " \t";
#endif
|
#pragma once
#include <vector>
#include <glm/glm.hpp>
#include "PointCloud.hpp"
#include <nanoflann.hpp>
#include "../implicits/Implicit.hpp"
#include "../implicits/GeneralQuadratic.hpp"
#include "../implicits/BivariateQuadratic.hpp"
#include "../implicits/UtilityFunctions.hpp"
#include <limits>
using namespace std;
using namespace glm;
using namespace nanoflann;
// Forward declaration for usage in Implicit cell
template <class T>
class ImplicitOctree;
//////////////////////////////////////////////////////
///////////// DECLARATION ImplicitCell /////////////
//////////////////////////////////////////////////////
template <class T>
class ImplicitCell {
private:
// Reference to the tree
ImplicitOctree<T> *treeRef;
// List of cell children
vector<ImplicitCell<T> > children;
// True if the cell is a leaf
bool isLeaf;
// Position (min cube vector) of the octree cell
tvec3<T> position;
// Length of the cell side
T size;
// Support radius
T radius;
// Depth of this cell
int depth;
// Implicit approximating points in this cell. (Only leafs should have this)
Implicit<T> *implicit = NULL;
public:
ImplicitCell() {};
ImplicitCell(ImplicitOctree<T> *tree, tvec3<T> position, T size, int depth);
~ImplicitCell() { if (implicit != NULL) delete implicit; };
inline tvec3<T> getCenter() { return this->position + (this->size / 2); }
// Subdivides the cell (creating 8 children)
void subdivide();
// Builds the tree and fits the implicits
void build();
// Calculates distance function for the given point
tvec2<T> globalFunctionValue(tvec3<T> position);
private:
inline T getSupportRadius() { return this->treeRef->params.alpha * 2 * sqrt(3) * this->size; }
};
//////////////////////////////////////////////////////
///////////// DEFINITIONS ImplicitCell /////////////
//////////////////////////////////////////////////////
template <class T>
ImplicitCell<T>::ImplicitCell(ImplicitOctree<T> *tree, tvec3<T> position, T size, int depth) {
this->treeRef = tree;
this->position = position;
this->size = size;
this->depth = depth;
this->isLeaf = true;
this->radius = tree->params.alpha * size * sqrt(3);
}
template <class T>
void ImplicitCell<T>::build() {
// Reference t o pointCloud points
vector<Point<T> > pcPoints = this->treeRef->pointCloud.points;
tvec3<T> cellCenter = this->getCenter();
T query_pt[3] = { cellCenter.x, cellCenter.y, cellCenter.z };
// List of support points
size_t minPoints = this->treeRef->params.minPoints;
vector<Point<T> > supportPoints;
T origRadius = this->radius;
// Fetch the points from support radius using kdtree
// Will hold pair for each point where the first element is point index and second is the distance from that point
vector<pair<size_t, T> > ret_matches;
size_t nMatches = this->treeRef->pcKdtree.radiusSearch(&query_pt[0], this->radius, ret_matches, SearchParams());
// Check if enough support points were found
if (nMatches < minPoints) {
// To few points were inside the support radius. Select minPoints nearest neighbours and set the radius accordingly
vector<size_t> indices(minPoints);
vector<T> distances(minPoints);
this->treeRef->pcKdtree.knnSearch(&query_pt[0], minPoints, &indices[0], &distances[0]);
// Set the radius to maximum distance
this->radius = sqrt(distances[minPoints - 1]);
// Add points to support vector points
for (auto idxIt = indices.begin(); idxIt != indices.end(); idxIt++) {
supportPoints.push_back(pcPoints[*idxIt]);
}
}
else {
for (auto matchIt = ret_matches.begin(); matchIt != ret_matches.end(); matchIt++) {
supportPoints.push_back(pcPoints[matchIt->first]);
}
}
// Calculate average tangent plane
pair<tvec3<T>, tvec3<T> > tangentPlane = MPUIUtility::findAveragedTangentPlane(supportPoints, cellCenter, this->radius);
// Check if the points should be approximated with either general quaratic or bivariate quadratic function
bool isGeneral = false;
for (auto itP = supportPoints.begin(); itP != supportPoints.end(); itP++) {
if (dot(tangentPlane.second, itP->normal) < 0) {
isGeneral = true;
break;
}
}
bool fittingSuccessful;
if (isGeneral) {
GeneralQuadratic<T> *gq = new GeneralQuadratic<T>();
fittingSuccessful = gq->fitOnPoints(supportPoints, cellCenter, this->size, this->radius, tangentPlane.first);
this->implicit = gq;
}
else {
BivariateQuadratic<T> *bq = new BivariateQuadratic<T>();
fittingSuccessful = bq->fitOnPoints(supportPoints, cellCenter, this->radius, origRadius, tangentPlane.first, tangentPlane.second);
this->implicit = bq;
}
// Maximal allowed error and max depth
T maxError = this->treeRef->params.maxError;
int maxDepth = this->treeRef->params.maxDepth;
//cout << this->implicit->getApproximationError() << endl;
// If implicit fitting was unsuccessful or if the error is above the threshold subdivide this cell
if ((!fittingSuccessful || this->implicit->getApproximationError() > maxError) && this->depth < maxDepth) {
// Current approximation is not good enough.. subdivide
this->subdivide();
// Build sub cells
for (int i = 0; i < 8; i++) {
this->children[i].build();
}
}
else {
if (this->depth > this->treeRef->maxDepth) {
this->treeRef->maxDepth = this->depth;
}
if (!fittingSuccessful && this->depth >= maxDepth) {
cerr << "Maximal depth was reached and the fitting was unsuccessful!";
}
}
}
template <class T>
void ImplicitCell<T>::subdivide() {
T halfSize = this->size / 2;
this->children.push_back(ImplicitCell<T>(this->treeRef, tvec3<T>(position.x, position.y, position.z), halfSize, this->depth + 1));
this->children.push_back(ImplicitCell<T>(this->treeRef, tvec3<T>(position.x + halfSize, position.y, position.z), halfSize, this->depth + 1));
this->children.push_back(ImplicitCell<T>(this->treeRef, tvec3<T>(position.x, position.y + halfSize, position.z), halfSize, this->depth + 1));
this->children.push_back(ImplicitCell<T>(this->treeRef, tvec3<T>(position.x + halfSize, position.y + halfSize, position.z), halfSize, this->depth + 1));
this->children.push_back(ImplicitCell<T>(this->treeRef, tvec3<T>(position.x, position.y, position.z + halfSize), halfSize, this->depth + 1));
this->children.push_back(ImplicitCell<T>(this->treeRef, tvec3<T>(position.x + halfSize, position.y, position.z + halfSize), halfSize, this->depth + 1));
this->children.push_back(ImplicitCell<T>(this->treeRef, tvec3<T>(position.x, position.y + halfSize, position.z + halfSize), halfSize, this->depth + 1));
this->children.push_back(ImplicitCell<T>(this->treeRef, tvec3<T>(position.x + halfSize, position.y + halfSize, position.z + halfSize), halfSize, this->depth + 1));
this->isLeaf = false;
}
template <class T>
tvec2<T> ImplicitCell<T>::globalFunctionValue(tvec3<T> position) {
tvec3<T> cellCenter = this->getCenter();
tvec3<T> relPos = position - cellCenter;
// first (x) - distance functions sum, second (y) - weight sum
tvec2<T> result(0, 0);
// Check if the point is within the support radius
if (sqrt(dot(relPos, relPos) < this->getSupportRadius())) {
if (this->isLeaf) {
T w = MPUIUtility::weight(position, cellCenter, this->radius);
result.x += (*this->implicit).funValue(position) * w;
result.y += w;
}
else {
// Calculate function value for children and sum up the results
for (auto itC = children.begin(); itC != children.end(); itC++) {
result += itC->globalFunctionValue(position);
}
}
}
return result;
}
//////////////////////////////////////////////////////
//////////// DECLARATION ImplicitOctree ////////////
//////////////////////////////////////////////////////
template <class T>
class ImplicitOctree {
private:
typedef KDTreeSingleIndexAdaptor<L2_Simple_Adaptor<T, PointCloud<T> >, PointCloud<T>, 3> kdtree;
public:
struct Parameters {
T alpha; // radius = alpha * cellDiag
T lambda; // Radius iteration step
size_t minPoints;
int maxDepth;
T maxError;
Parameters(T alpha, T lambda, size_t minPoints, int maxDepth, T maxError) : alpha(alpha), lambda(lambda), minPoints(minPoints), maxDepth(maxDepth), maxError(maxError) {};
};
// Pointcloud containing the data
PointCloud<T> pointCloud;
// Kdtree
kdtree pcKdtree;
// Root cell of the tree
ImplicitCell<T> root;
// Parameters
Parameters params;
int maxDepth = 0;
public:
ImplicitOctree(PointCloud<T> &pointCloud, Parameters params = Parameters((T) 0.75, (T) 0.1, 15, 10, (T) 0.01));
~ImplicitOctree() {};
void build();
T globalFunctionValue(tvec3<T> position);
};
//////////////////////////////////////////////////////
//////////// DEFINITIONS ImplicitOctree ////////////
//////////////////////////////////////////////////////
template <class T>
ImplicitOctree<T>::ImplicitOctree(PointCloud<T> &pointCloud, Parameters params)
: pointCloud(pointCloud), params(params), pcKdtree(3, pointCloud) {
root = ImplicitCell<T>(this, pointCloud.aabb.getMin(), pointCloud.aabb.getLongestEdge(), 0);
}
template <class T>
void ImplicitOctree<T>::build() {
// Build the kdtree
this->pcKdtree.buildIndex();
// Start building sublevels
this->root.build();
}
template <class T>
T ImplicitOctree<T>::globalFunctionValue(tvec3<T> position) {
// first (x) - distance functions sum, second (y) - weight sum
tvec2<T> result = this->root.globalFunctionValue(position);
if (result.y != 0) {
return result.x / result.y;
}
else {
return -numeric_limits<T>::max();
}
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
int main() {
freopen("puzzle.in", "r", stdin);
freopen("puzzle.out", "w", stdout);
LL ans =0 ;
int n, x;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
for (int j =0 ; j < n; ++j) {
scanf("%d", &x);
if (x == 0) x = n * n;
--x;
ans += abs(i - (x/n)) + abs(j - (x%n));
}
}
cout << ans << endl;
return 0;
}
|
#include<iostream>
using namespace std;
int partition(int a[], int first, int last);
void quickSort(int a[], int first, int last);
int main(){
int n;
cout<<"Enter the no. of elements : ";
cin>>n;
int a[n]; // Initialization of array for n numbers.
cout<<"Enter elements : \n";
for(int i=0;i<n;i++){
cin>>a[i]; // Taking value of n elements of array from User.
}
cout<<"Elements before sorting : \n";
for(int i=0;i<n;i++){
cout<<a[i]<<" "; // Display of each element of array.
}cout<<"\n";
int first = 0, last = n-1;
quickSort(a,first,last);
cout<<"Elements before sorting : \n";
for(int i=0;i<n;i++){
cout<<a[i]<<" "; // Display of each element of array.
}cout<<"\n";
return 0;
}
void quickSort(int a[], int first, int last){
if(first < last){
int p = partition(a,first,last);
quickSort(a,first,p-1);
quickSort(a,p+1,last);
}
}
int partition(int a[], int first, int last){
int pivot;
pivot = a[first];
int i = first;
for(int j = first+1;j<=last;j++){
if(a[j] < pivot){
i++;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
int temp = a[i];
a[i] = pivot;
a[first] = temp;
return i;
}
|
#include "FloatCondition.h"
FloatCondition::FloatCondition(const float min_value, const float max_value)
{
m_minValue = min_value;
m_maxValue = max_value;
}
FloatCondition::~FloatCondition()
= default;
void FloatCondition::setTestValue(const float value)
{
m_testValue = value;
}
bool FloatCondition::Test()
{
return (m_minValue <= m_testValue) && (m_testValue <= m_maxValue);
}
|
#include "NeuralNetwork.hpp"
namespace nanoNet
{
NeuralNetwork::NeuralNetwork()
: m_layers()
{
}
void NeuralNetwork::addLayer(const NeuralNetworkLayer& layer)
{
if (layerCount() == 0 || outputCount() == layer.inputCount())
m_layers.push_back(layer);
}
NeuralNetworkLayer::vector_type NeuralNetwork::predict(
const NeuralNetworkLayer::vector_type& inputData) const
{
NeuralNetworkLayer::vector_type result(inputData);
for (auto& layer : m_layers)
result = layer.predict(result);
return result;
}
} /* nanoNet */
|
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void inorder(TreeNode *root,vector<int> &res)
{
if(root == nullptr)
return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
int main()
{
vector<int> res;
TreeNode *root = new TreeNode(4);
root->left = new TreeNode(2);
root->right = new TreeNode(6);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(3);
inorder(root, res);
for(int i = 0; i < res.size(); i++)
{
cout<<res[i]<<endl;
}
return 0;
}
|
#include<iostream>
//#include"adjoin_maxtrix.h" //普通邻接矩阵
#include"obj_adjoin_maxtrix.h" //面向对象邻接矩阵
#include"obj_adjoin_list.h" //面向对象邻接表
using namespace std;
void Visit(char temp) {
cout << setw(4) << temp << " ";
}
int main20171228()
{
char a[] = { 'A','B','C','D','E' }; //顶点
RowColWeight rcw[] = { { 0,1,10 },{ 0,4,20 },{ 1,2,40 },{ 1,3,30 },{ 3,2,50 } };
//普通邻接矩阵图
//MGraph G;
//CreatGraph(&G, a, 5, rcw, 5);
//printAdjoinMaxtrix(G);
////面向对象邻接矩阵
adjMaxtrix<char> aMaxtrix;
aMaxtrix.CreatGraph(a, 5, rcw, 5);
cout << "深度优先遍历顶点:";
aMaxtrix.DepthFirstSearch(Visit); //深度优先遍历顶点
cout << endl;
cout << "广度优先遍历顶点:";
aMaxtrix.BroadFirstSearch(Visit); //广度优先遍历顶点
cout << endl;
cout << "邻接矩阵:"<<endl;
aMaxtrix.print();
cout<<"Prim构建最小生成树的路径为:"<<endl;
cout<<"最小路径权值为:"<<aMaxtrix.prim(5);
//面向对象邻接表
// adjList<char> aList;
// aList.CreatGraph(a, 5, rcw, 5); //创建图
// //cout << "深度优先遍历顶点:";
// //aList.DepthFirstSearch(Visit); //深度优先遍历顶点
// //cout << endl;
// //cout << "广度优先遍历顶点:";
// //aList.BroadFirstSearch(Visit); //广度优先遍历顶点
// cout << endl;
// cout <<endl<< "邻接表:"<<endl;
// aList.print();
return 0;
}
|
#include <iostream>
#define CATCH_CONFIG_MAIN
#include "../../../../catch2/catch.hpp"
#include "../Task5. ParseURL//UrlParser.h"
SCENARIO("Пустая строка - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Пустая строка - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("", pr, port, host, document) == false);
}
SCENARIO("Только цифры - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Только цифры - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("32532523523", pr, port, host, document) == false);
}
SCENARIO("Только буквы - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Только буквы - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("gewghwrherhwth", pr, port, host, document) == false);
}
SCENARIO("Только символы - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Только символы - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("*&/!@", pr, port, host, document) == false);
}
SCENARIO("Если есть :, но порт не указан - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Если есть :, но порт не указан - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("http://www.mysite.com:/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == false);
}
SCENARIO("Если порт указан в виде символов, а не цифр - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Если порт указан в виде символов, а не цифр - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("http://www.mysite.com:gerg/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == false);
}
SCENARIO("Если порт меньше 1 - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Если порт меньше 1 - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("http://www.mysite.com:0/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == false);
}
SCENARIO("Если порт больше 65535 - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Если порт больше 65535 - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("http://www.mysite.com:655356/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == false);
}
SCENARIO("Если хост - пустой, то - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Если хост - пустой, то - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("http://:www.mysite.com/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == false);
}
SCENARIO("Если протокол отличен от http | https | ftp - невалидный url")
{
setlocale(LC_ALL, "ru");
cout << "Если протокол отличен от http | https | ftp - невалидный url" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("hrte://www.mysite.com:234/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == false);
}
SCENARIO("Если порт не указан и протокол = http, то порт - 80")
{
setlocale(LC_ALL, "ru");
cout << "Если порт не указан и протокол = http, то порт - 80" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("http://www.mysite.com/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == true);
REQUIRE(port == 80);
REQUIRE(host == "www.mysite.com");
REQUIRE(document == "docs/document1.html?page=30&lang=en#title");
}
SCENARIO("Если порт не указан и протокол = https, то порт - 443")
{
setlocale(LC_ALL, "ru");
cout << "Если порт не указан и протокол = https, то порт - 443" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("https://www.mysite.com/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == true);
REQUIRE(port == 443);
REQUIRE(host == "www.mysite.com");
REQUIRE(document == "docs/document1.html?page=30&lang=en#title");
}
SCENARIO("Если порт не указан и протокол = ftp, то порт - 21")
{
setlocale(LC_ALL, "ru");
cout << "Если порт не указан и протокол = ftp, то порт - 21" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("ftp://www.mysite.com/docs/document1.html?page=30&lang=en#title", pr, port, host, document) == true);
REQUIRE(port == 21);
REQUIRE(host == "www.mysite.com");
REQUIRE(document == "docs/document1.html?page=30&lang=en#title");
}
SCENARIO("Если не указан документ, то он будет пустой строкой")
{
setlocale(LC_ALL, "ru");
cout << "Если не указан документ, то он будет пустой строкой" << endl;
Protocol pr;
int port;
string host, document;
REQUIRE(ParseURL("ftp://www.mysite.com", pr, port, host, document) == true);
REQUIRE(port == 21);
REQUIRE(host == "www.mysite.com");
REQUIRE(document == "");
}
|
// DisasterWatchDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "DisasterWatch.h"
#include "DisasterWatchDlg.h"
#include "string-trans.h"
#include "UsefulFunction.h"
#include <atlbase.h>
extern volatile bool close_alert;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define WM_SHOWTASK (WM_USER + 1000)
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CDisasterWatchDlg 对话框
CDisasterWatchDlg::CDisasterWatchDlg(CWnd* pParent /*=NULL*/)
: CDialog(CDisasterWatchDlg::IDD, pParent)
, auto_alert(TRUE)
, auto_send_message(TRUE)
, interval(10)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
char numbers_buf[1024] ;
DWORD result = GetPrivateProfileString("stations","numbers",NULL,numbers_buf,1000,"./dwsetup.ini");
std::string stations_str = numbers_buf;
GetPrivateProfileString("alert","send_message_mobile_phone",NULL,numbers_buf,1000,"./dwsetup.ini");
std::string mobile_phone_str = numbers_buf;
str_split(stations_str, " ", all_stations);
str_split(mobile_phone_str, " ", all_mobile_phone);
}
void CDisasterWatchDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Check(pDX, IDC_CHECK_ALERT, auto_alert);
DDX_Check(pDX, IDC_CHECK_SEND_MESSAGE, auto_send_message);
DDX_Control(pDX, IDC_DISASTER_VIEW, disa_view);
}
BEGIN_MESSAGE_MAP(CDisasterWatchDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_CHECK_ALERT, &CDisasterWatchDlg::OnBnClickedCheckAlert)
ON_BN_CLICKED(IDC_CHECK_SEND_MESSAGE, &CDisasterWatchDlg::OnBnClickedCheckSendMessage)
ON_WM_TIMER()
ON_WM_SYSCOMMAND()
ON_MESSAGE(WM_SHOWTASK,OnShowTask)
END_MESSAGE_MAP()
// CDisasterWatchDlg 消息处理程序
BOOL CDisasterWatchDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
AutoRunAfterStart();
//显示信息
disa_view.SetWindowTextA("正在监视网页");
// TODO: 在此添加额外的初始化代码
SetTimer(1,5*1000,NULL);//程序运行后5秒后启动定时器
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CDisasterWatchDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else if ( (nID == SC_MINIMIZE) || (nID == SC_CLOSE))
{
HideToTray();
ShowWindow(SW_HIDE); //隐藏主窗口
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CDisasterWatchDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CDisasterWatchDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CDisasterWatchDlg::OnBnClickedCheckAlert()
{
// 更新数据
UpdateData(TRUE);
}
void CDisasterWatchDlg::OnBnClickedCheckSendMessage()
{
// 更新数据
UpdateData(TRUE);
}
void CDisasterWatchDlg::OnTimer(UINT_PTR nIDEvent)
{
//定时器1
if(nIDEvent == 1)
{
KillTimer(nIDEvent);
BeginAllProc();
interval = GetPrivateProfileInt("alert","interval",10,"./dwsetup.ini");
SetTimer(1,interval*1000*60,NULL);// 时间不能太短 否则函数SetLastReadTime()还没执行完毕
}
CDialog::OnTimer(nIDEvent);
}
//处理函数起始
void CDisasterWatchDlg::BeginAllProc()
{
//http://172.18.152.124/dzsp/index.php?action=DisasterInfo_listbak
bool is_download = DownloadHttpPage("172.18.152.124","/dzsp/index.php?action=DisasterInfo_listbak","DisasterInfo_listbak");
if(is_download) CheckNewDisaster();
CTime curtime = CTime::GetCurrentTime();
viewtext.Format("最新读取时间:%s\r\n %d 分钟后重新读取",curtime.Format("%Y-%m-%d %H:%M:%S"), interval);
disa_view.SetWindowTextA(viewtext);Sleep(1000);
}
//返回新灾情的ID
bool CDisasterWatchDlg::CheckNewDisaster()
{
disa_view.SetWindowText("读取最新灾情文件");UpdateData(FALSE);Sleep(2000);
//MessageBox("good");
char str_buf[100];
DWORD result = GetPrivateProfileString("alert","last_disaster_id","201004271712570730007002",str_buf,100,"./dwsetup.ini");
last_disaster_id = str_buf;
std::string listbak_content;
filetostr("DisasterInfo_listbak",listbak_content,600);
size_t last_pos=listbak_content.npos;
bool have_new_disaster=false;
while( (last_pos=listbak_content.rfind("DisasterInfo_viewbak",last_pos))
!= listbak_content.npos)
{
size_t id_pos = listbak_content.find("ID",last_pos);
std::string IDstr = listbak_content.substr(id_pos+3,24);
if(IDstr > last_disaster_id)
{
bool is_in_region = false;
for(std::vector<std::string>::iterator it=all_stations.begin();
it != all_stations.end(); it++)
{
if(*it == IDstr.substr(12,5) )
{
is_in_region = true;
break;
}
}
if(is_in_region)
{
disa_view.SetWindowTextA("监测到新的灾情");Sleep(1000);
have_new_disaster = true;
last_disaster_id = IDstr;
WritePrivateProfileString("alert","last_disaster_id",IDstr.c_str(),"./dwsetup.ini");
disa_view.SetWindowTextA("读取灾情详细信息");Sleep(1000);
ReadNewDisaster();
}
}
last_pos--;
}
return have_new_disaster;
}
void CDisasterWatchDlg::ReadNewDisaster()
{
//http://172.18.152.124/dzsp/index.php?action=DisasterInfo_viewbak&ID=201005051329571873005013
std::string url = "/dzsp/index.php?action=DisasterInfo_viewbak&ID="+last_disaster_id;
bool is_download = DownloadHttpPage("172.18.152.124",url.c_str(),"DisasterInfo_viewbak");
Sleep(2000);
if(!is_download) return;
//灾情信息类
DisasterInfo disa_info;
disa_info.init("DisasterInfo_viewbak");
//自动发送短信
if(auto_send_message)
{
disa_view.SetWindowTextA("开始发送短信");Sleep(1000);
for(std::vector<std::string>::iterator it=all_mobile_phone.begin();
it != all_mobile_phone.end(); it++)
{
std::string disaster_sms=disa_info.to_sms();
send_short_message(disaster_sms,*it);
}
}
//显示灾情
disa_view.SetWindowTextA(disa_info.to_text().c_str());
//自动报警
if(auto_alert)
{
close_alert = false;
AfxBeginThread(MyThreadProc,NULL);
if(MessageBox(last_disaster_id.c_str(),"新的灾情",MB_OK)==IDOK)
{
close_alert = true;
}
}
}
// 开机自动运行
void CDisasterWatchDlg::AutoRunAfterStart(void)
{
char AppName[MAX_PATH];
GetModuleFileName(NULL,AppName,MAX_PATH);
CString skey = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
CRegKey writevalue;
writevalue.Create(HKEY_LOCAL_MACHINE,skey);
int error = writevalue.SetStringValue("DisasWatch",AppName);
writevalue.Close();
}
// 隐藏到任务栏
void CDisasterWatchDlg::HideToTray(void)
{
nid.cbSize=(DWORD)sizeof(NOTIFYICONDATA);
nid.hWnd=this->m_hWnd;
nid.uID=IDR_MAINFRAME;
nid.uFlags=NIF_ICON|NIF_MESSAGE|NIF_TIP ;
nid.uCallbackMessage=WM_SHOWTASK;//自定义的消息名称
nid.hIcon=LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAINFRAME));
strcpy_s(nid.szTip,"自动监测灾情直报网页"); //信息提示条为“计划任务提醒”
Shell_NotifyIcon(NIM_ADD,&nid); //在托盘区添加图标
}
LRESULT CDisasterWatchDlg::OnShowTask(WPARAM wParam,LPARAM lParam)
//wParam接收的是图标的ID,而lParam接收的是鼠标的行为
{
if(wParam!=IDR_MAINFRAME)
return 1;
switch(lParam)
{
case WM_RBUTTONUP://右键起来时弹出快捷菜单,这里只有一个“关闭”
{
LPPOINT lpoint=new tagPOINT;
::GetCursorPos(lpoint);//得到鼠标位置
CMenu menu;
menu.CreatePopupMenu();//声明一个弹出式菜单
//增加菜单项“关闭”,点击则发送消息WM_DESTROY给主窗口(已
//隐藏),将程序结束。
menu.AppendMenu(MF_STRING,WM_DESTROY," 退出 ");
//确定弹出式菜单的位置
menu.TrackPopupMenu(TPM_LEFTALIGN,lpoint->x,lpoint->y,this);
//资源回收
HMENU hmenu=menu.Detach();
menu.DestroyMenu();
delete lpoint;
}
break;
case WM_LBUTTONDBLCLK://双击左键的处理
{
ShowWindow(SW_SHOWNORMAL);//简单的显示主窗口完事儿
}
break;
}
return 0;
}
|
#include <iostream>
using namespace std;
int main() {
int num1;
cout <<"Enter the first number:";
cin >> num1;
int num2;
cout <<"Enter the second number:";
cin >> num2;
if(num2 == 0){
throw 99;
}
cout <<"Result:"<<num1 / num2;
return 0;
}
|
// Copyright 2017 Elias Kosunen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#if defined(SCN_HEADER_ONLY) && SCN_HEADER_ONLY
#define SCN_READER_INT_CPP
#endif
#include <scn/detail/args.h>
#include <scn/reader/int.h>
namespace scn {
SCN_BEGIN_NAMESPACE
namespace detail {
SCN_NODISCARD static unsigned char _char_to_int(char ch)
{
static constexpr unsigned char digits_arr[] = {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3,
4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255};
return digits_arr[static_cast<unsigned char>(ch)];
}
SCN_NODISCARD static unsigned char _char_to_int(wchar_t ch)
{
SCN_GCC_PUSH
SCN_GCC_IGNORE("-Wconversion")
if (ch >= std::numeric_limits<char>::min() &&
ch <= std::numeric_limits<char>::max()) {
return _char_to_int(static_cast<char>(ch));
}
return 255;
SCN_GCC_POP
}
template <typename T>
template <typename CharT>
expected<typename span<const CharT>::iterator>
integer_scanner<T>::parse_base_prefix(span<const CharT> s, int& b) const
{
auto it = s.begin();
// If base can be detected, it should start with '0'
if (*it == ascii_widen<CharT>('0')) {
++it;
if (it == s.end()) {
// It's really just 0
// Return it to begininng, where '0' is
b = -1;
return it;
}
if (*it == ascii_widen<CharT>('x') ||
*it == ascii_widen<CharT>('X')) {
// Hex: 0x or 0X
++it;
if (SCN_UNLIKELY(it == s.end())) {
// 0x/0X not a valid number
b = -1;
return --it;
}
if (b == 0) {
// Detect base
b = 16;
}
else if (b != 16) {
// Invalid prefix for base
return error(error::invalid_scanned_value,
"Invalid base prefix");
}
}
else if (*it == ascii_widen<CharT>('b') ||
*it == ascii_widen<CharT>('B')) {
// Binary: 0b or 0b
++it;
if (SCN_UNLIKELY(it == s.end())) {
// 0b/0B not a valid number
b = -1;
return --it;
}
if (b == 0) {
// Detect base
b = 2;
}
else if (b != 2) {
// Invalid prefix for base
return error(error::invalid_scanned_value,
"Invalid base prefix");
}
}
else if (*it == ascii_widen<CharT>('o') ||
*it == ascii_widen<CharT>('O')) {
// Octal: 0o or 0O
++it;
if (SCN_UNLIKELY(it == s.end())) {
// 0o/0O not a valid number
b = -1;
return --it;
}
if (b == 0) {
// Detect base
b = 8;
}
else if (b != 8) {
// Invalid prefix for base
return error(error::invalid_scanned_value,
"Invalid base prefix");
}
}
else if (b == 0) {
// Starting with only 0 -> octal
b = 8;
}
}
if (b == 0) {
// None detected, default to 10
b = 10;
}
return it;
}
template <typename T>
template <typename CharT>
expected<std::ptrdiff_t> integer_scanner<T>::_parse_int(
T& val,
span<const CharT> s)
{
SCN_EXPECT(s.size() > 0);
SCN_MSVC_PUSH
SCN_MSVC_IGNORE(4244)
SCN_MSVC_IGNORE(4127) // conditional expression is constant
if (std::is_unsigned<T>::value) {
if (s[0] == detail::ascii_widen<CharT>('-')) {
return error(error::invalid_scanned_value,
"Unexpected sign '-' when scanning an "
"unsigned integer");
}
}
SCN_MSVC_POP
T tmp = 0;
bool minus_sign = false;
auto it = s.begin();
SCN_GCC_PUSH
SCN_GCC_IGNORE("-Wsign-conversion")
if (s[0] == ascii_widen<CharT>('-')) {
if (SCN_UNLIKELY((format_options & only_unsigned) != 0)) {
// 'u' option -> negative values disallowed
return error(error::invalid_scanned_value,
"Parsed negative value when type was 'u'");
}
minus_sign = true;
++it;
}
else if (s[0] == ascii_widen<CharT>('+')) {
++it;
}
SCN_GCC_POP
if (SCN_UNLIKELY(it == s.end())) {
return error(error::invalid_scanned_value,
"Expected number after sign");
}
// Format string was 'i' or empty -> detect base
// or
// allow_base_prefix (skip 0x etc.)
if (SCN_UNLIKELY(base == 0 ||
(format_options & allow_base_prefix) != 0)) {
int b{base};
auto r = parse_base_prefix<CharT>({it, s.end()}, b);
if (!r) {
return r.error();
}
if (b == -1) {
// -1 means we read a '0'
val = 0;
return ranges::distance(s.begin(), r.value());
}
if (b != 10 && base != b && base != 0) {
return error(error::invalid_scanned_value,
"Invalid base prefix");
}
if (base == 0) {
base = static_cast<uint8_t>(b);
}
it = r.value();
}
SCN_GCC_PUSH
SCN_GCC_IGNORE("-Wconversion")
SCN_GCC_IGNORE("-Wsign-conversion")
SCN_GCC_IGNORE("-Wsign-compare")
SCN_CLANG_PUSH
SCN_CLANG_IGNORE("-Wconversion")
SCN_CLANG_IGNORE("-Wsign-conversion")
SCN_CLANG_IGNORE("-Wsign-compare")
SCN_ASSUME(base > 0);
SCN_CLANG_PUSH_IGNORE_UNDEFINED_TEMPLATE
auto r = _parse_int_impl(tmp, minus_sign, make_span(it, s.end()));
SCN_CLANG_POP_IGNORE_UNDEFINED_TEMPLATE
if (!r) {
return r.error();
}
it = r.value();
if (s.begin() == it) {
return error(error::invalid_scanned_value, "custom::read_int");
}
val = tmp;
return ranges::distance(s.begin(), it);
SCN_CLANG_POP
SCN_GCC_POP
}
template <typename T>
template <typename CharT>
expected<typename span<const CharT>::iterator>
integer_scanner<T>::_parse_int_impl(T& val,
bool minus_sign,
span<const CharT> buf) const
{
SCN_GCC_PUSH
SCN_GCC_IGNORE("-Wconversion")
SCN_GCC_IGNORE("-Wsign-conversion")
SCN_GCC_IGNORE("-Wsign-compare")
SCN_CLANG_PUSH
SCN_CLANG_IGNORE("-Wconversion")
SCN_CLANG_IGNORE("-Wsign-conversion")
SCN_CLANG_IGNORE("-Wsign-compare")
SCN_MSVC_PUSH
SCN_MSVC_IGNORE(4018) // > signed/unsigned mismatch
SCN_MSVC_IGNORE(4389) // == signed/unsigned mismatch
SCN_MSVC_IGNORE(4244) // lossy conversion
using utype = typename std::make_unsigned<T>::type;
const auto ubase = static_cast<utype>(base);
SCN_ASSUME(ubase > 0);
constexpr auto uint_max = static_cast<utype>(-1);
constexpr auto int_max = static_cast<utype>(uint_max >> 1);
constexpr auto abs_int_min = static_cast<utype>(int_max + 1);
const auto cut = div(
[&]() -> utype {
if (std::is_signed<T>::value) {
if (minus_sign) {
return abs_int_min;
}
return int_max;
}
return uint_max;
}(),
ubase);
const auto cutoff = cut.first;
const auto cutlim = cut.second;
auto it = buf.begin();
const auto end = buf.end();
utype tmp = 0;
for (; it != end; ++it) {
const auto digit = _char_to_int(*it);
if (digit >= ubase) {
break;
}
if (SCN_UNLIKELY(tmp > cutoff ||
(tmp == cutoff && digit > cutlim))) {
if (!minus_sign) {
return error(error::value_out_of_range,
"Out of range: integer overflow");
}
return error(error::value_out_of_range,
"Out of range: integer underflow");
}
tmp = tmp * ubase + digit;
}
if (minus_sign) {
// special case: signed int minimum's absolute value can't
// be represented with the same type
//
// For example, short int -- range is [-32768, 32767], 32768
// can't be represented
//
// In that case, -static_cast<T>(tmp) would trigger UB
if (SCN_UNLIKELY(tmp == abs_int_min)) {
val = std::numeric_limits<T>::min();
}
else {
val = -static_cast<T>(tmp);
}
}
else {
val = static_cast<T>(tmp);
}
return it;
SCN_MSVC_POP
SCN_CLANG_POP
SCN_GCC_POP
}
#if SCN_INCLUDE_SOURCE_DEFINITIONS
#define SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(CharT, T) \
template expected<std::ptrdiff_t> integer_scanner<T>::_parse_int( \
T& val, span<const CharT> s); \
template expected<typename span<const CharT>::iterator> \
integer_scanner<T>::_parse_int_impl(T& val, bool minus_sign, \
span<const CharT> buf) const; \
template expected<typename span<const CharT>::iterator> \
integer_scanner<T>::parse_base_prefix(span<const CharT>, int&) const;
#define SCN_DEFINE_INTEGER_SCANNER_MEMBERS(Char) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, signed char) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, short) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, int) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, long) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, long long) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, unsigned char) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, unsigned short) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, unsigned int) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, unsigned long) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, unsigned long long) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, char) \
SCN_DEFINE_INTEGER_SCANNER_MEMBERS_IMPL(Char, wchar_t)
SCN_DEFINE_INTEGER_SCANNER_MEMBERS(char)
SCN_DEFINE_INTEGER_SCANNER_MEMBERS(wchar_t)
#endif
} // namespace detail
SCN_END_NAMESPACE
} // namespace scn
|
#include <iostream>
using namespace std;
//! Template for function header, DO NOT TOUCH
/******************************************************
** Function:
** Description:
** Parameters: NA
** Pre-conditions: NA
** Post-conditions: NA
******************************************************/
/******************************************************
** Function: error_handle_cmd_line
** Description: Error handles the command line arguments
** before it continues.
** Parameters: string &, string &
** Pre-conditions: Take in the command line arguments as
** string references.
** Post-conditions: Return the corrected arguments after
** handling.
******************************************************/
void error_handle_cmd_line(string &, string &);
/******************************************************
** Function: is_int
** Description: Simple custom error handling of a string
** to show if its a valid integer.
** Parameters: string
** Pre-conditions: Take in a string to test.
** Post-conditions: Unchanged, returns a boolean to
** show if it is a valid integer.
******************************************************/
bool is_int(string);
|
/*
* ObstacleTracker detects and tracks obstacles
* Lidar and magnetometer is used
*
* THIS FUNCTION IS UNTESTED!!
*
* Creation date: 2019 08 08
* Author: Jan Kühnemund
*/
#ifndef OBSTACLETRACKER_H
#define OBSTACLETRACKER_H
class ObstacleTracker {
public:
short maxRange = 1200;
short maxObstacleAmount = 50;
float ultraSonicDeviation = 0; //Degrees to Heading when drawing Line from RDMcenter
float ultraSonicHeading = 0; //Degrees Deviation from Heading of RDM
float ultraSonicDistance = 140; //mm distance from center of RDM
float lidar0Deviation = 335;
float lidar0Heading = 0;
float lidar0Distance = 155;
float lidar1Deviation = 345;
float lidar1Heading = 330;
float lidar1Distance = 170;
float lidar2Deviation = 15;
float lidar2Heading = 30;
float lidar2Distance = 170;
float lidar3Deviation = 25;
float lidar3Heading = 0;
float lidar3Distance = 155;
float lidar4Deviation = 90;
float lidar4Heading = 90;
float lidar4Distance = 105;
float lidar5Deviation = 180;
float lidar5Heading = 180;
float lidar5Distance = 140;
float lidar6Deviation = 270;
float lidar6Heading = 270;
float lidar6Distance = 105;
struct obstacle_struct {
int detectionTime;
int updateTime;
float radius;
float xCoordinate;
float yCoordinate;
struct obstacle_struct *next;
};
typedef struct obstacle_struct* obstacle;
void checkForObstacles();
void delDistObst(obstacle);
void mergeSort(obstacle*);
obstacle sortedMerge(obstacle, obstacle);
void frontBackSplit(obstacle, obstacle*, obstacle*);
void updateObstacle(obstacle, float, float);
void addObstacle(obstacle, float, float);
//int checkIfObstacleExist(int*);
obstacle checkIfObstacleExist(obstacle, float, float);
private:
int obstacleAmount;
obstacle myObstacle;
};
#endif
|
#include "line.h"
Line::Line() {
this->x = 0;
this->y = 0;
this->z = 0;
}
Line::Line(Point& p1, Point& p2) {
this->p1 = p1;
this->p2 = p2;
this->v1.setX(p2.getX() - p1.getX());
this->v1.setY(p2.getY() - p1.getY());
this->v1.setX(p2.getZ() - p1.getZ());
}
Line::Line(Point& p1, Vector& v1) {
this->p1 = p1;
this->p2 = Point(p1.getX() + v1.getX(), p1.getY() + v1.getY(), p1.getZ() + v1.getZ());
this->v1 = v1;
}
Line::Line(Line& l2) {
Line& l1 = *this;
Point& p1 = l2.getP1();
Point& p2 = l2.getP2();
l1.setP1(p1);
l1.setP2(p2);
}
//Getters and setters
Point& Line::getP1() {
return this->p1;
}
Point& Line::getP2() {
return this->p2;
}
Vector& Line::getV1() {
return this->v1;
}
void Line::setP1(Point& p1) {
this->p1 = p1;
}
void Line::setP2(Point& p2) {
this->p2 = p2;
}
void Line::setV1(Vector& v1) {
this->v1 = v1;
}
//===============
//===============
// Operations
//===============
//===============
bool Line::operator +(Point& p) {
Line& l = *this;
double x = l.getP1().getX();
double y = l.getP1().getY();
double z = l.getP1().getZ();
Point first = l.getP1();
double x1 = first.getX();
double y1 = first.getY();
double z1 = first.getZ();
Point second = l.getP2();
double x2 = second.getX();
double y2 = second.getY();
double z2 = second.getZ();
double AB = sqrt(pow((x2 - x1), 2) +
pow((y2 - y1), 2) +
pow((z2 - z1), 2));
double AP = sqrt(pow((x - x1), 2) +
pow((y - y1), 2) +
pow((z - z1), 2));
double PB = sqrt(pow((x2 - x), 2) +
pow((y2 - y), 2) +
pow((z2 - z), 2));
if (AB == AP + PB)
{
return true;
}
else {
return false;
}
}
bool Line::operator ||(Line& l2) {
Line& l1 = *this;
if (l1.lineParCheck(l2)) return true;
else return false;
}
bool Line::operator ==(Line& l2) {
Line& l1 = *this;
Vector dir_vec_1 = l1.getV1();
double dir_vec_x1 = dir_vec_1.getX();
double dir_vec_y1 = dir_vec_1.getY();
double dir_vec_z1 = dir_vec_1.getZ();
Vector dir_vec_2 = l1.getV1();
double dir_vec_x2 = dir_vec_2.getX();
double dir_vec_y2 = dir_vec_2.getY();
double dir_vec_z2 = dir_vec_2.getZ();
double x1 = l1.getX();
double y1 = l1.getY();
double z1 = l1.getZ();
double x2 = l2.getX();
double y2 = l2.getY();
double z2 = l2.getZ();
if ((dir_vec_x1 / dir_vec_x2) == (dir_vec_y1 / dir_vec_y2) == (dir_vec_z1 / dir_vec_z2) &&
((x1 == x2) || (y1 == y2) || (z1 == z2)))
{
return true;
}
else {
return false;
}
}
bool Line::operator &&(Line& l2) {
Line& l1 = *this;
double x1 = l1.getX();
double y1 = l1.getY();
double z1 = l1.getZ();
double x2 = l2.getX();
double y2 = l2.getY();
double z2 = l2.getZ();
if ((x1 == x2) || (y1 == y2) || (z1 == z2))return true;
else return false;
}
bool Line::operator !=(Line& l2) {
Line& l1 = *this;
Point first = l2.getP1();
double x1 = first.getX();
double y1 = first.getY();
double z1 = first.getZ();
Point second = l2.getP2();
double x2 = second.getX();
double y2 = second.getY();
double z2 = second.getZ();
Vector dirVec1 = l1.getV1();
double dirVec1X = dirVec1.getX();
double dirVec1Y = dirVec1.getY();
double dirVec1Z = dirVec1.getZ();
Vector dirVec2 = l2.getV1();
double dirVec2X = dirVec2.getX();
double dirVec2Y = dirVec2.getY();
double dirVec2Z = dirVec2.getZ();
double det = (x2 - x1) * ((dirVec1Y * dirVec2Z) - (dirVec1Z * dirVec2Y)) -
(y2 - y1) * ((dirVec1X * dirVec2Z) - (dirVec1Z * dirVec2X)) -
(z2 - z1) * ((dirVec1Z * dirVec2Z) - (dirVec1Z * dirVec2Z));
if (det != 0) return true;
else return false;
}
bool Line::operator |(Line& l2) {
Line l1 = *this;
Vector dirVec1 = l1.getV1();
double dirVec1X = dirVec1.getX();
double dirVec1Y = dirVec1.getY();
double dirVec1Z = dirVec1.getZ();
Vector dirVec2 = l2.getV1();
double dirVec2X = dirVec2.getX();
double dirVec2Y = dirVec2.getY();
double dirVec2Z = dirVec2.getZ();
double dot_equation = (dirVec1X * dirVec2X) + (dirVec1Y * dirVec2Y) + (dirVec1Z * dirVec2Z);
if (dot_equation == 0)return true;
else return false;
}
//===============
//===============
// Methods
//===============
//===============
Vector Line::normalVector() {
Line& l1 = *this;
Vector dir_vec_1 = l1.getV1();
double l = dir_vec_1.getX();
double m = dir_vec_1.getY();
double n = dir_vec_1.getZ();
Point first = l1.getP1();
double x1 = first.getX();
double y1 = first.getY();
double z1 = first.getZ();
double k = -(l * x1 + m * y1 + n * z1) / (pow(l, 2) + pow(m, 2) + pow(n, 2));
double nmvX = (l * k) + x1;
double nmvY = (m * k) + y1;
double nmvZ = (n * k) + z1;
Vector nmv(nmvX, nmvY, nmvZ);
return nmv;
}
double Line::angle(Line& l2) {
Line& l1 = *this;
Vector dir_vec_1 = l1.getV1();
double dir_vec_x1 = dir_vec_1.getX();
double dir_vec_y1 = dir_vec_1.getY();
double dir_vec_z1 = dir_vec_1.getZ();
Vector dir_vec_2 = l2.getV1();
double dir_vec_x2 = dir_vec_2.getX();
double dir_vec_y2 = dir_vec_2.getY();
double dir_vec_z2 = dir_vec_2.getZ();
double cosOfAngle = ((dir_vec_x1 * dir_vec_x2) + (dir_vec_y1 * dir_vec_y2) + (dir_vec_z1 * dir_vec_z2)) / sqrt(pow(dir_vec_x1, 2) + pow(dir_vec_y1, 2) + pow(dir_vec_z1, 2)) * sqrt(pow(dir_vec_x2, 2) + pow(dir_vec_y2, 2) + pow(dir_vec_z2, 2));
double angleRad = acos(cosOfAngle) * 180.0 / PI;
return angleRad;
}
bool Line::lineParCheck(Line& l2) {
Line& l1 = *this;
if (((l1.x / l2.x) == (l1.y / l2.y) == (l1.z / l2.z))) return true;
else return false;
}
std::ostream& operator <<(std::ostream& out, Line& l1) {
out << "First point: " << l1.getP1() << " | Second point: " << l1.getP2();
return out;
}
|
namespace boost {
template<typename T> struct hash;
template<> struct hash<bool>;
template<> struct hash<char>;
template<> struct hash<signed char>;
template<> struct hash<unsigned char>;
template<> struct hash<wchar_t>;
template<> struct hash<short>;
template<> struct hash<unsigned short>;
template<> struct hash<int>;
template<> struct hash<unsigned int>;
template<> struct hash<long>;
template<> struct hash<unsigned long>;
template<> struct hash<long long>;
template<> struct hash<unsigned long long>;
template<> struct hash<float>;
template<> struct hash<double>;
template<> struct hash<long double>;
template<> struct hash<std::string>;
template<> struct hash<std::wstring>;
template<typename T> struct hash<T*>;
template<> struct hash<std::type_index>;
// Support functions (Boost extension).
template<typename T> void hash_combine(size_t &, T const&);
template<typename It> std::size_t hash_range(It, It);
template<typename It> void hash_range(std::size_t&, It, It);
// Overloadable hash implementation (Boost extension).
std::size_t hash_value(bool);
std::size_t hash_value(char);
std::size_t hash_value(signed char);
std::size_t hash_value(unsigned char);
std::size_t hash_value(wchar_t);
std::size_t hash_value(short);
std::size_t hash_value(unsigned short);
std::size_t hash_value(int);
std::size_t hash_value(unsigned int);
std::size_t hash_value(long);
std::size_t hash_value(unsigned long);
std::size_t hash_value(long long);
std::size_t hash_value(unsigned long long);
std::size_t hash_value(float);
std::size_t hash_value(double);
std::size_t hash_value(long double);
template<typename T> std::size_t hash_value(T* const&);
template<typename T, unsigned N> std::size_t hash_value(T (&val)[N]);
template<typename T, unsigned N> std::size_t hash_value(const T (&val)[N]);
template<typename Ch, typename A>
std::size_t hash_value(std::basic_string<Ch, std::char_traits<Ch>, A> const&);
template<typename A, typename B>
std::size_t hash_value(std::pair<A, B> const&);
template<typename T, typename A>
std::size_t hash_value(std::vector<T, A> const&);
template<typename T, typename A>
std::size_t hash_value(std::list<T, A> const&);
template<typename T, typename A>
std::size_t hash_value(std::deque<T, A> const&);
template<typename K, typename C, typename A>
std::size_t hash_value(std::set<K, C, A> const&);
template<typename K, typename C, typename A>
std::size_t hash_value(std::multiset<K, C, A> const&);
template<typename K, typename T, typename C, typename A>
std::size_t hash_value(std::map<K, T, C, A> const&);
template<typename K, typename T, typename C, typename A>
std::size_t hash_value(std::multimap<K, T, C, A> const&);
template<typename T> std::size_t hash_value(std::complex<T> const&);
std::size_t hash_value(std::type_index);
template<typename T, std::size_t N>
std::size_t hash_value(std::array<T, N> const&);
template<typename... T> std::size_t hash_value(std::tuple<T...>);
}
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
//
// A string p is called anti-palindrome if p[i] doesn't equal
// to p[n - i - 1] for each 0 <= i < (n-1)/2, where n is the
// length of p. It means that each character (except the
// middle in the case of a string of odd length) must be
// different from its symmetric character. For example, "c",
// "cpp", "java" are anti-palindrome, but "test", "pp" and
// "weather" are not.
//
//
// You are given a string s. Rearrange its letters in such a
// way that the resulting string is anti-palindrome. If there
// are several solutions, return the one that comes earliest
// alphabetically. If it is impossible to do it, return the
// empty string.
//
//
//
// DEFINITION
// Class:AntiPalindrome
// Method:rearrange
// Parameters:string
// Returns:string
// Method signature:string rearrange(string s)
//
//
// CONSTRAINTS
// -s will contain between 1 and 50 characters, inclusive.
// -s will contain only lowercase letters ('a'-'z').
//
//
// EXAMPLES
//
// 0)
// "test"
//
// Returns: "estt"
//
//
//
// 1)
// "aabbcc"
//
// Returns: "aabcbc"
//
//
//
// 2)
// "reflectionnoitcelfer"
//
// Returns: "cceeeeffiillnnoorrtt"
//
//
//
// 3)
// "hello"
//
// Returns: "ehllo"
//
//
//
// 4)
// "www"
//
// Returns: ""
//
//
//
// END CUT HERE
#line 73 "AntiPalindrome.cpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
class AntiPalindrome
{
public:
string rearrange(string s)
{
sort(s.begin(), s.end());
int n = s.size();
fi(n/2) {
if (s[i] == s[n - i - 1]) {
int st = n - i;
bool f = false;
for (; st<n; ++st) {
if (s[st] != s[n-i-1]) {
swap(s[st], s[n-i-1]);
i = -1;
f = true;
break;
}
}
if (!f) return "";
}
}
return s;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arg0 = "test"; string Arg1 = "estt"; verify_case(0, Arg1, rearrange(Arg0)); }
void test_case_1() { string Arg0 = "aabbcc"; string Arg1 = "aabcbc"; verify_case(1, Arg1, rearrange(Arg0)); }
void test_case_2() { string Arg0 = "reflectionnoitcelfer"; string Arg1 = "cceeeeffiillnnoorrtt"; verify_case(2, Arg1, rearrange(Arg0)); }
void test_case_3() { string Arg0 = "hello"; string Arg1 = "ehllo"; verify_case(3, Arg1, rearrange(Arg0)); }
void test_case_4() { string Arg0 = "www"; string Arg1 = ""; verify_case(4, Arg1, rearrange(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
AntiPalindrome ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
#include <string>
using std::string;
#include <vector>
using std::vector;
double c_ctof(const char* str) {
char* ptr;
double fahr;
double cel;
cel = strtod(str, &ptr);
fahr = ((1.8) * cel) + 32;
cout << "Turned:" << cel << " Celius to: " << fahr << " degrees Fahrenheit" << endl;
return fahr;
}
double cpp_ftoc(const char* str) {
double fahr;
double cel;
string degree;
fahr = atof(str);
cel = ((fahr - 32) * 5) / 9;
cout << "Turned:" << fahr << " degree Fahrenheit to: " << cel << " degrees Celcius" << endl;
return cel;
}
int main(){
vector<string> args;
for (int index = 0; index < argc; index++) {
args.push_back(argv[index]);
}
if (argc >= 2 && args[1] == "--ftoc") {
string temp;
cout << "What temp would you like to change?: ";
cin >> temp;
const char* cstr = temp.c_str();
cpp_ftoc(cstr);
}
if (argc >= 2 && args[1] == "--ctof") {
string temp;
cout << "What temp would you like to change?: ";
cin >> temp;
const char* cstr = temp.c_str();
c_ctof(cstr);
}
return 0;
}
|
/*
* @lc app=leetcode.cn id=855 lang=cpp
*
* [855] 考场就座
*/
// @lc code=start
#include<map>
#include<set>
#include<vector>
using namespace std;
class ExamRoom {
public:
class cmp{
public:
bool operator () (const vector<int> &l, const vector<int> &r){
int distA = distance(l);
int distB = distance(r);
if(distA == distB){
return r[0] - l[0];
}
return distA - distB;
}
};
int N;
map<int,vector<int> > startMap;
map<int, vector<int> > endMap;
set<vector<int>, cmp> pq;
static int distance(vector<int> intv){
int x = intv[0];
int y = intv[1];
int N = intv[2];
if(x == -1)return y;
if(y == N) return N - 1 - x;
return (y - x) / 2;
}
ExamRoom(int N) {
this->N = N;
}
void removeInterval(vector<int> intv){
pq.erase(intv);
startMap.erase(intv[0]);
endMap.erase(intv[1]);
}
void addInterval(vector<int> intv){
pq.insert(intv);
startMap[intv[0]] = intv;
endMap[intv[1]] = intv;
}
int seat() {
vector<int> longest = *(pq.begin());
int x = longest[0];
int y = longest[1];
int seat;
if(x == -1){
seat = 0;
}else if(y == N){
seat = N - 1;
}else{
seat = (y - x) / 2 + x;
}
vector<int> left = {x, seat, N};
vector<int> right = {seat, y, N};
removeInterval(longest);
addInterval(left);
addInterval(right);
return seat;
}
void leave(int p) {
vector<int> right = startMap[p];
vector<int> left = endMap[p];
vector<int> merged = {left[0], right[1], N};
removeInterval(left);
removeInterval(right);
addInterval(merged);
}
};
/**
* Your ExamRoom object will be instantiated and called as such:
* ExamRoom* obj = new ExamRoom(N);
* int param_1 = obj->seat();
* obj->leave(p);
*/
// @lc code=end
|
/**
* Buffer.h
*
* Interface that can be implemented by client applications and that
* is parsed to the Connection::parse() method.
*
* Normally, the Connection::parse() method is fed with a byte
* array. However, if you're receiving big frames, it may be inconvenient
* to copy these big frames into continguous byte arrays, and you
* prefer using objects that internally use linked lists or other
* ways to store the bytes. In such sitations, you can implement this
* interface and pass that to the connection.
*
* @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com>
* @copyright 2014 Copernica BV
*/
/**
* Include guard
*/
#pragma once
/**
* Namespace
*/
namespace AMQP {
/**
* Class definition
*/
class Buffer
{
};
/**
* End of namespace
*/
}
|
#include <iostream>
#include "Matrix.h"
#include <Windows.h>
void SetRuEnc()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
}
int main()
{
SetRuEnc();
std::string line;
while (getline(std::cin, line))
{
std::ofstream out("input.txt");
out << line;
out.close();
std::cout << MakeCalculation("input.txt") << std::endl;
}
return 0;
}
|
#include <iostream>
using namespace std;
int recursion(long long n) { // this doesn't work
if (n == 1)
return 1;
long long x = n;
while (!(x%2)) {
x /= 2;
}
if (x == 1)
return n;
recursion(n-1);
}
int main() {
// only gravity will pull me down
int t;
long long n, p;
cin >> t;
while(t--) {
cin >> n;
p = 1;
while(p*2 <= n) { // finding the power of 2 closest to n
p *= 2;
}
cout << p << endl;
}
return 0;
}
|
#include <iostream>
#include <vector>
using namespace std;
int k, n;
vector<long long> lines;
long long minLength, maxLength;
long long countCompare(long long num){
long long count = 0;
for(long long cur : lines){
count += cur / num;
}
return count;
}
long long find(){
while(minLength <= maxLength){
long long midLength = (minLength + maxLength) / 2;
long long kk = countCompare(midLength);
if(kk >= n){
minLength = midLength + 1;
}else{
maxLength = midLength - 1;
}
}
return maxLength;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> k >> n;
for(int i = 0; i < k; i++){
long long tp;
cin >> tp;
lines.push_back(tp);
maxLength += tp;
}
minLength = 1;
cout << find() << '\n';
return 0;
}
|
//
// Created by 钟奇龙 on 2019-05-01.
//
#include <iostream>
#include <map>
using namespace std;
class Node{
public:
int data;
Node *left;
Node *right;
Node(int x):data(x),left(NULL),right(NULL){}
};
int preorderFind(Node *root,int target,int preSum,int level,int maxLen,map<int,int> &sumMap){
if(!root) return maxLen;
int curSum = root->data + preSum;
if(sumMap.find(curSum) == sumMap.end()){
sumMap[curSum] = level;
}
if(sumMap.find(curSum - target) != sumMap.end()){
maxLen = max(maxLen,level - sumMap[curSum-target]);
}
maxLen = preorderFind(root->left,target,curSum,level+1,maxLen,sumMap);
maxLen = preorderFind(root->right,target,curSum,level+1,maxLen,sumMap);
if(sumMap[curSum] == level){
sumMap.erase(curSum);
}
return maxLen;
}
int getMaxLength(Node *root,int target){
map<int,int> sumMap;
sumMap[0] = 0;
return preorderFind(root,target,0,1,0,sumMap);
}
int main(){
Node *node1 = new Node(1);
Node *node2 = new Node(2);
Node *node3 = new Node(3);
Node *node4 = new Node(4);
Node *node5 = new Node(5);
Node *node6 = new Node(6);
Node *node7 = new Node(7);
node1->left = node2;
node1->right = node3;
node2->left = node4;
node2->right = node5;
node3->left = node6;
node5->right = node7;
cout<<getMaxLength(node1,15)<<endl;
return 0;
}
|
#include "Alime_WindowBase.h"
#include "Alime_TitleBar.h"
#include "Alime_ContentWidget.h"
#include "QFrameLessWidget_Alime.h"
#include "Alime_TransparentWidget.h"
#include <qpushbutton.h>
#include "qlayout.h"
#include "qicon.h"
#ifdef Q_OS_WIN
#pragma comment(lib, "user32.lib")
#include <qt_windows.h>
#endif
Alime_WindowBase::Alime_WindowBase(QWidget* parent, QLayout* ownerBox)
: QWidget(parent),
titleBar_(nullptr),
box_(ownerBox)
{
setAttribute(Qt::WA_StyledBackground, true);
auto content = Alime_ContentWidget::creator_(this);
titleBar_ = new Alime_TitleBar(this);
installEventFilter(titleBar_);
titleBar_->SysButtonEventRegister([=]() { box_->setMargin(content->GetShadowWidth());}, false);
titleBar_->SysButtonEventRegister([=]() {box_->setMargin(0);}, true);
setWindowTitle(content->GetTitle());
setWindowIcon(QIcon(content->GetIcon()));
parentWidget()->resize(content->GetWindowSize());
QVBoxLayout* pLayout = new QVBoxLayout();
pLayout->addWidget(titleBar_);
pLayout->addWidget(content);
pLayout->setSpacing(0);
pLayout->setContentsMargins(0, 0, 0, 0);
setLayout(pLayout);
Alime_TransparentWidget* ptr = (Alime_TransparentWidget*)parent;
connect(ptr, &Alime_TransparentWidget::windowMoved, titleBar_, &Alime_TitleBar::appWindowMoved);
}
|
#include "stdafx.h"
using std::vector;
/*
* Follow up for "remove duplicate from sorted array":what if duplicates are allowed at most twice
* for example, given sorted array A = [1, 1, 1 ,2, 2, 3], your funtion should return length = 5, and A is
* now [1, 1, 2, 2, 3] .
* 紧接着 “移除已排序顺序表中重复元素”: 如果元素最多允许重复两次呢?
* 举个例子,一个给定已排序的顺序表 A = [1, 1, 1 ,2, 2, 3], 你的函数应该返回长度等于5, 并且此时A = [1, 1, 2, 2, 3]
* 分析:
* 由于该顺序表是有序的,所以要顺序遍历用一个辅助变量计数即可
*
*
*/
int remove_duplicates2_self(vector<int> &nums)
{
if (nums.size() <= 2)
{
return nums.size();
}
//常规思维的方法删除中多余的元素不可行,因为删除会改变表的长度,引用时易发生违规内存访问
return nums.size();
}
int remove_duplicates2(vector<int> &nums)
{
if (nums.size() <= 2)
{
return nums.size();
}
int index = 2; //此时nums长度一定大于2,取index为2
//设初始符合结果的表长为index,初始为2,元素下标为2及2之后的元素
//为向表后添加使得nums的前index个元素仍符合结果要求
for(int i = 2; i < nums.size(); ++i)
{
//从第三个开始向后遍历
if (nums[i] not_eq nums[i - 2])
{
//如果第 i 个元素等于第 i - 2 个元素,那么这个元素不可以向输出表后添加直接跳过
//则index不变
//当第 i 个元素不等于第 i - 2 个元素,那么这个元素就可以向输出表后添加,
//那么index + 1
nums[index++] = nums[i];
}
}
//当循环结束时,index的值为输出表元素的个数
return index;
}
int remove_duplicates2_(vector<int> &nums)
{
int n = nums.size();
int index = 0; //设初始输出表长为0
for (int i = 0; i < n; ++i)
{
//当第 i 个元素等于第 i - 1 且等于第 i + 1 个元素时,认为表长是无需变化的
//第 i 个元素无需添加到表 index后面
if (i > 0 and i < n - 1 and nums[i] == nums[i - 1] and nums[i] == nums[i + 1])
continue;
//如果上述条件有一个不符合,则第 i 个元素应该添加到index后
nums[index++] = nums[i];
}
return index;
}
|
#pragma once
#include <memory>
#include <vector>
#include "Vec.h"
namespace quadtree {
class Node;
class Node {
private:
Vec pos;
Vec sz;
std::unique_ptr<Node> SE;
std::unique_ptr<Node> SW;
std::unique_ptr<Node> NW;
std::unique_ptr<Node> NE;
bool isLeaf() const { return !(NE || SW || SE || NW); }
bool isColision(Vec p) const { return p.x > pos.x && p.y > pos.y && p.x < pos.x + sz.x && p.y < pos.y + sz.y; }
void findLeaves(std::vector<const Node*>& leaves) const;
Node(Vec pos, Vec sz) : pos(pos), sz(sz) {};
public:
void setNE(Vec pos, Vec sz) { NE.reset(new Node(pos, sz)); }
void setSE(Vec pos, Vec sz) { SE.reset(new Node(pos, sz)); }
void setSW(Vec pos, Vec sz) { SW.reset(new Node(pos, sz)); }
void setNW(Vec pos, Vec sz) { NW.reset(new Node(pos, sz)); }
const Node* findLeaf(Vec p) const;
std::vector<const Node*> findLeaves() const;
Vec getPos() const { return pos; }
Vec getSize() const { return sz; }
static std::unique_ptr<Node> create(Vec pos, Vec sz) { return std::unique_ptr<Node>(new Node(pos, sz)); }
};
}
|
// TraceRouteDlg.h: 头文件
//
#pragma once
#include "NIC.h"
#include "Device.h"
#include "EthernetFrame.h"
#include "ICMP.h"
#define WM_RECV (WM_USER + 100)
#define WM_HOST (WM_USER + 101)
#define ICMP_REQUEST_ID 0x1234
// CTraceRouteDlg 对话框
class CTraceRouteDlg : public CDialogEx
{
// 构造
public:
CTraceRouteDlg(CWnd* pParent = nullptr); // 标准构造函数
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_TRACEROUTE_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg LRESULT OnRecv(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnHost(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
public:
NIC nic;
int index;
Device device;
bool started;
DWORD m_dstip;
DWORD m_srcip;
DWORD m_mask;
BYTE *m_srcmac;
BYTE *m_dstmac;
BYTE *m_gwmac;
CWinThread *hThread;
BYTE ttl;
SYSTEMTIME timesend;
SYSTEMTIME timerecv;
DWORD routerip;
time_t timesub;
CListCtrl m_CListCtrl;
CIPAddressCtrl m_CIPAddressCtrl;
public:
afx_msg void OnBnClickedButtonAbout();
afx_msg void OnBnClickedButtonTrace();
void icmpRequest(BYTE *buffer, BYTE ttl);
static UINT CTraceRouteDlg::sendAndRecv(LPVOID lpParam);
static UINT CTraceRouteDlg::getHostName(LPVOID lpParam);
afx_msg void OnBnClickedCancel();
};
|
#include <cstdio>
#include <algorithm>
using namespace std;
//In the order of favorite color, each color is unique, so hash color to order.
//The color can be duplicate so hash[i] >= hash[j]
//The length of dp[] is 10010 not 210
int main(){
int n, m, l, count = 0;
int pattern[210], target[10010], hash[210], dp[10010];
bool has[210] = {false};
scanf("%d", &n);
scanf("%d", &m);
for(int i = 0; i < m; i++){
scanf("%d", &pattern[i]);
has[pattern[i]] = true;
}
scanf("%d", &l);
for(int i = 0; i < l; i++){
int a;
scanf("%d", &a);
if(has[a]){
target[count++] = a;
}
}
for(int i = 0; i < m; i++){
hash[pattern[i]] = i;
}
int longest = 0;
for(int i = 0; i < count; i++){
dp[i] = 1;
for(int j = 0; j < i; j++){
if(hash[target[i]] >= hash[target[j]]){
dp[i] = max(dp[i], dp[j] + 1);
}
}
longest = max(dp[i], longest);
}
printf("%d\n", longest);
return 0;
}
|
#include <iostream>
#include <iomanip>
int main(int argc, char const *argv[])
{
int T;
std::cin >> T;
std::cout << setiosflags(std::ios::uppercase);
std::cout << setw(0xf) << internal;
while(T--) {
double A; std::cin >> A;
double B; std::cin >> B;
double C; std::cin >> C;
std::cout << resetiosflags(std::ios::uppercase|std::ios::scientific);
std::cout << std::setiosflags (std::ios::left|std::ios::fixed);
std::cout << setw(0) << std::hex;
std::cout << std::setiosflags (std::ios::showbase);
std::cout << (unsigned long)A << std::endl;
std::cout << resetiosflags(std::ios::showbase);
std::cout << setw(0xf) << setfill('_')<< std::dec ;
std::cout << setiosflags (std::ios::showpos) << std::setprecision(2);
std::cout << B << endl;
std::cout << resetiosflags(std::ios::fixed|std::ios::showpos);
std::cout << setiosflags (std::ios::scientific | std::ios::uppercase) << std::setprecision(9);
std::cout << C << std::endl;
}
return 0;
}
|
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "../include/command_interface.h"
command_interface::command_interface(void)
{
show_author();
show_command_list();
}
void command_interface::update_interface(void)
{
/* Interface variables */
string input, command, parameter, file_dir;
string symbol = symbol_const;
config_name = "config.xml"; // Default name
string generation_name = "";
isConfigOk = false;
isGenerationOk = false;
isFolderCreated = false;
while (1)
{
cout << symbol;
getline(cin, input);
if (input.empty()) continue; // If ENTER is pressed with no symbols
istringstream iss(input);
file_dir = "";
command = "";
parameter = "";
iss >> command >> parameter;
// Look until end if the input string fits command_list
auto it = find(command_list.begin(), command_list.end(), command);
/* Commands: load data, ld+file_name*/
if (it == find(command_list.begin(), command_list.end(), "ld"))
{
// Set filename if parameter is given
if (!parameter.empty()) // If no filename given, then use default
config_name = parameter;
// If "cd" was used
if (local_dir.empty())
file_dir = config_name;
else
file_dir = local_dir + "/" + config_name;
ifstream file(file_dir);
// Check file
if (file.good())
{
isConfigOk = true;
file.close();
}
if (isConfigOk)
isConfigOk = load_device_params(file_dir);
if (isConfigOk)
isConfigOk = load_stack_params(file_dir);
if (isConfigOk)
isConfigOk = load_settings(file_dir);
if (isConfigOk)
cout << "Device and settings loaded successfully" << endl;
// Print current stack by iteration through layers of the stack
cout << "The current stack is cathode/";
for (list<unscaled_layer_params>::iterator it_layer=layers_params.stack_params.begin(); it_layer != layers_params.stack_params.end(); ++it_layer)
cout << it_layer->name << "/";
cout << "anode" << endl;
// Report
if (isConfigOk)
cout << file_dir << " loaded successfully" << endl;
else
cout << file_dir << " has issues or doesn't exist!" << endl;
}
/* Commands: save data, sd */
else if (it == find(command_list.begin(), command_list.end(), "sd"))
{
if (local_dir.empty()) // If "cd" was used
file_dir = config_name;
else
file_dir = local_dir + "/" + config_name;
if (isConfigOk)
{
save_device_params(file_dir);
// Iterate through layers of the stack
for (list<unscaled_layer_params>::iterator it_layer=layers_params.stack_params.begin(); it_layer != layers_params.stack_params.end(); ++it_layer)
save_layer_params(file_dir, &(*it_layer));
save_setting(file_dir);
cout << "config.xml saved successfully" << endl;
}
else
cout << "Parameters are not loaded yet, ld" << endl;
}
/* Commands: create directory, cd+folder_name */
else if (it == find(command_list.begin(), command_list.end(), "cd"))
{
local_dir = parameter;
symbol = local_dir + symbol_const;
mkdir(local_dir.c_str(), 0700);
if (parameter.empty())
{
symbol = symbol_const;
isFolderCreated = false;
}
else
isFolderCreated = true;
}
/* Commands: load generation profile, lg+gener_dir_name */
else if (it == find(command_list.begin(), command_list.end(), "lg"))
{
generation_name = parameter;
if (local_dir.empty()) // If "cd" was used
file_dir = generation_name;
else
file_dir = local_dir + "/" + generation_name;
if (parameter.empty())
cout << "Name for file with generation profile must be given" << endl;
else
{
isGenerationOk = load_generation_file(file_dir);
if (isGenerationOk)
cout << file_dir << " loaded successfully" << endl;
else
cout << "File " << file_dir << " does not exist" << endl;
}
}
/* Commands: simulate, ds */
else if (it == find(command_list.begin(), command_list.end(), "ds"))
{
if (isConfigOk && isFolderCreated && isGenerationOk)
{
/* Simulate drift-diffusion model */
mode_single_voltage();
}
else if (isConfigOk == false)
cout << "Parameters are not loaded yet, ld" << endl;
else if (isFolderCreated == false)
cout << "Folder for the results is not created yet, cd" << endl;
else if (isGenerationOk == false)
cout << "Generation profile is not loaded, lg" << endl;
else
cout << "Check cd, ld or lg command" << endl;
}
/* Commands: simulate, dv */
else if (it == find(command_list.begin(), command_list.end(), "dv"))
{
if (isConfigOk && isFolderCreated && isGenerationOk)
{
/* Simulate drift-diffusion model */
mode_series_voltage();
}
else if (isConfigOk == false)
cout << "Parameters are not loaded yet, ld" << endl;
else if (isFolderCreated == false)
cout << "Folder for the results is not created yet, cd" << endl;
else if (isGenerationOk == false)
cout << "Generation profile is not loaded, lg" << endl;
else
cout << "Check cd, ld or lg command" << endl;
}
/* Commands: simulate, dt */
else if (it == find(command_list.begin(), command_list.end(), "dt"))
{
if (isConfigOk && isFolderCreated && isGenerationOk)
{
/* Simulate drift-diffusion model */
mode_pulse_illumination();
}
else if (isConfigOk == false)
cout << "Parameters are not loaded yet, ld" << endl;
else if (isFolderCreated == false)
cout << "Folder for the results is not created yet, cd" << endl;
else if (isGenerationOk == false)
cout << "Generation profile is not loaded, lg" << endl;
else
cout << "Check cd, ld or lg command" << endl;
}
/* Commands: simulate, dh */
else if (it == find(command_list.begin(), command_list.end(), "dh"))
{
if (isConfigOk && isFolderCreated && isGenerationOk)
{
/* Simulate drift-diffusion model */
mode_hysteresis();
}
else if (isConfigOk == false)
cout << "Parameters are not loaded yet, ld" << endl;
else if (isFolderCreated == false)
cout << "Folder for the results is not created yet, cd" << endl;
else if (isGenerationOk == false)
cout << "Generation profile is not loaded, lg" << endl;
else
cout << "Check cd, ld or lg command" << endl;
}
/* Commands: help, h */
else if (it == find(command_list.begin(), command_list.end(), "h"))
{
cout << "This is a transient 1D drift-diffusion model" << endl;
show_command_list();
}
/* Commands: show author, a */
else if (it == find(command_list.begin(), command_list.end(), "a"))
{
show_author();
}
/* Commands: clean screen, c */
else if (it == find(command_list.begin(), command_list.end(), "c"))
{
systemRet = system("clear");
if (systemRet == -1) // Error handler
{
cout << "System error" << endl;
break;
}
}
/* Commands: exit, q */
else if (it == find(command_list.begin(), command_list.end(), "q"))
{
break;
}
/* Command error */
else
cout << "There is no command like this!" << endl;
}
}
|
#include <iostream>
#include <cmath>
struct Point {
public:
int x = 0;
int y = 0;
public:
static double distance;
public:
static void setDistance(double distance) {
Point::distance = distance;
}
void setX(int x) {
Point::x = x;
}
void setY(int y) {
Point::y = y;
}
public :
static double CalculateDistance(Point q, Point p) {
distance = sqrt(pow((q.x - p.x), 2) + pow((q.y - p.y), 2));
return distance;
}
static void PrintDistance() {
std::cout << distance;
}
};
double Point::distance = 0;
int main() {
Point a;
Point b;
int x1=0;
std::cin>>x1;
a.setX(x1);
int y1=0;
std::cin>>y1;
a.setY(y1);
int x2=0;
std::cin>>x2;
b.setX(x2);
int y2=0;
std::cin>>y2;
b.setY(y2);
Point::CalculateDistance(a, b);
Point::PrintDistance();
return 0;
}
|
#ifndef SHOEMESSAGELOGIN_H
#define SHOEMESSAGELOGIN_H
#include <QByteArray>
#include "shoemanagermodel_global.h"
class SHOEMANAGERMODELSHARED_EXPORT ShoeMessageLogin
{
public:
// 留作以后的标识
QString getIMEI();
void parseData(QByteArray data);
private:
QString mIMEI;
QString mVersion;
};
#endif // SHOEMESSAGELOGIN_H
|
#include "Jeu.h"
Jeu::Jeu()
{
}
void Jeu::rejouer()
{
if(m_state==STATE_FIN)
{
m_joueur1=Joueur(1);
m_joueur2=Joueur(2);
m_joueur1.m_typeAffichage=TYPE_SANS;
m_joueur2.m_typeAffichage=TYPE_SANS;
m_state=STATE_REPOS;
m_timeStartNewState=system_clock::now();
}
}
void Jeu::jouer(vector<Marker> markers)
{
cout << "Temps depuis dernier changement : " << duration_cast<seconds>(system_clock::now()-m_timeStartNewState).count() << endl;
cout << "Etat : " << m_state << endl;
if(markers.size()!=2)
{
if(m_state==STATE_REPOS)
{
m_state=STATE_INITIAL;
m_timeStartNewState=system_clock::now();
}
else
return;
}
else
{
if(m_state==STATE_INITIAL)
{
cout << "Initialisation" << endl;
for(int i=0;i<2;i++)
{
cout << "type de marker :" << markers[i].id/150 << endl;
switch(markers[i].id/150)
{
case 0:
m_joueur1.m_carte=PLANTE;
break;
case 1:
m_joueur1.m_carte=FEU;
break;
case 2:
m_joueur1.m_carte=EAU;
break;
case 3:
m_joueur2.m_carte=PLANTE;
break;
case 4:
m_joueur2.m_carte=FEU;
break;
case 5:
m_joueur2.m_carte=EAU;
break;
default:
cerr << "Marker non reconnu" << endl;
break;
}
}
m_joueur1.m_typeAffichage=TYPE_COMBAT;
m_joueur2.m_typeAffichage=TYPE_COMBAT;
m_state=STATE_COMBAT;
m_timeStartNewState=system_clock::now();
}
if(m_state==STATE_COMBAT && (duration_cast<seconds>(system_clock::now()-m_timeStartNewState).count())>3)
{
cout << "Combat" << endl;
if(m_joueur1.m_carte==PLANTE && m_joueur2.m_carte==FEU)
{
m_joueur1.m_evolutionPlante=1;
m_joueur2.m_evolutionFeu++;
m_joueur1.m_typeAffichage=TYPE_MORT;
m_joueur2.m_typeAffichage=TYPE_EVOLUTION1;
}
if(m_joueur1.m_carte==PLANTE && m_joueur2.m_carte==EAU)
{
m_joueur1.m_evolutionPlante++;
m_joueur2.m_evolutionEau=1;
m_joueur1.m_typeAffichage=TYPE_EVOLUTION1;
m_joueur2.m_typeAffichage=TYPE_MORT;
}
if(m_joueur1.m_carte==EAU && m_joueur2.m_carte==FEU)
{
m_joueur1.m_evolutionEau++;
m_joueur2.m_evolutionFeu=1;
m_joueur1.m_typeAffichage=TYPE_EVOLUTION1;
m_joueur2.m_typeAffichage=TYPE_MORT;
}
if(m_joueur1.m_carte==EAU && m_joueur2.m_carte==PLANTE)
{
m_joueur1.m_evolutionEau=1;
m_joueur2.m_evolutionPlante++;
m_joueur1.m_typeAffichage=TYPE_MORT;
m_joueur2.m_typeAffichage=TYPE_EVOLUTION1;
}
if(m_joueur1.m_carte==FEU && m_joueur2.m_carte==EAU)
{
m_joueur1.m_evolutionFeu=1;
m_joueur2.m_evolutionEau++;
m_joueur1.m_typeAffichage=TYPE_MORT;
m_joueur2.m_typeAffichage=TYPE_EVOLUTION1;
}
if(m_joueur1.m_carte==FEU && m_joueur2.m_carte==PLANTE)
{
m_joueur1.m_evolutionFeu++;
m_joueur2.m_evolutionPlante=1;
m_joueur1.m_typeAffichage=TYPE_EVOLUTION1;
m_joueur2.m_typeAffichage=TYPE_MORT;
}
m_state=STATE_EVOLUTION;
m_timeStartNewState=system_clock::now();
}
if(m_state==STATE_EVOLUTION && (duration_cast<seconds>(system_clock::now()-m_timeStartNewState).count())>2)
{
if( m_joueur1.m_evolutionFeu==3 ||
m_joueur1.m_evolutionEau==3 ||
m_joueur1.m_evolutionPlante==3 ||
m_joueur2.m_evolutionFeu==3 ||
m_joueur2.m_evolutionEau==3 ||
m_joueur2.m_evolutionPlante==3)
{
m_state=STATE_FIN;
m_timeStartNewState=system_clock::now();
}
else
{
m_joueur1.m_typeAffichage=TYPE_SANS;
m_joueur2.m_typeAffichage=TYPE_SANS;
m_state=STATE_REPOS;
m_timeStartNewState=system_clock::now();
}
}
}
}
void Jeu::afficher(int id)
{
if(id/450==0)
m_joueur1.afficher();
else
m_joueur2.afficher();
}
|
/* Author: Puttichai Lertkultanon */
#include "SuperBotConfig.h"
#include "SuperBotStateSpace.h"
#include "SuperBotProjection.h"
#include <cmath>
#include <vector>
#include <sstream>
namespace ob = ompl::base;
SuperBotStateSpace::SuperBotStateSpace(RobotBasePtr probot) {
_probot = probot;
_ndof = _probot->GetActiveDOF();
_dimension = 2*_ndof;
ob::RealVectorStateSpace* qSpace(new ob::RealVectorStateSpace(_ndof));
ob::RealVectorStateSpace* qdSpace(new ob::RealVectorStateSpace(_ndof));
std::vector<double> qL, qU, qdU;
_probot->GetDOFLimits(qL, qU);
_probot->GetDOFVelocityLimits(qdU);
ob::RealVectorBounds qBounds(_ndof);
ob::RealVectorBounds qdBounds(_ndof);
// Set joint value and joint velocity bounds
for (unsigned int i = 0; i < _ndof; i++) {
qBounds.setLow(i, qL[i]);
qBounds.setHigh(i, qU[i]);
qdBounds.setLow(i, -qdU[i]);
qdBounds.setHigh(i, qdU[i]);
}
qSpace->setBounds(qBounds);
qdSpace->setBounds(qdBounds);
// Add subspaces to SuperBotStateSpace
addSubspace(ob::StateSpacePtr(qSpace), 0.5);
addSubspace(ob::StateSpacePtr(qdSpace), 0.5);
}
unsigned int SuperBotStateSpace::getDimension() {
return _dimension;
}
void SuperBotStateSpace::registerProjections() {
registerDefaultProjection(ob::ProjectionEvaluatorPtr(new SuperBotProjection(this, _probot, projectionType)));
}
double SuperBotStateSpace::distance(const ob::State *state1, const ob::State *state2) const {
const ob::CompoundStateSpace::StateType *s1 = state1->as<ob::CompoundStateSpace::StateType>();
const ob::CompoundStateSpace::StateType *s2 = state2->as<ob::CompoundStateSpace::StateType>();
const double* q1 = s1->as<ob::RealVectorStateSpace::StateType>(0)->values;
const double* qd1 = s1->as<ob::RealVectorStateSpace::StateType>(1)->values;
const double* q2 = s2->as<ob::RealVectorStateSpace::StateType>(0)->values;
const double* qd2 = s2->as<ob::RealVectorStateSpace::StateType>(1)->values;
double dist = 0.0;
for (unsigned int i = 0; i < _ndof; i++)
{
double delta_q = (q1[i] - q2[i]);
double delta_qd = 0;
double wq = 0.5;
double wqd = 0.5;
if (_includeVelocityDistance)
delta_qd = delta_qd + (qd1[i] - qd2[i]);
dist = dist + wq*(delta_q*delta_q) + wqd*(delta_qd*delta_qd);
}
return dist;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* 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.
*
* @author Arjan van Leeuwen (arjanl)
*/
#ifndef ZLIB_STREAM_H
#define ZLIB_STREAM_H
#include "adjunct/desktop_util/datastructures/StreamBuffer.h"
typedef struct z_stream_s z_stream;
/** @brief Stream class used to compress or decompress data with 'deflate' (zlib)
* Depending on use, use CompressZlibStream or DecompressZlibStream
*
* e.g.
* CompressZlibStream stream;
* stream.AddData(uncompressed, uncompressed_length)
* stream.Flush(compressed);
*/
class ZlibStream
{
public:
ZlibStream();
virtual ~ZlibStream();
/** Add input data to this stream
* @param source Data to add
* @param length Length of data to add
*/
OP_STATUS AddData(const char* source, size_t length) { return AddData(source, length, FALSE); }
/** Flush the output of this stream to a buffer
* @param output Where to flush output to
*/
OP_STATUS Flush(StreamBuffer<char>& output);
protected:
OP_STATUS AddData(const char* source, size_t length, BOOL flush);
OP_STATUS Init();
virtual OP_STATUS AddDataInternal(const char* source, size_t length, BOOL flush) = 0;
virtual OP_STATUS InitializeStream() = 0;
static const size_t BlockSize = 1024;
char* m_block;
StreamBuffer<char> m_buffer;
z_stream* m_stream;
};
class CompressZlibStream : public ZlibStream
{
public:
virtual ~CompressZlibStream();
protected:
virtual OP_STATUS AddDataInternal(const char* source, size_t length, BOOL flush);
virtual OP_STATUS InitializeStream();
};
class DecompressZlibStream : public ZlibStream
{
public:
DecompressZlibStream(BOOL has_gzip_header = FALSE)
: ZlibStream(), m_has_gzip_header(has_gzip_header) {}
virtual ~DecompressZlibStream();
protected:
virtual OP_STATUS AddDataInternal(const char* source, size_t length, BOOL flush);
virtual OP_STATUS InitializeStream();
private:
BOOL m_has_gzip_header;
};
#endif // ZLIB_STREAM_H
|
/*
Copyright (c) 2017 Xavier Leclercq
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "SQLiteDatabaseDumpComparisonTestTests.h"
#include "Ishiko/TestFramework/SQLiteTests/SQLiteDatabaseDumpComparisonTest.h"
#include "Ishiko/SQLite/sqlite3.h"
void AddSQLiteDatabaseDumpComparisonTestTests(Ishiko::TestFramework::TestHarness& theTestHarness)
{
Ishiko::TestFramework::TestSequence& comparisonTestSequence =
theTestHarness.appendTestSequence("SQLiteDatabaseDumpComparisonTest tests");
new Ishiko::TestFramework::HeapAllocationErrorsTest("Creation test 1",
SQLiteDatabaseDumpComparisonTestCreationTest1, comparisonTestSequence);
new Ishiko::TestFramework::HeapAllocationErrorsTest("Creation test 2",
SQLiteDatabaseDumpComparisonTestCreationTest2, comparisonTestSequence);
new Ishiko::TestFramework::HeapAllocationErrorsTest("run success test 1",
SQLiteDatabaseDumpComparisonTestRunSuccessTest1, comparisonTestSequence);
new Ishiko::TestFramework::HeapAllocationErrorsTest("run failure test 1",
SQLiteDatabaseDumpComparisonTestRunFailureTest1, comparisonTestSequence);
}
Ishiko::TestFramework::TestResult::EOutcome SQLiteDatabaseDumpComparisonTestCreationTest1()
{
Ishiko::TestFramework::SQLiteDatabaseDumpComparisonTest test(
Ishiko::TestFramework::TestNumber(), "SQLiteDatabaseDumpComparisonTestCreationTest1");
return Ishiko::TestFramework::TestResult::ePassed;
}
Ishiko::TestFramework::TestResult::EOutcome SQLiteDatabaseDumpComparisonTestCreationTest2Helper(Ishiko::TestFramework::SQLiteDatabaseDumpComparisonTest& test)
{
return Ishiko::TestFramework::TestResult::ePassed;
}
Ishiko::TestFramework::TestResult::EOutcome SQLiteDatabaseDumpComparisonTestCreationTest2()
{
Ishiko::TestFramework::SQLiteDatabaseDumpComparisonTest test(
Ishiko::TestFramework::TestNumber(), "SQLiteDatabaseDumpComparisonTestCreationTest2",
SQLiteDatabaseDumpComparisonTestCreationTest2Helper);
return Ishiko::TestFramework::TestResult::ePassed;
}
Ishiko::TestFramework::TestResult::EOutcome SQLiteDatabaseDumpComparisonTestRunSuccessTest1Helper(Ishiko::TestFramework::SQLiteDatabaseDumpComparisonTest& test)
{
sqlite3* db = 0;
sqlite3_open(test.databaseFilePath().string().c_str(), &db);
sqlite3_close(db);
return Ishiko::TestFramework::TestResult::ePassed;
}
Ishiko::TestFramework::TestResult::EOutcome SQLiteDatabaseDumpComparisonTestRunSuccessTest1(Ishiko::TestFramework::Test& test)
{
Ishiko::TestFramework::SQLiteDatabaseDumpComparisonTest dbtest(
Ishiko::TestFramework::TestNumber(), "SQLiteDatabaseDumpComparisonTestRunSuccessTest1",
SQLiteDatabaseDumpComparisonTestRunSuccessTest1Helper);
dbtest.setDatabaseFilePath(test.environment().getTestOutputDirectory() / "SQLiteDatabaseDumpComparisonTestRunSuccessTest1.db");
dbtest.run();
return dbtest.result().outcome();
}
Ishiko::TestFramework::TestResult::EOutcome SQLiteDatabaseDumpComparisonTestRunFailureTest1Helper(Ishiko::TestFramework::SQLiteDatabaseDumpComparisonTest& test)
{
return Ishiko::TestFramework::TestResult::eFailed;
}
Ishiko::TestFramework::TestResult::EOutcome SQLiteDatabaseDumpComparisonTestRunFailureTest1()
{
Ishiko::TestFramework::SQLiteDatabaseDumpComparisonTest test(
Ishiko::TestFramework::TestNumber(), "SQLiteDatabaseDumpComparisonTestRunFailureTest1",
SQLiteDatabaseDumpComparisonTestRunSuccessTest1Helper);
test.run();
if (test.result().outcome() == Ishiko::TestFramework::TestResult::eFailed)
{
return Ishiko::TestFramework::TestResult::ePassed;
}
else
{
return Ishiko::TestFramework::TestResult::eFailed;
}
}
|
#include <gtest/gtest.h>
#include "utl/base.h"
using namespace utl;
TEST(Base, Countof)
{
const uint8_t arr_1[10] = {};
const uint16_t arr_2[20] = {};
const uint32_t arr_3[30] = {};
EXPECT_EQ(countof(arr_1), 10);
EXPECT_EQ(countof(arr_2), 20);
EXPECT_EQ(countof(arr_3), 30);
}
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#ifndef __GT_DOC_PAGE_P_H__
#define __GT_DOC_PAGE_P_H__
#include "gtdocpage.h"
GT_BEGIN_NAMESPACE
class GtDocPagePrivate
{
Q_DECLARE_PUBLIC(GtDocPage)
public:
GtDocPagePrivate();
virtual ~GtDocPagePrivate();
public:
inline void initialize(GtDocument *d, int i, double w, double h)
{
document = d;
index = i;
width = w;
height = h;
}
GtAbstractPage *abstractPage;
GtDocTextPointer text;
protected:
GtDocPage *q_ptr;
GtDocument *document;
QString label;
int index;
int textLength;
double width;
double height;
};
GT_END_NAMESPACE
#endif /* __GT_DOC_PAGE_P_H__ */
|
#ifndef TRAPEZOID_H
#define TRAPEZOID_H
#include "figure.h"
// Наследуемся от Figure
class Trapezoid : public Figure
{
Q_OBJECT
public:
Trapezoid(QObject *parent = 0);
~Trapezoid();
private:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); // Реализуем отрисовку
};
#endif // TRAPEZOID_H
///////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef PENTAGON_H
#define PENTAGON_H
#include "figure.h"
// Наследуемся от Figure
class Pentagon : public Figure
{
Q_OBJECT
public:
Pentagon(QObject *parent = 0);
~Pentagon();
private:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); // Реализуем отрисовку
};
#endif // PENTAGON_H
///////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef DODECAGON_H
#define DODECAGON_H
#include "figure.h"
// Наследуемся от Figure
class Dodecagon : public Figure
{
Q_OBJECT
public:
Dodecagon(QObject *parent = 0);
~Dodecagon();
private:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); // Реализуем отрисовку
};
#endif // DODECAGON_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef PLUGIN_WRAPPER_MESSAGE_LOOP_H
#define PLUGIN_WRAPPER_MESSAGE_LOOP_H
#ifdef PLUGIN_WRAPPER
#include "platforms/windows/IPC/WindowsOpComponentPlatform.h"
class PluginWrapperMessageLoop : public WindowsOpComponentPlatform
{
public:
PluginWrapperMessageLoop();
~PluginWrapperMessageLoop();
OP_STATUS Init();
private:
OP_STATUS ProcessMessage(MSG &msg);
OP_STATUS DoLoopContent(BOOL ran_core);
double m_last_flash_message;
OpVector<MSG> m_delayed_flash_messages;
};
#endif // PLUGIN_WRAPPER
#endif // PLUGIN_WRAPPER_MESSAGE_LOOP_H
|
#include "mainwindow.h"
/**** PUBLIC FUNCTIONS ***/
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//ui->JackpotLabel->setStyleSheet("Background-image: url(:/Images/jackpot.jpg);");
ui->stackedWidget->setCurrentWidget(ui->w_main);
this->player_turn = _p1;
this->size = 0;
this->flagAI=0;
}
MainWindow::~MainWindow()
{
delete ui;
}
/**** PRIVATE FUNCTIONS ****/
void MainWindow::configureBoard()
{
GameBoardSizeDialog* dialog = new GameBoardSizeDialog(this);
dialog->exec(); //board size now set in shared.h
board_size = dialog->board_size;
tile = new Tile**[board_size];
for(int i = 0; i < board_size; i++)
tile[i] = new Tile*[board_size];
this->size = 0;
for(int row = 0; row < board_size; row++) {
for(int col = 0; col < board_size; col++) {
tile[row][col] = new Tile(row, col, this);
QSizePolicy policy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
tile[row][col]->setSizePolicy(policy);
connect(tile[row][col], SIGNAL(clicked()), this, SLOT(on_b_tile_clicked()));
ui->g_board->addWidget(tile[row][col], row, col);
}
}
ui->t_result->setText(QString("Player 'X' Turn"));
ui->t_result->setAlignment(Qt::AlignCenter);
}
void MainWindow::togglePlayer()
{
if(player_turn == _p1) {
player_turn = _p2;
ui->t_result->setText(QString("Player 'O' Turn"));
}
else {
player_turn = _p1;
ui->t_result->setText(QString("Player 'X' Turn"));
}
ui->t_result->setAlignment(Qt::AlignCenter);
}
void MainWindow::disableTileClicks()
{
for(int i=0;i<board_size;i++)
for(int j=0;j<board_size;j++)
tile[i][j]->setEnabled(false);
}
bool MainWindow::playMini()
{
SelectMinigameDialog selectMinigameDialog(this);
selectMinigameDialog.exec();
std::string mini = selectMinigameDialog.getSelectedMinigame();
if(mini.compare("Random Chance") == 0)
{
RandomChance mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Trivia") == 0)
{
Trivia mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Stone Paper Scissors")==0)
{
StonePapersScissors mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Jackpot") == 0)
{
coinToss mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Blackjack") == 0)
{
BlackJack mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Android Quiz") == 0)
{
AndroidQuiz mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Cricket") == 0)
{
bookcricket mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Bomb Mine") == 0)
{
hammer mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Luck and Skill") == 0)
{
LuckAndSkill mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Match Pattern") == 0)
{
MatchPattern mini(this);
mini.exec();
return mini.isWin();
}
else if(mini.compare("Whack A Mole") == 0)
{
WhackMole mini(this);
mini.exec();
return mini.isWin();
}
/***** TODO *****/
//else if
//...
//...
return false;
}
void MainWindow::showWin()
{
if(player_turn == _p1) {
showXWin();
}
else {
showOWin();
}
}
void MainWindow::showXWin()
{
ui->t_result->setText(QString("Player 'X' Wins!"));
ui->t_result->setAlignment(Qt::AlignCenter);
}
void MainWindow::showOWin()
{
ui->t_result->setText(QString("Player 'O' Wins!"));
ui->t_result->setAlignment(Qt::AlignCenter);
}
void MainWindow::showTie()
{
ui->t_result->setText(QString("Tie!"));
ui->t_result->setAlignment(Qt::AlignCenter);
}
/**** PRIVATE SLOTS ****/
void MainWindow::on_b_tile_clicked()
{
/*** handle to clicked button ***/
Tile* button = (Tile* )sender();
/*** is this a valid tile to click ***/
if( !button->isEmpty())
return;
/*** play minigame ***/
bool didWinMini = playMini();
/*** Maximum number of turns possible on board ***/
int tileSize=this->board_size*this->board_size;
this->size++;
/*** player won minigame ***/
if(didWinMini) {
button->handleClicked(player_turn);
}
/*** player lost minigame ***/
else {
togglePlayer();
button->handleClicked(player_turn);
togglePlayer();
}
/*** store tile change in backend ***/
resultArray[button->getRow()][button->getCol()]=button->getValue();
/*** win ***/
if(checkWin() == 1) {
if( !didWinMini)
togglePlayer(); // other player won game
showWin();
disableTileClicks();//disable button clicks, can only click end game
this->player_turn = _p1; // X is first at start of every game
return;
}
/*** draw ***/
else if(this->size == tileSize) {
disableTileClicks();
showTie();
this->player_turn = _p1; // X is first at start of every game
return;
}
button->setEnabled(false);
togglePlayer();
/*** AI ***/
if(this->flagAI)
{
while(true)
{
int i=rand()%this->board_size;
int j=rand()%this->board_size;
if(resultArray[i][j]!='X' && resultArray[i][j]!='O')
{
/*** lay AI's choice ***/
this->size++;
tile[i][j]->setValue('O');
tile[i][j]->setEnabled(false);
resultArray[i][j]='O';
/*** win ***/
if(checkWin())
{
showWin();
disableTileClicks(); //disable button clicks, can only click end game
togglePlayer(); //switch turn to human
return;
}
/*** draw ***/
else if(this->size == tileSize)
{
showTie();
disableTileClicks(); //disable button clicks, can only click end game
togglePlayer(); //switch turn to human
return;
}
togglePlayer(); //switch turn to human
return;
}
}
}
}
void MainWindow::on_b_singleplayer_clicked()
{
ui->stackedWidget->setCurrentWidget(ui->w_play);
this->flagAI=1;
configureBoard();
}
void MainWindow::on_b_multiplayer_clicked()
{
ui->stackedWidget->setCurrentWidget(ui->w_play);
this->flagAI=0;
configureBoard();
}
void MainWindow::on_b_main_menu_clicked()
{
ui->stackedWidget->setCurrentWidget(ui->w_main);
}
void MainWindow::on_b_end_game_clicked()
{
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
resultArray[i][j]=' ';
for(int i=0;i<board_size;i++)
for(int j=0;j<board_size;j++)
delete tile[i][j];
ui->stackedWidget->setCurrentWidget(ui->w_main);
}
/***** BACKEND *****/
/*
* Function Description: checkWin()
* Checks for consecutive 'X' or 'O' (matches) in each row, column and diagonal
*
* Returns:
* 1 on success
*/
int MainWindow::checkWin()
{
int n = this->board_size;
/*
* Row Check:
* Check each row for n consecutive 'X' or 'O' and
* return 1 on success
*/
for(int rowCount = 0; rowCount < n; rowCount++) {
int max1 = 0, max2 = 0;
for(int columnCount = 0; columnCount < n; columnCount++) {
if(resultArray[rowCount][columnCount] == 'X')
max1++;
if(resultArray[rowCount][columnCount] == 'O')
max2++;
}
if(max1 == this->board_size || max2 == this->board_size) {
for(int i = 0; i < this->board_size; i++){
tile[rowCount][i]->setHighlight();
}
return 1;
}
}
/*
* Column Check:
* Check each column for n consecutive 'X' or 'O' and
* return 1 on success
*/
for(int rowCount = 0;rowCount < n;rowCount++) {
int max3 = 0, max4 = 0;
for(int columnCount = 0; columnCount < n; columnCount++) {
if(resultArray[columnCount][rowCount] == 'X')
max3++;
if(resultArray[columnCount][rowCount] == 'O')
max4++;
}
if(max3 == this->board_size || max4 == this->board_size) {
for(int i = 0; i < this->board_size; i++) {
tile[i][rowCount]->setHighlight();
}
return 1;
}
}
/*
* Diagonal check1:
* Check the diagonal starting from leftmost top to rightmost bottom tile
*/
int max5 = 0, max6 = 0;
for(int rowColumnCount = 0; rowColumnCount < n; rowColumnCount++) {
if(resultArray[rowColumnCount][rowColumnCount] == 'X')
max5++;
if(resultArray[rowColumnCount][rowColumnCount] == 'O')
max6++;
}
if(max5 == this->board_size || max6 == this->board_size) {
for(int i = 0; i < this->board_size; i++) {
tile[i][i]->setHighlight();
}
return 1;
}
/* Diagonal Check 2:
* Check the diagonal starting from rightmost top to leftmost bottom tile
*/
int max7 = 0, max8 = 0;
for(int rowCount = 0,columnCount = n-1; columnCount >= 0; rowCount++, columnCount--) {
if(resultArray[columnCount][rowCount]=='X')
max7++;
if(resultArray[columnCount][rowCount]=='O')
max8++;
}
if(max7 == this->board_size || max8 == this->board_size) {
for(int i = 0, j = n-1; j >= 0; i++, j--) {
tile[i][j]->setHighlight();
}
return 1;
}
return 0;
}
void MainWindow::on_b_about_clicked()
{
AboutDialog dialog(this);
dialog.exec();
}
|
#include <stdio.h>
#include "shader.h"
GLuint compileShaderFromFile(std::string file, GLenum type) {
FILE *fp = fopen(file.c_str(), "rb");
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buffer = new char[length];
size_t err;
err = fread(buffer, sizeof(char), length, fp);
if ((long)err < length) {
perror("read shader");
}
GLuint shader = compileShader(buffer, length, type);
delete[] buffer;
return shader;
}
GLuint compileShader(char *shaderCode, size_t codeLength, GLenum type) {
GLuint shader;
shader = glCreateShader(type);
GLint shaderCodeLength = codeLength;
glShaderSource(shader, 1, (const GLchar **)&shaderCode, &shaderCodeLength);
glCompileShader(shader);
GLint mStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &mStatus);
if (mStatus == GL_FALSE) {
GLint len;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
GLchar *str = new GLchar[len];
glGetShaderInfoLog(shader, len, NULL, str);
fprintf(stderr, "Failed to compile shader: %s\n", str);
delete[] str;
}
else {
fprintf(stderr, "Failed to compile shader\n");
}
}
return shader;
}
bool linkShaderProgram(GLuint program) {
GLint link_status;
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, (int *)&link_status);
if (link_status == GL_FALSE) {
GLint log_length;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
char *log = (char*)calloc(log_length+1, 1);
glGetProgramInfoLog(program, log_length, &log_length, log);
fprintf(stderr, "shader: %.*s\n", (int)log_length, log);
}
if (link_status == GL_FALSE) {
glDeleteProgram(program);
program = 0;
}
return !!program;
}
|
#ifndef MODULES_WIDGETS_OPWIDGETSTRINGDRAWER
#define MODULES_WIDGETS_OPWIDGETSTRINGDRAWER
#include "modules/widgets/OpWidget.h"
#include "modules/display/vis_dev.h" // VD_TEXT_HIGHLIGHT_TYPE
class OpWidgetStringDrawer
{
public:
OpWidgetStringDrawer();
void Draw(OpWidgetString* widget_string, const OpRect& rect, VisualDevice* vis_dev, UINT32 color);
void Draw(OpWidgetString* widget_string, const OpRect& rect, VisualDevice* vis_dev, UINT32 color,
ELLIPSIS_POSITION ellipsis_position, INT32 x_scroll);
private:
VD_TEXT_HIGHLIGHT_TYPE selection_highlight_type;
INT32 caret_pos;
ELLIPSIS_POSITION ellipsis_position;
BOOL underline;
INT32 x_scroll;
BOOL caret_snap_forward;
BOOL only_text;
public:
VD_TEXT_HIGHLIGHT_TYPE GetSelectionHighlightType() const { return selection_highlight_type; }
void SetSelectionHighlightType(VD_TEXT_HIGHLIGHT_TYPE selection_highlight_type) { this->selection_highlight_type = selection_highlight_type; }
INT32 GetCaretPos() const { return caret_pos; }
void SetCaretPos(INT32 caret_pos) { this->caret_pos = caret_pos; }
ELLIPSIS_POSITION GetEllipsisPosition() const { return ellipsis_position; }
void SetEllipsisPosition(ELLIPSIS_POSITION ellipsis_position) { this->ellipsis_position = ellipsis_position; }
BOOL IsUnderline() const { return underline; }
void SetUnderline(BOOL underline) { this->underline = underline; }
INT32 GetXScroll() const { return x_scroll; }
void SetXScroll(INT32 x_scroll) { this->x_scroll = x_scroll; }
BOOL IsCaretSnapForward() const { return caret_snap_forward; }
void SetCaretSnapForward(BOOL caret_snap_forward) { this->caret_snap_forward = caret_snap_forward; }
BOOL IsOnlyText() const { return only_text; };
void SetOnlyText(BOOL only_text) { this->only_text = only_text; };
};
#endif // MODULES_WIDGETS_OPWIDGETSTRINGDRAWER
|
#ifndef GENERATOR_H
#define GENERATOR_H
#include <QtWidgets>
#include <algorithm>
class Generator : public QObject
{
Q_OBJECT
private:
int** numbers;
int difficulty;
int counter;
QVector<int> variants;
QVector<int> buffer;
QVector<int> wrongVariants;
public:
explicit Generator(QObject *parent = 0);
void recieveDifficulty(int diff);
int startGeneration(int row);
void fillVariants();
int possibleVariant();
void removeVariant(int v);
void removeVariantsForCell(int I, int J);
int oneVariantRemoving();
int rowLastHeroRemoving(int I);
int columnLastHeroRemoving(int J);
void setWrongVariantsForCell(int I, int J);
};
#endif // GENERATOR_H
|
#include "Obj.hh"
#include "Obj2.hh"
int main(int argv, char** args)
{
Obj obj;
Obj2 obj2;
return 0;
}
|
#ifndef PROJETCCLASSVECTOR_H
#define PROJETCCLASSVECTOR_H
#include<iostream>
#include<math.h>
#include<assert.h>
using namespace std;
class Vecteur{
private:
/**Representation des 4 coordonne du vecteur*/
double x;
double y;
double z;
double t;
// What ? C'est Quoi ça???!!
float Vect[3];
int i;
double PS;
public:
/**les constructeurs*/
// Faut pas demander à l'utilisateur d'entrer des trucs ... Sinon
// Si par exemple tu veux faire l'addition de deux vecteurs, eh ben
// Quand t'en crée un nouveau pour renvoyer le résultat, il te demande d'entrer
// Des trucs qui seront jamais utilisés
Vecteur(); //constructeur par defaut
Vecteur(double,double,double,double);//constructeur
// ça, ça ne va pas du tout ...
Vecteur add(Vecteur);//foncrion additionner 2 vect
double ProduitScalaire (Vecteur);
void afficher();
void AffPS();
};
#endif // PROJETC++2(CLASSVECTOR)_H_INCLUDED
|
/* BEGIN LICENSE */
/*****************************************************************************
* SKFind : the SK search engine
* Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr>
* $Id: mux.h,v 1.2.2.4 2005/02/21 14:22:44 krys Exp $
*
* Authors: Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr>
* Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Alternatively you can contact IDM <skcontact @at@ idm> for other license
* contracts concerning parts of the code owned by IDM.
*
*****************************************************************************/
/* END LICENSE */
#ifndef __MUX_H_
#define __MUX_H_
class SKIMuxAncillaryCallback
{
public:
virtual SKERR Compute(PRUint32 iId,
PRUint32* plRanks,
PRBool* plMatch,
void* pResult) = 0;
};
class SKMux
{
public:
SKMux();
~SKMux();
SKERR MuxCursors(SKCursor **ppCursors, PRUint32 iCount,
SKICursorComparator *pComparator,
PRBool *pbInterrupt);
SKERR MuxCursorsWithAncillary(
SKCursor **ppCursors, PRUint32 iCount,
PRUint32 lAncillaryItemSize,
SKIMuxAncillaryCallback* pCallback,
SKICursorComparator *pComparator,
PRBool *pbInterrupt);
SKERR RetrieveData(PRUint32 *piCount, PRUint32 **ppiData)
{
return RetrieveDataWithAncillary(piCount, ppiData, NULL);
}
SKERR RetrieveDataWithAncillary(PRUint32 *piCount, PRUint32 **ppiData,
void** pAncillaryData);
protected:
void InsertIndexWithoutComparator(PRUint32 iIndex);
SKERR InsertIndexWithComparator(PRUint32 iIndex,
SKICursorComparator *pComparator);
const PRUint32 ** m_ppiData;
PRUint32 * m_piCount;
PRUint32 * m_piPosition;
PRUint32 * m_piInputData;
PRUint32 * m_piSortedIndexes;
PRUint32 m_iSortedWidth;
PRUint32 * m_piFinalData;
void* m_pAncillary;
PRUint32 m_iFinalCount;
PRBool* m_pbKept;
};
#else
#error "Multiple inclusions of mux.h"
#endif
|
#pragma once
#include <vector>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <cmath>
#include <Eigen/Dense>
#include <map>
#include <limits>
struct Vertex {
float x;
float y;
float z;
};
struct Face {
int v1;
int v1n;
int v2;
int v2n;
int v3;
int v3n;
};
struct Point {
Eigen::Vector4f world;
Eigen::Vector4f ndc;
Eigen::Vector2i screen;
Eigen::Vector4f normal;
Eigen::Vector3f color;
};
struct Object {
std::string name;
Eigen::Vector3f ambient;
Eigen::Vector3f diffuse;
Eigen::Vector3f specular;
float shine;
std::vector<Vertex> vertices;
std::vector<Eigen::Vector4f> normals;
std::vector<Face> faces;
Eigen::Matrix4f v_transformation;
Eigen::Matrix4f n_transformation;
std::vector<Point> v_trans;
std::vector<Eigen::Vector4f> n_trans;
};
struct Camera {
Eigen::Matrix4f position;
Eigen::Matrix4f orientation;
Eigen::Matrix4f world_to_cam;
};
struct Perspective {
float n;
float f;
float l;
float r;
float t;
float b;
Eigen::Matrix4f projection;
};
struct Light {
Eigen::Vector4f point;
Eigen::Vector3f color;
float attenuation;
};
|
#pragma once
#include <unordered_map>
#include <typeindex>
#include "../../components/interfaces/Component.h"
#include "../../core/modules/interfaces/Module.h"
namespace Game
{
class Component;
class Entity : public Module
{
public:
Entity();
~Entity();
void update() override;
void draw() override;
void start() override;
void stop() override;
void configure() override;
void cleanup() override;
void setId(uint32_t uid);
void addComponent(Component* component);
void removeAndStopComponent(Component* component);
template<class T>
T& getComponent()
{
return static_cast<T&> (*mComponents.find(typeid(T))->second);
}
template<class T>
void removeComponent()
{
auto it = mComponents.find(typeid(T));
removeAndStopComponent(it->second);
mComponents.erase(it);
}
private:
uint32_t mUid;
std::unordered_map<std::type_index, Component* > mComponents;
};
}
|
#ifndef _BOARDCLASS_
#define _BOARDCLASS_
#include <iostream>
#include <array>
#include <cmath>
#include "BoardEnums.hpp"
// * Object that represents a tictactoe board. Now with templates!
template<unsigned long long Size = 3>
class Board
{
private:
std::array<std::array<BoardEnums::SpaceState, Size>, Size> CurrentBoard;
BoardEnums::VictoryState CurrentVictoryStatus;
public:
unsigned long long BoardSize;
BoardEnums::PlayerTurnState Turn;
Board()
{
BoardSize = Size;
CurrentVictoryStatus = BoardEnums::VictoryState::Nobody;
for (int i = 0; i != Size; ++i)
{
for (int j = 0; j != Size; ++j)
{
CurrentBoard[i][j] = BoardEnums::SpaceState::Empty; // Set every space of the CurrentBoard array to SpaceState::Empty
}
}
Turn = BoardEnums::PlayerTurnState::X;
}
// ? Maybe this function could be renamed to something more descriptive.
// NOTE: If this function returns MoveResult::Success, it will change the turn state to the opposite player's turn.
BoardEnums::MoveResult SetSpace(int space) // Takes int from 1 to <Size>. Returns success state of move.
{
if (CurrentVictoryStatus != BoardEnums::VictoryState::Nobody)
return BoardEnums::MoveResult::BoardAlreadyWon;
if (not((space <= Size * Size) and (space >= 1)))
return BoardEnums::MoveResult::MoveOutOfRange;
unsigned long long row = floor((space - 1) / Size); // Convert inputted number to 2d array indexes
unsigned long long col = (space - 1) % Size;
if (CurrentBoard[row][col] != BoardEnums::SpaceState::Empty) // Check if requested space is empty
return BoardEnums::MoveResult::SpaceTaken;
if (Turn == BoardEnums::PlayerTurnState::X) // Set state of space to the player of turn thing uhh how do i write comment
CurrentBoard[row][col] = BoardEnums::SpaceState::X;
else
CurrentBoard[row][col] = BoardEnums::SpaceState::O;
Turn == BoardEnums::PlayerTurnState::X ? Turn = BoardEnums::PlayerTurnState::O : Turn = BoardEnums::PlayerTurnState::X; // Set player turn state to other player
return BoardEnums::MoveResult::Success;
}
// * Just draws the board to the console. Better than manually typing the loop later amirite??? heh heh ehh
void DrawBoard()
{
for (auto i : CurrentBoard)
{
for (auto j : i)
{
switch (j)
{
case BoardEnums::SpaceState::Empty:
std::cout << '_';
break;
case BoardEnums::SpaceState::X:
std::cout << 'X';
break;
case BoardEnums::SpaceState::O:
std::cout << 'O';
break;
default:
std::cout << "This shouldnt happen...";
break;
}
std::cout << ' ';
}
std::cout << std::endl;
}
}
// * Return VictoryState. If victory state is not Board::VictoryState::Nobody, this returns CurrentVictoryStatus without doing any victory check, making this function act like a getter
BoardEnums::VictoryState CheckForVictor()
{
if (CurrentVictoryStatus != BoardEnums::VictoryState::Nobody)
return CurrentVictoryStatus;
// Check for horizontal victory
for (int i = 0; i != Size; ++i)
{
BoardEnums::SpaceState probableVictor = CurrentBoard[i][0];
bool isVictor = true;
for (int j = 0; j != CurrentBoard.size(); ++j)
{
if (CurrentBoard[i][j] != probableVictor)
{
isVictor = false;
break;
}
}
if (isVictor)
{
if (probableVictor == BoardEnums::SpaceState::X)
{
CurrentVictoryStatus = BoardEnums::VictoryState::X;
return BoardEnums::VictoryState::X;
}
else if (probableVictor == BoardEnums::SpaceState::O)
{
CurrentVictoryStatus = BoardEnums::VictoryState::O;
return BoardEnums::VictoryState::O;
}
}
}
// Check for vertical victory
for (int i = 0; i != Size; ++i)
{
BoardEnums::SpaceState probableVictor = CurrentBoard[0][i];
bool isVictor = true;
for (int j = 0; j != CurrentBoard.size(); ++j)
{
if (CurrentBoard[j][i] != probableVictor)
{
isVictor = false;
break;
}
}
if (isVictor)
{
if (probableVictor == BoardEnums::SpaceState::X)
{
CurrentVictoryStatus = BoardEnums::VictoryState::X;
return BoardEnums::VictoryState::X;
}
else if (probableVictor == BoardEnums::SpaceState::O)
{
CurrentVictoryStatus = BoardEnums::VictoryState::O;
return BoardEnums::VictoryState::O;
}
}
}
// * Check for diagonal victory
{
BoardEnums::SpaceState probableVictor = CurrentBoard[0][0];
bool isVictor = true;
for (int i = 0; i != Size; ++i)
{
if (CurrentBoard[i][i] != probableVictor)
{
isVictor = false;
break;
}
}
if (isVictor)
{
if (probableVictor == BoardEnums::SpaceState::X)
{
CurrentVictoryStatus = BoardEnums::VictoryState::X;
return BoardEnums::VictoryState::X;
}
else if (probableVictor == BoardEnums::SpaceState::O)
{
CurrentVictoryStatus = BoardEnums::VictoryState::O;
return BoardEnums::VictoryState::O;
}
}
}
{
BoardEnums::SpaceState probableVictor = CurrentBoard[0][Size-1];
bool isVictor = true;
for (int i = 0, j = Size-1; i != Size; ++i, --j)
{
if (CurrentBoard[i][j] != probableVictor)
{
isVictor = false;
break;
}
}
if (isVictor)
{
if (probableVictor == BoardEnums::SpaceState::X)
{
CurrentVictoryStatus = BoardEnums::VictoryState::X;
return BoardEnums::VictoryState::X;
}
else if (probableVictor == BoardEnums::SpaceState::O)
{
CurrentVictoryStatus = BoardEnums::VictoryState::O;
return BoardEnums::VictoryState::O;
}
}
}
// If no victory condition is met and all spaces are filled, return VictoryState::Draw
{
bool foundEmptySpace = false;
for (int i = 0; i != Size; ++i)
{
for (int j = 0; j != Size; ++j)
{
if (CurrentBoard[i][j] == BoardEnums::SpaceState::Empty)
{
foundEmptySpace = true;
break;
}
}
if (foundEmptySpace)
break;
}
if (not foundEmptySpace)
{
CurrentVictoryStatus = BoardEnums::VictoryState::Draw;
return BoardEnums::VictoryState::Draw;
}
}
return BoardEnums::VictoryState::Nobody;
}
// * Clears the board and sets the turn state to X
void ClearBoard()
{
for (int i = 0; i != Size; ++i)
{
for (int j = 0; j != Size; ++j)
{
CurrentBoard[i][j] = BoardEnums::SpaceState::Empty;
}
}
CurrentVictoryStatus = BoardEnums::VictoryState::Nobody;
Turn = BoardEnums::PlayerTurnState::X;
}
// * Get turn as a string. ONLY USE THIS FOR OUTPUTTING TO THE CONSOLE!
std::string GetTurn()
{
switch (Turn)
{
case BoardEnums::PlayerTurnState::X:
return "X";
break;
case BoardEnums::PlayerTurnState::O:
return "O";
break;
}
return "Error!";
}
// * Simulates a turn and returns the success of the would-be move without modifying the board.
BoardEnums::MoveResult SimulateTurn(int space) // Takes int from 1 to <Size>
{
if (CurrentVictoryStatus != BoardEnums::VictoryState::Nobody)
return BoardEnums::MoveResult::BoardAlreadyWon;
if (not((space <= Size * Size) and (space >= 1)))
return BoardEnums::MoveResult::MoveOutOfRange;
unsigned long long row = floor((space - 1) / Size); // Convert inputted number to 2d array indexes
unsigned long long col = (space - 1) % Size;
if (CurrentBoard[row][col] != BoardEnums::SpaceState::Empty) // Check if requested space is empty
return BoardEnums::MoveResult::SpaceTaken;
return BoardEnums::MoveResult::Success;
}
std::array<std::array<BoardEnums::SpaceState, Size>, Size> GetBoard()
{
return CurrentBoard;
}
};
#endif
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
struct point {
double x,y;
};
point p[1010];
bool vis[1010];
int f[1010];
stack<int> S;
vector<int> v[1010];
double dis(point a,point b) {
double x = a.x - b.x,y = a.y - b.y;
return sqrt(x*x + y*y);
}
int find(int k) {
while (f[k] != k) {
S.push(k);
k = f[k];
}
while (!S.empty()) {
int p = S.top();S.pop();
f[p] = k;
}
return k;
}
int main() {
int n,a,b;double d;char ch;
memset(vis,0,sizeof(vis));
scanf("%d%lf",&n,&d);
for (int i = 1;i <= n; i++) {
scanf("%lf%lf",&p[i].x,&p[i].y);
f[i] = i;
}
for (int i = 1;i <= n; i++)
for (int j = 1;j <= n; j++)
if (i != j && dis(p[i],p[j]) <= d + eps)
v[i].push_back(j);
getchar();
while ((ch = getchar())!= EOF) {
if (ch == 'O') {
scanf("%d",&a);
vis[a] = true;
for (int i = 0;i < v[a].size(); i++)
if (vis[v[a][i]]) {
int da = find(a),db = find(v[a][i]);
f[da] = db;
}
} else {
scanf("%d%d",&a,&b);
a = find(a),b = find(b);
if (a == b) puts("SUCCESS");
else puts("FAIL");
}
getchar();
}
return 0;
}
|
/**************************************************************************************
* File Name : Units.hpp
* Project Name : Keyboard Warriors
* Primary Author : Wonju Cho
* Secondary Author : Doyeong Yi
* Copyright Information :
* "All content 2019 DigiPen (USA) Corporation, all rights reserved."
**************************************************************************************/
#pragma once
#include "Object.h"
class Unit : public Object {
public:
void Initialize(const char* name) noexcept override;
//virtual ~Unit() { std::cout << "Unit destory\n"; }
};
//===Ally==============================================
class Knight : public Unit {
public:
//~Knight() { std::cout << "Knight destory\n"; }
};
class Archer : public Unit {
public:
//~Archer() { std::cout << "Archer destory\n"; }
};
class Magician : public Unit {
public:
//~Magician() { std::cout << "Magician destory\n"; }
};
//===Enemy=============================================
class Skeleton : public Unit {
public:
int GetMoney() { return money; }
private:
int money = 2;
};
class Lich : public Unit {
};
class Golem : public Unit {
};
|
#pragma once
#include "nsphere.h"
#include "polytope.h"
#include "abstractshapeinfo.h"
namespace sbg {
template<int n, typename T>
struct ShapeInfo;
template<int n>
struct ShapeInfo<n, shape::NSphere<n>> : AbstractShapeInfo<n> {
ShapeInfo(const shape::NSphere<n>& sphere);
ShapeInfo(shape::NSphere<n>&& sphere);
Vector<freedom(n), double> getMomentOfInertia(double mass) const override;
Vector<n, double> getCenterOfMass() const override;
shape::NSphere<n> getNSphere() const;
void setNSphere(const shape::NSphere<n>& sphere);
void setNSphere(shape::NSphere<n>&& sphere);
private:
shape::NSphere<n> _sphere;
};
template<> Vector<freedom(2), double> ShapeInfo<2, shape::NSphere<2>>::getMomentOfInertia(double mass) const;
template<> Vector<freedom(3), double> ShapeInfo<3, shape::NSphere<3>>::getMomentOfInertia(double mass) const;
template<int n>
struct ShapeInfo<n, shape::Polytope<n>> : AbstractShapeInfo<n> {
ShapeInfo(const shape::Polytope<n>& polytope);
ShapeInfo(shape::Polytope<n>&& polytope);
Vector<freedom(n), double> getMomentOfInertia(double mass) const override;
Vector<n, double> getCenterOfMass() const override;
shape::Polytope<n> getPolytope() const;
void setPolytope(const shape::Polytope<n>& polytope);
void setPolytope(shape::Polytope<n>&& polytope);
private:
shape::Polytope<n> _polytope;
};
template<> Vector<freedom(2), double> ShapeInfo<2, shape::Polytope<2>>::getMomentOfInertia(double mass) const;
template<> Vector<freedom(3), double> ShapeInfo<3, shape::Polytope<3>>::getMomentOfInertia(double mass) const;
extern template struct ShapeInfo<2, shape::Polytope<2>>;
extern template struct ShapeInfo<2, shape::NSphere<2>>;
extern template struct ShapeInfo<3, shape::Polytope<3>>;
extern template struct ShapeInfo<3, shape::NSphere<3>>;
template<typename T> using Shape2DInfo = ShapeInfo<2, T>;
template<typename T> using Shape3DInfo = ShapeInfo<3, T>;
}
|
class Solution {
public:
bool safe(int i,int j,int n,int m){
if(i<0||j<0||i>=n||j>=m){
return false;
}
return true;
}
int dfs(int i,int j,int n,int m,vector<vector<int>>& dp,vector<vector<int>>& v){
if(!safe(i,j,n,m)) return 0;
if(dp[i][j]!=-1) return dp[i][j];
int a,b,c,d;
if(safe(i+1,j,n,m)&&v[i+1][j]>v[i][j]) a=1+dfs(i+1,j,n,m,dp,v);
else a =1;
if(safe(i-1,j,n,m)&&v[i-1][j]>v[i][j]) b=1+dfs(i-1,j,n,m,dp,v);
else b =1;
if(safe(i,j+1,n,m)&&v[i][j+1]>v[i][j]) c=1+dfs(i,j+1,n,m,dp,v);
else c =1;
if(safe(i,j-1,n,m)&&v[i][j-1]>v[i][j]) d=1+dfs(i,j-1,n,m,dp,v);
else d =1;
return dp[i][j] = max({a,b,c,d});
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
vector<vector<int>> dp(matrix.size(),vector<int> (matrix[0].size(),-1));
int n = matrix.size();
int m = matrix[0].size();
int maxa = 0;
for(int i = 0;i<n;i++){
for(int j=0;j<m;j++){
maxa=max(maxa,dfs(i,j,n,m,dp,matrix));
}
}
return maxa;
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef PROTOBUF_SUPPORT
#include "modules/protobuf/src/protobuf_input_common.h"
#include "modules/protobuf/src/protobuf_data.h"
/*static*/
OP_STATUS
OpProtobufInput::AddBool(BOOL value, OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field)
{
if (field.GetQuantifier() == OpProtobufField::Repeated)
return instance.FieldPtrOpINT32Vector(field_idx)->Add(value);
else
*instance.FieldPtrBOOL(field_idx) = value;
return OpStatus::OK;
}
/*static*/
OP_STATUS
OpProtobufInput::AddString(const uni_char *text, int len, OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field)
{
if (field.GetQuantifier() == OpProtobufField::Repeated)
{
return instance.AddString(field_idx, OpProtobufStringChunkRange(text, len));
}
else
return instance.SetString(field_idx, OpProtobufStringChunkRange(text, len));
}
/*static*/
OP_STATUS
OpProtobufInput::AddString(const OpProtobufDataChunkRange &range, OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field)
{
if (field.GetQuantifier() == OpProtobufField::Repeated)
{
return instance.AddString(field_idx, range);
}
else
{
return instance.SetString(field_idx, range);
}
}
/*static*/
OP_STATUS
OpProtobufInput::AddBytes(const OpProtobufDataChunkRange &range, OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field)
{
if (field.GetQuantifier() == OpProtobufField::Repeated)
{
return instance.AddBytes(field_idx, range);
}
else
{
return instance.SetBytes(field_idx, range);
}
}
/*static*/
OP_STATUS
OpProtobufInput::AddMessage(void *&sub_instance_ptr, OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field)
{
const OpProtobufMessage *sub_message = field.GetMessage();
if (sub_message == NULL)
return OpStatus::ERR;
OpProtobufRepeatedItems *sub_msg_vector_ptr = instance.FieldPtrOpProtobufRepeatedItems(field_idx);
if (sub_msg_vector_ptr == NULL)
return OpStatus::ERR;
OpProtobufMessage::MakeFunc make_sub_msg = sub_message->GetMakeFunction();
if (make_sub_msg == NULL)
return OpStatus::ERR;
OpProtobufMessage::DestroyFunc destroy_sub_msg = sub_message->GetDestroyFunction();
if (destroy_sub_msg == NULL)
return OpStatus::ERR;
sub_instance_ptr = make_sub_msg();
if (sub_instance_ptr == NULL)
return OpStatus::ERR_NO_MEMORY;
OP_STATUS status = sub_msg_vector_ptr->Add(sub_instance_ptr);
if (OpStatus::IsError(status))
{
destroy_sub_msg(sub_instance_ptr);
sub_instance_ptr = NULL;
return status;
}
return OpStatus::OK;
}
/*static*/
OP_STATUS
OpProtobufInput::CreateMessage(void *&sub_instance_ptr, OpProtobufInstanceProxy &instance, int field_idx, const OpProtobufField &field)
{
const OpProtobufMessage *sub_message = field.GetMessage();
if (sub_message == NULL)
return OpStatus::ERR;
void **sub_msg_ptr_ptr = instance.FieldPtrVoidPtr(field_idx);
if (sub_msg_ptr_ptr == NULL)
return OpStatus::ERR;
OpProtobufMessage::MakeFunc make_sub_msg = sub_message->GetMakeFunction();
if (make_sub_msg == NULL)
return OpStatus::ERR;
OpProtobufMessage::DestroyFunc destroy_sub_msg = sub_message->GetDestroyFunction();
if (destroy_sub_msg == NULL)
return OpStatus::ERR;
sub_instance_ptr = make_sub_msg();
if (sub_instance_ptr == NULL)
return OpStatus::ERR_NO_MEMORY;
destroy_sub_msg(*sub_msg_ptr_ptr);
*sub_msg_ptr_ptr = sub_instance_ptr;
return OpStatus::OK;
}
/*static*/
OP_STATUS
OpProtobufInput::IsValid(OpProtobufInstanceProxy &instance, const OpProtobufMessage *message)
{
OP_ASSERT(message != NULL);
if (message == NULL)
return OpStatus::ERR_NULL_POINTER;
if (message->GetOffsetToBitfield() < 0)
return OpStatus::OK; // Cannot determine so we assume everything is ok
const OpProtobufField *fields = message->GetFields();
OpProtobufBitFieldRef has_bits = instance.GetBitfield();
for (int idx = 0; idx < message->GetFieldCount(); ++idx)
{
const OpProtobufField &field = fields[idx];
if (field.GetQuantifier() == OpProtobufField::Required)
{
if (has_bits.IsUnset(idx))
return OpStatus::ERR_PARSING_FAILED;
}
}
return OpStatus::OK;
}
#endif // PROTOBUF_SUPPORT
|
#include "GnSystemPCH.h"
#include "GnDebugAllocator.h"
#ifdef GN_MEMORY_DEBUGGER
GnDebugAllocator::GnDebugAllocator(GnAllocator* actualAllocator, bool writeToLog,
gtuint initialSize, gtuint growBy, bool alwaysValidateAll,bool checkArrayOverruns)
: mActualAlloctor(actualAllocator)
{
}
GnDebugAllocator::~GnDebugAllocator(void)
{
GnExternalDelete mActualAlloctor;
}
void* GnDebugAllocator::Allocate(gsize& sizeInBytes, gsize& alignment,
GnMemoryEventType eventType, bool provideAccurateSizeOnDeallocate, const gchar* pcFile,
int iLine, const gchar* allocateFunction)
{
//gsize stSizeOriginal = sizeInBytes;
//float fTime = GnGetCurrentTimeInSec();
//if( mCheckArrayOverruns )
//{
// sizeInBytes = PadForArrayOverrun(alignment, sizeInBytes);
//}
//fTime = GnGetCurrentTimeInSec() - fTime;
void* memory = mActualAlloctor->Allocate(sizeInBytes, alignment, eventType, provideAccurateSizeOnDeallocate,
pcFile, iLine, allocateFunction);
//#if WIN32
GnAllocUnit unit;
unit.mpMeomry = memory;
unit.mAllocSize = sizeInBytes;
GnStrcpy( unit.maFileName, pcFile, sizeof( unit.maFileName ) );
unit.mFileLine = iLine;
GnStrcpy( unit.maFunctionName, allocateFunction, sizeof( unit.maFunctionName ) );
mpAllocList.insert(std::make_pair(memory, unit));
//#endif //
return memory;
}
void GnDebugAllocator::Deallocate(void* pvMemory, GnMemoryEventType eEventType,
gsize stSizeInBytes)
{
//#if WIN32
mpAllocList.erase(pvMemory);
//#endif //
mActualAlloctor->Deallocate(pvMemory, eEventType, stSizeInBytes);
}
void* GnDebugAllocator::Reallocate(void* pvMemory, gsize& stSizeInBytes,
gsize& stAlignment, GnMemoryEventType eEventType,
bool bProvideAccurateSizeOnDeallocate, gsize stSizeCurrent,
const gchar* pcFile, int iLine, const gchar* pcFunction)
{
return mActualAlloctor->Reallocate(pvMemory, stSizeInBytes, stAlignment, eEventType,
bProvideAccurateSizeOnDeallocate, stSizeCurrent, pcFile, iLine, pcFunction);
}
bool GnDebugAllocator::TrackAllocate(const void* const pvMemory, gsize stSizeInBytes,
GnMemoryEventType eEventType, const gchar* pcFile,
int iLine, const gchar* pcFunction)
{
return true;
}
bool GnDebugAllocator::TrackDeallocate(const void* const pvMemory, GnMemoryEventType eEventType)
{
return true;
}
bool GnDebugAllocator::SetMarker(const char* pcMarkerType, const char* pcClassifier,
const char* pcString)
{
return true;
}
void GnDebugAllocator::Initialize()
{
}
void GnDebugAllocator::Shutdown()
{
//#ifdef WIN32
std::map<void*, GnAllocUnit>::iterator iter = mpAllocList.begin();
while(iter != mpAllocList.end())
{
GnAllocUnit item = iter->second;
GnLogA( "Memory Leak %d : Size = %d, %s %s %d\n" ,
item.mpMeomry,
item.mAllocSize,
item.maFileName,
item.maFunctionName,
item.mFileLine );
++iter;
}
//#endif // WIN32
}
bool GnDebugAllocator::VerifyAddress(const void* pvMemory)
{
return false;
}
gsize GnDebugAllocator::PadForArrayOverrun(gsize stAlignment, gsize stSizeOriginal)
{
return stSizeOriginal + 2 * stAlignment;
}
void GnDebugAllocator::AllocateAssert(const gchar* allocateFunction, gsize ID, gsize size)
{
//// If you hit this NIMEMASSERT, you requested a breakpoint on a specific
//// function name.
//GnAssert(strcmp(ms_pcBreakOnFunctionName, pcFunction) != 0);
//// If you hit this NIMEMASSERT, you requested a breakpoint on a specific
//// allocation ID.
//GnAssert(ms_stBreakOnAllocID != m_stCurrentAllocID);
//// If you hit this NIMEMASSERT, you requested a breakpoint on a specific
//// allocation request size.
//GnAssert(ms_stBreakOnSizeRequested != stSizeOriginal);
}
#endif // #ifdef GN_MEMORY_DEBUGGER
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "adjunct/quick_toolkit/widgets/OpToolTip.h"
#include "modules/pi/OpWindow.h"
#include "modules/pi/OpDragManager.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/pi/OpScreenInfo.h"
#include "modules/dragdrop/dragdrop_manager.h"
#include "adjunct/desktop_util/rtl/uidirection.h"
#include "adjunct/quick/thumbnails/GenericThumbnail.h"
#include "adjunct/quick/thumbnails/TabThumbnailContent.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/menus/DesktopMenuHandler.h"
#include "adjunct/quick/models/DesktopWindowCollection.h"
#include "adjunct/quick/quick-widget-names.h"
#include "modules/widgets/OpMultiEdit.h"
#include "modules/widgets/WidgetContainer.h"
#include "modules/style/css.h"
#include "modules/display/FontAtt.h"
#include "modules/display/styl_man.h"
#include "modules/display/vis_dev.h"
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#include "modules/prefs/prefsmanager/collections/pc_ui.h"
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#include "modules/skin/OpSkinManager.h"
#include "modules/libgogi/pi_impl/mde_opview.h"
#include "adjunct/quick/WindowCommanderProxy.h"
#include "adjunct/quick/managers/AnimationManager.h"
#include "adjunct/quick/windows/BrowserDesktopWindow.h"
#include "adjunct/quick_toolkit/widgets/QuickFlowLayout.h"
#include "adjunct/quick_toolkit/widgets/QuickScrollContainer.h"
#include "adjunct/quick_toolkit/widgets/QuickOpWidgetWrapper.h"
#if defined(_UNIX_DESKTOP_) || defined(MSWIN)
// We need a better interface [espen 2003-03-20]
BOOL IsPanning();
#endif
// when defined, even tooltips without thumbnails will use the skin and not be yellow
#define ALL_TOOLTIPS_SKINABLE
#define MAX_CALLOUT_THUMBNAIL_LAYOUT_WIDTH 800u
#define MAX_CALLOUT_THUMBNAIL_LAYOUT_HEIGHT 600u
#define THUMBNAIL_MINIMUM_WIDTH 120
#define THUMBNAIL_MINIMUM_HEIGHT 90
#define THUMBNAIL_MAXIMUM_WIDTH 256
#define THUMBNAIL_MAXIMUM_HEIGHT 192
TooltipThumbnailEntry::~TooltipThumbnailEntry()
{
if (thumbnail && !thumbnail->IsDeleted())
thumbnail->Delete();
}
// == OpToolTip =============================================
OpToolTipWindow::OpToolTipWindow(OpToolTip *tooltip) :
m_thumbnail_mode(FALSE)
, m_close_on_animation_completion(FALSE)
, m_parent_window(NULL)
, m_tooltip(tooltip)
, m_has_preferred_placement(FALSE)
, m_content(NULL)
, m_edit(NULL)
, m_scroll_container(NULL)
{
}
OpToolTipWindow::~OpToolTipWindow()
{
// may be NULL if Init failed
if (m_widget_container)
m_widget_container->SetWidgetListener(NULL);
m_tooltip->OnTooltipWindowClosing(this);
if (m_parent_window)
m_parent_window->RemoveListener(this);
OP_DELETE(m_scroll_container);
}
void OpToolTipWindow::SetShowThumbnail(BOOL enable)
{
UINT32 i;
for(i = 0; i < m_thumbnails.GetCount(); i++)
{
TooltipThumbnailEntry *entry = m_thumbnails.Get(i);
entry->thumbnail->SetVisibility(enable);
}
m_edit->SetVisibility(!enable);
}
void OpToolTipWindow::OnDesktopWindowClosing(DesktopWindow* desktop_window, BOOL user_initiated)
{
if (desktop_window == m_parent_window)
Close(TRUE);
else
QuickAnimationWindowObject::OnDesktopWindowClosing(desktop_window, user_initiated);
}
OP_STATUS OpToolTipWindow::Init(BOOL thumbnail_mode)
{
m_thumbnail_mode = thumbnail_mode;
if (m_thumbnail_mode)
{
// Linux requires us to get a parent window when using OpWindow::EFFECT_TRANSPARENT.
// Listen to it so we can delete ourself if it happens to be removed when we're still alive.
m_parent_window = g_application->GetActiveBrowserDesktopWindow();
if (m_parent_window)
{
m_parent_window->AddListener(this);
}
}
// TODO: MAKE NAME DEFINE
RETURN_IF_ERROR(DesktopWidgetWindow::Init(TOOLTIP_WINDOW_STYLE, "Tooltip Window", m_parent_window ? m_parent_window->GetOpWindow() : NULL,
NULL, m_thumbnail_mode ? OpWindow::EFFECT_TRANSPARENT : OpWindow::EFFECT_DROPSHADOW));
RETURN_IF_ERROR(OpMultilineEdit::Construct(&m_edit));
m_widget_container->SetWidgetListener(this);
OpWidget *root = m_widget_container->GetRoot();
root->SetHasCssBorder(FALSE);
root->SetCanHaveFocusInPopup(TRUE);
root->SetRTL(UiDirection::Get() == UiDirection::RTL);
m_edit->SetWrapping(m_thumbnail_mode);
m_edit->SetLabelMode();
m_edit->SetName(WIDGET_NAME_TOOLTIP_EDIT);
root->AddChild(m_edit);
if (m_thumbnail_mode)
{
root->GetBorderSkin()->SetImage("Thumbnail Tooltip Skin", "Tooltip Skin");
root->GetForegroundSkin()->SetImage("Thumbnail Tooltip Skin", "Tooltip Skin");
}
else
{
// Regular tooltip
// All platforms should use a real value for OP_SYSTEM_COLOR_TOOLTIP_TEXT, not hardcoded
#if defined(_UNIX_DESKTOP_)
UINT32 color = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TOOLTIP_TEXT);
g_skin_manager->GetTextColor("Tooltip Skin", &color, 0, SKINTYPE_DEFAULT, SKINSIZE_DEFAULT, TRUE);
m_edit->SetForegroundColor(color);
#endif
root->GetBorderSkin()->SetImage("Tooltip Skin", "Edit Skin");
root->GetForegroundSkin()->SetImage("Tooltip Skin", "Edit Skin");
}
#ifndef ALL_TOOLTIPS_SKINABLE
if(!m_thumbnail_mode)
{
m_edit->SetBackgroundColor(g_op_ui_info->GetUICSSColor(CSS_VALUE_InfoBackground));
m_edit->SetForegroundColor(g_op_ui_info->GetUICSSColor(CSS_VALUE_InfoText));
root->SetHasCssBorder(TRUE);
// Required for proper frame on all platforms
m_widget_container->SetEraseBg(TRUE);
#if defined(_MACINTOSH_)
root->SetBackgroundColor(g_op_ui_info->GetUICSSColor(CSS_VALUE_InfoBackground));
#else
root->SetBackgroundColor(OP_RGB(0, 0, 0));
#endif
}
else
#endif // ALL_TOOLTIPS_SKINABLE
{
root->SetHasCssBorder(FALSE);
}
RETURN_IF_ERROR(QuickAnimationWindowObject::Init(NULL, NULL, GetWindow()));
return OpStatus::OK;
}
void OpToolTipWindow::OnAnimationComplete()
{
QuickAnimationWindowObject::OnAnimationComplete();
if (m_close_on_animation_completion)
{
Show(FALSE);
Close(FALSE);
}
}
BOOL OpToolTipWindow::DeleteWidgetFromLayout(QuickWidget *delete_widget)
{
if(!m_content)
return FALSE;
// delete them from the layout
for(UINT32 n = 0; n < m_content->GetWidgetCount(); n++)
{
QuickWidget *widget = m_content->GetWidget(n);
if(widget == delete_widget)
{
m_content->RemoveWidget(n);
return TRUE;
}
}
return FALSE;
}
BOOL OpToolTipWindow::OnInputAction(OpInputAction* action)
{
switch (action->GetAction())
{
case OpInputAction::ACTION_ACTIVATE_GROUP_WINDOW:
{
INT32 id = action->GetActionData();
OP_ASSERT(id);
if(id)
{
UINT32 i;
for(i = 0; i < m_thumbnails.GetCount(); i++)
{
TooltipThumbnailEntry *entry = m_thumbnails.Get(i);
// update the selected state in our layout
entry->thumbnail->SetSelected(entry->group_window_id == id);
}
DesktopWindow* desktop_window = g_application->GetDesktopWindowCollection().GetDesktopWindowByID(id);
if(desktop_window)
{
desktop_window->Activate(TRUE);
}
return TRUE;
}
}
break;
case OpInputAction::ACTION_THUMB_CLOSE_PAGE:
{
INT32 id = action->GetActionData();
OP_ASSERT(id);
if(id)
{
UINT32 i;
for(i = 0; i < m_thumbnails.GetCount(); i++)
{
TooltipThumbnailEntry *entry = m_thumbnails.Get(i);
if(entry->group_window_id == id)
{
DeleteWidgetFromLayout(entry->quickwidget_thumbnail);
m_thumbnails.Delete(i);
UINT32 width = 0, height = 0;
GetRequiredSize(width, height);
// TODO: following code is duplicated in OpTooltip, merge.
if(!m_has_preferred_placement)
{
m_has_preferred_placement = m_tooltip->GetListener()->GetPreferredPlacement(m_tooltip, m_ref_screen_rect, m_placement);
}
OP_ASSERT(m_has_preferred_placement);
OpRect rect = GetPlacement(width, height, this->GetWindow(), GetWidgetContainer(), m_has_preferred_placement, m_ref_screen_rect, m_placement);
BOOL set_preferred_rectangle = TRUE;
if (g_animation_manager->GetEnabled())
{
QuickAnimationWindowObject::reset();
double duration = static_cast<double>(THUMBNAIL_ANIMATION_DURATION);
// Thumbnail was visible, so animate from the old position to the new.
int x, y;
UINT32 w, h;
GetWindow()->GetOuterPos(&x, &y);
GetWindow()->GetOuterSize(&w, &h);
OpRect target_rect(x, y, w, h);
if (!target_rect.Equals(rect))
{
QuickAnimationWindowObject::animateRect(target_rect, rect);
set_preferred_rectangle = FALSE;
if (IsAnimating()) // Give a little extra boost when moving mouse faster.
g_animation_manager->startAnimation(this, ANIM_CURVE_SLOW_DOWN, duration);
else
g_animation_manager->startAnimation(this, ANIM_CURVE_BEZIER, duration);
}
}
if(!m_thumbnails.GetCount())
{
// last tab, close window when animation is done
m_close_on_animation_completion = TRUE;
}
Show(TRUE, set_preferred_rectangle ? &rect : NULL);
OpInputAction* close_action = OP_NEW(OpInputAction, (OpInputAction::ACTION_CLOSE_WINDOW));
if (!close_action)
return TRUE;
close_action->SetActionData(id);
g_input_manager->InvokeAction(close_action);
break;
}
}
}
return TRUE;
}
break;
}
return FALSE;
}
#define MAX_THUMBNAILS_PER_ROW 4
OP_STATUS OpToolTipWindow::RecreateLayout()
{
OpWidget *root = m_widget_container->GetRoot();
// Create the main stack layout, the old m_content is deleted in the SetContent call further down
m_content = OP_NEW(QuickFlowLayout, ());
if(!m_content)
{
return OpStatus::ERR_NO_MEMORY;
}
m_content->KeepRatio(true);
if(!m_scroll_container)
{
m_scroll_container = OP_NEW(QuickScrollContainer, (QuickScrollContainer::VERTICAL, m_thumbnails.GetCount() > 16 ? QuickScrollContainer::SCROLLBAR_AUTO : QuickScrollContainer::SCROLLBAR_NONE));
if(!m_scroll_container)
{
OP_DELETE(m_content);
return OpStatus::ERR_NO_MEMORY;
}
RETURN_IF_ERROR(m_scroll_container->Init());
m_scroll_container->SetRespectScrollbarMargin(false);
m_scroll_container->SetParentOpWidget(root);
}
m_scroll_container->SetContent(m_content); // will delete any previous content
for (UINT32 n = 0; n < m_thumbnails.GetCount(); n++)
{
TooltipThumbnailEntry* entry = m_thumbnails.Get(n);
QuickWidget* widget = QuickWrap(entry->thumbnail);
RETURN_OOM_IF_NULL(widget);
RETURN_IF_ERROR(m_content->InsertWidget(widget));
widget->SetMinimumWidth(THUMBNAIL_MINIMUM_WIDTH);
widget->SetMinimumHeight(THUMBNAIL_MINIMUM_HEIGHT);
entry->quickwidget_thumbnail = widget;
entry->thumbnail->SetSelected(entry->active);
}
m_content->SetMaxBreak(MAX_THUMBNAILS_PER_ROW);
DoLayout();
return OpStatus::OK;
}
// force a layout
void OpToolTipWindow::DoLayout()
{
UINT32 w, h;
m_window->GetOuterSize(&w, &h);
OpRect rect(0, 0, w, h);
m_widget_container->GetRoot()->GetBorderSkin()->AddPadding(rect);
if(m_thumbnails.GetCount())
{
m_scroll_container->Layout(rect);
}
else
{
m_edit->SetRect(rect);
}
}
void OpToolTipWindow::OnResize(UINT32 width, UINT32 height)
{
WidgetWindow::OnResize(width, height);
OpRect rect(0, 0, width, height);
m_widget_container->GetRoot()->GetBorderSkin()->AddPadding(rect);
if(m_thumbnails.GetCount())
{
m_scroll_container->SetScrollbarBehavior(m_thumbnails.GetCount() > 16 ? QuickScrollContainer::SCROLLBAR_AUTO : QuickScrollContainer::SCROLLBAR_NONE);
m_scroll_container->Layout(rect);
}
else
{
m_edit->SetRect(rect);
}
}
void OpToolTipWindow::GetRequiredSize(UINT32& width, UINT32& height)
{
INT32 left, top, right, bottom;
width = height = 0;
if(m_thumbnails.GetCount() && m_scroll_container)
{
width = min(m_scroll_container->GetNominalWidth(), MAX_CALLOUT_THUMBNAIL_LAYOUT_WIDTH);
height = min(m_scroll_container->GetNominalHeight(width), MAX_CALLOUT_THUMBNAIL_LAYOUT_HEIGHT);
}
else
{
OpRect edit_rect = m_edit->GetRect();
if (m_edit->IsWrapping())
{
// Use same width as the thumbnailed mode when wrapping is on.
// We must set it here so the wrapping is done consistently,
// because GetContentWidth depends on it.
width = THUMBNAIL_MAXIMUM_WIDTH;
height = THUMBNAIL_MAXIMUM_HEIGHT;
m_edit->SetRect(OpRect(edit_rect.x, edit_rect.y, width, edit_rect.height));
}
m_edit->GetPadding(&left, &top, &right, &bottom);
width = m_edit->GetMaxBlockWidth() + left + right;
height = m_edit->GetContentHeight() + top + bottom;
if (m_edit->IsWrapping())
{
// Restore edit rect now.
m_edit->SetRect(edit_rect);
}
}
m_widget_container->GetRoot()->GetPadding(&left, &top, &right, &bottom);
width += left + right;
height += top + bottom;
}
void OpToolTipWindow::Update()
{
// Maybe used this instead
// m_edit->SetFont(OP_SYSTEM_FONT_UI_DIALOG);
// m_edit->SetDefaultUIFont(m_edit->font_info.justify); // re-calc height
FontAtt font;
g_pcfontscolors->GetFont(OP_SYSTEM_FONT_UI_TOOLTIP, font);
if (const OpFontInfo *font_info = styleManager->GetFontInfo(font.GetFontNumber()))
{
if (!m_thumbnails.GetCount())
{
const JUSTIFY justify = UiDirection::Get() == UiDirection::LTR ? JUSTIFY_LEFT : JUSTIFY_RIGHT;
m_edit->SetFontInfo(font_info, font.GetSize(), font.GetItalic(), font.GetWeight(), justify);
}
}
if (!m_thumbnail_mode)
{
// Regular tooltip
// All platforms should use a real value for OP_SYSTEM_COLOR_TOOLTIP_TEXT, not hardcoded
#if defined(_UNIX_DESKTOP_)
UINT32 color = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TOOLTIP_TEXT);
g_skin_manager->GetTextColor("Tooltip Skin", &color, 0, SKINTYPE_DEFAULT, SKINSIZE_DEFAULT, TRUE);
m_edit->SetForegroundColor(color);
#endif
}
}
OP_STATUS OpToolTipWindow::CreateThumbnailEntry(TooltipThumbnailEntry **entry, OpToolTipThumbnailPair* entry_pair)
{
OpAutoPtr<TabThumbnailContent> content(OP_NEW(TabThumbnailContent, ()));
RETURN_OOM_IF_NULL(content.get());
RETURN_IF_ERROR(content->Init(*entry_pair));
OpAutoPtr<GenericThumbnail> gen_thumb(OP_NEW(GenericThumbnail, ()));
RETURN_OOM_IF_NULL(gen_thumb.get());
GenericThumbnail::Config thumb_config;
thumb_config.m_title_border_image = "Thumbnail Title Label Skin";
thumb_config.m_close_border_image = "Thumbnail Close Button Skin";
thumb_config.m_close_foreground_image = "Speeddial Close";
thumb_config.m_drag_type = DRAG_TYPE_THUMBNAIL;
RETURN_IF_ERROR(gen_thumb->Init(thumb_config));
RETURN_IF_ERROR(gen_thumb->SetContent(content.release()));
gen_thumb->GetBorderSkin()->SetImage("Thumbnail Widget Skin");
*entry = OP_NEW(TooltipThumbnailEntry, (gen_thumb.get(), entry_pair->is_fixed_image, entry_pair->show_close_button, entry_pair->window_id, entry_pair->active));
RETURN_OOM_IF_NULL(*entry);
gen_thumb.release();
return OpStatus::OK;
}
OP_STATUS OpToolTipWindow::SetThumbnailEntry(UINT32 offset, OpToolTipThumbnailPair* entry_pair)
{
OpWidget *root = m_widget_container->GetRoot();
TooltipThumbnailEntry *entry = m_thumbnails.Get(offset);
if(entry && entry->thumbnail && entry_pair->show_close_button != entry->show_close_button)
{
m_thumbnails.Remove(offset);
RETURN_IF_ERROR(CreateThumbnailEntry(&entry, entry_pair));
OP_STATUS s = m_thumbnails.Insert(offset, entry);
if(OpStatus::IsError(s))
{
OP_DELETE(entry);
return s;
}
root->Relayout();
}
if(!entry)
{
RETURN_IF_ERROR(CreateThumbnailEntry(&entry, entry_pair));
OP_STATUS s = m_thumbnails.Add(entry);
if(OpStatus::IsError(s))
{
OP_DELETE(entry);
return s;
}
}
entry->is_fixed_image = entry_pair->is_fixed_image;
entry->thumbnail->SetEnabled(TRUE);
entry->thumbnail->SetVisibility(m_thumbnail_mode);
// Set Name (for access through scope)
OpString8 name;
if (OpStatus::IsSuccess(name.AppendFormat("Thumbnail %d", offset)))
{
entry->thumbnail->SetName(name.CStr());
}
root->Relayout();
#ifdef _DEBUG
// uni_char buf[1024];
// wsprintf(buf, UNI_L("SetThumbnailEntry(%d), image valid: %s, visible: %s\n"), offset, entry->thumbnail->IsEmpty() ? UNI_L("NO") : UNI_L("YES"), entry->thumbnail->IsVisible() ? UNI_L("YES") : UNI_L("NO"));
// OutputDebugStringW(buf);
#endif
return OpStatus::OK;
}
void OpToolTipWindow::ClearThumbnailEntries(UINT32 max_entries)
{
//#ifdef _DEBUG
// uni_char buf[1024];
// wsprintf(buf, UNI_L("ClearThumbnailEntries(%d)\n"), max_entries);
// OutputDebugStringW(buf);
//#endif
while(m_thumbnails.GetCount() > max_entries)
{
UINT32 offset = m_thumbnails.GetCount() - 1;
DeleteWidgetFromLayout(m_thumbnails.Get(offset)->quickwidget_thumbnail);
m_thumbnails.Delete(offset);
}
}
// == OpToolTip =============================================
OpToolTip::OpToolTip()
: m_thumb_window(NULL)
, m_text_window(NULL)
, m_listener(NULL)
, m_item(0)
, m_thumb_visible(FALSE)
, m_text_visible(FALSE)
, m_timer(NULL)
, m_is_fixed_image(FALSE)
, m_is_sticky(FALSE)
, m_invalidate_thumbnails(FALSE)
, m_show_on_hover(FALSE)
{
}
OpToolTip::~OpToolTip()
{
if (m_timer)
{
m_timer->Stop();
OP_DELETE(m_timer);
}
if (m_thumb_window)
m_thumb_window->Close(TRUE);
if (m_text_window)
m_text_window->Close(TRUE);
}
void OpToolTip::SetListener(OpToolTipListener* listener, uni_char key)
{
BOOL changed = m_listener != listener;
BOOL item_changed = FALSE;
if(m_show_on_hover && m_thumb_window && m_thumb_visible)
{
VisualDevice* visual_device = m_thumb_window->GetWidgetContainer()->GetRoot()->GetVisualDevice();
OpPoint point;
visual_device->GetView()->GetMousePos(&point.x, &point.y);
point.x = visual_device->ScaleToDoc(point.x);
point.y = visual_device->ScaleToDoc(point.y);
OpRect rect = m_thumb_window->GetWidgetContainer()->GetRoot()->GetRect();
// stick means we only allow it to close when the mouse leaves the area
if(key != OP_KEY_ESCAPE && rect.Contains(point))
{
SetSticky(TRUE);
m_thumb_window->SetFocus(FOCUS_REASON_OTHER);
return;
}
else
{
m_thumb_window->GetWidgetContainer()->GetRoot()->ReleaseFocus(FOCUS_REASON_OTHER);
SetSticky(FALSE);
}
}
m_listener = listener;
m_show_on_hover = listener && listener->CanHoverToolTip();
if (m_listener)
{
INT32 new_item = listener->GetToolTipItem(this);
item_changed = new_item != m_item;
changed = changed || abs(new_item - m_item) == 1;
m_item = new_item;
}
else
{
m_item = 0;
}
if (!m_listener)
{
Hide();
m_timer->Stop();
}
else
{
BOOL fast_change = changed && (m_thumb_visible || m_text_visible) && listener->HasToolTipText(this);
UINT32 delay = 0;
if(changed)
{
m_thumbnail_collection.DeleteAll();
if(m_listener->GetToolTipType(this) == OpToolTipListener::TOOLTIP_TYPE_MULTIPLE_THUMBNAILS)
{
m_listener->GetToolTipThumbnailCollection(this, m_thumbnail_collection);
if(!m_thumbnail_collection.GetCount())
{
Hide();
return;
}
}
//#ifdef _DEBUG
// uni_char buf[1024];
// wsprintf(buf, UNI_L("Invalidating thumbnails, listener: %08x, listener type: %d\n"), listener, listener->GetToolTipType(this));
// OutputDebugStringW(buf);
//#endif
m_invalidate_thumbnails = TRUE;
}
BOOL direct_hide = TRUE;
if (fast_change)
{
// Find out if the switch is from thumbnail to text.
// If it is, we don't want a fast change, and we don't want
// to hide the thumbnail immediately either.
if (m_thumb_visible && m_listener->GetToolTipType(this) == OpToolTipListener::TOOLTIP_TYPE_NORMAL)
{
fast_change = FALSE;
direct_hide = FALSE;
// Get the delay here without the image set since it's affected by having a image set or not.
Image old_image = m_image;
m_image.Empty();
delay = listener->GetToolTipDelay(this);
m_image = old_image;
}
}
if (fast_change)
{
Show();
}
else if ((!m_thumb_visible && !m_text_visible) || changed || item_changed)
{
if ((changed || item_changed) && direct_hide)
{
Hide();
}
m_timer->Stop();
if (listener->HasToolTipText(this))
{
m_timer->Start(delay ? delay : listener->GetToolTipDelay(this));
}
}
}
}
OP_STATUS OpToolTip::Init()
{
m_timer = OP_NEW(OpTimer, ());
if (!m_timer)
return OpStatus::ERR;
m_timer->SetTimerListener(this);
return OpStatus::OK;
}
void OpToolTip::OnTooltipWindowClosing(OpToolTipWindow *window)
{
if (window == m_thumb_window)
m_thumb_window = NULL;
else if (window == m_text_window)
m_text_window = NULL;
}
#define VERTICAL_OFFSET 21
OpRect GetPlacement(int width, int height, OpWindow *window, WidgetContainer* widget_container,
BOOL has_preferred_placement, const OpRect &ref_screen_rect,
OpToolTipListener::PREFERRED_PLACEMENT placement)
{
OpPoint screen_pos;
widget_container->GetView()->GetMousePos(&screen_pos.x, &screen_pos.y);
screen_pos = widget_container->GetView()->ConvertToScreen(screen_pos);
screen_pos.y += VERTICAL_OFFSET;
OpRect rect(screen_pos.x, screen_pos.y, width, height);
widget_container->GetRoot()->GetBorderSkin()->GetArrow()->Reset();
if (has_preferred_placement)
{
INT32 margin_left, margin_top, margin_right, margin_bottom;
widget_container->GetRoot()->GetBorderSkin()->GetMargin(&margin_left, &margin_top, &margin_right, &margin_bottom);
widget_container->GetRoot()->GetBorderSkin()->GetArrow()->SetOffset(50);
OpScreenProperties screen_props;
g_op_screen_info->GetProperties(&screen_props, window, &screen_pos);
OpRect screen(screen_props.screen_rect);
// Thumbnails can be clipped if there is no external compositing
DesktopWindow* dw = g_application->GetActiveDesktopWindow(TRUE);
if (dw && !dw->SupportsExternalCompositing())
{
dw->GetInnerPos(screen.x, screen.y);
dw->GetInnerSize((UINT32&)screen.width, (UINT32&)screen.height);
INT32 top, ignore;
dw->GetOpWindow()->GetMargin(&ignore, &top, &ignore, &ignore);
screen.height += top;
screen.IntersectWith(screen_props.workspace_rect);
}
int attempt = 0;
while (attempt++ < 2)
{
switch (placement)
{
case OpToolTipListener::PREFERRED_PLACEMENT_RIGHT:
rect.x = ref_screen_rect.x + ref_screen_rect.width;
rect.y = ref_screen_rect.y + (ref_screen_rect.height - rect.height) / 2;
widget_container->GetRoot()->GetBorderSkin()->GetArrow()->SetLeft();
rect.x += margin_left;
break;
case OpToolTipListener::PREFERRED_PLACEMENT_BOTTOM:
rect.x = ref_screen_rect.x + (ref_screen_rect.width - rect.width) / 2;
rect.y = ref_screen_rect.y + ref_screen_rect.height;
widget_container->GetRoot()->GetBorderSkin()->GetArrow()->SetTop();
rect.y += margin_top;
break;
case OpToolTipListener::PREFERRED_PLACEMENT_LEFT:
rect.x = ref_screen_rect.x - rect.width;
rect.y = ref_screen_rect.y + (ref_screen_rect.height - rect.height) / 2;
widget_container->GetRoot()->GetBorderSkin()->GetArrow()->SetRight();
rect.x -= margin_right;
break;
case OpToolTipListener::PREFERRED_PLACEMENT_TOP:
rect.x = ref_screen_rect.x + (ref_screen_rect.width - rect.width) / 2;
rect.y = ref_screen_rect.y - rect.height;
widget_container->GetRoot()->GetBorderSkin()->GetArrow()->SetBottom();
rect.y -= margin_bottom;
break;
default:
OP_ASSERT(!"Unknown placement");
}
// If outside, try again using the opposite side
//if (screen.Contains(rect))
// break;
if ((placement == OpToolTipListener::PREFERRED_PLACEMENT_LEFT ||
placement == OpToolTipListener::PREFERRED_PLACEMENT_RIGHT) &&
rect.x >= screen.x &&
rect.x < screen.x + screen.width - rect.width)
break;
if ((placement == OpToolTipListener::PREFERRED_PLACEMENT_TOP ||
placement == OpToolTipListener::PREFERRED_PLACEMENT_BOTTOM) &&
rect.y >= screen.y &&
rect.y < screen.y + screen.height - rect.height)
break;
switch (placement)
{
case OpToolTipListener::PREFERRED_PLACEMENT_LEFT:
placement = OpToolTipListener::PREFERRED_PLACEMENT_RIGHT; break;
case OpToolTipListener::PREFERRED_PLACEMENT_TOP:
placement = OpToolTipListener::PREFERRED_PLACEMENT_BOTTOM; break;
case OpToolTipListener::PREFERRED_PLACEMENT_RIGHT:
placement = OpToolTipListener::PREFERRED_PLACEMENT_LEFT; break;
case OpToolTipListener::PREFERRED_PLACEMENT_BOTTOM:
placement = OpToolTipListener::PREFERRED_PLACEMENT_TOP; break;
default:
OP_ASSERT(!"Unknown placement");
}
}
// Adjust the rect so it really is inside the screen.
rect.x = MAX(rect.x, screen.x);
rect.x = MIN(rect.x, screen.x + screen.width - rect.width);
rect.y = MAX(rect.y, screen.y);
rect.y = MIN(rect.y, screen.y + screen.height - rect.height);
if(placement == OpToolTipListener::PREFERRED_PLACEMENT_TOP ||
placement == OpToolTipListener::PREFERRED_PLACEMENT_BOTTOM)
{
// center the arrow on the tab associated with the tooltip. We don't need this for tabs on the sides, though.
OpWidgetImage * skin = widget_container->GetRoot()->GetBorderSkin();
OpSkinElement * skinelm = skin->GetSkinElement();
SkinArrow * arrow = skin->GetArrow();
double pos0 = rect.x;
double pos100 = rect.x + rect.width;
if (skinelm)
{
UINT8 border_left, border_top, border_right, border_bottom;
if (OpStatus::IsSuccess(skinelm->GetStretchBorder(&border_left, &border_top, &border_right, &border_bottom, 0)))
{
pos0 += border_left;
pos100 -= border_right;
};
INT32 arrow_width, arrow_height;
if (OpStatus::IsSuccess(skinelm->GetArrowSize(*arrow, &arrow_width, &arrow_height, 0)))
{
pos0 += arrow_width/2;
pos100 -= arrow_width/2;
};
};
double offset_pixels = ref_screen_rect.x + ref_screen_rect.width / 2.0 - pos0;
double offset_ratio = offset_pixels / (pos100-pos0);
arrow->SetOffset((int)(offset_ratio * 100.0));
}
}
else
{
if (UiDirection::Get() == UiDirection::RTL)
rect.x -= rect.width;
// Keep inside screen edges
OpScreenProperties screen_props;
g_op_screen_info->GetProperties(&screen_props, window, &screen_pos);
const OpRect screen = screen_props.screen_rect;
rect.x = MAX(rect.x, screen.x);
if (rect.Right() > screen.Right())
{
rect.x = MAX(screen.Right() - rect.width, screen.x);
}
if (rect.Right() > screen.Right())
{
rect.width = screen.width;
}
if (rect.y + rect.height > screen.y + screen.height)
{
rect.y = rect.y - rect.height - VERTICAL_OFFSET - 8;
}
if (rect.y < screen.y)
{
rect.y = screen.y;
if (rect.x < screen_pos.x)
{
rect.x = screen_pos.x - rect.width - VERTICAL_OFFSET;
}
else
{
rect.x += VERTICAL_OFFSET;
}
}
}
return rect;
}
void OpToolTip::Show()
{
#if defined(_UNIX_DESKTOP_) || defined(MSWIN)
if( IsPanning() )
{
Hide();
return;
}
#endif
m_image.Empty();
m_additional_text.Empty();
if (!m_listener || !m_listener->HasToolTipText(this) || g_application->GetMenuHandler()->IsShowingMenu())
{
Hide();
return;
}
#ifdef DRAG_SUPPORT
if (g_drag_manager->IsDragging() && !m_listener->GetShowWhileDragging(this))
{
// Something is being dragged and the tooltip is not intended to be shown while dragging
Hide();
return;
}
#endif
OpInfoText text;
OpToolTipListener::TOOLTIP_TYPE type = m_listener->GetToolTipType(this);
BOOL show_thumb_win = (type == OpToolTipListener::TOOLTIP_TYPE_THUMBNAIL || type == OpToolTipListener::TOOLTIP_TYPE_MULTIPLE_THUMBNAILS);
BOOL show_text_win = !show_thumb_win;
m_listener->GetToolTipText(this, text);
if (!text.HasTooltipText())
{
Hide();
return;
}
m_title.Empty();
m_url_string.Empty();
m_url = URL();
m_listener->GetToolTipThumbnailText(this, m_title, m_url_string, m_url);
if (m_text_visible && text.GetTooltipText().Compare(m_text.GetTooltipText()) == 0)
{
if (m_listener->GetToolTipUpdateDelay(this))
{
m_timer->Start(m_listener->GetToolTipUpdateDelay(this));
}
return;
}
if (show_thumb_win && m_title.IsEmpty())
{
// We want title or nothing in the new style tooltips. DSK-300793.
Hide();
return;
}
m_text.Copy(text);
// Set up tooltip window
if (!m_additional_text.IsEmpty())
show_text_win = TRUE;
// If we're switching to thumbnail tooltip we should hide the text tooltip, or the other way around.
if (show_text_win && m_thumb_visible)
Hide(FALSE, TRUE);
if (show_thumb_win && m_text_visible)
Hide(TRUE, FALSE);
// Create text tooltip if that's what we want
if (!m_text_window && show_text_win)
{
m_text_window = OP_NEW(OpToolTipWindow, (this));
if (!m_text_window || OpStatus::IsError(m_text_window->Init(FALSE)))
{
OP_DELETE(m_text_window);
m_text_window = NULL;
return;
}
}
// Create thumbnail tooltip if that's what we want
if (!m_thumb_window && show_thumb_win)
{
m_thumb_window = OP_NEW(OpToolTipWindow, (this));
if (!m_thumb_window || OpStatus::IsError(m_thumb_window->Init(TRUE)))
{
OP_DELETE(m_thumb_window);
m_thumb_window = NULL;
return;
}
m_invalidate_thumbnails = TRUE;
}
OpRect ref_screen_rect;
OpToolTipListener::PREFERRED_PLACEMENT placement;
BOOL has_preferred_placement = m_listener->GetPreferredPlacement(this, ref_screen_rect, placement);
if(show_thumb_win)
{
m_thumb_window->Update();
BOOL show_thumb = m_thumbnail_collection.GetCount() || (!m_image.IsEmpty() && !m_listener->GetHideThumbnail(this));
m_thumb_window->SetShowThumbnail(show_thumb);
if (show_thumb)
{
if(m_invalidate_thumbnails)
{
m_thumb_window->ClearThumbnailEntries(0); // m_thumbnail_collection.GetCount() ? m_thumbnail_collection.GetCount() : 1);
if(m_thumbnail_collection.GetCount())
{
for(UINT32 index = 0; index < m_thumbnail_collection.GetCount(); index++)
{
OpToolTipThumbnailPair *entry = m_thumbnail_collection.Get(index);
m_thumb_window->SetThumbnailEntry(index, entry);
}
}
else if(!m_image.IsEmpty())
{
OpToolTipThumbnailPair entry;
entry.window_id = m_listener->GetToolTipWindowID();
entry.can_activate_button = TRUE;
entry.thumbnail = m_image;
entry.is_fixed_image = m_is_fixed_image;
entry.title.Set(m_title.CStr());
m_thumb_window->SetThumbnailEntry(0, &entry);
}
OpStatus::Ignore(m_thumb_window->RecreateLayout());
m_invalidate_thumbnails = FALSE;
//#ifdef _DEBUG
// uni_char buf[1024];
// wsprintf(buf, UNI_L("Recreating layout, thumbnail count: %d\n"), m_thumbnail_collection.GetCount());
// OutputDebugStringW(buf);
//#endif
}
}
else
{
// We must set text alignment to left here, so the required width
// is calculated consistently below.
m_thumb_window->ClearThumbnailEntries(0);
m_thumb_window->m_edit->SetJustify(JUSTIFY_LEFT, FALSE);
m_thumb_window->m_edit->SetText(m_title.CStr());
OpStatus::Ignore(m_thumb_window->RecreateLayout());
m_invalidate_thumbnails = FALSE;
}
UINT32 width = 0, height = 0;
m_thumb_window->GetRequiredSize(width, height);
OpScreenProperties sp;
g_op_screen_info->GetProperties(&sp, m_thumb_window->GetWindow());
width = min(width, sp.width);
height = min(height, sp.height);
if (!show_thumb)
{
// Must be done after GetRequiredSize
m_thumb_window->m_edit->SetJustify(JUSTIFY_CENTER, FALSE);
}
OpRect rect = GetPlacement(width, height, m_thumb_window->GetWindow(), m_thumb_window->GetWidgetContainer(), has_preferred_placement, ref_screen_rect, placement);
BOOL set_preferred_rectangle = TRUE;
if (g_animation_manager->GetEnabled())
{
m_thumb_window->reset();
if (!m_thumb_visible && m_thumb_window->IsAnimating())
{
m_thumb_visible = TRUE;
//m_thumb_window->animateOpacity(0.0, 1.0);
}
if (m_thumb_visible)
{
double duration = static_cast<double>(THUMBNAIL_ANIMATION_DURATION);
// Thumbnail was visible, so animate from the old position to the new.
int x, y;
UINT32 w, h;
m_thumb_window->GetWindow()->GetOuterPos(&x, &y);
m_thumb_window->GetWindow()->GetOuterSize(&w, &h);
OpRect target_rect(x, y, w, h);
if (target_rect.IsEmpty())
{
// sometimes the start rect is empty for some reason, so just fade in then
m_thumb_visible = FALSE;
// Fade in
m_thumb_window->animateOpacity(0.0, 1.0);
g_animation_manager->startAnimation(m_thumb_window, ANIM_CURVE_LINEAR);
}
else if(!target_rect.Equals(rect))
{
m_thumb_window->animateRect(target_rect, rect);
set_preferred_rectangle = FALSE;
if (m_thumb_window->IsAnimating()) // Give a little extra boost when moving mouse faster.
g_animation_manager->startAnimation(m_thumb_window, ANIM_CURVE_SLOW_DOWN, duration);
else
g_animation_manager->startAnimation(m_thumb_window, ANIM_CURVE_BEZIER, duration);
}
}
else
{
// Fade in
m_thumb_window->animateOpacity(0.0, 1.0);
g_animation_manager->startAnimation(m_thumb_window, ANIM_CURVE_LINEAR);
}
}
m_thumb_window->Show(TRUE, set_preferred_rectangle ? &rect : NULL);
m_thumb_visible = TRUE;
// If the text window should also be shown, update the placement so it's relative to the thumb window.
ref_screen_rect = rect;
if (placement != OpToolTipListener::PREFERRED_PLACEMENT_TOP)
placement = OpToolTipListener::PREFERRED_PLACEMENT_BOTTOM;
}
if (m_text_window && show_text_win)
{
m_text_window->Update();
//calculate the required size of the tooltip
if (!m_additional_text.IsEmpty())
m_text_window->m_edit->SetText(m_additional_text.CStr());
else
m_text_window->m_edit->SetText(m_text.GetTooltipText().CStr());
UINT32 width, height;
m_text_window->GetRequiredSize(width, height);
OpRect rect = GetPlacement(width, height, m_text_window->GetWindow(), m_text_window->GetWidgetContainer(), has_preferred_placement, ref_screen_rect, placement);
if (g_pcui->GetIntegerPref(PrefsCollectionUI::PopupButtonHelp))
{
m_text_window->Show(TRUE, &rect);
}
m_text_visible = TRUE;
}
if(!m_listener)
{
Hide();
return;
}
if(m_listener->GetToolTipUpdateDelay(this))
{
m_timer->Start(m_listener->GetToolTipUpdateDelay(this));
}
}
void OpToolTip::Hide(BOOL hide_text_tooltip, BOOL hide_thumb_tooltip)
{
SetSticky(FALSE);
if (m_thumb_window && m_thumb_visible && hide_thumb_tooltip)
{
if (g_animation_manager->GetEnabled())
{
m_thumb_window->reset();
m_thumb_window->animateOpacity(1.0, 0.0);
//m_thumb_window->animateHideWhenCompleted(TRUE);
//g_animation_manager->startAnimation(m_thumb_window, ANIM_CURVE_LINEAR);
//Fade out and destroy. A new instance will be created & faded in when needed
m_thumb_window->m_close_on_animation_completion = TRUE;
g_animation_manager->startAnimation(m_thumb_window, ANIM_CURVE_LINEAR);
m_thumb_window = NULL;
}
else
m_thumb_window->Show(FALSE);
m_thumb_visible = FALSE;
}
if (m_text_window && m_text_visible && hide_text_tooltip)
{
m_text_window->Show(FALSE);
m_text_visible = FALSE;
}
}
void OpToolTip::OnTimeOut(OpTimer* timer)
{
if (timer == m_timer)
Show();
}
void OpToolTip::SetImage(Image image, BOOL fixed_image)
{
m_image = image;
m_is_fixed_image = fixed_image;
if(m_thumb_window && m_thumbnail_collection.GetCount() < 2)
{
OpToolTipThumbnailPair entry;
entry.thumbnail = m_image;
entry.is_fixed_image = fixed_image;
entry.title.Set(m_title.CStr());
m_thumb_window->ClearThumbnailEntries(1);
m_thumb_window->SetThumbnailEntry(0, &entry);
}
}
void OpToolTip::UrlChanged()
{
if (m_thumb_visible || m_text_visible)
{
Hide();
Show();
}
}
void OpToolTipWindow::OnMouseMove(const OpPoint &point)
{
}
void OpToolTipWindow::OnMouseLeave()
{
if(m_tooltip->IsSticky())
{
m_tooltip->SetSticky(FALSE);
}
}
|
/*
2016年4月26日19:45:25
#1050 : 树中的最长路
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
上回说到,小Ho得到了一棵二叉树玩具,这个玩具是由小球和木棍连接起来的,而在拆拼它的过程中,小Ho发现他不仅仅可以拼凑成一棵二叉树!还可以拼凑成一棵多叉树——好吧,其实就是更为平常的树而已。
但是不管怎么说,小Ho喜爱的玩具又升级换代了,于是他更加爱不释手(其实说起来小球和木棍有什么好玩的是吧= =)。小Ho手中的这棵玩具树现在由N个小球和N-1根木棍拼凑而成,这N个小球都被小Ho标上了不同的数字,并且这些数字都是出于1..N的范围之内,每根木棍都连接着两个不同的小球,并且保证任意两个小球间都不存在两条不同的路径可以互相到达。总而言之,是一个相当好玩的玩具啦!
但是小Hi瞧见小Ho这个样子,觉得他这样沉迷其中并不是一件好事,于是寻思着再找点问题让他来思考思考——不过以小Hi的水准,自然是手到擒来啦!
于是这天食过早饭后,小Hi便对着又拿着树玩具玩的不亦乐乎的小Ho道:“你说你天天玩这个东西,我就问你一个问题,看看你可否知道?”
“不好!”小Ho想都不想的拒绝了。
“那你就继续玩吧,一会回国的时候我不叫上你了~”小Hi严肃道。
“诶!别别别,你说你说,我听着呢。”一向习惯于开启跟随模式的小Ho忍不住了,马上喊道。
小Hi满意的点了点头,随即说道:“这才对嘛,我的问题很简单,就是——你这棵树中哪两个结点之间的距离最长?当然,这里的距离是指从一个结点走到另一个结点经过的木棍数。”。
“啊?”小Ho低头看了看手里的玩具树,困惑了。
提示一:路总有折点,路径也不例外!
×Close
提示一:路总有折点,路径也不例外!
小Ho为了能够回国也是很拼,但是一连思考了几天却仍然毫无结果,虽然仍然是在折腾自己的树玩具,但是却没有了那种单纯的快乐……小Ho无奈之下,只得乖乖去请教小Hi。
小Hi仿佛早就知道这个死脑筋不知道什么叫举一反三的同伴即将到来,马上递上了一张画着小Ho树玩具千千万万种形态中的一种。
“你且看看这棵树。”小Hi道:“你可知道这棵树里的最长路是哪一条么?”
“唔……应该是6-4-2-1-3这一条吧,它的长度是4。”这个图的结点数并不多,小Ho一眼便看了出来。
“那好,那么接下来我们把你的这棵树画成更像树一点,比如——给它指定一个根节点(注意啦!这里的根节点的意义指的是整棵树的根节点,而后文中出现的一些根结点的意思是这棵有根树中某棵子树的根节点,并不是说将这棵树另外指定一个根节点并且重新绘制!!),不如就1号结点把~”小Hi愉快的又画了一张图,递给了小Ho。
“好的……不过这,说明了什么?”小Ho摸不着头脑。
“你看这条最长路,是否在1号结点这里转折了一下?”小Hi问道。
“是啊,但是这不能说明什么吧?如果我以5号结点为整棵树的根节点重新绘制,那么这条最长路并不会在5号结点这里转折一下啊?”小Ho更加犯迷糊了。
“不不不,我不是想说在根节点转折——最长路当然不会经过每一个根结点啦,不然那不就是经过每一个结点了。我想说的是转折点存在的这个事实!”
“但是,如果我以3号结点为整棵树的根结点的话,那么就没有转折吧!”小Ho发现了一个盲点。
“你以为你是华生啊!还盲点呢!这种情况下,肯定是因为3号结点有且仅有一个子结点——不然这就和最长路矛盾了,这种时候我们可以视作它还有一个子结点——也就是它本身,不过它到这个子结点的距离就是0而已~”小Hi努力的圆话。
“如果你要这么说的话……好吧,我承认这个转折点的存在,所以呢?”
“既然你接受了这个设定,那么想来应该就会发现——如果设最长路的转折点为t,以t为根结点的子树中深度最深的叶子结点为l,以t为根结点的子树中不与l在t的同一棵子树中且深度最深的叶子结点为l2,那么最长路的长度就等于以t为根结点的子树中l的深度与l2的深度之和!”小Hi解释道。
“等等……你说太快了,我没能理解!”小Ho跟不上节奏了。
“你看……这个图中,以1号结点为根结点的子树中最深的叶子节点是6号结点是吧。”
“没错,我还知道,这棵树中不与6号结点在一棵子树中而且深度最深的结点就是3号结点,的确这样算出来就会是最长路,但是有没有可能这只是一个特例呢?”小Ho反问道。
“好的,我来证明给你看吧,我们要找的答案其实就是2个点l'和l2',这两个结点便是最长路的两个端点是不是?”小Hi整理了下思路,说道。
“没错,我想想,你说的‘转折点’其实就是这两个结点的最近公共祖先对不对?”小Ho问道。
“反应很快嘛,那么如果我知道了这个转折点——不妨也就设为t,我该如何求l'和l2'呢?”小Hi继续问道。
“也就是说我要找到t这棵子树中的两个结点l'和l2',使得dist(t, l') + dist(t, l2')——dist(a, b)表示结点a和结点b的距离,尽可能的大?”
“是的,并且我认为这两个结点会是以t为根结点的子树中深度最深的叶子结点l和以t为根结点的子树中不与l在t的同一棵子树中且深度最深的叶子结点l2。”小Hi道。
小Hi喝了口水,继续道:“我要想证明的结论是这样的——对于任意以t为根结点的子树中的两个结点l'和l2'(当然它们与t的连接路径上不能存在重合),一定满足dist(t, l')+dist(t, l2')<=dist(t, l)+dist(t, l2)。如果这个结论得到了证明,就意味着l和l2之间的路一定是最长路,或者说,不会有其它两个结点之间的距离比l和l2之间的距离更长了。”。
“并且这个证明非常简单——分情况讨论即可,如果l和l'在t的同一棵子树中,那么l2',l2肯定都不在这棵子树中——不然路径会发生重合,那么根据l,l',l2,l2'的定义,一定有dist(t, l)>=dist(t, l'),dist(t, l2)>=dist(t, l2'),于是我所想要的结论便得到了证明。”
“而如果l和l2'在t的同一棵子树中的话,这种情况就会和之前的那种一样。”
“那么接下来只有一种可能——l和l'不在t的同一棵子树中同时l和l2'不在t的同一棵子树中,首先我们可以知道dist(t, l)>=dist(t, l2),不然就与l与l2的定义矛盾了。其次我们知道dist(t, l2)>=dist(t, l'), dist(t, l2)>=dist(t, l2')——不然就与l2的定义矛盾了,那么显然便有dist(t, l')+dist(t, l2')<=dist(t, l2)+dist(t, l2)<=dist(t, l)+dist(t, l2)——也就是我们之前的结论得到了证明。”小Hi说到这里,抹了把汗,停下来看向小Ho。
“等……等……让我自己好好想想……”小Ho晕晕的拿出了纸币,自己演算了会,终于抬起头道:“没错,如果我知道了这个转折点t,那么我就可以用这样的方式找出最长路的两个端点来。”
小Ho言罢又想了想,继续问道:“那么我该怎么知道t是哪一个点呢?”
“好问题!而这个问题的答案是——枚举!”小Hi答道。
“枚举?”
“没错,我枚举每一个点作为转折点t,求出以t为根节点的子树中的‘最长路’以及与‘最长路’不重合的‘次长路’,用这两条路的长度之和去更新答案,那么最终的答案就是这棵树的最长路长度了!”小Hi道。
“但是……你这样做难道不是O(N^2)的复杂度么?”小Ho忍不住问道:“数据范围可是10^6啊!怎么可能算得出来。”
小Hi点了点头,答道:“所以就要利用一种神奇的性质了——如果我用first(t),second(t)分别表示以t为根节点的子树中最长路和次长路的长度,那么我只需要求出t的所有子结点的first值,first(t)便是这些first值中的最大值+1,second(t)便是这些first值中的次大值+1.”
“原来是这样,也就是说我只要以类似后序遍历的方式依次访问每个结点,从下往上依次计算每个结点的first值和second值,我就能够用O(N)的时间复杂度来解决这个问题咯!”
“是的呢!所以快去写程序吧~~”
输入
每个测试点(输入文件)有且仅有一组测试数据。
每组测试数据的第一行为一个整数N,意义如前文所述。
每组测试数据的第2~N行,每行分别描述一根木棍,其中第i+1行为两个整数Ai,Bi,表示第i根木棍连接的两个小球的编号。
对于20%的数据,满足N<=10。
对于50%的数据,满足N<=10^3。
对于100%的数据,满足N<=10^5,1<=Ai<=N, 1<=Bi<=N
小Hi的Tip:那些用数组存储树边的记得要开两倍大小哦!
输出
对于每组测试数据,输出一个整数Ans,表示给出的这棵树中距离最远的两个结点之间相隔的距离。
样例输入8
1 2
1 3
1 4
4 5
3 6
6 7
7 8
样例输出6
*/
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::cin;
using std::endl;
#define MAX_N 100005
vector<vector<int>> tree(MAX_N);
vector<int> first(MAX_N), second(MAX_N);//默认构造函数会默认都初始化为0
int longest = 0;
void dfs(int thisNode, int parentNode)//加一个parentNode是为了防止,寻找thisNode的子节点时回溯到了父节点;
{
int sizeOfSon = tree[thisNode].size();
for (int i = 0; i < sizeOfSon; ++ i)
{
if (parentNode == tree[thisNode][i])
{
continue;
}
dfs(tree[thisNode][i], thisNode);
if (first[thisNode] <= first[tree[thisNode][i]] + 1)
{
second[thisNode] = first[thisNode];
first[thisNode] = first[tree[thisNode][i]] + 1;
}
else if (second[thisNode] <= first[tree[thisNode][i]] + 1)
{
second[thisNode] = first[tree[thisNode][i]] + 1;
}
}
if (first[thisNode] + second[thisNode] > longest)
{
longest = first[thisNode] + second[thisNode];
//cout << thisNode << " " << first[thisNode] << " " << second[thisNode] << endl;
}
}
int main()
{
freopen("../test.txt", "r", stdin);
int N;
int ai, bi;
cin >> N;
for (int i = 1; i < N; ++ i)
{
cin >> ai >> bi;
tree[ai].push_back(bi);
tree[bi].push_back(ai);
}
dfs(1, 0);
cout << longest << endl;
return 0;
}
|
//
// Created by fab on 01/05/2020.
//
#include "../../headers/debug/TextureDebug.hpp"
TextureDebug::TextureDebug(const char *path) : shader("shaders/quad/")
{
texture.loadFrom(path, ITexture::Diffuse);
vboQuad = new Vbo(1, 6);
vboQuad->setElementDescription(0, Vbo::Element(3));
vboQuad->createCPUSide();
vboQuad->setElementData(0, 0, -1, -1, 0);
vboQuad->setElementData(0, 1, 1, -1, 0);
vboQuad->setElementData(0, 2, -1, 1, 0);
vboQuad->setElementData(0, 3, -1, 1, 0);
vboQuad->setElementData(0, 4, 1, -1, 0);
vboQuad->setElementData(0, 5, 1, 1, 0);
vboQuad->createGPUSide();
vboQuad->deleteCPUSide();
}
void TextureDebug::draw()
{
texture.use(0);
shader.use();
vboQuad->draw();
}
TextureDebug::TextureDebug(GLuint texID, glm::vec2 scale): shader("shaders/quad/")
{
vboQuad = new Vbo(1, 6);
vboQuad->setElementDescription(0, Vbo::Element(3));
vboQuad->createCPUSide();
vboQuad->setElementData(0, 0, -1 * scale.x, -1 * scale.y, 0);
vboQuad->setElementData(0, 1, 1 * scale.x, -1 * scale .y, 0);
vboQuad->setElementData(0, 2, -1 * scale.x, 1 * scale.y, 0);
vboQuad->setElementData(0, 3, -1 * scale.x, 1 * scale.y, 0);
vboQuad->setElementData(0, 4, 1 * scale.x, -1 * scale.y, 0);
vboQuad->setElementData(0, 5, 1 * scale.x, 1 * scale.y, 0);
vboQuad->createGPUSide();
vboQuad->deleteCPUSide();
texture.setID(texID);
}
|
#include <string>
#include <sstream>
#include <rapidxml/rapidxml.hpp>
#include <rapidjson/document.h>
#include <boost/format.hpp>
#include <lest/lest.hpp>
#include <owner/json.hpp>
#include <worker/command.hpp>
#include <worker/graph.hpp>
#include <worker/request.hpp>
#include <worker/response.hpp>
Graph theGraph;
// Do nothing on get (use the `inject` method on the global tree instead).
extern "C" void getJson(bound_buffer * target, char const * const) {}
// Clobber head up to and including the first ':'.
std::string & trim(std::string & s) {
s = s.substr(s.find(':')+1);
return s;
}
std::string final(std::string data) {
return "Finalizing Response: " + data;
}
std::string final(boost::format const & data) {
return final(data.str());
}
std::string provisional(std::string data) {
return "Provisional Response: " + data;
}
std::string provisional(boost::format const & data) {
return provisional(data.str());
}
// buffer responses for tests to validate against
std::stringstream responses;
extern "C" void emscripten_worker_respond(char const * const data, int length) {
responses << final(std::string(data, length));
}
extern "C" void emscripten_worker_respond_provisionally(char const * const data, int length) {
responses << provisional(std::string(data, length));
}
// Mock data
const std::string dag = "["
+ json::open() + json::pair("id", "1") + json::close() + ","
+ json::open() + json::pair("id", "2") + "," + json::pair("parents", "[1]") + json::close() + ","
+ json::open() + json::pair("id", "3") + "," + json::pair("parents", "[1]") + json::close() + ","
+ json::open() + json::pair("id", "4") + "," + json::pair("parents", "[1]") + json::close() + ","
+ json::open() + json::pair("id", "5") + "," + json::pair("parents", "[2,3]") + json::close() + ","
+ json::open() + json::pair("id", "6") + "," + json::pair("parents", "[3,4]") + json::close() + ","
+ json::open() + json::pair("id", "7") + "," + json::pair("parents", "[5,6]") + json::close()
+ "]";
char const * const vPathRaw[] = {static_cast<char const * const>("id")};
char const * const ePathRaw[] = {static_cast<char const * const>("parents")};
const Path theVertexPath(&vPathRaw[0], 1);
const Path theParentsBase(&ePathRaw[0], 1);
const Path theParentsPath(0, 0);
std::string dump_responses(void) {
std::string r = responses.str();
responses.str("");
return r;
}
const lest::test interrogate[] =
{
"Inject method parses mock data and responds Void", []
{
inject(dag.c_str());
boost::format sought = boost::format(R"({"response":%s})")
% std::to_string(response::VOID);
EXPECT( dump_responses() == provisional(sought) );
},
"Inject method maps mock data to its expected topology", []
{
// Vertices
EXPECT( contains(0) );
EXPECT( contains(1) );
EXPECT( contains(2) );
EXPECT( contains(3) );
EXPECT( contains(4) );
EXPECT( contains(5) );
EXPECT( contains(6) );
// Edges
EXPECT( contains(0,1) );
EXPECT( contains(0,2) );
EXPECT( contains(0,3) );
EXPECT( contains(1,4) );
EXPECT( contains(2,4) );
EXPECT( contains(2,5) );
EXPECT( contains(3,5) );
EXPECT( contains(4,6) );
EXPECT( contains(5,6) );
},
"Scale method responds Void", []
{
scale(5,10);
boost::format sought = boost::format(R"({"response":%s})")
% std::to_string(response::VOID);
EXPECT( dump_responses() == provisional(sought) );
},
"Set Physics method responds Void", []
{
setPhysics();
boost::format sought = boost::format(R"({"response":%s})")
% std::to_string(response::VOID);
EXPECT( dump_responses() == provisional(sought) );
},
"Iterate method responds Void", []
{
iterate(7);
boost::format sought = boost::format(R"({"response":%s})")
% std::to_string(response::VOID);
EXPECT( dump_responses() == provisional(sought) );
},
"Render SVG method generates an XML fragment and responds SVG", []
{
renderSvg(1);
rapidjson::Document svgResponse;
std::string raw = dump_responses();
EXPECT( !svgResponse.Parse<rapidjson::kParseDefaultFlags>(trim(raw).c_str()).HasParseError() );
EXPECT( svgResponse["response"].GetUint() == response::SVG );
rapidxml::xml_document<> svg;
char * fragment = const_cast<char *>(svgResponse["fragment"].GetString());
// Bind a return value to rapidxml's parsing for Lest (checking no throw).
EXPECT( [&]{ svg.parse<rapidxml::parse_fastest>(fragment); return true; }() );
},
"Scale method responds Void", []
{
scale(10,15);
boost::format sought = boost::format(R"({"response":%s})")
% std::to_string(response::VOID);
EXPECT( dump_responses() == provisional(sought) );
},
"Stop method responds Clean", []
{
stop();
boost::format sought = boost::format(R"({"response":%s})")
% std::to_string(response::CLEAN);
EXPECT( dump_responses() == final(sought) );
},
"Scale method responds Void", []
{
scale(10,15);
boost::format sought = boost::format(R"({"response":%s})")
% std::to_string(response::VOID);
EXPECT( dump_responses() == provisional(sought) );
}
};
int main(void)
{
return lest::run(interrogate);
}
|
#pragma once
#include "Commonheader.h"
#include "PhysicsInclude.h"
#include "Physics.h"
//動くオブジェクトの挙動を定義するクラス
class DynamicObj
{
protected:
vector3 position;
Physics* physics;
//物理データ関連のIndex
int rigidBodyIndex;
public:
DynamicObj();
~DynamicObj();
vector3 GetPos();
RigidbodyState States(int index){
return physics->GetRigidBodyState(index);
}
RigidBodyElements Bodies(int index){
return physics->GetRigidBodyElements(index);
}
Collider Collider(int index){
return physics->GetCollider(index);
}
bool miss;
void Set(GLfloat x, GLfloat y,GLfloat z);
virtual DynamicObj* Draw(){ return 0; };
virtual DynamicObj* Update(){ return 0; };
};
|
#ifndef HUFMAN
#define HUFMAN
#include <string>
#include <sstream>
#include <tuple>
#include <map>
#include <unordered_map>
#include <queue>
#include "bool_array.h"
#include <fstream>
using namespace std;
class Huffman
{
struct CharFreqSet
{
std::string char_set;
int freq;
bool operator<(const CharFreqSet& o) const;
};
public:
static std::map<char, std::string> encode(const std::string& text);
static void read_dict(ifstream& dict_is, int dict_size, map<string, char>& dict);
static string decode(ifstream& dict_is, ifstream& text_is);
};
#endif
|
#include "core.h"
template<typename Type>
Type** sort(int size, int sizec, Type** array, bool& error)
{
error = true;
Type** _array = new Type* [size];
for (int i = 0; i < size; i++)
_array[i] = new Type[sizec];
for (int i = 0; i < size; i++)
for (int j = 0; j < sizec; j++)
_array[i][j] = array[i][j];
for (int i = 0; i < sizec; i++)
{
if (character(size, sizec, _array, i) == 0)
error = false;
}
for (int j = 0; j < sizec; j++)
for (int i = j; i < sizec; i++)
if (character(size, sizec, _array, j) > character(size, sizec, _array, i))
_array = changec(size, _array, j, i);
return _array;
}
|
#include "LinkQueue.h"
template<typename T>
LinkQueue<T>::LinkQueue() {
front_ = new Node<T>;
rear_ = front_;
}
template<typename T>
LinkQueue<T>::~LinkQueue() {
Node<T>* p;
while (front_ != rear_) {
p = front_;
front_ = p->next;
delete p;
}
delete rear_;
}
template<typename T>
void LinkQueue<T>::EnQueue(T element) {
Node<T>* s = new Node<T>;
s->data = element;
s->next = nullptr;
rear_->next = s;
rear_ = s;
}
template<typename T>
void LinkQueue<T>::DeQueue() {
Node<T>* p = front_->next;
front_->next = p->next;
delete p;
}
template<typename T>
T LinkQueue<T>::GetFront() {
return front_->next->data;
}
template<typename T>
bool LinkQueue<T>::Empty() {
if (front_ == rear_)
return true;
return false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.